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