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 "SkCanvas.h"
9#include "SkColorData.h"
10#include "SkHalf.h"
11#include "SkImageInfoPriv.h"
12#include "SkMathPriv.h"
13#include "SkSurface.h"
14#include "Test.h"
15
16#if SK_SUPPORT_GPU
17#include "GrContext.h"
18#include "GrContextFactory.h"
19#include "GrContextPriv.h"
20#include "GrProxyProvider.h"
21#include "SkGr.h"
22#endif
23
24#include <initializer_list>
25
26static const int DEV_W = 100, DEV_H = 100;
27static const SkIRect DEV_RECT = SkIRect::MakeWH(DEV_W, DEV_H);
28static const SkRect DEV_RECT_S = SkRect::MakeWH(DEV_W * SK_Scalar1,
29                                                DEV_H * SK_Scalar1);
30
31static 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
60static 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
69static SkPMColor convert_to_pmcolor(SkColorType ct, SkAlphaType at, const uint32_t* addr,
70                                    bool* doUnpremul) {
71    *doUnpremul = (kUnpremul_SkAlphaType == at);
72
73    const uint8_t* c = reinterpret_cast<const uint8_t*>(addr);
74    U8CPU a,r,g,b;
75    switch (ct) {
76        case kBGRA_8888_SkColorType:
77            b = static_cast<U8CPU>(c[0]);
78            g = static_cast<U8CPU>(c[1]);
79            r = static_cast<U8CPU>(c[2]);
80            a = static_cast<U8CPU>(c[3]);
81            break;
82        case kRGBA_8888_SkColorType:
83            r = static_cast<U8CPU>(c[0]);
84            g = static_cast<U8CPU>(c[1]);
85            b = static_cast<U8CPU>(c[2]);
86            a = static_cast<U8CPU>(c[3]);
87            break;
88        default:
89            SkDEBUGFAIL("Unexpected colortype");
90            return 0;
91    }
92
93    if (*doUnpremul) {
94        r = SkMulDiv255Ceiling(r, a);
95        g = SkMulDiv255Ceiling(g, a);
96        b = SkMulDiv255Ceiling(b, a);
97    }
98    return SkPackARGB32(a, r, g, b);
99}
100
101static SkBitmap make_src_bitmap() {
102    static SkBitmap bmp;
103    if (bmp.isNull()) {
104        bmp.allocN32Pixels(DEV_W, DEV_H);
105        intptr_t pixels = reinterpret_cast<intptr_t>(bmp.getPixels());
106        for (int y = 0; y < DEV_H; ++y) {
107            for (int x = 0; x < DEV_W; ++x) {
108                SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bmp.rowBytes() + x * bmp.bytesPerPixel());
109                *pixel = get_src_color(x, y);
110            }
111        }
112    }
113    return bmp;
114}
115
116static void fill_src_canvas(SkCanvas* canvas) {
117    canvas->save();
118    canvas->setMatrix(SkMatrix::I());
119    canvas->clipRect(DEV_RECT_S, kReplace_SkClipOp);
120    SkPaint paint;
121    paint.setBlendMode(SkBlendMode::kSrc);
122    canvas->drawBitmap(make_src_bitmap(), 0, 0, &paint);
123    canvas->restore();
124}
125
126static void fill_dst_bmp_with_init_data(SkBitmap* bitmap) {
127    int w = bitmap->width();
128    int h = bitmap->height();
129    intptr_t pixels = reinterpret_cast<intptr_t>(bitmap->getPixels());
130    for (int y = 0; y < h; ++y) {
131        for (int x = 0; x < w; ++x) {
132            SkPMColor initColor = get_dst_bmp_init_color(x, y, w);
133            if (kAlpha_8_SkColorType == bitmap->colorType()) {
134                uint8_t* alpha = reinterpret_cast<uint8_t*>(pixels + y * bitmap->rowBytes() + x);
135                *alpha = SkGetPackedA32(initColor);
136            } else {
137                SkPMColor* pixel = reinterpret_cast<SkPMColor*>(pixels + y * bitmap->rowBytes() + x * bitmap->bytesPerPixel());
138                *pixel = initColor;
139            }
140        }
141    }
142}
143
144static bool check_read_pixel(SkPMColor a, SkPMColor b, bool didPremulConversion) {
145    if (!didPremulConversion) {
146        return a == b;
147    }
148    int32_t aA = static_cast<int32_t>(SkGetPackedA32(a));
149    int32_t aR = static_cast<int32_t>(SkGetPackedR32(a));
150    int32_t aG = static_cast<int32_t>(SkGetPackedG32(a));
151    int32_t aB = SkGetPackedB32(a);
152
153    int32_t bA = static_cast<int32_t>(SkGetPackedA32(b));
154    int32_t bR = static_cast<int32_t>(SkGetPackedR32(b));
155    int32_t bG = static_cast<int32_t>(SkGetPackedG32(b));
156    int32_t bB = static_cast<int32_t>(SkGetPackedB32(b));
157
158    return aA == bA &&
159           SkAbs32(aR - bR) <= 1 &&
160           SkAbs32(aG - bG) <= 1 &&
161           SkAbs32(aB - bB) <= 1;
162}
163
164// checks the bitmap contains correct pixels after the readPixels
165// if the bitmap was prefilled with pixels it checks that these weren't
166// overwritten in the area outside the readPixels.
167static bool check_read(skiatest::Reporter* reporter,
168                       const SkBitmap& bitmap,
169                       int x, int y,
170                       bool checkCanvasPixels,
171                       bool checkBitmapPixels,
172                       SkColorType ct,
173                       SkAlphaType at) {
174    SkASSERT(ct == bitmap.colorType() && at == bitmap.alphaType());
175    SkASSERT(!bitmap.isNull());
176    SkASSERT(checkCanvasPixels || 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 == ct) {
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 (checkCanvasPixels) {
195                        uint8_t canvasAlpha = SkGetPackedA32(get_src_color(devx, devy));
196                        if (canvasAlpha != *alpha) {
197                            ERRORF(reporter, "Expected readback alpha (%d, %d) value 0x%02x, got 0x%02x. ",
198                                   bx, by, canvasAlpha, *alpha);
199                            return false;
200                        }
201                    }
202                } else if (checkBitmapPixels) {
203                    uint32_t origDstAlpha = SkGetPackedA32(get_dst_bmp_init_color(bx, by, bw));
204                    if (origDstAlpha != *alpha) {
205                        ERRORF(reporter, "Expected clipped out area of readback to be unchanged. "
206                            "Expected 0x%02x, got 0x%02x", origDstAlpha, *alpha);
207                        return false;
208                    }
209                }
210            }
211        }
212        return true;
213    }
214    for (int by = 0; by < bh; ++by) {
215        for (int bx = 0; bx < bw; ++bx) {
216            int devx = bx + srcRect.fLeft;
217            int devy = by + srcRect.fTop;
218
219            const uint32_t* pixel = bitmap.getAddr32(bx, by);
220
221            if (clippedSrcRect.contains(devx, devy)) {
222                if (checkCanvasPixels) {
223                    SkPMColor canvasPixel = get_src_color(devx, devy);
224                    bool didPremul;
225                    SkPMColor pmPixel = convert_to_pmcolor(ct, at, pixel, &didPremul);
226                    if (!check_read_pixel(pmPixel, canvasPixel, didPremul)) {
227                        ERRORF(reporter, "Expected readback pixel (%d, %d) value 0x%08x, got 0x%08x. "
228                               "Readback was unpremul: %d", bx, by, canvasPixel, pmPixel, didPremul);
229                        return false;
230                    }
231                }
232            } else if (checkBitmapPixels) {
233                uint32_t origDstPixel = get_dst_bmp_init_color(bx, by, bw);
234                if (origDstPixel != *pixel) {
235                    ERRORF(reporter, "Expected clipped out area of readback to be unchanged. "
236                           "Expected 0x%08x, got 0x%08x", origDstPixel, *pixel);
237                    return false;
238                }
239            }
240        }
241    }
242    return true;
243}
244
245enum BitmapInit {
246    kFirstBitmapInit = 0,
247
248    kTight_BitmapInit = kFirstBitmapInit,
249    kRowBytes_BitmapInit,
250    kRowBytesOdd_BitmapInit,
251
252    kLastAligned_BitmapInit = kRowBytes_BitmapInit,
253
254#if 0  // THIS CAUSES ERRORS ON WINDOWS AND SOME ANDROID DEVICES
255    kLast_BitmapInit = kRowBytesOdd_BitmapInit
256#else
257    kLast_BitmapInit = kLastAligned_BitmapInit
258#endif
259};
260
261static BitmapInit nextBMI(BitmapInit bmi) {
262    int x = bmi;
263    return static_cast<BitmapInit>(++x);
264}
265
266static void init_bitmap(SkBitmap* bitmap, const SkIRect& rect, BitmapInit init, SkColorType ct,
267                        SkAlphaType at) {
268    SkImageInfo info = SkImageInfo::Make(rect.width(), rect.height(), ct, at);
269    size_t rowBytes = 0;
270    switch (init) {
271        case kTight_BitmapInit:
272            break;
273        case kRowBytes_BitmapInit:
274            rowBytes = SkAlign4((info.width() + 16) * info.bytesPerPixel());
275            break;
276        case kRowBytesOdd_BitmapInit:
277            rowBytes = SkAlign4(info.width() * info.bytesPerPixel()) + 3;
278            break;
279        default:
280            SkASSERT(0);
281            break;
282    }
283    bitmap->allocPixels(info, rowBytes);
284}
285
286static const struct {
287    SkColorType fColorType;
288    SkAlphaType fAlphaType;
289} gReadPixelsConfigs[] = {
290    { kRGBA_8888_SkColorType,   kPremul_SkAlphaType },
291    { kRGBA_8888_SkColorType,   kUnpremul_SkAlphaType },
292    { kBGRA_8888_SkColorType,   kPremul_SkAlphaType },
293    { kBGRA_8888_SkColorType,   kUnpremul_SkAlphaType },
294    { kAlpha_8_SkColorType,     kPremul_SkAlphaType },
295};
296const SkIRect gReadPixelsTestRects[] = {
297    // entire thing
298    DEV_RECT,
299    // larger on all sides
300    SkIRect::MakeLTRB(-10, -10, DEV_W + 10, DEV_H + 10),
301    // fully contained
302    SkIRect::MakeLTRB(DEV_W / 4, DEV_H / 4, 3 * DEV_W / 4, 3 * DEV_H / 4),
303    // outside top left
304    SkIRect::MakeLTRB(-10, -10, -1, -1),
305    // touching top left corner
306    SkIRect::MakeLTRB(-10, -10, 0, 0),
307    // overlapping top left corner
308    SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H / 4),
309    // overlapping top left and top right corners
310    SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, DEV_H / 4),
311    // touching entire top edge
312    SkIRect::MakeLTRB(-10, -10, DEV_W  + 10, 0),
313    // overlapping top right corner
314    SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W  + 10, DEV_H / 4),
315    // contained in x, overlapping top edge
316    SkIRect::MakeLTRB(DEV_W / 4, -10, 3 * DEV_W  / 4, DEV_H / 4),
317    // outside top right corner
318    SkIRect::MakeLTRB(DEV_W + 1, -10, DEV_W + 10, -1),
319    // touching top right corner
320    SkIRect::MakeLTRB(DEV_W, -10, DEV_W + 10, 0),
321    // overlapping top left and bottom left corners
322    SkIRect::MakeLTRB(-10, -10, DEV_W / 4, DEV_H + 10),
323    // touching entire left edge
324    SkIRect::MakeLTRB(-10, -10, 0, DEV_H + 10),
325    // overlapping bottom left corner
326    SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W / 4, DEV_H + 10),
327    // contained in y, overlapping left edge
328    SkIRect::MakeLTRB(-10, DEV_H / 4, DEV_W / 4, 3 * DEV_H / 4),
329    // outside bottom left corner
330    SkIRect::MakeLTRB(-10, DEV_H + 1, -1, DEV_H + 10),
331    // touching bottom left corner
332    SkIRect::MakeLTRB(-10, DEV_H, 0, DEV_H + 10),
333    // overlapping bottom left and bottom right corners
334    SkIRect::MakeLTRB(-10, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
335    // touching entire left edge
336    SkIRect::MakeLTRB(0, DEV_H, DEV_W, DEV_H + 10),
337    // overlapping bottom right corner
338    SkIRect::MakeLTRB(3 * DEV_W / 4, 3 * DEV_H / 4, DEV_W + 10, DEV_H + 10),
339    // overlapping top right and bottom right corners
340    SkIRect::MakeLTRB(3 * DEV_W / 4, -10, DEV_W + 10, DEV_H + 10),
341};
342
343static void test_readpixels(skiatest::Reporter* reporter, const sk_sp<SkSurface>& surface,
344                            BitmapInit lastBitmapInit) {
345    SkCanvas* canvas = surface->getCanvas();
346    fill_src_canvas(canvas);
347    for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
348        const SkIRect& srcRect = gReadPixelsTestRects[rect];
349        for (BitmapInit bmi = kFirstBitmapInit; bmi <= lastBitmapInit; bmi = nextBMI(bmi)) {
350            for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
351                SkBitmap bmp;
352                init_bitmap(&bmp, srcRect, bmi,
353                            gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
354
355                // if the bitmap has pixels allocated before the readPixels,
356                // note that and fill them with pattern
357                bool startsWithPixels = !bmp.isNull();
358                if (startsWithPixels) {
359                    fill_dst_bmp_with_init_data(&bmp);
360                }
361                uint32_t idBefore = surface->generationID();
362                bool success = surface->readPixels(bmp, srcRect.fLeft, srcRect.fTop);
363                uint32_t idAfter = surface->generationID();
364
365                // we expect to succeed when the read isn't fully clipped
366                // out.
367                bool expectSuccess = SkIRect::Intersects(srcRect, DEV_RECT);
368                // determine whether we expected the read to succeed.
369                REPORTER_ASSERT(reporter, success == expectSuccess);
370                // read pixels should never change the gen id
371                REPORTER_ASSERT(reporter, idBefore == idAfter);
372
373                if (success || startsWithPixels) {
374                    check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop,
375                               success, startsWithPixels,
376                               gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
377                } else {
378                    // if we had no pixels beforehand and the readPixels
379                    // failed then our bitmap should still not have pixels
380                    REPORTER_ASSERT(reporter, bmp.isNull());
381                }
382            }
383        }
384    }
385}
386DEF_TEST(ReadPixels, reporter) {
387    const SkImageInfo info = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
388    auto surface(SkSurface::MakeRaster(info));
389    // SW readback fails a premul check when reading back to an unaligned rowbytes.
390    test_readpixels(reporter, surface, kLastAligned_BitmapInit);
391}
392#if SK_SUPPORT_GPU
393DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Gpu, reporter, ctxInfo) {
394    if (ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_D3D9_ES2_ContextType ||
395        ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_GL_ES2_ContextType ||
396        ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_D3D11_ES2_ContextType) {
397        // skbug.com/6742 ReadPixels_Texture & _Gpu don't work with ANGLE ES2 configs
398        return;
399    }
400
401    const SkImageInfo ii = SkImageInfo::MakeN32Premul(DEV_W, DEV_H);
402    for (auto& origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
403        sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctxInfo.grContext(), SkBudgeted::kNo,
404                                                             ii, 0, origin, nullptr));
405        test_readpixels(reporter, surface, kLast_BitmapInit);
406    }
407}
408#endif
409
410#if SK_SUPPORT_GPU
411static void test_readpixels_texture(skiatest::Reporter* reporter,
412                                    sk_sp<GrSurfaceContext> sContext) {
413    for (size_t rect = 0; rect < SK_ARRAY_COUNT(gReadPixelsTestRects); ++rect) {
414        const SkIRect& srcRect = gReadPixelsTestRects[rect];
415        for (BitmapInit bmi = kFirstBitmapInit; bmi <= kLast_BitmapInit; bmi = nextBMI(bmi)) {
416            for (size_t c = 0; c < SK_ARRAY_COUNT(gReadPixelsConfigs); ++c) {
417                SkBitmap bmp;
418                init_bitmap(&bmp, srcRect, bmi,
419                            gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
420
421                // if the bitmap has pixels allocated before the readPixels,
422                // note that and fill them with pattern
423                bool startsWithPixels = !bmp.isNull();
424                // Try doing the read directly from a non-renderable texture
425                if (startsWithPixels) {
426                    fill_dst_bmp_with_init_data(&bmp);
427                    uint32_t flags = 0;
428                    if (gReadPixelsConfigs[c].fAlphaType == kUnpremul_SkAlphaType) {
429                        flags = GrContextPriv::kUnpremul_PixelOpsFlag;
430                    }
431                    bool success = sContext->readPixels(bmp.info(), bmp.getPixels(),
432                                                        bmp.rowBytes(),
433                                                        srcRect.fLeft, srcRect.fTop, flags);
434                    check_read(reporter, bmp, srcRect.fLeft, srcRect.fTop,
435                               success, true,
436                               gReadPixelsConfigs[c].fColorType, gReadPixelsConfigs[c].fAlphaType);
437                }
438            }
439        }
440    }
441}
442
443DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadPixels_Texture, reporter, ctxInfo) {
444    if (ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_D3D9_ES2_ContextType ||
445        ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_GL_ES2_ContextType ||
446        ctxInfo.type() == sk_gpu_test::GrContextFactory::kANGLE_D3D11_ES2_ContextType) {
447        // skbug.com/6742 ReadPixels_Texture & _Gpu don't work with ANGLE ES2 configs
448        return;
449    }
450
451    GrContext* context = ctxInfo.grContext();
452    GrProxyProvider* proxyProvider = context->contextPriv().proxyProvider();
453
454    SkBitmap bmp = make_src_bitmap();
455
456    // On the GPU we will also try reading back from a non-renderable texture.
457    for (auto origin : {kBottomLeft_GrSurfaceOrigin, kTopLeft_GrSurfaceOrigin}) {
458        for (auto flags : {kNone_GrSurfaceFlags, kRenderTarget_GrSurfaceFlag}) {
459            GrSurfaceDesc desc;
460            desc.fFlags = flags;
461            desc.fWidth = DEV_W;
462            desc.fHeight = DEV_H;
463            desc.fConfig = kSkia8888_GrPixelConfig;
464            desc.fOrigin = origin;
465
466            sk_sp<GrTextureProxy> proxy = proxyProvider->createTextureProxy(desc, SkBudgeted::kNo,
467                                                                            bmp.getPixels(),
468                                                                            bmp.rowBytes());
469
470            sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(
471                                                                                std::move(proxy));
472
473            test_readpixels_texture(reporter, std::move(sContext));
474        }
475    }
476}
477#endif
478
479///////////////////////////////////////////////////////////////////////////////////////////////////
480
481static const uint32_t kNumPixels = 5;
482
483// The five reference pixels are: red, green, blue, white, black.
484// Five is an interesting number to test because we'll exercise a full 4-wide SIMD vector
485// plus a tail pixel.
486static const uint32_t rgba[kNumPixels] = {
487        0xFF0000FF, 0xFF00FF00, 0xFFFF0000, 0xFFFFFFFF, 0xFF000000
488};
489static const uint32_t bgra[kNumPixels] = {
490        0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFFFFFF, 0xFF000000
491};
492static const uint16_t rgb565[kNumPixels] = {
493        SK_R16_MASK_IN_PLACE, SK_G16_MASK_IN_PLACE, SK_B16_MASK_IN_PLACE, 0xFFFF, 0x0
494};
495
496static const uint16_t rgba4444[kNumPixels] = { 0xF00F, 0x0F0F, 0x00FF, 0xFFFF, 0x000F };
497
498static const uint64_t kRed      = (uint64_t) SK_Half1 <<  0;
499static const uint64_t kGreen    = (uint64_t) SK_Half1 << 16;
500static const uint64_t kBlue     = (uint64_t) SK_Half1 << 32;
501static const uint64_t kAlpha    = (uint64_t) SK_Half1 << 48;
502static const uint64_t f16[kNumPixels] = {
503        kAlpha | kRed, kAlpha | kGreen, kAlpha | kBlue, kAlpha | kBlue | kGreen | kRed, kAlpha
504};
505
506static const uint8_t alpha8[kNumPixels] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
507static const uint8_t gray8[kNumPixels] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
508
509static const void* five_reference_pixels(SkColorType colorType) {
510    switch (colorType) {
511        case kUnknown_SkColorType:
512            return nullptr;
513        case kAlpha_8_SkColorType:
514            return alpha8;
515        case kRGB_565_SkColorType:
516            return rgb565;
517        case kARGB_4444_SkColorType:
518            return rgba4444;
519        case kRGBA_8888_SkColorType:
520            return rgba;
521        case kBGRA_8888_SkColorType:
522            return bgra;
523        case kGray_8_SkColorType:
524            return gray8;
525        case kRGBA_F16_SkColorType:
526            return f16;
527        default:
528            return nullptr; // remove me when kIndex_8 is removed from the enum
529    }
530
531    SkASSERT(false);
532    return nullptr;
533}
534
535static void test_conversion(skiatest::Reporter* r, const SkImageInfo& dstInfo,
536                            const SkImageInfo& srcInfo) {
537    if (!SkImageInfoIsValidRenderingCS(srcInfo)) {
538        return;
539    }
540
541    const void* srcPixels = five_reference_pixels(srcInfo.colorType());
542    SkPixmap srcPixmap(srcInfo, srcPixels, srcInfo.minRowBytes());
543    sk_sp<SkImage> src = SkImage::MakeFromRaster(srcPixmap, nullptr, nullptr);
544    REPORTER_ASSERT(r, src);
545
546    // Enough space for 5 pixels when color type is F16, more than enough space in other cases.
547    uint64_t dstPixels[kNumPixels];
548    SkPixmap dstPixmap(dstInfo, dstPixels, dstInfo.minRowBytes());
549    bool success = src->readPixels(dstPixmap, 0, 0);
550    REPORTER_ASSERT(r, success == SkImageInfoValidConversion(dstInfo, srcInfo));
551
552    if (success) {
553        if (kGray_8_SkColorType == srcInfo.colorType() &&
554            kGray_8_SkColorType != dstInfo.colorType())
555        {
556            // This conversion is legal, but we won't get the "reference" pixels since we cannot
557            // represent colors in kGray8.
558            return;
559        }
560
561        REPORTER_ASSERT(r, 0 == memcmp(dstPixels, five_reference_pixels(dstInfo.colorType()),
562                                       kNumPixels * SkColorTypeBytesPerPixel(dstInfo.colorType())));
563
564    }
565}
566
567DEF_TEST(ReadPixels_ValidConversion, reporter) {
568    const SkColorType kColorTypes[] = {
569            kUnknown_SkColorType,
570            kAlpha_8_SkColorType,
571            kRGB_565_SkColorType,
572            kARGB_4444_SkColorType,
573            kRGBA_8888_SkColorType,
574            kBGRA_8888_SkColorType,
575            kGray_8_SkColorType,
576            kRGBA_F16_SkColorType,
577    };
578
579    const SkAlphaType kAlphaTypes[] = {
580            kUnknown_SkAlphaType,
581            kOpaque_SkAlphaType,
582            kPremul_SkAlphaType,
583            kUnpremul_SkAlphaType,
584    };
585
586    const sk_sp<SkColorSpace> kColorSpaces[] = {
587            nullptr,
588            SkColorSpace::MakeSRGB(),
589    };
590
591    for (SkColorType dstCT : kColorTypes) {
592        for (SkAlphaType dstAT: kAlphaTypes) {
593            for (sk_sp<SkColorSpace> dstCS : kColorSpaces) {
594                for (SkColorType srcCT : kColorTypes) {
595                    for (SkAlphaType srcAT: kAlphaTypes) {
596                        for (sk_sp<SkColorSpace> srcCS : kColorSpaces) {
597                            if (kRGBA_F16_SkColorType == dstCT && dstCS) {
598                                dstCS = dstCS->makeLinearGamma();
599                            }
600
601                            if (kRGBA_F16_SkColorType == srcCT && srcCS) {
602                                srcCS = srcCS->makeLinearGamma();
603                            }
604
605                            test_conversion(reporter,
606                                            SkImageInfo::Make(kNumPixels, 1, dstCT, dstAT, dstCS),
607                                            SkImageInfo::Make(kNumPixels, 1, srcCT, srcAT, srcCS));
608                        }
609                    }
610                }
611            }
612        }
613    }
614}
615