blob: 4656d871a313848f20934809fb73548352f86b6c [file] [log] [blame]
halcanarya096d7a2015-03-27 12:16:53 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Leon Scroggins III932efed2016-12-16 11:39:51 -05008#include "FakeStreams.h"
halcanarya096d7a2015-03-27 12:16:53 -07009#include "Resources.h"
msarett3d9d7a72015-10-21 10:27:10 -070010#include "SkAndroidCodec.h"
Hal Canary95e3c052017-01-11 12:44:43 -050011#include "SkAutoMalloc.h"
halcanarya096d7a2015-03-27 12:16:53 -070012#include "SkBitmap.h"
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -050013#include "SkCanvas.h"
halcanarya096d7a2015-03-27 12:16:53 -070014#include "SkCodec.h"
msarettedd2dcf2016-01-14 13:12:26 -080015#include "SkCodecImageGenerator.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040016#include "SkColor.h"
17#include "SkColorSpace.h"
Matt Sarett0e032be2017-03-15 17:50:08 -040018#include "SkColorSpacePriv.h"
msarette6dd0042015-10-09 11:07:34 -070019#include "SkData.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040020#include "SkEncodedImageFormat.h"
Kevin Lubickc456b732017-01-11 17:21:57 +000021#include "SkFrontBufferedStream.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040022#include "SkImage.h"
23#include "SkImageGenerator.h"
24#include "SkImageInfo.h"
Ben Wagner501c17c2018-03-12 20:04:31 +000025#include "SkJpegEncoder.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040026#include "SkMD5.h"
27#include "SkMakeUnique.h"
28#include "SkMalloc.h"
29#include "SkMatrix44.h"
30#include "SkPixmap.h"
Hal Canary95e3c052017-01-11 12:44:43 -050031#include "SkPngChunkReader.h"
Matt Sarettc367d032017-05-05 11:13:26 -040032#include "SkPngEncoder.h"
scroggob636b452015-07-22 07:16:20 -070033#include "SkRandom.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040034#include "SkRect.h"
35#include "SkRefCnt.h"
36#include "SkSize.h"
scroggocf98fa92015-11-23 08:14:40 -080037#include "SkStream.h"
scroggob9a1e342015-11-30 06:25:31 -080038#include "SkStreamPriv.h"
Ben Wagnerb607a8f2018-03-12 13:46:21 -040039#include "SkString.h"
40#include "SkTemplates.h"
41#include "SkTypes.h"
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -050042#include "SkUnPreMultiply.h"
Matt Sarett04c37312017-05-05 14:02:13 -040043#include "SkWebpEncoder.h"
halcanarya096d7a2015-03-27 12:16:53 -070044#include "Test.h"
Ben Wagner501c17c2018-03-12 20:04:31 +000045#include "png.h"
Ben Wagner501c17c2018-03-12 20:04:31 +000046#include "sk_tool_utils.h"
Ben Wagner1a462bd2018-03-12 13:46:21 -040047
Ben Wagnerb607a8f2018-03-12 13:46:21 -040048#include <setjmp.h>
49#include <cstring>
50#include <memory>
51#include <utility>
52#include <vector>
53
scroggo8e6c7ad2016-09-16 08:20:38 -070054#if PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR < 5
55 // FIXME (scroggo): Google3 needs to be updated to use a newer version of libpng. In
56 // the meantime, we had to break some pieces of SkPngCodec in order to support Google3.
57 // The parts that are broken are likely not used by Google3.
58 #define SK_PNG_DISABLE_TESTS
59#endif
60
halcanarya096d7a2015-03-27 12:16:53 -070061static void md5(const SkBitmap& bm, SkMD5::Digest* digest) {
halcanarya096d7a2015-03-27 12:16:53 -070062 SkASSERT(bm.getPixels());
63 SkMD5 md5;
64 size_t rowLen = bm.info().bytesPerPixel() * bm.width();
65 for (int y = 0; y < bm.height(); ++y) {
halcanary1e903042016-04-25 10:29:36 -070066 md5.write(bm.getAddr(0, y), rowLen);
halcanarya096d7a2015-03-27 12:16:53 -070067 }
68 md5.finish(*digest);
69}
70
scroggo9b2cdbf42015-07-10 12:07:02 -070071/**
72 * Compute the digest for bm and compare it to a known good digest.
73 * @param r Reporter to assert that bm's digest matches goodDigest.
74 * @param goodDigest The known good digest to compare to.
75 * @param bm The bitmap to test.
76 */
77static void compare_to_good_digest(skiatest::Reporter* r, const SkMD5::Digest& goodDigest,
78 const SkBitmap& bm) {
79 SkMD5::Digest digest;
80 md5(bm, &digest);
81 REPORTER_ASSERT(r, digest == goodDigest);
82}
83
scroggod1bc5742015-08-12 08:31:44 -070084/**
85 * Test decoding an SkCodec to a particular SkImageInfo.
86 *
halcanary96fcdcc2015-08-27 07:41:13 -070087 * Calling getPixels(info) should return expectedResult, and if goodDigest is non nullptr,
scroggod1bc5742015-08-12 08:31:44 -070088 * the resulting decode should match.
89 */
scroggo7b5e5532016-02-04 06:14:24 -080090template<typename Codec>
91static void test_info(skiatest::Reporter* r, Codec* codec, const SkImageInfo& info,
scroggod1bc5742015-08-12 08:31:44 -070092 SkCodec::Result expectedResult, const SkMD5::Digest* goodDigest) {
93 SkBitmap bm;
94 bm.allocPixels(info);
scroggod1bc5742015-08-12 08:31:44 -070095
96 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
97 REPORTER_ASSERT(r, result == expectedResult);
98
99 if (goodDigest) {
100 compare_to_good_digest(r, *goodDigest, bm);
101 }
102}
103
scroggob636b452015-07-22 07:16:20 -0700104SkIRect generate_random_subset(SkRandom* rand, int w, int h) {
105 SkIRect rect;
106 do {
107 rect.fLeft = rand->nextRangeU(0, w);
108 rect.fTop = rand->nextRangeU(0, h);
109 rect.fRight = rand->nextRangeU(0, w);
110 rect.fBottom = rand->nextRangeU(0, h);
111 rect.sort();
112 } while (rect.isEmpty());
113 return rect;
114}
115
scroggo8e6c7ad2016-09-16 08:20:38 -0700116static void test_incremental_decode(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
117 const SkMD5::Digest& goodDigest) {
118 SkBitmap bm;
119 bm.allocPixels(info);
scroggo8e6c7ad2016-09-16 08:20:38 -0700120
121 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->startIncrementalDecode(info, bm.getPixels(),
122 bm.rowBytes()));
123
124 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->incrementalDecode());
125
126 compare_to_good_digest(r, goodDigest, bm);
127}
128
129// Test in stripes, similar to DM's kStripe_Mode
130static void test_in_stripes(skiatest::Reporter* r, SkCodec* codec, const SkImageInfo& info,
131 const SkMD5::Digest& goodDigest) {
132 SkBitmap bm;
133 bm.allocPixels(info);
134 bm.eraseColor(SK_ColorYELLOW);
135
136 const int height = info.height();
137 // Note that if numStripes does not evenly divide height there will be an extra
138 // stripe.
139 const int numStripes = 4;
140
141 if (numStripes > height) {
142 // Image is too small.
143 return;
144 }
145
146 const int stripeHeight = height / numStripes;
147
148 // Iterate through the image twice. Once to decode odd stripes, and once for even.
149 for (int oddEven = 1; oddEven >= 0; oddEven--) {
150 for (int y = oddEven * stripeHeight; y < height; y += 2 * stripeHeight) {
151 SkIRect subset = SkIRect::MakeLTRB(0, y, info.width(),
152 SkTMin(y + stripeHeight, height));
153 SkCodec::Options options;
154 options.fSubset = &subset;
155 if (SkCodec::kSuccess != codec->startIncrementalDecode(info, bm.getAddr(0, y),
156 bm.rowBytes(), &options)) {
157 ERRORF(r, "failed to start incremental decode!\ttop: %i\tbottom%i\n",
158 subset.top(), subset.bottom());
159 return;
160 }
161 if (SkCodec::kSuccess != codec->incrementalDecode()) {
162 ERRORF(r, "failed incremental decode starting from line %i\n", y);
163 return;
164 }
165 }
166 }
167
168 compare_to_good_digest(r, goodDigest, bm);
169}
170
scroggo7b5e5532016-02-04 06:14:24 -0800171template<typename Codec>
172static void test_codec(skiatest::Reporter* r, Codec* codec, SkBitmap& bm, const SkImageInfo& info,
scroggo27c17282015-10-27 08:14:46 -0700173 const SkISize& size, SkCodec::Result expectedResult, SkMD5::Digest* digest,
174 const SkMD5::Digest* goodDigest) {
msarette6dd0042015-10-09 11:07:34 -0700175
halcanarya096d7a2015-03-27 12:16:53 -0700176 REPORTER_ASSERT(r, info.dimensions() == size);
halcanarya096d7a2015-03-27 12:16:53 -0700177 bm.allocPixels(info);
msarettcc7f3052015-10-05 14:20:27 -0700178
179 SkCodec::Result result = codec->getPixels(info, bm.getPixels(), bm.rowBytes());
msarette6dd0042015-10-09 11:07:34 -0700180 REPORTER_ASSERT(r, result == expectedResult);
halcanarya096d7a2015-03-27 12:16:53 -0700181
msarettcc7f3052015-10-05 14:20:27 -0700182 md5(bm, digest);
183 if (goodDigest) {
184 REPORTER_ASSERT(r, *digest == *goodDigest);
185 }
halcanarya096d7a2015-03-27 12:16:53 -0700186
msarett8ff6ca62015-09-18 12:06:04 -0700187 {
188 // Test decoding to 565
189 SkImageInfo info565 = info.makeColorType(kRGB_565_SkColorType);
scroggoba584892016-05-20 13:56:13 -0700190 if (info.alphaType() == kOpaque_SkAlphaType) {
191 // Decoding to 565 should succeed.
192 SkBitmap bm565;
193 bm565.allocPixels(info565);
scroggoba584892016-05-20 13:56:13 -0700194
195 // This will allow comparison even if the image is incomplete.
196 bm565.eraseColor(SK_ColorBLACK);
197
198 REPORTER_ASSERT(r, expectedResult == codec->getPixels(info565,
199 bm565.getPixels(), bm565.rowBytes()));
200
201 SkMD5::Digest digest565;
202 md5(bm565, &digest565);
203
204 // A dumb client's 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 test_info(r, codec, info565, SkCodec::kInvalidConversion, nullptr);
211 }
212 }
213
214 if (codec->getInfo().colorType() == kGray_8_SkColorType) {
215 SkImageInfo grayInfo = codec->getInfo();
216 SkBitmap grayBm;
217 grayBm.allocPixels(grayInfo);
scroggoba584892016-05-20 13:56:13 -0700218
219 grayBm.eraseColor(SK_ColorBLACK);
220
221 REPORTER_ASSERT(r, expectedResult == codec->getPixels(grayInfo,
222 grayBm.getPixels(), grayBm.rowBytes()));
223
224 SkMD5::Digest grayDigest;
225 md5(grayBm, &grayDigest);
226
227 for (auto alpha : { kPremul_SkAlphaType, kUnpremul_SkAlphaType }) {
228 grayInfo = grayInfo.makeAlphaType(alpha);
229 test_info(r, codec, grayInfo, expectedResult, &grayDigest);
230 }
msarett8ff6ca62015-09-18 12:06:04 -0700231 }
232
233 // Verify that re-decoding gives the same result. It is interesting to check this after
234 // a decode to 565, since choosing to decode to 565 may result in some of the decode
235 // options being modified. These options should return to their defaults on another
236 // decode to kN32, so the new digest should match the old digest.
msarette6dd0042015-10-09 11:07:34 -0700237 test_info(r, codec, info, expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700238
239 {
240 // Check alpha type conversions
241 if (info.alphaType() == kOpaque_SkAlphaType) {
242 test_info(r, codec, info.makeAlphaType(kUnpremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800243 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700244 test_info(r, codec, info.makeAlphaType(kPremul_SkAlphaType),
scroggoc5560be2016-02-03 09:42:42 -0800245 expectedResult, digest);
scroggod1bc5742015-08-12 08:31:44 -0700246 } else {
247 // Decoding to opaque should fail
248 test_info(r, codec, info.makeAlphaType(kOpaque_SkAlphaType),
halcanary96fcdcc2015-08-27 07:41:13 -0700249 SkCodec::kInvalidConversion, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700250 SkAlphaType otherAt = info.alphaType();
251 if (kPremul_SkAlphaType == otherAt) {
252 otherAt = kUnpremul_SkAlphaType;
253 } else {
254 otherAt = kPremul_SkAlphaType;
255 }
256 // The other non-opaque alpha type should always succeed, but not match.
msarette6dd0042015-10-09 11:07:34 -0700257 test_info(r, codec, info.makeAlphaType(otherAt), expectedResult, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700258 }
259 }
msarettcc7f3052015-10-05 14:20:27 -0700260}
261
scroggobed1ed62016-02-11 10:24:55 -0800262static bool supports_partial_scanlines(const char path[]) {
scroggo2c3b2182015-10-09 08:40:59 -0700263 static const char* const exts[] = {
264 "jpg", "jpeg", "png", "webp"
265 "JPG", "JPEG", "PNG", "WEBP"
266 };
267
268 for (uint32_t i = 0; i < SK_ARRAY_COUNT(exts); i++) {
269 if (SkStrEndsWith(path, exts[i])) {
270 return true;
271 }
272 }
273 return false;
274}
275
scroggo8e6c7ad2016-09-16 08:20:38 -0700276// FIXME: Break up this giant function
msarettcc7f3052015-10-05 14:20:27 -0700277static void check(skiatest::Reporter* r,
278 const char path[],
279 SkISize size,
280 bool supportsScanlineDecoding,
281 bool supportsSubsetDecoding,
scroggo8e6c7ad2016-09-16 08:20:38 -0700282 bool supportsIncomplete,
283 bool supportsNewScanlineDecoding = false) {
Nigel Tao9b9453e2018-08-01 09:59:38 +1000284 // If we're testing incomplete decodes, let's run the same test on full decodes.
285 if (supportsIncomplete) {
286 check(r, path, size, supportsScanlineDecoding, supportsSubsetDecoding, false,
287 supportsNewScanlineDecoding);
288 }
msarettcc7f3052015-10-05 14:20:27 -0700289
Ben Wagner145dbcd2016-11-03 14:40:50 -0400290 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700291 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700292 return;
293 }
msarette6dd0042015-10-09 11:07:34 -0700294
Ben Wagner145dbcd2016-11-03 14:40:50 -0400295 std::unique_ptr<SkCodec> codec(nullptr);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000296 if (supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700297 size_t size = stream->getLength();
Mike Reedede7bac2017-07-23 15:30:02 -0400298 codec = SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 2 * size / 3));
msarette6dd0042015-10-09 11:07:34 -0700299 } else {
Mike Reedede7bac2017-07-23 15:30:02 -0400300 codec = SkCodec::MakeFromStream(std::move(stream));
msarette6dd0042015-10-09 11:07:34 -0700301 }
msarettcc7f3052015-10-05 14:20:27 -0700302 if (!codec) {
303 ERRORF(r, "Unable to decode '%s'", path);
304 return;
305 }
306
307 // Test full image decodes with SkCodec
308 SkMD5::Digest codecDigest;
scroggoef0fed32016-02-18 05:59:25 -0800309 const SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
msarettcc7f3052015-10-05 14:20:27 -0700310 SkBitmap bm;
Nigel Tao9b9453e2018-08-01 09:59:38 +1000311 SkCodec::Result expectedResult =
312 supportsIncomplete ? SkCodec::kIncompleteInput : SkCodec::kSuccess;
scroggo7b5e5532016-02-04 06:14:24 -0800313 test_codec(r, codec.get(), bm, info, size, expectedResult, &codecDigest, nullptr);
scroggod1bc5742015-08-12 08:31:44 -0700314
315 // Scanline decoding follows.
scroggod8d68552016-06-06 11:26:17 -0700316
Nigel Tao9b9453e2018-08-01 09:59:38 +1000317 if (supportsNewScanlineDecoding && !supportsIncomplete) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400318 test_incremental_decode(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700319 // This is only supported by codecs that use incremental decoding to
320 // support subset decodes - png and jpeg (once SkJpegCodec is
321 // converted).
322 if (SkStrEndsWith(path, "png") || SkStrEndsWith(path, "PNG")) {
Ben Wagner145dbcd2016-11-03 14:40:50 -0400323 test_in_stripes(r, codec.get(), info, codecDigest);
scroggo19b91532016-10-24 09:03:26 -0700324 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700325 }
326
327 // Need to call startScanlineDecode() first.
328 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0) == 0);
329 REPORTER_ASSERT(r, !codec->skipScanlines(1));
scroggo46c57472015-09-30 08:57:13 -0700330 const SkCodec::Result startResult = codec->startScanlineDecode(info);
scroggo58421542015-04-01 11:25:20 -0700331 if (supportsScanlineDecoding) {
332 bm.eraseColor(SK_ColorYELLOW);
msarettc0e80c12015-07-01 06:50:35 -0700333
scroggo46c57472015-09-30 08:57:13 -0700334 REPORTER_ASSERT(r, startResult == SkCodec::kSuccess);
scroggo9b2cdbf42015-07-10 12:07:02 -0700335
scroggo58421542015-04-01 11:25:20 -0700336 for (int y = 0; y < info.height(); y++) {
msarette6dd0042015-10-09 11:07:34 -0700337 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000338 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700339 REPORTER_ASSERT(r, 1 == lines);
340 }
scroggo58421542015-04-01 11:25:20 -0700341 }
342 // verify that scanline decoding gives the same result.
scroggo46c57472015-09-30 08:57:13 -0700343 if (SkCodec::kTopDown_SkScanlineOrder == codec->getScanlineOrder()) {
msarettcc7f3052015-10-05 14:20:27 -0700344 compare_to_good_digest(r, codecDigest, bm);
msarett5406d6f2015-08-31 06:55:13 -0700345 }
scroggo46c57472015-09-30 08:57:13 -0700346
347 // Cannot continue to decode scanlines beyond the end
348 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700349 == 0);
scroggo46c57472015-09-30 08:57:13 -0700350
351 // Interrupting a scanline decode with a full decode starts from
352 // scratch
353 REPORTER_ASSERT(r, codec->startScanlineDecode(info) == SkCodec::kSuccess);
msarette6dd0042015-10-09 11:07:34 -0700354 const int lines = codec->getScanlines(bm.getAddr(0, 0), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000355 if (!supportsIncomplete) {
msarette6dd0042015-10-09 11:07:34 -0700356 REPORTER_ASSERT(r, lines == 1);
357 }
scroggo46c57472015-09-30 08:57:13 -0700358 REPORTER_ASSERT(r, codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes())
msarette6dd0042015-10-09 11:07:34 -0700359 == expectedResult);
scroggo46c57472015-09-30 08:57:13 -0700360 REPORTER_ASSERT(r, codec->getScanlines(bm.getAddr(0, 0), 1, 0)
msarette6dd0042015-10-09 11:07:34 -0700361 == 0);
scroggo46c57472015-09-30 08:57:13 -0700362 REPORTER_ASSERT(r, codec->skipScanlines(1)
msarette6dd0042015-10-09 11:07:34 -0700363 == 0);
msarett80803ff2015-10-16 10:54:12 -0700364
365 // Test partial scanline decodes
scroggobed1ed62016-02-11 10:24:55 -0800366 if (supports_partial_scanlines(path) && info.width() >= 3) {
msarett80803ff2015-10-16 10:54:12 -0700367 SkCodec::Options options;
368 int width = info.width();
369 int height = info.height();
370 SkIRect subset = SkIRect::MakeXYWH(2 * (width / 3), 0, width / 3, height);
371 options.fSubset = &subset;
372
Leon Scroggins571b30f2017-07-11 17:35:31 +0000373 const auto partialStartResult = codec->startScanlineDecode(info, &options);
msarett80803ff2015-10-16 10:54:12 -0700374 REPORTER_ASSERT(r, partialStartResult == SkCodec::kSuccess);
375
376 for (int y = 0; y < height; y++) {
377 const int lines = codec->getScanlines(bm.getAddr(0, y), 1, 0);
Nigel Tao9b9453e2018-08-01 09:59:38 +1000378 if (!supportsIncomplete) {
msarett80803ff2015-10-16 10:54:12 -0700379 REPORTER_ASSERT(r, 1 == lines);
380 }
381 }
382 }
scroggo58421542015-04-01 11:25:20 -0700383 } else {
scroggo46c57472015-09-30 08:57:13 -0700384 REPORTER_ASSERT(r, startResult == SkCodec::kUnimplemented);
halcanarya096d7a2015-03-27 12:16:53 -0700385 }
scroggob636b452015-07-22 07:16:20 -0700386
387 // The rest of this function tests decoding subsets, and will decode an arbitrary number of
388 // random subsets.
389 // Do not attempt to decode subsets of an image of only once pixel, since there is no
390 // meaningful subset.
391 if (size.width() * size.height() == 1) {
392 return;
393 }
394
395 SkRandom rand;
396 SkIRect subset;
397 SkCodec::Options opts;
398 opts.fSubset = &subset;
399 for (int i = 0; i < 5; i++) {
400 subset = generate_random_subset(&rand, size.width(), size.height());
401 SkASSERT(!subset.isEmpty());
402 const bool supported = codec->getValidSubset(&subset);
403 REPORTER_ASSERT(r, supported == supportsSubsetDecoding);
404
405 SkImageInfo subsetInfo = info.makeWH(subset.width(), subset.height());
406 SkBitmap bm;
407 bm.allocPixels(subsetInfo);
Leon Scroggins571b30f2017-07-11 17:35:31 +0000408 const auto result = codec->getPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &opts);
scroggob636b452015-07-22 07:16:20 -0700409
410 if (supportsSubsetDecoding) {
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500411 if (expectedResult == SkCodec::kSuccess) {
412 REPORTER_ASSERT(r, result == expectedResult);
Leon Scroggins III58f100c2016-12-20 09:49:25 -0500413 }
scroggob636b452015-07-22 07:16:20 -0700414 // Webp is the only codec that supports subsets, and it will have modified the subset
415 // to have even left/top.
416 REPORTER_ASSERT(r, SkIsAlign2(subset.fLeft) && SkIsAlign2(subset.fTop));
417 } else {
418 // No subsets will work.
419 REPORTER_ASSERT(r, result == SkCodec::kUnimplemented);
420 }
421 }
msarettcc7f3052015-10-05 14:20:27 -0700422
scroggobed1ed62016-02-11 10:24:55 -0800423 // SkAndroidCodec tests
scroggo8e6c7ad2016-09-16 08:20:38 -0700424 if (supportsScanlineDecoding || supportsSubsetDecoding || supportsNewScanlineDecoding) {
scroggo2c3b2182015-10-09 08:40:59 -0700425
Ben Wagner145dbcd2016-11-03 14:40:50 -0400426 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarettcc7f3052015-10-05 14:20:27 -0700427 if (!stream) {
msarettcc7f3052015-10-05 14:20:27 -0700428 return;
429 }
msarette6dd0042015-10-09 11:07:34 -0700430
Leon Scroggins III7397d7a2018-01-04 13:26:30 -0500431 auto androidCodec = SkAndroidCodec::MakeFromCodec(std::move(codec));
scroggo7b5e5532016-02-04 06:14:24 -0800432 if (!androidCodec) {
msarettcc7f3052015-10-05 14:20:27 -0700433 ERRORF(r, "Unable to decode '%s'", path);
434 return;
435 }
436
437 SkBitmap bm;
scroggobed1ed62016-02-11 10:24:55 -0800438 SkMD5::Digest androidCodecDigest;
439 test_codec(r, androidCodec.get(), bm, info, size, expectedResult, &androidCodecDigest,
scroggo7b5e5532016-02-04 06:14:24 -0800440 &codecDigest);
msarette6dd0042015-10-09 11:07:34 -0700441 }
442
Nigel Tao9b9453e2018-08-01 09:59:38 +1000443 if (!supportsIncomplete) {
scroggoef0fed32016-02-18 05:59:25 -0800444 // Test SkCodecImageGenerator
Ben Wagner145dbcd2016-11-03 14:40:50 -0400445 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
446 sk_sp<SkData> fullData(SkData::MakeFromStream(stream.get(), stream->getLength()));
447 std::unique_ptr<SkImageGenerator> gen(
Mike Reed185130c2017-02-15 15:14:16 -0500448 SkCodecImageGenerator::MakeFromEncodedCodec(fullData));
msarettedd2dcf2016-01-14 13:12:26 -0800449 SkBitmap bm;
450 bm.allocPixels(info);
msarettedd2dcf2016-01-14 13:12:26 -0800451 REPORTER_ASSERT(r, gen->getPixels(info, bm.getPixels(), bm.rowBytes()));
452 compare_to_good_digest(r, codecDigest, bm);
scroggoef0fed32016-02-18 05:59:25 -0800453
scroggo8e6c7ad2016-09-16 08:20:38 -0700454#ifndef SK_PNG_DISABLE_TESTS
scroggod8d68552016-06-06 11:26:17 -0700455 // Test using SkFrontBufferedStream, as Android does
Mike Reed98c5d922017-09-15 21:39:47 -0400456 auto bufferedStream = SkFrontBufferedStream::Make(
457 SkMemoryStream::Make(std::move(fullData)), SkCodec::MinBufferedBytesNeeded());
scroggod8d68552016-06-06 11:26:17 -0700458 REPORTER_ASSERT(r, bufferedStream);
Mike Reed98c5d922017-09-15 21:39:47 -0400459 codec = SkCodec::MakeFromStream(std::move(bufferedStream));
scroggod8d68552016-06-06 11:26:17 -0700460 REPORTER_ASSERT(r, codec);
461 if (codec) {
462 test_info(r, codec.get(), info, SkCodec::kSuccess, &codecDigest);
scroggoef0fed32016-02-18 05:59:25 -0800463 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700464#endif
msarettedd2dcf2016-01-14 13:12:26 -0800465 }
halcanarya096d7a2015-03-27 12:16:53 -0700466}
467
Leon Scroggins III83926342016-12-06 10:58:02 -0500468DEF_TEST(Codec_wbmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500469 check(r, "images/mandrill.wbmp", SkISize::Make(512, 512), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500470}
halcanarya096d7a2015-03-27 12:16:53 -0700471
Leon Scroggins III83926342016-12-06 10:58:02 -0500472DEF_TEST(Codec_webp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500473 check(r, "images/baby_tux.webp", SkISize::Make(386, 395), false, true, true);
474 check(r, "images/color_wheel.webp", SkISize::Make(128, 128), false, true, true);
475 check(r, "images/yellow_rose.webp", SkISize::Make(400, 301), false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500476}
scroggo6f5e6192015-06-18 12:53:43 -0700477
Leon Scroggins III83926342016-12-06 10:58:02 -0500478DEF_TEST(Codec_bmp, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500479 check(r, "images/randPixels.bmp", SkISize::Make(8, 8), true, false, true);
480 check(r, "images/rle.bmp", SkISize::Make(320, 240), true, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500481}
halcanarya096d7a2015-03-27 12:16:53 -0700482
Leon Scroggins III83926342016-12-06 10:58:02 -0500483DEF_TEST(Codec_ico, r) {
msarette6dd0042015-10-09 11:07:34 -0700484 // FIXME: We are not ready to test incomplete ICOs
msarett68b204e2015-04-01 12:09:21 -0700485 // These two tests examine interestingly different behavior:
486 // Decodes an embedded BMP image
Hal Canaryc465d132017-12-08 10:21:31 -0500487 check(r, "images/color_wheel.ico", SkISize::Make(128, 128), true, false, false);
msarett68b204e2015-04-01 12:09:21 -0700488 // Decodes an embedded PNG image
Hal Canaryc465d132017-12-08 10:21:31 -0500489 check(r, "images/google_chrome.ico", SkISize::Make(256, 256), false, false, 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_gif, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500493 check(r, "images/box.gif", SkISize::Make(200, 55), false, false, true, true);
494 check(r, "images/color_wheel.gif", SkISize::Make(128, 128), false, false, true, true);
msarette6dd0042015-10-09 11:07:34 -0700495 // randPixels.gif is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500496 check(r, "images/randPixels.gif", SkISize::Make(8, 8), false, false, false, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500497}
msarett438b2ad2015-04-09 12:43:10 -0700498
Leon Scroggins III83926342016-12-06 10:58:02 -0500499DEF_TEST(Codec_jpg, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500500 check(r, "images/CMYK.jpg", SkISize::Make(642, 516), true, false, true);
501 check(r, "images/color_wheel.jpg", SkISize::Make(128, 128), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700502 // grayscale.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500503 check(r, "images/grayscale.jpg", SkISize::Make(128, 128), true, false, false);
504 check(r, "images/mandrill_512_q075.jpg", SkISize::Make(512, 512), true, false, true);
msarette6dd0042015-10-09 11:07:34 -0700505 // randPixels.jpg is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500506 check(r, "images/randPixels.jpg", SkISize::Make(8, 8), true, false, false);
Leon Scroggins III83926342016-12-06 10:58:02 -0500507}
msarette16b04a2015-04-15 07:32:19 -0700508
Leon Scroggins III83926342016-12-06 10:58:02 -0500509DEF_TEST(Codec_png, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500510 check(r, "images/arrow.png", SkISize::Make(187, 312), false, false, true, true);
511 check(r, "images/baby_tux.png", SkISize::Make(240, 246), false, false, true, true);
512 check(r, "images/color_wheel.png", SkISize::Make(128, 128), false, false, true, true);
scroggo8e6c7ad2016-09-16 08:20:38 -0700513 // half-transparent-white-pixel.png is too small to test incomplete
Hal Canaryc465d132017-12-08 10:21:31 -0500514 check(r, "images/half-transparent-white-pixel.png", SkISize::Make(1, 1), false, false, false, true);
515 check(r, "images/mandrill_128.png", SkISize::Make(128, 128), false, false, true, true);
Brian Osmanccb21bf2018-07-09 14:57:48 -0400516 // mandrill_16.png is too small (relative to embedded sRGB profile) to test incomplete
517 check(r, "images/mandrill_16.png", SkISize::Make(16, 16), false, false, false, true);
Hal Canaryc465d132017-12-08 10:21:31 -0500518 check(r, "images/mandrill_256.png", SkISize::Make(256, 256), false, false, true, true);
519 check(r, "images/mandrill_32.png", SkISize::Make(32, 32), false, false, true, true);
520 check(r, "images/mandrill_512.png", SkISize::Make(512, 512), false, false, true, true);
521 check(r, "images/mandrill_64.png", SkISize::Make(64, 64), false, false, true, true);
522 check(r, "images/plane.png", SkISize::Make(250, 126), false, false, true, true);
523 check(r, "images/plane_interlaced.png", SkISize::Make(250, 126), false, false, true, true);
524 check(r, "images/randPixels.png", SkISize::Make(8, 8), false, false, true, true);
525 check(r, "images/yellow_rose.png", SkISize::Make(400, 301), false, false, true, true);
Leon Scroggins III83926342016-12-06 10:58:02 -0500526}
yujieqin916de9f2016-01-25 08:26:16 -0800527
yujieqinf236ee42016-02-29 07:14:42 -0800528// Disable RAW tests for Win32.
529#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Leon Scroggins III83926342016-12-06 10:58:02 -0500530DEF_TEST(Codec_raw, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500531 check(r, "images/sample_1mp.dng", SkISize::Make(600, 338), false, false, false);
532 check(r, "images/sample_1mp_rotated.dng", SkISize::Make(600, 338), false, false, false);
533 check(r, "images/dng_with_preview.dng", SkISize::Make(600, 338), true, false, false);
halcanarya096d7a2015-03-27 12:16:53 -0700534}
Leon Scroggins III83926342016-12-06 10:58:02 -0500535#endif
scroggo0a7e69c2015-04-03 07:22:22 -0700536
537static void test_invalid_stream(skiatest::Reporter* r, const void* stream, size_t len) {
scroggo2c3b2182015-10-09 08:40:59 -0700538 // Neither of these calls should return a codec. Bots should catch us if we leaked anything.
Mike Reedede7bac2017-07-23 15:30:02 -0400539 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(
540 skstd::make_unique<SkMemoryStream>(stream, len, false)));
541 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(
542 skstd::make_unique<SkMemoryStream>(stream, len, false)));
scroggo0a7e69c2015-04-03 07:22:22 -0700543}
544
545// Ensure that SkCodec::NewFromStream handles freeing the passed in SkStream,
546// even on failure. Test some bad streams.
547DEF_TEST(Codec_leaks, r) {
548 // No codec should claim this as their format, so this tests SkCodec::NewFromStream.
549 const char nonSupportedStream[] = "hello world";
550 // The other strings should look like the beginning of a file type, so we'll call some
551 // internal version of NewFromStream, which must also delete the stream on failure.
552 const unsigned char emptyPng[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
553 const unsigned char emptyJpeg[] = { 0xFF, 0xD8, 0xFF };
554 const char emptyWebp[] = "RIFF1234WEBPVP";
555 const char emptyBmp[] = { 'B', 'M' };
556 const char emptyIco[] = { '\x00', '\x00', '\x01', '\x00' };
557 const char emptyGif[] = "GIFVER";
558
559 test_invalid_stream(r, nonSupportedStream, sizeof(nonSupportedStream));
560 test_invalid_stream(r, emptyPng, sizeof(emptyPng));
561 test_invalid_stream(r, emptyJpeg, sizeof(emptyJpeg));
562 test_invalid_stream(r, emptyWebp, sizeof(emptyWebp));
563 test_invalid_stream(r, emptyBmp, sizeof(emptyBmp));
564 test_invalid_stream(r, emptyIco, sizeof(emptyIco));
565 test_invalid_stream(r, emptyGif, sizeof(emptyGif));
566}
msarette16b04a2015-04-15 07:32:19 -0700567
scroggo2c3b2182015-10-09 08:40:59 -0700568DEF_TEST(Codec_null, r) {
scroggobed1ed62016-02-11 10:24:55 -0800569 // Attempting to create an SkCodec or an SkAndroidCodec with null should not
scroggo2c3b2182015-10-09 08:40:59 -0700570 // crash.
Mike Reedede7bac2017-07-23 15:30:02 -0400571 REPORTER_ASSERT(r, !SkCodec::MakeFromStream(nullptr));
572 REPORTER_ASSERT(r, !SkAndroidCodec::MakeFromStream(nullptr));
scroggo2c3b2182015-10-09 08:40:59 -0700573}
574
msarette16b04a2015-04-15 07:32:19 -0700575static void test_dimensions(skiatest::Reporter* r, const char path[]) {
576 // Create the codec from the resource file
Ben Wagner145dbcd2016-11-03 14:40:50 -0400577 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
msarette16b04a2015-04-15 07:32:19 -0700578 if (!stream) {
msarette16b04a2015-04-15 07:32:19 -0700579 return;
580 }
Mike Reedede7bac2017-07-23 15:30:02 -0400581 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
msarette16b04a2015-04-15 07:32:19 -0700582 if (!codec) {
583 ERRORF(r, "Unable to create codec '%s'", path);
584 return;
585 }
586
587 // Check that the decode is successful for a variety of scales
scroggo501b7342015-11-03 07:55:11 -0800588 for (int sampleSize = 1; sampleSize < 32; sampleSize++) {
msarette16b04a2015-04-15 07:32:19 -0700589 // Scale the output dimensions
msarett3d9d7a72015-10-21 10:27:10 -0700590 SkISize scaledDims = codec->getSampledDimensions(sampleSize);
msarettb32758a2015-08-18 13:22:46 -0700591 SkImageInfo scaledInfo = codec->getInfo()
592 .makeWH(scaledDims.width(), scaledDims.height())
593 .makeColorType(kN32_SkColorType);
msarette16b04a2015-04-15 07:32:19 -0700594
595 // Set up for the decode
596 size_t rowBytes = scaledDims.width() * sizeof(SkPMColor);
Mike Reedf0ffb892017-10-03 14:47:21 -0400597 size_t totalBytes = scaledInfo.computeByteSize(rowBytes);
msarette16b04a2015-04-15 07:32:19 -0700598 SkAutoTMalloc<SkPMColor> pixels(totalBytes);
599
msarett3d9d7a72015-10-21 10:27:10 -0700600 SkAndroidCodec::AndroidOptions options;
601 options.fSampleSize = sampleSize;
scroggoeb602a52015-07-09 08:16:03 -0700602 SkCodec::Result result =
msarett3d9d7a72015-10-21 10:27:10 -0700603 codec->getAndroidPixels(scaledInfo, pixels.get(), rowBytes, &options);
scroggoeb602a52015-07-09 08:16:03 -0700604 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarette16b04a2015-04-15 07:32:19 -0700605 }
606}
607
608// Ensure that onGetScaledDimensions returns valid image dimensions to use for decodes
609DEF_TEST(Codec_Dimensions, r) {
610 // JPG
Hal Canaryc465d132017-12-08 10:21:31 -0500611 test_dimensions(r, "images/CMYK.jpg");
612 test_dimensions(r, "images/color_wheel.jpg");
613 test_dimensions(r, "images/grayscale.jpg");
614 test_dimensions(r, "images/mandrill_512_q075.jpg");
615 test_dimensions(r, "images/randPixels.jpg");
msarettb32758a2015-08-18 13:22:46 -0700616
617 // Decoding small images with very large scaling factors is a potential
618 // source of bugs and crashes. We disable these tests in Gold because
619 // tiny images are not very useful to look at.
620 // Here we make sure that we do not crash or access illegal memory when
621 // performing scaled decodes on small images.
Hal Canaryc465d132017-12-08 10:21:31 -0500622 test_dimensions(r, "images/1x1.png");
623 test_dimensions(r, "images/2x2.png");
624 test_dimensions(r, "images/3x3.png");
625 test_dimensions(r, "images/3x1.png");
626 test_dimensions(r, "images/1x1.png");
627 test_dimensions(r, "images/16x1.png");
628 test_dimensions(r, "images/1x16.png");
629 test_dimensions(r, "images/mandrill_16.png");
msarettb32758a2015-08-18 13:22:46 -0700630
yujieqin916de9f2016-01-25 08:26:16 -0800631 // RAW
yujieqinf236ee42016-02-29 07:14:42 -0800632// Disable RAW tests for Win32.
633#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
Hal Canaryc465d132017-12-08 10:21:31 -0500634 test_dimensions(r, "images/sample_1mp.dng");
635 test_dimensions(r, "images/sample_1mp_rotated.dng");
636 test_dimensions(r, "images/dng_with_preview.dng");
msarett8e49ca32016-01-25 13:10:58 -0800637#endif
msarette16b04a2015-04-15 07:32:19 -0700638}
639
msarettd0375bc2015-08-12 08:08:56 -0700640static void test_invalid(skiatest::Reporter* r, const char path[]) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500641 auto data = GetResourceAsData(path);
642 if (!data) {
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500643 ERRORF(r, "Failed to get resource %s", path);
msarett4b17fa32015-04-23 08:53:39 -0700644 return;
645 }
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500646
647 REPORTER_ASSERT(r, !SkCodec::MakeFromData(data));
msarett4b17fa32015-04-23 08:53:39 -0700648}
msarette16b04a2015-04-15 07:32:19 -0700649
msarett4b17fa32015-04-23 08:53:39 -0700650DEF_TEST(Codec_Empty, r) {
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500651 if (GetResourcePath().isEmpty()) {
652 return;
653 }
654
msarett4b17fa32015-04-23 08:53:39 -0700655 // Test images that should not be able to create a codec
msarettd0375bc2015-08-12 08:08:56 -0700656 test_invalid(r, "empty_images/zero-dims.gif");
657 test_invalid(r, "empty_images/zero-embedded.ico");
658 test_invalid(r, "empty_images/zero-width.bmp");
659 test_invalid(r, "empty_images/zero-height.bmp");
660 test_invalid(r, "empty_images/zero-width.jpg");
661 test_invalid(r, "empty_images/zero-height.jpg");
662 test_invalid(r, "empty_images/zero-width.png");
663 test_invalid(r, "empty_images/zero-height.png");
664 test_invalid(r, "empty_images/zero-width.wbmp");
665 test_invalid(r, "empty_images/zero-height.wbmp");
666 // This image is an ico with an embedded mask-bmp. This is illegal.
667 test_invalid(r, "invalid_images/mask-bmp-ico.ico");
Matt Sarett5c496172017-02-07 17:01:16 -0500668 // It is illegal for a webp frame to not be fully contained by the canvas.
669 test_invalid(r, "invalid_images/invalid-offset.webp");
Leon Scroggins IIId87fbee2016-12-02 16:47:53 -0500670#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
671 test_invalid(r, "empty_images/zero_height.tiff");
672#endif
Leon Scroggins IIIfc4ee222017-07-14 11:48:52 -0400673 test_invalid(r, "invalid_images/b37623797.ico");
Leon Scroggins IIIfee7cba2018-02-13 16:41:03 -0500674 test_invalid(r, "invalid_images/osfuzz6295.webp");
Leon Scroggins IIIce6d93a2018-02-15 09:25:11 -0500675 test_invalid(r, "invalid_images/osfuzz6288.bmp");
Leon Scroggins III31476b72018-02-22 16:09:33 -0500676 test_invalid(r, "invalid_images/ossfuzz6347");
msarett4b17fa32015-04-23 08:53:39 -0700677}
msarett99f567e2015-08-05 12:58:26 -0700678
scroggo8e6c7ad2016-09-16 08:20:38 -0700679#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
680
681#ifndef SK_PNG_DISABLE_TESTS // reading chunks does not work properly with older versions.
682 // It does not appear that anyone in Google3 is reading chunks.
683
scroggocf98fa92015-11-23 08:14:40 -0800684static void codex_test_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) {
685 SkWStream* sk_stream = (SkWStream*)png_get_io_ptr(png_ptr);
686 if (!sk_stream->write(data, len)) {
687 png_error(png_ptr, "sk_write_fn Error!");
688 }
689}
690
scroggocf98fa92015-11-23 08:14:40 -0800691DEF_TEST(Codec_pngChunkReader, r) {
692 // Create a dummy bitmap. Use unpremul RGBA for libpng.
693 SkBitmap bm;
694 const int w = 1;
695 const int h = 1;
696 const SkImageInfo bmInfo = SkImageInfo::Make(w, h, kRGBA_8888_SkColorType,
697 kUnpremul_SkAlphaType);
698 bm.setInfo(bmInfo);
699 bm.allocPixels();
700 bm.eraseColor(SK_ColorBLUE);
701 SkMD5::Digest goodDigest;
702 md5(bm, &goodDigest);
703
704 // Write to a png file.
705 png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
706 REPORTER_ASSERT(r, png);
707 if (!png) {
708 return;
709 }
710
711 png_infop info = png_create_info_struct(png);
712 REPORTER_ASSERT(r, info);
713 if (!info) {
714 png_destroy_write_struct(&png, nullptr);
715 return;
716 }
717
718 if (setjmp(png_jmpbuf(png))) {
719 ERRORF(r, "failed writing png");
720 png_destroy_write_struct(&png, &info);
721 return;
722 }
723
724 SkDynamicMemoryWStream wStream;
725 png_set_write_fn(png, (void*) (&wStream), codex_test_write_fn, nullptr);
726
727 png_set_IHDR(png, info, (png_uint_32)w, (png_uint_32)h, 8,
728 PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
729 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
730
731 // Create some chunks that match the Android framework's use.
732 static png_unknown_chunk gUnknowns[] = {
msarett133eaaa2016-01-07 11:03:25 -0800733 { "npOl", (png_byte*)"outline", sizeof("outline"), PNG_HAVE_IHDR },
734 { "npLb", (png_byte*)"layoutBounds", sizeof("layoutBounds"), PNG_HAVE_IHDR },
735 { "npTc", (png_byte*)"ninePatchData", sizeof("ninePatchData"), PNG_HAVE_IHDR },
scroggocf98fa92015-11-23 08:14:40 -0800736 };
737
738 png_set_keep_unknown_chunks(png, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"npOl\0npLb\0npTc\0", 3);
739 png_set_unknown_chunks(png, info, gUnknowns, SK_ARRAY_COUNT(gUnknowns));
740#if PNG_LIBPNG_VER < 10600
741 /* Deal with unknown chunk location bug in 1.5.x and earlier */
msarett133eaaa2016-01-07 11:03:25 -0800742 png_set_unknown_chunk_location(png, info, 0, PNG_HAVE_IHDR);
743 png_set_unknown_chunk_location(png, info, 1, PNG_HAVE_IHDR);
scroggocf98fa92015-11-23 08:14:40 -0800744#endif
745
746 png_write_info(png, info);
747
748 for (int j = 0; j < h; j++) {
749 png_bytep row = (png_bytep)(bm.getAddr(0, j));
750 png_write_rows(png, &row, 1);
751 }
752 png_write_end(png, info);
753 png_destroy_write_struct(&png, &info);
754
755 class ChunkReader : public SkPngChunkReader {
756 public:
757 ChunkReader(skiatest::Reporter* r)
758 : fReporter(r)
759 {
760 this->reset();
761 }
762
763 bool readChunk(const char tag[], const void* data, size_t length) override {
764 for (size_t i = 0; i < SK_ARRAY_COUNT(gUnknowns); ++i) {
765 if (!strcmp(tag, (const char*) gUnknowns[i].name)) {
766 // Tag matches. This should have been the first time we see it.
767 REPORTER_ASSERT(fReporter, !fSeen[i]);
768 fSeen[i] = true;
769
770 // Data and length should match
771 REPORTER_ASSERT(fReporter, length == gUnknowns[i].size);
772 REPORTER_ASSERT(fReporter, !strcmp((const char*) data,
773 (const char*) gUnknowns[i].data));
774 return true;
775 }
776 }
777 ERRORF(fReporter, "Saw an unexpected unknown chunk.");
778 return true;
779 }
780
781 bool allHaveBeenSeen() {
782 bool ret = true;
783 for (auto seen : fSeen) {
784 ret &= seen;
785 }
786 return ret;
787 }
788
789 void reset() {
790 sk_bzero(fSeen, sizeof(fSeen));
791 }
792
793 private:
794 skiatest::Reporter* fReporter; // Unowned
795 bool fSeen[3];
796 };
797
798 ChunkReader chunkReader(r);
799
800 // Now read the file with SkCodec.
Mike Reedede7bac2017-07-23 15:30:02 -0400801 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(wStream.detachAsData(), &chunkReader));
scroggocf98fa92015-11-23 08:14:40 -0800802 REPORTER_ASSERT(r, codec);
803 if (!codec) {
804 return;
805 }
806
807 // Now compare to the original.
808 SkBitmap decodedBm;
809 decodedBm.setInfo(codec->getInfo());
810 decodedBm.allocPixels();
811 SkCodec::Result result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(),
812 decodedBm.rowBytes());
813 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
814
815 if (decodedBm.colorType() != bm.colorType()) {
816 SkBitmap tmp;
Matt Sarett68b8e3d2017-04-28 11:15:22 -0400817 bool success = sk_tool_utils::copy_to(&tmp, bm.colorType(), decodedBm);
scroggocf98fa92015-11-23 08:14:40 -0800818 REPORTER_ASSERT(r, success);
819 if (!success) {
820 return;
821 }
822
823 tmp.swap(decodedBm);
824 }
825
826 compare_to_good_digest(r, goodDigest, decodedBm);
827 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
828
829 // Decoding again will read the chunks again.
830 chunkReader.reset();
831 REPORTER_ASSERT(r, !chunkReader.allHaveBeenSeen());
832 result = codec->getPixels(codec->getInfo(), decodedBm.getPixels(), decodedBm.rowBytes());
833 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
834 REPORTER_ASSERT(r, chunkReader.allHaveBeenSeen());
835}
scroggo8e6c7ad2016-09-16 08:20:38 -0700836#endif // SK_PNG_DISABLE_TESTS
scroggocf98fa92015-11-23 08:14:40 -0800837#endif // PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
scroggob9a1e342015-11-30 06:25:31 -0800838
scroggodb30be22015-12-08 18:54:13 -0800839// Stream that can only peek up to a limit
840class LimitedPeekingMemStream : public SkStream {
841public:
reed42943c82016-09-12 12:01:44 -0700842 LimitedPeekingMemStream(sk_sp<SkData> data, size_t limit)
843 : fStream(std::move(data))
scroggodb30be22015-12-08 18:54:13 -0800844 , fLimit(limit) {}
845
846 size_t peek(void* buf, size_t bytes) const override {
847 return fStream.peek(buf, SkTMin(bytes, fLimit));
848 }
849 size_t read(void* buf, size_t bytes) override {
850 return fStream.read(buf, bytes);
851 }
852 bool rewind() override {
853 return fStream.rewind();
854 }
855 bool isAtEnd() const override {
msarettff2a6c82016-09-07 11:23:28 -0700856 return fStream.isAtEnd();
scroggodb30be22015-12-08 18:54:13 -0800857 }
858private:
859 SkMemoryStream fStream;
860 const size_t fLimit;
861};
862
yujieqinf236ee42016-02-29 07:14:42 -0800863// Disable RAW tests for Win32.
864#if defined(SK_CODEC_DECODES_RAW) && (!defined(_WIN32))
yujieqin9c7a8a42016-02-05 08:21:19 -0800865// Test that the RawCodec works also for not asset stream. This will test the code path using
866// SkRawBufferedStream instead of SkRawAssetStream.
yujieqin9c7a8a42016-02-05 08:21:19 -0800867DEF_TEST(Codec_raw_notseekable, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000868 constexpr char path[] = "images/dng_with_preview.dng";
869 sk_sp<SkData> data(GetResourceAsData(path));
yujieqin9c7a8a42016-02-05 08:21:19 -0800870 if (!data) {
871 SkDebugf("Missing resource '%s'\n", path);
872 return;
873 }
874
Mike Reedede7bac2017-07-23 15:30:02 -0400875 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
876 skstd::make_unique<NotAssetMemStream>(std::move(data))));
yujieqin9c7a8a42016-02-05 08:21:19 -0800877 REPORTER_ASSERT(r, codec);
878
879 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
880}
881#endif
882
scroggodb30be22015-12-08 18:54:13 -0800883// Test that even if webp_parse_header fails to peek enough, it will fall back to read()
884// + rewind() and succeed.
885DEF_TEST(Codec_webp_peek, r) {
Mike Reed0933bc92017-12-09 01:27:41 +0000886 constexpr char path[] = "images/baby_tux.webp";
887 auto data = GetResourceAsData(path);
scroggodb30be22015-12-08 18:54:13 -0800888 if (!data) {
889 SkDebugf("Missing resource '%s'\n", path);
890 return;
891 }
892
893 // The limit is less than webp needs to peek or read.
Mike Reedede7bac2017-07-23 15:30:02 -0400894 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(
895 skstd::make_unique<LimitedPeekingMemStream>(data, 25)));
scroggodb30be22015-12-08 18:54:13 -0800896 REPORTER_ASSERT(r, codec);
897
scroggo7b5e5532016-02-04 06:14:24 -0800898 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800899
900 // Similarly, a stream which does not peek should still succeed.
Mike Reedede7bac2017-07-23 15:30:02 -0400901 codec = SkCodec::MakeFromStream(skstd::make_unique<LimitedPeekingMemStream>(data, 0));
scroggodb30be22015-12-08 18:54:13 -0800902 REPORTER_ASSERT(r, codec);
903
scroggo7b5e5532016-02-04 06:14:24 -0800904 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggodb30be22015-12-08 18:54:13 -0800905}
906
msarett7f7ec202016-03-01 12:12:27 -0800907// SkCodec's wbmp decoder was initially unnecessarily restrictive.
908// It required the second byte to be zero. The wbmp specification allows
909// a couple of bits to be 1 (so long as they do not overlap with 0x9F).
910// Test that SkCodec now supports an image with these bits set.
Leon Scroggins III83926342016-12-06 10:58:02 -0500911DEF_TEST(Codec_wbmp_restrictive, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500912 const char* path = "images/mandrill.wbmp";
Ben Wagner145dbcd2016-11-03 14:40:50 -0400913 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
scroggob9a1e342015-11-30 06:25:31 -0800914 if (!stream) {
scroggob9a1e342015-11-30 06:25:31 -0800915 return;
916 }
917
918 // Modify the stream to contain a second byte with some bits set.
Ben Wagner145dbcd2016-11-03 14:40:50 -0400919 auto data = SkCopyStreamToData(stream.get());
scroggob9a1e342015-11-30 06:25:31 -0800920 uint8_t* writeableData = static_cast<uint8_t*>(data->writable_data());
921 writeableData[1] = static_cast<uint8_t>(~0x9F);
922
msarett7f7ec202016-03-01 12:12:27 -0800923 // SkCodec should support this.
Mike Reedede7bac2017-07-23 15:30:02 -0400924 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
scroggob9a1e342015-11-30 06:25:31 -0800925 REPORTER_ASSERT(r, codec);
926 if (!codec) {
927 return;
928 }
scroggo7b5e5532016-02-04 06:14:24 -0800929 test_info(r, codec.get(), codec->getInfo(), SkCodec::kSuccess, nullptr);
scroggob9a1e342015-11-30 06:25:31 -0800930}
scroggodb30be22015-12-08 18:54:13 -0800931
932// wbmp images have a header that can be arbitrarily large, depending on the
933// size of the image. We cap the size at 65535, meaning we only need to look at
934// 8 bytes to determine whether we can read the image. This is important
Leon Scroggins III04be2b52017-08-17 15:13:20 -0400935// because SkCodec only passes a limited number of bytes to SkWbmpCodec to
936// determine whether the image is a wbmp.
scroggodb30be22015-12-08 18:54:13 -0800937DEF_TEST(Codec_wbmp_max_size, r) {
938 const unsigned char maxSizeWbmp[] = { 0x00, 0x00, // Header
939 0x83, 0xFF, 0x7F, // W: 65535
940 0x83, 0xFF, 0x7F }; // H: 65535
Ben Wagner145dbcd2016-11-03 14:40:50 -0400941 std::unique_ptr<SkStream> stream(new SkMemoryStream(maxSizeWbmp, sizeof(maxSizeWbmp), false));
Mike Reedede7bac2017-07-23 15:30:02 -0400942 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggodb30be22015-12-08 18:54:13 -0800943
944 REPORTER_ASSERT(r, codec);
945 if (!codec) return;
946
947 REPORTER_ASSERT(r, codec->getInfo().width() == 65535);
948 REPORTER_ASSERT(r, codec->getInfo().height() == 65535);
949
950 // Now test an image which is too big. Any image with a larger header (i.e.
951 // has bigger width/height) is also too big.
952 const unsigned char tooBigWbmp[] = { 0x00, 0x00, // Header
953 0x84, 0x80, 0x00, // W: 65536
954 0x84, 0x80, 0x00 }; // H: 65536
955 stream.reset(new SkMemoryStream(tooBigWbmp, sizeof(tooBigWbmp), false));
Mike Reedede7bac2017-07-23 15:30:02 -0400956 codec = SkCodec::MakeFromStream(std::move(stream));
scroggodb30be22015-12-08 18:54:13 -0800957
958 REPORTER_ASSERT(r, !codec);
959}
msarett2812f032016-07-18 15:56:08 -0700960
961DEF_TEST(Codec_jpeg_rewind, r) {
Hal Canaryc465d132017-12-08 10:21:31 -0500962 const char* path = "images/mandrill_512_q075.jpg";
Leon Scroggins III42886572017-01-27 13:16:28 -0500963 sk_sp<SkData> data(GetResourceAsData(path));
964 if (!data) {
msarett2812f032016-07-18 15:56:08 -0700965 return;
966 }
Leon Scroggins III42886572017-01-27 13:16:28 -0500967
968 data = SkData::MakeSubset(data.get(), 0, data->size() / 2);
Mike Reedede7bac2017-07-23 15:30:02 -0400969 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromData(data));
msarett2812f032016-07-18 15:56:08 -0700970 if (!codec) {
971 ERRORF(r, "Unable to create codec '%s'.", path);
972 return;
973 }
974
975 const int width = codec->getInfo().width();
976 const int height = codec->getInfo().height();
977 size_t rowBytes = sizeof(SkPMColor) * width;
978 SkAutoMalloc pixelStorage(height * rowBytes);
979
980 // Perform a sampled decode.
981 SkAndroidCodec::AndroidOptions opts;
982 opts.fSampleSize = 12;
Leon Scroggins III42886572017-01-27 13:16:28 -0500983 auto sampledInfo = codec->getInfo().makeWH(width / 12, height / 12);
984 auto result = codec->getAndroidPixels(sampledInfo, pixelStorage.get(), rowBytes, &opts);
985 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -0700986
987 // Rewind the codec and perform a full image decode.
Matt Sarett74b16ed2017-01-25 11:58:11 -0500988 result = codec->getPixels(codec->getInfo(), pixelStorage.get(), rowBytes);
Leon Scroggins III42886572017-01-27 13:16:28 -0500989 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
Matt Sarett74b16ed2017-01-25 11:58:11 -0500990
991 // Now perform a subset decode.
992 {
993 opts.fSampleSize = 1;
994 SkIRect subset = SkIRect::MakeWH(100, 100);
995 opts.fSubset = &subset;
996 result = codec->getAndroidPixels(codec->getInfo().makeWH(100, 100), pixelStorage.get(),
997 rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -0500998 // Though we only have half the data, it is enough to decode this subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -0500999 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1000 }
1001
1002 // Perform another full image decode. ASAN will detect if we look at the subset when it is
1003 // out of scope. This would happen if we depend on the old state in the codec.
Leon Scroggins III42886572017-01-27 13:16:28 -05001004 // This tests two layers of bugs: both SkJpegCodec::readRows and SkCodec::fillIncompleteImage
1005 // used to look at the old subset.
Matt Sarett74b16ed2017-01-25 11:58:11 -05001006 opts.fSubset = nullptr;
1007 result = codec->getAndroidPixels(codec->getInfo(), pixelStorage.get(), rowBytes, &opts);
Leon Scroggins III42886572017-01-27 13:16:28 -05001008 REPORTER_ASSERT(r, SkCodec::kIncompleteInput == result);
msarett2812f032016-07-18 15:56:08 -07001009}
msarett549ca322016-08-17 08:54:08 -07001010
msarett35bb74b2016-08-22 07:41:28 -07001011static void check_color_xform(skiatest::Reporter* r, const char* path) {
Mike Reedede7bac2017-07-23 15:30:02 -04001012 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(GetResourceAsStream(path)));
msarett35bb74b2016-08-22 07:41:28 -07001013
1014 SkAndroidCodec::AndroidOptions opts;
1015 opts.fSampleSize = 3;
1016 const int subsetWidth = codec->getInfo().width() / 2;
1017 const int subsetHeight = codec->getInfo().height() / 2;
1018 SkIRect subset = SkIRect::MakeWH(subsetWidth, subsetHeight);
1019 opts.fSubset = &subset;
1020
1021 const int dstWidth = subsetWidth / opts.fSampleSize;
1022 const int dstHeight = subsetHeight / opts.fSampleSize;
Brian Osman499afea2018-05-23 13:12:18 -04001023 auto colorSpace = SkColorSpace::MakeRGB(g2Dot2_TransferFn, SkColorSpace::kAdobeRGB_Gamut);
msarett35bb74b2016-08-22 07:41:28 -07001024 SkImageInfo dstInfo = codec->getInfo().makeWH(dstWidth, dstHeight)
1025 .makeColorType(kN32_SkColorType)
1026 .makeColorSpace(colorSpace);
1027
1028 size_t rowBytes = dstInfo.minRowBytes();
Mike Reedf0ffb892017-10-03 14:47:21 -04001029 SkAutoMalloc pixelStorage(dstInfo.computeByteSize(rowBytes));
msarett35bb74b2016-08-22 07:41:28 -07001030 SkCodec::Result result = codec->getAndroidPixels(dstInfo, pixelStorage.get(), rowBytes, &opts);
1031 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1032}
1033
1034DEF_TEST(Codec_ColorXform, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001035 check_color_xform(r, "images/mandrill_512_q075.jpg");
1036 check_color_xform(r, "images/mandrill_512.png");
msarett35bb74b2016-08-22 07:41:28 -07001037}
1038
msarettf17b71f2016-09-12 14:30:03 -07001039static bool color_type_match(SkColorType origColorType, SkColorType codecColorType) {
1040 switch (origColorType) {
1041 case kRGBA_8888_SkColorType:
1042 case kBGRA_8888_SkColorType:
1043 return kRGBA_8888_SkColorType == codecColorType ||
1044 kBGRA_8888_SkColorType == codecColorType;
1045 default:
1046 return origColorType == codecColorType;
1047 }
1048}
1049
1050static bool alpha_type_match(SkAlphaType origAlphaType, SkAlphaType codecAlphaType) {
1051 switch (origAlphaType) {
1052 case kUnpremul_SkAlphaType:
1053 case kPremul_SkAlphaType:
1054 return kUnpremul_SkAlphaType == codecAlphaType ||
1055 kPremul_SkAlphaType == codecAlphaType;
1056 default:
1057 return origAlphaType == codecAlphaType;
1058 }
1059}
1060
1061static void check_round_trip(skiatest::Reporter* r, SkCodec* origCodec, const SkImageInfo& info) {
1062 SkBitmap bm1;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001063 bm1.allocPixels(info);
1064 SkCodec::Result result = origCodec->getPixels(info, bm1.getPixels(), bm1.rowBytes());
msarettf17b71f2016-09-12 14:30:03 -07001065 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
msarett9b09cd82016-08-29 14:47:49 -07001066
1067 // Encode the image to png.
Leon Scroggins III0098ccb2018-09-24 15:24:31 -04001068 auto data = SkEncodeBitmap(bm1, SkEncodedImageFormat::kPNG, 100);
msarett9b09cd82016-08-29 14:47:49 -07001069
Mike Reedede7bac2017-07-23 15:30:02 -04001070 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(data));
msarettf17b71f2016-09-12 14:30:03 -07001071 REPORTER_ASSERT(r, color_type_match(info.colorType(), codec->getInfo().colorType()));
1072 REPORTER_ASSERT(r, alpha_type_match(info.alphaType(), codec->getInfo().alphaType()));
msarett9b09cd82016-08-29 14:47:49 -07001073
1074 SkBitmap bm2;
Leon Scroggins571b30f2017-07-11 17:35:31 +00001075 bm2.allocPixels(info);
1076 result = codec->getPixels(info, bm2.getPixels(), bm2.rowBytes());
msarett9b09cd82016-08-29 14:47:49 -07001077 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1078
1079 SkMD5::Digest d1, d2;
1080 md5(bm1, &d1);
1081 md5(bm2, &d2);
1082 REPORTER_ASSERT(r, d1 == d2);
1083}
1084
1085DEF_TEST(Codec_PngRoundTrip, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001086 auto codec = SkCodec::MakeFromStream(GetResourceAsStream("images/mandrill_512_q075.jpg"));
msarett549ca322016-08-17 08:54:08 -07001087
msarettf17b71f2016-09-12 14:30:03 -07001088 SkColorType colorTypesOpaque[] = {
1089 kRGB_565_SkColorType, kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1090 };
1091 for (SkColorType colorType : colorTypesOpaque) {
1092 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType);
1093 check_round_trip(r, codec.get(), newInfo);
1094 }
1095
Hal Canaryc465d132017-12-08 10:21:31 -05001096 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/grayscale.jpg"));
msarettf17b71f2016-09-12 14:30:03 -07001097 check_round_trip(r, codec.get(), codec->getInfo());
1098
Hal Canaryc465d132017-12-08 10:21:31 -05001099 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/yellow_rose.png"));
msarettf17b71f2016-09-12 14:30:03 -07001100
1101 SkColorType colorTypesWithAlpha[] = {
1102 kRGBA_8888_SkColorType, kBGRA_8888_SkColorType
1103 };
1104 SkAlphaType alphaTypes[] = {
1105 kUnpremul_SkAlphaType, kPremul_SkAlphaType
1106 };
1107 for (SkColorType colorType : colorTypesWithAlpha) {
1108 for (SkAlphaType alphaType : alphaTypes) {
1109 // Set color space to nullptr because color correct premultiplies do not round trip.
1110 SkImageInfo newInfo = codec->getInfo().makeColorType(colorType)
1111 .makeAlphaType(alphaType)
1112 .makeColorSpace(nullptr);
1113 check_round_trip(r, codec.get(), newInfo);
1114 }
1115 }
1116
Hal Canaryc465d132017-12-08 10:21:31 -05001117 codec = SkCodec::MakeFromStream(GetResourceAsStream("images/index8.png"));
msarettf17b71f2016-09-12 14:30:03 -07001118
1119 for (SkAlphaType alphaType : alphaTypes) {
1120 SkImageInfo newInfo = codec->getInfo().makeAlphaType(alphaType)
1121 .makeColorSpace(nullptr);
1122 check_round_trip(r, codec.get(), newInfo);
1123 }
msarett549ca322016-08-17 08:54:08 -07001124}
msarett2ecc35f2016-09-08 11:55:16 -07001125
1126static void test_conversion_possible(skiatest::Reporter* r, const char* path,
scroggo8e6c7ad2016-09-16 08:20:38 -07001127 bool supportsScanlineDecoder,
1128 bool supportsIncrementalDecoder) {
Ben Wagner145dbcd2016-11-03 14:40:50 -04001129 std::unique_ptr<SkStream> stream(GetResourceAsStream(path));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001130 if (!stream) {
1131 return;
1132 }
1133
Mike Reedede7bac2017-07-23 15:30:02 -04001134 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIc9942a12017-01-30 09:59:28 -05001135 if (!codec) {
1136 ERRORF(r, "failed to create a codec for %s", path);
1137 return;
1138 }
1139
msarett2ecc35f2016-09-08 11:55:16 -07001140 SkImageInfo infoF16 = codec->getInfo().makeColorType(kRGBA_F16_SkColorType);
1141
1142 SkBitmap bm;
1143 bm.allocPixels(infoF16);
1144 SkCodec::Result result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
Mike Kleince4cf722018-05-10 11:29:15 -04001145 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001146
1147 result = codec->startScanlineDecode(infoF16);
1148 if (supportsScanlineDecoder) {
Mike Kleince4cf722018-05-10 11:29:15 -04001149 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001150 } else {
Leon Scroggins III07418182017-08-15 12:24:02 -04001151 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result
Mike Kleince4cf722018-05-10 11:29:15 -04001152 || SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001153 }
1154
1155 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1156 if (supportsIncrementalDecoder) {
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);
msarett2ecc35f2016-09-08 11:55:16 -07001161 }
1162
Brian Osman36703d92017-12-12 14:09:31 -05001163 infoF16 = infoF16.makeColorSpace(infoF16.colorSpace()->makeLinearGamma());
msarett2ecc35f2016-09-08 11:55:16 -07001164 result = codec->getPixels(infoF16, bm.getPixels(), bm.rowBytes());
1165 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001166 result = codec->startScanlineDecode(infoF16);
1167 if (supportsScanlineDecoder) {
msarett2ecc35f2016-09-08 11:55:16 -07001168 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
scroggo8e6c7ad2016-09-16 08:20:38 -07001169 } else {
1170 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
1171 }
1172
1173 result = codec->startIncrementalDecode(infoF16, bm.getPixels(), bm.rowBytes());
1174 if (supportsIncrementalDecoder) {
1175 REPORTER_ASSERT(r, SkCodec::kSuccess == result);
1176 } else {
1177 REPORTER_ASSERT(r, SkCodec::kUnimplemented == result);
msarett2ecc35f2016-09-08 11:55:16 -07001178 }
1179}
1180
1181DEF_TEST(Codec_F16ConversionPossible, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001182 test_conversion_possible(r, "images/color_wheel.webp", false, false);
1183 test_conversion_possible(r, "images/mandrill_512_q075.jpg", true, false);
1184 test_conversion_possible(r, "images/yellow_rose.png", false, true);
scroggo8e6c7ad2016-09-16 08:20:38 -07001185}
1186
scroggo19b91532016-10-24 09:03:26 -07001187static void decode_frame(skiatest::Reporter* r, SkCodec* codec, size_t frame) {
1188 SkBitmap bm;
1189 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1190 bm.allocPixels(info);
1191
1192 SkCodec::Options opts;
1193 opts.fFrameIndex = frame;
1194 REPORTER_ASSERT(r, SkCodec::kSuccess == codec->getPixels(info,
Leon Scroggins571b30f2017-07-11 17:35:31 +00001195 bm.getPixels(), bm.rowBytes(), &opts));
scroggo19b91532016-10-24 09:03:26 -07001196}
1197
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001198// For an animated GIF, we should only read enough to decode frame 0 if the
1199// client never calls getFrameInfo and only decodes frame 0.
scroggo19b91532016-10-24 09:03:26 -07001200DEF_TEST(Codec_skipFullParse, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001201 auto path = "images/test640x479.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001202 auto streamObj = GetResourceAsStream(path);
1203 if (!streamObj) {
scroggo19b91532016-10-24 09:03:26 -07001204 return;
1205 }
Mike Reed71f867c2017-07-23 13:14:10 -04001206 SkStream* stream = streamObj.get();
scroggo19b91532016-10-24 09:03:26 -07001207
1208 // Note that we cheat and hold on to the stream pointer, but SkCodec will
1209 // take ownership. We will not refer to the stream after the SkCodec
1210 // deletes it.
Mike Reedede7bac2017-07-23 15:30:02 -04001211 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(streamObj)));
scroggo19b91532016-10-24 09:03:26 -07001212 if (!codec) {
1213 ERRORF(r, "Failed to create codec for %s", path);
1214 return;
1215 }
1216
1217 REPORTER_ASSERT(r, stream->hasPosition());
1218 const size_t sizePosition = stream->getPosition();
1219 REPORTER_ASSERT(r, stream->hasLength() && sizePosition < stream->getLength());
1220
1221 // This should read more of the stream, but not the whole stream.
1222 decode_frame(r, codec.get(), 0);
1223 const size_t positionAfterFirstFrame = stream->getPosition();
1224 REPORTER_ASSERT(r, positionAfterFirstFrame > sizePosition
1225 && positionAfterFirstFrame < stream->getLength());
1226
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001227 // There is more data in the stream.
scroggo19b91532016-10-24 09:03:26 -07001228 auto frameInfo = codec->getFrameInfo();
1229 REPORTER_ASSERT(r, frameInfo.size() == 4);
Leon Scroggins III1f6af6b2017-06-12 16:41:09 -04001230 REPORTER_ASSERT(r, stream->getPosition() > positionAfterFirstFrame);
scroggo19b91532016-10-24 09:03:26 -07001231}
1232
scroggo8e6c7ad2016-09-16 08:20:38 -07001233// Only rewinds up to a limit.
1234class LimitedRewindingStream : public SkStream {
1235public:
Mike Reed71f867c2017-07-23 13:14:10 -04001236 static std::unique_ptr<SkStream> Make(const char path[], size_t limit) {
1237 auto stream = GetResourceAsStream(path);
scroggo8e6c7ad2016-09-16 08:20:38 -07001238 if (!stream) {
1239 return nullptr;
1240 }
Mike Reed71f867c2017-07-23 13:14:10 -04001241 return std::unique_ptr<SkStream>(new LimitedRewindingStream(std::move(stream), limit));
scroggo8e6c7ad2016-09-16 08:20:38 -07001242 }
1243
1244 size_t read(void* buffer, size_t size) override {
1245 const size_t bytes = fStream->read(buffer, size);
1246 fPosition += bytes;
1247 return bytes;
1248 }
1249
1250 bool isAtEnd() const override {
1251 return fStream->isAtEnd();
1252 }
1253
1254 bool rewind() override {
1255 if (fPosition <= fLimit && fStream->rewind()) {
1256 fPosition = 0;
1257 return true;
1258 }
1259
1260 return false;
1261 }
1262
1263private:
Ben Wagner145dbcd2016-11-03 14:40:50 -04001264 std::unique_ptr<SkStream> fStream;
1265 const size_t fLimit;
1266 size_t fPosition;
scroggo8e6c7ad2016-09-16 08:20:38 -07001267
Mike Reed71f867c2017-07-23 13:14:10 -04001268 LimitedRewindingStream(std::unique_ptr<SkStream> stream, size_t limit)
1269 : fStream(std::move(stream))
scroggo8e6c7ad2016-09-16 08:20:38 -07001270 , fLimit(limit)
1271 , fPosition(0)
1272 {
1273 SkASSERT(fStream);
1274 }
1275};
1276
1277DEF_TEST(Codec_fallBack, r) {
1278 // SkAndroidCodec needs to be able to fall back to scanline decoding
1279 // if incremental decoding does not work. Make sure this does not
1280 // require a rewind.
1281
1282 // Formats that currently do not support incremental decoding
1283 auto files = {
Hal Canaryc465d132017-12-08 10:21:31 -05001284 "images/CMYK.jpg",
1285 "images/color_wheel.ico",
1286 "images/mandrill.wbmp",
1287 "images/randPixels.bmp",
scroggo8e6c7ad2016-09-16 08:20:38 -07001288 };
1289 for (auto file : files) {
Leon Scroggins III04be2b52017-08-17 15:13:20 -04001290 auto stream = LimitedRewindingStream::Make(file, SkCodec::MinBufferedBytesNeeded());
scroggo8e6c7ad2016-09-16 08:20:38 -07001291 if (!stream) {
1292 SkDebugf("Missing resources (%s). Set --resourcePath.\n", file);
1293 return;
1294 }
1295
Mike Reedede7bac2017-07-23 15:30:02 -04001296 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
scroggo8e6c7ad2016-09-16 08:20:38 -07001297 if (!codec) {
1298 ERRORF(r, "Failed to create codec for %s,", file);
1299 continue;
1300 }
1301
1302 SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
1303 SkBitmap bm;
1304 bm.allocPixels(info);
1305
1306 if (SkCodec::kUnimplemented != codec->startIncrementalDecode(info, bm.getPixels(),
1307 bm.rowBytes())) {
1308 ERRORF(r, "Is scanline decoding now implemented for %s?", file);
1309 continue;
1310 }
1311
1312 // Scanline decoding should not require a rewind.
1313 SkCodec::Result result = codec->startScanlineDecode(info);
1314 if (SkCodec::kSuccess != result) {
1315 ERRORF(r, "Scanline decoding failed for %s with %i", file, result);
1316 }
1317 }
msarett2ecc35f2016-09-08 11:55:16 -07001318}
scroggoc46cdd42016-10-10 06:45:32 -07001319
1320// This test verifies that we fixed an assert statement that fired when reusing a png codec
1321// after scaling.
1322DEF_TEST(Codec_reusePng, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001323 std::unique_ptr<SkStream> stream(GetResourceAsStream("images/plane.png"));
scroggoc46cdd42016-10-10 06:45:32 -07001324 if (!stream) {
1325 return;
1326 }
1327
Mike Reedede7bac2017-07-23 15:30:02 -04001328 std::unique_ptr<SkAndroidCodec> codec(SkAndroidCodec::MakeFromStream(std::move(stream)));
scroggoc46cdd42016-10-10 06:45:32 -07001329 if (!codec) {
1330 ERRORF(r, "Failed to create codec\n");
1331 return;
1332 }
1333
1334 SkAndroidCodec::AndroidOptions opts;
1335 opts.fSampleSize = 5;
1336 auto size = codec->getSampledDimensions(opts.fSampleSize);
1337 auto info = codec->getInfo().makeWH(size.fWidth, size.fHeight).makeColorType(kN32_SkColorType);
1338 SkBitmap bm;
1339 bm.allocPixels(info);
1340 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1341 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1342
1343 info = codec->getInfo().makeColorType(kN32_SkColorType);
1344 bm.allocPixels(info);
1345 opts.fSampleSize = 1;
1346 result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &opts);
1347 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1348}
scroggoe61b3b42016-10-10 07:17:32 -07001349
1350DEF_TEST(Codec_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001351 auto file = "images/plane_interlaced.png";
scroggoe61b3b42016-10-10 07:17:32 -07001352 std::unique_ptr<SkStream> stream(GetResourceAsStream(file));
1353 if (!stream) {
1354 return;
1355 }
1356
1357 // This is enough to read the header etc, but no rows.
Mike Reedede7bac2017-07-23 15:30:02 -04001358 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromData(SkData::MakeFromStream(stream.get(), 99)));
scroggoe61b3b42016-10-10 07:17:32 -07001359 if (!codec) {
1360 ERRORF(r, "Failed to create codec\n");
1361 return;
1362 }
1363
1364 auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1365 SkBitmap bm;
1366 bm.allocPixels(info);
1367 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes());
1368 REPORTER_ASSERT(r, result == SkCodec::kSuccess);
1369
1370 // This is an arbitrary value. The important fact is that it is not zero, and rowsDecoded
1371 // should get set to zero by incrementalDecode.
1372 int rowsDecoded = 77;
1373 result = codec->incrementalDecode(&rowsDecoded);
1374 REPORTER_ASSERT(r, result == SkCodec::kIncompleteInput);
1375 REPORTER_ASSERT(r, rowsDecoded == 0);
1376}
Matt Sarett29121eb2016-10-17 14:32:46 -04001377
Matt Sarettd59948a2017-04-26 10:59:48 -04001378static void test_invalid_images(skiatest::Reporter* r, const char* path,
1379 SkCodec::Result expectedResult) {
Mike Reed71f867c2017-07-23 13:14:10 -04001380 auto stream = GetResourceAsStream(path);
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001381 if (!stream) {
1382 return;
1383 }
1384
Mike Reedede7bac2017-07-23 15:30:02 -04001385 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001386 REPORTER_ASSERT(r, codec);
1387
Matt Sarettd59948a2017-04-26 10:59:48 -04001388 test_info(r, codec.get(), codec->getInfo().makeColorType(kN32_SkColorType), expectedResult,
1389 nullptr);
1390}
1391
1392DEF_TEST(Codec_InvalidImages, r) {
1393 // ASAN will complain if there is an issue.
Leon Scroggins III674a1842017-07-06 12:26:09 -04001394 test_invalid_images(r, "invalid_images/skbug5887.gif", SkCodec::kErrorInInput);
Matt Sarettd59948a2017-04-26 10:59:48 -04001395 test_invalid_images(r, "invalid_images/many-progressive-scans.jpg", SkCodec::kInvalidInput);
1396 test_invalid_images(r, "invalid_images/b33251605.bmp", SkCodec::kIncompleteInput);
1397 test_invalid_images(r, "invalid_images/bad_palette.png", SkCodec::kInvalidInput);
1398}
1399
1400static void test_invalid_header(skiatest::Reporter* r, const char* path) {
Mike Reed0933bc92017-12-09 01:27:41 +00001401 auto data = GetResourceAsData(path);
1402 if (!data) {
1403 return;
1404 }
1405 std::unique_ptr<SkStreamAsset> stream(new SkMemoryStream(std::move(data)));
Mike Reed847068c2017-07-26 11:35:53 -04001406 if (!stream) {
Matt Sarettd59948a2017-04-26 10:59:48 -04001407 return;
1408 }
Mike Reedede7bac2017-07-23 15:30:02 -04001409 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Matt Sarettd59948a2017-04-26 10:59:48 -04001410 REPORTER_ASSERT(r, !codec);
1411}
1412
1413DEF_TEST(Codec_InvalidHeader, r) {
1414 test_invalid_header(r, "invalid_images/int_overflow.ico");
1415
1416 // These files report values that have caused problems with SkFILEStreams.
1417 // They are invalid, and should not create SkCodecs.
1418 test_invalid_header(r, "invalid_images/b33651913.bmp");
1419 test_invalid_header(r, "invalid_images/b34778578.bmp");
Leon Scroggins IIIb3b24532017-01-18 12:39:07 -05001420}
1421
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001422/*
1423For the Codec_InvalidAnimated test, immediately below,
1424resources/invalid_images/skbug6046.gif is:
1425
142600000000: 4749 4638 3961 2000 0000 0000 002c ff00 GIF89a ......,..
142700000010: 7400 0600 0000 4001 0021 f904 0a00 0000 t.....@..!......
142800000020: 002c ff00 0000 ff00 7400 0606 0606 0601 .,......t.......
142900000030: 0021 f904 0000 0000 002c ff00 0000 ffcc .!.......,......
143000000040: 1b36 5266 deba 543d .6Rf..T=
1431
1432It nominally contains 3 frames, but all of them are invalid. It came from a
1433fuzzer doing random mutations and copies. The breakdown:
1434
1435@000 6 bytes magic "GIF89a"
1436@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1437 - width = 32
1438 - height = 0
1439 - flags = 0x00
1440 - background color index, pixel aspect ratio bytes ignored
1441@00D 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x40
1442 - origin_x = 255
1443 - origin_y = 116
1444 - width = 6
1445 - height = 0
1446 - flags = 0x40, interlaced
1447@017 2 bytes Image Descriptor body (pixel data): 0x01 0x00
1448 - lit_width = 1, INVALID, OUTSIDE THE RANGE [2, 8]
1449 - 0x00 byte means "end of data" for this frame
1450@019 8 bytes Graphic Control Extension: 0x21 0xF9 ... 0x00
1451 - valid, but irrelevant here.
1452@021 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1453 - origin_x = 255
1454 - origin_y = 0
1455 - width = 255
1456 - height = 116
1457 - flags = 0x06, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1458@02B 14 bytes Image Descriptor body (pixel data): 0x06 0x06 ... 0x00
1459 - lit_width = 6
1460 - 0x06 precedes a 6 byte block of data
1461 - 0x04 precedes a 4 byte block of data
1462 - 0x00 byte means "end of data" for this frame
1463@039 10 bytes Image Descriptor header: 0x2C 0xFF ... 0x06
1464 - origin_x = 255
1465 - origin_y = 0
1466 - width = 52479
1467 - height = 13851
1468 - flags = 0x52, INVALID, 0x80 BIT ZERO IMPLIES 0x07 BITS SHOULD BE ZERO
1469@043 5 bytes Image Descriptor body (pixel data): 0x66 0xDE ... unexpected-EOF
1470 - lit_width = 102, INVALID, OUTSIDE THE RANGE [2, 8]
1471 - 0xDE precedes a 222 byte block of data, INVALIDLY TRUNCATED
1472
1473On Image Descriptor flags INVALIDITY,
1474https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 20.c says that "Size of
1475Local Color Table [the low 3 bits]... should be 0 if there is no Local Color
1476Table specified [the high bit]."
1477
1478On LZW literal width (also known as Minimum Code Size) INVALIDITY outside of
1479the range [2, 8], https://www.w3.org/Graphics/GIF/spec-gif89a.txt Appendix F
1480says that "Normally this will be the same as the number of [palette index]
1481bits. Because of some algorithmic constraints however, black & white images
1482which have one color bit must be indicated as having a code size of 2."
1483
1484In practice, some GIF decoders, including the old third_party/gif code, don't
1485enforce this. It says: "currentFrame->setDataSize(this->getOneByte())" with the
1486only further check being against an upper bound of SK_MAX_DICTIONARY_ENTRY_BITS
1487(the constant 12).
1488*/
1489
Leon Scroggins III56e32092016-12-12 17:10:46 -05001490DEF_TEST(Codec_InvalidAnimated, r) {
1491 // ASAN will complain if there is an issue.
1492 auto path = "invalid_images/skbug6046.gif";
Mike Reed71f867c2017-07-23 13:14:10 -04001493 auto stream = GetResourceAsStream(path);
Leon Scroggins III56e32092016-12-12 17:10:46 -05001494 if (!stream) {
1495 return;
1496 }
1497
Mike Reedede7bac2017-07-23 15:30:02 -04001498 std::unique_ptr<SkCodec> codec(SkCodec::MakeFromStream(std::move(stream)));
Leon Scroggins III56e32092016-12-12 17:10:46 -05001499 REPORTER_ASSERT(r, codec);
1500 if (!codec) {
1501 return;
1502 }
1503
1504 const auto info = codec->getInfo().makeColorType(kN32_SkColorType);
1505 SkBitmap bm;
1506 bm.allocPixels(info);
1507
1508 auto frameInfos = codec->getFrameInfo();
1509 SkCodec::Options opts;
Leon Scroggins III249b8e32017-04-17 12:46:33 -04001510 for (int i = 0; static_cast<size_t>(i) < frameInfos.size(); i++) {
Leon Scroggins III56e32092016-12-12 17:10:46 -05001511 opts.fFrameIndex = i;
Leon Scroggins III33deb7e2017-06-07 12:31:51 -04001512 const auto reqFrame = frameInfos[i].fRequiredFrame;
Nigel Tao66bc5242018-08-22 10:56:03 +10001513 opts.fPriorFrame = reqFrame == i - 1 ? reqFrame : SkCodec::kNoFrame;
Leon Scroggins III56e32092016-12-12 17:10:46 -05001514 auto result = codec->startIncrementalDecode(info, bm.getPixels(), bm.rowBytes(), &opts);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001515
1516#ifdef SK_HAS_WUFFS_LIBRARY
1517 // We are transitioning from an old GIF implementation to a new (Wuffs)
1518 // GIF implementation.
1519 //
1520 // This test (without SK_HAS_WUFFS_LIBRARY) is overly specific to the
1521 // old implementation. As a fuzzer-discovered test, it's likely that
1522 // what's fundamentally being tested isn't that decoding an invalid GIF
1523 // leads to kSuccess, but that decoding an invalid GIF doesn't lead to
1524 // an ASAN violation.
1525 //
1526 // Each of the 3 frames of the source GIF image is fundamentally
1527 // invalid, as per the "breakdown" comment above. The old
1528 // implementation is happy to call startIncrementalDecode 3 times. The
1529 // new implementation is happy for the first two times, but on the 3rd,
1530 // SkCodec::startIncrementalDecode calls SkCodec::handleFrameIndex
1531 // which calls SkCodec::getPixels on the requiredFrame (the 0'th
1532 // frame), and the new implementation subsequently hits the
1533 // invalid-ness and returns kErrorInInput instead of kSuccess.
1534 //
1535 // Once the transition is complete, we can remove the #ifdef and delete
1536 // the rest of the test function.
1537 if (i == 2) {
1538 if (result != SkCodec::kErrorInInput) {
1539 ERRORF(r, "Unexpected result for decoding frame %i (out of %i) with error %i\n", i,
1540 frameInfos.size(), result);
1541 }
1542 return;
1543 }
1544#endif
Leon Scroggins III56e32092016-12-12 17:10:46 -05001545 if (result != SkCodec::kSuccess) {
1546 ERRORF(r, "Failed to start decoding frame %i (out of %i) with error %i\n", i,
1547 frameInfos.size(), result);
1548 continue;
1549 }
1550
1551 codec->incrementalDecode();
1552 }
1553}
Matt Sarett0e032be2017-03-15 17:50:08 -04001554
Matt Sarett5df93de2017-03-22 21:52:47 +00001555static void encode_format(SkDynamicMemoryWStream* stream, const SkPixmap& pixmap,
Matt Sarettc367d032017-05-05 11:13:26 -04001556 SkEncodedImageFormat format) {
Matt Sarett5df93de2017-03-22 21:52:47 +00001557 switch (format) {
1558 case SkEncodedImageFormat::kPNG:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001559 SkPngEncoder::Encode(stream, pixmap, SkPngEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001560 break;
1561 case SkEncodedImageFormat::kJPEG:
Matt Sarett26b44df2017-05-02 16:04:56 -04001562 SkJpegEncoder::Encode(stream, pixmap, SkJpegEncoder::Options());
Matt Sarett5df93de2017-03-22 21:52:47 +00001563 break;
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001564 case SkEncodedImageFormat::kWEBP:
Brian Osmanb62f50c2018-07-12 14:44:27 -04001565 SkWebpEncoder::Encode(stream, pixmap, SkWebpEncoder::Options());
Matt Sarett3dbef9f2017-04-05 22:33:22 +00001566 break;
Matt Sarett5df93de2017-03-22 21:52:47 +00001567 default:
1568 SkASSERT(false);
1569 break;
1570 }
1571}
1572
Brian Osmanb62f50c2018-07-12 14:44:27 -04001573static void test_encode_icc(skiatest::Reporter* r, SkEncodedImageFormat format) {
Matt Sarett0e032be2017-03-15 17:50:08 -04001574 // Test with sRGB color space.
1575 SkBitmap srgbBitmap;
1576 SkImageInfo srgbInfo = SkImageInfo::MakeS32(1, 1, kOpaque_SkAlphaType);
1577 srgbBitmap.allocPixels(srgbInfo);
1578 *srgbBitmap.getAddr32(0, 0) = 0;
1579 SkPixmap pixmap;
1580 srgbBitmap.peekPixels(&pixmap);
1581 SkDynamicMemoryWStream srgbBuf;
Brian Osmanb62f50c2018-07-12 14:44:27 -04001582 encode_format(&srgbBuf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001583 sk_sp<SkData> srgbData = srgbBuf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001584 std::unique_ptr<SkCodec> srgbCodec(SkCodec::MakeFromData(srgbData));
Mike Kleine28a6b52018-07-25 13:05:17 -04001585 REPORTER_ASSERT(r, srgbCodec->getInfo().colorSpace() == sk_srgb_singleton());
Matt Sarett0e032be2017-03-15 17:50:08 -04001586
1587 // Test with P3 color space.
1588 SkDynamicMemoryWStream p3Buf;
1589 sk_sp<SkColorSpace> p3 = SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma,
1590 SkColorSpace::kDCIP3_D65_Gamut);
1591 pixmap.setColorSpace(p3);
Brian Osmanb62f50c2018-07-12 14:44:27 -04001592 encode_format(&p3Buf, pixmap, format);
Matt Sarett0e032be2017-03-15 17:50:08 -04001593 sk_sp<SkData> p3Data = p3Buf.detachAsData();
Mike Reedede7bac2017-07-23 15:30:02 -04001594 std::unique_ptr<SkCodec> p3Codec(SkCodec::MakeFromData(p3Data));
Matt Sarett0e032be2017-03-15 17:50:08 -04001595 REPORTER_ASSERT(r, p3Codec->getInfo().colorSpace()->gammaCloseToSRGB());
Mike Klein4429a4f2018-10-04 09:06:00 -04001596 SkMatrix44 mat0, mat1;
Matt Sarett0e032be2017-03-15 17:50:08 -04001597 bool success = p3->toXYZD50(&mat0);
1598 REPORTER_ASSERT(r, success);
1599 success = p3Codec->getInfo().colorSpace()->toXYZD50(&mat1);
1600 REPORTER_ASSERT(r, success);
1601
1602 for (int i = 0; i < 4; i++) {
1603 for (int j = 0; j < 4; j++) {
Matt Sarett5df93de2017-03-22 21:52:47 +00001604 REPORTER_ASSERT(r, color_space_almost_equal(mat0.get(i, j), mat1.get(i, j)));
Matt Sarett0e032be2017-03-15 17:50:08 -04001605 }
1606 }
1607}
Matt Sarett5df93de2017-03-22 21:52:47 +00001608
1609DEF_TEST(Codec_EncodeICC, r) {
Brian Osmanb62f50c2018-07-12 14:44:27 -04001610 test_encode_icc(r, SkEncodedImageFormat::kPNG);
1611 test_encode_icc(r, SkEncodedImageFormat::kJPEG);
1612 test_encode_icc(r, SkEncodedImageFormat::kWEBP);
Matt Sarett5df93de2017-03-22 21:52:47 +00001613}
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001614
1615DEF_TEST(Codec_webp_rowsDecoded, r) {
Hal Canaryc465d132017-12-08 10:21:31 -05001616 const char* path = "images/baby_tux.webp";
Leon Scroggins IIIe5677462017-09-27 16:31:08 -04001617 sk_sp<SkData> data(GetResourceAsData(path));
1618 if (!data) {
1619 return;
1620 }
1621
1622 // Truncate this file so that the header is available but no rows can be
1623 // decoded. This should create a codec but fail to decode.
1624 size_t truncatedSize = 5000;
1625 sk_sp<SkData> subset = SkData::MakeSubset(data.get(), 0, truncatedSize);
1626 std::unique_ptr<SkCodec> codec = SkCodec::MakeFromData(std::move(subset));
1627 if (!codec) {
1628 ERRORF(r, "Failed to create a codec for %s truncated to only %lu bytes",
1629 path, truncatedSize);
1630 return;
1631 }
1632
1633 test_info(r, codec.get(), codec->getInfo(), SkCodec::kInvalidInput, nullptr);
1634}
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001635
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001636/*
1637For the Codec_ossfuzz6274 test, immediately below,
1638resources/invalid_images/ossfuzz6274.gif is:
1639
164000000000: 4749 4638 3961 2000 2000 f120 2020 2020 GIF89a . ..
164100000010: 2020 2020 2020 2020 2021 f903 ff20 2020 !...
164200000020: 002c 0000 0000 2000 2000 2000 00 .,.... . . ..
1643
1644@000 6 bytes magic "GIF89a"
1645@006 7 bytes Logical Screen Descriptor: 0x20 0x00 ... 0x00
1646 - width = 32
1647 - height = 32
1648 - flags = 0xF1, global color table, 4 RGB entries
1649 - background color index, pixel aspect ratio bytes ignored
1650@00D 12 bytes Color Table: 0x20 0x20 ... 0x20
1651@019 20 bytes Graphic Control Extension: 0x21 0xF9 ... unexpected-EOF
1652 - 0x03 precedes a 3 byte block of data, INVALID, MUST BE 4
1653 - 0x20 precedes a 32 byte block of data, INVALIDly truncated
1654
1655https://www.w3.org/Graphics/GIF/spec-gif89a.txt section 23.c says that the
1656block size (for an 0x21 0xF9 Graphic Control Extension) must be "the fixed
1657value 4".
1658*/
1659
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001660DEF_TEST(Codec_ossfuzz6274, r) {
1661 if (GetResourcePath().isEmpty()) {
1662 return;
1663 }
1664
1665 const char* file = "invalid_images/ossfuzz6274.gif";
1666 auto image = GetResourceAsImage(file);
Leon Scroggins IIIe93ec682018-10-26 09:25:51 -04001667
1668#ifdef SK_HAS_WUFFS_LIBRARY
1669 // We are transitioning from an old GIF implementation to a new (Wuffs) GIF
1670 // implementation.
1671 //
1672 // This test (without SK_HAS_WUFFS_LIBRARY) is overly specific to the old
1673 // implementation. In the new implementation, the MakeFromStream factory
1674 // method returns a nullptr SkImage*, instead of returning a non-null but
1675 // otherwise all-transparent SkImage*.
1676 //
1677 // Either way, the end-to-end result is the same - the source input is
1678 // rejected as an invalid GIF image - but the two implementations differ in
1679 // how that's represented.
1680 //
1681 // Once the transition is complete, we can remove the #ifdef and delete the
1682 // rest of the test function.
1683 //
1684 // See Codec_GifTruncated3 for the equivalent of the rest of the test
1685 // function, on different (but still truncated) source data.
1686 if (image) {
1687 ERRORF(r, "Invalid data gave non-nullptr image");
1688 }
1689 return;
1690#endif
1691
Leon Scroggins IIIcbf66a22018-02-16 12:03:03 -05001692 if (!image) {
1693 ERRORF(r, "Missing %s", file);
1694 return;
1695 }
1696
1697 REPORTER_ASSERT(r, image->width() == 32);
1698 REPORTER_ASSERT(r, image->height() == 32);
1699
1700 SkBitmap bm;
1701 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(32, 32))) {
1702 ERRORF(r, "Failed to allocate pixels");
1703 return;
1704 }
1705
1706 bm.eraseColor(SK_ColorTRANSPARENT);
1707
1708 SkCanvas canvas(bm);
1709 canvas.drawImage(image, 0, 0, nullptr);
1710
1711 for (int i = 0; i < image->width(); ++i)
1712 for (int j = 0; j < image->height(); ++j) {
1713 SkColor actual = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(i, j));
1714 if (actual != SK_ColorTRANSPARENT) {
1715 ERRORF(r, "did not initialize pixels! %i, %i is %x", i, j, actual);
1716 }
1717 }
1718}
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001719
Leon Scroggins III665949a2018-06-26 10:49:42 -04001720DEF_TEST(Codec_78329453, r) {
1721 if (GetResourcePath().isEmpty()) {
1722 return;
1723 }
1724
1725 const char* file = "images/b78329453.jpeg";
1726 auto data = GetResourceAsData(file);
1727 if (!data) {
1728 ERRORF(r, "Missing %s", file);
1729 return;
1730 }
1731
1732 auto codec = SkAndroidCodec::MakeFromCodec(SkCodec::MakeFromData(data));
1733 if (!codec) {
1734 ERRORF(r, "failed to create codec from %s", file);
1735 return;
1736 }
1737
1738 // A bug in jpeg_skip_scanlines resulted in an infinite loop for this specific
1739 // sample size on this image. Other sample sizes could have had the same result,
1740 // but the ones tested by DM happen to not.
1741 constexpr int kSampleSize = 19;
1742 const auto size = codec->getSampledDimensions(kSampleSize);
1743 auto info = codec->getInfo().makeWH(size.width(), size.height());
1744 SkBitmap bm;
1745 bm.allocPixels(info);
1746 bm.eraseColor(SK_ColorTRANSPARENT);
1747
1748 SkAndroidCodec::AndroidOptions options;
1749 options.fSampleSize = kSampleSize;
1750 auto result = codec->getAndroidPixels(info, bm.getPixels(), bm.rowBytes(), &options);
1751 if (result != SkCodec::kSuccess) {
1752 ERRORF(r, "failed to decode with error %s", SkCodec::ResultToString(result));
1753 }
1754}
1755
Leon Scroggins III36f7e322018-08-27 11:55:46 -04001756DEF_TEST(Codec_A8, r) {
1757 if (GetResourcePath().isEmpty()) {
1758 return;
1759 }
1760
1761 const char* file = "images/mandrill_cmyk.jpg";
1762 auto data = GetResourceAsData(file);
1763 if (!data) {
1764 ERRORF(r, "missing %s", file);
1765 return;
1766 }
1767
1768 auto codec = SkCodec::MakeFromData(std::move(data));
1769 auto info = codec->getInfo().makeColorType(kAlpha_8_SkColorType);
1770 SkBitmap bm;
1771 bm.allocPixels(info);
1772 REPORTER_ASSERT(r, codec->getPixels(bm.pixmap()) == SkCodec::kInvalidConversion);
1773}
1774
Leon Scroggins III9e8a5942018-02-28 16:24:18 -05001775DEF_TEST(Codec_crbug807324, r) {
1776 if (GetResourcePath().isEmpty()) {
1777 return;
1778 }
1779
1780 const char* file = "images/crbug807324.png";
1781 auto image = GetResourceAsImage(file);
1782 if (!image) {
1783 ERRORF(r, "Missing %s", file);
1784 return;
1785 }
1786
1787 const int kWidth = image->width();
1788 const int kHeight = image->height();
1789
1790 SkBitmap bm;
1791 if (!bm.tryAllocPixels(SkImageInfo::MakeN32Premul(kWidth, kHeight))) {
1792 ERRORF(r, "Could not allocate pixels (%i x %i)", kWidth, kHeight);
1793 return;
1794 }
1795
1796 bm.eraseColor(SK_ColorTRANSPARENT);
1797
1798 SkCanvas canvas(bm);
1799 canvas.drawImage(image, 0, 0, nullptr);
1800
1801 for (int i = 0; i < kWidth; ++i)
1802 for (int j = 0; j < kHeight; ++j) {
1803 if (*bm.getAddr32(i, j) == SK_ColorTRANSPARENT) {
1804 ERRORF(r, "image should not be transparent! %i, %i is 0", i, j);
1805 return;
1806 }
1807 }
1808}