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 (d6844fe546ad)

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
/* -*- 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 "SharedSurface.h"

#include "../2d/2D.h"
#include "GLBlitHelper.h"
#include "GLContext.h"
#include "GLReadTexImageHelper.h"
#include "GLScreenBuffer.h"
#include "nsThreadUtils.h"
#include "ScopedGLHelpers.h"
#include "SharedSurfaceGL.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/layers/CompositorTypes.h"
#include "mozilla/layers/TextureClientSharedSurface.h"
#include "mozilla/layers/TextureForwarder.h"
#include "mozilla/Unused.h"
#include "VRManagerChild.h"

namespace mozilla {
namespace gl {

/*static*/
bool SharedSurface::ProdCopy(SharedSurface* src, SharedSurface* dest,
                             SurfaceFactory* factory) {
  GLContext* gl = src->mGL;

  // If `src` begins locked, it must end locked, though we may
  // temporarily unlock it if we need to.
  MOZ_ASSERT((src == gl->GetLockedSurface()) == src->IsLocked());

  gl->MakeCurrent();

  if (src->mAttachType == AttachmentType::Screen &&
      dest->mAttachType == AttachmentType::Screen) {
    // Here, we actually need to blit through a temp surface, so let's make one.
    UniquePtr<SharedSurface_Basic> tempSurf;
    tempSurf = SharedSurface_Basic::Create(gl, factory->mFormats, src->mSize,
                                           factory->mCaps.alpha);
    if (!tempSurf) {
      gfxCriticalNote << "Failed to allocate SharedSurface_Basic.";
      return false;
    }

    ProdCopy(src, tempSurf.get(), factory);
    ProdCopy(tempSurf.get(), dest, factory);
    return true;
  }

  if (src->mAttachType == AttachmentType::Screen) {
    SharedSurface* origLocked = gl->GetLockedSurface();
    bool srcNeedsUnlock = false;
    bool origNeedsRelock = false;
    if (origLocked != src) {
      if (origLocked) {
        origLocked->UnlockProd();
        origNeedsRelock = true;
      }

      src->LockProd();
      srcNeedsUnlock = true;
    }

    if (dest->mAttachType == AttachmentType::GLTexture) {
      GLuint destTex = dest->ProdTexture();
      GLenum destTarget = dest->ProdTextureTarget();

      const ScopedBindFramebuffer bindFB(gl, 0);

      gl->BlitHelper()->BlitFramebufferToTexture(destTex, src->mSize,
                                                 dest->mSize, destTarget);
    } else if (dest->mAttachType == AttachmentType::GLRenderbuffer) {
      GLuint destRB = dest->ProdRenderbuffer();
      ScopedFramebufferForRenderbuffer destWrapper(gl, destRB);

      gl->BlitHelper()->BlitFramebufferToFramebuffer(
          0, destWrapper.FB(), gfx::IntRect({}, src->mSize),
          gfx::IntRect({}, dest->mSize));
    } else {
      MOZ_CRASH("GFX: Unhandled dest->mAttachType 1.");
    }

    if (srcNeedsUnlock) src->UnlockProd();

    if (origNeedsRelock) origLocked->LockProd();

    return true;
  }

  if (dest->mAttachType == AttachmentType::Screen) {
    SharedSurface* origLocked = gl->GetLockedSurface();
    bool destNeedsUnlock = false;
    bool origNeedsRelock = false;
    if (origLocked != dest) {
      if (origLocked) {
        origLocked->UnlockProd();
        origNeedsRelock = true;
      }

      dest->LockProd();
      destNeedsUnlock = true;
    }

    if (src->mAttachType == AttachmentType::GLTexture) {
      GLuint srcTex = src->ProdTexture();
      GLenum srcTarget = src->ProdTextureTarget();

      const ScopedBindFramebuffer bindFB(gl, 0);

      gl->BlitHelper()->BlitTextureToFramebuffer(srcTex, src->mSize,
                                                 dest->mSize, srcTarget);
    } else if (src->mAttachType == AttachmentType::GLRenderbuffer) {
      GLuint srcRB = src->ProdRenderbuffer();
      ScopedFramebufferForRenderbuffer srcWrapper(gl, srcRB);

      gl->BlitHelper()->BlitFramebufferToFramebuffer(
          srcWrapper.FB(), 0, gfx::IntRect({}, src->mSize),
          gfx::IntRect({}, dest->mSize));
    } else {
      MOZ_CRASH("GFX: Unhandled src->mAttachType 2.");
    }

    if (destNeedsUnlock) dest->UnlockProd();

    if (origNeedsRelock) origLocked->LockProd();

    return true;
  }

  // Alright, done with cases involving Screen types.
  // Only {src,dest}x{texture,renderbuffer} left.

  if (src->mAttachType == AttachmentType::GLTexture) {
    GLuint srcTex = src->ProdTexture();
    GLenum srcTarget = src->ProdTextureTarget();

    if (dest->mAttachType == AttachmentType::GLTexture) {
      GLuint destTex = dest->ProdTexture();
      GLenum destTarget = dest->ProdTextureTarget();

      gl->BlitHelper()->BlitTextureToTexture(
          srcTex, destTex, src->mSize, dest->mSize, srcTarget, destTarget);

      return true;
    }

    if (dest->mAttachType == AttachmentType::GLRenderbuffer) {
      GLuint destRB = dest->ProdRenderbuffer();
      ScopedFramebufferForRenderbuffer destWrapper(gl, destRB);
      const ScopedBindFramebuffer bindFB(gl, destWrapper.FB());
      gl->BlitHelper()->BlitTextureToFramebuffer(srcTex, src->mSize,
                                                 dest->mSize, srcTarget);

      return true;
    }

    MOZ_CRASH("GFX: Unhandled dest->mAttachType 3.");
  }

  if (src->mAttachType == AttachmentType::GLRenderbuffer) {
    GLuint srcRB = src->ProdRenderbuffer();
    ScopedFramebufferForRenderbuffer srcWrapper(gl, srcRB);

    if (dest->mAttachType == AttachmentType::GLTexture) {
      GLuint destTex = dest->ProdTexture();
      GLenum destTarget = dest->ProdTextureTarget();
      const ScopedBindFramebuffer bindFB(gl, srcWrapper.FB());

      gl->BlitHelper()->BlitFramebufferToTexture(destTex, src->mSize,
                                                 dest->mSize, destTarget);

      return true;
    }

    if (dest->mAttachType == AttachmentType::GLRenderbuffer) {
      GLuint destRB = dest->ProdRenderbuffer();
      ScopedFramebufferForRenderbuffer destWrapper(gl, destRB);

      gl->BlitHelper()->BlitFramebufferToFramebuffer(
          srcWrapper.FB(), destWrapper.FB(), gfx::IntRect({}, src->mSize),
          gfx::IntRect({}, dest->mSize));

      return true;
    }

    MOZ_CRASH("GFX: Unhandled dest->mAttachType 4.");
  }

  MOZ_CRASH("GFX: Unhandled src->mAttachType 5.");
}

////////////////////////////////////////////////////////////////////////
// SharedSurface

SharedSurface::SharedSurface(SharedSurfaceType type, AttachmentType attachType,
                             GLContext* gl, const gfx::IntSize& size,
                             bool hasAlpha, bool canRecycle)
    : mType(type),
      mAttachType(attachType),
      mGL(gl),
      mSize(size),
      mHasAlpha(hasAlpha),
      mCanRecycle(canRecycle),
      mIsLocked(false),
      mIsProducerAcquired(false) {}

SharedSurface::~SharedSurface() = default;

layers::TextureFlags SharedSurface::GetTextureFlags() const {
  return layers::TextureFlags::NO_FLAGS;
}

void SharedSurface::LockProd() {
  MOZ_ASSERT(!mIsLocked);

  LockProdImpl();

  mGL->LockSurface(this);
  mIsLocked = true;
}

void SharedSurface::UnlockProd() {
  if (!mIsLocked) return;

  UnlockProdImpl();

  mGL->UnlockSurface(this);
  mIsLocked = false;
}

////////////////////////////////////////////////////////////////////////
// SurfaceFactory

static void ChooseBufferBits(const SurfaceCaps& caps,
                             SurfaceCaps* const out_drawCaps,
                             SurfaceCaps* const out_readCaps) {
  MOZ_ASSERT(out_drawCaps);
  MOZ_ASSERT(out_readCaps);

  SurfaceCaps screenCaps;

  screenCaps.color = caps.color;
  screenCaps.alpha = caps.alpha;
  screenCaps.bpp16 = caps.bpp16;

  screenCaps.depth = caps.depth;
  screenCaps.stencil = caps.stencil;

  screenCaps.preserve = caps.preserve;

  out_drawCaps->Clear();
  *out_readCaps = screenCaps;
}

SurfaceFactory::SurfaceFactory(
    SharedSurfaceType type, GLContext* gl, const SurfaceCaps& caps,
    const RefPtr<layers::LayersIPCChannel>& allocator,
    const layers::TextureFlags& flags)
    : mType(type),
      mGL(gl),
      mCaps(caps),
      mAllocator(allocator),
      mFlags(flags),
      mFormats(gl->ChooseGLFormats(caps)),
      mMutex("SurfaceFactor::mMutex") {
  ChooseBufferBits(mCaps, &mDrawCaps, &mReadCaps);
}

SurfaceFactory::~SurfaceFactory() {
  while (!mRecycleTotalPool.empty()) {
    RefPtr<layers::SharedSurfaceTextureClient> tex = *mRecycleTotalPool.begin();
    StopRecycling(tex);
  }

  MOZ_RELEASE_ASSERT(mRecycleTotalPool.empty(),
                     "GFX: Surface recycle pool not empty.");

  // If we mRecycleFreePool.clear() before StopRecycling(), we may try to
  // recycle it, fail, call StopRecycling(), then return here and call it again.
  mRecycleFreePool.clear();
}

already_AddRefed<layers::SharedSurfaceTextureClient>
SurfaceFactory::NewTexClient(const gfx::IntSize& size) {
  while (!mRecycleFreePool.empty()) {
    RefPtr<layers::SharedSurfaceTextureClient> cur = mRecycleFreePool.front();
    mRecycleFreePool.pop();

    if (cur->Surf()->mSize == size) {
      cur->Surf()->WaitForBufferOwnership();
      return cur.forget();
    }

    StopRecycling(cur);
  }

  UniquePtr<SharedSurface> surf = CreateShared(size);
  if (!surf) return nullptr;

  RefPtr<layers::SharedSurfaceTextureClient> ret;
  ret = layers::SharedSurfaceTextureClient::Create(std::move(surf), this,
                                                   mAllocator, mFlags);

  StartRecycling(ret);

  return ret.forget();
}

void SurfaceFactory::StartRecycling(layers::SharedSurfaceTextureClient* tc) {
  tc->SetRecycleCallback(&SurfaceFactory::RecycleCallback,
                         static_cast<void*>(this));

  bool didInsert = mRecycleTotalPool.insert(tc);
  MOZ_RELEASE_ASSERT(
      didInsert,
      "GFX: Shared surface texture client was not inserted to recycle.");
  mozilla::Unused << didInsert;
}

void SurfaceFactory::StopRecycling(layers::SharedSurfaceTextureClient* tc) {
  MutexAutoLock autoLock(mMutex);
  // Must clear before releasing ref.
  tc->ClearRecycleCallback();

  bool didErase = mRecycleTotalPool.erase(tc);
  MOZ_RELEASE_ASSERT(didErase,
                     "GFX: Shared texture surface client was not erased.");
  mozilla::Unused << didErase;
}

/*static*/
void SurfaceFactory::RecycleCallback(layers::TextureClient* rawTC,
                                     void* rawFactory) {
  RefPtr<layers::SharedSurfaceTextureClient> tc;
  tc = static_cast<layers::SharedSurfaceTextureClient*>(rawTC);
  SurfaceFactory* factory = static_cast<SurfaceFactory*>(rawFactory);

  if (tc->Surf()->mCanRecycle) {
    if (factory->Recycle(tc)) return;
  }

  // Did not recover the tex client. End the (re)cycle!
  factory->StopRecycling(tc);
}

bool SurfaceFactory::Recycle(layers::SharedSurfaceTextureClient* texClient) {
  MOZ_ASSERT(texClient);
  MutexAutoLock autoLock(mMutex);

  if (mRecycleFreePool.size() >= 2) {
    return false;
  }

  RefPtr<layers::SharedSurfaceTextureClient> texClientRef = texClient;
  mRecycleFreePool.push(texClientRef);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// ScopedReadbackFB

ScopedReadbackFB::ScopedReadbackFB(SharedSurface* src)
    : mGL(src->mGL), mAutoFB(mGL) {
  switch (src->mAttachType) {
    case AttachmentType::GLRenderbuffer: {
      mGL->fGenFramebuffers(1, &mTempFB);
      mGL->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mTempFB);

      GLuint rb = src->ProdRenderbuffer();
      mGL->fFramebufferRenderbuffer(LOCAL_GL_FRAMEBUFFER,
                                    LOCAL_GL_COLOR_ATTACHMENT0,
                                    LOCAL_GL_RENDERBUFFER, rb);
      break;
    }
    case AttachmentType::GLTexture: {
      mGL->fGenFramebuffers(1, &mTempFB);
      mGL->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mTempFB);

      GLuint tex = src->ProdTexture();
      GLenum texImageTarget = src->ProdTextureTarget();
      mGL->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER,
                                 LOCAL_GL_COLOR_ATTACHMENT0, texImageTarget,
                                 tex, 0);
      break;
    }
    case AttachmentType::Screen: {
      SharedSurface* origLocked = mGL->GetLockedSurface();
      if (origLocked != src) {
        if (origLocked) {
          mSurfToLock = origLocked;
          mSurfToLock->UnlockProd();
        }

        mSurfToUnlock = src;
        mSurfToUnlock->LockProd();
      }

      // TODO: This should just be BindFB, but we don't have
      // the patch for this yet. (bug 1045955)
      MOZ_ASSERT(mGL->Screen());
      mGL->Screen()->BindReadFB_Internal(0);
      break;
    }
    default:
      MOZ_CRASH("GFX: Unhandled `mAttachType`.");
  }

  if (src->NeedsIndirectReads()) {
    mGL->fGenTextures(1, &mTempTex);

    {
      ScopedBindTexture autoTex(mGL, mTempTex);

      GLenum format = src->mHasAlpha ? LOCAL_GL_RGBA : LOCAL_GL_RGB;
      auto width = src->mSize.width;
      auto height = src->mSize.height;
      mGL->fCopyTexImage2D(LOCAL_GL_TEXTURE_2D, 0, format, 0, 0, width, height,
                           0);
    }

    mGL->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER, LOCAL_GL_COLOR_ATTACHMENT0,
                               LOCAL_GL_TEXTURE_2D, mTempTex, 0);
  }
}

ScopedReadbackFB::~ScopedReadbackFB() {
  if (mTempFB) {
    mGL->fDeleteFramebuffers(1, &mTempFB);
  }
  if (mTempTex) {
    mGL->fDeleteTextures(1, &mTempTex);
  }
  if (mSurfToUnlock) {
    mSurfToUnlock->UnlockProd();
  }
  if (mSurfToLock) {
    mSurfToLock->LockProd();
  }
}

////////////////////////////////////////////////////////////////////////////////

class AutoLockBits {
  gfx::DrawTarget* mDT;
  uint8_t* mLockedBits;

 public:
  explicit AutoLockBits(gfx::DrawTarget* dt) : mDT(dt), mLockedBits(nullptr) {
    MOZ_ASSERT(mDT);
  }

  bool Lock(uint8_t** data, gfx::IntSize* size, int32_t* stride,
            gfx::SurfaceFormat* format) {
    if (!mDT->LockBits(data, size, stride, format)) return false;

    mLockedBits = *data;
    return true;
  }

  ~AutoLockBits() {
    if (mLockedBits) mDT->ReleaseBits(mLockedBits);
  }
};

bool ReadbackSharedSurface(SharedSurface* src, gfx::DrawTarget* dst) {
  AutoLockBits lock(dst);

  uint8_t* dstBytes;
  gfx::IntSize dstSize;
  int32_t dstStride;
  gfx::SurfaceFormat dstFormat;
  if (!lock.Lock(&dstBytes, &dstSize, &dstStride, &dstFormat)) return false;

  const bool isDstRGBA = (dstFormat == gfx::SurfaceFormat::R8G8B8A8 ||
                          dstFormat == gfx::SurfaceFormat::R8G8B8X8);
  MOZ_ASSERT_IF(!isDstRGBA, dstFormat == gfx::SurfaceFormat::B8G8R8A8 ||
                                dstFormat == gfx::SurfaceFormat::B8G8R8X8);

  size_t width = src->mSize.width;
  size_t height = src->mSize.height;
  MOZ_ASSERT(width == (size_t)dstSize.width);
  MOZ_ASSERT(height == (size_t)dstSize.height);

  GLenum readGLFormat;
  GLenum readType;

  {
    ScopedReadbackFB autoReadback(src);

    // We have a source FB, now we need a format.
    GLenum dstGLFormat = isDstRGBA ? LOCAL_GL_BGRA : LOCAL_GL_RGBA;
    GLenum dstType = LOCAL_GL_UNSIGNED_BYTE;

    // We actually don't care if they match, since we can handle
    // any read{Format,Type} we get.
    GLContext* gl = src->mGL;
    GetActualReadFormats(gl, dstGLFormat, dstType, &readGLFormat, &readType);

    MOZ_ASSERT(readGLFormat == LOCAL_GL_RGBA || readGLFormat == LOCAL_GL_BGRA);
    MOZ_ASSERT(readType == LOCAL_GL_UNSIGNED_BYTE);

    // ReadPixels from the current FB into lockedBits.
    {
      ScopedPackState scopedPackState(gl);
      bool handled = scopedPackState.SetForWidthAndStrideRGBA(width, dstStride);
      MOZ_RELEASE_ASSERT(handled, "Unhandled stride");
      gl->raw_fReadPixels(0, 0, width, height, readGLFormat, readType,
                          dstBytes);
    }
  }

  const bool isReadRGBA = readGLFormat == LOCAL_GL_RGBA;

  if (isReadRGBA != isDstRGBA) {
    for (size_t j = 0; j < height; ++j) {
      uint8_t* rowItr = dstBytes + j * dstStride;
      uint8_t* rowEnd = rowItr + 4 * width;
      while (rowItr != rowEnd) {
        Swap(rowItr[0], rowItr[2]);
        rowItr += 4;
      }
    }
  }

  return true;
}

uint32_t ReadPixel(SharedSurface* src) {
  GLContext* gl = src->mGL;

  uint32_t pixel;

  ScopedReadbackFB a(src);
  {
    ScopedPackState scopedPackState(gl);

    UniquePtr<uint8_t[]> bytes(new uint8_t[4]);
    gl->raw_fReadPixels(0, 0, 1, 1, LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE,
                        bytes.get());
    memcpy(&pixel, bytes.get(), 4);
  }

  return pixel;
}

}  // namespace gl

} /* namespace mozilla */