Added SkImage::MakeCrossContextFromEncoded
authorBrian Osman <brianosman@google.com>
Tue, 9 May 2017 17:19:50 +0000 (13:19 -0400)
committerSkia Commit-Bot <skia-commit-bot@chromium.org>
Tue, 9 May 2017 18:45:04 +0000 (18:45 +0000)
Designed for Flutter's threading architecture, with
an eye to being useful to other clients. Under the
hood, uses a new image generator class to lazily wrap
a texture for multiple GrContexts.

Re-land of https://skia-review.googlesource.com/c/14180/

Bug: skia:
Change-Id: I3dd382640629b79b3058f18fee68d043566e43e5
Reviewed-on: https://skia-review.googlesource.com/15895
Reviewed-by: Brian Salomon <bsalomon@google.com>
Commit-Queue: Brian Osman <brianosman@google.com>

18 files changed:
gm/crosscontextimage.cpp [new file with mode: 0644]
gn/gm.gni
gn/gpu.gni
include/core/SkImage.h
src/gpu/GrBackendTextureImageGenerator.cpp [new file with mode: 0644]
src/gpu/GrBackendTextureImageGenerator.h [new file with mode: 0644]
src/gpu/GrContext.cpp
src/gpu/GrGpu.h
src/gpu/GrResourceCache.cpp
src/gpu/GrResourceCache.h
src/gpu/gl/GrGLGpu.cpp
src/gpu/gl/GrGLGpu.h
src/gpu/vk/GrVkGpu.cpp
src/gpu/vk/GrVkGpu.h
src/gpu/vk/GrVkImage.h
src/image/SkImage_Gpu.cpp
tests/ImageTest.cpp
tools/gpu/GrTest.cpp

diff --git a/gm/crosscontextimage.cpp b/gm/crosscontextimage.cpp
new file mode 100644 (file)
index 0000000..cf973db
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "gm.h"
+#include "Resources.h"
+
+#if SK_SUPPORT_GPU
+#include "GrContext.h"
+#include "SkImage.h"
+
+DEF_SIMPLE_GM(cross_context_image, canvas, 512 + 512 + 30, 512 + 128 + 30) {
+    GrContext* context = canvas->getGrContext();
+    if (!context) {
+        skiagm::GM::DrawGpuOnlyMessage(canvas);
+        return;
+    }
+
+    sk_sp<SkData> encodedData = GetResourceAsData("mandrill_512.png");
+
+    sk_sp<SkImage> encodedImage = SkImage::MakeFromEncoded(encodedData);
+    canvas->drawImage(encodedImage, 10, 10);
+
+    sk_sp<SkImage> crossContextImage = SkImage::MakeCrossContextFromEncoded(
+        context, encodedData, false, canvas->imageInfo().colorSpace());
+    canvas->drawImage(crossContextImage, 512 + 30, 10);
+
+    SkIRect subset = SkIRect::MakeXYWH(256 - 64, 256 - 64, 128, 128);
+    sk_sp<SkImage> encodedSubset = encodedImage->makeSubset(subset);
+    sk_sp<SkImage> crossContextSubset = crossContextImage->makeSubset(subset);
+
+    canvas->drawImage(encodedSubset, 10, 512 + 30);
+    canvas->drawImage(crossContextSubset, 512 + 30, 512 + 30);
+}
+
+#endif
index 5cfde5f..4bcd103 100644 (file)
--- a/gn/gm.gni
+++ b/gn/gm.gni
@@ -85,6 +85,7 @@ gm_sources = [
   "$_gm/copyTo4444.cpp",
   "$_gm/crbug_691386.cpp",
   "$_gm/croppedrects.cpp",
+  "$_gm/crosscontextimage.cpp",
   "$_gm/cubicpaths.cpp",
   "$_gm/dashcircle.cpp",
   "$_gm/dashcubics.cpp",
index 7751d1e..fde979d 100644 (file)
@@ -50,6 +50,8 @@ skia_gpu_sources = [
   "$_src/gpu/GrAutoLocaleSetter.h",
   "$_src/gpu/GrAllocator.h",
   "$_src/gpu/GrBackendSurface.cpp",
+  "$_src/gpu/GrBackendTextureImageGenerator.cpp",
+  "$_src/gpu/GrBackendTextureImageGenerator.h",
   "$_src/gpu/GrBitmapTextureMaker.cpp",
   "$_src/gpu/GrBitmapTextureMaker.h",
   "$_src/gpu/GrBlend.cpp",
index e7cb3f3..2ba6761 100644 (file)
@@ -159,6 +159,21 @@ public:
                                           SkAlphaType, sk_sp<SkColorSpace>,
                                           TextureReleaseProc, ReleaseContext);
 
+    /**
+     *  Decodes and uploads the encoded data to a GPU backed image using the supplied GrContext.
+     *  That image can be safely used by other GrContexts, across thread boundaries. The GrContext
+     *  used here, and the ones used to draw this image later must be in the same GL share group,
+     *  or otherwise be able to share resources.
+     *
+     *  When the image's ref count reaches zero, the original GrContext will destroy the texture,
+     *  asynchronously.
+     *
+     *  The texture will be decoded and uploaded to be suitable for use with surfaces that have the
+     *  supplied destination color space. The color space of the image itself will be determined
+     *  from the encoded data.
+     */
+    static sk_sp<SkImage> MakeCrossContextFromEncoded(GrContext*, sk_sp<SkData>, bool buildMips,
+                                                      SkColorSpace* dstColorSpace);
 
     /**
      *  Create a new image from the specified descriptor. Note - Skia will delete or recycle the
diff --git a/src/gpu/GrBackendTextureImageGenerator.cpp b/src/gpu/GrBackendTextureImageGenerator.cpp
new file mode 100644 (file)
index 0000000..d92b32f
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * Copyright 2017 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+
+#include "GrBackendTextureImageGenerator.h"
+
+#include "GrContext.h"
+#include "GrContextPriv.h"
+#include "GrResourceCache.h"
+#include "GrResourceProvider.h"
+#include "GrSemaphore.h"
+
+#include "SkGr.h"
+#include "SkMessageBus.h"
+
+GrBackendTextureImageGenerator::RefHelper::~RefHelper() {
+    SkASSERT(nullptr == fBorrowedTexture);
+    SkASSERT(SK_InvalidGenID == fBorrowingContextID);
+
+    // Generator has been freed, and no one is borrowing the texture. Notify the original cache
+    // that it can free the last ref, so it happens on the correct thread.
+    GrGpuResourceFreedMessage msg { fOriginalTexture, fOwningContextID };
+    SkMessageBus<GrGpuResourceFreedMessage>::Post(msg);
+}
+
+// TODO: I copied this from SkImage_Gpu, perhaps we put a version of this somewhere else?
+static GrBackendTexture make_backend_texture_from_handle(GrBackend backend,
+                                                         int width, int height,
+                                                         GrPixelConfig config,
+                                                         GrBackendObject handle) {
+    if (kOpenGL_GrBackend == backend) {
+        GrGLTextureInfo* glInfo = (GrGLTextureInfo*)(handle);
+        return GrBackendTexture(width, height, config, *glInfo);
+    } else {
+        SkASSERT(kVulkan_GrBackend == backend);
+        GrVkImageInfo* vkInfo = (GrVkImageInfo*)(handle);
+        return GrBackendTexture(width, height, *vkInfo);
+    }
+}
+
+std::unique_ptr<SkImageGenerator>
+GrBackendTextureImageGenerator::Make(sk_sp<GrTexture> texture, sk_sp<GrSemaphore> semaphore,
+                                     SkAlphaType alphaType, sk_sp<SkColorSpace> colorSpace) {
+    if (colorSpace && (!colorSpace->gammaCloseToSRGB() && !colorSpace->gammaIsLinear())) {
+        return nullptr;
+    }
+
+    SkColorType colorType = kUnknown_SkColorType;
+    if (!GrPixelConfigToColorType(texture->config(), &colorType)) {
+        return nullptr;
+    }
+
+    GrContext* context = texture->getContext();
+
+    // Attach our texture to this context's resource cache. This ensures that deletion will happen
+    // in the correct thread/context. This adds the only ref to the texture that will persist from
+    // this point. That ref will be released when the generator's RefHelper is freed.
+    context->getResourceCache()->insertCrossContextGpuResource(texture.get());
+
+    GrBackend backend = context->contextPriv().getBackend();
+    GrBackendTexture backendTexture = make_backend_texture_from_handle(backend,
+                                                                       texture->width(),
+                                                                       texture->height(),
+                                                                       texture->config(),
+                                                                       texture->getTextureHandle());
+
+    SkImageInfo info = SkImageInfo::Make(texture->width(), texture->height(), colorType, alphaType,
+                                         std::move(colorSpace));
+    return std::unique_ptr<SkImageGenerator>(new GrBackendTextureImageGenerator(
+            info, texture.get(), context->uniqueID(), std::move(semaphore), backendTexture));
+}
+
+GrBackendTextureImageGenerator::GrBackendTextureImageGenerator(const SkImageInfo& info,
+                                                               GrTexture* texture,
+                                                               uint32_t owningContextID,
+                                                               sk_sp<GrSemaphore> semaphore,
+                                                               const GrBackendTexture& backendTex)
+    : INHERITED(info)
+    , fRefHelper(new RefHelper(texture, owningContextID))
+    , fSemaphore(std::move(semaphore))
+    , fLastBorrowingContextID(SK_InvalidGenID)
+    , fBackendTexture(backendTex)
+    , fSurfaceOrigin(texture->origin()) { }
+
+GrBackendTextureImageGenerator::~GrBackendTextureImageGenerator() {
+    fRefHelper->unref();
+}
+
+bool GrBackendTextureImageGenerator::onGetPixels(const SkImageInfo& info, void* pixels,
+                                                 size_t rowBytes, SkPMColor ctable[],
+                                                 int* ctableCount) {
+    // TODO: Is there any way to implement this? I don't think so.
+    return false;
+}
+
+bool GrBackendTextureImageGenerator::onGetPixels(const SkImageInfo& info, void* pixels,
+                                                 size_t rowBytes, const Options& opts) {
+
+    // TODO: Is there any way to implement this? I don't think so.
+    return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#if SK_SUPPORT_GPU
+void GrBackendTextureImageGenerator::ReleaseRefHelper_TextureReleaseProc(void* ctx) {
+    RefHelper* refHelper = static_cast<RefHelper*>(ctx);
+    SkASSERT(refHelper);
+
+    // Release texture so another context can use it
+    refHelper->fBorrowedTexture = nullptr;
+    refHelper->fBorrowingContextID = SK_InvalidGenID;
+    refHelper->unref();
+}
+
+sk_sp<GrTextureProxy> GrBackendTextureImageGenerator::onGenerateTexture(GrContext* context,
+                                                                        const SkImageInfo& info,
+                                                                        const SkIPoint& origin) {
+    SkASSERT(context);
+
+    if (context->contextPriv().getBackend() != fBackendTexture.backend()) {
+        return nullptr;
+    }
+
+    sk_sp<GrTexture> tex;
+
+    if (fRefHelper->fBorrowingContextID == context->uniqueID()) {
+        // If a client re-draws the same image multiple times, the texture we return will be cached
+        // and re-used. If they draw a subset, though, we may be re-called. In that case, we want
+        // to re-use the borrowed texture we've previously created.
+        tex = sk_ref_sp(fRefHelper->fBorrowedTexture);
+        SkASSERT(tex);
+    } else {
+        // The texture is available or borrwed by another context. Try for exclusive access.
+        uint32_t expectedID = SK_InvalidGenID;
+        if (!fRefHelper->fBorrowingContextID.compare_exchange(&expectedID, context->uniqueID())) {
+            // Some other context is currently borrowing the texture. We aren't allowed to use it.
+            return nullptr;
+        } else {
+            // Wait on a semaphore when a new context has just started borrowing the texture. This
+            // is conservative, but shouldn't be too expensive.
+            if (fSemaphore && fLastBorrowingContextID != context->uniqueID()) {
+                context->getGpu()->waitSemaphore(fSemaphore);
+                fLastBorrowingContextID = context->uniqueID();
+            }
+        }
+
+        // We just gained access to the texture. If we're on the original context, we could use the
+        // original texture, but we'd have no way of detecting that it's no longer in-use. So we
+        // always make a wrapped copy, where the release proc informs us that the context is done
+        // with it. This is unfortunate - we'll have two texture objects referencing the same GPU
+        // object. However, no client can ever see the original texture, so this should be safe.
+        tex = context->resourceProvider()->wrapBackendTexture(fBackendTexture, fSurfaceOrigin,
+                                                              kNone_GrBackendTextureFlag, 0,
+                                                              kBorrow_GrWrapOwnership);
+        if (!tex) {
+            fRefHelper->fBorrowingContextID = SK_InvalidGenID;
+            return nullptr;
+        }
+        fRefHelper->fBorrowedTexture = tex.get();
+
+        tex->setRelease(ReleaseRefHelper_TextureReleaseProc, fRefHelper);
+        fRefHelper->ref();
+    }
+
+    SkASSERT(fRefHelper->fBorrowingContextID == context->uniqueID());
+
+    sk_sp<GrTextureProxy> proxy = GrSurfaceProxy::MakeWrapped(std::move(tex));
+
+    if (0 == origin.fX && 0 == origin.fY &&
+        info.width() == fBackendTexture.width() && info.height() == fBackendTexture.height()) {
+        // If the caller wants the entire texture, we're done
+        return proxy;
+    } else {
+        // Otherwise, make a copy of the requested subset. Make sure our temporary is renderable,
+        // because Vulkan will want to do the copy as a draw.
+        GrSurfaceDesc desc = proxy->desc();
+        desc.fWidth = info.width();
+        desc.fHeight = info.height();
+        desc.fFlags = kRenderTarget_GrSurfaceFlag;
+        sk_sp<GrSurfaceContext> sContext(context->contextPriv().makeDeferredSurfaceContext(
+            desc, SkBackingFit::kExact, SkBudgeted::kYes));
+        if (!sContext) {
+            return nullptr;
+        }
+
+        SkIRect subset = SkIRect::MakeXYWH(origin.fX, origin.fY, info.width(), info.height());
+        if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {
+            return nullptr;
+        }
+
+        return sContext->asTextureProxyRef();
+    }
+}
+#endif
diff --git a/src/gpu/GrBackendTextureImageGenerator.h b/src/gpu/GrBackendTextureImageGenerator.h
new file mode 100644 (file)
index 0000000..2f35895
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2017 Google Inc.
+ *
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ */
+#ifndef GrBackendTextureImageGenerator_DEFINED
+#define GrBackendTextureImageGenerator_DEFINED
+
+#include "SkImageGenerator.h"
+
+#include "GrBackendSurface.h"
+#include "SkAtomics.h"
+
+class GrSemaphore;
+
+class GrBackendTextureImageGenerator : public SkImageGenerator {
+public:
+    static std::unique_ptr<SkImageGenerator> Make(sk_sp<GrTexture>, sk_sp<GrSemaphore>,
+                                                  SkAlphaType, sk_sp<SkColorSpace>);
+
+    ~GrBackendTextureImageGenerator();
+
+protected:
+    bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, SkPMColor ctable[],
+                     int* ctableCount) override;
+    bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options& opts)
+                     override;
+
+#if SK_SUPPORT_GPU
+    sk_sp<GrTextureProxy> onGenerateTexture(GrContext*, const SkImageInfo&,
+                                            const SkIPoint&) override;
+#endif
+
+private:
+    GrBackendTextureImageGenerator(const SkImageInfo& info, GrTexture*,
+                                   uint32_t owningContextID, sk_sp<GrSemaphore>,
+                                   const GrBackendTexture&);
+
+    static void ReleaseRefHelper_TextureReleaseProc(void* ctx);
+
+    class RefHelper : public SkNVRefCnt<RefHelper> {
+    public:
+        RefHelper(GrTexture* texture, uint32_t owningContextID)
+            : fOriginalTexture(texture)
+            , fOwningContextID(owningContextID)
+            , fBorrowedTexture(nullptr)
+            , fBorrowingContextID(SK_InvalidGenID) { }
+
+        ~RefHelper();
+
+        GrTexture* fOriginalTexture;
+        uint32_t fOwningContextID;
+
+        // There is never a ref associated with this pointer. We rely on our atomic bookkeeping
+        // with the context ID to know when this pointer is valid and safe to use. This lets us
+        // avoid releasing a ref from another thread, or get into races during context shutdown.
+        GrTexture* fBorrowedTexture;
+        SkAtomic<uint32_t> fBorrowingContextID;
+    };
+
+    RefHelper* fRefHelper;
+
+    sk_sp<GrSemaphore> fSemaphore;
+    uint32_t fLastBorrowingContextID;
+
+    GrBackendTexture fBackendTexture;
+    GrSurfaceOrigin fSurfaceOrigin;
+
+    typedef SkImageGenerator INHERITED;
+};
+#endif  // GrBackendTextureImageGenerator_DEFINED
index fc38dfa..7862a82 100644 (file)
@@ -97,7 +97,7 @@ void GrContext::initCommon(const GrContextOptions& options) {
     ASSERT_SINGLE_OWNER
 
     fCaps = SkRef(fGpu->caps());
-    fResourceCache = new GrResourceCache(fCaps);
+    fResourceCache = new GrResourceCache(fCaps, fUniqueID);
     fResourceProvider = new GrResourceProvider(fGpu, fResourceCache, &fSingleOwner);
 
     fDisableGpuYUVConversion = options.fDisableGpuYUVConversion;
index b7fe048..f1efadb 100644 (file)
@@ -388,6 +388,13 @@ public:
     virtual void insertSemaphore(sk_sp<GrSemaphore> semaphore, bool flush = false) = 0;
     virtual void waitSemaphore(sk_sp<GrSemaphore> semaphore) = 0;
 
+    /**
+     *  Put this texture in a safe and known state for use across multiple GrContexts. Depending on
+     *  the backend, this may return a GrSemaphore. If so, other contexts should wait on that
+     *  semaphore before using this texture.
+     */
+    virtual sk_sp<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) = 0;
+
     ///////////////////////////////////////////////////////////////////////////
     // Debugging and Stats
 
index e3373b2..299f63f 100644 (file)
@@ -18,6 +18,8 @@
 
 DECLARE_SKMESSAGEBUS_MESSAGE(GrUniqueKeyInvalidatedMessage);
 
+DECLARE_SKMESSAGEBUS_MESSAGE(GrGpuResourceFreedMessage);
+
 //////////////////////////////////////////////////////////////////////////////
 
 GrScratchKey::ResourceType GrScratchKey::GenerateResourceType() {
@@ -59,7 +61,7 @@ private:
  //////////////////////////////////////////////////////////////////////////////
 
 
-GrResourceCache::GrResourceCache(const GrCaps* caps)
+GrResourceCache::GrResourceCache(const GrCaps* caps, uint32_t contextUniqueID)
     : fTimestamp(0)
     , fMaxCount(kDefaultMaxCount)
     , fMaxBytes(kDefaultMaxSize)
@@ -75,6 +77,7 @@ GrResourceCache::GrResourceCache(const GrCaps* caps)
     , fBudgetedBytes(0)
     , fRequestFlush(false)
     , fExternalFlushCnt(0)
+    , fContextUniqueID(contextUniqueID)
     , fPreferVRAMUseOverFlushes(caps->preferVRAMUseOverFlushes()) {
     SkDEBUGCODE(fCount = 0;)
     SkDEBUGCODE(fNewlyPurgeableResourceForValidation = nullptr;)
@@ -186,6 +189,8 @@ void GrResourceCache::abandonAll() {
 void GrResourceCache::releaseAll() {
     AutoValidate av(this);
 
+    this->processFreedGpuResources();
+
     while(fNonpurgeableResources.count()) {
         GrGpuResource* back = *(fNonpurgeableResources.end() - 1);
         SkASSERT(!back->wasDestroyed());
@@ -450,6 +455,8 @@ void GrResourceCache::purgeAsNeeded() {
         this->processInvalidUniqueKeys(invalidKeyMsgs);
     }
 
+    this->processFreedGpuResources();
+
     if (fMaxUnusedFlushes > 0) {
         // We want to know how many complete flushes have occurred without the resource being used.
         // If the resource was tagged when fExternalFlushCnt was N then this means it became
@@ -534,6 +541,20 @@ void GrResourceCache::processInvalidUniqueKeys(
     }
 }
 
+void GrResourceCache::insertCrossContextGpuResource(GrGpuResource* resource) {
+    resource->ref();
+}
+
+void GrResourceCache::processFreedGpuResources() {
+    SkTArray<GrGpuResourceFreedMessage> msgs;
+    fFreedGpuResourceInbox.poll(&msgs);
+    for (int i = 0; i < msgs.count(); ++i) {
+        if (msgs[i].fOwningUniqueID == fContextUniqueID) {
+            msgs[i].fResource->unref();
+        }
+    }
+}
+
 void GrResourceCache::addToNonpurgeableArray(GrGpuResource* resource) {
     int index = fNonpurgeableResources.count();
     *fNonpurgeableResources.append() = resource;
index d871c9a..71070ee 100644 (file)
@@ -24,6 +24,11 @@ class GrCaps;
 class SkString;
 class SkTraceMemoryDump;
 
+struct GrGpuResourceFreedMessage {
+    GrGpuResource* fResource;
+    uint32_t fOwningUniqueID;
+};
+
 /**
  * Manages the lifetime of all GrGpuResource instances.
  *
@@ -43,7 +48,7 @@ class SkTraceMemoryDump;
  */
 class GrResourceCache {
 public:
-    GrResourceCache(const GrCaps* caps);
+    GrResourceCache(const GrCaps* caps, uint32_t contextUniqueID);
     ~GrResourceCache();
 
     // Default maximum number of budgeted resources in the cache.
@@ -174,6 +179,9 @@ public:
     };
     void notifyFlushOccurred(FlushType);
 
+    /** Maintain a ref to this resource until we receive a GrGpuResourceFreedMessage. */
+    void insertCrossContextGpuResource(GrGpuResource* resource);
+
 #if GR_CACHE_STATS
     struct Stats {
         int fTotal;
@@ -241,6 +249,7 @@ private:
     /// @}
 
     void processInvalidUniqueKeys(const SkTArray<GrUniqueKeyInvalidatedMessage>&);
+    void processFreedGpuResources();
     void addToNonpurgeableArray(GrGpuResource*);
     void removeFromNonpurgeableArray(GrGpuResource*);
     bool overBudget() const { return fBudgetedBytes > fMaxBytes || fBudgetedCount > fMaxCount; }
@@ -287,6 +296,7 @@ private:
     }
 
     typedef SkMessageBus<GrUniqueKeyInvalidatedMessage>::Inbox InvalidUniqueKeyInbox;
+    typedef SkMessageBus<GrGpuResourceFreedMessage>::Inbox FreedGpuResourceInbox;
     typedef SkTDPQueue<GrGpuResource*, CompareTimestamp, AccessResourceIndex> PurgeableQueue;
     typedef SkTDArray<GrGpuResource*> ResourceArray;
 
@@ -326,6 +336,9 @@ private:
     uint32_t                            fExternalFlushCnt;
 
     InvalidUniqueKeyInbox               fInvalidUniqueKeyInbox;
+    FreedGpuResourceInbox               fFreedGpuResourceInbox;
+
+    uint32_t                            fContextUniqueID;
 
     // This resource is allowed to be in the nonpurgeable array for the sake of validate() because
     // we're in the midst of converting it to purgeable status.
index e842ddc..a2eabe4 100644 (file)
@@ -4476,3 +4476,11 @@ void GrGLGpu::waitSemaphore(sk_sp<GrSemaphore> semaphore) {
 void GrGLGpu::deleteSync(GrGLsync sync) const {
     GL_CALL(DeleteSync(sync));
 }
+
+sk_sp<GrSemaphore> GrGLGpu::prepareTextureForCrossContextUsage(GrTexture* texture) {
+    // Set up a semaphore to be signaled once the data is ready, and flush GL
+    sk_sp<GrSemaphore> semaphore = this->makeSemaphore();
+    this->insertSemaphore(semaphore, true);
+
+    return semaphore;
+}
index 04929f8..041ecfb 100644 (file)
@@ -149,6 +149,8 @@ public:
     void insertSemaphore(sk_sp<GrSemaphore> semaphore, bool flush) override;
     void waitSemaphore(sk_sp<GrSemaphore> semaphore) override;
 
+    sk_sp<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) override;
+
     void deleteSync(GrGLsync) const;
 
 private:
index 23c7094..9dd3688 100644 (file)
@@ -1695,6 +1695,11 @@ bool GrVkGpu::onCopySurface(GrSurface* dst,
         srcImage = static_cast<GrVkTexture*>(src->asTexture());
     }
 
+    // For borrowed textures, we *only* want to copy using draws (to avoid layout changes)
+    if (srcImage->isBorrowed()) {
+        return false;
+    }
+
     if (can_copy_image(dst, src, this)) {
         this->copySurfaceAsCopyImage(dst, src, dstImage, srcImage, srcRect, dstPoint);
         return true;
@@ -1990,3 +1995,17 @@ void GrVkGpu::waitSemaphore(sk_sp<GrSemaphore> semaphore) {
     resource->ref();
     fSemaphoresToWaitOn.push_back(resource);
 }
+
+sk_sp<GrSemaphore> GrVkGpu::prepareTextureForCrossContextUsage(GrTexture* texture) {
+    SkASSERT(texture);
+    GrVkTexture* vkTexture = static_cast<GrVkTexture*>(texture);
+    vkTexture->setImageLayout(this,
+                              VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
+                              VK_ACCESS_SHADER_READ_BIT,
+                              VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
+                              false);
+    this->submitCommandBuffer(kSkip_SyncQueue);
+
+    // The image layout change serves as a barrier, so no semaphore is needed
+    return nullptr;
+}
index 605c7af..3bedfd2 100644 (file)
@@ -137,6 +137,8 @@ public:
     void insertSemaphore(sk_sp<GrSemaphore> semaphore, bool flush) override;
     void waitSemaphore(sk_sp<GrSemaphore> semaphore) override;
 
+    sk_sp<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) override;
+
     void generateMipmap(GrVkTexture* tex);
 
     bool updateBuffer(GrVkBuffer* buffer, const void* src, VkDeviceSize offset, VkDeviceSize size);
index 336e468..57ab18a 100644 (file)
@@ -48,6 +48,7 @@ public:
     bool isLinearTiled() const {
         return SkToBool(VK_IMAGE_TILING_LINEAR == fInfo.fImageTiling);
     }
+    bool isBorrowed() const { return fIsBorrowed; }
 
     VkImageLayout currentLayout() const { return fInfo.fImageLayout; }
 
index 1fdd084..9bb98fb 100644 (file)
@@ -11,6 +11,7 @@
 
 #include "SkAutoPixmapStorage.h"
 #include "GrBackendSurface.h"
+#include "GrBackendTextureImageGenerator.h"
 #include "GrBitmapTextureMaker.h"
 #include "GrCaps.h"
 #include "GrContext.h"
@@ -461,6 +462,46 @@ sk_sp<SkImage> SkImage::makeTextureImage(GrContext* context, SkColorSpace* dstCo
     return nullptr;
 }
 
+sk_sp<SkImage> SkImage::MakeCrossContextFromEncoded(GrContext* context, sk_sp<SkData> encoded,
+                                                    bool buildMips, SkColorSpace* dstColorSpace) {
+    sk_sp<SkImage> codecImage = SkImage::MakeFromEncoded(std::move(encoded));
+    if (!codecImage) {
+        return nullptr;
+    }
+
+    // Some backends or drivers don't support (safely) moving resources between contexts
+    if (!context || !context->caps()->crossContextTextureSupport()) {
+        return codecImage;
+    }
+
+    // Turn the codec image into a GrTextureProxy
+    GrImageTextureMaker maker(context, codecImage.get(), kDisallow_CachingHint);
+    sk_sp<SkColorSpace> texColorSpace;
+    GrSamplerParams params(SkShader::kClamp_TileMode,
+                           buildMips ? GrSamplerParams::kMipMap_FilterMode
+                                     : GrSamplerParams::kBilerp_FilterMode);
+    sk_sp<GrTextureProxy> proxy(maker.refTextureProxyForParams(params, dstColorSpace,
+                                                               &texColorSpace, nullptr));
+    if (!proxy) {
+        return codecImage;
+    }
+
+    sk_sp<GrTexture> texture(sk_ref_sp(proxy->instantiate(context->resourceProvider())));
+    if (!texture) {
+        return codecImage;
+    }
+
+    // Flush any writes or uploads
+    context->contextPriv().prepareSurfaceForExternalIO(proxy.get());
+
+    sk_sp<GrSemaphore> sema = context->getGpu()->prepareTextureForCrossContextUsage(texture.get());
+
+    auto gen = GrBackendTextureImageGenerator::Make(std::move(texture), std::move(sema),
+                                                    codecImage->alphaType(),
+                                                    std::move(texColorSpace));
+    return SkImage::MakeFromGenerator(std::move(gen));
+}
+
 std::unique_ptr<SkCrossContextImageData> SkCrossContextImageData::MakeFromEncoded(
         GrContext* context, sk_sp<SkData> encoded, SkColorSpace* dstColorSpace) {
     sk_sp<SkImage> codecImage = SkImage::MakeFromEncoded(std::move(encoded));
index 2c4ba8f..c747b8e 100644 (file)
@@ -34,6 +34,7 @@
 #if SK_SUPPORT_GPU
 #include "GrContextPriv.h"
 #include "GrGpu.h"
+#include "GrResourceCache.h"
 #include "GrTest.h"
 #endif
 
@@ -806,6 +807,7 @@ struct TextureReleaseChecker {
         static_cast<TextureReleaseChecker*>(self)->fReleaseCount++;
     }
 };
+
 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTextureRelease, reporter, ctxInfo) {
     const int kWidth = 10;
     const int kHeight = 10;
@@ -854,6 +856,135 @@ DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTextureRelease, reporter, c
     ctxInfo.grContext()->getGpu()->deleteTestingOnlyBackendTexture(backendTexHandle);
 }
 
+DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_MakeCrossContextRelease, reporter, ctxInfo) {
+    GrContext* ctx = ctxInfo.grContext();
+
+    // If we don't have proper support for this feature, the factory will fallback to returning
+    // codec-backed images. Those will "work", but some of our checks will fail because we expect
+    // the cross-context images not to work on multiple contexts at once.
+    if (!ctx->caps()->crossContextTextureSupport()) {
+        return;
+    }
+
+    // We test three lifetime patterns for a single context:
+    // 1) Create image, free image
+    // 2) Create image, draw, flush, free image
+    // 3) Create image, draw, free image, flush
+    // ... and then repeat the last two patterns with drawing on a second* context:
+    // 4) Create image, draw*, flush*, free image
+    // 5) Create image, draw*, free iamge, flush*
+
+    sk_sp<SkData> data = GetResourceAsData("mandrill_128.png");
+    SkASSERT(data.get());
+
+    // Case #1: Create image, free image
+    {
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+        refImg.reset(nullptr); // force a release of the image
+    }
+
+    SkImageInfo info = SkImageInfo::MakeN32Premul(128, 128);
+    sk_sp<SkSurface> surface = SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info);
+    SkCanvas* canvas = surface->getCanvas();
+
+    // Case #2: Create image, draw, flush, free image
+    {
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+
+        canvas->drawImage(refImg, 0, 0);
+        canvas->flush();
+
+        refImg.reset(nullptr); // force a release of the image
+    }
+
+    // Case #3: Create image, draw, free image, flush
+    {
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+
+        canvas->drawImage(refImg, 0, 0);
+        refImg.reset(nullptr); // force a release of the image
+
+        canvas->flush();
+    }
+
+    // Configure second context
+    sk_gpu_test::TestContext* testContext = ctxInfo.testContext();
+
+    GrContextFactory otherFactory;
+    ContextInfo otherContextInfo = otherFactory.getContextInfo(pick_second_context_type(ctxInfo));
+    GrContext* otherCtx = otherContextInfo.grContext();
+    sk_gpu_test::TestContext* otherTestContext = otherContextInfo.testContext();
+
+    surface = SkSurface::MakeRenderTarget(otherCtx, SkBudgeted::kNo, info);
+    canvas = surface->getCanvas();
+
+    // Case #4: Create image, draw*, flush*, free image
+    {
+        testContext->makeCurrent();
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+
+        otherTestContext->makeCurrent();
+        canvas->drawImage(refImg, 0, 0);
+        canvas->flush();
+
+        testContext->makeCurrent();
+        refImg.reset(nullptr); // force a release of the image
+    }
+
+    // Case #5: Create image, draw*, free image, flush*
+    {
+        testContext->makeCurrent();
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+
+        otherTestContext->makeCurrent();
+        canvas->drawImage(refImg, 0, 0);
+
+        testContext->makeCurrent();
+        refImg.reset(nullptr); // force a release of the image
+
+        otherTestContext->makeCurrent();
+        canvas->flush();
+    }
+
+    // Case #6: Verify that only one context can be using the image at a time
+    {
+        testContext->makeCurrent();
+        sk_sp<SkImage> refImg(SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr));
+
+        // Any context should be able to borrow the texture at this point
+        sk_sp<SkColorSpace> texColorSpace;
+        sk_sp<GrTextureProxy> proxy = as_IB(refImg)->asTextureProxyRef(
+            ctx, GrSamplerParams::ClampNoFilter(), nullptr, &texColorSpace, nullptr);
+        REPORTER_ASSERT(reporter, proxy);
+
+        // But once it's borrowed, no other context should be able to borrow
+        otherTestContext->makeCurrent();
+        sk_sp<GrTextureProxy> otherProxy = as_IB(refImg)->asTextureProxyRef(
+            otherCtx, GrSamplerParams::ClampNoFilter(), nullptr, &texColorSpace, nullptr);
+        REPORTER_ASSERT(reporter, !otherProxy);
+
+        // Original context (that's already borrowing) should be okay
+        testContext->makeCurrent();
+        sk_sp<GrTextureProxy> proxySecondRef = as_IB(refImg)->asTextureProxyRef(
+            ctx, GrSamplerParams::ClampNoFilter(), nullptr, &texColorSpace, nullptr);
+        REPORTER_ASSERT(reporter, proxySecondRef);
+
+        // Releae all refs from the original context
+        proxy.reset(nullptr);
+        proxySecondRef.reset(nullptr);
+
+        // Now we should be able to borrow the texture from the other context
+        otherTestContext->makeCurrent();
+        otherProxy = as_IB(refImg)->asTextureProxyRef(
+            otherCtx, GrSamplerParams::ClampNoFilter(), nullptr, &texColorSpace, nullptr);
+        REPORTER_ASSERT(reporter, otherProxy);
+
+        // Release everything
+        otherProxy.reset(nullptr);
+        refImg.reset(nullptr);
+    }
+}
+
 static void check_images_same(skiatest::Reporter* reporter, const SkImage* a, const SkImage* b) {
     if (a->width() != b->width() || a->height() != b->height()) {
         ERRORF(reporter, "Images must have the same size");
index 6dc21bb..cd21e83 100644 (file)
@@ -337,6 +337,7 @@ public:
     sk_sp<GrSemaphore> SK_WARN_UNUSED_RESULT makeSemaphore() override { return nullptr; }
     void insertSemaphore(sk_sp<GrSemaphore> semaphore, bool flush) override {}
     void waitSemaphore(sk_sp<GrSemaphore> semaphore) override {}
+    sk_sp<GrSemaphore> prepareTextureForCrossContextUsage(GrTexture*) override { return nullptr; }
 
 private:
     void onResetContext(uint32_t resetBits) override {}