blob: 29364933635b941ff2cae42f98cf30fd1fc47001 [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"
Brian Salomonf865b052018-03-09 09:01:53 -05009#include <cmath>
10#include <functional>
11#include "../src/jumper/SkJumper.h"
msarett9876ac52016-06-01 14:47:18 -070012#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -070013#include "SkAndroidCodec.h"
Hal Canary95e3c052017-01-11 12:44:43 -050014#include "SkAutoMalloc.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040015#include "SkBase64.h"
scroggof24f2242015-03-03 08:59:20 -080016#include "SkCodec.h"
msarettb714fb02016-01-22 14:46:42 -080017#include "SkCodecImageGenerator.h"
msarett888dc162016-05-23 10:21:17 -070018#include "SkColorSpace.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000019#include "SkColorSpaceXform.h"
Mike Klein841101d2017-03-10 09:55:51 -050020#include "SkColorSpaceXformCanvas.h"
Hal Canary95e3c052017-01-11 12:44:43 -050021#include "SkColorSpace_XYZ.h"
mtkleina16e69e2015-05-05 11:38:45 -070022#include "SkCommonFlags.h"
Chris Dalton040238b2017-12-18 14:22:34 -070023#include "SkCommonFlagsGpu.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070024#include "SkData.h"
Hal Canary85c7fe82016-10-25 10:33:27 -040025#include "SkDebugCanvas.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040026#include "SkDeferredDisplayListRecorder.h"
mtklein748ca3b2015-01-15 10:56:12 -080027#include "SkDocument.h"
Brian Osmanf9810662017-08-30 10:02:10 -040028#include "SkExecutor.h"
mtkleinb3e5e4d2015-03-25 13:13:43 -070029#include "SkImageGenerator.h"
msarett18976312016-03-09 14:20:58 -080030#include "SkImageGeneratorCG.h"
msarettfc0b6d12016-03-17 13:50:17 -070031#include "SkImageGeneratorWIC.h"
Mike Reed7fcfb622018-02-09 13:26:46 -050032#include "SkImageInfoPriv.h"
mtklein8bbbb692016-08-15 12:56:00 -070033#include "SkLiteDL.h"
34#include "SkLiteRecorder.h"
Herb Derbyefe39bc2018-05-01 17:06:20 -040035#include "SkMakeUnique.h"
mtkleinc8be09a2016-01-04 18:56:57 -080036#include "SkMallocPixelRef.h"
Hal Canary45cde312017-04-03 16:06:42 -040037#include "SkMultiPictureDocumentPriv.h"
mtklein748ca3b2015-01-15 10:56:12 -080038#include "SkMultiPictureDraw.h"
mtkleinad66f9b2015-02-13 15:11:10 -080039#include "SkNullCanvas.h"
mtklein748ca3b2015-01-15 10:56:12 -080040#include "SkOSFile.h"
Ben Wagnerbf111d72016-11-07 18:05:29 -050041#include "SkOSPath.h"
msarett9e9444c2016-02-03 12:39:10 -080042#include "SkOpts.h"
Mike Reede7a58322017-12-20 14:09:20 -050043#include "SkPictureCommon.h"
mtkleinffa901a2015-03-16 10:38:07 -070044#include "SkPictureData.h"
mtklein748ca3b2015-01-15 10:56:12 -080045#include "SkPictureRecorder.h"
reed54dc4872016-09-13 08:09:45 -070046#include "SkPipe.h"
Brian Osmane5756ec2017-09-06 17:08:30 -040047#include "SkPngEncoder.h"
mtklein748ca3b2015-01-15 10:56:12 -080048#include "SkRandom.h"
mtkleind31c13d2015-05-05 12:59:56 -070049#include "SkRecordDraw.h"
50#include "SkRecorder.h"
scroggoa1193e42015-01-21 12:09:53 -080051#include "SkStream.h"
Brian Salomonf865b052018-03-09 09:01:53 -050052#include "SkSurfaceCharacterization.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000053#include "SkSwizzler.h"
Brian Salomonf865b052018-03-09 09:01:53 -050054#include "SkTLogic.h"
Robert Phillipsad8a43f2017-08-30 12:06:35 -040055#include "SkTaskGroup.h"
Yuqian Lib8b62532018-02-23 14:13:36 +080056#include "SkThreadedBMPDevice.h"
msarettfc0b6d12016-03-17 13:50:17 -070057#if defined(SK_BUILD_FOR_WIN)
58 #include "SkAutoCoInitialize.h"
Hal Canary5e221e72017-02-06 09:51:42 -050059 #include "SkHRESULT.h"
60 #include "SkTScopedComPtr.h"
61 #include <XpsObjectModel.h>
msarettfc0b6d12016-03-17 13:50:17 -070062#endif
63
Florin Malita87ccf332018-05-04 12:23:24 -040064#if defined(SK_ENABLE_SKOTTIE)
Florin Malita54f65c42018-01-16 17:04:30 -050065 #include "Skottie.h"
Florin Malita124d5af2017-12-31 17:02:26 -050066#endif
67
fmalita718df0a2016-07-15 10:33:29 -070068#if defined(SK_XML)
Ben Wagner6ce482a2018-03-27 10:57:43 -040069 #include "SkSVGCanvas.h"
fmalitaa48f0e32016-08-04 06:26:05 -070070 #include "SkSVGDOM.h"
fmalita718df0a2016-07-15 10:33:29 -070071 #include "SkXMLWriter.h"
72#endif
73
Robert Phillips0c4b7b12018-03-06 08:20:37 -050074#if SK_SUPPORT_GPU
Brian Salomonf865b052018-03-09 09:01:53 -050075#include "GrBackendSurface.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050076#include "GrContextPriv.h"
Brian Salomonf865b052018-03-09 09:01:53 -050077#include "GrGpu.h"
Robert Phillips0c4b7b12018-03-06 08:20:37 -050078#endif
79
halcanary7e798182015-04-14 14:06:18 -070080DEFINE_bool(multiPage, false, "For document-type backends, render the source"
81 " into multiple pages");
scroggo3ac66e92016-02-08 15:09:48 -080082DEFINE_bool(RAW_threading, true, "Allow RAW decodes to run on multiple threads?");
halcanary7e798182015-04-14 14:06:18 -070083
bsalomon3724e572016-03-30 18:56:19 -070084using sk_gpu_test::GrContextFactory;
85
mtklein748ca3b2015-01-15 10:56:12 -080086namespace DM {
87
mtklein748ca3b2015-01-15 10:56:12 -080088GMSrc::GMSrc(skiagm::GMRegistry::Factory factory) : fFactory(factory) {}
89
90Error GMSrc::draw(SkCanvas* canvas) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040091 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080092 gm->draw(canvas);
93 return "";
94}
95
96SkISize GMSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -040097 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -080098 return gm->getISize();
99}
100
101Name GMSrc::name() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400102 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
mtklein748ca3b2015-01-15 10:56:12 -0800103 return gm->getName();
104}
105
bsalomon4ee6bd82015-05-27 13:23:23 -0700106void GMSrc::modifyGrContextOptions(GrContextOptions* options) const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400107 std::unique_ptr<skiagm::GM> gm(fFactory(nullptr));
bsalomon4ee6bd82015-05-27 13:23:23 -0700108 gm->modifyGrContextOptions(options);
109}
110
mtklein748ca3b2015-01-15 10:56:12 -0800111/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
112
msarettd1227a72016-05-18 06:23:57 -0700113BRDSrc::BRDSrc(Path path, Mode mode, CodecSrc::DstColorType dstColorType, uint32_t sampleSize)
msaretta5783ae2015-09-08 15:35:32 -0700114 : fPath(path)
msaretta5783ae2015-09-08 15:35:32 -0700115 , fMode(mode)
116 , fDstColorType(dstColorType)
117 , fSampleSize(sampleSize)
118{}
119
120bool BRDSrc::veto(SinkFlags flags) const {
121 // No need to test to non-raster or indirect backends.
122 return flags.type != SinkFlags::kRaster
123 || flags.approach != SinkFlags::kDirect;
124}
125
msarettd1227a72016-05-18 06:23:57 -0700126static SkBitmapRegionDecoder* create_brd(Path path) {
bungeman38d909e2016-08-02 14:40:46 -0700127 sk_sp<SkData> encoded(SkData::MakeFromFileName(path.c_str()));
msaretta5783ae2015-09-08 15:35:32 -0700128 if (!encoded) {
Ben Wagnera93a14a2017-08-28 10:34:05 -0400129 return nullptr;
msaretta5783ae2015-09-08 15:35:32 -0700130 }
reed42943c82016-09-12 12:01:44 -0700131 return SkBitmapRegionDecoder::Create(encoded, SkBitmapRegionDecoder::kAndroidCodec_Strategy);
msaretta5783ae2015-09-08 15:35:32 -0700132}
133
Matt Sarett334df3a2016-12-15 18:17:33 -0500134static inline void alpha8_to_gray8(SkBitmap* bitmap) {
135 // Android requires kGray8 bitmaps to be tagged as kAlpha8. Here we convert
136 // them back to kGray8 so our test framework can draw them correctly.
137 if (kAlpha_8_SkColorType == bitmap->info().colorType()) {
138 SkImageInfo newInfo = bitmap->info().makeColorType(kGray_8_SkColorType)
139 .makeAlphaType(kOpaque_SkAlphaType);
140 *const_cast<SkImageInfo*>(&bitmap->info()) = newInfo;
141 }
142}
143
msaretta5783ae2015-09-08 15:35:32 -0700144Error BRDSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400145 if (canvas->imageInfo().colorSpace() &&
146 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
147 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
148 // run these tests on legacy canvases.
149 // We allow an exception for F16, since Android uses F16.
150 return Error::Nonfatal("Skip testing to color correct canvas.");
151 }
152
msaretta5783ae2015-09-08 15:35:32 -0700153 SkColorType colorType = canvas->imageInfo().colorType();
154 if (kRGB_565_SkColorType == colorType &&
155 CodecSrc::kGetFromCanvas_DstColorType != fDstColorType) {
156 return Error::Nonfatal("Testing non-565 to 565 is uninteresting.");
157 }
158 switch (fDstColorType) {
159 case CodecSrc::kGetFromCanvas_DstColorType:
160 break;
msaretta5783ae2015-09-08 15:35:32 -0700161 case CodecSrc::kGrayscale_Always_DstColorType:
162 colorType = kGray_8_SkColorType;
163 break;
msarett34e0ec42016-04-22 16:27:24 -0700164 default:
165 SkASSERT(false);
166 break;
msaretta5783ae2015-09-08 15:35:32 -0700167 }
168
Ben Wagner145dbcd2016-11-03 14:40:50 -0400169 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700170 if (nullptr == brd.get()) {
171 return Error::Nonfatal(SkStringPrintf("Could not create brd for %s.", fPath.c_str()));
172 }
173
Leon Scroggins III0118e972018-03-13 11:14:33 -0400174 auto recommendedCT = brd->computeOutputColorType(colorType);
175 if (kRGB_565_SkColorType == colorType && recommendedCT != colorType) {
176 return Error::Nonfatal("Skip decoding non-opaque to 565.");
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400177 }
Leon Scroggins III0118e972018-03-13 11:14:33 -0400178 colorType = recommendedCT;
179
180 auto colorSpace = brd->computeOutputColorSpace(colorType, nullptr);
Leon Scroggins III1dc8ecb2017-08-17 13:42:48 -0400181
msaretta5783ae2015-09-08 15:35:32 -0700182 const uint32_t width = brd->width();
183 const uint32_t height = brd->height();
184 // Visually inspecting very small output images is not necessary.
185 if ((width / fSampleSize <= 10 || height / fSampleSize <= 10) && 1 != fSampleSize) {
186 return Error::Nonfatal("Scaling very small images is uninteresting.");
187 }
188 switch (fMode) {
189 case kFullImage_Mode: {
msarett35e5d1b2015-10-27 12:50:25 -0700190 SkBitmap bitmap;
191 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(0, 0, width, height),
Leon Scroggins III0118e972018-03-13 11:14:33 -0400192 fSampleSize, colorType, false, colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800193 return "Cannot decode (full) region.";
msarett35e5d1b2015-10-27 12:50:25 -0700194 }
Matt Sarett334df3a2016-12-15 18:17:33 -0500195 alpha8_to_gray8(&bitmap);
Matt Sarett8db74f12017-06-14 13:02:05 +0000196
msarett35e5d1b2015-10-27 12:50:25 -0700197 canvas->drawBitmap(bitmap, 0, 0);
msaretta5783ae2015-09-08 15:35:32 -0700198 return "";
199 }
200 case kDivisor_Mode: {
201 const uint32_t divisor = 2;
202 if (width < divisor || height < divisor) {
mtklein9b439152015-12-09 13:02:26 -0800203 return Error::Nonfatal("Divisor is larger than image dimension.");
msaretta5783ae2015-09-08 15:35:32 -0700204 }
205
206 // Use a border to test subsets that extend outside the image.
207 // We will not allow the border to be larger than the image dimensions. Allowing
208 // these large borders causes off by one errors that indicate a problem with the
209 // test suite, not a problem with the implementation.
210 const uint32_t maxBorder = SkTMin(width, height) / (fSampleSize * divisor);
211 const uint32_t scaledBorder = SkTMin(5u, maxBorder);
212 const uint32_t unscaledBorder = scaledBorder * fSampleSize;
213
214 // We may need to clear the canvas to avoid uninitialized memory.
215 // Assume we are scaling a 780x780 image with sampleSize = 8.
216 // The output image should be 97x97.
217 // Each subset will be 390x390.
218 // Each scaled subset be 48x48.
219 // Four scaled subsets will only fill a 96x96 image.
220 // The bottom row and last column will not be touched.
221 // This is an unfortunate result of our rounding rules when scaling.
222 // Maybe we need to consider testing scaled subsets without trying to
223 // combine them to match the full scaled image? Or maybe this is the
224 // best we can do?
225 canvas->clear(0);
226
227 for (uint32_t x = 0; x < divisor; x++) {
228 for (uint32_t y = 0; y < divisor; y++) {
229 // Calculate the subset dimensions
230 uint32_t subsetWidth = width / divisor;
231 uint32_t subsetHeight = height / divisor;
232 const int left = x * subsetWidth;
233 const int top = y * subsetHeight;
234
235 // Increase the size of the last subset in each row or column, when the
236 // divisor does not divide evenly into the image dimensions
237 subsetWidth += (x + 1 == divisor) ? (width % divisor) : 0;
238 subsetHeight += (y + 1 == divisor) ? (height % divisor) : 0;
239
240 // Increase the size of the subset in order to have a border on each side
241 const int decodeLeft = left - unscaledBorder;
242 const int decodeTop = top - unscaledBorder;
243 const uint32_t decodeWidth = subsetWidth + unscaledBorder * 2;
244 const uint32_t decodeHeight = subsetHeight + unscaledBorder * 2;
msarett35e5d1b2015-10-27 12:50:25 -0700245 SkBitmap bitmap;
246 if (!brd->decodeRegion(&bitmap, nullptr, SkIRect::MakeXYWH(decodeLeft,
Matt Sarett68feef42017-04-11 09:51:32 -0400247 decodeTop, decodeWidth, decodeHeight), fSampleSize, colorType, false,
Leon Scroggins III0118e972018-03-13 11:14:33 -0400248 colorSpace)) {
mtklein9b439152015-12-09 13:02:26 -0800249 return "Cannot decode region.";
msarett35e5d1b2015-10-27 12:50:25 -0700250 }
msaretta5783ae2015-09-08 15:35:32 -0700251
Matt Sarett334df3a2016-12-15 18:17:33 -0500252 alpha8_to_gray8(&bitmap);
msarett35e5d1b2015-10-27 12:50:25 -0700253 canvas->drawBitmapRect(bitmap,
msaretta5783ae2015-09-08 15:35:32 -0700254 SkRect::MakeXYWH((SkScalar) scaledBorder, (SkScalar) scaledBorder,
255 (SkScalar) (subsetWidth / fSampleSize),
256 (SkScalar) (subsetHeight / fSampleSize)),
257 SkRect::MakeXYWH((SkScalar) (left / fSampleSize),
258 (SkScalar) (top / fSampleSize),
259 (SkScalar) (subsetWidth / fSampleSize),
260 (SkScalar) (subsetHeight / fSampleSize)),
261 nullptr);
262 }
263 }
264 return "";
265 }
266 default:
267 SkASSERT(false);
mtklein9b439152015-12-09 13:02:26 -0800268 return "Error: Should not be reached.";
msaretta5783ae2015-09-08 15:35:32 -0700269 }
270}
271
272SkISize BRDSrc::size() const {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400273 std::unique_ptr<SkBitmapRegionDecoder> brd(create_brd(fPath));
msaretta5783ae2015-09-08 15:35:32 -0700274 if (brd) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400275 return {SkTMax(1, brd->width() / (int)fSampleSize),
276 SkTMax(1, brd->height() / (int)fSampleSize)};
msaretta5783ae2015-09-08 15:35:32 -0700277 }
Hal Canaryfafe1352017-04-11 12:12:02 -0400278 return {0, 0};
msaretta5783ae2015-09-08 15:35:32 -0700279}
280
281static SkString get_scaled_name(const Path& path, float scale) {
282 return SkStringPrintf("%s_%.3f", SkOSPath::Basename(path.c_str()).c_str(), scale);
283}
284
285Name BRDSrc::name() const {
286 // We will replicate the names used by CodecSrc so that images can
287 // be compared in Gold.
288 if (1 == fSampleSize) {
289 return SkOSPath::Basename(fPath.c_str());
290 }
msarett4b0778e2015-11-13 09:59:11 -0800291 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msaretta5783ae2015-09-08 15:35:32 -0700292}
293
294/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
295
scroggo3ac66e92016-02-08 15:09:48 -0800296static bool serial_from_path_name(const SkString& path) {
297 if (!FLAGS_RAW_threading) {
298 static const char* const exts[] = {
299 "arw", "cr2", "dng", "nef", "nrw", "orf", "raf", "rw2", "pef", "srw",
300 "ARW", "CR2", "DNG", "NEF", "NRW", "ORF", "RAF", "RW2", "PEF", "SRW",
301 };
302 const char* actualExt = strrchr(path.c_str(), '.');
303 if (actualExt) {
304 actualExt++;
305 for (auto* ext : exts) {
306 if (0 == strcmp(ext, actualExt)) {
307 return true;
308 }
309 }
310 }
311 }
312 return false;
313}
314
scroggoc5560be2016-02-03 09:42:42 -0800315CodecSrc::CodecSrc(Path path, Mode mode, DstColorType dstColorType, SkAlphaType dstAlphaType,
316 float scale)
msarett438b2ad2015-04-09 12:43:10 -0700317 : fPath(path)
318 , fMode(mode)
319 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800320 , fDstAlphaType(dstAlphaType)
msarett0a242972015-06-11 14:27:27 -0700321 , fScale(scale)
scroggo3ac66e92016-02-08 15:09:48 -0800322 , fRunSerially(serial_from_path_name(path))
msarett438b2ad2015-04-09 12:43:10 -0700323{}
mtklein748ca3b2015-01-15 10:56:12 -0800324
mtklein99cab4e2015-07-31 06:43:04 -0700325bool CodecSrc::veto(SinkFlags flags) const {
msarett18976312016-03-09 14:20:58 -0800326 // Test to direct raster backends (8888 and 565).
msarettb714fb02016-01-22 14:46:42 -0800327 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
mtkleine0effd62015-07-29 06:37:28 -0700328}
scroggo9b77ddd2015-03-19 06:03:39 -0700329
msarett34e0ec42016-04-22 16:27:24 -0700330// Allows us to test decodes to non-native 8888.
msarettb1be46b2016-05-17 08:52:11 -0700331static void swap_rb_if_necessary(SkBitmap& bitmap, CodecSrc::DstColorType dstColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700332 if (CodecSrc::kNonNative8888_Always_DstColorType != dstColorType) {
333 return;
334 }
335
336 for (int y = 0; y < bitmap.height(); y++) {
337 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
338 SkOpts::RGBA_to_BGRA(row, row, bitmap.width());
339 }
340}
341
msarett9e9444c2016-02-03 12:39:10 -0800342// FIXME: Currently we cannot draw unpremultiplied sources. skbug.com/3338 and skbug.com/3339.
343// This allows us to still test unpremultiplied decodes.
msarettb1be46b2016-05-17 08:52:11 -0700344static void premultiply_if_necessary(SkBitmap& bitmap) {
msarett9e9444c2016-02-03 12:39:10 -0800345 if (kUnpremul_SkAlphaType != bitmap.alphaType()) {
346 return;
347 }
348
349 switch (bitmap.colorType()) {
Mike Klein45c16fa2017-07-18 18:15:13 -0400350 case kRGBA_F16_SkColorType: {
351 SkJumper_MemoryCtx ctx = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
352 SkRasterPipeline_<256> p;
353 p.append(SkRasterPipeline::load_f16, &ctx);
354 p.append(SkRasterPipeline::premul);
355 p.append(SkRasterPipeline::store_f16, &ctx);
356 p.run(0,0, bitmap.width(), bitmap.height());
357 }
Leon Scroggins IIIeceee042017-05-23 16:58:09 -0400358 break;
msarett9e9444c2016-02-03 12:39:10 -0800359 case kN32_SkColorType:
360 for (int y = 0; y < bitmap.height(); y++) {
361 uint32_t* row = (uint32_t*) bitmap.getAddr(0, y);
362 SkOpts::RGBA_to_rgbA(row, row, bitmap.width());
363 }
364 break;
msarett9e9444c2016-02-03 12:39:10 -0800365 default:
366 // No need to premultiply kGray or k565 outputs.
367 break;
368 }
msarette1daa482016-02-03 15:31:18 -0800369
370 // In the kIndex_8 case, the canvas won't even try to draw unless we mark the
371 // bitmap as kPremul.
372 bitmap.setAlphaType(kPremul_SkAlphaType);
msarett9e9444c2016-02-03 12:39:10 -0800373}
374
msarettb1be46b2016-05-17 08:52:11 -0700375static bool get_decode_info(SkImageInfo* decodeInfo, SkColorType canvasColorType,
scroggoba584892016-05-20 13:56:13 -0700376 CodecSrc::DstColorType dstColorType, SkAlphaType dstAlphaType) {
msarett3d9d7a72015-10-21 10:27:10 -0700377 switch (dstColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700378 case CodecSrc::kGrayscale_Always_DstColorType:
scroggo1a361922016-05-20 14:27:16 -0700379 if (kRGB_565_SkColorType == canvasColorType) {
msarett3d9d7a72015-10-21 10:27:10 -0700380 return false;
381 }
scroggoc5560be2016-02-03 09:42:42 -0800382 *decodeInfo = decodeInfo->makeColorType(kGray_8_SkColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700383 break;
msarett34e0ec42016-04-22 16:27:24 -0700384 case CodecSrc::kNonNative8888_Always_DstColorType:
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400385 if (kRGB_565_SkColorType == canvasColorType
386 || kRGBA_F16_SkColorType == canvasColorType) {
msarett34e0ec42016-04-22 16:27:24 -0700387 return false;
388 }
389#ifdef SK_PMCOLOR_IS_RGBA
390 *decodeInfo = decodeInfo->makeColorType(kBGRA_8888_SkColorType);
391#else
392 *decodeInfo = decodeInfo->makeColorType(kRGBA_8888_SkColorType);
393#endif
394 break;
msarett3d9d7a72015-10-21 10:27:10 -0700395 default:
msarett55f7bdd2016-02-16 13:24:54 -0800396 if (kRGB_565_SkColorType == canvasColorType &&
397 kOpaque_SkAlphaType != decodeInfo->alphaType()) {
398 return false;
399 }
Matt Sarett09a1c082017-02-01 15:34:22 -0800400
401 if (kRGBA_F16_SkColorType == canvasColorType) {
Brian Osman36703d92017-12-12 14:09:31 -0500402 sk_sp<SkColorSpace> linearSpace = decodeInfo->colorSpace()->makeLinearGamma();
Matt Sarett09a1c082017-02-01 15:34:22 -0800403 *decodeInfo = decodeInfo->makeColorSpace(std::move(linearSpace));
404 }
405
scroggoc5560be2016-02-03 09:42:42 -0800406 *decodeInfo = decodeInfo->makeColorType(canvasColorType);
msarett3d9d7a72015-10-21 10:27:10 -0700407 break;
408 }
409
scroggoba584892016-05-20 13:56:13 -0700410 *decodeInfo = decodeInfo->makeAlphaType(dstAlphaType);
msarett3d9d7a72015-10-21 10:27:10 -0700411 return true;
412}
413
msarettb1be46b2016-05-17 08:52:11 -0700414static void draw_to_canvas(SkCanvas* canvas, const SkImageInfo& info, void* pixels, size_t rowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000415 CodecSrc::DstColorType dstColorType,
msarettb1be46b2016-05-17 08:52:11 -0700416 SkScalar left = 0, SkScalar top = 0) {
msarettb1be46b2016-05-17 08:52:11 -0700417 SkBitmap bitmap;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000418 bitmap.installPixels(info, pixels, rowBytes);
msarettb1be46b2016-05-17 08:52:11 -0700419 premultiply_if_necessary(bitmap);
420 swap_rb_if_necessary(bitmap, dstColorType);
421 canvas->drawBitmap(bitmap, left, top);
Yuqian Licb312482018-04-27 15:52:40 -0400422 canvas->flush();
msarettb1be46b2016-05-17 08:52:11 -0700423}
424
Matt Sarettf485cf92017-05-26 08:58:03 -0400425// For codec srcs, we want the "draw" step to be a memcpy. Any interesting color space or
426// color format conversions should be performed by the codec. Sometimes the output of the
427// decode will be in an interesting color space. On our srgb and f16 backends, we need to
428// "pretend" that the color space is standard sRGB to avoid triggering color conversion
429// at draw time.
430static void set_bitmap_color_space(SkImageInfo* info) {
431 if (kRGBA_F16_SkColorType == info->colorType()) {
432 *info = info->makeColorSpace(SkColorSpace::MakeSRGBLinear());
433 } else {
434 *info = info->makeColorSpace(SkColorSpace::MakeSRGB());
435 }
436}
437
mtkleine0effd62015-07-29 06:37:28 -0700438Error CodecSrc::draw(SkCanvas* canvas) const {
bungeman38d909e2016-08-02 14:40:46 -0700439 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
mtklein748ca3b2015-01-15 10:56:12 -0800440 if (!encoded) {
441 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
442 }
msarettb714fb02016-01-22 14:46:42 -0800443
Mike Reedede7bac2017-07-23 15:30:02 -0400444 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett9e707a02015-09-01 14:57:57 -0700445 if (nullptr == codec.get()) {
446 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
scroggo9b77ddd2015-03-19 06:03:39 -0700447 }
448
scroggoba584892016-05-20 13:56:13 -0700449 SkImageInfo decodeInfo = codec->getInfo();
450 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
451 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800452 return Error::Nonfatal("Skipping uninteresting test.");
msarett438b2ad2015-04-09 12:43:10 -0700453 }
454
msarett0a242972015-06-11 14:27:27 -0700455 // Try to scale the image if it is desired
456 SkISize size = codec->getScaledDimensions(fScale);
457 if (size == decodeInfo.dimensions() && 1.0f != fScale) {
458 return Error::Nonfatal("Test without scaling is uninteresting.");
459 }
msarettb32758a2015-08-18 13:22:46 -0700460
461 // Visually inspecting very small output images is not necessary. We will
462 // cover these cases in unit testing.
463 if ((size.width() <= 10 || size.height() <= 10) && 1.0f != fScale) {
464 return Error::Nonfatal("Scaling very small images is uninteresting.");
465 }
msarett0a242972015-06-11 14:27:27 -0700466 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
467
Mike Reed7fcfb622018-02-09 13:26:46 -0500468 const int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700469 const size_t rowBytes = size.width() * bpp;
Mike Reedf0ffb892017-10-03 14:47:21 -0400470 const size_t safeSize = decodeInfo.computeByteSize(rowBytes);
scroggo19b91532016-10-24 09:03:26 -0700471 SkAutoMalloc pixels(safeSize);
msarett438b2ad2015-04-09 12:43:10 -0700472
msarettbb25b532016-01-13 09:31:39 -0800473 SkCodec::Options options;
Matt Saretta40d9c82017-05-19 15:21:05 -0400474 options.fPremulBehavior = canvas->imageInfo().colorSpace() ?
475 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
msarettbb25b532016-01-13 09:31:39 -0800476 if (kCodecZeroInit_Mode == fMode) {
msarettb1be46b2016-05-17 08:52:11 -0700477 memset(pixels.get(), 0, size.height() * rowBytes);
msarettbb25b532016-01-13 09:31:39 -0800478 options.fZeroInitialized = SkCodec::kYes_ZeroInitialized;
479 }
msarett34e0ec42016-04-22 16:27:24 -0700480
481 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400482 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700483 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
484 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
485 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
486 }
scroggo9b77ddd2015-03-19 06:03:39 -0700487
scroggo9c59ebc2015-03-25 13:48:49 -0700488 switch (fMode) {
scroggo19b91532016-10-24 09:03:26 -0700489 case kAnimated_Mode: {
490 std::vector<SkCodec::FrameInfo> frameInfos = codec->getFrameInfo();
491 if (frameInfos.size() <= 1) {
492 return SkStringPrintf("%s is not an animated image.", fPath.c_str());
493 }
494
scroggo90e971a2016-10-25 06:11:01 -0700495 // As in CodecSrc::size(), compute a roughly square grid to draw the frames
496 // into. "factor" is the number of frames to draw on one row. There will be
497 // up to "factor" rows as well.
498 const float root = sqrt((float) frameInfos.size());
499 const int factor = sk_float_ceil2int(root);
500
scroggo19b91532016-10-24 09:03:26 -0700501 // Used to cache a frame that future frames will depend on.
502 SkAutoMalloc priorFramePixels;
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400503 int cachedFrame = SkCodec::kNone;
504 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
scroggo19b91532016-10-24 09:03:26 -0700505 options.fFrameIndex = i;
506 // Check for a prior frame
Leon Scroggins III249b8e32017-04-17 12:46:33 -0400507 const int reqFrame = frameInfos[i].fRequiredFrame;
scroggo19b91532016-10-24 09:03:26 -0700508 if (reqFrame != SkCodec::kNone && reqFrame == cachedFrame
509 && priorFramePixels.get()) {
510 // Copy into pixels
511 memcpy(pixels.get(), priorFramePixels.get(), safeSize);
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400512 options.fPriorFrame = reqFrame;
scroggo19b91532016-10-24 09:03:26 -0700513 } else {
Leon Scroggins III33deb7e2017-06-07 12:31:51 -0400514 options.fPriorFrame = SkCodec::kNone;
scroggo19b91532016-10-24 09:03:26 -0700515 }
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500516 SkCodec::Result result = codec->getPixels(decodeInfo, pixels.get(),
Leon Scroggins571b30f2017-07-11 17:35:31 +0000517 rowBytes, &options);
Leon Scroggins III3fc97d72016-12-09 16:39:33 -0500518 if (SkCodec::kInvalidInput == result && i > 0) {
519 // Some of our test images have truncated later frames. Treat that
520 // the same as incomplete.
521 result = SkCodec::kIncompleteInput;
522 }
scroggo19b91532016-10-24 09:03:26 -0700523 switch (result) {
524 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400525 case SkCodec::kErrorInInput:
scroggo90e971a2016-10-25 06:11:01 -0700526 case SkCodec::kIncompleteInput: {
Leon Scroggins III557fbbe2017-05-23 09:37:21 -0400527 // If the next frame depends on this one, store it in priorFrame.
528 // It is possible that we may discard a frame that future frames depend on,
529 // but the codec will simply redecode the discarded frame.
530 // Do this before calling draw_to_canvas, which premultiplies in place. If
531 // we're decoding to unpremul, we want to pass the unmodified frame to the
532 // codec for decoding the next frame.
533 if (static_cast<size_t>(i+1) < frameInfos.size()
534 && frameInfos[i+1].fRequiredFrame == i) {
535 memcpy(priorFramePixels.reset(safeSize), pixels.get(), safeSize);
536 cachedFrame = i;
537 }
538
scroggo90e971a2016-10-25 06:11:01 -0700539 SkAutoCanvasRestore acr(canvas, true);
540 const int xTranslate = (i % factor) * decodeInfo.width();
541 const int yTranslate = (i / factor) * decodeInfo.height();
542 canvas->translate(SkIntToScalar(xTranslate), SkIntToScalar(yTranslate));
Leon Scroggins571b30f2017-07-11 17:35:31 +0000543 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
Leon Scroggins III674a1842017-07-06 12:26:09 -0400544 if (result != SkCodec::kSuccess) {
scroggo19b91532016-10-24 09:03:26 -0700545 return "";
546 }
547 break;
scroggo90e971a2016-10-25 06:11:01 -0700548 }
scroggo53f63b62016-10-27 08:29:13 -0700549 case SkCodec::kInvalidConversion:
Mike Reed304a07c2017-07-12 15:10:28 -0400550 if (i > 0 && (decodeInfo.colorType() == kRGB_565_SkColorType)) {
scroggo53f63b62016-10-27 08:29:13 -0700551 return Error::Nonfatal(SkStringPrintf(
Mike Reed304a07c2017-07-12 15:10:28 -0400552 "Cannot decode frame %i to 565 (%s).", i, fPath.c_str()));
scroggo53f63b62016-10-27 08:29:13 -0700553 }
554 // Fall through.
scroggo19b91532016-10-24 09:03:26 -0700555 default:
556 return SkStringPrintf("Couldn't getPixels for frame %i in %s.",
557 i, fPath.c_str());
558 }
scroggo19b91532016-10-24 09:03:26 -0700559 }
560 break;
561 }
msarettbb25b532016-01-13 09:31:39 -0800562 case kCodecZeroInit_Mode:
msarett9e707a02015-09-01 14:57:57 -0700563 case kCodec_Mode: {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000564 switch (codec->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggoeb602a52015-07-09 08:16:03 -0700565 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400566 // We consider these to be valid, since we should still decode what is
scroggo9c59ebc2015-03-25 13:48:49 -0700567 // available.
Leon Scroggins III674a1842017-07-06 12:26:09 -0400568 case SkCodec::kErrorInInput:
scroggoeb602a52015-07-09 08:16:03 -0700569 case SkCodec::kIncompleteInput:
scroggo9c59ebc2015-03-25 13:48:49 -0700570 break;
scroggo9c59ebc2015-03-25 13:48:49 -0700571 default:
572 // Everything else is considered a failure.
573 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
574 }
msarettb1be46b2016-05-17 08:52:11 -0700575
Leon Scroggins571b30f2017-07-11 17:35:31 +0000576 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggo9c59ebc2015-03-25 13:48:49 -0700577 break;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700578 }
scroggo9c59ebc2015-03-25 13:48:49 -0700579 case kScanline_Mode: {
scroggod8d68552016-06-06 11:26:17 -0700580 void* dst = pixels.get();
581 uint32_t height = decodeInfo.height();
scroggo19b91532016-10-24 09:03:26 -0700582 const bool useIncremental = [this]() {
583 auto exts = { "png", "PNG", "gif", "GIF" };
584 for (auto ext : exts) {
585 if (fPath.endsWith(ext)) {
586 return true;
587 }
588 }
589 return false;
590 }();
591 // ico may use the old scanline method or the new one, depending on whether it
592 // internally holds a bmp or a png.
scroggo8e6c7ad2016-09-16 08:20:38 -0700593 const bool ico = fPath.endsWith("ico");
scroggo19b91532016-10-24 09:03:26 -0700594 bool useOldScanlineMethod = !useIncremental && !ico;
595 if (useIncremental || ico) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700596 if (SkCodec::kSuccess == codec->startIncrementalDecode(decodeInfo, dst,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000597 rowBytes, &options)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700598 int rowsDecoded;
Leon Scroggins III674a1842017-07-06 12:26:09 -0400599 auto result = codec->incrementalDecode(&rowsDecoded);
600 if (SkCodec::kIncompleteInput == result || SkCodec::kErrorInInput == result) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700601 codec->fillIncompleteImage(decodeInfo, dst, rowBytes,
602 SkCodec::kNo_ZeroInitialized, height,
603 rowsDecoded);
scroggo6fb23912016-06-02 14:16:43 -0700604 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700605 } else {
scroggo19b91532016-10-24 09:03:26 -0700606 if (useIncremental) {
607 // Error: These should support incremental decode.
scroggo8e6c7ad2016-09-16 08:20:38 -0700608 return "Could not start incremental decode";
609 }
610 // Otherwise, this is an ICO. Since incremental failed, it must contain a BMP,
611 // which should work via startScanlineDecode
612 useOldScanlineMethod = true;
613 }
614 }
615
616 if (useOldScanlineMethod) {
Leon Scroggins571b30f2017-07-11 17:35:31 +0000617 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700618 return "Could not start scanline decoder";
619 }
620
Brian Osmanea176c62018-04-06 15:28:23 -0400621 // We do not need to check the return value. On an incomplete
622 // image, memory will be filled with a default value.
623 codec->getScanlines(dst, height, rowBytes);
msarett10522ff2015-09-07 08:54:01 -0700624 }
625
Leon Scroggins571b30f2017-07-11 17:35:31 +0000626 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer97002062015-05-27 12:36:10 -0700627 break;
628 }
msarett0a242972015-06-11 14:27:27 -0700629 case kStripe_Mode: {
630 const int height = decodeInfo.height();
631 // This value is chosen arbitrarily. We exercise more cases by choosing a value that
632 // does not align with image blocks.
633 const int stripeHeight = 37;
634 const int numStripes = (height + stripeHeight - 1) / stripeHeight;
msarettb1be46b2016-05-17 08:52:11 -0700635 void* dst = pixels.get();
msarett0a242972015-06-11 14:27:27 -0700636
637 // Decode odd stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000638 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarettb65e6042016-02-23 05:37:25 -0800639 return "Could not start scanline decoder";
640 }
641
642 // This mode was designed to test the new skip scanlines API in libjpeg-turbo.
643 // Jpegs have kTopDown_SkScanlineOrder, and at this time, it is not interesting
644 // to run this test for image types that do not have this scanline ordering.
scroggo12e2f502016-05-16 09:04:18 -0700645 // We only run this on Jpeg, which is always kTopDown.
646 SkASSERT(SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder());
msarette6dd0042015-10-09 11:07:34 -0700647
msarett0a242972015-06-11 14:27:27 -0700648 for (int i = 0; i < numStripes; i += 2) {
649 // Skip a stripe
650 const int linesToSkip = SkTMin(stripeHeight, height - i * stripeHeight);
msarette6dd0042015-10-09 11:07:34 -0700651 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700652
653 // Read a stripe
654 const int startY = (i + 1) * stripeHeight;
655 const int linesToRead = SkTMin(stripeHeight, height - startY);
656 if (linesToRead > 0) {
msarettb1be46b2016-05-17 08:52:11 -0700657 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
658 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700659 }
660 }
661
662 // Decode even stripes
Leon Scroggins571b30f2017-07-11 17:35:31 +0000663 const SkCodec::Result startResult = codec->startScanlineDecode(decodeInfo);
scroggo1c005e42015-08-04 09:24:45 -0700664 if (SkCodec::kSuccess != startResult) {
665 return "Failed to restart scanline decoder with same parameters.";
msarett0a242972015-06-11 14:27:27 -0700666 }
667 for (int i = 0; i < numStripes; i += 2) {
668 // Read a stripe
669 const int startY = i * stripeHeight;
670 const int linesToRead = SkTMin(stripeHeight, height - startY);
msarettb1be46b2016-05-17 08:52:11 -0700671 codec->getScanlines(SkTAddOffset<void>(dst, rowBytes * startY), linesToRead,
672 rowBytes);
msarett0a242972015-06-11 14:27:27 -0700673
674 // Skip a stripe
msarettf6db27e2015-06-12 09:34:04 -0700675 const int linesToSkip = SkTMin(stripeHeight, height - (i + 1) * stripeHeight);
676 if (linesToSkip > 0) {
msarette6dd0042015-10-09 11:07:34 -0700677 codec->skipScanlines(linesToSkip);
msarett0a242972015-06-11 14:27:27 -0700678 }
679 }
msarettb1be46b2016-05-17 08:52:11 -0700680
Leon Scroggins571b30f2017-07-11 17:35:31 +0000681 draw_to_canvas(canvas, bitmapInfo, dst, rowBytes, fDstColorType);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700682 break;
msarett0a242972015-06-11 14:27:27 -0700683 }
msarett91c22b22016-02-22 12:27:46 -0800684 case kCroppedScanline_Mode: {
685 const int width = decodeInfo.width();
686 const int height = decodeInfo.height();
687 // This value is chosen because, as we move across the image, it will sometimes
688 // align with the jpeg block sizes and it will sometimes not. This allows us
689 // to test interestingly different code paths in the implementation.
690 const int tileSize = 36;
msarett91c22b22016-02-22 12:27:46 -0800691 SkIRect subset;
692 for (int x = 0; x < width; x += tileSize) {
693 subset = SkIRect::MakeXYWH(x, 0, SkTMin(tileSize, width - x), height);
Matt Saretta40d9c82017-05-19 15:21:05 -0400694 options.fSubset = &subset;
Leon Scroggins571b30f2017-07-11 17:35:31 +0000695 if (SkCodec::kSuccess != codec->startScanlineDecode(decodeInfo, &options)) {
msarett91c22b22016-02-22 12:27:46 -0800696 return "Could not start scanline decoder.";
697 }
698
msarettb1be46b2016-05-17 08:52:11 -0700699 codec->getScanlines(SkTAddOffset<void>(pixels.get(), x * bpp), height, rowBytes);
msarett91c22b22016-02-22 12:27:46 -0800700 }
701
Leon Scroggins571b30f2017-07-11 17:35:31 +0000702 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
msarett91c22b22016-02-22 12:27:46 -0800703 break;
704 }
scroggob636b452015-07-22 07:16:20 -0700705 case kSubset_Mode: {
706 // Arbitrarily choose a divisor.
707 int divisor = 2;
708 // Total width/height of the image.
709 const int W = codec->getInfo().width();
710 const int H = codec->getInfo().height();
711 if (divisor > W || divisor > H) {
712 return Error::Nonfatal(SkStringPrintf("Cannot codec subset: divisor %d is too big "
713 "for %s with dimensions (%d x %d)", divisor,
714 fPath.c_str(), W, H));
715 }
716 // subset dimensions
717 // SkWebpCodec, the only one that supports subsets, requires even top/left boundaries.
718 const int w = SkAlign2(W / divisor);
719 const int h = SkAlign2(H / divisor);
720 SkIRect subset;
Matt Saretta40d9c82017-05-19 15:21:05 -0400721 options.fSubset = &subset;
scroggob636b452015-07-22 07:16:20 -0700722 SkBitmap subsetBm;
723 // We will reuse pixel memory from bitmap.
msarettb1be46b2016-05-17 08:52:11 -0700724 void* dst = pixels.get();
scroggob636b452015-07-22 07:16:20 -0700725 // Keep track of left and top (for drawing subsetBm into canvas). We could use
726 // fScale * x and fScale * y, but we want integers such that the next subset will start
727 // where the last one ended. So we'll add decodeInfo.width() and height().
728 int left = 0;
729 for (int x = 0; x < W; x += w) {
730 int top = 0;
731 for (int y = 0; y < H; y+= h) {
732 // Do not make the subset go off the edge of the image.
733 const int preScaleW = SkTMin(w, W - x);
734 const int preScaleH = SkTMin(h, H - y);
735 subset.setXYWH(x, y, preScaleW, preScaleH);
736 // And scale
737 // FIXME: Should we have a version of getScaledDimensions that takes a subset
738 // into account?
msarettc7eb4902016-04-25 07:04:58 -0700739 const int scaledW = SkTMax(1, SkScalarRoundToInt(preScaleW * fScale));
740 const int scaledH = SkTMax(1, SkScalarRoundToInt(preScaleH * fScale));
741 decodeInfo = decodeInfo.makeWH(scaledW, scaledH);
742 SkImageInfo subsetBitmapInfo = bitmapInfo.makeWH(scaledW, scaledH);
msarettb1be46b2016-05-17 08:52:11 -0700743 size_t subsetRowBytes = subsetBitmapInfo.minRowBytes();
744 const SkCodec::Result result = codec->getPixels(decodeInfo, dst, subsetRowBytes,
Leon Scroggins571b30f2017-07-11 17:35:31 +0000745 &options);
scroggob636b452015-07-22 07:16:20 -0700746 switch (result) {
747 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400748 case SkCodec::kErrorInInput:
scroggob636b452015-07-22 07:16:20 -0700749 case SkCodec::kIncompleteInput:
750 break;
scroggob636b452015-07-22 07:16:20 -0700751 default:
752 return SkStringPrintf("subset codec failed to decode (%d, %d, %d, %d) "
753 "from %s with dimensions (%d x %d)\t error %d",
754 x, y, decodeInfo.width(), decodeInfo.height(),
755 fPath.c_str(), W, H, result);
756 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000757 draw_to_canvas(canvas, subsetBitmapInfo, dst, subsetRowBytes, fDstColorType,
758 SkIntToScalar(left), SkIntToScalar(top));
msarettb1be46b2016-05-17 08:52:11 -0700759
scroggob636b452015-07-22 07:16:20 -0700760 // translate by the scaled height.
761 top += decodeInfo.height();
762 }
763 // translate by the scaled width.
764 left += decodeInfo.width();
765 }
766 return "";
767 }
msarettb714fb02016-01-22 14:46:42 -0800768 default:
769 SkASSERT(false);
770 return "Invalid fMode";
scroggo9b77ddd2015-03-19 06:03:39 -0700771 }
scroggo9c59ebc2015-03-25 13:48:49 -0700772 return "";
scroggo9b77ddd2015-03-19 06:03:39 -0700773}
774
775SkISize CodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700776 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400777 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
scroggo7fac5af2015-09-30 11:33:12 -0700778 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400779 return {0, 0};
scroggo7fac5af2015-09-30 11:33:12 -0700780 }
scroggo19b91532016-10-24 09:03:26 -0700781
782 auto imageSize = codec->getScaledDimensions(fScale);
783 if (fMode == kAnimated_Mode) {
scroggo90e971a2016-10-25 06:11:01 -0700784 // We'll draw one of each frame, so make it big enough to hold them all
785 // in a grid. The grid will be roughly square, with "factor" frames per
786 // row and up to "factor" rows.
scroggo19b91532016-10-24 09:03:26 -0700787 const size_t count = codec->getFrameInfo().size();
scroggo90e971a2016-10-25 06:11:01 -0700788 const float root = sqrt((float) count);
789 const int factor = sk_float_ceil2int(root);
790 imageSize.fWidth = imageSize.fWidth * factor;
791 imageSize.fHeight = imageSize.fHeight * sk_float_ceil2int((float) count / (float) factor);
scroggo19b91532016-10-24 09:03:26 -0700792 }
793 return imageSize;
scroggo9b77ddd2015-03-19 06:03:39 -0700794}
795
796Name CodecSrc::name() const {
msarett0a242972015-06-11 14:27:27 -0700797 if (1.0f == fScale) {
scroggo6e8c68e2016-10-24 13:48:49 -0700798 Name name = SkOSPath::Basename(fPath.c_str());
799 if (fMode == kAnimated_Mode) {
800 name.append("_animated");
801 }
802 return name;
msarett0a242972015-06-11 14:27:27 -0700803 }
scroggo6e8c68e2016-10-24 13:48:49 -0700804 SkASSERT(fMode != kAnimated_Mode);
msaretta5783ae2015-09-08 15:35:32 -0700805 return get_scaled_name(fPath, fScale);
scroggo9b77ddd2015-03-19 06:03:39 -0700806}
807
808/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
809
scroggof8dc9df2016-05-16 09:04:13 -0700810AndroidCodecSrc::AndroidCodecSrc(Path path, CodecSrc::DstColorType dstColorType,
scroggoc5560be2016-02-03 09:42:42 -0800811 SkAlphaType dstAlphaType, int sampleSize)
msarett3d9d7a72015-10-21 10:27:10 -0700812 : fPath(path)
msarett3d9d7a72015-10-21 10:27:10 -0700813 , fDstColorType(dstColorType)
scroggoc5560be2016-02-03 09:42:42 -0800814 , fDstAlphaType(dstAlphaType)
msarett3d9d7a72015-10-21 10:27:10 -0700815 , fSampleSize(sampleSize)
scroggo3ac66e92016-02-08 15:09:48 -0800816 , fRunSerially(serial_from_path_name(path))
msarett3d9d7a72015-10-21 10:27:10 -0700817{}
818
819bool AndroidCodecSrc::veto(SinkFlags flags) const {
820 // No need to test decoding to non-raster or indirect backend.
msarett3d9d7a72015-10-21 10:27:10 -0700821 return flags.type != SinkFlags::kRaster
822 || flags.approach != SinkFlags::kDirect;
823}
824
825Error AndroidCodecSrc::draw(SkCanvas* canvas) const {
Matt Saretta40d9c82017-05-19 15:21:05 -0400826 if (canvas->imageInfo().colorSpace() &&
827 kRGBA_F16_SkColorType != canvas->imageInfo().colorType()) {
828 // SkAndroidCodec uses legacy premultiplication and blending. Therefore, we only
829 // run these tests on legacy canvases.
830 // We allow an exception for F16, since Android uses F16.
831 return Error::Nonfatal("Skip testing to color correct canvas.");
832 }
833
bungeman38d909e2016-08-02 14:40:46 -0700834 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett3d9d7a72015-10-21 10:27:10 -0700835 if (!encoded) {
836 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
837 }
Mike Reedede7bac2017-07-23 15:30:02 -0400838 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
839 if (nullptr == codec) {
msarett3d9d7a72015-10-21 10:27:10 -0700840 return SkStringPrintf("Couldn't create android codec for %s.", fPath.c_str());
841 }
842
scroggoba584892016-05-20 13:56:13 -0700843 SkImageInfo decodeInfo = codec->getInfo();
844 if (!get_decode_info(&decodeInfo, canvas->imageInfo().colorType(), fDstColorType,
845 fDstAlphaType)) {
Matt Sarettea518f02017-02-03 11:58:59 -0800846 return Error::Nonfatal("Skipping uninteresting test.");
msarett3d9d7a72015-10-21 10:27:10 -0700847 }
848
849 // Scale the image if it is desired.
850 SkISize size = codec->getSampledDimensions(fSampleSize);
851
852 // Visually inspecting very small output images is not necessary. We will
853 // cover these cases in unit testing.
854 if ((size.width() <= 10 || size.height() <= 10) && 1 != fSampleSize) {
855 return Error::Nonfatal("Scaling very small images is uninteresting.");
856 }
857 decodeInfo = decodeInfo.makeWH(size.width(), size.height());
858
Mike Reed7fcfb622018-02-09 13:26:46 -0500859 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700860 size_t rowBytes = size.width() * bpp;
861 SkAutoMalloc pixels(size.height() * rowBytes);
msarett3d9d7a72015-10-21 10:27:10 -0700862
863 SkBitmap bitmap;
msarett34e0ec42016-04-22 16:27:24 -0700864 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -0400865 set_bitmap_color_space(&bitmapInfo);
msarett34e0ec42016-04-22 16:27:24 -0700866 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
867 kBGRA_8888_SkColorType == decodeInfo.colorType()) {
868 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
869 }
msarett3d9d7a72015-10-21 10:27:10 -0700870
871 // Create options for the codec.
872 SkAndroidCodec::AndroidOptions options;
msarett3d9d7a72015-10-21 10:27:10 -0700873 options.fSampleSize = fSampleSize;
874
msarettb1be46b2016-05-17 08:52:11 -0700875 switch (codec->getAndroidPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
scroggof8dc9df2016-05-16 09:04:13 -0700876 case SkCodec::kSuccess:
Leon Scroggins III674a1842017-07-06 12:26:09 -0400877 case SkCodec::kErrorInInput:
scroggof8dc9df2016-05-16 09:04:13 -0700878 case SkCodec::kIncompleteInput:
879 break;
msarett3d9d7a72015-10-21 10:27:10 -0700880 default:
scroggof8dc9df2016-05-16 09:04:13 -0700881 return SkStringPrintf("Couldn't getPixels %s.", fPath.c_str());
msarett3d9d7a72015-10-21 10:27:10 -0700882 }
Leon Scroggins571b30f2017-07-11 17:35:31 +0000883 draw_to_canvas(canvas, bitmapInfo, pixels.get(), rowBytes, fDstColorType);
scroggof8dc9df2016-05-16 09:04:13 -0700884 return "";
msarett3d9d7a72015-10-21 10:27:10 -0700885}
886
887SkISize AndroidCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -0700888 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -0400889 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(encoded));
msarett3d9d7a72015-10-21 10:27:10 -0700890 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -0400891 return {0, 0};
msarett3d9d7a72015-10-21 10:27:10 -0700892 }
893 return codec->getSampledDimensions(fSampleSize);
894}
895
896Name AndroidCodecSrc::name() const {
897 // We will replicate the names used by CodecSrc so that images can
898 // be compared in Gold.
899 if (1 == fSampleSize) {
900 return SkOSPath::Basename(fPath.c_str());
901 }
msarett4b0778e2015-11-13 09:59:11 -0800902 return get_scaled_name(fPath, 1.0f / (float) fSampleSize);
msarett3d9d7a72015-10-21 10:27:10 -0700903}
904
905/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
906
msarett18976312016-03-09 14:20:58 -0800907ImageGenSrc::ImageGenSrc(Path path, Mode mode, SkAlphaType alphaType, bool isGpu)
908 : fPath(path)
909 , fMode(mode)
910 , fDstAlphaType(alphaType)
911 , fIsGpu(isGpu)
912 , fRunSerially(serial_from_path_name(path))
913{}
914
915bool ImageGenSrc::veto(SinkFlags flags) const {
916 if (fIsGpu) {
Brian Salomonbd7c5512017-03-07 09:08:36 -0500917 // MSAA runs tend to run out of memory and tests the same code paths as regular gpu configs.
918 return flags.type != SinkFlags::kGPU || flags.approach != SinkFlags::kDirect ||
919 flags.multisampled == SinkFlags::kMultisampled;
msarett18976312016-03-09 14:20:58 -0800920 }
921
922 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
923}
924
925Error ImageGenSrc::draw(SkCanvas* canvas) const {
926 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
927 return Error::Nonfatal("Uninteresting to test image generator to 565.");
928 }
929
bungeman38d909e2016-08-02 14:40:46 -0700930 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett18976312016-03-09 14:20:58 -0800931 if (!encoded) {
932 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
933 }
934
msarettfc0b6d12016-03-17 13:50:17 -0700935#if defined(SK_BUILD_FOR_WIN)
936 // Initialize COM in order to test with WIC.
937 SkAutoCoInitialize com;
938 if (!com.succeeded()) {
939 return "Could not initialize COM.";
940 }
941#endif
942
Ben Wagner145dbcd2016-11-03 14:40:50 -0400943 std::unique_ptr<SkImageGenerator> gen(nullptr);
msarett18976312016-03-09 14:20:58 -0800944 switch (fMode) {
945 case kCodec_Mode:
Mike Reed185130c2017-02-15 15:14:16 -0500946 gen = SkCodecImageGenerator::MakeFromEncodedCodec(encoded);
msarett18976312016-03-09 14:20:58 -0800947 if (!gen) {
948 return "Could not create codec image generator.";
949 }
950 break;
msarettfc0b6d12016-03-17 13:50:17 -0700951 case kPlatform_Mode: {
msarett18976312016-03-09 14:20:58 -0800952#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
Leon Scroggins III0cbc10f2017-10-30 09:07:53 -0400953 gen = SkImageGeneratorCG::MakeFromEncodedCG(encoded);
msarettfc0b6d12016-03-17 13:50:17 -0700954#elif defined(SK_BUILD_FOR_WIN)
bungeman38d909e2016-08-02 14:40:46 -0700955 gen.reset(SkImageGeneratorWIC::NewFromEncodedWIC(encoded.get()));
msarettfc0b6d12016-03-17 13:50:17 -0700956#endif
957
msarett18976312016-03-09 14:20:58 -0800958 if (!gen) {
msarettfc0b6d12016-03-17 13:50:17 -0700959 return "Could not create platform image generator.";
msarett18976312016-03-09 14:20:58 -0800960 }
961 break;
msarettfc0b6d12016-03-17 13:50:17 -0700962 }
msarett18976312016-03-09 14:20:58 -0800963 default:
964 SkASSERT(false);
965 return "Invalid image generator mode";
966 }
967
968 // Test deferred decoding path on GPU
969 if (fIsGpu) {
Mike Reed185130c2017-02-15 15:14:16 -0500970 sk_sp<SkImage> image(SkImage::MakeFromGenerator(std::move(gen), nullptr));
msarett18976312016-03-09 14:20:58 -0800971 if (!image) {
972 return "Could not create image from codec image generator.";
973 }
974 canvas->drawImage(image, 0, 0);
975 return "";
976 }
mtklein343a63d2016-03-22 11:46:53 -0700977
msarett18976312016-03-09 14:20:58 -0800978 // Test various color and alpha types on CPU
979 SkImageInfo decodeInfo = gen->getInfo().makeAlphaType(fDstAlphaType);
mtklein343a63d2016-03-22 11:46:53 -0700980
Matt Saretta40d9c82017-05-19 15:21:05 -0400981 SkImageGenerator::Options options;
982 options.fBehavior = canvas->imageInfo().colorSpace() ?
983 SkTransferFunctionBehavior::kRespect : SkTransferFunctionBehavior::kIgnore;
984
Mike Reed7fcfb622018-02-09 13:26:46 -0500985 int bpp = decodeInfo.bytesPerPixel();
msarettb1be46b2016-05-17 08:52:11 -0700986 size_t rowBytes = decodeInfo.width() * bpp;
987 SkAutoMalloc pixels(decodeInfo.height() * rowBytes);
Matt Saretta40d9c82017-05-19 15:21:05 -0400988 if (!gen->getPixels(decodeInfo, pixels.get(), rowBytes, &options)) {
Matt Sarett05cb4c32017-03-02 12:07:46 -0500989 SkString err =
990 SkStringPrintf("Image generator could not getPixels() for %s\n", fPath.c_str());
991
992#if defined(SK_BUILD_FOR_WIN)
993 if (kPlatform_Mode == fMode) {
994 // Do not issue a fatal error for WIC flakiness.
995 return Error::Nonfatal(err);
996 }
997#endif
998
999 return err;
msarett18976312016-03-09 14:20:58 -08001000 }
1001
Matt Sarettf485cf92017-05-26 08:58:03 -04001002 set_bitmap_color_space(&decodeInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +00001003 draw_to_canvas(canvas, decodeInfo, pixels.get(), rowBytes,
msarettb1be46b2016-05-17 08:52:11 -07001004 CodecSrc::kGetFromCanvas_DstColorType);
msarett18976312016-03-09 14:20:58 -08001005 return "";
1006}
1007
1008SkISize ImageGenSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001009 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001010 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett18976312016-03-09 14:20:58 -08001011 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001012 return {0, 0};
msarett18976312016-03-09 14:20:58 -08001013 }
1014 return codec->getInfo().dimensions();
1015}
1016
1017Name ImageGenSrc::name() const {
1018 return SkOSPath::Basename(fPath.c_str());
1019}
1020
1021/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1022
msarett9ce3a542016-07-15 13:54:38 -07001023ColorCodecSrc::ColorCodecSrc(Path path, Mode mode, SkColorType colorType)
msarett69deca82016-04-29 09:38:40 -07001024 : fPath(path)
1025 , fMode(mode)
msarett9ce3a542016-07-15 13:54:38 -07001026 , fColorType(colorType)
msarett69deca82016-04-29 09:38:40 -07001027{}
1028
1029bool ColorCodecSrc::veto(SinkFlags flags) const {
1030 // Test to direct raster backends (8888 and 565).
1031 return flags.type != SinkFlags::kRaster || flags.approach != SinkFlags::kDirect;
1032}
1033
Matt Sarett6a0feba2017-06-09 10:45:44 -04001034void clamp_if_necessary(const SkBitmap& bitmap, SkColorType dstCT) {
1035 if (kRGBA_F16_SkColorType != bitmap.colorType() || kRGBA_F16_SkColorType == dstCT) {
1036 // No need to clamp if the dst is F16. We will clamp when we encode to PNG.
1037 return;
1038 }
1039
Mike Klein45c16fa2017-07-18 18:15:13 -04001040 SkJumper_MemoryCtx ptr = { bitmap.getAddr(0,0), bitmap.rowBytesAsPixels() };
1041
Matt Sarett6a0feba2017-06-09 10:45:44 -04001042 SkRasterPipeline_<256> p;
1043 p.append(SkRasterPipeline::load_f16, &ptr);
1044 p.append(SkRasterPipeline::clamp_0);
1045 if (kPremul_SkAlphaType == bitmap.alphaType()) {
1046 p.append(SkRasterPipeline::clamp_a);
1047 } else {
1048 p.append(SkRasterPipeline::clamp_1);
1049 }
1050 p.append(SkRasterPipeline::store_f16, &ptr);
1051
Mike Klein45c16fa2017-07-18 18:15:13 -04001052 p.run(0,0, bitmap.width(), bitmap.height());
Matt Sarett6a0feba2017-06-09 10:45:44 -04001053}
1054
msarett69deca82016-04-29 09:38:40 -07001055Error ColorCodecSrc::draw(SkCanvas* canvas) const {
1056 if (kRGB_565_SkColorType == canvas->imageInfo().colorType()) {
1057 return Error::Nonfatal("No need to test color correction to 565 backend.");
1058 }
1059
msarettd1ec89b2016-08-03 12:59:27 -07001060 bool runInLegacyMode = kBaseline_Mode == fMode;
msarettd1ec89b2016-08-03 12:59:27 -07001061 if (runInLegacyMode && canvas->imageInfo().colorSpace()) {
1062 return Error::Nonfatal("Skipping tests that are only interesting in legacy mode.");
1063 } else if (!runInLegacyMode && !canvas->imageInfo().colorSpace()) {
1064 return Error::Nonfatal("Skipping tests that are only interesting in srgb mode.");
msarett9ce3a542016-07-15 13:54:38 -07001065 }
1066
bungeman38d909e2016-08-02 14:40:46 -07001067 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
msarett69deca82016-04-29 09:38:40 -07001068 if (!encoded) {
1069 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1070 }
1071
Mike Reedede7bac2017-07-23 15:30:02 -04001072 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
1073 if (nullptr == codec) {
msarett69deca82016-04-29 09:38:40 -07001074 return SkStringPrintf("Couldn't create codec for %s.", fPath.c_str());
1075 }
1076
msarett9876ac52016-06-01 14:47:18 -07001077 // Load the dst ICC profile. This particular dst is fairly similar to Adobe RGB.
Mike Reed0933bc92017-12-09 01:27:41 +00001078 sk_sp<SkData> dstData = GetResourceAsData("icc_profiles/HP_ZR30w.icc");
msarett9876ac52016-06-01 14:47:18 -07001079 if (!dstData) {
1080 return "Cannot read monitor profile. Is the resource path set correctly?";
1081 }
1082
msarett50ce1f22016-07-29 06:23:33 -07001083 sk_sp<SkColorSpace> dstSpace = nullptr;
1084 if (kDst_sRGB_Mode == fMode) {
Matt Sarett77a7a1b2017-02-07 13:56:11 -05001085 dstSpace = SkColorSpace::MakeSRGB();
msarett50ce1f22016-07-29 06:23:33 -07001086 } else if (kDst_HPZR30w_Mode == fMode) {
Brian Osman526972e2016-10-24 09:24:02 -04001087 dstSpace = SkColorSpace::MakeICC(dstData->data(), dstData->size());
msarett50ce1f22016-07-29 06:23:33 -07001088 }
1089
1090 SkImageInfo decodeInfo = codec->getInfo().makeColorType(fColorType).makeColorSpace(dstSpace);
msarettd1ec89b2016-08-03 12:59:27 -07001091 if (kUnpremul_SkAlphaType == decodeInfo.alphaType()) {
1092 decodeInfo = decodeInfo.makeAlphaType(kPremul_SkAlphaType);
1093 }
msarett2ecc35f2016-09-08 11:55:16 -07001094 if (kRGBA_F16_SkColorType == fColorType) {
Brian Osman36703d92017-12-12 14:09:31 -05001095 decodeInfo = decodeInfo.makeColorSpace(decodeInfo.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001096 }
msarettd1ec89b2016-08-03 12:59:27 -07001097
msarett50ce1f22016-07-29 06:23:33 -07001098 SkImageInfo bitmapInfo = decodeInfo;
Matt Sarettf485cf92017-05-26 08:58:03 -04001099 set_bitmap_color_space(&bitmapInfo);
msarett50ce1f22016-07-29 06:23:33 -07001100 if (kRGBA_8888_SkColorType == decodeInfo.colorType() ||
1101 kBGRA_8888_SkColorType == decodeInfo.colorType())
1102 {
1103 bitmapInfo = bitmapInfo.makeColorType(kN32_SkColorType);
1104 }
1105
1106 SkBitmap bitmap;
1107 if (!bitmap.tryAllocPixels(bitmapInfo)) {
1108 return SkStringPrintf("Image(%s) is too large (%d x %d)", fPath.c_str(),
1109 bitmapInfo.width(), bitmapInfo.height());
1110 }
1111
1112 size_t rowBytes = bitmap.rowBytes();
1113 SkCodec::Result r = codec->getPixels(decodeInfo, bitmap.getPixels(), rowBytes);
Leon Scroggins III674a1842017-07-06 12:26:09 -04001114 switch (r) {
1115 case SkCodec::kSuccess:
1116 case SkCodec::kErrorInInput:
1117 case SkCodec::kIncompleteInput:
1118 break;
1119 default:
1120 return SkStringPrintf("Couldn't getPixels %s. Error code %d", fPath.c_str(), r);
msarett50ce1f22016-07-29 06:23:33 -07001121 }
1122
msarett69deca82016-04-29 09:38:40 -07001123 switch (fMode) {
1124 case kBaseline_Mode:
msarett39979d82016-07-28 17:11:18 -07001125 case kDst_sRGB_Mode:
msarett50ce1f22016-07-29 06:23:33 -07001126 case kDst_HPZR30w_Mode:
Matt Sarett6a0feba2017-06-09 10:45:44 -04001127 // We do not support drawing unclamped F16.
1128 clamp_if_necessary(bitmap, canvas->imageInfo().colorType());
msarett39979d82016-07-28 17:11:18 -07001129 canvas->drawBitmap(bitmap, 0, 0);
1130 break;
msarett69deca82016-04-29 09:38:40 -07001131 default:
1132 SkASSERT(false);
1133 return "Invalid fMode";
1134 }
1135 return "";
1136}
1137
1138SkISize ColorCodecSrc::size() const {
bungeman38d909e2016-08-02 14:40:46 -07001139 sk_sp<SkData> encoded(SkData::MakeFromFileName(fPath.c_str()));
Mike Reedede7bac2017-07-23 15:30:02 -04001140 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(encoded));
msarett69deca82016-04-29 09:38:40 -07001141 if (nullptr == codec) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001142 return {0, 0};
msarett69deca82016-04-29 09:38:40 -07001143 }
Hal Canaryfafe1352017-04-11 12:12:02 -04001144 return {codec->getInfo().width(), codec->getInfo().height()};
msarett69deca82016-04-29 09:38:40 -07001145}
1146
1147Name ColorCodecSrc::name() const {
1148 return SkOSPath::Basename(fPath.c_str());
1149}
1150
1151/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1152
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001153SKPSrc::SKPSrc(Path path) : fPath(path) { }
mtklein748ca3b2015-01-15 10:56:12 -08001154
Robert Phillipse4aae342018-03-14 10:26:57 -04001155static sk_sp<SkPicture> read_skp(const char* path, const SkDeserialProcs* procs = nullptr) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001156 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtklein75d98fd2015-01-18 07:05:01 -08001157 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001158 return nullptr;
mtklein748ca3b2015-01-15 10:56:12 -08001159 }
Robert Phillipse4aae342018-03-14 10:26:57 -04001160 sk_sp<SkPicture> pic(SkPicture::MakeFromStream(stream.get(), procs));
mtklein75d98fd2015-01-18 07:05:01 -08001161 if (!pic) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001162 return nullptr;
mtklein75d98fd2015-01-18 07:05:01 -08001163 }
bungemanf93d7112016-09-16 06:24:20 -07001164 stream = nullptr; // Might as well drop this when we're done with it.
joshualitt7c3a2f82015-03-31 13:32:05 -07001165
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001166 return pic;
1167}
1168
1169Error SKPSrc::draw(SkCanvas* canvas) const {
1170 sk_sp<SkPicture> pic = read_skp(fPath.c_str());
1171 if (!pic) {
1172 return SkStringPrintf("Couldn't read %s.", fPath.c_str());
1173 }
1174
Robert Phillips33f02ed2018-03-27 08:06:57 -04001175 canvas->clipRect(SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize));
mtklein748ca3b2015-01-15 10:56:12 -08001176 canvas->drawPicture(pic);
1177 return "";
1178}
1179
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001180static SkRect get_cull_rect_for_skp(const char* path) {
1181 std::unique_ptr<SkStream> stream = SkStream::MakeFromFile(path);
mtkleinffa901a2015-03-16 10:38:07 -07001182 if (!stream) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001183 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001184 }
1185 SkPictInfo info;
Mike Reede7a58322017-12-20 14:09:20 -05001186 if (!SkPicture_StreamIsSKP(stream.get(), &info)) {
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001187 return SkRect::MakeEmpty();
mtkleinffa901a2015-03-16 10:38:07 -07001188 }
Robert Phillipsad8a43f2017-08-30 12:06:35 -04001189
1190 return info.fCullRect;
1191}
1192
1193SkISize SKPSrc::size() const {
1194 SkRect viewport = get_cull_rect_for_skp(fPath.c_str());
Robert Phillips33f02ed2018-03-27 08:06:57 -04001195 if (!viewport.intersect((SkRect::MakeWH(FLAGS_skpViewportSize, FLAGS_skpViewportSize)))) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001196 return {0, 0};
mtkleinffa901a2015-03-16 10:38:07 -07001197 }
1198 return viewport.roundOut().size();
mtklein748ca3b2015-01-15 10:56:12 -08001199}
1200
1201Name SKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1202
Florin Malitafc043dc2017-12-31 11:08:42 -05001203/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1204
Florin Malita87ccf332018-05-04 12:23:24 -04001205#if defined(SK_ENABLE_SKOTTIE)
Florin Malita54f65c42018-01-16 17:04:30 -05001206SkottieSrc::SkottieSrc(Path path)
Florin Malitafc043dc2017-12-31 11:08:42 -05001207 : fName(SkOSPath::Basename(path.c_str())) {
1208
Florin Malita54f65c42018-01-16 17:04:30 -05001209 fAnimation = skottie::Animation::MakeFromFile(path.c_str());
Florin Malitafc043dc2017-12-31 11:08:42 -05001210 if (!fAnimation) {
1211 return;
1212 }
1213
1214 // Fit kTileCount x kTileCount frames to a 1000x1000 film strip.
1215 static constexpr SkScalar kTargetSize = 1000;
Florin Malita3fae0f32018-03-15 21:52:54 -04001216 fTileSize = SkSize::Make(kTargetSize / kTileCount, kTargetSize / kTileCount).toCeil();
Florin Malitafc043dc2017-12-31 11:08:42 -05001217}
1218
Florin Malita54f65c42018-01-16 17:04:30 -05001219Error SkottieSrc::draw(SkCanvas* canvas) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001220 if (!fAnimation) {
1221 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
1222 }
1223
1224 canvas->drawColor(SK_ColorWHITE);
1225
Florin Malitafc043dc2017-12-31 11:08:42 -05001226 const auto ip = fAnimation->inPoint() * 1000 / fAnimation->frameRate(),
1227 op = fAnimation->outPoint() * 1000 / fAnimation->frameRate(),
1228 fr = (op - ip) / (kTileCount * kTileCount - 1);
1229
Florin Malitad3c1b842018-01-27 12:43:24 -05001230 // Shuffled order to exercise non-linear frame progression.
1231 static constexpr int frames[] = { 4, 0, 3, 1, 2 };
1232 static_assert(SK_ARRAY_COUNT(frames) == kTileCount, "");
1233
Florin Malitafc043dc2017-12-31 11:08:42 -05001234 for (int i = 0; i < kTileCount; ++i) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001235 const SkScalar y = frames[i] * fTileSize.height();
Florin Malitafc043dc2017-12-31 11:08:42 -05001236
1237 for (int j = 0; j < kTileCount; ++j) {
Florin Malita3fae0f32018-03-15 21:52:54 -04001238 const SkScalar x = frames[j] * fTileSize.width();
Florin Malitafc043dc2017-12-31 11:08:42 -05001239 SkRect dest = SkRect::MakeXYWH(x, y, fTileSize.width(), fTileSize.height());
1240
Florin Malitad3c1b842018-01-27 12:43:24 -05001241 const auto t = fr * (frames[i] * kTileCount + frames[j]);
Florin Malitadf2713c2018-01-09 15:51:21 -05001242 {
1243 SkAutoCanvasRestore acr(canvas, true);
Florin Malitad3c1b842018-01-27 12:43:24 -05001244 canvas->clipRect(dest, true);
Florin Malitadf2713c2018-01-09 15:51:21 -05001245 canvas->concat(SkMatrix::MakeRectToRect(SkRect::MakeSize(fAnimation->size()),
1246 dest,
Florin Malita3fae0f32018-03-15 21:52:54 -04001247 SkMatrix::kCenter_ScaleToFit));
Florin Malitadf2713c2018-01-09 15:51:21 -05001248
1249 fAnimation->animationTick(t);
1250 fAnimation->render(canvas);
1251 }
Florin Malitafc043dc2017-12-31 11:08:42 -05001252 }
1253 }
1254
1255 return "";
1256}
1257
Florin Malita54f65c42018-01-16 17:04:30 -05001258SkISize SkottieSrc::size() const {
Florin Malita3fae0f32018-03-15 21:52:54 -04001259 return SkISize::Make(kTileCount * fTileSize.width(),
1260 kTileCount * fTileSize.height());
Florin Malitafc043dc2017-12-31 11:08:42 -05001261}
1262
Florin Malita54f65c42018-01-16 17:04:30 -05001263Name SkottieSrc::name() const { return fName; }
Florin Malitafc043dc2017-12-31 11:08:42 -05001264
Florin Malita54f65c42018-01-16 17:04:30 -05001265bool SkottieSrc::veto(SinkFlags flags) const {
Florin Malitafc043dc2017-12-31 11:08:42 -05001266 // No need to test to non-(raster||gpu||vector) or indirect backends.
1267 bool type_ok = flags.type == SinkFlags::kRaster
1268 || flags.type == SinkFlags::kGPU
1269 || flags.type == SinkFlags::kVector;
1270
1271 return !type_ok || flags.approach != SinkFlags::kDirect;
1272}
Florin Malita124d5af2017-12-31 17:02:26 -05001273#endif
Florin Malitafc043dc2017-12-31 11:08:42 -05001274
1275/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
fmalitaa2b9fdf2016-08-03 19:53:36 -07001276#if defined(SK_XML)
fmalitabdf3e5c2016-09-17 07:26:26 -07001277// Used when the image doesn't have an intrinsic size.
Hal Canaryfafe1352017-04-11 12:12:02 -04001278static const SkSize kDefaultSVGSize = {1000, 1000};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001279
fmalitabdf3e5c2016-09-17 07:26:26 -07001280// Used to force-scale tiny fixed-size images.
Hal Canaryfafe1352017-04-11 12:12:02 -04001281static const SkSize kMinimumSVGSize = {128, 128};
fmalitaa2b9fdf2016-08-03 19:53:36 -07001282
fmalitaacd2f5c2016-11-08 07:13:45 -08001283SVGSrc::SVGSrc(Path path)
1284 : fName(SkOSPath::Basename(path.c_str()))
1285 , fScale(1) {
fmalitabdf3e5c2016-09-17 07:26:26 -07001286
fmalitaacd2f5c2016-11-08 07:13:45 -08001287 SkFILEStream stream(path.c_str());
1288 if (!stream.isValid()) {
1289 return;
1290 }
1291 fDom = SkSVGDOM::MakeFromStream(stream);
1292 if (!fDom) {
1293 return;
1294 }
1295
1296 const SkSize& sz = fDom->containerSize();
1297 if (sz.isEmpty()) {
1298 // no intrinsic size
1299 fDom->setContainerSize(kDefaultSVGSize);
1300 } else {
1301 fScale = SkTMax(1.f, SkTMax(kMinimumSVGSize.width() / sz.width(),
1302 kMinimumSVGSize.height() / sz.height()));
1303 }
1304}
1305
1306Error SVGSrc::draw(SkCanvas* canvas) const {
fmalitabdf3e5c2016-09-17 07:26:26 -07001307 if (!fDom) {
fmalitaacd2f5c2016-11-08 07:13:45 -08001308 return SkStringPrintf("Unable to parse file: %s", fName.c_str());
fmalitaa2b9fdf2016-08-03 19:53:36 -07001309 }
1310
fmalitaacd2f5c2016-11-08 07:13:45 -08001311 SkAutoCanvasRestore acr(canvas, true);
1312 canvas->scale(fScale, fScale);
1313 fDom->render(canvas);
1314
fmalitaa2b9fdf2016-08-03 19:53:36 -07001315 return "";
1316}
1317
1318SkISize SVGSrc::size() const {
fmalitaacd2f5c2016-11-08 07:13:45 -08001319 if (!fDom) {
Hal Canaryfafe1352017-04-11 12:12:02 -04001320 return {0, 0};
fmalitabdf3e5c2016-09-17 07:26:26 -07001321 }
1322
Hal Canaryfafe1352017-04-11 12:12:02 -04001323 return SkSize{fDom->containerSize().width() * fScale, fDom->containerSize().height() * fScale}
1324 .toRound();
fmalitaa2b9fdf2016-08-03 19:53:36 -07001325}
1326
fmalitaacd2f5c2016-11-08 07:13:45 -08001327Name SVGSrc::name() const { return fName; }
fmalitaa2b9fdf2016-08-03 19:53:36 -07001328
fmalita179d8852016-08-16 14:23:29 -07001329bool SVGSrc::veto(SinkFlags flags) const {
Florin Malita93323eb2017-06-16 15:31:17 -04001330 // No need to test to non-(raster||gpu||vector) or indirect backends.
fmalita179d8852016-08-16 14:23:29 -07001331 bool type_ok = flags.type == SinkFlags::kRaster
Florin Malita93323eb2017-06-16 15:31:17 -04001332 || flags.type == SinkFlags::kGPU
1333 || flags.type == SinkFlags::kVector;
fmalita179d8852016-08-16 14:23:29 -07001334
1335 return !type_ok || flags.approach != SinkFlags::kDirect;
1336}
1337
fmalitaa2b9fdf2016-08-03 19:53:36 -07001338#endif // defined(SK_XML)
1339/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
mtklein748ca3b2015-01-15 10:56:12 -08001340
halcanary45420a92016-06-02 12:41:14 -07001341MSKPSrc::MSKPSrc(Path path) : fPath(path) {
bungemanf93d7112016-09-16 06:24:20 -07001342 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
Hal Canary45cde312017-04-03 16:06:42 -04001343 int count = SkMultiPictureDocumentReadPageCount(stream.get());
1344 if (count > 0) {
1345 fPages.reset(count);
1346 (void)SkMultiPictureDocumentReadPageSizes(stream.get(), &fPages[0], fPages.count());
1347 }
halcanary45420a92016-06-02 12:41:14 -07001348}
1349
Hal Canary45cde312017-04-03 16:06:42 -04001350int MSKPSrc::pageCount() const { return fPages.count(); }
halcanary45420a92016-06-02 12:41:14 -07001351
1352SkISize MSKPSrc::size() const { return this->size(0); }
Hal Canary45cde312017-04-03 16:06:42 -04001353SkISize MSKPSrc::size(int i) const {
Hal Canaryfafe1352017-04-11 12:12:02 -04001354 return i >= 0 && i < fPages.count() ? fPages[i].fSize.toCeil() : SkISize{0, 0};
Hal Canary45cde312017-04-03 16:06:42 -04001355}
halcanary45420a92016-06-02 12:41:14 -07001356
1357Error MSKPSrc::draw(SkCanvas* c) const { return this->draw(0, c); }
1358Error MSKPSrc::draw(int i, SkCanvas* canvas) const {
Hal Canary45cde312017-04-03 16:06:42 -04001359 if (this->pageCount() == 0) {
halcanary45420a92016-06-02 12:41:14 -07001360 return SkStringPrintf("Unable to parse MultiPictureDocument file: %s", fPath.c_str());
1361 }
Hal Canary45cde312017-04-03 16:06:42 -04001362 if (i >= fPages.count() || i < 0) {
halcanary45420a92016-06-02 12:41:14 -07001363 return SkStringPrintf("MultiPictureDocument page number out of range: %d", i);
1364 }
Hal Canary45cde312017-04-03 16:06:42 -04001365 SkPicture* page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001366 if (!page) {
Hal Canary45cde312017-04-03 16:06:42 -04001367 std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(fPath.c_str());
1368 if (!stream) {
1369 return SkStringPrintf("Unable to open file: %s", fPath.c_str());
1370 }
1371 if (!SkMultiPictureDocumentRead(stream.get(), &fPages[0], fPages.count())) {
1372 return SkStringPrintf("SkMultiPictureDocument reader failed on page %d: %s", i,
1373 fPath.c_str());
1374 }
1375 page = fPages[i].fPicture.get();
halcanary45420a92016-06-02 12:41:14 -07001376 }
1377 canvas->drawPicture(page);
1378 return "";
1379}
1380
1381Name MSKPSrc::name() const { return SkOSPath::Basename(fPath.c_str()); }
1382
1383/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1384
mtkleinad66f9b2015-02-13 15:11:10 -08001385Error NullSink::draw(const Src& src, SkBitmap*, SkWStream*, SkString*) const {
Mike Reed5df49342016-11-12 08:06:55 -06001386 return src.draw(SkMakeNullCanvas().get());
mtkleinad66f9b2015-02-13 15:11:10 -08001387}
1388
1389/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1390
Brian Osmane5756ec2017-09-06 17:08:30 -04001391static bool encode_png_base64(const SkBitmap& bitmap, SkString* dst) {
1392 SkPixmap pm;
1393 if (!bitmap.peekPixels(&pm)) {
1394 dst->set("peekPixels failed");
1395 return false;
1396 }
1397
1398 // We're going to embed this PNG in a data URI, so make it as small as possible
1399 SkPngEncoder::Options options;
1400 options.fFilterFlags = SkPngEncoder::FilterFlag::kAll;
1401 options.fZLibLevel = 9;
1402 options.fUnpremulBehavior = pm.colorSpace() ? SkTransferFunctionBehavior::kRespect
1403 : SkTransferFunctionBehavior::kIgnore;
1404
1405 SkDynamicMemoryWStream wStream;
1406 if (!SkPngEncoder::Encode(&wStream, pm, options)) {
1407 dst->set("SkPngEncoder::Encode failed");
1408 return false;
1409 }
1410
1411 sk_sp<SkData> pngData = wStream.detachAsData();
1412 size_t len = SkBase64::Encode(pngData->data(), pngData->size(), nullptr);
1413
1414 // The PNG can be almost arbitrarily large. We don't want to fill our logs with enormous URLs.
1415 // Infra says these can be pretty big, as long as we're only outputting them on failure.
1416 static const size_t kMaxBase64Length = 1024 * 1024;
1417 if (len > kMaxBase64Length) {
1418 dst->printf("Encoded image too large (%u bytes)", static_cast<uint32_t>(len));
1419 return false;
1420 }
1421
1422 dst->resize(len);
1423 SkBase64::Encode(pngData->data(), pngData->size(), dst->writable_str());
1424 return true;
1425}
1426
1427static Error compare_bitmaps(const SkBitmap& reference, const SkBitmap& bitmap) {
1428 // The dimensions are a property of the Src only, and so should be identical.
Mike Reedf0ffb892017-10-03 14:47:21 -04001429 SkASSERT(reference.computeByteSize() == bitmap.computeByteSize());
1430 if (reference.computeByteSize() != bitmap.computeByteSize()) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001431 return "Dimensions don't match reference";
1432 }
1433 // All SkBitmaps in DM are tight, so this comparison is easy.
Mike Reedf0ffb892017-10-03 14:47:21 -04001434 if (0 != memcmp(reference.getPixels(), bitmap.getPixels(), reference.computeByteSize())) {
Brian Osmane5756ec2017-09-06 17:08:30 -04001435 SkString encoded;
1436 SkString errString("Pixels don't match reference");
1437 if (encode_png_base64(reference, &encoded)) {
1438 errString.append("\nExpected: data:image/png;base64,");
1439 errString.append(encoded);
1440 } else {
1441 errString.append("\nExpected image failed to encode: ");
1442 errString.append(encoded);
1443 }
1444 if (encode_png_base64(bitmap, &encoded)) {
1445 errString.append("\nActual: data:image/png;base64,");
1446 errString.append(encoded);
1447 } else {
1448 errString.append("\nActual image failed to encode: ");
1449 errString.append(encoded);
1450 }
1451 return errString;
1452 }
1453 return "";
1454}
1455
1456/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1457
mtkleinb9eb4ac2015-02-02 18:26:03 -08001458DEFINE_bool(gpuStats, false, "Append GPU stats to the log for each GPU task?");
1459
bsalomon85b4b532016-04-05 11:06:27 -07001460GPUSink::GPUSink(GrContextFactory::ContextType ct,
csmartdaltone812d492017-02-21 12:36:05 -07001461 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001462 SkCommandLineConfigGpu::SurfType surfType,
mtklein82d28432015-01-15 12:46:02 -08001463 int samples,
bsalomonafcd7cd2015-08-31 12:39:41 -07001464 bool diText,
brianosmand93c1202016-03-10 07:49:08 -08001465 SkColorType colorType,
Brian Salomonce5ee602017-07-17 11:31:31 -04001466 SkAlphaType alphaType,
brianosmanb109b8c2016-06-16 13:03:24 -07001467 sk_sp<SkColorSpace> colorSpace,
Brian Osmanf21aa042017-08-21 16:48:46 -04001468 bool threaded,
1469 const GrContextOptions& grCtxOptions)
Brian Salomonce5ee602017-07-17 11:31:31 -04001470 : fContextType(ct)
1471 , fContextOverrides(overrides)
Brian Salomonf865b052018-03-09 09:01:53 -05001472 , fSurfType(surfType)
Brian Salomonce5ee602017-07-17 11:31:31 -04001473 , fSampleCount(samples)
1474 , fUseDIText(diText)
1475 , fColorType(colorType)
1476 , fAlphaType(alphaType)
1477 , fColorSpace(std::move(colorSpace))
Brian Osmanf21aa042017-08-21 16:48:46 -04001478 , fThreaded(threaded)
1479 , fBaseContextOptions(grCtxOptions) {}
mtklein748ca3b2015-01-15 10:56:12 -08001480
Brian Salomon09d994e2016-12-21 11:14:46 -05001481DEFINE_bool(drawOpClip, false, "Clip each GrDrawOp to its device bounds for testing.");
bsalomon648c6962015-10-23 09:06:59 -07001482
Brian Osmanf9810662017-08-30 10:02:10 -04001483Error GPUSink::draw(const Src& src, SkBitmap* dst, SkWStream* dstStream, SkString* log) const {
1484 return this->onDraw(src, dst, dstStream, log, fBaseContextOptions);
1485}
1486
1487Error GPUSink::onDraw(const Src& src, SkBitmap* dst, SkWStream*, SkString* log,
1488 const GrContextOptions& baseOptions) const {
1489 GrContextOptions grOptions = baseOptions;
kkinnunen64492c42015-12-08 01:24:40 -08001490
kkinnunen5219fd92015-12-10 06:28:13 -08001491 src.modifyGrContextOptions(&grOptions);
1492
1493 GrContextFactory factory(grOptions);
mtkleinf4ba3212015-01-28 15:32:24 -08001494 const SkISize size = src.size();
Brian Salomonce5ee602017-07-17 11:31:31 -04001495 SkImageInfo info =
1496 SkImageInfo::Make(size.width(), size.height(), fColorType, fAlphaType, fColorSpace);
Brian Salomonf865b052018-03-09 09:01:53 -05001497 sk_sp<SkSurface> surface;
msarett13a036b2016-02-08 09:10:47 -08001498#if SK_SUPPORT_GPU
csmartdaltone812d492017-02-21 12:36:05 -07001499 GrContext* context = factory.getContextInfo(fContextType, fContextOverrides).grContext();
Brian Salomonc7fe0f72018-05-11 10:14:21 -04001500 const int maxDimension = context->contextPriv().caps()->maxTextureSize();
msarett13a036b2016-02-08 09:10:47 -08001501 if (maxDimension < SkTMax(size.width(), size.height())) {
1502 return Error::Nonfatal("Src too large to create a texture.\n");
1503 }
Brian Salomonf865b052018-03-09 09:01:53 -05001504 uint32_t flags = fUseDIText ? SkSurfaceProps::kUseDeviceIndependentFonts_Flag : 0;
1505 SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType);
1506 GrBackendTexture backendTexture;
1507 GrBackendRenderTarget backendRT;
1508 switch (fSurfType) {
1509 case SkCommandLineConfigGpu::SurfType::kDefault:
1510 surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, fSampleCount,
1511 &props);
1512 break;
1513 case SkCommandLineConfigGpu::SurfType::kBackendTexture:
1514 backendTexture = context->contextPriv().getGpu()->createTestingOnlyBackendTexture(
Greg Daniel57bf4a32018-04-19 10:28:37 -04001515 nullptr, info.width(), info.height(), info.colorType(), info.colorSpace(),
1516 true, GrMipMapped::kNo);
Brian Salomonf865b052018-03-09 09:01:53 -05001517 surface = SkSurface::MakeFromBackendTexture(context, backendTexture,
1518 kTopLeft_GrSurfaceOrigin, fSampleCount,
Brian Salomon53706772018-03-19 14:18:08 -04001519 fColorType, info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001520 break;
1521 case SkCommandLineConfigGpu::SurfType::kBackendRenderTarget:
1522 if (1 == fSampleCount) {
1523 auto srgbEncoded = info.colorSpace() && info.colorSpace()->gammaCloseToSRGB()
1524 ? GrSRGBEncoded::kYes
1525 : GrSRGBEncoded::kNo;
1526 auto colorType = SkColorTypeToGrColorType(info.colorType());
1527 backendRT = context->contextPriv().getGpu()->createTestingOnlyBackendRenderTarget(
1528 info.width(), info.height(), colorType, srgbEncoded);
Brian Salomon49edccd2018-03-23 15:31:32 -04001529 surface = SkSurface::MakeFromBackendRenderTarget(
1530 context, backendRT, kBottomLeft_GrSurfaceOrigin, info.colorType(),
1531 info.refColorSpace(), &props);
Brian Salomonf865b052018-03-09 09:01:53 -05001532 }
1533 break;
1534 }
msarett13a036b2016-02-08 09:10:47 -08001535#endif
1536
mtklein748ca3b2015-01-15 10:56:12 -08001537 if (!surface) {
1538 return "Could not create a surface.";
1539 }
joshualitt5f5a8d72015-02-25 14:09:45 -08001540 if (FLAGS_preAbandonGpuContext) {
joshualitt5f5a8d72015-02-25 14:09:45 -08001541 factory.abandonContexts();
1542 }
mtklein748ca3b2015-01-15 10:56:12 -08001543 SkCanvas* canvas = surface->getCanvas();
1544 Error err = src.draw(canvas);
1545 if (!err.isEmpty()) {
1546 return err;
1547 }
1548 canvas->flush();
mtkleinb9eb4ac2015-02-02 18:26:03 -08001549 if (FLAGS_gpuStats) {
Robert Phillips0c4b7b12018-03-06 08:20:37 -05001550#if SK_SUPPORT_GPU
1551 canvas->getGrContext()->contextPriv().dumpCacheStats(log);
1552 canvas->getGrContext()->contextPriv().dumpGpuStats(log);
1553#endif
mtkleinb9eb4ac2015-02-02 18:26:03 -08001554 }
Brian Salomon5fba7ad2018-03-22 10:01:16 -04001555 if (info.colorType() == kRGB_565_SkColorType || info.colorType() == kARGB_4444_SkColorType ||
1556 info.colorType() == kRGB_888x_SkColorType) {
Brian Salomonce5ee602017-07-17 11:31:31 -04001557 // We don't currently support readbacks into these formats on the GPU backend. Convert to
1558 // 32 bit.
1559 info = SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
1560 kPremul_SkAlphaType, fColorSpace);
1561 }
mtklein748ca3b2015-01-15 10:56:12 -08001562 dst->allocPixels(info);
Mike Reed12e946b2017-04-17 10:53:29 -04001563 canvas->readPixels(*dst, 0, 0);
mtklein55e88b22015-01-21 15:50:13 -08001564 if (FLAGS_abandonGpuContext) {
1565 factory.abandonContexts();
bsalomon6e2aad42016-04-01 11:54:31 -07001566 } else if (FLAGS_releaseAndAbandonGpuContext) {
1567 factory.releaseResourcesAndAbandonContexts();
mtklein55e88b22015-01-21 15:50:13 -08001568 }
Brian Salomonf865b052018-03-09 09:01:53 -05001569#if SK_SUPPORT_GPU
1570 if (!context->contextPriv().abandoned()) {
1571 surface.reset();
1572 if (backendTexture.isValid()) {
Brian Salomon26102cb2018-03-09 09:33:19 -05001573 context->contextPriv().getGpu()->deleteTestingOnlyBackendTexture(backendTexture);
Brian Salomonf865b052018-03-09 09:01:53 -05001574 }
1575 if (backendRT.isValid()) {
1576 context->contextPriv().getGpu()->deleteTestingOnlyBackendRenderTarget(backendRT);
1577 }
1578 }
1579#endif
mtklein748ca3b2015-01-15 10:56:12 -08001580 return "";
1581}
1582
1583/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1584
Brian Osmanf9810662017-08-30 10:02:10 -04001585GPUThreadTestingSink::GPUThreadTestingSink(GrContextFactory::ContextType ct,
1586 GrContextFactory::ContextOverrides overrides,
Brian Salomonf865b052018-03-09 09:01:53 -05001587 SkCommandLineConfigGpu::SurfType surfType,
Brian Osmanf9810662017-08-30 10:02:10 -04001588 int samples,
1589 bool diText,
1590 SkColorType colorType,
1591 SkAlphaType alphaType,
1592 sk_sp<SkColorSpace> colorSpace,
1593 bool threaded,
1594 const GrContextOptions& grCtxOptions)
Brian Salomonf865b052018-03-09 09:01:53 -05001595 : INHERITED(ct, overrides, surfType, samples, diText, colorType, alphaType,
1596 std::move(colorSpace), threaded, grCtxOptions)
Chris Dalton040238b2017-12-18 14:22:34 -07001597#if SK_SUPPORT_GPU
Mike Klein022cfa22017-09-01 11:53:16 -04001598 , fExecutor(SkExecutor::MakeFIFOThreadPool(FLAGS_gpuThreads)) {
Chris Dalton040238b2017-12-18 14:22:34 -07001599#else
1600 , fExecutor(nullptr) {
1601#endif
Brian Osmanf9810662017-08-30 10:02:10 -04001602 SkASSERT(fExecutor);
1603}
1604
1605Error GPUThreadTestingSink::draw(const Src& src, SkBitmap* dst, SkWStream* wStream,
1606 SkString* log) const {
1607 // Draw twice, once with worker threads, and once without. Verify that we get the same result.
1608 // Also, force us to only use the software path renderer, so we really stress-test the threaded
1609 // version of that code.
1610 GrContextOptions contextOptions = this->baseContextOptions();
Brian Osman195c05b2017-08-30 15:14:04 -04001611 contextOptions.fGpuPathRenderers = GpuPathRenderers::kNone;
Adrienne Walker328490c2018-05-07 12:48:34 -07001612
Greg Daniel024615e2018-05-10 17:25:52 +00001613 contextOptions.fExecutor = fExecutor.get();
Brian Osmanf9810662017-08-30 10:02:10 -04001614 Error err = this->onDraw(src, dst, wStream, log, contextOptions);
1615 if (!err.isEmpty() || !dst) {
1616 return err;
1617 }
1618
1619 SkBitmap reference;
1620 SkString refLog;
1621 SkDynamicMemoryWStream refStream;
1622 contextOptions.fExecutor = nullptr;
1623 Error refErr = this->onDraw(src, &reference, &refStream, &refLog, contextOptions);
1624 if (!refErr.isEmpty()) {
1625 return refErr;
1626 }
1627
Brian Osmane5756ec2017-09-06 17:08:30 -04001628 return compare_bitmaps(reference, *dst);
Brian Osmanf9810662017-08-30 10:02:10 -04001629}
1630
1631/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1632
halcanary47ef4d52015-03-03 09:13:09 -08001633static Error draw_skdocument(const Src& src, SkDocument* doc, SkWStream* dst) {
halcanary4ba051c2016-03-10 10:31:53 -08001634 if (src.size().isEmpty()) {
1635 return "Source has empty dimensions";
1636 }
halcanary47ef4d52015-03-03 09:13:09 -08001637 SkASSERT(doc);
halcanary45420a92016-06-02 12:41:14 -07001638 int pageCount = src.pageCount();
1639 for (int i = 0; i < pageCount; ++i) {
1640 int width = src.size(i).width(), height = src.size(i).height();
halcanary7e798182015-04-14 14:06:18 -07001641 SkCanvas* canvas =
1642 doc->beginPage(SkIntToScalar(width), SkIntToScalar(height));
1643 if (!canvas) {
halcanary96fcdcc2015-08-27 07:41:13 -07001644 return "SkDocument::beginPage(w,h) returned nullptr";
halcanary7e798182015-04-14 14:06:18 -07001645 }
halcanary45420a92016-06-02 12:41:14 -07001646 Error err = src.draw(i, canvas);
halcanary7e798182015-04-14 14:06:18 -07001647 if (!err.isEmpty()) {
1648 return err;
1649 }
1650 doc->endPage();
mtklein748ca3b2015-01-15 10:56:12 -08001651 }
reedd14df7c2016-09-22 14:12:46 -07001652 doc->close();
halcanaryfd4a9932015-01-28 11:45:58 -08001653 dst->flush();
mtklein748ca3b2015-01-15 10:56:12 -08001654 return "";
1655}
1656
halcanary47ef4d52015-03-03 09:13:09 -08001657Error PDFSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
halcanary4b656662016-04-27 07:45:18 -07001658 SkDocument::PDFMetadata metadata;
1659 metadata.fTitle = src.name();
1660 metadata.fSubject = "rendering correctness test";
1661 metadata.fCreator = "Skia/DM";
Mike Reeda4daf192017-12-14 13:25:04 -05001662 metadata.fRasterDPI = fRasterDpi;
1663 metadata.fPDFA = fPDFA;
1664 sk_sp<SkDocument> doc = SkDocument::MakePDF(dst, metadata);
halcanary47ef4d52015-03-03 09:13:09 -08001665 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001666 return "SkDocument::MakePDF() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001667 }
1668 return draw_skdocument(src, doc.get(), dst);
1669}
1670
1671/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1672
1673XPSSink::XPSSink() {}
1674
Hal Canaryabc88d22017-02-06 09:26:49 -05001675#ifdef SK_BUILD_FOR_WIN
Hal Canary5e221e72017-02-06 09:51:42 -05001676static SkTScopedComPtr<IXpsOMObjectFactory> make_xps_factory() {
1677 IXpsOMObjectFactory* factory;
1678 HRN(CoCreateInstance(CLSID_XpsOMObjectFactory,
1679 nullptr,
1680 CLSCTX_INPROC_SERVER,
1681 IID_PPV_ARGS(&factory)));
1682 return SkTScopedComPtr<IXpsOMObjectFactory>(factory);
1683}
1684
1685Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
Hal Canaryabc88d22017-02-06 09:26:49 -05001686 SkAutoCoInitialize com;
1687 if (!com.succeeded()) {
1688 return "Could not initialize COM.";
1689 }
Hal Canary5e221e72017-02-06 09:51:42 -05001690 SkTScopedComPtr<IXpsOMObjectFactory> factory = make_xps_factory();
1691 if (!factory) {
1692 return "Failed to create XPS Factory.";
1693 }
1694 sk_sp<SkDocument> doc(SkDocument::MakeXPS(dst, factory.get()));
halcanary47ef4d52015-03-03 09:13:09 -08001695 if (!doc) {
halcanary4b656662016-04-27 07:45:18 -07001696 return "SkDocument::MakeXPS() returned nullptr";
halcanary47ef4d52015-03-03 09:13:09 -08001697 }
1698 return draw_skdocument(src, doc.get(), dst);
1699}
Hal Canary5e221e72017-02-06 09:51:42 -05001700#else
1701Error XPSSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1702 return "XPS not supported on this platform.";
1703}
1704#endif
reed54dc4872016-09-13 08:09:45 -07001705
1706/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1707
1708PipeSink::PipeSink() {}
1709
1710Error PipeSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1711 return src.draw(SkPipeSerializer().beginWrite(SkRect::Make(src.size()), dst));
1712}
1713
mtklein748ca3b2015-01-15 10:56:12 -08001714/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1715
mtklein9c3f17d2015-01-28 11:35:18 -08001716SKPSink::SKPSink() {}
1717
mtkleinb9eb4ac2015-02-02 18:26:03 -08001718Error SKPSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
mtklein9c3f17d2015-01-28 11:35:18 -08001719 SkSize size;
1720 size = src.size();
1721 SkPictureRecorder recorder;
1722 Error err = src.draw(recorder.beginRecording(size.width(), size.height()));
1723 if (!err.isEmpty()) {
1724 return err;
1725 }
reedca2622b2016-03-18 07:25:55 -07001726 recorder.finishRecordingAsPicture()->serialize(dst);
mtklein9c3f17d2015-01-28 11:35:18 -08001727 return "";
1728}
1729
1730/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1731
Hal Canary85c7fe82016-10-25 10:33:27 -04001732Error DebugSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
1733 SkDebugCanvas debugCanvas(src.size().width(), src.size().height());
1734 Error err = src.draw(&debugCanvas);
1735 if (!err.isEmpty()) {
1736 return err;
1737 }
Mike Reed5df49342016-11-12 08:06:55 -06001738 std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas();
Hal Canary85c7fe82016-10-25 10:33:27 -04001739 UrlDataManager dataManager(SkString("data"));
1740 Json::Value json = debugCanvas.toJSON(
1741 dataManager, debugCanvas.getSize(), nullCanvas.get());
1742 std::string value = Json::StyledWriter().write(json);
1743 return dst->write(value.c_str(), value.size()) ? "" : "SkWStream Error";
1744}
1745
1746/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1747
Bryce Thomas95a7b762018-03-02 13:54:21 -08001748SVGSink::SVGSink(int pageIndex) : fPageIndex(pageIndex) {}
mtklein8a4527e2015-01-31 20:00:58 -08001749
mtkleinb9eb4ac2015-02-02 18:26:03 -08001750Error SVGSink::draw(const Src& src, SkBitmap*, SkWStream* dst, SkString*) const {
fmalita718df0a2016-07-15 10:33:29 -07001751#if defined(SK_XML)
Bryce Thomas95a7b762018-03-02 13:54:21 -08001752 if (src.pageCount() > 1) {
1753 int pageCount = src.pageCount();
1754 if (fPageIndex > pageCount - 1) {
1755 return Error(SkStringPrintf("Page index %d too high for document with only %d pages.",
1756 fPageIndex, pageCount));
1757 }
1758 }
Ben Wagner145dbcd2016-11-03 14:40:50 -04001759 std::unique_ptr<SkXMLWriter> xmlWriter(new SkXMLStreamWriter(dst));
Bryce Thomas95a7b762018-03-02 13:54:21 -08001760 return src.draw(fPageIndex,
1761 SkSVGCanvas::Make(SkRect::MakeWH(SkIntToScalar(src.size().width()),
Mike Reed5df49342016-11-12 08:06:55 -06001762 SkIntToScalar(src.size().height())),
Bryce Thomas95a7b762018-03-02 13:54:21 -08001763 xmlWriter.get())
1764 .get());
fmalita718df0a2016-07-15 10:33:29 -07001765#else
Hal Canary327ef032018-03-22 13:10:51 -04001766 (void)fPageIndex;
fmalita718df0a2016-07-15 10:33:29 -07001767 return Error("SVG sink is disabled.");
1768#endif // SK_XML
mtklein8a4527e2015-01-31 20:00:58 -08001769}
1770
1771/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1772
brianosmanb109b8c2016-06-16 13:03:24 -07001773RasterSink::RasterSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
mtklein27c3fdd2016-02-26 14:43:21 -08001774 : fColorType(colorType)
brianosmanb109b8c2016-06-16 13:03:24 -07001775 , fColorSpace(std::move(colorSpace)) {}
mtklein748ca3b2015-01-15 10:56:12 -08001776
Yuqian Lib8b62532018-02-23 14:13:36 +08001777void RasterSink::allocPixels(const Src& src, SkBitmap* dst) const {
mtkleinf4ba3212015-01-28 15:32:24 -08001778 const SkISize size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001779 // If there's an appropriate alpha type for this color type, use it, otherwise use premul.
1780 SkAlphaType alphaType = kPremul_SkAlphaType;
1781 (void)SkColorTypeValidateAlphaType(fColorType, alphaType, &alphaType);
1782
Mike Reed086a4272017-07-18 10:53:11 -04001783 dst->allocPixelsFlags(SkImageInfo::Make(size.width(), size.height(),
1784 fColorType, alphaType, fColorSpace),
1785 SkBitmap::kZeroPixels_AllocFlag);
Yuqian Lib8b62532018-02-23 14:13:36 +08001786}
1787
1788Error RasterSink::draw(const Src& src, SkBitmap* dst, SkWStream*, SkString*) const {
1789 this->allocPixels(src, dst);
mtklein748ca3b2015-01-15 10:56:12 -08001790 SkCanvas canvas(*dst);
1791 return src.draw(&canvas);
1792}
1793
1794/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1795
Yuqian Lib8b62532018-02-23 14:13:36 +08001796ThreadedSink::ThreadedSink(SkColorType colorType, sk_sp<SkColorSpace> colorSpace)
Yuqian Li0caef292018-05-02 10:56:17 -04001797 : RasterSink(colorType, colorSpace) {}
Yuqian Lib8b62532018-02-23 14:13:36 +08001798
1799Error ThreadedSink::draw(const Src& src, SkBitmap* dst, SkWStream* stream, SkString* str) const {
1800 this->allocPixels(src, dst);
1801
Herb Derbyefe39bc2018-05-01 17:06:20 -04001802 auto canvas = skstd::make_unique<SkCanvas>(
1803 sk_make_sp<SkThreadedBMPDevice>(
Yuqian Li0caef292018-05-02 10:56:17 -04001804 *dst, FLAGS_backendTiles, FLAGS_backendThreads));
Yuqian Lib8b62532018-02-23 14:13:36 +08001805 Error result = src.draw(canvas.get());
1806 canvas->flush();
1807 return result;
1808
1809 // ??? yuqian: why does the following give me segmentation fault while the above one works?
1810 // The seg fault occurs right in the beginning of ThreadedSink::draw with invalid
1811 // memory address (it would crash without even calling this->allocPixels).
1812
1813 // SkThreadedBMPDevice device(*dst, tileCnt, FLAGS_cpuThreads, fExecutor.get());
1814 // SkCanvas canvas(&device);
1815 // Error result = src.draw(&canvas);
1816 // canvas.flush();
1817 // return result;
1818}
1819
1820/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1821
mtkleina16e69e2015-05-05 11:38:45 -07001822// Handy for front-patching a Src. Do whatever up-front work you need, then call draw_to_canvas(),
mtkleine44b5082015-05-07 10:53:34 -07001823// passing the Sink draw() arguments, a size, and a function draws into an SkCanvas.
mtkleina16e69e2015-05-05 11:38:45 -07001824// Several examples below.
1825
mtkleincbf89782016-02-19 14:27:14 -08001826template <typename Fn>
msarett62d3b102015-12-10 15:14:27 -08001827static Error draw_to_canvas(Sink* sink, SkBitmap* bitmap, SkWStream* stream, SkString* log,
mtkleincbf89782016-02-19 14:27:14 -08001828 SkISize size, const Fn& draw) {
mtkleina16e69e2015-05-05 11:38:45 -07001829 class ProxySrc : public Src {
1830 public:
mtkleincbf89782016-02-19 14:27:14 -08001831 ProxySrc(SkISize size, const Fn& draw) : fSize(size), fDraw(draw) {}
mtkleina16e69e2015-05-05 11:38:45 -07001832 Error draw(SkCanvas* canvas) const override { return fDraw(canvas); }
halcanaryb4a7f142016-03-30 08:31:27 -07001833 Name name() const override { return "ProxySrc"; }
1834 SkISize size() const override { return fSize; }
mtkleina16e69e2015-05-05 11:38:45 -07001835 private:
mtkleincbf89782016-02-19 14:27:14 -08001836 SkISize fSize;
1837 const Fn& fDraw;
mtkleina16e69e2015-05-05 11:38:45 -07001838 };
msarett62d3b102015-12-10 15:14:27 -08001839 return sink->draw(ProxySrc(size, draw), bitmap, stream, log);
mtkleina16e69e2015-05-05 11:38:45 -07001840}
1841
1842/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1843
mtklein4a34ecb2016-01-08 10:19:35 -08001844DEFINE_bool(check, true, "If true, have most Via- modes fail if they affect the output.");
1845
1846// Is *bitmap identical to what you get drawing src into sink?
1847static Error check_against_reference(const SkBitmap* bitmap, const Src& src, Sink* sink) {
1848 // We can only check raster outputs.
1849 // (Non-raster outputs like .pdf, .skp, .svg may differ but still draw identically.)
1850 if (FLAGS_check && bitmap) {
1851 SkBitmap reference;
1852 SkString log;
halcanaryb4a7f142016-03-30 08:31:27 -07001853 SkDynamicMemoryWStream wStream;
1854 Error err = sink->draw(src, &reference, &wStream, &log);
mtklein4a34ecb2016-01-08 10:19:35 -08001855 // If we can draw into this Sink via some pipeline, we should be able to draw directly.
1856 SkASSERT(err.isEmpty());
1857 if (!err.isEmpty()) {
1858 return err;
1859 }
Brian Osmane5756ec2017-09-06 17:08:30 -04001860 return compare_bitmaps(reference, *bitmap);
mtklein4a34ecb2016-01-08 10:19:35 -08001861 }
1862 return "";
1863}
1864
1865/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1866
mtkleind603b222015-02-17 11:13:33 -08001867static SkISize auto_compute_translate(SkMatrix* matrix, int srcW, int srcH) {
1868 SkRect bounds = SkRect::MakeIWH(srcW, srcH);
1869 matrix->mapRect(&bounds);
1870 matrix->postTranslate(-bounds.x(), -bounds.y());
Hal Canaryfafe1352017-04-11 12:12:02 -04001871 return {SkScalarRoundToInt(bounds.width()), SkScalarRoundToInt(bounds.height())};
mtkleind603b222015-02-17 11:13:33 -08001872}
1873
msarett62d3b102015-12-10 15:14:27 -08001874ViaMatrix::ViaMatrix(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtklein748ca3b2015-01-15 10:56:12 -08001875
mtkleinb9eb4ac2015-02-02 18:26:03 -08001876Error ViaMatrix::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001877 SkMatrix matrix = fMatrix;
1878 SkISize size = auto_compute_translate(&matrix, src.size().width(), src.size().height());
Ben Wagner145dbcd2016-11-03 14:40:50 -04001879 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001880 canvas->concat(matrix);
1881 return src.draw(canvas);
1882 });
mtklein748ca3b2015-01-15 10:56:12 -08001883}
1884
mtkleind603b222015-02-17 11:13:33 -08001885// Undoes any flip or 90 degree rotate without changing the scale of the bitmap.
1886// This should be pixel-preserving.
msarett62d3b102015-12-10 15:14:27 -08001887ViaUpright::ViaUpright(SkMatrix matrix, Sink* sink) : Via(sink), fMatrix(matrix) {}
mtkleind603b222015-02-17 11:13:33 -08001888
1889Error ViaUpright::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
1890 Error err = fSink->draw(src, bitmap, stream, log);
1891 if (!err.isEmpty()) {
1892 return err;
1893 }
1894
1895 SkMatrix inverse;
1896 if (!fMatrix.rectStaysRect() || !fMatrix.invert(&inverse)) {
1897 return "Cannot upright --matrix.";
1898 }
1899 SkMatrix upright = SkMatrix::I();
1900 upright.setScaleX(SkScalarSignAsScalar(inverse.getScaleX()));
1901 upright.setScaleY(SkScalarSignAsScalar(inverse.getScaleY()));
1902 upright.setSkewX(SkScalarSignAsScalar(inverse.getSkewX()));
1903 upright.setSkewY(SkScalarSignAsScalar(inverse.getSkewY()));
1904
1905 SkBitmap uprighted;
1906 SkISize size = auto_compute_translate(&upright, bitmap->width(), bitmap->height());
1907 uprighted.allocPixels(bitmap->info().makeWH(size.width(), size.height()));
1908
1909 SkCanvas canvas(uprighted);
1910 canvas.concat(upright);
1911 SkPaint paint;
reed374772b2016-10-05 17:33:02 -07001912 paint.setBlendMode(SkBlendMode::kSrc);
mtkleind603b222015-02-17 11:13:33 -08001913 canvas.drawBitmap(*bitmap, 0, 0, &paint);
1914
1915 *bitmap = uprighted;
mtkleind603b222015-02-17 11:13:33 -08001916 return "";
1917}
1918
mtklein748ca3b2015-01-15 10:56:12 -08001919/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1920
mtkleina16e69e2015-05-05 11:38:45 -07001921Error ViaSerialization::draw(
1922 const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtklein748ca3b2015-01-15 10:56:12 -08001923 // Record our Src into a picture.
mtkleina16e69e2015-05-05 11:38:45 -07001924 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001925 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001926 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1927 SkIntToScalar(size.height())));
mtklein748ca3b2015-01-15 10:56:12 -08001928 if (!err.isEmpty()) {
1929 return err;
1930 }
reedca2622b2016-03-18 07:25:55 -07001931 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001932
1933 // Serialize it and then deserialize it.
reed39eaf5f2016-09-15 07:19:35 -07001934 sk_sp<SkPicture> deserialized(SkPicture::MakeFromData(pic->serialize().get()));
mtklein748ca3b2015-01-15 10:56:12 -08001935
Ben Wagner1861e882018-04-04 17:40:46 -04001936 err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001937 canvas->drawPicture(deserialized);
Ben Wagner1861e882018-04-04 17:40:46 -04001938 return "";
mtkleina16e69e2015-05-05 11:38:45 -07001939 });
Ben Wagner1861e882018-04-04 17:40:46 -04001940 if (!err.isEmpty()) {
1941 return err;
1942 }
1943
1944 return check_against_reference(bitmap, src, fSink.get());
mtklein748ca3b2015-01-15 10:56:12 -08001945}
1946
1947/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
1948
msarett62d3b102015-12-10 15:14:27 -08001949ViaTiles::ViaTiles(int w, int h, SkBBHFactory* factory, Sink* sink)
1950 : Via(sink)
mtklein78829242015-05-06 07:54:07 -07001951 , fW(w)
mtklein748ca3b2015-01-15 10:56:12 -08001952 , fH(h)
mtklein78829242015-05-06 07:54:07 -07001953 , fFactory(factory) {}
mtklein748ca3b2015-01-15 10:56:12 -08001954
mtkleinb9eb4ac2015-02-02 18:26:03 -08001955Error ViaTiles::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
mtkleina16e69e2015-05-05 11:38:45 -07001956 auto size = src.size();
mtklein748ca3b2015-01-15 10:56:12 -08001957 SkPictureRecorder recorder;
mtkleina16e69e2015-05-05 11:38:45 -07001958 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
1959 SkIntToScalar(size.height()),
1960 fFactory.get()));
mtklein748ca3b2015-01-15 10:56:12 -08001961 if (!err.isEmpty()) {
1962 return err;
1963 }
reedca2622b2016-03-18 07:25:55 -07001964 sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture());
mtklein748ca3b2015-01-15 10:56:12 -08001965
Ben Wagner145dbcd2016-11-03 14:40:50 -04001966 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(), [&](SkCanvas* canvas) {
mtkleina16e69e2015-05-05 11:38:45 -07001967 const int xTiles = (size.width() + fW - 1) / fW,
1968 yTiles = (size.height() + fH - 1) / fH;
1969 SkMultiPictureDraw mpd(xTiles*yTiles);
reede8f30622016-03-23 18:59:25 -07001970 SkTArray<sk_sp<SkSurface>> surfaces;
1971// surfaces.setReserve(xTiles*yTiles);
mtklein748ca3b2015-01-15 10:56:12 -08001972
mtkleina16e69e2015-05-05 11:38:45 -07001973 SkImageInfo info = canvas->imageInfo().makeWH(fW, fH);
1974 for (int j = 0; j < yTiles; j++) {
1975 for (int i = 0; i < xTiles; i++) {
1976 // This lets our ultimate Sink determine the best kind of surface.
1977 // E.g., if it's a GpuSink, the surfaces and images are textures.
reede8f30622016-03-23 18:59:25 -07001978 auto s = canvas->makeSurface(info);
mtkleina16e69e2015-05-05 11:38:45 -07001979 if (!s) {
reede8f30622016-03-23 18:59:25 -07001980 s = SkSurface::MakeRaster(info); // Some canvases can't create surfaces.
mtklein748ca3b2015-01-15 10:56:12 -08001981 }
reede8f30622016-03-23 18:59:25 -07001982 surfaces.push_back(s);
mtkleina16e69e2015-05-05 11:38:45 -07001983 SkCanvas* c = s->getCanvas();
1984 c->translate(SkIntToScalar(-i * fW),
1985 SkIntToScalar(-j * fH)); // Line up the canvas with this tile.
reedca2622b2016-03-18 07:25:55 -07001986 mpd.add(c, pic.get());
mtklein748ca3b2015-01-15 10:56:12 -08001987 }
mtklein748ca3b2015-01-15 10:56:12 -08001988 }
mtkleina16e69e2015-05-05 11:38:45 -07001989 mpd.draw();
1990 for (int j = 0; j < yTiles; j++) {
1991 for (int i = 0; i < xTiles; i++) {
reed9ce9d672016-03-17 10:51:11 -07001992 sk_sp<SkImage> image(surfaces[i+xTiles*j]->makeImageSnapshot());
mtkleina16e69e2015-05-05 11:38:45 -07001993 canvas->drawImage(image, SkIntToScalar(i*fW), SkIntToScalar(j*fH));
1994 }
1995 }
mtkleina16e69e2015-05-05 11:38:45 -07001996 return "";
1997 });
mtklein748ca3b2015-01-15 10:56:12 -08001998}
1999
mtkleinb7e8d692015-04-07 08:30:32 -07002000/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2001
Robert Phillips33f02ed2018-03-27 08:06:57 -04002002#if SK_SUPPORT_GPU
2003
2004ViaDDL::ViaDDL(int numDivisions, Sink* sink)
2005 : Via(sink)
2006 , fNumDivisions(numDivisions) {
2007}
2008
2009// This class consolidates tracking & extraction of the original image data from the sources,
2010// the upload of said data to the GPU and the fulfillment of promise images.
Robert Phillipsa479f962018-04-10 11:45:40 -04002011//
2012// The way this works is:
2013// the original skp is converted to SkData and all its image info is extracted into this
2014// class and only indices into this class are left in the SkData
2015// Prior to replaying in threads, all the images stored in this class are uploaded to the
2016// gpu and PromiseImageCallbackContexts are created for them
2017// Each thread reinflates the SkData into an SkPicture replacing all the indices w/
2018// promise images (all using the same GrBackendTexture and getting a ref to the
2019// appropriate PromiseImageCallbackContext) and then creates a DDL.
2020// This class is then reset - dropping all of its refs on the PromiseImageCallbackContexts
2021// Each done callback unrefs its PromiseImageCallbackContext so, once all the promise images
2022// are done the PromiseImageCallbackContext is freed and its GrBackendTexture removed
2023// from VRAM
2024//
Robert Phillips33f02ed2018-03-27 08:06:57 -04002025class ViaDDL::PromiseImageHelper {
2026public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002027 // This class acts as a proxy for the single GrBackendTexture representing an image.
2028 // Whenever a promise image is created for the image the promise image receives a ref to
2029 // this object. Once all the promise images receive their done callbacks this object
2030 // is deleted - removing the GrBackendTexture from VRAM.
2031 // Note that while the DDLs are being created in the threads, the PromiseImageHelper holds
2032 // a ref on all the PromiseImageCallbackContexts. However, once all the threads are done
2033 // it drops all of its refs (via "reset").
2034 class PromiseImageCallbackContext : public SkRefCnt {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002035 public:
Robert Phillipsa479f962018-04-10 11:45:40 -04002036 PromiseImageCallbackContext(GrContext* context) : fContext(context) {}
2037
2038 ~PromiseImageCallbackContext() {
2039 GrGpu* gpu = fContext->contextPriv().getGpu();
2040
2041 if (fBackendTexture.isValid()) {
2042 gpu->deleteTestingOnlyBackendTexture(fBackendTexture);
2043 }
2044 }
2045
2046 void setBackendTexture(const GrBackendTexture& backendTexture) {
2047 fBackendTexture = backendTexture;
2048 }
2049
2050 const GrBackendTexture& backendTexture() const { return fBackendTexture; }
2051
2052 private:
2053 GrContext* fContext;
2054 GrBackendTexture fBackendTexture;
2055
2056 typedef SkRefCnt INHERITED;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002057 };
2058
Robert Phillipsa479f962018-04-10 11:45:40 -04002059 // This is the information extracted into this class from the parsing of the skp file.
2060 // Once it has all been uploaded to the GPU and distributed to the promise images, it
2061 // is all dropped via "reset".
2062 class PromiseImageInfo {
2063 public:
2064 int fIndex; // index in the 'fImageInfo' array
2065 uint32_t fOriginalUniqueID; // original ID for deduping
2066 SkBitmap fBitmap; // CPU-side cache of the contents
2067 sk_sp<PromiseImageCallbackContext> fCallbackContext;
2068 };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002069
Robert Phillipsa479f962018-04-10 11:45:40 -04002070 PromiseImageHelper() { }
2071
2072 void reset() { fImageInfo.reset(); }
Robert Phillips33f02ed2018-03-27 08:06:57 -04002073
2074 bool isValidID(int id) const {
2075 return id >= 0 && id < fImageInfo.count();
2076 }
2077
Robert Phillipsa479f962018-04-10 11:45:40 -04002078 const PromiseImageInfo& getInfo(int id) const {
2079 return fImageInfo[id];
Robert Phillips33f02ed2018-03-27 08:06:57 -04002080 }
2081
2082 // returns -1 on failure
2083 int findOrDefineImage(SkImage* image) {
2084 int preExistingID = this->findImage(image);
2085 if (preExistingID >= 0) {
2086 SkASSERT(this->isValidID(preExistingID));
2087 return preExistingID;
2088 }
2089
2090 int newID = this->addImage(image);
2091 SkASSERT(this->isValidID(newID));
2092 return newID;
2093 }
2094
2095 void uploadAllToGPU(GrContext* context) {
2096 GrGpu* gpu = context->contextPriv().getGpu();
2097 SkASSERT(gpu);
2098
2099 for (int i = 0; i < fImageInfo.count(); ++i) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002100 sk_sp<PromiseImageCallbackContext> callbackContext(
2101 new PromiseImageCallbackContext(context));
2102
Robert Phillipsc186e172018-04-17 16:09:28 -04002103 const PromiseImageInfo& info = fImageInfo[i];
2104
Robert Phillips33f02ed2018-03-27 08:06:57 -04002105 // DDL TODO: how can we tell if we need mipmapping!
Robert Phillipsa479f962018-04-10 11:45:40 -04002106 callbackContext->setBackendTexture(gpu->createTestingOnlyBackendTexture(
Robert Phillipsc186e172018-04-17 16:09:28 -04002107 info.fBitmap.getPixels(),
2108 info.fBitmap.width(),
2109 info.fBitmap.height(),
2110 info.fBitmap.colorType(),
Greg Daniel57bf4a32018-04-19 10:28:37 -04002111 info.fBitmap.colorSpace(),
Robert Phillipsa479f962018-04-10 11:45:40 -04002112 false, GrMipMapped::kNo));
2113 // The GMs sometimes request too large an image
2114 //SkAssertResult(callbackContext->backendTexture().isValid());
Robert Phillips33f02ed2018-03-27 08:06:57 -04002115
Robert Phillipsa479f962018-04-10 11:45:40 -04002116 // The fImageInfo array gets the creation ref
2117 fImageInfo[i].fCallbackContext = std::move(callbackContext);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002118 }
2119 }
2120
2121 static void PromiseImageFulfillProc(void* textureContext, GrBackendTexture* outTexture) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002122 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2123 SkASSERT(callbackContext->backendTexture().isValid());
2124 *outTexture = callbackContext->backendTexture();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002125 }
2126
2127 static void PromiseImageReleaseProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002128#ifdef SK_DEBUG
2129 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2130 SkASSERT(callbackContext->backendTexture().isValid());
2131#endif
Robert Phillips33f02ed2018-03-27 08:06:57 -04002132 }
2133
2134 static void PromiseImageDoneProc(void* textureContext) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002135 auto callbackContext = static_cast<PromiseImageCallbackContext*>(textureContext);
2136 callbackContext->unref();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002137 }
2138
2139private:
2140 // returns -1 if not found
2141 int findImage(SkImage* image) const {
2142 for (int i = 0; i < fImageInfo.count(); ++i) {
2143 if (fImageInfo[i].fOriginalUniqueID == image->uniqueID()) {
2144 SkASSERT(fImageInfo[i].fIndex == i);
2145 SkASSERT(this->isValidID(i) && this->isValidID(fImageInfo[i].fIndex));
2146 return i;
2147 }
2148 }
2149 return -1;
2150 }
2151
2152 // returns -1 on failure
2153 int addImage(SkImage* image) {
Robert Phillips33f02ed2018-03-27 08:06:57 -04002154 sk_sp<SkImage> rasterImage = image->makeRasterImage(); // force decoding of lazy images
2155
2156 SkImageInfo ii = SkImageInfo::Make(rasterImage->width(), rasterImage->height(),
2157 rasterImage->colorType(), rasterImage->alphaType(),
2158 rasterImage->refColorSpace());
2159
2160 SkBitmap bm;
2161 bm.allocPixels(ii);
2162
2163 if (!rasterImage->readPixels(bm.pixmap(), 0, 0)) {
2164 return -1;
2165 }
2166
2167 bm.setImmutable();
2168
2169 PromiseImageInfo newImageInfo;
2170 newImageInfo.fIndex = fImageInfo.count();
2171 newImageInfo.fOriginalUniqueID = image->uniqueID();
2172 newImageInfo.fBitmap = bm;
Robert Phillipsa479f962018-04-10 11:45:40 -04002173 /* fCallbackContext is filled in by uploadAllToGPU */
Robert Phillips33f02ed2018-03-27 08:06:57 -04002174
2175 fImageInfo.push_back(newImageInfo);
2176 SkASSERT(newImageInfo.fIndex == fImageInfo.count()-1);
2177 return fImageInfo.count()-1;
2178 }
2179
2180 SkTArray<PromiseImageInfo> fImageInfo;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002181};
2182
2183// TileData class encapsulates the information and behavior for a single tile/thread in
2184// a DDL rendering.
2185class ViaDDL::TileData {
2186public:
2187 // Note: we could just pass in surface characterization
2188 TileData(sk_sp<SkSurface> surf, const SkIRect& clip)
2189 : fSurface(std::move(surf))
2190 , fClip(clip) {
2191 SkAssertResult(fSurface->characterize(&fCharacterization));
2192 }
2193
2194 // This method operates in parallel
2195 // In each thread we will reconvert the compressedPictureData into an SkPicture
2196 // replacing each image-index with a promise image.
2197 void preprocess(SkData* compressedPictureData, const PromiseImageHelper& helper) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002198
Robert Phillips33f02ed2018-03-27 08:06:57 -04002199 SkDeferredDisplayListRecorder recorder(fCharacterization);
2200
2201 // DDL TODO: the DDLRecorder's GrContext isn't initialized until getCanvas is called.
2202 // Maybe set it up in the ctor?
2203 SkCanvas* subCanvas = recorder.getCanvas();
2204
2205 sk_sp<SkPicture> reconstitutedPicture;
2206
2207 {
Robert Phillipsa479f962018-04-10 11:45:40 -04002208 PerRecorderContext perRecorderContext { &recorder, &helper };
Robert Phillips33f02ed2018-03-27 08:06:57 -04002209
2210 SkDeserialProcs procs;
Robert Phillipsa479f962018-04-10 11:45:40 -04002211 procs.fImageCtx = (void*) &perRecorderContext;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002212 procs.fImageProc = PromiseImageCreator;
2213
2214 reconstitutedPicture = SkPicture::MakeFromData(compressedPictureData, &procs);
2215 if (!reconstitutedPicture) {
2216 return;
2217 }
2218 }
2219
2220 subCanvas->clipRect(SkRect::MakeWH(fClip.width(), fClip.height()));
2221 subCanvas->translate(-fClip.fLeft, -fClip.fTop);
2222
2223 // Note: in this use case we only render a picture to the deferred canvas
2224 // but, more generally, clients will use arbitrary draw calls.
2225 subCanvas->drawPicture(reconstitutedPicture);
2226
2227 fDisplayList = recorder.detach();
2228 }
2229
2230 // This method operates serially and replays the recorded DDL into the tile surface.
2231 void draw() {
2232 fSurface->draw(fDisplayList.get());
2233 }
2234
2235 // This method also operates serially and composes the results of replaying the DDL into
2236 // the final destination surface.
2237 void compose(SkCanvas* dst) {
2238 sk_sp<SkImage> img = fSurface->makeImageSnapshot();
2239 dst->save();
2240 dst->clipRect(SkRect::Make(fClip));
2241 dst->drawImage(std::move(img), fClip.fLeft, fClip.fTop);
2242 dst->restore();
2243 }
2244
2245private:
Robert Phillipsa479f962018-04-10 11:45:40 -04002246 // This stack-based context allows each thread to re-inflate the image indices into
2247 // promise images while still using the same GrBackendTexture.
2248 struct PerRecorderContext {
2249 SkDeferredDisplayListRecorder* fRecorder;
2250 const PromiseImageHelper* fHelper;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002251 };
2252
2253 // This generates promise images to replace the indices in the compressed picture. This
Robert Phillipsa479f962018-04-10 11:45:40 -04002254 // reconstitution is performed separately in each thread so we end up with multiple
2255 // promise images referring to the same GrBackendTexture.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002256 static sk_sp<SkImage> PromiseImageCreator(const void* rawData, size_t length, void* ctxIn) {
Robert Phillipsa479f962018-04-10 11:45:40 -04002257 PerRecorderContext* perRecorderContext = static_cast<PerRecorderContext*>(ctxIn);
2258 const PromiseImageHelper* helper = perRecorderContext->fHelper;
2259 SkDeferredDisplayListRecorder* recorder = perRecorderContext->fRecorder;
Robert Phillips33f02ed2018-03-27 08:06:57 -04002260
2261 SkASSERT(length == sizeof(int));
2262
2263 const int* indexPtr = static_cast<const int*>(rawData);
2264 SkASSERT(helper->isValidID(*indexPtr));
2265
Robert Phillipsa479f962018-04-10 11:45:40 -04002266 const PromiseImageHelper::PromiseImageInfo& curImage = helper->getInfo(*indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002267
Robert Phillipsa479f962018-04-10 11:45:40 -04002268 if (!curImage.fCallbackContext->backendTexture().isValid()) {
Robert Phillipsc186e172018-04-17 16:09:28 -04002269 // We weren't able to make a backend texture for this SkImage. In this case we create
2270 // a separate bitmap-backed image for each thread.
2271 // Note: we would like to share the same bitmap between all the threads but
2272 // SkBitmap is not thread-safe.
2273 return SkImage::MakeRasterCopy(curImage.fBitmap.pixmap());
Robert Phillipsa479f962018-04-10 11:45:40 -04002274 }
2275 SkASSERT(curImage.fIndex == *indexPtr);
Robert Phillips33f02ed2018-03-27 08:06:57 -04002276
Robert Phillipsa479f962018-04-10 11:45:40 -04002277 GrBackendFormat backendFormat = curImage.fCallbackContext->backendTexture().format();
2278
2279 // Each DDL recorder gets its own ref on the promise callback context for the
2280 // promise images it creates.
Robert Phillips33f02ed2018-03-27 08:06:57 -04002281 // DDL TODO: sort out mipmapping
2282 sk_sp<SkImage> image = recorder->makePromiseTexture(
Robert Phillipsa479f962018-04-10 11:45:40 -04002283 backendFormat,
2284 curImage.fBitmap.width(),
2285 curImage.fBitmap.height(),
2286 GrMipMapped::kNo,
2287 GrSurfaceOrigin::kTopLeft_GrSurfaceOrigin,
2288 curImage.fBitmap.colorType(),
2289 curImage.fBitmap.alphaType(),
2290 curImage.fBitmap.refColorSpace(),
2291 PromiseImageHelper::PromiseImageFulfillProc,
2292 PromiseImageHelper::PromiseImageReleaseProc,
2293 PromiseImageHelper::PromiseImageDoneProc,
2294 (void*) SkSafeRef(curImage.fCallbackContext.get()));
Robert Phillips33f02ed2018-03-27 08:06:57 -04002295 SkASSERT(image);
2296 return image;
2297 }
2298
2299 sk_sp<SkSurface> fSurface;
2300 SkIRect fClip; // in the device space of the dest canvas
2301 std::unique_ptr<SkDeferredDisplayList> fDisplayList;
2302 SkSurfaceCharacterization fCharacterization;
2303};
2304
2305Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2306 auto size = src.size();
2307 SkPictureRecorder recorder;
2308 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2309 SkIntToScalar(size.height())));
2310 if (!err.isEmpty()) {
2311 return err;
2312 }
2313 sk_sp<SkPicture> inputPicture(recorder.finishRecordingAsPicture());
2314
2315 // this is our ultimate final drawing area/rect
2316 SkIRect viewport = SkIRect::MakeWH(size.fWidth, size.fHeight);
2317
2318 PromiseImageHelper helper;
2319 sk_sp<SkData> compressedPictureData;
2320
2321 // Convert the SkPicture into SkData replacing all the SkImages with an index.
2322 {
2323 SkSerialProcs procs;
2324
2325 procs.fImageCtx = &helper;
2326 procs.fImageProc = [](SkImage* image, void* ctx) -> sk_sp<SkData> {
2327 auto helper = static_cast<PromiseImageHelper*>(ctx);
2328
2329 int id = helper->findOrDefineImage(image);
2330 if (id >= 0) {
2331 SkASSERT(helper->isValidID(id));
2332 return SkData::MakeWithCopy(&id, sizeof(id));
2333 }
2334
2335 return nullptr;
2336 };
2337
2338 compressedPictureData = inputPicture->serialize(&procs);
2339 if (!compressedPictureData) {
2340 return SkStringPrintf("ViaDDL: Couldn't deflate SkPicture");
2341 }
2342 }
2343
Robert Phillips33f02ed2018-03-27 08:06:57 -04002344 return draw_to_canvas(fSink.get(), bitmap, stream, log, size,
2345 [&](SkCanvas* canvas) -> Error {
2346 GrContext* context = canvas->getGrContext();
2347 if (!context || !context->contextPriv().getGpu()) {
2348 return SkStringPrintf("DDLs are GPU only");
2349 }
2350
Robert Phillipsa479f962018-04-10 11:45:40 -04002351 // This is here bc this is the first point where we have access to the context
Robert Phillips33f02ed2018-03-27 08:06:57 -04002352 helper.uploadAllToGPU(context);
2353
2354 int xTileSize = viewport.width()/fNumDivisions;
2355 int yTileSize = viewport.height()/fNumDivisions;
2356
2357 SkTArray<TileData> tileData;
2358 tileData.reserve(fNumDivisions*fNumDivisions);
2359
2360 // First, create the destination tiles
2361 for (int y = 0, yOff = 0; y < fNumDivisions; ++y, yOff += yTileSize) {
2362 int ySize = (y < fNumDivisions-1) ? yTileSize : viewport.height()-yOff;
2363
2364 for (int x = 0, xOff = 0; x < fNumDivisions; ++x, xOff += xTileSize) {
2365 int xSize = (x < fNumDivisions-1) ? xTileSize : viewport.width()-xOff;
2366
2367 SkIRect clip = SkIRect::MakeXYWH(xOff, yOff, xSize, ySize);
2368
2369 SkASSERT(viewport.contains(clip));
2370
2371 SkImageInfo tileII = SkImageInfo::MakeN32Premul(xSize, ySize);
2372
2373 tileData.push_back(TileData(canvas->makeSurface(tileII), clip));
2374 }
2375 }
2376
2377 // Second, run the cpu pre-processing in threads
2378 SkTaskGroup().batch(tileData.count(), [&](int i) {
2379 tileData[i].preprocess(compressedPictureData.get(), helper);
2380 });
2381
Robert Phillipsa479f962018-04-10 11:45:40 -04002382 // This drops the helper's refs on all the promise images
2383 helper.reset();
2384
Robert Phillips33f02ed2018-03-27 08:06:57 -04002385 // Third, synchronously render the display lists into the dest tiles
2386 // TODO: it would be cool to not wait until all the tiles are drawn to begin
2387 // drawing to the GPU and composing to the final surface
2388 for (int i = 0; i < tileData.count(); ++i) {
2389 tileData[i].draw();
2390 }
2391
2392 // Finally, compose the drawn tiles into the result
2393 // Note: the separation between the tiles and the final composition better
2394 // matches Chrome but costs us a copy
2395 for (int i = 0; i < tileData.count(); ++i) {
2396 tileData[i].compose(canvas);
2397 }
2398
Robert Phillipscc473352018-03-27 10:46:00 -04002399 context->flush();
Robert Phillips33f02ed2018-03-27 08:06:57 -04002400 return "";
2401 });
2402}
2403
2404#else
2405
2406ViaDDL::ViaDDL(int numDivisions, Sink* sink) : Via(sink) { }
2407
2408Error ViaDDL::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2409 return "ViaDDL is GPU only";
2410}
2411
2412#endif
2413
2414/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2415
mtklein4a34ecb2016-01-08 10:19:35 -08002416Error ViaPicture::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2417 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002418 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
mtklein4a34ecb2016-01-08 10:19:35 -08002419 SkPictureRecorder recorder;
reedca2622b2016-03-18 07:25:55 -07002420 sk_sp<SkPicture> pic;
mtklein4a34ecb2016-01-08 10:19:35 -08002421 Error err = src.draw(recorder.beginRecording(SkIntToScalar(size.width()),
2422 SkIntToScalar(size.height())));
2423 if (!err.isEmpty()) {
2424 return err;
2425 }
reedca2622b2016-03-18 07:25:55 -07002426 pic = recorder.finishRecordingAsPicture();
mtklein4a34ecb2016-01-08 10:19:35 -08002427 canvas->drawPicture(pic);
Ben Wagner1861e882018-04-04 17:40:46 -04002428 return err;
mtklein4a34ecb2016-01-08 10:19:35 -08002429 });
Ben Wagner1861e882018-04-04 17:40:46 -04002430 if (!err.isEmpty()) {
2431 return err;
2432 }
2433
2434 return check_against_reference(bitmap, src, fSink.get());
mtklein4a34ecb2016-01-08 10:19:35 -08002435}
2436
2437/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2438
reed54dc4872016-09-13 08:09:45 -07002439Error ViaPipe::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2440 auto size = src.size();
Ben Wagner1861e882018-04-04 17:40:46 -04002441 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
reed54dc4872016-09-13 08:09:45 -07002442 SkDynamicMemoryWStream tmpStream;
2443 Error err = src.draw(SkPipeSerializer().beginWrite(SkRect::Make(size), &tmpStream));
2444 if (!err.isEmpty()) {
2445 return err;
2446 }
2447 sk_sp<SkData> data = tmpStream.detachAsData();
2448 SkPipeDeserializer().playback(data->data(), data->size(), canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002449 return err;
reed54dc4872016-09-13 08:09:45 -07002450 });
Ben Wagner1861e882018-04-04 17:40:46 -04002451 if (!err.isEmpty()) {
2452 return err;
2453 }
2454
2455 return check_against_reference(bitmap, src, fSink.get());
reed54dc4872016-09-13 08:09:45 -07002456}
2457
2458/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2459
Mike Reedbae888e2017-02-18 16:50:45 -05002460#ifdef TEST_VIA_SVG
Mike Reedf67c4592017-02-17 17:06:11 -05002461#include "SkXMLWriter.h"
2462#include "SkSVGCanvas.h"
2463#include "SkSVGDOM.h"
2464
2465Error ViaSVG::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2466 auto size = src.size();
2467 return draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) -> Error {
2468 SkDynamicMemoryWStream wstream;
2469 SkXMLStreamWriter writer(&wstream);
2470 Error err = src.draw(SkSVGCanvas::Make(SkRect::Make(size), &writer).get());
2471 if (!err.isEmpty()) {
2472 return err;
2473 }
2474 std::unique_ptr<SkStream> rstream(wstream.detachAsStream());
2475 auto dom = SkSVGDOM::MakeFromStream(*rstream);
2476 if (dom) {
2477 dom->setContainerSize(SkSize::Make(size));
2478 dom->render(canvas);
2479 }
2480 return "";
2481 });
2482}
Mike Reedbae888e2017-02-18 16:50:45 -05002483#endif
Mike Reedf67c4592017-02-17 17:06:11 -05002484
2485/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2486
mtklein9c5052f2016-08-06 12:51:51 -07002487Error ViaLite::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2488 auto size = src.size();
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002489 SkIRect bounds = {0,0, size.width(), size.height()};
Ben Wagner1861e882018-04-04 17:40:46 -04002490 Error err = draw_to_canvas(fSink.get(), bitmap, stream, log, size, [&](SkCanvas* canvas) {
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002491 SkLiteDL dl;
mtklein8bbbb692016-08-15 12:56:00 -07002492 SkLiteRecorder rec;
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002493 rec.reset(&dl, bounds);
mtklein8bbbb692016-08-15 12:56:00 -07002494
2495 Error err = src.draw(&rec);
mtklein9c5052f2016-08-06 12:51:51 -07002496 if (!err.isEmpty()) {
2497 return err;
2498 }
Derek Sollenbergerd7875f52017-03-01 15:33:23 -05002499 dl.draw(canvas);
Ben Wagner1861e882018-04-04 17:40:46 -04002500 return err;
mtklein9c5052f2016-08-06 12:51:51 -07002501 });
Ben Wagner1861e882018-04-04 17:40:46 -04002502 if (!err.isEmpty()) {
2503 return err;
2504 }
2505
2506 return check_against_reference(bitmap, src, fSink.get());
mtklein9c5052f2016-08-06 12:51:51 -07002507}
2508
Mike Klein841101d2017-03-10 09:55:51 -05002509/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
2510
Mike Klein919cc452017-03-18 15:36:52 +00002511ViaCSXform::ViaCSXform(Sink* sink, sk_sp<SkColorSpace> cs, bool colorSpin)
2512 : Via(sink)
2513 , fCS(std::move(cs))
2514 , fColorSpin(colorSpin) {}
Mike Klein841101d2017-03-10 09:55:51 -05002515
2516Error ViaCSXform::draw(const Src& src, SkBitmap* bitmap, SkWStream* stream, SkString* log) const {
2517 return draw_to_canvas(fSink.get(), bitmap, stream, log, src.size(),
2518 [&](SkCanvas* canvas) -> Error {
Brian Osman5b7e4702017-10-31 16:41:29 -04002519 {
2520 SkAutoCanvasRestore acr(canvas, true);
2521 auto proxy = SkCreateColorSpaceXformCanvas(canvas, fCS);
2522 Error err = src.draw(proxy.get());
2523 if (!err.isEmpty()) {
2524 return err;
2525 }
Mike Klein919cc452017-03-18 15:36:52 +00002526 }
2527
2528 // Undo the color spin, so we can look at the pixels in Gold.
2529 if (fColorSpin) {
2530 SkBitmap pixels;
2531 pixels.allocPixels(canvas->imageInfo());
Mike Reed12e946b2017-04-17 10:53:29 -04002532 canvas->readPixels(pixels, 0, 0);
Mike Klein919cc452017-03-18 15:36:52 +00002533
Brian Osman5b7e4702017-10-31 16:41:29 -04002534 SkPaint rotateColors;
2535 SkScalar matrix[20] = { 0, 0, 1, 0, 0, // B -> R
2536 1, 0, 0, 0, 0, // R -> G
2537 0, 1, 0, 0, 0, // G -> B
2538 0, 0, 0, 1, 0 };
2539 rotateColors.setBlendMode(SkBlendMode::kSrc);
2540 rotateColors.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(matrix));
2541 canvas->drawBitmap(pixels, 0, 0, &rotateColors);
Mike Klein919cc452017-03-18 15:36:52 +00002542 }
2543
2544 return "";
Mike Klein841101d2017-03-10 09:55:51 -05002545 });
2546}
2547
mtklein748ca3b2015-01-15 10:56:12 -08002548} // namespace DM