Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowsd3d11rhitextureimporter.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
5
6#include <QtMultimedia/private/qvideotexturehelper_p.h>
7
8#include <QtGui/rhi/qrhi.h>
9
10#include <QtCore/qloggingcategory.h>
11#include <QtCore/qscopeguard.h>
12#include <QtCore/qvarlengtharray.h>
13#include <QtCore/private/qsystemerror_p.h>
14#include <QtCore/private/qexpected_p.h>
15
16#include <d3d11on12.h>
17#include <d3d12.h>
18
19#include <algorithm>
20
21#if QT_CONFIG(opengl)
22# include <QtMultimedia/private/qmultimedia_gl_support_p.h>
23# include <QtMultimedia/private/qrhivaluemapper_p.h>
24# include <QtGui/qopenglcontext.h>
25# include <QtGui/qopenglextrafunctions.h>
26# include <QtGui/qopenglfunctions.h>
27# include <QtGui/qopenglext.h>
28#endif
29
30QT_BEGIN_NAMESPACE
31
32namespace QtMultimediaPrivate {
33
34using namespace Qt::Literals;
35
36namespace {
37
38Q_LOGGING_CATEGORY(lcD3D11RhiTextureImporter, "qt.multimedia.windows.d3d11rhitextureimporter");
39
40class D3D11TextureHandles : public QVideoFrameTexturesHandles
41{
42public:
43 explicit D3D11TextureHandles(ComPtr<ID3D11Texture2D> tex) : m_tex(std::move(tex)) { }
44
45 quint64 textureHandle(QRhi &rhi, int /*plane*/) override
46 {
47 if (rhi.backend() != QRhi::D3D11)
48 return 0;
49 return quint64(m_tex.Get());
50 }
51
52private:
53 const ComPtr<ID3D11Texture2D> m_tex;
54};
55
56const QRhiD3D11NativeHandles *resolveD3D11NativeHandles(QRhi &rhi)
57{
58 Q_ASSERT(rhi.backend() == QRhi::D3D11);
59 return static_cast<const QRhiD3D11NativeHandles *>(rhi.nativeHandles());
60}
61
62q23::expected<ComPtr<ID3D11Device1>, HRESULT>
63resolveD3D11Device(const QRhiD3D11NativeHandles *nativeHandles)
64{
65 ComPtr<ID3D11Device> rhiDevice = static_cast<ID3D11Device *>(nativeHandles->dev);
66 ComPtr<ID3D11Device1> rhiDevice1;
67 if (const HRESULT hr = rhiDevice.As(&rhiDevice1); FAILED(hr))
68 return q23::unexpected{ hr };
69 return rhiDevice1;
70}
71
72// Exposes the D3D12 view of a D3D11 texture, unwrapped via D3D11On12
73class D3D12TextureHandles : public QVideoFrameTexturesHandles
74{
75public:
76 D3D12TextureHandles(ComPtr<ID3D12Resource> resource, ComPtr<ID3D11On12Device2> on12Device,
77 ComPtr<ID3D11Texture2D> wrappedResource,
78 std::shared_ptr<std::atomic_bool> wrappedResourceInUse)
79 : m_resource(std::move(resource)),
80 m_on12Device(std::move(on12Device)),
81 m_wrappedResource(std::move(wrappedResource)),
82 m_wrappedResourceInUse(std::move(wrappedResourceInUse))
83 {
84 }
85
86 ~D3D12TextureHandles() override
87 {
88 m_resource.Reset();
89 if (m_on12Device && m_wrappedResource)
90 m_on12Device->ReturnUnderlyingResource(m_wrappedResource.Get(), 0, nullptr, nullptr);
91 // Only now may the texture be reused for another frame.
92 if (m_wrappedResourceInUse)
93 m_wrappedResourceInUse->store(false);
94 }
95
96 quint64 textureHandle(QRhi &rhi, int /*plane*/) override
97 {
98 switch (rhi.backend()) {
99 case QRhi::D3D12:
100 return quint64(m_resource.Get());
101 default:
102 return 0;
103 }
104 }
105
106private:
107 ComPtr<ID3D12Resource> m_resource;
108 const ComPtr<ID3D11On12Device2> m_on12Device;
109 const ComPtr<ID3D11Texture2D> m_wrappedResource;
110 const std::shared_ptr<std::atomic_bool> m_wrappedResourceInUse;
111};
112
113#if QT_CONFIG(opengl)
114
115// WGL_NV_DX_interop2 function types
116using PFNWGLDXOPENDEVICENVPROC = HANDLE(WINAPI *)(void *);
117using PFNWGLDXCLOSEDEVICENVPROC = BOOL(WINAPI *)(HANDLE);
118using PFNWGLDXREGISTEROBJECTNVPROC = HANDLE(WINAPI *)(HANDLE, void *, GLuint, GLenum, GLenum);
119using PFNWGLDXUNREGISTEROBJECTNVPROC = BOOL(WINAPI *)(HANDLE, HANDLE);
120using PFNWGLDXLOCKOBJECTSNVPROC = BOOL(WINAPI *)(HANDLE, GLint, HANDLE *);
121using PFNWGLDXUNLOCKOBJECTSNVPROC = BOOL(WINAPI *)(HANDLE, GLint, HANDLE *);
122
123# ifndef WGL_ACCESS_READ_ONLY_NV
124# define WGL_ACCESS_READ_ONLY_NV 0x00000000
125# endif
126
127struct WglDxInterop
128{
129 PFNWGLDXOPENDEVICENVPROC wglDXOpenDeviceNV = nullptr;
130 PFNWGLDXCLOSEDEVICENVPROC wglDXCloseDeviceNV = nullptr;
131 PFNWGLDXREGISTEROBJECTNVPROC wglDXRegisterObjectNV = nullptr;
132 PFNWGLDXUNREGISTEROBJECTNVPROC wglDXUnregisterObjectNV = nullptr;
133 PFNWGLDXLOCKOBJECTSNVPROC wglDXLockObjectsNV = nullptr;
134 PFNWGLDXUNLOCKOBJECTSNVPROC wglDXUnlockObjectsNV = nullptr;
135
136 static WglDxInterop resolve(QOpenGLContext *ctx)
137 {
138 using namespace QtMultimediaPrivate;
139 WglDxInterop f;
140 if (!ctx)
141 return f;
142 f.wglDXOpenDeviceNV = resolveGlFunction<PFNWGLDXOPENDEVICENVPROC>(ctx, "wglDXOpenDeviceNV");
143 f.wglDXCloseDeviceNV =
144 resolveGlFunction<PFNWGLDXCLOSEDEVICENVPROC>(ctx, "wglDXCloseDeviceNV");
145 f.wglDXRegisterObjectNV =
146 resolveGlFunction<PFNWGLDXREGISTEROBJECTNVPROC>(ctx, "wglDXRegisterObjectNV");
147 f.wglDXUnregisterObjectNV =
148 resolveGlFunction<PFNWGLDXUNREGISTEROBJECTNVPROC>(ctx, "wglDXUnregisterObjectNV");
149 f.wglDXLockObjectsNV =
150 resolveGlFunction<PFNWGLDXLOCKOBJECTSNVPROC>(ctx, "wglDXLockObjectsNV");
151 f.wglDXUnlockObjectsNV =
152 resolveGlFunction<PFNWGLDXUNLOCKOBJECTSNVPROC>(ctx, "wglDXUnlockObjectsNV");
153 return f;
154 }
155
156 bool valid() const
157 {
158 return wglDXOpenDeviceNV && wglDXCloseDeviceNV && wglDXRegisterObjectNV
159 && wglDXUnregisterObjectNV && wglDXLockObjectsNV && wglDXUnlockObjectsNV;
160 }
161};
162
163QRhiValueMapper<WglDxInterop> g_wglDxInteropMapper;
164
165bool supportsGlCopy(QOpenGLContext &glCtx)
166{
167 return (glCtx.format().version() >= std::pair(4, 3)
168 || glCtx.hasExtension("GL_ARB_copy_image"_ba));
169}
170
171GLenum dxFormatToGlTextureFormat(DXGI_FORMAT d3dFormat)
172{
173 switch (d3dFormat) {
174 case DXGI_FORMAT_R8G8B8A8_UNORM:
175 return GL_RGBA8;
176 case DXGI_FORMAT_R8_UNORM:
177 return GL_R8;
178 case DXGI_FORMAT_R8G8_UNORM:
179 return GL_RG8;
180 case DXGI_FORMAT_R16_UNORM:
181 return GL_R16;
182 case DXGI_FORMAT_R16G16_UNORM:
183 return GL_RG16;
184 default:
185 return GLenum(0);
186 }
187}
188
189// Unlike the D3D11/D3D12 handles, which keep their shared source texture alive, the GL result
190// must survive the transient WGL registration (see importTextureOpenGL): makes a GPU-side copy
191// of 'source' into a standalone texture with its own storage. Leaves the GL_TEXTURE_2D binding
192// as found, since QRhi tracks GL state.
193GlTextureHandle copyToOwnedGlTexture(QOpenGLContext *glCtx, GLuint source, DXGI_FORMAT sourceFormat,
194 GLsizei width, GLsizei height)
195{
196 Q_ASSERT(supportsGlCopy(*glCtx));
197
198 const GLenum internalFormat = dxFormatToGlTextureFormat(sourceFormat);
199 if (!internalFormat) {
200 qCWarning(lcD3D11RhiTextureImporter)
201 << "Cannot import D3D11 texture to OpenGL: unsupported DXGI format" << sourceFormat;
202 return {};
203 }
204
205 QOpenGLExtraFunctions *f = glCtx->extraFunctions();
206 clearGlErrors(f);
207 const auto checkGlError = [&](const char *call) {
208 const GLError error = GLError(f->glGetError());
209 if (error == GLError::NoError)
210 return true;
211 qCWarning(lcD3D11RhiTextureImporter) << call << "failed with GL error" << error;
212 return false;
213 };
214
215 GLint previousBinding = 0;
216 f->glGetIntegerv(GL_TEXTURE_BINDING_2D, &previousBinding);
217 if (!checkGlError("glGetIntegerv(GL_TEXTURE_BINDING_2D)"))
218 return {};
219 auto restoreBinding = qScopeGuard([&] {
220 f->glBindTexture(GL_TEXTURE_2D, GLuint(previousBinding));
221 });
222
223 GLuint texId = 0;
224 f->glGenTextures(1, &texId);
225 if (!checkGlError("glGenTextures") || !texId)
226 return {};
227 GlTextureHandle result{
228 texId,
229 GlTextureDeleter{ glCtx },
230 };
231
232 f->glBindTexture(GL_TEXTURE_2D, texId);
233 if (!checkGlError("glBindTexture"))
234 return {};
235
236 f->glTexStorage2D(GL_TEXTURE_2D, 1, internalFormat, width, height);
237 if (!checkGlError("glTexStorage2D"))
238 return {};
239
240 f->glCopyImageSubData(source, GL_TEXTURE_2D, 0, 0, 0, 0, texId, GL_TEXTURE_2D, 0, 0, 0, 0,
241 width, height, 1);
242 if (!checkGlError("glCopyImageSubData"))
243 return {};
244
245 return result;
246}
247
248[[nodiscard]] bool isInteropSlotReusable(const WglDxInteropSlot &slot, DXGI_FORMAT format,
249 UINT width, UINT height)
250{
251 if (!slot.registration)
252 return false;
253 CD3D11_TEXTURE2D_DESC desc;
254 slot.texture->GetDesc(&desc);
255 return desc.Format == format && desc.Width == width && desc.Height == height;
256}
257
258[[nodiscard]] bool prepareInteropSlot(WglDxInteropSlot &slot, ID3D11Device *srcDevice,
259 const D3D11_TEXTURE2D_DESC &desc,
260 const WglDxDeviceHandle &interopDevice, QOpenGLContext *glCtx,
261 const WglDxInterop &wgl)
262{
263 if (isInteropSlotReusable(slot, desc.Format, desc.Width, desc.Height))
264 return true;
265
266 slot.reset();
267 auto failureCleanup = qScopeGuard([&] {
268 slot.reset();
269 });
270
271 if (FAILED(srcDevice->CreateTexture2D(&desc, nullptr, slot.texture.ReleaseAndGetAddressOf())))
272 return false;
273
274 GLuint texId = 0;
275 glCtx->functions()->glGenTextures(1, &texId);
276 if (!texId)
277 return false;
278
279 slot.glTexture = GlTextureHandle{
280 texId,
281 GlTextureDeleter{ glCtx },
282 };
283
284 HANDLE registration =
285 wgl.wglDXRegisterObjectNV(interopDevice.get(), slot.texture.Get(), slot.glTexture.get(),
286 GL_TEXTURE_2D, WGL_ACCESS_READ_ONLY_NV);
287 if (!registration) {
288 qCWarning(lcD3D11RhiTextureImporter) << "wglDXRegisterObjectNV failed";
289 return false;
290 }
291
292 failureCleanup.dismiss();
293
294 slot.registration = WglDxObjectHandle{
295 registration,
296 WglDxObjectDeleter{ interopDevice.get(), wgl.wglDXUnregisterObjectNV },
297 };
298 return true;
299}
300
301class OpenGLTextureHandles : public QVideoFrameTexturesHandles
302{
303public:
304 explicit OpenGLTextureHandles(GlTextureHandle tex) : m_tex(std::move(tex)) { }
305
306 quint64 textureHandle(QRhi &rhi, int /*plane*/) override
307 {
308 if (rhi.backend() != QRhi::OpenGLES2)
309 return 0;
310 return quint64(m_tex.get());
311 }
312
313private:
314 const GlTextureHandle m_tex;
315};
316
317#endif // QT_CONFIG(opengl)
318
319// At most 2 planes: NV12 and P010 are luma plus a single chroma plane.
320class MultiPlaneTextureHandles : public QVideoFrameTexturesHandles
321{
322public:
323 explicit MultiPlaneTextureHandles(QVarLengthArray<QVideoFrameTexturesHandlesUPtr, 2> planes)
324 : m_planes(std::move(planes))
325 {
326 }
327
328 quint64 textureHandle(QRhi &rhi, int plane) override
329 {
330 if (plane < 0 || plane >= m_planes.size() || !m_planes[plane])
331 return 0;
332 return m_planes[plane]->textureHandle(rhi, 0);
333 }
334
335private:
336 const QVarLengthArray<QVideoFrameTexturesHandlesUPtr, 2> m_planes;
337};
338
339} // namespace
340
343
347{
348 const auto matches = [&](const Texture &entry) {
355 };
356
358 [&](const Texture &entry) {
359 return !entry.inUse->load() && !matches(entry);
360 }),
361 m_textures.end());
362
363 for (const Texture &entry : m_textures) {
364 if (!entry.inUse->load() && matches(entry)) {
365 entry.inUse->store(true);
366 return entry;
367 }
368 }
369
370 Texture entry{ {}, std::make_shared<std::atomic_bool>(true) };
371 if (const HRESULT hr = device->CreateTexture2D(&desc, nullptr, &entry.texture); FAILED(hr)) {
373 << "CreateTexture2D failed for D3D12 import:" << QSystemError::windowsComString(hr);
374 return {};
375 }
377 return entry;
378}
379
381{
382 switch (rhi.backend()) {
383 case QRhi::D3D11: {
384 // A software (WARP) D3D11 device lives on a different adapter than the source device,
385 // so opening a shared handle across them would either fail or, worse, block on the
386 // keyed mutex until the finite timeout expires. Treat it the same as unsupported.
388 return false;
389
391 return nh && nh->dev;
392 }
393 case QRhi::D3D12:
394 return true;
395#if QT_CONFIG(opengl)
396 case QRhi::OpenGLES2: {
397 const auto *nh = static_cast<const QRhiGles2NativeHandles *>(rhi.nativeHandles());
398 if (!nh || !nh->context)
399 return false;
400 if (!supportsGlCopy(*nh->context))
401 return false; // GL_ARB_copy_image or OpenGL >= 4.3 is required to copy the D3D texture into a GL texture
402
405 return WglDxInterop::resolve(glCtx);
406 });
407 return wgl.valid();
408 }
409#endif
410 default:
411 return false;
412 }
413}
414
417{
418 switch (rhi.backend()) {
419 case QRhi::D3D12:
420 case QRhi::OpenGLES2: {
422 if (desc && desc->nplanes == 1)
423 return true;
425 }
426 default:
427 return true;
428 }
429}
430
457
462{
464
468 if (!m_planeSplitter) {
469 qCWarning(lcD3D11RhiTextureImporter) << "Cannot create plane splitter";
470 return nullptr;
471 }
472 }
473
477 if (!planes)
478 return nullptr;
479
480 if (planes->size() > 2) {
481 qCWarning(lcD3D11RhiTextureImporter) << "Splitting more than 2 planes is not supported";
482 return nullptr;
483 }
484
488 for (size_t i = 0; i < planes->size(); ++i) {
490 if (rhi.backend() == QRhi::D3D12) {
492 (*planes)[i].size, 0, *bridges[i], *outputPools[i]);
493 }
494#if QT_CONFIG(opengl)
495 else {
498 (*planes)[i].size, *glInteropSlots[i]);
499 }
500#endif
501 if (!handles)
502 return nullptr;
504 }
505
507}
508
512{
515 Q_ASSERT(nh && nh->dev);
516
520
522 if (!device) {
523 qCWarning(lcD3D11RhiTextureImporter) << "QueryInterface(ID3D11Device1) failed:"
525 return nullptr;
526 }
528
531
533 return nullptr;
534
536 if (!rhiTex)
537 return nullptr;
538
540}
541
546{
551
552 const auto *nh = static_cast<const QRhiD3D12NativeHandles *>(rhi.nativeHandles());
553 if (!nh || !nh->dev || !nh->commandQueue)
554 return nullptr;
555
556 auto *d3d12Device = static_cast<ID3D12Device *>(nh->dev);
557 auto *cmdQueue = static_cast<ID3D12CommandQueue *>(nh->commandQueue);
558
559 if (!m_d3d11on12Device) {
560 // D3D11On12 needs a queue of its own: UnwrapUnderlyingResource() makes cmdQueue wait
561 // for a fence that D3D11On12 only signals in its next submission. If that submission
562 // goes to cmdQueue as well, it is queued behind the wait and cmdQueue deadlocks.
568 FAILED(hr)) {
570 << "CreateCommandQueue:" << QSystemError::windowsComString(hr);
571 return nullptr;
572 }
573
574 IUnknown *queues[] = { on12Queue.Get() };
575 HRESULT hr = D3D11On12CreateDevice(d3d12Device, 0, nullptr, 0, queues, 1, 0,
576 &m_d3d11on12Device, nullptr, nullptr);
577 if (FAILED(hr)) {
579 << "D3D11On12CreateDevice:" << QSystemError::windowsComString(hr);
580 return nullptr;
581 }
582 }
583
587 << "QueryInterface(ID3D11Device1) failed:" << QSystemError::windowsComString(hr);
588 return nullptr;
589 }
590
593
595 return nullptr;
596
600 outputDesc.Width = static_cast<UINT>(frameSize.width());
601 outputDesc.Height = static_cast<UINT>(frameSize.height());
608
610 if (!output.texture)
611 return nullptr;
612 // Give the texture back to the pool unless handles end up owning it.
613 auto releaseOutput = qScopeGuard([&] {
614 output.inUse->store(false);
615 });
616
618 return nullptr;
619
622 qCWarning(lcD3D11RhiTextureImporter) << "QueryInterface(ID3D11On12Device2) failed:"
624 return nullptr;
625 }
626
630 FAILED(hr)) {
632 << "UnwrapUnderlyingResource:" << QSystemError::windowsComString(hr);
633 return nullptr;
634 }
635
636 // UnwrapUnderlyingResource() doesn't flush: submit the copy and the fence signal that
637 // cmdQueue now waits for.
639
643 std::move(output.inUse));
644}
645
646#if QT_CONFIG(opengl)
647
652{
657
658 const auto *nh = static_cast<const QRhiGles2NativeHandles *>(rhi.nativeHandles());
659 if (!nh || !nh->context)
660 return nullptr;
662
664 return WglDxInterop::resolve(glCtx);
665 });
666 if (!wgl.valid()) {
667 qCWarning(lcD3D11RhiTextureImporter) << "WGL_NV_DX_interop2 functions not available";
668 return nullptr;
669 }
670
671 if (!m_glInteropDevice) {
673 if (!device) {
674 qCWarning(lcD3D11RhiTextureImporter) << "wglDXOpenDeviceNV failed";
675 return nullptr;
676 }
678 device,
680 };
681
682 // Release the WGL interop device before the GL context is destroyed to avoid leaking
683 // the handle.
686
688 [this] {
690 });
691 }
692
693 // Reuse or create a non-shared texture matching the frame size for WGL interop (keyed-mutex
694 // textures are incompatible with wglDXRegisterObjectNV, and the source texture may be
695 // larger than the frame, e.g. due to a decoder's surface alignment requirements).
696 const UINT width = static_cast<UINT>(frameSize.width());
697 const UINT height = static_cast<UINT>(frameSize.height());
701 desc.Width = width;
703 desc.ArraySize = 1;
704 desc.MiscFlags = 0;
707 return nullptr;
708
709 // D3D11 may write to a registered texture while GL doesn't hold the lock.
710 const D3D11_BOX crop{ 0, 0, 0, width, height, 1 };
712 &crop);
713 srcContext->Flush();
714
717 qCWarning(lcD3D11RhiTextureImporter) << "wglDXLockObjectsNV failed";
718 return nullptr;
719 }
720
721 // GL may only access a registered object while it is locked, so copy it into a texture that
722 // GL owns while it is locked. The copy isn't affected when the slot is written to for the next
723 // frame. Locking also synchronizes the D3D11 copy above with GL.
728
729 if (!ownedGlTex)
730 return nullptr;
731
733}
734
736{
740}
741
742#endif // QT_CONFIG(opengl)
743
744} // namespace QtMultimediaPrivate
745
746QT_END_NAMESPACE