blob: 84af854deae65c8597cd30839d98034795df5978 [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"
msarett18976312016-03-09 14:20:58 -080017#include "SkImageGeneratorCG.h"
mtkleinc8be09a2016-01-04 18:56:57 -080018#include "SkMallocPixelRef.h"
mtklein748ca3b2015-01-15 10:56:12 -080019#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080020#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080021#include "SkOSFile.h"
msarett9e9444c2016-02-03 12:39:10 -080022#include "SkOpts.h"
mtkleinffa901a2015-03-16 10:38:07 -070023#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080024#include "SkPictureRecorder.h"
25#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070026#include "SkRecordDraw.h"
27#include "SkRecorder.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 {
msarett18976312016-03-09 14:20:58 -0800267 // Test to direct raster backends (8888 and 565).
msarettb714fb02016-01-22 14:46:42 -0800268 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700269}
scroggo9b77ddd2015-03-19 06:03:39 -0700270
msarett9e9444c2016-02-03 12:39:10 -0800271// FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
272// This allows us to still test unpremultiplied decodes.
273void premultiply_if_necessary(SkBitmap& bitmap) {
274 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
275 return;
276 }
277
278 switch (bitmap.colorType()) {
279 case kN32_SkColorType:
280 for (int y = 0; y < bitmap.height(); y++) {
281 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
282 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
283 }
284 break;
285 case kIndex_8_SkColorType: {
286 SkColorTable* colorTable = bitmap.getColorTable();
287 SkPMColor* colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
288 SkOpts::RGBA_to_rgbA(colorPtr, colorPtr, colorTable->count());
289 break;
290 }
291 default:
292 // No need to premultiply kGray or k565 outputs.
293 break;
294 }
msarette1daa482016-02-03 15:31:18 -0800295
296 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
297 // bitmap as kPremul.
298 bitmap.setAlphaType(kPremul_SkAlphaType);
msarett9e9444c2016-02-03 12:39:10 -0800299}
300
scroggoc5560be2016-02-03 09:42:42 -0800301bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
302 CodecSrc::DstColorType dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700303 switch (dstColorType) {
304 case CodecSrc::kIndex8_Always_DstColorType:
305 if (kRGB_565_SkColorType == canvasColorType) {
306 return false;
307 }
scroggoc5560be2016-02-03 09:42:42 -0800308 *decodeInfo = decodeInfo->makeColorType(kIndex_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700309 break;
310 case CodecSrc::kGrayscale_Always_DstColorType:
msarett55f7bdd2016-02-16 13:24:54 -0800311 if (kRGB_565_SkColorType == canvasColorType ||
312 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
msarett3d9d7a72015-10-21 10:27:10 -0700313 return false;
314 }
scroggoc5560be2016-02-03 09:42:42 -0800315 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700316 break;
317 default:
msarett55f7bdd2016-02-16 13:24:54 -0800318 if (kRGB_565_SkColorType == canvasColorType &&
319 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
320 return false;
321 }
scroggoc5560be2016-02-03 09:42:42 -0800322 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700323 break;
324 }
325
msarett3d9d7a72015-10-21 10:27:10 -0700326 return true;
327}
328
mtkleine0effd62015-07-29 06:37:28 -0700329Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800330 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800331 if (!encoded) {
332 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
333 }
msarettb714fb02016-01-22 14:46:42 -0800334
msarett3d9d7a72015-10-21 10:27:10 -0700335 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700336 if (nullptr == codec.get()) {
337 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700338 }
339
scroggoc5560be2016-02-03 09:42:42 -0800340 SkImageInfo decodeInfo = codec->getInfo().makeAlphaType(fDstAlphaType);
341 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType)) {
msarett3d9d7a72015-10-21 10:27:10 -0700342 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
msarett438b2ad2015-04-09 12:43:10 -0700343 }
344
msarett0a242972015-06-11 14:27:27 -0700345 // Try to scale the image if it is desired
346 SkISize size = codec->getScaledDimensions(fScale);
347 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
348 return Error::Nonfatal("Test without scaling is uninteresting.");
349 }
msarettb32758a2015-08-18 13:22:46 -0700350
351 // Visually inspecting very small output images is not necessary. We will
352 // cover these cases in unit testing.
353 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
354 return Error::Nonfatal("Scaling very small images is uninteresting.");
355 }
msarett0a242972015-06-11 14:27:27 -0700356 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
357
msarett438b2ad2015-04-09 12:43:10 -0700358 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700359 SkAutoTUnref<SkColorTable> colorTable(nullptr);
360 SkPMColor* colorPtr = nullptr;
361 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700362 int maxColors = 256;
363 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
364 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700365 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700366 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
367 colorCountPtr = &maxColors;
368 }
369
scroggo9b77ddd2015-03-19 06:03:39 -0700370 SkBitmap bitmap;
msarettbb25b532016-01-13 09:31:39 -0800371 SkPixelRefFactory* factory = nullptr;
372 SkMallocPixelRef::ZeroedPRFactory zeroFactory;
373 SkCodec::Options options;
374 if (kCodecZeroInit_Mode == fMode) {
375 factory = &zeroFactory;
376 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
377 }
378 if (!bitmap.tryAllocPixels(decodeInfo, factory, colorTable.get())) {
mtklein9b439152015-12-09 13:02:26 -0800379 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
scroggo9b77ddd2015-03-19 06:03:39 -0700380 decodeInfo.width(), decodeInfo.height());
381 }
382
scroggo9c59ebc2015-03-25 13:48:49 -0700383 switch (fMode) {
msarettbb25b532016-01-13 09:31:39 -0800384 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700385 case kCodec_Mode: {
msarettbb25b532016-01-13 09:31:39 -0800386 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), &options,
msarett438b2ad2015-04-09 12:43:10 -0700387 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700388 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700389 // We consider incomplete to be valid, since we should still decode what is
390 // available.
scroggoeb602a52015-07-09 08:16:03 -0700391 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700392 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700393 default:
394 // Everything else is considered a failure.
395 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
396 }
msarett9e9444c2016-02-03 12:39:10 -0800397 premultiply_if_necessary(bitmap);
emmaleer97002062015-05-27 12:36:10 -0700398 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700399 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700400 }
scroggo9c59ebc2015-03-25 13:48:49 -0700401 case kScanline_Mode: {
scroggo46c57472015-09-30 08:57:13 -0700402 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
403 colorCountPtr)) {
msarettb65e6042016-02-23 05:37:25 -0800404 return "Could not start scanline decoder";
scroggo9c59ebc2015-03-25 13:48:49 -0700405 }
scroggo1c005e42015-08-04 09:24:45 -0700406
msarette6dd0042015-10-09 11:07:34 -0700407 void* dst = bitmap.getAddr(0, 0);
408 size_t rowBytes = bitmap.rowBytes();
409 uint32_t height = decodeInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700410 switch (codec->getScanlineOrder()) {
411 case SkCodec::kTopDown_SkScanlineOrder:
412 case SkCodec::kBottomUp_SkScanlineOrder:
413 case SkCodec::kNone_SkScanlineOrder:
msarette6dd0042015-10-09 11:07:34 -0700414 // We do not need to check the return value. On an incomplete
415 // image, memory will be filled with a default value.
416 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700417 break;
scroggo46c57472015-09-30 08:57:13 -0700418 case SkCodec::kOutOfOrder_SkScanlineOrder: {
msarett10522ff2015-09-07 08:54:01 -0700419 for (int y = 0; y < decodeInfo.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700420 int dstY = codec->outputScanline(y);
msarett10522ff2015-09-07 08:54:01 -0700421 void* dstPtr = bitmap.getAddr(0, dstY);
msarette6dd0042015-10-09 11:07:34 -0700422 // We complete the loop, even if this call begins to fail
423 // due to an incomplete image. This ensures any uninitialized
424 // memory will be filled with the proper value.
425 codec->getScanlines(dstPtr, 1, bitmap.rowBytes());
msarett10522ff2015-09-07 08:54:01 -0700426 }
427 break;
428 }
429 }
430
msarett9e9444c2016-02-03 12:39:10 -0800431 premultiply_if_necessary(bitmap);
emmaleer97002062015-05-27 12:36:10 -0700432 canvas->drawBitmap(bitmap, 0, 0);
433 break;
434 }
msarett0a242972015-06-11 14:27:27 -0700435 case kStripe_Mode: {
436 const int height = decodeInfo.height();
437 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
438 // does not align with image blocks.
439 const int stripeHeight = 37;
440 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
441
442 // Decode odd stripes
scroggo46c57472015-09-30 08:57:13 -0700443 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
msarettb65e6042016-02-23 05:37:25 -0800444 colorCountPtr)) {
445 return "Could not start scanline decoder";
446 }
447
448 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
449 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
450 // to run this test for image types that do not have this scanline ordering.
451 if (SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
452 return Error::Nonfatal("kStripe test is only interesting for kTopDown codecs.");
msarett0a242972015-06-11 14:27:27 -0700453 }
msarette6dd0042015-10-09 11:07:34 -0700454
msarett0a242972015-06-11 14:27:27 -0700455 for (int i = 0; i < numStripes; i += 2) {
456 // Skip a stripe
457 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700458 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700459
460 // Read a stripe
461 const int startY = (i + 1) * stripeHeight;
462 const int linesToRead = SkTMin(stripeHeight, height - startY);
463 if (linesToRead > 0) {
msarette6dd0042015-10-09 11:07:34 -0700464 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700465 }
466 }
467
468 // Decode even stripes
scroggo46c57472015-09-30 08:57:13 -0700469 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
470 colorPtr, colorCountPtr);
scroggo1c005e42015-08-04 09:24:45 -0700471 if (SkCodec::kSuccess != startResult) {
472 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700473 }
474 for (int i = 0; i < numStripes; i += 2) {
475 // Read a stripe
476 const int startY = i * stripeHeight;
477 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarette6dd0042015-10-09 11:07:34 -0700478 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700479
480 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700481 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
482 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700483 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700484 }
485 }
msarett9e9444c2016-02-03 12:39:10 -0800486 premultiply_if_necessary(bitmap);
msarett0a242972015-06-11 14:27:27 -0700487 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700488 break;
msarett0a242972015-06-11 14:27:27 -0700489 }
msarett91c22b22016-02-22 12:27:46 -0800490 case kCroppedScanline_Mode: {
491 const int width = decodeInfo.width();
492 const int height = decodeInfo.height();
493 // This value is chosen because, as we move across the image, it will sometimes
494 // align with the jpeg block sizes and it will sometimes not. This allows us
495 // to test interestingly different code paths in the implementation.
496 const int tileSize = 36;
497
498 SkCodec::Options opts;
499 SkIRect subset;
500 for (int x = 0; x < width; x += tileSize) {
501 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
502 opts.fSubset = &subset;
503 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &opts,
504 colorPtr, colorCountPtr)) {
505 return "Could not start scanline decoder.";
506 }
507
508 codec->getScanlines(bitmap.getAddr(x, 0), height, bitmap.rowBytes());
509 }
510
511 premultiply_if_necessary(bitmap);
512 canvas->drawBitmap(bitmap, 0, 0);
513 break;
514 }
scroggob636b452015-07-22 07:16:20 -0700515 case kSubset_Mode: {
516 // Arbitrarily choose a divisor.
517 int divisor = 2;
518 // Total width/height of the image.
519 const int W = codec->getInfo().width();
520 const int H = codec->getInfo().height();
521 if (divisor > W || divisor > H) {
522 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
523 "for %s with dimensions (%d x %d)", divisor,
524 fPath.c_str(), W, H));
525 }
526 // subset dimensions
527 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
528 const int w = SkAlign2(W / divisor);
529 const int h = SkAlign2(H / divisor);
530 SkIRect subset;
531 SkCodec::Options opts;
532 opts.fSubset = &subset;
533 SkBitmap subsetBm;
534 // We will reuse pixel memory from bitmap.
535 void* pixels = bitmap.getPixels();
536 // Keep track of left and top (for drawing subsetBm into canvas). We could use
537 // fScale * x and fScale * y, but we want integers such that the next subset will start
538 // where the last one ended. So we'll add decodeInfo.width() and height().
539 int left = 0;
540 for (int x = 0; x < W; x += w) {
541 int top = 0;
542 for (int y = 0; y < H; y+= h) {
543 // Do not make the subset go off the edge of the image.
544 const int preScaleW = SkTMin(w, W - x);
545 const int preScaleH = SkTMin(h, H - y);
546 subset.setXYWH(x, y, preScaleW, preScaleH);
547 // And scale
548 // FIXME: Should we have a version of getScaledDimensions that takes a subset
549 // into account?
msarette6dd0042015-10-09 11:07:34 -0700550 decodeInfo = decodeInfo.makeWH(
551 SkTMax(1, SkScalarRoundToInt(preScaleW * fScale)),
552 SkTMax(1, SkScalarRoundToInt(preScaleH * fScale)));
scroggob636b452015-07-22 07:16:20 -0700553 size_t rowBytes = decodeInfo.minRowBytes();
554 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700555 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700556 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
557 }
558 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
559 &opts, colorPtr, colorCountPtr);
560 switch (result) {
561 case SkCodec::kSuccess:
562 case SkCodec::kIncompleteInput:
563 break;
scroggob636b452015-07-22 07:16:20 -0700564 default:
565 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
566 "from %s with dimensions (%d x %d)\t error %d",
567 x, y, decodeInfo.width(), decodeInfo.height(),
568 fPath.c_str(), W, H, result);
569 }
msarett9e9444c2016-02-03 12:39:10 -0800570 premultiply_if_necessary(subsetBm);
scroggob636b452015-07-22 07:16:20 -0700571 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
572 // translate by the scaled height.
573 top += decodeInfo.height();
574 }
575 // translate by the scaled width.
576 left += decodeInfo.width();
577 }
578 return "";
579 }
msarettb714fb02016-01-22 14:46:42 -0800580 default:
581 SkASSERT(false);
582 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700583 }
scroggo9c59ebc2015-03-25 13:48:49 -0700584 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700585}
586
587SkISize CodecSrc::size() const {
588 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700589 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700590 if (nullptr == codec) {
591 return SkISize::Make(0, 0);
592 }
593 return codec->getScaledDimensions(fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700594}
595
596Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700597 if (1.0f == fScale) {
598 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700599 }
msaretta5783ae2015-09-08 15:35:32 -0700600 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700601}
602
603/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
604
msarett3d9d7a72015-10-21 10:27:10 -0700605AndroidCodecSrc::AndroidCodecSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800606 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700607 : fPath(path)
608 , fMode(mode)
609 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800610 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700611 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800612 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700613{}
614
615bool AndroidCodecSrc::veto(SinkFlags flags) const {
616 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700617 return flags.type != SinkFlags::kRaster
618 || flags.approach != SinkFlags::kDirect;
619}
620
621Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
622 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
623 if (!encoded) {
624 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
625 }
626 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
627 if (nullptr == codec.get()) {
628 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
629 }
630
scroggoc5560be2016-02-03 09:42:42 -0800631 SkImageInfo decodeInfo = codec->getInfo().makeAlphaType(fDstAlphaType);
632 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType)) {
msarett3d9d7a72015-10-21 10:27:10 -0700633 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
634 }
635
636 // Scale the image if it is desired.
637 SkISize size = codec->getSampledDimensions(fSampleSize);
638
639 // Visually inspecting very small output images is not necessary. We will
640 // cover these cases in unit testing.
641 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
642 return Error::Nonfatal("Scaling very small images is uninteresting.");
643 }
644 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
645
646 // Construct a color table for the decode if necessary
647 SkAutoTUnref<SkColorTable> colorTable(nullptr);
648 SkPMColor* colorPtr = nullptr;
649 int* colorCountPtr = nullptr;
650 int maxColors = 256;
651 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
652 SkPMColor colors[256];
653 colorTable.reset(new SkColorTable(colors, maxColors));
654 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
655 colorCountPtr = &maxColors;
656 }
657
658 SkBitmap bitmap;
659 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
mtklein9b439152015-12-09 13:02:26 -0800660 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
msarett3d9d7a72015-10-21 10:27:10 -0700661 decodeInfo.width(), decodeInfo.height());
662 }
663
664 // Create options for the codec.
665 SkAndroidCodec::AndroidOptions options;
666 options.fColorPtr = colorPtr;
667 options.fColorCount = colorCountPtr;
668 options.fSampleSize = fSampleSize;
669
670 switch (fMode) {
671 case kFullImage_Mode: {
672 switch (codec->getAndroidPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(),
673 &options)) {
674 case SkCodec::kSuccess:
675 case SkCodec::kIncompleteInput:
676 break;
msarett3d9d7a72015-10-21 10:27:10 -0700677 default:
678 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
679 }
msarett9e9444c2016-02-03 12:39:10 -0800680 premultiply_if_necessary(bitmap);
msarett3d9d7a72015-10-21 10:27:10 -0700681 canvas->drawBitmap(bitmap, 0, 0);
682 return "";
683 }
684 case kDivisor_Mode: {
685 const int width = codec->getInfo().width();
686 const int height = codec->getInfo().height();
687 const int divisor = 2;
688 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800689 return Error::Nonfatal("Divisor is larger than image dimension.");
msarett3d9d7a72015-10-21 10:27:10 -0700690 }
691
msarettfa23a9e2015-10-21 13:26:59 -0700692 // Keep track of the final decoded dimensions.
693 int finalScaledWidth = 0;
694 int finalScaledHeight = 0;
msarett3d9d7a72015-10-21 10:27:10 -0700695 for (int x = 0; x < divisor; x++) {
696 for (int y = 0; y < divisor; y++) {
697 // Calculate the subset dimensions
698 int subsetWidth = width / divisor;
699 int subsetHeight = height / divisor;
700 const int left = x * subsetWidth;
701 const int top = y * subsetHeight;
702
703 // Increase the size of the last subset in each row or column, when the
704 // divisor does not divide evenly into the image dimensions
705 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
706 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
707 SkIRect subset = SkIRect::MakeXYWH(left, top, subsetWidth, subsetHeight);
708 if (!codec->getSupportedSubset(&subset)) {
mtklein9b439152015-12-09 13:02:26 -0800709 return "Could not get supported subset to decode.";
msarett3d9d7a72015-10-21 10:27:10 -0700710 }
711 options.fSubset = &subset;
msarettfa23a9e2015-10-21 13:26:59 -0700712 const int scaledWidthOffset = subset.left() / fSampleSize;
713 const int scaledHeightOffset = subset.top() / fSampleSize;
714 void* pixels = bitmap.getAddr(scaledWidthOffset, scaledHeightOffset);
msarett3d9d7a72015-10-21 10:27:10 -0700715 SkISize scaledSubsetSize = codec->getSampledSubsetDimensions(fSampleSize,
716 subset);
717 SkImageInfo subsetDecodeInfo = decodeInfo.makeWH(scaledSubsetSize.width(),
718 scaledSubsetSize.height());
719
msarettfa23a9e2015-10-21 13:26:59 -0700720 if (x + 1 == divisor && y + 1 == divisor) {
721 finalScaledWidth = scaledWidthOffset + scaledSubsetSize.width();
722 finalScaledHeight = scaledHeightOffset + scaledSubsetSize.height();
723 }
724
msarett3d9d7a72015-10-21 10:27:10 -0700725 switch (codec->getAndroidPixels(subsetDecodeInfo, pixels, bitmap.rowBytes(),
726 &options)) {
727 case SkCodec::kSuccess:
728 case SkCodec::kIncompleteInput:
729 break;
msarett3d9d7a72015-10-21 10:27:10 -0700730 default:
731 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
732 }
733 }
734 }
msarettfa23a9e2015-10-21 13:26:59 -0700735
736 SkRect rect = SkRect::MakeXYWH(0, 0, (SkScalar) finalScaledWidth,
737 (SkScalar) finalScaledHeight);
msarett9e9444c2016-02-03 12:39:10 -0800738 premultiply_if_necessary(bitmap);
msarettfa23a9e2015-10-21 13:26:59 -0700739 canvas->drawBitmapRect(bitmap, rect, rect, nullptr);
msarett3d9d7a72015-10-21 10:27:10 -0700740 return "";
741 }
742 default:
743 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800744 return "Error: Should not be reached.";
msarett3d9d7a72015-10-21 10:27:10 -0700745 }
746}
747
748SkISize AndroidCodecSrc::size() const {
749 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
750 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
751 if (nullptr == codec) {
752 return SkISize::Make(0, 0);
753 }
754 return codec->getSampledDimensions(fSampleSize);
755}
756
757Name AndroidCodecSrc::name() const {
758 // We will replicate the names used by CodecSrc so that images can
759 // be compared in Gold.
760 if (1 == fSampleSize) {
761 return SkOSPath::Basename(fPath.c_str());
762 }
msarett4b0778e2015-11-13 09:59:11 -0800763 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700764}
765
766/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
767
msarett18976312016-03-09 14:20:58 -0800768ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
769 : fPath(path)
770 , fMode(mode)
771 , fDstAlphaType(alphaType)
772 , fIsGpu(isGpu)
773 , fRunSerially(serial_from_path_name(path))
774{}
775
776bool ImageGenSrc::veto(SinkFlags flags) const {
777 if (fIsGpu) {
778 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect;
779 }
780
781 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
782}
783
784Error ImageGenSrc::draw(SkCanvas* canvas) const {
785 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
786 return Error::Nonfatal("Uninteresting to test image generator to 565.");
787 }
788
789 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
790 if (!encoded) {
791 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
792 }
793
794 SkAutoTDelete<SkImageGenerator> gen(nullptr);
795 switch (fMode) {
796 case kCodec_Mode:
797 gen.reset(SkCodecImageGenerator::NewFromEncodedCodec(encoded));
798 if (!gen) {
799 return "Could not create codec image generator.";
800 }
801 break;
802#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
803 case kPlatform_Mode:
804 gen.reset(SkImageGeneratorCG::NewFromEncodedCG(encoded));
805 if (!gen) {
806 return "Could not create CG image generator.";
807 }
808 break;
809#endif
810 default:
811 SkASSERT(false);
812 return "Invalid image generator mode";
813 }
814
815 // Test deferred decoding path on GPU
816 if (fIsGpu) {
817 // FIXME: The gpu backend does not draw kGray sources correctly. (skbug.com/4822)
818 // We have disabled these tests in DM.cpp.
819 SkASSERT(kGray_8_SkColorType != gen->getInfo().colorType());
820
821 SkAutoTDelete<SkImage> image(SkImage::NewFromGenerator(gen.detach(), nullptr));
822 if (!image) {
823 return "Could not create image from codec image generator.";
824 }
825 canvas->drawImage(image, 0, 0);
826 return "";
827 }
828
829 // Test various color and alpha types on CPU
830 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
831
832 if (kGray_8_SkColorType == decodeInfo.colorType() &&
833 kOpaque_SkAlphaType != decodeInfo.alphaType()) {
834 return Error::Nonfatal("Avoid requesting non-opaque kGray8 decodes.");
835 }
836
837 SkAutoTUnref<SkColorTable> colorTable(nullptr);
838 SkPMColor* colorPtr = nullptr;
839 int* colorCountPtr = nullptr;
840 int maxColors = 256;
841 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
842 SkPMColor colors[256];
843 colorTable.reset(new SkColorTable(colors, maxColors));
844 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
845 colorCountPtr = &maxColors;
846 }
847
848 SkBitmap bitmap;
849 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
850 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
851 decodeInfo.width(), decodeInfo.height());
852 }
853
854 if (!gen->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), colorPtr,
855 colorCountPtr))
856 {
857 return SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
858 }
859
860 premultiply_if_necessary(bitmap);
861 canvas->drawBitmap(bitmap, 0, 0);
862 return "";
863}
864
865SkISize ImageGenSrc::size() const {
866 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
867 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
868 if (nullptr == codec) {
869 return SkISize::Make(0, 0);
870 }
871 return codec->getInfo().dimensions();
872}
873
874Name ImageGenSrc::name() const {
875 return SkOSPath::Basename(fPath.c_str());
876}
877
878/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
879
mtkleinf4ba3212015-01-28 15:32:24 -0800880static const SkRect kSKPViewport = {0,0, 1000,1000};
881
mtklein8d17a132015-01-30 11:42:31 -0800882SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800883
884Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800885 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800886 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800887 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
888 }
msarett8715d472016-02-17 10:02:29 -0800889 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream));
mtklein75d98fd2015-01-18 07:05:01 -0800890 if (!pic) {
891 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
892 }
halcanary96fcdcc2015-08-27 07:41:13 -0700893 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700894
mtkleinf4ba3212015-01-28 15:32:24 -0800895 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800896 canvas->drawPicture(pic);
897 return "";
898}
899
900SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700901 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
902 if (!stream) {
903 return SkISize::Make(0,0);
904 }
905 SkPictInfo info;
906 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
907 return SkISize::Make(0,0);
908 }
909 SkRect viewport = kSKPViewport;
910 if (!viewport.intersect(info.fCullRect)) {
911 return SkISize::Make(0,0);
912 }
913 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800914}
915
916Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
917
918/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
919
mtkleinad66f9b2015-02-13 15:11:10 -0800920Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
921 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
922 return src.draw(canvas);
923}
924
925/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
926
mtkleinb9eb4ac2015-02-02 18:26:03 -0800927DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
928
mtklein82d28432015-01-15 12:46:02 -0800929GPUSink::GPUSink(GrContextFactory::GLContextType ct,
kkinnunen5219fd92015-12-10 06:28:13 -0800930 GrContextFactory::GLContextOptions options,
mtklein82d28432015-01-15 12:46:02 -0800931 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700932 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800933 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800934 : fContextType(ct)
kkinnunen5219fd92015-12-10 06:28:13 -0800935 , fContextOptions(options)
mtklein748ca3b2015-01-15 10:56:12 -0800936 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700937 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800938 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800939
joshualitt5f5a8d72015-02-25 14:09:45 -0800940void PreAbandonGpuContextErrorHandler(SkError, void*) {}
941
bsalomon648c6962015-10-23 09:06:59 -0700942DEFINE_bool(imm, false, "Run gpu configs in immediate mode.");
bsalomon69cfe952015-11-30 13:27:47 -0800943DEFINE_bool(batchClip, false, "Clip each GrBatch to its device bounds for testing.");
bsalomon6dea83f2015-12-03 12:58:06 -0800944DEFINE_bool(batchBounds, false, "Draw a wireframe bounds of each GrBatch.");
bsalomon489147c2015-12-14 12:13:09 -0800945DEFINE_int32(batchLookback, -1, "Maximum GrBatch lookback for combining, negative means default.");
bsalomonaecc0182016-03-07 11:50:44 -0800946DEFINE_int32(batchLookahead, -1, "Maximum GrBatch lookahead for combining, negative means "
947 "default.");
bsalomon648c6962015-10-23 09:06:59 -0700948
mtkleinb9eb4ac2015-02-02 18:26:03 -0800949Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
kkinnunen5219fd92015-12-10 06:28:13 -0800950 GrContextOptions grOptions;
bsalomon489147c2015-12-14 12:13:09 -0800951 grOptions.fImmediateMode = FLAGS_imm;
952 grOptions.fClipBatchToBounds = FLAGS_batchClip;
953 grOptions.fDrawBatchBounds = FLAGS_batchBounds;
954 grOptions.fMaxBatchLookback = FLAGS_batchLookback;
bsalomonaecc0182016-03-07 11:50:44 -0800955 grOptions.fMaxBatchLookahead = FLAGS_batchLookahead;
kkinnunen64492c42015-12-08 01:24:40 -0800956
kkinnunen5219fd92015-12-10 06:28:13 -0800957 src.modifyGrContextOptions(&grOptions);
958
959 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -0800960 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800961 const SkImageInfo info =
brianosman744898a2016-03-01 13:44:28 -0800962 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
msarett13a036b2016-02-08 09:10:47 -0800963#if SK_SUPPORT_GPU
964 const int maxDimension = factory.getContextInfo(fContextType, fContextOptions).
965 fGrContext->caps()->maxTextureSize();
966 if (maxDimension < SkTMax(size.width(), size.height())) {
967 return Error::Nonfatal("Src too large to create a texture.\n");
968 }
969#endif
970
mtklein748ca3b2015-01-15 10:56:12 -0800971 SkAutoTUnref<SkSurface> surface(
kkinnunen3e980c32015-12-23 01:33:00 -0800972 NewGpuSurface(&factory, fContextType, fContextOptions, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800973 if (!surface) {
974 return "Could not create a surface.";
975 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800976 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700977 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800978 factory.abandonContexts();
979 }
mtklein748ca3b2015-01-15 10:56:12 -0800980 SkCanvas* canvas = surface->getCanvas();
981 Error err = src.draw(canvas);
982 if (!err.isEmpty()) {
983 return err;
984 }
985 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800986 if (FLAGS_gpuStats) {
987 canvas->getGrContext()->dumpCacheStats(log);
988 canvas->getGrContext()->dumpGpuStats(log);
989 }
mtklein748ca3b2015-01-15 10:56:12 -0800990 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800991 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800992 if (FLAGS_abandonGpuContext) {
993 factory.abandonContexts();
994 }
mtklein748ca3b2015-01-15 10:56:12 -0800995 return "";
996}
997
998/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
999
halcanary47ef4d52015-03-03 09:13:09 -08001000static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
1001 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
1002 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -08001003 int width = src.size().width(),
1004 height = src.size().height();
1005
halcanary7e798182015-04-14 14:06:18 -07001006 if (FLAGS_multiPage) {
1007 const int kLetterWidth = 612, // 8.5 * 72
1008 kLetterHeight = 792; // 11 * 72
1009 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
1010 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -08001011
halcanary7e798182015-04-14 14:06:18 -07001012 int xPages = ((width - 1) / kLetterWidth) + 1;
1013 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -08001014
halcanary7e798182015-04-14 14:06:18 -07001015 for (int y = 0; y < yPages; ++y) {
1016 for (int x = 0; x < xPages; ++x) {
1017 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
1018 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
1019 SkCanvas* canvas =
1020 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
1021 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001022 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001023 }
1024 canvas->clipRect(letter);
1025 canvas->translate(-letter.width() * x, -letter.height() * y);
1026 Error err = src.draw(canvas);
1027 if (!err.isEmpty()) {
1028 return err;
1029 }
1030 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -07001031 }
halcanaryfd4a9932015-01-28 11:45:58 -08001032 }
halcanary7e798182015-04-14 14:06:18 -07001033 } else {
1034 SkCanvas* canvas =
1035 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1036 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001037 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001038 }
1039 Error err = src.draw(canvas);
1040 if (!err.isEmpty()) {
1041 return err;
1042 }
1043 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001044 }
halcanary7e798182015-04-14 14:06:18 -07001045 if (!doc->close()) {
1046 return "SkDocument::close() returned false";
1047 }
halcanaryfd4a9932015-01-28 11:45:58 -08001048 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -08001049 return "";
1050}
1051
halcanaryc11c62f2015-09-28 11:51:54 -07001052PDFSink::PDFSink(const char* rasterizer) : fRasterizer(rasterizer) {}
halcanary47ef4d52015-03-03 09:13:09 -08001053
1054Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1055 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
1056 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -07001057 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001058 }
halcanaryf12a1672015-09-23 12:45:49 -07001059 SkTArray<SkDocument::Attribute> info;
1060 info.emplace_back(SkString("Title"), src.name());
1061 info.emplace_back(SkString("Subject"),
1062 SkString("rendering correctness test"));
1063 info.emplace_back(SkString("Creator"), SkString("Skia/DM"));
halcanaryc11c62f2015-09-28 11:51:54 -07001064
1065 info.emplace_back(SkString("Keywords"),
1066 SkStringPrintf("Rasterizer:%s;", fRasterizer));
halcanary70015762016-02-11 07:59:59 -08001067 doc->setMetadata(&info[0], info.count(), nullptr, nullptr);
halcanary47ef4d52015-03-03 09:13:09 -08001068 return draw_skdocument(src, doc.get(), dst);
1069}
1070
1071/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1072
1073XPSSink::XPSSink() {}
1074
1075Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1076 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
1077 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -07001078 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001079 }
1080 return draw_skdocument(src, doc.get(), dst);
1081}
mtklein748ca3b2015-01-15 10:56:12 -08001082/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1083
mtklein9c3f17d2015-01-28 11:35:18 -08001084SKPSink::SKPSink() {}
1085
mtkleinb9eb4ac2015-02-02 18:26:03 -08001086Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001087 SkSize size;
1088 size = src.size();
1089 SkPictureRecorder recorder;
1090 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1091 if (!err.isEmpty()) {
1092 return err;
1093 }
1094 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1095 pic->serialize(dst);
1096 return "";
1097}
1098
1099/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1100
mtklein8a4527e2015-01-31 20:00:58 -08001101SVGSink::SVGSink() {}
1102
mtkleinb9eb4ac2015-02-02 18:26:03 -08001103Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -07001104 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -08001105 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
1106 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
1107 xmlWriter));
1108 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -08001109}
1110
1111/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1112
mtklein27c3fdd2016-02-26 14:43:21 -08001113RasterSink::RasterSink(SkColorType colorType, SkColorProfileType profileType)
1114 : fColorType(colorType)
1115 , fProfileType(profileType) {}
mtklein748ca3b2015-01-15 10:56:12 -08001116
mtkleinb9eb4ac2015-02-02 18:26:03 -08001117Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001118 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001119 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1120 SkAlphaType alphaType = kPremul_SkAlphaType;
1121 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1122
mtkleinc8be09a2016-01-04 18:56:57 -08001123 SkMallocPixelRef::ZeroedPRFactory factory;
mtklein27c3fdd2016-02-26 14:43:21 -08001124 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(),
1125 fColorType, alphaType, fProfileType),
mtkleinc8be09a2016-01-04 18:56:57 -08001126 &factory,
1127 nullptr/*colortable*/);
mtklein748ca3b2015-01-15 10:56:12 -08001128 SkCanvas canvas(*dst);
1129 return src.draw(&canvas);
1130}
1131
1132/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1133
mtkleina16e69e2015-05-05 11:38:45 -07001134// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001135// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001136// Several examples below.
1137
mtkleincbf89782016-02-19 14:27:14 -08001138template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001139static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001140 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001141 class ProxySrc : public Src {
1142 public:
mtkleincbf89782016-02-19 14:27:14 -08001143 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001144 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
msarett62d3b102015-12-10 15:14:27 -08001145 Name name() const override { sk_throw(); return ""; } // Won't be called.
mtkleina16e69e2015-05-05 11:38:45 -07001146 SkISize size() const override { return fSize; }
1147 private:
mtkleincbf89782016-02-19 14:27:14 -08001148 SkISize fSize;
1149 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001150 };
msarett62d3b102015-12-10 15:14:27 -08001151 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001152}
1153
1154/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1155
mtklein4a34ecb2016-01-08 10:19:35 -08001156DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1157
1158// Is *bitmap identical to what you get drawing src into sink?
1159static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1160 // We can only check raster outputs.
1161 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1162 if (FLAGS_check && bitmap) {
1163 SkBitmap reference;
1164 SkString log;
1165 Error err = sink->draw(src, &reference, nullptr, &log);
1166 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1167 SkASSERT(err.isEmpty());
1168 if (!err.isEmpty()) {
1169 return err;
1170 }
1171 // The dimensions are a property of the Src only, and so should be identical.
1172 SkASSERT(reference.getSize() == bitmap->getSize());
1173 if (reference.getSize() != bitmap->getSize()) {
1174 return "Dimensions don't match reference";
1175 }
1176 // All SkBitmaps in DM are pre-locked and tight, so this comparison is easy.
1177 if (0 != memcmp(reference.getPixels(), bitmap->getPixels(), reference.getSize())) {
1178 return "Pixels don't match reference";
1179 }
1180 }
1181 return "";
1182}
1183
1184/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1185
mtkleind603b222015-02-17 11:13:33 -08001186static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1187 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1188 matrix->mapRect(&bounds);
1189 matrix->postTranslate(-bounds.x(), -bounds.y());
1190 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1191}
1192
msarett62d3b102015-12-10 15:14:27 -08001193ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001194
mtkleinb9eb4ac2015-02-02 18:26:03 -08001195Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001196 SkMatrix matrix = fMatrix;
1197 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
msarett62d3b102015-12-10 15:14:27 -08001198 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001199 canvas->concat(matrix);
1200 return src.draw(canvas);
1201 });
mtklein748ca3b2015-01-15 10:56:12 -08001202}
1203
mtkleind603b222015-02-17 11:13:33 -08001204// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1205// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001206ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001207
1208Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1209 Error err = fSink->draw(src, bitmap, stream, log);
1210 if (!err.isEmpty()) {
1211 return err;
1212 }
1213
1214 SkMatrix inverse;
1215 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1216 return "Cannot upright --matrix.";
1217 }
1218 SkMatrix upright = SkMatrix::I();
1219 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1220 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1221 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1222 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1223
1224 SkBitmap uprighted;
1225 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1226 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1227
1228 SkCanvas canvas(uprighted);
1229 canvas.concat(upright);
1230 SkPaint paint;
1231 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1232 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1233
1234 *bitmap = uprighted;
1235 bitmap->lockPixels();
1236 return "";
1237}
1238
mtklein748ca3b2015-01-15 10:56:12 -08001239/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1240
mtkleina16e69e2015-05-05 11:38:45 -07001241Error ViaSerialization::draw(
1242 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001243 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001244 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001245 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001246 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1247 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001248 if (!err.isEmpty()) {
1249 return err;
1250 }
1251 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1252
1253 // Serialize it and then deserialize it.
1254 SkDynamicMemoryWStream wStream;
1255 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001256 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
msarett8715d472016-02-17 10:02:29 -08001257 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream));
mtklein748ca3b2015-01-15 10:56:12 -08001258
msarett62d3b102015-12-10 15:14:27 -08001259 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001260 canvas->drawPicture(deserialized);
mtklein4a34ecb2016-01-08 10:19:35 -08001261 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001262 });
mtklein748ca3b2015-01-15 10:56:12 -08001263}
1264
1265/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1266
msarett62d3b102015-12-10 15:14:27 -08001267ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1268 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001269 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001270 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001271 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001272
mtkleinb9eb4ac2015-02-02 18:26:03 -08001273Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001274 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001275 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001276 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1277 SkIntToScalar(size.height()),
1278 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001279 if (!err.isEmpty()) {
1280 return err;
1281 }
mtkleinb7e8d692015-04-07 08:30:32 -07001282 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001283
msarett62d3b102015-12-10 15:14:27 -08001284 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001285 const int xTiles = (size.width() + fW - 1) / fW,
1286 yTiles = (size.height() + fH - 1) / fH;
1287 SkMultiPictureDraw mpd(xTiles*yTiles);
1288 SkTDArray<SkSurface*> surfaces;
1289 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001290
mtkleina16e69e2015-05-05 11:38:45 -07001291 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1292 for (int j = 0; j < yTiles; j++) {
1293 for (int i = 0; i < xTiles; i++) {
1294 // This lets our ultimate Sink determine the best kind of surface.
1295 // E.g., if it's a GpuSink, the surfaces and images are textures.
1296 SkSurface* s = canvas->newSurface(info);
1297 if (!s) {
1298 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001299 }
mtkleina16e69e2015-05-05 11:38:45 -07001300 surfaces.push(s);
1301 SkCanvas* c = s->getCanvas();
1302 c->translate(SkIntToScalar(-i * fW),
1303 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1304 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001305 }
mtklein748ca3b2015-01-15 10:56:12 -08001306 }
mtkleina16e69e2015-05-05 11:38:45 -07001307 mpd.draw();
1308 for (int j = 0; j < yTiles; j++) {
1309 for (int i = 0; i < xTiles; i++) {
1310 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1311 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1312 }
1313 }
1314 surfaces.unrefAll();
1315 return "";
1316 });
mtklein748ca3b2015-01-15 10:56:12 -08001317}
1318
mtkleinb7e8d692015-04-07 08:30:32 -07001319/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1320
mtklein4a34ecb2016-01-08 10:19:35 -08001321Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1322 auto size = src.size();
1323 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1324 SkPictureRecorder recorder;
1325 SkAutoTUnref<SkPicture> pic;
1326 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1327 SkIntToScalar(size.height())));
1328 if (!err.isEmpty()) {
1329 return err;
1330 }
1331 pic.reset(recorder.endRecordingAsPicture());
1332 canvas->drawPicture(pic);
1333 return check_against_reference(bitmap, src, fSink);
1334 });
1335}
1336
1337/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1338
mtkleinb7e8d692015-04-07 08:30:32 -07001339// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1340// This tests that any shortcuts we may take while recording that second picture are legal.
1341Error ViaSecondPicture::draw(
1342 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001343 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001344 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleina16e69e2015-05-05 11:38:45 -07001345 SkPictureRecorder recorder;
1346 SkAutoTUnref<SkPicture> pic;
1347 for (int i = 0; i < 2; i++) {
1348 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1349 SkIntToScalar(size.height())));
1350 if (!err.isEmpty()) {
1351 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001352 }
mtkleina16e69e2015-05-05 11:38:45 -07001353 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001354 }
mtkleina16e69e2015-05-05 11:38:45 -07001355 canvas->drawPicture(pic);
mtklein4a34ecb2016-01-08 10:19:35 -08001356 return check_against_reference(bitmap, src, fSink);
mtkleina16e69e2015-05-05 11:38:45 -07001357 });
mtkleinb7e8d692015-04-07 08:30:32 -07001358}
1359
mtkleind31c13d2015-05-05 12:59:56 -07001360/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1361
mtklein6fbf4b32015-05-06 11:35:40 -07001362// Draw the Src twice. This can help exercise caching.
1363Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
msarett62d3b102015-12-10 15:14:27 -08001364 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
mtklein6fbf4b32015-05-06 11:35:40 -07001365 for (int i = 0; i < 2; i++) {
1366 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1367 canvas->clear(SK_ColorTRANSPARENT);
1368 Error err = src.draw(canvas);
1369 if (err.isEmpty()) {
1370 return err;
1371 }
1372 }
mtklein4a34ecb2016-01-08 10:19:35 -08001373 return check_against_reference(bitmap, src, fSink);
mtklein6fbf4b32015-05-06 11:35:40 -07001374 });
1375}
1376
1377/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1378
halcanary7a76f9c2016-02-03 11:53:18 -08001379#ifdef SK_MOJO
1380 Error ViaMojo::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1381 SkPictureRecorder recorder;
1382 SkRect size = SkRect::Make(SkIRect::MakeSize(src.size()));
1383 Error err = src.draw(recorder.beginRecording(size));
1384 if (!err.isEmpty()) {
1385 return err;
1386 }
1387 SkAutoTUnref<SkPicture> skPicture(recorder.endRecording());
1388
1389 SkASSERT(skPicture);
1390 SkDynamicMemoryWStream buffer;
1391 skPicture->serialize(&buffer);
1392 skPicture.reset();
1393 SkMojo::FlattenedPicturePtr mojoPicture = SkMojo::FlattenedPicture::New();
1394 mojoPicture->data.resize(buffer.bytesWritten());
1395 buffer.copyTo(mojoPicture->data.data());
1396 buffer.reset();
1397 SkASSERT(mojoPicture.get() && mojoPicture->data);
1398
1399 size_t flatSize = mojoPicture->GetSerializedSize();
1400 SkAutoMalloc storage(flatSize);
1401 if (!mojoPicture->Serialize(storage.get(), flatSize)) {
1402 return "SkMojo::FlattenedPicture::Serialize failed";
1403 }
1404 mojoPicture = SkMojo::FlattenedPicture::New();
1405 mojoPicture->Deserialize(storage.get());
1406 storage.free();
1407 if (!mojoPicture) {
1408 return "SkMojo::FlattenedPicture::Deserialize failed";
1409 }
1410 SkMemoryStream tmpStream(mojoPicture->data.data(),
1411 mojoPicture->data.size());
1412 skPicture.reset(SkPicture::CreateFromStream(&tmpStream));
1413 mojoPicture.reset();
1414 auto fn = [&](SkCanvas* canvas) -> Error {
1415 canvas->drawPicture(skPicture.get());
1416 return check_against_reference(bitmap, src, fSink);
1417 };
1418 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), fn);
1419 }
1420#else // not SK_MOJO
1421 Error ViaMojo::draw(const Src&, SkBitmap*, SkWStream*, SkString*) const {
1422 return "Mojo is missing!";
1423 }
1424#endif
1425
1426/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1427
mtkleind31c13d2015-05-05 12:59:56 -07001428// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1429// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1430// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1431struct DrawsAsSingletonPictures {
1432 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001433 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001434
mtkleind31c13d2015-05-05 12:59:56 -07001435 template <typename T>
1436 void draw(const T& op, SkCanvas* canvas) {
1437 // We must pass SkMatrix::I() as our initial matrix.
1438 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1439 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001440 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1441 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001442 }
1443
mtklein449d9b72015-09-28 10:33:02 -07001444 // Draws get their own picture.
mtkleind31c13d2015-05-05 12:59:56 -07001445 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001446 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
mtkleind31c13d2015-05-05 12:59:56 -07001447 SkPictureRecorder rec;
1448 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1449 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1450 fCanvas->drawPicture(pic);
1451 }
1452
mtklein449d9b72015-09-28 10:33:02 -07001453 // We'll just issue non-draws directly.
mtkleind31c13d2015-05-05 12:59:56 -07001454 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001455 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1456 this->draw(op, fCanvas);
1457 }
mtkleind31c13d2015-05-05 12:59:56 -07001458};
1459
mtkleind31c13d2015-05-05 12:59:56 -07001460// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1461// Then play back that macro picture into our wrapped sink.
1462Error ViaSingletonPictures::draw(
1463 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1464 auto size = src.size();
msarett62d3b102015-12-10 15:14:27 -08001465 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
mtkleind31c13d2015-05-05 12:59:56 -07001466 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1467 SkRecord skr;
1468 SkRecorder recorder(&skr, size.width(), size.height());
1469 Error err = src.draw(&recorder);
1470 if (!err.isEmpty()) {
1471 return err;
1472 }
1473
1474 // Record our macro-picture, with each draw op as its own sub-picture.
1475 SkPictureRecorder macroRec;
1476 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1477 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001478
1479 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1480 const SkDrawableList empty;
1481
1482 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1483 macroCanvas,
1484 drawables ? *drawables : empty,
1485 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001486 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001487 skr.visit<void>(i, drawsAsSingletonPictures);
1488 }
1489 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1490
1491 canvas->drawPicture(macroPic);
mtklein4a34ecb2016-01-08 10:19:35 -08001492 return check_against_reference(bitmap, src, fSink);
mtkleind31c13d2015-05-05 12:59:56 -07001493 });
1494}
1495
mtklein748ca3b2015-01-15 10:56:12 -08001496} // namespace DM