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