blob: d139ca7075101e524b9f6979c290f8e432bed110 [file] [log] [blame]
reed871872f2015-06-22 12:48:26 -07001/*
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
halcanaryc56c6ef2015-09-28 11:55:28 -07008#include "SkBitmap.h"
reed871872f2015-06-22 12:48:26 -07009#include "SkCanvas.h"
10#include "SkData.h"
11#include "SkDevice.h"
12#include "SkImageEncoder.h"
13#include "SkImage_Base.h"
fmalitac3470342015-09-04 11:36:39 -070014#include "SkPicture.h"
15#include "SkPictureRecorder.h"
fmalita2be71252015-09-03 07:17:25 -070016#include "SkPixelSerializer.h"
reed871872f2015-06-22 12:48:26 -070017#include "SkRRect.h"
fmalitac3470342015-09-04 11:36:39 -070018#include "SkStream.h"
reed871872f2015-06-22 12:48:26 -070019#include "SkSurface.h"
20#include "SkUtils.h"
21#include "Test.h"
22
23#if SK_SUPPORT_GPU
24#include "GrContextFactory.h"
25#include "GrTest.h"
26#include "gl/GrGLInterface.h"
27#include "gl/GrGLUtil.h"
28#else
29class GrContextFactory;
30class GrContext;
31#endif
32
33static void assert_equal(skiatest::Reporter* reporter, SkImage* a, const SkIRect* subsetA,
34 SkImage* b) {
35 const int widthA = subsetA ? subsetA->width() : a->width();
36 const int heightA = subsetA ? subsetA->height() : a->height();
37
38 REPORTER_ASSERT(reporter, widthA == b->width());
39 REPORTER_ASSERT(reporter, heightA == b->height());
40#if 0
halcanary6950de62015-11-07 05:29:00 -080041 // see https://bug.skia.org/3965
reed871872f2015-06-22 12:48:26 -070042 bool AO = a->isOpaque();
43 bool BO = b->isOpaque();
44 REPORTER_ASSERT(reporter, AO == BO);
45#endif
46
47 SkImageInfo info = SkImageInfo::MakeN32(widthA, heightA,
48 a->isOpaque() ? kOpaque_SkAlphaType : kPremul_SkAlphaType);
49 SkAutoPixmapStorage pmapA, pmapB;
50 pmapA.alloc(info);
51 pmapB.alloc(info);
52
53 const int srcX = subsetA ? subsetA->x() : 0;
54 const int srcY = subsetA ? subsetA->y() : 0;
55
56 REPORTER_ASSERT(reporter, a->readPixels(pmapA, srcX, srcY));
57 REPORTER_ASSERT(reporter, b->readPixels(pmapB, 0, 0));
58
59 const size_t widthBytes = widthA * info.bytesPerPixel();
60 for (int y = 0; y < heightA; ++y) {
61 REPORTER_ASSERT(reporter, !memcmp(pmapA.addr32(0, y), pmapB.addr32(0, y), widthBytes));
62 }
63}
64
65static SkImage* make_image(GrContext* ctx, int w, int h, const SkIRect& ir) {
66 const SkImageInfo info = SkImageInfo::MakeN32(w, h, kOpaque_SkAlphaType);
67 SkAutoTUnref<SkSurface> surface(ctx ?
68 SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted, info) :
69 SkSurface::NewRaster(info));
70 SkCanvas* canvas = surface->getCanvas();
71 canvas->clear(SK_ColorWHITE);
72
73 SkPaint paint;
74 paint.setColor(SK_ColorBLACK);
75 canvas->drawRect(SkRect::Make(ir), paint);
76 return surface->newImageSnapshot();
77}
78
79static void test_encode(skiatest::Reporter* reporter, GrContext* ctx) {
80 const SkIRect ir = SkIRect::MakeXYWH(5, 5, 10, 10);
81 SkAutoTUnref<SkImage> orig(make_image(ctx, 20, 20, ir));
82 SkAutoTUnref<SkData> origEncoded(orig->encode());
83 REPORTER_ASSERT(reporter, origEncoded);
84 REPORTER_ASSERT(reporter, origEncoded->size() > 0);
85
86 SkAutoTUnref<SkImage> decoded(SkImage::NewFromEncoded(origEncoded));
87 REPORTER_ASSERT(reporter, decoded);
halcanary96fcdcc2015-08-27 07:41:13 -070088 assert_equal(reporter, orig, nullptr, decoded);
reed871872f2015-06-22 12:48:26 -070089
90 // Now see if we can instantiate an image from a subset of the surface/origEncoded
91
92 decoded.reset(SkImage::NewFromEncoded(origEncoded, &ir));
93 REPORTER_ASSERT(reporter, decoded);
94 assert_equal(reporter, orig, &ir, decoded);
95}
96
97DEF_TEST(Image_Encode_Cpu, reporter) {
halcanary96fcdcc2015-08-27 07:41:13 -070098 test_encode(reporter, nullptr);
reed871872f2015-06-22 12:48:26 -070099}
100
101#if SK_SUPPORT_GPU
102DEF_GPUTEST(Image_Encode_Gpu, reporter, factory) {
103 GrContext* ctx = factory->get(GrContextFactory::kNative_GLContextType);
104 if (!ctx) {
105 REPORTER_ASSERT(reporter, false);
106 return;
107 }
108 test_encode(reporter, ctx);
109}
110#endif
reed759373a2015-07-03 21:01:10 -0700111
fmalita2be71252015-09-03 07:17:25 -0700112namespace {
113
114const char* kSerializedData = "serialized";
115
116class MockSerializer : public SkPixelSerializer {
fmalitac3470342015-09-04 11:36:39 -0700117public:
118 MockSerializer(SkData* (*func)()) : fFunc(func), fDidEncode(false) { }
119
120 bool didEncode() const { return fDidEncode; }
121
fmalita2be71252015-09-03 07:17:25 -0700122protected:
reedc9e190d2015-09-28 09:58:41 -0700123 bool onUseEncodedData(const void*, size_t) override {
124 return false;
fmalita2be71252015-09-03 07:17:25 -0700125 }
126
127 SkData* onEncodePixels(const SkImageInfo&, const void*, size_t) override {
fmalitac3470342015-09-04 11:36:39 -0700128 fDidEncode = true;
129 return fFunc();
fmalita2be71252015-09-03 07:17:25 -0700130 }
fmalitac3470342015-09-04 11:36:39 -0700131
132private:
133 SkData* (*fFunc)();
134 bool fDidEncode;
135
136 typedef SkPixelSerializer INHERITED;
fmalita2be71252015-09-03 07:17:25 -0700137};
138
139} // anonymous namespace
140
141// Test that SkImage encoding observes custom pixel serializers.
142DEF_TEST(Image_Encode_Serializer, reporter) {
fmalitac3470342015-09-04 11:36:39 -0700143 MockSerializer serializer([]() -> SkData* { return SkData::NewWithCString(kSerializedData); });
fmalita2be71252015-09-03 07:17:25 -0700144 const SkIRect ir = SkIRect::MakeXYWH(5, 5, 10, 10);
145 SkAutoTUnref<SkImage> image(make_image(nullptr, 20, 20, ir));
146 SkAutoTUnref<SkData> encoded(image->encode(&serializer));
147 SkAutoTUnref<SkData> reference(SkData::NewWithCString(kSerializedData));
148
fmalitac3470342015-09-04 11:36:39 -0700149 REPORTER_ASSERT(reporter, serializer.didEncode());
fmalita2be71252015-09-03 07:17:25 -0700150 REPORTER_ASSERT(reporter, encoded);
151 REPORTER_ASSERT(reporter, encoded->size() > 0);
152 REPORTER_ASSERT(reporter, encoded->equals(reference));
153}
154
fmalitac3470342015-09-04 11:36:39 -0700155// Test that image encoding failures do not break picture serialization/deserialization.
156DEF_TEST(Image_Serialize_Encoding_Failure, reporter) {
157 SkAutoTUnref<SkSurface> surface(SkSurface::NewRasterN32Premul(100, 100));
158 surface->getCanvas()->clear(SK_ColorGREEN);
159 SkAutoTUnref<SkImage> image(surface->newImageSnapshot());
160 REPORTER_ASSERT(reporter, image);
161
162 SkPictureRecorder recorder;
163 SkCanvas* canvas = recorder.beginRecording(100, 100);
164 canvas->drawImage(image, 0, 0);
165 SkAutoTUnref<SkPicture> picture(recorder.endRecording());
166 REPORTER_ASSERT(reporter, picture);
167 REPORTER_ASSERT(reporter, picture->approximateOpCount() > 0);
168
169 MockSerializer emptySerializer([]() -> SkData* { return SkData::NewEmpty(); });
170 MockSerializer nullSerializer([]() -> SkData* { return nullptr; });
171 MockSerializer* serializers[] = { &emptySerializer, &nullSerializer };
172
173 for (size_t i = 0; i < SK_ARRAY_COUNT(serializers); ++i) {
174 SkDynamicMemoryWStream wstream;
175 REPORTER_ASSERT(reporter, !serializers[i]->didEncode());
176 picture->serialize(&wstream, serializers[i]);
177 REPORTER_ASSERT(reporter, serializers[i]->didEncode());
178
179 SkAutoTDelete<SkStream> rstream(wstream.detachAsStream());
180 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rstream));
181 REPORTER_ASSERT(reporter, deserialized);
182 REPORTER_ASSERT(reporter, deserialized->approximateOpCount() > 0);
183 }
184}
185
reed759373a2015-07-03 21:01:10 -0700186DEF_TEST(Image_NewRasterCopy, reporter) {
187 const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
188 const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
189 const SkPMColor blue = SkPackARGB32(0xFF, 0, 0, 0xFF);
190 SkPMColor colors[] = { red, green, blue, 0 };
halcanary385fe4d2015-08-26 13:07:48 -0700191 SkAutoTUnref<SkColorTable> ctable(new SkColorTable(colors, SK_ARRAY_COUNT(colors)));
reed759373a2015-07-03 21:01:10 -0700192 // The colortable made a copy, so we can trash the original colors
193 memset(colors, 0xFF, sizeof(colors));
194
195 const SkImageInfo srcInfo = SkImageInfo::Make(2, 2, kIndex_8_SkColorType, kPremul_SkAlphaType);
196 const size_t srcRowBytes = 2 * sizeof(uint8_t);
197 uint8_t indices[] = { 0, 1, 2, 3 };
198 SkAutoTUnref<SkImage> image(SkImage::NewRasterCopy(srcInfo, indices, srcRowBytes, ctable));
199 // The image made a copy, so we can trash the original indices
200 memset(indices, 0xFF, sizeof(indices));
201
202 const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
203 const size_t dstRowBytes = 2 * sizeof(SkPMColor);
204 SkPMColor pixels[4];
205 memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
206 image->readPixels(dstInfo, pixels, dstRowBytes, 0, 0);
207 REPORTER_ASSERT(reporter, red == pixels[0]);
208 REPORTER_ASSERT(reporter, green == pixels[1]);
209 REPORTER_ASSERT(reporter, blue == pixels[2]);
210 REPORTER_ASSERT(reporter, 0 == pixels[3]);
211}
fmalita8c0144c2015-07-22 05:56:16 -0700212
213// Test that a draw that only partially covers the drawing surface isn't
214// interpreted as covering the entire drawing surface (i.e., exercise one of the
215// conditions of SkCanvas::wouldOverwriteEntireSurface()).
216DEF_TEST(Image_RetainSnapshot, reporter) {
217 const SkPMColor red = SkPackARGB32(0xFF, 0xFF, 0, 0);
218 const SkPMColor green = SkPackARGB32(0xFF, 0, 0xFF, 0);
219 SkImageInfo info = SkImageInfo::MakeN32Premul(2, 2);
220 SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(info));
221 surface->getCanvas()->clear(0xFF00FF00);
222
223 SkPMColor pixels[4];
224 memset(pixels, 0xFF, sizeof(pixels)); // init with values we don't expect
225 const SkImageInfo dstInfo = SkImageInfo::MakeN32Premul(2, 2);
226 const size_t dstRowBytes = 2 * sizeof(SkPMColor);
227
228 SkAutoTUnref<SkImage> image1(surface->newImageSnapshot());
229 REPORTER_ASSERT(reporter, image1->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
230 for (size_t i = 0; i < SK_ARRAY_COUNT(pixels); ++i) {
231 REPORTER_ASSERT(reporter, pixels[i] == green);
232 }
233
234 SkPaint paint;
235 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
236 paint.setColor(SK_ColorRED);
237
238 surface->getCanvas()->drawRect(SkRect::MakeXYWH(1, 1, 1, 1), paint);
239
240 SkAutoTUnref<SkImage> image2(surface->newImageSnapshot());
241 REPORTER_ASSERT(reporter, image2->readPixels(dstInfo, pixels, dstRowBytes, 0, 0));
242 REPORTER_ASSERT(reporter, pixels[0] == green);
243 REPORTER_ASSERT(reporter, pixels[1] == green);
244 REPORTER_ASSERT(reporter, pixels[2] == green);
245 REPORTER_ASSERT(reporter, pixels[3] == red);
246}
reed80c772b2015-07-30 18:58:23 -0700247
248/////////////////////////////////////////////////////////////////////////////////////////////////
reed80c772b2015-07-30 18:58:23 -0700249
250static void make_bitmap_mutable(SkBitmap* bm) {
251 bm->allocN32Pixels(10, 10);
252}
253
254static void make_bitmap_immutable(SkBitmap* bm) {
255 bm->allocN32Pixels(10, 10);
256 bm->setImmutable();
257}
258
259DEF_TEST(image_newfrombitmap, reporter) {
260 const struct {
261 void (*fMakeProc)(SkBitmap*);
262 bool fExpectPeekSuccess;
263 bool fExpectSharedID;
fmalitaddbbdda2015-08-20 08:47:26 -0700264 bool fExpectLazy;
reed80c772b2015-07-30 18:58:23 -0700265 } rec[] = {
fmalitaddbbdda2015-08-20 08:47:26 -0700266 { make_bitmap_mutable, true, false, false },
267 { make_bitmap_immutable, true, true, false },
reed80c772b2015-07-30 18:58:23 -0700268 };
269
270 for (size_t i = 0; i < SK_ARRAY_COUNT(rec); ++i) {
271 SkBitmap bm;
272 rec[i].fMakeProc(&bm);
273
274 SkAutoTUnref<SkImage> image(SkImage::NewFromBitmap(bm));
275 SkPixmap pmap;
276
277 const bool sharedID = (image->uniqueID() == bm.getGenerationID());
278 REPORTER_ASSERT(reporter, sharedID == rec[i].fExpectSharedID);
279
reed80c772b2015-07-30 18:58:23 -0700280 const bool peekSuccess = image->peekPixels(&pmap);
281 REPORTER_ASSERT(reporter, peekSuccess == rec[i].fExpectPeekSuccess);
fmalitaddbbdda2015-08-20 08:47:26 -0700282
283 const bool lazy = image->isLazyGenerated();
284 REPORTER_ASSERT(reporter, lazy == rec[i].fExpectLazy);
reed80c772b2015-07-30 18:58:23 -0700285 }
286}
reed6f1216a2015-08-04 08:10:13 -0700287
288///////////////////////////////////////////////////////////////////////////////////////////////////
289#if SK_SUPPORT_GPU
290
291static SkImage* make_gpu_image(GrContext* ctx, const SkImageInfo& info, SkColor color) {
292 const SkSurface::Budgeted budgeted = SkSurface::kNo_Budgeted;
293 SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, budgeted, info, 0));
294 surface->getCanvas()->drawColor(color);
295 return surface->newImageSnapshot();
296}
297
298#include "SkBitmapCache.h"
299
300/*
301 * This tests the caching (and preemptive purge) of the raster equivalent of a gpu-image.
302 * We cache it for performance when drawing into a raster surface.
303 *
304 * A cleaner test would know if each drawImage call triggered a read-back from the gpu,
305 * but we don't have that facility (at the moment) so we use a little internal knowledge
306 * of *how* the raster version is cached, and look for that.
307 */
308DEF_GPUTEST(SkImage_Gpu2Cpu, reporter, factory) {
309 GrContext* ctx = factory->get(GrContextFactory::kNative_GLContextType);
310 if (!ctx) {
311 REPORTER_ASSERT(reporter, false);
312 return;
313 }
314
315 const SkImageInfo info = SkImageInfo::MakeN32Premul(10, 10);
316 SkAutoTUnref<SkImage> image(make_gpu_image(ctx, info, SK_ColorRED));
317 const uint32_t uniqueID = image->uniqueID();
318
319 SkAutoTUnref<SkSurface> surface(SkSurface::NewRaster(info));
320
321 // now we can test drawing a gpu-backed image into a cpu-backed surface
322
323 {
324 SkBitmap cachedBitmap;
325 REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
326 }
327
328 surface->getCanvas()->drawImage(image, 0, 0);
329 {
330 SkBitmap cachedBitmap;
331 if (SkBitmapCache::Find(uniqueID, &cachedBitmap)) {
332 REPORTER_ASSERT(reporter, cachedBitmap.getGenerationID() == uniqueID);
333 REPORTER_ASSERT(reporter, cachedBitmap.isImmutable());
334 REPORTER_ASSERT(reporter, cachedBitmap.getPixels());
335 } else {
336 // unexpected, but not really a bug, since the cache is global and this test may be
337 // run w/ other threads competing for its budget.
338 SkDebugf("SkImage_Gpu2Cpu : cachedBitmap was already purged\n");
339 }
340 }
341
342 image.reset(nullptr);
343 {
344 SkBitmap cachedBitmap;
345 REPORTER_ASSERT(reporter, !SkBitmapCache::Find(uniqueID, &cachedBitmap));
346 }
347}
348#endif
halcanaryc56c6ef2015-09-28 11:55:28 -0700349
halcanary6950de62015-11-07 05:29:00 -0800350// https://bug.skia.org/4390
halcanaryc56c6ef2015-09-28 11:55:28 -0700351DEF_TEST(ImageFromIndex8Bitmap, r) {
352 SkPMColor pmColors[1] = {SkPreMultiplyColor(SK_ColorWHITE)};
353 SkBitmap bm;
354 SkAutoTUnref<SkColorTable> ctable(
355 new SkColorTable(pmColors, SK_ARRAY_COUNT(pmColors)));
356 SkImageInfo info =
357 SkImageInfo::Make(1, 1, kIndex_8_SkColorType, kPremul_SkAlphaType);
358 bm.allocPixels(info, nullptr, ctable);
359 SkAutoLockPixels autoLockPixels(bm);
360 *bm.getAddr8(0, 0) = 0;
361 SkAutoTUnref<SkImage> img(SkImage::NewFromBitmap(bm));
362 REPORTER_ASSERT(r, img.get() != nullptr);
363}
kkinnunen4e184132015-11-17 22:53:28 -0800364
365// TODO: The tests below were moved from SurfaceTests and should be reformatted.
366
367enum ImageType {
368 kRasterCopy_ImageType,
369 kRasterData_ImageType,
370 kRasterProc_ImageType,
371 kGpu_ImageType,
372 kCodec_ImageType,
373};
374
375#include "SkImageGenerator.h"
376
377class EmptyGenerator : public SkImageGenerator {
378public:
379 EmptyGenerator() : SkImageGenerator(SkImageInfo::MakeN32Premul(0, 0)) {}
380};
381
382static void test_empty_image(skiatest::Reporter* reporter) {
383 const SkImageInfo info = SkImageInfo::Make(0, 0, kN32_SkColorType, kPremul_SkAlphaType);
384
385 REPORTER_ASSERT(reporter, nullptr == SkImage::NewRasterCopy(info, nullptr, 0));
386 REPORTER_ASSERT(reporter, nullptr == SkImage::NewRasterData(info, nullptr, 0));
387 REPORTER_ASSERT(reporter, nullptr == SkImage::NewFromRaster(info, nullptr, 0, nullptr, nullptr));
388 REPORTER_ASSERT(reporter, nullptr == SkImage::NewFromGenerator(new EmptyGenerator));
389}
390
391static void test_image(skiatest::Reporter* reporter) {
392 SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
393 size_t rowBytes = info.minRowBytes();
394 size_t size = info.getSafeSize(rowBytes);
395 SkData* data = SkData::NewUninitialized(size);
396
397 REPORTER_ASSERT(reporter, data->unique());
398 SkImage* image = SkImage::NewRasterData(info, data, rowBytes);
399 REPORTER_ASSERT(reporter, !data->unique());
400 image->unref();
401 REPORTER_ASSERT(reporter, data->unique());
402 data->unref();
403}
404
405// Want to ensure that our Release is called when the owning image is destroyed
406struct ReleaseDataContext {
407 skiatest::Reporter* fReporter;
408 SkData* fData;
409
410 static void Release(const void* pixels, void* context) {
411 ReleaseDataContext* state = (ReleaseDataContext*)context;
412 REPORTER_ASSERT(state->fReporter, state->fData);
413 state->fData->unref();
414 state->fData = nullptr;
415 }
416};
417
418// May we (soon) eliminate the need to keep testing this, by hiding the bloody device!
419#include "SkDevice.h"
420static uint32_t get_legacy_gen_id(SkSurface* surf) {
421 SkBaseDevice* device = surf->getCanvas()->getDevice_just_for_deprecated_compatibility_testing();
422 return device->accessBitmap(false).getGenerationID();
423}
424
425/*
426 * Test legacy behavor of bumping the surface's device's bitmap's genID when we access its
427 * texture handle for writing.
428 *
429 * Note: this needs to be tested separately from checking newImageSnapshot, as calling that
430 * can also incidentally bump the genID (when a new backing surface is created).
431 */
432template <class F>
433static void test_texture_handle_genID(skiatest::Reporter* reporter, SkSurface* surf, F f) {
434 const uint32_t gen0 = get_legacy_gen_id(surf);
435 f(surf, SkSurface::kFlushRead_BackendHandleAccess);
436 const uint32_t gen1 = get_legacy_gen_id(surf);
437 REPORTER_ASSERT(reporter, gen0 == gen1);
438
439 f(surf, SkSurface::kFlushWrite_BackendHandleAccess);
440 const uint32_t gen2 = get_legacy_gen_id(surf);
441 REPORTER_ASSERT(reporter, gen0 != gen2);
442
443 f(surf, SkSurface::kDiscardWrite_BackendHandleAccess);
444 const uint32_t gen3 = get_legacy_gen_id(surf);
445 REPORTER_ASSERT(reporter, gen0 != gen3);
446 REPORTER_ASSERT(reporter, gen2 != gen3);
447}
448
449template <class F>
450static void test_backend_handle(skiatest::Reporter* reporter, SkSurface* surf, F f) {
451 SkAutoTUnref<SkImage> image0(surf->newImageSnapshot());
452 GrBackendObject obj = f(surf, SkSurface::kFlushRead_BackendHandleAccess);
453 REPORTER_ASSERT(reporter, obj != 0);
454 SkAutoTUnref<SkImage> image1(surf->newImageSnapshot());
455 // just read access should not affect the snapshot
456 REPORTER_ASSERT(reporter, image0->uniqueID() == image1->uniqueID());
457
458 obj = f(surf, SkSurface::kFlushWrite_BackendHandleAccess);
459 REPORTER_ASSERT(reporter, obj != 0);
460 SkAutoTUnref<SkImage> image2(surf->newImageSnapshot());
461 // expect a new image, since we claimed we would write
462 REPORTER_ASSERT(reporter, image0->uniqueID() != image2->uniqueID());
463
464 obj = f(surf, SkSurface::kDiscardWrite_BackendHandleAccess);
465 REPORTER_ASSERT(reporter, obj != 0);
466 SkAutoTUnref<SkImage> image3(surf->newImageSnapshot());
467 // expect a new(er) image, since we claimed we would write
468 REPORTER_ASSERT(reporter, image0->uniqueID() != image3->uniqueID());
469 REPORTER_ASSERT(reporter, image2->uniqueID() != image3->uniqueID());
470}
471
472static SkImage* create_image(skiatest::Reporter* reporter,
473 ImageType imageType, GrContext* context, SkColor color,
474 ReleaseDataContext* releaseContext) {
475 const SkPMColor pmcolor = SkPreMultiplyColor(color);
476 const SkImageInfo info = SkImageInfo::MakeN32Premul(10, 10);
477 const size_t rowBytes = info.minRowBytes();
478 const size_t size = rowBytes * info.height();
479
480 SkAutoTUnref<SkData> data(SkData::NewUninitialized(size));
481 void* addr = data->writable_data();
482 sk_memset32((SkPMColor*)addr, pmcolor, SkToInt(size >> 2));
483
484 switch (imageType) {
485 case kRasterCopy_ImageType:
486 return SkImage::NewRasterCopy(info, addr, rowBytes);
487 case kRasterData_ImageType:
488 return SkImage::NewRasterData(info, data, rowBytes);
489 case kRasterProc_ImageType:
490 SkASSERT(releaseContext);
491 releaseContext->fData = SkRef(data.get());
492 return SkImage::NewFromRaster(info, addr, rowBytes,
493 ReleaseDataContext::Release, releaseContext);
494 case kGpu_ImageType: {
495 SkAutoTUnref<SkSurface> surf(
496 SkSurface::NewRenderTarget(context, SkSurface::kNo_Budgeted, info, 0));
497 surf->getCanvas()->clear(color);
498 // test our backing texture / rendertarget while were here...
499 auto textureAccessorFunc =
500 [](SkSurface* surf, SkSurface::BackendHandleAccess access) -> GrBackendObject {
501 return surf->getTextureHandle(access); };
502 auto renderTargetAccessorFunc =
503 [](SkSurface* surf, SkSurface::BackendHandleAccess access) -> GrBackendObject {
504 GrBackendObject obj;
505 SkAssertResult(surf->getRenderTargetHandle(&obj, access));
506 return obj; };
507 test_backend_handle(reporter, surf, textureAccessorFunc);
508 test_backend_handle(reporter, surf, renderTargetAccessorFunc);
509 test_texture_handle_genID(reporter, surf, textureAccessorFunc);
510 test_texture_handle_genID(reporter, surf, renderTargetAccessorFunc);
511
512 // redraw so our returned image looks as expected.
513 surf->getCanvas()->clear(color);
514 return surf->newImageSnapshot();
515 }
516 case kCodec_ImageType: {
517 SkBitmap bitmap;
518 bitmap.installPixels(info, addr, rowBytes);
519 SkAutoTUnref<SkData> src(
520 SkImageEncoder::EncodeData(bitmap, SkImageEncoder::kPNG_Type, 100));
521 return SkImage::NewFromEncoded(src);
522 }
523 }
524 SkASSERT(false);
525 return nullptr;
526}
527
528static void set_pixels(SkPMColor pixels[], int count, SkPMColor color) {
529 sk_memset32(pixels, color, count);
530}
531static bool has_pixels(const SkPMColor pixels[], int count, SkPMColor expected) {
532 for (int i = 0; i < count; ++i) {
533 if (pixels[i] != expected) {
534 return false;
535 }
536 }
537 return true;
538}
539
540static void test_image_readpixels(skiatest::Reporter* reporter, SkImage* image,
541 SkPMColor expected) {
542 const SkPMColor notExpected = ~expected;
543
544 const int w = 2, h = 2;
545 const size_t rowBytes = w * sizeof(SkPMColor);
546 SkPMColor pixels[w*h];
547
548 SkImageInfo info;
549
550 info = SkImageInfo::MakeUnknown(w, h);
551 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, 0));
552
553 // out-of-bounds should fail
554 info = SkImageInfo::MakeN32Premul(w, h);
555 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, -w, 0));
556 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, -h));
557 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, image->width(), 0));
558 REPORTER_ASSERT(reporter, !image->readPixels(info, pixels, rowBytes, 0, image->height()));
559
560 // top-left should succeed
561 set_pixels(pixels, w*h, notExpected);
562 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, 0, 0));
563 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
564
565 // bottom-right should succeed
566 set_pixels(pixels, w*h, notExpected);
567 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
568 image->width() - w, image->height() - h));
569 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h, expected));
570
571 // partial top-left should succeed
572 set_pixels(pixels, w*h, notExpected);
573 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes, -1, -1));
574 REPORTER_ASSERT(reporter, pixels[3] == expected);
575 REPORTER_ASSERT(reporter, has_pixels(pixels, w*h - 1, notExpected));
576
577 // partial bottom-right should succeed
578 set_pixels(pixels, w*h, notExpected);
579 REPORTER_ASSERT(reporter, image->readPixels(info, pixels, rowBytes,
580 image->width() - 1, image->height() - 1));
581 REPORTER_ASSERT(reporter, pixels[0] == expected);
582 REPORTER_ASSERT(reporter, has_pixels(&pixels[1], w*h - 1, notExpected));
583}
584
585static void check_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image,
586 const SkBitmap& bitmap, SkImage::LegacyBitmapMode mode) {
587 REPORTER_ASSERT(reporter, image->width() == bitmap.width());
588 REPORTER_ASSERT(reporter, image->height() == bitmap.height());
589 REPORTER_ASSERT(reporter, image->isOpaque() == bitmap.isOpaque());
590
591 if (SkImage::kRO_LegacyBitmapMode == mode) {
592 REPORTER_ASSERT(reporter, bitmap.isImmutable());
593 }
594
595 SkAutoLockPixels alp(bitmap);
596 REPORTER_ASSERT(reporter, bitmap.getPixels());
597
598 const SkImageInfo info = SkImageInfo::MakeN32(1, 1, bitmap.alphaType());
599 SkPMColor imageColor;
600 REPORTER_ASSERT(reporter, image->readPixels(info, &imageColor, sizeof(SkPMColor), 0, 0));
601 REPORTER_ASSERT(reporter, imageColor == *bitmap.getAddr32(0, 0));
602}
603
604static void test_legacy_bitmap(skiatest::Reporter* reporter, const SkImage* image) {
605 const SkImage::LegacyBitmapMode modes[] = {
606 SkImage::kRO_LegacyBitmapMode,
607 SkImage::kRW_LegacyBitmapMode,
608 };
609 for (size_t i = 0; i < SK_ARRAY_COUNT(modes); ++i) {
610 SkBitmap bitmap;
611 REPORTER_ASSERT(reporter, image->asLegacyBitmap(&bitmap, modes[i]));
612 check_legacy_bitmap(reporter, image, bitmap, modes[i]);
613
614 // Test subsetting to exercise the rowBytes logic.
615 SkBitmap tmp;
616 REPORTER_ASSERT(reporter, bitmap.extractSubset(&tmp, SkIRect::MakeWH(image->width() / 2,
617 image->height() / 2)));
618 SkAutoTUnref<SkImage> subsetImage(SkImage::NewFromBitmap(tmp));
619 REPORTER_ASSERT(reporter, subsetImage);
620
621 SkBitmap subsetBitmap;
622 REPORTER_ASSERT(reporter, subsetImage->asLegacyBitmap(&subsetBitmap, modes[i]));
623 check_legacy_bitmap(reporter, subsetImage, subsetBitmap, modes[i]);
624 }
625}
626
627static void test_imagepeek(skiatest::Reporter* reporter, GrContextFactory* factory) {
628 static const struct {
629 ImageType fType;
630 bool fPeekShouldSucceed;
631 const char* fName;
632 } gRec[] = {
633 { kRasterCopy_ImageType, true, "RasterCopy" },
634 { kRasterData_ImageType, true, "RasterData" },
635 { kRasterProc_ImageType, true, "RasterProc" },
636 { kGpu_ImageType, false, "Gpu" },
637 { kCodec_ImageType, false, "Codec" },
638 };
639
640 const SkColor color = SK_ColorRED;
641 const SkPMColor pmcolor = SkPreMultiplyColor(color);
642
643 GrContext* ctx = nullptr;
644#if SK_SUPPORT_GPU
645 ctx = factory->get(GrContextFactory::kNative_GLContextType);
646 if (nullptr == ctx) {
647 return;
648 }
649#endif
650
651 ReleaseDataContext releaseCtx;
652 releaseCtx.fReporter = reporter;
653
654 for (size_t i = 0; i < SK_ARRAY_COUNT(gRec); ++i) {
655 SkImageInfo info;
656 size_t rowBytes;
657
658 releaseCtx.fData = nullptr;
659 SkAutoTUnref<SkImage> image(create_image(reporter, gRec[i].fType, ctx, color, &releaseCtx));
660 if (!image.get()) {
661 SkDebugf("failed to createImage[%d] %s\n", i, gRec[i].fName);
662 continue; // gpu may not be enabled
663 }
664 if (kRasterProc_ImageType == gRec[i].fType) {
665 REPORTER_ASSERT(reporter, nullptr != releaseCtx.fData); // we are tracking the data
666 } else {
667 REPORTER_ASSERT(reporter, nullptr == releaseCtx.fData); // we ignored the context
668 }
669
670 test_legacy_bitmap(reporter, image);
671
672 const void* addr = image->peekPixels(&info, &rowBytes);
673 bool success = SkToBool(addr);
674 REPORTER_ASSERT(reporter, gRec[i].fPeekShouldSucceed == success);
675 if (success) {
676 REPORTER_ASSERT(reporter, 10 == info.width());
677 REPORTER_ASSERT(reporter, 10 == info.height());
678 REPORTER_ASSERT(reporter, kN32_SkColorType == info.colorType());
679 REPORTER_ASSERT(reporter, kPremul_SkAlphaType == info.alphaType() ||
680 kOpaque_SkAlphaType == info.alphaType());
681 REPORTER_ASSERT(reporter, info.minRowBytes() <= rowBytes);
682 REPORTER_ASSERT(reporter, pmcolor == *(const SkPMColor*)addr);
683 }
684
685 test_image_readpixels(reporter, image, pmcolor);
686 }
687 REPORTER_ASSERT(reporter, nullptr == releaseCtx.fData); // we released the data
688}
689#if SK_SUPPORT_GPU
690
691struct ReleaseTextureContext {
692 ReleaseTextureContext(skiatest::Reporter* reporter) {
693 fReporter = reporter;
694 fIsReleased = false;
695 }
696
697 skiatest::Reporter* fReporter;
698 bool fIsReleased;
699
700 void doRelease() {
701 REPORTER_ASSERT(fReporter, false == fIsReleased);
702 fIsReleased = true;
703 }
704
705 static void ReleaseProc(void* context) {
706 ((ReleaseTextureContext*)context)->doRelease();
707 }
708};
709
710static SkImage* make_desc_image(GrContext* ctx, int w, int h, GrBackendObject texID,
711 ReleaseTextureContext* releaseContext) {
712 GrBackendTextureDesc desc;
713 desc.fConfig = kSkia8888_GrPixelConfig;
714 // need to be a rendertarget for now...
715 desc.fFlags = kRenderTarget_GrBackendTextureFlag;
716 desc.fWidth = w;
717 desc.fHeight = h;
718 desc.fSampleCnt = 0;
719 desc.fTextureHandle = texID;
720 return releaseContext
721 ? SkImage::NewFromTexture(ctx, desc, kPremul_SkAlphaType,
722 ReleaseTextureContext::ReleaseProc, releaseContext)
723 : SkImage::NewFromTextureCopy(ctx, desc, kPremul_SkAlphaType);
724}
725
726static void test_image_color(skiatest::Reporter* reporter, SkImage* image, SkPMColor expected) {
727 const SkImageInfo info = SkImageInfo::MakeN32Premul(1, 1);
728 SkPMColor pixel;
729 REPORTER_ASSERT(reporter, image->readPixels(info, &pixel, sizeof(pixel), 0, 0));
730 REPORTER_ASSERT(reporter, pixel == expected);
731}
732
733DEF_GPUTEST(SkImage_NewFromTexture, reporter, factory) {
734 GrContext* ctx = factory->get(GrContextFactory::kNative_GLContextType);
735 if (!ctx) {
736 REPORTER_ASSERT(reporter, false);
737 return;
738 }
739 GrTextureProvider* provider = ctx->textureProvider();
740
741 const int w = 10;
742 const int h = 10;
743 SkPMColor storage[w * h];
744 const SkPMColor expected0 = SkPreMultiplyColor(SK_ColorRED);
745 sk_memset32(storage, expected0, w * h);
746
747 GrSurfaceDesc desc;
748 desc.fFlags = kRenderTarget_GrSurfaceFlag; // needs to be a rendertarget for readpixels();
749 desc.fOrigin = kDefault_GrSurfaceOrigin;
750 desc.fWidth = w;
751 desc.fHeight = h;
752 desc.fConfig = kSkia8888_GrPixelConfig;
753 desc.fSampleCnt = 0;
754
755 SkAutoTUnref<GrTexture> tex(provider->createTexture(desc, false, storage, w * 4));
756 if (!tex) {
757 REPORTER_ASSERT(reporter, false);
758 return;
759 }
760
761 GrBackendObject srcTex = tex->getTextureHandle();
762 ReleaseTextureContext releaseCtx(reporter);
763
764 SkAutoTUnref<SkImage> refImg(make_desc_image(ctx, w, h, srcTex, &releaseCtx));
765 SkAutoTUnref<SkImage> cpyImg(make_desc_image(ctx, w, h, srcTex, nullptr));
766
767 test_image_color(reporter, refImg, expected0);
768 test_image_color(reporter, cpyImg, expected0);
769
770 // Now lets jam new colors into our "external" texture, and see if the images notice
771 const SkPMColor expected1 = SkPreMultiplyColor(SK_ColorBLUE);
772 sk_memset32(storage, expected1, w * h);
773 tex->writePixels(0, 0, w, h, kSkia8888_GrPixelConfig, storage, GrContext::kFlushWrites_PixelOp);
774
775 // The cpy'd one should still see the old color
776#if 0
777 // There is no guarantee that refImg sees the new color. We are free to have made a copy. Our
778 // write pixels call violated the contract with refImg and refImg is now undefined.
779 test_image_color(reporter, refImg, expected1);
780#endif
781 test_image_color(reporter, cpyImg, expected0);
782
783 // Now exercise the release proc
784 REPORTER_ASSERT(reporter, !releaseCtx.fIsReleased);
785 refImg.reset(nullptr); // force a release of the image
786 REPORTER_ASSERT(reporter, releaseCtx.fIsReleased);
787}
788#endif
789DEF_GPUTEST(ImageTestsFromSurfaceTestsTODO, reporter, factory) {
790 test_image(reporter);
791 test_empty_image(reporter);
792 test_imagepeek(reporter, factory);
793}