blob: 8fd263aa2f27c5319a30170b9d7f5182d436cdb2 [file] [log] [blame]
Brian Salomonf84dfd62020-12-29 15:09:33 -05001/*
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/SkCanvas.h"
9#include "include/core/SkImage.h"
10#include "include/core/SkSurface.h"
11#include "include/effects/SkGradientShader.h"
12#include "include/gpu/GrDirectContext.h"
13#include "src/core/SkAutoPixmapStorage.h"
14#include "src/core/SkConvertPixels.h"
15#include "src/gpu/GrDirectContextPriv.h"
16#include "src/gpu/GrImageInfo.h"
Robert Phillips53eaa642021-08-10 13:49:51 -040017#include "src/gpu/SurfaceContext.h"
Robert Phillipsf3868622021-08-04 13:27:43 -040018#include "src/gpu/SurfaceFillContext.h"
Robert Phillips550de7f2021-07-06 16:28:52 -040019#include "src/gpu/effects/GrTextureEffect.h"
Brian Salomonf84dfd62020-12-29 15:09:33 -050020#include "tests/Test.h"
21#include "tests/TestUtils.h"
22#include "tools/ToolUtils.h"
Brian Salomonbacbb922021-01-21 19:48:00 -050023#include "tools/gpu/BackendSurfaceFactory.h"
Brian Salomonf84dfd62020-12-29 15:09:33 -050024#include "tools/gpu/BackendTextureImageFactory.h"
25#include "tools/gpu/GrContextFactory.h"
26#include "tools/gpu/ProxyUtils.h"
27
28#include <initializer_list>
29
30static constexpr int min_rgb_channel_bits(SkColorType ct) {
31 switch (ct) {
32 case kUnknown_SkColorType: return 0;
33 case kAlpha_8_SkColorType: return 0;
34 case kA16_unorm_SkColorType: return 0;
35 case kA16_float_SkColorType: return 0;
36 case kRGB_565_SkColorType: return 5;
37 case kARGB_4444_SkColorType: return 4;
38 case kR8G8_unorm_SkColorType: return 8;
39 case kR16G16_unorm_SkColorType: return 16;
40 case kR16G16_float_SkColorType: return 16;
41 case kRGBA_8888_SkColorType: return 8;
Brian Osman9f1e06a2021-08-10 14:39:18 -040042 case kSRGBA_8888_SkColorType: return 8;
Brian Salomonf84dfd62020-12-29 15:09:33 -050043 case kRGB_888x_SkColorType: return 8;
44 case kBGRA_8888_SkColorType: return 8;
45 case kRGBA_1010102_SkColorType: return 10;
46 case kRGB_101010x_SkColorType: return 10;
47 case kBGRA_1010102_SkColorType: return 10;
48 case kBGR_101010x_SkColorType: return 10;
49 case kGray_8_SkColorType: return 8; // counting gray as "rgb"
50 case kRGBA_F16Norm_SkColorType: return 10; // just counting the mantissa
51 case kRGBA_F16_SkColorType: return 10; // just counting the mantissa
52 case kRGBA_F32_SkColorType: return 23; // just counting the mantissa
53 case kR16G16B16A16_unorm_SkColorType: return 16;
54 }
55 SkUNREACHABLE;
56}
57
58static constexpr int alpha_channel_bits(SkColorType ct) {
59 switch (ct) {
60 case kUnknown_SkColorType: return 0;
61 case kAlpha_8_SkColorType: return 8;
62 case kA16_unorm_SkColorType: return 16;
63 case kA16_float_SkColorType: return 16;
64 case kRGB_565_SkColorType: return 0;
65 case kARGB_4444_SkColorType: return 4;
66 case kR8G8_unorm_SkColorType: return 0;
67 case kR16G16_unorm_SkColorType: return 0;
68 case kR16G16_float_SkColorType: return 0;
69 case kRGBA_8888_SkColorType: return 8;
Brian Osman9f1e06a2021-08-10 14:39:18 -040070 case kSRGBA_8888_SkColorType: return 8;
Brian Salomonf84dfd62020-12-29 15:09:33 -050071 case kRGB_888x_SkColorType: return 0;
72 case kBGRA_8888_SkColorType: return 8;
73 case kRGBA_1010102_SkColorType: return 2;
74 case kRGB_101010x_SkColorType: return 0;
75 case kBGRA_1010102_SkColorType: return 2;
76 case kBGR_101010x_SkColorType: return 0;
77 case kGray_8_SkColorType: return 0;
78 case kRGBA_F16Norm_SkColorType: return 10; // just counting the mantissa
79 case kRGBA_F16_SkColorType: return 10; // just counting the mantissa
80 case kRGBA_F32_SkColorType: return 23; // just counting the mantissa
81 case kR16G16B16A16_unorm_SkColorType: return 16;
82 }
83 SkUNREACHABLE;
84}
85
Brian Salomon1d2a26d2021-03-30 10:59:10 -040086std::vector<SkIRect> make_long_rect_array(int w, int h) {
87 return {
88 // entire thing
89 SkIRect::MakeWH(w, h),
90 // larger on all sides
91 SkIRect::MakeLTRB(-10, -10, w + 10, h + 10),
92 // fully contained
93 SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
94 // outside top left
95 SkIRect::MakeLTRB(-10, -10, -1, -1),
96 // touching top left corner
97 SkIRect::MakeLTRB(-10, -10, 0, 0),
98 // overlapping top left corner
99 SkIRect::MakeLTRB(-10, -10, w/4, h/4),
100 // overlapping top left and top right corners
101 SkIRect::MakeLTRB(-10, -10, w + 10, h/4),
102 // touching entire top edge
103 SkIRect::MakeLTRB(-10, -10, w + 10, 0),
104 // overlapping top right corner
105 SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
106 // contained in x, overlapping top edge
107 SkIRect::MakeLTRB(w/4, -10, 3*w/4, h/4),
108 // outside top right corner
109 SkIRect::MakeLTRB(w + 1, -10, w + 10, -1),
110 // touching top right corner
111 SkIRect::MakeLTRB(w, -10, w + 10, 0),
112 // overlapping top left and bottom left corners
113 SkIRect::MakeLTRB(-10, -10, w/4, h + 10),
114 // touching entire left edge
115 SkIRect::MakeLTRB(-10, -10, 0, h + 10),
116 // overlapping bottom left corner
117 SkIRect::MakeLTRB(-10, 3*h/4, w/4, h + 10),
118 // contained in y, overlapping left edge
119 SkIRect::MakeLTRB(-10, h/4, w/4, 3*h/4),
120 // outside bottom left corner
121 SkIRect::MakeLTRB(-10, h + 1, -1, h + 10),
122 // touching bottom left corner
123 SkIRect::MakeLTRB(-10, h, 0, h + 10),
124 // overlapping bottom left and bottom right corners
125 SkIRect::MakeLTRB(-10, 3*h/4, w + 10, h + 10),
126 // touching entire left edge
127 SkIRect::MakeLTRB(0, h, w, h + 10),
128 // overlapping bottom right corner
129 SkIRect::MakeLTRB(3*w/4, 3*h/4, w + 10, h + 10),
130 // overlapping top right and bottom right corners
131 SkIRect::MakeLTRB(3*w/4, -10, w + 10, h + 10),
132 };
133}
134
135std::vector<SkIRect> make_short_rect_array(int w, int h) {
136 return {
137 // entire thing
138 SkIRect::MakeWH(w, h),
139 // fully contained
140 SkIRect::MakeLTRB(w/4, h/4, 3*w/4, 3*h/4),
141 // overlapping top right corner
142 SkIRect::MakeLTRB(3*w/4, -10, w + 10, h/4),
143 };
144}
145
Brian Salomonf84dfd62020-12-29 15:09:33 -0500146namespace {
147
148struct GpuReadPixelTestRules {
149 // Test unpremul sources? We could omit this and detect that creating the source of the read
150 // failed but having it lets us skip generating reference color data.
151 bool fAllowUnpremulSrc = true;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500152 // Are reads that are overlapping but not contained by the src bounds expected to succeed?
153 bool fUncontainedRectSucceeds = true;
154};
155
156// Makes a src populated with the pixmap. The src should get its image info (or equivalent) from
157// the pixmap.
158template <typename T> using GpuSrcFactory = T(SkPixmap&);
159
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400160enum class Result {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500161 kFail,
162 kSuccess,
163 kExcusedFailure,
164};
165
166// Does a read from the T into the pixmap.
167template <typename T>
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400168using GpuReadSrcFn = Result(const T&, const SkIPoint& offset, const SkPixmap&);
169
170// Makes a dst for testing writes.
171template <typename T> using GpuDstFactory = T(const SkImageInfo& ii);
172
173// Does a write from the pixmap to the T.
174template <typename T>
175using GpuWriteDstFn = Result(const T&, const SkIPoint& offset, const SkPixmap&);
176
177// To test the results of the write we do a read. This reads the entire src T. It should do a non-
178// converting read (i.e. the image info of the returned pixmap matches that of the T).
179template <typename T>
180using GpuReadDstFn = SkAutoPixmapStorage(const T&);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500181
182} // anonymous namespace
183
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400184SkPixmap make_pixmap_have_valid_alpha_type(SkPixmap pm) {
185 if (pm.alphaType() == kUnknown_SkAlphaType) {
186 return {pm.info().makeAlphaType(kUnpremul_SkAlphaType), pm.addr(), pm.rowBytes()};
187 }
188 return pm;
189}
190
Brian Salomon2c673402021-04-02 14:36:58 -0400191static SkAutoPixmapStorage make_ref_data(const SkImageInfo& info, bool forceOpaque) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400192 SkAutoPixmapStorage result;
193 result.alloc(info);
194 auto surface = SkSurface::MakeRasterDirect(make_pixmap_have_valid_alpha_type(result));
195 if (!surface) {
196 return result;
197 }
198
199 SkPoint pts1[] = {{0, 0}, {float(info.width()), float(info.height())}};
200 static constexpr SkColor kColors1[] = {SK_ColorGREEN, SK_ColorRED};
201 SkPaint paint;
202 paint.setShader(SkGradientShader::MakeLinear(pts1, kColors1, nullptr, 2, SkTileMode::kClamp));
203 surface->getCanvas()->drawPaint(paint);
204
205 SkPoint pts2[] = {{float(info.width()), 0}, {0, float(info.height())}};
206 static constexpr SkColor kColors2[] = {SK_ColorBLUE, SK_ColorBLACK};
207 paint.setShader(SkGradientShader::MakeLinear(pts2, kColors2, nullptr, 2, SkTileMode::kClamp));
208 paint.setBlendMode(SkBlendMode::kPlus);
209 surface->getCanvas()->drawPaint(paint);
210
211 // If not opaque add some fractional alpha.
212 if (info.alphaType() != kOpaque_SkAlphaType && !forceOpaque) {
213 static constexpr SkColor kColors3[] = {SK_ColorWHITE,
214 SK_ColorWHITE,
215 0x60FFFFFF,
216 SK_ColorWHITE,
217 SK_ColorWHITE};
218 static constexpr SkScalar kPos3[] = {0.f, 0.15f, 0.5f, 0.85f, 1.f};
219 paint.setShader(SkGradientShader::MakeRadial({info.width()/2.f, info.height()/2.f},
220 (info.width() + info.height())/10.f,
221 kColors3, kPos3, 5, SkTileMode::kMirror));
222 paint.setBlendMode(SkBlendMode::kDstIn);
223 surface->getCanvas()->drawPaint(paint);
224 }
225 return result;
226};
227
Brian Salomonf84dfd62020-12-29 15:09:33 -0500228template <typename T>
229static void gpu_read_pixels_test_driver(skiatest::Reporter* reporter,
230 const GpuReadPixelTestRules& rules,
231 const std::function<GpuSrcFactory<T>>& srcFactory,
Brian Salomonbacbb922021-01-21 19:48:00 -0500232 const std::function<GpuReadSrcFn<T>>& read,
233 SkString label) {
234 if (!label.isEmpty()) {
235 // Add space for printing.
236 label.append(" ");
237 }
Brian Salomonf84dfd62020-12-29 15:09:33 -0500238 // Separate this out just to give it some line width to breathe. Note 'srcPixels' should have
239 // the same image info as src. We will do a converting readPixels() on it to get the data
240 // to compare with the results of 'read'.
241 auto runTest = [&](const T& src,
242 const SkPixmap& srcPixels,
243 const SkImageInfo& readInfo,
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400244 SkIPoint offset) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500245 const bool csConversion =
246 !SkColorSpace::Equals(readInfo.colorSpace(), srcPixels.info().colorSpace());
247 const auto readCT = readInfo.colorType();
248 const auto readAT = readInfo.alphaType();
249 const auto srcCT = srcPixels.info().colorType();
250 const auto srcAT = srcPixels.info().alphaType();
251 const auto rect = SkIRect::MakeWH(readInfo.width(), readInfo.height()).makeOffset(offset);
252 const auto surfBounds = SkIRect::MakeWH(srcPixels.width(), srcPixels.height());
253 const size_t readBpp = SkColorTypeBytesPerPixel(readCT);
254
255 // Make the row bytes in the dst be loose for extra stress.
256 const size_t dstRB = readBpp * readInfo.width() + 10 * readBpp;
257 // This will make the last row tight.
258 const size_t dstSize = readInfo.computeByteSize(dstRB);
259 std::unique_ptr<char[]> dstData(new char[dstSize]);
260 SkPixmap dstPixels(readInfo, dstData.get(), dstRB);
261 // Initialize with an arbitrary value for each byte. Later we will check that only the
262 // correct part of the destination gets overwritten by 'read'.
263 static constexpr auto kInitialByte = static_cast<char>(0x1B);
264 std::fill_n(static_cast<char*>(dstPixels.writable_addr()),
265 dstPixels.computeByteSize(),
266 kInitialByte);
267
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400268 const Result result = read(src, offset, dstPixels);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500269
270 if (!SkIRect::Intersects(rect, surfBounds)) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400271 REPORTER_ASSERT(reporter, result != Result::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500272 } else if (readCT == kUnknown_SkColorType) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400273 REPORTER_ASSERT(reporter, result != Result::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500274 } else if ((readAT == kUnknown_SkAlphaType) != (srcAT == kUnknown_SkAlphaType)) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400275 REPORTER_ASSERT(reporter, result != Result::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500276 } else if (!rules.fUncontainedRectSucceeds && !surfBounds.contains(rect)) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400277 REPORTER_ASSERT(reporter, result != Result::kSuccess);
278 } else if (result == Result::kFail) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500279 // TODO: Support RGB/BGR 101010x, BGRA 1010102 on the GPU.
280 if (SkColorTypeToGrColorType(readCT) != GrColorType::kUnknown) {
281 ERRORF(reporter,
Brian Salomonbacbb922021-01-21 19:48:00 -0500282 "Read failed. %sSrc CT: %s, Src AT: %s Read CT: %s, Read AT: %s, "
Brian Salomonf84dfd62020-12-29 15:09:33 -0500283 "Rect [%d, %d, %d, %d], CS conversion: %d\n",
Brian Salomonbacbb922021-01-21 19:48:00 -0500284 label.c_str(),
Brian Salomonf84dfd62020-12-29 15:09:33 -0500285 ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
286 ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
287 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
288 }
289 return result;
290 }
291
292 bool guardOk = true;
293 auto guardCheck = [](char x) { return x == kInitialByte; };
294
295 // Considering the rect we tried to read and the surface bounds figure out which pixels in
296 // both src and dst space should actually have been read and written.
297 SkIRect srcReadRect;
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400298 if (result == Result::kSuccess && srcReadRect.intersect(surfBounds, rect)) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500299 SkIRect dstWriteRect = srcReadRect.makeOffset(-rect.fLeft, -rect.fTop);
300
301 const bool lumConversion =
302 !(SkColorTypeChannelFlags(srcCT) & kGray_SkColorChannelFlag) &&
303 (SkColorTypeChannelFlags(readCT) & kGray_SkColorChannelFlag);
304 // A CS or luminance conversion allows a 3 value difference and otherwise a 2 value
305 // difference. Note that sometimes read back on GPU can be lossy even when there no
306 // conversion at all because GPU->CPU read may go to a lower bit depth format and then
307 // be promoted back to the original type. For example, GL ES cannot read to 1010102, so
308 // we go through 8888.
309 float numer = (lumConversion || csConversion) ? 3.f : 2.f;
310 // Allow some extra tolerance if unpremuling.
311 if (srcAT == kPremul_SkAlphaType && readAT == kUnpremul_SkAlphaType) {
312 numer += 1;
313 }
314 int rgbBits = std::min({min_rgb_channel_bits(readCT), min_rgb_channel_bits(srcCT), 8});
315 float tol = numer / (1 << rgbBits);
316 float alphaTol = 0;
317 if (readAT != kOpaque_SkAlphaType && srcAT != kOpaque_SkAlphaType) {
318 // Alpha can also get squashed down to 8 bits going through an intermediate
319 // color format.
320 const int alphaBits = std::min({alpha_channel_bits(readCT),
321 alpha_channel_bits(srcCT),
322 8});
323 alphaTol = 2.f / (1 << alphaBits);
324 }
325
326 const float tols[4] = {tol, tol, tol, alphaTol};
327 auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
328 const float diffs[4]) {
329 SkASSERT(x >= 0 && y >= 0);
330 ERRORF(reporter,
Brian Salomonbacbb922021-01-21 19:48:00 -0500331 "%sSrc CT: %s, Src AT: %s, Read CT: %s, Read AT: %s, Rect [%d, %d, %d, %d]"
Brian Salomonf84dfd62020-12-29 15:09:33 -0500332 ", CS conversion: %d\n"
Brian Salomon2c673402021-04-02 14:36:58 -0400333 "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
Brian Salomonbacbb922021-01-21 19:48:00 -0500334 label.c_str(),
Brian Salomonf84dfd62020-12-29 15:09:33 -0500335 ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
336 ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
337 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion, x, y,
338 diffs[0], diffs[1], diffs[2], diffs[3]);
339 });
340 SkAutoPixmapStorage ref;
341 SkImageInfo refInfo = readInfo.makeDimensions(dstWriteRect.size());
342 ref.alloc(refInfo);
343 if (readAT == kUnknown_SkAlphaType) {
344 // Do a spoofed read where src and dst alpha type are both kUnpremul. This will
345 // allow SkPixmap readPixels to succeed and won't do any alpha type conversion.
346 SkPixmap unpremulRef(refInfo.makeAlphaType(kUnpremul_SkAlphaType),
347 ref.addr(),
348 ref.rowBytes());
349 SkPixmap unpremulSRc(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
350 srcPixels.addr(),
351 srcPixels.rowBytes());
352
353 unpremulSRc.readPixels(unpremulRef, srcReadRect.x(), srcReadRect.y());
354 } else {
355 srcPixels.readPixels(ref, srcReadRect.x(), srcReadRect.y());
356 }
357 // This is the part of dstPixels that should have been updated.
358 SkPixmap actual;
359 SkAssertResult(dstPixels.extractSubset(&actual, dstWriteRect));
360 ComparePixels(ref, actual, tols, error);
361
362 const auto* v = dstData.get();
363 const auto* end = dstData.get() + dstSize;
364 guardOk = std::all_of(v, v + dstWriteRect.top() * dstPixels.rowBytes(), guardCheck);
365 v += dstWriteRect.top() * dstPixels.rowBytes();
366 for (int y = dstWriteRect.top(); y < dstWriteRect.bottom(); ++y) {
367 guardOk |= std::all_of(v, v + dstWriteRect.left() * readBpp, guardCheck);
368 auto pad = v + dstWriteRect.right() * readBpp;
369 auto rowEnd = std::min(end, v + dstPixels.rowBytes());
370 // min protects against reading past the end of the tight last row.
371 guardOk |= std::all_of(pad, rowEnd, guardCheck);
372 v = rowEnd;
373 }
374 guardOk |= std::all_of(v, end, guardCheck);
375 } else {
376 guardOk = std::all_of(dstData.get(), dstData.get() + dstSize, guardCheck);
377 }
378 if (!guardOk) {
379 ERRORF(reporter,
380 "Result pixels modified result outside read rect [%d, %d, %d, %d]. "
Brian Salomonbacbb922021-01-21 19:48:00 -0500381 "%sSrc CT: %s, Read CT: %s, CS conversion: %d",
382 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, label.c_str(),
Brian Salomonf84dfd62020-12-29 15:09:33 -0500383 ToolUtils::colortype_name(srcCT), ToolUtils::colortype_name(readCT),
384 csConversion);
385 }
386 return result;
387 };
388
389 static constexpr int kW = 16;
390 static constexpr int kH = 16;
391
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400392 const std::vector<SkIRect> longRectArray = make_long_rect_array(kW, kH);
393 const std::vector<SkIRect> shortRectArray = make_short_rect_array(kW, kH);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500394
Brian Salomonf84dfd62020-12-29 15:09:33 -0500395 // We ensure we use the long array once per src and read color type and otherwise use the
396 // short array to improve test run time.
397 // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
398 // equivalent. Just ensure each redundant AT is tested once with each CT (src and read).
399 // Similarly, alpha-only color types behave the same for all alpha types so just test premul
400 // after one iter.
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400401 // We consider a src or read CT thoroughly tested once it has run through the long rect array
Brian Salomonf84dfd62020-12-29 15:09:33 -0500402 // and full complement of alpha types with one successful read in the loop.
403 std::array<bool, kLastEnum_SkColorType + 1> srcCTTestedThoroughly = {},
404 readCTTestedThoroughly = {};
405 for (int sat = 0; sat < kLastEnum_SkAlphaType; ++sat) {
406 const auto srcAT = static_cast<SkAlphaType>(sat);
407 if (srcAT == kUnpremul_SkAlphaType && !rules.fAllowUnpremulSrc) {
408 continue;
409 }
410 for (int sct = 0; sct <= kLastEnum_SkColorType; ++sct) {
411 const auto srcCT = static_cast<SkColorType>(sct);
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400412 // We always make our ref data as F32
413 auto refInfo = SkImageInfo::Make(kW, kH,
414 kRGBA_F32_SkColorType,
415 srcAT,
416 SkColorSpace::MakeSRGB());
417 // 1010102 formats have an issue where it's easy to make a resulting
418 // color where r, g, or b is greater than a. CPU/GPU differ in whether the stored color
419 // channels are clipped to the alpha value. CPU clips but GPU does not.
420 // Note that we only currently use srcCT for the 1010102 workaround. If we remove this
421 // we can also put the ref data setup above the srcCT loop.
422 bool forceOpaque = srcAT == kPremul_SkAlphaType &&
423 (srcCT == kRGBA_1010102_SkColorType || srcCT == kBGRA_1010102_SkColorType);
424
425 SkAutoPixmapStorage srcPixels = make_ref_data(refInfo, forceOpaque);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500426 auto src = srcFactory(srcPixels);
427 if (!src) {
428 continue;
429 }
430 if (SkColorTypeIsAlwaysOpaque(srcCT) && srcCTTestedThoroughly[srcCT] &&
431 (kPremul_SkAlphaType == srcAT || kUnpremul_SkAlphaType == srcAT)) {
432 continue;
433 }
434 if (SkColorTypeIsAlphaOnly(srcCT) && srcCTTestedThoroughly[srcCT] &&
435 (kUnpremul_SkAlphaType == srcAT ||
436 kOpaque_SkAlphaType == srcAT ||
437 kUnknown_SkAlphaType == srcAT)) {
438 continue;
439 }
440 for (int rct = 0; rct <= kLastEnum_SkColorType; ++rct) {
441 const auto readCT = static_cast<SkColorType>(rct);
442 for (const sk_sp<SkColorSpace>& readCS :
443 {SkColorSpace::MakeSRGB(), SkColorSpace::MakeSRGBLinear()}) {
444 for (int at = 0; at <= kLastEnum_SkAlphaType; ++at) {
445 const auto readAT = static_cast<SkAlphaType>(at);
446 if (srcAT != kOpaque_SkAlphaType && readAT == kOpaque_SkAlphaType) {
447 // This doesn't make sense.
448 continue;
449 }
450 if (SkColorTypeIsAlwaysOpaque(readCT) && readCTTestedThoroughly[readCT] &&
451 (kPremul_SkAlphaType == readAT || kUnpremul_SkAlphaType == readAT)) {
452 continue;
453 }
454 if (SkColorTypeIsAlphaOnly(readCT) && readCTTestedThoroughly[readCT] &&
455 (kUnpremul_SkAlphaType == readAT ||
456 kOpaque_SkAlphaType == readAT ||
457 kUnknown_SkAlphaType == readAT)) {
458 continue;
459 }
460 const auto& rects =
461 srcCTTestedThoroughly[sct] && readCTTestedThoroughly[rct]
462 ? shortRectArray
463 : longRectArray;
464 for (const auto& rect : rects) {
465 const auto readInfo = SkImageInfo::Make(rect.width(), rect.height(),
466 readCT, readAT, readCS);
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400467 const SkIPoint offset = rect.topLeft();
468 Result r = runTest(src, srcPixels, readInfo, offset);
469 if (r == Result::kSuccess) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500470 srcCTTestedThoroughly[sct] = true;
471 readCTTestedThoroughly[rct] = true;
472 }
473 }
474 }
475 }
476 }
477 }
478 }
479}
480
481DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceContextReadPixels, reporter, ctxInfo) {
Robert Phillips53eaa642021-08-10 13:49:51 -0400482 using Surface = std::unique_ptr<skgpu::SurfaceContext>;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500483 GrDirectContext* direct = ctxInfo.directContext();
484 auto reader = std::function<GpuReadSrcFn<Surface>>(
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400485 [direct](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
486 if (surface->readPixels(direct, pixels, offset)) {
487 return Result::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500488 } else {
489 // Reading from a non-renderable format is not guaranteed to work on GL.
490 // We'd have to be able to force a copy or draw draw to a renderable format.
491 const auto& caps = *direct->priv().caps();
492 if (direct->backend() == GrBackendApi::kOpenGL &&
493 !caps.isFormatRenderable(surface->asSurfaceProxy()->backendFormat(), 1)) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400494 return Result::kExcusedFailure;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500495 }
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400496 return Result::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500497 }
498 });
499 GpuReadPixelTestRules rules;
500 rules.fAllowUnpremulSrc = true;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500501 rules.fUncontainedRectSucceeds = true;
502
503 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
504 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
505 auto factory = std::function<GpuSrcFactory<Surface>>(
506 [direct, origin, renderable](const SkPixmap& src) {
Robert Phillips168296b2021-08-16 11:41:27 -0400507 auto sc = CreateSurfaceContext(
Brian Salomonf84dfd62020-12-29 15:09:33 -0500508 direct, src.info(), SkBackingFit::kExact, origin, renderable);
Robert Phillips643f4812021-08-11 09:31:00 -0400509 if (sc) {
510 sc->writePixels(direct, src, {0, 0});
Brian Salomonf84dfd62020-12-29 15:09:33 -0500511 }
Robert Phillips643f4812021-08-11 09:31:00 -0400512 return sc;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500513 });
Brian Salomonbacbb922021-01-21 19:48:00 -0500514 auto label = SkStringPrintf("Renderable: %d, Origin: %d", (int)renderable, origin);
515 gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500516 }
517 }
518}
519
Brian Salomonc24c8ef2021-02-01 13:32:30 -0500520DEF_GPUTEST_FOR_ALL_CONTEXTS(ReadPixels_InvalidRowBytes_Gpu, reporter, ctxInfo) {
521 auto srcII = SkImageInfo::Make({10, 10}, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
522 auto surf = SkSurface::MakeRenderTarget(ctxInfo.directContext(), SkBudgeted::kYes, srcII);
523 for (int ct = 0; ct < kLastEnum_SkColorType + 1; ++ct) {
524 auto colorType = static_cast<SkColorType>(ct);
525 size_t bpp = SkColorTypeBytesPerPixel(colorType);
526 if (bpp <= 1) {
527 continue;
528 }
529 auto dstII = srcII.makeColorType(colorType);
530 size_t badRowBytes = (surf->width() + 1)*bpp - 1;
531 auto storage = std::make_unique<char[]>(badRowBytes*surf->height());
532 REPORTER_ASSERT(reporter, !surf->readPixels(dstII, storage.get(), badRowBytes, 0, 0));
533 }
534}
535
Michael Ludwiga5c90582021-03-09 15:35:32 -0500536DEF_GPUTEST_FOR_ALL_CONTEXTS(WritePixels_InvalidRowBytes_Gpu, reporter, ctxInfo) {
537 auto dstII = SkImageInfo::Make({10, 10}, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
538 auto surf = SkSurface::MakeRenderTarget(ctxInfo.directContext(), SkBudgeted::kYes, dstII);
539 for (int ct = 0; ct < kLastEnum_SkColorType + 1; ++ct) {
540 auto colorType = static_cast<SkColorType>(ct);
541 size_t bpp = SkColorTypeBytesPerPixel(colorType);
542 if (bpp <= 1) {
543 continue;
544 }
545 auto srcII = dstII.makeColorType(colorType);
546 size_t badRowBytes = (surf->width() + 1)*bpp - 1;
547 auto storage = std::make_unique<char[]>(badRowBytes*surf->height());
548 memset(storage.get(), 0, badRowBytes * surf->height());
549 // SkSurface::writePixels doesn't report bool, SkCanvas's does.
550 REPORTER_ASSERT(reporter,
551 !surf->getCanvas()->writePixels(srcII, storage.get(), badRowBytes, 0, 0));
552 }
553}
554
Brian Salomonf84dfd62020-12-29 15:09:33 -0500555namespace {
556struct AsyncContext {
557 bool fCalled = false;
558 std::unique_ptr<const SkImage::AsyncReadResult> fResult;
559};
560} // anonymous namespace
561
562// Making this a lambda in the test functions caused:
563// "error: cannot compile this forwarded non-trivially copyable parameter yet"
564// on x86/Win/Clang bot, referring to 'result'.
565static void async_callback(void* c, std::unique_ptr<const SkImage::AsyncReadResult> result) {
566 auto context = static_cast<AsyncContext*>(c);
567 context->fResult = std::move(result);
568 context->fCalled = true;
569};
570
571DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixels, reporter, ctxInfo) {
572 using Surface = sk_sp<SkSurface>;
573 auto reader = std::function<GpuReadSrcFn<Surface>>(
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400574 [](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500575 auto direct = surface->recordingContext()->asDirectContext();
576 SkASSERT(direct);
577
578 AsyncContext context;
579 auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
580
581 // Rescale quality and linearity don't matter since we're doing a non-scaling
582 // readback.
Mike Reed1efa14d2021-01-02 21:44:59 -0500583 surface->asyncRescaleAndReadPixels(pixels.info(), rect,
584 SkImage::RescaleGamma::kSrc,
585 SkImage::RescaleMode::kNearest,
586 async_callback, &context);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500587 direct->submit();
588 while (!context.fCalled) {
589 direct->checkAsyncWorkCompletion();
590 }
591 if (!context.fResult) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400592 return Result::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500593 }
594 SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), context.fResult->data(0),
595 context.fResult->rowBytes(0), pixels.info().minRowBytes(),
596 pixels.height());
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400597 return Result::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500598 });
599 GpuReadPixelTestRules rules;
600 rules.fAllowUnpremulSrc = false;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500601 rules.fUncontainedRectSucceeds = false;
602
603 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
604 auto factory = std::function<GpuSrcFactory<Surface>>(
605 [context = ctxInfo.directContext(), origin](const SkPixmap& src) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500606 auto surf = SkSurface::MakeRenderTarget(context,
607 SkBudgeted::kYes,
608 src.info(),
Brian Salomonbacbb922021-01-21 19:48:00 -0500609 1,
Brian Salomonf84dfd62020-12-29 15:09:33 -0500610 origin,
611 nullptr);
612 if (surf) {
613 surf->writePixels(src, 0, 0);
614 }
615 return surf;
616 });
Brian Salomonbacbb922021-01-21 19:48:00 -0500617 auto label = SkStringPrintf("Origin: %d", origin);
618 gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
619 auto backendRTFactory = std::function<GpuSrcFactory<Surface>>(
620 [context = ctxInfo.directContext(), origin](const SkPixmap& src) {
Brian Salomon2c673402021-04-02 14:36:58 -0400621 // Dawn backend implementation of backend render targets doesn't support
622 // reading.
623 if (context->backend() == GrBackendApi::kDawn) {
624 return Surface();
625 }
626 auto surf = sk_gpu_test::MakeBackendRenderTargetSurface(context,
627 src.info(),
628 origin,
629 1);
630 if (surf) {
631 surf->writePixels(src, 0, 0);
632 }
633 return surf;
Brian Salomonbacbb922021-01-21 19:48:00 -0500634 });
635 label = SkStringPrintf("BERT Origin: %d", origin);
636 gpu_read_pixels_test_driver(reporter, rules, backendRTFactory, reader, label);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500637 }
638}
639
640DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels, reporter, ctxInfo) {
641 using Image = sk_sp<SkImage>;
642 auto context = ctxInfo.directContext();
643 auto reader = std::function<GpuReadSrcFn<Image>>([context](const Image& image,
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400644 const SkIPoint& offset,
Brian Salomonf84dfd62020-12-29 15:09:33 -0500645 const SkPixmap& pixels) {
646 AsyncContext asyncContext;
647 auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
648 // The GPU implementation is based on rendering and will fail for non-renderable color
649 // types.
650 auto ct = SkColorTypeToGrColorType(image->colorType());
651 auto format = context->priv().caps()->getDefaultBackendFormat(ct, GrRenderable::kYes);
652 if (!context->priv().caps()->isFormatAsColorTypeRenderable(ct, format)) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400653 return Result::kExcusedFailure;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500654 }
655
656 // Rescale quality and linearity don't matter since we're doing a non-scaling readback.
Mike Reed1efa14d2021-01-02 21:44:59 -0500657 image->asyncRescaleAndReadPixels(pixels.info(), rect,
658 SkImage::RescaleGamma::kSrc,
659 SkImage::RescaleMode::kNearest,
660 async_callback, &asyncContext);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500661 context->submit();
662 while (!asyncContext.fCalled) {
663 context->checkAsyncWorkCompletion();
664 }
665 if (!asyncContext.fResult) {
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400666 return Result::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500667 }
668 SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), asyncContext.fResult->data(0),
669 asyncContext.fResult->rowBytes(0), pixels.info().minRowBytes(),
670 pixels.height());
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400671 return Result::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500672 });
673
674 GpuReadPixelTestRules rules;
675 rules.fAllowUnpremulSrc = true;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500676 rules.fUncontainedRectSucceeds = false;
677
678 for (auto origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
679 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
680 auto factory = std::function<GpuSrcFactory<Image>>([&](const SkPixmap& src) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500681 return sk_gpu_test::MakeBackendTextureImage(ctxInfo.directContext(), src,
682 renderable, origin);
683 });
Brian Salomonbacbb922021-01-21 19:48:00 -0500684 auto label = SkStringPrintf("Renderable: %d, Origin: %d", (int)renderable, origin);
685 gpu_read_pixels_test_driver(reporter, rules, factory, reader, label);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500686 }
687 }
688}
689
690DEF_GPUTEST(AsyncReadPixelsContextShutdown, reporter, options) {
691 const auto ii = SkImageInfo::Make(10, 10, kRGBA_8888_SkColorType, kPremul_SkAlphaType,
692 SkColorSpace::MakeSRGB());
693 enum class ShutdownSequence {
694 kFreeResult_DestroyContext,
695 kDestroyContext_FreeResult,
696 kFreeResult_ReleaseAndAbandon_DestroyContext,
697 kFreeResult_Abandon_DestroyContext,
698 kReleaseAndAbandon_FreeResult_DestroyContext,
699 kAbandon_FreeResult_DestroyContext,
700 kReleaseAndAbandon_DestroyContext_FreeResult,
701 kAbandon_DestroyContext_FreeResult,
702 };
703 for (int t = 0; t < sk_gpu_test::GrContextFactory::kContextTypeCnt; ++t) {
704 auto type = static_cast<sk_gpu_test::GrContextFactory::ContextType>(t);
705 for (auto sequence : {ShutdownSequence::kFreeResult_DestroyContext,
706 ShutdownSequence::kDestroyContext_FreeResult,
707 ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext,
708 ShutdownSequence::kFreeResult_Abandon_DestroyContext,
709 ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext,
710 ShutdownSequence::kAbandon_FreeResult_DestroyContext,
711 ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult,
712 ShutdownSequence::kAbandon_DestroyContext_FreeResult}) {
Jim Van Vertha655f0d2021-05-18 15:03:27 -0400713 // Vulkan and D3D context abandoning without resource release has issues outside of the
714 // scope of this test.
715 if ((type == sk_gpu_test::GrContextFactory::kVulkan_ContextType ||
716 type == sk_gpu_test::GrContextFactory::kDirect3D_ContextType) &&
Brian Salomonf84dfd62020-12-29 15:09:33 -0500717 (sequence == ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext ||
718 sequence == ShutdownSequence::kFreeResult_Abandon_DestroyContext ||
719 sequence == ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext ||
720 sequence == ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult ||
721 sequence == ShutdownSequence::kAbandon_FreeResult_DestroyContext ||
722 sequence == ShutdownSequence::kAbandon_DestroyContext_FreeResult)) {
723 continue;
724 }
725 for (bool yuv : {false, true}) {
726 sk_gpu_test::GrContextFactory factory(options);
727 auto direct = factory.get(type);
728 if (!direct) {
729 continue;
730 }
731 // This test is only meaningful for contexts that support transfer buffers for
732 // reads.
733 if (!direct->priv().caps()->transferFromSurfaceToBufferSupport()) {
734 continue;
735 }
736 auto surf = SkSurface::MakeRenderTarget(direct, SkBudgeted::kYes, ii, 1, nullptr);
737 if (!surf) {
738 continue;
739 }
740 AsyncContext cbContext;
741 if (yuv) {
742 surf->asyncRescaleAndReadPixelsYUV420(
743 kIdentity_SkYUVColorSpace, SkColorSpace::MakeSRGB(), ii.bounds(),
Mike Reed1efa14d2021-01-02 21:44:59 -0500744 ii.dimensions(), SkImage::RescaleGamma::kSrc,
745 SkImage::RescaleMode::kNearest, &async_callback, &cbContext);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500746 } else {
747 surf->asyncRescaleAndReadPixels(ii, ii.bounds(), SkImage::RescaleGamma::kSrc,
Mike Reed1efa14d2021-01-02 21:44:59 -0500748 SkImage::RescaleMode::kNearest, &async_callback,
Brian Salomonf84dfd62020-12-29 15:09:33 -0500749 &cbContext);
750 }
751 direct->submit();
752 while (!cbContext.fCalled) {
753 direct->checkAsyncWorkCompletion();
754 }
755 if (!cbContext.fResult) {
756 ERRORF(reporter, "Callback failed on %s. is YUV: %d",
757 sk_gpu_test::GrContextFactory::ContextTypeName(type), yuv);
758 continue;
759 }
760 // For vulkan we need to release all refs to the GrDirectContext before trying to
761 // destroy the test context. The surface here is holding a ref.
762 surf.reset();
763
764 // The real test is that we don't crash, get Vulkan validation errors, etc, during
765 // this shutdown sequence.
766 switch (sequence) {
767 case ShutdownSequence::kFreeResult_DestroyContext:
768 case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
769 case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
770 break;
771 case ShutdownSequence::kDestroyContext_FreeResult:
772 factory.destroyContexts();
773 break;
774 case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
775 factory.releaseResourcesAndAbandonContexts();
776 break;
777 case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
778 factory.abandonContexts();
779 break;
780 case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
781 factory.releaseResourcesAndAbandonContexts();
782 factory.destroyContexts();
783 break;
784 case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
785 factory.abandonContexts();
786 factory.destroyContexts();
787 break;
788 }
789 cbContext.fResult.reset();
790 switch (sequence) {
791 case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
792 factory.releaseResourcesAndAbandonContexts();
793 break;
794 case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
795 factory.abandonContexts();
796 break;
797 case ShutdownSequence::kFreeResult_DestroyContext:
798 case ShutdownSequence::kDestroyContext_FreeResult:
799 case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
800 case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
801 case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
802 case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
803 break;
804 }
805 }
806 }
807 }
808}
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400809
810template <typename T>
811static void gpu_write_pixels_test_driver(skiatest::Reporter* reporter,
812 const std::function<GpuDstFactory<T>>& dstFactory,
813 const std::function<GpuWriteDstFn<T>>& write,
814 const std::function<GpuReadDstFn<T>>& read) {
815 // Separate this out just to give it some line width to breathe.
816 auto runTest = [&](const T& dst,
817 const SkImageInfo& dstInfo,
818 const SkPixmap& srcPixels,
819 SkIPoint offset) {
820 const bool csConversion =
821 !SkColorSpace::Equals(dstInfo.colorSpace(), srcPixels.info().colorSpace());
822 const auto writeCT = srcPixels.colorType();
823 const auto writeAT = srcPixels.alphaType();
824 const auto dstCT = dstInfo.colorType();
825 const auto dstAT = dstInfo.alphaType();
826 const auto rect = SkIRect::MakePtSize(offset, srcPixels.dimensions());
827 const auto surfBounds = SkIRect::MakeSize(dstInfo.dimensions());
828
829 // Do an initial read before the write.
830 SkAutoPixmapStorage firstReadPM = read(dst);
831 if (!firstReadPM.addr()) {
832 // Particularly with GLES 2 we can have formats that are unreadable with our current
833 // implementation of read pixels. If the format can't be attached to a FBO we don't have
834 // a code path that draws it to another readable color type/format combo and reads from
835 // that.
836 return Result::kExcusedFailure;
837 }
838
839 const Result result = write(dst, offset, srcPixels);
840
841 if (!SkIRect::Intersects(rect, surfBounds)) {
842 REPORTER_ASSERT(reporter, result != Result::kSuccess);
843 } else if (writeCT == kUnknown_SkColorType) {
844 REPORTER_ASSERT(reporter, result != Result::kSuccess);
845 } else if ((writeAT == kUnknown_SkAlphaType) != (dstAT == kUnknown_SkAlphaType)) {
846 REPORTER_ASSERT(reporter, result != Result::kSuccess);
847 } else if (result == Result::kExcusedFailure) {
848 return result;
849 } else if (result == Result::kFail) {
850 // TODO: Support RGB/BGR 101010x, BGRA 1010102 on the GPU.
851 if (SkColorTypeToGrColorType(writeCT) != GrColorType::kUnknown) {
852 ERRORF(reporter,
853 "Write failed. Write CT: %s, Write AT: %s Dst CT: %s, Dst AT: %s, "
854 "Rect [%d, %d, %d, %d], CS conversion: %d\n",
855 ToolUtils::colortype_name(writeCT), ToolUtils::alphatype_name(writeAT),
856 ToolUtils::colortype_name(dstCT), ToolUtils::alphatype_name(dstAT),
857 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
858 }
859 return result;
860 }
861
862 SkIRect checkRect;
863 if (result != Result::kSuccess || !checkRect.intersect(surfBounds, rect)) {
864 return result;
865 }
866
867 // Do an initial read before the write. We'll use this to verify that areas outside the
868 // write are unaffected.
869 SkAutoPixmapStorage secondReadPM = read(dst);
870 if (!secondReadPM.addr()) {
871 // The first read succeeded so this one should, too.
872 ERRORF(reporter,
873 "could not read from dst (CT: %s, AT: %s)\n",
874 ToolUtils::colortype_name(dstCT),
875 ToolUtils::alphatype_name(dstAT));
876 return Result::kFail;
877 }
878
879 // Sometimes wider types go through 8bit unorm intermediates because of API
880 // restrictions.
881 int rgbBits = std::min({min_rgb_channel_bits(writeCT), min_rgb_channel_bits(dstCT), 8});
882 float tol = 2.f/(1 << rgbBits);
883 float alphaTol = 0;
884 if (writeAT != kOpaque_SkAlphaType && dstAT != kOpaque_SkAlphaType) {
885 // Alpha can also get squashed down to 8 bits going through an intermediate
886 // color format.
887 const int alphaBits = std::min({alpha_channel_bits(writeCT),
888 alpha_channel_bits(dstCT),
889 8});
890 alphaTol = 2.f/(1 << alphaBits);
891 }
892
893 const float tols[4] = {tol, tol, tol, alphaTol};
894 auto error = std::function<ComparePixmapsErrorReporter>([&](int x,
895 int y,
896 const float diffs[4]) {
897 SkASSERT(x >= 0 && y >= 0);
898 ERRORF(reporter,
899 "Write CT: %s, Write AT: %s, Dst CT: %s, Dst AT: %s, Rect [%d, %d, %d, %d]"
900 ", CS conversion: %d\n"
Brian Salomon2c673402021-04-02 14:36:58 -0400901 "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400902 ToolUtils::colortype_name(writeCT),
903 ToolUtils::alphatype_name(writeAT),
904 ToolUtils::colortype_name(dstCT),
905 ToolUtils::alphatype_name(dstAT),
906 rect.fLeft,
907 rect.fTop,
908 rect.fRight,
909 rect.fBottom,
910 csConversion,
911 x,
912 y,
913 diffs[0],
914 diffs[1],
915 diffs[2],
916 diffs[3]);
917 });
918
919 SkAutoPixmapStorage ref;
920 ref.alloc(secondReadPM.info().makeDimensions(checkRect.size()));
921 // Here we use the CPU backend to do the equivalent conversion as the write we're
922 // testing, using kUnpremul instead of kUnknown since CPU requires a valid alpha type.
923 SkAssertResult(make_pixmap_have_valid_alpha_type(srcPixels).readPixels(
924 make_pixmap_have_valid_alpha_type(ref),
925 std::max(0, -offset.fX),
926 std::max(0, -offset.fY)));
927 // This is the part of secondReadPixels that should have been updated by the write.
928 SkPixmap actual;
929 SkAssertResult(secondReadPM.extractSubset(&actual, checkRect));
930 ComparePixels(ref, actual, tols, error);
931 // The area around written rect should be the same in the first and second read.
932 SkIRect borders[]{
933 { 0, 0, secondReadPM.width(), secondReadPM.height()},
934 {checkRect.fRight, 0, checkRect.fLeft, secondReadPM.height()},
935 { checkRect.fLeft, 0, checkRect.fRight, checkRect.fTop},
936 { checkRect.fLeft, checkRect.fBottom, checkRect.fRight, secondReadPM.height()}
937 };
938 for (const auto r : borders) {
939 if (!r.isEmpty()) {
940 // Make a copy because MSVC for some reason doesn't correctly capture 'r'.
941 SkIPoint tl = r.topLeft();
942 auto guardError = std::function<ComparePixmapsErrorReporter>(
943 [&](int x, int y, const float diffs[4]) {
944 x += tl.x();
945 y += tl.y();
946 ERRORF(reporter,
947 "Write CT: %s, Write AT: %s, Dst CT: %s, Dst AT: %s,"
948 "Rect [%d, %d, %d, %d], CS conversion: %d\n"
Brian Salomon2c673402021-04-02 14:36:58 -0400949 "Error in guard region %d, %d. Diff in floats: (%f, %f, %f, %f)",
Brian Salomon1d2a26d2021-03-30 10:59:10 -0400950 ToolUtils::colortype_name(writeCT),
951 ToolUtils::alphatype_name(writeAT),
952 ToolUtils::colortype_name(dstCT),
953 ToolUtils::alphatype_name(dstAT),
954 rect.fLeft,
955 rect.fTop,
956 rect.fRight,
957 rect.fBottom,
958 csConversion,
959 x,
960 y,
961 diffs[0],
962 diffs[1],
963 diffs[2],
964 diffs[3]);
965 });
966 SkPixmap a, b;
967 SkAssertResult(firstReadPM.extractSubset(&a, r));
968 SkAssertResult(firstReadPM.extractSubset(&b, r));
969 float zeroTols[4] = {};
970 ComparePixels(a, b, zeroTols, guardError);
971 }
972 }
973 return result;
974 };
975
976 static constexpr int kW = 16;
977 static constexpr int kH = 16;
978
979 const std::vector<SkIRect> longRectArray = make_long_rect_array(kW, kH);
980 const std::vector<SkIRect> shortRectArray = make_short_rect_array(kW, kH);
981
982 // We ensure we use the long array once per src and read color type and otherwise use the
983 // short array to improve test run time.
984 // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
985 // equivalent. Just ensure each redundant AT is tested once with each CT (dst and write).
986 // Similarly, alpha-only color types behave the same for all alpha types so just test premul
987 // after one iter.
988 // We consider a dst or write CT thoroughly tested once it has run through the long rect array
989 // and full complement of alpha types with one successful read in the loop.
990 std::array<bool, kLastEnum_SkColorType + 1> dstCTTestedThoroughly = {},
991 writeCTTestedThoroughly = {};
992 for (int dat = 0; dat < kLastEnum_SkAlphaType; ++dat) {
993 const auto dstAT = static_cast<SkAlphaType>(dat);
994 for (int dct = 0; dct <= kLastEnum_SkColorType; ++dct) {
995 const auto dstCT = static_cast<SkColorType>(dct);
996 const auto dstInfo = SkImageInfo::Make(kW, kH, dstCT, dstAT, SkColorSpace::MakeSRGB());
997 auto dst = dstFactory(dstInfo);
998 if (!dst) {
999 continue;
1000 }
1001 if (SkColorTypeIsAlwaysOpaque(dstCT) && dstCTTestedThoroughly[dstCT] &&
1002 (kPremul_SkAlphaType == dstAT || kUnpremul_SkAlphaType == dstAT)) {
1003 continue;
1004 }
1005 if (SkColorTypeIsAlphaOnly(dstCT) && dstCTTestedThoroughly[dstCT] &&
1006 (kUnpremul_SkAlphaType == dstAT ||
1007 kOpaque_SkAlphaType == dstAT ||
1008 kUnknown_SkAlphaType == dstAT)) {
1009 continue;
1010 }
1011 for (int wct = 0; wct <= kLastEnum_SkColorType; ++wct) {
1012 const auto writeCT = static_cast<SkColorType>(wct);
1013 for (const sk_sp<SkColorSpace>& writeCS : {SkColorSpace::MakeSRGB(),
1014 SkColorSpace::MakeSRGBLinear()}) {
1015 for (int wat = 0; wat <= kLastEnum_SkAlphaType; ++wat) {
1016 const auto writeAT = static_cast<SkAlphaType>(wat);
1017 if (writeAT != kOpaque_SkAlphaType && dstAT == kOpaque_SkAlphaType) {
1018 // This doesn't make sense.
1019 continue;
1020 }
1021 if (SkColorTypeIsAlwaysOpaque(writeCT) &&
1022 writeCTTestedThoroughly[writeCT] &&
1023 (kPremul_SkAlphaType == writeAT || kUnpremul_SkAlphaType == writeAT)) {
1024 continue;
1025 }
1026 if (SkColorTypeIsAlphaOnly(writeCT) && writeCTTestedThoroughly[writeCT] &&
1027 (kUnpremul_SkAlphaType == writeAT ||
1028 kOpaque_SkAlphaType == writeAT ||
1029 kUnknown_SkAlphaType == writeAT)) {
1030 continue;
1031 }
1032 const auto& rects =
1033 dstCTTestedThoroughly[dct] && writeCTTestedThoroughly[wct]
1034 ? shortRectArray
1035 : longRectArray;
1036 for (const auto& rect : rects) {
1037 auto writeInfo = SkImageInfo::Make(rect.size(),
1038 writeCT,
1039 writeAT,
1040 writeCS);
1041 // CPU and GPU handle 1010102 differently. CPU clamps RGB to A, GPU
1042 // doesn't.
1043 bool forceOpaque = writeCT == kRGBA_1010102_SkColorType ||
1044 writeCT == kBGRA_1010102_SkColorType;
1045 SkAutoPixmapStorage writePixels = make_ref_data(writeInfo, forceOpaque);
1046 const SkIPoint offset = rect.topLeft();
1047 Result r = runTest(dst, dstInfo, writePixels, offset);
1048 if (r == Result::kSuccess) {
1049 dstCTTestedThoroughly[dct] = true;
1050 writeCTTestedThoroughly[wct] = true;
1051 }
1052 }
1053 }
1054 }
1055 }
1056 }
1057 }
1058}
1059
1060DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixels, reporter, ctxInfo) {
Robert Phillips53eaa642021-08-10 13:49:51 -04001061 using Surface = std::unique_ptr<skgpu::SurfaceContext>;
Brian Salomon1d2a26d2021-03-30 10:59:10 -04001062 GrDirectContext* direct = ctxInfo.directContext();
1063 auto writer = std::function<GpuWriteDstFn<Surface>>(
1064 [direct](const Surface& surface, const SkIPoint& offset, const SkPixmap& pixels) {
1065 if (surface->writePixels(direct, pixels, offset)) {
1066 return Result::kSuccess;
1067 } else {
1068 return Result::kFail;
1069 }
1070 });
1071 auto reader = std::function<GpuReadDstFn<Surface>>([direct](const Surface& s) {
1072 SkAutoPixmapStorage result;
1073 auto grInfo = s->imageInfo();
1074 SkColorType ct = GrColorTypeToSkColorType(grInfo.colorType());
1075 SkASSERT(ct != kUnknown_SkColorType);
1076 auto skInfo = SkImageInfo::Make(grInfo.dimensions(), ct, grInfo.alphaType(),
1077 grInfo.refColorSpace());
1078 result.alloc(skInfo);
1079 if (!s->readPixels(direct, result, {0, 0})) {
1080 SkAutoPixmapStorage badResult;
1081 return badResult;
1082 }
1083 return result;
1084 });
1085
1086 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
1087 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
1088 auto factory = std::function<GpuDstFactory<Surface>>(
1089 [direct, origin, renderable](const SkImageInfo& info) {
Robert Phillips168296b2021-08-16 11:41:27 -04001090 return CreateSurfaceContext(direct,
1091 info,
1092 SkBackingFit::kExact,
1093 origin,
1094 renderable);
Brian Salomon1d2a26d2021-03-30 10:59:10 -04001095 });
1096
1097 gpu_write_pixels_test_driver(reporter, factory, writer, reader);
1098 }
1099 }
1100}
Brian Salomon2c673402021-04-02 14:36:58 -04001101
1102DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceContextWritePixelsMipped, reporter, ctxInfo) {
1103 auto direct = ctxInfo.directContext();
1104 if (!direct->priv().caps()->mipmapSupport()) {
1105 return;
1106 }
1107 static constexpr int kW = 25,
1108 kH = 37;
1109 SkAutoPixmapStorage refP = make_ref_data(SkImageInfo::Make({kW, kH},
1110 kRGBA_F32_SkColorType,
1111 kPremul_SkAlphaType,
1112 nullptr),
1113 false);
1114 SkAutoPixmapStorage refO = make_ref_data(SkImageInfo::Make({kW, kH},
1115 kRGBA_F32_SkColorType,
1116 kOpaque_SkAlphaType,
1117 nullptr),
1118 true);
1119
1120 for (int c = 0; c < kGrColorTypeCnt; ++c) {
1121 auto ct = static_cast<GrColorType>(c);
Brian Salomon2c673402021-04-02 14:36:58 -04001122 // Below we use rendering to read the level pixels back.
1123 auto format = direct->priv().caps()->getDefaultBackendFormat(ct, GrRenderable::kYes);
1124 if (!format.isValid()) {
1125 continue;
1126 }
1127 SkAlphaType at = GrColorTypeHasAlpha(ct) ? kPremul_SkAlphaType : kOpaque_SkAlphaType;
1128 GrImageInfo info(ct, at, nullptr, kW, kH);
1129 SkTArray<GrCPixmap> levels;
1130 const auto& ref = at == kPremul_SkAlphaType ? refP : refO;
1131 for (int w = kW, h = kH; w || h; w/=2, h/=2) {
1132 auto level = GrPixmap::Allocate(info.makeWH(std::max(w, 1), std::max(h, 1)));
1133 SkPixmap src;
1134 SkAssertResult(ref.extractSubset(&src, SkIRect::MakeSize(level.dimensions())));
1135 SkAssertResult(GrConvertPixels(level, src));
1136 levels.push_back(level);
1137 }
1138
1139 for (bool unowned : {false, true}) { // test a GrCPixmap that doesn't own its storage.
1140 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
1141 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin,
1142 kBottomLeft_GrSurfaceOrigin}) {
Robert Phillips168296b2021-08-16 11:41:27 -04001143 auto sc = CreateSurfaceContext(direct,
1144 info,
1145 SkBackingFit::kExact,
1146 origin,
1147 renderable,
1148 /*sample count*/ 1,
1149 GrMipmapped::kYes);
Brian Salomon2c673402021-04-02 14:36:58 -04001150 if (!sc) {
1151 continue;
1152 }
1153 // Keeps pixels in unowned case alive until after writePixels is called but no
1154 // longer.
1155 GrPixmap keepAlive;
1156 GrCPixmap savedLevel = levels[1];
1157 if (unowned) {
1158 // Also test non-tight row bytes with the unowned pixmap, bump width by 1.
1159 int w = levels[1].width() + 1;
1160 int h = levels[1].height();
1161 keepAlive = GrPixmap::Allocate(levels[1].info().makeWH(w, h));
1162 SkPixmap src;
1163 // These pixel values will be the same as the original level 1.
1164 SkAssertResult(ref.extractSubset(&src, SkIRect::MakeWH(w, h)));
1165 SkAssertResult(GrConvertPixels(keepAlive, src));
1166 levels[1] = GrCPixmap(levels[1].info(),
1167 keepAlive.addr(),
1168 keepAlive.rowBytes());
1169 }
1170 // Going through intermediate textures is not supported for MIP levels (because
1171 // we don't support rendering to non-base levels). So it's hard to have any hard
1172 // rules about when we expect success.
1173 if (!sc->writePixels(direct, levels.begin(), levels.count())) {
1174 continue;
1175 }
1176 // Make sure the pixels from the unowned pixmap are released and then put the
1177 // original level back in for the comparison after the read below.
1178 keepAlive = {};
1179 levels[1] = savedLevel;
1180
1181 // TODO: Update this when read pixels supports reading back levels to read
1182 // directly rather than using minimizing draws.
Robert Phillips168296b2021-08-16 11:41:27 -04001183 auto dstSC = CreateSurfaceContext(direct,
1184 info,
1185 SkBackingFit::kExact,
1186 kBottomLeft_GrSurfaceOrigin,
1187 GrRenderable::kYes);
Robert Phillips1a2e7de2021-07-29 11:23:48 -04001188 SkASSERT(dstSC);
Brian Salomon2c673402021-04-02 14:36:58 -04001189 GrSamplerState sampler(SkFilterMode::kNearest, SkMipmapMode::kNearest);
1190 for (int i = 1; i <= 1; ++i) {
1191 auto te = GrTextureEffect::Make(sc->readSurfaceView(),
1192 info.alphaType(),
1193 SkMatrix::I(),
1194 sampler,
1195 *direct->priv().caps());
Robert Phillips1a2e7de2021-07-29 11:23:48 -04001196 dstSC->asFillContext()->fillRectToRectWithFP(
1197 SkIRect::MakeSize(sc->dimensions()),
1198 SkIRect::MakeSize(levels[i].dimensions()),
1199 std::move(te));
Brian Salomon2c673402021-04-02 14:36:58 -04001200 GrImageInfo readInfo =
Robert Phillips1a2e7de2021-07-29 11:23:48 -04001201 dstSC->imageInfo().makeDimensions(levels[i].dimensions());
Brian Salomon2c673402021-04-02 14:36:58 -04001202 GrPixmap read = GrPixmap::Allocate(readInfo);
Robert Phillips1a2e7de2021-07-29 11:23:48 -04001203 if (!dstSC->readPixels(direct, read, {0, 0})) {
Brian Salomon2c673402021-04-02 14:36:58 -04001204 continue;
1205 }
1206
1207 auto skCT = GrColorTypeToSkColorType(info.colorType());
1208 int rgbBits = std::min(min_rgb_channel_bits(skCT), 8);
1209 float rgbTol = 2.f / ((1 << rgbBits) - 1);
1210 int alphaBits = std::min(alpha_channel_bits(skCT), 8);
1211 float alphaTol = 2.f / ((1 << alphaBits) - 1);
1212 float tol[] = {rgbTol, rgbTol, rgbTol, alphaTol};
1213
1214 GrCPixmap a = levels[i];
1215 GrCPixmap b = read;
1216 // The compare code will linearize when reading the srgb data. This will
1217 // magnify differences at the high end. Rather than adjusting the tolerance
1218 // to compensate we do the comparison without going through srgb->linear.
1219 if (ct == GrColorType::kRGBA_8888_SRGB) {
1220 a = GrCPixmap(a.info().makeColorType(GrColorType::kRGBA_8888),
1221 a.addr(),
1222 a.rowBytes());
1223 b = GrCPixmap(b.info().makeColorType(GrColorType::kRGBA_8888),
1224 b.addr(),
1225 b.rowBytes());
1226 }
1227
1228 auto error = std::function<ComparePixmapsErrorReporter>(
1229 [&](int x, int y, const float diffs[4]) {
1230 SkASSERT(x >= 0 && y >= 0);
1231 ERRORF(reporter,
1232 "CT: %s, Level %d, Unowned: %d. "
1233 "Error at %d, %d. Diff in floats:"
1234 "(%f, %f, %f, %f)",
1235 GrColorTypeToStr(info.colorType()), i, unowned, x, y,
1236 diffs[0], diffs[1], diffs[2], diffs[3]);
1237 });
1238 ComparePixels(a, b, tol, error);
1239 }
1240 }
1241 }
1242 }
1243 }
1244}
Brian Salomon29578852021-08-02 10:18:16 -04001245
1246// Tests a bug found in OOP-R canvas2d in Chrome. The GPU backend would incorrectly not bind
1247// buffer 0 to GL_PIXEL_PACK_BUFFER before a glReadPixels() that was supposed to read into
1248// client memory if a GrDirectContext::resetContext() occurred.
1249DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(GLReadPixelsUnbindPBO, reporter, ctxInfo) {
1250 // Start with a async read so that we bind to GL_PIXEL_PACK_BUFFER.
1251 auto info = SkImageInfo::Make(16, 16, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
1252 SkAutoPixmapStorage pmap = make_ref_data(info, /*forceOpaque=*/false);
1253 auto image = SkImage::MakeFromRaster(pmap, nullptr, nullptr);
1254 image = image->makeTextureImage(ctxInfo.directContext());
1255 if (!image) {
1256 ERRORF(reporter, "Couldn't make texture image.");
1257 return;
1258 }
1259
1260 AsyncContext asyncContext;
1261 image->asyncRescaleAndReadPixels(info,
1262 SkIRect::MakeSize(info.dimensions()),
1263 SkImage::RescaleGamma::kSrc,
1264 SkImage::RescaleMode::kNearest,
1265 async_callback,
1266 &asyncContext);
1267
1268 // This will force the async readback to finish.
1269 ctxInfo.directContext()->flushAndSubmit(true);
1270 if (!asyncContext.fCalled) {
1271 ERRORF(reporter, "async_callback not called.");
1272 }
1273 if (!asyncContext.fResult) {
1274 ERRORF(reporter, "async read failed.");
1275 }
1276
1277 SkPixmap asyncResult(info, asyncContext.fResult->data(0), asyncContext.fResult->rowBytes(0));
1278
1279 // Bug was that this would cause GrGLGpu to think no buffer was left bound to
1280 // GL_PIXEL_PACK_BUFFER even though async transfer did leave one bound. So the sync read
1281 // wouldn't bind buffer 0.
1282 ctxInfo.directContext()->resetContext();
1283
1284 SkBitmap syncResult;
1285 syncResult.allocPixels(info);
1286 syncResult.eraseARGB(0xFF, 0xFF, 0xFF, 0xFF);
1287
1288 image->readPixels(ctxInfo.directContext(), syncResult.pixmap(), 0, 0);
1289
1290 float tol[4] = {}; // expect exactly same pixels, no conversions.
1291 auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
1292 const float diffs[4]) {
1293 SkASSERT(x >= 0 && y >= 0);
1294 ERRORF(reporter, "Expect sync and async read to be the same. "
1295 "Error at %d, %d. Diff in floats: (%f, %f, %f, %f)",
1296 x, y, diffs[0], diffs[1], diffs[2], diffs[3]);
1297 });
1298
1299 ComparePixels(syncResult.pixmap(), asyncResult, tol, error);
1300}