Debian Codegraph @

src/gpu/ganesh/SurfaceContext.cpp

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