blob: 9826f978224d74dfc5f543164fc84bb0121f7a02 [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"
emmaleer8f4ba762015-08-14 07:44:46 -070030#include "SkScaledCodec.h"
mtklein748ca3b2015-01-15 10:56:12 -080031
halcanary7e798182015-04-14 14:06:18 -070032DEFINE_bool(multiPage, false, "For document-type backends, render the source"
33 " into multiple pages");
34
mtkleinb3e5e4d2015-03-25 13:13:43 -070035static bool lazy_decode_bitmap(const void* src, size_t size, SkBitmap* dst) {
36 SkAutoTUnref<SkData> encoded(SkData::NewWithCopy(src, size));
37 return encoded && SkInstallDiscardablePixelRef(encoded, dst);
38}
39
mtklein748ca3b2015-01-15 10:56:12 -080040namespace DM {
41
mtklein748ca3b2015-01-15 10:56:12 -080042GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
43
44Error GMSrc::draw(SkCanvas* canvas) const {
45 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
46 canvas->concat(gm->getInitialTransform());
47 gm->draw(canvas);
48 return "";
49}
50
51SkISize GMSrc::size() const {
52 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
53 return gm->getISize();
54}
55
56Name GMSrc::name() const {
57 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
58 return gm->getName();
59}
60
bsalomon4ee6bd82015-05-27 13:23:23 -070061void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
62 SkAutoTDelete<skiagm::GM> gm(fFactory(NULL));
63 gm->modifyGrContextOptions(options);
64}
65
mtklein748ca3b2015-01-15 10:56:12 -080066/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
67
msarett0a242972015-06-11 14:27:27 -070068CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -070069 : fPath(path)
70 , fMode(mode)
71 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -070072 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -070073{}
mtklein748ca3b2015-01-15 10:56:12 -080074
mtklein99cab4e2015-07-31 06:43:04 -070075bool CodecSrc::veto(SinkFlags flags) const {
76 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -070077 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
78 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -070079 return flags.type != SinkFlags::kRaster
80 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -070081}
scroggo9b77ddd2015-03-19 06:03:39 -070082
mtkleine0effd62015-07-29 06:37:28 -070083Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -080084 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080085 if (!encoded) {
86 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
87 }
emmaleer8f4ba762015-08-14 07:44:46 -070088 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
msarett438b2ad2015-04-09 12:43:10 -070089 if (NULL == codec.get()) {
emmaleer8f4ba762015-08-14 07:44:46 -070090 // scaledCodec not supported, try normal codec
91 codec.reset(SkCodec::NewFromData(encoded));
92 if (NULL == codec.get()) {
93 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
94 }
scroggo9b77ddd2015-03-19 06:03:39 -070095 }
96
msarett438b2ad2015-04-09 12:43:10 -070097 // Choose the color type to decode to
98 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -070099 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -0700100 switch (fDstColorType) {
101 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700102 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
103 if (kRGB_565_SkColorType == canvasColorType) {
104 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
105 }
106 break;
msarett438b2ad2015-04-09 12:43:10 -0700107 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700108 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700109 if (kRGB_565_SkColorType == canvasColorType) {
110 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
111 }
112 break;
113 default:
114 decodeInfo = decodeInfo.makeColorType(canvasColorType);
115 break;
116 }
117
msarett0a242972015-06-11 14:27:27 -0700118 // Try to scale the image if it is desired
119 SkISize size = codec->getScaledDimensions(fScale);
120 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
121 return Error::Nonfatal("Test without scaling is uninteresting.");
122 }
123 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
124
msarett438b2ad2015-04-09 12:43:10 -0700125 // Construct a color table for the decode if necessary
126 SkAutoTUnref<SkColorTable> colorTable(NULL);
127 SkPMColor* colorPtr = NULL;
128 int* colorCountPtr = NULL;
129 int maxColors = 256;
130 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
131 SkPMColor colors[256];
132 colorTable.reset(SkNEW_ARGS(SkColorTable, (colors, maxColors)));
133 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
134 colorCountPtr = &maxColors;
135 }
136
137 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700138 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700139 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
140 }
141
142 SkBitmap bitmap;
msarett438b2ad2015-04-09 12:43:10 -0700143 if (!bitmap.tryAllocPixels(decodeInfo, NULL, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700144 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
145 decodeInfo.width(), decodeInfo.height());
146 }
147
scroggo9c59ebc2015-03-25 13:48:49 -0700148 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700149 case kNormal_Mode: {
msarett438b2ad2015-04-09 12:43:10 -0700150 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), NULL,
151 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700152 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700153 // We consider incomplete to be valid, since we should still decode what is
154 // available.
scroggoeb602a52015-07-09 08:16:03 -0700155 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700156 break;
scroggoeb602a52015-07-09 08:16:03 -0700157 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700158 return Error::Nonfatal("Incompatible colortype conversion");
159 default:
160 // Everything else is considered a failure.
161 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
162 }
emmaleer97002062015-05-27 12:36:10 -0700163 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700164 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700165 }
scroggo9c59ebc2015-03-25 13:48:49 -0700166 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700167 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
168 SkScanlineDecoder::NewFromData(encoded));
169 if (NULL == scanlineDecoder || SkCodec::kSuccess !=
170 scanlineDecoder->start(decodeInfo, NULL, colorPtr, colorCountPtr)) {
scroggo9c59ebc2015-03-25 13:48:49 -0700171 return Error::Nonfatal("Cannot use scanline decoder for all images");
172 }
scroggo1c005e42015-08-04 09:24:45 -0700173
scroggoeb602a52015-07-09 08:16:03 -0700174 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700175 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
176 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700177 case SkCodec::kSuccess:
178 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700179 break;
180 default:
181 return SkStringPrintf("%s failed with error message %d",
182 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700183 }
emmaleer97002062015-05-27 12:36:10 -0700184 canvas->drawBitmap(bitmap, 0, 0);
185 break;
186 }
187 case kScanline_Subset_Mode: {
188 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
189 const int divisor = 2;
190 const int w = decodeInfo.width();
191 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700192 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700193 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
194 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700195 }
196 const int subsetWidth = w/divisor;
197 const int subsetHeight = h/divisor;
198 // One of our subsets will be larger to contain any pixels that do not divide evenly.
199 const int extraX = w % divisor;
200 const int extraY = h % divisor;
201 /*
202 * if w or h are not evenly divided by divisor need to adjust width and height of end
203 * subsets to cover entire image.
204 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
205 * and height of end subsets.
206 * subsetBm is extracted from largestSubsetBm.
207 * subsetBm's size is determined based on the current subset and may be larger for end
208 * subsets.
209 */
msarett0a242972015-06-11 14:27:27 -0700210 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700211 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
212 SkBitmap largestSubsetBm;
213 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, NULL, colorTable.get())) {
214 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
215 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
216 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700217 const size_t rowBytes = decodeInfo.minRowBytes();
218 char* buffer = SkNEW_ARRAY(char, largestSubsetDecodeInfo.height() * rowBytes);
219 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700220 for (int col = 0; col < divisor; col++) {
221 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
222 const int currentSubsetWidth = (col + 1 == divisor) ?
223 subsetWidth + extraX : subsetWidth;
224 const int x = col * subsetWidth;
225 for (int row = 0; row < divisor; row++) {
226 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
227 const int currentSubsetHeight = (row + 1 == divisor) ?
228 subsetHeight + extraY : subsetHeight;
229 const int y = row * subsetHeight;
230 //create scanline decoder for each subset
scroggo9b2cdbf2015-07-10 12:07:02 -0700231 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
scroggo1c005e42015-08-04 09:24:45 -0700232 SkScanlineDecoder::NewFromData(encoded));
233 if (NULL == subsetScanlineDecoder || SkCodec::kSuccess !=
234 subsetScanlineDecoder->start(
235 decodeInfo, NULL, colorPtr, colorCountPtr))
236 {
emmaleer97002062015-05-27 12:36:10 -0700237 if (x == 0 && y == 0) {
238 //first try, image may not be compatible
239 return Error::Nonfatal("Cannot use scanline decoder for all images");
240 } else {
241 return "Error scanline decoder is NULL";
242 }
243 }
244 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700245 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700246 subsetScanlineDecoder->skipScanlines(y);
247 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700248 case SkCodec::kSuccess:
249 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700250 break;
251 default:
252 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
253 "with error message %d", fPath.c_str(), y, (int) skipResult);
254 }
255 //create and set size of subsetBm
256 SkBitmap subsetBm;
257 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
258 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
259 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
260 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700261 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700262 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
263 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700264 case SkCodec::kSuccess:
265 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700266 break;
267 default:
mtkleind2baa902015-07-07 09:43:28 -0700268 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700269 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700270 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700271 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700272 /*
273 * we copy all the lines at once becuase when calling getScanlines for
274 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700275 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
276 * decode the entire image height times, which is very slow
277 * it is aknowledged that copying each line as you read it in a loop
278 * may be faster for other types of images. Since this is a correctness test
279 * that's okay.
280 */
mtkleind2baa902015-07-07 09:43:28 -0700281 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700282 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700283 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700284 currentSubsetWidth*bpp);
285 bufferRow += rowBytes;
286 }
mtkleind2baa902015-07-07 09:43:28 -0700287
scroggo4358f132015-07-30 11:33:04 -0700288 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700289 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
290 }
291 }
scroggo9c59ebc2015-03-25 13:48:49 -0700292 break;
293 }
msarett0a242972015-06-11 14:27:27 -0700294 case kStripe_Mode: {
295 const int height = decodeInfo.height();
296 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
297 // does not align with image blocks.
298 const int stripeHeight = 37;
299 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
300
301 // Decode odd stripes
scroggo1c005e42015-08-04 09:24:45 -0700302 SkAutoTDelete<SkScanlineDecoder> decoder(SkScanlineDecoder::NewFromData(encoded));
303 if (NULL == decoder || SkCodec::kSuccess !=
304 decoder->start(decodeInfo, NULL, colorPtr, colorCountPtr)) {
msarett0a242972015-06-11 14:27:27 -0700305 return Error::Nonfatal("Cannot use scanline decoder for all images");
306 }
307 for (int i = 0; i < numStripes; i += 2) {
308 // Skip a stripe
309 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700310 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700311 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700312 case SkCodec::kSuccess:
313 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700314 break;
315 default:
316 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
317 }
318
319 // Read a stripe
320 const int startY = (i + 1) * stripeHeight;
321 const int linesToRead = SkTMin(stripeHeight, height - startY);
322 if (linesToRead > 0) {
323 result = decoder->getScanlines(bitmap.getAddr(0, startY),
324 linesToRead, bitmap.rowBytes());
325 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700326 case SkCodec::kSuccess:
327 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700328 break;
329 default:
330 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
331 }
332 }
333 }
334
335 // Decode even stripes
scroggo1c005e42015-08-04 09:24:45 -0700336 const SkCodec::Result startResult = decoder->start(decodeInfo, NULL, colorPtr,
337 colorCountPtr);
338 if (SkCodec::kSuccess != startResult) {
339 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700340 }
341 for (int i = 0; i < numStripes; i += 2) {
342 // Read a stripe
343 const int startY = i * stripeHeight;
344 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700345 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700346 linesToRead, bitmap.rowBytes());
347 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700348 case SkCodec::kSuccess:
349 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700350 break;
351 default:
352 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
353 }
354
355 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700356 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
357 if (linesToSkip > 0) {
358 result = decoder->skipScanlines(linesToSkip);
359 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700360 case SkCodec::kSuccess:
361 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700362 break;
363 default:
364 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
365 }
msarett0a242972015-06-11 14:27:27 -0700366 }
367 }
368 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700369 break;
msarett0a242972015-06-11 14:27:27 -0700370 }
scroggob636b452015-07-22 07:16:20 -0700371 case kSubset_Mode: {
372 // Arbitrarily choose a divisor.
373 int divisor = 2;
374 // Total width/height of the image.
375 const int W = codec->getInfo().width();
376 const int H = codec->getInfo().height();
377 if (divisor > W || divisor > H) {
378 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
379 "for %s with dimensions (%d x %d)", divisor,
380 fPath.c_str(), W, H));
381 }
382 // subset dimensions
383 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
384 const int w = SkAlign2(W / divisor);
385 const int h = SkAlign2(H / divisor);
386 SkIRect subset;
387 SkCodec::Options opts;
388 opts.fSubset = &subset;
389 SkBitmap subsetBm;
390 // We will reuse pixel memory from bitmap.
391 void* pixels = bitmap.getPixels();
392 // Keep track of left and top (for drawing subsetBm into canvas). We could use
393 // fScale * x and fScale * y, but we want integers such that the next subset will start
394 // where the last one ended. So we'll add decodeInfo.width() and height().
395 int left = 0;
396 for (int x = 0; x < W; x += w) {
397 int top = 0;
398 for (int y = 0; y < H; y+= h) {
399 // Do not make the subset go off the edge of the image.
400 const int preScaleW = SkTMin(w, W - x);
401 const int preScaleH = SkTMin(h, H - y);
402 subset.setXYWH(x, y, preScaleW, preScaleH);
403 // And scale
404 // FIXME: Should we have a version of getScaledDimensions that takes a subset
405 // into account?
406 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
407 SkScalarRoundToInt(preScaleH * fScale));
408 size_t rowBytes = decodeInfo.minRowBytes();
409 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
410 NULL, NULL)) {
411 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
412 }
413 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
414 &opts, colorPtr, colorCountPtr);
415 switch (result) {
416 case SkCodec::kSuccess:
417 case SkCodec::kIncompleteInput:
418 break;
419 case SkCodec::kInvalidConversion:
420 if (0 == (x|y)) {
421 // First subset is okay to return unimplemented.
422 return Error::Nonfatal("Incompatible colortype conversion");
423 }
424 // If the first subset succeeded, a later one should not fail.
425 // fall through to failure
426 case SkCodec::kUnimplemented:
427 if (0 == (x|y)) {
428 // First subset is okay to return unimplemented.
429 return Error::Nonfatal("subset codec not supported");
430 }
431 // If the first subset succeeded, why would a later one fail?
432 // fall through to failure
433 default:
434 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
435 "from %s with dimensions (%d x %d)\t error %d",
436 x, y, decodeInfo.width(), decodeInfo.height(),
437 fPath.c_str(), W, H, result);
438 }
439 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
440 // translate by the scaled height.
441 top += decodeInfo.height();
442 }
443 // translate by the scaled width.
444 left += decodeInfo.width();
445 }
446 return "";
447 }
scroggo9b77ddd2015-03-19 06:03:39 -0700448 }
scroggo9c59ebc2015-03-25 13:48:49 -0700449 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700450}
451
452SkISize CodecSrc::size() const {
453 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700454 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
455 if (NULL == codec) {
456 // scaledCodec not supported, try regular codec
457 codec.reset(SkCodec::NewFromData(encoded));
458 if (NULL == codec) {
459 return SkISize::Make(0, 0);
460 }
msarett9bde9182015-03-25 05:27:48 -0700461 }
emmaleer8f4ba762015-08-14 07:44:46 -0700462 SkISize size = codec->getScaledDimensions(fScale);
463 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700464}
465
466Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700467 if (1.0f == fScale) {
468 return SkOSPath::Basename(fPath.c_str());
469 } else {
470 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
471 }
scroggo9b77ddd2015-03-19 06:03:39 -0700472}
473
474/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
475
476ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
477
mtklein99cab4e2015-07-31 06:43:04 -0700478bool ImageSrc::veto(SinkFlags flags) const {
479 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700480 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700481 return flags.type != SinkFlags::kRaster
482 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700483}
scroggo9b77ddd2015-03-19 06:03:39 -0700484
mtkleine0effd62015-07-29 06:37:28 -0700485Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700486 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
487 if (!encoded) {
488 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
489 }
mtkleine0effd62015-07-29 06:37:28 -0700490 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800491 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800492 // Decode the full image.
493 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700494 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
495 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
496 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
497 }
498 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
499 // Do not draw a bitmap with alpha to a destination without alpha.
500 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800501 }
mtklein75d98fd2015-01-18 07:05:01 -0800502 encoded.reset((SkData*)NULL); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800503 canvas->drawBitmap(bitmap, 0,0);
504 return "";
505 }
mtkleinedc93bc2015-01-30 13:22:23 -0800506 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800507 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
508 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800509 if (!decoder) {
510 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
511 }
scroggoa1193e42015-01-21 12:09:53 -0800512 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800513 int w,h;
msarett70542572015-06-19 07:44:05 -0700514 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800515 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800516 }
mtkleinedc93bc2015-01-30 13:22:23 -0800517
518 // Divide the image into subsets that cover the entire image.
519 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700520 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
521 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800522 }
523 const int subsetWidth = w / fDivisor,
524 subsetHeight = h / fDivisor;
525 for (int y = 0; y < h; y += subsetHeight) {
526 for (int x = 0; x < w; x += subsetWidth) {
527 SkBitmap subset;
528 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
529 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
530 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
531 x, y, x+subsetWidth, y+subsetHeight);
532 }
scroggo56e25dd2015-03-05 11:46:40 -0800533 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
534 // Do not draw a bitmap with alpha to a destination without alpha.
535 // This is not an error, but there is nothing interesting to show.
536
537 // This should only happen on the first iteration through the loop.
538 SkASSERT(0 == x && 0 == y);
539
540 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
541 }
mtkleinedc93bc2015-01-30 13:22:23 -0800542 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800543 }
mtklein748ca3b2015-01-15 10:56:12 -0800544 }
545 return "";
546}
547
548SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800549 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700550 SkBitmap bitmap;
551 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
552 encoded->size(),
553 &bitmap,
554 kUnknown_SkColorType,
555 SkImageDecoder::kDecodeBounds_Mode)) {
556 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800557 }
scroggo9b77ddd2015-03-19 06:03:39 -0700558 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800559}
560
mtklein9264a952015-01-20 10:11:53 -0800561Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800562 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800563}
mtklein748ca3b2015-01-15 10:56:12 -0800564
565/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
566
mtkleinf4ba3212015-01-28 15:32:24 -0800567static const SkRect kSKPViewport = {0,0, 1000,1000};
568
mtklein8d17a132015-01-30 11:42:31 -0800569SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800570
571Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800572 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800573 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800574 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
575 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700576 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800577 if (!pic) {
578 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
579 }
580 stream.reset((SkStream*)NULL); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700581
mtkleinf4ba3212015-01-28 15:32:24 -0800582 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800583 canvas->drawPicture(pic);
584 return "";
585}
586
587SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700588 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
589 if (!stream) {
590 return SkISize::Make(0,0);
591 }
592 SkPictInfo info;
593 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
594 return SkISize::Make(0,0);
595 }
596 SkRect viewport = kSKPViewport;
597 if (!viewport.intersect(info.fCullRect)) {
598 return SkISize::Make(0,0);
599 }
600 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800601}
602
603Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
604
605/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
606
mtkleinad66f9b2015-02-13 15:11:10 -0800607Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
608 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
609 return src.draw(canvas);
610}
611
612/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
613
mtkleinb9eb4ac2015-02-02 18:26:03 -0800614DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
615
mtklein82d28432015-01-15 12:46:02 -0800616GPUSink::GPUSink(GrContextFactory::GLContextType ct,
617 GrGLStandard api,
618 int samples,
619 bool dfText,
620 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800621 : fContextType(ct)
622 , fGpuAPI(api)
623 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800624 , fUseDFText(dfText)
625 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800626
627int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800628 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800629}
630
joshualitt5f5a8d72015-02-25 14:09:45 -0800631void PreAbandonGpuContextErrorHandler(SkError, void*) {}
632
mtkleinb9eb4ac2015-02-02 18:26:03 -0800633Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700634 GrContextOptions options;
635 src.modifyGrContextOptions(&options);
636
637 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800638 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800639 const SkImageInfo info =
640 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
641 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800642 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800643 if (!surface) {
644 return "Could not create a surface.";
645 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800646 if (FLAGS_preAbandonGpuContext) {
647 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, NULL);
648 factory.abandonContexts();
649 }
mtklein748ca3b2015-01-15 10:56:12 -0800650 SkCanvas* canvas = surface->getCanvas();
651 Error err = src.draw(canvas);
652 if (!err.isEmpty()) {
653 return err;
654 }
655 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800656 if (FLAGS_gpuStats) {
657 canvas->getGrContext()->dumpCacheStats(log);
658 canvas->getGrContext()->dumpGpuStats(log);
659 }
mtklein748ca3b2015-01-15 10:56:12 -0800660 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800661 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800662 if (FLAGS_abandonGpuContext) {
663 factory.abandonContexts();
664 }
mtklein748ca3b2015-01-15 10:56:12 -0800665 return "";
666}
667
668/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
669
halcanary47ef4d52015-03-03 09:13:09 -0800670static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
671 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
672 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800673 int width = src.size().width(),
674 height = src.size().height();
675
halcanary7e798182015-04-14 14:06:18 -0700676 if (FLAGS_multiPage) {
677 const int kLetterWidth = 612, // 8.5 * 72
678 kLetterHeight = 792; // 11 * 72
679 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
680 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800681
halcanary7e798182015-04-14 14:06:18 -0700682 int xPages = ((width - 1) / kLetterWidth) + 1;
683 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800684
halcanary7e798182015-04-14 14:06:18 -0700685 for (int y = 0; y < yPages; ++y) {
686 for (int x = 0; x < xPages; ++x) {
687 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
688 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
689 SkCanvas* canvas =
690 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
691 if (!canvas) {
692 return "SkDocument::beginPage(w,h) returned NULL";
693 }
694 canvas->clipRect(letter);
695 canvas->translate(-letter.width() * x, -letter.height() * y);
696 Error err = src.draw(canvas);
697 if (!err.isEmpty()) {
698 return err;
699 }
700 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700701 }
halcanaryfd4a9932015-01-28 11:45:58 -0800702 }
halcanary7e798182015-04-14 14:06:18 -0700703 } else {
704 SkCanvas* canvas =
705 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
706 if (!canvas) {
707 return "SkDocument::beginPage(w,h) returned NULL";
708 }
709 Error err = src.draw(canvas);
710 if (!err.isEmpty()) {
711 return err;
712 }
713 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800714 }
halcanary7e798182015-04-14 14:06:18 -0700715 if (!doc->close()) {
716 return "SkDocument::close() returned false";
717 }
halcanaryfd4a9932015-01-28 11:45:58 -0800718 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800719 return "";
720}
721
halcanary47ef4d52015-03-03 09:13:09 -0800722PDFSink::PDFSink() {}
723
724Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
725 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
726 if (!doc) {
727 return "SkDocument::CreatePDF() returned NULL";
728 }
729 return draw_skdocument(src, doc.get(), dst);
730}
731
732/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
733
734XPSSink::XPSSink() {}
735
736Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
737 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
738 if (!doc) {
739 return "SkDocument::CreateXPS() returned NULL";
740 }
741 return draw_skdocument(src, doc.get(), dst);
742}
mtklein748ca3b2015-01-15 10:56:12 -0800743/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
744
mtklein9c3f17d2015-01-28 11:35:18 -0800745SKPSink::SKPSink() {}
746
mtkleinb9eb4ac2015-02-02 18:26:03 -0800747Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800748 SkSize size;
749 size = src.size();
750 SkPictureRecorder recorder;
751 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
752 if (!err.isEmpty()) {
753 return err;
754 }
755 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
756 pic->serialize(dst);
757 return "";
758}
759
760/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
761
mtklein8a4527e2015-01-31 20:00:58 -0800762SVGSink::SVGSink() {}
763
mtkleinb9eb4ac2015-02-02 18:26:03 -0800764Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita2aafe6f2015-02-06 12:51:10 -0800765 SkAutoTDelete<SkXMLWriter> xmlWriter(SkNEW_ARGS(SkXMLStreamWriter, (dst)));
766 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
767 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
768 xmlWriter));
769 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800770}
771
772/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
773
mtklein748ca3b2015-01-15 10:56:12 -0800774RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
775
mtkleinb9eb4ac2015-02-02 18:26:03 -0800776Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800777 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800778 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
779 SkAlphaType alphaType = kPremul_SkAlphaType;
780 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
781
782 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
783 dst->eraseColor(SK_ColorTRANSPARENT);
784 SkCanvas canvas(*dst);
785 return src.draw(&canvas);
786}
787
788/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
789
mtkleina16e69e2015-05-05 11:38:45 -0700790// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700791// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700792// Several examples below.
793
mtkleina16e69e2015-05-05 11:38:45 -0700794static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700795 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700796 class ProxySrc : public Src {
797 public:
mtkleine44b5082015-05-07 10:53:34 -0700798 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700799 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
800 Name name() const override { sk_throw(); return ""; } // Won't be called.
801 SkISize size() const override { return fSize; }
802 private:
mtkleine44b5082015-05-07 10:53:34 -0700803 SkISize fSize;
804 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700805 };
806 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
807}
808
809/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
810
mtkleind603b222015-02-17 11:13:33 -0800811static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
812 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
813 matrix->mapRect(&bounds);
814 matrix->postTranslate(-bounds.x(), -bounds.y());
815 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
816}
817
mtklein78829242015-05-06 07:54:07 -0700818ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800819
mtkleinb9eb4ac2015-02-02 18:26:03 -0800820Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700821 SkMatrix matrix = fMatrix;
822 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
823 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
824 canvas->concat(matrix);
825 return src.draw(canvas);
826 });
mtklein748ca3b2015-01-15 10:56:12 -0800827}
828
mtkleind603b222015-02-17 11:13:33 -0800829// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
830// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700831ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800832
833Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
834 Error err = fSink->draw(src, bitmap, stream, log);
835 if (!err.isEmpty()) {
836 return err;
837 }
838
839 SkMatrix inverse;
840 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
841 return "Cannot upright --matrix.";
842 }
843 SkMatrix upright = SkMatrix::I();
844 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
845 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
846 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
847 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
848
849 SkBitmap uprighted;
850 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
851 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
852
853 SkCanvas canvas(uprighted);
854 canvas.concat(upright);
855 SkPaint paint;
856 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
857 canvas.drawBitmap(*bitmap, 0, 0, &paint);
858
859 *bitmap = uprighted;
860 bitmap->lockPixels();
861 return "";
862}
863
mtklein748ca3b2015-01-15 10:56:12 -0800864/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
865
mtkleinb9eb4ac2015-02-02 18:26:03 -0800866Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700867 auto size = src.size();
868 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
869 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
870 SkGPipeWriter pipe;
871 const uint32_t kFlags = 0; // We mirror SkDeferredCanvas, which doesn't use any flags.
872 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
873 });
mtklein748ca3b2015-01-15 10:56:12 -0800874}
875
876/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700877
reed06a22f62015-05-05 08:11:33 -0700878Error ViaDeferred::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700879 // We draw via a deferred canvas into a surface that's compatible with the original canvas,
880 // then snap that surface as an image and draw it into the original canvas.
881 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
882 SkAutoTUnref<SkSurface> surface(canvas->newSurface(canvas->imageInfo()));
883 if (!surface.get()) {
884 return "can't make surface for deferred canvas";
reed06a22f62015-05-05 08:11:33 -0700885 }
mtkleina16e69e2015-05-05 11:38:45 -0700886 SkAutoTDelete<SkDeferredCanvas> defcan(SkDeferredCanvas::Create(surface));
887 Error err = src.draw(defcan);
888 if (!err.isEmpty()) {
889 return err;
890 }
891 SkAutoTUnref<SkImage> image(defcan->newImageSnapshot());
892 if (!image) {
893 return "failed to create deferred image snapshot";
894 }
895 canvas->drawImage(image, 0, 0, NULL);
896 return "";
897 });
reed06a22f62015-05-05 08:11:33 -0700898}
mtkleina16e69e2015-05-05 11:38:45 -0700899
reed06a22f62015-05-05 08:11:33 -0700900/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -0800901
mtkleina16e69e2015-05-05 11:38:45 -0700902Error ViaSerialization::draw(
903 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800904 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700905 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800906 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700907 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
908 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800909 if (!err.isEmpty()) {
910 return err;
911 }
912 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
913
914 // Serialize it and then deserialize it.
915 SkDynamicMemoryWStream wStream;
916 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800917 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700918 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800919
mtkleina16e69e2015-05-05 11:38:45 -0700920 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
921 canvas->drawPicture(deserialized);
922 return "";
923 });
mtklein748ca3b2015-01-15 10:56:12 -0800924}
925
926/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
927
928ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700929 : Via(sink)
930 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800931 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700932 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800933
mtkleinb9eb4ac2015-02-02 18:26:03 -0800934Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700935 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800936 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700937 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
938 SkIntToScalar(size.height()),
939 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800940 if (!err.isEmpty()) {
941 return err;
942 }
mtkleinb7e8d692015-04-07 08:30:32 -0700943 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800944
mtkleina16e69e2015-05-05 11:38:45 -0700945 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
946 const int xTiles = (size.width() + fW - 1) / fW,
947 yTiles = (size.height() + fH - 1) / fH;
948 SkMultiPictureDraw mpd(xTiles*yTiles);
949 SkTDArray<SkSurface*> surfaces;
950 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800951
mtkleina16e69e2015-05-05 11:38:45 -0700952 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
953 for (int j = 0; j < yTiles; j++) {
954 for (int i = 0; i < xTiles; i++) {
955 // This lets our ultimate Sink determine the best kind of surface.
956 // E.g., if it's a GpuSink, the surfaces and images are textures.
957 SkSurface* s = canvas->newSurface(info);
958 if (!s) {
959 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800960 }
mtkleina16e69e2015-05-05 11:38:45 -0700961 surfaces.push(s);
962 SkCanvas* c = s->getCanvas();
963 c->translate(SkIntToScalar(-i * fW),
964 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
965 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800966 }
mtklein748ca3b2015-01-15 10:56:12 -0800967 }
mtkleina16e69e2015-05-05 11:38:45 -0700968 mpd.draw();
969 for (int j = 0; j < yTiles; j++) {
970 for (int i = 0; i < xTiles; i++) {
971 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
972 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
973 }
974 }
975 surfaces.unrefAll();
976 return "";
977 });
mtklein748ca3b2015-01-15 10:56:12 -0800978}
979
mtkleinb7e8d692015-04-07 08:30:32 -0700980/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
981
mtkleinb7e8d692015-04-07 08:30:32 -0700982// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
983// This tests that any shortcuts we may take while recording that second picture are legal.
984Error ViaSecondPicture::draw(
985 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700986 auto size = src.size();
987 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
988 SkPictureRecorder recorder;
989 SkAutoTUnref<SkPicture> pic;
990 for (int i = 0; i < 2; i++) {
991 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
992 SkIntToScalar(size.height())));
993 if (!err.isEmpty()) {
994 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700995 }
mtkleina16e69e2015-05-05 11:38:45 -0700996 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700997 }
mtkleina16e69e2015-05-05 11:38:45 -0700998 canvas->drawPicture(pic);
999 return "";
1000 });
mtkleinb7e8d692015-04-07 08:30:32 -07001001}
1002
mtkleind31c13d2015-05-05 12:59:56 -07001003/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1004
mtklein6fbf4b32015-05-06 11:35:40 -07001005// Draw the Src twice. This can help exercise caching.
1006Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1007 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1008 for (int i = 0; i < 2; i++) {
1009 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1010 canvas->clear(SK_ColorTRANSPARENT);
1011 Error err = src.draw(canvas);
1012 if (err.isEmpty()) {
1013 return err;
1014 }
1015 }
1016 return "";
1017 });
1018}
1019
1020/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1021
mtkleind31c13d2015-05-05 12:59:56 -07001022// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1023// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1024// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1025struct DrawsAsSingletonPictures {
1026 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001027 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001028
1029 SK_CREATE_MEMBER_DETECTOR(paint);
1030
1031 template <typename T>
1032 void draw(const T& op, SkCanvas* canvas) {
1033 // We must pass SkMatrix::I() as our initial matrix.
1034 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1035 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001036 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1037 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001038 }
1039
1040 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1041 template <typename T>
1042 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1043 SkPictureRecorder rec;
1044 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1045 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1046 fCanvas->drawPicture(pic);
1047 }
1048
1049 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1050 // We cannot make subpictures out of these because they affect state. Draw them directly.
1051 template <typename T>
1052 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1053 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1054};
1055
mtkleind31c13d2015-05-05 12:59:56 -07001056// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1057// Then play back that macro picture into our wrapped sink.
1058Error ViaSingletonPictures::draw(
1059 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1060 auto size = src.size();
1061 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1062 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1063 SkRecord skr;
1064 SkRecorder recorder(&skr, size.width(), size.height());
1065 Error err = src.draw(&recorder);
1066 if (!err.isEmpty()) {
1067 return err;
1068 }
1069
1070 // Record our macro-picture, with each draw op as its own sub-picture.
1071 SkPictureRecorder macroRec;
1072 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1073 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001074
1075 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1076 const SkDrawableList empty;
1077
1078 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1079 macroCanvas,
1080 drawables ? *drawables : empty,
1081 };
mtkleind31c13d2015-05-05 12:59:56 -07001082 for (unsigned i = 0; i < skr.count(); i++) {
1083 skr.visit<void>(i, drawsAsSingletonPictures);
1084 }
1085 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1086
1087 canvas->drawPicture(macroPic);
1088 return "";
1089 });
1090}
1091
mtklein748ca3b2015-01-15 10:56:12 -08001092} // namespace DM