blob: 2c601fadb0e3f9a037ff51a66b8171d28e83106c [file] [log] [blame]
halcanarya096d7a2015-03-27 12:16:53 -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
Leon Scroggins III932efed2016-12-16 11:39:51 -05008#include "FakeStreams.h"
halcanarya096d7a2015-03-27 12:16:53 -07009#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -070010#include "SkAndroidCodec.h"
Hal Canary95e3c052017-01-11 12:44:43 -050011#include "SkAutoMalloc.h"
halcanarya096d7a2015-03-27 12:16:53 -070012#include "SkBitmap.h"
13#include "SkCodec.h"
msarettedd2dcf2016-01-14 13:12:26 -080014#include "SkCodecImageGenerator.h"
raftias94888332016-10-18 10:02:51 -070015#include "SkColorSpace_XYZ.h"
Matt Sarett0e032be2017-03-15 17:50:08 -040016#include "SkColorSpacePriv.h"
msarette6dd0042015-10-09 11:07:34 -070017#include "SkData.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000018#include "SkFrontBufferedStream.h"
Hal Canary95e3c052017-01-11 12:44:43 -050019#include "SkImageEncoder.h"
Matt Sarett0e032be2017-03-15 17:50:08 -040020#include "SkImageEncoderPriv.h"
halcanarya096d7a2015-03-27 12:16:53 -070021#include "SkMD5.h"
Leon Scroggins III0354c622017-02-24 15:33:24 -050022#include "SkOSPath.h"
Hal Canary95e3c052017-01-11 12:44:43 -050023#include "SkPngChunkReader.h"
scroggob636b452015-07-22 07:16:20 -070024#include "SkRandom.h"
scroggocf98fa92015-11-23 08:14:40 -080025#include "SkStream.h"
scroggob9a1e342015-11-30 06:25:31 -080026#include "SkStreamPriv.h"
halcanarya096d7a2015-03-27 12:16:53 -070027#include "Test.h"
28
scroggocf98fa92015-11-23 08:14:40 -080029#include "png.h"
30
Hal Canarydb683012016-11-23 08:55:18 -070031#include "sk_tool_utils.h"
32
scroggo8e6c7ad2016-09-16 08:20:38 -070033#if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
34 // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In
35 // the meantime, we had to break some pieces of SkPngCodec in order to support Google3.
36 // The parts that are broken are likely not used by Google3.
37 #define SK_PNG_DISABLE_TESTS
38#endif
39
halcanarya096d7a2015-03-27 12:16:53 -070040static void md5(const SkBitmap& bm, SkMD5::Digest* digest) {
41 SkAutoLockPixels autoLockPixels(bm);
42 SkASSERT(bm.getPixels());
43 SkMD5 md5;
44 size_t rowLen = bm.info().bytesPerPixel() * bm.width();
45 for (int y = 0; y < bm.height(); ++y) {
halcanary1e903042016-04-25 10:29:36 -070046 md5.write(bm.getAddr(0, y), rowLen);
halcanarya096d7a2015-03-27 12:16:53 -070047 }
48 md5.finish(*digest);
49}
50
scroggo9b2cdbf42015-07-10 12:07:02 -070051/**
52 * Compute the digest for bm and compare it to a known good digest.
53 * @param r Reporter to assert that bm's digest matches goodDigest.
54 * @param goodDigest The known good digest to compare to.
55 * @param bm The bitmap to test.
56 */
57static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
58 const SkBitmap& bm) {
59 SkMD5::Digest digest;
60 md5(bm, &digest);
61 REPORTER_ASSERT(r, digest == goodDigest);
62}
63
scroggod1bc5742015-08-12 08:31:44 -070064/**
65 * Test decoding an SkCodec to a particular SkImageInfo.
66 *
halcanary96fcdcc2015-08-27 07:41:13 -070067 * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
scroggod1bc5742015-08-12 08:31:44 -070068 * the resulting decode should match.
69 */
scroggo7b5e5532016-02-04 06:14:24 -080070template<typename Codec>
71static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
scroggod1bc5742015-08-12 08:31:44 -070072 SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
73 SkBitmap bm;
74 bm.allocPixels(info);
75 SkAutoLockPixels autoLockPixels(bm);
76
77 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
78 REPORTER_ASSERT(r, result == expectedResult);
79
80 if (goodDigest) {
81 compare_to_good_digest(r, *goodDigest, bm);
82 }
83}
84
scroggob636b452015-07-22 07:16:20 -070085SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
86 SkIRect rect;
87 do {
88 rect.fLeft = rand->nextRangeU(0, w);
89 rect.fTop = rand->nextRangeU(0, h);
90 rect.fRight = rand->nextRangeU(0, w);
91 rect.fBottom = rand->nextRangeU(0, h);
92 rect.sort();
93 } while (rect.isEmpty());
94 return rect;
95}
96
scroggo8e6c7ad2016-09-16 08:20:38 -070097static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
98 const SkMD5::Digest& goodDigest) {
99 SkBitmap bm;
100 bm.allocPixels(info);
101 SkAutoLockPixels autoLockPixels(bm);
102
103 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
104 bm.rowBytes()));
105
106 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
107
108 compare_to_good_digest(r, goodDigest, bm);
109}
110
111// Test in stripes, similar to DM's kStripe_Mode
112static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
113 const SkMD5::Digest& goodDigest) {
114 SkBitmap bm;
115 bm.allocPixels(info);
116 bm.eraseColor(SK_ColorYELLOW);
117
118 const int height = info.height();
119 // Note that if numStripes does not evenly divide height there will be an extra
120 // stripe.
121 const int numStripes = 4;
122
123 if (numStripes > height) {
124 // Image is too small.
125 return;
126 }
127
128 const int stripeHeight = height / numStripes;
129
130 // Iterate through the image twice. Once to decode odd stripes, and once for even.
131 for (int oddEven = 1; oddEven >= 0; oddEven--) {
132 for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
133 SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
134 SkTMin(y + stripeHeight, height));
135 SkCodec::Options options;
136 options.fSubset = &subset;
137 if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
138 bm.rowBytes(), &options)) {
139 ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
140 subset.top(), subset.bottom());
141 return;
142 }
143 if (SkCodec::kSuccess != codec->incrementalDecode()) {
144 ERRORF(r, "failed incremental decode starting from line %i\n", y);
145 return;
146 }
147 }
148 }
149
150 compare_to_good_digest(r, goodDigest, bm);
151}
152
scroggo7b5e5532016-02-04 06:14:24 -0800153template<typename Codec>
154static void test_codec(skiatest::Reporter* r, Codec* codec, SkBitmap& bm, const SkImageInfo& info,
scroggo27c17282015-10-27 08:14:46 -0700155 const SkISize& size, SkCodec::Result expectedResult, SkMD5::Digest* digest,
156 const SkMD5::Digest* goodDigest) {
msarette6dd0042015-10-09 11:07:34 -0700157
halcanarya096d7a2015-03-27 12:16:53 -0700158 REPORTER_ASSERT(r, info.dimensions() == size);
halcanarya096d7a2015-03-27 12:16:53 -0700159 bm.allocPixels(info);
160 SkAutoLockPixels autoLockPixels(bm);
msarettcc7f3052015-10-05 14:20:27 -0700161
162 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
msarette6dd0042015-10-09 11:07:34 -0700163 REPORTER_ASSERT(r, result == expectedResult);
halcanarya096d7a2015-03-27 12:16:53 -0700164
msarettcc7f3052015-10-05 14:20:27 -0700165 md5(bm, digest);
166 if (goodDigest) {
167 REPORTER_ASSERT(r, *digest == *goodDigest);
168 }
halcanarya096d7a2015-03-27 12:16:53 -0700169
msarett8ff6ca62015-09-18 12:06:04 -0700170 {
171 // Test decoding to 565
172 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
scroggoba584892016-05-20 13:56:13 -0700173 if (info.alphaType() == kOpaque_SkAlphaType) {
174 // Decoding to 565 should succeed.
175 SkBitmap bm565;
176 bm565.allocPixels(info565);
177 SkAutoLockPixels alp(bm565);
178
179 // This will allow comparison even if the image is incomplete.
180 bm565.eraseColor(SK_ColorBLACK);
181
182 REPORTER_ASSERT(r, expectedResult == codec->getPixels(info565,
183 bm565.getPixels(), bm565.rowBytes()));
184
185 SkMD5::Digest digest565;
186 md5(bm565, &digest565);
187
188 // A dumb client's request for non-opaque should also succeed.
189 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
190 info565 = info565.makeAlphaType(alpha);
191 test_info(r, codec, info565, expectedResult, &digest565);
192 }
193 } else {
194 test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
195 }
196 }
197
198 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
199 SkImageInfo grayInfo = codec->getInfo();
200 SkBitmap grayBm;
201 grayBm.allocPixels(grayInfo);
202 SkAutoLockPixels alp(grayBm);
203
204 grayBm.eraseColor(SK_ColorBLACK);
205
206 REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
207 grayBm.getPixels(), grayBm.rowBytes()));
208
209 SkMD5::Digest grayDigest;
210 md5(grayBm, &grayDigest);
211
212 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
213 grayInfo = grayInfo.makeAlphaType(alpha);
214 test_info(r, codec, grayInfo, expectedResult, &grayDigest);
215 }
msarett8ff6ca62015-09-18 12:06:04 -0700216 }
217
218 // Verify that re-decoding gives the same result. It is interesting to check this after
219 // a decode to 565, since choosing to decode to 565 may result in some of the decode
220 // options being modified. These options should return to their defaults on another
221 // decode to kN32, so the new digest should match the old digest.
msarette6dd0042015-10-09 11:07:34 -0700222 test_info(r, codec, info, expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700223
224 {
225 // Check alpha type conversions
226 if (info.alphaType() == kOpaque_SkAlphaType) {
227 test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800228 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700229 test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800230 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700231 } else {
232 // Decoding to opaque should fail
233 test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
halcanary96fcdcc2015-08-27 07:41:13 -0700234 SkCodec::kInvalidConversion, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700235 SkAlphaType otherAt = info.alphaType();
236 if (kPremul_SkAlphaType == otherAt) {
237 otherAt = kUnpremul_SkAlphaType;
238 } else {
239 otherAt = kPremul_SkAlphaType;
240 }
241 // The other non-opaque alpha type should always succeed, but not match.
msarette6dd0042015-10-09 11:07:34 -0700242 test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700243 }
244 }
msarettcc7f3052015-10-05 14:20:27 -0700245}
246
scroggobed1ed62016-02-11 10:24:55 -0800247static bool supports_partial_scanlines(const char path[]) {
scroggo2c3b2182015-10-09 08:40:59 -0700248 static const char* const exts[] = {
249 "jpg", "jpeg", "png", "webp"
250 "JPG", "JPEG", "PNG", "WEBP"
251 };
252
253 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
254 if (SkStrEndsWith(path, exts[i])) {
255 return true;
256 }
257 }
258 return false;
259}
260
scroggo8e6c7ad2016-09-16 08:20:38 -0700261// FIXME: Break up this giant function
msarettcc7f3052015-10-05 14:20:27 -0700262static void check(skiatest::Reporter* r,
263 const char path[],
264 SkISize size,
265 bool supportsScanlineDecoding,
266 bool supportsSubsetDecoding,
scroggo8e6c7ad2016-09-16 08:20:38 -0700267 bool supportsIncomplete,
268 bool supportsNewScanlineDecoding = false) {
msarettcc7f3052015-10-05 14:20:27 -0700269
Ben Wagner145dbcd2016-11-03 14:40:50 -0400270 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700271 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700272 return;
273 }
msarette6dd0042015-10-09 11:07:34 -0700274
Ben Wagner145dbcd2016-11-03 14:40:50 -0400275 std::unique_ptr<SkCodec> codec(nullptr);
msarette6dd0042015-10-09 11:07:34 -0700276 bool isIncomplete = supportsIncomplete;
277 if (isIncomplete) {
278 size_t size = stream->getLength();
Ben Wagner145dbcd2016-11-03 14:40:50 -0400279 sk_sp<SkData> data((SkData::MakeFromStream(stream.get(), 2 * size / 3)));
reed42943c82016-09-12 12:01:44 -0700280 codec.reset(SkCodec::NewFromData(data));
msarette6dd0042015-10-09 11:07:34 -0700281 } else {
mtklein18300a32016-03-16 13:53:35 -0700282 codec.reset(SkCodec::NewFromStream(stream.release()));
msarette6dd0042015-10-09 11:07:34 -0700283 }
msarettcc7f3052015-10-05 14:20:27 -0700284 if (!codec) {
285 ERRORF(r, "Unable to decode '%s'", path);
286 return;
287 }
288
289 // Test full image decodes with SkCodec
290 SkMD5::Digest codecDigest;
scroggoef0fed32016-02-18 05:59:25 -0800291 const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
msarettcc7f3052015-10-05 14:20:27 -0700292 SkBitmap bm;
msarette6dd0042015-10-09 11:07:34 -0700293 SkCodec::Result expectedResult = isIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
scroggo7b5e5532016-02-04 06:14:24 -0800294 test_codec(r, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700295
296 // Scanline decoding follows.
scroggod8d68552016-06-06 11:26:17 -0700297
scroggo8e6c7ad2016-09-16 08:20:38 -0700298 if (supportsNewScanlineDecoding && !isIncomplete) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400299 test_incremental_decode(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700300 // This is only supported by codecs that use incremental decoding to
301 // support subset decodes - png and jpeg (once SkJpegCodec is
302 // converted).
303 if (SkStrEndsWith(path, "png") || SkStrEndsWith(path, "PNG")) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400304 test_in_stripes(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700305 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700306 }
307
308 // Need to call startScanlineDecode() first.
309 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
310 REPORTER_ASSERT(r, !codec->skipScanlines(1));
scroggo46c57472015-09-30 08:57:13 -0700311 const SkCodec::Result startResult = codec->startScanlineDecode(info);
scroggo58421542015-04-01 11:25:20 -0700312 if (supportsScanlineDecoding) {
313 bm.eraseColor(SK_ColorYELLOW);
msarettc0e80c12015-07-01 06:50:35 -0700314
scroggo46c57472015-09-30 08:57:13 -0700315 REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
scroggo9b2cdbf42015-07-10 12:07:02 -0700316
scroggo58421542015-04-01 11:25:20 -0700317 for (int y = 0; y < info.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700318 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
319 if (!isIncomplete) {
320 REPORTER_ASSERT(r, 1 == lines);
321 }
scroggo58421542015-04-01 11:25:20 -0700322 }
323 // verify that scanline decoding gives the same result.
scroggo46c57472015-09-30 08:57:13 -0700324 if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
msarettcc7f3052015-10-05 14:20:27 -0700325 compare_to_good_digest(r, codecDigest, bm);
msarett5406d6f2015-08-31 06:55:13 -0700326 }
scroggo46c57472015-09-30 08:57:13 -0700327
328 // Cannot continue to decode scanlines beyond the end
329 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700330 == 0);
scroggo46c57472015-09-30 08:57:13 -0700331
332 // Interrupting a scanline decode with a full decode starts from
333 // scratch
334 REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
msarette6dd0042015-10-09 11:07:34 -0700335 const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
336 if (!isIncomplete) {
337 REPORTER_ASSERT(r, lines == 1);
338 }
scroggo46c57472015-09-30 08:57:13 -0700339 REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
msarette6dd0042015-10-09 11:07:34 -0700340 == expectedResult);
scroggo46c57472015-09-30 08:57:13 -0700341 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700342 == 0);
scroggo46c57472015-09-30 08:57:13 -0700343 REPORTER_ASSERT(r, codec->skipScanlines(1)
msarette6dd0042015-10-09 11:07:34 -0700344 == 0);
msarett80803ff2015-10-16 10:54:12 -0700345
346 // Test partial scanline decodes
scroggobed1ed62016-02-11 10:24:55 -0800347 if (supports_partial_scanlines(path) && info.width() >= 3) {
msarett80803ff2015-10-16 10:54:12 -0700348 SkCodec::Options options;
349 int width = info.width();
350 int height = info.height();
351 SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
352 options.fSubset = &subset;
353
354 const SkCodec::Result partialStartResult = codec->startScanlineDecode(info, &options,
355 nullptr, nullptr);
356 REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
357
358 for (int y = 0; y < height; y++) {
359 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
360 if (!isIncomplete) {
361 REPORTER_ASSERT(r, 1 == lines);
362 }
363 }
364 }
scroggo58421542015-04-01 11:25:20 -0700365 } else {
scroggo46c57472015-09-30 08:57:13 -0700366 REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
halcanarya096d7a2015-03-27 12:16:53 -0700367 }
scroggob636b452015-07-22 07:16:20 -0700368
369 // The rest of this function tests decoding subsets, and will decode an arbitrary number of
370 // random subsets.
371 // Do not attempt to decode subsets of an image of only once pixel, since there is no
372 // meaningful subset.
373 if (size.width() * size.height() == 1) {
374 return;
375 }
376
377 SkRandom rand;
378 SkIRect subset;
379 SkCodec::Options opts;
380 opts.fSubset = &subset;
381 for (int i = 0; i < 5; i++) {
382 subset = generate_random_subset(&rand, size.width(), size.height());
383 SkASSERT(!subset.isEmpty());
384 const bool supported = codec->getValidSubset(&subset);
385 REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
386
387 SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height());
388 SkBitmap bm;
389 bm.allocPixels(subsetInfo);
390 const SkCodec::Result result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(),
halcanary96fcdcc2015-08-27 07:41:13 -0700391 &opts, nullptr, nullptr);
scroggob636b452015-07-22 07:16:20 -0700392
393 if (supportsSubsetDecoding) {
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500394 if (expectedResult == SkCodec::kSuccess) {
395 REPORTER_ASSERT(r, result == expectedResult);
396 } else {
397 SkASSERT(expectedResult == SkCodec::kIncompleteInput);
398 REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput
399 || result == SkCodec::kSuccess);
400 }
scroggob636b452015-07-22 07:16:20 -0700401 // Webp is the only codec that supports subsets, and it will have modified the subset
402 // to have even left/top.
403 REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
404 } else {
405 // No subsets will work.
406 REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
407 }
408 }
msarettcc7f3052015-10-05 14:20:27 -0700409
scroggobed1ed62016-02-11 10:24:55 -0800410 // SkAndroidCodec tests
scroggo8e6c7ad2016-09-16 08:20:38 -0700411 if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
scroggo2c3b2182015-10-09 08:40:59 -0700412
Ben Wagner145dbcd2016-11-03 14:40:50 -0400413 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700414 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700415 return;
416 }
msarette6dd0042015-10-09 11:07:34 -0700417
Ben Wagner145dbcd2016-11-03 14:40:50 -0400418 std::unique_ptr<SkAndroidCodec> androidCodec(nullptr);
msarette6dd0042015-10-09 11:07:34 -0700419 if (isIncomplete) {
420 size_t size = stream->getLength();
Ben Wagner145dbcd2016-11-03 14:40:50 -0400421 sk_sp<SkData> data((SkData::MakeFromStream(stream.get(), 2 * size / 3)));
reed42943c82016-09-12 12:01:44 -0700422 androidCodec.reset(SkAndroidCodec::NewFromData(data));
msarette6dd0042015-10-09 11:07:34 -0700423 } else {
mtklein18300a32016-03-16 13:53:35 -0700424 androidCodec.reset(SkAndroidCodec::NewFromStream(stream.release()));
msarette6dd0042015-10-09 11:07:34 -0700425 }
scroggo7b5e5532016-02-04 06:14:24 -0800426 if (!androidCodec) {
msarettcc7f3052015-10-05 14:20:27 -0700427 ERRORF(r, "Unable to decode '%s'", path);
428 return;
429 }
430
431 SkBitmap bm;
scroggobed1ed62016-02-11 10:24:55 -0800432 SkMD5::Digest androidCodecDigest;
433 test_codec(r, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
scroggo7b5e5532016-02-04 06:14:24 -0800434 &codecDigest);
msarette6dd0042015-10-09 11:07:34 -0700435 }
436
msarettedd2dcf2016-01-14 13:12:26 -0800437 if (!isIncomplete) {
scroggoef0fed32016-02-18 05:59:25 -0800438 // Test SkCodecImageGenerator
Ben Wagner145dbcd2016-11-03 14:40:50 -0400439 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
440 sk_sp<SkData> fullData(SkData::MakeFromStream(stream.get(), stream->getLength()));
441 std::unique_ptr<SkImageGenerator> gen(
Mike Reed185130c2017-02-15 15:14:16 -0500442 SkCodecImageGenerator::MakeFromEncodedCodec(fullData));
msarettedd2dcf2016-01-14 13:12:26 -0800443 SkBitmap bm;
444 bm.allocPixels(info);
445 SkAutoLockPixels autoLockPixels(bm);
446 REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
447 compare_to_good_digest(r, codecDigest, bm);
scroggoef0fed32016-02-18 05:59:25 -0800448
scroggo8e6c7ad2016-09-16 08:20:38 -0700449#ifndef SK_PNG_DISABLE_TESTS
scroggod8d68552016-06-06 11:26:17 -0700450 // Test using SkFrontBufferedStream, as Android does
bungeman38d909e2016-08-02 14:40:46 -0700451 SkStream* bufferedStream = SkFrontBufferedStream::Create(
452 new SkMemoryStream(std::move(fullData)), SkCodec::MinBufferedBytesNeeded());
scroggod8d68552016-06-06 11:26:17 -0700453 REPORTER_ASSERT(r, bufferedStream);
454 codec.reset(SkCodec::NewFromStream(bufferedStream));
455 REPORTER_ASSERT(r, codec);
456 if (codec) {
457 test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
scroggoef0fed32016-02-18 05:59:25 -0800458 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700459#endif
msarettedd2dcf2016-01-14 13:12:26 -0800460 }
461
msarette6dd0042015-10-09 11:07:34 -0700462 // If we've just tested incomplete decodes, let's run the same test again on full decodes.
463 if (isIncomplete) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700464 check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false,
465 supportsNewScanlineDecoding);
msarettcc7f3052015-10-05 14:20:27 -0700466 }
halcanarya096d7a2015-03-27 12:16:53 -0700467}
468
Leon Scroggins III83926342016-12-06 10:58:02 -0500469DEF_TEST(Codec_wbmp, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700470 check(r, "mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500471}
halcanarya096d7a2015-03-27 12:16:53 -0700472
Leon Scroggins III83926342016-12-06 10:58:02 -0500473DEF_TEST(Codec_webp, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700474 check(r, "baby_tux.webp", SkISize::Make(386, 395), false, true, true);
475 check(r, "color_wheel.webp", SkISize::Make(128, 128), false, true, true);
476 check(r, "yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500477}
scroggo6f5e6192015-06-18 12:53:43 -0700478
Leon Scroggins III83926342016-12-06 10:58:02 -0500479DEF_TEST(Codec_bmp, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700480 check(r, "randPixels.bmp", SkISize::Make(8, 8), true, false, true);
481 check(r, "rle.bmp", SkISize::Make(320, 240), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500482}
halcanarya096d7a2015-03-27 12:16:53 -0700483
Leon Scroggins III83926342016-12-06 10:58:02 -0500484DEF_TEST(Codec_ico, r) {
msarette6dd0042015-10-09 11:07:34 -0700485 // FIXME: We are not ready to test incomplete ICOs
msarett68b204e2015-04-01 12:09:21 -0700486 // These two tests examine interestingly different behavior:
487 // Decodes an embedded BMP image
msarettbe8216a2015-12-04 08:00:50 -0800488 check(r, "color_wheel.ico", SkISize::Make(128, 128), true, false, false);
msarett68b204e2015-04-01 12:09:21 -0700489 // Decodes an embedded PNG image
scroggo8e6c7ad2016-09-16 08:20:38 -0700490 check(r, "google_chrome.ico", SkISize::Make(256, 256), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500491}
halcanarya096d7a2015-03-27 12:16:53 -0700492
Leon Scroggins III83926342016-12-06 10:58:02 -0500493DEF_TEST(Codec_gif, r) {
scroggo19b91532016-10-24 09:03:26 -0700494 check(r, "box.gif", SkISize::Make(200, 55), false, false, true, true);
495 check(r, "color_wheel.gif", SkISize::Make(128, 128), false, false, true, true);
msarette6dd0042015-10-09 11:07:34 -0700496 // randPixels.gif is too small to test incomplete
scroggo19b91532016-10-24 09:03:26 -0700497 check(r, "randPixels.gif", SkISize::Make(8, 8), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500498}
msarett438b2ad2015-04-09 12:43:10 -0700499
Leon Scroggins III83926342016-12-06 10:58:02 -0500500DEF_TEST(Codec_jpg, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700501 check(r, "CMYK.jpg", SkISize::Make(642, 516), true, false, true);
502 check(r, "color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700503 // grayscale.jpg is too small to test incomplete
scroggo27c17282015-10-27 08:14:46 -0700504 check(r, "grayscale.jpg", SkISize::Make(128, 128), true, false, false);
scroggo8e6c7ad2016-09-16 08:20:38 -0700505 check(r, "mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700506 // randPixels.jpg is too small to test incomplete
scroggo27c17282015-10-27 08:14:46 -0700507 check(r, "randPixels.jpg", SkISize::Make(8, 8), true, false, false);
Leon Scroggins III83926342016-12-06 10:58:02 -0500508}
msarette16b04a2015-04-15 07:32:19 -0700509
Leon Scroggins III83926342016-12-06 10:58:02 -0500510DEF_TEST(Codec_png, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700511 check(r, "arrow.png", SkISize::Make(187, 312), false, false, true, true);
512 check(r, "baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
513 check(r, "color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
514 // half-transparent-white-pixel.png is too small to test incomplete
515 check(r, "half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
516 check(r, "mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
517 check(r, "mandrill_16.png", SkISize::Make(16, 16), false, false, true, true);
518 check(r, "mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
519 check(r, "mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
520 check(r, "mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
521 check(r, "mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
522 check(r, "plane.png", SkISize::Make(250, 126), false, false, true, true);
523 check(r, "plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
524 check(r, "randPixels.png", SkISize::Make(8, 8), false, false, true, true);
525 check(r, "yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500526}
yujieqin916de9f2016-01-25 08:26:16 -0800527
yujieqinf236ee42016-02-29 07:14:42 -0800528// Disable RAW tests for Win32.
529#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Leon Scroggins III83926342016-12-06 10:58:02 -0500530DEF_TEST(Codec_raw, r) {
yujieqin916de9f2016-01-25 08:26:16 -0800531 check(r, "sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
ebrauer46d2aa82016-02-17 08:04:00 -0800532 check(r, "sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
yujieqin9c7a8a42016-02-05 08:21:19 -0800533 check(r, "dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
halcanarya096d7a2015-03-27 12:16:53 -0700534}
Leon Scroggins III83926342016-12-06 10:58:02 -0500535#endif
scroggo0a7e69c2015-04-03 07:22:22 -0700536
537static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
scroggo2c3b2182015-10-09 08:40:59 -0700538 // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
scroggo0a7e69c2015-04-03 07:22:22 -0700539 SkCodec* codec = SkCodec::NewFromStream(new SkMemoryStream(stream, len, false));
scroggo2c3b2182015-10-09 08:40:59 -0700540 REPORTER_ASSERT(r, !codec);
541
msarett3d9d7a72015-10-21 10:27:10 -0700542 SkAndroidCodec* androidCodec =
543 SkAndroidCodec::NewFromStream(new SkMemoryStream(stream, len, false));
544 REPORTER_ASSERT(r, !androidCodec);
scroggo0a7e69c2015-04-03 07:22:22 -0700545}
546
547// Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
548// even on failure. Test some bad streams.
549DEF_TEST(Codec_leaks, r) {
550 // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
551 const char nonSupportedStream[] = "hello world";
552 // The other strings should look like the beginning of a file type, so we'll call some
553 // internal version of NewFromStream, which must also delete the stream on failure.
554 const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
555 const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
556 const char emptyWebp[] = "RIFF1234WEBPVP";
557 const char emptyBmp[] = { 'B', 'M' };
558 const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
559 const char emptyGif[] = "GIFVER";
560
561 test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
562 test_invalid_stream(r, emptyPng, sizeof(emptyPng));
563 test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
564 test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
565 test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
566 test_invalid_stream(r, emptyIco, sizeof(emptyIco));
567 test_invalid_stream(r, emptyGif, sizeof(emptyGif));
568}
msarette16b04a2015-04-15 07:32:19 -0700569
scroggo2c3b2182015-10-09 08:40:59 -0700570DEF_TEST(Codec_null, r) {
scroggobed1ed62016-02-11 10:24:55 -0800571 // Attempting to create an SkCodec or an SkAndroidCodec with null should not
scroggo2c3b2182015-10-09 08:40:59 -0700572 // crash.
573 SkCodec* codec = SkCodec::NewFromStream(nullptr);
574 REPORTER_ASSERT(r, !codec);
575
msarett3d9d7a72015-10-21 10:27:10 -0700576 SkAndroidCodec* androidCodec = SkAndroidCodec::NewFromStream(nullptr);
577 REPORTER_ASSERT(r, !androidCodec);
scroggo2c3b2182015-10-09 08:40:59 -0700578}
579
msarette16b04a2015-04-15 07:32:19 -0700580static void test_dimensions(skiatest::Reporter* r, const char path[]) {
581 // Create the codec from the resource file
Ben Wagner145dbcd2016-11-03 14:40:50 -0400582 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarette16b04a2015-04-15 07:32:19 -0700583 if (!stream) {
msarette16b04a2015-04-15 07:32:19 -0700584 return;
585 }
Ben Wagner145dbcd2016-11-03 14:40:50 -0400586 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(stream.release()));
msarette16b04a2015-04-15 07:32:19 -0700587 if (!codec) {
588 ERRORF(r, "Unable to create codec '%s'", path);
589 return;
590 }
591
592 // Check that the decode is successful for a variety of scales
scroggo501b7342015-11-03 07:55:11 -0800593 for (int sampleSize = 1; sampleSize < 32; sampleSize++) {
msarette16b04a2015-04-15 07:32:19 -0700594 // Scale the output dimensions
msarett3d9d7a72015-10-21 10:27:10 -0700595 SkISize scaledDims = codec->getSampledDimensions(sampleSize);
msarettb32758a2015-08-18 13:22:46 -0700596 SkImageInfo scaledInfo = codec->getInfo()
597 .makeWH(scaledDims.width(), scaledDims.height())
598 .makeColorType(kN32_SkColorType);
msarette16b04a2015-04-15 07:32:19 -0700599
600 // Set up for the decode
601 size_t rowBytes = scaledDims.width() * sizeof(SkPMColor);
602 size_t totalBytes = scaledInfo.getSafeSize(rowBytes);
603 SkAutoTMalloc<SkPMColor> pixels(totalBytes);
604
msarett3d9d7a72015-10-21 10:27:10 -0700605 SkAndroidCodec::AndroidOptions options;
606 options.fSampleSize = sampleSize;
scroggoeb602a52015-07-09 08:16:03 -0700607 SkCodec::Result result =
msarett3d9d7a72015-10-21 10:27:10 -0700608 codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options);
scroggoeb602a52015-07-09 08:16:03 -0700609 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarette16b04a2015-04-15 07:32:19 -0700610 }
611}
612
613// Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes
614DEF_TEST(Codec_Dimensions, r) {
615 // JPG
616 test_dimensions(r, "CMYK.jpg");
617 test_dimensions(r, "color_wheel.jpg");
618 test_dimensions(r, "grayscale.jpg");
619 test_dimensions(r, "mandrill_512_q075.jpg");
620 test_dimensions(r, "randPixels.jpg");
msarettb32758a2015-08-18 13:22:46 -0700621
622 // Decoding small images with very large scaling factors is a potential
623 // source of bugs and crashes. We disable these tests in Gold because
624 // tiny images are not very useful to look at.
625 // Here we make sure that we do not crash or access illegal memory when
626 // performing scaled decodes on small images.
627 test_dimensions(r, "1x1.png");
628 test_dimensions(r, "2x2.png");
629 test_dimensions(r, "3x3.png");
630 test_dimensions(r, "3x1.png");
631 test_dimensions(r, "1x1.png");
632 test_dimensions(r, "16x1.png");
633 test_dimensions(r, "1x16.png");
634 test_dimensions(r, "mandrill_16.png");
635
yujieqin916de9f2016-01-25 08:26:16 -0800636 // RAW
yujieqinf236ee42016-02-29 07:14:42 -0800637// Disable RAW tests for Win32.
638#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin916de9f2016-01-25 08:26:16 -0800639 test_dimensions(r, "sample_1mp.dng");
ebrauer46d2aa82016-02-17 08:04:00 -0800640 test_dimensions(r, "sample_1mp_rotated.dng");
yujieqin9c7a8a42016-02-05 08:21:19 -0800641 test_dimensions(r, "dng_with_preview.dng");
msarett8e49ca32016-01-25 13:10:58 -0800642#endif
msarette16b04a2015-04-15 07:32:19 -0700643}
644
msarettd0375bc2015-08-12 08:08:56 -0700645static void test_invalid(skiatest::Reporter* r, const char path[]) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400646 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarett4b17fa32015-04-23 08:53:39 -0700647 if (!stream) {
msarett4b17fa32015-04-23 08:53:39 -0700648 return;
649 }
Ben Wagner145dbcd2016-11-03 14:40:50 -0400650 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
halcanary96fcdcc2015-08-27 07:41:13 -0700651 REPORTER_ASSERT(r, nullptr == codec);
msarett4b17fa32015-04-23 08:53:39 -0700652}
msarette16b04a2015-04-15 07:32:19 -0700653
msarett4b17fa32015-04-23 08:53:39 -0700654DEF_TEST(Codec_Empty, r) {
655 // Test images that should not be able to create a codec
msarettd0375bc2015-08-12 08:08:56 -0700656 test_invalid(r, "empty_images/zero-dims.gif");
657 test_invalid(r, "empty_images/zero-embedded.ico");
658 test_invalid(r, "empty_images/zero-width.bmp");
659 test_invalid(r, "empty_images/zero-height.bmp");
660 test_invalid(r, "empty_images/zero-width.jpg");
661 test_invalid(r, "empty_images/zero-height.jpg");
662 test_invalid(r, "empty_images/zero-width.png");
663 test_invalid(r, "empty_images/zero-height.png");
664 test_invalid(r, "empty_images/zero-width.wbmp");
665 test_invalid(r, "empty_images/zero-height.wbmp");
666 // This image is an ico with an embedded mask-bmp. This is illegal.
667 test_invalid(r, "invalid_images/mask-bmp-ico.ico");
Matt Sarett5c496172017-02-07 17:01:16 -0500668 // It is illegal for a webp frame to not be fully contained by the canvas.
669 test_invalid(r, "invalid_images/invalid-offset.webp");
Leon Scroggins IIId87fbee2016-12-02 16:47:53 -0500670#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
671 test_invalid(r, "empty_images/zero_height.tiff");
672#endif
msarett4b17fa32015-04-23 08:53:39 -0700673}
msarett99f567e2015-08-05 12:58:26 -0700674
675static void test_invalid_parameters(skiatest::Reporter* r, const char path[]) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400676 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarett99f567e2015-08-05 12:58:26 -0700677 if (!stream) {
msarett99f567e2015-08-05 12:58:26 -0700678 return;
679 }
Ben Wagner145dbcd2016-11-03 14:40:50 -0400680 std::unique_ptr<SkCodec> decoder(SkCodec::NewFromStream(stream.release()));
scroggo8e6c7ad2016-09-16 08:20:38 -0700681 if (!decoder) {
682 SkDebugf("Missing codec for %s\n", path);
683 return;
684 }
685
686 const SkImageInfo info = decoder->getInfo().makeColorType(kIndex_8_SkColorType);
halcanary9d524f22016-03-29 09:03:52 -0700687
msarett99f567e2015-08-05 12:58:26 -0700688 // This should return kSuccess because kIndex8 is supported.
689 SkPMColor colorStorage[256];
690 int colorCount;
scroggo8e6c7ad2016-09-16 08:20:38 -0700691 SkCodec::Result result = decoder->startScanlineDecode(info, nullptr, colorStorage,
692 &colorCount);
693 if (SkCodec::kSuccess == result) {
694 // This should return kInvalidParameters because, in kIndex_8 mode, we must pass in a valid
695 // colorPtr and a valid colorCountPtr.
696 result = decoder->startScanlineDecode(info, nullptr, nullptr, nullptr);
697 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
698 result = decoder->startScanlineDecode(info);
699 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
700 } else if (SkCodec::kUnimplemented == result) {
701 // New method should be supported:
702 SkBitmap bm;
Mike Reed6b3155c2017-04-03 14:41:44 -0400703 bm.allocPixels(info, SkColorTable::Make(colorStorage, 256));
scroggo8e6c7ad2016-09-16 08:20:38 -0700704 result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), nullptr,
705 colorStorage, &colorCount);
706 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
707 result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
708 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
709 } else {
710 // The test is uninteresting if kIndex8 is not supported
711 ERRORF(r, "Should not call test_invalid_parameters for non-Index8 file: %s\n", path);
msarett99f567e2015-08-05 12:58:26 -0700712 return;
713 }
714
msarett99f567e2015-08-05 12:58:26 -0700715}
716
717DEF_TEST(Codec_Params, r) {
718 test_invalid_parameters(r, "index8.png");
719 test_invalid_parameters(r, "mandrill.wbmp");
720}
scroggocf98fa92015-11-23 08:14:40 -0800721
scroggo8e6c7ad2016-09-16 08:20:38 -0700722#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
723
724#ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions.
725 // It does not appear that anyone in Google3 is reading chunks.
726
scroggocf98fa92015-11-23 08:14:40 -0800727static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
728 SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
729 if (!sk_stream->write(data, len)) {
730 png_error(png_ptr, "sk_write_fn Error!");
731 }
732}
733
scroggocf98fa92015-11-23 08:14:40 -0800734DEF_TEST(Codec_pngChunkReader, r) {
735 // Create a dummy bitmap. Use unpremul RGBA for libpng.
736 SkBitmap bm;
737 const int w = 1;
738 const int h = 1;
739 const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
740 kUnpremul_SkAlphaType);
741 bm.setInfo(bmInfo);
742 bm.allocPixels();
743 bm.eraseColor(SK_ColorBLUE);
744 SkMD5::Digest goodDigest;
745 md5(bm, &goodDigest);
746
747 // Write to a png file.
748 png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
749 REPORTER_ASSERT(r, png);
750 if (!png) {
751 return;
752 }
753
754 png_infop info = png_create_info_struct(png);
755 REPORTER_ASSERT(r, info);
756 if (!info) {
757 png_destroy_write_struct(&png, nullptr);
758 return;
759 }
760
761 if (setjmp(png_jmpbuf(png))) {
762 ERRORF(r, "failed writing png");
763 png_destroy_write_struct(&png, &info);
764 return;
765 }
766
767 SkDynamicMemoryWStream wStream;
768 png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
769
770 png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
771 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
772 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
773
774 // Create some chunks that match the Android framework's use.
775 static png_unknown_chunk gUnknowns[] = {
msarett133eaaa2016-01-07 11:03:25 -0800776 { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
777 { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
778 { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
scroggocf98fa92015-11-23 08:14:40 -0800779 };
780
781 png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
782 png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
783#if PNG_LIBPNG_VER < 10600
784 /* Deal with unknown chunk location bug in 1.5.x and earlier */
msarett133eaaa2016-01-07 11:03:25 -0800785 png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
786 png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
scroggocf98fa92015-11-23 08:14:40 -0800787#endif
788
789 png_write_info(png, info);
790
791 for (int j = 0; j < h; j++) {
792 png_bytep row = (png_bytep)(bm.getAddr(0, j));
793 png_write_rows(png, &row, 1);
794 }
795 png_write_end(png, info);
796 png_destroy_write_struct(&png, &info);
797
798 class ChunkReader : public SkPngChunkReader {
799 public:
800 ChunkReader(skiatest::Reporter* r)
801 : fReporter(r)
802 {
803 this->reset();
804 }
805
806 bool readChunk(const char tag[], const void* data, size_t length) override {
807 for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
808 if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
809 // Tag matches. This should have been the first time we see it.
810 REPORTER_ASSERT(fReporter, !fSeen[i]);
811 fSeen[i] = true;
812
813 // Data and length should match
814 REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
815 REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
816 (const char*) gUnknowns[i].data));
817 return true;
818 }
819 }
820 ERRORF(fReporter, "Saw an unexpected unknown chunk.");
821 return true;
822 }
823
824 bool allHaveBeenSeen() {
825 bool ret = true;
826 for (auto seen : fSeen) {
827 ret &= seen;
828 }
829 return ret;
830 }
831
832 void reset() {
833 sk_bzero(fSeen, sizeof(fSeen));
834 }
835
836 private:
837 skiatest::Reporter* fReporter; // Unowned
838 bool fSeen[3];
839 };
840
841 ChunkReader chunkReader(r);
842
843 // Now read the file with SkCodec.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400844 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(wStream.detachAsData(), &chunkReader));
scroggocf98fa92015-11-23 08:14:40 -0800845 REPORTER_ASSERT(r, codec);
846 if (!codec) {
847 return;
848 }
849
850 // Now compare to the original.
851 SkBitmap decodedBm;
852 decodedBm.setInfo(codec->getInfo());
853 decodedBm.allocPixels();
854 SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
855 decodedBm.rowBytes());
856 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
857
858 if (decodedBm.colorType() != bm.colorType()) {
859 SkBitmap tmp;
860 bool success = decodedBm.copyTo(&tmp, bm.colorType());
861 REPORTER_ASSERT(r, success);
862 if (!success) {
863 return;
864 }
865
866 tmp.swap(decodedBm);
867 }
868
869 compare_to_good_digest(r, goodDigest, decodedBm);
870 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
871
872 // Decoding again will read the chunks again.
873 chunkReader.reset();
874 REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
875 result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
876 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
877 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
878}
scroggo8e6c7ad2016-09-16 08:20:38 -0700879#endif // SK_PNG_DISABLE_TESTS
scroggocf98fa92015-11-23 08:14:40 -0800880#endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
scroggob9a1e342015-11-30 06:25:31 -0800881
scroggodb30be22015-12-08 18:54:13 -0800882// Stream that can only peek up to a limit
883class LimitedPeekingMemStream : public SkStream {
884public:
reed42943c82016-09-12 12:01:44 -0700885 LimitedPeekingMemStream(sk_sp<SkData> data, size_t limit)
886 : fStream(std::move(data))
scroggodb30be22015-12-08 18:54:13 -0800887 , fLimit(limit) {}
888
889 size_t peek(void* buf, size_t bytes) const override {
890 return fStream.peek(buf, SkTMin(bytes, fLimit));
891 }
892 size_t read(void* buf, size_t bytes) override {
893 return fStream.read(buf, bytes);
894 }
895 bool rewind() override {
896 return fStream.rewind();
897 }
898 bool isAtEnd() const override {
msarettff2a6c82016-09-07 11:23:28 -0700899 return fStream.isAtEnd();
scroggodb30be22015-12-08 18:54:13 -0800900 }
901private:
902 SkMemoryStream fStream;
903 const size_t fLimit;
904};
905
yujieqinf236ee42016-02-29 07:14:42 -0800906// Disable RAW tests for Win32.
907#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin9c7a8a42016-02-05 08:21:19 -0800908// Test that the RawCodec works also for not asset stream. This will test the code path using
909// SkRawBufferedStream instead of SkRawAssetStream.
yujieqin9c7a8a42016-02-05 08:21:19 -0800910DEF_TEST(Codec_raw_notseekable, r) {
911 const char* path = "dng_with_preview.dng";
912 SkString fullPath(GetResourcePath(path));
bungeman38d909e2016-08-02 14:40:46 -0700913 sk_sp<SkData> data(SkData::MakeFromFileName(fullPath.c_str()));
yujieqin9c7a8a42016-02-05 08:21:19 -0800914 if (!data) {
915 SkDebugf("Missing resource '%s'\n", path);
916 return;
917 }
918
Ben Wagner145dbcd2016-11-03 14:40:50 -0400919 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(new NotAssetMemStream(std::move(data))));
yujieqin9c7a8a42016-02-05 08:21:19 -0800920 REPORTER_ASSERT(r, codec);
921
922 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
923}
924#endif
925
scroggodb30be22015-12-08 18:54:13 -0800926// Test that even if webp_parse_header fails to peek enough, it will fall back to read()
927// + rewind() and succeed.
928DEF_TEST(Codec_webp_peek, r) {
929 const char* path = "baby_tux.webp";
930 SkString fullPath(GetResourcePath(path));
reedfde05112016-03-11 13:02:28 -0800931 auto data = SkData::MakeFromFileName(fullPath.c_str());
scroggodb30be22015-12-08 18:54:13 -0800932 if (!data) {
933 SkDebugf("Missing resource '%s'\n", path);
934 return;
935 }
936
937 // The limit is less than webp needs to peek or read.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400938 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(
reed42943c82016-09-12 12:01:44 -0700939 new LimitedPeekingMemStream(data, 25)));
scroggodb30be22015-12-08 18:54:13 -0800940 REPORTER_ASSERT(r, codec);
941
scroggo7b5e5532016-02-04 06:14:24 -0800942 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800943
944 // Similarly, a stream which does not peek should still succeed.
reed42943c82016-09-12 12:01:44 -0700945 codec.reset(SkCodec::NewFromStream(new LimitedPeekingMemStream(data, 0)));
scroggodb30be22015-12-08 18:54:13 -0800946 REPORTER_ASSERT(r, codec);
947
scroggo7b5e5532016-02-04 06:14:24 -0800948 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800949}
950
msarett7f7ec202016-03-01 12:12:27 -0800951// SkCodec's wbmp decoder was initially unnecessarily restrictive.
952// It required the second byte to be zero. The wbmp specification allows
953// a couple of bits to be 1 (so long as they do not overlap with 0x9F).
954// Test that SkCodec now supports an image with these bits set.
Leon Scroggins III83926342016-12-06 10:58:02 -0500955DEF_TEST(Codec_wbmp_restrictive, r) {
scroggob9a1e342015-11-30 06:25:31 -0800956 const char* path = "mandrill.wbmp";
Ben Wagner145dbcd2016-11-03 14:40:50 -0400957 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
scroggob9a1e342015-11-30 06:25:31 -0800958 if (!stream) {
scroggob9a1e342015-11-30 06:25:31 -0800959 return;
960 }
961
962 // Modify the stream to contain a second byte with some bits set.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400963 auto data = SkCopyStreamToData(stream.get());
scroggob9a1e342015-11-30 06:25:31 -0800964 uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
965 writeableData[1] = static_cast<uint8_t>(~0x9F);
966
msarett7f7ec202016-03-01 12:12:27 -0800967 // SkCodec should support this.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400968 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(data));
scroggob9a1e342015-11-30 06:25:31 -0800969 REPORTER_ASSERT(r, codec);
970 if (!codec) {
971 return;
972 }
scroggo7b5e5532016-02-04 06:14:24 -0800973 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggob9a1e342015-11-30 06:25:31 -0800974}
scroggodb30be22015-12-08 18:54:13 -0800975
976// wbmp images have a header that can be arbitrarily large, depending on the
977// size of the image. We cap the size at 65535, meaning we only need to look at
978// 8 bytes to determine whether we can read the image. This is important
979// because SkCodec only passes 14 bytes to SkWbmpCodec to determine whether the
980// image is a wbmp.
981DEF_TEST(Codec_wbmp_max_size, r) {
982 const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
983 0x83, 0xFF, 0x7F, // W: 65535
984 0x83, 0xFF, 0x7F }; // H: 65535
Ben Wagner145dbcd2016-11-03 14:40:50 -0400985 std::unique_ptr<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
986 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
scroggodb30be22015-12-08 18:54:13 -0800987
988 REPORTER_ASSERT(r, codec);
989 if (!codec) return;
990
991 REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
992 REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
993
994 // Now test an image which is too big. Any image with a larger header (i.e.
995 // has bigger width/height) is also too big.
996 const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
997 0x84, 0x80, 0x00, // W: 65536
998 0x84, 0x80, 0x00 }; // H: 65536
999 stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false));
mtklein18300a32016-03-16 13:53:35 -07001000 codec.reset(SkCodec::NewFromStream(stream.release()));
scroggodb30be22015-12-08 18:54:13 -08001001
1002 REPORTER_ASSERT(r, !codec);
1003}
msarett2812f032016-07-18 15:56:08 -07001004
1005DEF_TEST(Codec_jpeg_rewind, r) {
1006 const char* path = "mandrill_512_q075.jpg";
Leon Scroggins III42886572017-01-27 13:16:28 -05001007 sk_sp<SkData> data(GetResourceAsData(path));
1008 if (!data) {
msarett2812f032016-07-18 15:56:08 -07001009 return;
1010 }
Leon Scroggins III42886572017-01-27 13:16:28 -05001011
1012 data = SkData::MakeSubset(data.get(), 0, data->size() / 2);
1013 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromData(data));
msarett2812f032016-07-18 15:56:08 -07001014 if (!codec) {
1015 ERRORF(r, "Unable to create codec '%s'.", path);
1016 return;
1017 }
1018
1019 const int width = codec->getInfo().width();
1020 const int height = codec->getInfo().height();
1021 size_t rowBytes = sizeof(SkPMColor) * width;
1022 SkAutoMalloc pixelStorage(height * rowBytes);
1023
1024 // Perform a sampled decode.
1025 SkAndroidCodec::AndroidOptions opts;
1026 opts.fSampleSize = 12;
Leon Scroggins III42886572017-01-27 13:16:28 -05001027 auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12);
1028 auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts);
1029 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -07001030
1031 // Rewind the codec and perform a full image decode.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001032 result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes);
Leon Scroggins III42886572017-01-27 13:16:28 -05001033 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
Matt Sarett74b16ed2017-01-25 11:58:11 -05001034
1035 // Now perform a subset decode.
1036 {
1037 opts.fSampleSize = 1;
1038 SkIRect subset = SkIRect::MakeWH(100, 100);
1039 opts.fSubset = &subset;
1040 result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(),
1041 rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001042 // Though we only have half the data, it is enough to decode this subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001043 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1044 }
1045
1046 // Perform another full image decode. ASAN will detect if we look at the subset when it is
1047 // out of scope. This would happen if we depend on the old state in the codec.
Leon Scroggins III42886572017-01-27 13:16:28 -05001048 // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage
1049 // used to look at the old subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001050 opts.fSubset = nullptr;
1051 result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001052 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -07001053}
msarett549ca322016-08-17 08:54:08 -07001054
msarett35bb74b2016-08-22 07:41:28 -07001055static void check_color_xform(skiatest::Reporter* r, const char* path) {
Ben Wagner145dbcd2016-11-03 14:40:50 -04001056 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(GetResourceAsStream(path)));
msarett35bb74b2016-08-22 07:41:28 -07001057
1058 SkAndroidCodec::AndroidOptions opts;
1059 opts.fSampleSize = 3;
1060 const int subsetWidth = codec->getInfo().width() / 2;
1061 const int subsetHeight = codec->getInfo().height() / 2;
1062 SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight);
1063 opts.fSubset = &subset;
1064
1065 const int dstWidth = subsetWidth / opts.fSampleSize;
1066 const int dstHeight = subsetHeight / opts.fSampleSize;
1067 sk_sp<SkData> data = SkData::MakeFromFileName(
1068 GetResourcePath("icc_profiles/HP_ZR30w.icc").c_str());
Brian Osman526972e2016-10-24 09:24:02 -04001069 sk_sp<SkColorSpace> colorSpace = SkColorSpace::MakeICC(data->data(), data->size());
msarett35bb74b2016-08-22 07:41:28 -07001070 SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight)
1071 .makeColorType(kN32_SkColorType)
1072 .makeColorSpace(colorSpace);
1073
1074 size_t rowBytes = dstInfo.minRowBytes();
1075 SkAutoMalloc pixelStorage(dstInfo.getSafeSize(rowBytes));
1076 SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts);
1077 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1078}
1079
1080DEF_TEST(Codec_ColorXform, r) {
1081 check_color_xform(r, "mandrill_512_q075.jpg");
1082 check_color_xform(r, "mandrill_512.png");
1083}
1084
msarettf17b71f2016-09-12 14:30:03 -07001085static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) {
1086 switch (origColorType) {
1087 case kRGBA_8888_SkColorType:
1088 case kBGRA_8888_SkColorType:
1089 return kRGBA_8888_SkColorType == codecColorType ||
1090 kBGRA_8888_SkColorType == codecColorType;
1091 default:
1092 return origColorType == codecColorType;
1093 }
1094}
1095
1096static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) {
1097 switch (origAlphaType) {
1098 case kUnpremul_SkAlphaType:
1099 case kPremul_SkAlphaType:
1100 return kUnpremul_SkAlphaType == codecAlphaType ||
1101 kPremul_SkAlphaType == codecAlphaType;
1102 default:
1103 return origAlphaType == codecAlphaType;
1104 }
1105}
1106
1107static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) {
1108 SkBitmap bm1;
1109 SkPMColor colors[256];
Mike Reed6b3155c2017-04-03 14:41:44 -04001110 sk_sp<SkColorTable> colorTable1 = SkColorTable::Make(colors, 256);
1111 bm1.allocPixels(info, colorTable1);
msarettf17b71f2016-09-12 14:30:03 -07001112 int numColors;
1113 SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes(), nullptr,
1114 const_cast<SkPMColor*>(colorTable1->readColors()),
1115 &numColors);
1116 // This will fail to update colorTable1->count() but is fine for the purpose of this test.
1117 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarett9b09cd82016-08-29 14:47:49 -07001118
1119 // Encode the image to png.
1120 sk_sp<SkData> data =
Hal Canarydb683012016-11-23 08:55:18 -07001121 sk_sp<SkData>(sk_tool_utils::EncodeImageToData(bm1, SkEncodedImageFormat::kPNG, 100));
msarett9b09cd82016-08-29 14:47:49 -07001122
Ben Wagner145dbcd2016-11-03 14:40:50 -04001123 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(data));
msarettf17b71f2016-09-12 14:30:03 -07001124 REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType()));
1125 REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType()));
msarett9b09cd82016-08-29 14:47:49 -07001126
1127 SkBitmap bm2;
Mike Reed6b3155c2017-04-03 14:41:44 -04001128 sk_sp<SkColorTable> colorTable2 = SkColorTable::Make(colors, 256);
1129 bm2.allocPixels(info, colorTable2);
msarettf17b71f2016-09-12 14:30:03 -07001130 result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes(), nullptr,
1131 const_cast<SkPMColor*>(colorTable2->readColors()), &numColors);
msarett9b09cd82016-08-29 14:47:49 -07001132 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1133
1134 SkMD5::Digest d1, d2;
1135 md5(bm1, &d1);
1136 md5(bm2, &d2);
1137 REPORTER_ASSERT(r, d1 == d2);
1138}
1139
1140DEF_TEST(Codec_PngRoundTrip, r) {
msarett549ca322016-08-17 08:54:08 -07001141 const char* path = "mandrill_512_q075.jpg";
Ben Wagner145dbcd2016-11-03 14:40:50 -04001142 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
1143 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
msarett549ca322016-08-17 08:54:08 -07001144
msarettf17b71f2016-09-12 14:30:03 -07001145 SkColorType colorTypesOpaque[] = {
1146 kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1147 };
1148 for (SkColorType colorType : colorTypesOpaque) {
1149 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType);
1150 check_round_trip(r, codec.get(), newInfo);
1151 }
1152
msarett9b09cd82016-08-29 14:47:49 -07001153 path = "grayscale.jpg";
bungemanf93d7112016-09-16 06:24:20 -07001154 stream.reset(GetResourceAsStream(path));
msarett9b09cd82016-08-29 14:47:49 -07001155 codec.reset(SkCodec::NewFromStream(stream.release()));
msarettf17b71f2016-09-12 14:30:03 -07001156 check_round_trip(r, codec.get(), codec->getInfo());
1157
1158 path = "yellow_rose.png";
bungemanf93d7112016-09-16 06:24:20 -07001159 stream.reset(GetResourceAsStream(path));
msarettf17b71f2016-09-12 14:30:03 -07001160 codec.reset(SkCodec::NewFromStream(stream.release()));
1161
1162 SkColorType colorTypesWithAlpha[] = {
1163 kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1164 };
1165 SkAlphaType alphaTypes[] = {
1166 kUnpremul_SkAlphaType, kPremul_SkAlphaType
1167 };
1168 for (SkColorType colorType : colorTypesWithAlpha) {
1169 for (SkAlphaType alphaType : alphaTypes) {
1170 // Set color space to nullptr because color correct premultiplies do not round trip.
1171 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType)
1172 .makeAlphaType(alphaType)
1173 .makeColorSpace(nullptr);
1174 check_round_trip(r, codec.get(), newInfo);
1175 }
1176 }
1177
1178 path = "index8.png";
bungemanf93d7112016-09-16 06:24:20 -07001179 stream.reset(GetResourceAsStream(path));
msarettf17b71f2016-09-12 14:30:03 -07001180 codec.reset(SkCodec::NewFromStream(stream.release()));
1181
1182 for (SkAlphaType alphaType : alphaTypes) {
1183 SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType)
1184 .makeColorSpace(nullptr);
1185 check_round_trip(r, codec.get(), newInfo);
1186 }
msarett549ca322016-08-17 08:54:08 -07001187}
msarett2ecc35f2016-09-08 11:55:16 -07001188
1189static void test_conversion_possible(skiatest::Reporter* r, const char* path,
scroggo8e6c7ad2016-09-16 08:20:38 -07001190 bool supportsScanlineDecoder,
1191 bool supportsIncrementalDecoder) {
Ben Wagner145dbcd2016-11-03 14:40:50 -04001192 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001193 if (!stream) {
1194 return;
1195 }
1196
Ben Wagner145dbcd2016-11-03 14:40:50 -04001197 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001198 if (!codec) {
1199 ERRORF(r, "failed to create a codec for %s", path);
1200 return;
1201 }
1202
msarett2ecc35f2016-09-08 11:55:16 -07001203 SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType);
1204
1205 SkBitmap bm;
1206 bm.allocPixels(infoF16);
1207 SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
1208 REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001209
1210 result = codec->startScanlineDecode(infoF16);
1211 if (supportsScanlineDecoder) {
msarett2ecc35f2016-09-08 11:55:16 -07001212 REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001213 } else {
1214 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
1215 }
1216
1217 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1218 if (supportsIncrementalDecoder) {
1219 REPORTER_ASSERT(r, SkCodec::kInvalidConversion == result);
1220 } else {
1221 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
msarett2ecc35f2016-09-08 11:55:16 -07001222 }
1223
raftias94888332016-10-18 10:02:51 -07001224 SkASSERT(SkColorSpace_Base::Type::kXYZ == as_CSB(infoF16.colorSpace())->type());
1225 SkColorSpace_XYZ* csXYZ = static_cast<SkColorSpace_XYZ*>(infoF16.colorSpace());
1226 infoF16 = infoF16.makeColorSpace(csXYZ->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001227 result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
1228 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001229 result = codec->startScanlineDecode(infoF16);
1230 if (supportsScanlineDecoder) {
msarett2ecc35f2016-09-08 11:55:16 -07001231 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001232 } else {
1233 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
1234 }
1235
1236 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1237 if (supportsIncrementalDecoder) {
1238 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1239 } else {
1240 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
msarett2ecc35f2016-09-08 11:55:16 -07001241 }
1242}
1243
1244DEF_TEST(Codec_F16ConversionPossible, r) {
scroggo8e6c7ad2016-09-16 08:20:38 -07001245 test_conversion_possible(r, "color_wheel.webp", false, false);
1246 test_conversion_possible(r, "mandrill_512_q075.jpg", true, false);
1247 test_conversion_possible(r, "yellow_rose.png", false, true);
1248}
1249
scroggo19b91532016-10-24 09:03:26 -07001250static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) {
1251 SkBitmap bm;
1252 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1253 bm.allocPixels(info);
1254
1255 SkCodec::Options opts;
1256 opts.fFrameIndex = frame;
1257 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info,
1258 bm.getPixels(), bm.rowBytes(), &opts, nullptr, nullptr));
1259}
1260
1261// For an animated image, we should only read enough to decode the requested
1262// frame if the client never calls getFrameInfo.
1263DEF_TEST(Codec_skipFullParse, r) {
1264 auto path = "test640x479.gif";
1265 SkStream* stream(GetResourceAsStream(path));
1266 if (!stream) {
1267 return;
1268 }
1269
1270 // Note that we cheat and hold on to the stream pointer, but SkCodec will
1271 // take ownership. We will not refer to the stream after the SkCodec
1272 // deletes it.
1273 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream));
1274 if (!codec) {
1275 ERRORF(r, "Failed to create codec for %s", path);
1276 return;
1277 }
1278
1279 REPORTER_ASSERT(r, stream->hasPosition());
1280 const size_t sizePosition = stream->getPosition();
1281 REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength());
1282
1283 // This should read more of the stream, but not the whole stream.
1284 decode_frame(r, codec.get(), 0);
1285 const size_t positionAfterFirstFrame = stream->getPosition();
1286 REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition
1287 && positionAfterFirstFrame < stream->getLength());
1288
1289 // Again, this should read more of the stream.
1290 decode_frame(r, codec.get(), 2);
1291 const size_t positionAfterThirdFrame = stream->getPosition();
1292 REPORTER_ASSERT(r, positionAfterThirdFrame > positionAfterFirstFrame
1293 && positionAfterThirdFrame < stream->getLength());
1294
1295 // This does not need to read any more of the stream, since it has already
1296 // parsed the second frame.
1297 decode_frame(r, codec.get(), 1);
1298 REPORTER_ASSERT(r, stream->getPosition() == positionAfterThirdFrame);
1299
1300 // This should read the rest of the frames.
1301 decode_frame(r, codec.get(), 3);
1302 const size_t finalPosition = stream->getPosition();
1303 REPORTER_ASSERT(r, finalPosition > positionAfterThirdFrame);
1304
1305 // There may be more data in the stream.
1306 auto frameInfo = codec->getFrameInfo();
1307 REPORTER_ASSERT(r, frameInfo.size() == 4);
1308 REPORTER_ASSERT(r, stream->getPosition() >= finalPosition);
1309}
1310
scroggo8e6c7ad2016-09-16 08:20:38 -07001311// Only rewinds up to a limit.
1312class LimitedRewindingStream : public SkStream {
1313public:
1314 static SkStream* Make(const char path[], size_t limit) {
1315 SkStream* stream = GetResourceAsStream(path);
1316 if (!stream) {
1317 return nullptr;
1318 }
1319 return new LimitedRewindingStream(stream, limit);
1320 }
1321
1322 size_t read(void* buffer, size_t size) override {
1323 const size_t bytes = fStream->read(buffer, size);
1324 fPosition += bytes;
1325 return bytes;
1326 }
1327
1328 bool isAtEnd() const override {
1329 return fStream->isAtEnd();
1330 }
1331
1332 bool rewind() override {
1333 if (fPosition <= fLimit && fStream->rewind()) {
1334 fPosition = 0;
1335 return true;
1336 }
1337
1338 return false;
1339 }
1340
1341private:
Ben Wagner145dbcd2016-11-03 14:40:50 -04001342 std::unique_ptr<SkStream> fStream;
1343 const size_t fLimit;
1344 size_t fPosition;
scroggo8e6c7ad2016-09-16 08:20:38 -07001345
1346 LimitedRewindingStream(SkStream* stream, size_t limit)
1347 : fStream(stream)
1348 , fLimit(limit)
1349 , fPosition(0)
1350 {
1351 SkASSERT(fStream);
1352 }
1353};
1354
1355DEF_TEST(Codec_fallBack, r) {
1356 // SkAndroidCodec needs to be able to fall back to scanline decoding
1357 // if incremental decoding does not work. Make sure this does not
1358 // require a rewind.
1359
1360 // Formats that currently do not support incremental decoding
1361 auto files = {
scroggo8e6c7ad2016-09-16 08:20:38 -07001362 "CMYK.jpg",
1363 "color_wheel.ico",
1364 "mandrill.wbmp",
1365 "randPixels.bmp",
1366 };
1367 for (auto file : files) {
1368 SkStream* stream = LimitedRewindingStream::Make(file, 14);
1369 if (!stream) {
1370 SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
1371 return;
1372 }
1373
Ben Wagner145dbcd2016-11-03 14:40:50 -04001374 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream));
scroggo8e6c7ad2016-09-16 08:20:38 -07001375 if (!codec) {
1376 ERRORF(r, "Failed to create codec for %s,", file);
1377 continue;
1378 }
1379
1380 SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
1381 SkBitmap bm;
1382 bm.allocPixels(info);
1383
1384 if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
1385 bm.rowBytes())) {
1386 ERRORF(r, "Is scanline decoding now implemented for %s?", file);
1387 continue;
1388 }
1389
1390 // Scanline decoding should not require a rewind.
1391 SkCodec::Result result = codec->startScanlineDecode(info);
1392 if (SkCodec::kSuccess != result) {
1393 ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
1394 }
1395 }
msarett2ecc35f2016-09-08 11:55:16 -07001396}
scroggoc46cdd42016-10-10 06:45:32 -07001397
1398// This test verifies that we fixed an assert statement that fired when reusing a png codec
1399// after scaling.
1400DEF_TEST(Codec_reusePng, r) {
1401 std::unique_ptr<SkStream> stream(GetResourceAsStream("plane.png"));
1402 if (!stream) {
1403 return;
1404 }
1405
1406 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(stream.release()));
1407 if (!codec) {
1408 ERRORF(r, "Failed to create codec\n");
1409 return;
1410 }
1411
1412 SkAndroidCodec::AndroidOptions opts;
1413 opts.fSampleSize = 5;
1414 auto size = codec->getSampledDimensions(opts.fSampleSize);
1415 auto info = codec->getInfo().makeWH(size.fWidth, size.fHeight).makeColorType(kN32_SkColorType);
1416 SkBitmap bm;
1417 bm.allocPixels(info);
1418 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1419 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1420
1421 info = codec->getInfo().makeColorType(kN32_SkColorType);
1422 bm.allocPixels(info);
1423 opts.fSampleSize = 1;
1424 result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1425 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1426}
scroggoe61b3b42016-10-10 07:17:32 -07001427
1428DEF_TEST(Codec_rowsDecoded, r) {
1429 auto file = "plane_interlaced.png";
1430 std::unique_ptr<SkStream> stream(GetResourceAsStream(file));
1431 if (!stream) {
1432 return;
1433 }
1434
1435 // This is enough to read the header etc, but no rows.
1436 auto data = SkData::MakeFromStream(stream.get(), 99);
1437 std::unique_ptr<SkCodec> codec(SkCodec::NewFromData(data));
1438 if (!codec) {
1439 ERRORF(r, "Failed to create codec\n");
1440 return;
1441 }
1442
1443 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1444 SkBitmap bm;
1445 bm.allocPixels(info);
1446 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
1447 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1448
1449 // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded
1450 // should get set to zero by incrementalDecode.
1451 int rowsDecoded = 77;
1452 result = codec->incrementalDecode(&rowsDecoded);
1453 REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput);
1454 REPORTER_ASSERT(r, rowsDecoded == 0);
1455}
Matt Sarett29121eb2016-10-17 14:32:46 -04001456
Matt Sarett8a4e9c52016-10-25 14:24:50 -04001457static void test_invalid_images(skiatest::Reporter* r, const char* path, bool shouldSucceed) {
Matt Sarett29121eb2016-10-17 14:32:46 -04001458 SkBitmap bitmap;
Matt Sarett8a4e9c52016-10-25 14:24:50 -04001459 const bool success = GetResourceAsBitmap(path, &bitmap);
1460 REPORTER_ASSERT(r, success == shouldSucceed);
1461}
1462
1463DEF_TEST(Codec_InvalidImages, r) {
1464 // ASAN will complain if there is an issue.
1465 test_invalid_images(r, "invalid_images/int_overflow.ico", false);
1466 test_invalid_images(r, "invalid_images/skbug5887.gif", true);
Matt Sarettdbdf6d22016-11-08 15:26:56 -05001467 test_invalid_images(r, "invalid_images/many-progressive-scans.jpg", false);
Matt Sarett29121eb2016-10-17 14:32:46 -04001468}
Leon Scroggins III56e32092016-12-12 17:10:46 -05001469
Leon Scroggins III0b24cbd2016-12-15 15:58:22 -05001470DEF_TEST(Codec_InvalidBmp, r) {
Leon Scroggins III0354c622017-02-24 15:33:24 -05001471 // These files report values that have caused problems with SkFILEStreams.
1472 // They are invalid, and should not create SkCodecs.
1473 for (auto* bmp : { "b33651913.bmp", "b34778578.bmp" } ) {
1474 SkString path = SkOSPath::Join("invalid_images", bmp);
1475 path = GetResourcePath(path.c_str());
1476 std::unique_ptr<SkFILEStream> stream(new SkFILEStream(path.c_str()));
1477 if (!stream->isValid()) {
1478 return;
1479 }
Leon Scroggins III0b24cbd2016-12-15 15:58:22 -05001480
Leon Scroggins III0354c622017-02-24 15:33:24 -05001481 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
1482 REPORTER_ASSERT(r, !codec);
1483 }
Leon Scroggins III0b24cbd2016-12-15 15:58:22 -05001484}
1485
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001486DEF_TEST(Codec_InvalidRLEBmp, r) {
1487 auto* stream = GetResourceAsStream("invalid_images/b33251605.bmp");
1488 if (!stream) {
1489 return;
1490 }
1491
1492 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream));
1493 REPORTER_ASSERT(r, codec);
1494
1495 test_info(r, codec.get(), codec->getInfo(), SkCodec::kIncompleteInput, nullptr);
1496}
1497
Leon Scroggins III56e32092016-12-12 17:10:46 -05001498DEF_TEST(Codec_InvalidAnimated, r) {
1499 // ASAN will complain if there is an issue.
1500 auto path = "invalid_images/skbug6046.gif";
1501 auto* stream = GetResourceAsStream(path);
1502 if (!stream) {
1503 return;
1504 }
1505
1506 std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream));
1507 REPORTER_ASSERT(r, codec);
1508 if (!codec) {
1509 return;
1510 }
1511
1512 const auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1513 SkBitmap bm;
1514 bm.allocPixels(info);
1515
1516 auto frameInfos = codec->getFrameInfo();
1517 SkCodec::Options opts;
1518 for (size_t i = 0; i < frameInfos.size(); i++) {
1519 opts.fFrameIndex = i;
1520 opts.fHasPriorFrame = frameInfos[i].fRequiredFrame == i - 1;
1521 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts);
1522 if (result != SkCodec::kSuccess) {
1523 ERRORF(r, "Failed to start decoding frame %i (out of %i) with error %i\n", i,
1524 frameInfos.size(), result);
1525 continue;
1526 }
1527
1528 codec->incrementalDecode();
1529 }
1530}
Matt Sarett0e032be2017-03-15 17:50:08 -04001531
Matt Sarett5df93de2017-03-22 21:52:47 +00001532static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap,
1533 const SkEncodeOptions& opts, SkEncodedImageFormat format) {
1534 switch (format) {
1535 case SkEncodedImageFormat::kPNG:
1536 SkEncodeImageAsPNG(stream, pixmap, opts);
1537 break;
1538 case SkEncodedImageFormat::kJPEG:
1539 SkEncodeImageAsJPEG(stream, pixmap, opts);
1540 break;
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001541 case SkEncodedImageFormat::kWEBP:
1542 SkEncodeImageAsWEBP(stream, pixmap, opts);
1543 break;
Matt Sarett5df93de2017-03-22 21:52:47 +00001544 default:
1545 SkASSERT(false);
1546 break;
1547 }
1548}
1549
Matt Sarett7abfb5e2017-04-05 17:36:04 -04001550static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format,
1551 SkTransferFunctionBehavior unpremulBehavior) {
Matt Sarett0e032be2017-03-15 17:50:08 -04001552 // Test with sRGB color space.
1553 SkBitmap srgbBitmap;
1554 SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType);
1555 srgbBitmap.allocPixels(srgbInfo);
1556 *srgbBitmap.getAddr32(0, 0) = 0;
1557 SkPixmap pixmap;
1558 srgbBitmap.peekPixels(&pixmap);
1559 SkDynamicMemoryWStream srgbBuf;
1560 SkEncodeOptions opts;
Matt Sarett7abfb5e2017-04-05 17:36:04 -04001561 opts.fUnpremulBehavior = unpremulBehavior;
Matt Sarett5df93de2017-03-22 21:52:47 +00001562 encode_format(&srgbBuf, pixmap, opts, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001563 sk_sp<SkData> srgbData = srgbBuf.detachAsData();
1564 std::unique_ptr<SkCodec> srgbCodec(SkCodec::NewFromData(srgbData));
1565 REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == SkColorSpace::MakeSRGB().get());
1566
1567 // Test with P3 color space.
1568 SkDynamicMemoryWStream p3Buf;
1569 sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
1570 SkColorSpace::kDCIP3_D65_Gamut);
1571 pixmap.setColorSpace(p3);
Matt Sarett5df93de2017-03-22 21:52:47 +00001572 encode_format(&p3Buf, pixmap, opts, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001573 sk_sp<SkData> p3Data = p3Buf.detachAsData();
1574 std::unique_ptr<SkCodec> p3Codec(SkCodec::NewFromData(p3Data));
1575 REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB());
1576 SkMatrix44 mat0(SkMatrix44::kUninitialized_Constructor);
1577 SkMatrix44 mat1(SkMatrix44::kUninitialized_Constructor);
1578 bool success = p3->toXYZD50(&mat0);
1579 REPORTER_ASSERT(r, success);
1580 success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1);
1581 REPORTER_ASSERT(r, success);
1582
1583 for (int i = 0; i < 4; i++) {
1584 for (int j = 0; j < 4; j++) {
Matt Sarett5df93de2017-03-22 21:52:47 +00001585 REPORTER_ASSERT(r, color_space_almost_equal(mat0.get(i, j), mat1.get(i, j)));
Matt Sarett0e032be2017-03-15 17:50:08 -04001586 }
1587 }
1588}
Matt Sarett5df93de2017-03-22 21:52:47 +00001589
1590DEF_TEST(Codec_EncodeICC, r) {
Matt Sarett7abfb5e2017-04-05 17:36:04 -04001591 test_encode_icc(r, SkEncodedImageFormat::kPNG, SkTransferFunctionBehavior::kRespect);
1592 test_encode_icc(r, SkEncodedImageFormat::kJPEG, SkTransferFunctionBehavior::kRespect);
Matt Sarett46a45ba2017-04-06 20:34:38 +00001593 test_encode_icc(r, SkEncodedImageFormat::kWEBP, SkTransferFunctionBehavior::kRespect);
Matt Sarett7abfb5e2017-04-05 17:36:04 -04001594 test_encode_icc(r, SkEncodedImageFormat::kPNG, SkTransferFunctionBehavior::kIgnore);
1595 test_encode_icc(r, SkEncodedImageFormat::kJPEG, SkTransferFunctionBehavior::kIgnore);
Matt Sarett46a45ba2017-04-06 20:34:38 +00001596 test_encode_icc(r, SkEncodedImageFormat::kWEBP, SkTransferFunctionBehavior::kIgnore);
Matt Sarett5df93de2017-03-22 21:52:47 +00001597}