blob: 75f954f453e07e6d481d072e6cae8b3056b23307 [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"
9#include "SamplePipeControllers.h"
msarett3d9d7a72015-10-21 10:27:10 -070010#include "SkAndroidCodec.h"
scroggof24f2242015-03-03 08:59:20 -080011#include "SkCodec.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"
mtklein748ca3b2015-01-15 10:56:12 -080017#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080018#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080019#include "SkOSFile.h"
mtkleinffa901a2015-03-16 10:38:07 -070020#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080021#include "SkPictureRecorder.h"
22#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070023#include "SkRecordDraw.h"
24#include "SkRecorder.h"
mtklein2e2ea382015-10-16 10:29:41 -070025#include "SkRemote.h"
fmalita2aafe6f2015-02-06 12:51:10 -080026#include "SkSVGCanvas.h"
scroggoa1193e42015-01-21 12:09:53 -080027#include "SkStream.h"
mtklein449d9b72015-09-28 10:33:02 -070028#include "SkTLogic.h"
fmalita2aafe6f2015-02-06 12:51:10 -080029#include "SkXMLWriter.h"
msarette6dd0042015-10-09 11:07:34 -070030#include "SkSwizzler.h"
mtklein64593522015-11-12 10:41:05 -080031#include <functional>
mtklein748ca3b2015-01-15 10:56:12 -080032
halcanary7e798182015-04-14 14:06:18 -070033DEFINE_bool(multiPage, false, "For document-type backends, render the source"
34 " into multiple pages");
35
mtkleinb3e5e4d2015-03-25 13:13:43 -070036static bool lazy_decode_bitmap(const void* src, size_t size, SkBitmap* dst) {
37 SkAutoTUnref<SkData> encoded(SkData::NewWithCopy(src, size));
reedd1146452015-09-25 06:56:57 -070038 return encoded && SkDEPRECATED_InstallDiscardablePixelRef(encoded, dst);
mtkleinb3e5e4d2015-03-25 13:13:43 -070039}
40
mtklein748ca3b2015-01-15 10:56:12 -080041namespace DM {
42
mtklein748ca3b2015-01-15 10:56:12 -080043GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
44
45Error GMSrc::draw(SkCanvas* canvas) const {
halcanary96fcdcc2015-08-27 07:41:13 -070046 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080047 canvas->concat(gm->getInitialTransform());
48 gm->draw(canvas);
49 return "";
50}
51
52SkISize GMSrc::size() const {
halcanary96fcdcc2015-08-27 07:41:13 -070053 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080054 return gm->getISize();
55}
56
57Name GMSrc::name() const {
halcanary96fcdcc2015-08-27 07:41:13 -070058 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080059 return gm->getName();
60}
61
bsalomon4ee6bd82015-05-27 13:23:23 -070062void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
halcanary96fcdcc2015-08-27 07:41:13 -070063 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -070064 gm->modifyGrContextOptions(options);
65}
66
mtklein748ca3b2015-01-15 10:56:12 -080067/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
68
msarett5cb48852015-11-06 08:56:32 -080069BRDSrc::BRDSrc(Path path, SkBitmapRegionDecoder::Strategy strategy, Mode mode,
msaretta5783ae2015-09-08 15:35:32 -070070 CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
71 : fPath(path)
72 , fStrategy(strategy)
73 , fMode(mode)
74 , fDstColorType(dstColorType)
75 , fSampleSize(sampleSize)
76{}
77
78bool BRDSrc::veto(SinkFlags flags) const {
79 // No need to test to non-raster or indirect backends.
80 return flags.type != SinkFlags::kRaster
81 || flags.approach != SinkFlags::kDirect;
82}
83
msarett5cb48852015-11-06 08:56:32 -080084static SkBitmapRegionDecoder* create_brd(Path path,
85 SkBitmapRegionDecoder::Strategy strategy) {
msaretta5783ae2015-09-08 15:35:32 -070086 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
87 if (!encoded) {
88 return NULL;
89 }
msarett5cb48852015-11-06 08:56:32 -080090 return SkBitmapRegionDecoder::Create(encoded, strategy);
msaretta5783ae2015-09-08 15:35:32 -070091}
92
93Error BRDSrc::draw(SkCanvas* canvas) const {
94 SkColorType colorType = canvas->imageInfo().colorType();
95 if (kRGB_565_SkColorType == colorType &&
96 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
97 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
98 }
99 switch (fDstColorType) {
100 case CodecSrc::kGetFromCanvas_DstColorType:
101 break;
102 case CodecSrc::kIndex8_Always_DstColorType:
103 colorType = kIndex_8_SkColorType;
104 break;
105 case CodecSrc::kGrayscale_Always_DstColorType:
106 colorType = kGray_8_SkColorType;
107 break;
108 }
109
msarett5cb48852015-11-06 08:56:32 -0800110 SkAutoTDelete<SkBitmapRegionDecoder> brd(create_brd(fPath, fStrategy));
msaretta5783ae2015-09-08 15:35:32 -0700111 if (nullptr == brd.get()) {
112 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
113 }
114
msarett04965c62015-10-12 10:24:38 -0700115 if (!brd->conversionSupported(colorType)) {
116 return Error::Nonfatal("Cannot convert to color type.\n");
117 }
118
msaretta5783ae2015-09-08 15:35:32 -0700119 const uint32_t width = brd->width();
120 const uint32_t height = brd->height();
121 // Visually inspecting very small output images is not necessary.
122 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
123 return Error::Nonfatal("Scaling very small images is uninteresting.");
124 }
125 switch (fMode) {
126 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700127 SkBitmap bitmap;
128 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
129 fSampleSize, colorType, false)) {
scroggo6bd9c212015-11-04 04:28:54 -0800130 return "Cannot decode (full) region.\n";
msarett35e5d1b2015-10-27 12:50:25 -0700131 }
132 if (colorType != bitmap.colorType()) {
msaretta5783ae2015-09-08 15:35:32 -0700133 return Error::Nonfatal("Cannot convert to color type.\n");
134 }
msarett35e5d1b2015-10-27 12:50:25 -0700135 canvas->drawBitmap(bitmap, 0, 0);
msaretta5783ae2015-09-08 15:35:32 -0700136 return "";
137 }
138 case kDivisor_Mode: {
139 const uint32_t divisor = 2;
140 if (width < divisor || height < divisor) {
141 return Error::Nonfatal("Divisor is larger than image dimension.\n");
142 }
143
144 // Use a border to test subsets that extend outside the image.
145 // We will not allow the border to be larger than the image dimensions. Allowing
146 // these large borders causes off by one errors that indicate a problem with the
147 // test suite, not a problem with the implementation.
148 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
149 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
150 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
151
152 // We may need to clear the canvas to avoid uninitialized memory.
153 // Assume we are scaling a 780x780 image with sampleSize = 8.
154 // The output image should be 97x97.
155 // Each subset will be 390x390.
156 // Each scaled subset be 48x48.
157 // Four scaled subsets will only fill a 96x96 image.
158 // The bottom row and last column will not be touched.
159 // This is an unfortunate result of our rounding rules when scaling.
160 // Maybe we need to consider testing scaled subsets without trying to
161 // combine them to match the full scaled image? Or maybe this is the
162 // best we can do?
163 canvas->clear(0);
164
165 for (uint32_t x = 0; x < divisor; x++) {
166 for (uint32_t y = 0; y < divisor; y++) {
167 // Calculate the subset dimensions
168 uint32_t subsetWidth = width / divisor;
169 uint32_t subsetHeight = height / divisor;
170 const int left = x * subsetWidth;
171 const int top = y * subsetHeight;
172
173 // Increase the size of the last subset in each row or column, when the
174 // divisor does not divide evenly into the image dimensions
175 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
176 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
177
178 // Increase the size of the subset in order to have a border on each side
179 const int decodeLeft = left - unscaledBorder;
180 const int decodeTop = top - unscaledBorder;
181 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
182 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700183 SkBitmap bitmap;
184 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
185 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false)) {
scroggo6bd9c212015-11-04 04:28:54 -0800186 return "Cannot decode region.\n";
msarett35e5d1b2015-10-27 12:50:25 -0700187 }
188 if (colorType != bitmap.colorType()) {
msaretta5783ae2015-09-08 15:35:32 -0700189 return Error::Nonfatal("Cannot convert to color type.\n");
190 }
191
msarett35e5d1b2015-10-27 12:50:25 -0700192 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700193 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
194 (SkScalar) (subsetWidth / fSampleSize),
195 (SkScalar) (subsetHeight / fSampleSize)),
196 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
197 (SkScalar) (top / fSampleSize),
198 (SkScalar) (subsetWidth / fSampleSize),
199 (SkScalar) (subsetHeight / fSampleSize)),
200 nullptr);
201 }
202 }
203 return "";
204 }
205 default:
206 SkASSERT(false);
207 return "Error: Should not be reached.\n";
208 }
209}
210
211SkISize BRDSrc::size() const {
msarett5cb48852015-11-06 08:56:32 -0800212 SkAutoTDelete<SkBitmapRegionDecoder> brd(create_brd(fPath, fStrategy));
msaretta5783ae2015-09-08 15:35:32 -0700213 if (brd) {
214 return SkISize::Make(SkTMax(1, brd->width() / (int) fSampleSize),
215 SkTMax(1, brd->height() / (int) fSampleSize));
216 }
217 return SkISize::Make(0, 0);
218}
219
220static SkString get_scaled_name(const Path& path, float scale) {
221 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
222}
223
224Name BRDSrc::name() const {
225 // We will replicate the names used by CodecSrc so that images can
226 // be compared in Gold.
227 if (1 == fSampleSize) {
228 return SkOSPath::Basename(fPath.c_str());
229 }
msarett4b0778e2015-11-13 09:59:11 -0800230 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700231}
232
233/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
234
msarett0a242972015-06-11 14:27:27 -0700235CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -0700236 : fPath(path)
237 , fMode(mode)
238 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -0700239 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -0700240{}
mtklein748ca3b2015-01-15 10:56:12 -0800241
mtklein99cab4e2015-07-31 06:43:04 -0700242bool CodecSrc::veto(SinkFlags flags) const {
243 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700244 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
245 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -0700246 return flags.type != SinkFlags::kRaster
247 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700248}
scroggo9b77ddd2015-03-19 06:03:39 -0700249
msarett3d9d7a72015-10-21 10:27:10 -0700250bool get_decode_info(SkImageInfo* decodeInfo, const SkImageInfo& defaultInfo,
251 SkColorType canvasColorType, CodecSrc::DstColorType dstColorType) {
252 switch (dstColorType) {
253 case CodecSrc::kIndex8_Always_DstColorType:
254 if (kRGB_565_SkColorType == canvasColorType) {
255 return false;
256 }
257 *decodeInfo = defaultInfo.makeColorType(kIndex_8_SkColorType);
258 break;
259 case CodecSrc::kGrayscale_Always_DstColorType:
260 if (kRGB_565_SkColorType == canvasColorType) {
261 return false;
262 }
263 *decodeInfo = defaultInfo.makeColorType(kGray_8_SkColorType);
264 break;
265 default:
266 *decodeInfo = defaultInfo.makeColorType(canvasColorType);
267 break;
268 }
269
270 // FIXME: Currently we cannot draw unpremultiplied sources.
271 if (decodeInfo->alphaType() == kUnpremul_SkAlphaType) {
msarett90978142015-10-27 07:12:24 -0700272 *decodeInfo = decodeInfo->makeAlphaType(kPremul_SkAlphaType);
msarett3d9d7a72015-10-21 10:27:10 -0700273 }
274 return true;
275}
276
mtkleine0effd62015-07-29 06:37:28 -0700277Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800278 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800279 if (!encoded) {
280 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
281 }
msarett3d9d7a72015-10-21 10:27:10 -0700282 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700283 if (nullptr == codec.get()) {
284 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700285 }
286
msarett3d9d7a72015-10-21 10:27:10 -0700287 SkImageInfo decodeInfo;
288 if (!get_decode_info(&decodeInfo, codec->getInfo(), canvas->imageInfo().colorType(),
289 fDstColorType)) {
290 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
msarett438b2ad2015-04-09 12:43:10 -0700291 }
292
msarett0a242972015-06-11 14:27:27 -0700293 // Try to scale the image if it is desired
294 SkISize size = codec->getScaledDimensions(fScale);
295 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
296 return Error::Nonfatal("Test without scaling is uninteresting.");
297 }
msarettb32758a2015-08-18 13:22:46 -0700298
299 // Visually inspecting very small output images is not necessary. We will
300 // cover these cases in unit testing.
301 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
302 return Error::Nonfatal("Scaling very small images is uninteresting.");
303 }
msarett0a242972015-06-11 14:27:27 -0700304 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
305
msarett438b2ad2015-04-09 12:43:10 -0700306 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700307 SkAutoTUnref<SkColorTable> colorTable(nullptr);
308 SkPMColor* colorPtr = nullptr;
309 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700310 int maxColors = 256;
311 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
312 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700313 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700314 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
315 colorCountPtr = &maxColors;
316 }
317
scroggo9b77ddd2015-03-19 06:03:39 -0700318 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700319 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700320 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
321 decodeInfo.width(), decodeInfo.height());
322 }
323
scroggo9c59ebc2015-03-25 13:48:49 -0700324 switch (fMode) {
msarett9e707a02015-09-01 14:57:57 -0700325 case kCodec_Mode: {
halcanary96fcdcc2015-08-27 07:41:13 -0700326 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700327 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700328 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700329 // We consider incomplete to be valid, since we should still decode what is
330 // available.
scroggoeb602a52015-07-09 08:16:03 -0700331 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700332 break;
scroggoeb602a52015-07-09 08:16:03 -0700333 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700334 return Error::Nonfatal("Incompatible colortype conversion");
335 default:
336 // Everything else is considered a failure.
337 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
338 }
emmaleer97002062015-05-27 12:36:10 -0700339 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700340 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700341 }
scroggo9c59ebc2015-03-25 13:48:49 -0700342 case kScanline_Mode: {
scroggo46c57472015-09-30 08:57:13 -0700343 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
344 colorCountPtr)) {
msarett9e707a02015-09-01 14:57:57 -0700345 return Error::Nonfatal("Could not start scanline decoder");
scroggo9c59ebc2015-03-25 13:48:49 -0700346 }
scroggo1c005e42015-08-04 09:24:45 -0700347
msarette6dd0042015-10-09 11:07:34 -0700348 void* dst = bitmap.getAddr(0, 0);
349 size_t rowBytes = bitmap.rowBytes();
350 uint32_t height = decodeInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700351 switch (codec->getScanlineOrder()) {
352 case SkCodec::kTopDown_SkScanlineOrder:
353 case SkCodec::kBottomUp_SkScanlineOrder:
354 case SkCodec::kNone_SkScanlineOrder:
msarette6dd0042015-10-09 11:07:34 -0700355 // We do not need to check the return value. On an incomplete
356 // image, memory will be filled with a default value.
357 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700358 break;
scroggo46c57472015-09-30 08:57:13 -0700359 case SkCodec::kOutOfOrder_SkScanlineOrder: {
msarett10522ff2015-09-07 08:54:01 -0700360 for (int y = 0; y < decodeInfo.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700361 int dstY = codec->outputScanline(y);
msarett10522ff2015-09-07 08:54:01 -0700362 void* dstPtr = bitmap.getAddr(0, dstY);
msarette6dd0042015-10-09 11:07:34 -0700363 // We complete the loop, even if this call begins to fail
364 // due to an incomplete image. This ensures any uninitialized
365 // memory will be filled with the proper value.
366 codec->getScanlines(dstPtr, 1, bitmap.rowBytes());
msarett10522ff2015-09-07 08:54:01 -0700367 }
368 break;
369 }
370 }
371
emmaleer97002062015-05-27 12:36:10 -0700372 canvas->drawBitmap(bitmap, 0, 0);
373 break;
374 }
375 case kScanline_Subset_Mode: {
376 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
377 const int divisor = 2;
378 const int w = decodeInfo.width();
379 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700380 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700381 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
382 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700383 }
384 const int subsetWidth = w/divisor;
385 const int subsetHeight = h/divisor;
386 // One of our subsets will be larger to contain any pixels that do not divide evenly.
387 const int extraX = w % divisor;
388 const int extraY = h % divisor;
389 /*
390 * if w or h are not evenly divided by divisor need to adjust width and height of end
391 * subsets to cover entire image.
392 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
393 * and height of end subsets.
394 * subsetBm is extracted from largestSubsetBm.
395 * subsetBm's size is determined based on the current subset and may be larger for end
396 * subsets.
397 */
msarett0a242972015-06-11 14:27:27 -0700398 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700399 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
400 SkBitmap largestSubsetBm;
msarett9e707a02015-09-01 14:57:57 -0700401 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr,
402 colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700403 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
404 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
405 }
emmaleer97002062015-05-27 12:36:10 -0700406 for (int col = 0; col < divisor; col++) {
407 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
408 const int currentSubsetWidth = (col + 1 == divisor) ?
409 subsetWidth + extraX : subsetWidth;
410 const int x = col * subsetWidth;
411 for (int row = 0; row < divisor; row++) {
412 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
413 const int currentSubsetHeight = (row + 1 == divisor) ?
414 subsetHeight + extraY : subsetHeight;
415 const int y = row * subsetHeight;
416 //create scanline decoder for each subset
msarettfdb47572015-10-13 12:50:14 -0700417 SkCodec::Options options;
418 SkIRect subset = SkIRect::MakeXYWH(x, 0, currentSubsetWidth, h);
419 options.fSubset = &subset;
420 // TODO (msarett): Support this mode for all scanline orderings.
421 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options,
422 colorPtr, colorCountPtr) ||
423 SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
emmaleer97002062015-05-27 12:36:10 -0700424 if (x == 0 && y == 0) {
425 //first try, image may not be compatible
msarett5406d6f2015-08-31 06:55:13 -0700426 return Error::Nonfatal("Could not start top-down scanline decoder");
emmaleer97002062015-05-27 12:36:10 -0700427 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700428 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700429 }
430 }
msarette6dd0042015-10-09 11:07:34 -0700431 // Skip to the first line of subset. We ignore the result value here.
432 // If the skip value fails, this will indicate an incomplete image.
433 // This means that the call to getScanlines() will also fail, but it
434 // will fill the buffer with a default value, so we can still draw the
435 // image.
436 codec->skipScanlines(y);
437
emmaleer97002062015-05-27 12:36:10 -0700438 //create and set size of subsetBm
439 SkBitmap subsetBm;
scroggo6634cbb2015-09-30 13:01:55 -0700440 SkIRect bounds = SkIRect::MakeWH(currentSubsetWidth, currentSubsetHeight);
emmaleer97002062015-05-27 12:36:10 -0700441 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
msarettfdb47572015-10-13 12:50:14 -0700442 SkAutoLockPixels autolock(subsetBm, true);
443 codec->getScanlines(subsetBm.getAddr(0, 0), currentSubsetHeight,
444 subsetBm.rowBytes());
scroggo4358f132015-07-30 11:33:04 -0700445 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700446 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
447 }
448 }
scroggo9c59ebc2015-03-25 13:48:49 -0700449 break;
450 }
msarett0a242972015-06-11 14:27:27 -0700451 case kStripe_Mode: {
452 const int height = decodeInfo.height();
453 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
454 // does not align with image blocks.
455 const int stripeHeight = 37;
456 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
457
458 // Decode odd stripes
scroggo46c57472015-09-30 08:57:13 -0700459 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, NULL, colorPtr,
460 colorCountPtr)
461 || SkCodec::kTopDown_SkScanlineOrder != codec->getScanlineOrder()) {
msarett9e707a02015-09-01 14:57:57 -0700462 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
463 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
464 // to run this test for image types that do not have this scanline ordering.
msarett5406d6f2015-08-31 06:55:13 -0700465 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700466 }
msarette6dd0042015-10-09 11:07:34 -0700467
msarett0a242972015-06-11 14:27:27 -0700468 for (int i = 0; i < numStripes; i += 2) {
469 // Skip a stripe
470 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700471 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700472
473 // Read a stripe
474 const int startY = (i + 1) * stripeHeight;
475 const int linesToRead = SkTMin(stripeHeight, height - startY);
476 if (linesToRead > 0) {
msarette6dd0042015-10-09 11:07:34 -0700477 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700478 }
479 }
480
481 // Decode even stripes
scroggo46c57472015-09-30 08:57:13 -0700482 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo, nullptr,
483 colorPtr, colorCountPtr);
scroggo1c005e42015-08-04 09:24:45 -0700484 if (SkCodec::kSuccess != startResult) {
485 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700486 }
487 for (int i = 0; i < numStripes; i += 2) {
488 // Read a stripe
489 const int startY = i * stripeHeight;
490 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarette6dd0042015-10-09 11:07:34 -0700491 codec->getScanlines(bitmap.getAddr(0, startY), linesToRead, bitmap.rowBytes());
msarett0a242972015-06-11 14:27:27 -0700492
493 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700494 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
495 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700496 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700497 }
498 }
499 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700500 break;
msarett0a242972015-06-11 14:27:27 -0700501 }
scroggob636b452015-07-22 07:16:20 -0700502 case kSubset_Mode: {
503 // Arbitrarily choose a divisor.
504 int divisor = 2;
505 // Total width/height of the image.
506 const int W = codec->getInfo().width();
507 const int H = codec->getInfo().height();
508 if (divisor > W || divisor > H) {
509 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
510 "for %s with dimensions (%d x %d)", divisor,
511 fPath.c_str(), W, H));
512 }
513 // subset dimensions
514 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
515 const int w = SkAlign2(W / divisor);
516 const int h = SkAlign2(H / divisor);
517 SkIRect subset;
518 SkCodec::Options opts;
519 opts.fSubset = &subset;
520 SkBitmap subsetBm;
521 // We will reuse pixel memory from bitmap.
522 void* pixels = bitmap.getPixels();
523 // Keep track of left and top (for drawing subsetBm into canvas). We could use
524 // fScale * x and fScale * y, but we want integers such that the next subset will start
525 // where the last one ended. So we'll add decodeInfo.width() and height().
526 int left = 0;
527 for (int x = 0; x < W; x += w) {
528 int top = 0;
529 for (int y = 0; y < H; y+= h) {
530 // Do not make the subset go off the edge of the image.
531 const int preScaleW = SkTMin(w, W - x);
532 const int preScaleH = SkTMin(h, H - y);
533 subset.setXYWH(x, y, preScaleW, preScaleH);
534 // And scale
535 // FIXME: Should we have a version of getScaledDimensions that takes a subset
536 // into account?
msarette6dd0042015-10-09 11:07:34 -0700537 decodeInfo = decodeInfo.makeWH(
538 SkTMax(1, SkScalarRoundToInt(preScaleW * fScale)),
539 SkTMax(1, SkScalarRoundToInt(preScaleH * fScale)));
scroggob636b452015-07-22 07:16:20 -0700540 size_t rowBytes = decodeInfo.minRowBytes();
541 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700542 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700543 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
544 }
545 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
546 &opts, colorPtr, colorCountPtr);
547 switch (result) {
548 case SkCodec::kSuccess:
549 case SkCodec::kIncompleteInput:
550 break;
551 case SkCodec::kInvalidConversion:
552 if (0 == (x|y)) {
553 // First subset is okay to return unimplemented.
554 return Error::Nonfatal("Incompatible colortype conversion");
555 }
556 // If the first subset succeeded, a later one should not fail.
557 // fall through to failure
558 case SkCodec::kUnimplemented:
559 if (0 == (x|y)) {
560 // First subset is okay to return unimplemented.
561 return Error::Nonfatal("subset codec not supported");
562 }
563 // If the first subset succeeded, why would a later one fail?
564 // fall through to failure
565 default:
566 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
567 "from %s with dimensions (%d x %d)\t error %d",
568 x, y, decodeInfo.width(), decodeInfo.height(),
569 fPath.c_str(), W, H, result);
570 }
571 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 }
scroggo9b77ddd2015-03-19 06:03:39 -0700580 }
scroggo9c59ebc2015-03-25 13:48:49 -0700581 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700582}
583
584SkISize CodecSrc::size() const {
585 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700586 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700587 if (nullptr == codec) {
588 return SkISize::Make(0, 0);
589 }
590 return codec->getScaledDimensions(fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700591}
592
593Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700594 if (1.0f == fScale) {
595 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700596 }
msaretta5783ae2015-09-08 15:35:32 -0700597 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700598}
599
600/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
601
msarett3d9d7a72015-10-21 10:27:10 -0700602AndroidCodecSrc::AndroidCodecSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType,
603 int sampleSize)
604 : fPath(path)
605 , fMode(mode)
606 , fDstColorType(dstColorType)
607 , fSampleSize(sampleSize)
608{}
609
610bool AndroidCodecSrc::veto(SinkFlags flags) const {
611 // No need to test decoding to non-raster or indirect backend.
612 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
613 // let the GPU handle it.
614 return flags.type != SinkFlags::kRaster
615 || flags.approach != SinkFlags::kDirect;
616}
617
618Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
619 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
620 if (!encoded) {
621 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
622 }
623 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
624 if (nullptr == codec.get()) {
625 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
626 }
627
628 SkImageInfo decodeInfo;
629 if (!get_decode_info(&decodeInfo, codec->getInfo(), canvas->imageInfo().colorType(),
630 fDstColorType)) {
631 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
632 }
633
634 // Scale the image if it is desired.
635 SkISize size = codec->getSampledDimensions(fSampleSize);
636
637 // Visually inspecting very small output images is not necessary. We will
638 // cover these cases in unit testing.
639 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
640 return Error::Nonfatal("Scaling very small images is uninteresting.");
641 }
642 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
643
644 // Construct a color table for the decode if necessary
645 SkAutoTUnref<SkColorTable> colorTable(nullptr);
646 SkPMColor* colorPtr = nullptr;
647 int* colorCountPtr = nullptr;
648 int maxColors = 256;
649 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
650 SkPMColor colors[256];
651 colorTable.reset(new SkColorTable(colors, maxColors));
652 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
653 colorCountPtr = &maxColors;
654 }
655
656 SkBitmap bitmap;
657 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
658 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
659 decodeInfo.width(), decodeInfo.height());
660 }
661
662 // Create options for the codec.
663 SkAndroidCodec::AndroidOptions options;
664 options.fColorPtr = colorPtr;
665 options.fColorCount = colorCountPtr;
666 options.fSampleSize = fSampleSize;
667
668 switch (fMode) {
669 case kFullImage_Mode: {
670 switch (codec->getAndroidPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(),
671 &options)) {
672 case SkCodec::kSuccess:
673 case SkCodec::kIncompleteInput:
674 break;
675 case SkCodec::kInvalidConversion:
676 return Error::Nonfatal("Cannot convert to requested color type.\n");
677 default:
678 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
679 }
680 canvas->drawBitmap(bitmap, 0, 0);
681 return "";
682 }
683 case kDivisor_Mode: {
684 const int width = codec->getInfo().width();
685 const int height = codec->getInfo().height();
686 const int divisor = 2;
687 if (width < divisor || height < divisor) {
688 return Error::Nonfatal("Divisor is larger than image dimension.\n");
689 }
690
msarettfa23a9e2015-10-21 13:26:59 -0700691 // Keep track of the final decoded dimensions.
692 int finalScaledWidth = 0;
693 int finalScaledHeight = 0;
msarett3d9d7a72015-10-21 10:27:10 -0700694 for (int x = 0; x < divisor; x++) {
695 for (int y = 0; y < divisor; y++) {
696 // Calculate the subset dimensions
697 int subsetWidth = width / divisor;
698 int subsetHeight = height / divisor;
699 const int left = x * subsetWidth;
700 const int top = y * subsetHeight;
701
702 // Increase the size of the last subset in each row or column, when the
703 // divisor does not divide evenly into the image dimensions
704 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
705 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
706 SkIRect subset = SkIRect::MakeXYWH(left, top, subsetWidth, subsetHeight);
707 if (!codec->getSupportedSubset(&subset)) {
708 return "Could not get supported subset to decode.\n";
709 }
710 options.fSubset = &subset;
msarettfa23a9e2015-10-21 13:26:59 -0700711 const int scaledWidthOffset = subset.left() / fSampleSize;
712 const int scaledHeightOffset = subset.top() / fSampleSize;
713 void* pixels = bitmap.getAddr(scaledWidthOffset, scaledHeightOffset);
msarett3d9d7a72015-10-21 10:27:10 -0700714 SkISize scaledSubsetSize = codec->getSampledSubsetDimensions(fSampleSize,
715 subset);
716 SkImageInfo subsetDecodeInfo = decodeInfo.makeWH(scaledSubsetSize.width(),
717 scaledSubsetSize.height());
718
msarettfa23a9e2015-10-21 13:26:59 -0700719 if (x + 1 == divisor && y + 1 == divisor) {
720 finalScaledWidth = scaledWidthOffset + scaledSubsetSize.width();
721 finalScaledHeight = scaledHeightOffset + scaledSubsetSize.height();
722 }
723
msarett3d9d7a72015-10-21 10:27:10 -0700724 switch (codec->getAndroidPixels(subsetDecodeInfo, pixels, bitmap.rowBytes(),
725 &options)) {
726 case SkCodec::kSuccess:
727 case SkCodec::kIncompleteInput:
728 break;
729 case SkCodec::kInvalidConversion:
730 return Error::Nonfatal("Cannot convert to requested color type.\n");
731 default:
732 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
733 }
734 }
735 }
msarettfa23a9e2015-10-21 13:26:59 -0700736
737 SkRect rect = SkRect::MakeXYWH(0, 0, (SkScalar) finalScaledWidth,
738 (SkScalar) finalScaledHeight);
739 canvas->drawBitmapRect(bitmap, rect, rect, nullptr);
msarett3d9d7a72015-10-21 10:27:10 -0700740 return "";
741 }
742 default:
743 SkASSERT(false);
744 return "Error: Should not be reached.\n";
745 }
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
msarett164d3022015-11-10 15:09:03 -0800768ImageSrc::ImageSrc(Path path) : fPath(path) {}
scroggo9b77ddd2015-03-19 06:03:39 -0700769
mtklein99cab4e2015-07-31 06:43:04 -0700770bool ImageSrc::veto(SinkFlags flags) const {
771 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700772 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700773 return flags.type != SinkFlags::kRaster
774 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700775}
scroggo9b77ddd2015-03-19 06:03:39 -0700776
mtkleine0effd62015-07-29 06:37:28 -0700777Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700778 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
779 if (!encoded) {
780 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
781 }
mtkleine0effd62015-07-29 06:37:28 -0700782 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800783
msarett164d3022015-11-10 15:09:03 -0800784 // Decode the full image.
785 SkBitmap bitmap;
786 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
787 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
788 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
mtkleinedc93bc2015-01-30 13:22:23 -0800789 }
msarett164d3022015-11-10 15:09:03 -0800790 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
791 // Do not draw a bitmap with alpha to a destination without alpha.
792 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800793 }
msarett164d3022015-11-10 15:09:03 -0800794 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
795 canvas->drawBitmap(bitmap, 0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800796 return "";
797}
798
799SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800800 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700801 SkBitmap bitmap;
802 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
803 encoded->size(),
804 &bitmap,
805 kUnknown_SkColorType,
806 SkImageDecoder::kDecodeBounds_Mode)) {
807 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800808 }
scroggo9b77ddd2015-03-19 06:03:39 -0700809 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800810}
811
mtklein9264a952015-01-20 10:11:53 -0800812Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800813 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800814}
mtklein748ca3b2015-01-15 10:56:12 -0800815
816/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
817
mtkleinf4ba3212015-01-28 15:32:24 -0800818static const SkRect kSKPViewport = {0,0, 1000,1000};
819
mtklein8d17a132015-01-30 11:42:31 -0800820SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800821
822Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800823 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800824 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800825 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
826 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700827 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800828 if (!pic) {
829 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
830 }
halcanary96fcdcc2015-08-27 07:41:13 -0700831 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700832
mtkleinf4ba3212015-01-28 15:32:24 -0800833 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800834 canvas->drawPicture(pic);
835 return "";
836}
837
838SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700839 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
840 if (!stream) {
841 return SkISize::Make(0,0);
842 }
843 SkPictInfo info;
844 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
845 return SkISize::Make(0,0);
846 }
847 SkRect viewport = kSKPViewport;
848 if (!viewport.intersect(info.fCullRect)) {
849 return SkISize::Make(0,0);
850 }
851 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800852}
853
854Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
855
856/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
857
mtkleinad66f9b2015-02-13 15:11:10 -0800858Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
859 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
860 return src.draw(canvas);
861}
862
863/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
864
mtkleinb9eb4ac2015-02-02 18:26:03 -0800865DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
866
mtklein82d28432015-01-15 12:46:02 -0800867GPUSink::GPUSink(GrContextFactory::GLContextType ct,
868 GrGLStandard api,
869 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700870 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800871 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800872 : fContextType(ct)
873 , fGpuAPI(api)
874 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700875 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800876 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800877
878int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800879 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800880}
881
joshualitt5f5a8d72015-02-25 14:09:45 -0800882void PreAbandonGpuContextErrorHandler(SkError, void*) {}
883
bsalomon648c6962015-10-23 09:06:59 -0700884DEFINE_bool(imm, false, "Run gpu configs in immediate mode.");
885
mtkleinb9eb4ac2015-02-02 18:26:03 -0800886Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700887 GrContextOptions options;
bsalomon648c6962015-10-23 09:06:59 -0700888 if (FLAGS_imm) {
889 options.fImmediateMode = true;
890 }
bsalomon4ee6bd82015-05-27 13:23:23 -0700891 src.modifyGrContextOptions(&options);
892
893 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800894 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800895 const SkImageInfo info =
896 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
897 SkAutoTUnref<SkSurface> surface(
bsalomonafcd7cd2015-08-31 12:39:41 -0700898 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800899 if (!surface) {
900 return "Could not create a surface.";
901 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800902 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700903 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800904 factory.abandonContexts();
905 }
mtklein748ca3b2015-01-15 10:56:12 -0800906 SkCanvas* canvas = surface->getCanvas();
907 Error err = src.draw(canvas);
908 if (!err.isEmpty()) {
909 return err;
910 }
911 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800912 if (FLAGS_gpuStats) {
913 canvas->getGrContext()->dumpCacheStats(log);
914 canvas->getGrContext()->dumpGpuStats(log);
915 }
mtklein748ca3b2015-01-15 10:56:12 -0800916 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800917 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800918 if (FLAGS_abandonGpuContext) {
919 factory.abandonContexts();
920 }
mtklein748ca3b2015-01-15 10:56:12 -0800921 return "";
922}
923
924/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
925
halcanary47ef4d52015-03-03 09:13:09 -0800926static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
927 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
928 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800929 int width = src.size().width(),
930 height = src.size().height();
931
halcanary7e798182015-04-14 14:06:18 -0700932 if (FLAGS_multiPage) {
933 const int kLetterWidth = 612, // 8.5 * 72
934 kLetterHeight = 792; // 11 * 72
935 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
936 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800937
halcanary7e798182015-04-14 14:06:18 -0700938 int xPages = ((width - 1) / kLetterWidth) + 1;
939 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800940
halcanary7e798182015-04-14 14:06:18 -0700941 for (int y = 0; y < yPages; ++y) {
942 for (int x = 0; x < xPages; ++x) {
943 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
944 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
945 SkCanvas* canvas =
946 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
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 canvas->clipRect(letter);
951 canvas->translate(-letter.width() * x, -letter.height() * y);
952 Error err = src.draw(canvas);
953 if (!err.isEmpty()) {
954 return err;
955 }
956 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700957 }
halcanaryfd4a9932015-01-28 11:45:58 -0800958 }
halcanary7e798182015-04-14 14:06:18 -0700959 } else {
960 SkCanvas* canvas =
961 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
962 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700963 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700964 }
965 Error err = src.draw(canvas);
966 if (!err.isEmpty()) {
967 return err;
968 }
969 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800970 }
halcanary7e798182015-04-14 14:06:18 -0700971 if (!doc->close()) {
972 return "SkDocument::close() returned false";
973 }
halcanaryfd4a9932015-01-28 11:45:58 -0800974 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800975 return "";
976}
977
halcanaryc11c62f2015-09-28 11:51:54 -0700978PDFSink::PDFSink(const char* rasterizer) : fRasterizer(rasterizer) {}
halcanary47ef4d52015-03-03 09:13:09 -0800979
980Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
981 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
982 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700983 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800984 }
halcanaryf12a1672015-09-23 12:45:49 -0700985 SkTArray<SkDocument::Attribute> info;
986 info.emplace_back(SkString("Title"), src.name());
987 info.emplace_back(SkString("Subject"),
988 SkString("rendering correctness test"));
989 info.emplace_back(SkString("Creator"), SkString("Skia/DM"));
halcanaryc11c62f2015-09-28 11:51:54 -0700990
991 info.emplace_back(SkString("Keywords"),
992 SkStringPrintf("Rasterizer:%s;", fRasterizer));
halcanaryf12a1672015-09-23 12:45:49 -0700993 doc->setMetadata(info, nullptr, nullptr);
halcanary47ef4d52015-03-03 09:13:09 -0800994 return draw_skdocument(src, doc.get(), dst);
995}
996
997/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
998
999XPSSink::XPSSink() {}
1000
1001Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1002 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
1003 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -07001004 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001005 }
1006 return draw_skdocument(src, doc.get(), dst);
1007}
mtklein748ca3b2015-01-15 10:56:12 -08001008/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1009
mtklein9c3f17d2015-01-28 11:35:18 -08001010SKPSink::SKPSink() {}
1011
mtkleinb9eb4ac2015-02-02 18:26:03 -08001012Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001013 SkSize size;
1014 size = src.size();
1015 SkPictureRecorder recorder;
1016 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1017 if (!err.isEmpty()) {
1018 return err;
1019 }
1020 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1021 pic->serialize(dst);
1022 return "";
1023}
1024
1025/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1026
mtklein8a4527e2015-01-31 20:00:58 -08001027SVGSink::SVGSink() {}
1028
mtkleinb9eb4ac2015-02-02 18:26:03 -08001029Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -07001030 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -08001031 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
1032 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
1033 xmlWriter));
1034 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -08001035}
1036
1037/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1038
mtklein748ca3b2015-01-15 10:56:12 -08001039RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
1040
mtkleinb9eb4ac2015-02-02 18:26:03 -08001041Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001042 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001043 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1044 SkAlphaType alphaType = kPremul_SkAlphaType;
1045 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1046
1047 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
1048 dst->eraseColor(SK_ColorTRANSPARENT);
1049 SkCanvas canvas(*dst);
1050 return src.draw(&canvas);
1051}
1052
1053/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1054
mtkleina16e69e2015-05-05 11:38:45 -07001055// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001056// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001057// Several examples below.
1058
mtkleina16e69e2015-05-05 11:38:45 -07001059static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtklein64593522015-11-12 10:41:05 -08001060 SkISize size, std::function<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001061 class ProxySrc : public Src {
1062 public:
mtklein64593522015-11-12 10:41:05 -08001063 ProxySrc(SkISize size, std::function<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001064 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
1065 Name name() const override { sk_throw(); return ""; } // Won't be called.
1066 SkISize size() const override { return fSize; }
1067 private:
mtklein64593522015-11-12 10:41:05 -08001068 SkISize fSize;
1069 std::function<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001070 };
1071 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
1072}
1073
1074/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1075
mtkleind603b222015-02-17 11:13:33 -08001076static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1077 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1078 matrix->mapRect(&bounds);
1079 matrix->postTranslate(-bounds.x(), -bounds.y());
1080 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1081}
1082
mtklein78829242015-05-06 07:54:07 -07001083ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001084
mtkleinb9eb4ac2015-02-02 18:26:03 -08001085Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001086 SkMatrix matrix = fMatrix;
1087 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
1088 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1089 canvas->concat(matrix);
1090 return src.draw(canvas);
1091 });
mtklein748ca3b2015-01-15 10:56:12 -08001092}
1093
mtkleind603b222015-02-17 11:13:33 -08001094// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1095// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -07001096ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001097
1098Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1099 Error err = fSink->draw(src, bitmap, stream, log);
1100 if (!err.isEmpty()) {
1101 return err;
1102 }
1103
1104 SkMatrix inverse;
1105 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1106 return "Cannot upright --matrix.";
1107 }
1108 SkMatrix upright = SkMatrix::I();
1109 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1110 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1111 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1112 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1113
1114 SkBitmap uprighted;
1115 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1116 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1117
1118 SkCanvas canvas(uprighted);
1119 canvas.concat(upright);
1120 SkPaint paint;
1121 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1122 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1123
1124 *bitmap = uprighted;
1125 bitmap->lockPixels();
1126 return "";
1127}
1128
mtklein748ca3b2015-01-15 10:56:12 -08001129/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1130
mtkleinb9eb4ac2015-02-02 18:26:03 -08001131Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001132 auto size = src.size();
1133 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1134 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
1135 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -07001136 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -07001137 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
1138 });
mtklein748ca3b2015-01-15 10:56:12 -08001139}
1140
mtklein2e2ea382015-10-16 10:29:41 -07001141Error ViaRemote::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein479fe772015-10-21 12:34:01 -07001142 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* target) {
1143 SkAutoTDelete<SkRemote::Encoder> decoder(SkRemote::NewDecoder(target));
1144 SkAutoTDelete<SkRemote::Encoder> cache(fCache ? SkRemote::NewCachingEncoder(decoder)
1145 : nullptr);
1146 SkAutoTDelete<SkCanvas> canvas(SkRemote::NewCanvas(cache ? cache : decoder));
1147 return src.draw(canvas);
mtklein2e2ea382015-10-16 10:29:41 -07001148 });
1149}
1150
mtklein748ca3b2015-01-15 10:56:12 -08001151/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -07001152
mtkleina16e69e2015-05-05 11:38:45 -07001153Error ViaSerialization::draw(
1154 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001155 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001156 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001157 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001158 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1159 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001160 if (!err.isEmpty()) {
1161 return err;
1162 }
1163 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1164
1165 // Serialize it and then deserialize it.
1166 SkDynamicMemoryWStream wStream;
1167 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001168 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -07001169 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -08001170
mtkleina16e69e2015-05-05 11:38:45 -07001171 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1172 canvas->drawPicture(deserialized);
1173 return "";
1174 });
mtklein748ca3b2015-01-15 10:56:12 -08001175}
1176
1177/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1178
1179ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -07001180 : Via(sink)
1181 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001182 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001183 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001184
mtkleinb9eb4ac2015-02-02 18:26:03 -08001185Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001186 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001187 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001188 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1189 SkIntToScalar(size.height()),
1190 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001191 if (!err.isEmpty()) {
1192 return err;
1193 }
mtkleinb7e8d692015-04-07 08:30:32 -07001194 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001195
mtkleina16e69e2015-05-05 11:38:45 -07001196 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
1197 const int xTiles = (size.width() + fW - 1) / fW,
1198 yTiles = (size.height() + fH - 1) / fH;
1199 SkMultiPictureDraw mpd(xTiles*yTiles);
1200 SkTDArray<SkSurface*> surfaces;
1201 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001202
mtkleina16e69e2015-05-05 11:38:45 -07001203 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1204 for (int j = 0; j < yTiles; j++) {
1205 for (int i = 0; i < xTiles; i++) {
1206 // This lets our ultimate Sink determine the best kind of surface.
1207 // E.g., if it's a GpuSink, the surfaces and images are textures.
1208 SkSurface* s = canvas->newSurface(info);
1209 if (!s) {
1210 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001211 }
mtkleina16e69e2015-05-05 11:38:45 -07001212 surfaces.push(s);
1213 SkCanvas* c = s->getCanvas();
1214 c->translate(SkIntToScalar(-i * fW),
1215 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1216 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001217 }
mtklein748ca3b2015-01-15 10:56:12 -08001218 }
mtkleina16e69e2015-05-05 11:38:45 -07001219 mpd.draw();
1220 for (int j = 0; j < yTiles; j++) {
1221 for (int i = 0; i < xTiles; i++) {
1222 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1223 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1224 }
1225 }
1226 surfaces.unrefAll();
1227 return "";
1228 });
mtklein748ca3b2015-01-15 10:56:12 -08001229}
1230
mtkleinb7e8d692015-04-07 08:30:32 -07001231/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1232
mtkleinb7e8d692015-04-07 08:30:32 -07001233// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1234// This tests that any shortcuts we may take while recording that second picture are legal.
1235Error ViaSecondPicture::draw(
1236 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001237 auto size = src.size();
1238 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1239 SkPictureRecorder recorder;
1240 SkAutoTUnref<SkPicture> pic;
1241 for (int i = 0; i < 2; i++) {
1242 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1243 SkIntToScalar(size.height())));
1244 if (!err.isEmpty()) {
1245 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001246 }
mtkleina16e69e2015-05-05 11:38:45 -07001247 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001248 }
mtkleina16e69e2015-05-05 11:38:45 -07001249 canvas->drawPicture(pic);
1250 return "";
1251 });
mtkleinb7e8d692015-04-07 08:30:32 -07001252}
1253
mtkleind31c13d2015-05-05 12:59:56 -07001254/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1255
mtklein6fbf4b32015-05-06 11:35:40 -07001256// Draw the Src twice. This can help exercise caching.
1257Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1258 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1259 for (int i = 0; i < 2; i++) {
1260 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1261 canvas->clear(SK_ColorTRANSPARENT);
1262 Error err = src.draw(canvas);
1263 if (err.isEmpty()) {
1264 return err;
1265 }
1266 }
1267 return "";
1268 });
1269}
1270
1271/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1272
mtkleind31c13d2015-05-05 12:59:56 -07001273// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1274// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1275// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1276struct DrawsAsSingletonPictures {
1277 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001278 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001279
mtkleind31c13d2015-05-05 12:59:56 -07001280 template <typename T>
1281 void draw(const T& op, SkCanvas* canvas) {
1282 // We must pass SkMatrix::I() as our initial matrix.
1283 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1284 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001285 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1286 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001287 }
1288
mtklein449d9b72015-09-28 10:33:02 -07001289 // Draws get their own picture.
mtkleind31c13d2015-05-05 12:59:56 -07001290 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001291 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
mtkleind31c13d2015-05-05 12:59:56 -07001292 SkPictureRecorder rec;
1293 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1294 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1295 fCanvas->drawPicture(pic);
1296 }
1297
mtklein449d9b72015-09-28 10:33:02 -07001298 // We'll just issue non-draws directly.
mtkleind31c13d2015-05-05 12:59:56 -07001299 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001300 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1301 this->draw(op, fCanvas);
1302 }
mtkleind31c13d2015-05-05 12:59:56 -07001303};
1304
mtkleind31c13d2015-05-05 12:59:56 -07001305// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1306// Then play back that macro picture into our wrapped sink.
1307Error ViaSingletonPictures::draw(
1308 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1309 auto size = src.size();
1310 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1311 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1312 SkRecord skr;
1313 SkRecorder recorder(&skr, size.width(), size.height());
1314 Error err = src.draw(&recorder);
1315 if (!err.isEmpty()) {
1316 return err;
1317 }
1318
1319 // Record our macro-picture, with each draw op as its own sub-picture.
1320 SkPictureRecorder macroRec;
1321 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1322 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001323
1324 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1325 const SkDrawableList empty;
1326
1327 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1328 macroCanvas,
1329 drawables ? *drawables : empty,
1330 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001331 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001332 skr.visit<void>(i, drawsAsSingletonPictures);
1333 }
1334 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1335
1336 canvas->drawPicture(macroPic);
1337 return "";
1338 });
1339}
1340
mtklein748ca3b2015-01-15 10:56:12 -08001341} // namespace DM