blob: 64c18fc95f819d7e6bd655aae09e3c14a12261a9 [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 }
88 // DM scanline test assume kTopDown scanline ordering. Other orderings are
89 // tested from within SkScaledCodec.
90 // TODO (msarett): Redesign the CodecSrc tests to improve our coverage of SkCodec and
91 // SkScanlineDecoder functionality. Maybe we should write code to explicitly
92 // test kNone, kOutOfOrder, and kBottomUp.
93 if (SkScanlineDecoder::kTopDown_SkScanlineOrder != scanlineDecoder->getScanlineOrder()) {
94 return nullptr;
95 }
96 if (SkCodec::kSuccess != scanlineDecoder->start(info, NULL, colorPtr, colorCountPtr)) {
97 return nullptr;
98 }
99 return scanlineDecoder.detach();
100}
101
mtkleine0effd62015-07-29 06:37:28 -0700102Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800103 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800104 if (!encoded) {
105 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
106 }
emmaleer8f4ba762015-08-14 07:44:46 -0700107 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700108 if (nullptr == codec.get()) {
emmaleer8f4ba762015-08-14 07:44:46 -0700109 // scaledCodec not supported, try normal codec
110 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700111 if (nullptr == codec.get()) {
emmaleer8f4ba762015-08-14 07:44:46 -0700112 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
113 }
scroggo9b77ddd2015-03-19 06:03:39 -0700114 }
115
msarett438b2ad2015-04-09 12:43:10 -0700116 // Choose the color type to decode to
117 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -0700118 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -0700119 switch (fDstColorType) {
120 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700121 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
122 if (kRGB_565_SkColorType == canvasColorType) {
123 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
124 }
125 break;
msarett438b2ad2015-04-09 12:43:10 -0700126 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700127 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700128 if (kRGB_565_SkColorType == canvasColorType) {
129 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
130 }
131 break;
132 default:
133 decodeInfo = decodeInfo.makeColorType(canvasColorType);
134 break;
135 }
136
msarett0a242972015-06-11 14:27:27 -0700137 // Try to scale the image if it is desired
138 SkISize size = codec->getScaledDimensions(fScale);
139 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
140 return Error::Nonfatal("Test without scaling is uninteresting.");
141 }
msarettb32758a2015-08-18 13:22:46 -0700142
143 // Visually inspecting very small output images is not necessary. We will
144 // cover these cases in unit testing.
145 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
146 return Error::Nonfatal("Scaling very small images is uninteresting.");
147 }
msarett0a242972015-06-11 14:27:27 -0700148 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
149
msarett438b2ad2015-04-09 12:43:10 -0700150 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700151 SkAutoTUnref<SkColorTable> colorTable(nullptr);
152 SkPMColor* colorPtr = nullptr;
153 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700154 int maxColors = 256;
155 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
156 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700157 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700158 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
159 colorCountPtr = &maxColors;
160 }
161
162 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700163 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700164 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
165 }
166
167 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700168 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700169 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
170 decodeInfo.width(), decodeInfo.height());
171 }
172
scroggo9c59ebc2015-03-25 13:48:49 -0700173 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700174 case kNormal_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) {
195 return Error::Nonfatal("Could not start top-down 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;
halcanary96fcdcc2015-08-27 07:41:13 -0700237 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr, colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700238 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
239 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
240 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700241 const size_t rowBytes = decodeInfo.minRowBytes();
halcanary385fe4d2015-08-26 13:07:48 -0700242 char* buffer = new char[largestSubsetDecodeInfo.height() * rowBytes];
emmaleer0a4c3cb2015-06-22 10:40:21 -0700243 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700244 for (int col = 0; col < divisor; col++) {
245 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
246 const int currentSubsetWidth = (col + 1 == divisor) ?
247 subsetWidth + extraX : subsetWidth;
248 const int x = col * subsetWidth;
249 for (int row = 0; row < divisor; row++) {
250 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
251 const int currentSubsetHeight = (row + 1 == divisor) ?
252 subsetHeight + extraY : subsetHeight;
253 const int y = row * subsetHeight;
254 //create scanline decoder for each subset
scroggo9b2cdbf42015-07-10 12:07:02 -0700255 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
msarett5406d6f2015-08-31 06:55:13 -0700256 start_scanline_decoder(encoded.get(), decodeInfo,
257 colorPtr, colorCountPtr));
258 if (nullptr == subsetScanlineDecoder) {
emmaleer97002062015-05-27 12:36:10 -0700259 if (x == 0 && y == 0) {
260 //first try, image may not be compatible
msarett5406d6f2015-08-31 06:55:13 -0700261 return Error::Nonfatal("Could not start top-down scanline decoder");
emmaleer97002062015-05-27 12:36:10 -0700262 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700263 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700264 }
265 }
266 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700267 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700268 subsetScanlineDecoder->skipScanlines(y);
269 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700270 case SkCodec::kSuccess:
271 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700272 break;
273 default:
274 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
275 "with error message %d", fPath.c_str(), y, (int) skipResult);
276 }
277 //create and set size of subsetBm
278 SkBitmap subsetBm;
279 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
280 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
281 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
282 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700283 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700284 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
285 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700286 case SkCodec::kSuccess:
287 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700288 break;
289 default:
mtkleind2baa902015-07-07 09:43:28 -0700290 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700291 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700292 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700293 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700294 /*
295 * we copy all the lines at once becuase when calling getScanlines for
296 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700297 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
298 * decode the entire image height times, which is very slow
299 * it is aknowledged that copying each line as you read it in a loop
300 * may be faster for other types of images. Since this is a correctness test
301 * that's okay.
302 */
mtkleind2baa902015-07-07 09:43:28 -0700303 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700304 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700305 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700306 currentSubsetWidth*bpp);
307 bufferRow += rowBytes;
308 }
mtkleind2baa902015-07-07 09:43:28 -0700309
scroggo4358f132015-07-30 11:33:04 -0700310 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700311 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
312 }
313 }
scroggo9c59ebc2015-03-25 13:48:49 -0700314 break;
315 }
msarett0a242972015-06-11 14:27:27 -0700316 case kStripe_Mode: {
317 const int height = decodeInfo.height();
318 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
319 // does not align with image blocks.
320 const int stripeHeight = 37;
321 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
322
323 // Decode odd stripes
msarett5406d6f2015-08-31 06:55:13 -0700324 SkAutoTDelete<SkScanlineDecoder> decoder(
325 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
326 if (nullptr == decoder) {
327 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700328 }
329 for (int i = 0; i < numStripes; i += 2) {
330 // Skip a stripe
331 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700332 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700333 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700334 case SkCodec::kSuccess:
335 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700336 break;
337 default:
338 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
339 }
340
341 // Read a stripe
342 const int startY = (i + 1) * stripeHeight;
343 const int linesToRead = SkTMin(stripeHeight, height - startY);
344 if (linesToRead > 0) {
345 result = decoder->getScanlines(bitmap.getAddr(0, startY),
346 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 }
356
357 // Decode even stripes
halcanary96fcdcc2015-08-27 07:41:13 -0700358 const SkCodec::Result startResult = decoder->start(decodeInfo, nullptr, colorPtr,
scroggo1c005e42015-08-04 09:24:45 -0700359 colorCountPtr);
360 if (SkCodec::kSuccess != startResult) {
361 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700362 }
363 for (int i = 0; i < numStripes; i += 2) {
364 // Read a stripe
365 const int startY = i * stripeHeight;
366 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700367 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700368 linesToRead, bitmap.rowBytes());
369 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700370 case SkCodec::kSuccess:
371 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700372 break;
373 default:
374 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
375 }
376
377 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700378 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
379 if (linesToSkip > 0) {
380 result = decoder->skipScanlines(linesToSkip);
381 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700382 case SkCodec::kSuccess:
383 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700384 break;
385 default:
386 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
387 }
msarett0a242972015-06-11 14:27:27 -0700388 }
389 }
390 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700391 break;
msarett0a242972015-06-11 14:27:27 -0700392 }
scroggob636b452015-07-22 07:16:20 -0700393 case kSubset_Mode: {
394 // Arbitrarily choose a divisor.
395 int divisor = 2;
396 // Total width/height of the image.
397 const int W = codec->getInfo().width();
398 const int H = codec->getInfo().height();
399 if (divisor > W || divisor > H) {
400 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
401 "for %s with dimensions (%d x %d)", divisor,
402 fPath.c_str(), W, H));
403 }
404 // subset dimensions
405 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
406 const int w = SkAlign2(W / divisor);
407 const int h = SkAlign2(H / divisor);
408 SkIRect subset;
409 SkCodec::Options opts;
410 opts.fSubset = &subset;
411 SkBitmap subsetBm;
412 // We will reuse pixel memory from bitmap.
413 void* pixels = bitmap.getPixels();
414 // Keep track of left and top (for drawing subsetBm into canvas). We could use
415 // fScale * x and fScale * y, but we want integers such that the next subset will start
416 // where the last one ended. So we'll add decodeInfo.width() and height().
417 int left = 0;
418 for (int x = 0; x < W; x += w) {
419 int top = 0;
420 for (int y = 0; y < H; y+= h) {
421 // Do not make the subset go off the edge of the image.
422 const int preScaleW = SkTMin(w, W - x);
423 const int preScaleH = SkTMin(h, H - y);
424 subset.setXYWH(x, y, preScaleW, preScaleH);
425 // And scale
426 // FIXME: Should we have a version of getScaledDimensions that takes a subset
427 // into account?
428 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
429 SkScalarRoundToInt(preScaleH * fScale));
430 size_t rowBytes = decodeInfo.minRowBytes();
431 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700432 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700433 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
434 }
435 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
436 &opts, colorPtr, colorCountPtr);
437 switch (result) {
438 case SkCodec::kSuccess:
439 case SkCodec::kIncompleteInput:
440 break;
441 case SkCodec::kInvalidConversion:
442 if (0 == (x|y)) {
443 // First subset is okay to return unimplemented.
444 return Error::Nonfatal("Incompatible colortype conversion");
445 }
446 // If the first subset succeeded, a later one should not fail.
447 // fall through to failure
448 case SkCodec::kUnimplemented:
449 if (0 == (x|y)) {
450 // First subset is okay to return unimplemented.
451 return Error::Nonfatal("subset codec not supported");
452 }
453 // If the first subset succeeded, why would a later one fail?
454 // fall through to failure
455 default:
456 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
457 "from %s with dimensions (%d x %d)\t error %d",
458 x, y, decodeInfo.width(), decodeInfo.height(),
459 fPath.c_str(), W, H, result);
460 }
461 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
462 // translate by the scaled height.
463 top += decodeInfo.height();
464 }
465 // translate by the scaled width.
466 left += decodeInfo.width();
467 }
468 return "";
469 }
scroggo9b77ddd2015-03-19 06:03:39 -0700470 }
scroggo9c59ebc2015-03-25 13:48:49 -0700471 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700472}
473
474SkISize CodecSrc::size() const {
475 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700476 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700477 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700478 // scaledCodec not supported, try regular codec
479 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700480 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700481 return SkISize::Make(0, 0);
482 }
msarett9bde9182015-03-25 05:27:48 -0700483 }
emmaleer8f4ba762015-08-14 07:44:46 -0700484 SkISize size = codec->getScaledDimensions(fScale);
485 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700486}
487
488Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700489 if (1.0f == fScale) {
490 return SkOSPath::Basename(fPath.c_str());
491 } else {
492 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
493 }
scroggo9b77ddd2015-03-19 06:03:39 -0700494}
495
496/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
497
498ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
499
mtklein99cab4e2015-07-31 06:43:04 -0700500bool ImageSrc::veto(SinkFlags flags) const {
501 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700502 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700503 return flags.type != SinkFlags::kRaster
504 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700505}
scroggo9b77ddd2015-03-19 06:03:39 -0700506
mtkleine0effd62015-07-29 06:37:28 -0700507Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700508 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
509 if (!encoded) {
510 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
511 }
mtkleine0effd62015-07-29 06:37:28 -0700512 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800513 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800514 // Decode the full image.
515 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700516 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
517 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
518 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
519 }
520 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
521 // Do not draw a bitmap with alpha to a destination without alpha.
522 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800523 }
halcanary96fcdcc2015-08-27 07:41:13 -0700524 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800525 canvas->drawBitmap(bitmap, 0,0);
526 return "";
527 }
mtkleinedc93bc2015-01-30 13:22:23 -0800528 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800529 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
530 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800531 if (!decoder) {
532 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
533 }
scroggoa1193e42015-01-21 12:09:53 -0800534 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800535 int w,h;
msarett70542572015-06-19 07:44:05 -0700536 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800537 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800538 }
mtkleinedc93bc2015-01-30 13:22:23 -0800539
540 // Divide the image into subsets that cover the entire image.
541 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700542 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
543 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800544 }
545 const int subsetWidth = w / fDivisor,
546 subsetHeight = h / fDivisor;
547 for (int y = 0; y < h; y += subsetHeight) {
548 for (int x = 0; x < w; x += subsetWidth) {
549 SkBitmap subset;
550 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
551 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
552 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
553 x, y, x+subsetWidth, y+subsetHeight);
554 }
scroggo56e25dd2015-03-05 11:46:40 -0800555 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
556 // Do not draw a bitmap with alpha to a destination without alpha.
557 // This is not an error, but there is nothing interesting to show.
558
559 // This should only happen on the first iteration through the loop.
560 SkASSERT(0 == x && 0 == y);
561
562 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
563 }
mtkleinedc93bc2015-01-30 13:22:23 -0800564 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800565 }
mtklein748ca3b2015-01-15 10:56:12 -0800566 }
567 return "";
568}
569
570SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800571 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700572 SkBitmap bitmap;
573 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
574 encoded->size(),
575 &bitmap,
576 kUnknown_SkColorType,
577 SkImageDecoder::kDecodeBounds_Mode)) {
578 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800579 }
scroggo9b77ddd2015-03-19 06:03:39 -0700580 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800581}
582
mtklein9264a952015-01-20 10:11:53 -0800583Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800584 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800585}
mtklein748ca3b2015-01-15 10:56:12 -0800586
587/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
588
mtkleinf4ba3212015-01-28 15:32:24 -0800589static const SkRect kSKPViewport = {0,0, 1000,1000};
590
mtklein8d17a132015-01-30 11:42:31 -0800591SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800592
593Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800594 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800595 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800596 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
597 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700598 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800599 if (!pic) {
600 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
601 }
halcanary96fcdcc2015-08-27 07:41:13 -0700602 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700603
mtkleinf4ba3212015-01-28 15:32:24 -0800604 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800605 canvas->drawPicture(pic);
606 return "";
607}
608
609SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700610 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
611 if (!stream) {
612 return SkISize::Make(0,0);
613 }
614 SkPictInfo info;
615 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
616 return SkISize::Make(0,0);
617 }
618 SkRect viewport = kSKPViewport;
619 if (!viewport.intersect(info.fCullRect)) {
620 return SkISize::Make(0,0);
621 }
622 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800623}
624
625Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
626
627/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
628
mtkleinad66f9b2015-02-13 15:11:10 -0800629Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
630 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
631 return src.draw(canvas);
632}
633
634/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
635
mtkleinb9eb4ac2015-02-02 18:26:03 -0800636DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
637
mtklein82d28432015-01-15 12:46:02 -0800638GPUSink::GPUSink(GrContextFactory::GLContextType ct,
639 GrGLStandard api,
640 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700641 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800642 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800643 : fContextType(ct)
644 , fGpuAPI(api)
645 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700646 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800647 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800648
649int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800650 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800651}
652
joshualitt5f5a8d72015-02-25 14:09:45 -0800653void PreAbandonGpuContextErrorHandler(SkError, void*) {}
654
mtkleinb9eb4ac2015-02-02 18:26:03 -0800655Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700656 GrContextOptions options;
657 src.modifyGrContextOptions(&options);
658
659 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800660 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800661 const SkImageInfo info =
662 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
663 SkAutoTUnref<SkSurface> surface(
bsalomonafcd7cd2015-08-31 12:39:41 -0700664 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800665 if (!surface) {
666 return "Could not create a surface.";
667 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800668 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700669 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800670 factory.abandonContexts();
671 }
mtklein748ca3b2015-01-15 10:56:12 -0800672 SkCanvas* canvas = surface->getCanvas();
673 Error err = src.draw(canvas);
674 if (!err.isEmpty()) {
675 return err;
676 }
677 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800678 if (FLAGS_gpuStats) {
679 canvas->getGrContext()->dumpCacheStats(log);
680 canvas->getGrContext()->dumpGpuStats(log);
681 }
mtklein748ca3b2015-01-15 10:56:12 -0800682 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800683 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800684 if (FLAGS_abandonGpuContext) {
685 factory.abandonContexts();
686 }
mtklein748ca3b2015-01-15 10:56:12 -0800687 return "";
688}
689
690/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
691
halcanary47ef4d52015-03-03 09:13:09 -0800692static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
693 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
694 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800695 int width = src.size().width(),
696 height = src.size().height();
697
halcanary7e798182015-04-14 14:06:18 -0700698 if (FLAGS_multiPage) {
699 const int kLetterWidth = 612, // 8.5 * 72
700 kLetterHeight = 792; // 11 * 72
701 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
702 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800703
halcanary7e798182015-04-14 14:06:18 -0700704 int xPages = ((width - 1) / kLetterWidth) + 1;
705 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800706
halcanary7e798182015-04-14 14:06:18 -0700707 for (int y = 0; y < yPages; ++y) {
708 for (int x = 0; x < xPages; ++x) {
709 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
710 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
711 SkCanvas* canvas =
712 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
713 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700714 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700715 }
716 canvas->clipRect(letter);
717 canvas->translate(-letter.width() * x, -letter.height() * y);
718 Error err = src.draw(canvas);
719 if (!err.isEmpty()) {
720 return err;
721 }
722 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700723 }
halcanaryfd4a9932015-01-28 11:45:58 -0800724 }
halcanary7e798182015-04-14 14:06:18 -0700725 } else {
726 SkCanvas* canvas =
727 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
728 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700729 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700730 }
731 Error err = src.draw(canvas);
732 if (!err.isEmpty()) {
733 return err;
734 }
735 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800736 }
halcanary7e798182015-04-14 14:06:18 -0700737 if (!doc->close()) {
738 return "SkDocument::close() returned false";
739 }
halcanaryfd4a9932015-01-28 11:45:58 -0800740 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800741 return "";
742}
743
halcanary47ef4d52015-03-03 09:13:09 -0800744PDFSink::PDFSink() {}
745
746Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
747 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
748 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700749 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800750 }
751 return draw_skdocument(src, doc.get(), dst);
752}
753
754/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
755
756XPSSink::XPSSink() {}
757
758Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
759 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
760 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700761 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800762 }
763 return draw_skdocument(src, doc.get(), dst);
764}
mtklein748ca3b2015-01-15 10:56:12 -0800765/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
766
mtklein9c3f17d2015-01-28 11:35:18 -0800767SKPSink::SKPSink() {}
768
mtkleinb9eb4ac2015-02-02 18:26:03 -0800769Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800770 SkSize size;
771 size = src.size();
772 SkPictureRecorder recorder;
773 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
774 if (!err.isEmpty()) {
775 return err;
776 }
777 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
778 pic->serialize(dst);
779 return "";
780}
781
782/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
783
mtklein8a4527e2015-01-31 20:00:58 -0800784SVGSink::SVGSink() {}
785
mtkleinb9eb4ac2015-02-02 18:26:03 -0800786Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -0700787 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -0800788 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
789 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
790 xmlWriter));
791 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800792}
793
794/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
795
mtklein748ca3b2015-01-15 10:56:12 -0800796RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
797
mtkleinb9eb4ac2015-02-02 18:26:03 -0800798Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800799 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800800 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
801 SkAlphaType alphaType = kPremul_SkAlphaType;
802 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
803
804 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
805 dst->eraseColor(SK_ColorTRANSPARENT);
806 SkCanvas canvas(*dst);
807 return src.draw(&canvas);
808}
809
810/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
811
mtkleina16e69e2015-05-05 11:38:45 -0700812// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700813// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700814// Several examples below.
815
mtkleina16e69e2015-05-05 11:38:45 -0700816static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700817 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700818 class ProxySrc : public Src {
819 public:
mtkleine44b5082015-05-07 10:53:34 -0700820 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700821 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
822 Name name() const override { sk_throw(); return ""; } // Won't be called.
823 SkISize size() const override { return fSize; }
824 private:
mtkleine44b5082015-05-07 10:53:34 -0700825 SkISize fSize;
826 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700827 };
828 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
829}
830
831/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
832
mtkleind603b222015-02-17 11:13:33 -0800833static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
834 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
835 matrix->mapRect(&bounds);
836 matrix->postTranslate(-bounds.x(), -bounds.y());
837 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
838}
839
mtklein78829242015-05-06 07:54:07 -0700840ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800841
mtkleinb9eb4ac2015-02-02 18:26:03 -0800842Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700843 SkMatrix matrix = fMatrix;
844 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
845 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
846 canvas->concat(matrix);
847 return src.draw(canvas);
848 });
mtklein748ca3b2015-01-15 10:56:12 -0800849}
850
mtkleind603b222015-02-17 11:13:33 -0800851// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
852// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700853ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800854
855Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
856 Error err = fSink->draw(src, bitmap, stream, log);
857 if (!err.isEmpty()) {
858 return err;
859 }
860
861 SkMatrix inverse;
862 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
863 return "Cannot upright --matrix.";
864 }
865 SkMatrix upright = SkMatrix::I();
866 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
867 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
868 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
869 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
870
871 SkBitmap uprighted;
872 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
873 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
874
875 SkCanvas canvas(uprighted);
876 canvas.concat(upright);
877 SkPaint paint;
878 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
879 canvas.drawBitmap(*bitmap, 0, 0, &paint);
880
881 *bitmap = uprighted;
882 bitmap->lockPixels();
883 return "";
884}
885
mtklein748ca3b2015-01-15 10:56:12 -0800886/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
887
mtkleinb9eb4ac2015-02-02 18:26:03 -0800888Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700889 auto size = src.size();
890 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
891 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
892 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -0700893 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -0700894 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
895 });
mtklein748ca3b2015-01-15 10:56:12 -0800896}
897
898/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700899
mtkleina16e69e2015-05-05 11:38:45 -0700900Error ViaSerialization::draw(
901 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800902 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700903 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800904 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700905 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
906 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800907 if (!err.isEmpty()) {
908 return err;
909 }
910 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
911
912 // Serialize it and then deserialize it.
913 SkDynamicMemoryWStream wStream;
914 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800915 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700916 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800917
mtkleina16e69e2015-05-05 11:38:45 -0700918 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
919 canvas->drawPicture(deserialized);
920 return "";
921 });
mtklein748ca3b2015-01-15 10:56:12 -0800922}
923
924/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
925
926ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700927 : Via(sink)
928 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800929 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700930 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800931
mtkleinb9eb4ac2015-02-02 18:26:03 -0800932Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700933 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800934 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700935 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
936 SkIntToScalar(size.height()),
937 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800938 if (!err.isEmpty()) {
939 return err;
940 }
mtkleinb7e8d692015-04-07 08:30:32 -0700941 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800942
mtkleina16e69e2015-05-05 11:38:45 -0700943 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
944 const int xTiles = (size.width() + fW - 1) / fW,
945 yTiles = (size.height() + fH - 1) / fH;
946 SkMultiPictureDraw mpd(xTiles*yTiles);
947 SkTDArray<SkSurface*> surfaces;
948 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800949
mtkleina16e69e2015-05-05 11:38:45 -0700950 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
951 for (int j = 0; j < yTiles; j++) {
952 for (int i = 0; i < xTiles; i++) {
953 // This lets our ultimate Sink determine the best kind of surface.
954 // E.g., if it's a GpuSink, the surfaces and images are textures.
955 SkSurface* s = canvas->newSurface(info);
956 if (!s) {
957 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800958 }
mtkleina16e69e2015-05-05 11:38:45 -0700959 surfaces.push(s);
960 SkCanvas* c = s->getCanvas();
961 c->translate(SkIntToScalar(-i * fW),
962 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
963 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800964 }
mtklein748ca3b2015-01-15 10:56:12 -0800965 }
mtkleina16e69e2015-05-05 11:38:45 -0700966 mpd.draw();
967 for (int j = 0; j < yTiles; j++) {
968 for (int i = 0; i < xTiles; i++) {
969 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
970 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
971 }
972 }
973 surfaces.unrefAll();
974 return "";
975 });
mtklein748ca3b2015-01-15 10:56:12 -0800976}
977
mtkleinb7e8d692015-04-07 08:30:32 -0700978/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
979
mtkleinb7e8d692015-04-07 08:30:32 -0700980// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
981// This tests that any shortcuts we may take while recording that second picture are legal.
982Error ViaSecondPicture::draw(
983 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700984 auto size = src.size();
985 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
986 SkPictureRecorder recorder;
987 SkAutoTUnref<SkPicture> pic;
988 for (int i = 0; i < 2; i++) {
989 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
990 SkIntToScalar(size.height())));
991 if (!err.isEmpty()) {
992 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700993 }
mtkleina16e69e2015-05-05 11:38:45 -0700994 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700995 }
mtkleina16e69e2015-05-05 11:38:45 -0700996 canvas->drawPicture(pic);
997 return "";
998 });
mtkleinb7e8d692015-04-07 08:30:32 -0700999}
1000
mtkleind31c13d2015-05-05 12:59:56 -07001001/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1002
mtklein6fbf4b32015-05-06 11:35:40 -07001003// Draw the Src twice. This can help exercise caching.
1004Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1005 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1006 for (int i = 0; i < 2; i++) {
1007 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1008 canvas->clear(SK_ColorTRANSPARENT);
1009 Error err = src.draw(canvas);
1010 if (err.isEmpty()) {
1011 return err;
1012 }
1013 }
1014 return "";
1015 });
1016}
1017
1018/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1019
mtkleind31c13d2015-05-05 12:59:56 -07001020// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1021// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1022// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1023struct DrawsAsSingletonPictures {
1024 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001025 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001026
1027 SK_CREATE_MEMBER_DETECTOR(paint);
1028
1029 template <typename T>
1030 void draw(const T& op, SkCanvas* canvas) {
1031 // We must pass SkMatrix::I() as our initial matrix.
1032 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1033 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001034 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1035 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001036 }
1037
1038 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1039 template <typename T>
1040 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1041 SkPictureRecorder rec;
1042 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1043 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1044 fCanvas->drawPicture(pic);
1045 }
1046
1047 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1048 // We cannot make subpictures out of these because they affect state. Draw them directly.
1049 template <typename T>
1050 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1051 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1052};
1053
mtkleind31c13d2015-05-05 12:59:56 -07001054// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1055// Then play back that macro picture into our wrapped sink.
1056Error ViaSingletonPictures::draw(
1057 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1058 auto size = src.size();
1059 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1060 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1061 SkRecord skr;
1062 SkRecorder recorder(&skr, size.width(), size.height());
1063 Error err = src.draw(&recorder);
1064 if (!err.isEmpty()) {
1065 return err;
1066 }
1067
1068 // Record our macro-picture, with each draw op as its own sub-picture.
1069 SkPictureRecorder macroRec;
1070 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1071 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001072
1073 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1074 const SkDrawableList empty;
1075
1076 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1077 macroCanvas,
1078 drawables ? *drawables : empty,
1079 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001080 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001081 skr.visit<void>(i, drawsAsSingletonPictures);
1082 }
1083 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1084
1085 canvas->drawPicture(macroPic);
1086 return "";
1087 });
1088}
1089
mtklein748ca3b2015-01-15 10:56:12 -08001090} // namespace DM