Debian Codegraph @

dm/DMSrcSink.cpp

raw
1 /*
2 * Copyright 2015 Google Inc.
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 "dm/DMSrcSink.h"
9 #include "include/codec/SkAndroidCodec.h"
10 #include "include/codec/SkCodec.h"
11 #include "include/codec/SkPixmapUtils.h"
12 #include "include/core/SkColorSpace.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkDocument.h"
15 #include "include/core/SkExecutor.h"
16 #include "include/core/SkImageGenerator.h"
17 #include "include/core/SkMallocPixelRef.h"
18 #include "include/core/SkPictureRecorder.h"
19 #include "include/core/SkSerialProcs.h"
20 #include "include/core/SkStream.h"
21 #include "include/core/SkString.h"
22 #include "include/core/SkSurface.h"
23 #include "include/core/SkSurfaceProps.h"
24 #include "include/docs/SkMultiPictureDocument.h"
25 #include "include/docs/SkPDFDocument.h"
26 #include "include/docs/SkPDFJpegHelpers.h"
27 #include "include/encode/SkPngEncoder.h"
28 #include "include/gpu/ganesh/GrBackendSurface.h"
29 #include "include/gpu/ganesh/GrDirectContext.h"
30 #include "include/gpu/ganesh/SkImageGanesh.h"
31 #include "include/gpu/ganesh/SkSurfaceGanesh.h"
32 #include "include/private/base/SkTLogic.h"
33 #include "include/private/chromium/GrDeferredDisplayList.h"
34 #include "include/private/chromium/GrSurfaceCharacterization.h"
35 #include "include/utils/SkNullCanvas.h"
36 #include "include/utils/SkPaintFilterCanvas.h"
37 #include "modules/skcms/skcms.h"
38 #include "modules/skottie/utils/SkottieUtils.h"
39 #include "modules/skshaper/utils/FactoryHelpers.h"
40 #include "src/base/SkAutoMalloc.h"
41 #include "src/base/SkRandom.h"
42 #include "src/base/SkTLazy.h"
43 #include "src/codec/SkCodecImageGenerator.h"
44 #include "src/core/SkAutoPixmapStorage.h"
45 #include "src/core/SkImageInfoPriv.h"
46 #include "src/core/SkOSFile.h"
47 #include "src/core/SkPictureData.h"
48 #include "src/core/SkPicturePriv.h"
49 #include "src/core/SkRecordCanvas.h"
50 #include "src/core/SkRecordDraw.h"
51 #include "src/core/SkSwizzlePriv.h"
52 #include "src/core/SkTaskGroup.h"
53 #include "src/gpu/ganesh/GrDirectContextPriv.h"
54 #include "src/gpu/ganesh/GrGpu.h"
55 #include "src/gpu/ganesh/image/GrImageUtils.h"
56 #include "src/image/SkImage_Base.h"
57 #include "src/utils/SkJSONWriter.h"
58 #include "src/utils/SkMultiPictureDocumentPriv.h"
59 #include "src/utils/SkOSPath.h"
60 #include "tools/DeserialProcsUtils.h"
61 #include "tools/EncodeUtils.h"
62 #include "tools/GpuToolUtils.h"
63 #include "tools/Resources.h"
64 #include "tools/RuntimeBlendUtils.h"
65 #include "tools/ToolUtils.h"
66 #include "tools/UrlDataManager.h"
67 #include "tools/debugger/DebugCanvas.h"
68 #include "tools/fonts/FontToolUtils.h"
69 #include "tools/ganesh/DDLPromiseImageHelper.h"
70 #include "tools/ganesh/DDLTileHelper.h"
71 #include "tools/ganesh/MemoryCache.h"
72 #include "tools/ganesh/TestCanvas.h"
73 #include "tools/gpu/BackendSurfaceFactory.h"
74
75 #if defined(SK_BUILD_FOR_ANDROID)
76 #include "include/ports/SkImageGeneratorNDK.h"
77 #endif
78
79 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
80 #include "include/ports/SkImageGeneratorCG.h"
81 #endif
82
83 #if defined(SK_BUILD_FOR_WIN)
84 #include "include/docs/SkXPSDocument.h"
85 #include "include/ports/SkImageGeneratorWIC.h"
86 #include "src/utils/win/SkAutoCoInitialize.h"
87 #include "src/utils/win/SkHRESULT.h"
88 #include "src/utils/win/SkTScopedComPtr.h"
89
90 #include <XpsObjectModel.h>
91 #endif
92
93 #if defined(SK_ENABLE_SKOTTIE)
94 #include "modules/skottie/include/Skottie.h"
95 #include "modules/skresources/include/SkResources.h"
96 #endif
97
98 #if defined(SK_ENABLE_SVG)
99 #include "include/svg/SkSVGCanvas.h"
100 #include "modules/svg/include/SkSVGDOM.h"
101 #include "modules/svg/include/SkSVGNode.h"
102 #include "src/xml/SkXMLWriter.h"
103 #endif
104
105 #if defined(SK_GRAPHITE)
106 #include "include/gpu/graphite/Context.h"
107 #include "include/gpu/graphite/ContextOptions.h"
108 #include "include/gpu/graphite/Recorder.h"
109 #include "include/gpu/graphite/Recording.h"
110 #include "include/gpu/graphite/Surface.h"
111 #include "src/gpu/graphite/ContextOptionsPriv.h"
112 // TODO: Remove this src include once we figure out public readPixels call for Graphite.
113 #include "src/gpu/graphite/Surface_Graphite.h"
114 #include "tools/graphite/ContextFactory.h"
115 #include "tools/graphite/GraphiteTestContext.h"
116 #include "tools/graphite/GraphiteToolUtils.h"
117 #include "tools/graphite/PipelineCallbackHandler.h"
118
119 #if defined(SK_ENABLE_PRECOMPILE)
120 #include "src/gpu/graphite/Caps.h"
121 #include "src/gpu/graphite/ContextPriv.h"
122 #include "src/gpu/graphite/GraphicsPipeline.h"
123 #include "src/gpu/graphite/GraphicsPipelineDesc.h"
124 #include "src/gpu/graphite/PrecompileContextPriv.h"
125 #include "src/gpu/graphite/RecorderPriv.h"
126 #include "src/gpu/graphite/RenderPassDesc.h"
127 #include "src/gpu/graphite/RendererProvider.h"
128 #include "tools/graphite/UniqueKeyUtils.h"
129 #endif // SK_ENABLE_PRECOMPILE
130
131 #endif // SK_GRAPHITE
132
133
134 #if defined(SK_ENABLE_ANDROID_UTILS)
135 #include "client_utils/android/BitmapRegionDecoder.h"
136 #endif
137
138 #if defined(SK_CODEC_ENCODES_PNG_WITH_LIBPNG)
139 #include "include/encode/SkPngEncoder.h"
140 #endif
141
142 #if defined(SK_CODEC_ENCODES_PNG_WITH_RUST)
143 #include "include/encode/SkPngRustEncoder.h"
144 #endif
145
146 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
147 #include "include/codec/SkPngRustDecoder.h"
148 #else
149 #include "include/codec/SkPngDecoder.h"
150 #endif
151
152 #include <cmath>
153 #include <functional>
154
155 using namespace skia_private;
156
157 static DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
158 static DEFINE_int(mskpFrame, 0, "Which MSKP frame to draw?");
159
160 DECLARE_int(gpuThreads)
161
162 #if defined(SK_GANESH)
163 using sk_gpu_test::GrContextFactory;
164 using sk_gpu_test::ContextInfo;
165 #endif
166
167 namespace DM {
168
169 GMSrc::GMSrc(skiagm::GMFactory factory) : fFactory(factory) {}
170
171 Result GMSrc::draw(SkCanvas* canvas, GraphiteTestContext* testContext) const {
172 std::unique_ptr<skiagm::GM> gm(fFactory());
173 SkString msg;
174
175 skiagm::DrawResult gpuSetupResult = gm->gpuSetup(canvas, &msg, testContext);
176 switch (gpuSetupResult) {
177 case skiagm::DrawResult::kOk : break;
178 case skiagm::DrawResult::kFail: return Result(Result::Status::Fatal, msg);
179 case skiagm::DrawResult::kSkip: return Result(Result::Status::Skip, msg);
180 default: SK_ABORT("");
181 }
182
183 skiagm::DrawResult drawResult = gm->draw(canvas, &msg);
184 switch (drawResult) {
185 case skiagm::DrawResult::kOk : return Result(Result::Status::Ok, msg);
186 case skiagm::DrawResult::kFail: return Result(Result::Status::Fatal, msg);
187 case skiagm::DrawResult::kSkip: return Result(Result::Status::Skip, msg);
188 default: SK_ABORT("");
189 }
190
191 // Note: we don't call "gpuTeardown" here because, when testing DDL recording, we want
192 // the gpu-backed images to live past the lifetime of the GM.
193 }
194
195 SkISize GMSrc::size() const {
196 std::unique_ptr<skiagm::GM> gm(fFactory());
197 return gm->getISize();
198 }
199
200 Name GMSrc::name() const {
201 std::unique_ptr<skiagm::GM> gm(fFactory());
202 return gm->getName();
203 }
204
205 void GMSrc::modifySurfaceProps(SkSurfaceProps* props) const {
206 std::unique_ptr<skiagm::GM> gm(fFactory());
207 gm->modifySurfaceProps(props);
208 }
209
210 void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
211 std::unique_ptr<skiagm::GM> gm(fFactory());
212 gm->modifyGrContextOptions(options);
213 }
214
215 #if defined(SK_GRAPHITE)
216 void GMSrc::modifyGraphiteContextOptions(skgpu::graphite::ContextOptions* options) const {
217 std::unique_ptr<skiagm::GM> gm(fFactory());
218 gm->modifyGraphiteContextOptions(options);
219 }
220 #endif
221
222 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
223
224 static SkString get_scaled_name(const Path& path, float scale) {
225 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
226 }
227
228 #ifdef SK_ENABLE_ANDROID_UTILS
229 BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
230 : fPath(path)
231 , fMode(mode)
232 , fDstColorType(dstColorType)
233 , fSampleSize(sampleSize)
234 {}
235
236 bool BRDSrc::veto(SinkFlags flags) const {
237 // No need to test to non-raster or indirect backends.
238 return flags.type != SinkFlags::kRaster
239 || flags.approach != SinkFlags::kDirect;
240 }
241
242 static std::unique_ptr<android::skia::BitmapRegionDecoder> create_brd(Path path) {
243 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
244 return android::skia::BitmapRegionDecoder::Make(encoded);
245 }
246
247 static inline void alpha8_to_gray8(SkBitmap* bitmap) {
248 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
249 // them back to kGray8 so our test framework can draw them correctly.
250 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
251 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
252 .makeAlphaType(kOpaque_SkAlphaType);
253 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
254 }
255 }
256
257 Result BRDSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
258 SkColorType colorType = canvas->imageInfo().colorType();
259 if (kRGB_565_SkColorType == colorType &&
260 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType)
261 {
262 return Result::Skip("Testing non-565 to 565 is uninteresting.");
263 }
264 switch (fDstColorType) {
265 case CodecSrc::kGetFromCanvas_DstColorType:
266 break;
267 case CodecSrc::kGrayscale_Always_DstColorType:
268 colorType = kGray_8_SkColorType;
269 break;
270 default:
271 SkASSERT(false);
272 break;
273 }
274
275 auto brd = create_brd(fPath);
276 if (nullptr == brd) {
277 return Result::Skip("Could not create brd for %s.", fPath.c_str());
278 }
279
280 auto recommendedCT = brd->computeOutputColorType(colorType);
281 if (kRGB_565_SkColorType == colorType && recommendedCT != colorType) {
282 return Result::Skip("Skip decoding non-opaque to 565.");
283 }
284 colorType = recommendedCT;
285
286 auto colorSpace = brd->computeOutputColorSpace(colorType, nullptr);
287
288 const uint32_t width = brd->width();
289 const uint32_t height = brd->height();
290 // Visually inspecting very small output images is not necessary.
291 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
292 return Result::Skip("Scaling very small images is uninteresting.");
293 }
294 switch (fMode) {
295 case kFullImage_Mode: {
296 SkBitmap bitmap;
297 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
298 fSampleSize, colorType, false, colorSpace)) {
299 return Result::Fatal("Cannot decode (full) region.");
300 }
301 alpha8_to_gray8(&bitmap);
302
303 canvas->drawImage(bitmap.asImage(), 0, 0);
304 return Result::Ok();
305 }
306 case kDivisor_Mode: {
307 const uint32_t divisor = 2;
308 if (width < divisor || height < divisor) {
309 return Result::Skip("Divisor is larger than image dimension.");
310 }
311
312 // Use a border to test subsets that extend outside the image.
313 // We will not allow the border to be larger than the image dimensions. Allowing
314 // these large borders causes off by one errors that indicate a problem with the
315 // test suite, not a problem with the implementation.
316 const uint32_t maxBorder = std::min(width, height) / (fSampleSize * divisor);
317 const uint32_t scaledBorder = std::min(5u, maxBorder);
318 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
319
320 // We may need to clear the canvas to avoid uninitialized memory.
321 // Assume we are scaling a 780x780 image with sampleSize = 8.
322 // The output image should be 97x97.
323 // Each subset will be 390x390.
324 // Each scaled subset be 48x48.
325 // Four scaled subsets will only fill a 96x96 image.
326 // The bottom row and last column will not be touched.
327 // This is an unfortunate result of our rounding rules when scaling.
328 // Maybe we need to consider testing scaled subsets without trying to
329 // combine them to match the full scaled image? Or maybe this is the
330 // best we can do?
331 canvas->clear(0);
332
333 for (uint32_t x = 0; x < divisor; x++) {
334 for (uint32_t y = 0; y < divisor; y++) {
335 // Calculate the subset dimensions
336 uint32_t subsetWidth = width / divisor;
337 uint32_t subsetHeight = height / divisor;
338 const int left = x * subsetWidth;
339 const int top = y * subsetHeight;
340
341 // Increase the size of the last subset in each row or column, when the
342 // divisor does not divide evenly into the image dimensions
343 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
344 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
345
346 // Increase the size of the subset in order to have a border on each side
347 const int decodeLeft = left - unscaledBorder;
348 const int decodeTop = top - unscaledBorder;
349 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
350 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
351 SkBitmap bitmap;
352 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
353 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
354 colorSpace)) {
355 return Result::Fatal("Cannot decode region.");
356 }
357
358 alpha8_to_gray8(&bitmap);
359 canvas->drawImageRect(bitmap.asImage().get(),
360 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
361 (SkScalar) (subsetWidth / fSampleSize),
362 (SkScalar) (subsetHeight / fSampleSize)),
363 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
364 (SkScalar) (top / fSampleSize),
365 (SkScalar) (subsetWidth / fSampleSize),
366 (SkScalar) (subsetHeight / fSampleSize)),
367 SkSamplingOptions(), nullptr,
368 SkCanvas::kStrict_SrcRectConstraint);
369 }
370 }
371 return Result::Ok();
372 }
373 default:
374 SkASSERT(false);
375 return Result::Fatal("Error: Should not be reached.");
376 }
377 }
378
379 SkISize BRDSrc::size() const {
380 auto brd = create_brd(fPath);
381 if (brd) {
382 return {std::max(1, brd->width() / (int)fSampleSize),
383 std::max(1, brd->height() / (int)fSampleSize)};
384 }
385 return {0, 0};
386 }
387
388 Name BRDSrc::name() const {
389 // We will replicate the names used by CodecSrc so that images can
390 // be compared in Gold.
391 if (1 == fSampleSize) {
392 return SkOSPath::Basename(fPath.c_str());
393 }
394 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
395 }
396
397 #endif // SK_ENABLE_ANDROID_UTILS
398
399 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
400
401 static bool serial_from_path_name(const SkString& path) {
402 if (!FLAGS_RAW_threading) {
403 static const char* const exts[] = {
404 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
405 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
406 };
407 const char* actualExt = strrchr(path.c_str(), '.');
408 if (actualExt) {
409 actualExt++;
410 for (auto* ext : exts) {
411 if (0 == strcmp(ext, actualExt)) {
412 return true;
413 }
414 }
415 }
416 }
417 return false;
418 }
419
420 CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
421 float scale)
422 : fPath(path)
423 , fMode(mode)
424 , fDstColorType(dstColorType)
425 , fDstAlphaType(dstAlphaType)
426 , fScale(scale)
427 , fRunSerially(serial_from_path_name(path))
428 {}
429
430 bool CodecSrc::veto(SinkFlags flags) const {
431 // Test to direct raster backends (8888 and 565).
432 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
433 }
434
435 // Allows us to test decodes to non-native 8888.
436 static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
437 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
438 return;
439 }
440
441 for (int y = 0; y < bitmap.height(); y++) {
442 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
443 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
444 }
445 }
446
447 static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
448 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
449 switch (dstColorType) {
450 case CodecSrc::kGrayscale_Always_DstColorType:
451 if (kRGB_565_SkColorType == canvasColorType) {
452 return false;
453 }
454 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
455 break;
456 case CodecSrc::kNonNative8888_Always_DstColorType:
457 if (kRGB_565_SkColorType == canvasColorType
458 || kRGBA_F16_SkColorType == canvasColorType) {
459 return false;
460 }
461 #ifdef SK_PMCOLOR_IS_RGBA
462 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
463 #else
464 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
465 #endif
466 break;
467 default:
468 if (kRGB_565_SkColorType == canvasColorType &&
469 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
470 return false;
471 }
472
473 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
474 break;
475 }
476
477 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
478 return true;
479 }
480
481 static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
482 CodecSrc::DstColorType dstColorType,
483 SkScalar left = 0, SkScalar top = 0) {
484 SkBitmap bitmap;
485 bitmap.installPixels(info, pixels, rowBytes);
486 swap_rb_if_necessary(bitmap, dstColorType);
487 canvas->drawImage(bitmap.asImage(), left, top);
488 }
489
490 // For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
491 // color format conversions should be performed by the codec. Sometimes the output of the
492 // decode will be in an interesting color space. On our srgb and f16 backends, we need to
493 // "pretend" that the color space is standard sRGB to avoid triggering color conversion
494 // at draw time.
495 static void set_bitmap_color_space(SkImageInfo* info) {
496 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
497 }
498
499 Result CodecSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
500 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
501 if (!encoded) {
502 return Result::Fatal("Couldn't read %s.", fPath.c_str());
503 }
504
505 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
506 if (nullptr == codec) {
507 return Result::Fatal("Couldn't create codec for %s.", fPath.c_str());
508 }
509
510 SkImageInfo decodeInfo = codec->getInfo();
511 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
512 fDstAlphaType)) {
513 return Result::Skip("Skipping uninteresting test.");
514 }
515
516 // Try to scale the image if it is desired
517 SkISize size = codec->getScaledDimensions(fScale);
518
519 std::unique_ptr<SkAndroidCodec> androidCodec;
520 if (1.0f != fScale && fMode == kAnimated_Mode) {
521 androidCodec = SkAndroidCodec::MakeFromData(encoded);
522 size = androidCodec->getSampledDimensions(1 / fScale);
523 }
524
525 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
526 return Result::Skip("Test without scaling is uninteresting.");
527 }
528
529 // Visually inspecting very small output images is not necessary. We will
530 // cover these cases in unit testing.
531 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
532 return Result::Skip("Scaling very small images is uninteresting.");
533 }
534 decodeInfo = decodeInfo.makeDimensions(size);
535
536 const int bpp = decodeInfo.bytesPerPixel();
537 const size_t rowBytes = size.width() * bpp;
538 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
539 SkAutoMalloc pixels(safeSize);
540
541 SkCodec::Options options;
542 if (kCodecZeroInit_Mode == fMode) {
543 memset(pixels.get(), 0, size.height() * rowBytes);
544 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
545 }
546
547 SkImageInfo bitmapInfo = decodeInfo;
548 set_bitmap_color_space(&bitmapInfo);
549 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
550 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
551 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
552 }
553
554 switch (fMode) {
555 case kAnimated_Mode: {
556 SkAndroidCodec::AndroidOptions androidOptions;
557 if (fScale != 1.0f) {
558 SkASSERT(androidCodec);
559 androidOptions.fSampleSize = 1 / fScale;
560 auto dims = androidCodec->getSampledDimensions(androidOptions.fSampleSize);
561 decodeInfo = decodeInfo.makeDimensions(dims);
562 }
563
564 std::vector<SkCodec::FrameInfo> frameInfos = androidCodec
565 ? androidCodec->codec()->getFrameInfo() : codec->getFrameInfo();
566 if (frameInfos.size() <= 1) {
567 return Result::Fatal("%s is not an animated image.", fPath.c_str());
568 }
569
570 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
571 // into. "factor" is the number of frames to draw on one row. There will be
572 // up to "factor" rows as well.
573 const float root = sqrt((float) frameInfos.size());
574 const int factor = sk_float_ceil2int(root);
575
576 // Used to cache a frame that future frames will depend on.
577 SkAutoMalloc priorFramePixels;
578 int cachedFrame = SkCodec::kNoFrame;
579 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
580 androidOptions.fFrameIndex = i;
581 // Check for a prior frame
582 const int reqFrame = frameInfos[i].fRequiredFrame;
583 if (reqFrame != SkCodec::kNoFrame && reqFrame == cachedFrame
584 && priorFramePixels.get()) {
585 // Copy into pixels
586 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
587 androidOptions.fPriorFrame = reqFrame;
588 } else {
589 androidOptions.fPriorFrame = SkCodec::kNoFrame;
590 }
591 SkCodec::Result result = androidCodec
592 ? androidCodec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes,
593 &androidOptions)
594 : codec->getPixels(decodeInfo, pixels.get(), rowBytes, &androidOptions);
595 if (SkCodec::kInvalidInput == result && i > 0) {
596 // Some of our test images have truncated later frames. Treat that
597 // the same as incomplete.
598 result = SkCodec::kIncompleteInput;
599 }
600 switch (result) {
601 case SkCodec::kSuccess:
602 case SkCodec::kErrorInInput:
603 case SkCodec::kIncompleteInput: {
604 // If the next frame depends on this one, store it in priorFrame.
605 // It is possible that we may discard a frame that future frames depend on,
606 // but the codec will simply redecode the discarded frame.
607 // Do this before calling draw_to_canvas, which premultiplies in place. If
608 // we're decoding to unpremul, we want to pass the unmodified frame to the
609 // codec for decoding the next frame.
610 if (static_cast<size_t>(i+1) < frameInfos.size()
611 && frameInfos[i+1].fRequiredFrame == i) {
612 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
613 cachedFrame = i;
614 }
615
616 SkAutoCanvasRestore acr(canvas, true);
617 const int xTranslate = (i % factor) * decodeInfo.width();
618 const int yTranslate = (i / factor) * decodeInfo.height();
619 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
620 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
621 if (result != SkCodec::kSuccess) {
622 return Result::Ok();
623 }
624 break;
625 }
626 case SkCodec::kInvalidConversion:
627 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
628 return Result::Skip(
629 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str());
630 }
631 [[fallthrough]];
632 default:
633 return Result::Fatal(
634 "Couldn't getPixels for frame %i in %s.", i, fPath.c_str());
635 }
636 }
637 break;
638 }
639 case kCodecZeroInit_Mode:
640 case kCodec_Mode: {
641 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
642 case SkCodec::kSuccess:
643 // We consider these to be valid, since we should still decode what is
644 // available.
645 case SkCodec::kErrorInInput:
646 case SkCodec::kIncompleteInput:
647 break;
648 default:
649 // Everything else is considered a failure.
650 return Result::Fatal("Couldn't getPixels %s.", fPath.c_str());
651 }
652
653 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
654 break;
655 }
656 case kScanline_Mode: {
657 void* dst = pixels.get();
658 uint32_t height = decodeInfo.height();
659 const bool useIncremental = [this]() {
660 auto exts = { "png", "PNG", "gif", "GIF" };
661 for (auto ext : exts) {
662 if (fPath.endsWith(ext)) {
663 return true;
664 }
665 }
666 return false;
667 }();
668 // ico may use the old scanline method or the new one, depending on whether it
669 // internally holds a bmp or a png.
670 const bool ico = fPath.endsWith("ico");
671 bool useOldScanlineMethod = !useIncremental && !ico;
672 if (useIncremental || ico) {
673 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
674 rowBytes, &options)) {
675 int rowsDecoded;
676 auto result = codec->incrementalDecode(&rowsDecoded);
677 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
678 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
679 SkCodec::kNo_ZeroInitialized, height,
680 rowsDecoded);
681 }
682 } else {
683 if (useIncremental) {
684 // Error: These should support incremental decode.
685 return Result::Fatal("Could not start incremental decode");
686 }
687 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
688 // which should work via startScanlineDecode
689 useOldScanlineMethod = true;
690 }
691 }
692
693 if (useOldScanlineMethod) {
694 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
695 return Result::Fatal("Could not start scanline decoder");
696 }
697
698 // We do not need to check the return value. On an incomplete
699 // image, memory will be filled with a default value.
700 codec->getScanlines(dst, height, rowBytes);
701 }
702
703 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
704 break;
705 }
706 case kStripe_Mode: {
707 const int height = decodeInfo.height();
708 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
709 // does not align with image blocks.
710 const int stripeHeight = 37;
711 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
712 void* dst = pixels.get();
713
714 // Decode odd stripes
715 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
716 return Result::Fatal("Could not start scanline decoder");
717 }
718
719 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
720 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
721 // to run this test for image types that do not have this scanline ordering.
722 // We only run this on Jpeg, which is always kTopDown.
723 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
724
725 for (int i = 0; i < numStripes; i += 2) {
726 // Skip a stripe
727 const int linesToSkip = std::min(stripeHeight, height - i * stripeHeight);
728 codec->skipScanlines(linesToSkip);
729
730 // Read a stripe
731 const int startY = (i + 1) * stripeHeight;
732 const int linesToRead = std::min(stripeHeight, height - startY);
733 if (linesToRead > 0) {
734 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
735 rowBytes);
736 }
737 }
738
739 // Decode even stripes
740 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
741 if (SkCodec::kSuccess != startResult) {
742 return Result::Fatal("Failed to restart scanline decoder with same parameters.");
743 }
744 for (int i = 0; i < numStripes; i += 2) {
745 // Read a stripe
746 const int startY = i * stripeHeight;
747 const int linesToRead = std::min(stripeHeight, height - startY);
748 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
749 rowBytes);
750
751 // Skip a stripe
752 const int linesToSkip = std::min(stripeHeight, height - (i + 1) * stripeHeight);
753 if (linesToSkip > 0) {
754 codec->skipScanlines(linesToSkip);
755 }
756 }
757
758 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
759 break;
760 }
761 case kCroppedScanline_Mode: {
762 const int width = decodeInfo.width();
763 const int height = decodeInfo.height();
764 // This value is chosen because, as we move across the image, it will sometimes
765 // align with the jpeg block sizes and it will sometimes not. This allows us
766 // to test interestingly different code paths in the implementation.
767 const int tileSize = 36;
768 SkIRect subset;
769 for (int x = 0; x < width; x += tileSize) {
770 subset = SkIRect::MakeXYWH(x, 0, std::min(tileSize, width - x), height);
771 options.fSubset = &subset;
772 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
773 return Result::Fatal("Could not start scanline decoder.");
774 }
775
776 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
777 }
778
779 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
780 break;
781 }
782 case kSubset_Mode: {
783 // Arbitrarily choose a divisor.
784 int divisor = 2;
785 // Total width/height of the image.
786 const int W = codec->getInfo().width();
787 const int H = codec->getInfo().height();
788 if (divisor > W || divisor > H) {
789 return Result::Skip("Cannot codec subset: divisor %d is too big "
790 "for %s with dimensions (%d x %d)", divisor,
791 fPath.c_str(), W, H);
792 }
793 // subset dimensions
794 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
795 const int w = SkAlign2(W / divisor);
796 const int h = SkAlign2(H / divisor);
797 SkIRect subset;
798 options.fSubset = &subset;
799 SkBitmap subsetBm;
800 // We will reuse pixel memory from bitmap.
801 void* dst = pixels.get();
802 // Keep track of left and top (for drawing subsetBm into canvas). We could use
803 // fScale * x and fScale * y, but we want integers such that the next subset will start
804 // where the last one ended. So we'll add decodeInfo.width() and height().
805 int left = 0;
806 for (int x = 0; x < W; x += w) {
807 int top = 0;
808 for (int y = 0; y < H; y+= h) {
809 // Do not make the subset go off the edge of the image.
810 const int preScaleW = std::min(w, W - x);
811 const int preScaleH = std::min(h, H - y);
812 subset.setXYWH(x, y, preScaleW, preScaleH);
813 // And scale
814 // FIXME: Should we have a version of getScaledDimensions that takes a subset
815 // into account?
816 const int scaledW = std::max(1, SkScalarRoundToInt(preScaleW * fScale));
817 const int scaledH = std::max(1, SkScalarRoundToInt(preScaleH * fScale));
818 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
819 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
820 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
821 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
822 &options);
823 switch (result) {
824 case SkCodec::kSuccess:
825 case SkCodec::kErrorInInput:
826 case SkCodec::kIncompleteInput:
827 break;
828 default:
829 return Result::Fatal("subset codec failed to decode (%d, %d, %d, %d) "
830 "from %s with dimensions (%d x %d)\t error %d",
831 x, y, decodeInfo.width(), decodeInfo.height(),
832 fPath.c_str(), W, H, result);
833 }
834 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
835 SkIntToScalar(left), SkIntToScalar(top));
836
837 // translate by the scaled height.
838 top += decodeInfo.height();
839 }
840 // translate by the scaled width.
841 left += decodeInfo.width();
842 }
843 return Result::Ok();
844 }
845 default:
846 SkASSERT(false);
847 return Result::Fatal("Invalid fMode");
848 }
849 return Result::Ok();
850 }
851
852 SkISize CodecSrc::size() const {
853 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
854 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
855 if (nullptr == codec) {
856 return {0, 0};
857 }
858
859 if (fMode != kAnimated_Mode) {
860 return codec->getScaledDimensions(fScale);
861 }
862
863 // We'll draw one of each frame, so make it big enough to hold them all
864 // in a grid. The grid will be roughly square, with "factor" frames per
865 // row and up to "factor" rows.
866 const size_t count = codec->getFrameInfo().size();
867 const float root = sqrt((float) count);
868 const int factor = sk_float_ceil2int(root);
869
870 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
871 auto imageSize = androidCodec->getSampledDimensions(1 / fScale);
872 imageSize.fWidth = imageSize.fWidth * factor;
873 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
874 return imageSize;
875 }
876
877 Name CodecSrc::name() const {
878 Name name = SkOSPath::Basename(fPath.c_str());
879 if (fMode == kAnimated_Mode) {
880 name.append("_animated");
881 }
882 if (1.0f == fScale) {
883 return name;
884 }
885 return get_scaled_name(name.c_str(), fScale);
886 }
887
888 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
889
890 AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
891 SkAlphaType dstAlphaType, int sampleSize)
892 : fPath(path)
893 , fDstColorType(dstColorType)
894 , fDstAlphaType(dstAlphaType)
895 , fSampleSize(sampleSize)
896 , fRunSerially(serial_from_path_name(path))
897 {}
898
899 bool AndroidCodecSrc::veto(SinkFlags flags) const {
900 // No need to test decoding to non-raster or indirect backend.
901 return flags.type != SinkFlags::kRaster
902 || flags.approach != SinkFlags::kDirect;
903 }
904
905 Result AndroidCodecSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
906 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
907 if (!encoded) {
908 return Result::Fatal("Couldn't read %s.", fPath.c_str());
909 }
910 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
911 if (nullptr == codec) {
912 return Result::Fatal("Couldn't create android codec for %s.", fPath.c_str());
913 }
914
915 SkImageInfo decodeInfo = codec->getInfo();
916 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
917 fDstAlphaType)) {
918 return Result::Skip("Skipping uninteresting test.");
919 }
920
921 // Scale the image if it is desired.
922 SkISize size = codec->getSampledDimensions(fSampleSize);
923
924 // Visually inspecting very small output images is not necessary. We will
925 // cover these cases in unit testing.
926 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
927 return Result::Skip("Scaling very small images is uninteresting.");
928 }
929 decodeInfo = decodeInfo.makeDimensions(size);
930
931 int bpp = decodeInfo.bytesPerPixel();
932 size_t rowBytes = size.width() * bpp;
933 SkAutoMalloc pixels(size.height() * rowBytes);
934
935 SkBitmap bitmap;
936 SkImageInfo bitmapInfo = decodeInfo;
937 set_bitmap_color_space(&bitmapInfo);
938 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
939 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
940 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
941 }
942
943 // Create options for the codec.
944 SkAndroidCodec::AndroidOptions options;
945 options.fSampleSize = fSampleSize;
946
947 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
948 case SkCodec::kSuccess:
949 case SkCodec::kErrorInInput:
950 case SkCodec::kIncompleteInput:
951 break;
952 default:
953 return Result::Fatal("Couldn't getPixels %s.", fPath.c_str());
954 }
955 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
956 return Result::Ok();
957 }
958
959 SkISize AndroidCodecSrc::size() const {
960 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
961 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
962 if (nullptr == codec) {
963 return {0, 0};
964 }
965 return codec->getSampledDimensions(fSampleSize);
966 }
967
968 Name AndroidCodecSrc::name() const {
969 // We will replicate the names used by CodecSrc so that images can
970 // be compared in Gold.
971 if (1 == fSampleSize) {
972 return SkOSPath::Basename(fPath.c_str());
973 }
974 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
975 }
976
977 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
978
979 ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
980 : fPath(path)
981 , fMode(mode)
982 , fDstAlphaType(alphaType)
983 , fIsGpu(isGpu)
984 , fRunSerially(serial_from_path_name(path))
985 {}
986
987 bool ImageGenSrc::veto(SinkFlags flags) const {
988 if (fIsGpu) {
989 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
990 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
991 flags.multisampled == SinkFlags::kMultisampled;
992 }
993
994 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
995 }
996
997 Result ImageGenSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
998 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
999 return Result::Skip("Uninteresting to test image generator to 565.");
1000 }
1001
1002 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1003 if (!encoded) {
1004 return Result::Fatal("Couldn't read %s.", fPath.c_str());
1005 }
1006
1007 #if defined(SK_BUILD_FOR_WIN)
1008 // Initialize COM in order to test with WIC.
1009 SkAutoCoInitialize com;
1010 if (!com.succeeded()) {
1011 return Result::Fatal("Could not initialize COM.");
1012 }
1013 #endif
1014
1015 std::unique_ptr<SkImageGenerator> gen(nullptr);
1016 switch (fMode) {
1017 case kCodec_Mode:
1018 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
1019 if (!gen) {
1020 return Result::Fatal("Could not create codec image generator.");
1021 }
1022 break;
1023 case kPlatform_Mode: {
1024 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
1025 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
1026 #elif defined(SK_BUILD_FOR_WIN)
1027 gen = SkImageGeneratorWIC::MakeFromEncodedWIC(encoded);
1028 #elif defined(SK_ENABLE_NDK_IMAGES)
1029 gen = SkImageGeneratorNDK::MakeFromEncodedNDK(encoded);
1030 #endif
1031 if (!gen) {
1032 return Result::Fatal("Could not create platform image generator.");
1033 }
1034 break;
1035 }
1036 default:
1037 SkASSERT(false);
1038 return Result::Fatal("Invalid image generator mode");
1039 }
1040
1041 // Test deferred decoding path on GPU
1042 if (fIsGpu) {
1043 sk_sp<SkImage> image(SkImages::DeferredFromGenerator(std::move(gen)));
1044 if (!image) {
1045 return Result::Fatal("Could not create image from codec image generator.");
1046 }
1047 canvas->drawImage(image, 0, 0);
1048 return Result::Ok();
1049 }
1050
1051 // Test various color and alpha types on CPU
1052 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
1053
1054 int bpp = decodeInfo.bytesPerPixel();
1055 size_t rowBytes = decodeInfo.width() * bpp;
1056 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
1057 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes)) {
1058 Result::Status status = Result::Status::Fatal;
1059 #if defined(SK_BUILD_FOR_WIN)
1060 if (kPlatform_Mode == fMode) {
1061 // Do not issue a fatal error for WIC flakiness.
1062 status = Result::Status::Skip;
1063 }
1064 #endif
1065 return Result(
1066 status,
1067 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str()));
1068 }
1069
1070 set_bitmap_color_space(&decodeInfo);
1071 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
1072 CodecSrc::kGetFromCanvas_DstColorType);
1073 return Result::Ok();
1074 }
1075
1076 SkISize ImageGenSrc::size() const {
1077 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1078 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1079 if (nullptr == codec) {
1080 return {0, 0};
1081 }
1082 return codec->getInfo().dimensions();
1083 }
1084
1085 Name ImageGenSrc::name() const {
1086 return SkOSPath::Basename(fPath.c_str());
1087 }
1088
1089 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1090
1091 ColorCodecSrc::ColorCodecSrc(Path path, bool decode_to_dst) : fPath(path)
1092 , fDecodeToDst(decode_to_dst) {}
1093
1094 bool ColorCodecSrc::veto(SinkFlags flags) const {
1095 // Test to direct raster backends (8888 and 565).
1096 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1097 }
1098
1099 Result ColorCodecSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
1100 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1101 if (!encoded) {
1102 return Result::Fatal("Couldn't read %s.", fPath.c_str());
1103 }
1104
1105 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1106 if (nullptr == codec) {
1107 return Result::Fatal("Couldn't create codec for %s.", fPath.c_str());
1108 }
1109
1110 SkImageInfo info = codec->getInfo();
1111 if (SkEncodedOriginSwapsWidthHeight(codec->getOrigin())) {
1112 info = SkPixmapUtils::SwapWidthHeight(info);
1113 }
1114 if (fDecodeToDst) {
1115 SkImageInfo canvasInfo = canvas->imageInfo();
1116 if (!canvasInfo.colorSpace()) {
1117 // This will skip color conversion, and the resulting images will
1118 // look different from images they are compared against in Gold, but
1119 // that doesn't mean they are wrong. We have a test verifying that
1120 // passing a null SkColorSpace skips conversion, so skip this
1121 // misleading test.
1122 return Result::Skip("Skipping decoding without color transform.");
1123 }
1124 info = canvasInfo.makeDimensions(info.dimensions());
1125 }
1126
1127 auto [image, result] = codec->getImage(info);
1128 switch (result) {
1129 case SkCodec::kSuccess:
1130 case SkCodec::kErrorInInput:
1131 case SkCodec::kIncompleteInput:
1132 canvas->drawImage(image, 0,0);
1133 return Result::Ok();
1134 case SkCodec::kInvalidConversion:
1135 // TODO(mtklein): why are there formats we can't decode to?
1136 return Result::Skip("SkCodec can't decode to this format.");
1137 default:
1138 return Result::Fatal("Couldn't getPixels %s. Error code %d", fPath.c_str(), result);
1139 }
1140 }
1141
1142 SkISize ColorCodecSrc::size() const {
1143 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1144 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1145 if (nullptr == codec) {
1146 return {0, 0};
1147 }
1148 return {codec->getInfo().width(), codec->getInfo().height()};
1149 }
1150
1151 Name ColorCodecSrc::name() const {
1152 return SkOSPath::Basename(fPath.c_str());
1153 }
1154
1155 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1156
1157 static DEFINE_int(skpViewportSize, 1000,
1158 "Width & height of the viewport used to crop skp rendering.");
1159
1160 SKPSrc::SKPSrc(Path path) : fPath(path) { }
1161
1162 Result SKPSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
1163 struct DeserializationContext {
1164 GrDirectContext* fDirectContext = nullptr;
1165 #if defined(SK_GRAPHITE)
1166 skgpu::graphite::Recorder* fRecorder = nullptr;
1167 #endif
1168 } ctx {
1169 GrAsDirectContext(canvas->recordingContext()),
1170 #if defined(SK_GRAPHITE)
1171 canvas->recorder()
1172 #endif
1173 };
1174
1175 SkDeserialProcs procs = ToolUtils::get_default_skp_deserial_procs();
1176
1177 // We override the default fImageDataProc set above
1178 procs.fImageDataProc =
1179 [](sk_sp<SkData> data, std::optional<SkAlphaType> at, void* ctx) -> sk_sp<SkImage> {
1180 sk_sp<SkImage> image = SkImages::DeferredFromEncodedData(std::move(data));
1181 image = image->makeRasterImage(nullptr); // force decoding
1182
1183 #if defined(SK_GANESH)
1184 if (image) {
1185 DeserializationContext* context = reinterpret_cast<DeserializationContext*>(ctx);
1186 if (context->fDirectContext) {
1187 return SkImages::TextureFromImage(context->fDirectContext, image);
1188 }
1189 }
1190 #endif
1191 return image;
1192 };
1193
1194 procs.fImageCtx = &ctx;
1195
1196 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(fPath.c_str());
1197 if (!stream) {
1198 return Result::Fatal("Couldn't read %s.", fPath.c_str());
1199 }
1200 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get(), &procs));
1201 if (!pic) {
1202 return Result::Fatal("Couldn't parse file %s.", fPath.c_str());
1203 }
1204 stream = nullptr; // Might as well drop this when we're done with it.
1205 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
1206 canvas->drawPicture(pic);
1207 return Result::Ok();
1208 }
1209
1210 static SkRect get_cull_rect_for_skp(const char* path) {
1211 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
1212 if (!stream) {
1213 return SkRect::MakeEmpty();
1214 }
1215 SkPictInfo info;
1216 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
1217 return SkRect::MakeEmpty();
1218 }
1219
1220 return info.fCullRect;
1221 }
1222
1223 SkISize SKPSrc::size() const {
1224 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
1225 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
1226 return {0, 0};
1227 }
1228 return viewport.roundOut().size();
1229 }
1230
1231 Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1232
1233 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1234
1235 BisectSrc::BisectSrc(Path path, const char* trail) : INHERITED(path), fTrail(trail) {}
1236
1237 Result BisectSrc::draw(SkCanvas* canvas, GraphiteTestContext* testContext) const {
1238 struct FoundPath {
1239 SkPath fPath;
1240 SkPaint fPaint;
1241 SkMatrix fViewMatrix;
1242 };
1243
1244 // This subclass of SkCanvas just extracts all the SkPaths (drawn via drawPath) from an SKP.
1245 class PathFindingCanvas : public SkCanvas {
1246 public:
1247 PathFindingCanvas(int width, int height) : SkCanvas(width, height, nullptr) {}
1248 const TArray<FoundPath>& foundPaths() const { return fFoundPaths; }
1249
1250 private:
1251 void onDrawPath(const SkPath& path, const SkPaint& paint) override {
1252 fFoundPaths.push_back() = {path, paint, this->getTotalMatrix()};
1253 }
1254
1255 TArray<FoundPath> fFoundPaths;
1256 };
1257
1258 PathFindingCanvas pathFinder(canvas->getBaseLayerSize().width(),
1259 canvas->getBaseLayerSize().height());
1260 Result result = this->INHERITED::draw(&pathFinder, testContext);
1261 if (!result.isOk()) {
1262 return result;
1263 }
1264
1265 int start = 0, end = pathFinder.foundPaths().size();
1266 for (const char* ch = fTrail.c_str(); *ch; ++ch) {
1267 int midpt = (start + end) / 2;
1268 if ('l' == *ch) {
1269 start = midpt;
1270 } else if ('r' == *ch) {
1271 end = midpt;
1272 }
1273 }
1274
1275 for (int i = start; i < end; ++i) {
1276 const FoundPath& path = pathFinder.foundPaths()[i];
1277 SkAutoCanvasRestore acr(canvas, true);
1278 canvas->concat(path.fViewMatrix);
1279 canvas->drawPath(path.fPath, path.fPaint);
1280 }
1281
1282 return Result::Ok();
1283 }
1284
1285 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1286
1287 #if defined(SK_ENABLE_SKOTTIE)
1288 static DEFINE_bool(useLottieGlyphPaths, false,
1289 "Prioritize embedded glyph paths over native fonts.");
1290
1291 SkottieSrc::SkottieSrc(Path path) : fPath(std::move(path)) {}
1292
1293 Result SkottieSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
1294 auto predecode = skresources::ImageDecodeStrategy::kPreDecode;
1295 // DM should have already registered the codecs necessary for DataURIResourceProviderProxy
1296 // to decode images.
1297 auto resource_provider = skresources::DataURIResourceProviderProxy::Make(
1298 skresources::FileResourceProvider::Make(SkOSPath::Dirname(fPath.c_str()), predecode),
1299 predecode,
1300 ToolUtils::TestFontMgr());
1301
1302 static constexpr char kInterceptPrefix[] = "__";
1303 auto precomp_interceptor =
1304 sk_make_sp<skottie_utils::ExternalAnimationPrecompInterceptor>(resource_provider,
1305 kInterceptPrefix);
1306 uint32_t flags = 0;
1307 if (FLAGS_useLottieGlyphPaths) {
1308 flags |= skottie::Animation::Builder::kPreferEmbeddedFonts;
1309 }
1310
1311 auto animation = skottie::Animation::Builder(flags)
1312 .setFontManager(ToolUtils::TestFontMgr())
1313 .setResourceProvider(std::move(resource_provider))
1314 .setPrecompInterceptor(std::move(precomp_interceptor))
1315 .setTextShapingFactory(SkShapers::BestAvailable())
1316 .makeFromFile(fPath.c_str());
1317 if (!animation) {
1318 return Result::Fatal("Unable to parse file: %s", fPath.c_str());
1319 }
1320
1321 canvas->drawColor(SK_ColorWHITE);
1322
1323 const auto t_rate = 1.0f / (kTileCount * kTileCount - 1);
1324
1325 // Draw the frames in a shuffled order to exercise non-linear
1326 // frame progression. The film strip will still be in order left-to-right,
1327 // top-down, just not drawn in that order.
1328 static constexpr int frameOrder[] = { 4, 0, 3, 1, 2 };
1329 static_assert(std::size(frameOrder) == kTileCount, "");
1330
1331 for (int i = 0; i < kTileCount; ++i) {
1332 const SkScalar y = frameOrder[i] * kTileSize;
1333
1334 for (int j = 0; j < kTileCount; ++j) {
1335 const SkScalar x = frameOrder[j] * kTileSize;
1336 SkRect dest = SkRect::MakeXYWH(x, y, kTileSize, kTileSize);
1337
1338 const auto t = t_rate * (frameOrder[i] * kTileCount + frameOrder[j]);
1339 {
1340 SkAutoCanvasRestore acr(canvas, true);
1341 canvas->clipRect(dest, true);
1342 canvas->concat(SkMatrix::RectToRectOrIdentity(SkRect::MakeSize(animation->size()),
1343 dest, SkMatrix::kCenter_ScaleToFit));
1344 animation->seek(t);
1345 animation->render(canvas);
1346 }
1347 }
1348 }
1349
1350 return Result::Ok();
1351 }
1352
1353 SkISize SkottieSrc::size() const {
1354 return SkISize::Make(kTargetSize, kTargetSize);
1355 }
1356
1357 Name SkottieSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1358
1359 bool SkottieSrc::veto(SinkFlags flags) const {
1360 // No need to test to non-(raster||gpu||vector) or indirect backends.
1361 bool type_ok = flags.type == SinkFlags::kRaster
1362 || flags.type == SinkFlags::kGPU
1363 || flags.type == SinkFlags::kVector;
1364
1365 return !type_ok || flags.approach != SinkFlags::kDirect;
1366 }
1367 #endif
1368
1369 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1370 #if defined(SK_ENABLE_SVG)
1371 // Used when the image doesn't have an intrinsic size.
1372 static const SkSize kDefaultSVGSize = {1000, 1000};
1373
1374 // Used to force-scale tiny fixed-size images.
1375 static const SkSize kMinimumSVGSize = {128, 128};
1376
1377 SVGSrc::SVGSrc(Path path)
1378 : fName(SkOSPath::Basename(path.c_str()))
1379 , fScale(1) {
1380
1381 auto stream = SkStream::MakeFromFile(path.c_str());
1382 if (!stream) {
1383 return;
1384 }
1385
1386 // DM should have already registered the codecs necessary for DataURIResourceProviderProxy
1387 // to decode images.
1388 auto predecode = skresources::ImageDecodeStrategy::kPreDecode;
1389 auto rp = skresources::DataURIResourceProviderProxy::Make(
1390 skresources::FileResourceProvider::Make(SkOSPath::Dirname(path.c_str()), predecode),
1391 predecode,
1392 ToolUtils::TestFontMgr());
1393
1394 fDom = SkSVGDOM::Builder()
1395 .setResourceProvider(std::move(rp))
1396 .setFontManager(ToolUtils::TestFontMgr())
1397 .setTextShapingFactory(SkShapers::BestAvailable())
1398 .make(*stream);
1399 if (!fDom) {
1400 return;
1401 }
1402
1403 const SkSize& sz = fDom->containerSize();
1404 if (sz.isEmpty()) {
1405 // no intrinsic size
1406 fDom->setContainerSize(kDefaultSVGSize);
1407 } else {
1408 fScale = std::max(1.f, std::max(kMinimumSVGSize.width() / sz.width(),
1409 kMinimumSVGSize.height() / sz.height()));
1410 }
1411 }
1412
1413 Result SVGSrc::draw(SkCanvas* canvas, GraphiteTestContext*) const {
1414 if (!fDom) {
1415 return Result::Fatal("Unable to parse file: %s", fName.c_str());
1416 }
1417
1418 SkAutoCanvasRestore acr(canvas, true);
1419 canvas->scale(fScale, fScale);
1420 canvas->drawColor(SK_ColorWHITE);
1421 fDom->render(canvas);
1422
1423 return Result::Ok();
1424 }
1425
1426 SkISize SVGSrc::size() const {
1427 if (!fDom) {
1428 return {0, 0};
1429 }
1430
1431 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1432 .toRound();
1433 }
1434
1435 Name SVGSrc::name() const { return fName; }
1436
1437 bool SVGSrc::veto(SinkFlags flags) const {
1438 // No need to test to non-(raster||gpu||vector) or indirect backends.
1439 bool type_ok = flags.type == SinkFlags::kRaster
1440 || flags.type == SinkFlags::kGPU
1441 || flags.type == SinkFlags::kVector;
1442
1443 return !type_ok || flags.approach != SinkFlags::kDirect;
1444 }
1445
1446 #endif // defined(SK_ENABLE_SVG)
1447 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1448
1449 MSKPSrc::MSKPSrc(Path path) : fPath(path) {
1450 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1451 int count = SkMultiPictureDocument::ReadPageCount(stream.get());
1452 if (count > 0) {
1453 fPages.reset(count);
1454 SkASSERT_RELEASE(SkMultiPictureDocument::ReadPageSizes(stream.get(), &fPages[0],
1455 fPages.size()));
1456 }
1457 }
1458
1459 int MSKPSrc::pageCount() const { return fPages.size(); }
1460
1461 SkISize MSKPSrc::size() const { return this->size(FLAGS_mskpFrame); }
1462 SkISize MSKPSrc::size(int i) const {
1463 return i >= 0 && i < fPages.size() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
1464 }
1465
1466 Result MSKPSrc::draw(SkCanvas* c, GraphiteTestContext* testContext) const {
1467 return this->draw(FLAGS_mskpFrame, c, testContext);
1468 }
1469 Result MSKPSrc::draw(int i, SkCanvas* canvas, GraphiteTestContext*) const {
1470 if (this->pageCount() == 0) {
1471 return Result::Fatal("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1472 }
1473 if (i >= fPages.size() || i < 0) {
1474 return Result::Fatal("MultiPictureDocument page number out of range: %d", i);
1475 }
1476 SkPicture* page = fPages[i].fPicture.get();
1477 if (!page) {
1478 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1479 if (!stream) {
1480 return Result::Fatal("Unable to open file: %s", fPath.c_str());
1481 }
1482 if (!SkMultiPictureDocument::Read(stream.get(), &fPages[0], fPages.size())) {
1483 return Result::Fatal("SkMultiPictureDocument reader failed on page %d: %s", i,
1484 fPath.c_str());
1485 }
1486 page = fPages[i].fPicture.get();
1487 }
1488 canvas->drawPicture(page);
1489 return Result::Ok();
1490 }
1491
1492 Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1493
1494 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1495
1496 Result NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
1497 return src.draw(SkMakeNullCanvas().get(), /*GraphiteTestContext=*/nullptr);
1498 }
1499
1500 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1501
1502 static Result compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
1503 // The dimensions are a property of the Src only, and so should be identical.
1504 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1505 if (reference.computeByteSize() != bitmap.computeByteSize()) {
1506 return Result::Fatal("Dimensions don't match reference");
1507 }
1508 // All SkBitmaps in DM are tight, so this comparison is easy.
1509 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
1510 SkString encoded;
1511 SkString errString("Pixels don't match reference");
1512 if (ToolUtils::BitmapToBase64DataURI(reference, &encoded)) {
1513 errString.append("\nExpected: ");
1514 errString.append(encoded);
1515 } else {
1516 errString.append("\nExpected image failed to encode: ");
1517 errString.append(encoded);
1518 }
1519 if (ToolUtils::BitmapToBase64DataURI(bitmap, &encoded)) {
1520 errString.append("\nActual: ");
1521 errString.append(encoded);
1522 } else {
1523 errString.append("\nActual image failed to encode: ");
1524 errString.append(encoded);
1525 }
1526 return Result(Result::Status::Fatal, errString);
1527 }
1528 return Result::Ok();
1529 }
1530
1531 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1532
1533 static DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1534 static DEFINE_bool(preAbandonGpuContext, false,
1535 "Test abandoning the GrContext before running the test.");
1536 static DEFINE_bool(abandonGpuContext, false,
1537 "Test abandoning the GrContext after running each test.");
1538 static DEFINE_bool(releaseAndAbandonGpuContext, false,
1539 "Test releasing all gpu resources and abandoning the GrContext "
1540 "after running each test");
1541 static DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
1542 static DEFINE_bool(programBinaryCache, true, "Use in-memory program binary cache");
1543
1544 #if defined(SK_GANESH)
1545 GPUSink::GPUSink(const SkCommandLineConfigGpu* config,
1546 const GrContextOptions& grCtxOptions)
1547 : fContextType(config->getContextType())
1548 , fContextOverrides(config->getContextOverrides())
1549 , fSurfType(config->getSurfType())
1550 , fSampleCount(config->getSamples())
1551 , fSurfaceFlags(config->getSurfaceFlags())
1552 , fColorType(config->getColorType())
1553 , fAlphaType(config->getAlphaType())
1554 , fBaseContextOptions(grCtxOptions) {
1555 if (FLAGS_programBinaryCache) {
1556 fBaseContextOptions.fPersistentCache = &fMemoryCache;
1557 }
1558 }
1559
1560 Result GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
1561 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1562 }
1563
1564 sk_sp<SkSurface> GPUSink::createDstSurface(GrDirectContext* context, const Src& src) const {
1565 sk_sp<SkSurface> surface;
1566
1567 SkImageInfo info = SkImageInfo::Make(src.size(), this->colorInfo());
1568 SkSurfaceProps props(fSurfaceFlags, kRGB_H_SkPixelGeometry);
1569 src.modifySurfaceProps(&props);
1570
1571 switch (fSurfType) {
1572 case SkCommandLineConfigGpu::SurfType::kDefault:
1573 surface = SkSurfaces::RenderTarget(
1574 context, skgpu::Budgeted::kNo, info, fSampleCount, &props);
1575 break;
1576 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
1577 surface = sk_gpu_test::MakeBackendTextureSurface(context,
1578 info,
1579 kTopLeft_GrSurfaceOrigin,
1580 fSampleCount,
1581 skgpu::Mipmapped::kNo,
1582 GrProtected::kNo,
1583 &props);
1584 break;
1585 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1586 surface = sk_gpu_test::MakeBackendRenderTargetSurface(context,
1587 info,
1588 kBottomLeft_GrSurfaceOrigin,
1589 fSampleCount,
1590 GrProtected::kNo,
1591 &props);
1592 break;
1593 }
1594
1595 return surface;
1596 }
1597
1598 bool GPUSink::readBack(SkSurface* surface, SkBitmap* dst) const {
1599 SkCanvas* canvas = surface->getCanvas();
1600 SkISize size = surface->imageInfo().dimensions();
1601
1602 SkImageInfo info = SkImageInfo::Make(size, this->colorInfo());
1603 dst->allocPixels(info);
1604 return canvas->readPixels(*dst, 0, 0);
1605 }
1606
1607 Result GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1608 const GrContextOptions& baseOptions,
1609 std::function<void(GrDirectContext*)> initContext,
1610 std::function<SkCanvas*(SkCanvas*)> wrapCanvas) const {
1611 GrContextOptions grOptions = baseOptions;
1612
1613 // We don't expect the src to mess with the persistent cache or the executor.
1614 SkDEBUGCODE(auto cache = grOptions.fPersistentCache);
1615 SkDEBUGCODE(auto exec = grOptions.fExecutor);
1616 src.modifyGrContextOptions(&grOptions);
1617 SkASSERT(cache == grOptions.fPersistentCache);
1618 SkASSERT(exec == grOptions.fExecutor);
1619
1620 GrContextFactory factory(grOptions);
1621 auto direct = factory.getContextInfo(fContextType, fContextOverrides).directContext();
1622 if (initContext) {
1623 initContext(direct);
1624 }
1625
1626 const int maxDimension = direct->priv().caps()->maxTextureSize();
1627 if (maxDimension < std::max(src.size().width(), src.size().height())) {
1628 return Result::Skip("Src too large to create a texture.\n");
1629 }
1630
1631 sk_sp<SkSurface> surface = this->createDstSurface(direct, src);
1632 if (!surface) {
1633 return Result::Fatal("Could not create a surface.");
1634 }
1635 if (FLAGS_preAbandonGpuContext) {
1636 factory.abandonContexts();
1637 }
1638
1639 auto canvas = surface->getCanvas();
1640 if (wrapCanvas != nullptr) {
1641 canvas = wrapCanvas(canvas);
1642 }
1643
1644 Result result = src.draw(canvas, /*GraphiteTestContext=*/nullptr);
1645 if (!result.isOk()) {
1646 return result;
1647 }
1648 direct->flushAndSubmit(surface.get(), GrSyncCpu::kNo);
1649 if (FLAGS_gpuStats) {
1650 direct->priv().dumpCacheStats(log);
1651 direct->priv().dumpGpuStats(log);
1652 direct->priv().dumpContextStats(log);
1653 }
1654
1655 this->readBack(surface.get(), dst);
1656
1657 if (FLAGS_abandonGpuContext) {
1658 factory.abandonContexts();
1659 } else if (FLAGS_releaseAndAbandonGpuContext) {
1660 factory.releaseResourcesAndAbandonContexts();
1661 }
1662
1663 if (grOptions.fPersistentCache) {
1664 direct->storeVkPipelineCacheData();
1665 }
1666 return Result::Ok();
1667 }
1668
1669 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1670 GPUSlugSink::GPUSlugSink(const SkCommandLineConfigGpu* config, const GrContextOptions& options)
1671 : GPUSink(config, options) {}
1672
1673 Result GPUSlugSink::draw(const Src& src, SkBitmap* dst, SkWStream* write, SkString* log) const {
1674 GrContextOptions grOptions = this->baseContextOptions();
1675 // Force padded atlas entries for slug drawing.
1676 grOptions.fSupportBilerpFromGlyphAtlas |= true;
1677
1678 SkTLazy<skiatest::TestCanvas<skiatest::SkSlugTestKey>> testCanvas;
1679
1680 return onDraw(src, dst, write, log, grOptions, nullptr,
1681 [&](SkCanvas* canvas){
1682 testCanvas.init(canvas);
1683 return testCanvas.get();
1684 });
1685 }
1686
1687 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1688 GPUSerializeSlugSink::GPUSerializeSlugSink(
1689 const SkCommandLineConfigGpu* config, const GrContextOptions& options)
1690 : GPUSink(config, options) {}
1691
1692 Result GPUSerializeSlugSink::draw(
1693 const Src& src, SkBitmap* dst, SkWStream* write, SkString* log) const {
1694 GrContextOptions grOptions = this->baseContextOptions();
1695 // Force padded atlas entries for slug drawing.
1696 grOptions.fSupportBilerpFromGlyphAtlas |= true;
1697
1698 SkTLazy<skiatest::TestCanvas<skiatest::SkSerializeSlugTestKey>> testCanvas;
1699
1700 return onDraw(src, dst, write, log, grOptions, nullptr,
1701 [&](SkCanvas* canvas){
1702 testCanvas.init(canvas);
1703 return testCanvas.get();
1704 });
1705 }
1706
1707 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1708 GPURemoteSlugSink::GPURemoteSlugSink(
1709 const SkCommandLineConfigGpu* config, const GrContextOptions& options)
1710 : GPUSink(config, options) {}
1711
1712 Result GPURemoteSlugSink::draw(
1713 const Src& src, SkBitmap* dst, SkWStream* write, SkString* log) const {
1714 GrContextOptions grOptions = this->baseContextOptions();
1715 // Force padded atlas entries for slug drawing.
1716 grOptions.fSupportBilerpFromGlyphAtlas |= true;
1717
1718 SkTLazy<skiatest::TestCanvas<skiatest::SkRemoteSlugTestKey>> testCanvas;
1719
1720 return onDraw(src, dst, write, log, grOptions, nullptr,
1721 [&](SkCanvas* canvas) {
1722 testCanvas.init(canvas);
1723 return testCanvas.get();
1724 });
1725 }
1726
1727 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1728 GPUPersistentCacheTestingSink::GPUPersistentCacheTestingSink(const SkCommandLineConfigGpu* config,
1729 const GrContextOptions& grCtxOptions)
1730 : INHERITED(config, grCtxOptions)
1731 , fCacheType(config->getTestPersistentCache()) {}
1732
1733 Result GPUPersistentCacheTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1734 SkString* log) const {
1735 // Draw twice, once with a cold cache, and again with a warm cache. Verify that we get the same
1736 // result.
1737 sk_gpu_test::MemoryCache memoryCache;
1738 GrContextOptions contextOptions = this->baseContextOptions();
1739 contextOptions.fPersistentCache = &memoryCache;
1740 if (fCacheType == 2) {
1741 contextOptions.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kBackendSource;
1742 }
1743
1744 Result result = this->onDraw(src, dst, wStream, log, contextOptions);
1745 if (!result.isOk() || !dst) {
1746 return result;
1747 }
1748
1749 SkBitmap reference;
1750 SkString refLog;
1751 SkDynamicMemoryWStream refStream;
1752 memoryCache.resetCacheStats();
1753 Result refResult = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1754 if (!refResult.isOk()) {
1755 return refResult;
1756 }
1757 SkASSERT(!memoryCache.numCacheMisses());
1758 SkASSERT(!memoryCache.numCacheStores());
1759
1760 return compare_bitmaps(reference, *dst);
1761 }
1762
1763
1764 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1765
1766 GaneshPrecompileTestingSink::GaneshPrecompileTestingSink(const SkCommandLineConfigGpu* config,
1767 const GrContextOptions& grCtxOptions)
1768 : INHERITED(config, grCtxOptions) {}
1769
1770 Result GaneshPrecompileTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1771 SkString* log) const {
1772 // Three step process:
1773 // 1) Draw once with an SkSL cache, and store off the shader blobs.
1774 // 2) For the second context, pre-compile the shaders to warm the cache.
1775 // 3) Draw with the second context, ensuring that we get the same result, and no cache misses.
1776 sk_gpu_test::MemoryCache memoryCache;
1777 GrContextOptions contextOptions = this->baseContextOptions();
1778 contextOptions.fPersistentCache = &memoryCache;
1779 contextOptions.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kSkSL;
1780
1781 Result result = this->onDraw(src, dst, wStream, log, contextOptions);
1782 if (!result.isOk() || !dst) {
1783 return result;
1784 }
1785
1786 auto precompileShaders = [&memoryCache](GrDirectContext* dContext) {
1787 memoryCache.foreach([dContext](sk_sp<const SkData> key,
1788 sk_sp<SkData> data,
1789 const SkString& /*description*/,
1790 int /*count*/) {
1791 SkAssertResult(dContext->precompileShader(*key, *data));
1792 });
1793 };
1794
1795 sk_gpu_test::MemoryCache replayCache;
1796 GrContextOptions replayOptions = this->baseContextOptions();
1797 // Ensure that the runtime cache is large enough to hold all of the shaders we pre-compile
1798 replayOptions.fRuntimeProgramCacheSize = memoryCache.numCacheMisses();
1799 replayOptions.fPersistentCache = &replayCache;
1800
1801 SkBitmap reference;
1802 SkString refLog;
1803 SkDynamicMemoryWStream refStream;
1804 Result refResult = this->onDraw(src, &reference, &refStream, &refLog, replayOptions,
1805 precompileShaders);
1806 if (!refResult.isOk()) {
1807 return refResult;
1808 }
1809 SkASSERT(!replayCache.numCacheMisses());
1810
1811 return compare_bitmaps(reference, *dst);
1812 }
1813
1814 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1815 GPUDDLSink::GPUDDLSink(const SkCommandLineConfigGpu* config, const GrContextOptions& ctxOptions)
1816 : INHERITED(config, ctxOptions)
1817 , fRecordingExecutor(SkExecutor::MakeLIFOThreadPool(1))
1818 , fGPUExecutor(SkExecutor::MakeFIFOThreadPool(1, false)) {
1819 }
1820
1821 Result GPUDDLSink::ddlDraw(const Src& src,
1822 sk_sp<SkSurface> dstSurface,
1823 SkTaskGroup* recordingTaskGroup,
1824 SkTaskGroup* gpuTaskGroup,
1825 sk_gpu_test::TestContext* gpuTestCtx,
1826 GrDirectContext* dContext) const {
1827
1828 // We have to do this here bc characterization can hit the SkGpuDevice's thread guard (i.e.,
1829 // leaving it until the DDLTileHelper ctor will result in multiple threads trying to use the
1830 // same context (this thread and the gpuThread - which will be uploading textures)).
1831 GrSurfaceCharacterization dstCharacterization;
1832 SkAssertResult(dstSurface->characterize(&dstCharacterization));
1833
1834 auto size = src.size();
1835 SkPictureRecorder recorder;
1836 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1837 SkIntToScalar(size.height())),
1838 /*GraphiteTestContext=*/nullptr);
1839 if (!result.isOk()) {
1840 return result;
1841 }
1842 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
1843
1844 // this is our ultimate final drawing area/rect
1845 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
1846
1847 auto supportedYUVADataTypes = skgpu::ganesh::SupportedTextureFormats(*dContext);
1848 DDLPromiseImageHelper promiseImageHelper(supportedYUVADataTypes);
1849 sk_sp<SkPicture> newSKP = promiseImageHelper.recreateSKP(dContext, inputPicture.get());
1850 if (!newSKP) {
1851 return Result::Fatal("GPUDDLSink: Couldn't recreate the SKP");
1852 }
1853
1854 // 'gpuTestCtx/gpuThreadCtx' is being shifted to the gpuThread. Leave the main (this)
1855 // thread w/o a context.
1856 gpuTestCtx->makeNotCurrent();
1857
1858 // Job one for the GPU thread is to make 'gpuTestCtx' current!
1859 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeCurrent(); });
1860
1861 // TODO: move the image upload to the utility thread
1862 promiseImageHelper.uploadAllToGPU(gpuTaskGroup, dContext);
1863
1864 // Care must be taken when using 'gpuThreadCtx' bc it moves between the gpu-thread and this
1865 // one. About all it can be consistently used for is GrCaps access and 'defaultBackendFormat'
1866 // calls.
1867 constexpr int kNumDivisions = 3;
1868 DDLTileHelper tiles(dContext, dstCharacterization, viewport,
1869 kNumDivisions, kNumDivisions,
1870 /* addRandomPaddingToDst */ false);
1871
1872 tiles.createBackendTextures(gpuTaskGroup, dContext);
1873
1874 tiles.kickOffThreadedWork(recordingTaskGroup, gpuTaskGroup, dContext, newSKP.get());
1875
1876 // We have to wait for the recording threads to schedule all their work on the gpu thread
1877 // before we can schedule the composition draw and the flush. Note that the gpu thread
1878 // is not blocked at this point and this thread is borrowing recording work.
1879 recordingTaskGroup->wait();
1880
1881 // Note: at this point the recording thread(s) are stalled out w/ nothing to do.
1882
1883 if (FLAGS_preAbandonGpuContext) {
1884 dContext->abandonContext();
1885 }
1886
1887 // The recording threads have already scheduled the drawing of each tile's DDL on the gpu
1888 // thread. The composition DDL must be scheduled last bc it relies on the result of all
1889 // the tiles' rendering. Additionally, bc we're aliasing the tiles' backend textures,
1890 // there is nothing in the DAG to automatically force the required order.
1891 gpuTaskGroup->add([dstSurface, ddl = tiles.composeDDL()]() {
1892 skgpu::ganesh::DrawDDL(dstSurface, ddl);
1893 });
1894
1895 // This should be the only explicit flush for the entire DDL draw.
1896 gpuTaskGroup->add([dContext]() {
1897 // We need to ensure all the GPU work is finished so
1898 // the following 'deleteAllFromGPU' call will work
1899 // on Vulkan.
1900 // TODO: switch over to using the promiseImage callbacks
1901 // to free the backendTextures. This is complicated a
1902 // bit by which thread possesses the direct context.
1903 dContext->flush();
1904 dContext->submit(GrSyncCpu::kYes);
1905 });
1906
1907 // The backend textures are created on the gpuThread by the 'uploadAllToGPU' call.
1908 // It is simpler to also delete them at this point on the gpuThread.
1909 promiseImageHelper.deleteAllFromGPU(gpuTaskGroup, dContext);
1910
1911 tiles.deleteBackendTextures(gpuTaskGroup, dContext);
1912
1913 // A flush has already been scheduled on the gpu thread along with the clean up of the backend
1914 // textures so it is safe to schedule making 'gpuTestCtx' not current on the gpuThread.
1915 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeNotCurrent(); });
1916
1917 // All the work is scheduled on the gpu thread, we just need to wait
1918 gpuTaskGroup->wait();
1919
1920 return Result::Ok();
1921 }
1922
1923 Result GPUDDLSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
1924 GrContextOptions contextOptions = this->baseContextOptions();
1925 src.modifyGrContextOptions(&contextOptions);
1926 contextOptions.fPersistentCache = nullptr;
1927 contextOptions.fExecutor = nullptr;
1928
1929 GrContextFactory factory(contextOptions);
1930
1931 // This captures the context destined to be the main gpu context
1932 ContextInfo mainCtxInfo = factory.getContextInfo(this->contextType(), this->contextOverrides());
1933 sk_gpu_test::TestContext* mainTestCtx = mainCtxInfo.testContext();
1934 auto mainCtx = mainCtxInfo.directContext();
1935 if (!mainCtx) {
1936 return Result::Fatal("Could not create context.");
1937 }
1938
1939 SkASSERT(mainCtx->priv().getGpu());
1940
1941 // TODO: make use of 'otherCtx' for uploads & compilation
1942 #if 0
1943 // This captures the context destined to be the utility context. It is in a share group
1944 // with the main context
1945 ContextInfo otherCtxInfo = factory.getSharedContextInfo(mainCtx);
1946 sk_gpu_test::TestContext* otherTestCtx = otherCtxInfo.testContext();
1947 auto otherCtx = otherCtxInfo.directContext();
1948 if (!otherCtx) {
1949 return Result::Fatal("Cound not create shared context.");
1950 }
1951
1952 SkASSERT(otherCtx->priv().getGpu());
1953 #endif
1954
1955 SkTaskGroup recordingTaskGroup(*fRecordingExecutor);
1956 SkTaskGroup gpuTaskGroup(*fGPUExecutor);
1957
1958 // Make sure 'mainCtx' is current
1959 mainTestCtx->makeCurrent();
1960
1961 sk_sp<SkSurface> surface = this->createDstSurface(mainCtx, src);
1962 if (!surface) {
1963 return Result::Fatal("Could not create a surface.");
1964 }
1965
1966 Result result = this->ddlDraw(src, surface, &recordingTaskGroup, &gpuTaskGroup,
1967 mainTestCtx, mainCtx);
1968 if (!result.isOk()) {
1969 return result;
1970 }
1971
1972 // 'ddlDraw' will have made 'mainCtx' not current on the gpuThread
1973 mainTestCtx->makeCurrent();
1974
1975 if (FLAGS_gpuStats) {
1976 mainCtx->priv().dumpCacheStats(log);
1977 mainCtx->priv().dumpGpuStats(log);
1978 mainCtx->priv().dumpContextStats(log);
1979
1980 #if 0
1981 otherCtx->priv().dumpCacheStats(log);
1982 otherCtx->priv().dumpGpuStats(log);
1983 otherCtx->priv().dumpContextStats(log);
1984 #endif
1985 }
1986
1987 if (!this->readBack(surface.get(), dst)) {
1988 return Result::Fatal("Could not readback from surface.");
1989 }
1990
1991 return Result::Ok();
1992 }
1993
1994 #endif
1995
1996 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1997 static Result draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
1998 if (src.size().isEmpty()) {
1999 return Result::Fatal("Source has empty dimensions");
2000 }
2001 SkASSERT(doc);
2002 int pageCount = src.pageCount();
2003 for (int i = 0; i < pageCount; ++i) {
2004 int width = src.size(i).width(), height = src.size(i).height();
2005 SkCanvas* canvas =
2006 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
2007 if (!canvas) {
2008 return Result::Fatal("SkDocument::beginPage(w,h) returned nullptr");
2009 }
2010 Result result = src.draw(i, canvas, /*GraphiteTestContext=*/nullptr);
2011 if (!result.isOk()) {
2012 return result;
2013 }
2014 doc->endPage();
2015 }
2016 doc->close();
2017 dst->flush();
2018 return Result::Ok();
2019 }
2020
2021 Result PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2022 SkPDF::Metadata metadata;
2023 metadata.fTitle = src.name();
2024 metadata.fSubject = "rendering correctness test";
2025 metadata.fCreator = "Skia/DM";
2026 metadata.fProducer = "Skia/PDF HEAD"; // Set producer to avoid SK_MILESTONE churn.
2027 metadata.fRasterDPI = fRasterDpi;
2028 metadata.fPDFA = fPDFA;
2029 metadata.jpegDecoder = SkPDF::JPEG::Decode;
2030 metadata.jpegEncoder = SkPDF::JPEG::Encode;
2031 #if SK_PDF_TEST_EXECUTOR
2032 std::unique_ptr<SkExecutor> executor = SkExecutor::MakeFIFOThreadPool();
2033 metadata.fExecutor = executor.get();
2034 #endif
2035 auto doc = SkPDF::MakeDocument(dst, metadata);
2036 if (!doc) {
2037 return Result::Fatal("SkPDF::MakeDocument() returned nullptr");
2038 }
2039 return draw_skdocument(src, doc.get(), dst);
2040 }
2041
2042 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2043
2044 XPSSink::XPSSink() {}
2045
2046 #if defined(SK_SUPPORT_XPS)
2047 static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
2048 IXpsOMObjectFactory* factory;
2049 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
2050 nullptr,
2051 CLSCTX_INPROC_SERVER,
2052 IID_PPV_ARGS(&factory)));
2053 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
2054 }
2055
2056 Result XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2057 SkAutoCoInitialize com;
2058 if (!com.succeeded()) {
2059 return Result::Fatal("Could not initialize COM.");
2060 }
2061 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
2062 if (!factory) {
2063 return Result::Fatal("Failed to create XPS Factory.");
2064 }
2065 SkXPS::Options xpsOpts;
2066 xpsOpts.pngEncoder = [](SkWStream* dst, const SkPixmap& src) {
2067 #if defined(SK_CODEC_ENCODES_PNG_WITH_LIBPNG)
2068 return SkPngEncoder::Encode(dst, src, {});
2069 #elif defined(SK_CODEC_ENCODES_PNG_WITH_RUST)
2070 return SkPngRustEncoder::Encode(dst, src, {});
2071 #else
2072 #error "PNG encoder is required"
2073 #endif
2074 };
2075 auto doc = SkXPS::MakeDocument(dst, factory.get(), xpsOpts);
2076 if (!doc) {
2077 return Result::Fatal("SkXPS::MakeDocument() returned nullptr");
2078 }
2079 return draw_skdocument(src, doc.get(), dst);
2080 }
2081 #else
2082 Result XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2083 return Result::Fatal("XPS not supported on this platform.");
2084 }
2085 #endif
2086
2087 static SkSerialProcs serial_procs_using_png() {
2088 static SkSerialProcs procs{.fImageProc = [](SkImage* img, void*) -> sk_sp<const SkData> {
2089 #if defined(SK_CODEC_ENCODES_PNG_WITH_LIBPNG)
2090 return SkPngEncoder::Encode(as_IB(img)->directContext(), img, {});
2091 #elif defined(SK_CODEC_ENCODES_PNG_WITH_RUST)
2092 return SkPngRustEncoder::Encode(as_IB(img)->directContext(), img, {});
2093 #else
2094 // TODO: This catches SkImageEncoder_NDK (or other).
2095 return SkPngEncoder::Encode(as_IB(img)->directContext(), img, {});
2096 #endif
2097 }};
2098 return procs;
2099 }
2100
2101 static SkDeserialProcs deserial_procs_using_png() {
2102 static SkDeserialProcs procs{.fImageDataProc = [](sk_sp<SkData> data,
2103 std::optional<SkAlphaType> alphaType,
2104 void*) -> sk_sp<SkImage> {
2105 #if defined(SK_CODEC_DECODES_PNG_WITH_RUST)
2106 std::unique_ptr<SkStream> stream = SkMemoryStream::Make(data);
2107 auto codec = SkPngRustDecoder::Decode(std::move(stream), nullptr, nullptr);
2108 #else
2109 auto codec = SkPngDecoder::Decode(data, nullptr, nullptr);
2110 #endif
2111 return SkCodecs::DeferredImage(std::move(codec), alphaType);
2112 }};
2113 return procs;
2114 }
2115
2116 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2117
2118 SKPSink::SKPSink() {}
2119
2120 Result SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2121 auto size = SkSize::Make(src.size());
2122 SkPictureRecorder recorder;
2123 Result result = src.draw(recorder.beginRecording(size.width(), size.height()),
2124 /*GraphiteTestContext=*/nullptr);
2125 if (!result.isOk()) {
2126 return result;
2127 }
2128 SkSerialProcs procs = serial_procs_using_png();
2129 recorder.finishRecordingAsPicture()->serialize(dst, &procs);
2130 return Result::Ok();
2131 }
2132
2133 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2134
2135 Result DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2136 DebugCanvas debugCanvas(src.size().width(), src.size().height());
2137 Result result = src.draw(&debugCanvas, /*GraphiteTestContext=*/nullptr);
2138 if (!result.isOk()) {
2139 return result;
2140 }
2141 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
2142 UrlDataManager dataManager(SkString("data"));
2143 SkJSONWriter writer(dst, SkJSONWriter::Mode::kPretty);
2144 writer.beginObject(); // root
2145 debugCanvas.toJSON(writer, dataManager, nullCanvas.get());
2146 writer.endObject(); // root
2147 writer.flush();
2148 return Result::Ok();
2149 }
2150
2151 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2152
2153 SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
2154
2155 Result SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
2156 #if defined(SK_ENABLE_SVG)
2157 if (src.pageCount() > 1) {
2158 int pageCount = src.pageCount();
2159 if (fPageIndex > pageCount - 1) {
2160 return Result::Fatal("Page index %d too high for document with only %d pages.",
2161 fPageIndex, pageCount);
2162 }
2163 }
2164 return src.draw(fPageIndex,
2165 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
2166 SkIntToScalar(src.size().height())),
2167 dst)
2168 .get(),
2169 /*GraphiteTestContext=*/nullptr);
2170 #else
2171 (void)fPageIndex;
2172 return Result::Fatal("SVG sink is disabled.");
2173 #endif // SK_ENABLE_SVG
2174 }
2175
2176 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2177
2178 RasterSink::RasterSink(SkColorType colorType)
2179 : fColorType(colorType) {}
2180
2181 Result RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
2182 const SkISize size = src.size();
2183 if (size.isEmpty()) {
2184 return Result(Result::Status::Skip,
2185 SkStringPrintf("Skipping empty source: %s", src.name().c_str()));
2186 }
2187
2188 dst->allocPixelsFlags(SkImageInfo::Make(size, this->colorInfo()),
2189 SkBitmap::kZeroPixels_AllocFlag);
2190
2191 SkSurfaceProps props(/*flags=*/0, kRGB_H_SkPixelGeometry);
2192 src.modifySurfaceProps(&props);
2193 auto surface = SkSurfaces::WrapPixels(dst->pixmap(), &props);
2194 return src.draw(surface->getCanvas(), /*GraphiteTestContext=*/nullptr);
2195 }
2196
2197 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2198
2199 #if defined(SK_GRAPHITE)
2200
2201 GraphiteSink::GraphiteSink(const SkCommandLineConfigGraphite* config,
2202 const skiatest::graphite::TestOptions& options)
2203 : fOptions(options)
2204 , fContextType(config->getContextType())
2205 , fColorType(config->getColorType())
2206 , fAlphaType(config->getAlphaType()) {}
2207
2208 Result GraphiteSink::draw(const Src& src,
2209 SkBitmap* dst,
2210 SkWStream* dstStream,
2211 SkString* log) const {
2212 skiatest::graphite::TestOptions options = fOptions;
2213 // If we've copied context options from an external source we can't trust that the
2214 // priv pointer is still in scope, so assume it should be NULL and set our own up.
2215 SkASSERT(!options.fContextOptions.fOptionsPriv);
2216 skgpu::graphite::ContextOptionsPriv optionsPriv;
2217 options.fContextOptions.fOptionsPriv = &optionsPriv;
2218
2219 // We don't expect the src to mess with the more esoteric options
2220 SkDEBUGCODE(auto cache = options.fContextOptions.fPersistentPipelineStorage);
2221 SkDEBUGCODE(auto exec = options.fContextOptions.fExecutor);
2222 SkDEBUGCODE(auto cbContext = options.fContextOptions.fPipelineCallbackContext);
2223 SkDEBUGCODE(auto cb1 = options.fContextOptions.fPipelineCallback);
2224 SkDEBUGCODE(auto cb2 = options.fContextOptions.fPipelineCachingCallback);
2225 src.modifyGraphiteContextOptions(&options.fContextOptions);
2226 SkASSERT(cache == options.fContextOptions.fPersistentPipelineStorage);
2227 SkASSERT(exec == options.fContextOptions.fExecutor);
2228 SkASSERT(cbContext == options.fContextOptions.fPipelineCallbackContext);
2229 SkASSERT(cb1 == options.fContextOptions.fPipelineCallback);
2230 SkASSERT(cb2 == options.fContextOptions.fPipelineCachingCallback);
2231
2232 skiatest::graphite::ContextFactory factory(options);
2233 skiatest::graphite::ContextInfo ctxInfo = factory.getContextInfo(fContextType);
2234 skgpu::graphite::Context* context = ctxInfo.fContext;
2235 if (!context) {
2236 return Result::Fatal("Could not create a context.");
2237 }
2238
2239 std::unique_ptr<skgpu::graphite::Recorder> recorder =
2240 context->makeRecorder(ToolUtils::CreateTestingRecorderOptions());
2241 if (!recorder) {
2242 return Result::Fatal("Could not create a recorder.");
2243 }
2244
2245 {
2246 sk_sp<SkSurface> surface = this->makeSurface(recorder.get(), src);
2247 if (!surface) {
2248 return Result::Fatal("Could not create a surface.");
2249 }
2250 dst->allocPixels(surface->imageInfo());
2251 Result result = src.draw(surface->getCanvas(), ctxInfo.fTestContext);
2252 if (!result.isOk()) {
2253 return result;
2254 }
2255
2256 SkPixmap pm;
2257 if (!dst->peekPixels(&pm) ||
2258 !surface->readPixels(pm, 0, 0)) {
2259 return Result::Fatal("Could not readback from surface.");
2260 }
2261 }
2262
2263 std::unique_ptr<skgpu::graphite::Recording> recording = recorder->snap();
2264 if (!recording) {
2265 return Result::Fatal("Could not create a recording.");
2266 }
2267
2268 skgpu::graphite::InsertRecordingInfo info;
2269 info.fRecording = recording.get();
2270 if (!context->insertRecording(info)) {
2271 return Result::Fatal("Context::insertRecording failed.");
2272 }
2273 ctxInfo.fTestContext->syncedSubmit(context);
2274
2275 if (options.fContextOptions.fPersistentPipelineStorage) {
2276 context->syncPipelineData();
2277 }
2278
2279 return Result::Ok();
2280 }
2281
2282 sk_sp<SkSurface> GraphiteSink::makeSurface(skgpu::graphite::Recorder* recorder,
2283 const Src& src) const {
2284 SkSurfaceProps props(0, kRGB_H_SkPixelGeometry);
2285 src.modifySurfaceProps(&props);
2286 auto ii = SkImageInfo::Make(src.size(), this->colorInfo());
2287
2288 #if defined(SK_DAWN)
2289 if (fOptions.fUseWGPUTextureView) {
2290 return sk_gpu_test::MakeBackendTextureViewSurface(recorder,
2291 ii,
2292 skgpu::Mipmapped::kNo,
2293 skgpu::Protected::kNo,
2294 &props);
2295 }
2296 #endif // SK_DAWN
2297
2298 return SkSurfaces::RenderTarget(recorder, ii, skgpu::Mipmapped::kNo, &props);
2299 }
2300
2301 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2302 GraphitePersistentPipelineStorageTestingSink::GraphitePersistentPipelineStorageTestingSink(
2303 const SkCommandLineConfigGraphite* config,
2304 const skiatest::graphite::TestOptions& options)
2305 : GraphiteSink(config, options) {
2306 fOptions.fContextOptions.fPersistentPipelineStorage = &fMemoryPipelineStorage;
2307 SkASSERT(config->getTestPersistentStorage());
2308 }
2309
2310 Result GraphitePersistentPipelineStorageTestingSink::draw(const Src& src,
2311 SkBitmap* dst,
2312 SkWStream* wStream,
2313 SkString* log) const {
2314 // Draw twice, once with a cold start, and again with a warm start.
2315 fMemoryPipelineStorage.reset();
2316
2317 Result result = this->GraphiteSink::draw(src, dst, wStream, log);
2318 if (!result.isOk() || !dst) {
2319 return result;
2320 }
2321
2322 // With the cold start there shouldn't anything to load but we should store the new pipelines.
2323 SkAssertResult(fMemoryPipelineStorage.numLoads() == 0);
2324 SkAssertResult(fMemoryPipelineStorage.numStores() == 1);
2325
2326 fMemoryPipelineStorage.resetCacheStats();
2327
2328 SkBitmap reference;
2329 SkString refLog;
2330 SkDynamicMemoryWStream refStream;
2331 Result refResult = this->GraphiteSink::draw(src, &reference, &refStream, &refLog);
2332 if (!refResult.isOk()) {
2333 return refResult;
2334 }
2335
2336 // With the warm start we should be able to load the prior pipelines and, thus, not need
2337 // to store any new ones.
2338 SkAssertResult(fMemoryPipelineStorage.numLoads() == 1);
2339 SkAssertResult(fMemoryPipelineStorage.numStores() == 0);
2340
2341 return compare_bitmaps(reference, *dst);
2342 }
2343
2344 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2345 GraphitePipelineTrackingSink::GraphitePipelineTrackingSink(
2346 const SkCommandLineConfigGraphite* config,
2347 const skiatest::graphite::TestOptions& options)
2348 : GraphiteSink(config, options)
2349 , fPipelineHandler(new skiatools::graphite::PipelineCallBackHandler) {
2350 using namespace skiatools::graphite;
2351
2352 SkASSERT(!fOptions.fContextOptions.fPipelineCallbackContext);
2353 SkASSERT(!fOptions.fContextOptions.fPipelineCachingCallback);
2354 fOptions.fContextOptions.fPipelineCallbackContext = fPipelineHandler.get();
2355 fOptions.fContextOptions.fPipelineCachingCallback = PipelineCallBackHandler::CallBack;
2356 }
2357
2358 void GraphitePipelineTrackingSink::done() const {
2359 fPipelineHandler->report();
2360 }
2361
2362 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2363 #if defined(SK_ENABLE_PRECOMPILE)
2364 GraphitePrecompileTestingSink::GraphitePrecompileTestingSink(
2365 const SkCommandLineConfigGraphite* config,
2366 const skiatest::graphite::TestOptions& options)
2367 : GraphiteSink(config, options)
2368 , fPipelineHandler(new skiatools::graphite::PipelineCallBackHandler){
2369 using namespace skiatools::graphite;
2370
2371 SkASSERT(!fOptions.fContextOptions.fPipelineCallbackContext);
2372 SkASSERT(!fOptions.fContextOptions.fPipelineCallback);
2373 fOptions.fContextOptions.fPipelineCallbackContext = fPipelineHandler.get();
2374 fOptions.fContextOptions.fPipelineCachingCallback = PipelineCallBackHandler::CallBack;
2375 }
2376
2377 GraphitePrecompileTestingSink::~GraphitePrecompileTestingSink() {}
2378
2379 Result GraphitePrecompileTestingSink::drawSrc(
2380 const Src& src,
2381 skgpu::graphite::Context* context,
2382 skiatest::graphite::GraphiteTestContext* testContext,
2383 skgpu::graphite::Recorder* recorder) const {
2384
2385 sk_sp<SkSurface> surface = this->makeSurface(recorder, src);
2386 if (!surface) {
2387 return Result::Fatal("Could not create a surface.");
2388 }
2389 Result result = src.draw(surface->getCanvas(), testContext);
2390 if (!result.isOk()) {
2391 return result;
2392 }
2393
2394 std::unique_ptr<skgpu::graphite::Recording> recording = recorder->snap();
2395 if (!recording) {
2396 return Result::Fatal("Could not create a recording.");
2397 }
2398
2399 skgpu::graphite::InsertRecordingInfo info;
2400 info.fRecording = recording.get();
2401 if (!context->insertRecording(info)) {
2402 return Result::Fatal("Context::insertRecording failed.");
2403 }
2404 if (!context->submit(skgpu::graphite::SyncToCpu::kYes)) {
2405 return Result::Fatal("Context::submit failed.");
2406 }
2407
2408 return Result::Ok();
2409 }
2410
2411 Result GraphitePrecompileTestingSink::resetAndRecreatePipelines(
2412 skgpu::graphite::PrecompileContext* precompileContext) const {
2413 using namespace skgpu::graphite;
2414
2415 GlobalCache* globalCache = precompileContext->priv().globalCache();
2416
2417 std::vector<skgpu::UniqueKey> origKeys;
2418
2419 UniqueKeyUtils::FetchUniqueKeys(precompileContext, &origKeys);
2420
2421 std::vector<sk_sp<SkData>> androidStyleKeys;
2422
2423 fPipelineHandler->retrieveKeys(&androidStyleKeys);
2424 fPipelineHandler->reset();
2425
2426 SkASSERTF_RELEASE(origKeys.size() == androidStyleKeys.size(),
2427 "orig %zu != new %zu", origKeys.size(), androidStyleKeys.size());
2428
2429 int numBeforeReset = globalCache->numGraphicsPipelines();
2430 SkASSERT_RELEASE(numBeforeReset == (int) origKeys.size());
2431
2432 globalCache->resetGraphicsPipelines();
2433
2434 SkASSERT_RELEASE(globalCache->numGraphicsPipelines() == 0);
2435
2436 for (sk_sp<SkData>& d : androidStyleKeys) {
2437 bool result = precompileContext->precompile(d);
2438 SkAssertResult(result);
2439 }
2440
2441 int postRecreate = globalCache->numGraphicsPipelines();
2442
2443 SkASSERTF_RELEASE(numBeforeReset == postRecreate,
2444 "before %d after %d", numBeforeReset, postRecreate);
2445
2446 {
2447 std::vector<skgpu::UniqueKey> recreatedKeys;
2448
2449 UniqueKeyUtils::FetchUniqueKeys(precompileContext, &recreatedKeys);
2450
2451 CompareKeys(precompileContext,
2452 origKeys, "original",
2453 recreatedKeys, "recreated");
2454 }
2455
2456 return Result::Ok();
2457 }
2458
2459
2460 #ifdef SK_DEBUG
2461 void GraphitePrecompileTestingSink::LogMissingKey(
2462 skgpu::graphite::PrecompileContext* precompileContext,
2463 const skgpu::UniqueKey& missingKey,
2464 const char* missingKeyName,
2465 const std::vector<skgpu::UniqueKey>& pool,
2466 const char* poolName) {
2467 using namespace skgpu::graphite;
2468
2469 {
2470 GraphicsPipelineDesc originalPipelineDesc;
2471 RenderPassDesc originalRenderPassDesc;
2472 bool extracted = UniqueKeyUtils::ExtractKeyDescs(precompileContext, missingKey,
2473 &originalPipelineDesc,
2474 &originalRenderPassDesc);
2475
2476 SkDebugf("------- Key missing from %s keys:\n", poolName);
2477 missingKey.dump(missingKeyName);
2478 if (extracted) {
2479 UniqueKeyUtils::DumpDescs(precompileContext,
2480 originalPipelineDesc,
2481 originalRenderPassDesc);
2482 }
2483 }
2484
2485 SkDebugf("Have %d %s keys -----------------\n", (int) pool.size(), poolName);
2486 int count = 0;
2487 for (const skgpu::UniqueKey& b : pool) {
2488
2489 GraphicsPipelineDesc recreatedPipelineDesc;
2490 RenderPassDesc recreatedRenderPassDesc;
2491 bool extracted = UniqueKeyUtils::ExtractKeyDescs(precompileContext, b,
2492 &recreatedPipelineDesc,
2493 &recreatedRenderPassDesc);
2494
2495 SkDebugf("%d: ----\n", count++);
2496 b.dump("recreated key:");
2497 if (extracted) {
2498 UniqueKeyUtils::DumpDescs(precompileContext,
2499 recreatedPipelineDesc,
2500 recreatedRenderPassDesc);
2501 }
2502 }
2503 }
2504 #endif
2505
2506 void GraphitePrecompileTestingSink::CompareKeys(
2507 skgpu::graphite::PrecompileContext* precompileContext,
2508 const std::vector<skgpu::UniqueKey>& vA,
2509 const char* aName,
2510 const std::vector<skgpu::UniqueKey>& vB,
2511 const char* bName) {
2512
2513 for (const skgpu::UniqueKey& a : vA) {
2514 if (std::find(vB.begin(), vB.end(), a) == vB.end()) {
2515 #ifdef SK_DEBUG
2516 LogMissingKey(precompileContext, a, aName, vB, bName);
2517 #endif
2518
2519 SK_ABORT("missing");
2520 }
2521 }
2522 }
2523
2524 Result GraphitePrecompileTestingSink::draw(const Src& src,
2525 SkBitmap* dst,
2526 SkWStream* dstStream,
2527 SkString* log) const {
2528 using namespace skgpu::graphite;
2529 using namespace skiatest::graphite;
2530 using namespace skiatools::graphite;
2531
2532 fPipelineHandler->reset();
2533
2534 {
2535 TestOptions options = fOptions;
2536 // If we've copied context options from an external source we can't trust that the
2537 // priv pointer is still in scope, so assume it should be NULL and set our own up.
2538 SkASSERT(!options.fContextOptions.fOptionsPriv);
2539 ContextOptionsPriv optionsPriv;
2540 options.fContextOptions.fOptionsPriv = &optionsPriv;
2541
2542 // We don't expect the src to mess with the more esoteric options
2543 SkDEBUGCODE(auto cache = options.fContextOptions.fPersistentPipelineStorage);
2544 SkDEBUGCODE(auto exec = options.fContextOptions.fExecutor);
2545 SkDEBUGCODE(auto cbContext = options.fContextOptions.fPipelineCallbackContext);
2546 SkDEBUGCODE(auto cb1 = options.fContextOptions.fPipelineCallback);
2547 SkDEBUGCODE(auto cb2 = options.fContextOptions.fPipelineCachingCallback);
2548 src.modifyGraphiteContextOptions(&options.fContextOptions);
2549 SkASSERT(cache == options.fContextOptions.fPersistentPipelineStorage);
2550 SkASSERT(exec == options.fContextOptions.fExecutor);
2551 SkASSERT(cbContext == options.fContextOptions.fPipelineCallbackContext);
2552 SkASSERT(cb1 == options.fContextOptions.fPipelineCallback);
2553 SkASSERT(cb2 == options.fContextOptions.fPipelineCachingCallback);
2554
2555 ContextFactory factory(options);
2556 skiatest::graphite::ContextInfo ctxInfo = factory.getContextInfo(fContextType);
2557 Context* context = ctxInfo.fContext;
2558 if (!context) {
2559 return Result::Fatal("Could not create a context.");
2560 }
2561
2562 std::unique_ptr<skgpu::graphite::Recorder> recorder =
2563 context->makeRecorder(ToolUtils::CreateTestingRecorderOptions());
2564 if (!recorder) {
2565 return Result::Fatal("Could not create a recorder.");
2566 }
2567 std::unique_ptr<PrecompileContext> precompileContext = context->makePrecompileContext();
2568 ShaderCodeDictionary* shaderCodeDictionary = context->priv().shaderCodeDictionary();
2569
2570 SkASSERT_RELEASE(!context->priv().globalCache()->numGraphicsPipelines());
2571 SkASSERT_RELEASE(!shaderCodeDictionary->numUserDefinedRuntimeEffects());
2572
2573 // Draw the Src for the first time, populating the global pipeline cache.
2574 Result result = this->drawSrc(src, context, ctxInfo.fTestContext, recorder.get());
2575 if (!result.isOk()) {
2576 return result;
2577 }
2578
2579 // Note: this is different than numUserDefinedKnownRuntimeEffects! Known user-defined
2580 // runtime effects are allowed while unknown ones are not.
2581 if (shaderCodeDictionary->numUserDefinedRuntimeEffects()) {
2582 return Result::Skip("User-defined runtime effects cannot be serialized");
2583 }
2584
2585 // Call resetAndRecreatePipelines to clear out all the Pipelines in the global cache and
2586 // then regenerate them using the Precompilation system.
2587 result = this->resetAndRecreatePipelines(precompileContext.get());
2588 if (!result.isOk()) {
2589 return result;
2590 }
2591
2592 GlobalCache* globalCache = precompileContext->priv().globalCache();
2593 int numBeforeSecondDraw = globalCache->numGraphicsPipelines();
2594
2595 // Draw the Src for the second time. This shouldn't create any new Pipelines since the ones
2596 // generated via Precompilation should be sufficient.
2597 result = this->drawSrc(src, context, ctxInfo.fTestContext, recorder.get());
2598 if (!result.isOk()) {
2599 return result;
2600 }
2601
2602 SkASSERT_RELEASE(numBeforeSecondDraw == globalCache->numGraphicsPipelines());
2603 }
2604
2605 fPipelineHandler->reset();
2606
2607 return Result::Ok();
2608 }
2609 #endif // SK_ENABLE_PRECOMPILE
2610
2611 #endif // SK_GRAPHITE
2612
2613 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2614
2615 // Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
2616 // passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
2617 // Several examples below.
2618
2619 using DrawToCanvasFn = std::function<DM::Result(SkCanvas*, Src::GraphiteTestContext*)>;
2620
2621 static Result draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream,
2622 SkString* log, SkISize size, const DrawToCanvasFn& draw) {
2623 class ProxySrc : public Src {
2624 public:
2625 ProxySrc(SkISize size, const DrawToCanvasFn& draw) : fSize(size), fDraw(draw) {}
2626 Result draw(SkCanvas* canvas, GraphiteTestContext* testContext) const override {
2627 return fDraw(canvas, testContext);
2628 }
2629 Name name() const override { return "ProxySrc"; }
2630 SkISize size() const override { return fSize; }
2631 private:
2632 SkISize fSize;
2633 const DrawToCanvasFn& fDraw;
2634 };
2635 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
2636 }
2637
2638 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2639
2640 static DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
2641
2642 // Is *bitmap identical to what you get drawing src into sink?
2643 static Result check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
2644 // We can only check raster outputs.
2645 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
2646 if (FLAGS_check && bitmap) {
2647 SkBitmap reference;
2648 SkString log;
2649 SkDynamicMemoryWStream wStream;
2650 Result result = sink->draw(src, &reference, &wStream, &log);
2651 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
2652 SkASSERT(result.isOk());
2653 if (!result.isOk()) {
2654 return result;
2655 }
2656 return compare_bitmaps(reference, *bitmap);
2657 }
2658 return Result::Ok();
2659 }
2660
2661 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2662
2663 static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
2664 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
2665 matrix->mapRect(&bounds);
2666 matrix->postTranslate(-bounds.x(), -bounds.y());
2667 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
2668 }
2669
2670 ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
2671
2672 Result ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2673 SkMatrix matrix = fMatrix;
2674 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
2675 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2676 [&](SkCanvas* canvas,
2677 Src::GraphiteTestContext* testContext) {
2678 canvas->concat(matrix);
2679 return src.draw(canvas, testContext);
2680 });
2681 }
2682
2683 // Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
2684 // This should be pixel-preserving.
2685 ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
2686
2687 Result ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2688 Result result = fSink->draw(src, bitmap, stream, log);
2689 if (!result.isOk()) {
2690 return result;
2691 }
2692
2693 SkMatrix inverse;
2694 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
2695 return Result::Fatal("Cannot upright --matrix.");
2696 }
2697 SkMatrix upright = SkMatrix::I();
2698 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
2699 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
2700 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
2701 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
2702
2703 SkBitmap uprighted;
2704 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
2705 uprighted.allocPixels(bitmap->info().makeDimensions(size));
2706
2707 SkCanvas canvas(uprighted);
2708 canvas.concat(upright);
2709 SkPaint paint;
2710 paint.setBlendMode(SkBlendMode::kSrc);
2711 canvas.drawImage(bitmap->asImage(), 0, 0, SkSamplingOptions(), &paint);
2712
2713 *bitmap = uprighted;
2714 return Result::Ok();
2715 }
2716
2717 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2718
2719 Result ViaSerialization::draw(
2720 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2721 // Record our Src into a picture.
2722 auto size = src.size();
2723 SkPictureRecorder recorder;
2724 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2725 SkIntToScalar(size.height())),
2726 /*GraphiteTestContext=*/nullptr);
2727 if (!result.isOk()) {
2728 return result;
2729 }
2730 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
2731
2732 SkSerialProcs procs = serial_procs_using_png();
2733 SkDeserialProcs dProcs = deserial_procs_using_png();
2734 // Serialize it and then deserialize it.
2735 sk_sp<SkPicture> deserialized = SkPicture::MakeFromData(pic->serialize(&procs).get(), &dProcs);
2736
2737 result = draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2738 [&](SkCanvas* canvas, Src::GraphiteTestContext*) {
2739 canvas->drawPicture(deserialized);
2740 return Result::Ok();
2741 });
2742 if (!result.isOk()) {
2743 return result;
2744 }
2745
2746 return check_against_reference(bitmap, src, fSink.get());
2747 }
2748
2749 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2750
2751 Result ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2752 auto size = src.size();
2753 Result result = draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2754 [&](SkCanvas* canvas, Src::GraphiteTestContext* testContext) {
2755 SkPictureRecorder recorder;
2756 sk_sp<SkPicture> pic;
2757 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2758 SkIntToScalar(size.height())),
2759 testContext);
2760 if (!result.isOk()) {
2761 return result;
2762 }
2763 pic = recorder.finishRecordingAsPicture();
2764 canvas->drawPicture(pic);
2765 return result;
2766 });
2767 if (!result.isOk()) {
2768 return result;
2769 }
2770
2771 return check_against_reference(bitmap, src, fSink.get());
2772 }
2773
2774 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2775
2776 Result ViaRuntimeBlend::draw(const Src& src,
2777 SkBitmap* bitmap,
2778 SkWStream* stream,
2779 SkString* log) const {
2780 class RuntimeBlendFilterCanvas : public SkPaintFilterCanvas {
2781 public:
2782 RuntimeBlendFilterCanvas(SkCanvas* canvas) : INHERITED(canvas) { }
2783
2784 protected:
2785 bool onFilter(SkPaint& paint) const override {
2786 if (std::optional<SkBlendMode> mode = paint.asBlendMode()) {
2787 paint.setBlender(GetRuntimeBlendForBlendMode(*mode));
2788 }
2789 return true;
2790 }
2791
2792 private:
2793 using INHERITED = SkPaintFilterCanvas;
2794 };
2795
2796 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
2797 [&](SkCanvas* canvas, Src::GraphiteTestContext* testContext) {
2798 RuntimeBlendFilterCanvas runtimeBlendCanvas{canvas};
2799 return src.draw(&runtimeBlendCanvas, testContext);
2800 });
2801 }
2802
2803 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2804
2805 #ifdef TEST_VIA_SVG
2806 Result ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2807 auto size = src.size();
2808 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2809 [&](SkCanvas* canvas, Src::GraphiteTestContext* testContext) -> Result {
2810 SkDynamicMemoryWStream wstream;
2811 SkXMLStreamWriter writer(&wstream);
2812 Result result = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get(),
2813 testContext);
2814 if (!result.isOk()) {
2815 return result;
2816 }
2817
2818 auto shapingFactory = SkShapers::BestAvailable();
2819 auto fontMgr = ToolUtils::TestFontMgr();
2820 // When rendering our SVGs we want to be sure we are using shaping.
2821 // If we fail to make a shaper, then it can mean something like skunicode is misconfigured.
2822 SkASSERT(shapingFactory->makeShaper(fontMgr));
2823
2824 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2825 sk_sp<SkSVGDOM> dom = SkSVGDOM::Builder()
2826 .setFontManager(std::move(fontMgr))
2827 .setTextShapingFactory(std::move(shapingFactory))
2828 .make(*rstream);
2829 if (dom) {
2830 dom->setContainerSize(SkSize::Make(size));
2831 dom->render(canvas);
2832 }
2833 return Result::Ok();
2834 });
2835 }
2836 #endif
2837
2838 } // namespace DM