blob: 981e47d6c0bf84690c25c8a49392fa2e3abadc18 [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"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkCodec.h"
mtkleina16e69e2015-05-05 11:38:45 -070011#include "SkCommonFlags.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070012#include "SkData.h"
mtklein748ca3b2015-01-15 10:56:12 -080013#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080014#include "SkError.h"
mtkleine44b5082015-05-07 10:53:34 -070015#include "SkFunction.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"
fmalita2aafe6f2015-02-06 12:51:10 -080025#include "SkSVGCanvas.h"
mtkleina16e69e2015-05-05 11:38:45 -070026#include "SkScanlineDecoder.h"
scroggoa1193e42015-01-21 12:09:53 -080027#include "SkStream.h"
fmalita2aafe6f2015-02-06 12:51:10 -080028#include "SkXMLWriter.h"
emmaleer8f4ba762015-08-14 07:44:46 -070029#include "SkScaledCodec.h"
mtklein748ca3b2015-01-15 10:56:12 -080030
halcanary7e798182015-04-14 14:06:18 -070031DEFINE_bool(multiPage, false, "For document-type backends, render the source"
32 " into multiple pages");
33
mtkleinb3e5e4d2015-03-25 13:13:43 -070034static bool lazy_decode_bitmap(const void* src, size_t size, SkBitmap* dst) {
35 SkAutoTUnref<SkData> encoded(SkData::NewWithCopy(src, size));
36 return encoded && SkInstallDiscardablePixelRef(encoded, dst);
37}
38
mtklein748ca3b2015-01-15 10:56:12 -080039namespace DM {
40
mtklein748ca3b2015-01-15 10:56:12 -080041GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
42
43Error GMSrc::draw(SkCanvas* canvas) const {
halcanary96fcdcc2015-08-27 07:41:13 -070044 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080045 canvas->concat(gm->getInitialTransform());
46 gm->draw(canvas);
47 return "";
48}
49
50SkISize GMSrc::size() const {
halcanary96fcdcc2015-08-27 07:41:13 -070051 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080052 return gm->getISize();
53}
54
55Name GMSrc::name() const {
halcanary96fcdcc2015-08-27 07:41:13 -070056 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080057 return gm->getName();
58}
59
bsalomon4ee6bd82015-05-27 13:23:23 -070060void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
halcanary96fcdcc2015-08-27 07:41:13 -070061 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -070062 gm->modifyGrContextOptions(options);
63}
64
mtklein748ca3b2015-01-15 10:56:12 -080065/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
66
msaretta5783ae2015-09-08 15:35:32 -070067BRDSrc::BRDSrc(Path path, SkBitmapRegionDecoderInterface::Strategy strategy, Mode mode,
68 CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
69 : fPath(path)
70 , fStrategy(strategy)
71 , fMode(mode)
72 , fDstColorType(dstColorType)
73 , fSampleSize(sampleSize)
74{}
75
76bool BRDSrc::veto(SinkFlags flags) const {
77 // No need to test to non-raster or indirect backends.
78 return flags.type != SinkFlags::kRaster
79 || flags.approach != SinkFlags::kDirect;
80}
81
82static SkBitmapRegionDecoderInterface* create_brd(Path path,
83 SkBitmapRegionDecoderInterface::Strategy strategy) {
84 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
85 if (!encoded) {
86 return NULL;
87 }
88 return SkBitmapRegionDecoderInterface::CreateBitmapRegionDecoder(new SkMemoryStream(encoded),
89 strategy);
90}
91
92Error BRDSrc::draw(SkCanvas* canvas) const {
93 SkColorType colorType = canvas->imageInfo().colorType();
94 if (kRGB_565_SkColorType == colorType &&
95 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
96 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
97 }
98 switch (fDstColorType) {
99 case CodecSrc::kGetFromCanvas_DstColorType:
100 break;
101 case CodecSrc::kIndex8_Always_DstColorType:
102 colorType = kIndex_8_SkColorType;
103 break;
104 case CodecSrc::kGrayscale_Always_DstColorType:
105 colorType = kGray_8_SkColorType;
106 break;
107 }
108
109 SkAutoTDelete<SkBitmapRegionDecoderInterface> brd(create_brd(fPath, fStrategy));
110 if (nullptr == brd.get()) {
111 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
112 }
113
114 const uint32_t width = brd->width();
115 const uint32_t height = brd->height();
116 // Visually inspecting very small output images is not necessary.
117 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
118 return Error::Nonfatal("Scaling very small images is uninteresting.");
119 }
120 switch (fMode) {
121 case kFullImage_Mode: {
122 SkAutoTDelete<SkBitmap> bitmap(brd->decodeRegion(0, 0, width, height, fSampleSize,
123 colorType));
124 if (nullptr == bitmap.get() || colorType != bitmap->colorType()) {
125 return Error::Nonfatal("Cannot convert to color type.\n");
126 }
127 canvas->drawBitmap(*bitmap, 0, 0);
128 return "";
129 }
130 case kDivisor_Mode: {
131 const uint32_t divisor = 2;
132 if (width < divisor || height < divisor) {
133 return Error::Nonfatal("Divisor is larger than image dimension.\n");
134 }
135
136 // Use a border to test subsets that extend outside the image.
137 // We will not allow the border to be larger than the image dimensions. Allowing
138 // these large borders causes off by one errors that indicate a problem with the
139 // test suite, not a problem with the implementation.
140 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
141 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
142 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
143
144 // We may need to clear the canvas to avoid uninitialized memory.
145 // Assume we are scaling a 780x780 image with sampleSize = 8.
146 // The output image should be 97x97.
147 // Each subset will be 390x390.
148 // Each scaled subset be 48x48.
149 // Four scaled subsets will only fill a 96x96 image.
150 // The bottom row and last column will not be touched.
151 // This is an unfortunate result of our rounding rules when scaling.
152 // Maybe we need to consider testing scaled subsets without trying to
153 // combine them to match the full scaled image? Or maybe this is the
154 // best we can do?
155 canvas->clear(0);
156
157 for (uint32_t x = 0; x < divisor; x++) {
158 for (uint32_t y = 0; y < divisor; y++) {
159 // Calculate the subset dimensions
160 uint32_t subsetWidth = width / divisor;
161 uint32_t subsetHeight = height / divisor;
162 const int left = x * subsetWidth;
163 const int top = y * subsetHeight;
164
165 // Increase the size of the last subset in each row or column, when the
166 // divisor does not divide evenly into the image dimensions
167 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
168 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
169
170 // Increase the size of the subset in order to have a border on each side
171 const int decodeLeft = left - unscaledBorder;
172 const int decodeTop = top - unscaledBorder;
173 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
174 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
175 SkAutoTDelete<SkBitmap> bitmap(brd->decodeRegion(decodeLeft,
176 decodeTop, decodeWidth, decodeHeight, fSampleSize, colorType));
177 if (nullptr == bitmap.get() || colorType != bitmap->colorType()) {
178 return Error::Nonfatal("Cannot convert to color type.\n");
179 }
180
181 canvas->drawBitmapRect(*bitmap,
182 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
183 (SkScalar) (subsetWidth / fSampleSize),
184 (SkScalar) (subsetHeight / fSampleSize)),
185 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
186 (SkScalar) (top / fSampleSize),
187 (SkScalar) (subsetWidth / fSampleSize),
188 (SkScalar) (subsetHeight / fSampleSize)),
189 nullptr);
190 }
191 }
192 return "";
193 }
194 default:
195 SkASSERT(false);
196 return "Error: Should not be reached.\n";
197 }
198}
199
200SkISize BRDSrc::size() const {
201 SkAutoTDelete<SkBitmapRegionDecoderInterface> brd(create_brd(fPath, fStrategy));
202 if (brd) {
203 return SkISize::Make(SkTMax(1, brd->width() / (int) fSampleSize),
204 SkTMax(1, brd->height() / (int) fSampleSize));
205 }
206 return SkISize::Make(0, 0);
207}
208
209static SkString get_scaled_name(const Path& path, float scale) {
210 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
211}
212
213Name BRDSrc::name() const {
214 // We will replicate the names used by CodecSrc so that images can
215 // be compared in Gold.
216 if (1 == fSampleSize) {
217 return SkOSPath::Basename(fPath.c_str());
218 }
219 return get_scaled_name(fPath, BRDSrc::GetScale(fSampleSize));
220}
221
222/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
223
msarett0a242972015-06-11 14:27:27 -0700224CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -0700225 : fPath(path)
226 , fMode(mode)
227 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -0700228 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -0700229{}
mtklein748ca3b2015-01-15 10:56:12 -0800230
mtklein99cab4e2015-07-31 06:43:04 -0700231bool CodecSrc::veto(SinkFlags flags) const {
232 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700233 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
234 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -0700235 return flags.type != SinkFlags::kRaster
236 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700237}
scroggo9b77ddd2015-03-19 06:03:39 -0700238
msarett5406d6f2015-08-31 06:55:13 -0700239SkScanlineDecoder* start_scanline_decoder(SkData* encoded, const SkImageInfo& info,
240 SkPMColor* colorPtr, int* colorCountPtr) {
241 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(SkScanlineDecoder::NewFromData(encoded));
242 if (nullptr == scanlineDecoder) {
243 return nullptr;
244 }
msarett5406d6f2015-08-31 06:55:13 -0700245 if (SkCodec::kSuccess != scanlineDecoder->start(info, NULL, colorPtr, colorCountPtr)) {
246 return nullptr;
247 }
248 return scanlineDecoder.detach();
249}
250
mtkleine0effd62015-07-29 06:37:28 -0700251Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800252 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800253 if (!encoded) {
254 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
255 }
msarett9e707a02015-09-01 14:57:57 -0700256 SkAutoTDelete<SkCodec> codec(NULL);
257 if (kScaledCodec_Mode == fMode) {
258 codec.reset(SkScaledCodec::NewFromData(encoded));
259 // TODO (msarett): This should fall through to a fatal error once we support scaled
260 // codecs for all image types.
halcanary96fcdcc2015-08-27 07:41:13 -0700261 if (nullptr == codec.get()) {
msarett9e707a02015-09-01 14:57:57 -0700262 return Error::Nonfatal(SkStringPrintf("Couldn't create scaled codec for %s.",
263 fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700264 }
msarett9e707a02015-09-01 14:57:57 -0700265 } else {
266 codec.reset(SkCodec::NewFromData(encoded));
267 }
268 if (nullptr == codec.get()) {
269 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700270 }
271
msarett438b2ad2015-04-09 12:43:10 -0700272 // Choose the color type to decode to
273 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -0700274 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -0700275 switch (fDstColorType) {
276 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700277 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
278 if (kRGB_565_SkColorType == canvasColorType) {
279 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
280 }
281 break;
msarett438b2ad2015-04-09 12:43:10 -0700282 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700283 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700284 if (kRGB_565_SkColorType == canvasColorType) {
285 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
286 }
287 break;
288 default:
289 decodeInfo = decodeInfo.makeColorType(canvasColorType);
290 break;
291 }
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
318 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700319 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700320 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
321 }
322
323 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700324 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700325 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
326 decodeInfo.width(), decodeInfo.height());
327 }
328
scroggo9c59ebc2015-03-25 13:48:49 -0700329 switch (fMode) {
msarett9e707a02015-09-01 14:57:57 -0700330 case kScaledCodec_Mode:
331 case kCodec_Mode: {
halcanary96fcdcc2015-08-27 07:41:13 -0700332 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700333 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700334 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700335 // We consider incomplete to be valid, since we should still decode what is
336 // available.
scroggoeb602a52015-07-09 08:16:03 -0700337 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700338 break;
scroggoeb602a52015-07-09 08:16:03 -0700339 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700340 return Error::Nonfatal("Incompatible colortype conversion");
341 default:
342 // Everything else is considered a failure.
343 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
344 }
emmaleer97002062015-05-27 12:36:10 -0700345 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700346 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700347 }
scroggo9c59ebc2015-03-25 13:48:49 -0700348 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700349 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
msarett5406d6f2015-08-31 06:55:13 -0700350 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
351 if (nullptr == scanlineDecoder) {
msarett9e707a02015-09-01 14:57:57 -0700352 return Error::Nonfatal("Could not start scanline decoder");
scroggo9c59ebc2015-03-25 13:48:49 -0700353 }
scroggo1c005e42015-08-04 09:24:45 -0700354
msarett10522ff2015-09-07 08:54:01 -0700355 SkCodec::Result result = SkCodec::kUnimplemented;
356 switch (scanlineDecoder->getScanlineOrder()) {
357 case SkScanlineDecoder::kTopDown_SkScanlineOrder:
358 case SkScanlineDecoder::kBottomUp_SkScanlineOrder:
359 case SkScanlineDecoder::kNone_SkScanlineOrder:
360 result = scanlineDecoder->getScanlines(bitmap.getAddr(0, 0),
361 decodeInfo.height(), bitmap.rowBytes());
362 break;
363 case SkScanlineDecoder::kOutOfOrder_SkScanlineOrder: {
364 for (int y = 0; y < decodeInfo.height(); y++) {
365 int dstY = scanlineDecoder->getY();
366 void* dstPtr = bitmap.getAddr(0, dstY);
367 result = scanlineDecoder->getScanlines(dstPtr, 1, bitmap.rowBytes());
368 if (SkCodec::kSuccess != result && SkCodec::kIncompleteInput != result) {
369 return SkStringPrintf("%s failed with error message %d",
370 fPath.c_str(), (int) result);
371 }
372 }
373 break;
374 }
375 }
376
emmaleer0a4c3cb2015-06-22 10:40:21 -0700377 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700378 case SkCodec::kSuccess:
379 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700380 break;
381 default:
382 return SkStringPrintf("%s failed with error message %d",
383 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700384 }
emmaleer97002062015-05-27 12:36:10 -0700385 canvas->drawBitmap(bitmap, 0, 0);
386 break;
387 }
388 case kScanline_Subset_Mode: {
389 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
390 const int divisor = 2;
391 const int w = decodeInfo.width();
392 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700393 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700394 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
395 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700396 }
397 const int subsetWidth = w/divisor;
398 const int subsetHeight = h/divisor;
399 // One of our subsets will be larger to contain any pixels that do not divide evenly.
400 const int extraX = w % divisor;
401 const int extraY = h % divisor;
402 /*
403 * if w or h are not evenly divided by divisor need to adjust width and height of end
404 * subsets to cover entire image.
405 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
406 * and height of end subsets.
407 * subsetBm is extracted from largestSubsetBm.
408 * subsetBm's size is determined based on the current subset and may be larger for end
409 * subsets.
410 */
msarett0a242972015-06-11 14:27:27 -0700411 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700412 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
413 SkBitmap largestSubsetBm;
msarett9e707a02015-09-01 14:57:57 -0700414 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr,
415 colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700416 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
417 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
418 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700419 const size_t rowBytes = decodeInfo.minRowBytes();
halcanary385fe4d2015-08-26 13:07:48 -0700420 char* buffer = new char[largestSubsetDecodeInfo.height() * rowBytes];
emmaleer0a4c3cb2015-06-22 10:40:21 -0700421 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700422 for (int col = 0; col < divisor; col++) {
423 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
424 const int currentSubsetWidth = (col + 1 == divisor) ?
425 subsetWidth + extraX : subsetWidth;
426 const int x = col * subsetWidth;
427 for (int row = 0; row < divisor; row++) {
428 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
429 const int currentSubsetHeight = (row + 1 == divisor) ?
430 subsetHeight + extraY : subsetHeight;
431 const int y = row * subsetHeight;
432 //create scanline decoder for each subset
msarett9e707a02015-09-01 14:57:57 -0700433 SkAutoTDelete<SkScanlineDecoder> decoder(start_scanline_decoder(encoded.get(),
434 decodeInfo, colorPtr, colorCountPtr));
435 // TODO (msarett): Support this mode for all scanline orderings.
436 if (nullptr == decoder || SkScanlineDecoder::kTopDown_SkScanlineOrder !=
437 decoder->getScanlineOrder()) {
emmaleer97002062015-05-27 12:36:10 -0700438 if (x == 0 && y == 0) {
439 //first try, image may not be compatible
msarett5406d6f2015-08-31 06:55:13 -0700440 return Error::Nonfatal("Could not start top-down scanline decoder");
emmaleer97002062015-05-27 12:36:10 -0700441 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700442 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700443 }
444 }
445 //skip to first line of subset
msarett9e707a02015-09-01 14:57:57 -0700446 const SkCodec::Result skipResult = decoder->skipScanlines(y);
emmaleer97002062015-05-27 12:36:10 -0700447 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700448 case SkCodec::kSuccess:
449 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700450 break;
451 default:
452 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
453 "with error message %d", fPath.c_str(), y, (int) skipResult);
454 }
455 //create and set size of subsetBm
456 SkBitmap subsetBm;
457 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
458 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
459 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
460 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700461 const SkCodec::Result subsetResult =
msarett9e707a02015-09-01 14:57:57 -0700462 decoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700463 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700464 case SkCodec::kSuccess:
465 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700466 break;
467 default:
mtkleind2baa902015-07-07 09:43:28 -0700468 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700469 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700470 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700471 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700472 /*
473 * we copy all the lines at once becuase when calling getScanlines for
474 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700475 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
476 * decode the entire image height times, which is very slow
477 * it is aknowledged that copying each line as you read it in a loop
478 * may be faster for other types of images. Since this is a correctness test
479 * that's okay.
480 */
mtkleind2baa902015-07-07 09:43:28 -0700481 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700482 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700483 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700484 currentSubsetWidth*bpp);
485 bufferRow += rowBytes;
486 }
mtkleind2baa902015-07-07 09:43:28 -0700487
scroggo4358f132015-07-30 11:33:04 -0700488 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700489 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
490 }
491 }
scroggo9c59ebc2015-03-25 13:48:49 -0700492 break;
493 }
msarett0a242972015-06-11 14:27:27 -0700494 case kStripe_Mode: {
495 const int height = decodeInfo.height();
496 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
497 // does not align with image blocks.
498 const int stripeHeight = 37;
499 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
500
501 // Decode odd stripes
msarett5406d6f2015-08-31 06:55:13 -0700502 SkAutoTDelete<SkScanlineDecoder> decoder(
503 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
msarett9e707a02015-09-01 14:57:57 -0700504 if (nullptr == decoder ||
505 SkScanlineDecoder::kTopDown_SkScanlineOrder != decoder->getScanlineOrder()) {
506 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
507 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
508 // to run this test for image types that do not have this scanline ordering.
msarett5406d6f2015-08-31 06:55:13 -0700509 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700510 }
511 for (int i = 0; i < numStripes; i += 2) {
512 // Skip a stripe
513 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700514 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700515 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700516 case SkCodec::kSuccess:
517 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700518 break;
519 default:
520 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
521 }
522
523 // Read a stripe
524 const int startY = (i + 1) * stripeHeight;
525 const int linesToRead = SkTMin(stripeHeight, height - startY);
526 if (linesToRead > 0) {
527 result = decoder->getScanlines(bitmap.getAddr(0, startY),
528 linesToRead, bitmap.rowBytes());
529 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700530 case SkCodec::kSuccess:
531 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700532 break;
533 default:
534 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
535 }
536 }
537 }
538
539 // Decode even stripes
halcanary96fcdcc2015-08-27 07:41:13 -0700540 const SkCodec::Result startResult = decoder->start(decodeInfo, nullptr, colorPtr,
scroggo1c005e42015-08-04 09:24:45 -0700541 colorCountPtr);
542 if (SkCodec::kSuccess != startResult) {
543 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700544 }
545 for (int i = 0; i < numStripes; i += 2) {
546 // Read a stripe
547 const int startY = i * stripeHeight;
548 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700549 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700550 linesToRead, bitmap.rowBytes());
551 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700552 case SkCodec::kSuccess:
553 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700554 break;
555 default:
556 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
557 }
558
559 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700560 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
561 if (linesToSkip > 0) {
562 result = decoder->skipScanlines(linesToSkip);
563 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700564 case SkCodec::kSuccess:
565 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700566 break;
567 default:
568 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
569 }
msarett0a242972015-06-11 14:27:27 -0700570 }
571 }
572 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700573 break;
msarett0a242972015-06-11 14:27:27 -0700574 }
scroggob636b452015-07-22 07:16:20 -0700575 case kSubset_Mode: {
576 // Arbitrarily choose a divisor.
577 int divisor = 2;
578 // Total width/height of the image.
579 const int W = codec->getInfo().width();
580 const int H = codec->getInfo().height();
581 if (divisor > W || divisor > H) {
582 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
583 "for %s with dimensions (%d x %d)", divisor,
584 fPath.c_str(), W, H));
585 }
586 // subset dimensions
587 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
588 const int w = SkAlign2(W / divisor);
589 const int h = SkAlign2(H / divisor);
590 SkIRect subset;
591 SkCodec::Options opts;
592 opts.fSubset = &subset;
593 SkBitmap subsetBm;
594 // We will reuse pixel memory from bitmap.
595 void* pixels = bitmap.getPixels();
596 // Keep track of left and top (for drawing subsetBm into canvas). We could use
597 // fScale * x and fScale * y, but we want integers such that the next subset will start
598 // where the last one ended. So we'll add decodeInfo.width() and height().
599 int left = 0;
600 for (int x = 0; x < W; x += w) {
601 int top = 0;
602 for (int y = 0; y < H; y+= h) {
603 // Do not make the subset go off the edge of the image.
604 const int preScaleW = SkTMin(w, W - x);
605 const int preScaleH = SkTMin(h, H - y);
606 subset.setXYWH(x, y, preScaleW, preScaleH);
607 // And scale
608 // FIXME: Should we have a version of getScaledDimensions that takes a subset
609 // into account?
610 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
611 SkScalarRoundToInt(preScaleH * fScale));
612 size_t rowBytes = decodeInfo.minRowBytes();
613 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700614 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700615 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
616 }
617 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
618 &opts, colorPtr, colorCountPtr);
619 switch (result) {
620 case SkCodec::kSuccess:
621 case SkCodec::kIncompleteInput:
622 break;
623 case SkCodec::kInvalidConversion:
624 if (0 == (x|y)) {
625 // First subset is okay to return unimplemented.
626 return Error::Nonfatal("Incompatible colortype conversion");
627 }
628 // If the first subset succeeded, a later one should not fail.
629 // fall through to failure
630 case SkCodec::kUnimplemented:
631 if (0 == (x|y)) {
632 // First subset is okay to return unimplemented.
633 return Error::Nonfatal("subset codec not supported");
634 }
635 // If the first subset succeeded, why would a later one fail?
636 // fall through to failure
637 default:
638 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
639 "from %s with dimensions (%d x %d)\t error %d",
640 x, y, decodeInfo.width(), decodeInfo.height(),
641 fPath.c_str(), W, H, result);
642 }
643 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
644 // translate by the scaled height.
645 top += decodeInfo.height();
646 }
647 // translate by the scaled width.
648 left += decodeInfo.width();
649 }
650 return "";
651 }
scroggo9b77ddd2015-03-19 06:03:39 -0700652 }
scroggo9c59ebc2015-03-25 13:48:49 -0700653 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700654}
655
656SkISize CodecSrc::size() const {
657 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700658 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700659 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700660 // scaledCodec not supported, try regular codec
661 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700662 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700663 return SkISize::Make(0, 0);
664 }
msarett9bde9182015-03-25 05:27:48 -0700665 }
emmaleer8f4ba762015-08-14 07:44:46 -0700666 SkISize size = codec->getScaledDimensions(fScale);
667 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700668}
669
670Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700671 if (1.0f == fScale) {
672 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700673 }
msaretta5783ae2015-09-08 15:35:32 -0700674 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700675}
676
677/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
678
679ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
680
mtklein99cab4e2015-07-31 06:43:04 -0700681bool ImageSrc::veto(SinkFlags flags) const {
682 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700683 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700684 return flags.type != SinkFlags::kRaster
685 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700686}
scroggo9b77ddd2015-03-19 06:03:39 -0700687
mtkleine0effd62015-07-29 06:37:28 -0700688Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700689 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
690 if (!encoded) {
691 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
692 }
mtkleine0effd62015-07-29 06:37:28 -0700693 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800694 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800695 // Decode the full image.
696 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700697 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
698 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
699 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
700 }
701 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
702 // Do not draw a bitmap with alpha to a destination without alpha.
703 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800704 }
halcanary96fcdcc2015-08-27 07:41:13 -0700705 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800706 canvas->drawBitmap(bitmap, 0,0);
707 return "";
708 }
mtkleinedc93bc2015-01-30 13:22:23 -0800709 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800710 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
711 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800712 if (!decoder) {
713 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
714 }
scroggoa1193e42015-01-21 12:09:53 -0800715 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800716 int w,h;
msarett70542572015-06-19 07:44:05 -0700717 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800718 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800719 }
mtkleinedc93bc2015-01-30 13:22:23 -0800720
721 // Divide the image into subsets that cover the entire image.
722 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700723 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
724 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800725 }
726 const int subsetWidth = w / fDivisor,
727 subsetHeight = h / fDivisor;
728 for (int y = 0; y < h; y += subsetHeight) {
729 for (int x = 0; x < w; x += subsetWidth) {
730 SkBitmap subset;
731 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
732 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
733 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
734 x, y, x+subsetWidth, y+subsetHeight);
735 }
scroggo56e25dd2015-03-05 11:46:40 -0800736 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
737 // Do not draw a bitmap with alpha to a destination without alpha.
738 // This is not an error, but there is nothing interesting to show.
739
740 // This should only happen on the first iteration through the loop.
741 SkASSERT(0 == x && 0 == y);
742
743 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
744 }
mtkleinedc93bc2015-01-30 13:22:23 -0800745 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800746 }
mtklein748ca3b2015-01-15 10:56:12 -0800747 }
748 return "";
749}
750
751SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800752 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700753 SkBitmap bitmap;
754 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
755 encoded->size(),
756 &bitmap,
757 kUnknown_SkColorType,
758 SkImageDecoder::kDecodeBounds_Mode)) {
759 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800760 }
scroggo9b77ddd2015-03-19 06:03:39 -0700761 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800762}
763
mtklein9264a952015-01-20 10:11:53 -0800764Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800765 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800766}
mtklein748ca3b2015-01-15 10:56:12 -0800767
768/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
769
mtkleinf4ba3212015-01-28 15:32:24 -0800770static const SkRect kSKPViewport = {0,0, 1000,1000};
771
mtklein8d17a132015-01-30 11:42:31 -0800772SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800773
774Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800775 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800776 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800777 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
778 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700779 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800780 if (!pic) {
781 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
782 }
halcanary96fcdcc2015-08-27 07:41:13 -0700783 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700784
mtkleinf4ba3212015-01-28 15:32:24 -0800785 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800786 canvas->drawPicture(pic);
787 return "";
788}
789
790SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700791 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
792 if (!stream) {
793 return SkISize::Make(0,0);
794 }
795 SkPictInfo info;
796 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
797 return SkISize::Make(0,0);
798 }
799 SkRect viewport = kSKPViewport;
800 if (!viewport.intersect(info.fCullRect)) {
801 return SkISize::Make(0,0);
802 }
803 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800804}
805
806Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
807
808/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
809
mtkleinad66f9b2015-02-13 15:11:10 -0800810Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
811 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
812 return src.draw(canvas);
813}
814
815/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
816
mtkleinb9eb4ac2015-02-02 18:26:03 -0800817DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
818
mtklein82d28432015-01-15 12:46:02 -0800819GPUSink::GPUSink(GrContextFactory::GLContextType ct,
820 GrGLStandard api,
821 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700822 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800823 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800824 : fContextType(ct)
825 , fGpuAPI(api)
826 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700827 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800828 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800829
830int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800831 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800832}
833
joshualitt5f5a8d72015-02-25 14:09:45 -0800834void PreAbandonGpuContextErrorHandler(SkError, void*) {}
835
mtkleinb9eb4ac2015-02-02 18:26:03 -0800836Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700837 GrContextOptions options;
838 src.modifyGrContextOptions(&options);
839
840 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800841 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800842 const SkImageInfo info =
843 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
844 SkAutoTUnref<SkSurface> surface(
bsalomonafcd7cd2015-08-31 12:39:41 -0700845 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800846 if (!surface) {
847 return "Could not create a surface.";
848 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800849 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700850 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800851 factory.abandonContexts();
852 }
mtklein748ca3b2015-01-15 10:56:12 -0800853 SkCanvas* canvas = surface->getCanvas();
854 Error err = src.draw(canvas);
855 if (!err.isEmpty()) {
856 return err;
857 }
858 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800859 if (FLAGS_gpuStats) {
860 canvas->getGrContext()->dumpCacheStats(log);
861 canvas->getGrContext()->dumpGpuStats(log);
862 }
mtklein748ca3b2015-01-15 10:56:12 -0800863 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800864 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800865 if (FLAGS_abandonGpuContext) {
866 factory.abandonContexts();
867 }
mtklein748ca3b2015-01-15 10:56:12 -0800868 return "";
869}
870
871/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
872
halcanary47ef4d52015-03-03 09:13:09 -0800873static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
874 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
875 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800876 int width = src.size().width(),
877 height = src.size().height();
878
halcanary7e798182015-04-14 14:06:18 -0700879 if (FLAGS_multiPage) {
880 const int kLetterWidth = 612, // 8.5 * 72
881 kLetterHeight = 792; // 11 * 72
882 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
883 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800884
halcanary7e798182015-04-14 14:06:18 -0700885 int xPages = ((width - 1) / kLetterWidth) + 1;
886 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800887
halcanary7e798182015-04-14 14:06:18 -0700888 for (int y = 0; y < yPages; ++y) {
889 for (int x = 0; x < xPages; ++x) {
890 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
891 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
892 SkCanvas* canvas =
893 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
894 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700895 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700896 }
897 canvas->clipRect(letter);
898 canvas->translate(-letter.width() * x, -letter.height() * y);
899 Error err = src.draw(canvas);
900 if (!err.isEmpty()) {
901 return err;
902 }
903 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700904 }
halcanaryfd4a9932015-01-28 11:45:58 -0800905 }
halcanary7e798182015-04-14 14:06:18 -0700906 } else {
907 SkCanvas* canvas =
908 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
909 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700910 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700911 }
912 Error err = src.draw(canvas);
913 if (!err.isEmpty()) {
914 return err;
915 }
916 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800917 }
halcanary7e798182015-04-14 14:06:18 -0700918 if (!doc->close()) {
919 return "SkDocument::close() returned false";
920 }
halcanaryfd4a9932015-01-28 11:45:58 -0800921 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800922 return "";
923}
924
halcanary47ef4d52015-03-03 09:13:09 -0800925PDFSink::PDFSink() {}
926
927Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
928 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
929 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700930 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800931 }
932 return draw_skdocument(src, doc.get(), dst);
933}
934
935/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
936
937XPSSink::XPSSink() {}
938
939Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
940 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
941 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700942 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800943 }
944 return draw_skdocument(src, doc.get(), dst);
945}
mtklein748ca3b2015-01-15 10:56:12 -0800946/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
947
mtklein9c3f17d2015-01-28 11:35:18 -0800948SKPSink::SKPSink() {}
949
mtkleinb9eb4ac2015-02-02 18:26:03 -0800950Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800951 SkSize size;
952 size = src.size();
953 SkPictureRecorder recorder;
954 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
955 if (!err.isEmpty()) {
956 return err;
957 }
958 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
959 pic->serialize(dst);
960 return "";
961}
962
963/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
964
mtklein8a4527e2015-01-31 20:00:58 -0800965SVGSink::SVGSink() {}
966
mtkleinb9eb4ac2015-02-02 18:26:03 -0800967Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -0700968 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -0800969 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
970 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
971 xmlWriter));
972 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800973}
974
975/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
976
mtklein748ca3b2015-01-15 10:56:12 -0800977RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
978
mtkleinb9eb4ac2015-02-02 18:26:03 -0800979Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800980 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800981 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
982 SkAlphaType alphaType = kPremul_SkAlphaType;
983 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
984
985 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
986 dst->eraseColor(SK_ColorTRANSPARENT);
987 SkCanvas canvas(*dst);
988 return src.draw(&canvas);
989}
990
991/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
992
mtkleina16e69e2015-05-05 11:38:45 -0700993// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700994// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700995// Several examples below.
996
mtkleina16e69e2015-05-05 11:38:45 -0700997static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700998 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700999 class ProxySrc : public Src {
1000 public:
mtkleine44b5082015-05-07 10:53:34 -07001001 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001002 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
1003 Name name() const override { sk_throw(); return ""; } // Won't be called.
1004 SkISize size() const override { return fSize; }
1005 private:
mtkleine44b5082015-05-07 10:53:34 -07001006 SkISize fSize;
1007 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001008 };
1009 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
1010}
1011
1012/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1013
mtkleind603b222015-02-17 11:13:33 -08001014static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1015 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1016 matrix->mapRect(&bounds);
1017 matrix->postTranslate(-bounds.x(), -bounds.y());
1018 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1019}
1020
mtklein78829242015-05-06 07:54:07 -07001021ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001022
mtkleinb9eb4ac2015-02-02 18:26:03 -08001023Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001024 SkMatrix matrix = fMatrix;
1025 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
1026 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1027 canvas->concat(matrix);
1028 return src.draw(canvas);
1029 });
mtklein748ca3b2015-01-15 10:56:12 -08001030}
1031
mtkleind603b222015-02-17 11:13:33 -08001032// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1033// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -07001034ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001035
1036Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1037 Error err = fSink->draw(src, bitmap, stream, log);
1038 if (!err.isEmpty()) {
1039 return err;
1040 }
1041
1042 SkMatrix inverse;
1043 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1044 return "Cannot upright --matrix.";
1045 }
1046 SkMatrix upright = SkMatrix::I();
1047 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1048 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1049 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1050 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1051
1052 SkBitmap uprighted;
1053 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1054 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1055
1056 SkCanvas canvas(uprighted);
1057 canvas.concat(upright);
1058 SkPaint paint;
1059 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1060 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1061
1062 *bitmap = uprighted;
1063 bitmap->lockPixels();
1064 return "";
1065}
1066
mtklein748ca3b2015-01-15 10:56:12 -08001067/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1068
mtkleinb9eb4ac2015-02-02 18:26:03 -08001069Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001070 auto size = src.size();
1071 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1072 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
1073 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -07001074 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -07001075 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
1076 });
mtklein748ca3b2015-01-15 10:56:12 -08001077}
1078
1079/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -07001080
mtkleina16e69e2015-05-05 11:38:45 -07001081Error ViaSerialization::draw(
1082 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001083 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001084 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001085 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001086 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1087 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001088 if (!err.isEmpty()) {
1089 return err;
1090 }
1091 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1092
1093 // Serialize it and then deserialize it.
1094 SkDynamicMemoryWStream wStream;
1095 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001096 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -07001097 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -08001098
mtkleina16e69e2015-05-05 11:38:45 -07001099 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1100 canvas->drawPicture(deserialized);
1101 return "";
1102 });
mtklein748ca3b2015-01-15 10:56:12 -08001103}
1104
1105/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1106
1107ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -07001108 : Via(sink)
1109 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001110 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001111 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001112
mtkleinb9eb4ac2015-02-02 18:26:03 -08001113Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001114 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001115 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001116 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1117 SkIntToScalar(size.height()),
1118 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001119 if (!err.isEmpty()) {
1120 return err;
1121 }
mtkleinb7e8d692015-04-07 08:30:32 -07001122 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001123
mtkleina16e69e2015-05-05 11:38:45 -07001124 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
1125 const int xTiles = (size.width() + fW - 1) / fW,
1126 yTiles = (size.height() + fH - 1) / fH;
1127 SkMultiPictureDraw mpd(xTiles*yTiles);
1128 SkTDArray<SkSurface*> surfaces;
1129 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001130
mtkleina16e69e2015-05-05 11:38:45 -07001131 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1132 for (int j = 0; j < yTiles; j++) {
1133 for (int i = 0; i < xTiles; i++) {
1134 // This lets our ultimate Sink determine the best kind of surface.
1135 // E.g., if it's a GpuSink, the surfaces and images are textures.
1136 SkSurface* s = canvas->newSurface(info);
1137 if (!s) {
1138 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001139 }
mtkleina16e69e2015-05-05 11:38:45 -07001140 surfaces.push(s);
1141 SkCanvas* c = s->getCanvas();
1142 c->translate(SkIntToScalar(-i * fW),
1143 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1144 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001145 }
mtklein748ca3b2015-01-15 10:56:12 -08001146 }
mtkleina16e69e2015-05-05 11:38:45 -07001147 mpd.draw();
1148 for (int j = 0; j < yTiles; j++) {
1149 for (int i = 0; i < xTiles; i++) {
1150 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1151 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1152 }
1153 }
1154 surfaces.unrefAll();
1155 return "";
1156 });
mtklein748ca3b2015-01-15 10:56:12 -08001157}
1158
mtkleinb7e8d692015-04-07 08:30:32 -07001159/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1160
mtkleinb7e8d692015-04-07 08:30:32 -07001161// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1162// This tests that any shortcuts we may take while recording that second picture are legal.
1163Error ViaSecondPicture::draw(
1164 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001165 auto size = src.size();
1166 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1167 SkPictureRecorder recorder;
1168 SkAutoTUnref<SkPicture> pic;
1169 for (int i = 0; i < 2; i++) {
1170 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1171 SkIntToScalar(size.height())));
1172 if (!err.isEmpty()) {
1173 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001174 }
mtkleina16e69e2015-05-05 11:38:45 -07001175 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001176 }
mtkleina16e69e2015-05-05 11:38:45 -07001177 canvas->drawPicture(pic);
1178 return "";
1179 });
mtkleinb7e8d692015-04-07 08:30:32 -07001180}
1181
mtkleind31c13d2015-05-05 12:59:56 -07001182/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1183
mtklein6fbf4b32015-05-06 11:35:40 -07001184// Draw the Src twice. This can help exercise caching.
1185Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1186 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1187 for (int i = 0; i < 2; i++) {
1188 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1189 canvas->clear(SK_ColorTRANSPARENT);
1190 Error err = src.draw(canvas);
1191 if (err.isEmpty()) {
1192 return err;
1193 }
1194 }
1195 return "";
1196 });
1197}
1198
1199/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1200
mtkleind31c13d2015-05-05 12:59:56 -07001201// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1202// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1203// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1204struct DrawsAsSingletonPictures {
1205 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001206 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001207
1208 SK_CREATE_MEMBER_DETECTOR(paint);
1209
1210 template <typename T>
1211 void draw(const T& op, SkCanvas* canvas) {
1212 // We must pass SkMatrix::I() as our initial matrix.
1213 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1214 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001215 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1216 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001217 }
1218
1219 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1220 template <typename T>
1221 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1222 SkPictureRecorder rec;
1223 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1224 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1225 fCanvas->drawPicture(pic);
1226 }
1227
1228 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1229 // We cannot make subpictures out of these because they affect state. Draw them directly.
1230 template <typename T>
1231 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1232 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1233};
1234
mtkleind31c13d2015-05-05 12:59:56 -07001235// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1236// Then play back that macro picture into our wrapped sink.
1237Error ViaSingletonPictures::draw(
1238 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1239 auto size = src.size();
1240 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1241 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1242 SkRecord skr;
1243 SkRecorder recorder(&skr, size.width(), size.height());
1244 Error err = src.draw(&recorder);
1245 if (!err.isEmpty()) {
1246 return err;
1247 }
1248
1249 // Record our macro-picture, with each draw op as its own sub-picture.
1250 SkPictureRecorder macroRec;
1251 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1252 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001253
1254 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1255 const SkDrawableList empty;
1256
1257 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1258 macroCanvas,
1259 drawables ? *drawables : empty,
1260 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001261 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001262 skr.visit<void>(i, drawsAsSingletonPictures);
1263 }
1264 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1265
1266 canvas->drawPicture(macroPic);
1267 return "";
1268 });
1269}
1270
mtklein748ca3b2015-01-15 10:56:12 -08001271} // namespace DM