blob: 121b74ff0b3a97defc00a75ed5c2c1cabda5b2e4 [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
8#include "SkCodec_libpng.h"
msarett74114382015-03-16 11:55:18 -07009#include "SkCodecPriv.h"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkColorPriv.h"
11#include "SkColorTable.h"
12#include "SkBitmap.h"
13#include "SkMath.h"
scroggo05245902015-03-25 11:11:52 -070014#include "SkScanlineDecoder.h"
scroggof24f2242015-03-03 08:59:20 -080015#include "SkSize.h"
16#include "SkStream.h"
17#include "SkSwizzler.h"
18
19///////////////////////////////////////////////////////////////////////////////
20// Helper macros
21///////////////////////////////////////////////////////////////////////////////
22
23#ifndef png_jmpbuf
24# define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
25#endif
26
27/* These were dropped in libpng >= 1.4 */
28#ifndef png_infopp_NULL
29 #define png_infopp_NULL NULL
30#endif
31
32#ifndef png_bytepp_NULL
33 #define png_bytepp_NULL NULL
34#endif
35
36#ifndef int_p_NULL
37 #define int_p_NULL NULL
38#endif
39
40#ifndef png_flush_ptr_NULL
41 #define png_flush_ptr_NULL NULL
42#endif
43
44///////////////////////////////////////////////////////////////////////////////
45// Callback functions
46///////////////////////////////////////////////////////////////////////////////
47
48static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
scroggo230d4ac2015-03-26 07:15:55 -070049 SkCodecPrintf("------ png error %s\n", msg);
scroggof24f2242015-03-03 08:59:20 -080050 longjmp(png_jmpbuf(png_ptr), 1);
51}
52
scroggo0eed6df2015-03-26 10:07:56 -070053void sk_warning_fn(png_structp, png_const_charp msg) {
54 SkCodecPrintf("----- png warning %s\n", msg);
55}
56
scroggof24f2242015-03-03 08:59:20 -080057static void sk_read_fn(png_structp png_ptr, png_bytep data,
58 png_size_t length) {
59 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
60 const size_t bytes = stream->read(data, length);
61 if (bytes != length) {
62 // FIXME: We want to report the fact that the stream was truncated.
63 // One way to do that might be to pass a enum to longjmp so setjmp can
64 // specify the failure.
65 png_error(png_ptr, "Read Error!");
66 }
67}
68
69///////////////////////////////////////////////////////////////////////////////
70// Helpers
71///////////////////////////////////////////////////////////////////////////////
72
73class AutoCleanPng : public SkNoncopyable {
74public:
75 AutoCleanPng(png_structp png_ptr)
76 : fPng_ptr(png_ptr)
77 , fInfo_ptr(NULL) {}
78
79 ~AutoCleanPng() {
80 // fInfo_ptr will never be non-NULL unless fPng_ptr is.
81 if (fPng_ptr) {
82 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : NULL;
83 png_destroy_read_struct(&fPng_ptr, info_pp, png_infopp_NULL);
84 }
85 }
86
87 void setInfoPtr(png_infop info_ptr) {
88 SkASSERT(NULL == fInfo_ptr);
89 fInfo_ptr = info_ptr;
90 }
91
92 void detach() {
93 fPng_ptr = NULL;
94 fInfo_ptr = NULL;
95 }
96
97private:
98 png_structp fPng_ptr;
99 png_infop fInfo_ptr;
100};
101#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
102
103// call only if color_type is PALETTE. Returns true if the ctable has alpha
104static bool has_transparency_in_palette(png_structp png_ptr,
105 png_infop info_ptr) {
106 if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
107 return false;
108 }
109
110 png_bytep trans;
111 int num_trans;
112 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
113 return num_trans > 0;
114}
115
116// Method for coverting to either an SkPMColor or a similarly packed
117// unpremultiplied color.
118typedef uint32_t (*PackColorProc)(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
119
120// Note: SkColorTable claims to store SkPMColors, which is not necessarily
121// the case here.
scroggo05245902015-03-25 11:11:52 -0700122bool SkPngCodec::decodePalette(bool premultiply) {
scroggof24f2242015-03-03 08:59:20 -0800123 int numPalette;
124 png_colorp palette;
125 png_bytep trans;
126
scroggo05245902015-03-25 11:11:52 -0700127 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numPalette)) {
128 return false;
scroggof24f2242015-03-03 08:59:20 -0800129 }
130
131 /* BUGGY IMAGE WORKAROUND
132
133 We hit some images (e.g. fruit_.png) who contain bytes that are == colortable_count
134 which is a problem since we use the byte as an index. To work around this we grow
135 the colortable by 1 (if its < 256) and duplicate the last color into that slot.
136 */
137 const int colorCount = numPalette + (numPalette < 256);
138 // Note: These are not necessarily SkPMColors.
139 SkPMColor colorStorage[256]; // worst-case storage
140 SkPMColor* colorPtr = colorStorage;
141
142 int numTrans;
scroggo05245902015-03-25 11:11:52 -0700143 if (png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS)) {
144 png_get_tRNS(fPng_ptr, fInfo_ptr, &trans, &numTrans, NULL);
scroggof24f2242015-03-03 08:59:20 -0800145 } else {
146 numTrans = 0;
147 }
148
149 // check for bad images that might make us crash
150 if (numTrans > numPalette) {
151 numTrans = numPalette;
152 }
153
154 int index = 0;
155 int transLessThanFF = 0;
156
157 // Choose which function to use to create the color table. If the final destination's
158 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
159 PackColorProc proc;
160 if (premultiply) {
161 proc = &SkPreMultiplyARGB;
162 } else {
163 proc = &SkPackARGB32NoCheck;
164 }
165 for (; index < numTrans; index++) {
166 transLessThanFF |= (int)*trans - 0xFF;
167 *colorPtr++ = proc(*trans++, palette->red, palette->green, palette->blue);
168 palette++;
169 }
170
scroggo05245902015-03-25 11:11:52 -0700171 fReallyHasAlpha = transLessThanFF < 0;
scroggof24f2242015-03-03 08:59:20 -0800172
173 for (; index < numPalette; index++) {
174 *colorPtr++ = SkPackARGB32(0xFF, palette->red, palette->green, palette->blue);
175 palette++;
176 }
177
178 // see BUGGY IMAGE WORKAROUND comment above
179 if (numPalette < 256) {
180 *colorPtr = colorPtr[-1];
181 }
182
scroggo05245902015-03-25 11:11:52 -0700183 fColorTable.reset(SkNEW_ARGS(SkColorTable, (colorStorage, colorCount)));
184 return true;
scroggof24f2242015-03-03 08:59:20 -0800185}
186
187///////////////////////////////////////////////////////////////////////////////
188// Creation
189///////////////////////////////////////////////////////////////////////////////
190
191#define PNG_BYTES_TO_CHECK 4
192
193bool SkPngCodec::IsPng(SkStream* stream) {
194 char buf[PNG_BYTES_TO_CHECK];
195 if (stream->read(buf, PNG_BYTES_TO_CHECK) != PNG_BYTES_TO_CHECK) {
196 return false;
197 }
198 if (png_sig_cmp((png_bytep) buf, (png_size_t)0, PNG_BYTES_TO_CHECK)) {
199 return false;
200 }
201 return true;
202}
203
scroggo3eada2a2015-04-01 09:33:23 -0700204// Reads the header, and initializes the passed in fields, if not NULL (except
205// stream, which is passed to the read function).
206// Returns true on success, in which case the caller is responsible for calling
207// png_destroy_read_struct. If it returns false, the passed in fields (except
208// stream) are unchanged.
209static bool read_header(SkStream* stream, png_structp* png_ptrp,
210 png_infop* info_ptrp, SkImageInfo* imageInfo) {
scroggof24f2242015-03-03 08:59:20 -0800211 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
scroggof24f2242015-03-03 08:59:20 -0800212 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,
scroggo0eed6df2015-03-26 10:07:56 -0700213 sk_error_fn, sk_warning_fn);
scroggof24f2242015-03-03 08:59:20 -0800214 if (!png_ptr) {
scroggo3eada2a2015-04-01 09:33:23 -0700215 return false;
scroggof24f2242015-03-03 08:59:20 -0800216 }
217
218 AutoCleanPng autoClean(png_ptr);
219
220 png_infop info_ptr = png_create_info_struct(png_ptr);
221 if (info_ptr == NULL) {
scroggo3eada2a2015-04-01 09:33:23 -0700222 return false;
scroggof24f2242015-03-03 08:59:20 -0800223 }
224
225 autoClean.setInfoPtr(info_ptr);
226
227 // FIXME: Could we use the return value of setjmp to specify the type of
228 // error?
229 if (setjmp(png_jmpbuf(png_ptr))) {
scroggo3eada2a2015-04-01 09:33:23 -0700230 return false;
scroggof24f2242015-03-03 08:59:20 -0800231 }
232
233 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
234
235 // FIXME: This is where the old code hooks up the Peeker. Does it need to
236 // be set this early? (i.e. where are the user chunks? early in the stream,
237 // potentially?)
238 // If it does, we need to figure out a way to set it here.
239
240 // The call to png_read_info() gives us all of the information from the
241 // PNG file before the first IDAT (image data chunk).
242 png_read_info(png_ptr, info_ptr);
243 png_uint_32 origWidth, origHeight;
244 int bitDepth, colorType;
245 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
246 &colorType, int_p_NULL, int_p_NULL, int_p_NULL);
247
248 // sanity check for size
249 {
250 int64_t size = sk_64_mul(origWidth, origHeight);
251 // now check that if we are 4-bytes per pixel, we also don't overflow
252 if (size < 0 || size > (0x7FFFFFFF >> 2)) {
scroggo3eada2a2015-04-01 09:33:23 -0700253 return false;
scroggof24f2242015-03-03 08:59:20 -0800254 }
255 }
256
257 // Tell libpng to strip 16 bit/color files down to 8 bits/color
258 if (bitDepth == 16) {
259 png_set_strip_16(png_ptr);
260 }
261#ifdef PNG_READ_PACK_SUPPORTED
262 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
263 // byte into separate bytes (useful for paletted and grayscale images).
264 if (bitDepth < 8) {
265 png_set_packing(png_ptr);
266 }
267#endif
268 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
269 if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) {
270 png_set_expand_gray_1_2_4_to_8(png_ptr);
271 }
272
273
274 // Now determine the default SkColorType and SkAlphaType.
275 SkColorType skColorType;
276 SkAlphaType skAlphaType;
277 switch (colorType) {
278 case PNG_COLOR_TYPE_PALETTE:
279 // Technically, this is true of the data, but I don't think we want
280 // to support it.
281 // skColorType = kIndex8_SkColorType;
282 skColorType = kN32_SkColorType;
283 skAlphaType = has_transparency_in_palette(png_ptr, info_ptr) ?
284 kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
285 break;
286 case PNG_COLOR_TYPE_GRAY:
287 if (false) {
288 // FIXME: Is this the wrong default behavior? This means if the
289 // caller supplies the info we gave them, they'll get Alpha 8.
290 skColorType = kAlpha_8_SkColorType;
291 // FIXME: Strangely, the canonical type for Alpha 8 is Premul.
292 skAlphaType = kPremul_SkAlphaType;
293 } else {
294 skColorType = kN32_SkColorType;
295 skAlphaType = kOpaque_SkAlphaType;
296 }
297 break;
298 default:
299 // Note: This *almost* mimics the code in SkImageDecoder_libpng.
300 // has_transparency_in_palette makes an additional check - whether
301 // numTrans is greater than 0. Why does the other code not make that
302 // check?
303 if (has_transparency_in_palette(png_ptr, info_ptr)
304 || PNG_COLOR_TYPE_RGB_ALPHA == colorType
305 || PNG_COLOR_TYPE_GRAY_ALPHA == colorType)
306 {
307 skAlphaType = kUnpremul_SkAlphaType;
308 } else {
309 skAlphaType = kOpaque_SkAlphaType;
310 }
311 skColorType = kN32_SkColorType;
312 break;
313 }
314
315 {
316 // FIXME: Again, this block needs to go into onGetPixels.
317 bool convertGrayToRGB = PNG_COLOR_TYPE_GRAY == colorType && skColorType != kAlpha_8_SkColorType;
318
319 // Unless the user is requesting A8, convert a grayscale image into RGB.
320 // GRAY_ALPHA will always be converted to RGB
321 if (convertGrayToRGB || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
322 png_set_gray_to_rgb(png_ptr);
323 }
324
325 // Add filler (or alpha) byte (after each RGB triplet) if necessary.
326 // FIXME: It seems like we could just use RGB as the SrcConfig here.
327 if (colorType == PNG_COLOR_TYPE_RGB || convertGrayToRGB) {
328 png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
329 }
330 }
331
332 // FIXME: Also need to check for sRGB (skbug.com/3471).
333
scroggo3eada2a2015-04-01 09:33:23 -0700334 if (imageInfo) {
335 *imageInfo = SkImageInfo::Make(origWidth, origHeight, skColorType,
336 skAlphaType);
337 }
scroggof24f2242015-03-03 08:59:20 -0800338 autoClean.detach();
scroggo3eada2a2015-04-01 09:33:23 -0700339 if (png_ptrp) {
340 *png_ptrp = png_ptr;
341 }
342 if (info_ptrp) {
343 *info_ptrp = info_ptr;
344 }
345 return true;
346}
347
348SkCodec* SkPngCodec::NewFromStream(SkStream* stream) {
scroggo0a7e69c2015-04-03 07:22:22 -0700349 SkAutoTDelete<SkStream> streamDeleter(stream);
scroggo3eada2a2015-04-01 09:33:23 -0700350 png_structp png_ptr;
351 png_infop info_ptr;
352 SkImageInfo imageInfo;
353 if (read_header(stream, &png_ptr, &info_ptr, &imageInfo)) {
scroggo0a7e69c2015-04-03 07:22:22 -0700354 return SkNEW_ARGS(SkPngCodec, (imageInfo, streamDeleter.detach(), png_ptr, info_ptr));
scroggo3eada2a2015-04-01 09:33:23 -0700355 }
356 return NULL;
scroggof24f2242015-03-03 08:59:20 -0800357}
358
scroggo05245902015-03-25 11:11:52 -0700359#define INVALID_NUMBER_PASSES -1
scroggof24f2242015-03-03 08:59:20 -0800360SkPngCodec::SkPngCodec(const SkImageInfo& info, SkStream* stream,
361 png_structp png_ptr, png_infop info_ptr)
362 : INHERITED(info, stream)
363 , fPng_ptr(png_ptr)
scroggo05245902015-03-25 11:11:52 -0700364 , fInfo_ptr(info_ptr)
365 , fSrcConfig(SkSwizzler::kUnknown)
366 , fNumberPasses(INVALID_NUMBER_PASSES)
367 , fReallyHasAlpha(false)
368{}
scroggof24f2242015-03-03 08:59:20 -0800369
370SkPngCodec::~SkPngCodec() {
scroggo3eada2a2015-04-01 09:33:23 -0700371 this->destroyReadStruct();
372}
373
374void SkPngCodec::destroyReadStruct() {
375 if (fPng_ptr) {
376 // We will never have a NULL fInfo_ptr with a non-NULL fPng_ptr
377 SkASSERT(fInfo_ptr);
378 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, png_infopp_NULL);
379 fPng_ptr = NULL;
380 fInfo_ptr = NULL;
381 }
scroggof24f2242015-03-03 08:59:20 -0800382}
383
384///////////////////////////////////////////////////////////////////////////////
385// Getting the pixels
386///////////////////////////////////////////////////////////////////////////////
387
msaretteed039b2015-03-18 11:11:19 -0700388static bool conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
scroggof24f2242015-03-03 08:59:20 -0800389 // TODO: Support other conversions
msaretteed039b2015-03-18 11:11:19 -0700390 if (dst.colorType() != src.colorType()) {
scroggof24f2242015-03-03 08:59:20 -0800391 return false;
392 }
msaretteed039b2015-03-18 11:11:19 -0700393 if (dst.profileType() != src.profileType()) {
scroggof24f2242015-03-03 08:59:20 -0800394 return false;
395 }
msaretteed039b2015-03-18 11:11:19 -0700396 if (dst.alphaType() == src.alphaType()) {
scroggof24f2242015-03-03 08:59:20 -0800397 return true;
398 }
msaretteed039b2015-03-18 11:11:19 -0700399 return kPremul_SkAlphaType == dst.alphaType() &&
400 kUnpremul_SkAlphaType == src.alphaType();
scroggof24f2242015-03-03 08:59:20 -0800401}
402
scroggo05245902015-03-25 11:11:52 -0700403SkCodec::Result SkPngCodec::initializeSwizzler(const SkImageInfo& requestedInfo,
404 void* dst, size_t rowBytes,
405 const Options& options) {
scroggof24f2242015-03-03 08:59:20 -0800406 // FIXME: Could we use the return value of setjmp to specify the type of
407 // error?
408 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700409 SkCodecPrintf("setjmp long jump!\n");
scroggof24f2242015-03-03 08:59:20 -0800410 return kInvalidInput;
411 }
412
413 // FIXME: We already retrieved this information. Store it in SkPngCodec?
414 png_uint_32 origWidth, origHeight;
415 int bitDepth, pngColorType, interlaceType;
416 png_get_IHDR(fPng_ptr, fInfo_ptr, &origWidth, &origHeight, &bitDepth,
417 &pngColorType, &interlaceType, int_p_NULL, int_p_NULL);
418
scroggo05245902015-03-25 11:11:52 -0700419 fNumberPasses = (interlaceType != PNG_INTERLACE_NONE) ?
scroggof24f2242015-03-03 08:59:20 -0800420 png_set_interlace_handling(fPng_ptr) : 1;
421
scroggo05245902015-03-25 11:11:52 -0700422 // Set to the default before calling decodePalette, which may change it.
423 fReallyHasAlpha = false;
scroggof24f2242015-03-03 08:59:20 -0800424 if (PNG_COLOR_TYPE_PALETTE == pngColorType) {
scroggo05245902015-03-25 11:11:52 -0700425 fSrcConfig = SkSwizzler::kIndex;
426 if (!this->decodePalette(kPremul_SkAlphaType == requestedInfo.alphaType())) {
scroggof24f2242015-03-03 08:59:20 -0800427 return kInvalidInput;
428 }
scroggof24f2242015-03-03 08:59:20 -0800429 } else if (kAlpha_8_SkColorType == requestedInfo.colorType()) {
430 // Note: we check the destination, since otherwise we would have
431 // told png to upscale.
432 SkASSERT(PNG_COLOR_TYPE_GRAY == pngColorType);
scroggo05245902015-03-25 11:11:52 -0700433 fSrcConfig = SkSwizzler::kGray;
msarett9bde9182015-03-25 05:27:48 -0700434 } else if (this->getInfo().alphaType() == kOpaque_SkAlphaType) {
scroggo05245902015-03-25 11:11:52 -0700435 fSrcConfig = SkSwizzler::kRGBX;
scroggof24f2242015-03-03 08:59:20 -0800436 } else {
scroggo05245902015-03-25 11:11:52 -0700437 fSrcConfig = SkSwizzler::kRGBA;
scroggof24f2242015-03-03 08:59:20 -0800438 }
scroggo05245902015-03-25 11:11:52 -0700439 const SkPMColor* colors = fColorTable ? fColorTable->readColors() : NULL;
440 fSwizzler.reset(SkSwizzler::CreateSwizzler(fSrcConfig, colors, requestedInfo,
441 dst, rowBytes, options.fZeroInitialized));
442 if (!fSwizzler) {
scroggof24f2242015-03-03 08:59:20 -0800443 // FIXME: CreateSwizzler could fail for another reason.
444 return kUnimplemented;
445 }
446
447 // FIXME: Here is where we should likely insert some of the modifications
448 // made in the factory.
449 png_read_update_info(fPng_ptr, fInfo_ptr);
450
scroggo05245902015-03-25 11:11:52 -0700451 return kSuccess;
452}
453
scroggo58421542015-04-01 11:25:20 -0700454bool SkPngCodec::handleRewind() {
455 switch (this->rewindIfNeeded()) {
456 case kNoRewindNecessary_RewindState:
457 return true;
458 case kCouldNotRewind_RewindState:
459 return false;
460 case kRewound_RewindState: {
461 // This sets fPng_ptr and fInfo_ptr to NULL. If read_header
462 // succeeds, they will be repopulated, and if it fails, they will
463 // remain NULL. Any future accesses to fPng_ptr and fInfo_ptr will
464 // come through this function which will rewind and again attempt
465 // to reinitialize them.
466 this->destroyReadStruct();
467 png_structp png_ptr;
468 png_infop info_ptr;
469 if (read_header(this->stream(), &png_ptr, &info_ptr, NULL)) {
470 fPng_ptr = png_ptr;
471 fInfo_ptr = info_ptr;
472 return true;
473 }
474 return false;
475 }
476 default:
477 SkASSERT(false);
478 return false;
479 }
480}
481
scroggo05245902015-03-25 11:11:52 -0700482SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
483 size_t rowBytes, const Options& options,
484 SkPMColor ctable[], int* ctableCount) {
scroggo58421542015-04-01 11:25:20 -0700485 if (!this->handleRewind()) {
halcanarya096d7a2015-03-27 12:16:53 -0700486 return kCouldNotRewind;
scroggo05245902015-03-25 11:11:52 -0700487 }
488 if (requestedInfo.dimensions() != this->getInfo().dimensions()) {
489 return kInvalidScale;
490 }
491 if (!conversion_possible(requestedInfo, this->getInfo())) {
492 return kInvalidConversion;
493 }
494
495 const Result result = this->initializeSwizzler(requestedInfo, dst, rowBytes,
496 options);
497 if (result != kSuccess) {
498 return result;
499 }
500
501 // FIXME: Could we use the return value of setjmp to specify the type of
502 // error?
503 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700504 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700505 return kInvalidInput;
506 }
507
508 SkASSERT(fNumberPasses != INVALID_NUMBER_PASSES);
509 SkAutoMalloc storage;
510 if (fNumberPasses > 1) {
scroggof24f2242015-03-03 08:59:20 -0800511 const int width = requestedInfo.width();
512 const int height = requestedInfo.height();
scroggo05245902015-03-25 11:11:52 -0700513 const int bpp = SkSwizzler::BytesPerPixel(fSrcConfig);
scroggof24f2242015-03-03 08:59:20 -0800514 const size_t rowBytes = width * bpp;
515
516 storage.reset(width * height * bpp);
517 uint8_t* const base = static_cast<uint8_t*>(storage.get());
518
scroggo05245902015-03-25 11:11:52 -0700519 for (int i = 0; i < fNumberPasses; i++) {
scroggof24f2242015-03-03 08:59:20 -0800520 uint8_t* row = base;
521 for (int y = 0; y < height; y++) {
522 uint8_t* bmRow = row;
523 png_read_rows(fPng_ptr, &bmRow, png_bytepp_NULL, 1);
524 row += rowBytes;
525 }
526 }
527
528 // Now swizzle it.
529 uint8_t* row = base;
530 for (int y = 0; y < height; y++) {
scroggo05245902015-03-25 11:11:52 -0700531 fReallyHasAlpha |= !SkSwizzler::IsOpaque(fSwizzler->next(row));
scroggof24f2242015-03-03 08:59:20 -0800532 row += rowBytes;
533 }
534 } else {
scroggo05245902015-03-25 11:11:52 -0700535 storage.reset(requestedInfo.width() * SkSwizzler::BytesPerPixel(fSrcConfig));
scroggof24f2242015-03-03 08:59:20 -0800536 uint8_t* srcRow = static_cast<uint8_t*>(storage.get());
537 for (int y = 0; y < requestedInfo.height(); y++) {
538 png_read_rows(fPng_ptr, &srcRow, png_bytepp_NULL, 1);
scroggo05245902015-03-25 11:11:52 -0700539 fReallyHasAlpha |= !SkSwizzler::IsOpaque(fSwizzler->next(srcRow));
scroggof24f2242015-03-03 08:59:20 -0800540 }
541 }
542
scroggo05245902015-03-25 11:11:52 -0700543 // FIXME: do we need substituteTranspColor? Note that we cannot do it for
544 // scanline decoding, but we could do it here. Alternatively, we could do
545 // it as we go, instead of in post-processing like SkPNGImageDecoder.
scroggof24f2242015-03-03 08:59:20 -0800546
scroggo05245902015-03-25 11:11:52 -0700547 this->finish();
scroggof24f2242015-03-03 08:59:20 -0800548 return kSuccess;
549}
scroggo05245902015-03-25 11:11:52 -0700550
551void SkPngCodec::finish() {
552 if (setjmp(png_jmpbuf(fPng_ptr))) {
553 // We've already read all the scanlines. This is a success.
554 return;
555 }
556 /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
557 png_read_end(fPng_ptr, fInfo_ptr);
558}
559
560class SkPngScanlineDecoder : public SkScanlineDecoder {
561public:
562 SkPngScanlineDecoder(const SkImageInfo& dstInfo, SkPngCodec* codec)
563 : INHERITED(dstInfo)
564 , fCodec(codec)
565 , fHasAlpha(false)
566 {
567 fStorage.reset(dstInfo.width() * SkSwizzler::BytesPerPixel(fCodec->fSrcConfig));
568 fSrcRow = static_cast<uint8_t*>(fStorage.get());
569 }
570
mtklein36352bf2015-03-25 18:17:31 -0700571 SkImageGenerator::Result onGetScanlines(void* dst, int count, size_t rowBytes) override {
scroggo05245902015-03-25 11:11:52 -0700572 if (setjmp(png_jmpbuf(fCodec->fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700573 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700574 return SkImageGenerator::kInvalidInput;
575 }
576
577 for (int i = 0; i < count; i++) {
578 png_read_rows(fCodec->fPng_ptr, &fSrcRow, png_bytepp_NULL, 1);
579 fCodec->fSwizzler->setDstRow(dst);
580 fHasAlpha |= !SkSwizzler::IsOpaque(fCodec->fSwizzler->next(fSrcRow));
581 dst = SkTAddOffset<void>(dst, rowBytes);
582 }
583 return SkImageGenerator::kSuccess;
584 }
585
mtklein36352bf2015-03-25 18:17:31 -0700586 SkImageGenerator::Result onSkipScanlines(int count) override {
scroggo05245902015-03-25 11:11:52 -0700587 // FIXME: Could we use the return value of setjmp to specify the type of
588 // error?
589 if (setjmp(png_jmpbuf(fCodec->fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700590 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700591 return SkImageGenerator::kInvalidInput;
592 }
593
594 png_read_rows(fCodec->fPng_ptr, png_bytepp_NULL, png_bytepp_NULL, count);
595 return SkImageGenerator::kSuccess;
596 }
597
mtklein36352bf2015-03-25 18:17:31 -0700598 void onFinish() override {
scroggo05245902015-03-25 11:11:52 -0700599 fCodec->finish();
600 }
601
mtklein36352bf2015-03-25 18:17:31 -0700602 bool onReallyHasAlpha() const override { return fHasAlpha; }
scroggo05245902015-03-25 11:11:52 -0700603
604private:
605 SkPngCodec* fCodec; // Unowned.
606 bool fHasAlpha;
607 SkAutoMalloc fStorage;
608 uint8_t* fSrcRow;
609
610 typedef SkScanlineDecoder INHERITED;
611};
612
613SkScanlineDecoder* SkPngCodec::onGetScanlineDecoder(const SkImageInfo& dstInfo) {
scroggo58421542015-04-01 11:25:20 -0700614 if (!this->handleRewind()) {
615 return NULL;
616 }
617
scroggo05245902015-03-25 11:11:52 -0700618 // Check to see if scaling was requested.
619 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
620 return NULL;
621 }
622
623 if (!conversion_possible(dstInfo, this->getInfo())) {
scroggo230d4ac2015-03-26 07:15:55 -0700624 SkCodecPrintf("no conversion possible\n");
scroggo05245902015-03-25 11:11:52 -0700625 return NULL;
626 }
627
628 // Note: We set dst to NULL since we do not know it yet. rowBytes is not needed,
629 // since we'll be manually updating the dstRow, but the SkSwizzler requires it to
630 // be at least dstInfo.minRowBytes.
631 Options opts;
632 // FIXME: Pass this in to getScanlineDecoder?
633 opts.fZeroInitialized = kNo_ZeroInitialized;
634 if (this->initializeSwizzler(dstInfo, NULL, dstInfo.minRowBytes(), opts) != kSuccess) {
scroggo230d4ac2015-03-26 07:15:55 -0700635 SkCodecPrintf("failed to initialize the swizzler.\n");
scroggo05245902015-03-25 11:11:52 -0700636 return NULL;
637 }
638
639 SkASSERT(fNumberPasses != INVALID_NUMBER_PASSES);
640 if (fNumberPasses > 1) {
641 // We cannot efficiently do scanline decoding.
642 return NULL;
643 }
644
645 return SkNEW_ARGS(SkPngScanlineDecoder, (dstInfo, this));
646}
647