1 /*
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
8 #include "DMSrcSink.h"
9 #include "Resources.h"
10 #include "SkAndroidCodec.h"
11 #include "SkAutoMalloc.h"
12 #include "SkCodec.h"
13 #include "SkCodecImageGenerator.h"
14 #include "SkColorSpace.h"
15 #include "SkColorSpaceXform.h"
16 #include "SkColorSpaceXformCanvas.h"
17 #include "SkColorSpace_XYZ.h"
18 #include "SkCommonFlags.h"
19 #include "SkData.h"
20 #include "SkDebugCanvas.h"
21 #include "SkDeferredCanvas.h"
22 #include "SkDocument.h"
23 #include "SkImageGenerator.h"
24 #include "SkImageGeneratorCG.h"
25 #include "SkImageGeneratorWIC.h"
26 #include "SkLiteDL.h"
27 #include "SkLiteRecorder.h"
28 #include "SkMallocPixelRef.h"
29 #include "SkMultiPictureDocumentPriv.h"
30 #include "SkMultiPictureDraw.h"
31 #include "SkNullCanvas.h"
32 #include "SkOSFile.h"
33 #include "SkOSPath.h"
34 #include "SkOpts.h"
35 #include "SkPictureData.h"
36 #include "SkPictureRecorder.h"
37 #include "SkPipe.h"
38 #include "SkRandom.h"
39 #include "SkRecordDraw.h"
40 #include "SkRecorder.h"
41 #include "SkSVGCanvas.h"
42 #include "SkStream.h"
43 #include "SkSwizzler.h"
44 #include "SkTLogic.h"
45 #include <cmath>
46 #include <functional>
47
48 #if defined(SK_BUILD_FOR_WIN)
49 #include "SkAutoCoInitialize.h"
50 #include "SkHRESULT.h"
51 #include "SkTScopedComPtr.h"
52 #include <XpsObjectModel.h>
53 #endif
54
55 #if defined(SK_XML)
56 #include "SkSVGDOM.h"
57 #include "SkXMLWriter.h"
58 #endif
59
60 DEFINE_bool(multiPage, false, "For document-type backends, render the source"
61 " into multiple pages");
62 DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
63
64 using sk_gpu_test::GrContextFactory;
65
66 namespace DM {
67
GMSrc(skiagm::GMRegistry::Factory factory)68 GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
69
draw(SkCanvas * canvas) const70 Error GMSrc::draw(SkCanvas* canvas) const {
71 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
72 canvas->concat(gm->getInitialTransform());
73 gm->draw(canvas);
74 return "";
75 }
76
size() const77 SkISize GMSrc::size() const {
78 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
79 return gm->getISize();
80 }
81
name() const82 Name GMSrc::name() const {
83 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
84 return gm->getName();
85 }
86
modifyGrContextOptions(GrContextOptions * options) const87 void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
88 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
89 gm->modifyGrContextOptions(options);
90 }
91
92 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
93
BRDSrc(Path path,Mode mode,CodecSrc::DstColorType dstColorType,uint32_t sampleSize)94 BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
95 : fPath(path)
96 , fMode(mode)
97 , fDstColorType(dstColorType)
98 , fSampleSize(sampleSize)
99 {}
100
veto(SinkFlags flags) const101 bool BRDSrc::veto(SinkFlags flags) const {
102 // No need to test to non-raster or indirect backends.
103 return flags.type != SinkFlags::kRaster
104 || flags.approach != SinkFlags::kDirect;
105 }
106
create_brd(Path path)107 static SkBitmapRegionDecoder* create_brd(Path path) {
108 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
109 if (!encoded) {
110 return NULL;
111 }
112 return SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy);
113 }
114
alpha8_to_gray8(SkBitmap * bitmap)115 static inline void alpha8_to_gray8(SkBitmap* bitmap) {
116 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
117 // them back to kGray8 so our test framework can draw them correctly.
118 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
119 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
120 .makeAlphaType(kOpaque_SkAlphaType);
121 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
122 }
123 }
124
draw(SkCanvas * canvas) const125 Error BRDSrc::draw(SkCanvas* canvas) const {
126 if (canvas->imageInfo().colorSpace() &&
127 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
128 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
129 // run these tests on legacy canvases.
130 // We allow an exception for F16, since Android uses F16.
131 return Error::Nonfatal("Skip testing to color correct canvas.");
132 }
133
134 SkColorType colorType = canvas->imageInfo().colorType();
135 if (kRGB_565_SkColorType == colorType &&
136 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
137 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
138 }
139 switch (fDstColorType) {
140 case CodecSrc::kGetFromCanvas_DstColorType:
141 break;
142 case CodecSrc::kGrayscale_Always_DstColorType:
143 colorType = kGray_8_SkColorType;
144 break;
145 default:
146 SkASSERT(false);
147 break;
148 }
149
150 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
151 if (nullptr == brd.get()) {
152 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
153 }
154
155 if (!brd->conversionSupported(colorType)) {
156 return Error::Nonfatal("Cannot convert to color type.");
157 }
158
159 const uint32_t width = brd->width();
160 const uint32_t height = brd->height();
161 // Visually inspecting very small output images is not necessary.
162 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
163 return Error::Nonfatal("Scaling very small images is uninteresting.");
164 }
165 switch (fMode) {
166 case kFullImage_Mode: {
167 SkBitmap bitmap;
168 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
169 fSampleSize, colorType, false, SkColorSpace::MakeSRGB())) {
170 return "Cannot decode (full) region.";
171 }
172 alpha8_to_gray8(&bitmap);
173
174 canvas->drawBitmap(bitmap, 0, 0);
175 return "";
176 }
177 case kDivisor_Mode: {
178 const uint32_t divisor = 2;
179 if (width < divisor || height < divisor) {
180 return Error::Nonfatal("Divisor is larger than image dimension.");
181 }
182
183 // Use a border to test subsets that extend outside the image.
184 // We will not allow the border to be larger than the image dimensions. Allowing
185 // these large borders causes off by one errors that indicate a problem with the
186 // test suite, not a problem with the implementation.
187 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
188 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
189 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
190
191 // We may need to clear the canvas to avoid uninitialized memory.
192 // Assume we are scaling a 780x780 image with sampleSize = 8.
193 // The output image should be 97x97.
194 // Each subset will be 390x390.
195 // Each scaled subset be 48x48.
196 // Four scaled subsets will only fill a 96x96 image.
197 // The bottom row and last column will not be touched.
198 // This is an unfortunate result of our rounding rules when scaling.
199 // Maybe we need to consider testing scaled subsets without trying to
200 // combine them to match the full scaled image? Or maybe this is the
201 // best we can do?
202 canvas->clear(0);
203
204 for (uint32_t x = 0; x < divisor; x++) {
205 for (uint32_t y = 0; y < divisor; y++) {
206 // Calculate the subset dimensions
207 uint32_t subsetWidth = width / divisor;
208 uint32_t subsetHeight = height / divisor;
209 const int left = x * subsetWidth;
210 const int top = y * subsetHeight;
211
212 // Increase the size of the last subset in each row or column, when the
213 // divisor does not divide evenly into the image dimensions
214 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
215 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
216
217 // Increase the size of the subset in order to have a border on each side
218 const int decodeLeft = left - unscaledBorder;
219 const int decodeTop = top - unscaledBorder;
220 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
221 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
222 SkBitmap bitmap;
223 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
224 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
225 SkColorSpace::MakeSRGB())) {
226 return "Cannot decode region.";
227 }
228
229 alpha8_to_gray8(&bitmap);
230 canvas->drawBitmapRect(bitmap,
231 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
232 (SkScalar) (subsetWidth / fSampleSize),
233 (SkScalar) (subsetHeight / fSampleSize)),
234 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
235 (SkScalar) (top / fSampleSize),
236 (SkScalar) (subsetWidth / fSampleSize),
237 (SkScalar) (subsetHeight / fSampleSize)),
238 nullptr);
239 }
240 }
241 return "";
242 }
243 default:
244 SkASSERT(false);
245 return "Error: Should not be reached.";
246 }
247 }
248
size() const249 SkISize BRDSrc::size() const {
250 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
251 if (brd) {
252 return {SkTMax(1, brd->width() / (int)fSampleSize),
253 SkTMax(1, brd->height() / (int)fSampleSize)};
254 }
255 return {0, 0};
256 }
257
get_scaled_name(const Path & path,float scale)258 static SkString get_scaled_name(const Path& path, float scale) {
259 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
260 }
261
name() const262 Name BRDSrc::name() const {
263 // We will replicate the names used by CodecSrc so that images can
264 // be compared in Gold.
265 if (1 == fSampleSize) {
266 return SkOSPath::Basename(fPath.c_str());
267 }
268 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
269 }
270
271 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
272
serial_from_path_name(const SkString & path)273 static bool serial_from_path_name(const SkString& path) {
274 if (!FLAGS_RAW_threading) {
275 static const char* const exts[] = {
276 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
277 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
278 };
279 const char* actualExt = strrchr(path.c_str(), '.');
280 if (actualExt) {
281 actualExt++;
282 for (auto* ext : exts) {
283 if (0 == strcmp(ext, actualExt)) {
284 return true;
285 }
286 }
287 }
288 }
289 return false;
290 }
291
CodecSrc(Path path,Mode mode,DstColorType dstColorType,SkAlphaType dstAlphaType,float scale)292 CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
293 float scale)
294 : fPath(path)
295 , fMode(mode)
296 , fDstColorType(dstColorType)
297 , fDstAlphaType(dstAlphaType)
298 , fScale(scale)
299 , fRunSerially(serial_from_path_name(path))
300 {}
301
veto(SinkFlags flags) const302 bool CodecSrc::veto(SinkFlags flags) const {
303 // Test to direct raster backends (8888 and 565).
304 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
305 }
306
307 // Allows us to test decodes to non-native 8888.
swap_rb_if_necessary(SkBitmap & bitmap,CodecSrc::DstColorType dstColorType)308 static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
309 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
310 return;
311 }
312
313 for (int y = 0; y < bitmap.height(); y++) {
314 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
315 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
316 }
317 }
318
319 // FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
320 // This allows us to still test unpremultiplied decodes.
premultiply_if_necessary(SkBitmap & bitmap)321 static void premultiply_if_necessary(SkBitmap& bitmap) {
322 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
323 return;
324 }
325
326 switch (bitmap.colorType()) {
327 case kRGBA_F16_SkColorType:
328 for (int y = 0; y < bitmap.height(); y++) {
329 void* row = bitmap.getAddr(0, y);
330 SkRasterPipeline_<256> p;
331 p.append(SkRasterPipeline::load_f16, &row);
332 p.append(SkRasterPipeline::premul);
333 p.append(SkRasterPipeline::store_f16, &row);
334 p.run(0,y, bitmap.width());
335 }
336 break;
337 case kN32_SkColorType:
338 for (int y = 0; y < bitmap.height(); y++) {
339 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
340 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
341 }
342 break;
343 default:
344 // No need to premultiply kGray or k565 outputs.
345 break;
346 }
347
348 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
349 // bitmap as kPremul.
350 bitmap.setAlphaType(kPremul_SkAlphaType);
351 }
352
get_decode_info(SkImageInfo * decodeInfo,SkColorType canvasColorType,CodecSrc::DstColorType dstColorType,SkAlphaType dstAlphaType)353 static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
354 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
355 switch (dstColorType) {
356 case CodecSrc::kGrayscale_Always_DstColorType:
357 if (kRGB_565_SkColorType == canvasColorType) {
358 return false;
359 }
360 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
361 break;
362 case CodecSrc::kNonNative8888_Always_DstColorType:
363 if (kRGB_565_SkColorType == canvasColorType
364 || kRGBA_F16_SkColorType == canvasColorType) {
365 return false;
366 }
367 #ifdef SK_PMCOLOR_IS_RGBA
368 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
369 #else
370 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
371 #endif
372 break;
373 default:
374 if (kRGB_565_SkColorType == canvasColorType &&
375 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
376 return false;
377 }
378
379 if (kRGBA_F16_SkColorType == canvasColorType) {
380 sk_sp<SkColorSpace> linearSpace =
381 as_CSB(decodeInfo->colorSpace())->makeLinearGamma();
382 *decodeInfo = decodeInfo->makeColorSpace(std::move(linearSpace));
383 }
384
385 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
386 break;
387 }
388
389 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
390 return true;
391 }
392
draw_to_canvas(SkCanvas * canvas,const SkImageInfo & info,void * pixels,size_t rowBytes,CodecSrc::DstColorType dstColorType,SkScalar left=0,SkScalar top=0)393 static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
394 CodecSrc::DstColorType dstColorType,
395 SkScalar left = 0, SkScalar top = 0) {
396 SkBitmap bitmap;
397 bitmap.installPixels(info, pixels, rowBytes);
398 premultiply_if_necessary(bitmap);
399 swap_rb_if_necessary(bitmap, dstColorType);
400 canvas->drawBitmap(bitmap, left, top);
401 }
402
403 // For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
404 // color format conversions should be performed by the codec. Sometimes the output of the
405 // decode will be in an interesting color space. On our srgb and f16 backends, we need to
406 // "pretend" that the color space is standard sRGB to avoid triggering color conversion
407 // at draw time.
set_bitmap_color_space(SkImageInfo * info)408 static void set_bitmap_color_space(SkImageInfo* info) {
409 if (kRGBA_F16_SkColorType == info->colorType()) {
410 *info = info->makeColorSpace(SkColorSpace::MakeSRGBLinear());
411 } else {
412 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
413 }
414 }
415
draw(SkCanvas * canvas) const416 Error CodecSrc::draw(SkCanvas* canvas) const {
417 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
418 if (!encoded) {
419 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
420 }
421
422 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(encoded));
423 if (nullptr == codec.get()) {
424 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
425 }
426
427 SkImageInfo decodeInfo = codec->getInfo();
428 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
429 fDstAlphaType)) {
430 return Error::Nonfatal("Skipping uninteresting test.");
431 }
432
433 // Try to scale the image if it is desired
434 SkISize size = codec->getScaledDimensions(fScale);
435 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
436 return Error::Nonfatal("Test without scaling is uninteresting.");
437 }
438
439 // Visually inspecting very small output images is not necessary. We will
440 // cover these cases in unit testing.
441 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
442 return Error::Nonfatal("Scaling very small images is uninteresting.");
443 }
444 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
445
446 const int bpp = SkColorTypeBytesPerPixel(decodeInfo.colorType());
447 const size_t rowBytes = size.width() * bpp;
448 const size_t safeSize = decodeInfo.getSafeSize(rowBytes);
449 SkAutoMalloc pixels(safeSize);
450
451 SkCodec::Options options;
452 options.fPremulBehavior = canvas->imageInfo().colorSpace() ?
453 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
454 if (kCodecZeroInit_Mode == fMode) {
455 memset(pixels.get(), 0, size.height() * rowBytes);
456 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
457 }
458
459 SkImageInfo bitmapInfo = decodeInfo;
460 set_bitmap_color_space(&bitmapInfo);
461 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
462 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
463 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
464 }
465
466 switch (fMode) {
467 case kAnimated_Mode: {
468 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
469 if (frameInfos.size() <= 1) {
470 return SkStringPrintf("%s is not an animated image.", fPath.c_str());
471 }
472
473 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
474 // into. "factor" is the number of frames to draw on one row. There will be
475 // up to "factor" rows as well.
476 const float root = sqrt((float) frameInfos.size());
477 const int factor = sk_float_ceil2int(root);
478
479 // Used to cache a frame that future frames will depend on.
480 SkAutoMalloc priorFramePixels;
481 int cachedFrame = SkCodec::kNone;
482 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
483 options.fFrameIndex = i;
484 // Check for a prior frame
485 const int reqFrame = frameInfos[i].fRequiredFrame;
486 if (reqFrame != SkCodec::kNone && reqFrame == cachedFrame
487 && priorFramePixels.get()) {
488 // Copy into pixels
489 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
490 options.fPriorFrame = reqFrame;
491 } else {
492 options.fPriorFrame = SkCodec::kNone;
493 }
494 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
495 rowBytes, &options);
496 if (SkCodec::kInvalidInput == result && i > 0) {
497 // Some of our test images have truncated later frames. Treat that
498 // the same as incomplete.
499 result = SkCodec::kIncompleteInput;
500 }
501 switch (result) {
502 case SkCodec::kSuccess:
503 case SkCodec::kErrorInInput:
504 case SkCodec::kIncompleteInput: {
505 // If the next frame depends on this one, store it in priorFrame.
506 // It is possible that we may discard a frame that future frames depend on,
507 // but the codec will simply redecode the discarded frame.
508 // Do this before calling draw_to_canvas, which premultiplies in place. If
509 // we're decoding to unpremul, we want to pass the unmodified frame to the
510 // codec for decoding the next frame.
511 if (static_cast<size_t>(i+1) < frameInfos.size()
512 && frameInfos[i+1].fRequiredFrame == i) {
513 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
514 cachedFrame = i;
515 }
516
517 SkAutoCanvasRestore acr(canvas, true);
518 const int xTranslate = (i % factor) * decodeInfo.width();
519 const int yTranslate = (i / factor) * decodeInfo.height();
520 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
521 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
522 if (result != SkCodec::kSuccess) {
523 return "";
524 }
525 break;
526 }
527 case SkCodec::kInvalidConversion:
528 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
529 return Error::Nonfatal(SkStringPrintf(
530 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str()));
531 }
532 // Fall through.
533 default:
534 return SkStringPrintf("Couldn't getPixels for frame %i in %s.",
535 i, fPath.c_str());
536 }
537 }
538 break;
539 }
540 case kCodecZeroInit_Mode:
541 case kCodec_Mode: {
542 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
543 case SkCodec::kSuccess:
544 // We consider these to be valid, since we should still decode what is
545 // available.
546 case SkCodec::kErrorInInput:
547 case SkCodec::kIncompleteInput:
548 break;
549 default:
550 // Everything else is considered a failure.
551 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
552 }
553
554 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
555 break;
556 }
557 case kScanline_Mode: {
558 void* dst = pixels.get();
559 uint32_t height = decodeInfo.height();
560 const bool useIncremental = [this]() {
561 auto exts = { "png", "PNG", "gif", "GIF" };
562 for (auto ext : exts) {
563 if (fPath.endsWith(ext)) {
564 return true;
565 }
566 }
567 return false;
568 }();
569 // ico may use the old scanline method or the new one, depending on whether it
570 // internally holds a bmp or a png.
571 const bool ico = fPath.endsWith("ico");
572 bool useOldScanlineMethod = !useIncremental && !ico;
573 if (useIncremental || ico) {
574 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
575 rowBytes, &options)) {
576 int rowsDecoded;
577 auto result = codec->incrementalDecode(&rowsDecoded);
578 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
579 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
580 SkCodec::kNo_ZeroInitialized, height,
581 rowsDecoded);
582 }
583 } else {
584 if (useIncremental) {
585 // Error: These should support incremental decode.
586 return "Could not start incremental decode";
587 }
588 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
589 // which should work via startScanlineDecode
590 useOldScanlineMethod = true;
591 }
592 }
593
594 if (useOldScanlineMethod) {
595 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
596 return "Could not start scanline decoder";
597 }
598
599 switch (codec->getScanlineOrder()) {
600 case SkCodec::kTopDown_SkScanlineOrder:
601 case SkCodec::kBottomUp_SkScanlineOrder:
602 // We do not need to check the return value. On an incomplete
603 // image, memory will be filled with a default value.
604 codec->getScanlines(dst, height, rowBytes);
605 break;
606 }
607 }
608
609 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
610 break;
611 }
612 case kStripe_Mode: {
613 const int height = decodeInfo.height();
614 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
615 // does not align with image blocks.
616 const int stripeHeight = 37;
617 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
618 void* dst = pixels.get();
619
620 // Decode odd stripes
621 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
622 return "Could not start scanline decoder";
623 }
624
625 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
626 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
627 // to run this test for image types that do not have this scanline ordering.
628 // We only run this on Jpeg, which is always kTopDown.
629 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
630
631 for (int i = 0; i < numStripes; i += 2) {
632 // Skip a stripe
633 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
634 codec->skipScanlines(linesToSkip);
635
636 // Read a stripe
637 const int startY = (i + 1) * stripeHeight;
638 const int linesToRead = SkTMin(stripeHeight, height - startY);
639 if (linesToRead > 0) {
640 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
641 rowBytes);
642 }
643 }
644
645 // Decode even stripes
646 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
647 if (SkCodec::kSuccess != startResult) {
648 return "Failed to restart scanline decoder with same parameters.";
649 }
650 for (int i = 0; i < numStripes; i += 2) {
651 // Read a stripe
652 const int startY = i * stripeHeight;
653 const int linesToRead = SkTMin(stripeHeight, height - startY);
654 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
655 rowBytes);
656
657 // Skip a stripe
658 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
659 if (linesToSkip > 0) {
660 codec->skipScanlines(linesToSkip);
661 }
662 }
663
664 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
665 break;
666 }
667 case kCroppedScanline_Mode: {
668 const int width = decodeInfo.width();
669 const int height = decodeInfo.height();
670 // This value is chosen because, as we move across the image, it will sometimes
671 // align with the jpeg block sizes and it will sometimes not. This allows us
672 // to test interestingly different code paths in the implementation.
673 const int tileSize = 36;
674 SkIRect subset;
675 for (int x = 0; x < width; x += tileSize) {
676 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
677 options.fSubset = ⊂
678 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
679 return "Could not start scanline decoder.";
680 }
681
682 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
683 }
684
685 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
686 break;
687 }
688 case kSubset_Mode: {
689 // Arbitrarily choose a divisor.
690 int divisor = 2;
691 // Total width/height of the image.
692 const int W = codec->getInfo().width();
693 const int H = codec->getInfo().height();
694 if (divisor > W || divisor > H) {
695 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
696 "for %s with dimensions (%d x %d)", divisor,
697 fPath.c_str(), W, H));
698 }
699 // subset dimensions
700 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
701 const int w = SkAlign2(W / divisor);
702 const int h = SkAlign2(H / divisor);
703 SkIRect subset;
704 options.fSubset = ⊂
705 SkBitmap subsetBm;
706 // We will reuse pixel memory from bitmap.
707 void* dst = pixels.get();
708 // Keep track of left and top (for drawing subsetBm into canvas). We could use
709 // fScale * x and fScale * y, but we want integers such that the next subset will start
710 // where the last one ended. So we'll add decodeInfo.width() and height().
711 int left = 0;
712 for (int x = 0; x < W; x += w) {
713 int top = 0;
714 for (int y = 0; y < H; y+= h) {
715 // Do not make the subset go off the edge of the image.
716 const int preScaleW = SkTMin(w, W - x);
717 const int preScaleH = SkTMin(h, H - y);
718 subset.setXYWH(x, y, preScaleW, preScaleH);
719 // And scale
720 // FIXME: Should we have a version of getScaledDimensions that takes a subset
721 // into account?
722 const int scaledW = SkTMax(1, SkScalarRoundToInt(preScaleW * fScale));
723 const int scaledH = SkTMax(1, SkScalarRoundToInt(preScaleH * fScale));
724 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
725 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
726 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
727 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
728 &options);
729 switch (result) {
730 case SkCodec::kSuccess:
731 case SkCodec::kErrorInInput:
732 case SkCodec::kIncompleteInput:
733 break;
734 default:
735 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
736 "from %s with dimensions (%d x %d)\t error %d",
737 x, y, decodeInfo.width(), decodeInfo.height(),
738 fPath.c_str(), W, H, result);
739 }
740 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
741 SkIntToScalar(left), SkIntToScalar(top));
742
743 // translate by the scaled height.
744 top += decodeInfo.height();
745 }
746 // translate by the scaled width.
747 left += decodeInfo.width();
748 }
749 return "";
750 }
751 default:
752 SkASSERT(false);
753 return "Invalid fMode";
754 }
755 return "";
756 }
757
size() const758 SkISize CodecSrc::size() const {
759 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
760 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(encoded));
761 if (nullptr == codec) {
762 return {0, 0};
763 }
764
765 auto imageSize = codec->getScaledDimensions(fScale);
766 if (fMode == kAnimated_Mode) {
767 // We'll draw one of each frame, so make it big enough to hold them all
768 // in a grid. The grid will be roughly square, with "factor" frames per
769 // row and up to "factor" rows.
770 const size_t count = codec->getFrameInfo().size();
771 const float root = sqrt((float) count);
772 const int factor = sk_float_ceil2int(root);
773 imageSize.fWidth = imageSize.fWidth * factor;
774 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
775 }
776 return imageSize;
777 }
778
name() const779 Name CodecSrc::name() const {
780 if (1.0f == fScale) {
781 Name name = SkOSPath::Basename(fPath.c_str());
782 if (fMode == kAnimated_Mode) {
783 name.append("_animated");
784 }
785 return name;
786 }
787 SkASSERT(fMode != kAnimated_Mode);
788 return get_scaled_name(fPath, fScale);
789 }
790
791 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
792
AndroidCodecSrc(Path path,CodecSrc::DstColorType dstColorType,SkAlphaType dstAlphaType,int sampleSize)793 AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
794 SkAlphaType dstAlphaType, int sampleSize)
795 : fPath(path)
796 , fDstColorType(dstColorType)
797 , fDstAlphaType(dstAlphaType)
798 , fSampleSize(sampleSize)
799 , fRunSerially(serial_from_path_name(path))
800 {}
801
veto(SinkFlags flags) const802 bool AndroidCodecSrc::veto(SinkFlags flags) const {
803 // No need to test decoding to non-raster or indirect backend.
804 return flags.type != SinkFlags::kRaster
805 || flags.approach != SinkFlags::kDirect;
806 }
807
draw(SkCanvas * canvas) const808 Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
809 if (canvas->imageInfo().colorSpace() &&
810 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
811 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
812 // run these tests on legacy canvases.
813 // We allow an exception for F16, since Android uses F16.
814 return Error::Nonfatal("Skip testing to color correct canvas.");
815 }
816
817 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
818 if (!encoded) {
819 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
820 }
821 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
822 if (nullptr == codec.get()) {
823 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
824 }
825
826 SkImageInfo decodeInfo = codec->getInfo();
827 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
828 fDstAlphaType)) {
829 return Error::Nonfatal("Skipping uninteresting test.");
830 }
831
832 // Scale the image if it is desired.
833 SkISize size = codec->getSampledDimensions(fSampleSize);
834
835 // Visually inspecting very small output images is not necessary. We will
836 // cover these cases in unit testing.
837 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
838 return Error::Nonfatal("Scaling very small images is uninteresting.");
839 }
840 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
841
842 int bpp = SkColorTypeBytesPerPixel(decodeInfo.colorType());
843 size_t rowBytes = size.width() * bpp;
844 SkAutoMalloc pixels(size.height() * rowBytes);
845
846 SkBitmap bitmap;
847 SkImageInfo bitmapInfo = decodeInfo;
848 set_bitmap_color_space(&bitmapInfo);
849 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
850 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
851 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
852 }
853
854 // Create options for the codec.
855 SkAndroidCodec::AndroidOptions options;
856 options.fSampleSize = fSampleSize;
857
858 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
859 case SkCodec::kSuccess:
860 case SkCodec::kErrorInInput:
861 case SkCodec::kIncompleteInput:
862 break;
863 default:
864 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
865 }
866 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
867 return "";
868 }
869
size() const870 SkISize AndroidCodecSrc::size() const {
871 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
872 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(encoded));
873 if (nullptr == codec) {
874 return {0, 0};
875 }
876 return codec->getSampledDimensions(fSampleSize);
877 }
878
name() const879 Name AndroidCodecSrc::name() const {
880 // We will replicate the names used by CodecSrc so that images can
881 // be compared in Gold.
882 if (1 == fSampleSize) {
883 return SkOSPath::Basename(fPath.c_str());
884 }
885 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
886 }
887
888 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
889
ImageGenSrc(Path path,Mode mode,SkAlphaType alphaType,bool isGpu)890 ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
891 : fPath(path)
892 , fMode(mode)
893 , fDstAlphaType(alphaType)
894 , fIsGpu(isGpu)
895 , fRunSerially(serial_from_path_name(path))
896 {}
897
veto(SinkFlags flags) const898 bool ImageGenSrc::veto(SinkFlags flags) const {
899 if (fIsGpu) {
900 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
901 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
902 flags.multisampled == SinkFlags::kMultisampled;
903 }
904
905 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
906 }
907
draw(SkCanvas * canvas) const908 Error ImageGenSrc::draw(SkCanvas* canvas) const {
909 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
910 return Error::Nonfatal("Uninteresting to test image generator to 565.");
911 }
912
913 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
914 if (!encoded) {
915 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
916 }
917
918 #if defined(SK_BUILD_FOR_WIN)
919 // Initialize COM in order to test with WIC.
920 SkAutoCoInitialize com;
921 if (!com.succeeded()) {
922 return "Could not initialize COM.";
923 }
924 #endif
925
926 std::unique_ptr<SkImageGenerator> gen(nullptr);
927 switch (fMode) {
928 case kCodec_Mode:
929 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
930 if (!gen) {
931 return "Could not create codec image generator.";
932 }
933 break;
934 case kPlatform_Mode: {
935 #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
936 gen.reset(SkImageGeneratorCG::NewFromEncodedCG(encoded.get()));
937 #elif defined(SK_BUILD_FOR_WIN)
938 gen.reset(SkImageGeneratorWIC::NewFromEncodedWIC(encoded.get()));
939 #endif
940
941 if (!gen) {
942 return "Could not create platform image generator.";
943 }
944 break;
945 }
946 default:
947 SkASSERT(false);
948 return "Invalid image generator mode";
949 }
950
951 // Test deferred decoding path on GPU
952 if (fIsGpu) {
953 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
954 if (!image) {
955 return "Could not create image from codec image generator.";
956 }
957 canvas->drawImage(image, 0, 0);
958 return "";
959 }
960
961 // Test various color and alpha types on CPU
962 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
963
964 SkImageGenerator::Options options;
965 options.fBehavior = canvas->imageInfo().colorSpace() ?
966 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
967
968 int bpp = SkColorTypeBytesPerPixel(decodeInfo.colorType());
969 size_t rowBytes = decodeInfo.width() * bpp;
970 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
971 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
972 SkString err =
973 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
974
975 #if defined(SK_BUILD_FOR_WIN)
976 if (kPlatform_Mode == fMode) {
977 // Do not issue a fatal error for WIC flakiness.
978 return Error::Nonfatal(err);
979 }
980 #endif
981
982 return err;
983 }
984
985 set_bitmap_color_space(&decodeInfo);
986 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
987 CodecSrc::kGetFromCanvas_DstColorType);
988 return "";
989 }
990
size() const991 SkISize ImageGenSrc::size() const {
992 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
993 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(encoded));
994 if (nullptr == codec) {
995 return {0, 0};
996 }
997 return codec->getInfo().dimensions();
998 }
999
name() const1000 Name ImageGenSrc::name() const {
1001 return SkOSPath::Basename(fPath.c_str());
1002 }
1003
1004 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1005
ColorCodecSrc(Path path,Mode mode,SkColorType colorType)1006 ColorCodecSrc::ColorCodecSrc(Path path, Mode mode, SkColorType colorType)
1007 : fPath(path)
1008 , fMode(mode)
1009 , fColorType(colorType)
1010 {}
1011
veto(SinkFlags flags) const1012 bool ColorCodecSrc::veto(SinkFlags flags) const {
1013 // Test to direct raster backends (8888 and 565).
1014 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1015 }
1016
clamp_if_necessary(const SkBitmap & bitmap,SkColorType dstCT)1017 void clamp_if_necessary(const SkBitmap& bitmap, SkColorType dstCT) {
1018 if (kRGBA_F16_SkColorType != bitmap.colorType() || kRGBA_F16_SkColorType == dstCT) {
1019 // No need to clamp if the dst is F16. We will clamp when we encode to PNG.
1020 return;
1021 }
1022
1023 void* ptr = bitmap.getAddr(0, 0);
1024 SkRasterPipeline_<256> p;
1025 p.append(SkRasterPipeline::load_f16, &ptr);
1026 p.append(SkRasterPipeline::clamp_0);
1027 if (kPremul_SkAlphaType == bitmap.alphaType()) {
1028 p.append(SkRasterPipeline::clamp_a);
1029 } else {
1030 p.append(SkRasterPipeline::clamp_1);
1031 }
1032 p.append(SkRasterPipeline::store_f16, &ptr);
1033
1034 auto run = p.compile();
1035 for (int y = 0; y < bitmap.height(); y++) {
1036 run(0, y, bitmap.width());
1037 ptr = SkTAddOffset<void>(ptr, bitmap.rowBytes());
1038 }
1039 }
1040
draw(SkCanvas * canvas) const1041 Error ColorCodecSrc::draw(SkCanvas* canvas) const {
1042 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
1043 return Error::Nonfatal("No need to test color correction to 565 backend.");
1044 }
1045
1046 bool runInLegacyMode = kBaseline_Mode == fMode;
1047 if (runInLegacyMode && canvas->imageInfo().colorSpace()) {
1048 return Error::Nonfatal("Skipping tests that are only interesting in legacy mode.");
1049 } else if (!runInLegacyMode && !canvas->imageInfo().colorSpace()) {
1050 return Error::Nonfatal("Skipping tests that are only interesting in srgb mode.");
1051 }
1052
1053 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1054 if (!encoded) {
1055 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1056 }
1057
1058 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(encoded));
1059 if (nullptr == codec.get()) {
1060 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
1061 }
1062
1063 // Load the dst ICC profile. This particular dst is fairly similar to Adobe RGB.
1064 sk_sp<SkData> dstData = SkData::MakeFromFileName(
1065 GetResourcePath("icc_profiles/HP_ZR30w.icc").c_str());
1066 if (!dstData) {
1067 return "Cannot read monitor profile. Is the resource path set correctly?";
1068 }
1069
1070 sk_sp<SkColorSpace> dstSpace = nullptr;
1071 if (kDst_sRGB_Mode == fMode) {
1072 dstSpace = SkColorSpace::MakeSRGB();
1073 } else if (kDst_HPZR30w_Mode == fMode) {
1074 dstSpace = SkColorSpace::MakeICC(dstData->data(), dstData->size());
1075 }
1076
1077 SkImageInfo decodeInfo = codec->getInfo().makeColorType(fColorType).makeColorSpace(dstSpace);
1078 if (kUnpremul_SkAlphaType == decodeInfo.alphaType()) {
1079 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
1080 }
1081 if (kRGBA_F16_SkColorType == fColorType) {
1082 SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(decodeInfo.colorSpace())->type());
1083 SkColorSpace_XYZ* csXYZ = static_cast<SkColorSpace_XYZ*>(decodeInfo.colorSpace());
1084 decodeInfo = decodeInfo.makeColorSpace(csXYZ->makeLinearGamma());
1085 }
1086
1087 SkImageInfo bitmapInfo = decodeInfo;
1088 set_bitmap_color_space(&bitmapInfo);
1089 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
1090 kBGRA_8888_SkColorType == decodeInfo.colorType())
1091 {
1092 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
1093 }
1094
1095 SkBitmap bitmap;
1096 if (!bitmap.tryAllocPixels(bitmapInfo)) {
1097 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
1098 bitmapInfo.width(), bitmapInfo.height());
1099 }
1100
1101 size_t rowBytes = bitmap.rowBytes();
1102 SkCodec::Result r = codec->getPixels(decodeInfo, bitmap.getPixels(), rowBytes);
1103 switch (r) {
1104 case SkCodec::kSuccess:
1105 case SkCodec::kErrorInInput:
1106 case SkCodec::kIncompleteInput:
1107 break;
1108 default:
1109 return SkStringPrintf("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
1110 }
1111
1112 switch (fMode) {
1113 case kBaseline_Mode:
1114 case kDst_sRGB_Mode:
1115 case kDst_HPZR30w_Mode:
1116 // We do not support drawing unclamped F16.
1117 clamp_if_necessary(bitmap, canvas->imageInfo().colorType());
1118 canvas->drawBitmap(bitmap, 0, 0);
1119 break;
1120 default:
1121 SkASSERT(false);
1122 return "Invalid fMode";
1123 }
1124 return "";
1125 }
1126
size() const1127 SkISize ColorCodecSrc::size() const {
1128 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
1129 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(encoded));
1130 if (nullptr == codec) {
1131 return {0, 0};
1132 }
1133 return {codec->getInfo().width(), codec->getInfo().height()};
1134 }
1135
name() const1136 Name ColorCodecSrc::name() const {
1137 return SkOSPath::Basename(fPath.c_str());
1138 }
1139
1140 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1141
1142 static const SkRect kSKPViewport = {0,0, 1000,1000};
1143
SKPSrc(Path path)1144 SKPSrc::SKPSrc(Path path) : fPath(path) {}
1145
draw(SkCanvas * canvas) const1146 Error SKPSrc::draw(SkCanvas* canvas) const {
1147 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(fPath.c_str());
1148 if (!stream) {
1149 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1150 }
1151 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get()));
1152 if (!pic) {
1153 return SkStringPrintf("Couldn't decode %s as a picture.", fPath.c_str());
1154 }
1155 stream = nullptr; // Might as well drop this when we're done with it.
1156
1157 canvas->clipRect(kSKPViewport);
1158 canvas->drawPicture(pic);
1159 return "";
1160 }
1161
size() const1162 SkISize SKPSrc::size() const {
1163 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(fPath.c_str());
1164 if (!stream) {
1165 return {0, 0};
1166 }
1167 SkPictInfo info;
1168 if (!SkPicture::InternalOnly_StreamIsSKP(stream.get(), &info)) {
1169 return {0, 0};
1170 }
1171 SkRect viewport = kSKPViewport;
1172 if (!viewport.intersect(info.fCullRect)) {
1173 return {0, 0};
1174 }
1175 return viewport.roundOut().size();
1176 }
1177
name() const1178 Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1179
1180 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1181 #if defined(SK_XML)
1182 // Used when the image doesn't have an intrinsic size.
1183 static const SkSize kDefaultSVGSize = {1000, 1000};
1184
1185 // Used to force-scale tiny fixed-size images.
1186 static const SkSize kMinimumSVGSize = {128, 128};
1187
SVGSrc(Path path)1188 SVGSrc::SVGSrc(Path path)
1189 : fName(SkOSPath::Basename(path.c_str()))
1190 , fScale(1) {
1191
1192 SkFILEStream stream(path.c_str());
1193 if (!stream.isValid()) {
1194 return;
1195 }
1196 fDom = SkSVGDOM::MakeFromStream(stream);
1197 if (!fDom) {
1198 return;
1199 }
1200
1201 const SkSize& sz = fDom->containerSize();
1202 if (sz.isEmpty()) {
1203 // no intrinsic size
1204 fDom->setContainerSize(kDefaultSVGSize);
1205 } else {
1206 fScale = SkTMax(1.f, SkTMax(kMinimumSVGSize.width() / sz.width(),
1207 kMinimumSVGSize.height() / sz.height()));
1208 }
1209 }
1210
draw(SkCanvas * canvas) const1211 Error SVGSrc::draw(SkCanvas* canvas) const {
1212 if (!fDom) {
1213 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
1214 }
1215
1216 SkAutoCanvasRestore acr(canvas, true);
1217 canvas->scale(fScale, fScale);
1218 fDom->render(canvas);
1219
1220 return "";
1221 }
1222
size() const1223 SkISize SVGSrc::size() const {
1224 if (!fDom) {
1225 return {0, 0};
1226 }
1227
1228 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1229 .toRound();
1230 }
1231
name() const1232 Name SVGSrc::name() const { return fName; }
1233
veto(SinkFlags flags) const1234 bool SVGSrc::veto(SinkFlags flags) const {
1235 // No need to test to non-(raster||gpu||vector) or indirect backends.
1236 bool type_ok = flags.type == SinkFlags::kRaster
1237 || flags.type == SinkFlags::kGPU
1238 || flags.type == SinkFlags::kVector;
1239
1240 return !type_ok || flags.approach != SinkFlags::kDirect;
1241 }
1242
1243 #endif // defined(SK_XML)
1244 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1245
MSKPSrc(Path path)1246 MSKPSrc::MSKPSrc(Path path) : fPath(path) {
1247 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1248 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1249 if (count > 0) {
1250 fPages.reset(count);
1251 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1252 }
1253 }
1254
pageCount() const1255 int MSKPSrc::pageCount() const { return fPages.count(); }
1256
size() const1257 SkISize MSKPSrc::size() const { return this->size(0); }
size(int i) const1258 SkISize MSKPSrc::size(int i) const {
1259 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
1260 }
1261
draw(SkCanvas * c) const1262 Error MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
draw(int i,SkCanvas * canvas) const1263 Error MSKPSrc::draw(int i, SkCanvas* canvas) const {
1264 if (this->pageCount() == 0) {
1265 return SkStringPrintf("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1266 }
1267 if (i >= fPages.count() || i < 0) {
1268 return SkStringPrintf("MultiPictureDocument page number out of range: %d", i);
1269 }
1270 SkPicture* page = fPages[i].fPicture.get();
1271 if (!page) {
1272 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1273 if (!stream) {
1274 return SkStringPrintf("Unable to open file: %s", fPath.c_str());
1275 }
1276 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
1277 return SkStringPrintf("SkMultiPictureDocument reader failed on page %d: %s", i,
1278 fPath.c_str());
1279 }
1280 page = fPages[i].fPicture.get();
1281 }
1282 canvas->drawPicture(page);
1283 return "";
1284 }
1285
name() const1286 Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1287
1288 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1289
draw(const Src & src,SkBitmap *,SkWStream *,SkString *) const1290 Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
1291 return src.draw(SkMakeNullCanvas().get());
1292 }
1293
1294 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1295
1296 DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1297
GPUSink(GrContextFactory::ContextType ct,GrContextFactory::ContextOverrides overrides,int samples,bool diText,SkColorType colorType,SkAlphaType alphaType,sk_sp<SkColorSpace> colorSpace,bool threaded)1298 GPUSink::GPUSink(GrContextFactory::ContextType ct,
1299 GrContextFactory::ContextOverrides overrides,
1300 int samples,
1301 bool diText,
1302 SkColorType colorType,
1303 SkAlphaType alphaType,
1304 sk_sp<SkColorSpace> colorSpace,
1305 bool threaded)
1306 : fContextType(ct)
1307 , fContextOverrides(overrides)
1308 , fSampleCount(samples)
1309 , fUseDIText(diText)
1310 , fColorType(colorType)
1311 , fAlphaType(alphaType)
1312 , fColorSpace(std::move(colorSpace))
1313 , fThreaded(threaded) {}
1314
1315 DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
1316
draw(const Src & src,SkBitmap * dst,SkWStream *,SkString * log) const1317 Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log) const {
1318 GrContextOptions grOptions;
1319
1320 src.modifyGrContextOptions(&grOptions);
1321
1322 GrContextFactory factory(grOptions);
1323 const SkISize size = src.size();
1324 SkImageInfo info =
1325 SkImageInfo::Make(size.width(), size.height(), fColorType, fAlphaType, fColorSpace);
1326 #if SK_SUPPORT_GPU
1327 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
1328 const int maxDimension = context->caps()->maxTextureSize();
1329 if (maxDimension < SkTMax(size.width(), size.height())) {
1330 return Error::Nonfatal("Src too large to create a texture.\n");
1331 }
1332 #endif
1333
1334 auto surface(
1335 NewGpuSurface(&factory, fContextType, fContextOverrides, info, fSampleCount, fUseDIText));
1336 if (!surface) {
1337 return "Could not create a surface.";
1338 }
1339 if (FLAGS_preAbandonGpuContext) {
1340 factory.abandonContexts();
1341 }
1342 SkCanvas* canvas = surface->getCanvas();
1343 Error err = src.draw(canvas);
1344 if (!err.isEmpty()) {
1345 return err;
1346 }
1347 canvas->flush();
1348 if (FLAGS_gpuStats) {
1349 canvas->getGrContext()->dumpCacheStats(log);
1350 canvas->getGrContext()->dumpGpuStats(log);
1351 }
1352 if (info.colorType() == kRGB_565_SkColorType || info.colorType() == kARGB_4444_SkColorType) {
1353 // We don't currently support readbacks into these formats on the GPU backend. Convert to
1354 // 32 bit.
1355 info = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
1356 kPremul_SkAlphaType, fColorSpace);
1357 }
1358 dst->allocPixels(info);
1359 canvas->readPixels(*dst, 0, 0);
1360 if (FLAGS_abandonGpuContext) {
1361 factory.abandonContexts();
1362 } else if (FLAGS_releaseAndAbandonGpuContext) {
1363 factory.releaseResourcesAndAbandonContexts();
1364 }
1365 return "";
1366 }
1367
1368 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1369
draw_skdocument(const Src & src,SkDocument * doc,SkWStream * dst)1370 static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
1371 if (src.size().isEmpty()) {
1372 return "Source has empty dimensions";
1373 }
1374 SkASSERT(doc);
1375 int pageCount = src.pageCount();
1376 for (int i = 0; i < pageCount; ++i) {
1377 int width = src.size(i).width(), height = src.size(i).height();
1378 SkCanvas* canvas =
1379 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1380 if (!canvas) {
1381 return "SkDocument::beginPage(w,h) returned nullptr";
1382 }
1383 Error err = src.draw(i, canvas);
1384 if (!err.isEmpty()) {
1385 return err;
1386 }
1387 doc->endPage();
1388 }
1389 doc->close();
1390 dst->flush();
1391 return "";
1392 }
1393
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1394 Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1395 SkDocument::PDFMetadata metadata;
1396 metadata.fTitle = src.name();
1397 metadata.fSubject = "rendering correctness test";
1398 metadata.fCreator = "Skia/DM";
1399 sk_sp<SkDocument> doc = SkDocument::MakePDF(dst, SK_ScalarDefaultRasterDPI,
1400 metadata, nullptr, fPDFA);
1401 if (!doc) {
1402 return "SkDocument::MakePDF() returned nullptr";
1403 }
1404 return draw_skdocument(src, doc.get(), dst);
1405 }
1406
1407 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1408
XPSSink()1409 XPSSink::XPSSink() {}
1410
1411 #ifdef SK_BUILD_FOR_WIN
make_xps_factory()1412 static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1413 IXpsOMObjectFactory* factory;
1414 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1415 nullptr,
1416 CLSCTX_INPROC_SERVER,
1417 IID_PPV_ARGS(&factory)));
1418 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1419 }
1420
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1421 Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1422 SkAutoCoInitialize com;
1423 if (!com.succeeded()) {
1424 return "Could not initialize COM.";
1425 }
1426 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1427 if (!factory) {
1428 return "Failed to create XPS Factory.";
1429 }
1430 sk_sp<SkDocument> doc(SkDocument::MakeXPS(dst, factory.get()));
1431 if (!doc) {
1432 return "SkDocument::MakeXPS() returned nullptr";
1433 }
1434 return draw_skdocument(src, doc.get(), dst);
1435 }
1436 #else
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1437 Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1438 return "XPS not supported on this platform.";
1439 }
1440 #endif
1441
1442 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1443
PipeSink()1444 PipeSink::PipeSink() {}
1445
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1446 Error PipeSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1447 return src.draw(SkPipeSerializer().beginWrite(SkRect::Make(src.size()), dst));
1448 }
1449
1450 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1451
SKPSink()1452 SKPSink::SKPSink() {}
1453
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1454 Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1455 SkSize size;
1456 size = src.size();
1457 SkPictureRecorder recorder;
1458 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1459 if (!err.isEmpty()) {
1460 return err;
1461 }
1462 recorder.finishRecordingAsPicture()->serialize(dst);
1463 return "";
1464 }
1465
1466 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1467
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1468 Error DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1469 SkDebugCanvas debugCanvas(src.size().width(), src.size().height());
1470 Error err = src.draw(&debugCanvas);
1471 if (!err.isEmpty()) {
1472 return err;
1473 }
1474 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
1475 UrlDataManager dataManager(SkString("data"));
1476 Json::Value json = debugCanvas.toJSON(
1477 dataManager, debugCanvas.getSize(), nullCanvas.get());
1478 std::string value = Json::StyledWriter().write(json);
1479 return dst->write(value.c_str(), value.size()) ? "" : "SkWStream Error";
1480 }
1481
1482 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1483
SVGSink()1484 SVGSink::SVGSink() {}
1485
draw(const Src & src,SkBitmap *,SkWStream * dst,SkString *) const1486 Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1487 #if defined(SK_XML)
1488 std::unique_ptr<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
1489 return src.draw(SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
1490 SkIntToScalar(src.size().height())),
1491 xmlWriter.get()).get());
1492 #else
1493 return Error("SVG sink is disabled.");
1494 #endif // SK_XML
1495 }
1496
1497 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1498
RasterSink(SkColorType colorType,sk_sp<SkColorSpace> colorSpace)1499 RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
1500 : fColorType(colorType)
1501 , fColorSpace(std::move(colorSpace)) {}
1502
draw(const Src & src,SkBitmap * dst,SkWStream *,SkString *) const1503 Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
1504 const SkISize size = src.size();
1505 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1506 SkAlphaType alphaType = kPremul_SkAlphaType;
1507 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1508
1509 dst->allocPixelsFlags(SkImageInfo::Make(size.width(), size.height(),
1510 fColorType, alphaType, fColorSpace),
1511 SkBitmap::kZeroPixels_AllocFlag);
1512 SkCanvas canvas(*dst);
1513 return src.draw(&canvas);
1514 }
1515
1516 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1517
1518 // Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
1519 // passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
1520 // Several examples below.
1521
1522 template <typename Fn>
draw_to_canvas(Sink * sink,SkBitmap * bitmap,SkWStream * stream,SkString * log,SkISize size,const Fn & draw)1523 static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
1524 SkISize size, const Fn& draw) {
1525 class ProxySrc : public Src {
1526 public:
1527 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
1528 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
1529 Name name() const override { return "ProxySrc"; }
1530 SkISize size() const override { return fSize; }
1531 private:
1532 SkISize fSize;
1533 const Fn& fDraw;
1534 };
1535 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
1536 }
1537
1538 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1539
1540 DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1541
1542 // Is *bitmap identical to what you get drawing src into sink?
check_against_reference(const SkBitmap * bitmap,const Src & src,Sink * sink)1543 static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1544 // We can only check raster outputs.
1545 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1546 if (FLAGS_check && bitmap) {
1547 SkBitmap reference;
1548 SkString log;
1549 SkDynamicMemoryWStream wStream;
1550 Error err = sink->draw(src, &reference, &wStream, &log);
1551 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1552 SkASSERT(err.isEmpty());
1553 if (!err.isEmpty()) {
1554 return err;
1555 }
1556 // The dimensions are a property of the Src only, and so should be identical.
1557 SkASSERT(reference.getSize() == bitmap->getSize());
1558 if (reference.getSize() != bitmap->getSize()) {
1559 return "Dimensions don't match reference";
1560 }
1561 // All SkBitmaps in DM are pre-locked and tight, so this comparison is easy.
1562 if (0 != memcmp(reference.getPixels(), bitmap->getPixels(), reference.getSize())) {
1563 return "Pixels don't match reference";
1564 }
1565 }
1566 return "";
1567 }
1568
1569 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1570
auto_compute_translate(SkMatrix * matrix,int srcW,int srcH)1571 static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1572 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1573 matrix->mapRect(&bounds);
1574 matrix->postTranslate(-bounds.x(), -bounds.y());
1575 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
1576 }
1577
ViaMatrix(SkMatrix matrix,Sink * sink)1578 ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
1579
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1580 Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1581 SkMatrix matrix = fMatrix;
1582 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
1583 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
1584 canvas->concat(matrix);
1585 return src.draw(canvas);
1586 });
1587 }
1588
1589 // Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1590 // This should be pixel-preserving.
ViaUpright(SkMatrix matrix,Sink * sink)1591 ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
1592
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1593 Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1594 Error err = fSink->draw(src, bitmap, stream, log);
1595 if (!err.isEmpty()) {
1596 return err;
1597 }
1598
1599 SkMatrix inverse;
1600 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1601 return "Cannot upright --matrix.";
1602 }
1603 SkMatrix upright = SkMatrix::I();
1604 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1605 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1606 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1607 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1608
1609 SkBitmap uprighted;
1610 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1611 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1612
1613 SkCanvas canvas(uprighted);
1614 canvas.concat(upright);
1615 SkPaint paint;
1616 paint.setBlendMode(SkBlendMode::kSrc);
1617 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1618
1619 *bitmap = uprighted;
1620 return "";
1621 }
1622
1623 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1624
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1625 Error ViaSerialization::draw(
1626 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1627 // Record our Src into a picture.
1628 auto size = src.size();
1629 SkPictureRecorder recorder;
1630 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1631 SkIntToScalar(size.height())));
1632 if (!err.isEmpty()) {
1633 return err;
1634 }
1635 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
1636
1637 // Serialize it and then deserialize it.
1638 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
1639
1640 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
1641 canvas->drawPicture(deserialized);
1642 return check_against_reference(bitmap, src, fSink.get());
1643 });
1644 }
1645
1646 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1647
ViaTiles(int w,int h,SkBBHFactory * factory,Sink * sink)1648 ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1649 : Via(sink)
1650 , fW(w)
1651 , fH(h)
1652 , fFactory(factory) {}
1653
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1654 Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1655 auto size = src.size();
1656 SkPictureRecorder recorder;
1657 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1658 SkIntToScalar(size.height()),
1659 fFactory.get()));
1660 if (!err.isEmpty()) {
1661 return err;
1662 }
1663 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
1664
1665 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
1666 const int xTiles = (size.width() + fW - 1) / fW,
1667 yTiles = (size.height() + fH - 1) / fH;
1668 SkMultiPictureDraw mpd(xTiles*yTiles);
1669 SkTArray<sk_sp<SkSurface>> surfaces;
1670 // surfaces.setReserve(xTiles*yTiles);
1671
1672 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1673 for (int j = 0; j < yTiles; j++) {
1674 for (int i = 0; i < xTiles; i++) {
1675 // This lets our ultimate Sink determine the best kind of surface.
1676 // E.g., if it's a GpuSink, the surfaces and images are textures.
1677 auto s = canvas->makeSurface(info);
1678 if (!s) {
1679 s = SkSurface::MakeRaster(info); // Some canvases can't create surfaces.
1680 }
1681 surfaces.push_back(s);
1682 SkCanvas* c = s->getCanvas();
1683 c->translate(SkIntToScalar(-i * fW),
1684 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
1685 mpd.add(c, pic.get());
1686 }
1687 }
1688 mpd.draw();
1689 for (int j = 0; j < yTiles; j++) {
1690 for (int i = 0; i < xTiles; i++) {
1691 sk_sp<SkImage> image(surfaces[i+xTiles*j]->makeImageSnapshot());
1692 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1693 }
1694 }
1695 return "";
1696 });
1697 }
1698
1699 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1700
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1701 Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1702 auto size = src.size();
1703 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1704 SkPictureRecorder recorder;
1705 sk_sp<SkPicture> pic;
1706 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1707 SkIntToScalar(size.height())));
1708 if (!err.isEmpty()) {
1709 return err;
1710 }
1711 pic = recorder.finishRecordingAsPicture();
1712 canvas->drawPicture(pic);
1713 return check_against_reference(bitmap, src, fSink.get());
1714 });
1715 }
1716
1717 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1718
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1719 Error ViaDefer::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1720 auto size = src.size();
1721 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1722 SkDeferredCanvas deferred(canvas, SkDeferredCanvas::kEager);
1723 return src.draw(&deferred);
1724 });
1725 }
1726
1727 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1728
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1729 Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1730 auto size = src.size();
1731 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1732 SkDynamicMemoryWStream tmpStream;
1733 Error err = src.draw(SkPipeSerializer().beginWrite(SkRect::Make(size), &tmpStream));
1734 if (!err.isEmpty()) {
1735 return err;
1736 }
1737 sk_sp<SkData> data = tmpStream.detachAsData();
1738 SkPipeDeserializer().playback(data->data(), data->size(), canvas);
1739 return check_against_reference(bitmap, src, fSink.get());
1740 });
1741 }
1742
1743 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1744
1745 // Draw the Src into two pictures, then draw the second picture into the wrapped Sink.
1746 // This tests that any shortcuts we may take while recording that second picture are legal.
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1747 Error ViaSecondPicture::draw(
1748 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1749 auto size = src.size();
1750 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1751 SkPictureRecorder recorder;
1752 sk_sp<SkPicture> pic;
1753 for (int i = 0; i < 2; i++) {
1754 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1755 SkIntToScalar(size.height())));
1756 if (!err.isEmpty()) {
1757 return err;
1758 }
1759 pic = recorder.finishRecordingAsPicture();
1760 }
1761 canvas->drawPicture(pic);
1762 return check_against_reference(bitmap, src, fSink.get());
1763 });
1764 }
1765
1766 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1767
1768 // Draw the Src twice. This can help exercise caching.
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1769 Error ViaTwice::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1770 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) -> Error {
1771 for (int i = 0; i < 2; i++) {
1772 SkAutoCanvasRestore acr(canvas, true/*save now*/);
1773 canvas->clear(SK_ColorTRANSPARENT);
1774 Error err = src.draw(canvas);
1775 if (err.isEmpty()) {
1776 return err;
1777 }
1778 }
1779 return check_against_reference(bitmap, src, fSink.get());
1780 });
1781 }
1782
1783 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1784
1785 #ifdef TEST_VIA_SVG
1786 #include "SkXMLWriter.h"
1787 #include "SkSVGCanvas.h"
1788 #include "SkSVGDOM.h"
1789
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1790 Error ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1791 auto size = src.size();
1792 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1793 SkDynamicMemoryWStream wstream;
1794 SkXMLStreamWriter writer(&wstream);
1795 Error err = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
1796 if (!err.isEmpty()) {
1797 return err;
1798 }
1799 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
1800 auto dom = SkSVGDOM::MakeFromStream(*rstream);
1801 if (dom) {
1802 dom->setContainerSize(SkSize::Make(size));
1803 dom->render(canvas);
1804 }
1805 return "";
1806 });
1807 }
1808 #endif
1809
1810 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1811
1812 // This is like SkRecords::Draw, in that it plays back SkRecords ops into a Canvas.
1813 // Unlike SkRecords::Draw, it builds a single-op sub-picture out of each Draw-type op.
1814 // This is an only-slightly-exaggerated simluation of Blink's Slimming Paint pictures.
1815 struct DrawsAsSingletonPictures {
1816 SkCanvas* fCanvas;
1817 const SkDrawableList& fDrawables;
1818 SkRect fBounds;
1819
1820 template <typename T>
drawDM::DrawsAsSingletonPictures1821 void draw(const T& op, SkCanvas* canvas) {
1822 // We must pass SkMatrix::I() as our initial matrix.
1823 // By default SkRecords::Draw() uses the canvas' matrix as its initial matrix,
1824 // which would have the funky effect of applying transforms over and over.
1825 SkRecords::Draw d(canvas, nullptr, fDrawables.begin(), fDrawables.count(), &SkMatrix::I());
1826 d(op);
1827 }
1828
1829 // Draws get their own picture.
1830 template <typename T>
SK_WHENDM::DrawsAsSingletonPictures1831 SK_WHEN(T::kTags & SkRecords::kDraw_Tag, void) operator()(const T& op) {
1832 SkPictureRecorder rec;
1833 this->draw(op, rec.beginRecording(fBounds));
1834 sk_sp<SkPicture> pic(rec.finishRecordingAsPicture());
1835 fCanvas->drawPicture(pic);
1836 }
1837
1838 // We'll just issue non-draws directly.
1839 template <typename T>
operator ()DM::DrawsAsSingletonPictures1840 skstd::enable_if_t<!(T::kTags & SkRecords::kDraw_Tag), void> operator()(const T& op) {
1841 this->draw(op, fCanvas);
1842 }
1843 };
1844
1845 // Record Src into a picture, then record it into a macro picture with a sub-picture for each draw.
1846 // Then play back that macro picture into our wrapped sink.
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1847 Error ViaSingletonPictures::draw(
1848 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1849 auto size = src.size();
1850 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1851 // Use low-level (Skia-private) recording APIs so we can read the SkRecord.
1852 SkRecord skr;
1853 SkRecorder recorder(&skr, size.width(), size.height());
1854 Error err = src.draw(&recorder);
1855 if (!err.isEmpty()) {
1856 return err;
1857 }
1858
1859 // Record our macro-picture, with each draw op as its own sub-picture.
1860 SkPictureRecorder macroRec;
1861 SkCanvas* macroCanvas = macroRec.beginRecording(SkIntToScalar(size.width()),
1862 SkIntToScalar(size.height()));
1863
1864 std::unique_ptr<SkDrawableList> drawables(recorder.detachDrawableList());
1865 const SkDrawableList empty;
1866
1867 DrawsAsSingletonPictures drawsAsSingletonPictures = {
1868 macroCanvas,
1869 drawables ? *drawables : empty,
1870 SkRect::MakeWH((SkScalar)size.width(), (SkScalar)size.height()),
1871 };
1872 for (int i = 0; i < skr.count(); i++) {
1873 skr.visit(i, drawsAsSingletonPictures);
1874 }
1875 sk_sp<SkPicture> macroPic(macroRec.finishRecordingAsPicture());
1876
1877 canvas->drawPicture(macroPic);
1878 return check_against_reference(bitmap, src, fSink.get());
1879 });
1880 }
1881
1882 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1883
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1884 Error ViaLite::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1885 auto size = src.size();
1886 SkIRect bounds = {0,0, size.width(), size.height()};
1887 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
1888 SkLiteDL dl;
1889 SkLiteRecorder rec;
1890 rec.reset(&dl, bounds);
1891
1892 Error err = src.draw(&rec);
1893 if (!err.isEmpty()) {
1894 return err;
1895 }
1896 dl.draw(canvas);
1897 return check_against_reference(bitmap, src, fSink.get());
1898 });
1899 }
1900
1901 /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1902
ViaCSXform(Sink * sink,sk_sp<SkColorSpace> cs,bool colorSpin)1903 ViaCSXform::ViaCSXform(Sink* sink, sk_sp<SkColorSpace> cs, bool colorSpin)
1904 : Via(sink)
1905 , fCS(std::move(cs))
1906 , fColorSpin(colorSpin) {}
1907
draw(const Src & src,SkBitmap * bitmap,SkWStream * stream,SkString * log) const1908 Error ViaCSXform::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1909 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
1910 [&](SkCanvas* canvas) -> Error {
1911 auto proxy = SkCreateColorSpaceXformCanvas(canvas, fCS);
1912 Error err = src.draw(proxy.get());
1913 if (!err.isEmpty()) {
1914 return err;
1915 }
1916
1917 // Undo the color spin, so we can look at the pixels in Gold.
1918 if (fColorSpin) {
1919 SkBitmap pixels;
1920 pixels.allocPixels(canvas->imageInfo());
1921 canvas->readPixels(pixels, 0, 0);
1922 for (int y = 0; y < pixels.height(); y++) {
1923 for (int x = 0; x < pixels.width(); x++) {
1924 uint32_t pixel = *pixels.getAddr32(x, y);
1925 uint8_t r = SkGetPackedR32(pixel);
1926 uint8_t g = SkGetPackedG32(pixel);
1927 uint8_t b = SkGetPackedB32(pixel);
1928 uint8_t a = SkGetPackedA32(pixel);
1929 *pixels.getAddr32(x, y) =
1930 SkSwizzle_RGBA_to_PMColor(b << 0 | r << 8 | g << 16 | a << 24);
1931 }
1932 }
1933
1934 canvas->writePixels(pixels, 0, 0);
1935 }
1936
1937 return "";
1938 });
1939 }
1940
1941 } // namespace DM
1942