1 /*
2  * Copyright 2016 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/gpu/GrSurfaceContext.h"
9 
10 #include "include/private/GrRecordingContext.h"
11 #include "src/core/SkAutoPixmapStorage.h"
12 #include "src/gpu/GrAuditTrail.h"
13 #include "src/gpu/GrClip.h"
14 #include "src/gpu/GrContextPriv.h"
15 #include "src/gpu/GrDataUtils.h"
16 #include "src/gpu/GrDrawingManager.h"
17 #include "src/gpu/GrGpu.h"
18 #include "src/gpu/GrImageInfo.h"
19 #include "src/gpu/GrRecordingContextPriv.h"
20 #include "src/gpu/GrRenderTargetContext.h"
21 #include "src/gpu/GrSurfaceContextPriv.h"
22 #include "src/gpu/GrSurfacePriv.h"
23 #include "src/gpu/GrTextureContext.h"
24 #include "src/gpu/SkGr.h"
25 #include "src/gpu/effects/GrBicubicEffect.h"
26 
27 #define ASSERT_SINGLE_OWNER \
28     SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(this->singleOwner());)
29 #define RETURN_FALSE_IF_ABANDONED  if (this->fContext->priv().abandoned()) { return false; }
30 
31 // In MDB mode the reffing of the 'getLastOpsTask' call's result allows in-progress
32 // GrOpsTasks to be picked up and added to by renderTargetContexts lower in the call
33 // stack. When this occurs with a closed GrOpsTask, a new one will be allocated
34 // when the renderTargetContext attempts to use it (via getOpsTask).
GrSurfaceContext(GrRecordingContext * context,GrColorType colorType,SkAlphaType alphaType,sk_sp<SkColorSpace> colorSpace)35 GrSurfaceContext::GrSurfaceContext(GrRecordingContext* context,
36                                    GrColorType colorType,
37                                    SkAlphaType alphaType,
38                                    sk_sp<SkColorSpace> colorSpace)
39         : fContext(context), fColorInfo(colorType, alphaType, std::move(colorSpace)) {}
40 
caps() const41 const GrCaps* GrSurfaceContext::caps() const { return fContext->priv().caps(); }
42 
auditTrail()43 GrAuditTrail* GrSurfaceContext::auditTrail() {
44     return fContext->priv().auditTrail();
45 }
46 
drawingManager()47 GrDrawingManager* GrSurfaceContext::drawingManager() {
48     return fContext->priv().drawingManager();
49 }
50 
drawingManager() const51 const GrDrawingManager* GrSurfaceContext::drawingManager() const {
52     return fContext->priv().drawingManager();
53 }
54 
55 #ifdef SK_DEBUG
singleOwner()56 GrSingleOwner* GrSurfaceContext::singleOwner() {
57     return fContext->priv().singleOwner();
58 }
59 #endif
60 
readPixels(const GrImageInfo & origDstInfo,void * dst,size_t rowBytes,SkIPoint pt,GrContext * direct)61 bool GrSurfaceContext::readPixels(const GrImageInfo& origDstInfo, void* dst, size_t rowBytes,
62                                   SkIPoint pt, GrContext* direct) {
63     ASSERT_SINGLE_OWNER
64     RETURN_FALSE_IF_ABANDONED
65     SkDEBUGCODE(this->validate();)
66     GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContext::readPixels");
67 
68     if (!direct && !(direct = fContext->priv().asDirectContext())) {
69         return false;
70     }
71 
72     if (!dst) {
73         return false;
74     }
75 
76     size_t tightRowBytes = origDstInfo.minRowBytes();
77     if (!rowBytes) {
78         rowBytes = tightRowBytes;
79     } else if (rowBytes < tightRowBytes) {
80         return false;
81     }
82 
83     if (!origDstInfo.isValid()) {
84         return false;
85     }
86 
87     GrSurfaceProxy* srcProxy = this->asSurfaceProxy();
88 
89     // MDB TODO: delay this instantiation until later in the method
90     if (!srcProxy->instantiate(direct->priv().resourceProvider())) {
91         return false;
92     }
93 
94     GrSurface* srcSurface = srcProxy->peekSurface();
95 
96     auto dstInfo = origDstInfo;
97     if (!dstInfo.clip(this->width(), this->height(), &pt, &dst, rowBytes)) {
98         return false;
99     }
100     // Our tight row bytes may have been changed by clipping.
101     tightRowBytes = dstInfo.minRowBytes();
102 
103     bool premul   = this->colorInfo().alphaType() == kUnpremul_SkAlphaType &&
104                     dstInfo.alphaType() == kPremul_SkAlphaType;
105     bool unpremul = this->colorInfo().alphaType() == kPremul_SkAlphaType &&
106                     dstInfo.alphaType() == kUnpremul_SkAlphaType;
107 
108     bool needColorConversion =
109             SkColorSpaceXformSteps::Required(this->colorInfo().colorSpace(), dstInfo.colorSpace());
110 
111     const GrCaps* caps = direct->priv().caps();
112     // This is the getImageData equivalent to the canvas2D putImageData fast path. We probably don't
113     // care so much about getImageData performance. However, in order to ensure putImageData/
114     // getImageData in "legacy" mode are round-trippable we use the GPU to do the complementary
115     // unpremul step to writeSurfacePixels's premul step (which is determined empirically in
116     // fContext->vaildaPMUPMConversionExists()).
117     GrBackendFormat defaultRGBAFormat = caps->getDefaultBackendFormat(GrColorType::kRGBA_8888,
118                                                                       GrRenderable::kYes);
119     bool canvas2DFastPath = unpremul && !needColorConversion &&
120                             (GrColorType::kRGBA_8888 == dstInfo.colorType() ||
121                              GrColorType::kBGRA_8888 == dstInfo.colorType()) &&
122                             SkToBool(srcProxy->asTextureProxy()) &&
123                             (srcProxy->config() == kRGBA_8888_GrPixelConfig ||
124                              srcProxy->config() == kBGRA_8888_GrPixelConfig) &&
125                             defaultRGBAFormat.isValid() &&
126                             direct->priv().validPMUPMConversionExists();
127 
128     auto readFlag = caps->surfaceSupportsReadPixels(srcSurface);
129     if (readFlag == GrCaps::SurfaceReadPixelsSupport::kUnsupported) {
130         return false;
131     }
132 
133     if (readFlag == GrCaps::SurfaceReadPixelsSupport::kCopyToTexture2D || canvas2DFastPath) {
134         GrColorType colorType =
135                 canvas2DFastPath ? GrColorType::kRGBA_8888 : this->colorInfo().colorType();
136         sk_sp<SkColorSpace> cs = canvas2DFastPath ? nullptr : this->colorInfo().refColorSpace();
137 
138         auto tempCtx = direct->priv().makeDeferredRenderTargetContext(
139                 SkBackingFit::kApprox, dstInfo.width(), dstInfo.height(), colorType, std::move(cs),
140                 1, GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin, nullptr, SkBudgeted::kYes);
141         if (!tempCtx) {
142             return false;
143         }
144 
145         std::unique_ptr<GrFragmentProcessor> fp;
146         if (canvas2DFastPath) {
147             fp = direct->priv().createPMToUPMEffect(
148                     GrSimpleTextureEffect::Make(sk_ref_sp(srcProxy->asTextureProxy()),
149                                                 this->colorInfo().colorType(), SkMatrix::I()));
150             if (dstInfo.colorType() == GrColorType::kBGRA_8888) {
151                 fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), GrSwizzle::BGRA());
152                 dstInfo = dstInfo.makeColorType(GrColorType::kRGBA_8888);
153             }
154             // The render target context is incorrectly tagged as kPremul even though we're writing
155             // unpremul data thanks to the PMToUPM effect. Fake out the dst alpha type so we don't
156             // double unpremul.
157             dstInfo = dstInfo.makeAlphaType(kPremul_SkAlphaType);
158         } else {
159             fp = GrSimpleTextureEffect::Make(sk_ref_sp(srcProxy->asTextureProxy()),
160                                              this->colorInfo().colorType(), SkMatrix::I());
161         }
162         if (!fp) {
163             return false;
164         }
165         GrPaint paint;
166         paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
167         paint.addColorFragmentProcessor(std::move(fp));
168 
169         tempCtx->asRenderTargetContext()->fillRectToRect(
170                 GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
171                 SkRect::MakeWH(dstInfo.width(), dstInfo.height()),
172                 SkRect::MakeXYWH(pt.fX, pt.fY, dstInfo.width(), dstInfo.height()));
173 
174         return tempCtx->readPixels(dstInfo, dst, rowBytes, {0, 0}, direct);
175     }
176 
177     bool flip = srcProxy->origin() == kBottomLeft_GrSurfaceOrigin;
178 
179     auto supportedRead = caps->supportedReadPixelsColorType(
180             this->colorInfo().colorType(), srcProxy->backendFormat(), dstInfo.colorType());
181 
182     bool makeTight = !caps->readPixelsRowBytesSupport() && tightRowBytes != rowBytes;
183 
184     bool convert = unpremul || premul || needColorConversion || flip || makeTight ||
185                    (dstInfo.colorType() != supportedRead.fColorType);
186 
187     std::unique_ptr<char[]> tmpPixels;
188     GrImageInfo tmpInfo;
189     void* readDst = dst;
190     size_t readRB = rowBytes;
191     if (convert) {
192         tmpInfo = {supportedRead.fColorType, this->colorInfo().alphaType(),
193                    this->colorInfo().refColorSpace(), dstInfo.width(), dstInfo.height()};
194         size_t tmpRB = tmpInfo.minRowBytes();
195         size_t size = tmpRB * tmpInfo.height();
196         // Chrome MSAN bots require the data to be initialized (hence the ()).
197         tmpPixels.reset(new char[size]());
198 
199         readDst = tmpPixels.get();
200         readRB = tmpRB;
201         pt.fY = flip ? srcSurface->height() - pt.fY - dstInfo.height() : pt.fY;
202     }
203 
204     direct->priv().flushSurface(srcProxy);
205 
206     if (!direct->priv().getGpu()->readPixels(srcSurface, pt.fX, pt.fY, dstInfo.width(),
207                                              dstInfo.height(), this->colorInfo().colorType(),
208                                              supportedRead.fColorType, readDst, readRB)) {
209         return false;
210     }
211 
212     if (convert) {
213         return GrConvertPixels(dstInfo, dst, rowBytes, tmpInfo, readDst, readRB, flip);
214     }
215     return true;
216 }
217 
writePixels(const GrImageInfo & origSrcInfo,const void * src,size_t rowBytes,SkIPoint pt,GrContext * direct)218 bool GrSurfaceContext::writePixels(const GrImageInfo& origSrcInfo, const void* src, size_t rowBytes,
219                                    SkIPoint pt, GrContext* direct) {
220     ASSERT_SINGLE_OWNER
221     RETURN_FALSE_IF_ABANDONED
222     SkDEBUGCODE(this->validate();)
223     GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContext::writePixels");
224 
225     if (!direct && !(direct = fContext->priv().asDirectContext())) {
226         return false;
227     }
228 
229     if (this->asSurfaceProxy()->readOnly()) {
230         return false;
231     }
232 
233     if (!src) {
234         return false;
235     }
236 
237     size_t tightRowBytes = origSrcInfo.minRowBytes();
238     if (!rowBytes) {
239         rowBytes = tightRowBytes;
240     } else if (rowBytes < tightRowBytes) {
241         return false;
242     }
243 
244     if (!origSrcInfo.isValid()) {
245         return false;
246     }
247 
248     GrSurfaceProxy* dstProxy = this->asSurfaceProxy();
249     if (!dstProxy->instantiate(direct->priv().resourceProvider())) {
250         return false;
251     }
252 
253     GrSurface* dstSurface = dstProxy->peekSurface();
254 
255     auto srcInfo = origSrcInfo;
256     if (!srcInfo.clip(this->width(), this->height(), &pt, &src, rowBytes)) {
257         return false;
258     }
259     // Our tight row bytes may have been changed by clipping.
260     tightRowBytes = srcInfo.minRowBytes();
261 
262     bool premul   = this->colorInfo().alphaType() == kPremul_SkAlphaType &&
263                     srcInfo.alphaType() == kUnpremul_SkAlphaType;
264     bool unpremul = this->colorInfo().alphaType() == kUnpremul_SkAlphaType &&
265                     srcInfo.alphaType() == kPremul_SkAlphaType;
266 
267     bool needColorConversion =
268             SkColorSpaceXformSteps::Required(srcInfo.colorSpace(), this->colorInfo().colorSpace());
269 
270     const GrCaps* caps = direct->priv().caps();
271 
272     auto rgbaDefaultFormat = caps->getDefaultBackendFormat(GrColorType::kRGBA_8888,
273                                                            GrRenderable::kNo);
274 
275     // For canvas2D putImageData performance we have a special code path for unpremul RGBA_8888 srcs
276     // that are premultiplied on the GPU. This is kept as narrow as possible for now.
277     bool canvas2DFastPath = !caps->avoidWritePixelsFastPath() && premul && !needColorConversion &&
278                             (srcInfo.colorType() == GrColorType::kRGBA_8888 ||
279                              srcInfo.colorType() == GrColorType::kBGRA_8888) &&
280                             SkToBool(this->asRenderTargetContext()) &&
281                             (dstProxy->config() == kRGBA_8888_GrPixelConfig ||
282                              dstProxy->config() == kBGRA_8888_GrPixelConfig) &&
283                             rgbaDefaultFormat.isValid() &&
284                             direct->priv().validPMUPMConversionExists();
285 
286     if (!caps->surfaceSupportsWritePixels(dstSurface) || canvas2DFastPath) {
287         GrSurfaceDesc desc;
288         desc.fWidth = srcInfo.width();
289         desc.fHeight = srcInfo.height();
290         GrColorType colorType;
291 
292         GrBackendFormat format;
293         SkAlphaType alphaType;
294         if (canvas2DFastPath) {
295             desc.fConfig = kRGBA_8888_GrPixelConfig;
296             colorType = GrColorType::kRGBA_8888;
297             format = rgbaDefaultFormat;
298             alphaType = kUnpremul_SkAlphaType;
299         } else {
300             desc.fConfig =  dstProxy->config();
301             colorType = this->colorInfo().colorType();
302             format = dstProxy->backendFormat().makeTexture2D();
303             if (!format.isValid()) {
304                 return false;
305             }
306             alphaType = this->colorInfo().alphaType();
307         }
308 
309         // It is more efficient for us to write pixels into a top left origin so we prefer that.
310         // However, if the final proxy isn't a render target then we must use a copy to move the
311         // data into it which requires the origins to match. If the final proxy is a render target
312         // we can use a draw instead which doesn't have this origin restriction. Thus for render
313         // targets we will use top left and otherwise we will make the origins match.
314         GrSurfaceOrigin tempOrigin =
315                 this->asRenderTargetContext() ? kTopLeft_GrSurfaceOrigin : dstProxy->origin();
316         auto tempProxy = direct->priv().proxyProvider()->createProxy(
317                 format, desc, GrRenderable::kNo, 1, tempOrigin, GrMipMapped::kNo,
318                 SkBackingFit::kApprox, SkBudgeted::kYes, GrProtected::kNo);
319 
320         if (!tempProxy) {
321             return false;
322         }
323         auto tempCtx = direct->priv().drawingManager()->makeTextureContext(
324                 tempProxy, colorType, alphaType, this->colorInfo().refColorSpace());
325         if (!tempCtx) {
326             return false;
327         }
328 
329         // In the fast path we always write the srcData to the temp context as though it were RGBA.
330         // When the data is really BGRA the write will cause the R and B channels to be swapped in
331         // the intermediate surface which gets corrected by a swizzle effect when drawing to the
332         // dst.
333         if (canvas2DFastPath) {
334             srcInfo = srcInfo.makeColorType(GrColorType::kRGBA_8888);
335         }
336         if (!tempCtx->writePixels(srcInfo, src, rowBytes, {0, 0}, direct)) {
337             return false;
338         }
339 
340         if (this->asRenderTargetContext()) {
341             std::unique_ptr<GrFragmentProcessor> fp;
342             if (canvas2DFastPath) {
343                 fp = direct->priv().createUPMToPMEffect(
344                         GrSimpleTextureEffect::Make(std::move(tempProxy), colorType,
345                                                     SkMatrix::I()));
346                 // Important: check the original src color type here!
347                 if (origSrcInfo.colorType() == GrColorType::kBGRA_8888) {
348                     fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), GrSwizzle::BGRA());
349                 }
350             } else {
351                 fp = GrSimpleTextureEffect::Make(std::move(tempProxy), colorType, SkMatrix::I());
352             }
353             if (!fp) {
354                 return false;
355             }
356             GrPaint paint;
357             paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
358             paint.addColorFragmentProcessor(std::move(fp));
359             this->asRenderTargetContext()->fillRectToRect(
360                     GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
361                     SkRect::MakeXYWH(pt.fX, pt.fY, srcInfo.width(), srcInfo.height()),
362                     SkRect::MakeWH(srcInfo.width(), srcInfo.height()));
363         } else {
364             SkIRect srcRect = SkIRect::MakeWH(srcInfo.width(), srcInfo.height());
365             SkIPoint dstPoint = SkIPoint::Make(pt.fX, pt.fY);
366             if (!this->copy(tempProxy.get(), srcRect, dstPoint)) {
367                 return false;
368             }
369         }
370         return true;
371     }
372 
373     GrColorType allowedColorType =
374             caps->supportedWritePixelsColorType(this->colorInfo().colorType(),
375                                                 dstProxy->backendFormat(),
376                                                 srcInfo.colorType()).fColorType;
377     bool flip = dstProxy->origin() == kBottomLeft_GrSurfaceOrigin;
378     bool makeTight = !caps->writePixelsRowBytesSupport() && rowBytes != tightRowBytes;
379     bool convert = premul || unpremul || needColorConversion || makeTight ||
380                    (srcInfo.colorType() != allowedColorType) || flip;
381 
382     std::unique_ptr<char[]> tmpPixels;
383     GrColorType srcColorType = srcInfo.colorType();
384     if (convert) {
385         GrImageInfo tmpInfo(allowedColorType, this->colorInfo().alphaType(),
386                             this->colorInfo().refColorSpace(), srcInfo.width(), srcInfo.height());
387         auto tmpRB = tmpInfo.minRowBytes();
388         tmpPixels.reset(new char[tmpRB * tmpInfo.height()]);
389 
390         GrConvertPixels(tmpInfo, tmpPixels.get(), tmpRB, srcInfo, src, rowBytes, flip);
391 
392         srcColorType = tmpInfo.colorType();
393         rowBytes = tmpRB;
394         src = tmpPixels.get();
395         pt.fY = flip ? dstSurface->height() - pt.fY - tmpInfo.height() : pt.fY;
396     }
397 
398     // On platforms that prefer flushes over VRAM use (i.e., ANGLE) we're better off forcing a
399     // complete flush here. On platforms that prefer VRAM use over flushes we're better off
400     // giving the drawing manager the chance of skipping the flush (i.e., by passing in the
401     // destination proxy)
402     // TODO: should this policy decision just be moved into the drawing manager?
403     direct->priv().flushSurface(caps->preferVRAMUseOverFlushes() ? dstProxy : nullptr);
404 
405     return direct->priv().getGpu()->writePixels(dstSurface, pt.fX, pt.fY, srcInfo.width(),
406                                                 srcInfo.height(), this->colorInfo().colorType(),
407                                                 srcColorType, src, rowBytes);
408 }
409 
copy(GrSurfaceProxy * src,const SkIRect & srcRect,const SkIPoint & dstPoint)410 bool GrSurfaceContext::copy(GrSurfaceProxy* src, const SkIRect& srcRect, const SkIPoint& dstPoint) {
411     ASSERT_SINGLE_OWNER
412     RETURN_FALSE_IF_ABANDONED
413     SkDEBUGCODE(this->validate();)
414     GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContextPriv::copy");
415 
416     const GrCaps* caps = fContext->priv().caps();
417 
418     SkASSERT(src->backendFormat().textureType() != GrTextureType::kExternal);
419     SkASSERT(src->origin() == this->asSurfaceProxy()->origin());
420     SkASSERT(caps->makeConfigSpecific(src->config(), src->backendFormat()) ==
421              caps->makeConfigSpecific(this->asSurfaceProxy()->config(),
422                                       this->asSurfaceProxy()->backendFormat()));
423 
424     if (!caps->canCopySurface(this->asSurfaceProxy(), src, srcRect, dstPoint)) {
425         return false;
426     }
427 
428     return this->drawingManager()->newCopyRenderTask(sk_ref_sp(src), srcRect,
429                                                      this->asSurfaceProxyRef(), dstPoint);
430 }
431 
rescale(const SkImageInfo & info,const SkIRect & srcRect,SkSurface::RescaleGamma rescaleGamma,SkFilterQuality rescaleQuality)432 std::unique_ptr<GrRenderTargetContext> GrSurfaceContext::rescale(
433         const SkImageInfo& info,
434         const SkIRect& srcRect,
435         SkSurface::RescaleGamma rescaleGamma,
436         SkFilterQuality rescaleQuality) {
437     auto direct = fContext->priv().asDirectContext();
438     if (!direct) {
439         return nullptr;
440     }
441     auto rtProxy = this->asRenderTargetProxy();
442     if (rtProxy && rtProxy->wrapsVkSecondaryCB()) {
443         return nullptr;
444     }
445 
446     // We rescale by drawing and don't currently support drawing to a kUnpremul destination.
447     if (info.alphaType() == kUnpremul_SkAlphaType) {
448         return nullptr;
449     }
450 
451     int srcW = srcRect.width();
452     int srcH = srcRect.height();
453     int srcX = srcRect.fLeft;
454     int srcY = srcRect.fTop;
455     sk_sp<GrTextureProxy> texProxy = sk_ref_sp(this->asTextureProxy());
456     SkCanvas::SrcRectConstraint constraint = SkCanvas::kStrict_SrcRectConstraint;
457     GrColorType srcColorType = this->colorInfo().colorType();
458     if (!texProxy) {
459         texProxy = GrSurfaceProxy::Copy(fContext, this->asSurfaceProxy(), srcColorType,
460                                         GrMipMapped::kNo, srcRect, SkBackingFit::kApprox,
461                                         SkBudgeted::kNo);
462         if (!texProxy) {
463             return nullptr;
464         }
465         srcX = 0;
466         srcY = 0;
467         constraint = SkCanvas::kFast_SrcRectConstraint;
468     }
469 
470     float sx = (float)info.width() / srcW;
471     float sy = (float)info.height() / srcH;
472 
473     // How many bilerp/bicubic steps to do in X and Y. + means upscaling, - means downscaling.
474     int stepsX;
475     int stepsY;
476     if (rescaleQuality > kNone_SkFilterQuality) {
477         stepsX = static_cast<int>((sx > 1.f) ? ceil(log2f(sx)) : floor(log2f(sx)));
478         stepsY = static_cast<int>((sy > 1.f) ? ceil(log2f(sy)) : floor(log2f(sy)));
479     } else {
480         stepsX = sx != 1.f;
481         stepsY = sy != 1.f;
482     }
483     SkASSERT(stepsX || stepsY);
484 
485     // Within a rescaling pass A is the input (if not null) and B is the output. At the end of the
486     // pass B is moved to A. If 'this' is the input on the first pass then tempA is null.
487     std::unique_ptr<GrRenderTargetContext> tempA;
488     std::unique_ptr<GrRenderTargetContext> tempB;
489 
490     // Assume we should ignore the rescale linear request if the surface has no color space since
491     // it's unclear how we'd linearize from an unknown color space.
492     if (rescaleGamma == SkSurface::kLinear && this->colorInfo().colorSpace() &&
493         !this->colorInfo().colorSpace()->gammaIsLinear()) {
494         auto cs = this->colorInfo().colorSpace()->makeLinearGamma();
495         auto xform = GrColorSpaceXform::Make(this->colorInfo().colorSpace(),
496                                              this->colorInfo().alphaType(), cs.get(),
497                                              kPremul_SkAlphaType);
498         // We'll fall back to kRGBA_8888 if half float not supported.
499         auto linearRTC = fContext->priv().makeDeferredRenderTargetContextWithFallback(
500                 SkBackingFit::kExact, srcW, srcH, GrColorType::kRGBA_F16, cs, 1, GrMipMapped::kNo,
501                 kTopLeft_GrSurfaceOrigin);
502         if (!linearRTC) {
503             return nullptr;
504         }
505         linearRTC->drawTexture(GrNoClip(), texProxy, srcColorType, GrSamplerState::Filter::kNearest,
506                                SkBlendMode::kSrc, SK_PMColor4fWHITE, SkRect::Make(srcRect),
507                                SkRect::MakeWH(srcW, srcH), GrAA::kNo, GrQuadAAFlags::kNone,
508                                constraint, SkMatrix::I(), std::move(xform));
509         texProxy = linearRTC->asTextureProxyRef();
510         tempA = std::move(linearRTC);
511         srcX = 0;
512         srcY = 0;
513         constraint = SkCanvas::kFast_SrcRectConstraint;
514     }
515     while (stepsX || stepsY) {
516         int nextW = info.width();
517         int nextH = info.height();
518         if (stepsX < 0) {
519             nextW = info.width() << (-stepsX - 1);
520             stepsX++;
521         } else if (stepsX != 0) {
522             if (stepsX > 1) {
523                 nextW = srcW * 2;
524             }
525             --stepsX;
526         }
527         if (stepsY < 0) {
528             nextH = info.height() << (-stepsY - 1);
529             stepsY++;
530         } else if (stepsY != 0) {
531             if (stepsY > 1) {
532                 nextH = srcH * 2;
533             }
534             --stepsY;
535         }
536         auto input = tempA ? tempA.get() : this;
537         GrColorType colorType = input->colorInfo().colorType();
538         auto cs = input->colorInfo().refColorSpace();
539         sk_sp<GrColorSpaceXform> xform;
540         auto prevAlphaType = input->colorInfo().alphaType();
541         if (!stepsX && !stepsY) {
542             // Might as well fold conversion to final info in the last step.
543             cs = info.refColorSpace();
544             colorType = SkColorTypeToGrColorType(info.colorType());
545             xform = GrColorSpaceXform::Make(input->colorInfo().colorSpace(),
546                                             input->colorInfo().alphaType(), cs.get(),
547                                             info.alphaType());
548         }
549         tempB = fContext->priv().makeDeferredRenderTargetContextWithFallback(
550                 SkBackingFit::kExact, nextW, nextH, colorType, std::move(cs), 1, GrMipMapped::kNo,
551                 kTopLeft_GrSurfaceOrigin);
552         if (!tempB) {
553             return nullptr;
554         }
555         auto dstRect = SkRect::MakeWH(nextW, nextH);
556         if (rescaleQuality == kHigh_SkFilterQuality) {
557             SkMatrix matrix;
558             matrix.setScaleTranslate((float)srcW / nextW, (float)srcH / nextH, srcX, srcY);
559             std::unique_ptr<GrFragmentProcessor> fp;
560             auto dir = GrBicubicEffect::Direction::kXY;
561             if (nextW == srcW) {
562                 dir = GrBicubicEffect::Direction::kY;
563             } else if (nextH == srcH) {
564                 dir = GrBicubicEffect::Direction::kX;
565             }
566             if (srcW != texProxy->width() || srcH != texProxy->height()) {
567                 auto domain = GrTextureDomain::MakeTexelDomain(
568                         SkIRect::MakeXYWH(srcX, srcY, srcW, srcH), GrTextureDomain::kClamp_Mode);
569                 fp = GrBicubicEffect::Make(texProxy, srcColorType, matrix, domain, dir,
570                                            prevAlphaType);
571             } else {
572                 fp = GrBicubicEffect::Make(texProxy, srcColorType, matrix, dir, prevAlphaType);
573             }
574             if (xform) {
575                 fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(xform));
576             }
577             GrPaint paint;
578             paint.addColorFragmentProcessor(std::move(fp));
579             paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
580             tempB->fillRectToRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), dstRect,
581                                     dstRect);
582         } else {
583             auto filter = rescaleQuality == kNone_SkFilterQuality ? GrSamplerState::Filter::kNearest
584                                                                   : GrSamplerState::Filter::kBilerp;
585             auto srcSubset = SkRect::MakeXYWH(srcX, srcY, srcW, srcH);
586             tempB->drawTexture(GrNoClip(), texProxy, srcColorType, filter, SkBlendMode::kSrc,
587                                SK_PMColor4fWHITE, srcSubset, dstRect, GrAA::kNo,
588                                GrQuadAAFlags::kNone, constraint, SkMatrix::I(), std::move(xform));
589         }
590         texProxy = tempB->asTextureProxyRef();
591         tempA = std::move(tempB);
592         srcX = srcY = 0;
593         srcW = nextW;
594         srcH = nextH;
595         constraint = SkCanvas::kFast_SrcRectConstraint;
596     }
597     SkASSERT(tempA);
598     return tempA;
599 }
600 
transferPixels(GrColorType dstCT,const SkIRect & rect)601 GrSurfaceContext::PixelTransferResult GrSurfaceContext::transferPixels(GrColorType dstCT,
602                                                                        const SkIRect& rect) {
603     SkASSERT(rect.fLeft >= 0 && rect.fRight <= this->width());
604     SkASSERT(rect.fTop >= 0 && rect.fBottom <= this->height());
605     auto direct = fContext->priv().asDirectContext();
606     if (!direct) {
607         return {};
608     }
609     auto rtProxy = this->asRenderTargetProxy();
610     if (rtProxy && rtProxy->wrapsVkSecondaryCB()) {
611         return {};
612     }
613 
614     auto proxy = this->asSurfaceProxy();
615     auto supportedRead = this->caps()->supportedReadPixelsColorType(this->colorInfo().colorType(),
616                                                                     proxy->backendFormat(), dstCT);
617     // Fail if read color type does not have all of dstCT's color channels and those missing color
618     // channels are in the src.
619     uint32_t dstComponents = GrColorTypeComponentFlags(dstCT);
620     uint32_t legalReadComponents = GrColorTypeComponentFlags(supportedRead.fColorType);
621     uint32_t srcComponents = GrColorTypeComponentFlags(this->colorInfo().colorType());
622     if ((~legalReadComponents & dstComponents) & srcComponents) {
623         return {};
624     }
625 
626     if (!this->caps()->transferBufferSupport() ||
627         !supportedRead.fOffsetAlignmentForTransferBuffer) {
628         return {};
629     }
630 
631     size_t rowBytes = GrColorTypeBytesPerPixel(supportedRead.fColorType) * rect.width();
632     size_t size = rowBytes * rect.height();
633     auto buffer = direct->priv().resourceProvider()->createBuffer(
634             size, GrGpuBufferType::kXferGpuToCpu, GrAccessPattern::kStream_GrAccessPattern);
635     if (!buffer) {
636         return {};
637     }
638     auto srcRect = rect;
639     bool flip = proxy->origin() == kBottomLeft_GrSurfaceOrigin;
640     if (flip) {
641         srcRect = SkIRect::MakeLTRB(rect.fLeft, this->height() - rect.fBottom, rect.fRight,
642                                     this->height() - rect.fTop);
643     }
644     this->drawingManager()->newTransferFromRenderTask(this->asSurfaceProxyRef(), srcRect,
645                                                       this->colorInfo().colorType(),
646                                                       supportedRead.fColorType, buffer, 0);
647     PixelTransferResult result;
648     result.fTransferBuffer = std::move(buffer);
649     auto at = this->colorInfo().alphaType();
650     if (supportedRead.fColorType != dstCT || flip) {
651         result.fPixelConverter = [w = rect.width(), h = rect.height(), dstCT, supportedRead, at](
652                 void* dst, const void* src) {
653             GrImageInfo srcInfo(supportedRead.fColorType, at, nullptr, w, h);
654             GrImageInfo dstInfo(dstCT,                    at, nullptr, w, h);
655               GrConvertPixels(dstInfo, dst, dstInfo.minRowBytes(),
656                               srcInfo, src, srcInfo.minRowBytes(),
657                               /* flipY = */ false);
658         };
659     }
660     return result;
661 }
662