blob: 0cd2ac93471e1b0aff2c4858689c6090bc482e5d [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
mtkleine0effd62015-07-29 06:37:28 -070074bool CodecSrc::veto(SinkType type) const {
75 // No need to test decoding to non-raster backend.
76 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
77 // let the GPU handle it.
78 return type != kRaster_SinkType;
79}
scroggo9b77ddd2015-03-19 06:03:39 -070080
mtkleine0effd62015-07-29 06:37:28 -070081Error CodecSrc::draw(SkCanvas* canvas) const {
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();
mtkleine0effd62015-07-29 06:37:28 -070093 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -070094 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
scroggo4358f132015-07-30 11:33:04 -0700277 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700278 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
279 }
280 }
scroggo9c59ebc2015-03-25 13:48:49 -0700281 break;
282 }
msarett0a242972015-06-11 14:27:27 -0700283 case kStripe_Mode: {
284 const int height = decodeInfo.height();
285 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
286 // does not align with image blocks.
287 const int stripeHeight = 37;
288 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
289
290 // Decode odd stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700291 SkAutoTDelete<SkScanlineDecoder> decoder(
292 codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700293 if (NULL == decoder) {
294 return Error::Nonfatal("Cannot use scanline decoder for all images");
295 }
296 for (int i = 0; i < numStripes; i += 2) {
297 // Skip a stripe
298 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700299 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700300 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700301 case SkCodec::kSuccess:
302 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700303 break;
304 default:
305 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
306 }
307
308 // Read a stripe
309 const int startY = (i + 1) * stripeHeight;
310 const int linesToRead = SkTMin(stripeHeight, height - startY);
311 if (linesToRead > 0) {
312 result = decoder->getScanlines(bitmap.getAddr(0, startY),
313 linesToRead, bitmap.rowBytes());
314 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700315 case SkCodec::kSuccess:
316 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700317 break;
318 default:
319 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
320 }
321 }
322 }
323
324 // Decode even stripes
scroggo9b2cdbf42015-07-10 12:07:02 -0700325 decoder.reset(codec->getScanlineDecoder(decodeInfo, NULL, colorPtr, colorCountPtr));
msarett0a242972015-06-11 14:27:27 -0700326 if (NULL == decoder) {
327 return "Failed to create second scanline decoder.";
328 }
329 for (int i = 0; i < numStripes; i += 2) {
330 // Read a stripe
331 const int startY = i * stripeHeight;
332 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700333 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700334 linesToRead, bitmap.rowBytes());
335 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700336 case SkCodec::kSuccess:
337 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700338 break;
339 default:
340 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
341 }
342
343 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700344 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
345 if (linesToSkip > 0) {
346 result = decoder->skipScanlines(linesToSkip);
347 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700348 case SkCodec::kSuccess:
349 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700350 break;
351 default:
352 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
353 }
msarett0a242972015-06-11 14:27:27 -0700354 }
355 }
356 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700357 break;
msarett0a242972015-06-11 14:27:27 -0700358 }
scroggob636b452015-07-22 07:16:20 -0700359 case kSubset_Mode: {
360 // Arbitrarily choose a divisor.
361 int divisor = 2;
362 // Total width/height of the image.
363 const int W = codec->getInfo().width();
364 const int H = codec->getInfo().height();
365 if (divisor > W || divisor > H) {
366 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
367 "for %s with dimensions (%d x %d)", divisor,
368 fPath.c_str(), W, H));
369 }
370 // subset dimensions
371 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
372 const int w = SkAlign2(W / divisor);
373 const int h = SkAlign2(H / divisor);
374 SkIRect subset;
375 SkCodec::Options opts;
376 opts.fSubset = &subset;
377 SkBitmap subsetBm;
378 // We will reuse pixel memory from bitmap.
379 void* pixels = bitmap.getPixels();
380 // Keep track of left and top (for drawing subsetBm into canvas). We could use
381 // fScale * x and fScale * y, but we want integers such that the next subset will start
382 // where the last one ended. So we'll add decodeInfo.width() and height().
383 int left = 0;
384 for (int x = 0; x < W; x += w) {
385 int top = 0;
386 for (int y = 0; y < H; y+= h) {
387 // Do not make the subset go off the edge of the image.
388 const int preScaleW = SkTMin(w, W - x);
389 const int preScaleH = SkTMin(h, H - y);
390 subset.setXYWH(x, y, preScaleW, preScaleH);
391 // And scale
392 // FIXME: Should we have a version of getScaledDimensions that takes a subset
393 // into account?
394 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
395 SkScalarRoundToInt(preScaleH * fScale));
396 size_t rowBytes = decodeInfo.minRowBytes();
397 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
398 NULL, NULL)) {
399 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
400 }
401 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
402 &opts, colorPtr, colorCountPtr);
403 switch (result) {
404 case SkCodec::kSuccess:
405 case SkCodec::kIncompleteInput:
406 break;
407 case SkCodec::kInvalidConversion:
408 if (0 == (x|y)) {
409 // First subset is okay to return unimplemented.
410 return Error::Nonfatal("Incompatible colortype conversion");
411 }
412 // If the first subset succeeded, a later one should not fail.
413 // fall through to failure
414 case SkCodec::kUnimplemented:
415 if (0 == (x|y)) {
416 // First subset is okay to return unimplemented.
417 return Error::Nonfatal("subset codec not supported");
418 }
419 // If the first subset succeeded, why would a later one fail?
420 // fall through to failure
421 default:
422 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
423 "from %s with dimensions (%d x %d)\t error %d",
424 x, y, decodeInfo.width(), decodeInfo.height(),
425 fPath.c_str(), W, H, result);
426 }
427 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
428 // translate by the scaled height.
429 top += decodeInfo.height();
430 }
431 // translate by the scaled width.
432 left += decodeInfo.width();
433 }
434 return "";
435 }
scroggo9b77ddd2015-03-19 06:03:39 -0700436 }
scroggo9c59ebc2015-03-25 13:48:49 -0700437 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700438}
439
440SkISize CodecSrc::size() const {
441 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
442 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9bde9182015-03-25 05:27:48 -0700443 if (NULL != codec) {
msarett0a242972015-06-11 14:27:27 -0700444 SkISize size = codec->getScaledDimensions(fScale);
445 return size;
msarett9bde9182015-03-25 05:27:48 -0700446 } else {
447 return SkISize::Make(0, 0);
448 }
scroggo9b77ddd2015-03-19 06:03:39 -0700449}
450
451Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700452 if (1.0f == fScale) {
453 return SkOSPath::Basename(fPath.c_str());
454 } else {
455 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
456 }
scroggo9b77ddd2015-03-19 06:03:39 -0700457}
458
459/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
460
461ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
462
mtkleine0effd62015-07-29 06:37:28 -0700463bool ImageSrc::veto(SinkType type) const {
464 // No need to test decoding to non-raster backend.
465 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
466 return type != kRaster_SinkType;
467}
scroggo9b77ddd2015-03-19 06:03:39 -0700468
mtkleine0effd62015-07-29 06:37:28 -0700469Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700470 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
471 if (!encoded) {
472 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
473 }
mtkleine0effd62015-07-29 06:37:28 -0700474 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800475 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800476 // Decode the full image.
477 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700478 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
479 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
480 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
481 }
482 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
483 // Do not draw a bitmap with alpha to a destination without alpha.
484 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800485 }
mtklein75d98fd2015-01-18 07:05:01 -0800486 encoded.reset((SkData*)NULL); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800487 canvas->drawBitmap(bitmap, 0,0);
488 return "";
489 }
mtkleinedc93bc2015-01-30 13:22:23 -0800490 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800491 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
492 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800493 if (!decoder) {
494 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
495 }
scroggoa1193e42015-01-21 12:09:53 -0800496 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800497 int w,h;
msarett70542572015-06-19 07:44:05 -0700498 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800499 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800500 }
mtkleinedc93bc2015-01-30 13:22:23 -0800501
502 // Divide the image into subsets that cover the entire image.
503 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700504 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
505 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800506 }
507 const int subsetWidth = w / fDivisor,
508 subsetHeight = h / fDivisor;
509 for (int y = 0; y < h; y += subsetHeight) {
510 for (int x = 0; x < w; x += subsetWidth) {
511 SkBitmap subset;
512 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
513 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
514 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
515 x, y, x+subsetWidth, y+subsetHeight);
516 }
scroggo56e25dd2015-03-05 11:46:40 -0800517 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
518 // Do not draw a bitmap with alpha to a destination without alpha.
519 // This is not an error, but there is nothing interesting to show.
520
521 // This should only happen on the first iteration through the loop.
522 SkASSERT(0 == x && 0 == y);
523
524 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
525 }
mtkleinedc93bc2015-01-30 13:22:23 -0800526 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800527 }
mtklein748ca3b2015-01-15 10:56:12 -0800528 }
529 return "";
530}
531
532SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800533 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700534 SkBitmap bitmap;
535 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
536 encoded->size(),
537 &bitmap,
538 kUnknown_SkColorType,
539 SkImageDecoder::kDecodeBounds_Mode)) {
540 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800541 }
scroggo9b77ddd2015-03-19 06:03:39 -0700542 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800543}
544
mtklein9264a952015-01-20 10:11:53 -0800545Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800546 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800547}
mtklein748ca3b2015-01-15 10:56:12 -0800548
549/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
550
mtkleinf4ba3212015-01-28 15:32:24 -0800551static const SkRect kSKPViewport = {0,0, 1000,1000};
552
mtklein8d17a132015-01-30 11:42:31 -0800553SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800554
555Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800556 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800557 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800558 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
559 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700560 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800561 if (!pic) {
562 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
563 }
564 stream.reset((SkStream*)NULL); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700565
mtkleinf4ba3212015-01-28 15:32:24 -0800566 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800567 canvas->drawPicture(pic);
568 return "";
569}
570
571SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700572 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
573 if (!stream) {
574 return SkISize::Make(0,0);
575 }
576 SkPictInfo info;
577 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
578 return SkISize::Make(0,0);
579 }
580 SkRect viewport = kSKPViewport;
581 if (!viewport.intersect(info.fCullRect)) {
582 return SkISize::Make(0,0);
583 }
584 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800585}
586
587Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
588
589/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
590
mtkleinad66f9b2015-02-13 15:11:10 -0800591Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
592 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
593 return src.draw(canvas);
594}
595
596/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
597
mtkleinb9eb4ac2015-02-02 18:26:03 -0800598DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
599
mtklein82d28432015-01-15 12:46:02 -0800600GPUSink::GPUSink(GrContextFactory::GLContextType ct,
601 GrGLStandard api,
602 int samples,
603 bool dfText,
604 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800605 : fContextType(ct)
606 , fGpuAPI(api)
607 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800608 , fUseDFText(dfText)
609 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800610
611int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800612 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800613}
614
joshualitt5f5a8d72015-02-25 14:09:45 -0800615void PreAbandonGpuContextErrorHandler(SkError, void*) {}
616
mtkleinb9eb4ac2015-02-02 18:26:03 -0800617Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700618 GrContextOptions options;
619 src.modifyGrContextOptions(&options);
620
621 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800622 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800623 const SkImageInfo info =
624 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
625 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800626 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800627 if (!surface) {
628 return "Could not create a surface.";
629 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800630 if (FLAGS_preAbandonGpuContext) {
631 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, NULL);
632 factory.abandonContexts();
633 }
mtklein748ca3b2015-01-15 10:56:12 -0800634 SkCanvas* canvas = surface->getCanvas();
635 Error err = src.draw(canvas);
636 if (!err.isEmpty()) {
637 return err;
638 }
639 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800640 if (FLAGS_gpuStats) {
641 canvas->getGrContext()->dumpCacheStats(log);
642 canvas->getGrContext()->dumpGpuStats(log);
643 }
mtklein748ca3b2015-01-15 10:56:12 -0800644 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800645 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800646 if (FLAGS_abandonGpuContext) {
647 factory.abandonContexts();
648 }
mtklein748ca3b2015-01-15 10:56:12 -0800649 return "";
650}
651
652/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
653
halcanary47ef4d52015-03-03 09:13:09 -0800654static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
655 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
656 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800657 int width = src.size().width(),
658 height = src.size().height();
659
halcanary7e798182015-04-14 14:06:18 -0700660 if (FLAGS_multiPage) {
661 const int kLetterWidth = 612, // 8.5 * 72
662 kLetterHeight = 792; // 11 * 72
663 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
664 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800665
halcanary7e798182015-04-14 14:06:18 -0700666 int xPages = ((width - 1) / kLetterWidth) + 1;
667 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800668
halcanary7e798182015-04-14 14:06:18 -0700669 for (int y = 0; y < yPages; ++y) {
670 for (int x = 0; x < xPages; ++x) {
671 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
672 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
673 SkCanvas* canvas =
674 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
675 if (!canvas) {
676 return "SkDocument::beginPage(w,h) returned NULL";
677 }
678 canvas->clipRect(letter);
679 canvas->translate(-letter.width() * x, -letter.height() * y);
680 Error err = src.draw(canvas);
681 if (!err.isEmpty()) {
682 return err;
683 }
684 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700685 }
halcanaryfd4a9932015-01-28 11:45:58 -0800686 }
halcanary7e798182015-04-14 14:06:18 -0700687 } else {
688 SkCanvas* canvas =
689 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
690 if (!canvas) {
691 return "SkDocument::beginPage(w,h) returned NULL";
692 }
693 Error err = src.draw(canvas);
694 if (!err.isEmpty()) {
695 return err;
696 }
697 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800698 }
halcanary7e798182015-04-14 14:06:18 -0700699 if (!doc->close()) {
700 return "SkDocument::close() returned false";
701 }
halcanaryfd4a9932015-01-28 11:45:58 -0800702 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800703 return "";
704}
705
halcanary47ef4d52015-03-03 09:13:09 -0800706PDFSink::PDFSink() {}
707
708Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
709 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
710 if (!doc) {
711 return "SkDocument::CreatePDF() returned NULL";
712 }
713 return draw_skdocument(src, doc.get(), dst);
714}
715
716/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
717
718XPSSink::XPSSink() {}
719
720Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
721 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
722 if (!doc) {
723 return "SkDocument::CreateXPS() returned NULL";
724 }
725 return draw_skdocument(src, doc.get(), dst);
726}
mtklein748ca3b2015-01-15 10:56:12 -0800727/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
728
mtklein9c3f17d2015-01-28 11:35:18 -0800729SKPSink::SKPSink() {}
730
mtkleinb9eb4ac2015-02-02 18:26:03 -0800731Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800732 SkSize size;
733 size = src.size();
734 SkPictureRecorder recorder;
735 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
736 if (!err.isEmpty()) {
737 return err;
738 }
739 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
740 pic->serialize(dst);
741 return "";
742}
743
744/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
745
mtklein8a4527e2015-01-31 20:00:58 -0800746SVGSink::SVGSink() {}
747
mtkleinb9eb4ac2015-02-02 18:26:03 -0800748Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita2aafe6f2015-02-06 12:51:10 -0800749 SkAutoTDelete<SkXMLWriter> xmlWriter(SkNEW_ARGS(SkXMLStreamWriter, (dst)));
750 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
751 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
752 xmlWriter));
753 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800754}
755
756/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
757
mtklein748ca3b2015-01-15 10:56:12 -0800758RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
759
mtkleinb9eb4ac2015-02-02 18:26:03 -0800760Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800761 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800762 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
763 SkAlphaType alphaType = kPremul_SkAlphaType;
764 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
765
766 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
767 dst->eraseColor(SK_ColorTRANSPARENT);
768 SkCanvas canvas(*dst);
769 return src.draw(&canvas);
770}
771
772/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
773
mtkleina16e69e2015-05-05 11:38:45 -0700774// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700775// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700776// Several examples below.
777
mtkleina16e69e2015-05-05 11:38:45 -0700778static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700779 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700780 class ProxySrc : public Src {
781 public:
mtkleine44b5082015-05-07 10:53:34 -0700782 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700783 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
784 Name name() const override { sk_throw(); return ""; } // Won't be called.
785 SkISize size() const override { return fSize; }
786 private:
mtkleine44b5082015-05-07 10:53:34 -0700787 SkISize fSize;
788 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700789 };
790 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
791}
792
793/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
794
mtkleind603b222015-02-17 11:13:33 -0800795static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
796 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
797 matrix->mapRect(&bounds);
798 matrix->postTranslate(-bounds.x(), -bounds.y());
799 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
800}
801
mtklein78829242015-05-06 07:54:07 -0700802ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800803
mtkleinb9eb4ac2015-02-02 18:26:03 -0800804Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700805 SkMatrix matrix = fMatrix;
806 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
807 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
808 canvas->concat(matrix);
809 return src.draw(canvas);
810 });
mtklein748ca3b2015-01-15 10:56:12 -0800811}
812
mtkleind603b222015-02-17 11:13:33 -0800813// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
814// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700815ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800816
817Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
818 Error err = fSink->draw(src, bitmap, stream, log);
819 if (!err.isEmpty()) {
820 return err;
821 }
822
823 SkMatrix inverse;
824 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
825 return "Cannot upright --matrix.";
826 }
827 SkMatrix upright = SkMatrix::I();
828 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
829 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
830 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
831 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
832
833 SkBitmap uprighted;
834 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
835 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
836
837 SkCanvas canvas(uprighted);
838 canvas.concat(upright);
839 SkPaint paint;
840 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
841 canvas.drawBitmap(*bitmap, 0, 0, &paint);
842
843 *bitmap = uprighted;
844 bitmap->lockPixels();
845 return "";
846}
847
mtklein748ca3b2015-01-15 10:56:12 -0800848/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
849
mtkleinb9eb4ac2015-02-02 18:26:03 -0800850Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700851 auto size = src.size();
852 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
853 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
854 SkGPipeWriter pipe;
855 const uint32_t kFlags = 0; // We mirror SkDeferredCanvas, which doesn't use any flags.
856 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
857 });
mtklein748ca3b2015-01-15 10:56:12 -0800858}
859
860/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700861
reed06a22f62015-05-05 08:11:33 -0700862Error ViaDeferred::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700863 // We draw via a deferred canvas into a surface that's compatible with the original canvas,
864 // then snap that surface as an image and draw it into the original canvas.
865 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
866 SkAutoTUnref<SkSurface> surface(canvas->newSurface(canvas->imageInfo()));
867 if (!surface.get()) {
868 return "can't make surface for deferred canvas";
reed06a22f62015-05-05 08:11:33 -0700869 }
mtkleina16e69e2015-05-05 11:38:45 -0700870 SkAutoTDelete<SkDeferredCanvas> defcan(SkDeferredCanvas::Create(surface));
871 Error err = src.draw(defcan);
872 if (!err.isEmpty()) {
873 return err;
874 }
875 SkAutoTUnref<SkImage> image(defcan->newImageSnapshot());
876 if (!image) {
877 return "failed to create deferred image snapshot";
878 }
879 canvas->drawImage(image, 0, 0, NULL);
880 return "";
881 });
reed06a22f62015-05-05 08:11:33 -0700882}
mtkleina16e69e2015-05-05 11:38:45 -0700883
reed06a22f62015-05-05 08:11:33 -0700884/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -0800885
mtkleina16e69e2015-05-05 11:38:45 -0700886Error ViaSerialization::draw(
887 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800888 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700889 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800890 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700891 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
892 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800893 if (!err.isEmpty()) {
894 return err;
895 }
896 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
897
898 // Serialize it and then deserialize it.
899 SkDynamicMemoryWStream wStream;
900 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800901 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700902 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800903
mtkleina16e69e2015-05-05 11:38:45 -0700904 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
905 canvas->drawPicture(deserialized);
906 return "";
907 });
mtklein748ca3b2015-01-15 10:56:12 -0800908}
909
910/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
911
912ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700913 : Via(sink)
914 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800915 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700916 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800917
mtkleinb9eb4ac2015-02-02 18:26:03 -0800918Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700919 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800920 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700921 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
922 SkIntToScalar(size.height()),
923 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800924 if (!err.isEmpty()) {
925 return err;
926 }
mtkleinb7e8d692015-04-07 08:30:32 -0700927 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800928
mtkleina16e69e2015-05-05 11:38:45 -0700929 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
930 const int xTiles = (size.width() + fW - 1) / fW,
931 yTiles = (size.height() + fH - 1) / fH;
932 SkMultiPictureDraw mpd(xTiles*yTiles);
933 SkTDArray<SkSurface*> surfaces;
934 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800935
mtkleina16e69e2015-05-05 11:38:45 -0700936 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
937 for (int j = 0; j < yTiles; j++) {
938 for (int i = 0; i < xTiles; i++) {
939 // This lets our ultimate Sink determine the best kind of surface.
940 // E.g., if it's a GpuSink, the surfaces and images are textures.
941 SkSurface* s = canvas->newSurface(info);
942 if (!s) {
943 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800944 }
mtkleina16e69e2015-05-05 11:38:45 -0700945 surfaces.push(s);
946 SkCanvas* c = s->getCanvas();
947 c->translate(SkIntToScalar(-i * fW),
948 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
949 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800950 }
mtklein748ca3b2015-01-15 10:56:12 -0800951 }
mtkleina16e69e2015-05-05 11:38:45 -0700952 mpd.draw();
953 for (int j = 0; j < yTiles; j++) {
954 for (int i = 0; i < xTiles; i++) {
955 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
956 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
957 }
958 }
959 surfaces.unrefAll();
960 return "";
961 });
mtklein748ca3b2015-01-15 10:56:12 -0800962}
963
mtkleinb7e8d692015-04-07 08:30:32 -0700964/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
965
mtkleinb7e8d692015-04-07 08:30:32 -0700966// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
967// This tests that any shortcuts we may take while recording that second picture are legal.
968Error ViaSecondPicture::draw(
969 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700970 auto size = src.size();
971 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
972 SkPictureRecorder recorder;
973 SkAutoTUnref<SkPicture> pic;
974 for (int i = 0; i < 2; i++) {
975 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
976 SkIntToScalar(size.height())));
977 if (!err.isEmpty()) {
978 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700979 }
mtkleina16e69e2015-05-05 11:38:45 -0700980 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700981 }
mtkleina16e69e2015-05-05 11:38:45 -0700982 canvas->drawPicture(pic);
983 return "";
984 });
mtkleinb7e8d692015-04-07 08:30:32 -0700985}
986
mtkleind31c13d2015-05-05 12:59:56 -0700987/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
988
mtklein6fbf4b32015-05-06 11:35:40 -0700989// Draw the Src twice. This can help exercise caching.
990Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
991 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
992 for (int i = 0; i < 2; i++) {
993 SkAutoCanvasRestore acr(canvas, true/*save now*/);
994 canvas->clear(SK_ColorTRANSPARENT);
995 Error err = src.draw(canvas);
996 if (err.isEmpty()) {
997 return err;
998 }
999 }
1000 return "";
1001 });
1002}
1003
1004/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1005
mtkleind31c13d2015-05-05 12:59:56 -07001006// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1007// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1008// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1009struct DrawsAsSingletonPictures {
1010 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001011 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001012
1013 SK_CREATE_MEMBER_DETECTOR(paint);
1014
1015 template <typename T>
1016 void draw(const T& op, SkCanvas* canvas) {
1017 // We must pass SkMatrix::I() as our initial matrix.
1018 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1019 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001020 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1021 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001022 }
1023
1024 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1025 template <typename T>
1026 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1027 SkPictureRecorder rec;
1028 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1029 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1030 fCanvas->drawPicture(pic);
1031 }
1032
1033 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1034 // We cannot make subpictures out of these because they affect state. Draw them directly.
1035 template <typename T>
1036 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1037 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1038};
1039
mtkleind31c13d2015-05-05 12:59:56 -07001040// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1041// Then play back that macro picture into our wrapped sink.
1042Error ViaSingletonPictures::draw(
1043 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1044 auto size = src.size();
1045 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1046 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1047 SkRecord skr;
1048 SkRecorder recorder(&skr, size.width(), size.height());
1049 Error err = src.draw(&recorder);
1050 if (!err.isEmpty()) {
1051 return err;
1052 }
1053
1054 // Record our macro-picture, with each draw op as its own sub-picture.
1055 SkPictureRecorder macroRec;
1056 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1057 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001058
1059 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1060 const SkDrawableList empty;
1061
1062 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1063 macroCanvas,
1064 drawables ? *drawables : empty,
1065 };
mtkleind31c13d2015-05-05 12:59:56 -07001066 for (unsigned i = 0; i < skr.count(); i++) {
1067 skr.visit<void>(i, drawsAsSingletonPictures);
1068 }
1069 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1070
1071 canvas->drawPicture(macroPic);
1072 return "";
1073 });
1074}
1075
mtklein748ca3b2015-01-15 10:56:12 -08001076} // namespace DM