blob: a5ff9fcc96655b9cd36987b89ba5409e4ae83e7b [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// Note: SkColorTable claims to store SkPMColors, which is not necessarily
90// the case here.
msarett13a91232016-02-01 08:03:29 -080091// TODO: If we add support for non-native swizzles, we'll need to handle that here.
msarett34e0ec42016-04-22 16:27:24 -070092bool SkPngCodec::createColorTable(SkColorType dstColorType, bool premultiply, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -080093
msarett13a91232016-02-01 08:03:29 -080094 int numColors;
95 png_color* palette;
96 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -070097 return false;
scroggof24f2242015-03-03 08:59:20 -080098 }
99
msarett13a91232016-02-01 08:03:29 -0800100 // Note: These are not necessarily SkPMColors.
101 SkPMColor colorPtr[256];
scroggof24f2242015-03-03 08:59:20 -0800102
msarett13a91232016-02-01 08:03:29 -0800103 png_bytep alphas;
104 int numColorsWithAlpha = 0;
105 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
106 // Choose which function to use to create the color table. If the final destination's
107 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
msarett34e0ec42016-04-22 16:27:24 -0700108 PackColorProc proc = choose_pack_color_proc(premultiply, dstColorType);
msarett13a91232016-02-01 08:03:29 -0800109
110 for (int i = 0; i < numColorsWithAlpha; i++) {
111 // We don't have a function in SkOpts that combines a set of alphas with a set
112 // of RGBs. We could write one, but it's hardly worth it, given that this
113 // is such a small fraction of the total decode time.
114 colorPtr[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
115 palette++;
116 }
scroggof24f2242015-03-03 08:59:20 -0800117 }
118
msarett13a91232016-02-01 08:03:29 -0800119 if (numColorsWithAlpha < numColors) {
120 // The optimized code depends on a 3-byte png_color struct with the colors
121 // in RGB order. These checks make sure it is safe to use.
122 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
123#ifdef SK_DEBUG
124 SkASSERT(&palette->red < &palette->green);
125 SkASSERT(&palette->green < &palette->blue);
126#endif
127
msarett34e0ec42016-04-22 16:27:24 -0700128 if (is_rgba(dstColorType)) {
129 SkOpts::RGB_to_RGB1(colorPtr + numColorsWithAlpha, palette,
130 numColors - numColorsWithAlpha);
131 } else {
132 SkOpts::RGB_to_BGR1(colorPtr + numColorsWithAlpha, palette,
133 numColors - numColorsWithAlpha);
134 }
scroggof24f2242015-03-03 08:59:20 -0800135 }
136
msarett13a91232016-02-01 08:03:29 -0800137 // Pad the color table with the last color in the table (or black) in the case that
138 // invalid pixel indices exceed the number of colors in the table.
139 const int maxColors = 1 << fBitDepth;
140 if (numColors < maxColors) {
141 SkPMColor lastColor = numColors > 0 ? colorPtr[numColors - 1] : SK_ColorBLACK;
142 sk_memset32(colorPtr + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800143 }
144
msarett13a91232016-02-01 08:03:29 -0800145 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700146 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800147 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800148 }
149
msarett13a91232016-02-01 08:03:29 -0800150 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
scroggo05245902015-03-25 11:11:52 -0700151 return true;
scroggof24f2242015-03-03 08:59:20 -0800152}
153
154///////////////////////////////////////////////////////////////////////////////
155// Creation
156///////////////////////////////////////////////////////////////////////////////
157
scroggodb30be22015-12-08 18:54:13 -0800158bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
159 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800160}
161
msarett6a738212016-03-04 13:27:35 -0800162static float png_fixed_point_to_float(png_fixed_point x) {
163 // We multiply by the same factor that libpng used to convert
164 // fixed point -> double. Since we want floats, we choose to
165 // do the conversion ourselves rather than convert
166 // fixed point -> double -> float.
167 return ((float) x) * 0.00001f;
168}
169
msarett128245c2016-03-30 12:01:47 -0700170static float png_inverted_fixed_point_to_float(png_fixed_point x) {
171 // This is necessary because the gAMA chunk actually stores 1/gamma.
172 return 1.0f / png_fixed_point_to_float(x);
173}
174
msarett6a738212016-03-04 13:27:35 -0800175// Returns a colorSpace object that represents any color space information in
176// the encoded data. If the encoded data contains no color space, this will
177// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800178sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800179
msarette2443222016-03-04 14:20:49 -0800180#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
181
msarett6a738212016-03-04 13:27:35 -0800182 // First check for an ICC profile
183 png_bytep profile;
184 png_uint_32 length;
185 // The below variables are unused, however, we need to pass them in anyway or
186 // png_get_iCCP() will return nothing.
187 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
188 png_charp name;
189 // The |compression| is uninteresting since:
190 // (1) libpng has already decompressed the profile for us.
191 // (2) "deflate" is the only mode of decompression that libpng supports.
192 int compression;
193 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
194 &length)) {
195 return SkColorSpace::NewICC(profile, length);
196 }
197
198 // Second, check for sRGB.
199 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
200
201 // sRGB chunks also store a rendering intent: Absolute, Relative,
202 // Perceptual, and Saturation.
203 // FIXME (msarett): Extract this information from the sRGB chunk once
204 // we are able to handle this information in
205 // SkColorSpace.
206 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
207 }
208
209 // Next, check for chromaticities.
210 png_fixed_point XYZ[9];
211 SkFloat3x3 toXYZD50;
212 png_fixed_point gamma;
213 SkFloat3 gammas;
214 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &XYZ[0], &XYZ[1], &XYZ[2], &XYZ[3], &XYZ[4],
215 &XYZ[5], &XYZ[6], &XYZ[7], &XYZ[8])) {
216
217 // FIXME (msarett): Here we are treating XYZ values as D50 even though the color
218 // temperature is unspecified. I suspect that this assumption
219 // is most often ok, but we could also calculate the color
220 // temperature (D value) and then convert the XYZ to D50. Maybe
221 // we should add a new constructor to SkColorSpace that accepts
222 // XYZ with D-Unkown?
223 for (int i = 0; i < 9; i++) {
224 toXYZD50.fMat[i] = png_fixed_point_to_float(XYZ[i]);
225 }
226
msarett128245c2016-03-30 12:01:47 -0700227 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
228 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] =
229 png_inverted_fixed_point_to_float(gamma);
230 } else {
msarett6a738212016-03-04 13:27:35 -0800231 // If the image does not specify gamma, let's choose linear. Should we default
232 // to sRGB? Most images are intended to be sRGB (gamma = 2.2f).
msarett128245c2016-03-30 12:01:47 -0700233 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = 1.0f;
msarett6a738212016-03-04 13:27:35 -0800234 }
msarett128245c2016-03-30 12:01:47 -0700235
msarett6a738212016-03-04 13:27:35 -0800236
237 return SkColorSpace::NewRGB(toXYZD50, gammas);
238 }
239
240 // Last, check for gamma.
241 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
242
243 // Guess a default value for cHRM? Or should we just give up?
244 // Here we use the identity matrix as a default.
245 // FIXME (msarett): Should SkFloat3x3 have a method to set the identity matrix?
246 memset(toXYZD50.fMat, 0, 9 * sizeof(float));
247 toXYZD50.fMat[0] = toXYZD50.fMat[4] = toXYZD50.fMat[8] = 1.0f;
248
249 // Set the gammas.
msarett128245c2016-03-30 12:01:47 -0700250 gammas.fVec[0] = gammas.fVec[1] = gammas.fVec[2] = png_inverted_fixed_point_to_float(gamma);
msarett6a738212016-03-04 13:27:35 -0800251
252 return SkColorSpace::NewRGB(toXYZD50, gammas);
253 }
254
msarette2443222016-03-04 14:20:49 -0800255#endif // LIBPNG >= 1.6
256
msarett6a738212016-03-04 13:27:35 -0800257 // Finally, what should we do if there is no color space information in the PNG?
258 // The specification says that this indicates "gamma is unknown" and that the
259 // "color is device dependent". I'm assuming we can represent this with NULL.
260 // But should we guess sRGB? Most images are sRGB, even if they don't specify.
261 return nullptr;
262}
263
scroggocf98fa92015-11-23 08:14:40 -0800264// Reads the header and initializes the output fields, if not NULL.
265//
266// @param stream Input data. Will be read to get enough information to properly
267// setup the codec.
268// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
269// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
270// expected to continue to own it for the lifetime of the png_ptr.
271// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
272// png_structp on success.
273// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
274// png_infop on success;
msarettc30c4182016-04-20 11:53:35 -0700275// @param info Optional output variable. If non-NULL, will be set to
scroggocf98fa92015-11-23 08:14:40 -0800276// reflect the properties of the encoded image on success.
277// @param bitDepthPtr Optional output variable. If non-NULL, will be set to the
278// bit depth of the encoded image on success.
279// @param numberPassesPtr Optional output variable. If non-NULL, will be set to
280// the number_passes of the encoded image on success.
281// @return true on success, in which case the caller is responsible for calling
282// png_destroy_read_struct(png_ptrp, info_ptrp).
283// If it returns false, the passed in fields (except stream) are unchanged.
284static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader,
285 png_structp* png_ptrp, png_infop* info_ptrp,
msarettc30c4182016-04-20 11:53:35 -0700286 int* width, int* height, SkEncodedInfo* info, int* bitDepthPtr,
287 int* numberPassesPtr) {
scroggof24f2242015-03-03 08:59:20 -0800288 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
halcanary96fcdcc2015-08-27 07:41:13 -0700289 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
scroggo0eed6df2015-03-26 10:07:56 -0700290 sk_error_fn, sk_warning_fn);
scroggof24f2242015-03-03 08:59:20 -0800291 if (!png_ptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700292 return false;
scroggof24f2242015-03-03 08:59:20 -0800293 }
294
295 AutoCleanPng autoClean(png_ptr);
296
297 png_infop info_ptr = png_create_info_struct(png_ptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700298 if (info_ptr == nullptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700299 return false;
scroggof24f2242015-03-03 08:59:20 -0800300 }
301
302 autoClean.setInfoPtr(info_ptr);
303
304 // FIXME: Could we use the return value of setjmp to specify the type of
305 // error?
306 if (setjmp(png_jmpbuf(png_ptr))) {
scroggo3eada2a2015-04-01 09:33:23 -0700307 return false;
scroggof24f2242015-03-03 08:59:20 -0800308 }
309
310 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
311
scroggocf98fa92015-11-23 08:14:40 -0800312#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
msarett133eaaa2016-01-07 11:03:25 -0800313 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
314 // This needs to be installed before we read the png header. Android may store ninepatch
315 // chunks in the header.
scroggocf98fa92015-11-23 08:14:40 -0800316 if (chunkReader) {
317 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
318 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
319 }
320#endif
scroggof24f2242015-03-03 08:59:20 -0800321
322 // The call to png_read_info() gives us all of the information from the
323 // PNG file before the first IDAT (image data chunk).
324 png_read_info(png_ptr, info_ptr);
325 png_uint_32 origWidth, origHeight;
msarett13a91232016-02-01 08:03:29 -0800326 int bitDepth, encodedColorType;
scroggof24f2242015-03-03 08:59:20 -0800327 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarett13a91232016-02-01 08:03:29 -0800328 &encodedColorType, nullptr, nullptr, nullptr);
scroggof24f2242015-03-03 08:59:20 -0800329
scroggo6f29a3c2015-07-07 06:09:08 -0700330 if (bitDepthPtr) {
331 *bitDepthPtr = bitDepth;
332 }
333
msarett13a91232016-02-01 08:03:29 -0800334 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
335 // TODO: Should we handle this in SkSwizzler? Could this also benefit
336 // RAW decodes?
scroggof24f2242015-03-03 08:59:20 -0800337 if (bitDepth == 16) {
msarett13a91232016-02-01 08:03:29 -0800338 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggof24f2242015-03-03 08:59:20 -0800339 png_set_strip_16(png_ptr);
340 }
scroggof24f2242015-03-03 08:59:20 -0800341
msarett13a91232016-02-01 08:03:29 -0800342 // Now determine the default colorType and alphaType and set the required transforms.
343 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
344 // still depend on libpng for many of the rare and PNG-specific cases.
msarettc30c4182016-04-20 11:53:35 -0700345 SkEncodedInfo::Color color;
346 SkEncodedInfo::Alpha alpha;
msarett13a91232016-02-01 08:03:29 -0800347 switch (encodedColorType) {
scroggof24f2242015-03-03 08:59:20 -0800348 case PNG_COLOR_TYPE_PALETTE:
msarett13a91232016-02-01 08:03:29 -0800349 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
350 // byte into separate bytes (useful for paletted and grayscale images).
351 if (bitDepth < 8) {
352 // TODO: Should we use SkSwizzler here?
353 png_set_packing(png_ptr);
354 }
355
msarettc30c4182016-04-20 11:53:35 -0700356 color = SkEncodedInfo::kPalette_Color;
357 // Set the alpha depending on if a transparency chunk exists.
358 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
359 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
scroggof24f2242015-03-03 08:59:20 -0800360 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700361 case PNG_COLOR_TYPE_RGB:
msarett13a91232016-02-01 08:03:29 -0800362 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
363 // Convert to RGBA if transparency chunk exists.
scroggo6f29a3c2015-07-07 06:09:08 -0700364 png_set_tRNS_to_alpha(png_ptr);
msarettc30c4182016-04-20 11:53:35 -0700365 color = SkEncodedInfo::kRGBA_Color;
366 alpha = SkEncodedInfo::kBinary_Alpha;
jvanverth6c90e092015-07-02 10:35:25 -0700367 } else {
msarettc30c4182016-04-20 11:53:35 -0700368 color = SkEncodedInfo::kRGB_Color;
369 alpha = SkEncodedInfo::kOpaque_Alpha;
jvanverth6c90e092015-07-02 10:35:25 -0700370 }
jvanverth6c90e092015-07-02 10:35:25 -0700371 break;
scroggo6f29a3c2015-07-07 06:09:08 -0700372 case PNG_COLOR_TYPE_GRAY:
msarett13a91232016-02-01 08:03:29 -0800373 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
374 if (bitDepth < 8) {
375 // TODO: Should we use SkSwizzler here?
376 png_set_expand_gray_1_2_4_to_8(png_ptr);
377 }
378
379 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
scroggo6f29a3c2015-07-07 06:09:08 -0700380 png_set_tRNS_to_alpha(png_ptr);
msarettc30c4182016-04-20 11:53:35 -0700381 color = SkEncodedInfo::kGrayAlpha_Color;
382 alpha = SkEncodedInfo::kBinary_Alpha;
scroggo6f29a3c2015-07-07 06:09:08 -0700383 } else {
msarettc30c4182016-04-20 11:53:35 -0700384 color = SkEncodedInfo::kGray_Color;
385 alpha = SkEncodedInfo::kOpaque_Alpha;
scroggo6f29a3c2015-07-07 06:09:08 -0700386 }
387 break;
388 case PNG_COLOR_TYPE_GRAY_ALPHA:
msarettc30c4182016-04-20 11:53:35 -0700389 color = SkEncodedInfo::kGrayAlpha_Color;
390 alpha = SkEncodedInfo::kUnpremul_Alpha;
scroggo6f29a3c2015-07-07 06:09:08 -0700391 break;
392 case PNG_COLOR_TYPE_RGBA:
msarettc30c4182016-04-20 11:53:35 -0700393 color = SkEncodedInfo::kRGBA_Color;
394 alpha = SkEncodedInfo::kUnpremul_Alpha;
scroggo6f29a3c2015-07-07 06:09:08 -0700395 break;
396 default:
msarett13a91232016-02-01 08:03:29 -0800397 // All the color types have been covered above.
scroggo6f29a3c2015-07-07 06:09:08 -0700398 SkASSERT(false);
msarettc30c4182016-04-20 11:53:35 -0700399 color = SkEncodedInfo::kRGBA_Color;
400 alpha = SkEncodedInfo::kUnpremul_Alpha;
scroggof24f2242015-03-03 08:59:20 -0800401 }
402
scroggo46c57472015-09-30 08:57:13 -0700403 int numberPasses = png_set_interlace_handling(png_ptr);
404 if (numberPassesPtr) {
405 *numberPassesPtr = numberPasses;
406 }
407
msarettc30c4182016-04-20 11:53:35 -0700408 if (info) {
409 *info = SkEncodedInfo::Make(color, alpha, 8);
msaretta87d6de2016-02-04 15:37:58 -0800410 }
msarettc30c4182016-04-20 11:53:35 -0700411 if (width) {
412 *width = origWidth;
413 }
414 if (height) {
415 *height = origHeight;
scroggo3eada2a2015-04-01 09:33:23 -0700416 }
mtklein18300a32016-03-16 13:53:35 -0700417 autoClean.release();
scroggo3eada2a2015-04-01 09:33:23 -0700418 if (png_ptrp) {
419 *png_ptrp = png_ptr;
420 }
421 if (info_ptrp) {
422 *info_ptrp = info_ptr;
423 }
scroggo6f29a3c2015-07-07 06:09:08 -0700424
scroggo3eada2a2015-04-01 09:33:23 -0700425 return true;
426}
427
msarettc30c4182016-04-20 11:53:35 -0700428SkPngCodec::SkPngCodec(int width, int height, const SkEncodedInfo& info, SkStream* stream,
429 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr,
430 int bitDepth, int numberPasses, sk_sp<SkColorSpace> colorSpace)
431 : INHERITED(width, height, info, stream, colorSpace)
scroggocf98fa92015-11-23 08:14:40 -0800432 , fPngChunkReader(SkSafeRef(chunkReader))
scroggof24f2242015-03-03 08:59:20 -0800433 , fPng_ptr(png_ptr)
scroggo05245902015-03-25 11:11:52 -0700434 , fInfo_ptr(info_ptr)
scroggo46c57472015-09-30 08:57:13 -0700435 , fNumberPasses(numberPasses)
scroggo6f29a3c2015-07-07 06:09:08 -0700436 , fBitDepth(bitDepth)
msaretta4970dc2016-01-11 07:23:23 -0800437{}
scroggof24f2242015-03-03 08:59:20 -0800438
439SkPngCodec::~SkPngCodec() {
scroggo3eada2a2015-04-01 09:33:23 -0700440 this->destroyReadStruct();
441}
442
443void SkPngCodec::destroyReadStruct() {
444 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -0700445 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
scroggo3eada2a2015-04-01 09:33:23 -0700446 SkASSERT(fInfo_ptr);
msarett13a91232016-02-01 08:03:29 -0800447 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, nullptr);
halcanary96fcdcc2015-08-27 07:41:13 -0700448 fPng_ptr = nullptr;
449 fInfo_ptr = nullptr;
scroggo3eada2a2015-04-01 09:33:23 -0700450 }
scroggof24f2242015-03-03 08:59:20 -0800451}
452
453///////////////////////////////////////////////////////////////////////////////
454// Getting the pixels
455///////////////////////////////////////////////////////////////////////////////
456
scroggo05245902015-03-25 11:11:52 -0700457SkCodec::Result SkPngCodec::initializeSwizzler(const SkImageInfo& requestedInfo,
msarett438b2ad2015-04-09 12:43:10 -0700458 const Options& options,
msarett9e43cab2015-04-29 07:38:43 -0700459 SkPMColor ctable[],
msarett438b2ad2015-04-09 12:43:10 -0700460 int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -0800461 // FIXME: Could we use the return value of setjmp to specify the type of
462 // error?
463 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700464 SkCodecPrintf("setjmp long jump!\n");
scroggof24f2242015-03-03 08:59:20 -0800465 return kInvalidInput;
466 }
mtklein372d65c2016-01-27 13:01:41 -0800467 png_read_update_info(fPng_ptr, fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -0800468
msaretta45a6682016-04-22 13:18:37 -0700469 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
msarett34e0ec42016-04-22 16:27:24 -0700470 if (!this->createColorTable(requestedInfo.colorType(),
471 kPremul_SkAlphaType == requestedInfo.alphaType(), ctableCount)) {
msaretta45a6682016-04-22 13:18:37 -0700472 return kInvalidInput;
msarett93e613d2016-02-03 10:44:46 -0800473 }
mtklein372d65c2016-01-27 13:01:41 -0800474 }
msarett9e43cab2015-04-29 07:38:43 -0700475
476 // Copy the color table to the client if they request kIndex8 mode
477 copy_color_table(requestedInfo, fColorTable, ctable, ctableCount);
478
479 // Create the swizzler. SkPngCodec retains ownership of the color table.
msarett99f567e2015-08-05 12:58:26 -0700480 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msaretta45a6682016-04-22 13:18:37 -0700481 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colors, requestedInfo,
482 options));
msarett13a91232016-02-01 08:03:29 -0800483 SkASSERT(fSwizzler);
484
scroggo05245902015-03-25 11:11:52 -0700485 return kSuccess;
486}
487
scroggo6f29a3c2015-07-07 06:09:08 -0700488
scroggob427db12015-08-12 07:24:13 -0700489bool SkPngCodec::onRewind() {
halcanary96fcdcc2015-08-27 07:41:13 -0700490 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
scroggob427db12015-08-12 07:24:13 -0700491 // succeeds, they will be repopulated, and if it fails, they will
halcanary96fcdcc2015-08-27 07:41:13 -0700492 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
scroggob427db12015-08-12 07:24:13 -0700493 // come through this function which will rewind and again attempt
494 // to reinitialize them.
495 this->destroyReadStruct();
496
497 png_structp png_ptr;
498 png_infop info_ptr;
scroggocf98fa92015-11-23 08:14:40 -0800499 if (!read_header(this->stream(), fPngChunkReader.get(), &png_ptr, &info_ptr,
msarettc30c4182016-04-20 11:53:35 -0700500 nullptr, nullptr, nullptr, nullptr, nullptr)) {
scroggob427db12015-08-12 07:24:13 -0700501 return false;
scroggo58421542015-04-01 11:25:20 -0700502 }
scroggob427db12015-08-12 07:24:13 -0700503
504 fPng_ptr = png_ptr;
505 fInfo_ptr = info_ptr;
506 return true;
scroggo58421542015-04-01 11:25:20 -0700507}
508
msaretta45a6682016-04-22 13:18:37 -0700509static int bytes_per_pixel(int bitsPerPixel) {
510 // Note that we will have to change this implementation if we start
511 // supporting outputs from libpng that are less than 8-bits per component.
512 return bitsPerPixel / 8;
513}
514
scroggo05245902015-03-25 11:11:52 -0700515SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
msarett614aa072015-07-27 15:13:17 -0700516 size_t dstRowBytes, const Options& options,
msarette6dd0042015-10-09 11:07:34 -0700517 SkPMColor ctable[], int* ctableCount,
518 int* rowsDecoded) {
scroggo6f29a3c2015-07-07 06:09:08 -0700519 if (!conversion_possible(requestedInfo, this->getInfo())) {
520 return kInvalidConversion;
521 }
scroggob636b452015-07-22 07:16:20 -0700522 if (options.fSubset) {
523 // Subsets are not supported.
524 return kUnimplemented;
525 }
scroggo05245902015-03-25 11:11:52 -0700526
msarett9e43cab2015-04-29 07:38:43 -0700527 // Note that ctable and ctableCount may be modified if there is a color table
msarettfdb47572015-10-13 12:50:14 -0700528 const Result result = this->initializeSwizzler(requestedInfo, options, ctable, ctableCount);
scroggo05245902015-03-25 11:11:52 -0700529 if (result != kSuccess) {
530 return result;
531 }
msarett60dcd3c2016-02-05 15:13:12 -0800532
533 const int width = requestedInfo.width();
534 const int height = requestedInfo.height();
msaretta45a6682016-04-22 13:18:37 -0700535 const int bpp = bytes_per_pixel(this->getEncodedInfo().bitsPerPixel());
msarett60dcd3c2016-02-05 15:13:12 -0800536 const size_t srcRowBytes = width * bpp;
537
scroggo05245902015-03-25 11:11:52 -0700538 // FIXME: Could we use the return value of setjmp to specify the type of
539 // error?
msarette6dd0042015-10-09 11:07:34 -0700540 int row = 0;
541 // This must be declared above the call to setjmp to avoid memory leaks on incomplete images.
scroggo565901d2015-12-10 10:44:13 -0800542 SkAutoTMalloc<uint8_t> storage;
scroggo05245902015-03-25 11:11:52 -0700543 if (setjmp(png_jmpbuf(fPng_ptr))) {
msarette6dd0042015-10-09 11:07:34 -0700544 // Assume that any error that occurs while reading rows is caused by an incomplete input.
545 if (fNumberPasses > 1) {
546 // FIXME (msarett): Handle incomplete interlaced pngs.
msarett60dcd3c2016-02-05 15:13:12 -0800547 return (row == height) ? kSuccess : kInvalidInput;
msarette6dd0042015-10-09 11:07:34 -0700548 }
549 // FIXME: We do a poor job on incomplete pngs compared to other decoders (ex: Chromium,
550 // Ubuntu Image Viewer). This is because we use the default buffer size in libpng (8192
551 // bytes), and if we can't fill the buffer, we immediately fail.
552 // For example, if we try to read 8192 bytes, and the image (incorrectly) only contains
553 // half that, which may have been enough to contain a non-zero number of lines, we fail
554 // when we could have decoded a few more lines and then failed.
555 // The read function that we provide for libpng has no way of indicating that we have
556 // made a partial read.
557 // Making our buffer size smaller improves our incomplete decodes, but what impact does
558 // it have on regular decode performance? Should we investigate using a different API
msarett60dcd3c2016-02-05 15:13:12 -0800559 // instead of png_read_row? Chromium uses png_process_data.
msarette6dd0042015-10-09 11:07:34 -0700560 *rowsDecoded = row;
msarett60dcd3c2016-02-05 15:13:12 -0800561 return (row == height) ? kSuccess : kIncompleteInput;
scroggo05245902015-03-25 11:11:52 -0700562 }
563
scroggo46c57472015-09-30 08:57:13 -0700564 // FIXME: We could split these out based on subclass.
msarett614aa072015-07-27 15:13:17 -0700565 void* dstRow = dst;
scroggo05245902015-03-25 11:11:52 -0700566 if (fNumberPasses > 1) {
msarett60dcd3c2016-02-05 15:13:12 -0800567 storage.reset(height * srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800568 uint8_t* const base = storage.get();
scroggof24f2242015-03-03 08:59:20 -0800569
scroggo05245902015-03-25 11:11:52 -0700570 for (int i = 0; i < fNumberPasses; i++) {
msarett614aa072015-07-27 15:13:17 -0700571 uint8_t* srcRow = base;
scroggof24f2242015-03-03 08:59:20 -0800572 for (int y = 0; y < height; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800573 png_read_row(fPng_ptr, srcRow, nullptr);
msarett614aa072015-07-27 15:13:17 -0700574 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800575 }
576 }
577
578 // Now swizzle it.
msarett614aa072015-07-27 15:13:17 -0700579 uint8_t* srcRow = base;
msarett60dcd3c2016-02-05 15:13:12 -0800580 for (; row < height; row++) {
msaretta4970dc2016-01-11 07:23:23 -0800581 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700582 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
583 srcRow += srcRowBytes;
scroggof24f2242015-03-03 08:59:20 -0800584 }
585 } else {
msarett60dcd3c2016-02-05 15:13:12 -0800586 storage.reset(srcRowBytes);
scroggo565901d2015-12-10 10:44:13 -0800587 uint8_t* srcRow = storage.get();
msarett60dcd3c2016-02-05 15:13:12 -0800588 for (; row < height; row++) {
589 png_read_row(fPng_ptr, srcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800590 fSwizzler->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700591 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
scroggof24f2242015-03-03 08:59:20 -0800592 }
593 }
594
emmaleer973ae862015-07-20 13:38:44 -0700595 // read rest of file, and get additional comment and time chunks in info_ptr
scroggo05245902015-03-25 11:11:52 -0700596 png_read_end(fPng_ptr, fInfo_ptr);
scroggo46c57472015-09-30 08:57:13 -0700597
emmaleer973ae862015-07-20 13:38:44 -0700598 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700599}
600
scroggoc5560be2016-02-03 09:42:42 -0800601uint32_t SkPngCodec::onGetFillValue(SkColorType colorType) const {
msarette6dd0042015-10-09 11:07:34 -0700602 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
603 if (colorPtr) {
604 return get_color_table_fill_value(colorType, colorPtr, 0);
605 }
scroggoc5560be2016-02-03 09:42:42 -0800606 return INHERITED::onGetFillValue(colorType);
msarette6dd0042015-10-09 11:07:34 -0700607}
608
scroggo46c57472015-09-30 08:57:13 -0700609// Subclass of SkPngCodec which supports scanline decoding
610class SkPngScanlineDecoder : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700611public:
msarettc30c4182016-04-20 11:53:35 -0700612 SkPngScanlineDecoder(int width, int height, const SkEncodedInfo& info, SkStream* stream,
msarett6a738212016-03-04 13:27:35 -0800613 SkPngChunkReader* chunkReader, png_structp png_ptr, png_infop info_ptr, int bitDepth,
msarettad8bcfe2016-03-07 07:09:03 -0800614 sk_sp<SkColorSpace> colorSpace)
msarettc30c4182016-04-20 11:53:35 -0700615 : INHERITED(width, height, info, stream, chunkReader, png_ptr, info_ptr, bitDepth, 1,
616 colorSpace)
msarettf724b992015-10-15 06:41:06 -0700617 , fSrcRow(nullptr)
scroggo1c005e42015-08-04 09:24:45 -0700618 {}
619
scroggo46c57472015-09-30 08:57:13 -0700620 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
621 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700622 if (!conversion_possible(dstInfo, this->getInfo())) {
scroggo46c57472015-09-30 08:57:13 -0700623 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700624 }
625
scroggo46c57472015-09-30 08:57:13 -0700626 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
627 ctableCount);
628 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700629 return result;
630 }
631
msaretta45a6682016-04-22 13:18:37 -0700632 fStorage.reset(this->getInfo().width() *
633 (bytes_per_pixel(this->getEncodedInfo().bitsPerPixel())));
scroggo565901d2015-12-10 10:44:13 -0800634 fSrcRow = fStorage.get();
scroggo1c005e42015-08-04 09:24:45 -0700635
scroggo46c57472015-09-30 08:57:13 -0700636 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700637 }
638
msarette6dd0042015-10-09 11:07:34 -0700639 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
640 // Assume that an error in libpng indicates an incomplete input.
641 int row = 0;
scroggo46c57472015-09-30 08:57:13 -0700642 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700643 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700644 return row;
scroggo05245902015-03-25 11:11:52 -0700645 }
646
msarett614aa072015-07-27 15:13:17 -0700647 void* dstRow = dst;
msarette6dd0042015-10-09 11:07:34 -0700648 for (; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800649 png_read_row(this->png_ptr(), fSrcRow, nullptr);
msaretta4970dc2016-01-11 07:23:23 -0800650 this->swizzler()->swizzle(dstRow, fSrcRow);
msarett614aa072015-07-27 15:13:17 -0700651 dstRow = SkTAddOffset<void>(dstRow, rowBytes);
scroggo05245902015-03-25 11:11:52 -0700652 }
scroggo46c57472015-09-30 08:57:13 -0700653
msarette6dd0042015-10-09 11:07:34 -0700654 return row;
scroggo05245902015-03-25 11:11:52 -0700655 }
656
msarette6dd0042015-10-09 11:07:34 -0700657 bool onSkipScanlines(int count) override {
658 // Assume that an error in libpng indicates an incomplete input.
scroggo46c57472015-09-30 08:57:13 -0700659 if (setjmp(png_jmpbuf(this->png_ptr()))) {
scroggo230d4ac2015-03-26 07:15:55 -0700660 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700661 return false;
scroggo05245902015-03-25 11:11:52 -0700662 }
msarett60dcd3c2016-02-05 15:13:12 -0800663
msarette6dd0042015-10-09 11:07:34 -0700664 for (int row = 0; row < count; row++) {
msarett60dcd3c2016-02-05 15:13:12 -0800665 png_read_row(this->png_ptr(), fSrcRow, nullptr);
emmaleer7dc91902015-05-27 08:49:04 -0700666 }
msarette6dd0042015-10-09 11:07:34 -0700667 return true;
scroggo05245902015-03-25 11:11:52 -0700668 }
669
scroggo05245902015-03-25 11:11:52 -0700670private:
scroggo565901d2015-12-10 10:44:13 -0800671 SkAutoTMalloc<uint8_t> fStorage;
scroggo9b2cdbf42015-07-10 12:07:02 -0700672 uint8_t* fSrcRow;
scroggo05245902015-03-25 11:11:52 -0700673
scroggo46c57472015-09-30 08:57:13 -0700674 typedef SkPngCodec INHERITED;
scroggo05245902015-03-25 11:11:52 -0700675};
676
emmaleer0a4c3cb2015-06-22 10:40:21 -0700677
scroggo46c57472015-09-30 08:57:13 -0700678class SkPngInterlacedScanlineDecoder : public SkPngCodec {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700679public:
msarettc30c4182016-04-20 11:53:35 -0700680 SkPngInterlacedScanlineDecoder(int width, int height, const SkEncodedInfo& info,
681 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
682 png_infop info_ptr, int bitDepth, int numberPasses, sk_sp<SkColorSpace> colorSpace)
683 : INHERITED(width, height, info, stream, chunkReader, png_ptr, info_ptr, bitDepth,
684 numberPasses, colorSpace)
scroggo46c57472015-09-30 08:57:13 -0700685 , fHeight(-1)
scroggo1c005e42015-08-04 09:24:45 -0700686 , fCanSkipRewind(false)
scroggo1c005e42015-08-04 09:24:45 -0700687 {
scroggo46c57472015-09-30 08:57:13 -0700688 SkASSERT(numberPasses != 1);
689 }
690
691 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
msarettfdb47572015-10-13 12:50:14 -0700692 SkPMColor ctable[], int* ctableCount) override {
scroggo1c005e42015-08-04 09:24:45 -0700693 if (!conversion_possible(dstInfo, this->getInfo())) {
mtklein372d65c2016-01-27 13:01:41 -0800694 return kInvalidConversion;
scroggo1c005e42015-08-04 09:24:45 -0700695 }
696
msarettfdb47572015-10-13 12:50:14 -0700697 const Result result = this->initializeSwizzler(dstInfo, options, ctable,
698 ctableCount);
699 if (result != kSuccess) {
scroggo1c005e42015-08-04 09:24:45 -0700700 return result;
701 }
702
scroggo1c005e42015-08-04 09:24:45 -0700703 fHeight = dstInfo.height();
scroggo46c57472015-09-30 08:57:13 -0700704 // FIXME: This need not be called on a second call to onStartScanlineDecode.
msaretta45a6682016-04-22 13:18:37 -0700705 fSrcRowBytes = this->getInfo().width() *
706 (bytes_per_pixel(this->getEncodedInfo().bitsPerPixel()));
scroggo1c005e42015-08-04 09:24:45 -0700707 fGarbageRow.reset(fSrcRowBytes);
708 fGarbageRowPtr = static_cast<uint8_t*>(fGarbageRow.get());
709 fCanSkipRewind = true;
710
711 return SkCodec::kSuccess;
712 }
713
msarette6dd0042015-10-09 11:07:34 -0700714 int onGetScanlines(void* dst, int count, size_t dstRowBytes) override {
scroggo1c005e42015-08-04 09:24:45 -0700715 // rewind stream if have previously called onGetScanlines,
716 // since we need entire progressive image to get scanlines
717 if (fCanSkipRewind) {
scroggo46c57472015-09-30 08:57:13 -0700718 // We already rewound in onStartScanlineDecode, so there is no reason to rewind.
scroggo1c005e42015-08-04 09:24:45 -0700719 // Next time onGetScanlines is called, we will need to rewind.
720 fCanSkipRewind = false;
scroggo46c57472015-09-30 08:57:13 -0700721 } else {
722 // rewindIfNeeded resets fCurrScanline, since it assumes that start
723 // needs to be called again before scanline decoding. PNG scanline
724 // decoding is the exception, since it needs to rewind between
725 // calls to getScanlines. Keep track of fCurrScanline, to undo the
726 // reset.
msarette6dd0042015-10-09 11:07:34 -0700727 const int currScanline = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700728 // This method would never be called if currScanline is -1
729 SkASSERT(currScanline != -1);
730
731 if (!this->rewindIfNeeded()) {
732 return kCouldNotRewind;
733 }
msarettcb0d5c92015-12-03 12:23:43 -0800734 this->updateCurrScanline(currScanline);
scroggo1c005e42015-08-04 09:24:45 -0700735 }
736
scroggo46c57472015-09-30 08:57:13 -0700737 if (setjmp(png_jmpbuf(this->png_ptr()))) {
emmaleer0a4c3cb2015-06-22 10:40:21 -0700738 SkCodecPrintf("setjmp long jump!\n");
msarette6dd0042015-10-09 11:07:34 -0700739 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
740 // we may be able to report that all of the memory has been initialized. Even if we
741 // fail on the first pass, we can still report than some scanlines are initialized.
742 return 0;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700743 }
scroggo565901d2015-12-10 10:44:13 -0800744 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
745 uint8_t* storagePtr = storage.get();
emmaleer0a4c3cb2015-06-22 10:40:21 -0700746 uint8_t* srcRow;
msarette6dd0042015-10-09 11:07:34 -0700747 const int startRow = this->nextScanline();
scroggo46c57472015-09-30 08:57:13 -0700748 for (int i = 0; i < this->numberPasses(); i++) {
749 // read rows we planned to skip into garbage row
750 for (int y = 0; y < startRow; y++){
msarett60dcd3c2016-02-05 15:13:12 -0800751 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700752 }
scroggo46c57472015-09-30 08:57:13 -0700753 // read rows we care about into buffer
emmaleer0a4c3cb2015-06-22 10:40:21 -0700754 srcRow = storagePtr;
755 for (int y = 0; y < count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800756 png_read_row(this->png_ptr(), srcRow, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700757 srcRow += fSrcRowBytes;
758 }
scroggo46c57472015-09-30 08:57:13 -0700759 // read rows we don't want into garbage buffer
760 for (int y = 0; y < fHeight - startRow - count; y++) {
msarett60dcd3c2016-02-05 15:13:12 -0800761 png_read_row(this->png_ptr(), fGarbageRowPtr, nullptr);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700762 }
763 }
764 //swizzle the rows we care about
765 srcRow = storagePtr;
msarett614aa072015-07-27 15:13:17 -0700766 void* dstRow = dst;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700767 for (int y = 0; y < count; y++) {
msaretta4970dc2016-01-11 07:23:23 -0800768 this->swizzler()->swizzle(dstRow, srcRow);
msarett614aa072015-07-27 15:13:17 -0700769 dstRow = SkTAddOffset<void>(dstRow, dstRowBytes);
emmaleer0a4c3cb2015-06-22 10:40:21 -0700770 srcRow += fSrcRowBytes;
771 }
scroggo46c57472015-09-30 08:57:13 -0700772
msarette6dd0042015-10-09 11:07:34 -0700773 return count;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700774 }
775
msarette6dd0042015-10-09 11:07:34 -0700776 bool onSkipScanlines(int count) override {
scroggo46c57472015-09-30 08:57:13 -0700777 // The non-virtual version will update fCurrScanline.
msarette6dd0042015-10-09 11:07:34 -0700778 return true;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700779 }
780
msarett5406d6f2015-08-31 06:55:13 -0700781 SkScanlineOrder onGetScanlineOrder() const override {
782 return kNone_SkScanlineOrder;
emmaleer8f4ba762015-08-14 07:44:46 -0700783 }
784
emmaleer0a4c3cb2015-06-22 10:40:21 -0700785private:
scroggo9b2cdbf42015-07-10 12:07:02 -0700786 int fHeight;
787 size_t fSrcRowBytes;
788 SkAutoMalloc fGarbageRow;
789 uint8_t* fGarbageRowPtr;
scroggo1c005e42015-08-04 09:24:45 -0700790 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
791 // is called whenever some action is taken that reads the stream and
792 // therefore the next call will require a rewind. So it modifies a boolean
793 // to note that the *next* time it is called a rewind is needed.
scroggo46c57472015-09-30 08:57:13 -0700794 // SkPngInterlacedScanlineDecoder has an extra wrinkle - calling
795 // onStartScanlineDecode followed by onGetScanlines does *not* require a
796 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
797 // add another layer.
scroggo1c005e42015-08-04 09:24:45 -0700798 bool fCanSkipRewind;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700799
scroggo46c57472015-09-30 08:57:13 -0700800 typedef SkPngCodec INHERITED;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700801};
802
scroggocf98fa92015-11-23 08:14:40 -0800803SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
scroggo46c57472015-09-30 08:57:13 -0700804 SkAutoTDelete<SkStream> streamDeleter(stream);
805 png_structp png_ptr;
806 png_infop info_ptr;
msarettc30c4182016-04-20 11:53:35 -0700807 int width, height;
808 SkEncodedInfo imageInfo;
scroggo46c57472015-09-30 08:57:13 -0700809 int bitDepth;
810 int numberPasses;
811
msarettc30c4182016-04-20 11:53:35 -0700812 if (!read_header(stream, chunkReader, &png_ptr, &info_ptr, &width, &height, &imageInfo,
813 &bitDepth, &numberPasses)) {
halcanary96fcdcc2015-08-27 07:41:13 -0700814 return nullptr;
scroggo05245902015-03-25 11:11:52 -0700815 }
816
msarettad8bcfe2016-03-07 07:09:03 -0800817 auto colorSpace = read_color_space(png_ptr, info_ptr);
msarett6a738212016-03-04 13:27:35 -0800818
scroggo46c57472015-09-30 08:57:13 -0700819 if (1 == numberPasses) {
msarettc30c4182016-04-20 11:53:35 -0700820 return new SkPngScanlineDecoder(width, height, imageInfo, streamDeleter.release(),
821 chunkReader, png_ptr, info_ptr, bitDepth, colorSpace);
scroggo05245902015-03-25 11:11:52 -0700822 }
823
msarettc30c4182016-04-20 11:53:35 -0700824 return new SkPngInterlacedScanlineDecoder(width, height, imageInfo, streamDeleter.release(),
825 chunkReader, png_ptr, info_ptr, bitDepth,
826 numberPasses, colorSpace);
scroggo05245902015-03-25 11:11:52 -0700827}