blob: f555b9fcbdba78f485e47b9baf4be67d2fa1d83c [file] [log] [blame]
scroggo478652e2015-03-25 07:11:02 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
mtklein748ca3b2015-01-15 10:56:12 -08008#include "DMSrcSink.h"
9#include "SamplePipeControllers.h"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkCodec.h"
mtkleina16e69e2015-05-05 11:38:45 -070011#include "SkCommonFlags.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070012#include "SkData.h"
reed06a22f62015-05-05 08:11:33 -070013#include "SkDeferredCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080014#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080015#include "SkError.h"
mtkleine44b5082015-05-07 10:53:34 -070016#include "SkFunction.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070017#include "SkImageGenerator.h"
mtklein748ca3b2015-01-15 10:56:12 -080018#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080019#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080020#include "SkOSFile.h"
mtkleinffa901a2015-03-16 10:38:07 -070021#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080022#include "SkPictureRecorder.h"
23#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070024#include "SkRecordDraw.h"
25#include "SkRecorder.h"
fmalita2aafe6f2015-02-06 12:51:10 -080026#include "SkSVGCanvas.h"
mtkleina16e69e2015-05-05 11:38:45 -070027#include "SkScanlineDecoder.h"
scroggoa1193e42015-01-21 12:09:53 -080028#include "SkStream.h"
fmalita2aafe6f2015-02-06 12:51:10 -080029#include "SkXMLWriter.h"
mtklein748ca3b2015-01-15 10:56:12 -080030
halcanary7e798182015-04-14 14:06:18 -070031DEFINE_bool(multiPage, false, "For document-type backends, render the source"
32 " into multiple pages");
33
mtkleinb3e5e4d2015-03-25 13:13:43 -070034static bool lazy_decode_bitmap(const void* src, size_t size, SkBitmap* dst) {
35 SkAutoTUnref<SkData> encoded(SkData::NewWithCopy(src, size));
36 return encoded && SkInstallDiscardablePixelRef(encoded, dst);
37}
38
mtklein748ca3b2015-01-15 10:56:12 -080039namespace DM {
40
mtklein748ca3b2015-01-15 10:56:12 -080041GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
42
43Error GMSrc::draw(SkCanvas* canvas) const {
44 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
45 canvas->concat(gm->getInitialTransform());
46 gm->draw(canvas);
47 return "";
48}
49
50SkISize GMSrc::size() const {
51 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
52 return gm->getISize();
53}
54
55Name GMSrc::name() const {
56 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
57 return gm->getName();
58}
59
bsalomon4ee6bd82015-05-27 13:23:23 -070060void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
61 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
62 gm->modifyGrContextOptions(options);
63}
64
mtklein748ca3b2015-01-15 10:56:12 -080065/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
66
msarett0a242972015-06-11 14:27:27 -070067CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -070068 : fPath(path)
69 , fMode(mode)
70 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -070071 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -070072{}
mtklein748ca3b2015-01-15 10:56:12 -080073
mtklein99cab4e2015-07-31 06:43:04 -070074bool CodecSrc::veto(SinkFlags flags) const {
75 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -070076 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
77 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -070078 return flags.type != SinkFlags::kRaster
79 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -070080}
scroggo9b77ddd2015-03-19 06:03:39 -070081
mtkleine0effd62015-07-29 06:37:28 -070082Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -080083 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080084 if (!encoded) {
85 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
86 }
scroggo9b77ddd2015-03-19 06:03:39 -070087 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett438b2ad2015-04-09 12:43:10 -070088 if (NULL == codec.get()) {
89 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -070090 }
91
msarett438b2ad2015-04-09 12:43:10 -070092 // Choose the color type to decode to
93 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -070094 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -070095 switch (fDstColorType) {
96 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -070097 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
98 if (kRGB_565_SkColorType == canvasColorType) {
99 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
100 }
101 break;
msarett438b2ad2015-04-09 12:43:10 -0700102 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700103 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700104 if (kRGB_565_SkColorType == canvasColorType) {
105 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
106 }
107 break;
108 default:
109 decodeInfo = decodeInfo.makeColorType(canvasColorType);
110 break;
111 }
112
msarett0a242972015-06-11 14:27:27 -0700113 // Try to scale the image if it is desired
114 SkISize size = codec->getScaledDimensions(fScale);
115 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
116 return Error::Nonfatal("Test without scaling is uninteresting.");
117 }
118 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
119
msarett438b2ad2015-04-09 12:43:10 -0700120 // Construct a color table for the decode if necessary
121 SkAutoTUnref<SkColorTable> colorTable(NULL);
122 SkPMColor* colorPtr = NULL;
123 int* colorCountPtr = NULL;
124 int maxColors = 256;
125 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
126 SkPMColor colors[256];
127 colorTable.reset(SkNEW_ARGS(SkColorTable, (colors, maxColors)));
128 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
129 colorCountPtr = &maxColors;
130 }
131
132 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700133 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700134 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
135 }
136
137 SkBitmap bitmap;
msarett438b2ad2015-04-09 12:43:10 -0700138 if (!bitmap.tryAllocPixels(decodeInfo, NULL, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700139 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
140 decodeInfo.width(), decodeInfo.height());
141 }
142
scroggo9c59ebc2015-03-25 13:48:49 -0700143 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700144 case kNormal_Mode: {
msarett438b2ad2015-04-09 12:43:10 -0700145 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), NULL,
146 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700147 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700148 // We consider incomplete to be valid, since we should still decode what is
149 // available.
scroggoeb602a52015-07-09 08:16:03 -0700150 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700151 break;
scroggoeb602a52015-07-09 08:16:03 -0700152 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700153 return Error::Nonfatal("Incompatible colortype conversion");
154 default:
155 // Everything else is considered a failure.
156 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
157 }
emmaleer97002062015-05-27 12:36:10 -0700158 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700159 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700160 }
scroggo9c59ebc2015-03-25 13:48:49 -0700161 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700162 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
163 SkScanlineDecoder::NewFromData(encoded));
164 if (NULL == scanlineDecoder || SkCodec::kSuccess !=
165 scanlineDecoder->start(decodeInfo, NULL, colorPtr, colorCountPtr)) {
scroggo9c59ebc2015-03-25 13:48:49 -0700166 return Error::Nonfatal("Cannot use scanline decoder for all images");
167 }
scroggo1c005e42015-08-04 09:24:45 -0700168
scroggoeb602a52015-07-09 08:16:03 -0700169 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700170 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
171 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700172 case SkCodec::kSuccess:
173 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700174 break;
175 default:
176 return SkStringPrintf("%s failed with error message %d",
177 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700178 }
emmaleer97002062015-05-27 12:36:10 -0700179 canvas->drawBitmap(bitmap, 0, 0);
180 break;
181 }
182 case kScanline_Subset_Mode: {
183 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
184 const int divisor = 2;
185 const int w = decodeInfo.width();
186 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700187 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700188 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
189 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700190 }
191 const int subsetWidth = w/divisor;
192 const int subsetHeight = h/divisor;
193 // One of our subsets will be larger to contain any pixels that do not divide evenly.
194 const int extraX = w % divisor;
195 const int extraY = h % divisor;
196 /*
197 * if w or h are not evenly divided by divisor need to adjust width and height of end
198 * subsets to cover entire image.
199 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
200 * and height of end subsets.
201 * subsetBm is extracted from largestSubsetBm.
202 * subsetBm's size is determined based on the current subset and may be larger for end
203 * subsets.
204 */
msarett0a242972015-06-11 14:27:27 -0700205 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700206 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
207 SkBitmap largestSubsetBm;
208 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, NULL, colorTable.get())) {
209 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
210 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
211 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700212 const size_t rowBytes = decodeInfo.minRowBytes();
213 char* buffer = SkNEW_ARRAY(char, largestSubsetDecodeInfo.height() * rowBytes);
214 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700215 for (int col = 0; col < divisor; col++) {
216 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
217 const int currentSubsetWidth = (col + 1 == divisor) ?
218 subsetWidth + extraX : subsetWidth;
219 const int x = col * subsetWidth;
220 for (int row = 0; row < divisor; row++) {
221 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
222 const int currentSubsetHeight = (row + 1 == divisor) ?
223 subsetHeight + extraY : subsetHeight;
224 const int y = row * subsetHeight;
225 //create scanline decoder for each subset
scroggo9b2cdbf42015-07-10 12:07:02 -0700226 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
scroggo1c005e42015-08-04 09:24:45 -0700227 SkScanlineDecoder::NewFromData(encoded));
228 if (NULL == subsetScanlineDecoder || SkCodec::kSuccess !=
229 subsetScanlineDecoder->start(
230 decodeInfo, NULL, colorPtr, colorCountPtr))
231 {
emmaleer97002062015-05-27 12:36:10 -0700232 if (x == 0 && y == 0) {
233 //first try, image may not be compatible
234 return Error::Nonfatal("Cannot use scanline decoder for all images");
235 } else {
236 return "Error scanline decoder is NULL";
237 }
238 }
239 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700240 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700241 subsetScanlineDecoder->skipScanlines(y);
242 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700243 case SkCodec::kSuccess:
244 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700245 break;
246 default:
247 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
248 "with error message %d", fPath.c_str(), y, (int) skipResult);
249 }
250 //create and set size of subsetBm
251 SkBitmap subsetBm;
252 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
253 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
254 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
255 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700256 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700257 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
258 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700259 case SkCodec::kSuccess:
260 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700261 break;
262 default:
mtkleind2baa902015-07-07 09:43:28 -0700263 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700264 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700265 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700266 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700267 /*
268 * we copy all the lines at once becuase when calling getScanlines for
269 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700270 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
271 * decode the entire image height times, which is very slow
272 * it is aknowledged that copying each line as you read it in a loop
273 * may be faster for other types of images. Since this is a correctness test
274 * that's okay.
275 */
mtkleind2baa902015-07-07 09:43:28 -0700276 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700277 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700278 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700279 currentSubsetWidth*bpp);
280 bufferRow += rowBytes;
281 }
mtkleind2baa902015-07-07 09:43:28 -0700282
scroggo4358f132015-07-30 11:33:04 -0700283 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700284 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
285 }
286 }
scroggo9c59ebc2015-03-25 13:48:49 -0700287 break;
288 }
msarett0a242972015-06-11 14:27:27 -0700289 case kStripe_Mode: {
290 const int height = decodeInfo.height();
291 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
292 // does not align with image blocks.
293 const int stripeHeight = 37;
294 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
295
296 // Decode odd stripes
scroggo1c005e42015-08-04 09:24:45 -0700297 SkAutoTDelete<SkScanlineDecoder> decoder(SkScanlineDecoder::NewFromData(encoded));
298 if (NULL == decoder || SkCodec::kSuccess !=
299 decoder->start(decodeInfo, NULL, colorPtr, colorCountPtr)) {
msarett0a242972015-06-11 14:27:27 -0700300 return Error::Nonfatal("Cannot use scanline decoder for all images");
301 }
302 for (int i = 0; i < numStripes; i += 2) {
303 // Skip a stripe
304 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700305 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700306 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700307 case SkCodec::kSuccess:
308 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700309 break;
310 default:
311 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
312 }
313
314 // Read a stripe
315 const int startY = (i + 1) * stripeHeight;
316 const int linesToRead = SkTMin(stripeHeight, height - startY);
317 if (linesToRead > 0) {
318 result = decoder->getScanlines(bitmap.getAddr(0, startY),
319 linesToRead, bitmap.rowBytes());
320 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700321 case SkCodec::kSuccess:
322 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700323 break;
324 default:
325 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
326 }
327 }
328 }
329
330 // Decode even stripes
scroggo1c005e42015-08-04 09:24:45 -0700331 const SkCodec::Result startResult = decoder->start(decodeInfo, NULL, colorPtr,
332 colorCountPtr);
333 if (SkCodec::kSuccess != startResult) {
334 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700335 }
336 for (int i = 0; i < numStripes; i += 2) {
337 // Read a stripe
338 const int startY = i * stripeHeight;
339 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700340 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700341 linesToRead, bitmap.rowBytes());
342 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700343 case SkCodec::kSuccess:
344 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700345 break;
346 default:
347 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
348 }
349
350 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700351 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
352 if (linesToSkip > 0) {
353 result = decoder->skipScanlines(linesToSkip);
354 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700355 case SkCodec::kSuccess:
356 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700357 break;
358 default:
359 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
360 }
msarett0a242972015-06-11 14:27:27 -0700361 }
362 }
363 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700364 break;
msarett0a242972015-06-11 14:27:27 -0700365 }
scroggob636b452015-07-22 07:16:20 -0700366 case kSubset_Mode: {
367 // Arbitrarily choose a divisor.
368 int divisor = 2;
369 // Total width/height of the image.
370 const int W = codec->getInfo().width();
371 const int H = codec->getInfo().height();
372 if (divisor > W || divisor > H) {
373 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
374 "for %s with dimensions (%d x %d)", divisor,
375 fPath.c_str(), W, H));
376 }
377 // subset dimensions
378 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
379 const int w = SkAlign2(W / divisor);
380 const int h = SkAlign2(H / divisor);
381 SkIRect subset;
382 SkCodec::Options opts;
383 opts.fSubset = &subset;
384 SkBitmap subsetBm;
385 // We will reuse pixel memory from bitmap.
386 void* pixels = bitmap.getPixels();
387 // Keep track of left and top (for drawing subsetBm into canvas). We could use
388 // fScale * x and fScale * y, but we want integers such that the next subset will start
389 // where the last one ended. So we'll add decodeInfo.width() and height().
390 int left = 0;
391 for (int x = 0; x < W; x += w) {
392 int top = 0;
393 for (int y = 0; y < H; y+= h) {
394 // Do not make the subset go off the edge of the image.
395 const int preScaleW = SkTMin(w, W - x);
396 const int preScaleH = SkTMin(h, H - y);
397 subset.setXYWH(x, y, preScaleW, preScaleH);
398 // And scale
399 // FIXME: Should we have a version of getScaledDimensions that takes a subset
400 // into account?
401 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
402 SkScalarRoundToInt(preScaleH * fScale));
403 size_t rowBytes = decodeInfo.minRowBytes();
404 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
405 NULL, NULL)) {
406 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
407 }
408 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
409 &opts, colorPtr, colorCountPtr);
410 switch (result) {
411 case SkCodec::kSuccess:
412 case SkCodec::kIncompleteInput:
413 break;
414 case SkCodec::kInvalidConversion:
415 if (0 == (x|y)) {
416 // First subset is okay to return unimplemented.
417 return Error::Nonfatal("Incompatible colortype conversion");
418 }
419 // If the first subset succeeded, a later one should not fail.
420 // fall through to failure
421 case SkCodec::kUnimplemented:
422 if (0 == (x|y)) {
423 // First subset is okay to return unimplemented.
424 return Error::Nonfatal("subset codec not supported");
425 }
426 // If the first subset succeeded, why would a later one fail?
427 // fall through to failure
428 default:
429 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
430 "from %s with dimensions (%d x %d)\t error %d",
431 x, y, decodeInfo.width(), decodeInfo.height(),
432 fPath.c_str(), W, H, result);
433 }
434 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
435 // translate by the scaled height.
436 top += decodeInfo.height();
437 }
438 // translate by the scaled width.
439 left += decodeInfo.width();
440 }
441 return "";
442 }
scroggo9b77ddd2015-03-19 06:03:39 -0700443 }
scroggo9c59ebc2015-03-25 13:48:49 -0700444 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700445}
446
447SkISize CodecSrc::size() const {
448 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
449 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(encoded));
msarett9bde9182015-03-25 05:27:48 -0700450 if (NULL != codec) {
msarett0a242972015-06-11 14:27:27 -0700451 SkISize size = codec->getScaledDimensions(fScale);
452 return size;
msarett9bde9182015-03-25 05:27:48 -0700453 } else {
454 return SkISize::Make(0, 0);
455 }
scroggo9b77ddd2015-03-19 06:03:39 -0700456}
457
458Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700459 if (1.0f == fScale) {
460 return SkOSPath::Basename(fPath.c_str());
461 } else {
462 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
463 }
scroggo9b77ddd2015-03-19 06:03:39 -0700464}
465
466/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
467
468ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
469
mtklein99cab4e2015-07-31 06:43:04 -0700470bool ImageSrc::veto(SinkFlags flags) const {
471 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700472 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700473 return flags.type != SinkFlags::kRaster
474 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700475}
scroggo9b77ddd2015-03-19 06:03:39 -0700476
mtkleine0effd62015-07-29 06:37:28 -0700477Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700478 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
479 if (!encoded) {
480 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
481 }
mtkleine0effd62015-07-29 06:37:28 -0700482 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800483 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800484 // Decode the full image.
485 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700486 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
487 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
488 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
489 }
490 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
491 // Do not draw a bitmap with alpha to a destination without alpha.
492 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800493 }
mtklein75d98fd2015-01-18 07:05:01 -0800494 encoded.reset((SkData*)NULL); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800495 canvas->drawBitmap(bitmap, 0,0);
496 return "";
497 }
mtkleinedc93bc2015-01-30 13:22:23 -0800498 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800499 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
500 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800501 if (!decoder) {
502 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
503 }
scroggoa1193e42015-01-21 12:09:53 -0800504 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800505 int w,h;
msarett70542572015-06-19 07:44:05 -0700506 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800507 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800508 }
mtkleinedc93bc2015-01-30 13:22:23 -0800509
510 // Divide the image into subsets that cover the entire image.
511 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700512 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
513 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800514 }
515 const int subsetWidth = w / fDivisor,
516 subsetHeight = h / fDivisor;
517 for (int y = 0; y < h; y += subsetHeight) {
518 for (int x = 0; x < w; x += subsetWidth) {
519 SkBitmap subset;
520 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
521 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
522 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
523 x, y, x+subsetWidth, y+subsetHeight);
524 }
scroggo56e25dd2015-03-05 11:46:40 -0800525 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
526 // Do not draw a bitmap with alpha to a destination without alpha.
527 // This is not an error, but there is nothing interesting to show.
528
529 // This should only happen on the first iteration through the loop.
530 SkASSERT(0 == x && 0 == y);
531
532 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
533 }
mtkleinedc93bc2015-01-30 13:22:23 -0800534 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800535 }
mtklein748ca3b2015-01-15 10:56:12 -0800536 }
537 return "";
538}
539
540SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800541 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700542 SkBitmap bitmap;
543 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
544 encoded->size(),
545 &bitmap,
546 kUnknown_SkColorType,
547 SkImageDecoder::kDecodeBounds_Mode)) {
548 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800549 }
scroggo9b77ddd2015-03-19 06:03:39 -0700550 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800551}
552
mtklein9264a952015-01-20 10:11:53 -0800553Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800554 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800555}
mtklein748ca3b2015-01-15 10:56:12 -0800556
557/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
558
mtkleinf4ba3212015-01-28 15:32:24 -0800559static const SkRect kSKPViewport = {0,0, 1000,1000};
560
mtklein8d17a132015-01-30 11:42:31 -0800561SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800562
563Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800564 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800565 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800566 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
567 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700568 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800569 if (!pic) {
570 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
571 }
572 stream.reset((SkStream*)NULL); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700573
mtkleinf4ba3212015-01-28 15:32:24 -0800574 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800575 canvas->drawPicture(pic);
576 return "";
577}
578
579SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700580 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
581 if (!stream) {
582 return SkISize::Make(0,0);
583 }
584 SkPictInfo info;
585 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
586 return SkISize::Make(0,0);
587 }
588 SkRect viewport = kSKPViewport;
589 if (!viewport.intersect(info.fCullRect)) {
590 return SkISize::Make(0,0);
591 }
592 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800593}
594
595Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
596
597/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
598
mtkleinad66f9b2015-02-13 15:11:10 -0800599Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
600 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
601 return src.draw(canvas);
602}
603
604/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
605
mtkleinb9eb4ac2015-02-02 18:26:03 -0800606DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
607
mtklein82d28432015-01-15 12:46:02 -0800608GPUSink::GPUSink(GrContextFactory::GLContextType ct,
609 GrGLStandard api,
610 int samples,
611 bool dfText,
612 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800613 : fContextType(ct)
614 , fGpuAPI(api)
615 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800616 , fUseDFText(dfText)
617 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800618
619int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800620 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800621}
622
joshualitt5f5a8d72015-02-25 14:09:45 -0800623void PreAbandonGpuContextErrorHandler(SkError, void*) {}
624
mtkleinb9eb4ac2015-02-02 18:26:03 -0800625Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700626 GrContextOptions options;
627 src.modifyGrContextOptions(&options);
628
629 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800630 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800631 const SkImageInfo info =
632 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
633 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800634 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800635 if (!surface) {
636 return "Could not create a surface.";
637 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800638 if (FLAGS_preAbandonGpuContext) {
639 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, NULL);
640 factory.abandonContexts();
641 }
mtklein748ca3b2015-01-15 10:56:12 -0800642 SkCanvas* canvas = surface->getCanvas();
643 Error err = src.draw(canvas);
644 if (!err.isEmpty()) {
645 return err;
646 }
647 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800648 if (FLAGS_gpuStats) {
649 canvas->getGrContext()->dumpCacheStats(log);
650 canvas->getGrContext()->dumpGpuStats(log);
651 }
mtklein748ca3b2015-01-15 10:56:12 -0800652 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800653 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800654 if (FLAGS_abandonGpuContext) {
655 factory.abandonContexts();
656 }
mtklein748ca3b2015-01-15 10:56:12 -0800657 return "";
658}
659
660/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
661
halcanary47ef4d52015-03-03 09:13:09 -0800662static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
663 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
664 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800665 int width = src.size().width(),
666 height = src.size().height();
667
halcanary7e798182015-04-14 14:06:18 -0700668 if (FLAGS_multiPage) {
669 const int kLetterWidth = 612, // 8.5 * 72
670 kLetterHeight = 792; // 11 * 72
671 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
672 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800673
halcanary7e798182015-04-14 14:06:18 -0700674 int xPages = ((width - 1) / kLetterWidth) + 1;
675 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800676
halcanary7e798182015-04-14 14:06:18 -0700677 for (int y = 0; y < yPages; ++y) {
678 for (int x = 0; x < xPages; ++x) {
679 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
680 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
681 SkCanvas* canvas =
682 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
683 if (!canvas) {
684 return "SkDocument::beginPage(w,h) returned NULL";
685 }
686 canvas->clipRect(letter);
687 canvas->translate(-letter.width() * x, -letter.height() * y);
688 Error err = src.draw(canvas);
689 if (!err.isEmpty()) {
690 return err;
691 }
692 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700693 }
halcanaryfd4a9932015-01-28 11:45:58 -0800694 }
halcanary7e798182015-04-14 14:06:18 -0700695 } else {
696 SkCanvas* canvas =
697 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
698 if (!canvas) {
699 return "SkDocument::beginPage(w,h) returned NULL";
700 }
701 Error err = src.draw(canvas);
702 if (!err.isEmpty()) {
703 return err;
704 }
705 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800706 }
halcanary7e798182015-04-14 14:06:18 -0700707 if (!doc->close()) {
708 return "SkDocument::close() returned false";
709 }
halcanaryfd4a9932015-01-28 11:45:58 -0800710 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800711 return "";
712}
713
halcanary47ef4d52015-03-03 09:13:09 -0800714PDFSink::PDFSink() {}
715
716Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
717 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
718 if (!doc) {
719 return "SkDocument::CreatePDF() returned NULL";
720 }
721 return draw_skdocument(src, doc.get(), dst);
722}
723
724/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
725
726XPSSink::XPSSink() {}
727
728Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
729 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
730 if (!doc) {
731 return "SkDocument::CreateXPS() returned NULL";
732 }
733 return draw_skdocument(src, doc.get(), dst);
734}
mtklein748ca3b2015-01-15 10:56:12 -0800735/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
736
mtklein9c3f17d2015-01-28 11:35:18 -0800737SKPSink::SKPSink() {}
738
mtkleinb9eb4ac2015-02-02 18:26:03 -0800739Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800740 SkSize size;
741 size = src.size();
742 SkPictureRecorder recorder;
743 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
744 if (!err.isEmpty()) {
745 return err;
746 }
747 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
748 pic->serialize(dst);
749 return "";
750}
751
752/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
753
mtklein8a4527e2015-01-31 20:00:58 -0800754SVGSink::SVGSink() {}
755
mtkleinb9eb4ac2015-02-02 18:26:03 -0800756Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita2aafe6f2015-02-06 12:51:10 -0800757 SkAutoTDelete<SkXMLWriter> xmlWriter(SkNEW_ARGS(SkXMLStreamWriter, (dst)));
758 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
759 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
760 xmlWriter));
761 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800762}
763
764/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
765
mtklein748ca3b2015-01-15 10:56:12 -0800766RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
767
mtkleinb9eb4ac2015-02-02 18:26:03 -0800768Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800769 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800770 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
771 SkAlphaType alphaType = kPremul_SkAlphaType;
772 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
773
774 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
775 dst->eraseColor(SK_ColorTRANSPARENT);
776 SkCanvas canvas(*dst);
777 return src.draw(&canvas);
778}
779
780/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
781
mtkleina16e69e2015-05-05 11:38:45 -0700782// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700783// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700784// Several examples below.
785
mtkleina16e69e2015-05-05 11:38:45 -0700786static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700787 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700788 class ProxySrc : public Src {
789 public:
mtkleine44b5082015-05-07 10:53:34 -0700790 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700791 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
792 Name name() const override { sk_throw(); return ""; } // Won't be called.
793 SkISize size() const override { return fSize; }
794 private:
mtkleine44b5082015-05-07 10:53:34 -0700795 SkISize fSize;
796 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700797 };
798 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
799}
800
801/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
802
mtkleind603b222015-02-17 11:13:33 -0800803static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
804 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
805 matrix->mapRect(&bounds);
806 matrix->postTranslate(-bounds.x(), -bounds.y());
807 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
808}
809
mtklein78829242015-05-06 07:54:07 -0700810ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800811
mtkleinb9eb4ac2015-02-02 18:26:03 -0800812Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700813 SkMatrix matrix = fMatrix;
814 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
815 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
816 canvas->concat(matrix);
817 return src.draw(canvas);
818 });
mtklein748ca3b2015-01-15 10:56:12 -0800819}
820
mtkleind603b222015-02-17 11:13:33 -0800821// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
822// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700823ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800824
825Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
826 Error err = fSink->draw(src, bitmap, stream, log);
827 if (!err.isEmpty()) {
828 return err;
829 }
830
831 SkMatrix inverse;
832 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
833 return "Cannot upright --matrix.";
834 }
835 SkMatrix upright = SkMatrix::I();
836 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
837 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
838 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
839 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
840
841 SkBitmap uprighted;
842 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
843 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
844
845 SkCanvas canvas(uprighted);
846 canvas.concat(upright);
847 SkPaint paint;
848 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
849 canvas.drawBitmap(*bitmap, 0, 0, &paint);
850
851 *bitmap = uprighted;
852 bitmap->lockPixels();
853 return "";
854}
855
mtklein748ca3b2015-01-15 10:56:12 -0800856/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
857
mtkleinb9eb4ac2015-02-02 18:26:03 -0800858Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700859 auto size = src.size();
860 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
861 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
862 SkGPipeWriter pipe;
863 const uint32_t kFlags = 0; // We mirror SkDeferredCanvas, which doesn't use any flags.
864 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
865 });
mtklein748ca3b2015-01-15 10:56:12 -0800866}
867
868/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700869
reed06a22f62015-05-05 08:11:33 -0700870Error ViaDeferred::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700871 // We draw via a deferred canvas into a surface that's compatible with the original canvas,
872 // then snap that surface as an image and draw it into the original canvas.
873 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
874 SkAutoTUnref<SkSurface> surface(canvas->newSurface(canvas->imageInfo()));
875 if (!surface.get()) {
876 return "can't make surface for deferred canvas";
reed06a22f62015-05-05 08:11:33 -0700877 }
mtkleina16e69e2015-05-05 11:38:45 -0700878 SkAutoTDelete<SkDeferredCanvas> defcan(SkDeferredCanvas::Create(surface));
879 Error err = src.draw(defcan);
880 if (!err.isEmpty()) {
881 return err;
882 }
883 SkAutoTUnref<SkImage> image(defcan->newImageSnapshot());
884 if (!image) {
885 return "failed to create deferred image snapshot";
886 }
887 canvas->drawImage(image, 0, 0, NULL);
888 return "";
889 });
reed06a22f62015-05-05 08:11:33 -0700890}
mtkleina16e69e2015-05-05 11:38:45 -0700891
reed06a22f62015-05-05 08:11:33 -0700892/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -0800893
mtkleina16e69e2015-05-05 11:38:45 -0700894Error ViaSerialization::draw(
895 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800896 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700897 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800898 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700899 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
900 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800901 if (!err.isEmpty()) {
902 return err;
903 }
904 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
905
906 // Serialize it and then deserialize it.
907 SkDynamicMemoryWStream wStream;
908 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800909 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700910 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800911
mtkleina16e69e2015-05-05 11:38:45 -0700912 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
913 canvas->drawPicture(deserialized);
914 return "";
915 });
mtklein748ca3b2015-01-15 10:56:12 -0800916}
917
918/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
919
920ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700921 : Via(sink)
922 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800923 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700924 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800925
mtkleinb9eb4ac2015-02-02 18:26:03 -0800926Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700927 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800928 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700929 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
930 SkIntToScalar(size.height()),
931 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800932 if (!err.isEmpty()) {
933 return err;
934 }
mtkleinb7e8d692015-04-07 08:30:32 -0700935 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800936
mtkleina16e69e2015-05-05 11:38:45 -0700937 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
938 const int xTiles = (size.width() + fW - 1) / fW,
939 yTiles = (size.height() + fH - 1) / fH;
940 SkMultiPictureDraw mpd(xTiles*yTiles);
941 SkTDArray<SkSurface*> surfaces;
942 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800943
mtkleina16e69e2015-05-05 11:38:45 -0700944 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
945 for (int j = 0; j < yTiles; j++) {
946 for (int i = 0; i < xTiles; i++) {
947 // This lets our ultimate Sink determine the best kind of surface.
948 // E.g., if it's a GpuSink, the surfaces and images are textures.
949 SkSurface* s = canvas->newSurface(info);
950 if (!s) {
951 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800952 }
mtkleina16e69e2015-05-05 11:38:45 -0700953 surfaces.push(s);
954 SkCanvas* c = s->getCanvas();
955 c->translate(SkIntToScalar(-i * fW),
956 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
957 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800958 }
mtklein748ca3b2015-01-15 10:56:12 -0800959 }
mtkleina16e69e2015-05-05 11:38:45 -0700960 mpd.draw();
961 for (int j = 0; j < yTiles; j++) {
962 for (int i = 0; i < xTiles; i++) {
963 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
964 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
965 }
966 }
967 surfaces.unrefAll();
968 return "";
969 });
mtklein748ca3b2015-01-15 10:56:12 -0800970}
971
mtkleinb7e8d692015-04-07 08:30:32 -0700972/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
973
mtkleinb7e8d692015-04-07 08:30:32 -0700974// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
975// This tests that any shortcuts we may take while recording that second picture are legal.
976Error ViaSecondPicture::draw(
977 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700978 auto size = src.size();
979 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
980 SkPictureRecorder recorder;
981 SkAutoTUnref<SkPicture> pic;
982 for (int i = 0; i < 2; i++) {
983 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
984 SkIntToScalar(size.height())));
985 if (!err.isEmpty()) {
986 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700987 }
mtkleina16e69e2015-05-05 11:38:45 -0700988 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700989 }
mtkleina16e69e2015-05-05 11:38:45 -0700990 canvas->drawPicture(pic);
991 return "";
992 });
mtkleinb7e8d692015-04-07 08:30:32 -0700993}
994
mtkleind31c13d2015-05-05 12:59:56 -0700995/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
996
mtklein6fbf4b32015-05-06 11:35:40 -0700997// Draw the Src twice. This can help exercise caching.
998Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
999 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1000 for (int i = 0; i < 2; i++) {
1001 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1002 canvas->clear(SK_ColorTRANSPARENT);
1003 Error err = src.draw(canvas);
1004 if (err.isEmpty()) {
1005 return err;
1006 }
1007 }
1008 return "";
1009 });
1010}
1011
1012/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1013
mtkleind31c13d2015-05-05 12:59:56 -07001014// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1015// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1016// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1017struct DrawsAsSingletonPictures {
1018 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001019 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001020
1021 SK_CREATE_MEMBER_DETECTOR(paint);
1022
1023 template <typename T>
1024 void draw(const T& op, SkCanvas* canvas) {
1025 // We must pass SkMatrix::I() as our initial matrix.
1026 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1027 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001028 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1029 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001030 }
1031
1032 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1033 template <typename T>
1034 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1035 SkPictureRecorder rec;
1036 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1037 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1038 fCanvas->drawPicture(pic);
1039 }
1040
1041 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1042 // We cannot make subpictures out of these because they affect state. Draw them directly.
1043 template <typename T>
1044 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1045 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1046};
1047
mtkleind31c13d2015-05-05 12:59:56 -07001048// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1049// Then play back that macro picture into our wrapped sink.
1050Error ViaSingletonPictures::draw(
1051 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1052 auto size = src.size();
1053 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1054 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1055 SkRecord skr;
1056 SkRecorder recorder(&skr, size.width(), size.height());
1057 Error err = src.draw(&recorder);
1058 if (!err.isEmpty()) {
1059 return err;
1060 }
1061
1062 // Record our macro-picture, with each draw op as its own sub-picture.
1063 SkPictureRecorder macroRec;
1064 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1065 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001066
1067 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1068 const SkDrawableList empty;
1069
1070 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1071 macroCanvas,
1072 drawables ? *drawables : empty,
1073 };
mtkleind31c13d2015-05-05 12:59:56 -07001074 for (unsigned i = 0; i < skr.count(); i++) {
1075 skr.visit<void>(i, drawsAsSingletonPictures);
1076 }
1077 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1078
1079 canvas->drawPicture(macroPic);
1080 return "";
1081 });
1082}
1083
mtklein748ca3b2015-01-15 10:56:12 -08001084} // namespace DM