blob: 2c80fac6be9506e9e26a7a4c180be33e93e06984 [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"
mtklein748ca3b2015-01-15 10:56:12 -080013#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080014#include "SkError.h"
mtkleine44b5082015-05-07 10:53:34 -070015#include "SkFunction.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070016#include "SkImageGenerator.h"
mtklein748ca3b2015-01-15 10:56:12 -080017#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080018#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080019#include "SkOSFile.h"
mtkleinffa901a2015-03-16 10:38:07 -070020#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080021#include "SkPictureRecorder.h"
22#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070023#include "SkRecordDraw.h"
24#include "SkRecorder.h"
fmalita2aafe6f2015-02-06 12:51:10 -080025#include "SkSVGCanvas.h"
mtkleina16e69e2015-05-05 11:38:45 -070026#include "SkScanlineDecoder.h"
scroggoa1193e42015-01-21 12:09:53 -080027#include "SkStream.h"
fmalita2aafe6f2015-02-06 12:51:10 -080028#include "SkXMLWriter.h"
emmaleer8f4ba762015-08-14 07:44:46 -070029#include "SkScaledCodec.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 {
halcanary96fcdcc2015-08-27 07:41:13 -070044 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080045 canvas->concat(gm->getInitialTransform());
46 gm->draw(canvas);
47 return "";
48}
49
50SkISize GMSrc::size() const {
halcanary96fcdcc2015-08-27 07:41:13 -070051 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080052 return gm->getISize();
53}
54
55Name GMSrc::name() const {
halcanary96fcdcc2015-08-27 07:41:13 -070056 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080057 return gm->getName();
58}
59
bsalomon4ee6bd82015-05-27 13:23:23 -070060void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
halcanary96fcdcc2015-08-27 07:41:13 -070061 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -070062 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
msarett5406d6f2015-08-31 06:55:13 -070082SkScanlineDecoder* start_scanline_decoder(SkData* encoded, const SkImageInfo& info,
83 SkPMColor* colorPtr, int* colorCountPtr) {
84 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(SkScanlineDecoder::NewFromData(encoded));
85 if (nullptr == scanlineDecoder) {
86 return nullptr;
87 }
msarett5406d6f2015-08-31 06:55:13 -070088 if (SkCodec::kSuccess != scanlineDecoder->start(info, NULL, colorPtr, colorCountPtr)) {
89 return nullptr;
90 }
91 return scanlineDecoder.detach();
92}
93
mtkleine0effd62015-07-29 06:37:28 -070094Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -080095 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080096 if (!encoded) {
97 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
98 }
msarett9e707a02015-09-01 14:57:57 -070099 SkAutoTDelete<SkCodec> codec(NULL);
100 if (kScaledCodec_Mode == fMode) {
101 codec.reset(SkScaledCodec::NewFromData(encoded));
102 // TODO (msarett): This should fall through to a fatal error once we support scaled
103 // codecs for all image types.
halcanary96fcdcc2015-08-27 07:41:13 -0700104 if (nullptr == codec.get()) {
msarett9e707a02015-09-01 14:57:57 -0700105 return Error::Nonfatal(SkStringPrintf("Couldn't create scaled codec for %s.",
106 fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700107 }
msarett9e707a02015-09-01 14:57:57 -0700108 } else {
109 codec.reset(SkCodec::NewFromData(encoded));
110 }
111 if (nullptr == codec.get()) {
112 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700113 }
114
msarett438b2ad2015-04-09 12:43:10 -0700115 // Choose the color type to decode to
116 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -0700117 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -0700118 switch (fDstColorType) {
119 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700120 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
121 if (kRGB_565_SkColorType == canvasColorType) {
122 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
123 }
124 break;
msarett438b2ad2015-04-09 12:43:10 -0700125 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700126 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700127 if (kRGB_565_SkColorType == canvasColorType) {
128 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
129 }
130 break;
131 default:
132 decodeInfo = decodeInfo.makeColorType(canvasColorType);
133 break;
134 }
135
msarett0a242972015-06-11 14:27:27 -0700136 // Try to scale the image if it is desired
137 SkISize size = codec->getScaledDimensions(fScale);
138 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
139 return Error::Nonfatal("Test without scaling is uninteresting.");
140 }
msarettb32758a2015-08-18 13:22:46 -0700141
142 // Visually inspecting very small output images is not necessary. We will
143 // cover these cases in unit testing.
144 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
145 return Error::Nonfatal("Scaling very small images is uninteresting.");
146 }
msarett0a242972015-06-11 14:27:27 -0700147 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
148
msarett438b2ad2015-04-09 12:43:10 -0700149 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700150 SkAutoTUnref<SkColorTable> colorTable(nullptr);
151 SkPMColor* colorPtr = nullptr;
152 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700153 int maxColors = 256;
154 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
155 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700156 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700157 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
158 colorCountPtr = &maxColors;
159 }
160
161 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700162 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700163 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
164 }
165
166 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700167 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700168 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
169 decodeInfo.width(), decodeInfo.height());
170 }
171
scroggo9c59ebc2015-03-25 13:48:49 -0700172 switch (fMode) {
msarett9e707a02015-09-01 14:57:57 -0700173 case kScaledCodec_Mode:
174 case kCodec_Mode: {
halcanary96fcdcc2015-08-27 07:41:13 -0700175 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700176 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700177 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700178 // We consider incomplete to be valid, since we should still decode what is
179 // available.
scroggoeb602a52015-07-09 08:16:03 -0700180 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700181 break;
scroggoeb602a52015-07-09 08:16:03 -0700182 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700183 return Error::Nonfatal("Incompatible colortype conversion");
184 default:
185 // Everything else is considered a failure.
186 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
187 }
emmaleer97002062015-05-27 12:36:10 -0700188 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700189 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700190 }
scroggo9c59ebc2015-03-25 13:48:49 -0700191 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700192 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
msarett5406d6f2015-08-31 06:55:13 -0700193 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
194 if (nullptr == scanlineDecoder) {
msarett9e707a02015-09-01 14:57:57 -0700195 return Error::Nonfatal("Could not start scanline decoder");
scroggo9c59ebc2015-03-25 13:48:49 -0700196 }
scroggo1c005e42015-08-04 09:24:45 -0700197
scroggoeb602a52015-07-09 08:16:03 -0700198 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700199 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
200 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700201 case SkCodec::kSuccess:
202 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700203 break;
204 default:
205 return SkStringPrintf("%s failed with error message %d",
206 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700207 }
emmaleer97002062015-05-27 12:36:10 -0700208 canvas->drawBitmap(bitmap, 0, 0);
209 break;
210 }
211 case kScanline_Subset_Mode: {
212 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
213 const int divisor = 2;
214 const int w = decodeInfo.width();
215 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700216 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700217 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
218 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700219 }
220 const int subsetWidth = w/divisor;
221 const int subsetHeight = h/divisor;
222 // One of our subsets will be larger to contain any pixels that do not divide evenly.
223 const int extraX = w % divisor;
224 const int extraY = h % divisor;
225 /*
226 * if w or h are not evenly divided by divisor need to adjust width and height of end
227 * subsets to cover entire image.
228 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
229 * and height of end subsets.
230 * subsetBm is extracted from largestSubsetBm.
231 * subsetBm's size is determined based on the current subset and may be larger for end
232 * subsets.
233 */
msarett0a242972015-06-11 14:27:27 -0700234 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700235 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
236 SkBitmap largestSubsetBm;
msarett9e707a02015-09-01 14:57:57 -0700237 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr,
238 colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700239 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
240 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
241 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700242 const size_t rowBytes = decodeInfo.minRowBytes();
halcanary385fe4d2015-08-26 13:07:48 -0700243 char* buffer = new char[largestSubsetDecodeInfo.height() * rowBytes];
emmaleer0a4c3cb2015-06-22 10:40:21 -0700244 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700245 for (int col = 0; col < divisor; col++) {
246 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
247 const int currentSubsetWidth = (col + 1 == divisor) ?
248 subsetWidth + extraX : subsetWidth;
249 const int x = col * subsetWidth;
250 for (int row = 0; row < divisor; row++) {
251 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
252 const int currentSubsetHeight = (row + 1 == divisor) ?
253 subsetHeight + extraY : subsetHeight;
254 const int y = row * subsetHeight;
255 //create scanline decoder for each subset
msarett9e707a02015-09-01 14:57:57 -0700256 SkAutoTDelete<SkScanlineDecoder> decoder(start_scanline_decoder(encoded.get(),
257 decodeInfo, colorPtr, colorCountPtr));
258 // TODO (msarett): Support this mode for all scanline orderings.
259 if (nullptr == decoder || SkScanlineDecoder::kTopDown_SkScanlineOrder !=
260 decoder->getScanlineOrder()) {
emmaleer97002062015-05-27 12:36:10 -0700261 if (x == 0 && y == 0) {
262 //first try, image may not be compatible
msarett5406d6f2015-08-31 06:55:13 -0700263 return Error::Nonfatal("Could not start top-down scanline decoder");
emmaleer97002062015-05-27 12:36:10 -0700264 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700265 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700266 }
267 }
268 //skip to first line of subset
msarett9e707a02015-09-01 14:57:57 -0700269 const SkCodec::Result skipResult = decoder->skipScanlines(y);
emmaleer97002062015-05-27 12:36:10 -0700270 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700271 case SkCodec::kSuccess:
272 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700273 break;
274 default:
275 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
276 "with error message %d", fPath.c_str(), y, (int) skipResult);
277 }
278 //create and set size of subsetBm
279 SkBitmap subsetBm;
280 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
281 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
282 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
283 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700284 const SkCodec::Result subsetResult =
msarett9e707a02015-09-01 14:57:57 -0700285 decoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700286 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700287 case SkCodec::kSuccess:
288 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700289 break;
290 default:
mtkleind2baa902015-07-07 09:43:28 -0700291 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700292 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700293 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700294 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700295 /*
296 * we copy all the lines at once becuase when calling getScanlines for
297 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700298 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
299 * decode the entire image height times, which is very slow
300 * it is aknowledged that copying each line as you read it in a loop
301 * may be faster for other types of images. Since this is a correctness test
302 * that's okay.
303 */
mtkleind2baa902015-07-07 09:43:28 -0700304 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700305 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700306 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700307 currentSubsetWidth*bpp);
308 bufferRow += rowBytes;
309 }
mtkleind2baa902015-07-07 09:43:28 -0700310
scroggo4358f132015-07-30 11:33:04 -0700311 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700312 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
313 }
314 }
scroggo9c59ebc2015-03-25 13:48:49 -0700315 break;
316 }
msarett0a242972015-06-11 14:27:27 -0700317 case kStripe_Mode: {
318 const int height = decodeInfo.height();
319 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
320 // does not align with image blocks.
321 const int stripeHeight = 37;
322 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
323
324 // Decode odd stripes
msarett5406d6f2015-08-31 06:55:13 -0700325 SkAutoTDelete<SkScanlineDecoder> decoder(
326 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
msarett9e707a02015-09-01 14:57:57 -0700327 if (nullptr == decoder ||
328 SkScanlineDecoder::kTopDown_SkScanlineOrder != decoder->getScanlineOrder()) {
329 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
330 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
331 // to run this test for image types that do not have this scanline ordering.
msarett5406d6f2015-08-31 06:55:13 -0700332 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700333 }
334 for (int i = 0; i < numStripes; i += 2) {
335 // Skip a stripe
336 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700337 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700338 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700339 case SkCodec::kSuccess:
340 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700341 break;
342 default:
343 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
344 }
345
346 // Read a stripe
347 const int startY = (i + 1) * stripeHeight;
348 const int linesToRead = SkTMin(stripeHeight, height - startY);
349 if (linesToRead > 0) {
350 result = decoder->getScanlines(bitmap.getAddr(0, startY),
351 linesToRead, bitmap.rowBytes());
352 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700353 case SkCodec::kSuccess:
354 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700355 break;
356 default:
357 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
358 }
359 }
360 }
361
362 // Decode even stripes
halcanary96fcdcc2015-08-27 07:41:13 -0700363 const SkCodec::Result startResult = decoder->start(decodeInfo, nullptr, colorPtr,
scroggo1c005e42015-08-04 09:24:45 -0700364 colorCountPtr);
365 if (SkCodec::kSuccess != startResult) {
366 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700367 }
368 for (int i = 0; i < numStripes; i += 2) {
369 // Read a stripe
370 const int startY = i * stripeHeight;
371 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700372 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700373 linesToRead, bitmap.rowBytes());
374 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700375 case SkCodec::kSuccess:
376 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700377 break;
378 default:
379 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
380 }
381
382 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700383 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
384 if (linesToSkip > 0) {
385 result = decoder->skipScanlines(linesToSkip);
386 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700387 case SkCodec::kSuccess:
388 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700389 break;
390 default:
391 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
392 }
msarett0a242972015-06-11 14:27:27 -0700393 }
394 }
395 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700396 break;
msarett0a242972015-06-11 14:27:27 -0700397 }
scroggob636b452015-07-22 07:16:20 -0700398 case kSubset_Mode: {
399 // Arbitrarily choose a divisor.
400 int divisor = 2;
401 // Total width/height of the image.
402 const int W = codec->getInfo().width();
403 const int H = codec->getInfo().height();
404 if (divisor > W || divisor > H) {
405 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
406 "for %s with dimensions (%d x %d)", divisor,
407 fPath.c_str(), W, H));
408 }
409 // subset dimensions
410 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
411 const int w = SkAlign2(W / divisor);
412 const int h = SkAlign2(H / divisor);
413 SkIRect subset;
414 SkCodec::Options opts;
415 opts.fSubset = &subset;
416 SkBitmap subsetBm;
417 // We will reuse pixel memory from bitmap.
418 void* pixels = bitmap.getPixels();
419 // Keep track of left and top (for drawing subsetBm into canvas). We could use
420 // fScale * x and fScale * y, but we want integers such that the next subset will start
421 // where the last one ended. So we'll add decodeInfo.width() and height().
422 int left = 0;
423 for (int x = 0; x < W; x += w) {
424 int top = 0;
425 for (int y = 0; y < H; y+= h) {
426 // Do not make the subset go off the edge of the image.
427 const int preScaleW = SkTMin(w, W - x);
428 const int preScaleH = SkTMin(h, H - y);
429 subset.setXYWH(x, y, preScaleW, preScaleH);
430 // And scale
431 // FIXME: Should we have a version of getScaledDimensions that takes a subset
432 // into account?
433 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
434 SkScalarRoundToInt(preScaleH * fScale));
435 size_t rowBytes = decodeInfo.minRowBytes();
436 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700437 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700438 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
439 }
440 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
441 &opts, colorPtr, colorCountPtr);
442 switch (result) {
443 case SkCodec::kSuccess:
444 case SkCodec::kIncompleteInput:
445 break;
446 case SkCodec::kInvalidConversion:
447 if (0 == (x|y)) {
448 // First subset is okay to return unimplemented.
449 return Error::Nonfatal("Incompatible colortype conversion");
450 }
451 // If the first subset succeeded, a later one should not fail.
452 // fall through to failure
453 case SkCodec::kUnimplemented:
454 if (0 == (x|y)) {
455 // First subset is okay to return unimplemented.
456 return Error::Nonfatal("subset codec not supported");
457 }
458 // If the first subset succeeded, why would a later one fail?
459 // fall through to failure
460 default:
461 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
462 "from %s with dimensions (%d x %d)\t error %d",
463 x, y, decodeInfo.width(), decodeInfo.height(),
464 fPath.c_str(), W, H, result);
465 }
466 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
467 // translate by the scaled height.
468 top += decodeInfo.height();
469 }
470 // translate by the scaled width.
471 left += decodeInfo.width();
472 }
473 return "";
474 }
scroggo9b77ddd2015-03-19 06:03:39 -0700475 }
scroggo9c59ebc2015-03-25 13:48:49 -0700476 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700477}
478
479SkISize CodecSrc::size() const {
480 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700481 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700482 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700483 // scaledCodec not supported, try regular codec
484 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700485 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700486 return SkISize::Make(0, 0);
487 }
msarett9bde9182015-03-25 05:27:48 -0700488 }
emmaleer8f4ba762015-08-14 07:44:46 -0700489 SkISize size = codec->getScaledDimensions(fScale);
490 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700491}
492
493Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700494 if (1.0f == fScale) {
495 return SkOSPath::Basename(fPath.c_str());
496 } else {
497 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
498 }
scroggo9b77ddd2015-03-19 06:03:39 -0700499}
500
501/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
502
503ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
504
mtklein99cab4e2015-07-31 06:43:04 -0700505bool ImageSrc::veto(SinkFlags flags) const {
506 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700507 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700508 return flags.type != SinkFlags::kRaster
509 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700510}
scroggo9b77ddd2015-03-19 06:03:39 -0700511
mtkleine0effd62015-07-29 06:37:28 -0700512Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700513 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
514 if (!encoded) {
515 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
516 }
mtkleine0effd62015-07-29 06:37:28 -0700517 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800518 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800519 // Decode the full image.
520 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700521 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
522 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
523 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
524 }
525 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
526 // Do not draw a bitmap with alpha to a destination without alpha.
527 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800528 }
halcanary96fcdcc2015-08-27 07:41:13 -0700529 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800530 canvas->drawBitmap(bitmap, 0,0);
531 return "";
532 }
mtkleinedc93bc2015-01-30 13:22:23 -0800533 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800534 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
535 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800536 if (!decoder) {
537 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
538 }
scroggoa1193e42015-01-21 12:09:53 -0800539 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800540 int w,h;
msarett70542572015-06-19 07:44:05 -0700541 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800542 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800543 }
mtkleinedc93bc2015-01-30 13:22:23 -0800544
545 // Divide the image into subsets that cover the entire image.
546 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700547 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
548 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800549 }
550 const int subsetWidth = w / fDivisor,
551 subsetHeight = h / fDivisor;
552 for (int y = 0; y < h; y += subsetHeight) {
553 for (int x = 0; x < w; x += subsetWidth) {
554 SkBitmap subset;
555 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
556 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
557 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
558 x, y, x+subsetWidth, y+subsetHeight);
559 }
scroggo56e25dd2015-03-05 11:46:40 -0800560 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
561 // Do not draw a bitmap with alpha to a destination without alpha.
562 // This is not an error, but there is nothing interesting to show.
563
564 // This should only happen on the first iteration through the loop.
565 SkASSERT(0 == x && 0 == y);
566
567 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
568 }
mtkleinedc93bc2015-01-30 13:22:23 -0800569 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800570 }
mtklein748ca3b2015-01-15 10:56:12 -0800571 }
572 return "";
573}
574
575SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800576 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700577 SkBitmap bitmap;
578 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
579 encoded->size(),
580 &bitmap,
581 kUnknown_SkColorType,
582 SkImageDecoder::kDecodeBounds_Mode)) {
583 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800584 }
scroggo9b77ddd2015-03-19 06:03:39 -0700585 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800586}
587
mtklein9264a952015-01-20 10:11:53 -0800588Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800589 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800590}
mtklein748ca3b2015-01-15 10:56:12 -0800591
592/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
593
mtkleinf4ba3212015-01-28 15:32:24 -0800594static const SkRect kSKPViewport = {0,0, 1000,1000};
595
mtklein8d17a132015-01-30 11:42:31 -0800596SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800597
598Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800599 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800600 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800601 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
602 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700603 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800604 if (!pic) {
605 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
606 }
halcanary96fcdcc2015-08-27 07:41:13 -0700607 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700608
mtkleinf4ba3212015-01-28 15:32:24 -0800609 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800610 canvas->drawPicture(pic);
611 return "";
612}
613
614SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700615 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
616 if (!stream) {
617 return SkISize::Make(0,0);
618 }
619 SkPictInfo info;
620 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
621 return SkISize::Make(0,0);
622 }
623 SkRect viewport = kSKPViewport;
624 if (!viewport.intersect(info.fCullRect)) {
625 return SkISize::Make(0,0);
626 }
627 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800628}
629
630Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
631
632/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
633
mtkleinad66f9b2015-02-13 15:11:10 -0800634Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
635 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
636 return src.draw(canvas);
637}
638
639/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
640
mtkleinb9eb4ac2015-02-02 18:26:03 -0800641DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
642
mtklein82d28432015-01-15 12:46:02 -0800643GPUSink::GPUSink(GrContextFactory::GLContextType ct,
644 GrGLStandard api,
645 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700646 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800647 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800648 : fContextType(ct)
649 , fGpuAPI(api)
650 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700651 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800652 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800653
654int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800655 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800656}
657
joshualitt5f5a8d72015-02-25 14:09:45 -0800658void PreAbandonGpuContextErrorHandler(SkError, void*) {}
659
mtkleinb9eb4ac2015-02-02 18:26:03 -0800660Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700661 GrContextOptions options;
662 src.modifyGrContextOptions(&options);
663
664 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800665 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800666 const SkImageInfo info =
667 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
668 SkAutoTUnref<SkSurface> surface(
bsalomonafcd7cd2015-08-31 12:39:41 -0700669 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800670 if (!surface) {
671 return "Could not create a surface.";
672 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800673 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700674 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800675 factory.abandonContexts();
676 }
mtklein748ca3b2015-01-15 10:56:12 -0800677 SkCanvas* canvas = surface->getCanvas();
678 Error err = src.draw(canvas);
679 if (!err.isEmpty()) {
680 return err;
681 }
682 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800683 if (FLAGS_gpuStats) {
684 canvas->getGrContext()->dumpCacheStats(log);
685 canvas->getGrContext()->dumpGpuStats(log);
686 }
mtklein748ca3b2015-01-15 10:56:12 -0800687 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800688 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800689 if (FLAGS_abandonGpuContext) {
690 factory.abandonContexts();
691 }
mtklein748ca3b2015-01-15 10:56:12 -0800692 return "";
693}
694
695/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
696
halcanary47ef4d52015-03-03 09:13:09 -0800697static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
698 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
699 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800700 int width = src.size().width(),
701 height = src.size().height();
702
halcanary7e798182015-04-14 14:06:18 -0700703 if (FLAGS_multiPage) {
704 const int kLetterWidth = 612, // 8.5 * 72
705 kLetterHeight = 792; // 11 * 72
706 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
707 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800708
halcanary7e798182015-04-14 14:06:18 -0700709 int xPages = ((width - 1) / kLetterWidth) + 1;
710 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800711
halcanary7e798182015-04-14 14:06:18 -0700712 for (int y = 0; y < yPages; ++y) {
713 for (int x = 0; x < xPages; ++x) {
714 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
715 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
716 SkCanvas* canvas =
717 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
718 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700719 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700720 }
721 canvas->clipRect(letter);
722 canvas->translate(-letter.width() * x, -letter.height() * y);
723 Error err = src.draw(canvas);
724 if (!err.isEmpty()) {
725 return err;
726 }
727 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700728 }
halcanaryfd4a9932015-01-28 11:45:58 -0800729 }
halcanary7e798182015-04-14 14:06:18 -0700730 } else {
731 SkCanvas* canvas =
732 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
733 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700734 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700735 }
736 Error err = src.draw(canvas);
737 if (!err.isEmpty()) {
738 return err;
739 }
740 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800741 }
halcanary7e798182015-04-14 14:06:18 -0700742 if (!doc->close()) {
743 return "SkDocument::close() returned false";
744 }
halcanaryfd4a9932015-01-28 11:45:58 -0800745 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800746 return "";
747}
748
halcanary47ef4d52015-03-03 09:13:09 -0800749PDFSink::PDFSink() {}
750
751Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
752 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
753 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700754 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800755 }
756 return draw_skdocument(src, doc.get(), dst);
757}
758
759/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
760
761XPSSink::XPSSink() {}
762
763Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
764 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
765 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700766 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800767 }
768 return draw_skdocument(src, doc.get(), dst);
769}
mtklein748ca3b2015-01-15 10:56:12 -0800770/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
771
mtklein9c3f17d2015-01-28 11:35:18 -0800772SKPSink::SKPSink() {}
773
mtkleinb9eb4ac2015-02-02 18:26:03 -0800774Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800775 SkSize size;
776 size = src.size();
777 SkPictureRecorder recorder;
778 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
779 if (!err.isEmpty()) {
780 return err;
781 }
782 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
783 pic->serialize(dst);
784 return "";
785}
786
787/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
788
mtklein8a4527e2015-01-31 20:00:58 -0800789SVGSink::SVGSink() {}
790
mtkleinb9eb4ac2015-02-02 18:26:03 -0800791Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -0700792 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -0800793 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
794 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
795 xmlWriter));
796 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800797}
798
799/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
800
mtklein748ca3b2015-01-15 10:56:12 -0800801RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
802
mtkleinb9eb4ac2015-02-02 18:26:03 -0800803Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800804 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800805 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
806 SkAlphaType alphaType = kPremul_SkAlphaType;
807 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
808
809 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
810 dst->eraseColor(SK_ColorTRANSPARENT);
811 SkCanvas canvas(*dst);
812 return src.draw(&canvas);
813}
814
815/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
816
mtkleina16e69e2015-05-05 11:38:45 -0700817// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700818// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700819// Several examples below.
820
mtkleina16e69e2015-05-05 11:38:45 -0700821static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700822 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700823 class ProxySrc : public Src {
824 public:
mtkleine44b5082015-05-07 10:53:34 -0700825 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700826 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
827 Name name() const override { sk_throw(); return ""; } // Won't be called.
828 SkISize size() const override { return fSize; }
829 private:
mtkleine44b5082015-05-07 10:53:34 -0700830 SkISize fSize;
831 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700832 };
833 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
834}
835
836/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
837
mtkleind603b222015-02-17 11:13:33 -0800838static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
839 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
840 matrix->mapRect(&bounds);
841 matrix->postTranslate(-bounds.x(), -bounds.y());
842 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
843}
844
mtklein78829242015-05-06 07:54:07 -0700845ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800846
mtkleinb9eb4ac2015-02-02 18:26:03 -0800847Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700848 SkMatrix matrix = fMatrix;
849 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
850 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
851 canvas->concat(matrix);
852 return src.draw(canvas);
853 });
mtklein748ca3b2015-01-15 10:56:12 -0800854}
855
mtkleind603b222015-02-17 11:13:33 -0800856// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
857// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700858ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800859
860Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
861 Error err = fSink->draw(src, bitmap, stream, log);
862 if (!err.isEmpty()) {
863 return err;
864 }
865
866 SkMatrix inverse;
867 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
868 return "Cannot upright --matrix.";
869 }
870 SkMatrix upright = SkMatrix::I();
871 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
872 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
873 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
874 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
875
876 SkBitmap uprighted;
877 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
878 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
879
880 SkCanvas canvas(uprighted);
881 canvas.concat(upright);
882 SkPaint paint;
883 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
884 canvas.drawBitmap(*bitmap, 0, 0, &paint);
885
886 *bitmap = uprighted;
887 bitmap->lockPixels();
888 return "";
889}
890
mtklein748ca3b2015-01-15 10:56:12 -0800891/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
892
mtkleinb9eb4ac2015-02-02 18:26:03 -0800893Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700894 auto size = src.size();
895 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
896 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
897 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -0700898 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -0700899 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
900 });
mtklein748ca3b2015-01-15 10:56:12 -0800901}
902
903/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700904
mtkleina16e69e2015-05-05 11:38:45 -0700905Error ViaSerialization::draw(
906 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800907 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700908 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800909 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700910 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
911 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800912 if (!err.isEmpty()) {
913 return err;
914 }
915 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
916
917 // Serialize it and then deserialize it.
918 SkDynamicMemoryWStream wStream;
919 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800920 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700921 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800922
mtkleina16e69e2015-05-05 11:38:45 -0700923 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
924 canvas->drawPicture(deserialized);
925 return "";
926 });
mtklein748ca3b2015-01-15 10:56:12 -0800927}
928
929/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
930
931ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700932 : Via(sink)
933 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800934 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700935 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800936
mtkleinb9eb4ac2015-02-02 18:26:03 -0800937Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700938 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800939 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700940 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
941 SkIntToScalar(size.height()),
942 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800943 if (!err.isEmpty()) {
944 return err;
945 }
mtkleinb7e8d692015-04-07 08:30:32 -0700946 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800947
mtkleina16e69e2015-05-05 11:38:45 -0700948 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
949 const int xTiles = (size.width() + fW - 1) / fW,
950 yTiles = (size.height() + fH - 1) / fH;
951 SkMultiPictureDraw mpd(xTiles*yTiles);
952 SkTDArray<SkSurface*> surfaces;
953 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800954
mtkleina16e69e2015-05-05 11:38:45 -0700955 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
956 for (int j = 0; j < yTiles; j++) {
957 for (int i = 0; i < xTiles; i++) {
958 // This lets our ultimate Sink determine the best kind of surface.
959 // E.g., if it's a GpuSink, the surfaces and images are textures.
960 SkSurface* s = canvas->newSurface(info);
961 if (!s) {
962 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800963 }
mtkleina16e69e2015-05-05 11:38:45 -0700964 surfaces.push(s);
965 SkCanvas* c = s->getCanvas();
966 c->translate(SkIntToScalar(-i * fW),
967 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
968 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800969 }
mtklein748ca3b2015-01-15 10:56:12 -0800970 }
mtkleina16e69e2015-05-05 11:38:45 -0700971 mpd.draw();
972 for (int j = 0; j < yTiles; j++) {
973 for (int i = 0; i < xTiles; i++) {
974 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
975 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
976 }
977 }
978 surfaces.unrefAll();
979 return "";
980 });
mtklein748ca3b2015-01-15 10:56:12 -0800981}
982
mtkleinb7e8d692015-04-07 08:30:32 -0700983/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
984
mtkleinb7e8d692015-04-07 08:30:32 -0700985// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
986// This tests that any shortcuts we may take while recording that second picture are legal.
987Error ViaSecondPicture::draw(
988 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700989 auto size = src.size();
990 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
991 SkPictureRecorder recorder;
992 SkAutoTUnref<SkPicture> pic;
993 for (int i = 0; i < 2; i++) {
994 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
995 SkIntToScalar(size.height())));
996 if (!err.isEmpty()) {
997 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700998 }
mtkleina16e69e2015-05-05 11:38:45 -0700999 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001000 }
mtkleina16e69e2015-05-05 11:38:45 -07001001 canvas->drawPicture(pic);
1002 return "";
1003 });
mtkleinb7e8d692015-04-07 08:30:32 -07001004}
1005
mtkleind31c13d2015-05-05 12:59:56 -07001006/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1007
mtklein6fbf4b32015-05-06 11:35:40 -07001008// Draw the Src twice. This can help exercise caching.
1009Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1010 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1011 for (int i = 0; i < 2; i++) {
1012 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1013 canvas->clear(SK_ColorTRANSPARENT);
1014 Error err = src.draw(canvas);
1015 if (err.isEmpty()) {
1016 return err;
1017 }
1018 }
1019 return "";
1020 });
1021}
1022
1023/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1024
mtkleind31c13d2015-05-05 12:59:56 -07001025// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1026// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1027// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1028struct DrawsAsSingletonPictures {
1029 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001030 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001031
1032 SK_CREATE_MEMBER_DETECTOR(paint);
1033
1034 template <typename T>
1035 void draw(const T& op, SkCanvas* canvas) {
1036 // We must pass SkMatrix::I() as our initial matrix.
1037 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1038 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001039 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1040 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001041 }
1042
1043 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1044 template <typename T>
1045 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1046 SkPictureRecorder rec;
1047 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1048 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1049 fCanvas->drawPicture(pic);
1050 }
1051
1052 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1053 // We cannot make subpictures out of these because they affect state. Draw them directly.
1054 template <typename T>
1055 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1056 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1057};
1058
mtkleind31c13d2015-05-05 12:59:56 -07001059// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1060// Then play back that macro picture into our wrapped sink.
1061Error ViaSingletonPictures::draw(
1062 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1063 auto size = src.size();
1064 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1065 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1066 SkRecord skr;
1067 SkRecorder recorder(&skr, size.width(), size.height());
1068 Error err = src.draw(&recorder);
1069 if (!err.isEmpty()) {
1070 return err;
1071 }
1072
1073 // Record our macro-picture, with each draw op as its own sub-picture.
1074 SkPictureRecorder macroRec;
1075 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1076 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001077
1078 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1079 const SkDrawableList empty;
1080
1081 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1082 macroCanvas,
1083 drawables ? *drawables : empty,
1084 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001085 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001086 skr.visit<void>(i, drawsAsSingletonPictures);
1087 }
1088 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1089
1090 canvas->drawPicture(macroPic);
1091 return "";
1092 });
1093}
1094
mtklein748ca3b2015-01-15 10:56:12 -08001095} // namespace DM