summaryrefslogtreecommitdiffstats
path: root/gfx/webrender_bindings/RenderD3D11TextureHost.cpp
blob: 232f8572cb12341b620f10e6359379c2800fa319 (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "RenderD3D11TextureHost.h"

#include "GLContextEGL.h"
#include "GLLibraryEGL.h"
#include "RenderThread.h"
#include "RenderCompositor.h"
#include "RenderCompositorD3D11SWGL.h"
#include "ScopedGLHelpers.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/layers/TextureD3D11.h"

namespace mozilla {
namespace wr {

RenderDXGITextureHost::RenderDXGITextureHost(
    WindowsHandle aHandle,
    Maybe<layers::GpuProcessTextureId>& aGpuProcessTextureId,
    uint32_t aArrayIndex, gfx::SurfaceFormat aFormat,
    gfx::ColorSpace2 aColorSpace, gfx::ColorRange aColorRange,
    gfx::IntSize aSize)
    : mHandle(aHandle),
      mGpuProcessTextureId(aGpuProcessTextureId),
      mArrayIndex(aArrayIndex),
      mSurface(0),
      mStream(0),
      mTextureHandle{0},
      mFormat(aFormat),
      mColorSpace(aColorSpace),
      mColorRange(aColorRange),
      mSize(aSize),
      mLocked(false) {
  MOZ_COUNT_CTOR_INHERITED(RenderDXGITextureHost, RenderTextureHost);
  MOZ_ASSERT((mFormat != gfx::SurfaceFormat::NV12 &&
              mFormat != gfx::SurfaceFormat::P010 &&
              mFormat != gfx::SurfaceFormat::P016) ||
             (mSize.width % 2 == 0 && mSize.height % 2 == 0));
  MOZ_ASSERT((aHandle && aGpuProcessTextureId.isNothing()) ||
             (!aHandle && aGpuProcessTextureId.isSome()));
}

RenderDXGITextureHost::~RenderDXGITextureHost() {
  MOZ_COUNT_DTOR_INHERITED(RenderDXGITextureHost, RenderTextureHost);
  DeleteTextureHandle();
}

ID3D11Texture2D* RenderDXGITextureHost::GetD3D11Texture2DWithGL() {
  if (mTexture) {
    return mTexture;
  }

  if (!mGL) {
    // SingletonGL is always used on Windows with ANGLE.
    mGL = RenderThread::Get()->SingletonGL();
  }

  if (!EnsureD3D11Texture2DWithGL()) {
    return nullptr;
  }

  return mTexture;
}

size_t RenderDXGITextureHost::GetPlaneCount() const {
  if (mFormat == gfx::SurfaceFormat::NV12 ||
      mFormat == gfx::SurfaceFormat::P010 ||
      mFormat == gfx::SurfaceFormat::P016) {
    return 2;
  }
  return 1;
}

template <typename T>
static bool MapTexture(T* aHost, RenderCompositor* aCompositor,
                       RefPtr<ID3D11Texture2D>& aTexture,
                       RefPtr<ID3D11DeviceContext>& aDeviceContext,
                       RefPtr<ID3D11Texture2D>& aCpuTexture,
                       D3D11_MAPPED_SUBRESOURCE& aMappedSubresource) {
  if (!aCompositor) {
    return false;
  }

  RenderCompositorD3D11SWGL* compositor =
      aCompositor->AsRenderCompositorD3D11SWGL();
  if (!compositor) {
    return false;
  }

  if (!aHost->EnsureD3D11Texture2D(compositor->GetDevice())) {
    return false;
  }

  if (!aHost->LockInternal()) {
    return false;
  }

  D3D11_TEXTURE2D_DESC textureDesc = {0};
  aTexture->GetDesc(&textureDesc);

  compositor->GetDevice()->GetImmediateContext(getter_AddRefs(aDeviceContext));

  textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  textureDesc.Usage = D3D11_USAGE_STAGING;
  textureDesc.BindFlags = 0;
  textureDesc.MiscFlags = 0;
  textureDesc.MipLevels = 1;
  HRESULT hr = compositor->GetDevice()->CreateTexture2D(
      &textureDesc, nullptr, getter_AddRefs(aCpuTexture));
  if (FAILED(hr)) {
    return false;
  }

  aDeviceContext->CopyResource(aCpuTexture, aTexture);
  aHost->Unlock();

  hr = aDeviceContext->Map(aCpuTexture, 0, D3D11_MAP_READ, 0,
                           &aMappedSubresource);
  return SUCCEEDED(hr);
}

bool RenderDXGITextureHost::MapPlane(RenderCompositor* aCompositor,
                                     uint8_t aChannelIndex,
                                     PlaneInfo& aPlaneInfo) {
  // TODO: We currently readback from the GPU texture into a new
  // staging texture every time this is mapped. We might be better
  // off retaining the mapped memory to trade performance for memory
  // usage.
  if (!mCpuTexture && !MapTexture(this, aCompositor, mTexture, mDeviceContext,
                                  mCpuTexture, mMappedSubresource)) {
    return false;
  }

  aPlaneInfo.mSize = GetSize(aChannelIndex);
  aPlaneInfo.mStride = mMappedSubresource.RowPitch;
  aPlaneInfo.mData = mMappedSubresource.pData;

  // If this is the second plane, then offset the data pointer by the
  // size of the first plane.
  if (aChannelIndex == 1) {
    aPlaneInfo.mData =
        (uint8_t*)aPlaneInfo.mData + aPlaneInfo.mStride * GetSize(0).height;
  }
  return true;
}

void RenderDXGITextureHost::UnmapPlanes() {
  mMappedSubresource.pData = nullptr;
  if (mCpuTexture) {
    mDeviceContext->Unmap(mCpuTexture, 0);
    mCpuTexture = nullptr;
  }
  mDeviceContext = nullptr;
}

bool RenderDXGITextureHost::EnsureD3D11Texture2DWithGL() {
  if (mTexture) {
    return true;
  }

  if (mGpuProcessTextureId.isSome()) {
    auto* textureMap = layers::GpuProcessD3D11TextureMap::Get();
    if (textureMap) {
      RefPtr<ID3D11Texture2D> texture;
      mTexture = textureMap->GetTexture(mGpuProcessTextureId.ref());
      if (mTexture) {
        return true;
      }
    }
    return false;
  }

  const auto& gle = gl::GLContextEGL::Cast(mGL);
  const auto& egl = gle->mEgl;

  // Fetch the D3D11 device.
  EGLDeviceEXT eglDevice = nullptr;
  egl->fQueryDisplayAttribEXT(LOCAL_EGL_DEVICE_EXT, (EGLAttrib*)&eglDevice);
  MOZ_ASSERT(eglDevice);
  ID3D11Device* device = nullptr;
  egl->mLib->fQueryDeviceAttribEXT(eglDevice, LOCAL_EGL_D3D11_DEVICE_ANGLE,
                                   (EGLAttrib*)&device);
  // There's a chance this might fail if we end up on d3d9 angle for some
  // reason.
  if (!device) {
    gfxCriticalNote << "RenderDXGITextureHost device is not available";
    return false;
  }

  return EnsureD3D11Texture2D(device);
}

bool RenderDXGITextureHost::EnsureD3D11Texture2D(ID3D11Device* aDevice) {
  if (mTexture) {
    RefPtr<ID3D11Device> device;
    mTexture->GetDevice(getter_AddRefs(device));
    if (aDevice != device) {
      gfxCriticalNote << "RenderDXGITextureHost uses obsoleted device";
      return false;
    }
    return true;
  }

  // Get the D3D11 texture from shared handle.
  HRESULT hr = aDevice->OpenSharedResource(
      (HANDLE)mHandle, __uuidof(ID3D11Texture2D),
      (void**)(ID3D11Texture2D**)getter_AddRefs(mTexture));
  if (FAILED(hr)) {
    MOZ_ASSERT(false,
               "RenderDXGITextureHost::EnsureLockable(): Failed to open shared "
               "texture");
    gfxCriticalNote
        << "RenderDXGITextureHost Failed to open shared texture, hr="
        << gfx::hexa(hr);
    return false;
  }
  MOZ_ASSERT(mTexture.get());
  mTexture->QueryInterface((IDXGIKeyedMutex**)getter_AddRefs(mKeyedMutex));
  return true;
}

bool RenderDXGITextureHost::EnsureLockable() {
  if (mTextureHandle[0]) {
    return true;
  }

  const auto& gle = gl::GLContextEGL::Cast(mGL);
  const auto& egl = gle->mEgl;

  // We use EGLStream to get the converted gl handle from d3d texture. The
  // NV_stream_consumer_gltexture_yuv and ANGLE_stream_producer_d3d_texture
  // could support nv12 and rgb d3d texture format.
  if (!egl->IsExtensionSupported(
          gl::EGLExtension::NV_stream_consumer_gltexture_yuv) ||
      !egl->IsExtensionSupported(
          gl::EGLExtension::ANGLE_stream_producer_d3d_texture)) {
    gfxCriticalNote << "RenderDXGITextureHost egl extensions are not suppored";
    return false;
  }

  // Get the D3D11 texture from shared handle.
  if (!EnsureD3D11Texture2DWithGL()) {
    return false;
  }

  // Create the EGLStream.
  mStream = egl->fCreateStreamKHR(nullptr);
  MOZ_ASSERT(mStream);

  bool ok = true;
  if (mFormat != gfx::SurfaceFormat::NV12 &&
      mFormat != gfx::SurfaceFormat::P010 &&
      mFormat != gfx::SurfaceFormat::P016) {
    // The non-nv12 format.

    mGL->fGenTextures(1, mTextureHandle);
    ActivateBindAndTexParameteri(mGL, LOCAL_GL_TEXTURE0,
                                 LOCAL_GL_TEXTURE_EXTERNAL_OES,
                                 mTextureHandle[0]);
    ok &=
        bool(egl->fStreamConsumerGLTextureExternalAttribsNV(mStream, nullptr));
    ok &= bool(egl->fCreateStreamProducerD3DTextureANGLE(mStream, nullptr));
  } else {
    // The nv12/p016 format.

    // Setup the NV12 stream consumer/producer.
    EGLAttrib consumerAttributes[] = {
        LOCAL_EGL_COLOR_BUFFER_TYPE,
        LOCAL_EGL_YUV_BUFFER_EXT,
        LOCAL_EGL_YUV_NUMBER_OF_PLANES_EXT,
        2,
        LOCAL_EGL_YUV_PLANE0_TEXTURE_UNIT_NV,
        0,
        LOCAL_EGL_YUV_PLANE1_TEXTURE_UNIT_NV,
        1,
        LOCAL_EGL_NONE,
    };
    mGL->fGenTextures(2, mTextureHandle);
    ActivateBindAndTexParameteri(mGL, LOCAL_GL_TEXTURE0,
                                 LOCAL_GL_TEXTURE_EXTERNAL_OES,
                                 mTextureHandle[0]);
    ActivateBindAndTexParameteri(mGL, LOCAL_GL_TEXTURE1,
                                 LOCAL_GL_TEXTURE_EXTERNAL_OES,
                                 mTextureHandle[1]);
    ok &= bool(egl->fStreamConsumerGLTextureExternalAttribsNV(
        mStream, consumerAttributes));
    ok &= bool(egl->fCreateStreamProducerD3DTextureANGLE(mStream, nullptr));
  }

  const EGLAttrib frameAttributes[] = {
      LOCAL_EGL_D3D_TEXTURE_SUBRESOURCE_ID_ANGLE,
      static_cast<EGLAttrib>(mArrayIndex),
      LOCAL_EGL_NONE,
  };

  // Insert the d3d texture.
  ok &= bool(egl->fStreamPostD3DTextureANGLE(mStream, (void*)mTexture.get(),
                                             frameAttributes));

  if (!ok) {
    gfxCriticalNote << "RenderDXGITextureHost init stream failed";
    DeleteTextureHandle();
    return false;
  }

  // Now, we could get the gl handle from the stream.
  MOZ_ALWAYS_TRUE(egl->fStreamConsumerAcquireKHR(mStream));

  return true;
}

wr::WrExternalImage RenderDXGITextureHost::Lock(uint8_t aChannelIndex,
                                                gl::GLContext* aGL) {
  if (mGL.get() != aGL) {
    // Release the texture handle in the previous gl context.
    DeleteTextureHandle();
    mGL = aGL;
  }

  if (!mGL) {
    // XXX Software WebRender is not handled yet.
    // Software WebRender does not provide GLContext
    gfxCriticalNoteOnce
        << "Software WebRender is not suppored by RenderDXGITextureHost.";
    return InvalidToWrExternalImage();
  }

  if (!EnsureLockable()) {
    return InvalidToWrExternalImage();
  }

  if (!LockInternal()) {
    return InvalidToWrExternalImage();
  }

  const auto uvs = GetUvCoords(GetSize(aChannelIndex));
  return NativeTextureToWrExternalImage(GetGLHandle(aChannelIndex), uvs.first.x,
                                        uvs.first.y, uvs.second.x,
                                        uvs.second.y);
}

bool RenderDXGITextureHost::LockInternal() {
  if (!mLocked) {
    if (mKeyedMutex) {
      HRESULT hr = mKeyedMutex->AcquireSync(0, 10000);
      if (hr != S_OK) {
        gfxCriticalError() << "RenderDXGITextureHost AcquireSync timeout, hr="
                           << gfx::hexa(hr);
        return false;
      }
    }
    mLocked = true;
  }
  return true;
}

void RenderDXGITextureHost::Unlock() {
  if (mLocked) {
    if (mKeyedMutex) {
      mKeyedMutex->ReleaseSync(0);
    }
    mLocked = false;
  }
}

void RenderDXGITextureHost::ClearCachedResources() {
  DeleteTextureHandle();
  mGL = nullptr;
}

void RenderDXGITextureHost::DeleteTextureHandle() {
  if (mTextureHandle[0] == 0) {
    return;
  }

  MOZ_ASSERT(mGL.get());
  if (!mGL) {
    return;
  }

  if (mGL->MakeCurrent()) {
    mGL->fDeleteTextures(2, mTextureHandle);

    const auto& gle = gl::GLContextEGL::Cast(mGL);
    const auto& egl = gle->mEgl;
    if (mSurface) {
      egl->fDestroySurface(mSurface);
    }
    if (mStream) {
      egl->fDestroyStreamKHR(mStream);
    }
  }

  for (int i = 0; i < 2; ++i) {
    mTextureHandle[i] = 0;
  }

  mTexture = nullptr;
  mKeyedMutex = nullptr;
  mSurface = 0;
  mStream = 0;
}

GLuint RenderDXGITextureHost::GetGLHandle(uint8_t aChannelIndex) const {
  MOZ_ASSERT(((mFormat == gfx::SurfaceFormat::NV12 ||
               mFormat == gfx::SurfaceFormat::P010 ||
               mFormat == gfx::SurfaceFormat::P016) &&
              aChannelIndex < 2) ||
             aChannelIndex < 1);
  return mTextureHandle[aChannelIndex];
}

gfx::IntSize RenderDXGITextureHost::GetSize(uint8_t aChannelIndex) const {
  MOZ_ASSERT(((mFormat == gfx::SurfaceFormat::NV12 ||
               mFormat == gfx::SurfaceFormat::P010 ||
               mFormat == gfx::SurfaceFormat::P016) &&
              aChannelIndex < 2) ||
             aChannelIndex < 1);

  if (aChannelIndex == 0) {
    return mSize;
  } else {
    // The CbCr channel size is a half of Y channel size in NV12 format.
    return mSize / 2;
  }
}

RenderDXGIYCbCrTextureHost::RenderDXGIYCbCrTextureHost(
    WindowsHandle (&aHandles)[3], gfx::YUVColorSpace aYUVColorSpace,
    gfx::ColorDepth aColorDepth, gfx::ColorRange aColorRange,
    gfx::IntSize aSizeY, gfx::IntSize aSizeCbCr)
    : mHandles{aHandles[0], aHandles[1], aHandles[2]},
      mSurfaces{0},
      mStreams{0},
      mTextureHandles{0},
      mYUVColorSpace(aYUVColorSpace),
      mColorDepth(aColorDepth),
      mColorRange(aColorRange),
      mSizeY(aSizeY),
      mSizeCbCr(aSizeCbCr),
      mLocked(false) {
  MOZ_COUNT_CTOR_INHERITED(RenderDXGIYCbCrTextureHost, RenderTextureHost);
  // Assume the chroma planes are rounded up if the luma plane is odd sized.
  MOZ_ASSERT((mSizeCbCr.width == mSizeY.width ||
              mSizeCbCr.width == (mSizeY.width + 1) >> 1) &&
             (mSizeCbCr.height == mSizeY.height ||
              mSizeCbCr.height == (mSizeY.height + 1) >> 1));
  MOZ_ASSERT(aHandles[0] && aHandles[1] && aHandles[2]);
}

bool RenderDXGIYCbCrTextureHost::MapPlane(RenderCompositor* aCompositor,
                                          uint8_t aChannelIndex,
                                          PlaneInfo& aPlaneInfo) {
  D3D11_MAPPED_SUBRESOURCE mappedSubresource;
  if (!MapTexture(this, aCompositor, mTextures[aChannelIndex], mDeviceContext,
                  mCpuTexture[aChannelIndex], mappedSubresource)) {
    return false;
  }

  aPlaneInfo.mSize = GetSize(aChannelIndex);
  aPlaneInfo.mStride = mappedSubresource.RowPitch;
  aPlaneInfo.mData = mappedSubresource.pData;
  return true;
}

void RenderDXGIYCbCrTextureHost::UnmapPlanes() {
  for (uint32_t i = 0; i < 3; i++) {
    if (mCpuTexture[i]) {
      mDeviceContext->Unmap(mCpuTexture[i], 0);
      mCpuTexture[i] = nullptr;
    }
  }
  mDeviceContext = nullptr;
}

RenderDXGIYCbCrTextureHost::~RenderDXGIYCbCrTextureHost() {
  MOZ_COUNT_DTOR_INHERITED(RenderDXGIYCbCrTextureHost, RenderTextureHost);
  DeleteTextureHandle();
}

bool RenderDXGIYCbCrTextureHost::EnsureLockable() {
  if (mTextureHandles[0]) {
    return true;
  }

  const auto& gle = gl::GLContextEGL::Cast(mGL);
  const auto& egl = gle->mEgl;

  // The eglCreatePbufferFromClientBuffer doesn't support R8 format, so we
  // use EGLStream to get the converted gl handle from d3d R8 texture.

  if (!egl->IsExtensionSupported(
          gl::EGLExtension::NV_stream_consumer_gltexture_yuv) ||
      !egl->IsExtensionSupported(
          gl::EGLExtension::ANGLE_stream_producer_d3d_texture)) {
    gfxCriticalNote
        << "RenderDXGIYCbCrTextureHost egl extensions are not suppored";
    return false;
  }

  // Fetch the D3D11 device.
  EGLDeviceEXT eglDevice = nullptr;
  egl->fQueryDisplayAttribEXT(LOCAL_EGL_DEVICE_EXT, (EGLAttrib*)&eglDevice);
  MOZ_ASSERT(eglDevice);
  ID3D11Device* device = nullptr;
  egl->mLib->fQueryDeviceAttribEXT(eglDevice, LOCAL_EGL_D3D11_DEVICE_ANGLE,
                                   (EGLAttrib*)&device);
  // There's a chance this might fail if we end up on d3d9 angle for some
  // reason.
  if (!device) {
    gfxCriticalNote << "RenderDXGIYCbCrTextureHost device is not available";
    return false;
  }

  EnsureD3D11Texture2D(device);

  mGL->fGenTextures(3, mTextureHandles);
  bool ok = true;
  for (int i = 0; i < 3; ++i) {
    ActivateBindAndTexParameteri(mGL, LOCAL_GL_TEXTURE0 + i,
                                 LOCAL_GL_TEXTURE_EXTERNAL_OES,
                                 mTextureHandles[i]);

    // Create the EGLStream.
    mStreams[i] = egl->fCreateStreamKHR(nullptr);
    MOZ_ASSERT(mStreams[i]);

    ok &= bool(
        egl->fStreamConsumerGLTextureExternalAttribsNV(mStreams[i], nullptr));
    ok &= bool(egl->fCreateStreamProducerD3DTextureANGLE(mStreams[i], nullptr));

    // Insert the R8 texture.
    ok &= bool(egl->fStreamPostD3DTextureANGLE(
        mStreams[i], (void*)mTextures[i].get(), nullptr));

    // Now, we could get the R8 gl handle from the stream.
    MOZ_ALWAYS_TRUE(egl->fStreamConsumerAcquireKHR(mStreams[i]));
  }

  if (!ok) {
    gfxCriticalNote << "RenderDXGIYCbCrTextureHost init stream failed";
    DeleteTextureHandle();
    return false;
  }

  return true;
}

bool RenderDXGIYCbCrTextureHost::EnsureD3D11Texture2D(ID3D11Device* aDevice) {
  if (mTextures[0]) {
    RefPtr<ID3D11Device> device;
    mTextures[0]->GetDevice(getter_AddRefs(device));
    if (aDevice != device) {
      gfxCriticalNote << "RenderDXGIYCbCrTextureHost uses obsoleted device";
      return false;
    }
  }

  if (mTextureHandles[0]) {
    return true;
  }

  for (int i = 0; i < 3; ++i) {
    // Get the R8 D3D11 texture from shared handle.
    HRESULT hr = aDevice->OpenSharedResource(
        (HANDLE)mHandles[i], __uuidof(ID3D11Texture2D),
        (void**)(ID3D11Texture2D**)getter_AddRefs(mTextures[i]));
    if (FAILED(hr)) {
      NS_WARNING(
          "RenderDXGIYCbCrTextureHost::EnsureLockable(): Failed to open "
          "shared "
          "texture");
      gfxCriticalNote
          << "RenderDXGIYCbCrTextureHost Failed to open shared texture, hr="
          << gfx::hexa(hr);
      return false;
    }
  }

  for (int i = 0; i < 3; ++i) {
    mTextures[i]->QueryInterface(
        (IDXGIKeyedMutex**)getter_AddRefs(mKeyedMutexs[i]));
  }
  return true;
}

bool RenderDXGIYCbCrTextureHost::LockInternal() {
  if (!mLocked) {
    if (mKeyedMutexs[0]) {
      for (const auto& mutex : mKeyedMutexs) {
        HRESULT hr = mutex->AcquireSync(0, 10000);
        if (hr != S_OK) {
          gfxCriticalError()
              << "RenderDXGIYCbCrTextureHost AcquireSync timeout, hr="
              << gfx::hexa(hr);
          return false;
        }
      }
    }
    mLocked = true;
  }
  return true;
}

wr::WrExternalImage RenderDXGIYCbCrTextureHost::Lock(uint8_t aChannelIndex,
                                                     gl::GLContext* aGL) {
  if (mGL.get() != aGL) {
    // Release the texture handle in the previous gl context.
    DeleteTextureHandle();
    mGL = aGL;
  }

  if (!mGL) {
    // XXX Software WebRender is not handled yet.
    // Software WebRender does not provide GLContext
    gfxCriticalNoteOnce << "Software WebRender is not suppored by "
                           "RenderDXGIYCbCrTextureHost.";
    return InvalidToWrExternalImage();
  }

  if (!EnsureLockable()) {
    return InvalidToWrExternalImage();
  }

  if (!LockInternal()) {
    return InvalidToWrExternalImage();
  }

  const auto uvs = GetUvCoords(GetSize(aChannelIndex));
  return NativeTextureToWrExternalImage(GetGLHandle(aChannelIndex), uvs.first.x,
                                        uvs.first.y, uvs.second.x,
                                        uvs.second.y);
}

void RenderDXGIYCbCrTextureHost::Unlock() {
  if (mLocked) {
    if (mKeyedMutexs[0]) {
      for (const auto& mutex : mKeyedMutexs) {
        mutex->ReleaseSync(0);
      }
    }
    mLocked = false;
  }
}

void RenderDXGIYCbCrTextureHost::ClearCachedResources() {
  DeleteTextureHandle();
  mGL = nullptr;
}

GLuint RenderDXGIYCbCrTextureHost::GetGLHandle(uint8_t aChannelIndex) const {
  MOZ_ASSERT(aChannelIndex < 3);

  return mTextureHandles[aChannelIndex];
}

gfx::IntSize RenderDXGIYCbCrTextureHost::GetSize(uint8_t aChannelIndex) const {
  MOZ_ASSERT(aChannelIndex < 3);

  if (aChannelIndex == 0) {
    return mSizeY;
  } else {
    return mSizeCbCr;
  }
}

void RenderDXGIYCbCrTextureHost::DeleteTextureHandle() {
  if (mTextureHandles[0] == 0) {
    return;
  }

  MOZ_ASSERT(mGL.get());
  if (!mGL) {
    return;
  }

  if (mGL->MakeCurrent()) {
    mGL->fDeleteTextures(3, mTextureHandles);

    const auto& gle = gl::GLContextEGL::Cast(mGL);
    const auto& egl = gle->mEgl;
    for (int i = 0; i < 3; ++i) {
      mTextureHandles[i] = 0;
      mTextures[i] = nullptr;
      mKeyedMutexs[i] = nullptr;

      if (mSurfaces[i]) {
        egl->fDestroySurface(mSurfaces[i]);
        mSurfaces[i] = 0;
      }
      if (mStreams[i]) {
        egl->fDestroyStreamKHR(mStreams[i]);
        mStreams[i] = 0;
      }
    }
  }
}

}  // namespace wr
}  // namespace mozilla