1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include <functional>
9 #include <initializer_list>
10 #include <vector>
11
12 #include "SkAutoPixmapStorage.h"
13 #include "SkBitmap.h"
14 #include "SkCanvas.h"
15 #include "SkColorSpacePriv.h"
16 #include "SkData.h"
17 #include "SkImageEncoder.h"
18 #include "SkImageGenerator.h"
19 #include "SkImage_Base.h"
20 #include "SkImagePriv.h"
21 #include "SkMakeUnique.h"
22 #include "SkPicture.h"
23 #include "SkPictureRecorder.h"
24 #include "SkRRect.h"
25 #include "SkSerialProcs.h"
26 #include "SkStream.h"
27 #include "SkSurface.h"
28 #include "SkUtils.h"
29 #include "Test.h"
30
31 #include "Resources.h"
32 #include "sk_pixel_iter.h"
33 #include "sk_tool_utils.h"
34
35 #include "GrContextPriv.h"
36 #include "GrContextThreadSafeProxy.h"
37 #include "GrGpu.h"
38 #include "GrResourceCache.h"
39 #include "GrTexture.h"
40 #include "SkGr.h"
41
42 using namespace sk_gpu_test;
43
read_pixels_info(SkImage * image)44 SkImageInfo read_pixels_info(SkImage* image) {
45 if (as_IB(image)->onImageInfo().colorSpace()) {
46 return SkImageInfo::MakeS32(image->width(), image->height(), image->alphaType());
47 }
48
49 return SkImageInfo::MakeN32(image->width(), image->height(), image->alphaType());
50 }
51
assert_equal(skiatest::Reporter * reporter,SkImage * a,const SkIRect * subsetA,SkImage * b)52 static void assert_equal(skiatest::Reporter* reporter, SkImage* a, const SkIRect* subsetA,
53 SkImage* b) {
54 const int widthA = subsetA ? subsetA->width() : a->width();
55 const int heightA = subsetA ? subsetA->height() : a->height();
56
57 REPORTER_ASSERT(reporter, widthA == b->width());
58 REPORTER_ASSERT(reporter, heightA == b->height());
59
60 // see https://bug.skia.org/3965
61 //REPORTER_ASSERT(reporter, a->isOpaque() == b->isOpaque());
62
63 SkAutoPixmapStorage pmapA, pmapB;
64 pmapA.alloc(read_pixels_info(a));
65 pmapB.alloc(read_pixels_info(b));
66
67 const int srcX = subsetA ? subsetA->x() : 0;
68 const int srcY = subsetA ? subsetA->y() : 0;
69
70 REPORTER_ASSERT(reporter, a->readPixels(pmapA, srcX, srcY));
71 REPORTER_ASSERT(reporter, b->readPixels(pmapB, 0, 0));
72
73 const size_t widthBytes = widthA * 4;
74 for (int y = 0; y < heightA; ++y) {
75 REPORTER_ASSERT(reporter, !memcmp(pmapA.addr32(0, y), pmapB.addr32(0, y), widthBytes));
76 }
77 }
draw_image_test_pattern(SkCanvas * canvas)78 static void draw_image_test_pattern(SkCanvas* canvas) {
79 canvas->clear(SK_ColorWHITE);
80 SkPaint paint;
81 paint.setColor(SK_ColorBLACK);
82 canvas->drawRect(SkRect::MakeXYWH(5, 5, 10, 10), paint);
83 }
create_image()84 static sk_sp<SkImage> create_image() {
85 const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
86 auto surface(SkSurface::MakeRaster(info));
87 draw_image_test_pattern(surface->getCanvas());
88 return surface->makeImageSnapshot();
89 }
create_image_data(SkImageInfo * info)90 static sk_sp<SkData> create_image_data(SkImageInfo* info) {
91 *info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
92 const size_t rowBytes = info->minRowBytes();
93 sk_sp<SkData> data(SkData::MakeUninitialized(rowBytes * info->height()));
94 {
95 SkBitmap bm;
96 bm.installPixels(*info, data->writable_data(), rowBytes);
97 SkCanvas canvas(bm);
98 draw_image_test_pattern(&canvas);
99 }
100 return data;
101 }
create_data_image()102 static sk_sp<SkImage> create_data_image() {
103 SkImageInfo info;
104 sk_sp<SkData> data(create_image_data(&info));
105 return SkImage::MakeRasterData(info, std::move(data), info.minRowBytes());
106 }
create_image_large(int maxTextureSize)107 static sk_sp<SkImage> create_image_large(int maxTextureSize) {
108 const SkImageInfo info = SkImageInfo::MakeN32(maxTextureSize + 1, 32, kOpaque_SkAlphaType);
109 auto surface(SkSurface::MakeRaster(info));
110 surface->getCanvas()->clear(SK_ColorWHITE);
111 SkPaint paint;
112 paint.setColor(SK_ColorBLACK);
113 surface->getCanvas()->drawRect(SkRect::MakeXYWH(4000, 2, 28000, 30), paint);
114 return surface->makeImageSnapshot();
115 }
create_picture_image()116 static sk_sp<SkImage> create_picture_image() {
117 SkPictureRecorder recorder;
118 SkCanvas* canvas = recorder.beginRecording(10, 10);
119 canvas->clear(SK_ColorCYAN);
120 return SkImage::MakeFromPicture(recorder.finishRecordingAsPicture(), SkISize::Make(10, 10),
121 nullptr, nullptr, SkImage::BitDepth::kU8,
122 SkColorSpace::MakeSRGB());
123 };
124 // Want to ensure that our Release is called when the owning image is destroyed
125 struct RasterDataHolder {
RasterDataHolderRasterDataHolder126 RasterDataHolder() : fReleaseCount(0) {}
127 sk_sp<SkData> fData;
128 int fReleaseCount;
ReleaseRasterDataHolder129 static void Release(const void* pixels, void* context) {
130 RasterDataHolder* self = static_cast<RasterDataHolder*>(context);
131 self->fReleaseCount++;
132 self->fData.reset();
133 }
134 };
create_rasterproc_image(RasterDataHolder * dataHolder)135 static sk_sp<SkImage> create_rasterproc_image(RasterDataHolder* dataHolder) {
136 SkASSERT(dataHolder);
137 SkImageInfo info;
138 dataHolder->fData = create_image_data(&info);
139 return SkImage::MakeFromRaster(SkPixmap(info, dataHolder->fData->data(), info.minRowBytes()),
140 RasterDataHolder::Release, dataHolder);
141 }
create_codec_image()142 static sk_sp<SkImage> create_codec_image() {
143 SkImageInfo info;
144 sk_sp<SkData> data(create_image_data(&info));
145 SkBitmap bitmap;
146 bitmap.installPixels(info, data->writable_data(), info.minRowBytes());
147 auto src = SkEncodeBitmap(bitmap, SkEncodedImageFormat::kPNG, 100);
148 return SkImage::MakeFromEncoded(std::move(src));
149 }
create_gpu_image(GrContext * context,bool withMips=false)150 static sk_sp<SkImage> create_gpu_image(GrContext* context, bool withMips = false) {
151 const SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
152 auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, 0,
153 kBottomLeft_GrSurfaceOrigin, nullptr, withMips));
154 draw_image_test_pattern(surface->getCanvas());
155 return surface->makeImageSnapshot();
156 }
157
test_encode(skiatest::Reporter * reporter,SkImage * image)158 static void test_encode(skiatest::Reporter* reporter, SkImage* image) {
159 const SkIRect ir = SkIRect::MakeXYWH(5, 5, 10, 10);
160 sk_sp<SkData> origEncoded = image->encodeToData();
161 REPORTER_ASSERT(reporter, origEncoded);
162 REPORTER_ASSERT(reporter, origEncoded->size() > 0);
163
164 sk_sp<SkImage> decoded(SkImage::MakeFromEncoded(origEncoded));
165 if (!decoded) {
166 ERRORF(reporter, "failed to decode image!");
167 return;
168 }
169 REPORTER_ASSERT(reporter, decoded);
170 assert_equal(reporter, image, nullptr, decoded.get());
171
172 // Now see if we can instantiate an image from a subset of the surface/origEncoded
173
174 decoded = SkImage::MakeFromEncoded(origEncoded, &ir);
175 REPORTER_ASSERT(reporter, decoded);
176 assert_equal(reporter, image, &ir, decoded.get());
177 }
178
DEF_TEST(ImageEncode,reporter)179 DEF_TEST(ImageEncode, reporter) {
180 test_encode(reporter, create_image().get());
181 }
182
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageEncode_Gpu,reporter,ctxInfo)183 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageEncode_Gpu, reporter, ctxInfo) {
184 test_encode(reporter, create_gpu_image(ctxInfo.grContext()).get());
185 }
186
DEF_TEST(Image_MakeFromRasterBitmap,reporter)187 DEF_TEST(Image_MakeFromRasterBitmap, reporter) {
188 const struct {
189 SkCopyPixelsMode fCPM;
190 bool fExpectSameAsMutable;
191 bool fExpectSameAsImmutable;
192 } recs[] = {
193 { kIfMutable_SkCopyPixelsMode, false, true },
194 { kAlways_SkCopyPixelsMode, false, false },
195 { kNever_SkCopyPixelsMode, true, true },
196 };
197 for (auto rec : recs) {
198 SkPixmap pm;
199 SkBitmap bm;
200 bm.allocN32Pixels(100, 100);
201
202 auto img = SkMakeImageFromRasterBitmap(bm, rec.fCPM);
203 REPORTER_ASSERT(reporter, img->peekPixels(&pm));
204 const bool sameMutable = pm.addr32(0, 0) == bm.getAddr32(0, 0);
205 REPORTER_ASSERT(reporter, rec.fExpectSameAsMutable == sameMutable);
206 REPORTER_ASSERT(reporter, (bm.getGenerationID() == img->uniqueID()) == sameMutable);
207
208 bm.notifyPixelsChanged(); // force a new generation ID
209
210 bm.setImmutable();
211 img = SkMakeImageFromRasterBitmap(bm, rec.fCPM);
212 REPORTER_ASSERT(reporter, img->peekPixels(&pm));
213 const bool sameImmutable = pm.addr32(0, 0) == bm.getAddr32(0, 0);
214 REPORTER_ASSERT(reporter, rec.fExpectSameAsImmutable == sameImmutable);
215 REPORTER_ASSERT(reporter, (bm.getGenerationID() == img->uniqueID()) == sameImmutable);
216 }
217 }
218
219 // Test that image encoding failures do not break picture serialization/deserialization.
DEF_TEST(Image_Serialize_Encoding_Failure,reporter)220 DEF_TEST(Image_Serialize_Encoding_Failure, reporter) {
221 auto surface(SkSurface::MakeRasterN32Premul(100, 100));
222 surface->getCanvas()->clear(SK_ColorGREEN);
223 sk_sp<SkImage> image(surface->makeImageSnapshot());
224 REPORTER_ASSERT(reporter, image);
225
226 SkPictureRecorder recorder;
227 SkCanvas* canvas = recorder.beginRecording(100, 100);
228 canvas->drawImage(image, 0, 0);
229 sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture());
230 REPORTER_ASSERT(reporter, picture);
231 REPORTER_ASSERT(reporter, picture->approximateOpCount() > 0);
232
233 bool was_called = false;
234 SkSerialProcs procs;
235 procs.fImageProc = [](SkImage*, void* called) {
236 *(bool*)called = true;
237 return SkData::MakeEmpty();
238 };
239 procs.fImageCtx = &was_called;
240
241 REPORTER_ASSERT(reporter, !was_called);
242 auto data = picture->serialize(&procs);
243 REPORTER_ASSERT(reporter, was_called);
244 REPORTER_ASSERT(reporter, data && data->size() > 0);
245
246 auto deserialized = SkPicture::MakeFromData(data->data(), data->size());
247 REPORTER_ASSERT(reporter, deserialized);
248 REPORTER_ASSERT(reporter, deserialized->approximateOpCount() > 0);
249 }
250
251 // Test that a draw that only partially covers the drawing surface isn't
252 // interpreted as covering the entire drawing surface (i.e., exercise one of the
253 // conditions of SkCanvas::wouldOverwriteEntireSurface()).
DEF_TEST(Image_RetainSnapshot,reporter)254 DEF_TEST(Image_RetainSnapshot, reporter) {
255 const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
256 const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
257 SkImageInfo info = SkImageInfo::MakeN32Premul(2, 2);
258 auto surface(SkSurface::MakeRaster(info));
259 surface->getCanvas()->clear(0xFF00FF00);
260
261 SkPMColor pixels[4];
262 memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
263 const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
264 const size_t dstRowBytes = 2 * sizeof(SkPMColor);
265
266 sk_sp<SkImage> image1(surface->makeImageSnapshot());
267 REPORTER_ASSERT(reporter, image1->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
268 for (size_t i = 0; i < SK_ARRAY_COUNT(pixels); ++i) {
269 REPORTER_ASSERT(reporter, pixels[i] == green);
270 }
271
272 SkPaint paint;
273 paint.setBlendMode(SkBlendMode::kSrc);
274 paint.setColor(SK_ColorRED);
275
276 surface->getCanvas()->drawRect(SkRect::MakeXYWH(1, 1, 1, 1), paint);
277
278 sk_sp<SkImage> image2(surface->makeImageSnapshot());
279 REPORTER_ASSERT(reporter, image2->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
280 REPORTER_ASSERT(reporter, pixels[0] == green);
281 REPORTER_ASSERT(reporter, pixels[1] == green);
282 REPORTER_ASSERT(reporter, pixels[2] == green);
283 REPORTER_ASSERT(reporter, pixels[3] == red);
284 }
285
286 /////////////////////////////////////////////////////////////////////////////////////////////////
287
make_bitmap_mutable(SkBitmap * bm)288 static void make_bitmap_mutable(SkBitmap* bm) {
289 bm->allocN32Pixels(10, 10);
290 }
291
make_bitmap_immutable(SkBitmap * bm)292 static void make_bitmap_immutable(SkBitmap* bm) {
293 bm->allocN32Pixels(10, 10);
294 bm->setImmutable();
295 }
296
DEF_TEST(image_newfrombitmap,reporter)297 DEF_TEST(image_newfrombitmap, reporter) {
298 const struct {
299 void (*fMakeProc)(SkBitmap*);
300 bool fExpectPeekSuccess;
301 bool fExpectSharedID;
302 bool fExpectLazy;
303 } rec[] = {
304 { make_bitmap_mutable, true, false, false },
305 { make_bitmap_immutable, true, true, false },
306 };
307
308 for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
309 SkBitmap bm;
310 rec[i].fMakeProc(&bm);
311
312 sk_sp<SkImage> image(SkImage::MakeFromBitmap(bm));
313 SkPixmap pmap;
314
315 const bool sharedID = (image->uniqueID() == bm.getGenerationID());
316 REPORTER_ASSERT(reporter, sharedID == rec[i].fExpectSharedID);
317
318 const bool peekSuccess = image->peekPixels(&pmap);
319 REPORTER_ASSERT(reporter, peekSuccess == rec[i].fExpectPeekSuccess);
320
321 const bool lazy = image->isLazyGenerated();
322 REPORTER_ASSERT(reporter, lazy == rec[i].fExpectLazy);
323 }
324 }
325
326 ///////////////////////////////////////////////////////////////////////////////////////////////////
327
328 #include "SkBitmapCache.h"
329
330 /*
331 * This tests the caching (and preemptive purge) of the raster equivalent of a gpu-image.
332 * We cache it for performance when drawing into a raster surface.
333 *
334 * A cleaner test would know if each drawImage call triggered a read-back from the gpu,
335 * but we don't have that facility (at the moment) so we use a little internal knowledge
336 * of *how* the raster version is cached, and look for that.
337 */
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_Gpu2Cpu,reporter,ctxInfo)338 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_Gpu2Cpu, reporter, ctxInfo) {
339 SkImageInfo info = SkImageInfo::MakeN32(20, 20, kOpaque_SkAlphaType);
340 sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
341 const auto desc = SkBitmapCacheDesc::Make(image.get());
342
343 auto surface(SkSurface::MakeRaster(info));
344
345 // now we can test drawing a gpu-backed image into a cpu-backed surface
346
347 {
348 SkBitmap cachedBitmap;
349 REPORTER_ASSERT(reporter, !SkBitmapCache::Find(desc, &cachedBitmap));
350 }
351
352 surface->getCanvas()->drawImage(image, 0, 0);
353 {
354 SkBitmap cachedBitmap;
355 if (SkBitmapCache::Find(desc, &cachedBitmap)) {
356 REPORTER_ASSERT(reporter, cachedBitmap.isImmutable());
357 REPORTER_ASSERT(reporter, cachedBitmap.getPixels());
358 } else {
359 // unexpected, but not really a bug, since the cache is global and this test may be
360 // run w/ other threads competing for its budget.
361 SkDebugf("SkImage_Gpu2Cpu : cachedBitmap was already purged\n");
362 }
363 }
364
365 image.reset(nullptr);
366 {
367 SkBitmap cachedBitmap;
368 REPORTER_ASSERT(reporter, !SkBitmapCache::Find(desc, &cachedBitmap));
369 }
370 }
371
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_makeTextureImage,reporter,contextInfo)372 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_makeTextureImage, reporter, contextInfo) {
373 GrContext* context = contextInfo.grContext();
374 sk_gpu_test::TestContext* testContext = contextInfo.testContext();
375 GrContextFactory otherFactory;
376 ContextInfo otherContextInfo = otherFactory.getContextInfo(contextInfo.type());
377 testContext->makeCurrent();
378
379 std::function<sk_sp<SkImage>()> imageFactories[] = {
380 create_image,
381 create_codec_image,
382 create_data_image,
383 // Create an image from a picture.
384 create_picture_image,
385 // Create a texture image.
386 [context] { return create_gpu_image(context); },
387 // Create a texture image with mips
388 //[context] { return create_gpu_image(context, true); },
389 // Create a texture image in a another GrContext.
390 [otherContextInfo] {
391 auto restore = otherContextInfo.testContext()->makeCurrentAndAutoRestore();
392 sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
393 otherContextInfo.grContext()->flush();
394 return otherContextImage;
395 }
396 };
397
398 sk_sp<SkColorSpace> dstColorSpaces[] ={
399 nullptr,
400 SkColorSpace::MakeSRGB(),
401 };
402
403 for (auto& dstColorSpace : dstColorSpaces) {
404 for (auto mipMapped : {GrMipMapped::kNo, GrMipMapped::kYes}) {
405 for (auto factory : imageFactories) {
406 sk_sp<SkImage> image(factory());
407 if (!image) {
408 ERRORF(reporter, "Error creating image.");
409 continue;
410 }
411
412 sk_sp<SkImage> texImage(image->makeTextureImage(context, dstColorSpace.get(),
413 mipMapped));
414 if (!texImage) {
415 GrContext* imageContext = as_IB(image)->context();
416
417 // We expect to fail if image comes from a different GrContext.
418 if (!image->isTextureBacked() || imageContext == context) {
419 ERRORF(reporter, "makeTextureImage failed.");
420 }
421 continue;
422 }
423 if (!texImage->isTextureBacked()) {
424 ERRORF(reporter, "makeTextureImage returned non-texture image.");
425 continue;
426 }
427 if (GrMipMapped::kYes == mipMapped &&
428 as_IB(texImage)->peekProxy()->mipMapped() != mipMapped &&
429 context->contextPriv().caps()->mipMapSupport()) {
430 ERRORF(reporter, "makeTextureImage returned non-mipmapped texture.");
431 continue;
432 }
433 if (image->isTextureBacked()) {
434 GrSurfaceProxy* origProxy = as_IB(image)->peekProxy();
435 GrSurfaceProxy* copyProxy = as_IB(texImage)->peekProxy();
436
437 if (origProxy->underlyingUniqueID() != copyProxy->underlyingUniqueID()) {
438 SkASSERT(origProxy->asTextureProxy());
439 if (GrMipMapped::kNo == mipMapped ||
440 GrMipMapped::kYes == origProxy->asTextureProxy()->mipMapped()) {
441 ERRORF(reporter, "makeTextureImage made unnecessary texture copy.");
442 }
443 }
444 }
445 if (image->width() != texImage->width() || image->height() != texImage->height()) {
446 ERRORF(reporter, "makeTextureImage changed the image size.");
447 }
448 if (image->alphaType() != texImage->alphaType()) {
449 ERRORF(reporter, "makeTextureImage changed image alpha type.");
450 }
451 }
452 }
453 context->flush();
454 }
455 }
456
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_makeNonTextureImage,reporter,contextInfo)457 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SkImage_makeNonTextureImage, reporter, contextInfo) {
458 GrContext* context = contextInfo.grContext();
459
460 std::function<sk_sp<SkImage>()> imageFactories[] = {
461 create_image,
462 create_codec_image,
463 create_data_image,
464 create_picture_image,
465 [context] { return create_gpu_image(context); },
466 };
467 SkColorSpace* legacyColorSpace = nullptr;
468 for (auto factory : imageFactories) {
469 sk_sp<SkImage> image = factory();
470 if (!image->isTextureBacked()) {
471 REPORTER_ASSERT(reporter, image->makeNonTextureImage().get() == image.get());
472 if (!(image = image->makeTextureImage(context, legacyColorSpace))) {
473 continue;
474 }
475 }
476 auto rasterImage = image->makeNonTextureImage();
477 if (!rasterImage) {
478 ERRORF(reporter, "makeNonTextureImage failed for texture-backed image.");
479 }
480 REPORTER_ASSERT(reporter, !rasterImage->isTextureBacked());
481 assert_equal(reporter, image.get(), nullptr, rasterImage.get());
482 }
483 }
484
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsImage,reporter,ctxInfo)485 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrContext_colorTypeSupportedAsImage, reporter, ctxInfo) {
486 for (int ct = 0; ct < kLastEnum_SkColorType; ++ct) {
487 static constexpr int kSize = 10;
488 SkColorType colorType = static_cast<SkColorType>(ct);
489 bool can = ctxInfo.grContext()->colorTypeSupportedAsImage(colorType);
490 auto* gpu = ctxInfo.grContext()->contextPriv().getGpu();
491 GrBackendTexture backendTex = gpu->createTestingOnlyBackendTexture(
492 nullptr, kSize, kSize, colorType, false, GrMipMapped::kNo);
493 auto img =
494 SkImage::MakeFromTexture(ctxInfo.grContext(), backendTex, kTopLeft_GrSurfaceOrigin,
495 colorType, kOpaque_SkAlphaType, nullptr);
496 REPORTER_ASSERT(reporter, can == SkToBool(img),
497 "colorTypeSupportedAsImage:%d, actual:%d, ct:%d", can, SkToBool(img),
498 colorType);
499
500 img.reset();
501 ctxInfo.grContext()->flush();
502 if (backendTex.isValid()) {
503 gpu->deleteTestingOnlyBackendTexture(backendTex);
504 }
505 }
506 }
507
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(UnpremulTextureImage,reporter,ctxInfo)508 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(UnpremulTextureImage, reporter, ctxInfo) {
509 SkBitmap bmp;
510 bmp.allocPixels(
511 SkImageInfo::Make(256, 256, kRGBA_8888_SkColorType, kUnpremul_SkAlphaType, nullptr));
512 for (int y = 0; y < 256; ++y) {
513 for (int x = 0; x < 256; ++x) {
514 *bmp.getAddr32(x, y) =
515 SkColorSetARGB((U8CPU)y, 255 - (U8CPU)y, (U8CPU)x, 255 - (U8CPU)x);
516 }
517 }
518 auto texImage = SkImage::MakeFromBitmap(bmp)->makeTextureImage(ctxInfo.grContext(), nullptr);
519 if (!texImage || texImage->alphaType() != kUnpremul_SkAlphaType) {
520 ERRORF(reporter, "Failed to make unpremul texture image.");
521 return;
522 }
523 // The GPU backend always unpremuls the values stored in the texture because it assumes they
524 // are premul values. (skbug.com/7580).
525 if (false) {
526 SkBitmap unpremul;
527 unpremul.allocPixels(SkImageInfo::Make(256, 256, kRGBA_8888_SkColorType,
528 kUnpremul_SkAlphaType, nullptr));
529 if (!texImage->readPixels(unpremul.info(), unpremul.getPixels(), unpremul.rowBytes(), 0,
530 0)) {
531 ERRORF(reporter, "Unpremul readback failed.");
532 return;
533 }
534 for (int y = 0; y < 256; ++y) {
535 for (int x = 0; x < 256; ++x) {
536 if (*bmp.getAddr32(x, y) != *unpremul.getAddr32(x, y)) {
537 ERRORF(reporter, "unpremul(0x%08x)->unpremul(0x%08x) at %d, %d.",
538 *bmp.getAddr32(x, y), *unpremul.getAddr32(x, y), x, y);
539 return;
540 }
541 }
542 }
543 }
544 SkBitmap premul;
545 premul.allocPixels(
546 SkImageInfo::Make(256, 256, kRGBA_8888_SkColorType, kPremul_SkAlphaType, nullptr));
547 if (!texImage->readPixels(premul.info(), premul.getPixels(), premul.rowBytes(), 0, 0)) {
548 ERRORF(reporter, "Unpremul readback failed.");
549 return;
550 }
551 for (int y = 0; y < 256; ++y) {
552 for (int x = 0; x < 256; ++x) {
553 // Treat bmp's color as a pm color even though it may be the r/b swap of a PM color.
554 // SkPremultiplyColor acts the same on both channels.
555 uint32_t origColor = SkPreMultiplyColor(*bmp.getAddr32(x, y));
556 int32_t origA = (origColor >> 24) & 0xff;
557 int32_t origB = (origColor >> 16) & 0xff;
558 int32_t origG = (origColor >> 8) & 0xff;
559 int32_t origR = (origColor >> 0) & 0xff;
560 uint32_t read = *premul.getAddr32(x, y);
561 int32_t readA = (read >> 24) & 0xff;
562 int32_t readB = (read >> 16) & 0xff;
563 int32_t readG = (read >> 8) & 0xff;
564 int32_t readR = (read >> 0) & 0xff;
565 // We expect that alpha=1 and alpha=0 should come out exact. Otherwise allow a little
566 // bit of tolerance for GPU vs CPU premul math.
567 int32_t tol = (origA == 0 || origA == 255) ? 0 : 1;
568 if (origA != readA || SkTAbs(readB - origB) > tol || SkTAbs(readG - origG) > tol ||
569 SkTAbs(readR - origR) > tol) {
570 ERRORF(reporter, "unpremul(0x%08x)->premul(0x%08x) at %d, %d.",
571 *bmp.getAddr32(x, y), *premul.getAddr32(x, y), x, y);
572 return;
573 }
574 }
575 }
576 }
577
DEF_GPUTEST(AbandonedContextImage,reporter,options)578 DEF_GPUTEST(AbandonedContextImage, reporter, options) {
579 using Factory = sk_gpu_test::GrContextFactory;
580 for (int ct = 0; ct < Factory::kContextTypeCnt; ++ct) {
581 auto type = static_cast<Factory::ContextType>(ct);
582 std::unique_ptr<Factory> factory(new Factory);
583 if (!factory->get(type)) {
584 continue;
585 }
586
587 sk_sp<SkImage> img;
588 auto gsurf = SkSurface::MakeRenderTarget(
589 factory->get(type), SkBudgeted::kYes,
590 SkImageInfo::Make(100, 100, kRGBA_8888_SkColorType, kPremul_SkAlphaType), 1,
591 nullptr);
592 if (!gsurf) {
593 continue;
594 }
595 img = gsurf->makeImageSnapshot();
596 gsurf.reset();
597
598 auto rsurf = SkSurface::MakeRaster(SkImageInfo::MakeN32Premul(100, 100));
599
600 REPORTER_ASSERT(reporter, img->isValid(factory->get(type)));
601 REPORTER_ASSERT(reporter, img->isValid(rsurf->getCanvas()->getGrContext()));
602
603 factory->get(type)->abandonContext();
604 REPORTER_ASSERT(reporter, !img->isValid(factory->get(type)));
605 REPORTER_ASSERT(reporter, !img->isValid(rsurf->getCanvas()->getGrContext()));
606 // This shouldn't crash.
607 rsurf->getCanvas()->drawImage(img, 0, 0);
608
609 // Give up all other refs on GrContext.
610 factory.reset(nullptr);
611 REPORTER_ASSERT(reporter, !img->isValid(rsurf->getCanvas()->getGrContext()));
612 // This shouldn't crash.
613 rsurf->getCanvas()->drawImage(img, 0, 0);
614 }
615 }
616
617 class EmptyGenerator : public SkImageGenerator {
618 public:
EmptyGenerator()619 EmptyGenerator() : SkImageGenerator(SkImageInfo::MakeN32Premul(0, 0)) {}
620 };
621
DEF_TEST(ImageEmpty,reporter)622 DEF_TEST(ImageEmpty, reporter) {
623 const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
624 SkPixmap pmap(info, nullptr, 0);
625 REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterCopy(pmap));
626 REPORTER_ASSERT(reporter, nullptr == SkImage::MakeRasterData(info, nullptr, 0));
627 REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromRaster(pmap, nullptr, nullptr));
628 REPORTER_ASSERT(reporter, nullptr == SkImage::MakeFromGenerator(
629 skstd::make_unique<EmptyGenerator>()));
630 }
631
DEF_TEST(ImageDataRef,reporter)632 DEF_TEST(ImageDataRef, reporter) {
633 SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
634 size_t rowBytes = info.minRowBytes();
635 size_t size = info.computeByteSize(rowBytes);
636 sk_sp<SkData> data = SkData::MakeUninitialized(size);
637 REPORTER_ASSERT(reporter, data->unique());
638 sk_sp<SkImage> image = SkImage::MakeRasterData(info, data, rowBytes);
639 REPORTER_ASSERT(reporter, !data->unique());
640 image.reset();
641 REPORTER_ASSERT(reporter, data->unique());
642 }
643
has_pixels(const SkPMColor pixels[],int count,SkPMColor expected)644 static bool has_pixels(const SkPMColor pixels[], int count, SkPMColor expected) {
645 for (int i = 0; i < count; ++i) {
646 if (pixels[i] != expected) {
647 return false;
648 }
649 }
650 return true;
651 }
652
image_test_read_pixels(skiatest::Reporter * reporter,SkImage * image)653 static void image_test_read_pixels(skiatest::Reporter* reporter, SkImage* image) {
654 if (!image) {
655 ERRORF(reporter, "Failed to create image!");
656 return;
657 }
658 const SkPMColor expected = SkPreMultiplyColor(SK_ColorWHITE);
659 const SkPMColor notExpected = ~expected;
660
661 const int w = 2, h = 2;
662 const size_t rowBytes = w * sizeof(SkPMColor);
663 SkPMColor pixels[w*h];
664
665 SkImageInfo info;
666
667 info = SkImageInfo::MakeUnknown(w, h);
668 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, 0));
669
670 // out-of-bounds should fail
671 info = SkImageInfo::MakeN32Premul(w, h);
672 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, -w, 0));
673 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, -h));
674 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, image->width(), 0));
675 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, image->height()));
676
677 // top-left should succeed
678 sk_memset32(pixels, notExpected, w*h);
679 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, 0, 0));
680 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
681
682 // bottom-right should succeed
683 sk_memset32(pixels, notExpected, w*h);
684 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
685 image->width() - w, image->height() - h));
686 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
687
688 // partial top-left should succeed
689 sk_memset32(pixels, notExpected, w*h);
690 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, -1, -1));
691 REPORTER_ASSERT(reporter, pixels[3] == expected);
692 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h - 1, notExpected));
693
694 // partial bottom-right should succeed
695 sk_memset32(pixels, notExpected, w*h);
696 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
697 image->width() - 1, image->height() - 1));
698 REPORTER_ASSERT(reporter, pixels[0] == expected);
699 REPORTER_ASSERT(reporter, has_pixels(&pixels[1], w*h - 1, notExpected));
700 }
DEF_TEST(ImageReadPixels,reporter)701 DEF_TEST(ImageReadPixels, reporter) {
702 sk_sp<SkImage> image(create_image());
703 image_test_read_pixels(reporter, image.get());
704
705 image = create_data_image();
706 image_test_read_pixels(reporter, image.get());
707
708 RasterDataHolder dataHolder;
709 image = create_rasterproc_image(&dataHolder);
710 image_test_read_pixels(reporter, image.get());
711 image.reset();
712 REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
713
714 image = create_codec_image();
715 image_test_read_pixels(reporter, image.get());
716 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageReadPixels_Gpu,reporter,ctxInfo)717 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageReadPixels_Gpu, reporter, ctxInfo) {
718 image_test_read_pixels(reporter, create_gpu_image(ctxInfo.grContext()).get());
719 }
720
check_legacy_bitmap(skiatest::Reporter * reporter,const SkImage * image,const SkBitmap & bitmap)721 static void check_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image,
722 const SkBitmap& bitmap) {
723 REPORTER_ASSERT(reporter, image->width() == bitmap.width());
724 REPORTER_ASSERT(reporter, image->height() == bitmap.height());
725 REPORTER_ASSERT(reporter, image->alphaType() == bitmap.alphaType());
726
727 REPORTER_ASSERT(reporter, bitmap.isImmutable());
728
729 REPORTER_ASSERT(reporter, bitmap.getPixels());
730
731 const SkImageInfo info = SkImageInfo::MakeN32(1, 1, bitmap.alphaType());
732 SkPMColor imageColor;
733 REPORTER_ASSERT(reporter, image->readPixels(info, &imageColor, sizeof(SkPMColor), 0, 0));
734 REPORTER_ASSERT(reporter, imageColor == *bitmap.getAddr32(0, 0));
735 }
736
test_legacy_bitmap(skiatest::Reporter * reporter,const SkImage * image)737 static void test_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image) {
738 if (!image) {
739 ERRORF(reporter, "Failed to create image.");
740 return;
741 }
742 SkBitmap bitmap;
743 REPORTER_ASSERT(reporter, image->asLegacyBitmap(&bitmap));
744 check_legacy_bitmap(reporter, image, bitmap);
745
746 // Test subsetting to exercise the rowBytes logic.
747 SkBitmap tmp;
748 REPORTER_ASSERT(reporter, bitmap.extractSubset(&tmp, SkIRect::MakeWH(image->width() / 2,
749 image->height() / 2)));
750 sk_sp<SkImage> subsetImage(SkImage::MakeFromBitmap(tmp));
751 REPORTER_ASSERT(reporter, subsetImage.get());
752
753 SkBitmap subsetBitmap;
754 REPORTER_ASSERT(reporter, subsetImage->asLegacyBitmap(&subsetBitmap));
755 check_legacy_bitmap(reporter, subsetImage.get(), subsetBitmap);
756 }
DEF_TEST(ImageLegacyBitmap,reporter)757 DEF_TEST(ImageLegacyBitmap, reporter) {
758 sk_sp<SkImage> image(create_image());
759 test_legacy_bitmap(reporter, image.get());
760
761 image = create_data_image();
762 test_legacy_bitmap(reporter, image.get());
763
764 RasterDataHolder dataHolder;
765 image = create_rasterproc_image(&dataHolder);
766 test_legacy_bitmap(reporter, image.get());
767 image.reset();
768 REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
769
770 image = create_codec_image();
771 test_legacy_bitmap(reporter, image.get());
772 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageLegacyBitmap_Gpu,reporter,ctxInfo)773 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageLegacyBitmap_Gpu, reporter, ctxInfo) {
774 sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
775 test_legacy_bitmap(reporter, image.get());
776 }
777
test_peek(skiatest::Reporter * reporter,SkImage * image,bool expectPeekSuccess)778 static void test_peek(skiatest::Reporter* reporter, SkImage* image, bool expectPeekSuccess) {
779 if (!image) {
780 ERRORF(reporter, "Failed to create image!");
781 return;
782 }
783 SkPixmap pm;
784 bool success = image->peekPixels(&pm);
785 REPORTER_ASSERT(reporter, expectPeekSuccess == success);
786 if (success) {
787 const SkImageInfo& info = pm.info();
788 REPORTER_ASSERT(reporter, 20 == info.width());
789 REPORTER_ASSERT(reporter, 20 == info.height());
790 REPORTER_ASSERT(reporter, kN32_SkColorType == info.colorType());
791 REPORTER_ASSERT(reporter, kPremul_SkAlphaType == info.alphaType() ||
792 kOpaque_SkAlphaType == info.alphaType());
793 REPORTER_ASSERT(reporter, info.minRowBytes() <= pm.rowBytes());
794 REPORTER_ASSERT(reporter, SkPreMultiplyColor(SK_ColorWHITE) == *pm.addr32(0, 0));
795 }
796 }
DEF_TEST(ImagePeek,reporter)797 DEF_TEST(ImagePeek, reporter) {
798 sk_sp<SkImage> image(create_image());
799 test_peek(reporter, image.get(), true);
800
801 image = create_data_image();
802 test_peek(reporter, image.get(), true);
803
804 RasterDataHolder dataHolder;
805 image = create_rasterproc_image(&dataHolder);
806 test_peek(reporter, image.get(), true);
807 image.reset();
808 REPORTER_ASSERT(reporter, 1 == dataHolder.fReleaseCount);
809
810 image = create_codec_image();
811 test_peek(reporter, image.get(), false);
812 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImagePeek_Gpu,reporter,ctxInfo)813 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImagePeek_Gpu, reporter, ctxInfo) {
814 sk_sp<SkImage> image(create_gpu_image(ctxInfo.grContext()));
815 test_peek(reporter, image.get(), false);
816 }
817
818 struct TextureReleaseChecker {
TextureReleaseCheckerTextureReleaseChecker819 TextureReleaseChecker() : fReleaseCount(0) {}
820 int fReleaseCount;
ReleaseTextureReleaseChecker821 static void Release(void* self) {
822 static_cast<TextureReleaseChecker*>(self)->fReleaseCount++;
823 }
824 };
825
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTextureRelease,reporter,ctxInfo)826 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(SkImage_NewFromTextureRelease, reporter, ctxInfo) {
827 const int kWidth = 10;
828 const int kHeight = 10;
829 std::unique_ptr<uint32_t[]> pixels(new uint32_t[kWidth * kHeight]);
830
831 GrContext* ctx = ctxInfo.grContext();
832 GrGpu* gpu = ctx->contextPriv().getGpu();
833
834 GrBackendTexture backendTex = gpu->createTestingOnlyBackendTexture(
835 pixels.get(), kWidth, kHeight, GrColorType::kRGBA_8888, true, GrMipMapped::kNo);
836
837 TextureReleaseChecker releaseChecker;
838 GrSurfaceOrigin texOrigin = kBottomLeft_GrSurfaceOrigin;
839 sk_sp<SkImage> refImg(
840 SkImage::MakeFromTexture(ctx, backendTex, texOrigin, kRGBA_8888_SkColorType,
841 kPremul_SkAlphaType, nullptr,
842 TextureReleaseChecker::Release, &releaseChecker));
843
844 GrSurfaceOrigin readBackOrigin;
845 GrBackendTexture readBackBackendTex = refImg->getBackendTexture(false, &readBackOrigin);
846 readBackBackendTex.setPixelConfig(kRGBA_8888_GrPixelConfig);
847 if (!GrBackendTexture::TestingOnly_Equals(readBackBackendTex, backendTex)) {
848 ERRORF(reporter, "backend mismatch\n");
849 }
850 REPORTER_ASSERT(reporter, GrBackendTexture::TestingOnly_Equals(readBackBackendTex, backendTex));
851 if (readBackOrigin != texOrigin) {
852 ERRORF(reporter, "origin mismatch %d %d\n", readBackOrigin, texOrigin);
853 }
854 REPORTER_ASSERT(reporter, readBackOrigin == texOrigin);
855
856 // Now exercise the release proc
857 REPORTER_ASSERT(reporter, 0 == releaseChecker.fReleaseCount);
858 refImg.reset(nullptr); // force a release of the image
859 REPORTER_ASSERT(reporter, 1 == releaseChecker.fReleaseCount);
860
861 gpu->deleteTestingOnlyBackendTexture(backendTex);
862 }
863
test_cross_context_image(skiatest::Reporter * reporter,const GrContextOptions & options,const char * testName,std::function<sk_sp<SkImage> (GrContext *)> imageMaker)864 static void test_cross_context_image(skiatest::Reporter* reporter, const GrContextOptions& options,
865 const char* testName,
866 std::function<sk_sp<SkImage>(GrContext*)> imageMaker) {
867 for (int i = 0; i < GrContextFactory::kContextTypeCnt; ++i) {
868 GrContextFactory testFactory(options);
869 GrContextFactory::ContextType ctxType = static_cast<GrContextFactory::ContextType>(i);
870 ContextInfo ctxInfo = testFactory.getContextInfo(ctxType);
871 GrContext* ctx = ctxInfo.grContext();
872 if (!ctx) {
873 continue;
874 }
875
876 // If we don't have proper support for this feature, the factory will fallback to returning
877 // codec-backed images. Those will "work", but some of our checks will fail because we
878 // expect the cross-context images not to work on multiple contexts at once.
879 if (!ctx->contextPriv().caps()->crossContextTextureSupport()) {
880 continue;
881 }
882
883 // We test three lifetime patterns for a single context:
884 // 1) Create image, free image
885 // 2) Create image, draw, flush, free image
886 // 3) Create image, draw, free image, flush
887 // ... and then repeat the last two patterns with drawing on a second* context:
888 // 4) Create image, draw*, flush*, free image
889 // 5) Create image, draw*, free iamge, flush*
890
891 // Case #1: Create image, free image
892 {
893 sk_sp<SkImage> refImg(imageMaker(ctx));
894 refImg.reset(nullptr); // force a release of the image
895 }
896
897 SkImageInfo info = SkImageInfo::MakeN32Premul(128, 128);
898 sk_sp<SkSurface> surface = SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, info);
899 if (!surface) {
900 ERRORF(reporter, "SkSurface::MakeRenderTarget failed for %s.", testName);
901 continue;
902 }
903
904 SkCanvas* canvas = surface->getCanvas();
905
906 // Case #2: Create image, draw, flush, free image
907 {
908 sk_sp<SkImage> refImg(imageMaker(ctx));
909
910 canvas->drawImage(refImg, 0, 0);
911 canvas->flush();
912
913 refImg.reset(nullptr); // force a release of the image
914 }
915
916 // Case #3: Create image, draw, free image, flush
917 {
918 sk_sp<SkImage> refImg(imageMaker(ctx));
919
920 canvas->drawImage(refImg, 0, 0);
921 refImg.reset(nullptr); // force a release of the image
922
923 canvas->flush();
924 }
925
926 // Configure second context
927 sk_gpu_test::TestContext* testContext = ctxInfo.testContext();
928
929 ContextInfo otherContextInfo = testFactory.getSharedContextInfo(ctx);
930 GrContext* otherCtx = otherContextInfo.grContext();
931 sk_gpu_test::TestContext* otherTestContext = otherContextInfo.testContext();
932
933 // Creating a context in a share group may fail
934 if (!otherCtx) {
935 continue;
936 }
937
938 surface = SkSurface::MakeRenderTarget(otherCtx, SkBudgeted::kNo, info);
939 canvas = surface->getCanvas();
940
941 // Case #4: Create image, draw*, flush*, free image
942 {
943 testContext->makeCurrent();
944 sk_sp<SkImage> refImg(imageMaker(ctx));
945
946 otherTestContext->makeCurrent();
947 canvas->drawImage(refImg, 0, 0);
948 canvas->flush();
949
950 testContext->makeCurrent();
951 refImg.reset(nullptr); // force a release of the image
952 }
953
954 // Case #5: Create image, draw*, free image, flush*
955 {
956 testContext->makeCurrent();
957 sk_sp<SkImage> refImg(imageMaker(ctx));
958
959 otherTestContext->makeCurrent();
960 canvas->drawImage(refImg, 0, 0);
961
962 testContext->makeCurrent();
963 refImg.reset(nullptr); // force a release of the image
964
965 otherTestContext->makeCurrent();
966 canvas->flush();
967
968 // This is specifically here for vulkan to guarantee the command buffer will finish
969 // which is when we call the ReleaseProc.
970 otherCtx->contextPriv().getGpu()->testingOnly_flushGpuAndSync();
971 }
972
973 // Case #6: Verify that only one context can be using the image at a time
974 {
975 testContext->makeCurrent();
976 sk_sp<SkImage> refImg(imageMaker(ctx));
977
978 // Any context should be able to borrow the texture at this point
979 sk_sp<GrTextureProxy> proxy = as_IB(refImg)->asTextureProxyRef(
980 ctx, GrSamplerState::ClampNearest(), nullptr);
981 REPORTER_ASSERT(reporter, proxy);
982
983 // But once it's borrowed, no other context should be able to borrow
984 otherTestContext->makeCurrent();
985 sk_sp<GrTextureProxy> otherProxy = as_IB(refImg)->asTextureProxyRef(
986 otherCtx, GrSamplerState::ClampNearest(), nullptr);
987 REPORTER_ASSERT(reporter, !otherProxy);
988
989 // Original context (that's already borrowing) should be okay
990 testContext->makeCurrent();
991 sk_sp<GrTextureProxy> proxySecondRef = as_IB(refImg)->asTextureProxyRef(
992 ctx, GrSamplerState::ClampNearest(), nullptr);
993 REPORTER_ASSERT(reporter, proxySecondRef);
994
995 // Release first ref from the original context
996 proxy.reset(nullptr);
997
998 // We released one proxy but not the other from the current borrowing context. Make sure
999 // a new context is still not able to borrow the texture.
1000 otherTestContext->makeCurrent();
1001 otherProxy = as_IB(refImg)->asTextureProxyRef(otherCtx, GrSamplerState::ClampNearest(),
1002 nullptr);
1003 REPORTER_ASSERT(reporter, !otherProxy);
1004
1005 // Release second ref from the original context
1006 testContext->makeCurrent();
1007 proxySecondRef.reset(nullptr);
1008
1009 // Now we should be able to borrow the texture from the other context
1010 otherTestContext->makeCurrent();
1011 otherProxy = as_IB(refImg)->asTextureProxyRef(otherCtx, GrSamplerState::ClampNearest(),
1012 nullptr);
1013 REPORTER_ASSERT(reporter, otherProxy);
1014
1015 // Release everything
1016 otherProxy.reset(nullptr);
1017 refImg.reset(nullptr);
1018 }
1019 }
1020 }
1021
DEF_GPUTEST(SkImage_MakeCrossContextFromEncodedRelease,reporter,options)1022 DEF_GPUTEST(SkImage_MakeCrossContextFromEncodedRelease, reporter, options) {
1023 sk_sp<SkData> data = GetResourceAsData("images/mandrill_128.png");
1024 if (!data) {
1025 ERRORF(reporter, "missing resource");
1026 return;
1027 }
1028
1029 test_cross_context_image(reporter, options, "SkImage_MakeCrossContextFromEncodedRelease",
1030 [&data](GrContext* ctx) {
1031 return SkImage::MakeCrossContextFromEncoded(ctx, data, false, nullptr);
1032 });
1033 }
1034
DEF_GPUTEST(SkImage_MakeCrossContextFromPixmapRelease,reporter,options)1035 DEF_GPUTEST(SkImage_MakeCrossContextFromPixmapRelease, reporter, options) {
1036 SkBitmap bitmap;
1037 SkPixmap pixmap;
1038 if (!GetResourceAsBitmap("images/mandrill_128.png", &bitmap) || !bitmap.peekPixels(&pixmap)) {
1039 ERRORF(reporter, "missing resource");
1040 return;
1041 }
1042 test_cross_context_image(reporter, options, "SkImage_MakeCrossContextFromPixmapRelease",
1043 [&pixmap](GrContext* ctx) {
1044 return SkImage::MakeCrossContextFromPixmap(ctx, pixmap, false, nullptr);
1045 });
1046 }
1047
DEF_GPUTEST(SkImage_CrossContextGrayAlphaConfigs,reporter,options)1048 DEF_GPUTEST(SkImage_CrossContextGrayAlphaConfigs, reporter, options) {
1049
1050 for (SkColorType ct : { kGray_8_SkColorType, kAlpha_8_SkColorType }) {
1051 SkAutoPixmapStorage pixmap;
1052 pixmap.alloc(SkImageInfo::Make(4, 4, ct, kPremul_SkAlphaType));
1053
1054 for (int i = 0; i < GrContextFactory::kContextTypeCnt; ++i) {
1055 GrContextFactory testFactory(options);
1056 GrContextFactory::ContextType ctxType = static_cast<GrContextFactory::ContextType>(i);
1057 ContextInfo ctxInfo = testFactory.getContextInfo(ctxType);
1058 GrContext* ctx = ctxInfo.grContext();
1059 if (!ctx || !ctx->contextPriv().caps()->crossContextTextureSupport()) {
1060 continue;
1061 }
1062
1063 sk_sp<SkImage> image = SkImage::MakeCrossContextFromPixmap(ctx, pixmap, false, nullptr);
1064 REPORTER_ASSERT(reporter, image);
1065
1066 sk_sp<GrTextureProxy> proxy = as_IB(image)->asTextureProxyRef(
1067 ctx, GrSamplerState::ClampNearest(), nullptr);
1068 REPORTER_ASSERT(reporter, proxy);
1069
1070 bool expectAlpha = kAlpha_8_SkColorType == ct;
1071 REPORTER_ASSERT(reporter, expectAlpha == GrPixelConfigIsAlphaOnly(proxy->config()));
1072 }
1073 }
1074 }
1075
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(makeBackendTexture,reporter,ctxInfo)1076 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(makeBackendTexture, reporter, ctxInfo) {
1077 GrContext* context = ctxInfo.grContext();
1078 sk_gpu_test::TestContext* testContext = ctxInfo.testContext();
1079 sk_sp<GrContextThreadSafeProxy> proxy = context->threadSafeProxy();
1080
1081 GrContextFactory otherFactory;
1082 ContextInfo otherContextInfo = otherFactory.getContextInfo(ctxInfo.type());
1083
1084 testContext->makeCurrent();
1085 REPORTER_ASSERT(reporter, proxy);
1086 auto createLarge = [context] {
1087 return create_image_large(context->contextPriv().caps()->maxTextureSize());
1088 };
1089 struct {
1090 std::function<sk_sp<SkImage> ()> fImageFactory;
1091 bool fExpectation;
1092 bool fCanTakeDirectly;
1093 } testCases[] = {
1094 { create_image, true, false },
1095 { create_codec_image, true, false },
1096 { create_data_image, true, false },
1097 { create_picture_image, true, false },
1098 { [context] { return create_gpu_image(context); }, true, true },
1099 // Create a texture image in a another GrContext.
1100 { [otherContextInfo] {
1101 auto restore = otherContextInfo.testContext()->makeCurrentAndAutoRestore();
1102 sk_sp<SkImage> otherContextImage = create_gpu_image(otherContextInfo.grContext());
1103 otherContextInfo.grContext()->flush();
1104 return otherContextImage;
1105 }, false, false },
1106 // Create an image that is too large to be texture backed.
1107 { createLarge, false, false }
1108 };
1109
1110 for (auto testCase : testCases) {
1111 sk_sp<SkImage> image(testCase.fImageFactory());
1112 if (!image) {
1113 ERRORF(reporter, "Failed to create image!");
1114 continue;
1115 }
1116
1117 GrBackendTexture origBackend = image->getBackendTexture(true);
1118 if (testCase.fCanTakeDirectly) {
1119 SkASSERT(origBackend.isValid());
1120 }
1121
1122 GrBackendTexture newBackend;
1123 SkImage::BackendTextureReleaseProc proc;
1124 bool result = SkImage::MakeBackendTextureFromSkImage(context, std::move(image),
1125 &newBackend, &proc);
1126 if (result != testCase.fExpectation) {
1127 static const char *const kFS[] = { "fail", "succeed" };
1128 ERRORF(reporter, "This image was expected to %s but did not.",
1129 kFS[testCase.fExpectation]);
1130 }
1131
1132 if (result) {
1133 SkASSERT(newBackend.isValid());
1134 }
1135
1136 bool tookDirectly = result && GrBackendTexture::TestingOnly_Equals(origBackend, newBackend);
1137 if (testCase.fCanTakeDirectly != tookDirectly) {
1138 static const char *const kExpectedState[] = { "not expected", "expected" };
1139 ERRORF(reporter, "This backend texture was %s to be taken directly.",
1140 kExpectedState[testCase.fCanTakeDirectly]);
1141 }
1142
1143 context->flush();
1144 }
1145 }
1146
1147 ///////////////////////////////////////////////////////////////////////////////////////////////////
1148
create_picture_image(sk_sp<SkColorSpace> space)1149 static sk_sp<SkImage> create_picture_image(sk_sp<SkColorSpace> space) {
1150 SkPictureRecorder recorder;
1151 SkCanvas* canvas = recorder.beginRecording(10, 10);
1152 canvas->clear(SK_ColorCYAN);
1153 return SkImage::MakeFromPicture(recorder.finishRecordingAsPicture(), SkISize::Make(10, 10),
1154 nullptr, nullptr, SkImage::BitDepth::kU8, std::move(space));
1155 };
1156
DEF_TEST(Image_ColorSpace,r)1157 DEF_TEST(Image_ColorSpace, r) {
1158 sk_sp<SkColorSpace> srgb = SkColorSpace::MakeSRGB();
1159 sk_sp<SkImage> image = GetResourceAsImage("images/mandrill_512_q075.jpg");
1160 REPORTER_ASSERT(r, srgb.get() == image->colorSpace());
1161
1162 image = GetResourceAsImage("images/webp-color-profile-lossy.webp");
1163 skcms_TransferFunction fn;
1164 bool success = image->colorSpace()->isNumericalTransferFn(&fn);
1165 REPORTER_ASSERT(r, success);
1166 REPORTER_ASSERT(r, color_space_almost_equal(1.8f, fn.g));
1167
1168 sk_sp<SkColorSpace> rec2020 = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB,
1169 SkNamedGamut::kRec2020);
1170 image = create_picture_image(rec2020);
1171 REPORTER_ASSERT(r, SkColorSpace::Equals(rec2020.get(), image->colorSpace()));
1172
1173 SkBitmap bitmap;
1174 SkImageInfo info = SkImageInfo::MakeN32(10, 10, kPremul_SkAlphaType, rec2020);
1175 bitmap.allocPixels(info);
1176 image = SkImage::MakeFromBitmap(bitmap);
1177 REPORTER_ASSERT(r, SkColorSpace::Equals(rec2020.get(), image->colorSpace()));
1178
1179 sk_sp<SkSurface> surface = SkSurface::MakeRaster(
1180 SkImageInfo::MakeN32Premul(SkISize::Make(10, 10)));
1181 image = surface->makeImageSnapshot();
1182 REPORTER_ASSERT(r, nullptr == image->colorSpace());
1183
1184 surface = SkSurface::MakeRaster(info);
1185 image = surface->makeImageSnapshot();
1186 REPORTER_ASSERT(r, SkColorSpace::Equals(rec2020.get(), image->colorSpace()));
1187 }
1188
DEF_TEST(Image_makeColorSpace,r)1189 DEF_TEST(Image_makeColorSpace, r) {
1190 sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDCIP3);
1191 skcms_TransferFunction fn;
1192 fn.a = 1.f; fn.b = 0.f; fn.c = 0.f; fn.d = 0.f; fn.e = 0.f; fn.f = 0.f; fn.g = 1.8f;
1193 sk_sp<SkColorSpace> adobeGamut = SkColorSpace::MakeRGB(fn, SkNamedGamut::kAdobeRGB);
1194
1195 SkBitmap srgbBitmap;
1196 srgbBitmap.allocPixels(SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType));
1197 *srgbBitmap.getAddr32(0, 0) = SkSwizzle_RGBA_to_PMColor(0xFF604020);
1198 srgbBitmap.setImmutable();
1199 sk_sp<SkImage> srgbImage = SkImage::MakeFromBitmap(srgbBitmap);
1200 sk_sp<SkImage> p3Image = srgbImage->makeColorSpace(p3);
1201 SkBitmap p3Bitmap;
1202 bool success = p3Image->asLegacyBitmap(&p3Bitmap);
1203
1204 auto almost_equal = [](int a, int b) { return SkTAbs(a - b) <= 2; };
1205
1206 REPORTER_ASSERT(r, success);
1207 REPORTER_ASSERT(r, almost_equal(0x28, SkGetPackedR32(*p3Bitmap.getAddr32(0, 0))));
1208 REPORTER_ASSERT(r, almost_equal(0x40, SkGetPackedG32(*p3Bitmap.getAddr32(0, 0))));
1209 REPORTER_ASSERT(r, almost_equal(0x5E, SkGetPackedB32(*p3Bitmap.getAddr32(0, 0))));
1210
1211 sk_sp<SkImage> adobeImage = srgbImage->makeColorSpace(adobeGamut);
1212 SkBitmap adobeBitmap;
1213 success = adobeImage->asLegacyBitmap(&adobeBitmap);
1214 REPORTER_ASSERT(r, success);
1215 REPORTER_ASSERT(r, almost_equal(0x21, SkGetPackedR32(*adobeBitmap.getAddr32(0, 0))));
1216 REPORTER_ASSERT(r, almost_equal(0x31, SkGetPackedG32(*adobeBitmap.getAddr32(0, 0))));
1217 REPORTER_ASSERT(r, almost_equal(0x4C, SkGetPackedB32(*adobeBitmap.getAddr32(0, 0))));
1218
1219 srgbImage = GetResourceAsImage("images/1x1.png");
1220 p3Image = srgbImage->makeColorSpace(p3);
1221 success = p3Image->asLegacyBitmap(&p3Bitmap);
1222 REPORTER_ASSERT(r, success);
1223 REPORTER_ASSERT(r, almost_equal(0x8B, SkGetPackedR32(*p3Bitmap.getAddr32(0, 0))));
1224 REPORTER_ASSERT(r, almost_equal(0x82, SkGetPackedG32(*p3Bitmap.getAddr32(0, 0))));
1225 REPORTER_ASSERT(r, almost_equal(0x77, SkGetPackedB32(*p3Bitmap.getAddr32(0, 0))));
1226 }
1227
1228 ///////////////////////////////////////////////////////////////////////////////////////////////////
1229
make_all_premul(SkBitmap * bm)1230 static void make_all_premul(SkBitmap* bm) {
1231 bm->allocPixels(SkImageInfo::MakeN32(256, 256, kPremul_SkAlphaType));
1232 for (int a = 0; a < 256; ++a) {
1233 for (int r = 0; r < 256; ++r) {
1234 // make all valid premul combinations
1235 int c = SkTMin(a, r);
1236 *bm->getAddr32(a, r) = SkPackARGB32(a, c, c, c);
1237 }
1238 }
1239 }
1240
equal(const SkBitmap & a,const SkBitmap & b)1241 static bool equal(const SkBitmap& a, const SkBitmap& b) {
1242 SkASSERT(a.width() == b.width());
1243 SkASSERT(a.height() == b.height());
1244 for (int y = 0; y < a.height(); ++y) {
1245 for (int x = 0; x < a.width(); ++x) {
1246 SkPMColor pa = *a.getAddr32(x, y);
1247 SkPMColor pb = *b.getAddr32(x, y);
1248 if (pa != pb) {
1249 return false;
1250 }
1251 }
1252 }
1253 return true;
1254 }
1255
DEF_TEST(image_roundtrip_encode,reporter)1256 DEF_TEST(image_roundtrip_encode, reporter) {
1257 SkBitmap bm0;
1258 make_all_premul(&bm0);
1259
1260 auto img0 = SkImage::MakeFromBitmap(bm0);
1261 sk_sp<SkData> data = img0->encodeToData(SkEncodedImageFormat::kPNG, 100);
1262 auto img1 = SkImage::MakeFromEncoded(data);
1263
1264 SkBitmap bm1;
1265 bm1.allocPixels(SkImageInfo::MakeN32(256, 256, kPremul_SkAlphaType));
1266 img1->readPixels(bm1.info(), bm1.getPixels(), bm1.rowBytes(), 0, 0);
1267
1268 REPORTER_ASSERT(reporter, equal(bm0, bm1));
1269 }
1270
DEF_TEST(image_roundtrip_premul,reporter)1271 DEF_TEST(image_roundtrip_premul, reporter) {
1272 SkBitmap bm0;
1273 make_all_premul(&bm0);
1274
1275 SkBitmap bm1;
1276 bm1.allocPixels(SkImageInfo::MakeN32(256, 256, kUnpremul_SkAlphaType));
1277 bm0.readPixels(bm1.info(), bm1.getPixels(), bm1.rowBytes(), 0, 0);
1278
1279 SkBitmap bm2;
1280 bm2.allocPixels(SkImageInfo::MakeN32(256, 256, kPremul_SkAlphaType));
1281 bm1.readPixels(bm2.info(), bm2.getPixels(), bm2.rowBytes(), 0, 0);
1282
1283 REPORTER_ASSERT(reporter, equal(bm0, bm2));
1284 }
1285
1286 ///////////////////////////////////////////////////////////////////////////////////////////////////
1287
check_scaled_pixels(skiatest::Reporter * reporter,SkPixmap * pmap,uint32_t expected)1288 static void check_scaled_pixels(skiatest::Reporter* reporter, SkPixmap* pmap, uint32_t expected) {
1289 // Verify that all pixels contain the original test color
1290 for (auto y = 0; y < pmap->height(); ++y) {
1291 for (auto x = 0; x < pmap->width(); ++x) {
1292 uint32_t pixel = *pmap->addr32(x, y);
1293 if (pixel != expected) {
1294 ERRORF(reporter, "Expected scaled pixels to be the same. At %d,%d 0x%08x != 0x%08x",
1295 x, y, pixel, expected);
1296 return;
1297 }
1298 }
1299 }
1300 }
1301
test_scale_pixels(skiatest::Reporter * reporter,const SkImage * image,uint32_t expected)1302 static void test_scale_pixels(skiatest::Reporter* reporter, const SkImage* image,
1303 uint32_t expected) {
1304 SkImageInfo info = SkImageInfo::MakeN32Premul(image->width() * 2, image->height() * 2);
1305
1306 // Make sure to test kDisallow first, so we don't just get a cache hit in that case
1307 for (auto chint : { SkImage::kDisallow_CachingHint, SkImage::kAllow_CachingHint }) {
1308 SkAutoPixmapStorage scaled;
1309 scaled.alloc(info);
1310 if (!image->scalePixels(scaled, kLow_SkFilterQuality, chint)) {
1311 ERRORF(reporter, "Failed to scale image");
1312 continue;
1313 }
1314
1315 check_scaled_pixels(reporter, &scaled, expected);
1316 }
1317 }
1318
DEF_TEST(ImageScalePixels,reporter)1319 DEF_TEST(ImageScalePixels, reporter) {
1320 const SkPMColor pmRed = SkPackARGB32(0xFF, 0xFF, 0, 0);
1321 const SkColor red = SK_ColorRED;
1322
1323 // Test raster image
1324 SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
1325 sk_sp<SkSurface> surface = SkSurface::MakeRaster(info);
1326 surface->getCanvas()->clear(red);
1327 sk_sp<SkImage> rasterImage = surface->makeImageSnapshot();
1328 test_scale_pixels(reporter, rasterImage.get(), pmRed);
1329
1330 // Test encoded image
1331 sk_sp<SkData> data = rasterImage->encodeToData();
1332 sk_sp<SkImage> codecImage = SkImage::MakeFromEncoded(data);
1333 test_scale_pixels(reporter, codecImage.get(), pmRed);
1334 }
1335
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageScalePixels_Gpu,reporter,ctxInfo)1336 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageScalePixels_Gpu, reporter, ctxInfo) {
1337 const SkPMColor pmRed = SkPackARGB32(0xFF, 0xFF, 0, 0);
1338 const SkColor red = SK_ColorRED;
1339
1340 SkImageInfo info = SkImageInfo::MakeN32Premul(16, 16);
1341 sk_sp<SkSurface> surface = SkSurface::MakeRenderTarget(ctxInfo.grContext(), SkBudgeted::kNo,
1342 info);
1343 surface->getCanvas()->clear(red);
1344 sk_sp<SkImage> gpuImage = surface->makeImageSnapshot();
1345 test_scale_pixels(reporter, gpuImage.get(), pmRed);
1346 }
1347
any_image_will_do()1348 static sk_sp<SkImage> any_image_will_do() {
1349 return GetResourceAsImage("images/mandrill_32.png");
1350 }
1351
DEF_TEST(Image_nonfinite_dst,reporter)1352 DEF_TEST(Image_nonfinite_dst, reporter) {
1353 auto surf = SkSurface::MakeRasterN32Premul(10, 10);
1354 auto img = any_image_will_do();
1355 SkPaint paint;
1356
1357 for (SkScalar bad : { SK_ScalarInfinity, SK_ScalarNaN}) {
1358 for (int bits = 1; bits <= 15; ++bits) {
1359 SkRect dst = { 0, 0, 10, 10 };
1360 if (bits & 1) dst.fLeft = bad;
1361 if (bits & 2) dst.fTop = bad;
1362 if (bits & 4) dst.fRight = bad;
1363 if (bits & 8) dst.fBottom = bad;
1364
1365 surf->getCanvas()->drawImageRect(img, dst, &paint);
1366
1367 // we should draw nothing
1368 sk_tool_utils::PixelIter iter(surf.get());
1369 while (void* addr = iter.next()) {
1370 REPORTER_ASSERT(reporter, *(SkPMColor*)addr == 0);
1371 }
1372 }
1373 }
1374 }
1375
1376