blob: bbe2257dbae494fb7728d1a70ce1430b105b5e69 [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"
msarettc4ce6b52016-06-16 07:37:41 -070011#include "SkColorSpace_Base.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());
msarettcf7b8772016-09-22 12:37:04 -0700275 fColorXform->apply(colorTable, colorTable, numColors, xformColorFormat,
276 SkColorSpaceXform::kRGBA_8888_ColorFormat, xformAlphaType);
msarettdcd5e652016-08-22 08:48:40 -0700277 }
278
msarett13a91232016-02-01 08:03:29 -0800279 // Pad the color table with the last color in the table (or black) in the case that
280 // invalid pixel indices exceed the number of colors in the table.
281 const int maxColors = 1 << fBitDepth;
282 if (numColors < maxColors) {
msarettdcd5e652016-08-22 08:48:40 -0700283 SkPMColor lastColor = numColors > 0 ? colorTable[numColors - 1] : SK_ColorBLACK;
284 sk_memset32(colorTable + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800285 }
286
msarett13a91232016-02-01 08:03:29 -0800287 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700288 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800289 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800290 }
291
msarettdcd5e652016-08-22 08:48:40 -0700292 fColorTable.reset(new SkColorTable(colorTable, maxColors));
scroggo05245902015-03-25 11:11:52 -0700293 return true;
scroggof24f2242015-03-03 08:59:20 -0800294}
295
296///////////////////////////////////////////////////////////////////////////////
297// Creation
298///////////////////////////////////////////////////////////////////////////////
299
scroggodb30be22015-12-08 18:54:13 -0800300bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
301 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800302}
303
scroggo8e6c7ad2016-09-16 08:20:38 -0700304#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
305
msarett6a738212016-03-04 13:27:35 -0800306static float png_fixed_point_to_float(png_fixed_point x) {
307 // We multiply by the same factor that libpng used to convert
308 // fixed point -> double. Since we want floats, we choose to
309 // do the conversion ourselves rather than convert
310 // fixed point -> double -> float.
311 return ((float) x) * 0.00001f;
312}
313
msarett128245c2016-03-30 12:01:47 -0700314static float png_inverted_fixed_point_to_float(png_fixed_point x) {
315 // This is necessary because the gAMA chunk actually stores 1/gamma.
316 return 1.0f / png_fixed_point_to_float(x);
317}
318
msarettc4ce6b52016-06-16 07:37:41 -0700319static constexpr float gSRGB_toXYZD50[] {
brianosmande68d6c2016-09-09 10:36:17 -0700320 0.4358f, 0.3853f, 0.1430f, // Rx, Gx, Bx
321 0.2224f, 0.7170f, 0.0606f, // Ry, Gy, Gz
322 0.0139f, 0.0971f, 0.7139f, // Rz, Gz, Bz
msarettc4ce6b52016-06-16 07:37:41 -0700323};
324
msarett55447952016-07-22 14:07:23 -0700325static bool convert_to_D50(SkMatrix44* toXYZD50, float toXYZ[9], float whitePoint[2]) {
326 float wX = whitePoint[0];
327 float wY = whitePoint[1];
328 if (wX < 0.0f || wY < 0.0f || (wX + wY > 1.0f)) {
329 return false;
330 }
331
332 // Calculate the XYZ illuminant. Call this the src illuminant.
333 float wZ = 1.0f - wX - wY;
334 float scale = 1.0f / wY;
335 // TODO (msarett):
336 // What are common src illuminants? I'm guessing we will almost always see D65. Should
337 // we go ahead and save a precomputed D65->D50 Bradford matrix? Should we exit early if
338 // if the src illuminant is D50?
339 SkVector3 srcXYZ = SkVector3::Make(wX * scale, 1.0f, wZ * scale);
340
341 // The D50 illuminant.
342 SkVector3 dstXYZ = SkVector3::Make(0.96422f, 1.0f, 0.82521f);
343
344 // Calculate the chromatic adaptation matrix. We will use the Bradford method, thus
345 // the matrices below. The Bradford method is used by Adobe and is widely considered
346 // to be the best.
347 // http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
348 SkMatrix mA, mAInv;
349 mA.setAll(0.8951f, 0.2664f, -0.1614f, -0.7502f, 1.7135f, 0.0367f, 0.0389f, -0.0685f, 1.0296f);
350 mAInv.setAll(0.9869929f, -0.1470543f, 0.1599627f, 0.4323053f, 0.5183603f, 0.0492912f,
351 -0.0085287f, 0.0400428f, 0.9684867f);
352
353 // Map illuminant into cone response domain.
354 SkVector3 srcCone;
355 srcCone.fX = mA[0] * srcXYZ.fX + mA[1] * srcXYZ.fY + mA[2] * srcXYZ.fZ;
356 srcCone.fY = mA[3] * srcXYZ.fX + mA[4] * srcXYZ.fY + mA[5] * srcXYZ.fZ;
357 srcCone.fZ = mA[6] * srcXYZ.fX + mA[7] * srcXYZ.fY + mA[8] * srcXYZ.fZ;
358 SkVector3 dstCone;
359 dstCone.fX = mA[0] * dstXYZ.fX + mA[1] * dstXYZ.fY + mA[2] * dstXYZ.fZ;
360 dstCone.fY = mA[3] * dstXYZ.fX + mA[4] * dstXYZ.fY + mA[5] * dstXYZ.fZ;
361 dstCone.fZ = mA[6] * dstXYZ.fX + mA[7] * dstXYZ.fY + mA[8] * dstXYZ.fZ;
362
363 SkMatrix DXToD50;
364 DXToD50.setIdentity();
365 DXToD50[0] = dstCone.fX / srcCone.fX;
366 DXToD50[4] = dstCone.fY / srcCone.fY;
367 DXToD50[8] = dstCone.fZ / srcCone.fZ;
368 DXToD50.postConcat(mAInv);
369 DXToD50.preConcat(mA);
370
371 SkMatrix toXYZ3x3;
372 toXYZ3x3.setAll(toXYZ[0], toXYZ[3], toXYZ[6], toXYZ[1], toXYZ[4], toXYZ[7], toXYZ[2], toXYZ[5],
373 toXYZ[8]);
374 toXYZ3x3.postConcat(DXToD50);
375
brianosmande68d6c2016-09-09 10:36:17 -0700376 toXYZD50->set3x3(toXYZ3x3[0], toXYZ3x3[3], toXYZ3x3[6],
377 toXYZ3x3[1], toXYZ3x3[4], toXYZ3x3[7],
378 toXYZ3x3[2], toXYZ3x3[5], toXYZ3x3[8]);
msarett55447952016-07-22 14:07:23 -0700379 return true;
380}
381
scroggo8e6c7ad2016-09-16 08:20:38 -0700382#endif // LIBPNG >= 1.6
383
msarett6a738212016-03-04 13:27:35 -0800384// Returns a colorSpace object that represents any color space information in
385// the encoded data. If the encoded data contains no color space, this will
386// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800387sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800388
msarette2443222016-03-04 14:20:49 -0800389#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
390
msarett6a738212016-03-04 13:27:35 -0800391 // First check for an ICC profile
392 png_bytep profile;
393 png_uint_32 length;
394 // The below variables are unused, however, we need to pass them in anyway or
395 // png_get_iCCP() will return nothing.
396 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
397 png_charp name;
398 // The |compression| is uninteresting since:
399 // (1) libpng has already decompressed the profile for us.
400 // (2) "deflate" is the only mode of decompression that libpng supports.
401 int compression;
402 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
403 &length)) {
404 return SkColorSpace::NewICC(profile, length);
405 }
406
407 // Second, check for sRGB.
408 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
409
410 // sRGB chunks also store a rendering intent: Absolute, Relative,
411 // Perceptual, and Saturation.
412 // FIXME (msarett): Extract this information from the sRGB chunk once
413 // we are able to handle this information in
414 // SkColorSpace.
415 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
416 }
417
418 // Next, check for chromaticities.
msarett55447952016-07-22 14:07:23 -0700419 png_fixed_point toXYZFixed[9];
420 float toXYZ[9];
421 png_fixed_point whitePointFixed[2];
422 float whitePoint[2];
msarett6a738212016-03-04 13:27:35 -0800423 png_fixed_point gamma;
msarettbb9f7742016-05-17 09:31:20 -0700424 float gammas[3];
msarett55447952016-07-22 14:07:23 -0700425 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &toXYZFixed[0], &toXYZFixed[1], &toXYZFixed[2],
426 &toXYZFixed[3], &toXYZFixed[4], &toXYZFixed[5], &toXYZFixed[6],
427 &toXYZFixed[7], &toXYZFixed[8]) &&
428 png_get_cHRM_fixed(png_ptr, info_ptr, &whitePointFixed[0], &whitePointFixed[1], nullptr,
429 nullptr, nullptr, nullptr, nullptr, nullptr))
430 {
msarett6a738212016-03-04 13:27:35 -0800431 for (int i = 0; i < 9; i++) {
msarett55447952016-07-22 14:07:23 -0700432 toXYZ[i] = png_fixed_point_to_float(toXYZFixed[i]);
msarett6a738212016-03-04 13:27:35 -0800433 }
msarett55447952016-07-22 14:07:23 -0700434 whitePoint[0] = png_fixed_point_to_float(whitePointFixed[0]);
435 whitePoint[1] = png_fixed_point_to_float(whitePointFixed[1]);
436
437 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
438 if (!convert_to_D50(&toXYZD50, toXYZ, whitePoint)) {
439 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
440 }
msarett6a738212016-03-04 13:27:35 -0800441
msarett128245c2016-03-30 12:01:47 -0700442 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
msarettffc2aea2016-05-02 11:12:14 -0700443 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700444 gammas[0] = value;
445 gammas[1] = value;
446 gammas[2] = value;
msarettffc2aea2016-05-02 11:12:14 -0700447
msarett55447952016-07-22 14:07:23 -0700448 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800449 }
msarett128245c2016-03-30 12:01:47 -0700450
msarettc4ce6b52016-06-16 07:37:41 -0700451 // Default to sRGB gamma if the image has color space information,
452 // but does not specify gamma.
msarett48ba2b82016-09-07 18:55:49 -0700453 return SkColorSpace::NewRGB(SkColorSpace::kSRGB_RenderTargetGamma, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800454 }
455
456 // Last, check for gamma.
457 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
458
msarett6a738212016-03-04 13:27:35 -0800459 // Set the gammas.
msarettffc2aea2016-05-02 11:12:14 -0700460 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700461 gammas[0] = value;
462 gammas[1] = value;
463 gammas[2] = value;
msarett6a738212016-03-04 13:27:35 -0800464
msarettc4ce6b52016-06-16 07:37:41 -0700465 // Since there is no cHRM, we will guess sRGB gamut.
msarett55447952016-07-22 14:07:23 -0700466 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
467 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
msarettc4ce6b52016-06-16 07:37:41 -0700468
msarett55447952016-07-22 14:07:23 -0700469 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800470 }
471
msarette2443222016-03-04 14:20:49 -0800472#endif // LIBPNG >= 1.6
473
msarettc4ce6b52016-06-16 07:37:41 -0700474 // Report that there is no color space information in the PNG. SkPngCodec is currently
475 // implemented to guess sRGB in this case.
msarett6a738212016-03-04 13:27:35 -0800476 return nullptr;
477}
478
msarett400a93b2016-09-01 18:32:52 -0700479void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
480 switch (fXformMode) {
481 case kSwizzleOnly_XformMode:
msarett400a93b2016-09-01 18:32:52 -0700482 break;
483 case kColorOnly_XformMode:
484 // Intentional fall through. A swizzler hasn't been created yet, but one will
485 // be created later if we are sampling. We'll go ahead and allocate
486 // enough memory to swizzle if necessary.
487 case kSwizzleColor_XformMode: {
scroggo8e6c7ad2016-09-16 08:20:38 -0700488 const size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t);
489 fStorage.reset(colorXformBytes);
490 fColorXformSrcRow = (uint32_t*) fStorage.get();
msarett400a93b2016-09-01 18:32:52 -0700491 break;
492 }
493 }
msarettd1ec89b2016-08-03 12:59:27 -0700494}
495
scroggo8e6c7ad2016-09-16 08:20:38 -0700496void SkPngCodec::applyXformRow(void* dst, const void* src) {
msarettcf7b8772016-09-22 12:37:04 -0700497 const SkColorSpaceXform::ColorFormat srcColorFormat = SkColorSpaceXform::kRGBA_8888_ColorFormat;
msarett400a93b2016-09-01 18:32:52 -0700498 switch (fXformMode) {
499 case kSwizzleOnly_XformMode:
500 fSwizzler->swizzle(dst, (const uint8_t*) src);
501 break;
502 case kColorOnly_XformMode:
msarettc0444612016-09-16 11:45:58 -0700503 fColorXform->apply(dst, (const uint32_t*) src, fXformWidth, fXformColorFormat,
msarettcf7b8772016-09-22 12:37:04 -0700504 srcColorFormat, fXformAlphaType);
msarett400a93b2016-09-01 18:32:52 -0700505 break;
506 case kSwizzleColor_XformMode:
507 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src);
msarettc0444612016-09-16 11:45:58 -0700508 fColorXform->apply(dst, fColorXformSrcRow, fXformWidth, fXformColorFormat,
msarettcf7b8772016-09-22 12:37:04 -0700509 srcColorFormat, fXformAlphaType);
msarett400a93b2016-09-01 18:32:52 -0700510 break;
511 }
msarettdcd5e652016-08-22 08:48:40 -0700512}
513
scroggo8e6c7ad2016-09-16 08:20:38 -0700514class SkPngNormalDecoder : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700515public:
scroggo8e6c7ad2016-09-16 08:20:38 -0700516 SkPngNormalDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo, SkStream* stream,
517 SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr, int bitDepth)
518 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
519 , fLinesDecoded(0)
520 , fDst(nullptr)
521 , fRowBytes(0)
522 , fFirstRow(0)
523 , fLastRow(0)
scroggo1c005e42015-08-04 09:24:45 -0700524 {}
525
scroggo8e6c7ad2016-09-16 08:20:38 -0700526 static void AllRowsCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
527 GetDecoder(png_ptr)->allRowsCallback(row, rowNum);
scroggo05245902015-03-25 11:11:52 -0700528 }
529
scroggo8e6c7ad2016-09-16 08:20:38 -0700530 static void RowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
531 GetDecoder(png_ptr)->rowCallback(row, rowNum);
msarettd1ec89b2016-08-03 12:59:27 -0700532 }
533
scroggo8e6c7ad2016-09-16 08:20:38 -0700534#ifdef SK_GOOGLE3_PNG_HACK
535 static void RereadInfoCallback(png_structp png_ptr, png_infop) {
536 GetDecoder(png_ptr)->rereadInfoCallback();
scroggo05245902015-03-25 11:11:52 -0700537 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700538#endif
emmaleer8f4ba762015-08-14 07:44:46 -0700539
emmaleer0a4c3cb2015-06-22 10:40:21 -0700540private:
scroggo8e6c7ad2016-09-16 08:20:38 -0700541 int fLinesDecoded; // FIXME: Move to baseclass?
542 void* fDst;
543 size_t fRowBytes;
544
545 // Variables for partial decode
546 int fFirstRow; // FIXME: Move to baseclass?
547 int fLastRow;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700548
scroggo46c57472015-09-30 08:57:13 -0700549 typedef SkPngCodec INHERITED;
scroggo8e6c7ad2016-09-16 08:20:38 -0700550
551 static SkPngNormalDecoder* GetDecoder(png_structp png_ptr) {
552 return static_cast<SkPngNormalDecoder*>(png_get_progressive_ptr(png_ptr));
553 }
554
555 Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
556 const int height = this->getInfo().height();
557 png_progressive_info_ptr callback = nullptr;
558#ifdef SK_GOOGLE3_PNG_HACK
559 callback = RereadInfoCallback;
560#endif
561 png_set_progressive_read_fn(this->png_ptr(), this, callback, AllRowsCallback, nullptr);
562 fDst = dst;
563 fRowBytes = rowBytes;
564
565 fLinesDecoded = 0;
scroggoc46cdd42016-10-10 06:45:32 -0700566 fFirstRow = 0;
567 fLastRow = height - 1;
scroggo8e6c7ad2016-09-16 08:20:38 -0700568
569 this->processData();
570
571 if (fLinesDecoded == height) {
572 return SkCodec::kSuccess;
573 }
574
575 if (rowsDecoded) {
576 *rowsDecoded = fLinesDecoded;
577 }
578
579 return SkCodec::kIncompleteInput;
580 }
581
582 void allRowsCallback(png_bytep row, int rowNum) {
scroggoc46cdd42016-10-10 06:45:32 -0700583 SkASSERT(rowNum == fLinesDecoded);
scroggo8e6c7ad2016-09-16 08:20:38 -0700584 fLinesDecoded++;
585 this->applyXformRow(fDst, row);
586 fDst = SkTAddOffset<void>(fDst, fRowBytes);
587 }
588
589 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
590 png_progressive_info_ptr callback = nullptr;
591#ifdef SK_GOOGLE3_PNG_HACK
592 callback = RereadInfoCallback;
593#endif
594 png_set_progressive_read_fn(this->png_ptr(), this, callback, RowCallback, nullptr);
595 fFirstRow = firstRow;
596 fLastRow = lastRow;
597 fDst = dst;
598 fRowBytes = rowBytes;
599 fLinesDecoded = 0;
600 }
601
602 SkCodec::Result decode(int* rowsDecoded) override {
603 this->processData();
604
605 if (fLinesDecoded == fLastRow - fFirstRow + 1) {
606 return SkCodec::kSuccess;
607 }
608
609 if (rowsDecoded) {
610 *rowsDecoded = fLinesDecoded;
611 }
612
613 return SkCodec::kIncompleteInput;
614 }
615
616 void rowCallback(png_bytep row, int rowNum) {
617 if (rowNum < fFirstRow) {
618 // Ignore this row.
619 return;
620 }
621
622 SkASSERT(rowNum <= fLastRow);
623
624 // If there is no swizzler, all rows are needed.
625 if (!this->swizzler() || this->swizzler()->rowNeeded(fLinesDecoded)) {
626 this->applyXformRow(fDst, row);
627 fDst = SkTAddOffset<void>(fDst, fRowBytes);
628 }
629
630 fLinesDecoded++;
631
632 if (rowNum == fLastRow) {
633 // Fake error to stop decoding scanlines.
634 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
635 }
636 }
emmaleer0a4c3cb2015-06-22 10:40:21 -0700637};
638
scroggo8e6c7ad2016-09-16 08:20:38 -0700639class SkPngInterlacedDecoder : public SkPngCodec {
640public:
641 SkPngInterlacedDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo,
642 SkStream* stream, SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr,
643 int bitDepth, int numberPasses)
644 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
645 , fNumberPasses(numberPasses)
646 , fFirstRow(0)
647 , fLastRow(0)
648 , fLinesDecoded(0)
649 , fInterlacedComplete(false)
650 , fPng_rowbytes(0)
651 {}
652
653 static void InterlacedRowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int pass) {
654 auto decoder = static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr));
655 decoder->interlacedRowCallback(row, rowNum, pass);
656 }
657
658#ifdef SK_GOOGLE3_PNG_HACK
659 static void RereadInfoInterlacedCallback(png_structp png_ptr, png_infop) {
660 static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr))->rereadInfoInterlaced();
661 }
662#endif
663
664private:
665 const int fNumberPasses;
666 int fFirstRow;
667 int fLastRow;
668 void* fDst;
669 size_t fRowBytes;
670 int fLinesDecoded;
671 bool fInterlacedComplete;
672 size_t fPng_rowbytes;
673 SkAutoTMalloc<png_byte> fInterlaceBuffer;
674
675 typedef SkPngCodec INHERITED;
676
677#ifdef SK_GOOGLE3_PNG_HACK
678 void rereadInfoInterlaced() {
679 this->rereadInfoCallback();
680 // Note: This allocates more memory than necessary, if we are sampling/subset.
681 this->setUpInterlaceBuffer(this->getInfo().height());
682 }
683#endif
684
685 // FIXME: Currently sharing interlaced callback for all rows and subset. It's not
686 // as expensive as the subset version of non-interlaced, but it still does extra
687 // work.
688 void interlacedRowCallback(png_bytep row, int rowNum, int pass) {
689 if (rowNum < fFirstRow || rowNum > fLastRow) {
690 // Ignore this row
691 return;
692 }
693
694 png_bytep oldRow = fInterlaceBuffer.get() + (rowNum - fFirstRow) * fPng_rowbytes;
695 png_progressive_combine_row(this->png_ptr(), oldRow, row);
696
697 if (0 == pass) {
698 // The first pass initializes all rows.
699 SkASSERT(row);
700 SkASSERT(fLinesDecoded == rowNum - fFirstRow);
701 fLinesDecoded++;
702 } else {
703 SkASSERT(fLinesDecoded == fLastRow - fFirstRow + 1);
704 if (fNumberPasses - 1 == pass && rowNum == fLastRow) {
705 // Last pass, and we have read all of the rows we care about. Note that
706 // we do not care about reading anything beyond the end of the image (or
707 // beyond the last scanline requested).
708 fInterlacedComplete = true;
709 // Fake error to stop decoding scanlines.
710 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
711 }
712 }
713 }
714
715 SkCodec::Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
716 const int height = this->getInfo().height();
717 this->setUpInterlaceBuffer(height);
718 png_progressive_info_ptr callback = nullptr;
719#ifdef SK_GOOGLE3_PNG_HACK
720 callback = RereadInfoInterlacedCallback;
721#endif
722 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedRowCallback,
723 nullptr);
724
725 fFirstRow = 0;
726 fLastRow = height - 1;
727 fLinesDecoded = 0;
728
729 this->processData();
730
731 png_bytep srcRow = fInterlaceBuffer.get();
732 // FIXME: When resuming, this may rewrite rows that did not change.
733 for (int rowNum = 0; rowNum < fLinesDecoded; rowNum++) {
734 this->applyXformRow(dst, srcRow);
735 dst = SkTAddOffset<void>(dst, rowBytes);
736 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes);
737 }
738 if (fInterlacedComplete) {
739 return SkCodec::kSuccess;
740 }
741
742 if (rowsDecoded) {
743 *rowsDecoded = fLinesDecoded;
744 }
745
746 return SkCodec::kIncompleteInput;
747 }
748
749 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
750 // FIXME: We could skip rows in the interlace buffer that we won't put in the output.
751 this->setUpInterlaceBuffer(lastRow - firstRow + 1);
752 png_progressive_info_ptr callback = nullptr;
753#ifdef SK_GOOGLE3_PNG_HACK
754 callback = RereadInfoInterlacedCallback;
755#endif
756 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedRowCallback, nullptr);
757 fFirstRow = firstRow;
758 fLastRow = lastRow;
759 fDst = dst;
760 fRowBytes = rowBytes;
761 fLinesDecoded = 0;
762 }
763
764 SkCodec::Result decode(int* rowsDecoded) override {
765 this->processData();
766
767 // Now apply Xforms on all the rows that were decoded.
768 if (!fLinesDecoded) {
769 return SkCodec::kIncompleteInput;
770 }
771 const int lastRow = fLinesDecoded + fFirstRow - 1;
772 SkASSERT(lastRow <= fLastRow);
773
774 // FIXME: For resuming interlace, we may swizzle a row that hasn't changed. But it
775 // may be too tricky/expensive to handle that correctly.
776 png_bytep srcRow = fInterlaceBuffer.get();
777 const int sampleY = this->swizzler() ? this->swizzler()->sampleY() : 1;
778 void* dst = fDst;
779 for (int rowNum = fFirstRow; rowNum <= lastRow; rowNum += sampleY) {
780 this->applyXformRow(dst, srcRow);
781 dst = SkTAddOffset<void>(dst, fRowBytes);
782 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes * sampleY);
783 }
784
785 if (fInterlacedComplete) {
786 return SkCodec::kSuccess;
787 }
788
789 if (rowsDecoded) {
790 *rowsDecoded = fLinesDecoded;
791 }
792 return SkCodec::kIncompleteInput;
793 }
794
795 void setUpInterlaceBuffer(int height) {
796 fPng_rowbytes = png_get_rowbytes(this->png_ptr(), this->info_ptr());
797 fInterlaceBuffer.reset(fPng_rowbytes * height);
798 fInterlacedComplete = false;
799 }
800};
801
802#ifdef SK_GOOGLE3_PNG_HACK
803bool SkPngCodec::rereadHeaderIfNecessary() {
804 if (!fNeedsToRereadHeader) {
805 return true;
806 }
807
808 // On the first call, we'll need to rewind ourselves. Future calls will
809 // have already rewound in rewindIfNecessary.
810 if (this->stream()->getPosition() > 0) {
811 this->stream()->rewind();
812 }
813
814 this->destroyReadStruct();
815 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
816 sk_error_fn, sk_warning_fn);
817 if (!png_ptr) {
818 return false;
819 }
820
821 // Only use the AutoCleanPng to delete png_ptr as necessary.
822 // (i.e. not for reading bounds etc.)
823 AutoCleanPng autoClean(png_ptr, nullptr, nullptr, nullptr);
824
825 png_infop info_ptr = png_create_info_struct(png_ptr);
826 if (info_ptr == nullptr) {
827 return false;
828 }
829
830 autoClean.setInfoPtr(info_ptr);
831
832#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
833 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
834 // This needs to be installed before we read the png header. Android may store ninepatch
835 // chunks in the header.
836 if (fPngChunkReader.get()) {
837 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
838 png_set_read_user_chunk_fn(png_ptr, (png_voidp) fPngChunkReader.get(), sk_read_user_chunk);
839 }
840#endif
841
842 fPng_ptr = png_ptr;
843 fInfo_ptr = info_ptr;
844 autoClean.releasePngPtrs();
845 fNeedsToRereadHeader = false;
846 return true;
847}
848#endif // SK_GOOGLE3_PNG_HACK
849
msarettac6c7502016-04-25 09:30:24 -0700850// Reads the header and initializes the output fields, if not NULL.
851//
852// @param stream Input data. Will be read to get enough information to properly
853// setup the codec.
854// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
855// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
856// expected to continue to own it for the lifetime of the png_ptr.
857// @param outCodec Optional output variable. If non-NULL, will be set to a new
858// SkPngCodec on success.
859// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
860// png_structp on success.
861// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
862// png_infop on success;
863// @return true on success, in which case the caller is responsible for calling
864// png_destroy_read_struct(png_ptrp, info_ptrp).
865// If it returns false, the passed in fields (except stream) are unchanged.
866static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec** outCodec,
867 png_structp* png_ptrp, png_infop* info_ptrp) {
868 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
869 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
870 sk_error_fn, sk_warning_fn);
871 if (!png_ptr) {
872 return false;
873 }
874
scroggo8e6c7ad2016-09-16 08:20:38 -0700875 AutoCleanPng autoClean(png_ptr, stream, chunkReader, outCodec);
msarettac6c7502016-04-25 09:30:24 -0700876
877 png_infop info_ptr = png_create_info_struct(png_ptr);
878 if (info_ptr == nullptr) {
879 return false;
880 }
881
882 autoClean.setInfoPtr(info_ptr);
883
884 // FIXME: Could we use the return value of setjmp to specify the type of
885 // error?
scroggo8e6c7ad2016-09-16 08:20:38 -0700886 if (setjmp(PNG_JMPBUF(png_ptr))) {
msarettac6c7502016-04-25 09:30:24 -0700887 return false;
888 }
889
msarettac6c7502016-04-25 09:30:24 -0700890#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
891 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
892 // This needs to be installed before we read the png header. Android may store ninepatch
893 // chunks in the header.
894 if (chunkReader) {
895 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
896 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
897 }
898#endif
899
scroggo8e6c7ad2016-09-16 08:20:38 -0700900 const bool decodedBounds = autoClean.decodeBounds();
901
902 if (!decodedBounds) {
903 return false;
904 }
905
906 // On success, decodeBounds releases ownership of png_ptr and info_ptr.
907 if (png_ptrp) {
908 *png_ptrp = png_ptr;
909 }
910 if (info_ptrp) {
911 *info_ptrp = info_ptr;
912 }
913
914 // decodeBounds takes care of setting outCodec
915 if (outCodec) {
916 SkASSERT(*outCodec);
917 }
918 return true;
919}
920
921// FIXME (scroggo): Once SK_GOOGLE3_PNG_HACK is no more, this method can be inline in
922// AutoCleanPng::infoCallback
923static void general_info_callback(png_structp png_ptr, png_infop info_ptr,
924 SkEncodedInfo::Color* outColor, SkEncodedInfo::Alpha* outAlpha) {
msarettac6c7502016-04-25 09:30:24 -0700925 png_uint_32 origWidth, origHeight;
926 int bitDepth, encodedColorType;
scroggod8d68552016-06-06 11:26:17 -0700927 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarettac6c7502016-04-25 09:30:24 -0700928 &encodedColorType, nullptr, nullptr, nullptr);
929
930 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
931 // TODO: Should we handle this in SkSwizzler? Could this also benefit
932 // RAW decodes?
933 if (bitDepth == 16) {
934 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggod8d68552016-06-06 11:26:17 -0700935 png_set_strip_16(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700936 }
937
938 // Now determine the default colorType and alphaType and set the required transforms.
939 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
940 // still depend on libpng for many of the rare and PNG-specific cases.
941 SkEncodedInfo::Color color;
942 SkEncodedInfo::Alpha alpha;
943 switch (encodedColorType) {
944 case PNG_COLOR_TYPE_PALETTE:
945 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
946 // byte into separate bytes (useful for paletted and grayscale images).
947 if (bitDepth < 8) {
948 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700949 png_set_packing(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700950 }
951
952 color = SkEncodedInfo::kPalette_Color;
953 // Set the alpha depending on if a transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700954 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
msarettac6c7502016-04-25 09:30:24 -0700955 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
956 break;
957 case PNG_COLOR_TYPE_RGB:
scroggod8d68552016-06-06 11:26:17 -0700958 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
msarettac6c7502016-04-25 09:30:24 -0700959 // Convert to RGBA if transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700960 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700961 color = SkEncodedInfo::kRGBA_Color;
962 alpha = SkEncodedInfo::kBinary_Alpha;
963 } else {
964 color = SkEncodedInfo::kRGB_Color;
965 alpha = SkEncodedInfo::kOpaque_Alpha;
966 }
967 break;
968 case PNG_COLOR_TYPE_GRAY:
969 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
970 if (bitDepth < 8) {
971 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700972 png_set_expand_gray_1_2_4_to_8(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700973 }
974
scroggod8d68552016-06-06 11:26:17 -0700975 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
976 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700977 color = SkEncodedInfo::kGrayAlpha_Color;
978 alpha = SkEncodedInfo::kBinary_Alpha;
979 } else {
980 color = SkEncodedInfo::kGray_Color;
981 alpha = SkEncodedInfo::kOpaque_Alpha;
982 }
983 break;
984 case PNG_COLOR_TYPE_GRAY_ALPHA:
985 color = SkEncodedInfo::kGrayAlpha_Color;
986 alpha = SkEncodedInfo::kUnpremul_Alpha;
987 break;
988 case PNG_COLOR_TYPE_RGBA:
989 color = SkEncodedInfo::kRGBA_Color;
990 alpha = SkEncodedInfo::kUnpremul_Alpha;
991 break;
992 default:
993 // All the color types have been covered above.
994 SkASSERT(false);
995 color = SkEncodedInfo::kRGBA_Color;
996 alpha = SkEncodedInfo::kUnpremul_Alpha;
997 }
scroggo8e6c7ad2016-09-16 08:20:38 -0700998 if (outColor) {
999 *outColor = color;
scroggo9a89a092016-05-31 13:52:47 -07001000 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001001 if (outAlpha) {
1002 *outAlpha = alpha;
scroggod8d68552016-06-06 11:26:17 -07001003 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001004}
scroggod8d68552016-06-06 11:26:17 -07001005
scroggo8e6c7ad2016-09-16 08:20:38 -07001006#ifdef SK_GOOGLE3_PNG_HACK
1007void SkPngCodec::rereadInfoCallback() {
1008 general_info_callback(fPng_ptr, fInfo_ptr, nullptr, nullptr);
1009 png_set_interlace_handling(fPng_ptr);
1010 png_read_update_info(fPng_ptr, fInfo_ptr);
1011}
1012#endif
1013
1014void AutoCleanPng::infoCallback() {
1015 SkEncodedInfo::Color color;
1016 SkEncodedInfo::Alpha alpha;
1017 general_info_callback(fPng_ptr, fInfo_ptr, &color, &alpha);
1018
1019 const int numberPasses = png_set_interlace_handling(fPng_ptr);
1020
1021 fReadHeader = true;
1022 fDecodedBounds = true;
1023#ifndef SK_GOOGLE3_PNG_HACK
1024 // 1 tells libpng to save any extra data. We may be able to be more efficient by saving
1025 // it ourselves.
1026 png_process_data_pause(fPng_ptr, 1);
1027#else
1028 // Hack to make png_process_data stop.
1029 fPng_ptr->buffer_size = 0;
1030#endif
1031 if (fOutCodec) {
1032 SkASSERT(nullptr == *fOutCodec);
1033 sk_sp<SkColorSpace> colorSpace = read_color_space(fPng_ptr, fInfo_ptr);
msarettf34cd632016-05-25 10:13:53 -07001034 if (!colorSpace) {
1035 // Treat unmarked pngs as sRGB.
1036 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
1037 }
scroggod8d68552016-06-06 11:26:17 -07001038
msarett549ca322016-08-17 08:54:08 -07001039 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
scroggo8e6c7ad2016-09-16 08:20:38 -07001040 // FIXME (scroggo): Once we get rid of SK_GOOGLE3_PNG_HACK, general_info_callback can
1041 // be inlined, so these values will already be set.
1042 png_uint_32 origWidth = png_get_image_width(fPng_ptr, fInfo_ptr);
1043 png_uint_32 origHeight = png_get_image_height(fPng_ptr, fInfo_ptr);
1044 png_byte bitDepth = png_get_bit_depth(fPng_ptr, fInfo_ptr);
msarett549ca322016-08-17 08:54:08 -07001045 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
1046
1047 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
1048 png_color_8p sigBits;
scroggo8e6c7ad2016-09-16 08:20:38 -07001049 if (png_get_sBIT(fPng_ptr, fInfo_ptr, &sigBits)) {
msarett549ca322016-08-17 08:54:08 -07001050 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->blue) {
1051 // Recommend a decode to 565 if the sBIT indicates 565.
1052 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
1053 }
1054 }
1055 }
scroggod8d68552016-06-06 11:26:17 -07001056
msarettac6c7502016-04-25 09:30:24 -07001057 if (1 == numberPasses) {
scroggo8e6c7ad2016-09-16 08:20:38 -07001058 *fOutCodec = new SkPngNormalDecoder(encodedInfo, imageInfo, fStream,
1059 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth);
msarettac6c7502016-04-25 09:30:24 -07001060 } else {
scroggo8e6c7ad2016-09-16 08:20:38 -07001061 *fOutCodec = new SkPngInterlacedDecoder(encodedInfo, imageInfo, fStream,
1062 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth, numberPasses);
msarettac6c7502016-04-25 09:30:24 -07001063 }
1064 }
1065
scroggo8e6c7ad2016-09-16 08:20:38 -07001066
1067 // Release the pointers, which are now owned by the codec or the caller is expected to
1068 // take ownership.
1069 this->releasePngPtrs();
msarettac6c7502016-04-25 09:30:24 -07001070}
1071
msarett549ca322016-08-17 08:54:08 -07001072SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
mtklein6dc5b9a2016-08-24 12:22:32 -07001073 SkStream* stream, SkPngChunkReader* chunkReader, void* png_ptr,
scroggo8e6c7ad2016-09-16 08:20:38 -07001074 void* info_ptr, int bitDepth)
msarett549ca322016-08-17 08:54:08 -07001075 : INHERITED(encodedInfo, imageInfo, stream)
msarettac6c7502016-04-25 09:30:24 -07001076 , fPngChunkReader(SkSafeRef(chunkReader))
1077 , fPng_ptr(png_ptr)
1078 , fInfo_ptr(info_ptr)
msarettd1ec89b2016-08-03 12:59:27 -07001079 , fColorXformSrcRow(nullptr)
msarettac6c7502016-04-25 09:30:24 -07001080 , fBitDepth(bitDepth)
scroggo8e6c7ad2016-09-16 08:20:38 -07001081#ifdef SK_GOOGLE3_PNG_HACK
1082 , fNeedsToRereadHeader(true)
1083#endif
msarettac6c7502016-04-25 09:30:24 -07001084{}
1085
1086SkPngCodec::~SkPngCodec() {
1087 this->destroyReadStruct();
1088}
1089
1090void SkPngCodec::destroyReadStruct() {
1091 if (fPng_ptr) {
1092 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
1093 SkASSERT(fInfo_ptr);
mtklein6dc5b9a2016-08-24 12:22:32 -07001094 png_destroy_read_struct((png_struct**)&fPng_ptr, (png_info**)&fInfo_ptr, nullptr);
msarettac6c7502016-04-25 09:30:24 -07001095 fPng_ptr = nullptr;
1096 fInfo_ptr = nullptr;
1097 }
1098}
1099
1100///////////////////////////////////////////////////////////////////////////////
1101// Getting the pixels
1102///////////////////////////////////////////////////////////////////////////////
1103
msarettd1ec89b2016-08-03 12:59:27 -07001104bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& options,
1105 SkPMColor ctable[], int* ctableCount) {
scroggo8e6c7ad2016-09-16 08:20:38 -07001106 if (setjmp(PNG_JMPBUF((png_struct*)fPng_ptr))) {
msarettd1ec89b2016-08-03 12:59:27 -07001107 SkCodecPrintf("Failed on png_read_update_info.\n");
1108 return false;
msarettac6c7502016-04-25 09:30:24 -07001109 }
1110 png_read_update_info(fPng_ptr, fInfo_ptr);
1111
msarett400a93b2016-09-01 18:32:52 -07001112 // Reset fSwizzler and fColorXform. We can't do this in onRewind() because the
1113 // interlaced scanline decoder may need to rewind.
1114 fSwizzler.reset(nullptr);
msarettd1ec89b2016-08-03 12:59:27 -07001115 fColorXform = nullptr;
msarett400a93b2016-09-01 18:32:52 -07001116
msarett2ecc35f2016-09-08 11:55:16 -07001117 if (needs_color_xform(dstInfo, this->getInfo())) {
msarett4be0e7c2016-09-22 07:02:24 -07001118 fColorXform = SkColorSpaceXform::New(this->getInfo().colorSpace(), dstInfo.colorSpace());
msarett2ecc35f2016-09-08 11:55:16 -07001119 SkASSERT(fColorXform);
msarett400a93b2016-09-01 18:32:52 -07001120 }
msarettd3317422016-08-22 13:00:05 -07001121
msarett400a93b2016-09-01 18:32:52 -07001122 // If the image is RGBA and we have a color xform, we can skip the swizzler.
1123 // FIXME (msarett):
1124 // Support more input types to fColorXform (ex: RGB, Gray) and skip the swizzler more often.
1125 if (fColorXform && SkEncodedInfo::kRGBA_Color == this->getEncodedInfo().color() &&
1126 !options.fSubset)
1127 {
1128 fXformMode = kColorOnly_XformMode;
1129 return true;
msarettd1ec89b2016-08-03 12:59:27 -07001130 }
1131
msarettac6c7502016-04-25 09:30:24 -07001132 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
msarettdcd5e652016-08-22 08:48:40 -07001133 if (!this->createColorTable(dstInfo, ctableCount)) {
msarettd1ec89b2016-08-03 12:59:27 -07001134 return false;
msarettac6c7502016-04-25 09:30:24 -07001135 }
1136 }
1137
msarett400a93b2016-09-01 18:32:52 -07001138 // Copy the color table to the client if they request kIndex8 mode.
1139 copy_color_table(dstInfo, fColorTable, ctable, ctableCount);
msarettac6c7502016-04-25 09:30:24 -07001140
msarett400a93b2016-09-01 18:32:52 -07001141 this->initializeSwizzler(dstInfo, options);
1142 return true;
1143}
1144
msarettc0444612016-09-16 11:45:58 -07001145void SkPngCodec::initializeXformParams() {
1146 switch (fXformMode) {
1147 case kColorOnly_XformMode:
1148 fXformColorFormat = select_xform_format(this->dstInfo().colorType());
1149 fXformAlphaType = select_xform_alpha(this->dstInfo().alphaType(),
1150 this->getInfo().alphaType());
1151 fXformWidth = this->dstInfo().width();
1152 break;
1153 case kSwizzleColor_XformMode:
1154 fXformColorFormat = select_xform_format(this->dstInfo().colorType());
1155 fXformAlphaType = select_xform_alpha(this->dstInfo().alphaType(),
1156 this->getInfo().alphaType());
1157 fXformWidth = this->swizzler()->swizzleWidth();
1158 break;
1159 default:
1160 break;
1161 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001162}
1163
msarett400a93b2016-09-01 18:32:52 -07001164static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo::Color srcColor) {
1165 // We will apply the color xform when reading the color table, unless F16 is requested.
1166 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType;
1167}
1168
1169void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options) {
1170 SkImageInfo swizzlerInfo = dstInfo;
1171 Options swizzlerOptions = options;
1172 fXformMode = kSwizzleOnly_XformMode;
1173 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color())) {
1174 swizzlerInfo = swizzlerInfo.makeColorType(kRGBA_8888_SkColorType);
1175 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
1176 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
1177 }
1178
1179 fXformMode = kSwizzleColor_XformMode;
1180
1181 // Here, we swizzle into temporary memory, which is not zero initialized.
1182 // FIXME (msarett):
1183 // Is this a problem?
1184 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
1185 }
1186
msarettac6c7502016-04-25 09:30:24 -07001187 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettd1ec89b2016-08-03 12:59:27 -07001188 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colors, swizzlerInfo,
msarettd3317422016-08-22 13:00:05 -07001189 swizzlerOptions));
msarettac6c7502016-04-25 09:30:24 -07001190 SkASSERT(fSwizzler);
msarett400a93b2016-09-01 18:32:52 -07001191}
1192
1193SkSampler* SkPngCodec::getSampler(bool createIfNecessary) {
1194 if (fSwizzler || !createIfNecessary) {
1195 return fSwizzler;
1196 }
1197
1198 this->initializeSwizzler(this->dstInfo(), this->options());
1199 return fSwizzler;
msarettac6c7502016-04-25 09:30:24 -07001200}
1201
msarettac6c7502016-04-25 09:30:24 -07001202bool SkPngCodec::onRewind() {
scroggo8e6c7ad2016-09-16 08:20:38 -07001203#ifdef SK_GOOGLE3_PNG_HACK
1204 fNeedsToRereadHeader = true;
1205 return true;
1206#else
msarettac6c7502016-04-25 09:30:24 -07001207 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
1208 // succeeds, they will be repopulated, and if it fails, they will
1209 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
1210 // come through this function which will rewind and again attempt
1211 // to reinitialize them.
1212 this->destroyReadStruct();
1213
scroggo46c57472015-09-30 08:57:13 -07001214 png_structp png_ptr;
1215 png_infop info_ptr;
msarettac6c7502016-04-25 09:30:24 -07001216 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, &info_ptr)) {
1217 return false;
scroggo05245902015-03-25 11:11:52 -07001218 }
1219
msarettac6c7502016-04-25 09:30:24 -07001220 fPng_ptr = png_ptr;
1221 fInfo_ptr = info_ptr;
1222 return true;
scroggo8e6c7ad2016-09-16 08:20:38 -07001223#endif
msarettac6c7502016-04-25 09:30:24 -07001224}
msarett6a738212016-03-04 13:27:35 -08001225
msarettd1ec89b2016-08-03 12:59:27 -07001226SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
1227 size_t rowBytes, const Options& options,
msarettac6c7502016-04-25 09:30:24 -07001228 SkPMColor ctable[], int* ctableCount,
1229 int* rowsDecoded) {
msarett2ecc35f2016-09-08 11:55:16 -07001230 if (!conversion_possible(dstInfo, this->getInfo()) ||
msarettd1ec89b2016-08-03 12:59:27 -07001231 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1232 {
msarettac6c7502016-04-25 09:30:24 -07001233 return kInvalidConversion;
1234 }
scroggo8e6c7ad2016-09-16 08:20:38 -07001235#ifdef SK_GOOGLE3_PNG_HACK
1236 // Note that this is done after initializeXforms. Otherwise that method
1237 // would not have png_ptr to use.
1238 if (!this->rereadHeaderIfNecessary()) {
1239 return kCouldNotRewind;
1240 }
1241#endif
msarettd1ec89b2016-08-03 12:59:27 -07001242
msarettac6c7502016-04-25 09:30:24 -07001243 if (options.fSubset) {
msarettac6c7502016-04-25 09:30:24 -07001244 return kUnimplemented;
scroggo05245902015-03-25 11:11:52 -07001245 }
1246
msarett400a93b2016-09-01 18:32:52 -07001247 this->allocateStorage(dstInfo);
msarettc0444612016-09-16 11:45:58 -07001248 this->initializeXformParams();
scroggo8e6c7ad2016-09-16 08:20:38 -07001249 return this->decodeAllRows(dst, rowBytes, rowsDecoded);
1250}
msarettac6c7502016-04-25 09:30:24 -07001251
scroggo8e6c7ad2016-09-16 08:20:38 -07001252SkCodec::Result SkPngCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
1253 void* dst, size_t rowBytes, const SkCodec::Options& options,
1254 SkPMColor* ctable, int* ctableCount) {
1255 if (!conversion_possible(dstInfo, this->getInfo()) ||
1256 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1257 {
1258 return kInvalidConversion;
1259 }
1260#ifdef SK_GOOGLE3_PNG_HACK
1261 // See note in onGetPixels.
1262 if (!this->rereadHeaderIfNecessary()) {
1263 return kCouldNotRewind;
1264 }
1265#endif
1266
1267 this->allocateStorage(dstInfo);
1268
1269 int firstRow, lastRow;
1270 if (options.fSubset) {
1271 firstRow = options.fSubset->top();
1272 lastRow = options.fSubset->bottom() - 1;
1273 } else {
1274 firstRow = 0;
1275 lastRow = dstInfo.height() - 1;
1276 }
1277 this->setRange(firstRow, lastRow, dst, rowBytes);
scroggod8d68552016-06-06 11:26:17 -07001278 return kSuccess;
scroggo6fb23912016-06-02 14:16:43 -07001279}
1280
scroggo8e6c7ad2016-09-16 08:20:38 -07001281SkCodec::Result SkPngCodec::onIncrementalDecode(int* rowsDecoded) {
1282 // FIXME: Only necessary on the first call.
msarettc0444612016-09-16 11:45:58 -07001283 this->initializeXformParams();
scroggo8e6c7ad2016-09-16 08:20:38 -07001284
1285 return this->decode(rowsDecoded);
1286}
1287
msarettf7eb6fc2016-09-13 09:04:11 -07001288uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
msarettac6c7502016-04-25 09:30:24 -07001289 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
1290 if (colorPtr) {
msarettc0444612016-09-16 11:45:58 -07001291 SkAlphaType alphaType = select_xform_alpha(dstInfo.alphaType(),
msarettf7eb6fc2016-09-13 09:04:11 -07001292 this->getInfo().alphaType());
1293 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorPtr, 0,
1294 fColorXform.get());
msarettac6c7502016-04-25 09:30:24 -07001295 }
msarettf7eb6fc2016-09-13 09:04:11 -07001296 return INHERITED::onGetFillValue(dstInfo);
msarettac6c7502016-04-25 09:30:24 -07001297}
1298
1299SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
1300 SkAutoTDelete<SkStream> streamDeleter(stream);
1301
scroggo8e6c7ad2016-09-16 08:20:38 -07001302 SkCodec* outCodec = nullptr;
1303 if (read_header(streamDeleter.get(), chunkReader, &outCodec, nullptr, nullptr)) {
msarettac6c7502016-04-25 09:30:24 -07001304 // Codec has taken ownership of the stream.
1305 SkASSERT(outCodec);
1306 streamDeleter.release();
1307 return outCodec;
1308 }
1309
1310 return nullptr;
scroggo05245902015-03-25 11:11:52 -07001311}