blob: 23db4a978fa463388a7e8f45d4a6064d8a5a1abc [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/codec/SkAndroidCodec.h"
9#include "include/codec/SkCodec.h"
10#include "include/core/SkBitmap.h"
11#include "include/core/SkCanvas.h"
12#include "include/core/SkColor.h"
13#include "include/core/SkColorSpace.h"
14#include "include/core/SkData.h"
15#include "include/core/SkEncodedImageFormat.h"
16#include "include/core/SkImage.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040017#include "include/core/SkImageEncoder.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "include/core/SkImageGenerator.h"
19#include "include/core/SkImageInfo.h"
20#include "include/core/SkPixmap.h"
21#include "include/core/SkPngChunkReader.h"
22#include "include/core/SkRect.h"
23#include "include/core/SkRefCnt.h"
24#include "include/core/SkSize.h"
25#include "include/core/SkStream.h"
26#include "include/core/SkString.h"
27#include "include/core/SkTypes.h"
28#include "include/core/SkUnPreMultiply.h"
29#include "include/encode/SkJpegEncoder.h"
30#include "include/encode/SkPngEncoder.h"
31#include "include/encode/SkWebpEncoder.h"
32#include "include/private/SkMalloc.h"
33#include "include/private/SkTemplates.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040034#include "include/third_party/skcms/skcms.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050035#include "include/utils/SkFrontBufferedStream.h"
36#include "include/utils/SkRandom.h"
37#include "src/codec/SkCodecImageGenerator.h"
38#include "src/core/SkAutoMalloc.h"
39#include "src/core/SkColorSpacePriv.h"
40#include "src/core/SkMD5.h"
41#include "src/core/SkMakeUnique.h"
42#include "src/core/SkStreamPriv.h"
43#include "tests/FakeStreams.h"
44#include "tests/Test.h"
45#include "tools/Resources.h"
46#include "tools/ToolUtils.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040047
Ben Wagner501c17c2018-03-12 20:04:31 +000048#include "png.h"
Ben Wagner1a462bd2018-03-12 13:46:21 -040049
Ben Wagnerb607a8f2018-03-12 13:46:21 -040050#include <setjmp.h>
51#include <cstring>
Ben Wagner9707a7e2019-05-06 17:17:19 -040052#include <initializer_list>
Ben Wagnerb607a8f2018-03-12 13:46:21 -040053#include <memory>
54#include <utility>
55#include <vector>
56
scroggo8e6c7ad2016-09-16 08:20:38 -070057#if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
58 // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In
59 // the meantime, we had to break some pieces of SkPngCodec in order to support Google3.
60 // The parts that are broken are likely not used by Google3.
61 #define SK_PNG_DISABLE_TESTS
62#endif
63
Hal Canary0f2f5222019-04-03 10:13:45 -040064static SkMD5::Digest md5(const SkBitmap& bm) {
halcanarya096d7a2015-03-27 12:16:53 -070065 SkASSERT(bm.getPixels());
66 SkMD5 md5;
67 size_t rowLen = bm.info().bytesPerPixel() * bm.width();
68 for (int y = 0; y < bm.height(); ++y) {
halcanary1e903042016-04-25 10:29:36 -070069 md5.write(bm.getAddr(0, y), rowLen);
halcanarya096d7a2015-03-27 12:16:53 -070070 }
Hal Canary0f2f5222019-04-03 10:13:45 -040071 return md5.finish();
halcanarya096d7a2015-03-27 12:16:53 -070072}
73
scroggo9b2cdbf42015-07-10 12:07:02 -070074/**
75 * Compute the digest for bm and compare it to a known good digest.
76 * @param r Reporter to assert that bm's digest matches goodDigest.
77 * @param goodDigest The known good digest to compare to.
78 * @param bm The bitmap to test.
79 */
80static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
81 const SkBitmap& bm) {
Hal Canary0f2f5222019-04-03 10:13:45 -040082 SkMD5::Digest digest = md5(bm);
scroggo9b2cdbf42015-07-10 12:07:02 -070083 REPORTER_ASSERT(r, digest == goodDigest);
84}
85
scroggod1bc5742015-08-12 08:31:44 -070086/**
87 * Test decoding an SkCodec to a particular SkImageInfo.
88 *
halcanary96fcdcc2015-08-27 07:41:13 -070089 * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
scroggod1bc5742015-08-12 08:31:44 -070090 * the resulting decode should match.
91 */
scroggo7b5e5532016-02-04 06:14:24 -080092template<typename Codec>
93static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
scroggod1bc5742015-08-12 08:31:44 -070094 SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
95 SkBitmap bm;
96 bm.allocPixels(info);
scroggod1bc5742015-08-12 08:31:44 -070097
98 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
99 REPORTER_ASSERT(r, result == expectedResult);
100
101 if (goodDigest) {
102 compare_to_good_digest(r, *goodDigest, bm);
103 }
104}
105
scroggob636b452015-07-22 07:16:20 -0700106SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
107 SkIRect rect;
108 do {
109 rect.fLeft = rand->nextRangeU(0, w);
110 rect.fTop = rand->nextRangeU(0, h);
111 rect.fRight = rand->nextRangeU(0, w);
112 rect.fBottom = rand->nextRangeU(0, h);
113 rect.sort();
114 } while (rect.isEmpty());
115 return rect;
116}
117
scroggo8e6c7ad2016-09-16 08:20:38 -0700118static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
119 const SkMD5::Digest& goodDigest) {
120 SkBitmap bm;
121 bm.allocPixels(info);
scroggo8e6c7ad2016-09-16 08:20:38 -0700122
123 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
124 bm.rowBytes()));
125
126 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
127
128 compare_to_good_digest(r, goodDigest, bm);
129}
130
131// Test in stripes, similar to DM's kStripe_Mode
132static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
133 const SkMD5::Digest& goodDigest) {
134 SkBitmap bm;
135 bm.allocPixels(info);
136 bm.eraseColor(SK_ColorYELLOW);
137
138 const int height = info.height();
139 // Note that if numStripes does not evenly divide height there will be an extra
140 // stripe.
141 const int numStripes = 4;
142
143 if (numStripes > height) {
144 // Image is too small.
145 return;
146 }
147
148 const int stripeHeight = height / numStripes;
149
150 // Iterate through the image twice. Once to decode odd stripes, and once for even.
151 for (int oddEven = 1; oddEven >= 0; oddEven--) {
152 for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
153 SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
154 SkTMin(y + stripeHeight, height));
155 SkCodec::Options options;
156 options.fSubset = &subset;
157 if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
158 bm.rowBytes(), &options)) {
159 ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
160 subset.top(), subset.bottom());
161 return;
162 }
163 if (SkCodec::kSuccess != codec->incrementalDecode()) {
164 ERRORF(r, "failed incremental decode starting from line %i\n", y);
165 return;
166 }
167 }
168 }
169
170 compare_to_good_digest(r, goodDigest, bm);
171}
172
scroggo7b5e5532016-02-04 06:14:24 -0800173template<typename Codec>
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500174static void test_codec(skiatest::Reporter* r, const char* path, Codec* codec, SkBitmap& bm,
175 const SkImageInfo& info, const SkISize& size, SkCodec::Result expectedResult,
176 SkMD5::Digest* digest, const SkMD5::Digest* goodDigest) {
msarette6dd0042015-10-09 11:07:34 -0700177
halcanarya096d7a2015-03-27 12:16:53 -0700178 REPORTER_ASSERT(r, info.dimensions() == size);
halcanarya096d7a2015-03-27 12:16:53 -0700179 bm.allocPixels(info);
msarettcc7f3052015-10-05 14:20:27 -0700180
181 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
msarette6dd0042015-10-09 11:07:34 -0700182 REPORTER_ASSERT(r, result == expectedResult);
halcanarya096d7a2015-03-27 12:16:53 -0700183
Hal Canary0f2f5222019-04-03 10:13:45 -0400184 *digest = md5(bm);
msarettcc7f3052015-10-05 14:20:27 -0700185 if (goodDigest) {
186 REPORTER_ASSERT(r, *digest == *goodDigest);
187 }
halcanarya096d7a2015-03-27 12:16:53 -0700188
msarett8ff6ca62015-09-18 12:06:04 -0700189 {
190 // Test decoding to 565
191 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
scroggoba584892016-05-20 13:56:13 -0700192 if (info.alphaType() == kOpaque_SkAlphaType) {
193 // Decoding to 565 should succeed.
194 SkBitmap bm565;
195 bm565.allocPixels(info565);
scroggoba584892016-05-20 13:56:13 -0700196
197 // This will allow comparison even if the image is incomplete.
198 bm565.eraseColor(SK_ColorBLACK);
199
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500200 auto actualResult = codec->getPixels(info565, bm565.getPixels(), bm565.rowBytes());
201 if (actualResult == expectedResult) {
Hal Canary0f2f5222019-04-03 10:13:45 -0400202 SkMD5::Digest digest565 = md5(bm565);
scroggoba584892016-05-20 13:56:13 -0700203
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500204 // A request for non-opaque should also succeed.
205 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
206 info565 = info565.makeAlphaType(alpha);
207 test_info(r, codec, info565, expectedResult, &digest565);
208 }
209 } else {
210 ERRORF(r, "Decoding %s to 565 failed with result \"%s\"\n\t\t\t\texpected:\"%s\"",
211 path,
212 SkCodec::ResultToString(actualResult),
213 SkCodec::ResultToString(expectedResult));
scroggoba584892016-05-20 13:56:13 -0700214 }
215 } else {
216 test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
217 }
218 }
219
220 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
221 SkImageInfo grayInfo = codec->getInfo();
222 SkBitmap grayBm;
223 grayBm.allocPixels(grayInfo);
scroggoba584892016-05-20 13:56:13 -0700224
225 grayBm.eraseColor(SK_ColorBLACK);
226
227 REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
228 grayBm.getPixels(), grayBm.rowBytes()));
229
Hal Canary0f2f5222019-04-03 10:13:45 -0400230 SkMD5::Digest grayDigest = md5(grayBm);
scroggoba584892016-05-20 13:56:13 -0700231
232 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
233 grayInfo = grayInfo.makeAlphaType(alpha);
234 test_info(r, codec, grayInfo, expectedResult, &grayDigest);
235 }
msarett8ff6ca62015-09-18 12:06:04 -0700236 }
237
238 // Verify that re-decoding gives the same result. It is interesting to check this after
239 // a decode to 565, since choosing to decode to 565 may result in some of the decode
240 // options being modified. These options should return to their defaults on another
241 // decode to kN32, so the new digest should match the old digest.
msarette6dd0042015-10-09 11:07:34 -0700242 test_info(r, codec, info, expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700243
244 {
245 // Check alpha type conversions
246 if (info.alphaType() == kOpaque_SkAlphaType) {
247 test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800248 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700249 test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800250 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700251 } else {
252 // Decoding to opaque should fail
253 test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
halcanary96fcdcc2015-08-27 07:41:13 -0700254 SkCodec::kInvalidConversion, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700255 SkAlphaType otherAt = info.alphaType();
256 if (kPremul_SkAlphaType == otherAt) {
257 otherAt = kUnpremul_SkAlphaType;
258 } else {
259 otherAt = kPremul_SkAlphaType;
260 }
261 // The other non-opaque alpha type should always succeed, but not match.
msarette6dd0042015-10-09 11:07:34 -0700262 test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700263 }
264 }
msarettcc7f3052015-10-05 14:20:27 -0700265}
266
scroggobed1ed62016-02-11 10:24:55 -0800267static bool supports_partial_scanlines(const char path[]) {
scroggo2c3b2182015-10-09 08:40:59 -0700268 static const char* const exts[] = {
269 "jpg", "jpeg", "png", "webp"
270 "JPG", "JPEG", "PNG", "WEBP"
271 };
272
273 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
274 if (SkStrEndsWith(path, exts[i])) {
275 return true;
276 }
277 }
278 return false;
279}
280
scroggo8e6c7ad2016-09-16 08:20:38 -0700281// FIXME: Break up this giant function
msarettcc7f3052015-10-05 14:20:27 -0700282static void check(skiatest::Reporter* r,
283 const char path[],
284 SkISize size,
285 bool supportsScanlineDecoding,
286 bool supportsSubsetDecoding,
scroggo8e6c7ad2016-09-16 08:20:38 -0700287 bool supportsIncomplete,
288 bool supportsNewScanlineDecoding = false) {
Nigel Tao9b9453e2018-08-01 09:59:38 +1000289 // If we're testing incomplete decodes, let's run the same test on full decodes.
290 if (supportsIncomplete) {
291 check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false,
292 supportsNewScanlineDecoding);
293 }
msarettcc7f3052015-10-05 14:20:27 -0700294
Ben Wagner145dbcd2016-11-03 14:40:50 -0400295 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700296 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700297 return;
298 }
msarette6dd0042015-10-09 11:07:34 -0700299
Ben Wagner145dbcd2016-11-03 14:40:50 -0400300 std::unique_ptr<SkCodec> codec(nullptr);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000301 if (supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700302 size_t size = stream->getLength();
Mike Reedede7bac2017-07-23 15:30:02 -0400303 codec = SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 2 * size / 3));
msarette6dd0042015-10-09 11:07:34 -0700304 } else {
Mike Reedede7bac2017-07-23 15:30:02 -0400305 codec = SkCodec::MakeFromStream(std::move(stream));
msarette6dd0042015-10-09 11:07:34 -0700306 }
msarettcc7f3052015-10-05 14:20:27 -0700307 if (!codec) {
308 ERRORF(r, "Unable to decode '%s'", path);
309 return;
310 }
311
312 // Test full image decodes with SkCodec
313 SkMD5::Digest codecDigest;
scroggoef0fed32016-02-18 05:59:25 -0800314 const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
msarettcc7f3052015-10-05 14:20:27 -0700315 SkBitmap bm;
Nigel Tao9b9453e2018-08-01 09:59:38 +1000316 SkCodec::Result expectedResult =
317 supportsIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500318 test_codec(r, path, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700319
320 // Scanline decoding follows.
scroggod8d68552016-06-06 11:26:17 -0700321
Nigel Tao9b9453e2018-08-01 09:59:38 +1000322 if (supportsNewScanlineDecoding && !supportsIncomplete) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400323 test_incremental_decode(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700324 // This is only supported by codecs that use incremental decoding to
325 // support subset decodes - png and jpeg (once SkJpegCodec is
326 // converted).
327 if (SkStrEndsWith(path, "png") || SkStrEndsWith(path, "PNG")) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400328 test_in_stripes(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700329 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700330 }
331
332 // Need to call startScanlineDecode() first.
333 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
334 REPORTER_ASSERT(r, !codec->skipScanlines(1));
scroggo46c57472015-09-30 08:57:13 -0700335 const SkCodec::Result startResult = codec->startScanlineDecode(info);
scroggo58421542015-04-01 11:25:20 -0700336 if (supportsScanlineDecoding) {
337 bm.eraseColor(SK_ColorYELLOW);
msarettc0e80c12015-07-01 06:50:35 -0700338
scroggo46c57472015-09-30 08:57:13 -0700339 REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
scroggo9b2cdbf42015-07-10 12:07:02 -0700340
scroggo58421542015-04-01 11:25:20 -0700341 for (int y = 0; y < info.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700342 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000343 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700344 REPORTER_ASSERT(r, 1 == lines);
345 }
scroggo58421542015-04-01 11:25:20 -0700346 }
347 // verify that scanline decoding gives the same result.
scroggo46c57472015-09-30 08:57:13 -0700348 if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
msarettcc7f3052015-10-05 14:20:27 -0700349 compare_to_good_digest(r, codecDigest, bm);
msarett5406d6f2015-08-31 06:55:13 -0700350 }
scroggo46c57472015-09-30 08:57:13 -0700351
352 // Cannot continue to decode scanlines beyond the end
353 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700354 == 0);
scroggo46c57472015-09-30 08:57:13 -0700355
356 // Interrupting a scanline decode with a full decode starts from
357 // scratch
358 REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
msarette6dd0042015-10-09 11:07:34 -0700359 const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000360 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700361 REPORTER_ASSERT(r, lines == 1);
362 }
scroggo46c57472015-09-30 08:57:13 -0700363 REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
msarette6dd0042015-10-09 11:07:34 -0700364 == expectedResult);
scroggo46c57472015-09-30 08:57:13 -0700365 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700366 == 0);
scroggo46c57472015-09-30 08:57:13 -0700367 REPORTER_ASSERT(r, codec->skipScanlines(1)
msarette6dd0042015-10-09 11:07:34 -0700368 == 0);
msarett80803ff2015-10-16 10:54:12 -0700369
370 // Test partial scanline decodes
scroggobed1ed62016-02-11 10:24:55 -0800371 if (supports_partial_scanlines(path) && info.width() >= 3) {
msarett80803ff2015-10-16 10:54:12 -0700372 SkCodec::Options options;
373 int width = info.width();
374 int height = info.height();
375 SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
376 options.fSubset = &subset;
377
Leon Scroggins571b30f2017-07-11 17:35:31 +0000378 const auto partialStartResult = codec->startScanlineDecode(info, &options);
msarett80803ff2015-10-16 10:54:12 -0700379 REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
380
381 for (int y = 0; y < height; y++) {
382 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000383 if (!supportsIncomplete) {
msarett80803ff2015-10-16 10:54:12 -0700384 REPORTER_ASSERT(r, 1 == lines);
385 }
386 }
387 }
scroggo58421542015-04-01 11:25:20 -0700388 } else {
scroggo46c57472015-09-30 08:57:13 -0700389 REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
halcanarya096d7a2015-03-27 12:16:53 -0700390 }
scroggob636b452015-07-22 07:16:20 -0700391
392 // The rest of this function tests decoding subsets, and will decode an arbitrary number of
393 // random subsets.
394 // Do not attempt to decode subsets of an image of only once pixel, since there is no
395 // meaningful subset.
396 if (size.width() * size.height() == 1) {
397 return;
398 }
399
400 SkRandom rand;
401 SkIRect subset;
402 SkCodec::Options opts;
403 opts.fSubset = &subset;
404 for (int i = 0; i < 5; i++) {
405 subset = generate_random_subset(&rand, size.width(), size.height());
406 SkASSERT(!subset.isEmpty());
407 const bool supported = codec->getValidSubset(&subset);
408 REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
409
410 SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height());
411 SkBitmap bm;
412 bm.allocPixels(subsetInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +0000413 const auto result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &opts);
scroggob636b452015-07-22 07:16:20 -0700414
415 if (supportsSubsetDecoding) {
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500416 if (expectedResult == SkCodec::kSuccess) {
417 REPORTER_ASSERT(r, result == expectedResult);
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500418 }
scroggob636b452015-07-22 07:16:20 -0700419 // Webp is the only codec that supports subsets, and it will have modified the subset
420 // to have even left/top.
421 REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
422 } else {
423 // No subsets will work.
424 REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
425 }
426 }
msarettcc7f3052015-10-05 14:20:27 -0700427
scroggobed1ed62016-02-11 10:24:55 -0800428 // SkAndroidCodec tests
scroggo8e6c7ad2016-09-16 08:20:38 -0700429 if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
scroggo2c3b2182015-10-09 08:40:59 -0700430
Ben Wagner145dbcd2016-11-03 14:40:50 -0400431 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700432 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700433 return;
434 }
msarette6dd0042015-10-09 11:07:34 -0700435
Leon Scroggins III7397d7a2018-01-04 13:26:30 -0500436 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
scroggo7b5e5532016-02-04 06:14:24 -0800437 if (!androidCodec) {
msarettcc7f3052015-10-05 14:20:27 -0700438 ERRORF(r, "Unable to decode '%s'", path);
439 return;
440 }
441
442 SkBitmap bm;
scroggobed1ed62016-02-11 10:24:55 -0800443 SkMD5::Digest androidCodecDigest;
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500444 test_codec(r, path, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
scroggo7b5e5532016-02-04 06:14:24 -0800445 &codecDigest);
msarette6dd0042015-10-09 11:07:34 -0700446 }
447
Nigel Tao9b9453e2018-08-01 09:59:38 +1000448 if (!supportsIncomplete) {
scroggoef0fed32016-02-18 05:59:25 -0800449 // Test SkCodecImageGenerator
Ben Wagner145dbcd2016-11-03 14:40:50 -0400450 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
451 sk_sp<SkData> fullData(SkData::MakeFromStream(stream.get(), stream->getLength()));
452 std::unique_ptr<SkImageGenerator> gen(
Mike Reed185130c2017-02-15 15:14:16 -0500453 SkCodecImageGenerator::MakeFromEncodedCodec(fullData));
msarettedd2dcf2016-01-14 13:12:26 -0800454 SkBitmap bm;
455 bm.allocPixels(info);
msarettedd2dcf2016-01-14 13:12:26 -0800456 REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
457 compare_to_good_digest(r, codecDigest, bm);
scroggoef0fed32016-02-18 05:59:25 -0800458
scroggo8e6c7ad2016-09-16 08:20:38 -0700459#ifndef SK_PNG_DISABLE_TESTS
scroggod8d68552016-06-06 11:26:17 -0700460 // Test using SkFrontBufferedStream, as Android does
Mike Reed98c5d922017-09-15 21:39:47 -0400461 auto bufferedStream = SkFrontBufferedStream::Make(
462 SkMemoryStream::Make(std::move(fullData)), SkCodec::MinBufferedBytesNeeded());
scroggod8d68552016-06-06 11:26:17 -0700463 REPORTER_ASSERT(r, bufferedStream);
Mike Reed98c5d922017-09-15 21:39:47 -0400464 codec = SkCodec::MakeFromStream(std::move(bufferedStream));
scroggod8d68552016-06-06 11:26:17 -0700465 REPORTER_ASSERT(r, codec);
466 if (codec) {
467 test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
scroggoef0fed32016-02-18 05:59:25 -0800468 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700469#endif
msarettedd2dcf2016-01-14 13:12:26 -0800470 }
halcanarya096d7a2015-03-27 12:16:53 -0700471}
472
Leon Scroggins III83926342016-12-06 10:58:02 -0500473DEF_TEST(Codec_wbmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500474 check(r, "images/mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500475}
halcanarya096d7a2015-03-27 12:16:53 -0700476
Leon Scroggins III83926342016-12-06 10:58:02 -0500477DEF_TEST(Codec_webp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500478 check(r, "images/baby_tux.webp", SkISize::Make(386, 395), false, true, true);
479 check(r, "images/color_wheel.webp", SkISize::Make(128, 128), false, true, true);
480 check(r, "images/yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500481}
scroggo6f5e6192015-06-18 12:53:43 -0700482
Leon Scroggins III83926342016-12-06 10:58:02 -0500483DEF_TEST(Codec_bmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500484 check(r, "images/randPixels.bmp", SkISize::Make(8, 8), true, false, true);
485 check(r, "images/rle.bmp", SkISize::Make(320, 240), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500486}
halcanarya096d7a2015-03-27 12:16:53 -0700487
Leon Scroggins III83926342016-12-06 10:58:02 -0500488DEF_TEST(Codec_ico, r) {
msarette6dd0042015-10-09 11:07:34 -0700489 // FIXME: We are not ready to test incomplete ICOs
msarett68b204e2015-04-01 12:09:21 -0700490 // These two tests examine interestingly different behavior:
491 // Decodes an embedded BMP image
Hal Canaryc465d132017-12-08 10:21:31 -0500492 check(r, "images/color_wheel.ico", SkISize::Make(128, 128), true, false, false);
msarett68b204e2015-04-01 12:09:21 -0700493 // Decodes an embedded PNG image
Hal Canaryc465d132017-12-08 10:21:31 -0500494 check(r, "images/google_chrome.ico", SkISize::Make(256, 256), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500495}
halcanarya096d7a2015-03-27 12:16:53 -0700496
Leon Scroggins III83926342016-12-06 10:58:02 -0500497DEF_TEST(Codec_gif, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500498 check(r, "images/box.gif", SkISize::Make(200, 55), false, false, true, true);
499 check(r, "images/color_wheel.gif", SkISize::Make(128, 128), false, false, true, true);
msarette6dd0042015-10-09 11:07:34 -0700500 // randPixels.gif is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500501 check(r, "images/randPixels.gif", SkISize::Make(8, 8), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500502}
msarett438b2ad2015-04-09 12:43:10 -0700503
Leon Scroggins III83926342016-12-06 10:58:02 -0500504DEF_TEST(Codec_jpg, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500505 check(r, "images/CMYK.jpg", SkISize::Make(642, 516), true, false, true);
506 check(r, "images/color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700507 // grayscale.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500508 check(r, "images/grayscale.jpg", SkISize::Make(128, 128), true, false, false);
509 check(r, "images/mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700510 // randPixels.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500511 check(r, "images/randPixels.jpg", SkISize::Make(8, 8), true, false, false);
Leon Scroggins III83926342016-12-06 10:58:02 -0500512}
msarette16b04a2015-04-15 07:32:19 -0700513
Leon Scroggins III83926342016-12-06 10:58:02 -0500514DEF_TEST(Codec_png, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500515 check(r, "images/arrow.png", SkISize::Make(187, 312), false, false, true, true);
516 check(r, "images/baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
517 check(r, "images/color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
scroggo8e6c7ad2016-09-16 08:20:38 -0700518 // half-transparent-white-pixel.png is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500519 check(r, "images/half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
520 check(r, "images/mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
Brian Osmanccb21bf2018-07-09 14:57:48 -0400521 // mandrill_16.png is too small (relative to embedded sRGB profile) to test incomplete
522 check(r, "images/mandrill_16.png", SkISize::Make(16, 16), false, false, false, true);
Hal Canaryc465d132017-12-08 10:21:31 -0500523 check(r, "images/mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
524 check(r, "images/mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
525 check(r, "images/mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
526 check(r, "images/mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
527 check(r, "images/plane.png", SkISize::Make(250, 126), false, false, true, true);
528 check(r, "images/plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
529 check(r, "images/randPixels.png", SkISize::Make(8, 8), false, false, true, true);
530 check(r, "images/yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500531}
yujieqin916de9f2016-01-25 08:26:16 -0800532
yujieqinf236ee42016-02-29 07:14:42 -0800533// Disable RAW tests for Win32.
534#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Leon Scroggins III83926342016-12-06 10:58:02 -0500535DEF_TEST(Codec_raw, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500536 check(r, "images/sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
537 check(r, "images/sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
538 check(r, "images/dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
halcanarya096d7a2015-03-27 12:16:53 -0700539}
Leon Scroggins III83926342016-12-06 10:58:02 -0500540#endif
scroggo0a7e69c2015-04-03 07:22:22 -0700541
542static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
scroggo2c3b2182015-10-09 08:40:59 -0700543 // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
Mike Reedede7bac2017-07-23 15:30:02 -0400544 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(
545 skstd::make_unique<SkMemoryStream>(stream, len, false)));
546 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(
547 skstd::make_unique<SkMemoryStream>(stream, len, false)));
scroggo0a7e69c2015-04-03 07:22:22 -0700548}
549
550// Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
551// even on failure. Test some bad streams.
552DEF_TEST(Codec_leaks, r) {
553 // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
554 const char nonSupportedStream[] = "hello world";
555 // The other strings should look like the beginning of a file type, so we'll call some
556 // internal version of NewFromStream, which must also delete the stream on failure.
557 const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
558 const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
559 const char emptyWebp[] = "RIFF1234WEBPVP";
560 const char emptyBmp[] = { 'B', 'M' };
561 const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
562 const char emptyGif[] = "GIFVER";
563
564 test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
565 test_invalid_stream(r, emptyPng, sizeof(emptyPng));
566 test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
567 test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
568 test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
569 test_invalid_stream(r, emptyIco, sizeof(emptyIco));
570 test_invalid_stream(r, emptyGif, sizeof(emptyGif));
571}
msarette16b04a2015-04-15 07:32:19 -0700572
scroggo2c3b2182015-10-09 08:40:59 -0700573DEF_TEST(Codec_null, r) {
scroggobed1ed62016-02-11 10:24:55 -0800574 // Attempting to create an SkCodec or an SkAndroidCodec with null should not
scroggo2c3b2182015-10-09 08:40:59 -0700575 // crash.
Mike Reedede7bac2017-07-23 15:30:02 -0400576 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(nullptr));
577 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(nullptr));
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 }
Mike Reedede7bac2017-07-23 15:30:02 -0400586 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
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);
Mike Reedf0ffb892017-10-03 14:47:21 -0400602 size_t totalBytes = scaledInfo.computeByteSize(rowBytes);
msarette16b04a2015-04-15 07:32:19 -0700603 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
Hal Canaryc465d132017-12-08 10:21:31 -0500616 test_dimensions(r, "images/CMYK.jpg");
617 test_dimensions(r, "images/color_wheel.jpg");
618 test_dimensions(r, "images/grayscale.jpg");
619 test_dimensions(r, "images/mandrill_512_q075.jpg");
620 test_dimensions(r, "images/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.
Hal Canaryc465d132017-12-08 10:21:31 -0500627 test_dimensions(r, "images/1x1.png");
628 test_dimensions(r, "images/2x2.png");
629 test_dimensions(r, "images/3x3.png");
630 test_dimensions(r, "images/3x1.png");
631 test_dimensions(r, "images/1x1.png");
632 test_dimensions(r, "images/16x1.png");
633 test_dimensions(r, "images/1x16.png");
634 test_dimensions(r, "images/mandrill_16.png");
msarettb32758a2015-08-18 13:22:46 -0700635
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))
Hal Canaryc465d132017-12-08 10:21:31 -0500639 test_dimensions(r, "images/sample_1mp.dng");
640 test_dimensions(r, "images/sample_1mp_rotated.dng");
641 test_dimensions(r, "images/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[]) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500646 auto data = GetResourceAsData(path);
647 if (!data) {
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500648 ERRORF(r, "Failed to get resource %s", path);
msarett4b17fa32015-04-23 08:53:39 -0700649 return;
650 }
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500651
652 REPORTER_ASSERT(r, !SkCodec::MakeFromData(data));
msarett4b17fa32015-04-23 08:53:39 -0700653}
msarette16b04a2015-04-15 07:32:19 -0700654
msarett4b17fa32015-04-23 08:53:39 -0700655DEF_TEST(Codec_Empty, r) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500656 if (GetResourcePath().isEmpty()) {
657 return;
658 }
659
msarett4b17fa32015-04-23 08:53:39 -0700660 // Test images that should not be able to create a codec
msarettd0375bc2015-08-12 08:08:56 -0700661 test_invalid(r, "empty_images/zero-dims.gif");
662 test_invalid(r, "empty_images/zero-embedded.ico");
663 test_invalid(r, "empty_images/zero-width.bmp");
664 test_invalid(r, "empty_images/zero-height.bmp");
665 test_invalid(r, "empty_images/zero-width.jpg");
666 test_invalid(r, "empty_images/zero-height.jpg");
667 test_invalid(r, "empty_images/zero-width.png");
668 test_invalid(r, "empty_images/zero-height.png");
669 test_invalid(r, "empty_images/zero-width.wbmp");
670 test_invalid(r, "empty_images/zero-height.wbmp");
671 // This image is an ico with an embedded mask-bmp. This is illegal.
672 test_invalid(r, "invalid_images/mask-bmp-ico.ico");
Matt Sarett5c496172017-02-07 17:01:16 -0500673 // It is illegal for a webp frame to not be fully contained by the canvas.
674 test_invalid(r, "invalid_images/invalid-offset.webp");
Leon Scroggins IIId87fbee2016-12-02 16:47:53 -0500675#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
676 test_invalid(r, "empty_images/zero_height.tiff");
677#endif
Leon Scroggins IIIfc4ee222017-07-14 11:48:52 -0400678 test_invalid(r, "invalid_images/b37623797.ico");
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500679 test_invalid(r, "invalid_images/osfuzz6295.webp");
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500680 test_invalid(r, "invalid_images/osfuzz6288.bmp");
Leon Scroggins III31476b72018-02-22 16:09:33 -0500681 test_invalid(r, "invalid_images/ossfuzz6347");
msarett4b17fa32015-04-23 08:53:39 -0700682}
msarett99f567e2015-08-05 12:58:26 -0700683
scroggo8e6c7ad2016-09-16 08:20:38 -0700684#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
685
686#ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions.
687 // It does not appear that anyone in Google3 is reading chunks.
688
scroggocf98fa92015-11-23 08:14:40 -0800689static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
690 SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
691 if (!sk_stream->write(data, len)) {
692 png_error(png_ptr, "sk_write_fn Error!");
693 }
694}
695
scroggocf98fa92015-11-23 08:14:40 -0800696DEF_TEST(Codec_pngChunkReader, r) {
697 // Create a dummy bitmap. Use unpremul RGBA for libpng.
698 SkBitmap bm;
699 const int w = 1;
700 const int h = 1;
701 const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
702 kUnpremul_SkAlphaType);
703 bm.setInfo(bmInfo);
704 bm.allocPixels();
705 bm.eraseColor(SK_ColorBLUE);
Hal Canary0f2f5222019-04-03 10:13:45 -0400706 SkMD5::Digest goodDigest = md5(bm);
scroggocf98fa92015-11-23 08:14:40 -0800707
708 // Write to a png file.
709 png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
710 REPORTER_ASSERT(r, png);
711 if (!png) {
712 return;
713 }
714
715 png_infop info = png_create_info_struct(png);
716 REPORTER_ASSERT(r, info);
717 if (!info) {
718 png_destroy_write_struct(&png, nullptr);
719 return;
720 }
721
722 if (setjmp(png_jmpbuf(png))) {
723 ERRORF(r, "failed writing png");
724 png_destroy_write_struct(&png, &info);
725 return;
726 }
727
728 SkDynamicMemoryWStream wStream;
729 png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
730
731 png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
732 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
733 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
734
735 // Create some chunks that match the Android framework's use.
736 static png_unknown_chunk gUnknowns[] = {
msarett133eaaa2016-01-07 11:03:25 -0800737 { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
738 { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
739 { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
scroggocf98fa92015-11-23 08:14:40 -0800740 };
741
742 png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
743 png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
744#if PNG_LIBPNG_VER < 10600
745 /* Deal with unknown chunk location bug in 1.5.x and earlier */
msarett133eaaa2016-01-07 11:03:25 -0800746 png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
747 png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
scroggocf98fa92015-11-23 08:14:40 -0800748#endif
749
750 png_write_info(png, info);
751
752 for (int j = 0; j < h; j++) {
753 png_bytep row = (png_bytep)(bm.getAddr(0, j));
754 png_write_rows(png, &row, 1);
755 }
756 png_write_end(png, info);
757 png_destroy_write_struct(&png, &info);
758
759 class ChunkReader : public SkPngChunkReader {
760 public:
761 ChunkReader(skiatest::Reporter* r)
762 : fReporter(r)
763 {
764 this->reset();
765 }
766
767 bool readChunk(const char tag[], const void* data, size_t length) override {
768 for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
769 if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
770 // Tag matches. This should have been the first time we see it.
771 REPORTER_ASSERT(fReporter, !fSeen[i]);
772 fSeen[i] = true;
773
774 // Data and length should match
775 REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
776 REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
777 (const char*) gUnknowns[i].data));
778 return true;
779 }
780 }
781 ERRORF(fReporter, "Saw an unexpected unknown chunk.");
782 return true;
783 }
784
785 bool allHaveBeenSeen() {
786 bool ret = true;
787 for (auto seen : fSeen) {
788 ret &= seen;
789 }
790 return ret;
791 }
792
793 void reset() {
794 sk_bzero(fSeen, sizeof(fSeen));
795 }
796
797 private:
798 skiatest::Reporter* fReporter; // Unowned
799 bool fSeen[3];
800 };
801
802 ChunkReader chunkReader(r);
803
804 // Now read the file with SkCodec.
Mike Reedede7bac2017-07-23 15:30:02 -0400805 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(wStream.detachAsData(), &chunkReader));
scroggocf98fa92015-11-23 08:14:40 -0800806 REPORTER_ASSERT(r, codec);
807 if (!codec) {
808 return;
809 }
810
811 // Now compare to the original.
812 SkBitmap decodedBm;
813 decodedBm.setInfo(codec->getInfo());
814 decodedBm.allocPixels();
815 SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
816 decodedBm.rowBytes());
817 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
818
819 if (decodedBm.colorType() != bm.colorType()) {
820 SkBitmap tmp;
Mike Kleinea3f0142019-03-20 11:12:10 -0500821 bool success = ToolUtils::copy_to(&tmp, bm.colorType(), decodedBm);
scroggocf98fa92015-11-23 08:14:40 -0800822 REPORTER_ASSERT(r, success);
823 if (!success) {
824 return;
825 }
826
827 tmp.swap(decodedBm);
828 }
829
830 compare_to_good_digest(r, goodDigest, decodedBm);
831 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
832
833 // Decoding again will read the chunks again.
834 chunkReader.reset();
835 REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
836 result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
837 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
838 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
839}
scroggo8e6c7ad2016-09-16 08:20:38 -0700840#endif // SK_PNG_DISABLE_TESTS
scroggocf98fa92015-11-23 08:14:40 -0800841#endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
scroggob9a1e342015-11-30 06:25:31 -0800842
scroggodb30be22015-12-08 18:54:13 -0800843// Stream that can only peek up to a limit
844class LimitedPeekingMemStream : public SkStream {
845public:
reed42943c82016-09-12 12:01:44 -0700846 LimitedPeekingMemStream(sk_sp<SkData> data, size_t limit)
847 : fStream(std::move(data))
scroggodb30be22015-12-08 18:54:13 -0800848 , fLimit(limit) {}
849
850 size_t peek(void* buf, size_t bytes) const override {
851 return fStream.peek(buf, SkTMin(bytes, fLimit));
852 }
853 size_t read(void* buf, size_t bytes) override {
854 return fStream.read(buf, bytes);
855 }
856 bool rewind() override {
857 return fStream.rewind();
858 }
859 bool isAtEnd() const override {
msarettff2a6c82016-09-07 11:23:28 -0700860 return fStream.isAtEnd();
scroggodb30be22015-12-08 18:54:13 -0800861 }
862private:
863 SkMemoryStream fStream;
864 const size_t fLimit;
865};
866
yujieqinf236ee42016-02-29 07:14:42 -0800867// Disable RAW tests for Win32.
868#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin9c7a8a42016-02-05 08:21:19 -0800869// Test that the RawCodec works also for not asset stream. This will test the code path using
870// SkRawBufferedStream instead of SkRawAssetStream.
yujieqin9c7a8a42016-02-05 08:21:19 -0800871DEF_TEST(Codec_raw_notseekable, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000872 constexpr char path[] = "images/dng_with_preview.dng";
873 sk_sp<SkData> data(GetResourceAsData(path));
yujieqin9c7a8a42016-02-05 08:21:19 -0800874 if (!data) {
875 SkDebugf("Missing resource '%s'\n", path);
876 return;
877 }
878
Mike Reedede7bac2017-07-23 15:30:02 -0400879 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
880 skstd::make_unique<NotAssetMemStream>(std::move(data))));
yujieqin9c7a8a42016-02-05 08:21:19 -0800881 REPORTER_ASSERT(r, codec);
882
883 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
884}
885#endif
886
scroggodb30be22015-12-08 18:54:13 -0800887// Test that even if webp_parse_header fails to peek enough, it will fall back to read()
888// + rewind() and succeed.
889DEF_TEST(Codec_webp_peek, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000890 constexpr char path[] = "images/baby_tux.webp";
891 auto data = GetResourceAsData(path);
scroggodb30be22015-12-08 18:54:13 -0800892 if (!data) {
893 SkDebugf("Missing resource '%s'\n", path);
894 return;
895 }
896
897 // The limit is less than webp needs to peek or read.
Mike Reedede7bac2017-07-23 15:30:02 -0400898 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
899 skstd::make_unique<LimitedPeekingMemStream>(data, 25)));
scroggodb30be22015-12-08 18:54:13 -0800900 REPORTER_ASSERT(r, codec);
901
scroggo7b5e5532016-02-04 06:14:24 -0800902 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800903
904 // Similarly, a stream which does not peek should still succeed.
Mike Reedede7bac2017-07-23 15:30:02 -0400905 codec = SkCodec::MakeFromStream(skstd::make_unique<LimitedPeekingMemStream>(data, 0));
scroggodb30be22015-12-08 18:54:13 -0800906 REPORTER_ASSERT(r, codec);
907
scroggo7b5e5532016-02-04 06:14:24 -0800908 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800909}
910
msarett7f7ec202016-03-01 12:12:27 -0800911// SkCodec's wbmp decoder was initially unnecessarily restrictive.
912// It required the second byte to be zero. The wbmp specification allows
913// a couple of bits to be 1 (so long as they do not overlap with 0x9F).
914// Test that SkCodec now supports an image with these bits set.
Leon Scroggins III83926342016-12-06 10:58:02 -0500915DEF_TEST(Codec_wbmp_restrictive, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500916 const char* path = "images/mandrill.wbmp";
Ben Wagner145dbcd2016-11-03 14:40:50 -0400917 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
scroggob9a1e342015-11-30 06:25:31 -0800918 if (!stream) {
scroggob9a1e342015-11-30 06:25:31 -0800919 return;
920 }
921
922 // Modify the stream to contain a second byte with some bits set.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400923 auto data = SkCopyStreamToData(stream.get());
scroggob9a1e342015-11-30 06:25:31 -0800924 uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
925 writeableData[1] = static_cast<uint8_t>(~0x9F);
926
msarett7f7ec202016-03-01 12:12:27 -0800927 // SkCodec should support this.
Mike Reedede7bac2017-07-23 15:30:02 -0400928 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
scroggob9a1e342015-11-30 06:25:31 -0800929 REPORTER_ASSERT(r, codec);
930 if (!codec) {
931 return;
932 }
scroggo7b5e5532016-02-04 06:14:24 -0800933 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggob9a1e342015-11-30 06:25:31 -0800934}
scroggodb30be22015-12-08 18:54:13 -0800935
936// wbmp images have a header that can be arbitrarily large, depending on the
937// size of the image. We cap the size at 65535, meaning we only need to look at
938// 8 bytes to determine whether we can read the image. This is important
Leon Scroggins III04be2b52017-08-17 15:13:20 -0400939// because SkCodec only passes a limited number of bytes to SkWbmpCodec to
940// determine whether the image is a wbmp.
scroggodb30be22015-12-08 18:54:13 -0800941DEF_TEST(Codec_wbmp_max_size, r) {
942 const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
943 0x83, 0xFF, 0x7F, // W: 65535
944 0x83, 0xFF, 0x7F }; // H: 65535
Ben Wagner145dbcd2016-11-03 14:40:50 -0400945 std::unique_ptr<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
Mike Reedede7bac2017-07-23 15:30:02 -0400946 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggodb30be22015-12-08 18:54:13 -0800947
948 REPORTER_ASSERT(r, codec);
949 if (!codec) return;
950
951 REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
952 REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
953
954 // Now test an image which is too big. Any image with a larger header (i.e.
955 // has bigger width/height) is also too big.
956 const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
957 0x84, 0x80, 0x00, // W: 65536
958 0x84, 0x80, 0x00 }; // H: 65536
959 stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false));
Mike Reedede7bac2017-07-23 15:30:02 -0400960 codec = SkCodec::MakeFromStream(std::move(stream));
scroggodb30be22015-12-08 18:54:13 -0800961
962 REPORTER_ASSERT(r, !codec);
963}
msarett2812f032016-07-18 15:56:08 -0700964
965DEF_TEST(Codec_jpeg_rewind, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500966 const char* path = "images/mandrill_512_q075.jpg";
Leon Scroggins III42886572017-01-27 13:16:28 -0500967 sk_sp<SkData> data(GetResourceAsData(path));
968 if (!data) {
msarett2812f032016-07-18 15:56:08 -0700969 return;
970 }
Leon Scroggins III42886572017-01-27 13:16:28 -0500971
972 data = SkData::MakeSubset(data.get(), 0, data->size() / 2);
Mike Reedede7bac2017-07-23 15:30:02 -0400973 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(data));
msarett2812f032016-07-18 15:56:08 -0700974 if (!codec) {
975 ERRORF(r, "Unable to create codec '%s'.", path);
976 return;
977 }
978
979 const int width = codec->getInfo().width();
980 const int height = codec->getInfo().height();
981 size_t rowBytes = sizeof(SkPMColor) * width;
982 SkAutoMalloc pixelStorage(height * rowBytes);
983
984 // Perform a sampled decode.
985 SkAndroidCodec::AndroidOptions opts;
986 opts.fSampleSize = 12;
Leon Scroggins III42886572017-01-27 13:16:28 -0500987 auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12);
988 auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts);
989 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -0700990
991 // Rewind the codec and perform a full image decode.
Matt Sarett74b16ed2017-01-25 11:58:11 -0500992 result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes);
Leon Scroggins III42886572017-01-27 13:16:28 -0500993 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
Matt Sarett74b16ed2017-01-25 11:58:11 -0500994
995 // Now perform a subset decode.
996 {
997 opts.fSampleSize = 1;
998 SkIRect subset = SkIRect::MakeWH(100, 100);
999 opts.fSubset = &subset;
1000 result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(),
1001 rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001002 // Though we only have half the data, it is enough to decode this subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001003 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1004 }
1005
1006 // Perform another full image decode. ASAN will detect if we look at the subset when it is
1007 // out of scope. This would happen if we depend on the old state in the codec.
Leon Scroggins III42886572017-01-27 13:16:28 -05001008 // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage
1009 // used to look at the old subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001010 opts.fSubset = nullptr;
1011 result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001012 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -07001013}
msarett549ca322016-08-17 08:54:08 -07001014
msarett35bb74b2016-08-22 07:41:28 -07001015static void check_color_xform(skiatest::Reporter* r, const char* path) {
Mike Reedede7bac2017-07-23 15:30:02 -04001016 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(GetResourceAsStream(path)));
msarett35bb74b2016-08-22 07:41:28 -07001017
1018 SkAndroidCodec::AndroidOptions opts;
1019 opts.fSampleSize = 3;
1020 const int subsetWidth = codec->getInfo().width() / 2;
1021 const int subsetHeight = codec->getInfo().height() / 2;
1022 SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight);
1023 opts.fSubset = &subset;
1024
1025 const int dstWidth = subsetWidth / opts.fSampleSize;
1026 const int dstHeight = subsetHeight / opts.fSampleSize;
Brian Osman82ebe042019-01-04 17:03:00 -05001027 auto colorSpace = SkColorSpace::MakeRGB(SkNamedTransferFn::k2Dot2, SkNamedGamut::kAdobeRGB);
msarett35bb74b2016-08-22 07:41:28 -07001028 SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight)
1029 .makeColorType(kN32_SkColorType)
1030 .makeColorSpace(colorSpace);
1031
1032 size_t rowBytes = dstInfo.minRowBytes();
Mike Reedf0ffb892017-10-03 14:47:21 -04001033 SkAutoMalloc pixelStorage(dstInfo.computeByteSize(rowBytes));
msarett35bb74b2016-08-22 07:41:28 -07001034 SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts);
1035 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1036}
1037
1038DEF_TEST(Codec_ColorXform, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001039 check_color_xform(r, "images/mandrill_512_q075.jpg");
1040 check_color_xform(r, "images/mandrill_512.png");
msarett35bb74b2016-08-22 07:41:28 -07001041}
1042
msarettf17b71f2016-09-12 14:30:03 -07001043static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) {
1044 switch (origColorType) {
1045 case kRGBA_8888_SkColorType:
1046 case kBGRA_8888_SkColorType:
1047 return kRGBA_8888_SkColorType == codecColorType ||
1048 kBGRA_8888_SkColorType == codecColorType;
1049 default:
1050 return origColorType == codecColorType;
1051 }
1052}
1053
1054static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) {
1055 switch (origAlphaType) {
1056 case kUnpremul_SkAlphaType:
1057 case kPremul_SkAlphaType:
1058 return kUnpremul_SkAlphaType == codecAlphaType ||
1059 kPremul_SkAlphaType == codecAlphaType;
1060 default:
1061 return origAlphaType == codecAlphaType;
1062 }
1063}
1064
1065static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) {
1066 SkBitmap bm1;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001067 bm1.allocPixels(info);
1068 SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes());
msarettf17b71f2016-09-12 14:30:03 -07001069 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarett9b09cd82016-08-29 14:47:49 -07001070
1071 // Encode the image to png.
Leon Scroggins III0098ccb2018-09-24 15:24:31 -04001072 auto data = SkEncodeBitmap(bm1, SkEncodedImageFormat::kPNG, 100);
msarett9b09cd82016-08-29 14:47:49 -07001073
Mike Reedede7bac2017-07-23 15:30:02 -04001074 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
msarettf17b71f2016-09-12 14:30:03 -07001075 REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType()));
1076 REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType()));
msarett9b09cd82016-08-29 14:47:49 -07001077
1078 SkBitmap bm2;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001079 bm2.allocPixels(info);
1080 result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes());
msarett9b09cd82016-08-29 14:47:49 -07001081 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1082
Hal Canary0f2f5222019-04-03 10:13:45 -04001083 REPORTER_ASSERT(r, md5(bm1) == md5(bm2));
msarett9b09cd82016-08-29 14:47:49 -07001084}
1085
1086DEF_TEST(Codec_PngRoundTrip, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001087 auto codec = SkCodec::MakeFromStream(GetResourceAsStream("images/mandrill_512_q075.jpg"));
msarett549ca322016-08-17 08:54:08 -07001088
msarettf17b71f2016-09-12 14:30:03 -07001089 SkColorType colorTypesOpaque[] = {
1090 kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1091 };
1092 for (SkColorType colorType : colorTypesOpaque) {
1093 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType);
1094 check_round_trip(r, codec.get(), newInfo);
1095 }
1096
Hal Canaryc465d132017-12-08 10:21:31 -05001097 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/grayscale.jpg"));
msarettf17b71f2016-09-12 14:30:03 -07001098 check_round_trip(r, codec.get(), codec->getInfo());
1099
Hal Canaryc465d132017-12-08 10:21:31 -05001100 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/yellow_rose.png"));
msarettf17b71f2016-09-12 14:30:03 -07001101
1102 SkColorType colorTypesWithAlpha[] = {
1103 kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1104 };
1105 SkAlphaType alphaTypes[] = {
1106 kUnpremul_SkAlphaType, kPremul_SkAlphaType
1107 };
1108 for (SkColorType colorType : colorTypesWithAlpha) {
1109 for (SkAlphaType alphaType : alphaTypes) {
1110 // Set color space to nullptr because color correct premultiplies do not round trip.
1111 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType)
1112 .makeAlphaType(alphaType)
1113 .makeColorSpace(nullptr);
1114 check_round_trip(r, codec.get(), newInfo);
1115 }
1116 }
1117
Hal Canaryc465d132017-12-08 10:21:31 -05001118 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/index8.png"));
msarettf17b71f2016-09-12 14:30:03 -07001119
1120 for (SkAlphaType alphaType : alphaTypes) {
1121 SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType)
1122 .makeColorSpace(nullptr);
1123 check_round_trip(r, codec.get(), newInfo);
1124 }
msarett549ca322016-08-17 08:54:08 -07001125}
msarett2ecc35f2016-09-08 11:55:16 -07001126
1127static void test_conversion_possible(skiatest::Reporter* r, const char* path,
scroggo8e6c7ad2016-09-16 08:20:38 -07001128 bool supportsScanlineDecoder,
1129 bool supportsIncrementalDecoder) {
Ben Wagner145dbcd2016-11-03 14:40:50 -04001130 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001131 if (!stream) {
1132 return;
1133 }
1134
Mike Reedede7bac2017-07-23 15:30:02 -04001135 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001136 if (!codec) {
1137 ERRORF(r, "failed to create a codec for %s", path);
1138 return;
1139 }
1140
msarett2ecc35f2016-09-08 11:55:16 -07001141 SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType);
1142
1143 SkBitmap bm;
1144 bm.allocPixels(infoF16);
1145 SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
Mike Kleince4cf722018-05-10 11:29:15 -04001146 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001147
1148 result = codec->startScanlineDecode(infoF16);
1149 if (supportsScanlineDecoder) {
Mike Kleince4cf722018-05-10 11:29:15 -04001150 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001151 } else {
Leon Scroggins III07418182017-08-15 12:24:02 -04001152 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
Mike Kleince4cf722018-05-10 11:29:15 -04001153 || SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001154 }
1155
1156 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1157 if (supportsIncrementalDecoder) {
Mike Kleince4cf722018-05-10 11:29:15 -04001158 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001159 } else {
Leon Scroggins III07418182017-08-15 12:24:02 -04001160 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
Mike Kleince4cf722018-05-10 11:29:15 -04001161 || SkCodec::kSuccess == result);
msarett2ecc35f2016-09-08 11:55:16 -07001162 }
1163
Brian Osman36703d92017-12-12 14:09:31 -05001164 infoF16 = infoF16.makeColorSpace(infoF16.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001165 result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
1166 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001167 result = codec->startScanlineDecode(infoF16);
1168 if (supportsScanlineDecoder) {
msarett2ecc35f2016-09-08 11:55:16 -07001169 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001170 } else {
1171 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
1172 }
1173
1174 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1175 if (supportsIncrementalDecoder) {
1176 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1177 } else {
1178 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
msarett2ecc35f2016-09-08 11:55:16 -07001179 }
1180}
1181
1182DEF_TEST(Codec_F16ConversionPossible, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001183 test_conversion_possible(r, "images/color_wheel.webp", false, false);
1184 test_conversion_possible(r, "images/mandrill_512_q075.jpg", true, false);
1185 test_conversion_possible(r, "images/yellow_rose.png", false, true);
scroggo8e6c7ad2016-09-16 08:20:38 -07001186}
1187
scroggo19b91532016-10-24 09:03:26 -07001188static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) {
1189 SkBitmap bm;
1190 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1191 bm.allocPixels(info);
1192
1193 SkCodec::Options opts;
1194 opts.fFrameIndex = frame;
1195 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info,
Leon Scroggins571b30f2017-07-11 17:35:31 +00001196 bm.getPixels(), bm.rowBytes(), &opts));
scroggo19b91532016-10-24 09:03:26 -07001197}
1198
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001199// For an animated GIF, we should only read enough to decode frame 0 if the
1200// client never calls getFrameInfo and only decodes frame 0.
scroggo19b91532016-10-24 09:03:26 -07001201DEF_TEST(Codec_skipFullParse, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001202 auto path = "images/test640x479.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001203 auto streamObj = GetResourceAsStream(path);
1204 if (!streamObj) {
scroggo19b91532016-10-24 09:03:26 -07001205 return;
1206 }
Mike Reed71f867c2017-07-23 13:14:10 -04001207 SkStream* stream = streamObj.get();
scroggo19b91532016-10-24 09:03:26 -07001208
1209 // Note that we cheat and hold on to the stream pointer, but SkCodec will
1210 // take ownership. We will not refer to the stream after the SkCodec
1211 // deletes it.
Mike Reedede7bac2017-07-23 15:30:02 -04001212 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(streamObj)));
scroggo19b91532016-10-24 09:03:26 -07001213 if (!codec) {
1214 ERRORF(r, "Failed to create codec for %s", path);
1215 return;
1216 }
1217
1218 REPORTER_ASSERT(r, stream->hasPosition());
1219 const size_t sizePosition = stream->getPosition();
1220 REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength());
1221
1222 // This should read more of the stream, but not the whole stream.
1223 decode_frame(r, codec.get(), 0);
1224 const size_t positionAfterFirstFrame = stream->getPosition();
1225 REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition
1226 && positionAfterFirstFrame < stream->getLength());
1227
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001228 // There is more data in the stream.
scroggo19b91532016-10-24 09:03:26 -07001229 auto frameInfo = codec->getFrameInfo();
1230 REPORTER_ASSERT(r, frameInfo.size() == 4);
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001231 REPORTER_ASSERT(r, stream->getPosition() > positionAfterFirstFrame);
scroggo19b91532016-10-24 09:03:26 -07001232}
1233
scroggo8e6c7ad2016-09-16 08:20:38 -07001234// Only rewinds up to a limit.
1235class LimitedRewindingStream : public SkStream {
1236public:
Mike Reed71f867c2017-07-23 13:14:10 -04001237 static std::unique_ptr<SkStream> Make(const char path[], size_t limit) {
1238 auto stream = GetResourceAsStream(path);
scroggo8e6c7ad2016-09-16 08:20:38 -07001239 if (!stream) {
1240 return nullptr;
1241 }
Mike Reed71f867c2017-07-23 13:14:10 -04001242 return std::unique_ptr<SkStream>(new LimitedRewindingStream(std::move(stream), limit));
scroggo8e6c7ad2016-09-16 08:20:38 -07001243 }
1244
1245 size_t read(void* buffer, size_t size) override {
1246 const size_t bytes = fStream->read(buffer, size);
1247 fPosition += bytes;
1248 return bytes;
1249 }
1250
1251 bool isAtEnd() const override {
1252 return fStream->isAtEnd();
1253 }
1254
1255 bool rewind() override {
1256 if (fPosition <= fLimit && fStream->rewind()) {
1257 fPosition = 0;
1258 return true;
1259 }
1260
1261 return false;
1262 }
1263
1264private:
Ben Wagner145dbcd2016-11-03 14:40:50 -04001265 std::unique_ptr<SkStream> fStream;
1266 const size_t fLimit;
1267 size_t fPosition;
scroggo8e6c7ad2016-09-16 08:20:38 -07001268
Mike Reed71f867c2017-07-23 13:14:10 -04001269 LimitedRewindingStream(std::unique_ptr<SkStream> stream, size_t limit)
1270 : fStream(std::move(stream))
scroggo8e6c7ad2016-09-16 08:20:38 -07001271 , fLimit(limit)
1272 , fPosition(0)
1273 {
1274 SkASSERT(fStream);
1275 }
1276};
1277
1278DEF_TEST(Codec_fallBack, r) {
1279 // SkAndroidCodec needs to be able to fall back to scanline decoding
1280 // if incremental decoding does not work. Make sure this does not
1281 // require a rewind.
1282
1283 // Formats that currently do not support incremental decoding
1284 auto files = {
Hal Canaryc465d132017-12-08 10:21:31 -05001285 "images/CMYK.jpg",
1286 "images/color_wheel.ico",
1287 "images/mandrill.wbmp",
1288 "images/randPixels.bmp",
scroggo8e6c7ad2016-09-16 08:20:38 -07001289 };
1290 for (auto file : files) {
Leon Scroggins III04be2b52017-08-17 15:13:20 -04001291 auto stream = LimitedRewindingStream::Make(file, SkCodec::MinBufferedBytesNeeded());
scroggo8e6c7ad2016-09-16 08:20:38 -07001292 if (!stream) {
1293 SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
1294 return;
1295 }
1296
Mike Reedede7bac2017-07-23 15:30:02 -04001297 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggo8e6c7ad2016-09-16 08:20:38 -07001298 if (!codec) {
1299 ERRORF(r, "Failed to create codec for %s,", file);
1300 continue;
1301 }
1302
1303 SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
1304 SkBitmap bm;
1305 bm.allocPixels(info);
1306
1307 if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
1308 bm.rowBytes())) {
1309 ERRORF(r, "Is scanline decoding now implemented for %s?", file);
1310 continue;
1311 }
1312
1313 // Scanline decoding should not require a rewind.
1314 SkCodec::Result result = codec->startScanlineDecode(info);
1315 if (SkCodec::kSuccess != result) {
1316 ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
1317 }
1318 }
msarett2ecc35f2016-09-08 11:55:16 -07001319}
scroggoc46cdd42016-10-10 06:45:32 -07001320
1321// This test verifies that we fixed an assert statement that fired when reusing a png codec
1322// after scaling.
1323DEF_TEST(Codec_reusePng, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001324 std::unique_ptr<SkStream> stream(GetResourceAsStream("images/plane.png"));
scroggoc46cdd42016-10-10 06:45:32 -07001325 if (!stream) {
1326 return;
1327 }
1328
Mike Reedede7bac2017-07-23 15:30:02 -04001329 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
scroggoc46cdd42016-10-10 06:45:32 -07001330 if (!codec) {
1331 ERRORF(r, "Failed to create codec\n");
1332 return;
1333 }
1334
1335 SkAndroidCodec::AndroidOptions opts;
1336 opts.fSampleSize = 5;
1337 auto size = codec->getSampledDimensions(opts.fSampleSize);
1338 auto info = codec->getInfo().makeWH(size.fWidth, size.fHeight).makeColorType(kN32_SkColorType);
1339 SkBitmap bm;
1340 bm.allocPixels(info);
1341 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1342 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1343
1344 info = codec->getInfo().makeColorType(kN32_SkColorType);
1345 bm.allocPixels(info);
1346 opts.fSampleSize = 1;
1347 result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1348 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1349}
scroggoe61b3b42016-10-10 07:17:32 -07001350
1351DEF_TEST(Codec_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001352 auto file = "images/plane_interlaced.png";
scroggoe61b3b42016-10-10 07:17:32 -07001353 std::unique_ptr<SkStream> stream(GetResourceAsStream(file));
1354 if (!stream) {
1355 return;
1356 }
1357
1358 // This is enough to read the header etc, but no rows.
Mike Reedede7bac2017-07-23 15:30:02 -04001359 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 99)));
scroggoe61b3b42016-10-10 07:17:32 -07001360 if (!codec) {
1361 ERRORF(r, "Failed to create codec\n");
1362 return;
1363 }
1364
1365 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1366 SkBitmap bm;
1367 bm.allocPixels(info);
1368 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
1369 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1370
1371 // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded
1372 // should get set to zero by incrementalDecode.
1373 int rowsDecoded = 77;
1374 result = codec->incrementalDecode(&rowsDecoded);
1375 REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput);
1376 REPORTER_ASSERT(r, rowsDecoded == 0);
1377}
Matt Sarett29121eb2016-10-17 14:32:46 -04001378
Matt Sarettd59948a2017-04-26 10:59:48 -04001379static void test_invalid_images(skiatest::Reporter* r, const char* path,
1380 SkCodec::Result expectedResult) {
Mike Reed71f867c2017-07-23 13:14:10 -04001381 auto stream = GetResourceAsStream(path);
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001382 if (!stream) {
1383 return;
1384 }
1385
Mike Reedede7bac2017-07-23 15:30:02 -04001386 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001387 REPORTER_ASSERT(r, codec);
1388
Matt Sarettd59948a2017-04-26 10:59:48 -04001389 test_info(r, codec.get(), codec->getInfo().makeColorType(kN32_SkColorType), expectedResult,
1390 nullptr);
1391}
1392
1393DEF_TEST(Codec_InvalidImages, r) {
1394 // ASAN will complain if there is an issue.
Leon Scroggins III674a1842017-07-06 12:26:09 -04001395 test_invalid_images(r, "invalid_images/skbug5887.gif", SkCodec::kErrorInInput);
Matt Sarettd59948a2017-04-26 10:59:48 -04001396 test_invalid_images(r, "invalid_images/many-progressive-scans.jpg", SkCodec::kInvalidInput);
1397 test_invalid_images(r, "invalid_images/b33251605.bmp", SkCodec::kIncompleteInput);
1398 test_invalid_images(r, "invalid_images/bad_palette.png", SkCodec::kInvalidInput);
1399}
1400
1401static void test_invalid_header(skiatest::Reporter* r, const char* path) {
Mike Reed0933bc92017-12-09 01:27:41 +00001402 auto data = GetResourceAsData(path);
1403 if (!data) {
1404 return;
1405 }
1406 std::unique_ptr<SkStreamAsset> stream(new SkMemoryStream(std::move(data)));
Mike Reed847068c2017-07-26 11:35:53 -04001407 if (!stream) {
Matt Sarettd59948a2017-04-26 10:59:48 -04001408 return;
1409 }
Mike Reedede7bac2017-07-23 15:30:02 -04001410 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Matt Sarettd59948a2017-04-26 10:59:48 -04001411 REPORTER_ASSERT(r, !codec);
1412}
1413
1414DEF_TEST(Codec_InvalidHeader, r) {
1415 test_invalid_header(r, "invalid_images/int_overflow.ico");
1416
1417 // These files report values that have caused problems with SkFILEStreams.
1418 // They are invalid, and should not create SkCodecs.
1419 test_invalid_header(r, "invalid_images/b33651913.bmp");
1420 test_invalid_header(r, "invalid_images/b34778578.bmp");
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001421}
1422
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001423/*
1424For the Codec_InvalidAnimated test, immediately below,
1425resources/invalid_images/skbug6046.gif is:
1426
142700000000: 4749 4638 3961 2000 0000 0000 002c ff00 GIF89a ......,..
142800000010: 7400 0600 0000 4001 0021 f904 0a00 0000 t.....@..!......
142900000020: 002c ff00 0000 ff00 7400 0606 0606 0601 .,......t.......
143000000030: 0021 f904 0000 0000 002c ff00 0000 ffcc .!.......,......
143100000040: 1b36 5266 deba 543d .6Rf..T=
1432
Leon Scroggins980d03b2019-07-11 20:47:16 +00001433It nominally contains 3 frames, but only the first one is valid. It came from a
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001434fuzzer doing random mutations and copies. The breakdown:
1435
1436@000 6 bytes magic "GIF89a"
1437@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1438 - width = 32
1439 - height = 0
1440 - flags = 0x00
1441 - background color index, pixel aspect ratio bytes ignored
1442@00D 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x40
1443 - origin_x = 255
1444 - origin_y = 116
1445 - width = 6
1446 - height = 0
1447 - flags = 0x40, interlaced
1448@017 2 bytes Image Descriptor body (pixel data): 0x01 0x00
Leon Scroggins980d03b2019-07-11 20:47:16 +00001449 - lit_width = 1
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001450 - 0x00 byte means "end of data" for this frame
1451@019 8 bytes Graphic Control Extension: 0x21 0xF9 ... 0x00
1452 - valid, but irrelevant here.
1453@021 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1454 - origin_x = 255
1455 - origin_y = 0
1456 - width = 255
1457 - height = 116
1458 - flags = 0x06, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1459@02B 14 bytes Image Descriptor body (pixel data): 0x06 0x06 ... 0x00
1460 - lit_width = 6
1461 - 0x06 precedes a 6 byte block of data
1462 - 0x04 precedes a 4 byte block of data
1463 - 0x00 byte means "end of data" for this frame
1464@039 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1465 - origin_x = 255
1466 - origin_y = 0
1467 - width = 52479
1468 - height = 13851
1469 - flags = 0x52, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1470@043 5 bytes Image Descriptor body (pixel data): 0x66 0xDE ... unexpected-EOF
Leon Scroggins980d03b2019-07-11 20:47:16 +00001471 - lit_width = 102, INVALID, GREATER THAN 8
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001472 - 0xDE precedes a 222 byte block of data, INVALIDLY TRUNCATED
1473
1474On Image Descriptor flags INVALIDITY,
1475https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 20.c says that "Size of
1476Local Color Table [the low 3 bits]... should be 0 if there is no Local Color
1477Table specified [the high bit]."
1478
Leon Scroggins980d03b2019-07-11 20:47:16 +00001479On LZW literal width (also known as Minimum Code Size) INVALIDITY,
1480https://www.w3.org/Graphics/GIF/spec-gif89a.txt Appendix F says that "Normally
1481this will be the same as the number of [palette index] bits. Because of some
1482algorithmic constraints however, black & white images which have one color bit
1483must be indicated as having a code size of 2." In practice, some GIF decoders,
1484including both the old third_party/gif code and the Wuffs GIF decoder, don't
1485enforce this "at least 2" constraint. Nonetheless, any width greater than 8 is
1486invalid, as there are only 8 bits in a byte.
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001487*/
1488
Leon Scroggins III56e32092016-12-12 17:10:46 -05001489DEF_TEST(Codec_InvalidAnimated, r) {
1490 // ASAN will complain if there is an issue.
1491 auto path = "invalid_images/skbug6046.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001492 auto stream = GetResourceAsStream(path);
Leon Scroggins III56e32092016-12-12 17:10:46 -05001493 if (!stream) {
1494 return;
1495 }
1496
Mike Reedede7bac2017-07-23 15:30:02 -04001497 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins III56e32092016-12-12 17:10:46 -05001498 REPORTER_ASSERT(r, codec);
1499 if (!codec) {
1500 return;
1501 }
1502
1503 const auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1504 SkBitmap bm;
1505 bm.allocPixels(info);
1506
1507 auto frameInfos = codec->getFrameInfo();
1508 SkCodec::Options opts;
Leon Scroggins III249b8e32017-04-17 12:46:33 -04001509 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
Leon Scroggins III56e32092016-12-12 17:10:46 -05001510 opts.fFrameIndex = i;
Leon Scroggins III33deb7e2017-06-07 12:31:51 -04001511 const auto reqFrame = frameInfos[i].fRequiredFrame;
Nigel Tao66bc5242018-08-22 10:56:03 +10001512 opts.fPriorFrame = reqFrame == i - 1 ? reqFrame : SkCodec::kNoFrame;
Leon Scroggins III56e32092016-12-12 17:10:46 -05001513 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001514
Leon Scroggins III56e32092016-12-12 17:10:46 -05001515 if (result != SkCodec::kSuccess) {
1516 ERRORF(r, "Failed to start decoding frame %i (out of %i) with error %i\n", i,
1517 frameInfos.size(), result);
1518 continue;
1519 }
1520
1521 codec->incrementalDecode();
1522 }
1523}
Matt Sarett0e032be2017-03-15 17:50:08 -04001524
Matt Sarett5df93de2017-03-22 21:52:47 +00001525static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap,
Matt Sarettc367d032017-05-05 11:13:26 -04001526 SkEncodedImageFormat format) {
Matt Sarett5df93de2017-03-22 21:52:47 +00001527 switch (format) {
1528 case SkEncodedImageFormat::kPNG:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001529 SkPngEncoder::Encode(stream, pixmap, SkPngEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001530 break;
1531 case SkEncodedImageFormat::kJPEG:
Matt Sarett26b44df2017-05-02 16:04:56 -04001532 SkJpegEncoder::Encode(stream, pixmap, SkJpegEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001533 break;
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001534 case SkEncodedImageFormat::kWEBP:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001535 SkWebpEncoder::Encode(stream, pixmap, SkWebpEncoder::Options());
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001536 break;
Matt Sarett5df93de2017-03-22 21:52:47 +00001537 default:
1538 SkASSERT(false);
1539 break;
1540 }
1541}
1542
Brian Osmanb62f50c2018-07-12 14:44:27 -04001543static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format) {
Matt Sarett0e032be2017-03-15 17:50:08 -04001544 // Test with sRGB color space.
1545 SkBitmap srgbBitmap;
1546 SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType);
1547 srgbBitmap.allocPixels(srgbInfo);
1548 *srgbBitmap.getAddr32(0, 0) = 0;
1549 SkPixmap pixmap;
1550 srgbBitmap.peekPixels(&pixmap);
1551 SkDynamicMemoryWStream srgbBuf;
Brian Osmanb62f50c2018-07-12 14:44:27 -04001552 encode_format(&srgbBuf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001553 sk_sp<SkData> srgbData = srgbBuf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001554 std::unique_ptr<SkCodec> srgbCodec(SkCodec::MakeFromData(srgbData));
Mike Kleine28a6b52018-07-25 13:05:17 -04001555 REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == sk_srgb_singleton());
Matt Sarett0e032be2017-03-15 17:50:08 -04001556
1557 // Test with P3 color space.
1558 SkDynamicMemoryWStream p3Buf;
Brian Osman82ebe042019-01-04 17:03:00 -05001559 sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDCIP3);
Matt Sarett0e032be2017-03-15 17:50:08 -04001560 pixmap.setColorSpace(p3);
Brian Osmanb62f50c2018-07-12 14:44:27 -04001561 encode_format(&p3Buf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001562 sk_sp<SkData> p3Data = p3Buf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001563 std::unique_ptr<SkCodec> p3Codec(SkCodec::MakeFromData(p3Data));
Matt Sarett0e032be2017-03-15 17:50:08 -04001564 REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB());
Brian Osman82ebe042019-01-04 17:03:00 -05001565 skcms_Matrix3x3 mat0, mat1;
Matt Sarett0e032be2017-03-15 17:50:08 -04001566 bool success = p3->toXYZD50(&mat0);
1567 REPORTER_ASSERT(r, success);
1568 success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1);
1569 REPORTER_ASSERT(r, success);
1570
Brian Osman82ebe042019-01-04 17:03:00 -05001571 for (int i = 0; i < 3; i++) {
1572 for (int j = 0; j < 3; j++) {
1573 REPORTER_ASSERT(r, color_space_almost_equal(mat0.vals[i][j], mat1.vals[i][j]));
Matt Sarett0e032be2017-03-15 17:50:08 -04001574 }
1575 }
1576}
Matt Sarett5df93de2017-03-22 21:52:47 +00001577
1578DEF_TEST(Codec_EncodeICC, r) {
Brian Osmanb62f50c2018-07-12 14:44:27 -04001579 test_encode_icc(r, SkEncodedImageFormat::kPNG);
1580 test_encode_icc(r, SkEncodedImageFormat::kJPEG);
1581 test_encode_icc(r, SkEncodedImageFormat::kWEBP);
Matt Sarett5df93de2017-03-22 21:52:47 +00001582}
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001583
1584DEF_TEST(Codec_webp_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001585 const char* path = "images/baby_tux.webp";
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001586 sk_sp<SkData> data(GetResourceAsData(path));
1587 if (!data) {
1588 return;
1589 }
1590
1591 // Truncate this file so that the header is available but no rows can be
1592 // decoded. This should create a codec but fail to decode.
1593 size_t truncatedSize = 5000;
1594 sk_sp<SkData> subset = SkData::MakeSubset(data.get(), 0, truncatedSize);
1595 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(subset));
1596 if (!codec) {
1597 ERRORF(r, "Failed to create a codec for %s truncated to only %lu bytes",
1598 path, truncatedSize);
1599 return;
1600 }
1601
1602 test_info(r, codec.get(), codec->getInfo(), SkCodec::kInvalidInput, nullptr);
1603}
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001604
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001605/*
1606For the Codec_ossfuzz6274 test, immediately below,
1607resources/invalid_images/ossfuzz6274.gif is:
1608
160900000000: 4749 4638 3961 2000 2000 f120 2020 2020 GIF89a . ..
161000000010: 2020 2020 2020 2020 2021 f903 ff20 2020 !...
161100000020: 002c 0000 0000 2000 2000 2000 00 .,.... . . ..
1612
1613@000 6 bytes magic "GIF89a"
1614@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1615 - width = 32
1616 - height = 32
1617 - flags = 0xF1, global color table, 4 RGB entries
1618 - background color index, pixel aspect ratio bytes ignored
1619@00D 12 bytes Color Table: 0x20 0x20 ... 0x20
1620@019 20 bytes Graphic Control Extension: 0x21 0xF9 ... unexpected-EOF
1621 - 0x03 precedes a 3 byte block of data, INVALID, MUST BE 4
1622 - 0x20 precedes a 32 byte block of data, INVALIDly truncated
1623
1624https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 23.c says that the
1625block size (for an 0x21 0xF9 Graphic Control Extension) must be "the fixed
1626value 4".
1627*/
1628
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001629DEF_TEST(Codec_ossfuzz6274, r) {
1630 if (GetResourcePath().isEmpty()) {
1631 return;
1632 }
1633
1634 const char* file = "invalid_images/ossfuzz6274.gif";
1635 auto image = GetResourceAsImage(file);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001636
1637#ifdef SK_HAS_WUFFS_LIBRARY
1638 // We are transitioning from an old GIF implementation to a new (Wuffs) GIF
1639 // implementation.
1640 //
1641 // This test (without SK_HAS_WUFFS_LIBRARY) is overly specific to the old
1642 // implementation. In the new implementation, the MakeFromStream factory
1643 // method returns a nullptr SkImage*, instead of returning a non-null but
1644 // otherwise all-transparent SkImage*.
1645 //
1646 // Either way, the end-to-end result is the same - the source input is
1647 // rejected as an invalid GIF image - but the two implementations differ in
1648 // how that's represented.
1649 //
1650 // Once the transition is complete, we can remove the #ifdef and delete the
1651 // rest of the test function.
1652 //
1653 // See Codec_GifTruncated3 for the equivalent of the rest of the test
1654 // function, on different (but still truncated) source data.
1655 if (image) {
1656 ERRORF(r, "Invalid data gave non-nullptr image");
1657 }
1658 return;
1659#endif
1660
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001661 if (!image) {
1662 ERRORF(r, "Missing %s", file);
1663 return;
1664 }
1665
1666 REPORTER_ASSERT(r, image->width() == 32);
1667 REPORTER_ASSERT(r, image->height() == 32);
1668
1669 SkBitmap bm;
1670 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(32, 32))) {
1671 ERRORF(r, "Failed to allocate pixels");
1672 return;
1673 }
1674
1675 bm.eraseColor(SK_ColorTRANSPARENT);
1676
1677 SkCanvas canvas(bm);
1678 canvas.drawImage(image, 0, 0, nullptr);
1679
1680 for (int i = 0; i < image->width(); ++i)
1681 for (int j = 0; j < image->height(); ++j) {
1682 SkColor actual = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(i, j));
1683 if (actual != SK_ColorTRANSPARENT) {
1684 ERRORF(r, "did not initialize pixels! %i, %i is %x", i, j, actual);
1685 }
1686 }
1687}
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001688
Leon Scroggins III665949a2018-06-26 10:49:42 -04001689DEF_TEST(Codec_78329453, r) {
1690 if (GetResourcePath().isEmpty()) {
1691 return;
1692 }
1693
1694 const char* file = "images/b78329453.jpeg";
1695 auto data = GetResourceAsData(file);
1696 if (!data) {
1697 ERRORF(r, "Missing %s", file);
1698 return;
1699 }
1700
1701 auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(data));
1702 if (!codec) {
1703 ERRORF(r, "failed to create codec from %s", file);
1704 return;
1705 }
1706
1707 // A bug in jpeg_skip_scanlines resulted in an infinite loop for this specific
1708 // sample size on this image. Other sample sizes could have had the same result,
1709 // but the ones tested by DM happen to not.
1710 constexpr int kSampleSize = 19;
1711 const auto size = codec->getSampledDimensions(kSampleSize);
1712 auto info = codec->getInfo().makeWH(size.width(), size.height());
1713 SkBitmap bm;
1714 bm.allocPixels(info);
1715 bm.eraseColor(SK_ColorTRANSPARENT);
1716
1717 SkAndroidCodec::AndroidOptions options;
1718 options.fSampleSize = kSampleSize;
1719 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &options);
1720 if (result != SkCodec::kSuccess) {
1721 ERRORF(r, "failed to decode with error %s", SkCodec::ResultToString(result));
1722 }
1723}
1724
Leon Scroggins III36f7e322018-08-27 11:55:46 -04001725DEF_TEST(Codec_A8, r) {
1726 if (GetResourcePath().isEmpty()) {
1727 return;
1728 }
1729
1730 const char* file = "images/mandrill_cmyk.jpg";
1731 auto data = GetResourceAsData(file);
1732 if (!data) {
1733 ERRORF(r, "missing %s", file);
1734 return;
1735 }
1736
1737 auto codec = SkCodec::MakeFromData(std::move(data));
1738 auto info = codec->getInfo().makeColorType(kAlpha_8_SkColorType);
1739 SkBitmap bm;
1740 bm.allocPixels(info);
1741 REPORTER_ASSERT(r, codec->getPixels(bm.pixmap()) == SkCodec::kInvalidConversion);
1742}
1743
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001744DEF_TEST(Codec_crbug807324, r) {
1745 if (GetResourcePath().isEmpty()) {
1746 return;
1747 }
1748
1749 const char* file = "images/crbug807324.png";
1750 auto image = GetResourceAsImage(file);
1751 if (!image) {
1752 ERRORF(r, "Missing %s", file);
1753 return;
1754 }
1755
1756 const int kWidth = image->width();
1757 const int kHeight = image->height();
1758
1759 SkBitmap bm;
1760 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(kWidth, kHeight))) {
1761 ERRORF(r, "Could not allocate pixels (%i x %i)", kWidth, kHeight);
1762 return;
1763 }
1764
1765 bm.eraseColor(SK_ColorTRANSPARENT);
1766
1767 SkCanvas canvas(bm);
1768 canvas.drawImage(image, 0, 0, nullptr);
1769
1770 for (int i = 0; i < kWidth; ++i)
1771 for (int j = 0; j < kHeight; ++j) {
1772 if (*bm.getAddr32(i, j) == SK_ColorTRANSPARENT) {
1773 ERRORF(r, "image should not be transparent! %i, %i is 0", i, j);
1774 return;
1775 }
1776 }
1777}