blob: bab344b1e56b3f9675b23c5c4c2adaf7d5d15d8a [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);
Yuqian Licb312482018-04-27 15:52:40 -0400421 canvas->flush();
msarettb1be46b2016-05-17 08:52:11 -0700422}
423
Matt Sarettf485cf92017-05-26 08:58:03 -0400424// For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
425// color format conversions should be performed by the codec. Sometimes the output of the
426// decode will be in an interesting color space. On our srgb and f16 backends, we need to
427// "pretend" that the color space is standard sRGB to avoid triggering color conversion
428// at draw time.
429static void set_bitmap_color_space(SkImageInfo* info) {
430 if (kRGBA_F16_SkColorType == info->colorType()) {
431 *info = info->makeColorSpace(SkColorSpace::MakeSRGBLinear());
432 } else {
433 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
434 }
435}
436
mtkleine0effd62015-07-29 06:37:28 -0700437Error CodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700438 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800439 if (!encoded) {
440 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
441 }
msarettb714fb02016-01-22 14:46:42 -0800442
Mike Reedede7bac2017-07-23 15:30:02 -0400443 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700444 if (nullptr == codec.get()) {
445 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700446 }
447
scroggoba584892016-05-20 13:56:13 -0700448 SkImageInfo decodeInfo = codec->getInfo();
449 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
450 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800451 return Error::Nonfatal("Skipping uninteresting test.");
msarett438b2ad2015-04-09 12:43:10 -0700452 }
453
msarett0a242972015-06-11 14:27:27 -0700454 // Try to scale the image if it is desired
455 SkISize size = codec->getScaledDimensions(fScale);
456 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
457 return Error::Nonfatal("Test without scaling is uninteresting.");
458 }
msarettb32758a2015-08-18 13:22:46 -0700459
460 // Visually inspecting very small output images is not necessary. We will
461 // cover these cases in unit testing.
462 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
463 return Error::Nonfatal("Scaling very small images is uninteresting.");
464 }
msarett0a242972015-06-11 14:27:27 -0700465 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
466
Mike Reed7fcfb622018-02-09 13:26:46 -0500467 const int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700468 const size_t rowBytes = size.width() * bpp;
Mike Reedf0ffb892017-10-03 14:47:21 -0400469 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
scroggo19b91532016-10-24 09:03:26 -0700470 SkAutoMalloc pixels(safeSize);
msarett438b2ad2015-04-09 12:43:10 -0700471
msarettbb25b532016-01-13 09:31:39 -0800472 SkCodec::Options options;
Matt Saretta40d9c82017-05-19 15:21:05 -0400473 options.fPremulBehavior = canvas->imageInfo().colorSpace() ?
474 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
msarettbb25b532016-01-13 09:31:39 -0800475 if (kCodecZeroInit_Mode == fMode) {
msarettb1be46b2016-05-17 08:52:11 -0700476 memset(pixels.get(), 0, size.height() * rowBytes);
msarettbb25b532016-01-13 09:31:39 -0800477 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
478 }
msarett34e0ec42016-04-22 16:27:24 -0700479
480 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400481 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700482 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
483 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
484 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
485 }
scroggo9b77ddd2015-03-19 06:03:39 -0700486
scroggo9c59ebc2015-03-25 13:48:49 -0700487 switch (fMode) {
scroggo19b91532016-10-24 09:03:26 -0700488 case kAnimated_Mode: {
489 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
490 if (frameInfos.size() <= 1) {
491 return SkStringPrintf("%s is not an animated image.", fPath.c_str());
492 }
493
scroggo90e971a2016-10-25 06:11:01 -0700494 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
495 // into. "factor" is the number of frames to draw on one row. There will be
496 // up to "factor" rows as well.
497 const float root = sqrt((float) frameInfos.size());
498 const int factor = sk_float_ceil2int(root);
499
scroggo19b91532016-10-24 09:03:26 -0700500 // Used to cache a frame that future frames will depend on.
501 SkAutoMalloc priorFramePixels;
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400502 int cachedFrame = SkCodec::kNone;
503 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
scroggo19b91532016-10-24 09:03:26 -0700504 options.fFrameIndex = i;
505 // Check for a prior frame
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400506 const int reqFrame = frameInfos[i].fRequiredFrame;
scroggo19b91532016-10-24 09:03:26 -0700507 if (reqFrame != SkCodec::kNone && reqFrame == cachedFrame
508 && priorFramePixels.get()) {
509 // Copy into pixels
510 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400511 options.fPriorFrame = reqFrame;
scroggo19b91532016-10-24 09:03:26 -0700512 } else {
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400513 options.fPriorFrame = SkCodec::kNone;
scroggo19b91532016-10-24 09:03:26 -0700514 }
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500515 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
Leon Scroggins571b30f2017-07-11 17:35:31 +0000516 rowBytes, &options);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500517 if (SkCodec::kInvalidInput == result && i > 0) {
518 // Some of our test images have truncated later frames. Treat that
519 // the same as incomplete.
520 result = SkCodec::kIncompleteInput;
521 }
scroggo19b91532016-10-24 09:03:26 -0700522 switch (result) {
523 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400524 case SkCodec::kErrorInInput:
scroggo90e971a2016-10-25 06:11:01 -0700525 case SkCodec::kIncompleteInput: {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400526 // If the next frame depends on this one, store it in priorFrame.
527 // It is possible that we may discard a frame that future frames depend on,
528 // but the codec will simply redecode the discarded frame.
529 // Do this before calling draw_to_canvas, which premultiplies in place. If
530 // we're decoding to unpremul, we want to pass the unmodified frame to the
531 // codec for decoding the next frame.
532 if (static_cast<size_t>(i+1) < frameInfos.size()
533 && frameInfos[i+1].fRequiredFrame == i) {
534 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
535 cachedFrame = i;
536 }
537
scroggo90e971a2016-10-25 06:11:01 -0700538 SkAutoCanvasRestore acr(canvas, true);
539 const int xTranslate = (i % factor) * decodeInfo.width();
540 const int yTranslate = (i / factor) * decodeInfo.height();
541 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
Leon Scroggins571b30f2017-07-11 17:35:31 +0000542 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Leon Scroggins III674a1842017-07-06 12:26:09 -0400543 if (result != SkCodec::kSuccess) {
scroggo19b91532016-10-24 09:03:26 -0700544 return "";
545 }
546 break;
scroggo90e971a2016-10-25 06:11:01 -0700547 }
scroggo53f63b62016-10-27 08:29:13 -0700548 case SkCodec::kInvalidConversion:
Mike Reed304a07c2017-07-12 15:10:28 -0400549 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
scroggo53f63b62016-10-27 08:29:13 -0700550 return Error::Nonfatal(SkStringPrintf(
Mike Reed304a07c2017-07-12 15:10:28 -0400551 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str()));
scroggo53f63b62016-10-27 08:29:13 -0700552 }
553 // Fall through.
scroggo19b91532016-10-24 09:03:26 -0700554 default:
555 return SkStringPrintf("Couldn't getPixels for frame %i in %s.",
556 i, fPath.c_str());
557 }
scroggo19b91532016-10-24 09:03:26 -0700558 }
559 break;
560 }
msarettbb25b532016-01-13 09:31:39 -0800561 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700562 case kCodec_Mode: {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000563 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggoeb602a52015-07-09 08:16:03 -0700564 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400565 // We consider these to be valid, since we should still decode what is
scroggo9c59ebc2015-03-25 13:48:49 -0700566 // available.
Leon Scroggins III674a1842017-07-06 12:26:09 -0400567 case SkCodec::kErrorInInput:
scroggoeb602a52015-07-09 08:16:03 -0700568 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700569 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700570 default:
571 // Everything else is considered a failure.
572 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
573 }
msarettb1be46b2016-05-17 08:52:11 -0700574
Leon Scroggins571b30f2017-07-11 17:35:31 +0000575 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggo9c59ebc2015-03-25 13:48:49 -0700576 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700577 }
scroggo9c59ebc2015-03-25 13:48:49 -0700578 case kScanline_Mode: {
scroggod8d68552016-06-06 11:26:17 -0700579 void* dst = pixels.get();
580 uint32_t height = decodeInfo.height();
scroggo19b91532016-10-24 09:03:26 -0700581 const bool useIncremental = [this]() {
582 auto exts = { "png", "PNG", "gif", "GIF" };
583 for (auto ext : exts) {
584 if (fPath.endsWith(ext)) {
585 return true;
586 }
587 }
588 return false;
589 }();
590 // ico may use the old scanline method or the new one, depending on whether it
591 // internally holds a bmp or a png.
scroggo8e6c7ad2016-09-16 08:20:38 -0700592 const bool ico = fPath.endsWith("ico");
scroggo19b91532016-10-24 09:03:26 -0700593 bool useOldScanlineMethod = !useIncremental && !ico;
594 if (useIncremental || ico) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700595 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000596 rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700597 int rowsDecoded;
Leon Scroggins III674a1842017-07-06 12:26:09 -0400598 auto result = codec->incrementalDecode(&rowsDecoded);
599 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700600 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
601 SkCodec::kNo_ZeroInitialized, height,
602 rowsDecoded);
scroggo6fb23912016-06-02 14:16:43 -0700603 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700604 } else {
scroggo19b91532016-10-24 09:03:26 -0700605 if (useIncremental) {
606 // Error: These should support incremental decode.
scroggo8e6c7ad2016-09-16 08:20:38 -0700607 return "Could not start incremental decode";
608 }
609 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
610 // which should work via startScanlineDecode
611 useOldScanlineMethod = true;
612 }
613 }
614
615 if (useOldScanlineMethod) {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000616 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700617 return "Could not start scanline decoder";
618 }
619
Brian Osmanea176c62018-04-06 15:28:23 -0400620 // We do not need to check the return value. On an incomplete
621 // image, memory will be filled with a default value.
622 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700623 }
624
Leon Scroggins571b30f2017-07-11 17:35:31 +0000625 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer97002062015-05-27 12:36:10 -0700626 break;
627 }
msarett0a242972015-06-11 14:27:27 -0700628 case kStripe_Mode: {
629 const int height = decodeInfo.height();
630 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
631 // does not align with image blocks.
632 const int stripeHeight = 37;
633 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
msarettb1be46b2016-05-17 08:52:11 -0700634 void* dst = pixels.get();
msarett0a242972015-06-11 14:27:27 -0700635
636 // Decode odd stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000637 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarettb65e6042016-02-23 05:37:25 -0800638 return "Could not start scanline decoder";
639 }
640
641 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
642 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
643 // to run this test for image types that do not have this scanline ordering.
scroggo12e2f502016-05-16 09:04:18 -0700644 // We only run this on Jpeg, which is always kTopDown.
645 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
msarette6dd0042015-10-09 11:07:34 -0700646
msarett0a242972015-06-11 14:27:27 -0700647 for (int i = 0; i < numStripes; i += 2) {
648 // Skip a stripe
649 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700650 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700651
652 // Read a stripe
653 const int startY = (i + 1) * stripeHeight;
654 const int linesToRead = SkTMin(stripeHeight, height - startY);
655 if (linesToRead > 0) {
msarettb1be46b2016-05-17 08:52:11 -0700656 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
657 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700658 }
659 }
660
661 // Decode even stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000662 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
scroggo1c005e42015-08-04 09:24:45 -0700663 if (SkCodec::kSuccess != startResult) {
664 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700665 }
666 for (int i = 0; i < numStripes; i += 2) {
667 // Read a stripe
668 const int startY = i * stripeHeight;
669 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarettb1be46b2016-05-17 08:52:11 -0700670 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
671 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700672
673 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700674 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
675 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700676 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700677 }
678 }
msarettb1be46b2016-05-17 08:52:11 -0700679
Leon Scroggins571b30f2017-07-11 17:35:31 +0000680 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700681 break;
msarett0a242972015-06-11 14:27:27 -0700682 }
msarett91c22b22016-02-22 12:27:46 -0800683 case kCroppedScanline_Mode: {
684 const int width = decodeInfo.width();
685 const int height = decodeInfo.height();
686 // This value is chosen because, as we move across the image, it will sometimes
687 // align with the jpeg block sizes and it will sometimes not. This allows us
688 // to test interestingly different code paths in the implementation.
689 const int tileSize = 36;
msarett91c22b22016-02-22 12:27:46 -0800690 SkIRect subset;
691 for (int x = 0; x < width; x += tileSize) {
692 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
Matt Saretta40d9c82017-05-19 15:21:05 -0400693 options.fSubset = &subset;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000694 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarett91c22b22016-02-22 12:27:46 -0800695 return "Could not start scanline decoder.";
696 }
697
msarettb1be46b2016-05-17 08:52:11 -0700698 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
msarett91c22b22016-02-22 12:27:46 -0800699 }
700
Leon Scroggins571b30f2017-07-11 17:35:31 +0000701 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
msarett91c22b22016-02-22 12:27:46 -0800702 break;
703 }
scroggob636b452015-07-22 07:16:20 -0700704 case kSubset_Mode: {
705 // Arbitrarily choose a divisor.
706 int divisor = 2;
707 // Total width/height of the image.
708 const int W = codec->getInfo().width();
709 const int H = codec->getInfo().height();
710 if (divisor > W || divisor > H) {
711 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
712 "for %s with dimensions (%d x %d)", divisor,
713 fPath.c_str(), W, H));
714 }
715 // subset dimensions
716 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
717 const int w = SkAlign2(W / divisor);
718 const int h = SkAlign2(H / divisor);
719 SkIRect subset;
Matt Saretta40d9c82017-05-19 15:21:05 -0400720 options.fSubset = &subset;
scroggob636b452015-07-22 07:16:20 -0700721 SkBitmap subsetBm;
722 // We will reuse pixel memory from bitmap.
msarettb1be46b2016-05-17 08:52:11 -0700723 void* dst = pixels.get();
scroggob636b452015-07-22 07:16:20 -0700724 // Keep track of left and top (for drawing subsetBm into canvas). We could use
725 // fScale * x and fScale * y, but we want integers such that the next subset will start
726 // where the last one ended. So we'll add decodeInfo.width() and height().
727 int left = 0;
728 for (int x = 0; x < W; x += w) {
729 int top = 0;
730 for (int y = 0; y < H; y+= h) {
731 // Do not make the subset go off the edge of the image.
732 const int preScaleW = SkTMin(w, W - x);
733 const int preScaleH = SkTMin(h, H - y);
734 subset.setXYWH(x, y, preScaleW, preScaleH);
735 // And scale
736 // FIXME: Should we have a version of getScaledDimensions that takes a subset
737 // into account?
msarettc7eb4902016-04-25 07:04:58 -0700738 const int scaledW = SkTMax(1, SkScalarRoundToInt(preScaleW * fScale));
739 const int scaledH = SkTMax(1, SkScalarRoundToInt(preScaleH * fScale));
740 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
741 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
msarettb1be46b2016-05-17 08:52:11 -0700742 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
743 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000744 &options);
scroggob636b452015-07-22 07:16:20 -0700745 switch (result) {
746 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400747 case SkCodec::kErrorInInput:
scroggob636b452015-07-22 07:16:20 -0700748 case SkCodec::kIncompleteInput:
749 break;
scroggob636b452015-07-22 07:16:20 -0700750 default:
751 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
752 "from %s with dimensions (%d x %d)\t error %d",
753 x, y, decodeInfo.width(), decodeInfo.height(),
754 fPath.c_str(), W, H, result);
755 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000756 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
757 SkIntToScalar(left), SkIntToScalar(top));
msarettb1be46b2016-05-17 08:52:11 -0700758
scroggob636b452015-07-22 07:16:20 -0700759 // translate by the scaled height.
760 top += decodeInfo.height();
761 }
762 // translate by the scaled width.
763 left += decodeInfo.width();
764 }
765 return "";
766 }
msarettb714fb02016-01-22 14:46:42 -0800767 default:
768 SkASSERT(false);
769 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700770 }
scroggo9c59ebc2015-03-25 13:48:49 -0700771 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700772}
773
774SkISize CodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700775 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400776 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700777 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400778 return {0, 0};
scroggo7fac5af2015-09-30 11:33:12 -0700779 }
scroggo19b91532016-10-24 09:03:26 -0700780
781 auto imageSize = codec->getScaledDimensions(fScale);
782 if (fMode == kAnimated_Mode) {
scroggo90e971a2016-10-25 06:11:01 -0700783 // We'll draw one of each frame, so make it big enough to hold them all
784 // in a grid. The grid will be roughly square, with "factor" frames per
785 // row and up to "factor" rows.
scroggo19b91532016-10-24 09:03:26 -0700786 const size_t count = codec->getFrameInfo().size();
scroggo90e971a2016-10-25 06:11:01 -0700787 const float root = sqrt((float) count);
788 const int factor = sk_float_ceil2int(root);
789 imageSize.fWidth = imageSize.fWidth * factor;
790 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
scroggo19b91532016-10-24 09:03:26 -0700791 }
792 return imageSize;
scroggo9b77ddd2015-03-19 06:03:39 -0700793}
794
795Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700796 if (1.0f == fScale) {
scroggo6e8c68e2016-10-24 13:48:49 -0700797 Name name = SkOSPath::Basename(fPath.c_str());
798 if (fMode == kAnimated_Mode) {
799 name.append("_animated");
800 }
801 return name;
msarett0a242972015-06-11 14:27:27 -0700802 }
scroggo6e8c68e2016-10-24 13:48:49 -0700803 SkASSERT(fMode != kAnimated_Mode);
msaretta5783ae2015-09-08 15:35:32 -0700804 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700805}
806
807/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
808
scroggof8dc9df2016-05-16 09:04:13 -0700809AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800810 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700811 : fPath(path)
msarett3d9d7a72015-10-21 10:27:10 -0700812 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800813 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700814 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800815 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700816{}
817
818bool AndroidCodecSrc::veto(SinkFlags flags) const {
819 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700820 return flags.type != SinkFlags::kRaster
821 || flags.approach != SinkFlags::kDirect;
822}
823
824Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400825 if (canvas->imageInfo().colorSpace() &&
826 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
827 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
828 // run these tests on legacy canvases.
829 // We allow an exception for F16, since Android uses F16.
830 return Error::Nonfatal("Skip testing to color correct canvas.");
831 }
832
bungeman38d909e2016-08-02 14:40:46 -0700833 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700834 if (!encoded) {
835 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
836 }
Mike Reedede7bac2017-07-23 15:30:02 -0400837 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
838 if (nullptr == codec) {
msarett3d9d7a72015-10-21 10:27:10 -0700839 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
840 }
841
scroggoba584892016-05-20 13:56:13 -0700842 SkImageInfo decodeInfo = codec->getInfo();
843 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
844 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800845 return Error::Nonfatal("Skipping uninteresting test.");
msarett3d9d7a72015-10-21 10:27:10 -0700846 }
847
848 // Scale the image if it is desired.
849 SkISize size = codec->getSampledDimensions(fSampleSize);
850
851 // Visually inspecting very small output images is not necessary. We will
852 // cover these cases in unit testing.
853 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
854 return Error::Nonfatal("Scaling very small images is uninteresting.");
855 }
856 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
857
Mike Reed7fcfb622018-02-09 13:26:46 -0500858 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700859 size_t rowBytes = size.width() * bpp;
860 SkAutoMalloc pixels(size.height() * rowBytes);
msarett3d9d7a72015-10-21 10:27:10 -0700861
862 SkBitmap bitmap;
msarett34e0ec42016-04-22 16:27:24 -0700863 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400864 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700865 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
866 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
867 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
868 }
msarett3d9d7a72015-10-21 10:27:10 -0700869
870 // Create options for the codec.
871 SkAndroidCodec::AndroidOptions options;
msarett3d9d7a72015-10-21 10:27:10 -0700872 options.fSampleSize = fSampleSize;
873
msarettb1be46b2016-05-17 08:52:11 -0700874 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggof8dc9df2016-05-16 09:04:13 -0700875 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400876 case SkCodec::kErrorInInput:
scroggof8dc9df2016-05-16 09:04:13 -0700877 case SkCodec::kIncompleteInput:
878 break;
msarett3d9d7a72015-10-21 10:27:10 -0700879 default:
scroggof8dc9df2016-05-16 09:04:13 -0700880 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700881 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000882 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggof8dc9df2016-05-16 09:04:13 -0700883 return "";
msarett3d9d7a72015-10-21 10:27:10 -0700884}
885
886SkISize AndroidCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700887 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400888 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
msarett3d9d7a72015-10-21 10:27:10 -0700889 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400890 return {0, 0};
msarett3d9d7a72015-10-21 10:27:10 -0700891 }
892 return codec->getSampledDimensions(fSampleSize);
893}
894
895Name AndroidCodecSrc::name() const {
896 // We will replicate the names used by CodecSrc so that images can
897 // be compared in Gold.
898 if (1 == fSampleSize) {
899 return SkOSPath::Basename(fPath.c_str());
900 }
msarett4b0778e2015-11-13 09:59:11 -0800901 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700902}
903
904/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
905
msarett18976312016-03-09 14:20:58 -0800906ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
907 : fPath(path)
908 , fMode(mode)
909 , fDstAlphaType(alphaType)
910 , fIsGpu(isGpu)
911 , fRunSerially(serial_from_path_name(path))
912{}
913
914bool ImageGenSrc::veto(SinkFlags flags) const {
915 if (fIsGpu) {
Brian Salomonbd7c5512017-03-07 09:08:36 -0500916 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
917 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
918 flags.multisampled == SinkFlags::kMultisampled;
msarett18976312016-03-09 14:20:58 -0800919 }
920
921 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
922}
923
924Error ImageGenSrc::draw(SkCanvas* canvas) const {
925 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
926 return Error::Nonfatal("Uninteresting to test image generator to 565.");
927 }
928
bungeman38d909e2016-08-02 14:40:46 -0700929 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett18976312016-03-09 14:20:58 -0800930 if (!encoded) {
931 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
932 }
933
msarettfc0b6d12016-03-17 13:50:17 -0700934#if defined(SK_BUILD_FOR_WIN)
935 // Initialize COM in order to test with WIC.
936 SkAutoCoInitialize com;
937 if (!com.succeeded()) {
938 return "Could not initialize COM.";
939 }
940#endif
941
Ben Wagner145dbcd2016-11-03 14:40:50 -0400942 std::unique_ptr<SkImageGenerator> gen(nullptr);
msarett18976312016-03-09 14:20:58 -0800943 switch (fMode) {
944 case kCodec_Mode:
Mike Reed185130c2017-02-15 15:14:16 -0500945 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
msarett18976312016-03-09 14:20:58 -0800946 if (!gen) {
947 return "Could not create codec image generator.";
948 }
949 break;
msarettfc0b6d12016-03-17 13:50:17 -0700950 case kPlatform_Mode: {
msarett18976312016-03-09 14:20:58 -0800951#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
Leon Scroggins III0cbc10f2017-10-30 09:07:53 -0400952 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700953#elif defined(SK_BUILD_FOR_WIN)
bungeman38d909e2016-08-02 14:40:46 -0700954 gen.reset(SkImageGeneratorWIC::NewFromEncodedWIC(encoded.get()));
msarettfc0b6d12016-03-17 13:50:17 -0700955#endif
956
msarett18976312016-03-09 14:20:58 -0800957 if (!gen) {
msarettfc0b6d12016-03-17 13:50:17 -0700958 return "Could not create platform image generator.";
msarett18976312016-03-09 14:20:58 -0800959 }
960 break;
msarettfc0b6d12016-03-17 13:50:17 -0700961 }
msarett18976312016-03-09 14:20:58 -0800962 default:
963 SkASSERT(false);
964 return "Invalid image generator mode";
965 }
966
967 // Test deferred decoding path on GPU
968 if (fIsGpu) {
Mike Reed185130c2017-02-15 15:14:16 -0500969 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
msarett18976312016-03-09 14:20:58 -0800970 if (!image) {
971 return "Could not create image from codec image generator.";
972 }
973 canvas->drawImage(image, 0, 0);
974 return "";
975 }
mtklein343a63d2016-03-22 11:46:53 -0700976
msarett18976312016-03-09 14:20:58 -0800977 // Test various color and alpha types on CPU
978 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
mtklein343a63d2016-03-22 11:46:53 -0700979
Matt Saretta40d9c82017-05-19 15:21:05 -0400980 SkImageGenerator::Options options;
981 options.fBehavior = canvas->imageInfo().colorSpace() ?
982 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
983
Mike Reed7fcfb622018-02-09 13:26:46 -0500984 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700985 size_t rowBytes = decodeInfo.width() * bpp;
986 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
Matt Saretta40d9c82017-05-19 15:21:05 -0400987 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
Matt Sarett05cb4c32017-03-02 12:07:46 -0500988 SkString err =
989 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
990
991#if defined(SK_BUILD_FOR_WIN)
992 if (kPlatform_Mode == fMode) {
993 // Do not issue a fatal error for WIC flakiness.
994 return Error::Nonfatal(err);
995 }
996#endif
997
998 return err;
msarett18976312016-03-09 14:20:58 -0800999 }
1000
Matt Sarettf485cf92017-05-26 08:58:03 -04001001 set_bitmap_color_space(&decodeInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +00001002 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
msarettb1be46b2016-05-17 08:52:11 -07001003 CodecSrc::kGetFromCanvas_DstColorType);
msarett18976312016-03-09 14:20:58 -08001004 return "";
1005}
1006
1007SkISize ImageGenSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001008 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001009 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett18976312016-03-09 14:20:58 -08001010 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001011 return {0, 0};
msarett18976312016-03-09 14:20:58 -08001012 }
1013 return codec->getInfo().dimensions();
1014}
1015
1016Name ImageGenSrc::name() const {
1017 return SkOSPath::Basename(fPath.c_str());
1018}
1019
1020/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1021
msarett9ce3a542016-07-15 13:54:38 -07001022ColorCodecSrc::ColorCodecSrc(Path path, Mode mode, SkColorType colorType)
msarett69deca82016-04-29 09:38:40 -07001023 : fPath(path)
1024 , fMode(mode)
msarett9ce3a542016-07-15 13:54:38 -07001025 , fColorType(colorType)
msarett69deca82016-04-29 09:38:40 -07001026{}
1027
1028bool ColorCodecSrc::veto(SinkFlags flags) const {
1029 // Test to direct raster backends (8888 and 565).
1030 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1031}
1032
Matt Sarett6a0feba2017-06-09 10:45:44 -04001033void clamp_if_necessary(const SkBitmap& bitmap, SkColorType dstCT) {
1034 if (kRGBA_F16_SkColorType != bitmap.colorType() || kRGBA_F16_SkColorType == dstCT) {
1035 // No need to clamp if the dst is F16. We will clamp when we encode to PNG.
1036 return;
1037 }
1038
Mike Klein45c16fa2017-07-18 18:15:13 -04001039 SkJumper_MemoryCtx ptr = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
1040
Matt Sarett6a0feba2017-06-09 10:45:44 -04001041 SkRasterPipeline_<256> p;
1042 p.append(SkRasterPipeline::load_f16, &ptr);
1043 p.append(SkRasterPipeline::clamp_0);
1044 if (kPremul_SkAlphaType == bitmap.alphaType()) {
1045 p.append(SkRasterPipeline::clamp_a);
1046 } else {
1047 p.append(SkRasterPipeline::clamp_1);
1048 }
1049 p.append(SkRasterPipeline::store_f16, &ptr);
1050
Mike Klein45c16fa2017-07-18 18:15:13 -04001051 p.run(0,0, bitmap.width(), bitmap.height());
Matt Sarett6a0feba2017-06-09 10:45:44 -04001052}
1053
msarett69deca82016-04-29 09:38:40 -07001054Error ColorCodecSrc::draw(SkCanvas* canvas) const {
1055 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
1056 return Error::Nonfatal("No need to test color correction to 565 backend.");
1057 }
1058
msarettd1ec89b2016-08-03 12:59:27 -07001059 bool runInLegacyMode = kBaseline_Mode == fMode;
msarettd1ec89b2016-08-03 12:59:27 -07001060 if (runInLegacyMode && canvas->imageInfo().colorSpace()) {
1061 return Error::Nonfatal("Skipping tests that are only interesting in legacy mode.");
1062 } else if (!runInLegacyMode && !canvas->imageInfo().colorSpace()) {
1063 return Error::Nonfatal("Skipping tests that are only interesting in srgb mode.");
msarett9ce3a542016-07-15 13:54:38 -07001064 }
1065
bungeman38d909e2016-08-02 14:40:46 -07001066 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett69deca82016-04-29 09:38:40 -07001067 if (!encoded) {
1068 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1069 }
1070
Mike Reedede7bac2017-07-23 15:30:02 -04001071 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1072 if (nullptr == codec) {
msarett69deca82016-04-29 09:38:40 -07001073 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
1074 }
1075
msarett9876ac52016-06-01 14:47:18 -07001076 // Load the dst ICC profile. This particular dst is fairly similar to Adobe RGB.
Mike Reed0933bc92017-12-09 01:27:41 +00001077 sk_sp<SkData> dstData = GetResourceAsData("icc_profiles/HP_ZR30w.icc");
msarett9876ac52016-06-01 14:47:18 -07001078 if (!dstData) {
1079 return "Cannot read monitor profile. Is the resource path set correctly?";
1080 }
1081
msarett50ce1f22016-07-29 06:23:33 -07001082 sk_sp<SkColorSpace> dstSpace = nullptr;
1083 if (kDst_sRGB_Mode == fMode) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -05001084 dstSpace = SkColorSpace::MakeSRGB();
msarett50ce1f22016-07-29 06:23:33 -07001085 } else if (kDst_HPZR30w_Mode == fMode) {
Brian Osman526972e2016-10-24 09:24:02 -04001086 dstSpace = SkColorSpace::MakeICC(dstData->data(), dstData->size());
msarett50ce1f22016-07-29 06:23:33 -07001087 }
1088
1089 SkImageInfo decodeInfo = codec->getInfo().makeColorType(fColorType).makeColorSpace(dstSpace);
msarettd1ec89b2016-08-03 12:59:27 -07001090 if (kUnpremul_SkAlphaType == decodeInfo.alphaType()) {
1091 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
1092 }
msarett2ecc35f2016-09-08 11:55:16 -07001093 if (kRGBA_F16_SkColorType == fColorType) {
Brian Osman36703d92017-12-12 14:09:31 -05001094 decodeInfo = decodeInfo.makeColorSpace(decodeInfo.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001095 }
msarettd1ec89b2016-08-03 12:59:27 -07001096
msarett50ce1f22016-07-29 06:23:33 -07001097 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -04001098 set_bitmap_color_space(&bitmapInfo);
msarett50ce1f22016-07-29 06:23:33 -07001099 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
1100 kBGRA_8888_SkColorType == decodeInfo.colorType())
1101 {
1102 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
1103 }
1104
1105 SkBitmap bitmap;
1106 if (!bitmap.tryAllocPixels(bitmapInfo)) {
1107 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
1108 bitmapInfo.width(), bitmapInfo.height());
1109 }
1110
1111 size_t rowBytes = bitmap.rowBytes();
1112 SkCodec::Result r = codec->getPixels(decodeInfo, bitmap.getPixels(), rowBytes);
Leon Scroggins III674a1842017-07-06 12:26:09 -04001113 switch (r) {
1114 case SkCodec::kSuccess:
1115 case SkCodec::kErrorInInput:
1116 case SkCodec::kIncompleteInput:
1117 break;
1118 default:
1119 return SkStringPrintf("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
msarett50ce1f22016-07-29 06:23:33 -07001120 }
1121
msarett69deca82016-04-29 09:38:40 -07001122 switch (fMode) {
1123 case kBaseline_Mode:
msarett39979d82016-07-28 17:11:18 -07001124 case kDst_sRGB_Mode:
msarett50ce1f22016-07-29 06:23:33 -07001125 case kDst_HPZR30w_Mode:
Matt Sarett6a0feba2017-06-09 10:45:44 -04001126 // We do not support drawing unclamped F16.
1127 clamp_if_necessary(bitmap, canvas->imageInfo().colorType());
msarett39979d82016-07-28 17:11:18 -07001128 canvas->drawBitmap(bitmap, 0, 0);
1129 break;
msarett69deca82016-04-29 09:38:40 -07001130 default:
1131 SkASSERT(false);
1132 return "Invalid fMode";
1133 }
1134 return "";
1135}
1136
1137SkISize ColorCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001138 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001139 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett69deca82016-04-29 09:38:40 -07001140 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001141 return {0, 0};
msarett69deca82016-04-29 09:38:40 -07001142 }
Hal Canaryfafe1352017-04-11 12:12:02 -04001143 return {codec->getInfo().width(), codec->getInfo().height()};
msarett69deca82016-04-29 09:38:40 -07001144}
1145
1146Name ColorCodecSrc::name() const {
1147 return SkOSPath::Basename(fPath.c_str());
1148}
1149
1150/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1151
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001152SKPSrc::SKPSrc(Path path) : fPath(path) { }
mtklein748ca3b2015-01-15 10:56:12 -08001153
Robert Phillipse4aae342018-03-14 10:26:57 -04001154static sk_sp<SkPicture> read_skp(const char* path, const SkDeserialProcs* procs = nullptr) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001155 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtklein75d98fd2015-01-18 07:05:01 -08001156 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001157 return nullptr;
mtklein748ca3b2015-01-15 10:56:12 -08001158 }
Robert Phillipse4aae342018-03-14 10:26:57 -04001159 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get(), procs));
mtklein75d98fd2015-01-18 07:05:01 -08001160 if (!pic) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001161 return nullptr;
mtklein75d98fd2015-01-18 07:05:01 -08001162 }
bungemanf93d7112016-09-16 06:24:20 -07001163 stream = nullptr; // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -07001164
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001165 return pic;
1166}
1167
1168Error SKPSrc::draw(SkCanvas* canvas) const {
1169 sk_sp<SkPicture> pic = read_skp(fPath.c_str());
1170 if (!pic) {
1171 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1172 }
1173
Robert Phillips33f02ed2018-03-27 08:06:57 -04001174 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
mtklein748ca3b2015-01-15 10:56:12 -08001175 canvas->drawPicture(pic);
1176 return "";
1177}
1178
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001179static SkRect get_cull_rect_for_skp(const char* path) {
1180 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtkleinffa901a2015-03-16 10:38:07 -07001181 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001182 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001183 }
1184 SkPictInfo info;
Mike Reede7a58322017-12-20 14:09:20 -05001185 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001186 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001187 }
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001188
1189 return info.fCullRect;
1190}
1191
1192SkISize SKPSrc::size() const {
1193 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
Robert Phillips33f02ed2018-03-27 08:06:57 -04001194 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001195 return {0, 0};
mtkleinffa901a2015-03-16 10:38:07 -07001196 }
1197 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -08001198}
1199
1200Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1201
Florin Malitafc043dc2017-12-31 11:08:42 -05001202/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1203
Florin Malita124d5af2017-12-31 17:02:26 -05001204#if !defined(SK_BUILD_FOR_GOOGLE3)
Florin Malita54f65c42018-01-16 17:04:30 -05001205SkottieSrc::SkottieSrc(Path path)
Florin Malitafc043dc2017-12-31 11:08:42 -05001206 : fName(SkOSPath::Basename(path.c_str())) {
1207
Florin Malita54f65c42018-01-16 17:04:30 -05001208 fAnimation = skottie::Animation::MakeFromFile(path.c_str());
Florin Malitafc043dc2017-12-31 11:08:42 -05001209 if (!fAnimation) {
1210 return;
1211 }
1212
1213 // Fit kTileCount x kTileCount frames to a 1000x1000 film strip.
1214 static constexpr SkScalar kTargetSize = 1000;
Florin Malita3fae0f32018-03-15 21:52:54 -04001215 fTileSize = SkSize::Make(kTargetSize / kTileCount, kTargetSize / kTileCount).toCeil();
Florin Malitafc043dc2017-12-31 11:08:42 -05001216}
1217
Florin Malita54f65c42018-01-16 17:04:30 -05001218Error SkottieSrc::draw(SkCanvas* canvas) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001219 if (!fAnimation) {
1220 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
1221 }
1222
1223 canvas->drawColor(SK_ColorWHITE);
1224
Florin Malitafc043dc2017-12-31 11:08:42 -05001225 const auto ip = fAnimation->inPoint() * 1000 / fAnimation->frameRate(),
1226 op = fAnimation->outPoint() * 1000 / fAnimation->frameRate(),
1227 fr = (op - ip) / (kTileCount * kTileCount - 1);
1228
Florin Malitad3c1b842018-01-27 12:43:24 -05001229 // Shuffled order to exercise non-linear frame progression.
1230 static constexpr int frames[] = { 4, 0, 3, 1, 2 };
1231 static_assert(SK_ARRAY_COUNT(frames) == kTileCount, "");
1232
Florin Malitafc043dc2017-12-31 11:08:42 -05001233 for (int i = 0; i < kTileCount; ++i) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001234 const SkScalar y = frames[i] * fTileSize.height();
Florin Malitafc043dc2017-12-31 11:08:42 -05001235
1236 for (int j = 0; j < kTileCount; ++j) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001237 const SkScalar x = frames[j] * fTileSize.width();
Florin Malitafc043dc2017-12-31 11:08:42 -05001238 SkRect dest = SkRect::MakeXYWH(x, y, fTileSize.width(), fTileSize.height());
1239
Florin Malitad3c1b842018-01-27 12:43:24 -05001240 const auto t = fr * (frames[i] * kTileCount + frames[j]);
Florin Malitadf2713c2018-01-09 15:51:21 -05001241 {
1242 SkAutoCanvasRestore acr(canvas, true);
Florin Malitad3c1b842018-01-27 12:43:24 -05001243 canvas->clipRect(dest, true);
Florin Malitadf2713c2018-01-09 15:51:21 -05001244 canvas->concat(SkMatrix::MakeRectToRect(SkRect::MakeSize(fAnimation->size()),
1245 dest,
Florin Malita3fae0f32018-03-15 21:52:54 -04001246 SkMatrix::kCenter_ScaleToFit));
Florin Malitadf2713c2018-01-09 15:51:21 -05001247
1248 fAnimation->animationTick(t);
1249 fAnimation->render(canvas);
1250 }
Florin Malitafc043dc2017-12-31 11:08:42 -05001251 }
1252 }
1253
1254 return "";
1255}
1256
Florin Malita54f65c42018-01-16 17:04:30 -05001257SkISize SkottieSrc::size() const {
Florin Malita3fae0f32018-03-15 21:52:54 -04001258 return SkISize::Make(kTileCount * fTileSize.width(),
1259 kTileCount * fTileSize.height());
Florin Malitafc043dc2017-12-31 11:08:42 -05001260}
1261
Florin Malita54f65c42018-01-16 17:04:30 -05001262Name SkottieSrc::name() const { return fName; }
Florin Malitafc043dc2017-12-31 11:08:42 -05001263
Florin Malita54f65c42018-01-16 17:04:30 -05001264bool SkottieSrc::veto(SinkFlags flags) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001265 // No need to test to non-(raster||gpu||vector) or indirect backends.
1266 bool type_ok = flags.type == SinkFlags::kRaster
1267 || flags.type == SinkFlags::kGPU
1268 || flags.type == SinkFlags::kVector;
1269
1270 return !type_ok || flags.approach != SinkFlags::kDirect;
1271}
Florin Malita124d5af2017-12-31 17:02:26 -05001272#endif
Florin Malitafc043dc2017-12-31 11:08:42 -05001273
1274/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
fmalitaa2b9fdf2016-08-03 19:53:36 -07001275#if defined(SK_XML)
fmalitabdf3e5c2016-09-17 07:26:26 -07001276// Used when the image doesn't have an intrinsic size.
Hal Canaryfafe1352017-04-11 12:12:02 -04001277static const SkSize kDefaultSVGSize = {1000, 1000};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001278
fmalitabdf3e5c2016-09-17 07:26:26 -07001279// Used to force-scale tiny fixed-size images.
Hal Canaryfafe1352017-04-11 12:12:02 -04001280static const SkSize kMinimumSVGSize = {128, 128};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001281
fmalitaacd2f5c2016-11-08 07:13:45 -08001282SVGSrc::SVGSrc(Path path)
1283 : fName(SkOSPath::Basename(path.c_str()))
1284 , fScale(1) {
fmalitabdf3e5c2016-09-17 07:26:26 -07001285
fmalitaacd2f5c2016-11-08 07:13:45 -08001286 SkFILEStream stream(path.c_str());
1287 if (!stream.isValid()) {
1288 return;
1289 }
1290 fDom = SkSVGDOM::MakeFromStream(stream);
1291 if (!fDom) {
1292 return;
1293 }
1294
1295 const SkSize& sz = fDom->containerSize();
1296 if (sz.isEmpty()) {
1297 // no intrinsic size
1298 fDom->setContainerSize(kDefaultSVGSize);
1299 } else {
1300 fScale = SkTMax(1.f, SkTMax(kMinimumSVGSize.width() / sz.width(),
1301 kMinimumSVGSize.height() / sz.height()));
1302 }
1303}
1304
1305Error SVGSrc::draw(SkCanvas* canvas) const {
fmalitabdf3e5c2016-09-17 07:26:26 -07001306 if (!fDom) {
fmalitaacd2f5c2016-11-08 07:13:45 -08001307 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
fmalitaa2b9fdf2016-08-03 19:53:36 -07001308 }
1309
fmalitaacd2f5c2016-11-08 07:13:45 -08001310 SkAutoCanvasRestore acr(canvas, true);
1311 canvas->scale(fScale, fScale);
1312 fDom->render(canvas);
1313
fmalitaa2b9fdf2016-08-03 19:53:36 -07001314 return "";
1315}
1316
1317SkISize SVGSrc::size() const {
fmalitaacd2f5c2016-11-08 07:13:45 -08001318 if (!fDom) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001319 return {0, 0};
fmalitabdf3e5c2016-09-17 07:26:26 -07001320 }
1321
Hal Canaryfafe1352017-04-11 12:12:02 -04001322 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1323 .toRound();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001324}
1325
fmalitaacd2f5c2016-11-08 07:13:45 -08001326Name SVGSrc::name() const { return fName; }
fmalitaa2b9fdf2016-08-03 19:53:36 -07001327
fmalita179d8852016-08-16 14:23:29 -07001328bool SVGSrc::veto(SinkFlags flags) const {
Florin Malita93323eb2017-06-16 15:31:17 -04001329 // No need to test to non-(raster||gpu||vector) or indirect backends.
fmalita179d8852016-08-16 14:23:29 -07001330 bool type_ok = flags.type == SinkFlags::kRaster
Florin Malita93323eb2017-06-16 15:31:17 -04001331 || flags.type == SinkFlags::kGPU
1332 || flags.type == SinkFlags::kVector;
fmalita179d8852016-08-16 14:23:29 -07001333
1334 return !type_ok || flags.approach != SinkFlags::kDirect;
1335}
1336
fmalitaa2b9fdf2016-08-03 19:53:36 -07001337#endif // defined(SK_XML)
1338/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -08001339
halcanary45420a92016-06-02 12:41:14 -07001340MSKPSrc::MSKPSrc(Path path) : fPath(path) {
bungemanf93d7112016-09-16 06:24:20 -07001341 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001342 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1343 if (count > 0) {
1344 fPages.reset(count);
1345 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1346 }
halcanary45420a92016-06-02 12:41:14 -07001347}
1348
Hal Canary45cde312017-04-03 16:06:42 -04001349int MSKPSrc::pageCount() const { return fPages.count(); }
halcanary45420a92016-06-02 12:41:14 -07001350
1351SkISize MSKPSrc::size() const { return this->size(0); }
Hal Canary45cde312017-04-03 16:06:42 -04001352SkISize MSKPSrc::size(int i) const {
Hal Canaryfafe1352017-04-11 12:12:02 -04001353 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
Hal Canary45cde312017-04-03 16:06:42 -04001354}
halcanary45420a92016-06-02 12:41:14 -07001355
1356Error MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
1357Error MSKPSrc::draw(int i, SkCanvas* canvas) const {
Hal Canary45cde312017-04-03 16:06:42 -04001358 if (this->pageCount() == 0) {
halcanary45420a92016-06-02 12:41:14 -07001359 return SkStringPrintf("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1360 }
Hal Canary45cde312017-04-03 16:06:42 -04001361 if (i >= fPages.count() || i < 0) {
halcanary45420a92016-06-02 12:41:14 -07001362 return SkStringPrintf("MultiPictureDocument page number out of range: %d", i);
1363 }
Hal Canary45cde312017-04-03 16:06:42 -04001364 SkPicture* page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001365 if (!page) {
Hal Canary45cde312017-04-03 16:06:42 -04001366 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1367 if (!stream) {
1368 return SkStringPrintf("Unable to open file: %s", fPath.c_str());
1369 }
1370 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
1371 return SkStringPrintf("SkMultiPictureDocument reader failed on page %d: %s", i,
1372 fPath.c_str());
1373 }
1374 page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001375 }
1376 canvas->drawPicture(page);
1377 return "";
1378}
1379
1380Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1381
1382/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1383
mtkleinad66f9b2015-02-13 15:11:10 -08001384Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
Mike Reed5df49342016-11-12 08:06:55 -06001385 return src.draw(SkMakeNullCanvas().get());
mtkleinad66f9b2015-02-13 15:11:10 -08001386}
1387
1388/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1389
Brian Osmane5756ec2017-09-06 17:08:30 -04001390static bool encode_png_base64(const SkBitmap& bitmap, SkString* dst) {
1391 SkPixmap pm;
1392 if (!bitmap.peekPixels(&pm)) {
1393 dst->set("peekPixels failed");
1394 return false;
1395 }
1396
1397 // We're going to embed this PNG in a data URI, so make it as small as possible
1398 SkPngEncoder::Options options;
1399 options.fFilterFlags = SkPngEncoder::FilterFlag::kAll;
1400 options.fZLibLevel = 9;
1401 options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
1402 : SkTransferFunctionBehavior::kIgnore;
1403
1404 SkDynamicMemoryWStream wStream;
1405 if (!SkPngEncoder::Encode(&wStream, pm, options)) {
1406 dst->set("SkPngEncoder::Encode failed");
1407 return false;
1408 }
1409
1410 sk_sp<SkData> pngData = wStream.detachAsData();
1411 size_t len = SkBase64::Encode(pngData->data(), pngData->size(), nullptr);
1412
1413 // The PNG can be almost arbitrarily large. We don't want to fill our logs with enormous URLs.
1414 // Infra says these can be pretty big, as long as we're only outputting them on failure.
1415 static const size_t kMaxBase64Length = 1024 * 1024;
1416 if (len > kMaxBase64Length) {
1417 dst->printf("Encoded image too large (%u bytes)", static_cast<uint32_t>(len));
1418 return false;
1419 }
1420
1421 dst->resize(len);
1422 SkBase64::Encode(pngData->data(), pngData->size(), dst->writable_str());
1423 return true;
1424}
1425
1426static Error compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
1427 // The dimensions are a property of the Src only, and so should be identical.
Mike Reedf0ffb892017-10-03 14:47:21 -04001428 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1429 if (reference.computeByteSize() != bitmap.computeByteSize()) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001430 return "Dimensions don't match reference";
1431 }
1432 // All SkBitmaps in DM are tight, so this comparison is easy.
Mike Reedf0ffb892017-10-03 14:47:21 -04001433 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001434 SkString encoded;
1435 SkString errString("Pixels don't match reference");
1436 if (encode_png_base64(reference, &encoded)) {
1437 errString.append("\nExpected: data:image/png;base64,");
1438 errString.append(encoded);
1439 } else {
1440 errString.append("\nExpected image failed to encode: ");
1441 errString.append(encoded);
1442 }
1443 if (encode_png_base64(bitmap, &encoded)) {
1444 errString.append("\nActual: data:image/png;base64,");
1445 errString.append(encoded);
1446 } else {
1447 errString.append("\nActual image failed to encode: ");
1448 errString.append(encoded);
1449 }
1450 return errString;
1451 }
1452 return "";
1453}
1454
1455/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1456
mtkleinb9eb4ac2015-02-02 18:26:03 -08001457DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1458
bsalomon85b4b532016-04-05 11:06:27 -07001459GPUSink::GPUSink(GrContextFactory::ContextType ct,
csmartdaltone812d492017-02-21 12:36:05 -07001460 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001461 SkCommandLineConfigGpu::SurfType surfType,
mtklein82d28432015-01-15 12:46:02 -08001462 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -07001463 bool diText,
brianosmand93c1202016-03-10 07:49:08 -08001464 SkColorType colorType,
Brian Salomonce5ee602017-07-17 11:31:31 -04001465 SkAlphaType alphaType,
brianosmanb109b8c2016-06-16 13:03:24 -07001466 sk_sp<SkColorSpace> colorSpace,
Brian Osmanf21aa042017-08-21 16:48:46 -04001467 bool threaded,
1468 const GrContextOptions& grCtxOptions)
Brian Salomonce5ee602017-07-17 11:31:31 -04001469 : fContextType(ct)
1470 , fContextOverrides(overrides)
Brian Salomonf865b052018-03-09 09:01:53 -05001471 , fSurfType(surfType)
Brian Salomonce5ee602017-07-17 11:31:31 -04001472 , fSampleCount(samples)
1473 , fUseDIText(diText)
1474 , fColorType(colorType)
1475 , fAlphaType(alphaType)
1476 , fColorSpace(std::move(colorSpace))
Brian Osmanf21aa042017-08-21 16:48:46 -04001477 , fThreaded(threaded)
1478 , fBaseContextOptions(grCtxOptions) {}
mtklein748ca3b2015-01-15 10:56:12 -08001479
Brian Salomon09d994e2016-12-21 11:14:46 -05001480DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
bsalomon648c6962015-10-23 09:06:59 -07001481
Brian Osmanf9810662017-08-30 10:02:10 -04001482Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
1483 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1484}
1485
1486Error GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1487 const GrContextOptions& baseOptions) const {
1488 GrContextOptions grOptions = baseOptions;
kkinnunen64492c42015-12-08 01:24:40 -08001489
kkinnunen5219fd92015-12-10 06:28:13 -08001490 src.modifyGrContextOptions(&grOptions);
1491
1492 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -08001493 const SkISize size = src.size();
Brian Salomonce5ee602017-07-17 11:31:31 -04001494 SkImageInfo info =
1495 SkImageInfo::Make(size.width(), size.height(), fColorType, fAlphaType, fColorSpace);
Brian Salomonf865b052018-03-09 09:01:53 -05001496 sk_sp<SkSurface> surface;
msarett13a036b2016-02-08 09:10:47 -08001497#if SK_SUPPORT_GPU
csmartdaltone812d492017-02-21 12:36:05 -07001498 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
bsalomon8b7451a2016-05-11 06:33:06 -07001499 const int maxDimension = context->caps()->maxTextureSize();
msarett13a036b2016-02-08 09:10:47 -08001500 if (maxDimension < SkTMax(size.width(), size.height())) {
1501 return Error::Nonfatal("Src too large to create a texture.\n");
1502 }
Brian Salomonf865b052018-03-09 09:01:53 -05001503 uint32_t flags = fUseDIText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
1504 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
1505 GrBackendTexture backendTexture;
1506 GrBackendRenderTarget backendRT;
1507 switch (fSurfType) {
1508 case SkCommandLineConfigGpu::SurfType::kDefault:
1509 surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, fSampleCount,
1510 &props);
1511 break;
1512 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
1513 backendTexture = context->contextPriv().getGpu()->createTestingOnlyBackendTexture(
Greg Daniel57bf4a32018-04-19 10:28:37 -04001514 nullptr, info.width(), info.height(), info.colorType(), info.colorSpace(),
1515 true, GrMipMapped::kNo);
Brian Salomonf865b052018-03-09 09:01:53 -05001516 surface = SkSurface::MakeFromBackendTexture(context, backendTexture,
1517 kTopLeft_GrSurfaceOrigin, fSampleCount,
Brian Salomon53706772018-03-19 14:18:08 -04001518 fColorType, info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001519 break;
1520 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1521 if (1 == fSampleCount) {
1522 auto srgbEncoded = info.colorSpace() && info.colorSpace()->gammaCloseToSRGB()
1523 ? GrSRGBEncoded::kYes
1524 : GrSRGBEncoded::kNo;
1525 auto colorType = SkColorTypeToGrColorType(info.colorType());
1526 backendRT = context->contextPriv().getGpu()->createTestingOnlyBackendRenderTarget(
1527 info.width(), info.height(), colorType, srgbEncoded);
Brian Salomon49edccd2018-03-23 15:31:32 -04001528 surface = SkSurface::MakeFromBackendRenderTarget(
1529 context, backendRT, kBottomLeft_GrSurfaceOrigin, info.colorType(),
1530 info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001531 }
1532 break;
1533 }
msarett13a036b2016-02-08 09:10:47 -08001534#endif
1535
mtklein748ca3b2015-01-15 10:56:12 -08001536 if (!surface) {
1537 return "Could not create a surface.";
1538 }
joshualitt5f5a8d72015-02-25 14:09:45 -08001539 if (FLAGS_preAbandonGpuContext) {
joshualitt5f5a8d72015-02-25 14:09:45 -08001540 factory.abandonContexts();
1541 }
mtklein748ca3b2015-01-15 10:56:12 -08001542 SkCanvas* canvas = surface->getCanvas();
1543 Error err = src.draw(canvas);
1544 if (!err.isEmpty()) {
1545 return err;
1546 }
1547 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -08001548 if (FLAGS_gpuStats) {
Robert Phillips0c4b7b12018-03-06 08:20:37 -05001549#if SK_SUPPORT_GPU
1550 canvas->getGrContext()->contextPriv().dumpCacheStats(log);
1551 canvas->getGrContext()->contextPriv().dumpGpuStats(log);
1552#endif
mtkleinb9eb4ac2015-02-02 18:26:03 -08001553 }
Brian Salomon5fba7ad2018-03-22 10:01:16 -04001554 if (info.colorType() == kRGB_565_SkColorType || info.colorType() == kARGB_4444_SkColorType ||
1555 info.colorType() == kRGB_888x_SkColorType) {
Brian Salomonce5ee602017-07-17 11:31:31 -04001556 // We don't currently support readbacks into these formats on the GPU backend. Convert to
1557 // 32 bit.
1558 info = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
1559 kPremul_SkAlphaType, fColorSpace);
1560 }
mtklein748ca3b2015-01-15 10:56:12 -08001561 dst->allocPixels(info);
Mike Reed12e946b2017-04-17 10:53:29 -04001562 canvas->readPixels(*dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -08001563 if (FLAGS_abandonGpuContext) {
1564 factory.abandonContexts();
bsalomon6e2aad42016-04-01 11:54:31 -07001565 } else if (FLAGS_releaseAndAbandonGpuContext) {
1566 factory.releaseResourcesAndAbandonContexts();
mtklein55e88b22015-01-21 15:50:13 -08001567 }
Brian Salomonf865b052018-03-09 09:01:53 -05001568#if SK_SUPPORT_GPU
1569 if (!context->contextPriv().abandoned()) {
1570 surface.reset();
1571 if (backendTexture.isValid()) {
Brian Salomon26102cb2018-03-09 09:33:19 -05001572 context->contextPriv().getGpu()->deleteTestingOnlyBackendTexture(backendTexture);
Brian Salomonf865b052018-03-09 09:01:53 -05001573 }
1574 if (backendRT.isValid()) {
1575 context->contextPriv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
1576 }
1577 }
1578#endif
mtklein748ca3b2015-01-15 10:56:12 -08001579 return "";
1580}
1581
1582/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1583
Brian Osmanf9810662017-08-30 10:02:10 -04001584GPUThreadTestingSink::GPUThreadTestingSink(GrContextFactory::ContextType ct,
1585 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001586 SkCommandLineConfigGpu::SurfType surfType,
Brian Osmanf9810662017-08-30 10:02:10 -04001587 int samples,
1588 bool diText,
1589 SkColorType colorType,
1590 SkAlphaType alphaType,
1591 sk_sp<SkColorSpace> colorSpace,
1592 bool threaded,
1593 const GrContextOptions& grCtxOptions)
Brian Salomonf865b052018-03-09 09:01:53 -05001594 : INHERITED(ct, overrides, surfType, samples, diText, colorType, alphaType,
1595 std::move(colorSpace), threaded, grCtxOptions)
Chris Dalton040238b2017-12-18 14:22:34 -07001596#if SK_SUPPORT_GPU
Mike Klein022cfa22017-09-01 11:53:16 -04001597 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)) {
Chris Dalton040238b2017-12-18 14:22:34 -07001598#else
1599 , fExecutor(nullptr) {
1600#endif
Brian Osmanf9810662017-08-30 10:02:10 -04001601 SkASSERT(fExecutor);
1602}
1603
1604Error GPUThreadTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1605 SkString* log) const {
1606 // Draw twice, once with worker threads, and once without. Verify that we get the same result.
1607 // Also, force us to only use the software path renderer, so we really stress-test the threaded
1608 // version of that code.
1609 GrContextOptions contextOptions = this->baseContextOptions();
Brian Osman195c05b2017-08-30 15:14:04 -04001610 contextOptions.fGpuPathRenderers = GpuPathRenderers::kNone;
Brian Osmanf9810662017-08-30 10:02:10 -04001611
1612 contextOptions.fExecutor = fExecutor.get();
1613 Error err = this->onDraw(src, dst, wStream, log, contextOptions);
1614 if (!err.isEmpty() || !dst) {
1615 return err;
1616 }
1617
1618 SkBitmap reference;
1619 SkString refLog;
1620 SkDynamicMemoryWStream refStream;
1621 contextOptions.fExecutor = nullptr;
1622 Error refErr = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1623 if (!refErr.isEmpty()) {
1624 return refErr;
1625 }
1626
Brian Osmane5756ec2017-09-06 17:08:30 -04001627 return compare_bitmaps(reference, *dst);
Brian Osmanf9810662017-08-30 10:02:10 -04001628}
1629
1630/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1631
halcanary47ef4d52015-03-03 09:13:09 -08001632static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
halcanary4ba051c2016-03-10 10:31:53 -08001633 if (src.size().isEmpty()) {
1634 return "Source has empty dimensions";
1635 }
halcanary47ef4d52015-03-03 09:13:09 -08001636 SkASSERT(doc);
halcanary45420a92016-06-02 12:41:14 -07001637 int pageCount = src.pageCount();
1638 for (int i = 0; i < pageCount; ++i) {
1639 int width = src.size(i).width(), height = src.size(i).height();
halcanary7e798182015-04-14 14:06:18 -07001640 SkCanvas* canvas =
1641 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1642 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001643 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001644 }
halcanary45420a92016-06-02 12:41:14 -07001645 Error err = src.draw(i, canvas);
halcanary7e798182015-04-14 14:06:18 -07001646 if (!err.isEmpty()) {
1647 return err;
1648 }
1649 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001650 }
reedd14df7c2016-09-22 14:12:46 -07001651 doc->close();
halcanaryfd4a9932015-01-28 11:45:58 -08001652 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -08001653 return "";
1654}
1655
halcanary47ef4d52015-03-03 09:13:09 -08001656Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary4b656662016-04-27 07:45:18 -07001657 SkDocument::PDFMetadata metadata;
1658 metadata.fTitle = src.name();
1659 metadata.fSubject = "rendering correctness test";
1660 metadata.fCreator = "Skia/DM";
Mike Reeda4daf192017-12-14 13:25:04 -05001661 metadata.fRasterDPI = fRasterDpi;
1662 metadata.fPDFA = fPDFA;
1663 sk_sp<SkDocument> doc = SkDocument::MakePDF(dst, metadata);
halcanary47ef4d52015-03-03 09:13:09 -08001664 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001665 return "SkDocument::MakePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001666 }
1667 return draw_skdocument(src, doc.get(), dst);
1668}
1669
1670/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1671
1672XPSSink::XPSSink() {}
1673
Hal Canaryabc88d22017-02-06 09:26:49 -05001674#ifdef SK_BUILD_FOR_WIN
Hal Canary5e221e72017-02-06 09:51:42 -05001675static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1676 IXpsOMObjectFactory* factory;
1677 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1678 nullptr,
1679 CLSCTX_INPROC_SERVER,
1680 IID_PPV_ARGS(&factory)));
1681 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1682}
1683
1684Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canaryabc88d22017-02-06 09:26:49 -05001685 SkAutoCoInitialize com;
1686 if (!com.succeeded()) {
1687 return "Could not initialize COM.";
1688 }
Hal Canary5e221e72017-02-06 09:51:42 -05001689 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1690 if (!factory) {
1691 return "Failed to create XPS Factory.";
1692 }
1693 sk_sp<SkDocument> doc(SkDocument::MakeXPS(dst, factory.get()));
halcanary47ef4d52015-03-03 09:13:09 -08001694 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001695 return "SkDocument::MakeXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001696 }
1697 return draw_skdocument(src, doc.get(), dst);
1698}
Hal Canary5e221e72017-02-06 09:51:42 -05001699#else
1700Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1701 return "XPS not supported on this platform.";
1702}
1703#endif
reed54dc4872016-09-13 08:09:45 -07001704
1705/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1706
1707PipeSink::PipeSink() {}
1708
1709Error PipeSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1710 return src.draw(SkPipeSerializer().beginWrite(SkRect::Make(src.size()), dst));
1711}
1712
mtklein748ca3b2015-01-15 10:56:12 -08001713/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1714
mtklein9c3f17d2015-01-28 11:35:18 -08001715SKPSink::SKPSink() {}
1716
mtkleinb9eb4ac2015-02-02 18:26:03 -08001717Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001718 SkSize size;
1719 size = src.size();
1720 SkPictureRecorder recorder;
1721 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1722 if (!err.isEmpty()) {
1723 return err;
1724 }
reedca2622b2016-03-18 07:25:55 -07001725 recorder.finishRecordingAsPicture()->serialize(dst);
mtklein9c3f17d2015-01-28 11:35:18 -08001726 return "";
1727}
1728
1729/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1730
Hal Canary85c7fe82016-10-25 10:33:27 -04001731Error DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1732 SkDebugCanvas debugCanvas(src.size().width(), src.size().height());
1733 Error err = src.draw(&debugCanvas);
1734 if (!err.isEmpty()) {
1735 return err;
1736 }
Mike Reed5df49342016-11-12 08:06:55 -06001737 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
Hal Canary85c7fe82016-10-25 10:33:27 -04001738 UrlDataManager dataManager(SkString("data"));
1739 Json::Value json = debugCanvas.toJSON(
1740 dataManager, debugCanvas.getSize(), nullCanvas.get());
1741 std::string value = Json::StyledWriter().write(json);
1742 return dst->write(value.c_str(), value.size()) ? "" : "SkWStream Error";
1743}
1744
1745/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1746
Bryce Thomas95a7b762018-03-02 13:54:21 -08001747SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
mtklein8a4527e2015-01-31 20:00:58 -08001748
mtkleinb9eb4ac2015-02-02 18:26:03 -08001749Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita718df0a2016-07-15 10:33:29 -07001750#if defined(SK_XML)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001751 if (src.pageCount() > 1) {
1752 int pageCount = src.pageCount();
1753 if (fPageIndex > pageCount - 1) {
1754 return Error(SkStringPrintf("Page index %d too high for document with only %d pages.",
1755 fPageIndex, pageCount));
1756 }
1757 }
Ben Wagner145dbcd2016-11-03 14:40:50 -04001758 std::unique_ptr<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
Bryce Thomas95a7b762018-03-02 13:54:21 -08001759 return src.draw(fPageIndex,
1760 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
Mike Reed5df49342016-11-12 08:06:55 -06001761 SkIntToScalar(src.size().height())),
Bryce Thomas95a7b762018-03-02 13:54:21 -08001762 xmlWriter.get())
1763 .get());
fmalita718df0a2016-07-15 10:33:29 -07001764#else
Hal Canary327ef032018-03-22 13:10:51 -04001765 (void)fPageIndex;
fmalita718df0a2016-07-15 10:33:29 -07001766 return Error("SVG sink is disabled.");
1767#endif // SK_XML
mtklein8a4527e2015-01-31 20:00:58 -08001768}
1769
1770/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1771
brianosmanb109b8c2016-06-16 13:03:24 -07001772RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
mtklein27c3fdd2016-02-26 14:43:21 -08001773 : fColorType(colorType)
brianosmanb109b8c2016-06-16 13:03:24 -07001774 , fColorSpace(std::move(colorSpace)) {}
mtklein748ca3b2015-01-15 10:56:12 -08001775
Yuqian Lib8b62532018-02-23 14:13:36 +08001776void RasterSink::allocPixels(const Src& src, SkBitmap* dst) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001777 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001778 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1779 SkAlphaType alphaType = kPremul_SkAlphaType;
1780 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1781
Mike Reed086a4272017-07-18 10:53:11 -04001782 dst->allocPixelsFlags(SkImageInfo::Make(size.width(), size.height(),
1783 fColorType, alphaType, fColorSpace),
1784 SkBitmap::kZeroPixels_AllocFlag);
Yuqian Lib8b62532018-02-23 14:13:36 +08001785}
1786
1787Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
1788 this->allocPixels(src, dst);
mtklein748ca3b2015-01-15 10:56:12 -08001789 SkCanvas canvas(*dst);
1790 return src.draw(&canvas);
1791}
1792
1793/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1794
Yuqian Lib8b62532018-02-23 14:13:36 +08001795ThreadedSink::ThreadedSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
1796 : RasterSink(colorType, colorSpace)
1797 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_backendThreads)) {
1798}
1799
1800Error ThreadedSink::draw(const Src& src, SkBitmap* dst, SkWStream* stream, SkString* str) const {
1801 this->allocPixels(src, dst);
1802
1803 std::unique_ptr<SkThreadedBMPDevice> device(new SkThreadedBMPDevice(
1804 *dst, FLAGS_backendTiles, FLAGS_backendThreads, fExecutor.get()));
1805 std::unique_ptr<SkCanvas> canvas(new SkCanvas(device.get()));
1806 Error result = src.draw(canvas.get());
1807 canvas->flush();
1808 return result;
1809
1810 // ??? yuqian: why does the following give me segmentation fault while the above one works?
1811 // The seg fault occurs right in the beginning of ThreadedSink::draw with invalid
1812 // memory address (it would crash without even calling this->allocPixels).
1813
1814 // SkThreadedBMPDevice device(*dst, tileCnt, FLAGS_cpuThreads, fExecutor.get());
1815 // SkCanvas canvas(&device);
1816 // Error result = src.draw(&canvas);
1817 // canvas.flush();
1818 // return result;
1819}
1820
1821/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1822
mtkleina16e69e2015-05-05 11:38:45 -07001823// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001824// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001825// Several examples below.
1826
mtkleincbf89782016-02-19 14:27:14 -08001827template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001828static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001829 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001830 class ProxySrc : public Src {
1831 public:
mtkleincbf89782016-02-19 14:27:14 -08001832 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001833 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
halcanaryb4a7f142016-03-30 08:31:27 -07001834 Name name() const override { return "ProxySrc"; }
1835 SkISize size() const override { return fSize; }
mtkleina16e69e2015-05-05 11:38:45 -07001836 private:
mtkleincbf89782016-02-19 14:27:14 -08001837 SkISize fSize;
1838 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001839 };
msarett62d3b102015-12-10 15:14:27 -08001840 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001841}
1842
1843/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1844
mtklein4a34ecb2016-01-08 10:19:35 -08001845DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1846
1847// Is *bitmap identical to what you get drawing src into sink?
1848static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1849 // We can only check raster outputs.
1850 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1851 if (FLAGS_check && bitmap) {
1852 SkBitmap reference;
1853 SkString log;
halcanaryb4a7f142016-03-30 08:31:27 -07001854 SkDynamicMemoryWStream wStream;
1855 Error err = sink->draw(src, &reference, &wStream, &log);
mtklein4a34ecb2016-01-08 10:19:35 -08001856 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1857 SkASSERT(err.isEmpty());
1858 if (!err.isEmpty()) {
1859 return err;
1860 }
Brian Osmane5756ec2017-09-06 17:08:30 -04001861 return compare_bitmaps(reference, *bitmap);
mtklein4a34ecb2016-01-08 10:19:35 -08001862 }
1863 return "";
1864}
1865
1866/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1867
mtkleind603b222015-02-17 11:13:33 -08001868static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1869 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1870 matrix->mapRect(&bounds);
1871 matrix->postTranslate(-bounds.x(), -bounds.y());
Hal Canaryfafe1352017-04-11 12:12:02 -04001872 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
mtkleind603b222015-02-17 11:13:33 -08001873}
1874
msarett62d3b102015-12-10 15:14:27 -08001875ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001876
mtkleinb9eb4ac2015-02-02 18:26:03 -08001877Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001878 SkMatrix matrix = fMatrix;
1879 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
Ben Wagner145dbcd2016-11-03 14:40:50 -04001880 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001881 canvas->concat(matrix);
1882 return src.draw(canvas);
1883 });
mtklein748ca3b2015-01-15 10:56:12 -08001884}
1885
mtkleind603b222015-02-17 11:13:33 -08001886// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1887// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001888ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001889
1890Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1891 Error err = fSink->draw(src, bitmap, stream, log);
1892 if (!err.isEmpty()) {
1893 return err;
1894 }
1895
1896 SkMatrix inverse;
1897 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1898 return "Cannot upright --matrix.";
1899 }
1900 SkMatrix upright = SkMatrix::I();
1901 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1902 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1903 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1904 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1905
1906 SkBitmap uprighted;
1907 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1908 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1909
1910 SkCanvas canvas(uprighted);
1911 canvas.concat(upright);
1912 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001913 paint.setBlendMode(SkBlendMode::kSrc);
mtkleind603b222015-02-17 11:13:33 -08001914 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1915
1916 *bitmap = uprighted;
mtkleind603b222015-02-17 11:13:33 -08001917 return "";
1918}
1919
mtklein748ca3b2015-01-15 10:56:12 -08001920/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1921
mtkleina16e69e2015-05-05 11:38:45 -07001922Error ViaSerialization::draw(
1923 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001924 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001925 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001926 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001927 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1928 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001929 if (!err.isEmpty()) {
1930 return err;
1931 }
reedca2622b2016-03-18 07:25:55 -07001932 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001933
1934 // Serialize it and then deserialize it.
reed39eaf5f2016-09-15 07:19:35 -07001935 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
mtklein748ca3b2015-01-15 10:56:12 -08001936
Ben Wagner1861e882018-04-04 17:40:46 -04001937 err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001938 canvas->drawPicture(deserialized);
Ben Wagner1861e882018-04-04 17:40:46 -04001939 return "";
mtkleina16e69e2015-05-05 11:38:45 -07001940 });
Ben Wagner1861e882018-04-04 17:40:46 -04001941 if (!err.isEmpty()) {
1942 return err;
1943 }
1944
1945 return check_against_reference(bitmap, src, fSink.get());
mtklein748ca3b2015-01-15 10:56:12 -08001946}
1947
1948/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1949
msarett62d3b102015-12-10 15:14:27 -08001950ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1951 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001952 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001953 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001954 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001955
mtkleinb9eb4ac2015-02-02 18:26:03 -08001956Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001957 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001958 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001959 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1960 SkIntToScalar(size.height()),
1961 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001962 if (!err.isEmpty()) {
1963 return err;
1964 }
reedca2622b2016-03-18 07:25:55 -07001965 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001966
Ben Wagner145dbcd2016-11-03 14:40:50 -04001967 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001968 const int xTiles = (size.width() + fW - 1) / fW,
1969 yTiles = (size.height() + fH - 1) / fH;
1970 SkMultiPictureDraw mpd(xTiles*yTiles);
reede8f30622016-03-23 18:59:25 -07001971 SkTArray<sk_sp<SkSurface>> surfaces;
1972// surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001973
mtkleina16e69e2015-05-05 11:38:45 -07001974 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1975 for (int j = 0; j < yTiles; j++) {
1976 for (int i = 0; i < xTiles; i++) {
1977 // This lets our ultimate Sink determine the best kind of surface.
1978 // E.g., if it's a GpuSink, the surfaces and images are textures.
reede8f30622016-03-23 18:59:25 -07001979 auto s = canvas->makeSurface(info);
mtkleina16e69e2015-05-05 11:38:45 -07001980 if (!s) {
reede8f30622016-03-23 18:59:25 -07001981 s = SkSurface::MakeRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001982 }
reede8f30622016-03-23 18:59:25 -07001983 surfaces.push_back(s);
mtkleina16e69e2015-05-05 11:38:45 -07001984 SkCanvas* c = s->getCanvas();
1985 c->translate(SkIntToScalar(-i * fW),
1986 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
reedca2622b2016-03-18 07:25:55 -07001987 mpd.add(c, pic.get());
mtklein748ca3b2015-01-15 10:56:12 -08001988 }
mtklein748ca3b2015-01-15 10:56:12 -08001989 }
mtkleina16e69e2015-05-05 11:38:45 -07001990 mpd.draw();
1991 for (int j = 0; j < yTiles; j++) {
1992 for (int i = 0; i < xTiles; i++) {
reed9ce9d672016-03-17 10:51:11 -07001993 sk_sp<SkImage> image(surfaces[i+xTiles*j]->makeImageSnapshot());
mtkleina16e69e2015-05-05 11:38:45 -07001994 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1995 }
1996 }
mtkleina16e69e2015-05-05 11:38:45 -07001997 return "";
1998 });
mtklein748ca3b2015-01-15 10:56:12 -08001999}
2000
mtkleinb7e8d692015-04-07 08:30:32 -07002001/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2002
Robert Phillips33f02ed2018-03-27 08:06:57 -04002003#if SK_SUPPORT_GPU
2004
2005ViaDDL::ViaDDL(int numDivisions, Sink* sink)
2006 : Via(sink)
2007 , fNumDivisions(numDivisions) {
2008}
2009
2010// This class consolidates tracking & extraction of the original image data from the sources,
2011// the upload of said data to the GPU and the fulfillment of promise images.
Robert Phillipsa479f962018-04-10 11:45:40 -04002012//
2013// The way this works is:
2014// the original skp is converted to SkData and all its image info is extracted into this
2015// class and only indices into this class are left in the SkData
2016// Prior to replaying in threads, all the images stored in this class are uploaded to the
2017// gpu and PromiseImageCallbackContexts are created for them
2018// Each thread reinflates the SkData into an SkPicture replacing all the indices w/
2019// promise images (all using the same GrBackendTexture and getting a ref to the
2020// appropriate PromiseImageCallbackContext) and then creates a DDL.
2021// This class is then reset - dropping all of its refs on the PromiseImageCallbackContexts
2022// Each done callback unrefs its PromiseImageCallbackContext so, once all the promise images
2023// are done the PromiseImageCallbackContext is freed and its GrBackendTexture removed
2024// from VRAM
2025//
Robert Phillips33f02ed2018-03-27 08:06:57 -04002026class ViaDDL::PromiseImageHelper {
2027public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002028 // This class acts as a proxy for the single GrBackendTexture representing an image.
2029 // Whenever a promise image is created for the image the promise image receives a ref to
2030 // this object. Once all the promise images receive their done callbacks this object
2031 // is deleted - removing the GrBackendTexture from VRAM.
2032 // Note that while the DDLs are being created in the threads, the PromiseImageHelper holds
2033 // a ref on all the PromiseImageCallbackContexts. However, once all the threads are done
2034 // it drops all of its refs (via "reset").
2035 class PromiseImageCallbackContext : public SkRefCnt {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002036 public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002037 PromiseImageCallbackContext(GrContext* context) : fContext(context) {}
2038
2039 ~PromiseImageCallbackContext() {
2040 GrGpu* gpu = fContext->contextPriv().getGpu();
2041
2042 if (fBackendTexture.isValid()) {
2043 gpu->deleteTestingOnlyBackendTexture(fBackendTexture);
2044 }
2045 }
2046
2047 void setBackendTexture(const GrBackendTexture& backendTexture) {
2048 fBackendTexture = backendTexture;
2049 }
2050
2051 const GrBackendTexture& backendTexture() const { return fBackendTexture; }
2052
2053 private:
2054 GrContext* fContext;
2055 GrBackendTexture fBackendTexture;
2056
2057 typedef SkRefCnt INHERITED;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002058 };
2059
Robert Phillipsa479f962018-04-10 11:45:40 -04002060 // This is the information extracted into this class from the parsing of the skp file.
2061 // Once it has all been uploaded to the GPU and distributed to the promise images, it
2062 // is all dropped via "reset".
2063 class PromiseImageInfo {
2064 public:
2065 int fIndex; // index in the 'fImageInfo' array
2066 uint32_t fOriginalUniqueID; // original ID for deduping
2067 SkBitmap fBitmap; // CPU-side cache of the contents
2068 sk_sp<PromiseImageCallbackContext> fCallbackContext;
2069 };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002070
Robert Phillipsa479f962018-04-10 11:45:40 -04002071 PromiseImageHelper() { }
2072
2073 void reset() { fImageInfo.reset(); }
Robert Phillips33f02ed2018-03-27 08:06:57 -04002074
2075 bool isValidID(int id) const {
2076 return id >= 0 && id < fImageInfo.count();
2077 }
2078
Robert Phillipsa479f962018-04-10 11:45:40 -04002079 const PromiseImageInfo& getInfo(int id) const {
2080 return fImageInfo[id];
Robert Phillips33f02ed2018-03-27 08:06:57 -04002081 }
2082
2083 // returns -1 on failure
2084 int findOrDefineImage(SkImage* image) {
2085 int preExistingID = this->findImage(image);
2086 if (preExistingID >= 0) {
2087 SkASSERT(this->isValidID(preExistingID));
2088 return preExistingID;
2089 }
2090
2091 int newID = this->addImage(image);
2092 SkASSERT(this->isValidID(newID));
2093 return newID;
2094 }
2095
2096 void uploadAllToGPU(GrContext* context) {
2097 GrGpu* gpu = context->contextPriv().getGpu();
2098 SkASSERT(gpu);
2099
2100 for (int i = 0; i < fImageInfo.count(); ++i) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002101 sk_sp<PromiseImageCallbackContext> callbackContext(
2102 new PromiseImageCallbackContext(context));
2103
Robert Phillipsc186e172018-04-17 16:09:28 -04002104 const PromiseImageInfo& info = fImageInfo[i];
2105
Robert Phillips33f02ed2018-03-27 08:06:57 -04002106 // DDL TODO: how can we tell if we need mipmapping!
Robert Phillipsa479f962018-04-10 11:45:40 -04002107 callbackContext->setBackendTexture(gpu->createTestingOnlyBackendTexture(
Robert Phillipsc186e172018-04-17 16:09:28 -04002108 info.fBitmap.getPixels(),
2109 info.fBitmap.width(),
2110 info.fBitmap.height(),
2111 info.fBitmap.colorType(),
Greg Daniel57bf4a32018-04-19 10:28:37 -04002112 info.fBitmap.colorSpace(),
Robert Phillipsa479f962018-04-10 11:45:40 -04002113 false, GrMipMapped::kNo));
2114 // The GMs sometimes request too large an image
2115 //SkAssertResult(callbackContext->backendTexture().isValid());
Robert Phillips33f02ed2018-03-27 08:06:57 -04002116
Robert Phillipsa479f962018-04-10 11:45:40 -04002117 // The fImageInfo array gets the creation ref
2118 fImageInfo[i].fCallbackContext = std::move(callbackContext);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002119 }
2120 }
2121
2122 static void PromiseImageFulfillProc(void* textureContext, GrBackendTexture* outTexture) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002123 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2124 SkASSERT(callbackContext->backendTexture().isValid());
2125 *outTexture = callbackContext->backendTexture();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002126 }
2127
2128 static void PromiseImageReleaseProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002129#ifdef SK_DEBUG
2130 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2131 SkASSERT(callbackContext->backendTexture().isValid());
2132#endif
Robert Phillips33f02ed2018-03-27 08:06:57 -04002133 }
2134
2135 static void PromiseImageDoneProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002136 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2137 callbackContext->unref();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002138 }
2139
2140private:
2141 // returns -1 if not found
2142 int findImage(SkImage* image) const {
2143 for (int i = 0; i < fImageInfo.count(); ++i) {
2144 if (fImageInfo[i].fOriginalUniqueID == image->uniqueID()) {
2145 SkASSERT(fImageInfo[i].fIndex == i);
2146 SkASSERT(this->isValidID(i) && this->isValidID(fImageInfo[i].fIndex));
2147 return i;
2148 }
2149 }
2150 return -1;
2151 }
2152
2153 // returns -1 on failure
2154 int addImage(SkImage* image) {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002155 sk_sp<SkImage> rasterImage = image->makeRasterImage(); // force decoding of lazy images
2156
2157 SkImageInfo ii = SkImageInfo::Make(rasterImage->width(), rasterImage->height(),
2158 rasterImage->colorType(), rasterImage->alphaType(),
2159 rasterImage->refColorSpace());
2160
2161 SkBitmap bm;
2162 bm.allocPixels(ii);
2163
2164 if (!rasterImage->readPixels(bm.pixmap(), 0, 0)) {
2165 return -1;
2166 }
2167
2168 bm.setImmutable();
2169
2170 PromiseImageInfo newImageInfo;
2171 newImageInfo.fIndex = fImageInfo.count();
2172 newImageInfo.fOriginalUniqueID = image->uniqueID();
2173 newImageInfo.fBitmap = bm;
Robert Phillipsa479f962018-04-10 11:45:40 -04002174 /* fCallbackContext is filled in by uploadAllToGPU */
Robert Phillips33f02ed2018-03-27 08:06:57 -04002175
2176 fImageInfo.push_back(newImageInfo);
2177 SkASSERT(newImageInfo.fIndex == fImageInfo.count()-1);
2178 return fImageInfo.count()-1;
2179 }
2180
2181 SkTArray<PromiseImageInfo> fImageInfo;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002182};
2183
2184// TileData class encapsulates the information and behavior for a single tile/thread in
2185// a DDL rendering.
2186class ViaDDL::TileData {
2187public:
2188 // Note: we could just pass in surface characterization
2189 TileData(sk_sp<SkSurface> surf, const SkIRect& clip)
2190 : fSurface(std::move(surf))
2191 , fClip(clip) {
2192 SkAssertResult(fSurface->characterize(&fCharacterization));
2193 }
2194
2195 // This method operates in parallel
2196 // In each thread we will reconvert the compressedPictureData into an SkPicture
2197 // replacing each image-index with a promise image.
2198 void preprocess(SkData* compressedPictureData, const PromiseImageHelper& helper) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002199
Robert Phillips33f02ed2018-03-27 08:06:57 -04002200 SkDeferredDisplayListRecorder recorder(fCharacterization);
2201
2202 // DDL TODO: the DDLRecorder's GrContext isn't initialized until getCanvas is called.
2203 // Maybe set it up in the ctor?
2204 SkCanvas* subCanvas = recorder.getCanvas();
2205
2206 sk_sp<SkPicture> reconstitutedPicture;
2207
2208 {
Robert Phillipsa479f962018-04-10 11:45:40 -04002209 PerRecorderContext perRecorderContext { &recorder, &helper };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002210
2211 SkDeserialProcs procs;
Robert Phillipsa479f962018-04-10 11:45:40 -04002212 procs.fImageCtx = (void*) &perRecorderContext;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002213 procs.fImageProc = PromiseImageCreator;
2214
2215 reconstitutedPicture = SkPicture::MakeFromData(compressedPictureData, &procs);
2216 if (!reconstitutedPicture) {
2217 return;
2218 }
2219 }
2220
2221 subCanvas->clipRect(SkRect::MakeWH(fClip.width(), fClip.height()));
2222 subCanvas->translate(-fClip.fLeft, -fClip.fTop);
2223
2224 // Note: in this use case we only render a picture to the deferred canvas
2225 // but, more generally, clients will use arbitrary draw calls.
2226 subCanvas->drawPicture(reconstitutedPicture);
2227
2228 fDisplayList = recorder.detach();
2229 }
2230
2231 // This method operates serially and replays the recorded DDL into the tile surface.
2232 void draw() {
2233 fSurface->draw(fDisplayList.get());
2234 }
2235
2236 // This method also operates serially and composes the results of replaying the DDL into
2237 // the final destination surface.
2238 void compose(SkCanvas* dst) {
2239 sk_sp<SkImage> img = fSurface->makeImageSnapshot();
2240 dst->save();
2241 dst->clipRect(SkRect::Make(fClip));
2242 dst->drawImage(std::move(img), fClip.fLeft, fClip.fTop);
2243 dst->restore();
2244 }
2245
2246private:
Robert Phillipsa479f962018-04-10 11:45:40 -04002247 // This stack-based context allows each thread to re-inflate the image indices into
2248 // promise images while still using the same GrBackendTexture.
2249 struct PerRecorderContext {
2250 SkDeferredDisplayListRecorder* fRecorder;
2251 const PromiseImageHelper* fHelper;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002252 };
2253
2254 // This generates promise images to replace the indices in the compressed picture. This
Robert Phillipsa479f962018-04-10 11:45:40 -04002255 // reconstitution is performed separately in each thread so we end up with multiple
2256 // promise images referring to the same GrBackendTexture.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002257 static sk_sp<SkImage> PromiseImageCreator(const void* rawData, size_t length, void* ctxIn) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002258 PerRecorderContext* perRecorderContext = static_cast<PerRecorderContext*>(ctxIn);
2259 const PromiseImageHelper* helper = perRecorderContext->fHelper;
2260 SkDeferredDisplayListRecorder* recorder = perRecorderContext->fRecorder;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002261
2262 SkASSERT(length == sizeof(int));
2263
2264 const int* indexPtr = static_cast<const int*>(rawData);
2265 SkASSERT(helper->isValidID(*indexPtr));
2266
Robert Phillipsa479f962018-04-10 11:45:40 -04002267 const PromiseImageHelper::PromiseImageInfo& curImage = helper->getInfo(*indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002268
Robert Phillipsa479f962018-04-10 11:45:40 -04002269 if (!curImage.fCallbackContext->backendTexture().isValid()) {
Robert Phillipsc186e172018-04-17 16:09:28 -04002270 // We weren't able to make a backend texture for this SkImage. In this case we create
2271 // a separate bitmap-backed image for each thread.
2272 // Note: we would like to share the same bitmap between all the threads but
2273 // SkBitmap is not thread-safe.
2274 return SkImage::MakeRasterCopy(curImage.fBitmap.pixmap());
Robert Phillipsa479f962018-04-10 11:45:40 -04002275 }
2276 SkASSERT(curImage.fIndex == *indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002277
Robert Phillipsa479f962018-04-10 11:45:40 -04002278 GrBackendFormat backendFormat = curImage.fCallbackContext->backendTexture().format();
2279
2280 // Each DDL recorder gets its own ref on the promise callback context for the
2281 // promise images it creates.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002282 // DDL TODO: sort out mipmapping
2283 sk_sp<SkImage> image = recorder->makePromiseTexture(
Robert Phillipsa479f962018-04-10 11:45:40 -04002284 backendFormat,
2285 curImage.fBitmap.width(),
2286 curImage.fBitmap.height(),
2287 GrMipMapped::kNo,
2288 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
2289 curImage.fBitmap.colorType(),
2290 curImage.fBitmap.alphaType(),
2291 curImage.fBitmap.refColorSpace(),
2292 PromiseImageHelper::PromiseImageFulfillProc,
2293 PromiseImageHelper::PromiseImageReleaseProc,
2294 PromiseImageHelper::PromiseImageDoneProc,
2295 (void*) SkSafeRef(curImage.fCallbackContext.get()));
Robert Phillips33f02ed2018-03-27 08:06:57 -04002296 SkASSERT(image);
2297 return image;
2298 }
2299
2300 sk_sp<SkSurface> fSurface;
2301 SkIRect fClip; // in the device space of the dest canvas
2302 std::unique_ptr<SkDeferredDisplayList> fDisplayList;
2303 SkSurfaceCharacterization fCharacterization;
2304};
2305
2306Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2307 auto size = src.size();
2308 SkPictureRecorder recorder;
2309 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2310 SkIntToScalar(size.height())));
2311 if (!err.isEmpty()) {
2312 return err;
2313 }
2314 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
2315
2316 // this is our ultimate final drawing area/rect
2317 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
2318
2319 PromiseImageHelper helper;
2320 sk_sp<SkData> compressedPictureData;
2321
2322 // Convert the SkPicture into SkData replacing all the SkImages with an index.
2323 {
2324 SkSerialProcs procs;
2325
2326 procs.fImageCtx = &helper;
2327 procs.fImageProc = [](SkImage* image, void* ctx) -> sk_sp<SkData> {
2328 auto helper = static_cast<PromiseImageHelper*>(ctx);
2329
2330 int id = helper->findOrDefineImage(image);
2331 if (id >= 0) {
2332 SkASSERT(helper->isValidID(id));
2333 return SkData::MakeWithCopy(&id, sizeof(id));
2334 }
2335
2336 return nullptr;
2337 };
2338
2339 compressedPictureData = inputPicture->serialize(&procs);
2340 if (!compressedPictureData) {
2341 return SkStringPrintf("ViaDDL: Couldn't deflate SkPicture");
2342 }
2343 }
2344
Robert Phillips33f02ed2018-03-27 08:06:57 -04002345 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2346 [&](SkCanvas* canvas) -> Error {
2347 GrContext* context = canvas->getGrContext();
2348 if (!context || !context->contextPriv().getGpu()) {
2349 return SkStringPrintf("DDLs are GPU only");
2350 }
2351
Robert Phillipsa479f962018-04-10 11:45:40 -04002352 // This is here bc this is the first point where we have access to the context
Robert Phillips33f02ed2018-03-27 08:06:57 -04002353 helper.uploadAllToGPU(context);
2354
2355 int xTileSize = viewport.width()/fNumDivisions;
2356 int yTileSize = viewport.height()/fNumDivisions;
2357
2358 SkTArray<TileData> tileData;
2359 tileData.reserve(fNumDivisions*fNumDivisions);
2360
2361 // First, create the destination tiles
2362 for (int y = 0, yOff = 0; y < fNumDivisions; ++y, yOff += yTileSize) {
2363 int ySize = (y < fNumDivisions-1) ? yTileSize : viewport.height()-yOff;
2364
2365 for (int x = 0, xOff = 0; x < fNumDivisions; ++x, xOff += xTileSize) {
2366 int xSize = (x < fNumDivisions-1) ? xTileSize : viewport.width()-xOff;
2367
2368 SkIRect clip = SkIRect::MakeXYWH(xOff, yOff, xSize, ySize);
2369
2370 SkASSERT(viewport.contains(clip));
2371
2372 SkImageInfo tileII = SkImageInfo::MakeN32Premul(xSize, ySize);
2373
2374 tileData.push_back(TileData(canvas->makeSurface(tileII), clip));
2375 }
2376 }
2377
2378 // Second, run the cpu pre-processing in threads
2379 SkTaskGroup().batch(tileData.count(), [&](int i) {
2380 tileData[i].preprocess(compressedPictureData.get(), helper);
2381 });
2382
Robert Phillipsa479f962018-04-10 11:45:40 -04002383 // This drops the helper's refs on all the promise images
2384 helper.reset();
2385
Robert Phillips33f02ed2018-03-27 08:06:57 -04002386 // Third, synchronously render the display lists into the dest tiles
2387 // TODO: it would be cool to not wait until all the tiles are drawn to begin
2388 // drawing to the GPU and composing to the final surface
2389 for (int i = 0; i < tileData.count(); ++i) {
2390 tileData[i].draw();
2391 }
2392
2393 // Finally, compose the drawn tiles into the result
2394 // Note: the separation between the tiles and the final composition better
2395 // matches Chrome but costs us a copy
2396 for (int i = 0; i < tileData.count(); ++i) {
2397 tileData[i].compose(canvas);
2398 }
2399
Robert Phillipscc473352018-03-27 10:46:00 -04002400 context->flush();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002401 return "";
2402 });
2403}
2404
2405#else
2406
2407ViaDDL::ViaDDL(int numDivisions, Sink* sink) : Via(sink) { }
2408
2409Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2410 return "ViaDDL is GPU only";
2411}
2412
2413#endif
2414
2415/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2416
mtklein4a34ecb2016-01-08 10:19:35 -08002417Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2418 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002419 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtklein4a34ecb2016-01-08 10:19:35 -08002420 SkPictureRecorder recorder;
reedca2622b2016-03-18 07:25:55 -07002421 sk_sp<SkPicture> pic;
mtklein4a34ecb2016-01-08 10:19:35 -08002422 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2423 SkIntToScalar(size.height())));
2424 if (!err.isEmpty()) {
2425 return err;
2426 }
reedca2622b2016-03-18 07:25:55 -07002427 pic = recorder.finishRecordingAsPicture();
mtklein4a34ecb2016-01-08 10:19:35 -08002428 canvas->drawPicture(pic);
Ben Wagner1861e882018-04-04 17:40:46 -04002429 return err;
mtklein4a34ecb2016-01-08 10:19:35 -08002430 });
Ben Wagner1861e882018-04-04 17:40:46 -04002431 if (!err.isEmpty()) {
2432 return err;
2433 }
2434
2435 return check_against_reference(bitmap, src, fSink.get());
mtklein4a34ecb2016-01-08 10:19:35 -08002436}
2437
2438/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2439
reed54dc4872016-09-13 08:09:45 -07002440Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2441 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002442 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
reed54dc4872016-09-13 08:09:45 -07002443 SkDynamicMemoryWStream tmpStream;
2444 Error err = src.draw(SkPipeSerializer().beginWrite(SkRect::Make(size), &tmpStream));
2445 if (!err.isEmpty()) {
2446 return err;
2447 }
2448 sk_sp<SkData> data = tmpStream.detachAsData();
2449 SkPipeDeserializer().playback(data->data(), data->size(), canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002450 return err;
reed54dc4872016-09-13 08:09:45 -07002451 });
Ben Wagner1861e882018-04-04 17:40:46 -04002452 if (!err.isEmpty()) {
2453 return err;
2454 }
2455
2456 return check_against_reference(bitmap, src, fSink.get());
reed54dc4872016-09-13 08:09:45 -07002457}
2458
2459/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2460
Mike Reedbae888e2017-02-18 16:50:45 -05002461#ifdef TEST_VIA_SVG
Mike Reedf67c4592017-02-17 17:06:11 -05002462#include "SkXMLWriter.h"
2463#include "SkSVGCanvas.h"
2464#include "SkSVGDOM.h"
2465
2466Error ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2467 auto size = src.size();
2468 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
2469 SkDynamicMemoryWStream wstream;
2470 SkXMLStreamWriter writer(&wstream);
2471 Error err = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
2472 if (!err.isEmpty()) {
2473 return err;
2474 }
2475 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2476 auto dom = SkSVGDOM::MakeFromStream(*rstream);
2477 if (dom) {
2478 dom->setContainerSize(SkSize::Make(size));
2479 dom->render(canvas);
2480 }
2481 return "";
2482 });
2483}
Mike Reedbae888e2017-02-18 16:50:45 -05002484#endif
Mike Reedf67c4592017-02-17 17:06:11 -05002485
2486/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2487
mtklein9c5052f2016-08-06 12:51:51 -07002488Error ViaLite::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2489 auto size = src.size();
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002490 SkIRect bounds = {0,0, size.width(), size.height()};
Ben Wagner1861e882018-04-04 17:40:46 -04002491 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002492 SkLiteDL dl;
mtklein8bbbb692016-08-15 12:56:00 -07002493 SkLiteRecorder rec;
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002494 rec.reset(&dl, bounds);
mtklein8bbbb692016-08-15 12:56:00 -07002495
2496 Error err = src.draw(&rec);
mtklein9c5052f2016-08-06 12:51:51 -07002497 if (!err.isEmpty()) {
2498 return err;
2499 }
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002500 dl.draw(canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002501 return err;
mtklein9c5052f2016-08-06 12:51:51 -07002502 });
Ben Wagner1861e882018-04-04 17:40:46 -04002503 if (!err.isEmpty()) {
2504 return err;
2505 }
2506
2507 return check_against_reference(bitmap, src, fSink.get());
mtklein9c5052f2016-08-06 12:51:51 -07002508}
2509
Mike Klein841101d2017-03-10 09:55:51 -05002510/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2511
Mike Klein919cc452017-03-18 15:36:52 +00002512ViaCSXform::ViaCSXform(Sink* sink, sk_sp<SkColorSpace> cs, bool colorSpin)
2513 : Via(sink)
2514 , fCS(std::move(cs))
2515 , fColorSpin(colorSpin) {}
Mike Klein841101d2017-03-10 09:55:51 -05002516
2517Error ViaCSXform::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2518 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
2519 [&](SkCanvas* canvas) -> Error {
Brian Osman5b7e4702017-10-31 16:41:29 -04002520 {
2521 SkAutoCanvasRestore acr(canvas, true);
2522 auto proxy = SkCreateColorSpaceXformCanvas(canvas, fCS);
2523 Error err = src.draw(proxy.get());
2524 if (!err.isEmpty()) {
2525 return err;
2526 }
Mike Klein919cc452017-03-18 15:36:52 +00002527 }
2528
2529 // Undo the color spin, so we can look at the pixels in Gold.
2530 if (fColorSpin) {
2531 SkBitmap pixels;
2532 pixels.allocPixels(canvas->imageInfo());
Mike Reed12e946b2017-04-17 10:53:29 -04002533 canvas->readPixels(pixels, 0, 0);
Mike Klein919cc452017-03-18 15:36:52 +00002534
Brian Osman5b7e4702017-10-31 16:41:29 -04002535 SkPaint rotateColors;
2536 SkScalar matrix[20] = { 0, 0, 1, 0, 0, // B -> R
2537 1, 0, 0, 0, 0, // R -> G
2538 0, 1, 0, 0, 0, // G -> B
2539 0, 0, 0, 1, 0 };
2540 rotateColors.setBlendMode(SkBlendMode::kSrc);
2541 rotateColors.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(matrix));
2542 canvas->drawBitmap(pixels, 0, 0, &rotateColors);
Mike Klein919cc452017-03-18 15:36:52 +00002543 }
2544
2545 return "";
Mike Klein841101d2017-03-10 09:55:51 -05002546 });
2547}
2548
mtklein748ca3b2015-01-15 10:56:12 -08002549} // namespace DM