Debian Codegraph @

src/gpu/ganesh/SurfaceContext.cpp

raw ◀ ▶
1 Debian patch touch this file
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 #include "src/gpu/ganesh/SurfaceContext.h"
8
9 #include "include/core/SkAlphaType.h"
10 #include "include/core/SkColorSpace.h"
11 #include "include/core/SkColorType.h"
12 #include "include/core/SkData.h"
13 #include "include/core/SkImageInfo.h"
14 #include "include/core/SkMatrix.h"
15 #include "include/core/SkSamplingOptions.h"
16 #include "include/core/SkSurface.h"
17 #include "include/gpu/GpuTypes.h"
18 #include "include/gpu/ganesh/GrBackendSurface.h"
19 #include "include/gpu/ganesh/GrDirectContext.h"
20 #include "include/gpu/ganesh/GrRecordingContext.h"
21 #include "include/gpu/ganesh/GrTypes.h"
22 #include "include/private/base/SingleOwner.h"
23 #include "include/private/base/SkAlign.h"
24 #include "include/private/base/SkAssert.h"
25 #include "include/private/base/SkPoint_impl.h"
26 #include "include/private/base/SkTemplates.h"
27 #include "include/private/base/SkTo.h"
28 #include "include/private/gpu/ganesh/GrTypesPriv.h"
•29 #include "src/base/SkSafeMath.h"
30 #include "src/core/SkColorSpaceXformSteps.h"
31 #include "src/core/SkMipmap.h"
32 #include "src/core/SkTraceEvent.h"
33 #include "src/core/SkYUVMath.h"
34 #include "src/gpu/AsyncReadTypes.h"
35 #include "src/gpu/SkBackingFit.h"
36 #include "src/gpu/ganesh/GrAuditTrail.h"
37 #include "src/gpu/ganesh/GrCaps.h"
38 #include "src/gpu/ganesh/GrClientMappedBufferManager.h"
39 #include "src/gpu/ganesh/GrColorSpaceXform.h"
40 #include "src/gpu/ganesh/GrDataUtils.h"
41 #include "src/gpu/ganesh/GrDirectContextPriv.h"
42 #include "src/gpu/ganesh/GrDrawingManager.h"
43 #include "src/gpu/ganesh/GrFragmentProcessor.h"
44 #include "src/gpu/ganesh/GrGpu.h"
45 #include "src/gpu/ganesh/GrImageInfo.h"
46 #include "src/gpu/ganesh/GrProxyProvider.h"
47 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
48 #include "src/gpu/ganesh/GrRenderTargetProxy.h"
49 #include "src/gpu/ganesh/GrRenderTask.h"
50 #include "src/gpu/ganesh/GrResourceProvider.h"
51 #include "src/gpu/ganesh/GrSurface.h"
52 #include "src/gpu/ganesh/GrTextureProxy.h"
53 #include "src/gpu/ganesh/GrTracing.h"
54 #include "src/gpu/ganesh/SurfaceFillContext.h"
55 #include "src/gpu/ganesh/effects/GrBicubicEffect.h"
56 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
57 #include "src/gpu/ganesh/geometry/GrRect.h"
58
59 #include <algorithm>
60 #include <cstdint>
61 #include <memory>
62 #include <tuple>
63
64 using namespace skia_private;
65
66 #define ASSERT_SINGLE_OWNER SKGPU_ASSERT_SINGLE_OWNER(this->singleOwner())
67 #define RETURN_FALSE_IF_ABANDONED if (this->fContext->abandoned()) { return false; }
68 #define RETURN_NULLPTR_IF_ABANDONED if (this->fContext->abandoned()) { return nullptr; }
69
70 namespace skgpu::ganesh {
71
72 SurfaceContext::SurfaceContext(GrRecordingContext* context,
73 GrSurfaceProxyView readView,
74 const GrColorInfo& info)
75 : fContext(context), fReadView(std::move(readView)), fColorInfo(info) {
76 SkASSERT(!context->abandoned());
77 }
78
79 const GrCaps* SurfaceContext::caps() const { return fContext->priv().caps(); }
80
81 GrDrawingManager* SurfaceContext::drawingManager() {
82 return fContext->priv().drawingManager();
83 }
84
85 const GrDrawingManager* SurfaceContext::drawingManager() const {
86 return fContext->priv().drawingManager();
87 }
88
89 #ifdef SK_DEBUG
90 skgpu::SingleOwner* SurfaceContext::singleOwner() const { return fContext->priv().singleOwner(); }
91 #endif
92
93 static bool alpha_types_compatible(SkAlphaType srcAlphaType, SkAlphaType dstAlphaType) {
94 // If both alpha types are kUnknown things make sense. If not, it's too underspecified.
95 return (srcAlphaType == kUnknown_SkAlphaType) == (dstAlphaType == kUnknown_SkAlphaType);
96 }
97
98 bool SurfaceContext::readPixels(GrDirectContext* dContext, GrPixmap dst, SkIPoint pt) {
99 ASSERT_SINGLE_OWNER
100 RETURN_FALSE_IF_ABANDONED
101 SkDEBUGCODE(this->validate();)
102 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceContext", "readPixels", fContext);
103
104 if (!fContext->priv().matches(dContext)) {
105 return false;
106 }
107
108 if (dst.colorType() == GrColorType::kUnknown) {
109 return false;
110 }
111
112 if (dst.rowBytes() % dst.info().bpp()) {
113 return false;
114 }
115
116 dst = dst.clip(this->dimensions(), &pt);
117 if (!dst.hasPixels()) {
118 return false;
119 }
120 if (!alpha_types_compatible(this->colorInfo().alphaType(), dst.alphaType())) {
121 return false;
122 }
123 // We allow unknown alpha types but only if both src and dst are unknown. Otherwise, it's too
124 // weird to reason about what should be expected.
125
126 sk_sp<GrSurfaceProxy> srcProxy = this->asSurfaceProxyRef();
127
128 if (srcProxy->framebufferOnly()) {
129 return false;
130 }
131
132 // MDB TODO: delay this instantiation until later in the method
133 if (!srcProxy->instantiate(dContext->priv().resourceProvider())) {
134 return false;
135 }
136
137 GrSurface* srcSurface = srcProxy->peekSurface();
138
139 SkColorSpaceXformSteps::Flags flags =
140 SkColorSpaceXformSteps{this->colorInfo(), dst.info()}.fFlags;
141 bool unpremul = flags.unpremul,
142 needColorConversion = flags.linearize || flags.gamut_transform || flags.encode,
143 premul = flags.premul;
144
145 const GrCaps* caps = dContext->priv().caps();
146 bool srcIsCompressed = caps->isFormatCompressed(srcSurface->backendFormat());
147 // This is the getImageData equivalent to the canvas2D putImageData fast path. We probably don't
148 // care so much about getImageData performance. However, in order to ensure putImageData/
149 // getImageData in "legacy" mode are round-trippable we use the GPU to do the complementary
150 // unpremul step to writeSurfacePixels's premul step (which is determined empirically in
151 // fContext->vaildaPMUPMConversionExists()).
152 GrBackendFormat defaultRGBAFormat = caps->getDefaultBackendFormat(GrColorType::kRGBA_8888,
153 GrRenderable::kYes);
154 GrColorType srcColorType = this->colorInfo().colorType();
155 bool canvas2DFastPath = unpremul && !needColorConversion &&
156 (GrColorType::kRGBA_8888 == dst.colorType() ||
157 GrColorType::kBGRA_8888 == dst.colorType()) &&
158 SkToBool(srcProxy->asTextureProxy()) &&
159 (srcColorType == GrColorType::kRGBA_8888 ||
160 srcColorType == GrColorType::kBGRA_8888) &&
161 defaultRGBAFormat.isValid() &&
162 dContext->priv().validPMUPMConversionExists();
163
164 // Since the validPMUPMConversionExists function actually submits work to the gpu to do its
165 // tests, it is possible that during that call we have abandoned the context. Thus, we do
166 // another abandoned check here to make sure we are still valid.
167 RETURN_FALSE_IF_ABANDONED
168
169 auto readFlag = caps->surfaceSupportsReadPixels(srcSurface);
170 if (readFlag == GrCaps::SurfaceReadPixelsSupport::kUnsupported) {
171 return false;
172 }
173
174 if (readFlag == GrCaps::SurfaceReadPixelsSupport::kCopyToTexture2D || canvas2DFastPath) {
175 std::unique_ptr<SurfaceContext> tempCtx;
176 if (this->asTextureProxy()) {
177 GrColorType colorType = this->colorInfo().colorType();
178 if (canvas2DFastPath || srcIsCompressed) {
179 colorType = GrColorType::kRGBA_8888;
180 } else {
181 GrBackendFormat backendFormat =
182 caps->getDefaultBackendFormat(colorType, GrRenderable::kYes);
183 if (!backendFormat.isValid()) {
184 colorType = GrColorType::kRGBA_8888;
185 }
186 }
187
188 SkAlphaType alphaType = canvas2DFastPath ? dst.alphaType()
189 : this->colorInfo().alphaType();
190 GrImageInfo tempInfo(colorType,
191 alphaType,
192 this->colorInfo().refColorSpace(),
193 dst.dimensions());
194 auto sfc = dContext->priv().makeSFC(
195 tempInfo, "SurfaceContext_ReadPixels", SkBackingFit::kApprox);
196 if (!sfc) {
197 return false;
198 }
199
200 std::unique_ptr<GrFragmentProcessor> fp;
201 if (canvas2DFastPath) {
202 fp = dContext->priv().createPMToUPMEffect(GrTextureEffect::Make(
203 this->readSurfaceView(), this->colorInfo().alphaType()));
204 if (dst.colorType() == GrColorType::kBGRA_8888) {
205 fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), skgpu::Swizzle::BGRA());
206 dst = GrPixmap(dst.info().makeColorType(GrColorType::kRGBA_8888),
207 dst.addr(),
208 dst.rowBytes());
209 }
210 } else {
211 fp = GrTextureEffect::Make(this->readSurfaceView(), this->colorInfo().alphaType());
212 }
213 if (!fp) {
214 return false;
215 }
216 sfc->fillRectToRectWithFP(SkIRect::MakePtSize(pt, dst.dimensions()),
217 SkIRect::MakeSize(dst.dimensions()),
218 std::move(fp));
219 pt = {0, 0};
220 tempCtx = std::move(sfc);
221 } else {
222 auto restrictions = this->caps()->getDstCopyRestrictions(this->asRenderTargetProxy(),
223 this->colorInfo().colorType());
224 sk_sp<GrSurfaceProxy> copy;
225 static constexpr auto kFit = SkBackingFit::kExact;
226 static constexpr auto kBudgeted = skgpu::Budgeted::kYes;
227 static constexpr auto kMipMapped = skgpu::Mipmapped::kNo;
228 if (restrictions.fMustCopyWholeSrc) {
229 copy = GrSurfaceProxy::Copy(fContext,
230 std::move(srcProxy),
231 this->origin(),
232 kMipMapped,
233 kFit,
234 kBudgeted,
235 /*label=*/"SurfaceContext_ReadPixelsWithCopyWholeSrc");
236 } else {
237 auto srcRect = SkIRect::MakePtSize(pt, dst.dimensions());
238 copy = GrSurfaceProxy::Copy(fContext,
239 std::move(srcProxy),
240 this->origin(),
241 kMipMapped,
242 srcRect,
243 kFit,
244 kBudgeted,
245 /*label=*/"SurfaceContext_ReadPixels",
246 restrictions.fRectsMustMatch);
247 pt = {0, 0};
248 }
249 if (!copy) {
250 return false;
251 }
252 GrSurfaceProxyView view{std::move(copy), this->origin(), this->readSwizzle()};
253 tempCtx = dContext->priv().makeSC(std::move(view), this->colorInfo());
254 SkASSERT(tempCtx);
255 }
256 return tempCtx->readPixels(dContext, dst, pt);
257 }
258
259 bool flip = this->origin() == kBottomLeft_GrSurfaceOrigin;
260
261 auto supportedRead = caps->supportedReadPixelsColorType(
262 this->colorInfo().colorType(), srcProxy->backendFormat(), dst.colorType());
263
264 bool makeTight =
265 !caps->readPixelsRowBytesSupport() && dst.rowBytes() != dst.info().minRowBytes();
266
267 bool convert = unpremul || premul || needColorConversion || flip || makeTight ||
268 (dst.colorType() != supportedRead.fColorType);
269
270 std::unique_ptr<char[]> tmpPixels;
271 GrPixmap tmp;
272 void* readDst = dst.addr();
273 size_t readRB = dst.rowBytes();
274 if (convert) {
275 GrImageInfo tmpInfo(supportedRead.fColorType,
276 this->colorInfo().alphaType(),
277 this->colorInfo().refColorSpace(),
278 dst.dimensions());
279 size_t tmpRB = tmpInfo.minRowBytes();
•280 SkSafeMath safe;
281 size_t size = safe.mul(tmpRB, tmpInfo.height());
282 if (!safe.ok()) {
283 return false;
284 }
285 // Chrome MSAN bots require the data to be initialized (hence the ()).
286 tmpPixels = std::make_unique<char[]>(size);
287 tmp = {tmpInfo, tmpPixels.get(), tmpRB};
288
289 readDst = tmpPixels.get();
290 readRB = tmpRB;
291 pt.fY = flip ? srcSurface->height() - pt.fY - dst.height() : pt.fY;
292 }
293
294 dContext->priv().flushSurface(srcProxy.get());
295 dContext->submit();
296 if (!dContext->priv().getGpu()->readPixels(srcSurface,
297 SkIRect::MakePtSize(pt, dst.dimensions()),
298 this->colorInfo().colorType(),
299 supportedRead.fColorType,
300 readDst,
301 readRB)) {
302 return false;
303 }
304
305 if (tmp.hasPixels()) {
306 return GrConvertPixels(dst, tmp, flip);
307 }
308 return true;
309 }
310
311 bool SurfaceContext::writePixels(GrDirectContext* dContext,
312 GrCPixmap src,
313 SkIPoint dstPt) {
314 ASSERT_SINGLE_OWNER
315 RETURN_FALSE_IF_ABANDONED
316 SkDEBUGCODE(this->validate();)
317
318 src = src.clip(this->dimensions(), &dstPt);
319 if (!src.hasPixels()) {
320 return false;
321 }
322 if (!src.info().bpp() || src.rowBytes() % src.info().bpp()) {
323 return false;
324 }
325 return this->internalWritePixels(dContext, &src, 1, dstPt);
326 }
327
328 bool SurfaceContext::writePixels(GrDirectContext* dContext,
329 const GrCPixmap src[],
330 int numLevels) {
331 ASSERT_SINGLE_OWNER
332 RETURN_FALSE_IF_ABANDONED
333 SkDEBUGCODE(this->validate();)
334
335 SkASSERT(dContext);
336 SkASSERT(numLevels >= 1);
337 SkASSERT(src);
338
339 if (numLevels == 1) {
340 if (src->dimensions() != this->dimensions()) {
341 return false;
342 }
343 return this->writePixels(dContext, src[0], {0, 0});
344 }
345 if (!this->asTextureProxy() ||
346 this->asTextureProxy()->proxyMipmapped() == skgpu::Mipmapped::kNo) {
347 return false;
348 }
349
350 SkISize dims = this->dimensions();
351 if (numLevels != SkMipmap::ComputeLevelCount(dims) + 1) {
352 return false;
353 }
354 for (int i = 0; i < numLevels; ++i) {
355 if (src[i].colorInfo() != src[0].colorInfo()) {
356 return false;
357 }
358 if (dims != src[i].dimensions()) {
359 return false;
360 }
361 if (!src[i].info().bpp() || src[i].rowBytes() % src[i].info().bpp()) {
362 return false;
363 }
364 dims = {std::max(1, dims.width()/2), std::max(1, dims.height()/2)};
365 }
366 return this->internalWritePixels(dContext, src, numLevels, {0, 0});
367 }
368
369 bool SurfaceContext::internalWritePixels(GrDirectContext* dContext,
370 const GrCPixmap src[],
371 int numLevels,
372 SkIPoint pt) {
373 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceContext", "internalWritePixels", fContext);
374
375 SkASSERT(numLevels >= 1);
376 SkASSERT(src);
377
378 // We can either write to a subset or write MIP levels, but not both.
379 SkASSERT((src[0].dimensions() == this->dimensions() && pt.isZero()) || numLevels == 1);
380 SkASSERT(numLevels == 1 || (this->asTextureProxy() &&
381 this->asTextureProxy()->mipmapped() == skgpu::Mipmapped::kYes));
382 // Our public caller should have clipped to the bounds of the surface already.
383 SkASSERT(SkIRect::MakeSize(this->dimensions()).contains(
384 SkIRect::MakePtSize(pt, src[0].dimensions())));
385
386 if (!dContext) {
387 return false;
388 }
389
390 if (this->asSurfaceProxy()->readOnly()) {
391 return false;
392 }
393
394 if (src[0].colorType() == GrColorType::kUnknown) {
395 return false;
396 }
397
398 if (!alpha_types_compatible(src[0].alphaType(), this->colorInfo().alphaType())) {
399 return false;
400 }
401
402 GrSurfaceProxy* dstProxy = this->asSurfaceProxy();
403
404 if (dstProxy->framebufferOnly()) {
405 return false;
406 }
407
408 if (!dstProxy->instantiate(dContext->priv().resourceProvider())) {
409 return false;
410 }
411
412 GrSurface* dstSurface = dstProxy->peekSurface();
413
414 SkColorSpaceXformSteps::Flags flags =
415 SkColorSpaceXformSteps{src[0].colorInfo(), this->colorInfo()}.fFlags;
416 bool unpremul = flags.unpremul,
417 needColorConversion = flags.linearize || flags.gamut_transform || flags.encode,
418 premul = flags.premul;
419
420 const GrCaps* caps = dContext->priv().caps();
421
422 auto rgbaDefaultFormat = caps->getDefaultBackendFormat(GrColorType::kRGBA_8888,
423 GrRenderable::kNo);
424
425 GrColorType dstColorType = this->colorInfo().colorType();
426 // For canvas2D putImageData performance we have a special code path for unpremul RGBA_8888 srcs
427 // that are premultiplied on the GPU. This is kept as narrow as possible for now.
428 bool canvas2DFastPath = !caps->avoidWritePixelsFastPath() && premul && !needColorConversion &&
429 (src[0].colorType() == GrColorType::kRGBA_8888 ||
430 src[0].colorType() == GrColorType::kBGRA_8888) &&
431 this->asFillContext() &&
432 (dstColorType == GrColorType::kRGBA_8888 ||
433 dstColorType == GrColorType::kBGRA_8888) &&
434 rgbaDefaultFormat.isValid() &&
435 dContext->priv().validPMUPMConversionExists();
436
437 // Since the validPMUPMConversionExists function actually submits work to the gpu to do its
438 // tests, it is possible that during that call we have abanoned the context. Thus we do an
439 // abanoned check here to make sure we are still valid.
440 RETURN_FALSE_IF_ABANDONED
441
442 // Drawing code path doesn't support writing to levels and doesn't support inserting layout
443 // transitions.
444 if ((!caps->surfaceSupportsWritePixels(dstSurface) || canvas2DFastPath) && numLevels == 1) {
445 GrColorInfo tempColorInfo;
446 GrBackendFormat format;
447 skgpu::Swizzle tempReadSwizzle;
448 if (canvas2DFastPath) {
449 tempColorInfo = {GrColorType::kRGBA_8888,
450 kUnpremul_SkAlphaType,
451 this->colorInfo().refColorSpace()};
452 format = rgbaDefaultFormat;
453 } else {
454 tempColorInfo = this->colorInfo();
455 format = dstProxy->backendFormat().makeTexture2D();
456 if (!format.isValid()) {
457 return false;
458 }
459 tempReadSwizzle = this->readSwizzle();
460 }
461
462 // It is more efficient for us to write pixels into a top left origin so we prefer that.
463 // However, if the final proxy isn't a render target then we must use a copy to move the
464 // data into it which requires the origins to match. If the final proxy is a render target
465 // we can use a draw instead which doesn't have this origin restriction. Thus for render
466 // targets we will use top left and otherwise we will make the origins match.
467 GrSurfaceOrigin tempOrigin =
468 this->asFillContext() ? kTopLeft_GrSurfaceOrigin : this->origin();
469 auto tempProxy = dContext->priv().proxyProvider()->createProxy(
470 format,
471 src[0].dimensions(),
472 GrRenderable::kNo,
473 1,
474 skgpu::Mipmapped::kNo,
475 SkBackingFit::kApprox,
476 skgpu::Budgeted::kYes,
477 GrProtected::kNo,
478 /*label=*/"SurfaceContext_InternalWritePixels");
479 if (!tempProxy) {
480 return false;
481 }
482 GrSurfaceProxyView tempView(tempProxy, tempOrigin, tempReadSwizzle);
483 SurfaceContext tempCtx(dContext, tempView, tempColorInfo);
484
485 // In the fast path we always write the srcData to the temp context as though it were RGBA.
486 // When the data is really BGRA the write will cause the R and B channels to be swapped in
487 // the intermediate surface which gets corrected by a swizzle effect when drawing to the
488 // dst.
489 GrCPixmap origSrcBase = src[0];
490 GrCPixmap srcBase = origSrcBase;
491 if (canvas2DFastPath) {
492 srcBase = GrCPixmap(origSrcBase.info().makeColorType(GrColorType::kRGBA_8888),
493 origSrcBase.addr(),
494 origSrcBase.rowBytes());
495 }
496 if (!tempCtx.writePixels(dContext, srcBase, {0, 0})) {
497 return false;
498 }
499
500 if (this->asFillContext()) {
501 std::unique_ptr<GrFragmentProcessor> fp;
502 if (canvas2DFastPath) {
503 fp = dContext->priv().createUPMToPMEffect(
504 GrTextureEffect::Make(std::move(tempView), tempColorInfo.alphaType()));
505 // Important: check the original src color type here!
506 if (origSrcBase.colorType() == GrColorType::kBGRA_8888) {
507 fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), skgpu::Swizzle::BGRA());
508 }
509 } else {
510 fp = GrTextureEffect::Make(std::move(tempView), tempColorInfo.alphaType());
511 }
512 if (!fp) {
513 return false;
514 }
515 this->asFillContext()->fillRectToRectWithFP(
516 SkIRect::MakeSize(srcBase.dimensions()),
517 SkIRect::MakePtSize(pt, srcBase.dimensions()),
518 std::move(fp));
519 } else {
520 SkIRect srcRect = SkIRect::MakeSize(srcBase.dimensions());
521 SkIPoint dstPoint = SkIPoint::Make(pt.fX, pt.fY);
522 if (!this->copy(std::move(tempProxy), srcRect, dstPoint)) {
523 return false;
524 }
525 }
526 return true;
527 }
528
529 GrColorType srcColorType = src[0].colorType();
530 auto [allowedColorType, _] =
531 caps->supportedWritePixelsColorType(this->colorInfo().colorType(),
532 dstProxy->backendFormat(),
533 srcColorType);
534 bool flip = this->origin() == kBottomLeft_GrSurfaceOrigin;
535
536 bool convertAll = premul ||
537 unpremul ||
538 needColorConversion ||
539 flip ||
540 (srcColorType != allowedColorType);
541 bool mustBeTight = !caps->writePixelsRowBytesSupport();
542 size_t tmpSize = 0;
543 if (mustBeTight || convertAll) {
•544 SkSafeMath safe;
545 for (int i = 0; i < numLevels; ++i) {
546 if (convertAll || (mustBeTight && src[i].rowBytes() != src[i].info().minRowBytes())) {
•547 size_t minRowBytes = src[i].info().makeColorType(allowedColorType).minRowBytes();
548 size_t levelSize = safe.mul(minRowBytes, src[i].height());
549 tmpSize = safe.add(tmpSize, levelSize);
550 }
551 }
•552 if (!safe.ok()) {
553 return false;
554 }
555 }
556
557 auto tmpData = tmpSize ? SkData::MakeUninitialized(tmpSize) : nullptr;
•558 if (tmpSize && !tmpData) {
559 return false;
560 }
561 void* tmp = tmpSize ? tmpData->writable_data() : nullptr;
562 AutoSTArray<15, GrMipLevel> srcLevels(numLevels);
563 bool ownAllStorage = true;
564 for (int i = 0; i < numLevels; ++i) {
565 if (convertAll || (mustBeTight && src[i].rowBytes() != src[i].info().minRowBytes())) {
566 GrImageInfo tmpInfo(allowedColorType,
567 this->colorInfo().alphaType(),
568 this->colorInfo().refColorSpace(),
569 src[i].dimensions());
570 auto tmpRB = tmpInfo.minRowBytes();
571 GrPixmap tmpPM(tmpInfo, tmp, tmpRB);
572 SkAssertResult(GrConvertPixels(tmpPM, src[i], flip));
573 srcLevels[i] = {tmpPM.addr(), tmpPM.rowBytes(), tmpData};
574 tmp = SkTAddOffset<void>(tmp, tmpRB*tmpPM.height());
575 } else {
576 srcLevels[i] = {src[i].addr(), src[i].rowBytes(), src[i].pixelStorage()};
577 ownAllStorage &= src[i].ownsPixels();
578 }
579 }
580 pt.fY = flip ? dstSurface->height() - pt.fY - src[0].height() : pt.fY;
581
582 if (!dContext->priv().drawingManager()->newWritePixelsTask(
583 sk_ref_sp(dstProxy),
584 SkIRect::MakePtSize(pt, src[0].dimensions()),
585 allowedColorType,
586 this->colorInfo().colorType(),
587 srcLevels.begin(),
588 numLevels)) {
589 return false;
590 }
591 if (numLevels > 1) {
592 dstProxy->asTextureProxy()->markMipmapsClean();
593 }
594 if (!ownAllStorage) {
595 // If any pixmap doesn't own its pixels then we must flush so that the pixels are pushed to
596 // the GPU before we return.
597 dContext->priv().flushSurface(dstProxy);
598 }
599 return true;
600 }
601
602 void SurfaceContext::asyncRescaleAndReadPixels(GrDirectContext* dContext,
603 const SkImageInfo& info,
604 const SkIRect& srcRect,
605 RescaleGamma rescaleGamma,
606 RescaleMode rescaleMode,
607 ReadPixelsCallback callback,
608 ReadPixelsContext callbackContext) {
609 if (!dContext) {
610 callback(callbackContext, nullptr);
611 return;
612 }
613 auto rt = this->asRenderTargetProxy();
614 if (rt && rt->wrapsVkSecondaryCB()) {
615 callback(callbackContext, nullptr);
616 return;
617 }
618 if (rt && rt->framebufferOnly()) {
619 callback(callbackContext, nullptr);
620 return;
621 }
622 auto dstCT = SkColorTypeToGrColorType(info.colorType());
623 if (dstCT == GrColorType::kUnknown) {
624 callback(callbackContext, nullptr);
625 return;
626 }
627 bool needsRescale = srcRect.size() != info.dimensions() ||
628 this->origin() == kBottomLeft_GrSurfaceOrigin ||
629 this->colorInfo().alphaType() != info.alphaType() ||
630 !SkColorSpace::Equals(this->colorInfo().colorSpace(), info.colorSpace());
631 auto surfaceBackendFormat = this->asSurfaceProxy()->backendFormat();
632 auto readInfo = this->caps()->supportedReadPixelsColorType(this->colorInfo().colorType(),
633 surfaceBackendFormat,
634 dstCT);
635 // Fail if we can't read from the source surface's color type.
636 if (readInfo.fColorType == GrColorType::kUnknown) {
637 callback(callbackContext, nullptr);
638 return;
639 }
640 // Fail if read color type does not have all of dstCT's color channels and those missing color
641 // channels are in the src.
642 uint32_t dstChannels = GrColorTypeChannelFlags(dstCT);
643 uint32_t legalReadChannels = GrColorTypeChannelFlags(readInfo.fColorType);
644 uint32_t srcChannels = GrColorTypeChannelFlags(this->colorInfo().colorType());
645 if ((~legalReadChannels & dstChannels) & srcChannels) {
646 callback(callbackContext, nullptr);
647 return;
648 }
649
650 std::unique_ptr<SurfaceFillContext> tempFC;
651 int x = srcRect.fLeft;
652 int y = srcRect.fTop;
653 if (needsRescale) {
654 auto tempInfo = GrImageInfo(info).makeColorType(this->colorInfo().colorType());
655 tempFC = this->rescale(tempInfo, kTopLeft_GrSurfaceOrigin, srcRect,
656 rescaleGamma, rescaleMode);
657 if (!tempFC) {
658 callback(callbackContext, nullptr);
659 return;
660 }
661 SkASSERT(SkColorSpace::Equals(tempFC->colorInfo().colorSpace(), info.colorSpace()));
662 SkASSERT(tempFC->origin() == kTopLeft_GrSurfaceOrigin);
663 x = y = 0;
664 }
665 auto srcCtx = tempFC ? tempFC.get() : this;
666 return srcCtx->asyncReadPixels(dContext,
667 SkIRect::MakePtSize({x, y}, info.dimensions()),
668 info.colorType(),
669 callback,
670 callbackContext);
671 }
672
673 void SurfaceContext::asyncReadPixels(GrDirectContext* dContext,
674 const SkIRect& rect,
675 SkColorType colorType,
676 ReadPixelsCallback callback,
677 ReadPixelsContext callbackContext) {
678 using AsyncReadResult = skgpu::TAsyncReadResult<GrGpuBuffer, GrDirectContext::DirectContextID,
679 PixelTransferResult>;
680
681 SkASSERT(rect.fLeft >= 0 && rect.fRight <= this->width());
682 SkASSERT(rect.fTop >= 0 && rect.fBottom <= this->height());
683
684 if (!dContext || this->asSurfaceProxy()->isProtected() == GrProtected::kYes) {
685 callback(callbackContext, nullptr);
686 return;
687 }
688
689 auto mappedBufferManager = dContext->priv().clientMappedBufferManager();
690
691 auto transferResult = this->transferPixels(SkColorTypeToGrColorType(colorType), rect);
692
693 if (!transferResult.fTransferBuffer) {
694 auto ii = SkImageInfo::Make(rect.size(), colorType, this->colorInfo().alphaType(),
695 this->colorInfo().refColorSpace());
696 static const GrDirectContext::DirectContextID kInvalid;
697 auto result = std::make_unique<AsyncReadResult>(kInvalid);
698 GrPixmap pm = GrPixmap::Allocate(ii);
699 result->addCpuPlane(pm.pixelStorage(), pm.rowBytes());
700
701 SkIPoint pt{rect.fLeft, rect.fTop};
702 if (!this->readPixels(dContext, pm, pt)) {
703 callback(callbackContext, nullptr);
704 return;
705 }
706 callback(callbackContext, std::move(result));
707 return;
708 }
709
710 struct FinishContext {
711 ReadPixelsCallback* fClientCallback;
712 ReadPixelsContext fClientContext;
713 SkISize fSize;
714 GrClientMappedBufferManager* fMappedBufferManager;
715 PixelTransferResult fTransferResult;
716 };
717 // Assumption is that the caller would like to flush. We could take a parameter or require an
718 // explicit flush from the caller. We'd have to have a way to defer attaching the finish
719 // callback to GrGpu until after the next flush that flushes our op list, though.
720 auto* finishContext = new FinishContext{callback,
721 callbackContext,
722 rect.size(),
723 mappedBufferManager,
724 std::move(transferResult)};
725 auto finishCallback = [](GrGpuFinishedContext c) {
726 const auto* context = reinterpret_cast<const FinishContext*>(c);
727 auto manager = context->fMappedBufferManager;
728 auto result = std::make_unique<AsyncReadResult>(manager->ownerID());
729 if (!result->addTransferResult(context->fTransferResult,
730 context->fSize,
731 context->fTransferResult.fRowBytes,
732 manager)) {
733 result.reset();
734 }
735 (*context->fClientCallback)(context->fClientContext, std::move(result));
736 delete context;
737 };
738 GrFlushInfo flushInfo;
739 flushInfo.fFinishedContext = finishContext;
740 flushInfo.fFinishedProc = finishCallback;
741
742 dContext->priv().flushSurface(
743 this->asSurfaceProxy(), SkSurfaces::BackendSurfaceAccess::kNoAccess, flushInfo);
744 }
745
746 void SurfaceContext::asyncRescaleAndReadPixelsYUV420(GrDirectContext* dContext,
747 SkYUVColorSpace yuvColorSpace,
748 bool readAlpha,
749 sk_sp<SkColorSpace> dstColorSpace,
750 const SkIRect& srcRect,
751 SkISize dstSize,
752 RescaleGamma rescaleGamma,
753 RescaleMode rescaleMode,
754 ReadPixelsCallback callback,
755 ReadPixelsContext callbackContext) {
756 using AsyncReadResult = skgpu::TAsyncReadResult<GrGpuBuffer, GrDirectContext::DirectContextID,
757 PixelTransferResult>;
758
759 SkASSERT(srcRect.fLeft >= 0 && srcRect.fRight <= this->width());
760 SkASSERT(srcRect.fTop >= 0 && srcRect.fBottom <= this->height());
761 SkASSERT(!dstSize.isZero());
762 SkASSERT((dstSize.width() % 2 == 0) && (dstSize.height() % 2 == 0));
763
764 if (!dContext) {
765 callback(callbackContext, nullptr);
766 return;
767 }
768 auto rt = this->asRenderTargetProxy();
769 if (rt && rt->wrapsVkSecondaryCB()) {
770 callback(callbackContext, nullptr);
771 return;
772 }
773 if (rt && rt->framebufferOnly()) {
774 callback(callbackContext, nullptr);
775 return;
776 }
777 if (this->asSurfaceProxy()->isProtected() == GrProtected::kYes) {
778 callback(callbackContext, nullptr);
779 return;
780 }
781 int x = srcRect.fLeft;
782 int y = srcRect.fTop;
783 bool needsRescale = srcRect.size() != dstSize ||
784 !SkColorSpace::Equals(this->colorInfo().colorSpace(), dstColorSpace.get());
785 GrSurfaceProxyView srcView = this->readSurfaceView();
786 if (needsRescale) {
787 auto info = SkImageInfo::Make(dstSize,
788 kRGBA_8888_SkColorType,
789 this->colorInfo().alphaType(),
790 dstColorSpace);
791 // TODO: Incorporate the YUV conversion into last pass of rescaling.
792 auto tempFC = this->rescale(info,
793 kTopLeft_GrSurfaceOrigin,
794 srcRect,
795 rescaleGamma,
796 rescaleMode);
797 if (!tempFC) {
798 callback(callbackContext, nullptr);
799 return;
800 }
801 SkASSERT(SkColorSpace::Equals(tempFC->colorInfo().colorSpace(), info.colorSpace()));
802 SkASSERT(tempFC->origin() == kTopLeft_GrSurfaceOrigin);
803 x = y = 0;
804 srcView = tempFC->readSurfaceView();
805 } else if (!srcView.asTextureProxy()) {
806 srcView = GrSurfaceProxyView::Copy(
807 fContext,
808 std::move(srcView),
809 skgpu::Mipmapped::kNo,
810 srcRect,
811 SkBackingFit::kApprox,
812 skgpu::Budgeted::kYes,
813 /*label=*/"SurfaceContext_AsyncRescaleAndReadPixelsYUV420");
814 if (!srcView) {
815 // If we can't get a texture copy of the contents then give up.
816 callback(callbackContext, nullptr);
817 return;
818 }
819 SkASSERT(srcView.asTextureProxy());
820 x = y = 0;
821 }
822
823 auto yaInfo = SkImageInfo::MakeA8(dstSize);
824 auto yFC = dContext->priv().makeSFCWithFallback(yaInfo, SkBackingFit::kApprox,
825 /* sampleCount= */ 1,
826 skgpu::Mipmapped::kNo, skgpu::Protected::kNo);
827 std::unique_ptr<SurfaceFillContext> aFC;
828 if (readAlpha) {
829 aFC = dContext->priv().makeSFCWithFallback(yaInfo, SkBackingFit::kApprox,
830 /* sampleCount= */ 1,
831 skgpu::Mipmapped::kNo, skgpu::Protected::kNo);
832 }
833
834 auto uvInfo = yaInfo.makeWH(yaInfo.width()/2, yaInfo.height()/2);
835 auto uFC = dContext->priv().makeSFCWithFallback(uvInfo, SkBackingFit::kApprox,
836 /* sampleCount= */ 1,
837 skgpu::Mipmapped::kNo, skgpu::Protected::kNo);
838 auto vFC = dContext->priv().makeSFCWithFallback(uvInfo, SkBackingFit::kApprox,
839 /* sampleCount= */ 1,
840 skgpu::Mipmapped::kNo, skgpu::Protected::kNo);
841
842 if (!yFC || !uFC || !vFC || (readAlpha && !aFC)) {
843 callback(callbackContext, nullptr);
844 return;
845 }
846
847 float baseM[20];
848 SkColorMatrix_RGB2YUV(yuvColorSpace, baseM);
849
850 // TODO: Use one transfer buffer for all three planes to reduce map/unmap cost?
851
852 auto texMatrix = SkMatrix::Translate(x, y);
853
854 auto [readCT, offsetAlignment] =
855 this->caps()->supportedReadPixelsColorType(yFC->colorInfo().colorType(),
856 yFC->asSurfaceProxy()->backendFormat(),
857 GrColorType::kAlpha_8);
858 if (readCT == GrColorType::kUnknown) {
859 callback(callbackContext, nullptr);
860 return;
861 }
862 bool doSynchronousRead = !this->caps()->transferFromSurfaceToBufferSupport() ||
863 !offsetAlignment;
864 PixelTransferResult yTransfer, aTransfer, uTransfer, vTransfer;
865
866 // This matrix generates (r,g,b,a) = (0, 0, 0, y)
867 float yM[20];
868 std::fill_n(yM, 15, 0.f);
869 std::copy_n(baseM + 0, 5, yM + 15);
870
871 auto yFP = GrTextureEffect::Make(srcView, this->colorInfo().alphaType(), texMatrix);
872 yFP = GrFragmentProcessor::ColorMatrix(std::move(yFP),
873 yM,
874 /*unpremulInput=*/false,
875 /*clampRGBOutput=*/true,
876 /*premulOutput=*/false);
877 yFC->fillWithFP(std::move(yFP));
878 if (!doSynchronousRead) {
879 yTransfer = yFC->transferPixels(GrColorType::kAlpha_8,
880 SkIRect::MakeSize(yFC->dimensions()));
881 if (!yTransfer.fTransferBuffer) {
882 callback(callbackContext, nullptr);
883 return;
884 }
885 }
886
887 if (readAlpha) {
888 auto aFP = GrTextureEffect::Make(srcView, this->colorInfo().alphaType(), texMatrix);
889 SkASSERT(baseM[15] == 0 &&
890 baseM[16] == 0 &&
891 baseM[17] == 0 &&
892 baseM[18] == 1 &&
893 baseM[19] == 0);
894 aFC->fillWithFP(std::move(aFP));
895 if (!doSynchronousRead) {
896 aTransfer = aFC->transferPixels(GrColorType::kAlpha_8,
897 SkIRect::MakeSize(aFC->dimensions()));
898 if (!aTransfer.fTransferBuffer) {
899 callback(callbackContext, nullptr);
900 return;
901 }
902 }
903 }
904
905 texMatrix.preScale(2.f, 2.f);
906 // This matrix generates (r,g,b,a) = (0, 0, 0, u)
907 float uM[20];
908 std::fill_n(uM, 15, 0.f);
909 std::copy_n(baseM + 5, 5, uM + 15);
910
911 auto uFP = GrTextureEffect::Make(srcView,
912 this->colorInfo().alphaType(),
913 texMatrix,
914 GrSamplerState::Filter::kLinear);
915 uFP = GrFragmentProcessor::ColorMatrix(std::move(uFP),
916 uM,
917 /*unpremulInput=*/false,
918 /*clampRGBOutput=*/true,
919 /*premulOutput=*/false);
920 uFC->fillWithFP(std::move(uFP));
921 if (!doSynchronousRead) {
922 uTransfer = uFC->transferPixels(GrColorType::kAlpha_8,
923 SkIRect::MakeSize(uFC->dimensions()));
924 if (!uTransfer.fTransferBuffer) {
925 callback(callbackContext, nullptr);
926 return;
927 }
928 }
929
930 // This matrix generates (r,g,b,a) = (0, 0, 0, v)
931 float vM[20];
932 std::fill_n(vM, 15, 0.f);
933 std::copy_n(baseM + 10, 5, vM + 15);
934 auto vFP = GrTextureEffect::Make(std::move(srcView),
935 this->colorInfo().alphaType(),
936 texMatrix,
937 GrSamplerState::Filter::kLinear);
938 vFP = GrFragmentProcessor::ColorMatrix(std::move(vFP),
939 vM,
940 /*unpremulInput=*/false,
941 /*clampRGBOutput=*/true,
942 /*premulOutput=*/false);
943 vFC->fillWithFP(std::move(vFP));
944
945 if (!doSynchronousRead) {
946 vTransfer = vFC->transferPixels(GrColorType::kAlpha_8,
947 SkIRect::MakeSize(vFC->dimensions()));
948 if (!vTransfer.fTransferBuffer) {
949 callback(callbackContext, nullptr);
950 return;
951 }
952 }
953
954 if (doSynchronousRead) {
955 GrPixmap yPmp = GrPixmap::Allocate(yaInfo);
956 GrPixmap uPmp = GrPixmap::Allocate(uvInfo);
957 GrPixmap vPmp = GrPixmap::Allocate(uvInfo);
958 GrPixmap aPmp;
959 if (readAlpha) {
960 aPmp = GrPixmap::Allocate(yaInfo);
961 }
962 if (!yFC->readPixels(dContext, yPmp, {0, 0}) ||
963 !uFC->readPixels(dContext, uPmp, {0, 0}) ||
964 !vFC->readPixels(dContext, vPmp, {0, 0}) ||
965 (readAlpha && !aFC->readPixels(dContext, aPmp, {0, 0}))) {
966 callback(callbackContext, nullptr);
967 return;
968 }
969 auto result = std::make_unique<AsyncReadResult>(dContext->directContextID());
970 result->addCpuPlane(yPmp.pixelStorage(), yPmp.rowBytes());
971 result->addCpuPlane(uPmp.pixelStorage(), uPmp.rowBytes());
972 result->addCpuPlane(vPmp.pixelStorage(), vPmp.rowBytes());
973 if (readAlpha) {
974 result->addCpuPlane(aPmp.pixelStorage(), aPmp.rowBytes());
975 }
976 callback(callbackContext, std::move(result));
977 return;
978 }
979
980 struct FinishContext {
981 ReadPixelsCallback* fClientCallback;
982 ReadPixelsContext fClientContext;
983 GrClientMappedBufferManager* fMappedBufferManager;
984 SkISize fSize;
985 PixelTransferResult fYTransfer;
986 PixelTransferResult fUTransfer;
987 PixelTransferResult fVTransfer;
988 PixelTransferResult fATransfer;
989 };
990 // Assumption is that the caller would like to flush. We could take a parameter or require an
991 // explicit flush from the caller. We'd have to have a way to defer attaching the finish
992 // callback to GrGpu until after the next flush that flushes our op list, though.
993 auto* finishContext = new FinishContext{callback,
994 callbackContext,
995 dContext->priv().clientMappedBufferManager(),
996 dstSize,
997 std::move(yTransfer),
998 std::move(uTransfer),
999 std::move(vTransfer),
1000 std::move(aTransfer)};
1001 auto finishCallback = [](GrGpuFinishedContext c) {
1002 const auto* context = reinterpret_cast<const FinishContext*>(c);
1003 auto manager = context->fMappedBufferManager;
1004 auto result = std::make_unique<AsyncReadResult>(manager->ownerID());
1005 if (!result->addTransferResult(context->fYTransfer,
1006 context->fSize,
1007 context->fYTransfer.fRowBytes,
1008 manager)) {
1009 (*context->fClientCallback)(context->fClientContext, nullptr);
1010 delete context;
1011 return;
1012 }
1013 SkISize uvSize = {context->fSize.width() / 2, context->fSize.height() / 2};
1014 if (!result->addTransferResult(context->fUTransfer,
1015 uvSize,
1016 context->fUTransfer.fRowBytes,
1017 manager)) {
1018 (*context->fClientCallback)(context->fClientContext, nullptr);
1019 delete context;
1020 return;
1021 }
1022 if (!result->addTransferResult(context->fVTransfer,
1023 uvSize,
1024 context->fVTransfer.fRowBytes,
1025 manager)) {
1026 (*context->fClientCallback)(context->fClientContext, nullptr);
1027 delete context;
1028 return;
1029 }
1030 if (context->fATransfer.fTransferBuffer &&
1031 !result->addTransferResult(context->fATransfer,
1032 context->fSize,
1033 context->fATransfer.fRowBytes,
1034 manager)) {
1035 (*context->fClientCallback)(context->fClientContext, nullptr);
1036 delete context;
1037 return;
1038 }
1039 (*context->fClientCallback)(context->fClientContext, std::move(result));
1040 delete context;
1041 };
1042 GrFlushInfo flushInfo;
1043 flushInfo.fFinishedContext = finishContext;
1044 flushInfo.fFinishedProc = finishCallback;
1045 dContext->priv().flushSurface(
1046 this->asSurfaceProxy(), SkSurfaces::BackendSurfaceAccess::kNoAccess, flushInfo);
1047 }
1048
1049 sk_sp<GrRenderTask> SurfaceContext::copy(sk_sp<GrSurfaceProxy> src,
1050 SkIRect srcRect,
1051 SkIPoint dstPoint) {
1052 if (!GrClipSrcRectAndDstPoint(this->dimensions(), &dstPoint,
1053 src->dimensions(), &srcRect)) {
1054 return nullptr;
1055 }
1056
1057 SkIRect dstRect = SkIRect::MakePtSize(dstPoint, srcRect.size());
1058 return this->copyScaled(src, srcRect, dstRect, GrSamplerState::Filter::kNearest);
1059 }
1060
1061 sk_sp<GrRenderTask> SurfaceContext::copyScaled(sk_sp<GrSurfaceProxy> src,
1062 SkIRect srcRect,
1063 SkIRect dstRect,
1064 GrSamplerState::Filter filter) {
1065 ASSERT_SINGLE_OWNER
1066 RETURN_NULLPTR_IF_ABANDONED
1067 SkDEBUGCODE(this->validate();)
1068 GR_CREATE_TRACE_MARKER_CONTEXT("SurfaceContext", "copyScaled", fContext);
1069
1070 const GrCaps* caps = fContext->priv().caps();
1071
1072 if (this->asSurfaceProxy()->framebufferOnly()) {
1073 return nullptr;
1074 }
1075
1076 // canCopySurface() verifies that src and dst rects are contained in their surfaces.
1077 if (!caps->canCopySurface(this->asSurfaceProxy(), dstRect, src.get(), srcRect)) {
1078 return nullptr;
1079 }
1080
1081 if (filter == GrSamplerState::Filter::kLinear && !src->isFunctionallyExact()) {
1082 // If we're linear filtering an image that is approx-sized, there are cases where the filter
1083 // could sample outside the logical dimensions. Specifically if we're upscaling along an
1084 // axis where we are copying up to the logical dimension, but that dimension is less than
1085 // the actual backing store dimension, the linear filter will access one texel beyond the
1086 // logical size, potentially incorporating undefined values.
1087 // NOTE: Identity scales that sample along the logical boundary of an approxi-fit texture
1088 // can still technically access a row or column of undefined data (albeit with a weight that
1089 // *should* be zero). We also disallow copying with linear filtering in that scenario,
1090 // just in case.
1091 #if defined(SK_USE_SAFE_INSET_FOR_TEXTURE_SAMPLING)
1092 const bool upscalingXAtApproxEdge =
1093 dstRect.width() >= srcRect.width() &&
1094 srcRect.fRight == src->width() &&
1095 srcRect.fRight < src->backingStoreDimensions().width();
1096 const bool upscalingYAtApproxEdge =
1097 dstRect.height() >= srcRect.height() &&
1098 srcRect.fBottom == src->height() &&
1099 srcRect.fBottom < src->backingStoreDimensions().height();
1100 #else
1101 // In this mode we allow non-scaling copies through even if the linear filtering would
1102 // access the adjacent undefined row or column.
1103 const bool upscalingXAtApproxEdge =
1104 dstRect.width() > srcRect.width() &&
1105 srcRect.fRight == src->width() &&
1106 srcRect.fRight < src->backingStoreDimensions().width();
1107 const bool upscalingYAtApproxEdge =
1108 dstRect.height() > srcRect.height() &&
1109 srcRect.fBottom == src->height() &&
1110 srcRect.fBottom < src->backingStoreDimensions().height();
1111 #endif
1112 if (upscalingXAtApproxEdge || upscalingYAtApproxEdge) {
1113 return nullptr;
1114 }
1115
1116 // NOTE: Any upscaling with the linear filter will include content that's 1px outside the
1117 // src rect, but as long as that's still within the logical dimensions we assume it's okay.
1118 }
1119
1120 SkASSERT(src->backendFormat().textureType() != GrTextureType::kExternal);
1121 SkASSERT(src->backendFormat() == this->asSurfaceProxy()->backendFormat());
1122 return this->drawingManager()->newCopyRenderTask(this->asSurfaceProxyRef(),
1123 dstRect,
1124 std::move(src),
1125 srcRect,
1126 filter,
1127 this->origin());
1128 }
1129
1130 std::unique_ptr<SurfaceFillContext> SurfaceContext::rescale(const GrImageInfo& info,
1131 GrSurfaceOrigin origin,
1132 SkIRect srcRect,
1133 RescaleGamma rescaleGamma,
1134 RescaleMode rescaleMode) {
1135 auto sfc = fContext->priv().makeSFCWithFallback(info,
1136 SkBackingFit::kExact,
1137 /* sampleCount= */ 1,
1138 skgpu::Mipmapped::kNo,
1139 this->asSurfaceProxy()->isProtected(),
1140 origin);
1141 if (!sfc || !this->rescaleInto(sfc.get(),
1142 SkIRect::MakeSize(sfc->dimensions()),
1143 srcRect,
1144 rescaleGamma,
1145 rescaleMode)) {
1146 return nullptr;
1147 }
1148 return sfc;
1149 }
1150
1151 bool SurfaceContext::rescaleInto(SurfaceFillContext* dst,
1152 SkIRect dstRect,
1153 SkIRect srcRect,
1154 RescaleGamma rescaleGamma,
1155 RescaleMode rescaleMode) {
1156 SkASSERT(dst);
1157 if (!SkIRect::MakeSize(dst->dimensions()).contains((dstRect))) {
1158 return false;
1159 }
1160
1161 auto rtProxy = this->asRenderTargetProxy();
1162 if (rtProxy && rtProxy->wrapsVkSecondaryCB()) {
1163 return false;
1164 }
1165
1166 if (this->asSurfaceProxy()->framebufferOnly()) {
1167 return false;
1168 }
1169
1170 GrSurfaceProxyView texView = this->readSurfaceView();
1171 // If we perform scaling as draws, texView must be texturable; if it's not already, we have to
1172 // make a copy. However, if the scaling can use copyScaled(), we can avoid this copy.
1173 auto ensureTexturable = [this](GrSurfaceProxyView texView, SkIRect srcRect) {
1174 if (!texView.asTextureProxy()) {
1175 // TODO: If copying supported specifying a renderable copy then we could return the copy
1176 // when there are no other conversions.
1177 texView = GrSurfaceProxyView::Copy(fContext,
1178 std::move(texView),
1179 skgpu::Mipmapped::kNo,
1180 srcRect,
1181 SkBackingFit::kApprox,
1182 skgpu::Budgeted::kNo,
1183 "SurfaceContext_RescaleInto");
1184 if (texView) {
1185 SkASSERT(texView.asTextureProxy());
1186 srcRect = SkIRect::MakeSize(srcRect.size());
1187 }
1188 }
1189 return std::make_pair(std::move(texView), srcRect);
1190 };
1191
1192 SkISize finalSize = dstRect.size();
1193 if (finalSize == srcRect.size()) {
1194 rescaleGamma = RescaleGamma::kSrc;
1195 rescaleMode = RescaleMode::kNearest;
1196 }
1197
1198 // Within a rescaling pass A is the input (if not null) and B is the output. At the end of the
1199 // pass B is moved to A. If 'this' is the input on the first pass then tempA is null.
1200 std::unique_ptr<SurfaceFillContext> tempA;
1201 std::unique_ptr<SurfaceFillContext> tempB;
1202
1203 // Assume we should ignore the rescale linear request if the surface has no color space since
1204 // it's unclear how we'd linearize from an unknown color space.
1205 if (rescaleGamma == RescaleGamma::kLinear && this->colorInfo().colorSpace() &&
1206 !this->colorInfo().colorSpace()->gammaIsLinear()) {
1207 // Colorspace transformations are always handled by drawing so we need to be texturable
1208 std::tie(texView, srcRect) = ensureTexturable(texView, srcRect);
1209 if (!texView) {
1210 return false;
1211 }
1212 auto cs = this->colorInfo().colorSpace()->makeLinearGamma();
1213 // We'll fall back to kRGBA_8888 if half float not supported.
1214 GrImageInfo ii(GrColorType::kRGBA_F16,
1215 dst->colorInfo().alphaType(),
1216 std::move(cs),
1217 srcRect.size());
1218 auto linearRTC = fContext->priv().makeSFCWithFallback(std::move(ii),
1219 SkBackingFit::kApprox,
1220 /* sampleCount= */ 1,
1221 skgpu::Mipmapped::kNo,
1222 texView.proxy()->isProtected(),
1223 dst->origin());
1224 if (!linearRTC) {
1225 return false;
1226 }
1227 auto fp = GrTextureEffect::Make(std::move(texView),
1228 this->colorInfo().alphaType(),
1229 SkMatrix::Translate(srcRect.topLeft()),
1230 GrSamplerState::Filter::kNearest,
1231 GrSamplerState::MipmapMode::kNone);
1232 fp = GrColorSpaceXformEffect::Make(std::move(fp),
1233 this->colorInfo(),
1234 linearRTC->colorInfo());
1235 linearRTC->fillWithFP(std::move(fp));
1236 texView = linearRTC->readSurfaceView();
1237 SkASSERT(texView.asTextureProxy());
1238 tempA = std::move(linearRTC);
1239 srcRect = SkIRect::MakeSize(srcRect.size());
1240 }
1241
1242 do {
1243 SkISize nextDims = finalSize;
1244 if (rescaleMode != RescaleMode::kNearest && rescaleMode != RescaleMode::kLinear) {
1245 if (srcRect.width() > finalSize.width()) {
1246 nextDims.fWidth = std::max((srcRect.width() + 1)/2, finalSize.width());
1247 } else if (srcRect.width() < finalSize.width()) {
1248 nextDims.fWidth = std::min(srcRect.width()*2, finalSize.width());
1249 }
1250 if (srcRect.height() > finalSize.height()) {
1251 nextDims.fHeight = std::max((srcRect.height() + 1)/2, finalSize.height());
1252 } else if (srcRect.height() < finalSize.height()) {
1253 nextDims.fHeight = std::min(srcRect.height()*2, finalSize.height());
1254 }
1255 }
1256 auto input = tempA ? tempA.get() : this;
1257 sk_sp<GrColorSpaceXform> xform;
1258 SurfaceFillContext* stepDst;
1259 SkIRect stepDstRect;
1260 if (nextDims == finalSize) {
1261 stepDst = dst;
1262 stepDstRect = dstRect;
1263 xform = GrColorSpaceXform::Make(input->colorInfo(), dst->colorInfo());
1264 } else {
1265 GrImageInfo nextInfo(input->colorInfo(), nextDims);
1266
1267 tempB = fContext->priv().makeSFCWithFallback(nextInfo, SkBackingFit::kApprox,
1268 /* sampleCount= */ 1,
1269 skgpu::Mipmapped::kNo,
1270 texView.proxy()->isProtected());
1271 if (!tempB) {
1272 return false;
1273 }
1274 stepDst = tempB.get();
1275 stepDstRect = SkIRect::MakeSize(tempB->dimensions());
1276 }
1277 std::unique_ptr<GrFragmentProcessor> fp;
1278 if (rescaleMode == RescaleMode::kRepeatedCubic) {
1279 // Cubic sampling is always handled by drawing with a shader, so we must be texturable
1280 std::tie(texView, srcRect) = ensureTexturable(texView, srcRect);
1281 if (!texView) {
1282 return false;
1283 }
1284 auto dir = GrBicubicEffect::Direction::kXY;
1285 if (nextDims.width() == srcRect.width()) {
1286 dir = GrBicubicEffect::Direction::kY;
1287 } else if (nextDims.height() == srcRect.height()) {
1288 dir = GrBicubicEffect::Direction::kX;
1289 }
1290 static constexpr auto kWM = GrSamplerState::WrapMode::kClamp;
1291 static constexpr auto kKernel = GrBicubicEffect::gCatmullRom;
1292 fp = GrBicubicEffect::MakeSubset(std::move(texView),
1293 input->colorInfo().alphaType(),
1294 SkMatrix::I(),
1295 kWM,
1296 kWM,
1297 SkRect::Make(srcRect),
1298 kKernel,
1299 dir,
1300 *this->caps());
1301 } else {
1302 auto filter = rescaleMode == RescaleMode::kNearest ? GrSamplerState::Filter::kNearest
1303 : GrSamplerState::Filter::kLinear;
1304 if (xform ||
1305 texView.origin() != stepDst->origin() ||
1306 !stepDst->copyScaled(texView.refProxy(), srcRect, stepDstRect, filter)) {
1307 // We could not or were unable to successful perform a scaling blit (which can be
1308 // much faster if texView isn't already texturable). Scale by drawing instead.
1309 std::tie(texView, srcRect) = ensureTexturable(texView, srcRect);
1310 if (!texView) {
1311 return false;
1312 }
1313 auto srcRectF = SkRect::Make(srcRect);
1314 fp = GrTextureEffect::MakeSubset(std::move(texView),
1315 this->colorInfo().alphaType(),
1316 SkMatrix::I(),
1317 {filter, GrSamplerState::MipmapMode::kNone},
1318 srcRectF,
1319 srcRectF,
1320 *this->caps());
1321 }
1322 }
1323 if (xform) {
1324 SkASSERT(SkToBool(fp)); // shouldn't have done a copy if there was a color xform
1325 fp = GrColorSpaceXformEffect::Make(std::move(fp), std::move(xform));
1326 }
1327 if (fp) {
1328 // When fp is not null, we scale by drawing; if it is null, presumably the src has
1329 // already been copied into stepDst.
1330 stepDst->fillRectToRectWithFP(srcRect, stepDstRect, std::move(fp));
1331 }
1332 texView = stepDst->readSurfaceView();
1333 tempA = std::move(tempB);
1334 srcRect = SkIRect::MakeSize(nextDims);
1335 } while (srcRect.size() != finalSize);
1336 return true;
1337 }
1338
1339 SurfaceContext::PixelTransferResult SurfaceContext::transferPixels(GrColorType dstCT,
1340 const SkIRect& rect) {
1341 SkASSERT(rect.fLeft >= 0 && rect.fRight <= this->width());
1342 SkASSERT(rect.fTop >= 0 && rect.fBottom <= this->height());
1343 auto direct = fContext->asDirectContext();
1344 if (!direct) {
1345 return {};
1346 }
1347 auto rtProxy = this->asRenderTargetProxy();
1348 if (rtProxy && rtProxy->wrapsVkSecondaryCB()) {
1349 return {};
1350 }
1351
1352 auto proxy = this->asSurfaceProxy();
1353 auto supportedRead = this->caps()->supportedReadPixelsColorType(this->colorInfo().colorType(),
1354 proxy->backendFormat(), dstCT);
1355 // Fail if read color type does not have all of dstCT's color channels and those missing color
1356 // channels are in the src.
1357 uint32_t dstChannels = GrColorTypeChannelFlags(dstCT);
1358 uint32_t legalReadChannels = GrColorTypeChannelFlags(supportedRead.fColorType);
1359 uint32_t srcChannels = GrColorTypeChannelFlags(this->colorInfo().colorType());
1360 if ((~legalReadChannels & dstChannels) & srcChannels) {
1361 return {};
1362 }
1363
1364 if (!this->caps()->transferFromSurfaceToBufferSupport() ||
1365 !supportedRead.fOffsetAlignmentForTransferBuffer) {
1366 return {};
1367 }
1368
•1369 SkSafeMath safe;
1370 size_t bytesPerPixel = GrColorTypeBytesPerPixel(supportedRead.fColorType);
1371 size_t rowBytes = safe.mul(bytesPerPixel, rect.width());
1372 size_t maxTransAlignment = this->caps()->transferBufferRowBytesAlignment();
1373 rowBytes = safe.alignUp(rowBytes, maxTransAlignment);
1374 size_t size = safe.mul(rowBytes, rect.height());
1375 if (!safe.ok()) {
1376 return {};
1377 }
1378 // By using kStream_GrAccessPattern here, we are not able to cache and reuse the buffer for
1379 // multiple reads. Switching to kDynamic_GrAccessPattern would allow for this, however doing
1380 // so causes a crash in a chromium test. See skbug.com/40042671
1381 auto buffer = direct->priv().resourceProvider()->createBuffer(
1382 size,
1383 GrGpuBufferType::kXferGpuToCpu,
1384 GrAccessPattern::kStream_GrAccessPattern,
1385 GrResourceProvider::ZeroInit::kNo);
1386 if (!buffer) {
1387 return {};
1388 }
1389 auto srcRect = rect;
1390 bool flip = this->origin() == kBottomLeft_GrSurfaceOrigin;
1391 if (flip) {
1392 srcRect = SkIRect::MakeLTRB(rect.fLeft, this->height() - rect.fBottom, rect.fRight,
1393 this->height() - rect.fTop);
1394 }
1395 this->drawingManager()->newTransferFromRenderTask(this->asSurfaceProxyRef(), srcRect,
1396 this->colorInfo().colorType(),
1397 supportedRead.fColorType, buffer, 0);
1398 PixelTransferResult result;
1399 result.fTransferBuffer = std::move(buffer);
1400 auto at = this->colorInfo().alphaType();
1401 if (supportedRead.fColorType != dstCT || flip) {
1402 int w = rect.width(), h = rect.height();
1403 GrImageInfo srcInfo(supportedRead.fColorType, at, nullptr, w, h);
1404 GrImageInfo dstInfo(dstCT, at, nullptr, w, h);
1405 result.fRowBytes = dstInfo.minRowBytes();
1406 result.fPixelConverter = [dstInfo, srcInfo, rowBytes](
1407 void* dst, const void* src) {
1408 GrConvertPixels( GrPixmap(dstInfo, dst, dstInfo.minRowBytes()),
1409 GrCPixmap(srcInfo, src, rowBytes));
1410 };
1411 } else {
1412 result.fRowBytes = rowBytes;
1413 }
1414 return result;
1415 }
1416
1417 #ifdef SK_DEBUG
1418 void SurfaceContext::validate() const {
1419 SkASSERT(fReadView.proxy());
1420 fReadView.proxy()->validate(fContext);
1421 if (this->colorInfo().colorType() != GrColorType::kUnknown) {
1422 SkASSERT(fContext->priv().caps()->areColorTypeAndFormatCompatible(
1423 this->colorInfo().colorType(), fReadView.proxy()->backendFormat()));
1424 }
1425 this->onValidate();
1426 }
1427 #endif
1428
1429 } // namespace skgpu::ganesh