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 864d4653720..b1c341e9638 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 { @@ -334,6 +336,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,10 +348,19 @@ impl Default for SegmentedVideoEncoderConfig { bpp: H264EncoderBuilder::QUALITY_BPP, output_size: None, prefer_videotoolbox_hw_input: false, + d3d11_device: None, } } } +#[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, @@ -462,7 +475,27 @@ impl SegmentedVideoEncoder { } else { None }; - #[cfg(not(target_os = "macos"))] + #[cfg(target_os = "windows")] + 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) => { + 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, error.to_string()) + } + } + } + None => (None, String::new()), + }; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] let hw_attempt: Option = None; let encoder = match hw_attempt { @@ -527,6 +560,8 @@ impl SegmentedVideoEncoder { pending_fallback: None, unrecovered_codec_failure: None, flush_failure: None, + #[cfg(windows)] + d3d11_status, }; if write_behind { @@ -583,6 +618,64 @@ 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 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() { + 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!( + encoder = %encoder_name, + "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 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)] + 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_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 new file mode 100644 index 00000000000..f4c6f6bafc4 --- /dev/null +++ b/crates/enc-ffmpeg/src/video/d3d11_hw.rs @@ -0,0 +1,319 @@ +//! `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::{ + 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; + +#[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("D3D11 device context: {0}")] + DeviceInit(String), + #[error("Failed to allocate a D3D11 hardware frames context")] + FramesAllocation, + #[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 { + 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, + 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 {} + +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); + 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::DeviceInit(av_error(device_init))); + } + + 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 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 = 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; + 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(av_error(init_result))); + } + + Ok(Self { + device_ctx, + frames_ctx, + qsv_frames: null_mut(), + width, + height, + }) + } + } + + /// # Safety + /// `encoder_ctx` must be a valid, not-yet-opened `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(frames); + } + } + + /// # Safety + /// 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, + 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); + } + 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) + } + } +} + +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 6f10c31278f..5db6fa30698 100644 --- a/crates/enc-ffmpeg/src/video/h264.rs +++ b/crates/enc-ffmpeg/src/video/h264.rs @@ -13,6 +13,10 @@ 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}; use crate::video::isolated_self_test; @@ -87,10 +91,57 @@ 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)] +struct D3d11EncoderTarget<'a> { + frames_ctx: *mut ffmpeg::sys::AVBufferRef, + pixel: ffmpeg::format::Pixel, + hw_frames: &'a D3d11HwFrames, +} + +#[cfg(windows)] +fn open_d3d11_encoder( + target: D3d11EncoderTarget<'_>, + 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(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); + 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; + 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); + 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 +414,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 +457,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 +645,147 @@ 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 { + 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 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( + &input_config, + self.preset, + self.encoder_priority_override, + self.is_export, + None, + ); + let mut failures = Vec::new(); + for (codec, encoder_options) in candidates { + let codec_name = codec.name().to_string(); + 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; + } + }; + let hardware_session = + is_hardware_h264(&codec_name).then(|| HardwareEncoderSession::begin(&codec_name)); + match open_d3d11_encoder( + D3d11EncoderTarget { + frames_ctx, + pixel, + hw_frames: &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, + sw_format = D3d11SwFormat::Nv12.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: pixel, + 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, + }); + } + Err(error) => { + drop(hardware_session); + hw_frames.clear_qsv(); + let text = match &error { + H264EncoderError::FFmpeg(inner) => inner.to_string(), + other => other.to_string(), + }; + debug!( + encoder = %codec_name, + error = %text, + "D3D11 texture input open failed" + ); + failures.push(format!("{codec_name}: {text}")); + } + } + } + Err(H264EncoderError::D3d11HwInput(if failures.is_empty() { + "no hardware encoder accepted the D3D11 texture".to_string() + } else { + failures.join("; ") + })) + } + pub fn build_standalone(self) -> Result { let input_config = self.input_config; let (raw_width, raw_height) = self @@ -1063,6 +1259,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 +1309,35 @@ impl H264Encoder { self.videotoolbox_hw.is_some() } + #[cfg(windows)] + pub fn is_d3d11_hw_input(&self) -> bool { + 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 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)] + 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 +1399,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..5a2091860cd 100644 --- a/crates/enc-ffmpeg/src/video/mod.rs +++ b/crates/enc-ffmpeg/src/video/mod.rs @@ -1,6 +1,10 @@ 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; pub mod h264_packet; pub mod hardware_crash; @@ -10,6 +14,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/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 new file mode 100644 index 00000000000..5f73aa55a49 --- /dev/null +++ b/crates/recording/examples/d3d11-texture-encode-benchmark.rs @@ -0,0 +1,576 @@ +//! `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::time::{Duration, Instant}; + + 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::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 SOURCES: usize = 4; + const FPS: u32 = 60; + const FRAME_TICK_US: u64 = 1_000_000 / 60; + + #[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 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; + 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, + ); + } + } + + 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( + 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, + encoder: String, + sw: String, + ring_capacity: Option, + ring_high_water: Option, + } + + 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 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 { + let frame = readback_frame(device, sources, staging, info, &mut reusable, &mut last, i); + encoder + .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; + let frame = readback_frame( + device, + sources, + staging, + info, + &mut reusable, + &mut last, + index, + ); + encoder + .queue_frame(frame, frame_timestamp(index)) + .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, + encoder: encoder_name, + sw: "frames rgba".to_string(), + ring_capacity: None, + ring_high_water: None, + } + } + + 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 {}", + ring.capacity(), + ring.high_water() + ) + } + + fn run_texture( + dir: &Path, + device: &Device, + sources: &[ID3D11Texture2D], + info: VideoInfo, + ) -> Result { + 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() + }, + ) + .map_err(|error| error.to_string())?; + let encoder_name = encoder.codec_name(); + if !encoder.is_d3d11_hw_input() { + return Err(format!("{} encoder {encoder_name}", encoder.d3d11_status())); + } + 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 { + 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 { + 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); + encoder + .finish() + .map_err(|error| texture_refusal(&ring, &encoder_name, &sw, &error.to_string()))?; + let decoded = decode_count(&assemble(dir)); + Ok(Run { + wall, + cpu, + decoded, + encoder: encoder_name, + sw, + ring_capacity: Some(ring.capacity()), + ring_high_water: Some(ring.high_water()), + }) + } + + 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(); + 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); + 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"); + 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}{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::>() + ); + } + + pub fn run() { + ffmpeg::init().ok(); + 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} 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, FPS); + 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_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"); + 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) { + Ok(texture) => { + if texture.decoded != expected { + failed = true; + } + texture_runs.push(texture); + } + Err(reason) => { + if texture_refusal.is_none() { + texture_refusal = Some(reason); + } + } + } + } + let label = format!("{width}x{height}"); + report(&label, "readback", &readback_runs); + 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"); + std::process::exit(1); + } + } +} diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs index 48d0ae69e84..300ebd11937 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 } @@ -633,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 { @@ -784,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 new file mode 100644 index 00000000000..e1b88c0559d --- /dev/null +++ b/crates/recording/src/output_pipeline/d3d11_texture_ring.rs @@ -0,0 +1,458 @@ +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_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::core::Interface; + +use super::texture_slots::{TEXTURE_RING_CAPACITY, TextureSlots}; + +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) }; + } + } +} + +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 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, + }) + } + + pub(crate) fn is_unusable(&self) -> bool { + 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() + .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 fn resubmit_last(&mut self) -> Option<(*mut c_void, D3d11TextureLifetime)> { + self.repeat_last()?.into_submit() + } + + 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.refuse("odd or zero size"); + return None; + } + let mut desc = D3D11_TEXTURE2D_DESC::default(); + unsafe { src.GetDesc(&mut desc) }; + 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.refuse("size changed"); + return None; + } + if self.textures.is_empty() + && let Err(error) = self.allocate(width, height) + { + self.refuse(error); + return None; + } + 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.refuse("device removed"); + return None; + } + self.slots.hold(slot); + self.last = Some(slot); + 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 { + let slot = self.last?; + let texture = self.textures.get(slot as usize)?; + self.slots.hold(slot); + Some(self.prepared(slot, texture)) + } + + 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, + } + } + Err(last) + } + + 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, + }), + } + } +} + +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/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..4643fa99fbe 100644 --- a/crates/recording/src/output_pipeline/mod.rs +++ b/crates/recording/src/output_pipeline/mod.rs @@ -1,5 +1,9 @@ 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; @@ -13,6 +17,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..938cf4da722 --- /dev/null +++ b/crates/recording/src/output_pipeline/texture_slots.rs @@ -0,0 +1,163 @@ +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::Duration; + +/// 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. +/// +/// 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], + 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 { + (0..TEXTURE_RING_CAPACITY) + .find(|&slot| self.holds[slot as usize].load(Ordering::Acquire) == 0) + } + + pub(crate) fn hold(&self, slot: u32) { + 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) { + let previous = self.holds[slot as usize].fetch_sub(1, Ordering::AcqRel); + if previous == 1 { + self.busy.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 the_ring_outlasts_amf_inflight_and_reuses_a_released_slot() { + let slots = TextureSlots::new(); + 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; + 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, 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:?}"); } }