blob: 08f19f30b40cdd2d20c854ccd2c3a2b7e0cd18a3 [file] [log] [blame]
halcanarya096d7a2015-03-27 12:16:53 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Leon Scroggins III63cfb362020-04-24 13:00:48 -04008// Make sure SkUserConfig.h is included so #defines are available on
9// Android.
10#include "include/core/SkTypes.h"
11#ifdef SK_ENABLE_ANDROID_UTILS
12#include "client_utils/android/FrontBufferedStream.h"
13#endif
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "include/codec/SkAndroidCodec.h"
15#include "include/codec/SkCodec.h"
16#include "include/core/SkBitmap.h"
17#include "include/core/SkCanvas.h"
18#include "include/core/SkColor.h"
19#include "include/core/SkColorSpace.h"
20#include "include/core/SkData.h"
21#include "include/core/SkEncodedImageFormat.h"
22#include "include/core/SkImage.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040023#include "include/core/SkImageEncoder.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "include/core/SkImageGenerator.h"
25#include "include/core/SkImageInfo.h"
26#include "include/core/SkPixmap.h"
27#include "include/core/SkPngChunkReader.h"
28#include "include/core/SkRect.h"
29#include "include/core/SkRefCnt.h"
30#include "include/core/SkSize.h"
31#include "include/core/SkStream.h"
32#include "include/core/SkString.h"
33#include "include/core/SkTypes.h"
34#include "include/core/SkUnPreMultiply.h"
35#include "include/encode/SkJpegEncoder.h"
36#include "include/encode/SkPngEncoder.h"
37#include "include/encode/SkWebpEncoder.h"
38#include "include/private/SkMalloc.h"
39#include "include/private/SkTemplates.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040040#include "include/third_party/skcms/skcms.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050041#include "include/utils/SkRandom.h"
42#include "src/codec/SkCodecImageGenerator.h"
43#include "src/core/SkAutoMalloc.h"
44#include "src/core/SkColorSpacePriv.h"
45#include "src/core/SkMD5.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050046#include "src/core/SkStreamPriv.h"
47#include "tests/FakeStreams.h"
48#include "tests/Test.h"
49#include "tools/Resources.h"
50#include "tools/ToolUtils.h"
Ben Wagner9707a7e2019-05-06 17:17:19 -040051
Ben Wagner501c17c2018-03-12 20:04:31 +000052#include "png.h"
Ben Wagner1a462bd2018-03-12 13:46:21 -040053
Ben Wagnerb607a8f2018-03-12 13:46:21 -040054#include <setjmp.h>
55#include <cstring>
Ben Wagner9707a7e2019-05-06 17:17:19 -040056#include <initializer_list>
Ben Wagnerb607a8f2018-03-12 13:46:21 -040057#include <memory>
58#include <utility>
59#include <vector>
60
scroggo8e6c7ad2016-09-16 08:20:38 -070061#if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
62 // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In
63 // the meantime, we had to break some pieces of SkPngCodec in order to support Google3.
64 // The parts that are broken are likely not used by Google3.
65 #define SK_PNG_DISABLE_TESTS
66#endif
67
Hal Canary0f2f5222019-04-03 10:13:45 -040068static SkMD5::Digest md5(const SkBitmap& bm) {
halcanarya096d7a2015-03-27 12:16:53 -070069 SkASSERT(bm.getPixels());
70 SkMD5 md5;
71 size_t rowLen = bm.info().bytesPerPixel() * bm.width();
72 for (int y = 0; y < bm.height(); ++y) {
halcanary1e903042016-04-25 10:29:36 -070073 md5.write(bm.getAddr(0, y), rowLen);
halcanarya096d7a2015-03-27 12:16:53 -070074 }
Hal Canary0f2f5222019-04-03 10:13:45 -040075 return md5.finish();
halcanarya096d7a2015-03-27 12:16:53 -070076}
77
scroggo9b2cdbf42015-07-10 12:07:02 -070078/**
79 * Compute the digest for bm and compare it to a known good digest.
80 * @param r Reporter to assert that bm's digest matches goodDigest.
81 * @param goodDigest The known good digest to compare to.
82 * @param bm The bitmap to test.
83 */
84static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
85 const SkBitmap& bm) {
Hal Canary0f2f5222019-04-03 10:13:45 -040086 SkMD5::Digest digest = md5(bm);
scroggo9b2cdbf42015-07-10 12:07:02 -070087 REPORTER_ASSERT(r, digest == goodDigest);
88}
89
scroggod1bc5742015-08-12 08:31:44 -070090/**
91 * Test decoding an SkCodec to a particular SkImageInfo.
92 *
halcanary96fcdcc2015-08-27 07:41:13 -070093 * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
scroggod1bc5742015-08-12 08:31:44 -070094 * the resulting decode should match.
95 */
scroggo7b5e5532016-02-04 06:14:24 -080096template<typename Codec>
97static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
scroggod1bc5742015-08-12 08:31:44 -070098 SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
99 SkBitmap bm;
100 bm.allocPixels(info);
scroggod1bc5742015-08-12 08:31:44 -0700101
102 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
103 REPORTER_ASSERT(r, result == expectedResult);
104
105 if (goodDigest) {
106 compare_to_good_digest(r, *goodDigest, bm);
107 }
108}
109
scroggob636b452015-07-22 07:16:20 -0700110SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
111 SkIRect rect;
112 do {
113 rect.fLeft = rand->nextRangeU(0, w);
114 rect.fTop = rand->nextRangeU(0, h);
115 rect.fRight = rand->nextRangeU(0, w);
116 rect.fBottom = rand->nextRangeU(0, h);
117 rect.sort();
118 } while (rect.isEmpty());
119 return rect;
120}
121
scroggo8e6c7ad2016-09-16 08:20:38 -0700122static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
123 const SkMD5::Digest& goodDigest) {
124 SkBitmap bm;
125 bm.allocPixels(info);
scroggo8e6c7ad2016-09-16 08:20:38 -0700126
127 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
128 bm.rowBytes()));
129
130 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
131
132 compare_to_good_digest(r, goodDigest, bm);
133}
134
135// Test in stripes, similar to DM's kStripe_Mode
136static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
137 const SkMD5::Digest& goodDigest) {
138 SkBitmap bm;
139 bm.allocPixels(info);
140 bm.eraseColor(SK_ColorYELLOW);
141
142 const int height = info.height();
143 // Note that if numStripes does not evenly divide height there will be an extra
144 // stripe.
145 const int numStripes = 4;
146
147 if (numStripes > height) {
148 // Image is too small.
149 return;
150 }
151
152 const int stripeHeight = height / numStripes;
153
154 // Iterate through the image twice. Once to decode odd stripes, and once for even.
155 for (int oddEven = 1; oddEven >= 0; oddEven--) {
156 for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
157 SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
Brian Osman788b9162020-02-07 10:36:46 -0500158 std::min(y + stripeHeight, height));
scroggo8e6c7ad2016-09-16 08:20:38 -0700159 SkCodec::Options options;
160 options.fSubset = &subset;
161 if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
162 bm.rowBytes(), &options)) {
163 ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
164 subset.top(), subset.bottom());
165 return;
166 }
167 if (SkCodec::kSuccess != codec->incrementalDecode()) {
168 ERRORF(r, "failed incremental decode starting from line %i\n", y);
169 return;
170 }
171 }
172 }
173
174 compare_to_good_digest(r, goodDigest, bm);
175}
176
scroggo7b5e5532016-02-04 06:14:24 -0800177template<typename Codec>
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500178static void test_codec(skiatest::Reporter* r, const char* path, Codec* codec, SkBitmap& bm,
179 const SkImageInfo& info, const SkISize& size, SkCodec::Result expectedResult,
180 SkMD5::Digest* digest, const SkMD5::Digest* goodDigest) {
msarette6dd0042015-10-09 11:07:34 -0700181
halcanarya096d7a2015-03-27 12:16:53 -0700182 REPORTER_ASSERT(r, info.dimensions() == size);
halcanarya096d7a2015-03-27 12:16:53 -0700183 bm.allocPixels(info);
msarettcc7f3052015-10-05 14:20:27 -0700184
185 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
msarette6dd0042015-10-09 11:07:34 -0700186 REPORTER_ASSERT(r, result == expectedResult);
halcanarya096d7a2015-03-27 12:16:53 -0700187
Hal Canary0f2f5222019-04-03 10:13:45 -0400188 *digest = md5(bm);
msarettcc7f3052015-10-05 14:20:27 -0700189 if (goodDigest) {
190 REPORTER_ASSERT(r, *digest == *goodDigest);
191 }
halcanarya096d7a2015-03-27 12:16:53 -0700192
msarett8ff6ca62015-09-18 12:06:04 -0700193 {
194 // Test decoding to 565
195 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
scroggoba584892016-05-20 13:56:13 -0700196 if (info.alphaType() == kOpaque_SkAlphaType) {
197 // Decoding to 565 should succeed.
198 SkBitmap bm565;
199 bm565.allocPixels(info565);
scroggoba584892016-05-20 13:56:13 -0700200
201 // This will allow comparison even if the image is incomplete.
202 bm565.eraseColor(SK_ColorBLACK);
203
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500204 auto actualResult = codec->getPixels(info565, bm565.getPixels(), bm565.rowBytes());
205 if (actualResult == expectedResult) {
Hal Canary0f2f5222019-04-03 10:13:45 -0400206 SkMD5::Digest digest565 = md5(bm565);
scroggoba584892016-05-20 13:56:13 -0700207
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500208 // A request for non-opaque should also succeed.
209 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
210 info565 = info565.makeAlphaType(alpha);
211 test_info(r, codec, info565, expectedResult, &digest565);
212 }
213 } else {
214 ERRORF(r, "Decoding %s to 565 failed with result \"%s\"\n\t\t\t\texpected:\"%s\"",
215 path,
216 SkCodec::ResultToString(actualResult),
217 SkCodec::ResultToString(expectedResult));
scroggoba584892016-05-20 13:56:13 -0700218 }
219 } else {
220 test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
221 }
222 }
223
224 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
225 SkImageInfo grayInfo = codec->getInfo();
226 SkBitmap grayBm;
227 grayBm.allocPixels(grayInfo);
scroggoba584892016-05-20 13:56:13 -0700228
229 grayBm.eraseColor(SK_ColorBLACK);
230
231 REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
232 grayBm.getPixels(), grayBm.rowBytes()));
233
Hal Canary0f2f5222019-04-03 10:13:45 -0400234 SkMD5::Digest grayDigest = md5(grayBm);
scroggoba584892016-05-20 13:56:13 -0700235
236 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
237 grayInfo = grayInfo.makeAlphaType(alpha);
238 test_info(r, codec, grayInfo, expectedResult, &grayDigest);
239 }
msarett8ff6ca62015-09-18 12:06:04 -0700240 }
241
242 // Verify that re-decoding gives the same result. It is interesting to check this after
243 // a decode to 565, since choosing to decode to 565 may result in some of the decode
244 // options being modified. These options should return to their defaults on another
245 // decode to kN32, so the new digest should match the old digest.
msarette6dd0042015-10-09 11:07:34 -0700246 test_info(r, codec, info, expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700247
248 {
249 // Check alpha type conversions
250 if (info.alphaType() == kOpaque_SkAlphaType) {
251 test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800252 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700253 test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800254 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700255 } else {
256 // Decoding to opaque should fail
257 test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
halcanary96fcdcc2015-08-27 07:41:13 -0700258 SkCodec::kInvalidConversion, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700259 SkAlphaType otherAt = info.alphaType();
260 if (kPremul_SkAlphaType == otherAt) {
261 otherAt = kUnpremul_SkAlphaType;
262 } else {
263 otherAt = kPremul_SkAlphaType;
264 }
265 // The other non-opaque alpha type should always succeed, but not match.
msarette6dd0042015-10-09 11:07:34 -0700266 test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700267 }
268 }
msarettcc7f3052015-10-05 14:20:27 -0700269}
270
scroggobed1ed62016-02-11 10:24:55 -0800271static bool supports_partial_scanlines(const char path[]) {
scroggo2c3b2182015-10-09 08:40:59 -0700272 static const char* const exts[] = {
Brian Salomon7a492f72020-08-21 12:39:33 -0400273 "jpg", "jpeg", "png", "webp",
scroggo2c3b2182015-10-09 08:40:59 -0700274 "JPG", "JPEG", "PNG", "WEBP"
275 };
276
277 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
278 if (SkStrEndsWith(path, exts[i])) {
279 return true;
280 }
281 }
282 return false;
283}
284
scroggo8e6c7ad2016-09-16 08:20:38 -0700285// FIXME: Break up this giant function
msarettcc7f3052015-10-05 14:20:27 -0700286static void check(skiatest::Reporter* r,
287 const char path[],
288 SkISize size,
289 bool supportsScanlineDecoding,
290 bool supportsSubsetDecoding,
scroggo8e6c7ad2016-09-16 08:20:38 -0700291 bool supportsIncomplete,
292 bool supportsNewScanlineDecoding = false) {
Nigel Tao9b9453e2018-08-01 09:59:38 +1000293 // If we're testing incomplete decodes, let's run the same test on full decodes.
294 if (supportsIncomplete) {
295 check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false,
296 supportsNewScanlineDecoding);
297 }
msarettcc7f3052015-10-05 14:20:27 -0700298
Ben Wagner145dbcd2016-11-03 14:40:50 -0400299 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700300 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700301 return;
302 }
msarette6dd0042015-10-09 11:07:34 -0700303
Ben Wagner145dbcd2016-11-03 14:40:50 -0400304 std::unique_ptr<SkCodec> codec(nullptr);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000305 if (supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700306 size_t size = stream->getLength();
Mike Reedede7bac2017-07-23 15:30:02 -0400307 codec = SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 2 * size / 3));
msarette6dd0042015-10-09 11:07:34 -0700308 } else {
Mike Reedede7bac2017-07-23 15:30:02 -0400309 codec = SkCodec::MakeFromStream(std::move(stream));
msarette6dd0042015-10-09 11:07:34 -0700310 }
msarettcc7f3052015-10-05 14:20:27 -0700311 if (!codec) {
312 ERRORF(r, "Unable to decode '%s'", path);
313 return;
314 }
315
316 // Test full image decodes with SkCodec
317 SkMD5::Digest codecDigest;
scroggoef0fed32016-02-18 05:59:25 -0800318 const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
msarettcc7f3052015-10-05 14:20:27 -0700319 SkBitmap bm;
Nigel Tao9b9453e2018-08-01 09:59:38 +1000320 SkCodec::Result expectedResult =
321 supportsIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500322 test_codec(r, path, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700323
324 // Scanline decoding follows.
scroggod8d68552016-06-06 11:26:17 -0700325
Nigel Tao9b9453e2018-08-01 09:59:38 +1000326 if (supportsNewScanlineDecoding && !supportsIncomplete) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400327 test_incremental_decode(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700328 // This is only supported by codecs that use incremental decoding to
329 // support subset decodes - png and jpeg (once SkJpegCodec is
330 // converted).
331 if (SkStrEndsWith(path, "png") || SkStrEndsWith(path, "PNG")) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400332 test_in_stripes(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700333 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700334 }
335
336 // Need to call startScanlineDecode() first.
337 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
338 REPORTER_ASSERT(r, !codec->skipScanlines(1));
scroggo46c57472015-09-30 08:57:13 -0700339 const SkCodec::Result startResult = codec->startScanlineDecode(info);
scroggo58421542015-04-01 11:25:20 -0700340 if (supportsScanlineDecoding) {
341 bm.eraseColor(SK_ColorYELLOW);
msarettc0e80c12015-07-01 06:50:35 -0700342
scroggo46c57472015-09-30 08:57:13 -0700343 REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
scroggo9b2cdbf42015-07-10 12:07:02 -0700344
scroggo58421542015-04-01 11:25:20 -0700345 for (int y = 0; y < info.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700346 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000347 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700348 REPORTER_ASSERT(r, 1 == lines);
349 }
scroggo58421542015-04-01 11:25:20 -0700350 }
351 // verify that scanline decoding gives the same result.
scroggo46c57472015-09-30 08:57:13 -0700352 if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
msarettcc7f3052015-10-05 14:20:27 -0700353 compare_to_good_digest(r, codecDigest, bm);
msarett5406d6f2015-08-31 06:55:13 -0700354 }
scroggo46c57472015-09-30 08:57:13 -0700355
356 // Cannot continue to decode scanlines beyond the end
357 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700358 == 0);
scroggo46c57472015-09-30 08:57:13 -0700359
360 // Interrupting a scanline decode with a full decode starts from
361 // scratch
362 REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
msarette6dd0042015-10-09 11:07:34 -0700363 const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000364 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700365 REPORTER_ASSERT(r, lines == 1);
366 }
scroggo46c57472015-09-30 08:57:13 -0700367 REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
msarette6dd0042015-10-09 11:07:34 -0700368 == expectedResult);
scroggo46c57472015-09-30 08:57:13 -0700369 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700370 == 0);
scroggo46c57472015-09-30 08:57:13 -0700371 REPORTER_ASSERT(r, codec->skipScanlines(1)
msarette6dd0042015-10-09 11:07:34 -0700372 == 0);
msarett80803ff2015-10-16 10:54:12 -0700373
374 // Test partial scanline decodes
scroggobed1ed62016-02-11 10:24:55 -0800375 if (supports_partial_scanlines(path) && info.width() >= 3) {
msarett80803ff2015-10-16 10:54:12 -0700376 SkCodec::Options options;
377 int width = info.width();
378 int height = info.height();
379 SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
380 options.fSubset = &subset;
381
Leon Scroggins571b30f2017-07-11 17:35:31 +0000382 const auto partialStartResult = codec->startScanlineDecode(info, &options);
msarett80803ff2015-10-16 10:54:12 -0700383 REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
384
385 for (int y = 0; y < height; y++) {
386 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000387 if (!supportsIncomplete) {
msarett80803ff2015-10-16 10:54:12 -0700388 REPORTER_ASSERT(r, 1 == lines);
389 }
390 }
391 }
scroggo58421542015-04-01 11:25:20 -0700392 } else {
scroggo46c57472015-09-30 08:57:13 -0700393 REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
halcanarya096d7a2015-03-27 12:16:53 -0700394 }
scroggob636b452015-07-22 07:16:20 -0700395
396 // The rest of this function tests decoding subsets, and will decode an arbitrary number of
397 // random subsets.
398 // Do not attempt to decode subsets of an image of only once pixel, since there is no
399 // meaningful subset.
400 if (size.width() * size.height() == 1) {
401 return;
402 }
403
404 SkRandom rand;
405 SkIRect subset;
406 SkCodec::Options opts;
407 opts.fSubset = &subset;
408 for (int i = 0; i < 5; i++) {
409 subset = generate_random_subset(&rand, size.width(), size.height());
410 SkASSERT(!subset.isEmpty());
411 const bool supported = codec->getValidSubset(&subset);
412 REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
413
Brian Salomon9241a6d2019-10-03 13:26:54 -0400414 SkImageInfo subsetInfo = info.makeDimensions(subset.size());
scroggob636b452015-07-22 07:16:20 -0700415 SkBitmap bm;
416 bm.allocPixels(subsetInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +0000417 const auto result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &opts);
scroggob636b452015-07-22 07:16:20 -0700418
419 if (supportsSubsetDecoding) {
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500420 if (expectedResult == SkCodec::kSuccess) {
421 REPORTER_ASSERT(r, result == expectedResult);
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500422 }
scroggob636b452015-07-22 07:16:20 -0700423 // Webp is the only codec that supports subsets, and it will have modified the subset
424 // to have even left/top.
425 REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
426 } else {
427 // No subsets will work.
428 REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
429 }
430 }
msarettcc7f3052015-10-05 14:20:27 -0700431
scroggobed1ed62016-02-11 10:24:55 -0800432 // SkAndroidCodec tests
scroggo8e6c7ad2016-09-16 08:20:38 -0700433 if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
scroggo2c3b2182015-10-09 08:40:59 -0700434
Ben Wagner145dbcd2016-11-03 14:40:50 -0400435 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700436 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700437 return;
438 }
msarette6dd0042015-10-09 11:07:34 -0700439
Leon Scroggins III7397d7a2018-01-04 13:26:30 -0500440 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
scroggo7b5e5532016-02-04 06:14:24 -0800441 if (!androidCodec) {
msarettcc7f3052015-10-05 14:20:27 -0700442 ERRORF(r, "Unable to decode '%s'", path);
443 return;
444 }
445
446 SkBitmap bm;
scroggobed1ed62016-02-11 10:24:55 -0800447 SkMD5::Digest androidCodecDigest;
Leon Scroggins IIIb41321b2018-12-11 10:37:07 -0500448 test_codec(r, path, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
scroggo7b5e5532016-02-04 06:14:24 -0800449 &codecDigest);
msarette6dd0042015-10-09 11:07:34 -0700450 }
451
Nigel Tao9b9453e2018-08-01 09:59:38 +1000452 if (!supportsIncomplete) {
scroggoef0fed32016-02-18 05:59:25 -0800453 // Test SkCodecImageGenerator
Ben Wagner145dbcd2016-11-03 14:40:50 -0400454 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
455 sk_sp<SkData> fullData(SkData::MakeFromStream(stream.get(), stream->getLength()));
456 std::unique_ptr<SkImageGenerator> gen(
Mike Reed185130c2017-02-15 15:14:16 -0500457 SkCodecImageGenerator::MakeFromEncodedCodec(fullData));
msarettedd2dcf2016-01-14 13:12:26 -0800458 SkBitmap bm;
459 bm.allocPixels(info);
msarettedd2dcf2016-01-14 13:12:26 -0800460 REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
461 compare_to_good_digest(r, codecDigest, bm);
scroggoef0fed32016-02-18 05:59:25 -0800462
Leon Scroggins III63cfb362020-04-24 13:00:48 -0400463#if !defined(SK_PNG_DISABLE_TESTS) && defined(SK_ENABLE_ANDROID_UTILS)
464 // Test using FrontBufferedStream, as Android does
465 auto bufferedStream = android::skia::FrontBufferedStream::Make(
Mike Reed98c5d922017-09-15 21:39:47 -0400466 SkMemoryStream::Make(std::move(fullData)), SkCodec::MinBufferedBytesNeeded());
scroggod8d68552016-06-06 11:26:17 -0700467 REPORTER_ASSERT(r, bufferedStream);
Mike Reed98c5d922017-09-15 21:39:47 -0400468 codec = SkCodec::MakeFromStream(std::move(bufferedStream));
scroggod8d68552016-06-06 11:26:17 -0700469 REPORTER_ASSERT(r, codec);
470 if (codec) {
471 test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
scroggoef0fed32016-02-18 05:59:25 -0800472 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700473#endif
msarettedd2dcf2016-01-14 13:12:26 -0800474 }
halcanarya096d7a2015-03-27 12:16:53 -0700475}
476
Leon Scroggins III83926342016-12-06 10:58:02 -0500477DEF_TEST(Codec_wbmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500478 check(r, "images/mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500479}
halcanarya096d7a2015-03-27 12:16:53 -0700480
Leon Scroggins III83926342016-12-06 10:58:02 -0500481DEF_TEST(Codec_webp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500482 check(r, "images/baby_tux.webp", SkISize::Make(386, 395), false, true, true);
483 check(r, "images/color_wheel.webp", SkISize::Make(128, 128), false, true, true);
484 check(r, "images/yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500485}
scroggo6f5e6192015-06-18 12:53:43 -0700486
Leon Scroggins III83926342016-12-06 10:58:02 -0500487DEF_TEST(Codec_bmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500488 check(r, "images/randPixels.bmp", SkISize::Make(8, 8), true, false, true);
489 check(r, "images/rle.bmp", SkISize::Make(320, 240), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500490}
halcanarya096d7a2015-03-27 12:16:53 -0700491
Leon Scroggins III83926342016-12-06 10:58:02 -0500492DEF_TEST(Codec_ico, r) {
msarette6dd0042015-10-09 11:07:34 -0700493 // FIXME: We are not ready to test incomplete ICOs
msarett68b204e2015-04-01 12:09:21 -0700494 // These two tests examine interestingly different behavior:
495 // Decodes an embedded BMP image
Hal Canaryc465d132017-12-08 10:21:31 -0500496 check(r, "images/color_wheel.ico", SkISize::Make(128, 128), true, false, false);
msarett68b204e2015-04-01 12:09:21 -0700497 // Decodes an embedded PNG image
Hal Canaryc465d132017-12-08 10:21:31 -0500498 check(r, "images/google_chrome.ico", SkISize::Make(256, 256), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500499}
halcanarya096d7a2015-03-27 12:16:53 -0700500
Leon Scroggins III83926342016-12-06 10:58:02 -0500501DEF_TEST(Codec_gif, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500502 check(r, "images/box.gif", SkISize::Make(200, 55), false, false, true, true);
503 check(r, "images/color_wheel.gif", SkISize::Make(128, 128), false, false, true, true);
msarette6dd0042015-10-09 11:07:34 -0700504 // randPixels.gif is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500505 check(r, "images/randPixels.gif", SkISize::Make(8, 8), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500506}
msarett438b2ad2015-04-09 12:43:10 -0700507
Leon Scroggins III83926342016-12-06 10:58:02 -0500508DEF_TEST(Codec_jpg, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500509 check(r, "images/CMYK.jpg", SkISize::Make(642, 516), true, false, true);
510 check(r, "images/color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700511 // grayscale.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500512 check(r, "images/grayscale.jpg", SkISize::Make(128, 128), true, false, false);
513 check(r, "images/mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700514 // randPixels.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500515 check(r, "images/randPixels.jpg", SkISize::Make(8, 8), true, false, false);
Leon Scroggins III83926342016-12-06 10:58:02 -0500516}
msarette16b04a2015-04-15 07:32:19 -0700517
Leon Scroggins III83926342016-12-06 10:58:02 -0500518DEF_TEST(Codec_png, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500519 check(r, "images/arrow.png", SkISize::Make(187, 312), false, false, true, true);
520 check(r, "images/baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
521 check(r, "images/color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
scroggo8e6c7ad2016-09-16 08:20:38 -0700522 // half-transparent-white-pixel.png is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500523 check(r, "images/half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
524 check(r, "images/mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
Brian Osmanccb21bf2018-07-09 14:57:48 -0400525 // mandrill_16.png is too small (relative to embedded sRGB profile) to test incomplete
526 check(r, "images/mandrill_16.png", SkISize::Make(16, 16), false, false, false, true);
Hal Canaryc465d132017-12-08 10:21:31 -0500527 check(r, "images/mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
528 check(r, "images/mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
529 check(r, "images/mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
530 check(r, "images/mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
531 check(r, "images/plane.png", SkISize::Make(250, 126), false, false, true, true);
532 check(r, "images/plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
533 check(r, "images/randPixels.png", SkISize::Make(8, 8), false, false, true, true);
534 check(r, "images/yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500535}
yujieqin916de9f2016-01-25 08:26:16 -0800536
yujieqinf236ee42016-02-29 07:14:42 -0800537// Disable RAW tests for Win32.
538#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Leon Scroggins III83926342016-12-06 10:58:02 -0500539DEF_TEST(Codec_raw, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500540 check(r, "images/sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
541 check(r, "images/sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
542 check(r, "images/dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
halcanarya096d7a2015-03-27 12:16:53 -0700543}
Leon Scroggins III83926342016-12-06 10:58:02 -0500544#endif
scroggo0a7e69c2015-04-03 07:22:22 -0700545
546static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
scroggo2c3b2182015-10-09 08:40:59 -0700547 // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
Mike Reedede7bac2017-07-23 15:30:02 -0400548 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500549 std::make_unique<SkMemoryStream>(stream, len, false)));
Mike Reedede7bac2017-07-23 15:30:02 -0400550 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500551 std::make_unique<SkMemoryStream>(stream, len, false)));
scroggo0a7e69c2015-04-03 07:22:22 -0700552}
553
554// Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
555// even on failure. Test some bad streams.
556DEF_TEST(Codec_leaks, r) {
557 // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
558 const char nonSupportedStream[] = "hello world";
559 // The other strings should look like the beginning of a file type, so we'll call some
560 // internal version of NewFromStream, which must also delete the stream on failure.
561 const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
562 const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
563 const char emptyWebp[] = "RIFF1234WEBPVP";
564 const char emptyBmp[] = { 'B', 'M' };
565 const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
566 const char emptyGif[] = "GIFVER";
567
568 test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
569 test_invalid_stream(r, emptyPng, sizeof(emptyPng));
570 test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
571 test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
572 test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
573 test_invalid_stream(r, emptyIco, sizeof(emptyIco));
574 test_invalid_stream(r, emptyGif, sizeof(emptyGif));
575}
msarette16b04a2015-04-15 07:32:19 -0700576
scroggo2c3b2182015-10-09 08:40:59 -0700577DEF_TEST(Codec_null, r) {
scroggobed1ed62016-02-11 10:24:55 -0800578 // Attempting to create an SkCodec or an SkAndroidCodec with null should not
scroggo2c3b2182015-10-09 08:40:59 -0700579 // crash.
Mike Reedede7bac2017-07-23 15:30:02 -0400580 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(nullptr));
581 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(nullptr));
scroggo2c3b2182015-10-09 08:40:59 -0700582}
583
msarette16b04a2015-04-15 07:32:19 -0700584static void test_dimensions(skiatest::Reporter* r, const char path[]) {
585 // Create the codec from the resource file
Ben Wagner145dbcd2016-11-03 14:40:50 -0400586 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarette16b04a2015-04-15 07:32:19 -0700587 if (!stream) {
msarette16b04a2015-04-15 07:32:19 -0700588 return;
589 }
Mike Reedede7bac2017-07-23 15:30:02 -0400590 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
msarette16b04a2015-04-15 07:32:19 -0700591 if (!codec) {
592 ERRORF(r, "Unable to create codec '%s'", path);
593 return;
594 }
595
596 // Check that the decode is successful for a variety of scales
scroggo501b7342015-11-03 07:55:11 -0800597 for (int sampleSize = 1; sampleSize < 32; sampleSize++) {
msarette16b04a2015-04-15 07:32:19 -0700598 // Scale the output dimensions
msarett3d9d7a72015-10-21 10:27:10 -0700599 SkISize scaledDims = codec->getSampledDimensions(sampleSize);
msarettb32758a2015-08-18 13:22:46 -0700600 SkImageInfo scaledInfo = codec->getInfo()
Brian Salomon9241a6d2019-10-03 13:26:54 -0400601 .makeDimensions(scaledDims)
msarettb32758a2015-08-18 13:22:46 -0700602 .makeColorType(kN32_SkColorType);
msarette16b04a2015-04-15 07:32:19 -0700603
604 // Set up for the decode
605 size_t rowBytes = scaledDims.width() * sizeof(SkPMColor);
Mike Reedf0ffb892017-10-03 14:47:21 -0400606 size_t totalBytes = scaledInfo.computeByteSize(rowBytes);
msarette16b04a2015-04-15 07:32:19 -0700607 SkAutoTMalloc<SkPMColor> pixels(totalBytes);
608
msarett3d9d7a72015-10-21 10:27:10 -0700609 SkAndroidCodec::AndroidOptions options;
610 options.fSampleSize = sampleSize;
scroggoeb602a52015-07-09 08:16:03 -0700611 SkCodec::Result result =
msarett3d9d7a72015-10-21 10:27:10 -0700612 codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options);
Leon Scroggins1340dbd2020-11-09 14:18:12 -0500613 if (result != SkCodec::kSuccess) {
614 ERRORF(r, "Failed to decode %s with sample size %i; error: %s", path, sampleSize,
615 SkCodec::ResultToString(result));
616 }
msarette16b04a2015-04-15 07:32:19 -0700617 }
618}
619
620// Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes
621DEF_TEST(Codec_Dimensions, r) {
622 // JPG
Hal Canaryc465d132017-12-08 10:21:31 -0500623 test_dimensions(r, "images/CMYK.jpg");
624 test_dimensions(r, "images/color_wheel.jpg");
625 test_dimensions(r, "images/grayscale.jpg");
626 test_dimensions(r, "images/mandrill_512_q075.jpg");
627 test_dimensions(r, "images/randPixels.jpg");
msarettb32758a2015-08-18 13:22:46 -0700628
629 // Decoding small images with very large scaling factors is a potential
630 // source of bugs and crashes. We disable these tests in Gold because
631 // tiny images are not very useful to look at.
632 // Here we make sure that we do not crash or access illegal memory when
633 // performing scaled decodes on small images.
Hal Canaryc465d132017-12-08 10:21:31 -0500634 test_dimensions(r, "images/1x1.png");
635 test_dimensions(r, "images/2x2.png");
636 test_dimensions(r, "images/3x3.png");
637 test_dimensions(r, "images/3x1.png");
638 test_dimensions(r, "images/1x1.png");
639 test_dimensions(r, "images/16x1.png");
640 test_dimensions(r, "images/1x16.png");
641 test_dimensions(r, "images/mandrill_16.png");
msarettb32758a2015-08-18 13:22:46 -0700642
yujieqin916de9f2016-01-25 08:26:16 -0800643 // RAW
yujieqinf236ee42016-02-29 07:14:42 -0800644// Disable RAW tests for Win32.
645#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Hal Canaryc465d132017-12-08 10:21:31 -0500646 test_dimensions(r, "images/sample_1mp.dng");
647 test_dimensions(r, "images/sample_1mp_rotated.dng");
648 test_dimensions(r, "images/dng_with_preview.dng");
msarett8e49ca32016-01-25 13:10:58 -0800649#endif
msarette16b04a2015-04-15 07:32:19 -0700650}
651
msarettd0375bc2015-08-12 08:08:56 -0700652static void test_invalid(skiatest::Reporter* r, const char path[]) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500653 auto data = GetResourceAsData(path);
654 if (!data) {
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500655 ERRORF(r, "Failed to get resource %s", path);
msarett4b17fa32015-04-23 08:53:39 -0700656 return;
657 }
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500658
659 REPORTER_ASSERT(r, !SkCodec::MakeFromData(data));
msarett4b17fa32015-04-23 08:53:39 -0700660}
msarette16b04a2015-04-15 07:32:19 -0700661
msarett4b17fa32015-04-23 08:53:39 -0700662DEF_TEST(Codec_Empty, r) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500663 if (GetResourcePath().isEmpty()) {
664 return;
665 }
666
msarett4b17fa32015-04-23 08:53:39 -0700667 // Test images that should not be able to create a codec
msarettd0375bc2015-08-12 08:08:56 -0700668 test_invalid(r, "empty_images/zero-dims.gif");
669 test_invalid(r, "empty_images/zero-embedded.ico");
670 test_invalid(r, "empty_images/zero-width.bmp");
671 test_invalid(r, "empty_images/zero-height.bmp");
672 test_invalid(r, "empty_images/zero-width.jpg");
673 test_invalid(r, "empty_images/zero-height.jpg");
674 test_invalid(r, "empty_images/zero-width.png");
675 test_invalid(r, "empty_images/zero-height.png");
676 test_invalid(r, "empty_images/zero-width.wbmp");
677 test_invalid(r, "empty_images/zero-height.wbmp");
678 // This image is an ico with an embedded mask-bmp. This is illegal.
679 test_invalid(r, "invalid_images/mask-bmp-ico.ico");
Matt Sarett5c496172017-02-07 17:01:16 -0500680 // It is illegal for a webp frame to not be fully contained by the canvas.
681 test_invalid(r, "invalid_images/invalid-offset.webp");
Leon Scroggins IIId87fbee2016-12-02 16:47:53 -0500682#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
683 test_invalid(r, "empty_images/zero_height.tiff");
684#endif
Leon Scroggins IIIfc4ee222017-07-14 11:48:52 -0400685 test_invalid(r, "invalid_images/b37623797.ico");
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500686 test_invalid(r, "invalid_images/osfuzz6295.webp");
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500687 test_invalid(r, "invalid_images/osfuzz6288.bmp");
Leon Scroggins III31476b72018-02-22 16:09:33 -0500688 test_invalid(r, "invalid_images/ossfuzz6347");
msarett4b17fa32015-04-23 08:53:39 -0700689}
msarett99f567e2015-08-05 12:58:26 -0700690
scroggo8e6c7ad2016-09-16 08:20:38 -0700691#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
692
693#ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions.
694 // It does not appear that anyone in Google3 is reading chunks.
695
scroggocf98fa92015-11-23 08:14:40 -0800696static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
697 SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
698 if (!sk_stream->write(data, len)) {
699 png_error(png_ptr, "sk_write_fn Error!");
700 }
701}
702
scroggocf98fa92015-11-23 08:14:40 -0800703DEF_TEST(Codec_pngChunkReader, r) {
704 // Create a dummy bitmap. Use unpremul RGBA for libpng.
705 SkBitmap bm;
706 const int w = 1;
707 const int h = 1;
708 const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
709 kUnpremul_SkAlphaType);
710 bm.setInfo(bmInfo);
711 bm.allocPixels();
712 bm.eraseColor(SK_ColorBLUE);
Hal Canary0f2f5222019-04-03 10:13:45 -0400713 SkMD5::Digest goodDigest = md5(bm);
scroggocf98fa92015-11-23 08:14:40 -0800714
715 // Write to a png file.
716 png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
717 REPORTER_ASSERT(r, png);
718 if (!png) {
719 return;
720 }
721
722 png_infop info = png_create_info_struct(png);
723 REPORTER_ASSERT(r, info);
724 if (!info) {
725 png_destroy_write_struct(&png, nullptr);
726 return;
727 }
728
729 if (setjmp(png_jmpbuf(png))) {
730 ERRORF(r, "failed writing png");
731 png_destroy_write_struct(&png, &info);
732 return;
733 }
734
735 SkDynamicMemoryWStream wStream;
736 png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
737
738 png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
739 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
740 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
741
742 // Create some chunks that match the Android framework's use.
743 static png_unknown_chunk gUnknowns[] = {
msarett133eaaa2016-01-07 11:03:25 -0800744 { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
745 { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
746 { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
scroggocf98fa92015-11-23 08:14:40 -0800747 };
748
749 png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
750 png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
751#if PNG_LIBPNG_VER < 10600
752 /* Deal with unknown chunk location bug in 1.5.x and earlier */
msarett133eaaa2016-01-07 11:03:25 -0800753 png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
754 png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
scroggocf98fa92015-11-23 08:14:40 -0800755#endif
756
757 png_write_info(png, info);
758
759 for (int j = 0; j < h; j++) {
760 png_bytep row = (png_bytep)(bm.getAddr(0, j));
761 png_write_rows(png, &row, 1);
762 }
763 png_write_end(png, info);
764 png_destroy_write_struct(&png, &info);
765
766 class ChunkReader : public SkPngChunkReader {
767 public:
768 ChunkReader(skiatest::Reporter* r)
769 : fReporter(r)
770 {
771 this->reset();
772 }
773
774 bool readChunk(const char tag[], const void* data, size_t length) override {
775 for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
776 if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
777 // Tag matches. This should have been the first time we see it.
778 REPORTER_ASSERT(fReporter, !fSeen[i]);
779 fSeen[i] = true;
780
781 // Data and length should match
782 REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
783 REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
784 (const char*) gUnknowns[i].data));
785 return true;
786 }
787 }
788 ERRORF(fReporter, "Saw an unexpected unknown chunk.");
789 return true;
790 }
791
792 bool allHaveBeenSeen() {
793 bool ret = true;
794 for (auto seen : fSeen) {
795 ret &= seen;
796 }
797 return ret;
798 }
799
800 void reset() {
801 sk_bzero(fSeen, sizeof(fSeen));
802 }
803
804 private:
805 skiatest::Reporter* fReporter; // Unowned
806 bool fSeen[3];
807 };
808
809 ChunkReader chunkReader(r);
810
811 // Now read the file with SkCodec.
Mike Reedede7bac2017-07-23 15:30:02 -0400812 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(wStream.detachAsData(), &chunkReader));
scroggocf98fa92015-11-23 08:14:40 -0800813 REPORTER_ASSERT(r, codec);
814 if (!codec) {
815 return;
816 }
817
818 // Now compare to the original.
819 SkBitmap decodedBm;
820 decodedBm.setInfo(codec->getInfo());
821 decodedBm.allocPixels();
822 SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
823 decodedBm.rowBytes());
824 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
825
826 if (decodedBm.colorType() != bm.colorType()) {
827 SkBitmap tmp;
Mike Kleinea3f0142019-03-20 11:12:10 -0500828 bool success = ToolUtils::copy_to(&tmp, bm.colorType(), decodedBm);
scroggocf98fa92015-11-23 08:14:40 -0800829 REPORTER_ASSERT(r, success);
830 if (!success) {
831 return;
832 }
833
834 tmp.swap(decodedBm);
835 }
836
837 compare_to_good_digest(r, goodDigest, decodedBm);
838 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
839
840 // Decoding again will read the chunks again.
841 chunkReader.reset();
842 REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
843 result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
844 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
845 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
846}
scroggo8e6c7ad2016-09-16 08:20:38 -0700847#endif // SK_PNG_DISABLE_TESTS
scroggocf98fa92015-11-23 08:14:40 -0800848#endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
scroggob9a1e342015-11-30 06:25:31 -0800849
scroggodb30be22015-12-08 18:54:13 -0800850// Stream that can only peek up to a limit
851class LimitedPeekingMemStream : public SkStream {
852public:
reed42943c82016-09-12 12:01:44 -0700853 LimitedPeekingMemStream(sk_sp<SkData> data, size_t limit)
854 : fStream(std::move(data))
scroggodb30be22015-12-08 18:54:13 -0800855 , fLimit(limit) {}
856
857 size_t peek(void* buf, size_t bytes) const override {
Brian Osman788b9162020-02-07 10:36:46 -0500858 return fStream.peek(buf, std::min(bytes, fLimit));
scroggodb30be22015-12-08 18:54:13 -0800859 }
860 size_t read(void* buf, size_t bytes) override {
861 return fStream.read(buf, bytes);
862 }
863 bool rewind() override {
864 return fStream.rewind();
865 }
866 bool isAtEnd() const override {
msarettff2a6c82016-09-07 11:23:28 -0700867 return fStream.isAtEnd();
scroggodb30be22015-12-08 18:54:13 -0800868 }
869private:
870 SkMemoryStream fStream;
871 const size_t fLimit;
872};
873
yujieqinf236ee42016-02-29 07:14:42 -0800874// Disable RAW tests for Win32.
875#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin9c7a8a42016-02-05 08:21:19 -0800876// Test that the RawCodec works also for not asset stream. This will test the code path using
877// SkRawBufferedStream instead of SkRawAssetStream.
yujieqin9c7a8a42016-02-05 08:21:19 -0800878DEF_TEST(Codec_raw_notseekable, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000879 constexpr char path[] = "images/dng_with_preview.dng";
880 sk_sp<SkData> data(GetResourceAsData(path));
yujieqin9c7a8a42016-02-05 08:21:19 -0800881 if (!data) {
882 SkDebugf("Missing resource '%s'\n", path);
883 return;
884 }
885
Mike Reedede7bac2017-07-23 15:30:02 -0400886 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500887 std::make_unique<NotAssetMemStream>(std::move(data))));
yujieqin9c7a8a42016-02-05 08:21:19 -0800888 REPORTER_ASSERT(r, codec);
889
890 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
891}
892#endif
893
scroggodb30be22015-12-08 18:54:13 -0800894// Test that even if webp_parse_header fails to peek enough, it will fall back to read()
895// + rewind() and succeed.
896DEF_TEST(Codec_webp_peek, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000897 constexpr char path[] = "images/baby_tux.webp";
898 auto data = GetResourceAsData(path);
scroggodb30be22015-12-08 18:54:13 -0800899 if (!data) {
900 SkDebugf("Missing resource '%s'\n", path);
901 return;
902 }
903
904 // The limit is less than webp needs to peek or read.
Mike Reedede7bac2017-07-23 15:30:02 -0400905 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500906 std::make_unique<LimitedPeekingMemStream>(data, 25)));
scroggodb30be22015-12-08 18:54:13 -0800907 REPORTER_ASSERT(r, codec);
908
scroggo7b5e5532016-02-04 06:14:24 -0800909 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800910
911 // Similarly, a stream which does not peek should still succeed.
Mike Kleinf46d5ca2019-12-11 10:45:01 -0500912 codec = SkCodec::MakeFromStream(std::make_unique<LimitedPeekingMemStream>(data, 0));
scroggodb30be22015-12-08 18:54:13 -0800913 REPORTER_ASSERT(r, codec);
914
scroggo7b5e5532016-02-04 06:14:24 -0800915 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800916}
917
msarett7f7ec202016-03-01 12:12:27 -0800918// SkCodec's wbmp decoder was initially unnecessarily restrictive.
919// It required the second byte to be zero. The wbmp specification allows
920// a couple of bits to be 1 (so long as they do not overlap with 0x9F).
921// Test that SkCodec now supports an image with these bits set.
Leon Scroggins III83926342016-12-06 10:58:02 -0500922DEF_TEST(Codec_wbmp_restrictive, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500923 const char* path = "images/mandrill.wbmp";
Ben Wagner145dbcd2016-11-03 14:40:50 -0400924 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
scroggob9a1e342015-11-30 06:25:31 -0800925 if (!stream) {
scroggob9a1e342015-11-30 06:25:31 -0800926 return;
927 }
928
929 // Modify the stream to contain a second byte with some bits set.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400930 auto data = SkCopyStreamToData(stream.get());
scroggob9a1e342015-11-30 06:25:31 -0800931 uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
932 writeableData[1] = static_cast<uint8_t>(~0x9F);
933
msarett7f7ec202016-03-01 12:12:27 -0800934 // SkCodec should support this.
Mike Reedede7bac2017-07-23 15:30:02 -0400935 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
scroggob9a1e342015-11-30 06:25:31 -0800936 REPORTER_ASSERT(r, codec);
937 if (!codec) {
938 return;
939 }
scroggo7b5e5532016-02-04 06:14:24 -0800940 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggob9a1e342015-11-30 06:25:31 -0800941}
scroggodb30be22015-12-08 18:54:13 -0800942
943// wbmp images have a header that can be arbitrarily large, depending on the
944// size of the image. We cap the size at 65535, meaning we only need to look at
945// 8 bytes to determine whether we can read the image. This is important
Leon Scroggins III04be2b52017-08-17 15:13:20 -0400946// because SkCodec only passes a limited number of bytes to SkWbmpCodec to
947// determine whether the image is a wbmp.
scroggodb30be22015-12-08 18:54:13 -0800948DEF_TEST(Codec_wbmp_max_size, r) {
949 const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
950 0x83, 0xFF, 0x7F, // W: 65535
951 0x83, 0xFF, 0x7F }; // H: 65535
Ben Wagner145dbcd2016-11-03 14:40:50 -0400952 std::unique_ptr<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
Mike Reedede7bac2017-07-23 15:30:02 -0400953 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggodb30be22015-12-08 18:54:13 -0800954
955 REPORTER_ASSERT(r, codec);
956 if (!codec) return;
957
958 REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
959 REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
960
961 // Now test an image which is too big. Any image with a larger header (i.e.
962 // has bigger width/height) is also too big.
963 const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
964 0x84, 0x80, 0x00, // W: 65536
965 0x84, 0x80, 0x00 }; // H: 65536
John Stilesfbd050b2020-08-03 13:21:46 -0400966 stream = std::make_unique<SkMemoryStream>(tooBigWbmp, sizeof(tooBigWbmp), false);
Mike Reedede7bac2017-07-23 15:30:02 -0400967 codec = SkCodec::MakeFromStream(std::move(stream));
scroggodb30be22015-12-08 18:54:13 -0800968
969 REPORTER_ASSERT(r, !codec);
970}
msarett2812f032016-07-18 15:56:08 -0700971
972DEF_TEST(Codec_jpeg_rewind, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500973 const char* path = "images/mandrill_512_q075.jpg";
Leon Scroggins III42886572017-01-27 13:16:28 -0500974 sk_sp<SkData> data(GetResourceAsData(path));
975 if (!data) {
msarett2812f032016-07-18 15:56:08 -0700976 return;
977 }
Leon Scroggins III42886572017-01-27 13:16:28 -0500978
979 data = SkData::MakeSubset(data.get(), 0, data->size() / 2);
Mike Reedede7bac2017-07-23 15:30:02 -0400980 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(data));
msarett2812f032016-07-18 15:56:08 -0700981 if (!codec) {
982 ERRORF(r, "Unable to create codec '%s'.", path);
983 return;
984 }
985
986 const int width = codec->getInfo().width();
987 const int height = codec->getInfo().height();
988 size_t rowBytes = sizeof(SkPMColor) * width;
989 SkAutoMalloc pixelStorage(height * rowBytes);
990
991 // Perform a sampled decode.
992 SkAndroidCodec::AndroidOptions opts;
993 opts.fSampleSize = 12;
Leon Scroggins III42886572017-01-27 13:16:28 -0500994 auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12);
995 auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts);
996 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -0700997
998 // Rewind the codec and perform a full image decode.
Matt Sarett74b16ed2017-01-25 11:58:11 -0500999 result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes);
Leon Scroggins III42886572017-01-27 13:16:28 -05001000 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
Matt Sarett74b16ed2017-01-25 11:58:11 -05001001
1002 // Now perform a subset decode.
1003 {
1004 opts.fSampleSize = 1;
1005 SkIRect subset = SkIRect::MakeWH(100, 100);
1006 opts.fSubset = &subset;
1007 result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(),
1008 rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001009 // Though we only have half the data, it is enough to decode this subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001010 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1011 }
1012
1013 // Perform another full image decode. ASAN will detect if we look at the subset when it is
1014 // out of scope. This would happen if we depend on the old state in the codec.
Leon Scroggins III42886572017-01-27 13:16:28 -05001015 // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage
1016 // used to look at the old subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001017 opts.fSubset = nullptr;
1018 result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001019 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -07001020}
msarett549ca322016-08-17 08:54:08 -07001021
msarett35bb74b2016-08-22 07:41:28 -07001022static void check_color_xform(skiatest::Reporter* r, const char* path) {
Mike Reedede7bac2017-07-23 15:30:02 -04001023 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(GetResourceAsStream(path)));
msarett35bb74b2016-08-22 07:41:28 -07001024
1025 SkAndroidCodec::AndroidOptions opts;
1026 opts.fSampleSize = 3;
1027 const int subsetWidth = codec->getInfo().width() / 2;
1028 const int subsetHeight = codec->getInfo().height() / 2;
1029 SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight);
1030 opts.fSubset = &subset;
1031
1032 const int dstWidth = subsetWidth / opts.fSampleSize;
1033 const int dstHeight = subsetHeight / opts.fSampleSize;
Brian Osman82ebe042019-01-04 17:03:00 -05001034 auto colorSpace = SkColorSpace::MakeRGB(SkNamedTransferFn::k2Dot2, SkNamedGamut::kAdobeRGB);
msarett35bb74b2016-08-22 07:41:28 -07001035 SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight)
1036 .makeColorType(kN32_SkColorType)
1037 .makeColorSpace(colorSpace);
1038
1039 size_t rowBytes = dstInfo.minRowBytes();
Mike Reedf0ffb892017-10-03 14:47:21 -04001040 SkAutoMalloc pixelStorage(dstInfo.computeByteSize(rowBytes));
msarett35bb74b2016-08-22 07:41:28 -07001041 SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts);
1042 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1043}
1044
1045DEF_TEST(Codec_ColorXform, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001046 check_color_xform(r, "images/mandrill_512_q075.jpg");
1047 check_color_xform(r, "images/mandrill_512.png");
msarett35bb74b2016-08-22 07:41:28 -07001048}
1049
msarettf17b71f2016-09-12 14:30:03 -07001050static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) {
1051 switch (origColorType) {
1052 case kRGBA_8888_SkColorType:
1053 case kBGRA_8888_SkColorType:
1054 return kRGBA_8888_SkColorType == codecColorType ||
1055 kBGRA_8888_SkColorType == codecColorType;
1056 default:
1057 return origColorType == codecColorType;
1058 }
1059}
1060
1061static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) {
1062 switch (origAlphaType) {
1063 case kUnpremul_SkAlphaType:
1064 case kPremul_SkAlphaType:
1065 return kUnpremul_SkAlphaType == codecAlphaType ||
1066 kPremul_SkAlphaType == codecAlphaType;
1067 default:
1068 return origAlphaType == codecAlphaType;
1069 }
1070}
1071
1072static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) {
1073 SkBitmap bm1;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001074 bm1.allocPixels(info);
1075 SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes());
msarettf17b71f2016-09-12 14:30:03 -07001076 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarett9b09cd82016-08-29 14:47:49 -07001077
1078 // Encode the image to png.
Leon Scroggins III0098ccb2018-09-24 15:24:31 -04001079 auto data = SkEncodeBitmap(bm1, SkEncodedImageFormat::kPNG, 100);
msarett9b09cd82016-08-29 14:47:49 -07001080
Mike Reedede7bac2017-07-23 15:30:02 -04001081 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
msarettf17b71f2016-09-12 14:30:03 -07001082 REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType()));
1083 REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType()));
msarett9b09cd82016-08-29 14:47:49 -07001084
1085 SkBitmap bm2;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001086 bm2.allocPixels(info);
1087 result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes());
msarett9b09cd82016-08-29 14:47:49 -07001088 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1089
Hal Canary0f2f5222019-04-03 10:13:45 -04001090 REPORTER_ASSERT(r, md5(bm1) == md5(bm2));
msarett9b09cd82016-08-29 14:47:49 -07001091}
1092
1093DEF_TEST(Codec_PngRoundTrip, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001094 auto codec = SkCodec::MakeFromStream(GetResourceAsStream("images/mandrill_512_q075.jpg"));
msarett549ca322016-08-17 08:54:08 -07001095
msarettf17b71f2016-09-12 14:30:03 -07001096 SkColorType colorTypesOpaque[] = {
1097 kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1098 };
1099 for (SkColorType colorType : colorTypesOpaque) {
1100 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType);
1101 check_round_trip(r, codec.get(), newInfo);
1102 }
1103
Hal Canaryc465d132017-12-08 10:21:31 -05001104 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/grayscale.jpg"));
msarettf17b71f2016-09-12 14:30:03 -07001105 check_round_trip(r, codec.get(), codec->getInfo());
1106
Hal Canaryc465d132017-12-08 10:21:31 -05001107 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/yellow_rose.png"));
msarettf17b71f2016-09-12 14:30:03 -07001108
1109 SkColorType colorTypesWithAlpha[] = {
1110 kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1111 };
1112 SkAlphaType alphaTypes[] = {
1113 kUnpremul_SkAlphaType, kPremul_SkAlphaType
1114 };
1115 for (SkColorType colorType : colorTypesWithAlpha) {
1116 for (SkAlphaType alphaType : alphaTypes) {
1117 // Set color space to nullptr because color correct premultiplies do not round trip.
1118 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType)
1119 .makeAlphaType(alphaType)
1120 .makeColorSpace(nullptr);
1121 check_round_trip(r, codec.get(), newInfo);
1122 }
1123 }
1124
Hal Canaryc465d132017-12-08 10:21:31 -05001125 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/index8.png"));
msarettf17b71f2016-09-12 14:30:03 -07001126
1127 for (SkAlphaType alphaType : alphaTypes) {
1128 SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType)
1129 .makeColorSpace(nullptr);
1130 check_round_trip(r, codec.get(), newInfo);
1131 }
msarett549ca322016-08-17 08:54:08 -07001132}
msarett2ecc35f2016-09-08 11:55:16 -07001133
1134static void test_conversion_possible(skiatest::Reporter* r, const char* path,
scroggo8e6c7ad2016-09-16 08:20:38 -07001135 bool supportsScanlineDecoder,
1136 bool supportsIncrementalDecoder) {
Ben Wagner145dbcd2016-11-03 14:40:50 -04001137 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001138 if (!stream) {
1139 return;
1140 }
1141
Mike Reedede7bac2017-07-23 15:30:02 -04001142 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001143 if (!codec) {
1144 ERRORF(r, "failed to create a codec for %s", path);
1145 return;
1146 }
1147
msarett2ecc35f2016-09-08 11:55:16 -07001148 SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType);
1149
1150 SkBitmap bm;
1151 bm.allocPixels(infoF16);
1152 SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
Mike Kleince4cf722018-05-10 11:29:15 -04001153 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001154
1155 result = codec->startScanlineDecode(infoF16);
1156 if (supportsScanlineDecoder) {
Mike Kleince4cf722018-05-10 11:29:15 -04001157 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001158 } else {
Leon Scroggins III07418182017-08-15 12:24:02 -04001159 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
Mike Kleince4cf722018-05-10 11:29:15 -04001160 || SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001161 }
1162
1163 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1164 if (supportsIncrementalDecoder) {
Mike Kleince4cf722018-05-10 11:29:15 -04001165 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001166 } else {
Leon Scroggins III07418182017-08-15 12:24:02 -04001167 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
Mike Kleince4cf722018-05-10 11:29:15 -04001168 || SkCodec::kSuccess == result);
msarett2ecc35f2016-09-08 11:55:16 -07001169 }
1170
Brian Osman36703d92017-12-12 14:09:31 -05001171 infoF16 = infoF16.makeColorSpace(infoF16.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001172 result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
1173 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001174 result = codec->startScanlineDecode(infoF16);
1175 if (supportsScanlineDecoder) {
msarett2ecc35f2016-09-08 11:55:16 -07001176 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001177 } else {
1178 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
1179 }
1180
1181 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1182 if (supportsIncrementalDecoder) {
1183 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1184 } else {
1185 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
msarett2ecc35f2016-09-08 11:55:16 -07001186 }
1187}
1188
1189DEF_TEST(Codec_F16ConversionPossible, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001190 test_conversion_possible(r, "images/color_wheel.webp", false, false);
1191 test_conversion_possible(r, "images/mandrill_512_q075.jpg", true, false);
1192 test_conversion_possible(r, "images/yellow_rose.png", false, true);
scroggo8e6c7ad2016-09-16 08:20:38 -07001193}
1194
scroggo19b91532016-10-24 09:03:26 -07001195static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) {
1196 SkBitmap bm;
1197 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1198 bm.allocPixels(info);
1199
1200 SkCodec::Options opts;
1201 opts.fFrameIndex = frame;
1202 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info,
Leon Scroggins571b30f2017-07-11 17:35:31 +00001203 bm.getPixels(), bm.rowBytes(), &opts));
scroggo19b91532016-10-24 09:03:26 -07001204}
1205
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001206// For an animated GIF, we should only read enough to decode frame 0 if the
1207// client never calls getFrameInfo and only decodes frame 0.
scroggo19b91532016-10-24 09:03:26 -07001208DEF_TEST(Codec_skipFullParse, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001209 auto path = "images/test640x479.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001210 auto streamObj = GetResourceAsStream(path);
1211 if (!streamObj) {
scroggo19b91532016-10-24 09:03:26 -07001212 return;
1213 }
Mike Reed71f867c2017-07-23 13:14:10 -04001214 SkStream* stream = streamObj.get();
scroggo19b91532016-10-24 09:03:26 -07001215
1216 // Note that we cheat and hold on to the stream pointer, but SkCodec will
1217 // take ownership. We will not refer to the stream after the SkCodec
1218 // deletes it.
Mike Reedede7bac2017-07-23 15:30:02 -04001219 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(streamObj)));
scroggo19b91532016-10-24 09:03:26 -07001220 if (!codec) {
1221 ERRORF(r, "Failed to create codec for %s", path);
1222 return;
1223 }
1224
1225 REPORTER_ASSERT(r, stream->hasPosition());
1226 const size_t sizePosition = stream->getPosition();
1227 REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength());
1228
1229 // This should read more of the stream, but not the whole stream.
1230 decode_frame(r, codec.get(), 0);
1231 const size_t positionAfterFirstFrame = stream->getPosition();
1232 REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition
1233 && positionAfterFirstFrame < stream->getLength());
1234
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001235 // There is more data in the stream.
scroggo19b91532016-10-24 09:03:26 -07001236 auto frameInfo = codec->getFrameInfo();
1237 REPORTER_ASSERT(r, frameInfo.size() == 4);
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001238 REPORTER_ASSERT(r, stream->getPosition() > positionAfterFirstFrame);
scroggo19b91532016-10-24 09:03:26 -07001239}
1240
scroggo8e6c7ad2016-09-16 08:20:38 -07001241// Only rewinds up to a limit.
1242class LimitedRewindingStream : public SkStream {
1243public:
Mike Reed71f867c2017-07-23 13:14:10 -04001244 static std::unique_ptr<SkStream> Make(const char path[], size_t limit) {
1245 auto stream = GetResourceAsStream(path);
scroggo8e6c7ad2016-09-16 08:20:38 -07001246 if (!stream) {
1247 return nullptr;
1248 }
Mike Reed71f867c2017-07-23 13:14:10 -04001249 return std::unique_ptr<SkStream>(new LimitedRewindingStream(std::move(stream), limit));
scroggo8e6c7ad2016-09-16 08:20:38 -07001250 }
1251
1252 size_t read(void* buffer, size_t size) override {
1253 const size_t bytes = fStream->read(buffer, size);
1254 fPosition += bytes;
1255 return bytes;
1256 }
1257
1258 bool isAtEnd() const override {
1259 return fStream->isAtEnd();
1260 }
1261
1262 bool rewind() override {
1263 if (fPosition <= fLimit && fStream->rewind()) {
1264 fPosition = 0;
1265 return true;
1266 }
1267
1268 return false;
1269 }
1270
1271private:
Ben Wagner145dbcd2016-11-03 14:40:50 -04001272 std::unique_ptr<SkStream> fStream;
1273 const size_t fLimit;
1274 size_t fPosition;
scroggo8e6c7ad2016-09-16 08:20:38 -07001275
Mike Reed71f867c2017-07-23 13:14:10 -04001276 LimitedRewindingStream(std::unique_ptr<SkStream> stream, size_t limit)
1277 : fStream(std::move(stream))
scroggo8e6c7ad2016-09-16 08:20:38 -07001278 , fLimit(limit)
1279 , fPosition(0)
1280 {
1281 SkASSERT(fStream);
1282 }
1283};
1284
1285DEF_TEST(Codec_fallBack, r) {
1286 // SkAndroidCodec needs to be able to fall back to scanline decoding
1287 // if incremental decoding does not work. Make sure this does not
1288 // require a rewind.
1289
1290 // Formats that currently do not support incremental decoding
1291 auto files = {
Hal Canaryc465d132017-12-08 10:21:31 -05001292 "images/CMYK.jpg",
1293 "images/color_wheel.ico",
1294 "images/mandrill.wbmp",
1295 "images/randPixels.bmp",
scroggo8e6c7ad2016-09-16 08:20:38 -07001296 };
1297 for (auto file : files) {
Leon Scroggins III04be2b52017-08-17 15:13:20 -04001298 auto stream = LimitedRewindingStream::Make(file, SkCodec::MinBufferedBytesNeeded());
scroggo8e6c7ad2016-09-16 08:20:38 -07001299 if (!stream) {
1300 SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
1301 return;
1302 }
1303
Mike Reedede7bac2017-07-23 15:30:02 -04001304 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggo8e6c7ad2016-09-16 08:20:38 -07001305 if (!codec) {
1306 ERRORF(r, "Failed to create codec for %s,", file);
1307 continue;
1308 }
1309
1310 SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
1311 SkBitmap bm;
1312 bm.allocPixels(info);
1313
1314 if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
1315 bm.rowBytes())) {
1316 ERRORF(r, "Is scanline decoding now implemented for %s?", file);
1317 continue;
1318 }
1319
1320 // Scanline decoding should not require a rewind.
1321 SkCodec::Result result = codec->startScanlineDecode(info);
1322 if (SkCodec::kSuccess != result) {
1323 ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
1324 }
1325 }
msarett2ecc35f2016-09-08 11:55:16 -07001326}
scroggoc46cdd42016-10-10 06:45:32 -07001327
1328// This test verifies that we fixed an assert statement that fired when reusing a png codec
1329// after scaling.
1330DEF_TEST(Codec_reusePng, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001331 std::unique_ptr<SkStream> stream(GetResourceAsStream("images/plane.png"));
scroggoc46cdd42016-10-10 06:45:32 -07001332 if (!stream) {
1333 return;
1334 }
1335
Mike Reedede7bac2017-07-23 15:30:02 -04001336 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
scroggoc46cdd42016-10-10 06:45:32 -07001337 if (!codec) {
1338 ERRORF(r, "Failed to create codec\n");
1339 return;
1340 }
1341
1342 SkAndroidCodec::AndroidOptions opts;
1343 opts.fSampleSize = 5;
1344 auto size = codec->getSampledDimensions(opts.fSampleSize);
Brian Salomon9241a6d2019-10-03 13:26:54 -04001345 auto info = codec->getInfo().makeDimensions(size).makeColorType(kN32_SkColorType);
scroggoc46cdd42016-10-10 06:45:32 -07001346 SkBitmap bm;
1347 bm.allocPixels(info);
1348 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1349 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1350
1351 info = codec->getInfo().makeColorType(kN32_SkColorType);
1352 bm.allocPixels(info);
1353 opts.fSampleSize = 1;
1354 result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1355 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1356}
scroggoe61b3b42016-10-10 07:17:32 -07001357
1358DEF_TEST(Codec_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001359 auto file = "images/plane_interlaced.png";
scroggoe61b3b42016-10-10 07:17:32 -07001360 std::unique_ptr<SkStream> stream(GetResourceAsStream(file));
1361 if (!stream) {
1362 return;
1363 }
1364
1365 // This is enough to read the header etc, but no rows.
Mike Reedede7bac2017-07-23 15:30:02 -04001366 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 99)));
scroggoe61b3b42016-10-10 07:17:32 -07001367 if (!codec) {
1368 ERRORF(r, "Failed to create codec\n");
1369 return;
1370 }
1371
1372 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1373 SkBitmap bm;
1374 bm.allocPixels(info);
1375 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
1376 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1377
1378 // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded
1379 // should get set to zero by incrementalDecode.
1380 int rowsDecoded = 77;
1381 result = codec->incrementalDecode(&rowsDecoded);
1382 REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput);
1383 REPORTER_ASSERT(r, rowsDecoded == 0);
1384}
Matt Sarett29121eb2016-10-17 14:32:46 -04001385
Matt Sarettd59948a2017-04-26 10:59:48 -04001386static void test_invalid_images(skiatest::Reporter* r, const char* path,
1387 SkCodec::Result expectedResult) {
Mike Reed71f867c2017-07-23 13:14:10 -04001388 auto stream = GetResourceAsStream(path);
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001389 if (!stream) {
1390 return;
1391 }
1392
Mike Reedede7bac2017-07-23 15:30:02 -04001393 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001394 REPORTER_ASSERT(r, codec);
1395
Matt Sarettd59948a2017-04-26 10:59:48 -04001396 test_info(r, codec.get(), codec->getInfo().makeColorType(kN32_SkColorType), expectedResult,
1397 nullptr);
1398}
1399
1400DEF_TEST(Codec_InvalidImages, r) {
1401 // ASAN will complain if there is an issue.
Leon Scroggins III674a1842017-07-06 12:26:09 -04001402 test_invalid_images(r, "invalid_images/skbug5887.gif", SkCodec::kErrorInInput);
Matt Sarettd59948a2017-04-26 10:59:48 -04001403 test_invalid_images(r, "invalid_images/many-progressive-scans.jpg", SkCodec::kInvalidInput);
1404 test_invalid_images(r, "invalid_images/b33251605.bmp", SkCodec::kIncompleteInput);
1405 test_invalid_images(r, "invalid_images/bad_palette.png", SkCodec::kInvalidInput);
1406}
1407
1408static void test_invalid_header(skiatest::Reporter* r, const char* path) {
Mike Reed0933bc92017-12-09 01:27:41 +00001409 auto data = GetResourceAsData(path);
1410 if (!data) {
1411 return;
1412 }
1413 std::unique_ptr<SkStreamAsset> stream(new SkMemoryStream(std::move(data)));
Mike Reed847068c2017-07-26 11:35:53 -04001414 if (!stream) {
Matt Sarettd59948a2017-04-26 10:59:48 -04001415 return;
1416 }
Mike Reedede7bac2017-07-23 15:30:02 -04001417 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Matt Sarettd59948a2017-04-26 10:59:48 -04001418 REPORTER_ASSERT(r, !codec);
1419}
1420
1421DEF_TEST(Codec_InvalidHeader, r) {
1422 test_invalid_header(r, "invalid_images/int_overflow.ico");
1423
1424 // These files report values that have caused problems with SkFILEStreams.
1425 // They are invalid, and should not create SkCodecs.
1426 test_invalid_header(r, "invalid_images/b33651913.bmp");
1427 test_invalid_header(r, "invalid_images/b34778578.bmp");
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001428}
1429
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001430/*
1431For the Codec_InvalidAnimated test, immediately below,
1432resources/invalid_images/skbug6046.gif is:
1433
143400000000: 4749 4638 3961 2000 0000 0000 002c ff00 GIF89a ......,..
143500000010: 7400 0600 0000 4001 0021 f904 0a00 0000 t.....@..!......
143600000020: 002c ff00 0000 ff00 7400 0606 0606 0601 .,......t.......
143700000030: 0021 f904 0000 0000 002c ff00 0000 ffcc .!.......,......
143800000040: 1b36 5266 deba 543d .6Rf..T=
1439
Leon Scroggins980d03b2019-07-11 20:47:16 +00001440It nominally contains 3 frames, but only the first one is valid. It came from a
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001441fuzzer doing random mutations and copies. The breakdown:
1442
1443@000 6 bytes magic "GIF89a"
1444@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1445 - width = 32
1446 - height = 0
1447 - flags = 0x00
1448 - background color index, pixel aspect ratio bytes ignored
1449@00D 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x40
1450 - origin_x = 255
1451 - origin_y = 116
1452 - width = 6
1453 - height = 0
1454 - flags = 0x40, interlaced
1455@017 2 bytes Image Descriptor body (pixel data): 0x01 0x00
Leon Scroggins980d03b2019-07-11 20:47:16 +00001456 - lit_width = 1
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001457 - 0x00 byte means "end of data" for this frame
1458@019 8 bytes Graphic Control Extension: 0x21 0xF9 ... 0x00
1459 - valid, but irrelevant here.
1460@021 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1461 - origin_x = 255
1462 - origin_y = 0
1463 - width = 255
1464 - height = 116
1465 - flags = 0x06, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1466@02B 14 bytes Image Descriptor body (pixel data): 0x06 0x06 ... 0x00
1467 - lit_width = 6
1468 - 0x06 precedes a 6 byte block of data
1469 - 0x04 precedes a 4 byte block of data
1470 - 0x00 byte means "end of data" for this frame
1471@039 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1472 - origin_x = 255
1473 - origin_y = 0
1474 - width = 52479
1475 - height = 13851
1476 - flags = 0x52, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1477@043 5 bytes Image Descriptor body (pixel data): 0x66 0xDE ... unexpected-EOF
Leon Scroggins980d03b2019-07-11 20:47:16 +00001478 - lit_width = 102, INVALID, GREATER THAN 8
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001479 - 0xDE precedes a 222 byte block of data, INVALIDLY TRUNCATED
1480
1481On Image Descriptor flags INVALIDITY,
1482https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 20.c says that "Size of
1483Local Color Table [the low 3 bits]... should be 0 if there is no Local Color
1484Table specified [the high bit]."
1485
Leon Scroggins980d03b2019-07-11 20:47:16 +00001486On LZW literal width (also known as Minimum Code Size) INVALIDITY,
1487https://www.w3.org/Graphics/GIF/spec-gif89a.txt Appendix F says that "Normally
1488this will be the same as the number of [palette index] bits. Because of some
1489algorithmic constraints however, black & white images which have one color bit
1490must be indicated as having a code size of 2." In practice, some GIF decoders,
1491including both the old third_party/gif code and the Wuffs GIF decoder, don't
1492enforce this "at least 2" constraint. Nonetheless, any width greater than 8 is
1493invalid, as there are only 8 bits in a byte.
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001494*/
1495
Leon Scroggins III56e32092016-12-12 17:10:46 -05001496DEF_TEST(Codec_InvalidAnimated, r) {
1497 // ASAN will complain if there is an issue.
1498 auto path = "invalid_images/skbug6046.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001499 auto stream = GetResourceAsStream(path);
Leon Scroggins III56e32092016-12-12 17:10:46 -05001500 if (!stream) {
1501 return;
1502 }
1503
Mike Reedede7bac2017-07-23 15:30:02 -04001504 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins III56e32092016-12-12 17:10:46 -05001505 REPORTER_ASSERT(r, codec);
1506 if (!codec) {
1507 return;
1508 }
1509
1510 const auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1511 SkBitmap bm;
1512 bm.allocPixels(info);
1513
1514 auto frameInfos = codec->getFrameInfo();
1515 SkCodec::Options opts;
Leon Scroggins III249b8e32017-04-17 12:46:33 -04001516 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
Leon Scroggins III56e32092016-12-12 17:10:46 -05001517 opts.fFrameIndex = i;
Leon Scroggins III33deb7e2017-06-07 12:31:51 -04001518 const auto reqFrame = frameInfos[i].fRequiredFrame;
Nigel Tao66bc5242018-08-22 10:56:03 +10001519 opts.fPriorFrame = reqFrame == i - 1 ? reqFrame : SkCodec::kNoFrame;
Leon Scroggins III56e32092016-12-12 17:10:46 -05001520 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001521
Leon Scroggins III56e32092016-12-12 17:10:46 -05001522 if (result != SkCodec::kSuccess) {
Adlai Holler684838f2020-05-12 10:41:04 -04001523 ERRORF(r, "Failed to start decoding frame %i (out of %zu) with error %i\n", i,
Leon Scroggins III56e32092016-12-12 17:10:46 -05001524 frameInfos.size(), result);
1525 continue;
1526 }
1527
1528 codec->incrementalDecode();
1529 }
1530}
Matt Sarett0e032be2017-03-15 17:50:08 -04001531
Matt Sarett5df93de2017-03-22 21:52:47 +00001532static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap,
Matt Sarettc367d032017-05-05 11:13:26 -04001533 SkEncodedImageFormat format) {
Matt Sarett5df93de2017-03-22 21:52:47 +00001534 switch (format) {
1535 case SkEncodedImageFormat::kPNG:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001536 SkPngEncoder::Encode(stream, pixmap, SkPngEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001537 break;
1538 case SkEncodedImageFormat::kJPEG:
Matt Sarett26b44df2017-05-02 16:04:56 -04001539 SkJpegEncoder::Encode(stream, pixmap, SkJpegEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001540 break;
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001541 case SkEncodedImageFormat::kWEBP:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001542 SkWebpEncoder::Encode(stream, pixmap, SkWebpEncoder::Options());
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001543 break;
Matt Sarett5df93de2017-03-22 21:52:47 +00001544 default:
1545 SkASSERT(false);
1546 break;
1547 }
1548}
1549
Brian Osmanb62f50c2018-07-12 14:44:27 -04001550static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format) {
Matt Sarett0e032be2017-03-15 17:50:08 -04001551 // Test with sRGB color space.
1552 SkBitmap srgbBitmap;
1553 SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType);
1554 srgbBitmap.allocPixels(srgbInfo);
1555 *srgbBitmap.getAddr32(0, 0) = 0;
1556 SkPixmap pixmap;
1557 srgbBitmap.peekPixels(&pixmap);
1558 SkDynamicMemoryWStream srgbBuf;
Brian Osmanb62f50c2018-07-12 14:44:27 -04001559 encode_format(&srgbBuf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001560 sk_sp<SkData> srgbData = srgbBuf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001561 std::unique_ptr<SkCodec> srgbCodec(SkCodec::MakeFromData(srgbData));
Mike Kleine28a6b52018-07-25 13:05:17 -04001562 REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == sk_srgb_singleton());
Matt Sarett0e032be2017-03-15 17:50:08 -04001563
1564 // Test with P3 color space.
1565 SkDynamicMemoryWStream p3Buf;
Mike Kleinb147ace2020-01-16 11:11:06 -06001566 sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3);
Matt Sarett0e032be2017-03-15 17:50:08 -04001567 pixmap.setColorSpace(p3);
Brian Osmanb62f50c2018-07-12 14:44:27 -04001568 encode_format(&p3Buf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001569 sk_sp<SkData> p3Data = p3Buf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001570 std::unique_ptr<SkCodec> p3Codec(SkCodec::MakeFromData(p3Data));
Matt Sarett0e032be2017-03-15 17:50:08 -04001571 REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB());
Brian Osman82ebe042019-01-04 17:03:00 -05001572 skcms_Matrix3x3 mat0, mat1;
Matt Sarett0e032be2017-03-15 17:50:08 -04001573 bool success = p3->toXYZD50(&mat0);
1574 REPORTER_ASSERT(r, success);
1575 success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1);
1576 REPORTER_ASSERT(r, success);
1577
Brian Osman82ebe042019-01-04 17:03:00 -05001578 for (int i = 0; i < 3; i++) {
1579 for (int j = 0; j < 3; j++) {
1580 REPORTER_ASSERT(r, color_space_almost_equal(mat0.vals[i][j], mat1.vals[i][j]));
Matt Sarett0e032be2017-03-15 17:50:08 -04001581 }
1582 }
1583}
Matt Sarett5df93de2017-03-22 21:52:47 +00001584
1585DEF_TEST(Codec_EncodeICC, r) {
Brian Osmanb62f50c2018-07-12 14:44:27 -04001586 test_encode_icc(r, SkEncodedImageFormat::kPNG);
1587 test_encode_icc(r, SkEncodedImageFormat::kJPEG);
1588 test_encode_icc(r, SkEncodedImageFormat::kWEBP);
Matt Sarett5df93de2017-03-22 21:52:47 +00001589}
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001590
1591DEF_TEST(Codec_webp_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001592 const char* path = "images/baby_tux.webp";
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001593 sk_sp<SkData> data(GetResourceAsData(path));
1594 if (!data) {
1595 return;
1596 }
1597
1598 // Truncate this file so that the header is available but no rows can be
1599 // decoded. This should create a codec but fail to decode.
1600 size_t truncatedSize = 5000;
1601 sk_sp<SkData> subset = SkData::MakeSubset(data.get(), 0, truncatedSize);
1602 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(subset));
1603 if (!codec) {
1604 ERRORF(r, "Failed to create a codec for %s truncated to only %lu bytes",
1605 path, truncatedSize);
1606 return;
1607 }
1608
1609 test_info(r, codec.get(), codec->getInfo(), SkCodec::kInvalidInput, nullptr);
1610}
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001611
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001612/*
1613For the Codec_ossfuzz6274 test, immediately below,
1614resources/invalid_images/ossfuzz6274.gif is:
1615
161600000000: 4749 4638 3961 2000 2000 f120 2020 2020 GIF89a . ..
161700000010: 2020 2020 2020 2020 2021 f903 ff20 2020 !...
161800000020: 002c 0000 0000 2000 2000 2000 00 .,.... . . ..
1619
1620@000 6 bytes magic "GIF89a"
1621@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1622 - width = 32
1623 - height = 32
1624 - flags = 0xF1, global color table, 4 RGB entries
1625 - background color index, pixel aspect ratio bytes ignored
1626@00D 12 bytes Color Table: 0x20 0x20 ... 0x20
1627@019 20 bytes Graphic Control Extension: 0x21 0xF9 ... unexpected-EOF
1628 - 0x03 precedes a 3 byte block of data, INVALID, MUST BE 4
1629 - 0x20 precedes a 32 byte block of data, INVALIDly truncated
1630
1631https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 23.c says that the
1632block size (for an 0x21 0xF9 Graphic Control Extension) must be "the fixed
1633value 4".
1634*/
1635
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001636DEF_TEST(Codec_ossfuzz6274, r) {
1637 if (GetResourcePath().isEmpty()) {
1638 return;
1639 }
1640
1641 const char* file = "invalid_images/ossfuzz6274.gif";
1642 auto image = GetResourceAsImage(file);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001643
1644#ifdef SK_HAS_WUFFS_LIBRARY
1645 // We are transitioning from an old GIF implementation to a new (Wuffs) GIF
1646 // implementation.
1647 //
1648 // This test (without SK_HAS_WUFFS_LIBRARY) is overly specific to the old
1649 // implementation. In the new implementation, the MakeFromStream factory
1650 // method returns a nullptr SkImage*, instead of returning a non-null but
1651 // otherwise all-transparent SkImage*.
1652 //
1653 // Either way, the end-to-end result is the same - the source input is
1654 // rejected as an invalid GIF image - but the two implementations differ in
1655 // how that's represented.
1656 //
1657 // Once the transition is complete, we can remove the #ifdef and delete the
1658 // rest of the test function.
1659 //
1660 // See Codec_GifTruncated3 for the equivalent of the rest of the test
1661 // function, on different (but still truncated) source data.
1662 if (image) {
1663 ERRORF(r, "Invalid data gave non-nullptr image");
1664 }
1665 return;
1666#endif
1667
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001668 if (!image) {
1669 ERRORF(r, "Missing %s", file);
1670 return;
1671 }
1672
1673 REPORTER_ASSERT(r, image->width() == 32);
1674 REPORTER_ASSERT(r, image->height() == 32);
1675
1676 SkBitmap bm;
1677 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(32, 32))) {
1678 ERRORF(r, "Failed to allocate pixels");
1679 return;
1680 }
1681
1682 bm.eraseColor(SK_ColorTRANSPARENT);
1683
1684 SkCanvas canvas(bm);
1685 canvas.drawImage(image, 0, 0, nullptr);
1686
1687 for (int i = 0; i < image->width(); ++i)
1688 for (int j = 0; j < image->height(); ++j) {
1689 SkColor actual = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(i, j));
1690 if (actual != SK_ColorTRANSPARENT) {
1691 ERRORF(r, "did not initialize pixels! %i, %i is %x", i, j, actual);
1692 }
1693 }
1694}
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001695
Leon Scroggins III665949a2018-06-26 10:49:42 -04001696DEF_TEST(Codec_78329453, r) {
1697 if (GetResourcePath().isEmpty()) {
1698 return;
1699 }
1700
1701 const char* file = "images/b78329453.jpeg";
1702 auto data = GetResourceAsData(file);
1703 if (!data) {
1704 ERRORF(r, "Missing %s", file);
1705 return;
1706 }
1707
1708 auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(data));
1709 if (!codec) {
1710 ERRORF(r, "failed to create codec from %s", file);
1711 return;
1712 }
1713
1714 // A bug in jpeg_skip_scanlines resulted in an infinite loop for this specific
1715 // sample size on this image. Other sample sizes could have had the same result,
1716 // but the ones tested by DM happen to not.
1717 constexpr int kSampleSize = 19;
1718 const auto size = codec->getSampledDimensions(kSampleSize);
Brian Salomon9241a6d2019-10-03 13:26:54 -04001719 auto info = codec->getInfo().makeDimensions(size);
Leon Scroggins III665949a2018-06-26 10:49:42 -04001720 SkBitmap bm;
1721 bm.allocPixels(info);
1722 bm.eraseColor(SK_ColorTRANSPARENT);
1723
1724 SkAndroidCodec::AndroidOptions options;
1725 options.fSampleSize = kSampleSize;
1726 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &options);
1727 if (result != SkCodec::kSuccess) {
1728 ERRORF(r, "failed to decode with error %s", SkCodec::ResultToString(result));
1729 }
1730}
1731
Leon Scroggins III36f7e322018-08-27 11:55:46 -04001732DEF_TEST(Codec_A8, r) {
1733 if (GetResourcePath().isEmpty()) {
1734 return;
1735 }
1736
1737 const char* file = "images/mandrill_cmyk.jpg";
1738 auto data = GetResourceAsData(file);
1739 if (!data) {
1740 ERRORF(r, "missing %s", file);
1741 return;
1742 }
1743
1744 auto codec = SkCodec::MakeFromData(std::move(data));
1745 auto info = codec->getInfo().makeColorType(kAlpha_8_SkColorType);
1746 SkBitmap bm;
1747 bm.allocPixels(info);
1748 REPORTER_ASSERT(r, codec->getPixels(bm.pixmap()) == SkCodec::kInvalidConversion);
1749}
1750
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001751DEF_TEST(Codec_crbug807324, r) {
1752 if (GetResourcePath().isEmpty()) {
1753 return;
1754 }
1755
1756 const char* file = "images/crbug807324.png";
1757 auto image = GetResourceAsImage(file);
1758 if (!image) {
1759 ERRORF(r, "Missing %s", file);
1760 return;
1761 }
1762
1763 const int kWidth = image->width();
1764 const int kHeight = image->height();
1765
1766 SkBitmap bm;
1767 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(kWidth, kHeight))) {
1768 ERRORF(r, "Could not allocate pixels (%i x %i)", kWidth, kHeight);
1769 return;
1770 }
1771
1772 bm.eraseColor(SK_ColorTRANSPARENT);
1773
1774 SkCanvas canvas(bm);
1775 canvas.drawImage(image, 0, 0, nullptr);
1776
1777 for (int i = 0; i < kWidth; ++i)
1778 for (int j = 0; j < kHeight; ++j) {
1779 if (*bm.getAddr32(i, j) == SK_ColorTRANSPARENT) {
1780 ERRORF(r, "image should not be transparent! %i, %i is 0", i, j);
1781 return;
1782 }
1783 }
1784}
Leon Scroggins III196f3192020-02-03 12:39:54 -05001785
1786DEF_TEST(Codec_F16_noColorSpace, r) {
1787 const char* path = "images/color_wheel.png";
1788 auto data = GetResourceAsData(path);
1789 if (!data) {
1790 return;
1791 }
1792
1793 auto codec = SkCodec::MakeFromData(std::move(data));
1794 SkImageInfo info = codec->getInfo().makeColorType(kRGBA_F16_SkColorType)
1795 .makeColorSpace(nullptr);
1796 test_info(r, codec.get(), info, SkCodec::kSuccess, nullptr);
1797}
Leon Scroggins III42a604f2020-02-06 15:47:58 -05001798
1799// These test images have ICC profiles that do not map to an SkColorSpace.
1800// Verify that decoding them with a null destination space does not perform
1801// color space transformations.
1802DEF_TEST(Codec_noConversion, r) {
1803 const struct Rec {
1804 const char* name;
1805 SkColor color;
1806 } recs[] = {
1807 { "images/cmyk_yellow_224_224_32.jpg", 0xFFD8FC04 },
1808 { "images/wide_gamut_yellow_224_224_64.jpeg",0xFFE0E040 },
1809 };
1810
1811 for (const auto& rec : recs) {
1812 auto data = GetResourceAsData(rec.name);
1813 if (!data) {
1814 continue;
1815 }
1816
1817 auto codec = SkCodec::MakeFromData(std::move(data));
1818 if (!codec) {
1819 ERRORF(r, "Failed to create a codec from %s", rec.name);
1820 continue;
1821 }
1822
1823 const auto* profile = codec->getICCProfile();
1824 if (!profile) {
1825 ERRORF(r, "Expected %s to have a profile", rec.name);
1826 continue;
1827 }
1828
1829 auto cs = SkColorSpace::Make(*profile);
1830 REPORTER_ASSERT(r, !cs.get());
1831
1832 SkImageInfo info = codec->getInfo().makeColorSpace(nullptr);
1833 SkBitmap bm;
1834 bm.allocPixels(info);
1835 if (codec->getPixels(info, bm.getPixels(), bm.rowBytes()) != SkCodec::kSuccess) {
1836 ERRORF(r, "Failed to decode %s", rec.name);
1837 continue;
1838 }
1839 REPORTER_ASSERT(r, bm.getColor(0, 0) == rec.color);
1840 }
1841}