blob: fd1331366dd34b07761e57e5c5e91e13dc4cea9f [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
scroggo9b77ddd2015-03-19 06:03:39 -070074Error CodecSrc::draw(SkCanvas* canvas) const {
75 SkImageInfo canvasInfo;
76 if (NULL == canvas->peekPixels(&canvasInfo, NULL)) {
77 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
78 // let the GPU handle it.
79 return Error::Nonfatal("No need to test decoding to non-raster backend.");
80 }
81
mtklein75d98fd2015-01-18 07:05:01 -080082 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080083 if (!encoded) {
84 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
85 }
scroggo9b77ddd2015-03-19 06:03:39 -070086 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett438b2ad2015-04-09 12:43:10 -070087 if (NULL == codec.get()) {
88 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -070089 }
90
msarett438b2ad2015-04-09 12:43:10 -070091 // Choose the color type to decode to
92 SkImageInfo decodeInfo = codec->getInfo();
93 SkColorType canvasColorType = canvasInfo.colorType();
94 switch (fDstColorType) {
95 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -070096 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
97 if (kRGB_565_SkColorType == canvasColorType) {
98 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
99 }
100 break;
msarett438b2ad2015-04-09 12:43:10 -0700101 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700102 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700103 if (kRGB_565_SkColorType == canvasColorType) {
104 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
105 }
106 break;
107 default:
108 decodeInfo = decodeInfo.makeColorType(canvasColorType);
109 break;
110 }
111
msarett0a242972015-06-11 14:27:27 -0700112 // Try to scale the image if it is desired
113 SkISize size = codec->getScaledDimensions(fScale);
114 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
115 return Error::Nonfatal("Test without scaling is uninteresting.");
116 }
117 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
118
msarett438b2ad2015-04-09 12:43:10 -0700119 // Construct a color table for the decode if necessary
120 SkAutoTUnref<SkColorTable> colorTable(NULL);
121 SkPMColor* colorPtr = NULL;
122 int* colorCountPtr = NULL;
123 int maxColors = 256;
124 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
125 SkPMColor colors[256];
126 colorTable.reset(SkNEW_ARGS(SkColorTable, (colors, maxColors)));
127 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
128 colorCountPtr = &maxColors;
129 }
130
131 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700132 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700133 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
134 }
135
136 SkBitmap bitmap;
msarett438b2ad2015-04-09 12:43:10 -0700137 if (!bitmap.tryAllocPixels(decodeInfo, NULL, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700138 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
139 decodeInfo.width(), decodeInfo.height());
140 }
141
scroggo9c59ebc2015-03-25 13:48:49 -0700142 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700143 case kNormal_Mode: {
msarett438b2ad2015-04-09 12:43:10 -0700144 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), NULL,
145 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700146 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700147 // We consider incomplete to be valid, since we should still decode what is
148 // available.
scroggoeb602a52015-07-09 08:16:03 -0700149 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700150 break;
scroggoeb602a52015-07-09 08:16:03 -0700151 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700152 return Error::Nonfatal("Incompatible colortype conversion");
153 default:
154 // Everything else is considered a failure.
155 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
156 }
emmaleer97002062015-05-27 12:36:10 -0700157 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700158 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700159 }
scroggo9c59ebc2015-03-25 13:48:49 -0700160 case kScanline_Mode: {
scroggo9b2cdbf42015-07-10 12:07:02 -0700161 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(codec->getScanlineDecoder(
162 decodeInfo, NULL, colorPtr, colorCountPtr));
scroggo9c59ebc2015-03-25 13:48:49 -0700163 if (NULL == scanlineDecoder) {
164 return Error::Nonfatal("Cannot use scanline decoder for all images");
165 }
scroggoeb602a52015-07-09 08:16:03 -0700166 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700167 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
168 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700169 case SkCodec::kSuccess:
170 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700171 break;
172 default:
173 return SkStringPrintf("%s failed with error message %d",
174 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700175 }
emmaleer97002062015-05-27 12:36:10 -0700176 canvas->drawBitmap(bitmap, 0, 0);
177 break;
178 }
179 case kScanline_Subset_Mode: {
180 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
181 const int divisor = 2;
182 const int w = decodeInfo.width();
183 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700184 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700185 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
186 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700187 }
188 const int subsetWidth = w/divisor;
189 const int subsetHeight = h/divisor;
190 // One of our subsets will be larger to contain any pixels that do not divide evenly.
191 const int extraX = w % divisor;
192 const int extraY = h % divisor;
193 /*
194 * if w or h are not evenly divided by divisor need to adjust width and height of end
195 * subsets to cover entire image.
196 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
197 * and height of end subsets.
198 * subsetBm is extracted from largestSubsetBm.
199 * subsetBm's size is determined based on the current subset and may be larger for end
200 * subsets.
201 */
msarett0a242972015-06-11 14:27:27 -0700202 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700203 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
204 SkBitmap largestSubsetBm;
205 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, NULL, colorTable.get())) {
206 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
207 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
208 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700209 const size_t rowBytes = decodeInfo.minRowBytes();
210 char* buffer = SkNEW_ARRAY(char, largestSubsetDecodeInfo.height() * rowBytes);
211 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700212 for (int col = 0; col < divisor; col++) {
213 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
214 const int currentSubsetWidth = (col + 1 == divisor) ?
215 subsetWidth + extraX : subsetWidth;
216 const int x = col * subsetWidth;
217 for (int row = 0; row < divisor; row++) {
218 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
219 const int currentSubsetHeight = (row + 1 == divisor) ?
220 subsetHeight + extraY : subsetHeight;
221 const int y = row * subsetHeight;
222 //create scanline decoder for each subset
scroggo9b2cdbf42015-07-10 12:07:02 -0700223 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
224 codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
emmaleer97002062015-05-27 12:36:10 -0700225 if (NULL == subsetScanlineDecoder) {
226 if (x == 0 && y == 0) {
227 //first try, image may not be compatible
228 return Error::Nonfatal("Cannot use scanline decoder for all images");
229 } else {
230 return "Error scanline decoder is NULL";
231 }
232 }
233 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700234 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700235 subsetScanlineDecoder->skipScanlines(y);
236 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700237 case SkCodec::kSuccess:
238 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700239 break;
240 default:
241 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
242 "with error message %d", fPath.c_str(), y, (int) skipResult);
243 }
244 //create and set size of subsetBm
245 SkBitmap subsetBm;
246 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
247 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
248 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
249 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700250 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700251 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
252 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700253 case SkCodec::kSuccess:
254 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700255 break;
256 default:
mtkleind2baa902015-07-07 09:43:28 -0700257 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700258 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700259 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700260 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700261 /*
262 * we copy all the lines at once becuase when calling getScanlines for
263 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700264 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
265 * decode the entire image height times, which is very slow
266 * it is aknowledged that copying each line as you read it in a loop
267 * may be faster for other types of images. Since this is a correctness test
268 * that's okay.
269 */
mtkleind2baa902015-07-07 09:43:28 -0700270 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700271 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700272 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700273 currentSubsetWidth*bpp);
274 bufferRow += rowBytes;
275 }
mtkleind2baa902015-07-07 09:43:28 -0700276
emmaleer97002062015-05-27 12:36:10 -0700277 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
278 }
279 }
scroggo9c59ebc2015-03-25 13:48:49 -0700280 break;
281 }
msarett0a242972015-06-11 14:27:27 -0700282 case kStripe_Mode: {
283 const int height = decodeInfo.height();
284 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
285 // does not align with image blocks.
286 const int stripeHeight = 37;
287 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
288
289 // Decode odd stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700290 SkAutoTDelete<SkScanlineDecoder> decoder(
291 codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700292 if (NULL == decoder) {
293 return Error::Nonfatal("Cannot use scanline decoder for all images");
294 }
295 for (int i = 0; i < numStripes; i += 2) {
296 // Skip a stripe
297 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700298 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700299 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700300 case SkCodec::kSuccess:
301 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700302 break;
303 default:
304 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
305 }
306
307 // Read a stripe
308 const int startY = (i + 1) * stripeHeight;
309 const int linesToRead = SkTMin(stripeHeight, height - startY);
310 if (linesToRead > 0) {
311 result = decoder->getScanlines(bitmap.getAddr(0, startY),
312 linesToRead, bitmap.rowBytes());
313 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700314 case SkCodec::kSuccess:
315 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700316 break;
317 default:
318 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
319 }
320 }
321 }
322
323 // Decode even stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700324 decoder.reset(codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700325 if (NULL == decoder) {
326 return "Failed to create second scanline decoder.";
327 }
328 for (int i = 0; i < numStripes; i += 2) {
329 // Read a stripe
330 const int startY = i * stripeHeight;
331 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700332 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700333 linesToRead, bitmap.rowBytes());
334 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700335 case SkCodec::kSuccess:
336 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700337 break;
338 default:
339 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
340 }
341
342 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700343 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
344 if (linesToSkip > 0) {
345 result = decoder->skipScanlines(linesToSkip);
346 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700347 case SkCodec::kSuccess:
348 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700349 break;
350 default:
351 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
352 }
msarett0a242972015-06-11 14:27:27 -0700353 }
354 }
355 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700356 break;
msarett0a242972015-06-11 14:27:27 -0700357 }
scroggob636b452015-07-22 07:16:20 -0700358 case kSubset_Mode: {
359 // Arbitrarily choose a divisor.
360 int divisor = 2;
361 // Total width/height of the image.
362 const int W = codec->getInfo().width();
363 const int H = codec->getInfo().height();
364 if (divisor > W || divisor > H) {
365 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
366 "for %s with dimensions (%d x %d)", divisor,
367 fPath.c_str(), W, H));
368 }
369 // subset dimensions
370 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
371 const int w = SkAlign2(W / divisor);
372 const int h = SkAlign2(H / divisor);
373 SkIRect subset;
374 SkCodec::Options opts;
375 opts.fSubset = &subset;
376 SkBitmap subsetBm;
377 // We will reuse pixel memory from bitmap.
378 void* pixels = bitmap.getPixels();
379 // Keep track of left and top (for drawing subsetBm into canvas). We could use
380 // fScale * x and fScale * y, but we want integers such that the next subset will start
381 // where the last one ended. So we'll add decodeInfo.width() and height().
382 int left = 0;
383 for (int x = 0; x < W; x += w) {
384 int top = 0;
385 for (int y = 0; y < H; y+= h) {
386 // Do not make the subset go off the edge of the image.
387 const int preScaleW = SkTMin(w, W - x);
388 const int preScaleH = SkTMin(h, H - y);
389 subset.setXYWH(x, y, preScaleW, preScaleH);
390 // And scale
391 // FIXME: Should we have a version of getScaledDimensions that takes a subset
392 // into account?
393 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
394 SkScalarRoundToInt(preScaleH * fScale));
395 size_t rowBytes = decodeInfo.minRowBytes();
396 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
397 NULL, NULL)) {
398 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
399 }
400 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
401 &opts, colorPtr, colorCountPtr);
402 switch (result) {
403 case SkCodec::kSuccess:
404 case SkCodec::kIncompleteInput:
405 break;
406 case SkCodec::kInvalidConversion:
407 if (0 == (x|y)) {
408 // First subset is okay to return unimplemented.
409 return Error::Nonfatal("Incompatible colortype conversion");
410 }
411 // If the first subset succeeded, a later one should not fail.
412 // fall through to failure
413 case SkCodec::kUnimplemented:
414 if (0 == (x|y)) {
415 // First subset is okay to return unimplemented.
416 return Error::Nonfatal("subset codec not supported");
417 }
418 // If the first subset succeeded, why would a later one fail?
419 // fall through to failure
420 default:
421 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
422 "from %s with dimensions (%d x %d)\t error %d",
423 x, y, decodeInfo.width(), decodeInfo.height(),
424 fPath.c_str(), W, H, result);
425 }
426 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
427 // translate by the scaled height.
428 top += decodeInfo.height();
429 }
430 // translate by the scaled width.
431 left += decodeInfo.width();
432 }
433 return "";
434 }
scroggo9b77ddd2015-03-19 06:03:39 -0700435 }
scroggo9c59ebc2015-03-25 13:48:49 -0700436 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700437}
438
439SkISize CodecSrc::size() const {
440 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
441 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9bde9182015-03-25 05:27:48 -0700442 if (NULL != codec) {
msarett0a242972015-06-11 14:27:27 -0700443 SkISize size = codec->getScaledDimensions(fScale);
444 return size;
msarett9bde9182015-03-25 05:27:48 -0700445 } else {
446 return SkISize::Make(0, 0);
447 }
scroggo9b77ddd2015-03-19 06:03:39 -0700448}
449
450Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700451 if (1.0f == fScale) {
452 return SkOSPath::Basename(fPath.c_str());
453 } else {
454 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
455 }
scroggo9b77ddd2015-03-19 06:03:39 -0700456}
457
458/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
459
460ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
461
462Error ImageSrc::draw(SkCanvas* canvas) const {
463 SkImageInfo canvasInfo;
464 if (NULL == canvas->peekPixels(&canvasInfo, NULL)) {
465 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
466 return Error::Nonfatal("No need to test decoding to non-raster backend.");
467 }
468
469 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
470 if (!encoded) {
471 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
472 }
473 const SkColorType dstColorType = canvasInfo.colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800474 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800475 // Decode the full image.
476 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700477 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
478 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
479 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
480 }
481 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
482 // Do not draw a bitmap with alpha to a destination without alpha.
483 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800484 }
mtklein75d98fd2015-01-18 07:05:01 -0800485 encoded.reset((SkData*)NULL); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800486 canvas->drawBitmap(bitmap, 0,0);
487 return "";
488 }
mtkleinedc93bc2015-01-30 13:22:23 -0800489 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800490 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
491 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800492 if (!decoder) {
493 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
494 }
scroggoa1193e42015-01-21 12:09:53 -0800495 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800496 int w,h;
msarett70542572015-06-19 07:44:05 -0700497 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800498 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800499 }
mtkleinedc93bc2015-01-30 13:22:23 -0800500
501 // Divide the image into subsets that cover the entire image.
502 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700503 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
504 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800505 }
506 const int subsetWidth = w / fDivisor,
507 subsetHeight = h / fDivisor;
508 for (int y = 0; y < h; y += subsetHeight) {
509 for (int x = 0; x < w; x += subsetWidth) {
510 SkBitmap subset;
511 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
512 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
513 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
514 x, y, x+subsetWidth, y+subsetHeight);
515 }
scroggo56e25dd2015-03-05 11:46:40 -0800516 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
517 // Do not draw a bitmap with alpha to a destination without alpha.
518 // This is not an error, but there is nothing interesting to show.
519
520 // This should only happen on the first iteration through the loop.
521 SkASSERT(0 == x && 0 == y);
522
523 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
524 }
mtkleinedc93bc2015-01-30 13:22:23 -0800525 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800526 }
mtklein748ca3b2015-01-15 10:56:12 -0800527 }
528 return "";
529}
530
531SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800532 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700533 SkBitmap bitmap;
534 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
535 encoded->size(),
536 &bitmap,
537 kUnknown_SkColorType,
538 SkImageDecoder::kDecodeBounds_Mode)) {
539 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800540 }
scroggo9b77ddd2015-03-19 06:03:39 -0700541 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800542}
543
mtklein9264a952015-01-20 10:11:53 -0800544Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800545 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800546}
mtklein748ca3b2015-01-15 10:56:12 -0800547
548/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
549
mtkleinf4ba3212015-01-28 15:32:24 -0800550static const SkRect kSKPViewport = {0,0, 1000,1000};
551
mtklein8d17a132015-01-30 11:42:31 -0800552SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800553
554Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800555 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800556 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800557 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
558 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700559 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800560 if (!pic) {
561 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
562 }
563 stream.reset((SkStream*)NULL); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700564
mtkleinf4ba3212015-01-28 15:32:24 -0800565 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800566 canvas->drawPicture(pic);
567 return "";
568}
569
570SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700571 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
572 if (!stream) {
573 return SkISize::Make(0,0);
574 }
575 SkPictInfo info;
576 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
577 return SkISize::Make(0,0);
578 }
579 SkRect viewport = kSKPViewport;
580 if (!viewport.intersect(info.fCullRect)) {
581 return SkISize::Make(0,0);
582 }
583 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800584}
585
586Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
587
588/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
589
mtkleinad66f9b2015-02-13 15:11:10 -0800590Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
591 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
592 return src.draw(canvas);
593}
594
595/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
596
mtkleinb9eb4ac2015-02-02 18:26:03 -0800597DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
598
mtklein82d28432015-01-15 12:46:02 -0800599GPUSink::GPUSink(GrContextFactory::GLContextType ct,
600 GrGLStandard api,
601 int samples,
602 bool dfText,
603 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800604 : fContextType(ct)
605 , fGpuAPI(api)
606 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800607 , fUseDFText(dfText)
608 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800609
610int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800611 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800612}
613
joshualitt5f5a8d72015-02-25 14:09:45 -0800614void PreAbandonGpuContextErrorHandler(SkError, void*) {}
615
mtkleinb9eb4ac2015-02-02 18:26:03 -0800616Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700617 GrContextOptions options;
618 src.modifyGrContextOptions(&options);
619
620 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800621 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800622 const SkImageInfo info =
623 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
624 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800625 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800626 if (!surface) {
627 return "Could not create a surface.";
628 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800629 if (FLAGS_preAbandonGpuContext) {
630 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, NULL);
631 factory.abandonContexts();
632 }
mtklein748ca3b2015-01-15 10:56:12 -0800633 SkCanvas* canvas = surface->getCanvas();
634 Error err = src.draw(canvas);
635 if (!err.isEmpty()) {
636 return err;
637 }
638 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800639 if (FLAGS_gpuStats) {
640 canvas->getGrContext()->dumpCacheStats(log);
641 canvas->getGrContext()->dumpGpuStats(log);
642 }
mtklein748ca3b2015-01-15 10:56:12 -0800643 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800644 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800645 if (FLAGS_abandonGpuContext) {
646 factory.abandonContexts();
647 }
mtklein748ca3b2015-01-15 10:56:12 -0800648 return "";
649}
650
651/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
652
halcanary47ef4d52015-03-03 09:13:09 -0800653static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
654 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
655 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800656 int width = src.size().width(),
657 height = src.size().height();
658
halcanary7e798182015-04-14 14:06:18 -0700659 if (FLAGS_multiPage) {
660 const int kLetterWidth = 612, // 8.5 * 72
661 kLetterHeight = 792; // 11 * 72
662 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
663 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800664
halcanary7e798182015-04-14 14:06:18 -0700665 int xPages = ((width - 1) / kLetterWidth) + 1;
666 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800667
halcanary7e798182015-04-14 14:06:18 -0700668 for (int y = 0; y < yPages; ++y) {
669 for (int x = 0; x < xPages; ++x) {
670 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
671 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
672 SkCanvas* canvas =
673 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
674 if (!canvas) {
675 return "SkDocument::beginPage(w,h) returned NULL";
676 }
677 canvas->clipRect(letter);
678 canvas->translate(-letter.width() * x, -letter.height() * y);
679 Error err = src.draw(canvas);
680 if (!err.isEmpty()) {
681 return err;
682 }
683 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700684 }
halcanaryfd4a9932015-01-28 11:45:58 -0800685 }
halcanary7e798182015-04-14 14:06:18 -0700686 } else {
687 SkCanvas* canvas =
688 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
689 if (!canvas) {
690 return "SkDocument::beginPage(w,h) returned NULL";
691 }
692 Error err = src.draw(canvas);
693 if (!err.isEmpty()) {
694 return err;
695 }
696 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800697 }
halcanary7e798182015-04-14 14:06:18 -0700698 if (!doc->close()) {
699 return "SkDocument::close() returned false";
700 }
halcanaryfd4a9932015-01-28 11:45:58 -0800701 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800702 return "";
703}
704
halcanary47ef4d52015-03-03 09:13:09 -0800705PDFSink::PDFSink() {}
706
707Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
708 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
709 if (!doc) {
710 return "SkDocument::CreatePDF() returned NULL";
711 }
712 return draw_skdocument(src, doc.get(), dst);
713}
714
715/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
716
717XPSSink::XPSSink() {}
718
719Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
720 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
721 if (!doc) {
722 return "SkDocument::CreateXPS() returned NULL";
723 }
724 return draw_skdocument(src, doc.get(), dst);
725}
mtklein748ca3b2015-01-15 10:56:12 -0800726/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
727
mtklein9c3f17d2015-01-28 11:35:18 -0800728SKPSink::SKPSink() {}
729
mtkleinb9eb4ac2015-02-02 18:26:03 -0800730Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800731 SkSize size;
732 size = src.size();
733 SkPictureRecorder recorder;
734 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
735 if (!err.isEmpty()) {
736 return err;
737 }
738 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
739 pic->serialize(dst);
740 return "";
741}
742
743/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
744
mtklein8a4527e2015-01-31 20:00:58 -0800745SVGSink::SVGSink() {}
746
mtkleinb9eb4ac2015-02-02 18:26:03 -0800747Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita2aafe6f2015-02-06 12:51:10 -0800748 SkAutoTDelete<SkXMLWriter> xmlWriter(SkNEW_ARGS(SkXMLStreamWriter, (dst)));
749 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
750 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
751 xmlWriter));
752 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800753}
754
755/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
756
mtklein748ca3b2015-01-15 10:56:12 -0800757RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
758
mtkleinb9eb4ac2015-02-02 18:26:03 -0800759Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800760 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800761 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
762 SkAlphaType alphaType = kPremul_SkAlphaType;
763 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
764
765 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
766 dst->eraseColor(SK_ColorTRANSPARENT);
767 SkCanvas canvas(*dst);
768 return src.draw(&canvas);
769}
770
771/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
772
mtkleina16e69e2015-05-05 11:38:45 -0700773// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700774// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700775// Several examples below.
776
mtkleina16e69e2015-05-05 11:38:45 -0700777static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700778 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700779 class ProxySrc : public Src {
780 public:
mtkleine44b5082015-05-07 10:53:34 -0700781 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700782 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
783 Name name() const override { sk_throw(); return ""; } // Won't be called.
784 SkISize size() const override { return fSize; }
785 private:
mtkleine44b5082015-05-07 10:53:34 -0700786 SkISize fSize;
787 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700788 };
789 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
790}
791
792/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
793
mtkleind603b222015-02-17 11:13:33 -0800794static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
795 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
796 matrix->mapRect(&bounds);
797 matrix->postTranslate(-bounds.x(), -bounds.y());
798 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
799}
800
mtklein78829242015-05-06 07:54:07 -0700801ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800802
mtkleinb9eb4ac2015-02-02 18:26:03 -0800803Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700804 SkMatrix matrix = fMatrix;
805 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
806 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
807 canvas->concat(matrix);
808 return src.draw(canvas);
809 });
mtklein748ca3b2015-01-15 10:56:12 -0800810}
811
mtkleind603b222015-02-17 11:13:33 -0800812// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
813// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700814ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800815
816Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
817 Error err = fSink->draw(src, bitmap, stream, log);
818 if (!err.isEmpty()) {
819 return err;
820 }
821
822 SkMatrix inverse;
823 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
824 return "Cannot upright --matrix.";
825 }
826 SkMatrix upright = SkMatrix::I();
827 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
828 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
829 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
830 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
831
832 SkBitmap uprighted;
833 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
834 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
835
836 SkCanvas canvas(uprighted);
837 canvas.concat(upright);
838 SkPaint paint;
839 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
840 canvas.drawBitmap(*bitmap, 0, 0, &paint);
841
842 *bitmap = uprighted;
843 bitmap->lockPixels();
844 return "";
845}
846
mtklein748ca3b2015-01-15 10:56:12 -0800847/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
848
mtkleinb9eb4ac2015-02-02 18:26:03 -0800849Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700850 auto size = src.size();
851 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
852 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
853 SkGPipeWriter pipe;
854 const uint32_t kFlags = 0; // We mirror SkDeferredCanvas, which doesn't use any flags.
855 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
856 });
mtklein748ca3b2015-01-15 10:56:12 -0800857}
858
859/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700860
reed06a22f62015-05-05 08:11:33 -0700861Error ViaDeferred::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700862 // We draw via a deferred canvas into a surface that's compatible with the original canvas,
863 // then snap that surface as an image and draw it into the original canvas.
864 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
865 SkAutoTUnref<SkSurface> surface(canvas->newSurface(canvas->imageInfo()));
866 if (!surface.get()) {
867 return "can't make surface for deferred canvas";
reed06a22f62015-05-05 08:11:33 -0700868 }
mtkleina16e69e2015-05-05 11:38:45 -0700869 SkAutoTDelete<SkDeferredCanvas> defcan(SkDeferredCanvas::Create(surface));
870 Error err = src.draw(defcan);
871 if (!err.isEmpty()) {
872 return err;
873 }
874 SkAutoTUnref<SkImage> image(defcan->newImageSnapshot());
875 if (!image) {
876 return "failed to create deferred image snapshot";
877 }
878 canvas->drawImage(image, 0, 0, NULL);
879 return "";
880 });
reed06a22f62015-05-05 08:11:33 -0700881}
mtkleina16e69e2015-05-05 11:38:45 -0700882
reed06a22f62015-05-05 08:11:33 -0700883/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -0800884
mtkleina16e69e2015-05-05 11:38:45 -0700885Error ViaSerialization::draw(
886 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800887 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700888 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800889 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700890 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
891 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800892 if (!err.isEmpty()) {
893 return err;
894 }
895 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
896
897 // Serialize it and then deserialize it.
898 SkDynamicMemoryWStream wStream;
899 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800900 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700901 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800902
mtkleina16e69e2015-05-05 11:38:45 -0700903 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
904 canvas->drawPicture(deserialized);
905 return "";
906 });
mtklein748ca3b2015-01-15 10:56:12 -0800907}
908
909/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
910
911ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700912 : Via(sink)
913 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800914 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700915 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800916
mtkleinb9eb4ac2015-02-02 18:26:03 -0800917Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700918 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800919 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700920 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
921 SkIntToScalar(size.height()),
922 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800923 if (!err.isEmpty()) {
924 return err;
925 }
mtkleinb7e8d692015-04-07 08:30:32 -0700926 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800927
mtkleina16e69e2015-05-05 11:38:45 -0700928 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
929 const int xTiles = (size.width() + fW - 1) / fW,
930 yTiles = (size.height() + fH - 1) / fH;
931 SkMultiPictureDraw mpd(xTiles*yTiles);
932 SkTDArray<SkSurface*> surfaces;
933 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800934
mtkleina16e69e2015-05-05 11:38:45 -0700935 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
936 for (int j = 0; j < yTiles; j++) {
937 for (int i = 0; i < xTiles; i++) {
938 // This lets our ultimate Sink determine the best kind of surface.
939 // E.g., if it's a GpuSink, the surfaces and images are textures.
940 SkSurface* s = canvas->newSurface(info);
941 if (!s) {
942 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800943 }
mtkleina16e69e2015-05-05 11:38:45 -0700944 surfaces.push(s);
945 SkCanvas* c = s->getCanvas();
946 c->translate(SkIntToScalar(-i * fW),
947 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
948 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800949 }
mtklein748ca3b2015-01-15 10:56:12 -0800950 }
mtkleina16e69e2015-05-05 11:38:45 -0700951 mpd.draw();
952 for (int j = 0; j < yTiles; j++) {
953 for (int i = 0; i < xTiles; i++) {
954 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
955 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
956 }
957 }
958 surfaces.unrefAll();
959 return "";
960 });
mtklein748ca3b2015-01-15 10:56:12 -0800961}
962
mtkleinb7e8d692015-04-07 08:30:32 -0700963/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
964
mtkleinb7e8d692015-04-07 08:30:32 -0700965// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
966// This tests that any shortcuts we may take while recording that second picture are legal.
967Error ViaSecondPicture::draw(
968 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700969 auto size = src.size();
970 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
971 SkPictureRecorder recorder;
972 SkAutoTUnref<SkPicture> pic;
973 for (int i = 0; i < 2; i++) {
974 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
975 SkIntToScalar(size.height())));
976 if (!err.isEmpty()) {
977 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700978 }
mtkleina16e69e2015-05-05 11:38:45 -0700979 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700980 }
mtkleina16e69e2015-05-05 11:38:45 -0700981 canvas->drawPicture(pic);
982 return "";
983 });
mtkleinb7e8d692015-04-07 08:30:32 -0700984}
985
mtkleind31c13d2015-05-05 12:59:56 -0700986/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
987
mtklein6fbf4b32015-05-06 11:35:40 -0700988// Draw the Src twice. This can help exercise caching.
989Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
990 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
991 for (int i = 0; i < 2; i++) {
992 SkAutoCanvasRestore acr(canvas, true/*save now*/);
993 canvas->clear(SK_ColorTRANSPARENT);
994 Error err = src.draw(canvas);
995 if (err.isEmpty()) {
996 return err;
997 }
998 }
999 return "";
1000 });
1001}
1002
1003/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1004
mtkleind31c13d2015-05-05 12:59:56 -07001005// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1006// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1007// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1008struct DrawsAsSingletonPictures {
1009 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001010 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001011
1012 SK_CREATE_MEMBER_DETECTOR(paint);
1013
1014 template <typename T>
1015 void draw(const T& op, SkCanvas* canvas) {
1016 // We must pass SkMatrix::I() as our initial matrix.
1017 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1018 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001019 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1020 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001021 }
1022
1023 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1024 template <typename T>
1025 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1026 SkPictureRecorder rec;
1027 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1028 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1029 fCanvas->drawPicture(pic);
1030 }
1031
1032 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1033 // We cannot make subpictures out of these because they affect state. Draw them directly.
1034 template <typename T>
1035 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1036 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1037};
1038
mtkleind31c13d2015-05-05 12:59:56 -07001039// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1040// Then play back that macro picture into our wrapped sink.
1041Error ViaSingletonPictures::draw(
1042 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1043 auto size = src.size();
1044 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1045 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1046 SkRecord skr;
1047 SkRecorder recorder(&skr, size.width(), size.height());
1048 Error err = src.draw(&recorder);
1049 if (!err.isEmpty()) {
1050 return err;
1051 }
1052
1053 // Record our macro-picture, with each draw op as its own sub-picture.
1054 SkPictureRecorder macroRec;
1055 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1056 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001057
1058 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1059 const SkDrawableList empty;
1060
1061 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1062 macroCanvas,
1063 drawables ? *drawables : empty,
1064 };
mtkleind31c13d2015-05-05 12:59:56 -07001065 for (unsigned i = 0; i < skr.count(); i++) {
1066 skr.visit<void>(i, drawsAsSingletonPictures);
1067 }
1068 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1069
1070 canvas->drawPicture(macroPic);
1071 return "";
1072 });
1073}
1074
mtklein748ca3b2015-01-15 10:56:12 -08001075} // namespace DM