use std::ffi::c_void;
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
use std::ptr::NonNull;
use windows::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
use windows::Win32::System::Threading::GetCurrentProcess;
#[derive(Debug)]
pub struct SharedHandleFrame {
handle: OwnedHandle,
width: u32,
height: u32,
format: wgpu::TextureFormat,
}
impl SharedHandleFrame {
#[must_use]
pub unsafe fn duplicate(
handle: NonNull<c_void>,
width: u32,
height: u32,
format: wgpu::TextureFormat,
) -> Self {
let mut duplicate = HANDLE::default();
unsafe {
DuplicateHandle(
GetCurrentProcess(),
HANDLE(handle.as_ptr()),
GetCurrentProcess(),
&raw mut duplicate,
0,
false,
DUPLICATE_SAME_ACCESS,
)
.expect("failed to duplicate the shared texture handle");
}
Self {
handle: unsafe { OwnedHandle::from_raw_handle(duplicate.0) },
width,
height,
format,
}
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub const fn format(&self) -> wgpu::TextureFormat {
self.format
}
#[must_use]
pub fn import(&self, device: &wgpu::Device) -> wgpu::Texture {
let descriptor = wgpu::TextureDescriptor {
label: Some("wgpu_external_frame_shared_handle"),
size: wgpu::Extent3d {
width: self.width,
height: self.height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
};
let hal_device = unsafe {
device
.as_hal::<wgpu::hal::api::Dx12>()
.expect("a shared texture handle requires a Direct3D 12 device")
};
let mut resource = None;
unsafe {
hal_device
.raw_device()
.OpenSharedHandle::<ID3D12Resource>(
HANDLE(self.handle.as_raw_handle()),
&raw mut resource,
)
.expect("Direct3D 12 failed to open the shared texture handle");
}
let resource = resource.expect("the shared handle did not contain a D3D12 texture");
let hal_texture = unsafe {
<wgpu::hal::api::Dx12 as wgpu::hal::Api>::Device::texture_from_raw(
resource,
self.format,
wgpu::TextureDimension::D2,
descriptor.size,
1,
1,
)
};
unsafe {
device.create_texture_from_hal::<wgpu::hal::api::Dx12>(
hal_texture,
&descriptor,
wgpu::TextureUses::COPY_SRC,
)
}
}
}