forge
Explore
Log in

Don't you dare go Hollow

Windows: ec_hw::D3d11Pool copies captured D3D11 frames (WGC) into a ring of four shared NT-handle textures (CopyResource, Flush, event-query wait) and returns the D3d11Frame for encode_d3d11, so callers need no unsafe; imports key on a per-texture id instead of the handle value (a closed and reused handle can no longer hit a stale import). windows 0.62.2 as windows-capture 2.0.1. d3d11_pool example: verified on a WARP device (shared copies read back identical, ids cycle); the Vulkan import half still untested on Windows hardware

Browse files at this commit

9b677004c74b0939c4368504f5723748301bacc7Ahmet Kaan GümüşParent: 301ebce
Cargo.lockmodified+105 -0
@@ -1899,6 +1899,7 @@ dependencies = [
1899 "ec-h264-syntax",1899 "ec-h264-syntax",
1900 "ec-h265-syntax",1900 "ec-h265-syntax",
1901 "vulkanalia",1901 "vulkanalia",
1902+ "windows",
1902 ]1903 ]
1903 1904
1904 [[package]]1905 [[package]]
@@ -2018,12 +2019,116 @@ version = "0.1.2"
2018 source = "registry+https://github.com/rust-lang/crates.io-index"2019 source = "registry+https://github.com/rust-lang/crates.io-index"
2019 checksum = "d107c80dd656e1a2c254dfb1d57ece73b7f515b8a8684c270c23cab68f4a440d"2020 checksum = "d107c80dd656e1a2c254dfb1d57ece73b7f515b8a8684c270c23cab68f4a440d"
2020 2021
2022+[[package]]
2023+name = "windows"
2024+version = "0.62.2"
2025+source = "registry+https://github.com/rust-lang/crates.io-index"
2026+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
2027+dependencies = [
2028+ "windows-collections",
2029+ "windows-core",
2030+ "windows-future",
2031+ "windows-numerics",
2032+]
2033+
2034+[[package]]
2035+name = "windows-collections"
2036+version = "0.3.2"
2037+source = "registry+https://github.com/rust-lang/crates.io-index"
2038+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
2039+dependencies = [
2040+ "windows-core",
2041+]
2042+
2043+[[package]]
2044+name = "windows-core"
2045+version = "0.62.2"
2046+source = "registry+https://github.com/rust-lang/crates.io-index"
2047+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
2048+dependencies = [
2049+ "windows-implement",
2050+ "windows-interface",
2051+ "windows-link",
2052+ "windows-result",
2053+ "windows-strings",
2054+]
2055+
2056+[[package]]
2057+name = "windows-future"
2058+version = "0.3.2"
2059+source = "registry+https://github.com/rust-lang/crates.io-index"
2060+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
2061+dependencies = [
2062+ "windows-core",
2063+ "windows-link",
2064+ "windows-threading",
2065+]
2066+
2067+[[package]]
2068+name = "windows-implement"
2069+version = "0.60.2"
2070+source = "registry+https://github.com/rust-lang/crates.io-index"
2071+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
2072+dependencies = [
2073+ "proc-macro2",
2074+ "quote",
2075+ "syn 2.0.119",
2076+]
2077+
2078+[[package]]
2079+name = "windows-interface"
2080+version = "0.59.3"
2081+source = "registry+https://github.com/rust-lang/crates.io-index"
2082+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
2083+dependencies = [
2084+ "proc-macro2",
2085+ "quote",
2086+ "syn 2.0.119",
2087+]
2088+
2021 [[package]]2089 [[package]]
2022 name = "windows-link"2090 name = "windows-link"
2023 version = "0.2.1"2091 version = "0.2.1"
2024 source = "registry+https://github.com/rust-lang/crates.io-index"2092 source = "registry+https://github.com/rust-lang/crates.io-index"
2025 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"2093 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
2026 2094
2095+[[package]]
2096+name = "windows-numerics"
2097+version = "0.3.1"
2098+source = "registry+https://github.com/rust-lang/crates.io-index"
2099+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
2100+dependencies = [
2101+ "windows-core",
2102+ "windows-link",
2103+]
2104+
2105+[[package]]
2106+name = "windows-result"
2107+version = "0.4.1"
2108+source = "registry+https://github.com/rust-lang/crates.io-index"
2109+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
2110+dependencies = [
2111+ "windows-link",
2112+]
2113+
2114+[[package]]
2115+name = "windows-strings"
2116+version = "0.5.1"
2117+source = "registry+https://github.com/rust-lang/crates.io-index"
2118+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
2119+dependencies = [
2120+ "windows-link",
2121+]
2122+
2123+[[package]]
2124+name = "windows-threading"
2125+version = "0.2.1"
2126+source = "registry+https://github.com/rust-lang/crates.io-index"
2127+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
2128+dependencies = [
2129+ "windows-link",
2130+]
2131+
2027 [[package]]2132 [[package]]
2028 name = "wit-bindgen"2133 name = "wit-bindgen"
2029 version = "0.57.1"2134 version = "0.57.1"
crates/ec-hw/src/hw.rsmodified+31 -1
@@ -343,12 +343,14 @@ pub fn dup_fd(fd: std::os::fd::RawFd) -> Result<std::os::fd::OwnedFd> {
343 343
344 /// 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`.344 /// 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`.
345 ///345 ///
346-/// 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.346+/// [`D3d11Pool::submit`] makes these. The encoder's import cache keys on `id`, unique per texture. The D3D11 writes must be finished before the call, and the texture left unwritten until its coded picture is returned.
347 #[cfg(windows)]347 #[cfg(windows)]
348 #[derive(Debug, Clone, Copy)]348 #[derive(Debug, Clone, Copy)]
349 pub struct D3d11Frame<'a> {349 pub struct D3d11Frame<'a> {
350 /// Shared NT handle; borrowed, not closed.350 /// Shared NT handle; borrowed, not closed.
351 pub handle: std::os::windows::io::BorrowedHandle<'a>,351 pub handle: std::os::windows::io::BorrowedHandle<'a>,
352+ /// Identity of the texture, unique for the process lifetime.
353+ pub id: u64,
352 /// Width in pixels, even; at least the encoder width.354 /// Width in pixels, even; at least the encoder width.
353 pub width: u32,355 pub width: u32,
354 /// Height in pixels, even; at least the encoder height.356 /// Height in pixels, even; at least the encoder height.
@@ -362,6 +364,7 @@ impl D3d11Frame<'_> {
362 fn texture(&self) -> ec_vk::D3d11Texture<'_> {364 fn texture(&self) -> ec_vk::D3d11Texture<'_> {
363 ec_vk::D3d11Texture {365 ec_vk::D3d11Texture {
364 handle: self.handle,366 handle: self.handle,
367+ id: self.id,
365 width: self.width,368 width: self.width,
366 height: self.height,369 height: self.height,
367 bgr: self.order == RgbOrder::Bgra,370 bgr: self.order == RgbOrder::Bgra,
@@ -369,6 +372,33 @@ impl D3d11Frame<'_> {
369 }372 }
370 }373 }
371 374
375+/// Copies captured D3D11 frames into a ring of shared textures for [`HwEncoder::encode_d3d11`], waiting for each copy to finish. Use it on the thread that owns the device's immediate context (the capture callback).
376+#[cfg(windows)]
377+pub struct D3d11Pool(ec_vk::D3d11Pool);
378+
379+#[cfg(windows)]
380+impl D3d11Pool {
381+ /// A pool on the device that produces the frames.
382+ pub fn new(device: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Device) -> Result<Self> {
383+ Ok(D3d11Pool(ec_vk::D3d11Pool::new(device)?))
384+ }
385+
386+ /// Copies `frame` (B8G8R8A8 or R8G8B8A8, one mip, one layer) into the next shared texture. The result is valid until the pool reuses that texture, four calls later.
387+ pub fn submit(
388+ &mut self,
389+ frame: &ec_vk::windows::Win32::Graphics::Direct3D11::ID3D11Texture2D,
390+ ) -> Result<D3d11Frame<'_>> {
391+ let t = self.0.submit(frame)?;
392+ Ok(D3d11Frame {
393+ handle: t.handle,
394+ id: t.id,
395+ width: t.width,
396+ height: t.height,
397+ order: if t.bgr { RgbOrder::Bgra } else { RgbOrder::Rgba },
398+ })
399+ }
400+}
401+
372 /// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device.402 /// Whether [`HwEncoder::encode_d3d11`] can import textures of `order` on this machine's Vulkan device.
373 #[cfg(windows)]403 #[cfg(windows)]
374 pub fn d3d11_supported(order: RgbOrder) -> bool {404 pub fn d3d11_supported(order: RgbOrder) -> bool {
crates/ec-hw/src/lib.rsmodified+1 -1
@@ -93,7 +93,7 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane};
93 #[cfg(target_os = "linux")]93 #[cfg(target_os = "linux")]
94 pub use hw::{DmaBufFrame, DmaBufYuvFrame, dmabuf_modifiers, dup_fd};94 pub use hw::{DmaBufFrame, DmaBufYuvFrame, dmabuf_modifiers, dup_fd};
95 #[cfg(windows)]95 #[cfg(windows)]
96-pub use hw::{D3d11Frame, d3d11_supported};96+pub use hw::{D3d11Frame, D3d11Pool, d3d11_supported};
97 pub use hw::{97 pub use hw::{
98 Backend, Capability, CodecProfile, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame,98 Backend, Capability, CodecProfile, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame,
99 RgbOrder, RgbOutput, capabilities,99 RgbOrder, RgbOutput, capabilities,
crates/ec-vk/src/lib.rsmodified+1 -1
@@ -14,7 +14,7 @@ mod history;
14 pub use av1::{Av1Encoder, Av1EncoderConfig};14 pub use av1::{Av1Encoder, Av1EncoderConfig};
15 pub use h265::{H265Encoder, H265EncoderConfig};15 pub use h265::{H265Encoder, H265EncoderConfig};
16 #[cfg(windows)]16 #[cfg(windows)]
17-pub use vk_video_ffi::{D3d11Texture, d3d11_importable};17+pub use vk_video_ffi::{D3d11Pool, D3d11Texture, d3d11_importable, windows};
18 #[cfg(target_os = "linux")]18 #[cfg(target_os = "linux")]
19 pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers};19 pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers};
20 pub use vk_video_ffi::{20 pub use vk_video_ffi::{
shims/vk-video-ffi/Cargo.tomlmodified+12 -0
@@ -8,7 +8,19 @@ authors.workspace = true
8 [dependencies]8 [dependencies]
9 vulkanalia = { version = "0.35", features = ["libloading"] }9 vulkanalia = { version = "0.35", features = ["libloading"] }
10 10
11+[target.'cfg(windows)'.dependencies]
12+windows = { version = "0.62.2", features = [
13+ "Win32_Foundation",
14+ "Win32_Security",
15+ "Win32_Graphics_Direct3D11",
16+ "Win32_Graphics_Dxgi",
17+ "Win32_Graphics_Dxgi_Common",
18+] }
19+
11 [dev-dependencies]20 [dev-dependencies]
12 ec-av1-syntax.workspace = true21 ec-av1-syntax.workspace = true
13 ec-h264-syntax.workspace = true22 ec-h264-syntax.workspace = true
14 ec-h265-syntax.workspace = true23 ec-h265-syntax.workspace = true
24+
25+[target.'cfg(windows)'.dev-dependencies]
26+windows = { version = "0.62.2", features = ["Win32_Graphics_Direct3D"] }
shims/vk-video-ffi/examples/d3d11_pool.rsadded+111 -0
@@ -0,0 +1,111 @@
1+#[cfg(windows)]
2+fn main() {
3+ use std::os::windows::io::AsRawHandle;
4+
5+ use vk_video_ffi::D3d11Pool;
6+ use windows::Win32::Foundation::{HANDLE, HMODULE};
7+ use windows::Win32::Graphics::Direct3D::D3D_DRIVER_TYPE_WARP;
8+ use windows::Win32::Graphics::Direct3D11::{
9+ D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_MAP_READ,
10+ D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC,
11+ D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING, D3D11CreateDevice, ID3D11Device, ID3D11Device1,
12+ ID3D11Texture2D,
13+ };
14+ use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};
15+ use windows::core::Interface;
16+
17+ let (w, h) = (256u32, 144u32);
18+ let mut device: Option<ID3D11Device> = None;
19+ unsafe {
20+ D3D11CreateDevice(
21+ None,
22+ D3D_DRIVER_TYPE_WARP,
23+ HMODULE::default(),
24+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,
25+ None,
26+ D3D11_SDK_VERSION,
27+ Some(&mut device),
28+ None,
29+ None,
30+ )
31+ .expect("WARP device");
32+ }
33+ let device = device.expect("device");
34+ let context = unsafe { device.GetImmediateContext() }.expect("context");
35+ let desc = |usage, cpu: u32, bind: u32| D3D11_TEXTURE2D_DESC {
36+ Width: w,
37+ Height: h,
38+ MipLevels: 1,
39+ ArraySize: 1,
40+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,
41+ SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
42+ Usage: usage,
43+ BindFlags: bind,
44+ CPUAccessFlags: cpu,
45+ MiscFlags: 0,
46+ };
47+ let mut pool = D3d11Pool::new(&device).expect("pool");
48+ let mut ids = Vec::new();
49+ for round in 0..6u32 {
50+ let pixels: Vec<u8> = (0..w * h * 4).map(|i| (i * 7 + round * 13) as u8).collect();
51+ let init = D3D11_SUBRESOURCE_DATA {
52+ pSysMem: pixels.as_ptr().cast(),
53+ SysMemPitch: w * 4,
54+ SysMemSlicePitch: 0,
55+ };
56+ let mut src: Option<ID3D11Texture2D> = None;
57+ unsafe {
58+ device
59+ .CreateTexture2D(&desc(D3D11_USAGE_DEFAULT, 0, 8), Some(&init), Some(&mut src))
60+ .expect("source texture");
61+ }
62+ let src = src.expect("source");
63+ let frame = pool.submit(&src).expect("submit");
64+ ids.push(frame.id);
65+ let dev1: ID3D11Device1 = device.cast().expect("ID3D11Device1");
66+ let opened: ID3D11Texture2D =
67+ unsafe { dev1.OpenSharedResource1(HANDLE(frame.handle.as_raw_handle())) }
68+ .expect("OpenSharedResource1");
69+ let mut staging: Option<ID3D11Texture2D> = None;
70+ unsafe {
71+ device
72+ .CreateTexture2D(
73+ &desc(D3D11_USAGE_STAGING, D3D11_CPU_ACCESS_READ.0 as u32, 0),
74+ None,
75+ Some(&mut staging),
76+ )
77+ .expect("staging");
78+ }
79+ let staging = staging.expect("staging");
80+ let mut got = vec![0u8; pixels.len()];
81+ unsafe {
82+ context.CopyResource(&staging, &opened);
83+ let mut map = D3D11_MAPPED_SUBRESOURCE::default();
84+ context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut map)).expect("map");
85+ for y in 0..h as usize {
86+ let row = std::slice::from_raw_parts(
87+ map.pData.cast::<u8>().add(y * map.RowPitch as usize),
88+ w as usize * 4,
89+ );
90+ got[y * w as usize * 4..][..w as usize * 4].copy_from_slice(row);
91+ }
92+ context.Unmap(&staging, 0);
93+ }
94+ println!(
95+ "round {round} id {} {}x{} bgr {} {}",
96+ frame.id,
97+ frame.width,
98+ frame.height,
99+ frame.bgr,
100+ if got == pixels { "identical" } else { "DIFFERS" }
101+ );
102+ }
103+ println!("ids {ids:?}");
104+ match vk_video_ffi::Gpu::open() {
105+ Ok(gpu) => println!("vulkan: importable bgr {}", vk_video_ffi::d3d11_importable(&gpu, true)),
106+ Err(e) => println!("vulkan: {e}"),
107+ }
108+}
109+
110+#[cfg(not(windows))]
111+fn main() {}
shims/vk-video-ffi/src/av1_encode.rsmodified+1 -1
@@ -309,7 +309,7 @@ impl Av1EncodeSession {
309 self.enc.flush_last()309 self.enc.flush_last()
310 }310 }
311 311
312- /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once.312+ /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once.
313 #[cfg(windows)]313 #[cfg(windows)]
314 pub fn d3d11_imports(&self) -> usize {314 pub fn d3d11_imports(&self) -> usize {
315 self.enc.import_count()315 self.enc.import_count()
shims/vk-video-ffi/src/d3d11.rsmodified+155 -4
@@ -1,4 +1,17 @@
1-use std::os::windows::io::{AsRawHandle, BorrowedHandle};1+use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle};
2+
3+use windows::Win32::Graphics::Direct3D11::{
4+ D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_QUERY_DESC, D3D11_QUERY_EVENT,
5+ D3D11_RESOURCE_MISC_SHARED, D3D11_RESOURCE_MISC_SHARED_NTHANDLE, D3D11_TEXTURE2D_DESC,
6+ D3D11_USAGE_DEFAULT, ID3D11Device, ID3D11DeviceContext, ID3D11Query, ID3D11Texture2D,
7+};
8+use windows::Win32::Graphics::Dxgi::Common::{
9+ DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC,
10+};
11+use windows::Win32::Graphics::Dxgi::{
12+ DXGI_SHARED_RESOURCE_READ, DXGI_SHARED_RESOURCE_WRITE, IDXGIResource1,
13+};
14+use windows::core::{Interface, PCWSTR};
2 15
3 use vulkanalia::prelude::v1_3::*;16 use vulkanalia::prelude::v1_3::*;
4 use vulkanalia::vk::KhrExternalMemoryWin32ExtensionDeviceCommands;17 use vulkanalia::vk::KhrExternalMemoryWin32ExtensionDeviceCommands;
@@ -12,11 +25,13 @@ const HANDLE_TYPE: vk::ExternalMemoryHandleTypeFlags =
12 25
13 /// 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.26 /// 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.
14 ///27 ///
15-/// 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.28+/// The import cache keys on `id`: give every texture its own, never reused ([`D3d11Pool`] does). 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.
16 #[derive(Debug, Clone, Copy)]29 #[derive(Debug, Clone, Copy)]
17 pub struct D3d11Texture<'a> {30 pub struct D3d11Texture<'a> {
18 /// Shared NT handle of the texture; borrowed, not closed.31 /// Shared NT handle of the texture; borrowed, not closed.
19 pub handle: BorrowedHandle<'a>,32 pub handle: BorrowedHandle<'a>,
33+ /// Identity of the texture, unique for the process lifetime.
34+ pub id: u64,
20 /// Width in pixels.35 /// Width in pixels.
21 pub width: u32,36 pub width: u32,
22 /// Height in pixels.37 /// Height in pixels.
@@ -69,7 +84,7 @@ pub fn d3d11_importable(gpu: &Gpu, bgr: bool) -> bool {
69 84
70 #[derive(PartialEq, Eq)]85 #[derive(PartialEq, Eq)]
71 struct Key {86 struct Key {
72- handle: usize,87+ id: u64,
73 width: u32,88 width: u32,
74 height: u32,89 height: u32,
75 bgr: bool,90 bgr: bool,
@@ -78,7 +93,7 @@ struct Key {
78 impl Key {93 impl Key {
79 fn new(src: &D3d11Texture) -> Self {94 fn new(src: &D3d11Texture) -> Self {
80 Key {95 Key {
81- handle: src.handle.as_raw_handle() as usize,96+ id: src.id,
82 width: src.width,97 width: src.width,
83 height: src.height,98 height: src.height,
84 bgr: src.bgr,99 bgr: src.bgr,
@@ -225,3 +240,139 @@ impl ImportCache {
225 }240 }
226 }241 }
227 }242 }
243+
244+const POOL_SIZE: usize = 4;
245+
246+struct Shared {
247+ texture: ID3D11Texture2D,
248+ handle: OwnedHandle,
249+ desc: D3D11_TEXTURE2D_DESC,
250+ id: u64,
251+}
252+
253+static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
254+
255+/// Copies frames (a Windows.Graphics.Capture surface, for one) into a ring of shared NT-handle textures the encoder imports.
256+///
257+/// Call [`D3d11Pool::submit`] on the thread that owns the device's immediate context, such as the capture callback.
258+pub struct D3d11Pool {
259+ device: ID3D11Device,
260+ context: ID3D11DeviceContext,
261+ query: ID3D11Query,
262+ ring: Vec<Shared>,
263+ next: usize,
264+}
265+
266+fn d3d(e: windows::core::Error, call: &str) -> Error {
267+ Error::Invalid(format!("{call}: {e}"))
268+}
269+
270+impl D3d11Pool {
271+ /// A pool on the device that produces the frames.
272+ pub fn new(device: &ID3D11Device) -> Result<Self, Error> {
273+ let context = unsafe { device.GetImmediateContext() }.map_err(|e| d3d(e, "GetImmediateContext"))?;
274+ let desc = D3D11_QUERY_DESC {
275+ Query: D3D11_QUERY_EVENT,
276+ MiscFlags: 0,
277+ };
278+ let mut query = None;
279+ unsafe { device.CreateQuery(&desc, Some(&mut query)) }.map_err(|e| d3d(e, "CreateQuery"))?;
280+ let query = query.ok_or_else(|| Error::Invalid("CreateQuery returned no query".into()))?;
281+ Ok(D3d11Pool {
282+ device: device.clone(),
283+ context,
284+ query,
285+ ring: Vec::new(),
286+ next: 0,
287+ })
288+ }
289+
290+ /// Copies `frame` (B8G8R8A8 or R8G8B8A8, one mip, one layer, not multisampled) into the next shared texture and waits for the copy to finish. The result stays valid until the pool hands out the same texture again, [`POOL_SIZE`] calls later.
291+ pub fn submit(&mut self, frame: &ID3D11Texture2D) -> Result<D3d11Texture<'_>, Error> {
292+ let mut src = D3D11_TEXTURE2D_DESC::default();
293+ unsafe { frame.GetDesc(&mut src) };
294+ let bgr = match src.Format {
295+ DXGI_FORMAT_B8G8R8A8_UNORM => true,
296+ DXGI_FORMAT_R8G8B8A8_UNORM => false,
297+ _ => return Err(Error::Unsupported(format!("D3D11 frame format {}", src.Format.0))),
298+ };
299+ if src.MipLevels != 1 || src.ArraySize != 1 || src.SampleDesc.Count != 1 {
300+ return Err(Error::Invalid("D3D11 frame must have one mip, one layer, one sample".into()));
301+ }
302+ let desc = D3D11_TEXTURE2D_DESC {
303+ Width: src.Width,
304+ Height: src.Height,
305+ MipLevels: 1,
306+ ArraySize: 1,
307+ Format: src.Format,
308+ SampleDesc: DXGI_SAMPLE_DESC {
309+ Count: 1,
310+ Quality: 0,
311+ },
312+ Usage: D3D11_USAGE_DEFAULT,
313+ BindFlags: (D3D11_BIND_SHADER_RESOURCE.0 | D3D11_BIND_RENDER_TARGET.0) as u32,
314+ CPUAccessFlags: 0,
315+ MiscFlags: (D3D11_RESOURCE_MISC_SHARED.0 | D3D11_RESOURCE_MISC_SHARED_NTHANDLE.0) as u32,
316+ };
317+ let k = self.next;
318+ self.next = (k + 1) % POOL_SIZE;
319+ if self.ring.get(k).is_none_or(|s| s.desc != desc) {
320+ let shared = self.shared(&desc)?;
321+ if k < self.ring.len() {
322+ self.ring[k] = shared;
323+ } else {
324+ self.ring.push(shared);
325+ }
326+ }
327+ let shared = &self.ring[k];
328+ let mut done = windows::core::BOOL(0);
329+ unsafe {
330+ self.context.CopyResource(&shared.texture, frame);
331+ self.context.End(&self.query);
332+ self.context.Flush();
333+ while done.0 == 0 {
334+ self.context
335+ .GetData(
336+ &self.query,
337+ Some((&raw mut done).cast()),
338+ size_of::<windows::core::BOOL>() as u32,
339+ 0,
340+ )
341+ .map_err(|e| d3d(e, "GetData"))?;
342+ if done.0 == 0 {
343+ std::thread::yield_now();
344+ }
345+ }
346+ }
347+ Ok(D3d11Texture {
348+ handle: shared.handle.as_handle(),
349+ id: shared.id,
350+ width: src.Width,
351+ height: src.Height,
352+ bgr,
353+ })
354+ }
355+
356+ fn shared(&self, desc: &D3D11_TEXTURE2D_DESC) -> Result<Shared, Error> {
357+ let mut texture = None;
358+ unsafe { self.device.CreateTexture2D(desc, None, Some(&mut texture)) }
359+ .map_err(|e| d3d(e, "CreateTexture2D"))?;
360+ let texture = texture.ok_or_else(|| Error::Invalid("CreateTexture2D returned no texture".into()))?;
361+ let resource: IDXGIResource1 = texture.cast().map_err(|e| d3d(e, "IDXGIResource1"))?;
362+ let raw = unsafe {
363+ resource.CreateSharedHandle(
364+ None,
365+ DXGI_SHARED_RESOURCE_READ.0 | DXGI_SHARED_RESOURCE_WRITE.0,
366+ PCWSTR::null(),
367+ )
368+ }
369+ .map_err(|e| d3d(e, "CreateSharedHandle"))?;
370+ let handle = unsafe { OwnedHandle::from_raw_handle(raw.0) };
371+ Ok(Shared {
372+ texture,
373+ handle,
374+ desc: *desc,
375+ id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
376+ })
377+ }
378+}
shims/vk-video-ffi/src/h264_encode.rsmodified+1 -1
@@ -406,7 +406,7 @@ impl H264EncodeSession {
406 self.enc.flush_last()406 self.enc.flush_last()
407 }407 }
408 408
409- /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once.409+ /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once.
410 #[cfg(windows)]410 #[cfg(windows)]
411 pub fn d3d11_imports(&self) -> usize {411 pub fn d3d11_imports(&self) -> usize {
412 self.enc.import_count()412 self.enc.import_count()
shims/vk-video-ffi/src/h265_encode.rsmodified+1 -1
@@ -351,7 +351,7 @@ impl H265EncodeSession {
351 self.enc.flush_last()351 self.enc.flush_last()
352 }352 }
353 353
354- /// Number of D3D11 texture imports made so far; a texture re-used by handle is imported once.354+ /// Number of D3D11 texture imports made so far; a texture re-used by id is imported once.
355 #[cfg(windows)]355 #[cfg(windows)]
356 pub fn d3d11_imports(&self) -> usize {356 pub fn d3d11_imports(&self) -> usize {
357 self.enc.import_count()357 self.enc.import_count()
shims/vk-video-ffi/src/lib.rsmodified+3 -1
@@ -30,7 +30,9 @@ pub use av1_decode::{
30 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};30 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
31 pub use session::DPB_SLOTS;31 pub use session::DPB_SLOTS;
32 #[cfg(windows)]32 #[cfg(windows)]
33-pub use d3d11::{D3d11Texture, d3d11_importable};33+pub use d3d11::{D3d11Pool, D3d11Texture, d3d11_importable};
34+#[cfg(windows)]
35+pub use windows;
34 #[cfg(target_os = "linux")]36 #[cfg(target_os = "linux")]
35 pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers};37 pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, dup_raw_fd, read_dmabuf, rgb_import_modifiers};
36 pub use vp9_decode::{38 pub use vp9_decode::{