blob: 52ddbff801b643f0e2a3b9f88c24c304f12470f5 [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
8#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -07009#include "SkAndroidCodec.h"
halcanarya096d7a2015-03-27 12:16:53 -070010#include "SkBitmap.h"
11#include "SkCodec.h"
msarettedd2dcf2016-01-14 13:12:26 -080012#include "SkCodecImageGenerator.h"
msarette6dd0042015-10-09 11:07:34 -070013#include "SkData.h"
scroggoef0fed32016-02-18 05:59:25 -080014#include "SkFrontBufferedStream.h"
halcanarya096d7a2015-03-27 12:16:53 -070015#include "SkMD5.h"
scroggob636b452015-07-22 07:16:20 -070016#include "SkRandom.h"
scroggocf98fa92015-11-23 08:14:40 -080017#include "SkStream.h"
scroggob9a1e342015-11-30 06:25:31 -080018#include "SkStreamPriv.h"
scroggocf98fa92015-11-23 08:14:40 -080019#include "SkPngChunkReader.h"
halcanarya096d7a2015-03-27 12:16:53 -070020#include "Test.h"
21
scroggocf98fa92015-11-23 08:14:40 -080022#include "png.h"
23
halcanarya096d7a2015-03-27 12:16:53 -070024static SkStreamAsset* resource(const char path[]) {
25 SkString fullPath = GetResourcePath(path);
26 return SkStream::NewFromFile(fullPath.c_str());
27}
28
29static void md5(const SkBitmap& bm, SkMD5::Digest* digest) {
30 SkAutoLockPixels autoLockPixels(bm);
31 SkASSERT(bm.getPixels());
32 SkMD5 md5;
33 size_t rowLen = bm.info().bytesPerPixel() * bm.width();
34 for (int y = 0; y < bm.height(); ++y) {
halcanary1e903042016-04-25 10:29:36 -070035 md5.write(bm.getAddr(0, y), rowLen);
halcanarya096d7a2015-03-27 12:16:53 -070036 }
37 md5.finish(*digest);
38}
39
scroggo9b2cdbf42015-07-10 12:07:02 -070040/**
41 * Compute the digest for bm and compare it to a known good digest.
42 * @param r Reporter to assert that bm's digest matches goodDigest.
43 * @param goodDigest The known good digest to compare to.
44 * @param bm The bitmap to test.
45 */
46static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
47 const SkBitmap& bm) {
48 SkMD5::Digest digest;
49 md5(bm, &digest);
50 REPORTER_ASSERT(r, digest == goodDigest);
51}
52
scroggod1bc5742015-08-12 08:31:44 -070053/**
54 * Test decoding an SkCodec to a particular SkImageInfo.
55 *
halcanary96fcdcc2015-08-27 07:41:13 -070056 * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
scroggod1bc5742015-08-12 08:31:44 -070057 * the resulting decode should match.
58 */
scroggo7b5e5532016-02-04 06:14:24 -080059template<typename Codec>
60static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
scroggod1bc5742015-08-12 08:31:44 -070061 SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
62 SkBitmap bm;
63 bm.allocPixels(info);
64 SkAutoLockPixels autoLockPixels(bm);
65
66 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
67 REPORTER_ASSERT(r, result == expectedResult);
68
69 if (goodDigest) {
70 compare_to_good_digest(r, *goodDigest, bm);
71 }
72}
73
scroggob636b452015-07-22 07:16:20 -070074SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
75 SkIRect rect;
76 do {
77 rect.fLeft = rand->nextRangeU(0, w);
78 rect.fTop = rand->nextRangeU(0, h);
79 rect.fRight = rand->nextRangeU(0, w);
80 rect.fBottom = rand->nextRangeU(0, h);
81 rect.sort();
82 } while (rect.isEmpty());
83 return rect;
84}
85
scroggo6fb23912016-06-02 14:16:43 -070086static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
87 const SkMD5::Digest& goodDigest) {
88 SkBitmap bm;
89 bm.allocPixels(info);
90 SkAutoLockPixels autoLockPixels(bm);
91
92 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
93 bm.rowBytes()));
94
95 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
96
97 compare_to_good_digest(r, goodDigest, bm);
98}
99
100// Test in stripes, similar to DM's kStripe_Mode
101static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
102 const SkMD5::Digest& goodDigest) {
103 SkBitmap bm;
104 bm.allocPixels(info);
105 bm.eraseColor(SK_ColorYELLOW);
106
107 const int height = info.height();
108 // Note that if numStripes does not evenly divide height there will be an extra
109 // stripe.
110 const int numStripes = 4;
111
112 if (numStripes > height) {
113 // Image is too small.
114 return;
115 }
116
117 const int stripeHeight = height / numStripes;
118
119 // Iterate through the image twice. Once to decode odd stripes, and once for even.
120 for (int oddEven = 1; oddEven >= 0; oddEven--) {
121 for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
122 SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
123 SkTMin(y + stripeHeight, height));
124 SkCodec::Options options;
125 options.fSubset = &subset;
126 if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
127 bm.rowBytes(), &options)) {
128 ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
129 subset.top(), subset.bottom());
130 return;
131 }
132 if (SkCodec::kSuccess != codec->incrementalDecode()) {
133 ERRORF(r, "failed incremental decode starting from line %i\n", y);
134 return;
135 }
136 }
137 }
138
139 compare_to_good_digest(r, goodDigest, bm);
140}
141
scroggo7b5e5532016-02-04 06:14:24 -0800142template<typename Codec>
143static void test_codec(skiatest::Reporter* r, Codec* codec, SkBitmap& bm, const SkImageInfo& info,
scroggo27c17282015-10-27 08:14:46 -0700144 const SkISize& size, SkCodec::Result expectedResult, SkMD5::Digest* digest,
145 const SkMD5::Digest* goodDigest) {
msarette6dd0042015-10-09 11:07:34 -0700146
halcanarya096d7a2015-03-27 12:16:53 -0700147 REPORTER_ASSERT(r, info.dimensions() == size);
halcanarya096d7a2015-03-27 12:16:53 -0700148 bm.allocPixels(info);
149 SkAutoLockPixels autoLockPixels(bm);
msarettcc7f3052015-10-05 14:20:27 -0700150
151 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
msarette6dd0042015-10-09 11:07:34 -0700152 REPORTER_ASSERT(r, result == expectedResult);
halcanarya096d7a2015-03-27 12:16:53 -0700153
msarettcc7f3052015-10-05 14:20:27 -0700154 md5(bm, digest);
155 if (goodDigest) {
156 REPORTER_ASSERT(r, *digest == *goodDigest);
157 }
halcanarya096d7a2015-03-27 12:16:53 -0700158
msarett8ff6ca62015-09-18 12:06:04 -0700159 {
160 // Test decoding to 565
161 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
scroggoba584892016-05-20 13:56:13 -0700162 if (info.alphaType() == kOpaque_SkAlphaType) {
163 // Decoding to 565 should succeed.
164 SkBitmap bm565;
165 bm565.allocPixels(info565);
166 SkAutoLockPixels alp(bm565);
167
168 // This will allow comparison even if the image is incomplete.
169 bm565.eraseColor(SK_ColorBLACK);
170
171 REPORTER_ASSERT(r, expectedResult == codec->getPixels(info565,
172 bm565.getPixels(), bm565.rowBytes()));
173
174 SkMD5::Digest digest565;
175 md5(bm565, &digest565);
176
177 // A dumb client's request for non-opaque should also succeed.
178 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
179 info565 = info565.makeAlphaType(alpha);
180 test_info(r, codec, info565, expectedResult, &digest565);
181 }
182 } else {
183 test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
184 }
185 }
186
187 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
188 SkImageInfo grayInfo = codec->getInfo();
189 SkBitmap grayBm;
190 grayBm.allocPixels(grayInfo);
191 SkAutoLockPixels alp(grayBm);
192
193 grayBm.eraseColor(SK_ColorBLACK);
194
195 REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
196 grayBm.getPixels(), grayBm.rowBytes()));
197
198 SkMD5::Digest grayDigest;
199 md5(grayBm, &grayDigest);
200
201 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
202 grayInfo = grayInfo.makeAlphaType(alpha);
203 test_info(r, codec, grayInfo, expectedResult, &grayDigest);
204 }
msarett8ff6ca62015-09-18 12:06:04 -0700205 }
206
207 // Verify that re-decoding gives the same result. It is interesting to check this after
208 // a decode to 565, since choosing to decode to 565 may result in some of the decode
209 // options being modified. These options should return to their defaults on another
210 // decode to kN32, so the new digest should match the old digest.
msarette6dd0042015-10-09 11:07:34 -0700211 test_info(r, codec, info, expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700212
213 {
214 // Check alpha type conversions
215 if (info.alphaType() == kOpaque_SkAlphaType) {
216 test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800217 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700218 test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800219 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700220 } else {
221 // Decoding to opaque should fail
222 test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
halcanary96fcdcc2015-08-27 07:41:13 -0700223 SkCodec::kInvalidConversion, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700224 SkAlphaType otherAt = info.alphaType();
225 if (kPremul_SkAlphaType == otherAt) {
226 otherAt = kUnpremul_SkAlphaType;
227 } else {
228 otherAt = kPremul_SkAlphaType;
229 }
230 // The other non-opaque alpha type should always succeed, but not match.
msarette6dd0042015-10-09 11:07:34 -0700231 test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700232 }
233 }
msarettcc7f3052015-10-05 14:20:27 -0700234}
235
scroggobed1ed62016-02-11 10:24:55 -0800236static bool supports_partial_scanlines(const char path[]) {
scroggo2c3b2182015-10-09 08:40:59 -0700237 static const char* const exts[] = {
238 "jpg", "jpeg", "png", "webp"
239 "JPG", "JPEG", "PNG", "WEBP"
240 };
241
242 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
243 if (SkStrEndsWith(path, exts[i])) {
244 return true;
245 }
246 }
247 return false;
248}
249
scroggo6fb23912016-06-02 14:16:43 -0700250// FIXME: Break up this giant function
msarettcc7f3052015-10-05 14:20:27 -0700251static void check(skiatest::Reporter* r,
252 const char path[],
253 SkISize size,
254 bool supportsScanlineDecoding,
255 bool supportsSubsetDecoding,
scroggo6fb23912016-06-02 14:16:43 -0700256 bool supportsIncomplete,
257 bool supportsNewScanlineDecoding = false) {
msarettcc7f3052015-10-05 14:20:27 -0700258
259 SkAutoTDelete<SkStream> stream(resource(path));
260 if (!stream) {
261 SkDebugf("Missing resource '%s'\n", path);
262 return;
263 }
msarette6dd0042015-10-09 11:07:34 -0700264
265 SkAutoTDelete<SkCodec> codec(nullptr);
266 bool isIncomplete = supportsIncomplete;
267 if (isIncomplete) {
268 size_t size = stream->getLength();
269 SkAutoTUnref<SkData> data((SkData::NewFromStream(stream, 2 * size / 3)));
270 codec.reset(SkCodec::NewFromData(data));
271 } else {
mtklein18300a32016-03-16 13:53:35 -0700272 codec.reset(SkCodec::NewFromStream(stream.release()));
msarette6dd0042015-10-09 11:07:34 -0700273 }
msarettcc7f3052015-10-05 14:20:27 -0700274 if (!codec) {
275 ERRORF(r, "Unable to decode '%s'", path);
276 return;
277 }
278
279 // Test full image decodes with SkCodec
280 SkMD5::Digest codecDigest;
scroggoef0fed32016-02-18 05:59:25 -0800281 const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
msarettcc7f3052015-10-05 14:20:27 -0700282 SkBitmap bm;
msarette6dd0042015-10-09 11:07:34 -0700283 SkCodec::Result expectedResult = isIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
scroggo7b5e5532016-02-04 06:14:24 -0800284 test_codec(r, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700285
286 // Scanline decoding follows.
scroggo26694c32016-06-01 12:08:23 -0700287
scroggo6fb23912016-06-02 14:16:43 -0700288 if (supportsNewScanlineDecoding && !isIncomplete) {
289 test_incremental_decode(r, codec, info, codecDigest);
290 test_in_stripes(r, codec, info, codecDigest);
291 }
292
293 // Need to call startScanlineDecode() first.
294 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
295 REPORTER_ASSERT(r, !codec->skipScanlines(1));
scroggo46c57472015-09-30 08:57:13 -0700296 const SkCodec::Result startResult = codec->startScanlineDecode(info);
scroggo58421542015-04-01 11:25:20 -0700297 if (supportsScanlineDecoding) {
298 bm.eraseColor(SK_ColorYELLOW);
msarettc0e80c12015-07-01 06:50:35 -0700299
scroggo46c57472015-09-30 08:57:13 -0700300 REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
scroggo9b2cdbf42015-07-10 12:07:02 -0700301
scroggo58421542015-04-01 11:25:20 -0700302 for (int y = 0; y < info.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700303 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
304 if (!isIncomplete) {
305 REPORTER_ASSERT(r, 1 == lines);
306 }
scroggo58421542015-04-01 11:25:20 -0700307 }
308 // verify that scanline decoding gives the same result.
scroggo46c57472015-09-30 08:57:13 -0700309 if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
msarettcc7f3052015-10-05 14:20:27 -0700310 compare_to_good_digest(r, codecDigest, bm);
msarett5406d6f2015-08-31 06:55:13 -0700311 }
scroggo46c57472015-09-30 08:57:13 -0700312
313 // Cannot continue to decode scanlines beyond the end
314 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700315 == 0);
scroggo46c57472015-09-30 08:57:13 -0700316
317 // Interrupting a scanline decode with a full decode starts from
318 // scratch
319 REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
msarette6dd0042015-10-09 11:07:34 -0700320 const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
321 if (!isIncomplete) {
322 REPORTER_ASSERT(r, lines == 1);
323 }
scroggo46c57472015-09-30 08:57:13 -0700324 REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
msarette6dd0042015-10-09 11:07:34 -0700325 == expectedResult);
scroggo46c57472015-09-30 08:57:13 -0700326 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700327 == 0);
scroggo46c57472015-09-30 08:57:13 -0700328 REPORTER_ASSERT(r, codec->skipScanlines(1)
msarette6dd0042015-10-09 11:07:34 -0700329 == 0);
msarett80803ff2015-10-16 10:54:12 -0700330
331 // Test partial scanline decodes
scroggobed1ed62016-02-11 10:24:55 -0800332 if (supports_partial_scanlines(path) && info.width() >= 3) {
msarett80803ff2015-10-16 10:54:12 -0700333 SkCodec::Options options;
334 int width = info.width();
335 int height = info.height();
336 SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
337 options.fSubset = &subset;
338
339 const SkCodec::Result partialStartResult = codec->startScanlineDecode(info, &options,
340 nullptr, nullptr);
341 REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
342
343 for (int y = 0; y < height; y++) {
344 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
345 if (!isIncomplete) {
346 REPORTER_ASSERT(r, 1 == lines);
347 }
348 }
349 }
scroggo58421542015-04-01 11:25:20 -0700350 } else {
scroggo46c57472015-09-30 08:57:13 -0700351 REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
halcanarya096d7a2015-03-27 12:16:53 -0700352 }
scroggob636b452015-07-22 07:16:20 -0700353
354 // The rest of this function tests decoding subsets, and will decode an arbitrary number of
355 // random subsets.
356 // Do not attempt to decode subsets of an image of only once pixel, since there is no
357 // meaningful subset.
358 if (size.width() * size.height() == 1) {
359 return;
360 }
361
362 SkRandom rand;
363 SkIRect subset;
364 SkCodec::Options opts;
365 opts.fSubset = &subset;
366 for (int i = 0; i < 5; i++) {
367 subset = generate_random_subset(&rand, size.width(), size.height());
368 SkASSERT(!subset.isEmpty());
369 const bool supported = codec->getValidSubset(&subset);
370 REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
371
372 SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height());
373 SkBitmap bm;
374 bm.allocPixels(subsetInfo);
375 const SkCodec::Result result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(),
halcanary96fcdcc2015-08-27 07:41:13 -0700376 &opts, nullptr, nullptr);
scroggob636b452015-07-22 07:16:20 -0700377
378 if (supportsSubsetDecoding) {
msarette6dd0042015-10-09 11:07:34 -0700379 REPORTER_ASSERT(r, result == expectedResult);
scroggob636b452015-07-22 07:16:20 -0700380 // Webp is the only codec that supports subsets, and it will have modified the subset
381 // to have even left/top.
382 REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
383 } else {
384 // No subsets will work.
385 REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
386 }
387 }
msarettcc7f3052015-10-05 14:20:27 -0700388
scroggobed1ed62016-02-11 10:24:55 -0800389 // SkAndroidCodec tests
scroggo6fb23912016-06-02 14:16:43 -0700390 if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
scroggo2c3b2182015-10-09 08:40:59 -0700391
msarettcc7f3052015-10-05 14:20:27 -0700392 SkAutoTDelete<SkStream> stream(resource(path));
393 if (!stream) {
394 SkDebugf("Missing resource '%s'\n", path);
395 return;
396 }
msarette6dd0042015-10-09 11:07:34 -0700397
scroggo7b5e5532016-02-04 06:14:24 -0800398 SkAutoTDelete<SkAndroidCodec> androidCodec(nullptr);
msarette6dd0042015-10-09 11:07:34 -0700399 if (isIncomplete) {
400 size_t size = stream->getLength();
401 SkAutoTUnref<SkData> data((SkData::NewFromStream(stream, 2 * size / 3)));
scroggo7b5e5532016-02-04 06:14:24 -0800402 androidCodec.reset(SkAndroidCodec::NewFromData(data));
msarette6dd0042015-10-09 11:07:34 -0700403 } else {
mtklein18300a32016-03-16 13:53:35 -0700404 androidCodec.reset(SkAndroidCodec::NewFromStream(stream.release()));
msarette6dd0042015-10-09 11:07:34 -0700405 }
scroggo7b5e5532016-02-04 06:14:24 -0800406 if (!androidCodec) {
msarettcc7f3052015-10-05 14:20:27 -0700407 ERRORF(r, "Unable to decode '%s'", path);
408 return;
409 }
410
411 SkBitmap bm;
scroggobed1ed62016-02-11 10:24:55 -0800412 SkMD5::Digest androidCodecDigest;
413 test_codec(r, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
scroggo7b5e5532016-02-04 06:14:24 -0800414 &codecDigest);
msarette6dd0042015-10-09 11:07:34 -0700415 }
416
msarettedd2dcf2016-01-14 13:12:26 -0800417 if (!isIncomplete) {
scroggoef0fed32016-02-18 05:59:25 -0800418 // Test SkCodecImageGenerator
msarettedd2dcf2016-01-14 13:12:26 -0800419 SkAutoTDelete<SkStream> stream(resource(path));
420 SkAutoTUnref<SkData> fullData(SkData::NewFromStream(stream, stream->getLength()));
421 SkAutoTDelete<SkImageGenerator> gen(SkCodecImageGenerator::NewFromEncodedCodec(fullData));
422 SkBitmap bm;
423 bm.allocPixels(info);
424 SkAutoLockPixels autoLockPixels(bm);
425 REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
426 compare_to_good_digest(r, codecDigest, bm);
scroggoef0fed32016-02-18 05:59:25 -0800427
scroggo6fb23912016-06-02 14:16:43 -0700428#if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
429 // FIXME: With older versions of libpng, SkPngCodec requires being able to call
430 // SkStream::move(), which is not supported by SkFrontBufferedStream. (Android
431 // has a more recent version of libpng which uses png_process_data_pause to
432 // avoid calling move().)
433 if (!SkStrEndsWith(path, ".png"))
434#endif
435 {
436 // Test using SkFrontBufferedStream, as Android does
437 SkStream* bufferedStream = SkFrontBufferedStream::Create(new SkMemoryStream(fullData),
438 SkCodec::MinBufferedBytesNeeded());
439 REPORTER_ASSERT(r, bufferedStream);
440 codec.reset(SkCodec::NewFromStream(bufferedStream));
441 REPORTER_ASSERT(r, codec);
442 if (codec) {
443 test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
444 }
scroggoef0fed32016-02-18 05:59:25 -0800445 }
msarettedd2dcf2016-01-14 13:12:26 -0800446 }
447
msarette6dd0042015-10-09 11:07:34 -0700448 // If we've just tested incomplete decodes, let's run the same test again on full decodes.
449 if (isIncomplete) {
scroggo27c17282015-10-27 08:14:46 -0700450 check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false);
msarettcc7f3052015-10-05 14:20:27 -0700451 }
halcanarya096d7a2015-03-27 12:16:53 -0700452}
453
454DEF_TEST(Codec, r) {
455 // WBMP
scroggo6fb23912016-06-02 14:16:43 -0700456 check(r, "mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
halcanarya096d7a2015-03-27 12:16:53 -0700457
scroggo6f5e6192015-06-18 12:53:43 -0700458 // WEBP
scroggo6fb23912016-06-02 14:16:43 -0700459 check(r, "baby_tux.webp", SkISize::Make(386, 395), false, true, true);
460 check(r, "color_wheel.webp", SkISize::Make(128, 128), false, true, true);
461 check(r, "yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
scroggo6f5e6192015-06-18 12:53:43 -0700462
halcanarya096d7a2015-03-27 12:16:53 -0700463 // BMP
scroggo6fb23912016-06-02 14:16:43 -0700464 check(r, "randPixels.bmp", SkISize::Make(8, 8), true, false, true);
465 check(r, "rle.bmp", SkISize::Make(320, 240), true, false, true);
halcanarya096d7a2015-03-27 12:16:53 -0700466
467 // ICO
msarette6dd0042015-10-09 11:07:34 -0700468 // FIXME: We are not ready to test incomplete ICOs
msarett68b204e2015-04-01 12:09:21 -0700469 // These two tests examine interestingly different behavior:
470 // Decodes an embedded BMP image
msarettbe8216a2015-12-04 08:00:50 -0800471 check(r, "color_wheel.ico", SkISize::Make(128, 128), true, false, false);
msarett68b204e2015-04-01 12:09:21 -0700472 // Decodes an embedded PNG image
scroggo6fb23912016-06-02 14:16:43 -0700473 check(r, "google_chrome.ico", SkISize::Make(256, 256), false, false, false, true);
halcanarya096d7a2015-03-27 12:16:53 -0700474
msarett438b2ad2015-04-09 12:43:10 -0700475 // GIF
msarette6dd0042015-10-09 11:07:34 -0700476 // FIXME: We are not ready to test incomplete GIFs
scroggo27c17282015-10-27 08:14:46 -0700477 check(r, "box.gif", SkISize::Make(200, 55), true, false, false);
478 check(r, "color_wheel.gif", SkISize::Make(128, 128), true, false, false);
msarette6dd0042015-10-09 11:07:34 -0700479 // randPixels.gif is too small to test incomplete
scroggo27c17282015-10-27 08:14:46 -0700480 check(r, "randPixels.gif", SkISize::Make(8, 8), true, false, false);
msarett438b2ad2015-04-09 12:43:10 -0700481
msarette16b04a2015-04-15 07:32:19 -0700482 // JPG
scroggo6fb23912016-06-02 14:16:43 -0700483 check(r, "CMYK.jpg", SkISize::Make(642, 516), true, false, true);
484 check(r, "color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700485 // grayscale.jpg is too small to test incomplete
scroggo27c17282015-10-27 08:14:46 -0700486 check(r, "grayscale.jpg", SkISize::Make(128, 128), true, false, false);
scroggo6fb23912016-06-02 14:16:43 -0700487 check(r, "mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700488 // randPixels.jpg is too small to test incomplete
scroggo27c17282015-10-27 08:14:46 -0700489 check(r, "randPixels.jpg", SkISize::Make(8, 8), true, false, false);
msarette16b04a2015-04-15 07:32:19 -0700490
halcanarya096d7a2015-03-27 12:16:53 -0700491 // PNG
scroggo6fb23912016-06-02 14:16:43 -0700492 check(r, "arrow.png", SkISize::Make(187, 312), false, false, true, true);
493 check(r, "baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
494 check(r, "color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
495 // half-transparent-white-pixel.png is too small to test incomplete
496 check(r, "half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
497 check(r, "mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
498 check(r, "mandrill_16.png", SkISize::Make(16, 16), false, false, true, true);
499 check(r, "mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
500 check(r, "mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
501 check(r, "mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
502 check(r, "mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
503 check(r, "plane.png", SkISize::Make(250, 126), false, false, true, true);
504 check(r, "plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
505 check(r, "randPixels.png", SkISize::Make(8, 8), false, false, true, true);
506 check(r, "yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
yujieqin916de9f2016-01-25 08:26:16 -0800507
508 // RAW
yujieqinf236ee42016-02-29 07:14:42 -0800509// Disable RAW tests for Win32.
510#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin916de9f2016-01-25 08:26:16 -0800511 check(r, "sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
ebrauer46d2aa82016-02-17 08:04:00 -0800512 check(r, "sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
yujieqin9c7a8a42016-02-05 08:21:19 -0800513 check(r, "dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
msarett02cb4d42016-01-25 11:01:34 -0800514#endif
halcanarya096d7a2015-03-27 12:16:53 -0700515}
scroggo0a7e69c2015-04-03 07:22:22 -0700516
517static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
scroggo2c3b2182015-10-09 08:40:59 -0700518 // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
scroggo0a7e69c2015-04-03 07:22:22 -0700519 SkCodec* codec = SkCodec::NewFromStream(new SkMemoryStream(stream, len, false));
scroggo2c3b2182015-10-09 08:40:59 -0700520 REPORTER_ASSERT(r, !codec);
521
msarett3d9d7a72015-10-21 10:27:10 -0700522 SkAndroidCodec* androidCodec =
523 SkAndroidCodec::NewFromStream(new SkMemoryStream(stream, len, false));
524 REPORTER_ASSERT(r, !androidCodec);
scroggo0a7e69c2015-04-03 07:22:22 -0700525}
526
527// Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
528// even on failure. Test some bad streams.
529DEF_TEST(Codec_leaks, r) {
530 // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
531 const char nonSupportedStream[] = "hello world";
532 // The other strings should look like the beginning of a file type, so we'll call some
533 // internal version of NewFromStream, which must also delete the stream on failure.
534 const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
535 const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
536 const char emptyWebp[] = "RIFF1234WEBPVP";
537 const char emptyBmp[] = { 'B', 'M' };
538 const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
539 const char emptyGif[] = "GIFVER";
540
541 test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
542 test_invalid_stream(r, emptyPng, sizeof(emptyPng));
543 test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
544 test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
545 test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
546 test_invalid_stream(r, emptyIco, sizeof(emptyIco));
547 test_invalid_stream(r, emptyGif, sizeof(emptyGif));
548}
msarette16b04a2015-04-15 07:32:19 -0700549
scroggo2c3b2182015-10-09 08:40:59 -0700550DEF_TEST(Codec_null, r) {
scroggobed1ed62016-02-11 10:24:55 -0800551 // Attempting to create an SkCodec or an SkAndroidCodec with null should not
scroggo2c3b2182015-10-09 08:40:59 -0700552 // crash.
553 SkCodec* codec = SkCodec::NewFromStream(nullptr);
554 REPORTER_ASSERT(r, !codec);
555
msarett3d9d7a72015-10-21 10:27:10 -0700556 SkAndroidCodec* androidCodec = SkAndroidCodec::NewFromStream(nullptr);
557 REPORTER_ASSERT(r, !androidCodec);
scroggo2c3b2182015-10-09 08:40:59 -0700558}
559
msarette16b04a2015-04-15 07:32:19 -0700560static void test_dimensions(skiatest::Reporter* r, const char path[]) {
561 // Create the codec from the resource file
562 SkAutoTDelete<SkStream> stream(resource(path));
563 if (!stream) {
564 SkDebugf("Missing resource '%s'\n", path);
565 return;
566 }
mtklein18300a32016-03-16 13:53:35 -0700567 SkAutoTDelete<SkAndroidCodec> codec(SkAndroidCodec::NewFromStream(stream.release()));
msarette16b04a2015-04-15 07:32:19 -0700568 if (!codec) {
569 ERRORF(r, "Unable to create codec '%s'", path);
570 return;
571 }
572
573 // Check that the decode is successful for a variety of scales
scroggo501b7342015-11-03 07:55:11 -0800574 for (int sampleSize = 1; sampleSize < 32; sampleSize++) {
msarette16b04a2015-04-15 07:32:19 -0700575 // Scale the output dimensions
msarett3d9d7a72015-10-21 10:27:10 -0700576 SkISize scaledDims = codec->getSampledDimensions(sampleSize);
msarettb32758a2015-08-18 13:22:46 -0700577 SkImageInfo scaledInfo = codec->getInfo()
578 .makeWH(scaledDims.width(), scaledDims.height())
579 .makeColorType(kN32_SkColorType);
msarette16b04a2015-04-15 07:32:19 -0700580
581 // Set up for the decode
582 size_t rowBytes = scaledDims.width() * sizeof(SkPMColor);
583 size_t totalBytes = scaledInfo.getSafeSize(rowBytes);
584 SkAutoTMalloc<SkPMColor> pixels(totalBytes);
585
msarett3d9d7a72015-10-21 10:27:10 -0700586 SkAndroidCodec::AndroidOptions options;
587 options.fSampleSize = sampleSize;
scroggoeb602a52015-07-09 08:16:03 -0700588 SkCodec::Result result =
msarett3d9d7a72015-10-21 10:27:10 -0700589 codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options);
scroggoeb602a52015-07-09 08:16:03 -0700590 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarette16b04a2015-04-15 07:32:19 -0700591 }
592}
593
594// Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes
595DEF_TEST(Codec_Dimensions, r) {
596 // JPG
597 test_dimensions(r, "CMYK.jpg");
598 test_dimensions(r, "color_wheel.jpg");
599 test_dimensions(r, "grayscale.jpg");
600 test_dimensions(r, "mandrill_512_q075.jpg");
601 test_dimensions(r, "randPixels.jpg");
msarettb32758a2015-08-18 13:22:46 -0700602
603 // Decoding small images with very large scaling factors is a potential
604 // source of bugs and crashes. We disable these tests in Gold because
605 // tiny images are not very useful to look at.
606 // Here we make sure that we do not crash or access illegal memory when
607 // performing scaled decodes on small images.
608 test_dimensions(r, "1x1.png");
609 test_dimensions(r, "2x2.png");
610 test_dimensions(r, "3x3.png");
611 test_dimensions(r, "3x1.png");
612 test_dimensions(r, "1x1.png");
613 test_dimensions(r, "16x1.png");
614 test_dimensions(r, "1x16.png");
615 test_dimensions(r, "mandrill_16.png");
616
yujieqin916de9f2016-01-25 08:26:16 -0800617 // RAW
yujieqinf236ee42016-02-29 07:14:42 -0800618// Disable RAW tests for Win32.
619#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin916de9f2016-01-25 08:26:16 -0800620 test_dimensions(r, "sample_1mp.dng");
ebrauer46d2aa82016-02-17 08:04:00 -0800621 test_dimensions(r, "sample_1mp_rotated.dng");
yujieqin9c7a8a42016-02-05 08:21:19 -0800622 test_dimensions(r, "dng_with_preview.dng");
msarett8e49ca32016-01-25 13:10:58 -0800623#endif
msarette16b04a2015-04-15 07:32:19 -0700624}
625
msarettd0375bc2015-08-12 08:08:56 -0700626static void test_invalid(skiatest::Reporter* r, const char path[]) {
msarett4b17fa32015-04-23 08:53:39 -0700627 SkAutoTDelete<SkStream> stream(resource(path));
628 if (!stream) {
629 SkDebugf("Missing resource '%s'\n", path);
630 return;
631 }
mtklein18300a32016-03-16 13:53:35 -0700632 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
halcanary96fcdcc2015-08-27 07:41:13 -0700633 REPORTER_ASSERT(r, nullptr == codec);
msarett4b17fa32015-04-23 08:53:39 -0700634}
msarette16b04a2015-04-15 07:32:19 -0700635
msarett4b17fa32015-04-23 08:53:39 -0700636DEF_TEST(Codec_Empty, r) {
637 // Test images that should not be able to create a codec
msarettd0375bc2015-08-12 08:08:56 -0700638 test_invalid(r, "empty_images/zero-dims.gif");
639 test_invalid(r, "empty_images/zero-embedded.ico");
640 test_invalid(r, "empty_images/zero-width.bmp");
641 test_invalid(r, "empty_images/zero-height.bmp");
642 test_invalid(r, "empty_images/zero-width.jpg");
643 test_invalid(r, "empty_images/zero-height.jpg");
644 test_invalid(r, "empty_images/zero-width.png");
645 test_invalid(r, "empty_images/zero-height.png");
646 test_invalid(r, "empty_images/zero-width.wbmp");
647 test_invalid(r, "empty_images/zero-height.wbmp");
648 // This image is an ico with an embedded mask-bmp. This is illegal.
649 test_invalid(r, "invalid_images/mask-bmp-ico.ico");
msarett4b17fa32015-04-23 08:53:39 -0700650}
msarett99f567e2015-08-05 12:58:26 -0700651
652static void test_invalid_parameters(skiatest::Reporter* r, const char path[]) {
653 SkAutoTDelete<SkStream> stream(resource(path));
654 if (!stream) {
655 SkDebugf("Missing resource '%s'\n", path);
656 return;
657 }
mtklein18300a32016-03-16 13:53:35 -0700658 SkAutoTDelete<SkCodec> decoder(SkCodec::NewFromStream(stream.release()));
scroggo6fb23912016-06-02 14:16:43 -0700659 if (!decoder) {
660 SkDebugf("Missing codec for %s\n", path);
661 return;
662 }
663
664 const SkImageInfo info = decoder->getInfo().makeColorType(kIndex_8_SkColorType);
halcanary9d524f22016-03-29 09:03:52 -0700665
msarett99f567e2015-08-05 12:58:26 -0700666 // This should return kSuccess because kIndex8 is supported.
667 SkPMColor colorStorage[256];
668 int colorCount;
scroggo6fb23912016-06-02 14:16:43 -0700669 SkCodec::Result result = decoder->startScanlineDecode(info, nullptr, colorStorage,
670 &colorCount);
671 if (SkCodec::kSuccess == result) {
672 // This should return kInvalidParameters because, in kIndex_8 mode, we must pass in a valid
673 // colorPtr and a valid colorCountPtr.
674 result = decoder->startScanlineDecode(info, nullptr, nullptr, nullptr);
675 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
676 result = decoder->startScanlineDecode(info);
677 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
678 } else if (SkCodec::kUnimplemented == result) {
679 // New method should be supported:
680 SkBitmap bm;
681 sk_sp<SkColorTable> colorTable(new SkColorTable(colorStorage, 256));
682 bm.allocPixels(info, nullptr, colorTable.get());
683 result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), nullptr,
684 colorStorage, &colorCount);
685 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
686 result = decoder->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
687 REPORTER_ASSERT(r, SkCodec::kInvalidParameters == result);
688 } else {
689 // The test is uninteresting if kIndex8 is not supported
690 ERRORF(r, "Should not call test_invalid_parameters for non-Index8 file: %s\n", path);
msarett99f567e2015-08-05 12:58:26 -0700691 return;
692 }
693
msarett99f567e2015-08-05 12:58:26 -0700694}
695
696DEF_TEST(Codec_Params, r) {
697 test_invalid_parameters(r, "index8.png");
698 test_invalid_parameters(r, "mandrill.wbmp");
699}
scroggocf98fa92015-11-23 08:14:40 -0800700
701static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
702 SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
703 if (!sk_stream->write(data, len)) {
704 png_error(png_ptr, "sk_write_fn Error!");
705 }
706}
707
708#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
709DEF_TEST(Codec_pngChunkReader, r) {
710 // Create a dummy bitmap. Use unpremul RGBA for libpng.
711 SkBitmap bm;
712 const int w = 1;
713 const int h = 1;
714 const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
715 kUnpremul_SkAlphaType);
716 bm.setInfo(bmInfo);
717 bm.allocPixels();
718 bm.eraseColor(SK_ColorBLUE);
719 SkMD5::Digest goodDigest;
720 md5(bm, &goodDigest);
721
722 // Write to a png file.
723 png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
724 REPORTER_ASSERT(r, png);
725 if (!png) {
726 return;
727 }
728
729 png_infop info = png_create_info_struct(png);
730 REPORTER_ASSERT(r, info);
731 if (!info) {
732 png_destroy_write_struct(&png, nullptr);
733 return;
734 }
735
736 if (setjmp(png_jmpbuf(png))) {
737 ERRORF(r, "failed writing png");
738 png_destroy_write_struct(&png, &info);
739 return;
740 }
741
742 SkDynamicMemoryWStream wStream;
743 png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
744
745 png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
746 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
747 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
748
749 // Create some chunks that match the Android framework's use.
750 static png_unknown_chunk gUnknowns[] = {
msarett133eaaa2016-01-07 11:03:25 -0800751 { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
752 { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
753 { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
scroggocf98fa92015-11-23 08:14:40 -0800754 };
755
756 png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
757 png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
758#if PNG_LIBPNG_VER < 10600
759 /* Deal with unknown chunk location bug in 1.5.x and earlier */
msarett133eaaa2016-01-07 11:03:25 -0800760 png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
761 png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
scroggocf98fa92015-11-23 08:14:40 -0800762#endif
763
764 png_write_info(png, info);
765
766 for (int j = 0; j < h; j++) {
767 png_bytep row = (png_bytep)(bm.getAddr(0, j));
768 png_write_rows(png, &row, 1);
769 }
770 png_write_end(png, info);
771 png_destroy_write_struct(&png, &info);
772
773 class ChunkReader : public SkPngChunkReader {
774 public:
775 ChunkReader(skiatest::Reporter* r)
776 : fReporter(r)
777 {
778 this->reset();
779 }
780
781 bool readChunk(const char tag[], const void* data, size_t length) override {
782 for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
783 if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
784 // Tag matches. This should have been the first time we see it.
785 REPORTER_ASSERT(fReporter, !fSeen[i]);
786 fSeen[i] = true;
787
788 // Data and length should match
789 REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
790 REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
791 (const char*) gUnknowns[i].data));
792 return true;
793 }
794 }
795 ERRORF(fReporter, "Saw an unexpected unknown chunk.");
796 return true;
797 }
798
799 bool allHaveBeenSeen() {
800 bool ret = true;
801 for (auto seen : fSeen) {
802 ret &= seen;
803 }
804 return ret;
805 }
806
807 void reset() {
808 sk_bzero(fSeen, sizeof(fSeen));
809 }
810
811 private:
812 skiatest::Reporter* fReporter; // Unowned
813 bool fSeen[3];
814 };
815
816 ChunkReader chunkReader(r);
817
818 // Now read the file with SkCodec.
819 SkAutoTUnref<SkData> data(wStream.copyToData());
820 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(data, &chunkReader));
821 REPORTER_ASSERT(r, codec);
822 if (!codec) {
823 return;
824 }
825
826 // Now compare to the original.
827 SkBitmap decodedBm;
828 decodedBm.setInfo(codec->getInfo());
829 decodedBm.allocPixels();
830 SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
831 decodedBm.rowBytes());
832 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
833
834 if (decodedBm.colorType() != bm.colorType()) {
835 SkBitmap tmp;
836 bool success = decodedBm.copyTo(&tmp, bm.colorType());
837 REPORTER_ASSERT(r, success);
838 if (!success) {
839 return;
840 }
841
842 tmp.swap(decodedBm);
843 }
844
845 compare_to_good_digest(r, goodDigest, decodedBm);
846 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
847
848 // Decoding again will read the chunks again.
849 chunkReader.reset();
850 REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
851 result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
852 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
853 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
854}
855#endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
scroggob9a1e342015-11-30 06:25:31 -0800856
scroggodb30be22015-12-08 18:54:13 -0800857// Stream that can only peek up to a limit
858class LimitedPeekingMemStream : public SkStream {
859public:
860 LimitedPeekingMemStream(SkData* data, size_t limit)
861 : fStream(data)
862 , fLimit(limit) {}
863
864 size_t peek(void* buf, size_t bytes) const override {
865 return fStream.peek(buf, SkTMin(bytes, fLimit));
866 }
867 size_t read(void* buf, size_t bytes) override {
868 return fStream.read(buf, bytes);
869 }
870 bool rewind() override {
871 return fStream.rewind();
872 }
873 bool isAtEnd() const override {
874 return false;
875 }
876private:
877 SkMemoryStream fStream;
878 const size_t fLimit;
879};
880
yujieqin9c7a8a42016-02-05 08:21:19 -0800881// Stream that is not an asset stream (!hasPosition() or !hasLength())
882class NotAssetMemStream : public SkStream {
883public:
884 NotAssetMemStream(SkData* data) : fStream(data) {}
885
886 bool hasPosition() const override {
887 return false;
888 }
889
890 bool hasLength() const override {
891 return false;
892 }
893
894 size_t peek(void* buf, size_t bytes) const override {
895 return fStream.peek(buf, bytes);
896 }
897 size_t read(void* buf, size_t bytes) override {
898 return fStream.read(buf, bytes);
899 }
900 bool rewind() override {
901 return fStream.rewind();
902 }
903 bool isAtEnd() const override {
904 return fStream.isAtEnd();
905 }
906private:
907 SkMemoryStream fStream;
908};
909
yujieqinf236ee42016-02-29 07:14:42 -0800910// Disable RAW tests for Win32.
911#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin9c7a8a42016-02-05 08:21:19 -0800912// Test that the RawCodec works also for not asset stream. This will test the code path using
913// SkRawBufferedStream instead of SkRawAssetStream.
yujieqin9c7a8a42016-02-05 08:21:19 -0800914DEF_TEST(Codec_raw_notseekable, r) {
915 const char* path = "dng_with_preview.dng";
916 SkString fullPath(GetResourcePath(path));
917 SkAutoTUnref<SkData> data(SkData::NewFromFileName(fullPath.c_str()));
918 if (!data) {
919 SkDebugf("Missing resource '%s'\n", path);
920 return;
921 }
922
923 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(new NotAssetMemStream(data)));
924 REPORTER_ASSERT(r, codec);
925
926 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
927}
928#endif
929
scroggodb30be22015-12-08 18:54:13 -0800930// Test that even if webp_parse_header fails to peek enough, it will fall back to read()
931// + rewind() and succeed.
932DEF_TEST(Codec_webp_peek, r) {
933 const char* path = "baby_tux.webp";
934 SkString fullPath(GetResourcePath(path));
reedfde05112016-03-11 13:02:28 -0800935 auto data = SkData::MakeFromFileName(fullPath.c_str());
scroggodb30be22015-12-08 18:54:13 -0800936 if (!data) {
937 SkDebugf("Missing resource '%s'\n", path);
938 return;
939 }
940
941 // The limit is less than webp needs to peek or read.
reedfde05112016-03-11 13:02:28 -0800942 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(
943 new LimitedPeekingMemStream(data.get(), 25)));
scroggodb30be22015-12-08 18:54:13 -0800944 REPORTER_ASSERT(r, codec);
945
scroggo7b5e5532016-02-04 06:14:24 -0800946 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800947
948 // Similarly, a stream which does not peek should still succeed.
reedfde05112016-03-11 13:02:28 -0800949 codec.reset(SkCodec::NewFromStream(new LimitedPeekingMemStream(data.get(), 0)));
scroggodb30be22015-12-08 18:54:13 -0800950 REPORTER_ASSERT(r, codec);
951
scroggo7b5e5532016-02-04 06:14:24 -0800952 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800953}
954
msarett7f7ec202016-03-01 12:12:27 -0800955// SkCodec's wbmp decoder was initially unnecessarily restrictive.
956// It required the second byte to be zero. The wbmp specification allows
957// a couple of bits to be 1 (so long as they do not overlap with 0x9F).
958// Test that SkCodec now supports an image with these bits set.
scroggob9a1e342015-11-30 06:25:31 -0800959DEF_TEST(Codec_wbmp, r) {
960 const char* path = "mandrill.wbmp";
961 SkAutoTDelete<SkStream> stream(resource(path));
962 if (!stream) {
963 SkDebugf("Missing resource '%s'\n", path);
964 return;
965 }
966
967 // Modify the stream to contain a second byte with some bits set.
reedfde05112016-03-11 13:02:28 -0800968 auto data = SkCopyStreamToData(stream);
scroggob9a1e342015-11-30 06:25:31 -0800969 uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
970 writeableData[1] = static_cast<uint8_t>(~0x9F);
971
msarett7f7ec202016-03-01 12:12:27 -0800972 // SkCodec should support this.
reedfde05112016-03-11 13:02:28 -0800973 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromData(data.get()));
scroggob9a1e342015-11-30 06:25:31 -0800974 REPORTER_ASSERT(r, codec);
975 if (!codec) {
976 return;
977 }
scroggo7b5e5532016-02-04 06:14:24 -0800978 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggob9a1e342015-11-30 06:25:31 -0800979}
scroggodb30be22015-12-08 18:54:13 -0800980
981// wbmp images have a header that can be arbitrarily large, depending on the
982// size of the image. We cap the size at 65535, meaning we only need to look at
983// 8 bytes to determine whether we can read the image. This is important
984// because SkCodec only passes 14 bytes to SkWbmpCodec to determine whether the
985// image is a wbmp.
986DEF_TEST(Codec_wbmp_max_size, r) {
987 const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
988 0x83, 0xFF, 0x7F, // W: 65535
989 0x83, 0xFF, 0x7F }; // H: 65535
990 SkAutoTDelete<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
mtklein18300a32016-03-16 13:53:35 -0700991 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
scroggodb30be22015-12-08 18:54:13 -0800992
993 REPORTER_ASSERT(r, codec);
994 if (!codec) return;
995
996 REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
997 REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
998
999 // Now test an image which is too big. Any image with a larger header (i.e.
1000 // has bigger width/height) is also too big.
1001 const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
1002 0x84, 0x80, 0x00, // W: 65536
1003 0x84, 0x80, 0x00 }; // H: 65536
1004 stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false));
mtklein18300a32016-03-16 13:53:35 -07001005 codec.reset(SkCodec::NewFromStream(stream.release()));
scroggodb30be22015-12-08 18:54:13 -08001006
1007 REPORTER_ASSERT(r, !codec);
1008}
scroggo6fb23912016-06-02 14:16:43 -07001009
1010// Only rewinds up to a limit.
1011class LimitedRewindingStream : public SkStream {
1012public:
1013 static SkStream* Make(const char path[], size_t limit) {
1014 SkStream* stream = resource(path);
1015 if (!stream) {
1016 return nullptr;
1017 }
1018 return new LimitedRewindingStream(stream, limit);
1019 }
1020
1021 size_t read(void* buffer, size_t size) override {
1022 const size_t bytes = fStream->read(buffer, size);
1023 fPosition += bytes;
1024 return bytes;
1025 }
1026
1027 bool isAtEnd() const override {
1028 return fStream->isAtEnd();
1029 }
1030
1031 bool rewind() override {
1032 if (fPosition <= fLimit && fStream->rewind()) {
1033 fPosition = 0;
1034 return true;
1035 }
1036
1037 return false;
1038 }
1039
1040private:
1041 SkAutoTDelete<SkStream> fStream;
1042 const size_t fLimit;
1043 size_t fPosition;
1044
1045 LimitedRewindingStream(SkStream* stream, size_t limit)
1046 : fStream(stream)
1047 , fLimit(limit)
1048 , fPosition(0)
1049 {
1050 SkASSERT(fStream);
1051 }
1052};
1053
1054DEF_TEST(Codec_fallBack, r) {
1055 // SkAndroidCodec needs to be able to fall back to scanline decoding
1056 // if incremental decoding does not work. Make sure this does not
1057 // require a rewind.
1058
1059 // Formats that currently do not support incremental decoding
1060 auto files = {
1061 "box.gif",
1062 "CMYK.jpg",
1063 "color_wheel.ico",
1064 "mandrill.wbmp",
1065 "randPixels.bmp",
1066 };
1067 for (auto file : files) {
1068 SkStream* stream = LimitedRewindingStream::Make(file, 14);
1069 if (!stream) {
1070 SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
1071 return;
1072 }
1073
1074 SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream));
1075 if (!codec) {
1076 ERRORF(r, "Failed to create codec for %s,", file);
1077 continue;
1078 }
1079
1080 SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
1081 SkBitmap bm;
1082 bm.allocPixels(info);
1083
1084 if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
1085 bm.rowBytes())) {
1086 ERRORF(r, "Is scanline decoding now implemented for %s?", file);
1087 continue;
1088 }
1089
1090 // Scanline decoding should not require a rewind.
1091 SkCodec::Result result = codec->startScanlineDecode(info);
1092 if (SkCodec::kSuccess != result) {
1093 ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
1094 }
1095 }
1096}