From 2946872ca1bee85ad37288f45fef2a0a06b7ff61 Mon Sep 17 00:00:00 2001 From: ONEO Date: Tue, 24 Nov 2026 19:11:17 +0800 Subject: [PATCH 1/2] feat(gpu): import hardware decoders' frames as textures Co-Authored-By: Claude Opus 5.5 --- changelog.d/gpu-import-textures.md | 3 + docs/architecture/gpu.md | 11 +- docs/roadmap.md | 2 +- gpu/device.go | 20 +- gpu/external.go | 159 +++++++++ gpu/external_internal_test.go | 116 ++++++ gpu/gpu.go | 9 + internal/driver/gpu.go | 78 ++++- internal/platform/linux/gpu.go | 5 + internal/platform/linux/gpu_external.go | 112 ++++++ .../linux/gpu_external_native_test.go | 330 ++++++++++++++++++ internal/platform/linux/gpu_gl.go | 25 +- internal/platform/linux/gpu_gl_external.go | 159 +++++++++ .../platform/linux/gpu_gl_external_test.go | 113 ++++++ internal/platform/linux/gpu_gl_test.go | 4 + internal/platform/windows/gpu.go | 11 +- internal/platform/windows/gpu_d3d11_desc.go | 181 +++++++++- internal/platform/windows/gpu_d3d11_test.go | 113 ++++++ internal/platform/windows/gpu_external.go | 155 ++++++++ .../windows/gpu_external_native_test.go | 224 ++++++++++++ 20 files changed, 1807 insertions(+), 23 deletions(-) create mode 100644 changelog.d/gpu-import-textures.md create mode 100644 gpu/external.go create mode 100644 gpu/external_internal_test.go create mode 100644 internal/platform/linux/gpu_external.go create mode 100644 internal/platform/linux/gpu_external_native_test.go create mode 100644 internal/platform/linux/gpu_gl_external.go create mode 100644 internal/platform/linux/gpu_gl_external_test.go create mode 100644 internal/platform/windows/gpu_external.go create mode 100644 internal/platform/windows/gpu_external_native_test.go diff --git a/changelog.d/gpu-import-textures.md b/changelog.d/gpu-import-textures.md new file mode 100644 index 000000000..9e9e7e58e --- /dev/null +++ b/changelog.d/gpu-import-textures.md @@ -0,0 +1,3 @@ +### Added + +- Sample hardware decoders' frames in `gpu.View` without copying them, through `Device.ImportTexture`: Direct3D 11 shared textures on Windows and DMA-BUFs on Linux (#2296 by @oneo-me). diff --git a/docs/architecture/gpu.md b/docs/architecture/gpu.md index aa0ecaaed..aaadc07c5 100644 --- a/docs/architecture/gpu.md +++ b/docs/architecture/gpu.md @@ -297,6 +297,15 @@ return gpu.View{ 2. `core` bumps the surface's device generation, marks all handles from the lost `Device` invalid (subsequent writes/submits become no-ops rather than panicking), and calls `View.OnDeviceLost`. 3. When the platform restores or recreates the device/context, it emits `EventGPUDeviceReady` with the new generation and `core` invokes `View.OnReady` with a fresh `*gpu.Device` so the app rebuilds its resources cleanly. +### Imported textures + +`Device.ImportTexture` ([#2296](https://github.com/nsgo-dev/nsgo/issues/2296)) opens GPU memory another device owns, such as a hardware decoder's frame, as a sampled 2D texture without copying it; `Device.SupportsExternalTexture(kind)` (`Features.ImportD3D11Shared`, `Features.ImportDMABuf`) says whether a target can, and elsewhere it returns `ErrUnsupported`, so callers fall back to `WriteTexture`. + +- **One plane per import**: an NV12 frame is two textures, luma `FormatR8Unorm` and chroma `FormatRG8Unorm` at half size, and P010's are the import-only `FormatR16Unorm` and `FormatRG16Unorm`, which `CreateTexture` rejects. Shaders keep a plain `texture_2d` and convert YUV themselves, so no backend needs `samplerExternalOES` or a YCbCr sampler. +- **Windows**: the backend opens the NT handle with `ID3D11Device1::OpenSharedResource1` once per handle, whose planes share that resource (opening it twice can yield two resources, and the keyed mutex of one does not make the other's writes visible), and views the plane with `CreateShaderResourceView1`'s `PlaneSlice`. With `KeyedMutex`, it acquires `AcquireKey` (100 ms at most, reporting a timeout on `OnError`) before a frame whose passes bind the texture and releases `ReleaseKey` after them. +- **Linux**: the backend makes an EGLImage with `EGL_EXT_image_dma_buf_import` (naming the modifier where `_modifiers` is present) on the display `eglGetCurrentDisplay` gives inside the `GtkGLArea`'s context, and binds it with `glEGLImageTargetTexture2DOES`; a GLX context reports no support. +- **Lifetime**: the caller keeps the handle or file descriptors, open until the first frame submitted after the import completes. Imported textures are only sampled: writes, copies, readbacks and render passes on them are dropped or rejected, and they are not retained across device loss. Closing one releases what the backend opened after the frames already submitted, so a decoder's frame goes back to its pool once the `FrameFence` of the last frame that sampled it completes. + ## Web backend: WebGPU with WebGL 2 fallback (Decision 2) On the web (`internal/platform/web`, [#1108](https://github.com/nsgo-dev/nsgo/issues/1108)), a `gpu.View` mounts a `` sized to physical pixels (`width * pixelRatio`, `height * pixelRatio`), reusing the canvas sizing and animation-frame lifecycle already established in `internal/platform/web/shader.go`: @@ -450,7 +459,7 @@ Tracked as staged follow-up issues once Stage 1 (`#1105`–`#1110`) is green on - Dynamic uniform buffer offsets, ring-buffered streaming updates, mipmap generation, and GPU timing/profiling queries. - **Compute, interop, and Stage 2 backends ([#1234](https://github.com/nsgo-dev/nsgo/issues/1234)–[#1240](https://github.com/nsgo-dev/nsgo/issues/1240))**: - Compute pipelines (`@compute @workgroup_size(X, Y, Z)`, `var`, `var`, `texture_storage_2d`, `Device.CreateComputePipeline`, `Encoder.BeginComputePass`, `Dispatch` / `DispatchIndirect`, `Device.ReadBuffer`) with `Device.Capabilities().Features.Compute` / `Device.SupportsCompute()` capability queries ([#1234](https://github.com/nsgo-dev/nsgo/issues/1234)). Compute shaders compile to MSL (`kernel void`), HLSL SM 5.0 (`[numthreads]` + `StructuredBuffer`/`RWStructuredBuffer`), WGSL, and GLSL 4.30 / ES 3.10 (`layout(local_size_*) in;` + `std430` SSBOs), and dispatch runs today on the headless software device (`gpu.NewSoftwareRenderer`, `nsgotest`). The Metal, Direct3D 11, WebGPU, WebGL 2, OpenGL and Android GLES backends still report `Features.Compute` false until each wires compute dispatch. Where `SupportsCompute()` is false, creating compute pipelines, read/write storage or storage texture bindings, dispatching, or `ReadBuffer` returns `gpu.ErrUnsupported`, and a compute pass records nothing; applications should fall back to CPU updates (`Device.WriteBuffer`) or ping-pong render-to-texture passes. - - Zero-copy / shared-texture interop with `core.Image`, `core.Video`, and pixel buffers; + - Zero-copy interop with `core.Image`, `core.Video`, and pixel buffers, and importing `CVPixelBuffer` / IOSurface frames on Metal ([#1105](https://github.com/nsgo-dev/nsgo/issues/1105)); [imported textures](#imported-textures) cover Direct3D 11 and DMA-BUF; - Stage 2 **Android Vulkan** (`purego` once bionic `dlopen` and cross-process surface sharing land) and Stage 2 **HarmonyOS** GPU surface support. ### Completion criteria diff --git a/docs/roadmap.md b/docs/roadmap.md index 55ec7d0e5..acbf5a850 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -199,7 +199,7 @@ The [games plan (#1047)](https://github.com/nsgo-dev/nsgo/issues/1047) targets m | Audio scheduling and latency | [#1223](https://github.com/nsgo-dev/nsgo/issues/1223), [audio timing](architecture/audio.md#timing) | Windows schedules sounds against XAudio2's clock, which its backend does not yet do (`CanSchedule` is false there), and reads its output latency, which it reports as unknown; Android cannot schedule a start and answers the output-latency query at once as unknown, as `SoundPool` and `MediaPlayer` expose no route latency ([#1097](https://github.com/nsgo-dev/nsgo/issues/1097)); two scheduled starts 500 ms apart are measured against recorded output on Windows | | Crash reports outside native apps | [#1226](https://github.com/nsgo-dev/nsgo/issues/1226), [crash reports](architecture/application.md#crash-reports) | Web, HarmonyOS and mini-program hosts have a persistent place for reports and return them on the next launch | | HarmonyOS system edge gestures | [#1218](https://github.com/nsgo-dev/nsgo/issues/1218) | Establish whether ArkUI offers a supported way to defer navigation gestures over game controls, as iOS and Android do | -| GPU view for 3D | [#1059](https://github.com/nsgo-dev/nsgo/issues/1059), [GPU view](architecture/gpu.md) ([#1104](https://github.com/nsgo-dev/nsgo/issues/1104)), [#1105](https://github.com/nsgo-dev/nsgo/issues/1105)–[#1110](https://github.com/nsgo-dev/nsgo/issues/1110), [#1189](https://github.com/nsgo-dev/nsgo/issues/1189), [#1191](https://github.com/nsgo-dev/nsgo/issues/1191), [#1195](https://github.com/nsgo-dev/nsgo/issues/1195), [#1196](https://github.com/nsgo-dev/nsgo/issues/1196), [#1240](https://github.com/nsgo-dev/nsgo/issues/1240), [#1193](https://github.com/nsgo-dev/nsgo/issues/1193), [#1237](https://github.com/nsgo-dev/nsgo/issues/1237), [#1238](https://github.com/nsgo-dev/nsgo/issues/1238), [#1239](https://github.com/nsgo-dev/nsgo/issues/1239), [#1234](https://github.com/nsgo-dev/nsgo/issues/1234), [#1192](https://github.com/nsgo-dev/nsgo/issues/1192), [#1235](https://github.com/nsgo-dev/nsgo/issues/1235), [#1236](https://github.com/nsgo-dev/nsgo/issues/1236), [#1190](https://github.com/nsgo-dev/nsgo/issues/1190), [#1194](https://github.com/nsgo-dev/nsgo/issues/1194) | A depth-tested mesh draws with textures and lighting in `gpu.View` on macOS, iOS, Windows, Linux, Web (WebGPU with WebGL 2 fallback), Android (GLES 3.0; Vulkan in Stage 2) and headless `nsgotest`/CI with zero UI view-tree commits per frame; so far the portable `gpu` package (including offscreen color/depth render targets, depth-only shadow passes, readable `texture_depth_2d` textures, and `sampler_comparison` / `textureSampleCompare` / `textureSampleCompareLevel` shadow sampling, compressed BCn/ETC2/ASTC texture formats with capability queries and pure-Go software decoding, per-pass GPU timing queries, zero-cost-in-release debug labels/groups, and compute pipelines with read/write storage buffers, storage textures, `Device.SupportsCompute()` and `Device.ReadBuffer`, 4x MSAA render targets with pass-end and explicit `ResolveTexture` resolves, stencil and full pipeline state, up to four color targets (MRT), HDR float and sRGB formats, and cubemaps, 2D texture arrays, mip chain uploads and LOD sampling), `core`/`driver`/`engine` off-commit surface hook, vertex+fragment+compute WGSL/`shaderir` compilation and MSL/HLSL/GLSL (3.30/4.30/ES 3.00/ES 3.10)/WGSL emitters, instanced drawing (`VertexStepInstance`, `StepRate`, `@builtin(instance_index)`, `DrawInstanced`/`DrawIndexedInstanced`), per-frame `RingBuffer` / dynamic uniform offsets / `FramesInFlight` `FrameFence` pipelining, and headless `nsgotest` software 3D rasterizer and compute VM with pixel, depth and buffer readback exist, as do the Metal backend on macOS and iOS ([#1105](https://github.com/nsgo-dev/nsgo/issues/1105)) and the Web GPU backend ([#1108](https://github.com/nsgo-dev/nsgo/issues/1108), WebGPU primary via WGSL with automatic WebGL 2 fallback via GLSL ES 3.00, verified in headless Chrome via `nsgo test -target web ./internal/platform/web` with textured offscreen draw, readback, resize, context loss/restore, and clean teardown) and the Android OpenGL ES 3.0 backend ([#1109](https://github.com/nsgo-dev/nsgo/issues/1109)) and the Windows Direct3D 11 backend ([#1106](https://github.com/nsgo-dev/nsgo/issues/1106)) and the Linux OpenGL 3.3 / ES 3.0 backend on `GtkGLArea` ([#1107](https://github.com/nsgo-dev/nsgo/issues/1107)); cross-target pixel comparison is pending. Device and context loss recovery with app-suspension gating and opt-in retained resource restoration ([#1238](https://github.com/nsgo-dev/nsgo/issues/1238)) and a persistent JSON `PipelineCache` with asynchronous pipeline precompilation ([#1239](https://github.com/nsgo-dev/nsgo/issues/1239)) are in place. Compute dispatch, pipeline stencil testing, MRT beyond one target and the extended formats (`FormatRG11B10Float`, `FormatR32Float`, `FormatRGBA32Float`, `FormatBGRA8UnormSRGB`, `FormatStencil8`) currently run only on the software device; the native backends report `Features.Compute`, `Features.StencilTest` and `Features.ExtendedFormats` false and `Limits.MaxColorAttachments` 1. Device-side mipmap generation (`Features.MipmapGeneration`) and sampler LOD clamps are software-only as well; native backends sample mip chains uploaded with `WriteTextureMip`. | +| GPU view for 3D | [#1059](https://github.com/nsgo-dev/nsgo/issues/1059), [GPU view](architecture/gpu.md) ([#1104](https://github.com/nsgo-dev/nsgo/issues/1104)), [#1105](https://github.com/nsgo-dev/nsgo/issues/1105)–[#1110](https://github.com/nsgo-dev/nsgo/issues/1110), [#1189](https://github.com/nsgo-dev/nsgo/issues/1189), [#1191](https://github.com/nsgo-dev/nsgo/issues/1191), [#1195](https://github.com/nsgo-dev/nsgo/issues/1195), [#1196](https://github.com/nsgo-dev/nsgo/issues/1196), [#1240](https://github.com/nsgo-dev/nsgo/issues/1240), [#1193](https://github.com/nsgo-dev/nsgo/issues/1193), [#1237](https://github.com/nsgo-dev/nsgo/issues/1237), [#1238](https://github.com/nsgo-dev/nsgo/issues/1238), [#1239](https://github.com/nsgo-dev/nsgo/issues/1239), [#1234](https://github.com/nsgo-dev/nsgo/issues/1234), [#1192](https://github.com/nsgo-dev/nsgo/issues/1192), [#1235](https://github.com/nsgo-dev/nsgo/issues/1235), [#1236](https://github.com/nsgo-dev/nsgo/issues/1236), [#1190](https://github.com/nsgo-dev/nsgo/issues/1190), [#1194](https://github.com/nsgo-dev/nsgo/issues/1194) | A depth-tested mesh draws with textures and lighting in `gpu.View` on macOS, iOS, Windows, Linux, Web (WebGPU with WebGL 2 fallback), Android (GLES 3.0; Vulkan in Stage 2) and headless `nsgotest`/CI with zero UI view-tree commits per frame; so far the portable `gpu` package (including offscreen color/depth render targets, depth-only shadow passes, readable `texture_depth_2d` textures, and `sampler_comparison` / `textureSampleCompare` / `textureSampleCompareLevel` shadow sampling, compressed BCn/ETC2/ASTC texture formats with capability queries and pure-Go software decoding, per-pass GPU timing queries, zero-cost-in-release debug labels/groups, and compute pipelines with read/write storage buffers, storage textures, `Device.SupportsCompute()` and `Device.ReadBuffer`, 4x MSAA render targets with pass-end and explicit `ResolveTexture` resolves, stencil and full pipeline state, up to four color targets (MRT), HDR float and sRGB formats, and cubemaps, 2D texture arrays, mip chain uploads and LOD sampling), `core`/`driver`/`engine` off-commit surface hook, vertex+fragment+compute WGSL/`shaderir` compilation and MSL/HLSL/GLSL (3.30/4.30/ES 3.00/ES 3.10)/WGSL emitters, instanced drawing (`VertexStepInstance`, `StepRate`, `@builtin(instance_index)`, `DrawInstanced`/`DrawIndexedInstanced`), per-frame `RingBuffer` / dynamic uniform offsets / `FramesInFlight` `FrameFence` pipelining, and headless `nsgotest` software 3D rasterizer and compute VM with pixel, depth and buffer readback exist, as do the Metal backend on macOS and iOS ([#1105](https://github.com/nsgo-dev/nsgo/issues/1105)) and the Web GPU backend ([#1108](https://github.com/nsgo-dev/nsgo/issues/1108), WebGPU primary via WGSL with automatic WebGL 2 fallback via GLSL ES 3.00, verified in headless Chrome via `nsgo test -target web ./internal/platform/web` with textured offscreen draw, readback, resize, context loss/restore, and clean teardown) and the Android OpenGL ES 3.0 backend ([#1109](https://github.com/nsgo-dev/nsgo/issues/1109)) and the Windows Direct3D 11 backend ([#1106](https://github.com/nsgo-dev/nsgo/issues/1106)) and the Linux OpenGL 3.3 / ES 3.0 backend on `GtkGLArea` ([#1107](https://github.com/nsgo-dev/nsgo/issues/1107)); cross-target pixel comparison is pending. Device and context loss recovery with app-suspension gating and opt-in retained resource restoration ([#1238](https://github.com/nsgo-dev/nsgo/issues/1238)) and a persistent JSON `PipelineCache` with asynchronous pipeline precompilation ([#1239](https://github.com/nsgo-dev/nsgo/issues/1239)) are in place. Compute dispatch, pipeline stencil testing, MRT beyond one target and the extended formats (`FormatRG11B10Float`, `FormatR32Float`, `FormatRGBA32Float`, `FormatBGRA8UnormSRGB`, `FormatStencil8`) currently run only on the software device; the native backends report `Features.Compute`, `Features.StencilTest` and `Features.ExtendedFormats` false and `Limits.MaxColorAttachments` 1. Device-side mipmap generation (`Features.MipmapGeneration`) and sampler LOD clamps are software-only as well; native backends sample mip chains uploaded with `WriteTextureMip`. `Device.ImportTexture` samples hardware decoders' frames without copying on Windows (Direct3D 11 shared textures) and Linux (DMA-BUFs over EGL) ([#2296](https://github.com/nsgo-dev/nsgo/issues/2296)); Metal (`CVPixelBuffer` / IOSurface, [#1105](https://github.com/nsgo-dev/nsgo/issues/1105)), Web, Android and the software device report `SupportsExternalTexture` false. | | Display refresh rates | [#1213](https://github.com/nsgo-dev/nsgo/issues/1213), [displays](architecture/services.md#displays-and-locale-settings) | Linux reports a panel's maximum rate where the compositor exposes its modes. watchOS and mini programs report the current display and its rate where the host exposes them | | Games on HarmonyOS | [#1117](https://github.com/nsgo-dev/nsgo/issues/1117), [#1051](https://github.com/nsgo-dev/nsgo/issues/1051), [#1113](https://github.com/nsgo-dev/nsgo/issues/1113), [#1352](https://github.com/nsgo-dev/nsgo/issues/1352), [#1512](https://github.com/nsgo-dev/nsgo/issues/1512) | **Works today:** multi-touch `OnTouch` (presentation coordinates under bound transforms), presses and long presses, scroll/pinch-zoom, physical-keyboard shortcuts via `Scope.OnKey`; 2D `core.Canvas` on ArkUI `CanvasRenderingContext2D` (paths, fills, strokes, linear/radial gradients, text, encoded/resource images, animated slots; ~62–63 FPS on emulator) and encoded/URI `core.Image`; `RequestAnimationFrame` via ArkGraphics2D `displaySync` (`expected: 60`, `min: 30, max: 120`, passing `targetTimestamp`); `KeepAwake` via ArkUI power assertion; `RequestOrientation` via `window.setPreferredOrientation` ([#2227](https://github.com/nsgo-dev/nsgo/issues/2227)). **`Env` reports:** `OS` `android`, `Idiom` phone/tablet, `Simulated` false, `HasWebView` true, `CanTakePhoto` true, `CanPlayAudio`/`CanSpeak`/`CanRecognizeSpeech`/`CanScanCode`/`SupportsCustomCursor` false. **Missing:** `OnKeyDown`/`OnKeyUp`/`KeysDown`/`KeyHeld` (#1352), `OnPan`/`OnPinch`/`OnRotation` outside scroll views, gamepads (#1049), mouse/pointer lock (#1054), `ImageSource.Pixels` ArkUI `PixelMap` bridge (#1051), `core.OffscreenImage` and `KeepImage`, conic gradients, `core.Shader` and `gpu.View` 3D (Stage 2 via `XComponent` GLES 3.0/Vulkan or ArkWeb WebGL 2, [GPU view](architecture/gpu.md)), `audio.Sound`/`audio.Player` (#1050), and haptics (`ItemHaptic`) | | Games in mini programs | [#1117](https://github.com/nsgo-dev/nsgo/issues/1117), [#1051](https://github.com/nsgo-dev/nsgo/issues/1051), [#1101](https://github.com/nsgo-dev/nsgo/issues/1101), [#1113](https://github.com/nsgo-dev/nsgo/issues/1113), [#1503](https://github.com/nsgo-dev/nsgo/issues/1503), [#1505](https://github.com/nsgo-dev/nsgo/issues/1505), [#1507](https://github.com/nsgo-dev/nsgo/issues/1507) | **Works today:** multi-touch `OnTouch`, presses, long presses, single-finger `OnPan`, two-finger `OnPinch` and `OnRotation`, with presentation touch coordinates under bound transforms, and back navigation on WeChat; 2D `core.Canvas` via `canvas2d` offscreen canvas serialized to PNG data URLs (with animated slots), `ImageSource.Pixels` in canvases on all hosts and in `core.Image` via a dedicated 2D `` on WeChat (#1101); `RequestAnimationFrame` on a 16 ms `setTimeout` loop using the graph clock. **`Env` reports:** host device `OS` with `Simulated` true, `Idiom` phone/tablet, `AppleKeys` true on iOS/macOS, `CanTakePhoto` true on mobile hosts with `chooseMedia`/`chooseImage`, `CanPlayAudio`/`CanSpeak`/`CanRecognizeSpeech`/`CanScanCode`/`HasWebView`/`SupportsCustomCursor` false. **Missing:** physical keyboard (`OnKeyDown`/`OnKeyUp`/`KeysDown`/`OnKey`), mouse/pointer lock (#1054), gamepads (#1049), transformed pointer coordinates outside touches (#1502), pixel-buffer image views on QQ/Douyin/Alipay (#1051), `core.OffscreenImage`, `core.Shader` (`nsgo_noshader`, #1507) and `gpu.View` 3D (out of scope: 2 MB package cap and no logic-layer GPU surface, [GPU view](architecture/gpu.md)), `audio.Sound`/`audio.Player` (#1050, [audio](architecture/audio.md)), display-vsync frame timing (logic layer has none, #1113), haptics, `KeepAwake`, orientation, and fitting larger game binaries within the 2 MB package limit (#1505) | diff --git a/gpu/device.go b/gpu/device.go index 34d61d92e..c43dc7882 100644 --- a/gpu/device.go +++ b/gpu/device.go @@ -331,13 +331,15 @@ func (d *Device) SupportsCompressedFormat(format TextureFormat) bool { return slices.Contains(d.compressedFormats, format) } -// SupportsFormat reports whether d can create textures in format. Compressed formats follow SupportsCompressedFormat, and the extended formats (FormatBGRA8UnormSRGB, FormatRG11B10Float, FormatR32Float, FormatRGBA32Float, FormatStencil8) require Features.ExtendedFormats. +// SupportsFormat reports whether d can create textures in format. Compressed formats follow SupportsCompressedFormat, the import-only FormatR16Unorm and FormatRG16Unorm are never created, and the extended formats (FormatBGRA8UnormSRGB, FormatRG11B10Float, FormatR32Float, FormatRGBA32Float, FormatStencil8) require Features.ExtendedFormats. func (d *Device) SupportsFormat(format TextureFormat) bool { switch { case d == nil || format == FormatUndefined: return false case format.IsCompressed(): return d.SupportsCompressedFormat(format) + case driver.GPUTextureFormat(format).IsImportOnly(): + return false case driver.GPUTextureFormat(format).IsExtended(): return d.features.ExtendedFormats default: @@ -530,6 +532,8 @@ type Texture struct { retained bool shadowWrites []retainedTextureWrite closed bool + // external marks a texture from ImportTexture, which is only sampled. + external bool } // ID returns the texture's numeric handle. @@ -2088,7 +2092,7 @@ func (d *Device) WriteBuffer(buf *Buffer, offset uint64, data []byte) { // WriteTexture copies raw texel bytes into dst according to layout. The written width is BytesPerRow / bytes-per-texel (clamped to the mip edge), and the row count follows the data length and RowsPerImage, on every backend. func (d *Device) WriteTexture(tex *Texture, dst TextureCopy, data []byte, layout DataLayout) { - if !d.alive() || tex == nil || !tex.Valid() || tex.dev != d || len(data) == 0 { + if !d.alive() || tex == nil || !tex.Valid() || tex.dev != d || tex.external || len(data) == 0 { return } cloned := slices.Clone(data) @@ -2314,7 +2318,7 @@ func (e *Encoder) BeginRenderPass(desc RenderPassDesc) *RenderPass { for i, ca := range desc.ColorAttachments { var tid, rid driver.GPUID if ca.Texture != nil { - if !ca.Texture.Valid() || ca.Texture.dev != e.dev || ca.Texture.epoch != e.epoch { + if !ca.Texture.Valid() || ca.Texture.external || ca.Texture.dev != e.dev || ca.Texture.epoch != e.epoch { invalid = true } else { tid = ca.Texture.id @@ -2519,7 +2523,7 @@ func (e *Encoder) CopyBufferToTexture(src BufferCopy, dst TextureCopy, width, he if e == nil || e.finished || e.dev == nil || !e.dev.alive() { return } - if !src.Buffer.Valid() || !dst.Texture.Valid() || src.Buffer.dev != e.dev || dst.Texture.dev != e.dev || src.Buffer.epoch != e.epoch || dst.Texture.epoch != e.epoch { + if !src.Buffer.Valid() || !dst.Texture.Valid() || dst.Texture.external || src.Buffer.dev != e.dev || dst.Texture.dev != e.dev || src.Buffer.epoch != e.epoch || dst.Texture.epoch != e.epoch { return } e.copies = append(e.copies, driver.GPUCopyOp{ @@ -2549,7 +2553,7 @@ func (e *Encoder) CopyTextureToTexture(src, dst TextureCopy, width, height, laye if e == nil || e.finished || e.dev == nil || !e.dev.alive() { return } - if !src.Texture.Valid() || !dst.Texture.Valid() || src.Texture.dev != e.dev || dst.Texture.dev != e.dev || src.Texture.epoch != e.epoch || dst.Texture.epoch != e.epoch { + if !src.Texture.Valid() || !dst.Texture.Valid() || src.Texture.external || dst.Texture.external || src.Texture.dev != e.dev || dst.Texture.dev != e.dev || src.Texture.epoch != e.epoch || dst.Texture.epoch != e.epoch { return } e.copies = append(e.copies, driver.GPUCopyOp{ @@ -2904,6 +2908,12 @@ func (d *Device) ReadTexture(tex *Texture, region TextureRegion, fn func(rgba [] } return } + if tex.external { + if fn != nil { + fn(nil, Error{Code: ErrInvalidDescriptor, Message: "ReadTexture cannot read an imported texture; render it to a texture and read that"}) + } + return + } rid := readbackIDGen.Add(1) d.opMu.Lock() d.readbacks[rid] = fn diff --git a/gpu/external.go b/gpu/external.go new file mode 100644 index 000000000..d26a87b9c --- /dev/null +++ b/gpu/external.go @@ -0,0 +1,159 @@ +package gpu + +import ( + "fmt" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// ExternalTextureKind identifies the GPU memory Device.ImportTexture opens. +type ExternalTextureKind uint8 + +const ( + // ExternalD3D11Shared is a Direct3D 11 texture another device shares through an NT handle (IDXGIResource1::CreateSharedHandle), such as a D3D11VA decoder's frame. Windows only. + ExternalD3D11Shared ExternalTextureKind = ExternalTextureKind(driver.GPUExternalD3D11Shared) + // ExternalDMABuf is a Linux DMA-BUF, such as a VAAPI surface exported with vaExportSurfaceHandle or a GBM buffer. Linux only, where GTK's GL context runs on EGL. + ExternalDMABuf ExternalTextureKind = ExternalTextureKind(driver.GPUExternalDMABuf) +) + +// DRMFormatModInvalid is DRM_FORMAT_MOD_INVALID, the ExternalTextureDesc.Modifier of a DMA-BUF whose layout its driver implies. +const DRMFormatModInvalid = driver.GPUDRMFormatModInvalid + +// DMABufPlane is one plane of a DMA-BUF: its file descriptor, byte offset and row pitch. +type DMABufPlane struct { + FD int + Offset uint32 + Pitch uint32 +} + +// ExternalTextureDesc describes a texture Device.ImportTexture opens from GPU memory another device or API owns. +// +// An import is one plane sampled as a plain 2D texture: import a planar NV12 frame as two textures, its luma as FormatR8Unorm and its chroma as FormatRG8Unorm at half the size, and convert to RGB in the shader. A 10-bit P010 frame's planes are FormatR16Unorm and FormatRG16Unorm. +// +// The caller keeps ownership of Handle and the planes' FDs: keep them open until the FrameFence of the first frame submitted after ImportTexture completes, after which the backend holds its own reference, and close them yourself. +type ExternalTextureDesc struct { + Label string + Kind ExternalTextureKind + // Width and Height are the plane's size in texels. + Width, Height uint32 + // Format is the plane's format as the shader samples it: FormatR8Unorm, FormatRG8Unorm, FormatR16Unorm, FormatRG16Unorm, FormatRGBA8Unorm or FormatBGRA8Unorm. + Format TextureFormat + + // Handle is the shared texture's NT handle (ExternalD3D11Shared). + Handle uintptr + // Plane picks the plane of an NV12 or P010 texture: 0 for luma, 1 for chroma (ExternalD3D11Shared). + Plane uint32 + // KeyedMutex makes the backend hold the texture's IDXGIKeyedMutex while a submitted frame reads it, acquiring AcquireKey and releasing ReleaseKey (ExternalD3D11Shared). The texture must have been created with D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; with both keys 0 it is a plain mutex. + KeyedMutex bool + AcquireKey uint64 + ReleaseKey uint64 + + // FourCC is the plane's single-plane DRM format: DRM_FORMAT_R8, GR88, R16, GR1616, ABGR8888, XBGR8888, ARGB8888 or XRGB8888 (ExternalDMABuf). + FourCC uint32 + // Modifier is the DRM format modifier: 0 for DRM_FORMAT_MOD_LINEAR, DRMFormatModInvalid for none (ExternalDMABuf). + Modifier uint64 + // Planes holds the plane's DMA-BUF, one (ExternalDMABuf). + Planes []DMABufPlane +} + +// SupportsExternalTexture reports whether d can import textures of kind. Where it is false, ImportTexture returns ErrUnsupported: copy the frame to memory and upload it with WriteTexture instead. +func (d *Device) SupportsExternalTexture(kind ExternalTextureKind) bool { + if d == nil { + return false + } + switch kind { + case ExternalD3D11Shared: + return d.features.ImportD3D11Shared + case ExternalDMABuf: + return d.features.ImportDMABuf + default: + return false + } +} + +// ImportTexture opens GPU memory another device or API owns, such as a hardware decoder's frame, as a sampled 2D texture scoped to cx, without copying it. The texture goes into bind groups and is sampled like any other; it cannot be written, copied, read back, rendered to or retained across device loss, so render it to a texture of your own to do those. Close releases what the backend opened, after the frames already submitted finish with it: give the frame back to its owner, such as FFmpeg's pool, once the FrameFence of the last frame that sampled it completes. +// +// The backend opens the memory when the next frame is submitted; an import it rejects, such as a handle that does not open or a format that does not match, arrives on ViewProps.OnError. +func (d *Device) ImportTexture(cx *core.Scope, desc ExternalTextureDesc) (*Texture, error) { + if !d.alive() { + return nil, Error{Code: ErrDeviceLost, Message: "device is lost or disposed"} + } + if !d.SupportsExternalTexture(desc.Kind) { + return nil, Error{Code: ErrUnsupported, Message: fmt.Sprintf("importing external textures of kind %d is not supported on this device", desc.Kind)} + } + if desc.Width == 0 || desc.Height == 0 { + return nil, Error{Code: ErrInvalidDescriptor, Message: "imported texture width and height must be positive"} + } + if d.limits.MaxTextureDimension2D > 0 && (desc.Width > d.limits.MaxTextureDimension2D || desc.Height > d.limits.MaxTextureDimension2D) { + return nil, Error{Code: ErrInvalidDescriptor, Message: fmt.Sprintf("imported texture %dx%d exceeds limit %d", desc.Width, desc.Height, d.limits.MaxTextureDimension2D)} + } + switch desc.Format { + case FormatR8Unorm, FormatRG8Unorm, FormatR16Unorm, FormatRG16Unorm, FormatRGBA8Unorm, FormatBGRA8Unorm: + default: + return nil, Error{Code: ErrInvalidDescriptor, Message: fmt.Sprintf("textures cannot be imported in format %s", desc.Format)} + } + switch desc.Kind { + case ExternalD3D11Shared: + if desc.Handle == 0 { + return nil, Error{Code: ErrInvalidDescriptor, Message: "ExternalD3D11Shared requires a shared Handle"} + } + if desc.Plane > 1 { + return nil, Error{Code: ErrInvalidDescriptor, Message: fmt.Sprintf("plane %d does not exist (0 is luma, 1 is chroma)", desc.Plane)} + } + case ExternalDMABuf: + if desc.FourCC == 0 { + return nil, Error{Code: ErrInvalidDescriptor, Message: "ExternalDMABuf requires a DRM FourCC"} + } + if len(desc.Planes) != 1 { + return nil, Error{Code: ErrInvalidDescriptor, Message: fmt.Sprintf("ExternalDMABuf imports one plane, got %d", len(desc.Planes))} + } + for i, p := range desc.Planes { + if p.FD < 0 { + return nil, Error{Code: ErrInvalidDescriptor, Message: fmt.Sprintf("DMA-BUF plane %d has no file descriptor", i)} + } + } + } + lbl := debugLabel(desc.Label) + dd := driver.GPUExternalTextureDesc{ + Label: lbl, + Kind: driver.GPUExternalTextureKind(desc.Kind), + Width: desc.Width, + Height: desc.Height, + Format: driver.GPUTextureFormat(desc.Format), + Handle: desc.Handle, + Plane: desc.Plane, + KeyedMutex: desc.KeyedMutex, + AcquireKey: desc.AcquireKey, + ReleaseKey: desc.ReleaseKey, + FourCC: desc.FourCC, + Modifier: desc.Modifier, + } + for _, p := range desc.Planes { + dd.Planes = append(dd.Planes, driver.GPUDMABufPlane{FD: p.FD, Offset: p.Offset, Pitch: p.Pitch}) + } + id := d.nextID() + d.enqueueOp(driver.GPUResourceOp{Kind: driver.GPUOpImportTexture, ID: id, External: &dd}) + tex := &Texture{ + dev: d, + id: id, + epoch: d.generation, + desc: TextureDesc{ + Label: lbl, + Dimension: Dim2D, + Width: desc.Width, + Height: desc.Height, + Layers: 1, + MipLevels: 1, + SampleCount: 1, + Format: desc.Format, + Usage: TextureSampled, + }, + external: true, + } + d.bindCleanup(cx, func() { _ = tex.Close() }) + return tex, nil +} + +// Imported reports whether t was opened by Device.ImportTexture. +func (t *Texture) Imported() bool { return t != nil && t.external } diff --git a/gpu/external_internal_test.go b/gpu/external_internal_test.go new file mode 100644 index 000000000..53e62faa8 --- /dev/null +++ b/gpu/external_internal_test.go @@ -0,0 +1,116 @@ +package gpu + +import ( + "errors" + "testing" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +func TestImportTextureUnsupported(t *testing.T) { + dev := NewSoftwareRenderer(8, 8, FormatUndefined).Device() + for _, kind := range []ExternalTextureKind{ExternalD3D11Shared, ExternalDMABuf} { + if dev.SupportsExternalTexture(kind) { + t.Errorf("software device supports importing kind %d", kind) + } + if _, err := dev.ImportTexture(nil, ExternalTextureDesc{Kind: kind, Width: 4, Height: 4, Format: FormatR8Unorm, Handle: 1, FourCC: 1, Planes: []DMABufPlane{{}}}); !errors.Is(err, ErrUnsupported) { + t.Errorf("ImportTexture of kind %d = %v, want ErrUnsupported", kind, err) + } + } + if dev.SupportsFormat(FormatR16Unorm) || dev.SupportsFormat(FormatRG16Unorm) { + t.Error("import-only formats are reported as creatable") + } + if _, err := dev.CreateTexture(nil, TextureDesc{Width: 4, Height: 4, Format: FormatR16Unorm, Usage: TextureSampled}); !errors.Is(err, ErrUnsupported) { + t.Errorf("CreateTexture(FormatR16Unorm) = %v, want ErrUnsupported", err) + } +} + +func TestImportTextureEnqueuesAndReleases(t *testing.T) { + dev := NewSoftwareRenderer(8, 8, FormatUndefined).Device() + dev.features.ImportD3D11Shared = true + dev.features.ImportDMABuf = true + var frames []driver.GPUFrame + dev.submitFn = func(f driver.GPUFrame) { + frames = append(frames, f) + if f.OnComplete != nil { + f.OnComplete() + } + } + + for name, bad := range map[string]ExternalTextureDesc{ + "no size": {Kind: ExternalD3D11Shared, Format: FormatR8Unorm, Handle: 1}, + "bad format": {Kind: ExternalD3D11Shared, Width: 4, Height: 4, Format: FormatRGBA16Float, Handle: 1}, + "no handle": {Kind: ExternalD3D11Shared, Width: 4, Height: 4, Format: FormatR8Unorm}, + "third plane": {Kind: ExternalD3D11Shared, Width: 4, Height: 4, Format: FormatR8Unorm, Handle: 1, Plane: 2}, + "no fourcc": {Kind: ExternalDMABuf, Width: 4, Height: 4, Format: FormatR8Unorm, Planes: []DMABufPlane{{FD: 3}}}, + "no planes": {Kind: ExternalDMABuf, Width: 4, Height: 4, Format: FormatR8Unorm, FourCC: 1}, + "negative fd": {Kind: ExternalDMABuf, Width: 4, Height: 4, Format: FormatR8Unorm, FourCC: 1, Planes: []DMABufPlane{{FD: -1}}}, + "over the limit": {Kind: ExternalD3D11Shared, Width: 1 << 20, Height: 4, Format: FormatR8Unorm, Handle: 1}, + } { + if _, err := dev.ImportTexture(nil, bad); !errors.Is(err, ErrInvalidDescriptor) { + t.Errorf("%s: ImportTexture = %v, want ErrInvalidDescriptor", name, err) + } + } + + tex, err := dev.ImportTexture(nil, ExternalTextureDesc{Label: "luma", Kind: ExternalD3D11Shared, Width: 16, Height: 8, Format: FormatRG16Unorm, Handle: 0x44, Plane: 1, KeyedMutex: true, AcquireKey: 1}) + if err != nil { + t.Fatal(err) + } + if !tex.Imported() || tex.Desc().Format != FormatRG16Unorm || tex.Desc().Usage != TextureSampled || tex.Desc().MipLevels != 1 { + t.Fatalf("imported texture desc = %+v", tex.Desc()) + } + plane, err := dev.ImportTexture(nil, ExternalTextureDesc{Kind: ExternalDMABuf, Width: 8, Height: 4, Format: FormatR8Unorm, FourCC: 0x20203852, Modifier: DRMFormatModInvalid, Planes: []DMABufPlane{{FD: 9, Offset: 16, Pitch: 64}}}) + if err != nil { + t.Fatal(err) + } + + // Imported textures are only sampled. + dev.WriteTexture(tex, TextureCopy{Texture: tex}, []byte{1, 2, 3, 4}, DataLayout{}) + var readErr error + dev.ReadTexture(tex, TextureRegion{Width: 1, Height: 1}, func(_ []byte, err error) { readErr = err }) + if !errors.Is(readErr, ErrInvalidDescriptor) { + t.Errorf("ReadTexture of an imported texture = %v", readErr) + } + enc := dev.BeginEncoder() + enc.CopyTextureToTexture(TextureCopy{Texture: tex}, TextureCopy{Texture: plane}, 1, 1, 1) + enc.BeginRenderPass(RenderPassDesc{ColorAttachments: []ColorAttachment{{Texture: tex}}}).End() + cb := enc.Finish() + if len(cb.copies) != 0 { + t.Errorf("a copy to or from an imported texture was recorded: %+v", cb.copies) + } + dev.Submit() + + var imports []*driver.GPUExternalTextureDesc + for _, f := range frames { + for _, op := range f.Ops { + switch op.Kind { + case driver.GPUOpImportTexture: + imports = append(imports, op.External) + case driver.GPUOpWriteTexture: + t.Errorf("a write to imported texture %d was sent", op.ID) + } + } + } + if len(imports) != 2 { + t.Fatalf("imports sent = %d, want 2", len(imports)) + } + if d := imports[0]; d.Kind != driver.GPUExternalD3D11Shared || d.Handle != 0x44 || d.Plane != 1 || !d.KeyedMutex || d.AcquireKey != 1 || d.Format != driver.GPUFormatRG16Unorm { + t.Errorf("D3D11 import = %+v", d) + } + if d := imports[1]; d.Kind != driver.GPUExternalDMABuf || d.FourCC != 0x20203852 || d.Modifier != driver.GPUDRMFormatModInvalid || len(d.Planes) != 1 || d.Planes[0] != (driver.GPUDMABufPlane{FD: 9, Offset: 16, Pitch: 64}) { + t.Errorf("DMA-BUF import = %+v", d) + } + + frames = nil + _ = tex.Close() + dev.Submit() + var destroyed bool + for _, f := range frames { + for _, op := range f.Ops { + destroyed = destroyed || (op.Kind == driver.GPUOpDestroyTexture && op.ID == tex.id) + } + } + if !destroyed { + t.Error("Close sent no GPUOpDestroyTexture") + } +} diff --git a/gpu/gpu.go b/gpu/gpu.go index 0e77ad7b1..255225c04 100644 --- a/gpu/gpu.go +++ b/gpu/gpu.go @@ -196,6 +196,10 @@ const ( FormatRGBA32Float TextureFormat = TextureFormat(driver.GPUFormatRGBA32Float) FormatStencil8 TextureFormat = TextureFormat(driver.GPUFormatStencil8) + // Import-only formats: textures from Device.ImportTexture, such as the planes of a P010 frame, have them; Device.CreateTexture does not take them. + FormatR16Unorm TextureFormat = TextureFormat(driver.GPUFormatR16Unorm) + FormatRG16Unorm TextureFormat = TextureFormat(driver.GPUFormatRG16Unorm) + // Short HDR float format aliases matching WGSL/shader shorthand. FormatRGBA16F TextureFormat = FormatRGBA16Float FormatRG11B10F TextureFormat = FormatRG11B10Float @@ -870,6 +874,9 @@ type Features struct { StencilTest bool // MipmapGeneration reports support for Device.GenerateMipmaps. Where it is false, build the chain on the CPU (GenerateMipChainRGBA) and upload each level with WriteTextureMip. MipmapGeneration bool + // ImportD3D11Shared and ImportDMABuf report support for Device.ImportTexture of ExternalD3D11Shared and ExternalDMABuf textures (Device.SupportsExternalTexture). + ImportD3D11Shared bool + ImportDMABuf bool } // DeviceCapabilities summarizes the active GPU device's limits, optional features, timing query support, and supported compressed texture formats. Targets without native compute support (WebGL 2, OpenGL ES 3.0) report Features.Compute false; check Device.SupportsCompute and use a CPU or render-pass fallback there. @@ -895,6 +902,8 @@ func featuresFromDriver(f driver.GPUFeatures) Features { ExtendedFormats: f.ExtendedFormats, StencilTest: f.StencilTest, MipmapGeneration: f.MipmapGeneration, + ImportD3D11Shared: f.ImportD3D11Shared, + ImportDMABuf: f.ImportDMABuf, } } diff --git a/internal/driver/gpu.go b/internal/driver/gpu.go index eff54d10d..ca7e24758 100644 --- a/internal/driver/gpu.go +++ b/internal/driver/gpu.go @@ -40,6 +40,9 @@ const ( GPUFormatR32Float GPUFormatRGBA32Float GPUFormatStencil8 + // The 16-bit normalized formats below exist only for imported textures, such as the planes of a P010 video frame; no device creates them (IsImportOnly). + GPUFormatR16Unorm + GPUFormatRG16Unorm ) // IsDepth reports whether f carries a depth aspect. @@ -72,6 +75,11 @@ func (f GPUTextureFormat) IsExtended() bool { } } +// IsImportOnly reports whether f is a format only imported textures have (GPUOpImportTexture). +func (f GPUTextureFormat) IsImportOnly() bool { + return f == GPUFormatR16Unorm || f == GPUFormatRG16Unorm +} + // IsCompressed reports whether f is a block-compressed GPU texture format. func (f GPUTextureFormat) IsCompressed() bool { switch f { @@ -112,7 +120,8 @@ func (f GPUTextureFormat) BlockSize() (width, height uint32) { case GPUFormatRGBA8Unorm, GPUFormatRGBA8UnormSRGB, GPUFormatBGRA8Unorm, GPUFormatRG8Unorm, GPUFormatR8Unorm, GPUFormatRGBA16Float, GPUFormatDepth24Plus, GPUFormatDepth24PlusStencil8, GPUFormatDepth32Float, - GPUFormatBGRA8UnormSRGB, GPUFormatRG11B10Float, GPUFormatR32Float, GPUFormatRGBA32Float, GPUFormatStencil8: + GPUFormatBGRA8UnormSRGB, GPUFormatRG11B10Float, GPUFormatR32Float, GPUFormatRGBA32Float, GPUFormatStencil8, + GPUFormatR16Unorm, GPUFormatRG16Unorm: return 1, 1 default: return 0, 0 @@ -151,9 +160,9 @@ func (f GPUTextureFormat) BytesPerPixel() uint32 { switch f { case GPUFormatR8Unorm: return 1 - case GPUFormatRG8Unorm: + case GPUFormatRG8Unorm, GPUFormatR16Unorm: return 2 - case GPUFormatRGBA8Unorm, GPUFormatRGBA8UnormSRGB, GPUFormatBGRA8Unorm, GPUFormatBGRA8UnormSRGB, GPUFormatRG11B10Float, GPUFormatR32Float: + case GPUFormatRGBA8Unorm, GPUFormatRGBA8UnormSRGB, GPUFormatBGRA8Unorm, GPUFormatBGRA8UnormSRGB, GPUFormatRG11B10Float, GPUFormatR32Float, GPUFormatRG16Unorm: return 4 case GPUFormatRGBA16Float: return 8 @@ -217,6 +226,10 @@ func (f GPUTextureFormat) String() string { return "RGBA32Float" case GPUFormatStencil8: return "Stencil8" + case GPUFormatR16Unorm: + return "R16Unorm" + case GPUFormatRG16Unorm: + return "RG16Unorm" default: return "Unknown" } @@ -646,6 +659,21 @@ type GPUFeatures struct { StencilTest bool // MipmapGeneration reports support for GPUOpGenerateMipmaps (box-filtered mip chains generated on the device). MipmapGeneration bool + // ImportD3D11Shared and ImportDMABuf report support for GPUOpImportTexture of each GPUExternalTextureKind. + ImportD3D11Shared bool + ImportDMABuf bool +} + +// SupportsImport reports whether f supports GPUOpImportTexture of kind. +func (f GPUFeatures) SupportsImport(kind GPUExternalTextureKind) bool { + switch kind { + case GPUExternalD3D11Shared: + return f.ImportD3D11Shared + case GPUExternalDMABuf: + return f.ImportDMABuf + default: + return false + } } // DefaultSoftwareGPUFeatures returns the capabilities supported by the pure-Go headless software GPU device. @@ -759,6 +787,47 @@ type GPUTextureDesc struct { Usage GPUTextureUsage } +// GPUExternalTextureKind identifies the GPU memory a GPUOpImportTexture opens. +type GPUExternalTextureKind uint8 + +const ( + // GPUExternalD3D11Shared is a Direct3D 11 texture shared through an NT handle (IDXGIResource1::CreateSharedHandle). + GPUExternalD3D11Shared GPUExternalTextureKind = iota + 1 + // GPUExternalDMABuf is a Linux DMA-BUF imported through EGL_EXT_image_dma_buf_import. + GPUExternalDMABuf +) + +// GPUDMABufPlane is one plane of a DMA-BUF: its file descriptor, byte offset and row pitch. +type GPUDMABufPlane struct { + FD int + Offset uint32 + Pitch uint32 +} + +// GPUDRMFormatModInvalid is DRM_FORMAT_MOD_INVALID: the DMA-BUF's layout is implied by its driver rather than named. +const GPUDRMFormatModInvalid uint64 = 0x00ffffffffffffff + +// GPUExternalTextureDesc describes a texture imported from GPU memory another API or device owns. The imported texture is a sampled 2D texture of Width x Height texels in Format. +type GPUExternalTextureDesc struct { + Label string + Kind GPUExternalTextureKind + Width uint32 + Height uint32 + Format GPUTextureFormat + + // D3D11: the shared NT handle, the plane of a planar texture (0 luma, 1 chroma for NV12 and P010), and the keyed mutex to hold while reading it. + Handle uintptr + Plane uint32 + KeyedMutex bool + AcquireKey uint64 + ReleaseKey uint64 + + // DMA-BUF: the plane's single-plane DRM fourcc, its format modifier (GPUDRMFormatModInvalid for none) and its one plane. + FourCC uint32 + Modifier uint64 + Planes []GPUDMABufPlane +} + // GPUSamplerDesc describes a GPU texture sampler. type GPUSamplerDesc struct { Label string @@ -987,6 +1056,8 @@ const ( GPUOpDestroyComputePipeline GPUOpReadBuffer GPUOpGenerateMipmaps + // GPUOpImportTexture opens External as the texture ID; GPUOpDestroyTexture releases it. + GPUOpImportTexture ) // GPUResourceOp is one resource creation, update, destruction, or readback op. @@ -1002,6 +1073,7 @@ type GPUResourceOp struct { BindGroup *GPUBindGroupDesc Pipeline *GPUPipelineDesc ComputePipeline *GPUComputePipelineDesc + External *GPUExternalTextureDesc TextureDst GPUTextureCopy DataLayout GPUDataLayout ReadbackID uint64 diff --git a/internal/platform/linux/gpu.go b/internal/platform/linux/gpu.go index 53db8a69e..15d0439de 100644 --- a/internal/platform/linux/gpu.go +++ b/internal/platform/linux/gpu.go @@ -620,8 +620,13 @@ func (w *window) initGPUContext(v *view, g *glGPUView, context uintptr) bool { feat := driver.GPUFeatures{ Depth32Float: true, } + importer := newEGLImporter() + feat.ImportDMABuf = importer != nil g.generation++ g.ctx = newGLGPUContext(api, es, g.generation, lim, feat) + if importer != nil { + g.ctx.importer = importer + } g.realized = true g.hasRendered = false pw, ph := gpuPhysicalSize(v, g.area) diff --git a/internal/platform/linux/gpu_external.go b/internal/platform/linux/gpu_external.go new file mode 100644 index 000000000..5c97fa587 --- /dev/null +++ b/internal/platform/linux/gpu_external.go @@ -0,0 +1,112 @@ +//go:build linux && !android + +package linux + +import ( + "fmt" + "runtime" + + "github.com/ebitengine/purego" +) + +// EGL entry points for importing DMA-BUFs (gpu_gl_external.go), bound once through libepoxy. +var ( + eglImportOnce bool + eglImportOK bool + + eglCreateImageKHR func(dpy, ctx uintptr, target uint32, buffer uintptr, attribs *int32) uintptr + eglDestroyImageKHR func(dpy, image uintptr) uint32 + eglGetError func() int32 + glEGLImageTargetTexture2DOES func(target uint32, image uintptr) + epoxyHasEGLExtension func(dpy uintptr, name *byte) bool + epoxyHasGLExtension func(name *byte) bool + eglGetCurrentDisplay func() uintptr +) + +func loadEGLImport() bool { + if eglImportOnce { + return eglImportOK + } + eglImportOnce = true + epoxy, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + return false + } + ok := true + // libepoxy's GL and EGL functions are pointer variables it resolves on the first call; its own are functions. + pointer := func(out any, name string) { + addr, err := purego.Dlsym(epoxy, "epoxy_"+name) + if err != nil || *(*uintptr)(cPointer(addr)) == 0 { + ok = false + return + } + purego.RegisterFunc(out, *(*uintptr)(cPointer(addr))) + } + function := func(lib uintptr, out any, name string) { + addr, err := purego.Dlsym(lib, name) + if err != nil { + ok = false + return + } + purego.RegisterFunc(out, addr) + } + pointer(&eglCreateImageKHR, "eglCreateImageKHR") + pointer(&eglDestroyImageKHR, "eglDestroyImageKHR") + pointer(&eglGetError, "eglGetError") + pointer(&eglGetCurrentDisplay, "eglGetCurrentDisplay") + pointer(&glEGLImageTargetTexture2DOES, "glEGLImageTargetTexture2DOES") + function(epoxy, &epoxyHasEGLExtension, "epoxy_has_egl_extension") + function(epoxy, &epoxyHasGLExtension, "epoxy_has_gl_extension") + eglImportOK = ok + return ok +} + +// eglImporter makes EGLImages of DMA-BUFs on the EGL display GTK's GL contexts run on. +type eglImporter struct { + dpy uintptr + modifiers bool +} + +// newEGLImporter returns the importer for the current GL context, or nil if GTK's context is not EGL, as with GLX, or lacks EGL_EXT_image_dma_buf_import or GL_OES_EGL_image. +func newEGLImporter() *eglImporter { + if !loadEGLImport() { + return nil + } + // EGL_NO_DISPLAY unless the current context is an EGL one. + dpy := eglGetCurrentDisplay() + if dpy == 0 { + return nil + } + has := func(name string) bool { + cs := cstr(name) + defer runtime.KeepAlive(cs) + return epoxyHasEGLExtension(dpy, cs) + } + gl := cstr("GL_OES_EGL_image") + defer runtime.KeepAlive(gl) + if !has("EGL_EXT_image_dma_buf_import") || !epoxyHasGLExtension(gl) { + return nil + } + return &eglImporter{dpy: dpy, modifiers: has("EGL_EXT_image_dma_buf_import_modifiers")} +} + +func (e *eglImporter) Modifiers() bool { return e.modifiers } + +func (e *eglImporter) CreateDMABufImage(attribs []int32) (uintptr, error) { + img := eglCreateImageKHR(e.dpy, 0, eglLinuxDMABufTarget, 0, &attribs[0]) + runtime.KeepAlive(attribs) + if img == 0 { + return 0, fmt.Errorf("eglCreateImageKHR of a DMA-BUF failed with EGL error %#x", eglGetError()) + } + return img, nil +} + +func (e *eglImporter) DestroyImage(image uintptr) { + eglDestroyImageKHR(e.dpy, image) +} + +func (e epoxyGL) EGLImageTargetTexture2D(target uint32, image uintptr) { + if glEGLImageTargetTexture2DOES != nil { + glEGLImageTargetTexture2DOES(target, image) + } +} diff --git a/internal/platform/linux/gpu_external_native_test.go b/internal/platform/linux/gpu_external_native_test.go new file mode 100644 index 000000000..874429e25 --- /dev/null +++ b/internal/platform/linux/gpu_external_native_test.go @@ -0,0 +1,330 @@ +//go:build linux && !android + +package linux + +import ( + "bytes" + "os" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/ebitengine/purego" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/gpu" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// gbmAPI is the part of libgbm the test makes DMA-BUFs with, standing in for a decoder's VAAPI surfaces. +type gbmAPI struct { + createDevice func(fd int32) uintptr + destroyDevice func(dev uintptr) + boCreate func(dev uintptr, w, h, format, flags uint32) uintptr + boDestroy func(bo uintptr) + boMap func(bo uintptr, x, y, w, h, flags uint32, stride *uint32, data *uintptr) uintptr + boUnmap func(bo, data uintptr) + boGetFD func(bo uintptr) int32 + boGetStride func(bo uintptr) uint32 + boGetOffset func(bo uintptr, plane int32) uint32 +} + +const ( + gbmBOUseRendering = 1 << 2 + gbmBOUseLinear = 1 << 4 + gbmBOTransferW = 2 +) + +func openGBM(t *testing.T) (*gbmAPI, uintptr) { + lib, err := purego.Dlopen("libgbm.so.1", purego.RTLD_NOW|purego.RTLD_GLOBAL) + if err != nil { + t.Skipf("no libgbm: %v", err) + } + g := &gbmAPI{} + purego.RegisterLibFunc(&g.createDevice, lib, "gbm_create_device") + purego.RegisterLibFunc(&g.destroyDevice, lib, "gbm_device_destroy") + purego.RegisterLibFunc(&g.boCreate, lib, "gbm_bo_create") + purego.RegisterLibFunc(&g.boDestroy, lib, "gbm_bo_destroy") + purego.RegisterLibFunc(&g.boMap, lib, "gbm_bo_map") + purego.RegisterLibFunc(&g.boUnmap, lib, "gbm_bo_unmap") + purego.RegisterLibFunc(&g.boGetFD, lib, "gbm_bo_get_fd") + purego.RegisterLibFunc(&g.boGetStride, lib, "gbm_bo_get_stride") + purego.RegisterLibFunc(&g.boGetOffset, lib, "gbm_bo_get_offset") + node, err := os.OpenFile("/dev/dri/renderD128", os.O_RDWR, 0) + if err != nil { + t.Skipf("no DRM render node: %v", err) + } + dev := g.createDevice(int32(node.Fd())) + if dev == 0 { + node.Close() + t.Skip("gbm_create_device failed") + } + t.Cleanup(func() { + g.destroyDevice(dev) + node.Close() + }) + return g, dev +} + +// plane makes a linear w x h DMA-BUF in fourcc holding texels, rows of w*bpp bytes, and returns it as an import's plane. +func (g *gbmAPI) plane(t *testing.T, dev uintptr, w, h, bpp, fourcc uint32, texels []byte) gpu.DMABufPlane { + bo := g.boCreate(dev, w, h, fourcc, gbmBOUseLinear|gbmBOUseRendering) + if bo == 0 { + t.Skipf("GBM cannot make linear %#08x buffers", fourcc) + } + t.Cleanup(func() { g.boDestroy(bo) }) + var stride uint32 + var mapData uintptr + ptr := g.boMap(bo, 0, 0, w, h, gbmBOTransferW, &stride, &mapData) + if ptr == 0 { + t.Skip("gbm_bo_map failed") + } + dst := unsafe.Slice((*byte)(cPointer(ptr)), int(stride*h)) + for y := range h { + copy(dst[y*stride:], texels[y*w*bpp:(y+1)*w*bpp]) + } + g.boUnmap(bo, mapData) + fd := g.boGetFD(bo) + if fd < 0 { + t.Fatal("gbm_bo_get_fd failed") + } + t.Cleanup(func() { syscall.Close(int(fd)) }) + return gpu.DMABufPlane{FD: int(fd), Offset: g.boGetOffset(bo, 0), Pitch: g.boGetStride(bo)} +} + +// yuvPlanesWGSL samples an NV12 frame's luma and chroma planes into one color: (Y, U, V, 1). +const yuvPlanesWGSL = ` +@group(0) @binding(0) var lumaTex: texture_2d; +@group(0) @binding(1) var chromaTex: texture_2d; +@group(0) @binding(2) var samp: sampler; + +struct VOut { + @builtin(position) pos: vec4, + @location(0) uv: vec2, +} + +@vertex +fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2) -> VOut { + var out: VOut; + out.pos = vec4(pos, 0.0, 1.0); + out.uv = uv; + return out; +} + +@fragment +fn fs_main(in: VOut) -> @location(0) vec4 { + let y = textureSample(lumaTex, samp, in.uv).r; + let c = textureSample(chromaTex, samp, in.uv).rg; + return vec4(y, c.r, c.g, 1.0); +} +` + +// TestLinuxGPUViewImportedDMABufMatchesUpload imports an NV12 frame's planes from DMA-BUFs into a gpu.View and checks that sampling them renders exactly what sampling the same bytes uploaded with WriteTexture does, and that closing the imports releases their EGLImages. +func TestLinuxGPUViewImportedDMABufMatchesUpload(t *testing.T) { + if testing.Short() { + t.Skip("opens a window") + } + const w, h = 8, 4 + luma := make([]byte, w*h) + for i := range luma { + luma[i] = byte(16 + i*7) + } + chroma := make([]byte, w*h/2) + for i := range chroma { + chroma[i] = byte(240 - i*13) + } + g, gbmDev := openGBM(t) + lumaPlane := g.plane(t, gbmDev, w, h, 1, drmFormatR8, luma) + chromaPlane := g.plane(t, gbmDev, w/2, h/2, 2, drmFormatGR88, chroma) + + mod := gpu.MustCompileWGSL(yuvPlanesWGSL) + quad := packF32( + -1, -1, 0, 1, + 1, -1, 1, 1, + 1, 1, 1, 0, + -1, -1, 0, 1, + 1, 1, 1, 0, + -1, 1, 0, 0, + ) + type result struct { + imported, uploaded []byte + unsupported bool + err error + } + done := make(chan result, 1) + finish := func(r result) { + select { + case done <- r: + default: + } + } + var imports []*gpu.Texture + title := "nsgo-native-" + t.Name() + app := func(cx *core.Scope) core.Node { + cx.SetTitle(title) + if !cx.Env().SupportsGPU() { + finish(result{unsupported: true}) + return core.View{} + } + var ( + pipe *gpu.Pipeline + vb *gpu.Buffer + groups [2]*gpu.BindGroup + targets [2]*gpu.RenderTarget + sent bool + got [2][]byte + pendingRead int + ) + return gpu.View(cx, gpu.ViewProps{ + Style: core.Style{Width: driver.Pt(64), Height: driver.Pt(64)}, + OnError: func(err gpu.Error) { finish(result{err: err}) }, + OnReady: func(dev *gpu.Device) { + if !dev.SupportsExternalTexture(gpu.ExternalDMABuf) { + finish(result{unsupported: true}) + return + } + fail := func(err error) bool { + if err != nil { + finish(result{err: err}) + } + return err != nil + } + y, err := dev.ImportTexture(cx, gpu.ExternalTextureDesc{Kind: gpu.ExternalDMABuf, Width: w, Height: h, Format: gpu.FormatR8Unorm, FourCC: drmFormatR8, Planes: []gpu.DMABufPlane{lumaPlane}}) + if fail(err) { + return + } + uv, err := dev.ImportTexture(cx, gpu.ExternalTextureDesc{Kind: gpu.ExternalDMABuf, Width: w / 2, Height: h / 2, Format: gpu.FormatRG8Unorm, FourCC: drmFormatGR88, Planes: []gpu.DMABufPlane{chromaPlane}}) + if fail(err) { + return + } + imports = []*gpu.Texture{y, uv} + upY, err := dev.CreateTexture(cx, gpu.TextureDesc{Width: w, Height: h, Format: gpu.FormatR8Unorm, Usage: gpu.TextureSampled | gpu.TextureCopyDst}) + if fail(err) { + return + } + dev.WriteTexture(upY, gpu.TextureCopy{Texture: upY}, luma, gpu.DataLayout{BytesPerRow: w, RowsPerImage: h}) + upUV, err := dev.CreateTexture(cx, gpu.TextureDesc{Width: w / 2, Height: h / 2, Format: gpu.FormatRG8Unorm, Usage: gpu.TextureSampled | gpu.TextureCopyDst}) + if fail(err) { + return + } + dev.WriteTexture(upUV, gpu.TextureCopy{Texture: upUV}, chroma, gpu.DataLayout{BytesPerRow: w, RowsPerImage: h / 2}) + samp, err := dev.CreateSampler(cx, gpu.SamplerDesc{MinFilter: gpu.FilterNearest, MagFilter: gpu.FilterNearest, AddressU: gpu.AddressClampToEdge, AddressV: gpu.AddressClampToEdge}) + if fail(err) { + return + } + layout, err := dev.CreateBindGroupLayout(cx, []gpu.BindGroupLayoutEntry{ + {Binding: 0, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 1, Visibility: gpu.StageFragment, Type: gpu.BindingTexture}, + {Binding: 2, Visibility: gpu.StageFragment, Type: gpu.BindingSampler}, + }) + if fail(err) { + return + } + for i, planes := range [2][2]*gpu.Texture{{y, uv}, {upY, upUV}} { + if groups[i], err = dev.CreateBindGroup(cx, layout, []gpu.BindGroupEntry{{Binding: 0, Texture: planes[0]}, {Binding: 1, Texture: planes[1]}, {Binding: 2, Sampler: samp}}); fail(err) { + return + } + if targets[i], err = dev.CreateRenderTarget(cx, gpu.RenderTargetDesc{Width: w, Height: h, ColorFormat: gpu.FormatRGBA8Unorm}); fail(err) { + return + } + } + if vb, err = dev.CreateBuffer(cx, gpu.BufferDesc{Usage: gpu.UsageVertex, Data: quad}); fail(err) { + return + } + pipe, err = dev.CreatePipeline(cx, gpu.PipelineDesc{ + Vertex: gpu.ShaderStage{Module: mod, EntryPoint: "vs_main"}, + Fragment: gpu.ShaderStage{Module: mod, EntryPoint: "fs_main"}, + Layouts: []*gpu.BindGroupLayout{layout}, + VertexBuffers: []gpu.VertexBufferLayout{{Stride: 16, Attributes: []gpu.VertexAttribute{ + {Location: 0, Offset: 0, Format: gpu.VertexFloat32x2}, + {Location: 1, Offset: 8, Format: gpu.VertexFloat32x2}, + }}}, + Primitive: gpu.PrimitiveState{Topology: gpu.TopologyTriangleList}, + Targets: []gpu.ColorTargetState{{Format: gpu.FormatRGBA8Unorm}}, + }) + fail(err) + }, + OnFrame: func(frame *gpu.Frame) { + if pipe == nil || sent { + return + } + sent = true + for i := range 2 { + pass := frame.BeginRenderPass(gpu.RenderPassDesc{ColorAttachments: []gpu.ColorAttachment{{Texture: targets[i].Color, LoadOp: gpu.LoadClear, StoreOp: gpu.StoreStore}}}) + pass.SetPipeline(pipe) + pass.SetBindGroup(0, groups[i]) + pass.SetVertexBuffer(0, vb, 0) + pass.Draw(6, 0) + pass.End() + } + frame.Submit() + pendingRead = 2 + for i := range 2 { + frame.Device().ReadTexture(targets[i].Color, gpu.TextureRegion{Width: w, Height: h}, func(rgba []byte, err error) { + if err != nil { + finish(result{err: err}) + return + } + got[i] = rgba + if pendingRead--; pendingRead == 0 { + finish(result{imported: got[0], uploaded: got[1]}) + } + }) + } + }, + }) + } + win := startTestWindow(t, app, Options{Title: title, Width: 64, Height: 64}) + waitForTitle(t, win, title) + var r result + select { + case r = <-done: + case <-time.After(10 * time.Second): + t.Fatal("the imported frame was not rendered") + } + switch { + case r.unsupported: + t.Skip("GTK's GL context is not EGL, or lacks DMA-BUF import") + case r.err != nil: + t.Fatal(r.err) + } + if len(r.imported) != w*h*4 || !bytes.Equal(r.imported, r.uploaded) { + t.Fatalf("imported DMA-BUFs rendered\n%v\nuploaded planes rendered\n%v", r.imported, r.uploaded) + } + // Pixel (3, 1) samples luma byte 1*w+3 and the chroma pair at (1, 0). + if px := r.imported[(1*w+3)*4:][:4]; px[0] != luma[1*w+3] || px[1] != chroma[2] || px[2] != chroma[3] { + t.Fatalf("pixel (3, 1) = %v, want Y %d U %d V %d", px, luma[1*w+3], chroma[2], chroma[3]) + } + + // Closing the imports destroys their EGLImages. + countImages := func() (n int) { + win.onLoop(t, func() { + for _, v := range win.views { + if v != nil && v.gpu != nil && v.gpu.ctx != nil { + for _, tex := range v.gpu.ctx.textures { + if tex.eglImage != 0 { + n++ + } + } + } + } + }) + return n + } + if n := countImages(); n != 2 { + t.Fatalf("%d EGLImages before closing the imports, want 2", n) + } + win.onLoop(t, func() { + for _, tex := range imports { + _ = tex.Close() + } + }) + deadline := time.Now().Add(3 * time.Second) + for countImages() != 0 && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if n := countImages(); n != 0 { + t.Fatalf("%d EGLImages left after closing the imports", n) + } +} diff --git a/internal/platform/linux/gpu_gl.go b/internal/platform/linux/gpu_gl.go index 4080c1fb0..256c52dfc 100644 --- a/internal/platform/linux/gpu_gl.go +++ b/internal/platform/linux/gpu_gl.go @@ -210,6 +210,8 @@ type glAPI interface { TexSubImage3D(target uint32, level, x, y, z, width, height, depth int32, format, typ uint32, data []byte) TexSubImage3DOffset(target uint32, level, x, y, z, width, height, depth int32, format, typ uint32, offset uintptr) TexParameteri(target, pname uint32, param int32) + // EGLImageTargetTexture2D is glEGLImageTargetTexture2DOES, binding an EGLImage to the bound texture (gpu_gl_external.go). + EGLImageTargetTexture2D(target uint32, image uintptr) // Samplers. GenSampler() uint32 @@ -281,6 +283,8 @@ type glGPUTexture struct { mipLevels uint32 // rendered records whether the texture's current contents came from an FBO render pass (OpenGL Y-up) rather than a top-row-first WriteTexture upload. rendered bool + // eglImage is the EGLImage an imported texture is bound to. + eglImage uintptr } type glGPUSampler struct { @@ -320,6 +324,8 @@ type glGPUContext struct { generation uint32 limits driver.GPULimits features driver.GPUFeatures + // importer makes EGLImages of DMA-BUFs; nil where GTK's context is not EGL. + importer glExternalImporter buffers map[driver.GPUID]*glGPUBuffer textures map[driver.GPUID]*glGPUTexture @@ -380,11 +386,8 @@ func (c *glGPUContext) destroyAll() { } delete(c.buffers, id) } - for id, t := range c.textures { - if t.glID != 0 { - c.gl.DeleteTexture(t.glID) - } - delete(c.textures, id) + for id := range c.textures { + c.deleteTexture(id) } for id, s := range c.samplers { if s.glID != 0 { @@ -474,13 +477,10 @@ func (c *glGPUContext) applyOp(op driver.GPUResourceOp) *glGPUError { return c.createTexture(op.ID, op.Texture) case driver.GPUOpWriteTexture: return c.writeTexture(op.ID, op.TextureDst, op.Data, op.DataLayout) + case driver.GPUOpImportTexture: + return c.importTexture(op.ID, op.External) case driver.GPUOpDestroyTexture: - if t, ok := c.textures[op.ID]; ok { - if t.glID != 0 { - c.gl.DeleteTexture(t.glID) - } - delete(c.textures, op.ID) - } + c.deleteTexture(op.ID) case driver.GPUOpCreateSampler: return c.createSampler(op.ID, op.Sampler) case driver.GPUOpDestroySampler: @@ -732,6 +732,9 @@ func (c *glGPUContext) writeTexture(id driver.GPUID, dst driver.GPUTextureCopy, if !ok { return &glGPUError{code: driver.GPUErrorInvalidDescriptor, message: fmt.Sprintf("unknown texture %d", id)} } + if t.eglImage != 0 { + return &glGPUError{code: driver.GPUErrorInvalidDescriptor, message: fmt.Sprintf("texture %d is imported and cannot be written", id)} + } _, pixelFmt, pixelType, _, ok := glTextureFormatInfo(t.format) if !ok { return &glGPUError{code: driver.GPUErrorInvalidDescriptor, message: fmt.Sprintf("unsupported texture format %d", t.format)} diff --git a/internal/platform/linux/gpu_gl_external.go b/internal/platform/linux/gpu_gl_external.go new file mode 100644 index 000000000..2db8ee6ab --- /dev/null +++ b/internal/platform/linux/gpu_gl_external.go @@ -0,0 +1,159 @@ +package linux + +import ( + "fmt" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// Importing DMA-BUFs as textures (gpu.ExternalDMABuf, #2296): each import is one plane in a single-plane DRM format, made an EGLImage with EGL_EXT_image_dma_buf_import and bound to a plain GL_TEXTURE_2D with glEGLImageTargetTexture2DOES, so shaders sample it with sampler2D, never samplerExternalOES. This file has no build constraint so its logic is tested on every host. + +// glExternalImporter makes and destroys the EGLImages imported textures are bound to. +type glExternalImporter interface { + // CreateDMABufImage makes an EGLImage of the DMA-BUF attribs describes. + CreateDMABufImage(attribs []int32) (uintptr, error) + DestroyImage(image uintptr) + // Modifiers reports EGL_EXT_image_dma_buf_import_modifiers. + Modifiers() bool +} + +// DRM fourccs (drm_fourcc.h) of the single-plane formats imports take. +const ( + drmFormatR8 = 0x20203852 // 'R', '8', ' ', ' ' + drmFormatGR88 = 0x38385247 // 'G', 'R', '8', '8' + drmFormatR16 = 0x20363152 // 'R', '1', '6', ' ' + drmFormatGR1616 = 0x32335247 // 'G', 'R', '3', '2' + drmFormatABGR8888 = 0x34324241 // 'A', 'B', '2', '4' + drmFormatXBGR8888 = 0x34324258 // 'X', 'B', '2', '4' + drmFormatARGB8888 = 0x34325241 // 'A', 'R', '2', '4' + drmFormatXRGB8888 = 0x34325258 // 'X', 'R', '2', '4' +) + +// EGL_EXT_image_dma_buf_import(_modifiers) attributes. +const ( + eglNone = 0x3038 + eglHeight = 0x3056 + eglWidth = 0x3057 + eglLinuxDRMFourCC = 0x3271 + eglDMABufPlane0FD = 0x3272 + eglDMABufPlane0Offset = 0x3273 + eglDMABufPlane0Pitch = 0x3274 + eglDMABufPlane0ModLo = 0x3443 + eglDMABufPlane0ModHi = 0x3444 + eglLinuxDMABufTarget = 0x3270 + drmFormatModLinear = 0 + glDMABufImportPlaneCount = 1 +) + +// drmPlaneFormat is the texture format a shader samples a single-plane DRM format as. +func drmPlaneFormat(fourcc uint32) (driver.GPUTextureFormat, bool) { + switch fourcc { + case drmFormatR8: + return driver.GPUFormatR8Unorm, true + case drmFormatGR88: + return driver.GPUFormatRG8Unorm, true + case drmFormatR16: + return driver.GPUFormatR16Unorm, true + case drmFormatGR1616: + return driver.GPUFormatRG16Unorm, true + case drmFormatABGR8888, drmFormatXBGR8888: + return driver.GPUFormatRGBA8Unorm, true + case drmFormatARGB8888, drmFormatXRGB8888: + return driver.GPUFormatBGRA8Unorm, true + default: + return driver.GPUFormatUndefined, false + } +} + +// dmaBufImageAttribs builds eglCreateImageKHR's attribute list for desc, naming its modifier when it has one and the display takes modifiers. +func dmaBufImageAttribs(desc *driver.GPUExternalTextureDesc, modifiers bool) ([]int32, error) { + f, ok := drmPlaneFormat(desc.FourCC) + if !ok { + return nil, fmt.Errorf("DMA-BUF format %#08x is not a single-plane format; import each plane as DRM_FORMAT_R8, GR88, R16 or GR1616", desc.FourCC) + } + if f != desc.Format { + return nil, fmt.Errorf("DMA-BUF format %#08x is sampled as %s, not %s", desc.FourCC, f, desc.Format) + } + if len(desc.Planes) != glDMABufImportPlaneCount { + return nil, fmt.Errorf("DMA-BUF format %#08x has 1 plane, got %d", desc.FourCC, len(desc.Planes)) + } + p := desc.Planes[0] + attribs := []int32{ + eglWidth, int32(desc.Width), + eglHeight, int32(desc.Height), + eglLinuxDRMFourCC, int32(desc.FourCC), + eglDMABufPlane0FD, int32(p.FD), + eglDMABufPlane0Offset, int32(p.Offset), + eglDMABufPlane0Pitch, int32(p.Pitch), + } + switch { + case desc.Modifier == driver.GPUDRMFormatModInvalid: + case modifiers: + attribs = append(attribs, eglDMABufPlane0ModLo, int32(uint32(desc.Modifier)), eglDMABufPlane0ModHi, int32(uint32(desc.Modifier>>32))) + case desc.Modifier != drmFormatModLinear: + return nil, fmt.Errorf("DMA-BUF modifier %#x needs EGL_EXT_image_dma_buf_import_modifiers", desc.Modifier) + } + return append(attribs, eglNone), nil +} + +// importTexture binds an EGLImage of desc's DMA-BUF to a new GL texture. +func (c *glGPUContext) importTexture(id driver.GPUID, desc *driver.GPUExternalTextureDesc) *glGPUError { + if desc == nil { + return &glGPUError{code: driver.GPUErrorInvalidDescriptor, message: "nil external texture descriptor"} + } + if desc.Kind != driver.GPUExternalDMABuf || c.importer == nil { + return &glGPUError{code: driver.GPUErrorUnsupported, message: fmt.Sprintf("external textures of kind %d cannot be imported here", desc.Kind)} + } + attribs, err := dmaBufImageAttribs(desc, c.importer.Modifiers()) + if err != nil { + return &glGPUError{code: driver.GPUErrorInvalidDescriptor, message: err.Error()} + } + img, err := c.importer.CreateDMABufImage(attribs) + if err != nil { + return &glGPUError{code: driver.GPUErrorFailed, message: err.Error()} + } + c.deleteTexture(id) + glID := c.gl.GenTexture() + c.gl.BindTexture(gpuGLTexture2D, glID) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureBaseLevel, 0) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureMaxLevel, 0) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureMinFilter, gpuGLNearest) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureMagFilter, gpuGLNearest) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureWrapS, gpuGLClampToEdge) + c.gl.TexParameteri(gpuGLTexture2D, gpuGLTextureWrapT, gpuGLClampToEdge) + c.gl.EGLImageTargetTexture2D(gpuGLTexture2D, img) + glErr := c.gl.GetError() + c.gl.BindTexture(gpuGLTexture2D, 0) + if glErr != 0 { + c.gl.DeleteTexture(glID) + c.importer.DestroyImage(img) + return &glGPUError{code: driver.GPUErrorFailed, message: fmt.Sprintf("glEGLImageTargetTexture2DOES failed with GL error %#x", glErr)} + } + c.textures[id] = &glGPUTexture{ + glID: glID, + target: gpuGLTexture2D, + dim: driver.GPUDim2D, + format: desc.Format, + width: desc.Width, + height: desc.Height, + layers: 1, + mipLevels: 1, + eglImage: img, + } + return nil +} + +// deleteTexture deletes texture id and the EGLImage an imported one is bound to. +func (c *glGPUContext) deleteTexture(id driver.GPUID) { + t, ok := c.textures[id] + if !ok { + return + } + if t.glID != 0 { + c.gl.DeleteTexture(t.glID) + } + if t.eglImage != 0 && c.importer != nil { + c.importer.DestroyImage(t.eglImage) + } + delete(c.textures, id) +} diff --git a/internal/platform/linux/gpu_gl_external_test.go b/internal/platform/linux/gpu_gl_external_test.go new file mode 100644 index 000000000..00182b299 --- /dev/null +++ b/internal/platform/linux/gpu_gl_external_test.go @@ -0,0 +1,113 @@ +package linux + +import ( + "slices" + "strings" + "testing" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +type fakeEGLImporter struct { + modifiers bool + next uintptr + live map[uintptr]bool + attribs [][]int32 +} + +func (f *fakeEGLImporter) Modifiers() bool { return f.modifiers } + +func (f *fakeEGLImporter) CreateDMABufImage(attribs []int32) (uintptr, error) { + f.next++ + if f.live == nil { + f.live = map[uintptr]bool{} + } + f.live[f.next] = true + f.attribs = append(f.attribs, slices.Clone(attribs)) + return f.next, nil +} + +func (f *fakeEGLImporter) DestroyImage(image uintptr) { delete(f.live, image) } + +func TestDMABufImageAttribs(t *testing.T) { + desc := &driver.GPUExternalTextureDesc{ + Kind: driver.GPUExternalDMABuf, Width: 64, Height: 36, Format: driver.GPUFormatRG8Unorm, + FourCC: drmFormatGR88, Modifier: 0x0100000000000002, + Planes: []driver.GPUDMABufPlane{{FD: 7, Offset: 4096, Pitch: 128}}, + } + got, err := dmaBufImageAttribs(desc, true) + want := []int32{ + eglWidth, 64, eglHeight, 36, eglLinuxDRMFourCC, drmFormatGR88, + eglDMABufPlane0FD, 7, eglDMABufPlane0Offset, 4096, eglDMABufPlane0Pitch, 128, + eglDMABufPlane0ModLo, 2, eglDMABufPlane0ModHi, 0x01000000, + eglNone, + } + if err != nil || !slices.Equal(got, want) { + t.Fatalf("attribs = %v, %v; want %v", got, err, want) + } + if _, err := dmaBufImageAttribs(desc, false); err == nil { + t.Error("a tiled modifier without EGL_EXT_image_dma_buf_import_modifiers was accepted") + } + linear := *desc + linear.Modifier = drmFormatModLinear + if got, err := dmaBufImageAttribs(&linear, false); err != nil || got[len(got)-1] != eglNone || len(got) != 13 { + t.Errorf("linear without modifiers = %v, %v", got, err) + } + implicit := *desc + implicit.Modifier = driver.GPUDRMFormatModInvalid + if got, err := dmaBufImageAttribs(&implicit, true); err != nil || len(got) != 13 { + t.Errorf("DRM_FORMAT_MOD_INVALID = %v, %v; want no modifier attributes", got, err) + } + for name, bad := range map[string]driver.GPUExternalTextureDesc{ + "multi-plane NV12": {Width: 4, Height: 4, Format: driver.GPUFormatR8Unorm, FourCC: 0x3231564e, Planes: desc.Planes}, + "format mismatch": {Width: 4, Height: 4, Format: driver.GPUFormatR8Unorm, FourCC: drmFormatGR88, Planes: desc.Planes}, + "two planes for R8": {Width: 4, Height: 4, Format: driver.GPUFormatR8Unorm, FourCC: drmFormatR8, Planes: []driver.GPUDMABufPlane{{FD: 1}, {FD: 2}}}, + } { + if _, err := dmaBufImageAttribs(&bad, true); err == nil { + t.Errorf("%s was accepted", name) + } + } + if f, ok := drmPlaneFormat(drmFormatR16); !ok || f != driver.GPUFormatR16Unorm { + t.Errorf("R16 samples as %s", f) + } + if f, ok := drmPlaneFormat(drmFormatXRGB8888); !ok || f != driver.GPUFormatBGRA8Unorm { + t.Errorf("XRGB8888 samples as %s", f) + } +} + +func TestGLGPUImportTextureBindsAndReleasesEGLImage(t *testing.T) { + gl := newMockGL() + imp := &fakeEGLImporter{modifiers: true} + ctx := newGLGPUContext(gl, false, 1, driver.DefaultGPULimits(), driver.GPUFeatures{ImportDMABuf: true}) + ctx.importer = imp + luma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalDMABuf, Width: 8, Height: 8, Format: driver.GPUFormatR8Unorm, FourCC: drmFormatR8, Modifier: driver.GPUDRMFormatModInvalid, Planes: []driver.GPUDMABufPlane{{FD: 3, Pitch: 64}}} + chroma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalDMABuf, Width: 4, Height: 4, Format: driver.GPUFormatRG8Unorm, FourCC: drmFormatGR88, Modifier: driver.GPUDRMFormatModInvalid, Planes: []driver.GPUDMABufPlane{{FD: 3, Offset: 512, Pitch: 64}}} + _, errs := ctx.executeFrame(driver.GPUFrame{Ops: []driver.GPUResourceOp{ + {Kind: driver.GPUOpImportTexture, ID: 1, External: luma}, + {Kind: driver.GPUOpImportTexture, ID: 2, External: chroma}, + {Kind: driver.GPUOpWriteTexture, ID: 1, Data: []byte{1, 2, 3, 4}, DataLayout: driver.GPUDataLayout{BytesPerRow: 2}}, + }}, 0, 8, 8) + if len(errs) != 1 || !strings.Contains(errs[0].message, "imported") { + t.Fatalf("errors = %+v, want only the write to the imported texture rejected", errs) + } + if len(imp.live) != 2 || len(gl.eglImageTargets) != 2 || ctx.textures[2].eglImage == 0 || ctx.textures[2].format != driver.GPUFormatRG8Unorm { + t.Fatalf("images %v, targets %v, textures %+v", imp.live, gl.eglImageTargets, ctx.textures) + } + if len(gl.texUploads) != 0 { + t.Fatalf("an imported texture was uploaded to: %+v", gl.texUploads) + } + ctx.executeFrame(driver.GPUFrame{Ops: []driver.GPUResourceOp{{Kind: driver.GPUOpDestroyTexture, ID: 1}}}, 0, 8, 8) + if len(imp.live) != 1 || len(gl.liveTextures) != 1 { + t.Fatalf("after destroy: images %v, textures %v", imp.live, gl.liveTextures) + } + ctx.destroyAll() + if len(imp.live) != 0 || len(gl.liveTextures) != 0 { + t.Fatalf("leak after destroyAll: images %v, textures %v", imp.live, gl.liveTextures) + } + + // Without an EGL importer, imports are unsupported. + plain := newGLGPUContext(newMockGL(), false, 1, driver.DefaultGPULimits(), driver.GPUFeatures{}) + if err := plain.importTexture(1, luma); err == nil || err.code != driver.GPUErrorUnsupported { + t.Fatalf("import without EGL = %+v", err) + } +} diff --git a/internal/platform/linux/gpu_gl_test.go b/internal/platform/linux/gpu_gl_test.go index 33266b43b..fdd50f6b9 100644 --- a/internal/platform/linux/gpu_gl_test.go +++ b/internal/platform/linux/gpu_gl_test.go @@ -125,6 +125,7 @@ type mockGL struct { blitCalls int readPixelsCalls [][4]int32 readPixelsSource []byte + eglImageTargets []uintptr } func newMockGL() *mockGL { @@ -326,6 +327,9 @@ func (m *mockGL) TexSubImage3DOffset(target uint32, level, x, y, z, width, heigh }) } func (m *mockGL) TexParameteri(target, pname uint32, param int32) {} +func (m *mockGL) EGLImageTargetTexture2D(target uint32, image uintptr) { + m.eglImageTargets = append(m.eglImageTargets, image) +} func (m *mockGL) GenSampler() uint32 { id := m.alloc() diff --git a/internal/platform/windows/gpu.go b/internal/platform/windows/gpu.go index f81dd2519..d85450ac7 100644 --- a/internal/platform/windows/gpu.go +++ b/internal/platform/windows/gpu.go @@ -189,6 +189,9 @@ func (b *d3d11BufferHandle) Release() { type d3d11TextureHandle struct { tex, srv, rtv, dsv *comObject sliceRTVs map[uint64]*comObject + // shared is the shared texture an imported plane views, and mutex its IDXGIKeyedMutex (gpu_external.go). + shared *d3d11SharedTexture + mutex *comObject } func (t *d3d11TextureHandle) Release() { @@ -200,7 +203,11 @@ func (t *d3d11TextureHandle) Release() { delete(t.sliceRTVs, k) } t.sliceRTVs = nil - releaseAll(&t.dsv, &t.rtv, &t.srv, &t.tex) + releaseAll(&t.mutex, &t.dsv, &t.rtv, &t.srv, &t.tex) + if t.shared != nil { + t.shared.release() + t.shared = nil + } } func (t *d3d11TextureHandle) rtvFor(d3d *comObject, desc driver.GPUTextureDesc, mip, layer uint32) *comObject { @@ -262,6 +269,8 @@ func (p *d3d11PipelineHandle) Release() { type d3d11NativeOps struct { scaleFn func() float32 + // shared holds each shared texture imports opened, by NT handle (gpu_external.go). + shared map[uintptr]*d3d11SharedTexture } func (n *d3d11NativeOps) getDevices() (*gfx, *comObject, error) { diff --git a/internal/platform/windows/gpu_d3d11_desc.go b/internal/platform/windows/gpu_d3d11_desc.go index 14b15b0c1..770286ebb 100644 --- a/internal/platform/windows/gpu_d3d11_desc.go +++ b/internal/platform/windows/gpu_d3d11_desc.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "math" + "slices" "github.com/nsgo-dev/nsgo/internal/driver" "github.com/nsgo-dev/nsgo/internal/shaderir" @@ -34,10 +35,14 @@ const ( dxgiFmtR24G8Typeless uint32 = 44 dxgiFmtD24UnormS8Uint uint32 = 45 dxgiFmtR24UnormX8Typeless uint32 = 46 + dxgiFmtR16G16Unorm uint32 = 35 dxgiFmtR8G8Unorm uint32 = 49 + dxgiFmtR16Unorm uint32 = 56 dxgiFmtR16Uint uint32 = 57 dxgiFmtR8Unorm uint32 = 61 dxgiFmtB8G8R8A8Unorm uint32 = 87 + dxgiFmtNV12 uint32 = 103 + dxgiFmtP010 uint32 = 104 // D3D11_USAGE (d3d11.h). d3d11UsageDefault uint32 = 0 @@ -60,6 +65,13 @@ const ( // D3D11_RESOURCE_MISC_FLAG (d3d11.h). d3d11MiscTextureCube uint32 = 0x4 d3d11MiscBufferStructured uint32 = 0x40 + d3d11MiscSharedKeyedMutex uint32 = 0x100 + d3d11MiscSharedNTHandle uint32 = 0x800 + + // IDXGIKeyedMutex::AcquireSync's success codes besides S_OK (WAIT_TIMEOUT, WAIT_ABANDONED), and how long a frame waits for an imported texture's key. + d3dKeyedMutexWaitTimeout uint32 = 0x102 + d3dKeyedMutexWaitAbandoned uint32 = 0x80 + d3dKeyedMutexAcquireTimeoutMS = 100 // D3D11_MAP (d3d11.h). d3d11MapRead uint32 = 1 @@ -316,7 +328,81 @@ func d3d11Features() driver.GPUFeatures { MSAA4x: true, Depth32Float: true, Anisotropy: true, + // ID3D11Device1::OpenSharedResource1, which every Windows 10 device has. + ImportD3D11Shared: true, + } +} + +// d3dExternalViewFormat returns the SRV format that samples plane of a shared texture in DXGI format texFmt as the plane format want, or dxgiFmtUnknown if the texture has no such plane. +func d3dExternalViewFormat(texFmt uint32, plane uint32, want driver.GPUTextureFormat) uint32 { + var view uint32 + switch texFmt { + case dxgiFmtNV12: + view = [2]uint32{dxgiFmtR8Unorm, dxgiFmtR8G8Unorm}[min(plane, 1)] + case dxgiFmtP010: + view = [2]uint32{dxgiFmtR16Unorm, dxgiFmtR16G16Unorm}[min(plane, 1)] + case dxgiFmtR8Unorm, dxgiFmtR8G8Unorm, dxgiFmtR16Unorm, dxgiFmtR16G16Unorm, dxgiFmtR8G8B8A8Unorm, dxgiFmtB8G8R8A8Unorm: + if plane != 0 { + return dxgiFmtUnknown + } + view = texFmt + default: + return dxgiFmtUnknown + } + if d3dPlaneFormat(want) != view { + return dxgiFmtUnknown } + return view +} + +// d3dExternalSRVDescriptor validates that the shared texture td has the plane ext imports, at its size and format, and returns the SRV that samples it. +func d3dExternalSRVDescriptor(td d3d11Texture2DDesc, ext driver.GPUExternalTextureDesc) (d3d11SRVDesc, error) { + if td.arraySize != 1 || td.sampleCount > 1 { + return d3d11SRVDesc{}, fmt.Errorf("d3d11: imported texture must be a single-sampled 2D texture, not an array of %d or %d samples", td.arraySize, td.sampleCount) + } + if td.bindFlags&d3d11BindShaderResource == 0 { + return d3d11SRVDesc{}, errors.New("d3d11: imported texture lacks D3D11_BIND_SHADER_RESOURCE") + } + if ext.KeyedMutex && td.misc&d3d11MiscSharedKeyedMutex == 0 { + return d3d11SRVDesc{}, errors.New("d3d11: imported texture has no keyed mutex (D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX)") + } + view := d3dExternalViewFormat(td.format, ext.Plane, ext.Format) + if view == dxgiFmtUnknown { + return d3d11SRVDesc{}, fmt.Errorf("d3d11: plane %d of a DXGI format %d texture cannot be sampled as %s", ext.Plane, td.format, ext.Format) + } + if w, h := d3dExternalPlaneSize(td.format, ext.Plane, td.width, td.height); w != ext.Width || h != ext.Height { + return d3d11SRVDesc{}, fmt.Errorf("d3d11: plane %d of the imported texture is %dx%d, not %dx%d", ext.Plane, w, h, ext.Width, ext.Height) + } + // Texture2D SRV: MostDetailedMip 0, MipLevels 1. + return d3d11SRVDesc{format: view, viewDimension: d3d11SRVDimTexture2D, u0: 0, u1: 1}, nil +} + +// d3dPlaneFormat is the DXGI format of an imported plane in format f. +func d3dPlaneFormat(f driver.GPUTextureFormat) uint32 { + switch f { + case driver.GPUFormatR8Unorm: + return dxgiFmtR8Unorm + case driver.GPUFormatRG8Unorm: + return dxgiFmtR8G8Unorm + case driver.GPUFormatR16Unorm: + return dxgiFmtR16Unorm + case driver.GPUFormatRG16Unorm: + return dxgiFmtR16G16Unorm + case driver.GPUFormatRGBA8Unorm: + return dxgiFmtR8G8B8A8Unorm + case driver.GPUFormatBGRA8Unorm: + return dxgiFmtB8G8R8A8Unorm + default: + return dxgiFmtUnknown + } +} + +// d3dExternalPlaneSize is the size in texels of plane of a texture of width x height in DXGI format texFmt: the chroma plane of NV12 and P010 is half the size, rounded up. +func d3dExternalPlaneSize(texFmt, plane, width, height uint32) (uint32, uint32) { + if plane == 1 && (texFmt == dxgiFmtNV12 || texFmt == dxgiFmtP010) { + return (width + 1) / 2, (height + 1) / 2 + } + return width, height } // d3dAlignConstantBufferSize rounds size up to a 16-byte multiple (min 16), matching Direct3D 11's D3D11_BIND_CONSTANT_BUFFER ByteWidth requirement. @@ -999,6 +1085,8 @@ type d3dTrackedTexture struct { rtvDesc d3d11RTVDesc dsvDesc d3d11DSVDesc handle d3dReleaser + // external describes a texture opened by GPUOpImportTexture, which the controller only samples. + external *driver.GPUExternalTextureDesc } type d3dTrackedSampler struct { @@ -1046,6 +1134,11 @@ type d3dNativeOps interface { ExecuteCopy(cp driver.GPUCopyOp, lookup *d3dPassLookup) (uint32, error) ExecutePass(pass driver.GPUPass, swap d3dReleaser, swapW, swapH uint32, lookup *d3dPassLookup) (drewSwap bool, hr uint32, err error) ReadTexture(swap d3dReleaser, swapW, swapH uint32, tex *d3dTrackedTexture, region driver.GPUTextureRegion, surface bool) ([]byte, uint32, error) + // ImportTexture opens a shared texture's plane and returns its handle and the shared texture's descriptor. + ImportTexture(desc driver.GPUExternalTextureDesc) (d3dReleaser, d3d11Texture2DDesc, uint32, error) + // AcquireKeyedMutex and ReleaseKeyedMutex hold an imported texture's IDXGIKeyedMutex; AcquireKeyedMutex returns d3dKeyedMutexWaitTimeout if it timed out. + AcquireKeyedMutex(tex *d3dTrackedTexture, key uint64, timeoutMS uint32) (uint32, error) + ReleaseKeyedMutex(tex *d3dTrackedTexture, key uint64) DeviceRemovedReason() uint32 } @@ -1268,6 +1361,10 @@ func (c *d3dGPUController) Submit(frame driver.GPUFrame) (drewSwap bool) { pipelines: c.pipelines, } + // Hold the keyed mutexes of the imported textures the passes sample until they are recorded. + held := c.acquireExternal(frame) + defer func() { c.releaseExternal(held) }() + // Phase 2: copies. for _, cp := range frame.Copies { hr, err := c.ops.ExecuteCopy(cp, lookup) @@ -1332,6 +1429,9 @@ func (c *d3dGPUController) Submit(frame driver.GPUFrame) (drewSwap bool) { }) } + c.releaseExternal(held) + held = nil + // Phase 5: deferred destroys (safe because IDs are globally monotonic). for _, op := range deferredDestroys { c.execDestroy(op) @@ -1425,9 +1525,45 @@ func (c *d3dGPUController) execCreateOrWrite(op driver.GPUResourceOp) bool { } return true + case driver.GPUOpImportTexture: + if op.External == nil { + return false + } + ext := *op.External + ext.Planes = slices.Clone(ext.Planes) + handle, td, hr, err := c.ops.ImportTexture(ext) + if err != nil { + if c.checkDeviceLost(hr, err.Error()) { + return false + } + c.emitError(d3dErrorCodeFromHR(hr, driver.GPUErrorFailed), err.Error()) + return false + } + if prev := c.textures[op.ID]; prev != nil && prev.handle != nil { + prev.handle.Release() + } + c.textures[op.ID] = &d3dTrackedTexture{ + id: op.ID, + desc: driver.GPUTextureDesc{ + Label: ext.Label, + Dimension: driver.GPUDim2D, + Width: ext.Width, + Height: ext.Height, + Layers: 1, + MipLevels: 1, + SampleCount: 1, + Format: ext.Format, + Usage: driver.GPUTextureSampled, + }, + texDesc: td, + handle: handle, + external: &ext, + } + return true + case driver.GPUOpWriteTexture: tex := c.textures[op.ID] - if tex == nil || len(op.Data) == 0 { + if tex == nil || tex.external != nil || len(op.Data) == 0 { return false } hr, err := c.ops.WriteTexture(tex, op.TextureDst, op.Data, op.DataLayout) @@ -1566,6 +1702,49 @@ func (c *d3dGPUController) execDestroy(op driver.GPUResourceOp) { } } +// acquireExternal acquires the keyed mutex of each imported texture that frame's passes bind, once per shared handle, and returns those it holds. +func (c *d3dGPUController) acquireExternal(frame driver.GPUFrame) []*d3dTrackedTexture { + var held []*d3dTrackedTexture + seen := map[uintptr]bool{} + for _, pass := range frame.Passes { + for _, cmd := range pass.Commands { + if cmd.Kind != driver.GPUCmdSetBindGroup { + continue + } + bg := c.bindGroups[cmd.ID] + if bg == nil { + continue + } + for _, e := range bg.entries { + t := c.textures[e.Texture] + if e.Texture == 0 || t == nil || t.external == nil || !t.external.KeyedMutex || seen[t.external.Handle] { + continue + } + seen[t.external.Handle] = true + hr, err := c.ops.AcquireKeyedMutex(t, t.external.AcquireKey, d3dKeyedMutexAcquireTimeoutMS) + switch { + case err != nil: + c.emitError(driver.GPUErrorFailed, err.Error()) + case hr == d3dKeyedMutexWaitTimeout: + c.emitError(driver.GPUErrorFailed, fmt.Sprintf("d3d11: imported texture %d: keyed mutex key %d not released within %d ms", t.id, t.external.AcquireKey, d3dKeyedMutexAcquireTimeoutMS)) + default: + held = append(held, t) + } + } + } + } + return held +} + +// releaseExternal releases the keyed mutexes acquireExternal took on textures that are still open. +func (c *d3dGPUController) releaseExternal(held []*d3dTrackedTexture) { + for _, t := range held { + if c.textures[t.id] == t { + c.ops.ReleaseKeyedMutex(t, t.external.ReleaseKey) + } + } +} + func (c *d3dGPUController) checkDeviceLost(hr uint32, msg string) bool { if d3dIsDeviceLostHR(hr) { c.NotifyDeviceLost(hr, msg) diff --git a/internal/platform/windows/gpu_d3d11_test.go b/internal/platform/windows/gpu_d3d11_test.go index e842d4082..a0cba3114 100644 --- a/internal/platform/windows/gpu_d3d11_test.go +++ b/internal/platform/windows/gpu_d3d11_test.go @@ -3,6 +3,7 @@ package windows import ( "bytes" "errors" + "fmt" "math" "strings" "testing" @@ -304,6 +305,9 @@ type fakeD3D11Ops struct { executedPasses int executedCopies int readbackPixelsOut []byte + imports int + keyedMutexBusy bool + keyedMutexLog []string } func (f *fakeD3D11Ops) alloc(kind string) *fakeD3DHandle { @@ -377,6 +381,23 @@ func (f *fakeD3D11Ops) ReadTexture(swap d3dReleaser, swapW, swapH uint32, tex *d return append([]byte(nil), f.readbackPixelsOut...), 0, nil } +func (f *fakeD3D11Ops) ImportTexture(desc driver.GPUExternalTextureDesc) (d3dReleaser, d3d11Texture2DDesc, uint32, error) { + f.imports++ + return f.alloc("imported texture"), d3d11Texture2DDesc{width: desc.Width, height: desc.Height, mipLevels: 1, arraySize: 1}, 0, nil +} + +func (f *fakeD3D11Ops) AcquireKeyedMutex(tex *d3dTrackedTexture, key uint64, timeoutMS uint32) (uint32, error) { + if f.keyedMutexBusy { + return d3dKeyedMutexWaitTimeout, nil + } + f.keyedMutexLog = append(f.keyedMutexLog, fmt.Sprintf("acquire %d:%d", tex.id, key)) + return 0, nil +} + +func (f *fakeD3D11Ops) ReleaseKeyedMutex(tex *d3dTrackedTexture, key uint64) { + f.keyedMutexLog = append(f.keyedMutexLog, fmt.Sprintf("release %d:%d", tex.id, key)) +} + func (f *fakeD3D11Ops) DeviceRemovedReason() uint32 { return f.deviceRemovedHR } @@ -618,3 +639,95 @@ type fakeReadbackLossOps struct { func (f *fakeReadbackLossOps) ReadTexture(swap d3dReleaser, swapW, swapH uint32, tex *d3dTrackedTexture, region driver.GPUTextureRegion, surface bool) ([]byte, uint32, error) { return nil, dxgiHRErrDeviceRemoved, errors.New("simulated readback device removed") } + +func TestD3D11ExternalSRVDescriptor(t *testing.T) { + nv12 := d3d11Texture2DDesc{width: 64, height: 35, mipLevels: 1, arraySize: 1, format: dxgiFmtNV12, sampleCount: 1, bindFlags: d3d11BindShaderResource, misc: d3d11MiscSharedNTHandle | d3d11MiscSharedKeyedMutex} + for _, tc := range []struct { + name string + td d3d11Texture2DDesc + ext driver.GPUExternalTextureDesc + want uint32 + fails bool + }{ + {"NV12 luma", nv12, driver.GPUExternalTextureDesc{Width: 64, Height: 35, Format: driver.GPUFormatR8Unorm}, dxgiFmtR8Unorm, false}, + {"NV12 chroma rounds up", nv12, driver.GPUExternalTextureDesc{Width: 32, Height: 18, Plane: 1, Format: driver.GPUFormatRG8Unorm, KeyedMutex: true}, dxgiFmtR8G8Unorm, false}, + {"P010 chroma", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 1, format: dxgiFmtP010, bindFlags: d3d11BindShaderResource}, driver.GPUExternalTextureDesc{Width: 4, Height: 4, Plane: 1, Format: driver.GPUFormatRG16Unorm}, dxgiFmtR16G16Unorm, false}, + {"BGRA", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 1, format: dxgiFmtB8G8R8A8Unorm, bindFlags: d3d11BindShaderResource}, driver.GPUExternalTextureDesc{Width: 8, Height: 8, Format: driver.GPUFormatBGRA8Unorm}, dxgiFmtB8G8R8A8Unorm, false}, + {"wrong plane format", nv12, driver.GPUExternalTextureDesc{Width: 32, Height: 18, Plane: 1, Format: driver.GPUFormatR8Unorm}, 0, true}, + {"wrong size", nv12, driver.GPUExternalTextureDesc{Width: 64, Height: 36, Format: driver.GPUFormatR8Unorm}, 0, true}, + {"plane of a single-plane texture", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 1, format: dxgiFmtR8Unorm, bindFlags: d3d11BindShaderResource}, driver.GPUExternalTextureDesc{Width: 8, Height: 8, Plane: 1, Format: driver.GPUFormatR8Unorm}, 0, true}, + {"array", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 4, format: dxgiFmtNV12, bindFlags: d3d11BindShaderResource}, driver.GPUExternalTextureDesc{Width: 8, Height: 8, Format: driver.GPUFormatR8Unorm}, 0, true}, + {"not a shader resource", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 1, format: dxgiFmtNV12}, driver.GPUExternalTextureDesc{Width: 8, Height: 8, Format: driver.GPUFormatR8Unorm}, 0, true}, + {"no keyed mutex", d3d11Texture2DDesc{width: 8, height: 8, arraySize: 1, format: dxgiFmtNV12, bindFlags: d3d11BindShaderResource}, driver.GPUExternalTextureDesc{Width: 8, Height: 8, Format: driver.GPUFormatR8Unorm, KeyedMutex: true}, 0, true}, + } { + srv, err := d3dExternalSRVDescriptor(tc.td, tc.ext) + if tc.fails { + if err == nil { + t.Errorf("%s: no error, srv %+v", tc.name, srv) + } + continue + } + if err != nil || srv.format != tc.want || srv.viewDimension != d3d11SRVDimTexture2D || srv.u1 != 1 { + t.Errorf("%s: srv %+v, err %v", tc.name, srv, err) + } + } +} + +func TestD3D11ControllerImportsTexturesAndHoldsKeyedMutexWhileDrawing(t *testing.T) { + ops := &fakeD3D11Ops{} + var errs []string + ctrl := newD3DGPUController(ops, func(ev *driver.GPUEvent) { + if ev.Kind == driver.GPUEventError { + errs = append(errs, ev.Message) + } + }) + if !ctrl.MountOrResize(16, 16) { + t.Fatal("mount failed") + } + luma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: 16, Height: 16, Format: driver.GPUFormatR8Unorm, Handle: 0x40, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 0} + chroma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: 8, Height: 8, Plane: 1, Format: driver.GPUFormatRG8Unorm, Handle: 0x40, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 0} + pass := driver.GPUPass{ + ColorAttachments: []driver.GPUColorAttachment{{LoadOp: driver.GPULoadClear, StoreOp: driver.GPUStoreStore}}, + Commands: []driver.GPUCommand{{Kind: driver.GPUCmdSetBindGroup, ID: 3}, {Kind: driver.GPUCmdDraw, U0: 3}}, + } + ctrl.Submit(driver.GPUFrame{ + Generation: 1, + Ops: []driver.GPUResourceOp{ + {Kind: driver.GPUOpImportTexture, ID: 1, External: luma}, + {Kind: driver.GPUOpImportTexture, ID: 2, External: chroma}, + {Kind: driver.GPUOpCreateBindGroup, ID: 3, BindGroup: &driver.GPUBindGroupDesc{Entries: []driver.GPUBindGroupEntry{{Binding: 0, Texture: 1}, {Binding: 1, Texture: 2}}}}, + // Writes to an imported texture are dropped. + {Kind: driver.GPUOpWriteTexture, ID: 1, Data: []byte{1}}, + }, + Passes: []driver.GPUPass{pass}, + Present: true, + }) + if ops.imports != 2 || ctrl.textures[1].external == nil || ctrl.textures[2].desc.Format != driver.GPUFormatRG8Unorm { + t.Fatalf("imports = %d, textures = %+v", ops.imports, ctrl.textures) + } + // Both planes share one handle, so its mutex is taken once, around the pass. + if len(ops.keyedMutexLog) != 2 || !strings.HasPrefix(ops.keyedMutexLog[0], "acquire ") || !strings.HasSuffix(ops.keyedMutexLog[0], ":1") || !strings.HasSuffix(ops.keyedMutexLog[1], ":0") { + t.Fatalf("keyed mutex log = %v", ops.keyedMutexLog) + } + // A frame that does not bind them leaves the mutex alone. + ops.keyedMutexLog = nil + ctrl.Submit(driver.GPUFrame{Generation: 1, Passes: []driver.GPUPass{{ColorAttachments: pass.ColorAttachments}}, Present: true}) + if len(ops.keyedMutexLog) != 0 { + t.Fatalf("keyed mutex log without bindings = %v", ops.keyedMutexLog) + } + // A mutex the decoder keeps is reported, and not released. + ops.keyedMutexBusy = true + ctrl.Submit(driver.GPUFrame{Generation: 1, Passes: []driver.GPUPass{pass}, Present: true}) + if len(errs) != 1 || !strings.Contains(errs[0], "keyed mutex") || len(ops.keyedMutexLog) != 0 { + t.Fatalf("busy mutex errors = %v, log = %v", errs, ops.keyedMutexLog) + } + // Destroying both releases what the imports opened. + ctrl.Submit(driver.GPUFrame{Generation: 1, Ops: []driver.GPUResourceOp{{Kind: driver.GPUOpDestroyTexture, ID: 1}, {Kind: driver.GPUOpDestroyTexture, ID: 2}}}) + if ops.alive != 1 || len(ctrl.textures) != 0 { + t.Fatalf("alive after destroying imports = %d (want the swap chain only), textures = %v", ops.alive, ctrl.textures) + } + ctrl.Release() + if ops.alive != 0 { + t.Fatalf("leak: alive = %d", ops.alive) + } +} diff --git a/internal/platform/windows/gpu_external.go b/internal/platform/windows/gpu_external.go new file mode 100644 index 000000000..dfb1e04fd --- /dev/null +++ b/internal/platform/windows/gpu_external.go @@ -0,0 +1,155 @@ +//go:build windows + +package windows + +import ( + "errors" + "unsafe" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// Importing textures other Direct3D 11 devices share (gpu.ExternalD3D11Shared, #2296). + +var ( + iidD3D11Device1 = parseGUID("a04bfb29-08ef-43d6-a49c-a9bdbdcbe686") + iidD3D11Device3 = parseGUID("a05c8c37-d2c6-4732-b3a0-9ce0b0dc9ae6") + iidD3D11Texture2D = parseGUID("6f15aaf2-d208-4e89-9ab4-489535d34f9c") + iidDXGIKeyedMutex = parseGUID("9d8e1289-d7b3-465f-8126-250e349af85d") +) + +// Vtable indexes (d3d11_1.h, d3d11.h, dxgi.h). +const ( + d3d1OpenSharedResource1 = 48 // ID3D11Device1 + d3d3CreateSRV1 = 57 // ID3D11Device3::CreateShaderResourceView1 + tex2DGetDesc = 10 // ID3D11Texture2D + keyedMutexAcquireSync = 8 // IDXGIKeyedMutex + keyedMutexReleaseSync = 9 +) + +// d3d11SharedTexture is a shared texture opened once for all the planes imported from its handle: opening a handle twice can make two resources, and holding the keyed mutex of one does not make the other's contents visible. +type d3d11SharedTexture struct { + ops *d3d11NativeOps + handle uintptr + tex *comObject + mutex *comObject + refs int +} + +func (s *d3d11SharedTexture) release() { + if s.refs--; s.refs > 0 { + return + } + releaseAll(&s.mutex, &s.tex) + if s.ops.shared[s.handle] == s { + delete(s.ops.shared, s.handle) + } +} + +// openShared returns the shared texture of handle, opening it on the device the GPU views render with the first time. +func (n *d3d11NativeOps) openShared(d3d *comObject, handle uintptr) (*d3d11SharedTexture, uint32, error) { + if s := n.shared[handle]; s != nil { + s.refs++ + return s, 0, nil + } + dev1 := d3d.query(&iidD3D11Device1) + if dev1 == nil { + return nil, 0, errors.New("d3d11: ID3D11Device1 is unavailable, so shared textures cannot be opened") + } + defer dev1.release() + s := &d3d11SharedTexture{ops: n, handle: handle, refs: 1} + if hr := dev1.call(d3d1OpenSharedResource1, handle, uintptr(unsafe.Pointer(&iidD3D11Texture2D)), uintptr(unsafe.Pointer(&s.tex))); failed(hr) { + return nil, uint32(hr), hresultError("d3d11: OpenSharedResource1", hr) + } + if n.shared == nil { + n.shared = map[uintptr]*d3d11SharedTexture{} + } + n.shared[handle] = s + return s, 0, nil +} + +// ImportTexture opens the shared NT handle and makes a view of the plane ext names. +func (n *d3d11NativeOps) ImportTexture(ext driver.GPUExternalTextureDesc) (d3dReleaser, d3d11Texture2DDesc, uint32, error) { + g, err := devices() + if err != nil { + return nil, d3d11Texture2DDesc{}, 0, err + } + s, hr, err := n.openShared(g.d3d, ext.Handle) + if err != nil { + return nil, d3d11Texture2DDesc{}, hr, err + } + s.tex.addRef() + h := &d3d11TextureHandle{tex: s.tex, shared: s} + var td d3d11Texture2DDesc + h.tex.call(tex2DGetDesc, uintptr(unsafe.Pointer(&td))) + srv, err := d3dExternalSRVDescriptor(td, ext) + if err != nil { + h.Release() + return nil, td, 0, err + } + if err := createPlaneSRV(g.d3d, h, srv, ext.Plane); err != nil { + h.Release() + return nil, td, 0, err + } + if ext.KeyedMutex { + if s.mutex == nil { + s.mutex = s.tex.query(&iidDXGIKeyedMutex) + } + if s.mutex == nil { + h.Release() + return nil, td, 0, errors.New("d3d11: imported texture has no IDXGIKeyedMutex") + } + s.mutex.addRef() + h.mutex = s.mutex + } + return h, td, 0, nil +} + +// createPlaneSRV makes h's view of plane: through ID3D11Device3::CreateShaderResourceView1, which names the plane, where the device has it, as drivers do not all pick the chroma plane of an NV12 or P010 texture from a two-channel view's format alone. +func createPlaneSRV(d3d *comObject, h *d3d11TextureHandle, srv d3d11SRVDesc, plane uint32) error { + if dev3 := d3d.query(&iidD3D11Device3); dev3 != nil { + defer dev3.release() + // D3D11_SHADER_RESOURCE_VIEW_DESC1's Texture2D is MostDetailedMip, MipLevels and PlaneSlice. + srv1 := srv + srv1.u2 = plane + if hr := dev3.call(d3d3CreateSRV1, h.tex.ptr(), uintptr(unsafe.Pointer(&srv1)), uintptr(unsafe.Pointer(&h.srv))); failed(hr) { + return hresultError("d3d11: CreateShaderResourceView1 of an imported texture", hr) + } + return nil + } + if hr := d3d.call(d3dCreateShaderResourceView, h.tex.ptr(), uintptr(unsafe.Pointer(&srv)), uintptr(unsafe.Pointer(&h.srv))); failed(hr) { + return hresultError("d3d11: CreateShaderResourceView of an imported texture", hr) + } + return nil +} + +// keyedMutexArgs passes a UINT64 key as one argument on 64-bit Windows and as two on 32-bit. +func keyedMutexArgs(key uint64, rest ...uintptr) []uintptr { + if unsafe.Sizeof(uintptr(0)) == 8 { + return append([]uintptr{uintptr(key)}, rest...) + } + return append([]uintptr{uintptr(uint32(key)), uintptr(key >> 32)}, rest...) +} + +func (n *d3d11NativeOps) AcquireKeyedMutex(tex *d3dTrackedTexture, key uint64, timeoutMS uint32) (uint32, error) { + h, _ := tex.handle.(*d3d11TextureHandle) + if h == nil || h.mutex == nil { + return 0, errors.New("d3d11: imported texture has no keyed mutex") + } + hr := h.mutex.call(keyedMutexAcquireSync, keyedMutexArgs(key, uintptr(timeoutMS))...) + switch { + case uint32(hr) == d3dKeyedMutexWaitTimeout: + return d3dKeyedMutexWaitTimeout, nil + case uint32(hr) == d3dKeyedMutexWaitAbandoned: + return uint32(hr), errors.New("d3d11: the imported texture's keyed mutex was abandoned") + case failed(hr): + return uint32(hr), hresultError("d3d11: IDXGIKeyedMutex::AcquireSync", hr) + } + return 0, nil +} + +func (n *d3d11NativeOps) ReleaseKeyedMutex(tex *d3dTrackedTexture, key uint64) { + if h, _ := tex.handle.(*d3d11TextureHandle); h != nil && h.mutex != nil { + h.mutex.call(keyedMutexReleaseSync, keyedMutexArgs(key)...) + } +} diff --git a/internal/platform/windows/gpu_external_native_test.go b/internal/platform/windows/gpu_external_native_test.go new file mode 100644 index 000000000..ee1127fda --- /dev/null +++ b/internal/platform/windows/gpu_external_native_test.go @@ -0,0 +1,224 @@ +//go:build windows + +package windows + +import ( + "bytes" + "syscall" + "testing" + "unsafe" + + "github.com/nsgo-dev/nsgo/internal/driver" + "github.com/nsgo-dev/nsgo/internal/shader/wgsl" +) + +var iidDXGIResource1 = parseGUID("30961379-4609-4a41-998e-54fe567ee0c1") + +const ( + dxgiResource1CreateSharedHandle = 13 + dxgiSharedResourceRead = 0x80000000 + dxgiSharedResourceWrite = 1 +) + +// yuvPlanesWGSL samples an NV12 frame's luma and chroma planes into one color: (Y, U, V, 1). +const yuvPlanesWGSL = ` +@group(0) @binding(0) var lumaTex: texture_2d; +@group(0) @binding(1) var chromaTex: texture_2d; +@group(0) @binding(2) var samp: sampler; + +struct VOut { + @builtin(position) pos: vec4, + @location(0) uv: vec2, +} + +@vertex +fn vs_main(@location(0) pos: vec2, @location(1) uv: vec2) -> VOut { + var out: VOut; + out.pos = vec4(pos, 0.0, 1.0); + out.uv = uv; + return out; +} + +@fragment +fn fs_main(in: VOut) -> @location(0) vec4 { + let y = textureSample(lumaTex, samp, in.uv).r; + let c = textureSample(chromaTex, samp, in.uv).rg; + return vec4(y, c.r, c.g, 1.0); +} +` + +// TestD3D11ImportedNV12MatchesUpload writes an NV12 frame on a second Direct3D 11 device, as a decoder would, shares it with a keyed mutex, imports both planes, and checks that sampling them renders exactly what sampling the same bytes uploaded with WriteTexture does; closing the imports releases what they opened. +func TestD3D11ImportedNV12MatchesUpload(t *testing.T) { + if !gpuAvailable() { + t.Skip("Direct3D 11 or D3DCompile unavailable") + } + if _, err := devices(); err != nil { + t.Skip(err) + } + const w, h = 8, 4 + // NV12: w x h luma bytes, then w/2 x h/2 interleaved U, V pairs, both w bytes a row. + frame := make([]byte, w*h+w*h/2) + for i := range w * h { + frame[i] = byte(16 + i*7) + } + for i := range w * h / 2 { + frame[w*h+i] = byte(240 - i*13) + } + + decoder, err := createD3D(d3dDriverHardware) + if err != nil { + if decoder, err = createD3D(d3dDriverWARP); err != nil { + t.Skip(err) + } + } + defer decoder.release() + td := d3d11Texture2DDesc{ + width: w, height: h, mipLevels: 1, arraySize: 1, format: dxgiFmtNV12, sampleCount: 1, + usage: d3d11UsageDefault, bindFlags: d3d11BindShaderResource, + misc: d3d11MiscSharedNTHandle | d3d11MiscSharedKeyedMutex, + } + init := d3d11SubresourceData{pSysMem: uintptr(unsafe.Pointer(&frame[0])), sysMemPitch: w} + var shared *comObject + if hr := decoder.call(d3dCreateTexture2D, uintptr(unsafe.Pointer(&td)), uintptr(unsafe.Pointer(&init)), uintptr(unsafe.Pointer(&shared))); failed(hr) { + t.Skip(hresultError("this adapter cannot create shared NV12 textures", hr)) + } + defer shared.release() + res := shared.query(&iidDXGIResource1) + if res == nil { + t.Fatal("no IDXGIResource1") + } + var handle uintptr + hr := res.call(dxgiResource1CreateSharedHandle, 0, dxgiSharedResourceRead|dxgiSharedResourceWrite, 0, uintptr(unsafe.Pointer(&handle))) + res.release() + if failed(hr) { + t.Fatal(hresultError("CreateSharedHandle", hr)) + } + defer syscall.CloseHandle(syscall.Handle(handle)) + // The decoder takes key 0, has written the frame, and hands it over as key 1. + mutex := shared.query(&iidDXGIKeyedMutex) + if mutex == nil { + t.Fatal("no IDXGIKeyedMutex") + } + defer mutex.release() + if hr := mutex.call(keyedMutexAcquireSync, keyedMutexArgs(0, 1000)...); failed(hr) || uint32(hr) == d3dKeyedMutexWaitTimeout { + t.Fatalf("decoder AcquireSync(0) = %#x", hr) + } + if hr := mutex.call(keyedMutexReleaseSync, keyedMutexArgs(1)...); failed(hr) { + t.Fatal(hresultError("decoder ReleaseSync(1)", hr)) + } + + prog, err := wgsl.CompilePipeline(yuvPlanesWGSL) + if err != nil { + t.Fatal(err) + } + var events []*driver.GPUEvent + ops := &d3d11NativeOps{scaleFn: func() float32 { return 1 }} + ctrl := newD3DGPUController(ops, func(ev *driver.GPUEvent) { events = append(events, ev) }) + defer ctrl.Release() + ctrl.Configure(driver.GPUViewConfig{ColorFormat: driver.GPUFormatBGRA8Unorm, SampleCount: 1}) + if !ctrl.MountOrResize(w, h) { + t.Fatalf("MountOrResize failed: %+v", events) + } + + quad := packF32( + -1, -1, 0, 1, + 1, -1, 1, 1, + 1, 1, 1, 0, + -1, -1, 0, 1, + 1, 1, 1, 0, + -1, 1, 0, 0, + ) + sampled := driver.GPUTextureSampled | driver.GPUTextureCopyDst + target := driver.GPUTextureRenderAttachment | driver.GPUTextureCopySrc + pass := func(target, group driver.GPUID) driver.GPUPass { + return driver.GPUPass{ + ColorAttachments: []driver.GPUColorAttachment{{Texture: target, LoadOp: driver.GPULoadClear, StoreOp: driver.GPUStoreStore}}, + Commands: []driver.GPUCommand{ + {Kind: driver.GPUCmdSetPipeline, ID: 20}, + {Kind: driver.GPUCmdSetBindGroup, ID: group}, + {Kind: driver.GPUCmdSetVertexBuffer, ID: 1}, + {Kind: driver.GPUCmdDraw, U0: 6}, + }, + } + } + ctrl.Submit(driver.GPUFrame{ + Generation: 1, + Ops: []driver.GPUResourceOp{ + {Kind: driver.GPUOpCreateBuffer, ID: 1, Buffer: &driver.GPUBufferDesc{Size: uint64(len(quad)), Usage: driver.GPUBufferVertex, Data: quad}}, + {Kind: driver.GPUOpCreateSampler, ID: 2, Sampler: &driver.GPUSamplerDesc{MinFilter: driver.GPUFilterNearest, MagFilter: driver.GPUFilterNearest, AddressU: driver.GPUAddressClampToEdge, AddressV: driver.GPUAddressClampToEdge}}, + {Kind: driver.GPUOpImportTexture, ID: 3, External: &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: w, Height: h, Format: driver.GPUFormatR8Unorm, Handle: handle, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 1}}, + {Kind: driver.GPUOpImportTexture, ID: 4, External: &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: w / 2, Height: h / 2, Plane: 1, Format: driver.GPUFormatRG8Unorm, Handle: handle, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 1}}, + {Kind: driver.GPUOpCreateTexture, ID: 5, Texture: &driver.GPUTextureDesc{Width: w, Height: h, Format: driver.GPUFormatR8Unorm, Usage: sampled}}, + {Kind: driver.GPUOpWriteTexture, ID: 5, Data: frame[:w*h], TextureDst: driver.GPUTextureCopy{Texture: 5}, DataLayout: driver.GPUDataLayout{BytesPerRow: w, RowsPerImage: h}}, + {Kind: driver.GPUOpCreateTexture, ID: 6, Texture: &driver.GPUTextureDesc{Width: w / 2, Height: h / 2, Format: driver.GPUFormatRG8Unorm, Usage: sampled}}, + {Kind: driver.GPUOpWriteTexture, ID: 6, Data: frame[w*h:], TextureDst: driver.GPUTextureCopy{Texture: 6}, DataLayout: driver.GPUDataLayout{BytesPerRow: w, RowsPerImage: h / 2}}, + {Kind: driver.GPUOpCreateBindGroupLayout, ID: 7, BindGroupLayout: &driver.GPUBindGroupLayoutDesc{}}, + {Kind: driver.GPUOpCreateBindGroup, ID: 8, BindGroup: &driver.GPUBindGroupDesc{Layout: 7, Entries: []driver.GPUBindGroupEntry{{Binding: 0, Texture: 3}, {Binding: 1, Texture: 4}, {Binding: 2, Sampler: 2}}}}, + {Kind: driver.GPUOpCreateBindGroup, ID: 9, BindGroup: &driver.GPUBindGroupDesc{Layout: 7, Entries: []driver.GPUBindGroupEntry{{Binding: 0, Texture: 5}, {Binding: 1, Texture: 6}, {Binding: 2, Sampler: 2}}}}, + {Kind: driver.GPUOpCreateTexture, ID: 10, Texture: &driver.GPUTextureDesc{Width: w, Height: h, Format: driver.GPUFormatRGBA8Unorm, Usage: target}}, + {Kind: driver.GPUOpCreateTexture, ID: 11, Texture: &driver.GPUTextureDesc{Width: w, Height: h, Format: driver.GPUFormatRGBA8Unorm, Usage: target}}, + {Kind: driver.GPUOpCreatePipeline, ID: 20, Pipeline: &driver.GPUPipelineDesc{ + Vertex: driver.GPUShaderStage{IR: prog.IR, EntryPoint: "vs_main"}, + Fragment: driver.GPUShaderStage{IR: prog.IR, EntryPoint: "fs_main"}, + Layouts: []driver.GPUID{7}, + VertexBuffers: []driver.GPUVertexBufferLayout{{Stride: 16, Attributes: []driver.GPUVertexAttribute{ + {Location: 0, Offset: 0, Format: driver.GPUVertexFloat32x2}, + {Location: 1, Offset: 8, Format: driver.GPUVertexFloat32x2}, + }}}, + Primitive: driver.GPUPrimitiveState{Topology: driver.GPUTopologyTriangleList}, + Targets: []driver.GPUColorTargetState{{Format: driver.GPUFormatRGBA8Unorm}}, + }}, + {Kind: driver.GPUOpReadTexture, ID: 10, ReadbackID: 1, ReadbackRegion: driver.GPUTextureRegion{Width: w, Height: h}}, + {Kind: driver.GPUOpReadTexture, ID: 11, ReadbackID: 2, ReadbackRegion: driver.GPUTextureRegion{Width: w, Height: h}}, + }, + Passes: []driver.GPUPass{pass(10, 8), pass(11, 9)}, + }) + read := map[uint64][]byte{} + for _, ev := range events { + switch ev.Kind { + case driver.GPUEventError: + t.Fatalf("GPU error: %s", ev.Message) + case driver.GPUEventReadback: + if ev.Message != "" { + t.Fatalf("readback %d: %s", ev.ReadbackID, ev.Message) + } + read[ev.ReadbackID] = ev.Pixels + } + } + imported, uploaded := read[1], read[2] + if len(imported) != w*h*4 || !bytes.Equal(imported, uploaded) { + t.Fatalf("imported NV12 rendered\n%v\nuploaded planes rendered\n%v", imported, uploaded) + } + // Pixel (3, 1) samples luma byte 1*w+3 and the chroma pair at (1, 0). + if px := imported[(1*w+3)*4:][:4]; px[0] != frame[1*w+3] || px[1] != frame[w*h+2] || px[2] != frame[w*h+3] { + t.Fatalf("pixel (3, 1) = %v, want Y %d U %d V %d", px, frame[1*w+3], frame[w*h+2], frame[w*h+3]) + } + // The renderer gave key 1 back, so the decoder can take it again. + if hr := mutex.call(keyedMutexAcquireSync, keyedMutexArgs(1, 1000)...); failed(hr) || uint32(hr) == d3dKeyedMutexWaitTimeout { + t.Fatalf("decoder AcquireSync(1) after rendering = %#x", hr) + } + mutex.call(keyedMutexReleaseSync, keyedMutexArgs(1)...) + + if len(ops.shared) != 1 { + t.Fatalf("both planes should view one opened texture, have %d", len(ops.shared)) + } + // Closing the imports releases the views they made and the texture they opened. + var views []*comObject + for _, id := range []driver.GPUID{3, 4} { + srv := ctrl.textures[id].handle.(*d3d11TextureHandle).srv + srv.addRef() + views = append(views, srv) + } + ctrl.Submit(driver.GPUFrame{Generation: 1, Ops: []driver.GPUResourceOp{{Kind: driver.GPUOpDestroyTexture, ID: 3}, {Kind: driver.GPUOpDestroyTexture, ID: 4}}}) + if ctrl.textures[3] != nil || ctrl.textures[4] != nil { + t.Fatal("imported textures outlived their destroy") + } + for i, srv := range views { + if refs := srv.call(comRelease); refs != 0 { + t.Errorf("plane %d's view has %d references left after its destroy", i, refs) + } + } + if len(ops.shared) != 0 { + t.Errorf("the opened shared texture outlived its planes") + } +} From 716c7cb5360e6d0326c3985be2ef5f0596368fdc Mon Sep 17 00:00:00 2001 From: ONEO Date: Tue, 24 Nov 2026 20:11:09 +0800 Subject: [PATCH 2/2] fix(windows): scope shared GPU handle cache per submit and document KeyedMutex reuse --- docs/architecture/gpu.md | 2 +- gpu/external.go | 2 +- internal/platform/windows/gpu.go | 2 +- internal/platform/windows/gpu_d3d11_desc.go | 45 ++++++---- internal/platform/windows/gpu_d3d11_test.go | 83 ++++++++++++++++++- internal/platform/windows/gpu_external.go | 9 +- .../windows/gpu_external_native_test.go | 14 +++- 7 files changed, 133 insertions(+), 24 deletions(-) diff --git a/docs/architecture/gpu.md b/docs/architecture/gpu.md index aaadc07c5..be980dc10 100644 --- a/docs/architecture/gpu.md +++ b/docs/architecture/gpu.md @@ -302,7 +302,7 @@ return gpu.View{ `Device.ImportTexture` ([#2296](https://github.com/nsgo-dev/nsgo/issues/2296)) opens GPU memory another device owns, such as a hardware decoder's frame, as a sampled 2D texture without copying it; `Device.SupportsExternalTexture(kind)` (`Features.ImportD3D11Shared`, `Features.ImportDMABuf`) says whether a target can, and elsewhere it returns `ErrUnsupported`, so callers fall back to `WriteTexture`. - **One plane per import**: an NV12 frame is two textures, luma `FormatR8Unorm` and chroma `FormatRG8Unorm` at half size, and P010's are the import-only `FormatR16Unorm` and `FormatRG16Unorm`, which `CreateTexture` rejects. Shaders keep a plain `texture_2d` and convert YUV themselves, so no backend needs `samplerExternalOES` or a YCbCr sampler. -- **Windows**: the backend opens the NT handle with `ID3D11Device1::OpenSharedResource1` once per handle, whose planes share that resource (opening it twice can yield two resources, and the keyed mutex of one does not make the other's writes visible), and views the plane with `CreateShaderResourceView1`'s `PlaneSlice`. With `KeyedMutex`, it acquires `AcquireKey` (100 ms at most, reporting a timeout on `OnError`) before a frame whose passes bind the texture and releases `ReleaseKey` after them. +- **Windows**: the backend opens the NT handle with `ID3D11Device1::OpenSharedResource1` once per handle within a `Submit`, so planes imported together share that resource (opening a handle twice can yield two resources, and the keyed mutex of one does not make the other's writes visible) while handle values closed and recycled by Windows in a later `Submit` open the new resource, and views the plane with `CreateShaderResourceView1`'s `PlaneSlice`. With `KeyedMutex`, each frame whose passes bind the texture acquires `AcquireKey` (100 ms at most, reporting a timeout on `OnError`) before the passes and releases `ReleaseKey` after them. - **Linux**: the backend makes an EGLImage with `EGL_EXT_image_dma_buf_import` (naming the modifier where `_modifiers` is present) on the display `eglGetCurrentDisplay` gives inside the `GtkGLArea`'s context, and binds it with `glEGLImageTargetTexture2DOES`; a GLX context reports no support. - **Lifetime**: the caller keeps the handle or file descriptors, open until the first frame submitted after the import completes. Imported textures are only sampled: writes, copies, readbacks and render passes on them are dropped or rejected, and they are not retained across device loss. Closing one releases what the backend opened after the frames already submitted, so a decoder's frame goes back to its pool once the `FrameFence` of the last frame that sampled it completes. diff --git a/gpu/external.go b/gpu/external.go index d26a87b9c..fe245dca3 100644 --- a/gpu/external.go +++ b/gpu/external.go @@ -44,7 +44,7 @@ type ExternalTextureDesc struct { Handle uintptr // Plane picks the plane of an NV12 or P010 texture: 0 for luma, 1 for chroma (ExternalD3D11Shared). Plane uint32 - // KeyedMutex makes the backend hold the texture's IDXGIKeyedMutex while a submitted frame reads it, acquiring AcquireKey and releasing ReleaseKey (ExternalD3D11Shared). The texture must have been created with D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; with both keys 0 it is a plain mutex. + // KeyedMutex makes the backend hold the texture's IDXGIKeyedMutex while a submitted frame reads it, acquiring AcquireKey and releasing ReleaseKey (ExternalD3D11Shared). The texture must have been created with D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; with both keys 0 it is a plain mutex. Each submitted frame that binds the texture takes AcquireKey and releases ReleaseKey again, so use keys that allow repeated reads (such as equal keys) or sample each import in one frame only. KeyedMutex bool AcquireKey uint64 ReleaseKey uint64 diff --git a/internal/platform/windows/gpu.go b/internal/platform/windows/gpu.go index d85450ac7..22d5882c9 100644 --- a/internal/platform/windows/gpu.go +++ b/internal/platform/windows/gpu.go @@ -269,7 +269,7 @@ func (p *d3d11PipelineHandle) Release() { type d3d11NativeOps struct { scaleFn func() float32 - // shared holds each shared texture imports opened, by NT handle (gpu_external.go). + // shared holds each shared texture opened during the current Submit, by NT handle, cleared by EndImportBatch (gpu_external.go). shared map[uintptr]*d3d11SharedTexture } diff --git a/internal/platform/windows/gpu_d3d11_desc.go b/internal/platform/windows/gpu_d3d11_desc.go index 770286ebb..8e8a96718 100644 --- a/internal/platform/windows/gpu_d3d11_desc.go +++ b/internal/platform/windows/gpu_d3d11_desc.go @@ -1087,6 +1087,8 @@ type d3dTrackedTexture struct { handle d3dReleaser // external describes a texture opened by GPUOpImportTexture, which the controller only samples. external *driver.GPUExternalTextureDesc + // importBatch identifies the Submit that imported this texture so planes imported together share one keyed-mutex acquisition while a recycled NT handle in a later Submit does not alias them. + importBatch uint64 } type d3dTrackedSampler struct { @@ -1136,6 +1138,8 @@ type d3dNativeOps interface { ReadTexture(swap d3dReleaser, swapW, swapH uint32, tex *d3dTrackedTexture, region driver.GPUTextureRegion, surface bool) ([]byte, uint32, error) // ImportTexture opens a shared texture's plane and returns its handle and the shared texture's descriptor. ImportTexture(desc driver.GPUExternalTextureDesc) (d3dReleaser, d3d11Texture2DDesc, uint32, error) + // EndImportBatch drops per-submit shared-handle cache entries without releasing opened textures, so an NT handle closed and recycled by Windows in a later Submit opens the new resource. + EndImportBatch() // AcquireKeyedMutex and ReleaseKeyedMutex hold an imported texture's IDXGIKeyedMutex; AcquireKeyedMutex returns d3dKeyedMutexWaitTimeout if it timed out. AcquireKeyedMutex(tex *d3dTrackedTexture, key uint64, timeoutMS uint32) (uint32, error) ReleaseKeyedMutex(tex *d3dTrackedTexture, key uint64) @@ -1147,13 +1151,14 @@ type d3dGPUController struct { ops d3dNativeOps emit func(*driver.GPUEvent) - cfg driver.GPUViewConfig - cfgDirty bool - pw, ph uint32 - generation uint32 - ready bool - lost bool - disposed bool + cfg driver.GPUViewConfig + cfgDirty bool + pw, ph uint32 + generation uint32 + importBatch uint64 + ready bool + lost bool + disposed bool swap d3dReleaser buffers map[driver.GPUID]*d3dTrackedBuffer @@ -1335,6 +1340,9 @@ func (c *d3dGPUController) Submit(frame driver.GPUFrame) (drewSwap bool) { var deferredReadbacks []driver.GPUResourceOp var deferredDestroys []driver.GPUResourceOp + c.importBatch++ + defer c.ops.EndImportBatch() + // Phase 1: creates and writes. for _, op := range frame.Ops { switch op.Kind { @@ -1555,9 +1563,10 @@ func (c *d3dGPUController) execCreateOrWrite(op driver.GPUResourceOp) bool { Format: ext.Format, Usage: driver.GPUTextureSampled, }, - texDesc: td, - handle: handle, - external: &ext, + texDesc: td, + handle: handle, + external: &ext, + importBatch: c.importBatch, } return true @@ -1702,10 +1711,14 @@ func (c *d3dGPUController) execDestroy(op driver.GPUResourceOp) { } } -// acquireExternal acquires the keyed mutex of each imported texture that frame's passes bind, once per shared handle, and returns those it holds. +// acquireExternal acquires the keyed mutex of each imported texture that frame's passes bind, once per shared handle within its import batch, and returns those it holds. func (c *d3dGPUController) acquireExternal(frame driver.GPUFrame) []*d3dTrackedTexture { + type sharedKey struct { + batch uint64 + handle uintptr + } var held []*d3dTrackedTexture - seen := map[uintptr]bool{} + seen := map[sharedKey]bool{} for _, pass := range frame.Passes { for _, cmd := range pass.Commands { if cmd.Kind != driver.GPUCmdSetBindGroup { @@ -1717,10 +1730,14 @@ func (c *d3dGPUController) acquireExternal(frame driver.GPUFrame) []*d3dTrackedT } for _, e := range bg.entries { t := c.textures[e.Texture] - if e.Texture == 0 || t == nil || t.external == nil || !t.external.KeyedMutex || seen[t.external.Handle] { + if e.Texture == 0 || t == nil || t.external == nil || !t.external.KeyedMutex { + continue + } + key := sharedKey{batch: t.importBatch, handle: t.external.Handle} + if seen[key] { continue } - seen[t.external.Handle] = true + seen[key] = true hr, err := c.ops.AcquireKeyedMutex(t, t.external.AcquireKey, d3dKeyedMutexAcquireTimeoutMS) switch { case err != nil: diff --git a/internal/platform/windows/gpu_d3d11_test.go b/internal/platform/windows/gpu_d3d11_test.go index a0cba3114..ce74c53e8 100644 --- a/internal/platform/windows/gpu_d3d11_test.go +++ b/internal/platform/windows/gpu_d3d11_test.go @@ -280,6 +280,7 @@ func TestD3D11BGRASwizzleAndDeviceLostHR(t *testing.T) { type fakeD3DHandle struct { kind string + sharedID int released *int alive *int closed bool @@ -306,6 +307,8 @@ type fakeD3D11Ops struct { executedCopies int readbackPixelsOut []byte imports int + sharedOpens int + shared map[uintptr]int keyedMutexBusy bool keyedMutexLog []string } @@ -383,7 +386,22 @@ func (f *fakeD3D11Ops) ReadTexture(swap d3dReleaser, swapW, swapH uint32, tex *d func (f *fakeD3D11Ops) ImportTexture(desc driver.GPUExternalTextureDesc) (d3dReleaser, d3d11Texture2DDesc, uint32, error) { f.imports++ - return f.alloc("imported texture"), d3d11Texture2DDesc{width: desc.Width, height: desc.Height, mipLevels: 1, arraySize: 1}, 0, nil + if f.shared == nil { + f.shared = map[uintptr]int{} + } + sid, ok := f.shared[desc.Handle] + if !ok { + f.sharedOpens++ + sid = f.sharedOpens + f.shared[desc.Handle] = sid + } + h := f.alloc("imported texture") + h.sharedID = sid + return h, d3d11Texture2DDesc{width: desc.Width, height: desc.Height, mipLevels: 1, arraySize: 1}, 0, nil +} + +func (f *fakeD3D11Ops) EndImportBatch() { + clear(f.shared) } func (f *fakeD3D11Ops) AcquireKeyedMutex(tex *d3dTrackedTexture, key uint64, timeoutMS uint32) (uint32, error) { @@ -731,3 +749,66 @@ func TestD3D11ControllerImportsTexturesAndHoldsKeyedMutexWhileDrawing(t *testing t.Fatalf("leak: alive = %d", ops.alive) } } + +// TestD3D11ImportedTextureRecycledHandleOpensFreshResource verifies that shared-handle deduplication is scoped to one Submit: when a frame destroys the previous imports and imports a new shared texture whose Windows NT handle value was recycled, phase 1 opens a fresh resource rather than reusing the old texture's cached entry (which is only destroyed in phase 5), and keyed-mutex acquisition does not alias distinct import batches. +func TestD3D11ImportedTextureRecycledHandleOpensFreshResource(t *testing.T) { + ops := &fakeD3D11Ops{} + ctrl := newD3DGPUController(ops, nil) + if !ctrl.MountOrResize(16, 16) { + t.Fatal("mount failed") + } + const recycledHandle = uintptr(0x40) + luma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: 16, Height: 16, Format: driver.GPUFormatR8Unorm, Handle: recycledHandle, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 1} + chroma := &driver.GPUExternalTextureDesc{Kind: driver.GPUExternalD3D11Shared, Width: 8, Height: 8, Plane: 1, Format: driver.GPUFormatRG8Unorm, Handle: recycledHandle, KeyedMutex: true, AcquireKey: 1, ReleaseKey: 1} + + // Frame 1: both planes imported in the same Submit share one opened resource. + ctrl.Submit(driver.GPUFrame{ + Generation: 1, + Ops: []driver.GPUResourceOp{ + {Kind: driver.GPUOpImportTexture, ID: 1, External: luma}, + {Kind: driver.GPUOpImportTexture, ID: 2, External: chroma}, + }, + }) + h1 := ctrl.textures[1].handle.(*fakeD3DHandle) + h2 := ctrl.textures[2].handle.(*fakeD3DHandle) + if ops.sharedOpens != 1 || h1.sharedID != 1 || h2.sharedID != 1 { + t.Fatalf("frame 1 shared opens=%d, ids=(%d,%d), want 1 and (1,1)", ops.sharedOpens, h1.sharedID, h2.sharedID) + } + if len(ops.shared) != 0 { + t.Fatalf("per-submit shared map was not cleared after frame 1: %v", ops.shared) + } + + // Frame 2: destroys frame 1's textures (phase 5) while importing frame 2's planes under the recycled handle value (phase 1). + // Also bind texture 1 (still alive during phases 2-3) alongside texture 3 to confirm keyed mutexes are not aliased across batches. + pass := driver.GPUPass{ + ColorAttachments: []driver.GPUColorAttachment{{LoadOp: driver.GPULoadClear, StoreOp: driver.GPUStoreStore}}, + Commands: []driver.GPUCommand{{Kind: driver.GPUCmdSetBindGroup, ID: 10}, {Kind: driver.GPUCmdDraw, U0: 3}}, + } + ctrl.Submit(driver.GPUFrame{ + Generation: 1, + Ops: []driver.GPUResourceOp{ + {Kind: driver.GPUOpDestroyTexture, ID: 1}, + {Kind: driver.GPUOpDestroyTexture, ID: 2}, + {Kind: driver.GPUOpImportTexture, ID: 3, External: luma}, + {Kind: driver.GPUOpImportTexture, ID: 4, External: chroma}, + {Kind: driver.GPUOpCreateBindGroup, ID: 10, BindGroup: &driver.GPUBindGroupDesc{Entries: []driver.GPUBindGroupEntry{{Binding: 0, Texture: 1}, {Binding: 1, Texture: 3}, {Binding: 2, Texture: 4}}}}, + }, + Passes: []driver.GPUPass{pass}, + }) + h3 := ctrl.textures[3].handle.(*fakeD3DHandle) + h4 := ctrl.textures[4].handle.(*fakeD3DHandle) + if ops.sharedOpens != 2 || h3.sharedID != 2 || h4.sharedID != 2 { + t.Fatalf("frame 2 shared opens=%d, ids=(%d,%d), want 2 and (2,2)", ops.sharedOpens, h3.sharedID, h4.sharedID) + } + if ctrl.textures[1] != nil || ctrl.textures[2] != nil { + t.Fatalf("frame 1 textures survived deferred destroy") + } + // Textures 1 (batch 1) and 3/4 (batch 2) must each acquire and release their own keyed mutex (2 acquires + 2 releases). + if len(ops.keyedMutexLog) != 4 { + t.Fatalf("keyed mutex log = %v, want 4 entries (two distinct batches)", ops.keyedMutexLog) + } + ctrl.Release() + if ops.alive != 0 { + t.Fatalf("leak: alive = %d", ops.alive) + } +} diff --git a/internal/platform/windows/gpu_external.go b/internal/platform/windows/gpu_external.go index dfb1e04fd..8a776ccf4 100644 --- a/internal/platform/windows/gpu_external.go +++ b/internal/platform/windows/gpu_external.go @@ -27,7 +27,7 @@ const ( keyedMutexReleaseSync = 9 ) -// d3d11SharedTexture is a shared texture opened once for all the planes imported from its handle: opening a handle twice can make two resources, and holding the keyed mutex of one does not make the other's contents visible. +// d3d11SharedTexture is a shared texture opened once for all the planes imported from its handle within one Submit: opening a handle twice can make two resources, and holding the keyed mutex of one does not make the other's contents visible. EndImportBatch drops the handle map entries after each Submit without releasing open textures so a handle value Windows later recycles opens the new resource. type d3d11SharedTexture struct { ops *d3d11NativeOps handle uintptr @@ -46,7 +46,12 @@ func (s *d3d11SharedTexture) release() { } } -// openShared returns the shared texture of handle, opening it on the device the GPU views render with the first time. +// EndImportBatch forgets this submit's handle-to-resource entries without releasing any imported textures' references. +func (n *d3d11NativeOps) EndImportBatch() { + clear(n.shared) +} + +// openShared returns the shared texture of handle for the current submit, opening it on the device the GPU views render with the first time in this submit. func (n *d3d11NativeOps) openShared(d3d *comObject, handle uintptr) (*d3d11SharedTexture, uint32, error) { if s := n.shared[handle]; s != nil { s.refs++ diff --git a/internal/platform/windows/gpu_external_native_test.go b/internal/platform/windows/gpu_external_native_test.go index ee1127fda..a4695ce09 100644 --- a/internal/platform/windows/gpu_external_native_test.go +++ b/internal/platform/windows/gpu_external_native_test.go @@ -199,10 +199,16 @@ func TestD3D11ImportedNV12MatchesUpload(t *testing.T) { } mutex.call(keyedMutexReleaseSync, keyedMutexArgs(1)...) - if len(ops.shared) != 1 { - t.Fatalf("both planes should view one opened texture, have %d", len(ops.shared)) + if len(ops.shared) != 0 { + t.Fatalf("EndImportBatch should clear the per-submit shared handle cache, have %d entries", len(ops.shared)) + } + h3 := ctrl.textures[3].handle.(*d3d11TextureHandle) + h4 := ctrl.textures[4].handle.(*d3d11TextureHandle) + if h3.shared == nil || h3.shared != h4.shared || h3.tex != h4.tex { + t.Fatalf("both planes should view one opened texture") } // Closing the imports releases the views they made and the texture they opened. + opened := h3.shared var views []*comObject for _, id := range []driver.GPUID{3, 4} { srv := ctrl.textures[id].handle.(*d3d11TextureHandle).srv @@ -218,7 +224,7 @@ func TestD3D11ImportedNV12MatchesUpload(t *testing.T) { t.Errorf("plane %d's view has %d references left after its destroy", i, refs) } } - if len(ops.shared) != 0 { - t.Errorf("the opened shared texture outlived its planes") + if opened.refs != 0 || opened.tex != nil || opened.mutex != nil { + t.Errorf("the opened shared texture outlived its planes: refs=%d tex=%v mutex=%v", opened.refs, opened.tex, opened.mutex) } }