blob: 7ccaf223fc3a32b8e2baa867dcd575454332b6ec [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)) {
msarett9e707a02015-09-01 14:57:57 -0700442 return Error::Nonfatal("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,
482 colorCountPtr)
483 || SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
msarett9e707a02015-09-01 14:57:57 -0700484 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
485 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
486 // to run this test for image types that do not have this scanline ordering.
msarett5406d6f2015-08-31 06:55:13 -0700487 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700488 }
msarette6dd0042015-10-09 11:07:34 -0700489
msarett0a242972015-06-11 14:27:27 -0700490 for (int i = 0; i < numStripes; i += 2) {
491 // Skip a stripe
492 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700493 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700494
495 // Read a stripe
496 const int startY = (i + 1) * stripeHeight;
497 const int linesToRead = SkTMin(stripeHeight, height - startY);
498 if (linesToRead > 0) {
msarette6dd0042015-10-09 11:07:34 -0700499 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700500 }
501 }
502
503 // Decode even stripes
scroggo46c57472015-09-30 08:57:13 -0700504 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
505 colorPtr, colorCountPtr);
scroggo1c005e42015-08-04 09:24:45 -0700506 if (SkCodec::kSuccess != startResult) {
507 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700508 }
509 for (int i = 0; i < numStripes; i += 2) {
510 // Read a stripe
511 const int startY = i * stripeHeight;
512 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarette6dd0042015-10-09 11:07:34 -0700513 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700514
515 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700516 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
517 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700518 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700519 }
520 }
msarett9e9444c2016-02-03 12:39:10 -0800521 premultiply_if_necessary(bitmap);
msarett0a242972015-06-11 14:27:27 -0700522 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700523 break;
msarett0a242972015-06-11 14:27:27 -0700524 }
scroggob636b452015-07-22 07:16:20 -0700525 case kSubset_Mode: {
526 // Arbitrarily choose a divisor.
527 int divisor = 2;
528 // Total width/height of the image.
529 const int W = codec->getInfo().width();
530 const int H = codec->getInfo().height();
531 if (divisor > W || divisor > H) {
532 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
533 "for %s with dimensions (%d x %d)", divisor,
534 fPath.c_str(), W, H));
535 }
536 // subset dimensions
537 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
538 const int w = SkAlign2(W / divisor);
539 const int h = SkAlign2(H / divisor);
540 SkIRect subset;
541 SkCodec::Options opts;
542 opts.fSubset = &subset;
543 SkBitmap subsetBm;
544 // We will reuse pixel memory from bitmap.
545 void* pixels = bitmap.getPixels();
546 // Keep track of left and top (for drawing subsetBm into canvas). We could use
547 // fScale * x and fScale * y, but we want integers such that the next subset will start
548 // where the last one ended. So we'll add decodeInfo.width() and height().
549 int left = 0;
550 for (int x = 0; x < W; x += w) {
551 int top = 0;
552 for (int y = 0; y < H; y+= h) {
553 // Do not make the subset go off the edge of the image.
554 const int preScaleW = SkTMin(w, W - x);
555 const int preScaleH = SkTMin(h, H - y);
556 subset.setXYWH(x, y, preScaleW, preScaleH);
557 // And scale
558 // FIXME: Should we have a version of getScaledDimensions that takes a subset
559 // into account?
msarette6dd0042015-10-09 11:07:34 -0700560 decodeInfo = decodeInfo.makeWH(
561 SkTMax(1, SkScalarRoundToInt(preScaleW * fScale)),
562 SkTMax(1, SkScalarRoundToInt(preScaleH * fScale)));
scroggob636b452015-07-22 07:16:20 -0700563 size_t rowBytes = decodeInfo.minRowBytes();
564 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700565 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700566 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
567 }
568 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
569 &opts, colorPtr, colorCountPtr);
570 switch (result) {
571 case SkCodec::kSuccess:
572 case SkCodec::kIncompleteInput:
573 break;
574 case SkCodec::kInvalidConversion:
575 if (0 == (x|y)) {
576 // First subset is okay to return unimplemented.
577 return Error::Nonfatal("Incompatible colortype conversion");
578 }
579 // If the first subset succeeded, a later one should not fail.
580 // fall through to failure
581 case SkCodec::kUnimplemented:
582 if (0 == (x|y)) {
583 // First subset is okay to return unimplemented.
584 return Error::Nonfatal("subset codec not supported");
585 }
586 // If the first subset succeeded, why would a later one fail?
587 // fall through to failure
588 default:
589 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
590 "from %s with dimensions (%d x %d)\t error %d",
591 x, y, decodeInfo.width(), decodeInfo.height(),
592 fPath.c_str(), W, H, result);
593 }
msarett9e9444c2016-02-03 12:39:10 -0800594 premultiply_if_necessary(subsetBm);
scroggob636b452015-07-22 07:16:20 -0700595 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
596 // translate by the scaled height.
597 top += decodeInfo.height();
598 }
599 // translate by the scaled width.
600 left += decodeInfo.width();
601 }
602 return "";
603 }
msarettb714fb02016-01-22 14:46:42 -0800604 default:
605 SkASSERT(false);
606 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700607 }
scroggo9c59ebc2015-03-25 13:48:49 -0700608 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700609}
610
611SkISize CodecSrc::size() const {
612 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700613 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700614 if (nullptr == codec) {
615 return SkISize::Make(0, 0);
616 }
617 return codec->getScaledDimensions(fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700618}
619
620Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700621 if (1.0f == fScale) {
622 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700623 }
msaretta5783ae2015-09-08 15:35:32 -0700624 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700625}
626
627/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
628
msarett3d9d7a72015-10-21 10:27:10 -0700629AndroidCodecSrc::AndroidCodecSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800630 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700631 : fPath(path)
632 , fMode(mode)
633 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800634 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700635 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800636 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700637{}
638
639bool AndroidCodecSrc::veto(SinkFlags flags) const {
640 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700641 return flags.type != SinkFlags::kRaster
642 || flags.approach != SinkFlags::kDirect;
643}
644
645Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
646 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
647 if (!encoded) {
648 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
649 }
650 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
651 if (nullptr == codec.get()) {
652 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
653 }
654
scroggoc5560be2016-02-03 09:42:42 -0800655 SkImageInfo decodeInfo = codec->getInfo().makeAlphaType(fDstAlphaType);
656 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType)) {
msarett3d9d7a72015-10-21 10:27:10 -0700657 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
658 }
659
660 // Scale the image if it is desired.
661 SkISize size = codec->getSampledDimensions(fSampleSize);
662
663 // Visually inspecting very small output images is not necessary. We will
664 // cover these cases in unit testing.
665 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
666 return Error::Nonfatal("Scaling very small images is uninteresting.");
667 }
668 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
669
670 // Construct a color table for the decode if necessary
671 SkAutoTUnref<SkColorTable> colorTable(nullptr);
672 SkPMColor* colorPtr = nullptr;
673 int* colorCountPtr = nullptr;
674 int maxColors = 256;
675 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
676 SkPMColor colors[256];
677 colorTable.reset(new SkColorTable(colors, maxColors));
678 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
679 colorCountPtr = &maxColors;
680 }
681
682 SkBitmap bitmap;
683 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
mtklein9b439152015-12-09 13:02:26 -0800684 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
msarett3d9d7a72015-10-21 10:27:10 -0700685 decodeInfo.width(), decodeInfo.height());
686 }
687
688 // Create options for the codec.
689 SkAndroidCodec::AndroidOptions options;
690 options.fColorPtr = colorPtr;
691 options.fColorCount = colorCountPtr;
692 options.fSampleSize = fSampleSize;
693
694 switch (fMode) {
695 case kFullImage_Mode: {
696 switch (codec->getAndroidPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(),
697 &options)) {
698 case SkCodec::kSuccess:
699 case SkCodec::kIncompleteInput:
700 break;
msarett3d9d7a72015-10-21 10:27:10 -0700701 default:
702 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
703 }
msarett9e9444c2016-02-03 12:39:10 -0800704 premultiply_if_necessary(bitmap);
msarett3d9d7a72015-10-21 10:27:10 -0700705 canvas->drawBitmap(bitmap, 0, 0);
706 return "";
707 }
708 case kDivisor_Mode: {
709 const int width = codec->getInfo().width();
710 const int height = codec->getInfo().height();
711 const int divisor = 2;
712 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800713 return Error::Nonfatal("Divisor is larger than image dimension.");
msarett3d9d7a72015-10-21 10:27:10 -0700714 }
715
msarettfa23a9e2015-10-21 13:26:59 -0700716 // Keep track of the final decoded dimensions.
717 int finalScaledWidth = 0;
718 int finalScaledHeight = 0;
msarett3d9d7a72015-10-21 10:27:10 -0700719 for (int x = 0; x < divisor; x++) {
720 for (int y = 0; y < divisor; y++) {
721 // Calculate the subset dimensions
722 int subsetWidth = width / divisor;
723 int subsetHeight = height / divisor;
724 const int left = x * subsetWidth;
725 const int top = y * subsetHeight;
726
727 // Increase the size of the last subset in each row or column, when the
728 // divisor does not divide evenly into the image dimensions
729 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
730 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
731 SkIRect subset = SkIRect::MakeXYWH(left, top, subsetWidth, subsetHeight);
732 if (!codec->getSupportedSubset(&subset)) {
mtklein9b439152015-12-09 13:02:26 -0800733 return "Could not get supported subset to decode.";
msarett3d9d7a72015-10-21 10:27:10 -0700734 }
735 options.fSubset = &subset;
msarettfa23a9e2015-10-21 13:26:59 -0700736 const int scaledWidthOffset = subset.left() / fSampleSize;
737 const int scaledHeightOffset = subset.top() / fSampleSize;
738 void* pixels = bitmap.getAddr(scaledWidthOffset, scaledHeightOffset);
msarett3d9d7a72015-10-21 10:27:10 -0700739 SkISize scaledSubsetSize = codec->getSampledSubsetDimensions(fSampleSize,
740 subset);
741 SkImageInfo subsetDecodeInfo = decodeInfo.makeWH(scaledSubsetSize.width(),
742 scaledSubsetSize.height());
743
msarettfa23a9e2015-10-21 13:26:59 -0700744 if (x + 1 == divisor && y + 1 == divisor) {
745 finalScaledWidth = scaledWidthOffset + scaledSubsetSize.width();
746 finalScaledHeight = scaledHeightOffset + scaledSubsetSize.height();
747 }
748
msarett3d9d7a72015-10-21 10:27:10 -0700749 switch (codec->getAndroidPixels(subsetDecodeInfo, pixels, bitmap.rowBytes(),
750 &options)) {
751 case SkCodec::kSuccess:
752 case SkCodec::kIncompleteInput:
753 break;
754 case SkCodec::kInvalidConversion:
mtklein9b439152015-12-09 13:02:26 -0800755 return Error::Nonfatal("Cannot convert to requested color type.");
msarett3d9d7a72015-10-21 10:27:10 -0700756 default:
757 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
758 }
759 }
760 }
msarettfa23a9e2015-10-21 13:26:59 -0700761
762 SkRect rect = SkRect::MakeXYWH(0, 0, (SkScalar) finalScaledWidth,
763 (SkScalar) finalScaledHeight);
msarett9e9444c2016-02-03 12:39:10 -0800764 premultiply_if_necessary(bitmap);
msarettfa23a9e2015-10-21 13:26:59 -0700765 canvas->drawBitmapRect(bitmap, rect, rect, nullptr);
msarett3d9d7a72015-10-21 10:27:10 -0700766 return "";
767 }
768 default:
769 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800770 return "Error: Should not be reached.";
msarett3d9d7a72015-10-21 10:27:10 -0700771 }
772}
773
774SkISize AndroidCodecSrc::size() const {
775 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
776 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
777 if (nullptr == codec) {
778 return SkISize::Make(0, 0);
779 }
780 return codec->getSampledDimensions(fSampleSize);
781}
782
783Name AndroidCodecSrc::name() const {
784 // We will replicate the names used by CodecSrc so that images can
785 // be compared in Gold.
786 if (1 == fSampleSize) {
787 return SkOSPath::Basename(fPath.c_str());
788 }
msarett4b0778e2015-11-13 09:59:11 -0800789 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700790}
791
792/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
793
mtkleinf4ba3212015-01-28 15:32:24 -0800794static const SkRect kSKPViewport = {0,0, 1000,1000};
795
mtklein8d17a132015-01-30 11:42:31 -0800796SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800797
798Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800799 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800800 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800801 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
802 }
msarett8715d472016-02-17 10:02:29 -0800803 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream));
mtklein75d98fd2015-01-18 07:05:01 -0800804 if (!pic) {
805 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
806 }
halcanary96fcdcc2015-08-27 07:41:13 -0700807 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700808
mtkleinf4ba3212015-01-28 15:32:24 -0800809 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800810 canvas->drawPicture(pic);
811 return "";
812}
813
814SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700815 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
816 if (!stream) {
817 return SkISize::Make(0,0);
818 }
819 SkPictInfo info;
820 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
821 return SkISize::Make(0,0);
822 }
823 SkRect viewport = kSKPViewport;
824 if (!viewport.intersect(info.fCullRect)) {
825 return SkISize::Make(0,0);
826 }
827 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800828}
829
830Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
831
832/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
833
mtkleinad66f9b2015-02-13 15:11:10 -0800834Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
835 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
836 return src.draw(canvas);
837}
838
839/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
840
mtkleinb9eb4ac2015-02-02 18:26:03 -0800841DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
842
mtklein82d28432015-01-15 12:46:02 -0800843GPUSink::GPUSink(GrContextFactory::GLContextType ct,
kkinnunen5219fd92015-12-10 06:28:13 -0800844 GrContextFactory::GLContextOptions options,
mtklein82d28432015-01-15 12:46:02 -0800845 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700846 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800847 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800848 : fContextType(ct)
kkinnunen5219fd92015-12-10 06:28:13 -0800849 , fContextOptions(options)
mtklein748ca3b2015-01-15 10:56:12 -0800850 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700851 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800852 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800853
joshualitt5f5a8d72015-02-25 14:09:45 -0800854void PreAbandonGpuContextErrorHandler(SkError, void*) {}
855
bsalomon648c6962015-10-23 09:06:59 -0700856DEFINE_bool(imm, false, "Run gpu configs in immediate mode.");
bsalomon69cfe952015-11-30 13:27:47 -0800857DEFINE_bool(batchClip, false, "Clip each GrBatch to its device bounds for testing.");
bsalomon6dea83f2015-12-03 12:58:06 -0800858DEFINE_bool(batchBounds, false, "Draw a wireframe bounds of each GrBatch.");
bsalomon489147c2015-12-14 12:13:09 -0800859DEFINE_int32(batchLookback, -1, "Maximum GrBatch lookback for combining, negative means default.");
bsalomon648c6962015-10-23 09:06:59 -0700860
mtkleinb9eb4ac2015-02-02 18:26:03 -0800861Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
kkinnunen5219fd92015-12-10 06:28:13 -0800862 GrContextOptions grOptions;
bsalomon489147c2015-12-14 12:13:09 -0800863 grOptions.fImmediateMode = FLAGS_imm;
864 grOptions.fClipBatchToBounds = FLAGS_batchClip;
865 grOptions.fDrawBatchBounds = FLAGS_batchBounds;
866 grOptions.fMaxBatchLookback = FLAGS_batchLookback;
kkinnunen64492c42015-12-08 01:24:40 -0800867
kkinnunen5219fd92015-12-10 06:28:13 -0800868 src.modifyGrContextOptions(&grOptions);
869
870 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -0800871 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800872 const SkImageInfo info =
873 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
msarett13a036b2016-02-08 09:10:47 -0800874#if SK_SUPPORT_GPU
875 const int maxDimension = factory.getContextInfo(fContextType, fContextOptions).
876 fGrContext->caps()->maxTextureSize();
877 if (maxDimension < SkTMax(size.width(), size.height())) {
878 return Error::Nonfatal("Src too large to create a texture.\n");
879 }
880#endif
881
mtklein748ca3b2015-01-15 10:56:12 -0800882 SkAutoTUnref<SkSurface> surface(
kkinnunen3e980c32015-12-23 01:33:00 -0800883 NewGpuSurface(&factory, fContextType, fContextOptions, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800884 if (!surface) {
885 return "Could not create a surface.";
886 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800887 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700888 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800889 factory.abandonContexts();
890 }
mtklein748ca3b2015-01-15 10:56:12 -0800891 SkCanvas* canvas = surface->getCanvas();
892 Error err = src.draw(canvas);
893 if (!err.isEmpty()) {
894 return err;
895 }
896 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800897 if (FLAGS_gpuStats) {
898 canvas->getGrContext()->dumpCacheStats(log);
899 canvas->getGrContext()->dumpGpuStats(log);
900 }
mtklein748ca3b2015-01-15 10:56:12 -0800901 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800902 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800903 if (FLAGS_abandonGpuContext) {
904 factory.abandonContexts();
905 }
mtklein748ca3b2015-01-15 10:56:12 -0800906 return "";
907}
908
909/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
910
halcanary47ef4d52015-03-03 09:13:09 -0800911static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
912 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
913 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800914 int width = src.size().width(),
915 height = src.size().height();
916
halcanary7e798182015-04-14 14:06:18 -0700917 if (FLAGS_multiPage) {
918 const int kLetterWidth = 612, // 8.5 * 72
919 kLetterHeight = 792; // 11 * 72
920 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
921 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800922
halcanary7e798182015-04-14 14:06:18 -0700923 int xPages = ((width - 1) / kLetterWidth) + 1;
924 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800925
halcanary7e798182015-04-14 14:06:18 -0700926 for (int y = 0; y < yPages; ++y) {
927 for (int x = 0; x < xPages; ++x) {
928 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
929 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
930 SkCanvas* canvas =
931 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
932 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700933 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700934 }
935 canvas->clipRect(letter);
936 canvas->translate(-letter.width() * x, -letter.height() * y);
937 Error err = src.draw(canvas);
938 if (!err.isEmpty()) {
939 return err;
940 }
941 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700942 }
halcanaryfd4a9932015-01-28 11:45:58 -0800943 }
halcanary7e798182015-04-14 14:06:18 -0700944 } else {
945 SkCanvas* canvas =
946 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
947 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700948 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700949 }
950 Error err = src.draw(canvas);
951 if (!err.isEmpty()) {
952 return err;
953 }
954 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800955 }
halcanary7e798182015-04-14 14:06:18 -0700956 if (!doc->close()) {
957 return "SkDocument::close() returned false";
958 }
halcanaryfd4a9932015-01-28 11:45:58 -0800959 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800960 return "";
961}
962
halcanaryc11c62f2015-09-28 11:51:54 -0700963PDFSink::PDFSink(const char* rasterizer) : fRasterizer(rasterizer) {}
halcanary47ef4d52015-03-03 09:13:09 -0800964
965Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
966 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
967 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700968 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800969 }
halcanaryf12a1672015-09-23 12:45:49 -0700970 SkTArray<SkDocument::Attribute> info;
971 info.emplace_back(SkString("Title"), src.name());
972 info.emplace_back(SkString("Subject"),
973 SkString("rendering correctness test"));
974 info.emplace_back(SkString("Creator"), SkString("Skia/DM"));
halcanaryc11c62f2015-09-28 11:51:54 -0700975
976 info.emplace_back(SkString("Keywords"),
977 SkStringPrintf("Rasterizer:%s;", fRasterizer));
halcanary70015762016-02-11 07:59:59 -0800978 doc->setMetadata(&info[0], info.count(), nullptr, nullptr);
halcanary47ef4d52015-03-03 09:13:09 -0800979 return draw_skdocument(src, doc.get(), dst);
980}
981
982/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
983
984XPSSink::XPSSink() {}
985
986Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
987 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
988 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700989 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800990 }
991 return draw_skdocument(src, doc.get(), dst);
992}
mtklein748ca3b2015-01-15 10:56:12 -0800993/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
994
mtklein9c3f17d2015-01-28 11:35:18 -0800995SKPSink::SKPSink() {}
996
mtkleinb9eb4ac2015-02-02 18:26:03 -0800997Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800998 SkSize size;
999 size = src.size();
1000 SkPictureRecorder recorder;
1001 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1002 if (!err.isEmpty()) {
1003 return err;
1004 }
1005 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1006 pic->serialize(dst);
1007 return "";
1008}
1009
1010/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1011
mtklein8a4527e2015-01-31 20:00:58 -08001012SVGSink::SVGSink() {}
1013
mtkleinb9eb4ac2015-02-02 18:26:03 -08001014Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -07001015 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -08001016 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
1017 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
1018 xmlWriter));
1019 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -08001020}
1021
1022/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1023
mtklein748ca3b2015-01-15 10:56:12 -08001024RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
1025
mtkleinb9eb4ac2015-02-02 18:26:03 -08001026Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001027 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001028 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1029 SkAlphaType alphaType = kPremul_SkAlphaType;
1030 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1031
mtkleinc8be09a2016-01-04 18:56:57 -08001032 SkMallocPixelRef::ZeroedPRFactory factory;
1033 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType),
1034 &factory,
1035 nullptr/*colortable*/);
mtklein748ca3b2015-01-15 10:56:12 -08001036 SkCanvas canvas(*dst);
1037 return src.draw(&canvas);
1038}
1039
1040/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1041
mtkleina16e69e2015-05-05 11:38:45 -07001042// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001043// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001044// Several examples below.
1045
mtkleincbf89782016-02-19 14:27:14 -08001046template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001047static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001048 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001049 class ProxySrc : public Src {
1050 public:
mtkleincbf89782016-02-19 14:27:14 -08001051 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001052 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
msarett62d3b102015-12-10 15:14:27 -08001053 Name name() const override { sk_throw(); return ""; } // Won't be called.
mtkleina16e69e2015-05-05 11:38:45 -07001054 SkISize size() const override { return fSize; }
1055 private:
mtkleincbf89782016-02-19 14:27:14 -08001056 SkISize fSize;
1057 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001058 };
msarett62d3b102015-12-10 15:14:27 -08001059 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001060}
1061
1062/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1063
mtklein4a34ecb2016-01-08 10:19:35 -08001064DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1065
1066// Is *bitmap identical to what you get drawing src into sink?
1067static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1068 // We can only check raster outputs.
1069 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1070 if (FLAGS_check && bitmap) {
1071 SkBitmap reference;
1072 SkString log;
1073 Error err = sink->draw(src, &reference, nullptr, &log);
1074 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1075 SkASSERT(err.isEmpty());
1076 if (!err.isEmpty()) {
1077 return err;
1078 }
1079 // The dimensions are a property of the Src only, and so should be identical.
1080 SkASSERT(reference.getSize() == bitmap->getSize());
1081 if (reference.getSize() != bitmap->getSize()) {
1082 return "Dimensions don't match reference";
1083 }
1084 // All SkBitmaps in DM are pre-locked and tight, so this comparison is easy.
1085 if (0 != memcmp(reference.getPixels(), bitmap->getPixels(), reference.getSize())) {
1086 return "Pixels don't match reference";
1087 }
1088 }
1089 return "";
1090}
1091
1092/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1093
mtkleind603b222015-02-17 11:13:33 -08001094static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1095 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1096 matrix->mapRect(&bounds);
1097 matrix->postTranslate(-bounds.x(), -bounds.y());
1098 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1099}
1100
msarett62d3b102015-12-10 15:14:27 -08001101ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001102
mtkleinb9eb4ac2015-02-02 18:26:03 -08001103Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001104 SkMatrix matrix = fMatrix;
1105 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
msarett62d3b102015-12-10 15:14:27 -08001106 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001107 canvas->concat(matrix);
1108 return src.draw(canvas);
1109 });
mtklein748ca3b2015-01-15 10:56:12 -08001110}
1111
mtkleind603b222015-02-17 11:13:33 -08001112// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1113// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001114ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001115
1116Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1117 Error err = fSink->draw(src, bitmap, stream, log);
1118 if (!err.isEmpty()) {
1119 return err;
1120 }
1121
1122 SkMatrix inverse;
1123 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1124 return "Cannot upright --matrix.";
1125 }
1126 SkMatrix upright = SkMatrix::I();
1127 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1128 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1129 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1130 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1131
1132 SkBitmap uprighted;
1133 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1134 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1135
1136 SkCanvas canvas(uprighted);
1137 canvas.concat(upright);
1138 SkPaint paint;
1139 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1140 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1141
1142 *bitmap = uprighted;
1143 bitmap->lockPixels();
1144 return "";
1145}
1146
mtklein748ca3b2015-01-15 10:56:12 -08001147/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1148
mtklein2e2ea382015-10-16 10:29:41 -07001149Error ViaRemote::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
msarett62d3b102015-12-10 15:14:27 -08001150 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* target) {
mtklein479fe772015-10-21 12:34:01 -07001151 SkAutoTDelete<SkRemote::Encoder> decoder(SkRemote::NewDecoder(target));
1152 SkAutoTDelete<SkRemote::Encoder> cache(fCache ? SkRemote::NewCachingEncoder(decoder)
1153 : nullptr);
1154 SkAutoTDelete<SkCanvas> canvas(SkRemote::NewCanvas(cache ? cache : decoder));
1155 return src.draw(canvas);
mtklein2e2ea382015-10-16 10:29:41 -07001156 });
1157}
1158
mtklein748ca3b2015-01-15 10:56:12 -08001159/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -07001160
mtkleina16e69e2015-05-05 11:38:45 -07001161Error ViaSerialization::draw(
1162 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001163 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001164 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001165 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001166 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1167 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001168 if (!err.isEmpty()) {
1169 return err;
1170 }
1171 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1172
1173 // Serialize it and then deserialize it.
1174 SkDynamicMemoryWStream wStream;
1175 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001176 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
msarett8715d472016-02-17 10:02:29 -08001177 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream));
mtklein748ca3b2015-01-15 10:56:12 -08001178
msarett62d3b102015-12-10 15:14:27 -08001179 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001180 canvas->drawPicture(deserialized);
mtklein4a34ecb2016-01-08 10:19:35 -08001181 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001182 });
mtklein748ca3b2015-01-15 10:56:12 -08001183}
1184
1185/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1186
msarett62d3b102015-12-10 15:14:27 -08001187ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1188 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001189 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001190 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001191 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001192
mtkleinb9eb4ac2015-02-02 18:26:03 -08001193Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001194 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001195 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001196 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1197 SkIntToScalar(size.height()),
1198 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001199 if (!err.isEmpty()) {
1200 return err;
1201 }
mtkleinb7e8d692015-04-07 08:30:32 -07001202 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001203
msarett62d3b102015-12-10 15:14:27 -08001204 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001205 const int xTiles = (size.width() + fW - 1) / fW,
1206 yTiles = (size.height() + fH - 1) / fH;
1207 SkMultiPictureDraw mpd(xTiles*yTiles);
1208 SkTDArray<SkSurface*> surfaces;
1209 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001210
mtkleina16e69e2015-05-05 11:38:45 -07001211 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1212 for (int j = 0; j < yTiles; j++) {
1213 for (int i = 0; i < xTiles; i++) {
1214 // This lets our ultimate Sink determine the best kind of surface.
1215 // E.g., if it's a GpuSink, the surfaces and images are textures.
1216 SkSurface* s = canvas->newSurface(info);
1217 if (!s) {
1218 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001219 }
mtkleina16e69e2015-05-05 11:38:45 -07001220 surfaces.push(s);
1221 SkCanvas* c = s->getCanvas();
1222 c->translate(SkIntToScalar(-i * fW),
1223 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1224 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001225 }
mtklein748ca3b2015-01-15 10:56:12 -08001226 }
mtkleina16e69e2015-05-05 11:38:45 -07001227 mpd.draw();
1228 for (int j = 0; j < yTiles; j++) {
1229 for (int i = 0; i < xTiles; i++) {
1230 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1231 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1232 }
1233 }
1234 surfaces.unrefAll();
1235 return "";
1236 });
mtklein748ca3b2015-01-15 10:56:12 -08001237}
1238
mtkleinb7e8d692015-04-07 08:30:32 -07001239/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1240
mtklein4a34ecb2016-01-08 10:19:35 -08001241Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1242 auto size = src.size();
1243 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1244 SkPictureRecorder recorder;
1245 SkAutoTUnref<SkPicture> pic;
1246 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1247 SkIntToScalar(size.height())));
1248 if (!err.isEmpty()) {
1249 return err;
1250 }
1251 pic.reset(recorder.endRecordingAsPicture());
1252 canvas->drawPicture(pic);
1253 return check_against_reference(bitmap, src, fSink);
1254 });
1255}
1256
1257/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1258
mtkleinb7e8d692015-04-07 08:30:32 -07001259// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1260// This tests that any shortcuts we may take while recording that second picture are legal.
1261Error ViaSecondPicture::draw(
1262 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001263 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001264 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleina16e69e2015-05-05 11:38:45 -07001265 SkPictureRecorder recorder;
1266 SkAutoTUnref<SkPicture> pic;
1267 for (int i = 0; i < 2; i++) {
1268 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1269 SkIntToScalar(size.height())));
1270 if (!err.isEmpty()) {
1271 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001272 }
mtkleina16e69e2015-05-05 11:38:45 -07001273 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001274 }
mtkleina16e69e2015-05-05 11:38:45 -07001275 canvas->drawPicture(pic);
mtklein4a34ecb2016-01-08 10:19:35 -08001276 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001277 });
mtkleinb7e8d692015-04-07 08:30:32 -07001278}
1279
mtkleind31c13d2015-05-05 12:59:56 -07001280/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1281
mtklein6fbf4b32015-05-06 11:35:40 -07001282// Draw the Src twice. This can help exercise caching.
1283Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
msarett62d3b102015-12-10 15:14:27 -08001284 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
mtklein6fbf4b32015-05-06 11:35:40 -07001285 for (int i = 0; i < 2; i++) {
1286 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1287 canvas->clear(SK_ColorTRANSPARENT);
1288 Error err = src.draw(canvas);
1289 if (err.isEmpty()) {
1290 return err;
1291 }
1292 }
mtklein4a34ecb2016-01-08 10:19:35 -08001293 return check_against_reference(bitmap, src, fSink);
mtklein6fbf4b32015-05-06 11:35:40 -07001294 });
1295}
1296
1297/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1298
halcanary7a76f9c2016-02-03 11:53:18 -08001299#ifdef SK_MOJO
1300 Error ViaMojo::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1301 SkPictureRecorder recorder;
1302 SkRect size = SkRect::Make(SkIRect::MakeSize(src.size()));
1303 Error err = src.draw(recorder.beginRecording(size));
1304 if (!err.isEmpty()) {
1305 return err;
1306 }
1307 SkAutoTUnref<SkPicture> skPicture(recorder.endRecording());
1308
1309 SkASSERT(skPicture);
1310 SkDynamicMemoryWStream buffer;
1311 skPicture->serialize(&buffer);
1312 skPicture.reset();
1313 SkMojo::FlattenedPicturePtr mojoPicture = SkMojo::FlattenedPicture::New();
1314 mojoPicture->data.resize(buffer.bytesWritten());
1315 buffer.copyTo(mojoPicture->data.data());
1316 buffer.reset();
1317 SkASSERT(mojoPicture.get() && mojoPicture->data);
1318
1319 size_t flatSize = mojoPicture->GetSerializedSize();
1320 SkAutoMalloc storage(flatSize);
1321 if (!mojoPicture->Serialize(storage.get(), flatSize)) {
1322 return "SkMojo::FlattenedPicture::Serialize failed";
1323 }
1324 mojoPicture = SkMojo::FlattenedPicture::New();
1325 mojoPicture->Deserialize(storage.get());
1326 storage.free();
1327 if (!mojoPicture) {
1328 return "SkMojo::FlattenedPicture::Deserialize failed";
1329 }
1330 SkMemoryStream tmpStream(mojoPicture->data.data(),
1331 mojoPicture->data.size());
1332 skPicture.reset(SkPicture::CreateFromStream(&tmpStream));
1333 mojoPicture.reset();
1334 auto fn = [&](SkCanvas* canvas) -> Error {
1335 canvas->drawPicture(skPicture.get());
1336 return check_against_reference(bitmap, src, fSink);
1337 };
1338 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), fn);
1339 }
1340#else // not SK_MOJO
1341 Error ViaMojo::draw(const Src&, SkBitmap*, SkWStream*, SkString*) const {
1342 return "Mojo is missing!";
1343 }
1344#endif
1345
1346/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1347
mtkleind31c13d2015-05-05 12:59:56 -07001348// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1349// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1350// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1351struct DrawsAsSingletonPictures {
1352 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001353 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001354
mtkleind31c13d2015-05-05 12:59:56 -07001355 template <typename T>
1356 void draw(const T& op, SkCanvas* canvas) {
1357 // We must pass SkMatrix::I() as our initial matrix.
1358 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1359 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001360 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1361 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001362 }
1363
mtklein449d9b72015-09-28 10:33:02 -07001364 // Draws get their own picture.
mtkleind31c13d2015-05-05 12:59:56 -07001365 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001366 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
mtkleind31c13d2015-05-05 12:59:56 -07001367 SkPictureRecorder rec;
1368 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1369 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1370 fCanvas->drawPicture(pic);
1371 }
1372
mtklein449d9b72015-09-28 10:33:02 -07001373 // We'll just issue non-draws directly.
mtkleind31c13d2015-05-05 12:59:56 -07001374 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001375 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1376 this->draw(op, fCanvas);
1377 }
mtkleind31c13d2015-05-05 12:59:56 -07001378};
1379
mtkleind31c13d2015-05-05 12:59:56 -07001380// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1381// Then play back that macro picture into our wrapped sink.
1382Error ViaSingletonPictures::draw(
1383 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1384 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001385 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleind31c13d2015-05-05 12:59:56 -07001386 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1387 SkRecord skr;
1388 SkRecorder recorder(&skr, size.width(), size.height());
1389 Error err = src.draw(&recorder);
1390 if (!err.isEmpty()) {
1391 return err;
1392 }
1393
1394 // Record our macro-picture, with each draw op as its own sub-picture.
1395 SkPictureRecorder macroRec;
1396 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1397 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001398
1399 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1400 const SkDrawableList empty;
1401
1402 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1403 macroCanvas,
1404 drawables ? *drawables : empty,
1405 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001406 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001407 skr.visit<void>(i, drawsAsSingletonPictures);
1408 }
1409 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1410
1411 canvas->drawPicture(macroPic);
mtklein4a34ecb2016-01-08 10:19:35 -08001412 return check_against_reference(bitmap, src, fSink);
mtkleind31c13d2015-05-05 12:59:56 -07001413 });
1414}
1415
mtklein748ca3b2015-01-15 10:56:12 -08001416} // namespace DM