blob: 8ae2360f2570f5addb6cfb37fc4bea8e6b0483f7 [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"
msarettad8bcfe2016-03-07 07:09:03 -080011#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"
scroggof24f2242015-03-03 08:59:20 -080016#include "SkSize.h"
17#include "SkStream.h"
18#include "SkSwizzler.h"
scroggo565901d2015-12-10 10:44:13 -080019#include "SkTemplates.h"
bungeman5d2cd6e2016-02-23 07:34:25 -080020#include "SkUtils.h"
scroggof24f2242015-03-03 08:59:20 -080021
22///////////////////////////////////////////////////////////////////////////////
scroggof24f2242015-03-03 08:59:20 -080023// Callback functions
24///////////////////////////////////////////////////////////////////////////////
25
26static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
scroggo230d4ac2015-03-26 07:15:55 -070027 SkCodecPrintf("------ png error %s\n", msg);
scroggof24f2242015-03-03 08:59:20 -080028 longjmp(png_jmpbuf(png_ptr), 1);
29}
30
scroggo0eed6df2015-03-26 10:07:56 -070031void sk_warning_fn(png_structp, png_const_charp msg) {
32 SkCodecPrintf("----- png warning %s\n", msg);
33}
34
scroggof24f2242015-03-03 08:59:20 -080035static void sk_read_fn(png_structp png_ptr, png_bytep data,
36 png_size_t length) {
37 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
38 const size_t bytes = stream->read(data, length);
39 if (bytes != length) {
40 // FIXME: We want to report the fact that the stream was truncated.
41 // One way to do that might be to pass a enum to longjmp so setjmp can
42 // specify the failure.
43 png_error(png_ptr, "Read Error!");
44 }
45}
46
scroggocf98fa92015-11-23 08:14:40 -080047#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
48static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
49 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(png_ptr);
50 // readChunk() returning true means continue decoding
51 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk->size) ? 1 : -1;
52}
53#endif
54
scroggof24f2242015-03-03 08:59:20 -080055///////////////////////////////////////////////////////////////////////////////
56// Helpers
57///////////////////////////////////////////////////////////////////////////////
58
59class AutoCleanPng : public SkNoncopyable {
60public:
61 AutoCleanPng(png_structp png_ptr)
62 : fPng_ptr(png_ptr)
halcanary96fcdcc2015-08-27 07:41:13 -070063 , fInfo_ptr(nullptr) {}
scroggof24f2242015-03-03 08:59:20 -080064
65 ~AutoCleanPng() {
halcanary96fcdcc2015-08-27 07:41:13 -070066 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
scroggof24f2242015-03-03 08:59:20 -080067 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070068 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
msarett13a91232016-02-01 08:03:29 -080069 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
scroggof24f2242015-03-03 08:59:20 -080070 }
71 }
72
73 void setInfoPtr(png_infop info_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070074 SkASSERT(nullptr == fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -080075 fInfo_ptr = info_ptr;
76 }
77
mtklein18300a32016-03-16 13:53:35 -070078 void release() {
halcanary96fcdcc2015-08-27 07:41:13 -070079 fPng_ptr = nullptr;
80 fInfo_ptr = nullptr;
scroggof24f2242015-03-03 08:59:20 -080081 }
82
83private:
84 png_structp fPng_ptr;
85 png_infop fInfo_ptr;
86};
87#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
88
scroggof24f2242015-03-03 08:59:20 -080089// Method for coverting to either an SkPMColor or a similarly packed
90// unpremultiplied color.
91typedef uint32_t (*PackColorProc)(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
92
93// Note: SkColorTable claims to store SkPMColors, which is not necessarily
94// the case here.
msarett13a91232016-02-01 08:03:29 -080095// TODO: If we add support for non-native swizzles, we'll need to handle that here.
scroggo9b2cdbf42015-07-10 12:07:02 -070096bool SkPngCodec::decodePalette(bool premultiply, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -080097
msarett13a91232016-02-01 08:03:29 -080098 int numColors;
99 png_color* palette;
100 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -0700101 return false;
scroggof24f2242015-03-03 08:59:20 -0800102 }
103
msarett13a91232016-02-01 08:03:29 -0800104 // Note: These are not necessarily SkPMColors.
105 SkPMColor colorPtr[256];
scroggof24f2242015-03-03 08:59:20 -0800106
msarett13a91232016-02-01 08:03:29 -0800107 png_bytep alphas;
108 int numColorsWithAlpha = 0;
109 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
110 // Choose which function to use to create the color table. If the final destination's
111 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
112 PackColorProc proc;
113 if (premultiply) {
114 proc = &SkPremultiplyARGBInline;
115 } else {
116 proc = &SkPackARGB32NoCheck;
117 }
118
119 for (int i = 0; i < numColorsWithAlpha; i++) {
120 // We don't have a function in SkOpts that combines a set of alphas with a set
121 // of RGBs. We could write one, but it's hardly worth it, given that this
122 // is such a small fraction of the total decode time.
123 colorPtr[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
124 palette++;
125 }
scroggof24f2242015-03-03 08:59:20 -0800126 }
127
msarett13a91232016-02-01 08:03:29 -0800128 if (numColorsWithAlpha < numColors) {
129 // The optimized code depends on a 3-byte png_color struct with the colors
130 // in RGB order. These checks make sure it is safe to use.
131 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
132#ifdef SK_DEBUG
133 SkASSERT(&palette->red < &palette->green);
134 SkASSERT(&palette->green < &palette->blue);
135#endif
136
137#ifdef SK_PMCOLOR_IS_RGBA
138 SkOpts::RGB_to_RGB1(colorPtr + numColorsWithAlpha, palette, numColors - numColorsWithAlpha);
139#else
140 SkOpts::RGB_to_BGR1(colorPtr + numColorsWithAlpha, palette, numColors - numColorsWithAlpha);
141#endif
scroggof24f2242015-03-03 08:59:20 -0800142 }
143
msarett13a91232016-02-01 08:03:29 -0800144 // Pad the color table with the last color in the table (or black) in the case that
145 // invalid pixel indices exceed the number of colors in the table.
146 const int maxColors = 1 << fBitDepth;
147 if (numColors < maxColors) {
148 SkPMColor lastColor = numColors > 0 ? colorPtr[numColors - 1] : SK_ColorBLACK;
149 sk_memset32(colorPtr + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800150 }
151
msarett13a91232016-02-01 08:03:29 -0800152 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700153 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800154 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800155 }
156
msarett13a91232016-02-01 08:03:29 -0800157 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
scroggo05245902015-03-25 11:11:52 -0700158 return true;
scroggof24f2242015-03-03 08:59:20 -0800159}
160
161///////////////////////////////////////////////////////////////////////////////
162// Creation
163///////////////////////////////////////////////////////////////////////////////
164
scroggodb30be22015-12-08 18:54:13 -0800165bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
166 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800167}
168
msarett6a738212016-03-04 13:27:35 -0800169static float png_fixed_point_to_float(png_fixed_point x) {
170 // We multiply by the same factor that libpng used to convert
171 // fixed point -> double. Since we want floats, we choose to
172 // do the conversion ourselves rather than convert
173 // fixed point -> double -> float.
174 return ((float) x) * 0.00001f;
175}
176
msarett128245c2016-03-30 12:01:47 -0700177static float png_inverted_fixed_point_to_float(png_fixed_point x) {
178 // This is necessary because the gAMA chunk actually stores 1/gamma.
179 return 1.0f / png_fixed_point_to_float(x);
180}
181
msarett6a738212016-03-04 13:27:35 -0800182// Returns a colorSpace object that represents any color space information in
183// the encoded data. If the encoded data contains no color space, this will
184// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800185sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800186
msarette2443222016-03-04 14:20:49 -0800187#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
188
msarett6a738212016-03-04 13:27:35 -0800189 // First check for an ICC profile
190 png_bytep profile;
191 png_uint_32 length;
192 // The below variables are unused, however, we need to pass them in anyway or
193 // png_get_iCCP() will return nothing.
194 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
195 png_charp name;
196 // The |compression| is uninteresting since:
197 // (1) libpng has already decompressed the profile for us.
198 // (2) "deflate" is the only mode of decompression that libpng supports.
199 int compression;
200 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
201 &length)) {
202 return SkColorSpace::NewICC(profile, length);
203 }
204
205 // Second, check for sRGB.
206 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
207
208 // sRGB chunks also store a rendering intent: Absolute, Relative,
209 // Perceptual, and Saturation.
210 // FIXME (msarett): Extract this information from the sRGB chunk once
211 // we are able to handle this information in
212 // SkColorSpace.
213 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
214 }
215
216 // Next, check for chromaticities.
217 png_fixed_point XYZ[9];
218 SkFloat3x3 toXYZD50;
219 png_fixed_point gamma;
220 SkFloat3 gammas;
221 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &XYZ[0], &XYZ[1], &XYZ[2], &XYZ[3], &XYZ[4],
222 &XYZ[5], &XYZ[6], &XYZ[7], &XYZ[8])) {
223
224 // FIXME (msarett): Here we are treating XYZ values as D50 even though the color
225 // temperature is unspecified. I suspect that this assumption
226 // is most often ok, but we could also calculate the color
227 // temperature (D value) and then convert the XYZ to D50. Maybe
228 // we should add a new constructor to SkColorSpace that accepts
229 // XYZ with D-Unkown?
230 for (int i = 0; i < 9; i++) {
231 toXYZD50.fMat[i] = png_fixed_point_to_float(XYZ[i]);
232 }
233
msarett128245c2016-03-30 12:01:47 -0700234 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
235 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] =
236 png_inverted_fixed_point_to_float(gamma);
237 } else {
msarett6a738212016-03-04 13:27:35 -0800238 // If the image does not specify gamma, let's choose linear. Should we default
239 // to sRGB? Most images are intended to be sRGB (gamma = 2.2f).
msarett128245c2016-03-30 12:01:47 -0700240 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = 1.0f;
msarett6a738212016-03-04 13:27:35 -0800241 }
msarett128245c2016-03-30 12:01:47 -0700242
msarett6a738212016-03-04 13:27:35 -0800243
244 return SkColorSpace::NewRGB(toXYZD50, gammas);
245 }
246
247 // Last, check for gamma.
248 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
249
250 // Guess a default value for cHRM? Or should we just give up?
251 // Here we use the identity matrix as a default.
252 // FIXME (msarett): Should SkFloat3x3 have a method to set the identity matrix?
253 memset(toXYZD50.fMat, 0, 9 * sizeof(float));
254 toXYZD50.fMat[0] = toXYZD50.fMat[4] = toXYZD50.fMat[8] = 1.0f;
255
256 // Set the gammas.
msarett128245c2016-03-30 12:01:47 -0700257 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = png_inverted_fixed_point_to_float(gamma);
msarett6a738212016-03-04 13:27:35 -0800258
259 return SkColorSpace::NewRGB(toXYZD50, gammas);
260 }
261
msarette2443222016-03-04 14:20:49 -0800262#endif // LIBPNG >= 1.6
263
msarett6a738212016-03-04 13:27:35 -0800264 // Finally, what should we do if there is no color space information in the PNG?
265 // The specification says that this indicates "gamma is unknown" and that the
266 // "color is device dependent". I'm assuming we can represent this with NULL.
267 // But should we guess sRGB? Most images are sRGB, even if they don't specify.
268 return nullptr;
269}
270
scroggocf98fa92015-11-23 08:14:40 -0800271// Reads the header and initializes the output fields, if not NULL.
272//
273// @param stream Input data. Will be read to get enough information to properly
274// setup the codec.
275// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
276// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
277// expected to continue to own it for the lifetime of the png_ptr.
278// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
279// png_structp on success.
280// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
281// png_infop on success;
282// @param imageInfo Optional output variable. If non-NULL, will be set to
283// reflect the properties of the encoded image on success.
284// @param bitDepthPtr Optional output variable. If non-NULL, will be set to the
285// bit depth of the encoded image on success.
286// @param numberPassesPtr Optional output variable. If non-NULL, will be set to
287// the number_passes of the encoded image on success.
288// @return true on success, in which case the caller is responsible for calling
289// png_destroy_read_struct(png_ptrp, info_ptrp).
290// If it returns false, the passed in fields (except stream) are unchanged.
291static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader,
292 png_structp* png_ptrp, png_infop* info_ptrp,
293 SkImageInfo* imageInfo, int* bitDepthPtr, int* numberPassesPtr) {
scroggof24f2242015-03-03 08:59:20 -0800294 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
halcanary96fcdcc2015-08-27 07:41:13 -0700295 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
scroggo0eed6df2015-03-26 10:07:56 -0700296 sk_error_fn, sk_warning_fn);
scroggof24f2242015-03-03 08:59:20 -0800297 if (!png_ptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700298 return false;
scroggof24f2242015-03-03 08:59:20 -0800299 }
300
301 AutoCleanPng autoClean(png_ptr);
302
303 png_infop info_ptr = png_create_info_struct(png_ptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700304 if (info_ptr == nullptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700305 return false;
scroggof24f2242015-03-03 08:59:20 -0800306 }
307
308 autoClean.setInfoPtr(info_ptr);
309
310 // FIXME: Could we use the return value of setjmp to specify the type of
311 // error?
312 if (setjmp(png_jmpbuf(png_ptr))) {
scroggo3eada2a2015-04-01 09:33:23 -0700313 return false;
scroggof24f2242015-03-03 08:59:20 -0800314 }
315
316 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
317
scroggocf98fa92015-11-23 08:14:40 -0800318#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
msarett133eaaa2016-01-07 11:03:25 -0800319 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
320 // This needs to be installed before we read the png header. Android may store ninepatch
321 // chunks in the header.
scroggocf98fa92015-11-23 08:14:40 -0800322 if (chunkReader) {
323 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
324 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
325 }
326#endif
scroggof24f2242015-03-03 08:59:20 -0800327
328 // The call to png_read_info() gives us all of the information from the
329 // PNG file before the first IDAT (image data chunk).
330 png_read_info(png_ptr, info_ptr);
331 png_uint_32 origWidth, origHeight;
msarett13a91232016-02-01 08:03:29 -0800332 int bitDepth, encodedColorType;
scroggof24f2242015-03-03 08:59:20 -0800333 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarett13a91232016-02-01 08:03:29 -0800334 &encodedColorType, nullptr, nullptr, nullptr);
scroggof24f2242015-03-03 08:59:20 -0800335
scroggo6f29a3c2015-07-07 06:09:08 -0700336 if (bitDepthPtr) {
337 *bitDepthPtr = bitDepth;
338 }
339
msarett13a91232016-02-01 08:03:29 -0800340 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
341 // TODO: Should we handle this in SkSwizzler? Could this also benefit
342 // RAW decodes?
scroggof24f2242015-03-03 08:59:20 -0800343 if (bitDepth == 16) {
msarett13a91232016-02-01 08:03:29 -0800344 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggof24f2242015-03-03 08:59:20 -0800345 png_set_strip_16(png_ptr);
346 }
scroggof24f2242015-03-03 08:59:20 -0800347
msarett13a91232016-02-01 08:03:29 -0800348 // Now determine the default colorType and alphaType and set the required transforms.
349 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
350 // still depend on libpng for many of the rare and PNG-specific cases.
351 SkColorType colorType = kUnknown_SkColorType;
352 SkAlphaType alphaType = kUnknown_SkAlphaType;
353 switch (encodedColorType) {
scroggof24f2242015-03-03 08:59:20 -0800354 case PNG_COLOR_TYPE_PALETTE:
msarett13a91232016-02-01 08:03:29 -0800355 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
356 // byte into separate bytes (useful for paletted and grayscale images).
357 if (bitDepth < 8) {
358 // TODO: Should we use SkSwizzler here?
359 png_set_packing(png_ptr);
360 }
361
362 colorType = kIndex_8_SkColorType;
363 // Set the alpha type depending on if a transparency chunk exists.
364 alphaType = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
scroggof24f2242015-03-03 08:59:20 -0800365 kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
366 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700367 case PNG_COLOR_TYPE_RGB:
msarett13a91232016-02-01 08:03:29 -0800368 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
369 // Convert to RGBA if transparency chunk exists.
scroggo6f29a3c2015-07-07 06:09:08 -0700370 png_set_tRNS_to_alpha(png_ptr);
msarett13a91232016-02-01 08:03:29 -0800371 alphaType = kUnpremul_SkAlphaType;
jvanverth6c90e092015-07-02 10:35:25 -0700372 } else {
msarett13a91232016-02-01 08:03:29 -0800373 alphaType = kOpaque_SkAlphaType;
jvanverth6c90e092015-07-02 10:35:25 -0700374 }
msarett13a91232016-02-01 08:03:29 -0800375 colorType = kN32_SkColorType;
jvanverth6c90e092015-07-02 10:35:25 -0700376 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700377 case PNG_COLOR_TYPE_GRAY:
msarett13a91232016-02-01 08:03:29 -0800378 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
379 if (bitDepth < 8) {
380 // TODO: Should we use SkSwizzler here?
381 png_set_expand_gray_1_2_4_to_8(png_ptr);
382 }
383
384 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
scroggo6f29a3c2015-07-07 06:09:08 -0700385 png_set_tRNS_to_alpha(png_ptr);
msarett93e613d2016-02-03 10:44:46 -0800386
387 // We will recommend kN32 here since we do not support kGray
388 // with alpha.
msarett13a91232016-02-01 08:03:29 -0800389 colorType = kN32_SkColorType;
390 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700391 } else {
msarett13a91232016-02-01 08:03:29 -0800392 colorType = kGray_8_SkColorType;
393 alphaType = kOpaque_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700394 }
395 break;
396 case PNG_COLOR_TYPE_GRAY_ALPHA:
msarett93e613d2016-02-03 10:44:46 -0800397 // We will recommend kN32 here since we do not support anything
398 // similar to GRAY_ALPHA.
msarett13a91232016-02-01 08:03:29 -0800399 colorType = kN32_SkColorType;
400 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700401 break;
402 case PNG_COLOR_TYPE_RGBA:
msarett13a91232016-02-01 08:03:29 -0800403 colorType = kN32_SkColorType;
404 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700405 break;
406 default:
msarett13a91232016-02-01 08:03:29 -0800407 // All the color types have been covered above.
scroggo6f29a3c2015-07-07 06:09:08 -0700408 SkASSERT(false);
scroggof24f2242015-03-03 08:59:20 -0800409 }
410
scroggo46c57472015-09-30 08:57:13 -0700411 int numberPasses = png_set_interlace_handling(png_ptr);
412 if (numberPassesPtr) {
413 *numberPassesPtr = numberPasses;
414 }
415
msaretta87d6de2016-02-04 15:37:58 -0800416 SkColorProfileType profileType = kLinear_SkColorProfileType;
417 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
418 profileType = kSRGB_SkColorProfileType;
419 }
scroggof24f2242015-03-03 08:59:20 -0800420
scroggo3eada2a2015-04-01 09:33:23 -0700421 if (imageInfo) {
msaretta87d6de2016-02-04 15:37:58 -0800422 *imageInfo = SkImageInfo::Make(origWidth, origHeight, colorType, alphaType, profileType);
scroggo3eada2a2015-04-01 09:33:23 -0700423 }
mtklein18300a32016-03-16 13:53:35 -0700424 autoClean.release();
scroggo3eada2a2015-04-01 09:33:23 -0700425 if (png_ptrp) {
426 *png_ptrp = png_ptr;
427 }
428 if (info_ptrp) {
429 *info_ptrp = info_ptr;
430 }
scroggo6f29a3c2015-07-07 06:09:08 -0700431
scroggo3eada2a2015-04-01 09:33:23 -0700432 return true;
433}
434
scroggocf98fa92015-11-23 08:14:40 -0800435SkPngCodec::SkPngCodec(const SkImageInfo& info, SkStream* stream, SkPngChunkReader* chunkReader,
msarett6a738212016-03-04 13:27:35 -0800436 png_structp png_ptr, png_infop info_ptr, int bitDepth, int numberPasses,
msarettad8bcfe2016-03-07 07:09:03 -0800437 sk_sp<SkColorSpace> colorSpace)
msarett6a738212016-03-04 13:27:35 -0800438 : INHERITED(info, stream, colorSpace)
scroggocf98fa92015-11-23 08:14:40 -0800439 , fPngChunkReader(SkSafeRef(chunkReader))
scroggof24f2242015-03-03 08:59:20 -0800440 , fPng_ptr(png_ptr)
scroggo05245902015-03-25 11:11:52 -0700441 , fInfo_ptr(info_ptr)
442 , fSrcConfig(SkSwizzler::kUnknown)
scroggo46c57472015-09-30 08:57:13 -0700443 , fNumberPasses(numberPasses)
scroggo6f29a3c2015-07-07 06:09:08 -0700444 , fBitDepth(bitDepth)
msaretta4970dc2016-01-11 07:23:23 -0800445{}
scroggof24f2242015-03-03 08:59:20 -0800446
447SkPngCodec::~SkPngCodec() {
scroggo3eada2a2015-04-01 09:33:23 -0700448 this->destroyReadStruct();
449}
450
451void SkPngCodec::destroyReadStruct() {
452 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -0700453 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
scroggo3eada2a2015-04-01 09:33:23 -0700454 SkASSERT(fInfo_ptr);
msarett13a91232016-02-01 08:03:29 -0800455 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, nullptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700456 fPng_ptr = nullptr;
457 fInfo_ptr = nullptr;
scroggo3eada2a2015-04-01 09:33:23 -0700458 }
scroggof24f2242015-03-03 08:59:20 -0800459}
460
461///////////////////////////////////////////////////////////////////////////////
462// Getting the pixels
463///////////////////////////////////////////////////////////////////////////////
464
scroggo05245902015-03-25 11:11:52 -0700465SkCodec::Result SkPngCodec::initializeSwizzler(const SkImageInfo& requestedInfo,
msarett438b2ad2015-04-09 12:43:10 -0700466 const Options& options,
msarett9e43cab2015-04-29 07:38:43 -0700467 SkPMColor ctable[],
msarett438b2ad2015-04-09 12:43:10 -0700468 int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -0800469 // FIXME: Could we use the return value of setjmp to specify the type of
470 // error?
471 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700472 SkCodecPrintf("setjmp long jump!\n");
scroggof24f2242015-03-03 08:59:20 -0800473 return kInvalidInput;
474 }
mtklein372d65c2016-01-27 13:01:41 -0800475 png_read_update_info(fPng_ptr, fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -0800476
msarett93e613d2016-02-03 10:44:46 -0800477 // suggestedColorType was determined in read_header() based on the encodedColorType
478 const SkColorType suggestedColorType = this->getInfo().colorType();
scroggo6f29a3c2015-07-07 06:09:08 -0700479
msarett93e613d2016-02-03 10:44:46 -0800480 switch (suggestedColorType) {
scroggo6f29a3c2015-07-07 06:09:08 -0700481 case kIndex_8_SkColorType:
482 //decode palette to Skia format
483 fSrcConfig = SkSwizzler::kIndex;
scroggo9b2cdbf42015-07-10 12:07:02 -0700484 if (!this->decodePalette(kPremul_SkAlphaType == requestedInfo.alphaType(),
scroggo6f29a3c2015-07-07 06:09:08 -0700485 ctableCount)) {
486 return kInvalidInput;
487 }
488 break;
489 case kGray_8_SkColorType:
490 fSrcConfig = SkSwizzler::kGray;
mtklein372d65c2016-01-27 13:01:41 -0800491 break;
msarett93e613d2016-02-03 10:44:46 -0800492 case kN32_SkColorType: {
493 const uint8_t encodedColorType = png_get_color_type(fPng_ptr, fInfo_ptr);
494 if (PNG_COLOR_TYPE_GRAY_ALPHA == encodedColorType ||
495 PNG_COLOR_TYPE_GRAY == encodedColorType) {
496 // If encodedColorType is GRAY, there must be a transparent chunk.
497 // Otherwise, suggestedColorType would be kGray. We have already
498 // instructed libpng to convert the transparent chunk to alpha,
499 // so we can treat both GRAY and GRAY_ALPHA as kGrayAlpha.
500 SkASSERT(encodedColorType == PNG_COLOR_TYPE_GRAY_ALPHA ||
501 png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS));
502
503 fSrcConfig = SkSwizzler::kGrayAlpha;
504 } else {
505 if (this->getInfo().alphaType() == kOpaque_SkAlphaType) {
msarettbda86092016-01-19 10:40:12 -0800506 fSrcConfig = SkSwizzler::kRGB;
scroggo6f29a3c2015-07-07 06:09:08 -0700507 } else {
508 fSrcConfig = SkSwizzler::kRGBA;
msarett93e613d2016-02-03 10:44:46 -0800509 }
scroggo6f29a3c2015-07-07 06:09:08 -0700510 }
511 break;
msarett93e613d2016-02-03 10:44:46 -0800512 }
scroggo6f29a3c2015-07-07 06:09:08 -0700513 default:
msarett13a91232016-02-01 08:03:29 -0800514 // We will always recommend one of the above colorTypes.
scroggo6f29a3c2015-07-07 06:09:08 -0700515 SkASSERT(false);
mtklein372d65c2016-01-27 13:01:41 -0800516 }
msarett9e43cab2015-04-29 07:38:43 -0700517
518 // Copy the color table to the client if they request kIndex8 mode
519 copy_color_table(requestedInfo, fColorTable, ctable, ctableCount);
520
521 // Create the swizzler. SkPngCodec retains ownership of the color table.
msarett99f567e2015-08-05 12:58:26 -0700522 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettfdb47572015-10-13 12:50:14 -0700523 fSwizzler.reset(SkSwizzler::CreateSwizzler(fSrcConfig, colors, requestedInfo, options));
msarett13a91232016-02-01 08:03:29 -0800524 SkASSERT(fSwizzler);
525
scroggo05245902015-03-25 11:11:52 -0700526 return kSuccess;
527}
528
scroggo6f29a3c2015-07-07 06:09:08 -0700529
scroggob427db12015-08-12 07:24:13 -0700530bool SkPngCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700531 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
scroggob427db12015-08-12 07:24:13 -0700532 // succeeds, they will be repopulated, and if it fails, they will
halcanary96fcdcc2015-08-27 07:41:13 -0700533 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
scroggob427db12015-08-12 07:24:13 -0700534 // come through this function which will rewind and again attempt
535 // to reinitialize them.
536 this->destroyReadStruct();
537
538 png_structp png_ptr;
539 png_infop info_ptr;
scroggocf98fa92015-11-23 08:14:40 -0800540 if (!read_header(this->stream(), fPngChunkReader.get(), &png_ptr, &info_ptr,
541 nullptr, nullptr, nullptr)) {
scroggob427db12015-08-12 07:24:13 -0700542 return false;
scroggo58421542015-04-01 11:25:20 -0700543 }
scroggob427db12015-08-12 07:24:13 -0700544
545 fPng_ptr = png_ptr;
546 fInfo_ptr = info_ptr;
547 return true;
scroggo58421542015-04-01 11:25:20 -0700548}
549
scroggo05245902015-03-25 11:11:52 -0700550SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
msarett614aa072015-07-27 15:13:17 -0700551 size_t dstRowBytes, const Options& options,
msarette6dd0042015-10-09 11:07:34 -0700552 SkPMColor ctable[], int* ctableCount,
553 int* rowsDecoded) {
scroggo6f29a3c2015-07-07 06:09:08 -0700554 if (!conversion_possible(requestedInfo, this->getInfo())) {
555 return kInvalidConversion;
556 }
scroggob636b452015-07-22 07:16:20 -0700557 if (options.fSubset) {
558 // Subsets are not supported.
559 return kUnimplemented;
560 }
scroggo05245902015-03-25 11:11:52 -0700561
msarett9e43cab2015-04-29 07:38:43 -0700562 // Note that ctable and ctableCount may be modified if there is a color table
msarettfdb47572015-10-13 12:50:14 -0700563 const Result result = this->initializeSwizzler(requestedInfo, options, ctable, ctableCount);
scroggo05245902015-03-25 11:11:52 -0700564 if (result != kSuccess) {
565 return result;
566 }
msarett60dcd3c2016-02-05 15:13:12 -0800567
568 const int width = requestedInfo.width();
569 const int height = requestedInfo.height();
570 const int bpp = SkSwizzler::BytesPerPixel(fSrcConfig);
571 const size_t srcRowBytes = width * bpp;
572
scroggo05245902015-03-25 11:11:52 -0700573 // FIXME: Could we use the return value of setjmp to specify the type of
574 // error?
msarette6dd0042015-10-09 11:07:34 -0700575 int row = 0;
576 // This must be declared above the call to setjmp to avoid memory leaks on incomplete images.
scroggo565901d2015-12-10 10:44:13 -0800577 SkAutoTMalloc<uint8_t> storage;
scroggo05245902015-03-25 11:11:52 -0700578 if (setjmp(png_jmpbuf(fPng_ptr))) {
msarette6dd0042015-10-09 11:07:34 -0700579 // Assume that any error that occurs while reading rows is caused by an incomplete input.
580 if (fNumberPasses > 1) {
581 // FIXME (msarett): Handle incomplete interlaced pngs.
msarett60dcd3c2016-02-05 15:13:12 -0800582 return (row == height) ? kSuccess : kInvalidInput;
msarette6dd0042015-10-09 11:07:34 -0700583 }
584 // FIXME: We do a poor job on incomplete pngs compared to other decoders (ex: Chromium,
585 // Ubuntu Image Viewer). This is because we use the default buffer size in libpng (8192
586 // bytes), and if we can't fill the buffer, we immediately fail.
587 // For example, if we try to read 8192 bytes, and the image (incorrectly) only contains
588 // half that, which may have been enough to contain a non-zero number of lines, we fail
589 // when we could have decoded a few more lines and then failed.
590 // The read function that we provide for libpng has no way of indicating that we have
591 // made a partial read.
592 // Making our buffer size smaller improves our incomplete decodes, but what impact does
593 // it have on regular decode performance? Should we investigate using a different API
msarett60dcd3c2016-02-05 15:13:12 -0800594 // instead of png_read_row? Chromium uses png_process_data.
msarette6dd0042015-10-09 11:07:34 -0700595 *rowsDecoded = row;
msarett60dcd3c2016-02-05 15:13:12 -0800596 return (row == height) ? kSuccess : kIncompleteInput;
scroggo05245902015-03-25 11:11:52 -0700597 }
598
scroggo46c57472015-09-30 08:57:13 -0700599 // FIXME: We could split these out based on subclass.
msarett614aa072015-07-27 15:13:17 -0700600 void* dstRow = dst;
scroggo05245902015-03-25 11:11:52 -0700601 if (fNumberPasses > 1) {
msarett60dcd3c2016-02-05 15:13:12 -0800602 storage.reset(height * srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800603 uint8_t* const base = storage.get();
scroggof24f2242015-03-03 08:59:20 -0800604
scroggo05245902015-03-25 11:11:52 -0700605 for (int i = 0; i < fNumberPasses; i++) {
msarett614aa072015-07-27 15:13:17 -0700606 uint8_t* srcRow = base;
scroggof24f2242015-03-03 08:59:20 -0800607 for (int y = 0; y < height; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800608 png_read_row(fPng_ptr, srcRow, nullptr);
msarett614aa072015-07-27 15:13:17 -0700609 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800610 }
611 }
612
613 // Now swizzle it.
msarett614aa072015-07-27 15:13:17 -0700614 uint8_t* srcRow = base;
msarett60dcd3c2016-02-05 15:13:12 -0800615 for (; row < height; row++) {
msaretta4970dc2016-01-11 07:23:23 -0800616 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700617 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
618 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800619 }
620 } else {
msarett60dcd3c2016-02-05 15:13:12 -0800621 storage.reset(srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800622 uint8_t* srcRow = storage.get();
msarett60dcd3c2016-02-05 15:13:12 -0800623 for (; row < height; row++) {
624 png_read_row(fPng_ptr, srcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800625 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700626 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
scroggof24f2242015-03-03 08:59:20 -0800627 }
628 }
629
emmaleer973ae862015-07-20 13:38:44 -0700630 // read rest of file, and get additional comment and time chunks in info_ptr
scroggo05245902015-03-25 11:11:52 -0700631 png_read_end(fPng_ptr, fInfo_ptr);
scroggo46c57472015-09-30 08:57:13 -0700632
emmaleer973ae862015-07-20 13:38:44 -0700633 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700634}
635
scroggoc5560be2016-02-03 09:42:42 -0800636uint32_t SkPngCodec::onGetFillValue(SkColorType colorType) const {
msarette6dd0042015-10-09 11:07:34 -0700637 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
638 if (colorPtr) {
639 return get_color_table_fill_value(colorType, colorPtr, 0);
640 }
scroggoc5560be2016-02-03 09:42:42 -0800641 return INHERITED::onGetFillValue(colorType);
msarette6dd0042015-10-09 11:07:34 -0700642}
643
scroggo46c57472015-09-30 08:57:13 -0700644// Subclass of SkPngCodec which supports scanline decoding
645class SkPngScanlineDecoder : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700646public:
scroggo46c57472015-09-30 08:57:13 -0700647 SkPngScanlineDecoder(const SkImageInfo& srcInfo, SkStream* stream,
msarett6a738212016-03-04 13:27:35 -0800648 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr, int bitDepth,
msarettad8bcfe2016-03-07 07:09:03 -0800649 sk_sp<SkColorSpace> colorSpace)
msarett6a738212016-03-04 13:27:35 -0800650 : INHERITED(srcInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, 1, colorSpace)
msarettf724b992015-10-15 06:41:06 -0700651 , fSrcRow(nullptr)
scroggo1c005e42015-08-04 09:24:45 -0700652 {}
653
scroggo46c57472015-09-30 08:57:13 -0700654 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
655 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700656 if (!conversion_possible(dstInfo, this->getInfo())) {
scroggo46c57472015-09-30 08:57:13 -0700657 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700658 }
659
scroggo46c57472015-09-30 08:57:13 -0700660 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
661 ctableCount);
662 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700663 return result;
664 }
665
scroggo46c57472015-09-30 08:57:13 -0700666 fStorage.reset(this->getInfo().width() * SkSwizzler::BytesPerPixel(this->srcConfig()));
scroggo565901d2015-12-10 10:44:13 -0800667 fSrcRow = fStorage.get();
scroggo1c005e42015-08-04 09:24:45 -0700668
scroggo46c57472015-09-30 08:57:13 -0700669 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700670 }
671
msarette6dd0042015-10-09 11:07:34 -0700672 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
673 // Assume that an error in libpng indicates an incomplete input.
674 int row = 0;
scroggo46c57472015-09-30 08:57:13 -0700675 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700676 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700677 return row;
scroggo05245902015-03-25 11:11:52 -0700678 }
679
msarett614aa072015-07-27 15:13:17 -0700680 void* dstRow = dst;
msarette6dd0042015-10-09 11:07:34 -0700681 for (; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800682 png_read_row(this->png_ptr(), fSrcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800683 this->swizzler()->swizzle(dstRow, fSrcRow);
msarett614aa072015-07-27 15:13:17 -0700684 dstRow = SkTAddOffset<void>(dstRow, rowBytes);
scroggo05245902015-03-25 11:11:52 -0700685 }
scroggo46c57472015-09-30 08:57:13 -0700686
msarette6dd0042015-10-09 11:07:34 -0700687 return row;
scroggo05245902015-03-25 11:11:52 -0700688 }
689
msarette6dd0042015-10-09 11:07:34 -0700690 bool onSkipScanlines(int count) override {
691 // Assume that an error in libpng indicates an incomplete input.
scroggo46c57472015-09-30 08:57:13 -0700692 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700693 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700694 return false;
scroggo05245902015-03-25 11:11:52 -0700695 }
msarett60dcd3c2016-02-05 15:13:12 -0800696
msarette6dd0042015-10-09 11:07:34 -0700697 for (int row = 0; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800698 png_read_row(this->png_ptr(), fSrcRow, nullptr);
emmaleer7dc91902015-05-27 08:49:04 -0700699 }
msarette6dd0042015-10-09 11:07:34 -0700700 return true;
scroggo05245902015-03-25 11:11:52 -0700701 }
702
scroggo05245902015-03-25 11:11:52 -0700703private:
scroggo565901d2015-12-10 10:44:13 -0800704 SkAutoTMalloc<uint8_t> fStorage;
scroggo9b2cdbf42015-07-10 12:07:02 -0700705 uint8_t* fSrcRow;
scroggo05245902015-03-25 11:11:52 -0700706
scroggo46c57472015-09-30 08:57:13 -0700707 typedef SkPngCodec INHERITED;
scroggo05245902015-03-25 11:11:52 -0700708};
709
emmaleer0a4c3cb2015-06-22 10:40:21 -0700710
scroggo46c57472015-09-30 08:57:13 -0700711class SkPngInterlacedScanlineDecoder : public SkPngCodec {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700712public:
scroggo46c57472015-09-30 08:57:13 -0700713 SkPngInterlacedScanlineDecoder(const SkImageInfo& srcInfo, SkStream* stream,
scroggocf98fa92015-11-23 08:14:40 -0800714 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr,
msarettad8bcfe2016-03-07 07:09:03 -0800715 int bitDepth, int numberPasses, sk_sp<SkColorSpace> colorSpace)
msarett6a738212016-03-04 13:27:35 -0800716 : INHERITED(srcInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, numberPasses,
717 colorSpace)
scroggo46c57472015-09-30 08:57:13 -0700718 , fHeight(-1)
scroggo1c005e42015-08-04 09:24:45 -0700719 , fCanSkipRewind(false)
scroggo1c005e42015-08-04 09:24:45 -0700720 {
scroggo46c57472015-09-30 08:57:13 -0700721 SkASSERT(numberPasses != 1);
722 }
723
724 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
msarettfdb47572015-10-13 12:50:14 -0700725 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700726 if (!conversion_possible(dstInfo, this->getInfo())) {
mtklein372d65c2016-01-27 13:01:41 -0800727 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700728 }
729
msarettfdb47572015-10-13 12:50:14 -0700730 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
731 ctableCount);
732 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700733 return result;
734 }
735
scroggo1c005e42015-08-04 09:24:45 -0700736 fHeight = dstInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700737 // FIXME: This need not be called on a second call to onStartScanlineDecode.
738 fSrcRowBytes = this->getInfo().width() * SkSwizzler::BytesPerPixel(this->srcConfig());
scroggo1c005e42015-08-04 09:24:45 -0700739 fGarbageRow.reset(fSrcRowBytes);
740 fGarbageRowPtr = static_cast<uint8_t*>(fGarbageRow.get());
741 fCanSkipRewind = true;
742
743 return SkCodec::kSuccess;
744 }
745
msarette6dd0042015-10-09 11:07:34 -0700746 int onGetScanlines(void* dst, int count, size_t dstRowBytes) override {
scroggo1c005e42015-08-04 09:24:45 -0700747 // rewind stream if have previously called onGetScanlines,
748 // since we need entire progressive image to get scanlines
749 if (fCanSkipRewind) {
scroggo46c57472015-09-30 08:57:13 -0700750 // We already rewound in onStartScanlineDecode, so there is no reason to rewind.
scroggo1c005e42015-08-04 09:24:45 -0700751 // Next time onGetScanlines is called, we will need to rewind.
752 fCanSkipRewind = false;
scroggo46c57472015-09-30 08:57:13 -0700753 } else {
754 // rewindIfNeeded resets fCurrScanline, since it assumes that start
755 // needs to be called again before scanline decoding. PNG scanline
756 // decoding is the exception, since it needs to rewind between
757 // calls to getScanlines. Keep track of fCurrScanline, to undo the
758 // reset.
msarette6dd0042015-10-09 11:07:34 -0700759 const int currScanline = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700760 // This method would never be called if currScanline is -1
761 SkASSERT(currScanline != -1);
762
763 if (!this->rewindIfNeeded()) {
764 return kCouldNotRewind;
765 }
msarettcb0d5c92015-12-03 12:23:43 -0800766 this->updateCurrScanline(currScanline);
scroggo1c005e42015-08-04 09:24:45 -0700767 }
768
scroggo46c57472015-09-30 08:57:13 -0700769 if (setjmp(png_jmpbuf(this->png_ptr()))) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700770 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700771 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
772 // we may be able to report that all of the memory has been initialized. Even if we
773 // fail on the first pass, we can still report than some scanlines are initialized.
774 return 0;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700775 }
scroggo565901d2015-12-10 10:44:13 -0800776 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
777 uint8_t* storagePtr = storage.get();
emmaleer0a4c3cb2015-06-22 10:40:21 -0700778 uint8_t* srcRow;
msarette6dd0042015-10-09 11:07:34 -0700779 const int startRow = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700780 for (int i = 0; i < this->numberPasses(); i++) {
781 // read rows we planned to skip into garbage row
782 for (int y = 0; y < startRow; y++){
msarett60dcd3c2016-02-05 15:13:12 -0800783 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700784 }
scroggo46c57472015-09-30 08:57:13 -0700785 // read rows we care about into buffer
emmaleer0a4c3cb2015-06-22 10:40:21 -0700786 srcRow = storagePtr;
787 for (int y = 0; y < count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800788 png_read_row(this->png_ptr(), srcRow, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700789 srcRow += fSrcRowBytes;
790 }
scroggo46c57472015-09-30 08:57:13 -0700791 // read rows we don't want into garbage buffer
792 for (int y = 0; y < fHeight - startRow - count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800793 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700794 }
795 }
796 //swizzle the rows we care about
797 srcRow = storagePtr;
msarett614aa072015-07-27 15:13:17 -0700798 void* dstRow = dst;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700799 for (int y = 0; y < count; y++) {
msaretta4970dc2016-01-11 07:23:23 -0800800 this->swizzler()->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700801 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700802 srcRow += fSrcRowBytes;
803 }
scroggo46c57472015-09-30 08:57:13 -0700804
msarette6dd0042015-10-09 11:07:34 -0700805 return count;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700806 }
807
msarette6dd0042015-10-09 11:07:34 -0700808 bool onSkipScanlines(int count) override {
scroggo46c57472015-09-30 08:57:13 -0700809 // The non-virtual version will update fCurrScanline.
msarette6dd0042015-10-09 11:07:34 -0700810 return true;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700811 }
812
msarett5406d6f2015-08-31 06:55:13 -0700813 SkScanlineOrder onGetScanlineOrder() const override {
814 return kNone_SkScanlineOrder;
emmaleer8f4ba762015-08-14 07:44:46 -0700815 }
816
emmaleer0a4c3cb2015-06-22 10:40:21 -0700817private:
scroggo9b2cdbf42015-07-10 12:07:02 -0700818 int fHeight;
819 size_t fSrcRowBytes;
820 SkAutoMalloc fGarbageRow;
821 uint8_t* fGarbageRowPtr;
scroggo1c005e42015-08-04 09:24:45 -0700822 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
823 // is called whenever some action is taken that reads the stream and
824 // therefore the next call will require a rewind. So it modifies a boolean
825 // to note that the *next* time it is called a rewind is needed.
scroggo46c57472015-09-30 08:57:13 -0700826 // SkPngInterlacedScanlineDecoder has an extra wrinkle - calling
827 // onStartScanlineDecode followed by onGetScanlines does *not* require a
828 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
829 // add another layer.
scroggo1c005e42015-08-04 09:24:45 -0700830 bool fCanSkipRewind;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700831
scroggo46c57472015-09-30 08:57:13 -0700832 typedef SkPngCodec INHERITED;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700833};
834
scroggocf98fa92015-11-23 08:14:40 -0800835SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
scroggo46c57472015-09-30 08:57:13 -0700836 SkAutoTDelete<SkStream> streamDeleter(stream);
837 png_structp png_ptr;
838 png_infop info_ptr;
839 SkImageInfo imageInfo;
840 int bitDepth;
841 int numberPasses;
842
scroggocf98fa92015-11-23 08:14:40 -0800843 if (!read_header(stream, chunkReader, &png_ptr, &info_ptr, &imageInfo, &bitDepth,
844 &numberPasses)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700845 return nullptr;
scroggo05245902015-03-25 11:11:52 -0700846 }
847
msarettad8bcfe2016-03-07 07:09:03 -0800848 auto colorSpace = read_color_space(png_ptr, info_ptr);
msarett6a738212016-03-04 13:27:35 -0800849
scroggo46c57472015-09-30 08:57:13 -0700850 if (1 == numberPasses) {
mtklein18300a32016-03-16 13:53:35 -0700851 return new SkPngScanlineDecoder(imageInfo, streamDeleter.release(), chunkReader,
msarett6a738212016-03-04 13:27:35 -0800852 png_ptr, info_ptr, bitDepth, colorSpace);
scroggo05245902015-03-25 11:11:52 -0700853 }
854
mtklein18300a32016-03-16 13:53:35 -0700855 return new SkPngInterlacedScanlineDecoder(imageInfo, streamDeleter.release(), chunkReader,
msarett6a738212016-03-04 13:27:35 -0800856 png_ptr, info_ptr, bitDepth, numberPasses,
857 colorSpace);
scroggo05245902015-03-25 11:11:52 -0700858}