blob: 1b51432e5ec1c1bb143ca69972d08968ce1a8c5f [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
msarett74114382015-03-16 11:55:18 -07008#include "SkCodecPriv.h"
scroggof24f2242015-03-03 08:59:20 -08009#include "SkColorPriv.h"
10#include "SkColorTable.h"
11#include "SkBitmap.h"
12#include "SkMath.h"
msarett13a91232016-02-01 08:03:29 -080013#include "SkOpts.h"
msarettbe1d5552016-01-21 09:05:23 -080014#include "SkPngCodec.h"
scroggof24f2242015-03-03 08:59:20 -080015#include "SkSize.h"
16#include "SkStream.h"
17#include "SkSwizzler.h"
scroggo565901d2015-12-10 10:44:13 -080018#include "SkTemplates.h"
bungeman5d2cd6e2016-02-23 07:34:25 -080019#include "SkUtils.h"
scroggof24f2242015-03-03 08:59:20 -080020
21///////////////////////////////////////////////////////////////////////////////
scroggof24f2242015-03-03 08:59:20 -080022// Callback functions
23///////////////////////////////////////////////////////////////////////////////
24
25static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
scroggo230d4ac2015-03-26 07:15:55 -070026 SkCodecPrintf("------ png error %s\n", msg);
scroggof24f2242015-03-03 08:59:20 -080027 longjmp(png_jmpbuf(png_ptr), 1);
28}
29
scroggo0eed6df2015-03-26 10:07:56 -070030void sk_warning_fn(png_structp, png_const_charp msg) {
31 SkCodecPrintf("----- png warning %s\n", msg);
32}
33
scroggof24f2242015-03-03 08:59:20 -080034static void sk_read_fn(png_structp png_ptr, png_bytep data,
35 png_size_t length) {
36 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
37 const size_t bytes = stream->read(data, length);
38 if (bytes != length) {
39 // FIXME: We want to report the fact that the stream was truncated.
40 // One way to do that might be to pass a enum to longjmp so setjmp can
41 // specify the failure.
42 png_error(png_ptr, "Read Error!");
43 }
44}
45
scroggocf98fa92015-11-23 08:14:40 -080046#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
47static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
48 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(png_ptr);
49 // readChunk() returning true means continue decoding
50 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk->size) ? 1 : -1;
51}
52#endif
53
scroggof24f2242015-03-03 08:59:20 -080054///////////////////////////////////////////////////////////////////////////////
55// Helpers
56///////////////////////////////////////////////////////////////////////////////
57
58class AutoCleanPng : public SkNoncopyable {
59public:
60 AutoCleanPng(png_structp png_ptr)
61 : fPng_ptr(png_ptr)
halcanary96fcdcc2015-08-27 07:41:13 -070062 , fInfo_ptr(nullptr) {}
scroggof24f2242015-03-03 08:59:20 -080063
64 ~AutoCleanPng() {
halcanary96fcdcc2015-08-27 07:41:13 -070065 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
scroggof24f2242015-03-03 08:59:20 -080066 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070067 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
msarett13a91232016-02-01 08:03:29 -080068 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
scroggof24f2242015-03-03 08:59:20 -080069 }
70 }
71
72 void setInfoPtr(png_infop info_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070073 SkASSERT(nullptr == fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -080074 fInfo_ptr = info_ptr;
75 }
76
77 void detach() {
halcanary96fcdcc2015-08-27 07:41:13 -070078 fPng_ptr = nullptr;
79 fInfo_ptr = nullptr;
scroggof24f2242015-03-03 08:59:20 -080080 }
81
82private:
83 png_structp fPng_ptr;
84 png_infop fInfo_ptr;
85};
86#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
87
scroggof24f2242015-03-03 08:59:20 -080088// Method for coverting to either an SkPMColor or a similarly packed
89// unpremultiplied color.
90typedef uint32_t (*PackColorProc)(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
91
92// Note: SkColorTable claims to store SkPMColors, which is not necessarily
93// the case here.
msarett13a91232016-02-01 08:03:29 -080094// TODO: If we add support for non-native swizzles, we'll need to handle that here.
scroggo9b2cdbf2015-07-10 12:07:02 -070095bool SkPngCodec::decodePalette(bool premultiply, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -080096
msarett13a91232016-02-01 08:03:29 -080097 int numColors;
98 png_color* palette;
99 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -0700100 return false;
scroggof24f2242015-03-03 08:59:20 -0800101 }
102
msarett13a91232016-02-01 08:03:29 -0800103 // Note: These are not necessarily SkPMColors.
104 SkPMColor colorPtr[256];
scroggof24f2242015-03-03 08:59:20 -0800105
msarett13a91232016-02-01 08:03:29 -0800106 png_bytep alphas;
107 int numColorsWithAlpha = 0;
108 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
109 // Choose which function to use to create the color table. If the final destination's
110 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
111 PackColorProc proc;
112 if (premultiply) {
113 proc = &SkPremultiplyARGBInline;
114 } else {
115 proc = &SkPackARGB32NoCheck;
116 }
117
118 for (int i = 0; i < numColorsWithAlpha; i++) {
119 // We don't have a function in SkOpts that combines a set of alphas with a set
120 // of RGBs. We could write one, but it's hardly worth it, given that this
121 // is such a small fraction of the total decode time.
122 colorPtr[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
123 palette++;
124 }
scroggof24f2242015-03-03 08:59:20 -0800125 }
126
msarett13a91232016-02-01 08:03:29 -0800127 if (numColorsWithAlpha < numColors) {
128 // The optimized code depends on a 3-byte png_color struct with the colors
129 // in RGB order. These checks make sure it is safe to use.
130 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
131#ifdef SK_DEBUG
132 SkASSERT(&palette->red < &palette->green);
133 SkASSERT(&palette->green < &palette->blue);
134#endif
135
136#ifdef SK_PMCOLOR_IS_RGBA
137 SkOpts::RGB_to_RGB1(colorPtr + numColorsWithAlpha, palette, numColors - numColorsWithAlpha);
138#else
139 SkOpts::RGB_to_BGR1(colorPtr + numColorsWithAlpha, palette, numColors - numColorsWithAlpha);
140#endif
scroggof24f2242015-03-03 08:59:20 -0800141 }
142
msarett13a91232016-02-01 08:03:29 -0800143 // Pad the color table with the last color in the table (or black) in the case that
144 // invalid pixel indices exceed the number of colors in the table.
145 const int maxColors = 1 << fBitDepth;
146 if (numColors < maxColors) {
147 SkPMColor lastColor = numColors > 0 ? colorPtr[numColors - 1] : SK_ColorBLACK;
148 sk_memset32(colorPtr + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800149 }
150
msarett13a91232016-02-01 08:03:29 -0800151 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700152 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800153 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800154 }
155
msarett13a91232016-02-01 08:03:29 -0800156 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
scroggo05245902015-03-25 11:11:52 -0700157 return true;
scroggof24f2242015-03-03 08:59:20 -0800158}
159
160///////////////////////////////////////////////////////////////////////////////
161// Creation
162///////////////////////////////////////////////////////////////////////////////
163
scroggodb30be22015-12-08 18:54:13 -0800164bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
165 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800166}
167
msarett6a738212016-03-04 13:27:35 -0800168static float png_fixed_point_to_float(png_fixed_point x) {
169 // We multiply by the same factor that libpng used to convert
170 // fixed point -> double. Since we want floats, we choose to
171 // do the conversion ourselves rather than convert
172 // fixed point -> double -> float.
173 return ((float) x) * 0.00001f;
174}
175
176// Returns a colorSpace object that represents any color space information in
177// the encoded data. If the encoded data contains no color space, this will
178// return NULL.
179SkColorSpace* read_color_space(png_structp png_ptr, png_infop info_ptr) {
180
181 // First check for an ICC profile
182 png_bytep profile;
183 png_uint_32 length;
184 // The below variables are unused, however, we need to pass them in anyway or
185 // png_get_iCCP() will return nothing.
186 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
187 png_charp name;
188 // The |compression| is uninteresting since:
189 // (1) libpng has already decompressed the profile for us.
190 // (2) "deflate" is the only mode of decompression that libpng supports.
191 int compression;
192 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
193 &length)) {
194 return SkColorSpace::NewICC(profile, length);
195 }
196
197 // Second, check for sRGB.
198 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
199
200 // sRGB chunks also store a rendering intent: Absolute, Relative,
201 // Perceptual, and Saturation.
202 // FIXME (msarett): Extract this information from the sRGB chunk once
203 // we are able to handle this information in
204 // SkColorSpace.
205 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
206 }
207
208 // Next, check for chromaticities.
209 png_fixed_point XYZ[9];
210 SkFloat3x3 toXYZD50;
211 png_fixed_point gamma;
212 SkFloat3 gammas;
213 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &XYZ[0], &XYZ[1], &XYZ[2], &XYZ[3], &XYZ[4],
214 &XYZ[5], &XYZ[6], &XYZ[7], &XYZ[8])) {
215
216 // FIXME (msarett): Here we are treating XYZ values as D50 even though the color
217 // temperature is unspecified. I suspect that this assumption
218 // is most often ok, but we could also calculate the color
219 // temperature (D value) and then convert the XYZ to D50. Maybe
220 // we should add a new constructor to SkColorSpace that accepts
221 // XYZ with D-Unkown?
222 for (int i = 0; i < 9; i++) {
223 toXYZD50.fMat[i] = png_fixed_point_to_float(XYZ[i]);
224 }
225
226 if (PNG_INFO_gAMA != png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
227
228 // If the image does not specify gamma, let's choose linear. Should we default
229 // to sRGB? Most images are intended to be sRGB (gamma = 2.2f).
230 gamma = PNG_GAMMA_LINEAR;
231 }
232 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = png_fixed_point_to_float(gamma);
233
234 return SkColorSpace::NewRGB(toXYZD50, gammas);
235 }
236
237 // Last, check for gamma.
238 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
239
240 // Guess a default value for cHRM? Or should we just give up?
241 // Here we use the identity matrix as a default.
242 // FIXME (msarett): Should SkFloat3x3 have a method to set the identity matrix?
243 memset(toXYZD50.fMat, 0, 9 * sizeof(float));
244 toXYZD50.fMat[0] = toXYZD50.fMat[4] = toXYZD50.fMat[8] = 1.0f;
245
246 // Set the gammas.
247 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = png_fixed_point_to_float(gamma);
248
249 return SkColorSpace::NewRGB(toXYZD50, gammas);
250 }
251
252 // Finally, what should we do if there is no color space information in the PNG?
253 // The specification says that this indicates "gamma is unknown" and that the
254 // "color is device dependent". I'm assuming we can represent this with NULL.
255 // But should we guess sRGB? Most images are sRGB, even if they don't specify.
256 return nullptr;
257}
258
scroggocf98fa92015-11-23 08:14:40 -0800259// Reads the header and initializes the output fields, if not NULL.
260//
261// @param stream Input data. Will be read to get enough information to properly
262// setup the codec.
263// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
264// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
265// expected to continue to own it for the lifetime of the png_ptr.
266// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
267// png_structp on success.
268// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
269// png_infop on success;
270// @param imageInfo Optional output variable. If non-NULL, will be set to
271// reflect the properties of the encoded image on success.
272// @param bitDepthPtr Optional output variable. If non-NULL, will be set to the
273// bit depth of the encoded image on success.
274// @param numberPassesPtr Optional output variable. If non-NULL, will be set to
275// the number_passes of the encoded image on success.
276// @return true on success, in which case the caller is responsible for calling
277// png_destroy_read_struct(png_ptrp, info_ptrp).
278// If it returns false, the passed in fields (except stream) are unchanged.
279static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader,
280 png_structp* png_ptrp, png_infop* info_ptrp,
281 SkImageInfo* imageInfo, int* bitDepthPtr, int* numberPassesPtr) {
scroggof24f2242015-03-03 08:59:20 -0800282 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
halcanary96fcdcc2015-08-27 07:41:13 -0700283 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
scroggo0eed6df2015-03-26 10:07:56 -0700284 sk_error_fn, sk_warning_fn);
scroggof24f2242015-03-03 08:59:20 -0800285 if (!png_ptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700286 return false;
scroggof24f2242015-03-03 08:59:20 -0800287 }
288
289 AutoCleanPng autoClean(png_ptr);
290
291 png_infop info_ptr = png_create_info_struct(png_ptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700292 if (info_ptr == nullptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700293 return false;
scroggof24f2242015-03-03 08:59:20 -0800294 }
295
296 autoClean.setInfoPtr(info_ptr);
297
298 // FIXME: Could we use the return value of setjmp to specify the type of
299 // error?
300 if (setjmp(png_jmpbuf(png_ptr))) {
scroggo3eada2a2015-04-01 09:33:23 -0700301 return false;
scroggof24f2242015-03-03 08:59:20 -0800302 }
303
304 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
305
scroggocf98fa92015-11-23 08:14:40 -0800306#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
msarett133eaaa2016-01-07 11:03:25 -0800307 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
308 // This needs to be installed before we read the png header. Android may store ninepatch
309 // chunks in the header.
scroggocf98fa92015-11-23 08:14:40 -0800310 if (chunkReader) {
311 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
312 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
313 }
314#endif
scroggof24f2242015-03-03 08:59:20 -0800315
316 // The call to png_read_info() gives us all of the information from the
317 // PNG file before the first IDAT (image data chunk).
318 png_read_info(png_ptr, info_ptr);
319 png_uint_32 origWidth, origHeight;
msarett13a91232016-02-01 08:03:29 -0800320 int bitDepth, encodedColorType;
scroggof24f2242015-03-03 08:59:20 -0800321 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarett13a91232016-02-01 08:03:29 -0800322 &encodedColorType, nullptr, nullptr, nullptr);
scroggof24f2242015-03-03 08:59:20 -0800323
scroggo6f29a3c2015-07-07 06:09:08 -0700324 if (bitDepthPtr) {
325 *bitDepthPtr = bitDepth;
326 }
327
msarett13a91232016-02-01 08:03:29 -0800328 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
329 // TODO: Should we handle this in SkSwizzler? Could this also benefit
330 // RAW decodes?
scroggof24f2242015-03-03 08:59:20 -0800331 if (bitDepth == 16) {
msarett13a91232016-02-01 08:03:29 -0800332 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggof24f2242015-03-03 08:59:20 -0800333 png_set_strip_16(png_ptr);
334 }
scroggof24f2242015-03-03 08:59:20 -0800335
msarett13a91232016-02-01 08:03:29 -0800336 // Now determine the default colorType and alphaType and set the required transforms.
337 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
338 // still depend on libpng for many of the rare and PNG-specific cases.
339 SkColorType colorType = kUnknown_SkColorType;
340 SkAlphaType alphaType = kUnknown_SkAlphaType;
341 switch (encodedColorType) {
scroggof24f2242015-03-03 08:59:20 -0800342 case PNG_COLOR_TYPE_PALETTE:
msarett13a91232016-02-01 08:03:29 -0800343 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
344 // byte into separate bytes (useful for paletted and grayscale images).
345 if (bitDepth < 8) {
346 // TODO: Should we use SkSwizzler here?
347 png_set_packing(png_ptr);
348 }
349
350 colorType = kIndex_8_SkColorType;
351 // Set the alpha type depending on if a transparency chunk exists.
352 alphaType = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
scroggof24f2242015-03-03 08:59:20 -0800353 kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
354 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700355 case PNG_COLOR_TYPE_RGB:
msarett13a91232016-02-01 08:03:29 -0800356 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
357 // Convert to RGBA if transparency chunk exists.
scroggo6f29a3c2015-07-07 06:09:08 -0700358 png_set_tRNS_to_alpha(png_ptr);
msarett13a91232016-02-01 08:03:29 -0800359 alphaType = kUnpremul_SkAlphaType;
jvanverth6c90e092015-07-02 10:35:25 -0700360 } else {
msarett13a91232016-02-01 08:03:29 -0800361 alphaType = kOpaque_SkAlphaType;
jvanverth6c90e092015-07-02 10:35:25 -0700362 }
msarett13a91232016-02-01 08:03:29 -0800363 colorType = kN32_SkColorType;
jvanverth6c90e092015-07-02 10:35:25 -0700364 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700365 case PNG_COLOR_TYPE_GRAY:
msarett13a91232016-02-01 08:03:29 -0800366 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
367 if (bitDepth < 8) {
368 // TODO: Should we use SkSwizzler here?
369 png_set_expand_gray_1_2_4_to_8(png_ptr);
370 }
371
372 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
scroggo6f29a3c2015-07-07 06:09:08 -0700373 png_set_tRNS_to_alpha(png_ptr);
msarett93e613d2016-02-03 10:44:46 -0800374
375 // We will recommend kN32 here since we do not support kGray
376 // with alpha.
msarett13a91232016-02-01 08:03:29 -0800377 colorType = kN32_SkColorType;
378 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700379 } else {
msarett13a91232016-02-01 08:03:29 -0800380 colorType = kGray_8_SkColorType;
381 alphaType = kOpaque_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700382 }
383 break;
384 case PNG_COLOR_TYPE_GRAY_ALPHA:
msarett93e613d2016-02-03 10:44:46 -0800385 // We will recommend kN32 here since we do not support anything
386 // similar to GRAY_ALPHA.
msarett13a91232016-02-01 08:03:29 -0800387 colorType = kN32_SkColorType;
388 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700389 break;
390 case PNG_COLOR_TYPE_RGBA:
msarett13a91232016-02-01 08:03:29 -0800391 colorType = kN32_SkColorType;
392 alphaType = kUnpremul_SkAlphaType;
scroggo6f29a3c2015-07-07 06:09:08 -0700393 break;
394 default:
msarett13a91232016-02-01 08:03:29 -0800395 // All the color types have been covered above.
scroggo6f29a3c2015-07-07 06:09:08 -0700396 SkASSERT(false);
scroggof24f2242015-03-03 08:59:20 -0800397 }
398
scroggo46c57472015-09-30 08:57:13 -0700399 int numberPasses = png_set_interlace_handling(png_ptr);
400 if (numberPassesPtr) {
401 *numberPassesPtr = numberPasses;
402 }
403
msaretta87d6de2016-02-04 15:37:58 -0800404 SkColorProfileType profileType = kLinear_SkColorProfileType;
405 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
406 profileType = kSRGB_SkColorProfileType;
407 }
scroggof24f2242015-03-03 08:59:20 -0800408
scroggo3eada2a2015-04-01 09:33:23 -0700409 if (imageInfo) {
msaretta87d6de2016-02-04 15:37:58 -0800410 *imageInfo = SkImageInfo::Make(origWidth, origHeight, colorType, alphaType, profileType);
scroggo3eada2a2015-04-01 09:33:23 -0700411 }
scroggof24f2242015-03-03 08:59:20 -0800412 autoClean.detach();
scroggo3eada2a2015-04-01 09:33:23 -0700413 if (png_ptrp) {
414 *png_ptrp = png_ptr;
415 }
416 if (info_ptrp) {
417 *info_ptrp = info_ptr;
418 }
scroggo6f29a3c2015-07-07 06:09:08 -0700419
scroggo3eada2a2015-04-01 09:33:23 -0700420 return true;
421}
422
scroggocf98fa92015-11-23 08:14:40 -0800423SkPngCodec::SkPngCodec(const SkImageInfo& info, SkStream* stream, SkPngChunkReader* chunkReader,
msarett6a738212016-03-04 13:27:35 -0800424 png_structp png_ptr, png_infop info_ptr, int bitDepth, int numberPasses,
425 SkColorSpace* colorSpace)
426 : INHERITED(info, stream, colorSpace)
scroggocf98fa92015-11-23 08:14:40 -0800427 , fPngChunkReader(SkSafeRef(chunkReader))
scroggof24f2242015-03-03 08:59:20 -0800428 , fPng_ptr(png_ptr)
scroggo05245902015-03-25 11:11:52 -0700429 , fInfo_ptr(info_ptr)
430 , fSrcConfig(SkSwizzler::kUnknown)
scroggo46c57472015-09-30 08:57:13 -0700431 , fNumberPasses(numberPasses)
scroggo6f29a3c2015-07-07 06:09:08 -0700432 , fBitDepth(bitDepth)
msaretta4970dc2016-01-11 07:23:23 -0800433{}
scroggof24f2242015-03-03 08:59:20 -0800434
435SkPngCodec::~SkPngCodec() {
scroggo3eada2a2015-04-01 09:33:23 -0700436 this->destroyReadStruct();
437}
438
439void SkPngCodec::destroyReadStruct() {
440 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -0700441 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
scroggo3eada2a2015-04-01 09:33:23 -0700442 SkASSERT(fInfo_ptr);
msarett13a91232016-02-01 08:03:29 -0800443 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, nullptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700444 fPng_ptr = nullptr;
445 fInfo_ptr = nullptr;
scroggo3eada2a2015-04-01 09:33:23 -0700446 }
scroggof24f2242015-03-03 08:59:20 -0800447}
448
449///////////////////////////////////////////////////////////////////////////////
450// Getting the pixels
451///////////////////////////////////////////////////////////////////////////////
452
scroggo05245902015-03-25 11:11:52 -0700453SkCodec::Result SkPngCodec::initializeSwizzler(const SkImageInfo& requestedInfo,
msarett438b2ad2015-04-09 12:43:10 -0700454 const Options& options,
msarett9e43cab2015-04-29 07:38:43 -0700455 SkPMColor ctable[],
msarett438b2ad2015-04-09 12:43:10 -0700456 int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -0800457 // FIXME: Could we use the return value of setjmp to specify the type of
458 // error?
459 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700460 SkCodecPrintf("setjmp long jump!\n");
scroggof24f2242015-03-03 08:59:20 -0800461 return kInvalidInput;
462 }
mtklein372d65c2016-01-27 13:01:41 -0800463 png_read_update_info(fPng_ptr, fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -0800464
msarett93e613d2016-02-03 10:44:46 -0800465 // suggestedColorType was determined in read_header() based on the encodedColorType
466 const SkColorType suggestedColorType = this->getInfo().colorType();
scroggo6f29a3c2015-07-07 06:09:08 -0700467
msarett93e613d2016-02-03 10:44:46 -0800468 switch (suggestedColorType) {
scroggo6f29a3c2015-07-07 06:09:08 -0700469 case kIndex_8_SkColorType:
470 //decode palette to Skia format
471 fSrcConfig = SkSwizzler::kIndex;
scroggo9b2cdbf2015-07-10 12:07:02 -0700472 if (!this->decodePalette(kPremul_SkAlphaType == requestedInfo.alphaType(),
scroggo6f29a3c2015-07-07 06:09:08 -0700473 ctableCount)) {
474 return kInvalidInput;
475 }
476 break;
477 case kGray_8_SkColorType:
478 fSrcConfig = SkSwizzler::kGray;
mtklein372d65c2016-01-27 13:01:41 -0800479 break;
msarett93e613d2016-02-03 10:44:46 -0800480 case kN32_SkColorType: {
481 const uint8_t encodedColorType = png_get_color_type(fPng_ptr, fInfo_ptr);
482 if (PNG_COLOR_TYPE_GRAY_ALPHA == encodedColorType ||
483 PNG_COLOR_TYPE_GRAY == encodedColorType) {
484 // If encodedColorType is GRAY, there must be a transparent chunk.
485 // Otherwise, suggestedColorType would be kGray. We have already
486 // instructed libpng to convert the transparent chunk to alpha,
487 // so we can treat both GRAY and GRAY_ALPHA as kGrayAlpha.
488 SkASSERT(encodedColorType == PNG_COLOR_TYPE_GRAY_ALPHA ||
489 png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS));
490
491 fSrcConfig = SkSwizzler::kGrayAlpha;
492 } else {
493 if (this->getInfo().alphaType() == kOpaque_SkAlphaType) {
msarettbda86092016-01-19 10:40:12 -0800494 fSrcConfig = SkSwizzler::kRGB;
scroggo6f29a3c2015-07-07 06:09:08 -0700495 } else {
496 fSrcConfig = SkSwizzler::kRGBA;
msarett93e613d2016-02-03 10:44:46 -0800497 }
scroggo6f29a3c2015-07-07 06:09:08 -0700498 }
499 break;
msarett93e613d2016-02-03 10:44:46 -0800500 }
scroggo6f29a3c2015-07-07 06:09:08 -0700501 default:
msarett13a91232016-02-01 08:03:29 -0800502 // We will always recommend one of the above colorTypes.
scroggo6f29a3c2015-07-07 06:09:08 -0700503 SkASSERT(false);
mtklein372d65c2016-01-27 13:01:41 -0800504 }
msarett9e43cab2015-04-29 07:38:43 -0700505
506 // Copy the color table to the client if they request kIndex8 mode
507 copy_color_table(requestedInfo, fColorTable, ctable, ctableCount);
508
509 // Create the swizzler. SkPngCodec retains ownership of the color table.
msarett99f567e2015-08-05 12:58:26 -0700510 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettfdb47572015-10-13 12:50:14 -0700511 fSwizzler.reset(SkSwizzler::CreateSwizzler(fSrcConfig, colors, requestedInfo, options));
msarett13a91232016-02-01 08:03:29 -0800512 SkASSERT(fSwizzler);
513
scroggo05245902015-03-25 11:11:52 -0700514 return kSuccess;
515}
516
scroggo6f29a3c2015-07-07 06:09:08 -0700517
scroggob427db12015-08-12 07:24:13 -0700518bool SkPngCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700519 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
scroggob427db12015-08-12 07:24:13 -0700520 // succeeds, they will be repopulated, and if it fails, they will
halcanary96fcdcc2015-08-27 07:41:13 -0700521 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
scroggob427db12015-08-12 07:24:13 -0700522 // come through this function which will rewind and again attempt
523 // to reinitialize them.
524 this->destroyReadStruct();
525
526 png_structp png_ptr;
527 png_infop info_ptr;
scroggocf98fa92015-11-23 08:14:40 -0800528 if (!read_header(this->stream(), fPngChunkReader.get(), &png_ptr, &info_ptr,
529 nullptr, nullptr, nullptr)) {
scroggob427db12015-08-12 07:24:13 -0700530 return false;
scroggo58421542015-04-01 11:25:20 -0700531 }
scroggob427db12015-08-12 07:24:13 -0700532
533 fPng_ptr = png_ptr;
534 fInfo_ptr = info_ptr;
535 return true;
scroggo58421542015-04-01 11:25:20 -0700536}
537
scroggo05245902015-03-25 11:11:52 -0700538SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
msarett614aa072015-07-27 15:13:17 -0700539 size_t dstRowBytes, const Options& options,
msarette6dd0042015-10-09 11:07:34 -0700540 SkPMColor ctable[], int* ctableCount,
541 int* rowsDecoded) {
scroggo6f29a3c2015-07-07 06:09:08 -0700542 if (!conversion_possible(requestedInfo, this->getInfo())) {
543 return kInvalidConversion;
544 }
scroggob636b452015-07-22 07:16:20 -0700545 if (options.fSubset) {
546 // Subsets are not supported.
547 return kUnimplemented;
548 }
scroggo05245902015-03-25 11:11:52 -0700549
msarett9e43cab2015-04-29 07:38:43 -0700550 // Note that ctable and ctableCount may be modified if there is a color table
msarettfdb47572015-10-13 12:50:14 -0700551 const Result result = this->initializeSwizzler(requestedInfo, options, ctable, ctableCount);
scroggo05245902015-03-25 11:11:52 -0700552 if (result != kSuccess) {
553 return result;
554 }
msarett60dcd3c2016-02-05 15:13:12 -0800555
556 const int width = requestedInfo.width();
557 const int height = requestedInfo.height();
558 const int bpp = SkSwizzler::BytesPerPixel(fSrcConfig);
559 const size_t srcRowBytes = width * bpp;
560
scroggo05245902015-03-25 11:11:52 -0700561 // FIXME: Could we use the return value of setjmp to specify the type of
562 // error?
msarette6dd0042015-10-09 11:07:34 -0700563 int row = 0;
564 // This must be declared above the call to setjmp to avoid memory leaks on incomplete images.
scroggo565901d2015-12-10 10:44:13 -0800565 SkAutoTMalloc<uint8_t> storage;
scroggo05245902015-03-25 11:11:52 -0700566 if (setjmp(png_jmpbuf(fPng_ptr))) {
msarette6dd0042015-10-09 11:07:34 -0700567 // Assume that any error that occurs while reading rows is caused by an incomplete input.
568 if (fNumberPasses > 1) {
569 // FIXME (msarett): Handle incomplete interlaced pngs.
msarett60dcd3c2016-02-05 15:13:12 -0800570 return (row == height) ? kSuccess : kInvalidInput;
msarette6dd0042015-10-09 11:07:34 -0700571 }
572 // FIXME: We do a poor job on incomplete pngs compared to other decoders (ex: Chromium,
573 // Ubuntu Image Viewer). This is because we use the default buffer size in libpng (8192
574 // bytes), and if we can't fill the buffer, we immediately fail.
575 // For example, if we try to read 8192 bytes, and the image (incorrectly) only contains
576 // half that, which may have been enough to contain a non-zero number of lines, we fail
577 // when we could have decoded a few more lines and then failed.
578 // The read function that we provide for libpng has no way of indicating that we have
579 // made a partial read.
580 // Making our buffer size smaller improves our incomplete decodes, but what impact does
581 // it have on regular decode performance? Should we investigate using a different API
msarett60dcd3c2016-02-05 15:13:12 -0800582 // instead of png_read_row? Chromium uses png_process_data.
msarette6dd0042015-10-09 11:07:34 -0700583 *rowsDecoded = row;
msarett60dcd3c2016-02-05 15:13:12 -0800584 return (row == height) ? kSuccess : kIncompleteInput;
scroggo05245902015-03-25 11:11:52 -0700585 }
586
scroggo46c57472015-09-30 08:57:13 -0700587 // FIXME: We could split these out based on subclass.
msarett614aa072015-07-27 15:13:17 -0700588 void* dstRow = dst;
scroggo05245902015-03-25 11:11:52 -0700589 if (fNumberPasses > 1) {
msarett60dcd3c2016-02-05 15:13:12 -0800590 storage.reset(height * srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800591 uint8_t* const base = storage.get();
scroggof24f2242015-03-03 08:59:20 -0800592
scroggo05245902015-03-25 11:11:52 -0700593 for (int i = 0; i < fNumberPasses; i++) {
msarett614aa072015-07-27 15:13:17 -0700594 uint8_t* srcRow = base;
scroggof24f2242015-03-03 08:59:20 -0800595 for (int y = 0; y < height; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800596 png_read_row(fPng_ptr, srcRow, nullptr);
msarett614aa072015-07-27 15:13:17 -0700597 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800598 }
599 }
600
601 // Now swizzle it.
msarett614aa072015-07-27 15:13:17 -0700602 uint8_t* srcRow = base;
msarett60dcd3c2016-02-05 15:13:12 -0800603 for (; row < height; row++) {
msaretta4970dc2016-01-11 07:23:23 -0800604 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700605 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
606 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800607 }
608 } else {
msarett60dcd3c2016-02-05 15:13:12 -0800609 storage.reset(srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800610 uint8_t* srcRow = storage.get();
msarett60dcd3c2016-02-05 15:13:12 -0800611 for (; row < height; row++) {
612 png_read_row(fPng_ptr, srcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800613 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700614 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
scroggof24f2242015-03-03 08:59:20 -0800615 }
616 }
617
emmaleer973ae862015-07-20 13:38:44 -0700618 // read rest of file, and get additional comment and time chunks in info_ptr
scroggo05245902015-03-25 11:11:52 -0700619 png_read_end(fPng_ptr, fInfo_ptr);
scroggo46c57472015-09-30 08:57:13 -0700620
emmaleer973ae862015-07-20 13:38:44 -0700621 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700622}
623
scroggoc5560be2016-02-03 09:42:42 -0800624uint32_t SkPngCodec::onGetFillValue(SkColorType colorType) const {
msarette6dd0042015-10-09 11:07:34 -0700625 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
626 if (colorPtr) {
627 return get_color_table_fill_value(colorType, colorPtr, 0);
628 }
scroggoc5560be2016-02-03 09:42:42 -0800629 return INHERITED::onGetFillValue(colorType);
msarette6dd0042015-10-09 11:07:34 -0700630}
631
scroggo46c57472015-09-30 08:57:13 -0700632// Subclass of SkPngCodec which supports scanline decoding
633class SkPngScanlineDecoder : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700634public:
scroggo46c57472015-09-30 08:57:13 -0700635 SkPngScanlineDecoder(const SkImageInfo& srcInfo, SkStream* stream,
msarett6a738212016-03-04 13:27:35 -0800636 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr, int bitDepth,
637 SkColorSpace* colorSpace)
638 : INHERITED(srcInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, 1, colorSpace)
msarettf724b992015-10-15 06:41:06 -0700639 , fSrcRow(nullptr)
scroggo1c005e42015-08-04 09:24:45 -0700640 {}
641
scroggo46c57472015-09-30 08:57:13 -0700642 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
643 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700644 if (!conversion_possible(dstInfo, this->getInfo())) {
scroggo46c57472015-09-30 08:57:13 -0700645 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700646 }
647
scroggo46c57472015-09-30 08:57:13 -0700648 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
649 ctableCount);
650 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700651 return result;
652 }
653
scroggo46c57472015-09-30 08:57:13 -0700654 fStorage.reset(this->getInfo().width() * SkSwizzler::BytesPerPixel(this->srcConfig()));
scroggo565901d2015-12-10 10:44:13 -0800655 fSrcRow = fStorage.get();
scroggo1c005e42015-08-04 09:24:45 -0700656
scroggo46c57472015-09-30 08:57:13 -0700657 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700658 }
659
msarette6dd0042015-10-09 11:07:34 -0700660 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
661 // Assume that an error in libpng indicates an incomplete input.
662 int row = 0;
scroggo46c57472015-09-30 08:57:13 -0700663 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700664 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700665 return row;
scroggo05245902015-03-25 11:11:52 -0700666 }
667
msarett614aa072015-07-27 15:13:17 -0700668 void* dstRow = dst;
msarette6dd0042015-10-09 11:07:34 -0700669 for (; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800670 png_read_row(this->png_ptr(), fSrcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800671 this->swizzler()->swizzle(dstRow, fSrcRow);
msarett614aa072015-07-27 15:13:17 -0700672 dstRow = SkTAddOffset<void>(dstRow, rowBytes);
scroggo05245902015-03-25 11:11:52 -0700673 }
scroggo46c57472015-09-30 08:57:13 -0700674
msarette6dd0042015-10-09 11:07:34 -0700675 return row;
scroggo05245902015-03-25 11:11:52 -0700676 }
677
msarette6dd0042015-10-09 11:07:34 -0700678 bool onSkipScanlines(int count) override {
679 // Assume that an error in libpng indicates an incomplete input.
scroggo46c57472015-09-30 08:57:13 -0700680 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700681 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700682 return false;
scroggo05245902015-03-25 11:11:52 -0700683 }
msarett60dcd3c2016-02-05 15:13:12 -0800684
msarette6dd0042015-10-09 11:07:34 -0700685 for (int row = 0; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800686 png_read_row(this->png_ptr(), fSrcRow, nullptr);
emmaleer7dc91902015-05-27 08:49:04 -0700687 }
msarette6dd0042015-10-09 11:07:34 -0700688 return true;
scroggo05245902015-03-25 11:11:52 -0700689 }
690
scroggo05245902015-03-25 11:11:52 -0700691private:
scroggo565901d2015-12-10 10:44:13 -0800692 SkAutoTMalloc<uint8_t> fStorage;
scroggo9b2cdbf2015-07-10 12:07:02 -0700693 uint8_t* fSrcRow;
scroggo05245902015-03-25 11:11:52 -0700694
scroggo46c57472015-09-30 08:57:13 -0700695 typedef SkPngCodec INHERITED;
scroggo05245902015-03-25 11:11:52 -0700696};
697
emmaleer0a4c3cb2015-06-22 10:40:21 -0700698
scroggo46c57472015-09-30 08:57:13 -0700699class SkPngInterlacedScanlineDecoder : public SkPngCodec {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700700public:
scroggo46c57472015-09-30 08:57:13 -0700701 SkPngInterlacedScanlineDecoder(const SkImageInfo& srcInfo, SkStream* stream,
scroggocf98fa92015-11-23 08:14:40 -0800702 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr,
msarett6a738212016-03-04 13:27:35 -0800703 int bitDepth, int numberPasses, SkColorSpace* colorSpace)
704 : INHERITED(srcInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, numberPasses,
705 colorSpace)
scroggo46c57472015-09-30 08:57:13 -0700706 , fHeight(-1)
scroggo1c005e42015-08-04 09:24:45 -0700707 , fCanSkipRewind(false)
scroggo1c005e42015-08-04 09:24:45 -0700708 {
scroggo46c57472015-09-30 08:57:13 -0700709 SkASSERT(numberPasses != 1);
710 }
711
712 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
msarettfdb47572015-10-13 12:50:14 -0700713 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700714 if (!conversion_possible(dstInfo, this->getInfo())) {
mtklein372d65c2016-01-27 13:01:41 -0800715 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700716 }
717
msarettfdb47572015-10-13 12:50:14 -0700718 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
719 ctableCount);
720 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700721 return result;
722 }
723
scroggo1c005e42015-08-04 09:24:45 -0700724 fHeight = dstInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700725 // FIXME: This need not be called on a second call to onStartScanlineDecode.
726 fSrcRowBytes = this->getInfo().width() * SkSwizzler::BytesPerPixel(this->srcConfig());
scroggo1c005e42015-08-04 09:24:45 -0700727 fGarbageRow.reset(fSrcRowBytes);
728 fGarbageRowPtr = static_cast<uint8_t*>(fGarbageRow.get());
729 fCanSkipRewind = true;
730
731 return SkCodec::kSuccess;
732 }
733
msarette6dd0042015-10-09 11:07:34 -0700734 int onGetScanlines(void* dst, int count, size_t dstRowBytes) override {
scroggo1c005e42015-08-04 09:24:45 -0700735 // rewind stream if have previously called onGetScanlines,
736 // since we need entire progressive image to get scanlines
737 if (fCanSkipRewind) {
scroggo46c57472015-09-30 08:57:13 -0700738 // We already rewound in onStartScanlineDecode, so there is no reason to rewind.
scroggo1c005e42015-08-04 09:24:45 -0700739 // Next time onGetScanlines is called, we will need to rewind.
740 fCanSkipRewind = false;
scroggo46c57472015-09-30 08:57:13 -0700741 } else {
742 // rewindIfNeeded resets fCurrScanline, since it assumes that start
743 // needs to be called again before scanline decoding. PNG scanline
744 // decoding is the exception, since it needs to rewind between
745 // calls to getScanlines. Keep track of fCurrScanline, to undo the
746 // reset.
msarette6dd0042015-10-09 11:07:34 -0700747 const int currScanline = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700748 // This method would never be called if currScanline is -1
749 SkASSERT(currScanline != -1);
750
751 if (!this->rewindIfNeeded()) {
752 return kCouldNotRewind;
753 }
msarettcb0d5c92015-12-03 12:23:43 -0800754 this->updateCurrScanline(currScanline);
scroggo1c005e42015-08-04 09:24:45 -0700755 }
756
scroggo46c57472015-09-30 08:57:13 -0700757 if (setjmp(png_jmpbuf(this->png_ptr()))) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700758 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700759 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
760 // we may be able to report that all of the memory has been initialized. Even if we
761 // fail on the first pass, we can still report than some scanlines are initialized.
762 return 0;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700763 }
scroggo565901d2015-12-10 10:44:13 -0800764 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
765 uint8_t* storagePtr = storage.get();
emmaleer0a4c3cb2015-06-22 10:40:21 -0700766 uint8_t* srcRow;
msarette6dd0042015-10-09 11:07:34 -0700767 const int startRow = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700768 for (int i = 0; i < this->numberPasses(); i++) {
769 // read rows we planned to skip into garbage row
770 for (int y = 0; y < startRow; y++){
msarett60dcd3c2016-02-05 15:13:12 -0800771 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700772 }
scroggo46c57472015-09-30 08:57:13 -0700773 // read rows we care about into buffer
emmaleer0a4c3cb2015-06-22 10:40:21 -0700774 srcRow = storagePtr;
775 for (int y = 0; y < count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800776 png_read_row(this->png_ptr(), srcRow, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700777 srcRow += fSrcRowBytes;
778 }
scroggo46c57472015-09-30 08:57:13 -0700779 // read rows we don't want into garbage buffer
780 for (int y = 0; y < fHeight - startRow - count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800781 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700782 }
783 }
784 //swizzle the rows we care about
785 srcRow = storagePtr;
msarett614aa072015-07-27 15:13:17 -0700786 void* dstRow = dst;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700787 for (int y = 0; y < count; y++) {
msaretta4970dc2016-01-11 07:23:23 -0800788 this->swizzler()->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700789 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700790 srcRow += fSrcRowBytes;
791 }
scroggo46c57472015-09-30 08:57:13 -0700792
msarette6dd0042015-10-09 11:07:34 -0700793 return count;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700794 }
795
msarette6dd0042015-10-09 11:07:34 -0700796 bool onSkipScanlines(int count) override {
scroggo46c57472015-09-30 08:57:13 -0700797 // The non-virtual version will update fCurrScanline.
msarette6dd0042015-10-09 11:07:34 -0700798 return true;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700799 }
800
msarett5406d6f2015-08-31 06:55:13 -0700801 SkScanlineOrder onGetScanlineOrder() const override {
802 return kNone_SkScanlineOrder;
emmaleer8f4ba762015-08-14 07:44:46 -0700803 }
804
emmaleer0a4c3cb2015-06-22 10:40:21 -0700805private:
scroggo9b2cdbf2015-07-10 12:07:02 -0700806 int fHeight;
807 size_t fSrcRowBytes;
808 SkAutoMalloc fGarbageRow;
809 uint8_t* fGarbageRowPtr;
scroggo1c005e42015-08-04 09:24:45 -0700810 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
811 // is called whenever some action is taken that reads the stream and
812 // therefore the next call will require a rewind. So it modifies a boolean
813 // to note that the *next* time it is called a rewind is needed.
scroggo46c57472015-09-30 08:57:13 -0700814 // SkPngInterlacedScanlineDecoder has an extra wrinkle - calling
815 // onStartScanlineDecode followed by onGetScanlines does *not* require a
816 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
817 // add another layer.
scroggo1c005e42015-08-04 09:24:45 -0700818 bool fCanSkipRewind;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700819
scroggo46c57472015-09-30 08:57:13 -0700820 typedef SkPngCodec INHERITED;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700821};
822
scroggocf98fa92015-11-23 08:14:40 -0800823SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
scroggo46c57472015-09-30 08:57:13 -0700824 SkAutoTDelete<SkStream> streamDeleter(stream);
825 png_structp png_ptr;
826 png_infop info_ptr;
827 SkImageInfo imageInfo;
828 int bitDepth;
829 int numberPasses;
830
scroggocf98fa92015-11-23 08:14:40 -0800831 if (!read_header(stream, chunkReader, &png_ptr, &info_ptr, &imageInfo, &bitDepth,
832 &numberPasses)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700833 return nullptr;
scroggo05245902015-03-25 11:11:52 -0700834 }
835
msarett6a738212016-03-04 13:27:35 -0800836 SkAutoTUnref<SkColorSpace> colorSpace(read_color_space(png_ptr, info_ptr));
837
scroggo46c57472015-09-30 08:57:13 -0700838 if (1 == numberPasses) {
scroggocf98fa92015-11-23 08:14:40 -0800839 return new SkPngScanlineDecoder(imageInfo, streamDeleter.detach(), chunkReader,
msarett6a738212016-03-04 13:27:35 -0800840 png_ptr, info_ptr, bitDepth, colorSpace);
scroggo05245902015-03-25 11:11:52 -0700841 }
842
scroggocf98fa92015-11-23 08:14:40 -0800843 return new SkPngInterlacedScanlineDecoder(imageInfo, streamDeleter.detach(), chunkReader,
msarett6a738212016-03-04 13:27:35 -0800844 png_ptr, info_ptr, bitDepth, numberPasses,
845 colorSpace);
scroggo05245902015-03-25 11:11:52 -0700846}