blob: f0b329c5b9a7d9210a49a9668916c20c83ae2f79 [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
mtklein748ca3b2015-01-15 10:56:12 -08008#include "DMSrcSink.h"
Brian Salomonf865b052018-03-09 09:01:53 -05009#include <cmath>
10#include <functional>
11#include "../src/jumper/SkJumper.h"
msarett9876ac52016-06-01 14:47:18 -070012#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -070013#include "SkAndroidCodec.h"
Hal Canary95e3c052017-01-11 12:44:43 -050014#include "SkAutoMalloc.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040015#include "SkBase64.h"
scroggof24f2242015-03-03 08:59:20 -080016#include "SkCodec.h"
msarettb714fb02016-01-22 14:46:42 -080017#include "SkCodecImageGenerator.h"
msarett888dc162016-05-23 10:21:17 -070018#include "SkColorSpace.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000019#include "SkColorSpaceXform.h"
Mike Klein841101d2017-03-10 09:55:51 -050020#include "SkColorSpaceXformCanvas.h"
Hal Canary95e3c052017-01-11 12:44:43 -050021#include "SkColorSpace_XYZ.h"
mtkleina16e69e2015-05-05 11:38:45 -070022#include "SkCommonFlags.h"
Chris Dalton040238b2017-12-18 14:22:34 -070023#include "SkCommonFlagsGpu.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070024#include "SkData.h"
Hal Canary85c7fe82016-10-25 10:33:27 -040025#include "SkDebugCanvas.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040026#include "SkDeferredDisplayListRecorder.h"
mtklein748ca3b2015-01-15 10:56:12 -080027#include "SkDocument.h"
Brian Osmanf9810662017-08-30 10:02:10 -040028#include "SkExecutor.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070029#include "SkImageGenerator.h"
msarett18976312016-03-09 14:20:58 -080030#include "SkImageGeneratorCG.h"
msarettfc0b6d12016-03-17 13:50:17 -070031#include "SkImageGeneratorWIC.h"
Mike Reed7fcfb622018-02-09 13:26:46 -050032#include "SkImageInfoPriv.h"
mtklein8bbbb692016-08-15 12:56:00 -070033#include "SkLiteDL.h"
34#include "SkLiteRecorder.h"
mtkleinc8be09a2016-01-04 18:56:57 -080035#include "SkMallocPixelRef.h"
Hal Canary45cde312017-04-03 16:06:42 -040036#include "SkMultiPictureDocumentPriv.h"
mtklein748ca3b2015-01-15 10:56:12 -080037#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080038#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080039#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050040#include "SkOSPath.h"
msarett9e9444c2016-02-03 12:39:10 -080041#include "SkOpts.h"
Mike Reede7a58322017-12-20 14:09:20 -050042#include "SkPictureCommon.h"
mtkleinffa901a2015-03-16 10:38:07 -070043#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080044#include "SkPictureRecorder.h"
reed54dc4872016-09-13 08:09:45 -070045#include "SkPipe.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040046#include "SkPngEncoder.h"
mtklein748ca3b2015-01-15 10:56:12 -080047#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070048#include "SkRecordDraw.h"
49#include "SkRecorder.h"
scroggoa1193e42015-01-21 12:09:53 -080050#include "SkStream.h"
Brian Salomonf865b052018-03-09 09:01:53 -050051#include "SkSurfaceCharacterization.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000052#include "SkSwizzler.h"
Brian Salomonf865b052018-03-09 09:01:53 -050053#include "SkTLogic.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040054#include "SkTaskGroup.h"
Yuqian Lib8b62532018-02-23 14:13:36 +080055#include "SkThreadedBMPDevice.h"
msarettfc0b6d12016-03-17 13:50:17 -070056#if defined(SK_BUILD_FOR_WIN)
57 #include "SkAutoCoInitialize.h"
Hal Canary5e221e72017-02-06 09:51:42 -050058 #include "SkHRESULT.h"
59 #include "SkTScopedComPtr.h"
60 #include <XpsObjectModel.h>
msarettfc0b6d12016-03-17 13:50:17 -070061#endif
62
Florin Malita124d5af2017-12-31 17:02:26 -050063#if !defined(SK_BUILD_FOR_GOOGLE3)
Florin Malita54f65c42018-01-16 17:04:30 -050064 #include "Skottie.h"
Florin Malita124d5af2017-12-31 17:02:26 -050065#endif
66
fmalita718df0a2016-07-15 10:33:29 -070067#if defined(SK_XML)
Ben Wagner6ce482a2018-03-27 10:57:43 -040068 #include "SkSVGCanvas.h"
fmalitaa48f0e32016-08-04 06:26:05 -070069 #include "SkSVGDOM.h"
fmalita718df0a2016-07-15 10:33:29 -070070 #include "SkXMLWriter.h"
71#endif
72
Robert Phillips0c4b7b12018-03-06 08:20:37 -050073#if SK_SUPPORT_GPU
Brian Salomonf865b052018-03-09 09:01:53 -050074#include "GrBackendSurface.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050075#include "GrContextPriv.h"
Brian Salomonf865b052018-03-09 09:01:53 -050076#include "GrGpu.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050077#endif
78
halcanary7e798182015-04-14 14:06:18 -070079DEFINE_bool(multiPage, false, "For document-type backends, render the source"
80 " into multiple pages");
scroggo3ac66e92016-02-08 15:09:48 -080081DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
halcanary7e798182015-04-14 14:06:18 -070082
bsalomon3724e572016-03-30 18:56:19 -070083using sk_gpu_test::GrContextFactory;
84
mtklein748ca3b2015-01-15 10:56:12 -080085namespace DM {
86
mtklein748ca3b2015-01-15 10:56:12 -080087GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
88
89Error GMSrc::draw(SkCanvas* canvas) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040090 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080091 gm->draw(canvas);
92 return "";
93}
94
95SkISize GMSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040096 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080097 return gm->getISize();
98}
99
100Name GMSrc::name() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400101 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -0800102 return gm->getName();
103}
104
bsalomon4ee6bd82015-05-27 13:23:23 -0700105void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400106 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -0700107 gm->modifyGrContextOptions(options);
108}
109
mtklein748ca3b2015-01-15 10:56:12 -0800110/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
111
msarettd1227a72016-05-18 06:23:57 -0700112BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
msaretta5783ae2015-09-08 15:35:32 -0700113 : fPath(path)
msaretta5783ae2015-09-08 15:35:32 -0700114 , fMode(mode)
115 , fDstColorType(dstColorType)
116 , fSampleSize(sampleSize)
117{}
118
119bool BRDSrc::veto(SinkFlags flags) const {
120 // No need to test to non-raster or indirect backends.
121 return flags.type != SinkFlags::kRaster
122 || flags.approach != SinkFlags::kDirect;
123}
124
msarettd1227a72016-05-18 06:23:57 -0700125static SkBitmapRegionDecoder* create_brd(Path path) {
bungeman38d909e2016-08-02 14:40:46 -0700126 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
msaretta5783ae2015-09-08 15:35:32 -0700127 if (!encoded) {
Ben Wagnera93a14a2017-08-28 10:34:05 -0400128 return nullptr;
msaretta5783ae2015-09-08 15:35:32 -0700129 }
reed42943c82016-09-12 12:01:44 -0700130 return SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy);
msaretta5783ae2015-09-08 15:35:32 -0700131}
132
Matt Sarett334df3a2016-12-15 18:17:33 -0500133static inline void alpha8_to_gray8(SkBitmap* bitmap) {
134 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
135 // them back to kGray8 so our test framework can draw them correctly.
136 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
137 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
138 .makeAlphaType(kOpaque_SkAlphaType);
139 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
140 }
141}
142
msaretta5783ae2015-09-08 15:35:32 -0700143Error BRDSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400144 if (canvas->imageInfo().colorSpace() &&
145 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
146 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
147 // run these tests on legacy canvases.
148 // We allow an exception for F16, since Android uses F16.
149 return Error::Nonfatal("Skip testing to color correct canvas.");
150 }
151
msaretta5783ae2015-09-08 15:35:32 -0700152 SkColorType colorType = canvas->imageInfo().colorType();
153 if (kRGB_565_SkColorType == colorType &&
154 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
155 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
156 }
157 switch (fDstColorType) {
158 case CodecSrc::kGetFromCanvas_DstColorType:
159 break;
msaretta5783ae2015-09-08 15:35:32 -0700160 case CodecSrc::kGrayscale_Always_DstColorType:
161 colorType = kGray_8_SkColorType;
162 break;
msarett34e0ec42016-04-22 16:27:24 -0700163 default:
164 SkASSERT(false);
165 break;
msaretta5783ae2015-09-08 15:35:32 -0700166 }
167
Ben Wagner145dbcd2016-11-03 14:40:50 -0400168 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700169 if (nullptr == brd.get()) {
170 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
171 }
172
Leon Scroggins III0118e972018-03-13 11:14:33 -0400173 auto recommendedCT = brd->computeOutputColorType(colorType);
174 if (kRGB_565_SkColorType == colorType && recommendedCT != colorType) {
175 return Error::Nonfatal("Skip decoding non-opaque to 565.");
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400176 }
Leon Scroggins III0118e972018-03-13 11:14:33 -0400177 colorType = recommendedCT;
178
179 auto colorSpace = brd->computeOutputColorSpace(colorType, nullptr);
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400180
msaretta5783ae2015-09-08 15:35:32 -0700181 const uint32_t width = brd->width();
182 const uint32_t height = brd->height();
183 // Visually inspecting very small output images is not necessary.
184 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
185 return Error::Nonfatal("Scaling very small images is uninteresting.");
186 }
187 switch (fMode) {
188 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700189 SkBitmap bitmap;
190 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
Leon Scroggins III0118e972018-03-13 11:14:33 -0400191 fSampleSize, colorType, false, colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800192 return "Cannot decode (full) region.";
msarett35e5d1b2015-10-27 12:50:25 -0700193 }
Matt Sarett334df3a2016-12-15 18:17:33 -0500194 alpha8_to_gray8(&bitmap);
Matt Sarett8db74f12017-06-14 13:02:05 +0000195
msarett35e5d1b2015-10-27 12:50:25 -0700196 canvas->drawBitmap(bitmap, 0, 0);
msaretta5783ae2015-09-08 15:35:32 -0700197 return "";
198 }
199 case kDivisor_Mode: {
200 const uint32_t divisor = 2;
201 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800202 return Error::Nonfatal("Divisor is larger than image dimension.");
msaretta5783ae2015-09-08 15:35:32 -0700203 }
204
205 // Use a border to test subsets that extend outside the image.
206 // We will not allow the border to be larger than the image dimensions. Allowing
207 // these large borders causes off by one errors that indicate a problem with the
208 // test suite, not a problem with the implementation.
209 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
210 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
211 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
212
213 // We may need to clear the canvas to avoid uninitialized memory.
214 // Assume we are scaling a 780x780 image with sampleSize = 8.
215 // The output image should be 97x97.
216 // Each subset will be 390x390.
217 // Each scaled subset be 48x48.
218 // Four scaled subsets will only fill a 96x96 image.
219 // The bottom row and last column will not be touched.
220 // This is an unfortunate result of our rounding rules when scaling.
221 // Maybe we need to consider testing scaled subsets without trying to
222 // combine them to match the full scaled image? Or maybe this is the
223 // best we can do?
224 canvas->clear(0);
225
226 for (uint32_t x = 0; x < divisor; x++) {
227 for (uint32_t y = 0; y < divisor; y++) {
228 // Calculate the subset dimensions
229 uint32_t subsetWidth = width / divisor;
230 uint32_t subsetHeight = height / divisor;
231 const int left = x * subsetWidth;
232 const int top = y * subsetHeight;
233
234 // Increase the size of the last subset in each row or column, when the
235 // divisor does not divide evenly into the image dimensions
236 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
237 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
238
239 // Increase the size of the subset in order to have a border on each side
240 const int decodeLeft = left - unscaledBorder;
241 const int decodeTop = top - unscaledBorder;
242 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
243 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700244 SkBitmap bitmap;
245 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
Matt Sarett68feef42017-04-11 09:51:32 -0400246 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
Leon Scroggins III0118e972018-03-13 11:14:33 -0400247 colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800248 return "Cannot decode region.";
msarett35e5d1b2015-10-27 12:50:25 -0700249 }
msaretta5783ae2015-09-08 15:35:32 -0700250
Matt Sarett334df3a2016-12-15 18:17:33 -0500251 alpha8_to_gray8(&bitmap);
msarett35e5d1b2015-10-27 12:50:25 -0700252 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700253 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
254 (SkScalar) (subsetWidth / fSampleSize),
255 (SkScalar) (subsetHeight / fSampleSize)),
256 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
257 (SkScalar) (top / fSampleSize),
258 (SkScalar) (subsetWidth / fSampleSize),
259 (SkScalar) (subsetHeight / fSampleSize)),
260 nullptr);
261 }
262 }
263 return "";
264 }
265 default:
266 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800267 return "Error: Should not be reached.";
msaretta5783ae2015-09-08 15:35:32 -0700268 }
269}
270
271SkISize BRDSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400272 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700273 if (brd) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400274 return {SkTMax(1, brd->width() / (int)fSampleSize),
275 SkTMax(1, brd->height() / (int)fSampleSize)};
msaretta5783ae2015-09-08 15:35:32 -0700276 }
Hal Canaryfafe1352017-04-11 12:12:02 -0400277 return {0, 0};
msaretta5783ae2015-09-08 15:35:32 -0700278}
279
280static SkString get_scaled_name(const Path& path, float scale) {
281 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
282}
283
284Name BRDSrc::name() const {
285 // We will replicate the names used by CodecSrc so that images can
286 // be compared in Gold.
287 if (1 == fSampleSize) {
288 return SkOSPath::Basename(fPath.c_str());
289 }
msarett4b0778e2015-11-13 09:59:11 -0800290 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700291}
292
293/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
294
scroggo3ac66e92016-02-08 15:09:48 -0800295static bool serial_from_path_name(const SkString& path) {
296 if (!FLAGS_RAW_threading) {
297 static const char* const exts[] = {
298 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
299 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
300 };
301 const char* actualExt = strrchr(path.c_str(), '.');
302 if (actualExt) {
303 actualExt++;
304 for (auto* ext : exts) {
305 if (0 == strcmp(ext, actualExt)) {
306 return true;
307 }
308 }
309 }
310 }
311 return false;
312}
313
scroggoc5560be2016-02-03 09:42:42 -0800314CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
315 float scale)
msarett438b2ad2015-04-09 12:43:10 -0700316 : fPath(path)
317 , fMode(mode)
318 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800319 , fDstAlphaType(dstAlphaType)
msarett0a242972015-06-11 14:27:27 -0700320 , fScale(scale)
scroggo3ac66e92016-02-08 15:09:48 -0800321 , fRunSerially(serial_from_path_name(path))
msarett438b2ad2015-04-09 12:43:10 -0700322{}
mtklein748ca3b2015-01-15 10:56:12 -0800323
mtklein99cab4e2015-07-31 06:43:04 -0700324bool CodecSrc::veto(SinkFlags flags) const {
msarett18976312016-03-09 14:20:58 -0800325 // Test to direct raster backends (8888 and 565).
msarettb714fb02016-01-22 14:46:42 -0800326 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700327}
scroggo9b77ddd2015-03-19 06:03:39 -0700328
msarett34e0ec42016-04-22 16:27:24 -0700329// Allows us to test decodes to non-native 8888.
msarettb1be46b2016-05-17 08:52:11 -0700330static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700331 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
332 return;
333 }
334
335 for (int y = 0; y < bitmap.height(); y++) {
336 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
337 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
338 }
339}
340
msarett9e9444c2016-02-03 12:39:10 -0800341// FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
342// This allows us to still test unpremultiplied decodes.
msarettb1be46b2016-05-17 08:52:11 -0700343static void premultiply_if_necessary(SkBitmap& bitmap) {
msarett9e9444c2016-02-03 12:39:10 -0800344 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
345 return;
346 }
347
348 switch (bitmap.colorType()) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400349 case kRGBA_F16_SkColorType: {
350 SkJumper_MemoryCtx ctx = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
351 SkRasterPipeline_<256> p;
352 p.append(SkRasterPipeline::load_f16, &ctx);
353 p.append(SkRasterPipeline::premul);
354 p.append(SkRasterPipeline::store_f16, &ctx);
355 p.run(0,0, bitmap.width(), bitmap.height());
356 }
Leon Scroggins IIIeceee042017-05-23 16:58:09 -0400357 break;
msarett9e9444c2016-02-03 12:39:10 -0800358 case kN32_SkColorType:
359 for (int y = 0; y < bitmap.height(); y++) {
360 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
361 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
362 }
363 break;
msarett9e9444c2016-02-03 12:39:10 -0800364 default:
365 // No need to premultiply kGray or k565 outputs.
366 break;
367 }
msarette1daa482016-02-03 15:31:18 -0800368
369 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
370 // bitmap as kPremul.
371 bitmap.setAlphaType(kPremul_SkAlphaType);
msarett9e9444c2016-02-03 12:39:10 -0800372}
373
msarettb1be46b2016-05-17 08:52:11 -0700374static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
scroggoba584892016-05-20 13:56:13 -0700375 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
msarett3d9d7a72015-10-21 10:27:10 -0700376 switch (dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700377 case CodecSrc::kGrayscale_Always_DstColorType:
scroggo1a361922016-05-20 14:27:16 -0700378 if (kRGB_565_SkColorType == canvasColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700379 return false;
380 }
scroggoc5560be2016-02-03 09:42:42 -0800381 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700382 break;
msarett34e0ec42016-04-22 16:27:24 -0700383 case CodecSrc::kNonNative8888_Always_DstColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400384 if (kRGB_565_SkColorType == canvasColorType
385 || kRGBA_F16_SkColorType == canvasColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700386 return false;
387 }
388#ifdef SK_PMCOLOR_IS_RGBA
389 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
390#else
391 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
392#endif
393 break;
msarett3d9d7a72015-10-21 10:27:10 -0700394 default:
msarett55f7bdd2016-02-16 13:24:54 -0800395 if (kRGB_565_SkColorType == canvasColorType &&
396 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
397 return false;
398 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800399
400 if (kRGBA_F16_SkColorType == canvasColorType) {
Brian Osman36703d92017-12-12 14:09:31 -0500401 sk_sp<SkColorSpace> linearSpace = decodeInfo->colorSpace()->makeLinearGamma();
Matt Sarett09a1c082017-02-01 15:34:22 -0800402 *decodeInfo = decodeInfo->makeColorSpace(std::move(linearSpace));
403 }
404
scroggoc5560be2016-02-03 09:42:42 -0800405 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700406 break;
407 }
408
scroggoba584892016-05-20 13:56:13 -0700409 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
msarett3d9d7a72015-10-21 10:27:10 -0700410 return true;
411}
412
msarettb1be46b2016-05-17 08:52:11 -0700413static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000414 CodecSrc::DstColorType dstColorType,
msarettb1be46b2016-05-17 08:52:11 -0700415 SkScalar left = 0, SkScalar top = 0) {
msarettb1be46b2016-05-17 08:52:11 -0700416 SkBitmap bitmap;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000417 bitmap.installPixels(info, pixels, rowBytes);
msarettb1be46b2016-05-17 08:52:11 -0700418 premultiply_if_necessary(bitmap);
419 swap_rb_if_necessary(bitmap, dstColorType);
420 canvas->drawBitmap(bitmap, left, top);
421}
422
Matt Sarettf485cf92017-05-26 08:58:03 -0400423// For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
424// color format conversions should be performed by the codec. Sometimes the output of the
425// decode will be in an interesting color space. On our srgb and f16 backends, we need to
426// "pretend" that the color space is standard sRGB to avoid triggering color conversion
427// at draw time.
428static void set_bitmap_color_space(SkImageInfo* info) {
429 if (kRGBA_F16_SkColorType == info->colorType()) {
430 *info = info->makeColorSpace(SkColorSpace::MakeSRGBLinear());
431 } else {
432 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
433 }
434}
435
mtkleine0effd62015-07-29 06:37:28 -0700436Error CodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700437 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800438 if (!encoded) {
439 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
440 }
msarettb714fb02016-01-22 14:46:42 -0800441
Mike Reedede7bac2017-07-23 15:30:02 -0400442 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700443 if (nullptr == codec.get()) {
444 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700445 }
446
scroggoba584892016-05-20 13:56:13 -0700447 SkImageInfo decodeInfo = codec->getInfo();
448 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
449 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800450 return Error::Nonfatal("Skipping uninteresting test.");
msarett438b2ad2015-04-09 12:43:10 -0700451 }
452
msarett0a242972015-06-11 14:27:27 -0700453 // Try to scale the image if it is desired
454 SkISize size = codec->getScaledDimensions(fScale);
455 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
456 return Error::Nonfatal("Test without scaling is uninteresting.");
457 }
msarettb32758a2015-08-18 13:22:46 -0700458
459 // Visually inspecting very small output images is not necessary. We will
460 // cover these cases in unit testing.
461 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
462 return Error::Nonfatal("Scaling very small images is uninteresting.");
463 }
msarett0a242972015-06-11 14:27:27 -0700464 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
465
Mike Reed7fcfb622018-02-09 13:26:46 -0500466 const int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700467 const size_t rowBytes = size.width() * bpp;
Mike Reedf0ffb892017-10-03 14:47:21 -0400468 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
scroggo19b91532016-10-24 09:03:26 -0700469 SkAutoMalloc pixels(safeSize);
msarett438b2ad2015-04-09 12:43:10 -0700470
msarettbb25b532016-01-13 09:31:39 -0800471 SkCodec::Options options;
Matt Saretta40d9c82017-05-19 15:21:05 -0400472 options.fPremulBehavior = canvas->imageInfo().colorSpace() ?
473 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
msarettbb25b532016-01-13 09:31:39 -0800474 if (kCodecZeroInit_Mode == fMode) {
msarettb1be46b2016-05-17 08:52:11 -0700475 memset(pixels.get(), 0, size.height() * rowBytes);
msarettbb25b532016-01-13 09:31:39 -0800476 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
477 }
msarett34e0ec42016-04-22 16:27:24 -0700478
479 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400480 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700481 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
482 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
483 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
484 }
scroggo9b77ddd2015-03-19 06:03:39 -0700485
scroggo9c59ebc2015-03-25 13:48:49 -0700486 switch (fMode) {
scroggo19b91532016-10-24 09:03:26 -0700487 case kAnimated_Mode: {
488 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
489 if (frameInfos.size() <= 1) {
490 return SkStringPrintf("%s is not an animated image.", fPath.c_str());
491 }
492
scroggo90e971a2016-10-25 06:11:01 -0700493 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
494 // into. "factor" is the number of frames to draw on one row. There will be
495 // up to "factor" rows as well.
496 const float root = sqrt((float) frameInfos.size());
497 const int factor = sk_float_ceil2int(root);
498
scroggo19b91532016-10-24 09:03:26 -0700499 // Used to cache a frame that future frames will depend on.
500 SkAutoMalloc priorFramePixels;
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400501 int cachedFrame = SkCodec::kNone;
502 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
scroggo19b91532016-10-24 09:03:26 -0700503 options.fFrameIndex = i;
504 // Check for a prior frame
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400505 const int reqFrame = frameInfos[i].fRequiredFrame;
scroggo19b91532016-10-24 09:03:26 -0700506 if (reqFrame != SkCodec::kNone && reqFrame == cachedFrame
507 && priorFramePixels.get()) {
508 // Copy into pixels
509 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400510 options.fPriorFrame = reqFrame;
scroggo19b91532016-10-24 09:03:26 -0700511 } else {
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400512 options.fPriorFrame = SkCodec::kNone;
scroggo19b91532016-10-24 09:03:26 -0700513 }
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500514 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
Leon Scroggins571b30f2017-07-11 17:35:31 +0000515 rowBytes, &options);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500516 if (SkCodec::kInvalidInput == result && i > 0) {
517 // Some of our test images have truncated later frames. Treat that
518 // the same as incomplete.
519 result = SkCodec::kIncompleteInput;
520 }
scroggo19b91532016-10-24 09:03:26 -0700521 switch (result) {
522 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400523 case SkCodec::kErrorInInput:
scroggo90e971a2016-10-25 06:11:01 -0700524 case SkCodec::kIncompleteInput: {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400525 // If the next frame depends on this one, store it in priorFrame.
526 // It is possible that we may discard a frame that future frames depend on,
527 // but the codec will simply redecode the discarded frame.
528 // Do this before calling draw_to_canvas, which premultiplies in place. If
529 // we're decoding to unpremul, we want to pass the unmodified frame to the
530 // codec for decoding the next frame.
531 if (static_cast<size_t>(i+1) < frameInfos.size()
532 && frameInfos[i+1].fRequiredFrame == i) {
533 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
534 cachedFrame = i;
535 }
536
scroggo90e971a2016-10-25 06:11:01 -0700537 SkAutoCanvasRestore acr(canvas, true);
538 const int xTranslate = (i % factor) * decodeInfo.width();
539 const int yTranslate = (i / factor) * decodeInfo.height();
540 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
Leon Scroggins571b30f2017-07-11 17:35:31 +0000541 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Leon Scroggins III674a1842017-07-06 12:26:09 -0400542 if (result != SkCodec::kSuccess) {
scroggo19b91532016-10-24 09:03:26 -0700543 return "";
544 }
545 break;
scroggo90e971a2016-10-25 06:11:01 -0700546 }
scroggo53f63b62016-10-27 08:29:13 -0700547 case SkCodec::kInvalidConversion:
Mike Reed304a07c2017-07-12 15:10:28 -0400548 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
scroggo53f63b62016-10-27 08:29:13 -0700549 return Error::Nonfatal(SkStringPrintf(
Mike Reed304a07c2017-07-12 15:10:28 -0400550 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str()));
scroggo53f63b62016-10-27 08:29:13 -0700551 }
552 // Fall through.
scroggo19b91532016-10-24 09:03:26 -0700553 default:
554 return SkStringPrintf("Couldn't getPixels for frame %i in %s.",
555 i, fPath.c_str());
556 }
scroggo19b91532016-10-24 09:03:26 -0700557 }
558 break;
559 }
msarettbb25b532016-01-13 09:31:39 -0800560 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700561 case kCodec_Mode: {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000562 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggoeb602a52015-07-09 08:16:03 -0700563 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400564 // We consider these to be valid, since we should still decode what is
scroggo9c59ebc2015-03-25 13:48:49 -0700565 // available.
Leon Scroggins III674a1842017-07-06 12:26:09 -0400566 case SkCodec::kErrorInInput:
scroggoeb602a52015-07-09 08:16:03 -0700567 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700568 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700569 default:
570 // Everything else is considered a failure.
571 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
572 }
msarettb1be46b2016-05-17 08:52:11 -0700573
Leon Scroggins571b30f2017-07-11 17:35:31 +0000574 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggo9c59ebc2015-03-25 13:48:49 -0700575 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700576 }
scroggo9c59ebc2015-03-25 13:48:49 -0700577 case kScanline_Mode: {
scroggod8d68552016-06-06 11:26:17 -0700578 void* dst = pixels.get();
579 uint32_t height = decodeInfo.height();
scroggo19b91532016-10-24 09:03:26 -0700580 const bool useIncremental = [this]() {
581 auto exts = { "png", "PNG", "gif", "GIF" };
582 for (auto ext : exts) {
583 if (fPath.endsWith(ext)) {
584 return true;
585 }
586 }
587 return false;
588 }();
589 // ico may use the old scanline method or the new one, depending on whether it
590 // internally holds a bmp or a png.
scroggo8e6c7ad2016-09-16 08:20:38 -0700591 const bool ico = fPath.endsWith("ico");
scroggo19b91532016-10-24 09:03:26 -0700592 bool useOldScanlineMethod = !useIncremental && !ico;
593 if (useIncremental || ico) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700594 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000595 rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700596 int rowsDecoded;
Leon Scroggins III674a1842017-07-06 12:26:09 -0400597 auto result = codec->incrementalDecode(&rowsDecoded);
598 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700599 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
600 SkCodec::kNo_ZeroInitialized, height,
601 rowsDecoded);
scroggo6fb23912016-06-02 14:16:43 -0700602 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700603 } else {
scroggo19b91532016-10-24 09:03:26 -0700604 if (useIncremental) {
605 // Error: These should support incremental decode.
scroggo8e6c7ad2016-09-16 08:20:38 -0700606 return "Could not start incremental decode";
607 }
608 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
609 // which should work via startScanlineDecode
610 useOldScanlineMethod = true;
611 }
612 }
613
614 if (useOldScanlineMethod) {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000615 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700616 return "Could not start scanline decoder";
617 }
618
Brian Osmanea176c62018-04-06 15:28:23 -0400619 // We do not need to check the return value. On an incomplete
620 // image, memory will be filled with a default value.
621 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700622 }
623
Leon Scroggins571b30f2017-07-11 17:35:31 +0000624 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer97002062015-05-27 12:36:10 -0700625 break;
626 }
msarett0a242972015-06-11 14:27:27 -0700627 case kStripe_Mode: {
628 const int height = decodeInfo.height();
629 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
630 // does not align with image blocks.
631 const int stripeHeight = 37;
632 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
msarettb1be46b2016-05-17 08:52:11 -0700633 void* dst = pixels.get();
msarett0a242972015-06-11 14:27:27 -0700634
635 // Decode odd stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000636 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarettb65e6042016-02-23 05:37:25 -0800637 return "Could not start scanline decoder";
638 }
639
640 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
641 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
642 // to run this test for image types that do not have this scanline ordering.
scroggo12e2f502016-05-16 09:04:18 -0700643 // We only run this on Jpeg, which is always kTopDown.
644 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
msarette6dd0042015-10-09 11:07:34 -0700645
msarett0a242972015-06-11 14:27:27 -0700646 for (int i = 0; i < numStripes; i += 2) {
647 // Skip a stripe
648 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700649 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700650
651 // Read a stripe
652 const int startY = (i + 1) * stripeHeight;
653 const int linesToRead = SkTMin(stripeHeight, height - startY);
654 if (linesToRead > 0) {
msarettb1be46b2016-05-17 08:52:11 -0700655 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
656 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700657 }
658 }
659
660 // Decode even stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000661 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
scroggo1c005e42015-08-04 09:24:45 -0700662 if (SkCodec::kSuccess != startResult) {
663 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700664 }
665 for (int i = 0; i < numStripes; i += 2) {
666 // Read a stripe
667 const int startY = i * stripeHeight;
668 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarettb1be46b2016-05-17 08:52:11 -0700669 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
670 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700671
672 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700673 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
674 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700675 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700676 }
677 }
msarettb1be46b2016-05-17 08:52:11 -0700678
Leon Scroggins571b30f2017-07-11 17:35:31 +0000679 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700680 break;
msarett0a242972015-06-11 14:27:27 -0700681 }
msarett91c22b22016-02-22 12:27:46 -0800682 case kCroppedScanline_Mode: {
683 const int width = decodeInfo.width();
684 const int height = decodeInfo.height();
685 // This value is chosen because, as we move across the image, it will sometimes
686 // align with the jpeg block sizes and it will sometimes not. This allows us
687 // to test interestingly different code paths in the implementation.
688 const int tileSize = 36;
msarett91c22b22016-02-22 12:27:46 -0800689 SkIRect subset;
690 for (int x = 0; x < width; x += tileSize) {
691 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
Matt Saretta40d9c82017-05-19 15:21:05 -0400692 options.fSubset = &subset;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000693 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarett91c22b22016-02-22 12:27:46 -0800694 return "Could not start scanline decoder.";
695 }
696
msarettb1be46b2016-05-17 08:52:11 -0700697 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
msarett91c22b22016-02-22 12:27:46 -0800698 }
699
Leon Scroggins571b30f2017-07-11 17:35:31 +0000700 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
msarett91c22b22016-02-22 12:27:46 -0800701 break;
702 }
scroggob636b452015-07-22 07:16:20 -0700703 case kSubset_Mode: {
704 // Arbitrarily choose a divisor.
705 int divisor = 2;
706 // Total width/height of the image.
707 const int W = codec->getInfo().width();
708 const int H = codec->getInfo().height();
709 if (divisor > W || divisor > H) {
710 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
711 "for %s with dimensions (%d x %d)", divisor,
712 fPath.c_str(), W, H));
713 }
714 // subset dimensions
715 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
716 const int w = SkAlign2(W / divisor);
717 const int h = SkAlign2(H / divisor);
718 SkIRect subset;
Matt Saretta40d9c82017-05-19 15:21:05 -0400719 options.fSubset = &subset;
scroggob636b452015-07-22 07:16:20 -0700720 SkBitmap subsetBm;
721 // We will reuse pixel memory from bitmap.
msarettb1be46b2016-05-17 08:52:11 -0700722 void* dst = pixels.get();
scroggob636b452015-07-22 07:16:20 -0700723 // Keep track of left and top (for drawing subsetBm into canvas). We could use
724 // fScale * x and fScale * y, but we want integers such that the next subset will start
725 // where the last one ended. So we'll add decodeInfo.width() and height().
726 int left = 0;
727 for (int x = 0; x < W; x += w) {
728 int top = 0;
729 for (int y = 0; y < H; y+= h) {
730 // Do not make the subset go off the edge of the image.
731 const int preScaleW = SkTMin(w, W - x);
732 const int preScaleH = SkTMin(h, H - y);
733 subset.setXYWH(x, y, preScaleW, preScaleH);
734 // And scale
735 // FIXME: Should we have a version of getScaledDimensions that takes a subset
736 // into account?
msarettc7eb4902016-04-25 07:04:58 -0700737 const int scaledW = SkTMax(1, SkScalarRoundToInt(preScaleW * fScale));
738 const int scaledH = SkTMax(1, SkScalarRoundToInt(preScaleH * fScale));
739 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
740 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
msarettb1be46b2016-05-17 08:52:11 -0700741 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
742 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000743 &options);
scroggob636b452015-07-22 07:16:20 -0700744 switch (result) {
745 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400746 case SkCodec::kErrorInInput:
scroggob636b452015-07-22 07:16:20 -0700747 case SkCodec::kIncompleteInput:
748 break;
scroggob636b452015-07-22 07:16:20 -0700749 default:
750 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
751 "from %s with dimensions (%d x %d)\t error %d",
752 x, y, decodeInfo.width(), decodeInfo.height(),
753 fPath.c_str(), W, H, result);
754 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000755 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
756 SkIntToScalar(left), SkIntToScalar(top));
msarettb1be46b2016-05-17 08:52:11 -0700757
scroggob636b452015-07-22 07:16:20 -0700758 // translate by the scaled height.
759 top += decodeInfo.height();
760 }
761 // translate by the scaled width.
762 left += decodeInfo.width();
763 }
764 return "";
765 }
msarettb714fb02016-01-22 14:46:42 -0800766 default:
767 SkASSERT(false);
768 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700769 }
scroggo9c59ebc2015-03-25 13:48:49 -0700770 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700771}
772
773SkISize CodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700774 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400775 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700776 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400777 return {0, 0};
scroggo7fac5af2015-09-30 11:33:12 -0700778 }
scroggo19b91532016-10-24 09:03:26 -0700779
780 auto imageSize = codec->getScaledDimensions(fScale);
781 if (fMode == kAnimated_Mode) {
scroggo90e971a2016-10-25 06:11:01 -0700782 // We'll draw one of each frame, so make it big enough to hold them all
783 // in a grid. The grid will be roughly square, with "factor" frames per
784 // row and up to "factor" rows.
scroggo19b91532016-10-24 09:03:26 -0700785 const size_t count = codec->getFrameInfo().size();
scroggo90e971a2016-10-25 06:11:01 -0700786 const float root = sqrt((float) count);
787 const int factor = sk_float_ceil2int(root);
788 imageSize.fWidth = imageSize.fWidth * factor;
789 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
scroggo19b91532016-10-24 09:03:26 -0700790 }
791 return imageSize;
scroggo9b77ddd2015-03-19 06:03:39 -0700792}
793
794Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700795 if (1.0f == fScale) {
scroggo6e8c68e2016-10-24 13:48:49 -0700796 Name name = SkOSPath::Basename(fPath.c_str());
797 if (fMode == kAnimated_Mode) {
798 name.append("_animated");
799 }
800 return name;
msarett0a242972015-06-11 14:27:27 -0700801 }
scroggo6e8c68e2016-10-24 13:48:49 -0700802 SkASSERT(fMode != kAnimated_Mode);
msaretta5783ae2015-09-08 15:35:32 -0700803 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700804}
805
806/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
807
scroggof8dc9df2016-05-16 09:04:13 -0700808AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800809 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700810 : fPath(path)
msarett3d9d7a72015-10-21 10:27:10 -0700811 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800812 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700813 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800814 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700815{}
816
817bool AndroidCodecSrc::veto(SinkFlags flags) const {
818 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700819 return flags.type != SinkFlags::kRaster
820 || flags.approach != SinkFlags::kDirect;
821}
822
823Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400824 if (canvas->imageInfo().colorSpace() &&
825 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
826 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
827 // run these tests on legacy canvases.
828 // We allow an exception for F16, since Android uses F16.
829 return Error::Nonfatal("Skip testing to color correct canvas.");
830 }
831
bungeman38d909e2016-08-02 14:40:46 -0700832 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700833 if (!encoded) {
834 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
835 }
Mike Reedede7bac2017-07-23 15:30:02 -0400836 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
837 if (nullptr == codec) {
msarett3d9d7a72015-10-21 10:27:10 -0700838 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
839 }
840
scroggoba584892016-05-20 13:56:13 -0700841 SkImageInfo decodeInfo = codec->getInfo();
842 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
843 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800844 return Error::Nonfatal("Skipping uninteresting test.");
msarett3d9d7a72015-10-21 10:27:10 -0700845 }
846
847 // Scale the image if it is desired.
848 SkISize size = codec->getSampledDimensions(fSampleSize);
849
850 // Visually inspecting very small output images is not necessary. We will
851 // cover these cases in unit testing.
852 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
853 return Error::Nonfatal("Scaling very small images is uninteresting.");
854 }
855 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
856
Mike Reed7fcfb622018-02-09 13:26:46 -0500857 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700858 size_t rowBytes = size.width() * bpp;
859 SkAutoMalloc pixels(size.height() * rowBytes);
msarett3d9d7a72015-10-21 10:27:10 -0700860
861 SkBitmap bitmap;
msarett34e0ec42016-04-22 16:27:24 -0700862 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400863 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700864 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
865 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
866 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
867 }
msarett3d9d7a72015-10-21 10:27:10 -0700868
869 // Create options for the codec.
870 SkAndroidCodec::AndroidOptions options;
msarett3d9d7a72015-10-21 10:27:10 -0700871 options.fSampleSize = fSampleSize;
872
msarettb1be46b2016-05-17 08:52:11 -0700873 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggof8dc9df2016-05-16 09:04:13 -0700874 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400875 case SkCodec::kErrorInInput:
scroggof8dc9df2016-05-16 09:04:13 -0700876 case SkCodec::kIncompleteInput:
877 break;
msarett3d9d7a72015-10-21 10:27:10 -0700878 default:
scroggof8dc9df2016-05-16 09:04:13 -0700879 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700880 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000881 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggof8dc9df2016-05-16 09:04:13 -0700882 return "";
msarett3d9d7a72015-10-21 10:27:10 -0700883}
884
885SkISize AndroidCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700886 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400887 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
msarett3d9d7a72015-10-21 10:27:10 -0700888 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400889 return {0, 0};
msarett3d9d7a72015-10-21 10:27:10 -0700890 }
891 return codec->getSampledDimensions(fSampleSize);
892}
893
894Name AndroidCodecSrc::name() const {
895 // We will replicate the names used by CodecSrc so that images can
896 // be compared in Gold.
897 if (1 == fSampleSize) {
898 return SkOSPath::Basename(fPath.c_str());
899 }
msarett4b0778e2015-11-13 09:59:11 -0800900 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700901}
902
903/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
904
msarett18976312016-03-09 14:20:58 -0800905ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
906 : fPath(path)
907 , fMode(mode)
908 , fDstAlphaType(alphaType)
909 , fIsGpu(isGpu)
910 , fRunSerially(serial_from_path_name(path))
911{}
912
913bool ImageGenSrc::veto(SinkFlags flags) const {
914 if (fIsGpu) {
Brian Salomonbd7c5512017-03-07 09:08:36 -0500915 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
916 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
917 flags.multisampled == SinkFlags::kMultisampled;
msarett18976312016-03-09 14:20:58 -0800918 }
919
920 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
921}
922
923Error ImageGenSrc::draw(SkCanvas* canvas) const {
924 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
925 return Error::Nonfatal("Uninteresting to test image generator to 565.");
926 }
927
bungeman38d909e2016-08-02 14:40:46 -0700928 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett18976312016-03-09 14:20:58 -0800929 if (!encoded) {
930 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
931 }
932
msarettfc0b6d12016-03-17 13:50:17 -0700933#if defined(SK_BUILD_FOR_WIN)
934 // Initialize COM in order to test with WIC.
935 SkAutoCoInitialize com;
936 if (!com.succeeded()) {
937 return "Could not initialize COM.";
938 }
939#endif
940
Ben Wagner145dbcd2016-11-03 14:40:50 -0400941 std::unique_ptr<SkImageGenerator> gen(nullptr);
msarett18976312016-03-09 14:20:58 -0800942 switch (fMode) {
943 case kCodec_Mode:
Mike Reed185130c2017-02-15 15:14:16 -0500944 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
msarett18976312016-03-09 14:20:58 -0800945 if (!gen) {
946 return "Could not create codec image generator.";
947 }
948 break;
msarettfc0b6d12016-03-17 13:50:17 -0700949 case kPlatform_Mode: {
msarett18976312016-03-09 14:20:58 -0800950#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
Leon Scroggins III0cbc10f2017-10-30 09:07:53 -0400951 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700952#elif defined(SK_BUILD_FOR_WIN)
bungeman38d909e2016-08-02 14:40:46 -0700953 gen.reset(SkImageGeneratorWIC::NewFromEncodedWIC(encoded.get()));
msarettfc0b6d12016-03-17 13:50:17 -0700954#endif
955
msarett18976312016-03-09 14:20:58 -0800956 if (!gen) {
msarettfc0b6d12016-03-17 13:50:17 -0700957 return "Could not create platform image generator.";
msarett18976312016-03-09 14:20:58 -0800958 }
959 break;
msarettfc0b6d12016-03-17 13:50:17 -0700960 }
msarett18976312016-03-09 14:20:58 -0800961 default:
962 SkASSERT(false);
963 return "Invalid image generator mode";
964 }
965
966 // Test deferred decoding path on GPU
967 if (fIsGpu) {
Mike Reed185130c2017-02-15 15:14:16 -0500968 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
msarett18976312016-03-09 14:20:58 -0800969 if (!image) {
970 return "Could not create image from codec image generator.";
971 }
972 canvas->drawImage(image, 0, 0);
973 return "";
974 }
mtklein343a63d2016-03-22 11:46:53 -0700975
msarett18976312016-03-09 14:20:58 -0800976 // Test various color and alpha types on CPU
977 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
mtklein343a63d2016-03-22 11:46:53 -0700978
Matt Saretta40d9c82017-05-19 15:21:05 -0400979 SkImageGenerator::Options options;
980 options.fBehavior = canvas->imageInfo().colorSpace() ?
981 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
982
Mike Reed7fcfb622018-02-09 13:26:46 -0500983 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700984 size_t rowBytes = decodeInfo.width() * bpp;
985 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
Matt Saretta40d9c82017-05-19 15:21:05 -0400986 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
Matt Sarett05cb4c32017-03-02 12:07:46 -0500987 SkString err =
988 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
989
990#if defined(SK_BUILD_FOR_WIN)
991 if (kPlatform_Mode == fMode) {
992 // Do not issue a fatal error for WIC flakiness.
993 return Error::Nonfatal(err);
994 }
995#endif
996
997 return err;
msarett18976312016-03-09 14:20:58 -0800998 }
999
Matt Sarettf485cf92017-05-26 08:58:03 -04001000 set_bitmap_color_space(&decodeInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +00001001 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
msarettb1be46b2016-05-17 08:52:11 -07001002 CodecSrc::kGetFromCanvas_DstColorType);
msarett18976312016-03-09 14:20:58 -08001003 return "";
1004}
1005
1006SkISize ImageGenSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001007 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001008 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett18976312016-03-09 14:20:58 -08001009 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001010 return {0, 0};
msarett18976312016-03-09 14:20:58 -08001011 }
1012 return codec->getInfo().dimensions();
1013}
1014
1015Name ImageGenSrc::name() const {
1016 return SkOSPath::Basename(fPath.c_str());
1017}
1018
1019/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1020
msarett9ce3a542016-07-15 13:54:38 -07001021ColorCodecSrc::ColorCodecSrc(Path path, Mode mode, SkColorType colorType)
msarett69deca82016-04-29 09:38:40 -07001022 : fPath(path)
1023 , fMode(mode)
msarett9ce3a542016-07-15 13:54:38 -07001024 , fColorType(colorType)
msarett69deca82016-04-29 09:38:40 -07001025{}
1026
1027bool ColorCodecSrc::veto(SinkFlags flags) const {
1028 // Test to direct raster backends (8888 and 565).
1029 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1030}
1031
Matt Sarett6a0feba2017-06-09 10:45:44 -04001032void clamp_if_necessary(const SkBitmap& bitmap, SkColorType dstCT) {
1033 if (kRGBA_F16_SkColorType != bitmap.colorType() || kRGBA_F16_SkColorType == dstCT) {
1034 // No need to clamp if the dst is F16. We will clamp when we encode to PNG.
1035 return;
1036 }
1037
Mike Klein45c16fa2017-07-18 18:15:13 -04001038 SkJumper_MemoryCtx ptr = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
1039
Matt Sarett6a0feba2017-06-09 10:45:44 -04001040 SkRasterPipeline_<256> p;
1041 p.append(SkRasterPipeline::load_f16, &ptr);
1042 p.append(SkRasterPipeline::clamp_0);
1043 if (kPremul_SkAlphaType == bitmap.alphaType()) {
1044 p.append(SkRasterPipeline::clamp_a);
1045 } else {
1046 p.append(SkRasterPipeline::clamp_1);
1047 }
1048 p.append(SkRasterPipeline::store_f16, &ptr);
1049
Mike Klein45c16fa2017-07-18 18:15:13 -04001050 p.run(0,0, bitmap.width(), bitmap.height());
Matt Sarett6a0feba2017-06-09 10:45:44 -04001051}
1052
msarett69deca82016-04-29 09:38:40 -07001053Error ColorCodecSrc::draw(SkCanvas* canvas) const {
1054 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
1055 return Error::Nonfatal("No need to test color correction to 565 backend.");
1056 }
1057
msarettd1ec89b2016-08-03 12:59:27 -07001058 bool runInLegacyMode = kBaseline_Mode == fMode;
msarettd1ec89b2016-08-03 12:59:27 -07001059 if (runInLegacyMode && canvas->imageInfo().colorSpace()) {
1060 return Error::Nonfatal("Skipping tests that are only interesting in legacy mode.");
1061 } else if (!runInLegacyMode && !canvas->imageInfo().colorSpace()) {
1062 return Error::Nonfatal("Skipping tests that are only interesting in srgb mode.");
msarett9ce3a542016-07-15 13:54:38 -07001063 }
1064
bungeman38d909e2016-08-02 14:40:46 -07001065 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett69deca82016-04-29 09:38:40 -07001066 if (!encoded) {
1067 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1068 }
1069
Mike Reedede7bac2017-07-23 15:30:02 -04001070 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1071 if (nullptr == codec) {
msarett69deca82016-04-29 09:38:40 -07001072 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
1073 }
1074
msarett9876ac52016-06-01 14:47:18 -07001075 // Load the dst ICC profile. This particular dst is fairly similar to Adobe RGB.
Mike Reed0933bc92017-12-09 01:27:41 +00001076 sk_sp<SkData> dstData = GetResourceAsData("icc_profiles/HP_ZR30w.icc");
msarett9876ac52016-06-01 14:47:18 -07001077 if (!dstData) {
1078 return "Cannot read monitor profile. Is the resource path set correctly?";
1079 }
1080
msarett50ce1f22016-07-29 06:23:33 -07001081 sk_sp<SkColorSpace> dstSpace = nullptr;
1082 if (kDst_sRGB_Mode == fMode) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -05001083 dstSpace = SkColorSpace::MakeSRGB();
msarett50ce1f22016-07-29 06:23:33 -07001084 } else if (kDst_HPZR30w_Mode == fMode) {
Brian Osman526972e2016-10-24 09:24:02 -04001085 dstSpace = SkColorSpace::MakeICC(dstData->data(), dstData->size());
msarett50ce1f22016-07-29 06:23:33 -07001086 }
1087
1088 SkImageInfo decodeInfo = codec->getInfo().makeColorType(fColorType).makeColorSpace(dstSpace);
msarettd1ec89b2016-08-03 12:59:27 -07001089 if (kUnpremul_SkAlphaType == decodeInfo.alphaType()) {
1090 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
1091 }
msarett2ecc35f2016-09-08 11:55:16 -07001092 if (kRGBA_F16_SkColorType == fColorType) {
Brian Osman36703d92017-12-12 14:09:31 -05001093 decodeInfo = decodeInfo.makeColorSpace(decodeInfo.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001094 }
msarettd1ec89b2016-08-03 12:59:27 -07001095
msarett50ce1f22016-07-29 06:23:33 -07001096 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -04001097 set_bitmap_color_space(&bitmapInfo);
msarett50ce1f22016-07-29 06:23:33 -07001098 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
1099 kBGRA_8888_SkColorType == decodeInfo.colorType())
1100 {
1101 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
1102 }
1103
1104 SkBitmap bitmap;
1105 if (!bitmap.tryAllocPixels(bitmapInfo)) {
1106 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
1107 bitmapInfo.width(), bitmapInfo.height());
1108 }
1109
1110 size_t rowBytes = bitmap.rowBytes();
1111 SkCodec::Result r = codec->getPixels(decodeInfo, bitmap.getPixels(), rowBytes);
Leon Scroggins III674a1842017-07-06 12:26:09 -04001112 switch (r) {
1113 case SkCodec::kSuccess:
1114 case SkCodec::kErrorInInput:
1115 case SkCodec::kIncompleteInput:
1116 break;
1117 default:
1118 return SkStringPrintf("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
msarett50ce1f22016-07-29 06:23:33 -07001119 }
1120
msarett69deca82016-04-29 09:38:40 -07001121 switch (fMode) {
1122 case kBaseline_Mode:
msarett39979d82016-07-28 17:11:18 -07001123 case kDst_sRGB_Mode:
msarett50ce1f22016-07-29 06:23:33 -07001124 case kDst_HPZR30w_Mode:
Matt Sarett6a0feba2017-06-09 10:45:44 -04001125 // We do not support drawing unclamped F16.
1126 clamp_if_necessary(bitmap, canvas->imageInfo().colorType());
msarett39979d82016-07-28 17:11:18 -07001127 canvas->drawBitmap(bitmap, 0, 0);
1128 break;
msarett69deca82016-04-29 09:38:40 -07001129 default:
1130 SkASSERT(false);
1131 return "Invalid fMode";
1132 }
1133 return "";
1134}
1135
1136SkISize ColorCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001137 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001138 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett69deca82016-04-29 09:38:40 -07001139 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001140 return {0, 0};
msarett69deca82016-04-29 09:38:40 -07001141 }
Hal Canaryfafe1352017-04-11 12:12:02 -04001142 return {codec->getInfo().width(), codec->getInfo().height()};
msarett69deca82016-04-29 09:38:40 -07001143}
1144
1145Name ColorCodecSrc::name() const {
1146 return SkOSPath::Basename(fPath.c_str());
1147}
1148
1149/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1150
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001151SKPSrc::SKPSrc(Path path) : fPath(path) { }
mtklein748ca3b2015-01-15 10:56:12 -08001152
Robert Phillipse4aae342018-03-14 10:26:57 -04001153static sk_sp<SkPicture> read_skp(const char* path, const SkDeserialProcs* procs = nullptr) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001154 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtklein75d98fd2015-01-18 07:05:01 -08001155 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001156 return nullptr;
mtklein748ca3b2015-01-15 10:56:12 -08001157 }
Robert Phillipse4aae342018-03-14 10:26:57 -04001158 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get(), procs));
mtklein75d98fd2015-01-18 07:05:01 -08001159 if (!pic) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001160 return nullptr;
mtklein75d98fd2015-01-18 07:05:01 -08001161 }
bungemanf93d7112016-09-16 06:24:20 -07001162 stream = nullptr; // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -07001163
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001164 return pic;
1165}
1166
1167Error SKPSrc::draw(SkCanvas* canvas) const {
1168 sk_sp<SkPicture> pic = read_skp(fPath.c_str());
1169 if (!pic) {
1170 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1171 }
1172
Robert Phillips33f02ed2018-03-27 08:06:57 -04001173 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
mtklein748ca3b2015-01-15 10:56:12 -08001174 canvas->drawPicture(pic);
1175 return "";
1176}
1177
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001178static SkRect get_cull_rect_for_skp(const char* path) {
1179 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtkleinffa901a2015-03-16 10:38:07 -07001180 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001181 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001182 }
1183 SkPictInfo info;
Mike Reede7a58322017-12-20 14:09:20 -05001184 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001185 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001186 }
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001187
1188 return info.fCullRect;
1189}
1190
1191SkISize SKPSrc::size() const {
1192 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
Robert Phillips33f02ed2018-03-27 08:06:57 -04001193 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001194 return {0, 0};
mtkleinffa901a2015-03-16 10:38:07 -07001195 }
1196 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -08001197}
1198
1199Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1200
Florin Malitafc043dc2017-12-31 11:08:42 -05001201/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1202
Florin Malita124d5af2017-12-31 17:02:26 -05001203#if !defined(SK_BUILD_FOR_GOOGLE3)
Florin Malita54f65c42018-01-16 17:04:30 -05001204SkottieSrc::SkottieSrc(Path path)
Florin Malitafc043dc2017-12-31 11:08:42 -05001205 : fName(SkOSPath::Basename(path.c_str())) {
1206
Florin Malita54f65c42018-01-16 17:04:30 -05001207 fAnimation = skottie::Animation::MakeFromFile(path.c_str());
Florin Malitafc043dc2017-12-31 11:08:42 -05001208 if (!fAnimation) {
1209 return;
1210 }
1211
1212 // Fit kTileCount x kTileCount frames to a 1000x1000 film strip.
1213 static constexpr SkScalar kTargetSize = 1000;
Florin Malita3fae0f32018-03-15 21:52:54 -04001214 fTileSize = SkSize::Make(kTargetSize / kTileCount, kTargetSize / kTileCount).toCeil();
Florin Malitafc043dc2017-12-31 11:08:42 -05001215}
1216
Florin Malita54f65c42018-01-16 17:04:30 -05001217Error SkottieSrc::draw(SkCanvas* canvas) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001218 if (!fAnimation) {
1219 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
1220 }
1221
1222 canvas->drawColor(SK_ColorWHITE);
1223
Florin Malitafc043dc2017-12-31 11:08:42 -05001224 const auto ip = fAnimation->inPoint() * 1000 / fAnimation->frameRate(),
1225 op = fAnimation->outPoint() * 1000 / fAnimation->frameRate(),
1226 fr = (op - ip) / (kTileCount * kTileCount - 1);
1227
Florin Malitad3c1b842018-01-27 12:43:24 -05001228 // Shuffled order to exercise non-linear frame progression.
1229 static constexpr int frames[] = { 4, 0, 3, 1, 2 };
1230 static_assert(SK_ARRAY_COUNT(frames) == kTileCount, "");
1231
Florin Malitafc043dc2017-12-31 11:08:42 -05001232 for (int i = 0; i < kTileCount; ++i) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001233 const SkScalar y = frames[i] * fTileSize.height();
Florin Malitafc043dc2017-12-31 11:08:42 -05001234
1235 for (int j = 0; j < kTileCount; ++j) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001236 const SkScalar x = frames[j] * fTileSize.width();
Florin Malitafc043dc2017-12-31 11:08:42 -05001237 SkRect dest = SkRect::MakeXYWH(x, y, fTileSize.width(), fTileSize.height());
1238
Florin Malitad3c1b842018-01-27 12:43:24 -05001239 const auto t = fr * (frames[i] * kTileCount + frames[j]);
Florin Malitadf2713c2018-01-09 15:51:21 -05001240 {
1241 SkAutoCanvasRestore acr(canvas, true);
Florin Malitad3c1b842018-01-27 12:43:24 -05001242 canvas->clipRect(dest, true);
Florin Malitadf2713c2018-01-09 15:51:21 -05001243 canvas->concat(SkMatrix::MakeRectToRect(SkRect::MakeSize(fAnimation->size()),
1244 dest,
Florin Malita3fae0f32018-03-15 21:52:54 -04001245 SkMatrix::kCenter_ScaleToFit));
Florin Malitadf2713c2018-01-09 15:51:21 -05001246
1247 fAnimation->animationTick(t);
1248 fAnimation->render(canvas);
1249 }
Florin Malitafc043dc2017-12-31 11:08:42 -05001250 }
1251 }
1252
1253 return "";
1254}
1255
Florin Malita54f65c42018-01-16 17:04:30 -05001256SkISize SkottieSrc::size() const {
Florin Malita3fae0f32018-03-15 21:52:54 -04001257 return SkISize::Make(kTileCount * fTileSize.width(),
1258 kTileCount * fTileSize.height());
Florin Malitafc043dc2017-12-31 11:08:42 -05001259}
1260
Florin Malita54f65c42018-01-16 17:04:30 -05001261Name SkottieSrc::name() const { return fName; }
Florin Malitafc043dc2017-12-31 11:08:42 -05001262
Florin Malita54f65c42018-01-16 17:04:30 -05001263bool SkottieSrc::veto(SinkFlags flags) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001264 // No need to test to non-(raster||gpu||vector) or indirect backends.
1265 bool type_ok = flags.type == SinkFlags::kRaster
1266 || flags.type == SinkFlags::kGPU
1267 || flags.type == SinkFlags::kVector;
1268
1269 return !type_ok || flags.approach != SinkFlags::kDirect;
1270}
Florin Malita124d5af2017-12-31 17:02:26 -05001271#endif
Florin Malitafc043dc2017-12-31 11:08:42 -05001272
1273/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
fmalitaa2b9fdf2016-08-03 19:53:36 -07001274#if defined(SK_XML)
fmalitabdf3e5c2016-09-17 07:26:26 -07001275// Used when the image doesn't have an intrinsic size.
Hal Canaryfafe1352017-04-11 12:12:02 -04001276static const SkSize kDefaultSVGSize = {1000, 1000};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001277
fmalitabdf3e5c2016-09-17 07:26:26 -07001278// Used to force-scale tiny fixed-size images.
Hal Canaryfafe1352017-04-11 12:12:02 -04001279static const SkSize kMinimumSVGSize = {128, 128};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001280
fmalitaacd2f5c2016-11-08 07:13:45 -08001281SVGSrc::SVGSrc(Path path)
1282 : fName(SkOSPath::Basename(path.c_str()))
1283 , fScale(1) {
fmalitabdf3e5c2016-09-17 07:26:26 -07001284
fmalitaacd2f5c2016-11-08 07:13:45 -08001285 SkFILEStream stream(path.c_str());
1286 if (!stream.isValid()) {
1287 return;
1288 }
1289 fDom = SkSVGDOM::MakeFromStream(stream);
1290 if (!fDom) {
1291 return;
1292 }
1293
1294 const SkSize& sz = fDom->containerSize();
1295 if (sz.isEmpty()) {
1296 // no intrinsic size
1297 fDom->setContainerSize(kDefaultSVGSize);
1298 } else {
1299 fScale = SkTMax(1.f, SkTMax(kMinimumSVGSize.width() / sz.width(),
1300 kMinimumSVGSize.height() / sz.height()));
1301 }
1302}
1303
1304Error SVGSrc::draw(SkCanvas* canvas) const {
fmalitabdf3e5c2016-09-17 07:26:26 -07001305 if (!fDom) {
fmalitaacd2f5c2016-11-08 07:13:45 -08001306 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
fmalitaa2b9fdf2016-08-03 19:53:36 -07001307 }
1308
fmalitaacd2f5c2016-11-08 07:13:45 -08001309 SkAutoCanvasRestore acr(canvas, true);
1310 canvas->scale(fScale, fScale);
1311 fDom->render(canvas);
1312
fmalitaa2b9fdf2016-08-03 19:53:36 -07001313 return "";
1314}
1315
1316SkISize SVGSrc::size() const {
fmalitaacd2f5c2016-11-08 07:13:45 -08001317 if (!fDom) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001318 return {0, 0};
fmalitabdf3e5c2016-09-17 07:26:26 -07001319 }
1320
Hal Canaryfafe1352017-04-11 12:12:02 -04001321 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1322 .toRound();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001323}
1324
fmalitaacd2f5c2016-11-08 07:13:45 -08001325Name SVGSrc::name() const { return fName; }
fmalitaa2b9fdf2016-08-03 19:53:36 -07001326
fmalita179d8852016-08-16 14:23:29 -07001327bool SVGSrc::veto(SinkFlags flags) const {
Florin Malita93323eb2017-06-16 15:31:17 -04001328 // No need to test to non-(raster||gpu||vector) or indirect backends.
fmalita179d8852016-08-16 14:23:29 -07001329 bool type_ok = flags.type == SinkFlags::kRaster
Florin Malita93323eb2017-06-16 15:31:17 -04001330 || flags.type == SinkFlags::kGPU
1331 || flags.type == SinkFlags::kVector;
fmalita179d8852016-08-16 14:23:29 -07001332
1333 return !type_ok || flags.approach != SinkFlags::kDirect;
1334}
1335
fmalitaa2b9fdf2016-08-03 19:53:36 -07001336#endif // defined(SK_XML)
1337/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -08001338
halcanary45420a92016-06-02 12:41:14 -07001339MSKPSrc::MSKPSrc(Path path) : fPath(path) {
bungemanf93d7112016-09-16 06:24:20 -07001340 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001341 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1342 if (count > 0) {
1343 fPages.reset(count);
1344 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1345 }
halcanary45420a92016-06-02 12:41:14 -07001346}
1347
Hal Canary45cde312017-04-03 16:06:42 -04001348int MSKPSrc::pageCount() const { return fPages.count(); }
halcanary45420a92016-06-02 12:41:14 -07001349
1350SkISize MSKPSrc::size() const { return this->size(0); }
Hal Canary45cde312017-04-03 16:06:42 -04001351SkISize MSKPSrc::size(int i) const {
Hal Canaryfafe1352017-04-11 12:12:02 -04001352 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
Hal Canary45cde312017-04-03 16:06:42 -04001353}
halcanary45420a92016-06-02 12:41:14 -07001354
1355Error MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
1356Error MSKPSrc::draw(int i, SkCanvas* canvas) const {
Hal Canary45cde312017-04-03 16:06:42 -04001357 if (this->pageCount() == 0) {
halcanary45420a92016-06-02 12:41:14 -07001358 return SkStringPrintf("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1359 }
Hal Canary45cde312017-04-03 16:06:42 -04001360 if (i >= fPages.count() || i < 0) {
halcanary45420a92016-06-02 12:41:14 -07001361 return SkStringPrintf("MultiPictureDocument page number out of range: %d", i);
1362 }
Hal Canary45cde312017-04-03 16:06:42 -04001363 SkPicture* page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001364 if (!page) {
Hal Canary45cde312017-04-03 16:06:42 -04001365 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1366 if (!stream) {
1367 return SkStringPrintf("Unable to open file: %s", fPath.c_str());
1368 }
1369 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
1370 return SkStringPrintf("SkMultiPictureDocument reader failed on page %d: %s", i,
1371 fPath.c_str());
1372 }
1373 page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001374 }
1375 canvas->drawPicture(page);
1376 return "";
1377}
1378
1379Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1380
1381/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1382
mtkleinad66f9b2015-02-13 15:11:10 -08001383Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
Mike Reed5df49342016-11-12 08:06:55 -06001384 return src.draw(SkMakeNullCanvas().get());
mtkleinad66f9b2015-02-13 15:11:10 -08001385}
1386
1387/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1388
Brian Osmane5756ec2017-09-06 17:08:30 -04001389static bool encode_png_base64(const SkBitmap& bitmap, SkString* dst) {
1390 SkPixmap pm;
1391 if (!bitmap.peekPixels(&pm)) {
1392 dst->set("peekPixels failed");
1393 return false;
1394 }
1395
1396 // We're going to embed this PNG in a data URI, so make it as small as possible
1397 SkPngEncoder::Options options;
1398 options.fFilterFlags = SkPngEncoder::FilterFlag::kAll;
1399 options.fZLibLevel = 9;
1400 options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
1401 : SkTransferFunctionBehavior::kIgnore;
1402
1403 SkDynamicMemoryWStream wStream;
1404 if (!SkPngEncoder::Encode(&wStream, pm, options)) {
1405 dst->set("SkPngEncoder::Encode failed");
1406 return false;
1407 }
1408
1409 sk_sp<SkData> pngData = wStream.detachAsData();
1410 size_t len = SkBase64::Encode(pngData->data(), pngData->size(), nullptr);
1411
1412 // The PNG can be almost arbitrarily large. We don't want to fill our logs with enormous URLs.
1413 // Infra says these can be pretty big, as long as we're only outputting them on failure.
1414 static const size_t kMaxBase64Length = 1024 * 1024;
1415 if (len > kMaxBase64Length) {
1416 dst->printf("Encoded image too large (%u bytes)", static_cast<uint32_t>(len));
1417 return false;
1418 }
1419
1420 dst->resize(len);
1421 SkBase64::Encode(pngData->data(), pngData->size(), dst->writable_str());
1422 return true;
1423}
1424
1425static Error compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
1426 // The dimensions are a property of the Src only, and so should be identical.
Mike Reedf0ffb892017-10-03 14:47:21 -04001427 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1428 if (reference.computeByteSize() != bitmap.computeByteSize()) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001429 return "Dimensions don't match reference";
1430 }
1431 // All SkBitmaps in DM are tight, so this comparison is easy.
Mike Reedf0ffb892017-10-03 14:47:21 -04001432 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001433 SkString encoded;
1434 SkString errString("Pixels don't match reference");
1435 if (encode_png_base64(reference, &encoded)) {
1436 errString.append("\nExpected: data:image/png;base64,");
1437 errString.append(encoded);
1438 } else {
1439 errString.append("\nExpected image failed to encode: ");
1440 errString.append(encoded);
1441 }
1442 if (encode_png_base64(bitmap, &encoded)) {
1443 errString.append("\nActual: data:image/png;base64,");
1444 errString.append(encoded);
1445 } else {
1446 errString.append("\nActual image failed to encode: ");
1447 errString.append(encoded);
1448 }
1449 return errString;
1450 }
1451 return "";
1452}
1453
1454/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1455
mtkleinb9eb4ac2015-02-02 18:26:03 -08001456DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1457
bsalomon85b4b532016-04-05 11:06:27 -07001458GPUSink::GPUSink(GrContextFactory::ContextType ct,
csmartdaltone812d492017-02-21 12:36:05 -07001459 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001460 SkCommandLineConfigGpu::SurfType surfType,
mtklein82d28432015-01-15 12:46:02 -08001461 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -07001462 bool diText,
brianosmand93c1202016-03-10 07:49:08 -08001463 SkColorType colorType,
Brian Salomonce5ee602017-07-17 11:31:31 -04001464 SkAlphaType alphaType,
brianosmanb109b8c2016-06-16 13:03:24 -07001465 sk_sp<SkColorSpace> colorSpace,
Brian Osmanf21aa042017-08-21 16:48:46 -04001466 bool threaded,
1467 const GrContextOptions& grCtxOptions)
Brian Salomonce5ee602017-07-17 11:31:31 -04001468 : fContextType(ct)
1469 , fContextOverrides(overrides)
Brian Salomonf865b052018-03-09 09:01:53 -05001470 , fSurfType(surfType)
Brian Salomonce5ee602017-07-17 11:31:31 -04001471 , fSampleCount(samples)
1472 , fUseDIText(diText)
1473 , fColorType(colorType)
1474 , fAlphaType(alphaType)
1475 , fColorSpace(std::move(colorSpace))
Brian Osmanf21aa042017-08-21 16:48:46 -04001476 , fThreaded(threaded)
1477 , fBaseContextOptions(grCtxOptions) {}
mtklein748ca3b2015-01-15 10:56:12 -08001478
Brian Salomon09d994e2016-12-21 11:14:46 -05001479DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
bsalomon648c6962015-10-23 09:06:59 -07001480
Brian Osmanf9810662017-08-30 10:02:10 -04001481Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
1482 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1483}
1484
1485Error GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1486 const GrContextOptions& baseOptions) const {
1487 GrContextOptions grOptions = baseOptions;
kkinnunen64492c42015-12-08 01:24:40 -08001488
kkinnunen5219fd92015-12-10 06:28:13 -08001489 src.modifyGrContextOptions(&grOptions);
1490
1491 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -08001492 const SkISize size = src.size();
Brian Salomonce5ee602017-07-17 11:31:31 -04001493 SkImageInfo info =
1494 SkImageInfo::Make(size.width(), size.height(), fColorType, fAlphaType, fColorSpace);
Brian Salomonf865b052018-03-09 09:01:53 -05001495 sk_sp<SkSurface> surface;
msarett13a036b2016-02-08 09:10:47 -08001496#if SK_SUPPORT_GPU
csmartdaltone812d492017-02-21 12:36:05 -07001497 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
bsalomon8b7451a2016-05-11 06:33:06 -07001498 const int maxDimension = context->caps()->maxTextureSize();
msarett13a036b2016-02-08 09:10:47 -08001499 if (maxDimension < SkTMax(size.width(), size.height())) {
1500 return Error::Nonfatal("Src too large to create a texture.\n");
1501 }
Brian Salomonf865b052018-03-09 09:01:53 -05001502 uint32_t flags = fUseDIText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
1503 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
1504 GrBackendTexture backendTexture;
1505 GrBackendRenderTarget backendRT;
1506 switch (fSurfType) {
1507 case SkCommandLineConfigGpu::SurfType::kDefault:
1508 surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, fSampleCount,
1509 &props);
1510 break;
1511 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
1512 backendTexture = context->contextPriv().getGpu()->createTestingOnlyBackendTexture(
1513 nullptr, info.width(), info.height(), info.colorType(), true, GrMipMapped::kNo);
1514 surface = SkSurface::MakeFromBackendTexture(context, backendTexture,
1515 kTopLeft_GrSurfaceOrigin, fSampleCount,
Brian Salomon53706772018-03-19 14:18:08 -04001516 fColorType, info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001517 break;
1518 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1519 if (1 == fSampleCount) {
1520 auto srgbEncoded = info.colorSpace() && info.colorSpace()->gammaCloseToSRGB()
1521 ? GrSRGBEncoded::kYes
1522 : GrSRGBEncoded::kNo;
1523 auto colorType = SkColorTypeToGrColorType(info.colorType());
1524 backendRT = context->contextPriv().getGpu()->createTestingOnlyBackendRenderTarget(
1525 info.width(), info.height(), colorType, srgbEncoded);
Brian Salomon49edccd2018-03-23 15:31:32 -04001526 surface = SkSurface::MakeFromBackendRenderTarget(
1527 context, backendRT, kBottomLeft_GrSurfaceOrigin, info.colorType(),
1528 info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001529 }
1530 break;
1531 }
msarett13a036b2016-02-08 09:10:47 -08001532#endif
1533
mtklein748ca3b2015-01-15 10:56:12 -08001534 if (!surface) {
1535 return "Could not create a surface.";
1536 }
joshualitt5f5a8d72015-02-25 14:09:45 -08001537 if (FLAGS_preAbandonGpuContext) {
joshualitt5f5a8d72015-02-25 14:09:45 -08001538 factory.abandonContexts();
1539 }
mtklein748ca3b2015-01-15 10:56:12 -08001540 SkCanvas* canvas = surface->getCanvas();
1541 Error err = src.draw(canvas);
1542 if (!err.isEmpty()) {
1543 return err;
1544 }
1545 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -08001546 if (FLAGS_gpuStats) {
Robert Phillips0c4b7b12018-03-06 08:20:37 -05001547#if SK_SUPPORT_GPU
1548 canvas->getGrContext()->contextPriv().dumpCacheStats(log);
1549 canvas->getGrContext()->contextPriv().dumpGpuStats(log);
1550#endif
mtkleinb9eb4ac2015-02-02 18:26:03 -08001551 }
Brian Salomon5fba7ad2018-03-22 10:01:16 -04001552 if (info.colorType() == kRGB_565_SkColorType || info.colorType() == kARGB_4444_SkColorType ||
1553 info.colorType() == kRGB_888x_SkColorType) {
Brian Salomonce5ee602017-07-17 11:31:31 -04001554 // We don't currently support readbacks into these formats on the GPU backend. Convert to
1555 // 32 bit.
1556 info = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
1557 kPremul_SkAlphaType, fColorSpace);
1558 }
mtklein748ca3b2015-01-15 10:56:12 -08001559 dst->allocPixels(info);
Mike Reed12e946b2017-04-17 10:53:29 -04001560 canvas->readPixels(*dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -08001561 if (FLAGS_abandonGpuContext) {
1562 factory.abandonContexts();
bsalomon6e2aad42016-04-01 11:54:31 -07001563 } else if (FLAGS_releaseAndAbandonGpuContext) {
1564 factory.releaseResourcesAndAbandonContexts();
mtklein55e88b22015-01-21 15:50:13 -08001565 }
Brian Salomonf865b052018-03-09 09:01:53 -05001566#if SK_SUPPORT_GPU
1567 if (!context->contextPriv().abandoned()) {
1568 surface.reset();
1569 if (backendTexture.isValid()) {
Brian Salomon26102cb2018-03-09 09:33:19 -05001570 context->contextPriv().getGpu()->deleteTestingOnlyBackendTexture(backendTexture);
Brian Salomonf865b052018-03-09 09:01:53 -05001571 }
1572 if (backendRT.isValid()) {
1573 context->contextPriv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
1574 }
1575 }
1576#endif
mtklein748ca3b2015-01-15 10:56:12 -08001577 return "";
1578}
1579
1580/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1581
Brian Osmanf9810662017-08-30 10:02:10 -04001582GPUThreadTestingSink::GPUThreadTestingSink(GrContextFactory::ContextType ct,
1583 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001584 SkCommandLineConfigGpu::SurfType surfType,
Brian Osmanf9810662017-08-30 10:02:10 -04001585 int samples,
1586 bool diText,
1587 SkColorType colorType,
1588 SkAlphaType alphaType,
1589 sk_sp<SkColorSpace> colorSpace,
1590 bool threaded,
1591 const GrContextOptions& grCtxOptions)
Brian Salomonf865b052018-03-09 09:01:53 -05001592 : INHERITED(ct, overrides, surfType, samples, diText, colorType, alphaType,
1593 std::move(colorSpace), threaded, grCtxOptions)
Chris Dalton040238b2017-12-18 14:22:34 -07001594#if SK_SUPPORT_GPU
Mike Klein022cfa22017-09-01 11:53:16 -04001595 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)) {
Chris Dalton040238b2017-12-18 14:22:34 -07001596#else
1597 , fExecutor(nullptr) {
1598#endif
Brian Osmanf9810662017-08-30 10:02:10 -04001599 SkASSERT(fExecutor);
1600}
1601
1602Error GPUThreadTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1603 SkString* log) const {
1604 // Draw twice, once with worker threads, and once without. Verify that we get the same result.
1605 // Also, force us to only use the software path renderer, so we really stress-test the threaded
1606 // version of that code.
1607 GrContextOptions contextOptions = this->baseContextOptions();
Brian Osman195c05b2017-08-30 15:14:04 -04001608 contextOptions.fGpuPathRenderers = GpuPathRenderers::kNone;
Brian Osmanf9810662017-08-30 10:02:10 -04001609
1610 contextOptions.fExecutor = fExecutor.get();
1611 Error err = this->onDraw(src, dst, wStream, log, contextOptions);
1612 if (!err.isEmpty() || !dst) {
1613 return err;
1614 }
1615
1616 SkBitmap reference;
1617 SkString refLog;
1618 SkDynamicMemoryWStream refStream;
1619 contextOptions.fExecutor = nullptr;
1620 Error refErr = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1621 if (!refErr.isEmpty()) {
1622 return refErr;
1623 }
1624
Brian Osmane5756ec2017-09-06 17:08:30 -04001625 return compare_bitmaps(reference, *dst);
Brian Osmanf9810662017-08-30 10:02:10 -04001626}
1627
1628/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1629
halcanary47ef4d52015-03-03 09:13:09 -08001630static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
halcanary4ba051c2016-03-10 10:31:53 -08001631 if (src.size().isEmpty()) {
1632 return "Source has empty dimensions";
1633 }
halcanary47ef4d52015-03-03 09:13:09 -08001634 SkASSERT(doc);
halcanary45420a92016-06-02 12:41:14 -07001635 int pageCount = src.pageCount();
1636 for (int i = 0; i < pageCount; ++i) {
1637 int width = src.size(i).width(), height = src.size(i).height();
halcanary7e798182015-04-14 14:06:18 -07001638 SkCanvas* canvas =
1639 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1640 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001641 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001642 }
halcanary45420a92016-06-02 12:41:14 -07001643 Error err = src.draw(i, canvas);
halcanary7e798182015-04-14 14:06:18 -07001644 if (!err.isEmpty()) {
1645 return err;
1646 }
1647 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001648 }
reedd14df7c2016-09-22 14:12:46 -07001649 doc->close();
halcanaryfd4a9932015-01-28 11:45:58 -08001650 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -08001651 return "";
1652}
1653
halcanary47ef4d52015-03-03 09:13:09 -08001654Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary4b656662016-04-27 07:45:18 -07001655 SkDocument::PDFMetadata metadata;
1656 metadata.fTitle = src.name();
1657 metadata.fSubject = "rendering correctness test";
1658 metadata.fCreator = "Skia/DM";
Mike Reeda4daf192017-12-14 13:25:04 -05001659 metadata.fRasterDPI = fRasterDpi;
1660 metadata.fPDFA = fPDFA;
1661 sk_sp<SkDocument> doc = SkDocument::MakePDF(dst, metadata);
halcanary47ef4d52015-03-03 09:13:09 -08001662 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001663 return "SkDocument::MakePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001664 }
1665 return draw_skdocument(src, doc.get(), dst);
1666}
1667
1668/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1669
1670XPSSink::XPSSink() {}
1671
Hal Canaryabc88d22017-02-06 09:26:49 -05001672#ifdef SK_BUILD_FOR_WIN
Hal Canary5e221e72017-02-06 09:51:42 -05001673static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1674 IXpsOMObjectFactory* factory;
1675 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1676 nullptr,
1677 CLSCTX_INPROC_SERVER,
1678 IID_PPV_ARGS(&factory)));
1679 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1680}
1681
1682Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canaryabc88d22017-02-06 09:26:49 -05001683 SkAutoCoInitialize com;
1684 if (!com.succeeded()) {
1685 return "Could not initialize COM.";
1686 }
Hal Canary5e221e72017-02-06 09:51:42 -05001687 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1688 if (!factory) {
1689 return "Failed to create XPS Factory.";
1690 }
1691 sk_sp<SkDocument> doc(SkDocument::MakeXPS(dst, factory.get()));
halcanary47ef4d52015-03-03 09:13:09 -08001692 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001693 return "SkDocument::MakeXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001694 }
1695 return draw_skdocument(src, doc.get(), dst);
1696}
Hal Canary5e221e72017-02-06 09:51:42 -05001697#else
1698Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1699 return "XPS not supported on this platform.";
1700}
1701#endif
reed54dc4872016-09-13 08:09:45 -07001702
1703/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1704
1705PipeSink::PipeSink() {}
1706
1707Error PipeSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1708 return src.draw(SkPipeSerializer().beginWrite(SkRect::Make(src.size()), dst));
1709}
1710
mtklein748ca3b2015-01-15 10:56:12 -08001711/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1712
mtklein9c3f17d2015-01-28 11:35:18 -08001713SKPSink::SKPSink() {}
1714
mtkleinb9eb4ac2015-02-02 18:26:03 -08001715Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001716 SkSize size;
1717 size = src.size();
1718 SkPictureRecorder recorder;
1719 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1720 if (!err.isEmpty()) {
1721 return err;
1722 }
reedca2622b2016-03-18 07:25:55 -07001723 recorder.finishRecordingAsPicture()->serialize(dst);
mtklein9c3f17d2015-01-28 11:35:18 -08001724 return "";
1725}
1726
1727/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1728
Hal Canary85c7fe82016-10-25 10:33:27 -04001729Error DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1730 SkDebugCanvas debugCanvas(src.size().width(), src.size().height());
1731 Error err = src.draw(&debugCanvas);
1732 if (!err.isEmpty()) {
1733 return err;
1734 }
Mike Reed5df49342016-11-12 08:06:55 -06001735 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
Hal Canary85c7fe82016-10-25 10:33:27 -04001736 UrlDataManager dataManager(SkString("data"));
1737 Json::Value json = debugCanvas.toJSON(
1738 dataManager, debugCanvas.getSize(), nullCanvas.get());
1739 std::string value = Json::StyledWriter().write(json);
1740 return dst->write(value.c_str(), value.size()) ? "" : "SkWStream Error";
1741}
1742
1743/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1744
Bryce Thomas95a7b762018-03-02 13:54:21 -08001745SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
mtklein8a4527e2015-01-31 20:00:58 -08001746
mtkleinb9eb4ac2015-02-02 18:26:03 -08001747Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita718df0a2016-07-15 10:33:29 -07001748#if defined(SK_XML)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001749 if (src.pageCount() > 1) {
1750 int pageCount = src.pageCount();
1751 if (fPageIndex > pageCount - 1) {
1752 return Error(SkStringPrintf("Page index %d too high for document with only %d pages.",
1753 fPageIndex, pageCount));
1754 }
1755 }
Ben Wagner145dbcd2016-11-03 14:40:50 -04001756 std::unique_ptr<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
Bryce Thomas95a7b762018-03-02 13:54:21 -08001757 return src.draw(fPageIndex,
1758 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
Mike Reed5df49342016-11-12 08:06:55 -06001759 SkIntToScalar(src.size().height())),
Bryce Thomas95a7b762018-03-02 13:54:21 -08001760 xmlWriter.get())
1761 .get());
fmalita718df0a2016-07-15 10:33:29 -07001762#else
Hal Canary327ef032018-03-22 13:10:51 -04001763 (void)fPageIndex;
fmalita718df0a2016-07-15 10:33:29 -07001764 return Error("SVG sink is disabled.");
1765#endif // SK_XML
mtklein8a4527e2015-01-31 20:00:58 -08001766}
1767
1768/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1769
brianosmanb109b8c2016-06-16 13:03:24 -07001770RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
mtklein27c3fdd2016-02-26 14:43:21 -08001771 : fColorType(colorType)
brianosmanb109b8c2016-06-16 13:03:24 -07001772 , fColorSpace(std::move(colorSpace)) {}
mtklein748ca3b2015-01-15 10:56:12 -08001773
Yuqian Lib8b62532018-02-23 14:13:36 +08001774void RasterSink::allocPixels(const Src& src, SkBitmap* dst) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001775 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001776 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1777 SkAlphaType alphaType = kPremul_SkAlphaType;
1778 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1779
Mike Reed086a4272017-07-18 10:53:11 -04001780 dst->allocPixelsFlags(SkImageInfo::Make(size.width(), size.height(),
1781 fColorType, alphaType, fColorSpace),
1782 SkBitmap::kZeroPixels_AllocFlag);
Yuqian Lib8b62532018-02-23 14:13:36 +08001783}
1784
1785Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
1786 this->allocPixels(src, dst);
mtklein748ca3b2015-01-15 10:56:12 -08001787 SkCanvas canvas(*dst);
1788 return src.draw(&canvas);
1789}
1790
1791/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1792
Yuqian Lib8b62532018-02-23 14:13:36 +08001793ThreadedSink::ThreadedSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
1794 : RasterSink(colorType, colorSpace)
1795 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_backendThreads)) {
1796}
1797
1798Error ThreadedSink::draw(const Src& src, SkBitmap* dst, SkWStream* stream, SkString* str) const {
1799 this->allocPixels(src, dst);
1800
1801 std::unique_ptr<SkThreadedBMPDevice> device(new SkThreadedBMPDevice(
1802 *dst, FLAGS_backendTiles, FLAGS_backendThreads, fExecutor.get()));
1803 std::unique_ptr<SkCanvas> canvas(new SkCanvas(device.get()));
1804 Error result = src.draw(canvas.get());
1805 canvas->flush();
1806 return result;
1807
1808 // ??? yuqian: why does the following give me segmentation fault while the above one works?
1809 // The seg fault occurs right in the beginning of ThreadedSink::draw with invalid
1810 // memory address (it would crash without even calling this->allocPixels).
1811
1812 // SkThreadedBMPDevice device(*dst, tileCnt, FLAGS_cpuThreads, fExecutor.get());
1813 // SkCanvas canvas(&device);
1814 // Error result = src.draw(&canvas);
1815 // canvas.flush();
1816 // return result;
1817}
1818
1819/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1820
mtkleina16e69e2015-05-05 11:38:45 -07001821// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001822// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001823// Several examples below.
1824
mtkleincbf89782016-02-19 14:27:14 -08001825template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001826static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001827 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001828 class ProxySrc : public Src {
1829 public:
mtkleincbf89782016-02-19 14:27:14 -08001830 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001831 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
halcanaryb4a7f142016-03-30 08:31:27 -07001832 Name name() const override { return "ProxySrc"; }
1833 SkISize size() const override { return fSize; }
mtkleina16e69e2015-05-05 11:38:45 -07001834 private:
mtkleincbf89782016-02-19 14:27:14 -08001835 SkISize fSize;
1836 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001837 };
msarett62d3b102015-12-10 15:14:27 -08001838 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001839}
1840
1841/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1842
mtklein4a34ecb2016-01-08 10:19:35 -08001843DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1844
1845// Is *bitmap identical to what you get drawing src into sink?
1846static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1847 // We can only check raster outputs.
1848 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1849 if (FLAGS_check && bitmap) {
1850 SkBitmap reference;
1851 SkString log;
halcanaryb4a7f142016-03-30 08:31:27 -07001852 SkDynamicMemoryWStream wStream;
1853 Error err = sink->draw(src, &reference, &wStream, &log);
mtklein4a34ecb2016-01-08 10:19:35 -08001854 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1855 SkASSERT(err.isEmpty());
1856 if (!err.isEmpty()) {
1857 return err;
1858 }
Brian Osmane5756ec2017-09-06 17:08:30 -04001859 return compare_bitmaps(reference, *bitmap);
mtklein4a34ecb2016-01-08 10:19:35 -08001860 }
1861 return "";
1862}
1863
1864/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1865
mtkleind603b222015-02-17 11:13:33 -08001866static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1867 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1868 matrix->mapRect(&bounds);
1869 matrix->postTranslate(-bounds.x(), -bounds.y());
Hal Canaryfafe1352017-04-11 12:12:02 -04001870 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
mtkleind603b222015-02-17 11:13:33 -08001871}
1872
msarett62d3b102015-12-10 15:14:27 -08001873ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001874
mtkleinb9eb4ac2015-02-02 18:26:03 -08001875Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001876 SkMatrix matrix = fMatrix;
1877 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
Ben Wagner145dbcd2016-11-03 14:40:50 -04001878 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001879 canvas->concat(matrix);
1880 return src.draw(canvas);
1881 });
mtklein748ca3b2015-01-15 10:56:12 -08001882}
1883
mtkleind603b222015-02-17 11:13:33 -08001884// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1885// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001886ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001887
1888Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1889 Error err = fSink->draw(src, bitmap, stream, log);
1890 if (!err.isEmpty()) {
1891 return err;
1892 }
1893
1894 SkMatrix inverse;
1895 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1896 return "Cannot upright --matrix.";
1897 }
1898 SkMatrix upright = SkMatrix::I();
1899 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1900 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1901 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1902 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1903
1904 SkBitmap uprighted;
1905 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1906 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1907
1908 SkCanvas canvas(uprighted);
1909 canvas.concat(upright);
1910 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001911 paint.setBlendMode(SkBlendMode::kSrc);
mtkleind603b222015-02-17 11:13:33 -08001912 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1913
1914 *bitmap = uprighted;
mtkleind603b222015-02-17 11:13:33 -08001915 return "";
1916}
1917
mtklein748ca3b2015-01-15 10:56:12 -08001918/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1919
mtkleina16e69e2015-05-05 11:38:45 -07001920Error ViaSerialization::draw(
1921 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001922 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001923 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001924 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001925 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1926 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001927 if (!err.isEmpty()) {
1928 return err;
1929 }
reedca2622b2016-03-18 07:25:55 -07001930 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001931
1932 // Serialize it and then deserialize it.
reed39eaf5f2016-09-15 07:19:35 -07001933 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
mtklein748ca3b2015-01-15 10:56:12 -08001934
Ben Wagner1861e882018-04-04 17:40:46 -04001935 err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001936 canvas->drawPicture(deserialized);
Ben Wagner1861e882018-04-04 17:40:46 -04001937 return "";
mtkleina16e69e2015-05-05 11:38:45 -07001938 });
Ben Wagner1861e882018-04-04 17:40:46 -04001939 if (!err.isEmpty()) {
1940 return err;
1941 }
1942
1943 return check_against_reference(bitmap, src, fSink.get());
mtklein748ca3b2015-01-15 10:56:12 -08001944}
1945
1946/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1947
msarett62d3b102015-12-10 15:14:27 -08001948ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1949 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001950 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001951 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001952 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001953
mtkleinb9eb4ac2015-02-02 18:26:03 -08001954Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001955 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001956 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001957 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1958 SkIntToScalar(size.height()),
1959 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001960 if (!err.isEmpty()) {
1961 return err;
1962 }
reedca2622b2016-03-18 07:25:55 -07001963 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001964
Ben Wagner145dbcd2016-11-03 14:40:50 -04001965 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001966 const int xTiles = (size.width() + fW - 1) / fW,
1967 yTiles = (size.height() + fH - 1) / fH;
1968 SkMultiPictureDraw mpd(xTiles*yTiles);
reede8f30622016-03-23 18:59:25 -07001969 SkTArray<sk_sp<SkSurface>> surfaces;
1970// surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001971
mtkleina16e69e2015-05-05 11:38:45 -07001972 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1973 for (int j = 0; j < yTiles; j++) {
1974 for (int i = 0; i < xTiles; i++) {
1975 // This lets our ultimate Sink determine the best kind of surface.
1976 // E.g., if it's a GpuSink, the surfaces and images are textures.
reede8f30622016-03-23 18:59:25 -07001977 auto s = canvas->makeSurface(info);
mtkleina16e69e2015-05-05 11:38:45 -07001978 if (!s) {
reede8f30622016-03-23 18:59:25 -07001979 s = SkSurface::MakeRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001980 }
reede8f30622016-03-23 18:59:25 -07001981 surfaces.push_back(s);
mtkleina16e69e2015-05-05 11:38:45 -07001982 SkCanvas* c = s->getCanvas();
1983 c->translate(SkIntToScalar(-i * fW),
1984 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
reedca2622b2016-03-18 07:25:55 -07001985 mpd.add(c, pic.get());
mtklein748ca3b2015-01-15 10:56:12 -08001986 }
mtklein748ca3b2015-01-15 10:56:12 -08001987 }
mtkleina16e69e2015-05-05 11:38:45 -07001988 mpd.draw();
1989 for (int j = 0; j < yTiles; j++) {
1990 for (int i = 0; i < xTiles; i++) {
reed9ce9d672016-03-17 10:51:11 -07001991 sk_sp<SkImage> image(surfaces[i+xTiles*j]->makeImageSnapshot());
mtkleina16e69e2015-05-05 11:38:45 -07001992 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1993 }
1994 }
mtkleina16e69e2015-05-05 11:38:45 -07001995 return "";
1996 });
mtklein748ca3b2015-01-15 10:56:12 -08001997}
1998
mtkleinb7e8d692015-04-07 08:30:32 -07001999/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2000
Robert Phillips33f02ed2018-03-27 08:06:57 -04002001#if SK_SUPPORT_GPU
2002
2003ViaDDL::ViaDDL(int numDivisions, Sink* sink)
2004 : Via(sink)
2005 , fNumDivisions(numDivisions) {
2006}
2007
2008// This class consolidates tracking & extraction of the original image data from the sources,
2009// the upload of said data to the GPU and the fulfillment of promise images.
Robert Phillipsa479f962018-04-10 11:45:40 -04002010//
2011// The way this works is:
2012// the original skp is converted to SkData and all its image info is extracted into this
2013// class and only indices into this class are left in the SkData
2014// Prior to replaying in threads, all the images stored in this class are uploaded to the
2015// gpu and PromiseImageCallbackContexts are created for them
2016// Each thread reinflates the SkData into an SkPicture replacing all the indices w/
2017// promise images (all using the same GrBackendTexture and getting a ref to the
2018// appropriate PromiseImageCallbackContext) and then creates a DDL.
2019// This class is then reset - dropping all of its refs on the PromiseImageCallbackContexts
2020// Each done callback unrefs its PromiseImageCallbackContext so, once all the promise images
2021// are done the PromiseImageCallbackContext is freed and its GrBackendTexture removed
2022// from VRAM
2023//
Robert Phillips33f02ed2018-03-27 08:06:57 -04002024class ViaDDL::PromiseImageHelper {
2025public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002026 // This class acts as a proxy for the single GrBackendTexture representing an image.
2027 // Whenever a promise image is created for the image the promise image receives a ref to
2028 // this object. Once all the promise images receive their done callbacks this object
2029 // is deleted - removing the GrBackendTexture from VRAM.
2030 // Note that while the DDLs are being created in the threads, the PromiseImageHelper holds
2031 // a ref on all the PromiseImageCallbackContexts. However, once all the threads are done
2032 // it drops all of its refs (via "reset").
2033 class PromiseImageCallbackContext : public SkRefCnt {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002034 public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002035 PromiseImageCallbackContext(GrContext* context) : fContext(context) {}
2036
2037 ~PromiseImageCallbackContext() {
2038 GrGpu* gpu = fContext->contextPriv().getGpu();
2039
2040 if (fBackendTexture.isValid()) {
2041 gpu->deleteTestingOnlyBackendTexture(fBackendTexture);
2042 }
2043 }
2044
2045 void setBackendTexture(const GrBackendTexture& backendTexture) {
2046 fBackendTexture = backendTexture;
2047 }
2048
2049 const GrBackendTexture& backendTexture() const { return fBackendTexture; }
2050
2051 private:
2052 GrContext* fContext;
2053 GrBackendTexture fBackendTexture;
2054
2055 typedef SkRefCnt INHERITED;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002056 };
2057
Robert Phillipsa479f962018-04-10 11:45:40 -04002058 // This is the information extracted into this class from the parsing of the skp file.
2059 // Once it has all been uploaded to the GPU and distributed to the promise images, it
2060 // is all dropped via "reset".
2061 class PromiseImageInfo {
2062 public:
2063 int fIndex; // index in the 'fImageInfo' array
2064 uint32_t fOriginalUniqueID; // original ID for deduping
2065 SkBitmap fBitmap; // CPU-side cache of the contents
2066 sk_sp<PromiseImageCallbackContext> fCallbackContext;
2067 };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002068
Robert Phillipsa479f962018-04-10 11:45:40 -04002069 PromiseImageHelper() { }
2070
2071 void reset() { fImageInfo.reset(); }
Robert Phillips33f02ed2018-03-27 08:06:57 -04002072
2073 bool isValidID(int id) const {
2074 return id >= 0 && id < fImageInfo.count();
2075 }
2076
Robert Phillipsa479f962018-04-10 11:45:40 -04002077 const PromiseImageInfo& getInfo(int id) const {
2078 return fImageInfo[id];
Robert Phillips33f02ed2018-03-27 08:06:57 -04002079 }
2080
2081 // returns -1 on failure
2082 int findOrDefineImage(SkImage* image) {
2083 int preExistingID = this->findImage(image);
2084 if (preExistingID >= 0) {
2085 SkASSERT(this->isValidID(preExistingID));
2086 return preExistingID;
2087 }
2088
2089 int newID = this->addImage(image);
2090 SkASSERT(this->isValidID(newID));
2091 return newID;
2092 }
2093
2094 void uploadAllToGPU(GrContext* context) {
2095 GrGpu* gpu = context->contextPriv().getGpu();
2096 SkASSERT(gpu);
2097
2098 for (int i = 0; i < fImageInfo.count(); ++i) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002099 sk_sp<PromiseImageCallbackContext> callbackContext(
2100 new PromiseImageCallbackContext(context));
2101
Robert Phillips33f02ed2018-03-27 08:06:57 -04002102 // DDL TODO: how can we tell if we need mipmapping!
Robert Phillipsa479f962018-04-10 11:45:40 -04002103 callbackContext->setBackendTexture(gpu->createTestingOnlyBackendTexture(
Robert Phillips33f02ed2018-03-27 08:06:57 -04002104 fImageInfo[i].fBitmap.getPixels(),
2105 fImageInfo[i].fBitmap.width(),
2106 fImageInfo[i].fBitmap.height(),
2107 fImageInfo[i].fBitmap.colorType(),
Robert Phillipsa479f962018-04-10 11:45:40 -04002108 false, GrMipMapped::kNo));
2109 // The GMs sometimes request too large an image
2110 //SkAssertResult(callbackContext->backendTexture().isValid());
Robert Phillips33f02ed2018-03-27 08:06:57 -04002111
Robert Phillipsa479f962018-04-10 11:45:40 -04002112 // The fImageInfo array gets the creation ref
2113 fImageInfo[i].fCallbackContext = std::move(callbackContext);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002114 }
2115 }
2116
2117 static void PromiseImageFulfillProc(void* textureContext, GrBackendTexture* outTexture) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002118 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2119 SkASSERT(callbackContext->backendTexture().isValid());
2120 *outTexture = callbackContext->backendTexture();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002121 }
2122
2123 static void PromiseImageReleaseProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002124#ifdef SK_DEBUG
2125 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2126 SkASSERT(callbackContext->backendTexture().isValid());
2127#endif
Robert Phillips33f02ed2018-03-27 08:06:57 -04002128 }
2129
2130 static void PromiseImageDoneProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002131 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2132 callbackContext->unref();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002133 }
2134
2135private:
2136 // returns -1 if not found
2137 int findImage(SkImage* image) const {
2138 for (int i = 0; i < fImageInfo.count(); ++i) {
2139 if (fImageInfo[i].fOriginalUniqueID == image->uniqueID()) {
2140 SkASSERT(fImageInfo[i].fIndex == i);
2141 SkASSERT(this->isValidID(i) && this->isValidID(fImageInfo[i].fIndex));
2142 return i;
2143 }
2144 }
2145 return -1;
2146 }
2147
2148 // returns -1 on failure
2149 int addImage(SkImage* image) {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002150 sk_sp<SkImage> rasterImage = image->makeRasterImage(); // force decoding of lazy images
2151
2152 SkImageInfo ii = SkImageInfo::Make(rasterImage->width(), rasterImage->height(),
2153 rasterImage->colorType(), rasterImage->alphaType(),
2154 rasterImage->refColorSpace());
2155
2156 SkBitmap bm;
2157 bm.allocPixels(ii);
2158
2159 if (!rasterImage->readPixels(bm.pixmap(), 0, 0)) {
2160 return -1;
2161 }
2162
2163 bm.setImmutable();
2164
2165 PromiseImageInfo newImageInfo;
2166 newImageInfo.fIndex = fImageInfo.count();
2167 newImageInfo.fOriginalUniqueID = image->uniqueID();
2168 newImageInfo.fBitmap = bm;
Robert Phillipsa479f962018-04-10 11:45:40 -04002169 /* fCallbackContext is filled in by uploadAllToGPU */
Robert Phillips33f02ed2018-03-27 08:06:57 -04002170
2171 fImageInfo.push_back(newImageInfo);
2172 SkASSERT(newImageInfo.fIndex == fImageInfo.count()-1);
2173 return fImageInfo.count()-1;
2174 }
2175
2176 SkTArray<PromiseImageInfo> fImageInfo;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002177};
2178
2179// TileData class encapsulates the information and behavior for a single tile/thread in
2180// a DDL rendering.
2181class ViaDDL::TileData {
2182public:
2183 // Note: we could just pass in surface characterization
2184 TileData(sk_sp<SkSurface> surf, const SkIRect& clip)
2185 : fSurface(std::move(surf))
2186 , fClip(clip) {
2187 SkAssertResult(fSurface->characterize(&fCharacterization));
2188 }
2189
2190 // This method operates in parallel
2191 // In each thread we will reconvert the compressedPictureData into an SkPicture
2192 // replacing each image-index with a promise image.
2193 void preprocess(SkData* compressedPictureData, const PromiseImageHelper& helper) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002194
Robert Phillips33f02ed2018-03-27 08:06:57 -04002195 SkDeferredDisplayListRecorder recorder(fCharacterization);
2196
2197 // DDL TODO: the DDLRecorder's GrContext isn't initialized until getCanvas is called.
2198 // Maybe set it up in the ctor?
2199 SkCanvas* subCanvas = recorder.getCanvas();
2200
2201 sk_sp<SkPicture> reconstitutedPicture;
2202
2203 {
Robert Phillipsa479f962018-04-10 11:45:40 -04002204 PerRecorderContext perRecorderContext { &recorder, &helper };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002205
2206 SkDeserialProcs procs;
Robert Phillipsa479f962018-04-10 11:45:40 -04002207 procs.fImageCtx = (void*) &perRecorderContext;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002208 procs.fImageProc = PromiseImageCreator;
2209
2210 reconstitutedPicture = SkPicture::MakeFromData(compressedPictureData, &procs);
2211 if (!reconstitutedPicture) {
2212 return;
2213 }
2214 }
2215
2216 subCanvas->clipRect(SkRect::MakeWH(fClip.width(), fClip.height()));
2217 subCanvas->translate(-fClip.fLeft, -fClip.fTop);
2218
2219 // Note: in this use case we only render a picture to the deferred canvas
2220 // but, more generally, clients will use arbitrary draw calls.
2221 subCanvas->drawPicture(reconstitutedPicture);
2222
2223 fDisplayList = recorder.detach();
2224 }
2225
2226 // This method operates serially and replays the recorded DDL into the tile surface.
2227 void draw() {
2228 fSurface->draw(fDisplayList.get());
2229 }
2230
2231 // This method also operates serially and composes the results of replaying the DDL into
2232 // the final destination surface.
2233 void compose(SkCanvas* dst) {
2234 sk_sp<SkImage> img = fSurface->makeImageSnapshot();
2235 dst->save();
2236 dst->clipRect(SkRect::Make(fClip));
2237 dst->drawImage(std::move(img), fClip.fLeft, fClip.fTop);
2238 dst->restore();
2239 }
2240
2241private:
Robert Phillipsa479f962018-04-10 11:45:40 -04002242 // This stack-based context allows each thread to re-inflate the image indices into
2243 // promise images while still using the same GrBackendTexture.
2244 struct PerRecorderContext {
2245 SkDeferredDisplayListRecorder* fRecorder;
2246 const PromiseImageHelper* fHelper;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002247 };
2248
2249 // This generates promise images to replace the indices in the compressed picture. This
Robert Phillipsa479f962018-04-10 11:45:40 -04002250 // reconstitution is performed separately in each thread so we end up with multiple
2251 // promise images referring to the same GrBackendTexture.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002252 static sk_sp<SkImage> PromiseImageCreator(const void* rawData, size_t length, void* ctxIn) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002253 PerRecorderContext* perRecorderContext = static_cast<PerRecorderContext*>(ctxIn);
2254 const PromiseImageHelper* helper = perRecorderContext->fHelper;
2255 SkDeferredDisplayListRecorder* recorder = perRecorderContext->fRecorder;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002256
2257 SkASSERT(length == sizeof(int));
2258
2259 const int* indexPtr = static_cast<const int*>(rawData);
2260 SkASSERT(helper->isValidID(*indexPtr));
2261
Robert Phillipsa479f962018-04-10 11:45:40 -04002262 const PromiseImageHelper::PromiseImageInfo& curImage = helper->getInfo(*indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002263
Robert Phillipsa479f962018-04-10 11:45:40 -04002264 if (!curImage.fCallbackContext->backendTexture().isValid()) {
2265 // We weren't able to make a backend texture for this SkImage
2266 return nullptr;
2267 }
2268 SkASSERT(curImage.fIndex == *indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002269
Robert Phillipsa479f962018-04-10 11:45:40 -04002270 GrBackendFormat backendFormat = curImage.fCallbackContext->backendTexture().format();
2271
2272 // Each DDL recorder gets its own ref on the promise callback context for the
2273 // promise images it creates.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002274 // DDL TODO: sort out mipmapping
2275 sk_sp<SkImage> image = recorder->makePromiseTexture(
Robert Phillipsa479f962018-04-10 11:45:40 -04002276 backendFormat,
2277 curImage.fBitmap.width(),
2278 curImage.fBitmap.height(),
2279 GrMipMapped::kNo,
2280 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
2281 curImage.fBitmap.colorType(),
2282 curImage.fBitmap.alphaType(),
2283 curImage.fBitmap.refColorSpace(),
2284 PromiseImageHelper::PromiseImageFulfillProc,
2285 PromiseImageHelper::PromiseImageReleaseProc,
2286 PromiseImageHelper::PromiseImageDoneProc,
2287 (void*) SkSafeRef(curImage.fCallbackContext.get()));
Robert Phillips33f02ed2018-03-27 08:06:57 -04002288 SkASSERT(image);
2289 return image;
2290 }
2291
2292 sk_sp<SkSurface> fSurface;
2293 SkIRect fClip; // in the device space of the dest canvas
2294 std::unique_ptr<SkDeferredDisplayList> fDisplayList;
2295 SkSurfaceCharacterization fCharacterization;
2296};
2297
2298Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2299 auto size = src.size();
2300 SkPictureRecorder recorder;
2301 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2302 SkIntToScalar(size.height())));
2303 if (!err.isEmpty()) {
2304 return err;
2305 }
2306 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
2307
2308 // this is our ultimate final drawing area/rect
2309 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
2310
2311 PromiseImageHelper helper;
2312 sk_sp<SkData> compressedPictureData;
2313
2314 // Convert the SkPicture into SkData replacing all the SkImages with an index.
2315 {
2316 SkSerialProcs procs;
2317
2318 procs.fImageCtx = &helper;
2319 procs.fImageProc = [](SkImage* image, void* ctx) -> sk_sp<SkData> {
2320 auto helper = static_cast<PromiseImageHelper*>(ctx);
2321
2322 int id = helper->findOrDefineImage(image);
2323 if (id >= 0) {
2324 SkASSERT(helper->isValidID(id));
2325 return SkData::MakeWithCopy(&id, sizeof(id));
2326 }
2327
2328 return nullptr;
2329 };
2330
2331 compressedPictureData = inputPicture->serialize(&procs);
2332 if (!compressedPictureData) {
2333 return SkStringPrintf("ViaDDL: Couldn't deflate SkPicture");
2334 }
2335 }
2336
Robert Phillips33f02ed2018-03-27 08:06:57 -04002337 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2338 [&](SkCanvas* canvas) -> Error {
2339 GrContext* context = canvas->getGrContext();
2340 if (!context || !context->contextPriv().getGpu()) {
2341 return SkStringPrintf("DDLs are GPU only");
2342 }
2343
Robert Phillipsa479f962018-04-10 11:45:40 -04002344 // This is here bc this is the first point where we have access to the context
Robert Phillips33f02ed2018-03-27 08:06:57 -04002345 helper.uploadAllToGPU(context);
2346
2347 int xTileSize = viewport.width()/fNumDivisions;
2348 int yTileSize = viewport.height()/fNumDivisions;
2349
2350 SkTArray<TileData> tileData;
2351 tileData.reserve(fNumDivisions*fNumDivisions);
2352
2353 // First, create the destination tiles
2354 for (int y = 0, yOff = 0; y < fNumDivisions; ++y, yOff += yTileSize) {
2355 int ySize = (y < fNumDivisions-1) ? yTileSize : viewport.height()-yOff;
2356
2357 for (int x = 0, xOff = 0; x < fNumDivisions; ++x, xOff += xTileSize) {
2358 int xSize = (x < fNumDivisions-1) ? xTileSize : viewport.width()-xOff;
2359
2360 SkIRect clip = SkIRect::MakeXYWH(xOff, yOff, xSize, ySize);
2361
2362 SkASSERT(viewport.contains(clip));
2363
2364 SkImageInfo tileII = SkImageInfo::MakeN32Premul(xSize, ySize);
2365
2366 tileData.push_back(TileData(canvas->makeSurface(tileII), clip));
2367 }
2368 }
2369
2370 // Second, run the cpu pre-processing in threads
2371 SkTaskGroup().batch(tileData.count(), [&](int i) {
2372 tileData[i].preprocess(compressedPictureData.get(), helper);
2373 });
2374
Robert Phillipsa479f962018-04-10 11:45:40 -04002375 // This drops the helper's refs on all the promise images
2376 helper.reset();
2377
Robert Phillips33f02ed2018-03-27 08:06:57 -04002378 // Third, synchronously render the display lists into the dest tiles
2379 // TODO: it would be cool to not wait until all the tiles are drawn to begin
2380 // drawing to the GPU and composing to the final surface
2381 for (int i = 0; i < tileData.count(); ++i) {
2382 tileData[i].draw();
2383 }
2384
2385 // Finally, compose the drawn tiles into the result
2386 // Note: the separation between the tiles and the final composition better
2387 // matches Chrome but costs us a copy
2388 for (int i = 0; i < tileData.count(); ++i) {
2389 tileData[i].compose(canvas);
2390 }
2391
Robert Phillipscc473352018-03-27 10:46:00 -04002392 context->flush();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002393 return "";
2394 });
2395}
2396
2397#else
2398
2399ViaDDL::ViaDDL(int numDivisions, Sink* sink) : Via(sink) { }
2400
2401Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2402 return "ViaDDL is GPU only";
2403}
2404
2405#endif
2406
2407/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2408
mtklein4a34ecb2016-01-08 10:19:35 -08002409Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2410 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002411 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtklein4a34ecb2016-01-08 10:19:35 -08002412 SkPictureRecorder recorder;
reedca2622b2016-03-18 07:25:55 -07002413 sk_sp<SkPicture> pic;
mtklein4a34ecb2016-01-08 10:19:35 -08002414 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2415 SkIntToScalar(size.height())));
2416 if (!err.isEmpty()) {
2417 return err;
2418 }
reedca2622b2016-03-18 07:25:55 -07002419 pic = recorder.finishRecordingAsPicture();
mtklein4a34ecb2016-01-08 10:19:35 -08002420 canvas->drawPicture(pic);
Ben Wagner1861e882018-04-04 17:40:46 -04002421 return err;
mtklein4a34ecb2016-01-08 10:19:35 -08002422 });
Ben Wagner1861e882018-04-04 17:40:46 -04002423 if (!err.isEmpty()) {
2424 return err;
2425 }
2426
2427 return check_against_reference(bitmap, src, fSink.get());
mtklein4a34ecb2016-01-08 10:19:35 -08002428}
2429
2430/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2431
reed54dc4872016-09-13 08:09:45 -07002432Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2433 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002434 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
reed54dc4872016-09-13 08:09:45 -07002435 SkDynamicMemoryWStream tmpStream;
2436 Error err = src.draw(SkPipeSerializer().beginWrite(SkRect::Make(size), &tmpStream));
2437 if (!err.isEmpty()) {
2438 return err;
2439 }
2440 sk_sp<SkData> data = tmpStream.detachAsData();
2441 SkPipeDeserializer().playback(data->data(), data->size(), canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002442 return err;
reed54dc4872016-09-13 08:09:45 -07002443 });
Ben Wagner1861e882018-04-04 17:40:46 -04002444 if (!err.isEmpty()) {
2445 return err;
2446 }
2447
2448 return check_against_reference(bitmap, src, fSink.get());
reed54dc4872016-09-13 08:09:45 -07002449}
2450
2451/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2452
Mike Reedbae888e2017-02-18 16:50:45 -05002453#ifdef TEST_VIA_SVG
Mike Reedf67c4592017-02-17 17:06:11 -05002454#include "SkXMLWriter.h"
2455#include "SkSVGCanvas.h"
2456#include "SkSVGDOM.h"
2457
2458Error ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2459 auto size = src.size();
2460 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
2461 SkDynamicMemoryWStream wstream;
2462 SkXMLStreamWriter writer(&wstream);
2463 Error err = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
2464 if (!err.isEmpty()) {
2465 return err;
2466 }
2467 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2468 auto dom = SkSVGDOM::MakeFromStream(*rstream);
2469 if (dom) {
2470 dom->setContainerSize(SkSize::Make(size));
2471 dom->render(canvas);
2472 }
2473 return "";
2474 });
2475}
Mike Reedbae888e2017-02-18 16:50:45 -05002476#endif
Mike Reedf67c4592017-02-17 17:06:11 -05002477
2478/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2479
mtklein9c5052f2016-08-06 12:51:51 -07002480Error ViaLite::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2481 auto size = src.size();
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002482 SkIRect bounds = {0,0, size.width(), size.height()};
Ben Wagner1861e882018-04-04 17:40:46 -04002483 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002484 SkLiteDL dl;
mtklein8bbbb692016-08-15 12:56:00 -07002485 SkLiteRecorder rec;
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002486 rec.reset(&dl, bounds);
mtklein8bbbb692016-08-15 12:56:00 -07002487
2488 Error err = src.draw(&rec);
mtklein9c5052f2016-08-06 12:51:51 -07002489 if (!err.isEmpty()) {
2490 return err;
2491 }
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002492 dl.draw(canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002493 return err;
mtklein9c5052f2016-08-06 12:51:51 -07002494 });
Ben Wagner1861e882018-04-04 17:40:46 -04002495 if (!err.isEmpty()) {
2496 return err;
2497 }
2498
2499 return check_against_reference(bitmap, src, fSink.get());
mtklein9c5052f2016-08-06 12:51:51 -07002500}
2501
Mike Klein841101d2017-03-10 09:55:51 -05002502/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2503
Mike Klein919cc452017-03-18 15:36:52 +00002504ViaCSXform::ViaCSXform(Sink* sink, sk_sp<SkColorSpace> cs, bool colorSpin)
2505 : Via(sink)
2506 , fCS(std::move(cs))
2507 , fColorSpin(colorSpin) {}
Mike Klein841101d2017-03-10 09:55:51 -05002508
2509Error ViaCSXform::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2510 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
2511 [&](SkCanvas* canvas) -> Error {
Brian Osman5b7e4702017-10-31 16:41:29 -04002512 {
2513 SkAutoCanvasRestore acr(canvas, true);
2514 auto proxy = SkCreateColorSpaceXformCanvas(canvas, fCS);
2515 Error err = src.draw(proxy.get());
2516 if (!err.isEmpty()) {
2517 return err;
2518 }
Mike Klein919cc452017-03-18 15:36:52 +00002519 }
2520
2521 // Undo the color spin, so we can look at the pixels in Gold.
2522 if (fColorSpin) {
2523 SkBitmap pixels;
2524 pixels.allocPixels(canvas->imageInfo());
Mike Reed12e946b2017-04-17 10:53:29 -04002525 canvas->readPixels(pixels, 0, 0);
Mike Klein919cc452017-03-18 15:36:52 +00002526
Brian Osman5b7e4702017-10-31 16:41:29 -04002527 SkPaint rotateColors;
2528 SkScalar matrix[20] = { 0, 0, 1, 0, 0, // B -> R
2529 1, 0, 0, 0, 0, // R -> G
2530 0, 1, 0, 0, 0, // G -> B
2531 0, 0, 0, 1, 0 };
2532 rotateColors.setBlendMode(SkBlendMode::kSrc);
2533 rotateColors.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(matrix));
2534 canvas->drawBitmap(pixels, 0, 0, &rotateColors);
Mike Klein919cc452017-03-18 15:36:52 +00002535 }
2536
2537 return "";
Mike Klein841101d2017-03-10 09:55:51 -05002538 });
2539}
2540
mtklein748ca3b2015-01-15 10:56:12 -08002541} // namespace DM