Skip to main content

velox_engine/renderers/wgpu/interop/
mod.rs

1//! 跨 API / 跨框架零拷贝 GPU 显存纹理句柄桥接层(`velox_engine::renderers::wgpu::interop`)。
2//!
3//! 统一封装四大原生桌面/移动平台的显存导出句柄与 GPU 同步原语:
4//! - **Windows (DX12)**:`ID3D12Resource` 共享堆 + Win32 NT `HANDLE` + 共享 `ID3D12Fence` NT `HANDLE`;
5//! - **Linux (Vulkan)**:`VK_EXT_external_memory_dma_buf` 导出 `dma_buf` fd + DRM FourCC/Modifier + Timeline Semaphore FD;
6//! - **macOS / iOS (Metal)**:`IOSurfaceRef` + `MTLSharedEvent`;
7//! - **Android (Vulkan)**:`AHardwareBuffer*` + Sync FD。
8//!
9//! 当未启用 `gpu-interop` feature 或平台驱动不支持外部句柄导出时,自动回退为标准 `wgpu::Texture`(`ExportedHandle::InternalOnly`),
10//! 确保所有上层 [`WgpuSharedExportRenderer`](super::WgpuSharedExportRenderer) 与单元测试在任意平台均可安全运行。
11
12use ::wgpu;
13
14#[cfg(all(feature = "gpu-interop", target_os = "windows"))]
15pub(crate) mod dx12;
16#[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
17pub(crate) mod metal_iosurface;
18#[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
19pub(crate) mod vk_dmabuf;
20
21/// 跨平台导出的共享显存句柄描述符(供外部 Qt6 / GTK4 / WinUI 3 / WPF / 原生合成器零拷贝采样)。
22#[derive(Copy, Clone, Debug, PartialEq, Eq)]
23pub enum ExportedHandle {
24    /// Windows DX12 跨进程/跨 API NT `HANDLE`(由 `ID3D12Device::CreateSharedHandle` 创建,宿主通过 `OpenSharedHandle` / `ID3D11Device1::OpenSharedResource1` 打开)。
25    Win32Dx12NtHandle {
26        /// Win32 `HANDLE` 指针整数表示(`0` 表示无效)。
27        nt_handle: u64,
28        /// DXGI 像素格式数值(如 `DXGI_FORMAT_B8G8R8A8_UNORM = 87`、`DXGI_FORMAT_R8G8B8A8_UNORM = 28`)。
29        dxgi_format: u32,
30        /// 物理适配器 LUID(供宿主校验同卡)。
31        adapter_luid: [u8; 8],
32    },
33    /// Linux Vulkan / Wayland `dma_buf` 文件描述符(对接 `zwp_linux_dmabuf_v1` / `GdkDmabufTextureBuilder` / Qt RHI)。
34    LinuxDmaBuf {
35        fd: i32,
36        stride: u32,
37        offset: u32,
38        /// DRM FourCC(如 `DRM_FORMAT_ARGB8888 = 0x34325241` / `DRM_FORMAT_ABGR8888 = 0x34324241`)。
39        drm_format: u32,
40        /// DRM Format Modifier(`0` = Linear,`0x00ff_ffff_ffff_ffff` = Invalid/Implicit)。
41        modifier: u64,
42    },
43    /// Apple Metal `IOSurfaceRef` 指针与全局 `IOSurfaceID`(macOS / iOS 零拷贝共享显存)。
44    AppleIoSurface {
45        iosurface_ref: u64,
46        iosurface_id: u32,
47    },
48    /// Android NDK `AHardwareBuffer*` 原生句柄(对接 `ASurfaceTransaction_setBuffer` / Vulkan 外部内存)。
49    AndroidHardwareBuffer {
50        ahb_ptr: u64,
51    },
52    /// 内部标准 `wgpu::Texture`(未启用 `gpu-interop` 或驱动不支持外部显存导出时的安全回退模式)。
53    InternalOnly,
54}
55
56impl ExportedHandle {
57    /// 判断该句柄是否为真实的跨 API / 跨框架外部共享显存句柄。
58    #[inline(always)]
59    pub const fn is_external_shared(&self) -> bool {
60        !matches!(self, Self::InternalOnly)
61    }
62
63    /// 返回适合 C-FFI 传递的原始数值句柄(`Win32 NT HANDLE` / `dma_buf fd` / `IOSurfaceRef` / `AHB*`)。
64    #[inline(always)]
65    pub const fn raw_u64(&self) -> u64 {
66        match *self {
67            Self::Win32Dx12NtHandle { nt_handle, .. } => nt_handle,
68            Self::LinuxDmaBuf { fd, .. } => fd as u64,
69            Self::AppleIoSurface { iosurface_ref, .. } => iosurface_ref,
70            Self::AndroidHardwareBuffer { ahb_ptr } => ahb_ptr,
71            Self::InternalOnly => 0,
72        }
73    }
74}
75
76/// 跨平台外部 GPU 同步栅栏/信号量导出句柄(宿主在采样共享纹理前须等待该同步对象达到 `fence_value`)。
77#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
78pub enum ExternalSyncHandle {
79    /// Windows DX12 共享 `ID3D12Fence` NT `HANDLE`。
80    Win32Dx12FenceNtHandle(u64),
81    /// Linux Vulkan Timeline Semaphore OPAQUE_FD / SYNC_FD。
82    LinuxSemaphoreFd(i32),
83    /// Apple Metal `MTLSharedEvent` 指针句柄。
84    AppleMetalSharedEvent(u64),
85    /// Android Vulkan Sync FD。
86    AndroidSyncFd(i32),
87    /// 仅内部队列同步(无跨进程同步句柄)。
88    #[default]
89    None,
90}
91
92impl ExternalSyncHandle {
93    #[inline(always)]
94    pub const fn raw_u64(&self) -> u64 {
95        match *self {
96            Self::Win32Dx12FenceNtHandle(h) => h,
97            Self::LinuxSemaphoreFd(fd) => fd as u64,
98            Self::AppleMetalSharedEvent(p) => p,
99            Self::AndroidSyncFd(fd) => fd as u64,
100            Self::None => 0,
101        }
102    }
103}
104
105/// 平台原生显存资源句柄 RAII 守卫(与 `wgpu::Texture` 同步存活,销毁时自动释放 OS 句柄防泄漏)。
106#[allow(dead_code)]
107pub(crate) enum PlatformTextureGuard {
108    None,
109    #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
110    Dx12(dx12::Dx12SharedTextureGuard),
111    #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
112    VkDmaBuf(vk_dmabuf::VkSharedTextureGuard),
113    #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
114    MetalIoSurface(metal_iosurface::MetalIoSurfaceGuard),
115}
116
117/// 单张已分配并包装完毕的共享导出纹理槽位资源。
118pub(crate) struct ExportedTextureAlloc {
119    pub(crate) texture: wgpu::Texture,
120    pub(crate) view: wgpu::TextureView,
121    pub(crate) handle: ExportedHandle,
122    pub(crate) _guard: PlatformTextureGuard,
123}
124
125/// 跨平台 GPU 共享栅栏包装(渲染提交后在 GPU 队列上 `signal`,宿主侧异步等待或本机 CPU 等待)。
126pub(crate) enum PlatformSharedFence {
127    Fallback(core::sync::atomic::AtomicU64),
128    #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
129    Dx12(dx12::Dx12SharedFence),
130    #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
131    Vk(vk_dmabuf::VkSharedFence),
132    #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
133    Metal(metal_iosurface::MetalSharedFence),
134}
135
136impl PlatformSharedFence {
137    /// 返回可供外部宿主导入的跨 API 同步句柄。
138    pub(crate) fn export_handle(&self) -> ExternalSyncHandle {
139        match self {
140            Self::Fallback(_) => ExternalSyncHandle::None,
141            #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
142            Self::Dx12(f) => f.export_handle(),
143            #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
144            Self::Vk(f) => f.export_handle(),
145            #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
146            Self::Metal(f) => f.export_handle(),
147        }
148    }
149
150    /// 在 `wgpu::Queue` 提交完渲染命令后向共享栅栏写入单调递增的 `value`。
151    pub(crate) fn signal_on_queue(&self, device: &wgpu::Device, value: u64) {
152        match self {
153            Self::Fallback(v) => {
154                let _ = device.poll(wgpu::PollType::Poll);
155                v.store(value, core::sync::atomic::Ordering::Release);
156            }
157            #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
158            Self::Dx12(f) => f.signal_on_device(device, value),
159            #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
160            Self::Vk(f) => f.signal_on_device(device, value),
161            #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
162            Self::Metal(f) => f.signal_on_device(device, value),
163        }
164    }
165
166    /// 查询 GPU 当前已完成的最高栅栏值。
167    pub(crate) fn completed_value(&self) -> u64 {
168        match self {
169            Self::Fallback(v) => v.load(core::sync::atomic::Ordering::Acquire),
170            #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
171            Self::Dx12(f) => f.completed_value(),
172            #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
173            Self::Vk(f) => f.completed_value(),
174            #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
175            Self::Metal(f) => f.completed_value(),
176        }
177    }
178
179    /// CPU 阻塞等待直到 GPU 完成指定 `value`(或在 `timeout_ms` 超时返回 `false`)。
180    #[allow(unused_variables)]
181    pub(crate) fn wait_cpu(&self, device: &wgpu::Device, value: u64, timeout_ms: u32) -> bool {
182        match self {
183            Self::Fallback(v) => {
184                let _ = device.poll(wgpu::PollType::wait_indefinitely());
185                v.load(core::sync::atomic::Ordering::Acquire) >= value
186            }
187            #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
188            Self::Dx12(f) => f.wait_cpu(value, timeout_ms),
189            #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
190            Self::Vk(f) => f.wait_cpu(device, value, timeout_ms),
191            #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
192            Self::Metal(f) => f.wait_cpu(device, value, timeout_ms),
193        }
194    }
195}
196
197/// 按宿主物理显卡 LUID / UUID 精确初始化对齐的 [`PreparedWgpuContext`](super::PreparedWgpuContext)。
198#[cfg(feature = "gpu-interop")]
199pub(crate) fn init_aligned_wgpu_context(
200    adapter_luid: Option<[u8; 8]>,
201    device_uuid: Option<[u8; 16]>,
202) -> Option<super::PreparedWgpuContext> {
203    #[cfg(target_os = "windows")]
204    {
205        let _ = device_uuid;
206        if let Some(ctx) = dx12::init_aligned_dx12_context(adapter_luid) {
207            return Some(ctx);
208        }
209    }
210    #[cfg(any(target_os = "linux", target_os = "android"))]
211    {
212        let _ = adapter_luid;
213        if let Some(ctx) = vk_dmabuf::init_aligned_vk_context(device_uuid) {
214            return Some(ctx);
215        }
216    }
217    #[cfg(any(target_os = "macos", target_os = "ios"))]
218    {
219        let _ = (adapter_luid, device_uuid);
220        if let Some(ctx) = metal_iosurface::init_aligned_metal_context() {
221            return Some(ctx);
222        }
223    }
224    let _ = (adapter_luid, device_uuid);
225    None
226}
227
228/// 为共享导出渲染器分配单张带平台外部句柄的 `wgpu::Texture`(不支持导出时自动回退为标准离屏 `wgpu::Texture`)。
229pub(crate) fn allocate_shared_texture(
230    device: &wgpu::Device,
231    width: u32,
232    height: u32,
233    format: wgpu::TextureFormat,
234    adapter_luid: [u8; 8],
235) -> ExportedTextureAlloc {
236    let w = width.max(1);
237    let h = height.max(1);
238
239    #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
240    {
241        if let Some(alloc) = dx12::allocate_dx12_shared_texture(device, w, h, format, adapter_luid) {
242            return alloc;
243        }
244    }
245    #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
246    {
247        let _ = adapter_luid;
248        if let Some(alloc) = vk_dmabuf::allocate_vk_shared_texture(device, w, h, format) {
249            return alloc;
250        }
251    }
252    #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
253    {
254        let _ = adapter_luid;
255        if let Some(alloc) = metal_iosurface::allocate_metal_shared_texture(device, w, h, format) {
256            return alloc;
257        }
258    }
259
260    let _ = adapter_luid;
261    let texture = device.create_texture(&wgpu::TextureDescriptor {
262        label: Some("velox_shared_slot_fallback"),
263        size: wgpu::Extent3d {
264            width: w,
265            height: h,
266            depth_or_array_layers: 1,
267        },
268        mip_level_count: 1,
269        sample_count: 1,
270        dimension: wgpu::TextureDimension::D2,
271        format,
272        usage: wgpu::TextureUsages::RENDER_ATTACHMENT
273            | wgpu::TextureUsages::TEXTURE_BINDING
274            | wgpu::TextureUsages::COPY_SRC
275            | wgpu::TextureUsages::COPY_DST,
276        view_formats: &[],
277    });
278    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
279    ExportedTextureAlloc {
280        texture,
281        view,
282        handle: ExportedHandle::InternalOnly,
283        _guard: PlatformTextureGuard::None,
284    }
285}
286
287/// 创建跨平台 GPU 共享同步栅栏(Windows DX12 `ID3D12Fence` / Vulkan Timeline Semaphore / Metal SharedEvent)。
288pub(crate) fn create_shared_fence(device: &wgpu::Device) -> PlatformSharedFence {
289    #[cfg(all(feature = "gpu-interop", target_os = "windows"))]
290    {
291        if let Some(f) = dx12::Dx12SharedFence::new(device) {
292            return PlatformSharedFence::Dx12(f);
293        }
294    }
295    #[cfg(all(feature = "gpu-interop", any(target_os = "linux", target_os = "android")))]
296    {
297        if let Some(f) = vk_dmabuf::VkSharedFence::new(device) {
298            return PlatformSharedFence::Vk(f);
299        }
300    }
301    #[cfg(all(feature = "gpu-interop", any(target_os = "macos", target_os = "ios")))]
302    {
303        if let Some(f) = metal_iosurface::MetalSharedFence::new(device) {
304            return PlatformSharedFence::Metal(f);
305        }
306    }
307    let _ = device;
308    PlatformSharedFence::Fallback(core::sync::atomic::AtomicU64::new(0))
309}
310
311/// Windows DX12 诊断/测试辅助:验证导出的纹理 NT `HANDLE` 与栅栏 NT `HANDLE` 可被原生 `ID3D12Device::OpenSharedHandle` 零拷贝打开。
312#[cfg(all(feature = "gpu-interop", target_os = "windows"))]
313pub fn verify_dx12_exported_handles(
314    device: &wgpu::Device,
315    tex_nt_handle: u64,
316    fence_nt_handle: u64,
317) -> Option<(u64, u32, u64)> {
318    dx12::verify_dx12_exported_handles(device, tex_nt_handle, fence_nt_handle)
319}