• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 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/SkBitmap.h"
10 #include "include/core/SkBlendMode.h"
11 #include "include/core/SkCanvas.h"
12 #include "include/core/SkColor.h"
13 #include "include/core/SkColorSpace.h"
14 #include "include/core/SkColorType.h"
15 #include "include/core/SkImage.h"
16 #include "include/core/SkImageInfo.h"
17 #include "include/core/SkMatrix.h"
18 #include "include/core/SkPaint.h"
19 #include "include/core/SkPixmap.h"
20 #include "include/core/SkPoint.h"
21 #include "include/core/SkRect.h"
22 #include "include/core/SkRefCnt.h"
23 #include "include/core/SkSamplingOptions.h"
24 #include "include/core/SkScalar.h"
25 #include "include/core/SkString.h"
26 #include "include/core/SkSurface.h"
27 #include "include/core/SkTileMode.h"
28 #include "include/core/SkTypes.h"
29 #include "include/effects/SkGradientShader.h"
30 #include "include/gpu/GpuTypes.h"
31 #include "include/gpu/GrBackendSurface.h"
32 #include "include/gpu/GrDirectContext.h"
33 #include "include/gpu/GrRecordingContext.h"
34 #include "include/gpu/GrTypes.h"
35 #include "include/gpu/ganesh/SkImageGanesh.h"
36 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
37 #include "include/private/base/SkTArray.h"
38 #include "include/private/gpu/ganesh/GrTypesPriv.h"
39 #include "src/base/SkRectMemcpy.h"
40 #include "src/core/SkAutoPixmapStorage.h"
41 #include "src/core/SkImageInfoPriv.h"
42 #include "src/gpu/SkBackingFit.h"
43 #include "src/gpu/ganesh/GrCaps.h"
44 #include "src/gpu/ganesh/GrDataUtils.h"
45 #include "src/gpu/ganesh/GrDirectContextPriv.h"
46 #include "src/gpu/ganesh/GrFragmentProcessor.h"
47 #include "src/gpu/ganesh/GrImageInfo.h"
48 #include "src/gpu/ganesh/GrPixmap.h"
49 #include "src/gpu/ganesh/GrSamplerState.h"
50 #include "src/gpu/ganesh/GrSurfaceProxy.h"
51 #include "src/gpu/ganesh/SurfaceContext.h"
52 #include "src/gpu/ganesh/SurfaceFillContext.h"
53 #include "src/gpu/ganesh/effects/GrTextureEffect.h"
54 #include "tests/CtsEnforcement.h"
55 #include "tests/Test.h"
56 #include "tests/TestUtils.h"
57 #include "tools/ToolUtils.h"
58 #include "tools/gpu/BackendSurfaceFactory.h"
59 #include "tools/gpu/BackendTextureImageFactory.h"
60 #include "tools/gpu/ContextType.h"
61 
62 #include <algorithm>
63 #include <array>
64 #include <cstring>
65 #include <functional>
66 #include <initializer_list>
67 #include <memory>
68 #include <utility>
69 #include <vector>
70 
71 using namespace skia_private;
72 
73 struct GrContextOptions;
74 
min_rgb_channel_bits(SkColorType ct)75 static constexpr int min_rgb_channel_bits(SkColorType ct) {
76     switch (ct) {
77         case kUnknown_SkColorType:            return 0;
78         case kAlpha_8_SkColorType:            return 0;
79         case kA16_unorm_SkColorType:          return 0;
80         case kA16_float_SkColorType:          return 0;
81         case kRGB_565_SkColorType:            return 5;
82         case kARGB_4444_SkColorType:          return 4;
83         case kR8G8_unorm_SkColorType:         return 8;
84         case kR16G16_unorm_SkColorType:       return 16;
85         case kR16G16_float_SkColorType:       return 16;
86         case kRGBA_8888_SkColorType:          return 8;
87         case kSRGBA_8888_SkColorType:         return 8;
88         case kRGB_888x_SkColorType:           return 8;
89         case kBGRA_8888_SkColorType:          return 8;
90         case kRGBA_1010102_SkColorType:       return 10;
91         case kRGB_101010x_SkColorType:        return 10;
92         case kBGRA_1010102_SkColorType:       return 10;
93         case kBGR_101010x_SkColorType:        return 10;
94         case kBGR_101010x_XR_SkColorType:     return 10;
95         case kRGBA_10x6_SkColorType:          return 10;
96         case kBGRA_10101010_XR_SkColorType:   return 10;
97         case kGray_8_SkColorType:             return 8;   // counting gray as "rgb"
98         case kRGBA_F16Norm_SkColorType:       return 10;  // just counting the mantissa
99         case kRGBA_F16_SkColorType:           return 10;  // just counting the mantissa
100         case kRGBA_F32_SkColorType:           return 23;  // just counting the mantissa
101         case kR16G16B16A16_unorm_SkColorType: return 16;
102         case kR8_unorm_SkColorType:           return 8;
103     }
104     SkUNREACHABLE;
105 }
106 
alpha_channel_bits(SkColorType ct)107 static constexpr int alpha_channel_bits(SkColorType ct) {
108     switch (ct) {
109         case kUnknown_SkColorType:            return 0;
110         case kAlpha_8_SkColorType:            return 8;
111         case kA16_unorm_SkColorType:          return 16;
112         case kA16_float_SkColorType:          return 16;
113         case kRGB_565_SkColorType:            return 0;
114         case kARGB_4444_SkColorType:          return 4;
115         case kR8G8_unorm_SkColorType:         return 0;
116         case kR16G16_unorm_SkColorType:       return 0;
117         case kR16G16_float_SkColorType:       return 0;
118         case kRGBA_8888_SkColorType:          return 8;
119         case kSRGBA_8888_SkColorType:         return 8;
120         case kRGB_888x_SkColorType:           return 0;
121         case kBGRA_8888_SkColorType:          return 8;
122         case kRGBA_1010102_SkColorType:       return 2;
123         case kRGB_101010x_SkColorType:        return 0;
124         case kBGRA_1010102_SkColorType:       return 2;
125         case kBGR_101010x_SkColorType:        return 0;
126         case kBGR_101010x_XR_SkColorType:     return 0;
127         case kRGBA_10x6_SkColorType:          return 10;
128         case kBGRA_10101010_XR_SkColorType:   return 10;
129         case kGray_8_SkColorType:             return 0;
130         case kRGBA_F16Norm_SkColorType:       return 10;  // just counting the mantissa
131         case kRGBA_F16_SkColorType:           return 10;  // just counting the mantissa
132         case kRGBA_F32_SkColorType:           return 23;  // just counting the mantissa
133         case kR16G16B16A16_unorm_SkColorType: return 16;
134         case kR8_unorm_SkColorType:           return 0;
135     }
136     SkUNREACHABLE;
137 }
138 
make_long_rect_array(int w,int h)139 std::vector<SkIRect> make_long_rect_array(int w, int h) {
140     return {
141             // entire thing
142             SkIRect::MakeWH(w, h),
143             // larger on all sides
144             SkIRect::MakeLTRB(-10, -10, w + 10, h + 10),
145             // fully contained
146             SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
147             // outside top left
148             SkIRect::MakeLTRB(-10, -10, -1, -1),
149             // touching top left corner
150             SkIRect::MakeLTRB(-10, -10, 0, 0),
151             // overlapping top left corner
152             SkIRect::MakeLTRB(-10, -10, w/4, h/4),
153             // overlapping top left and top right corners
154             SkIRect::MakeLTRB(-10, -10, w + 10, h/4),
155             // touching entire top edge
156             SkIRect::MakeLTRB(-10, -10, w + 10, 0),
157             // overlapping top right corner
158             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
159             // contained in x, overlapping top edge
160             SkIRect::MakeLTRB(w/4, -10, 3*w/4, h/4),
161             // outside top right corner
162             SkIRect::MakeLTRB(w + 1, -10, w + 10, -1),
163             // touching top right corner
164             SkIRect::MakeLTRB(w, -10, w + 10, 0),
165             // overlapping top left and bottom left corners
166             SkIRect::MakeLTRB(-10, -10, w/4, h + 10),
167             // touching entire left edge
168             SkIRect::MakeLTRB(-10, -10, 0, h + 10),
169             // overlapping bottom left corner
170             SkIRect::MakeLTRB(-10, 3*h/4, w/4, h + 10),
171             // contained in y, overlapping left edge
172             SkIRect::MakeLTRB(-10, h/4, w/4, 3*h/4),
173             // outside bottom left corner
174             SkIRect::MakeLTRB(-10, h + 1, -1, h + 10),
175             // touching bottom left corner
176             SkIRect::MakeLTRB(-10, h, 0, h + 10),
177             // overlapping bottom left and bottom right corners
178             SkIRect::MakeLTRB(-10, 3*h/4, w + 10, h + 10),
179             // touching entire left edge
180             SkIRect::MakeLTRB(0, h, w, h + 10),
181             // overlapping bottom right corner
182             SkIRect::MakeLTRB(3*w/4, 3*h/4, w + 10, h + 10),
183             // overlapping top right and bottom right corners
184             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h + 10),
185     };
186 }
187 
make_short_rect_array(int w,int h)188 std::vector<SkIRect> make_short_rect_array(int w, int h) {
189     return {
190             // entire thing
191             SkIRect::MakeWH(w, h),
192             // fully contained
193             SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
194             // overlapping top right corner
195             SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
196     };
197 }
198 
199 namespace {
200 
201 struct GpuReadPixelTestRules {
202     // Test unpremul sources? We could omit this and detect that creating the source of the read
203     // failed but having it lets us skip generating reference color data.
204     bool fAllowUnpremulSrc = true;
205     // Are reads that are overlapping but not contained by the src bounds expected to succeed?
206     bool fUncontainedRectSucceeds = true;
207     // Skip SRGB src colortype?
208     bool fSkipSRGBCT = false;
209     // Skip 16-bit src colortypes?
210     bool fSkip16BitCT = false;
211 };
212 
213 // Makes a src populated with the pixmap. The src should get its image info (or equivalent) from
214 // the pixmap.
215 template <typename T> using GpuSrcFactory = T(SkPixmap&);
216 
217 enum class Result {
218     kFail,
219     kSuccess,
220     kExcusedFailure,
221 };
222 
223 // Does a read from the T into the pixmap.
224 template <typename T>
225 using GpuReadSrcFn = Result(const T&, const SkIPoint& offset, const SkPixmap&);
226 
227 // Makes a dst for testing writes.
228 template <typename T> using GpuDstFactory = T(const SkImageInfo& ii);
229 
230 // Does a write from the pixmap to the T.
231 template <typename T>
232 using GpuWriteDstFn = Result(const T&, const SkIPoint& offset, const SkPixmap&);
233 
234 // To test the results of the write we do a read. This reads the entire src T. It should do a non-
235 // converting read (i.e. the image info of the returned pixmap matches that of the T).
236 template <typename T>
237 using GpuReadDstFn = SkAutoPixmapStorage(const T&);
238 
239 }  // anonymous namespace
240 
make_pixmap_have_valid_alpha_type(SkPixmap pm)241 SkPixmap make_pixmap_have_valid_alpha_type(SkPixmap pm) {
242     if (pm.alphaType() == kUnknown_SkAlphaType) {
243         return {pm.info().makeAlphaType(kUnpremul_SkAlphaType), pm.addr(), pm.rowBytes()};
244     }
245     return pm;
246 }
247 
make_ref_data(const SkImageInfo & info,bool forceOpaque)248 static SkAutoPixmapStorage make_ref_data(const SkImageInfo& info, bool forceOpaque) {
249     SkAutoPixmapStorage result;
250     if (info.alphaType() == kUnknown_SkAlphaType) {
251         result.alloc(info.makeAlphaType(kUnpremul_SkAlphaType));
252     } else {
253         result.alloc(info);
254     }
255     auto surface = SkSurfaces::WrapPixels(result);
256     if (!surface) {
257         return result;
258     }
259 
260     SkPoint pts1[] = {{0, 0}, {float(info.width()), float(info.height())}};
261     static constexpr SkColor kColors1[] = {SK_ColorGREEN, SK_ColorRED};
262     SkPaint paint;
263     paint.setShader(SkGradientShader::MakeLinear(pts1, kColors1, nullptr, 2, SkTileMode::kClamp));
264     surface->getCanvas()->drawPaint(paint);
265 
266     SkPoint pts2[] = {{float(info.width()), 0}, {0, float(info.height())}};
267     static constexpr SkColor kColors2[] = {SK_ColorBLUE, SK_ColorBLACK};
268     paint.setShader(SkGradientShader::MakeLinear(pts2, kColors2, nullptr, 2, SkTileMode::kClamp));
269     paint.setBlendMode(SkBlendMode::kPlus);
270     surface->getCanvas()->drawPaint(paint);
271 
272     // If not opaque add some fractional alpha.
273     if (info.alphaType() != kOpaque_SkAlphaType && !forceOpaque) {
274         static constexpr SkColor kColors3[] = {SK_ColorWHITE,
275                                                SK_ColorWHITE,
276                                                0x60FFFFFF,
277                                                SK_ColorWHITE,
278                                                SK_ColorWHITE};
279         static constexpr SkScalar kPos3[] = {0.f, 0.15f, 0.5f, 0.85f, 1.f};
280         paint.setShader(SkGradientShader::MakeRadial({info.width()/2.f, info.height()/2.f},
281                                                      (info.width() + info.height())/10.f,
282                                                      kColors3, kPos3, 5, SkTileMode::kMirror));
283         paint.setBlendMode(SkBlendMode::kDstIn);
284         surface->getCanvas()->drawPaint(paint);
285     }
286     return result;
287 }
288 
289 template <typename T>
gpu_read_pixels_test_driver(skiatest::Reporter * reporter,const GpuReadPixelTestRules & rules,const std::function<GpuSrcFactory<T>> & srcFactory,const std::function<GpuReadSrcFn<T>> & read,SkString label)290 static void gpu_read_pixels_test_driver(skiatest::Reporter* reporter,
291                                         const GpuReadPixelTestRules& rules,
292                                         const std::function<GpuSrcFactory<T>>& srcFactory,
293                                         const std::function<GpuReadSrcFn<T>>& read,
294                                         SkString label) {
295     if (!label.isEmpty()) {
296         // Add space for printing.
297         label.append(" ");
298     }
299     // Separate this out just to give it some line width to breathe. Note 'srcPixels' should have
300     // the same image info as src. We will do a converting readPixels() on it to get the data
301     // to compare with the results of 'read'.
302     auto runTest = [&](const T& src,
303                        const SkPixmap& srcPixels,
304                        const SkImageInfo& readInfo,
305                        SkIPoint offset) {
306         const bool csConversion =
307                 !SkColorSpace::Equals(readInfo.colorSpace(), srcPixels.info().colorSpace());
308         const auto readCT = readInfo.colorType();
309         const auto readAT = readInfo.alphaType();
310         const auto srcCT = srcPixels.info().colorType();
311         const auto srcAT = srcPixels.info().alphaType();
312         const auto rect = SkIRect::MakeWH(readInfo.width(), readInfo.height()).makeOffset(offset);
313         const auto surfBounds = SkIRect::MakeWH(srcPixels.width(), srcPixels.height());
314         const size_t readBpp = SkColorTypeBytesPerPixel(readCT);
315 
316         // Make the row bytes in the dst be loose for extra stress.
317         const size_t dstRB = readBpp * readInfo.width() + 10 * readBpp;
318         // This will make the last row tight.
319         const size_t dstSize = readInfo.computeByteSize(dstRB);
320         std::unique_ptr<char[]> dstData(new char[dstSize]);
321         SkPixmap dstPixels(readInfo, dstData.get(), dstRB);
322         // Initialize with an arbitrary value for each byte. Later we will check that only the
323         // correct part of the destination gets overwritten by 'read'.
324         static constexpr auto kInitialByte = static_cast<char>(0x1B);
325         std::fill_n(static_cast<char*>(dstPixels.writable_addr()),
326                     dstPixels.computeByteSize(),
327                     kInitialByte);
328 
329         const Result result = read(src, offset, dstPixels);
330 
331         if (!SkIRect::Intersects(rect, surfBounds)) {
332             REPORTER_ASSERT(reporter, result != Result::kSuccess);
333         } else if (readCT == kUnknown_SkColorType) {
334             REPORTER_ASSERT(reporter, result != Result::kSuccess);
335         } else if ((readAT == kUnknown_SkAlphaType) != (srcAT == kUnknown_SkAlphaType)) {
336             REPORTER_ASSERT(reporter, result != Result::kSuccess);
337         } else if (!rules.fUncontainedRectSucceeds && !surfBounds.contains(rect)) {
338             REPORTER_ASSERT(reporter, result != Result::kSuccess);
339         } else if (result == Result::kFail) {
340             // TODO: Support RGB/BGR 101010x, BGRA 1010102 on the GPU.
341             if (SkColorTypeToGrColorType(readCT) != GrColorType::kUnknown) {
342                 ERRORF(reporter,
343                        "Read failed. %sSrc CT: %s, Src AT: %s Read CT: %s, Read AT: %s, "
344                        "Rect [%d, %d, %d, %d], CS conversion: %d\n",
345                        label.c_str(),
346                        ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
347                        ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
348                        rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
349             }
350             return result;
351         }
352 
353         bool guardOk = true;
354         auto guardCheck = [](char x) { return x == kInitialByte; };
355 
356         // Considering the rect we tried to read and the surface bounds figure  out which pixels in
357         // both src and dst space should actually have been read and written.
358         SkIRect srcReadRect;
359         if (result == Result::kSuccess && srcReadRect.intersect(surfBounds, rect)) {
360             SkIRect dstWriteRect = srcReadRect.makeOffset(-rect.fLeft, -rect.fTop);
361 
362             const bool lumConversion =
363                     !(SkColorTypeChannelFlags(srcCT) & kGray_SkColorChannelFlag) &&
364                     (SkColorTypeChannelFlags(readCT) & kGray_SkColorChannelFlag);
365             // A CS or luminance conversion allows a 3 value difference and otherwise a 2 value
366             // difference. Note that sometimes read back on GPU can be lossy even when there no
367             // conversion at all because GPU->CPU read may go to a lower bit depth format and then
368             // be promoted back to the original type. For example, GL ES cannot read to 1010102, so
369             // we go through 8888.
370             float numer = (lumConversion || csConversion) ? 3.f : 2.f;
371             // Allow some extra tolerance if unpremuling.
372             if (srcAT == kPremul_SkAlphaType && readAT == kUnpremul_SkAlphaType) {
373                 numer += 1;
374             }
375             int rgbBits = std::min({min_rgb_channel_bits(readCT), min_rgb_channel_bits(srcCT), 8});
376             float tol = (rgbBits == 0) ? 1.f : numer / ((1 << rgbBits) - 1);
377             // Swiftshader is producing alpha errors with 16-bit UNORM. We choose to always allow
378             // a small tolerance:
379             float alphaTol = 1.f / ((1 << 10) - 1);
380             if (readAT != kOpaque_SkAlphaType && srcAT != kOpaque_SkAlphaType) {
381                 // Alpha can also get squashed down to 8 bits going through an intermediate
382                 // color format.
383                 const int alphaBits = std::min({alpha_channel_bits(readCT),
384                                                 alpha_channel_bits(srcCT),
385                                                 8});
386                 alphaTol = (alphaBits == 0) ? 1.f : 2.f / ((1 << alphaBits) - 1);
387             }
388 
389             const float tols[4] = {tol, tol, tol, alphaTol};
390             auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
391                                                                         const float diffs[4]) {
392                 SkASSERT(x >= 0 && y >= 0);
393                 ERRORF(reporter,
394                        "%sSrc CT: %s, Src AT: %s, Read CT: %s, Read AT: %s, Rect [%d, %d, %d, %d]"
395                        ", CS conversion: %d\n"
396                        "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
397                        label.c_str(),
398                        ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
399                        ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
400                        rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion, x, y,
401                        diffs[0], diffs[1], diffs[2], diffs[3]);
402             });
403             SkAutoPixmapStorage ref;
404             SkImageInfo refInfo = readInfo.makeDimensions(dstWriteRect.size());
405             ref.alloc(refInfo);
406             if (readAT == kUnknown_SkAlphaType) {
407                 // Do a spoofed read where src and dst alpha type are both kUnpremul. This will
408                 // allow SkPixmap readPixels to succeed and won't do any alpha type conversion.
409                 SkPixmap unpremulRef(refInfo.makeAlphaType(kUnpremul_SkAlphaType),
410                                      ref.addr(),
411                                      ref.rowBytes());
412                 SkPixmap unpremulSRc(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
413                                      srcPixels.addr(),
414                                      srcPixels.rowBytes());
415 
416                 unpremulSRc.readPixels(unpremulRef, srcReadRect.x(), srcReadRect.y());
417             } else {
418                 srcPixels.readPixels(ref, srcReadRect.x(), srcReadRect.y());
419             }
420             // This is the part of dstPixels that should have been updated.
421             SkPixmap actual;
422             SkAssertResult(dstPixels.extractSubset(&actual, dstWriteRect));
423             ComparePixels(ref, actual, tols, error);
424 
425             const auto* v = dstData.get();
426             const auto* end = dstData.get() + dstSize;
427             guardOk = std::all_of(v, v + dstWriteRect.top() * dstPixels.rowBytes(), guardCheck);
428             v += dstWriteRect.top() * dstPixels.rowBytes();
429             for (int y = dstWriteRect.top(); y < dstWriteRect.bottom(); ++y) {
430                 guardOk |= std::all_of(v, v + dstWriteRect.left() * readBpp, guardCheck);
431                 auto pad = v + dstWriteRect.right() * readBpp;
432                 auto rowEnd = std::min(end, v + dstPixels.rowBytes());
433                 // min protects against reading past the end of the tight last row.
434                 guardOk |= std::all_of(pad, rowEnd, guardCheck);
435                 v = rowEnd;
436             }
437             guardOk |= std::all_of(v, end, guardCheck);
438         } else {
439             guardOk = std::all_of(dstData.get(), dstData.get() + dstSize, guardCheck);
440         }
441         if (!guardOk) {
442             ERRORF(reporter,
443                    "Result pixels modified result outside read rect [%d, %d, %d, %d]. "
444                    "%sSrc CT: %s, Read CT: %s, CS conversion: %d",
445                    rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, label.c_str(),
446                    ToolUtils::colortype_name(srcCT), ToolUtils::colortype_name(readCT),
447                    csConversion);
448         }
449         return result;
450     };
451 
452     static constexpr int kW = 16;
453     static constexpr int kH = 16;
454 
455     const std::vector<SkIRect> longRectArray = make_long_rect_array(kW, kH);
456     const std::vector<SkIRect> shortRectArray = make_short_rect_array(kW, kH);
457 
458     // We ensure we use the long array once per src and read color type and otherwise use the
459     // short array to improve test run time.
460     // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
461     // equivalent. Just ensure each redundant AT is tested once with each CT (src and read).
462     // Similarly, alpha-only color types behave the same for all alpha types so just test premul
463     // after one iter.
464     // We consider a src or read CT thoroughly tested once it has run through the long rect array
465     // and full complement of alpha types with one successful read in the loop.
466     std::array<bool, kLastEnum_SkColorType + 1> srcCTTestedThoroughly  = {},
467                                                 readCTTestedThoroughly = {};
468     for (int sat = 0; sat <= kLastEnum_SkAlphaType; ++sat) {
469         const auto srcAT = static_cast<SkAlphaType>(sat);
470         if (srcAT == kUnpremul_SkAlphaType && !rules.fAllowUnpremulSrc) {
471             continue;
472         }
473         for (int sct = 0; sct <= kLastEnum_SkColorType; ++sct) {
474             const auto srcCT = static_cast<SkColorType>(sct);
475             if (rules.fSkipSRGBCT && srcCT == kSRGBA_8888_SkColorType) {
476                 continue;
477             }
478             if (rules.fSkip16BitCT &&
479                 (srcCT == kR16G16_unorm_SkColorType ||
480                  srcCT == kR16G16B16A16_unorm_SkColorType)) {
481                 continue;
482             }
483 
484             // We always make our ref data as F32
485             auto refInfo = SkImageInfo::Make(kW, kH,
486                                              kRGBA_F32_SkColorType,
487                                              srcAT,
488                                              SkColorSpace::MakeSRGB());
489             // 1010102 formats have an issue where it's easy to make a resulting
490             // color where r, g, or b is greater than a. CPU/GPU differ in whether the stored color
491             // channels are clipped to the alpha value. CPU clips but GPU does not.
492             // Note that we only currently use srcCT for the 1010102 workaround. If we remove this
493             // we can also put the ref data setup above the srcCT loop.
494             bool forceOpaque = srcAT == kPremul_SkAlphaType &&
495                     (srcCT == kRGBA_1010102_SkColorType || srcCT == kBGRA_1010102_SkColorType);
496 
497             SkAutoPixmapStorage refPixels = make_ref_data(refInfo, forceOpaque);
498             // Convert the ref data to our desired src color type.
499             const auto srcInfo = SkImageInfo::Make(kW, kH, srcCT, srcAT, SkColorSpace::MakeSRGB());
500             SkAutoPixmapStorage srcPixels;
501             srcPixels.alloc(srcInfo);
502             {
503                 SkPixmap readPixmap = srcPixels;
504                 // Spoof the alpha type to kUnpremul so the read will succeed without doing any
505                 // conversion (because we made our surface also use kUnpremul).
506                 if (srcAT == kUnknown_SkAlphaType) {
507                     readPixmap.reset(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
508                                      srcPixels.addr(),
509                                      srcPixels.rowBytes());
510                 }
511                 refPixels.readPixels(readPixmap, 0, 0);
512             }
513 
514             auto src = srcFactory(srcPixels);
515             if (!src) {
516                 continue;
517             }
518             if (SkColorTypeIsAlwaysOpaque(srcCT) && srcCTTestedThoroughly[srcCT] &&
519                 (kPremul_SkAlphaType == srcAT || kUnpremul_SkAlphaType == srcAT)) {
520                 continue;
521             }
522             if (SkColorTypeIsAlphaOnly(srcCT) && srcCTTestedThoroughly[srcCT] &&
523                 (kUnpremul_SkAlphaType == srcAT ||
524                  kOpaque_SkAlphaType   == srcAT ||
525                  kUnknown_SkAlphaType  == srcAT)) {
526                 continue;
527             }
528             for (int rct = 0; rct <= kLastEnum_SkColorType; ++rct) {
529                 const auto readCT = static_cast<SkColorType>(rct);
530                 for (const sk_sp<SkColorSpace>& readCS :
531                      {SkColorSpace::MakeSRGB(), SkColorSpace::MakeSRGBLinear()}) {
532                     for (int at = 0; at <= kLastEnum_SkAlphaType; ++at) {
533                         const auto readAT = static_cast<SkAlphaType>(at);
534                         if (srcAT != kOpaque_SkAlphaType && readAT == kOpaque_SkAlphaType) {
535                             // This doesn't make sense.
536                             continue;
537                         }
538                         if (SkColorTypeIsAlwaysOpaque(readCT) && readCTTestedThoroughly[readCT] &&
539                             (kPremul_SkAlphaType == readAT || kUnpremul_SkAlphaType == readAT)) {
540                             continue;
541                         }
542                         if (SkColorTypeIsAlphaOnly(readCT) && readCTTestedThoroughly[readCT] &&
543                             (kUnpremul_SkAlphaType == readAT ||
544                              kOpaque_SkAlphaType   == readAT ||
545                              kUnknown_SkAlphaType  == readAT)) {
546                             continue;
547                         }
548                         const auto& rects =
549                                 srcCTTestedThoroughly[sct] && readCTTestedThoroughly[rct]
550                                         ? shortRectArray
551                                         : longRectArray;
552                         for (const auto& rect : rects) {
553                             const auto readInfo = SkImageInfo::Make(rect.width(), rect.height(),
554                                                                     readCT, readAT, readCS);
555                             const SkIPoint offset = rect.topLeft();
556                             Result r = runTest(src, srcPixels, readInfo, offset);
557                             if (r == Result::kSuccess) {
558                                 srcCTTestedThoroughly[sct] = true;
559                                 readCTTestedThoroughly[rct] = true;
560                             }
561                         }
562                     }
563                 }
564             }
565         }
566     }
567 }
568 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextReadPixels,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)569 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextReadPixels,
570                                        reporter,
571                                        ctxInfo,
572                                        CtsEnforcement::kApiLevel_T) {
573     using Surface = std::unique_ptr<skgpu::ganesh::SurfaceContext>;
574     GrDirectContext* direct = ctxInfo.directContext();
575     auto reader = std::function<GpuReadSrcFn<Surface>>(
576             [direct](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
577                 if (surface->readPixels(direct, pixels, offset)) {
578                     return Result::kSuccess;
579                 } else {
580                     // Reading from a non-renderable format is not guaranteed to work on GL.
581                     // We'd have to be able to force a copy or draw to a renderable format.
582                     const auto& caps = *direct->priv().caps();
583                     if (direct->backend() == GrBackendApi::kOpenGL &&
584                         !caps.isFormatRenderable(surface->asSurfaceProxy()->backendFormat(), 1)) {
585                         return Result::kExcusedFailure;
586                     }
587                     return Result::kFail;
588                 }
589             });
590     GpuReadPixelTestRules rules;
591     rules.fAllowUnpremulSrc = true;
592     rules.fUncontainedRectSucceeds = true;
593 
594     for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
595         for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
596             auto factory = std::function<GpuSrcFactory<Surface>>(
597                     [direct, origin, renderable](const SkPixmap& src) {
598                         auto sc = CreateSurfaceContext(
599                                 direct, src.info(), SkBackingFit::kExact, origin, renderable);
600                         if (sc) {
601                             sc->writePixels(direct, src, {0, 0});
602                         }
603                         return sc;
604                     });
605             auto label = SkStringPrintf("Renderable: %d, Origin: %d", (int)renderable, origin);
606             gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
607         }
608     }
609 }
610 
DEF_GANESH_TEST_FOR_ALL_CONTEXTS(ReadPixels_InvalidRowBytes_Gpu,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)611 DEF_GANESH_TEST_FOR_ALL_CONTEXTS(ReadPixels_InvalidRowBytes_Gpu,
612                                  reporter,
613                                  ctxInfo,
614                                  CtsEnforcement::kApiLevel_T) {
615     auto srcII = SkImageInfo::Make({10, 10}, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
616     auto surf = SkSurfaces::RenderTarget(ctxInfo.directContext(), skgpu::Budgeted::kYes, srcII);
617     for (int ct = 0; ct < kLastEnum_SkColorType + 1; ++ct) {
618         auto colorType = static_cast<SkColorType>(ct);
619         size_t bpp = SkColorTypeBytesPerPixel(colorType);
620         if (bpp <= 1) {
621             continue;
622         }
623         auto dstII = srcII.makeColorType(colorType);
624         size_t badRowBytes = (surf->width() + 1)*bpp - 1;
625         auto storage = std::make_unique<char[]>(badRowBytes*surf->height());
626         REPORTER_ASSERT(reporter, !surf->readPixels(dstII, storage.get(), badRowBytes, 0, 0));
627     }
628 }
629 
DEF_GANESH_TEST_FOR_ALL_CONTEXTS(WritePixels_InvalidRowBytes_Gpu,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)630 DEF_GANESH_TEST_FOR_ALL_CONTEXTS(WritePixels_InvalidRowBytes_Gpu,
631                                  reporter,
632                                  ctxInfo,
633                                  CtsEnforcement::kApiLevel_T) {
634     auto dstII = SkImageInfo::Make({10, 10}, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
635     auto surf = SkSurfaces::RenderTarget(ctxInfo.directContext(), skgpu::Budgeted::kYes, dstII);
636     for (int ct = 0; ct < kLastEnum_SkColorType + 1; ++ct) {
637         auto colorType = static_cast<SkColorType>(ct);
638         size_t bpp = SkColorTypeBytesPerPixel(colorType);
639         if (bpp <= 1) {
640             continue;
641         }
642         auto srcII = dstII.makeColorType(colorType);
643         size_t badRowBytes = (surf->width() + 1)*bpp - 1;
644         auto storage = std::make_unique<char[]>(badRowBytes*surf->height());
645         memset(storage.get(), 0, badRowBytes * surf->height());
646         // SkSurface::writePixels doesn't report bool, SkCanvas's does.
647         REPORTER_ASSERT(reporter,
648                         !surf->getCanvas()->writePixels(srcII, storage.get(), badRowBytes, 0, 0));
649     }
650 }
651 
652 namespace {
653 struct AsyncContext {
654     bool fCalled = false;
655     std::unique_ptr<const SkImage::AsyncReadResult> fResult;
656 };
657 }  // anonymous namespace
658 
659 // Making this a lambda in the test functions caused:
660 //   "error: cannot compile this forwarded non-trivially copyable parameter yet"
661 // on x86/Win/Clang bot, referring to 'result'.
async_callback(void * c,std::unique_ptr<const SkImage::AsyncReadResult> result)662 static void async_callback(void* c, std::unique_ptr<const SkImage::AsyncReadResult> result) {
663     auto context = static_cast<AsyncContext*>(c);
664     context->fResult = std::move(result);
665     context->fCalled = true;
666 }
667 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixels,reporter,ctxInfo,CtsEnforcement::kApiLevel_V)668 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixels,
669                                        reporter,
670                                        ctxInfo,
671                                        CtsEnforcement::kApiLevel_V) {
672     using Surface = sk_sp<SkSurface>;
673     auto reader = std::function<GpuReadSrcFn<Surface>>(
674             [](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
675                 auto direct = surface->recordingContext()->asDirectContext();
676                 SkASSERT(direct);
677 
678                 AsyncContext context;
679                 auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
680 
681                 // Rescale quality and linearity don't matter since we're doing a non-scaling
682                 // readback.
683                 surface->asyncRescaleAndReadPixels(pixels.info(), rect,
684                                                    SkImage::RescaleGamma::kSrc,
685                                                    SkImage::RescaleMode::kNearest,
686                                                    async_callback, &context);
687                 direct->submit();
688                 while (!context.fCalled) {
689                     direct->checkAsyncWorkCompletion();
690                 }
691                 if (!context.fResult) {
692                     return Result::kFail;
693                 }
694                 SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), context.fResult->data(0),
695                              context.fResult->rowBytes(0), pixels.info().minRowBytes(),
696                              pixels.height());
697                 return Result::kSuccess;
698             });
699     GpuReadPixelTestRules rules;
700     rules.fAllowUnpremulSrc = false;
701     rules.fUncontainedRectSucceeds = false;
702     // TODO: some mobile GPUs have issues reading back sRGB src data with GLES -- skip for now
703     // b/296440036
704     if (ctxInfo.type() == skgpu::ContextType::kGLES) {
705         rules.fSkipSRGBCT = true;
706     }
707 
708     for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
709         auto factory = std::function<GpuSrcFactory<Surface>>(
710                 [context = ctxInfo.directContext(), origin](const SkPixmap& src) {
711                     auto surf = SkSurfaces::RenderTarget(
712                             context, skgpu::Budgeted::kYes, src.info(), 1, origin, nullptr);
713                     if (surf) {
714                         surf->writePixels(src, 0, 0);
715                     }
716                     return surf;
717                 });
718         auto label = SkStringPrintf("Origin: %d", origin);
719         gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
720         auto backendRTFactory = std::function<GpuSrcFactory<Surface>>(
721                 [context = ctxInfo.directContext(), origin](const SkPixmap& src) {
722                     auto surf = sk_gpu_test::MakeBackendRenderTargetSurface(context,
723                                                                             src.info(),
724                                                                             origin,
725                                                                             1);
726                     if (surf) {
727                         surf->writePixels(src, 0, 0);
728                     }
729                     return surf;
730                 });
731         label = SkStringPrintf("BERT Origin: %d", origin);
732         gpu_read_pixels_test_driver(reporter, rules, backendRTFactory, reader, label);
733     }
734 }
735 
736 // Manually parameterized by GrRenderable and GrSurfaceOrigin to reduce per-test run time.
image_async_read_pixels(GrRenderable renderable,GrSurfaceOrigin origin,skiatest::Reporter * reporter,const sk_gpu_test::ContextInfo & ctxInfo)737 static void image_async_read_pixels(GrRenderable renderable,
738                                     GrSurfaceOrigin origin,
739                                     skiatest::Reporter* reporter,
740                                     const sk_gpu_test::ContextInfo& ctxInfo) {
741     using Image = sk_sp<SkImage>;
742     auto context = ctxInfo.directContext();
743     auto reader = std::function<GpuReadSrcFn<Image>>([context](const Image& image,
744                                                                const SkIPoint& offset,
745                                                                const SkPixmap& pixels) {
746         AsyncContext asyncContext;
747         auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
748         // The GPU implementation is based on rendering and will fail for non-renderable color
749         // types.
750         auto ct = SkColorTypeToGrColorType(image->colorType());
751         auto format = context->priv().caps()->getDefaultBackendFormat(ct, GrRenderable::kYes);
752         if (!context->priv().caps()->isFormatAsColorTypeRenderable(ct, format)) {
753             return Result::kExcusedFailure;
754         }
755 
756         // Rescale quality and linearity don't matter since we're doing a non-scaling readback.
757         image->asyncRescaleAndReadPixels(pixels.info(), rect,
758                                          SkImage::RescaleGamma::kSrc,
759                                          SkImage::RescaleMode::kNearest,
760                                          async_callback, &asyncContext);
761         context->submit();
762         while (!asyncContext.fCalled) {
763             context->checkAsyncWorkCompletion();
764         }
765         if (!asyncContext.fResult) {
766             return Result::kFail;
767         }
768         SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), asyncContext.fResult->data(0),
769                      asyncContext.fResult->rowBytes(0), pixels.info().minRowBytes(),
770                      pixels.height());
771         return Result::kSuccess;
772     });
773 
774     GpuReadPixelTestRules rules;
775     rules.fAllowUnpremulSrc = true;
776     rules.fUncontainedRectSucceeds = false;
777     // TODO: some mobile GPUs have issues reading back sRGB src data with GLES -- skip for now
778     // b/296440036
779     if (ctxInfo.type() == skgpu::ContextType::kGLES) {
780         rules.fSkipSRGBCT = true;
781     }
782     // TODO: D3D on Intel has issues reading back 16-bit src data -- skip for now
783     // b/296440036
784     if (ctxInfo.type() == skgpu::ContextType::kDirect3D) {
785         rules.fSkip16BitCT = true;
786     }
787 
788     auto factory = std::function<GpuSrcFactory<Image>>([&](const SkPixmap& src) {
789         return sk_gpu_test::MakeBackendTextureImage(ctxInfo.directContext(), src,
790                                                     renderable, origin,
791                                                     GrProtected::kNo);
792     });
793     auto label = SkStringPrintf("Renderable: %d, Origin: %d", (int)renderable, origin);
794     gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
795 }
796 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_NonRenderable_TopLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_V)797 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_NonRenderable_TopLeft,
798                                        reporter,
799                                        ctxInfo,
800                                        CtsEnforcement::kApiLevel_V) {
801     image_async_read_pixels(GrRenderable::kNo, GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
802                             reporter, ctxInfo);
803 }
804 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_NonRenderable_BottomLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_V)805 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_NonRenderable_BottomLeft,
806                                        reporter,
807                                        ctxInfo,
808                                        CtsEnforcement::kApiLevel_V) {
809     image_async_read_pixels(GrRenderable::kNo, GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin,
810                             reporter, ctxInfo);
811 }
812 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_Renderable_TopLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_V)813 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_Renderable_TopLeft,
814                                        reporter,
815                                        ctxInfo,
816                                        CtsEnforcement::kApiLevel_V) {
817     image_async_read_pixels(GrRenderable::kYes, GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
818                             reporter, ctxInfo);
819 }
820 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_Renderable_BottomLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_V)821 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels_Renderable_BottomLeft,
822                                        reporter,
823                                        ctxInfo,
824                                        CtsEnforcement::kApiLevel_V) {
825     image_async_read_pixels(GrRenderable::kYes, GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin,
826                             reporter, ctxInfo);
827 }
828 
DEF_GANESH_TEST(AsyncReadPixelsContextShutdown,reporter,options,CtsEnforcement::kApiLevel_T)829 DEF_GANESH_TEST(AsyncReadPixelsContextShutdown, reporter, options, CtsEnforcement::kApiLevel_T) {
830     const auto ii = SkImageInfo::Make(10, 10, kRGBA_8888_SkColorType, kPremul_SkAlphaType,
831                                       SkColorSpace::MakeSRGB());
832     enum class ShutdownSequence {
833         kFreeResult_DestroyContext,
834         kDestroyContext_FreeResult,
835         kFreeResult_ReleaseAndAbandon_DestroyContext,
836         kFreeResult_Abandon_DestroyContext,
837         kReleaseAndAbandon_FreeResult_DestroyContext,
838         kAbandon_FreeResult_DestroyContext,
839         kReleaseAndAbandon_DestroyContext_FreeResult,
840         kAbandon_DestroyContext_FreeResult,
841     };
842     for (int t = 0; t < skgpu::kContextTypeCount; ++t) {
843         auto type = static_cast<skgpu::ContextType>(t);
844         for (auto sequence : {ShutdownSequence::kFreeResult_DestroyContext,
845                               ShutdownSequence::kDestroyContext_FreeResult,
846                               ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext,
847                               ShutdownSequence::kFreeResult_Abandon_DestroyContext,
848                               ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext,
849                               ShutdownSequence::kAbandon_FreeResult_DestroyContext,
850                               ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult,
851                               ShutdownSequence::kAbandon_DestroyContext_FreeResult}) {
852             // Vulkan and D3D context abandoning without resource release has issues outside of the
853             // scope of this test.
854             if ((type == skgpu::ContextType::kVulkan || type == skgpu::ContextType::kDirect3D) &&
855                 (sequence == ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext ||
856                  sequence == ShutdownSequence::kFreeResult_Abandon_DestroyContext ||
857                  sequence == ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext ||
858                  sequence == ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult ||
859                  sequence == ShutdownSequence::kAbandon_FreeResult_DestroyContext ||
860                  sequence == ShutdownSequence::kAbandon_DestroyContext_FreeResult)) {
861                 continue;
862             }
863             enum class ReadType {
864                 kRGBA,
865                 kYUV,
866                 kYUVA
867             };
868             for (ReadType readType : {ReadType::kRGBA, ReadType::kYUV, ReadType::kYUVA}) {
869                 sk_gpu_test::GrContextFactory factory(options);
870                 auto direct = factory.get(type);
871                 if (!direct) {
872                     continue;
873                 }
874                 // This test is only meaningful for contexts that support transfer buffers for
875                 // reads.
876                 if (!direct->priv().caps()->transferFromSurfaceToBufferSupport()) {
877                     continue;
878                 }
879                 auto surf = SkSurfaces::RenderTarget(direct, skgpu::Budgeted::kYes, ii, 1, nullptr);
880                 if (!surf) {
881                     continue;
882                 }
883                 AsyncContext cbContext;
884                 switch (readType) {
885                     case ReadType::kRGBA:
886                         surf->asyncRescaleAndReadPixels(ii, ii.bounds(),
887                                                         SkImage::RescaleGamma::kSrc,
888                                                         SkImage::RescaleMode::kNearest,
889                                                         &async_callback, &cbContext);
890                         break;
891                     case ReadType::kYUV:
892                         surf->asyncRescaleAndReadPixelsYUV420(
893                                 kIdentity_SkYUVColorSpace, SkColorSpace::MakeSRGB(), ii.bounds(),
894                                 ii.dimensions(), SkImage::RescaleGamma::kSrc,
895                                 SkImage::RescaleMode::kNearest, &async_callback, &cbContext);
896                         break;
897                     case ReadType::kYUVA:
898                         surf->asyncRescaleAndReadPixelsYUVA420(
899                                 kIdentity_SkYUVColorSpace, SkColorSpace::MakeSRGB(), ii.bounds(),
900                                 ii.dimensions(), SkImage::RescaleGamma::kSrc,
901                                 SkImage::RescaleMode::kNearest, &async_callback, &cbContext);
902                         break;
903                 }
904 
905                 direct->submit();
906                 while (!cbContext.fCalled) {
907                     direct->checkAsyncWorkCompletion();
908                 }
909                 if (!cbContext.fResult) {
910                     const char* readTypeStr;
911                     switch (readType) {
912                         case ReadType::kRGBA: readTypeStr = "rgba"; break;
913                         case ReadType::kYUV:  readTypeStr = "yuv";  break;
914                         case ReadType::kYUVA: readTypeStr = "yuva"; break;
915                     }
916                     ERRORF(reporter, "Callback failed on %s. read type is: %s",
917                            skgpu::ContextTypeName(type), readTypeStr);
918                     continue;
919                 }
920                 // For vulkan we need to release all refs to the GrDirectContext before trying to
921                 // destroy the test context. The surface here is holding a ref.
922                 surf.reset();
923 
924                 // The real test is that we don't crash, get Vulkan validation errors, etc, during
925                 // this shutdown sequence.
926                 switch (sequence) {
927                     case ShutdownSequence::kFreeResult_DestroyContext:
928                     case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
929                     case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
930                         break;
931                     case ShutdownSequence::kDestroyContext_FreeResult:
932                         factory.destroyContexts();
933                         break;
934                     case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
935                         factory.releaseResourcesAndAbandonContexts();
936                         break;
937                     case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
938                         factory.abandonContexts();
939                         break;
940                     case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
941                         factory.releaseResourcesAndAbandonContexts();
942                         factory.destroyContexts();
943                         break;
944                     case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
945                         factory.abandonContexts();
946                         factory.destroyContexts();
947                         break;
948                 }
949                 cbContext.fResult.reset();
950                 switch (sequence) {
951                     case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
952                         factory.releaseResourcesAndAbandonContexts();
953                         break;
954                     case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
955                         factory.abandonContexts();
956                         break;
957                     case ShutdownSequence::kFreeResult_DestroyContext:
958                     case ShutdownSequence::kDestroyContext_FreeResult:
959                     case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
960                     case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
961                     case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
962                     case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
963                         break;
964                 }
965             }
966         }
967     }
968 }
969 
970 template <typename T>
gpu_write_pixels_test_driver(skiatest::Reporter * reporter,const std::function<GpuDstFactory<T>> & dstFactory,const std::function<GpuWriteDstFn<T>> & write,const std::function<GpuReadDstFn<T>> & read)971 static void gpu_write_pixels_test_driver(skiatest::Reporter* reporter,
972                                          const std::function<GpuDstFactory<T>>& dstFactory,
973                                          const std::function<GpuWriteDstFn<T>>& write,
974                                          const std::function<GpuReadDstFn<T>>& read) {
975     // Separate this out just to give it some line width to breathe.
976     auto runTest = [&](const T& dst,
977                        const SkImageInfo& dstInfo,
978                        const SkPixmap& srcPixels,
979                        SkIPoint offset) {
980         const bool csConversion =
981                 !SkColorSpace::Equals(dstInfo.colorSpace(), srcPixels.info().colorSpace());
982         const auto writeCT = srcPixels.colorType();
983         const auto writeAT = srcPixels.alphaType();
984         const auto dstCT = dstInfo.colorType();
985         const auto dstAT = dstInfo.alphaType();
986         const auto rect = SkIRect::MakePtSize(offset, srcPixels.dimensions());
987         const auto surfBounds = SkIRect::MakeSize(dstInfo.dimensions());
988 
989         // Do an initial read before the write.
990         SkAutoPixmapStorage firstReadPM = read(dst);
991         if (!firstReadPM.addr()) {
992             // Particularly with GLES 2 we can have formats that are unreadable with our current
993             // implementation of read pixels. If the format can't be attached to a FBO we don't have
994             // a code path that draws it to another readable color type/format combo and reads from
995             // that.
996             return Result::kExcusedFailure;
997         }
998 
999         const Result result = write(dst, offset, srcPixels);
1000 
1001         if (!SkIRect::Intersects(rect, surfBounds)) {
1002             REPORTER_ASSERT(reporter, result != Result::kSuccess);
1003         } else if (writeCT == kUnknown_SkColorType) {
1004             REPORTER_ASSERT(reporter, result != Result::kSuccess);
1005         } else if ((writeAT == kUnknown_SkAlphaType) != (dstAT == kUnknown_SkAlphaType)) {
1006             REPORTER_ASSERT(reporter, result != Result::kSuccess);
1007         } else if (result == Result::kExcusedFailure) {
1008             return result;
1009         } else if (result == Result::kFail) {
1010             // TODO: Support RGB/BGR 101010x, BGRA 1010102 on the GPU.
1011             if (SkColorTypeToGrColorType(writeCT) != GrColorType::kUnknown) {
1012                 ERRORF(reporter,
1013                        "Write failed. Write CT: %s, Write AT: %s Dst CT: %s, Dst AT: %s, "
1014                        "Rect [%d, %d, %d, %d], CS conversion: %d\n",
1015                        ToolUtils::colortype_name(writeCT), ToolUtils::alphatype_name(writeAT),
1016                        ToolUtils::colortype_name(dstCT), ToolUtils::alphatype_name(dstAT),
1017                        rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
1018             }
1019             return result;
1020         }
1021 
1022         SkIRect checkRect;
1023         if (result != Result::kSuccess || !checkRect.intersect(surfBounds, rect)) {
1024             return result;
1025         }
1026 
1027         // Do an initial read before the write. We'll use this to verify that areas outside the
1028         // write are unaffected.
1029         SkAutoPixmapStorage secondReadPM = read(dst);
1030         if (!secondReadPM.addr()) {
1031             // The first read succeeded so this one should, too.
1032             ERRORF(reporter,
1033                    "could not read from dst (CT: %s, AT: %s)\n",
1034                    ToolUtils::colortype_name(dstCT),
1035                    ToolUtils::alphatype_name(dstAT));
1036             return Result::kFail;
1037         }
1038 
1039         // Sometimes wider types go through 8bit unorm intermediates because of API
1040         // restrictions.
1041         int rgbBits = std::min({min_rgb_channel_bits(writeCT), min_rgb_channel_bits(dstCT), 8});
1042         float tol = (rgbBits == 0) ? 1.f : 2.f / ((1 << rgbBits) - 1);
1043         float alphaTol = 0;
1044         if (writeAT != kOpaque_SkAlphaType && dstAT != kOpaque_SkAlphaType) {
1045             // Alpha can also get squashed down to 8 bits going through an intermediate
1046             // color format.
1047             const int alphaBits = std::min({alpha_channel_bits(writeCT),
1048                                             alpha_channel_bits(dstCT),
1049                                             8});
1050             alphaTol = (alphaBits == 0) ? 1.f : 2.f / ((1 << alphaBits) - 1);
1051         }
1052 
1053         const float tols[4] = {tol, tol, tol, alphaTol};
1054         auto error = std::function<ComparePixmapsErrorReporter>([&](int x,
1055                                                                     int y,
1056                                                                     const float diffs[4]) {
1057             SkASSERT(x >= 0 && y >= 0);
1058             ERRORF(reporter,
1059                    "Write CT: %s, Write AT: %s, Dst CT: %s, Dst AT: %s, Rect [%d, %d, %d, %d]"
1060                    ", CS conversion: %d\n"
1061                    "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
1062                    ToolUtils::colortype_name(writeCT),
1063                    ToolUtils::alphatype_name(writeAT),
1064                    ToolUtils::colortype_name(dstCT),
1065                    ToolUtils::alphatype_name(dstAT),
1066                    rect.fLeft,
1067                    rect.fTop,
1068                    rect.fRight,
1069                    rect.fBottom,
1070                    csConversion,
1071                    x,
1072                    y,
1073                    diffs[0],
1074                    diffs[1],
1075                    diffs[2],
1076                    diffs[3]);
1077         });
1078 
1079         SkAutoPixmapStorage ref;
1080         ref.alloc(secondReadPM.info().makeDimensions(checkRect.size()));
1081         // Here we use the CPU backend to do the equivalent conversion as the write we're
1082         // testing, using kUnpremul instead of kUnknown since CPU requires a valid alpha type.
1083         SkAssertResult(make_pixmap_have_valid_alpha_type(srcPixels).readPixels(
1084                 make_pixmap_have_valid_alpha_type(ref),
1085                 std::max(0, -offset.fX),
1086                 std::max(0, -offset.fY)));
1087         // This is the part of secondReadPixels that should have been updated by the write.
1088         SkPixmap actual;
1089         SkAssertResult(secondReadPM.extractSubset(&actual, checkRect));
1090         ComparePixels(ref, actual, tols, error);
1091         // The area around written rect should be the same in the first and second read.
1092         SkIRect borders[]{
1093                 {               0,                 0, secondReadPM.width(), secondReadPM.height()},
1094                 {checkRect.fRight,                 0,      checkRect.fLeft, secondReadPM.height()},
1095                 { checkRect.fLeft,                 0,     checkRect.fRight,        checkRect.fTop},
1096                 { checkRect.fLeft, checkRect.fBottom,     checkRect.fRight, secondReadPM.height()}
1097         };
1098         for (const auto r : borders) {
1099             if (!r.isEmpty()) {
1100                 // Make a copy because MSVC for some reason doesn't correctly capture 'r'.
1101                 SkIPoint tl = r.topLeft();
1102                 auto guardError = std::function<ComparePixmapsErrorReporter>(
1103                         [&](int x, int y, const float diffs[4]) {
1104                             x += tl.x();
1105                             y += tl.y();
1106                             ERRORF(reporter,
1107                                    "Write CT: %s, Write AT: %s, Dst CT: %s, Dst AT: %s,"
1108                                    "Rect [%d, %d, %d, %d], CS conversion: %d\n"
1109                                    "Error in guard region %d, %d. Diff in floats: (%f, %f, %f, %f)",
1110                                    ToolUtils::colortype_name(writeCT),
1111                                    ToolUtils::alphatype_name(writeAT),
1112                                    ToolUtils::colortype_name(dstCT),
1113                                    ToolUtils::alphatype_name(dstAT),
1114                                    rect.fLeft,
1115                                    rect.fTop,
1116                                    rect.fRight,
1117                                    rect.fBottom,
1118                                    csConversion,
1119                                    x,
1120                                    y,
1121                                    diffs[0],
1122                                    diffs[1],
1123                                    diffs[2],
1124                                    diffs[3]);
1125                         });
1126                 SkPixmap a, b;
1127                 SkAssertResult(firstReadPM.extractSubset(&a, r));
1128                 SkAssertResult(firstReadPM.extractSubset(&b, r));
1129                 float zeroTols[4] = {};
1130                 ComparePixels(a, b, zeroTols, guardError);
1131             }
1132         }
1133         return result;
1134     };
1135 
1136     static constexpr int kW = 16;
1137     static constexpr int kH = 16;
1138 
1139     const std::vector<SkIRect> longRectArray = make_long_rect_array(kW, kH);
1140     const std::vector<SkIRect> shortRectArray = make_short_rect_array(kW, kH);
1141 
1142     // We ensure we use the long array once per src and read color type and otherwise use the
1143     // short array to improve test run time.
1144     // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
1145     // equivalent. Just ensure each redundant AT is tested once with each CT (dst and write).
1146     // Similarly, alpha-only color types behave the same for all alpha types so just test premul
1147     // after one iter.
1148     // We consider a dst or write CT thoroughly tested once it has run through the long rect array
1149     // and full complement of alpha types with one successful read in the loop.
1150     std::array<bool, kLastEnum_SkColorType + 1> dstCTTestedThoroughly   = {},
1151                                                 writeCTTestedThoroughly = {};
1152     for (int dat = 0; dat < kLastEnum_SkAlphaType; ++dat) {
1153         const auto dstAT = static_cast<SkAlphaType>(dat);
1154         for (int dct = 0; dct <= kLastEnum_SkColorType; ++dct) {
1155             const auto dstCT = static_cast<SkColorType>(dct);
1156             const auto dstInfo = SkImageInfo::Make(kW, kH, dstCT, dstAT, SkColorSpace::MakeSRGB());
1157             auto dst = dstFactory(dstInfo);
1158             if (!dst) {
1159                 continue;
1160             }
1161             if (SkColorTypeIsAlwaysOpaque(dstCT) && dstCTTestedThoroughly[dstCT] &&
1162                 (kPremul_SkAlphaType == dstAT || kUnpremul_SkAlphaType == dstAT)) {
1163                 continue;
1164             }
1165             if (SkColorTypeIsAlphaOnly(dstCT) && dstCTTestedThoroughly[dstCT] &&
1166                 (kUnpremul_SkAlphaType == dstAT ||
1167                  kOpaque_SkAlphaType   == dstAT ||
1168                  kUnknown_SkAlphaType  == dstAT)) {
1169                 continue;
1170             }
1171             for (int wct = 0; wct <= kLastEnum_SkColorType; ++wct) {
1172                 const auto writeCT = static_cast<SkColorType>(wct);
1173                 for (const sk_sp<SkColorSpace>& writeCS : {SkColorSpace::MakeSRGB(),
1174                                                            SkColorSpace::MakeSRGBLinear()}) {
1175                     for (int wat = 0; wat <= kLastEnum_SkAlphaType; ++wat) {
1176                         const auto writeAT = static_cast<SkAlphaType>(wat);
1177                         if (writeAT != kOpaque_SkAlphaType && dstAT == kOpaque_SkAlphaType) {
1178                             // This doesn't make sense.
1179                             continue;
1180                         }
1181                         if (SkColorTypeIsAlwaysOpaque(writeCT) &&
1182                             writeCTTestedThoroughly[writeCT] &&
1183                             (kPremul_SkAlphaType == writeAT || kUnpremul_SkAlphaType == writeAT)) {
1184                             continue;
1185                         }
1186                         if (SkColorTypeIsAlphaOnly(writeCT) && writeCTTestedThoroughly[writeCT] &&
1187                             (kUnpremul_SkAlphaType == writeAT ||
1188                              kOpaque_SkAlphaType   == writeAT ||
1189                              kUnknown_SkAlphaType  == writeAT)) {
1190                             continue;
1191                         }
1192                         const auto& rects =
1193                                 dstCTTestedThoroughly[dct] && writeCTTestedThoroughly[wct]
1194                                         ? shortRectArray
1195                                         : longRectArray;
1196                         for (const auto& rect : rects) {
1197                             auto writeInfo = SkImageInfo::Make(rect.size(),
1198                                                                writeCT,
1199                                                                writeAT,
1200                                                                writeCS);
1201                             // CPU and GPU handle 1010102 differently. CPU clamps RGB to A, GPU
1202                             // doesn't.
1203                             bool forceOpaque = writeCT == kRGBA_1010102_SkColorType ||
1204                                                writeCT == kBGRA_1010102_SkColorType;
1205                             SkAutoPixmapStorage writePixels = make_ref_data(writeInfo, forceOpaque);
1206                             const SkIPoint offset = rect.topLeft();
1207                             Result r = runTest(dst, dstInfo, writePixels, offset);
1208                             if (r == Result::kSuccess) {
1209                                 dstCTTestedThoroughly[dct] = true;
1210                                 writeCTTestedThoroughly[wct] = true;
1211                             }
1212                         }
1213                     }
1214                 }
1215             }
1216         }
1217     }
1218 }
1219 
1220 // Manually parameterized by GrRenderable and GrSurfaceOrigin to reduce per-test run time.
surface_context_write_pixels(GrRenderable renderable,GrSurfaceOrigin origin,skiatest::Reporter * reporter,const sk_gpu_test::ContextInfo & ctxInfo)1221 static void surface_context_write_pixels(GrRenderable renderable,
1222                                          GrSurfaceOrigin origin,
1223                                          skiatest::Reporter* reporter,
1224                                          const sk_gpu_test::ContextInfo& ctxInfo) {
1225     using Surface = std::unique_ptr<skgpu::ganesh::SurfaceContext>;
1226     GrDirectContext* direct = ctxInfo.directContext();
1227     auto writer = std::function<GpuWriteDstFn<Surface>>(
1228             [direct](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
1229                 if (surface->writePixels(direct, pixels, offset)) {
1230                     return Result::kSuccess;
1231                 } else {
1232                     return Result::kFail;
1233                 }
1234             });
1235     auto reader = std::function<GpuReadDstFn<Surface>>([direct](const Surface& s) {
1236         SkAutoPixmapStorage result;
1237         auto grInfo = s->imageInfo();
1238         SkColorType ct = GrColorTypeToSkColorType(grInfo.colorType());
1239         SkASSERT(ct != kUnknown_SkColorType);
1240         auto skInfo = SkImageInfo::Make(grInfo.dimensions(), ct, grInfo.alphaType(),
1241                                         grInfo.refColorSpace());
1242         result.alloc(skInfo);
1243         if (!s->readPixels(direct, result, {0, 0})) {
1244             SkAutoPixmapStorage badResult;
1245             return badResult;
1246         }
1247         return result;
1248     });
1249 
1250     auto factory = std::function<GpuDstFactory<Surface>>(
1251             [direct, origin, renderable](const SkImageInfo& info) {
1252                 return CreateSurfaceContext(direct,
1253                                             info,
1254                                             SkBackingFit::kExact,
1255                                             origin,
1256                                             renderable);
1257             });
1258 
1259     gpu_write_pixels_test_driver(reporter, factory, writer, reader);
1260 }
1261 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_NonRenderable_TopLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1262 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_NonRenderable_TopLeft,
1263                                        reporter,
1264                                        ctxInfo,
1265                                        CtsEnforcement::kApiLevel_T) {
1266     surface_context_write_pixels(GrRenderable::kNo, GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
1267                                  reporter, ctxInfo);
1268 }
1269 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_NonRenderable_BottomLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1270 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_NonRenderable_BottomLeft,
1271                                        reporter,
1272                                        ctxInfo,
1273                                        CtsEnforcement::kApiLevel_T) {
1274     surface_context_write_pixels(GrRenderable::kNo, GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin,
1275                                  reporter, ctxInfo);
1276 }
1277 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_Renderable_TopLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1278 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_Renderable_TopLeft,
1279                                        reporter,
1280                                        ctxInfo,
1281                                        CtsEnforcement::kApiLevel_T) {
1282     surface_context_write_pixels(GrRenderable::kYes, GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
1283                                  reporter, ctxInfo);
1284 }
1285 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_Renderable_BottomLeft,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1286 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels_Renderable_BottomLeft,
1287                                        reporter,
1288                                        ctxInfo,
1289                                        CtsEnforcement::kApiLevel_T) {
1290     surface_context_write_pixels(GrRenderable::kYes, GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin,
1291                                  reporter, ctxInfo);
1292 }
1293 
DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixelsMipped,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1294 DEF_GANESH_TEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixelsMipped,
1295                                        reporter,
1296                                        ctxInfo,
1297                                        CtsEnforcement::kApiLevel_T) {
1298     auto direct = ctxInfo.directContext();
1299     if (!direct->priv().caps()->mipmapSupport()) {
1300         return;
1301     }
1302     static constexpr int kW = 25,
1303                          kH = 37;
1304     SkAutoPixmapStorage refP = make_ref_data(SkImageInfo::Make({kW, kH},
1305                                                                kRGBA_F32_SkColorType,
1306                                                                kPremul_SkAlphaType,
1307                                                                nullptr),
1308                                              false);
1309     SkAutoPixmapStorage refO = make_ref_data(SkImageInfo::Make({kW, kH},
1310                                                                kRGBA_F32_SkColorType,
1311                                                                kOpaque_SkAlphaType,
1312                                                                nullptr),
1313                                              true);
1314 
1315     for (int c = 0; c < kGrColorTypeCnt; ++c) {
1316         auto ct = static_cast<GrColorType>(c);
1317         // Below we use rendering to read the level pixels back.
1318         auto format = direct->priv().caps()->getDefaultBackendFormat(ct, GrRenderable::kYes);
1319         if (!format.isValid()) {
1320             continue;
1321         }
1322         SkAlphaType at = GrColorTypeHasAlpha(ct) ? kPremul_SkAlphaType : kOpaque_SkAlphaType;
1323         GrImageInfo info(ct, at, nullptr, kW, kH);
1324         TArray<GrCPixmap> levels;
1325         const auto& ref = at == kPremul_SkAlphaType ? refP : refO;
1326         for (int w = kW, h = kH; w || h; w/=2, h/=2) {
1327             auto level = GrPixmap::Allocate(info.makeWH(std::max(w, 1), std::max(h, 1)));
1328             SkPixmap src;
1329             SkAssertResult(ref.extractSubset(&src, SkIRect::MakeSize(level.dimensions())));
1330             SkAssertResult(GrConvertPixels(level, src));
1331             levels.push_back(level);
1332         }
1333 
1334         for (bool unowned : {false, true}) { // test a GrCPixmap that doesn't own its storage.
1335             for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
1336                 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin,
1337                                                kBottomLeft_GrSurfaceOrigin}) {
1338                     auto sc = CreateSurfaceContext(direct,
1339                                                    info,
1340                                                    SkBackingFit::kExact,
1341                                                    origin,
1342                                                    renderable,
1343                                                    /*sample count*/ 1,
1344                                                    skgpu::Mipmapped::kYes);
1345                     if (!sc) {
1346                         continue;
1347                     }
1348                     // Keeps pixels in unowned case alive until after writePixels is called but no
1349                     // longer.
1350                     GrPixmap keepAlive;
1351                     GrCPixmap savedLevel = levels[1];
1352                     if (unowned) {
1353                         // Also test non-tight row bytes with the unowned pixmap, bump width by 1.
1354                         int w = levels[1].width() + 1;
1355                         int h = levels[1].height();
1356                         keepAlive = GrPixmap::Allocate(levels[1].info().makeWH(w, h));
1357                         SkPixmap src;
1358                         // These pixel values will be the same as the original level 1.
1359                         SkAssertResult(ref.extractSubset(&src, SkIRect::MakeWH(w, h)));
1360                         SkAssertResult(GrConvertPixels(keepAlive, src));
1361                         levels[1] = GrCPixmap(levels[1].info(),
1362                                               keepAlive.addr(),
1363                                               keepAlive.rowBytes());
1364                     }
1365                     // Going through intermediate textures is not supported for MIP levels (because
1366                     // we don't support rendering to non-base levels). So it's hard to have any hard
1367                     // rules about when we expect success.
1368                     if (!sc->writePixels(direct, levels.begin(), levels.size())) {
1369                         continue;
1370                     }
1371                     // Make sure the pixels from the unowned pixmap are released and then put the
1372                     // original level back in for the comparison after the read below.
1373                     keepAlive = {};
1374                     levels[1] = savedLevel;
1375 
1376                     // TODO: Update this when read pixels supports reading back levels to read
1377                     // directly rather than using minimizing draws.
1378                     auto dstSC = CreateSurfaceContext(direct,
1379                                                       info,
1380                                                       SkBackingFit::kExact,
1381                                                       kBottomLeft_GrSurfaceOrigin,
1382                                                       GrRenderable::kYes);
1383                     SkASSERT(dstSC);
1384                     GrSamplerState sampler(SkFilterMode::kNearest, SkMipmapMode::kNearest);
1385                     for (int i = 1; i <= 1; ++i) {
1386                         auto te = GrTextureEffect::Make(sc->readSurfaceView(),
1387                                                         info.alphaType(),
1388                                                         SkMatrix::I(),
1389                                                         sampler,
1390                                                         *direct->priv().caps());
1391                         dstSC->asFillContext()->fillRectToRectWithFP(
1392                                 SkIRect::MakeSize(sc->dimensions()),
1393                                 SkIRect::MakeSize(levels[i].dimensions()),
1394                                 std::move(te));
1395                         GrImageInfo readInfo =
1396                                 dstSC->imageInfo().makeDimensions(levels[i].dimensions());
1397                         GrPixmap read = GrPixmap::Allocate(readInfo);
1398                         if (!dstSC->readPixels(direct, read, {0, 0})) {
1399                             continue;
1400                         }
1401 
1402                         auto skCT = GrColorTypeToSkColorType(info.colorType());
1403                         int rgbBits = std::min(min_rgb_channel_bits(skCT), 8);
1404                         float rgbTol = (rgbBits == 0) ? 1.f : 2.f / ((1 << rgbBits) - 1);
1405                         int alphaBits = std::min(alpha_channel_bits(skCT), 8);
1406                         float alphaTol = (alphaBits == 0) ? 1.f : 2.f / ((1 << alphaBits) - 1);
1407                         float tol[] = {rgbTol, rgbTol, rgbTol, alphaTol};
1408 
1409                         GrCPixmap a = levels[i];
1410                         GrCPixmap b = read;
1411                         // The compare code will linearize when reading the srgb data. This will
1412                         // magnify differences at the high end. Rather than adjusting the tolerance
1413                         // to compensate we do the comparison without going through srgb->linear.
1414                         if (ct == GrColorType::kRGBA_8888_SRGB) {
1415                             a = GrCPixmap(a.info().makeColorType(GrColorType::kRGBA_8888),
1416                                           a.addr(),
1417                                           a.rowBytes());
1418                             b = GrCPixmap(b.info().makeColorType(GrColorType::kRGBA_8888),
1419                                           b.addr(),
1420                                           b.rowBytes());
1421                         }
1422 
1423                         auto error = std::function<ComparePixmapsErrorReporter>(
1424                                 [&](int x, int y, const float diffs[4]) {
1425                                     SkASSERT(x >= 0 && y >= 0);
1426                                     ERRORF(reporter,
1427                                            "CT: %s, Level %d, Unowned: %d. "
1428                                            "Error at %d, %d. Diff in floats:"
1429                                            "(%f, %f, %f, %f)",
1430                                            GrColorTypeToStr(info.colorType()), i, unowned, x, y,
1431                                            diffs[0], diffs[1], diffs[2], diffs[3]);
1432                                 });
1433                         ComparePixels(a, b, tol, error);
1434                     }
1435                 }
1436             }
1437         }
1438     }
1439 }
1440 
1441 // Tests a bug found in OOP-R canvas2d in Chrome. The GPU backend would incorrectly not bind
1442 // buffer 0 to GL_PIXEL_PACK_BUFFER before a glReadPixels() that was supposed to read into
1443 // client memory if a GrDirectContext::resetContext() occurred.
DEF_GANESH_TEST_FOR_GL_CONTEXT(GLReadPixelsUnbindPBO,reporter,ctxInfo,CtsEnforcement::kApiLevel_T)1444 DEF_GANESH_TEST_FOR_GL_CONTEXT(GLReadPixelsUnbindPBO,
1445                                reporter,
1446                                ctxInfo,
1447                                CtsEnforcement::kApiLevel_T) {
1448     // Start with a async read so that we bind to GL_PIXEL_PACK_BUFFER.
1449     auto info = SkImageInfo::Make(16, 16, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
1450     SkAutoPixmapStorage pmap = make_ref_data(info, /*forceOpaque=*/false);
1451     auto image = SkImages::RasterFromPixmap(pmap, nullptr, nullptr);
1452     image = SkImages::TextureFromImage(ctxInfo.directContext(), image);
1453     if (!image) {
1454         ERRORF(reporter, "Couldn't make texture image.");
1455         return;
1456     }
1457 
1458     AsyncContext asyncContext;
1459     image->asyncRescaleAndReadPixels(info,
1460                                      SkIRect::MakeSize(info.dimensions()),
1461                                      SkImage::RescaleGamma::kSrc,
1462                                      SkImage::RescaleMode::kNearest,
1463                                      async_callback,
1464                                      &asyncContext);
1465 
1466     // This will force the async readback to finish.
1467     ctxInfo.directContext()->flushAndSubmit(GrSyncCpu::kYes);
1468     if (!asyncContext.fCalled) {
1469         ERRORF(reporter, "async_callback not called.");
1470     }
1471     if (!asyncContext.fResult) {
1472         ERRORF(reporter, "async read failed.");
1473     }
1474 
1475     SkPixmap asyncResult(info, asyncContext.fResult->data(0), asyncContext.fResult->rowBytes(0));
1476 
1477     // Bug was that this would cause GrGLGpu to think no buffer was left bound to
1478     // GL_PIXEL_PACK_BUFFER even though async transfer did leave one bound. So the sync read
1479     // wouldn't bind buffer 0.
1480     ctxInfo.directContext()->resetContext();
1481 
1482     SkBitmap syncResult;
1483     syncResult.allocPixels(info);
1484     syncResult.eraseARGB(0xFF, 0xFF, 0xFF, 0xFF);
1485 
1486     image->readPixels(ctxInfo.directContext(), syncResult.pixmap(), 0, 0);
1487 
1488     float tol[4] = {};  // expect exactly same pixels, no conversions.
1489     auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
1490                                                                 const float diffs[4]) {
1491       SkASSERT(x >= 0 && y >= 0);
1492       ERRORF(reporter, "Expect sync and async read to be the same. "
1493              "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
1494              x, y, diffs[0], diffs[1], diffs[2], diffs[3]);
1495     });
1496 
1497     ComparePixels(syncResult.pixmap(), asyncResult, tol, error);
1498 }
1499