• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2012 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/image/SkImage_Gpu.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/gpu/GrBackendSurface.h"
12 #include "include/gpu/GrDirectContext.h"
13 #include "include/gpu/GrRecordingContext.h"
14 #include "include/gpu/GrYUVABackendTextures.h"
15 #include "include/private/SkImageInfoPriv.h"
16 #include "src/core/SkAutoPixmapStorage.h"
17 #include "src/core/SkBitmapCache.h"
18 #include "src/core/SkMipmap.h"
19 #include "src/core/SkScopeExit.h"
20 #include "src/core/SkTraceEvent.h"
21 #include "src/gpu/GrAHardwareBufferImageGenerator.h"
22 #include "src/gpu/GrAHardwareBufferUtils.h"
23 #include "src/gpu/GrBackendTextureImageGenerator.h"
24 #include "src/gpu/GrBackendUtils.h"
25 #include "src/gpu/GrCaps.h"
26 #include "src/gpu/GrColorSpaceXform.h"
27 #include "src/gpu/GrContextThreadSafeProxyPriv.h"
28 #include "src/gpu/GrDirectContextPriv.h"
29 #include "src/gpu/GrDrawingManager.h"
30 #include "src/gpu/GrGpu.h"
31 #include "src/gpu/GrImageContextPriv.h"
32 #include "src/gpu/GrImageInfo.h"
33 #include "src/gpu/GrProxyProvider.h"
34 #include "src/gpu/GrRecordingContextPriv.h"
35 #include "src/gpu/GrSemaphore.h"
36 #include "src/gpu/GrTexture.h"
37 #include "src/gpu/GrTextureProxy.h"
38 #include "src/gpu/GrTextureProxyPriv.h"
39 #include "src/gpu/GrYUVATextureProxies.h"
40 #include "src/gpu/SurfaceFillContext.h"
41 #include "src/gpu/effects/GrTextureEffect.h"
42 #include "src/gpu/gl/GrGLTexture.h"
43 
44 #include <cstddef>
45 #include <cstring>
46 #include <type_traits>
47 
ProxyChooser(sk_sp<GrSurfaceProxy> stableProxy)48 inline SkImage_Gpu::ProxyChooser::ProxyChooser(sk_sp<GrSurfaceProxy> stableProxy)
49         : fStableProxy(std::move(stableProxy)) {
50     SkASSERT(fStableProxy);
51 }
52 
ProxyChooser(sk_sp<GrSurfaceProxy> stableProxy,sk_sp<GrSurfaceProxy> volatileProxy,sk_sp<GrRenderTask> copyTask,int volatileProxyTargetCount)53 inline SkImage_Gpu::ProxyChooser::ProxyChooser(sk_sp<GrSurfaceProxy> stableProxy,
54                                                sk_sp<GrSurfaceProxy> volatileProxy,
55                                                sk_sp<GrRenderTask> copyTask,
56                                                int volatileProxyTargetCount)
57         : fStableProxy(std::move(stableProxy))
58         , fVolatileProxy(std::move(volatileProxy))
59         , fVolatileToStableCopyTask(std::move(copyTask))
60         , fVolatileProxyTargetCount(volatileProxyTargetCount) {
61     SkASSERT(fStableProxy);
62     SkASSERT(fVolatileProxy);
63     SkASSERT(fVolatileToStableCopyTask);
64 }
65 
~ProxyChooser()66 inline SkImage_Gpu::ProxyChooser::~ProxyChooser() {
67     // The image is being destroyed. If there is a stable copy proxy but we've been able to use
68     // the volatile proxy for all requests then we can skip the copy.
69     if (fVolatileToStableCopyTask) {
70         fVolatileToStableCopyTask->makeSkippable();
71     }
72 }
73 
chooseProxy(GrRecordingContext * context)74 inline sk_sp<GrSurfaceProxy> SkImage_Gpu::ProxyChooser::chooseProxy(GrRecordingContext* context) {
75     SkAutoSpinlock hold(fLock);
76     if (fVolatileProxy) {
77         SkASSERT(fVolatileProxyTargetCount <= fVolatileProxy->getTaskTargetCount());
78         // If this image is used off the direct context it originated on, i.e. on a recording-only
79         // context, we don't know how the recording context's actions are ordered WRT direct context
80         // actions until the recording context's DAG is imported into the direct context.
81         if (context->asDirectContext() &&
82             fVolatileProxyTargetCount == fVolatileProxy->getTaskTargetCount()) {
83             return fVolatileProxy;
84         }
85         fVolatileProxy.reset();
86         fVolatileToStableCopyTask.reset();
87         return fStableProxy;
88     }
89     return fStableProxy;
90 }
91 
switchToStableProxy()92 inline sk_sp<GrSurfaceProxy> SkImage_Gpu::ProxyChooser::switchToStableProxy() {
93     SkAutoSpinlock hold(fLock);
94     fVolatileProxy.reset();
95     fVolatileToStableCopyTask.reset();
96     return fStableProxy;
97 }
98 
makeVolatileProxyStable()99 inline sk_sp<GrSurfaceProxy> SkImage_Gpu::ProxyChooser::makeVolatileProxyStable() {
100     SkAutoSpinlock hold(fLock);
101     if (fVolatileProxy) {
102         fStableProxy = std::move(fVolatileProxy);
103         fVolatileToStableCopyTask->makeSkippable();
104         fVolatileToStableCopyTask.reset();
105     }
106     return fStableProxy;
107 }
108 
surfaceMustCopyOnWrite(GrSurfaceProxy * surfaceProxy) const109 inline bool SkImage_Gpu::ProxyChooser::surfaceMustCopyOnWrite(GrSurfaceProxy* surfaceProxy) const {
110     SkAutoSpinlock hold(fLock);
111     return surfaceProxy->underlyingUniqueID() == fStableProxy->underlyingUniqueID();
112 }
113 
gpuMemorySize() const114 inline size_t SkImage_Gpu::ProxyChooser::gpuMemorySize() const {
115     SkAutoSpinlock hold(fLock);
116     size_t size = fStableProxy->gpuMemorySize();
117     if (fVolatileProxy) {
118         SkASSERT(fVolatileProxy->gpuMemorySize() == size);
119     }
120     return size;
121 }
122 
mipmapped() const123 inline GrMipmapped SkImage_Gpu::ProxyChooser::mipmapped() const {
124     SkAutoSpinlock hold(fLock);
125     GrMipmapped mipmapped = fStableProxy->asTextureProxy()->mipmapped();
126     if (fVolatileProxy) {
127         SkASSERT(fVolatileProxy->asTextureProxy()->mipmapped() == mipmapped);
128     }
129     return mipmapped;
130 }
131 
132 #ifdef SK_DEBUG
backendFormat()133 inline GrBackendFormat SkImage_Gpu::ProxyChooser::backendFormat() {
134     SkAutoSpinlock hold(fLock);
135     if (fVolatileProxy) {
136         SkASSERT(fVolatileProxy->backendFormat() == fStableProxy->backendFormat());
137     }
138     return fStableProxy->backendFormat();
139 }
140 #endif
141 
142 //////////////////////////////////////////////////////////////////////////////
143 
SkImage_Gpu(sk_sp<GrImageContext> context,uint32_t uniqueID,GrSurfaceProxyView view,SkColorInfo info)144 SkImage_Gpu::SkImage_Gpu(sk_sp<GrImageContext> context,
145                          uint32_t uniqueID,
146                          GrSurfaceProxyView view,
147                          SkColorInfo info)
148         : INHERITED(std::move(context),
149                     SkImageInfo::Make(view.proxy()->backingStoreDimensions(), std::move(info)),
150                     uniqueID)
151         , fChooser(view.detachProxy())
152         , fSwizzle(view.swizzle())
153         , fOrigin(view.origin()) {
154 #ifdef SK_DEBUG
155     const GrBackendFormat& format = fChooser.backendFormat();
156     const GrCaps* caps = this->context()->priv().caps();
157     GrColorType grCT = SkColorTypeToGrColorType(this->colorType());
158     SkASSERT(caps->isFormatCompressed(format) ||
159              caps->areColorTypeAndFormatCompatible(grCT, format));
160 #endif
161 }
162 
SkImage_Gpu(sk_sp<GrDirectContext> dContext,GrSurfaceProxyView volatileSrc,sk_sp<GrSurfaceProxy> stableCopy,sk_sp<GrRenderTask> copyTask,int volatileSrcTargetCount,SkColorInfo info)163 SkImage_Gpu::SkImage_Gpu(sk_sp<GrDirectContext> dContext,
164                          GrSurfaceProxyView volatileSrc,
165                          sk_sp<GrSurfaceProxy> stableCopy,
166                          sk_sp<GrRenderTask> copyTask,
167                          int volatileSrcTargetCount,
168                          SkColorInfo info)
169         : INHERITED(std::move(dContext),
170                     SkImageInfo::Make(volatileSrc.proxy()->backingStoreDimensions(),
171                                       std::move(info)),
172                     kNeedNewImageUniqueID)
173         , fChooser(std::move(stableCopy),
174                    volatileSrc.detachProxy(),
175                    std::move(copyTask),
176                    volatileSrcTargetCount)
177         , fSwizzle(volatileSrc.swizzle())
178         , fOrigin(volatileSrc.origin()) {
179 #ifdef SK_DEBUG
180     const GrBackendFormat& format = fChooser.backendFormat();
181     const GrCaps* caps = this->context()->priv().caps();
182     GrColorType grCT = SkColorTypeToGrColorType(this->colorType());
183     SkASSERT(caps->isFormatCompressed(format) ||
184              caps->areColorTypeAndFormatCompatible(grCT, format));
185 #endif
186 }
187 
MakeWithVolatileSrc(sk_sp<GrRecordingContext> rContext,GrSurfaceProxyView volatileSrc,SkColorInfo colorInfo)188 sk_sp<SkImage> SkImage_Gpu::MakeWithVolatileSrc(sk_sp<GrRecordingContext> rContext,
189                                                 GrSurfaceProxyView volatileSrc,
190                                                 SkColorInfo colorInfo) {
191     SkASSERT(rContext);
192     SkASSERT(volatileSrc);
193     SkASSERT(volatileSrc.proxy()->asTextureProxy());
194     GrMipmapped mm = volatileSrc.proxy()->asTextureProxy()->mipmapped();
195     sk_sp<GrRenderTask> copyTask;
196     auto copy = GrSurfaceProxy::Copy(rContext.get(),
197                                      volatileSrc.refProxy(),
198                                      volatileSrc.origin(),
199                                      mm,
200                                      SkBackingFit::kExact,
201                                      SkBudgeted::kYes,
202                                      &copyTask);
203     if (!copy) {
204         return nullptr;
205     }
206     // We only attempt to make a dual-proxy image on a direct context. This optimziation requires
207     // knowing how things are ordered and recording-only contexts are not well ordered WRT other
208     // recording contexts.
209     if (auto direct = sk_ref_sp(rContext->asDirectContext())) {
210         int targetCount = volatileSrc.proxy()->getTaskTargetCount();
211         return sk_sp<SkImage>(new SkImage_Gpu(std::move(direct),
212                                               std::move(volatileSrc),
213                                               std::move(copy),
214                                               std::move(copyTask),
215                                               targetCount,
216                                               std::move(colorInfo)));
217     }
218     GrSurfaceProxyView copyView(std::move(copy), volatileSrc.origin(), volatileSrc.swizzle());
219     return sk_make_sp<SkImage_Gpu>(std::move(rContext),
220                                    kNeedNewImageUniqueID,
221                                    std::move(copyView),
222                                    std::move(colorInfo));
223 }
224 
225 SkImage_Gpu::~SkImage_Gpu() = default;
226 
surfaceMustCopyOnWrite(GrSurfaceProxy * surfaceProxy) const227 bool SkImage_Gpu::surfaceMustCopyOnWrite(GrSurfaceProxy* surfaceProxy) const {
228     return fChooser.surfaceMustCopyOnWrite(surfaceProxy);
229 }
230 
onHasMipmaps() const231 bool SkImage_Gpu::onHasMipmaps() const { return fChooser.mipmapped() == GrMipmapped::kYes; }
232 
onFlush(GrDirectContext * dContext,const GrFlushInfo & info) const233 GrSemaphoresSubmitted SkImage_Gpu::onFlush(GrDirectContext* dContext,
234                                            const GrFlushInfo& info) const {
235     if (!fContext->priv().matches(dContext) || dContext->abandoned()) {
236         if (info.fSubmittedProc) {
237             info.fSubmittedProc(info.fSubmittedContext, false);
238         }
239         if (info.fFinishedProc) {
240             info.fFinishedProc(info.fFinishedContext);
241         }
242         return GrSemaphoresSubmitted::kNo;
243     }
244 
245     sk_sp<GrSurfaceProxy> proxy = fChooser.chooseProxy(dContext);
246     return dContext->priv().flushSurface(proxy.get(),
247                                          SkSurface::BackendSurfaceAccess::kNoAccess,
248                                          info);
249 }
250 
onGetBackendTexture(bool flushPendingGrContextIO,GrSurfaceOrigin * origin) const251 GrBackendTexture SkImage_Gpu::onGetBackendTexture(bool flushPendingGrContextIO,
252                                                   GrSurfaceOrigin* origin) const {
253     auto direct = fContext->asDirectContext();
254     if (!direct) {
255         // This image was created with a DDL context and cannot be instantiated.
256         return GrBackendTexture();  // invalid
257     }
258     if (direct->abandoned()) {
259         return GrBackendTexture();  // invalid;
260     }
261 
262     // We don't know how client's use of the texture will be ordered WRT Skia's. Ensure the
263     // texture seen by the client won't be mutated by a SkSurface.
264     sk_sp<GrSurfaceProxy> proxy = fChooser.switchToStableProxy();
265 
266     if (!proxy->isInstantiated()) {
267         auto resourceProvider = direct->priv().resourceProvider();
268 
269         if (!proxy->instantiate(resourceProvider)) {
270             return GrBackendTexture();  // invalid
271         }
272     }
273 
274     GrTexture* texture = proxy->peekTexture();
275     if (texture) {
276         if (flushPendingGrContextIO) {
277             direct->priv().flushSurface(proxy.get());
278         }
279         if (origin) {
280             *origin = fOrigin;
281         }
282         return texture->getBackendTexture();
283     }
284     return GrBackendTexture();  // invalid
285 }
286 
onTextureSize() const287 size_t SkImage_Gpu::onTextureSize() const { return fChooser.gpuMemorySize(); }
288 
onMakeColorTypeAndColorSpace(SkColorType targetCT,sk_sp<SkColorSpace> targetCS,GrDirectContext * dContext) const289 sk_sp<SkImage> SkImage_Gpu::onMakeColorTypeAndColorSpace(SkColorType targetCT,
290                                                          sk_sp<SkColorSpace> targetCS,
291                                                          GrDirectContext* dContext) const {
292     SkColorInfo info(targetCT, this->alphaType(), std::move(targetCS));
293     if (!fContext->priv().matches(dContext)) {
294         return nullptr;
295     }
296 
297     auto sfc = dContext->priv().makeSFCWithFallback(GrImageInfo(info, this->dimensions()),
298                                                     SkBackingFit::kExact);
299     if (!sfc) {
300         return nullptr;
301     }
302     // We respecify info's CT because we called MakeWithFallback.
303     auto ct = GrColorTypeToSkColorType(sfc->colorInfo().colorType());
304     info = info.makeColorType(ct);
305 
306     // Draw this image's texture into the SFC.
307     auto [view, _] = this->asView(dContext, GrMipmapped(this->hasMipmaps()));
308     auto texFP = GrTextureEffect::Make(std::move(view), this->alphaType());
309     auto colorFP = GrColorSpaceXformEffect::Make(std::move(texFP),
310                                                  this->imageInfo().colorInfo(),
311                                                  info);
312     sfc->fillWithFP(std::move(colorFP));
313 
314     return sk_make_sp<SkImage_Gpu>(sk_ref_sp(dContext),
315                                    kNeedNewImageUniqueID,
316                                    sfc->readSurfaceView(),
317                                    std::move(info));
318 }
319 
onReinterpretColorSpace(sk_sp<SkColorSpace> newCS) const320 sk_sp<SkImage> SkImage_Gpu::onReinterpretColorSpace(sk_sp<SkColorSpace> newCS) const {
321     // It doesn't seem worth the complexity of trying to share the ProxyChooser among multiple
322     // images. Just fall back to the stable copy.
323     GrSurfaceProxyView view(fChooser.switchToStableProxy(), fOrigin, fSwizzle);
324     return sk_make_sp<SkImage_Gpu>(fContext,
325                                    kNeedNewImageUniqueID,
326                                    std::move(view),
327                                    this->imageInfo().colorInfo().makeColorSpace(std::move(newCS)));
328 }
329 
onAsyncRescaleAndReadPixels(const SkImageInfo & info,const SkIRect & srcRect,RescaleGamma rescaleGamma,RescaleMode rescaleMode,ReadPixelsCallback callback,ReadPixelsContext context) const330 void SkImage_Gpu::onAsyncRescaleAndReadPixels(const SkImageInfo& info,
331                                               const SkIRect& srcRect,
332                                               RescaleGamma rescaleGamma,
333                                               RescaleMode rescaleMode,
334                                               ReadPixelsCallback callback,
335                                               ReadPixelsContext context) const {
336     auto dContext = fContext->asDirectContext();
337     if (!dContext) {
338         // DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
339         callback(context, nullptr);
340         return;
341     }
342     auto ctx = dContext->priv().makeSC(this->makeView(dContext), this->imageInfo().colorInfo());
343     if (!ctx) {
344         callback(context, nullptr);
345         return;
346     }
347     ctx->asyncRescaleAndReadPixels(dContext, info, srcRect, rescaleGamma, rescaleMode,
348                                    callback, context);
349 }
350 
onAsyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace,sk_sp<SkColorSpace> dstColorSpace,const SkIRect & srcRect,const SkISize & dstSize,RescaleGamma rescaleGamma,RescaleMode rescaleMode,ReadPixelsCallback callback,ReadPixelsContext context) const351 void SkImage_Gpu::onAsyncRescaleAndReadPixelsYUV420(SkYUVColorSpace yuvColorSpace,
352                                                     sk_sp<SkColorSpace> dstColorSpace,
353                                                     const SkIRect& srcRect,
354                                                     const SkISize& dstSize,
355                                                     RescaleGamma rescaleGamma,
356                                                     RescaleMode rescaleMode,
357                                                     ReadPixelsCallback callback,
358                                                     ReadPixelsContext context) const {
359     auto dContext = fContext->asDirectContext();
360     if (!dContext) {
361         // DDL TODO: buffer up the readback so it occurs when the DDL is drawn?
362         callback(context, nullptr);
363         return;
364     }
365     auto ctx = dContext->priv().makeSC(this->makeView(dContext), this->imageInfo().colorInfo());
366     if (!ctx) {
367         callback(context, nullptr);
368         return;
369     }
370     ctx->asyncRescaleAndReadPixelsYUV420(dContext,
371                                          yuvColorSpace,
372                                          std::move(dstColorSpace),
373                                          srcRect,
374                                          dstSize,
375                                          rescaleGamma,
376                                          rescaleMode,
377                                          callback,
378                                          context);
379 }
380 
generatingSurfaceIsDeleted()381 void SkImage_Gpu::generatingSurfaceIsDeleted() { fChooser.makeVolatileProxyStable(); }
382 
383 ///////////////////////////////////////////////////////////////////////////////////////////////////
384 
new_wrapped_texture_common(GrRecordingContext * rContext,const GrBackendTexture & backendTex,GrColorType colorType,GrSurfaceOrigin origin,SkAlphaType at,sk_sp<SkColorSpace> colorSpace,GrWrapOwnership ownership,sk_sp<GrRefCntedCallback> releaseHelper)385 static sk_sp<SkImage> new_wrapped_texture_common(GrRecordingContext* rContext,
386                                                  const GrBackendTexture& backendTex,
387                                                  GrColorType colorType,
388                                                  GrSurfaceOrigin origin,
389                                                  SkAlphaType at,
390                                                  sk_sp<SkColorSpace> colorSpace,
391                                                  GrWrapOwnership ownership,
392                                                  sk_sp<GrRefCntedCallback> releaseHelper) {
393     if (!backendTex.isValid() || backendTex.width() <= 0 || backendTex.height() <= 0) {
394         return nullptr;
395     }
396 
397     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
398     sk_sp<GrTextureProxy> proxy = proxyProvider->wrapBackendTexture(
399             backendTex, ownership, GrWrapCacheable::kNo, kRead_GrIOType, std::move(releaseHelper));
400     if (!proxy) {
401         return nullptr;
402     }
403 
404     skgpu::Swizzle swizzle = rContext->priv().caps()->getReadSwizzle(proxy->backendFormat(),
405                                                                      colorType);
406     GrSurfaceProxyView view(std::move(proxy), origin, swizzle);
407     SkColorInfo info(GrColorTypeToSkColorType(colorType), at, std::move(colorSpace));
408     return sk_make_sp<SkImage_Gpu>(sk_ref_sp(rContext),
409                                    kNeedNewImageUniqueID,
410                                    std::move(view),
411                                    std::move(info));
412 }
413 
MakeFromCompressedTexture(GrRecordingContext * rContext,const GrBackendTexture & tex,GrSurfaceOrigin origin,SkAlphaType at,sk_sp<SkColorSpace> cs,TextureReleaseProc releaseP,ReleaseContext releaseC)414 sk_sp<SkImage> SkImage::MakeFromCompressedTexture(GrRecordingContext* rContext,
415                                                   const GrBackendTexture& tex,
416                                                   GrSurfaceOrigin origin,
417                                                   SkAlphaType at,
418                                                   sk_sp<SkColorSpace> cs,
419                                                   TextureReleaseProc releaseP,
420                                                   ReleaseContext releaseC) {
421     auto releaseHelper = GrRefCntedCallback::Make(releaseP, releaseC);
422 
423     if (!rContext) {
424         return nullptr;
425     }
426 
427     const GrCaps* caps = rContext->priv().caps();
428 
429     if (!SkImage_GpuBase::ValidateCompressedBackendTexture(caps, tex, at)) {
430         return nullptr;
431     }
432 
433     GrProxyProvider* proxyProvider = rContext->priv().proxyProvider();
434     sk_sp<GrTextureProxy> proxy = proxyProvider->wrapCompressedBackendTexture(
435             tex, kBorrow_GrWrapOwnership, GrWrapCacheable::kNo, std::move(releaseHelper));
436     if (!proxy) {
437         return nullptr;
438     }
439 
440     CompressionType type = GrBackendFormatToCompressionType(tex.getBackendFormat());
441     SkColorType ct = GrCompressionTypeToSkColorType(type);
442 
443     GrSurfaceProxyView view(std::move(proxy), origin, skgpu::Swizzle::RGBA());
444     return sk_make_sp<SkImage_Gpu>(sk_ref_sp(rContext),
445                                    kNeedNewImageUniqueID,
446                                    std::move(view),
447                                    SkColorInfo(ct, at, std::move(cs)));
448 }
449 
MakeFromTexture(GrRecordingContext * rContext,const GrBackendTexture & tex,GrSurfaceOrigin origin,SkColorType ct,SkAlphaType at,sk_sp<SkColorSpace> cs,TextureReleaseProc releaseP,ReleaseContext releaseC)450 sk_sp<SkImage> SkImage::MakeFromTexture(GrRecordingContext* rContext,
451                                         const GrBackendTexture& tex, GrSurfaceOrigin origin,
452                                         SkColorType ct, SkAlphaType at, sk_sp<SkColorSpace> cs,
453                                         TextureReleaseProc releaseP, ReleaseContext releaseC) {
454     auto releaseHelper = GrRefCntedCallback::Make(releaseP, releaseC);
455 
456     if (!rContext) {
457         return nullptr;
458     }
459 
460     const GrCaps* caps = rContext->priv().caps();
461 
462     GrColorType grColorType = SkColorTypeToGrColorType(ct);
463     if (GrColorType::kUnknown == grColorType) {
464         return nullptr;
465     }
466 
467     if (!SkImage_GpuBase::ValidateBackendTexture(caps, tex, grColorType, ct, at, cs)) {
468         return nullptr;
469     }
470 
471     return new_wrapped_texture_common(rContext, tex, grColorType, origin, at, std::move(cs),
472                                       kBorrow_GrWrapOwnership, std::move(releaseHelper));
473 }
474 
MakeFromAdoptedTexture(GrRecordingContext * rContext,const GrBackendTexture & tex,GrSurfaceOrigin origin,SkColorType ct,SkAlphaType at,sk_sp<SkColorSpace> cs)475 sk_sp<SkImage> SkImage::MakeFromAdoptedTexture(GrRecordingContext* rContext,
476                                                const GrBackendTexture& tex, GrSurfaceOrigin origin,
477                                                SkColorType ct, SkAlphaType at,
478                                                sk_sp<SkColorSpace> cs) {
479     auto dContext = GrAsDirectContext(rContext);
480     if (!dContext) {
481         // We have a DDL context and we don't support adopted textures for them.
482         return nullptr;
483     }
484 
485     const GrCaps* caps = dContext->priv().caps();
486 
487     GrColorType grColorType = SkColorTypeToGrColorType(ct);
488     if (GrColorType::kUnknown == grColorType) {
489         return nullptr;
490     }
491 
492     if (!SkImage_GpuBase::ValidateBackendTexture(caps, tex, grColorType, ct, at, cs)) {
493         return nullptr;
494     }
495 
496     return new_wrapped_texture_common(dContext, tex, grColorType, origin, at, std::move(cs),
497                                       kAdopt_GrWrapOwnership, nullptr);
498 }
499 
MakeTextureFromCompressed(GrDirectContext * direct,sk_sp<SkData> data,int width,int height,CompressionType type,GrMipmapped mipMapped,GrProtected isProtected)500 sk_sp<SkImage> SkImage::MakeTextureFromCompressed(GrDirectContext* direct, sk_sp<SkData> data,
501                                                   int width, int height, CompressionType type,
502                                                   GrMipmapped mipMapped,
503                                                   GrProtected isProtected) {
504     if (!direct || !data) {
505         return nullptr;
506     }
507 
508     GrBackendFormat beFormat = direct->compressedBackendFormat(type);
509     if (!beFormat.isValid()) {
510         sk_sp<SkImage> tmp = MakeRasterFromCompressed(std::move(data), width, height, type);
511         if (!tmp) {
512             return nullptr;
513         }
514         return tmp->makeTextureImage(direct, mipMapped);
515     }
516 
517     GrProxyProvider* proxyProvider = direct->priv().proxyProvider();
518     sk_sp<GrTextureProxy> proxy = proxyProvider->createCompressedTextureProxy(
519             {width, height}, SkBudgeted::kYes, mipMapped, isProtected, type, std::move(data));
520     if (!proxy) {
521         return nullptr;
522     }
523     GrSurfaceProxyView view(std::move(proxy));
524 
525     SkColorType colorType = GrCompressionTypeToSkColorType(type);
526 
527     return sk_make_sp<SkImage_Gpu>(sk_ref_sp(direct),
528                                    kNeedNewImageUniqueID,
529                                    std::move(view),
530                                    SkColorInfo(colorType, kOpaque_SkAlphaType, nullptr));
531 }
532 
makeTextureImage(GrDirectContext * dContext,GrMipmapped mipmapped,SkBudgeted budgeted) const533 sk_sp<SkImage> SkImage::makeTextureImage(GrDirectContext* dContext,
534                                          GrMipmapped mipmapped,
535                                          SkBudgeted budgeted) const {
536     if (!dContext) {
537         return nullptr;
538     }
539     if (!dContext->priv().caps()->mipmapSupport() || this->dimensions().area() <= 1) {
540         mipmapped = GrMipmapped::kNo;
541     }
542 
543     if (this->isTextureBacked()) {
544         if (!as_IB(this)->context()->priv().matches(dContext)) {
545             return nullptr;
546         }
547 
548         if (this->isTextureBacked() && (mipmapped == GrMipmapped::kNo || this->hasMipmaps())) {
549             return sk_ref_sp(const_cast<SkImage*>(this));
550         }
551     }
552     GrImageTexGenPolicy policy = budgeted == SkBudgeted::kYes
553                                          ? GrImageTexGenPolicy::kNew_Uncached_Budgeted
554                                          : GrImageTexGenPolicy::kNew_Uncached_Unbudgeted;
555     // TODO: Don't flatten YUVA images here. Add mips to the planes instead.
556     auto [view, ct] = as_IB(this)->asView(dContext, mipmapped, policy);
557     if (!view) {
558         return nullptr;
559     }
560     SkASSERT(view.asTextureProxy());
561     SkASSERT(mipmapped == GrMipmapped::kNo ||
562              view.asTextureProxy()->mipmapped() == GrMipmapped::kYes);
563     SkColorInfo colorInfo(GrColorTypeToSkColorType(ct), this->alphaType(), this->refColorSpace());
564     return sk_make_sp<SkImage_Gpu>(sk_ref_sp(dContext),
565                                    this->uniqueID(),
566                                    std::move(view),
567                                    std::move(colorInfo));
568 }
569 
570 ///////////////////////////////////////////////////////////////////////////////////////////////////
571 
MakePromiseTexture(sk_sp<GrContextThreadSafeProxy> threadSafeProxy,const GrBackendFormat & backendFormat,SkISize dimensions,GrMipmapped mipMapped,GrSurfaceOrigin origin,SkColorType colorType,SkAlphaType alphaType,sk_sp<SkColorSpace> colorSpace,PromiseImageTextureFulfillProc textureFulfillProc,PromiseImageTextureReleaseProc textureReleaseProc,PromiseImageTextureContext textureContext)572 sk_sp<SkImage> SkImage::MakePromiseTexture(sk_sp<GrContextThreadSafeProxy> threadSafeProxy,
573                                            const GrBackendFormat& backendFormat,
574                                            SkISize dimensions,
575                                            GrMipmapped mipMapped,
576                                            GrSurfaceOrigin origin,
577                                            SkColorType colorType,
578                                            SkAlphaType alphaType,
579                                            sk_sp<SkColorSpace> colorSpace,
580                                            PromiseImageTextureFulfillProc textureFulfillProc,
581                                            PromiseImageTextureReleaseProc textureReleaseProc,
582                                            PromiseImageTextureContext textureContext) {
583     // Our contract is that we will always call the release proc even on failure.
584     // We use the helper to convey the context, so we need to ensure make doesn't fail.
585     textureReleaseProc = textureReleaseProc ? textureReleaseProc : [](void*) {};
586     auto releaseHelper = GrRefCntedCallback::Make(textureReleaseProc, textureContext);
587     SkImageInfo info = SkImageInfo::Make(dimensions, colorType, alphaType, colorSpace);
588     if (!SkImageInfoIsValid(info)) {
589         return nullptr;
590     }
591 
592     if (!threadSafeProxy) {
593         return nullptr;
594     }
595 
596     if (dimensions.isEmpty()) {
597         return nullptr;
598     }
599 
600     GrColorType grColorType = SkColorTypeToGrColorType(colorType);
601     if (GrColorType::kUnknown == grColorType) {
602         return nullptr;
603     }
604 
605     if (!threadSafeProxy->priv().caps()->areColorTypeAndFormatCompatible(grColorType,
606                                                                          backendFormat)) {
607         return nullptr;
608     }
609 
610     auto proxy = SkImage_GpuBase::MakePromiseImageLazyProxy(threadSafeProxy.get(),
611                                                             dimensions,
612                                                             backendFormat,
613                                                             mipMapped,
614                                                             textureFulfillProc,
615                                                             std::move(releaseHelper));
616     if (!proxy) {
617         return nullptr;
618     }
619     skgpu::Swizzle swizzle = threadSafeProxy->priv().caps()->getReadSwizzle(backendFormat,
620                                                                             grColorType);
621     GrSurfaceProxyView view(std::move(proxy), origin, swizzle);
622     sk_sp<GrImageContext> ctx(GrImageContextPriv::MakeForPromiseImage(std::move(threadSafeProxy)));
623     return sk_make_sp<SkImage_Gpu>(std::move(ctx),
624                                    kNeedNewImageUniqueID,
625                                    std::move(view),
626                                    SkColorInfo(colorType, alphaType, std::move(colorSpace)));
627 }
628 
629 ///////////////////////////////////////////////////////////////////////////////////////////////////
630 
MakeCrossContextFromPixmap(GrDirectContext * dContext,const SkPixmap & originalPixmap,bool buildMips,bool limitToMaxTextureSize)631 sk_sp<SkImage> SkImage::MakeCrossContextFromPixmap(GrDirectContext* dContext,
632                                                    const SkPixmap& originalPixmap, bool buildMips,
633                                                    bool limitToMaxTextureSize) {
634     // Some backends or drivers don't support (safely) moving resources between contexts
635     if (!dContext || !dContext->priv().caps()->crossContextTextureSupport()) {
636         return SkImage::MakeRasterCopy(originalPixmap);
637     }
638 
639     // If non-power-of-two mipmapping isn't supported, ignore the client's request
640     if (!dContext->priv().caps()->mipmapSupport()) {
641         buildMips = false;
642     }
643 
644     const SkPixmap* pixmap = &originalPixmap;
645     SkAutoPixmapStorage resized;
646     int maxTextureSize = dContext->priv().caps()->maxTextureSize();
647     int maxDim = std::max(originalPixmap.width(), originalPixmap.height());
648     if (limitToMaxTextureSize && maxDim > maxTextureSize) {
649         float scale = static_cast<float>(maxTextureSize) / maxDim;
650         int newWidth = std::min(static_cast<int>(originalPixmap.width() * scale), maxTextureSize);
651         int newHeight = std::min(static_cast<int>(originalPixmap.height() * scale), maxTextureSize);
652         SkImageInfo info = originalPixmap.info().makeWH(newWidth, newHeight);
653         SkSamplingOptions sampling(SkFilterMode::kLinear);
654         if (!resized.tryAlloc(info) || !originalPixmap.scalePixels(resized, sampling)) {
655             return nullptr;
656         }
657         pixmap = &resized;
658     }
659     // Turn the pixmap into a GrTextureProxy
660     SkBitmap bmp;
661     bmp.installPixels(*pixmap);
662     GrMipmapped mipmapped = buildMips ? GrMipmapped::kYes : GrMipmapped::kNo;
663     auto [view, ct] = GrMakeUncachedBitmapProxyView(dContext, bmp, mipmapped);
664     if (!view) {
665         return SkImage::MakeRasterCopy(*pixmap);
666     }
667 
668     sk_sp<GrTexture> texture = sk_ref_sp(view.proxy()->peekTexture());
669 
670     // Flush any writes or uploads
671     dContext->priv().flushSurface(view.proxy());
672     GrGpu* gpu = dContext->priv().getGpu();
673 
674     std::unique_ptr<GrSemaphore> sema = gpu->prepareTextureForCrossContextUsage(texture.get());
675 
676     SkColorType skCT = GrColorTypeToSkColorType(ct);
677     auto gen = GrBackendTextureImageGenerator::Make(std::move(texture), view.origin(),
678                                                     std::move(sema), skCT,
679                                                     pixmap->alphaType(),
680                                                     pixmap->info().refColorSpace());
681     return SkImage::MakeFromGenerator(std::move(gen));
682 }
683 
684 #if defined(SK_BUILD_FOR_ANDROID) && __ANDROID_API__ >= 26
MakeFromAHardwareBuffer(AHardwareBuffer * graphicBuffer,SkAlphaType at,sk_sp<SkColorSpace> cs,GrSurfaceOrigin surfaceOrigin)685 sk_sp<SkImage> SkImage::MakeFromAHardwareBuffer(AHardwareBuffer* graphicBuffer, SkAlphaType at,
686                                                 sk_sp<SkColorSpace> cs,
687                                                 GrSurfaceOrigin surfaceOrigin) {
688     auto gen = GrAHardwareBufferImageGenerator::Make(graphicBuffer, at, cs, surfaceOrigin);
689     return SkImage::MakeFromGenerator(std::move(gen));
690 }
691 
MakeFromAHardwareBufferWithData(GrDirectContext * dContext,const SkPixmap & pixmap,AHardwareBuffer * hardwareBuffer,GrSurfaceOrigin surfaceOrigin)692 sk_sp<SkImage> SkImage::MakeFromAHardwareBufferWithData(GrDirectContext* dContext,
693                                                         const SkPixmap& pixmap,
694                                                         AHardwareBuffer* hardwareBuffer,
695                                                         GrSurfaceOrigin surfaceOrigin) {
696     AHardwareBuffer_Desc bufferDesc;
697     AHardwareBuffer_describe(hardwareBuffer, &bufferDesc);
698 
699     if (!SkToBool(bufferDesc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) {
700         return nullptr;
701     }
702 
703 
704     GrBackendFormat backendFormat = GrAHardwareBufferUtils::GetBackendFormat(dContext,
705                                                                              hardwareBuffer,
706                                                                              bufferDesc.format,
707                                                                              true);
708 
709     if (!backendFormat.isValid()) {
710         return nullptr;
711     }
712 
713     GrAHardwareBufferUtils::DeleteImageProc deleteImageProc = nullptr;
714     GrAHardwareBufferUtils::UpdateImageProc updateImageProc = nullptr;
715     GrAHardwareBufferUtils::TexImageCtx deleteImageCtx = nullptr;
716 
717     const bool isRenderable = SkToBool(bufferDesc.usage & AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER);
718 
719     GrBackendTexture backendTexture =
720             GrAHardwareBufferUtils::MakeBackendTexture(dContext, hardwareBuffer,
721                                                        bufferDesc.width, bufferDesc.height,
722                                                        &deleteImageProc, &updateImageProc,
723                                                        &deleteImageCtx, false, backendFormat,
724                                                        isRenderable);
725     if (!backendTexture.isValid()) {
726         return nullptr;
727     }
728     SkASSERT(deleteImageProc);
729 
730     auto releaseHelper = GrRefCntedCallback::Make(deleteImageProc, deleteImageCtx);
731 
732     SkColorType colorType =
733             GrAHardwareBufferUtils::GetSkColorTypeFromBufferFormat(bufferDesc.format);
734 
735     GrColorType grColorType = SkColorTypeToGrColorType(colorType);
736 
737     GrProxyProvider* proxyProvider = dContext->priv().proxyProvider();
738     if (!proxyProvider) {
739         return nullptr;
740     }
741 
742     sk_sp<GrTextureProxy> proxy = proxyProvider->wrapBackendTexture(
743             backendTexture, kBorrow_GrWrapOwnership, GrWrapCacheable::kNo, kRW_GrIOType,
744             std::move(releaseHelper));
745     if (!proxy) {
746         return nullptr;
747     }
748 
749     skgpu::Swizzle swizzle = dContext->priv().caps()->getReadSwizzle(backendFormat, grColorType);
750     GrSurfaceProxyView framebufferView(std::move(proxy), surfaceOrigin, swizzle);
751     SkColorInfo colorInfo = pixmap.info().colorInfo().makeColorType(colorType);
752     sk_sp<SkImage> image = sk_make_sp<SkImage_Gpu>(sk_ref_sp(dContext),
753                                                    kNeedNewImageUniqueID,
754                                                    framebufferView,
755                                                    std::move(colorInfo));
756     if (!image) {
757         return nullptr;
758     }
759 
760     GrDrawingManager* drawingManager = dContext->priv().drawingManager();
761     if (!drawingManager) {
762         return nullptr;
763     }
764 
765     skgpu::SurfaceContext surfaceContext(
766             dContext, std::move(framebufferView),image->imageInfo().colorInfo());
767 
768     surfaceContext.writePixels(dContext, pixmap, {0, 0});
769 
770     GrSurfaceProxy* p[1] = {surfaceContext.asSurfaceProxy()};
771     drawingManager->flush(SkMakeSpan(p), SkSurface::BackendSurfaceAccess::kNoAccess, {}, nullptr);
772 
773     return image;
774 }
775 #endif
776 
777 ///////////////////////////////////////////////////////////////////////////////////////////////////
778 
MakeBackendTextureFromSkImage(GrDirectContext * direct,sk_sp<SkImage> image,GrBackendTexture * backendTexture,BackendTextureReleaseProc * releaseProc)779 bool SkImage::MakeBackendTextureFromSkImage(GrDirectContext* direct,
780                                             sk_sp<SkImage> image,
781                                             GrBackendTexture* backendTexture,
782                                             BackendTextureReleaseProc* releaseProc) {
783     if (!image || !backendTexture || !releaseProc) {
784         return false;
785     }
786 
787     auto [view, ct] = as_IB(image)->asView(direct, GrMipmapped::kNo);
788 
789     if (!view) {
790         return false;
791     }
792 
793     // Flush any pending IO on the texture.
794     direct->priv().flushSurface(view.proxy());
795 
796     GrTexture* texture = view.asTextureProxy()->peekTexture();
797     if (!texture) {
798         return false;
799     }
800     // We must make a copy of the image if the image is not unique, if the GrTexture owned by the
801     // image is not unique, or if the texture wraps an external object.
802     if (!image->unique() || !texture->unique() ||
803         texture->resourcePriv().refsWrappedObjects()) {
804         // onMakeSubset will always copy the image.
805         image = as_IB(image)->onMakeSubset(image->bounds(), direct);
806         if (!image) {
807             return false;
808         }
809         return MakeBackendTextureFromSkImage(direct, std::move(image), backendTexture, releaseProc);
810     }
811 
812     SkASSERT(!texture->resourcePriv().refsWrappedObjects());
813     SkASSERT(texture->unique());
814     SkASSERT(image->unique());
815 
816     // Take a reference to the GrTexture and release the image.
817     sk_sp<GrTexture> textureRef = sk_ref_sp(texture);
818     view.reset();
819     image = nullptr;
820     SkASSERT(textureRef->unique());
821 
822     // Steal the backend texture from the GrTexture, releasing the GrTexture in the process.
823     return GrTexture::StealBackendTexture(std::move(textureRef), backendTexture, releaseProc);
824 }
825 
onAsView(GrRecordingContext * recordingContext,GrMipmapped mipmapped,GrImageTexGenPolicy policy) const826 std::tuple<GrSurfaceProxyView, GrColorType> SkImage_Gpu::onAsView(
827         GrRecordingContext* recordingContext,
828         GrMipmapped mipmapped,
829         GrImageTexGenPolicy policy) const {
830     if (!fContext->priv().matches(recordingContext)) {
831         return {};
832     }
833     if (policy != GrImageTexGenPolicy::kDraw) {
834         return {CopyView(recordingContext, this->makeView(recordingContext), mipmapped, policy),
835                 SkColorTypeToGrColorType(this->colorType())};
836     }
837     GrSurfaceProxyView view = this->makeView(recordingContext);
838     GrColorType ct = SkColorTypeToGrColorType(this->colorType());
839     if (mipmapped == GrMipmapped::kYes) {
840         view = FindOrMakeCachedMipmappedView(recordingContext, std::move(view), this->uniqueID());
841     }
842     return {std::move(view), ct};
843 }
844 
onAsFragmentProcessor(GrRecordingContext * rContext,SkSamplingOptions sampling,const SkTileMode tileModes[2],const SkMatrix & m,const SkRect * subset,const SkRect * domain) const845 std::unique_ptr<GrFragmentProcessor> SkImage_Gpu::onAsFragmentProcessor(
846         GrRecordingContext* rContext,
847         SkSamplingOptions sampling,
848         const SkTileMode tileModes[2],
849         const SkMatrix& m,
850         const SkRect* subset,
851         const SkRect* domain) const {
852     if (!fContext->priv().matches(rContext)) {
853         return {};
854     }
855     auto mm = sampling.mipmap == SkMipmapMode::kNone ? GrMipmapped::kNo : GrMipmapped::kYes;
856     return MakeFragmentProcessorFromView(rContext,
857                                          std::get<0>(this->asView(rContext, mm)),
858                                          this->alphaType(),
859                                          sampling,
860                                          tileModes,
861                                          m,
862                                          subset,
863                                          domain);
864 }
865 
makeView(GrRecordingContext * rContext) const866 GrSurfaceProxyView SkImage_Gpu::makeView(GrRecordingContext* rContext) const {
867     return {fChooser.chooseProxy(rContext), fOrigin, fSwizzle};
868 }
869