DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 4; -*- */
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 4; -*- */
/* 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 "GLScreenBuffer.h"
#include "GLScreenBuffer.h"

#include <cstring>
#include "CompositorTypes.h"
#include "mozilla/StaticPrefs_webgl.h"
#include "GLContext.h"
#include "GLContext.h"
#include "GLBlitHelper.h"
#include "GLReadTexImageHelper.h"
#include "SharedSurfaceEGL.h"
#include "SharedSurfaceGL.h"
#include "ScopedGLHelpers.h"
#include "ScopedGLHelpers.h"
#include "gfx2DGlue.h"
#include "../layers/ipc/ShadowLayers.h"
#include "mozilla/layers/TextureForwarder.h"
#include "mozilla/layers/TextureClientSharedSurface.h"


#ifdef XP_WIN
#  include "SharedSurfaceANGLE.h"         // for SurfaceFactory_ANGLEShareHandle
#  include "SharedSurfaceD3D11Interop.h"  // for SurfaceFactory_D3D11Interop
#  include "mozilla/gfx/DeviceManagerDx.h"
#endif
#endif

#ifdef XP_MACOSX
#  include "SharedSurfaceIO.h"
#endif

#ifdef MOZ_X11
#ifdef MOZ_X11
#  include "GLXLibrary.h"
#  include "SharedSurfaceGLX.h"
#endif

#ifdef MOZ_WAYLAND
#ifdef MOZ_WAYLAND
#  include "gfxPlatformGtk.h"
#  include "SharedSurfaceDMABUF.h"
#endif

namespace mozilla::gl {
namespace mozilla::gl {

UniquePtr<GLScreenBuffer> GLScreenBuffer::Create(GLContext* gl,
                                                 const gfx::IntSize& size,
                                                 const SurfaceCaps& caps) {
  UniquePtr<GLScreenBuffer> ret;
  UniquePtr<GLScreenBuffer> ret;

  layers::TextureFlags flags = layers::TextureFlags::ORIGIN_BOTTOM_LEFT;
  if (!caps.premultAlpha) {
    flags |= layers::TextureFlags::NON_PREMULTIPLIED;
  }
  }

  UniquePtr<SurfaceFactory> factory =
      MakeUnique<SurfaceFactory_Basic>(gl, caps, flags);

  ret.reset(new GLScreenBuffer(gl, caps, std::move(factory)));
  return ret;
}
}

/* static */
UniquePtr<SurfaceFactory> GLScreenBuffer::CreateFactory(
    GLContext* gl, const SurfaceCaps& caps,
    layers::KnowsCompositor* compositorConnection,
    layers::KnowsCompositor* compositorConnection,
    const layers::TextureFlags& flags) {
  const auto& ipcChannel = compositorConnection->GetTextureForwarder();
  const auto& backend = compositorConnection->GetCompositorBackendType();
  bool useANGLE = compositorConnection->GetCompositorUseANGLE();
  return CreateFactory(gl, caps, ipcChannel, backend, useANGLE, flags);
}
}

/* static */
UniquePtr<SurfaceFactory> GLScreenBuffer::CreateFactory(
    GLContext* gl, const SurfaceCaps& caps,
    GLContext* gl, const SurfaceCaps& caps,
    layers::LayersIPCChannel* ipcChannel, layers::LayersBackend backend,
    bool useANGLE, const layers::TextureFlags& flags) {
  const bool useGl =
      !StaticPrefs::webgl_force_layers_readback() &&
      (backend == layers::LayersBackend::LAYERS_OPENGL ||
      (backend == layers::LayersBackend::LAYERS_OPENGL ||
       (backend == layers::LayersBackend::LAYERS_WR && !useANGLE));
  const bool useD3D =
      !StaticPrefs::webgl_force_layers_readback() &&
      (backend == layers::LayersBackend::LAYERS_D3D11 ||
       (backend == layers::LayersBackend::LAYERS_WR && useANGLE));
       (backend == layers::LayersBackend::LAYERS_WR && useANGLE));

  UniquePtr<SurfaceFactory> factory = nullptr;
  if (useGl) {
#if defined(XP_MACOSX)
    factory = SurfaceFactory_IOSurface::Create(gl, caps, ipcChannel, flags);
    factory = SurfaceFactory_IOSurface::Create(gl, caps, ipcChannel, flags);
#elif defined(MOZ_WAYLAND)
    if (gl->GetContextType() == GLContextType::EGL) {
      if (gfxPlatformGtk::GetPlatform()->UseWaylandDMABufWebGL()) {
        factory =
            MakeUnique<SurfaceFactory_DMABUF>(gl, caps, ipcChannel, flags);
            MakeUnique<SurfaceFactory_DMABUF>(gl, caps, ipcChannel, flags);
      }
    }
#elif defined(MOZ_X11)
    if (sGLXLibrary.UseTextureFromPixmap())
      factory = SurfaceFactory_GLXDrawable::Create(gl, caps, ipcChannel, flags);
      factory = SurfaceFactory_GLXDrawable::Create(gl, caps, ipcChannel, flags);
#elif defined(MOZ_WIDGET_UIKIT)
    factory = MakeUnique<SurfaceFactory_GLTexture>(mGLContext, caps, ipcChannel,
                                                   mFlags);
#elif defined(MOZ_WIDGET_ANDROID)
    if (XRE_IsParentProcess() && !StaticPrefs::webgl_enable_surface_texture()) {
    if (XRE_IsParentProcess() && !StaticPrefs::webgl_enable_surface_texture()) {
      factory = SurfaceFactory_EGLImage::Create(gl, caps, ipcChannel, flags);
    } else {
      factory =
          SurfaceFactory_SurfaceTexture::Create(gl, caps, ipcChannel, flags);
          SurfaceFactory_SurfaceTexture::Create(gl, caps, ipcChannel, flags);
    }
#else
    if (gl->GetContextType() == GLContextType::EGL) {
      if (XRE_IsParentProcess()) {
        factory = SurfaceFactory_EGLImage::Create(gl, caps, ipcChannel, flags);
        factory = SurfaceFactory_EGLImage::Create(gl, caps, ipcChannel, flags);
      }
    }
#endif
  } else if (useD3D) {
#ifdef XP_WIN
#ifdef XP_WIN
    // Ensure devices initialization. SharedSurfaceANGLE and
    // SharedSurfaceD3D11Interop use them. The devices are lazily initialized
    // with WebRender to reduce memory usage.
    if (XRE_IsContentProcess()) {
      gfxPlatform::GetPlatform()->EnsureDevicesInitialized();
      gfxPlatform::GetPlatform()->EnsureDevicesInitialized();
    }

    // Enable surface sharing only if ANGLE and compositing devices
    // are both WARP or both not WARP
    // are both WARP or both not WARP
    gfx::DeviceManagerDx* dm = gfx::DeviceManagerDx::Get();
    MOZ_ASSERT(dm);
    if (gl->IsANGLE() && (gl->IsWARP() == dm->IsWARP()) &&
        dm->TextureSharingWorks()) {
      factory =
      factory =
          SurfaceFactory_ANGLEShareHandle::Create(gl, caps, ipcChannel, flags);
    }

    if (!factory && StaticPrefs::webgl_dxgl_enabled()) {
      factory =
      factory =
          SurfaceFactory_D3D11Interop::Create(gl, caps, ipcChannel, flags);
    }
#endif
  }


#ifdef MOZ_X11
  if (!factory && sGLXLibrary.UseTextureFromPixmap()) {
    factory = SurfaceFactory_GLXDrawable::Create(gl, caps, ipcChannel, flags);
  }
#endif

  return factory;
  return factory;
}

GLScreenBuffer::GLScreenBuffer(GLContext* gl, const SurfaceCaps& caps,
                               UniquePtr<SurfaceFactory> factory)
    : mGL(gl),
      mCaps(caps),
      mFactory(std::move(factory)),
      mFactory(std::move(factory)),
      mUserDrawFB(0),
      mUserReadFB(0),
      mInternalDrawFB(0),
      mInternalReadFB(0)
#ifdef DEBUG
#ifdef DEBUG
      ,
      mInInternalMode_DrawFB(true),
      mInInternalMode_ReadFB(true)
#endif
{
{
}

GLScreenBuffer::~GLScreenBuffer() {
  mFactory = nullptr;
  mRead = nullptr;
  mRead = nullptr;

  if (!mBack) return;

  // Detach mBack cleanly.
  mBack->Surf()->ProducerRelease();
  mBack->Surf()->ProducerRelease();
}

void GLScreenBuffer::BindFB(GLuint fb) {
  GLuint drawFB = DrawFB();
  GLuint readFB = ReadFB();
  GLuint readFB = ReadFB();

  mUserDrawFB = fb;
  mUserReadFB = fb;
  mInternalDrawFB = (fb == 0) ? drawFB : fb;
  mInternalDrawFB = (fb == 0) ? drawFB : fb;
  mInternalReadFB = (fb == 0) ? readFB : fb;

  if (mInternalDrawFB == mInternalReadFB) {
    mGL->raw_fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mInternalDrawFB);
  } else {
  } else {
    MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));
    MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));
    mGL->raw_fBindFramebuffer(LOCAL_GL_DRAW_FRAMEBUFFER_EXT, mInternalDrawFB);
    mGL->raw_fBindFramebuffer(LOCAL_GL_READ_FRAMEBUFFER_EXT, mInternalReadFB);
  }

#ifdef DEBUG
#ifdef DEBUG
  mInInternalMode_DrawFB = false;
  mInInternalMode_ReadFB = false;
#endif
}


void GLScreenBuffer::BindDrawFB(GLuint fb) {
  MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));

  GLuint drawFB = DrawFB();
  mUserDrawFB = fb;
  mUserDrawFB = fb;
  mInternalDrawFB = (fb == 0) ? drawFB : fb;

  mGL->raw_fBindFramebuffer(LOCAL_GL_DRAW_FRAMEBUFFER_EXT, mInternalDrawFB);

#ifdef DEBUG
#ifdef DEBUG
  mInInternalMode_DrawFB = false;
#endif
}

void GLScreenBuffer::BindReadFB(GLuint fb) {
void GLScreenBuffer::BindReadFB(GLuint fb) {
  MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));

  GLuint readFB = ReadFB();
  mUserReadFB = fb;
  mInternalReadFB = (fb == 0) ? readFB : fb;
  mInternalReadFB = (fb == 0) ? readFB : fb;

  mGL->raw_fBindFramebuffer(LOCAL_GL_READ_FRAMEBUFFER_EXT, mInternalReadFB);

#ifdef DEBUG
  mInInternalMode_ReadFB = false;
  mInInternalMode_ReadFB = false;
#endif
}

void GLScreenBuffer::BindReadFB_Internal(GLuint fb) {
  MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));
  MOZ_ASSERT(mGL->IsSupported(GLFeature::split_framebuffer));

  mInternalReadFB = mUserReadFB = fb;
  mGL->raw_fBindFramebuffer(LOCAL_GL_READ_FRAMEBUFFER_EXT, mInternalReadFB);

#ifdef DEBUG
  mInInternalMode_ReadFB = true;
#endif
#endif
}

GLuint GLScreenBuffer::GetDrawFB() const {
#ifdef DEBUG
  MOZ_ASSERT(!mInInternalMode_DrawFB);
  MOZ_ASSERT(!mInInternalMode_DrawFB);

  // Don't need a branch here, because:
  // LOCAL_GL_DRAW_FRAMEBUFFER_BINDING_EXT == LOCAL_GL_FRAMEBUFFER_BINDING ==
  // 0x8CA6 We use raw_ here because this is debug code and we need to see what
  // the driver thinks.
  // the driver thinks.
  GLuint actual = 0;
  mGL->raw_fGetIntegerv(LOCAL_GL_DRAW_FRAMEBUFFER_BINDING_EXT, (GLint*)&actual);


  GLuint predicted = mInternalDrawFB;
  GLuint predicted = mInternalDrawFB;
  if (predicted != actual && !mGL->CheckContextLost()) {
    printf_stderr("Misprediction: Bound draw FB predicted: %d. Was: %d.\n",
                  predicted, actual);
                  predicted, actual);
    MOZ_ASSERT(false, "Draw FB binding misprediction!");
  }
#endif

  return mUserDrawFB;
  return mUserDrawFB;
}

GLuint GLScreenBuffer::GetReadFB() const {
#ifdef DEBUG
  MOZ_ASSERT(!mInInternalMode_ReadFB);
  MOZ_ASSERT(!mInInternalMode_ReadFB);

  // We use raw_ here because this is debug code and we need to see what
  // the driver thinks.
  GLuint actual = 0;
  if (mGL->IsSupported(GLFeature::split_framebuffer))
  if (mGL->IsSupported(GLFeature::split_framebuffer))
    mGL->raw_fGetIntegerv(LOCAL_GL_READ_FRAMEBUFFER_BINDING_EXT,
                          (GLint*)&actual);
  else
    mGL->raw_fGetIntegerv(LOCAL_GL_FRAMEBUFFER_BINDING, (GLint*)&actual);

  GLuint predicted = mInternalReadFB;
  if (predicted != actual && !mGL->CheckContextLost()) {
    printf_stderr("Misprediction: Bound read FB predicted: %d. Was: %d.\n",
                  predicted, actual);
    MOZ_ASSERT(false, "Read FB binding misprediction!");
  }
  }
#endif

  return mUserReadFB;
}


GLuint GLScreenBuffer::GetFB() const {
  MOZ_ASSERT(GetDrawFB() == GetReadFB());
  return GetDrawFB();
}


void GLScreenBuffer::DeletingFB(GLuint fb) {
  if (fb == mInternalDrawFB) {
    mInternalDrawFB = 0;
    mUserDrawFB = 0;
  }
  }
  if (fb == mInternalReadFB) {
    mInternalReadFB = 0;
    mUserReadFB = 0;
  }
}
}

bool GLScreenBuffer::CopyTexImage2D(GLenum target, GLint level,
                                    GLenum internalformat, GLint x, GLint y,
                                    GLsizei width, GLsizei height,
                                    GLsizei width, GLsizei height,
                                    GLint border) {
  SharedSurface* surf;
  if (GetReadFB() == 0) {
    surf = SharedSurf();
  } else {
  } else {
    surf = mGL->mFBOMapping[GetReadFB()];
  }
  if (surf) {
    return surf->CopyTexImage2D(target, level, internalformat, x, y, width,
                                height, border);
                                height, border);
  }


  return false;
}

bool GLScreenBuffer::ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                                GLenum format, GLenum type, GLvoid* pixels) {
                                GLenum format, GLenum type, GLvoid* pixels) {
  // If the currently bound framebuffer is backed by a SharedSurface
  // then it might want to override how we read pixel data from it.
  // This is normally only the default framebuffer, but we can also
  // have SharedSurfaces bound to other framebuffers when doing
  // readback for BasicLayers.
  // readback for BasicLayers.
  SharedSurface* surf;
  if (GetReadFB() == 0) {
    surf = SharedSurf();
  } else {
    surf = mGL->mFBOMapping[GetReadFB()];
    surf = mGL->mFBOMapping[GetReadFB()];
  }
  if (surf) {
    return surf->ReadPixels(x, y, width, height, format, type, pixels);
  }


  return false;
}

void GLScreenBuffer::Morph(UniquePtr<SurfaceFactory> newFactory) {
  MOZ_RELEASE_ASSERT(newFactory, "newFactory must not be null");
  mFactory = std::move(newFactory);
}
}

bool GLScreenBuffer::Attach(SharedSurface* surf, const gfx::IntSize& size) {
  ScopedBindFramebuffer autoFB(mGL);

  const bool readNeedsUnlock = (mRead && SharedSurf());
  const bool readNeedsUnlock = (mRead && SharedSurf());
  if (readNeedsUnlock) {
    SharedSurf()->UnlockProd();
  }

  surf->LockProd();
  surf->LockProd();

  if (mRead && surf->mAttachType == SharedSurf()->mAttachType &&
      size == Size()) {
    // Same size, same type, ready for reuse!
    // Same size, same type, ready for reuse!
    mRead->Attach(surf);
  } else {
    UniquePtr<ReadBuffer> read = CreateRead(surf);
    if (!read) {
      surf->UnlockProd();
      surf->UnlockProd();
      if (readNeedsUnlock) {
        SharedSurf()->LockProd();
      }
      return false;
      return false;
    }

    mRead = std::move(read);
  }


  // Check that we're all set up.
  MOZ_ASSERT(SharedSurf() == surf);

  return true;
}
}

bool GLScreenBuffer::Swap(const gfx::IntSize& size) {
  RefPtr<layers::SharedSurfaceTextureClient> newBack =
      mFactory->NewTexClient(size);
  if (!newBack) return false;
  if (!newBack) return false;

  // In the case of DXGL interop, the new surface needs to be acquired before
  // it is attached so that the interop surface is locked, which populates
  // the GL renderbuffer. This results in the renderbuffer being ready and
  // attachment to framebuffer succeeds in Attach() call.
  // attachment to framebuffer succeeds in Attach() call.
  newBack->Surf()->ProducerAcquire();

  if (!Attach(newBack->Surf(), size)) {
    newBack->Surf()->ProducerRelease();
    return false;
    return false;
  }
  // Attach was successful.

  mFront = mBack;
  mBack = newBack;
  mBack = newBack;

  if (mCaps.preserve && mFront && mBack) {
    auto src = mFront->Surf();
    auto dest = mBack->Surf();
    auto dest = mBack->Surf();

    // uint32_t srcPixel = ReadPixel(src);
    // uint32_t destPixel = ReadPixel(dest);
    // uint32_t destPixel = ReadPixel(dest);
    // printf_stderr("Before: src: 0x%08x, dest: 0x%08x\n", srcPixel,
    // printf_stderr("Before: src: 0x%08x, dest: 0x%08x\n", srcPixel,
    // destPixel);
#ifdef DEBUG
    GLContext::LocalErrorScope errorScope(*mGL);
    GLContext::LocalErrorScope errorScope(*mGL);
#endif

    if (!SharedSurface::ProdCopy(src, dest, mFactory.get())) {
      newBack->Surf()->ProducerRelease();
      return false;
      return false;
    }

#ifdef DEBUG
    MOZ_ASSERT(!errorScope.GetError());
#endif
#endif

    // srcPixel = ReadPixel(src);
    // destPixel = ReadPixel(dest);
    // printf_stderr("After: src: 0x%08x, dest: 0x%08x\n", srcPixel, destPixel);
  }
  }

  // XXX: We would prefer to fence earlier on platforms that don't need
  // the full ProducerAcquire/ProducerRelease semantics, so that the fence
  // doesn't include the copy operation. Unfortunately, the current API
  // doesn't expose a good way to do that.
  // doesn't expose a good way to do that.
  if (mFront) {
    mFront->Surf()->ProducerRelease();
  }


  return true;
}

bool GLScreenBuffer::Resize(const gfx::IntSize& size) {
  RefPtr<layers::SharedSurfaceTextureClient> newBack =
  RefPtr<layers::SharedSurfaceTextureClient> newBack =
      mFactory->NewTexClient(size);
  if (!newBack) return false;

  if (!Attach(newBack->Surf(), size)) return false;


  if (mBack) mBack->Surf()->ProducerRelease();

  mBack = newBack;

  mBack->Surf()->ProducerAcquire();
  mBack->Surf()->ProducerAcquire();

  return true;
}

UniquePtr<ReadBuffer> GLScreenBuffer::CreateRead(SharedSurface* surf) {
UniquePtr<ReadBuffer> GLScreenBuffer::CreateRead(SharedSurface* surf) {
  GLContext* gl = mFactory->mGL;
  const GLFormats& formats = mFactory->mFormats;
  const SurfaceCaps& caps = mFactory->ReadCaps();

  return ReadBuffer::Create(gl, caps, formats, surf);
  return ReadBuffer::Create(gl, caps, formats, surf);
}

////////////////////////////////////////////////////////////////////////
// Utils


static void CreateRenderbuffersForOffscreen(GLContext* const aGL,
                                            const GLFormats& aFormats,
                                            const gfx::IntSize& aSize,
                                            GLuint* const aDepthRB,
                                            GLuint* const aStencilRB) {
                                            GLuint* const aStencilRB) {
  const auto fnCreateRenderbuffer = [&](const GLenum sizedFormat) {
    GLuint rb = 0;
    aGL->fGenRenderbuffers(1, &rb);
    ScopedBindRenderbuffer autoRB(aGL, rb);


    aGL->fRenderbufferStorage(LOCAL_GL_RENDERBUFFER, sizedFormat, aSize.width,
                              aSize.height);
    return rb;
  };

  if (aDepthRB && aStencilRB && aFormats.depthStencil) {
    *aDepthRB = fnCreateRenderbuffer(aFormats.depthStencil);
    *aDepthRB = fnCreateRenderbuffer(aFormats.depthStencil);
    *aStencilRB = *aDepthRB;
  } else {
    if (aDepthRB) {
      MOZ_ASSERT(aFormats.depth);
      MOZ_ASSERT(aFormats.depth);

      *aDepthRB = fnCreateRenderbuffer(aFormats.depth);
    }

    if (aStencilRB) {
    if (aStencilRB) {
      MOZ_ASSERT(aFormats.stencil);

      *aStencilRB = fnCreateRenderbuffer(aFormats.stencil);
    }
  }
  }
}

////////////////////////////////////////////////////////////////////////
// ReadBuffer


UniquePtr<ReadBuffer> ReadBuffer::Create(GLContext* gl, const SurfaceCaps& caps,
                                         const GLFormats& formats,
                                         SharedSurface* surf) {
  MOZ_ASSERT(surf);


  if (surf->mAttachType == AttachmentType::Screen) {
    // Don't need anything. Our read buffer will be the 'screen'.
    return UniquePtr<ReadBuffer>(new ReadBuffer(gl, 0, 0, 0, surf));
  }


  GLuint depthRB = 0;
  GLuint stencilRB = 0;

  GLuint* pDepthRB = caps.depth ? &depthRB : nullptr;
  GLuint* pStencilRB = caps.stencil ? &stencilRB : nullptr;
  GLuint* pStencilRB = caps.stencil ? &stencilRB : nullptr;

  GLContext::LocalErrorScope localError(*gl);

  CreateRenderbuffersForOffscreen(gl, formats, surf->mSize, pDepthRB,
                                  pStencilRB);

  GLuint colorTex = 0;
  GLuint colorTex = 0;
  GLuint colorRB = 0;
  GLenum target = 0;

  switch (surf->mAttachType) {
    case AttachmentType::GLTexture:
      colorTex = surf->ProdTexture();
      target = surf->ProdTextureTarget();
      break;
      break;
    case AttachmentType::GLRenderbuffer:
      colorRB = surf->ProdRenderbuffer();
      break;
    default:
      MOZ_CRASH("GFX: Unknown attachment type, create?");
      MOZ_CRASH("GFX: Unknown attachment type, create?");
  }
  MOZ_ASSERT(colorTex || colorRB);

  GLuint fb = 0;
  gl->fGenFramebuffers(1, &fb);
  gl->fGenFramebuffers(1, &fb);
  gl->AttachBuffersToFB(colorTex, colorRB, depthRB, stencilRB, fb, target);
  gl->mFBOMapping[fb] = surf;

  UniquePtr<ReadBuffer> ret(new ReadBuffer(gl, fb, depthRB, stencilRB, surf));


  GLenum err = localError.GetError();
  MOZ_ASSERT_IF(err != LOCAL_GL_NO_ERROR, err == LOCAL_GL_OUT_OF_MEMORY);
  if (err) return nullptr;


  const bool needsAcquire = !surf->IsProducerAcquired();
  if (needsAcquire) {
    surf->ProducerReadAcquire();
  }
  const bool isComplete = gl->IsFramebufferComplete(fb);
  const bool isComplete = gl->IsFramebufferComplete(fb);
  if (needsAcquire) {
    surf->ProducerReadRelease();
  }

  if (!isComplete) return nullptr;
  if (!isComplete) return nullptr;

  return ret;
}

ReadBuffer::~ReadBuffer() {
ReadBuffer::~ReadBuffer() {
  if (!mGL->MakeCurrent()) return;

  GLuint fb = mFB;
  GLuint rbs[] = {
      mDepthRB,
      (mStencilRB != mDepthRB) ? mStencilRB
      (mStencilRB != mDepthRB) ? mStencilRB
                               : 0,  // Don't double-delete DEPTH_STENCIL RBs.
  };

  mGL->fDeleteFramebuffers(1, &fb);
  mGL->fDeleteRenderbuffers(2, rbs);
  mGL->fDeleteRenderbuffers(2, rbs);

  mGL->mFBOMapping.erase(mFB);
}

void ReadBuffer::Attach(SharedSurface* surf) {
void ReadBuffer::Attach(SharedSurface* surf) {
  MOZ_ASSERT(surf && mSurf);
  MOZ_ASSERT(surf->mAttachType == mSurf->mAttachType);
  MOZ_ASSERT(surf->mSize == mSurf->mSize);

  // Nothing else is needed for AttachType Screen.
  if (surf->mAttachType != AttachmentType::Screen) {
    GLuint colorTex = 0;
    GLuint colorTex = 0;
    GLuint colorRB = 0;
    GLenum target = 0;

    switch (surf->mAttachType) {
      case AttachmentType::GLTexture:
      case AttachmentType::GLTexture:
        colorTex = surf->ProdTexture();
        target = surf->ProdTextureTarget();
        break;
      case AttachmentType::GLRenderbuffer:
        colorRB = surf->ProdRenderbuffer();
        colorRB = surf->ProdRenderbuffer();
        break;
      default:
        MOZ_CRASH("GFX: Unknown attachment type, attach?");
    }


    mGL->AttachBuffersToFB(colorTex, colorRB, 0, 0, mFB, target);
    mGL->mFBOMapping[mFB] = surf;
    MOZ_GL_ASSERT(mGL, mGL->IsFramebufferComplete(mFB));
  }


  mSurf = surf;
}

const gfx::IntSize& ReadBuffer::Size() const { return mSurf->mSize; }
const gfx::IntSize& ReadBuffer::Size() const { return mSurf->mSize; }

}  // namespace mozilla::gl