blob: e5eb97571406ba203548c609ce2fe35eda2d08dd [file] [log] [blame]
scroggo478652e2015-03-25 07:11:02 -07001/*
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "dm/DMSrcSink.h"
Tyler Denniston45f94f82020-02-04 16:09:08 -05009#include "gm/verifiers/gmverifier.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "include/codec/SkAndroidCodec.h"
11#include "include/codec/SkCodec.h"
12#include "include/core/SkColorSpace.h"
13#include "include/core/SkData.h"
14#include "include/core/SkDeferredDisplayListRecorder.h"
15#include "include/core/SkDocument.h"
16#include "include/core/SkExecutor.h"
17#include "include/core/SkImageGenerator.h"
18#include "include/core/SkMallocPixelRef.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "include/core/SkPictureRecorder.h"
20#include "include/core/SkStream.h"
21#include "include/core/SkSurface.h"
22#include "include/core/SkSurfaceCharacterization.h"
23#include "include/docs/SkPDFDocument.h"
24#include "include/gpu/GrBackendSurface.h"
25#include "include/ports/SkImageGeneratorCG.h"
26#include "include/ports/SkImageGeneratorWIC.h"
27#include "include/private/SkImageInfoPriv.h"
28#include "include/private/SkTLogic.h"
Brian Osmanea236bf2019-04-29 10:28:22 -040029#include "include/third_party/skcms/skcms.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050030#include "include/utils/SkNullCanvas.h"
31#include "include/utils/SkRandom.h"
Florin Malitafbddfbb2020-05-06 15:55:18 -040032#include "modules/skottie/utils/SkottieUtils.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050033#include "src/codec/SkCodecImageGenerator.h"
34#include "src/codec/SkSwizzler.h"
35#include "src/core/SkAutoMalloc.h"
36#include "src/core/SkAutoPixmapStorage.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050037#include "src/core/SkOSFile.h"
38#include "src/core/SkOpts.h"
39#include "src/core/SkPictureCommon.h"
40#include "src/core/SkPictureData.h"
41#include "src/core/SkRecordDraw.h"
42#include "src/core/SkRecorder.h"
43#include "src/core/SkTaskGroup.h"
44#include "src/gpu/GrContextPriv.h"
45#include "src/gpu/GrGpu.h"
46#include "src/utils/SkMultiPictureDocumentPriv.h"
47#include "src/utils/SkOSPath.h"
48#include "tools/DDLPromiseImageHelper.h"
49#include "tools/DDLTileHelper.h"
50#include "tools/Resources.h"
51#include "tools/debugger/DebugCanvas.h"
52#include "tools/gpu/MemoryCache.h"
msarettfc0b6d12016-03-17 13:50:17 -070053#if defined(SK_BUILD_FOR_WIN)
Mike Kleinc0bd9f92019-04-23 12:05:21 -050054 #include "include/docs/SkXPSDocument.h"
55 #include "src/utils/win/SkAutoCoInitialize.h"
56 #include "src/utils/win/SkHRESULT.h"
57 #include "src/utils/win/SkTScopedComPtr.h"
Hal Canary5e221e72017-02-06 09:51:42 -050058 #include <XpsObjectModel.h>
msarettfc0b6d12016-03-17 13:50:17 -070059#endif
60
Florin Malita87ccf332018-05-04 12:23:24 -040061#if defined(SK_ENABLE_SKOTTIE)
Mike Kleinc0bd9f92019-04-23 12:05:21 -050062 #include "modules/skottie/include/Skottie.h"
Brian Osman849f4d62019-11-26 08:58:26 -050063 #include "modules/skresources/include/SkResources.h"
Florin Malita124d5af2017-12-31 17:02:26 -050064#endif
65
fmalita718df0a2016-07-15 10:33:29 -070066#if defined(SK_XML)
Mike Kleinc0bd9f92019-04-23 12:05:21 -050067 #include "experimental/svg/model/SkSVGDOM.h"
68 #include "include/svg/SkSVGCanvas.h"
69 #include "src/xml/SkXMLWriter.h"
fmalita718df0a2016-07-15 10:33:29 -070070#endif
Mike Kleinc0bd9f92019-04-23 12:05:21 -050071#include "tests/TestUtils.h"
fmalita718df0a2016-07-15 10:33:29 -070072
Hal Canary8a001442018-09-19 11:31:27 -040073#include <cmath>
74#include <functional>
75
Mike Klein84836b72019-03-21 11:31:36 -050076static DEFINE_bool(multiPage, false,
77 "For document-type backends, render the source into multiple pages");
78static DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
halcanary7e798182015-04-14 14:06:18 -070079
Mike Klein4932a5e2019-03-22 11:08:02 -050080DECLARE_int(gpuThreads);
81
bsalomon3724e572016-03-30 18:56:19 -070082using sk_gpu_test::GrContextFactory;
Robert Phillips291f3402020-02-19 14:14:47 -050083using sk_gpu_test::ContextInfo;
bsalomon3724e572016-03-30 18:56:19 -070084
mtklein748ca3b2015-01-15 10:56:12 -080085namespace DM {
86
Hal Canary972eba32018-07-30 17:07:07 -040087GMSrc::GMSrc(skiagm::GMFactory factory) : fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -080088
Ben Wagnerea25fcf2020-02-12 11:18:46 -050089Result GMSrc::draw(SkCanvas* canvas) const {
Hal Canaryedda5652019-08-05 10:28:09 -040090 std::unique_ptr<skiagm::GM> gm(fFactory());
Ben Wagnerea25fcf2020-02-12 11:18:46 -050091 SkString msg;
92 skiagm::DrawResult drawResult = gm->draw(canvas, &msg);
93 switch (drawResult) {
94 case skiagm::DrawResult::kOk : return Result(Result::Status::Ok, msg);
95 case skiagm::DrawResult::kFail: return Result(Result::Status::Fatal, msg);
96 case skiagm::DrawResult::kSkip: return Result(Result::Status::Skip, msg);
97 default: SK_ABORT("");
Chris Dalton50e24d72019-02-07 16:20:09 -070098 }
mtklein748ca3b2015-01-15 10:56:12 -080099}
100
101SkISize GMSrc::size() const {
Hal Canaryedda5652019-08-05 10:28:09 -0400102 std::unique_ptr<skiagm::GM> gm(fFactory());
mtklein748ca3b2015-01-15 10:56:12 -0800103 return gm->getISize();
104}
105
106Name GMSrc::name() const {
Hal Canaryedda5652019-08-05 10:28:09 -0400107 std::unique_ptr<skiagm::GM> gm(fFactory());
mtklein748ca3b2015-01-15 10:56:12 -0800108 return gm->getName();
109}
110
bsalomon4ee6bd82015-05-27 13:23:23 -0700111void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
Hal Canaryedda5652019-08-05 10:28:09 -0400112 std::unique_ptr<skiagm::GM> gm(fFactory());
bsalomon4ee6bd82015-05-27 13:23:23 -0700113 gm->modifyGrContextOptions(options);
114}
115
Tyler Denniston45f94f82020-02-04 16:09:08 -0500116std::unique_ptr<skiagm::verifiers::VerifierList> GMSrc::getVerifiers() const {
117 std::unique_ptr<skiagm::GM> gm(fFactory());
118 return gm->getVerifiers();
119}
120
mtklein748ca3b2015-01-15 10:56:12 -0800121/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
122
msarettd1227a72016-05-18 06:23:57 -0700123BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
msaretta5783ae2015-09-08 15:35:32 -0700124 : fPath(path)
msaretta5783ae2015-09-08 15:35:32 -0700125 , fMode(mode)
126 , fDstColorType(dstColorType)
127 , fSampleSize(sampleSize)
128{}
129
130bool BRDSrc::veto(SinkFlags flags) const {
131 // No need to test to non-raster or indirect backends.
132 return flags.type != SinkFlags::kRaster
133 || flags.approach != SinkFlags::kDirect;
134}
135
msarettd1227a72016-05-18 06:23:57 -0700136static SkBitmapRegionDecoder* create_brd(Path path) {
bungeman38d909e2016-08-02 14:40:46 -0700137 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
msaretta5783ae2015-09-08 15:35:32 -0700138 if (!encoded) {
Ben Wagnera93a14a2017-08-28 10:34:05 -0400139 return nullptr;
msaretta5783ae2015-09-08 15:35:32 -0700140 }
reed42943c82016-09-12 12:01:44 -0700141 return SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy);
msaretta5783ae2015-09-08 15:35:32 -0700142}
143
Matt Sarett334df3a2016-12-15 18:17:33 -0500144static inline void alpha8_to_gray8(SkBitmap* bitmap) {
145 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
146 // them back to kGray8 so our test framework can draw them correctly.
147 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
148 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
149 .makeAlphaType(kOpaque_SkAlphaType);
150 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
151 }
152}
153
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500154Result BRDSrc::draw(SkCanvas* canvas) const {
msaretta5783ae2015-09-08 15:35:32 -0700155 SkColorType colorType = canvas->imageInfo().colorType();
156 if (kRGB_565_SkColorType == colorType &&
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500157 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType)
158 {
159 return Result::Skip("Testing non-565 to 565 is uninteresting.");
msaretta5783ae2015-09-08 15:35:32 -0700160 }
161 switch (fDstColorType) {
162 case CodecSrc::kGetFromCanvas_DstColorType:
163 break;
msaretta5783ae2015-09-08 15:35:32 -0700164 case CodecSrc::kGrayscale_Always_DstColorType:
165 colorType = kGray_8_SkColorType;
166 break;
msarett34e0ec42016-04-22 16:27:24 -0700167 default:
168 SkASSERT(false);
169 break;
msaretta5783ae2015-09-08 15:35:32 -0700170 }
171
Ben Wagner145dbcd2016-11-03 14:40:50 -0400172 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700173 if (nullptr == brd.get()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500174 return Result::Skip("Could not create brd for %s.", fPath.c_str());
msaretta5783ae2015-09-08 15:35:32 -0700175 }
176
Leon Scroggins III0118e972018-03-13 11:14:33 -0400177 auto recommendedCT = brd->computeOutputColorType(colorType);
178 if (kRGB_565_SkColorType == colorType && recommendedCT != colorType) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500179 return Result::Skip("Skip decoding non-opaque to 565.");
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400180 }
Leon Scroggins III0118e972018-03-13 11:14:33 -0400181 colorType = recommendedCT;
182
183 auto colorSpace = brd->computeOutputColorSpace(colorType, nullptr);
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400184
msaretta5783ae2015-09-08 15:35:32 -0700185 const uint32_t width = brd->width();
186 const uint32_t height = brd->height();
187 // Visually inspecting very small output images is not necessary.
188 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500189 return Result::Skip("Scaling very small images is uninteresting.");
msaretta5783ae2015-09-08 15:35:32 -0700190 }
191 switch (fMode) {
192 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700193 SkBitmap bitmap;
194 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
Leon Scroggins III0118e972018-03-13 11:14:33 -0400195 fSampleSize, colorType, false, colorSpace)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500196 return Result::Fatal("Cannot decode (full) region.");
msarett35e5d1b2015-10-27 12:50:25 -0700197 }
Matt Sarett334df3a2016-12-15 18:17:33 -0500198 alpha8_to_gray8(&bitmap);
Matt Sarett8db74f12017-06-14 13:02:05 +0000199
msarett35e5d1b2015-10-27 12:50:25 -0700200 canvas->drawBitmap(bitmap, 0, 0);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500201 return Result::Ok();
msaretta5783ae2015-09-08 15:35:32 -0700202 }
203 case kDivisor_Mode: {
204 const uint32_t divisor = 2;
205 if (width < divisor || height < divisor) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500206 return Result::Skip("Divisor is larger than image dimension.");
msaretta5783ae2015-09-08 15:35:32 -0700207 }
208
209 // Use a border to test subsets that extend outside the image.
210 // We will not allow the border to be larger than the image dimensions. Allowing
211 // these large borders causes off by one errors that indicate a problem with the
212 // test suite, not a problem with the implementation.
Brian Osman788b9162020-02-07 10:36:46 -0500213 const uint32_t maxBorder = std::min(width, height) / (fSampleSize * divisor);
214 const uint32_t scaledBorder = std::min(5u, maxBorder);
msaretta5783ae2015-09-08 15:35:32 -0700215 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
216
217 // We may need to clear the canvas to avoid uninitialized memory.
218 // Assume we are scaling a 780x780 image with sampleSize = 8.
219 // The output image should be 97x97.
220 // Each subset will be 390x390.
221 // Each scaled subset be 48x48.
222 // Four scaled subsets will only fill a 96x96 image.
223 // The bottom row and last column will not be touched.
224 // This is an unfortunate result of our rounding rules when scaling.
225 // Maybe we need to consider testing scaled subsets without trying to
226 // combine them to match the full scaled image? Or maybe this is the
227 // best we can do?
228 canvas->clear(0);
229
230 for (uint32_t x = 0; x < divisor; x++) {
231 for (uint32_t y = 0; y < divisor; y++) {
232 // Calculate the subset dimensions
233 uint32_t subsetWidth = width / divisor;
234 uint32_t subsetHeight = height / divisor;
235 const int left = x * subsetWidth;
236 const int top = y * subsetHeight;
237
238 // Increase the size of the last subset in each row or column, when the
239 // divisor does not divide evenly into the image dimensions
240 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
241 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
242
243 // Increase the size of the subset in order to have a border on each side
244 const int decodeLeft = left - unscaledBorder;
245 const int decodeTop = top - unscaledBorder;
246 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
247 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700248 SkBitmap bitmap;
249 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
Matt Sarett68feef42017-04-11 09:51:32 -0400250 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
Leon Scroggins III0118e972018-03-13 11:14:33 -0400251 colorSpace)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500252 return Result::Fatal("Cannot decode region.");
msarett35e5d1b2015-10-27 12:50:25 -0700253 }
msaretta5783ae2015-09-08 15:35:32 -0700254
Matt Sarett334df3a2016-12-15 18:17:33 -0500255 alpha8_to_gray8(&bitmap);
msarett35e5d1b2015-10-27 12:50:25 -0700256 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700257 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
258 (SkScalar) (subsetWidth / fSampleSize),
259 (SkScalar) (subsetHeight / fSampleSize)),
260 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
261 (SkScalar) (top / fSampleSize),
262 (SkScalar) (subsetWidth / fSampleSize),
263 (SkScalar) (subsetHeight / fSampleSize)),
264 nullptr);
265 }
266 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500267 return Result::Ok();
msaretta5783ae2015-09-08 15:35:32 -0700268 }
269 default:
270 SkASSERT(false);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500271 return Result::Fatal("Error: Should not be reached.");
msaretta5783ae2015-09-08 15:35:32 -0700272 }
273}
274
275SkISize BRDSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400276 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700277 if (brd) {
Brian Osman788b9162020-02-07 10:36:46 -0500278 return {std::max(1, brd->width() / (int)fSampleSize),
279 std::max(1, brd->height() / (int)fSampleSize)};
msaretta5783ae2015-09-08 15:35:32 -0700280 }
Hal Canaryfafe1352017-04-11 12:12:02 -0400281 return {0, 0};
msaretta5783ae2015-09-08 15:35:32 -0700282}
283
284static SkString get_scaled_name(const Path& path, float scale) {
285 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
286}
287
288Name BRDSrc::name() const {
289 // We will replicate the names used by CodecSrc so that images can
290 // be compared in Gold.
291 if (1 == fSampleSize) {
292 return SkOSPath::Basename(fPath.c_str());
293 }
msarett4b0778e2015-11-13 09:59:11 -0800294 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700295}
296
297/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
298
scroggo3ac66e92016-02-08 15:09:48 -0800299static bool serial_from_path_name(const SkString& path) {
300 if (!FLAGS_RAW_threading) {
301 static const char* const exts[] = {
302 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
303 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
304 };
305 const char* actualExt = strrchr(path.c_str(), '.');
306 if (actualExt) {
307 actualExt++;
308 for (auto* ext : exts) {
309 if (0 == strcmp(ext, actualExt)) {
310 return true;
311 }
312 }
313 }
314 }
315 return false;
316}
317
scroggoc5560be2016-02-03 09:42:42 -0800318CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
319 float scale)
msarett438b2ad2015-04-09 12:43:10 -0700320 : fPath(path)
321 , fMode(mode)
322 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800323 , fDstAlphaType(dstAlphaType)
msarett0a242972015-06-11 14:27:27 -0700324 , fScale(scale)
scroggo3ac66e92016-02-08 15:09:48 -0800325 , fRunSerially(serial_from_path_name(path))
msarett438b2ad2015-04-09 12:43:10 -0700326{}
mtklein748ca3b2015-01-15 10:56:12 -0800327
mtklein99cab4e2015-07-31 06:43:04 -0700328bool CodecSrc::veto(SinkFlags flags) const {
msarett18976312016-03-09 14:20:58 -0800329 // Test to direct raster backends (8888 and 565).
msarettb714fb02016-01-22 14:46:42 -0800330 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700331}
scroggo9b77ddd2015-03-19 06:03:39 -0700332
msarett34e0ec42016-04-22 16:27:24 -0700333// Allows us to test decodes to non-native 8888.
msarettb1be46b2016-05-17 08:52:11 -0700334static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700335 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
336 return;
337 }
338
339 for (int y = 0; y < bitmap.height(); y++) {
340 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
341 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
342 }
343}
344
msarettb1be46b2016-05-17 08:52:11 -0700345static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
scroggoba584892016-05-20 13:56:13 -0700346 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
msarett3d9d7a72015-10-21 10:27:10 -0700347 switch (dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700348 case CodecSrc::kGrayscale_Always_DstColorType:
scroggo1a361922016-05-20 14:27:16 -0700349 if (kRGB_565_SkColorType == canvasColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700350 return false;
351 }
scroggoc5560be2016-02-03 09:42:42 -0800352 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700353 break;
msarett34e0ec42016-04-22 16:27:24 -0700354 case CodecSrc::kNonNative8888_Always_DstColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400355 if (kRGB_565_SkColorType == canvasColorType
356 || kRGBA_F16_SkColorType == canvasColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700357 return false;
358 }
359#ifdef SK_PMCOLOR_IS_RGBA
360 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
361#else
362 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
363#endif
364 break;
msarett3d9d7a72015-10-21 10:27:10 -0700365 default:
msarett55f7bdd2016-02-16 13:24:54 -0800366 if (kRGB_565_SkColorType == canvasColorType &&
367 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
368 return false;
369 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800370
scroggoc5560be2016-02-03 09:42:42 -0800371 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700372 break;
373 }
374
scroggoba584892016-05-20 13:56:13 -0700375 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
msarett3d9d7a72015-10-21 10:27:10 -0700376 return true;
377}
378
msarettb1be46b2016-05-17 08:52:11 -0700379static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000380 CodecSrc::DstColorType dstColorType,
msarettb1be46b2016-05-17 08:52:11 -0700381 SkScalar left = 0, SkScalar top = 0) {
msarettb1be46b2016-05-17 08:52:11 -0700382 SkBitmap bitmap;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000383 bitmap.installPixels(info, pixels, rowBytes);
msarettb1be46b2016-05-17 08:52:11 -0700384 swap_rb_if_necessary(bitmap, dstColorType);
385 canvas->drawBitmap(bitmap, left, top);
386}
387
Matt Sarettf485cf92017-05-26 08:58:03 -0400388// For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
389// color format conversions should be performed by the codec. Sometimes the output of the
390// decode will be in an interesting color space. On our srgb and f16 backends, we need to
391// "pretend" that the color space is standard sRGB to avoid triggering color conversion
392// at draw time.
393static void set_bitmap_color_space(SkImageInfo* info) {
Brian Osman6b622962018-08-27 19:16:02 +0000394 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
Matt Sarettf485cf92017-05-26 08:58:03 -0400395}
396
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500397Result CodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700398 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800399 if (!encoded) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500400 return Result::Fatal("Couldn't read %s.", fPath.c_str());
mtklein748ca3b2015-01-15 10:56:12 -0800401 }
msarettb714fb02016-01-22 14:46:42 -0800402
Mike Reedede7bac2017-07-23 15:30:02 -0400403 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700404 if (nullptr == codec.get()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500405 return Result::Fatal("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700406 }
407
scroggoba584892016-05-20 13:56:13 -0700408 SkImageInfo decodeInfo = codec->getInfo();
409 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
410 fDstAlphaType)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500411 return Result::Skip("Skipping uninteresting test.");
msarett438b2ad2015-04-09 12:43:10 -0700412 }
413
msarett0a242972015-06-11 14:27:27 -0700414 // Try to scale the image if it is desired
415 SkISize size = codec->getScaledDimensions(fScale);
416 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500417 return Result::Skip("Test without scaling is uninteresting.");
msarett0a242972015-06-11 14:27:27 -0700418 }
msarettb32758a2015-08-18 13:22:46 -0700419
420 // Visually inspecting very small output images is not necessary. We will
421 // cover these cases in unit testing.
422 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500423 return Result::Skip("Scaling very small images is uninteresting.");
msarettb32758a2015-08-18 13:22:46 -0700424 }
Brian Salomon9241a6d2019-10-03 13:26:54 -0400425 decodeInfo = decodeInfo.makeDimensions(size);
msarett0a242972015-06-11 14:27:27 -0700426
Mike Reed7fcfb622018-02-09 13:26:46 -0500427 const int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700428 const size_t rowBytes = size.width() * bpp;
Mike Reedf0ffb892017-10-03 14:47:21 -0400429 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
scroggo19b91532016-10-24 09:03:26 -0700430 SkAutoMalloc pixels(safeSize);
msarett438b2ad2015-04-09 12:43:10 -0700431
msarettbb25b532016-01-13 09:31:39 -0800432 SkCodec::Options options;
433 if (kCodecZeroInit_Mode == fMode) {
msarettb1be46b2016-05-17 08:52:11 -0700434 memset(pixels.get(), 0, size.height() * rowBytes);
msarettbb25b532016-01-13 09:31:39 -0800435 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
436 }
msarett34e0ec42016-04-22 16:27:24 -0700437
438 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400439 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700440 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
441 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
442 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
443 }
scroggo9b77ddd2015-03-19 06:03:39 -0700444
scroggo9c59ebc2015-03-25 13:48:49 -0700445 switch (fMode) {
scroggo19b91532016-10-24 09:03:26 -0700446 case kAnimated_Mode: {
447 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
448 if (frameInfos.size() <= 1) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500449 return Result::Fatal("%s is not an animated image.", fPath.c_str());
scroggo19b91532016-10-24 09:03:26 -0700450 }
451
scroggo90e971a2016-10-25 06:11:01 -0700452 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
453 // into. "factor" is the number of frames to draw on one row. There will be
454 // up to "factor" rows as well.
455 const float root = sqrt((float) frameInfos.size());
456 const int factor = sk_float_ceil2int(root);
457
scroggo19b91532016-10-24 09:03:26 -0700458 // Used to cache a frame that future frames will depend on.
459 SkAutoMalloc priorFramePixels;
Nigel Tao66bc5242018-08-22 10:56:03 +1000460 int cachedFrame = SkCodec::kNoFrame;
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400461 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
scroggo19b91532016-10-24 09:03:26 -0700462 options.fFrameIndex = i;
463 // Check for a prior frame
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400464 const int reqFrame = frameInfos[i].fRequiredFrame;
Nigel Tao66bc5242018-08-22 10:56:03 +1000465 if (reqFrame != SkCodec::kNoFrame && reqFrame == cachedFrame
scroggo19b91532016-10-24 09:03:26 -0700466 && priorFramePixels.get()) {
467 // Copy into pixels
468 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400469 options.fPriorFrame = reqFrame;
scroggo19b91532016-10-24 09:03:26 -0700470 } else {
Nigel Tao66bc5242018-08-22 10:56:03 +1000471 options.fPriorFrame = SkCodec::kNoFrame;
scroggo19b91532016-10-24 09:03:26 -0700472 }
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500473 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
Leon Scroggins571b30f2017-07-11 17:35:31 +0000474 rowBytes, &options);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500475 if (SkCodec::kInvalidInput == result && i > 0) {
476 // Some of our test images have truncated later frames. Treat that
477 // the same as incomplete.
478 result = SkCodec::kIncompleteInput;
479 }
scroggo19b91532016-10-24 09:03:26 -0700480 switch (result) {
481 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400482 case SkCodec::kErrorInInput:
scroggo90e971a2016-10-25 06:11:01 -0700483 case SkCodec::kIncompleteInput: {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400484 // If the next frame depends on this one, store it in priorFrame.
485 // It is possible that we may discard a frame that future frames depend on,
486 // but the codec will simply redecode the discarded frame.
487 // Do this before calling draw_to_canvas, which premultiplies in place. If
488 // we're decoding to unpremul, we want to pass the unmodified frame to the
489 // codec for decoding the next frame.
490 if (static_cast<size_t>(i+1) < frameInfos.size()
491 && frameInfos[i+1].fRequiredFrame == i) {
492 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
493 cachedFrame = i;
494 }
495
scroggo90e971a2016-10-25 06:11:01 -0700496 SkAutoCanvasRestore acr(canvas, true);
497 const int xTranslate = (i % factor) * decodeInfo.width();
498 const int yTranslate = (i / factor) * decodeInfo.height();
499 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
Leon Scroggins571b30f2017-07-11 17:35:31 +0000500 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Leon Scroggins III674a1842017-07-06 12:26:09 -0400501 if (result != SkCodec::kSuccess) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500502 return Result::Ok();
scroggo19b91532016-10-24 09:03:26 -0700503 }
504 break;
scroggo90e971a2016-10-25 06:11:01 -0700505 }
scroggo53f63b62016-10-27 08:29:13 -0700506 case SkCodec::kInvalidConversion:
Mike Reed304a07c2017-07-12 15:10:28 -0400507 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500508 return Result::Skip(
509 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str());
scroggo53f63b62016-10-27 08:29:13 -0700510 }
511 // Fall through.
scroggo19b91532016-10-24 09:03:26 -0700512 default:
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500513 return Result::Fatal(
514 "Couldn't getPixels for frame %i in %s.", i, fPath.c_str());
scroggo19b91532016-10-24 09:03:26 -0700515 }
scroggo19b91532016-10-24 09:03:26 -0700516 }
517 break;
518 }
msarettbb25b532016-01-13 09:31:39 -0800519 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700520 case kCodec_Mode: {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000521 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggoeb602a52015-07-09 08:16:03 -0700522 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400523 // We consider these to be valid, since we should still decode what is
scroggo9c59ebc2015-03-25 13:48:49 -0700524 // available.
Leon Scroggins III674a1842017-07-06 12:26:09 -0400525 case SkCodec::kErrorInInput:
scroggoeb602a52015-07-09 08:16:03 -0700526 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700527 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700528 default:
529 // Everything else is considered a failure.
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500530 return Result::Fatal("Couldn't getPixels %s.", fPath.c_str());
scroggo9c59ebc2015-03-25 13:48:49 -0700531 }
msarettb1be46b2016-05-17 08:52:11 -0700532
Leon Scroggins571b30f2017-07-11 17:35:31 +0000533 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggo9c59ebc2015-03-25 13:48:49 -0700534 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700535 }
scroggo9c59ebc2015-03-25 13:48:49 -0700536 case kScanline_Mode: {
scroggod8d68552016-06-06 11:26:17 -0700537 void* dst = pixels.get();
538 uint32_t height = decodeInfo.height();
scroggo19b91532016-10-24 09:03:26 -0700539 const bool useIncremental = [this]() {
540 auto exts = { "png", "PNG", "gif", "GIF" };
541 for (auto ext : exts) {
542 if (fPath.endsWith(ext)) {
543 return true;
544 }
545 }
546 return false;
547 }();
548 // ico may use the old scanline method or the new one, depending on whether it
549 // internally holds a bmp or a png.
scroggo8e6c7ad2016-09-16 08:20:38 -0700550 const bool ico = fPath.endsWith("ico");
scroggo19b91532016-10-24 09:03:26 -0700551 bool useOldScanlineMethod = !useIncremental && !ico;
552 if (useIncremental || ico) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700553 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000554 rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700555 int rowsDecoded;
Leon Scroggins III674a1842017-07-06 12:26:09 -0400556 auto result = codec->incrementalDecode(&rowsDecoded);
557 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700558 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
559 SkCodec::kNo_ZeroInitialized, height,
560 rowsDecoded);
scroggo6fb23912016-06-02 14:16:43 -0700561 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700562 } else {
scroggo19b91532016-10-24 09:03:26 -0700563 if (useIncremental) {
564 // Error: These should support incremental decode.
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500565 return Result::Fatal("Could not start incremental decode");
scroggo8e6c7ad2016-09-16 08:20:38 -0700566 }
567 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
568 // which should work via startScanlineDecode
569 useOldScanlineMethod = true;
570 }
571 }
572
573 if (useOldScanlineMethod) {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000574 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500575 return Result::Fatal("Could not start scanline decoder");
scroggo8e6c7ad2016-09-16 08:20:38 -0700576 }
577
Brian Osmanea176c62018-04-06 15:28:23 -0400578 // We do not need to check the return value. On an incomplete
579 // image, memory will be filled with a default value.
580 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700581 }
582
Leon Scroggins571b30f2017-07-11 17:35:31 +0000583 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer97002062015-05-27 12:36:10 -0700584 break;
585 }
msarett0a242972015-06-11 14:27:27 -0700586 case kStripe_Mode: {
587 const int height = decodeInfo.height();
588 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
589 // does not align with image blocks.
590 const int stripeHeight = 37;
591 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
msarettb1be46b2016-05-17 08:52:11 -0700592 void* dst = pixels.get();
msarett0a242972015-06-11 14:27:27 -0700593
594 // Decode odd stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000595 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500596 return Result::Fatal("Could not start scanline decoder");
msarettb65e6042016-02-23 05:37:25 -0800597 }
598
599 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
600 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
601 // to run this test for image types that do not have this scanline ordering.
scroggo12e2f502016-05-16 09:04:18 -0700602 // We only run this on Jpeg, which is always kTopDown.
603 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
msarette6dd0042015-10-09 11:07:34 -0700604
msarett0a242972015-06-11 14:27:27 -0700605 for (int i = 0; i < numStripes; i += 2) {
606 // Skip a stripe
Brian Osman788b9162020-02-07 10:36:46 -0500607 const int linesToSkip = std::min(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700608 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700609
610 // Read a stripe
611 const int startY = (i + 1) * stripeHeight;
Brian Osman788b9162020-02-07 10:36:46 -0500612 const int linesToRead = std::min(stripeHeight, height - startY);
msarett0a242972015-06-11 14:27:27 -0700613 if (linesToRead > 0) {
msarettb1be46b2016-05-17 08:52:11 -0700614 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
615 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700616 }
617 }
618
619 // Decode even stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000620 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
scroggo1c005e42015-08-04 09:24:45 -0700621 if (SkCodec::kSuccess != startResult) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500622 return Result::Fatal("Failed to restart scanline decoder with same parameters.");
msarett0a242972015-06-11 14:27:27 -0700623 }
624 for (int i = 0; i < numStripes; i += 2) {
625 // Read a stripe
626 const int startY = i * stripeHeight;
Brian Osman788b9162020-02-07 10:36:46 -0500627 const int linesToRead = std::min(stripeHeight, height - startY);
msarettb1be46b2016-05-17 08:52:11 -0700628 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
629 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700630
631 // Skip a stripe
Brian Osman788b9162020-02-07 10:36:46 -0500632 const int linesToSkip = std::min(stripeHeight, height - (i + 1) * stripeHeight);
msarettf6db27e2015-06-12 09:34:04 -0700633 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700634 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700635 }
636 }
msarettb1be46b2016-05-17 08:52:11 -0700637
Leon Scroggins571b30f2017-07-11 17:35:31 +0000638 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700639 break;
msarett0a242972015-06-11 14:27:27 -0700640 }
msarett91c22b22016-02-22 12:27:46 -0800641 case kCroppedScanline_Mode: {
642 const int width = decodeInfo.width();
643 const int height = decodeInfo.height();
644 // This value is chosen because, as we move across the image, it will sometimes
645 // align with the jpeg block sizes and it will sometimes not. This allows us
646 // to test interestingly different code paths in the implementation.
647 const int tileSize = 36;
msarett91c22b22016-02-22 12:27:46 -0800648 SkIRect subset;
649 for (int x = 0; x < width; x += tileSize) {
Brian Osman788b9162020-02-07 10:36:46 -0500650 subset = SkIRect::MakeXYWH(x, 0, std::min(tileSize, width - x), height);
Matt Saretta40d9c82017-05-19 15:21:05 -0400651 options.fSubset = &subset;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000652 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500653 return Result::Fatal("Could not start scanline decoder.");
msarett91c22b22016-02-22 12:27:46 -0800654 }
655
msarettb1be46b2016-05-17 08:52:11 -0700656 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
msarett91c22b22016-02-22 12:27:46 -0800657 }
658
Leon Scroggins571b30f2017-07-11 17:35:31 +0000659 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
msarett91c22b22016-02-22 12:27:46 -0800660 break;
661 }
scroggob636b452015-07-22 07:16:20 -0700662 case kSubset_Mode: {
663 // Arbitrarily choose a divisor.
664 int divisor = 2;
665 // Total width/height of the image.
666 const int W = codec->getInfo().width();
667 const int H = codec->getInfo().height();
668 if (divisor > W || divisor > H) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500669 return Result::Skip("Cannot codec subset: divisor %d is too big "
670 "for %s with dimensions (%d x %d)", divisor,
671 fPath.c_str(), W, H);
scroggob636b452015-07-22 07:16:20 -0700672 }
673 // subset dimensions
674 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
675 const int w = SkAlign2(W / divisor);
676 const int h = SkAlign2(H / divisor);
677 SkIRect subset;
Matt Saretta40d9c82017-05-19 15:21:05 -0400678 options.fSubset = &subset;
scroggob636b452015-07-22 07:16:20 -0700679 SkBitmap subsetBm;
680 // We will reuse pixel memory from bitmap.
msarettb1be46b2016-05-17 08:52:11 -0700681 void* dst = pixels.get();
scroggob636b452015-07-22 07:16:20 -0700682 // Keep track of left and top (for drawing subsetBm into canvas). We could use
683 // fScale * x and fScale * y, but we want integers such that the next subset will start
684 // where the last one ended. So we'll add decodeInfo.width() and height().
685 int left = 0;
686 for (int x = 0; x < W; x += w) {
687 int top = 0;
688 for (int y = 0; y < H; y+= h) {
689 // Do not make the subset go off the edge of the image.
Brian Osman788b9162020-02-07 10:36:46 -0500690 const int preScaleW = std::min(w, W - x);
691 const int preScaleH = std::min(h, H - y);
scroggob636b452015-07-22 07:16:20 -0700692 subset.setXYWH(x, y, preScaleW, preScaleH);
693 // And scale
694 // FIXME: Should we have a version of getScaledDimensions that takes a subset
695 // into account?
Brian Osman788b9162020-02-07 10:36:46 -0500696 const int scaledW = std::max(1, SkScalarRoundToInt(preScaleW * fScale));
697 const int scaledH = std::max(1, SkScalarRoundToInt(preScaleH * fScale));
msarettc7eb4902016-04-25 07:04:58 -0700698 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
699 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
msarettb1be46b2016-05-17 08:52:11 -0700700 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
701 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000702 &options);
scroggob636b452015-07-22 07:16:20 -0700703 switch (result) {
704 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400705 case SkCodec::kErrorInInput:
scroggob636b452015-07-22 07:16:20 -0700706 case SkCodec::kIncompleteInput:
707 break;
scroggob636b452015-07-22 07:16:20 -0700708 default:
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500709 return Result::Fatal("subset codec failed to decode (%d, %d, %d, %d) "
710 "from %s with dimensions (%d x %d)\t error %d",
711 x, y, decodeInfo.width(), decodeInfo.height(),
712 fPath.c_str(), W, H, result);
scroggob636b452015-07-22 07:16:20 -0700713 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000714 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
715 SkIntToScalar(left), SkIntToScalar(top));
msarettb1be46b2016-05-17 08:52:11 -0700716
scroggob636b452015-07-22 07:16:20 -0700717 // translate by the scaled height.
718 top += decodeInfo.height();
719 }
720 // translate by the scaled width.
721 left += decodeInfo.width();
722 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500723 return Result::Ok();
scroggob636b452015-07-22 07:16:20 -0700724 }
msarettb714fb02016-01-22 14:46:42 -0800725 default:
726 SkASSERT(false);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500727 return Result::Fatal("Invalid fMode");
scroggo9b77ddd2015-03-19 06:03:39 -0700728 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500729 return Result::Ok();
scroggo9b77ddd2015-03-19 06:03:39 -0700730}
731
732SkISize CodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700733 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400734 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700735 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400736 return {0, 0};
scroggo7fac5af2015-09-30 11:33:12 -0700737 }
scroggo19b91532016-10-24 09:03:26 -0700738
739 auto imageSize = codec->getScaledDimensions(fScale);
740 if (fMode == kAnimated_Mode) {
scroggo90e971a2016-10-25 06:11:01 -0700741 // We'll draw one of each frame, so make it big enough to hold them all
742 // in a grid. The grid will be roughly square, with "factor" frames per
743 // row and up to "factor" rows.
scroggo19b91532016-10-24 09:03:26 -0700744 const size_t count = codec->getFrameInfo().size();
scroggo90e971a2016-10-25 06:11:01 -0700745 const float root = sqrt((float) count);
746 const int factor = sk_float_ceil2int(root);
747 imageSize.fWidth = imageSize.fWidth * factor;
748 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
scroggo19b91532016-10-24 09:03:26 -0700749 }
750 return imageSize;
scroggo9b77ddd2015-03-19 06:03:39 -0700751}
752
753Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700754 if (1.0f == fScale) {
scroggo6e8c68e2016-10-24 13:48:49 -0700755 Name name = SkOSPath::Basename(fPath.c_str());
756 if (fMode == kAnimated_Mode) {
757 name.append("_animated");
758 }
759 return name;
msarett0a242972015-06-11 14:27:27 -0700760 }
scroggo6e8c68e2016-10-24 13:48:49 -0700761 SkASSERT(fMode != kAnimated_Mode);
msaretta5783ae2015-09-08 15:35:32 -0700762 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700763}
764
765/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
766
scroggof8dc9df2016-05-16 09:04:13 -0700767AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800768 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700769 : fPath(path)
msarett3d9d7a72015-10-21 10:27:10 -0700770 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800771 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700772 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800773 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700774{}
775
776bool AndroidCodecSrc::veto(SinkFlags flags) const {
777 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700778 return flags.type != SinkFlags::kRaster
779 || flags.approach != SinkFlags::kDirect;
780}
781
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500782Result AndroidCodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700783 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700784 if (!encoded) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500785 return Result::Fatal("Couldn't read %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700786 }
Mike Reedede7bac2017-07-23 15:30:02 -0400787 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
788 if (nullptr == codec) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500789 return Result::Fatal("Couldn't create android codec for %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700790 }
791
scroggoba584892016-05-20 13:56:13 -0700792 SkImageInfo decodeInfo = codec->getInfo();
793 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
794 fDstAlphaType)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500795 return Result::Skip("Skipping uninteresting test.");
msarett3d9d7a72015-10-21 10:27:10 -0700796 }
797
798 // Scale the image if it is desired.
799 SkISize size = codec->getSampledDimensions(fSampleSize);
800
801 // Visually inspecting very small output images is not necessary. We will
802 // cover these cases in unit testing.
803 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500804 return Result::Skip("Scaling very small images is uninteresting.");
msarett3d9d7a72015-10-21 10:27:10 -0700805 }
Brian Salomon9241a6d2019-10-03 13:26:54 -0400806 decodeInfo = decodeInfo.makeDimensions(size);
msarett3d9d7a72015-10-21 10:27:10 -0700807
Mike Reed7fcfb622018-02-09 13:26:46 -0500808 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700809 size_t rowBytes = size.width() * bpp;
810 SkAutoMalloc pixels(size.height() * rowBytes);
msarett3d9d7a72015-10-21 10:27:10 -0700811
812 SkBitmap bitmap;
msarett34e0ec42016-04-22 16:27:24 -0700813 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400814 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700815 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
816 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
817 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
818 }
msarett3d9d7a72015-10-21 10:27:10 -0700819
820 // Create options for the codec.
821 SkAndroidCodec::AndroidOptions options;
msarett3d9d7a72015-10-21 10:27:10 -0700822 options.fSampleSize = fSampleSize;
823
msarettb1be46b2016-05-17 08:52:11 -0700824 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggof8dc9df2016-05-16 09:04:13 -0700825 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400826 case SkCodec::kErrorInInput:
scroggof8dc9df2016-05-16 09:04:13 -0700827 case SkCodec::kIncompleteInput:
828 break;
msarett3d9d7a72015-10-21 10:27:10 -0700829 default:
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500830 return Result::Fatal("Couldn't getPixels %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700831 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000832 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500833 return Result::Ok();
msarett3d9d7a72015-10-21 10:27:10 -0700834}
835
836SkISize AndroidCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700837 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400838 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
msarett3d9d7a72015-10-21 10:27:10 -0700839 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400840 return {0, 0};
msarett3d9d7a72015-10-21 10:27:10 -0700841 }
842 return codec->getSampledDimensions(fSampleSize);
843}
844
845Name AndroidCodecSrc::name() const {
846 // We will replicate the names used by CodecSrc so that images can
847 // be compared in Gold.
848 if (1 == fSampleSize) {
849 return SkOSPath::Basename(fPath.c_str());
850 }
msarett4b0778e2015-11-13 09:59:11 -0800851 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700852}
853
854/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
855
msarett18976312016-03-09 14:20:58 -0800856ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
857 : fPath(path)
858 , fMode(mode)
859 , fDstAlphaType(alphaType)
860 , fIsGpu(isGpu)
861 , fRunSerially(serial_from_path_name(path))
862{}
863
864bool ImageGenSrc::veto(SinkFlags flags) const {
865 if (fIsGpu) {
Brian Salomonbd7c5512017-03-07 09:08:36 -0500866 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
867 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
868 flags.multisampled == SinkFlags::kMultisampled;
msarett18976312016-03-09 14:20:58 -0800869 }
870
871 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
872}
873
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500874Result ImageGenSrc::draw(SkCanvas* canvas) const {
msarett18976312016-03-09 14:20:58 -0800875 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500876 return Result::Skip("Uninteresting to test image generator to 565.");
msarett18976312016-03-09 14:20:58 -0800877 }
878
bungeman38d909e2016-08-02 14:40:46 -0700879 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett18976312016-03-09 14:20:58 -0800880 if (!encoded) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500881 return Result::Fatal("Couldn't read %s.", fPath.c_str());
msarett18976312016-03-09 14:20:58 -0800882 }
883
msarettfc0b6d12016-03-17 13:50:17 -0700884#if defined(SK_BUILD_FOR_WIN)
885 // Initialize COM in order to test with WIC.
886 SkAutoCoInitialize com;
887 if (!com.succeeded()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500888 return Result::Fatal("Could not initialize COM.");
msarettfc0b6d12016-03-17 13:50:17 -0700889 }
890#endif
891
Ben Wagner145dbcd2016-11-03 14:40:50 -0400892 std::unique_ptr<SkImageGenerator> gen(nullptr);
msarett18976312016-03-09 14:20:58 -0800893 switch (fMode) {
894 case kCodec_Mode:
Mike Reed185130c2017-02-15 15:14:16 -0500895 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
msarett18976312016-03-09 14:20:58 -0800896 if (!gen) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500897 return Result::Fatal("Could not create codec image generator.");
msarett18976312016-03-09 14:20:58 -0800898 }
899 break;
msarettfc0b6d12016-03-17 13:50:17 -0700900 case kPlatform_Mode: {
msarett18976312016-03-09 14:20:58 -0800901#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
Leon Scroggins III0cbc10f2017-10-30 09:07:53 -0400902 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700903#elif defined(SK_BUILD_FOR_WIN)
Leon Scroggins IIIa57488a2018-06-25 14:01:29 -0400904 gen = SkImageGeneratorWIC::MakeFromEncodedWIC(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700905#endif
msarett18976312016-03-09 14:20:58 -0800906 if (!gen) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500907 return Result::Fatal("Could not create platform image generator.");
msarett18976312016-03-09 14:20:58 -0800908 }
909 break;
msarettfc0b6d12016-03-17 13:50:17 -0700910 }
msarett18976312016-03-09 14:20:58 -0800911 default:
912 SkASSERT(false);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500913 return Result::Fatal("Invalid image generator mode");
msarett18976312016-03-09 14:20:58 -0800914 }
915
916 // Test deferred decoding path on GPU
917 if (fIsGpu) {
Mike Reed185130c2017-02-15 15:14:16 -0500918 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
msarett18976312016-03-09 14:20:58 -0800919 if (!image) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500920 return Result::Fatal("Could not create image from codec image generator.");
msarett18976312016-03-09 14:20:58 -0800921 }
922 canvas->drawImage(image, 0, 0);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500923 return Result::Ok();
msarett18976312016-03-09 14:20:58 -0800924 }
mtklein343a63d2016-03-22 11:46:53 -0700925
msarett18976312016-03-09 14:20:58 -0800926 // Test various color and alpha types on CPU
927 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
mtklein343a63d2016-03-22 11:46:53 -0700928
Mike Reed7fcfb622018-02-09 13:26:46 -0500929 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700930 size_t rowBytes = decodeInfo.width() * bpp;
931 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
Brian Osmanc87cfb62018-07-11 09:08:46 -0400932 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500933 Result::Status status = Result::Status::Fatal;
Matt Sarett05cb4c32017-03-02 12:07:46 -0500934#if defined(SK_BUILD_FOR_WIN)
935 if (kPlatform_Mode == fMode) {
936 // Do not issue a fatal error for WIC flakiness.
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500937 status = Result::Status::Skip;
Matt Sarett05cb4c32017-03-02 12:07:46 -0500938 }
939#endif
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500940 return Result(status, "Image generator could not getPixels() for %s\n", fPath.c_str());
msarett18976312016-03-09 14:20:58 -0800941 }
942
Matt Sarettf485cf92017-05-26 08:58:03 -0400943 set_bitmap_color_space(&decodeInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +0000944 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
msarettb1be46b2016-05-17 08:52:11 -0700945 CodecSrc::kGetFromCanvas_DstColorType);
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500946 return Result::Ok();
msarett18976312016-03-09 14:20:58 -0800947}
948
949SkISize ImageGenSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700950 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400951 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett18976312016-03-09 14:20:58 -0800952 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400953 return {0, 0};
msarett18976312016-03-09 14:20:58 -0800954 }
955 return codec->getInfo().dimensions();
956}
957
958Name ImageGenSrc::name() const {
959 return SkOSPath::Basename(fPath.c_str());
960}
961
962/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
963
Mike Klein0d5d1422019-03-06 10:56:04 -0600964ColorCodecSrc::ColorCodecSrc(Path path, bool decode_to_dst) : fPath(path)
965 , fDecodeToDst(decode_to_dst) {}
msarett69deca82016-04-29 09:38:40 -0700966
967bool ColorCodecSrc::veto(SinkFlags flags) const {
968 // Test to direct raster backends (8888 and 565).
969 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
970}
971
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500972Result ColorCodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700973 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett69deca82016-04-29 09:38:40 -0700974 if (!encoded) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500975 return Result::Fatal("Couldn't read %s.", fPath.c_str());
msarett69deca82016-04-29 09:38:40 -0700976 }
977
Mike Reedede7bac2017-07-23 15:30:02 -0400978 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
979 if (nullptr == codec) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500980 return Result::Fatal("Couldn't create codec for %s.", fPath.c_str());
msarett69deca82016-04-29 09:38:40 -0700981 }
982
Mike Klein0d5d1422019-03-06 10:56:04 -0600983 SkImageInfo info = codec->getInfo();
984 if (fDecodeToDst) {
Leon Scroggins III42a604f2020-02-06 15:47:58 -0500985 SkImageInfo canvasInfo = canvas->imageInfo();
986 if (!canvasInfo.colorSpace()) {
987 // This will skip color conversion, and the resulting images will
988 // look different from images they are compared against in Gold, but
989 // that doesn't mean they are wrong. We have a test verifying that
990 // passing a null SkColorSpace skips conversion, so skip this
991 // misleading test.
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500992 return Result::Skip("Skipping decoding without color transform.");
Leon Scroggins III42a604f2020-02-06 15:47:58 -0500993 }
994 info = canvasInfo.makeDimensions(info.dimensions());
msarett50ce1f22016-07-29 06:23:33 -0700995 }
996
997 SkBitmap bitmap;
Mike Klein0d5d1422019-03-06 10:56:04 -0600998 if (!bitmap.tryAllocPixels(info)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -0500999 return Result::Fatal("Image(%s) is too large (%d x %d)",
1000 fPath.c_str(), info.width(), info.height());
msarett50ce1f22016-07-29 06:23:33 -07001001 }
1002
Mike Klein0d5d1422019-03-06 10:56:04 -06001003 switch (auto r = codec->getPixels(info, bitmap.getPixels(), bitmap.rowBytes())) {
Leon Scroggins III674a1842017-07-06 12:26:09 -04001004 case SkCodec::kSuccess:
1005 case SkCodec::kErrorInInput:
1006 case SkCodec::kIncompleteInput:
Mike Klein0d5d1422019-03-06 10:56:04 -06001007 canvas->drawBitmap(bitmap, 0,0);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001008 return Result::Ok();
Mike Klein0d5d1422019-03-06 10:56:04 -06001009 case SkCodec::kInvalidConversion:
1010 // TODO(mtklein): why are there formats we can't decode to?
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001011 return Result::Skip("SkCodec can't decode to this format.");
Leon Scroggins III674a1842017-07-06 12:26:09 -04001012 default:
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001013 return Result::Fatal("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
msarett50ce1f22016-07-29 06:23:33 -07001014 }
msarett69deca82016-04-29 09:38:40 -07001015}
1016
1017SkISize ColorCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001018 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001019 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett69deca82016-04-29 09:38:40 -07001020 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001021 return {0, 0};
msarett69deca82016-04-29 09:38:40 -07001022 }
Hal Canaryfafe1352017-04-11 12:12:02 -04001023 return {codec->getInfo().width(), codec->getInfo().height()};
msarett69deca82016-04-29 09:38:40 -07001024}
1025
1026Name ColorCodecSrc::name() const {
1027 return SkOSPath::Basename(fPath.c_str());
1028}
1029
1030/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1031
Mike Klein19fb3972019-03-21 13:08:08 -05001032static DEFINE_int(skpViewportSize, 1000,
1033 "Width & height of the viewport used to crop skp rendering.");
1034
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001035SKPSrc::SKPSrc(Path path) : fPath(path) { }
mtklein748ca3b2015-01-15 10:56:12 -08001036
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001037Result SKPSrc::draw(SkCanvas* canvas) const {
Hal Canary72b91cb2019-01-14 12:47:59 -05001038 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(fPath.c_str());
1039 if (!stream) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001040 return Result::Fatal("Couldn't read %s.", fPath.c_str());
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001041 }
Hal Canary72b91cb2019-01-14 12:47:59 -05001042 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get()));
1043 if (!pic) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001044 return Result::Fatal("Couldn't parse file %s.", fPath.c_str());
Hal Canary72b91cb2019-01-14 12:47:59 -05001045 }
1046 stream = nullptr; // Might as well drop this when we're done with it.
Robert Phillips33f02ed2018-03-27 08:06:57 -04001047 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
mtklein748ca3b2015-01-15 10:56:12 -08001048 canvas->drawPicture(pic);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001049 return Result::Ok();
mtklein748ca3b2015-01-15 10:56:12 -08001050}
1051
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001052static SkRect get_cull_rect_for_skp(const char* path) {
1053 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtkleinffa901a2015-03-16 10:38:07 -07001054 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001055 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001056 }
1057 SkPictInfo info;
Mike Reede7a58322017-12-20 14:09:20 -05001058 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001059 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001060 }
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001061
1062 return info.fCullRect;
1063}
1064
1065SkISize SKPSrc::size() const {
1066 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
Robert Phillips33f02ed2018-03-27 08:06:57 -04001067 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001068 return {0, 0};
mtkleinffa901a2015-03-16 10:38:07 -07001069 }
1070 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -08001071}
1072
1073Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1074
Florin Malitafc043dc2017-12-31 11:08:42 -05001075/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1076
Chris Dalton184c37e2018-09-28 11:27:39 -06001077BisectSrc::BisectSrc(Path path, const char* trail) : INHERITED(path), fTrail(trail) {}
1078
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001079Result BisectSrc::draw(SkCanvas* canvas) const {
Chris Dalton184c37e2018-09-28 11:27:39 -06001080 struct FoundPath {
1081 SkPath fPath;
1082 SkPaint fPaint;
1083 SkMatrix fViewMatrix;
1084 };
1085
1086 // This subclass of SkCanvas just extracts all the SkPaths (drawn via drawPath) from an SKP.
1087 class PathFindingCanvas : public SkCanvas {
1088 public:
1089 PathFindingCanvas(int width, int height) : SkCanvas(width, height, nullptr) {}
1090 const SkTArray<FoundPath>& foundPaths() const { return fFoundPaths; }
1091
1092 private:
1093 void onDrawPath(const SkPath& path, const SkPaint& paint) override {
1094 fFoundPaths.push_back() = {path, paint, this->getTotalMatrix()};
1095 }
1096
1097 SkTArray<FoundPath> fFoundPaths;
1098 };
1099
1100 PathFindingCanvas pathFinder(canvas->getBaseLayerSize().width(),
1101 canvas->getBaseLayerSize().height());
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001102 Result result = this->INHERITED::draw(&pathFinder);
1103 if (!result.isOk()) {
1104 return result;
Chris Dalton184c37e2018-09-28 11:27:39 -06001105 }
1106
1107 int start = 0, end = pathFinder.foundPaths().count();
1108 for (const char* ch = fTrail.c_str(); *ch; ++ch) {
1109 int midpt = (start + end) / 2;
1110 if ('l' == *ch) {
1111 start = midpt;
1112 } else if ('r' == *ch) {
1113 end = midpt;
1114 }
1115 }
1116
1117 for (int i = start; i < end; ++i) {
1118 const FoundPath& path = pathFinder.foundPaths()[i];
1119 SkAutoCanvasRestore acr(canvas, true);
1120 canvas->concat(path.fViewMatrix);
1121 canvas->drawPath(path.fPath, path.fPaint);
1122 }
1123
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001124 return Result::Ok();
Chris Dalton184c37e2018-09-28 11:27:39 -06001125}
1126
1127/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1128
Florin Malita87ccf332018-05-04 12:23:24 -04001129#if defined(SK_ENABLE_SKOTTIE)
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001130SkottieSrc::SkottieSrc(Path path) : fPath(std::move(path)) {}
Florin Malitafc043dc2017-12-31 11:08:42 -05001131
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001132Result SkottieSrc::draw(SkCanvas* canvas) const {
Florin Malitafbddfbb2020-05-06 15:55:18 -04001133 auto resource_provider =
1134 skresources::DataURIResourceProviderProxy::Make(
1135 skresources::FileResourceProvider::Make(SkOSPath::Dirname(fPath.c_str()),
1136 /*predecode=*/true),
1137 /*predecode=*/true);
1138
1139 static constexpr char kInterceptPrefix[] = "__";
1140 auto precomp_interceptor =
1141 sk_make_sp<skottie_utils::ExternalAnimationPrecompInterceptor>(resource_provider,
1142 kInterceptPrefix);
Florin Malitaa8316552018-11-09 16:19:44 -05001143 auto animation = skottie::Animation::Builder()
Florin Malitafbddfbb2020-05-06 15:55:18 -04001144 .setResourceProvider(std::move(resource_provider))
1145 .setPrecompInterceptor(std::move(precomp_interceptor))
Florin Malitaa8316552018-11-09 16:19:44 -05001146 .makeFromFile(fPath.c_str());
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001147 if (!animation) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001148 return Result::Fatal("Unable to parse file: %s", fPath.c_str());
Florin Malitafc043dc2017-12-31 11:08:42 -05001149 }
1150
1151 canvas->drawColor(SK_ColorWHITE);
1152
Florin Malitaa33447d2018-05-29 13:46:54 -04001153 const auto t_rate = 1.0f / (kTileCount * kTileCount - 1);
Florin Malitafc043dc2017-12-31 11:08:42 -05001154
Kevin Lubickc5fe15d2018-08-29 09:52:52 -04001155 // Draw the frames in a shuffled order to exercise non-linear
1156 // frame progression. The film strip will still be in order left-to-right,
1157 // top-down, just not drawn in that order.
1158 static constexpr int frameOrder[] = { 4, 0, 3, 1, 2 };
1159 static_assert(SK_ARRAY_COUNT(frameOrder) == kTileCount, "");
Florin Malitad3c1b842018-01-27 12:43:24 -05001160
Florin Malitafc043dc2017-12-31 11:08:42 -05001161 for (int i = 0; i < kTileCount; ++i) {
Kevin Lubickc5fe15d2018-08-29 09:52:52 -04001162 const SkScalar y = frameOrder[i] * kTileSize;
Florin Malitafc043dc2017-12-31 11:08:42 -05001163
1164 for (int j = 0; j < kTileCount; ++j) {
Kevin Lubickc5fe15d2018-08-29 09:52:52 -04001165 const SkScalar x = frameOrder[j] * kTileSize;
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001166 SkRect dest = SkRect::MakeXYWH(x, y, kTileSize, kTileSize);
Florin Malitafc043dc2017-12-31 11:08:42 -05001167
Kevin Lubickc5fe15d2018-08-29 09:52:52 -04001168 const auto t = t_rate * (frameOrder[i] * kTileCount + frameOrder[j]);
Florin Malitadf2713c2018-01-09 15:51:21 -05001169 {
1170 SkAutoCanvasRestore acr(canvas, true);
Florin Malitad3c1b842018-01-27 12:43:24 -05001171 canvas->clipRect(dest, true);
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001172 canvas->concat(SkMatrix::MakeRectToRect(SkRect::MakeSize(animation->size()),
Florin Malitadf2713c2018-01-09 15:51:21 -05001173 dest,
Florin Malita3fae0f32018-03-15 21:52:54 -04001174 SkMatrix::kCenter_ScaleToFit));
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001175 animation->seek(t);
1176 animation->render(canvas);
Florin Malitadf2713c2018-01-09 15:51:21 -05001177 }
Florin Malitafc043dc2017-12-31 11:08:42 -05001178 }
1179 }
1180
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001181 return Result::Ok();
Florin Malitafc043dc2017-12-31 11:08:42 -05001182}
1183
Florin Malita54f65c42018-01-16 17:04:30 -05001184SkISize SkottieSrc::size() const {
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001185 return SkISize::Make(kTargetSize, kTargetSize);
Florin Malitafc043dc2017-12-31 11:08:42 -05001186}
1187
Florin Malita9f7d4cd2018-07-30 15:49:20 -04001188Name SkottieSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
Florin Malitafc043dc2017-12-31 11:08:42 -05001189
Florin Malita54f65c42018-01-16 17:04:30 -05001190bool SkottieSrc::veto(SinkFlags flags) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001191 // No need to test to non-(raster||gpu||vector) or indirect backends.
1192 bool type_ok = flags.type == SinkFlags::kRaster
1193 || flags.type == SinkFlags::kGPU
1194 || flags.type == SinkFlags::kVector;
1195
1196 return !type_ok || flags.approach != SinkFlags::kDirect;
1197}
Florin Malita124d5af2017-12-31 17:02:26 -05001198#endif
Florin Malitafc043dc2017-12-31 11:08:42 -05001199
1200/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
fmalitaa2b9fdf2016-08-03 19:53:36 -07001201#if defined(SK_XML)
fmalitabdf3e5c2016-09-17 07:26:26 -07001202// Used when the image doesn't have an intrinsic size.
Hal Canaryfafe1352017-04-11 12:12:02 -04001203static const SkSize kDefaultSVGSize = {1000, 1000};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001204
fmalitabdf3e5c2016-09-17 07:26:26 -07001205// Used to force-scale tiny fixed-size images.
Hal Canaryfafe1352017-04-11 12:12:02 -04001206static const SkSize kMinimumSVGSize = {128, 128};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001207
fmalitaacd2f5c2016-11-08 07:13:45 -08001208SVGSrc::SVGSrc(Path path)
1209 : fName(SkOSPath::Basename(path.c_str()))
1210 , fScale(1) {
fmalitabdf3e5c2016-09-17 07:26:26 -07001211
Brian Osman133823d2018-09-19 14:14:15 -04001212 sk_sp<SkData> data(SkData::MakeFromFileName(path.c_str()));
1213 if (!data) {
1214 return;
1215 }
fmalitaacd2f5c2016-11-08 07:13:45 -08001216
Brian Osman133823d2018-09-19 14:14:15 -04001217 SkMemoryStream stream(std::move(data));
1218 fDom = SkSVGDOM::MakeFromStream(stream);
1219 if (!fDom) {
1220 return;
1221 }
1222
1223 const SkSize& sz = fDom->containerSize();
1224 if (sz.isEmpty()) {
1225 // no intrinsic size
1226 fDom->setContainerSize(kDefaultSVGSize);
1227 } else {
Brian Osman788b9162020-02-07 10:36:46 -05001228 fScale = std::max(1.f, std::max(kMinimumSVGSize.width() / sz.width(),
Brian Osman133823d2018-09-19 14:14:15 -04001229 kMinimumSVGSize.height() / sz.height()));
1230 }
fmalitaacd2f5c2016-11-08 07:13:45 -08001231}
1232
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001233Result SVGSrc::draw(SkCanvas* canvas) const {
fmalitabdf3e5c2016-09-17 07:26:26 -07001234 if (!fDom) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001235 return Result::Fatal("Unable to parse file: %s", fName.c_str());
fmalitaa2b9fdf2016-08-03 19:53:36 -07001236 }
1237
fmalitaacd2f5c2016-11-08 07:13:45 -08001238 SkAutoCanvasRestore acr(canvas, true);
1239 canvas->scale(fScale, fScale);
1240 fDom->render(canvas);
1241
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001242 return Result::Ok();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001243}
1244
1245SkISize SVGSrc::size() const {
fmalitaacd2f5c2016-11-08 07:13:45 -08001246 if (!fDom) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001247 return {0, 0};
fmalitabdf3e5c2016-09-17 07:26:26 -07001248 }
1249
Hal Canaryfafe1352017-04-11 12:12:02 -04001250 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1251 .toRound();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001252}
1253
fmalitaacd2f5c2016-11-08 07:13:45 -08001254Name SVGSrc::name() const { return fName; }
fmalitaa2b9fdf2016-08-03 19:53:36 -07001255
fmalita179d8852016-08-16 14:23:29 -07001256bool SVGSrc::veto(SinkFlags flags) const {
Florin Malita93323eb2017-06-16 15:31:17 -04001257 // No need to test to non-(raster||gpu||vector) or indirect backends.
fmalita179d8852016-08-16 14:23:29 -07001258 bool type_ok = flags.type == SinkFlags::kRaster
Florin Malita93323eb2017-06-16 15:31:17 -04001259 || flags.type == SinkFlags::kGPU
1260 || flags.type == SinkFlags::kVector;
fmalita179d8852016-08-16 14:23:29 -07001261
1262 return !type_ok || flags.approach != SinkFlags::kDirect;
1263}
1264
fmalitaa2b9fdf2016-08-03 19:53:36 -07001265#endif // defined(SK_XML)
1266/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -08001267
halcanary45420a92016-06-02 12:41:14 -07001268MSKPSrc::MSKPSrc(Path path) : fPath(path) {
bungemanf93d7112016-09-16 06:24:20 -07001269 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001270 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1271 if (count > 0) {
1272 fPages.reset(count);
1273 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1274 }
halcanary45420a92016-06-02 12:41:14 -07001275}
1276
Hal Canary45cde312017-04-03 16:06:42 -04001277int MSKPSrc::pageCount() const { return fPages.count(); }
halcanary45420a92016-06-02 12:41:14 -07001278
1279SkISize MSKPSrc::size() const { return this->size(0); }
Hal Canary45cde312017-04-03 16:06:42 -04001280SkISize MSKPSrc::size(int i) const {
Hal Canaryfafe1352017-04-11 12:12:02 -04001281 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
Hal Canary45cde312017-04-03 16:06:42 -04001282}
halcanary45420a92016-06-02 12:41:14 -07001283
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001284Result MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
1285Result MSKPSrc::draw(int i, SkCanvas* canvas) const {
Hal Canary45cde312017-04-03 16:06:42 -04001286 if (this->pageCount() == 0) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001287 return Result::Fatal("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
halcanary45420a92016-06-02 12:41:14 -07001288 }
Hal Canary45cde312017-04-03 16:06:42 -04001289 if (i >= fPages.count() || i < 0) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001290 return Result::Fatal("MultiPictureDocument page number out of range: %d", i);
halcanary45420a92016-06-02 12:41:14 -07001291 }
Hal Canary45cde312017-04-03 16:06:42 -04001292 SkPicture* page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001293 if (!page) {
Hal Canary45cde312017-04-03 16:06:42 -04001294 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1295 if (!stream) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001296 return Result::Fatal("Unable to open file: %s", fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001297 }
1298 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001299 return Result::Fatal("SkMultiPictureDocument reader failed on page %d: %s", i,
1300 fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001301 }
1302 page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001303 }
1304 canvas->drawPicture(page);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001305 return Result::Ok();
halcanary45420a92016-06-02 12:41:14 -07001306}
1307
1308Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1309
1310/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1311
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001312Result NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
Mike Reed5df49342016-11-12 08:06:55 -06001313 return src.draw(SkMakeNullCanvas().get());
mtkleinad66f9b2015-02-13 15:11:10 -08001314}
1315
1316/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1317
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001318static Result compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001319 // The dimensions are a property of the Src only, and so should be identical.
Mike Reedf0ffb892017-10-03 14:47:21 -04001320 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1321 if (reference.computeByteSize() != bitmap.computeByteSize()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001322 return Result::Fatal("Dimensions don't match reference");
Brian Osmane5756ec2017-09-06 17:08:30 -04001323 }
1324 // All SkBitmaps in DM are tight, so this comparison is easy.
Mike Reedf0ffb892017-10-03 14:47:21 -04001325 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001326 SkString encoded;
1327 SkString errString("Pixels don't match reference");
Brian Salomon28a8f282019-10-24 20:07:39 -04001328 if (BipmapToBase64DataURI(reference, &encoded)) {
Michael Ludwige8e10752018-10-01 12:42:53 -04001329 errString.append("\nExpected: ");
Brian Osmane5756ec2017-09-06 17:08:30 -04001330 errString.append(encoded);
1331 } else {
1332 errString.append("\nExpected image failed to encode: ");
1333 errString.append(encoded);
1334 }
Brian Salomon28a8f282019-10-24 20:07:39 -04001335 if (BipmapToBase64DataURI(bitmap, &encoded)) {
Michael Ludwige8e10752018-10-01 12:42:53 -04001336 errString.append("\nActual: ");
Brian Osmane5756ec2017-09-06 17:08:30 -04001337 errString.append(encoded);
1338 } else {
1339 errString.append("\nActual image failed to encode: ");
1340 errString.append(encoded);
1341 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001342 return Result::Fatal(errString);
Brian Osmane5756ec2017-09-06 17:08:30 -04001343 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001344 return Result::Ok();
Brian Osmane5756ec2017-09-06 17:08:30 -04001345}
1346
1347/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1348
Mike Klein84836b72019-03-21 11:31:36 -05001349static DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
Mike Klein19fb3972019-03-21 13:08:08 -05001350static DEFINE_bool(preAbandonGpuContext, false,
1351 "Test abandoning the GrContext before running the test.");
1352static DEFINE_bool(abandonGpuContext, false,
1353 "Test abandoning the GrContext after running each test.");
1354static DEFINE_bool(releaseAndAbandonGpuContext, false,
1355 "Test releasing all gpu resources and abandoning the GrContext "
1356 "after running each test");
1357static DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
Brian Osman9c310472019-06-27 16:43:27 -04001358static DEFINE_bool(programBinaryCache, true, "Use in-memory program binary cache");
mtkleinb9eb4ac2015-02-02 18:26:03 -08001359
Brian Osman3fdfe282019-09-09 13:46:52 -04001360GPUSink::GPUSink(const SkCommandLineConfigGpu* config,
Brian Osmanf21aa042017-08-21 16:48:46 -04001361 const GrContextOptions& grCtxOptions)
Brian Osman3fdfe282019-09-09 13:46:52 -04001362 : fContextType(config->getContextType())
1363 , fContextOverrides(config->getContextOverrides())
1364 , fSurfType(config->getSurfType())
1365 , fSampleCount(config->getSamples())
1366 , fUseDIText(config->getUseDIText())
1367 , fColorType(config->getColorType())
1368 , fAlphaType(config->getAlphaType())
1369 , fColorSpace(sk_ref_sp(config->getColorSpace()))
Brian Osman9c310472019-06-27 16:43:27 -04001370 , fBaseContextOptions(grCtxOptions) {
1371 if (FLAGS_programBinaryCache) {
1372 fBaseContextOptions.fPersistentCache = &fMemoryCache;
1373 }
1374}
mtklein748ca3b2015-01-15 10:56:12 -08001375
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001376Result GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
Brian Osmanf9810662017-08-30 10:02:10 -04001377 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1378}
1379
Robert Phillips3c1efd42020-02-13 15:51:59 -05001380sk_sp<SkSurface> GPUSink::createDstSurface(GrContext* context, SkISize size,
1381 GrBackendTexture* backendTexture,
1382 GrBackendRenderTarget* backendRT) const {
1383 sk_sp<SkSurface> surface;
1384
1385 SkImageInfo info = SkImageInfo::Make(size, fColorType, fAlphaType, fColorSpace);
1386 uint32_t flags = fUseDIText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
1387 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
1388
1389 switch (fSurfType) {
1390 case SkCommandLineConfigGpu::SurfType::kDefault:
1391 surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, fSampleCount,
1392 &props);
1393 break;
1394 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
Greg Danielc1ad77c2020-05-06 11:40:03 -04001395 CreateBackendTexture(context, backendTexture, info.width(), info.height(),
1396 info.colorType(), SkColors::kTransparent, GrMipMapped::kNo,
1397 GrRenderable::kYes, GrProtected::kNo);
Robert Phillips3c1efd42020-02-13 15:51:59 -05001398 surface = SkSurface::MakeFromBackendTexture(context, *backendTexture,
1399 kTopLeft_GrSurfaceOrigin, fSampleCount,
1400 fColorType, info.refColorSpace(), &props);
1401 break;
1402 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1403 if (1 == fSampleCount) {
1404 auto colorType = SkColorTypeToGrColorType(info.colorType());
1405 *backendRT = context->priv().getGpu()->createTestingOnlyBackendRenderTarget(
1406 info.width(), info.height(), colorType);
1407 surface = SkSurface::MakeFromBackendRenderTarget(
1408 context, *backendRT, kBottomLeft_GrSurfaceOrigin, info.colorType(),
1409 info.refColorSpace(), &props);
1410 }
1411 break;
1412 }
1413
1414 return surface;
1415}
1416
1417bool GPUSink::readBack(SkSurface* surface, SkBitmap* dst) const {
1418 SkCanvas* canvas = surface->getCanvas();
1419 SkISize size = surface->imageInfo().dimensions();
1420
1421 SkImageInfo info = SkImageInfo::Make(size, fColorType, fAlphaType, fColorSpace);
Robert Phillips3c1efd42020-02-13 15:51:59 -05001422 dst->allocPixels(info);
1423 return canvas->readPixels(*dst, 0, 0);
1424}
1425
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001426Result GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1427 const GrContextOptions& baseOptions,
1428 std::function<void(GrContext*)> initContext) const {
Brian Osmanf9810662017-08-30 10:02:10 -04001429 GrContextOptions grOptions = baseOptions;
kkinnunen64492c42015-12-08 01:24:40 -08001430
Brian Salomon00a5eb82018-07-11 15:32:05 -04001431 // We don't expect the src to mess with the persistent cache or the executor.
1432 SkDEBUGCODE(auto cache = grOptions.fPersistentCache);
1433 SkDEBUGCODE(auto exec = grOptions.fExecutor);
kkinnunen5219fd92015-12-10 06:28:13 -08001434 src.modifyGrContextOptions(&grOptions);
Brian Salomon00a5eb82018-07-11 15:32:05 -04001435 SkASSERT(cache == grOptions.fPersistentCache);
1436 SkASSERT(exec == grOptions.fExecutor);
kkinnunen5219fd92015-12-10 06:28:13 -08001437
1438 GrContextFactory factory(grOptions);
csmartdaltone812d492017-02-21 12:36:05 -07001439 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
Brian Osmaned58e002019-09-06 14:42:43 -04001440 if (initContext) {
1441 initContext(context);
1442 }
Robert Phillips3c1efd42020-02-13 15:51:59 -05001443
Robert Phillips45f37c32020-02-13 20:26:58 +00001444 const int maxDimension = context->priv().caps()->maxTextureSize();
Robert Phillips3c1efd42020-02-13 15:51:59 -05001445 if (maxDimension < std::max(src.size().width(), src.size().height())) {
Robert Phillips45f37c32020-02-13 20:26:58 +00001446 return Result::Skip("Src too large to create a texture.\n");
1447 }
Robert Phillips3c1efd42020-02-13 15:51:59 -05001448
Brian Salomonf865b052018-03-09 09:01:53 -05001449 GrBackendTexture backendTexture;
1450 GrBackendRenderTarget backendRT;
Robert Phillips3c1efd42020-02-13 15:51:59 -05001451 sk_sp<SkSurface> surface = this->createDstSurface(context, src.size(),
1452 &backendTexture, &backendRT);
mtklein748ca3b2015-01-15 10:56:12 -08001453 if (!surface) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001454 return Result::Fatal("Could not create a surface.");
mtklein748ca3b2015-01-15 10:56:12 -08001455 }
joshualitt5f5a8d72015-02-25 14:09:45 -08001456 if (FLAGS_preAbandonGpuContext) {
joshualitt5f5a8d72015-02-25 14:09:45 -08001457 factory.abandonContexts();
1458 }
mtklein748ca3b2015-01-15 10:56:12 -08001459 SkCanvas* canvas = surface->getCanvas();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001460 Result result = src.draw(canvas);
1461 if (!result.isOk()) {
1462 return result;
mtklein748ca3b2015-01-15 10:56:12 -08001463 }
Greg Daniel0a2464f2020-05-14 15:45:44 -04001464 surface->flushAndSubmit();
mtkleinb9eb4ac2015-02-02 18:26:03 -08001465 if (FLAGS_gpuStats) {
Robert Phillips9da87e02019-02-04 13:26:26 -05001466 canvas->getGrContext()->priv().dumpCacheStats(log);
1467 canvas->getGrContext()->priv().dumpGpuStats(log);
Robert Phillips273f1072020-05-05 13:03:07 -04001468 canvas->getGrContext()->priv().dumpContextStats(log);
mtkleinb9eb4ac2015-02-02 18:26:03 -08001469 }
Robert Phillips3c1efd42020-02-13 15:51:59 -05001470
1471 this->readBack(surface.get(), dst);
1472
mtklein55e88b22015-01-21 15:50:13 -08001473 if (FLAGS_abandonGpuContext) {
1474 factory.abandonContexts();
bsalomon6e2aad42016-04-01 11:54:31 -07001475 } else if (FLAGS_releaseAndAbandonGpuContext) {
1476 factory.releaseResourcesAndAbandonContexts();
mtklein55e88b22015-01-21 15:50:13 -08001477 }
Khushalc421ca12018-06-26 14:38:34 -07001478 if (!context->abandoned()) {
Brian Salomonf865b052018-03-09 09:01:53 -05001479 surface.reset();
1480 if (backendTexture.isValid()) {
Robert Phillips5c7a25b2019-05-20 08:38:07 -04001481 context->deleteBackendTexture(backendTexture);
Brian Salomonf865b052018-03-09 09:01:53 -05001482 }
1483 if (backendRT.isValid()) {
Robert Phillips9da87e02019-02-04 13:26:26 -05001484 context->priv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
Brian Salomonf865b052018-03-09 09:01:53 -05001485 }
1486 }
Greg Daniela870b462019-01-08 15:49:46 -05001487 if (grOptions.fPersistentCache) {
1488 context->storeVkPipelineCacheData();
1489 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001490 return Result::Ok();
mtklein748ca3b2015-01-15 10:56:12 -08001491}
1492
1493/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1494
Brian Osman3fdfe282019-09-09 13:46:52 -04001495GPUThreadTestingSink::GPUThreadTestingSink(const SkCommandLineConfigGpu* config,
Brian Osmanf9810662017-08-30 10:02:10 -04001496 const GrContextOptions& grCtxOptions)
Brian Osman3fdfe282019-09-09 13:46:52 -04001497 : INHERITED(config, grCtxOptions)
Mike Klein022cfa22017-09-01 11:53:16 -04001498 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)) {
Brian Osmanf9810662017-08-30 10:02:10 -04001499 SkASSERT(fExecutor);
1500}
1501
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001502Result GPUThreadTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
Brian Osmanf9810662017-08-30 10:02:10 -04001503 SkString* log) const {
1504 // Draw twice, once with worker threads, and once without. Verify that we get the same result.
1505 // Also, force us to only use the software path renderer, so we really stress-test the threaded
1506 // version of that code.
1507 GrContextOptions contextOptions = this->baseContextOptions();
Brian Osman195c05b2017-08-30 15:14:04 -04001508 contextOptions.fGpuPathRenderers = GpuPathRenderers::kNone;
Greg Daniel024615e2018-05-10 17:25:52 +00001509 contextOptions.fExecutor = fExecutor.get();
Adrienne Walkerab7181d2018-05-14 14:02:03 -07001510
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001511 Result result = this->onDraw(src, dst, wStream, log, contextOptions);
1512 if (!result.isOk() || !dst) {
1513 return result;
Brian Osmanf9810662017-08-30 10:02:10 -04001514 }
1515
1516 SkBitmap reference;
1517 SkString refLog;
1518 SkDynamicMemoryWStream refStream;
1519 contextOptions.fExecutor = nullptr;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001520 Result refResult = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1521 if (!refResult.isOk()) {
1522 return refResult;
Brian Osmanf9810662017-08-30 10:02:10 -04001523 }
1524
Brian Osmane5756ec2017-09-06 17:08:30 -04001525 return compare_bitmaps(reference, *dst);
Brian Osmanf9810662017-08-30 10:02:10 -04001526}
1527
1528/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1529
Brian Osman3fdfe282019-09-09 13:46:52 -04001530GPUPersistentCacheTestingSink::GPUPersistentCacheTestingSink(const SkCommandLineConfigGpu* config,
1531 const GrContextOptions& grCtxOptions)
1532 : INHERITED(config, grCtxOptions)
1533 , fCacheType(config->getTestPersistentCache()) {}
Brian Salomon00a5eb82018-07-11 15:32:05 -04001534
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001535Result GPUPersistentCacheTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1536 SkString* log) const {
Brian Salomon00a5eb82018-07-11 15:32:05 -04001537 // Draw twice, once with a cold cache, and again with a warm cache. Verify that we get the same
1538 // result.
1539 sk_gpu_test::MemoryCache memoryCache;
1540 GrContextOptions contextOptions = this->baseContextOptions();
1541 contextOptions.fPersistentCache = &memoryCache;
Brian Osmana66081d2019-09-03 14:59:26 -04001542 if (fCacheType == 2) {
1543 contextOptions.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kBackendSource;
1544 }
Brian Salomon00a5eb82018-07-11 15:32:05 -04001545
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001546 Result result = this->onDraw(src, dst, wStream, log, contextOptions);
1547 if (!result.isOk() || !dst) {
1548 return result;
Brian Salomon00a5eb82018-07-11 15:32:05 -04001549 }
1550
1551 SkBitmap reference;
1552 SkString refLog;
1553 SkDynamicMemoryWStream refStream;
1554 memoryCache.resetNumCacheMisses();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001555 Result refResult = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1556 if (!refResult.isOk()) {
1557 return refResult;
Brian Salomon00a5eb82018-07-11 15:32:05 -04001558 }
Brian Salomon7fc52992018-07-12 16:20:23 -04001559 SkASSERT(!memoryCache.numCacheMisses());
Brian Salomon00a5eb82018-07-11 15:32:05 -04001560
1561 return compare_bitmaps(reference, *dst);
1562}
1563
Brian Osmaned58e002019-09-06 14:42:43 -04001564
1565/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1566
Brian Osman3fdfe282019-09-09 13:46:52 -04001567GPUPrecompileTestingSink::GPUPrecompileTestingSink(const SkCommandLineConfigGpu* config,
1568 const GrContextOptions& grCtxOptions)
1569 : INHERITED(config, grCtxOptions) {}
Brian Osmaned58e002019-09-06 14:42:43 -04001570
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001571Result GPUPrecompileTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1572 SkString* log) const {
Brian Osmaned58e002019-09-06 14:42:43 -04001573 // Three step process:
1574 // 1) Draw once with an SkSL cache, and store off the shader blobs.
1575 // 2) For the second context, pre-compile the shaders to warm the cache.
1576 // 3) Draw with the second context, ensuring that we get the same result, and no cache misses.
1577 sk_gpu_test::MemoryCache memoryCache;
1578 GrContextOptions contextOptions = this->baseContextOptions();
1579 contextOptions.fPersistentCache = &memoryCache;
1580 contextOptions.fShaderCacheStrategy = GrContextOptions::ShaderCacheStrategy::kSkSL;
Brian Osmaned58e002019-09-06 14:42:43 -04001581
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001582 Result result = this->onDraw(src, dst, wStream, log, contextOptions);
1583 if (!result.isOk() || !dst) {
1584 return result;
Brian Osmaned58e002019-09-06 14:42:43 -04001585 }
1586
1587 auto precompileShaders = [&memoryCache](GrContext* context) {
1588 memoryCache.foreach([context](sk_sp<const SkData> key, sk_sp<SkData> data, int /*count*/) {
1589 SkAssertResult(context->precompileShader(*key, *data));
1590 });
1591 };
1592
1593 sk_gpu_test::MemoryCache replayCache;
1594 GrContextOptions replayOptions = this->baseContextOptions();
1595 // Ensure that the runtime cache is large enough to hold all of the shaders we pre-compile
1596 replayOptions.fRuntimeProgramCacheSize = memoryCache.numCacheMisses();
1597 replayOptions.fPersistentCache = &replayCache;
Brian Osmaned58e002019-09-06 14:42:43 -04001598
1599 SkBitmap reference;
1600 SkString refLog;
1601 SkDynamicMemoryWStream refStream;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001602 Result refResult = this->onDraw(src, &reference, &refStream, &refLog, replayOptions,
1603 precompileShaders);
1604 if (!refResult.isOk()) {
1605 return refResult;
Brian Osmaned58e002019-09-06 14:42:43 -04001606 }
1607 SkASSERT(!replayCache.numCacheMisses());
1608
1609 return compare_bitmaps(reference, *dst);
1610}
1611
Robert Phillips62768192020-04-22 08:28:58 -04001612/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
Robert Phillips291f3402020-02-19 14:14:47 -05001613GPUDDLSink::GPUDDLSink(const SkCommandLineConfigGpu* config, const GrContextOptions& grCtxOptions)
1614 : INHERITED(config, grCtxOptions)
Robert Phillips19f466d2020-02-26 10:27:07 -05001615 , fRecordingThreadPool(SkExecutor::MakeLIFOThreadPool(1)) // TODO: this should be at least 2
Robert Phillips62768192020-04-22 08:28:58 -04001616 , fGPUThread(SkExecutor::MakeFIFOThreadPool(1, false)) {
Robert Phillips291f3402020-02-19 14:14:47 -05001617}
1618
1619Result GPUDDLSink::ddlDraw(const Src& src,
1620 sk_sp<SkSurface> dstSurface,
1621 SkTaskGroup* recordingTaskGroup,
1622 SkTaskGroup* gpuTaskGroup,
Robert Phillips19f466d2020-02-26 10:27:07 -05001623 sk_gpu_test::TestContext* gpuTestCtx,
Robert Phillips291f3402020-02-19 14:14:47 -05001624 GrContext* gpuThreadCtx) const {
Robert Phillips19f466d2020-02-26 10:27:07 -05001625
1626 // We have to do this here bc characterization can hit the SkGpuDevice's thread guard (i.e.,
1627 // leaving it until the DDLTileHelper ctor will result in multiple threads trying to use the
1628 // same context (this thread and the gpuThread - which will be uploading textures)).
1629 SkSurfaceCharacterization dstCharacterization;
1630 SkAssertResult(dstSurface->characterize(&dstCharacterization));
1631
1632 // 'gpuTestCtx/gpuThreadCtx' is being shifted to the gpuThread. Leave the main (this)
1633 // thread w/o a context.
1634 gpuTestCtx->makeNotCurrent();
1635
1636 // Job one for the GPU thread is to make 'gpuTestCtx' current!
1637 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeCurrent(); });
1638
Robert Phillips291f3402020-02-19 14:14:47 -05001639 auto size = src.size();
1640 SkPictureRecorder recorder;
1641 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1642 SkIntToScalar(size.height())));
1643 if (!result.isOk()) {
Robert Phillipsce978572020-02-28 11:56:44 -05001644 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeNotCurrent(); });
1645 gpuTaskGroup->wait();
Robert Phillips291f3402020-02-19 14:14:47 -05001646 return result;
1647 }
1648 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
1649
1650 // this is our ultimate final drawing area/rect
1651 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
1652
1653 DDLPromiseImageHelper promiseImageHelper;
1654 sk_sp<SkData> compressedPictureData = promiseImageHelper.deflateSKP(inputPicture.get());
1655 if (!compressedPictureData) {
Robert Phillipsce978572020-02-28 11:56:44 -05001656 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeNotCurrent(); });
1657 gpuTaskGroup->wait();
Robert Phillips291f3402020-02-19 14:14:47 -05001658 return Result::Fatal("GPUDDLSink: Couldn't deflate SkPicture");
1659 }
1660
1661 promiseImageHelper.createCallbackContexts(gpuThreadCtx);
1662
1663 // TODO: move the image upload to the utility thread
1664 promiseImageHelper.uploadAllToGPU(gpuTaskGroup, gpuThreadCtx);
1665
Robert Phillips11c67672020-04-23 15:10:03 -04001666 // Care must be taken when using 'gpuThreadCtx' bc it moves between the gpu-thread and this
1667 // one. About all it can be consistently used for is GrCaps access and 'defaultBackendFormat'
1668 // calls.
Robert Phillips291f3402020-02-19 14:14:47 -05001669 constexpr int kNumDivisions = 3;
Robert Phillips11c67672020-04-23 15:10:03 -04001670 DDLTileHelper tiles(gpuThreadCtx, dstCharacterization, viewport, kNumDivisions);
Robert Phillips291f3402020-02-19 14:14:47 -05001671
Robert Phillips8472a3d2020-04-16 16:27:45 -04001672 tiles.createBackendTextures(gpuTaskGroup, gpuThreadCtx);
1673
Robert Phillips291f3402020-02-19 14:14:47 -05001674 // Reinflate the compressed picture individually for each thread.
1675 tiles.createSKPPerTile(compressedPictureData.get(), promiseImageHelper);
1676
1677 tiles.kickOffThreadedWork(recordingTaskGroup, gpuTaskGroup, gpuThreadCtx);
Robert Phillips11c67672020-04-23 15:10:03 -04001678
1679 // We have to wait for the recording threads to schedule all their work on the gpu thread
1680 // before we can schedule the composition draw and the flush. Note that the gpu thread
1681 // is not blocked at this point and this thread is borrowing recording work.
Robert Phillips19f466d2020-02-26 10:27:07 -05001682 recordingTaskGroup->wait();
Robert Phillips291f3402020-02-19 14:14:47 -05001683
Robert Phillips11c67672020-04-23 15:10:03 -04001684 // Note: at this point the recording thread(s) are stalled out w/ nothing to do.
1685
1686 // The recording threads have already scheduled the drawing of each tile's DDL on the gpu
1687 // thread. The composition DDL must be scheduled last bc it relies on the result of all
1688 // the tiles' rendering. Additionally, bc we're aliasing the tiles' backend textures,
1689 // there is nothing in the DAG to automatically force the required order.
1690 gpuTaskGroup->add([dstSurface, ddl = tiles.composeDDL()]() {
1691 dstSurface->draw(ddl);
1692 });
1693
Robert Phillips291f3402020-02-19 14:14:47 -05001694 // This should be the only explicit flush for the entire DDL draw
Robert Phillips4e3ceb92020-04-16 15:42:50 -04001695 gpuTaskGroup->add([gpuThreadCtx]() {
1696 // We need to ensure all the GPU work is finished so
1697 // the following 'deleteAllFromGPU' call will work
1698 // on Vulkan.
1699 // TODO: switch over to using the promiseImage callbacks
1700 // to free the backendTextures. This is complicated a
1701 // bit by which thread possesses the direct context.
1702 GrFlushInfo flushInfoSyncCpu;
1703 flushInfoSyncCpu.fFlags = kSyncCpu_GrFlushFlag;
1704 gpuThreadCtx->flush(flushInfoSyncCpu);
Greg Daniel0a2464f2020-05-14 15:45:44 -04001705 gpuThreadCtx->submit(true);
Robert Phillips4e3ceb92020-04-16 15:42:50 -04001706 });
Robert Phillips291f3402020-02-19 14:14:47 -05001707
Robert Phillips19f466d2020-02-26 10:27:07 -05001708 // The backend textures are created on the gpuThread by the 'uploadAllToGPU' call.
1709 // It is simpler to also delete them at this point on the gpuThread.
1710 promiseImageHelper.deleteAllFromGPU(gpuTaskGroup, gpuThreadCtx);
1711
Robert Phillips8472a3d2020-04-16 16:27:45 -04001712 tiles.deleteBackendTextures(gpuTaskGroup, gpuThreadCtx);
1713
Robert Phillips19f466d2020-02-26 10:27:07 -05001714 // A flush has already been scheduled on the gpu thread along with the clean up of the backend
Robert Phillips8472a3d2020-04-16 16:27:45 -04001715 // textures so it is safe to schedule making 'gpuTestCtx' not current on the gpuThread.
Robert Phillips19f466d2020-02-26 10:27:07 -05001716 gpuTaskGroup->add([gpuTestCtx] { gpuTestCtx->makeNotCurrent(); });
1717
1718 // All the work is scheduled on the gpu thread, we just need to wait
Robert Phillips291f3402020-02-19 14:14:47 -05001719 gpuTaskGroup->wait();
1720
1721 return Result::Ok();
1722}
1723
1724Result GPUDDLSink::draw(const Src& src, SkBitmap* dst, SkWStream* stream, SkString* log) const {
1725 GrContextOptions contextOptions = this->baseContextOptions();
1726 src.modifyGrContextOptions(&contextOptions);
1727 contextOptions.fPersistentCache = nullptr;
1728 contextOptions.fExecutor = nullptr;
1729
1730 GrContextFactory factory(contextOptions);
1731
1732 // This captures the context destined to be the main gpu context
1733 ContextInfo mainCtxInfo = factory.getContextInfo(this->contextType(), this->contextOverrides());
1734 sk_gpu_test::TestContext* mainTestCtx = mainCtxInfo.testContext();
1735 GrContext* mainCtx = mainCtxInfo.grContext();
1736 if (!mainCtx) {
1737 return Result::Fatal("Could not create context.");
1738 }
1739
1740 SkASSERT(mainCtx->priv().getGpu());
1741
1742 // TODO: make use of 'otherCtx' for uploads & compilation
1743#if 0
1744 // This captures the context destined to be the utility context. It is in a share group
1745 // with the main context
1746 ContextInfo otherCtxInfo = factory.getSharedContextInfo(mainCtx);
1747 sk_gpu_test::TestContext* otherTestCtx = otherCtxInfo.testContext();
1748 GrContext* otherCtx = otherCtxInfo.grContext();
1749 if (!otherCtx) {
1750 return Result::Fatal("Cound not create shared context.");
1751 }
1752
1753 SkASSERT(otherCtx->priv().getGpu());
1754#endif
1755
1756 SkTaskGroup recordingTaskGroup(*fRecordingThreadPool);
1757 SkTaskGroup gpuTaskGroup(*fGPUThread);
1758
1759 // Make sure 'mainCtx' is current
1760 mainTestCtx->makeCurrent();
1761
1762 GrBackendTexture backendTexture;
1763 GrBackendRenderTarget backendRT;
1764 sk_sp<SkSurface> surface = this->createDstSurface(mainCtx, src.size(),
1765 &backendTexture, &backendRT);
1766 if (!surface) {
1767 return Result::Fatal("Could not create a surface.");
1768 }
1769
Robert Phillips19f466d2020-02-26 10:27:07 -05001770 Result result = this->ddlDraw(src, surface, &recordingTaskGroup, &gpuTaskGroup,
1771 mainTestCtx, mainCtx);
Robert Phillips291f3402020-02-19 14:14:47 -05001772 if (!result.isOk()) {
1773 return result;
1774 }
1775
Robert Phillips19f466d2020-02-26 10:27:07 -05001776 // 'ddlDraw' will have made 'mainCtx' not current on the gpuThread
Robert Phillips291f3402020-02-19 14:14:47 -05001777 mainTestCtx->makeCurrent();
1778
1779 if (FLAGS_gpuStats) {
1780 mainCtx->priv().dumpCacheStats(log);
1781 mainCtx->priv().dumpGpuStats(log);
Robert Phillips273f1072020-05-05 13:03:07 -04001782 mainCtx->priv().dumpContextStats(log);
Robert Phillips291f3402020-02-19 14:14:47 -05001783
1784#if 0
1785 otherCtx->priv().dumpCacheStats(log);
1786 otherCtx->priv().dumpGpuStats(log);
Robert Phillips273f1072020-05-05 13:03:07 -04001787 otherCtx->priv().dumpContextStats(log);
Robert Phillips291f3402020-02-19 14:14:47 -05001788#endif
1789 }
1790
1791 if (!this->readBack(surface.get(), dst)) {
1792 return Result::Fatal("Could not readback from surface.");
1793 }
1794
1795 surface.reset();
1796 if (backendTexture.isValid()) {
1797 mainCtx->deleteBackendTexture(backendTexture);
1798 }
1799 if (backendRT.isValid()) {
1800 mainCtx->priv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
1801 }
1802
1803 return Result::Ok();
1804}
1805
Brian Salomon00a5eb82018-07-11 15:32:05 -04001806/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001807static Result draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
halcanary4ba051c2016-03-10 10:31:53 -08001808 if (src.size().isEmpty()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001809 return Result::Fatal("Source has empty dimensions");
halcanary4ba051c2016-03-10 10:31:53 -08001810 }
halcanary47ef4d52015-03-03 09:13:09 -08001811 SkASSERT(doc);
halcanary45420a92016-06-02 12:41:14 -07001812 int pageCount = src.pageCount();
1813 for (int i = 0; i < pageCount; ++i) {
1814 int width = src.size(i).width(), height = src.size(i).height();
halcanary7e798182015-04-14 14:06:18 -07001815 SkCanvas* canvas =
1816 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1817 if (!canvas) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001818 return Result::Fatal("SkDocument::beginPage(w,h) returned nullptr");
halcanary7e798182015-04-14 14:06:18 -07001819 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001820 Result result = src.draw(i, canvas);
1821 if (!result.isOk()) {
1822 return result;
halcanary7e798182015-04-14 14:06:18 -07001823 }
1824 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001825 }
reedd14df7c2016-09-22 14:12:46 -07001826 doc->close();
halcanaryfd4a9932015-01-28 11:45:58 -08001827 dst->flush();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001828 return Result::Ok();
mtklein748ca3b2015-01-15 10:56:12 -08001829}
1830
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001831Result PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canary23564b92018-09-07 14:33:14 -04001832 SkPDF::Metadata metadata;
halcanary4b656662016-04-27 07:45:18 -07001833 metadata.fTitle = src.name();
1834 metadata.fSubject = "rendering correctness test";
1835 metadata.fCreator = "Skia/DM";
Mike Reeda4daf192017-12-14 13:25:04 -05001836 metadata.fRasterDPI = fRasterDpi;
1837 metadata.fPDFA = fPDFA;
Hal Canaryf34131a2018-12-18 15:11:03 -05001838#if SK_PDF_TEST_EXECUTOR
Hal Canary9a3f5542018-12-10 19:59:07 -05001839 std::unique_ptr<SkExecutor> executor = SkExecutor::MakeFIFOThreadPool();
1840 metadata.fExecutor = executor.get();
1841#endif
Hal Canary3026d4b2019-01-07 10:00:48 -05001842 auto doc = SkPDF::MakeDocument(dst, metadata);
halcanary47ef4d52015-03-03 09:13:09 -08001843 if (!doc) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001844 return Result::Fatal("SkPDF::MakeDocument() returned nullptr");
halcanary47ef4d52015-03-03 09:13:09 -08001845 }
1846 return draw_skdocument(src, doc.get(), dst);
1847}
1848
1849/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1850
1851XPSSink::XPSSink() {}
1852
Robert Phillips9b00f1f2020-03-24 12:29:44 -04001853#if defined(SK_SUPPORT_XPS)
Hal Canary5e221e72017-02-06 09:51:42 -05001854static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1855 IXpsOMObjectFactory* factory;
1856 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1857 nullptr,
1858 CLSCTX_INPROC_SERVER,
1859 IID_PPV_ARGS(&factory)));
1860 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1861}
1862
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001863Result XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canaryabc88d22017-02-06 09:26:49 -05001864 SkAutoCoInitialize com;
1865 if (!com.succeeded()) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001866 return Result::Fatal("Could not initialize COM.");
Hal Canaryabc88d22017-02-06 09:26:49 -05001867 }
Hal Canary5e221e72017-02-06 09:51:42 -05001868 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1869 if (!factory) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001870 return Result::Fatal("Failed to create XPS Factory.");
Hal Canary5e221e72017-02-06 09:51:42 -05001871 }
Hal Canary3026d4b2019-01-07 10:00:48 -05001872 auto doc = SkXPS::MakeDocument(dst, factory.get());
halcanary47ef4d52015-03-03 09:13:09 -08001873 if (!doc) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001874 return Result::Fatal("SkXPS::MakeDocument() returned nullptr");
halcanary47ef4d52015-03-03 09:13:09 -08001875 }
1876 return draw_skdocument(src, doc.get(), dst);
1877}
Hal Canary5e221e72017-02-06 09:51:42 -05001878#else
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001879Result XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1880 return Result::Fatal("XPS not supported on this platform.");
Hal Canary5e221e72017-02-06 09:51:42 -05001881}
1882#endif
reed54dc4872016-09-13 08:09:45 -07001883
1884/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1885
mtklein9c3f17d2015-01-28 11:35:18 -08001886SKPSink::SKPSink() {}
1887
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001888Result SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Brian Salomon4e1066f2019-12-04 10:33:52 -05001889 auto size = SkSize::Make(src.size());
mtklein9c3f17d2015-01-28 11:35:18 -08001890 SkPictureRecorder recorder;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001891 Result result = src.draw(recorder.beginRecording(size.width(), size.height()));
1892 if (!result.isOk()) {
1893 return result;
mtklein9c3f17d2015-01-28 11:35:18 -08001894 }
reedca2622b2016-03-18 07:25:55 -07001895 recorder.finishRecordingAsPicture()->serialize(dst);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001896 return Result::Ok();
mtklein9c3f17d2015-01-28 11:35:18 -08001897}
1898
1899/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1900
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001901Result DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Mike Klein8f4e2242019-03-20 11:59:00 -05001902 DebugCanvas debugCanvas(src.size().width(), src.size().height());
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001903 Result result = src.draw(&debugCanvas);
1904 if (!result.isOk()) {
1905 return result;
Hal Canary85c7fe82016-10-25 10:33:27 -04001906 }
Mike Reed5df49342016-11-12 08:06:55 -06001907 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
Hal Canary85c7fe82016-10-25 10:33:27 -04001908 UrlDataManager dataManager(SkString("data"));
Brian Osmand8a90f92019-01-28 13:41:19 -05001909 SkJSONWriter writer(dst, SkJSONWriter::Mode::kPretty);
1910 writer.beginObject(); // root
Nathaniel Nifonga072b7b2019-12-13 13:51:14 -05001911 debugCanvas.toJSON(writer, dataManager, nullCanvas.get());
Brian Osmand8a90f92019-01-28 13:41:19 -05001912 writer.endObject(); // root
1913 writer.flush();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001914 return Result::Ok();
Hal Canary85c7fe82016-10-25 10:33:27 -04001915}
1916
1917/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1918
Bryce Thomas95a7b762018-03-02 13:54:21 -08001919SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
mtklein8a4527e2015-01-31 20:00:58 -08001920
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001921Result SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita718df0a2016-07-15 10:33:29 -07001922#if defined(SK_XML)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001923 if (src.pageCount() > 1) {
1924 int pageCount = src.pageCount();
1925 if (fPageIndex > pageCount - 1) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001926 return Result::Fatal("Page index %d too high for document with only %d pages.",
1927 fPageIndex, pageCount);
Bryce Thomas95a7b762018-03-02 13:54:21 -08001928 }
1929 }
Bryce Thomas95a7b762018-03-02 13:54:21 -08001930 return src.draw(fPageIndex,
1931 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
Mike Reed5df49342016-11-12 08:06:55 -06001932 SkIntToScalar(src.size().height())),
Florin Malita562017b2019-02-14 13:42:15 -05001933 dst)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001934 .get());
fmalita718df0a2016-07-15 10:33:29 -07001935#else
Hal Canary327ef032018-03-22 13:10:51 -04001936 (void)fPageIndex;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001937 return Result::Fatal("SVG sink is disabled.");
fmalita718df0a2016-07-15 10:33:29 -07001938#endif // SK_XML
mtklein8a4527e2015-01-31 20:00:58 -08001939}
1940
1941/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1942
brianosmanb109b8c2016-06-16 13:03:24 -07001943RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
mtklein27c3fdd2016-02-26 14:43:21 -08001944 : fColorType(colorType)
brianosmanb109b8c2016-06-16 13:03:24 -07001945 , fColorSpace(std::move(colorSpace)) {}
mtklein748ca3b2015-01-15 10:56:12 -08001946
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001947Result RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001948 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001949 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1950 SkAlphaType alphaType = kPremul_SkAlphaType;
1951 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1952
Brian Salomon4bc0c1f2019-09-30 15:12:27 -04001953 dst->allocPixelsFlags(SkImageInfo::Make(size, fColorType, alphaType, fColorSpace),
Mike Reed086a4272017-07-18 10:53:11 -04001954 SkBitmap::kZeroPixels_AllocFlag);
Yuqian Lib8b62532018-02-23 14:13:36 +08001955
mtklein748ca3b2015-01-15 10:56:12 -08001956 SkCanvas canvas(*dst);
1957 return src.draw(&canvas);
1958}
1959
1960/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1961
mtkleina16e69e2015-05-05 11:38:45 -07001962// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001963// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001964// Several examples below.
1965
mtkleincbf89782016-02-19 14:27:14 -08001966template <typename Fn>
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001967static Result draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001968 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001969 class ProxySrc : public Src {
1970 public:
mtkleincbf89782016-02-19 14:27:14 -08001971 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001972 Result draw(SkCanvas* canvas) const override { return fDraw(canvas); }
halcanaryb4a7f142016-03-30 08:31:27 -07001973 Name name() const override { return "ProxySrc"; }
1974 SkISize size() const override { return fSize; }
mtkleina16e69e2015-05-05 11:38:45 -07001975 private:
mtkleincbf89782016-02-19 14:27:14 -08001976 SkISize fSize;
1977 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001978 };
msarett62d3b102015-12-10 15:14:27 -08001979 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001980}
1981
1982/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1983
Mike Klein84836b72019-03-21 11:31:36 -05001984static DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
mtklein4a34ecb2016-01-08 10:19:35 -08001985
1986// Is *bitmap identical to what you get drawing src into sink?
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001987static Result check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
mtklein4a34ecb2016-01-08 10:19:35 -08001988 // We can only check raster outputs.
1989 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1990 if (FLAGS_check && bitmap) {
1991 SkBitmap reference;
1992 SkString log;
halcanaryb4a7f142016-03-30 08:31:27 -07001993 SkDynamicMemoryWStream wStream;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001994 Result result = sink->draw(src, &reference, &wStream, &log);
mtklein4a34ecb2016-01-08 10:19:35 -08001995 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
Ben Wagnerea25fcf2020-02-12 11:18:46 -05001996 SkASSERT(result.isOk());
1997 if (!result.isOk()) {
1998 return result;
mtklein4a34ecb2016-01-08 10:19:35 -08001999 }
Brian Osmane5756ec2017-09-06 17:08:30 -04002000 return compare_bitmaps(reference, *bitmap);
mtklein4a34ecb2016-01-08 10:19:35 -08002001 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002002 return Result::Ok();
mtklein4a34ecb2016-01-08 10:19:35 -08002003}
2004
2005/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2006
mtkleind603b222015-02-17 11:13:33 -08002007static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
2008 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
2009 matrix->mapRect(&bounds);
2010 matrix->postTranslate(-bounds.x(), -bounds.y());
Hal Canaryfafe1352017-04-11 12:12:02 -04002011 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
mtkleind603b222015-02-17 11:13:33 -08002012}
2013
msarett62d3b102015-12-10 15:14:27 -08002014ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08002015
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002016Result ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07002017 SkMatrix matrix = fMatrix;
2018 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
Ben Wagner145dbcd2016-11-03 14:40:50 -04002019 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07002020 canvas->concat(matrix);
2021 return src.draw(canvas);
2022 });
mtklein748ca3b2015-01-15 10:56:12 -08002023}
2024
mtkleind603b222015-02-17 11:13:33 -08002025// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
2026// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08002027ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08002028
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002029Result ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2030 Result result = fSink->draw(src, bitmap, stream, log);
2031 if (!result.isOk()) {
2032 return result;
mtkleind603b222015-02-17 11:13:33 -08002033 }
2034
2035 SkMatrix inverse;
2036 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002037 return Result::Fatal("Cannot upright --matrix.");
mtkleind603b222015-02-17 11:13:33 -08002038 }
2039 SkMatrix upright = SkMatrix::I();
2040 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
2041 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
2042 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
2043 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
2044
2045 SkBitmap uprighted;
2046 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
Brian Salomon9241a6d2019-10-03 13:26:54 -04002047 uprighted.allocPixels(bitmap->info().makeDimensions(size));
mtkleind603b222015-02-17 11:13:33 -08002048
2049 SkCanvas canvas(uprighted);
2050 canvas.concat(upright);
2051 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07002052 paint.setBlendMode(SkBlendMode::kSrc);
mtkleind603b222015-02-17 11:13:33 -08002053 canvas.drawBitmap(*bitmap, 0, 0, &paint);
2054
2055 *bitmap = uprighted;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002056 return Result::Ok();
mtkleind603b222015-02-17 11:13:33 -08002057}
2058
mtklein748ca3b2015-01-15 10:56:12 -08002059/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2060
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002061Result ViaSerialization::draw(
mtkleina16e69e2015-05-05 11:38:45 -07002062 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08002063 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07002064 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08002065 SkPictureRecorder recorder;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002066 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2067 SkIntToScalar(size.height())));
2068 if (!result.isOk()) {
2069 return result;
mtklein748ca3b2015-01-15 10:56:12 -08002070 }
reedca2622b2016-03-18 07:25:55 -07002071 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08002072
2073 // Serialize it and then deserialize it.
reed39eaf5f2016-09-15 07:19:35 -07002074 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
mtklein748ca3b2015-01-15 10:56:12 -08002075
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002076 result = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07002077 canvas->drawPicture(deserialized);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002078 return Result::Ok();
mtkleina16e69e2015-05-05 11:38:45 -07002079 });
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002080 if (!result.isOk()) {
2081 return result;
Ben Wagner1861e882018-04-04 17:40:46 -04002082 }
2083
2084 return check_against_reference(bitmap, src, fSink.get());
mtklein748ca3b2015-01-15 10:56:12 -08002085}
2086
2087/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2088
Brian Salomon57904202018-12-17 14:45:00 -05002089ViaDDL::ViaDDL(int numReplays, int numDivisions, Sink* sink)
2090 : Via(sink), fNumReplays(numReplays), fNumDivisions(numDivisions) {}
Robert Phillips33f02ed2018-03-27 08:06:57 -04002091
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002092Result ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002093 auto size = src.size();
2094 SkPictureRecorder recorder;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002095 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2096 SkIntToScalar(size.height())));
2097 if (!result.isOk()) {
2098 return result;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002099 }
2100 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
2101
2102 // this is our ultimate final drawing area/rect
2103 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
2104
Brian Salomon7d88f312019-02-28 10:03:03 -05002105 DDLPromiseImageHelper promiseImageHelper;
Robert Phillips96601082018-05-29 16:13:26 -04002106 sk_sp<SkData> compressedPictureData = promiseImageHelper.deflateSKP(inputPicture.get());
2107 if (!compressedPictureData) {
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002108 return Result::Fatal("ViaDDL: Couldn't deflate SkPicture");
Robert Phillips33f02ed2018-03-27 08:06:57 -04002109 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002110 auto draw = [&](SkCanvas* canvas) -> Result {
Brian Salomon57904202018-12-17 14:45:00 -05002111 GrContext* context = canvas->getGrContext();
Robert Phillips9da87e02019-02-04 13:26:26 -05002112 if (!context || !context->priv().getGpu()) {
Robert Phillipsa865a3a2020-02-14 10:49:39 -05002113 return Result::Fatal("ViaDDL: DDLs are GPU only");
Brian Salomon57904202018-12-17 14:45:00 -05002114 }
Robert Phillipsa865a3a2020-02-14 10:49:39 -05002115 SkSurface* tmp = canvas->getSurface();
2116 if (!tmp) {
2117 return Result::Fatal("ViaDDL: cannot get surface from canvas");
2118 }
Robert Phillips19f466d2020-02-26 10:27:07 -05002119 sk_sp<SkSurface> dstSurface = sk_ref_sp(tmp);
2120
2121 SkSurfaceCharacterization dstCharacterization;
2122 SkAssertResult(dstSurface->characterize(&dstCharacterization));
Robert Phillips33f02ed2018-03-27 08:06:57 -04002123
Robert Phillips923181b2020-02-14 12:36:37 -05002124 promiseImageHelper.createCallbackContexts(context);
2125
Brian Salomon57904202018-12-17 14:45:00 -05002126 // This is here bc this is the first point where we have access to the context
Robert Phillips923181b2020-02-14 12:36:37 -05002127 promiseImageHelper.uploadAllToGPU(nullptr, context);
Brian Salomon7d88f312019-02-28 10:03:03 -05002128 // We draw N times, with a clear between.
Brian Salomon57904202018-12-17 14:45:00 -05002129 for (int replay = 0; replay < fNumReplays; ++replay) {
2130 if (replay > 0) {
2131 // Clear the drawing of the previous replay
Brian Salomon8d23a582018-12-19 11:35:20 -05002132 canvas->clear(SK_ColorTRANSPARENT);
Brian Salomon57904202018-12-17 14:45:00 -05002133 }
2134 // First, create all the tiles (including their individual dest surfaces)
Robert Phillips11c67672020-04-23 15:10:03 -04002135 DDLTileHelper tiles(context, dstCharacterization, viewport, fNumDivisions);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002136
Robert Phillips8472a3d2020-04-16 16:27:45 -04002137 tiles.createBackendTextures(nullptr, context);
2138
Brian Salomon57904202018-12-17 14:45:00 -05002139 // Second, reinflate the compressed picture individually for each thread
Brian Salomon1bf0ed82019-01-16 13:51:35 -05002140 // This recreates the promise SkImages on each replay iteration. We are currently
2141 // relying on this to test using a SkPromiseImageTexture to fulfill different
2142 // SkImages. On each replay the promise SkImages are recreated in createSKPPerTile.
Brian Salomon57904202018-12-17 14:45:00 -05002143 tiles.createSKPPerTile(compressedPictureData.get(), promiseImageHelper);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002144
Brian Salomon57904202018-12-17 14:45:00 -05002145 // Third, create the DDLs in parallel
2146 tiles.createDDLsInParallel();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002147
Brian Salomon57904202018-12-17 14:45:00 -05002148 if (replay == fNumReplays - 1) {
Robert Phillips11c67672020-04-23 15:10:03 -04002149 // All the DDLs are created and they ref any created promise images which,
2150 // in turn, ref the callback contexts. If it is the last run, drop the
2151 // promise image helper's refs on the callback contexts.
Brian Salomon57904202018-12-17 14:45:00 -05002152 promiseImageHelper.reset();
Robert Phillips11c67672020-04-23 15:10:03 -04002153 // Note: we cannot drop the tiles' callback contexts here bc they are needed
2154 // to create each tile's destination surface.
Brian Salomon57904202018-12-17 14:45:00 -05002155 }
Robert Phillips33f02ed2018-03-27 08:06:57 -04002156
Brian Salomon57904202018-12-17 14:45:00 -05002157 // Fourth, synchronously render the display lists into the dest tiles
2158 // TODO: it would be cool to not wait until all the tiles are drawn to begin
2159 // drawing to the GPU and composing to the final surface
Robert Phillips6eb5cb92020-03-05 12:52:45 -05002160 tiles.precompileAndDrawAllTiles(context);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002161
Robert Phillips11c67672020-04-23 15:10:03 -04002162 if (replay == fNumReplays - 1) {
2163 // At this point the compose DDL holds refs to the composition promise images
2164 // which, in turn, hold refs on the tile callback contexts. If it is the last run,
2165 // drop the refs on tile callback contexts.
2166 tiles.dropCallbackContexts();
2167 }
Robert Phillips8472a3d2020-04-16 16:27:45 -04002168
Robert Phillips11c67672020-04-23 15:10:03 -04002169 dstSurface->draw(tiles.composeDDL());
2170
2171 // We need to ensure all the GPU work is finished so the promise image callback
2172 // contexts will delete all the backend textures.
Robert Phillips8472a3d2020-04-16 16:27:45 -04002173 GrFlushInfo flushInfoSyncCpu;
2174 flushInfoSyncCpu.fFlags = kSyncCpu_GrFlushFlag;
2175 context->flush(flushInfoSyncCpu);
Greg Daniel0a2464f2020-05-14 15:45:44 -04002176 context->submit(true);
Brian Salomon57904202018-12-17 14:45:00 -05002177 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002178 return Result::Ok();
Brian Salomon57904202018-12-17 14:45:00 -05002179 };
2180 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, draw);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002181}
2182
Robert Phillips33f02ed2018-03-27 08:06:57 -04002183/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2184
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002185Result ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein4a34ecb2016-01-08 10:19:35 -08002186 auto size = src.size();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002187 Result result = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtklein4a34ecb2016-01-08 10:19:35 -08002188 SkPictureRecorder recorder;
reedca2622b2016-03-18 07:25:55 -07002189 sk_sp<SkPicture> pic;
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002190 Result result = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2191 SkIntToScalar(size.height())));
2192 if (!result.isOk()) {
2193 return result;
mtklein4a34ecb2016-01-08 10:19:35 -08002194 }
reedca2622b2016-03-18 07:25:55 -07002195 pic = recorder.finishRecordingAsPicture();
mtklein4a34ecb2016-01-08 10:19:35 -08002196 canvas->drawPicture(pic);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002197 return result;
mtklein4a34ecb2016-01-08 10:19:35 -08002198 });
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002199 if (!result.isOk()) {
2200 return result;
Ben Wagner1861e882018-04-04 17:40:46 -04002201 }
2202
2203 return check_against_reference(bitmap, src, fSink.get());
mtklein4a34ecb2016-01-08 10:19:35 -08002204}
2205
2206/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2207
Mike Reedbae888e2017-02-18 16:50:45 -05002208#ifdef TEST_VIA_SVG
Mike Kleinc0bd9f92019-04-23 12:05:21 -05002209#include "experimental/svg/model/SkSVGDOM.h"
2210#include "include/svg/SkSVGCanvas.h"
2211#include "src/xml/SkXMLWriter.h"
Mike Reedf67c4592017-02-17 17:06:11 -05002212
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002213Result ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
Mike Reedf67c4592017-02-17 17:06:11 -05002214 auto size = src.size();
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002215 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Result {
Mike Reedf67c4592017-02-17 17:06:11 -05002216 SkDynamicMemoryWStream wstream;
2217 SkXMLStreamWriter writer(&wstream);
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002218 Result result = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
2219 if (!result.isOk()) {
2220 return result;
Mike Reedf67c4592017-02-17 17:06:11 -05002221 }
2222 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2223 auto dom = SkSVGDOM::MakeFromStream(*rstream);
2224 if (dom) {
2225 dom->setContainerSize(SkSize::Make(size));
2226 dom->render(canvas);
2227 }
Ben Wagnerea25fcf2020-02-12 11:18:46 -05002228 return Result::Ok();
Mike Reedf67c4592017-02-17 17:06:11 -05002229 });
2230}
Mike Reedbae888e2017-02-18 16:50:45 -05002231#endif
Mike Reedf67c4592017-02-17 17:06:11 -05002232
mtklein748ca3b2015-01-15 10:56:12 -08002233} // namespace DM