blob: 50c107172aac780f7ad9a6d788d95e431e250d47 [file] [log] [blame]
scroggof24f2242015-03-03 08:59:20 -08001/*
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
msarettad8bcfe2016-03-07 07:09:03 -08008#include "SkBitmap.h"
msarett74114382015-03-16 11:55:18 -07009#include "SkCodecPriv.h"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkColorPriv.h"
Matt Sarettc434f512016-10-13 18:24:20 -040011#include "SkColorSpace.h"
scroggof24f2242015-03-03 08:59:20 -080012#include "SkColorTable.h"
scroggof24f2242015-03-03 08:59:20 -080013#include "SkMath.h"
msarett13a91232016-02-01 08:03:29 -080014#include "SkOpts.h"
msarettbe1d5552016-01-21 09:05:23 -080015#include "SkPngCodec.h"
msarett55447952016-07-22 14:07:23 -070016#include "SkPoint3.h"
scroggof24f2242015-03-03 08:59:20 -080017#include "SkSize.h"
18#include "SkStream.h"
19#include "SkSwizzler.h"
scroggo565901d2015-12-10 10:44:13 -080020#include "SkTemplates.h"
bungeman5d2cd6e2016-02-23 07:34:25 -080021#include "SkUtils.h"
scroggof24f2242015-03-03 08:59:20 -080022
mtklein63213812016-08-24 09:55:56 -070023#include "png.h"
24
mtkleindc90b532016-07-28 14:45:28 -070025// This warning triggers false postives way too often in here.
26#if defined(__GNUC__) && !defined(__clang__)
27 #pragma GCC diagnostic ignored "-Wclobbered"
28#endif
29
scroggo8e6c7ad2016-09-16 08:20:38 -070030#if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5)
31 // This is not needed with version 1.5
32 #undef SK_GOOGLE3_PNG_HACK
33#endif
34
35// FIXME (scroggo): We can use png_jumpbuf directly once Google3 is on 1.6
36#define PNG_JMPBUF(x) png_jmpbuf((png_structp) x)
37
scroggof24f2242015-03-03 08:59:20 -080038///////////////////////////////////////////////////////////////////////////////
scroggof24f2242015-03-03 08:59:20 -080039// Callback functions
40///////////////////////////////////////////////////////////////////////////////
41
scroggo8e6c7ad2016-09-16 08:20:38 -070042// When setjmp is first called, it returns 0, meaning longjmp was not called.
43constexpr int kSetJmpOkay = 0;
44// An error internal to libpng.
45constexpr int kPngError = 1;
46// Passed to longjmp when we have decoded as many lines as we need.
47constexpr int kStopDecoding = 2;
48
scroggof24f2242015-03-03 08:59:20 -080049static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
scroggo230d4ac2015-03-26 07:15:55 -070050 SkCodecPrintf("------ png error %s\n", msg);
scroggo8e6c7ad2016-09-16 08:20:38 -070051 longjmp(PNG_JMPBUF(png_ptr), kPngError);
scroggof24f2242015-03-03 08:59:20 -080052}
53
scroggo0eed6df2015-03-26 10:07:56 -070054void sk_warning_fn(png_structp, png_const_charp msg) {
55 SkCodecPrintf("----- png warning %s\n", msg);
56}
57
scroggocf98fa92015-11-23 08:14:40 -080058#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
59static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
60 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(png_ptr);
61 // readChunk() returning true means continue decoding
62 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk->size) ? 1 : -1;
63}
64#endif
65
scroggof24f2242015-03-03 08:59:20 -080066///////////////////////////////////////////////////////////////////////////////
67// Helpers
68///////////////////////////////////////////////////////////////////////////////
69
70class AutoCleanPng : public SkNoncopyable {
71public:
scroggo8e6c7ad2016-09-16 08:20:38 -070072 /*
73 * This class does not take ownership of stream or reader, but if codecPtr
74 * is non-NULL, and decodeBounds succeeds, it will have created a new
75 * SkCodec (pointed to by *codecPtr) which will own/ref them, as well as
76 * the png_ptr and info_ptr.
77 */
78 AutoCleanPng(png_structp png_ptr, SkStream* stream, SkPngChunkReader* reader,
79 SkCodec** codecPtr)
scroggof24f2242015-03-03 08:59:20 -080080 : fPng_ptr(png_ptr)
scroggo8e6c7ad2016-09-16 08:20:38 -070081 , fInfo_ptr(nullptr)
82 , fDecodedBounds(false)
83 , fReadHeader(false)
84 , fStream(stream)
85 , fChunkReader(reader)
86 , fOutCodec(codecPtr)
87 {}
scroggof24f2242015-03-03 08:59:20 -080088
89 ~AutoCleanPng() {
halcanary96fcdcc2015-08-27 07:41:13 -070090 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
scroggof24f2242015-03-03 08:59:20 -080091 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070092 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
msarett13a91232016-02-01 08:03:29 -080093 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
scroggof24f2242015-03-03 08:59:20 -080094 }
95 }
96
97 void setInfoPtr(png_infop info_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070098 SkASSERT(nullptr == fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -080099 fInfo_ptr = info_ptr;
100 }
101
scroggo8e6c7ad2016-09-16 08:20:38 -0700102 /**
103 * Reads enough of the input stream to decode the bounds.
104 * @return false if the stream is not a valid PNG (or too short).
105 * true if it read enough of the stream to determine the bounds.
106 * In the latter case, the stream may have been read beyond the
107 * point to determine the bounds, and the png_ptr will have saved
108 * any extra data. Further, if the codecPtr supplied to the
109 * constructor was not NULL, it will now point to a new SkCodec,
110 * which owns (or refs, in the case of the SkPngChunkReader) the
111 * inputs. If codecPtr was NULL, the png_ptr and info_ptr are
112 * unowned, and it is up to the caller to destroy them.
113 */
114 bool decodeBounds();
115
116private:
117 png_structp fPng_ptr;
118 png_infop fInfo_ptr;
119 bool fDecodedBounds;
120 bool fReadHeader;
121 SkStream* fStream;
122 SkPngChunkReader* fChunkReader;
123 SkCodec** fOutCodec;
124
125 /**
126 * Supplied to libpng to call when it has read enough data to determine
127 * bounds.
128 */
129 static void InfoCallback(png_structp png_ptr, png_infop) {
130 // png_get_progressive_ptr returns the pointer we set on the png_ptr with
131 // png_set_progressive_read_fn
132 static_cast<AutoCleanPng*>(png_get_progressive_ptr(png_ptr))->infoCallback();
133 }
134
135 void infoCallback();
136
137#ifdef SK_GOOGLE3_PNG_HACK
138// public so it can be called by SkPngCodec::rereadHeaderIfNecessary().
139public:
140#endif
141 void releasePngPtrs() {
halcanary96fcdcc2015-08-27 07:41:13 -0700142 fPng_ptr = nullptr;
143 fInfo_ptr = nullptr;
scroggof24f2242015-03-03 08:59:20 -0800144 }
scroggof24f2242015-03-03 08:59:20 -0800145};
146#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
147
scroggo8e6c7ad2016-09-16 08:20:38 -0700148bool AutoCleanPng::decodeBounds() {
149 if (setjmp(PNG_JMPBUF(fPng_ptr))) {
150 return false;
151 }
152
153 png_set_progressive_read_fn(fPng_ptr, this, InfoCallback, nullptr, nullptr);
154
155 // Arbitrary buffer size, though note that it matches (below)
156 // SkPngCodec::processData(). FIXME: Can we better suit this to the size of
157 // the PNG header?
158 constexpr size_t kBufferSize = 4096;
159 char buffer[kBufferSize];
160
161 while (true) {
162 const size_t bytesRead = fStream->read(buffer, kBufferSize);
163 if (!bytesRead) {
164 // We have read to the end of the input without decoding bounds.
165 break;
166 }
167
168 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
169 if (fReadHeader) {
170 break;
171 }
172 }
173
174 // For safety, clear the pointer to this object.
175 png_set_progressive_read_fn(fPng_ptr, nullptr, nullptr, nullptr, nullptr);
176 return fDecodedBounds;
177}
178
179void SkPngCodec::processData() {
180 switch (setjmp(PNG_JMPBUF(fPng_ptr))) {
181 case kPngError:
182 // There was an error. Stop processing data.
183 // FIXME: Do we need to discard png_ptr?
184 return;
185 case kStopDecoding:
186 // We decoded all the lines we want.
187 return;
188 case kSetJmpOkay:
189 // Everything is okay.
190 break;
191 default:
192 // No other values should be passed to longjmp.
193 SkASSERT(false);
194 }
195
196 // Arbitrary buffer size
197 constexpr size_t kBufferSize = 4096;
198 char buffer[kBufferSize];
199
200 while (true) {
201 const size_t bytesRead = this->stream()->read(buffer, kBufferSize);
202 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
203
204 if (!bytesRead) {
205 // We have read to the end of the input. Note that we quit *after*
206 // calling png_process_data, because decodeBounds may have told
207 // libpng to save the remainder of the buffer, in which case
208 // png_process_data will process the saved buffer, though the
209 // stream has no more to read.
210 break;
211 }
212 }
213}
214
msarettd1ec89b2016-08-03 12:59:27 -0700215// Note: SkColorTable claims to store SkPMColors, which is not necessarily the case here.
msarettdcd5e652016-08-22 08:48:40 -0700216bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -0800217
msarett13a91232016-02-01 08:03:29 -0800218 int numColors;
219 png_color* palette;
220 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -0700221 return false;
scroggof24f2242015-03-03 08:59:20 -0800222 }
223
msarettdcd5e652016-08-22 08:48:40 -0700224 // Contents depend on tableColorType and our choice of if/when to premultiply:
225 // { kPremul, kUnpremul, kOpaque } x { RGBA, BGRA }
226 SkPMColor colorTable[256];
227 SkColorType tableColorType = fColorXform ? kRGBA_8888_SkColorType : dstInfo.colorType();
scroggof24f2242015-03-03 08:59:20 -0800228
msarett13a91232016-02-01 08:03:29 -0800229 png_bytep alphas;
230 int numColorsWithAlpha = 0;
231 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
msarettdcd5e652016-08-22 08:48:40 -0700232 // If we are performing a color xform, it will handle the premultiply. Otherwise,
233 // we'll do it here.
234 bool premultiply = !fColorXform && needs_premul(dstInfo, this->getInfo());
235
msarett13a91232016-02-01 08:03:29 -0800236 // Choose which function to use to create the color table. If the final destination's
237 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
msarettdcd5e652016-08-22 08:48:40 -0700238 PackColorProc proc = choose_pack_color_proc(premultiply, tableColorType);
msarett13a91232016-02-01 08:03:29 -0800239
240 for (int i = 0; i < numColorsWithAlpha; i++) {
241 // We don't have a function in SkOpts that combines a set of alphas with a set
242 // of RGBs. We could write one, but it's hardly worth it, given that this
243 // is such a small fraction of the total decode time.
msarettdcd5e652016-08-22 08:48:40 -0700244 colorTable[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
msarett13a91232016-02-01 08:03:29 -0800245 palette++;
246 }
scroggof24f2242015-03-03 08:59:20 -0800247 }
248
msarett13a91232016-02-01 08:03:29 -0800249 if (numColorsWithAlpha < numColors) {
250 // The optimized code depends on a 3-byte png_color struct with the colors
251 // in RGB order. These checks make sure it is safe to use.
252 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
253#ifdef SK_DEBUG
254 SkASSERT(&palette->red < &palette->green);
255 SkASSERT(&palette->green < &palette->blue);
256#endif
257
msarettdcd5e652016-08-22 08:48:40 -0700258 if (is_rgba(tableColorType)) {
259 SkOpts::RGB_to_RGB1(colorTable + numColorsWithAlpha, palette,
msarett34e0ec42016-04-22 16:27:24 -0700260 numColors - numColorsWithAlpha);
261 } else {
msarettdcd5e652016-08-22 08:48:40 -0700262 SkOpts::RGB_to_BGR1(colorTable + numColorsWithAlpha, palette,
msarett34e0ec42016-04-22 16:27:24 -0700263 numColors - numColorsWithAlpha);
264 }
scroggof24f2242015-03-03 08:59:20 -0800265 }
266
msarettdcd5e652016-08-22 08:48:40 -0700267 // If we are not decoding to F16, we can color xform now and store the results
268 // in the color table.
269 if (fColorXform && kRGBA_F16_SkColorType != dstInfo.colorType()) {
msarettc0444612016-09-16 11:45:58 -0700270 SkColorSpaceXform::ColorFormat xformColorFormat = is_rgba(dstInfo.colorType()) ?
271 SkColorSpaceXform::kRGBA_8888_ColorFormat :
272 SkColorSpaceXform::kBGRA_8888_ColorFormat;
273 SkAlphaType xformAlphaType = select_xform_alpha(dstInfo.alphaType(),
msarette99883f2016-09-08 06:05:35 -0700274 this->getInfo().alphaType());
msarett31d097e82016-10-11 12:15:03 -0700275 SkAssertResult(fColorXform->apply(xformColorFormat, colorTable,
276 SkColorSpaceXform::kRGBA_8888_ColorFormat, colorTable,
277 numColors, xformAlphaType));
msarettdcd5e652016-08-22 08:48:40 -0700278 }
279
msarett13a91232016-02-01 08:03:29 -0800280 // Pad the color table with the last color in the table (or black) in the case that
281 // invalid pixel indices exceed the number of colors in the table.
282 const int maxColors = 1 << fBitDepth;
283 if (numColors < maxColors) {
msarettdcd5e652016-08-22 08:48:40 -0700284 SkPMColor lastColor = numColors > 0 ? colorTable[numColors - 1] : SK_ColorBLACK;
285 sk_memset32(colorTable + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800286 }
287
msarett13a91232016-02-01 08:03:29 -0800288 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700289 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800290 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800291 }
292
msarettdcd5e652016-08-22 08:48:40 -0700293 fColorTable.reset(new SkColorTable(colorTable, maxColors));
scroggo05245902015-03-25 11:11:52 -0700294 return true;
scroggof24f2242015-03-03 08:59:20 -0800295}
296
297///////////////////////////////////////////////////////////////////////////////
298// Creation
299///////////////////////////////////////////////////////////////////////////////
300
scroggodb30be22015-12-08 18:54:13 -0800301bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
302 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800303}
304
scroggo8e6c7ad2016-09-16 08:20:38 -0700305#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
306
msarett6a738212016-03-04 13:27:35 -0800307static float png_fixed_point_to_float(png_fixed_point x) {
308 // We multiply by the same factor that libpng used to convert
309 // fixed point -> double. Since we want floats, we choose to
310 // do the conversion ourselves rather than convert
311 // fixed point -> double -> float.
312 return ((float) x) * 0.00001f;
313}
314
msarett128245c2016-03-30 12:01:47 -0700315static float png_inverted_fixed_point_to_float(png_fixed_point x) {
316 // This is necessary because the gAMA chunk actually stores 1/gamma.
317 return 1.0f / png_fixed_point_to_float(x);
318}
319
msarettc4ce6b52016-06-16 07:37:41 -0700320static constexpr float gSRGB_toXYZD50[] {
brianosmande68d6c2016-09-09 10:36:17 -0700321 0.4358f, 0.3853f, 0.1430f, // Rx, Gx, Bx
322 0.2224f, 0.7170f, 0.0606f, // Ry, Gy, Gz
323 0.0139f, 0.0971f, 0.7139f, // Rz, Gz, Bz
msarettc4ce6b52016-06-16 07:37:41 -0700324};
325
scroggo8e6c7ad2016-09-16 08:20:38 -0700326#endif // LIBPNG >= 1.6
327
msarett6a738212016-03-04 13:27:35 -0800328// Returns a colorSpace object that represents any color space information in
329// the encoded data. If the encoded data contains no color space, this will
330// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800331sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800332
msarette2443222016-03-04 14:20:49 -0800333#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
334
msarett6a738212016-03-04 13:27:35 -0800335 // First check for an ICC profile
336 png_bytep profile;
337 png_uint_32 length;
338 // The below variables are unused, however, we need to pass them in anyway or
339 // png_get_iCCP() will return nothing.
340 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
341 png_charp name;
342 // The |compression| is uninteresting since:
343 // (1) libpng has already decompressed the profile for us.
344 // (2) "deflate" is the only mode of decompression that libpng supports.
345 int compression;
346 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
347 &length)) {
348 return SkColorSpace::NewICC(profile, length);
349 }
350
351 // Second, check for sRGB.
352 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
353
354 // sRGB chunks also store a rendering intent: Absolute, Relative,
355 // Perceptual, and Saturation.
356 // FIXME (msarett): Extract this information from the sRGB chunk once
357 // we are able to handle this information in
358 // SkColorSpace.
359 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
360 }
361
362 // Next, check for chromaticities.
msaretta5a31dd2016-10-11 09:41:16 -0700363 png_fixed_point chrm[8];
msarett6a738212016-03-04 13:27:35 -0800364 png_fixed_point gamma;
msarettbb9f7742016-05-17 09:31:20 -0700365 float gammas[3];
msaretta5a31dd2016-10-11 09:41:16 -0700366 if (png_get_cHRM_fixed(png_ptr, info_ptr, &chrm[0], &chrm[1], &chrm[2], &chrm[3], &chrm[4],
367 &chrm[5], &chrm[6], &chrm[7]))
msarett55447952016-07-22 14:07:23 -0700368 {
msaretta5a31dd2016-10-11 09:41:16 -0700369 SkColorSpacePrimaries primaries;
370 primaries.fRX = png_fixed_point_to_float(chrm[2]);
371 primaries.fRY = png_fixed_point_to_float(chrm[3]);
372 primaries.fGX = png_fixed_point_to_float(chrm[4]);
373 primaries.fGY = png_fixed_point_to_float(chrm[5]);
374 primaries.fBX = png_fixed_point_to_float(chrm[6]);
375 primaries.fBY = png_fixed_point_to_float(chrm[7]);
376 primaries.fWX = png_fixed_point_to_float(chrm[0]);
377 primaries.fWY = png_fixed_point_to_float(chrm[1]);
msarett55447952016-07-22 14:07:23 -0700378
379 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
msaretta5a31dd2016-10-11 09:41:16 -0700380 if (!primaries.toXYZD50(&toXYZD50)) {
msarett55447952016-07-22 14:07:23 -0700381 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
382 }
msarett6a738212016-03-04 13:27:35 -0800383
msarett128245c2016-03-30 12:01:47 -0700384 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
msarettffc2aea2016-05-02 11:12:14 -0700385 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700386 gammas[0] = value;
387 gammas[1] = value;
388 gammas[2] = value;
msarettffc2aea2016-05-02 11:12:14 -0700389
Matt Sarettc434f512016-10-13 18:24:20 -0400390 return SkColorSpace::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800391 }
msarett128245c2016-03-30 12:01:47 -0700392
msarettc4ce6b52016-06-16 07:37:41 -0700393 // Default to sRGB gamma if the image has color space information,
394 // but does not specify gamma.
msarett48ba2b82016-09-07 18:55:49 -0700395 return SkColorSpace::NewRGB(SkColorSpace::kSRGB_RenderTargetGamma, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800396 }
397
398 // Last, check for gamma.
399 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
400
msarett6a738212016-03-04 13:27:35 -0800401 // Set the gammas.
msarettffc2aea2016-05-02 11:12:14 -0700402 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700403 gammas[0] = value;
404 gammas[1] = value;
405 gammas[2] = value;
msarett6a738212016-03-04 13:27:35 -0800406
msarettc4ce6b52016-06-16 07:37:41 -0700407 // Since there is no cHRM, we will guess sRGB gamut.
msarett55447952016-07-22 14:07:23 -0700408 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
409 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
msarettc4ce6b52016-06-16 07:37:41 -0700410
Matt Sarettc434f512016-10-13 18:24:20 -0400411 return SkColorSpace::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800412 }
413
msarette2443222016-03-04 14:20:49 -0800414#endif // LIBPNG >= 1.6
415
msarettc4ce6b52016-06-16 07:37:41 -0700416 // Report that there is no color space information in the PNG. SkPngCodec is currently
417 // implemented to guess sRGB in this case.
msarett6a738212016-03-04 13:27:35 -0800418 return nullptr;
419}
420
msarett400a93b2016-09-01 18:32:52 -0700421void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
422 switch (fXformMode) {
423 case kSwizzleOnly_XformMode:
msarett400a93b2016-09-01 18:32:52 -0700424 break;
425 case kColorOnly_XformMode:
426 // Intentional fall through. A swizzler hasn't been created yet, but one will
427 // be created later if we are sampling. We'll go ahead and allocate
428 // enough memory to swizzle if necessary.
429 case kSwizzleColor_XformMode: {
scroggo8e6c7ad2016-09-16 08:20:38 -0700430 const size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t);
431 fStorage.reset(colorXformBytes);
432 fColorXformSrcRow = (uint32_t*) fStorage.get();
msarett400a93b2016-09-01 18:32:52 -0700433 break;
434 }
435 }
msarettd1ec89b2016-08-03 12:59:27 -0700436}
437
scroggo8e6c7ad2016-09-16 08:20:38 -0700438void SkPngCodec::applyXformRow(void* dst, const void* src) {
msarettcf7b8772016-09-22 12:37:04 -0700439 const SkColorSpaceXform::ColorFormat srcColorFormat = SkColorSpaceXform::kRGBA_8888_ColorFormat;
msarett400a93b2016-09-01 18:32:52 -0700440 switch (fXformMode) {
441 case kSwizzleOnly_XformMode:
442 fSwizzler->swizzle(dst, (const uint8_t*) src);
443 break;
444 case kColorOnly_XformMode:
msarett31d097e82016-10-11 12:15:03 -0700445 SkAssertResult(fColorXform->apply(fXformColorFormat, dst, srcColorFormat, src,
446 fXformWidth, fXformAlphaType));
msarett400a93b2016-09-01 18:32:52 -0700447 break;
448 case kSwizzleColor_XformMode:
449 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src);
msarett31d097e82016-10-11 12:15:03 -0700450 SkAssertResult(fColorXform->apply(fXformColorFormat, dst, srcColorFormat, fColorXformSrcRow,
451 fXformWidth, fXformAlphaType));
msarett400a93b2016-09-01 18:32:52 -0700452 break;
453 }
msarettdcd5e652016-08-22 08:48:40 -0700454}
455
scroggo8e6c7ad2016-09-16 08:20:38 -0700456class SkPngNormalDecoder : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700457public:
scroggo8e6c7ad2016-09-16 08:20:38 -0700458 SkPngNormalDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo, SkStream* stream,
459 SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr, int bitDepth)
460 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
scroggoff9f7bb2016-10-10 11:35:01 -0700461 , fRowsWrittenToOutput(0)
scroggo8e6c7ad2016-09-16 08:20:38 -0700462 , fDst(nullptr)
463 , fRowBytes(0)
464 , fFirstRow(0)
465 , fLastRow(0)
scroggo1c005e42015-08-04 09:24:45 -0700466 {}
467
scroggo8e6c7ad2016-09-16 08:20:38 -0700468 static void AllRowsCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
469 GetDecoder(png_ptr)->allRowsCallback(row, rowNum);
scroggo05245902015-03-25 11:11:52 -0700470 }
471
scroggo8e6c7ad2016-09-16 08:20:38 -0700472 static void RowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
473 GetDecoder(png_ptr)->rowCallback(row, rowNum);
msarettd1ec89b2016-08-03 12:59:27 -0700474 }
475
scroggo8e6c7ad2016-09-16 08:20:38 -0700476#ifdef SK_GOOGLE3_PNG_HACK
477 static void RereadInfoCallback(png_structp png_ptr, png_infop) {
478 GetDecoder(png_ptr)->rereadInfoCallback();
scroggo05245902015-03-25 11:11:52 -0700479 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700480#endif
emmaleer8f4ba762015-08-14 07:44:46 -0700481
emmaleer0a4c3cb2015-06-22 10:40:21 -0700482private:
scroggoff9f7bb2016-10-10 11:35:01 -0700483 int fRowsWrittenToOutput;
scroggo8e6c7ad2016-09-16 08:20:38 -0700484 void* fDst;
485 size_t fRowBytes;
486
487 // Variables for partial decode
488 int fFirstRow; // FIXME: Move to baseclass?
489 int fLastRow;
scroggo4f2a88c2016-10-17 14:32:41 -0700490 int fRowsNeeded;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700491
scroggo46c57472015-09-30 08:57:13 -0700492 typedef SkPngCodec INHERITED;
scroggo8e6c7ad2016-09-16 08:20:38 -0700493
494 static SkPngNormalDecoder* GetDecoder(png_structp png_ptr) {
495 return static_cast<SkPngNormalDecoder*>(png_get_progressive_ptr(png_ptr));
496 }
497
498 Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
499 const int height = this->getInfo().height();
500 png_progressive_info_ptr callback = nullptr;
501#ifdef SK_GOOGLE3_PNG_HACK
502 callback = RereadInfoCallback;
503#endif
504 png_set_progressive_read_fn(this->png_ptr(), this, callback, AllRowsCallback, nullptr);
505 fDst = dst;
506 fRowBytes = rowBytes;
507
scroggoff9f7bb2016-10-10 11:35:01 -0700508 fRowsWrittenToOutput = 0;
scroggoc46cdd42016-10-10 06:45:32 -0700509 fFirstRow = 0;
510 fLastRow = height - 1;
scroggo8e6c7ad2016-09-16 08:20:38 -0700511
512 this->processData();
513
scroggoff9f7bb2016-10-10 11:35:01 -0700514 if (fRowsWrittenToOutput == height) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700515 return SkCodec::kSuccess;
516 }
517
518 if (rowsDecoded) {
scroggoff9f7bb2016-10-10 11:35:01 -0700519 *rowsDecoded = fRowsWrittenToOutput;
scroggo8e6c7ad2016-09-16 08:20:38 -0700520 }
521
522 return SkCodec::kIncompleteInput;
523 }
524
525 void allRowsCallback(png_bytep row, int rowNum) {
scroggoff9f7bb2016-10-10 11:35:01 -0700526 SkASSERT(rowNum == fRowsWrittenToOutput);
527 fRowsWrittenToOutput++;
scroggo8e6c7ad2016-09-16 08:20:38 -0700528 this->applyXformRow(fDst, row);
529 fDst = SkTAddOffset<void>(fDst, fRowBytes);
530 }
531
532 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
533 png_progressive_info_ptr callback = nullptr;
534#ifdef SK_GOOGLE3_PNG_HACK
535 callback = RereadInfoCallback;
536#endif
537 png_set_progressive_read_fn(this->png_ptr(), this, callback, RowCallback, nullptr);
538 fFirstRow = firstRow;
539 fLastRow = lastRow;
540 fDst = dst;
541 fRowBytes = rowBytes;
scroggoff9f7bb2016-10-10 11:35:01 -0700542 fRowsWrittenToOutput = 0;
scroggo4f2a88c2016-10-17 14:32:41 -0700543 fRowsNeeded = fLastRow - fFirstRow + 1;
scroggo8e6c7ad2016-09-16 08:20:38 -0700544 }
545
546 SkCodec::Result decode(int* rowsDecoded) override {
scroggo4f2a88c2016-10-17 14:32:41 -0700547 if (this->swizzler()) {
548 const int sampleY = this->swizzler()->sampleY();
549 fRowsNeeded = get_scaled_dimension(fLastRow - fFirstRow + 1, sampleY);
550 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700551 this->processData();
552
scroggo4f2a88c2016-10-17 14:32:41 -0700553 if (fRowsWrittenToOutput == fRowsNeeded) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700554 return SkCodec::kSuccess;
555 }
556
557 if (rowsDecoded) {
scroggoff9f7bb2016-10-10 11:35:01 -0700558 *rowsDecoded = fRowsWrittenToOutput;
scroggo8e6c7ad2016-09-16 08:20:38 -0700559 }
560
561 return SkCodec::kIncompleteInput;
562 }
563
564 void rowCallback(png_bytep row, int rowNum) {
565 if (rowNum < fFirstRow) {
566 // Ignore this row.
567 return;
568 }
569
570 SkASSERT(rowNum <= fLastRow);
scroggo4f2a88c2016-10-17 14:32:41 -0700571 SkASSERT(fRowsWrittenToOutput < fRowsNeeded);
scroggo8e6c7ad2016-09-16 08:20:38 -0700572
573 // If there is no swizzler, all rows are needed.
scroggo4f2a88c2016-10-17 14:32:41 -0700574 if (!this->swizzler() || this->swizzler()->rowNeeded(rowNum - fFirstRow)) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700575 this->applyXformRow(fDst, row);
576 fDst = SkTAddOffset<void>(fDst, fRowBytes);
scroggoff9f7bb2016-10-10 11:35:01 -0700577 fRowsWrittenToOutput++;
scroggo8e6c7ad2016-09-16 08:20:38 -0700578 }
579
scroggo4f2a88c2016-10-17 14:32:41 -0700580 if (fRowsWrittenToOutput == fRowsNeeded) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700581 // Fake error to stop decoding scanlines.
582 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
583 }
584 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700585};
586
scroggo8e6c7ad2016-09-16 08:20:38 -0700587class SkPngInterlacedDecoder : public SkPngCodec {
588public:
589 SkPngInterlacedDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo,
590 SkStream* stream, SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr,
591 int bitDepth, int numberPasses)
592 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
593 , fNumberPasses(numberPasses)
594 , fFirstRow(0)
595 , fLastRow(0)
596 , fLinesDecoded(0)
597 , fInterlacedComplete(false)
598 , fPng_rowbytes(0)
599 {}
600
601 static void InterlacedRowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int pass) {
602 auto decoder = static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr));
603 decoder->interlacedRowCallback(row, rowNum, pass);
604 }
605
606#ifdef SK_GOOGLE3_PNG_HACK
607 static void RereadInfoInterlacedCallback(png_structp png_ptr, png_infop) {
608 static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr))->rereadInfoInterlaced();
609 }
610#endif
611
612private:
613 const int fNumberPasses;
614 int fFirstRow;
615 int fLastRow;
616 void* fDst;
617 size_t fRowBytes;
618 int fLinesDecoded;
619 bool fInterlacedComplete;
620 size_t fPng_rowbytes;
621 SkAutoTMalloc<png_byte> fInterlaceBuffer;
622
623 typedef SkPngCodec INHERITED;
624
625#ifdef SK_GOOGLE3_PNG_HACK
626 void rereadInfoInterlaced() {
627 this->rereadInfoCallback();
628 // Note: This allocates more memory than necessary, if we are sampling/subset.
629 this->setUpInterlaceBuffer(this->getInfo().height());
630 }
631#endif
632
633 // FIXME: Currently sharing interlaced callback for all rows and subset. It's not
634 // as expensive as the subset version of non-interlaced, but it still does extra
635 // work.
636 void interlacedRowCallback(png_bytep row, int rowNum, int pass) {
637 if (rowNum < fFirstRow || rowNum > fLastRow) {
638 // Ignore this row
639 return;
640 }
641
642 png_bytep oldRow = fInterlaceBuffer.get() + (rowNum - fFirstRow) * fPng_rowbytes;
643 png_progressive_combine_row(this->png_ptr(), oldRow, row);
644
645 if (0 == pass) {
646 // The first pass initializes all rows.
647 SkASSERT(row);
648 SkASSERT(fLinesDecoded == rowNum - fFirstRow);
649 fLinesDecoded++;
650 } else {
651 SkASSERT(fLinesDecoded == fLastRow - fFirstRow + 1);
652 if (fNumberPasses - 1 == pass && rowNum == fLastRow) {
653 // Last pass, and we have read all of the rows we care about. Note that
654 // we do not care about reading anything beyond the end of the image (or
655 // beyond the last scanline requested).
656 fInterlacedComplete = true;
657 // Fake error to stop decoding scanlines.
658 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
659 }
660 }
661 }
662
663 SkCodec::Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
664 const int height = this->getInfo().height();
665 this->setUpInterlaceBuffer(height);
666 png_progressive_info_ptr callback = nullptr;
667#ifdef SK_GOOGLE3_PNG_HACK
668 callback = RereadInfoInterlacedCallback;
669#endif
670 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedRowCallback,
671 nullptr);
672
673 fFirstRow = 0;
674 fLastRow = height - 1;
675 fLinesDecoded = 0;
676
677 this->processData();
678
679 png_bytep srcRow = fInterlaceBuffer.get();
680 // FIXME: When resuming, this may rewrite rows that did not change.
681 for (int rowNum = 0; rowNum < fLinesDecoded; rowNum++) {
682 this->applyXformRow(dst, srcRow);
683 dst = SkTAddOffset<void>(dst, rowBytes);
684 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes);
685 }
686 if (fInterlacedComplete) {
687 return SkCodec::kSuccess;
688 }
689
690 if (rowsDecoded) {
691 *rowsDecoded = fLinesDecoded;
692 }
693
694 return SkCodec::kIncompleteInput;
695 }
696
697 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
698 // FIXME: We could skip rows in the interlace buffer that we won't put in the output.
699 this->setUpInterlaceBuffer(lastRow - firstRow + 1);
700 png_progressive_info_ptr callback = nullptr;
701#ifdef SK_GOOGLE3_PNG_HACK
702 callback = RereadInfoInterlacedCallback;
703#endif
704 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedRowCallback, nullptr);
705 fFirstRow = firstRow;
706 fLastRow = lastRow;
707 fDst = dst;
708 fRowBytes = rowBytes;
709 fLinesDecoded = 0;
710 }
711
712 SkCodec::Result decode(int* rowsDecoded) override {
713 this->processData();
714
715 // Now apply Xforms on all the rows that were decoded.
716 if (!fLinesDecoded) {
scroggoe61b3b42016-10-10 07:17:32 -0700717 if (rowsDecoded) {
718 *rowsDecoded = 0;
719 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700720 return SkCodec::kIncompleteInput;
721 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700722
scroggo4f2a88c2016-10-17 14:32:41 -0700723 const int sampleY = this->swizzler() ? this->swizzler()->sampleY() : 1;
724 const int rowsNeeded = get_scaled_dimension(fLastRow - fFirstRow + 1, sampleY);
scroggoff9f7bb2016-10-10 11:35:01 -0700725 int rowsWrittenToOutput = 0;
726
scroggo8e6c7ad2016-09-16 08:20:38 -0700727 // FIXME: For resuming interlace, we may swizzle a row that hasn't changed. But it
728 // may be too tricky/expensive to handle that correctly.
scroggoe9ea3492016-10-18 09:14:11 -0700729
730 // Offset srcRow by get_start_coord rows. We do not need to account for fFirstRow,
731 // since the first row in fInterlaceBuffer corresponds to fFirstRow.
732 png_bytep srcRow = SkTAddOffset<png_byte>(fInterlaceBuffer.get(),
733 fPng_rowbytes * get_start_coord(sampleY));
scroggo8e6c7ad2016-09-16 08:20:38 -0700734 void* dst = fDst;
scroggoe9ea3492016-10-18 09:14:11 -0700735 for (; rowsWrittenToOutput < rowsNeeded; rowsWrittenToOutput++) {
scroggo8e6c7ad2016-09-16 08:20:38 -0700736 this->applyXformRow(dst, srcRow);
737 dst = SkTAddOffset<void>(dst, fRowBytes);
738 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes * sampleY);
739 }
740
741 if (fInterlacedComplete) {
742 return SkCodec::kSuccess;
743 }
744
745 if (rowsDecoded) {
scroggoff9f7bb2016-10-10 11:35:01 -0700746 *rowsDecoded = rowsWrittenToOutput;
scroggo8e6c7ad2016-09-16 08:20:38 -0700747 }
748 return SkCodec::kIncompleteInput;
749 }
750
751 void setUpInterlaceBuffer(int height) {
752 fPng_rowbytes = png_get_rowbytes(this->png_ptr(), this->info_ptr());
753 fInterlaceBuffer.reset(fPng_rowbytes * height);
754 fInterlacedComplete = false;
755 }
756};
757
758#ifdef SK_GOOGLE3_PNG_HACK
759bool SkPngCodec::rereadHeaderIfNecessary() {
760 if (!fNeedsToRereadHeader) {
761 return true;
762 }
763
764 // On the first call, we'll need to rewind ourselves. Future calls will
765 // have already rewound in rewindIfNecessary.
766 if (this->stream()->getPosition() > 0) {
767 this->stream()->rewind();
768 }
769
770 this->destroyReadStruct();
771 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
772 sk_error_fn, sk_warning_fn);
773 if (!png_ptr) {
774 return false;
775 }
776
777 // Only use the AutoCleanPng to delete png_ptr as necessary.
778 // (i.e. not for reading bounds etc.)
779 AutoCleanPng autoClean(png_ptr, nullptr, nullptr, nullptr);
780
781 png_infop info_ptr = png_create_info_struct(png_ptr);
782 if (info_ptr == nullptr) {
783 return false;
784 }
785
786 autoClean.setInfoPtr(info_ptr);
787
788#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
789 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
790 // This needs to be installed before we read the png header. Android may store ninepatch
791 // chunks in the header.
792 if (fPngChunkReader.get()) {
793 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
794 png_set_read_user_chunk_fn(png_ptr, (png_voidp) fPngChunkReader.get(), sk_read_user_chunk);
795 }
796#endif
797
798 fPng_ptr = png_ptr;
799 fInfo_ptr = info_ptr;
800 autoClean.releasePngPtrs();
801 fNeedsToRereadHeader = false;
802 return true;
803}
804#endif // SK_GOOGLE3_PNG_HACK
805
msarettac6c7502016-04-25 09:30:24 -0700806// Reads the header and initializes the output fields, if not NULL.
807//
808// @param stream Input data. Will be read to get enough information to properly
809// setup the codec.
810// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
811// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
812// expected to continue to own it for the lifetime of the png_ptr.
813// @param outCodec Optional output variable. If non-NULL, will be set to a new
814// SkPngCodec on success.
815// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
816// png_structp on success.
817// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
818// png_infop on success;
819// @return true on success, in which case the caller is responsible for calling
820// png_destroy_read_struct(png_ptrp, info_ptrp).
821// If it returns false, the passed in fields (except stream) are unchanged.
822static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec** outCodec,
823 png_structp* png_ptrp, png_infop* info_ptrp) {
824 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
825 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
826 sk_error_fn, sk_warning_fn);
827 if (!png_ptr) {
828 return false;
829 }
830
scroggo8e6c7ad2016-09-16 08:20:38 -0700831 AutoCleanPng autoClean(png_ptr, stream, chunkReader, outCodec);
msarettac6c7502016-04-25 09:30:24 -0700832
833 png_infop info_ptr = png_create_info_struct(png_ptr);
834 if (info_ptr == nullptr) {
835 return false;
836 }
837
838 autoClean.setInfoPtr(info_ptr);
839
840 // FIXME: Could we use the return value of setjmp to specify the type of
841 // error?
scroggo8e6c7ad2016-09-16 08:20:38 -0700842 if (setjmp(PNG_JMPBUF(png_ptr))) {
msarettac6c7502016-04-25 09:30:24 -0700843 return false;
844 }
845
msarettac6c7502016-04-25 09:30:24 -0700846#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
847 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
848 // This needs to be installed before we read the png header. Android may store ninepatch
849 // chunks in the header.
850 if (chunkReader) {
851 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
852 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
853 }
854#endif
855
scroggo8e6c7ad2016-09-16 08:20:38 -0700856 const bool decodedBounds = autoClean.decodeBounds();
857
858 if (!decodedBounds) {
859 return false;
860 }
861
862 // On success, decodeBounds releases ownership of png_ptr and info_ptr.
863 if (png_ptrp) {
864 *png_ptrp = png_ptr;
865 }
866 if (info_ptrp) {
867 *info_ptrp = info_ptr;
868 }
869
870 // decodeBounds takes care of setting outCodec
871 if (outCodec) {
872 SkASSERT(*outCodec);
873 }
874 return true;
875}
876
877// FIXME (scroggo): Once SK_GOOGLE3_PNG_HACK is no more, this method can be inline in
878// AutoCleanPng::infoCallback
879static void general_info_callback(png_structp png_ptr, png_infop info_ptr,
880 SkEncodedInfo::Color* outColor, SkEncodedInfo::Alpha* outAlpha) {
msarettac6c7502016-04-25 09:30:24 -0700881 png_uint_32 origWidth, origHeight;
882 int bitDepth, encodedColorType;
scroggod8d68552016-06-06 11:26:17 -0700883 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarettac6c7502016-04-25 09:30:24 -0700884 &encodedColorType, nullptr, nullptr, nullptr);
885
886 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
887 // TODO: Should we handle this in SkSwizzler? Could this also benefit
888 // RAW decodes?
889 if (bitDepth == 16) {
890 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggod8d68552016-06-06 11:26:17 -0700891 png_set_strip_16(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700892 }
893
894 // Now determine the default colorType and alphaType and set the required transforms.
895 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
896 // still depend on libpng for many of the rare and PNG-specific cases.
897 SkEncodedInfo::Color color;
898 SkEncodedInfo::Alpha alpha;
899 switch (encodedColorType) {
900 case PNG_COLOR_TYPE_PALETTE:
901 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
902 // byte into separate bytes (useful for paletted and grayscale images).
903 if (bitDepth < 8) {
904 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700905 png_set_packing(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700906 }
907
908 color = SkEncodedInfo::kPalette_Color;
909 // Set the alpha depending on if a transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700910 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
msarettac6c7502016-04-25 09:30:24 -0700911 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
912 break;
913 case PNG_COLOR_TYPE_RGB:
scroggod8d68552016-06-06 11:26:17 -0700914 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
msarettac6c7502016-04-25 09:30:24 -0700915 // Convert to RGBA if transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700916 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700917 color = SkEncodedInfo::kRGBA_Color;
918 alpha = SkEncodedInfo::kBinary_Alpha;
919 } else {
920 color = SkEncodedInfo::kRGB_Color;
921 alpha = SkEncodedInfo::kOpaque_Alpha;
922 }
923 break;
924 case PNG_COLOR_TYPE_GRAY:
925 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
926 if (bitDepth < 8) {
927 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700928 png_set_expand_gray_1_2_4_to_8(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700929 }
930
scroggod8d68552016-06-06 11:26:17 -0700931 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
932 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700933 color = SkEncodedInfo::kGrayAlpha_Color;
934 alpha = SkEncodedInfo::kBinary_Alpha;
935 } else {
936 color = SkEncodedInfo::kGray_Color;
937 alpha = SkEncodedInfo::kOpaque_Alpha;
938 }
939 break;
940 case PNG_COLOR_TYPE_GRAY_ALPHA:
941 color = SkEncodedInfo::kGrayAlpha_Color;
942 alpha = SkEncodedInfo::kUnpremul_Alpha;
943 break;
944 case PNG_COLOR_TYPE_RGBA:
945 color = SkEncodedInfo::kRGBA_Color;
946 alpha = SkEncodedInfo::kUnpremul_Alpha;
947 break;
948 default:
949 // All the color types have been covered above.
950 SkASSERT(false);
951 color = SkEncodedInfo::kRGBA_Color;
952 alpha = SkEncodedInfo::kUnpremul_Alpha;
953 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700954 if (outColor) {
955 *outColor = color;
scroggo9a89a092016-05-31 13:52:47 -0700956 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700957 if (outAlpha) {
958 *outAlpha = alpha;
scroggod8d68552016-06-06 11:26:17 -0700959 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700960}
scroggod8d68552016-06-06 11:26:17 -0700961
scroggo8e6c7ad2016-09-16 08:20:38 -0700962#ifdef SK_GOOGLE3_PNG_HACK
963void SkPngCodec::rereadInfoCallback() {
964 general_info_callback(fPng_ptr, fInfo_ptr, nullptr, nullptr);
965 png_set_interlace_handling(fPng_ptr);
966 png_read_update_info(fPng_ptr, fInfo_ptr);
967}
968#endif
969
970void AutoCleanPng::infoCallback() {
971 SkEncodedInfo::Color color;
972 SkEncodedInfo::Alpha alpha;
973 general_info_callback(fPng_ptr, fInfo_ptr, &color, &alpha);
974
975 const int numberPasses = png_set_interlace_handling(fPng_ptr);
976
977 fReadHeader = true;
978 fDecodedBounds = true;
979#ifndef SK_GOOGLE3_PNG_HACK
980 // 1 tells libpng to save any extra data. We may be able to be more efficient by saving
981 // it ourselves.
982 png_process_data_pause(fPng_ptr, 1);
983#else
984 // Hack to make png_process_data stop.
985 fPng_ptr->buffer_size = 0;
986#endif
987 if (fOutCodec) {
988 SkASSERT(nullptr == *fOutCodec);
989 sk_sp<SkColorSpace> colorSpace = read_color_space(fPng_ptr, fInfo_ptr);
msarettf34cd632016-05-25 10:13:53 -0700990 if (!colorSpace) {
991 // Treat unmarked pngs as sRGB.
992 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
993 }
scroggod8d68552016-06-06 11:26:17 -0700994
msarett549ca322016-08-17 08:54:08 -0700995 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
scroggo8e6c7ad2016-09-16 08:20:38 -0700996 // FIXME (scroggo): Once we get rid of SK_GOOGLE3_PNG_HACK, general_info_callback can
997 // be inlined, so these values will already be set.
998 png_uint_32 origWidth = png_get_image_width(fPng_ptr, fInfo_ptr);
999 png_uint_32 origHeight = png_get_image_height(fPng_ptr, fInfo_ptr);
1000 png_byte bitDepth = png_get_bit_depth(fPng_ptr, fInfo_ptr);
msarett549ca322016-08-17 08:54:08 -07001001 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
1002
1003 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
1004 png_color_8p sigBits;
scroggo8e6c7ad2016-09-16 08:20:38 -07001005 if (png_get_sBIT(fPng_ptr, fInfo_ptr, &sigBits)) {
msarett549ca322016-08-17 08:54:08 -07001006 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->blue) {
1007 // Recommend a decode to 565 if the sBIT indicates 565.
1008 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
1009 }
1010 }
1011 }
scroggod8d68552016-06-06 11:26:17 -07001012
msarettac6c7502016-04-25 09:30:24 -07001013 if (1 == numberPasses) {
scroggo8e6c7ad2016-09-16 08:20:38 -07001014 *fOutCodec = new SkPngNormalDecoder(encodedInfo, imageInfo, fStream,
1015 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth);
msarettac6c7502016-04-25 09:30:24 -07001016 } else {
scroggo8e6c7ad2016-09-16 08:20:38 -07001017 *fOutCodec = new SkPngInterlacedDecoder(encodedInfo, imageInfo, fStream,
1018 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth, numberPasses);
msarettac6c7502016-04-25 09:30:24 -07001019 }
1020 }
1021
scroggo8e6c7ad2016-09-16 08:20:38 -07001022
1023 // Release the pointers, which are now owned by the codec or the caller is expected to
1024 // take ownership.
1025 this->releasePngPtrs();
msarettac6c7502016-04-25 09:30:24 -07001026}
1027
msarett549ca322016-08-17 08:54:08 -07001028SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
mtklein6dc5b9a2016-08-24 12:22:32 -07001029 SkStream* stream, SkPngChunkReader* chunkReader, void* png_ptr,
scroggo8e6c7ad2016-09-16 08:20:38 -07001030 void* info_ptr, int bitDepth)
msarett549ca322016-08-17 08:54:08 -07001031 : INHERITED(encodedInfo, imageInfo, stream)
msarettac6c7502016-04-25 09:30:24 -07001032 , fPngChunkReader(SkSafeRef(chunkReader))
1033 , fPng_ptr(png_ptr)
1034 , fInfo_ptr(info_ptr)
msarettd1ec89b2016-08-03 12:59:27 -07001035 , fColorXformSrcRow(nullptr)
msarettac6c7502016-04-25 09:30:24 -07001036 , fBitDepth(bitDepth)
scroggo8e6c7ad2016-09-16 08:20:38 -07001037#ifdef SK_GOOGLE3_PNG_HACK
1038 , fNeedsToRereadHeader(true)
1039#endif
msarettac6c7502016-04-25 09:30:24 -07001040{}
1041
1042SkPngCodec::~SkPngCodec() {
1043 this->destroyReadStruct();
1044}
1045
1046void SkPngCodec::destroyReadStruct() {
1047 if (fPng_ptr) {
1048 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
1049 SkASSERT(fInfo_ptr);
mtklein6dc5b9a2016-08-24 12:22:32 -07001050 png_destroy_read_struct((png_struct**)&fPng_ptr, (png_info**)&fInfo_ptr, nullptr);
msarettac6c7502016-04-25 09:30:24 -07001051 fPng_ptr = nullptr;
1052 fInfo_ptr = nullptr;
1053 }
1054}
1055
1056///////////////////////////////////////////////////////////////////////////////
1057// Getting the pixels
1058///////////////////////////////////////////////////////////////////////////////
1059
msarettd1ec89b2016-08-03 12:59:27 -07001060bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& options,
1061 SkPMColor ctable[], int* ctableCount) {
scroggo8e6c7ad2016-09-16 08:20:38 -07001062 if (setjmp(PNG_JMPBUF((png_struct*)fPng_ptr))) {
msarettd1ec89b2016-08-03 12:59:27 -07001063 SkCodecPrintf("Failed on png_read_update_info.\n");
1064 return false;
msarettac6c7502016-04-25 09:30:24 -07001065 }
1066 png_read_update_info(fPng_ptr, fInfo_ptr);
1067
msarett400a93b2016-09-01 18:32:52 -07001068 // Reset fSwizzler and fColorXform. We can't do this in onRewind() because the
1069 // interlaced scanline decoder may need to rewind.
1070 fSwizzler.reset(nullptr);
msarettd1ec89b2016-08-03 12:59:27 -07001071 fColorXform = nullptr;
msarett400a93b2016-09-01 18:32:52 -07001072
msarett2ecc35f2016-09-08 11:55:16 -07001073 if (needs_color_xform(dstInfo, this->getInfo())) {
msarett4be0e7c2016-09-22 07:02:24 -07001074 fColorXform = SkColorSpaceXform::New(this->getInfo().colorSpace(), dstInfo.colorSpace());
msarett2ecc35f2016-09-08 11:55:16 -07001075 SkASSERT(fColorXform);
msarett400a93b2016-09-01 18:32:52 -07001076 }
msarettd3317422016-08-22 13:00:05 -07001077
msarett400a93b2016-09-01 18:32:52 -07001078 // If the image is RGBA and we have a color xform, we can skip the swizzler.
1079 // FIXME (msarett):
1080 // Support more input types to fColorXform (ex: RGB, Gray) and skip the swizzler more often.
1081 if (fColorXform && SkEncodedInfo::kRGBA_Color == this->getEncodedInfo().color() &&
1082 !options.fSubset)
1083 {
1084 fXformMode = kColorOnly_XformMode;
1085 return true;
msarettd1ec89b2016-08-03 12:59:27 -07001086 }
1087
msarettac6c7502016-04-25 09:30:24 -07001088 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
msarettdcd5e652016-08-22 08:48:40 -07001089 if (!this->createColorTable(dstInfo, ctableCount)) {
msarettd1ec89b2016-08-03 12:59:27 -07001090 return false;
msarettac6c7502016-04-25 09:30:24 -07001091 }
1092 }
1093
msarett400a93b2016-09-01 18:32:52 -07001094 // Copy the color table to the client if they request kIndex8 mode.
1095 copy_color_table(dstInfo, fColorTable, ctable, ctableCount);
msarettac6c7502016-04-25 09:30:24 -07001096
msarett400a93b2016-09-01 18:32:52 -07001097 this->initializeSwizzler(dstInfo, options);
1098 return true;
1099}
1100
msarettc0444612016-09-16 11:45:58 -07001101void SkPngCodec::initializeXformParams() {
1102 switch (fXformMode) {
1103 case kColorOnly_XformMode:
1104 fXformColorFormat = select_xform_format(this->dstInfo().colorType());
1105 fXformAlphaType = select_xform_alpha(this->dstInfo().alphaType(),
1106 this->getInfo().alphaType());
1107 fXformWidth = this->dstInfo().width();
1108 break;
1109 case kSwizzleColor_XformMode:
1110 fXformColorFormat = select_xform_format(this->dstInfo().colorType());
1111 fXformAlphaType = select_xform_alpha(this->dstInfo().alphaType(),
1112 this->getInfo().alphaType());
1113 fXformWidth = this->swizzler()->swizzleWidth();
1114 break;
1115 default:
1116 break;
1117 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001118}
1119
msarett400a93b2016-09-01 18:32:52 -07001120static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo::Color srcColor) {
1121 // We will apply the color xform when reading the color table, unless F16 is requested.
1122 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType;
1123}
1124
1125void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options) {
1126 SkImageInfo swizzlerInfo = dstInfo;
1127 Options swizzlerOptions = options;
1128 fXformMode = kSwizzleOnly_XformMode;
1129 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color())) {
1130 swizzlerInfo = swizzlerInfo.makeColorType(kRGBA_8888_SkColorType);
1131 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
1132 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
1133 }
1134
1135 fXformMode = kSwizzleColor_XformMode;
1136
1137 // Here, we swizzle into temporary memory, which is not zero initialized.
1138 // FIXME (msarett):
1139 // Is this a problem?
1140 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
1141 }
1142
msarettac6c7502016-04-25 09:30:24 -07001143 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettd1ec89b2016-08-03 12:59:27 -07001144 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colors, swizzlerInfo,
msarettd3317422016-08-22 13:00:05 -07001145 swizzlerOptions));
msarettac6c7502016-04-25 09:30:24 -07001146 SkASSERT(fSwizzler);
msarett400a93b2016-09-01 18:32:52 -07001147}
1148
1149SkSampler* SkPngCodec::getSampler(bool createIfNecessary) {
1150 if (fSwizzler || !createIfNecessary) {
1151 return fSwizzler;
1152 }
1153
1154 this->initializeSwizzler(this->dstInfo(), this->options());
1155 return fSwizzler;
msarettac6c7502016-04-25 09:30:24 -07001156}
1157
msarettac6c7502016-04-25 09:30:24 -07001158bool SkPngCodec::onRewind() {
scroggo8e6c7ad2016-09-16 08:20:38 -07001159#ifdef SK_GOOGLE3_PNG_HACK
1160 fNeedsToRereadHeader = true;
1161 return true;
1162#else
msarettac6c7502016-04-25 09:30:24 -07001163 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
1164 // succeeds, they will be repopulated, and if it fails, they will
1165 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
1166 // come through this function which will rewind and again attempt
1167 // to reinitialize them.
1168 this->destroyReadStruct();
1169
scroggo46c57472015-09-30 08:57:13 -07001170 png_structp png_ptr;
1171 png_infop info_ptr;
msarettac6c7502016-04-25 09:30:24 -07001172 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, &info_ptr)) {
1173 return false;
scroggo05245902015-03-25 11:11:52 -07001174 }
1175
msarettac6c7502016-04-25 09:30:24 -07001176 fPng_ptr = png_ptr;
1177 fInfo_ptr = info_ptr;
1178 return true;
scroggo8e6c7ad2016-09-16 08:20:38 -07001179#endif
msarettac6c7502016-04-25 09:30:24 -07001180}
msarett6a738212016-03-04 13:27:35 -08001181
msarettd1ec89b2016-08-03 12:59:27 -07001182SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
1183 size_t rowBytes, const Options& options,
msarettac6c7502016-04-25 09:30:24 -07001184 SkPMColor ctable[], int* ctableCount,
1185 int* rowsDecoded) {
msarett2ecc35f2016-09-08 11:55:16 -07001186 if (!conversion_possible(dstInfo, this->getInfo()) ||
msarettd1ec89b2016-08-03 12:59:27 -07001187 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1188 {
msarettac6c7502016-04-25 09:30:24 -07001189 return kInvalidConversion;
1190 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001191#ifdef SK_GOOGLE3_PNG_HACK
1192 // Note that this is done after initializeXforms. Otherwise that method
1193 // would not have png_ptr to use.
1194 if (!this->rereadHeaderIfNecessary()) {
1195 return kCouldNotRewind;
1196 }
1197#endif
msarettd1ec89b2016-08-03 12:59:27 -07001198
msarettac6c7502016-04-25 09:30:24 -07001199 if (options.fSubset) {
msarettac6c7502016-04-25 09:30:24 -07001200 return kUnimplemented;
scroggo05245902015-03-25 11:11:52 -07001201 }
1202
msarett400a93b2016-09-01 18:32:52 -07001203 this->allocateStorage(dstInfo);
msarettc0444612016-09-16 11:45:58 -07001204 this->initializeXformParams();
scroggo8e6c7ad2016-09-16 08:20:38 -07001205 return this->decodeAllRows(dst, rowBytes, rowsDecoded);
1206}
msarettac6c7502016-04-25 09:30:24 -07001207
scroggo8e6c7ad2016-09-16 08:20:38 -07001208SkCodec::Result SkPngCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
1209 void* dst, size_t rowBytes, const SkCodec::Options& options,
1210 SkPMColor* ctable, int* ctableCount) {
1211 if (!conversion_possible(dstInfo, this->getInfo()) ||
1212 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1213 {
1214 return kInvalidConversion;
1215 }
1216#ifdef SK_GOOGLE3_PNG_HACK
1217 // See note in onGetPixels.
1218 if (!this->rereadHeaderIfNecessary()) {
1219 return kCouldNotRewind;
1220 }
1221#endif
1222
1223 this->allocateStorage(dstInfo);
1224
1225 int firstRow, lastRow;
1226 if (options.fSubset) {
1227 firstRow = options.fSubset->top();
1228 lastRow = options.fSubset->bottom() - 1;
1229 } else {
1230 firstRow = 0;
1231 lastRow = dstInfo.height() - 1;
1232 }
1233 this->setRange(firstRow, lastRow, dst, rowBytes);
scroggod8d68552016-06-06 11:26:17 -07001234 return kSuccess;
scroggo6fb23912016-06-02 14:16:43 -07001235}
1236
scroggo8e6c7ad2016-09-16 08:20:38 -07001237SkCodec::Result SkPngCodec::onIncrementalDecode(int* rowsDecoded) {
1238 // FIXME: Only necessary on the first call.
msarettc0444612016-09-16 11:45:58 -07001239 this->initializeXformParams();
scroggo8e6c7ad2016-09-16 08:20:38 -07001240
1241 return this->decode(rowsDecoded);
1242}
1243
msarettf7eb6fc2016-09-13 09:04:11 -07001244uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
msarettac6c7502016-04-25 09:30:24 -07001245 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
1246 if (colorPtr) {
msarettc0444612016-09-16 11:45:58 -07001247 SkAlphaType alphaType = select_xform_alpha(dstInfo.alphaType(),
msarettf7eb6fc2016-09-13 09:04:11 -07001248 this->getInfo().alphaType());
1249 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorPtr, 0,
1250 fColorXform.get());
msarettac6c7502016-04-25 09:30:24 -07001251 }
msarettf7eb6fc2016-09-13 09:04:11 -07001252 return INHERITED::onGetFillValue(dstInfo);
msarettac6c7502016-04-25 09:30:24 -07001253}
1254
1255SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
1256 SkAutoTDelete<SkStream> streamDeleter(stream);
1257
scroggo8e6c7ad2016-09-16 08:20:38 -07001258 SkCodec* outCodec = nullptr;
1259 if (read_header(streamDeleter.get(), chunkReader, &outCodec, nullptr, nullptr)) {
msarettac6c7502016-04-25 09:30:24 -07001260 // Codec has taken ownership of the stream.
1261 SkASSERT(outCodec);
1262 streamDeleter.release();
1263 return outCodec;
1264 }
1265
1266 return nullptr;
scroggo05245902015-03-25 11:11:52 -07001267}