blob: dd5cf351e5d2204ef12762f684fbca68545c2b2e [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"
17#include "src/gpu/GrSurfaceContext.h"
18#include "tests/Test.h"
19#include "tests/TestUtils.h"
20#include "tools/ToolUtils.h"
21#include "tools/gpu/BackendTextureImageFactory.h"
22#include "tools/gpu/GrContextFactory.h"
23#include "tools/gpu/ProxyUtils.h"
24
25#include <initializer_list>
26
27static constexpr int min_rgb_channel_bits(SkColorType ct) {
28 switch (ct) {
29 case kUnknown_SkColorType: return 0;
30 case kAlpha_8_SkColorType: return 0;
31 case kA16_unorm_SkColorType: return 0;
32 case kA16_float_SkColorType: return 0;
33 case kRGB_565_SkColorType: return 5;
34 case kARGB_4444_SkColorType: return 4;
35 case kR8G8_unorm_SkColorType: return 8;
36 case kR16G16_unorm_SkColorType: return 16;
37 case kR16G16_float_SkColorType: return 16;
38 case kRGBA_8888_SkColorType: return 8;
39 case kRGB_888x_SkColorType: return 8;
40 case kBGRA_8888_SkColorType: return 8;
41 case kRGBA_1010102_SkColorType: return 10;
42 case kRGB_101010x_SkColorType: return 10;
43 case kBGRA_1010102_SkColorType: return 10;
44 case kBGR_101010x_SkColorType: return 10;
45 case kGray_8_SkColorType: return 8; // counting gray as "rgb"
46 case kRGBA_F16Norm_SkColorType: return 10; // just counting the mantissa
47 case kRGBA_F16_SkColorType: return 10; // just counting the mantissa
48 case kRGBA_F32_SkColorType: return 23; // just counting the mantissa
49 case kR16G16B16A16_unorm_SkColorType: return 16;
50 }
51 SkUNREACHABLE;
52}
53
54static constexpr int alpha_channel_bits(SkColorType ct) {
55 switch (ct) {
56 case kUnknown_SkColorType: return 0;
57 case kAlpha_8_SkColorType: return 8;
58 case kA16_unorm_SkColorType: return 16;
59 case kA16_float_SkColorType: return 16;
60 case kRGB_565_SkColorType: return 0;
61 case kARGB_4444_SkColorType: return 4;
62 case kR8G8_unorm_SkColorType: return 0;
63 case kR16G16_unorm_SkColorType: return 0;
64 case kR16G16_float_SkColorType: return 0;
65 case kRGBA_8888_SkColorType: return 8;
66 case kRGB_888x_SkColorType: return 0;
67 case kBGRA_8888_SkColorType: return 8;
68 case kRGBA_1010102_SkColorType: return 2;
69 case kRGB_101010x_SkColorType: return 0;
70 case kBGRA_1010102_SkColorType: return 2;
71 case kBGR_101010x_SkColorType: return 0;
72 case kGray_8_SkColorType: return 0;
73 case kRGBA_F16Norm_SkColorType: return 10; // just counting the mantissa
74 case kRGBA_F16_SkColorType: return 10; // just counting the mantissa
75 case kRGBA_F32_SkColorType: return 23; // just counting the mantissa
76 case kR16G16B16A16_unorm_SkColorType: return 16;
77 }
78 SkUNREACHABLE;
79}
80
81namespace {
82
83struct GpuReadPixelTestRules {
84 // Test unpremul sources? We could omit this and detect that creating the source of the read
85 // failed but having it lets us skip generating reference color data.
86 bool fAllowUnpremulSrc = true;
87 // Expect read function to succeed for kUnpremul?
88 bool fAllowUnpremulRead = true;
89 // Are reads that are overlapping but not contained by the src bounds expected to succeed?
90 bool fUncontainedRectSucceeds = true;
91};
92
93// Makes a src populated with the pixmap. The src should get its image info (or equivalent) from
94// the pixmap.
95template <typename T> using GpuSrcFactory = T(SkPixmap&);
96
Brian Salomon674d2162021-01-06 14:23:51 +000097enum class GpuReadResult {
Brian Salomonf84dfd62020-12-29 15:09:33 -050098 kFail,
99 kSuccess,
100 kExcusedFailure,
101};
102
103// Does a read from the T into the pixmap.
104template <typename T>
Brian Salomon674d2162021-01-06 14:23:51 +0000105using GpuReadSrcFn = GpuReadResult(const T&, const SkIVector& offset, const SkPixmap&);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500106
107} // anonymous namespace
108
109template <typename T>
110static void gpu_read_pixels_test_driver(skiatest::Reporter* reporter,
111 const GpuReadPixelTestRules& rules,
112 const std::function<GpuSrcFactory<T>>& srcFactory,
113 const std::function<GpuReadSrcFn<T>>& read) {
114 // Separate this out just to give it some line width to breathe. Note 'srcPixels' should have
115 // the same image info as src. We will do a converting readPixels() on it to get the data
116 // to compare with the results of 'read'.
117 auto runTest = [&](const T& src,
118 const SkPixmap& srcPixels,
119 const SkImageInfo& readInfo,
Brian Salomon674d2162021-01-06 14:23:51 +0000120 const SkIVector& offset) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500121 const bool csConversion =
122 !SkColorSpace::Equals(readInfo.colorSpace(), srcPixels.info().colorSpace());
123 const auto readCT = readInfo.colorType();
124 const auto readAT = readInfo.alphaType();
125 const auto srcCT = srcPixels.info().colorType();
126 const auto srcAT = srcPixels.info().alphaType();
127 const auto rect = SkIRect::MakeWH(readInfo.width(), readInfo.height()).makeOffset(offset);
128 const auto surfBounds = SkIRect::MakeWH(srcPixels.width(), srcPixels.height());
129 const size_t readBpp = SkColorTypeBytesPerPixel(readCT);
130
131 // Make the row bytes in the dst be loose for extra stress.
132 const size_t dstRB = readBpp * readInfo.width() + 10 * readBpp;
133 // This will make the last row tight.
134 const size_t dstSize = readInfo.computeByteSize(dstRB);
135 std::unique_ptr<char[]> dstData(new char[dstSize]);
136 SkPixmap dstPixels(readInfo, dstData.get(), dstRB);
137 // Initialize with an arbitrary value for each byte. Later we will check that only the
138 // correct part of the destination gets overwritten by 'read'.
139 static constexpr auto kInitialByte = static_cast<char>(0x1B);
140 std::fill_n(static_cast<char*>(dstPixels.writable_addr()),
141 dstPixels.computeByteSize(),
142 kInitialByte);
143
Brian Salomon674d2162021-01-06 14:23:51 +0000144 const GpuReadResult result = read(src, offset, dstPixels);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500145
146 if (!SkIRect::Intersects(rect, surfBounds)) {
Brian Salomon674d2162021-01-06 14:23:51 +0000147 REPORTER_ASSERT(reporter, result != GpuReadResult::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500148 } else if (readCT == kUnknown_SkColorType) {
Brian Salomon674d2162021-01-06 14:23:51 +0000149 REPORTER_ASSERT(reporter, result != GpuReadResult::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500150 } else if ((readAT == kUnknown_SkAlphaType) != (srcAT == kUnknown_SkAlphaType)) {
Brian Salomon674d2162021-01-06 14:23:51 +0000151 REPORTER_ASSERT(reporter, result != GpuReadResult::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500152 } else if (!rules.fUncontainedRectSucceeds && !surfBounds.contains(rect)) {
Brian Salomon674d2162021-01-06 14:23:51 +0000153 REPORTER_ASSERT(reporter, result != GpuReadResult::kSuccess);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500154 } else if (!rules.fAllowUnpremulRead && readAT == kUnpremul_SkAlphaType) {
Brian Salomon674d2162021-01-06 14:23:51 +0000155 REPORTER_ASSERT(reporter, result != GpuReadResult::kSuccess);
156 } else if (result == GpuReadResult::kFail) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500157 // TODO: Support RGB/BGR 101010x, BGRA 1010102 on the GPU.
158 if (SkColorTypeToGrColorType(readCT) != GrColorType::kUnknown) {
159 ERRORF(reporter,
160 "Read failed. Src CT: %s, Src AT: %s Read CT: %s, Read AT: %s, "
161 "Rect [%d, %d, %d, %d], CS conversion: %d\n",
162 ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
163 ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
164 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion);
165 }
166 return result;
167 }
168
169 bool guardOk = true;
170 auto guardCheck = [](char x) { return x == kInitialByte; };
171
172 // Considering the rect we tried to read and the surface bounds figure out which pixels in
173 // both src and dst space should actually have been read and written.
174 SkIRect srcReadRect;
Brian Salomon674d2162021-01-06 14:23:51 +0000175 if (result == GpuReadResult::kSuccess && srcReadRect.intersect(surfBounds, rect)) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500176 SkIRect dstWriteRect = srcReadRect.makeOffset(-rect.fLeft, -rect.fTop);
177
178 const bool lumConversion =
179 !(SkColorTypeChannelFlags(srcCT) & kGray_SkColorChannelFlag) &&
180 (SkColorTypeChannelFlags(readCT) & kGray_SkColorChannelFlag);
181 // A CS or luminance conversion allows a 3 value difference and otherwise a 2 value
182 // difference. Note that sometimes read back on GPU can be lossy even when there no
183 // conversion at all because GPU->CPU read may go to a lower bit depth format and then
184 // be promoted back to the original type. For example, GL ES cannot read to 1010102, so
185 // we go through 8888.
186 float numer = (lumConversion || csConversion) ? 3.f : 2.f;
187 // Allow some extra tolerance if unpremuling.
188 if (srcAT == kPremul_SkAlphaType && readAT == kUnpremul_SkAlphaType) {
189 numer += 1;
190 }
191 int rgbBits = std::min({min_rgb_channel_bits(readCT), min_rgb_channel_bits(srcCT), 8});
192 float tol = numer / (1 << rgbBits);
193 float alphaTol = 0;
194 if (readAT != kOpaque_SkAlphaType && srcAT != kOpaque_SkAlphaType) {
195 // Alpha can also get squashed down to 8 bits going through an intermediate
196 // color format.
197 const int alphaBits = std::min({alpha_channel_bits(readCT),
198 alpha_channel_bits(srcCT),
199 8});
200 alphaTol = 2.f / (1 << alphaBits);
201 }
202
203 const float tols[4] = {tol, tol, tol, alphaTol};
204 auto error = std::function<ComparePixmapsErrorReporter>([&](int x, int y,
205 const float diffs[4]) {
206 SkASSERT(x >= 0 && y >= 0);
207 ERRORF(reporter,
208 "Src CT: %s, Src AT: %s, Read CT: %s, Read AT: %s, Rect [%d, %d, %d, %d]"
209 ", CS conversion: %d\n"
210 "Error at %d, %d. Diff in floats: (%f, %f, %f %f)",
211 ToolUtils::colortype_name(srcCT), ToolUtils::alphatype_name(srcAT),
212 ToolUtils::colortype_name(readCT), ToolUtils::alphatype_name(readAT),
213 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom, csConversion, x, y,
214 diffs[0], diffs[1], diffs[2], diffs[3]);
215 });
216 SkAutoPixmapStorage ref;
217 SkImageInfo refInfo = readInfo.makeDimensions(dstWriteRect.size());
218 ref.alloc(refInfo);
219 if (readAT == kUnknown_SkAlphaType) {
220 // Do a spoofed read where src and dst alpha type are both kUnpremul. This will
221 // allow SkPixmap readPixels to succeed and won't do any alpha type conversion.
222 SkPixmap unpremulRef(refInfo.makeAlphaType(kUnpremul_SkAlphaType),
223 ref.addr(),
224 ref.rowBytes());
225 SkPixmap unpremulSRc(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
226 srcPixels.addr(),
227 srcPixels.rowBytes());
228
229 unpremulSRc.readPixels(unpremulRef, srcReadRect.x(), srcReadRect.y());
230 } else {
231 srcPixels.readPixels(ref, srcReadRect.x(), srcReadRect.y());
232 }
233 // This is the part of dstPixels that should have been updated.
234 SkPixmap actual;
235 SkAssertResult(dstPixels.extractSubset(&actual, dstWriteRect));
236 ComparePixels(ref, actual, tols, error);
237
238 const auto* v = dstData.get();
239 const auto* end = dstData.get() + dstSize;
240 guardOk = std::all_of(v, v + dstWriteRect.top() * dstPixels.rowBytes(), guardCheck);
241 v += dstWriteRect.top() * dstPixels.rowBytes();
242 for (int y = dstWriteRect.top(); y < dstWriteRect.bottom(); ++y) {
243 guardOk |= std::all_of(v, v + dstWriteRect.left() * readBpp, guardCheck);
244 auto pad = v + dstWriteRect.right() * readBpp;
245 auto rowEnd = std::min(end, v + dstPixels.rowBytes());
246 // min protects against reading past the end of the tight last row.
247 guardOk |= std::all_of(pad, rowEnd, guardCheck);
248 v = rowEnd;
249 }
250 guardOk |= std::all_of(v, end, guardCheck);
251 } else {
252 guardOk = std::all_of(dstData.get(), dstData.get() + dstSize, guardCheck);
253 }
254 if (!guardOk) {
255 ERRORF(reporter,
256 "Result pixels modified result outside read rect [%d, %d, %d, %d]. "
257 "Src CT: %s, Read CT: %s, CS conversion: %d",
258 rect.fLeft, rect.fTop, rect.fRight, rect.fBottom,
259 ToolUtils::colortype_name(srcCT), ToolUtils::colortype_name(readCT),
260 csConversion);
261 }
262 return result;
263 };
264
265 static constexpr int kW = 16;
266 static constexpr int kH = 16;
267
Brian Salomon674d2162021-01-06 14:23:51 +0000268 // Makes the reference data that is used to populate the src. Always F32 regardless of srcCT.
269 auto make_ref_f32_data = [](SkAlphaType srcAT, SkColorType srcCT) -> SkAutoPixmapStorage {
270 // Make src data in F32 with srcAT. We will convert it to each color type we test to
271 // initialize the src.
272 auto surfInfo = SkImageInfo::Make(kW, kH,
273 kRGBA_F32_SkColorType,
274 srcAT,
275 SkColorSpace::MakeSRGB());
276 // Can't make a kUnknown_SkAlphaType surface.
277 if (srcAT == kUnknown_SkAlphaType) {
278 surfInfo = surfInfo.makeAlphaType(kUnpremul_SkAlphaType);
279 }
280 auto refSurf = SkSurface::MakeRaster(surfInfo);
281 static constexpr SkPoint kPts1[] = {{0, 0}, {kW, kH}};
282 static constexpr SkColor kColors1[] = {SK_ColorGREEN, SK_ColorRED};
283 SkPaint paint;
284 paint.setShader(
285 SkGradientShader::MakeLinear(kPts1, kColors1, nullptr, 2, SkTileMode::kClamp));
286 refSurf->getCanvas()->drawPaint(paint);
287 static constexpr SkPoint kPts2[] = {{kW, 0}, {0, kH}};
288 static constexpr SkColor kColors2[] = {SK_ColorBLUE, SK_ColorBLACK};
289 paint.setShader(
290 SkGradientShader::MakeLinear(kPts2, kColors2, nullptr, 2, SkTileMode::kClamp));
291 paint.setBlendMode(SkBlendMode::kPlus);
292 refSurf->getCanvas()->drawPaint(paint);
293 // Keep everything opaque if the src alpha type is opaque. Also, there is an issue with
294 // 1010102 (the only color type where the number of alpha bits is non-zero and not the
295 // same as r, g, and b). Because of the different precisions the draw below can create
296 // data that isn't strictly premul (e.g. alpha is 1/3 but green is .4). SW will clamp
297 // r, g, b to a if the dst is premul and a different color type. GPU doesn't do this.
298 // We could but 1010102 premul is kind of dubious anyway. So for now just keep the data
299 // opaque.
300 if (srcAT != kOpaque_SkAlphaType &&
301 (srcAT == kPremul_SkAlphaType && srcCT != kRGBA_1010102_SkColorType &&
302 srcCT != kBGRA_1010102_SkColorType)) {
303 static constexpr SkColor kColors3[] = {SK_ColorWHITE,
304 SK_ColorWHITE,
305 0x60FFFFFF,
306 SK_ColorWHITE,
307 SK_ColorWHITE};
308 static constexpr SkScalar kPos3[] = {0.f, 0.15f, 0.5f, 0.85f, 1.f};
309 paint.setShader(SkGradientShader::MakeRadial({kW / 2.f, kH / 2.f}, (kW + kH) / 10.f,
310 kColors3, kPos3, 5, SkTileMode::kMirror));
311 paint.setBlendMode(SkBlendMode::kDstIn);
312 refSurf->getCanvas()->drawPaint(paint);
313 }
Brian Salomonf84dfd62020-12-29 15:09:33 -0500314
Brian Salomon674d2162021-01-06 14:23:51 +0000315 const auto srcInfo = SkImageInfo::Make(kW, kH, srcCT, srcAT, SkColorSpace::MakeSRGB());
316 SkAutoPixmapStorage srcPixels;
317 srcPixels.alloc(srcInfo);
318 SkPixmap readPixmap = srcPixels;
319 // Spoof the alpha type to kUnpremul so the read will succeed without doing any conversion
320 // (because we made our surface also be kUnpremul).
321 if (srcAT == kUnknown_SkAlphaType) {
322 readPixmap.reset(srcPixels.info().makeAlphaType(kUnpremul_SkAlphaType),
323 srcPixels.addr(),
324 srcPixels.rowBytes());
325 }
326 refSurf->readPixels(readPixmap, 0, 0);
327 return srcPixels;
328 };
329 const std::vector<SkIRect> longRectArray = {
330 // entire thing
331 SkIRect::MakeWH(kW, kH),
332 // larger on all sides
333 SkIRect::MakeLTRB(-10, -10, kW + 10, kH + 10),
334 // fully contained
335 SkIRect::MakeLTRB(kW / 4, kH / 4, 3 * kW / 4, 3 * kH / 4),
336 // outside top left
337 SkIRect::MakeLTRB(-10, -10, -1, -1),
338 // touching top left corner
339 SkIRect::MakeLTRB(-10, -10, 0, 0),
340 // overlapping top left corner
341 SkIRect::MakeLTRB(-10, -10, kW / 4, kH / 4),
342 // overlapping top left and top right corners
343 SkIRect::MakeLTRB(-10, -10, kW + 10, kH / 4),
344 // touching entire top edge
345 SkIRect::MakeLTRB(-10, -10, kW + 10, 0),
346 // overlapping top right corner
347 SkIRect::MakeLTRB(3 * kW / 4, -10, kW + 10, kH / 4),
348 // contained in x, overlapping top edge
349 SkIRect::MakeLTRB(kW / 4, -10, 3 * kW / 4, kH / 4),
350 // outside top right corner
351 SkIRect::MakeLTRB(kW + 1, -10, kW + 10, -1),
352 // touching top right corner
353 SkIRect::MakeLTRB(kW, -10, kW + 10, 0),
354 // overlapping top left and bottom left corners
355 SkIRect::MakeLTRB(-10, -10, kW / 4, kH + 10),
356 // touching entire left edge
357 SkIRect::MakeLTRB(-10, -10, 0, kH + 10),
358 // overlapping bottom left corner
359 SkIRect::MakeLTRB(-10, 3 * kH / 4, kW / 4, kH + 10),
360 // contained in y, overlapping left edge
361 SkIRect::MakeLTRB(-10, kH / 4, kW / 4, 3 * kH / 4),
362 // outside bottom left corner
363 SkIRect::MakeLTRB(-10, kH + 1, -1, kH + 10),
364 // touching bottom left corner
365 SkIRect::MakeLTRB(-10, kH, 0, kH + 10),
366 // overlapping bottom left and bottom right corners
367 SkIRect::MakeLTRB(-10, 3 * kH / 4, kW + 10, kH + 10),
368 // touching entire left edge
369 SkIRect::MakeLTRB(0, kH, kW, kH + 10),
370 // overlapping bottom right corner
371 SkIRect::MakeLTRB(3 * kW / 4, 3 * kH / 4, kW + 10, kH + 10),
372 // overlapping top right and bottom right corners
373 SkIRect::MakeLTRB(3 * kW / 4, -10, kW + 10, kH + 10),
374 };
375 const std::vector<SkIRect> shortRectArray = {
376 // entire thing
377 SkIRect::MakeWH(kW, kH),
378 // fully contained
379 SkIRect::MakeLTRB(kW / 4, kH / 4, 3 * kW / 4, 3 * kH / 4),
380 // overlapping top right corner
381 SkIRect::MakeLTRB(3 * kW / 4, -10, kW + 10, kH / 4),
382 };
Brian Salomonf84dfd62020-12-29 15:09:33 -0500383 // We ensure we use the long array once per src and read color type and otherwise use the
384 // short array to improve test run time.
385 // Also, some color types have no alpha values and thus Opaque Premul and Unpremul are
386 // equivalent. Just ensure each redundant AT is tested once with each CT (src and read).
387 // Similarly, alpha-only color types behave the same for all alpha types so just test premul
388 // after one iter.
Brian Salomon674d2162021-01-06 14:23:51 +0000389 // We consider a src or read CT thoroughly tested once it has run through the short rect array
Brian Salomonf84dfd62020-12-29 15:09:33 -0500390 // and full complement of alpha types with one successful read in the loop.
391 std::array<bool, kLastEnum_SkColorType + 1> srcCTTestedThoroughly = {},
392 readCTTestedThoroughly = {};
393 for (int sat = 0; sat < kLastEnum_SkAlphaType; ++sat) {
394 const auto srcAT = static_cast<SkAlphaType>(sat);
395 if (srcAT == kUnpremul_SkAlphaType && !rules.fAllowUnpremulSrc) {
396 continue;
397 }
398 for (int sct = 0; sct <= kLastEnum_SkColorType; ++sct) {
399 const auto srcCT = static_cast<SkColorType>(sct);
Brian Salomon674d2162021-01-06 14:23:51 +0000400 // Note that we only currently use srcCT for a 1010102 workaround. If we remove this we
401 // can also put the ref data setup above the srcCT loop.
402 SkAutoPixmapStorage srcPixels = make_ref_f32_data(srcAT, srcCT);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500403 auto src = srcFactory(srcPixels);
404 if (!src) {
405 continue;
406 }
407 if (SkColorTypeIsAlwaysOpaque(srcCT) && srcCTTestedThoroughly[srcCT] &&
408 (kPremul_SkAlphaType == srcAT || kUnpremul_SkAlphaType == srcAT)) {
409 continue;
410 }
411 if (SkColorTypeIsAlphaOnly(srcCT) && srcCTTestedThoroughly[srcCT] &&
412 (kUnpremul_SkAlphaType == srcAT ||
413 kOpaque_SkAlphaType == srcAT ||
414 kUnknown_SkAlphaType == srcAT)) {
415 continue;
416 }
417 for (int rct = 0; rct <= kLastEnum_SkColorType; ++rct) {
418 const auto readCT = static_cast<SkColorType>(rct);
419 for (const sk_sp<SkColorSpace>& readCS :
420 {SkColorSpace::MakeSRGB(), SkColorSpace::MakeSRGBLinear()}) {
421 for (int at = 0; at <= kLastEnum_SkAlphaType; ++at) {
422 const auto readAT = static_cast<SkAlphaType>(at);
423 if (srcAT != kOpaque_SkAlphaType && readAT == kOpaque_SkAlphaType) {
424 // This doesn't make sense.
425 continue;
426 }
427 if (SkColorTypeIsAlwaysOpaque(readCT) && readCTTestedThoroughly[readCT] &&
428 (kPremul_SkAlphaType == readAT || kUnpremul_SkAlphaType == readAT)) {
429 continue;
430 }
431 if (SkColorTypeIsAlphaOnly(readCT) && readCTTestedThoroughly[readCT] &&
432 (kUnpremul_SkAlphaType == readAT ||
433 kOpaque_SkAlphaType == readAT ||
434 kUnknown_SkAlphaType == readAT)) {
435 continue;
436 }
437 const auto& rects =
438 srcCTTestedThoroughly[sct] && readCTTestedThoroughly[rct]
439 ? shortRectArray
440 : longRectArray;
441 for (const auto& rect : rects) {
442 const auto readInfo = SkImageInfo::Make(rect.width(), rect.height(),
443 readCT, readAT, readCS);
Brian Salomon674d2162021-01-06 14:23:51 +0000444 const SkIVector offset = rect.topLeft();
445 GpuReadResult r = runTest(src, srcPixels, readInfo, offset);
446 if (r == GpuReadResult::kSuccess) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500447 srcCTTestedThoroughly[sct] = true;
448 readCTTestedThoroughly[rct] = true;
449 }
450 }
451 }
452 }
453 }
454 }
455 }
456}
457
458DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceContextReadPixels, reporter, ctxInfo) {
459 using Surface = std::unique_ptr<GrSurfaceContext>;
460 GrDirectContext* direct = ctxInfo.directContext();
461 auto reader = std::function<GpuReadSrcFn<Surface>>(
Brian Salomon674d2162021-01-06 14:23:51 +0000462 [direct](const Surface& surface, const SkIVector& offset, const SkPixmap& pixels) {
463 if (surface->readPixels(direct, pixels, {offset.fX, offset.fY})) {
464 return GpuReadResult::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500465 } else {
466 // Reading from a non-renderable format is not guaranteed to work on GL.
467 // We'd have to be able to force a copy or draw draw to a renderable format.
468 const auto& caps = *direct->priv().caps();
469 if (direct->backend() == GrBackendApi::kOpenGL &&
470 !caps.isFormatRenderable(surface->asSurfaceProxy()->backendFormat(), 1)) {
Brian Salomon674d2162021-01-06 14:23:51 +0000471 return GpuReadResult::kExcusedFailure;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500472 }
Brian Salomon674d2162021-01-06 14:23:51 +0000473 return GpuReadResult::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500474 }
475 });
476 GpuReadPixelTestRules rules;
477 rules.fAllowUnpremulSrc = true;
478 rules.fAllowUnpremulRead = true;
479 rules.fUncontainedRectSucceeds = true;
480
481 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
482 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
483 auto factory = std::function<GpuSrcFactory<Surface>>(
484 [direct, origin, renderable](const SkPixmap& src) {
485 if (src.colorType() == kRGB_888x_SkColorType) {
486 return Surface();
487 }
488 auto surfContext = GrSurfaceContext::Make(
489 direct, src.info(), SkBackingFit::kExact, origin, renderable);
490 if (surfContext) {
491 surfContext->writePixels(direct, src, {0, 0});
492 }
493 return surfContext;
494 });
495 gpu_read_pixels_test_driver(reporter, rules, factory, reader);
496 }
497 }
498}
499
500namespace {
501struct AsyncContext {
502 bool fCalled = false;
503 std::unique_ptr<const SkImage::AsyncReadResult> fResult;
504};
505} // anonymous namespace
506
507// Making this a lambda in the test functions caused:
508// "error: cannot compile this forwarded non-trivially copyable parameter yet"
509// on x86/Win/Clang bot, referring to 'result'.
510static void async_callback(void* c, std::unique_ptr<const SkImage::AsyncReadResult> result) {
511 auto context = static_cast<AsyncContext*>(c);
512 context->fResult = std::move(result);
513 context->fCalled = true;
514};
515
516DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SurfaceAsyncReadPixels, reporter, ctxInfo) {
517 using Surface = sk_sp<SkSurface>;
518 auto reader = std::function<GpuReadSrcFn<Surface>>(
Brian Salomon674d2162021-01-06 14:23:51 +0000519 [](const Surface& surface, const SkIVector& offset, const SkPixmap& pixels) {
Brian Salomonf84dfd62020-12-29 15:09:33 -0500520 auto direct = surface->recordingContext()->asDirectContext();
521 SkASSERT(direct);
522
523 AsyncContext context;
524 auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
525
526 // Rescale quality and linearity don't matter since we're doing a non-scaling
527 // readback.
Mike Reed1efa14d2021-01-02 21:44:59 -0500528 surface->asyncRescaleAndReadPixels(pixels.info(), rect,
529 SkImage::RescaleGamma::kSrc,
530 SkImage::RescaleMode::kNearest,
531 async_callback, &context);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500532 direct->submit();
533 while (!context.fCalled) {
534 direct->checkAsyncWorkCompletion();
535 }
536 if (!context.fResult) {
Brian Salomon674d2162021-01-06 14:23:51 +0000537 return GpuReadResult::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500538 }
539 SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), context.fResult->data(0),
540 context.fResult->rowBytes(0), pixels.info().minRowBytes(),
541 pixels.height());
Brian Salomon674d2162021-01-06 14:23:51 +0000542 return GpuReadResult::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500543 });
544 GpuReadPixelTestRules rules;
545 rules.fAllowUnpremulSrc = false;
546 rules.fAllowUnpremulRead = false;
547 rules.fUncontainedRectSucceeds = false;
548
549 for (GrSurfaceOrigin origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
550 auto factory = std::function<GpuSrcFactory<Surface>>(
551 [context = ctxInfo.directContext(), origin](const SkPixmap& src) {
552 if (src.colorType() == kRGB_888x_SkColorType) {
553 return Surface();
554 }
555 auto surf = SkSurface::MakeRenderTarget(context,
556 SkBudgeted::kYes,
557 src.info(),
558 0,
559 origin,
560 nullptr);
561 if (surf) {
562 surf->writePixels(src, 0, 0);
563 }
564 return surf;
565 });
566 gpu_read_pixels_test_driver(reporter, rules, factory, reader);
567 }
568}
569
570DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ImageAsyncReadPixels, reporter, ctxInfo) {
571 using Image = sk_sp<SkImage>;
572 auto context = ctxInfo.directContext();
573 auto reader = std::function<GpuReadSrcFn<Image>>([context](const Image& image,
Brian Salomon674d2162021-01-06 14:23:51 +0000574 const SkIVector& offset,
Brian Salomonf84dfd62020-12-29 15:09:33 -0500575 const SkPixmap& pixels) {
576 AsyncContext asyncContext;
577 auto rect = SkIRect::MakeSize(pixels.dimensions()).makeOffset(offset);
578 // The GPU implementation is based on rendering and will fail for non-renderable color
579 // types.
580 auto ct = SkColorTypeToGrColorType(image->colorType());
581 auto format = context->priv().caps()->getDefaultBackendFormat(ct, GrRenderable::kYes);
582 if (!context->priv().caps()->isFormatAsColorTypeRenderable(ct, format)) {
Brian Salomon674d2162021-01-06 14:23:51 +0000583 return GpuReadResult::kExcusedFailure;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500584 }
585
586 // Rescale quality and linearity don't matter since we're doing a non-scaling readback.
Mike Reed1efa14d2021-01-02 21:44:59 -0500587 image->asyncRescaleAndReadPixels(pixels.info(), rect,
588 SkImage::RescaleGamma::kSrc,
589 SkImage::RescaleMode::kNearest,
590 async_callback, &asyncContext);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500591 context->submit();
592 while (!asyncContext.fCalled) {
593 context->checkAsyncWorkCompletion();
594 }
595 if (!asyncContext.fResult) {
Brian Salomon674d2162021-01-06 14:23:51 +0000596 return GpuReadResult::kFail;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500597 }
598 SkRectMemcpy(pixels.writable_addr(), pixels.rowBytes(), asyncContext.fResult->data(0),
599 asyncContext.fResult->rowBytes(0), pixels.info().minRowBytes(),
600 pixels.height());
Brian Salomon674d2162021-01-06 14:23:51 +0000601 return GpuReadResult::kSuccess;
Brian Salomonf84dfd62020-12-29 15:09:33 -0500602 });
603
604 GpuReadPixelTestRules rules;
605 rules.fAllowUnpremulSrc = true;
606 // GPU doesn't support reading to kUnpremul because the rescaling works by rendering and now
607 // we only support premul rendering.
608 rules.fAllowUnpremulRead = false;
609 rules.fUncontainedRectSucceeds = false;
610
611 for (auto origin : {kTopLeft_GrSurfaceOrigin, kBottomLeft_GrSurfaceOrigin}) {
612 for (auto renderable : {GrRenderable::kNo, GrRenderable::kYes}) {
613 auto factory = std::function<GpuSrcFactory<Image>>([&](const SkPixmap& src) {
614 if (src.colorType() == kRGB_888x_SkColorType) {
615 return Image();
616 }
617 return sk_gpu_test::MakeBackendTextureImage(ctxInfo.directContext(), src,
618 renderable, origin);
619 });
620 gpu_read_pixels_test_driver(reporter, rules, factory, reader);
621 }
622 }
623}
624
625DEF_GPUTEST(AsyncReadPixelsContextShutdown, reporter, options) {
626 const auto ii = SkImageInfo::Make(10, 10, kRGBA_8888_SkColorType, kPremul_SkAlphaType,
627 SkColorSpace::MakeSRGB());
628 enum class ShutdownSequence {
629 kFreeResult_DestroyContext,
630 kDestroyContext_FreeResult,
631 kFreeResult_ReleaseAndAbandon_DestroyContext,
632 kFreeResult_Abandon_DestroyContext,
633 kReleaseAndAbandon_FreeResult_DestroyContext,
634 kAbandon_FreeResult_DestroyContext,
635 kReleaseAndAbandon_DestroyContext_FreeResult,
636 kAbandon_DestroyContext_FreeResult,
637 };
638 for (int t = 0; t < sk_gpu_test::GrContextFactory::kContextTypeCnt; ++t) {
639 auto type = static_cast<sk_gpu_test::GrContextFactory::ContextType>(t);
640 for (auto sequence : {ShutdownSequence::kFreeResult_DestroyContext,
641 ShutdownSequence::kDestroyContext_FreeResult,
642 ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext,
643 ShutdownSequence::kFreeResult_Abandon_DestroyContext,
644 ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext,
645 ShutdownSequence::kAbandon_FreeResult_DestroyContext,
646 ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult,
647 ShutdownSequence::kAbandon_DestroyContext_FreeResult}) {
648 // Vulkan context abandoning without resource release has issues outside of the scope of
649 // this test.
650 if (type == sk_gpu_test::GrContextFactory::kVulkan_ContextType &&
651 (sequence == ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext ||
652 sequence == ShutdownSequence::kFreeResult_Abandon_DestroyContext ||
653 sequence == ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext ||
654 sequence == ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult ||
655 sequence == ShutdownSequence::kAbandon_FreeResult_DestroyContext ||
656 sequence == ShutdownSequence::kAbandon_DestroyContext_FreeResult)) {
657 continue;
658 }
659 for (bool yuv : {false, true}) {
660 sk_gpu_test::GrContextFactory factory(options);
661 auto direct = factory.get(type);
662 if (!direct) {
663 continue;
664 }
665 // This test is only meaningful for contexts that support transfer buffers for
666 // reads.
667 if (!direct->priv().caps()->transferFromSurfaceToBufferSupport()) {
668 continue;
669 }
670 auto surf = SkSurface::MakeRenderTarget(direct, SkBudgeted::kYes, ii, 1, nullptr);
671 if (!surf) {
672 continue;
673 }
674 AsyncContext cbContext;
675 if (yuv) {
676 surf->asyncRescaleAndReadPixelsYUV420(
677 kIdentity_SkYUVColorSpace, SkColorSpace::MakeSRGB(), ii.bounds(),
Mike Reed1efa14d2021-01-02 21:44:59 -0500678 ii.dimensions(), SkImage::RescaleGamma::kSrc,
679 SkImage::RescaleMode::kNearest, &async_callback, &cbContext);
Brian Salomonf84dfd62020-12-29 15:09:33 -0500680 } else {
681 surf->asyncRescaleAndReadPixels(ii, ii.bounds(), SkImage::RescaleGamma::kSrc,
Mike Reed1efa14d2021-01-02 21:44:59 -0500682 SkImage::RescaleMode::kNearest, &async_callback,
Brian Salomonf84dfd62020-12-29 15:09:33 -0500683 &cbContext);
684 }
685 direct->submit();
686 while (!cbContext.fCalled) {
687 direct->checkAsyncWorkCompletion();
688 }
689 if (!cbContext.fResult) {
690 ERRORF(reporter, "Callback failed on %s. is YUV: %d",
691 sk_gpu_test::GrContextFactory::ContextTypeName(type), yuv);
692 continue;
693 }
694 // For vulkan we need to release all refs to the GrDirectContext before trying to
695 // destroy the test context. The surface here is holding a ref.
696 surf.reset();
697
698 // The real test is that we don't crash, get Vulkan validation errors, etc, during
699 // this shutdown sequence.
700 switch (sequence) {
701 case ShutdownSequence::kFreeResult_DestroyContext:
702 case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
703 case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
704 break;
705 case ShutdownSequence::kDestroyContext_FreeResult:
706 factory.destroyContexts();
707 break;
708 case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
709 factory.releaseResourcesAndAbandonContexts();
710 break;
711 case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
712 factory.abandonContexts();
713 break;
714 case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
715 factory.releaseResourcesAndAbandonContexts();
716 factory.destroyContexts();
717 break;
718 case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
719 factory.abandonContexts();
720 factory.destroyContexts();
721 break;
722 }
723 cbContext.fResult.reset();
724 switch (sequence) {
725 case ShutdownSequence::kFreeResult_ReleaseAndAbandon_DestroyContext:
726 factory.releaseResourcesAndAbandonContexts();
727 break;
728 case ShutdownSequence::kFreeResult_Abandon_DestroyContext:
729 factory.abandonContexts();
730 break;
731 case ShutdownSequence::kFreeResult_DestroyContext:
732 case ShutdownSequence::kDestroyContext_FreeResult:
733 case ShutdownSequence::kReleaseAndAbandon_FreeResult_DestroyContext:
734 case ShutdownSequence::kAbandon_FreeResult_DestroyContext:
735 case ShutdownSequence::kReleaseAndAbandon_DestroyContext_FreeResult:
736 case ShutdownSequence::kAbandon_DestroyContext_FreeResult:
737 break;
738 }
739 }
740 }
741 }
742}