From 4054364e12e7447be4b92c402d168179db9119b8 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 26 Oct 2026 08:31:45 +0800 Subject: [PATCH 1/6] perf(windows-screen-capture): scale resized frames on D3D11 --- .../src/sources/screen_capture/windows.rs | 738 +++++++++++++++++- 1 file changed, 701 insertions(+), 37 deletions(-) diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rs index 36d5d448386..e8e909e7b8e 100644 --- a/crates/recording/src/sources/screen_capture/windows.rs +++ b/crates/recording/src/sources/screen_capture/windows.rs @@ -3,10 +3,20 @@ use crate::{ screen_capture::{ScreenCaptureConfig, ScreenCaptureFormat, cadence::FrameCadenceGate}, }; use ::windows::Win32::Graphics::Direct3D11::{ - D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC, - D3D11_USAGE_DEFAULT, ID3D11Device, ID3D11Texture2D, + D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_CPU_ACCESS_READ, + D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SUBRESOURCE_DATA, D3D11_TEX2D_VPIV, + D3D11_TEX2D_VPOV, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, + D3D11_VIDEO_PROCESSOR_CONTENT_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, + D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_STREAM, + D3D11_VPIV_DIMENSION_TEXTURE2D, D3D11_VPOV_DIMENSION_TEXTURE2D, ID3D11Device, + ID3D11DeviceContext, ID3D11Texture2D, ID3D11VideoContext, ID3D11VideoDevice, + ID3D11VideoProcessor, ID3D11VideoProcessorInputView, ID3D11VideoProcessorOutputView, }; -use ::windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; +use ::windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_RATIONAL, + DXGI_SAMPLE_DESC, +}; +use ::windows::core::Interface; use anyhow::anyhow; use cap_media_info::{AudioInfo, VideoInfo}; use cap_timestamp::{PerformanceCounterTimestamp, Timestamp}; @@ -17,7 +27,9 @@ use futures::{ }; use scap_ffmpeg::*; use scap_targets::{Display, DisplayId}; +use std::mem::ManuallyDrop; use std::{ + borrow::Cow, sync::{ Arc, Mutex, atomic::{self, AtomicBool, AtomicU32}, @@ -100,7 +112,8 @@ pub enum ScreenFrame { pub struct ScaledScreenFrame { texture: ID3D11Texture2D, - pixel_data: Vec, + pixel_data: Option>, + readback: Option>, width: u32, height: u32, pixel_format: scap_direct3d::PixelFormat, @@ -108,6 +121,322 @@ pub struct ScaledScreenFrame { unsafe impl Send for ScaledScreenFrame {} +struct D3D11FrameReadback { + device: ID3D11Device, + context: ID3D11DeviceContext, + staging: Mutex>, + width: u32, + height: u32, + pixel_format: scap_direct3d::PixelFormat, +} + +impl D3D11FrameReadback { + fn read(&self, texture: &ID3D11Texture2D) -> Result, ::windows::core::Error> { + let mut staging = self + .staging + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if staging.is_none() { + let desc = D3D11_TEXTURE2D_DESC { + Width: self.width, + Height: self.height, + MipLevels: 1, + ArraySize: 1, + Format: pixel_format_dxgi(self.pixel_format), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_STAGING, + BindFlags: 0, + CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32, + MiscFlags: 0, + }; + let mut created = None; + unsafe { + self.device + .CreateTexture2D(&desc, None, Some(&mut created))?; + } + *staging = Some(created.ok_or_else(::windows::core::Error::from_win32)?); + } + let staging = staging + .as_ref() + .ok_or_else(::windows::core::Error::from_win32)?; + + unsafe { + self.context.CopyResource(staging, texture); + } + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + unsafe { + self.context + .Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?; + } + + let row_length = self.width as usize * 4; + let source_stride = mapped.RowPitch as usize; + let mut pixels = vec![0; row_length * self.height as usize]; + for row in 0..self.height as usize { + let source_start = row * source_stride; + let destination_start = row * row_length; + let copy_length = row_length.min(source_stride); + unsafe { + // SAFETY: Map keeps pData valid until the matching Unmap. + let source = std::slice::from_raw_parts( + (mapped.pData as *const u8).add(source_start), + copy_length, + ); + pixels[destination_start..destination_start + copy_length].copy_from_slice(source); + } + } + unsafe { + self.context.Unmap(staging, 0); + } + + Ok(pixels) + } +} + +const D3D11_SCALE_TARGET_POOL_SIZE: usize = 3; + +struct D3D11ScaleTarget { + texture: ID3D11Texture2D, + view: ID3D11VideoProcessorOutputView, +} + +struct D3D11VideoScaler { + device: ID3D11Device, + context: ID3D11DeviceContext, + video_context: ID3D11VideoContext, + processor: ID3D11VideoProcessor, + input_texture: ID3D11Texture2D, + input_view: ID3D11VideoProcessorInputView, + targets: Vec, + next_target: usize, + target_width: u32, + target_height: u32, + pixel_format: scap_direct3d::PixelFormat, + readback: Arc, +} + +impl D3D11VideoScaler { + fn new( + device: ID3D11Device, + source_width: u32, + source_height: u32, + target_width: u32, + target_height: u32, + pixel_format: scap_direct3d::PixelFormat, + ) -> Result { + let context = unsafe { device.GetImmediateContext()? }; + let video_device: ID3D11VideoDevice = device.cast()?; + let video_context: ID3D11VideoContext = context.cast()?; + let content_desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC { + InputFrameFormat: + ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, + InputFrameRate: DXGI_RATIONAL { + Numerator: 30, + Denominator: 1, + }, + InputWidth: source_width, + InputHeight: source_height, + OutputFrameRate: DXGI_RATIONAL { + Numerator: 30, + Denominator: 1, + }, + OutputWidth: target_width, + OutputHeight: target_height, + Usage: ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_USAGE_PLAYBACK_NORMAL, + }; + let enumerator = unsafe { video_device.CreateVideoProcessorEnumerator(&content_desc)? }; + let processor = unsafe { video_device.CreateVideoProcessor(&enumerator, 0)? }; + let input_texture_desc = D3D11_TEXTURE2D_DESC { + Width: source_width, + Height: source_height, + MipLevels: 1, + ArraySize: 1, + Format: pixel_format_dxgi(pixel_format), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let mut input_texture = None; + unsafe { + device.CreateTexture2D(&input_texture_desc, None, Some(&mut input_texture))?; + } + let input_texture = input_texture.ok_or_else(::windows::core::Error::from_win32)?; + let input_view_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { + FourCC: 0, + ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D, + Anonymous: + ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 { + Texture2D: D3D11_TEX2D_VPIV { + MipSlice: 0, + ArraySlice: 0, + }, + }, + }; + let mut input_view = None; + unsafe { + video_device.CreateVideoProcessorInputView( + &input_texture, + &enumerator, + &input_view_desc, + Some(&mut input_view), + )?; + } + let input_view: ID3D11VideoProcessorInputView = + input_view.ok_or_else(::windows::core::Error::from_win32)?; + let output_view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { + ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D, + Anonymous: + ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 { + Texture2D: D3D11_TEX2D_VPOV { MipSlice: 0 }, + }, + }; + let texture_desc = D3D11_TEXTURE2D_DESC { + Width: target_width, + Height: target_height, + MipLevels: 1, + ArraySize: 1, + Format: pixel_format_dxgi(pixel_format), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let mut targets = Vec::with_capacity(D3D11_SCALE_TARGET_POOL_SIZE); + for _ in 0..D3D11_SCALE_TARGET_POOL_SIZE { + let mut texture = None; + unsafe { + device.CreateTexture2D(&texture_desc, None, Some(&mut texture))?; + } + let texture = texture.ok_or_else(::windows::core::Error::from_win32)?; + let mut view = None; + unsafe { + video_device.CreateVideoProcessorOutputView( + &texture, + &enumerator, + &output_view_desc, + Some(&mut view), + )?; + } + targets.push(D3D11ScaleTarget { + texture, + view: view.ok_or_else(::windows::core::Error::from_win32)?, + }); + } + let readback = Arc::new(D3D11FrameReadback { + device: device.clone(), + context: context.clone(), + staging: Mutex::new(None), + width: target_width, + height: target_height, + pixel_format, + }); + + Ok(Self { + device, + context, + video_context, + processor, + input_texture, + input_view, + targets, + next_target: 0, + target_width, + target_height, + pixel_format, + readback, + }) + } + + fn scale_frame( + &mut self, + input: &ID3D11Texture2D, + ) -> Result { + unsafe { + self.context.CopyResource(&self.input_texture, input); + } + let target_index = self.next_target; + self.next_target = (self.next_target + 1) % self.targets.len(); + let target = &self.targets[target_index]; + let mut stream = D3D11_VIDEO_PROCESSOR_STREAM { + Enable: true.into(), + pInputSurface: ManuallyDrop::new(Some(self.input_view.clone())), + ..Default::default() + }; + let blt = unsafe { + self.video_context.VideoProcessorBlt( + &self.processor, + &target.view, + 0, + std::slice::from_ref(&stream), + ) + }; + unsafe { + ManuallyDrop::drop(&mut stream.pInputSurface); + } + blt?; + + let texture_desc = D3D11_TEXTURE2D_DESC { + Width: self.target_width, + Height: self.target_height, + MipLevels: 1, + ArraySize: 1, + Format: pixel_format_dxgi(self.pixel_format), + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let mut output = None; + unsafe { + self.device + .CreateTexture2D(&texture_desc, None, Some(&mut output))?; + } + let output = output.ok_or_else(::windows::core::Error::from_win32)?; + unsafe { + self.context.CopyResource(&output, &target.texture); + } + + Ok(ScaledScreenFrame { + texture: output, + pixel_data: None, + readback: Some(self.readback.clone()), + width: self.target_width, + height: self.target_height, + pixel_format: self.pixel_format, + }) + } +} + +fn pixel_format_ffmpeg(pixel_format: scap_direct3d::PixelFormat) -> ffmpeg::format::Pixel { + match pixel_format { + scap_direct3d::PixelFormat::R8G8B8A8Unorm => ffmpeg::format::Pixel::RGBA, + scap_direct3d::PixelFormat::B8G8R8A8Unorm => ffmpeg::format::Pixel::BGRA, + } +} + +fn pixel_format_dxgi(pixel_format: scap_direct3d::PixelFormat) -> DXGI_FORMAT { + match pixel_format { + scap_direct3d::PixelFormat::R8G8B8A8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM, + scap_direct3d::PixelFormat::B8G8R8A8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM, + } +} + impl ScreenFrame { pub fn texture(&self) -> &ID3D11Texture2D { match self { @@ -137,9 +466,18 @@ impl ScreenFrame { frame.as_ffmpeg() } ScreenFrame::Scaled(scaled) => { - let ffmpeg_pixel = match scaled.pixel_format { - scap_direct3d::PixelFormat::R8G8B8A8Unorm => ffmpeg::format::Pixel::RGBA, - scap_direct3d::PixelFormat::B8G8R8A8Unorm => ffmpeg::format::Pixel::BGRA, + let ffmpeg_pixel = pixel_format_ffmpeg(scaled.pixel_format); + let readback; + let pixel_data = match &scaled.pixel_data { + Some(pixel_data) => Cow::Borrowed(pixel_data.as_slice()), + None => { + readback = scaled + .readback + .as_ref() + .ok_or_else(::windows::core::Error::from_win32)? + .read(&scaled.texture)?; + Cow::Borrowed(readback.as_slice()) + } }; let mut ff_frame = ffmpeg::frame::Video::new(ffmpeg_pixel, scaled.width, scaled.height); @@ -151,15 +489,14 @@ impl ScreenFrame { let src_start = row * row_length; let dst_start = row * dest_stride; let copy_len = row_length.min( - scaled - .pixel_data + pixel_data .len() .saturating_sub(src_start) .min(dest_bytes.len().saturating_sub(dst_start)), ); if copy_len > 0 { dest_bytes[dst_start..dst_start + copy_len] - .copy_from_slice(&scaled.pixel_data[src_start..src_start + copy_len]); + .copy_from_slice(&pixel_data[src_start..src_start + copy_len]); } } @@ -170,7 +507,8 @@ impl ScreenFrame { } struct FrameScalerState { - context: ffmpeg::software::scaling::Context, + context: Option, + video_scaler: Option, source_width: u32, source_height: u32, } @@ -211,11 +549,55 @@ impl WindowsFrameScaler { .is_none_or(|s| s.source_width != src_width || s.source_height != src_height); if needs_reinit { - let src_pixel = match self.pixel_format { - scap_direct3d::PixelFormat::R8G8B8A8Unorm => ffmpeg::format::Pixel::RGBA, - scap_direct3d::PixelFormat::B8G8R8A8Unorm => ffmpeg::format::Pixel::BGRA, + let video_scaler = match D3D11VideoScaler::new( + self.d3d_device.clone(), + src_width, + src_height, + self.target_width, + self.target_height, + self.pixel_format, + ) { + Ok(scaler) => Some(scaler), + Err(error) => { + warn!(?error, "D3D11 screen scaling unavailable; using CPU scaler"); + None + } }; + self.state = Some(FrameScalerState { + context: None, + video_scaler, + source_width: src_width, + source_height: src_height, + }); + } + + let gpu_result = self + .state + .as_mut()? + .video_scaler + .as_mut() + .map(|scaler| scaler.scale_frame(frame.texture())); + if let Some(result) = gpu_result { + match result { + Ok(scaled) => return Some(ScreenFrame::Scaled(scaled)), + Err(error) => { + warn!(?error, "D3D11 screen scaling failed; using CPU scaler"); + self.state.as_mut()?.video_scaler = None; + } + } + } + + self.scale_frame_cpu(frame, src_width, src_height) + } + fn scale_frame_cpu( + &mut self, + frame: &scap_direct3d::Frame, + src_width: u32, + src_height: u32, + ) -> Option { + if self.state.as_ref()?.context.is_none() { + let src_pixel = pixel_format_ffmpeg(self.pixel_format); let context = ffmpeg::software::scaling::Context::get( src_pixel, src_width, @@ -226,23 +608,14 @@ impl WindowsFrameScaler { ffmpeg::software::scaling::Flags::BILINEAR, ) .ok()?; - - self.state = Some(FrameScalerState { - context, - source_width: src_width, - source_height: src_height, - }); + self.state.as_mut()?.context = Some(context); } let buffer = frame.as_buffer().ok()?; let src_data = buffer.data(); let src_stride = buffer.stride() as usize; let row_length = (src_width * 4) as usize; - - let src_pixel = match self.pixel_format { - scap_direct3d::PixelFormat::R8G8B8A8Unorm => ffmpeg::format::Pixel::RGBA, - scap_direct3d::PixelFormat::B8G8R8A8Unorm => ffmpeg::format::Pixel::BGRA, - }; + let src_pixel = pixel_format_ffmpeg(self.pixel_format); let mut src_frame = ffmpeg::frame::Video::new(src_pixel, src_width, src_height); let ff_stride = src_frame.stride(0); @@ -268,7 +641,11 @@ impl WindowsFrameScaler { let state = self.state.as_mut()?; let mut dst_frame = ffmpeg::frame::Video::new(src_pixel, self.target_width, self.target_height); - state.context.run(&src_frame, &mut dst_frame).ok()?; + state + .context + .as_mut()? + .run(&src_frame, &mut dst_frame) + .ok()?; let dst_stride = dst_frame.stride(0); let dst_row_length = (self.target_width * 4) as usize; @@ -291,21 +668,12 @@ impl WindowsFrameScaler { } } - let dxgi_format = match self.pixel_format { - scap_direct3d::PixelFormat::R8G8B8A8Unorm => { - ::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM - } - scap_direct3d::PixelFormat::B8G8R8A8Unorm => { - ::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM - } - }; - let texture_desc = D3D11_TEXTURE2D_DESC { Width: self.target_width, Height: self.target_height, MipLevels: 1, ArraySize: 1, - Format: dxgi_format, + Format: pixel_format_dxgi(self.pixel_format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, @@ -332,7 +700,8 @@ impl WindowsFrameScaler { Some(ScreenFrame::Scaled(ScaledScreenFrame { texture, - pixel_data, + pixel_data: Some(pixel_data), + readback: None, width: self.target_width, height: self.target_height, pixel_format: self.pixel_format, @@ -1598,3 +1967,298 @@ mod first_screen_frame_tests { assert!(error.to_string().contains("closed before its first frame")); } } +#[cfg(test)] +mod windows_screen_scale_benchmark { + use super::*; + use ::windows::Win32::Graphics::Direct3D11::{ + D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SUBRESOURCE_DATA, + D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, + }; + use ::windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use std::time::Instant; + + struct CpuScaler { + device: ID3D11Device, + context: ::windows::Win32::Graphics::Direct3D11::ID3D11DeviceContext, + staging: ID3D11Texture2D, + scaler: ffmpeg::software::scaling::Context, + source_width: u32, + source_height: u32, + target_width: u32, + target_height: u32, + } + + impl CpuScaler { + fn new( + device: ID3D11Device, + source_width: u32, + source_height: u32, + target_width: u32, + target_height: u32, + ) -> Self { + let context = unsafe { device.GetImmediateContext().unwrap() }; + let staging_desc = D3D11_TEXTURE2D_DESC { + Width: source_width, + Height: source_height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_STAGING, + BindFlags: 0, + CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32, + MiscFlags: 0, + }; + let mut staging = None; + unsafe { + device + .CreateTexture2D(&staging_desc, None, Some(&mut staging)) + .unwrap(); + } + let scaler = ffmpeg::software::scaling::Context::get( + ffmpeg::format::Pixel::RGBA, + source_width, + source_height, + ffmpeg::format::Pixel::RGBA, + target_width, + target_height, + ffmpeg::software::scaling::Flags::BILINEAR, + ) + .unwrap(); + Self { + device, + context, + staging: staging.unwrap(), + scaler, + source_width, + source_height, + target_width, + target_height, + } + } + + fn scale(&mut self, texture: &ID3D11Texture2D) -> ScreenFrame { + unsafe { + self.context.CopyResource(&self.staging, texture); + } + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + unsafe { + self.context + .Map(&self.staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped)) + .unwrap(); + } + let source_stride = mapped.RowPitch as usize; + let source_row_length = self.source_width as usize * 4; + let mut source_frame = ffmpeg::frame::Video::new( + ffmpeg::format::Pixel::RGBA, + self.source_width, + self.source_height, + ); + let source_ffmpeg_stride = source_frame.stride(0); + let source_ffmpeg_data = source_frame.data_mut(0); + for row in 0..self.source_height as usize { + let source_start = row * source_stride; + let destination_start = row * source_ffmpeg_stride; + let copy_length = source_row_length + .min(source_ffmpeg_data.len().saturating_sub(destination_start)); + unsafe { + // SAFETY: Map keeps pData valid until the matching Unmap. + let source = std::slice::from_raw_parts( + (mapped.pData as *const u8).add(source_start), + copy_length, + ); + source_ffmpeg_data[destination_start..destination_start + copy_length] + .copy_from_slice(source); + } + } + unsafe { + self.context.Unmap(&self.staging, 0); + } + + let mut output_frame = ffmpeg::frame::Video::new( + ffmpeg::format::Pixel::RGBA, + self.target_width, + self.target_height, + ); + self.scaler.run(&source_frame, &mut output_frame).unwrap(); + let row_length = self.target_width as usize * 4; + let mut pixel_data = vec![0; row_length * self.target_height as usize]; + let output_stride = output_frame.stride(0); + let output_data = output_frame.data(0); + for row in 0..self.target_height as usize { + let source_start = row * output_stride; + let destination_start = row * row_length; + pixel_data[destination_start..destination_start + row_length] + .copy_from_slice(&output_data[source_start..source_start + row_length]); + } + + let texture_desc = D3D11_TEXTURE2D_DESC { + Width: self.target_width, + Height: self.target_height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let data = D3D11_SUBRESOURCE_DATA { + pSysMem: pixel_data.as_ptr().cast(), + SysMemPitch: row_length as u32, + SysMemSlicePitch: 0, + }; + let mut output_texture = None; + unsafe { + self.device + .CreateTexture2D(&texture_desc, Some(&data), Some(&mut output_texture)) + .unwrap(); + } + ScreenFrame::Scaled(ScaledScreenFrame { + texture: output_texture.unwrap(), + pixel_data: Some(pixel_data), + readback: None, + width: self.target_width, + height: self.target_height, + pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm, + }) + } + } + + fn create_source_texture(device: &ID3D11Device, width: u32, height: u32) -> ID3D11Texture2D { + let mut pixels = vec![0u8; width as usize * height as usize * 4]; + for y in 0..height { + for x in 0..width { + let index = (y as usize * width as usize + x as usize) * 4; + pixels[index] = (x * 255 / (width - 1)) as u8; + pixels[index + 1] = (y * 255 / (height - 1)) as u8; + pixels[index + 2] = ((x + y) * 255 / (width + height - 2)) as u8; + pixels[index + 3] = 255; + } + } + let desc = D3D11_TEXTURE2D_DESC { + Width: width, + Height: height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let data = D3D11_SUBRESOURCE_DATA { + pSysMem: pixels.as_ptr().cast(), + SysMemPitch: width * 4, + SysMemSlicePitch: 0, + }; + let mut texture = None; + unsafe { + device + .CreateTexture2D(&desc, Some(&data), Some(&mut texture)) + .unwrap(); + } + texture.unwrap() + } + + fn run_scenario(source: (u32, u32), target: (u32, u32)) { + ffmpeg::init().unwrap(); + let device = crate::capture_pipeline::create_d3d_device().unwrap(); + let source_texture = create_source_texture(&device, source.0, source.1); + let mut cpu_scaler = CpuScaler::new(device.clone(), source.0, source.1, target.0, target.1); + let mut video_scaler = D3D11VideoScaler::new( + device, + source.0, + source.1, + target.0, + target.1, + scap_direct3d::PixelFormat::R8G8B8A8Unorm, + ) + .unwrap(); + for _ in 0..3 { + std::hint::black_box(cpu_scaler.scale(&source_texture)); + let scaled = ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()); + std::hint::black_box(scaled.as_ffmpeg().unwrap()); + } + + let cpu_output = cpu_scaler.scale(&source_texture).as_ffmpeg().unwrap(); + let gpu_output = ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()) + .as_ffmpeg() + .unwrap(); + let mut max_error = 0u8; + let mut total_error = 0u64; + let mut compared_channels = 0u64; + let row_length = target.0 as usize * 4; + for row in 0..target.1 as usize { + let cpu_start = row * cpu_output.stride(0); + let gpu_start = row * gpu_output.stride(0); + let cpu_row = &cpu_output.data(0)[cpu_start..cpu_start + row_length]; + let gpu_row = &gpu_output.data(0)[gpu_start..gpu_start + row_length]; + for (cpu, gpu) in cpu_row.iter().zip(gpu_row) { + let error = cpu.abs_diff(*gpu); + max_error = max_error.max(error); + total_error += error as u64; + compared_channels += 1; + } + } + let mean_error = total_error as f64 / compared_channels as f64; + println!( + "PIXELS {}x{} -> {}x{} max error {} mean error {:.3}", + source.0, source.1, target.0, target.1, max_error, mean_error + ); + assert!(mean_error <= 4.0 && max_error <= 20); + + let mut scale_samples = Vec::new(); + let mut software_samples = Vec::new(); + for _ in 0..3 { + let started = Instant::now(); + for _ in 0..12 { + std::hint::black_box(video_scaler.scale_frame(&source_texture).unwrap()); + } + scale_samples.push(started.elapsed().as_secs_f64() * 1000.0 / 12.0); + + let started = Instant::now(); + for _ in 0..12 { + let scaled = + ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()); + std::hint::black_box(scaled.as_ffmpeg().unwrap()); + } + software_samples.push(started.elapsed().as_secs_f64() * 1000.0 / 12.0); + } + scale_samples.sort_by(f64::total_cmp); + software_samples.sort_by(f64::total_cmp); + println!( + "D3D11 {}x{} -> {}x{} scale median {:.3} ms/frame (runs {:.3}, {:.3}, {:.3}); software-output median {:.3} ms/frame (runs {:.3}, {:.3}, {:.3})", + source.0, + source.1, + target.0, + target.1, + scale_samples[1], + scale_samples[0], + scale_samples[1], + scale_samples[2], + software_samples[1], + software_samples[0], + software_samples[1], + software_samples[2] + ); + } + + #[test] + #[ignore] + fn run_windows_screen_scale_benchmark() { + run_scenario((1920, 1080), (1280, 720)); + run_scenario((3840, 2160), (1920, 1080)); + } +} From 9fb5ca34b7caf131b1c066f565e5bbc2f02d5843 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:06:28 +0800 Subject: [PATCH 2/6] chore: rerun interrupted CI checks From 6c5e2575b47d8a1ea3efb9bc8a97d398b731464f Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:44:58 +0800 Subject: [PATCH 3/6] fix: repair Linux camera and screenshot CI setup --- .github/workflows/instant-reliability.yml | 7 +++++-- scripts/linux-desktop-harness/scenario-screenshot.sh | 8 +++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/instant-reliability.yml b/.github/workflows/instant-reliability.yml index af99f5174a4..6bf6b4de713 100644 --- a/.github/workflows/instant-reliability.yml +++ b/.github/workflows/instant-reliability.yml @@ -316,8 +316,11 @@ jobs: run: | set -euo pipefail sudo apt-get update -qq - # v4l2loopback needs videodev, which is in the extra kernel modules. - sudo apt-get install -y -qq "linux-modules-extra-$(uname -r)" v4l2loopback-dkms xvfb x11-utils xdotool \ + if ! sudo modprobe videodev 2>/dev/null; then + sudo apt-get install -y -qq "linux-modules-extra-$(uname -r)" + sudo modprobe videodev + fi + sudo apt-get install -y -qq "linux-headers-$(uname -r)" v4l2loopback-dkms xvfb x11-utils xdotool \ dbus ffmpeg pulseaudio pulseaudio-utils libasound2-plugins >/dev/null chmod +x "$RUNNER_TEMP/build/cap-gpui" "$RUNNER_TEMP/build/real-app-tests" sudo modprobe v4l2loopback video_nr=42 card_label="Cap Test Camera" exclusive_caps=1 diff --git a/scripts/linux-desktop-harness/scenario-screenshot.sh b/scripts/linux-desktop-harness/scenario-screenshot.sh index 512d63c9367..2ef6f75cf75 100755 --- a/scripts/linux-desktop-harness/scenario-screenshot.sh +++ b/scripts/linux-desktop-harness/scenario-screenshot.sh @@ -5,6 +5,12 @@ export XDG_RUNTIME_DIR=/run/user/$(id -u) export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus out=${HARNESS_OUT:-/out} eval "$(systemctl --user show-environment | grep -E "^(WAYLAND_DISPLAY|XDG_SESSION_TYPE|XDG_CURRENT_DESKTOP|XDG_SESSION_DESKTOP|LIBGL_ALWAYS_SOFTWARE|HYPRLAND_INSTANCE_SIGNATURE|NIRI_SOCKET)=" | sed 's/^/export /')" +expected_size=${SCREEN:-1920x1080} +if [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then + expected_size=$(hyprctl -j monitors | python3 -c 'import json, sys +monitor, = json.load(sys.stdin) +print("{}x{}".format(monitor["width"], monitor["height"]))') || exit 1 +fi : >"$out/result.txt" result() { printf '%s=%s\n' "$1" "$2" >>"$out/result.txt"; } @@ -81,7 +87,7 @@ if data[:8] == b"\x89PNG\r\n\x1a\n": print(*struct.unpack(">II", data[16:24]))' "$shot") echo "screenshot: ${shot:-none} ${size:-}" >>"$out/actions.log" result screenshot_taken "$([[ -n $size ]] && echo yes || echo no)" -result screenshot_size "$([[ ${size// /x} == "${SCREEN:-1920x1080}" ]] && echo yes || echo "${size// /x}")" +result screenshot_size "$([[ ${size// /x} == "$expected_size" ]] && echo yes || echo "${size// /x}")" result capture_failed "$(grep -ac 'screenshot capture failed' "$out/cap.log")" if [[ -z $shot ]]; then find "$HOME" /tmp -newer "$out/profile/store" -iname "Screenshot*.png" -printf "portal file: %s bytes %p\n" 2>/dev/null >>"$out/actions.log" From 9788aec6f681173fc29c13ed385292e523fe2d73 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:11:16 +0800 Subject: [PATCH 4/6] fix: configure current Hyprland in the Linux harness --- scripts/linux-desktop-harness/arch-up.sh | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/scripts/linux-desktop-harness/arch-up.sh b/scripts/linux-desktop-harness/arch-up.sh index 6a1a8028862..043d83d2e23 100755 --- a/scripts/linux-desktop-harness/arch-up.sh +++ b/scripts/linux-desktop-harness/arch-up.sh @@ -30,6 +30,17 @@ debug { disable_logs = false } exec-once = sh -c '$export_session' exec-once = waybar CONF + cat >"$HOME/.config/hypr/hyprland.lua" <"$HOME/.config/hypr/xdph.conf" < Date: Sun, 1 Nov 2026 02:40:44 +0800 Subject: [PATCH 5/6] fix: allow busy Wayland compositors to enumerate displays --- .../src/platform/linux/wayland.rs | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/scap-targets/src/platform/linux/wayland.rs b/crates/scap-targets/src/platform/linux/wayland.rs index c4b8bcdbf6a..8c0118f92bb 100644 --- a/crates/scap-targets/src/platform/linux/wayland.rs +++ b/crates/scap-targets/src/platform/linux/wayland.rs @@ -15,6 +15,8 @@ use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zx use super::{DisplayImpl, LogicalBounds, LogicalPosition, LogicalSize}; +const QUERY_TIMEOUT: Duration = Duration::from_secs(1); + #[derive(Clone, Copy, Default)] struct OutputGeometry { position: (i32, i32), @@ -108,7 +110,7 @@ pub(super) fn displays() -> Option> { runtime.join(display) }; let connection = Connection::from_socket(UnixStream::connect(socket).ok()?).ok()?; - query(&connection, Duration::from_millis(250)) + query(&connection, QUERY_TIMEOUT) } fn output_uuid(name: &str) -> Option { @@ -453,6 +455,45 @@ mod tests { assert!(started.elapsed() < Duration::from_secs(1)); } + #[test] + fn busy_compositor_can_finish_display_enumeration_after_a_quarter_second() { + use std::io::{Read, Write}; + + let (client, mut server) = UnixStream::pair().unwrap(); + let (finished_tx, finished_rx) = std::sync::mpsc::channel(); + let responder = std::thread::spawn(move || -> std::io::Result<()> { + for reply in 0..2 { + loop { + let mut header = [0u8; 8]; + server.read_exact(&mut header)?; + let object = u32::from_ne_bytes(header[..4].try_into().unwrap()); + let message = u32::from_ne_bytes(header[4..].try_into().unwrap()); + let mut payload = vec![0; (message >> 16) as usize - header.len()]; + server.read_exact(&mut payload)?; + if object != 1 || message & 0xffff != 0 { + continue; + } + if reply == 0 { + std::thread::sleep(Duration::from_millis(350)); + } + let callback = u32::from_ne_bytes(payload[..4].try_into().unwrap()); + server.write_all(&callback.to_ne_bytes())?; + server.write_all(&(12u32 << 16).to_ne_bytes())?; + server.write_all(&0u32.to_ne_bytes())?; + break; + } + } + let _ = finished_rx.recv(); + Ok(()) + }); + let connection = Connection::from_socket(client).unwrap(); + let result = query(&connection, QUERY_TIMEOUT); + drop(connection); + let _ = finished_tx.send(()); + responder.join().unwrap().unwrap(); + assert!(result.is_some()); + } + #[test] fn wayland_session_does_not_use_xwayland_dimensions() { assert!(super::super::prefers_wayland_environment( From 39a47f566b03ebad487b7ec6a6d6cb9b6c67c502 Mon Sep 17 00:00:00 2001 From: Kyzer <36684609+kyzer1023@users.noreply.github.com> Date: Thu, 5 Nov 2026 03:29:28 +0800 Subject: [PATCH 6/6] fix: lease pooled D3D11 screen scaling targets Retain scaled-frame leases through native encoder copies and paced repeats, and allocate overflow targets only when every pool slot is in flight. Add adapter-selectable pixel parity, allocation and lifetime tests, and explicit WARP capability and CPU-scaling coverage. --- crates/recording/src/output_pipeline/win.rs | 9 +- .../src/output_pipeline/win_segmented.rs | 3 + .../src/sources/screen_capture/windows.rs | 475 ++++++++++++++---- 3 files changed, 389 insertions(+), 98 deletions(-) diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs index faab33d6e76..1d318fabc60 100644 --- a/crates/recording/src/output_pipeline/win.rs +++ b/crates/recording/src/output_pipeline/win.rs @@ -342,7 +342,7 @@ impl Muxer for WindowsMuxer { either::Left((mut encoder, mut muxer)) => { trace!("Running native encoder with frame pacing"); let mut pacer = FramePacer::new(config.frame_rate); - let mut last_texture: Option = None; + let mut last_frame: Option = None; let mut first_timestamp: Option = None; let mut frame_count: u64 = 0; let mut frames_reused: u64 = 0; @@ -353,11 +353,12 @@ impl Muxer for WindowsMuxer { let (texture, timestamp) = match pacer.next(&video_rx, &pause_flag) { Paced::Frame(frame, timestamp) => { let texture = frame.texture().clone(); - last_texture = Some(texture.clone()); + // Retain the pool lease through the encoder's copy and any paced repeats. + last_frame = Some(frame); (texture, timestamp) } Paced::Repeat(timestamp) => { - let Some(texture) = &last_texture else { + let Some(frame) = &last_frame else { continue; }; frames_reused += 1; @@ -368,7 +369,7 @@ impl Muxer for WindowsMuxer { "Frame pacing: reusing frames due to slow capture" ); } - (texture.clone(), timestamp) + (frame.texture().clone(), timestamp) } Paced::End => { trace!("End of stream signal received"); diff --git a/crates/recording/src/output_pipeline/win_segmented.rs b/crates/recording/src/output_pipeline/win_segmented.rs index 1edaf97daf1..69417772681 100644 --- a/crates/recording/src/output_pipeline/win_segmented.rs +++ b/crates/recording/src/output_pipeline/win_segmented.rs @@ -531,6 +531,7 @@ impl WindowsSegmentedMuxer { either::Left((mut encoder, mut muxer)) => { trace!("Running native encoder for segment"); let mut first_timestamp: Option = None; + let mut last_frame: Option = None; let result = encoder.run( Arc::new(AtomicBool::default()), || { @@ -547,6 +548,8 @@ impl WindowsSegmentedMuxer { }; let frame_time = duration_to_timespan(relative); + // The encoder queues its texture copy before requesting the next frame. + let frame = last_frame.insert(frame); Ok(Some((frame.texture().clone(), frame_time))) }, |output_sample| { diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rs index 443013ce184..72976398322 100644 --- a/crates/recording/src/sources/screen_capture/windows.rs +++ b/crates/recording/src/sources/screen_capture/windows.rs @@ -12,7 +12,8 @@ use ::windows::Win32::Graphics::Direct3D11::{ D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_STREAM, D3D11_VPIV_DIMENSION_TEXTURE2D, D3D11_VPOV_DIMENSION_TEXTURE2D, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, ID3D11VideoContext, ID3D11VideoDevice, - ID3D11VideoProcessor, ID3D11VideoProcessorInputView, ID3D11VideoProcessorOutputView, + ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator, ID3D11VideoProcessorInputView, + ID3D11VideoProcessorOutputView, }; use ::windows::Win32::Graphics::Dxgi::Common::{ DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_RATIONAL, @@ -113,7 +114,7 @@ pub enum ScreenFrame { } pub struct ScaledScreenFrame { - texture: ID3D11Texture2D, + texture: Arc, pixel_data: Option>, readback: Option>, width: u32, @@ -201,12 +202,50 @@ impl D3D11FrameReadback { const D3D11_SCALE_TARGET_POOL_SIZE: usize = 3; struct D3D11ScaleTarget { - texture: ID3D11Texture2D, + texture: Arc, view: ID3D11VideoProcessorOutputView, } +impl D3D11ScaleTarget { + fn new( + device: &ID3D11Device, + video_device: &ID3D11VideoDevice, + enumerator: &ID3D11VideoProcessorEnumerator, + texture_desc: &D3D11_TEXTURE2D_DESC, + ) -> Result { + let mut texture = None; + unsafe { + device.CreateTexture2D(texture_desc, None, Some(&mut texture))?; + } + let texture = texture.ok_or_else(::windows::core::Error::from_win32)?; + let output_view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { + ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D, + Anonymous: + ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 { + Texture2D: D3D11_TEX2D_VPOV { MipSlice: 0 }, + }, + }; + let mut view = None; + unsafe { + video_device.CreateVideoProcessorOutputView( + &texture, + enumerator, + &output_view_desc, + Some(&mut view), + )?; + } + Ok(Self { + texture: Arc::new(texture), + view: view.ok_or_else(::windows::core::Error::from_win32)?, + }) + } +} + struct D3D11VideoScaler { device: ID3D11Device, + video_device: ID3D11VideoDevice, + enumerator: ID3D11VideoProcessorEnumerator, + target_desc: D3D11_TEXTURE2D_DESC, context: ID3D11DeviceContext, video_context: ID3D11VideoContext, processor: ID3D11VideoProcessor, @@ -218,6 +257,8 @@ struct D3D11VideoScaler { target_height: u32, pixel_format: scap_direct3d::PixelFormat, readback: Arc, + #[cfg(test)] + targets_created: usize, } impl D3D11VideoScaler { @@ -293,13 +334,6 @@ impl D3D11VideoScaler { } let input_view: ID3D11VideoProcessorInputView = input_view.ok_or_else(::windows::core::Error::from_win32)?; - let output_view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { - ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D, - Anonymous: - ::windows::Win32::Graphics::Direct3D11::D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 { - Texture2D: D3D11_TEX2D_VPOV { MipSlice: 0 }, - }, - }; let texture_desc = D3D11_TEXTURE2D_DESC { Width: target_width, Height: target_height, @@ -317,24 +351,12 @@ impl D3D11VideoScaler { }; let mut targets = Vec::with_capacity(D3D11_SCALE_TARGET_POOL_SIZE); for _ in 0..D3D11_SCALE_TARGET_POOL_SIZE { - let mut texture = None; - unsafe { - device.CreateTexture2D(&texture_desc, None, Some(&mut texture))?; - } - let texture = texture.ok_or_else(::windows::core::Error::from_win32)?; - let mut view = None; - unsafe { - video_device.CreateVideoProcessorOutputView( - &texture, - &enumerator, - &output_view_desc, - Some(&mut view), - )?; - } - targets.push(D3D11ScaleTarget { - texture, - view: view.ok_or_else(::windows::core::Error::from_win32)?, - }); + targets.push(D3D11ScaleTarget::new( + &device, + &video_device, + &enumerator, + &texture_desc, + )?); } let readback = Arc::new(D3D11FrameReadback { device: device.clone(), @@ -347,6 +369,9 @@ impl D3D11VideoScaler { Ok(Self { device, + video_device, + enumerator, + target_desc: texture_desc, context, video_context, processor, @@ -358,6 +383,8 @@ impl D3D11VideoScaler { target_height, pixel_format, readback, + #[cfg(test)] + targets_created: D3D11_SCALE_TARGET_POOL_SIZE, }) } @@ -368,9 +395,26 @@ impl D3D11VideoScaler { unsafe { self.context.CopyResource(&self.input_texture, input); } - let target_index = self.next_target; - self.next_target = (self.next_target + 1) % self.targets.len(); - let target = &self.targets[target_index]; + let free_target = (0..self.targets.len()) + .map(|offset| (self.next_target + offset) % self.targets.len()) + .find(|&index| Arc::strong_count(&self.targets[index].texture) == 1); + let overflow; + let target = if let Some(index) = free_target { + self.next_target = (index + 1) % self.targets.len(); + &self.targets[index] + } else { + overflow = D3D11ScaleTarget::new( + &self.device, + &self.video_device, + &self.enumerator, + &self.target_desc, + )?; + #[cfg(test)] + { + self.targets_created += 1; + } + &overflow + }; let mut stream = D3D11_VIDEO_PROCESSOR_STREAM { Enable: true.into(), pInputSurface: ManuallyDrop::new(Some(self.input_view.clone())), @@ -389,33 +433,8 @@ impl D3D11VideoScaler { } blt?; - let texture_desc = D3D11_TEXTURE2D_DESC { - Width: self.target_width, - Height: self.target_height, - MipLevels: 1, - ArraySize: 1, - Format: pixel_format_dxgi(self.pixel_format), - SampleDesc: DXGI_SAMPLE_DESC { - Count: 1, - Quality: 0, - }, - Usage: D3D11_USAGE_DEFAULT, - BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, - CPUAccessFlags: 0, - MiscFlags: 0, - }; - let mut output = None; - unsafe { - self.device - .CreateTexture2D(&texture_desc, None, Some(&mut output))?; - } - let output = output.ok_or_else(::windows::core::Error::from_win32)?; - unsafe { - self.context.CopyResource(&output, &target.texture); - } - Ok(ScaledScreenFrame { - texture: output, + texture: target.texture.clone(), pixel_data: None, readback: Some(self.readback.clone()), width: self.target_width, @@ -440,6 +459,7 @@ fn pixel_format_dxgi(pixel_format: scap_direct3d::PixelFormat) -> DXGI_FORMAT { } impl ScreenFrame { + // COM clones do not retain the pool lease; keep the frame until GPU reads are queued. pub fn texture(&self) -> &ID3D11Texture2D { match self { ScreenFrame::Captured(frame) => frame.texture(), @@ -701,7 +721,7 @@ impl WindowsFrameScaler { }; Some(ScreenFrame::Scaled(ScaledScreenFrame { - texture, + texture: Arc::new(texture), pixel_data: Some(pixel_data), readback: None, width: self.target_width, @@ -2046,15 +2066,79 @@ mod first_screen_frame_tests { } } #[cfg(test)] -mod windows_screen_scale_benchmark { +mod windows_screen_scale_tests { use super::*; + use ::windows::Win32::Foundation::{E_NOINTERFACE, HMODULE}; + use ::windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_UNKNOWN, D3D_DRIVER_TYPE_WARP}; use ::windows::Win32::Graphics::Direct3D11::{ - D3D11_CPU_ACCESS_READ, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SUBRESOURCE_DATA, - D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, + D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION, D3D11CreateDevice, }; - use ::windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use ::windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIDevice, IDXGIFactory1}; use std::time::Instant; + fn create_device(selector: &str) -> ID3D11Device { + let mut device = None; + if selector == "warp" { + unsafe { + D3D11CreateDevice( + None, + D3D_DRIVER_TYPE_WARP, + HMODULE::default(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + None, + D3D11_SDK_VERSION, + Some(&mut device), + None, + None, + ) + .expect("create WARP device"); + } + } else { + let adapter = if selector == "hardware" { + cap_d3d_adapter::select_capture_adapter(None) + .expect("physical hardware adapter") + .adapter + } else { + let index = selector.parse::().expect( + "CAP_D3D11_SCALE_ADAPTER must be hardware, warp, or a DXGI adapter index", + ); + let factory: IDXGIFactory1 = unsafe { CreateDXGIFactory1().unwrap() }; + unsafe { factory.EnumAdapters1(index).expect("DXGI adapter index") } + .cast() + .unwrap() + }; + unsafe { + D3D11CreateDevice( + &adapter, + D3D_DRIVER_TYPE_UNKNOWN, + HMODULE::default(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + None, + D3D11_SDK_VERSION, + Some(&mut device), + None, + None, + ) + .expect("create device on specified adapter"); + } + } + let device = device.unwrap(); + let dxgi_device: IDXGIDevice = device.cast().unwrap(); + let desc = unsafe { dxgi_device.GetAdapter().unwrap().GetDesc().unwrap() }; + let length = desc.Description.iter().take_while(|&&c| c != 0).count(); + println!( + "ADAPTER selector={selector} description={} vendor_id=0x{:04X} device_id=0x{:04X}", + String::from_utf16_lossy(&desc.Description[..length]), + desc.VendorId, + desc.DeviceId, + ); + device + } + + fn selected_device() -> ID3D11Device { + create_device(&std::env::var("CAP_D3D11_SCALE_ADAPTER").unwrap_or("hardware".into())) + } + struct CpuScaler { device: ID3D11Device, context: ::windows::Win32::Graphics::Direct3D11::ID3D11DeviceContext, @@ -2064,6 +2148,7 @@ mod windows_screen_scale_benchmark { source_height: u32, target_width: u32, target_height: u32, + pixel_format: scap_direct3d::PixelFormat, } impl CpuScaler { @@ -2073,6 +2158,7 @@ mod windows_screen_scale_benchmark { source_height: u32, target_width: u32, target_height: u32, + pixel_format: scap_direct3d::PixelFormat, ) -> Self { let context = unsafe { device.GetImmediateContext().unwrap() }; let staging_desc = D3D11_TEXTURE2D_DESC { @@ -2080,7 +2166,7 @@ mod windows_screen_scale_benchmark { Height: source_height, MipLevels: 1, ArraySize: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Format: pixel_format_dxgi(pixel_format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, @@ -2097,10 +2183,10 @@ mod windows_screen_scale_benchmark { .unwrap(); } let scaler = ffmpeg::software::scaling::Context::get( - ffmpeg::format::Pixel::RGBA, + pixel_format_ffmpeg(pixel_format), source_width, source_height, - ffmpeg::format::Pixel::RGBA, + pixel_format_ffmpeg(pixel_format), target_width, target_height, ffmpeg::software::scaling::Flags::BILINEAR, @@ -2115,6 +2201,7 @@ mod windows_screen_scale_benchmark { source_height, target_width, target_height, + pixel_format, } } @@ -2131,7 +2218,7 @@ mod windows_screen_scale_benchmark { let source_stride = mapped.RowPitch as usize; let source_row_length = self.source_width as usize * 4; let mut source_frame = ffmpeg::frame::Video::new( - ffmpeg::format::Pixel::RGBA, + pixel_format_ffmpeg(self.pixel_format), self.source_width, self.source_height, ); @@ -2157,7 +2244,7 @@ mod windows_screen_scale_benchmark { } let mut output_frame = ffmpeg::frame::Video::new( - ffmpeg::format::Pixel::RGBA, + pixel_format_ffmpeg(self.pixel_format), self.target_width, self.target_height, ); @@ -2178,7 +2265,7 @@ mod windows_screen_scale_benchmark { Height: self.target_height, MipLevels: 1, ArraySize: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Format: pixel_format_dxgi(self.pixel_format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, @@ -2200,25 +2287,40 @@ mod windows_screen_scale_benchmark { .unwrap(); } ScreenFrame::Scaled(ScaledScreenFrame { - texture: output_texture.unwrap(), + texture: Arc::new(output_texture.unwrap()), pixel_data: Some(pixel_data), readback: None, width: self.target_width, height: self.target_height, - pixel_format: scap_direct3d::PixelFormat::R8G8B8A8Unorm, + pixel_format: self.pixel_format, }) } } - fn create_source_texture(device: &ID3D11Device, width: u32, height: u32) -> ID3D11Texture2D { + fn create_source_texture( + device: &ID3D11Device, + width: u32, + height: u32, + pixel_format: scap_direct3d::PixelFormat, + solid: Option<[u8; 4]>, + ) -> ID3D11Texture2D { let mut pixels = vec![0u8; width as usize * height as usize * 4]; for y in 0..height { for x in 0..width { let index = (y as usize * width as usize + x as usize) * 4; - pixels[index] = (x * 255 / (width - 1)) as u8; - pixels[index + 1] = (y * 255 / (height - 1)) as u8; - pixels[index + 2] = ((x + y) * 255 / (width + height - 2)) as u8; - pixels[index + 3] = 255; + let rgba = solid.unwrap_or([ + (x * 255 / (width - 1)) as u8, + (y * 255 / (height - 1)) as u8, + ((x + y) * 255 / (width + height - 2)) as u8, + 255, + ]); + let channels = match pixel_format { + scap_direct3d::PixelFormat::R8G8B8A8Unorm => rgba, + scap_direct3d::PixelFormat::B8G8R8A8Unorm => { + [rgba[2], rgba[1], rgba[0], rgba[3]] + } + }; + pixels[index..index + 4].copy_from_slice(&channels); } } let desc = D3D11_TEXTURE2D_DESC { @@ -2226,7 +2328,7 @@ mod windows_screen_scale_benchmark { Height: height, MipLevels: 1, ArraySize: 1, - Format: DXGI_FORMAT_R8G8B8A8_UNORM, + Format: pixel_format_dxgi(pixel_format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, @@ -2250,25 +2352,37 @@ mod windows_screen_scale_benchmark { texture.unwrap() } - fn run_scenario(source: (u32, u32), target: (u32, u32)) { + fn run_scenario( + device: &ID3D11Device, + source: (u32, u32), + target: (u32, u32), + pixel_format: scap_direct3d::PixelFormat, + solid: Option<[u8; 4]>, + benchmark: bool, + ) { ffmpeg::init().unwrap(); - let device = crate::capture_pipeline::create_d3d_device().unwrap(); - let source_texture = create_source_texture(&device, source.0, source.1); - let mut cpu_scaler = CpuScaler::new(device.clone(), source.0, source.1, target.0, target.1); let mut video_scaler = D3D11VideoScaler::new( - device, + device.clone(), source.0, source.1, target.0, target.1, - scap_direct3d::PixelFormat::R8G8B8A8Unorm, + pixel_format, ) - .unwrap(); - for _ in 0..3 { - std::hint::black_box(cpu_scaler.scale(&source_texture)); - let scaled = ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()); - std::hint::black_box(scaled.as_ffmpeg().unwrap()); - } + .unwrap_or_else(|error| { + panic!( + "D3D11 video scaling unavailable: {error:?}. WARP does not expose ID3D11VideoDevice; pixel parity and video-processor benchmarks require a supporting hardware adapter." + ) + }); + let source_texture = create_source_texture(device, source.0, source.1, pixel_format, solid); + let mut cpu_scaler = CpuScaler::new( + device.clone(), + source.0, + source.1, + target.0, + target.1, + pixel_format, + ); let cpu_output = cpu_scaler.scale(&source_texture).as_ffmpeg().unwrap(); let gpu_output = ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()) @@ -2277,33 +2391,61 @@ mod windows_screen_scale_benchmark { let mut max_error = 0u8; let mut total_error = 0u64; let mut compared_channels = 0u64; + let mut channel_max = [0u8; 4]; + let mut channel_total = [0u64; 4]; let row_length = target.0 as usize * 4; for row in 0..target.1 as usize { let cpu_start = row * cpu_output.stride(0); let gpu_start = row * gpu_output.stride(0); let cpu_row = &cpu_output.data(0)[cpu_start..cpu_start + row_length]; let gpu_row = &gpu_output.data(0)[gpu_start..gpu_start + row_length]; - for (cpu, gpu) in cpu_row.iter().zip(gpu_row) { + for (index, (cpu, gpu)) in cpu_row.iter().zip(gpu_row).enumerate() { let error = cpu.abs_diff(*gpu); max_error = max_error.max(error); total_error += error as u64; compared_channels += 1; + channel_max[index % 4] = channel_max[index % 4].max(error); + channel_total[index % 4] += error as u64; } } let mean_error = total_error as f64 / compared_channels as f64; + let channel_mean = channel_total.map(|total| total as f64 / (target.0 * target.1) as f64); println!( - "PIXELS {}x{} -> {}x{} max error {} mean error {:.3}", - source.0, source.1, target.0, target.1, max_error, mean_error + "PIXELS {:?} solid={solid:?} {}x{} -> {}x{} max delta {} mean delta {:.6}; channel max {:?} mean {:.6?}", + pixel_format, + source.0, + source.1, + target.0, + target.1, + max_error, + mean_error, + channel_max, + channel_mean, ); assert!(mean_error <= 4.0 && max_error <= 20); + if !benchmark { + return; + } + for _ in 0..3 { + std::hint::black_box(cpu_scaler.scale(&source_texture)); + let scaled = ScreenFrame::Scaled(video_scaler.scale_frame(&source_texture).unwrap()); + std::hint::black_box(scaled.as_ffmpeg().unwrap()); + } let mut scale_samples = Vec::new(); let mut software_samples = Vec::new(); + let mut cpu_samples = Vec::new(); for _ in 0..3 { let started = Instant::now(); for _ in 0..12 { std::hint::black_box(video_scaler.scale_frame(&source_texture).unwrap()); } + std::hint::black_box( + video_scaler + .readback + .read(&video_scaler.targets[0].texture) + .unwrap(), + ); scale_samples.push(started.elapsed().as_secs_f64() * 1000.0 / 12.0); let started = Instant::now(); @@ -2313,9 +2455,16 @@ mod windows_screen_scale_benchmark { std::hint::black_box(scaled.as_ffmpeg().unwrap()); } software_samples.push(started.elapsed().as_secs_f64() * 1000.0 / 12.0); + + let started = Instant::now(); + for _ in 0..12 { + std::hint::black_box(cpu_scaler.scale(&source_texture)); + } + cpu_samples.push(started.elapsed().as_secs_f64() * 1000.0 / 12.0); } scale_samples.sort_by(f64::total_cmp); software_samples.sort_by(f64::total_cmp); + cpu_samples.sort_by(f64::total_cmp); println!( "D3D11 {}x{} -> {}x{} scale median {:.3} ms/frame (runs {:.3}, {:.3}, {:.3}); software-output median {:.3} ms/frame (runs {:.3}, {:.3}, {:.3})", source.0, @@ -2331,13 +2480,151 @@ mod windows_screen_scale_benchmark { software_samples[1], software_samples[2] ); + println!( + "CPU {}x{} -> {}x{} median {:.3} ms/frame (runs {:.3}, {:.3}, {:.3}); output textures created {}", + source.0, + source.1, + target.0, + target.1, + cpu_samples[1], + cpu_samples[0], + cpu_samples[1], + cpu_samples[2], + video_scaler.targets_created, + ); + assert_eq!(video_scaler.targets_created, D3D11_SCALE_TARGET_POOL_SIZE); + } + + #[test] + #[ignore = "requires a video-capable adapter; CAP_D3D11_SCALE_ADAPTER=hardware|warp|"] + fn d3d11_scale_pixel_parity() { + let device = selected_device(); + for format in [ + scap_direct3d::PixelFormat::R8G8B8A8Unorm, + scap_direct3d::PixelFormat::B8G8R8A8Unorm, + ] { + run_scenario(&device, (1920, 1080), (1280, 720), format, None, false); + run_scenario(&device, (3840, 2160), (1920, 1080), format, None, false); + run_scenario(&device, (638, 358), (318, 178), format, None, false); + for color in [ + [255, 0, 0, 255], + [0, 255, 0, 255], + [0, 0, 255, 255], + [128, 128, 128, 255], + ] { + run_scenario(&device, (64, 48), (32, 24), format, Some(color), false); + } + } + } + + #[test] + fn d3d11_scale_warp_reports_unsupported_video_processing() { + let device = create_device("warp"); + let result = D3D11VideoScaler::new( + device.clone(), + 64, + 48, + 32, + 24, + scap_direct3d::PixelFormat::R8G8B8A8Unorm, + ); + let Err(error) = result else { + panic!("WARP unexpectedly supports ID3D11VideoDevice"); + }; + println!("WARP video processor unsupported: {error:?}; CPU fallback required"); + assert_eq!(error.code(), E_NOINTERFACE); + for format in [ + scap_direct3d::PixelFormat::R8G8B8A8Unorm, + scap_direct3d::PixelFormat::B8G8R8A8Unorm, + ] { + let source = create_source_texture(&device, 64, 48, format, Some([255, 0, 0, 255])); + let mut cpu_scaler = CpuScaler::new(device.clone(), 64, 48, 32, 24, format); + let frame = cpu_scaler.scale(&source).as_ffmpeg().unwrap(); + let expected = match format { + scap_direct3d::PixelFormat::R8G8B8A8Unorm => [255, 0, 0, 255], + scap_direct3d::PixelFormat::B8G8R8A8Unorm => [0, 0, 255, 255], + }; + for row in 0..24 { + let start = row * frame.stride(0); + assert!( + frame.data(0)[start..start + 32 * 4] + .chunks_exact(4) + .all(|pixel| pixel == expected) + ); + } + println!("WARP CPU scaler {format:?} 64x48 -> 32x24: solid red preserved"); + } + } + + #[test] + #[ignore = "requires a video-capable adapter; CAP_D3D11_SCALE_ADAPTER=hardware|"] + fn d3d11_scale_pool_reuses_targets_without_allocating() { + let device = selected_device(); + let format = scap_direct3d::PixelFormat::R8G8B8A8Unorm; + let source = create_source_texture(&device, 64, 48, format, None); + let mut scaler = D3D11VideoScaler::new(device, 64, 48, 32, 24, format).unwrap(); + for index in 0..120 { + let frame = scaler.scale_frame(&source).unwrap(); + assert!(Arc::ptr_eq( + &frame.texture, + &scaler.targets[index % D3D11_SCALE_TARGET_POOL_SIZE].texture, + )); + drop(frame); + } + println!( + "POOL 120 promptly dropped frames: {} output textures created", + scaler.targets_created + ); + assert_eq!(scaler.targets_created, D3D11_SCALE_TARGET_POOL_SIZE); + } + + #[test] + #[ignore = "requires a video-capable adapter; CAP_D3D11_SCALE_ADAPTER=hardware|"] + fn d3d11_scale_pool_preserves_in_flight_frames() { + let device = selected_device(); + let format = scap_direct3d::PixelFormat::R8G8B8A8Unorm; + let mut scaler = D3D11VideoScaler::new(device.clone(), 64, 48, 32, 24, format).unwrap(); + let mut held = Vec::new(); + let mut expected = Vec::new(); + for color in [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]] { + let source = create_source_texture(&device, 64, 48, format, Some(color)); + let frame = scaler.scale_frame(&source).unwrap(); + expected.push(scaler.readback.read(&frame.texture).unwrap()); + held.push(frame); + } + let source = create_source_texture(&device, 64, 48, format, Some([255; 4])); + for _ in 0..12 { + let overflow = scaler.scale_frame(&source).unwrap(); + assert!( + held.iter() + .all(|frame| !Arc::ptr_eq(&frame.texture, &overflow.texture)) + ); + drop(overflow); + } + assert_eq!(scaler.targets_created, D3D11_SCALE_TARGET_POOL_SIZE + 12); + for (frame, pixels) in held.iter().zip(&expected) { + assert_eq!(&scaler.readback.read(&frame.texture).unwrap(), pixels); + } + let released = held.remove(1); + let released_pointer = Arc::as_ptr(&released.texture); + drop(released); + let reused = scaler.scale_frame(&source).unwrap(); + assert_eq!(Arc::as_ptr(&reused.texture), released_pointer); + assert_eq!(scaler.targets_created, D3D11_SCALE_TARGET_POOL_SIZE + 12); + println!("POOL held frames preserved through 12 overflows; released slot reused"); + drop(scaler); + let frame = ScreenFrame::Scaled(held.remove(0)); + let pixels = frame.as_ffmpeg().unwrap(); + assert_eq!(&pixels.data(0)[..32 * 4], &expected[0][..32 * 4]); } #[test] - #[ignore] + #[ignore = "requires a video-capable adapter; CAP_D3D11_SCALE_ADAPTER=hardware|warp|"] fn run_windows_screen_scale_benchmark() { - run_scenario((1920, 1080), (1280, 720)); - run_scenario((3840, 2160), (1920, 1080)); + let device = selected_device(); + let format = scap_direct3d::PixelFormat::R8G8B8A8Unorm; + run_scenario(&device, (1920, 1080), (1280, 720), format, None, true); + run_scenario(&device, (3840, 2160), (1920, 1080), format, None, true); } }