From 301ebce0bb3291a44812a75ccce8f523834957ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 27 Nov 2026 22:57:16 +0300 Subject: [PATCH] Windows zero-copy encode: HwEncoder::encode_d3d11 / EncodeInput::D3d11 take a shared D3D11 BGRA/RGBA texture (NT handle, VK_KHR_external_memory_win32 D3D11_TEXTURE import, dedicated allocation, cached per handle like DMA-BUF imports) into the same GPU RGB->NV12 path; d3d11_supported(order) reports importability. Compile-checked for x86_64-pc-windows-msvc only: no Windows GPU to run it on --- crates/ec-hw/src/hw.rs | 63 +++++++ crates/ec-hw/src/lib.rs | 2 + crates/ec-vk/src/av1.rs | 26 +++ crates/ec-vk/src/h265.rs | 26 +++ crates/ec-vk/src/lib.rs | 26 +++ shims/vk-video-ffi/src/av1_encode.rs | 21 +++ shims/vk-video-ffi/src/d3d11.rs | 227 ++++++++++++++++++++++++++ shims/vk-video-ffi/src/h264_encode.rs | 21 +++ shims/vk-video-ffi/src/h265_encode.rs | 21 +++ shims/vk-video-ffi/src/lib.rs | 7 +- shims/vk-video-ffi/src/rgb_convert.rs | 18 +- shims/vk-video-ffi/src/session.rs | 40 +++-- 12 files changed, 480 insertions(+), 18 deletions(-) create mode 100644 shims/vk-video-ffi/src/d3d11.rs diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 7853b987..e6759e19 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -341,6 +341,40 @@ pub fn dup_fd(fd: std::os::fd::RawFd) -> Result { Ok(ec_vk::dup_raw_fd(fd)?) } +/// A D3D11 texture of packed 32-bit RGB pixels (DXGI_FORMAT_B8G8R8A8_UNORM or R8G8B8A8_UNORM, one mip, one layer) shared as an NT handle from `IDXGIResource1::CreateSharedHandle`. +/// +/// The encoder's import cache keys on the handle value: keep one handle open per texture for as long as frames come from it. The D3D11 writes must be finished before the call, and the texture left unwritten until its coded picture is returned. +#[cfg(windows)] +#[derive(Debug, Clone, Copy)] +pub struct D3d11Frame<'a> { + /// Shared NT handle; borrowed, not closed. + pub handle: std::os::windows::io::BorrowedHandle<'a>, + /// Width in pixels, even; at least the encoder width. + pub width: u32, + /// Height in pixels, even; at least the encoder height. + pub height: u32, + /// Byte order of each pixel. + pub order: RgbOrder, +} + +#[cfg(windows)] +impl D3d11Frame<'_> { + fn texture(&self) -> ec_vk::D3d11Texture<'_> { + ec_vk::D3d11Texture { + handle: self.handle, + width: self.width, + height: self.height, + bgr: self.order == RgbOrder::Bgra, + } + } +} + +/// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device. +#[cfg(windows)] +pub fn d3d11_supported(order: RgbOrder) -> bool { + vk_gpu().is_some_and(|gpu| ec_vk::d3d11_importable(&gpu, order == RgbOrder::Bgra)) +} + /// One picture for [`HwEncoder::submit`]. #[derive(Debug, Clone, Copy)] pub enum EncodeInput<'a> { @@ -356,6 +390,9 @@ pub enum EncodeInput<'a> { /// DMA-BUF of NV12 or P010 at the encoder size, Vulkan only. #[cfg(target_os = "linux")] DmaBufYuv(&'a DmaBufYuvFrame<'a>), + /// Shared D3D11 texture of packed RGB, Vulkan only. + #[cfg(windows)] + D3d11(&'a D3d11Frame<'a>), } #[cfg(target_os = "linux")] @@ -483,6 +520,15 @@ impl VkEncoder { }; self.submit_dma(&src, force_keyframe) } + #[cfg(windows)] + EncodeInput::D3d11(frame) => { + let src = frame.texture(); + match self { + VkEncoder::H264(e) => e.submit_d3d11(&src, force_keyframe), + VkEncoder::H265(e) => e.submit_d3d11(&src, force_keyframe), + VkEncoder::Av1(e) => e.submit_d3d11(&src, force_keyframe), + } + } } } @@ -859,6 +905,23 @@ impl HwEncoder { self.encode_dma(&src, meta) } + /// Encode one shared D3D11 texture of the source size, downscaled to the encoder size on the GPU. + #[cfg(windows)] + pub fn encode_d3d11(&mut self, frame: &D3d11Frame, meta: FrameMetadata) -> Result { + let meta = self.with_recovery(meta); + self.idle()?; + let EncInner::Vk(enc) = &mut self.inner; + vk_session_alive(self.born_epoch)?; + let src = frame.texture(); + let coded = match enc { + VkEncoder::H264(e) => e.encode_d3d11(&src, meta.force_keyframe), + VkEncoder::H265(e) => e.encode_d3d11(&src, meta.force_keyframe), + VkEncoder::Av1(e) => e.encode_d3d11(&src, meta.force_keyframe), + }?; + self.steer(coded.data.len())?; + Ok(self.vk_frame(coded, meta.timestamp)) + } + #[cfg(target_os = "linux")] fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result { let meta = self.with_recovery(meta); diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 67e4737b..a0be61e9 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -92,6 +92,8 @@ pub use error::{Error, Result}; pub use ec_vk::{DmaBufFormat, DmaBufPlane}; #[cfg(target_os = "linux")] pub use hw::{DmaBufFrame, DmaBufYuvFrame, dmabuf_modifiers, dup_fd}; +#[cfg(windows)] +pub use hw::{D3d11Frame, d3d11_supported}; pub use hw::{ Backend, Capability, CodecProfile, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput, capabilities, diff --git a/crates/ec-vk/src/av1.rs b/crates/ec-vk/src/av1.rs index a9035ba3..a95bc062 100644 --- a/crates/ec-vk/src/av1.rs +++ b/crates/ec-vk/src/av1.rs @@ -1,5 +1,7 @@ use vk_video_ffi::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; +#[cfg(windows)] +use crate::D3d11Texture; #[cfg(target_os = "linux")] use crate::DmaBuf; use crate::history::History; @@ -191,6 +193,30 @@ impl Av1Encoder { last_frame(first, rest) } + /// Submits one shared D3D11 texture of the source size without waiting. + #[cfg(windows)] + pub fn submit_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self.session.submit_d3d11(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU. + #[cfg(windows)] + pub fn encode_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result { + let first = self.submit_d3d11(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + /// Submits one DMA-BUF frame of the source size without waiting. #[cfg(target_os = "linux")] pub fn submit_dmabuf( diff --git a/crates/ec-vk/src/h265.rs b/crates/ec-vk/src/h265.rs index b5aaa81e..4c399ec4 100644 --- a/crates/ec-vk/src/h265.rs +++ b/crates/ec-vk/src/h265.rs @@ -1,5 +1,7 @@ use vk_video_ffi::{H265EncodeConfig, H265EncodeSession, H265Picture, H265Ref}; +#[cfg(windows)] +use crate::D3d11Texture; #[cfg(target_os = "linux")] use crate::DmaBuf; use crate::history::History; @@ -189,6 +191,30 @@ impl H265Encoder { last_frame(first, rest) } + /// Submits one shared D3D11 texture of the source size without waiting. + #[cfg(windows)] + pub fn submit_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self.session.submit_d3d11(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU. + #[cfg(windows)] + pub fn encode_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result { + let first = self.submit_d3d11(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + /// Submits one DMA-BUF frame of the source size without waiting. #[cfg(target_os = "linux")] pub fn submit_dmabuf( diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index c7af8f06..a6cd1d3e 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -13,6 +13,8 @@ mod history; pub use av1::{Av1Encoder, Av1EncoderConfig}; pub use h265::{H265Encoder, H265EncoderConfig}; +#[cfg(windows)] +pub use vk_video_ffi::{D3d11Texture, d3d11_importable}; #[cfg(target_os = "linux")] pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers}; pub use vk_video_ffi::{ @@ -223,6 +225,30 @@ impl H264Encoder { last_frame(first, rest) } + /// Submits one shared D3D11 texture of the source size without waiting. + #[cfg(windows)] + pub fn submit_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result, Error> { + let pic = self.next_picture(force_keyframe); + let out = self.session.submit_d3d11(src, &pic)?; + Ok(out.map(|bytes| self.coded(bytes))) + } + + /// Encodes one shared D3D11 texture of the source size (BGRA if `bgr`, else RGBA), downscaled to the encoder size on the GPU. + #[cfg(windows)] + pub fn encode_d3d11( + &mut self, + src: &D3d11Texture<'_>, + force_keyframe: bool, + ) -> Result { + let first = self.submit_d3d11(src, force_keyframe)?; + let rest = self.flush()?; + last_frame(first, rest) + } + /// Submits one DMA-BUF frame of the source size without waiting. #[cfg(target_os = "linux")] pub fn submit_dmabuf( diff --git a/shims/vk-video-ffi/src/av1_encode.rs b/shims/vk-video-ffi/src/av1_encode.rs index fd35350d..69c64cfc 100644 --- a/shims/vk-video-ffi/src/av1_encode.rs +++ b/shims/vk-video-ffi/src/av1_encode.rs @@ -294,6 +294,27 @@ impl Av1EncodeSession { self.encode_uploaded(pic) } + /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. + #[cfg(windows)] + pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &Av1Picture) -> Result>, Error> { + self.check(pic)?; + self.enc.upload_d3d11(src)?; + self.encode_uploaded(pic) + } + + /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. + #[cfg(windows)] + pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &Av1Picture) -> Result, Error> { + self.submit_d3d11(src, pic)?; + self.enc.flush_last() + } + + /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once. + #[cfg(windows)] + pub fn d3d11_imports(&self) -> usize { + self.enc.import_count() + } + /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. #[cfg(target_os = "linux")] pub fn dmabuf_imports(&self) -> usize { diff --git a/shims/vk-video-ffi/src/d3d11.rs b/shims/vk-video-ffi/src/d3d11.rs new file mode 100644 index 00000000..8d49087a --- /dev/null +++ b/shims/vk-video-ffi/src/d3d11.rs @@ -0,0 +1,227 @@ +use std::os::windows::io::{AsRawHandle, BorrowedHandle}; + +use vulkanalia::prelude::v1_3::*; +use vulkanalia::vk::KhrExternalMemoryWin32ExtensionDeviceCommands; + +use crate::session::{memory_type, vk}; +use crate::{Error, Gpu}; + +const CACHE_SIZE: usize = 16; +const HANDLE_TYPE: vk::ExternalMemoryHandleTypeFlags = + vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE; + +/// A D3D11 texture of DXGI_FORMAT_B8G8R8A8_UNORM or R8G8B8A8_UNORM pixels shared as an NT handle (`IDXGIResource1::CreateSharedHandle`), one mip and one array layer. +/// +/// The import cache keys on the handle value: keep one handle open per texture while sending frames from it. The D3D11 writes must be complete (flushed and finished) before the call, and the texture must not be written again until the coded picture comes back. +#[derive(Debug, Clone, Copy)] +pub struct D3d11Texture<'a> { + /// Shared NT handle of the texture; borrowed, not closed. + pub handle: BorrowedHandle<'a>, + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// B8G8R8A8 when true, R8G8B8A8 otherwise. + pub bgr: bool, +} + +fn format(bgr: bool) -> vk::Format { + if bgr { + vk::Format::B8G8R8A8_UNORM + } else { + vk::Format::R8G8B8A8_UNORM + } +} + +/// Whether a [`D3d11Texture`] of this byte order can be imported on `gpu`. +pub fn d3d11_importable(gpu: &Gpu, bgr: bool) -> bool { + if !gpu + .device() + .extensions() + .contains(&vk::KHR_EXTERNAL_MEMORY_WIN32_EXTENSION.name) + { + return false; + } + let mut external_info = vk::PhysicalDeviceExternalImageFormatInfo::builder() + .handle_type(HANDLE_TYPE) + .build(); + let info = vk::PhysicalDeviceImageFormatInfo2::builder() + .format(format(bgr)) + .type_(vk::ImageType::_2D) + .tiling(vk::ImageTiling::OPTIMAL) + .usage(vk::ImageUsageFlags::TRANSFER_SRC) + .push_next(&mut external_info) + .build(); + let mut external = vk::ExternalImageFormatProperties::builder().build(); + let mut props = vk::ImageFormatProperties2::builder() + .push_next(&mut external) + .build(); + let ok = unsafe { + gpu.instance() + .get_physical_device_image_format_properties2(gpu.physical(), &info, &mut props) + .is_ok() + }; + ok && external + .external_memory_properties + .external_memory_features + .contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE) +} + +#[derive(PartialEq, Eq)] +struct Key { + handle: usize, + width: u32, + height: u32, + bgr: bool, +} + +impl Key { + fn new(src: &D3d11Texture) -> Self { + Key { + handle: src.handle.as_raw_handle() as usize, + width: src.width, + height: src.height, + bgr: src.bgr, + } + } +} + +struct Import { + image: vk::Image, + memory: vk::DeviceMemory, + id: u64, +} + +impl Import { + fn new(gpu: &Gpu, src: &D3d11Texture, id: u64) -> Result { + if !d3d11_importable(gpu, src.bgr) { + return Err(Error::Unsupported("D3D11 texture import".into())); + } + if src.width == 0 || src.height == 0 { + return Err(Error::Invalid("D3D11 texture size".into())); + } + let d = gpu.device(); + let mut external = vk::ExternalMemoryImageCreateInfo::builder() + .handle_types(HANDLE_TYPE) + .build(); + let info = vk::ImageCreateInfo::builder() + .image_type(vk::ImageType::_2D) + .format(format(src.bgr)) + .extent(vk::Extent3D { + width: src.width, + height: src.height, + depth: 1, + }) + .mip_levels(1) + .array_layers(1) + .samples(vk::SampleCountFlags::_1) + .tiling(vk::ImageTiling::OPTIMAL) + .usage(vk::ImageUsageFlags::TRANSFER_SRC) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED) + .push_next(&mut external) + .build(); + let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? }; + match import_memory(gpu, image, src.handle) { + Ok(memory) => Ok(Import { image, memory, id }), + Err(e) => { + unsafe { d.destroy_image(image, None) }; + Err(e) + } + } + } + + fn destroy(&self, d: &Device) { + unsafe { + d.destroy_image(self.image, None); + d.free_memory(self.memory, None); + } + } +} + +fn import_memory( + gpu: &Gpu, + image: vk::Image, + handle: BorrowedHandle, +) -> Result { + let d = gpu.device(); + let req = unsafe { d.get_image_memory_requirements(image) }; + let raw = handle.as_raw_handle(); + let mut props = vk::MemoryWin32HandlePropertiesKHR::default(); + let bits = + match unsafe { d.get_memory_win32_handle_properties_khr(HANDLE_TYPE, raw, &mut props) } { + Ok(()) => req.memory_type_bits & props.memory_type_bits, + Err(_) => req.memory_type_bits, + }; + let index = memory_type(gpu, bits, vk::MemoryPropertyFlags::empty())?; + let mut import = vk::ImportMemoryWin32HandleInfoKHR::builder() + .handle_type(HANDLE_TYPE) + .handle(raw) + .build(); + let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder() + .image(image) + .build(); + let alloc = vk::MemoryAllocateInfo::builder() + .allocation_size(req.size) + .memory_type_index(index) + .push_next(&mut dedicated) + .push_next(&mut import) + .build(); + let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? }; + if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } { + unsafe { d.free_memory(memory, None) }; + return Err(e); + } + Ok(memory) +} + +#[derive(Default)] +pub(crate) struct ImportCache { + entries: Vec<(Key, Import)>, + next_id: u64, + pub(crate) count: usize, +} + +impl ImportCache { + pub(crate) fn get( + &mut self, + gpu: &Gpu, + src: &D3d11Texture, + busy: &[u64], + ) -> Result<(vk::Image, u64), Error> { + let key = Key::new(src); + match self.entries.iter().position(|(k, _)| *k == key) { + Some(i) => { + let entry = self.entries.remove(i); + self.entries.push(entry); + } + None => { + if self.entries.len() == CACHE_SIZE { + let i = self + .entries + .iter() + .position(|(_, import)| !busy.contains(&import.id)) + .ok_or_else(|| { + Error::Invalid("D3D11 import cache is full of in-flight imports".into()) + })?; + let (_, old) = self.entries.remove(i); + old.destroy(gpu.device()); + } + self.next_id += 1; + let import = Import::new(gpu, src, self.next_id)?; + self.count += 1; + self.entries.push((key, import)); + } + } + self.entries + .last() + .map(|(_, import)| (import.image, import.id)) + .ok_or_else(|| Error::Invalid("D3D11 import cache".into())) + } + + pub(crate) fn destroy(&self, d: &Device) { + for (_, import) in &self.entries { + import.destroy(d); + } + } +} diff --git a/shims/vk-video-ffi/src/h264_encode.rs b/shims/vk-video-ffi/src/h264_encode.rs index a02c9e0b..0a935ade 100644 --- a/shims/vk-video-ffi/src/h264_encode.rs +++ b/shims/vk-video-ffi/src/h264_encode.rs @@ -391,6 +391,27 @@ impl H264EncodeSession { self.encode_uploaded(pic) } + /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. + #[cfg(windows)] + pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H264Picture) -> Result>, Error> { + self.check(pic)?; + self.enc.upload_d3d11(src)?; + self.encode_uploaded(pic) + } + + /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. + #[cfg(windows)] + pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H264Picture) -> Result, Error> { + self.submit_d3d11(src, pic)?; + self.enc.flush_last() + } + + /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once. + #[cfg(windows)] + pub fn d3d11_imports(&self) -> usize { + self.enc.import_count() + } + /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. #[cfg(target_os = "linux")] pub fn dmabuf_imports(&self) -> usize { diff --git a/shims/vk-video-ffi/src/h265_encode.rs b/shims/vk-video-ffi/src/h265_encode.rs index dc65c36d..2ef85b6b 100644 --- a/shims/vk-video-ffi/src/h265_encode.rs +++ b/shims/vk-video-ffi/src/h265_encode.rs @@ -336,6 +336,27 @@ impl H265EncodeSession { self.encode_uploaded(pic) } + /// Encodes one picture from a shared D3D11 texture of BGRA or RGBA pixels, downscaled to the encoder size. + #[cfg(windows)] + pub fn submit_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result>, Error> { + self.check(pic)?; + self.enc.upload_d3d11(src)?; + self.encode_uploaded(pic) + } + + /// Encodes one picture from a shared D3D11 texture synchronously and returns its coded bytes. + #[cfg(windows)] + pub fn encode_d3d11(&mut self, src: &crate::D3d11Texture<'_>, pic: &H265Picture) -> Result, Error> { + self.submit_d3d11(src, pic)?; + self.enc.flush_last() + } + + /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once. + #[cfg(windows)] + pub fn d3d11_imports(&self) -> usize { + self.enc.import_count() + } + /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once. #[cfg(target_os = "linux")] pub fn dmabuf_imports(&self) -> usize { diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index 341d0962..3a8885e8 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -8,6 +8,8 @@ use std::sync::Arc; mod av1_decode; mod av1_encode; +#[cfg(windows)] +mod d3d11; #[cfg(target_os = "linux")] mod dmabuf; mod h264_decode; @@ -27,6 +29,8 @@ pub use av1_decode::{ }; pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; pub use session::DPB_SLOTS; +#[cfg(windows)] +pub use d3d11::{D3d11Texture, d3d11_importable}; #[cfg(target_os = "linux")] pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers}; pub use vp9_decode::{ @@ -65,7 +69,7 @@ use vk::KhrVideoQueueExtensionInstanceCommands; use vulkanalia::loader::LibloadingLoader; use vulkanalia::prelude::v1_3::*; -const WANTED: [vk::Extension; 15] = [ +const WANTED: [vk::Extension; 16] = [ vk::KHR_VIDEO_QUEUE_EXTENSION, vk::KHR_VIDEO_ENCODE_QUEUE_EXTENSION, vk::KHR_VIDEO_DECODE_QUEUE_EXTENSION, @@ -81,6 +85,7 @@ const WANTED: [vk::Extension; 15] = [ vk::KHR_EXTERNAL_MEMORY_FD_EXTENSION, vk::EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION, vk::EXT_QUEUE_FAMILY_FOREIGN_EXTENSION, + vk::KHR_EXTERNAL_MEMORY_WIN32_EXTENSION, ]; /// Errors from opening a GPU or probing it. diff --git a/shims/vk-video-ffi/src/rgb_convert.rs b/shims/vk-video-ffi/src/rgb_convert.rs index fa7fd4b2..b8b0e73e 100644 --- a/shims/vk-video-ffi/src/rgb_convert.rs +++ b/shims/vk-video-ffi/src/rgb_convert.rs @@ -22,8 +22,8 @@ pub(crate) enum Input<'a> { stride: usize, bgr: bool, }, - #[cfg(target_os = "linux")] - DmaBuf { + #[cfg(any(target_os = "linux", windows))] + Imported { image: vk::Image, width: usize, height: usize, @@ -36,16 +36,16 @@ impl Input<'_> { match *self { Input::Nv12 { .. } | Input::P010 { .. } => None, Input::Rgb { bgr, .. } => Some(bgr), - #[cfg(target_os = "linux")] - Input::DmaBuf { bgr, .. } => Some(bgr), + #[cfg(any(target_os = "linux", windows))] + Input::Imported { bgr, .. } => Some(bgr), } } pub(crate) fn source_image(&self) -> Option { match *self { Input::Nv12 { .. } | Input::P010 { .. } | Input::Rgb { .. } => None, - #[cfg(target_os = "linux")] - Input::DmaBuf { image, .. } => Some(image), + #[cfg(any(target_os = "linux", windows))] + Input::Imported { image, .. } => Some(image), } } } @@ -299,7 +299,11 @@ impl RgbConverter { .dst_access_mask(vk::AccessFlags2::TRANSFER_READ) .old_layout(vk::ImageLayout::GENERAL) .new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL) - .src_queue_family_index(vk::QUEUE_FAMILY_FOREIGN_EXT) + .src_queue_family_index(if cfg!(windows) { + vk::QUEUE_FAMILY_EXTERNAL + } else { + vk::QUEUE_FAMILY_FOREIGN_EXT + }) .dst_queue_family_index(family) .image(image) .subresource_range(color_range()) diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 51c4e4ca..a3693bc2 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -8,7 +8,7 @@ use vulkanalia::vk::{ #[cfg(target_os = "linux")] use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, release}; -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", windows))] use crate::rgb_convert::check_size; use crate::rgb_convert::{Input, RgbConverter}; use crate::rgb_decode::{Params, RgbPass}; @@ -863,7 +863,7 @@ struct Slot { upload: Lane, ready: vk::Semaphore, encoded: vk::Semaphore, - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] import: Option, } @@ -917,13 +917,13 @@ impl Slot { upload: Lane::new(&gpu, upload_family)?, ready: semaphore(d)?, encoded: semaphore(d)?, - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] import: None, }) } fn retire(&mut self) { - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] { self.import = None; } @@ -944,6 +944,8 @@ pub(crate) struct Encoder { pub(crate) dpb: [Image; DPB_SLOTS], #[cfg(target_os = "linux")] pub(crate) imports: ImportCache, + #[cfg(windows)] + pub(crate) imports: crate::d3d11::ImportCache, slots: [Slot; FLIGHT], cur: usize, next: usize, @@ -1010,7 +1012,7 @@ impl Encoder { coded: false, bitstream_len, dpb, - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] imports: Default::default(), slots, cur: 0, @@ -1096,8 +1098,8 @@ impl Encoder { rgb.reserve(&gpu, width, height)?; rgb.load(data, stride); } - #[cfg(target_os = "linux")] - Input::DmaBuf { width, height, .. } => { + #[cfg(any(target_os = "linux", windows))] + Input::Imported { width, height, .. } => { self.slots[k].rgb.reserve(&gpu, width, height)?; } } @@ -1172,7 +1174,7 @@ impl Encoder { let (image, planes, id) = self.imports.get(&gpu, src, &busy)?; let k = self.next; let result = match (src.format, planes) { - (DmaBufFormat::Bgrx | DmaBufFormat::Rgbx, _) => self.upload(Input::DmaBuf { + (DmaBufFormat::Bgrx | DmaBufFormat::Rgbx, _) => self.upload(Input::Imported { image, width, height, @@ -1189,6 +1191,24 @@ impl Encoder { result } + #[cfg(windows)] + pub(crate) fn upload_d3d11(&mut self, src: &crate::d3d11::D3d11Texture) -> Result<(), Error> { + let gpu = self.vs.gpu.clone(); + let (width, height) = (src.width as usize, src.height as usize); + check_size(self.input, (width, height))?; + let busy: Vec = self.slots.iter().filter_map(|s| s.import).collect(); + let (image, id) = self.imports.get(&gpu, src, &busy)?; + let k = self.next; + self.upload(Input::Imported { + image, + width, + height, + bgr: src.bgr, + })?; + self.slots[k].import = Some(id); + Ok(()) + } + #[cfg(target_os = "linux")] fn check_planar(&self, src: &DmaBuf) -> Result<(), Error> { let ten_bit = src.format == DmaBufFormat::P010; @@ -1336,7 +1356,7 @@ impl Encoder { slot.upload.submit_with(&[], &[slot.ready]) } - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] pub(crate) fn import_count(&self) -> usize { self.imports.count } @@ -1485,7 +1505,7 @@ impl Drop for Encoder { for img in &self.dpb { img.destroy(d); } - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", windows))] self.imports.destroy(d); for slot in self.slots.iter_mut() { unsafe {