xref: /aosp_15_r20/external/skia/tests/graphite/ReadWritePixelsGraphiteTest.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2022 Google LLC.
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 "include/core/SkAlphaType.h"
9 #include "include/core/SkCanvas.h"
10 #include "include/core/SkColorSpace.h"
11 #include "include/core/SkColorType.h"
12 #include "include/core/SkPixmap.h"
13 #include "include/core/SkSurface.h"
14 #include "include/effects/SkGradientShader.h"
15 #include "include/gpu/GpuTypes.h"
16 #include "include/gpu/graphite/BackendTexture.h"
17 #include "include/gpu/graphite/Context.h"
18 #include "include/gpu/graphite/Image.h"
19 #include "include/gpu/graphite/Recorder.h"
20 #include "include/gpu/graphite/Recording.h"
21 #include "include/gpu/graphite/Surface.h"
22 #include "include/gpu/graphite/TextureInfo.h"
23 #include "src/base/SkRectMemcpy.h"
24 #include "src/core/SkAutoPixmapStorage.h"
25 #include "src/core/SkImageInfoPriv.h"
26 #include "src/gpu/graphite/Caps.h"
27 #include "src/gpu/graphite/ContextPriv.h"
28 #include "src/gpu/graphite/RecorderPriv.h"
29 #include "src/gpu/graphite/ResourceTypes.h"
30 #include "tests/Test.h"
31 #include "tests/TestUtils.h"
32 #include "tools/ToolUtils.h"
33 #include "tools/gpu/BackendTextureImageFactory.h"
34 #include "tools/gpu/ManagedBackendTexture.h"
35 #include "tools/graphite/GraphiteTestContext.h"
36 
37 using Mipmapped = skgpu::Mipmapped;
38 
min_rgb_channel_bits(SkColorType ct)39 static constexpr int min_rgb_channel_bits(SkColorType ct) {
40     switch (ct) {
41         case kUnknown_SkColorType:            return 0;
42         case kAlpha_8_SkColorType:            return 0;
43         case kA16_unorm_SkColorType:          return 0;
44         case kA16_float_SkColorType:          return 0;
45         case kRGB_565_SkColorType:            return 5;
46         case kARGB_4444_SkColorType:          return 4;
47         case kR8G8_unorm_SkColorType:         return 8;
48         case kR16G16_unorm_SkColorType:       return 16;
49         case kR16G16_float_SkColorType:       return 16;
50         case kRGBA_8888_SkColorType:          return 8;
51         case kSRGBA_8888_SkColorType:         return 8;
52         case kRGB_888x_SkColorType:           return 8;
53         case kBGRA_8888_SkColorType:          return 8;
54         case kRGBA_1010102_SkColorType:       return 10;
55         case kRGB_101010x_SkColorType:        return 10;
56         case kBGRA_1010102_SkColorType:       return 10;
57         case kBGR_101010x_SkColorType:        return 10;
58         case kBGR_101010x_XR_SkColorType:     return 10;
59         case kRGBA_10x6_SkColorType:          return 10;
60         case kBGRA_10101010_XR_SkColorType:   return 10;
61         case kGray_8_SkColorType:             return 8;   // counting gray as "rgb"
62         case kRGBA_F16Norm_SkColorType:       return 10;  // just counting the mantissa
63         case kRGBA_F16_SkColorType:           return 10;  // just counting the mantissa
64         case kRGB_F16F16F16x_SkColorType:     return 10;
65         case kRGBA_F32_SkColorType:           return 23;  // just counting the mantissa
66         case kR16G16B16A16_unorm_SkColorType: return 16;
67         case kR8_unorm_SkColorType:           return 8;
68     }
69     SkUNREACHABLE;
70 }
71 
alpha_channel_bits(SkColorType ct)72 static constexpr int alpha_channel_bits(SkColorType ct) {
73     switch (ct) {
74         case kUnknown_SkColorType:            return 0;
75         case kAlpha_8_SkColorType:            return 8;
76         case kA16_unorm_SkColorType:          return 16;
77         case kA16_float_SkColorType:          return 16;
78         case kRGB_565_SkColorType:            return 0;
79         case kARGB_4444_SkColorType:          return 4;
80         case kR8G8_unorm_SkColorType:         return 0;
81         case kR16G16_unorm_SkColorType:       return 0;
82         case kR16G16_float_SkColorType:       return 0;
83         case kRGBA_8888_SkColorType:          return 8;
84         case kSRGBA_8888_SkColorType:         return 8;
85         case kRGB_888x_SkColorType:           return 0;
86         case kBGRA_8888_SkColorType:          return 8;
87         case kRGBA_1010102_SkColorType:       return 2;
88         case kRGB_101010x_SkColorType:        return 0;
89         case kBGRA_1010102_SkColorType:       return 2;
90         case kBGR_101010x_SkColorType:        return 0;
91         case kBGR_101010x_XR_SkColorType:     return 0;
92         case kRGBA_10x6_SkColorType:          return 10;
93         case kBGRA_10101010_XR_SkColorType:   return 10;
94         case kGray_8_SkColorType:             return 0;
95         case kRGBA_F16Norm_SkColorType:       return 10;  // just counting the mantissa
96         case kRGBA_F16_SkColorType:           return 10;  // just counting the mantissa
97         case kRGB_F16F16F16x_SkColorType:     return 0;
98         case kRGBA_F32_SkColorType:           return 23;  // just counting the mantissa
99         case kR16G16B16A16_unorm_SkColorType: return 16;
100         case kR8_unorm_SkColorType:           return 0;
101     }
102     SkUNREACHABLE;
103 }
104 
105 namespace {
make_long_rect_array(int w,int h)106 std::vector<SkIRect> make_long_rect_array(int w, int h) {
107     return {
108             // entire thing
109             SkIRect::MakeWH(w, h),
110             // larger on all sides
111             SkIRect::MakeLTRB(-10, -10, w + 10, h + 10),
112             // fully contained
113             SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
114             // outside top left
115             SkIRect::MakeLTRB(-10, -10, -1, -1),
116             // touching top left corner
117             SkIRect::MakeLTRB(-10, -10, 0, 0),
118             // overlapping top left corner
119             SkIRect::MakeLTRB(-10, -10, w/4, h/4),
120             // overlapping top left and top right corners
121             SkIRect::MakeLTRB(-10, -10, w + 10, h/4),
122             // touching entire top edge
123             SkIRect::MakeLTRB(-10, -10, w + 10, 0),
124             // overlapping top right corner
125             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
126             // contained in x, overlapping top edge
127             SkIRect::MakeLTRB(w/4, -10, 3*w/4, h/4),
128             // outside top right corner
129             SkIRect::MakeLTRB(w + 1, -10, w + 10, -1),
130             // touching top right corner
131             SkIRect::MakeLTRB(w, -10, w + 10, 0),
132             // overlapping top left and bottom left corners
133             SkIRect::MakeLTRB(-10, -10, w/4, h + 10),
134             // touching entire left edge
135             SkIRect::MakeLTRB(-10, -10, 0, h + 10),
136             // overlapping bottom left corner
137             SkIRect::MakeLTRB(-10, 3*h/4, w/4, h + 10),
138             // contained in y, overlapping left edge
139             SkIRect::MakeLTRB(-10, h/4, w/4, 3*h/4),
140             // outside bottom left corner
141             SkIRect::MakeLTRB(-10, h + 1, -1, h + 10),
142             // touching bottom left corner
143             SkIRect::MakeLTRB(-10, h, 0, h + 10),
144             // overlapping bottom left and bottom right corners
145             SkIRect::MakeLTRB(-10, 3*h/4, w + 10, h + 10),
146             // touching entire left edge
147             SkIRect::MakeLTRB(0, h, w, h + 10),
148             // overlapping bottom right corner
149             SkIRect::MakeLTRB(3*w/4, 3*h/4, w + 10, h + 10),
150             // overlapping top right and bottom right corners
151             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h + 10),
152     };
153 }
154 
make_short_rect_array(int w,int h)155 std::vector<SkIRect> make_short_rect_array(int w, int h) {
156     return {
157             // entire thing
158             SkIRect::MakeWH(w, h),
159             // fully contained
160             SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
161             // overlapping top right corner
162             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
163     };
164 }
165 
166 struct GraphiteReadPixelTestRules {
167     // Test unpremul sources? We could omit this and detect that creating the source of the read
168     // failed but having it lets us skip generating reference color data.
169     bool fAllowUnpremulSrc = true;
170     // Are reads that are overlapping but not contained by the src bounds expected to succeed?
171     bool fUncontainedRectSucceeds = true;
172 };
173 
174 // Makes a src populated with the pixmap. The src should get its image info (or equivalent) from
175 // the pixmap.
176 template <typename T> using GraphiteSrcFactory = T(skgpu::graphite::Recorder*, SkPixmap&);
177 
178 enum class Result {
179     kFail,
180     kSuccess,
181     kExcusedFailure,
182 };
183 
184 // Does a read from the T into the pixmap.
185 template <typename T>
186 using GraphiteReadSrcFn = Result(const T&, const SkIPoint& offset, const SkPixmap&);
187 
make_ref_data(const SkImageInfo & info,bool forceOpaque)188 static SkAutoPixmapStorage make_ref_data(const SkImageInfo& info, bool forceOpaque) {
189     SkAutoPixmapStorage result;
190     if (info.alphaType() == kUnknown_SkAlphaType) {
191         result.alloc(info.makeAlphaType(kUnpremul_SkAlphaType));
192     } else {
193         result.alloc(info);
194     }
195     auto surface = SkSurfaces::WrapPixels(result);
196     if (!surface) {
197         return result;
198     }
199 
200     SkPoint pts1[] = {{0, 0}, {float(info.width()), float(info.height())}};
201     static constexpr SkColor kColors1[] = {SK_ColorGREEN, SK_ColorRED};
202     SkPaint paint;
203     paint.setShader(SkGradientShader::MakeLinear(pts1, kColors1, nullptr, 2, SkTileMode::kClamp));
204     surface->getCanvas()->drawPaint(paint);
205 
206     SkPoint pts2[] = {{float(info.width()), 0}, {0, float(info.height())}};
207     static constexpr SkColor kColors2[] = {SK_ColorBLUE, SK_ColorBLACK};
208     paint.setShader(SkGradientShader::MakeLinear(pts2, kColors2, nullptr, 2, SkTileMode::kClamp));
209     paint.setBlendMode(SkBlendMode::kPlus);
210     surface->getCanvas()->drawPaint(paint);
211 
212     // If not opaque add some fractional alpha.
213     if (info.alphaType() != kOpaque_SkAlphaType && !forceOpaque) {
214         static constexpr SkColor kColors3[] = {SK_ColorWHITE,
215                                                SK_ColorWHITE,
216                                                0x60FFFFFF,
217                                                SK_ColorWHITE,
218                                                SK_ColorWHITE};
219         static constexpr SkScalar kPos3[] = {0.f, 0.15f, 0.5f, 0.85f, 1.f};
220         paint.setShader(SkGradientShader::MakeRadial({info.width()/2.f, info.height()/2.f},
221                                                      (info.width() + info.height())/10.f,
222                                                      kColors3, kPos3, 5, SkTileMode::kMirror));
223         paint.setBlendMode(SkBlendMode::kDstIn);
224         surface->getCanvas()->drawPaint(paint);
225     }
226     return result;
227 };
228 }  // anonymous namespace
229 
230 template <typename T>
graphite_read_pixels_test_driver(skiatest::Reporter * reporter,skgpu::graphite::Context * context,const GraphiteReadPixelTestRules & rules,const std::function<GraphiteSrcFactory<T>> & srcFactory,const std::function<GraphiteReadSrcFn<T>> & read,SkString label)231 static void graphite_read_pixels_test_driver(skiatest::Reporter* reporter,
232                                              skgpu::graphite::Context* context,
233                                              const GraphiteReadPixelTestRules& rules,
234                                              const std::function<GraphiteSrcFactory<T>>& srcFactory,
235                                              const std::function<GraphiteReadSrcFn<T>>& read,
236                                              SkString label) {
237     if (!label.isEmpty()) {
238         // Add space for printing.
239         label.append(" ");
240     }
241     // Separate this out just to give it some line width to breathe. Note 'srcPixels' should have
242     // the same image info as src. We will do a converting readPixels() on it to get the data
243     // to compare with the results of 'read'.
244     auto runTest = [&](const T& src,
245                        const SkPixmap& srcPixels,
246                        const SkImageInfo& readInfo,
247                        SkIPoint offset) {
248         const bool csConversion =
249                 !SkColorSpace::Equals(readInfo.colorSpace(), srcPixels.info().colorSpace());
250         const auto readCT = readInfo.colorType();
251         const auto readAT = readInfo.alphaType();
252         const auto srcCT = srcPixels.info().colorType();
253         const auto srcAT = srcPixels.info().alphaType();
254         const auto rect = SkIRect::MakeWH(readInfo.width(), readInfo.height()).makeOffset(offset);
255         const auto surfBounds = SkIRect::MakeWH(srcPixels.width(), srcPixels.height());
256         const size_t readBpp = SkColorTypeBytesPerPixel(readCT);
257 
258         // Make the row bytes in the dst be loose for extra stress.
259         const size_t dstRB = readBpp * readInfo.width() + 10 * readBpp;
260         // This will make the last row tight.
261         const size_t dstSize = readInfo.computeByteSize(dstRB);
262         std::unique_ptr<char[]> dstData(new char[dstSize]);
263         SkPixmap dstPixels(readInfo, dstData.get(), dstRB);
264         // Initialize with an arbitrary value for each byte. Later we will check that only the
265         // correct part of the destination gets overwritten by 'read'.
266         static constexpr auto kInitialByte = static_cast<char>(0x1B);
267         std::fill_n(static_cast<char*>(dstPixels.writable_addr()),
268                     dstPixels.computeByteSize(),
269                     kInitialByte);
270 
271         const Result result = read(src, offset, dstPixels);
272 
273         if (!SkIRect::Intersects(rect, surfBounds)) {
274             REPORTER_ASSERT(reporter, result != Result::kSuccess);
275         } else if (readCT == kUnknown_SkColorType) {
276             REPORTER_ASSERT(reporter, result != Result::kSuccess);
277         } else if (readAT == kUnknown_SkAlphaType) {
278             REPORTER_ASSERT(reporter, result != Result::kSuccess);
279         } else if (!rules.fUncontainedRectSucceeds && !surfBounds.contains(rect)) {
280             REPORTER_ASSERT(reporter, result != Result::kSuccess);
281         } else if (result == Result::kFail) {
282             // TODO: Support BGR 101010x, BGRA 1010102, on the GPU.
283             ERRORF(reporter,
284                    "Read failed. %sSrc CT: %s, Src AT: %s Read CT: %s, Read AT: %s, "
285                    "Rect [%d, %d, %d, %d], CS conversion: %d\n",
286                    label.c_str(),
287                    ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
288                    ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
289                    rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
290             return result;
291         }
292 
293         bool guardOk = true;
294         auto guardCheck = [](char x) { return x == kInitialByte; };
295 
296         // Considering the rect we tried to read and the surface bounds figure  out which pixels in
297         // both src and dst space should actually have been read and written.
298         SkIRect srcReadRect;
299         if (result == Result::kSuccess && srcReadRect.intersect(surfBounds, rect)) {
300             SkIRect dstWriteRect = srcReadRect.makeOffset(-rect.fLeft, -rect.fTop);
301 
302             const bool lumConversion =
303                     !(SkColorTypeChannelFlags(srcCT) & kGray_SkColorChannelFlag) &&
304                     (SkColorTypeChannelFlags(readCT) & kGray_SkColorChannelFlag);
305             // A CS or luminance conversion allows a 3 value difference and otherwise a 2 value
306             // difference. Note that sometimes read back on GPU can be lossy even when there no
307             // conversion at all because GPU->CPU read may go to a lower bit depth format and then
308             // be promoted back to the original type. For example, GL ES cannot read to 1010102, so
309             // we go through 8888.
310             float numer = (lumConversion || csConversion) ? 3.f : 2.f;
311             // Allow some extra tolerance if unpremuling.
312             if (srcAT == kPremul_SkAlphaType && readAT == kUnpremul_SkAlphaType) {
313                 numer += 1;
314             }
315             int rgbBits = std::min({min_rgb_channel_bits(readCT), min_rgb_channel_bits(srcCT), 8});
316             float tol = numer / (1 << rgbBits);
317             float alphaTol = 0;
318             if (readAT != kOpaque_SkAlphaType && srcAT != kOpaque_SkAlphaType) {
319                 // Alpha can also get squashed down to 8 bits going through an intermediate
320                 // color format.
321                 const int alphaBits = std::min({alpha_channel_bits(readCT),
322                                                 alpha_channel_bits(srcCT),
323                                                 8});
324                 alphaTol = 2.f / (1 << alphaBits);
325             }
326 
327             const float tols[4] = {tol, tol, tol, alphaTol};
328             auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
329                                                                         const float diffs[4]) {
330                 SkASSERT(x >= 0 && y >= 0);
331                 ERRORF(reporter,
332                        "%sSrc CT: %s, Src AT: %s, Read CT: %s, Read AT: %s, Rect [%d, %d, %d, %d]"
333                        ", CS conversion: %d\n"
334                        "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
335                        label.c_str(),
336                        ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
337                        ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
338                        rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion, x, y,
339                        diffs[0], diffs[1], diffs[2], diffs[3]);
340             });
341             SkAutoPixmapStorage ref;
342             SkImageInfo refInfo = readInfo.makeDimensions(dstWriteRect.size());
343             ref.alloc(refInfo);
344             if (readAT == kUnknown_SkAlphaType) {
345                 // Do a spoofed read where src and dst alpha type are both kUnpremul. This will
346                 // allow SkPixmap readPixels to succeed and won't do any alpha type conversion.
347                 SkPixmap unpremulRef(refInfo.makeAlphaType(kUnpremul_SkAlphaType),
348                                      ref.addr(),
349                                      ref.rowBytes());
350                 SkPixmap unpremulSrc(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
351                                      srcPixels.addr(),
352                                      srcPixels.rowBytes());
353 
354                 unpremulSrc.readPixels(unpremulRef, srcReadRect.x(), srcReadRect.y());
355             } else {
356                 srcPixels.readPixels(ref, srcReadRect.x(), srcReadRect.y());
357             }
358             // This is the part of dstPixels that should have been updated.
359             SkPixmap actual;
360             SkAssertResult(dstPixels.extractSubset(&actual, dstWriteRect));
361             ComparePixels(ref, actual, tols, error);
362 
363             const auto* v = dstData.get();
364             const auto* end = dstData.get() + dstSize;
365             guardOk = std::all_of(v, v + dstWriteRect.top() * dstPixels.rowBytes(), guardCheck);
366             v += dstWriteRect.top() * dstPixels.rowBytes();
367             for (int y = dstWriteRect.top(); y < dstWriteRect.bottom(); ++y) {
368                 guardOk |= std::all_of(v, v + dstWriteRect.left() * readBpp, guardCheck);
369                 auto pad = v + dstWriteRect.right() * readBpp;
370                 auto rowEnd = std::min(end, v + dstPixels.rowBytes());
371                 // min protects against reading past the end of the tight last row.
372                 guardOk |= std::all_of(pad, rowEnd, guardCheck);
373                 v = rowEnd;
374             }
375             guardOk |= std::all_of(v, end, guardCheck);
376         } else {
377             guardOk = std::all_of(dstData.get(), dstData.get() + dstSize, guardCheck);
378         }
379         if (!guardOk) {
380             ERRORF(reporter,
381                    "Result pixels modified result outside read rect [%d, %d, %d, %d]. "
382                    "%sSrc CT: %s, Read CT: %s, CS conversion: %d",
383                    rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, label.c_str(),
384                    ToolUtils::colortype_name(srcCT), ToolUtils::colortype_name(readCT),
385                    csConversion);
386         }
387         return result;
388     };
389 
390     static constexpr int kW = 16;
391     static constexpr int kH = 16;
392 
393     const std::vector<SkIRect> longRectArray = make_long_rect_array(kW, kH);
394     const std::vector<SkIRect> shortRectArray = make_short_rect_array(kW, kH);
395 
396     // We ensure we use the long array once per src and read color type and otherwise use the
397     // short array to improve test run time.
398     // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
399     // equivalent. Just ensure each redundant AT is tested once with each CT (src and read).
400     // Similarly, alpha-only color types behave the same for all alpha types so just test premul
401     // after one iter.
402     // We consider a src or read CT thoroughly tested once it has run through the long rect array
403     // and full complement of alpha types with one successful read in the loop.
404     std::array<bool, kLastEnum_SkColorType + 1> srcCTTestedThoroughly  = {},
405                                                 readCTTestedThoroughly = {};
406     for (int sat = 0; sat <= kLastEnum_SkAlphaType; ++sat) {
407         const auto srcAT = static_cast<SkAlphaType>(sat);
408         if (srcAT == kUnpremul_SkAlphaType && !rules.fAllowUnpremulSrc) {
409             continue;
410         }
411         for (int sct = 0; sct <= kLastEnum_SkColorType; ++sct) {
412             const auto srcCT = static_cast<SkColorType>(sct);
413             // We always make our ref data as F32
414             auto refInfo = SkImageInfo::Make(kW, kH,
415                                              kRGBA_F32_SkColorType,
416                                              srcAT,
417                                              SkColorSpace::MakeSRGB());
418             // 1010102 formats have an issue where it's easy to make a resulting
419             // color where r, g, or b is greater than a. CPU/GPU differ in whether the stored color
420             // channels are clipped to the alpha value. CPU clips but GPU does not.
421             // Note that we only currently use srcCT for the 1010102 workaround. If we remove this
422             // we can also put the ref data setup above the srcCT loop.
423             bool forceOpaque = srcAT == kPremul_SkAlphaType &&
424                     (srcCT == kRGBA_1010102_SkColorType || srcCT == kBGRA_1010102_SkColorType);
425 
426             SkAutoPixmapStorage refPixels = make_ref_data(refInfo, forceOpaque);
427             // Convert the ref data to our desired src color type.
428             const auto srcInfo = SkImageInfo::Make(kW, kH, srcCT, srcAT, SkColorSpace::MakeSRGB());
429             SkAutoPixmapStorage srcPixels;
430             srcPixels.alloc(srcInfo);
431             {
432                 SkPixmap readPixmap = srcPixels;
433                 // Spoof the alpha type to kUnpremul so the read will succeed without doing any
434                 // conversion (because we made our surface also use kUnpremul).
435                 if (srcAT == kUnknown_SkAlphaType) {
436                     readPixmap.reset(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
437                                      srcPixels.addr(),
438                                      srcPixels.rowBytes());
439                 }
440                 refPixels.readPixels(readPixmap, 0, 0);
441             }
442 
443             std::unique_ptr<skgpu::graphite::Recorder> recorder = context->makeRecorder();
444 
445             auto src = srcFactory(recorder.get(), srcPixels);
446             if (!src) {
447                 continue;
448             }
449             if (SkColorTypeIsAlwaysOpaque(srcCT) && srcCTTestedThoroughly[srcCT] &&
450                 (kPremul_SkAlphaType == srcAT || kUnpremul_SkAlphaType == srcAT)) {
451                 continue;
452             }
453             if (SkColorTypeIsAlphaOnly(srcCT) && srcCTTestedThoroughly[srcCT] &&
454                 (kUnpremul_SkAlphaType == srcAT ||
455                  kOpaque_SkAlphaType   == srcAT ||
456                  kUnknown_SkAlphaType  == srcAT)) {
457                 continue;
458             }
459             for (int rct = 0; rct <= kLastEnum_SkColorType; ++rct) {
460                 const auto readCT = static_cast<SkColorType>(rct);
461                 // ComparePixels will end up converting these types to kUnknown
462                 // because there's no corresponding GrColorType, and hence it will fail
463                 if (readCT == kBGR_101010x_XR_SkColorType ||
464                     readCT == kBGRA_10101010_XR_SkColorType ||
465                     readCT == kBGR_101010x_SkColorType) {
466                     continue;
467                 }
468                 for (const sk_sp<SkColorSpace>& readCS :
469                      {SkColorSpace::MakeSRGB(), SkColorSpace::MakeSRGBLinear()}) {
470                     for (int at = 0; at <= kLastEnum_SkAlphaType; ++at) {
471                         const auto readAT = static_cast<SkAlphaType>(at);
472                         if (srcAT != kOpaque_SkAlphaType && readAT == kOpaque_SkAlphaType) {
473                             // This doesn't make sense.
474                             continue;
475                         }
476                         if (SkColorTypeIsAlwaysOpaque(readCT) && readCTTestedThoroughly[readCT] &&
477                             (kPremul_SkAlphaType == readAT || kUnpremul_SkAlphaType == readAT)) {
478                             continue;
479                         }
480                         if (SkColorTypeIsAlphaOnly(readCT) && readCTTestedThoroughly[readCT] &&
481                             (kUnpremul_SkAlphaType == readAT ||
482                              kOpaque_SkAlphaType   == readAT ||
483                              kUnknown_SkAlphaType  == readAT)) {
484                             continue;
485                         }
486                         const auto& rects =
487                                 srcCTTestedThoroughly[sct] && readCTTestedThoroughly[rct]
488                                         ? shortRectArray
489                                         : longRectArray;
490                         for (const auto& rect : rects) {
491                             const auto readInfo = SkImageInfo::Make(rect.width(), rect.height(),
492                                                                     readCT, readAT, readCS);
493                             const SkIPoint offset = rect.topLeft();
494                             Result r = runTest(src, srcPixels, readInfo, offset);
495                             if (r == Result::kSuccess) {
496                                 srcCTTestedThoroughly[sct] = true;
497                                 readCTTestedThoroughly[rct] = true;
498                             }
499                         }
500                     }
501                 }
502             }
503         }
504     }
505 }
506 
507 namespace {
508 struct AsyncContext {
509     bool fCalled = false;
510     std::unique_ptr<const SkImage::AsyncReadResult> fResult;
511 };
512 }  // anonymous namespace
513 
514 // Making this a lambda in the test functions caused:
515 //   "error: cannot compile this forwarded non-trivially copyable parameter yet"
516 // on x86/Win/Clang bot, referring to 'result'.
async_callback(void * c,std::unique_ptr<const SkImage::AsyncReadResult> result)517 static void async_callback(void* c, std::unique_ptr<const SkImage::AsyncReadResult> result) {
518     auto context = static_cast<AsyncContext*>(c);
519     context->fResult = std::move(result);
520     context->fCalled = true;
521 };
522 
DEF_CONDITIONAL_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixelsGraphite,reporter,context,testContext,true,CtsEnforcement::kApiLevel_V)523 DEF_CONDITIONAL_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixelsGraphite,
524                                                      reporter,
525                                                      context,
526                                                      testContext,
527                                                      true,
528                                                      CtsEnforcement::kApiLevel_V) {
529     using Image = sk_sp<SkImage>;
530     using Renderable = skgpu::Renderable;
531     using TextureInfo = skgpu::graphite::TextureInfo;
532 
533     auto reader = std::function<GraphiteReadSrcFn<Image>>([context, testContext](
534                                                                   const Image& image,
535                                                                   const SkIPoint& offset,
536                                                                   const SkPixmap& pixels) {
537         AsyncContext asyncContext;
538         auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
539         // The GPU implementation is based on rendering and will fail for non-renderable color
540         // types.
541         TextureInfo texInfo = context->priv().caps()->getDefaultSampledTextureInfo(
542                 image->colorType(),
543                 Mipmapped::kNo,
544                 skgpu::Protected::kNo,
545                 Renderable::kYes);
546         if (!context->priv().caps()->isRenderable(texInfo)) {
547             return Result::kExcusedFailure;
548         }
549 
550         context->asyncRescaleAndReadPixels(image.get(),
551                                            pixels.info(),
552                                            rect,
553                                            SkImage::RescaleGamma::kSrc,
554                                            SkImage::RescaleMode::kRepeatedLinear,
555                                            async_callback,
556                                            &asyncContext);
557         if (!asyncContext.fCalled) {
558             context->submit();
559         }
560         while (!asyncContext.fCalled) {
561             testContext->tick();
562             context->checkAsyncWorkCompletion();
563         }
564         if (!asyncContext.fResult) {
565             return Result::kFail;
566         }
567         SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), asyncContext.fResult->data(0),
568                      asyncContext.fResult->rowBytes(0), pixels.info().minRowBytes(),
569                      pixels.height());
570         return Result::kSuccess;
571     });
572 
573     GraphiteReadPixelTestRules rules;
574     rules.fAllowUnpremulSrc = true;
575     rules.fUncontainedRectSucceeds = false;
576 
577     for (auto renderable : {Renderable::kNo, Renderable::kYes}) {
578         auto factory = std::function<GraphiteSrcFactory<Image>>([&](
579                 skgpu::graphite::Recorder* recorder,
580                 const SkPixmap& src) {
581             Image image = sk_gpu_test::MakeBackendTextureImage(recorder,
582                                                                src,
583                                                                Mipmapped::kNo,
584                                                                renderable,
585                                                                skgpu::Origin::kTopLeft,
586                                                                skgpu::Protected::kNo);
587 
588             std::unique_ptr<skgpu::graphite::Recording> recording = recorder->snap();
589             skgpu::graphite::InsertRecordingInfo recordingInfo;
590             recordingInfo.fRecording = recording.get();
591             context->insertRecording(recordingInfo);
592 
593             return image;
594         });
595         auto label = SkStringPrintf("Renderable: %d", (int)renderable);
596         graphite_read_pixels_test_driver(reporter, context, rules, factory, reader, label);
597     }
598 
599     // It's possible that we've created an Image using the factory, but then don't try to do
600     // readPixels on it, leaving a hanging command buffer. So we submit here to clean up.
601     context->submit();
602 }
603 
DEF_CONDITIONAL_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixelsGraphite,reporter,context,testContext,true,CtsEnforcement::kApiLevel_V)604 DEF_CONDITIONAL_GRAPHITE_TEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixelsGraphite,
605                                                      reporter,
606                                                      context,
607                                                      testContext,
608                                                      true,
609                                                      CtsEnforcement::kApiLevel_V) {
610     using Surface = sk_sp<SkSurface>;
611 
612     auto reader = std::function<GraphiteReadSrcFn<Surface>>([context, testContext](
613                                                                     const Surface& surface,
614                                                                     const SkIPoint& offset,
615                                                                     const SkPixmap& pixels) {
616         AsyncContext asyncContext;
617         auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
618 
619         context->asyncRescaleAndReadPixels(surface.get(),
620                                            pixels.info(),
621                                            rect,
622                                            SkImage::RescaleGamma::kSrc,
623                                            SkImage::RescaleMode::kRepeatedLinear,
624                                            async_callback,
625                                            &asyncContext);
626         if (!asyncContext.fCalled) {
627             context->submit();
628         }
629         while (!asyncContext.fCalled) {
630             testContext->tick();
631             context->checkAsyncWorkCompletion();
632         }
633         if (!asyncContext.fResult) {
634             return Result::kFail;
635         }
636         SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), asyncContext.fResult->data(0),
637                      asyncContext.fResult->rowBytes(0), pixels.info().minRowBytes(),
638                      pixels.height());
639         return Result::kSuccess;
640     });
641 
642     GraphiteReadPixelTestRules rules;
643     rules.fAllowUnpremulSrc = true;
644     rules.fUncontainedRectSucceeds = false;
645 
646     auto factory = std::function<GraphiteSrcFactory<Surface>>(
647             [&](skgpu::graphite::Recorder* recorder, const SkPixmap& src) {
648                 Surface surface = SkSurfaces::RenderTarget(recorder,
649                                                            src.info(),
650                                                            Mipmapped::kNo,
651                                                            /*surfaceProps=*/nullptr);
652                 if (surface) {
653                     surface->writePixels(src, 0, 0);
654 
655                     std::unique_ptr<skgpu::graphite::Recording> recording = recorder->snap();
656                     skgpu::graphite::InsertRecordingInfo recordingInfo;
657                     recordingInfo.fRecording = recording.get();
658                     context->insertRecording(recordingInfo);
659                 }
660 
661                 return surface;
662             });
663     graphite_read_pixels_test_driver(reporter, context, rules, factory, reader, {});
664 
665     // It's possible that we've created an Image using the factory, but then don't try to do
666     // readPixels on it, leaving a hanging command buffer. So we submit here to clean up.
667     context->submit();
668 }
669