blob: 33111cee67841938335fd6f7b0862d5f9ec0a9c6 [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) {
349 png_structp png_ptr;
350 png_infop info_ptr;
351 SkImageInfo imageInfo;
352 if (read_header(stream, &png_ptr, &info_ptr, &imageInfo)) {
353 return SkNEW_ARGS(SkPngCodec, (imageInfo, stream, png_ptr, info_ptr));
354 }
355 return NULL;
scroggof24f2242015-03-03 08:59:20 -0800356}
357
scroggo05245902015-03-25 11:11:52 -0700358#define INVALID_NUMBER_PASSES -1
scroggof24f2242015-03-03 08:59:20 -0800359SkPngCodec::SkPngCodec(const SkImageInfo& info, SkStream* stream,
360 png_structp png_ptr, png_infop info_ptr)
361 : INHERITED(info, stream)
362 , fPng_ptr(png_ptr)
scroggo05245902015-03-25 11:11:52 -0700363 , fInfo_ptr(info_ptr)
364 , fSrcConfig(SkSwizzler::kUnknown)
365 , fNumberPasses(INVALID_NUMBER_PASSES)
366 , fReallyHasAlpha(false)
367{}
scroggof24f2242015-03-03 08:59:20 -0800368
369SkPngCodec::~SkPngCodec() {
scroggo3eada2a2015-04-01 09:33:23 -0700370 this->destroyReadStruct();
371}
372
373void SkPngCodec::destroyReadStruct() {
374 if (fPng_ptr) {
375 // We will never have a NULL fInfo_ptr with a non-NULL fPng_ptr
376 SkASSERT(fInfo_ptr);
377 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, png_infopp_NULL);
378 fPng_ptr = NULL;
379 fInfo_ptr = NULL;
380 }
scroggof24f2242015-03-03 08:59:20 -0800381}
382
383///////////////////////////////////////////////////////////////////////////////
384// Getting the pixels
385///////////////////////////////////////////////////////////////////////////////
386
msaretteed039b2015-03-18 11:11:19 -0700387static bool conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
scroggof24f2242015-03-03 08:59:20 -0800388 // TODO: Support other conversions
msaretteed039b2015-03-18 11:11:19 -0700389 if (dst.colorType() != src.colorType()) {
scroggof24f2242015-03-03 08:59:20 -0800390 return false;
391 }
msaretteed039b2015-03-18 11:11:19 -0700392 if (dst.profileType() != src.profileType()) {
scroggof24f2242015-03-03 08:59:20 -0800393 return false;
394 }
msaretteed039b2015-03-18 11:11:19 -0700395 if (dst.alphaType() == src.alphaType()) {
scroggof24f2242015-03-03 08:59:20 -0800396 return true;
397 }
msaretteed039b2015-03-18 11:11:19 -0700398 return kPremul_SkAlphaType == dst.alphaType() &&
399 kUnpremul_SkAlphaType == src.alphaType();
scroggof24f2242015-03-03 08:59:20 -0800400}
401
scroggo05245902015-03-25 11:11:52 -0700402SkCodec::Result SkPngCodec::initializeSwizzler(const SkImageInfo& requestedInfo,
403 void* dst, size_t rowBytes,
404 const Options& options) {
scroggof24f2242015-03-03 08:59:20 -0800405 // FIXME: Could we use the return value of setjmp to specify the type of
406 // error?
407 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700408 SkCodecPrintf("setjmp long jump!\n");
scroggof24f2242015-03-03 08:59:20 -0800409 return kInvalidInput;
410 }
411
412 // FIXME: We already retrieved this information. Store it in SkPngCodec?
413 png_uint_32 origWidth, origHeight;
414 int bitDepth, pngColorType, interlaceType;
415 png_get_IHDR(fPng_ptr, fInfo_ptr, &origWidth, &origHeight, &bitDepth,
416 &pngColorType, &interlaceType, int_p_NULL, int_p_NULL);
417
scroggo05245902015-03-25 11:11:52 -0700418 fNumberPasses = (interlaceType != PNG_INTERLACE_NONE) ?
scroggof24f2242015-03-03 08:59:20 -0800419 png_set_interlace_handling(fPng_ptr) : 1;
420
scroggo05245902015-03-25 11:11:52 -0700421 // Set to the default before calling decodePalette, which may change it.
422 fReallyHasAlpha = false;
scroggof24f2242015-03-03 08:59:20 -0800423 if (PNG_COLOR_TYPE_PALETTE == pngColorType) {
scroggo05245902015-03-25 11:11:52 -0700424 fSrcConfig = SkSwizzler::kIndex;
425 if (!this->decodePalette(kPremul_SkAlphaType == requestedInfo.alphaType())) {
scroggof24f2242015-03-03 08:59:20 -0800426 return kInvalidInput;
427 }
scroggof24f2242015-03-03 08:59:20 -0800428 } else if (kAlpha_8_SkColorType == requestedInfo.colorType()) {
429 // Note: we check the destination, since otherwise we would have
430 // told png to upscale.
431 SkASSERT(PNG_COLOR_TYPE_GRAY == pngColorType);
scroggo05245902015-03-25 11:11:52 -0700432 fSrcConfig = SkSwizzler::kGray;
msarett9bde9182015-03-25 05:27:48 -0700433 } else if (this->getInfo().alphaType() == kOpaque_SkAlphaType) {
scroggo05245902015-03-25 11:11:52 -0700434 fSrcConfig = SkSwizzler::kRGBX;
scroggof24f2242015-03-03 08:59:20 -0800435 } else {
scroggo05245902015-03-25 11:11:52 -0700436 fSrcConfig = SkSwizzler::kRGBA;
scroggof24f2242015-03-03 08:59:20 -0800437 }
scroggo05245902015-03-25 11:11:52 -0700438 const SkPMColor* colors = fColorTable ? fColorTable->readColors() : NULL;
439 fSwizzler.reset(SkSwizzler::CreateSwizzler(fSrcConfig, colors, requestedInfo,
440 dst, rowBytes, options.fZeroInitialized));
441 if (!fSwizzler) {
scroggof24f2242015-03-03 08:59:20 -0800442 // FIXME: CreateSwizzler could fail for another reason.
443 return kUnimplemented;
444 }
445
446 // FIXME: Here is where we should likely insert some of the modifications
447 // made in the factory.
448 png_read_update_info(fPng_ptr, fInfo_ptr);
449
scroggo05245902015-03-25 11:11:52 -0700450 return kSuccess;
451}
452
scroggo58421542015-04-01 11:25:20 -0700453bool SkPngCodec::handleRewind() {
454 switch (this->rewindIfNeeded()) {
455 case kNoRewindNecessary_RewindState:
456 return true;
457 case kCouldNotRewind_RewindState:
458 return false;
459 case kRewound_RewindState: {
460 // This sets fPng_ptr and fInfo_ptr to NULL. If read_header
461 // succeeds, they will be repopulated, and if it fails, they will
462 // remain NULL. Any future accesses to fPng_ptr and fInfo_ptr will
463 // come through this function which will rewind and again attempt
464 // to reinitialize them.
465 this->destroyReadStruct();
466 png_structp png_ptr;
467 png_infop info_ptr;
468 if (read_header(this->stream(), &png_ptr, &info_ptr, NULL)) {
469 fPng_ptr = png_ptr;
470 fInfo_ptr = info_ptr;
471 return true;
472 }
473 return false;
474 }
475 default:
476 SkASSERT(false);
477 return false;
478 }
479}
480
scroggo05245902015-03-25 11:11:52 -0700481SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
482 size_t rowBytes, const Options& options,
483 SkPMColor ctable[], int* ctableCount) {
scroggo58421542015-04-01 11:25:20 -0700484 if (!this->handleRewind()) {
halcanarya096d7a2015-03-27 12:16:53 -0700485 return kCouldNotRewind;
scroggo05245902015-03-25 11:11:52 -0700486 }
487 if (requestedInfo.dimensions() != this->getInfo().dimensions()) {
488 return kInvalidScale;
489 }
490 if (!conversion_possible(requestedInfo, this->getInfo())) {
491 return kInvalidConversion;
492 }
493
494 const Result result = this->initializeSwizzler(requestedInfo, dst, rowBytes,
495 options);
496 if (result != kSuccess) {
497 return result;
498 }
499
500 // FIXME: Could we use the return value of setjmp to specify the type of
501 // error?
502 if (setjmp(png_jmpbuf(fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700503 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700504 return kInvalidInput;
505 }
506
507 SkASSERT(fNumberPasses != INVALID_NUMBER_PASSES);
508 SkAutoMalloc storage;
509 if (fNumberPasses > 1) {
scroggof24f2242015-03-03 08:59:20 -0800510 const int width = requestedInfo.width();
511 const int height = requestedInfo.height();
scroggo05245902015-03-25 11:11:52 -0700512 const int bpp = SkSwizzler::BytesPerPixel(fSrcConfig);
scroggof24f2242015-03-03 08:59:20 -0800513 const size_t rowBytes = width * bpp;
514
515 storage.reset(width * height * bpp);
516 uint8_t* const base = static_cast<uint8_t*>(storage.get());
517
scroggo05245902015-03-25 11:11:52 -0700518 for (int i = 0; i < fNumberPasses; i++) {
scroggof24f2242015-03-03 08:59:20 -0800519 uint8_t* row = base;
520 for (int y = 0; y < height; y++) {
521 uint8_t* bmRow = row;
522 png_read_rows(fPng_ptr, &bmRow, png_bytepp_NULL, 1);
523 row += rowBytes;
524 }
525 }
526
527 // Now swizzle it.
528 uint8_t* row = base;
529 for (int y = 0; y < height; y++) {
scroggo05245902015-03-25 11:11:52 -0700530 fReallyHasAlpha |= !SkSwizzler::IsOpaque(fSwizzler->next(row));
scroggof24f2242015-03-03 08:59:20 -0800531 row += rowBytes;
532 }
533 } else {
scroggo05245902015-03-25 11:11:52 -0700534 storage.reset(requestedInfo.width() * SkSwizzler::BytesPerPixel(fSrcConfig));
scroggof24f2242015-03-03 08:59:20 -0800535 uint8_t* srcRow = static_cast<uint8_t*>(storage.get());
536 for (int y = 0; y < requestedInfo.height(); y++) {
537 png_read_rows(fPng_ptr, &srcRow, png_bytepp_NULL, 1);
scroggo05245902015-03-25 11:11:52 -0700538 fReallyHasAlpha |= !SkSwizzler::IsOpaque(fSwizzler->next(srcRow));
scroggof24f2242015-03-03 08:59:20 -0800539 }
540 }
541
scroggo05245902015-03-25 11:11:52 -0700542 // FIXME: do we need substituteTranspColor? Note that we cannot do it for
543 // scanline decoding, but we could do it here. Alternatively, we could do
544 // it as we go, instead of in post-processing like SkPNGImageDecoder.
scroggof24f2242015-03-03 08:59:20 -0800545
scroggo05245902015-03-25 11:11:52 -0700546 this->finish();
scroggof24f2242015-03-03 08:59:20 -0800547 return kSuccess;
548}
scroggo05245902015-03-25 11:11:52 -0700549
550void SkPngCodec::finish() {
551 if (setjmp(png_jmpbuf(fPng_ptr))) {
552 // We've already read all the scanlines. This is a success.
553 return;
554 }
555 /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
556 png_read_end(fPng_ptr, fInfo_ptr);
557}
558
559class SkPngScanlineDecoder : public SkScanlineDecoder {
560public:
561 SkPngScanlineDecoder(const SkImageInfo& dstInfo, SkPngCodec* codec)
562 : INHERITED(dstInfo)
563 , fCodec(codec)
564 , fHasAlpha(false)
565 {
566 fStorage.reset(dstInfo.width() * SkSwizzler::BytesPerPixel(fCodec->fSrcConfig));
567 fSrcRow = static_cast<uint8_t*>(fStorage.get());
568 }
569
mtklein36352bf2015-03-25 18:17:31 -0700570 SkImageGenerator::Result onGetScanlines(void* dst, int count, size_t rowBytes) override {
scroggo05245902015-03-25 11:11:52 -0700571 if (setjmp(png_jmpbuf(fCodec->fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700572 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700573 return SkImageGenerator::kInvalidInput;
574 }
575
576 for (int i = 0; i < count; i++) {
577 png_read_rows(fCodec->fPng_ptr, &fSrcRow, png_bytepp_NULL, 1);
578 fCodec->fSwizzler->setDstRow(dst);
579 fHasAlpha |= !SkSwizzler::IsOpaque(fCodec->fSwizzler->next(fSrcRow));
580 dst = SkTAddOffset<void>(dst, rowBytes);
581 }
582 return SkImageGenerator::kSuccess;
583 }
584
mtklein36352bf2015-03-25 18:17:31 -0700585 SkImageGenerator::Result onSkipScanlines(int count) override {
scroggo05245902015-03-25 11:11:52 -0700586 // FIXME: Could we use the return value of setjmp to specify the type of
587 // error?
588 if (setjmp(png_jmpbuf(fCodec->fPng_ptr))) {
scroggo230d4ac2015-03-26 07:15:55 -0700589 SkCodecPrintf("setjmp long jump!\n");
scroggo05245902015-03-25 11:11:52 -0700590 return SkImageGenerator::kInvalidInput;
591 }
592
593 png_read_rows(fCodec->fPng_ptr, png_bytepp_NULL, png_bytepp_NULL, count);
594 return SkImageGenerator::kSuccess;
595 }
596
mtklein36352bf2015-03-25 18:17:31 -0700597 void onFinish() override {
scroggo05245902015-03-25 11:11:52 -0700598 fCodec->finish();
599 }
600
mtklein36352bf2015-03-25 18:17:31 -0700601 bool onReallyHasAlpha() const override { return fHasAlpha; }
scroggo05245902015-03-25 11:11:52 -0700602
603private:
604 SkPngCodec* fCodec; // Unowned.
605 bool fHasAlpha;
606 SkAutoMalloc fStorage;
607 uint8_t* fSrcRow;
608
609 typedef SkScanlineDecoder INHERITED;
610};
611
612SkScanlineDecoder* SkPngCodec::onGetScanlineDecoder(const SkImageInfo& dstInfo) {
scroggo58421542015-04-01 11:25:20 -0700613 if (!this->handleRewind()) {
614 return NULL;
615 }
616
scroggo05245902015-03-25 11:11:52 -0700617 // Check to see if scaling was requested.
618 if (dstInfo.dimensions() != this->getInfo().dimensions()) {
619 return NULL;
620 }
621
622 if (!conversion_possible(dstInfo, this->getInfo())) {
scroggo230d4ac2015-03-26 07:15:55 -0700623 SkCodecPrintf("no conversion possible\n");
scroggo05245902015-03-25 11:11:52 -0700624 return NULL;
625 }
626
627 // Note: We set dst to NULL since we do not know it yet. rowBytes is not needed,
628 // since we'll be manually updating the dstRow, but the SkSwizzler requires it to
629 // be at least dstInfo.minRowBytes.
630 Options opts;
631 // FIXME: Pass this in to getScanlineDecoder?
632 opts.fZeroInitialized = kNo_ZeroInitialized;
633 if (this->initializeSwizzler(dstInfo, NULL, dstInfo.minRowBytes(), opts) != kSuccess) {
scroggo230d4ac2015-03-26 07:15:55 -0700634 SkCodecPrintf("failed to initialize the swizzler.\n");
scroggo05245902015-03-25 11:11:52 -0700635 return NULL;
636 }
637
638 SkASSERT(fNumberPasses != INVALID_NUMBER_PASSES);
639 if (fNumberPasses > 1) {
640 // We cannot efficiently do scanline decoding.
641 return NULL;
642 }
643
644 return SkNEW_ARGS(SkPngScanlineDecoder, (dstInfo, this));
645}
646