blob: 25b5f7b4609c615ee4973c5da44eaa6e83a49fd9 [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"
msarett7f691442015-09-22 11:56:16 -070011#include "SkCodecTools.h"
mtkleina16e69e2015-05-05 11:38:45 -070012#include "SkCommonFlags.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070013#include "SkData.h"
mtklein748ca3b2015-01-15 10:56:12 -080014#include "SkDocument.h"
joshualitt5f5a8d72015-02-25 14:09:45 -080015#include "SkError.h"
mtkleine44b5082015-05-07 10:53:34 -070016#include "SkFunction.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070017#include "SkImageGenerator.h"
mtklein748ca3b2015-01-15 10:56:12 -080018#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080019#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080020#include "SkOSFile.h"
mtkleinffa901a2015-03-16 10:38:07 -070021#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080022#include "SkPictureRecorder.h"
23#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070024#include "SkRecordDraw.h"
25#include "SkRecorder.h"
fmalita2aafe6f2015-02-06 12:51:10 -080026#include "SkSVGCanvas.h"
mtklein449d9b72015-09-28 10:33:02 -070027#include "SkScaledCodec.h"
mtkleina16e69e2015-05-05 11:38:45 -070028#include "SkScanlineDecoder.h"
scroggoa1193e42015-01-21 12:09:53 -080029#include "SkStream.h"
mtklein449d9b72015-09-28 10:33:02 -070030#include "SkTLogic.h"
fmalita2aafe6f2015-02-06 12:51:10 -080031#include "SkXMLWriter.h"
mtklein748ca3b2015-01-15 10:56:12 -080032
halcanary7e798182015-04-14 14:06:18 -070033DEFINE_bool(multiPage, false, "For document-type backends, render the source"
34 " into multiple pages");
35
mtkleinb3e5e4d2015-03-25 13:13:43 -070036static bool lazy_decode_bitmap(const void* src, size_t size, SkBitmap* dst) {
37 SkAutoTUnref<SkData> encoded(SkData::NewWithCopy(src, size));
reedd1146452015-09-25 06:56:57 -070038 return encoded && SkDEPRECATED_InstallDiscardablePixelRef(encoded, dst);
mtkleinb3e5e4d2015-03-25 13:13:43 -070039}
40
mtklein748ca3b2015-01-15 10:56:12 -080041namespace DM {
42
mtklein748ca3b2015-01-15 10:56:12 -080043GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
44
45Error GMSrc::draw(SkCanvas* canvas) const {
halcanary96fcdcc2015-08-27 07:41:13 -070046 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080047 canvas->concat(gm->getInitialTransform());
48 gm->draw(canvas);
49 return "";
50}
51
52SkISize GMSrc::size() const {
halcanary96fcdcc2015-08-27 07:41:13 -070053 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080054 return gm->getISize();
55}
56
57Name GMSrc::name() const {
halcanary96fcdcc2015-08-27 07:41:13 -070058 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080059 return gm->getName();
60}
61
bsalomon4ee6bd82015-05-27 13:23:23 -070062void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
halcanary96fcdcc2015-08-27 07:41:13 -070063 SkAutoTDelete<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -070064 gm->modifyGrContextOptions(options);
65}
66
mtklein748ca3b2015-01-15 10:56:12 -080067/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
68
msaretta5783ae2015-09-08 15:35:32 -070069BRDSrc::BRDSrc(Path path, SkBitmapRegionDecoderInterface::Strategy strategy, Mode mode,
70 CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
71 : fPath(path)
72 , fStrategy(strategy)
73 , fMode(mode)
74 , fDstColorType(dstColorType)
75 , fSampleSize(sampleSize)
76{}
77
78bool BRDSrc::veto(SinkFlags flags) const {
79 // No need to test to non-raster or indirect backends.
80 return flags.type != SinkFlags::kRaster
81 || flags.approach != SinkFlags::kDirect;
82}
83
84static SkBitmapRegionDecoderInterface* create_brd(Path path,
85 SkBitmapRegionDecoderInterface::Strategy strategy) {
86 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(path.c_str()));
87 if (!encoded) {
88 return NULL;
89 }
90 return SkBitmapRegionDecoderInterface::CreateBitmapRegionDecoder(new SkMemoryStream(encoded),
91 strategy);
92}
93
94Error BRDSrc::draw(SkCanvas* canvas) const {
95 SkColorType colorType = canvas->imageInfo().colorType();
96 if (kRGB_565_SkColorType == colorType &&
97 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
98 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
99 }
100 switch (fDstColorType) {
101 case CodecSrc::kGetFromCanvas_DstColorType:
102 break;
103 case CodecSrc::kIndex8_Always_DstColorType:
104 colorType = kIndex_8_SkColorType;
105 break;
106 case CodecSrc::kGrayscale_Always_DstColorType:
107 colorType = kGray_8_SkColorType;
108 break;
109 }
110
111 SkAutoTDelete<SkBitmapRegionDecoderInterface> brd(create_brd(fPath, fStrategy));
112 if (nullptr == brd.get()) {
113 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
114 }
115
116 const uint32_t width = brd->width();
117 const uint32_t height = brd->height();
118 // Visually inspecting very small output images is not necessary.
119 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
120 return Error::Nonfatal("Scaling very small images is uninteresting.");
121 }
122 switch (fMode) {
123 case kFullImage_Mode: {
124 SkAutoTDelete<SkBitmap> bitmap(brd->decodeRegion(0, 0, width, height, fSampleSize,
125 colorType));
126 if (nullptr == bitmap.get() || colorType != bitmap->colorType()) {
127 return Error::Nonfatal("Cannot convert to color type.\n");
128 }
129 canvas->drawBitmap(*bitmap, 0, 0);
130 return "";
131 }
132 case kDivisor_Mode: {
133 const uint32_t divisor = 2;
134 if (width < divisor || height < divisor) {
135 return Error::Nonfatal("Divisor is larger than image dimension.\n");
136 }
137
138 // Use a border to test subsets that extend outside the image.
139 // We will not allow the border to be larger than the image dimensions. Allowing
140 // these large borders causes off by one errors that indicate a problem with the
141 // test suite, not a problem with the implementation.
142 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
143 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
144 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
145
146 // We may need to clear the canvas to avoid uninitialized memory.
147 // Assume we are scaling a 780x780 image with sampleSize = 8.
148 // The output image should be 97x97.
149 // Each subset will be 390x390.
150 // Each scaled subset be 48x48.
151 // Four scaled subsets will only fill a 96x96 image.
152 // The bottom row and last column will not be touched.
153 // This is an unfortunate result of our rounding rules when scaling.
154 // Maybe we need to consider testing scaled subsets without trying to
155 // combine them to match the full scaled image? Or maybe this is the
156 // best we can do?
157 canvas->clear(0);
158
159 for (uint32_t x = 0; x < divisor; x++) {
160 for (uint32_t y = 0; y < divisor; y++) {
161 // Calculate the subset dimensions
162 uint32_t subsetWidth = width / divisor;
163 uint32_t subsetHeight = height / divisor;
164 const int left = x * subsetWidth;
165 const int top = y * subsetHeight;
166
167 // Increase the size of the last subset in each row or column, when the
168 // divisor does not divide evenly into the image dimensions
169 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
170 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
171
172 // Increase the size of the subset in order to have a border on each side
173 const int decodeLeft = left - unscaledBorder;
174 const int decodeTop = top - unscaledBorder;
175 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
176 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
177 SkAutoTDelete<SkBitmap> bitmap(brd->decodeRegion(decodeLeft,
178 decodeTop, decodeWidth, decodeHeight, fSampleSize, colorType));
179 if (nullptr == bitmap.get() || colorType != bitmap->colorType()) {
180 return Error::Nonfatal("Cannot convert to color type.\n");
181 }
182
183 canvas->drawBitmapRect(*bitmap,
184 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
185 (SkScalar) (subsetWidth / fSampleSize),
186 (SkScalar) (subsetHeight / fSampleSize)),
187 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
188 (SkScalar) (top / fSampleSize),
189 (SkScalar) (subsetWidth / fSampleSize),
190 (SkScalar) (subsetHeight / fSampleSize)),
191 nullptr);
192 }
193 }
194 return "";
195 }
196 default:
197 SkASSERT(false);
198 return "Error: Should not be reached.\n";
199 }
200}
201
202SkISize BRDSrc::size() const {
203 SkAutoTDelete<SkBitmapRegionDecoderInterface> brd(create_brd(fPath, fStrategy));
204 if (brd) {
205 return SkISize::Make(SkTMax(1, brd->width() / (int) fSampleSize),
206 SkTMax(1, brd->height() / (int) fSampleSize));
207 }
208 return SkISize::Make(0, 0);
209}
210
211static SkString get_scaled_name(const Path& path, float scale) {
212 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
213}
214
215Name BRDSrc::name() const {
216 // We will replicate the names used by CodecSrc so that images can
217 // be compared in Gold.
218 if (1 == fSampleSize) {
219 return SkOSPath::Basename(fPath.c_str());
220 }
msarett7f691442015-09-22 11:56:16 -0700221 return get_scaled_name(fPath, get_scale_from_sample_size(fSampleSize));
msaretta5783ae2015-09-08 15:35:32 -0700222}
223
224/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
225
msarett0a242972015-06-11 14:27:27 -0700226CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, float scale)
msarett438b2ad2015-04-09 12:43:10 -0700227 : fPath(path)
228 , fMode(mode)
229 , fDstColorType(dstColorType)
msarett0a242972015-06-11 14:27:27 -0700230 , fScale(scale)
msarett438b2ad2015-04-09 12:43:10 -0700231{}
mtklein748ca3b2015-01-15 10:56:12 -0800232
mtklein99cab4e2015-07-31 06:43:04 -0700233bool CodecSrc::veto(SinkFlags flags) const {
234 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700235 // TODO: Once we implement GPU paths (e.g. JPEG YUV), we should use a deferred decode to
236 // let the GPU handle it.
mtklein99cab4e2015-07-31 06:43:04 -0700237 return flags.type != SinkFlags::kRaster
238 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700239}
scroggo9b77ddd2015-03-19 06:03:39 -0700240
msarett5406d6f2015-08-31 06:55:13 -0700241SkScanlineDecoder* start_scanline_decoder(SkData* encoded, const SkImageInfo& info,
242 SkPMColor* colorPtr, int* colorCountPtr) {
243 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(SkScanlineDecoder::NewFromData(encoded));
244 if (nullptr == scanlineDecoder) {
245 return nullptr;
246 }
msarett5406d6f2015-08-31 06:55:13 -0700247 if (SkCodec::kSuccess != scanlineDecoder->start(info, NULL, colorPtr, colorCountPtr)) {
248 return nullptr;
249 }
250 return scanlineDecoder.detach();
251}
252
mtkleine0effd62015-07-29 06:37:28 -0700253Error CodecSrc::draw(SkCanvas* canvas) const {
mtklein75d98fd2015-01-18 07:05:01 -0800254 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800255 if (!encoded) {
256 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
257 }
msarett9e707a02015-09-01 14:57:57 -0700258 SkAutoTDelete<SkCodec> codec(NULL);
259 if (kScaledCodec_Mode == fMode) {
260 codec.reset(SkScaledCodec::NewFromData(encoded));
261 // TODO (msarett): This should fall through to a fatal error once we support scaled
262 // codecs for all image types.
halcanary96fcdcc2015-08-27 07:41:13 -0700263 if (nullptr == codec.get()) {
msarett9e707a02015-09-01 14:57:57 -0700264 return Error::Nonfatal(SkStringPrintf("Couldn't create scaled codec for %s.",
265 fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700266 }
msarett9e707a02015-09-01 14:57:57 -0700267 } else {
268 codec.reset(SkCodec::NewFromData(encoded));
269 }
270 if (nullptr == codec.get()) {
271 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700272 }
273
msarett438b2ad2015-04-09 12:43:10 -0700274 // Choose the color type to decode to
275 SkImageInfo decodeInfo = codec->getInfo();
mtkleine0effd62015-07-29 06:37:28 -0700276 SkColorType canvasColorType = canvas->imageInfo().colorType();
msarett438b2ad2015-04-09 12:43:10 -0700277 switch (fDstColorType) {
278 case kIndex8_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700279 decodeInfo = codec->getInfo().makeColorType(kIndex_8_SkColorType);
280 if (kRGB_565_SkColorType == canvasColorType) {
281 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
282 }
283 break;
msarett438b2ad2015-04-09 12:43:10 -0700284 case kGrayscale_Always_DstColorType:
msarette16b04a2015-04-15 07:32:19 -0700285 decodeInfo = codec->getInfo().makeColorType(kGray_8_SkColorType);
msarett438b2ad2015-04-09 12:43:10 -0700286 if (kRGB_565_SkColorType == canvasColorType) {
287 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
288 }
289 break;
290 default:
291 decodeInfo = decodeInfo.makeColorType(canvasColorType);
292 break;
293 }
294
msarett0a242972015-06-11 14:27:27 -0700295 // Try to scale the image if it is desired
296 SkISize size = codec->getScaledDimensions(fScale);
297 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
298 return Error::Nonfatal("Test without scaling is uninteresting.");
299 }
msarettb32758a2015-08-18 13:22:46 -0700300
301 // Visually inspecting very small output images is not necessary. We will
302 // cover these cases in unit testing.
303 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
304 return Error::Nonfatal("Scaling very small images is uninteresting.");
305 }
msarett0a242972015-06-11 14:27:27 -0700306 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
307
msarett438b2ad2015-04-09 12:43:10 -0700308 // Construct a color table for the decode if necessary
halcanary96fcdcc2015-08-27 07:41:13 -0700309 SkAutoTUnref<SkColorTable> colorTable(nullptr);
310 SkPMColor* colorPtr = nullptr;
311 int* colorCountPtr = nullptr;
msarett438b2ad2015-04-09 12:43:10 -0700312 int maxColors = 256;
313 if (kIndex_8_SkColorType == decodeInfo.colorType()) {
314 SkPMColor colors[256];
halcanary385fe4d2015-08-26 13:07:48 -0700315 colorTable.reset(new SkColorTable(colors, maxColors));
msarett438b2ad2015-04-09 12:43:10 -0700316 colorPtr = const_cast<SkPMColor*>(colorTable->readColors());
317 colorCountPtr = &maxColors;
318 }
319
320 // FIXME: Currently we cannot draw unpremultiplied sources.
scroggo9b77ddd2015-03-19 06:03:39 -0700321 if (decodeInfo.alphaType() == kUnpremul_SkAlphaType) {
scroggo9b77ddd2015-03-19 06:03:39 -0700322 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
323 }
324
325 SkBitmap bitmap;
halcanary96fcdcc2015-08-27 07:41:13 -0700326 if (!bitmap.tryAllocPixels(decodeInfo, nullptr, colorTable.get())) {
scroggo9b77ddd2015-03-19 06:03:39 -0700327 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
328 decodeInfo.width(), decodeInfo.height());
329 }
330
scroggo9c59ebc2015-03-25 13:48:49 -0700331 switch (fMode) {
msarett9e707a02015-09-01 14:57:57 -0700332 case kScaledCodec_Mode:
333 case kCodec_Mode: {
halcanary96fcdcc2015-08-27 07:41:13 -0700334 switch (codec->getPixels(decodeInfo, bitmap.getPixels(), bitmap.rowBytes(), nullptr,
msarett438b2ad2015-04-09 12:43:10 -0700335 colorPtr, colorCountPtr)) {
scroggoeb602a52015-07-09 08:16:03 -0700336 case SkCodec::kSuccess:
scroggo9c59ebc2015-03-25 13:48:49 -0700337 // We consider incomplete to be valid, since we should still decode what is
338 // available.
scroggoeb602a52015-07-09 08:16:03 -0700339 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700340 break;
scroggoeb602a52015-07-09 08:16:03 -0700341 case SkCodec::kInvalidConversion:
scroggo9c59ebc2015-03-25 13:48:49 -0700342 return Error::Nonfatal("Incompatible colortype conversion");
343 default:
344 // Everything else is considered a failure.
345 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
346 }
emmaleer97002062015-05-27 12:36:10 -0700347 canvas->drawBitmap(bitmap, 0, 0);
scroggo9c59ebc2015-03-25 13:48:49 -0700348 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700349 }
scroggo9c59ebc2015-03-25 13:48:49 -0700350 case kScanline_Mode: {
scroggo1c005e42015-08-04 09:24:45 -0700351 SkAutoTDelete<SkScanlineDecoder> scanlineDecoder(
msarett5406d6f2015-08-31 06:55:13 -0700352 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
353 if (nullptr == scanlineDecoder) {
msarett9e707a02015-09-01 14:57:57 -0700354 return Error::Nonfatal("Could not start scanline decoder");
scroggo9c59ebc2015-03-25 13:48:49 -0700355 }
scroggo1c005e42015-08-04 09:24:45 -0700356
msarett10522ff2015-09-07 08:54:01 -0700357 SkCodec::Result result = SkCodec::kUnimplemented;
358 switch (scanlineDecoder->getScanlineOrder()) {
359 case SkScanlineDecoder::kTopDown_SkScanlineOrder:
360 case SkScanlineDecoder::kBottomUp_SkScanlineOrder:
361 case SkScanlineDecoder::kNone_SkScanlineOrder:
362 result = scanlineDecoder->getScanlines(bitmap.getAddr(0, 0),
363 decodeInfo.height(), bitmap.rowBytes());
364 break;
365 case SkScanlineDecoder::kOutOfOrder_SkScanlineOrder: {
366 for (int y = 0; y < decodeInfo.height(); y++) {
367 int dstY = scanlineDecoder->getY();
368 void* dstPtr = bitmap.getAddr(0, dstY);
369 result = scanlineDecoder->getScanlines(dstPtr, 1, bitmap.rowBytes());
370 if (SkCodec::kSuccess != result && SkCodec::kIncompleteInput != result) {
371 return SkStringPrintf("%s failed with error message %d",
372 fPath.c_str(), (int) result);
373 }
374 }
375 break;
376 }
377 }
378
emmaleer0a4c3cb2015-06-22 10:40:21 -0700379 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700380 case SkCodec::kSuccess:
381 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700382 break;
383 default:
384 return SkStringPrintf("%s failed with error message %d",
385 fPath.c_str(), (int) result);
scroggo9c59ebc2015-03-25 13:48:49 -0700386 }
emmaleer97002062015-05-27 12:36:10 -0700387 canvas->drawBitmap(bitmap, 0, 0);
388 break;
389 }
390 case kScanline_Subset_Mode: {
391 //this mode decodes the image in divisor*divisor subsets, using a scanline decoder
392 const int divisor = 2;
393 const int w = decodeInfo.width();
394 const int h = decodeInfo.height();
emmaleer97002062015-05-27 12:36:10 -0700395 if (divisor > w || divisor > h) {
msarett70542572015-06-19 07:44:05 -0700396 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
397 "for %s with dimensions (%d x %d)", divisor, fPath.c_str(), w, h));
emmaleer97002062015-05-27 12:36:10 -0700398 }
399 const int subsetWidth = w/divisor;
400 const int subsetHeight = h/divisor;
401 // One of our subsets will be larger to contain any pixels that do not divide evenly.
402 const int extraX = w % divisor;
403 const int extraY = h % divisor;
404 /*
405 * if w or h are not evenly divided by divisor need to adjust width and height of end
406 * subsets to cover entire image.
407 * Add extraX and extraY to largestSubsetBm's width and height to adjust width
408 * and height of end subsets.
409 * subsetBm is extracted from largestSubsetBm.
410 * subsetBm's size is determined based on the current subset and may be larger for end
411 * subsets.
412 */
msarett0a242972015-06-11 14:27:27 -0700413 SkImageInfo largestSubsetDecodeInfo =
emmaleer97002062015-05-27 12:36:10 -0700414 decodeInfo.makeWH(subsetWidth + extraX, subsetHeight + extraY);
415 SkBitmap largestSubsetBm;
msarett9e707a02015-09-01 14:57:57 -0700416 if (!largestSubsetBm.tryAllocPixels(largestSubsetDecodeInfo, nullptr,
417 colorTable.get())) {
emmaleer97002062015-05-27 12:36:10 -0700418 return SkStringPrintf("Image(%s) is too large (%d x %d)\n", fPath.c_str(),
419 largestSubsetDecodeInfo.width(), largestSubsetDecodeInfo.height());
420 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700421 const size_t rowBytes = decodeInfo.minRowBytes();
halcanary385fe4d2015-08-26 13:07:48 -0700422 char* buffer = new char[largestSubsetDecodeInfo.height() * rowBytes];
emmaleer0a4c3cb2015-06-22 10:40:21 -0700423 SkAutoTDeleteArray<char> lineDeleter(buffer);
emmaleer97002062015-05-27 12:36:10 -0700424 for (int col = 0; col < divisor; col++) {
425 //currentSubsetWidth may be larger than subsetWidth for rightmost subsets
426 const int currentSubsetWidth = (col + 1 == divisor) ?
427 subsetWidth + extraX : subsetWidth;
428 const int x = col * subsetWidth;
429 for (int row = 0; row < divisor; row++) {
430 //currentSubsetHeight may be larger than subsetHeight for bottom subsets
431 const int currentSubsetHeight = (row + 1 == divisor) ?
432 subsetHeight + extraY : subsetHeight;
433 const int y = row * subsetHeight;
434 //create scanline decoder for each subset
msarett9e707a02015-09-01 14:57:57 -0700435 SkAutoTDelete<SkScanlineDecoder> decoder(start_scanline_decoder(encoded.get(),
436 decodeInfo, colorPtr, colorCountPtr));
437 // TODO (msarett): Support this mode for all scanline orderings.
438 if (nullptr == decoder || SkScanlineDecoder::kTopDown_SkScanlineOrder !=
439 decoder->getScanlineOrder()) {
emmaleer97002062015-05-27 12:36:10 -0700440 if (x == 0 && y == 0) {
441 //first try, image may not be compatible
msarett5406d6f2015-08-31 06:55:13 -0700442 return Error::Nonfatal("Could not start top-down scanline decoder");
emmaleer97002062015-05-27 12:36:10 -0700443 } else {
halcanary96fcdcc2015-08-27 07:41:13 -0700444 return "Error scanline decoder is nullptr";
emmaleer97002062015-05-27 12:36:10 -0700445 }
446 }
447 //skip to first line of subset
msarett9e707a02015-09-01 14:57:57 -0700448 const SkCodec::Result skipResult = decoder->skipScanlines(y);
emmaleer97002062015-05-27 12:36:10 -0700449 switch (skipResult) {
scroggoeb602a52015-07-09 08:16:03 -0700450 case SkCodec::kSuccess:
451 case SkCodec::kIncompleteInput:
emmaleer97002062015-05-27 12:36:10 -0700452 break;
453 default:
454 return SkStringPrintf("%s failed after attempting to skip %d scanlines"
455 "with error message %d", fPath.c_str(), y, (int) skipResult);
456 }
457 //create and set size of subsetBm
458 SkBitmap subsetBm;
459 SkIRect bounds = SkIRect::MakeWH(subsetWidth, subsetHeight);
460 bounds.setXYWH(0, 0, currentSubsetWidth, currentSubsetHeight);
461 SkAssertResult(largestSubsetBm.extractSubset(&subsetBm, bounds));
462 SkAutoLockPixels autlockSubsetBm(subsetBm, true);
scroggoeb602a52015-07-09 08:16:03 -0700463 const SkCodec::Result subsetResult =
msarett9e707a02015-09-01 14:57:57 -0700464 decoder->getScanlines(buffer, currentSubsetHeight, rowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700465 switch (subsetResult) {
scroggoeb602a52015-07-09 08:16:03 -0700466 case SkCodec::kSuccess:
467 case SkCodec::kIncompleteInput:
emmaleer0a4c3cb2015-06-22 10:40:21 -0700468 break;
469 default:
mtkleind2baa902015-07-07 09:43:28 -0700470 return SkStringPrintf("%s failed with error message %d",
emmaleer0a4c3cb2015-06-22 10:40:21 -0700471 fPath.c_str(), (int) subsetResult);
emmaleer97002062015-05-27 12:36:10 -0700472 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700473 const size_t bpp = decodeInfo.bytesPerPixel();
mtkleind2baa902015-07-07 09:43:28 -0700474 /*
475 * we copy all the lines at once becuase when calling getScanlines for
476 * interlaced pngs the entire image must be read regardless of the number
emmaleer0a4c3cb2015-06-22 10:40:21 -0700477 * of lines requested. Reading an interlaced png in a loop, line-by-line, would
478 * decode the entire image height times, which is very slow
479 * it is aknowledged that copying each line as you read it in a loop
480 * may be faster for other types of images. Since this is a correctness test
481 * that's okay.
482 */
mtkleind2baa902015-07-07 09:43:28 -0700483 char* bufferRow = buffer;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700484 for (int subsetY = 0; subsetY < currentSubsetHeight; ++subsetY) {
mtkleind2baa902015-07-07 09:43:28 -0700485 memcpy(subsetBm.getAddr(0, subsetY), bufferRow + x*bpp,
emmaleer0a4c3cb2015-06-22 10:40:21 -0700486 currentSubsetWidth*bpp);
487 bufferRow += rowBytes;
488 }
mtkleind2baa902015-07-07 09:43:28 -0700489
scroggo4358f132015-07-30 11:33:04 -0700490 subsetBm.notifyPixelsChanged();
emmaleer97002062015-05-27 12:36:10 -0700491 canvas->drawBitmap(subsetBm, SkIntToScalar(x), SkIntToScalar(y));
492 }
493 }
scroggo9c59ebc2015-03-25 13:48:49 -0700494 break;
495 }
msarett0a242972015-06-11 14:27:27 -0700496 case kStripe_Mode: {
497 const int height = decodeInfo.height();
498 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
499 // does not align with image blocks.
500 const int stripeHeight = 37;
501 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
502
503 // Decode odd stripes
msarett5406d6f2015-08-31 06:55:13 -0700504 SkAutoTDelete<SkScanlineDecoder> decoder(
505 start_scanline_decoder(encoded.get(), decodeInfo, colorPtr, colorCountPtr));
msarett9e707a02015-09-01 14:57:57 -0700506 if (nullptr == decoder ||
507 SkScanlineDecoder::kTopDown_SkScanlineOrder != decoder->getScanlineOrder()) {
508 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
509 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
510 // to run this test for image types that do not have this scanline ordering.
msarett5406d6f2015-08-31 06:55:13 -0700511 return Error::Nonfatal("Could not start top-down scanline decoder");
msarett0a242972015-06-11 14:27:27 -0700512 }
513 for (int i = 0; i < numStripes; i += 2) {
514 // Skip a stripe
515 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
scroggoeb602a52015-07-09 08:16:03 -0700516 SkCodec::Result result = decoder->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700517 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700518 case SkCodec::kSuccess:
519 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700520 break;
521 default:
522 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
523 }
524
525 // Read a stripe
526 const int startY = (i + 1) * stripeHeight;
527 const int linesToRead = SkTMin(stripeHeight, height - startY);
528 if (linesToRead > 0) {
529 result = decoder->getScanlines(bitmap.getAddr(0, startY),
530 linesToRead, bitmap.rowBytes());
531 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700532 case SkCodec::kSuccess:
533 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700534 break;
535 default:
536 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
537 }
538 }
539 }
540
541 // Decode even stripes
halcanary96fcdcc2015-08-27 07:41:13 -0700542 const SkCodec::Result startResult = decoder->start(decodeInfo, nullptr, colorPtr,
scroggo1c005e42015-08-04 09:24:45 -0700543 colorCountPtr);
544 if (SkCodec::kSuccess != startResult) {
545 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700546 }
547 for (int i = 0; i < numStripes; i += 2) {
548 // Read a stripe
549 const int startY = i * stripeHeight;
550 const int linesToRead = SkTMin(stripeHeight, height - startY);
scroggoeb602a52015-07-09 08:16:03 -0700551 SkCodec::Result result = decoder->getScanlines(bitmap.getAddr(0, startY),
msarett0a242972015-06-11 14:27:27 -0700552 linesToRead, bitmap.rowBytes());
553 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700554 case SkCodec::kSuccess:
555 case SkCodec::kIncompleteInput:
msarett0a242972015-06-11 14:27:27 -0700556 break;
557 default:
558 return SkStringPrintf("Cannot get scanlines for %s.", fPath.c_str());
559 }
560
561 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700562 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
563 if (linesToSkip > 0) {
564 result = decoder->skipScanlines(linesToSkip);
565 switch (result) {
scroggoeb602a52015-07-09 08:16:03 -0700566 case SkCodec::kSuccess:
567 case SkCodec::kIncompleteInput:
msarettf6db27e2015-06-12 09:34:04 -0700568 break;
569 default:
570 return SkStringPrintf("Cannot skip scanlines for %s.", fPath.c_str());
571 }
msarett0a242972015-06-11 14:27:27 -0700572 }
573 }
574 canvas->drawBitmap(bitmap, 0, 0);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700575 break;
msarett0a242972015-06-11 14:27:27 -0700576 }
scroggob636b452015-07-22 07:16:20 -0700577 case kSubset_Mode: {
578 // Arbitrarily choose a divisor.
579 int divisor = 2;
580 // Total width/height of the image.
581 const int W = codec->getInfo().width();
582 const int H = codec->getInfo().height();
583 if (divisor > W || divisor > H) {
584 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
585 "for %s with dimensions (%d x %d)", divisor,
586 fPath.c_str(), W, H));
587 }
588 // subset dimensions
589 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
590 const int w = SkAlign2(W / divisor);
591 const int h = SkAlign2(H / divisor);
592 SkIRect subset;
593 SkCodec::Options opts;
594 opts.fSubset = &subset;
595 SkBitmap subsetBm;
596 // We will reuse pixel memory from bitmap.
597 void* pixels = bitmap.getPixels();
598 // Keep track of left and top (for drawing subsetBm into canvas). We could use
599 // fScale * x and fScale * y, but we want integers such that the next subset will start
600 // where the last one ended. So we'll add decodeInfo.width() and height().
601 int left = 0;
602 for (int x = 0; x < W; x += w) {
603 int top = 0;
604 for (int y = 0; y < H; y+= h) {
605 // Do not make the subset go off the edge of the image.
606 const int preScaleW = SkTMin(w, W - x);
607 const int preScaleH = SkTMin(h, H - y);
608 subset.setXYWH(x, y, preScaleW, preScaleH);
609 // And scale
610 // FIXME: Should we have a version of getScaledDimensions that takes a subset
611 // into account?
612 decodeInfo = decodeInfo.makeWH(SkScalarRoundToInt(preScaleW * fScale),
613 SkScalarRoundToInt(preScaleH * fScale));
614 size_t rowBytes = decodeInfo.minRowBytes();
615 if (!subsetBm.installPixels(decodeInfo, pixels, rowBytes, colorTable.get(),
halcanary96fcdcc2015-08-27 07:41:13 -0700616 nullptr, nullptr)) {
scroggob636b452015-07-22 07:16:20 -0700617 return SkStringPrintf("could not install pixels for %s.", fPath.c_str());
618 }
619 const SkCodec::Result result = codec->getPixels(decodeInfo, pixels, rowBytes,
620 &opts, colorPtr, colorCountPtr);
621 switch (result) {
622 case SkCodec::kSuccess:
623 case SkCodec::kIncompleteInput:
624 break;
625 case SkCodec::kInvalidConversion:
626 if (0 == (x|y)) {
627 // First subset is okay to return unimplemented.
628 return Error::Nonfatal("Incompatible colortype conversion");
629 }
630 // If the first subset succeeded, a later one should not fail.
631 // fall through to failure
632 case SkCodec::kUnimplemented:
633 if (0 == (x|y)) {
634 // First subset is okay to return unimplemented.
635 return Error::Nonfatal("subset codec not supported");
636 }
637 // If the first subset succeeded, why would a later one fail?
638 // fall through to failure
639 default:
640 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
641 "from %s with dimensions (%d x %d)\t error %d",
642 x, y, decodeInfo.width(), decodeInfo.height(),
643 fPath.c_str(), W, H, result);
644 }
645 canvas->drawBitmap(subsetBm, SkIntToScalar(left), SkIntToScalar(top));
646 // translate by the scaled height.
647 top += decodeInfo.height();
648 }
649 // translate by the scaled width.
650 left += decodeInfo.width();
651 }
652 return "";
653 }
scroggo9b77ddd2015-03-19 06:03:39 -0700654 }
scroggo9c59ebc2015-03-25 13:48:49 -0700655 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700656}
657
658SkISize CodecSrc::size() const {
659 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
emmaleer8f4ba762015-08-14 07:44:46 -0700660 SkAutoTDelete<SkCodec> codec(SkScaledCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700661 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700662 // scaledCodec not supported, try regular codec
663 codec.reset(SkCodec::NewFromData(encoded));
halcanary96fcdcc2015-08-27 07:41:13 -0700664 if (nullptr == codec) {
emmaleer8f4ba762015-08-14 07:44:46 -0700665 return SkISize::Make(0, 0);
666 }
msarett9bde9182015-03-25 05:27:48 -0700667 }
emmaleer8f4ba762015-08-14 07:44:46 -0700668 SkISize size = codec->getScaledDimensions(fScale);
669 return size;
scroggo9b77ddd2015-03-19 06:03:39 -0700670}
671
672Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700673 if (1.0f == fScale) {
674 return SkOSPath::Basename(fPath.c_str());
msarett0a242972015-06-11 14:27:27 -0700675 }
msaretta5783ae2015-09-08 15:35:32 -0700676 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700677}
678
679/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
680
681ImageSrc::ImageSrc(Path path, int divisor) : fPath(path), fDivisor(divisor) {}
682
mtklein99cab4e2015-07-31 06:43:04 -0700683bool ImageSrc::veto(SinkFlags flags) const {
684 // No need to test decoding to non-raster or indirect backend.
mtkleine0effd62015-07-29 06:37:28 -0700685 // TODO: Instead, use lazy decoding to allow the GPU to handle cases like YUV.
mtklein99cab4e2015-07-31 06:43:04 -0700686 return flags.type != SinkFlags::kRaster
687 || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700688}
scroggo9b77ddd2015-03-19 06:03:39 -0700689
mtkleine0effd62015-07-29 06:37:28 -0700690Error ImageSrc::draw(SkCanvas* canvas) const {
scroggo9b77ddd2015-03-19 06:03:39 -0700691 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
692 if (!encoded) {
693 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
694 }
mtkleine0effd62015-07-29 06:37:28 -0700695 const SkColorType dstColorType = canvas->imageInfo().colorType();
mtkleinedc93bc2015-01-30 13:22:23 -0800696 if (fDivisor == 0) {
mtklein748ca3b2015-01-15 10:56:12 -0800697 // Decode the full image.
698 SkBitmap bitmap;
scroggo9b77ddd2015-03-19 06:03:39 -0700699 if (!SkImageDecoder::DecodeMemory(encoded->data(), encoded->size(), &bitmap,
700 dstColorType, SkImageDecoder::kDecodePixels_Mode)) {
701 return SkStringPrintf("Couldn't decode %s.", fPath.c_str());
702 }
703 if (kRGB_565_SkColorType == dstColorType && !bitmap.isOpaque()) {
704 // Do not draw a bitmap with alpha to a destination without alpha.
705 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
mtklein748ca3b2015-01-15 10:56:12 -0800706 }
halcanary96fcdcc2015-08-27 07:41:13 -0700707 encoded.reset((SkData*)nullptr); // Might as well drop this when we're done with it.
mtklein748ca3b2015-01-15 10:56:12 -0800708 canvas->drawBitmap(bitmap, 0,0);
709 return "";
710 }
mtkleinedc93bc2015-01-30 13:22:23 -0800711 // Decode subsets. This is a little involved.
scroggoa1193e42015-01-21 12:09:53 -0800712 SkAutoTDelete<SkMemoryStream> stream(new SkMemoryStream(encoded));
713 SkAutoTDelete<SkImageDecoder> decoder(SkImageDecoder::Factory(stream.get()));
mtklein748ca3b2015-01-15 10:56:12 -0800714 if (!decoder) {
715 return SkStringPrintf("Can't find a good decoder for %s.", fPath.c_str());
716 }
scroggoa1193e42015-01-21 12:09:53 -0800717 stream->rewind();
mtklein748ca3b2015-01-15 10:56:12 -0800718 int w,h;
msarett70542572015-06-19 07:44:05 -0700719 if (!decoder->buildTileIndex(stream.detach(), &w, &h)) {
mtklein4089ef72015-03-05 08:40:28 -0800720 return Error::Nonfatal("Subset decoding not supported.");
mtklein748ca3b2015-01-15 10:56:12 -0800721 }
mtkleinedc93bc2015-01-30 13:22:23 -0800722
723 // Divide the image into subsets that cover the entire image.
724 if (fDivisor > w || fDivisor > h) {
msarett70542572015-06-19 07:44:05 -0700725 return Error::Nonfatal(SkStringPrintf("Cannot decode subset: divisor %d is too big"
726 "for %s with dimensions (%d x %d)", fDivisor, fPath.c_str(), w, h));
mtkleinedc93bc2015-01-30 13:22:23 -0800727 }
728 const int subsetWidth = w / fDivisor,
729 subsetHeight = h / fDivisor;
730 for (int y = 0; y < h; y += subsetHeight) {
731 for (int x = 0; x < w; x += subsetWidth) {
732 SkBitmap subset;
733 SkIRect rect = SkIRect::MakeXYWH(x, y, subsetWidth, subsetHeight);
734 if (!decoder->decodeSubset(&subset, rect, dstColorType)) {
735 return SkStringPrintf("Could not decode subset (%d, %d, %d, %d).",
736 x, y, x+subsetWidth, y+subsetHeight);
737 }
scroggo56e25dd2015-03-05 11:46:40 -0800738 if (kRGB_565_SkColorType == dstColorType && !subset.isOpaque()) {
739 // Do not draw a bitmap with alpha to a destination without alpha.
740 // This is not an error, but there is nothing interesting to show.
741
742 // This should only happen on the first iteration through the loop.
743 SkASSERT(0 == x && 0 == y);
744
745 return Error::Nonfatal("Uninteresting to decode image with alpha into 565.");
746 }
mtkleinedc93bc2015-01-30 13:22:23 -0800747 canvas->drawBitmap(subset, SkIntToScalar(x), SkIntToScalar(y));
mtklein748ca3b2015-01-15 10:56:12 -0800748 }
mtklein748ca3b2015-01-15 10:56:12 -0800749 }
750 return "";
751}
752
753SkISize ImageSrc::size() const {
mtklein75d98fd2015-01-18 07:05:01 -0800754 SkAutoTUnref<SkData> encoded(SkData::NewFromFileName(fPath.c_str()));
scroggo9b77ddd2015-03-19 06:03:39 -0700755 SkBitmap bitmap;
756 if (!encoded || !SkImageDecoder::DecodeMemory(encoded->data(),
757 encoded->size(),
758 &bitmap,
759 kUnknown_SkColorType,
760 SkImageDecoder::kDecodeBounds_Mode)) {
761 return SkISize::Make(0,0);
mtklein748ca3b2015-01-15 10:56:12 -0800762 }
scroggo9b77ddd2015-03-19 06:03:39 -0700763 return bitmap.dimensions();
mtklein748ca3b2015-01-15 10:56:12 -0800764}
765
mtklein9264a952015-01-20 10:11:53 -0800766Name ImageSrc::name() const {
mtkleinedc93bc2015-01-30 13:22:23 -0800767 return SkOSPath::Basename(fPath.c_str());
mtklein9264a952015-01-20 10:11:53 -0800768}
mtklein748ca3b2015-01-15 10:56:12 -0800769
770/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
771
mtkleinf4ba3212015-01-28 15:32:24 -0800772static const SkRect kSKPViewport = {0,0, 1000,1000};
773
mtklein8d17a132015-01-30 11:42:31 -0800774SKPSrc::SKPSrc(Path path) : fPath(path) {}
mtklein748ca3b2015-01-15 10:56:12 -0800775
776Error SKPSrc::draw(SkCanvas* canvas) const {
scroggoa1193e42015-01-21 12:09:53 -0800777 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
mtklein75d98fd2015-01-18 07:05:01 -0800778 if (!stream) {
mtklein748ca3b2015-01-15 10:56:12 -0800779 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
780 }
mtkleinb3e5e4d2015-03-25 13:13:43 -0700781 SkAutoTUnref<SkPicture> pic(SkPicture::CreateFromStream(stream, &lazy_decode_bitmap));
mtklein75d98fd2015-01-18 07:05:01 -0800782 if (!pic) {
783 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
784 }
halcanary96fcdcc2015-08-27 07:41:13 -0700785 stream.reset((SkStream*)nullptr); // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -0700786
mtkleinf4ba3212015-01-28 15:32:24 -0800787 canvas->clipRect(kSKPViewport);
mtklein748ca3b2015-01-15 10:56:12 -0800788 canvas->drawPicture(pic);
789 return "";
790}
791
792SkISize SKPSrc::size() const {
mtkleinffa901a2015-03-16 10:38:07 -0700793 SkAutoTDelete<SkStream> stream(SkStream::NewFromFile(fPath.c_str()));
794 if (!stream) {
795 return SkISize::Make(0,0);
796 }
797 SkPictInfo info;
798 if (!SkPicture::InternalOnly_StreamIsSKP(stream, &info)) {
799 return SkISize::Make(0,0);
800 }
801 SkRect viewport = kSKPViewport;
802 if (!viewport.intersect(info.fCullRect)) {
803 return SkISize::Make(0,0);
804 }
805 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -0800806}
807
808Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
809
810/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
811
mtkleinad66f9b2015-02-13 15:11:10 -0800812Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
813 SkAutoTDelete<SkCanvas> canvas(SkCreateNullCanvas());
814 return src.draw(canvas);
815}
816
817/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
818
mtkleinb9eb4ac2015-02-02 18:26:03 -0800819DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
820
mtklein82d28432015-01-15 12:46:02 -0800821GPUSink::GPUSink(GrContextFactory::GLContextType ct,
822 GrGLStandard api,
823 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -0700824 bool diText,
mtklein82d28432015-01-15 12:46:02 -0800825 bool threaded)
mtklein748ca3b2015-01-15 10:56:12 -0800826 : fContextType(ct)
827 , fGpuAPI(api)
828 , fSampleCount(samples)
bsalomonafcd7cd2015-08-31 12:39:41 -0700829 , fUseDIText(diText)
mtklein82d28432015-01-15 12:46:02 -0800830 , fThreaded(threaded) {}
mtklein748ca3b2015-01-15 10:56:12 -0800831
832int GPUSink::enclave() const {
mtklein55e88b22015-01-21 15:50:13 -0800833 return fThreaded ? kAnyThread_Enclave : kGPU_Enclave;
mtklein748ca3b2015-01-15 10:56:12 -0800834}
835
joshualitt5f5a8d72015-02-25 14:09:45 -0800836void PreAbandonGpuContextErrorHandler(SkError, void*) {}
837
mtkleinb9eb4ac2015-02-02 18:26:03 -0800838Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
bsalomon4ee6bd82015-05-27 13:23:23 -0700839 GrContextOptions options;
840 src.modifyGrContextOptions(&options);
841
842 GrContextFactory factory(options);
mtkleinf4ba3212015-01-28 15:32:24 -0800843 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800844 const SkImageInfo info =
845 SkImageInfo::Make(size.width(), size.height(), kN32_SkColorType, kPremul_SkAlphaType);
846 SkAutoTUnref<SkSurface> surface(
bsalomonafcd7cd2015-08-31 12:39:41 -0700847 NewGpuSurface(&factory, fContextType, fGpuAPI, info, fSampleCount, fUseDIText));
mtklein748ca3b2015-01-15 10:56:12 -0800848 if (!surface) {
849 return "Could not create a surface.";
850 }
joshualitt5f5a8d72015-02-25 14:09:45 -0800851 if (FLAGS_preAbandonGpuContext) {
halcanary96fcdcc2015-08-27 07:41:13 -0700852 SkSetErrorCallback(&PreAbandonGpuContextErrorHandler, nullptr);
joshualitt5f5a8d72015-02-25 14:09:45 -0800853 factory.abandonContexts();
854 }
mtklein748ca3b2015-01-15 10:56:12 -0800855 SkCanvas* canvas = surface->getCanvas();
856 Error err = src.draw(canvas);
857 if (!err.isEmpty()) {
858 return err;
859 }
860 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -0800861 if (FLAGS_gpuStats) {
862 canvas->getGrContext()->dumpCacheStats(log);
863 canvas->getGrContext()->dumpGpuStats(log);
864 }
mtklein748ca3b2015-01-15 10:56:12 -0800865 dst->allocPixels(info);
joshualitt5f5a8d72015-02-25 14:09:45 -0800866 canvas->readPixels(dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -0800867 if (FLAGS_abandonGpuContext) {
868 factory.abandonContexts();
869 }
mtklein748ca3b2015-01-15 10:56:12 -0800870 return "";
871}
872
873/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
874
halcanary47ef4d52015-03-03 09:13:09 -0800875static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
876 // Print the given DM:Src to a document, breaking on 8.5x11 pages.
877 SkASSERT(doc);
halcanaryfd4a9932015-01-28 11:45:58 -0800878 int width = src.size().width(),
879 height = src.size().height();
880
halcanary7e798182015-04-14 14:06:18 -0700881 if (FLAGS_multiPage) {
882 const int kLetterWidth = 612, // 8.5 * 72
883 kLetterHeight = 792; // 11 * 72
884 const SkRect letter = SkRect::MakeWH(SkIntToScalar(kLetterWidth),
885 SkIntToScalar(kLetterHeight));
halcanaryfd4a9932015-01-28 11:45:58 -0800886
halcanary7e798182015-04-14 14:06:18 -0700887 int xPages = ((width - 1) / kLetterWidth) + 1;
888 int yPages = ((height - 1) / kLetterHeight) + 1;
halcanaryfd4a9932015-01-28 11:45:58 -0800889
halcanary7e798182015-04-14 14:06:18 -0700890 for (int y = 0; y < yPages; ++y) {
891 for (int x = 0; x < xPages; ++x) {
892 int w = SkTMin(kLetterWidth, width - (x * kLetterWidth));
893 int h = SkTMin(kLetterHeight, height - (y * kLetterHeight));
894 SkCanvas* canvas =
895 doc->beginPage(SkIntToScalar(w), SkIntToScalar(h));
896 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700897 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700898 }
899 canvas->clipRect(letter);
900 canvas->translate(-letter.width() * x, -letter.height() * y);
901 Error err = src.draw(canvas);
902 if (!err.isEmpty()) {
903 return err;
904 }
905 doc->endPage();
djsollen2ab90002015-04-03 06:38:31 -0700906 }
halcanaryfd4a9932015-01-28 11:45:58 -0800907 }
halcanary7e798182015-04-14 14:06:18 -0700908 } else {
909 SkCanvas* canvas =
910 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
911 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -0700912 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -0700913 }
914 Error err = src.draw(canvas);
915 if (!err.isEmpty()) {
916 return err;
917 }
918 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -0800919 }
halcanary7e798182015-04-14 14:06:18 -0700920 if (!doc->close()) {
921 return "SkDocument::close() returned false";
922 }
halcanaryfd4a9932015-01-28 11:45:58 -0800923 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -0800924 return "";
925}
926
halcanary47ef4d52015-03-03 09:13:09 -0800927PDFSink::PDFSink() {}
928
929Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
930 SkAutoTUnref<SkDocument> doc(SkDocument::CreatePDF(dst));
931 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700932 return "SkDocument::CreatePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800933 }
halcanaryf12a1672015-09-23 12:45:49 -0700934 SkTArray<SkDocument::Attribute> info;
935 info.emplace_back(SkString("Title"), src.name());
936 info.emplace_back(SkString("Subject"),
937 SkString("rendering correctness test"));
938 info.emplace_back(SkString("Creator"), SkString("Skia/DM"));
939 doc->setMetadata(info, nullptr, nullptr);
halcanary47ef4d52015-03-03 09:13:09 -0800940 return draw_skdocument(src, doc.get(), dst);
941}
942
943/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
944
945XPSSink::XPSSink() {}
946
947Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
948 SkAutoTUnref<SkDocument> doc(SkDocument::CreateXPS(dst));
949 if (!doc) {
halcanary96fcdcc2015-08-27 07:41:13 -0700950 return "SkDocument::CreateXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -0800951 }
952 return draw_skdocument(src, doc.get(), dst);
953}
mtklein748ca3b2015-01-15 10:56:12 -0800954/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
955
mtklein9c3f17d2015-01-28 11:35:18 -0800956SKPSink::SKPSink() {}
957
mtkleinb9eb4ac2015-02-02 18:26:03 -0800958Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -0800959 SkSize size;
960 size = src.size();
961 SkPictureRecorder recorder;
962 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
963 if (!err.isEmpty()) {
964 return err;
965 }
966 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
967 pic->serialize(dst);
968 return "";
969}
970
971/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
972
mtklein8a4527e2015-01-31 20:00:58 -0800973SVGSink::SVGSink() {}
974
mtkleinb9eb4ac2015-02-02 18:26:03 -0800975Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary385fe4d2015-08-26 13:07:48 -0700976 SkAutoTDelete<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
fmalita2aafe6f2015-02-06 12:51:10 -0800977 SkAutoTUnref<SkCanvas> canvas(SkSVGCanvas::Create(
978 SkRect::MakeWH(SkIntToScalar(src.size().width()), SkIntToScalar(src.size().height())),
979 xmlWriter));
980 return src.draw(canvas);
mtklein8a4527e2015-01-31 20:00:58 -0800981}
982
983/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
984
mtklein748ca3b2015-01-15 10:56:12 -0800985RasterSink::RasterSink(SkColorType colorType) : fColorType(colorType) {}
986
mtkleinb9eb4ac2015-02-02 18:26:03 -0800987Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
mtkleinf4ba3212015-01-28 15:32:24 -0800988 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -0800989 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
990 SkAlphaType alphaType = kPremul_SkAlphaType;
991 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
992
993 dst->allocPixels(SkImageInfo::Make(size.width(), size.height(), fColorType, alphaType));
994 dst->eraseColor(SK_ColorTRANSPARENT);
995 SkCanvas canvas(*dst);
996 return src.draw(&canvas);
997}
998
999/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1000
mtkleina16e69e2015-05-05 11:38:45 -07001001// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001002// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001003// Several examples below.
1004
mtkleina16e69e2015-05-05 11:38:45 -07001005static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleine44b5082015-05-07 10:53:34 -07001006 SkISize size, SkFunction<Error(SkCanvas*)> draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001007 class ProxySrc : public Src {
1008 public:
mtkleine44b5082015-05-07 10:53:34 -07001009 ProxySrc(SkISize size, SkFunction<Error(SkCanvas*)> draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001010 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
1011 Name name() const override { sk_throw(); return ""; } // Won't be called.
1012 SkISize size() const override { return fSize; }
1013 private:
mtkleine44b5082015-05-07 10:53:34 -07001014 SkISize fSize;
1015 SkFunction<Error(SkCanvas*)> fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001016 };
1017 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
1018}
1019
1020/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1021
mtkleind603b222015-02-17 11:13:33 -08001022static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1023 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1024 matrix->mapRect(&bounds);
1025 matrix->postTranslate(-bounds.x(), -bounds.y());
1026 return SkISize::Make(SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height()));
1027}
1028
mtklein78829242015-05-06 07:54:07 -07001029ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001030
mtkleinb9eb4ac2015-02-02 18:26:03 -08001031Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001032 SkMatrix matrix = fMatrix;
1033 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
1034 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1035 canvas->concat(matrix);
1036 return src.draw(canvas);
1037 });
mtklein748ca3b2015-01-15 10:56:12 -08001038}
1039
mtkleind603b222015-02-17 11:13:33 -08001040// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1041// This should be pixel-preserving.
mtklein78829242015-05-06 07:54:07 -07001042ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001043
1044Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1045 Error err = fSink->draw(src, bitmap, stream, log);
1046 if (!err.isEmpty()) {
1047 return err;
1048 }
1049
1050 SkMatrix inverse;
1051 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1052 return "Cannot upright --matrix.";
1053 }
1054 SkMatrix upright = SkMatrix::I();
1055 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1056 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1057 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1058 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1059
1060 SkBitmap uprighted;
1061 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1062 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1063
1064 SkCanvas canvas(uprighted);
1065 canvas.concat(upright);
1066 SkPaint paint;
1067 paint.setXfermodeMode(SkXfermode::kSrc_Mode);
1068 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1069
1070 *bitmap = uprighted;
1071 bitmap->lockPixels();
1072 return "";
1073}
1074
mtklein748ca3b2015-01-15 10:56:12 -08001075/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1076
mtkleinb9eb4ac2015-02-02 18:26:03 -08001077Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001078 auto size = src.size();
1079 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1080 PipeController controller(canvas, &SkImageDecoder::DecodeMemory);
1081 SkGPipeWriter pipe;
reed451af502015-08-19 08:18:04 -07001082 const uint32_t kFlags = 0;
mtkleina16e69e2015-05-05 11:38:45 -07001083 return src.draw(pipe.startRecording(&controller, kFlags, size.width(), size.height()));
1084 });
mtklein748ca3b2015-01-15 10:56:12 -08001085}
1086
1087/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtkleina16e69e2015-05-05 11:38:45 -07001088
mtkleina16e69e2015-05-05 11:38:45 -07001089Error ViaSerialization::draw(
1090 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001091 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001092 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001093 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001094 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1095 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001096 if (!err.isEmpty()) {
1097 return err;
1098 }
1099 SkAutoTUnref<SkPicture> pic(recorder.endRecording());
1100
1101 // Serialize it and then deserialize it.
1102 SkDynamicMemoryWStream wStream;
1103 pic->serialize(&wStream);
scroggoa1193e42015-01-21 12:09:53 -08001104 SkAutoTDelete<SkStream> rStream(wStream.detachAsStream());
mtkleinb3e5e4d2015-03-25 13:13:43 -07001105 SkAutoTUnref<SkPicture> deserialized(SkPicture::CreateFromStream(rStream, &lazy_decode_bitmap));
mtklein748ca3b2015-01-15 10:56:12 -08001106
mtkleina16e69e2015-05-05 11:38:45 -07001107 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) {
1108 canvas->drawPicture(deserialized);
1109 return "";
1110 });
mtklein748ca3b2015-01-15 10:56:12 -08001111}
1112
1113/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1114
1115ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
mtklein78829242015-05-06 07:54:07 -07001116 : Via(sink)
1117 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001118 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001119 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001120
mtkleinb9eb4ac2015-02-02 18:26:03 -08001121Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001122 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001123 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001124 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1125 SkIntToScalar(size.height()),
1126 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001127 if (!err.isEmpty()) {
1128 return err;
1129 }
mtkleinb7e8d692015-04-07 08:30:32 -07001130 SkAutoTUnref<SkPicture> pic(recorder.endRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001131
mtkleina16e69e2015-05-05 11:38:45 -07001132 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
1133 const int xTiles = (size.width() + fW - 1) / fW,
1134 yTiles = (size.height() + fH - 1) / fH;
1135 SkMultiPictureDraw mpd(xTiles*yTiles);
1136 SkTDArray<SkSurface*> surfaces;
1137 surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001138
mtkleina16e69e2015-05-05 11:38:45 -07001139 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1140 for (int j = 0; j < yTiles; j++) {
1141 for (int i = 0; i < xTiles; i++) {
1142 // This lets our ultimate Sink determine the best kind of surface.
1143 // E.g., if it's a GpuSink, the surfaces and images are textures.
1144 SkSurface* s = canvas->newSurface(info);
1145 if (!s) {
1146 s = SkSurface::NewRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001147 }
mtkleina16e69e2015-05-05 11:38:45 -07001148 surfaces.push(s);
1149 SkCanvas* c = s->getCanvas();
1150 c->translate(SkIntToScalar(-i * fW),
1151 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1152 mpd.add(c, pic);
mtklein748ca3b2015-01-15 10:56:12 -08001153 }
mtklein748ca3b2015-01-15 10:56:12 -08001154 }
mtkleina16e69e2015-05-05 11:38:45 -07001155 mpd.draw();
1156 for (int j = 0; j < yTiles; j++) {
1157 for (int i = 0; i < xTiles; i++) {
1158 SkAutoTUnref<SkImage> image(surfaces[i+xTiles*j]->newImageSnapshot());
1159 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1160 }
1161 }
1162 surfaces.unrefAll();
1163 return "";
1164 });
mtklein748ca3b2015-01-15 10:56:12 -08001165}
1166
mtkleinb7e8d692015-04-07 08:30:32 -07001167/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1168
mtkleinb7e8d692015-04-07 08:30:32 -07001169// Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1170// This tests that any shortcuts we may take while recording that second picture are legal.
1171Error ViaSecondPicture::draw(
1172 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001173 auto size = src.size();
1174 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1175 SkPictureRecorder recorder;
1176 SkAutoTUnref<SkPicture> pic;
1177 for (int i = 0; i < 2; i++) {
1178 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1179 SkIntToScalar(size.height())));
1180 if (!err.isEmpty()) {
1181 return err;
mtkleinb7e8d692015-04-07 08:30:32 -07001182 }
mtkleina16e69e2015-05-05 11:38:45 -07001183 pic.reset(recorder.endRecordingAsPicture());
mtkleinb7e8d692015-04-07 08:30:32 -07001184 }
mtkleina16e69e2015-05-05 11:38:45 -07001185 canvas->drawPicture(pic);
1186 return "";
1187 });
mtkleinb7e8d692015-04-07 08:30:32 -07001188}
1189
mtkleind31c13d2015-05-05 12:59:56 -07001190/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1191
mtklein6fbf4b32015-05-06 11:35:40 -07001192// Draw the Src twice. This can help exercise caching.
1193Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1194 return draw_to_canvas(fSink, bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1195 for (int i = 0; i < 2; i++) {
1196 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1197 canvas->clear(SK_ColorTRANSPARENT);
1198 Error err = src.draw(canvas);
1199 if (err.isEmpty()) {
1200 return err;
1201 }
1202 }
1203 return "";
1204 });
1205}
1206
1207/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1208
mtkleind31c13d2015-05-05 12:59:56 -07001209// This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1210// Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1211// This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1212struct DrawsAsSingletonPictures {
1213 SkCanvas* fCanvas;
mtkleind2baa902015-07-07 09:43:28 -07001214 const SkDrawableList& fDrawables;
mtkleind31c13d2015-05-05 12:59:56 -07001215
mtkleind31c13d2015-05-05 12:59:56 -07001216 template <typename T>
1217 void draw(const T& op, SkCanvas* canvas) {
1218 // We must pass SkMatrix::I() as our initial matrix.
1219 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1220 // which would have the funky effect of applying transforms over and over.
mtkleind2baa902015-07-07 09:43:28 -07001221 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1222 d(op);
mtkleind31c13d2015-05-05 12:59:56 -07001223 }
1224
mtklein449d9b72015-09-28 10:33:02 -07001225 // Draws get their own picture.
mtkleind31c13d2015-05-05 12:59:56 -07001226 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001227 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
mtkleind31c13d2015-05-05 12:59:56 -07001228 SkPictureRecorder rec;
1229 this->draw(op, rec.beginRecording(SkRect::MakeLargest()));
1230 SkAutoTUnref<SkPicture> pic(rec.endRecordingAsPicture());
1231 fCanvas->drawPicture(pic);
1232 }
1233
mtklein449d9b72015-09-28 10:33:02 -07001234 // We'll just issue non-draws directly.
mtkleind31c13d2015-05-05 12:59:56 -07001235 template <typename T>
mtklein449d9b72015-09-28 10:33:02 -07001236 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1237 this->draw(op, fCanvas);
1238 }
mtkleind31c13d2015-05-05 12:59:56 -07001239};
1240
mtkleind31c13d2015-05-05 12:59:56 -07001241// Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1242// Then play back that macro picture into our wrapped sink.
1243Error ViaSingletonPictures::draw(
1244 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1245 auto size = src.size();
1246 return draw_to_canvas(fSink, bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1247 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1248 SkRecord skr;
1249 SkRecorder recorder(&skr, size.width(), size.height());
1250 Error err = src.draw(&recorder);
1251 if (!err.isEmpty()) {
1252 return err;
1253 }
1254
1255 // Record our macro-picture, with each draw op as its own sub-picture.
1256 SkPictureRecorder macroRec;
1257 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1258 SkIntToScalar(size.height()));
mtkleind2baa902015-07-07 09:43:28 -07001259
1260 SkAutoTDelete<SkDrawableList> drawables(recorder.detachDrawableList());
1261 const SkDrawableList empty;
1262
1263 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1264 macroCanvas,
1265 drawables ? *drawables : empty,
1266 };
mtkleinc6ad06a2015-08-19 09:51:00 -07001267 for (int i = 0; i < skr.count(); i++) {
mtkleind31c13d2015-05-05 12:59:56 -07001268 skr.visit<void>(i, drawsAsSingletonPictures);
1269 }
1270 SkAutoTUnref<SkPicture> macroPic(macroRec.endRecordingAsPicture());
1271
1272 canvas->drawPicture(macroPic);
1273 return "";
1274 });
1275}
1276
mtklein748ca3b2015-01-15 10:56:12 -08001277} // namespace DM