Add native Windows capture backend

This commit is contained in:
Alvin-Zilverstand committed 2026-09-10 08:52:03 +02:00
1 parent 2b465a3555
commit a89e61ed95
9 files changed
+800 -21

No files matched your search

Generated
+170 -5
View File
@@ -86,6 +86,7 @@ dependencies = [
"serde",
"serde_json",
"sysinfo",
"windows-capture",
]
[[package]]
@@ -514,6 +515,15 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
@@ -574,6 +584,29 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -727,6 +760,15 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -849,6 +891,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
@@ -997,7 +1045,7 @@ dependencies = [
"memchr",
"ntapi",
"rayon",
"windows",
"windows 0.57.0",
]
[[package]]
@@ -1314,22 +1362,80 @@ version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143"
dependencies = [
"windows-core",
"windows-core 0.57.0",
"windows-targets",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core 0.62.2",
"windows-future",
"windows-numerics",
]
[[package]]
name = "windows-capture"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09046acbe9b6d039cde50e8c8178d95bb0f9b33ed7feccc4465dadc5404b31b4"
dependencies = [
"parking_lot",
"rayon",
"thiserror",
"windows 0.62.2",
"windows-future",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.57.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d"
dependencies = [
"windows-implement",
"windows-interface",
"windows-result",
"windows-implement 0.57.0",
"windows-interface 0.57.0",
"windows-result 0.1.2",
"windows-targets",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link",
"windows-result 0.4.1",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.57.0"
@@ -1341,6 +1447,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.57.0"
@@ -1352,12 +1469,33 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.1.2"
@@ -1367,6 +1505,24 @@ dependencies = [
"windows-targets",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
@@ -1401,6 +1557,15 @@ dependencies = [
"windows_x86_64_msvc",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
+1
View File
@@ -19,6 +19,7 @@ rusqlite = { version = "0.32", features = ["bundled"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sysinfo = "0.31"
windows-capture = "2.0.1"
[profile.dev]
debug = true
+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.
- Capture prefers FFmpeg Desktop Duplication (`ddagrab`) when available and falls back to `gdigrab`.
- Video-only capture prefers native Windows Graphics Capture with H.264, 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 Windows Graphics Capture and native Rust WASAPI mixing are still future work.
- Native Rust WASAPI mixing is still future work; audio-enabled recording currently uses the FFmpeg path.
## Commands
+7 -6
View File
@@ -9,8 +9,9 @@
- The installer bundles `ffmpeg-x86_64-pc-windows-msvc.exe`, so users do not need to install FFmpeg separately.
- 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 FFmpeg segmented replay recorder with a low-spec default profile: 720p30 at 6 Mbps using Media Foundation H.264 when available.
- Capture prefers FFmpeg's Windows Desktop Duplication `ddagrab` filter when available and falls back to `gdigrab`; a local smoke test produced a real MP4 segment with `ddagrab`.
- 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.
- 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.
- Auto clips now use the same segment extraction/thumbnail pipeline as manual clips.
@@ -34,8 +35,8 @@
## Not Fully Working Yet
- Native Windows Graphics Capture is still a trait/stub boundary; FFmpeg `gdigrab` is the current MVP bridge.
- WASAPI/system-audio capture is enabled only when the selected FFmpeg build exposes a WASAPI input device; the current local FFmpeg build does not, so video capture remains enabled while system-audio capture is marked unavailable.
- 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.
- 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.
@@ -43,8 +44,8 @@
## Next Engineering Steps
1. Replace the FFmpeg Desktop Duplication/GDI bridge with native Windows Graphics Capture for lower overhead and better game/window targeting.
2. Add native Rust WASAPI capture/mixing and audio device selection.
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.
+69 -4
View File
@@ -365,6 +365,7 @@ dependencies = [
"serde",
"serde_json",
"sysinfo",
"windows-capture",
]
[[package]]
@@ -4570,11 +4571,36 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-collections 0.2.0",
"windows-core 0.61.2",
"windows-future",
"windows-future 0.2.1",
"windows-link 0.1.3",
"windows-numerics",
"windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows-capture"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09046acbe9b6d039cde50e8c8178d95bb0f9b33ed7feccc4465dadc5404b31b4"
dependencies = [
"parking_lot",
"rayon",
"thiserror 2.0.20",
"windows 0.62.2",
"windows-future 0.3.2",
]
[[package]]
@@ -4586,6 +4612,15 @@ dependencies = [
"windows-core 0.61.2",
]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]]
name = "windows-core"
version = "0.57.0"
@@ -4632,7 +4667,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-link 0.1.3",
"windows-threading",
"windows-threading 0.1.0",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
@@ -4701,6 +4747,16 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.1.2"
@@ -4822,6 +4878,15 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-version"
version = "0.1.7"
+53 -4
View File
@@ -17,6 +17,7 @@ use clipforge::media::{
trim_clip as ffmpeg_trim_clip,
};
use clipforge::models::{Clip, ClipSource, GameEvent, RecordingStatus};
use clipforge::native_wgc::NativeWgcReplayCaptureBackend;
use clipforge::recorder::{RecorderAction, RecorderService};
use clipforge::settings::{load_or_create_settings, save_settings};
use clipforge::storage::{clip_path, is_inside_root, LibraryPaths};
@@ -44,13 +45,33 @@ struct AppRuntime {
valve_events: Mutex<Vec<RawGameEvent>>,
}
#[derive(Debug)]
struct ActiveCapture {
buffer_dir: PathBuf,
session_output_path: PathBuf,
segment_duration: Duration,
started_at: SystemTime,
backend: FfmpegReplayCaptureBackend,
backend: ActiveCaptureBackend,
}
enum ActiveCaptureBackend {
Ffmpeg(FfmpegReplayCaptureBackend),
NativeWgc(NativeWgcReplayCaptureBackend),
}
impl ActiveCaptureBackend {
fn name(&self) -> &'static str {
match self {
Self::Ffmpeg(backend) => backend.name(),
Self::NativeWgc(backend) => backend.name(),
}
}
fn stop(&mut self) -> Result<(), clipforge::capture::CaptureError> {
match self {
Self::Ffmpeg(backend) => backend.stop(),
Self::NativeWgc(backend) => backend.stop(),
}
}
}
#[derive(Debug, Serialize)]
@@ -64,6 +85,7 @@ struct DesktopStatus {
upload_enabled: bool,
session_recording: bool,
capture_active: bool,
capture_backend: Option<String>,
capture_path: Option<String>,
clip_count: usize,
library_root: String,
@@ -457,8 +479,13 @@ fn start_capture_inner(runtime: &AppRuntime) -> Result<DesktopStatus, String> {
system_audio_device: recorder.settings.privacy.system_audio_device.clone(),
mic_device: recorder.settings.privacy.mic_device.clone(),
};
let mut backend = FfmpegReplayCaptureBackend::new(ffmpeg, &segment_pattern, segment_duration);
backend.start(config).map_err(|error| error.to_string())?;
let backend = start_best_capture_backend(
&ffmpeg,
&segment_pattern,
segment_duration,
config,
system_audio_enabled || recorder.settings.privacy.mic_enabled,
)?;
*capture = Some(ActiveCapture {
buffer_dir,
session_output_path,
@@ -845,6 +872,27 @@ fn add_session_clip(
Ok(clip)
}
fn start_best_capture_backend(
ffmpeg: &std::path::Path,
segment_pattern: &std::path::Path,
segment_duration: Duration,
config: CaptureConfig,
needs_ffmpeg_audio: bool,
) -> Result<ActiveCaptureBackend, String> {
if !needs_ffmpeg_audio {
let mut native = NativeWgcReplayCaptureBackend::new(segment_pattern, segment_duration);
if native.start(config.clone()).is_ok() {
return Ok(ActiveCaptureBackend::NativeWgc(native));
}
}
let mut ffmpeg_backend = FfmpegReplayCaptureBackend::new(ffmpeg, segment_pattern, segment_duration);
ffmpeg_backend
.start(config)
.map_err(|error| error.to_string())?;
Ok(ActiveCaptureBackend::Ffmpeg(ffmpeg_backend))
}
fn start_valve_gsi_receiver(app: tauri::AppHandle) {
thread::spawn(move || {
let Ok(listener) = TcpListener::bind("127.0.0.1:49321") else {
@@ -886,6 +934,7 @@ fn status_from_recorder(recorder: &RecorderService, capture: Option<&ActiveCaptu
upload_enabled: false,
session_recording: matches!(recorder.state.status, RecordingStatus::RecordingSession),
capture_active: capture.is_some(),
capture_backend: capture.map(|active| active.backend.name().to_string()),
capture_path: capture.map(|active| active.session_output_path.display().to_string()),
clip_count: recorder.library.all().len(),
library_root: recorder.paths.clip_root.display().to_string(),
+1
View File
@@ -10,6 +10,7 @@ pub mod jobs;
pub mod library;
pub mod media;
pub mod models;
pub mod native_wgc;
pub mod recorder;
pub mod settings;
pub mod storage;
+492
View File
@@ -0,0 +1,492 @@
use crate::capture::{CaptureBackend, CaptureConfig, CaptureError};
use std::path::PathBuf;
#[cfg(target_os = "windows")]
mod windows_impl {
use super::*;
use std::error::Error;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler};
use windows_capture::encoder::{
AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder,
VideoSettingsSubType,
};
use windows_capture::frame::Frame;
use windows_capture::graphics_capture_api::InternalCaptureControl;
use windows_capture::monitor::Monitor;
use windows_capture::settings::{
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings,
};
type HandlerError = Box<dyn Error + Send + Sync>;
struct WgcFlags {
output_path: String,
stop: Arc<AtomicBool>,
width: u32,
height: u32,
fps: u32,
bitrate: u32,
}
struct WgcRecorderHandler {
encoder: Option<VideoEncoder>,
stop: Arc<AtomicBool>,
started_at: Instant,
}
struct WgcSegmentFlags {
segment_pattern: String,
stop: Arc<AtomicBool>,
segment_duration: Duration,
width: u32,
height: u32,
fps: u32,
bitrate: u32,
}
struct WgcSegmentHandler {
encoder: Option<VideoEncoder>,
stop: Arc<AtomicBool>,
segment_pattern: String,
segment_duration: Duration,
segment_started_at: Instant,
segment_index: u32,
width: u32,
height: u32,
fps: u32,
bitrate: u32,
}
impl GraphicsCaptureApiHandler for WgcRecorderHandler {
type Flags = WgcFlags;
type Error = HandlerError;
fn new(ctx: Context<Self::Flags>) -> Result<Self, Self::Error> {
let video = VideoSettingsBuilder::new(ctx.flags.width, ctx.flags.height)
.sub_type(VideoSettingsSubType::H264)
.frame_rate(ctx.flags.fps)
.bitrate(ctx.flags.bitrate);
let encoder = VideoEncoder::new(
video,
AudioSettingsBuilder::default().disabled(true),
ContainerSettingsBuilder::default(),
&ctx.flags.output_path,
)?;
Ok(Self {
encoder: Some(encoder),
stop: ctx.flags.stop,
started_at: Instant::now(),
})
}
fn on_frame_arrived(
&mut self,
frame: &mut Frame,
capture_control: InternalCaptureControl,
) -> Result<(), Self::Error> {
if let Some(encoder) = self.encoder.as_mut() {
encoder.send_frame(frame)?;
}
if self.stop.load(Ordering::SeqCst) {
if let Some(encoder) = self.encoder.take() {
encoder.finish()?;
}
capture_control.stop();
}
let _ = self.started_at.elapsed();
Ok(())
}
fn on_closed(&mut self) -> Result<(), Self::Error> {
self.stop.store(true, Ordering::SeqCst);
Ok(())
}
}
impl GraphicsCaptureApiHandler for WgcSegmentHandler {
type Flags = WgcSegmentFlags;
type Error = HandlerError;
fn new(ctx: Context<Self::Flags>) -> Result<Self, Self::Error> {
let first_segment = segment_path(&ctx.flags.segment_pattern, 0);
let encoder = create_encoder(
&first_segment,
ctx.flags.width,
ctx.flags.height,
ctx.flags.fps,
ctx.flags.bitrate,
)?;
Ok(Self {
encoder: Some(encoder),
stop: ctx.flags.stop,
segment_pattern: ctx.flags.segment_pattern,
segment_duration: ctx.flags.segment_duration,
segment_started_at: Instant::now(),
segment_index: 0,
width: ctx.flags.width,
height: ctx.flags.height,
fps: ctx.flags.fps,
bitrate: ctx.flags.bitrate,
})
}
fn on_frame_arrived(
&mut self,
frame: &mut Frame,
capture_control: InternalCaptureControl,
) -> Result<(), Self::Error> {
if self.segment_started_at.elapsed() >= self.segment_duration {
if let Some(encoder) = self.encoder.take() {
encoder.finish()?;
}
self.segment_index = self.segment_index.saturating_add(1);
self.segment_started_at = Instant::now();
let next_segment = segment_path(&self.segment_pattern, self.segment_index);
self.encoder = Some(create_encoder(
&next_segment,
self.width,
self.height,
self.fps,
self.bitrate,
)?);
}
if let Some(encoder) = self.encoder.as_mut() {
encoder.send_frame(frame)?;
}
if self.stop.load(Ordering::SeqCst) {
if let Some(encoder) = self.encoder.take() {
encoder.finish()?;
}
capture_control.stop();
}
Ok(())
}
fn on_closed(&mut self) -> Result<(), Self::Error> {
self.stop.store(true, Ordering::SeqCst);
Ok(())
}
}
fn create_encoder(
output_path: &str,
width: u32,
height: u32,
fps: u32,
bitrate: u32,
) -> Result<VideoEncoder, HandlerError> {
let video = VideoSettingsBuilder::new(width, height)
.sub_type(VideoSettingsSubType::H264)
.frame_rate(fps)
.bitrate(bitrate);
Ok(VideoEncoder::new(
video,
AudioSettingsBuilder::default().disabled(true),
ContainerSettingsBuilder::default(),
output_path,
)?)
}
fn segment_path(pattern: &str, index: u32) -> String {
if pattern.contains("%05d") {
pattern.replace("%05d", &format!("{index:05}"))
} else if pattern.contains("%d") {
pattern.replace("%d", &index.to_string())
} else {
format!("{pattern}.{index:05}.mp4")
}
}
pub struct NativeWgcCaptureBackend {
output_path: PathBuf,
stop: Option<Arc<AtomicBool>>,
control: Option<CaptureControl<WgcRecorderHandler, HandlerError>>,
}
impl NativeWgcCaptureBackend {
pub fn new(output_path: impl Into<PathBuf>) -> Self {
Self {
output_path: output_path.into(),
stop: None,
control: None,
}
}
}
impl CaptureBackend for NativeWgcCaptureBackend {
fn name(&self) -> &'static str {
"windows-graphics-capture"
}
fn start(&mut self, config: CaptureConfig) -> Result<(), CaptureError> {
if self.control.is_some() {
return Ok(());
}
let Some(parent) = self.output_path.parent() else {
return Err(CaptureError::DeviceUnavailable(
"native WGC output path has no parent directory".to_string(),
));
};
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(),
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()))?;
self.stop = Some(stop);
self.control = Some(control);
Ok(())
}
fn stop(&mut self) -> Result<(), CaptureError> {
if let Some(stop) = &self.stop {
stop.store(true, Ordering::SeqCst);
}
if let Some(control) = self.control.take() {
control
.stop()
.map_err(|error| CaptureError::DeviceUnavailable(format!("{error:?}")))?;
}
self.stop = None;
Ok(())
}
}
impl Drop for NativeWgcCaptureBackend {
fn drop(&mut self) {
let _ = self.stop();
}
}
pub struct NativeWgcReplayCaptureBackend {
segment_pattern: PathBuf,
segment_duration: Duration,
stop: Option<Arc<AtomicBool>>,
control: Option<CaptureControl<WgcSegmentHandler, HandlerError>>,
}
impl NativeWgcReplayCaptureBackend {
pub fn new(segment_pattern: impl Into<PathBuf>, segment_duration: Duration) -> Self {
Self {
segment_pattern: segment_pattern.into(),
segment_duration,
stop: None,
control: None,
}
}
}
impl CaptureBackend for NativeWgcReplayCaptureBackend {
fn name(&self) -> &'static str {
"windows-graphics-capture-segments"
}
fn start(&mut self, config: CaptureConfig) -> Result<(), CaptureError> {
if self.control.is_some() {
return Ok(());
}
let Some(parent) = self.segment_pattern.parent() else {
return Err(CaptureError::DeviceUnavailable(
"native WGC segment pattern has no parent directory".to_string(),
));
};
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,
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()))?;
self.stop = Some(stop);
self.control = Some(control);
Ok(())
}
fn stop(&mut self) -> Result<(), CaptureError> {
if let Some(stop) = &self.stop {
stop.store(true, Ordering::SeqCst);
}
if let Some(control) = self.control.take() {
control
.stop()
.map_err(|error| CaptureError::DeviceUnavailable(format!("{error:?}")))?;
}
self.stop = None;
Ok(())
}
}
impl Drop for NativeWgcReplayCaptureBackend {
fn drop(&mut self) {
let _ = self.stop();
}
}
fn even_dimension(value: u32) -> u32 {
value.saturating_sub(value % 2).max(2)
}
}
#[cfg(target_os = "windows")]
pub use windows_impl::NativeWgcCaptureBackend;
#[cfg(target_os = "windows")]
pub use windows_impl::NativeWgcReplayCaptureBackend;
#[cfg(not(target_os = "windows"))]
pub struct NativeWgcCaptureBackend;
#[cfg(not(target_os = "windows"))]
pub struct NativeWgcReplayCaptureBackend;
#[cfg(not(target_os = "windows"))]
impl NativeWgcCaptureBackend {
pub fn new(_output_path: impl Into<PathBuf>) -> Self {
Self
}
}
#[cfg(not(target_os = "windows"))]
impl NativeWgcReplayCaptureBackend {
pub fn new(
_segment_pattern: impl Into<PathBuf>,
_segment_duration: std::time::Duration,
) -> Self {
Self
}
}
#[cfg(not(target_os = "windows"))]
impl CaptureBackend for NativeWgcCaptureBackend {
fn name(&self) -> &'static str {
"windows-graphics-capture"
}
fn start(&mut self, _config: CaptureConfig) -> Result<(), CaptureError> {
Err(CaptureError::UnsupportedPlatform)
}
fn stop(&mut self) -> Result<(), CaptureError> {
Ok(())
}
}
#[cfg(not(target_os = "windows"))]
impl CaptureBackend for NativeWgcReplayCaptureBackend {
fn name(&self) -> &'static str {
"windows-graphics-capture-segments"
}
fn start(&mut self, _config: CaptureConfig) -> Result<(), CaptureError> {
Err(CaptureError::UnsupportedPlatform)
}
fn stop(&mut self) -> Result<(), CaptureError> {
Ok(())
}
}
#[cfg(all(test, target_os = "windows"))]
mod tests {
use super::*;
use crate::capture::{CaptureMethod, CaptureSource, EncoderPreference};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[test]
#[ignore = "captures the desktop for a short local smoke test"]
fn native_wgc_replay_smoke_writes_segment() {
let root = std::env::temp_dir().join(format!(
"clipforge-wgc-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: 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");
thread::sleep(Duration::from_secs(3));
backend.stop().expect("stop native WGC");
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 should write at least one segment"
);
let _ = std::fs::remove_dir_all(root);
}
}
+5
View File
@@ -45,6 +45,7 @@ type DesktopStatus = {
upload_enabled: boolean;
session_recording: boolean;
capture_active: boolean;
capture_backend: string | null;
capture_path: string | null;
clip_count: number;
library_root: string;
@@ -86,6 +87,7 @@ type AppState = {
replayBufferSeconds: number;
sessionRecording: boolean;
captureActive: boolean;
captureBackend: string | null;
capturePath: string | null;
ffmpegAvailable: boolean;
ffmpegPath: string | null;
@@ -127,6 +129,7 @@ const state: AppState = {
replayBufferSeconds: 60,
sessionRecording: false,
captureActive: false,
captureBackend: null,
capturePath: null,
ffmpegAvailable: false,
ffmpegPath: null,
@@ -392,6 +395,7 @@ function renderRecordingView() {
<h2>720p30 Performance</h2>
<p class="muted">Lightweight desktop capture uses bundled FFmpeg when system FFmpeg is missing.</p>
<p class="muted">${state.desktopDuplicationAvailable ? "Desktop Duplication capture available" : "Using GDI capture fallback"}</p>
<p class="muted">${state.captureBackend ? `Active backend: ${state.captureBackend}` : "Active backend: idle"}</p>
<p class="muted">${state.ffmpegAvailable ? "FFmpeg ready" : "FFmpeg missing"}${state.ffmpegPath ? ` · ${state.ffmpegPath}` : ""}</p>
<p class="muted">${state.capturePath ? `Writing ${state.capturePath}` : "No active capture file"}</p>
</article>
@@ -666,6 +670,7 @@ function applyDesktopStatus(status: DesktopStatus) {
state.autoUpload = status.upload_enabled;
state.sessionRecording = status.session_recording;
state.captureActive = status.capture_active;
state.captureBackend = status.capture_backend;
state.capturePath = status.capture_path;
state.ffmpegAvailable = status.ffmpeg_available;
state.ffmpegPath = status.ffmpeg_path;