blob: 12530142d29f013eff4f65162721aff7e0437dcc [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
mtkleine0effd62015-07-29 06:37:28 -070082Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -080083 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -080084 if (!encoded) {
85 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
86 }
emmaleer8f4ba762015-08-14 07:44:46 -070087 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -070088 if (nullptr == codec.get()) {
emmaleer8f4ba762015-08-14 07:44:46 -070089 // scaledCodec not supported, try normal codec
90 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -070091 if (nullptr == codec.get()) {
emmaleer8f4ba762015-08-14 07:44:46 -070092 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
93 }
scroggo9b77ddd2015-03-19 06:03:39 -070094 }
95
msarett438b2ad2015-04-09 12:43:10 -070096 // Choose the color type to decode to
97 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -070098 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -070099 switch (fDstColorType) {
100 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700101 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
102 if (kRGB_565_SkColorType == canvasColorType) {
103 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
104 }
105 break;
msarett438b2ad2015-04-09 12:43:10 -0700106 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700107 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700108 if (kRGB_565_SkColorType == canvasColorType) {
109 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
110 }
111 break;
112 default:
113 decodeInfo = decodeInfo.makeColorType(canvasColorType);
114 break;
115 }
116
msarett0a242972015-06-11 14:27:27 -0700117 // Try to scale the image if it is desired
118 SkISize size = codec->getScaledDimensions(fScale);
119 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
120 return Error::Nonfatal("Test without scaling is uninteresting.");
121 }
msarettb32758a2015-08-18 13:22:46 -0700122
123 // Visually inspecting very small output images is not necessary. We will
124 // cover these cases in unit testing.
125 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
126 return Error::Nonfatal("Scaling very small images is uninteresting.");
127 }
msarett0a242972015-06-11 14:27:27 -0700128 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
129
msarett438b2ad2015-04-09 12:43:10 -0700130 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700131 SkAutoTUnref<SkColorTable> colorTable(nullptr);
132 SkPMColor* colorPtr = nullptr;
133 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700134 int maxColors = 256;
135 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
136 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700137 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700138 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
139 colorCountPtr = &maxColors;
140 }
141
142 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700143 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700144 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
145 }
146
147 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700148 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700149 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
150 decodeInfo.width(), decodeInfo.height());
151 }
152
scroggo9c59ebc2015-03-25 13:48:49 -0700153 switch (fMode) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700154 case kNormal_Mode: {
halcanary96fcdcc2015-08-27 07:41:13 -0700155 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700156 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700157 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700158 // We consider incomplete to be valid, since we should still decode what is
159 // available.
scroggoeb602a52015-07-09 08:16:03 -0700160 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700161 break;
scroggoeb602a52015-07-09 08:16:03 -0700162 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700163 return Error::Nonfatal("Incompatible colortype conversion");
164 default:
165 // Everything else is considered a failure.
166 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
167 }
emmaleer97002062015-05-27 12:36:10 -0700168 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700169 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700170 }
scroggo9c59ebc2015-03-25 13:48:49 -0700171 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700172 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
173 SkScanlineDecoder::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700174 if (nullptr == scanlineDecoder || SkCodec::kSuccess !=
175 scanlineDecoder->start(decodeInfo, nullptr, colorPtr, colorCountPtr)) {
scroggo9c59ebc2015-03-25 13:48:49 -0700176 return Error::Nonfatal("Cannot use scanline decoder for all images");
177 }
scroggo1c005e42015-08-04 09:24:45 -0700178
scroggoeb602a52015-07-09 08:16:03 -0700179 const SkCodec::Result result = scanlineDecoder->getScanlines(
emmaleer0a4c3cb2015-06-22 10:40:21 -0700180 bitmap.getAddr(0, 0), decodeInfo.height(), bitmap.rowBytes());
181 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700182 case SkCodec::kSuccess:
183 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700184 break;
185 default:
186 return SkStringPrintf("%s failed with error message %d",
187 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700188 }
emmaleer97002062015-05-27 12:36:10 -0700189 canvas->drawBitmap(bitmap, 0, 0);
190 break;
191 }
192 case kScanline_Subset_Mode: {
193 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
194 const int divisor = 2;
195 const int w = decodeInfo.width();
196 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700197 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700198 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
199 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700200 }
201 const int subsetWidth = w/divisor;
202 const int subsetHeight = h/divisor;
203 // One of our subsets will be larger to contain any pixels that do not divide evenly.
204 const int extraX = w % divisor;
205 const int extraY = h % divisor;
206 /*
207 * if w or h are not evenly divided by divisor need to adjust width and height of end
208 * subsets to cover entire image.
209 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
210 * and height of end subsets.
211 * subsetBm is extracted from largestSubsetBm.
212 * subsetBm's size is determined based on the current subset and may be larger for end
213 * subsets.
214 */
msarett0a242972015-06-11 14:27:27 -0700215 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700216 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
217 SkBitmap largestSubsetBm;
halcanary96fcdcc2015-08-27 07:41:13 -0700218 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr, colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700219 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
220 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
221 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700222 const size_t rowBytes = decodeInfo.minRowBytes();
halcanary385fe4d2015-08-26 13:07:48 -0700223 char* buffer = new char[largestSubsetDecodeInfo.height() * rowBytes];
emmaleer0a4c3cb2015-06-22 10:40:21 -0700224 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700225 for (int col = 0; col < divisor; col++) {
226 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
227 const int currentSubsetWidth = (col + 1 == divisor) ?
228 subsetWidth + extraX : subsetWidth;
229 const int x = col * subsetWidth;
230 for (int row = 0; row < divisor; row++) {
231 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
232 const int currentSubsetHeight = (row + 1 == divisor) ?
233 subsetHeight + extraY : subsetHeight;
234 const int y = row * subsetHeight;
235 //create scanline decoder for each subset
scroggo9b2cdbf42015-07-10 12:07:02 -0700236 SkAutoTDelete<SkScanlineDecoder> subsetScanlineDecoder(
scroggo1c005e42015-08-04 09:24:45 -0700237 SkScanlineDecoder::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700238 if (nullptr == subsetScanlineDecoder || SkCodec::kSuccess !=
scroggo1c005e42015-08-04 09:24:45 -0700239 subsetScanlineDecoder->start(
halcanary96fcdcc2015-08-27 07:41:13 -0700240 decodeInfo, nullptr, colorPtr, colorCountPtr))
scroggo1c005e42015-08-04 09:24:45 -0700241 {
emmaleer97002062015-05-27 12:36:10 -0700242 if (x == 0 && y == 0) {
243 //first try, image may not be compatible
244 return Error::Nonfatal("Cannot use scanline decoder for all images");
245 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700246 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700247 }
248 }
249 //skip to first line of subset
scroggoeb602a52015-07-09 08:16:03 -0700250 const SkCodec::Result skipResult =
emmaleer97002062015-05-27 12:36:10 -0700251 subsetScanlineDecoder->skipScanlines(y);
252 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700253 case SkCodec::kSuccess:
254 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700255 break;
256 default:
257 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
258 "with error message %d", fPath.c_str(), y, (int) skipResult);
259 }
260 //create and set size of subsetBm
261 SkBitmap subsetBm;
262 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
263 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
264 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
265 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700266 const SkCodec::Result subsetResult =
emmaleer0a4c3cb2015-06-22 10:40:21 -0700267 subsetScanlineDecoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
268 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700269 case SkCodec::kSuccess:
270 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700271 break;
272 default:
mtkleind2baa902015-07-07 09:43:28 -0700273 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700274 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700275 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700276 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700277 /*
278 * we copy all the lines at once becuase when calling getScanlines for
279 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700280 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
281 * decode the entire image height times, which is very slow
282 * it is aknowledged that copying each line as you read it in a loop
283 * may be faster for other types of images. Since this is a correctness test
284 * that's okay.
285 */
mtkleind2baa902015-07-07 09:43:28 -0700286 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700287 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700288 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700289 currentSubsetWidth*bpp);
290 bufferRow += rowBytes;
291 }
mtkleind2baa902015-07-07 09:43:28 -0700292
scroggo4358f132015-07-30 11:33:04 -0700293 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700294 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
295 }
296 }
scroggo9c59ebc2015-03-25 13:48:49 -0700297 break;
298 }
msarett0a242972015-06-11 14:27:27 -0700299 case kStripe_Mode: {
300 const int height = decodeInfo.height();
301 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
302 // does not align with image blocks.
303 const int stripeHeight = 37;
304 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
305
306 // Decode odd stripes
scroggo1c005e42015-08-04 09:24:45 -0700307 SkAutoTDelete<SkScanlineDecoder> decoder(SkScanlineDecoder::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700308 if (nullptr == decoder || SkCodec::kSuccess !=
309 decoder->start(decodeInfo, nullptr, colorPtr, colorCountPtr)) {
msarett0a242972015-06-11 14:27:27 -0700310 return Error::Nonfatal("Cannot use scanline decoder for all images");
311 }
312 for (int i = 0; i < numStripes; i += 2) {
313 // Skip a stripe
314 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700315 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700316 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700317 case SkCodec::kSuccess:
318 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700319 break;
320 default:
321 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
322 }
323
324 // Read a stripe
325 const int startY = (i + 1) * stripeHeight;
326 const int linesToRead = SkTMin(stripeHeight, height - startY);
327 if (linesToRead > 0) {
328 result = decoder->getScanlines(bitmap.getAddr(0, startY),
329 linesToRead, bitmap.rowBytes());
330 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700331 case SkCodec::kSuccess:
332 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700333 break;
334 default:
335 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
336 }
337 }
338 }
339
340 // Decode even stripes
halcanary96fcdcc2015-08-27 07:41:13 -0700341 const SkCodec::Result startResult = decoder->start(decodeInfo, nullptr, colorPtr,
scroggo1c005e42015-08-04 09:24:45 -0700342 colorCountPtr);
343 if (SkCodec::kSuccess != startResult) {
344 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700345 }
346 for (int i = 0; i < numStripes; i += 2) {
347 // Read a stripe
348 const int startY = i * stripeHeight;
349 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700350 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700351 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 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700361 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
362 if (linesToSkip > 0) {
363 result = decoder->skipScanlines(linesToSkip);
364 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700365 case SkCodec::kSuccess:
366 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700367 break;
368 default:
369 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
370 }
msarett0a242972015-06-11 14:27:27 -0700371 }
372 }
373 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700374 break;
msarett0a242972015-06-11 14:27:27 -0700375 }
scroggob636b452015-07-22 07:16:20 -0700376 case kSubset_Mode: {
377 // Arbitrarily choose a divisor.
378 int divisor = 2;
379 // Total width/height of the image.
380 const int W = codec->getInfo().width();
381 const int H = codec->getInfo().height();
382 if (divisor > W || divisor > H) {
383 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
384 "for %s with dimensions (%d x %d)", divisor,
385 fPath.c_str(), W, H));
386 }
387 // subset dimensions
388 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
389 const int w = SkAlign2(W / divisor);
390 const int h = SkAlign2(H / divisor);
391 SkIRect subset;
392 SkCodec::Options opts;
393 opts.fSubset = &subset;
394 SkBitmap subsetBm;
395 // We will reuse pixel memory from bitmap.
396 void* pixels = bitmap.getPixels();
397 // Keep track of left and top (for drawing subsetBm into canvas). We could use
398 // fScale * x and fScale * y, but we want integers such that the next subset will start
399 // where the last one ended. So we'll add decodeInfo.width() and height().
400 int left = 0;
401 for (int x = 0; x < W; x += w) {
402 int top = 0;
403 for (int y = 0; y < H; y+= h) {
404 // Do not make the subset go off the edge of the image.
405 const int preScaleW = SkTMin(w, W - x);
406 const int preScaleH = SkTMin(h, H - y);
407 subset.setXYWH(x, y, preScaleW, preScaleH);
408 // And scale
409 // FIXME: Should we have a version of getScaledDimensions that takes a subset
410 // into account?
411 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
412 SkScalarRoundToInt(preScaleH * fScale));
413 size_t rowBytes = decodeInfo.minRowBytes();
414 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700415 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700416 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
417 }
418 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
419 &opts, colorPtr, colorCountPtr);
420 switch (result) {
421 case SkCodec::kSuccess:
422 case SkCodec::kIncompleteInput:
423 break;
424 case SkCodec::kInvalidConversion:
425 if (0 == (x|y)) {
426 // First subset is okay to return unimplemented.
427 return Error::Nonfatal("Incompatible colortype conversion");
428 }
429 // If the first subset succeeded, a later one should not fail.
430 // fall through to failure
431 case SkCodec::kUnimplemented:
432 if (0 == (x|y)) {
433 // First subset is okay to return unimplemented.
434 return Error::Nonfatal("subset codec not supported");
435 }
436 // If the first subset succeeded, why would a later one fail?
437 // fall through to failure
438 default:
439 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
440 "from %s with dimensions (%d x %d)\t error %d",
441 x, y, decodeInfo.width(), decodeInfo.height(),
442 fPath.c_str(), W, H, result);
443 }
444 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
445 // translate by the scaled height.
446 top += decodeInfo.height();
447 }
448 // translate by the scaled width.
449 left += decodeInfo.width();
450 }
451 return "";
452 }
scroggo9b77ddd2015-03-19 06:03:39 -0700453 }
scroggo9c59ebc2015-03-25 13:48:49 -0700454 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700455}
456
457SkISize CodecSrc::size() const {
458 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700459 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700460 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700461 // scaledCodec not supported, try regular codec
462 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700463 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700464 return SkISize::Make(0, 0);
465 }
msarett9bde9182015-03-25 05:27:48 -0700466 }
emmaleer8f4ba762015-08-14 07:44:46 -0700467 SkISize size = codec->getScaledDimensions(fScale);
468 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700469}
470
471Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700472 if (1.0f == fScale) {
473 return SkOSPath::Basename(fPath.c_str());
474 } else {
475 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(fPath.c_str()).c_str(), fScale);
476 }
scroggo9b77ddd2015-03-19 06:03:39 -0700477}
478
479/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
480
481ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
482
mtklein99cab4e2015-07-31 06:43:04 -0700483bool ImageSrc::veto(SinkFlags flags) const {
484 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700485 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700486 return flags.type != SinkFlags::kRaster
487 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700488}
scroggo9b77ddd2015-03-19 06:03:39 -0700489
mtkleine0effd62015-07-29 06:37:28 -0700490Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700491 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
492 if (!encoded) {
493 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
494 }
mtkleine0effd62015-07-29 06:37:28 -0700495 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800496 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800497 // Decode the full image.
498 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700499 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
500 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
501 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
502 }
503 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
504 // Do not draw a bitmap with alpha to a destination without alpha.
505 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800506 }
halcanary96fcdcc2015-08-27 07:41:13 -0700507 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800508 canvas->drawBitmap(bitmap, 0,0);
509 return "";
510 }
mtkleinedc93bc2015-01-30 13:22:23 -0800511 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800512 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
513 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800514 if (!decoder) {
515 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
516 }
scroggoa1193e42015-01-21 12:09:53 -0800517 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800518 int w,h;
msarett70542572015-06-19 07:44:05 -0700519 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800520 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800521 }
mtkleinedc93bc2015-01-30 13:22:23 -0800522
523 // Divide the image into subsets that cover the entire image.
524 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700525 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
526 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800527 }
528 const int subsetWidth = w / fDivisor,
529 subsetHeight = h / fDivisor;
530 for (int y = 0; y < h; y += subsetHeight) {
531 for (int x = 0; x < w; x += subsetWidth) {
532 SkBitmap subset;
533 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
534 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
535 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
536 x, y, x+subsetWidth, y+subsetHeight);
537 }
scroggo56e25dd2015-03-05 11:46:40 -0800538 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
539 // Do not draw a bitmap with alpha to a destination without alpha.
540 // This is not an error, but there is nothing interesting to show.
541
542 // This should only happen on the first iteration through the loop.
543 SkASSERT(0 == x && 0 == y);
544
545 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
546 }
mtkleinedc93bc2015-01-30 13:22:23 -0800547 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800548 }
mtklein748ca3b2015-01-15 10:56:12 -0800549 }
550 return "";
551}
552
553SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800554 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700555 SkBitmap bitmap;
556 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
557 encoded->size(),
558 &bitmap,
559 kUnknown_SkColorType,
560 SkImageDecoder::kDecodeBounds_Mode)) {
561 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800562 }
scroggo9b77ddd2015-03-19 06:03:39 -0700563 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800564}
565
mtklein9264a952015-01-20 10:11:53 -0800566Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800567 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800568}
mtklein748ca3b2015-01-15 10:56:12 -0800569
570/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
571
mtkleinf4ba3212015-01-28 15:32:24 -0800572static const SkRect kSKPViewport = {0,0, 1000,1000};
573
mtklein8d17a132015-01-30 11:42:31 -0800574SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800575
576Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800577 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800578 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800579 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
580 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700581 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800582 if (!pic) {
583 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
584 }
halcanary96fcdcc2015-08-27 07:41:13 -0700585 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700586
mtkleinf4ba3212015-01-28 15:32:24 -0800587 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800588 canvas->drawPicture(pic);
589 return "";
590}
591
592SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700593 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
594 if (!stream) {
595 return SkISize::Make(0,0);
596 }
597 SkPictInfo info;
598 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
599 return SkISize::Make(0,0);
600 }
601 SkRect viewport = kSKPViewport;
602 if (!viewport.intersect(info.fCullRect)) {
603 return SkISize::Make(0,0);
604 }
605 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800606}
607
608Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
609
610/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
611
mtkleinad66f9b2015-02-13 15:11:10 -0800612Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
613 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
614 return src.draw(canvas);
615}
616
617/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
618
mtkleinb9eb4ac2015-02-02 18:26:03 -0800619DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
620
mtklein82d28432015-01-15 12:46:02 -0800621GPUSink::GPUSink(GrContextFactory::GLContextType ct,
622 GrGLStandard api,
623 int samples,
624 bool dfText,
625 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800626 : fContextType(ct)
627 , fGpuAPI(api)
628 , fSampleCount(samples)
mtklein82d28432015-01-15 12:46:02 -0800629 , fUseDFText(dfText)
630 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800631
632int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800633 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800634}
635
joshualitt5f5a8d72015-02-25 14:09:45 -0800636void PreAbandonGpuContextErrorHandler(SkError, void*) {}
637
mtkleinb9eb4ac2015-02-02 18:26:03 -0800638Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700639 GrContextOptions options;
640 src.modifyGrContextOptions(&options);
641
642 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800643 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800644 const SkImageInfo info =
645 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
646 SkAutoTUnref<SkSurface> surface(
mtklein55e88b22015-01-21 15:50:13 -0800647 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDFText));
mtklein748ca3b2015-01-15 10:56:12 -0800648 if (!surface) {
649 return "Could not create a surface.";
650 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800651 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700652 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800653 factory.abandonContexts();
654 }
mtklein748ca3b2015-01-15 10:56:12 -0800655 SkCanvas* canvas = surface->getCanvas();
656 Error err = src.draw(canvas);
657 if (!err.isEmpty()) {
658 return err;
659 }
660 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800661 if (FLAGS_gpuStats) {
662 canvas->getGrContext()->dumpCacheStats(log);
663 canvas->getGrContext()->dumpGpuStats(log);
664 }
mtklein748ca3b2015-01-15 10:56:12 -0800665 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800666 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800667 if (FLAGS_abandonGpuContext) {
668 factory.abandonContexts();
669 }
mtklein748ca3b2015-01-15 10:56:12 -0800670 return "";
671}
672
673/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
674
halcanary47ef4d52015-03-03 09:13:09 -0800675static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
676 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
677 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800678 int width = src.size().width(),
679 height = src.size().height();
680
halcanary7e798182015-04-14 14:06:18 -0700681 if (FLAGS_multiPage) {
682 const int kLetterWidth = 612, // 8.5 * 72
683 kLetterHeight = 792; // 11 * 72
684 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
685 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800686
halcanary7e798182015-04-14 14:06:18 -0700687 int xPages = ((width - 1) / kLetterWidth) + 1;
688 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800689
halcanary7e798182015-04-14 14:06:18 -0700690 for (int y = 0; y < yPages; ++y) {
691 for (int x = 0; x < xPages; ++x) {
692 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
693 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
694 SkCanvas* canvas =
695 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
696 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700697 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700698 }
699 canvas->clipRect(letter);
700 canvas->translate(-letter.width() * x, -letter.height() * y);
701 Error err = src.draw(canvas);
702 if (!err.isEmpty()) {
703 return err;
704 }
705 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700706 }
halcanaryfd4a9932015-01-28 11:45:58 -0800707 }
halcanary7e798182015-04-14 14:06:18 -0700708 } else {
709 SkCanvas* canvas =
710 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
711 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700712 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700713 }
714 Error err = src.draw(canvas);
715 if (!err.isEmpty()) {
716 return err;
717 }
718 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800719 }
halcanary7e798182015-04-14 14:06:18 -0700720 if (!doc->close()) {
721 return "SkDocument::close() returned false";
722 }
halcanaryfd4a9932015-01-28 11:45:58 -0800723 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800724 return "";
725}
726
halcanary47ef4d52015-03-03 09:13:09 -0800727PDFSink::PDFSink() {}
728
729Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
730 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
731 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700732 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800733 }
734 return draw_skdocument(src, doc.get(), dst);
735}
736
737/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
738
739XPSSink::XPSSink() {}
740
741Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
742 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
743 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700744 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800745 }
746 return draw_skdocument(src, doc.get(), dst);
747}
mtklein748ca3b2015-01-15 10:56:12 -0800748/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
749
mtklein9c3f17d2015-01-28 11:35:18 -0800750SKPSink::SKPSink() {}
751
mtkleinb9eb4ac2015-02-02 18:26:03 -0800752Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800753 SkSize size;
754 size = src.size();
755 SkPictureRecorder recorder;
756 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
757 if (!err.isEmpty()) {
758 return err;
759 }
760 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
761 pic->serialize(dst);
762 return "";
763}
764
765/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
766
mtklein8a4527e2015-01-31 20:00:58 -0800767SVGSink::SVGSink() {}
768
mtkleinb9eb4ac2015-02-02 18:26:03 -0800769Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -0700770 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -0800771 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
772 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
773 xmlWriter));
774 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800775}
776
777/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
778
mtklein748ca3b2015-01-15 10:56:12 -0800779RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
780
mtkleinb9eb4ac2015-02-02 18:26:03 -0800781Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800782 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800783 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
784 SkAlphaType alphaType = kPremul_SkAlphaType;
785 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
786
787 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
788 dst->eraseColor(SK_ColorTRANSPARENT);
789 SkCanvas canvas(*dst);
790 return src.draw(&canvas);
791}
792
793/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
794
mtkleina16e69e2015-05-05 11:38:45 -0700795// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -0700796// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -0700797// Several examples below.
798
mtkleina16e69e2015-05-05 11:38:45 -0700799static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -0700800 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -0700801 class ProxySrc : public Src {
802 public:
mtkleine44b5082015-05-07 10:53:34 -0700803 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -0700804 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
805 Name name() const override { sk_throw(); return ""; } // Won't be called.
806 SkISize size() const override { return fSize; }
807 private:
mtkleine44b5082015-05-07 10:53:34 -0700808 SkISize fSize;
809 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -0700810 };
811 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
812}
813
814/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
815
mtkleind603b222015-02-17 11:13:33 -0800816static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
817 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
818 matrix->mapRect(&bounds);
819 matrix->postTranslate(-bounds.x(), -bounds.y());
820 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
821}
822
mtklein78829242015-05-06 07:54:07 -0700823ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -0800824
mtkleinb9eb4ac2015-02-02 18:26:03 -0800825Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700826 SkMatrix matrix = fMatrix;
827 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
828 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
829 canvas->concat(matrix);
830 return src.draw(canvas);
831 });
mtklein748ca3b2015-01-15 10:56:12 -0800832}
833
mtkleind603b222015-02-17 11:13:33 -0800834// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
835// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -0700836ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -0800837
838Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
839 Error err = fSink->draw(src, bitmap, stream, log);
840 if (!err.isEmpty()) {
841 return err;
842 }
843
844 SkMatrix inverse;
845 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
846 return "Cannot upright --matrix.";
847 }
848 SkMatrix upright = SkMatrix::I();
849 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
850 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
851 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
852 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
853
854 SkBitmap uprighted;
855 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
856 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
857
858 SkCanvas canvas(uprighted);
859 canvas.concat(upright);
860 SkPaint paint;
861 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
862 canvas.drawBitmap(*bitmap, 0, 0, &paint);
863
864 *bitmap = uprighted;
865 bitmap->lockPixels();
866 return "";
867}
868
mtklein748ca3b2015-01-15 10:56:12 -0800869/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
870
mtkleinb9eb4ac2015-02-02 18:26:03 -0800871Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700872 auto size = src.size();
873 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
874 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
875 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -0700876 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -0700877 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
878 });
mtklein748ca3b2015-01-15 10:56:12 -0800879}
880
881/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -0700882
mtkleina16e69e2015-05-05 11:38:45 -0700883Error ViaSerialization::draw(
884 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -0800885 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -0700886 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800887 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700888 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
889 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -0800890 if (!err.isEmpty()) {
891 return err;
892 }
893 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
894
895 // Serialize it and then deserialize it.
896 SkDynamicMemoryWStream wStream;
897 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -0800898 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -0700899 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -0800900
mtkleina16e69e2015-05-05 11:38:45 -0700901 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
902 canvas->drawPicture(deserialized);
903 return "";
904 });
mtklein748ca3b2015-01-15 10:56:12 -0800905}
906
907/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
908
909ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -0700910 : Via(sink)
911 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -0800912 , fH(h)
mtklein78829242015-05-06 07:54:07 -0700913 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -0800914
mtkleinb9eb4ac2015-02-02 18:26:03 -0800915Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700916 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800917 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -0700918 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
919 SkIntToScalar(size.height()),
920 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800921 if (!err.isEmpty()) {
922 return err;
923 }
mtkleinb7e8d692015-04-07 08:30:32 -0700924 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -0800925
mtkleina16e69e2015-05-05 11:38:45 -0700926 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
927 const int xTiles = (size.width() + fW - 1) / fW,
928 yTiles = (size.height() + fH - 1) / fH;
929 SkMultiPictureDraw mpd(xTiles*yTiles);
930 SkTDArray<SkSurface*> surfaces;
931 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -0800932
mtkleina16e69e2015-05-05 11:38:45 -0700933 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
934 for (int j = 0; j < yTiles; j++) {
935 for (int i = 0; i < xTiles; i++) {
936 // This lets our ultimate Sink determine the best kind of surface.
937 // E.g., if it's a GpuSink, the surfaces and images are textures.
938 SkSurface* s = canvas->newSurface(info);
939 if (!s) {
940 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -0800941 }
mtkleina16e69e2015-05-05 11:38:45 -0700942 surfaces.push(s);
943 SkCanvas* c = s->getCanvas();
944 c->translate(SkIntToScalar(-i * fW),
945 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
946 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -0800947 }
mtklein748ca3b2015-01-15 10:56:12 -0800948 }
mtkleina16e69e2015-05-05 11:38:45 -0700949 mpd.draw();
950 for (int j = 0; j < yTiles; j++) {
951 for (int i = 0; i < xTiles; i++) {
952 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
953 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
954 }
955 }
956 surfaces.unrefAll();
957 return "";
958 });
mtklein748ca3b2015-01-15 10:56:12 -0800959}
960
mtkleinb7e8d692015-04-07 08:30:32 -0700961/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
962
mtkleinb7e8d692015-04-07 08:30:32 -0700963// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
964// This tests that any shortcuts we may take while recording that second picture are legal.
965Error ViaSecondPicture::draw(
966 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -0700967 auto size = src.size();
968 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
969 SkPictureRecorder recorder;
970 SkAutoTUnref<SkPicture> pic;
971 for (int i = 0; i < 2; i++) {
972 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
973 SkIntToScalar(size.height())));
974 if (!err.isEmpty()) {
975 return err;
mtkleinb7e8d692015-04-07 08:30:32 -0700976 }
mtkleina16e69e2015-05-05 11:38:45 -0700977 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -0700978 }
mtkleina16e69e2015-05-05 11:38:45 -0700979 canvas->drawPicture(pic);
980 return "";
981 });
mtkleinb7e8d692015-04-07 08:30:32 -0700982}
983
mtkleind31c13d2015-05-05 12:59:56 -0700984/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
985
mtklein6fbf4b32015-05-06 11:35:40 -0700986// Draw the Src twice. This can help exercise caching.
987Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
988 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
989 for (int i = 0; i < 2; i++) {
990 SkAutoCanvasRestore acr(canvas, true/*save now*/);
991 canvas->clear(SK_ColorTRANSPARENT);
992 Error err = src.draw(canvas);
993 if (err.isEmpty()) {
994 return err;
995 }
996 }
997 return "";
998 });
999}
1000
1001/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1002
mtkleind31c13d2015-05-05 12:59:56 -07001003// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1004// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1005// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1006struct DrawsAsSingletonPictures {
1007 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001008 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001009
1010 SK_CREATE_MEMBER_DETECTOR(paint);
1011
1012 template <typename T>
1013 void draw(const T& op, SkCanvas* canvas) {
1014 // We must pass SkMatrix::I() as our initial matrix.
1015 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1016 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001017 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1018 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001019 }
1020
1021 // Most things that have paints are Draw-type ops. Create sub-pictures for each.
1022 template <typename T>
1023 SK_WHEN(HasMember_paint<T>, void) operator()(const T& op) {
1024 SkPictureRecorder rec;
1025 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1026 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1027 fCanvas->drawPicture(pic);
1028 }
1029
1030 // If you don't have a paint or are a SaveLayer, you're not a Draw-type op.
1031 // We cannot make subpictures out of these because they affect state. Draw them directly.
1032 template <typename T>
1033 SK_WHEN(!HasMember_paint<T>, void) operator()(const T& op) { this->draw(op, fCanvas); }
1034 void operator()(const SkRecords::SaveLayer& op) { this->draw(op, fCanvas); }
1035};
1036
mtkleind31c13d2015-05-05 12:59:56 -07001037// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1038// Then play back that macro picture into our wrapped sink.
1039Error ViaSingletonPictures::draw(
1040 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1041 auto size = src.size();
1042 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1043 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1044 SkRecord skr;
1045 SkRecorder recorder(&skr, size.width(), size.height());
1046 Error err = src.draw(&recorder);
1047 if (!err.isEmpty()) {
1048 return err;
1049 }
1050
1051 // Record our macro-picture, with each draw op as its own sub-picture.
1052 SkPictureRecorder macroRec;
1053 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1054 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001055
1056 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1057 const SkDrawableList empty;
1058
1059 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1060 macroCanvas,
1061 drawables ? *drawables : empty,
1062 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001063 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001064 skr.visit<void>(i, drawsAsSingletonPictures);
1065 }
1066 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1067
1068 canvas->drawPicture(macroPic);
1069 return "";
1070 });
1071}
1072
mtklein748ca3b2015-01-15 10:56:12 -08001073} // namespace DM