blob: d1d9be030ffffb584bc537d23184965332bd92dc [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"
reed06a22f62015-05-05 08:11:33 -070013#include "SkDeferredCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080014#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080015#include "SkError.h"
mtkleine44b5082015-05-07 10:53:34 -070016#include "SkFunction.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070017#include "SkImageGenerator.h"
mtklein748ca3b2015-01-15 10:56:12 -080018#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080019#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080020#include "SkOSFile.h"
mtkleinffa901a2015-03-16 10:38:07 -070021#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080022#include "SkPictureRecorder.h"
23#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070024#include "SkRecordDraw.h"
25#include "SkRecorder.h"
fmalita2aafe6f2015-02-06 12:51:10 -080026#include "SkSVGCanvas.h"
mtkleina16e69e2015-05-05 11:38:45 -070027#include "SkScanlineDecoder.h"
scroggoa1193e42015-01-21 12:09:53 -080028#include "SkStream.h"
fmalita2aafe6f2015-02-06 12:51:10 -080029#include "SkXMLWriter.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 {
44 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
45 canvas->concat(gm->getInitialTransform());
46 gm->draw(canvas);
47 return "";
48}
49
50SkISize GMSrc::size() const {
51 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
52 return gm->getISize();
53}
54
55Name GMSrc::name() const {
56 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
57 return gm->getName();
58}
59
bsalomon4ee6bd82015-05-27 13:23:23 -070060void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
61 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
62 gm->modifyGrContextOptions(options);
63}
64
mtklein748ca3b2015-01-15 10:56:12 -080065/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
66
msarett0a242972015-06-11 14:27:27 -070067CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -070068 : fPath(path)
69 , fMode(mode)
70 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -070071 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -070072{}
mtklein748ca3b2015-01-15 10:56:12 -080073
mtklein99cab4e2015-07-31 06:43:04 -070074bool CodecSrc::veto(SinkFlags flags) const {
75 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -070076 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
77 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -070078 return flags.type != SinkFlags::kRaster
79 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -070080}
scroggo9b77ddd2015-03-19 06:03:39 -070081
mtkleine0effd62015-07-29 06:37:28 -070082Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -080083 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080084 if (!encoded) {
85 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
86 }
scroggo9b77ddd2015-03-19 06:03:39 -070087 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett438b2ad2015-04-09 12:43:10 -070088 if (NULL == codec.get()) {
89 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -070090 }
91
msarett438b2ad2015-04-09 12:43:10 -070092 // Choose the color type to decode to
93 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -070094 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -070095 switch (fDstColorType) {
96 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -070097 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
98 if (kRGB_565_SkColorType == canvasColorType) {
99 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
100 }
101 break;
msarett438b2ad2015-04-09 12:43:10 -0700102 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700103 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700104 if (kRGB_565_SkColorType == canvasColorType) {
105 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
106 }
107 break;
108 default:
109 decodeInfo = decodeInfo.makeColorType(canvasColorType);
110 break;
111 }
112
msarett0a242972015-06-11 14:27:27 -0700113 // Try to scale the image if it is desired
114 SkISize size = codec->getScaledDimensions(fScale);
115 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
116 return Error::Nonfatal("Test without scaling is uninteresting.");
117 }
118 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
119
msarett438b2ad2015-04-09 12:43:10 -0700120 // Construct a color table for the decode if necessary
121 SkAutoTUnref<SkColorTable> colorTable(NULL);
122 SkPMColor* colorPtr = NULL;
123 int* colorCountPtr = NULL;
124 int maxColors = 256;
125 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
126 SkPMColor colors[256];
127 colorTable.reset(SkNEW_ARGS(SkColorTable, (colors, maxColors)));
128 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
129 colorCountPtr = &maxColors;
130 }
131
132 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700133 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700134 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
135 }
136
137 SkBitmap bitmap;
msarett438b2ad2015-04-09 12:43:10 -0700138 if (!bitmap.tryAllocPixels(decodeInfo, NULL, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700139 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
140 decodeInfo.width(), decodeInfo.height());
141 }
142
scroggo9c59ebc2015-03-25 13:48:49 -0700143 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700144 case kNormal_Mode: {
msarett438b2ad2015-04-09 12:43:10 -0700145 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), NULL,
146 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700147 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700148 // We consider incomplete to be valid, since we should still decode what is
149 // available.
scroggoeb602a52015-07-09 08:16:03 -0700150 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700151 break;
scroggoeb602a52015-07-09 08:16:03 -0700152 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700153 return Error::Nonfatal("Incompatible colortype conversion");
154 default:
155 // Everything else is considered a failure.
156 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
157 }
emmaleer97002062015-05-27 12:36:10 -0700158 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700159 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700160 }
scroggo9c59ebc2015-03-25 13:48:49 -0700161 case kScanline_Mode: {
scroggo9b2cdbf42015-07-10 12:07:02 -0700162 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(codec->getScanlineDecoder(
163 decodeInfo, NULL, colorPtr, colorCountPtr));
scroggo9c59ebc2015-03-25 13:48:49 -0700164 if (NULL == scanlineDecoder) {
165 return Error::Nonfatal("Cannot use scanline decoder for all images");
166 }
scroggoeb602a52015-07-09 08:16:03 -0700167 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700168 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
169 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700170 case SkCodec::kSuccess:
171 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700172 break;
173 default:
174 return SkStringPrintf("%s failed with error message %d",
175 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700176 }
emmaleer97002062015-05-27 12:36:10 -0700177 canvas->drawBitmap(bitmap, 0, 0);
178 break;
179 }
180 case kScanline_Subset_Mode: {
181 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
182 const int divisor = 2;
183 const int w = decodeInfo.width();
184 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700185 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700186 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
187 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700188 }
189 const int subsetWidth = w/divisor;
190 const int subsetHeight = h/divisor;
191 // One of our subsets will be larger to contain any pixels that do not divide evenly.
192 const int extraX = w % divisor;
193 const int extraY = h % divisor;
194 /*
195 * if w or h are not evenly divided by divisor need to adjust width and height of end
196 * subsets to cover entire image.
197 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
198 * and height of end subsets.
199 * subsetBm is extracted from largestSubsetBm.
200 * subsetBm's size is determined based on the current subset and may be larger for end
201 * subsets.
202 */
msarett0a242972015-06-11 14:27:27 -0700203 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700204 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
205 SkBitmap largestSubsetBm;
206 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, NULL, colorTable.get())) {
207 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
208 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
209 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700210 const size_t rowBytes = decodeInfo.minRowBytes();
211 char* buffer = SkNEW_ARRAY(char, largestSubsetDecodeInfo.height() * rowBytes);
212 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700213 for (int col = 0; col < divisor; col++) {
214 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
215 const int currentSubsetWidth = (col + 1 == divisor) ?
216 subsetWidth + extraX : subsetWidth;
217 const int x = col * subsetWidth;
218 for (int row = 0; row < divisor; row++) {
219 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
220 const int currentSubsetHeight = (row + 1 == divisor) ?
221 subsetHeight + extraY : subsetHeight;
222 const int y = row * subsetHeight;
223 //create scanline decoder for each subset
scroggo9b2cdbf42015-07-10 12:07:02 -0700224 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
225 codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
emmaleer97002062015-05-27 12:36:10 -0700226 if (NULL == subsetScanlineDecoder) {
227 if (x == 0 && y == 0) {
228 //first try, image may not be compatible
229 return Error::Nonfatal("Cannot use scanline decoder for all images");
230 } else {
231 return "Error scanline decoder is NULL";
232 }
233 }
234 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700235 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700236 subsetScanlineDecoder->skipScanlines(y);
237 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700238 case SkCodec::kSuccess:
239 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700240 break;
241 default:
242 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
243 "with error message %d", fPath.c_str(), y, (int) skipResult);
244 }
245 //create and set size of subsetBm
246 SkBitmap subsetBm;
247 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
248 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
249 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
250 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700251 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700252 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
253 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700254 case SkCodec::kSuccess:
255 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700256 break;
257 default:
mtkleind2baa902015-07-07 09:43:28 -0700258 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700259 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700260 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700261 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700262 /*
263 * we copy all the lines at once becuase when calling getScanlines for
264 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700265 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
266 * decode the entire image height times, which is very slow
267 * it is aknowledged that copying each line as you read it in a loop
268 * may be faster for other types of images. Since this is a correctness test
269 * that's okay.
270 */
mtkleind2baa902015-07-07 09:43:28 -0700271 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700272 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700273 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700274 currentSubsetWidth*bpp);
275 bufferRow += rowBytes;
276 }
mtkleind2baa902015-07-07 09:43:28 -0700277
scroggo4358f132015-07-30 11:33:04 -0700278 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700279 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
280 }
281 }
scroggo9c59ebc2015-03-25 13:48:49 -0700282 break;
283 }
msarett0a242972015-06-11 14:27:27 -0700284 case kStripe_Mode: {
285 const int height = decodeInfo.height();
286 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
287 // does not align with image blocks.
288 const int stripeHeight = 37;
289 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
290
291 // Decode odd stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700292 SkAutoTDelete<SkScanlineDecoder> decoder(
293 codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700294 if (NULL == decoder) {
295 return Error::Nonfatal("Cannot use scanline decoder for all images");
296 }
297 for (int i = 0; i < numStripes; i += 2) {
298 // Skip a stripe
299 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700300 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700301 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700302 case SkCodec::kSuccess:
303 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700304 break;
305 default:
306 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
307 }
308
309 // Read a stripe
310 const int startY = (i + 1) * stripeHeight;
311 const int linesToRead = SkTMin(stripeHeight, height - startY);
312 if (linesToRead > 0) {
313 result = decoder->getScanlines(bitmap.getAddr(0, startY),
314 linesToRead, bitmap.rowBytes());
315 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700316 case SkCodec::kSuccess:
317 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700318 break;
319 default:
320 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
321 }
322 }
323 }
324
325 // Decode even stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700326 decoder.reset(codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700327 if (NULL == decoder) {
328 return "Failed to create second scanline decoder.";
329 }
330 for (int i = 0; i < numStripes; i += 2) {
331 // Read a stripe
332 const int startY = i * stripeHeight;
333 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700334 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700335 linesToRead, bitmap.rowBytes());
336 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700337 case SkCodec::kSuccess:
338 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700339 break;
340 default:
341 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
342 }
343
344 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700345 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
346 if (linesToSkip > 0) {
347 result = decoder->skipScanlines(linesToSkip);
348 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700349 case SkCodec::kSuccess:
350 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700351 break;
352 default:
353 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
354 }
msarett0a242972015-06-11 14:27:27 -0700355 }
356 }
357 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700358 break;
msarett0a242972015-06-11 14:27:27 -0700359 }
scroggob636b452015-07-22 07:16:20 -0700360 case kSubset_Mode: {
361 // Arbitrarily choose a divisor.
362 int divisor = 2;
363 // Total width/height of the image.
364 const int W = codec->getInfo().width();
365 const int H = codec->getInfo().height();
366 if (divisor > W || divisor > H) {
367 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
368 "for %s with dimensions (%d x %d)", divisor,
369 fPath.c_str(), W, H));
370 }
371 // subset dimensions
372 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
373 const int w = SkAlign2(W / divisor);
374 const int h = SkAlign2(H / divisor);
375 SkIRect subset;
376 SkCodec::Options opts;
377 opts.fSubset = &subset;
378 SkBitmap subsetBm;
379 // We will reuse pixel memory from bitmap.
380 void* pixels = bitmap.getPixels();
381 // Keep track of left and top (for drawing subsetBm into canvas). We could use
382 // fScale * x and fScale * y, but we want integers such that the next subset will start
383 // where the last one ended. So we'll add decodeInfo.width() and height().
384 int left = 0;
385 for (int x = 0; x < W; x += w) {
386 int top = 0;
387 for (int y = 0; y < H; y+= h) {
388 // Do not make the subset go off the edge of the image.
389 const int preScaleW = SkTMin(w, W - x);
390 const int preScaleH = SkTMin(h, H - y);
391 subset.setXYWH(x, y, preScaleW, preScaleH);
392 // And scale
393 // FIXME: Should we have a version of getScaledDimensions that takes a subset
394 // into account?
395 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
396 SkScalarRoundToInt(preScaleH * fScale));
397 size_t rowBytes = decodeInfo.minRowBytes();
398 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
399 NULL, NULL)) {
400 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
401 }
402 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
403 &opts, colorPtr, colorCountPtr);
404 switch (result) {
405 case SkCodec::kSuccess:
406 case SkCodec::kIncompleteInput:
407 break;
408 case SkCodec::kInvalidConversion:
409 if (0 == (x|y)) {
410 // First subset is okay to return unimplemented.
411 return Error::Nonfatal("Incompatible colortype conversion");
412 }
413 // If the first subset succeeded, a later one should not fail.
414 // fall through to failure
415 case SkCodec::kUnimplemented:
416 if (0 == (x|y)) {
417 // First subset is okay to return unimplemented.
418 return Error::Nonfatal("subset codec not supported");
419 }
420 // If the first subset succeeded, why would a later one fail?
421 // fall through to failure
422 default:
423 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
424 "from %s with dimensions (%d x %d)\t error %d",
425 x, y, decodeInfo.width(), decodeInfo.height(),
426 fPath.c_str(), W, H, result);
427 }
428 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
429 // translate by the scaled height.
430 top += decodeInfo.height();
431 }
432 // translate by the scaled width.
433 left += decodeInfo.width();
434 }
435 return "";
436 }
scroggo9b77ddd2015-03-19 06:03:39 -0700437 }
scroggo9c59ebc2015-03-25 13:48:49 -0700438 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700439}
440
441SkISize CodecSrc::size() const {
442 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
443 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9bde9182015-03-25 05:27:48 -0700444 if (NULL != codec) {
msarett0a242972015-06-11 14:27:27 -0700445 SkISize size = codec->getScaledDimensions(fScale);
446 return size;
msarett9bde9182015-03-25 05:27:48 -0700447 } else {
448 return SkISize::Make(0, 0);
449 }
scroggo9b77ddd2015-03-19 06:03:39 -0700450}
451
452Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700453 if (1.0f == fScale) {
454 return SkOSPath::Basename(fPath.c_str());
455 } else {
456 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
457 }
scroggo9b77ddd2015-03-19 06:03:39 -0700458}
459
460/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
461
462ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
463
mtklein99cab4e2015-07-31 06:43:04 -0700464bool ImageSrc::veto(SinkFlags flags) const {
465 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700466 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700467 return flags.type != SinkFlags::kRaster
468 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700469}
scroggo9b77ddd2015-03-19 06:03:39 -0700470
mtkleine0effd62015-07-29 06:37:28 -0700471Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700472 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
473 if (!encoded) {
474 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
475 }
mtkleine0effd62015-07-29 06:37:28 -0700476 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800477 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800478 // Decode the full image.
479 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700480 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
481 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
482 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
483 }
484 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
485 // Do not draw a bitmap with alpha to a destination without alpha.
486 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800487 }
mtklein75d98fd2015-01-18 07:05:01 -0800488 encoded.reset((SkData*)NULL); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800489 canvas->drawBitmap(bitmap, 0,0);
490 return "";
491 }
mtkleinedc93bc2015-01-30 13:22:23 -0800492 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800493 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
494 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800495 if (!decoder) {
496 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
497 }
scroggoa1193e42015-01-21 12:09:53 -0800498 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800499 int w,h;
msarett70542572015-06-19 07:44:05 -0700500 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800501 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800502 }
mtkleinedc93bc2015-01-30 13:22:23 -0800503
504 // Divide the image into subsets that cover the entire image.
505 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700506 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
507 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800508 }
509 const int subsetWidth = w / fDivisor,
510 subsetHeight = h / fDivisor;
511 for (int y = 0; y < h; y += subsetHeight) {
512 for (int x = 0; x < w; x += subsetWidth) {
513 SkBitmap subset;
514 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
515 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
516 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
517 x, y, x+subsetWidth, y+subsetHeight);
518 }
scroggo56e25dd2015-03-05 11:46:40 -0800519 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
520 // Do not draw a bitmap with alpha to a destination without alpha.
521 // This is not an error, but there is nothing interesting to show.
522
523 // This should only happen on the first iteration through the loop.
524 SkASSERT(0 == x && 0 == y);
525
526 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
527 }
mtkleinedc93bc2015-01-30 13:22:23 -0800528 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800529 }
mtklein748ca3b2015-01-15 10:56:12 -0800530 }
531 return "";
532}
533
534SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800535 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700536 SkBitmap bitmap;
537 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
538 encoded->size(),
539 &bitmap,
540 kUnknown_SkColorType,
541 SkImageDecoder::kDecodeBounds_Mode)) {
542 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800543 }
scroggo9b77ddd2015-03-19 06:03:39 -0700544 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800545}
546
mtklein9264a952015-01-20 10:11:53 -0800547Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800548 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800549}
mtklein748ca3b2015-01-15 10:56:12 -0800550
551/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
552
mtkleinf4ba3212015-01-28 15:32:24 -0800553static const SkRect kSKPViewport = {0,0, 1000,1000};
554
mtklein8d17a132015-01-30 11:42:31 -0800555SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800556
557Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800558 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800559 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800560 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
561 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700562 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800563 if (!pic) {
564 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
565 }
566 stream.reset((SkStream*)NULL); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700567
mtkleinf4ba3212015-01-28 15:32:24 -0800568 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800569 canvas->drawPicture(pic);
570 return "";
571}
572
573SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700574 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
575 if (!stream) {
576 return SkISize::Make(0,0);
577 }
578 SkPictInfo info;
579 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
580 return SkISize::Make(0,0);
581 }
582 SkRect viewport = kSKPViewport;
583 if (!viewport.intersect(info.fCullRect)) {
584 return SkISize::Make(0,0);
585 }
586 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800587}
588
589Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
590
591/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
592
mtkleinad66f9b2015-02-13 15:11:10 -0800593Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
594 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
595 return src.draw(canvas);
596}
597
598/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
599
mtkleinb9eb4ac2015-02-02 18:26:03 -0800600DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
601
mtklein82d28432015-01-15 12:46:02 -0800602GPUSink::GPUSink(GrContextFactory::GLContextType ct,
603 GrGLStandard api,
604 int samples,
605 bool dfText,
606 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800607 : fContextType(ct)
608 , fGpuAPI(api)
609 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800610 , fUseDFText(dfText)
611 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800612
613int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800614 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800615}
616
joshualitt5f5a8d72015-02-25 14:09:45 -0800617void PreAbandonGpuContextErrorHandler(SkError, void*) {}
618
mtkleinb9eb4ac2015-02-02 18:26:03 -0800619Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700620 GrContextOptions options;
621 src.modifyGrContextOptions(&options);
622
623 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800624 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800625 const SkImageInfo info =
626 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
627 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800628 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800629 if (!surface) {
630 return "Could not create a surface.";
631 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800632 if (FLAGS_preAbandonGpuContext) {
633 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, NULL);
634 factory.abandonContexts();
635 }
mtklein748ca3b2015-01-15 10:56:12 -0800636 SkCanvas* canvas = surface->getCanvas();
637 Error err = src.draw(canvas);
638 if (!err.isEmpty()) {
639 return err;
640 }
641 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800642 if (FLAGS_gpuStats) {
643 canvas->getGrContext()->dumpCacheStats(log);
644 canvas->getGrContext()->dumpGpuStats(log);
645 }
mtklein748ca3b2015-01-15 10:56:12 -0800646 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800647 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800648 if (FLAGS_abandonGpuContext) {
649 factory.abandonContexts();
650 }
mtklein748ca3b2015-01-15 10:56:12 -0800651 return "";
652}
653
654/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
655
halcanary47ef4d52015-03-03 09:13:09 -0800656static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
657 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
658 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800659 int width = src.size().width(),
660 height = src.size().height();
661
halcanary7e798182015-04-14 14:06:18 -0700662 if (FLAGS_multiPage) {
663 const int kLetterWidth = 612, // 8.5 * 72
664 kLetterHeight = 792; // 11 * 72
665 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
666 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800667
halcanary7e798182015-04-14 14:06:18 -0700668 int xPages = ((width - 1) / kLetterWidth) + 1;
669 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800670
halcanary7e798182015-04-14 14:06:18 -0700671 for (int y = 0; y < yPages; ++y) {
672 for (int x = 0; x < xPages; ++x) {
673 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
674 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
675 SkCanvas* canvas =
676 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
677 if (!canvas) {
678 return "SkDocument::beginPage(w,h) returned NULL";
679 }
680 canvas->clipRect(letter);
681 canvas->translate(-letter.width() * x, -letter.height() * y);
682 Error err = src.draw(canvas);
683 if (!err.isEmpty()) {
684 return err;
685 }
686 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700687 }
halcanaryfd4a9932015-01-28 11:45:58 -0800688 }
halcanary7e798182015-04-14 14:06:18 -0700689 } else {
690 SkCanvas* canvas =
691 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
692 if (!canvas) {
693 return "SkDocument::beginPage(w,h) returned NULL";
694 }
695 Error err = src.draw(canvas);
696 if (!err.isEmpty()) {
697 return err;
698 }
699 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800700 }
halcanary7e798182015-04-14 14:06:18 -0700701 if (!doc->close()) {
702 return "SkDocument::close() returned false";
703 }
halcanaryfd4a9932015-01-28 11:45:58 -0800704 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800705 return "";
706}
707
halcanary47ef4d52015-03-03 09:13:09 -0800708PDFSink::PDFSink() {}
709
710Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
711 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
712 if (!doc) {
713 return "SkDocument::CreatePDF() returned NULL";
714 }
715 return draw_skdocument(src, doc.get(), dst);
716}
717
718/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
719
720XPSSink::XPSSink() {}
721
722Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
723 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
724 if (!doc) {
725 return "SkDocument::CreateXPS() returned NULL";
726 }
727 return draw_skdocument(src, doc.get(), dst);
728}
mtklein748ca3b2015-01-15 10:56:12 -0800729/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
730
mtklein9c3f17d2015-01-28 11:35:18 -0800731SKPSink::SKPSink() {}
732
mtkleinb9eb4ac2015-02-02 18:26:03 -0800733Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800734 SkSize size;
735 size = src.size();
736 SkPictureRecorder recorder;
737 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
738 if (!err.isEmpty()) {
739 return err;
740 }
741 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
742 pic->serialize(dst);
743 return "";
744}
745
746/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
747
mtklein8a4527e2015-01-31 20:00:58 -0800748SVGSink::SVGSink() {}
749
mtkleinb9eb4ac2015-02-02 18:26:03 -0800750Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita2aafe6f2015-02-06 12:51:10 -0800751 SkAutoTDelete<SkXMLWriter> xmlWriter(SkNEW_ARGS(SkXMLStreamWriter, (dst)));
752 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
753 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
754 xmlWriter));
755 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800756}
757
758/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
759
mtklein748ca3b2015-01-15 10:56:12 -0800760RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
761
mtkleinb9eb4ac2015-02-02 18:26:03 -0800762Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800763 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800764 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
765 SkAlphaType alphaType = kPremul_SkAlphaType;
766 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
767
768 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
769 dst->eraseColor(SK_ColorTRANSPARENT);
770 SkCanvas canvas(*dst);
771 return src.draw(&canvas);
772}
773
774/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
775
mtkleina16e69e2015-05-05 11:38:45 -0700776// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700777// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700778// Several examples below.
779
mtkleina16e69e2015-05-05 11:38:45 -0700780static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700781 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700782 class ProxySrc : public Src {
783 public:
mtkleine44b5082015-05-07 10:53:34 -0700784 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700785 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
786 Name name() const override { sk_throw(); return ""; } // Won't be called.
787 SkISize size() const override { return fSize; }
788 private:
mtkleine44b5082015-05-07 10:53:34 -0700789 SkISize fSize;
790 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700791 };
792 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
793}
794
795/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
796
mtkleind603b222015-02-17 11:13:33 -0800797static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
798 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
799 matrix->mapRect(&bounds);
800 matrix->postTranslate(-bounds.x(), -bounds.y());
801 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
802}
803
mtklein78829242015-05-06 07:54:07 -0700804ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800805
mtkleinb9eb4ac2015-02-02 18:26:03 -0800806Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700807 SkMatrix matrix = fMatrix;
808 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
809 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
810 canvas->concat(matrix);
811 return src.draw(canvas);
812 });
mtklein748ca3b2015-01-15 10:56:12 -0800813}
814
mtkleind603b222015-02-17 11:13:33 -0800815// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
816// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700817ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800818
819Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
820 Error err = fSink->draw(src, bitmap, stream, log);
821 if (!err.isEmpty()) {
822 return err;
823 }
824
825 SkMatrix inverse;
826 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
827 return "Cannot upright --matrix.";
828 }
829 SkMatrix upright = SkMatrix::I();
830 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
831 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
832 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
833 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
834
835 SkBitmap uprighted;
836 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
837 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
838
839 SkCanvas canvas(uprighted);
840 canvas.concat(upright);
841 SkPaint paint;
842 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
843 canvas.drawBitmap(*bitmap, 0, 0, &paint);
844
845 *bitmap = uprighted;
846 bitmap->lockPixels();
847 return "";
848}
849
mtklein748ca3b2015-01-15 10:56:12 -0800850/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
851
mtkleinb9eb4ac2015-02-02 18:26:03 -0800852Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700853 auto size = src.size();
854 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
855 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
856 SkGPipeWriter pipe;
857 const uint32_t kFlags = 0; // We mirror SkDeferredCanvas, which doesn't use any flags.
858 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
859 });
mtklein748ca3b2015-01-15 10:56:12 -0800860}
861
862/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700863
reed06a22f62015-05-05 08:11:33 -0700864Error ViaDeferred::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700865 // We draw via a deferred canvas into a surface that's compatible with the original canvas,
866 // then snap that surface as an image and draw it into the original canvas.
867 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
868 SkAutoTUnref<SkSurface> surface(canvas->newSurface(canvas->imageInfo()));
869 if (!surface.get()) {
870 return "can't make surface for deferred canvas";
reed06a22f62015-05-05 08:11:33 -0700871 }
mtkleina16e69e2015-05-05 11:38:45 -0700872 SkAutoTDelete<SkDeferredCanvas> defcan(SkDeferredCanvas::Create(surface));
873 Error err = src.draw(defcan);
874 if (!err.isEmpty()) {
875 return err;
876 }
877 SkAutoTUnref<SkImage> image(defcan->newImageSnapshot());
878 if (!image) {
879 return "failed to create deferred image snapshot";
880 }
881 canvas->drawImage(image, 0, 0, NULL);
882 return "";
883 });
reed06a22f62015-05-05 08:11:33 -0700884}
mtkleina16e69e2015-05-05 11:38:45 -0700885
reed06a22f62015-05-05 08:11:33 -0700886/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -0800887
mtkleina16e69e2015-05-05 11:38:45 -0700888Error ViaSerialization::draw(
889 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800890 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700891 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800892 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700893 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
894 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800895 if (!err.isEmpty()) {
896 return err;
897 }
898 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
899
900 // Serialize it and then deserialize it.
901 SkDynamicMemoryWStream wStream;
902 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800903 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700904 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800905
mtkleina16e69e2015-05-05 11:38:45 -0700906 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
907 canvas->drawPicture(deserialized);
908 return "";
909 });
mtklein748ca3b2015-01-15 10:56:12 -0800910}
911
912/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
913
914ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700915 : Via(sink)
916 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800917 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700918 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800919
mtkleinb9eb4ac2015-02-02 18:26:03 -0800920Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700921 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800922 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700923 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
924 SkIntToScalar(size.height()),
925 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800926 if (!err.isEmpty()) {
927 return err;
928 }
mtkleinb7e8d692015-04-07 08:30:32 -0700929 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800930
mtkleina16e69e2015-05-05 11:38:45 -0700931 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
932 const int xTiles = (size.width() + fW - 1) / fW,
933 yTiles = (size.height() + fH - 1) / fH;
934 SkMultiPictureDraw mpd(xTiles*yTiles);
935 SkTDArray<SkSurface*> surfaces;
936 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800937
mtkleina16e69e2015-05-05 11:38:45 -0700938 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
939 for (int j = 0; j < yTiles; j++) {
940 for (int i = 0; i < xTiles; i++) {
941 // This lets our ultimate Sink determine the best kind of surface.
942 // E.g., if it's a GpuSink, the surfaces and images are textures.
943 SkSurface* s = canvas->newSurface(info);
944 if (!s) {
945 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800946 }
mtkleina16e69e2015-05-05 11:38:45 -0700947 surfaces.push(s);
948 SkCanvas* c = s->getCanvas();
949 c->translate(SkIntToScalar(-i * fW),
950 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
951 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800952 }
mtklein748ca3b2015-01-15 10:56:12 -0800953 }
mtkleina16e69e2015-05-05 11:38:45 -0700954 mpd.draw();
955 for (int j = 0; j < yTiles; j++) {
956 for (int i = 0; i < xTiles; i++) {
957 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
958 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
959 }
960 }
961 surfaces.unrefAll();
962 return "";
963 });
mtklein748ca3b2015-01-15 10:56:12 -0800964}
965
mtkleinb7e8d692015-04-07 08:30:32 -0700966/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
967
mtkleinb7e8d692015-04-07 08:30:32 -0700968// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
969// This tests that any shortcuts we may take while recording that second picture are legal.
970Error ViaSecondPicture::draw(
971 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700972 auto size = src.size();
973 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
974 SkPictureRecorder recorder;
975 SkAutoTUnref<SkPicture> pic;
976 for (int i = 0; i < 2; i++) {
977 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
978 SkIntToScalar(size.height())));
979 if (!err.isEmpty()) {
980 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700981 }
mtkleina16e69e2015-05-05 11:38:45 -0700982 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700983 }
mtkleina16e69e2015-05-05 11:38:45 -0700984 canvas->drawPicture(pic);
985 return "";
986 });
mtkleinb7e8d692015-04-07 08:30:32 -0700987}
988
mtkleind31c13d2015-05-05 12:59:56 -0700989/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
990
mtklein6fbf4b32015-05-06 11:35:40 -0700991// Draw the Src twice. This can help exercise caching.
992Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
993 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
994 for (int i = 0; i < 2; i++) {
995 SkAutoCanvasRestore acr(canvas, true/*save now*/);
996 canvas->clear(SK_ColorTRANSPARENT);
997 Error err = src.draw(canvas);
998 if (err.isEmpty()) {
999 return err;
1000 }
1001 }
1002 return "";
1003 });
1004}
1005
1006/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1007
mtkleind31c13d2015-05-05 12:59:56 -07001008// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1009// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1010// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1011struct DrawsAsSingletonPictures {
1012 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001013 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001014
1015 SK_CREATE_MEMBER_DETECTOR(paint);
1016
1017 template <typename T>
1018 void draw(const T& op, SkCanvas* canvas) {
1019 // We must pass SkMatrix::I() as our initial matrix.
1020 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1021 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001022 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1023 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001024 }
1025
1026 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1027 template <typename T>
1028 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1029 SkPictureRecorder rec;
1030 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1031 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1032 fCanvas->drawPicture(pic);
1033 }
1034
1035 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1036 // We cannot make subpictures out of these because they affect state. Draw them directly.
1037 template <typename T>
1038 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1039 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1040};
1041
mtkleind31c13d2015-05-05 12:59:56 -07001042// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1043// Then play back that macro picture into our wrapped sink.
1044Error ViaSingletonPictures::draw(
1045 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1046 auto size = src.size();
1047 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1048 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1049 SkRecord skr;
1050 SkRecorder recorder(&skr, size.width(), size.height());
1051 Error err = src.draw(&recorder);
1052 if (!err.isEmpty()) {
1053 return err;
1054 }
1055
1056 // Record our macro-picture, with each draw op as its own sub-picture.
1057 SkPictureRecorder macroRec;
1058 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1059 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001060
1061 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1062 const SkDrawableList empty;
1063
1064 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1065 macroCanvas,
1066 drawables ? *drawables : empty,
1067 };
mtkleind31c13d2015-05-05 12:59:56 -07001068 for (unsigned i = 0; i < skr.count(); i++) {
1069 skr.visit<void>(i, drawsAsSingletonPictures);
1070 }
1071 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1072
1073 canvas->drawPicture(macroPic);
1074 return "";
1075 });
1076}
1077
mtklein748ca3b2015-01-15 10:56:12 -08001078} // namespace DM