blob: ea21d7a69593c98df6627ee1360cddfa5669f067 [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"
msarett3d9d7a72015-10-21 10:27:10 -07009#include "SkAndroidCodec.h"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkCodec.h"
msarettb714fb02016-01-22 14:46:42 -080011#include "SkCodecImageGenerator.h"
mtkleina16e69e2015-05-05 11:38:45 -070012#include "SkCommonFlags.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070013#include "SkData.h"
mtklein748ca3b2015-01-15 10:56:12 -080014#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080015#include "SkError.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070016#include "SkImageGenerator.h"
mtkleinc8be09a2016-01-04 18:56:57 -080017#include "SkMallocPixelRef.h"
mtklein748ca3b2015-01-15 10:56:12 -080018#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080019#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080020#include "SkOSFile.h"
msarett9e9444c2016-02-03 12:39:10 -080021#include "SkOpts.h"
mtkleinffa901a2015-03-16 10:38:07 -070022#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080023#include "SkPictureRecorder.h"
24#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070025#include "SkRecordDraw.h"
26#include "SkRecorder.h"
mtklein2e2ea382015-10-16 10:29:41 -070027#include "SkRemote.h"
fmalita2aafe6f2015-02-06 12:51:10 -080028#include "SkSVGCanvas.h"
scroggoa1193e42015-01-21 12:09:53 -080029#include "SkStream.h"
mtklein449d9b72015-09-28 10:33:02 -070030#include "SkTLogic.h"
fmalita2aafe6f2015-02-06 12:51:10 -080031#include "SkXMLWriter.h"
msarette6dd0042015-10-09 11:07:34 -070032#include "SkSwizzler.h"
mtklein64593522015-11-12 10:41:05 -080033#include <functional>
mtklein748ca3b2015-01-15 10:56:12 -080034
halcanary7a76f9c2016-02-03 11:53:18 -080035#ifdef SK_MOJO
36 #include "SkMojo.mojom.h"
37#endif
38
halcanary7e798182015-04-14 14:06:18 -070039DEFINE_bool(multiPage, false, "For document-type backends, render the source"
40 " into multiple pages");
scroggo3ac66e92016-02-08 15:09:48 -080041DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
halcanary7e798182015-04-14 14:06:18 -070042
mtklein748ca3b2015-01-15 10:56:12 -080043namespace DM {
44
mtklein748ca3b2015-01-15 10:56:12 -080045GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
46
47Error GMSrc::draw(SkCanvas* canvas) const {
halcanary96fcdcc2015-08-27 07:41:13 -070048 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080049 canvas->concat(gm->getInitialTransform());
50 gm->draw(canvas);
51 return "";
52}
53
54SkISize GMSrc::size() const {
halcanary96fcdcc2015-08-27 07:41:13 -070055 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080056 return gm->getISize();
57}
58
59Name GMSrc::name() const {
halcanary96fcdcc2015-08-27 07:41:13 -070060 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080061 return gm->getName();
62}
63
bsalomon4ee6bd82015-05-27 13:23:23 -070064void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
halcanary96fcdcc2015-08-27 07:41:13 -070065 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -070066 gm->modifyGrContextOptions(options);
67}
68
mtklein748ca3b2015-01-15 10:56:12 -080069/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
70
msarett5cb48852015-11-06 08:56:32 -080071BRDSrc::BRDSrc(Path path, SkBitmapRegionDecoder::Strategy strategy, Mode mode,
msaretta5783ae2015-09-08 15:35:32 -070072 CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
73 : fPath(path)
74 , fStrategy(strategy)
75 , fMode(mode)
76 , fDstColorType(dstColorType)
77 , fSampleSize(sampleSize)
78{}
79
80bool BRDSrc::veto(SinkFlags flags) const {
81 // No need to test to non-raster or indirect backends.
82 return flags.type != SinkFlags::kRaster
83 || flags.approach != SinkFlags::kDirect;
84}
85
msarett5cb48852015-11-06 08:56:32 -080086static SkBitmapRegionDecoder* create_brd(Path path,
87 SkBitmapRegionDecoder::Strategy strategy) {
msaretta5783ae2015-09-08 15:35:32 -070088 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
89 if (!encoded) {
90 return NULL;
91 }
msarett5cb48852015-11-06 08:56:32 -080092 return SkBitmapRegionDecoder::Create(encoded, strategy);
msaretta5783ae2015-09-08 15:35:32 -070093}
94
95Error BRDSrc::draw(SkCanvas* canvas) const {
96 SkColorType colorType = canvas->imageInfo().colorType();
97 if (kRGB_565_SkColorType == colorType &&
98 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
99 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
100 }
101 switch (fDstColorType) {
102 case CodecSrc::kGetFromCanvas_DstColorType:
103 break;
104 case CodecSrc::kIndex8_Always_DstColorType:
105 colorType = kIndex_8_SkColorType;
106 break;
107 case CodecSrc::kGrayscale_Always_DstColorType:
108 colorType = kGray_8_SkColorType;
109 break;
110 }
111
msarett5cb48852015-11-06 08:56:32 -0800112 SkAutoTDelete<SkBitmapRegionDecoder> brd(create_brd(fPath, fStrategy));
msaretta5783ae2015-09-08 15:35:32 -0700113 if (nullptr == brd.get()) {
114 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
115 }
116
msarett04965c62015-10-12 10:24:38 -0700117 if (!brd->conversionSupported(colorType)) {
mtklein9b439152015-12-09 13:02:26 -0800118 return Error::Nonfatal("Cannot convert to color type.");
msarett04965c62015-10-12 10:24:38 -0700119 }
120
msaretta5783ae2015-09-08 15:35:32 -0700121 const uint32_t width = brd->width();
122 const uint32_t height = brd->height();
123 // Visually inspecting very small output images is not necessary.
124 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
125 return Error::Nonfatal("Scaling very small images is uninteresting.");
126 }
127 switch (fMode) {
128 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700129 SkBitmap bitmap;
130 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
131 fSampleSize, colorType, false)) {
mtklein9b439152015-12-09 13:02:26 -0800132 return "Cannot decode (full) region.";
msarett35e5d1b2015-10-27 12:50:25 -0700133 }
134 if (colorType != bitmap.colorType()) {
mtklein9b439152015-12-09 13:02:26 -0800135 return Error::Nonfatal("Cannot convert to color type.");
msaretta5783ae2015-09-08 15:35:32 -0700136 }
msarett35e5d1b2015-10-27 12:50:25 -0700137 canvas->drawBitmap(bitmap, 0, 0);
msaretta5783ae2015-09-08 15:35:32 -0700138 return "";
139 }
140 case kDivisor_Mode: {
141 const uint32_t divisor = 2;
142 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800143 return Error::Nonfatal("Divisor is larger than image dimension.");
msaretta5783ae2015-09-08 15:35:32 -0700144 }
145
146 // Use a border to test subsets that extend outside the image.
147 // We will not allow the border to be larger than the image dimensions. Allowing
148 // these large borders causes off by one errors that indicate a problem with the
149 // test suite, not a problem with the implementation.
150 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
151 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
152 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
153
154 // We may need to clear the canvas to avoid uninitialized memory.
155 // Assume we are scaling a 780x780 image with sampleSize = 8.
156 // The output image should be 97x97.
157 // Each subset will be 390x390.
158 // Each scaled subset be 48x48.
159 // Four scaled subsets will only fill a 96x96 image.
160 // The bottom row and last column will not be touched.
161 // This is an unfortunate result of our rounding rules when scaling.
162 // Maybe we need to consider testing scaled subsets without trying to
163 // combine them to match the full scaled image? Or maybe this is the
164 // best we can do?
165 canvas->clear(0);
166
167 for (uint32_t x = 0; x < divisor; x++) {
168 for (uint32_t y = 0; y < divisor; y++) {
169 // Calculate the subset dimensions
170 uint32_t subsetWidth = width / divisor;
171 uint32_t subsetHeight = height / divisor;
172 const int left = x * subsetWidth;
173 const int top = y * subsetHeight;
174
175 // Increase the size of the last subset in each row or column, when the
176 // divisor does not divide evenly into the image dimensions
177 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
178 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
179
180 // Increase the size of the subset in order to have a border on each side
181 const int decodeLeft = left - unscaledBorder;
182 const int decodeTop = top - unscaledBorder;
183 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
184 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700185 SkBitmap bitmap;
186 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
187 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false)) {
mtklein9b439152015-12-09 13:02:26 -0800188 return "Cannot decode region.";
msarett35e5d1b2015-10-27 12:50:25 -0700189 }
190 if (colorType != bitmap.colorType()) {
mtklein9b439152015-12-09 13:02:26 -0800191 return Error::Nonfatal("Cannot convert to color type.");
msaretta5783ae2015-09-08 15:35:32 -0700192 }
193
msarett35e5d1b2015-10-27 12:50:25 -0700194 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700195 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
196 (SkScalar) (subsetWidth / fSampleSize),
197 (SkScalar) (subsetHeight / fSampleSize)),
198 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
199 (SkScalar) (top / fSampleSize),
200 (SkScalar) (subsetWidth / fSampleSize),
201 (SkScalar) (subsetHeight / fSampleSize)),
202 nullptr);
203 }
204 }
205 return "";
206 }
207 default:
208 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800209 return "Error: Should not be reached.";
msaretta5783ae2015-09-08 15:35:32 -0700210 }
211}
212
213SkISize BRDSrc::size() const {
msarett5cb48852015-11-06 08:56:32 -0800214 SkAutoTDelete<SkBitmapRegionDecoder> brd(create_brd(fPath, fStrategy));
msaretta5783ae2015-09-08 15:35:32 -0700215 if (brd) {
216 return SkISize::Make(SkTMax(1, brd->width() / (int) fSampleSize),
217 SkTMax(1, brd->height() / (int) fSampleSize));
218 }
219 return SkISize::Make(0, 0);
220}
221
222static SkString get_scaled_name(const Path& path, float scale) {
223 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
224}
225
226Name BRDSrc::name() const {
227 // We will replicate the names used by CodecSrc so that images can
228 // be compared in Gold.
229 if (1 == fSampleSize) {
230 return SkOSPath::Basename(fPath.c_str());
231 }
msarett4b0778e2015-11-13 09:59:11 -0800232 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700233}
234
235/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
236
scroggo3ac66e92016-02-08 15:09:48 -0800237static bool serial_from_path_name(const SkString& path) {
238 if (!FLAGS_RAW_threading) {
239 static const char* const exts[] = {
240 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
241 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
242 };
243 const char* actualExt = strrchr(path.c_str(), '.');
244 if (actualExt) {
245 actualExt++;
246 for (auto* ext : exts) {
247 if (0 == strcmp(ext, actualExt)) {
248 return true;
249 }
250 }
251 }
252 }
253 return false;
254}
255
scroggoc5560be2016-02-03 09:42:42 -0800256CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
257 float scale)
msarett438b2ad2015-04-09 12:43:10 -0700258 : fPath(path)
259 , fMode(mode)
260 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800261 , fDstAlphaType(dstAlphaType)
msarett0a242972015-06-11 14:27:27 -0700262 , fScale(scale)
scroggo3ac66e92016-02-08 15:09:48 -0800263 , fRunSerially(serial_from_path_name(path))
msarett438b2ad2015-04-09 12:43:10 -0700264{}
mtklein748ca3b2015-01-15 10:56:12 -0800265
mtklein99cab4e2015-07-31 06:43:04 -0700266bool CodecSrc::veto(SinkFlags flags) const {
msarettb714fb02016-01-22 14:46:42 -0800267 // Test CodecImageGenerator on 8888, 565, and gpu
268 if (kGen_Mode == fMode) {
msarett36c070d2016-02-10 06:48:21 -0800269 // For image generator, we want to test kDirect approaches for kRaster and kGPU,
270 // while skipping everything else.
271 return (flags.type != SinkFlags::kRaster && flags.type != SinkFlags::kGPU) ||
msaretta23659f2016-02-09 12:39:17 -0800272 flags.approach != SinkFlags::kDirect;
msarettb714fb02016-01-22 14:46:42 -0800273 }
274
275 // Test all other modes to direct raster backends (8888 and 565).
276 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700277}
scroggo9b77ddd2015-03-19 06:03:39 -0700278
msarett9e9444c2016-02-03 12:39:10 -0800279// FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
280// This allows us to still test unpremultiplied decodes.
281void premultiply_if_necessary(SkBitmap& bitmap) {
282 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
283 return;
284 }
285
286 switch (bitmap.colorType()) {
287 case kN32_SkColorType:
288 for (int y = 0; y < bitmap.height(); y++) {
289 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
290 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
291 }
292 break;
293 case kIndex_8_SkColorType: {
294 SkColorTable* colorTable = bitmap.getColorTable();
295 SkPMColor* colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
296 SkOpts::RGBA_to_rgbA(colorPtr, colorPtr, colorTable->count());
297 break;
298 }
299 default:
300 // No need to premultiply kGray or k565 outputs.
301 break;
302 }
msarette1daa482016-02-03 15:31:18 -0800303
304 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
305 // bitmap as kPremul.
306 bitmap.setAlphaType(kPremul_SkAlphaType);
msarett9e9444c2016-02-03 12:39:10 -0800307}
308
scroggoc5560be2016-02-03 09:42:42 -0800309bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
310 CodecSrc::DstColorType dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700311 switch (dstColorType) {
312 case CodecSrc::kIndex8_Always_DstColorType:
313 if (kRGB_565_SkColorType == canvasColorType) {
314 return false;
315 }
scroggoc5560be2016-02-03 09:42:42 -0800316 *decodeInfo = decodeInfo->makeColorType(kIndex_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700317 break;
318 case CodecSrc::kGrayscale_Always_DstColorType:
msarett55f7bdd2016-02-16 13:24:54 -0800319 if (kRGB_565_SkColorType == canvasColorType ||
320 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
msarett3d9d7a72015-10-21 10:27:10 -0700321 return false;
322 }
scroggoc5560be2016-02-03 09:42:42 -0800323 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700324 break;
325 default:
msarett55f7bdd2016-02-16 13:24:54 -0800326 if (kRGB_565_SkColorType == canvasColorType &&
327 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
328 return false;
329 }
scroggoc5560be2016-02-03 09:42:42 -0800330 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700331 break;
332 }
333
msarett3d9d7a72015-10-21 10:27:10 -0700334 return true;
335}
336
msarettb714fb02016-01-22 14:46:42 -0800337Error test_gen(SkCanvas* canvas, SkData* data) {
msarett01813e82016-01-25 10:51:29 -0800338 SkAutoTDelete<SkImageGenerator> gen = SkCodecImageGenerator::NewFromEncodedCodec(data);
msarettb714fb02016-01-22 14:46:42 -0800339 if (!gen) {
340 return "Could not create image generator.";
341 }
342
343 // FIXME: The gpu backend does not draw kGray sources correctly. (skbug.com/4822)
344 // Currently, we will avoid creating a CodecSrc for this case (see DM.cpp).
345 SkASSERT(kGray_8_SkColorType != gen->getInfo().colorType());
346
msarettd03b7ae2016-01-25 08:20:55 -0800347 if (kOpaque_SkAlphaType != gen->getInfo().alphaType() &&
348 kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
349 return Error::Nonfatal("Skip testing non-opaque images to 565.");
350 }
351
msarett01813e82016-01-25 10:51:29 -0800352 SkAutoTDelete<SkImage> image(SkImage::NewFromGenerator(gen.detach(), nullptr));
msarettb714fb02016-01-22 14:46:42 -0800353 if (!image) {
354 return "Could not create image from codec image generator.";
355 }
356
357 canvas->drawImage(image, 0, 0);
358 return "";
359}
360
mtkleine0effd62015-07-29 06:37:28 -0700361Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800362 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800363 if (!encoded) {
364 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
365 }
msarettb714fb02016-01-22 14:46:42 -0800366
367 // The CodecImageGenerator test does not share much code with the other tests,
368 // so we will handle it in its own function.
369 if (kGen_Mode == fMode) {
370 return test_gen(canvas, encoded);
371 }
372
msarett3d9d7a72015-10-21 10:27:10 -0700373 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700374 if (nullptr == codec.get()) {
375 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700376 }
377
scroggoc5560be2016-02-03 09:42:42 -0800378 SkImageInfo decodeInfo = codec->getInfo().makeAlphaType(fDstAlphaType);
379 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType)) {
msarett3d9d7a72015-10-21 10:27:10 -0700380 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
msarett438b2ad2015-04-09 12:43:10 -0700381 }
382
msarett0a242972015-06-11 14:27:27 -0700383 // Try to scale the image if it is desired
384 SkISize size = codec->getScaledDimensions(fScale);
385 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
386 return Error::Nonfatal("Test without scaling is uninteresting.");
387 }
msarettb32758a2015-08-18 13:22:46 -0700388
389 // Visually inspecting very small output images is not necessary. We will
390 // cover these cases in unit testing.
391 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
392 return Error::Nonfatal("Scaling very small images is uninteresting.");
393 }
msarett0a242972015-06-11 14:27:27 -0700394 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
395
msarett438b2ad2015-04-09 12:43:10 -0700396 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700397 SkAutoTUnref<SkColorTable> colorTable(nullptr);
398 SkPMColor* colorPtr = nullptr;
399 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700400 int maxColors = 256;
401 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
402 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700403 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700404 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
405 colorCountPtr = &maxColors;
406 }
407
scroggo9b77ddd2015-03-19 06:03:39 -0700408 SkBitmap bitmap;
msarettbb25b532016-01-13 09:31:39 -0800409 SkPixelRefFactory* factory = nullptr;
410 SkMallocPixelRef::ZeroedPRFactory zeroFactory;
411 SkCodec::Options options;
412 if (kCodecZeroInit_Mode == fMode) {
413 factory = &zeroFactory;
414 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
415 }
416 if (!bitmap.tryAllocPixels(decodeInfo, factory, colorTable.get())) {
mtklein9b439152015-12-09 13:02:26 -0800417 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
scroggo9b77ddd2015-03-19 06:03:39 -0700418 decodeInfo.width(), decodeInfo.height());
419 }
420
scroggo9c59ebc2015-03-25 13:48:49 -0700421 switch (fMode) {
msarettbb25b532016-01-13 09:31:39 -0800422 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700423 case kCodec_Mode: {
msarettbb25b532016-01-13 09:31:39 -0800424 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), &options,
msarett438b2ad2015-04-09 12:43:10 -0700425 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700426 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700427 // We consider incomplete to be valid, since we should still decode what is
428 // available.
scroggoeb602a52015-07-09 08:16:03 -0700429 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700430 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700431 default:
432 // Everything else is considered a failure.
433 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
434 }
msarett9e9444c2016-02-03 12:39:10 -0800435 premultiply_if_necessary(bitmap);
emmaleer97002062015-05-27 12:36:10 -0700436 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700437 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700438 }
scroggo9c59ebc2015-03-25 13:48:49 -0700439 case kScanline_Mode: {
scroggo46c57472015-09-30 08:57:13 -0700440 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
441 colorCountPtr)) {
msarettb65e6042016-02-23 05:37:25 -0800442 return "Could not start scanline decoder";
scroggo9c59ebc2015-03-25 13:48:49 -0700443 }
scroggo1c005e42015-08-04 09:24:45 -0700444
msarette6dd0042015-10-09 11:07:34 -0700445 void* dst = bitmap.getAddr(0, 0);
446 size_t rowBytes = bitmap.rowBytes();
447 uint32_t height = decodeInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700448 switch (codec->getScanlineOrder()) {
449 case SkCodec::kTopDown_SkScanlineOrder:
450 case SkCodec::kBottomUp_SkScanlineOrder:
451 case SkCodec::kNone_SkScanlineOrder:
msarette6dd0042015-10-09 11:07:34 -0700452 // We do not need to check the return value. On an incomplete
453 // image, memory will be filled with a default value.
454 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700455 break;
scroggo46c57472015-09-30 08:57:13 -0700456 case SkCodec::kOutOfOrder_SkScanlineOrder: {
msarett10522ff2015-09-07 08:54:01 -0700457 for (int y = 0; y < decodeInfo.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700458 int dstY = codec->outputScanline(y);
msarett10522ff2015-09-07 08:54:01 -0700459 void* dstPtr = bitmap.getAddr(0, dstY);
msarette6dd0042015-10-09 11:07:34 -0700460 // We complete the loop, even if this call begins to fail
461 // due to an incomplete image. This ensures any uninitialized
462 // memory will be filled with the proper value.
463 codec->getScanlines(dstPtr, 1, bitmap.rowBytes());
msarett10522ff2015-09-07 08:54:01 -0700464 }
465 break;
466 }
467 }
468
msarett9e9444c2016-02-03 12:39:10 -0800469 premultiply_if_necessary(bitmap);
emmaleer97002062015-05-27 12:36:10 -0700470 canvas->drawBitmap(bitmap, 0, 0);
471 break;
472 }
msarett0a242972015-06-11 14:27:27 -0700473 case kStripe_Mode: {
474 const int height = decodeInfo.height();
475 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
476 // does not align with image blocks.
477 const int stripeHeight = 37;
478 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
479
480 // Decode odd stripes
scroggo46c57472015-09-30 08:57:13 -0700481 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
msarettb65e6042016-02-23 05:37:25 -0800482 colorCountPtr)) {
483 return "Could not start scanline decoder";
484 }
485
486 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
487 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
488 // to run this test for image types that do not have this scanline ordering.
489 if (SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
490 return Error::Nonfatal("kStripe test is only interesting for kTopDown codecs.");
msarett0a242972015-06-11 14:27:27 -0700491 }
msarette6dd0042015-10-09 11:07:34 -0700492
msarett0a242972015-06-11 14:27:27 -0700493 for (int i = 0; i < numStripes; i += 2) {
494 // Skip a stripe
495 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700496 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700497
498 // Read a stripe
499 const int startY = (i + 1) * stripeHeight;
500 const int linesToRead = SkTMin(stripeHeight, height - startY);
501 if (linesToRead > 0) {
msarette6dd0042015-10-09 11:07:34 -0700502 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700503 }
504 }
505
506 // Decode even stripes
scroggo46c57472015-09-30 08:57:13 -0700507 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
508 colorPtr, colorCountPtr);
scroggo1c005e42015-08-04 09:24:45 -0700509 if (SkCodec::kSuccess != startResult) {
510 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700511 }
512 for (int i = 0; i < numStripes; i += 2) {
513 // Read a stripe
514 const int startY = i * stripeHeight;
515 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarette6dd0042015-10-09 11:07:34 -0700516 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700517
518 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700519 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
520 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700521 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700522 }
523 }
msarett9e9444c2016-02-03 12:39:10 -0800524 premultiply_if_necessary(bitmap);
msarett0a242972015-06-11 14:27:27 -0700525 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700526 break;
msarett0a242972015-06-11 14:27:27 -0700527 }
msarett91c22b22016-02-22 12:27:46 -0800528 case kCroppedScanline_Mode: {
529 const int width = decodeInfo.width();
530 const int height = decodeInfo.height();
531 // This value is chosen because, as we move across the image, it will sometimes
532 // align with the jpeg block sizes and it will sometimes not. This allows us
533 // to test interestingly different code paths in the implementation.
534 const int tileSize = 36;
535
536 SkCodec::Options opts;
537 SkIRect subset;
538 for (int x = 0; x < width; x += tileSize) {
539 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
540 opts.fSubset = &subset;
541 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &opts,
542 colorPtr, colorCountPtr)) {
543 return "Could not start scanline decoder.";
544 }
545
546 codec->getScanlines(bitmap.getAddr(x, 0), height, bitmap.rowBytes());
547 }
548
549 premultiply_if_necessary(bitmap);
550 canvas->drawBitmap(bitmap, 0, 0);
551 break;
552 }
scroggob636b452015-07-22 07:16:20 -0700553 case kSubset_Mode: {
554 // Arbitrarily choose a divisor.
555 int divisor = 2;
556 // Total width/height of the image.
557 const int W = codec->getInfo().width();
558 const int H = codec->getInfo().height();
559 if (divisor > W || divisor > H) {
560 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
561 "for %s with dimensions (%d x %d)", divisor,
562 fPath.c_str(), W, H));
563 }
564 // subset dimensions
565 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
566 const int w = SkAlign2(W / divisor);
567 const int h = SkAlign2(H / divisor);
568 SkIRect subset;
569 SkCodec::Options opts;
570 opts.fSubset = &subset;
571 SkBitmap subsetBm;
572 // We will reuse pixel memory from bitmap.
573 void* pixels = bitmap.getPixels();
574 // Keep track of left and top (for drawing subsetBm into canvas). We could use
575 // fScale * x and fScale * y, but we want integers such that the next subset will start
576 // where the last one ended. So we'll add decodeInfo.width() and height().
577 int left = 0;
578 for (int x = 0; x < W; x += w) {
579 int top = 0;
580 for (int y = 0; y < H; y+= h) {
581 // Do not make the subset go off the edge of the image.
582 const int preScaleW = SkTMin(w, W - x);
583 const int preScaleH = SkTMin(h, H - y);
584 subset.setXYWH(x, y, preScaleW, preScaleH);
585 // And scale
586 // FIXME: Should we have a version of getScaledDimensions that takes a subset
587 // into account?
msarette6dd0042015-10-09 11:07:34 -0700588 decodeInfo = decodeInfo.makeWH(
589 SkTMax(1, SkScalarRoundToInt(preScaleW * fScale)),
590 SkTMax(1, SkScalarRoundToInt(preScaleH * fScale)));
scroggob636b452015-07-22 07:16:20 -0700591 size_t rowBytes = decodeInfo.minRowBytes();
592 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700593 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700594 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
595 }
596 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
597 &opts, colorPtr, colorCountPtr);
598 switch (result) {
599 case SkCodec::kSuccess:
600 case SkCodec::kIncompleteInput:
601 break;
scroggob636b452015-07-22 07:16:20 -0700602 default:
603 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
604 "from %s with dimensions (%d x %d)\t error %d",
605 x, y, decodeInfo.width(), decodeInfo.height(),
606 fPath.c_str(), W, H, result);
607 }
msarett9e9444c2016-02-03 12:39:10 -0800608 premultiply_if_necessary(subsetBm);
scroggob636b452015-07-22 07:16:20 -0700609 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
610 // translate by the scaled height.
611 top += decodeInfo.height();
612 }
613 // translate by the scaled width.
614 left += decodeInfo.width();
615 }
616 return "";
617 }
msarettb714fb02016-01-22 14:46:42 -0800618 default:
619 SkASSERT(false);
620 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700621 }
scroggo9c59ebc2015-03-25 13:48:49 -0700622 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700623}
624
625SkISize CodecSrc::size() const {
626 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700627 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700628 if (nullptr == codec) {
629 return SkISize::Make(0, 0);
630 }
631 return codec->getScaledDimensions(fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700632}
633
634Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700635 if (1.0f == fScale) {
636 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700637 }
msaretta5783ae2015-09-08 15:35:32 -0700638 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700639}
640
641/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
642
msarett3d9d7a72015-10-21 10:27:10 -0700643AndroidCodecSrc::AndroidCodecSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800644 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700645 : fPath(path)
646 , fMode(mode)
647 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800648 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700649 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800650 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700651{}
652
653bool AndroidCodecSrc::veto(SinkFlags flags) const {
654 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700655 return flags.type != SinkFlags::kRaster
656 || flags.approach != SinkFlags::kDirect;
657}
658
659Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
660 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
661 if (!encoded) {
662 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
663 }
664 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
665 if (nullptr == codec.get()) {
666 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
667 }
668
scroggoc5560be2016-02-03 09:42:42 -0800669 SkImageInfo decodeInfo = codec->getInfo().makeAlphaType(fDstAlphaType);
670 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType)) {
msarett3d9d7a72015-10-21 10:27:10 -0700671 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
672 }
673
674 // Scale the image if it is desired.
675 SkISize size = codec->getSampledDimensions(fSampleSize);
676
677 // Visually inspecting very small output images is not necessary. We will
678 // cover these cases in unit testing.
679 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
680 return Error::Nonfatal("Scaling very small images is uninteresting.");
681 }
682 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
683
684 // Construct a color table for the decode if necessary
685 SkAutoTUnref<SkColorTable> colorTable(nullptr);
686 SkPMColor* colorPtr = nullptr;
687 int* colorCountPtr = nullptr;
688 int maxColors = 256;
689 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
690 SkPMColor colors[256];
691 colorTable.reset(new SkColorTable(colors, maxColors));
692 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
693 colorCountPtr = &maxColors;
694 }
695
696 SkBitmap bitmap;
697 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
mtklein9b439152015-12-09 13:02:26 -0800698 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
msarett3d9d7a72015-10-21 10:27:10 -0700699 decodeInfo.width(), decodeInfo.height());
700 }
701
702 // Create options for the codec.
703 SkAndroidCodec::AndroidOptions options;
704 options.fColorPtr = colorPtr;
705 options.fColorCount = colorCountPtr;
706 options.fSampleSize = fSampleSize;
707
708 switch (fMode) {
709 case kFullImage_Mode: {
710 switch (codec->getAndroidPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(),
711 &options)) {
712 case SkCodec::kSuccess:
713 case SkCodec::kIncompleteInput:
714 break;
msarett3d9d7a72015-10-21 10:27:10 -0700715 default:
716 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
717 }
msarett9e9444c2016-02-03 12:39:10 -0800718 premultiply_if_necessary(bitmap);
msarett3d9d7a72015-10-21 10:27:10 -0700719 canvas->drawBitmap(bitmap, 0, 0);
720 return "";
721 }
722 case kDivisor_Mode: {
723 const int width = codec->getInfo().width();
724 const int height = codec->getInfo().height();
725 const int divisor = 2;
726 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800727 return Error::Nonfatal("Divisor is larger than image dimension.");
msarett3d9d7a72015-10-21 10:27:10 -0700728 }
729
msarettfa23a9e2015-10-21 13:26:59 -0700730 // Keep track of the final decoded dimensions.
731 int finalScaledWidth = 0;
732 int finalScaledHeight = 0;
msarett3d9d7a72015-10-21 10:27:10 -0700733 for (int x = 0; x < divisor; x++) {
734 for (int y = 0; y < divisor; y++) {
735 // Calculate the subset dimensions
736 int subsetWidth = width / divisor;
737 int subsetHeight = height / divisor;
738 const int left = x * subsetWidth;
739 const int top = y * subsetHeight;
740
741 // Increase the size of the last subset in each row or column, when the
742 // divisor does not divide evenly into the image dimensions
743 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
744 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
745 SkIRect subset = SkIRect::MakeXYWH(left, top, subsetWidth, subsetHeight);
746 if (!codec->getSupportedSubset(&subset)) {
mtklein9b439152015-12-09 13:02:26 -0800747 return "Could not get supported subset to decode.";
msarett3d9d7a72015-10-21 10:27:10 -0700748 }
749 options.fSubset = &subset;
msarettfa23a9e2015-10-21 13:26:59 -0700750 const int scaledWidthOffset = subset.left() / fSampleSize;
751 const int scaledHeightOffset = subset.top() / fSampleSize;
752 void* pixels = bitmap.getAddr(scaledWidthOffset, scaledHeightOffset);
msarett3d9d7a72015-10-21 10:27:10 -0700753 SkISize scaledSubsetSize = codec->getSampledSubsetDimensions(fSampleSize,
754 subset);
755 SkImageInfo subsetDecodeInfo = decodeInfo.makeWH(scaledSubsetSize.width(),
756 scaledSubsetSize.height());
757
msarettfa23a9e2015-10-21 13:26:59 -0700758 if (x + 1 == divisor && y + 1 == divisor) {
759 finalScaledWidth = scaledWidthOffset + scaledSubsetSize.width();
760 finalScaledHeight = scaledHeightOffset + scaledSubsetSize.height();
761 }
762
msarett3d9d7a72015-10-21 10:27:10 -0700763 switch (codec->getAndroidPixels(subsetDecodeInfo, pixels, bitmap.rowBytes(),
764 &options)) {
765 case SkCodec::kSuccess:
766 case SkCodec::kIncompleteInput:
767 break;
msarett3d9d7a72015-10-21 10:27:10 -0700768 default:
769 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
770 }
771 }
772 }
msarettfa23a9e2015-10-21 13:26:59 -0700773
774 SkRect rect = SkRect::MakeXYWH(0, 0, (SkScalar) finalScaledWidth,
775 (SkScalar) finalScaledHeight);
msarett9e9444c2016-02-03 12:39:10 -0800776 premultiply_if_necessary(bitmap);
msarettfa23a9e2015-10-21 13:26:59 -0700777 canvas->drawBitmapRect(bitmap, rect, rect, nullptr);
msarett3d9d7a72015-10-21 10:27:10 -0700778 return "";
779 }
780 default:
781 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800782 return "Error: Should not be reached.";
msarett3d9d7a72015-10-21 10:27:10 -0700783 }
784}
785
786SkISize AndroidCodecSrc::size() const {
787 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
788 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
789 if (nullptr == codec) {
790 return SkISize::Make(0, 0);
791 }
792 return codec->getSampledDimensions(fSampleSize);
793}
794
795Name AndroidCodecSrc::name() const {
796 // We will replicate the names used by CodecSrc so that images can
797 // be compared in Gold.
798 if (1 == fSampleSize) {
799 return SkOSPath::Basename(fPath.c_str());
800 }
msarett4b0778e2015-11-13 09:59:11 -0800801 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700802}
803
804/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
805
mtkleinf4ba3212015-01-28 15:32:24 -0800806static const SkRect kSKPViewport = {0,0, 1000,1000};
807
mtklein8d17a132015-01-30 11:42:31 -0800808SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800809
810Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800811 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800812 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800813 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
814 }
msarett8715d472016-02-17 10:02:29 -0800815 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream));
mtklein75d98fd2015-01-18 07:05:01 -0800816 if (!pic) {
817 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
818 }
halcanary96fcdcc2015-08-27 07:41:13 -0700819 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700820
mtkleinf4ba3212015-01-28 15:32:24 -0800821 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800822 canvas->drawPicture(pic);
823 return "";
824}
825
826SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700827 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
828 if (!stream) {
829 return SkISize::Make(0,0);
830 }
831 SkPictInfo info;
832 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
833 return SkISize::Make(0,0);
834 }
835 SkRect viewport = kSKPViewport;
836 if (!viewport.intersect(info.fCullRect)) {
837 return SkISize::Make(0,0);
838 }
839 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800840}
841
842Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
843
844/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
845
mtkleinad66f9b2015-02-13 15:11:10 -0800846Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
847 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
848 return src.draw(canvas);
849}
850
851/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
852
mtkleinb9eb4ac2015-02-02 18:26:03 -0800853DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
854
mtklein82d28432015-01-15 12:46:02 -0800855GPUSink::GPUSink(GrContextFactory::GLContextType ct,
kkinnunen5219fd92015-12-10 06:28:13 -0800856 GrContextFactory::GLContextOptions options,
mtklein82d28432015-01-15 12:46:02 -0800857 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700858 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800859 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800860 : fContextType(ct)
kkinnunen5219fd92015-12-10 06:28:13 -0800861 , fContextOptions(options)
mtklein748ca3b2015-01-15 10:56:12 -0800862 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700863 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800864 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800865
joshualitt5f5a8d72015-02-25 14:09:45 -0800866void PreAbandonGpuContextErrorHandler(SkError, void*) {}
867
bsalomon648c6962015-10-23 09:06:59 -0700868DEFINE_bool(imm, false, "Run gpu configs in immediate mode.");
bsalomon69cfe952015-11-30 13:27:47 -0800869DEFINE_bool(batchClip, false, "Clip each GrBatch to its device bounds for testing.");
bsalomon6dea83f2015-12-03 12:58:06 -0800870DEFINE_bool(batchBounds, false, "Draw a wireframe bounds of each GrBatch.");
bsalomon489147c2015-12-14 12:13:09 -0800871DEFINE_int32(batchLookback, -1, "Maximum GrBatch lookback for combining, negative means default.");
bsalomon648c6962015-10-23 09:06:59 -0700872
mtkleinb9eb4ac2015-02-02 18:26:03 -0800873Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
kkinnunen5219fd92015-12-10 06:28:13 -0800874 GrContextOptions grOptions;
bsalomon489147c2015-12-14 12:13:09 -0800875 grOptions.fImmediateMode = FLAGS_imm;
876 grOptions.fClipBatchToBounds = FLAGS_batchClip;
877 grOptions.fDrawBatchBounds = FLAGS_batchBounds;
878 grOptions.fMaxBatchLookback = FLAGS_batchLookback;
kkinnunen64492c42015-12-08 01:24:40 -0800879
kkinnunen5219fd92015-12-10 06:28:13 -0800880 src.modifyGrContextOptions(&grOptions);
881
882 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -0800883 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800884 const SkImageInfo info =
885 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
msarett13a036b2016-02-08 09:10:47 -0800886#if SK_SUPPORT_GPU
887 const int maxDimension = factory.getContextInfo(fContextType, fContextOptions).
888 fGrContext->caps()->maxTextureSize();
889 if (maxDimension < SkTMax(size.width(), size.height())) {
890 return Error::Nonfatal("Src too large to create a texture.\n");
891 }
892#endif
893
mtklein748ca3b2015-01-15 10:56:12 -0800894 SkAutoTUnref<SkSurface> surface(
kkinnunen3e980c32015-12-23 01:33:00 -0800895 NewGpuSurface(&factory, fContextType, fContextOptions, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800896 if (!surface) {
897 return "Could not create a surface.";
898 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800899 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700900 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800901 factory.abandonContexts();
902 }
mtklein748ca3b2015-01-15 10:56:12 -0800903 SkCanvas* canvas = surface->getCanvas();
904 Error err = src.draw(canvas);
905 if (!err.isEmpty()) {
906 return err;
907 }
908 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800909 if (FLAGS_gpuStats) {
910 canvas->getGrContext()->dumpCacheStats(log);
911 canvas->getGrContext()->dumpGpuStats(log);
912 }
mtklein748ca3b2015-01-15 10:56:12 -0800913 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800914 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800915 if (FLAGS_abandonGpuContext) {
916 factory.abandonContexts();
917 }
mtklein748ca3b2015-01-15 10:56:12 -0800918 return "";
919}
920
921/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
922
halcanary47ef4d52015-03-03 09:13:09 -0800923static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
924 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
925 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800926 int width = src.size().width(),
927 height = src.size().height();
928
halcanary7e798182015-04-14 14:06:18 -0700929 if (FLAGS_multiPage) {
930 const int kLetterWidth = 612, // 8.5 * 72
931 kLetterHeight = 792; // 11 * 72
932 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
933 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800934
halcanary7e798182015-04-14 14:06:18 -0700935 int xPages = ((width - 1) / kLetterWidth) + 1;
936 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800937
halcanary7e798182015-04-14 14:06:18 -0700938 for (int y = 0; y < yPages; ++y) {
939 for (int x = 0; x < xPages; ++x) {
940 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
941 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
942 SkCanvas* canvas =
943 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
944 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700945 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700946 }
947 canvas->clipRect(letter);
948 canvas->translate(-letter.width() * x, -letter.height() * y);
949 Error err = src.draw(canvas);
950 if (!err.isEmpty()) {
951 return err;
952 }
953 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700954 }
halcanaryfd4a9932015-01-28 11:45:58 -0800955 }
halcanary7e798182015-04-14 14:06:18 -0700956 } else {
957 SkCanvas* canvas =
958 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
959 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700960 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700961 }
962 Error err = src.draw(canvas);
963 if (!err.isEmpty()) {
964 return err;
965 }
966 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800967 }
halcanary7e798182015-04-14 14:06:18 -0700968 if (!doc->close()) {
969 return "SkDocument::close() returned false";
970 }
halcanaryfd4a9932015-01-28 11:45:58 -0800971 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800972 return "";
973}
974
halcanaryc11c62f2015-09-28 11:51:54 -0700975PDFSink::PDFSink(const char* rasterizer) : fRasterizer(rasterizer) {}
halcanary47ef4d52015-03-03 09:13:09 -0800976
977Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
978 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
979 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700980 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800981 }
halcanaryf12a1672015-09-23 12:45:49 -0700982 SkTArray<SkDocument::Attribute> info;
983 info.emplace_back(SkString("Title"), src.name());
984 info.emplace_back(SkString("Subject"),
985 SkString("rendering correctness test"));
986 info.emplace_back(SkString("Creator"), SkString("Skia/DM"));
halcanaryc11c62f2015-09-28 11:51:54 -0700987
988 info.emplace_back(SkString("Keywords"),
989 SkStringPrintf("Rasterizer:%s;", fRasterizer));
halcanary70015762016-02-11 07:59:59 -0800990 doc->setMetadata(&info[0], info.count(), nullptr, nullptr);
halcanary47ef4d52015-03-03 09:13:09 -0800991 return draw_skdocument(src, doc.get(), dst);
992}
993
994/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
995
996XPSSink::XPSSink() {}
997
998Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
999 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
1000 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -07001001 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001002 }
1003 return draw_skdocument(src, doc.get(), dst);
1004}
mtklein748ca3b2015-01-15 10:56:12 -08001005/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1006
mtklein9c3f17d2015-01-28 11:35:18 -08001007SKPSink::SKPSink() {}
1008
mtkleinb9eb4ac2015-02-02 18:26:03 -08001009Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001010 SkSize size;
1011 size = src.size();
1012 SkPictureRecorder recorder;
1013 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1014 if (!err.isEmpty()) {
1015 return err;
1016 }
1017 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1018 pic->serialize(dst);
1019 return "";
1020}
1021
1022/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1023
mtklein8a4527e2015-01-31 20:00:58 -08001024SVGSink::SVGSink() {}
1025
mtkleinb9eb4ac2015-02-02 18:26:03 -08001026Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -07001027 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -08001028 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
1029 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
1030 xmlWriter));
1031 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -08001032}
1033
1034/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1035
mtklein748ca3b2015-01-15 10:56:12 -08001036RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
1037
mtkleinb9eb4ac2015-02-02 18:26:03 -08001038Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001039 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001040 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1041 SkAlphaType alphaType = kPremul_SkAlphaType;
1042 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1043
mtkleinc8be09a2016-01-04 18:56:57 -08001044 SkMallocPixelRef::ZeroedPRFactory factory;
1045 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType),
1046 &factory,
1047 nullptr/*colortable*/);
mtklein748ca3b2015-01-15 10:56:12 -08001048 SkCanvas canvas(*dst);
1049 return src.draw(&canvas);
1050}
1051
1052/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1053
mtkleina16e69e2015-05-05 11:38:45 -07001054// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001055// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001056// Several examples below.
1057
mtkleincbf89782016-02-19 14:27:14 -08001058template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001059static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001060 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001061 class ProxySrc : public Src {
1062 public:
mtkleincbf89782016-02-19 14:27:14 -08001063 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001064 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
msarett62d3b102015-12-10 15:14:27 -08001065 Name name() const override { sk_throw(); return ""; } // Won't be called.
mtkleina16e69e2015-05-05 11:38:45 -07001066 SkISize size() const override { return fSize; }
1067 private:
mtkleincbf89782016-02-19 14:27:14 -08001068 SkISize fSize;
1069 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001070 };
msarett62d3b102015-12-10 15:14:27 -08001071 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001072}
1073
1074/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1075
mtklein4a34ecb2016-01-08 10:19:35 -08001076DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1077
1078// Is *bitmap identical to what you get drawing src into sink?
1079static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1080 // We can only check raster outputs.
1081 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1082 if (FLAGS_check && bitmap) {
1083 SkBitmap reference;
1084 SkString log;
1085 Error err = sink->draw(src, &reference, nullptr, &log);
1086 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1087 SkASSERT(err.isEmpty());
1088 if (!err.isEmpty()) {
1089 return err;
1090 }
1091 // The dimensions are a property of the Src only, and so should be identical.
1092 SkASSERT(reference.getSize() == bitmap->getSize());
1093 if (reference.getSize() != bitmap->getSize()) {
1094 return "Dimensions don't match reference";
1095 }
1096 // All SkBitmaps in DM are pre-locked and tight, so this comparison is easy.
1097 if (0 != memcmp(reference.getPixels(), bitmap->getPixels(), reference.getSize())) {
1098 return "Pixels don't match reference";
1099 }
1100 }
1101 return "";
1102}
1103
1104/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1105
mtkleind603b222015-02-17 11:13:33 -08001106static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1107 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1108 matrix->mapRect(&bounds);
1109 matrix->postTranslate(-bounds.x(), -bounds.y());
1110 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1111}
1112
msarett62d3b102015-12-10 15:14:27 -08001113ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001114
mtkleinb9eb4ac2015-02-02 18:26:03 -08001115Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001116 SkMatrix matrix = fMatrix;
1117 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
msarett62d3b102015-12-10 15:14:27 -08001118 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001119 canvas->concat(matrix);
1120 return src.draw(canvas);
1121 });
mtklein748ca3b2015-01-15 10:56:12 -08001122}
1123
mtkleind603b222015-02-17 11:13:33 -08001124// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1125// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001126ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001127
1128Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1129 Error err = fSink->draw(src, bitmap, stream, log);
1130 if (!err.isEmpty()) {
1131 return err;
1132 }
1133
1134 SkMatrix inverse;
1135 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1136 return "Cannot upright --matrix.";
1137 }
1138 SkMatrix upright = SkMatrix::I();
1139 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1140 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1141 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1142 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1143
1144 SkBitmap uprighted;
1145 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1146 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1147
1148 SkCanvas canvas(uprighted);
1149 canvas.concat(upright);
1150 SkPaint paint;
1151 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1152 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1153
1154 *bitmap = uprighted;
1155 bitmap->lockPixels();
1156 return "";
1157}
1158
mtklein748ca3b2015-01-15 10:56:12 -08001159/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1160
mtklein2e2ea382015-10-16 10:29:41 -07001161Error ViaRemote::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
msarett62d3b102015-12-10 15:14:27 -08001162 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* target) {
mtklein479fe772015-10-21 12:34:01 -07001163 SkAutoTDelete<SkRemote::Encoder> decoder(SkRemote::NewDecoder(target));
1164 SkAutoTDelete<SkRemote::Encoder> cache(fCache ? SkRemote::NewCachingEncoder(decoder)
1165 : nullptr);
1166 SkAutoTDelete<SkCanvas> canvas(SkRemote::NewCanvas(cache ? cache : decoder));
1167 return src.draw(canvas);
mtklein2e2ea382015-10-16 10:29:41 -07001168 });
1169}
1170
mtklein748ca3b2015-01-15 10:56:12 -08001171/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -07001172
mtkleina16e69e2015-05-05 11:38:45 -07001173Error ViaSerialization::draw(
1174 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001175 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001176 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001177 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001178 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1179 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001180 if (!err.isEmpty()) {
1181 return err;
1182 }
1183 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1184
1185 // Serialize it and then deserialize it.
1186 SkDynamicMemoryWStream wStream;
1187 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001188 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
msarett8715d472016-02-17 10:02:29 -08001189 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream));
mtklein748ca3b2015-01-15 10:56:12 -08001190
msarett62d3b102015-12-10 15:14:27 -08001191 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001192 canvas->drawPicture(deserialized);
mtklein4a34ecb2016-01-08 10:19:35 -08001193 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001194 });
mtklein748ca3b2015-01-15 10:56:12 -08001195}
1196
1197/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1198
msarett62d3b102015-12-10 15:14:27 -08001199ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1200 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001201 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001202 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001203 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001204
mtkleinb9eb4ac2015-02-02 18:26:03 -08001205Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001206 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001207 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001208 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1209 SkIntToScalar(size.height()),
1210 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001211 if (!err.isEmpty()) {
1212 return err;
1213 }
mtkleinb7e8d692015-04-07 08:30:32 -07001214 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001215
msarett62d3b102015-12-10 15:14:27 -08001216 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001217 const int xTiles = (size.width() + fW - 1) / fW,
1218 yTiles = (size.height() + fH - 1) / fH;
1219 SkMultiPictureDraw mpd(xTiles*yTiles);
1220 SkTDArray<SkSurface*> surfaces;
1221 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001222
mtkleina16e69e2015-05-05 11:38:45 -07001223 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1224 for (int j = 0; j < yTiles; j++) {
1225 for (int i = 0; i < xTiles; i++) {
1226 // This lets our ultimate Sink determine the best kind of surface.
1227 // E.g., if it's a GpuSink, the surfaces and images are textures.
1228 SkSurface* s = canvas->newSurface(info);
1229 if (!s) {
1230 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001231 }
mtkleina16e69e2015-05-05 11:38:45 -07001232 surfaces.push(s);
1233 SkCanvas* c = s->getCanvas();
1234 c->translate(SkIntToScalar(-i * fW),
1235 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1236 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001237 }
mtklein748ca3b2015-01-15 10:56:12 -08001238 }
mtkleina16e69e2015-05-05 11:38:45 -07001239 mpd.draw();
1240 for (int j = 0; j < yTiles; j++) {
1241 for (int i = 0; i < xTiles; i++) {
1242 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1243 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1244 }
1245 }
1246 surfaces.unrefAll();
1247 return "";
1248 });
mtklein748ca3b2015-01-15 10:56:12 -08001249}
1250
mtkleinb7e8d692015-04-07 08:30:32 -07001251/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1252
mtklein4a34ecb2016-01-08 10:19:35 -08001253Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1254 auto size = src.size();
1255 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1256 SkPictureRecorder recorder;
1257 SkAutoTUnref<SkPicture> pic;
1258 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1259 SkIntToScalar(size.height())));
1260 if (!err.isEmpty()) {
1261 return err;
1262 }
1263 pic.reset(recorder.endRecordingAsPicture());
1264 canvas->drawPicture(pic);
1265 return check_against_reference(bitmap, src, fSink);
1266 });
1267}
1268
1269/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1270
mtkleinb7e8d692015-04-07 08:30:32 -07001271// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1272// This tests that any shortcuts we may take while recording that second picture are legal.
1273Error ViaSecondPicture::draw(
1274 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001275 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001276 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleina16e69e2015-05-05 11:38:45 -07001277 SkPictureRecorder recorder;
1278 SkAutoTUnref<SkPicture> pic;
1279 for (int i = 0; i < 2; i++) {
1280 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1281 SkIntToScalar(size.height())));
1282 if (!err.isEmpty()) {
1283 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001284 }
mtkleina16e69e2015-05-05 11:38:45 -07001285 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001286 }
mtkleina16e69e2015-05-05 11:38:45 -07001287 canvas->drawPicture(pic);
mtklein4a34ecb2016-01-08 10:19:35 -08001288 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001289 });
mtkleinb7e8d692015-04-07 08:30:32 -07001290}
1291
mtkleind31c13d2015-05-05 12:59:56 -07001292/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1293
mtklein6fbf4b32015-05-06 11:35:40 -07001294// Draw the Src twice. This can help exercise caching.
1295Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
msarett62d3b102015-12-10 15:14:27 -08001296 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
mtklein6fbf4b32015-05-06 11:35:40 -07001297 for (int i = 0; i < 2; i++) {
1298 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1299 canvas->clear(SK_ColorTRANSPARENT);
1300 Error err = src.draw(canvas);
1301 if (err.isEmpty()) {
1302 return err;
1303 }
1304 }
mtklein4a34ecb2016-01-08 10:19:35 -08001305 return check_against_reference(bitmap, src, fSink);
mtklein6fbf4b32015-05-06 11:35:40 -07001306 });
1307}
1308
1309/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1310
halcanary7a76f9c2016-02-03 11:53:18 -08001311#ifdef SK_MOJO
1312 Error ViaMojo::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1313 SkPictureRecorder recorder;
1314 SkRect size = SkRect::Make(SkIRect::MakeSize(src.size()));
1315 Error err = src.draw(recorder.beginRecording(size));
1316 if (!err.isEmpty()) {
1317 return err;
1318 }
1319 SkAutoTUnref<SkPicture> skPicture(recorder.endRecording());
1320
1321 SkASSERT(skPicture);
1322 SkDynamicMemoryWStream buffer;
1323 skPicture->serialize(&buffer);
1324 skPicture.reset();
1325 SkMojo::FlattenedPicturePtr mojoPicture = SkMojo::FlattenedPicture::New();
1326 mojoPicture->data.resize(buffer.bytesWritten());
1327 buffer.copyTo(mojoPicture->data.data());
1328 buffer.reset();
1329 SkASSERT(mojoPicture.get() && mojoPicture->data);
1330
1331 size_t flatSize = mojoPicture->GetSerializedSize();
1332 SkAutoMalloc storage(flatSize);
1333 if (!mojoPicture->Serialize(storage.get(), flatSize)) {
1334 return "SkMojo::FlattenedPicture::Serialize failed";
1335 }
1336 mojoPicture = SkMojo::FlattenedPicture::New();
1337 mojoPicture->Deserialize(storage.get());
1338 storage.free();
1339 if (!mojoPicture) {
1340 return "SkMojo::FlattenedPicture::Deserialize failed";
1341 }
1342 SkMemoryStream tmpStream(mojoPicture->data.data(),
1343 mojoPicture->data.size());
1344 skPicture.reset(SkPicture::CreateFromStream(&tmpStream));
1345 mojoPicture.reset();
1346 auto fn = [&](SkCanvas* canvas) -> Error {
1347 canvas->drawPicture(skPicture.get());
1348 return check_against_reference(bitmap, src, fSink);
1349 };
1350 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), fn);
1351 }
1352#else // not SK_MOJO
1353 Error ViaMojo::draw(const Src&, SkBitmap*, SkWStream*, SkString*) const {
1354 return "Mojo is missing!";
1355 }
1356#endif
1357
1358/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1359
mtkleind31c13d2015-05-05 12:59:56 -07001360// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1361// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1362// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1363struct DrawsAsSingletonPictures {
1364 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001365 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001366
mtkleind31c13d2015-05-05 12:59:56 -07001367 template <typename T>
1368 void draw(const T& op, SkCanvas* canvas) {
1369 // We must pass SkMatrix::I() as our initial matrix.
1370 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1371 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001372 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1373 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001374 }
1375
mtklein449d9b72015-09-28 10:33:02 -07001376 // Draws get their own picture.
mtkleind31c13d2015-05-05 12:59:56 -07001377 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001378 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
mtkleind31c13d2015-05-05 12:59:56 -07001379 SkPictureRecorder rec;
1380 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1381 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1382 fCanvas->drawPicture(pic);
1383 }
1384
mtklein449d9b72015-09-28 10:33:02 -07001385 // We'll just issue non-draws directly.
mtkleind31c13d2015-05-05 12:59:56 -07001386 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001387 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1388 this->draw(op, fCanvas);
1389 }
mtkleind31c13d2015-05-05 12:59:56 -07001390};
1391
mtkleind31c13d2015-05-05 12:59:56 -07001392// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1393// Then play back that macro picture into our wrapped sink.
1394Error ViaSingletonPictures::draw(
1395 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1396 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001397 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleind31c13d2015-05-05 12:59:56 -07001398 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1399 SkRecord skr;
1400 SkRecorder recorder(&skr, size.width(), size.height());
1401 Error err = src.draw(&recorder);
1402 if (!err.isEmpty()) {
1403 return err;
1404 }
1405
1406 // Record our macro-picture, with each draw op as its own sub-picture.
1407 SkPictureRecorder macroRec;
1408 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1409 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001410
1411 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1412 const SkDrawableList empty;
1413
1414 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1415 macroCanvas,
1416 drawables ? *drawables : empty,
1417 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001418 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001419 skr.visit<void>(i, drawsAsSingletonPictures);
1420 }
1421 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1422
1423 canvas->drawPicture(macroPic);
mtklein4a34ecb2016-01-08 10:19:35 -08001424 return check_against_reference(bitmap, src, fSink);
mtkleind31c13d2015-05-05 12:59:56 -07001425 });
1426}
1427
mtklein748ca3b2015-01-15 10:56:12 -08001428} // namespace DM