• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 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 <initializer_list>
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkSurface.h"
11 #include "include/gpu/GrContext.h"
12 #include "include/private/SkColorData.h"
13 #include "include/private/SkHalf.h"
14 #include "include/private/SkImageInfoPriv.h"
15 #include "src/core/SkAutoPixmapStorage.h"
16 #include "src/core/SkConvertPixels.h"
17 #include "src/core/SkMathPriv.h"
18 #include "src/gpu/GrContextPriv.h"
19 #include "src/gpu/GrProxyProvider.h"
20 #include "src/gpu/SkGr.h"
21 #include "tests/Test.h"
22 #include "tests/TestUtils.h"
23 #include "tools/gpu/GrContextFactory.h"
24 #include "tools/gpu/ProxyUtils.h"
25 
26 static const int DEV_W = 100, DEV_H = 100;
27 static const SkIRect DEV_RECT = SkIRect::MakeWH(DEV_W, DEV_H);
28 static const SkRect DEV_RECT_S = SkRect::MakeWH(DEV_W * SK_Scalar1,
29                                                 DEV_H * SK_Scalar1);
30 
get_src_color(int x,int y)31 static SkPMColor get_src_color(int x, int y) {
32     SkASSERT(x >= 0 && x < DEV_W);
33     SkASSERT(y >= 0 && y < DEV_H);
34 
35     U8CPU r = x;
36     U8CPU g = y;
37     U8CPU b = 0xc;
38 
39     U8CPU a = 0xff;
40     switch ((x+y) % 5) {
41         case 0:
42             a = 0xff;
43             break;
44         case 1:
45             a = 0x80;
46             break;
47         case 2:
48             a = 0xCC;
49             break;
50         case 4:
51             a = 0x01;
52             break;
53         case 3:
54             a = 0x00;
55             break;
56     }
57     return SkPremultiplyARGBInline(a, r, g, b);
58 }
59 
get_dst_bmp_init_color(int x,int y,int w)60 static SkPMColor get_dst_bmp_init_color(int x, int y, int w) {
61     int n = y * w + x;
62 
63     U8CPU b = n & 0xff;
64     U8CPU g = (n >> 8) & 0xff;
65     U8CPU r = (n >> 16) & 0xff;
66     return SkPackARGB32(0xff, r, g , b);
67 }
68 
69 // TODO: Make this consider both ATs
convert_to_pmcolor(SkColorType ct,SkAlphaType at,const uint32_t * addr,bool * doUnpremul)70 static SkPMColor convert_to_pmcolor(SkColorType ct, SkAlphaType at, const uint32_t* addr,
71                                     bool* doUnpremul) {
72     *doUnpremul = (kUnpremul_SkAlphaType == at);
73 
74     const uint8_t* c = reinterpret_cast<const uint8_t*>(addr);
75     U8CPU a,r,g,b;
76     switch (ct) {
77         case kBGRA_8888_SkColorType:
78             b = static_cast<U8CPU>(c[0]);
79             g = static_cast<U8CPU>(c[1]);
80             r = static_cast<U8CPU>(c[2]);
81             a = static_cast<U8CPU>(c[3]);
82             break;
83         case kRGB_888x_SkColorType:  // fallthrough
84         case kRGBA_8888_SkColorType:
85             r = static_cast<U8CPU>(c[0]);
86             g = static_cast<U8CPU>(c[1]);
87             b = static_cast<U8CPU>(c[2]);
88             // We set this even when for kRGB_888x because our caller will validate that it is 0xff.
89             a = static_cast<U8CPU>(c[3]);
90             break;
91         default:
92             SkDEBUGFAIL("Unexpected colortype");
93             return 0;
94     }
95 
96     if (*doUnpremul) {
97         r = SkMulDiv255Ceiling(r, a);
98         g = SkMulDiv255Ceiling(g, a);
99         b = SkMulDiv255Ceiling(b, a);
100     }
101     return SkPackARGB32(a, r, g, b);
102 }
103 
make_src_bitmap()104 static SkBitmap make_src_bitmap() {
105     static SkBitmap bmp;
106     if (bmp.isNull()) {
107         bmp.allocN32Pixels(DEV_W, DEV_H);
108         intptr_t pixels = reinterpret_cast<intptr_t>(bmp.getPixels());
109         for (int y = 0; y < DEV_H; ++y) {
110             for (int x = 0; x < DEV_W; ++x) {
111                 SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bmp.rowBytes() + x * bmp.bytesPerPixel());
112                 *pixel = get_src_color(x, y);
113             }
114         }
115     }
116     return bmp;
117 }
118 
fill_src_canvas(SkCanvas * canvas)119 static void fill_src_canvas(SkCanvas* canvas) {
120     canvas->save();
121     canvas->setMatrix(SkMatrix::I());
122     canvas->clipRect(DEV_RECT_S, kReplace_SkClipOp);
123     SkPaint paint;
124     paint.setBlendMode(SkBlendMode::kSrc);
125     canvas->drawBitmap(make_src_bitmap(), 0, 0, &paint);
126     canvas->restore();
127 }
128 
fill_dst_bmp_with_init_data(SkBitmap * bitmap)129 static void fill_dst_bmp_with_init_data(SkBitmap* bitmap) {
130     int w = bitmap->width();
131     int h = bitmap->height();
132     intptr_t pixels = reinterpret_cast<intptr_t>(bitmap->getPixels());
133     for (int y = 0; y < h; ++y) {
134         for (int x = 0; x < w; ++x) {
135             SkPMColor initColor = get_dst_bmp_init_color(x, y, w);
136             if (kAlpha_8_SkColorType == bitmap->colorType()) {
137                 uint8_t* alpha = reinterpret_cast<uint8_t*>(pixels + y * bitmap->rowBytes() + x);
138                 *alpha = SkGetPackedA32(initColor);
139             } else {
140                 SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bitmap->rowBytes() + x * bitmap->bytesPerPixel());
141                 *pixel = initColor;
142             }
143         }
144     }
145 }
146 
check_read_pixel(SkPMColor a,SkPMColor b,bool didPremulConversion)147 static bool check_read_pixel(SkPMColor a, SkPMColor b, bool didPremulConversion) {
148     if (!didPremulConversion) {
149         return a == b;
150     }
151     int32_t aA = static_cast<int32_t>(SkGetPackedA32(a));
152     int32_t aR = static_cast<int32_t>(SkGetPackedR32(a));
153     int32_t aG = static_cast<int32_t>(SkGetPackedG32(a));
154     int32_t aB = SkGetPackedB32(a);
155 
156     int32_t bA = static_cast<int32_t>(SkGetPackedA32(b));
157     int32_t bR = static_cast<int32_t>(SkGetPackedR32(b));
158     int32_t bG = static_cast<int32_t>(SkGetPackedG32(b));
159     int32_t bB = static_cast<int32_t>(SkGetPackedB32(b));
160 
161     return aA == bA &&
162            SkAbs32(aR - bR) <= 1 &&
163            SkAbs32(aG - bG) <= 1 &&
164            SkAbs32(aB - bB) <= 1;
165 }
166 
167 // checks the bitmap contains correct pixels after the readPixels
168 // if the bitmap was prefilled with pixels it checks that these weren't
169 // overwritten in the area outside the readPixels.
check_read(skiatest::Reporter * reporter,const SkBitmap & bitmap,int x,int y,bool checkSurfacePixels,bool checkBitmapPixels,SkImageInfo surfaceInfo)170 static bool check_read(skiatest::Reporter* reporter, const SkBitmap& bitmap, int x, int y,
171                        bool checkSurfacePixels, bool checkBitmapPixels,
172                        SkImageInfo surfaceInfo) {
173     SkAlphaType bmpAT = bitmap.alphaType();
174     SkColorType bmpCT = bitmap.colorType();
175     SkASSERT(!bitmap.isNull());
176     SkASSERT(checkSurfacePixels || checkBitmapPixels);
177 
178     int bw = bitmap.width();
179     int bh = bitmap.height();
180 
181     SkIRect srcRect = SkIRect::MakeXYWH(x, y, bw, bh);
182     SkIRect clippedSrcRect = DEV_RECT;
183     if (!clippedSrcRect.intersect(srcRect)) {
184         clippedSrcRect.setEmpty();
185     }
186     if (kAlpha_8_SkColorType == bmpCT) {
187         for (int by = 0; by < bh; ++by) {
188             for (int bx = 0; bx < bw; ++bx) {
189                 int devx = bx + srcRect.fLeft;
190                 int devy = by + srcRect.fTop;
191                 const uint8_t* alpha = bitmap.getAddr8(bx, by);
192 
193                 if (clippedSrcRect.contains(devx, devy)) {
194                     if (checkSurfacePixels) {
195                         uint8_t surfaceAlpha = (surfaceInfo.alphaType() == kOpaque_SkAlphaType)
196                                                        ? 0xFF
197                                                        : SkGetPackedA32(get_src_color(devx, devy));
198                         if (surfaceAlpha != *alpha) {
199                             ERRORF(reporter,
200                                    "Expected readback alpha (%d, %d) value 0x%02x, got 0x%02x. ",
201                                    bx, by, surfaceAlpha, *alpha);
202                             return false;
203                         }
204                     }
205                 } else if (checkBitmapPixels) {
206                     uint32_t origDstAlpha = SkGetPackedA32(get_dst_bmp_init_color(bx, by, bw));
207                     if (origDstAlpha != *alpha) {
208                         ERRORF(reporter, "Expected clipped out area of readback to be unchanged. "
209                             "Expected 0x%02x, got 0x%02x", origDstAlpha, *alpha);
210                         return false;
211                     }
212                 }
213             }
214         }
215         return true;
216     }
217     for (int by = 0; by < bh; ++by) {
218         for (int bx = 0; bx < bw; ++bx) {
219             int devx = bx + srcRect.fLeft;
220             int devy = by + srcRect.fTop;
221 
222             const uint32_t* pixel = bitmap.getAddr32(bx, by);
223 
224             if (clippedSrcRect.contains(devx, devy)) {
225                 if (checkSurfacePixels) {
226                     SkPMColor surfacePMColor = get_src_color(devx, devy);
227                     if (SkColorTypeIsAlphaOnly(surfaceInfo.colorType())) {
228                         surfacePMColor &= 0xFF000000;
229                     }
230                     if (kOpaque_SkAlphaType == surfaceInfo.alphaType() || kOpaque_SkAlphaType == bmpAT) {
231                         surfacePMColor |= 0xFF000000;
232                     }
233                     bool didPremul;
234                     SkPMColor pmPixel = convert_to_pmcolor(bmpCT, bmpAT, pixel, &didPremul);
235                     if (!check_read_pixel(pmPixel, surfacePMColor, didPremul)) {
236                         ERRORF(reporter,
237                                "Expected readback pixel (%d, %d) value 0x%08x, got 0x%08x. "
238                                "Readback was unpremul: %d",
239                                bx, by, surfacePMColor, pmPixel, didPremul);
240                         return false;
241                     }
242                 }
243             } else if (checkBitmapPixels) {
244                 uint32_t origDstPixel = get_dst_bmp_init_color(bx, by, bw);
245                 if (origDstPixel != *pixel) {
246                     ERRORF(reporter, "Expected clipped out area of readback to be unchanged. "
247                            "Expected 0x%08x, got 0x%08x", origDstPixel, *pixel);
248                     return false;
249                 }
250             }
251         }
252     }
253     return true;
254 }
255 
256 enum BitmapInit {
257     kFirstBitmapInit = 0,
258 
259     kTight_BitmapInit = kFirstBitmapInit,
260     kRowBytes_BitmapInit,
261     kRowBytesOdd_BitmapInit,
262 
263     kLastAligned_BitmapInit = kRowBytes_BitmapInit,
264 
265 #if 0  // THIS CAUSES ERRORS ON WINDOWS AND SOME ANDROID DEVICES
266     kLast_BitmapInit = kRowBytesOdd_BitmapInit
267 #else
268     kLast_BitmapInit = kLastAligned_BitmapInit
269 #endif
270 };
271 
nextBMI(BitmapInit bmi)272 static BitmapInit nextBMI(BitmapInit bmi) {
273     int x = bmi;
274     return static_cast<BitmapInit>(++x);
275 }
276 
init_bitmap(SkBitmap * bitmap,const SkIRect & rect,BitmapInit init,SkColorType ct,SkAlphaType at)277 static void init_bitmap(SkBitmap* bitmap, const SkIRect& rect, BitmapInit init, SkColorType ct,
278                         SkAlphaType at) {
279     SkImageInfo info = SkImageInfo::Make(rect.width(), rect.height(), ct, at);
280     size_t rowBytes = 0;
281     switch (init) {
282         case kTight_BitmapInit:
283             break;
284         case kRowBytes_BitmapInit:
285             rowBytes = SkAlign4((info.width() + 16) * info.bytesPerPixel());
286             break;
287         case kRowBytesOdd_BitmapInit:
288             rowBytes = SkAlign4(info.width() * info.bytesPerPixel()) + 3;
289             break;
290         default:
291             SkASSERT(0);
292             break;
293     }
294     bitmap->allocPixels(info, rowBytes);
295 }
296 
297 static const struct {
298     SkColorType fColorType;
299     SkAlphaType fAlphaType;
300 } gReadPixelsConfigs[] = {
301         {kRGBA_8888_SkColorType, kPremul_SkAlphaType},
302         {kRGBA_8888_SkColorType, kUnpremul_SkAlphaType},
303         {kRGB_888x_SkColorType, kOpaque_SkAlphaType},
304         {kBGRA_8888_SkColorType, kPremul_SkAlphaType},
305         {kBGRA_8888_SkColorType, kUnpremul_SkAlphaType},
306         {kAlpha_8_SkColorType, kPremul_SkAlphaType},
307 };
308 const SkIRect gReadPixelsTestRects[] = {
309     // entire thing
310     DEV_RECT,
311     // larger on all sides
312     SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H + 10),
313     // fully contained
314     SkIRect::MakeLTRB(DEV_W / 4, DEV_H / 4, 3 * DEV_W / 4, 3 * DEV_H / 4),
315     // outside top left
316     SkIRect::MakeLTRB(-10, -10, -1, -1),
317     // touching top left corner
318     SkIRect::MakeLTRB(-10, -10, 0, 0),
319     // overlapping top left corner
320     SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H / 4),
321     // overlapping top left and top right corners
322     SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, DEV_H / 4),
323     // touching entire top edge
324     SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, 0),
325     // overlapping top right corner
326     SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W  + 10, DEV_H / 4),
327     // contained in x, overlapping top edge
328     SkIRect::MakeLTRB(DEV_W / 4, -10, 3 * DEV_W  / 4, DEV_H / 4),
329     // outside top right corner
330     SkIRect::MakeLTRB(DEV_W + 1, -10, DEV_W + 10, -1),
331     // touching top right corner
332     SkIRect::MakeLTRB(DEV_W, -10, DEV_W + 10, 0),
333     // overlapping top left and bottom left corners
334     SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H + 10),
335     // touching entire left edge
336     SkIRect::MakeLTRB(-10, -10, 0, DEV_H + 10),
337     // overlapping bottom left corner
338     SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W / 4, DEV_H + 10),
339     // contained in y, overlapping left edge
340     SkIRect::MakeLTRB(-10, DEV_H / 4, DEV_W / 4, 3 * DEV_H / 4),
341     // outside bottom left corner
342     SkIRect::MakeLTRB(-10, DEV_H + 1, -1, DEV_H + 10),
343     // touching bottom left corner
344     SkIRect::MakeLTRB(-10, DEV_H, 0, DEV_H + 10),
345     // overlapping bottom left and bottom right corners
346     SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
347     // touching entire left edge
348     SkIRect::MakeLTRB(0, DEV_H, DEV_W, DEV_H + 10),
349     // overlapping bottom right corner
350     SkIRect::MakeLTRB(3 * DEV_W / 4, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
351     // overlapping top right and bottom right corners
352     SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H + 10),
353 };
354 
read_should_succeed(const SkIRect & srcRect,const SkImageInfo & dstInfo,const SkImageInfo & srcInfo)355 bool read_should_succeed(const SkIRect& srcRect, const SkImageInfo& dstInfo,
356                          const SkImageInfo& srcInfo) {
357     return SkIRect::Intersects(srcRect, DEV_RECT) && SkImageInfoValidConversion(dstInfo, srcInfo);
358 }
359 
test_readpixels(skiatest::Reporter * reporter,const sk_sp<SkSurface> & surface,const SkImageInfo & surfaceInfo,BitmapInit lastBitmapInit)360 static void test_readpixels(skiatest::Reporter* reporter, const sk_sp<SkSurface>& surface,
361                             const SkImageInfo& surfaceInfo, BitmapInit lastBitmapInit) {
362     SkCanvas* canvas = surface->getCanvas();
363     fill_src_canvas(canvas);
364     for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
365         const SkIRect& srcRect = gReadPixelsTestRects[rect];
366         for (BitmapInit bmi = kFirstBitmapInit; bmi <= lastBitmapInit; bmi = nextBMI(bmi)) {
367             for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
368                 SkBitmap bmp;
369                 init_bitmap(&bmp, srcRect, bmi,
370                             gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
371 
372                 // if the bitmap has pixels allocated before the readPixels,
373                 // note that and fill them with pattern
374                 bool startsWithPixels = !bmp.isNull();
375                 if (startsWithPixels) {
376                     fill_dst_bmp_with_init_data(&bmp);
377                 }
378                 uint32_t idBefore = surface->generationID();
379                 bool success = surface->readPixels(bmp, srcRect.fLeft, srcRect.fTop);
380                 uint32_t idAfter = surface->generationID();
381 
382                 // we expect to succeed when the read isn't fully clipped out and the infos are
383                 // compatible.
384                 bool expectSuccess = read_should_succeed(srcRect, bmp.info(), surfaceInfo);
385                 // determine whether we expected the read to succeed.
386                 REPORTER_ASSERT(reporter, expectSuccess == success,
387                                 "Read succeed=%d unexpectedly, src ct/at: %d/%d, dst ct/at: %d/%d",
388                                 success, surfaceInfo.colorType(), surfaceInfo.alphaType(),
389                                 bmp.info().colorType(), bmp.info().alphaType());
390                 // read pixels should never change the gen id
391                 REPORTER_ASSERT(reporter, idBefore == idAfter);
392 
393                 if (success || startsWithPixels) {
394                     check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop, success,
395                                startsWithPixels, surfaceInfo);
396                 } else {
397                     // if we had no pixels beforehand and the readPixels
398                     // failed then our bitmap should still not have pixels
399                     REPORTER_ASSERT(reporter, bmp.isNull());
400                 }
401             }
402         }
403     }
404 }
405 
DEF_TEST(ReadPixels,reporter)406 DEF_TEST(ReadPixels, reporter) {
407     const SkImageInfo info = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
408     auto surface(SkSurface::MakeRaster(info));
409     // SW readback fails a premul check when reading back to an unaligned rowbytes.
410     test_readpixels(reporter, surface, info, kLastAligned_BitmapInit);
411 }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Gpu,reporter,ctxInfo)412 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Gpu, reporter, ctxInfo) {
413     static const SkImageInfo kImageInfos[] = {
414             SkImageInfo::Make(DEV_W, DEV_H, kRGBA_8888_SkColorType, kPremul_SkAlphaType),
415             SkImageInfo::Make(DEV_W, DEV_H, kBGRA_8888_SkColorType, kPremul_SkAlphaType),
416             SkImageInfo::Make(DEV_W, DEV_H, kRGB_888x_SkColorType, kOpaque_SkAlphaType),
417             SkImageInfo::Make(DEV_W, DEV_H, kAlpha_8_SkColorType, kPremul_SkAlphaType),
418     };
419     for (const auto& ii : kImageInfos) {
420         for (auto& origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
421             sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(
422                     ctxInfo.grContext(), SkBudgeted::kNo, ii, 0, origin, nullptr));
423             if (!surface) {
424                 continue;
425             }
426             test_readpixels(reporter, surface, ii, kLast_BitmapInit);
427         }
428     }
429 }
430 
test_readpixels_texture(skiatest::Reporter * reporter,sk_sp<GrSurfaceContext> sContext,const SkImageInfo & surfaceInfo)431 static void test_readpixels_texture(skiatest::Reporter* reporter,
432                                     sk_sp<GrSurfaceContext> sContext,
433                                     const SkImageInfo& surfaceInfo) {
434     for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
435         const SkIRect& srcRect = gReadPixelsTestRects[rect];
436         for (BitmapInit bmi = kFirstBitmapInit; bmi <= kLast_BitmapInit; bmi = nextBMI(bmi)) {
437             for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
438                 SkBitmap bmp;
439                 init_bitmap(&bmp, srcRect, bmi,
440                             gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
441 
442                 // if the bitmap has pixels allocated before the readPixels,
443                 // note that and fill them with pattern
444                 bool startsWithPixels = !bmp.isNull();
445                 // Try doing the read directly from a non-renderable texture
446                 if (startsWithPixels) {
447                     fill_dst_bmp_with_init_data(&bmp);
448                     bool success = sContext->readPixels(bmp.info(), bmp.getPixels(),
449                             bmp.rowBytes(), {srcRect.fLeft, srcRect.fTop});
450                     auto expectSuccess = read_should_succeed(srcRect, bmp.info(), surfaceInfo);
451                     REPORTER_ASSERT(
452                             reporter, expectSuccess == success,
453                             "Read succeed=%d unexpectedly, src ct/at: %d/%d, dst ct/at: %d/%d",
454                             success, surfaceInfo.colorType(), surfaceInfo.alphaType(),
455                             bmp.info().colorType(), bmp.info().alphaType());
456                     if (success) {
457                         check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop, success, true,
458                                    surfaceInfo);
459                     }
460                 }
461             }
462         }
463     }
464 }
465 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Texture,reporter,ctxInfo)466 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Texture, reporter, ctxInfo) {
467     GrContext* context = ctxInfo.grContext();
468     SkBitmap bmp = make_src_bitmap();
469 
470     // On the GPU we will also try reading back from a non-renderable texture.
471     for (auto origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
472         for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
473             sk_sp<GrTextureProxy> proxy = sk_gpu_test::MakeTextureProxyFromData(
474                     context, renderable, DEV_W, DEV_H, bmp.colorType(), bmp.alphaType(), origin,
475                     bmp.getPixels(), bmp.rowBytes());
476             sk_sp<GrSurfaceContext> sContext = context->priv().makeWrappedSurfaceContext(
477                     std::move(proxy), SkColorTypeToGrColorType(bmp.colorType()),
478                     kPremul_SkAlphaType);
479             auto info = SkImageInfo::Make(DEV_W, DEV_H, kN32_SkColorType, kPremul_SkAlphaType);
480             test_readpixels_texture(reporter, std::move(sContext), info);
481         }
482     }
483 }
484 
485 ///////////////////////////////////////////////////////////////////////////////////////////////////
486 
487 static const uint32_t kNumPixels = 5;
488 
489 // The five reference pixels are: red, green, blue, white, black.
490 // Five is an interesting number to test because we'll exercise a full 4-wide SIMD vector
491 // plus a tail pixel.
492 static const uint32_t rgba[kNumPixels] = {
493         0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF, 0xFF000000
494 };
495 static const uint32_t bgra[kNumPixels] = {
496         0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFFFFFF, 0xFF000000
497 };
498 static const uint16_t rgb565[kNumPixels] = {
499         SK_R16_MASK_IN_PLACE, SK_G16_MASK_IN_PLACE, SK_B16_MASK_IN_PLACE, 0xFFFF, 0x0
500 };
501 
502 static const uint16_t rgba4444[kNumPixels] = { 0xF00F, 0x0F0F, 0x00FF, 0xFFFF, 0x000F };
503 
504 static const uint64_t kRed      = (uint64_t) SK_Half1 <<  0;
505 static const uint64_t kGreen    = (uint64_t) SK_Half1 << 16;
506 static const uint64_t kBlue     = (uint64_t) SK_Half1 << 32;
507 static const uint64_t kAlpha    = (uint64_t) SK_Half1 << 48;
508 static const uint64_t f16[kNumPixels] = {
509         kAlpha | kRed, kAlpha | kGreen, kAlpha | kBlue, kAlpha | kBlue | kGreen | kRed, kAlpha
510 };
511 
512 static const uint8_t alpha8[kNumPixels] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
513 static const uint8_t gray8[kNumPixels] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
514 
five_reference_pixels(SkColorType colorType)515 static const void* five_reference_pixels(SkColorType colorType) {
516     switch (colorType) {
517         case kUnknown_SkColorType:
518             return nullptr;
519         case kAlpha_8_SkColorType:
520             return alpha8;
521         case kRGB_565_SkColorType:
522             return rgb565;
523         case kARGB_4444_SkColorType:
524             return rgba4444;
525         case kRGBA_8888_SkColorType:
526             return rgba;
527         case kBGRA_8888_SkColorType:
528             return bgra;
529         case kGray_8_SkColorType:
530             return gray8;
531         case kRGBA_F16_SkColorType:
532             return f16;
533         default:
534             return nullptr;
535     }
536 
537     SkASSERT(false);
538     return nullptr;
539 }
540 
test_conversion(skiatest::Reporter * r,const SkImageInfo & dstInfo,const SkImageInfo & srcInfo)541 static void test_conversion(skiatest::Reporter* r, const SkImageInfo& dstInfo,
542                             const SkImageInfo& srcInfo) {
543     if (!SkImageInfoIsValid(srcInfo)) {
544         return;
545     }
546 
547     const void* srcPixels = five_reference_pixels(srcInfo.colorType());
548     SkPixmap srcPixmap(srcInfo, srcPixels, srcInfo.minRowBytes());
549     sk_sp<SkImage> src = SkImage::MakeFromRaster(srcPixmap, nullptr, nullptr);
550     REPORTER_ASSERT(r, src);
551 
552     // Enough space for 5 pixels when color type is F16, more than enough space in other cases.
553     uint64_t dstPixels[kNumPixels];
554     SkPixmap dstPixmap(dstInfo, dstPixels, dstInfo.minRowBytes());
555     bool success = src->readPixels(dstPixmap, 0, 0);
556     REPORTER_ASSERT(r, success == SkImageInfoValidConversion(dstInfo, srcInfo));
557 
558     if (success) {
559         if (kGray_8_SkColorType == srcInfo.colorType() &&
560             kGray_8_SkColorType != dstInfo.colorType()) {
561             // TODO: test (r,g,b) == (gray,gray,gray)?
562             return;
563         }
564 
565         if (kGray_8_SkColorType == dstInfo.colorType() &&
566             kGray_8_SkColorType != srcInfo.colorType()) {
567             // TODO: test gray = luminance?
568             return;
569         }
570 
571         if (kAlpha_8_SkColorType == srcInfo.colorType() &&
572             kAlpha_8_SkColorType != dstInfo.colorType()) {
573             // TODO: test output = black with this alpha?
574             return;
575         }
576 
577         REPORTER_ASSERT(r, 0 == memcmp(dstPixels, five_reference_pixels(dstInfo.colorType()),
578                                        kNumPixels * SkColorTypeBytesPerPixel(dstInfo.colorType())));
579     }
580 }
581 
DEF_TEST(ReadPixels_ValidConversion,reporter)582 DEF_TEST(ReadPixels_ValidConversion, reporter) {
583     const SkColorType kColorTypes[] = {
584             kUnknown_SkColorType,
585             kAlpha_8_SkColorType,
586             kRGB_565_SkColorType,
587             kARGB_4444_SkColorType,
588             kRGBA_8888_SkColorType,
589             kBGRA_8888_SkColorType,
590             kGray_8_SkColorType,
591             kRGBA_F16_SkColorType,
592     };
593 
594     const SkAlphaType kAlphaTypes[] = {
595             kUnknown_SkAlphaType,
596             kOpaque_SkAlphaType,
597             kPremul_SkAlphaType,
598             kUnpremul_SkAlphaType,
599     };
600 
601     const sk_sp<SkColorSpace> kColorSpaces[] = {
602             nullptr,
603             SkColorSpace::MakeSRGB(),
604     };
605 
606     for (SkColorType dstCT : kColorTypes) {
607         for (SkAlphaType dstAT: kAlphaTypes) {
608             for (sk_sp<SkColorSpace> dstCS : kColorSpaces) {
609                 for (SkColorType srcCT : kColorTypes) {
610                     for (SkAlphaType srcAT: kAlphaTypes) {
611                         for (sk_sp<SkColorSpace> srcCS : kColorSpaces) {
612                             test_conversion(reporter,
613                                             SkImageInfo::Make(kNumPixels, 1, dstCT, dstAT, dstCS),
614                                             SkImageInfo::Make(kNumPixels, 1, srcCT, srcAT, srcCS));
615                         }
616                     }
617                 }
618             }
619         }
620     }
621 }
622 
min_rgb_channel_bits(SkColorType ct)623 static int min_rgb_channel_bits(SkColorType ct) {
624     switch (ct) {
625         case kUnknown_SkColorType:      return 0;
626         case kAlpha_8_SkColorType:      return 8;
627         case kRGB_565_SkColorType:      return 5;
628         case kARGB_4444_SkColorType:    return 4;
629         case kRGBA_8888_SkColorType:    return 8;
630         case kRGB_888x_SkColorType:     return 8;
631         case kBGRA_8888_SkColorType:    return 8;
632         case kRGBA_1010102_SkColorType: return 10;
633         case kRGB_101010x_SkColorType:  return 10;
634         case kGray_8_SkColorType:       return 8;   // counting gray as "rgb"
635         case kRGBA_F16Norm_SkColorType: return 10;  // just counting the mantissa
636         case kRGBA_F16_SkColorType:     return 10;  // just counting the mantissa
637         case kRGBA_F32_SkColorType:     return 23;  // just counting the mantissa
638     }
639     SK_ABORT("Unexpected color type.");
640 }
641 
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(AsyncReadPixels,reporter,ctxInfo)642 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(AsyncReadPixels, reporter, ctxInfo) {
643     struct Context {
644         SkPixmap* fPixmap = nullptr;
645         bool fSuceeded = false;
646         bool fCalled = false;
647     };
648     auto callback = [](SkSurface::ReleaseContext context, const void* data, size_t rowBytes) {
649         auto* pm = static_cast<Context*>(context)->fPixmap;
650         static_cast<Context*>(context)->fCalled = true;
651         if ((static_cast<Context*>(context)->fSuceeded = SkToBool(data))) {
652             auto dst = static_cast<char*>(pm->writable_addr());
653             const auto* src = static_cast<const char*>(data);
654             for (int y = 0; y < pm->height(); ++y, src += rowBytes, dst += pm->rowBytes()) {
655                 memcpy(dst, src, pm->width() * SkColorTypeBytesPerPixel(pm->colorType()));
656             }
657         }
658     };
659     for (auto origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
660         static constexpr int kW = 16;
661         static constexpr int kH = 16;
662         for (int sct = 0; sct <= kLastEnum_SkColorType; ++sct) {
663             auto surfCT = static_cast<SkColorType>(sct);
664             auto info = SkImageInfo::Make(kW, kH, surfCT, kPremul_SkAlphaType, nullptr);
665             auto surf = SkSurface::MakeRenderTarget(ctxInfo.grContext(), SkBudgeted::kNo, info, 1,
666                                                     origin, nullptr);
667             if (!surf) {
668                 continue;
669             }
670             float d = std::sqrt((float)surf->width() * surf->width() +
671                                 (float)surf->height() * surf->height());
672             for (int j = 0; j < surf->height(); ++j) {
673                 for (int i = 0; i < surf->width(); ++i) {
674                     float r = i / (float)surf->width();
675                     float g = 1.f - i / (float)surf->height();
676                     float b = std::sqrt((float)i * i + (float)j * j) / d;
677                     SkPaint paint;
678                     paint.setColor4f(SkColor4f{r, g, b, 1.f}, nullptr);
679                     surf->getCanvas()->drawRect(SkRect::MakeXYWH(i, j, 1, 1), paint);
680                 }
681             }
682             for (const auto& rect : {SkIRect::MakeWH(kW, kH),                  // full size
683                                      SkIRect::MakeLTRB(1, 2, kW - 3, kH - 4),  // partial
684                                      SkIRect::MakeXYWH(1, 1, 0, 0),            // empty: fail
685                                      SkIRect::MakeWH(kW + 1, kH / 2)}) {       // too wide: fail
686                 for (int rct = 0; rct <= kLastEnum_SkColorType; ++rct) {
687                     auto readCT = static_cast<SkColorType>(rct);
688                     for (const sk_sp<SkColorSpace>& readCS :
689                          {sk_sp<SkColorSpace>(), SkColorSpace::MakeSRGBLinear()}) {
690                         SkAutoPixmapStorage result;
691                         Context context;
692                         context.fPixmap = &result;
693                         info = SkImageInfo::Make(rect.width(), rect.height(), readCT,
694                                                  kPremul_SkAlphaType, readCS);
695                         result.alloc(info);
696                         memset(result.writable_addr(), 0xAB, result.computeByteSize());
697                         // Rescale quality and linearity don't matter since we're doing a non-
698                         // scaling readback.
699                         surf->asyncRescaleAndReadPixels(info, rect, SkSurface::RescaleGamma::kSrc,
700                                                         kNone_SkFilterQuality, callback, &context);
701                         while (!context.fCalled) {
702                             ctxInfo.grContext()->checkAsyncWorkCompletion();
703                         }
704                         if (rect.isEmpty() || !SkIRect::MakeWH(kW, kH).contains(rect)) {
705                             REPORTER_ASSERT(reporter, !context.fSuceeded);
706                         }
707                         if (context.fSuceeded) {
708                             REPORTER_ASSERT(reporter, readCT != kUnknown_SkColorType &&
709                                                       !rect.isEmpty());
710                         } else {
711                             // TODO: Support reading to kGray.
712                             auto surfBounds = SkIRect::MakeWH(surf->width(), surf->height());
713                             if (readCT != kUnknown_SkColorType && readCT != kGray_8_SkColorType &&
714                                 !rect.isEmpty() && surfBounds.contains(rect)) {
715                                 ERRORF(reporter,
716                                        "Async read failed. Surf Color Type: %d, Read CT: %d,"
717                                        "Rect [%d, %d, %d, %d], origin: %d, CS conversion: %d\n",
718                                        surfCT, readCT, rect.fLeft, rect.fTop, rect.fRight,
719                                        rect.fBottom, origin, (bool)readCS);
720                             }
721                             continue;
722                         }
723                         // We use a synchronous read as the source of truth.
724                         SkAutoPixmapStorage ref;
725                         ref.alloc(info);
726                         memset(ref.writable_addr(), 0xCD, ref.computeByteSize());
727                         if (!surf->readPixels(ref, rect.fLeft, rect.fTop)) {
728                             continue;
729                         }
730                         // When there is no conversion, don't allow a difference.
731                         float tol = 0.f;
732                         if (readCS || readCT != surfCT) {
733                             // When there is a conversion allow a diff of two values when no
734                             // color space conversion and three otherwise. Except for alpha where
735                             // we allow no difference. Allow intermediate truncation to an 8 bit per
736                             // channel format.
737                             int rgbBits = std::min({min_rgb_channel_bits(readCT),
738                                                     min_rgb_channel_bits(surfCT), 8});
739 
740                             tol = (readCS ? 3.f : 2.f) / (1 << rgbBits);
741                         }
742                         const float tols[4] = {tol, tol, tol, 0};
743                         auto error = std::function<ComparePixmapsErrorReporter>(
744                                 [&](int x, int y, const float diffs[4]) {
745                                     SkASSERT(x >= 0 && y >= 0);
746                                     ERRORF(reporter,
747                                            "Surf Color Type: %d, Read CT: %d, Rect [%d, %d, %d, %d]"
748                                            ", origin: %d, CS conversion: %d\n"
749                                            "Error at %d, %d. Diff in floats: (%f, %f, %f %f)",
750                                            surfCT, readCT, rect.fLeft, rect.fTop, rect.fRight,
751                                            rect.fBottom, origin, (bool)readCS, x, y, diffs[0],
752                                            diffs[1], diffs[2], diffs[3]);
753                                 });
754                         compare_pixels(ref, result, tols, error);
755                     }
756                 }
757             }
758         }
759     }
760 }
761