summaryrefslogtreecommitdiffstats
path: root/gfx/gl/SharedSurfaceD3D11Interop.cpp
blob: e667005d83eb652c920134f3612211d9c2a6c404 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* -*- Mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40; -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "SharedSurfaceD3D11Interop.h"

#include <d3d11.h>
#include "gfxPrefs.h"
#include "GLContext.h"
#include "WGLLibrary.h"
#include "nsPrintfCString.h"
#include "mozilla/gfx/DeviceManagerDx.h"

namespace mozilla {
namespace gl {

/*
Sample Code for WGL_NV_DX_interop2:
Example: Render to Direct3D 11 backbuffer with openGL:

// create D3D11 device, context and swap chain.
ID3D11Device *device;
ID3D11DeviceContext *devCtx;
IDXGISwapChain *swapChain;

DXGI_SWAP_CHAIN_DESC scd;

<set appropriate swap chain parameters in scd>

hr = D3D11CreateDeviceAndSwapChain(NULL,                        // pAdapter
                                   D3D_DRIVER_TYPE_HARDWARE,    // DriverType
                                   NULL,                        // Software
                                   0,                           // Flags (Do not set D3D11_CREATE_DEVICE_SINGLETHREADED)
                                   NULL,                        // pFeatureLevels
                                   0,                           // FeatureLevels
                                   D3D11_SDK_VERSION,           // SDKVersion
                                   &scd,                        // pSwapChainDesc
                                   &swapChain,                  // ppSwapChain
                                   &device,                     // ppDevice
                                   NULL,                        // pFeatureLevel
                                   &devCtx);                    // ppImmediateContext

// Fetch the swapchain backbuffer
ID3D11Texture2D *dxColorbuffer;
swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&dxColorbuffer);

// Create depth stencil texture
ID3D11Texture2D *dxDepthBuffer;
D3D11_TEXTURE2D_DESC depthDesc;
depthDesc.Usage = D3D11_USAGE_DEFAULT;
<set other depthDesc parameters appropriately>

// Create Views
ID3D11RenderTargetView *colorBufferView;
D3D11_RENDER_TARGET_VIEW_DESC rtd;
<set rtd parameters appropriately>
device->CreateRenderTargetView(dxColorbuffer, &rtd, &colorBufferView);

ID3D11DepthStencilView *depthBufferView;
D3D11_DEPTH_STENCIL_VIEW_DESC dsd;
<set dsd parameters appropriately>
device->CreateDepthStencilView(dxDepthBuffer, &dsd, &depthBufferView);

// Attach back buffer and depth texture to redertarget for the device.
devCtx->OMSetRenderTargets(1, &colorBufferView, depthBufferView);

// Register D3D11 device with GL
HANDLE gl_handleD3D;
gl_handleD3D = wglDXOpenDeviceNV(device);

// register the Direct3D color and depth/stencil buffers as
// renderbuffers in opengl
GLuint gl_names[2];
HANDLE gl_handles[2];

glGenRenderbuffers(2, gl_names);

gl_handles[0] = wglDXRegisterObjectNV(gl_handleD3D, dxColorBuffer,
                                      gl_names[0],
                                      GL_RENDERBUFFER,
                                      WGL_ACCESS_READ_WRITE_NV);

gl_handles[1] = wglDXRegisterObjectNV(gl_handleD3D, dxDepthBuffer,
                                      gl_names[1],
                                      GL_RENDERBUFFER,
                                      WGL_ACCESS_READ_WRITE_NV);

// attach the Direct3D buffers to an FBO
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                          GL_RENDERBUFFER, gl_names[0]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                          GL_RENDERBUFFER, gl_names[1]);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT,
                          GL_RENDERBUFFER, gl_names[1]);

while (!done) {
      <direct3d renders to the render targets>

      // lock the render targets for GL access
      wglDXLockObjectsNVX(gl_handleD3D, 2, gl_handles);

      <opengl renders to the render targets>

      // unlock the render targets
      wglDXUnlockObjectsNVX(gl_handleD3D, 2, gl_handles);

      <direct3d renders to the render targets and presents
       the results on the screen>
}
*/

////////////////////////////////////////////////////////////////////////////////
// DXInterop2Device

class DXInterop2Device : public RefCounted<DXInterop2Device>
{
public:
    MOZ_DECLARE_REFCOUNTED_TYPENAME(DXInterop2Device)

    WGLLibrary* const mWGL;
    const RefPtr<ID3D11Device> mD3D; // Only needed for lifetime guarantee.
    const HANDLE mInteropDevice;
    GLContext* const mGL;

    static already_AddRefed<DXInterop2Device> Open(WGLLibrary* wgl, GLContext* gl)
    {
        MOZ_ASSERT(wgl->HasDXInterop2());

        const RefPtr<ID3D11Device> d3d = gfx::DeviceManagerDx::Get()->GetContentDevice();
        if (!d3d) {
            gfxCriticalNote << "DXInterop2Device::Open: Failed to create D3D11 device.";
            return nullptr;
        }

        if (!gl->MakeCurrent())
            return nullptr;

        const auto interopDevice = wgl->fDXOpenDevice(d3d);
        if (!interopDevice) {
            gfxCriticalNote << "DXInterop2Device::Open: DXOpenDevice failed.";
            return nullptr;
        }

        return MakeAndAddRef<DXInterop2Device>(wgl, d3d, interopDevice, gl);
    }

    DXInterop2Device(WGLLibrary* wgl, ID3D11Device* d3d, HANDLE interopDevice,
                     GLContext* gl)
        : mWGL(wgl)
        , mD3D(d3d)
        , mInteropDevice(interopDevice)
        , mGL(gl)
    { }

    ~DXInterop2Device() {
        const auto isCurrent = mGL->MakeCurrent();

        if (mWGL->fDXCloseDevice(mInteropDevice))
            return;

        if (isCurrent) {
            // That shouldn't have failed.
            const uint32_t error = GetLastError();
            const nsPrintfCString errorMessage("wglDXCloseDevice(0x%p) failed:"
                                               " GetLastError(): %u\n",
                                               mInteropDevice, error);
            gfxCriticalError() << errorMessage.BeginReading();
        }
    }

    HANDLE RegisterObject(void* d3dObject, GLuint name, GLenum type,
                          GLenum access) const
    {
        if (!mGL->MakeCurrent())
            return nullptr;

        const auto ret = mWGL->fDXRegisterObject(mInteropDevice, d3dObject, name, type,
                                                 access);
        if (ret)
            return ret;

        const uint32_t error = GetLastError();
        const nsPrintfCString errorMessage("wglDXRegisterObject(0x%p, 0x%p, %u, 0x%04x,"
                                           " 0x%04x) failed: GetLastError(): %u\n",
                                           mInteropDevice, d3dObject, name, type, access,
                                           error);
        gfxCriticalNote << errorMessage.BeginReading();
        return nullptr;
    }

    bool UnregisterObject(HANDLE lockHandle) const {
        const auto isCurrent = mGL->MakeCurrent();

        if (mWGL->fDXUnregisterObject(mInteropDevice, lockHandle))
            return true;

        if (!isCurrent) {
            // That shouldn't have failed.
            const uint32_t error = GetLastError();
            const nsPrintfCString errorMessage("wglDXUnregisterObject(0x%p, 0x%p) failed:"
                                               " GetLastError(): %u\n",
                                               mInteropDevice, lockHandle, error);
            gfxCriticalError() << errorMessage.BeginReading();
        }
        return false;
    }

    bool LockObject(HANDLE lockHandle) const {
        MOZ_ASSERT(mGL->IsCurrent());

        if (mWGL->fDXLockObjects(mInteropDevice, 1, &lockHandle))
            return true;

        if (!mGL->MakeCurrent())
            return false;

        gfxCriticalNote << "wglDXLockObjects called without mGL being current."
                        << " Retrying after MakeCurrent.";

        if (mWGL->fDXLockObjects(mInteropDevice, 1, &lockHandle))
            return true;

        const uint32_t error = GetLastError();
        const nsPrintfCString errorMessage("wglDXLockObjects(0x%p, 1, {0x%p}) failed:"
                                           " GetLastError(): %u\n",
                                           mInteropDevice, lockHandle, error);
        gfxCriticalError() << errorMessage.BeginReading();
        return false;
    }

    bool UnlockObject(HANDLE lockHandle) const {
        MOZ_ASSERT(mGL->IsCurrent());

        if (mWGL->fDXUnlockObjects(mInteropDevice, 1, &lockHandle))
            return true;

        if (!mGL->MakeCurrent())
            return false;

        gfxCriticalNote << "wglDXUnlockObjects called without mGL being current."
                        << " Retrying after MakeCurrent.";

        if (mWGL->fDXUnlockObjects(mInteropDevice, 1, &lockHandle))
            return true;

        const uint32_t error = GetLastError();
        const nsPrintfCString errorMessage("wglDXUnlockObjects(0x%p, 1, {0x%p}) failed:"
                                           " GetLastError(): %u\n",
                                           mInteropDevice, lockHandle, error);
        gfxCriticalError() << errorMessage.BeginReading();
        return false;
    }
};

////////////////////////////////////////////////////////////////////////////////
// Shared Surface

/*static*/ UniquePtr<SharedSurface_D3D11Interop>
SharedSurface_D3D11Interop::Create(DXInterop2Device* interop,
                                   GLContext* gl,
                                   const gfx::IntSize& size,
                                   bool hasAlpha)
{
    const auto& d3d = interop->mD3D;

    // Create a texture in case we need to readback.
    DXGI_FORMAT format = hasAlpha ? DXGI_FORMAT_B8G8R8A8_UNORM
                                  : DXGI_FORMAT_B8G8R8X8_UNORM;
    CD3D11_TEXTURE2D_DESC desc(format, size.width, size.height, 1, 1);
    desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;

    RefPtr<ID3D11Texture2D> texD3D;
    auto hr = d3d->CreateTexture2D(&desc, nullptr, getter_AddRefs(texD3D));
    if (FAILED(hr)) {
        NS_WARNING("Failed to create texture for CanvasLayer!");
        return nullptr;
    }

    RefPtr<IDXGIResource> texDXGI;
    hr = texD3D->QueryInterface(__uuidof(IDXGIResource), getter_AddRefs(texDXGI));
    if (FAILED(hr)) {
        NS_WARNING("Failed to open texture for sharing!");
        return nullptr;
    }

    HANDLE dxgiHandle;
    texDXGI->GetSharedHandle(&dxgiHandle);

    ////

    if (!gl->MakeCurrent()) {
        NS_WARNING("MakeCurrent failed.");
        return nullptr;
    }

    GLuint rbGL = 0;
    gl->fGenRenderbuffers(1, &rbGL);
    const auto lockHandle = interop->RegisterObject(texD3D, rbGL, LOCAL_GL_RENDERBUFFER,
                                                    LOCAL_WGL_ACCESS_WRITE_DISCARD_NV);
    if (!lockHandle) {
        NS_WARNING("Failed to register D3D object with WGL.");
        gl->fDeleteRenderbuffers(1, &rbGL);
        return nullptr;
    }

    ////

    typedef SharedSurface_D3D11Interop ptrT;
    UniquePtr<ptrT> ret ( new ptrT(gl, size, hasAlpha, rbGL, interop, lockHandle,
                                   texD3D, dxgiHandle) );
    return Move(ret);
}

SharedSurface_D3D11Interop::SharedSurface_D3D11Interop(GLContext* gl,
                                                       const gfx::IntSize& size,
                                                       bool hasAlpha, GLuint rbGL,
                                                       DXInterop2Device* interop,
                                                       HANDLE lockHandle,
                                                       ID3D11Texture2D* texD3D,
                                                       HANDLE dxgiHandle)
    : SharedSurface(SharedSurfaceType::DXGLInterop2,
                    AttachmentType::GLRenderbuffer,
                    gl,
                    size,
                    hasAlpha,
                    true)
    , mProdRB(rbGL)
    , mInterop(interop)
    , mLockHandle(lockHandle)
    , mTexD3D(texD3D)
    , mDXGIHandle(dxgiHandle)
    , mNeedsFinish(gfxPrefs::WebGLDXGLNeedsFinish())
    , mLockedForGL(false)
{ }

SharedSurface_D3D11Interop::~SharedSurface_D3D11Interop()
{
    MOZ_ASSERT(!IsProducerAcquired());

    if (!mGL || !mGL->MakeCurrent())
        return;

    if (!mInterop->UnregisterObject(mLockHandle)) {
        NS_WARNING("Failed to release mLockHandle, possibly leaking it.");
    }

    mGL->fDeleteRenderbuffers(1, &mProdRB);
}

void
SharedSurface_D3D11Interop::ProducerAcquireImpl()
{
    MOZ_ASSERT(!mLockedForGL);

    // Now we have the mutex, we can lock for GL.
    MOZ_ALWAYS_TRUE( mInterop->LockObject(mLockHandle) );

    mLockedForGL = true;
}

void
SharedSurface_D3D11Interop::ProducerReleaseImpl()
{
    MOZ_ASSERT(mLockedForGL);

    if (mNeedsFinish) {
        mGL->fFinish();
    } else {
        // We probably don't even need this.
        mGL->fFlush();
    }
    MOZ_ALWAYS_TRUE( mInterop->UnlockObject(mLockHandle) );

    mLockedForGL = false;
}

bool
SharedSurface_D3D11Interop::ToSurfaceDescriptor(layers::SurfaceDescriptor* const out_descriptor)
{
    const auto format = (mHasAlpha ? gfx::SurfaceFormat::B8G8R8A8
                                   : gfx::SurfaceFormat::B8G8R8X8);
    *out_descriptor = layers::SurfaceDescriptorD3D10(WindowsHandle(mDXGIHandle), format,
                                                     mSize);
    return true;
}

//////////////////////////////////////////////////////////////////////////////////////////
// Factory

/*static*/ UniquePtr<SurfaceFactory_D3D11Interop>
SurfaceFactory_D3D11Interop::Create(GLContext* gl, const SurfaceCaps& caps,
                                    layers::LayersIPCChannel* allocator,
                                    const layers::TextureFlags& flags)
{
    WGLLibrary* wgl = &sWGLLib;
    if (!wgl || !wgl->HasDXInterop2())
        return nullptr;

    const RefPtr<DXInterop2Device> interop = DXInterop2Device::Open(wgl, gl);
    if (!interop) {
        NS_WARNING("Failed to open D3D device for use by WGL.");
        return nullptr;
    }

    typedef SurfaceFactory_D3D11Interop ptrT;
    UniquePtr<ptrT> ret(new ptrT(gl, caps, allocator, flags, interop));
    return Move(ret);
}

SurfaceFactory_D3D11Interop::SurfaceFactory_D3D11Interop(GLContext* gl,
                                                         const SurfaceCaps& caps,
                                                         layers::LayersIPCChannel* allocator,
                                                         const layers::TextureFlags& flags,
                                                         DXInterop2Device* interop)
    : SurfaceFactory(SharedSurfaceType::DXGLInterop2, gl, caps, allocator, flags)
    , mInterop(interop)
{ }

SurfaceFactory_D3D11Interop::~SurfaceFactory_D3D11Interop()
{ }

} // namespace gl
} // namespace mozilla