From 88450190edfaabb09143677cb79fd5d56eee3ec5 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:29:10 +0000 Subject: [PATCH 1/4] perf(recording): submit Windows screen frames as D3D11 textures The fragmented Studio and Instant screen encoders copy the capture texture into a private ring and queue that texture when a hardware encoder accepts D3D11 input. libx264, a refused MFT, and a dead device stay on the Map plus BGRA upload path. Co-authored-by: Kyzer --- crates/enc-ffmpeg/src/mux/segmented_stream.rs | 60 +- crates/enc-ffmpeg/src/video/d3d11_hw.rs | 224 ++++++++ crates/enc-ffmpeg/src/video/h264.rs | 193 +++++++ crates/enc-ffmpeg/src/video/mod.rs | 4 + .../d3d11-texture-encode-benchmark.rs | 513 ++++++++++++++++++ crates/recording/src/capture_pipeline.rs | 4 + .../src/output_pipeline/d3d11_texture_ring.rs | 171 ++++++ .../recording/src/output_pipeline/ffmpeg.rs | 1 + .../output_pipeline/macos_fragmented_m4s.rs | 2 + crates/recording/src/output_pipeline/mod.rs | 4 + .../src/output_pipeline/texture_slots.rs | 103 ++++ .../src/output_pipeline/win_fragmented_m4s.rs | 272 ++++++++-- 12 files changed, 1500 insertions(+), 51 deletions(-) create mode 100644 crates/enc-ffmpeg/src/video/d3d11_hw.rs create mode 100644 crates/recording/examples/d3d11-texture-encode-benchmark.rs create mode 100644 crates/recording/src/output_pipeline/d3d11_texture_ring.rs create mode 100644 crates/recording/src/output_pipeline/texture_slots.rs diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 864d4653720..0249b584ada 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -334,6 +334,8 @@ pub struct SegmentedVideoEncoderConfig { /// [`SegmentedVideoEncoder::queue_hw_pixel_buffer`]) before falling back /// to the software-frame path. Ignored on other platforms. pub prefer_videotoolbox_hw_input: bool, + /// Address of an `ID3D11Device` that must outlive the encoder. Windows only. + pub d3d11_device: Option, } impl Default for SegmentedVideoEncoderConfig { @@ -344,6 +346,7 @@ impl Default for SegmentedVideoEncoderConfig { bpp: H264EncoderBuilder::QUALITY_BPP, output_size: None, prefer_videotoolbox_hw_input: false, + d3d11_device: None, } } } @@ -462,7 +465,24 @@ impl SegmentedVideoEncoder { } else { None }; - #[cfg(not(target_os = "macos"))] + #[cfg(target_os = "windows")] + let hw_attempt = match config.d3d11_device { + Some(device) => { + let device = device as *mut std::ffi::c_void; + match unsafe { builder.clone().build_d3d11_hw_input(&mut output, device) } { + Ok(encoder) => Some(encoder), + Err(error) => { + tracing::info!( + %error, + "D3D11 texture input unavailable, using the CPU frame path" + ); + None + } + } + } + None => None, + }; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] let hw_attempt: Option = None; let encoder = match hw_attempt { @@ -583,6 +603,44 @@ impl SegmentedVideoEncoder { self.queue_frame(frame, timestamp) } + #[cfg(windows)] + pub fn is_d3d11_hw_input(&self) -> bool { + self.encoder.is_d3d11_hw_input() + } + + #[cfg(windows)] + pub fn abandon_d3d11_input(&mut self) -> bool { + if !self.encoder.is_d3d11_hw_input() { + return false; + } + match self.encoder.replace_with_software() { + Ok(()) => { + tracing::warn!("D3D11 texture input stopped; later frames use the CPU path"); + true + } + Err(error) => { + tracing::error!(%error, "Could not leave the D3D11 texture path"); + false + } + } + } + + /// # Safety + /// `texture` must be an RGBA texture on the device passed at init, at the + /// encoder's width and height. `lifetime.free` runs once when the queued + /// frame is dropped. + #[cfg(windows)] + pub unsafe fn queue_d3d11_texture( + &mut self, + texture: *mut std::ffi::c_void, + timestamp: Duration, + lifetime: Option, + ) -> Result<(), QueueFrameError> { + let frame = unsafe { self.encoder.wrap_d3d11_texture(texture, lifetime) } + .map_err(InitError::Encoder)?; + self.queue_frame(frame, timestamp) + } + pub fn queue_frame( &mut self, frame: frame::Video, diff --git a/crates/enc-ffmpeg/src/video/d3d11_hw.rs b/crates/enc-ffmpeg/src/video/d3d11_hw.rs new file mode 100644 index 00000000000..d4c93ae95ba --- /dev/null +++ b/crates/enc-ffmpeg/src/video/d3d11_hw.rs @@ -0,0 +1,224 @@ +//! `data[0]` is the texture pointer and `data[1]` is the array index. +//! FFmpeg releases the device pointer stored on the hwdevice context, so that +//! pointer is AddRef'd before `av_hwdevice_ctx_init`. + +use std::ffi::c_void; +use std::ptr::null_mut; + +use ffmpeg::sys::{ + AVBufferRef, AVCodecContext, AVHWDeviceContext, AVHWDeviceType, AVHWFramesContext, + AVPixelFormat, av_buffer_create, av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_alloc, + av_hwdevice_ctx_init, av_hwframe_ctx_alloc, av_hwframe_ctx_init, +}; +use windows::core::{IUnknown, Interface}; + +const BIND_SHADER_RESOURCE: u32 = 0x8; +const BIND_RENDER_TARGET: u32 = 0x20; +const BIND_VIDEO_ENCODER: u32 = 0x400; + +#[repr(C)] +struct D3d11FramesHwctx { + texture: *mut c_void, + bind_flags: u32, + misc_flags: u32, +} + +#[derive(thiserror::Error, Debug)] +pub enum D3d11HwError { + #[error("Failed to create a D3D11 hardware device context")] + DeviceCreation, + #[error("Failed to allocate a D3D11 hardware frames context")] + FramesAllocation, + #[error("Failed to initialize a D3D11 hardware frames context: {0}")] + FramesInit(i32), + #[error("Failed to wrap a D3D11 texture into an AVFrame")] + FrameWrap, +} + +pub struct D3d11TextureLifetime { + pub data: *mut c_void, + pub free: unsafe extern "C" fn(*mut c_void), +} + +struct ExtraRelease { + free: unsafe extern "C" fn(*mut c_void), + data: *mut c_void, +} + +pub(crate) struct D3d11HwFrames { + device_ctx: *mut AVBufferRef, + frames_ctx: *mut AVBufferRef, + width: u32, + height: u32, +} + +unsafe impl Send for D3d11HwFrames {} +unsafe impl Sync for D3d11HwFrames {} + +unsafe fn add_ref(ptr: *mut c_void) -> *mut c_void { + unsafe { + let owned = IUnknown::from_raw(ptr); + let extra = owned.clone(); + std::mem::forget(extra); + std::mem::forget(owned); + } + ptr +} + +unsafe fn release(ptr: *mut c_void) { + if ptr.is_null() { + return; + } + unsafe { + drop(IUnknown::from_raw(ptr)); + } +} + +unsafe extern "C" fn release_texture(opaque: *mut c_void, data: *mut u8) { + unsafe { + release(data as *mut c_void); + if !opaque.is_null() { + let extra = Box::from_raw(opaque as *mut ExtraRelease); + (extra.free)(extra.data); + } + } +} + +fn fail_lifetime(lifetime: Option) { + if let Some(lifetime) = lifetime { + unsafe { (lifetime.free)(lifetime.data) }; + } +} + +impl D3d11HwFrames { + /// # Safety + /// `device` must be a valid `ID3D11Device` that stays alive until this + /// value is dropped. Textures wrapped later must belong to that device. + pub(crate) unsafe fn new( + device: *mut c_void, + width: u32, + height: u32, + ) -> Result { + if device.is_null() || width == 0 || height == 0 { + return Err(D3d11HwError::DeviceCreation); + } + unsafe { + let device_ctx = av_hwdevice_ctx_alloc(AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA); + if device_ctx.is_null() { + return Err(D3d11HwError::DeviceCreation); + } + let hw = (*device_ctx).data as *mut AVHWDeviceContext; + let d3d_device = (*hw).hwctx as *mut *mut c_void; + if hw.is_null() || d3d_device.is_null() { + let mut device_ctx = device_ctx; + av_buffer_unref(&mut device_ctx); + return Err(D3d11HwError::DeviceCreation); + } + *d3d_device = add_ref(device); + if av_hwdevice_ctx_init(device_ctx) < 0 { + let mut device_ctx = device_ctx; + av_buffer_unref(&mut device_ctx); + return Err(D3d11HwError::DeviceCreation); + } + + let frames_ctx = av_hwframe_ctx_alloc(device_ctx); + if frames_ctx.is_null() { + let mut device_ctx = device_ctx; + av_buffer_unref(&mut device_ctx); + return Err(D3d11HwError::FramesAllocation); + } + + let ctx = (*frames_ctx).data as *mut AVHWFramesContext; + (*ctx).format = AVPixelFormat::AV_PIX_FMT_D3D11; + (*ctx).sw_format = AVPixelFormat::AV_PIX_FMT_RGBA; + (*ctx).width = width as i32; + (*ctx).height = height as i32; + (*ctx).initial_pool_size = 0; + let frames_hw = (*ctx).hwctx as *mut D3d11FramesHwctx; + if !frames_hw.is_null() { + (*frames_hw).bind_flags = + BIND_SHADER_RESOURCE | BIND_RENDER_TARGET | BIND_VIDEO_ENCODER; + } + + let init_result = av_hwframe_ctx_init(frames_ctx); + if init_result < 0 { + let mut frames_ctx = frames_ctx; + av_buffer_unref(&mut frames_ctx); + let mut device_ctx = device_ctx; + av_buffer_unref(&mut device_ctx); + return Err(D3d11HwError::FramesInit(init_result)); + } + + Ok(Self { + device_ctx, + frames_ctx, + width, + height, + }) + } + } + + /// # Safety + /// `encoder_ctx` must be a valid, not-yet-opened `AVCodecContext`. + pub(crate) unsafe fn attach_to_encoder(&self, encoder_ctx: *mut AVCodecContext) { + unsafe { + (*encoder_ctx).hw_frames_ctx = av_buffer_ref(self.frames_ctx); + } + } + + /// # Safety + /// `texture` must be a 2D `ID3D11Texture2D` on this device, RGBA + /// (`DXGI_FORMAT_R8G8B8A8_UNORM`), matching `width` and `height`. + /// `lifetime.free` runs once, on whichever thread drops the frame. + pub(crate) unsafe fn wrap_texture( + &self, + texture: *mut c_void, + lifetime: Option, + ) -> Result { + if texture.is_null() { + fail_lifetime(lifetime); + return Err(D3d11HwError::FrameWrap); + } + let mut frame = ffmpeg::frame::Video::empty(); + unsafe { + let retained = add_ref(texture); + let opaque = match lifetime { + Some(lifetime) => Box::into_raw(Box::new(ExtraRelease { + free: lifetime.free, + data: lifetime.data, + })) as *mut c_void, + None => null_mut(), + }; + let buf = av_buffer_create(retained as *mut u8, 1, Some(release_texture), opaque, 0); + if buf.is_null() { + release(retained); + if !opaque.is_null() { + let extra = Box::from_raw(opaque as *mut ExtraRelease); + (extra.free)(extra.data); + } + return Err(D3d11HwError::FrameWrap); + } + let ptr = frame.as_mut_ptr(); + (*ptr).buf[0] = buf; + (*ptr).data[0] = retained as *mut u8; + (*ptr).data[1] = null_mut(); + (*ptr).format = AVPixelFormat::AV_PIX_FMT_D3D11 as i32; + (*ptr).width = self.width as i32; + (*ptr).height = self.height as i32; + (*ptr).hw_frames_ctx = av_buffer_ref(self.frames_ctx); + if (*ptr).hw_frames_ctx.is_null() { + return Err(D3d11HwError::FrameWrap); + } + } + Ok(frame) + } +} + +impl Drop for D3d11HwFrames { + fn drop(&mut self) { + unsafe { + av_buffer_unref(&mut self.frames_ctx); + av_buffer_unref(&mut self.device_ctx); + } + } +} diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 6f10c31278f..7f06a132215 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -13,6 +13,8 @@ use tracing::{debug, error, info, trace, warn}; use crate::base::{EncoderBase, PacketSink}; use crate::video::HwUpload; +#[cfg(windows)] +use crate::video::d3d11_hw::{D3d11HwFrames, D3d11TextureLifetime}; use crate::video::h264_packet::H264PacketEncoder; use crate::video::hardware_crash::{self, HardwareEncoderSession}; use crate::video::isolated_self_test; @@ -87,10 +89,48 @@ pub enum H264EncoderError { SelfTest(String), #[error("VideoToolbox hardware input unavailable: {0}")] VideoToolboxHwInput(String), + #[error("D3D11 texture input unavailable: {0}")] + D3d11HwInput(String), #[error("VA-API: {0}")] Vaapi(String), } +#[cfg(windows)] +fn open_d3d11_encoder( + hw_frames: &D3d11HwFrames, + codec: Codec, + encoder_options: Dictionary<'static>, + input_config: &VideoInfo, + output_width: u32, + output_height: u32, + bpp: f32, +) -> Result { + let thread_count = thread::available_parallelism() + .map(|count| count.get()) + .unwrap_or(1); + let mut encoder_ctx = context::Context::new_with_codec(codec); + encoder_ctx.set_threading(Config::count(thread_count)); + let mut encoder = encoder_ctx.encoder().video()?; + encoder.set_width(output_width); + encoder.set_height(output_height); + encoder.set_format(ffmpeg::format::Pixel::D3D11); + encoder.set_time_base(input_config.time_base); + encoder.set_frame_rate(Some(input_config.frame_rate)); + encoder.set_colorspace(color::Space::BT709); + encoder.set_color_range(color::Range::MPEG); + unsafe { + (*encoder.as_mut_ptr()).color_primaries = ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709; + (*encoder.as_mut_ptr()).color_trc = + ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709; + hw_frames.attach_to_encoder(encoder.as_mut_ptr()); + } + let frame_rate = input_config.frame_rate.0 as f32 / input_config.frame_rate.1.max(1) as f32; + let bitrate = get_bitrate(output_width, output_height, frame_rate, bpp); + encoder.set_bit_rate(bitrate); + encoder.set_max_bit_rate(bitrate * 3 / 2); + Ok(encoder.open_as_with(codec, encoder_options)?) +} + fn is_hardware_h264(codec_name: &str) -> bool { matches!( codec_name, @@ -363,6 +403,8 @@ impl H264EncoderBuilder { hw_upload, #[cfg(target_os = "macos")] videotoolbox_hw: None, + #[cfg(windows)] + d3d11_hw: None, software_fallback: None, #[cfg(test)] injected_failure: None, @@ -404,6 +446,8 @@ impl H264EncoderBuilder { hw_upload, #[cfg(target_os = "macos")] videotoolbox_hw: None, + #[cfg(windows)] + d3d11_hw: None, software_fallback: None, #[cfg(test)] injected_failure: None, @@ -590,6 +634,125 @@ impl H264EncoderBuilder { }) } + /// # Safety + /// `device` must be a live `ID3D11Device` that outlives the encoder. + #[cfg(windows)] + pub unsafe fn build_d3d11_hw_input( + self, + output: &mut format::context::Output, + device: *mut std::ffi::c_void, + ) -> Result { + const D3D11_TEXTURE_ENCODERS: &[&str] = &["h264_amf", "h264_nvenc", "h264_qsv", "h264_mf"]; + + let software_fallback = Box::new(self.clone()); + let input_config = self.input_config; + let (output_width, output_height) = match self.output_size { + Some((width, height)) + if width == input_config.width && height == input_config.height => + { + (width, height) + } + Some((width, height)) => { + return Err(H264EncoderError::D3d11HwInput(format!( + "scaling {}x{} to {}x{} stays on the CPU frame path", + input_config.width, input_config.height, width, height + ))); + } + None => (input_config.width, input_config.height), + }; + if !output_width.is_multiple_of(2) || !output_height.is_multiple_of(2) { + return Err(H264EncoderError::InvalidOutputDimensions { + width: output_width, + height: output_height, + }); + } + if device.is_null() { + return Err(H264EncoderError::D3d11HwInput( + "no D3D11 device".to_string(), + )); + } + if force_software_encoder() + || requires_software_encoder(&input_config, self.preset, self.is_export) + || self.crf.is_some() + { + return Err(H264EncoderError::D3d11HwInput( + "software encoder required for this recording".to_string(), + )); + } + + let hw_frames = unsafe { D3d11HwFrames::new(device, output_width, output_height) } + .map_err(|error| H264EncoderError::D3d11HwInput(error.to_string()))?; + + let candidates = get_codec_and_options( + &input_config, + self.preset, + self.encoder_priority_override, + self.is_export, + None, + ); + let mut last_error = None; + for (codec, encoder_options) in candidates { + let codec_name = codec.name().to_string(); + if !D3D11_TEXTURE_ENCODERS.contains(&codec_name.as_str()) { + continue; + } + match open_d3d11_encoder( + &hw_frames, + codec, + encoder_options, + &input_config, + output_width, + output_height, + self.bpp, + ) { + Ok(encoder) => { + let mut output_stream = output.add_stream(codec)?; + let stream_index = output_stream.index(); + output_stream.set_time_base((1, H264Encoder::TIME_BASE)); + output_stream.set_rate(input_config.frame_rate); + output_stream.set_parameters(&encoder); + info!( + encoder = %codec_name, + width = output_width, + height = output_height, + "Selected hardware H264 encoder with D3D11 texture input" + ); + return Ok(H264Encoder { + base: EncoderBase::new(stream_index), + encoder, + converter: None, + output_format: ffmpeg::format::Pixel::D3D11, + output_width, + output_height, + input_format: input_config.pixel_format, + input_width: input_config.width, + input_height: input_config.height, + converted_frame_pool: None, + hw_upload: HwUpload::default(), + d3d11_hw: Some(Arc::new(hw_frames)), + software_fallback: Some(software_fallback), + #[cfg(test)] + injected_failure: None, + hardware_session: Some(HardwareEncoderSession::begin(&codec_name)), + }); + } + Err(error) => { + debug!( + encoder = %codec_name, + %error, + "D3D11 texture input open failed" + ); + last_error = Some(error); + } + } + } + Err(last_error.unwrap_or_else(|| { + H264EncoderError::D3d11HwInput( + "no hardware encoder accepted the D3D11 texture".to_string(), + ) + })) + } + pub fn build_standalone(self) -> Result { let input_config = self.input_config; let (raw_width, raw_height) = self @@ -1063,6 +1226,8 @@ pub struct H264Encoder { hw_upload: HwUpload, #[cfg(target_os = "macos")] videotoolbox_hw: Option>, + #[cfg(windows)] + d3d11_hw: Option>, software_fallback: Option>, #[cfg(test)] injected_failure: Option, @@ -1111,6 +1276,30 @@ impl H264Encoder { self.videotoolbox_hw.is_some() } + #[cfg(windows)] + pub fn is_d3d11_hw_input(&self) -> bool { + self.d3d11_hw.is_some() + } + + /// # Safety + /// `texture` must be an RGBA `ID3D11Texture2D` on the device this encoder + /// was opened with, at this encoder's width and height. `lifetime.free` + /// runs once when the frame is dropped. + #[cfg(windows)] + pub unsafe fn wrap_d3d11_texture( + &self, + texture: *mut std::ffi::c_void, + lifetime: Option, + ) -> Result { + let hw_frames = self.d3d11_hw.as_ref().ok_or_else(|| { + H264EncoderError::D3d11HwInput( + "encoder was not built for D3D11 texture input".to_string(), + ) + })?; + unsafe { hw_frames.wrap_texture(texture, lifetime) } + .map_err(|error| H264EncoderError::D3d11HwInput(error.to_string())) + } + /// Wraps an IOSurface-backed NV12 `CVPixelBufferRef` as a frame this /// encoder can queue directly. Only available on encoders built with /// [`H264EncoderBuilder::build_videotoolbox_hw_input`]. @@ -1172,6 +1361,10 @@ impl H264Encoder { self.converted_frame_pool = opened.converted_frame_pool; self.output_format = opened.output_format; self.hw_upload = opened.hw_upload; + #[cfg(windows)] + { + self.d3d11_hw = None; + } #[cfg(test)] { self.injected_failure = None; diff --git a/crates/enc-ffmpeg/src/video/mod.rs b/crates/enc-ffmpeg/src/video/mod.rs index c83201a08b4..c0660a0b675 100644 --- a/crates/enc-ffmpeg/src/video/mod.rs +++ b/crates/enc-ffmpeg/src/video/mod.rs @@ -1,6 +1,8 @@ use ffmpeg::frame; pub mod colour; +#[cfg(target_os = "windows")] +mod d3d11_hw; pub mod h264; pub mod h264_packet; pub mod hardware_crash; @@ -10,6 +12,8 @@ mod packed_yuv; pub mod prores; mod rgb_to_yuv; pub mod standin; +#[cfg(target_os = "windows")] +pub use d3d11_hw::D3d11TextureLifetime; #[cfg(target_os = "linux")] pub(crate) mod vaapi; #[cfg(target_os = "macos")] diff --git a/crates/recording/examples/d3d11-texture-encode-benchmark.rs b/crates/recording/examples/d3d11-texture-encode-benchmark.rs new file mode 100644 index 00000000000..6ba8a4740d2 --- /dev/null +++ b/crates/recording/examples/d3d11-texture-encode-benchmark.rs @@ -0,0 +1,513 @@ +//! `cargo run -p cap-recording --example d3d11-texture-encode-benchmark --release` + +#[cfg(not(windows))] +fn main() { + eprintln!("Windows only. Run this on DESKTOP-MQ99RT1."); +} + +#[cfg(windows)] +fn main() { + windows::run(); +} + +#[cfg(windows)] +mod windows { + use std::ffi::c_void; + use std::path::{Path, PathBuf}; + use std::sync::Arc; + use std::sync::atomic::{AtomicU32, Ordering}; + use std::time::{Duration, Instant}; + + use cap_enc_ffmpeg::D3d11TextureLifetime; + use cap_enc_ffmpeg::h264::H264Preset; + use cap_enc_ffmpeg::remux::concatenate_m4s_segments_with_init; + use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig}; + use cap_media_info::{RawVideoFormat, VideoInfo}; + use windows::Win32::Foundation::HMODULE; + use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_HARDWARE; + use windows::Win32::Graphics::Direct3D11::{ + D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_CREATE_DEVICE_BGRA_SUPPORT, + D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, + D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, + ID3D11DeviceContext, ID3D11Multithread, ID3D11Texture2D, + }; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use windows::core::Interface; + + const WARMUP: usize = 30; + const FRAMES: usize = 300; + const RUNS: usize = 5; + const RING: usize = 8; + const SOURCES: usize = 4; + + #[repr(C)] + struct Filetime { + low: u32, + high: u32, + } + + unsafe extern "system" { + fn GetCurrentProcess() -> *mut c_void; + fn GetProcessTimes( + process: *mut c_void, + created: *mut Filetime, + exited: *mut Filetime, + kernel: *mut Filetime, + user: *mut Filetime, + ) -> i32; + } + + fn process_cpu() -> Duration { + let mut created = Filetime { low: 0, high: 0 }; + let mut exited = Filetime { low: 0, high: 0 }; + let mut kernel = Filetime { low: 0, high: 0 }; + let mut user = Filetime { low: 0, high: 0 }; + let ok = unsafe { + GetProcessTimes( + GetCurrentProcess(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; + if ok == 0 { + return Duration::ZERO; + } + let ticks = (u64::from(kernel.high) << 32 | u64::from(kernel.low)) + + (u64::from(user.high) << 32 | u64::from(user.low)); + Duration::from_nanos(ticks.saturating_mul(100)) + } + + fn median(values: &mut [u128]) -> u128 { + values.sort_unstable(); + let mid = values.len() / 2; + if values.len().is_multiple_of(2) { + values[mid - 1].midpoint(values[mid]) + } else { + values[mid] + } + } + + struct Device { + device: ID3D11Device, + context: ID3D11DeviceContext, + } + + fn open_device() -> Device { + let mut device = None; + unsafe { + D3D11CreateDevice( + None, + D3D_DRIVER_TYPE_HARDWARE, + HMODULE::default(), + D3D11_CREATE_DEVICE_BGRA_SUPPORT, + None, + D3D11_SDK_VERSION, + Some(&mut device), + None, + None, + ) + .expect("D3D11CreateDevice"); + } + let device = device.expect("D3D11 device"); + if let Ok(multithread) = device.cast::() { + let _ = unsafe { multithread.SetMultithreadProtected(true) }; + } + let context = unsafe { device.GetImmediateContext() }.expect("immediate context"); + Device { device, context } + } + + fn rgba_texture( + device: &ID3D11Device, + width: u32, + height: u32, + cpu_read: bool, + ) -> ID3D11Texture2D { + 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: if cpu_read { + D3D11_USAGE_STAGING + } else { + D3D11_USAGE_DEFAULT + }, + BindFlags: if cpu_read { + 0 + } else { + (D3D11_BIND_SHADER_RESOURCE.0 | D3D11_BIND_RENDER_TARGET.0) as u32 + }, + CPUAccessFlags: if cpu_read { + windows::Win32::Graphics::Direct3D11::D3D11_CPU_ACCESS_READ.0 as u32 + } else { + 0 + }, + MiscFlags: 0, + }; + let mut texture = None; + unsafe { + device + .CreateTexture2D(&desc, None, Some(&mut texture)) + .expect("CreateTexture2D"); + } + texture.expect("texture") + } + + fn paint(device: &Device, texture: &ID3D11Texture2D, width: u32, height: u32, index: usize) { + let stride = width as usize * 4; + let mut bytes = vec![0u8; stride * height as usize]; + let shift = index * 4; + for row in 0..height as usize { + for col in 0..width as usize { + let pixel = (row * stride) + col * 4; + bytes[pixel] = ((col + shift) % 251) as u8; + bytes[pixel + 1] = ((row + shift) % 251) as u8; + bytes[pixel + 2] = ((row + col + shift) % 251) as u8; + bytes[pixel + 3] = 255; + } + } + unsafe { + device.context.UpdateSubresource( + texture, + 0, + None, + bytes.as_ptr() as *const c_void, + stride as u32, + 0, + ); + } + } + + struct Holds { + counts: Arc<[AtomicU32; RING]>, + index: u32, + } + + unsafe extern "C" fn release_hold(data: *mut c_void) { + let hold = unsafe { Box::from_raw(data as *mut Holds) }; + hold.counts[hold.index as usize].fetch_sub(1, Ordering::AcqRel); + } + + struct Ring { + textures: Vec, + counts: Arc<[AtomicU32; RING]>, + next: usize, + } + + impl Ring { + fn new(device: &ID3D11Device, width: u32, height: u32) -> Self { + let textures = (0..RING) + .map(|_| rgba_texture(device, width, height, false)) + .collect(); + Self { + textures, + counts: Arc::new(std::array::from_fn(|_| AtomicU32::new(0))), + next: 0, + } + } + + fn submit_source( + &mut self, + context: &ID3D11DeviceContext, + source: &ID3D11Texture2D, + ) -> (*mut c_void, D3d11TextureLifetime) { + let mut chosen = None; + for step in 0..RING { + let index = (self.next + step) % RING; + if self.counts[index].load(Ordering::Acquire) == 0 { + chosen = Some(index); + break; + } + } + let index = chosen.expect("texture ring full"); + self.next = (index + 1) % RING; + let dest = &self.textures[index]; + unsafe { context.CopyResource(dest, source) }; + self.counts[index].fetch_add(1, Ordering::AcqRel); + let hold = Box::new(Holds { + counts: Arc::clone(&self.counts), + index: index as u32, + }); + ( + dest.as_raw(), + D3d11TextureLifetime { + data: Box::into_raw(hold) as *mut c_void, + free: release_hold, + }, + ) + } + } + + fn readback( + context: &ID3D11DeviceContext, + source: &ID3D11Texture2D, + staging: &ID3D11Texture2D, + frame: &mut ffmpeg::frame::Video, + width: u32, + height: u32, + ) { + unsafe { + context.CopyResource(staging, source); + let mut mapped = D3D11_MAPPED_SUBRESOURCE::default(); + context + .Map(staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped)) + .expect("Map"); + let src_stride = mapped.RowPitch as usize; + let row_bytes = width as usize * 4; + let dest_stride = frame.stride(0); + let dest = frame.data_mut(0); + for row in 0..height as usize { + dest[row * dest_stride..row * dest_stride + row_bytes].copy_from_slice( + std::slice::from_raw_parts( + (mapped.pData as *const u8).add(row * src_stride), + row_bytes, + ), + ); + } + context.Unmap(staging, 0); + } + } + + struct Run { + wall: Duration, + cpu: Duration, + decoded: usize, + } + + fn decode_count(path: &Path) -> usize { + let mut input = ffmpeg::format::input(path).expect("open assembled output"); + let stream_index = input + .streams() + .best(ffmpeg::media::Type::Video) + .expect("video stream") + .index(); + let params = input.stream(stream_index).unwrap().parameters(); + let context = ffmpeg::codec::context::Context::from_parameters(params).expect("context"); + let mut decoder = context.decoder().video().expect("decoder"); + let mut frame = ffmpeg::frame::Video::empty(); + let mut count = 0usize; + for (stream, packet) in input.packets() { + if stream.index() != stream_index { + continue; + } + if decoder.send_packet(&packet).is_ok() { + while decoder.receive_frame(&mut frame).is_ok() { + count += 1; + } + } + } + if decoder.send_eof().is_ok() { + while decoder.receive_frame(&mut frame).is_ok() { + count += 1; + } + } + count + } + + fn assemble(dir: &Path) -> PathBuf { + let mut segments: Vec = std::fs::read_dir(dir) + .expect("read segment dir") + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path.extension().is_some_and(|ext| ext == "m4s")) + .collect(); + segments.sort(); + assert!(!segments.is_empty(), "no media segments in {dir:?}"); + let output = dir.join("assembled.mp4"); + concatenate_m4s_segments_with_init(&dir.join("init.mp4"), &segments, &output) + .expect("assemble segments"); + output + } + + fn run_readback( + dir: &Path, + device: &Device, + sources: &[ID3D11Texture2D], + staging: &ID3D11Texture2D, + info: VideoInfo, + ) -> Run { + let mut encoder = SegmentedVideoEncoder::init( + dir.to_path_buf(), + info, + SegmentedVideoEncoderConfig { + preset: H264Preset::Ultrafast, + ..Default::default() + }, + ) + .expect("readback encoder"); + let mut reusable = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); + for i in 0..WARMUP { + readback( + &device.context, + &sources[i % SOURCES], + staging, + &mut reusable, + info.width, + info.height, + ); + let mut owned = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); + std::mem::swap(&mut owned, &mut reusable); + encoder + .queue_frame(owned, Duration::from_millis(i as u64 * 33)) + .expect("warmup readback"); + } + let wall_start = Instant::now(); + let cpu_start = process_cpu(); + for i in 0..FRAMES { + let index = WARMUP + i; + readback( + &device.context, + &sources[index % SOURCES], + staging, + &mut reusable, + info.width, + info.height, + ); + let mut owned = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); + std::mem::swap(&mut owned, &mut reusable); + encoder + .queue_frame(owned, Duration::from_millis(index as u64 * 33)) + .expect("readback frame"); + } + let wall = wall_start.elapsed(); + let cpu = process_cpu().saturating_sub(cpu_start); + encoder.finish().expect("finish readback"); + let decoded = decode_count(&assemble(dir)); + Run { wall, cpu, decoded } + } + + fn run_texture( + dir: &Path, + device: &Device, + sources: &[ID3D11Texture2D], + info: VideoInfo, + ) -> Option { + let mut encoder = SegmentedVideoEncoder::init( + dir.to_path_buf(), + info, + SegmentedVideoEncoderConfig { + preset: H264Preset::Ultrafast, + d3d11_device: Some(device.device.as_raw() as usize), + ..Default::default() + }, + ) + .expect("texture encoder"); + if !encoder.is_d3d11_hw_input() { + return None; + } + let mut ring = Ring::new(&device.device, info.width, info.height); + for i in 0..WARMUP { + let (texture, lifetime) = ring.submit_source(&device.context, &sources[i % SOURCES]); + unsafe { + encoder + .queue_d3d11_texture( + texture, + Duration::from_millis(i as u64 * 33), + Some(lifetime), + ) + .expect("warmup texture"); + } + } + let wall_start = Instant::now(); + let cpu_start = process_cpu(); + for i in 0..FRAMES { + let index = WARMUP + i; + let (texture, lifetime) = + ring.submit_source(&device.context, &sources[index % SOURCES]); + unsafe { + encoder + .queue_d3d11_texture( + texture, + Duration::from_millis(index as u64 * 33), + Some(lifetime), + ) + .expect("texture frame"); + } + } + let wall = wall_start.elapsed(); + let cpu = process_cpu().saturating_sub(cpu_start); + encoder.finish().expect("finish texture"); + let decoded = decode_count(&assemble(dir)); + Some(Run { wall, cpu, decoded }) + } + + fn report(label: &str, path: &str, runs: &[Run]) { + let mut wall: Vec = runs.iter().map(|run| run.wall.as_millis()).collect(); + let mut cpu: Vec = runs.iter().map(|run| run.cpu.as_millis()).collect(); + let wall_min = *wall.iter().min().unwrap_or(&0); + let wall_max = *wall.iter().max().unwrap_or(&0); + let cpu_min = *cpu.iter().min().unwrap_or(&0); + let cpu_max = *cpu.iter().max().unwrap_or(&0); + println!( + "{label} {path} wall median {} ms range {wall_min}-{wall_max} cpu median {} ms range {cpu_min}-{cpu_max} decoded {:?}", + median(&mut wall), + median(&mut cpu), + runs.iter().map(|run| run.decoded).collect::>() + ); + } + + pub fn run() { + ffmpeg::init().ok(); + let device = open_device(); + let expected = WARMUP + FRAMES; + let mut failed = false; + println!("frames {FRAMES} warmup {WARMUP} runs {RUNS} expected decoded {expected}"); + for (width, height) in [(1920u32, 1080u32), (3840, 2160)] { + let info = VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, 30); + let sources: Vec<_> = (0..SOURCES) + .map(|index| { + let texture = rgba_texture(&device.device, width, height, false); + paint(&device, &texture, width, height, index); + texture + }) + .collect(); + let staging = rgba_texture(&device.device, width, height, true); + let base = std::env::temp_dir().join(format!("d3d11-texture-bench-{width}x{height}")); + let _ = std::fs::remove_dir_all(&base); + let mut readback_runs = Vec::new(); + let mut texture_runs = Vec::new(); + let mut texture_refused = false; + for run_index in 0..RUNS { + let readback_dir = base.join(format!("readback-{run_index}")); + std::fs::create_dir_all(&readback_dir).expect("readback dir"); + let readback = run_readback(&readback_dir, &device, &sources, &staging, info); + if readback.decoded != expected { + failed = true; + } + readback_runs.push(readback); + + let texture_dir = base.join(format!("texture-{run_index}")); + std::fs::create_dir_all(&texture_dir).expect("texture dir"); + match run_texture(&texture_dir, &device, &sources, info) { + Some(texture) => { + if texture.decoded != expected { + failed = true; + } + texture_runs.push(texture); + } + None => texture_refused = true, + } + } + let label = format!("{width}x{height}"); + report(&label, "readback", &readback_runs); + if texture_refused { + println!("{label} texture refused, CPU frame path stayed in use"); + } else { + report(&label, "texture", &texture_runs); + } + } + if failed { + eprintln!("decoded frame count did not match frames submitted"); + std::process::exit(1); + } + } +} diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs index 48d0ae69e84..b7868a6977b 100644 --- a/crates/recording/src/capture_pipeline.rs +++ b/crates/recording/src/capture_pipeline.rs @@ -286,6 +286,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture { false }; + let d3d_device = screen_capture.d3d_device.clone(); if oop_ok { use crate::output_pipeline::{ WindowsOOPFragmentedM4SMuxer, WindowsOOPFragmentedM4SMuxerConfig, @@ -320,6 +321,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture { shared_pause_state, disk_space_callback: None, segment_tx: None, + d3d_device: Some(d3d_device), }) .await } @@ -356,6 +358,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture { start_gate: Option, segment_tx: Option>, ) -> anyhow::Result { + let d3d_device = screen_capture.d3d_device.clone(); OutputPipeline::builder(segments_dir) .with_video::(screen_capture) .with_timestamps(start_time) @@ -369,6 +372,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture { shared_pause_state: None, disk_space_callback: None, segment_tx, + d3d_device: Some(d3d_device), }) .await } diff --git a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs new file mode 100644 index 00000000000..096a3a8b621 --- /dev/null +++ b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs @@ -0,0 +1,171 @@ +use super::texture_slots::{TEXTURE_RING_CAPACITY, TextureSlots}; +use cap_enc_ffmpeg::D3d11TextureLifetime; +use std::ffi::c_void; +use std::sync::Arc; +use windows::Win32::Graphics::Direct3D11::{ + D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_TEXTURE2D_DESC, + D3D11_USAGE_DEFAULT, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, +}; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; +use windows::core::Interface; + +struct SlotRelease { + slots: Arc, + slot: u32, +} + +unsafe extern "C" fn release_slot(data: *mut c_void) { + let release = unsafe { Box::from_raw(data as *mut SlotRelease) }; + release.slots.release(release.slot); +} + +pub(crate) struct PreparedTexture { + ptr: *mut c_void, + lifetime: Option, +} + +impl PreparedTexture { + pub(crate) fn into_submit(mut self) -> Option<(*mut c_void, D3d11TextureLifetime)> { + let lifetime = self.lifetime.take()?; + let ptr = self.ptr; + std::mem::forget(self); + Some((ptr, lifetime)) + } +} + +impl Drop for PreparedTexture { + fn drop(&mut self) { + if let Some(lifetime) = self.lifetime.take() { + unsafe { (lifetime.free)(lifetime.data) }; + } + } +} + +pub(crate) struct GpuTextureRing { + device: ID3D11Device, + context: ID3D11DeviceContext, + textures: Vec, + slots: Arc, + last: Option, + width: u32, + height: u32, + unusable: bool, +} + +impl GpuTextureRing { + pub(crate) fn new(device: ID3D11Device) -> Option { + let context = unsafe { device.GetImmediateContext() }.ok()?; + Some(Self { + device, + context, + textures: Vec::new(), + slots: Arc::new(TextureSlots::new()), + last: None, + width: 0, + height: 0, + unusable: false, + }) + } + + pub(crate) fn is_unusable(&self) -> bool { + self.unusable + } + + pub(crate) fn copy_from( + &mut self, + src: &ID3D11Texture2D, + width: u32, + height: u32, + ) -> Option { + if self.unusable + || width == 0 + || height == 0 + || !width.is_multiple_of(2) + || !height.is_multiple_of(2) + { + self.unusable = true; + return None; + } + let mut desc = D3D11_TEXTURE2D_DESC::default(); + unsafe { src.GetDesc(&mut desc) }; + if desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM || desc.Width != width || desc.Height != height + { + self.unusable = true; + return None; + } + if self.width != 0 && (self.width != width || self.height != height) { + self.unusable = true; + return None; + } + if self.textures.is_empty() && self.allocate(width, height).is_none() { + self.unusable = true; + return None; + } + let slot = self.slots.try_acquire()?; + let dest = self.textures.get(slot as usize)?; + unsafe { + self.context.CopyResource(dest, src); + self.context.Flush(); + } + if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { + self.unusable = true; + return None; + } + self.slots.hold(slot); + self.last = Some(slot); + Some(self.prepared(slot, dest)) + } + + pub(crate) fn repeat_last(&mut self) -> Option { + let slot = self.last?; + let texture = self.textures.get(slot as usize)?; + self.slots.hold(slot); + Some(self.prepared(slot, texture)) + } + + fn allocate(&mut self, width: u32, height: u32) -> Option<()> { + 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_SHADER_RESOURCE.0 | D3D11_BIND_RENDER_TARGET.0) as u32, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let mut textures = Vec::with_capacity(TEXTURE_RING_CAPACITY as usize); + for _ in 0..TEXTURE_RING_CAPACITY { + let mut texture = None; + unsafe { + self.device + .CreateTexture2D(&desc, None, Some(&mut texture)) + .ok()?; + } + textures.push(texture?); + } + self.textures = textures; + self.width = width; + self.height = height; + Some(()) + } + + fn prepared(&self, slot: u32, texture: &ID3D11Texture2D) -> PreparedTexture { + let release = Box::new(SlotRelease { + slots: Arc::clone(&self.slots), + slot, + }); + PreparedTexture { + ptr: texture.as_raw(), + lifetime: Some(D3d11TextureLifetime { + data: Box::into_raw(release) as *mut c_void, + free: release_slot, + }), + } + } +} diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rs index 8a10285e247..bc13f9f10a6 100644 --- a/crates/recording/src/output_pipeline/ffmpeg.rs +++ b/crates/recording/src/output_pipeline/ffmpeg.rs @@ -690,6 +690,7 @@ impl SegmentedVideoMuxer { bpp: H264EncoderBuilder::QUALITY_BPP, output_size: self.output_size, prefer_videotoolbox_hw_input: false, + d3d11_device: None, }; let slow_threshold_ms = frame_timing_log_threshold_ms(&self.video_config); diff --git a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs index 0d62519099b..4833b88d0e5 100644 --- a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs @@ -368,6 +368,7 @@ impl MacOSFragmentedM4SMuxer { bpp: self.bpp, output_size: self.output_size, prefer_videotoolbox_hw_input: true, + d3d11_device: None, }; let mut encoder = SegmentedVideoEncoder::init_write_behind( @@ -771,6 +772,7 @@ impl MacOSFragmentedM4SCameraMuxer { bpp: self.bpp, output_size: self.output_size, prefer_videotoolbox_hw_input: false, + d3d11_device: None, }; let mut encoder = SegmentedVideoEncoder::init_write_behind( diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rs index 25ecb5c52aa..02cb29962c5 100644 --- a/crates/recording/src/output_pipeline/mod.rs +++ b/crates/recording/src/output_pipeline/mod.rs @@ -1,5 +1,7 @@ mod async_camera; mod core; +#[cfg(windows)] +mod d3d11_texture_ring; pub mod ffmpeg; #[cfg(any(windows, test))] mod frame_pacing; @@ -13,6 +15,8 @@ mod mjpeg; mod oop_fragmented_m4s; pub mod oop_muxer; mod start_gate; +#[cfg(any(windows, test))] +mod texture_slots; pub use async_camera::*; pub use core::*; diff --git a/crates/recording/src/output_pipeline/texture_slots.rs b/crates/recording/src/output_pipeline/texture_slots.rs new file mode 100644 index 00000000000..6bd9331bf48 --- /dev/null +++ b/crates/recording/src/output_pipeline/texture_slots.rs @@ -0,0 +1,103 @@ +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Duration; + +pub(crate) const TEXTURE_RING_CAPACITY: u32 = 8; + +/// How many encoder frames still reference each copied texture. +/// +/// The encode thread is the only caller of `try_acquire` and `hold`. The +/// frame's release callback may run on another thread, and it only calls +/// `release`. +pub(crate) struct TextureSlots { + holds: [AtomicU32; TEXTURE_RING_CAPACITY as usize], +} + +impl TextureSlots { + pub(crate) fn new() -> Self { + Self { + holds: std::array::from_fn(|_| AtomicU32::new(0)), + } + } + + /// The first slot no frame still references. The caller must `hold` it + /// before the next acquire, or this returns the same slot again. + pub(crate) fn try_acquire(&self) -> Option { + (0..TEXTURE_RING_CAPACITY) + .find(|&slot| self.holds[slot as usize].load(Ordering::Acquire) == 0) + } + + pub(crate) fn hold(&self, slot: u32) { + self.holds[slot as usize].fetch_add(1, Ordering::AcqRel); + } + + pub(crate) fn release(&self, slot: u32) { + self.holds[slot as usize].fetch_sub(1, Ordering::AcqRel); + } +} + +pub(crate) fn offset_from_first(ts: Duration, first: &mut Option) -> Duration { + if let Some(first_ts) = *first { + ts.checked_sub(first_ts).unwrap_or(Duration::ZERO) + } else { + *first = Some(ts); + Duration::ZERO + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn acquire_skips_held_slots_and_reuses_a_released_one() { + let slots = TextureSlots::new(); + assert_eq!(slots.try_acquire(), Some(0)); + slots.hold(0); + assert_eq!(slots.try_acquire(), Some(1)); + slots.hold(1); + slots.release(0); + assert_eq!(slots.try_acquire(), Some(0)); + } + + #[test] + fn a_slot_with_two_holds_stays_busy_until_both_release() { + let slots = TextureSlots::new(); + for slot in 0..3 { + slots.hold(slot); + } + slots.hold(3); + slots.hold(3); + assert_ne!(slots.try_acquire(), Some(3)); + slots.release(3); + assert_ne!(slots.try_acquire(), Some(3)); + slots.release(3); + assert_eq!(slots.try_acquire(), Some(3)); + } + + #[test] + fn a_full_ring_has_no_free_slot() { + let slots = TextureSlots::new(); + for slot in 0..TEXTURE_RING_CAPACITY { + slots.hold(slot); + } + assert_eq!(slots.try_acquire(), None); + slots.release(5); + assert_eq!(slots.try_acquire(), Some(5)); + } + + #[test] + fn timestamps_start_at_zero_and_keep_later_offsets() { + let mut first = None; + let start = Duration::from_millis(5_000); + assert_eq!(offset_from_first(start, &mut first), Duration::ZERO); + assert_eq!( + offset_from_first(start + Duration::from_millis(16), &mut first), + Duration::from_millis(16) + ); + assert_eq!( + offset_from_first(start - Duration::from_millis(1), &mut first), + Duration::ZERO + ); + assert_eq!(first, Some(start)); + } +} diff --git a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs index 62c80496c58..1ba00586ca3 100644 --- a/crates/recording/src/output_pipeline/win_fragmented_m4s.rs +++ b/crates/recording/src/output_pipeline/win_fragmented_m4s.rs @@ -281,6 +281,7 @@ pub struct WindowsFragmentedM4SMuxer { timed_fragments: bool, base_path: PathBuf, video_config: VideoInfo, + d3d_device: Option, segment_duration: Duration, preset: H264Preset, bpp: f32, @@ -305,6 +306,7 @@ pub struct WindowsFragmentedM4SMuxerConfig { pub disk_space_callback: Option, pub segment_tx: Option>, + pub d3d_device: Option, } impl Default for WindowsFragmentedM4SMuxerConfig { @@ -318,6 +320,7 @@ impl Default for WindowsFragmentedM4SMuxerConfig { shared_pause_state: None, disk_space_callback: None, segment_tx: None, + d3d_device: None, } } } @@ -364,6 +367,7 @@ impl Muxer for WindowsFragmentedM4SMuxer { disk_space_callback: config.disk_space_callback, segment_tx: config.segment_tx, health_tx: SharedHealthSender::new(), + d3d_device: config.d3d_device, }; muxer.start_encoder()?; @@ -413,12 +417,18 @@ impl WindowsFragmentedM4SMuxer { sync_channel::>(buffer_size); let (ready_tx, ready_rx) = sync_channel::>(1); + let d3d11_device = self + .d3d_device + .as_ref() + .map(windows::core::Interface::as_raw) + .map(|ptr| ptr as usize); let encoder_config = SegmentedVideoEncoderConfig { segment_duration: self.segment_duration, preset: self.preset, bpp: self.bpp, output_size: self.output_size, prefer_videotoolbox_hw_input: false, + d3d11_device, }; let mut encoder = SegmentedVideoEncoder::init_with_timed_fragments( @@ -427,6 +437,9 @@ impl WindowsFragmentedM4SMuxer { encoder_config, self.timed_fragments, )?; + if encoder.is_d3d11_hw_input() { + info!("Windows M4S screen encoder is taking D3D11 textures"); + } if let Some(callback) = &self.disk_space_callback { encoder.set_disk_space_callback(callback.clone()); } @@ -440,6 +453,7 @@ impl WindowsFragmentedM4SMuxer { let health_tx = self.health_tx.clone(); let base_path = self.base_path.clone(); let pause_flag = self.pause.flag(); + let texture_device = self.d3d_device.clone(); let encoder_handle = std::thread::Builder::new() .name("win-m4s-segment-encoder".to_string()) .spawn(move || { @@ -452,6 +466,8 @@ impl WindowsFragmentedM4SMuxer { let mut pacer = FramePacer::new(video_config.fps()); let mut last_ffmpeg_frame: Option = None; let mut first_timestamp: Option = None; + let mut gpu_ring = + texture_device.and_then(super::d3d11_texture_ring::GpuTextureRing::new); let mut slow_convert_count = 0u32; let mut slow_encode_count = 0u32; @@ -466,15 +482,7 @@ impl WindowsFragmentedM4SMuxer { "encoder:windows-fragmented", )); - let normalize_timestamp = - |ts: Duration, first: &mut Option| -> Duration { - if let Some(first_ts) = *first { - ts.checked_sub(first_ts).unwrap_or(Duration::ZERO) - } else { - *first = Some(ts); - Duration::ZERO - } - }; + let normalize_timestamp = super::texture_slots::offset_from_first; let encode_frame_fn = |ffmpeg_frame: ffmpeg::frame::Video, timestamp: Duration, @@ -523,6 +531,80 @@ impl WindowsFragmentedM4SMuxer { Ok(()) }; + let encode_texture_fn = |prepared: super::d3d11_texture_ring::PreparedTexture, + timestamp: Duration, + slow_encode_count: &mut u32, + total_frames: &mut u64, + encoder: &Arc>| + -> anyhow::Result<()> { + let Some((texture, lifetime)) = prepared.into_submit() else { + return Ok(()); + }; + let encode_start = std::time::Instant::now(); + let encoded = match encoder.lock() { + Ok(mut enc) => { + let result = unsafe { + enc.queue_d3d11_texture(texture, timestamp, Some(lifetime)) + }; + report_encode_result( + &mut enc, + result, + &encode_failures, + &encode_drops, + &health_tx, + "screen", + ) + } + Err(_) => { + return Err(anyhow!( + "Encoder mutex poisoned - all subsequent frames would be lost" + )); + } + }; + let encode_elapsed_ms = encode_start.elapsed().as_millis(); + if encode_elapsed_ms > SLOW_THRESHOLD_MS { + *slow_encode_count += 1; + if *slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) { + debug!( + elapsed_ms = encode_elapsed_ms, + count = *slow_encode_count, + "encoder.queue_d3d11_texture exceeded {}ms threshold", + SLOW_THRESHOLD_MS + ); + } + } + if encoded { + *total_frames += 1; + } + Ok(()) + }; + + enum ScreenSubmit { + Cpu(ffmpeg::frame::Video), + Gpu(super::d3d11_texture_ring::PreparedTexture), + } + + let cpu_screen_frame = |frame: &screen_capture::ScreenFrame, + ts: Duration, + last_ffmpeg_frame: &mut Option, + duplicated_frames: &mut u64| + -> Option<(ScreenSubmit, Duration)> { + match frame.as_ffmpeg() { + Ok(frame) => { + *last_ffmpeg_frame = Some(reference_video_frame(&frame)); + Some((ScreenSubmit::Cpu(frame), ts)) + } + Err(error) => { + warn!("Failed to convert D3D11 frame: {error:?}"); + *duplicated_frames += 1; + last_ffmpeg_frame + .as_ref() + .map(reference_video_frame) + .map(|frame| (ScreenSubmit::Cpu(frame), ts)) + } + } + }; + loop { if matches!( disk_monitor.poll(&base_path, &health_tx), @@ -536,25 +618,74 @@ impl WindowsFragmentedM4SMuxer { } let convert_start = std::time::Instant::now(); + let mut texture_ready = encoder_clone + .lock() + .is_ok_and(|encoder| encoder.is_d3d11_hw_input()); - let (ffmpeg_frame, timestamp) = match pacer.next(&video_rx, &pause_flag) { - Paced::Frame(frame, ts) => match frame.as_ffmpeg() { - Ok(f) => { - last_ffmpeg_frame = Some(reference_video_frame(&f)); - (Some(f), ts) - } - Err(e) => { - warn!("Failed to convert D3D11 frame: {e:?}"); - duplicated_frames += 1; - (last_ffmpeg_frame.as_ref().map(reference_video_frame), ts) + let submission = match pacer.next(&video_rx, &pause_flag) { + Paced::Frame(frame, ts) => { + if texture_ready { + let prepared = gpu_ring.as_mut().and_then(|ring| { + ring.copy_from(frame.texture(), frame.width(), frame.height()) + }); + if let Some(prepared) = prepared { + Some((ScreenSubmit::Gpu(prepared), ts)) + } else if gpu_ring.as_ref().is_none_or(|ring| ring.is_unusable()) { + if encoder_clone + .lock() + .is_ok_and(|mut encoder| encoder.abandon_d3d11_input()) + { + cpu_screen_frame( + &frame, + ts, + &mut last_ffmpeg_frame, + &mut duplicated_frames, + ) + } else { + warn!("D3D11 texture path could not switch to CPU frames"); + duplicated_frames += 1; + None + } + } else { + warn!("D3D11 texture ring is full; dropping this screen frame"); + duplicated_frames += 1; + None + } + } else { + cpu_screen_frame( + &frame, + ts, + &mut last_ffmpeg_frame, + &mut duplicated_frames, + ) } - }, + } Paced::Repeat(ts) => { - let Some(f) = &last_ffmpeg_frame else { + let texture_repeat = texture_ready + && gpu_ring.as_ref().is_some_and(|ring| !ring.is_unusable()); + if texture_repeat + && let Some(prepared) = + gpu_ring.as_mut().and_then(|ring| ring.repeat_last()) + { + duplicated_frames += 1; + Some((ScreenSubmit::Gpu(prepared), ts)) + } else if texture_repeat { continue; - }; - duplicated_frames += 1; - (Some(reference_video_frame(f)), ts) + } else { + if texture_ready { + let left = encoder_clone + .lock() + .is_ok_and(|mut encoder| encoder.abandon_d3d11_input()); + if !left { + continue; + } + } + let Some(frame) = &last_ffmpeg_frame else { + continue; + }; + duplicated_frames += 1; + Some((ScreenSubmit::Cpu(reference_video_frame(frame)), ts)) + } } Paced::End => { let mut drained = 0u64; @@ -564,20 +695,58 @@ impl WindowsFragmentedM4SMuxer { loop { match video_rx.recv_timeout(Duration::from_millis(10)) { Ok(Some((frame, ts))) => { - if let Ok(f) = frame.as_ffmpeg() { - let normalized_ts = - normalize_timestamp(ts, &mut first_timestamp); - if let Err(e) = encode_frame_fn( - f, + let normalized_ts = + normalize_timestamp(ts, &mut first_timestamp); + let gpu = if texture_ready { + gpu_ring.as_mut().and_then(|ring| { + ring.copy_from( + frame.texture(), + frame.width(), + frame.height(), + ) + }) + } else { + None + }; + if texture_ready + && gpu.is_none() + && gpu_ring + .as_ref() + .is_none_or(|ring| ring.is_unusable()) + && encoder_clone.lock().is_ok_and(|mut encoder| { + encoder.abandon_d3d11_input() + }) + { + texture_ready = false; + } + let encoded = if let Some(prepared) = gpu { + Some(encode_texture_fn( + prepared, normalized_ts, &mut slow_encode_count, &mut total_frames, &encoder_clone, - ) { - warn!("Failed to encode drained frame: {e}"); + )) + } else if !texture_ready { + frame.as_ffmpeg().ok().map(|frame| { + encode_frame_fn( + frame, + normalized_ts, + &mut slow_encode_count, + &mut total_frames, + &encoder_clone, + ) + }) + } else { + None + }; + match encoded { + Some(Err(error)) => { + warn!("Failed to encode drained frame: {error}"); break; } - drained += 1; + Some(Ok(())) => drained += 1, + None => {} } } Ok(None) => break, @@ -599,7 +768,7 @@ impl WindowsFragmentedM4SMuxer { let convert_elapsed_ms = convert_start.elapsed().as_millis(); - let Some(ffmpeg_frame) = ffmpeg_frame else { + let Some((submission, timestamp)) = submission else { continue; }; @@ -616,15 +785,25 @@ impl WindowsFragmentedM4SMuxer { } let normalized_ts = normalize_timestamp(timestamp, &mut first_timestamp); - if let Err(e) = encode_frame_fn( - ffmpeg_frame, - normalized_ts, - &mut slow_encode_count, - &mut total_frames, - &encoder_clone, - ) { + let encoded = match submission { + ScreenSubmit::Cpu(frame) => encode_frame_fn( + frame, + normalized_ts, + &mut slow_encode_count, + &mut total_frames, + &encoder_clone, + ), + ScreenSubmit::Gpu(prepared) => encode_texture_fn( + prepared, + normalized_ts, + &mut slow_encode_count, + &mut total_frames, + &encoder_clone, + ), + }; + if let Err(error) = encoded { error!("Encoder mutex poisoned - encoder thread likely panicked, stopping"); - return Err(e); + return Err(error); } } @@ -884,6 +1063,7 @@ impl WindowsFragmentedM4SCameraMuxer { bpp: self.bpp, output_size: self.output_size, prefer_videotoolbox_hw_input: false, + d3d11_device: None, }; let mut encoder = SegmentedVideoEncoder::init_with_timed_fragments( @@ -931,15 +1111,7 @@ impl WindowsFragmentedM4SCameraMuxer { "encoder:windows-fragmented-camera", )); - let normalize_timestamp = - |ts: Duration, first: &mut Option| -> Duration { - if let Some(first_ts) = *first { - ts.checked_sub(first_ts).unwrap_or(Duration::ZERO) - } else { - *first = Some(ts); - Duration::ZERO - } - }; + let normalize_timestamp = super::texture_slots::offset_from_first; let encode_camera_frame_fn = |camera_frame: &NativeCameraFrame, From b6c30105340f0a5eb765d42c0e37f7841fa70e57 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:00:00 +0000 Subject: [PATCH 2/4] fix(recording): encode D3D11 textures as NV12 FFmpeg 7.1 rejects an RGBA D3D11 frames context, and h264_amf rejects BGRA. The texture path now creates NV12 frames, converts RGBA or BGRA capture on the GPU with BT.709 studio color, and keeps the CPU fallback. QSV is opened from a derived QSV context when the device can build one. The bench prints the adapter, the encoder that opened, the sw_format, and the AVERROR string when the texture path is refused. Co-authored-by: Kyzer --- crates/enc-ffmpeg/src/lib.rs | 2 + crates/enc-ffmpeg/src/mux/segmented_stream.rs | 26 +- crates/enc-ffmpeg/src/video/d3d11_format.rs | 111 ++++++ crates/enc-ffmpeg/src/video/d3d11_hw.rs | 123 +++++- crates/enc-ffmpeg/src/video/h264.rs | 71 +++- crates/enc-ffmpeg/src/video/mod.rs | 2 + crates/recording/Cargo.toml | 1 + .../d3d11-texture-encode-benchmark.rs | 151 ++++--- .../src/output_pipeline/d3d11_texture_ring.rs | 373 +++++++++++++++--- crates/recording/src/output_pipeline/mod.rs | 2 + 10 files changed, 695 insertions(+), 167 deletions(-) create mode 100644 crates/enc-ffmpeg/src/video/d3d11_format.rs diff --git a/crates/enc-ffmpeg/src/lib.rs b/crates/enc-ffmpeg/src/lib.rs index 7e2c0c2060c..24c8ebb5cf1 100644 --- a/crates/enc-ffmpeg/src/lib.rs +++ b/crates/enc-ffmpeg/src/lib.rs @@ -8,6 +8,8 @@ mod audio; pub use audio::*; mod video; +#[cfg(any(windows, test))] +pub use video::d3d11_format::capture_texel_feeds_nv12; pub use video::*; mod mux; diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 0249b584ada..14dc39df926 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -192,6 +192,8 @@ pub struct SegmentedVideoEncoder { pending_fallback: Option, unrecovered_codec_failure: Option<(String, ffmpeg::Error)>, flush_failure: Option, + #[cfg(windows)] + d3d11_status: String, } struct SegmentMux { @@ -466,21 +468,24 @@ impl SegmentedVideoEncoder { None }; #[cfg(target_os = "windows")] - let hw_attempt = match config.d3d11_device { + let (hw_attempt, d3d11_status) = match config.d3d11_device { Some(device) => { let device = device as *mut std::ffi::c_void; match unsafe { builder.clone().build_d3d11_hw_input(&mut output, device) } { - Ok(encoder) => Some(encoder), + Ok(encoder) => { + let status = encoder.d3d11_sw_format_name().unwrap_or("nv12").to_string(); + (Some(encoder), status) + } Err(error) => { tracing::info!( %error, "D3D11 texture input unavailable, using the CPU frame path" ); - None + (None, error.to_string()) } } } - None => None, + None => (None, String::new()), }; #[cfg(not(any(target_os = "macos", target_os = "windows")))] let hw_attempt: Option = None; @@ -547,6 +552,8 @@ impl SegmentedVideoEncoder { pending_fallback: None, unrecovered_codec_failure: None, flush_failure: None, + #[cfg(windows)] + d3d11_status, }; if write_behind { @@ -608,6 +615,15 @@ impl SegmentedVideoEncoder { self.encoder.is_d3d11_hw_input() } + #[cfg(windows)] + pub fn d3d11_status(&self) -> &str { + &self.d3d11_status + } + + pub fn codec_name(&self) -> String { + self.encoder.codec_name() + } + #[cfg(windows)] pub fn abandon_d3d11_input(&mut self) -> bool { if !self.encoder.is_d3d11_hw_input() { @@ -626,7 +642,7 @@ impl SegmentedVideoEncoder { } /// # Safety - /// `texture` must be an RGBA texture on the device passed at init, at the + /// `texture` must be an NV12 texture on the device passed at init, at the /// encoder's width and height. `lifetime.free` runs once when the queued /// frame is dropped. #[cfg(windows)] diff --git a/crates/enc-ffmpeg/src/video/d3d11_format.rs b/crates/enc-ffmpeg/src/video/d3d11_format.rs new file mode 100644 index 00000000000..1a5182da7fd --- /dev/null +++ b/crates/enc-ffmpeg/src/video/d3d11_format.rs @@ -0,0 +1,111 @@ +//! Which D3D11 `sw_format` FFmpeg 7.1 will actually encode. +//! +//! `hwcontext_d3d11va.c` `supported_formats` accepts NV12 and BGRA and rejects +//! RGBA (`Unsupported pixel format`). `amfenc.c` `format_map` accepts NV12 and +//! has `BGR0`, not `BGRA`, so a BGRA frames context fails with +//! `Format of input frames context (bgra) is not supported by AMF`. +//! `ff_nvenc_pix_fmts` includes `AV_PIX_FMT_D3D11` and maps NV12 through. +//! `qsvenc_h264.c` lists only NV12 and QSV, so QSV is a derived `AV_PIX_FMT_QSV` +//! context on those same NV12 frames. `mfenc.c` lists NV12 and YUV420P and is +//! not a D3D11 texture input. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum D3d11SwFormat { + Nv12, +} + +impl D3d11SwFormat { + pub fn name(self) -> &'static str { + match self { + Self::Nv12 => "nv12", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum D3d11TexturePath { + D3d11Nv12, + QsvFromD3d11Nv12, +} + +pub fn d3d11_texture_path(encoder: &str) -> Option { + match encoder { + "h264_amf" | "hevc_amf" | "av1_amf" | "h264_nvenc" | "hevc_nvenc" | "av1_nvenc" => { + Some(D3d11TexturePath::D3d11Nv12) + } + "h264_qsv" | "hevc_qsv" | "av1_qsv" => Some(D3d11TexturePath::QsvFromD3d11Nv12), + _ => None, + } +} + +pub fn d3d11_sw_format(encoder: &str) -> Option { + d3d11_texture_path(encoder).map(|_| D3d11SwFormat::Nv12) +} + +pub fn shared_d3d11_sw_format(encoders: &[&str]) -> Option { + let mut chosen = None; + for encoder in encoders { + let format = d3d11_sw_format(encoder)?; + match chosen { + None => chosen = Some(format), + Some(existing) if existing == format => {} + Some(_) => return None, + } + } + chosen +} + +pub fn capture_texel_feeds_nv12(format_name: &str) -> bool { + matches!(format_name, "rgba" | "bgra" | "nv12") +} + +pub const H264_TEXTURE_ENCODERS: &[&str] = &["h264_amf", "h264_nvenc", "h264_qsv"]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn amf_and_nvenc_share_nv12_and_reject_rgba_and_bgra() { + assert_eq!(D3d11SwFormat::Nv12.name(), "nv12"); + assert_eq!(d3d11_sw_format("h264_amf"), Some(D3d11SwFormat::Nv12)); + assert_eq!(d3d11_sw_format("hevc_amf"), Some(D3d11SwFormat::Nv12)); + assert_eq!(d3d11_sw_format("av1_amf"), Some(D3d11SwFormat::Nv12)); + assert_eq!( + d3d11_texture_path("h264_nvenc"), + Some(D3d11TexturePath::D3d11Nv12) + ); + assert_eq!( + d3d11_texture_path("hevc_nvenc"), + Some(D3d11TexturePath::D3d11Nv12) + ); + assert_eq!(d3d11_sw_format("rgba"), None); + assert_eq!(d3d11_sw_format("bgra"), None); + assert_eq!( + shared_d3d11_sw_format(H264_TEXTURE_ENCODERS), + Some(D3d11SwFormat::Nv12) + ); + } + + #[test] + fn qsv_derives_from_nv12_and_mf_and_libx264_stay_off_the_texture_path() { + assert_eq!( + d3d11_texture_path("h264_qsv"), + Some(D3d11TexturePath::QsvFromD3d11Nv12) + ); + assert_eq!(d3d11_sw_format("hevc_qsv"), Some(D3d11SwFormat::Nv12)); + assert_eq!(d3d11_texture_path("h264_mf"), None); + assert_eq!(d3d11_texture_path("hevc_mf"), None); + assert_eq!(d3d11_texture_path("libx264"), None); + assert_eq!(shared_d3d11_sw_format(&["h264_amf", "libx264"]), None); + } + + #[test] + fn rgba_and_bgra_capture_convert_to_nv12() { + assert!(capture_texel_feeds_nv12("rgba")); + assert!(capture_texel_feeds_nv12("bgra")); + assert!(capture_texel_feeds_nv12("nv12")); + assert!(!capture_texel_feeds_nv12("rgba64")); + assert!(!capture_texel_feeds_nv12("other")); + } +} diff --git a/crates/enc-ffmpeg/src/video/d3d11_hw.rs b/crates/enc-ffmpeg/src/video/d3d11_hw.rs index d4c93ae95ba..f4c6f6bafc4 100644 --- a/crates/enc-ffmpeg/src/video/d3d11_hw.rs +++ b/crates/enc-ffmpeg/src/video/d3d11_hw.rs @@ -6,12 +6,17 @@ use std::ffi::c_void; use std::ptr::null_mut; use ffmpeg::sys::{ - AVBufferRef, AVCodecContext, AVHWDeviceContext, AVHWDeviceType, AVHWFramesContext, - AVPixelFormat, av_buffer_create, av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_alloc, - av_hwdevice_ctx_init, av_hwframe_ctx_alloc, av_hwframe_ctx_init, + AV_HWFRAME_MAP_READ, AVBufferRef, AVCodecContext, AVHWDeviceContext, AVHWDeviceType, + AVHWFramesContext, AVPixelFormat, av_buffer_create, av_buffer_ref, av_buffer_unref, + av_hwdevice_ctx_alloc, av_hwdevice_ctx_create_derived, av_hwdevice_ctx_init, + av_hwframe_ctx_alloc, av_hwframe_ctx_create_derived, av_hwframe_ctx_init, av_hwframe_map, }; use windows::core::{IUnknown, Interface}; +use super::d3d11_format::{ + D3d11SwFormat, D3d11TexturePath, H264_TEXTURE_ENCODERS, shared_d3d11_sw_format, +}; + const BIND_SHADER_RESOURCE: u32 = 0x8; const BIND_RENDER_TARGET: u32 = 0x20; const BIND_VIDEO_ENCODER: u32 = 0x400; @@ -27,12 +32,16 @@ struct D3d11FramesHwctx { pub enum D3d11HwError { #[error("Failed to create a D3D11 hardware device context")] DeviceCreation, + #[error("D3D11 device context: {0}")] + DeviceInit(String), #[error("Failed to allocate a D3D11 hardware frames context")] FramesAllocation, - #[error("Failed to initialize a D3D11 hardware frames context: {0}")] - FramesInit(i32), + #[error("D3D11 frames context: {0}")] + FramesInit(String), #[error("Failed to wrap a D3D11 texture into an AVFrame")] FrameWrap, + #[error("D3D11 frame map: {0}")] + FrameMap(String), } pub struct D3d11TextureLifetime { @@ -48,10 +57,15 @@ struct ExtraRelease { pub(crate) struct D3d11HwFrames { device_ctx: *mut AVBufferRef, frames_ctx: *mut AVBufferRef, + qsv_frames: *mut AVBufferRef, width: u32, height: u32, } +fn av_error(code: i32) -> String { + format!("{} ({code})", ffmpeg::Error::from(code)) +} + unsafe impl Send for D3d11HwFrames {} unsafe impl Sync for D3d11HwFrames {} @@ -115,10 +129,11 @@ impl D3d11HwFrames { return Err(D3d11HwError::DeviceCreation); } *d3d_device = add_ref(device); - if av_hwdevice_ctx_init(device_ctx) < 0 { + let device_init = av_hwdevice_ctx_init(device_ctx); + if device_init < 0 { let mut device_ctx = device_ctx; av_buffer_unref(&mut device_ctx); - return Err(D3d11HwError::DeviceCreation); + return Err(D3d11HwError::DeviceInit(av_error(device_init))); } let frames_ctx = av_hwframe_ctx_alloc(device_ctx); @@ -128,9 +143,13 @@ impl D3d11HwFrames { return Err(D3d11HwError::FramesAllocation); } + let sw_format = shared_d3d11_sw_format(H264_TEXTURE_ENCODERS) + .ok_or_else(|| D3d11HwError::FramesInit("no shared NV12 sw_format".to_string()))?; let ctx = (*frames_ctx).data as *mut AVHWFramesContext; (*ctx).format = AVPixelFormat::AV_PIX_FMT_D3D11; - (*ctx).sw_format = AVPixelFormat::AV_PIX_FMT_RGBA; + (*ctx).sw_format = match sw_format { + D3d11SwFormat::Nv12 => AVPixelFormat::AV_PIX_FMT_NV12, + }; (*ctx).width = width as i32; (*ctx).height = height as i32; (*ctx).initial_pool_size = 0; @@ -146,12 +165,13 @@ impl D3d11HwFrames { av_buffer_unref(&mut frames_ctx); let mut device_ctx = device_ctx; av_buffer_unref(&mut device_ctx); - return Err(D3d11HwError::FramesInit(init_result)); + return Err(D3d11HwError::FramesInit(av_error(init_result))); } Ok(Self { device_ctx, frames_ctx, + qsv_frames: null_mut(), width, height, }) @@ -160,15 +180,73 @@ impl D3d11HwFrames { /// # Safety /// `encoder_ctx` must be a valid, not-yet-opened `AVCodecContext`. - pub(crate) unsafe fn attach_to_encoder(&self, encoder_ctx: *mut AVCodecContext) { + /// `frames` must be the D3D11 frames context or a QSV context derived from it. + pub(crate) unsafe fn attach_frames( + &self, + encoder_ctx: *mut AVCodecContext, + frames: *mut AVBufferRef, + ) { unsafe { - (*encoder_ctx).hw_frames_ctx = av_buffer_ref(self.frames_ctx); + (*encoder_ctx).hw_frames_ctx = av_buffer_ref(frames); } } /// # Safety - /// `texture` must be a 2D `ID3D11Texture2D` on this device, RGBA - /// (`DXGI_FORMAT_R8G8B8A8_UNORM`), matching `width` and `height`. + /// Called only while this value is still owned by the opening thread. + pub(crate) unsafe fn frames_for( + &mut self, + path: D3d11TexturePath, + ) -> Result<*mut AVBufferRef, D3d11HwError> { + match path { + D3d11TexturePath::D3d11Nv12 => Ok(self.frames_ctx), + D3d11TexturePath::QsvFromD3d11Nv12 => { + unsafe { self.derive_qsv() }?; + Ok(self.qsv_frames) + } + } + } + + pub(crate) fn clear_qsv(&mut self) { + if !self.qsv_frames.is_null() { + unsafe { av_buffer_unref(&mut self.qsv_frames) }; + } + } + + unsafe fn derive_qsv(&mut self) -> Result<(), D3d11HwError> { + if !self.qsv_frames.is_null() { + return Ok(()); + } + unsafe { + let mut device = null_mut(); + let device_result = av_hwdevice_ctx_create_derived( + &mut device, + AVHWDeviceType::AV_HWDEVICE_TYPE_QSV, + self.device_ctx, + 0, + ); + if device_result < 0 { + return Err(D3d11HwError::FramesInit(av_error(device_result))); + } + let mut frames = null_mut(); + let frames_result = av_hwframe_ctx_create_derived( + &mut frames, + AVPixelFormat::AV_PIX_FMT_QSV, + device, + self.frames_ctx, + AV_HWFRAME_MAP_READ as i32, + ); + av_buffer_unref(&mut device); + if frames_result < 0 { + return Err(D3d11HwError::FramesInit(av_error(frames_result))); + } + self.qsv_frames = frames; + Ok(()) + } + } + + /// # Safety + /// `texture` must be a 2D `ID3D11Texture2D` on this device, NV12 + /// (`DXGI_FORMAT_NV12`), matching `width` and `height`. /// `lifetime.free` runs once, on whichever thread drops the frame. pub(crate) unsafe fn wrap_texture( &self, @@ -209,14 +287,31 @@ impl D3d11HwFrames { if (*ptr).hw_frames_ctx.is_null() { return Err(D3d11HwError::FrameWrap); } + if self.qsv_frames.is_null() { + return Ok(frame); + } + let mut mapped = ffmpeg::frame::Video::empty(); + let dst = mapped.as_mut_ptr(); + (*dst).format = AVPixelFormat::AV_PIX_FMT_QSV as i32; + (*dst).hw_frames_ctx = av_buffer_ref(self.qsv_frames); + if (*dst).hw_frames_ctx.is_null() { + return Err(D3d11HwError::FrameWrap); + } + let map_result = av_hwframe_map(dst, frame.as_ptr(), AV_HWFRAME_MAP_READ as i32); + if map_result < 0 { + return Err(D3d11HwError::FrameMap(av_error(map_result))); + } + Ok(mapped) } - Ok(frame) } } impl Drop for D3d11HwFrames { fn drop(&mut self) { unsafe { + if !self.qsv_frames.is_null() { + av_buffer_unref(&mut self.qsv_frames); + } av_buffer_unref(&mut self.frames_ctx); av_buffer_unref(&mut self.device_ctx); } diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 7f06a132215..9e2ac6ff63a 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -14,6 +14,8 @@ use tracing::{debug, error, info, trace, warn}; use crate::base::{EncoderBase, PacketSink}; use crate::video::HwUpload; #[cfg(windows)] +use crate::video::d3d11_format::{D3d11SwFormat, D3d11TexturePath, d3d11_texture_path}; +#[cfg(windows)] use crate::video::d3d11_hw::{D3d11HwFrames, D3d11TextureLifetime}; use crate::video::h264_packet::H264PacketEncoder; use crate::video::hardware_crash::{self, HardwareEncoderSession}; @@ -95,9 +97,16 @@ pub enum H264EncoderError { Vaapi(String), } +#[cfg(windows)] +struct D3d11EncoderTarget<'a> { + frames_ctx: *mut ffmpeg::sys::AVBufferRef, + pixel: ffmpeg::format::Pixel, + hw_frames: &'a D3d11HwFrames, +} + #[cfg(windows)] fn open_d3d11_encoder( - hw_frames: &D3d11HwFrames, + target: D3d11EncoderTarget<'_>, codec: Codec, encoder_options: Dictionary<'static>, input_config: &VideoInfo, @@ -113,7 +122,7 @@ fn open_d3d11_encoder( let mut encoder = encoder_ctx.encoder().video()?; encoder.set_width(output_width); encoder.set_height(output_height); - encoder.set_format(ffmpeg::format::Pixel::D3D11); + encoder.set_format(target.pixel); encoder.set_time_base(input_config.time_base); encoder.set_frame_rate(Some(input_config.frame_rate)); encoder.set_colorspace(color::Space::BT709); @@ -122,7 +131,9 @@ fn open_d3d11_encoder( (*encoder.as_mut_ptr()).color_primaries = ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709; (*encoder.as_mut_ptr()).color_trc = ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709; - hw_frames.attach_to_encoder(encoder.as_mut_ptr()); + target + .hw_frames + .attach_frames(encoder.as_mut_ptr(), target.frames_ctx); } let frame_rate = input_config.frame_rate.0 as f32 / input_config.frame_rate.1.max(1) as f32; let bitrate = get_bitrate(output_width, output_height, frame_rate, bpp); @@ -642,8 +653,6 @@ impl H264EncoderBuilder { output: &mut format::context::Output, device: *mut std::ffi::c_void, ) -> Result { - const D3D11_TEXTURE_ENCODERS: &[&str] = &["h264_amf", "h264_nvenc", "h264_qsv", "h264_mf"]; - let software_fallback = Box::new(self.clone()); let input_config = self.input_config; let (output_width, output_height) = match self.output_size { @@ -680,7 +689,7 @@ impl H264EncoderBuilder { )); } - let hw_frames = unsafe { D3d11HwFrames::new(device, output_width, output_height) } + let mut hw_frames = unsafe { D3d11HwFrames::new(device, output_width, output_height) } .map_err(|error| H264EncoderError::D3d11HwInput(error.to_string()))?; let candidates = get_codec_and_options( @@ -690,14 +699,29 @@ impl H264EncoderBuilder { self.is_export, None, ); - let mut last_error = None; + let mut failures = Vec::new(); for (codec, encoder_options) in candidates { let codec_name = codec.name().to_string(); - if !D3D11_TEXTURE_ENCODERS.contains(&codec_name.as_str()) { + let Some(path) = d3d11_texture_path(&codec_name) else { continue; - } + }; + let pixel = match path { + D3d11TexturePath::D3d11Nv12 => ffmpeg::format::Pixel::D3D11, + D3d11TexturePath::QsvFromD3d11Nv12 => ffmpeg::format::Pixel::QSV, + }; + let frames_ctx = match unsafe { hw_frames.frames_for(path) } { + Ok(frames_ctx) => frames_ctx, + Err(error) => { + failures.push(format!("{codec_name}: {error}")); + continue; + } + }; match open_d3d11_encoder( - &hw_frames, + D3d11EncoderTarget { + frames_ctx, + pixel, + hw_frames: &hw_frames, + }, codec, encoder_options, &input_config, @@ -713,6 +737,7 @@ impl H264EncoderBuilder { output_stream.set_parameters(&encoder); info!( encoder = %codec_name, + sw_format = D3d11SwFormat::Nv12.name(), width = output_width, height = output_height, "Selected hardware H264 encoder with D3D11 texture input" @@ -721,7 +746,7 @@ impl H264EncoderBuilder { base: EncoderBase::new(stream_index), encoder, converter: None, - output_format: ffmpeg::format::Pixel::D3D11, + output_format: pixel, output_width, output_height, input_format: input_config.pixel_format, @@ -737,19 +762,24 @@ impl H264EncoderBuilder { }); } Err(error) => { + hw_frames.clear_qsv(); + let text = match &error { + H264EncoderError::FFmpeg(inner) => inner.to_string(), + other => other.to_string(), + }; debug!( encoder = %codec_name, - %error, + error = %text, "D3D11 texture input open failed" ); - last_error = Some(error); + failures.push(format!("{codec_name}: {text}")); } } } - Err(last_error.unwrap_or_else(|| { - H264EncoderError::D3d11HwInput( - "no hardware encoder accepted the D3D11 texture".to_string(), - ) + Err(H264EncoderError::D3d11HwInput(if failures.is_empty() { + "no hardware encoder accepted the D3D11 texture".to_string() + } else { + failures.join("; ") })) } @@ -1281,8 +1311,13 @@ impl H264Encoder { self.d3d11_hw.is_some() } + #[cfg(windows)] + pub fn d3d11_sw_format_name(&self) -> Option<&'static str> { + self.d3d11_hw.as_ref().map(|_| D3d11SwFormat::Nv12.name()) + } + /// # Safety - /// `texture` must be an RGBA `ID3D11Texture2D` on the device this encoder + /// `texture` must be an NV12 `ID3D11Texture2D` on the device this encoder /// was opened with, at this encoder's width and height. `lifetime.free` /// runs once when the frame is dropped. #[cfg(windows)] diff --git a/crates/enc-ffmpeg/src/video/mod.rs b/crates/enc-ffmpeg/src/video/mod.rs index c0660a0b675..5a2091860cd 100644 --- a/crates/enc-ffmpeg/src/video/mod.rs +++ b/crates/enc-ffmpeg/src/video/mod.rs @@ -1,6 +1,8 @@ use ffmpeg::frame; pub mod colour; +#[cfg(any(windows, test))] +pub(crate) mod d3d11_format; #[cfg(target_os = "windows")] mod d3d11_hw; pub mod h264; diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml index 84d8000acf2..442cd5c3fde 100644 --- a/crates/recording/Cargo.toml +++ b/crates/recording/Cargo.toml @@ -86,6 +86,7 @@ windows = { workspace = true, features = [ "Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D11", + "Win32_Graphics_Dxgi", "Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging", "Win32_System_Performance", diff --git a/crates/recording/examples/d3d11-texture-encode-benchmark.rs b/crates/recording/examples/d3d11-texture-encode-benchmark.rs index 6ba8a4740d2..e01a892e4e3 100644 --- a/crates/recording/examples/d3d11-texture-encode-benchmark.rs +++ b/crates/recording/examples/d3d11-texture-encode-benchmark.rs @@ -14,11 +14,8 @@ fn main() { mod windows { use std::ffi::c_void; use std::path::{Path, PathBuf}; - use std::sync::Arc; - use std::sync::atomic::{AtomicU32, Ordering}; use std::time::{Duration, Instant}; - use cap_enc_ffmpeg::D3d11TextureLifetime; use cap_enc_ffmpeg::h264::H264Preset; use cap_enc_ffmpeg::remux::concatenate_m4s_segments_with_init; use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig}; @@ -32,12 +29,14 @@ mod windows { ID3D11DeviceContext, ID3D11Multithread, ID3D11Texture2D, }; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + use windows::Win32::Graphics::Dxgi::{IDXGIAdapter, IDXGIDevice}; use windows::core::Interface; + use cap_recording::GpuTextureRing; + const WARMUP: usize = 30; const FRAMES: usize = 300; const RUNS: usize = 5; - const RING: usize = 8; const SOURCES: usize = 4; #[repr(C)] @@ -185,64 +184,22 @@ mod windows { } } - struct Holds { - counts: Arc<[AtomicU32; RING]>, - index: u32, - } - - unsafe extern "C" fn release_hold(data: *mut c_void) { - let hold = unsafe { Box::from_raw(data as *mut Holds) }; - hold.counts[hold.index as usize].fetch_sub(1, Ordering::AcqRel); - } - - struct Ring { - textures: Vec, - counts: Arc<[AtomicU32; RING]>, - next: usize, - } - - impl Ring { - fn new(device: &ID3D11Device, width: u32, height: u32) -> Self { - let textures = (0..RING) - .map(|_| rgba_texture(device, width, height, false)) - .collect(); - Self { - textures, - counts: Arc::new(std::array::from_fn(|_| AtomicU32::new(0))), - next: 0, - } - } - - fn submit_source( - &mut self, - context: &ID3D11DeviceContext, - source: &ID3D11Texture2D, - ) -> (*mut c_void, D3d11TextureLifetime) { - let mut chosen = None; - for step in 0..RING { - let index = (self.next + step) % RING; - if self.counts[index].load(Ordering::Acquire) == 0 { - chosen = Some(index); - break; - } - } - let index = chosen.expect("texture ring full"); - self.next = (index + 1) % RING; - let dest = &self.textures[index]; - unsafe { context.CopyResource(dest, source) }; - self.counts[index].fetch_add(1, Ordering::AcqRel); - let hold = Box::new(Holds { - counts: Arc::clone(&self.counts), - index: index as u32, - }); - ( - dest.as_raw(), - D3d11TextureLifetime { - data: Box::into_raw(hold) as *mut c_void, - free: release_hold, - }, - ) - } + fn adapter_description(device: &ID3D11Device) -> String { + let Ok(dxgi) = device.cast::() else { + return "unknown".to_string(); + }; + let Ok(adapter) = (unsafe { dxgi.GetAdapter() }) else { + return "unknown".to_string(); + }; + let Ok(desc) = (unsafe { IDXGIAdapter::GetDesc(&adapter) }) else { + return "unknown".to_string(); + }; + let end = desc + .Description + .iter() + .position(|unit| *unit == 0) + .unwrap_or(desc.Description.len()); + String::from_utf16_lossy(&desc.Description[..end]) } fn readback( @@ -279,6 +236,8 @@ mod windows { wall: Duration, cpu: Duration, decoded: usize, + encoder: String, + sw: String, } fn decode_count(path: &Path) -> usize { @@ -341,6 +300,7 @@ mod windows { }, ) .expect("readback encoder"); + let encoder_name = encoder.codec_name(); let mut reusable = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); for i in 0..WARMUP { @@ -382,7 +342,13 @@ mod windows { let cpu = process_cpu().saturating_sub(cpu_start); encoder.finish().expect("finish readback"); let decoded = decode_count(&assemble(dir)); - Run { wall, cpu, decoded } + Run { + wall, + cpu, + decoded, + encoder: encoder_name, + sw: "frames rgba".to_string(), + } } fn run_texture( @@ -390,7 +356,7 @@ mod windows { device: &Device, sources: &[ID3D11Texture2D], info: VideoInfo, - ) -> Option { + ) -> Result { let mut encoder = SegmentedVideoEncoder::init( dir.to_path_buf(), info, @@ -400,13 +366,18 @@ mod windows { ..Default::default() }, ) - .expect("texture encoder"); + .map_err(|error| error.to_string())?; if !encoder.is_d3d11_hw_input() { - return None; + return Err(encoder.d3d11_status().to_string()); } - let mut ring = Ring::new(&device.device, info.width, info.height); + let encoder_name = encoder.codec_name(); + let sw = format!("hw sw_format {}", encoder.d3d11_status()); + let mut ring = GpuTextureRing::new(device.device.clone()) + .ok_or_else(|| "no immediate context".to_string())?; for i in 0..WARMUP { - let (texture, lifetime) = ring.submit_source(&device.context, &sources[i % SOURCES]); + let (texture, lifetime) = ring + .submit_from(&sources[i % SOURCES], info.width, info.height) + .ok_or_else(|| ring.refusal().to_string())?; unsafe { encoder .queue_d3d11_texture( @@ -414,15 +385,16 @@ mod windows { Duration::from_millis(i as u64 * 33), Some(lifetime), ) - .expect("warmup texture"); + .map_err(|error| error.to_string())?; } } let wall_start = Instant::now(); let cpu_start = process_cpu(); for i in 0..FRAMES { let index = WARMUP + i; - let (texture, lifetime) = - ring.submit_source(&device.context, &sources[index % SOURCES]); + let (texture, lifetime) = ring + .submit_from(&sources[index % SOURCES], info.width, info.height) + .ok_or_else(|| ring.refusal().to_string())?; unsafe { encoder .queue_d3d11_texture( @@ -430,14 +402,20 @@ mod windows { Duration::from_millis(index as u64 * 33), Some(lifetime), ) - .expect("texture frame"); + .map_err(|error| error.to_string())?; } } let wall = wall_start.elapsed(); let cpu = process_cpu().saturating_sub(cpu_start); - encoder.finish().expect("finish texture"); + encoder.finish().map_err(|error| error.to_string())?; let decoded = decode_count(&assemble(dir)); - Some(Run { wall, cpu, decoded }) + Ok(Run { + wall, + cpu, + decoded, + encoder: encoder_name, + sw, + }) } fn report(label: &str, path: &str, runs: &[Run]) { @@ -447,8 +425,13 @@ mod windows { let wall_max = *wall.iter().max().unwrap_or(&0); let cpu_min = *cpu.iter().min().unwrap_or(&0); let cpu_max = *cpu.iter().max().unwrap_or(&0); + let encoder = runs + .first() + .map(|run| run.encoder.as_str()) + .unwrap_or("unknown"); + let sw = runs.first().map(|run| run.sw.as_str()).unwrap_or("unknown"); println!( - "{label} {path} wall median {} ms range {wall_min}-{wall_max} cpu median {} ms range {cpu_min}-{cpu_max} decoded {:?}", + "{label} {path} encoder {encoder} {sw} wall median {} ms range {wall_min}-{wall_max} cpu median {} ms range {cpu_min}-{cpu_max} decoded {:?}", median(&mut wall), median(&mut cpu), runs.iter().map(|run| run.decoded).collect::>() @@ -460,6 +443,7 @@ mod windows { let device = open_device(); let expected = WARMUP + FRAMES; let mut failed = false; + println!("adapter: {}", adapter_description(&device.device)); println!("frames {FRAMES} warmup {WARMUP} runs {RUNS} expected decoded {expected}"); for (width, height) in [(1920u32, 1080u32), (3840, 2160)] { let info = VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, 30); @@ -475,7 +459,7 @@ mod windows { let _ = std::fs::remove_dir_all(&base); let mut readback_runs = Vec::new(); let mut texture_runs = Vec::new(); - let mut texture_refused = false; + let mut texture_refusal = None; for run_index in 0..RUNS { let readback_dir = base.join(format!("readback-{run_index}")); std::fs::create_dir_all(&readback_dir).expect("readback dir"); @@ -488,22 +472,27 @@ mod windows { let texture_dir = base.join(format!("texture-{run_index}")); std::fs::create_dir_all(&texture_dir).expect("texture dir"); match run_texture(&texture_dir, &device, &sources, info) { - Some(texture) => { + Ok(texture) => { if texture.decoded != expected { failed = true; } texture_runs.push(texture); } - None => texture_refused = true, + Err(reason) => { + if texture_refusal.is_none() { + texture_refusal = Some(reason); + } + } } } let label = format!("{width}x{height}"); report(&label, "readback", &readback_runs); - if texture_refused { - println!("{label} texture refused, CPU frame path stayed in use"); - } else { + if !texture_runs.is_empty() { report(&label, "texture", &texture_runs); } + if let Some(reason) = texture_refusal { + println!("{label} texture refused: {reason}"); + } } if failed { eprintln!("decoded frame count did not match frames submitted"); diff --git a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs index 096a3a8b621..99618509786 100644 --- a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs +++ b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs @@ -1,14 +1,31 @@ -use super::texture_slots::{TEXTURE_RING_CAPACITY, TextureSlots}; -use cap_enc_ffmpeg::D3d11TextureLifetime; use std::ffi::c_void; +use std::mem::ManuallyDrop; use std::sync::Arc; + +use cap_enc_ffmpeg::D3d11TextureLifetime; +use cap_enc_ffmpeg::capture_texel_feeds_nv12; use windows::Win32::Graphics::Direct3D11::{ - D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_TEXTURE2D_DESC, - D3D11_USAGE_DEFAULT, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, + D3D11_BIND_RENDER_TARGET, D3D11_BIND_VIDEO_ENCODER, D3D11_TEX2D_VPIV, D3D11_TEX2D_VPOV, + D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, + D3D11_VIDEO_PROCESSOR_COLOR_SPACE, D3D11_VIDEO_PROCESSOR_CONTENT_DESC, + D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0, + D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_0_255, D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235, + D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0, + D3D11_VIDEO_PROCESSOR_STREAM, D3D11_VIDEO_USAGE_OPTIMAL_QUALITY, + D3D11_VPIV_DIMENSION_TEXTURE2D, D3D11_VPOV_DIMENSION_TEXTURE2D, ID3D11Device, + ID3D11DeviceContext, ID3D11Texture2D, ID3D11VideoContext, ID3D11VideoContext1, + ID3D11VideoDevice, ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator, + ID3D11VideoProcessorOutputView, +}; +use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709, + DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12, DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_RATIONAL, DXGI_SAMPLE_DESC, }; -use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; use windows::core::Interface; +use super::texture_slots::{TEXTURE_RING_CAPACITY, TextureSlots}; + struct SlotRelease { slots: Arc, slot: u32, @@ -41,29 +58,194 @@ impl Drop for PreparedTexture { } } -pub(crate) struct GpuTextureRing { +struct Nv12Converter { + video_device: ID3D11VideoDevice, + video_context: ID3D11VideoContext, + enumerator: ID3D11VideoProcessorEnumerator, + processor: ID3D11VideoProcessor, + output_views: Vec, + input_format: DXGI_FORMAT, +} + +impl Nv12Converter { + fn new( + device: &ID3D11Device, + context: &ID3D11DeviceContext, + textures: &[ID3D11Texture2D], + width: u32, + height: u32, + input_format: DXGI_FORMAT, + ) -> Result { + let video_device: ID3D11VideoDevice = device + .cast() + .map_err(|error| format!("video device: {error}"))?; + let video_context: ID3D11VideoContext = context + .cast() + .map_err(|error| format!("video context: {error}"))?; + let desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC { + InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, + InputFrameRate: DXGI_RATIONAL { + Numerator: 60, + Denominator: 1, + }, + InputWidth: width, + InputHeight: height, + OutputFrameRate: DXGI_RATIONAL { + Numerator: 60, + Denominator: 1, + }, + OutputWidth: width, + OutputHeight: height, + Usage: D3D11_VIDEO_USAGE_OPTIMAL_QUALITY, + }; + let enumerator = unsafe { video_device.CreateVideoProcessorEnumerator(&desc) } + .map_err(|error| format!("video processor enumerator: {error}"))?; + let processor = unsafe { video_device.CreateVideoProcessor(&enumerator, 0) } + .map_err(|error| format!("video processor: {error}"))?; + set_studio_bt709(&video_context, &processor); + let view_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC { + ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D, + Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 { + Texture2D: D3D11_TEX2D_VPOV { MipSlice: 0 }, + }, + }; + let mut output_views = Vec::with_capacity(textures.len()); + for texture in textures { + let mut view = None; + unsafe { + video_device + .CreateVideoProcessorOutputView( + texture, + &enumerator, + &view_desc, + Some(&mut view), + ) + .map_err(|error| format!("NV12 output view: {error}"))?; + } + output_views.push(view.ok_or_else(|| "NV12 output view missing".to_string())?); + } + Ok(Self { + video_device, + video_context, + enumerator, + processor, + output_views, + input_format, + }) + } + + fn blit(&self, src: &ID3D11Texture2D, slot: u32) -> Result<(), String> { + let input_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC { + ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D, + Anonymous: D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 { + Texture2D: D3D11_TEX2D_VPIV { + MipSlice: 0, + ..Default::default() + }, + }, + ..Default::default() + }; + let mut input = None; + unsafe { + self.video_device + .CreateVideoProcessorInputView(src, &self.enumerator, &input_desc, Some(&mut input)) + .map_err(|error| format!("video processor input: {error}"))?; + } + let input = input.ok_or_else(|| "video processor input missing".to_string())?; + let output = self + .output_views + .get(slot as usize) + .ok_or_else(|| "NV12 output view missing".to_string())?; + let mut stream = D3D11_VIDEO_PROCESSOR_STREAM { + Enable: true.into(), + OutputIndex: 0, + InputFrameOrField: 0, + pInputSurface: ManuallyDrop::new(Some(input)), + ..Default::default() + }; + let result = unsafe { + self.video_context.VideoProcessorBlt( + &self.processor, + output, + 0, + std::slice::from_ref(&stream), + ) + }; + unsafe { ManuallyDrop::drop(&mut stream.pInputSurface) }; + result.map_err(|error| format!("video processor blit: {error}")) + } +} + +fn set_studio_bt709(context: &ID3D11VideoContext, processor: &ID3D11VideoProcessor) { + if let Ok(context1) = context.cast::() { + unsafe { + context1.VideoProcessorSetStreamColorSpace1( + processor, + 0, + DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, + ); + context1.VideoProcessorSetOutputColorSpace1( + processor, + DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709, + ); + } + return; + } + let bt709 = 1u32 << 2; + let full = (D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_0_255.0 as u32) << 4; + let limited_rgb = 1u32 << 1; + let studio = (D3D11_VIDEO_PROCESSOR_NOMINAL_RANGE_16_235.0 as u32) << 4; + let input = D3D11_VIDEO_PROCESSOR_COLOR_SPACE { + _bitfield: bt709 | full, + }; + let output = D3D11_VIDEO_PROCESSOR_COLOR_SPACE { + _bitfield: limited_rgb | bt709 | studio, + }; + unsafe { + context.VideoProcessorSetStreamColorSpace(processor, 0, &input); + context.VideoProcessorSetOutputColorSpace(processor, &output); + } +} + +fn texel_name(format: DXGI_FORMAT) -> &'static str { + if format == DXGI_FORMAT_R8G8B8A8_UNORM { + "rgba" + } else if format == DXGI_FORMAT_B8G8R8A8_UNORM { + "bgra" + } else if format == DXGI_FORMAT_NV12 { + "nv12" + } else { + "other" + } +} + +pub struct GpuTextureRing { device: ID3D11Device, context: ID3D11DeviceContext, textures: Vec, + converter: Option, slots: Arc, last: Option, width: u32, height: u32, unusable: bool, + refusal: Option, } impl GpuTextureRing { - pub(crate) fn new(device: ID3D11Device) -> Option { + pub fn new(device: ID3D11Device) -> Option { let context = unsafe { device.GetImmediateContext() }.ok()?; Some(Self { device, context, textures: Vec::new(), + converter: None, slots: Arc::new(TextureSlots::new()), last: None, width: 0, height: 0, unusable: false, + refusal: None, }) } @@ -71,6 +253,21 @@ impl GpuTextureRing { self.unusable } + pub fn refusal(&self) -> &str { + self.refusal + .as_deref() + .unwrap_or("D3D11 texture path refused") + } + + pub fn submit_from( + &mut self, + src: &ID3D11Texture2D, + width: u32, + height: u32, + ) -> Option<(*mut c_void, D3d11TextureLifetime)> { + self.copy_from(src, width, height)?.into_submit() + } + pub(crate) fn copy_from( &mut self, src: &ID3D11Texture2D, @@ -83,37 +280,68 @@ impl GpuTextureRing { || !width.is_multiple_of(2) || !height.is_multiple_of(2) { - self.unusable = true; + self.refuse("odd or zero size"); return None; } let mut desc = D3D11_TEXTURE2D_DESC::default(); unsafe { src.GetDesc(&mut desc) }; - if desc.Format != DXGI_FORMAT_R8G8B8A8_UNORM || desc.Width != width || desc.Height != height - { - self.unusable = true; + let texel = texel_name(desc.Format); + if !capture_texel_feeds_nv12(texel) || desc.Width != width || desc.Height != height { + self.refuse(format!("capture format {texel} cannot feed NV12")); return None; } if self.width != 0 && (self.width != width || self.height != height) { - self.unusable = true; + self.refuse("size changed"); return None; } - if self.textures.is_empty() && self.allocate(width, height).is_none() { - self.unusable = true; + if self.textures.is_empty() + && let Err(error) = self.allocate(width, height) + { + self.refuse(error); return None; } - let slot = self.slots.try_acquire()?; - let dest = self.textures.get(slot as usize)?; - unsafe { - self.context.CopyResource(dest, src); - self.context.Flush(); + let Some(slot) = self.slots.try_acquire() else { + self.refusal = Some("texture ring full".to_string()); + return None; + }; + if self.textures.get(slot as usize).is_none() { + self.refuse("texture slot missing"); + return None; } + let converted = if texel == "nv12" { + let dest = &self.textures[slot as usize]; + unsafe { self.context.CopyResource(dest, src) }; + Ok(()) + } else { + self.convert(src, desc.Format, slot) + }; + if let Err(error) = converted { + self.refuse(error); + return None; + } + unsafe { self.context.Flush() }; if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { - self.unusable = true; + self.refuse("device removed"); return None; } self.slots.hold(slot); self.last = Some(slot); - Some(self.prepared(slot, dest)) + self.refusal = None; + let dest = self.textures[slot as usize].clone(); + Some(self.prepared(slot, &dest)) + } + + fn convert( + &mut self, + src: &ID3D11Texture2D, + format: DXGI_FORMAT, + slot: u32, + ) -> Result<(), String> { + self.ensure_converter(format)?; + match self.converter.as_ref() { + Some(converter) => converter.blit(src, slot), + None => Err("NV12 converter missing".to_string()), + } } pub(crate) fn repeat_last(&mut self) -> Option { @@ -123,36 +351,49 @@ impl GpuTextureRing { Some(self.prepared(slot, texture)) } - fn allocate(&mut self, width: u32, height: u32) -> Option<()> { - 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_SHADER_RESOURCE.0 | D3D11_BIND_RENDER_TARGET.0) as u32, - CPUAccessFlags: 0, - MiscFlags: 0, - }; - let mut textures = Vec::with_capacity(TEXTURE_RING_CAPACITY as usize); - for _ in 0..TEXTURE_RING_CAPACITY { - let mut texture = None; - unsafe { - self.device - .CreateTexture2D(&desc, None, Some(&mut texture)) - .ok()?; + fn refuse(&mut self, reason: impl Into) { + self.unusable = true; + self.refusal = Some(reason.into()); + } + + fn ensure_converter(&mut self, format: DXGI_FORMAT) -> Result<(), String> { + if self + .converter + .as_ref() + .is_some_and(|converter| converter.input_format == format) + { + return Ok(()); + } + let converter = Nv12Converter::new( + &self.device, + &self.context, + &self.textures, + self.width, + self.height, + format, + )?; + self.converter = Some(converter); + Ok(()) + } + + fn allocate(&mut self, width: u32, height: u32) -> Result<(), String> { + let binds = [ + (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_VIDEO_ENCODER.0) as u32, + D3D11_BIND_RENDER_TARGET.0 as u32, + ]; + let mut last = "NV12 texture allocation failed".to_string(); + for bind in binds { + match create_textures(&self.device, width, height, bind) { + Ok(textures) => { + self.textures = textures; + self.width = width; + self.height = height; + return Ok(()); + } + Err(error) => last = error, } - textures.push(texture?); } - self.textures = textures; - self.width = width; - self.height = height; - Some(()) + Err(last) } fn prepared(&self, slot: u32, texture: &ID3D11Texture2D) -> PreparedTexture { @@ -169,3 +410,37 @@ impl GpuTextureRing { } } } + +fn create_textures( + device: &ID3D11Device, + width: u32, + height: u32, + bind_flags: u32, +) -> Result, String> { + let desc = D3D11_TEXTURE2D_DESC { + Width: width, + Height: height, + MipLevels: 1, + ArraySize: 1, + Format: DXGI_FORMAT_NV12, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Usage: D3D11_USAGE_DEFAULT, + BindFlags: bind_flags, + CPUAccessFlags: 0, + MiscFlags: 0, + }; + let mut textures = Vec::with_capacity(TEXTURE_RING_CAPACITY as usize); + for _ in 0..TEXTURE_RING_CAPACITY { + let mut texture = None; + unsafe { + device + .CreateTexture2D(&desc, None, Some(&mut texture)) + .map_err(|error| format!("NV12 texture: {error}"))?; + } + textures.push(texture.ok_or_else(|| "NV12 texture missing".to_string())?); + } + Ok(textures) +} diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rs index 02cb29962c5..4643fa99fbe 100644 --- a/crates/recording/src/output_pipeline/mod.rs +++ b/crates/recording/src/output_pipeline/mod.rs @@ -2,6 +2,8 @@ mod async_camera; mod core; #[cfg(windows)] mod d3d11_texture_ring; +#[cfg(windows)] +pub use d3d11_texture_ring::GpuTextureRing; pub mod ffmpeg; #[cfg(any(windows, test))] mod frame_pacing; From 0650913cc20d0e18d1ac7085e0e62d9c2c265551 Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:38:49 +0000 Subject: [PATCH 3/4] fix(recording): size the D3D11 texture ring past AMF's input queue FFmpeg 7.1 keeps 16 D3D11 input surfaces referenced and only waits for output once that queue is full. A ring of 8 filled first, so the bench stopped with "texture ring full" before AMF could drain a slot. The ring is now 32, and the bench prints the encoder, sw_format, capacity, and high-water mark. Co-authored-by: Kyzer --- .../d3d11-texture-encode-benchmark.rs | 50 ++++++++++---- .../src/output_pipeline/d3d11_texture_ring.rs | 8 +++ .../src/output_pipeline/texture_slots.rs | 67 ++++++++++++++++++- 3 files changed, 110 insertions(+), 15 deletions(-) diff --git a/crates/recording/examples/d3d11-texture-encode-benchmark.rs b/crates/recording/examples/d3d11-texture-encode-benchmark.rs index e01a892e4e3..e4bd98ee80d 100644 --- a/crates/recording/examples/d3d11-texture-encode-benchmark.rs +++ b/crates/recording/examples/d3d11-texture-encode-benchmark.rs @@ -238,6 +238,8 @@ mod windows { decoded: usize, encoder: String, sw: String, + ring_capacity: Option, + ring_high_water: Option, } fn decode_count(path: &Path) -> usize { @@ -348,9 +350,19 @@ mod windows { decoded, encoder: encoder_name, sw: "frames rgba".to_string(), + ring_capacity: None, + ring_high_water: None, } } + fn texture_refusal(ring: &GpuTextureRing, encoder: &str, sw: &str, reason: &str) -> String { + format!( + "{reason} encoder {encoder} {sw} ring {} high-water {}", + ring.capacity(), + ring.high_water() + ) + } + fn run_texture( dir: &Path, device: &Device, @@ -367,17 +379,17 @@ mod windows { }, ) .map_err(|error| error.to_string())?; + let encoder_name = encoder.codec_name(); if !encoder.is_d3d11_hw_input() { - return Err(encoder.d3d11_status().to_string()); + return Err(format!("{} encoder {encoder_name}", encoder.d3d11_status())); } - let encoder_name = encoder.codec_name(); let sw = format!("hw sw_format {}", encoder.d3d11_status()); let mut ring = GpuTextureRing::new(device.device.clone()) .ok_or_else(|| "no immediate context".to_string())?; for i in 0..WARMUP { - let (texture, lifetime) = ring - .submit_from(&sources[i % SOURCES], info.width, info.height) - .ok_or_else(|| ring.refusal().to_string())?; + let submitted = ring.submit_from(&sources[i % SOURCES], info.width, info.height); + let (texture, lifetime) = submitted + .ok_or_else(|| texture_refusal(&ring, &encoder_name, &sw, ring.refusal()))?; unsafe { encoder .queue_d3d11_texture( @@ -385,16 +397,18 @@ mod windows { Duration::from_millis(i as u64 * 33), Some(lifetime), ) - .map_err(|error| error.to_string())?; + .map_err(|error| { + texture_refusal(&ring, &encoder_name, &sw, &error.to_string()) + })?; } } let wall_start = Instant::now(); let cpu_start = process_cpu(); for i in 0..FRAMES { let index = WARMUP + i; - let (texture, lifetime) = ring - .submit_from(&sources[index % SOURCES], info.width, info.height) - .ok_or_else(|| ring.refusal().to_string())?; + let submitted = ring.submit_from(&sources[index % SOURCES], info.width, info.height); + let (texture, lifetime) = submitted + .ok_or_else(|| texture_refusal(&ring, &encoder_name, &sw, ring.refusal()))?; unsafe { encoder .queue_d3d11_texture( @@ -402,12 +416,16 @@ mod windows { Duration::from_millis(index as u64 * 33), Some(lifetime), ) - .map_err(|error| error.to_string())?; + .map_err(|error| { + texture_refusal(&ring, &encoder_name, &sw, &error.to_string()) + })?; } } let wall = wall_start.elapsed(); let cpu = process_cpu().saturating_sub(cpu_start); - encoder.finish().map_err(|error| error.to_string())?; + encoder + .finish() + .map_err(|error| texture_refusal(&ring, &encoder_name, &sw, &error.to_string()))?; let decoded = decode_count(&assemble(dir)); Ok(Run { wall, @@ -415,6 +433,8 @@ mod windows { decoded, encoder: encoder_name, sw, + ring_capacity: Some(ring.capacity()), + ring_high_water: Some(ring.high_water()), }) } @@ -430,8 +450,14 @@ mod windows { .map(|run| run.encoder.as_str()) .unwrap_or("unknown"); let sw = runs.first().map(|run| run.sw.as_str()).unwrap_or("unknown"); + let capacity = runs.iter().find_map(|run| run.ring_capacity); + let high_water = runs.iter().filter_map(|run| run.ring_high_water).max(); + let ring_text = match (capacity, high_water) { + (Some(capacity), Some(peak)) => format!(" ring {capacity} high-water {peak}"), + _ => String::new(), + }; println!( - "{label} {path} encoder {encoder} {sw} wall median {} ms range {wall_min}-{wall_max} cpu median {} ms range {cpu_min}-{cpu_max} decoded {:?}", + "{label} {path} encoder {encoder} {sw}{ring_text} wall median {} ms range {wall_min}-{wall_max} cpu median {} ms range {cpu_min}-{cpu_max} decoded {:?}", median(&mut wall), median(&mut cpu), runs.iter().map(|run| run.decoded).collect::>() diff --git a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs index 99618509786..9b175de460e 100644 --- a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs +++ b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs @@ -253,6 +253,14 @@ impl GpuTextureRing { self.unusable } + pub fn capacity(&self) -> u32 { + TEXTURE_RING_CAPACITY + } + + pub fn high_water(&self) -> u32 { + self.slots.high_water() + } + pub fn refusal(&self) -> &str { self.refusal .as_deref() diff --git a/crates/recording/src/output_pipeline/texture_slots.rs b/crates/recording/src/output_pipeline/texture_slots.rs index 6bd9331bf48..d9b8ff8ac7f 100644 --- a/crates/recording/src/output_pipeline/texture_slots.rs +++ b/crates/recording/src/output_pipeline/texture_slots.rs @@ -1,7 +1,13 @@ use std::sync::atomic::{AtomicU32, Ordering}; use std::time::Duration; -pub(crate) const TEXTURE_RING_CAPACITY: u32 = 8; +/// FFmpeg 7.1 `amfenc.c` keeps `hwsurfaces_in_queue_max` at 16 when the D3D11 +/// frames context has `initial_pool_size == 0`, and each input texture stays +/// referenced until `QueryOutput`. AMF only waits for that output once 16 +/// surfaces are queued. A smaller ring fills first, the submitter stops, and +/// nothing is ever drained. +pub(crate) const AMF_HW_SURFACE_QUEUE: u32 = 16; +pub(crate) const TEXTURE_RING_CAPACITY: u32 = AMF_HW_SURFACE_QUEUE + 16; /// How many encoder frames still reference each copied texture. /// @@ -10,15 +16,23 @@ pub(crate) const TEXTURE_RING_CAPACITY: u32 = 8; /// `release`. pub(crate) struct TextureSlots { holds: [AtomicU32; TEXTURE_RING_CAPACITY as usize], + busy: AtomicU32, + peak: AtomicU32, } impl TextureSlots { pub(crate) fn new() -> Self { Self { holds: std::array::from_fn(|_| AtomicU32::new(0)), + busy: AtomicU32::new(0), + peak: AtomicU32::new(0), } } + pub(crate) fn high_water(&self) -> u32 { + self.peak.load(Ordering::Acquire) + } + /// The first slot no frame still references. The caller must `hold` it /// before the next acquire, or this returns the same slot again. pub(crate) fn try_acquire(&self) -> Option { @@ -27,11 +41,18 @@ impl TextureSlots { } pub(crate) fn hold(&self, slot: u32) { - self.holds[slot as usize].fetch_add(1, Ordering::AcqRel); + let previous = self.holds[slot as usize].fetch_add(1, Ordering::AcqRel); + if previous == 0 { + let busy = self.busy.fetch_add(1, Ordering::AcqRel) + 1; + self.peak.fetch_max(busy, Ordering::AcqRel); + } } pub(crate) fn release(&self, slot: u32) { - self.holds[slot as usize].fetch_sub(1, Ordering::AcqRel); + let previous = self.holds[slot as usize].fetch_sub(1, Ordering::AcqRel); + if previous == 1 { + self.busy.fetch_sub(1, Ordering::AcqRel); + } } } @@ -85,6 +106,46 @@ mod tests { assert_eq!(slots.try_acquire(), Some(5)); } + #[test] + fn the_ring_outlasts_amf_inflight_and_reuses_a_released_slot() { + let slots = TextureSlots::new(); + assert!(TEXTURE_RING_CAPACITY > AMF_HW_SURFACE_QUEUE); + for _ in 0..AMF_HW_SURFACE_QUEUE { + let slot = slots.try_acquire().expect("free slot"); + slots.hold(slot); + } + assert!(slots.try_acquire().is_some()); + assert_eq!(slots.high_water(), AMF_HW_SURFACE_QUEUE); + + let mut filled = AMF_HW_SURFACE_QUEUE; + while let Some(slot) = slots.try_acquire() { + slots.hold(slot); + filled += 1; + assert!(filled <= TEXTURE_RING_CAPACITY); + } + assert_eq!(filled, TEXTURE_RING_CAPACITY); + assert!(slots.try_acquire().is_none()); + assert_eq!(slots.high_water(), TEXTURE_RING_CAPACITY); + + slots.release(3); + assert_eq!(slots.try_acquire(), Some(3)); + assert_eq!(slots.high_water(), TEXTURE_RING_CAPACITY); + } + + #[test] + fn a_second_hold_does_not_raise_the_high_water_mark() { + let slots = TextureSlots::new(); + slots.hold(0); + slots.hold(0); + assert_eq!(slots.high_water(), 1); + assert_ne!(slots.try_acquire(), Some(0)); + slots.release(0); + assert_ne!(slots.try_acquire(), Some(0)); + slots.release(0); + assert_eq!(slots.try_acquire(), Some(0)); + assert_eq!(slots.high_water(), 1); + } + #[test] fn timestamps_start_at_zero_and_keep_later_offsets() { let mut first = None; From 84c28a4b91fa91fc660decb506aff89101e6a96b Mon Sep 17 00:00:00 2001 From: kyzer1023 <36684609+kyzer1023@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:51:24 +0000 Subject: [PATCH 4/4] fix(recording): attribute D3D11 open crashes and drain before CPU fallback Start the hardware encoder session before open_d3d11_encoder, and drop it when open fails. Flush queued packets into the mux before leaving the texture path. The bench submits 60 fps frames and resubmits the previous frame on every other tick. Co-authored-by: Kyzer --- crates/enc-ffmpeg/src/mux/segmented_stream.rs | 21 ++- crates/enc-ffmpeg/src/video/h264.rs | 5 +- .../d3d11-texture-encode-benchmark.rs | 152 ++++++++++++------ crates/recording/src/capture_pipeline.rs | 108 ++++++------- crates/recording/src/cursor.rs | 1 + .../src/output_pipeline/d3d11_texture_ring.rs | 4 + .../src/output_pipeline/texture_slots.rs | 1 - .../src/recovery/needs_remux_tests.rs | 16 +- 8 files changed, 191 insertions(+), 117 deletions(-) diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rs index 14dc39df926..b1c341e9638 100644 --- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs +++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs @@ -353,6 +353,14 @@ impl Default for SegmentedVideoEncoderConfig { } } +#[cfg(windows)] +fn flush_video_encoder( + encoder: &mut H264Encoder, + mux: &mut MuxSink, +) -> Result<(), ffmpeg::Error> { + encoder.flush_to(mux) +} + impl SegmentedVideoEncoder { pub fn init( base_path: PathBuf, @@ -629,9 +637,20 @@ impl SegmentedVideoEncoder { if !self.encoder.is_d3d11_hw_input() { return false; } + let encoder_name = self.encoder.codec_name(); + if let Err(error) = flush_video_encoder(&mut self.encoder, &mut self.mux) { + tracing::error!( + encoder = %encoder_name, + %error, + "D3D11 texture input stopped before its queued frames could be written; those frames are lost" + ); + } match self.encoder.replace_with_software() { Ok(()) => { - tracing::warn!("D3D11 texture input stopped; later frames use the CPU path"); + tracing::warn!( + encoder = %encoder_name, + "D3D11 texture input stopped; later frames use the CPU path" + ); true } Err(error) => { diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs index 9e2ac6ff63a..5db6fa30698 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -716,6 +716,8 @@ impl H264EncoderBuilder { continue; } }; + let hardware_session = + is_hardware_h264(&codec_name).then(|| HardwareEncoderSession::begin(&codec_name)); match open_d3d11_encoder( D3d11EncoderTarget { frames_ctx, @@ -758,10 +760,11 @@ impl H264EncoderBuilder { software_fallback: Some(software_fallback), #[cfg(test)] injected_failure: None, - hardware_session: Some(HardwareEncoderSession::begin(&codec_name)), + hardware_session, }); } Err(error) => { + drop(hardware_session); hw_frames.clear_qsv(); let text = match &error { H264EncoderError::FFmpeg(inner) => inner.to_string(), diff --git a/crates/recording/examples/d3d11-texture-encode-benchmark.rs b/crates/recording/examples/d3d11-texture-encode-benchmark.rs index e4bd98ee80d..5f73aa55a49 100644 --- a/crates/recording/examples/d3d11-texture-encode-benchmark.rs +++ b/crates/recording/examples/d3d11-texture-encode-benchmark.rs @@ -38,6 +38,8 @@ mod windows { const FRAMES: usize = 300; const RUNS: usize = 5; const SOURCES: usize = 4; + const FPS: u32 = 60; + const FRAME_TICK_US: u64 = 1_000_000 / 60; #[repr(C)] struct Filetime { @@ -78,6 +80,21 @@ mod windows { Duration::from_nanos(ticks.saturating_mul(100)) } + fn frame_timestamp(index: usize) -> Duration { + Duration::from_micros(index as u64 * FRAME_TICK_US) + } + + fn repeats_previous(index: usize) -> bool { + index % 2 == 1 + } + + fn reference_frame(frame: &ffmpeg::frame::Video) -> ffmpeg::frame::Video { + let mut reference = ffmpeg::frame::Video::empty(); + let status = unsafe { ffmpeg::ffi::av_frame_ref(reference.as_mut_ptr(), frame.as_ptr()) }; + assert!(status >= 0, "av_frame_ref {status}"); + reference + } + fn median(values: &mut [u128]) -> u128 { values.sort_unstable(); let mid = values.len() / 2; @@ -305,39 +322,28 @@ mod windows { let encoder_name = encoder.codec_name(); let mut reusable = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); + let mut last = ffmpeg::frame::Video::empty(); for i in 0..WARMUP { - readback( - &device.context, - &sources[i % SOURCES], - staging, - &mut reusable, - info.width, - info.height, - ); - let mut owned = - ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); - std::mem::swap(&mut owned, &mut reusable); + let frame = readback_frame(device, sources, staging, info, &mut reusable, &mut last, i); encoder - .queue_frame(owned, Duration::from_millis(i as u64 * 33)) + .queue_frame(frame, frame_timestamp(i)) .expect("warmup readback"); } let wall_start = Instant::now(); let cpu_start = process_cpu(); for i in 0..FRAMES { let index = WARMUP + i; - readback( - &device.context, - &sources[index % SOURCES], + let frame = readback_frame( + device, + sources, staging, + info, &mut reusable, - info.width, - info.height, + &mut last, + index, ); - let mut owned = - ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); - std::mem::swap(&mut owned, &mut reusable); encoder - .queue_frame(owned, Duration::from_millis(index as u64 * 33)) + .queue_frame(frame, frame_timestamp(index)) .expect("readback frame"); } let wall = wall_start.elapsed(); @@ -355,6 +361,33 @@ mod windows { } } + fn readback_frame( + device: &Device, + sources: &[ID3D11Texture2D], + staging: &ID3D11Texture2D, + info: VideoInfo, + reusable: &mut ffmpeg::frame::Video, + last: &mut ffmpeg::frame::Video, + index: usize, + ) -> ffmpeg::frame::Video { + if repeats_previous(index) { + return reference_frame(last); + } + readback( + &device.context, + &sources[index % SOURCES], + staging, + reusable, + info.width, + info.height, + ); + let mut owned = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, info.width, info.height); + std::mem::swap(&mut owned, reusable); + *last = owned; + reference_frame(last) + } + fn texture_refusal(ring: &GpuTextureRing, encoder: &str, sw: &str, reason: &str) -> String { format!( "{reason} encoder {encoder} {sw} ring {} high-water {}", @@ -387,39 +420,28 @@ mod windows { let mut ring = GpuTextureRing::new(device.device.clone()) .ok_or_else(|| "no immediate context".to_string())?; for i in 0..WARMUP { - let submitted = ring.submit_from(&sources[i % SOURCES], info.width, info.height); - let (texture, lifetime) = submitted - .ok_or_else(|| texture_refusal(&ring, &encoder_name, &sw, ring.refusal()))?; - unsafe { - encoder - .queue_d3d11_texture( - texture, - Duration::from_millis(i as u64 * 33), - Some(lifetime), - ) - .map_err(|error| { - texture_refusal(&ring, &encoder_name, &sw, &error.to_string()) - })?; - } + queue_texture( + &mut encoder, + &mut ring, + sources, + info, + &encoder_name, + &sw, + i, + )?; } let wall_start = Instant::now(); let cpu_start = process_cpu(); for i in 0..FRAMES { - let index = WARMUP + i; - let submitted = ring.submit_from(&sources[index % SOURCES], info.width, info.height); - let (texture, lifetime) = submitted - .ok_or_else(|| texture_refusal(&ring, &encoder_name, &sw, ring.refusal()))?; - unsafe { - encoder - .queue_d3d11_texture( - texture, - Duration::from_millis(index as u64 * 33), - Some(lifetime), - ) - .map_err(|error| { - texture_refusal(&ring, &encoder_name, &sw, &error.to_string()) - })?; - } + queue_texture( + &mut encoder, + &mut ring, + sources, + info, + &encoder_name, + &sw, + WARMUP + i, + )?; } let wall = wall_start.elapsed(); let cpu = process_cpu().saturating_sub(cpu_start); @@ -438,6 +460,30 @@ mod windows { }) } + fn queue_texture( + encoder: &mut SegmentedVideoEncoder, + ring: &mut GpuTextureRing, + sources: &[ID3D11Texture2D], + info: VideoInfo, + encoder_name: &str, + sw: &str, + index: usize, + ) -> Result<(), String> { + let submitted = if repeats_previous(index) { + ring.resubmit_last() + } else { + ring.submit_from(&sources[index % SOURCES], info.width, info.height) + }; + let (texture, lifetime) = + submitted.ok_or_else(|| texture_refusal(ring, encoder_name, sw, ring.refusal()))?; + unsafe { + encoder + .queue_d3d11_texture(texture, frame_timestamp(index), Some(lifetime)) + .map_err(|error| texture_refusal(ring, encoder_name, sw, &error.to_string()))?; + } + Ok(()) + } + fn report(label: &str, path: &str, runs: &[Run]) { let mut wall: Vec = runs.iter().map(|run| run.wall.as_millis()).collect(); let mut cpu: Vec = runs.iter().map(|run| run.cpu.as_millis()).collect(); @@ -470,9 +516,11 @@ mod windows { let expected = WARMUP + FRAMES; let mut failed = false; println!("adapter: {}", adapter_description(&device.device)); - println!("frames {FRAMES} warmup {WARMUP} runs {RUNS} expected decoded {expected}"); + println!( + "frames {FRAMES} warmup {WARMUP} runs {RUNS} fps {FPS} tick {FRAME_TICK_US}us repeat every other frame expected decoded {expected}" + ); for (width, height) in [(1920u32, 1080u32), (3840, 2160)] { - let info = VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, 30); + let info = VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, FPS); let sources: Vec<_> = (0..SOURCES) .map(|index| { let texture = rgba_texture(&device.device, width, height, false); diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs index b7868a6977b..300ebd11937 100644 --- a/crates/recording/src/capture_pipeline.rs +++ b/crates/recording/src/capture_pipeline.rs @@ -637,60 +637,6 @@ fn resolve_area_display_notch( }) } -#[cfg(test)] -mod display_notch_tests { - use super::*; - use scap_targets::bounds::{LogicalBounds, LogicalPosition, LogicalSize}; - - const NOTCH: scap_targets::NotchGeometry = scap_targets::NotchGeometry { - x: 0.4, - width: 0.2, - height: 0.1, - }; - - fn display_size() -> LogicalSize { - LogicalSize::new(1_000.0, 800.0) - } - - #[test] - fn area_containing_the_full_notch_rebases_it() { - let bounds = LogicalBounds::new( - LogicalPosition::new(300.0, 0.0), - LogicalSize::new(400.0, 200.0), - ); - - assert_eq!( - resolve_area_display_notch(NOTCH, display_size(), bounds), - Some(cap_project::DisplayNotch { - x: 0.25, - width: 0.5, - height: 0.4, - }) - ); - } - - #[test] - fn partially_intersected_notches_are_omitted() { - let horizontal = LogicalBounds::new( - LogicalPosition::new(500.0, 0.0), - LogicalSize::new(200.0, 200.0), - ); - let vertical = LogicalBounds::new( - LogicalPosition::new(300.0, 40.0), - LogicalSize::new(400.0, 200.0), - ); - - assert_eq!( - resolve_area_display_notch(NOTCH, display_size(), horizontal), - None - ); - assert_eq!( - resolve_area_display_notch(NOTCH, display_size(), vertical), - None - ); - } -} - #[cfg(windows)] pub fn create_d3d_device() -> windows::core::Result { @@ -788,3 +734,57 @@ pub fn create_d3d_device() Ok(device.unwrap()) } + +#[cfg(test)] +mod display_notch_tests { + use super::*; + use scap_targets::bounds::{LogicalBounds, LogicalPosition, LogicalSize}; + + const NOTCH: scap_targets::NotchGeometry = scap_targets::NotchGeometry { + x: 0.4, + width: 0.2, + height: 0.1, + }; + + fn display_size() -> LogicalSize { + LogicalSize::new(1_000.0, 800.0) + } + + #[test] + fn area_containing_the_full_notch_rebases_it() { + let bounds = LogicalBounds::new( + LogicalPosition::new(300.0, 0.0), + LogicalSize::new(400.0, 200.0), + ); + + assert_eq!( + resolve_area_display_notch(NOTCH, display_size(), bounds), + Some(cap_project::DisplayNotch { + x: 0.25, + width: 0.5, + height: 0.4, + }) + ); + } + + #[test] + fn partially_intersected_notches_are_omitted() { + let horizontal = LogicalBounds::new( + LogicalPosition::new(500.0, 0.0), + LogicalSize::new(200.0, 200.0), + ); + let vertical = LogicalBounds::new( + LogicalPosition::new(300.0, 40.0), + LogicalSize::new(400.0, 200.0), + ); + + assert_eq!( + resolve_area_display_notch(NOTCH, display_size(), horizontal), + None + ); + assert_eq!( + resolve_area_display_notch(NOTCH, display_size(), vertical), + None + ); + } +} diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs index 8ca123d3498..2882c7480aa 100644 --- a/crates/recording/src/cursor.rs +++ b/crates/recording/src/cursor.rs @@ -2054,6 +2054,7 @@ mod input_epoch_tests { mod incremental_writer_tests { use super::*; use cap_project::CursorEvents; + #[cfg(unix)] use std::sync::atomic::AtomicBool; use std::time::Duration; diff --git a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs index 9b175de460e..e1b88c0559d 100644 --- a/crates/recording/src/output_pipeline/d3d11_texture_ring.rs +++ b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs @@ -276,6 +276,10 @@ impl GpuTextureRing { self.copy_from(src, width, height)?.into_submit() } + pub fn resubmit_last(&mut self) -> Option<(*mut c_void, D3d11TextureLifetime)> { + self.repeat_last()?.into_submit() + } + pub(crate) fn copy_from( &mut self, src: &ID3D11Texture2D, diff --git a/crates/recording/src/output_pipeline/texture_slots.rs b/crates/recording/src/output_pipeline/texture_slots.rs index d9b8ff8ac7f..938cf4da722 100644 --- a/crates/recording/src/output_pipeline/texture_slots.rs +++ b/crates/recording/src/output_pipeline/texture_slots.rs @@ -109,7 +109,6 @@ mod tests { #[test] fn the_ring_outlasts_amf_inflight_and_reuses_a_released_slot() { let slots = TextureSlots::new(); - assert!(TEXTURE_RING_CAPACITY > AMF_HW_SURFACE_QUEUE); for _ in 0..AMF_HW_SURFACE_QUEUE { let slot = slots.try_acquire().expect("free slot"); slots.hold(slot); diff --git a/crates/recording/src/recovery/needs_remux_tests.rs b/crates/recording/src/recovery/needs_remux_tests.rs index ae11a64dec2..51bfd4ae855 100644 --- a/crates/recording/src/recovery/needs_remux_tests.rs +++ b/crates/recording/src/recovery/needs_remux_tests.rs @@ -240,7 +240,7 @@ fn needs_remux_recordings_of_every_size_validate_and_remux_in_order() { indexes.windows(2).all(|pair| pair[0] < pair[1]), "{fragments}" ); - assert_eq!(RecoveryManager::remux_if_needed(&project).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&project).unwrap()); assert_eq!(remuxed_frames(&project), recorded, "{fragments}"); assert!(original_backups(&project).is_empty()); assert!(!project.join(RECOVERY_PUBLICATION).exists()); @@ -257,19 +257,19 @@ fn torn_missing_or_unlisted_tails_still_remux_and_mid_recording_damage_is_refuse let last = partial.join(DISPLAY).join("segment_1356.m4s"); let bytes = fs::read(&last).unwrap(); fs::write(&last, &bytes[..bytes.len() / 2]).unwrap(); - assert_eq!(RecoveryManager::remux_if_needed(&partial).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&partial).unwrap()); assert_eq!(remuxed_frames(&partial), recorded); let missing = make("missing last fragment"); let recorded = recorded_frames(&missing, Some("segment_1356.m4s")); fs::remove_file(missing.join(DISPLAY).join("segment_1356.m4s")).unwrap(); - assert_eq!(RecoveryManager::remux_if_needed(&missing).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&missing).unwrap()); assert_eq!(remuxed_frames(&missing), recorded); let unlisted = make("missing manifest"); let recorded = recorded_frames(&unlisted, None); fs::remove_file(unlisted.join(DISPLAY).join("manifest.json")).unwrap(); - assert_eq!(RecoveryManager::remux_if_needed(&unlisted).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&unlisted).unwrap()); assert_eq!(remuxed_frames(&unlisted), recorded); let damaged = make("damaged middle fragment"); @@ -286,7 +286,7 @@ fn torn_missing_or_unlisted_tails_still_remux_and_mid_recording_damage_is_refuse fs::remove_file(no_meta.join("recording-meta.json")).unwrap(); let before = layout(&no_meta); assert!(RecoveryManager::inspect_recording(&no_meta).is_none()); - assert_eq!(RecoveryManager::remux_if_needed(&no_meta).unwrap(), false); + assert!(!RecoveryManager::remux_if_needed(&no_meta).unwrap()); RecoveryManager::restore_interrupted_recovery(&no_meta).unwrap(); assert_eq!(layout(&no_meta), before); } @@ -327,7 +327,7 @@ fn a_publication_killed_at_any_step_relaunches_to_the_original_layout() { .len(), 40 ); - assert_eq!(RecoveryManager::remux_if_needed(&project).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&project).unwrap()); assert_eq!(remuxed_frames(&project), recorded); } } @@ -413,7 +413,7 @@ fn a_rollback_that_windows_refuses_is_finished_by_the_next_open() { RecoveryManager::restore_interrupted_recovery(&project).unwrap(); assert_eq!(layout(&project), before, "failure at rename {failure}"); assert!(!project.join(RECOVERY_PUBLICATION).exists()); - assert_eq!(RecoveryManager::remux_if_needed(&project).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&project).unwrap()); assert_eq!(remuxed_frames(&project), recorded); } } @@ -542,7 +542,7 @@ fn projects_an_older_build_stranded_are_restored_and_open_again() { fs::set_permissions(entry.path(), permissions).unwrap(); } } - assert_eq!(RecoveryManager::remux_if_needed(&project).unwrap(), true); + assert!(RecoveryManager::remux_if_needed(&project).unwrap()); assert_eq!(remuxed_frames(&project), recorded, "{variant:?}"); } }