Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add encoder preferences and software fallback for camera muxers
Richie McIlroy4a97110b5a26
diff --git a/Cargo.lock b/Cargo.lockindex 10649ea5f..1cbb176ce 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7726,6 +7726,7 @@ dependencies = ["scap-ffmpeg","scap-targets","thiserror 1.0.69",+ "tracing","windows 0.60.0","windows-numerics 0.2.0","workspace-hack",diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rsindex 5b635396d..b332813b8 100644--- a/crates/recording/src/output_pipeline/win.rs+++ b/crates/recording/src/output_pipeline/win.rs@@ -435,6 +435,7 @@ pub struct WindowsCameraMuxerConfig {pub output_height: Option<u32>,pub fragmented: bool,pub frag_duration_us: i64,+ pub encoder_preferences: crate::capture_pipeline::EncoderPreferences,}impl Default for WindowsCameraMuxerConfig {@@ -443,6 +444,7 @@ impl Default for WindowsCameraMuxerConfig {output_height: None,fragmented: false,frag_duration_us: 2_000_000,+ encoder_preferences: crate::capture_pipeline::EncoderPreferences::new(),}}}@@ -501,6 +503,7 @@ impl Muxer for WindowsCameraMuxer {{let output = output.clone();+ let encoder_preferences = config.encoder_preferences;tasks.spawn_thread("windows-camera-encoder", move || {cap_mediafoundation_utils::thread_init();@@ -527,132 +530,230 @@ impl Muxer for WindowsCameraMuxer {let input_format = first_frame.0.dxgi_format();- let encoder_result = cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(- &d3d_device,- input_format,- input_size,- output_size,- frame_rate,- bitrate_multiplier,- );-- let (mut encoder, mut muxer) = match encoder_result {- Ok(encoder) => {- let muxer = {- let mut output_guard = match output.lock() {- Ok(guard) => guard,- Err(poisoned) => {- let msg = format!("Failed to lock output mutex: {poisoned}");- let _ = ready_tx.send(Err(anyhow!("{}", msg)));- return Err(anyhow!("{}", msg));- }- };+ let encoder = (|| {+ let fallback = |reason: Option<String>| {+ encoder_preferences.force_software_only();+ if let Some(reason) = reason.as_ref() {+ error!(+ "Falling back to software H264 encoder for camera: {reason}"+ );+ } else {+ info!("Using software H264 encoder for camera");+ }- cap_mediafoundation_ffmpeg::H264StreamMuxer::new(- &mut output_guard,- cap_mediafoundation_ffmpeg::MuxerConfig {- width: output_width,- height: output_height,- fps: frame_rate,- bitrate: encoder.bitrate(),- fragmented,- frag_duration_us,- },- )+ let mut output_guard = match output.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return Err(anyhow!(+ "CameraSoftwareEncoder: failed to lock output mutex: {}",+ poisoned+ ));+ }};- match muxer {- Ok(muxer) => (encoder, muxer),- Err(err) => {- let msg = format!("Failed to create muxer: {err}");- let _ = ready_tx.send(Err(anyhow!("{}", msg)));- return Err(anyhow!("{}", msg));+ cap_enc_ffmpeg::h264::H264Encoder::builder(video_config)+ .with_output_size(output_width, output_height)+ .and_then(|builder| builder.build(&mut output_guard))+ .map(either::Right)+ .map_err(|e| anyhow!("CameraSoftwareEncoder/{e}"))+ };++ if encoder_preferences.should_force_software() {+ return fallback(None);+ }++ match cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(+ &d3d_device,+ input_format,+ input_size,+ output_size,+ frame_rate,+ bitrate_multiplier,+ ) {+ Ok(encoder) => {+ let muxer = {+ let mut output_guard = match output.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return fallback(Some(format!(+ "Failed to lock output mutex: {poisoned}"+ )));+ }+ };++ cap_mediafoundation_ffmpeg::H264StreamMuxer::new(+ &mut output_guard,+ cap_mediafoundation_ffmpeg::MuxerConfig {+ width: output_width,+ height: output_height,+ fps: frame_rate,+ bitrate: encoder.bitrate(),+ fragmented,+ frag_duration_us,+ },+ )+ };++ match muxer {+ Ok(muxer) => Ok(either::Left((encoder, muxer))),+ Err(err) => fallback(Some(err.to_string())),}}+ Err(err) => fallback(Some(err.to_string())),}- Err(err) => {- let msg = format!("Failed to create H264 encoder: {err}");- let _ = ready_tx.send(Err(anyhow!("{}", msg)));- return Err(anyhow!("{}", msg));+ })();++ let encoder = match encoder {+ Ok(encoder) => {+ if ready_tx.send(Ok(())).is_err() {+ error!("Failed to send ready signal - receiver dropped");+ return Ok(());+ }+ encoder+ }+ Err(e) => {+ error!("Camera encoder setup failed: {:#}", e);+ let _ = ready_tx.send(Err(anyhow!("{e}")));+ return Err(anyhow!("{e}"));}};- if ready_tx.send(Ok(())).is_err() {- error!("Failed to send ready signal - receiver dropped");- return Ok(());- }+ match encoder {+ either::Left((mut encoder, mut muxer)) => {+ info!(+ "Windows camera encoder started (hardware): {:?} {}x{} -> NV12 {}x{} @ {}fps",+ input_format,+ input_size.Width,+ input_size.Height,+ output_size.Width,+ output_size.Height,+ frame_rate+ );- info!(- "Windows camera encoder started: {:?} {}x{} -> NV12 {}x{} @ {}fps",- input_format,- input_size.Width,- input_size.Height,- output_size.Width,- output_size.Height,- frame_rate- );-- let mut first_timestamp: Option<Duration> = None;- let mut frame_count = 0u64;-- let mut process_frame = |frame: NativeCameraFrame,- timestamp: Duration|- -> windows::core::Result<- Option<(- windows::Win32::Graphics::Direct3D11::ID3D11Texture2D,- TimeSpan,- )>,- > {- let relative = if let Some(first) = first_timestamp {- timestamp.checked_sub(first).unwrap_or(Duration::ZERO)- } else {- first_timestamp = Some(timestamp);- Duration::ZERO- };+ let mut first_timestamp: Option<Duration> = None;+ let mut frame_count = 0u64;++ let mut process_frame = |frame: NativeCameraFrame,+ timestamp: Duration|+ -> windows::core::Result<+ Option<(+ windows::Win32::Graphics::Direct3D11::ID3D11Texture2D,+ TimeSpan,+ )>,+ > {+ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };- let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;- Ok(Some((texture, duration_to_timespan(relative))))- };+ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;+ Ok(Some((texture, duration_to_timespan(relative))))+ };- if let Ok(Some((texture, frame_time))) = process_frame(first_frame.0, first_frame.1)- {- encoder- .run(- Arc::new(AtomicBool::default()),- || {- if frame_count > 0 {- let Ok(Some((frame, timestamp))) = video_rx.recv() else {- trace!("No more camera frames available");- return Ok(None);- };- frame_count += 1;- if frame_count.is_multiple_of(30) {- debug!(- "Windows camera encoder: processed {} frames",- frame_count- );- }- return process_frame(frame, timestamp);- }+ if let Ok(Some((texture, frame_time))) =+ process_frame(first_frame.0, first_frame.1)+ {+ encoder+ .run(+ Arc::new(AtomicBool::default()),+ || {+ if frame_count > 0 {+ let Ok(Some((frame, timestamp))) = video_rx.recv()+ else {+ trace!("No more camera frames available");+ return Ok(None);+ };+ frame_count += 1;+ if frame_count.is_multiple_of(30) {+ debug!(+ "Windows camera encoder: processed {} frames",+ frame_count+ );+ }+ return process_frame(frame, timestamp);+ }+ frame_count += 1;+ Ok(Some((texture.clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output.lock().unwrap();+ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));+ Ok(())+ },+ )+ .context("run camera encoder")?;+ }++ info!(+ "Windows camera encoder finished (hardware): {} frames encoded",+ frame_count+ );+ Ok(())+ }+ either::Right(mut encoder) => {+ info!(+ "Windows camera encoder started (software): {}x{} -> {}x{} @ {}fps",+ video_config.width,+ video_config.height,+ output_width,+ output_height,+ frame_rate+ );++ let mut first_timestamp: Option<Duration> = None;+ let mut frame_count = 0u64;++ let mut process_frame =+ |frame: NativeCameraFrame,+ timestamp: Duration|+ -> anyhow::Result<Option<Duration>> {+ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };++ let ffmpeg_frame = camera_frame_to_ffmpeg(&frame)?;++ let Ok(mut output_guard) = output.lock() else {+ return Ok(None);+ };++ encoder+ .queue_frame(ffmpeg_frame, relative, &mut output_guard)+ .context("queue camera frame")?;++ Ok(Some(relative))+ };++ if process_frame(first_frame.0, first_frame.1)?.is_some() {+ frame_count += 1;+ }++ while let Ok(Some((frame, timestamp))) = video_rx.recv() {+ if process_frame(frame, timestamp)?.is_some() {frame_count += 1;- Ok(Some((texture.clone(), frame_time)))- },- |output_sample| {- let mut output = output.lock().unwrap();- let _ = muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| format!("WriteSample: {e}"));- Ok(())- },- )- .context("run camera encoder")?;- }+ if frame_count.is_multiple_of(30) {+ debug!(+ "Windows camera encoder (software): processed {} frames",+ frame_count+ );+ }+ }+ }- info!(- "Windows camera encoder finished: {} frames encoded",- frame_count- );- Ok(())+ info!(+ "Windows camera encoder finished (software): {} frames encoded",+ frame_count+ );+ Ok(())+ }+ }});}@@ -738,6 +839,60 @@ fn convert_uyvy_to_yuyv(src: &[u8], width: u32, height: u32) -> Vec<u8> {dst}+pub fn camera_frame_to_ffmpeg(frame: &NativeCameraFrame) -> anyhow::Result<ffmpeg::frame::Video> {+ use cap_mediafoundation_utils::IMFMediaBufferExt;++ let ffmpeg_format = match frame.pixel_format {+ cap_camera_windows::PixelFormat::NV12 => ffmpeg::format::Pixel::NV12,+ cap_camera_windows::PixelFormat::YUYV422 => ffmpeg::format::Pixel::YUYV422,+ cap_camera_windows::PixelFormat::UYVY422 => ffmpeg::format::Pixel::UYVY422,+ other => anyhow::bail!("Unsupported camera pixel format: {:?}", other),+ };++ let buffer_guard = frame+ .buffer+ .lock()+ .map_err(|_| anyhow!("Failed to lock camera buffer"))?;+ let lock = buffer_guard+ .lock()+ .map_err(|e| anyhow!("Failed to lock MF buffer: {:?}", e))?;+ let data = &*lock;++ let converted_data: Option<Vec<u8>>;+ let (final_data, final_format): (&[u8], ffmpeg::format::Pixel) =+ if frame.pixel_format == cap_camera_windows::PixelFormat::UYVY422 {+ converted_data = Some(convert_uyvy_to_yuyv(data, frame.width, frame.height));+ (+ converted_data.as_ref().unwrap(),+ ffmpeg::format::Pixel::YUYV422,+ )+ } else {+ (data, ffmpeg_format)+ };++ let mut ffmpeg_frame = ffmpeg::frame::Video::new(final_format, frame.width, frame.height);++ match final_format {+ ffmpeg::format::Pixel::NV12 => {+ let y_size = (frame.width * frame.height) as usize;+ let uv_size = y_size / 2;+ if final_data.len() >= y_size + uv_size {+ ffmpeg_frame.data_mut(0)[..y_size].copy_from_slice(&final_data[..y_size]);+ ffmpeg_frame.data_mut(1)[..uv_size].copy_from_slice(&final_data[y_size..]);+ }+ }+ ffmpeg::format::Pixel::YUYV422 => {+ let size = (frame.width * frame.height * 2) as usize;+ if final_data.len() >= size {+ ffmpeg_frame.data_mut(0)[..size].copy_from_slice(&final_data[..size]);+ }+ }+ _ => {}+ }++ Ok(ffmpeg_frame)+}+pub fn upload_mf_buffer_to_texture(device: &ID3D11Device,frame: &NativeCameraFrame,diff --git a/crates/recording/src/output_pipeline/win_segmented_camera.rs b/crates/recording/src/output_pipeline/win_segmented_camera.rsindex 67878cf3a..88462f1d6 100644--- a/crates/recording/src/output_pipeline/win_segmented_camera.rs+++ b/crates/recording/src/output_pipeline/win_segmented_camera.rs@@ -147,6 +147,7 @@ pub struct WindowsSegmentedCameraMuxer {video_config: VideoInfo,output_height: Option<u32>,+ encoder_preferences: crate::capture_pipeline::EncoderPreferences,pause: PauseTracker,frame_drops: FrameDropTracker,@@ -155,6 +156,7 @@ pub struct WindowsSegmentedCameraMuxer {pub struct WindowsSegmentedCameraMuxerConfig {pub output_height: Option<u32>,pub segment_duration: Duration,+ pub encoder_preferences: crate::capture_pipeline::EncoderPreferences,}impl Default for WindowsSegmentedCameraMuxerConfig {@@ -162,6 +164,7 @@ impl Default for WindowsSegmentedCameraMuxerConfig {Self {output_height: None,segment_duration: Duration::from_secs(3),+ encoder_preferences: crate::capture_pipeline::EncoderPreferences::new(),}}}@@ -195,6 +198,7 @@ impl Muxer for WindowsSegmentedCameraMuxer {current_state: None,video_config,output_height: config.output_height,+ encoder_preferences: config.encoder_preferences,pause: PauseTracker::new(pause_flag),frame_drops: FrameDropTracker::new(),})@@ -341,6 +345,8 @@ impl WindowsSegmentedCameraMuxer {}fn create_segment(&mut self, first_frame: &NativeCameraFrame) -> anyhow::Result<()> {+ use crate::output_pipeline::win::camera_frame_to_ffmpeg;+let segment_path = self.current_segment_path();let input_size = SizeInt32 {@@ -361,6 +367,8 @@ impl WindowsSegmentedCameraMuxer {let frame_rate = self.video_config.fps();let bitrate_multiplier = 0.2f32;let input_format = first_frame.dxgi_format();+ let video_config = self.video_config;+ let encoder_preferences = self.encoder_preferences.clone();let (video_tx, video_rx) = sync_channel::<Option<(NativeCameraFrame, Duration)>>(30);let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);@@ -381,85 +389,154 @@ impl WindowsSegmentedCameraMuxer {}};- let encoder_result = cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(- &d3d_device,- input_format,- input_size,- output_size,- frame_rate,- bitrate_multiplier,- );-- let (mut encoder, mut muxer) = match encoder_result {- Ok(encoder) => {- let muxer = {- let mut output_guard = match output_clone.lock() {- Ok(guard) => guard,- Err(poisoned) => {- let _ = ready_tx.send(Err(anyhow!(- "Failed to lock output mutex: {poisoned}"- )));- return Err(anyhow!(- "Failed to lock output mutex: {}",- poisoned- ));- }- };+ let encoder = (|| {+ let fallback = |reason: Option<String>| {+ encoder_preferences.force_software_only();+ if let Some(reason) = reason.as_ref() {+ error!(+ "Falling back to software H264 encoder for camera segment: {reason}"+ );+ } else {+ info!("Using software H264 encoder for camera segment");+ }- cap_mediafoundation_ffmpeg::H264StreamMuxer::new(- &mut output_guard,- cap_mediafoundation_ffmpeg::MuxerConfig {- width: output_width,- height: output_height,- fps: frame_rate,- bitrate: encoder.bitrate(),- fragmented: false,- frag_duration_us: 0,- },- )+ let mut output_guard = match output_clone.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return Err(anyhow!(+ "CameraSegmentSoftwareEncoder: failed to lock output mutex: {}",+ poisoned+ ));+ }};- match muxer {- Ok(muxer) => (encoder, muxer),- Err(err) => {- let _ =- ready_tx.send(Err(anyhow!("Failed to create muxer: {err}")));- return Err(anyhow!("Failed to create muxer: {err}"));+ cap_enc_ffmpeg::h264::H264Encoder::builder(video_config)+ .with_output_size(output_width, output_height)+ .and_then(|builder| builder.build(&mut output_guard))+ .map(either::Right)+ .map_err(|e| anyhow!("CameraSegmentSoftwareEncoder/{e}"))+ };++ if encoder_preferences.should_force_software() {+ return fallback(None);+ }++ match cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(+ &d3d_device,+ input_format,+ input_size,+ output_size,+ frame_rate,+ bitrate_multiplier,+ ) {+ Ok(encoder) => {+ let muxer = {+ let mut output_guard = match output_clone.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return fallback(Some(format!(+ "Failed to lock output mutex: {poisoned}"+ )));+ }+ };++ cap_mediafoundation_ffmpeg::H264StreamMuxer::new(+ &mut output_guard,+ cap_mediafoundation_ffmpeg::MuxerConfig {+ width: output_width,+ height: output_height,+ fps: frame_rate,+ bitrate: encoder.bitrate(),+ fragmented: false,+ frag_duration_us: 0,+ },+ )+ };++ match muxer {+ Ok(muxer) => Ok(either::Left((encoder, muxer))),+ Err(err) => fallback(Some(err.to_string())),}}+ Err(err) => fallback(Some(err.to_string())),}- Err(err) => {- let _ = ready_tx.send(Err(anyhow!("Failed to create H264 encoder: {err}")));- return Err(anyhow!("Failed to create H264 encoder: {err}"));+ })();++ let encoder = match encoder {+ Ok(encoder) => {+ if ready_tx.send(Ok(())).is_err() {+ error!("Failed to send ready signal - receiver dropped");+ return Ok(());+ }+ encoder+ }+ Err(e) => {+ error!("Camera segment encoder setup failed: {:#}", e);+ let _ = ready_tx.send(Err(anyhow!("{e}")));+ return Err(anyhow!("{e}"));}};- if ready_tx.send(Ok(())).is_err() {- error!("Failed to send ready signal - receiver dropped");- return Ok(());- }+ match encoder {+ either::Left((mut encoder, mut muxer)) => {+ info!(+ "Camera segment encoder started (hardware): {:?} {}x{} -> NV12 {}x{} @ {}fps",+ input_format,+ input_size.Width,+ input_size.Height,+ output_size.Width,+ output_size.Height,+ frame_rate+ );- info!(- "Camera segment encoder started: {:?} {}x{} -> NV12 {}x{} @ {}fps",- input_format,- input_size.Width,- input_size.Height,- output_size.Width,- output_size.Height,- frame_rate- );-- let mut first_timestamp: Option<Duration> = None;-- encoder- .run(- Arc::new(AtomicBool::default()),- || {- let Ok(Some((frame, timestamp))) = video_rx.recv() else {- trace!("No more camera frames available for segment");- return Ok(None);- };+ let mut first_timestamp: Option<Duration> = None;++ encoder+ .run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more camera frames available for segment");+ return Ok(None);+ };++ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };++ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;+ Ok(Some((texture, duration_to_timespan(relative))))+ },+ |output_sample| {+ let mut output = output_clone.lock().unwrap();+ muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| {+ windows::core::Error::new(+ windows::core::HRESULT(-1),+ format!("WriteSample: {e}"),+ )+ })+ },+ )+ .context("run camera encoder for segment")+ }+ either::Right(mut encoder) => {+ info!(+ "Camera segment encoder started (software): {}x{} -> {}x{} @ {}fps",+ video_config.width,+ video_config.height,+ output_width,+ output_height,+ frame_rate+ );+ let mut first_timestamp: Option<Duration> = None;++ while let Ok(Some((frame, timestamp))) = video_rx.recv() {let relative = if let Some(first) = first_timestamp {timestamp.checked_sub(first).unwrap_or(Duration::ZERO)} else {@@ -467,22 +544,28 @@ impl WindowsSegmentedCameraMuxer {Duration::ZERO};- let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;- Ok(Some((texture, duration_to_timespan(relative))))- },- |output_sample| {- let mut output = output_clone.lock().unwrap();- muxer- .write_sample(&output_sample, &mut output)- .map_err(|e| {- windows::core::Error::new(- windows::core::HRESULT(-1),- format!("WriteSample: {e}"),- )- })- },- )- .context("run camera encoder for segment")+ let ffmpeg_frame = match camera_frame_to_ffmpeg(&frame) {+ Ok(f) => f,+ Err(e) => {+ warn!("Failed to convert camera frame: {e}");+ continue;+ }+ };++ let Ok(mut output_guard) = output_clone.lock() else {+ continue;+ };++ if let Err(e) =+ encoder.queue_frame(ffmpeg_frame, relative, &mut output_guard)+ {+ warn!("Failed to queue camera frame: {e}");+ }+ }++ Ok(())+ }+ }})?;ready_rxdiff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 0a5a437ab..325ee7509 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -874,7 +874,7 @@ async fn create_segment_pipeline(start_time,fragmented,#[cfg(windows)]- encoder_preferences,+ encoder_preferences.clone(),).instrument(error_span!("screen-out")).await@@ -912,14 +912,20 @@ async fn create_segment_pipeline(OutputPipeline::builder(fragments_dir).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)- .build::<WindowsSegmentedCameraMuxer>(WindowsSegmentedCameraMuxerConfig::default())+ .build::<WindowsSegmentedCameraMuxer>(WindowsSegmentedCameraMuxerConfig {+ encoder_preferences: encoder_preferences.clone(),+ ..Default::default()+ }).instrument(error_span!("camera-out")).await} else {OutputPipeline::builder(dir.join("camera.mp4")).with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)- .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig::default())+ .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig {+ encoder_preferences: encoder_preferences.clone(),+ ..Default::default()+ }).instrument(error_span!("camera-out")).await};diff --git a/crates/scap-direct3d/Cargo.toml b/crates/scap-direct3d/Cargo.tomlindex d19e4e823..ace537f6e 100644--- a/crates/scap-direct3d/Cargo.toml+++ b/crates/scap-direct3d/Cargo.toml@@ -41,4 +41,5 @@ workspace = true[dependencies]thiserror.workspace = true+tracing.workspace = trueworkspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/scap-direct3d/src/lib.rs b/crates/scap-direct3d/src/lib.rsindex 77ebf6140..d671d8691 100644--- a/crates/scap-direct3d/src/lib.rs+++ b/crates/scap-direct3d/src/lib.rs@@ -22,19 +22,20 @@ use windows::{Win32::{Foundation::HMODULE,Graphics::{- Direct3D::D3D_DRIVER_TYPE_HARDWARE,+ Direct3D::{D3D_DRIVER_TYPE, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP},Direct3D11::{D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_BOX,- D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION,- D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice,- ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D,+ D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_FLAG, D3D11_MAP_READ,+ D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC,+ D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device,+ ID3D11DeviceContext, ID3D11Texture2D,},Dxgi::{Common::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM,DXGI_SAMPLE_DESC,},- IDXGIDevice,+ DXGI_ERROR_UNSUPPORTED, IDXGIDevice,},},System::WinRT::Direct3D11::{@@ -157,6 +158,43 @@ pub fn is_supported() -> windows::core::Result<bool> {)? && GraphicsCaptureSession::IsSupported()?)}+fn create_d3d_device_with_type(+ driver_type: D3D_DRIVER_TYPE,+ flags: D3D11_CREATE_DEVICE_FLAG,+ device: *mut Option<ID3D11Device>,+) -> windows::core::Result<()> {+ unsafe {+ D3D11CreateDevice(+ None,+ driver_type,+ HMODULE::default(),+ flags,+ None,+ D3D11_SDK_VERSION,+ Some(device),+ None,+ None,+ )+ }+}++fn create_d3d_device_with_warp_fallback() -> windows::core::Result<(ID3D11Device, bool)> {+ let mut device = None;+ let flags = D3D11_CREATE_DEVICE_FLAG::default();++ let result = create_d3d_device_with_type(D3D_DRIVER_TYPE_HARDWARE, flags, &mut device);++ match result {+ Ok(()) => Ok((device.unwrap(), false)),+ Err(e) if e.code() == DXGI_ERROR_UNSUPPORTED => {+ tracing::info!("Hardware D3D11 device unavailable, attempting WARP fallback");+ create_d3d_device_with_type(D3D_DRIVER_TYPE_WARP, flags, &mut device)?;+ Ok((device.unwrap(), true))+ }+ Err(e) => Err(e),+ }+}+#[derive(Clone, Default, Debug)]pub struct Settings {pub is_border_required: Option<bool>,@@ -192,6 +230,12 @@ impl Settings {#[derive(Clone, Debug, thiserror::Error)]pub enum NewCapturerError {+ #[error("Screen capture requires Windows 10 version 1903 (build 18362) or later")]+ WindowsVersionTooOld,+ #[error(+ "Windows Graphics Capture API is disabled or unavailable. This may be due to group policy or missing system components."+ )]+ GraphicsCaptureDisabled,#[error("NotSupported")]NotSupported,#[error("BorderNotSupported")]@@ -232,6 +276,7 @@ pub struct Capturer {frame_pool: Direct3D11CaptureFramePool,frame_arrived_token: i64,stop_flag: Arc<AtomicBool>,+ is_using_warp: bool,}impl Capturer {@@ -240,10 +285,20 @@ impl Capturer {settings: Settings,mut callback: impl FnMut(Frame) -> windows::core::Result<()> + Send + 'static,mut closed_callback: impl FnMut() -> windows::core::Result<()> + Send + 'static,- mut d3d_device: Option<ID3D11Device>,+ d3d_device: Option<ID3D11Device>,) -> Result<Capturer, NewCapturerError> {- if !is_supported()? {- return Err(NewCapturerError::NotSupported);+ let api_present = ApiInformation::IsApiContractPresentByMajor(+ &HSTRING::from("Windows.Foundation.UniversalApiContract"),+ 8,+ )+ .unwrap_or(false);++ if !api_present {+ return Err(NewCapturerError::WindowsVersionTooOld);+ }++ if !GraphicsCaptureSession::IsSupported().unwrap_or(false) {+ return Err(NewCapturerError::GraphicsCaptureDisabled);}if settings.is_border_required.is_some() && !Settings::can_is_border_required()? {@@ -260,24 +315,13 @@ impl Capturer {return Err(NewCapturerError::UpdateIntervalNotSupported);}- if d3d_device.is_none() {- unsafe {- D3D11CreateDevice(- None,- D3D_DRIVER_TYPE_HARDWARE,- HMODULE::default(),- Default::default(),- None,- D3D11_SDK_VERSION,- Some(&mut d3d_device),- None,- None,- )- }- .map_err(NewCapturerError::CreateDevice)?;- }+ let (d3d_device, is_using_warp) = if let Some(device) = d3d_device {+ (device, false)+ } else {+ create_d3d_device_with_warp_fallback().map_err(NewCapturerError::CreateDevice)?+ };- let (d3d_device, d3d_context) = d3d_device+ let (d3d_device, d3d_context) = Some(d3d_device).map(|d| unsafe { d.GetImmediateContext() }.map(|v| (d, v))).transpose().map_err(NewCapturerError::Context)?@@ -433,6 +477,12 @@ impl Capturer {).map_err(NewCapturerError::RegisterClosed)?;+ if is_using_warp {+ tracing::warn!(+ "Hardware GPU unavailable, using WARP software rasterizer for screen capture"+ );+ }+Ok(Capturer {settings,d3d_device,@@ -441,9 +491,14 @@ impl Capturer {frame_pool,frame_arrived_token,stop_flag,+ is_using_warp,})}+ pub fn is_using_software_rendering(&self) -> bool {+ self.is_using_warp+ }+pub fn settings(&self) -> &Settings {&self.settings}