blob: 6a14c6363c89d14efd4603c28ab8937b34c4f4d4 [file] [log] [blame]
scroggo478652e2015-03-25 07:11:02 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
mtklein748ca3b2015-01-15 10:56:12 -08008#include "DMSrcSink.h"
Brian Salomonf865b052018-03-09 09:01:53 -05009#include <cmath>
10#include <functional>
11#include "../src/jumper/SkJumper.h"
msarett9876ac52016-06-01 14:47:18 -070012#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -070013#include "SkAndroidCodec.h"
Hal Canary95e3c052017-01-11 12:44:43 -050014#include "SkAutoMalloc.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040015#include "SkBase64.h"
scroggof24f2242015-03-03 08:59:20 -080016#include "SkCodec.h"
msarettb714fb02016-01-22 14:46:42 -080017#include "SkCodecImageGenerator.h"
msarett888dc162016-05-23 10:21:17 -070018#include "SkColorSpace.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000019#include "SkColorSpaceXform.h"
Mike Klein841101d2017-03-10 09:55:51 -050020#include "SkColorSpaceXformCanvas.h"
Hal Canary95e3c052017-01-11 12:44:43 -050021#include "SkColorSpace_XYZ.h"
mtkleina16e69e2015-05-05 11:38:45 -070022#include "SkCommonFlags.h"
Chris Dalton040238b2017-12-18 14:22:34 -070023#include "SkCommonFlagsGpu.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070024#include "SkData.h"
Hal Canary85c7fe82016-10-25 10:33:27 -040025#include "SkDebugCanvas.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040026#include "SkDeferredDisplayListRecorder.h"
mtklein748ca3b2015-01-15 10:56:12 -080027#include "SkDocument.h"
Brian Osmanf9810662017-08-30 10:02:10 -040028#include "SkExecutor.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070029#include "SkImageGenerator.h"
msarett18976312016-03-09 14:20:58 -080030#include "SkImageGeneratorCG.h"
msarettfc0b6d12016-03-17 13:50:17 -070031#include "SkImageGeneratorWIC.h"
Mike Reed7fcfb622018-02-09 13:26:46 -050032#include "SkImageInfoPriv.h"
mtklein8bbbb692016-08-15 12:56:00 -070033#include "SkLiteDL.h"
34#include "SkLiteRecorder.h"
mtkleinc8be09a2016-01-04 18:56:57 -080035#include "SkMallocPixelRef.h"
Hal Canary45cde312017-04-03 16:06:42 -040036#include "SkMultiPictureDocumentPriv.h"
mtklein748ca3b2015-01-15 10:56:12 -080037#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080038#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080039#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050040#include "SkOSPath.h"
msarett9e9444c2016-02-03 12:39:10 -080041#include "SkOpts.h"
Mike Reede7a58322017-12-20 14:09:20 -050042#include "SkPictureCommon.h"
mtkleinffa901a2015-03-16 10:38:07 -070043#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080044#include "SkPictureRecorder.h"
reed54dc4872016-09-13 08:09:45 -070045#include "SkPipe.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040046#include "SkPngEncoder.h"
mtklein748ca3b2015-01-15 10:56:12 -080047#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070048#include "SkRecordDraw.h"
49#include "SkRecorder.h"
scroggoa1193e42015-01-21 12:09:53 -080050#include "SkStream.h"
Brian Salomonf865b052018-03-09 09:01:53 -050051#include "SkSurfaceCharacterization.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000052#include "SkSwizzler.h"
Brian Salomonf865b052018-03-09 09:01:53 -050053#include "SkTLogic.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040054#include "SkTaskGroup.h"
Yuqian Lib8b62532018-02-23 14:13:36 +080055#include "SkThreadedBMPDevice.h"
msarettfc0b6d12016-03-17 13:50:17 -070056#if defined(SK_BUILD_FOR_WIN)
57 #include "SkAutoCoInitialize.h"
Hal Canary5e221e72017-02-06 09:51:42 -050058 #include "SkHRESULT.h"
59 #include "SkTScopedComPtr.h"
60 #include <XpsObjectModel.h>
msarettfc0b6d12016-03-17 13:50:17 -070061#endif
62
Florin Malita124d5af2017-12-31 17:02:26 -050063#if !defined(SK_BUILD_FOR_GOOGLE3)
Florin Malita54f65c42018-01-16 17:04:30 -050064 #include "Skottie.h"
Florin Malita124d5af2017-12-31 17:02:26 -050065#endif
66
fmalita718df0a2016-07-15 10:33:29 -070067#if defined(SK_XML)
Ben Wagner6ce482a2018-03-27 10:57:43 -040068 #include "SkSVGCanvas.h"
fmalitaa48f0e32016-08-04 06:26:05 -070069 #include "SkSVGDOM.h"
fmalita718df0a2016-07-15 10:33:29 -070070 #include "SkXMLWriter.h"
71#endif
72
Robert Phillips0c4b7b12018-03-06 08:20:37 -050073#if SK_SUPPORT_GPU
Brian Salomonf865b052018-03-09 09:01:53 -050074#include "GrBackendSurface.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050075#include "GrContextPriv.h"
Brian Salomonf865b052018-03-09 09:01:53 -050076#include "GrGpu.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050077#endif
78
halcanary7e798182015-04-14 14:06:18 -070079DEFINE_bool(multiPage, false, "For document-type backends, render the source"
80 " into multiple pages");
scroggo3ac66e92016-02-08 15:09:48 -080081DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
halcanary7e798182015-04-14 14:06:18 -070082
bsalomon3724e572016-03-30 18:56:19 -070083using sk_gpu_test::GrContextFactory;
84
mtklein748ca3b2015-01-15 10:56:12 -080085namespace DM {
86
mtklein748ca3b2015-01-15 10:56:12 -080087GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
88
89Error GMSrc::draw(SkCanvas* canvas) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040090 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080091 gm->draw(canvas);
92 return "";
93}
94
95SkISize GMSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040096 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080097 return gm->getISize();
98}
99
100Name GMSrc::name() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400101 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -0800102 return gm->getName();
103}
104
bsalomon4ee6bd82015-05-27 13:23:23 -0700105void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400106 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -0700107 gm->modifyGrContextOptions(options);
108}
109
mtklein748ca3b2015-01-15 10:56:12 -0800110/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
111
msarettd1227a72016-05-18 06:23:57 -0700112BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
msaretta5783ae2015-09-08 15:35:32 -0700113 : fPath(path)
msaretta5783ae2015-09-08 15:35:32 -0700114 , fMode(mode)
115 , fDstColorType(dstColorType)
116 , fSampleSize(sampleSize)
117{}
118
119bool BRDSrc::veto(SinkFlags flags) const {
120 // No need to test to non-raster or indirect backends.
121 return flags.type != SinkFlags::kRaster
122 || flags.approach != SinkFlags::kDirect;
123}
124
msarettd1227a72016-05-18 06:23:57 -0700125static SkBitmapRegionDecoder* create_brd(Path path) {
bungeman38d909e2016-08-02 14:40:46 -0700126 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
msaretta5783ae2015-09-08 15:35:32 -0700127 if (!encoded) {
Ben Wagnera93a14a2017-08-28 10:34:05 -0400128 return nullptr;
msaretta5783ae2015-09-08 15:35:32 -0700129 }
reed42943c82016-09-12 12:01:44 -0700130 return SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy);
msaretta5783ae2015-09-08 15:35:32 -0700131}
132
Matt Sarett334df3a2016-12-15 18:17:33 -0500133static inline void alpha8_to_gray8(SkBitmap* bitmap) {
134 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
135 // them back to kGray8 so our test framework can draw them correctly.
136 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
137 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
138 .makeAlphaType(kOpaque_SkAlphaType);
139 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
140 }
141}
142
msaretta5783ae2015-09-08 15:35:32 -0700143Error BRDSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400144 if (canvas->imageInfo().colorSpace() &&
145 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
146 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
147 // run these tests on legacy canvases.
148 // We allow an exception for F16, since Android uses F16.
149 return Error::Nonfatal("Skip testing to color correct canvas.");
150 }
151
msaretta5783ae2015-09-08 15:35:32 -0700152 SkColorType colorType = canvas->imageInfo().colorType();
153 if (kRGB_565_SkColorType == colorType &&
154 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
155 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
156 }
157 switch (fDstColorType) {
158 case CodecSrc::kGetFromCanvas_DstColorType:
159 break;
msaretta5783ae2015-09-08 15:35:32 -0700160 case CodecSrc::kGrayscale_Always_DstColorType:
161 colorType = kGray_8_SkColorType;
162 break;
msarett34e0ec42016-04-22 16:27:24 -0700163 default:
164 SkASSERT(false);
165 break;
msaretta5783ae2015-09-08 15:35:32 -0700166 }
167
Ben Wagner145dbcd2016-11-03 14:40:50 -0400168 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700169 if (nullptr == brd.get()) {
170 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
171 }
172
Leon Scroggins III0118e972018-03-13 11:14:33 -0400173 auto recommendedCT = brd->computeOutputColorType(colorType);
174 if (kRGB_565_SkColorType == colorType && recommendedCT != colorType) {
175 return Error::Nonfatal("Skip decoding non-opaque to 565.");
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400176 }
Leon Scroggins III0118e972018-03-13 11:14:33 -0400177 colorType = recommendedCT;
178
179 auto colorSpace = brd->computeOutputColorSpace(colorType, nullptr);
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400180
msaretta5783ae2015-09-08 15:35:32 -0700181 const uint32_t width = brd->width();
182 const uint32_t height = brd->height();
183 // Visually inspecting very small output images is not necessary.
184 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
185 return Error::Nonfatal("Scaling very small images is uninteresting.");
186 }
187 switch (fMode) {
188 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700189 SkBitmap bitmap;
190 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
Leon Scroggins III0118e972018-03-13 11:14:33 -0400191 fSampleSize, colorType, false, colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800192 return "Cannot decode (full) region.";
msarett35e5d1b2015-10-27 12:50:25 -0700193 }
Matt Sarett334df3a2016-12-15 18:17:33 -0500194 alpha8_to_gray8(&bitmap);
Matt Sarett8db74f12017-06-14 13:02:05 +0000195
msarett35e5d1b2015-10-27 12:50:25 -0700196 canvas->drawBitmap(bitmap, 0, 0);
msaretta5783ae2015-09-08 15:35:32 -0700197 return "";
198 }
199 case kDivisor_Mode: {
200 const uint32_t divisor = 2;
201 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800202 return Error::Nonfatal("Divisor is larger than image dimension.");
msaretta5783ae2015-09-08 15:35:32 -0700203 }
204
205 // Use a border to test subsets that extend outside the image.
206 // We will not allow the border to be larger than the image dimensions. Allowing
207 // these large borders causes off by one errors that indicate a problem with the
208 // test suite, not a problem with the implementation.
209 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
210 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
211 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
212
213 // We may need to clear the canvas to avoid uninitialized memory.
214 // Assume we are scaling a 780x780 image with sampleSize = 8.
215 // The output image should be 97x97.
216 // Each subset will be 390x390.
217 // Each scaled subset be 48x48.
218 // Four scaled subsets will only fill a 96x96 image.
219 // The bottom row and last column will not be touched.
220 // This is an unfortunate result of our rounding rules when scaling.
221 // Maybe we need to consider testing scaled subsets without trying to
222 // combine them to match the full scaled image? Or maybe this is the
223 // best we can do?
224 canvas->clear(0);
225
226 for (uint32_t x = 0; x < divisor; x++) {
227 for (uint32_t y = 0; y < divisor; y++) {
228 // Calculate the subset dimensions
229 uint32_t subsetWidth = width / divisor;
230 uint32_t subsetHeight = height / divisor;
231 const int left = x * subsetWidth;
232 const int top = y * subsetHeight;
233
234 // Increase the size of the last subset in each row or column, when the
235 // divisor does not divide evenly into the image dimensions
236 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
237 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
238
239 // Increase the size of the subset in order to have a border on each side
240 const int decodeLeft = left - unscaledBorder;
241 const int decodeTop = top - unscaledBorder;
242 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
243 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700244 SkBitmap bitmap;
245 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
Matt Sarett68feef42017-04-11 09:51:32 -0400246 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
Leon Scroggins III0118e972018-03-13 11:14:33 -0400247 colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800248 return "Cannot decode region.";
msarett35e5d1b2015-10-27 12:50:25 -0700249 }
msaretta5783ae2015-09-08 15:35:32 -0700250
Matt Sarett334df3a2016-12-15 18:17:33 -0500251 alpha8_to_gray8(&bitmap);
msarett35e5d1b2015-10-27 12:50:25 -0700252 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700253 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
254 (SkScalar) (subsetWidth / fSampleSize),
255 (SkScalar) (subsetHeight / fSampleSize)),
256 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
257 (SkScalar) (top / fSampleSize),
258 (SkScalar) (subsetWidth / fSampleSize),
259 (SkScalar) (subsetHeight / fSampleSize)),
260 nullptr);
261 }
262 }
263 return "";
264 }
265 default:
266 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800267 return "Error: Should not be reached.";
msaretta5783ae2015-09-08 15:35:32 -0700268 }
269}
270
271SkISize BRDSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400272 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700273 if (brd) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400274 return {SkTMax(1, brd->width() / (int)fSampleSize),
275 SkTMax(1, brd->height() / (int)fSampleSize)};
msaretta5783ae2015-09-08 15:35:32 -0700276 }
Hal Canaryfafe1352017-04-11 12:12:02 -0400277 return {0, 0};
msaretta5783ae2015-09-08 15:35:32 -0700278}
279
280static SkString get_scaled_name(const Path& path, float scale) {
281 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
282}
283
284Name BRDSrc::name() const {
285 // We will replicate the names used by CodecSrc so that images can
286 // be compared in Gold.
287 if (1 == fSampleSize) {
288 return SkOSPath::Basename(fPath.c_str());
289 }
msarett4b0778e2015-11-13 09:59:11 -0800290 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700291}
292
293/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
294
scroggo3ac66e92016-02-08 15:09:48 -0800295static bool serial_from_path_name(const SkString& path) {
296 if (!FLAGS_RAW_threading) {
297 static const char* const exts[] = {
298 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
299 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
300 };
301 const char* actualExt = strrchr(path.c_str(), '.');
302 if (actualExt) {
303 actualExt++;
304 for (auto* ext : exts) {
305 if (0 == strcmp(ext, actualExt)) {
306 return true;
307 }
308 }
309 }
310 }
311 return false;
312}
313
scroggoc5560be2016-02-03 09:42:42 -0800314CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
315 float scale)
msarett438b2ad2015-04-09 12:43:10 -0700316 : fPath(path)
317 , fMode(mode)
318 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800319 , fDstAlphaType(dstAlphaType)
msarett0a242972015-06-11 14:27:27 -0700320 , fScale(scale)
scroggo3ac66e92016-02-08 15:09:48 -0800321 , fRunSerially(serial_from_path_name(path))
msarett438b2ad2015-04-09 12:43:10 -0700322{}
mtklein748ca3b2015-01-15 10:56:12 -0800323
mtklein99cab4e2015-07-31 06:43:04 -0700324bool CodecSrc::veto(SinkFlags flags) const {
msarett18976312016-03-09 14:20:58 -0800325 // Test to direct raster backends (8888 and 565).
msarettb714fb02016-01-22 14:46:42 -0800326 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700327}
scroggo9b77ddd2015-03-19 06:03:39 -0700328
msarett34e0ec42016-04-22 16:27:24 -0700329// Allows us to test decodes to non-native 8888.
msarettb1be46b2016-05-17 08:52:11 -0700330static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700331 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
332 return;
333 }
334
335 for (int y = 0; y < bitmap.height(); y++) {
336 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
337 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
338 }
339}
340
msarett9e9444c2016-02-03 12:39:10 -0800341// FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
342// This allows us to still test unpremultiplied decodes.
msarettb1be46b2016-05-17 08:52:11 -0700343static void premultiply_if_necessary(SkBitmap& bitmap) {
msarett9e9444c2016-02-03 12:39:10 -0800344 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
345 return;
346 }
347
348 switch (bitmap.colorType()) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400349 case kRGBA_F16_SkColorType: {
350 SkJumper_MemoryCtx ctx = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
351 SkRasterPipeline_<256> p;
352 p.append(SkRasterPipeline::load_f16, &ctx);
353 p.append(SkRasterPipeline::premul);
354 p.append(SkRasterPipeline::store_f16, &ctx);
355 p.run(0,0, bitmap.width(), bitmap.height());
356 }
Leon Scroggins IIIeceee042017-05-23 16:58:09 -0400357 break;
msarett9e9444c2016-02-03 12:39:10 -0800358 case kN32_SkColorType:
359 for (int y = 0; y < bitmap.height(); y++) {
360 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
361 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
362 }
363 break;
msarett9e9444c2016-02-03 12:39:10 -0800364 default:
365 // No need to premultiply kGray or k565 outputs.
366 break;
367 }
msarette1daa482016-02-03 15:31:18 -0800368
369 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
370 // bitmap as kPremul.
371 bitmap.setAlphaType(kPremul_SkAlphaType);
msarett9e9444c2016-02-03 12:39:10 -0800372}
373
msarettb1be46b2016-05-17 08:52:11 -0700374static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
scroggoba584892016-05-20 13:56:13 -0700375 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
msarett3d9d7a72015-10-21 10:27:10 -0700376 switch (dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700377 case CodecSrc::kGrayscale_Always_DstColorType:
scroggo1a361922016-05-20 14:27:16 -0700378 if (kRGB_565_SkColorType == canvasColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700379 return false;
380 }
scroggoc5560be2016-02-03 09:42:42 -0800381 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700382 break;
msarett34e0ec42016-04-22 16:27:24 -0700383 case CodecSrc::kNonNative8888_Always_DstColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400384 if (kRGB_565_SkColorType == canvasColorType
385 || kRGBA_F16_SkColorType == canvasColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700386 return false;
387 }
388#ifdef SK_PMCOLOR_IS_RGBA
389 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
390#else
391 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
392#endif
393 break;
msarett3d9d7a72015-10-21 10:27:10 -0700394 default:
msarett55f7bdd2016-02-16 13:24:54 -0800395 if (kRGB_565_SkColorType == canvasColorType &&
396 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
397 return false;
398 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800399
400 if (kRGBA_F16_SkColorType == canvasColorType) {
Brian Osman36703d92017-12-12 14:09:31 -0500401 sk_sp<SkColorSpace> linearSpace = decodeInfo->colorSpace()->makeLinearGamma();
Matt Sarett09a1c082017-02-01 15:34:22 -0800402 *decodeInfo = decodeInfo->makeColorSpace(std::move(linearSpace));
403 }
404
scroggoc5560be2016-02-03 09:42:42 -0800405 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700406 break;
407 }
408
scroggoba584892016-05-20 13:56:13 -0700409 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
msarett3d9d7a72015-10-21 10:27:10 -0700410 return true;
411}
412
msarettb1be46b2016-05-17 08:52:11 -0700413static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000414 CodecSrc::DstColorType dstColorType,
msarettb1be46b2016-05-17 08:52:11 -0700415 SkScalar left = 0, SkScalar top = 0) {
msarettb1be46b2016-05-17 08:52:11 -0700416 SkBitmap bitmap;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000417 bitmap.installPixels(info, pixels, rowBytes);
msarettb1be46b2016-05-17 08:52:11 -0700418 premultiply_if_necessary(bitmap);
419 swap_rb_if_necessary(bitmap, dstColorType);
420 canvas->drawBitmap(bitmap, left, top);
421}
422
Matt Sarettf485cf92017-05-26 08:58:03 -0400423// For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
424// color format conversions should be performed by the codec. Sometimes the output of the
425// decode will be in an interesting color space. On our srgb and f16 backends, we need to
426// "pretend" that the color space is standard sRGB to avoid triggering color conversion
427// at draw time.
428static void set_bitmap_color_space(SkImageInfo* info) {
429 if (kRGBA_F16_SkColorType == info->colorType()) {
430 *info = info->makeColorSpace(SkColorSpace::MakeSRGBLinear());
431 } else {
432 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
433 }
434}
435
mtkleine0effd62015-07-29 06:37:28 -0700436Error CodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700437 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800438 if (!encoded) {
439 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
440 }
msarettb714fb02016-01-22 14:46:42 -0800441
Mike Reedede7bac2017-07-23 15:30:02 -0400442 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700443 if (nullptr == codec.get()) {
444 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700445 }
446
scroggoba584892016-05-20 13:56:13 -0700447 SkImageInfo decodeInfo = codec->getInfo();
448 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
449 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800450 return Error::Nonfatal("Skipping uninteresting test.");
msarett438b2ad2015-04-09 12:43:10 -0700451 }
452
msarett0a242972015-06-11 14:27:27 -0700453 // Try to scale the image if it is desired
454 SkISize size = codec->getScaledDimensions(fScale);
455 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
456 return Error::Nonfatal("Test without scaling is uninteresting.");
457 }
msarettb32758a2015-08-18 13:22:46 -0700458
459 // Visually inspecting very small output images is not necessary. We will
460 // cover these cases in unit testing.
461 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
462 return Error::Nonfatal("Scaling very small images is uninteresting.");
463 }
msarett0a242972015-06-11 14:27:27 -0700464 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
465
Mike Reed7fcfb622018-02-09 13:26:46 -0500466 const int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700467 const size_t rowBytes = size.width() * bpp;
Mike Reedf0ffb892017-10-03 14:47:21 -0400468 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
scroggo19b91532016-10-24 09:03:26 -0700469 SkAutoMalloc pixels(safeSize);
msarett438b2ad2015-04-09 12:43:10 -0700470
msarettbb25b532016-01-13 09:31:39 -0800471 SkCodec::Options options;
Matt Saretta40d9c82017-05-19 15:21:05 -0400472 options.fPremulBehavior = canvas->imageInfo().colorSpace() ?
473 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
msarettbb25b532016-01-13 09:31:39 -0800474 if (kCodecZeroInit_Mode == fMode) {
msarettb1be46b2016-05-17 08:52:11 -0700475 memset(pixels.get(), 0, size.height() * rowBytes);
msarettbb25b532016-01-13 09:31:39 -0800476 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
477 }
msarett34e0ec42016-04-22 16:27:24 -0700478
479 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400480 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700481 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
482 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
483 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
484 }
scroggo9b77ddd2015-03-19 06:03:39 -0700485
scroggo9c59ebc2015-03-25 13:48:49 -0700486 switch (fMode) {
scroggo19b91532016-10-24 09:03:26 -0700487 case kAnimated_Mode: {
488 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
489 if (frameInfos.size() <= 1) {
490 return SkStringPrintf("%s is not an animated image.", fPath.c_str());
491 }
492
scroggo90e971a2016-10-25 06:11:01 -0700493 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
494 // into. "factor" is the number of frames to draw on one row. There will be
495 // up to "factor" rows as well.
496 const float root = sqrt((float) frameInfos.size());
497 const int factor = sk_float_ceil2int(root);
498
scroggo19b91532016-10-24 09:03:26 -0700499 // Used to cache a frame that future frames will depend on.
500 SkAutoMalloc priorFramePixels;
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400501 int cachedFrame = SkCodec::kNone;
502 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
scroggo19b91532016-10-24 09:03:26 -0700503 options.fFrameIndex = i;
504 // Check for a prior frame
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400505 const int reqFrame = frameInfos[i].fRequiredFrame;
scroggo19b91532016-10-24 09:03:26 -0700506 if (reqFrame != SkCodec::kNone && reqFrame == cachedFrame
507 && priorFramePixels.get()) {
508 // Copy into pixels
509 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400510 options.fPriorFrame = reqFrame;
scroggo19b91532016-10-24 09:03:26 -0700511 } else {
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400512 options.fPriorFrame = SkCodec::kNone;
scroggo19b91532016-10-24 09:03:26 -0700513 }
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500514 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
Leon Scroggins571b30f2017-07-11 17:35:31 +0000515 rowBytes, &options);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500516 if (SkCodec::kInvalidInput == result && i > 0) {
517 // Some of our test images have truncated later frames. Treat that
518 // the same as incomplete.
519 result = SkCodec::kIncompleteInput;
520 }
scroggo19b91532016-10-24 09:03:26 -0700521 switch (result) {
522 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400523 case SkCodec::kErrorInInput:
scroggo90e971a2016-10-25 06:11:01 -0700524 case SkCodec::kIncompleteInput: {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400525 // If the next frame depends on this one, store it in priorFrame.
526 // It is possible that we may discard a frame that future frames depend on,
527 // but the codec will simply redecode the discarded frame.
528 // Do this before calling draw_to_canvas, which premultiplies in place. If
529 // we're decoding to unpremul, we want to pass the unmodified frame to the
530 // codec for decoding the next frame.
531 if (static_cast<size_t>(i+1) < frameInfos.size()
532 && frameInfos[i+1].fRequiredFrame == i) {
533 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
534 cachedFrame = i;
535 }
536
scroggo90e971a2016-10-25 06:11:01 -0700537 SkAutoCanvasRestore acr(canvas, true);
538 const int xTranslate = (i % factor) * decodeInfo.width();
539 const int yTranslate = (i / factor) * decodeInfo.height();
540 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
Leon Scroggins571b30f2017-07-11 17:35:31 +0000541 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Leon Scroggins III674a1842017-07-06 12:26:09 -0400542 if (result != SkCodec::kSuccess) {
scroggo19b91532016-10-24 09:03:26 -0700543 return "";
544 }
545 break;
scroggo90e971a2016-10-25 06:11:01 -0700546 }
scroggo53f63b62016-10-27 08:29:13 -0700547 case SkCodec::kInvalidConversion:
Mike Reed304a07c2017-07-12 15:10:28 -0400548 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
scroggo53f63b62016-10-27 08:29:13 -0700549 return Error::Nonfatal(SkStringPrintf(
Mike Reed304a07c2017-07-12 15:10:28 -0400550 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str()));
scroggo53f63b62016-10-27 08:29:13 -0700551 }
552 // Fall through.
scroggo19b91532016-10-24 09:03:26 -0700553 default:
554 return SkStringPrintf("Couldn't getPixels for frame %i in %s.",
555 i, fPath.c_str());
556 }
scroggo19b91532016-10-24 09:03:26 -0700557 }
558 break;
559 }
msarettbb25b532016-01-13 09:31:39 -0800560 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700561 case kCodec_Mode: {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000562 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggoeb602a52015-07-09 08:16:03 -0700563 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400564 // We consider these to be valid, since we should still decode what is
scroggo9c59ebc2015-03-25 13:48:49 -0700565 // available.
Leon Scroggins III674a1842017-07-06 12:26:09 -0400566 case SkCodec::kErrorInInput:
scroggoeb602a52015-07-09 08:16:03 -0700567 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700568 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700569 default:
570 // Everything else is considered a failure.
571 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
572 }
msarettb1be46b2016-05-17 08:52:11 -0700573
Leon Scroggins571b30f2017-07-11 17:35:31 +0000574 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggo9c59ebc2015-03-25 13:48:49 -0700575 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700576 }
scroggo9c59ebc2015-03-25 13:48:49 -0700577 case kScanline_Mode: {
scroggod8d68552016-06-06 11:26:17 -0700578 void* dst = pixels.get();
579 uint32_t height = decodeInfo.height();
scroggo19b91532016-10-24 09:03:26 -0700580 const bool useIncremental = [this]() {
581 auto exts = { "png", "PNG", "gif", "GIF" };
582 for (auto ext : exts) {
583 if (fPath.endsWith(ext)) {
584 return true;
585 }
586 }
587 return false;
588 }();
589 // ico may use the old scanline method or the new one, depending on whether it
590 // internally holds a bmp or a png.
scroggo8e6c7ad2016-09-16 08:20:38 -0700591 const bool ico = fPath.endsWith("ico");
scroggo19b91532016-10-24 09:03:26 -0700592 bool useOldScanlineMethod = !useIncremental && !ico;
593 if (useIncremental || ico) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700594 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000595 rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700596 int rowsDecoded;
Leon Scroggins III674a1842017-07-06 12:26:09 -0400597 auto result = codec->incrementalDecode(&rowsDecoded);
598 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700599 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
600 SkCodec::kNo_ZeroInitialized, height,
601 rowsDecoded);
scroggo6fb23912016-06-02 14:16:43 -0700602 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700603 } else {
scroggo19b91532016-10-24 09:03:26 -0700604 if (useIncremental) {
605 // Error: These should support incremental decode.
scroggo8e6c7ad2016-09-16 08:20:38 -0700606 return "Could not start incremental decode";
607 }
608 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
609 // which should work via startScanlineDecode
610 useOldScanlineMethod = true;
611 }
612 }
613
614 if (useOldScanlineMethod) {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000615 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700616 return "Could not start scanline decoder";
617 }
618
619 switch (codec->getScanlineOrder()) {
620 case SkCodec::kTopDown_SkScanlineOrder:
621 case SkCodec::kBottomUp_SkScanlineOrder:
622 // We do not need to check the return value. On an incomplete
623 // image, memory will be filled with a default value.
624 codec->getScanlines(dst, height, rowBytes);
625 break;
msarett10522ff2015-09-07 08:54:01 -0700626 }
627 }
628
Leon Scroggins571b30f2017-07-11 17:35:31 +0000629 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer97002062015-05-27 12:36:10 -0700630 break;
631 }
msarett0a242972015-06-11 14:27:27 -0700632 case kStripe_Mode: {
633 const int height = decodeInfo.height();
634 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
635 // does not align with image blocks.
636 const int stripeHeight = 37;
637 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
msarettb1be46b2016-05-17 08:52:11 -0700638 void* dst = pixels.get();
msarett0a242972015-06-11 14:27:27 -0700639
640 // Decode odd stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000641 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarettb65e6042016-02-23 05:37:25 -0800642 return "Could not start scanline decoder";
643 }
644
645 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
646 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
647 // to run this test for image types that do not have this scanline ordering.
scroggo12e2f502016-05-16 09:04:18 -0700648 // We only run this on Jpeg, which is always kTopDown.
649 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
msarette6dd0042015-10-09 11:07:34 -0700650
msarett0a242972015-06-11 14:27:27 -0700651 for (int i = 0; i < numStripes; i += 2) {
652 // Skip a stripe
653 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700654 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700655
656 // Read a stripe
657 const int startY = (i + 1) * stripeHeight;
658 const int linesToRead = SkTMin(stripeHeight, height - startY);
659 if (linesToRead > 0) {
msarettb1be46b2016-05-17 08:52:11 -0700660 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
661 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700662 }
663 }
664
665 // Decode even stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000666 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
scroggo1c005e42015-08-04 09:24:45 -0700667 if (SkCodec::kSuccess != startResult) {
668 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700669 }
670 for (int i = 0; i < numStripes; i += 2) {
671 // Read a stripe
672 const int startY = i * stripeHeight;
673 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarettb1be46b2016-05-17 08:52:11 -0700674 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
675 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700676
677 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700678 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
679 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700680 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700681 }
682 }
msarettb1be46b2016-05-17 08:52:11 -0700683
Leon Scroggins571b30f2017-07-11 17:35:31 +0000684 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700685 break;
msarett0a242972015-06-11 14:27:27 -0700686 }
msarett91c22b22016-02-22 12:27:46 -0800687 case kCroppedScanline_Mode: {
688 const int width = decodeInfo.width();
689 const int height = decodeInfo.height();
690 // This value is chosen because, as we move across the image, it will sometimes
691 // align with the jpeg block sizes and it will sometimes not. This allows us
692 // to test interestingly different code paths in the implementation.
693 const int tileSize = 36;
msarett91c22b22016-02-22 12:27:46 -0800694 SkIRect subset;
695 for (int x = 0; x < width; x += tileSize) {
696 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
Matt Saretta40d9c82017-05-19 15:21:05 -0400697 options.fSubset = &subset;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000698 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarett91c22b22016-02-22 12:27:46 -0800699 return "Could not start scanline decoder.";
700 }
701
msarettb1be46b2016-05-17 08:52:11 -0700702 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
msarett91c22b22016-02-22 12:27:46 -0800703 }
704
Leon Scroggins571b30f2017-07-11 17:35:31 +0000705 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
msarett91c22b22016-02-22 12:27:46 -0800706 break;
707 }
scroggob636b452015-07-22 07:16:20 -0700708 case kSubset_Mode: {
709 // Arbitrarily choose a divisor.
710 int divisor = 2;
711 // Total width/height of the image.
712 const int W = codec->getInfo().width();
713 const int H = codec->getInfo().height();
714 if (divisor > W || divisor > H) {
715 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
716 "for %s with dimensions (%d x %d)", divisor,
717 fPath.c_str(), W, H));
718 }
719 // subset dimensions
720 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
721 const int w = SkAlign2(W / divisor);
722 const int h = SkAlign2(H / divisor);
723 SkIRect subset;
Matt Saretta40d9c82017-05-19 15:21:05 -0400724 options.fSubset = &subset;
scroggob636b452015-07-22 07:16:20 -0700725 SkBitmap subsetBm;
726 // We will reuse pixel memory from bitmap.
msarettb1be46b2016-05-17 08:52:11 -0700727 void* dst = pixels.get();
scroggob636b452015-07-22 07:16:20 -0700728 // Keep track of left and top (for drawing subsetBm into canvas). We could use
729 // fScale * x and fScale * y, but we want integers such that the next subset will start
730 // where the last one ended. So we'll add decodeInfo.width() and height().
731 int left = 0;
732 for (int x = 0; x < W; x += w) {
733 int top = 0;
734 for (int y = 0; y < H; y+= h) {
735 // Do not make the subset go off the edge of the image.
736 const int preScaleW = SkTMin(w, W - x);
737 const int preScaleH = SkTMin(h, H - y);
738 subset.setXYWH(x, y, preScaleW, preScaleH);
739 // And scale
740 // FIXME: Should we have a version of getScaledDimensions that takes a subset
741 // into account?
msarettc7eb4902016-04-25 07:04:58 -0700742 const int scaledW = SkTMax(1, SkScalarRoundToInt(preScaleW * fScale));
743 const int scaledH = SkTMax(1, SkScalarRoundToInt(preScaleH * fScale));
744 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
745 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
msarettb1be46b2016-05-17 08:52:11 -0700746 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
747 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000748 &options);
scroggob636b452015-07-22 07:16:20 -0700749 switch (result) {
750 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400751 case SkCodec::kErrorInInput:
scroggob636b452015-07-22 07:16:20 -0700752 case SkCodec::kIncompleteInput:
753 break;
scroggob636b452015-07-22 07:16:20 -0700754 default:
755 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
756 "from %s with dimensions (%d x %d)\t error %d",
757 x, y, decodeInfo.width(), decodeInfo.height(),
758 fPath.c_str(), W, H, result);
759 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000760 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
761 SkIntToScalar(left), SkIntToScalar(top));
msarettb1be46b2016-05-17 08:52:11 -0700762
scroggob636b452015-07-22 07:16:20 -0700763 // translate by the scaled height.
764 top += decodeInfo.height();
765 }
766 // translate by the scaled width.
767 left += decodeInfo.width();
768 }
769 return "";
770 }
msarettb714fb02016-01-22 14:46:42 -0800771 default:
772 SkASSERT(false);
773 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700774 }
scroggo9c59ebc2015-03-25 13:48:49 -0700775 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700776}
777
778SkISize CodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700779 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400780 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700781 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400782 return {0, 0};
scroggo7fac5af2015-09-30 11:33:12 -0700783 }
scroggo19b91532016-10-24 09:03:26 -0700784
785 auto imageSize = codec->getScaledDimensions(fScale);
786 if (fMode == kAnimated_Mode) {
scroggo90e971a2016-10-25 06:11:01 -0700787 // We'll draw one of each frame, so make it big enough to hold them all
788 // in a grid. The grid will be roughly square, with "factor" frames per
789 // row and up to "factor" rows.
scroggo19b91532016-10-24 09:03:26 -0700790 const size_t count = codec->getFrameInfo().size();
scroggo90e971a2016-10-25 06:11:01 -0700791 const float root = sqrt((float) count);
792 const int factor = sk_float_ceil2int(root);
793 imageSize.fWidth = imageSize.fWidth * factor;
794 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
scroggo19b91532016-10-24 09:03:26 -0700795 }
796 return imageSize;
scroggo9b77ddd2015-03-19 06:03:39 -0700797}
798
799Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700800 if (1.0f == fScale) {
scroggo6e8c68e2016-10-24 13:48:49 -0700801 Name name = SkOSPath::Basename(fPath.c_str());
802 if (fMode == kAnimated_Mode) {
803 name.append("_animated");
804 }
805 return name;
msarett0a242972015-06-11 14:27:27 -0700806 }
scroggo6e8c68e2016-10-24 13:48:49 -0700807 SkASSERT(fMode != kAnimated_Mode);
msaretta5783ae2015-09-08 15:35:32 -0700808 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700809}
810
811/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
812
scroggof8dc9df2016-05-16 09:04:13 -0700813AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800814 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700815 : fPath(path)
msarett3d9d7a72015-10-21 10:27:10 -0700816 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800817 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700818 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800819 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700820{}
821
822bool AndroidCodecSrc::veto(SinkFlags flags) const {
823 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700824 return flags.type != SinkFlags::kRaster
825 || flags.approach != SinkFlags::kDirect;
826}
827
828Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400829 if (canvas->imageInfo().colorSpace() &&
830 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
831 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
832 // run these tests on legacy canvases.
833 // We allow an exception for F16, since Android uses F16.
834 return Error::Nonfatal("Skip testing to color correct canvas.");
835 }
836
bungeman38d909e2016-08-02 14:40:46 -0700837 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700838 if (!encoded) {
839 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
840 }
Mike Reedede7bac2017-07-23 15:30:02 -0400841 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
842 if (nullptr == codec) {
msarett3d9d7a72015-10-21 10:27:10 -0700843 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
844 }
845
scroggoba584892016-05-20 13:56:13 -0700846 SkImageInfo decodeInfo = codec->getInfo();
847 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
848 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800849 return Error::Nonfatal("Skipping uninteresting test.");
msarett3d9d7a72015-10-21 10:27:10 -0700850 }
851
852 // Scale the image if it is desired.
853 SkISize size = codec->getSampledDimensions(fSampleSize);
854
855 // Visually inspecting very small output images is not necessary. We will
856 // cover these cases in unit testing.
857 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
858 return Error::Nonfatal("Scaling very small images is uninteresting.");
859 }
860 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
861
Mike Reed7fcfb622018-02-09 13:26:46 -0500862 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700863 size_t rowBytes = size.width() * bpp;
864 SkAutoMalloc pixels(size.height() * rowBytes);
msarett3d9d7a72015-10-21 10:27:10 -0700865
866 SkBitmap bitmap;
msarett34e0ec42016-04-22 16:27:24 -0700867 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400868 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700869 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
870 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
871 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
872 }
msarett3d9d7a72015-10-21 10:27:10 -0700873
874 // Create options for the codec.
875 SkAndroidCodec::AndroidOptions options;
msarett3d9d7a72015-10-21 10:27:10 -0700876 options.fSampleSize = fSampleSize;
877
msarettb1be46b2016-05-17 08:52:11 -0700878 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggof8dc9df2016-05-16 09:04:13 -0700879 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400880 case SkCodec::kErrorInInput:
scroggof8dc9df2016-05-16 09:04:13 -0700881 case SkCodec::kIncompleteInput:
882 break;
msarett3d9d7a72015-10-21 10:27:10 -0700883 default:
scroggof8dc9df2016-05-16 09:04:13 -0700884 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700885 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000886 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggof8dc9df2016-05-16 09:04:13 -0700887 return "";
msarett3d9d7a72015-10-21 10:27:10 -0700888}
889
890SkISize AndroidCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700891 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400892 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
msarett3d9d7a72015-10-21 10:27:10 -0700893 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400894 return {0, 0};
msarett3d9d7a72015-10-21 10:27:10 -0700895 }
896 return codec->getSampledDimensions(fSampleSize);
897}
898
899Name AndroidCodecSrc::name() const {
900 // We will replicate the names used by CodecSrc so that images can
901 // be compared in Gold.
902 if (1 == fSampleSize) {
903 return SkOSPath::Basename(fPath.c_str());
904 }
msarett4b0778e2015-11-13 09:59:11 -0800905 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700906}
907
908/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
909
msarett18976312016-03-09 14:20:58 -0800910ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
911 : fPath(path)
912 , fMode(mode)
913 , fDstAlphaType(alphaType)
914 , fIsGpu(isGpu)
915 , fRunSerially(serial_from_path_name(path))
916{}
917
918bool ImageGenSrc::veto(SinkFlags flags) const {
919 if (fIsGpu) {
Brian Salomonbd7c5512017-03-07 09:08:36 -0500920 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
921 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
922 flags.multisampled == SinkFlags::kMultisampled;
msarett18976312016-03-09 14:20:58 -0800923 }
924
925 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
926}
927
928Error ImageGenSrc::draw(SkCanvas* canvas) const {
929 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
930 return Error::Nonfatal("Uninteresting to test image generator to 565.");
931 }
932
bungeman38d909e2016-08-02 14:40:46 -0700933 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett18976312016-03-09 14:20:58 -0800934 if (!encoded) {
935 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
936 }
937
msarettfc0b6d12016-03-17 13:50:17 -0700938#if defined(SK_BUILD_FOR_WIN)
939 // Initialize COM in order to test with WIC.
940 SkAutoCoInitialize com;
941 if (!com.succeeded()) {
942 return "Could not initialize COM.";
943 }
944#endif
945
Ben Wagner145dbcd2016-11-03 14:40:50 -0400946 std::unique_ptr<SkImageGenerator> gen(nullptr);
msarett18976312016-03-09 14:20:58 -0800947 switch (fMode) {
948 case kCodec_Mode:
Mike Reed185130c2017-02-15 15:14:16 -0500949 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
msarett18976312016-03-09 14:20:58 -0800950 if (!gen) {
951 return "Could not create codec image generator.";
952 }
953 break;
msarettfc0b6d12016-03-17 13:50:17 -0700954 case kPlatform_Mode: {
msarett18976312016-03-09 14:20:58 -0800955#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
Leon Scroggins III0cbc10f2017-10-30 09:07:53 -0400956 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700957#elif defined(SK_BUILD_FOR_WIN)
bungeman38d909e2016-08-02 14:40:46 -0700958 gen.reset(SkImageGeneratorWIC::NewFromEncodedWIC(encoded.get()));
msarettfc0b6d12016-03-17 13:50:17 -0700959#endif
960
msarett18976312016-03-09 14:20:58 -0800961 if (!gen) {
msarettfc0b6d12016-03-17 13:50:17 -0700962 return "Could not create platform image generator.";
msarett18976312016-03-09 14:20:58 -0800963 }
964 break;
msarettfc0b6d12016-03-17 13:50:17 -0700965 }
msarett18976312016-03-09 14:20:58 -0800966 default:
967 SkASSERT(false);
968 return "Invalid image generator mode";
969 }
970
971 // Test deferred decoding path on GPU
972 if (fIsGpu) {
Mike Reed185130c2017-02-15 15:14:16 -0500973 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
msarett18976312016-03-09 14:20:58 -0800974 if (!image) {
975 return "Could not create image from codec image generator.";
976 }
977 canvas->drawImage(image, 0, 0);
978 return "";
979 }
mtklein343a63d2016-03-22 11:46:53 -0700980
msarett18976312016-03-09 14:20:58 -0800981 // Test various color and alpha types on CPU
982 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
mtklein343a63d2016-03-22 11:46:53 -0700983
Matt Saretta40d9c82017-05-19 15:21:05 -0400984 SkImageGenerator::Options options;
985 options.fBehavior = canvas->imageInfo().colorSpace() ?
986 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
987
Mike Reed7fcfb622018-02-09 13:26:46 -0500988 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700989 size_t rowBytes = decodeInfo.width() * bpp;
990 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
Matt Saretta40d9c82017-05-19 15:21:05 -0400991 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
Matt Sarett05cb4c32017-03-02 12:07:46 -0500992 SkString err =
993 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
994
995#if defined(SK_BUILD_FOR_WIN)
996 if (kPlatform_Mode == fMode) {
997 // Do not issue a fatal error for WIC flakiness.
998 return Error::Nonfatal(err);
999 }
1000#endif
1001
1002 return err;
msarett18976312016-03-09 14:20:58 -08001003 }
1004
Matt Sarettf485cf92017-05-26 08:58:03 -04001005 set_bitmap_color_space(&decodeInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +00001006 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
msarettb1be46b2016-05-17 08:52:11 -07001007 CodecSrc::kGetFromCanvas_DstColorType);
msarett18976312016-03-09 14:20:58 -08001008 return "";
1009}
1010
1011SkISize ImageGenSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001012 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001013 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett18976312016-03-09 14:20:58 -08001014 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001015 return {0, 0};
msarett18976312016-03-09 14:20:58 -08001016 }
1017 return codec->getInfo().dimensions();
1018}
1019
1020Name ImageGenSrc::name() const {
1021 return SkOSPath::Basename(fPath.c_str());
1022}
1023
1024/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1025
msarett9ce3a542016-07-15 13:54:38 -07001026ColorCodecSrc::ColorCodecSrc(Path path, Mode mode, SkColorType colorType)
msarett69deca82016-04-29 09:38:40 -07001027 : fPath(path)
1028 , fMode(mode)
msarett9ce3a542016-07-15 13:54:38 -07001029 , fColorType(colorType)
msarett69deca82016-04-29 09:38:40 -07001030{}
1031
1032bool ColorCodecSrc::veto(SinkFlags flags) const {
1033 // Test to direct raster backends (8888 and 565).
1034 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1035}
1036
Matt Sarett6a0feba2017-06-09 10:45:44 -04001037void clamp_if_necessary(const SkBitmap& bitmap, SkColorType dstCT) {
1038 if (kRGBA_F16_SkColorType != bitmap.colorType() || kRGBA_F16_SkColorType == dstCT) {
1039 // No need to clamp if the dst is F16. We will clamp when we encode to PNG.
1040 return;
1041 }
1042
Mike Klein45c16fa2017-07-18 18:15:13 -04001043 SkJumper_MemoryCtx ptr = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
1044
Matt Sarett6a0feba2017-06-09 10:45:44 -04001045 SkRasterPipeline_<256> p;
1046 p.append(SkRasterPipeline::load_f16, &ptr);
1047 p.append(SkRasterPipeline::clamp_0);
1048 if (kPremul_SkAlphaType == bitmap.alphaType()) {
1049 p.append(SkRasterPipeline::clamp_a);
1050 } else {
1051 p.append(SkRasterPipeline::clamp_1);
1052 }
1053 p.append(SkRasterPipeline::store_f16, &ptr);
1054
Mike Klein45c16fa2017-07-18 18:15:13 -04001055 p.run(0,0, bitmap.width(), bitmap.height());
Matt Sarett6a0feba2017-06-09 10:45:44 -04001056}
1057
msarett69deca82016-04-29 09:38:40 -07001058Error ColorCodecSrc::draw(SkCanvas* canvas) const {
1059 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
1060 return Error::Nonfatal("No need to test color correction to 565 backend.");
1061 }
1062
msarettd1ec89b2016-08-03 12:59:27 -07001063 bool runInLegacyMode = kBaseline_Mode == fMode;
msarettd1ec89b2016-08-03 12:59:27 -07001064 if (runInLegacyMode && canvas->imageInfo().colorSpace()) {
1065 return Error::Nonfatal("Skipping tests that are only interesting in legacy mode.");
1066 } else if (!runInLegacyMode && !canvas->imageInfo().colorSpace()) {
1067 return Error::Nonfatal("Skipping tests that are only interesting in srgb mode.");
msarett9ce3a542016-07-15 13:54:38 -07001068 }
1069
bungeman38d909e2016-08-02 14:40:46 -07001070 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett69deca82016-04-29 09:38:40 -07001071 if (!encoded) {
1072 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1073 }
1074
Mike Reedede7bac2017-07-23 15:30:02 -04001075 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1076 if (nullptr == codec) {
msarett69deca82016-04-29 09:38:40 -07001077 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
1078 }
1079
msarett9876ac52016-06-01 14:47:18 -07001080 // Load the dst ICC profile. This particular dst is fairly similar to Adobe RGB.
Mike Reed0933bc92017-12-09 01:27:41 +00001081 sk_sp<SkData> dstData = GetResourceAsData("icc_profiles/HP_ZR30w.icc");
msarett9876ac52016-06-01 14:47:18 -07001082 if (!dstData) {
1083 return "Cannot read monitor profile. Is the resource path set correctly?";
1084 }
1085
msarett50ce1f22016-07-29 06:23:33 -07001086 sk_sp<SkColorSpace> dstSpace = nullptr;
1087 if (kDst_sRGB_Mode == fMode) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -05001088 dstSpace = SkColorSpace::MakeSRGB();
msarett50ce1f22016-07-29 06:23:33 -07001089 } else if (kDst_HPZR30w_Mode == fMode) {
Brian Osman526972e2016-10-24 09:24:02 -04001090 dstSpace = SkColorSpace::MakeICC(dstData->data(), dstData->size());
msarett50ce1f22016-07-29 06:23:33 -07001091 }
1092
1093 SkImageInfo decodeInfo = codec->getInfo().makeColorType(fColorType).makeColorSpace(dstSpace);
msarettd1ec89b2016-08-03 12:59:27 -07001094 if (kUnpremul_SkAlphaType == decodeInfo.alphaType()) {
1095 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
1096 }
msarett2ecc35f2016-09-08 11:55:16 -07001097 if (kRGBA_F16_SkColorType == fColorType) {
Brian Osman36703d92017-12-12 14:09:31 -05001098 decodeInfo = decodeInfo.makeColorSpace(decodeInfo.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001099 }
msarettd1ec89b2016-08-03 12:59:27 -07001100
msarett50ce1f22016-07-29 06:23:33 -07001101 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -04001102 set_bitmap_color_space(&bitmapInfo);
msarett50ce1f22016-07-29 06:23:33 -07001103 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
1104 kBGRA_8888_SkColorType == decodeInfo.colorType())
1105 {
1106 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
1107 }
1108
1109 SkBitmap bitmap;
1110 if (!bitmap.tryAllocPixels(bitmapInfo)) {
1111 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
1112 bitmapInfo.width(), bitmapInfo.height());
1113 }
1114
1115 size_t rowBytes = bitmap.rowBytes();
1116 SkCodec::Result r = codec->getPixels(decodeInfo, bitmap.getPixels(), rowBytes);
Leon Scroggins III674a1842017-07-06 12:26:09 -04001117 switch (r) {
1118 case SkCodec::kSuccess:
1119 case SkCodec::kErrorInInput:
1120 case SkCodec::kIncompleteInput:
1121 break;
1122 default:
1123 return SkStringPrintf("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
msarett50ce1f22016-07-29 06:23:33 -07001124 }
1125
msarett69deca82016-04-29 09:38:40 -07001126 switch (fMode) {
1127 case kBaseline_Mode:
msarett39979d82016-07-28 17:11:18 -07001128 case kDst_sRGB_Mode:
msarett50ce1f22016-07-29 06:23:33 -07001129 case kDst_HPZR30w_Mode:
Matt Sarett6a0feba2017-06-09 10:45:44 -04001130 // We do not support drawing unclamped F16.
1131 clamp_if_necessary(bitmap, canvas->imageInfo().colorType());
msarett39979d82016-07-28 17:11:18 -07001132 canvas->drawBitmap(bitmap, 0, 0);
1133 break;
msarett69deca82016-04-29 09:38:40 -07001134 default:
1135 SkASSERT(false);
1136 return "Invalid fMode";
1137 }
1138 return "";
1139}
1140
1141SkISize ColorCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001142 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001143 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett69deca82016-04-29 09:38:40 -07001144 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001145 return {0, 0};
msarett69deca82016-04-29 09:38:40 -07001146 }
Hal Canaryfafe1352017-04-11 12:12:02 -04001147 return {codec->getInfo().width(), codec->getInfo().height()};
msarett69deca82016-04-29 09:38:40 -07001148}
1149
1150Name ColorCodecSrc::name() const {
1151 return SkOSPath::Basename(fPath.c_str());
1152}
1153
1154/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1155
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001156SKPSrc::SKPSrc(Path path) : fPath(path) { }
mtklein748ca3b2015-01-15 10:56:12 -08001157
Robert Phillipse4aae342018-03-14 10:26:57 -04001158static sk_sp<SkPicture> read_skp(const char* path, const SkDeserialProcs* procs = nullptr) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001159 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtklein75d98fd2015-01-18 07:05:01 -08001160 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001161 return nullptr;
mtklein748ca3b2015-01-15 10:56:12 -08001162 }
Robert Phillipse4aae342018-03-14 10:26:57 -04001163 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get(), procs));
mtklein75d98fd2015-01-18 07:05:01 -08001164 if (!pic) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001165 return nullptr;
mtklein75d98fd2015-01-18 07:05:01 -08001166 }
bungemanf93d7112016-09-16 06:24:20 -07001167 stream = nullptr; // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -07001168
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001169 return pic;
1170}
1171
1172Error SKPSrc::draw(SkCanvas* canvas) const {
1173 sk_sp<SkPicture> pic = read_skp(fPath.c_str());
1174 if (!pic) {
1175 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1176 }
1177
Robert Phillips33f02ed2018-03-27 08:06:57 -04001178 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
mtklein748ca3b2015-01-15 10:56:12 -08001179 canvas->drawPicture(pic);
1180 return "";
1181}
1182
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001183static SkRect get_cull_rect_for_skp(const char* path) {
1184 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtkleinffa901a2015-03-16 10:38:07 -07001185 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001186 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001187 }
1188 SkPictInfo info;
Mike Reede7a58322017-12-20 14:09:20 -05001189 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001190 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001191 }
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001192
1193 return info.fCullRect;
1194}
1195
1196SkISize SKPSrc::size() const {
1197 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
Robert Phillips33f02ed2018-03-27 08:06:57 -04001198 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001199 return {0, 0};
mtkleinffa901a2015-03-16 10:38:07 -07001200 }
1201 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -08001202}
1203
1204Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1205
Florin Malitafc043dc2017-12-31 11:08:42 -05001206/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1207
Florin Malita124d5af2017-12-31 17:02:26 -05001208#if !defined(SK_BUILD_FOR_GOOGLE3)
Florin Malita54f65c42018-01-16 17:04:30 -05001209SkottieSrc::SkottieSrc(Path path)
Florin Malitafc043dc2017-12-31 11:08:42 -05001210 : fName(SkOSPath::Basename(path.c_str())) {
1211
Florin Malita54f65c42018-01-16 17:04:30 -05001212 fAnimation = skottie::Animation::MakeFromFile(path.c_str());
Florin Malitafc043dc2017-12-31 11:08:42 -05001213 if (!fAnimation) {
1214 return;
1215 }
1216
1217 // Fit kTileCount x kTileCount frames to a 1000x1000 film strip.
1218 static constexpr SkScalar kTargetSize = 1000;
Florin Malita3fae0f32018-03-15 21:52:54 -04001219 fTileSize = SkSize::Make(kTargetSize / kTileCount, kTargetSize / kTileCount).toCeil();
Florin Malitafc043dc2017-12-31 11:08:42 -05001220}
1221
Florin Malita54f65c42018-01-16 17:04:30 -05001222Error SkottieSrc::draw(SkCanvas* canvas) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001223 if (!fAnimation) {
1224 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
1225 }
1226
1227 canvas->drawColor(SK_ColorWHITE);
1228
Florin Malitafc043dc2017-12-31 11:08:42 -05001229 const auto ip = fAnimation->inPoint() * 1000 / fAnimation->frameRate(),
1230 op = fAnimation->outPoint() * 1000 / fAnimation->frameRate(),
1231 fr = (op - ip) / (kTileCount * kTileCount - 1);
1232
Florin Malitad3c1b842018-01-27 12:43:24 -05001233 // Shuffled order to exercise non-linear frame progression.
1234 static constexpr int frames[] = { 4, 0, 3, 1, 2 };
1235 static_assert(SK_ARRAY_COUNT(frames) == kTileCount, "");
1236
Florin Malitafc043dc2017-12-31 11:08:42 -05001237 for (int i = 0; i < kTileCount; ++i) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001238 const SkScalar y = frames[i] * fTileSize.height();
Florin Malitafc043dc2017-12-31 11:08:42 -05001239
1240 for (int j = 0; j < kTileCount; ++j) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001241 const SkScalar x = frames[j] * fTileSize.width();
Florin Malitafc043dc2017-12-31 11:08:42 -05001242 SkRect dest = SkRect::MakeXYWH(x, y, fTileSize.width(), fTileSize.height());
1243
Florin Malitad3c1b842018-01-27 12:43:24 -05001244 const auto t = fr * (frames[i] * kTileCount + frames[j]);
Florin Malitadf2713c2018-01-09 15:51:21 -05001245 {
1246 SkAutoCanvasRestore acr(canvas, true);
Florin Malitad3c1b842018-01-27 12:43:24 -05001247 canvas->clipRect(dest, true);
Florin Malitadf2713c2018-01-09 15:51:21 -05001248 canvas->concat(SkMatrix::MakeRectToRect(SkRect::MakeSize(fAnimation->size()),
1249 dest,
Florin Malita3fae0f32018-03-15 21:52:54 -04001250 SkMatrix::kCenter_ScaleToFit));
Florin Malitadf2713c2018-01-09 15:51:21 -05001251
1252 fAnimation->animationTick(t);
1253 fAnimation->render(canvas);
1254 }
Florin Malitafc043dc2017-12-31 11:08:42 -05001255 }
1256 }
1257
1258 return "";
1259}
1260
Florin Malita54f65c42018-01-16 17:04:30 -05001261SkISize SkottieSrc::size() const {
Florin Malita3fae0f32018-03-15 21:52:54 -04001262 return SkISize::Make(kTileCount * fTileSize.width(),
1263 kTileCount * fTileSize.height());
Florin Malitafc043dc2017-12-31 11:08:42 -05001264}
1265
Florin Malita54f65c42018-01-16 17:04:30 -05001266Name SkottieSrc::name() const { return fName; }
Florin Malitafc043dc2017-12-31 11:08:42 -05001267
Florin Malita54f65c42018-01-16 17:04:30 -05001268bool SkottieSrc::veto(SinkFlags flags) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001269 // No need to test to non-(raster||gpu||vector) or indirect backends.
1270 bool type_ok = flags.type == SinkFlags::kRaster
1271 || flags.type == SinkFlags::kGPU
1272 || flags.type == SinkFlags::kVector;
1273
1274 return !type_ok || flags.approach != SinkFlags::kDirect;
1275}
Florin Malita124d5af2017-12-31 17:02:26 -05001276#endif
Florin Malitafc043dc2017-12-31 11:08:42 -05001277
1278/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
fmalitaa2b9fdf2016-08-03 19:53:36 -07001279#if defined(SK_XML)
fmalitabdf3e5c2016-09-17 07:26:26 -07001280// Used when the image doesn't have an intrinsic size.
Hal Canaryfafe1352017-04-11 12:12:02 -04001281static const SkSize kDefaultSVGSize = {1000, 1000};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001282
fmalitabdf3e5c2016-09-17 07:26:26 -07001283// Used to force-scale tiny fixed-size images.
Hal Canaryfafe1352017-04-11 12:12:02 -04001284static const SkSize kMinimumSVGSize = {128, 128};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001285
fmalitaacd2f5c2016-11-08 07:13:45 -08001286SVGSrc::SVGSrc(Path path)
1287 : fName(SkOSPath::Basename(path.c_str()))
1288 , fScale(1) {
fmalitabdf3e5c2016-09-17 07:26:26 -07001289
fmalitaacd2f5c2016-11-08 07:13:45 -08001290 SkFILEStream stream(path.c_str());
1291 if (!stream.isValid()) {
1292 return;
1293 }
1294 fDom = SkSVGDOM::MakeFromStream(stream);
1295 if (!fDom) {
1296 return;
1297 }
1298
1299 const SkSize& sz = fDom->containerSize();
1300 if (sz.isEmpty()) {
1301 // no intrinsic size
1302 fDom->setContainerSize(kDefaultSVGSize);
1303 } else {
1304 fScale = SkTMax(1.f, SkTMax(kMinimumSVGSize.width() / sz.width(),
1305 kMinimumSVGSize.height() / sz.height()));
1306 }
1307}
1308
1309Error SVGSrc::draw(SkCanvas* canvas) const {
fmalitabdf3e5c2016-09-17 07:26:26 -07001310 if (!fDom) {
fmalitaacd2f5c2016-11-08 07:13:45 -08001311 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
fmalitaa2b9fdf2016-08-03 19:53:36 -07001312 }
1313
fmalitaacd2f5c2016-11-08 07:13:45 -08001314 SkAutoCanvasRestore acr(canvas, true);
1315 canvas->scale(fScale, fScale);
1316 fDom->render(canvas);
1317
fmalitaa2b9fdf2016-08-03 19:53:36 -07001318 return "";
1319}
1320
1321SkISize SVGSrc::size() const {
fmalitaacd2f5c2016-11-08 07:13:45 -08001322 if (!fDom) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001323 return {0, 0};
fmalitabdf3e5c2016-09-17 07:26:26 -07001324 }
1325
Hal Canaryfafe1352017-04-11 12:12:02 -04001326 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1327 .toRound();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001328}
1329
fmalitaacd2f5c2016-11-08 07:13:45 -08001330Name SVGSrc::name() const { return fName; }
fmalitaa2b9fdf2016-08-03 19:53:36 -07001331
fmalita179d8852016-08-16 14:23:29 -07001332bool SVGSrc::veto(SinkFlags flags) const {
Florin Malita93323eb2017-06-16 15:31:17 -04001333 // No need to test to non-(raster||gpu||vector) or indirect backends.
fmalita179d8852016-08-16 14:23:29 -07001334 bool type_ok = flags.type == SinkFlags::kRaster
Florin Malita93323eb2017-06-16 15:31:17 -04001335 || flags.type == SinkFlags::kGPU
1336 || flags.type == SinkFlags::kVector;
fmalita179d8852016-08-16 14:23:29 -07001337
1338 return !type_ok || flags.approach != SinkFlags::kDirect;
1339}
1340
fmalitaa2b9fdf2016-08-03 19:53:36 -07001341#endif // defined(SK_XML)
1342/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -08001343
halcanary45420a92016-06-02 12:41:14 -07001344MSKPSrc::MSKPSrc(Path path) : fPath(path) {
bungemanf93d7112016-09-16 06:24:20 -07001345 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001346 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1347 if (count > 0) {
1348 fPages.reset(count);
1349 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1350 }
halcanary45420a92016-06-02 12:41:14 -07001351}
1352
Hal Canary45cde312017-04-03 16:06:42 -04001353int MSKPSrc::pageCount() const { return fPages.count(); }
halcanary45420a92016-06-02 12:41:14 -07001354
1355SkISize MSKPSrc::size() const { return this->size(0); }
Hal Canary45cde312017-04-03 16:06:42 -04001356SkISize MSKPSrc::size(int i) const {
Hal Canaryfafe1352017-04-11 12:12:02 -04001357 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
Hal Canary45cde312017-04-03 16:06:42 -04001358}
halcanary45420a92016-06-02 12:41:14 -07001359
1360Error MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
1361Error MSKPSrc::draw(int i, SkCanvas* canvas) const {
Hal Canary45cde312017-04-03 16:06:42 -04001362 if (this->pageCount() == 0) {
halcanary45420a92016-06-02 12:41:14 -07001363 return SkStringPrintf("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1364 }
Hal Canary45cde312017-04-03 16:06:42 -04001365 if (i >= fPages.count() || i < 0) {
halcanary45420a92016-06-02 12:41:14 -07001366 return SkStringPrintf("MultiPictureDocument page number out of range: %d", i);
1367 }
Hal Canary45cde312017-04-03 16:06:42 -04001368 SkPicture* page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001369 if (!page) {
Hal Canary45cde312017-04-03 16:06:42 -04001370 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1371 if (!stream) {
1372 return SkStringPrintf("Unable to open file: %s", fPath.c_str());
1373 }
1374 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
1375 return SkStringPrintf("SkMultiPictureDocument reader failed on page %d: %s", i,
1376 fPath.c_str());
1377 }
1378 page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001379 }
1380 canvas->drawPicture(page);
1381 return "";
1382}
1383
1384Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1385
1386/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1387
mtkleinad66f9b2015-02-13 15:11:10 -08001388Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
Mike Reed5df49342016-11-12 08:06:55 -06001389 return src.draw(SkMakeNullCanvas().get());
mtkleinad66f9b2015-02-13 15:11:10 -08001390}
1391
1392/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1393
Brian Osmane5756ec2017-09-06 17:08:30 -04001394static bool encode_png_base64(const SkBitmap& bitmap, SkString* dst) {
1395 SkPixmap pm;
1396 if (!bitmap.peekPixels(&pm)) {
1397 dst->set("peekPixels failed");
1398 return false;
1399 }
1400
1401 // We're going to embed this PNG in a data URI, so make it as small as possible
1402 SkPngEncoder::Options options;
1403 options.fFilterFlags = SkPngEncoder::FilterFlag::kAll;
1404 options.fZLibLevel = 9;
1405 options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
1406 : SkTransferFunctionBehavior::kIgnore;
1407
1408 SkDynamicMemoryWStream wStream;
1409 if (!SkPngEncoder::Encode(&wStream, pm, options)) {
1410 dst->set("SkPngEncoder::Encode failed");
1411 return false;
1412 }
1413
1414 sk_sp<SkData> pngData = wStream.detachAsData();
1415 size_t len = SkBase64::Encode(pngData->data(), pngData->size(), nullptr);
1416
1417 // The PNG can be almost arbitrarily large. We don't want to fill our logs with enormous URLs.
1418 // Infra says these can be pretty big, as long as we're only outputting them on failure.
1419 static const size_t kMaxBase64Length = 1024 * 1024;
1420 if (len > kMaxBase64Length) {
1421 dst->printf("Encoded image too large (%u bytes)", static_cast<uint32_t>(len));
1422 return false;
1423 }
1424
1425 dst->resize(len);
1426 SkBase64::Encode(pngData->data(), pngData->size(), dst->writable_str());
1427 return true;
1428}
1429
1430static Error compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
1431 // The dimensions are a property of the Src only, and so should be identical.
Mike Reedf0ffb892017-10-03 14:47:21 -04001432 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1433 if (reference.computeByteSize() != bitmap.computeByteSize()) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001434 return "Dimensions don't match reference";
1435 }
1436 // All SkBitmaps in DM are tight, so this comparison is easy.
Mike Reedf0ffb892017-10-03 14:47:21 -04001437 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001438 SkString encoded;
1439 SkString errString("Pixels don't match reference");
1440 if (encode_png_base64(reference, &encoded)) {
1441 errString.append("\nExpected: data:image/png;base64,");
1442 errString.append(encoded);
1443 } else {
1444 errString.append("\nExpected image failed to encode: ");
1445 errString.append(encoded);
1446 }
1447 if (encode_png_base64(bitmap, &encoded)) {
1448 errString.append("\nActual: data:image/png;base64,");
1449 errString.append(encoded);
1450 } else {
1451 errString.append("\nActual image failed to encode: ");
1452 errString.append(encoded);
1453 }
1454 return errString;
1455 }
1456 return "";
1457}
1458
1459/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1460
mtkleinb9eb4ac2015-02-02 18:26:03 -08001461DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1462
bsalomon85b4b532016-04-05 11:06:27 -07001463GPUSink::GPUSink(GrContextFactory::ContextType ct,
csmartdaltone812d492017-02-21 12:36:05 -07001464 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001465 SkCommandLineConfigGpu::SurfType surfType,
mtklein82d28432015-01-15 12:46:02 -08001466 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -07001467 bool diText,
brianosmand93c1202016-03-10 07:49:08 -08001468 SkColorType colorType,
Brian Salomonce5ee602017-07-17 11:31:31 -04001469 SkAlphaType alphaType,
brianosmanb109b8c2016-06-16 13:03:24 -07001470 sk_sp<SkColorSpace> colorSpace,
Brian Osmanf21aa042017-08-21 16:48:46 -04001471 bool threaded,
1472 const GrContextOptions& grCtxOptions)
Brian Salomonce5ee602017-07-17 11:31:31 -04001473 : fContextType(ct)
1474 , fContextOverrides(overrides)
Brian Salomonf865b052018-03-09 09:01:53 -05001475 , fSurfType(surfType)
Brian Salomonce5ee602017-07-17 11:31:31 -04001476 , fSampleCount(samples)
1477 , fUseDIText(diText)
1478 , fColorType(colorType)
1479 , fAlphaType(alphaType)
1480 , fColorSpace(std::move(colorSpace))
Brian Osmanf21aa042017-08-21 16:48:46 -04001481 , fThreaded(threaded)
1482 , fBaseContextOptions(grCtxOptions) {}
mtklein748ca3b2015-01-15 10:56:12 -08001483
Brian Salomon09d994e2016-12-21 11:14:46 -05001484DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
bsalomon648c6962015-10-23 09:06:59 -07001485
Brian Osmanf9810662017-08-30 10:02:10 -04001486Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
1487 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1488}
1489
1490Error GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1491 const GrContextOptions& baseOptions) const {
1492 GrContextOptions grOptions = baseOptions;
kkinnunen64492c42015-12-08 01:24:40 -08001493
kkinnunen5219fd92015-12-10 06:28:13 -08001494 src.modifyGrContextOptions(&grOptions);
1495
1496 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -08001497 const SkISize size = src.size();
Brian Salomonce5ee602017-07-17 11:31:31 -04001498 SkImageInfo info =
1499 SkImageInfo::Make(size.width(), size.height(), fColorType, fAlphaType, fColorSpace);
Brian Salomonf865b052018-03-09 09:01:53 -05001500 sk_sp<SkSurface> surface;
msarett13a036b2016-02-08 09:10:47 -08001501#if SK_SUPPORT_GPU
csmartdaltone812d492017-02-21 12:36:05 -07001502 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
bsalomon8b7451a2016-05-11 06:33:06 -07001503 const int maxDimension = context->caps()->maxTextureSize();
msarett13a036b2016-02-08 09:10:47 -08001504 if (maxDimension < SkTMax(size.width(), size.height())) {
1505 return Error::Nonfatal("Src too large to create a texture.\n");
1506 }
Brian Salomonf865b052018-03-09 09:01:53 -05001507 uint32_t flags = fUseDIText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
1508 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
1509 GrBackendTexture backendTexture;
1510 GrBackendRenderTarget backendRT;
1511 switch (fSurfType) {
1512 case SkCommandLineConfigGpu::SurfType::kDefault:
1513 surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, fSampleCount,
1514 &props);
1515 break;
1516 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
1517 backendTexture = context->contextPriv().getGpu()->createTestingOnlyBackendTexture(
1518 nullptr, info.width(), info.height(), info.colorType(), true, GrMipMapped::kNo);
1519 surface = SkSurface::MakeFromBackendTexture(context, backendTexture,
1520 kTopLeft_GrSurfaceOrigin, fSampleCount,
Brian Salomon53706772018-03-19 14:18:08 -04001521 fColorType, info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001522 break;
1523 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1524 if (1 == fSampleCount) {
1525 auto srgbEncoded = info.colorSpace() && info.colorSpace()->gammaCloseToSRGB()
1526 ? GrSRGBEncoded::kYes
1527 : GrSRGBEncoded::kNo;
1528 auto colorType = SkColorTypeToGrColorType(info.colorType());
1529 backendRT = context->contextPriv().getGpu()->createTestingOnlyBackendRenderTarget(
1530 info.width(), info.height(), colorType, srgbEncoded);
Brian Salomon49edccd2018-03-23 15:31:32 -04001531 surface = SkSurface::MakeFromBackendRenderTarget(
1532 context, backendRT, kBottomLeft_GrSurfaceOrigin, info.colorType(),
1533 info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001534 }
1535 break;
1536 }
msarett13a036b2016-02-08 09:10:47 -08001537#endif
1538
mtklein748ca3b2015-01-15 10:56:12 -08001539 if (!surface) {
1540 return "Could not create a surface.";
1541 }
joshualitt5f5a8d72015-02-25 14:09:45 -08001542 if (FLAGS_preAbandonGpuContext) {
joshualitt5f5a8d72015-02-25 14:09:45 -08001543 factory.abandonContexts();
1544 }
mtklein748ca3b2015-01-15 10:56:12 -08001545 SkCanvas* canvas = surface->getCanvas();
1546 Error err = src.draw(canvas);
1547 if (!err.isEmpty()) {
1548 return err;
1549 }
1550 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -08001551 if (FLAGS_gpuStats) {
Robert Phillips0c4b7b12018-03-06 08:20:37 -05001552#if SK_SUPPORT_GPU
1553 canvas->getGrContext()->contextPriv().dumpCacheStats(log);
1554 canvas->getGrContext()->contextPriv().dumpGpuStats(log);
1555#endif
mtkleinb9eb4ac2015-02-02 18:26:03 -08001556 }
Brian Salomon5fba7ad2018-03-22 10:01:16 -04001557 if (info.colorType() == kRGB_565_SkColorType || info.colorType() == kARGB_4444_SkColorType ||
1558 info.colorType() == kRGB_888x_SkColorType) {
Brian Salomonce5ee602017-07-17 11:31:31 -04001559 // We don't currently support readbacks into these formats on the GPU backend. Convert to
1560 // 32 bit.
1561 info = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
1562 kPremul_SkAlphaType, fColorSpace);
1563 }
mtklein748ca3b2015-01-15 10:56:12 -08001564 dst->allocPixels(info);
Mike Reed12e946b2017-04-17 10:53:29 -04001565 canvas->readPixels(*dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -08001566 if (FLAGS_abandonGpuContext) {
1567 factory.abandonContexts();
bsalomon6e2aad42016-04-01 11:54:31 -07001568 } else if (FLAGS_releaseAndAbandonGpuContext) {
1569 factory.releaseResourcesAndAbandonContexts();
mtklein55e88b22015-01-21 15:50:13 -08001570 }
Brian Salomonf865b052018-03-09 09:01:53 -05001571#if SK_SUPPORT_GPU
1572 if (!context->contextPriv().abandoned()) {
1573 surface.reset();
1574 if (backendTexture.isValid()) {
Brian Salomon26102cb2018-03-09 09:33:19 -05001575 context->contextPriv().getGpu()->deleteTestingOnlyBackendTexture(backendTexture);
Brian Salomonf865b052018-03-09 09:01:53 -05001576 }
1577 if (backendRT.isValid()) {
1578 context->contextPriv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
1579 }
1580 }
1581#endif
mtklein748ca3b2015-01-15 10:56:12 -08001582 return "";
1583}
1584
1585/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1586
Brian Osmanf9810662017-08-30 10:02:10 -04001587GPUThreadTestingSink::GPUThreadTestingSink(GrContextFactory::ContextType ct,
1588 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001589 SkCommandLineConfigGpu::SurfType surfType,
Brian Osmanf9810662017-08-30 10:02:10 -04001590 int samples,
1591 bool diText,
1592 SkColorType colorType,
1593 SkAlphaType alphaType,
1594 sk_sp<SkColorSpace> colorSpace,
1595 bool threaded,
1596 const GrContextOptions& grCtxOptions)
Brian Salomonf865b052018-03-09 09:01:53 -05001597 : INHERITED(ct, overrides, surfType, samples, diText, colorType, alphaType,
1598 std::move(colorSpace), threaded, grCtxOptions)
Chris Dalton040238b2017-12-18 14:22:34 -07001599#if SK_SUPPORT_GPU
Mike Klein022cfa22017-09-01 11:53:16 -04001600 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)) {
Chris Dalton040238b2017-12-18 14:22:34 -07001601#else
1602 , fExecutor(nullptr) {
1603#endif
Brian Osmanf9810662017-08-30 10:02:10 -04001604 SkASSERT(fExecutor);
1605}
1606
1607Error GPUThreadTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1608 SkString* log) const {
1609 // Draw twice, once with worker threads, and once without. Verify that we get the same result.
1610 // Also, force us to only use the software path renderer, so we really stress-test the threaded
1611 // version of that code.
1612 GrContextOptions contextOptions = this->baseContextOptions();
Brian Osman195c05b2017-08-30 15:14:04 -04001613 contextOptions.fGpuPathRenderers = GpuPathRenderers::kNone;
Brian Osmanf9810662017-08-30 10:02:10 -04001614
1615 contextOptions.fExecutor = fExecutor.get();
1616 Error err = this->onDraw(src, dst, wStream, log, contextOptions);
1617 if (!err.isEmpty() || !dst) {
1618 return err;
1619 }
1620
1621 SkBitmap reference;
1622 SkString refLog;
1623 SkDynamicMemoryWStream refStream;
1624 contextOptions.fExecutor = nullptr;
1625 Error refErr = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1626 if (!refErr.isEmpty()) {
1627 return refErr;
1628 }
1629
Brian Osmane5756ec2017-09-06 17:08:30 -04001630 return compare_bitmaps(reference, *dst);
Brian Osmanf9810662017-08-30 10:02:10 -04001631}
1632
1633/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1634
halcanary47ef4d52015-03-03 09:13:09 -08001635static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
halcanary4ba051c2016-03-10 10:31:53 -08001636 if (src.size().isEmpty()) {
1637 return "Source has empty dimensions";
1638 }
halcanary47ef4d52015-03-03 09:13:09 -08001639 SkASSERT(doc);
halcanary45420a92016-06-02 12:41:14 -07001640 int pageCount = src.pageCount();
1641 for (int i = 0; i < pageCount; ++i) {
1642 int width = src.size(i).width(), height = src.size(i).height();
halcanary7e798182015-04-14 14:06:18 -07001643 SkCanvas* canvas =
1644 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1645 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001646 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001647 }
halcanary45420a92016-06-02 12:41:14 -07001648 Error err = src.draw(i, canvas);
halcanary7e798182015-04-14 14:06:18 -07001649 if (!err.isEmpty()) {
1650 return err;
1651 }
1652 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001653 }
reedd14df7c2016-09-22 14:12:46 -07001654 doc->close();
halcanaryfd4a9932015-01-28 11:45:58 -08001655 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -08001656 return "";
1657}
1658
halcanary47ef4d52015-03-03 09:13:09 -08001659Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary4b656662016-04-27 07:45:18 -07001660 SkDocument::PDFMetadata metadata;
1661 metadata.fTitle = src.name();
1662 metadata.fSubject = "rendering correctness test";
1663 metadata.fCreator = "Skia/DM";
Mike Reeda4daf192017-12-14 13:25:04 -05001664 metadata.fRasterDPI = fRasterDpi;
1665 metadata.fPDFA = fPDFA;
1666 sk_sp<SkDocument> doc = SkDocument::MakePDF(dst, metadata);
halcanary47ef4d52015-03-03 09:13:09 -08001667 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001668 return "SkDocument::MakePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001669 }
1670 return draw_skdocument(src, doc.get(), dst);
1671}
1672
1673/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1674
1675XPSSink::XPSSink() {}
1676
Hal Canaryabc88d22017-02-06 09:26:49 -05001677#ifdef SK_BUILD_FOR_WIN
Hal Canary5e221e72017-02-06 09:51:42 -05001678static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1679 IXpsOMObjectFactory* factory;
1680 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1681 nullptr,
1682 CLSCTX_INPROC_SERVER,
1683 IID_PPV_ARGS(&factory)));
1684 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1685}
1686
1687Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canaryabc88d22017-02-06 09:26:49 -05001688 SkAutoCoInitialize com;
1689 if (!com.succeeded()) {
1690 return "Could not initialize COM.";
1691 }
Hal Canary5e221e72017-02-06 09:51:42 -05001692 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1693 if (!factory) {
1694 return "Failed to create XPS Factory.";
1695 }
1696 sk_sp<SkDocument> doc(SkDocument::MakeXPS(dst, factory.get()));
halcanary47ef4d52015-03-03 09:13:09 -08001697 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001698 return "SkDocument::MakeXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001699 }
1700 return draw_skdocument(src, doc.get(), dst);
1701}
Hal Canary5e221e72017-02-06 09:51:42 -05001702#else
1703Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1704 return "XPS not supported on this platform.";
1705}
1706#endif
reed54dc4872016-09-13 08:09:45 -07001707
1708/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1709
1710PipeSink::PipeSink() {}
1711
1712Error PipeSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1713 return src.draw(SkPipeSerializer().beginWrite(SkRect::Make(src.size()), dst));
1714}
1715
mtklein748ca3b2015-01-15 10:56:12 -08001716/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1717
mtklein9c3f17d2015-01-28 11:35:18 -08001718SKPSink::SKPSink() {}
1719
mtkleinb9eb4ac2015-02-02 18:26:03 -08001720Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001721 SkSize size;
1722 size = src.size();
1723 SkPictureRecorder recorder;
1724 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1725 if (!err.isEmpty()) {
1726 return err;
1727 }
reedca2622b2016-03-18 07:25:55 -07001728 recorder.finishRecordingAsPicture()->serialize(dst);
mtklein9c3f17d2015-01-28 11:35:18 -08001729 return "";
1730}
1731
1732/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1733
Hal Canary85c7fe82016-10-25 10:33:27 -04001734Error DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1735 SkDebugCanvas debugCanvas(src.size().width(), src.size().height());
1736 Error err = src.draw(&debugCanvas);
1737 if (!err.isEmpty()) {
1738 return err;
1739 }
Mike Reed5df49342016-11-12 08:06:55 -06001740 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
Hal Canary85c7fe82016-10-25 10:33:27 -04001741 UrlDataManager dataManager(SkString("data"));
1742 Json::Value json = debugCanvas.toJSON(
1743 dataManager, debugCanvas.getSize(), nullCanvas.get());
1744 std::string value = Json::StyledWriter().write(json);
1745 return dst->write(value.c_str(), value.size()) ? "" : "SkWStream Error";
1746}
1747
1748/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1749
Bryce Thomas95a7b762018-03-02 13:54:21 -08001750SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
mtklein8a4527e2015-01-31 20:00:58 -08001751
mtkleinb9eb4ac2015-02-02 18:26:03 -08001752Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita718df0a2016-07-15 10:33:29 -07001753#if defined(SK_XML)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001754 if (src.pageCount() > 1) {
1755 int pageCount = src.pageCount();
1756 if (fPageIndex > pageCount - 1) {
1757 return Error(SkStringPrintf("Page index %d too high for document with only %d pages.",
1758 fPageIndex, pageCount));
1759 }
1760 }
Ben Wagner145dbcd2016-11-03 14:40:50 -04001761 std::unique_ptr<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
Bryce Thomas95a7b762018-03-02 13:54:21 -08001762 return src.draw(fPageIndex,
1763 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
Mike Reed5df49342016-11-12 08:06:55 -06001764 SkIntToScalar(src.size().height())),
Bryce Thomas95a7b762018-03-02 13:54:21 -08001765 xmlWriter.get())
1766 .get());
fmalita718df0a2016-07-15 10:33:29 -07001767#else
Hal Canary327ef032018-03-22 13:10:51 -04001768 (void)fPageIndex;
fmalita718df0a2016-07-15 10:33:29 -07001769 return Error("SVG sink is disabled.");
1770#endif // SK_XML
mtklein8a4527e2015-01-31 20:00:58 -08001771}
1772
1773/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1774
brianosmanb109b8c2016-06-16 13:03:24 -07001775RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
mtklein27c3fdd2016-02-26 14:43:21 -08001776 : fColorType(colorType)
brianosmanb109b8c2016-06-16 13:03:24 -07001777 , fColorSpace(std::move(colorSpace)) {}
mtklein748ca3b2015-01-15 10:56:12 -08001778
Yuqian Lib8b62532018-02-23 14:13:36 +08001779void RasterSink::allocPixels(const Src& src, SkBitmap* dst) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001780 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001781 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1782 SkAlphaType alphaType = kPremul_SkAlphaType;
1783 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1784
Mike Reed086a4272017-07-18 10:53:11 -04001785 dst->allocPixelsFlags(SkImageInfo::Make(size.width(), size.height(),
1786 fColorType, alphaType, fColorSpace),
1787 SkBitmap::kZeroPixels_AllocFlag);
Yuqian Lib8b62532018-02-23 14:13:36 +08001788}
1789
1790Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
1791 this->allocPixels(src, dst);
mtklein748ca3b2015-01-15 10:56:12 -08001792 SkCanvas canvas(*dst);
1793 return src.draw(&canvas);
1794}
1795
1796/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1797
Yuqian Lib8b62532018-02-23 14:13:36 +08001798ThreadedSink::ThreadedSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
1799 : RasterSink(colorType, colorSpace)
1800 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_backendThreads)) {
1801}
1802
1803Error ThreadedSink::draw(const Src& src, SkBitmap* dst, SkWStream* stream, SkString* str) const {
1804 this->allocPixels(src, dst);
1805
1806 std::unique_ptr<SkThreadedBMPDevice> device(new SkThreadedBMPDevice(
1807 *dst, FLAGS_backendTiles, FLAGS_backendThreads, fExecutor.get()));
1808 std::unique_ptr<SkCanvas> canvas(new SkCanvas(device.get()));
1809 Error result = src.draw(canvas.get());
1810 canvas->flush();
1811 return result;
1812
1813 // ??? yuqian: why does the following give me segmentation fault while the above one works?
1814 // The seg fault occurs right in the beginning of ThreadedSink::draw with invalid
1815 // memory address (it would crash without even calling this->allocPixels).
1816
1817 // SkThreadedBMPDevice device(*dst, tileCnt, FLAGS_cpuThreads, fExecutor.get());
1818 // SkCanvas canvas(&device);
1819 // Error result = src.draw(&canvas);
1820 // canvas.flush();
1821 // return result;
1822}
1823
1824/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1825
mtkleina16e69e2015-05-05 11:38:45 -07001826// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001827// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001828// Several examples below.
1829
mtkleincbf89782016-02-19 14:27:14 -08001830template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001831static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001832 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001833 class ProxySrc : public Src {
1834 public:
mtkleincbf89782016-02-19 14:27:14 -08001835 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001836 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
halcanaryb4a7f142016-03-30 08:31:27 -07001837 Name name() const override { return "ProxySrc"; }
1838 SkISize size() const override { return fSize; }
mtkleina16e69e2015-05-05 11:38:45 -07001839 private:
mtkleincbf89782016-02-19 14:27:14 -08001840 SkISize fSize;
1841 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001842 };
msarett62d3b102015-12-10 15:14:27 -08001843 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001844}
1845
1846/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1847
mtklein4a34ecb2016-01-08 10:19:35 -08001848DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1849
1850// Is *bitmap identical to what you get drawing src into sink?
1851static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1852 // We can only check raster outputs.
1853 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1854 if (FLAGS_check && bitmap) {
1855 SkBitmap reference;
1856 SkString log;
halcanaryb4a7f142016-03-30 08:31:27 -07001857 SkDynamicMemoryWStream wStream;
1858 Error err = sink->draw(src, &reference, &wStream, &log);
mtklein4a34ecb2016-01-08 10:19:35 -08001859 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1860 SkASSERT(err.isEmpty());
1861 if (!err.isEmpty()) {
1862 return err;
1863 }
Brian Osmane5756ec2017-09-06 17:08:30 -04001864 return compare_bitmaps(reference, *bitmap);
mtklein4a34ecb2016-01-08 10:19:35 -08001865 }
1866 return "";
1867}
1868
1869/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1870
mtkleind603b222015-02-17 11:13:33 -08001871static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1872 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1873 matrix->mapRect(&bounds);
1874 matrix->postTranslate(-bounds.x(), -bounds.y());
Hal Canaryfafe1352017-04-11 12:12:02 -04001875 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
mtkleind603b222015-02-17 11:13:33 -08001876}
1877
msarett62d3b102015-12-10 15:14:27 -08001878ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001879
mtkleinb9eb4ac2015-02-02 18:26:03 -08001880Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001881 SkMatrix matrix = fMatrix;
1882 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
Ben Wagner145dbcd2016-11-03 14:40:50 -04001883 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001884 canvas->concat(matrix);
1885 return src.draw(canvas);
1886 });
mtklein748ca3b2015-01-15 10:56:12 -08001887}
1888
mtkleind603b222015-02-17 11:13:33 -08001889// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1890// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001891ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001892
1893Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1894 Error err = fSink->draw(src, bitmap, stream, log);
1895 if (!err.isEmpty()) {
1896 return err;
1897 }
1898
1899 SkMatrix inverse;
1900 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1901 return "Cannot upright --matrix.";
1902 }
1903 SkMatrix upright = SkMatrix::I();
1904 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1905 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1906 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1907 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1908
1909 SkBitmap uprighted;
1910 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1911 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1912
1913 SkCanvas canvas(uprighted);
1914 canvas.concat(upright);
1915 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001916 paint.setBlendMode(SkBlendMode::kSrc);
mtkleind603b222015-02-17 11:13:33 -08001917 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1918
1919 *bitmap = uprighted;
mtkleind603b222015-02-17 11:13:33 -08001920 return "";
1921}
1922
mtklein748ca3b2015-01-15 10:56:12 -08001923/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1924
mtkleina16e69e2015-05-05 11:38:45 -07001925Error ViaSerialization::draw(
1926 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001927 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001928 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001929 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001930 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1931 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001932 if (!err.isEmpty()) {
1933 return err;
1934 }
reedca2622b2016-03-18 07:25:55 -07001935 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001936
1937 // Serialize it and then deserialize it.
reed39eaf5f2016-09-15 07:19:35 -07001938 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
mtklein748ca3b2015-01-15 10:56:12 -08001939
Ben Wagner1861e882018-04-04 17:40:46 -04001940 err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001941 canvas->drawPicture(deserialized);
Ben Wagner1861e882018-04-04 17:40:46 -04001942 return "";
mtkleina16e69e2015-05-05 11:38:45 -07001943 });
Ben Wagner1861e882018-04-04 17:40:46 -04001944 if (!err.isEmpty()) {
1945 return err;
1946 }
1947
1948 return check_against_reference(bitmap, src, fSink.get());
mtklein748ca3b2015-01-15 10:56:12 -08001949}
1950
1951/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1952
msarett62d3b102015-12-10 15:14:27 -08001953ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1954 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001955 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001956 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001957 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001958
mtkleinb9eb4ac2015-02-02 18:26:03 -08001959Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001960 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001961 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001962 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1963 SkIntToScalar(size.height()),
1964 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001965 if (!err.isEmpty()) {
1966 return err;
1967 }
reedca2622b2016-03-18 07:25:55 -07001968 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001969
Ben Wagner145dbcd2016-11-03 14:40:50 -04001970 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001971 const int xTiles = (size.width() + fW - 1) / fW,
1972 yTiles = (size.height() + fH - 1) / fH;
1973 SkMultiPictureDraw mpd(xTiles*yTiles);
reede8f30622016-03-23 18:59:25 -07001974 SkTArray<sk_sp<SkSurface>> surfaces;
1975// surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001976
mtkleina16e69e2015-05-05 11:38:45 -07001977 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1978 for (int j = 0; j < yTiles; j++) {
1979 for (int i = 0; i < xTiles; i++) {
1980 // This lets our ultimate Sink determine the best kind of surface.
1981 // E.g., if it's a GpuSink, the surfaces and images are textures.
reede8f30622016-03-23 18:59:25 -07001982 auto s = canvas->makeSurface(info);
mtkleina16e69e2015-05-05 11:38:45 -07001983 if (!s) {
reede8f30622016-03-23 18:59:25 -07001984 s = SkSurface::MakeRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001985 }
reede8f30622016-03-23 18:59:25 -07001986 surfaces.push_back(s);
mtkleina16e69e2015-05-05 11:38:45 -07001987 SkCanvas* c = s->getCanvas();
1988 c->translate(SkIntToScalar(-i * fW),
1989 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
reedca2622b2016-03-18 07:25:55 -07001990 mpd.add(c, pic.get());
mtklein748ca3b2015-01-15 10:56:12 -08001991 }
mtklein748ca3b2015-01-15 10:56:12 -08001992 }
mtkleina16e69e2015-05-05 11:38:45 -07001993 mpd.draw();
1994 for (int j = 0; j < yTiles; j++) {
1995 for (int i = 0; i < xTiles; i++) {
reed9ce9d672016-03-17 10:51:11 -07001996 sk_sp<SkImage> image(surfaces[i+xTiles*j]->makeImageSnapshot());
mtkleina16e69e2015-05-05 11:38:45 -07001997 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1998 }
1999 }
mtkleina16e69e2015-05-05 11:38:45 -07002000 return "";
2001 });
mtklein748ca3b2015-01-15 10:56:12 -08002002}
2003
mtkleinb7e8d692015-04-07 08:30:32 -07002004/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2005
Robert Phillips33f02ed2018-03-27 08:06:57 -04002006#if SK_SUPPORT_GPU
2007
2008ViaDDL::ViaDDL(int numDivisions, Sink* sink)
2009 : Via(sink)
2010 , fNumDivisions(numDivisions) {
2011}
2012
2013// This class consolidates tracking & extraction of the original image data from the sources,
2014// the upload of said data to the GPU and the fulfillment of promise images.
2015class ViaDDL::PromiseImageHelper {
2016public:
2017 class PromiseImageInfo {
2018 public:
2019 int fIndex; // index in the 'fImageInfo' array
2020 uint32_t fOriginalUniqueID; // original ID for deduping
2021 SkBitmap fBitmap; // CPU-side cache of the contents
2022 GrBackendTexture fBackendTexture; // GPU-side version
2023 };
2024
2025 PromiseImageHelper() : fLocked(false) { }
2026
2027 // This class will hand out pointers to its PromiseImageInfo. This is just some insurance
2028 // we won't be moving them around.
2029 void lock() { fLocked = true; }
2030
2031 bool isValidID(int id) const {
2032 return id >= 0 && id < fImageInfo.count();
2033 }
2034
2035 const PromiseImageInfo* getInfo(int id) const {
2036 SkASSERT(fLocked);
2037 return &fImageInfo[id];
2038 }
2039
2040 // returns -1 on failure
2041 int findOrDefineImage(SkImage* image) {
2042 int preExistingID = this->findImage(image);
2043 if (preExistingID >= 0) {
2044 SkASSERT(this->isValidID(preExistingID));
2045 return preExistingID;
2046 }
2047
2048 int newID = this->addImage(image);
2049 SkASSERT(this->isValidID(newID));
2050 return newID;
2051 }
2052
2053 void uploadAllToGPU(GrContext* context) {
2054 GrGpu* gpu = context->contextPriv().getGpu();
2055 SkASSERT(gpu);
2056
2057 for (int i = 0; i < fImageInfo.count(); ++i) {
2058 // DDL TODO: how can we tell if we need mipmapping!
2059 fImageInfo[i].fBackendTexture = gpu->createTestingOnlyBackendTexture(
2060 fImageInfo[i].fBitmap.getPixels(),
2061 fImageInfo[i].fBitmap.width(),
2062 fImageInfo[i].fBitmap.height(),
2063 fImageInfo[i].fBitmap.colorType(),
2064 false, GrMipMapped::kNo);
2065 SkAssertResult(fImageInfo[i].fBackendTexture.isValid());
2066 }
2067 }
2068
2069 void cleanUpVRAM(GrContext* context) {
2070 GrGpu* gpu = context->contextPriv().getGpu();
2071 SkASSERT(gpu);
2072
2073 for (int i = 0; i < fImageInfo.count(); ++i) {
2074 gpu->deleteTestingOnlyBackendTexture(fImageInfo[i].fBackendTexture);
2075 }
2076 }
2077
2078 static void PromiseImageFulfillProc(void* textureContext, GrBackendTexture* outTexture) {
2079 auto imgInfo = static_cast<const PromiseImageInfo*>(textureContext);
2080
2081 SkASSERT(imgInfo->fBackendTexture.isValid());
2082 *outTexture = imgInfo->fBackendTexture;
2083 }
2084
2085 static void PromiseImageReleaseProc(void* textureContext) {
2086 // Do nothing. We free all the backend textures at the end in cleanUpVRAM.
2087 }
2088
2089 static void PromiseImageDoneProc(void* textureContext) {
2090 // Do nothing.
2091 }
2092
2093private:
2094 // returns -1 if not found
2095 int findImage(SkImage* image) const {
2096 for (int i = 0; i < fImageInfo.count(); ++i) {
2097 if (fImageInfo[i].fOriginalUniqueID == image->uniqueID()) {
2098 SkASSERT(fImageInfo[i].fIndex == i);
2099 SkASSERT(this->isValidID(i) && this->isValidID(fImageInfo[i].fIndex));
2100 return i;
2101 }
2102 }
2103 return -1;
2104 }
2105
2106 // returns -1 on failure
2107 int addImage(SkImage* image) {
2108 SkASSERT(!fLocked);
2109
2110 sk_sp<SkImage> rasterImage = image->makeRasterImage(); // force decoding of lazy images
2111
2112 SkImageInfo ii = SkImageInfo::Make(rasterImage->width(), rasterImage->height(),
2113 rasterImage->colorType(), rasterImage->alphaType(),
2114 rasterImage->refColorSpace());
2115
2116 SkBitmap bm;
2117 bm.allocPixels(ii);
2118
2119 if (!rasterImage->readPixels(bm.pixmap(), 0, 0)) {
2120 return -1;
2121 }
2122
2123 bm.setImmutable();
2124
2125 PromiseImageInfo newImageInfo;
2126 newImageInfo.fIndex = fImageInfo.count();
2127 newImageInfo.fOriginalUniqueID = image->uniqueID();
2128 newImageInfo.fBitmap = bm;
2129 /* fBackendTexture is filled in by uploadAllToGPU */
2130
2131 fImageInfo.push_back(newImageInfo);
2132 SkASSERT(newImageInfo.fIndex == fImageInfo.count()-1);
2133 return fImageInfo.count()-1;
2134 }
2135
2136 SkTArray<PromiseImageInfo> fImageInfo;
2137 bool fLocked; // are additions still allowed
2138};
2139
2140// TileData class encapsulates the information and behavior for a single tile/thread in
2141// a DDL rendering.
2142class ViaDDL::TileData {
2143public:
2144 // Note: we could just pass in surface characterization
2145 TileData(sk_sp<SkSurface> surf, const SkIRect& clip)
2146 : fSurface(std::move(surf))
2147 , fClip(clip) {
2148 SkAssertResult(fSurface->characterize(&fCharacterization));
2149 }
2150
2151 // This method operates in parallel
2152 // In each thread we will reconvert the compressedPictureData into an SkPicture
2153 // replacing each image-index with a promise image.
2154 void preprocess(SkData* compressedPictureData, const PromiseImageHelper& helper) {
2155 SkDeferredDisplayListRecorder recorder(fCharacterization);
2156
2157 // DDL TODO: the DDLRecorder's GrContext isn't initialized until getCanvas is called.
2158 // Maybe set it up in the ctor?
2159 SkCanvas* subCanvas = recorder.getCanvas();
2160
2161 sk_sp<SkPicture> reconstitutedPicture;
2162
2163 {
2164 PromiseImageCallbackContext callbackCtx = { &helper, &recorder };
2165
2166 SkDeserialProcs procs;
2167 procs.fImageCtx = &callbackCtx;
2168 procs.fImageProc = PromiseImageCreator;
2169
2170 reconstitutedPicture = SkPicture::MakeFromData(compressedPictureData, &procs);
2171 if (!reconstitutedPicture) {
2172 return;
2173 }
2174 }
2175
2176 subCanvas->clipRect(SkRect::MakeWH(fClip.width(), fClip.height()));
2177 subCanvas->translate(-fClip.fLeft, -fClip.fTop);
2178
2179 // Note: in this use case we only render a picture to the deferred canvas
2180 // but, more generally, clients will use arbitrary draw calls.
2181 subCanvas->drawPicture(reconstitutedPicture);
2182
2183 fDisplayList = recorder.detach();
2184 }
2185
2186 // This method operates serially and replays the recorded DDL into the tile surface.
2187 void draw() {
2188 fSurface->draw(fDisplayList.get());
2189 }
2190
2191 // This method also operates serially and composes the results of replaying the DDL into
2192 // the final destination surface.
2193 void compose(SkCanvas* dst) {
2194 sk_sp<SkImage> img = fSurface->makeImageSnapshot();
2195 dst->save();
2196 dst->clipRect(SkRect::Make(fClip));
2197 dst->drawImage(std::move(img), fClip.fLeft, fClip.fTop);
2198 dst->restore();
2199 }
2200
2201private:
2202 // This class lets us pass the collected image information and the DDLRecorder to the
2203 // promise_image_creator callback when reconstituting a deflated SKP for a particular tile
2204 // (i.e., in a thread).
2205 class PromiseImageCallbackContext {
2206 public:
2207 const PromiseImageHelper* fHelper;
2208 SkDeferredDisplayListRecorder* fRecorder;
2209 };
2210
2211 // This generates promise images to replace the indices in the compressed picture. This
2212 // reconstitution is performed separately in each thread so we end of with multiple
2213 // promise image referring to the same GrBackendTexture.
2214 // DDL TODO: Having multiple promise images using the same GrBackendTexture won't work in
2215 // Vulkan! Move creation of the promise images to the main thread & SkImage.
2216 static sk_sp<SkImage> PromiseImageCreator(const void* rawData, size_t length, void* ctxIn) {
2217 PromiseImageCallbackContext* ctx = static_cast<PromiseImageCallbackContext*>(ctxIn);
2218 const PromiseImageHelper* helper = ctx->fHelper;
2219 SkDeferredDisplayListRecorder* recorder = ctx->fRecorder;
2220
2221 SkASSERT(length == sizeof(int));
2222
2223 const int* indexPtr = static_cast<const int*>(rawData);
2224 SkASSERT(helper->isValidID(*indexPtr));
2225
2226 const PromiseImageHelper::PromiseImageInfo* curImage = helper->getInfo(*indexPtr);
2227 SkASSERT(curImage->fIndex == *indexPtr);
2228
2229 GrBackendFormat backendFormat = curImage->fBackendTexture.format();
2230
2231 // DDL TODO: sort out mipmapping
2232 sk_sp<SkImage> image = recorder->makePromiseTexture(
2233 backendFormat,
2234 curImage->fBitmap.width(),
2235 curImage->fBitmap.height(),
2236 GrMipMapped::kNo,
2237 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
2238 curImage->fBitmap.colorType(),
2239 curImage->fBitmap.alphaType(),
2240 curImage->fBitmap.refColorSpace(),
2241 PromiseImageHelper::PromiseImageFulfillProc,
2242 PromiseImageHelper::PromiseImageReleaseProc,
2243 PromiseImageHelper::PromiseImageDoneProc,
2244 (void*) curImage);
2245 SkASSERT(image);
2246 return image;
2247 }
2248
2249 sk_sp<SkSurface> fSurface;
2250 SkIRect fClip; // in the device space of the dest canvas
2251 std::unique_ptr<SkDeferredDisplayList> fDisplayList;
2252 SkSurfaceCharacterization fCharacterization;
2253};
2254
2255Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2256 auto size = src.size();
2257 SkPictureRecorder recorder;
2258 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2259 SkIntToScalar(size.height())));
2260 if (!err.isEmpty()) {
2261 return err;
2262 }
2263 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
2264
2265 // this is our ultimate final drawing area/rect
2266 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
2267
2268 PromiseImageHelper helper;
2269 sk_sp<SkData> compressedPictureData;
2270
2271 // Convert the SkPicture into SkData replacing all the SkImages with an index.
2272 {
2273 SkSerialProcs procs;
2274
2275 procs.fImageCtx = &helper;
2276 procs.fImageProc = [](SkImage* image, void* ctx) -> sk_sp<SkData> {
2277 auto helper = static_cast<PromiseImageHelper*>(ctx);
2278
2279 int id = helper->findOrDefineImage(image);
2280 if (id >= 0) {
2281 SkASSERT(helper->isValidID(id));
2282 return SkData::MakeWithCopy(&id, sizeof(id));
2283 }
2284
2285 return nullptr;
2286 };
2287
2288 compressedPictureData = inputPicture->serialize(&procs);
2289 if (!compressedPictureData) {
2290 return SkStringPrintf("ViaDDL: Couldn't deflate SkPicture");
2291 }
2292 }
2293
2294 helper.lock(); // after this point no more images should be added to the helper
2295
2296 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2297 [&](SkCanvas* canvas) -> Error {
2298 GrContext* context = canvas->getGrContext();
2299 if (!context || !context->contextPriv().getGpu()) {
2300 return SkStringPrintf("DDLs are GPU only");
2301 }
2302
2303 helper.uploadAllToGPU(context);
2304
2305 int xTileSize = viewport.width()/fNumDivisions;
2306 int yTileSize = viewport.height()/fNumDivisions;
2307
2308 SkTArray<TileData> tileData;
2309 tileData.reserve(fNumDivisions*fNumDivisions);
2310
2311 // First, create the destination tiles
2312 for (int y = 0, yOff = 0; y < fNumDivisions; ++y, yOff += yTileSize) {
2313 int ySize = (y < fNumDivisions-1) ? yTileSize : viewport.height()-yOff;
2314
2315 for (int x = 0, xOff = 0; x < fNumDivisions; ++x, xOff += xTileSize) {
2316 int xSize = (x < fNumDivisions-1) ? xTileSize : viewport.width()-xOff;
2317
2318 SkIRect clip = SkIRect::MakeXYWH(xOff, yOff, xSize, ySize);
2319
2320 SkASSERT(viewport.contains(clip));
2321
2322 SkImageInfo tileII = SkImageInfo::MakeN32Premul(xSize, ySize);
2323
2324 tileData.push_back(TileData(canvas->makeSurface(tileII), clip));
2325 }
2326 }
2327
2328 // Second, run the cpu pre-processing in threads
2329 SkTaskGroup().batch(tileData.count(), [&](int i) {
2330 tileData[i].preprocess(compressedPictureData.get(), helper);
2331 });
2332
2333 // Third, synchronously render the display lists into the dest tiles
2334 // TODO: it would be cool to not wait until all the tiles are drawn to begin
2335 // drawing to the GPU and composing to the final surface
2336 for (int i = 0; i < tileData.count(); ++i) {
2337 tileData[i].draw();
2338 }
2339
2340 // Finally, compose the drawn tiles into the result
2341 // Note: the separation between the tiles and the final composition better
2342 // matches Chrome but costs us a copy
2343 for (int i = 0; i < tileData.count(); ++i) {
2344 tileData[i].compose(canvas);
2345 }
2346
2347 // All promise images need to be fulfilled before leaving this method since we
2348 // are about to delete their backing GrBackendTextures
2349 // DDL TODO: remove the cleanUpVRAM method and use the release & done
2350 // callbacks.
2351 GrGpu* gpu = context->contextPriv().getGpu();
Robert Phillipscc473352018-03-27 10:46:00 -04002352 context->flush();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002353 gpu->testingOnly_flushGpuAndSync();
2354
2355 helper.cleanUpVRAM(context);
2356 return "";
2357 });
2358}
2359
2360#else
2361
2362ViaDDL::ViaDDL(int numDivisions, Sink* sink) : Via(sink) { }
2363
2364Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2365 return "ViaDDL is GPU only";
2366}
2367
2368#endif
2369
2370/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2371
mtklein4a34ecb2016-01-08 10:19:35 -08002372Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2373 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002374 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtklein4a34ecb2016-01-08 10:19:35 -08002375 SkPictureRecorder recorder;
reedca2622b2016-03-18 07:25:55 -07002376 sk_sp<SkPicture> pic;
mtklein4a34ecb2016-01-08 10:19:35 -08002377 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2378 SkIntToScalar(size.height())));
2379 if (!err.isEmpty()) {
2380 return err;
2381 }
reedca2622b2016-03-18 07:25:55 -07002382 pic = recorder.finishRecordingAsPicture();
mtklein4a34ecb2016-01-08 10:19:35 -08002383 canvas->drawPicture(pic);
Ben Wagner1861e882018-04-04 17:40:46 -04002384 return err;
mtklein4a34ecb2016-01-08 10:19:35 -08002385 });
Ben Wagner1861e882018-04-04 17:40:46 -04002386 if (!err.isEmpty()) {
2387 return err;
2388 }
2389
2390 return check_against_reference(bitmap, src, fSink.get());
mtklein4a34ecb2016-01-08 10:19:35 -08002391}
2392
2393/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2394
reed54dc4872016-09-13 08:09:45 -07002395Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2396 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002397 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
reed54dc4872016-09-13 08:09:45 -07002398 SkDynamicMemoryWStream tmpStream;
2399 Error err = src.draw(SkPipeSerializer().beginWrite(SkRect::Make(size), &tmpStream));
2400 if (!err.isEmpty()) {
2401 return err;
2402 }
2403 sk_sp<SkData> data = tmpStream.detachAsData();
2404 SkPipeDeserializer().playback(data->data(), data->size(), canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002405 return err;
reed54dc4872016-09-13 08:09:45 -07002406 });
Ben Wagner1861e882018-04-04 17:40:46 -04002407 if (!err.isEmpty()) {
2408 return err;
2409 }
2410
2411 return check_against_reference(bitmap, src, fSink.get());
reed54dc4872016-09-13 08:09:45 -07002412}
2413
2414/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2415
Mike Reedbae888e2017-02-18 16:50:45 -05002416#ifdef TEST_VIA_SVG
Mike Reedf67c4592017-02-17 17:06:11 -05002417#include "SkXMLWriter.h"
2418#include "SkSVGCanvas.h"
2419#include "SkSVGDOM.h"
2420
2421Error ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2422 auto size = src.size();
2423 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
2424 SkDynamicMemoryWStream wstream;
2425 SkXMLStreamWriter writer(&wstream);
2426 Error err = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
2427 if (!err.isEmpty()) {
2428 return err;
2429 }
2430 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2431 auto dom = SkSVGDOM::MakeFromStream(*rstream);
2432 if (dom) {
2433 dom->setContainerSize(SkSize::Make(size));
2434 dom->render(canvas);
2435 }
2436 return "";
2437 });
2438}
Mike Reedbae888e2017-02-18 16:50:45 -05002439#endif
Mike Reedf67c4592017-02-17 17:06:11 -05002440
2441/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2442
mtklein9c5052f2016-08-06 12:51:51 -07002443Error ViaLite::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2444 auto size = src.size();
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002445 SkIRect bounds = {0,0, size.width(), size.height()};
Ben Wagner1861e882018-04-04 17:40:46 -04002446 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002447 SkLiteDL dl;
mtklein8bbbb692016-08-15 12:56:00 -07002448 SkLiteRecorder rec;
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002449 rec.reset(&dl, bounds);
mtklein8bbbb692016-08-15 12:56:00 -07002450
2451 Error err = src.draw(&rec);
mtklein9c5052f2016-08-06 12:51:51 -07002452 if (!err.isEmpty()) {
2453 return err;
2454 }
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002455 dl.draw(canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002456 return err;
mtklein9c5052f2016-08-06 12:51:51 -07002457 });
Ben Wagner1861e882018-04-04 17:40:46 -04002458 if (!err.isEmpty()) {
2459 return err;
2460 }
2461
2462 return check_against_reference(bitmap, src, fSink.get());
mtklein9c5052f2016-08-06 12:51:51 -07002463}
2464
Mike Klein841101d2017-03-10 09:55:51 -05002465/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2466
Mike Klein919cc452017-03-18 15:36:52 +00002467ViaCSXform::ViaCSXform(Sink* sink, sk_sp<SkColorSpace> cs, bool colorSpin)
2468 : Via(sink)
2469 , fCS(std::move(cs))
2470 , fColorSpin(colorSpin) {}
Mike Klein841101d2017-03-10 09:55:51 -05002471
2472Error ViaCSXform::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2473 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
2474 [&](SkCanvas* canvas) -> Error {
Brian Osman5b7e4702017-10-31 16:41:29 -04002475 {
2476 SkAutoCanvasRestore acr(canvas, true);
2477 auto proxy = SkCreateColorSpaceXformCanvas(canvas, fCS);
2478 Error err = src.draw(proxy.get());
2479 if (!err.isEmpty()) {
2480 return err;
2481 }
Mike Klein919cc452017-03-18 15:36:52 +00002482 }
2483
2484 // Undo the color spin, so we can look at the pixels in Gold.
2485 if (fColorSpin) {
2486 SkBitmap pixels;
2487 pixels.allocPixels(canvas->imageInfo());
Mike Reed12e946b2017-04-17 10:53:29 -04002488 canvas->readPixels(pixels, 0, 0);
Mike Klein919cc452017-03-18 15:36:52 +00002489
Brian Osman5b7e4702017-10-31 16:41:29 -04002490 SkPaint rotateColors;
2491 SkScalar matrix[20] = { 0, 0, 1, 0, 0, // B -> R
2492 1, 0, 0, 0, 0, // R -> G
2493 0, 1, 0, 0, 0, // G -> B
2494 0, 0, 0, 1, 0 };
2495 rotateColors.setBlendMode(SkBlendMode::kSrc);
2496 rotateColors.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(matrix));
2497 canvas->drawBitmap(pixels, 0, 0, &rotateColors);
Mike Klein919cc452017-03-18 15:36:52 +00002498 }
2499
2500 return "";
Mike Klein841101d2017-03-10 09:55:51 -05002501 });
2502}
2503
mtklein748ca3b2015-01-15 10:56:12 -08002504} // namespace DM