blob: 8e7ee33a9554bce341cf8681b2db86d334bfae1b [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"
9#include "SkColorPriv.h"
10#include "SkColorTable.h"
11#include "SkBitmap.h"
12#include "SkMath.h"
13#include "SkSize.h"
14#include "SkStream.h"
15#include "SkSwizzler.h"
16
17///////////////////////////////////////////////////////////////////////////////
18// Helper macros
19///////////////////////////////////////////////////////////////////////////////
20
21#ifndef png_jmpbuf
22# define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
23#endif
24
25/* These were dropped in libpng >= 1.4 */
26#ifndef png_infopp_NULL
27 #define png_infopp_NULL NULL
28#endif
29
30#ifndef png_bytepp_NULL
31 #define png_bytepp_NULL NULL
32#endif
33
34#ifndef int_p_NULL
35 #define int_p_NULL NULL
36#endif
37
38#ifndef png_flush_ptr_NULL
39 #define png_flush_ptr_NULL NULL
40#endif
41
42///////////////////////////////////////////////////////////////////////////////
43// Callback functions
44///////////////////////////////////////////////////////////////////////////////
45
46static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
47 SkDebugf("------ png error %s\n", msg);
48 longjmp(png_jmpbuf(png_ptr), 1);
49}
50
51static void sk_read_fn(png_structp png_ptr, png_bytep data,
52 png_size_t length) {
53 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
54 const size_t bytes = stream->read(data, length);
55 if (bytes != length) {
56 // FIXME: We want to report the fact that the stream was truncated.
57 // One way to do that might be to pass a enum to longjmp so setjmp can
58 // specify the failure.
59 png_error(png_ptr, "Read Error!");
60 }
61}
62
63///////////////////////////////////////////////////////////////////////////////
64// Helpers
65///////////////////////////////////////////////////////////////////////////////
66
67class AutoCleanPng : public SkNoncopyable {
68public:
69 AutoCleanPng(png_structp png_ptr)
70 : fPng_ptr(png_ptr)
71 , fInfo_ptr(NULL) {}
72
73 ~AutoCleanPng() {
74 // fInfo_ptr will never be non-NULL unless fPng_ptr is.
75 if (fPng_ptr) {
76 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : NULL;
77 png_destroy_read_struct(&fPng_ptr, info_pp, png_infopp_NULL);
78 }
79 }
80
81 void setInfoPtr(png_infop info_ptr) {
82 SkASSERT(NULL == fInfo_ptr);
83 fInfo_ptr = info_ptr;
84 }
85
86 void detach() {
87 fPng_ptr = NULL;
88 fInfo_ptr = NULL;
89 }
90
91private:
92 png_structp fPng_ptr;
93 png_infop fInfo_ptr;
94};
95#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
96
97// call only if color_type is PALETTE. Returns true if the ctable has alpha
98static bool has_transparency_in_palette(png_structp png_ptr,
99 png_infop info_ptr) {
100 if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
101 return false;
102 }
103
104 png_bytep trans;
105 int num_trans;
106 png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL);
107 return num_trans > 0;
108}
109
110// Method for coverting to either an SkPMColor or a similarly packed
111// unpremultiplied color.
112typedef uint32_t (*PackColorProc)(U8CPU a, U8CPU r, U8CPU g, U8CPU b);
113
114// Note: SkColorTable claims to store SkPMColors, which is not necessarily
115// the case here.
116SkColorTable* decode_palette(png_structp png_ptr, png_infop info_ptr,
117 bool premultiply, SkAlphaType* outAlphaType) {
118 SkASSERT(outAlphaType != NULL);
119 int numPalette;
120 png_colorp palette;
121 png_bytep trans;
122
123 if (!png_get_PLTE(png_ptr, info_ptr, &palette, &numPalette)) {
124 return NULL;
125 }
126
127 /* BUGGY IMAGE WORKAROUND
128
129 We hit some images (e.g. fruit_.png) who contain bytes that are == colortable_count
130 which is a problem since we use the byte as an index. To work around this we grow
131 the colortable by 1 (if its < 256) and duplicate the last color into that slot.
132 */
133 const int colorCount = numPalette + (numPalette < 256);
134 // Note: These are not necessarily SkPMColors.
135 SkPMColor colorStorage[256]; // worst-case storage
136 SkPMColor* colorPtr = colorStorage;
137
138 int numTrans;
139 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
140 png_get_tRNS(png_ptr, info_ptr, &trans, &numTrans, NULL);
141 } else {
142 numTrans = 0;
143 }
144
145 // check for bad images that might make us crash
146 if (numTrans > numPalette) {
147 numTrans = numPalette;
148 }
149
150 int index = 0;
151 int transLessThanFF = 0;
152
153 // Choose which function to use to create the color table. If the final destination's
154 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
155 PackColorProc proc;
156 if (premultiply) {
157 proc = &SkPreMultiplyARGB;
158 } else {
159 proc = &SkPackARGB32NoCheck;
160 }
161 for (; index < numTrans; index++) {
162 transLessThanFF |= (int)*trans - 0xFF;
163 *colorPtr++ = proc(*trans++, palette->red, palette->green, palette->blue);
164 palette++;
165 }
166
167 if (transLessThanFF < 0) {
168 *outAlphaType = premultiply ? kPremul_SkAlphaType : kUnpremul_SkAlphaType;
169 } else {
170 *outAlphaType = kOpaque_SkAlphaType;
171 }
172
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
183 return SkNEW_ARGS(SkColorTable, (colorStorage, colorCount));
184}
185
186///////////////////////////////////////////////////////////////////////////////
187// Creation
188///////////////////////////////////////////////////////////////////////////////
189
190#define PNG_BYTES_TO_CHECK 4
191
192bool SkPngCodec::IsPng(SkStream* stream) {
193 char buf[PNG_BYTES_TO_CHECK];
194 if (stream->read(buf, PNG_BYTES_TO_CHECK) != PNG_BYTES_TO_CHECK) {
195 return false;
196 }
197 if (png_sig_cmp((png_bytep) buf, (png_size_t)0, PNG_BYTES_TO_CHECK)) {
198 return false;
199 }
200 return true;
201}
202
203SkCodec* SkPngCodec::NewFromStream(SkStream* stream) {
204 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
205 // FIXME: Allow silencing warnings.
206 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,
207 sk_error_fn, NULL);
208 if (!png_ptr) {
209 return NULL;
210 }
211
212 AutoCleanPng autoClean(png_ptr);
213
214 png_infop info_ptr = png_create_info_struct(png_ptr);
215 if (info_ptr == NULL) {
216 return NULL;
217 }
218
219 autoClean.setInfoPtr(info_ptr);
220
221 // FIXME: Could we use the return value of setjmp to specify the type of
222 // error?
223 if (setjmp(png_jmpbuf(png_ptr))) {
224 return NULL;
225 }
226
227 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
228
229 // FIXME: This is where the old code hooks up the Peeker. Does it need to
230 // be set this early? (i.e. where are the user chunks? early in the stream,
231 // potentially?)
232 // If it does, we need to figure out a way to set it here.
233
234 // The call to png_read_info() gives us all of the information from the
235 // PNG file before the first IDAT (image data chunk).
236 png_read_info(png_ptr, info_ptr);
237 png_uint_32 origWidth, origHeight;
238 int bitDepth, colorType;
239 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
240 &colorType, int_p_NULL, int_p_NULL, int_p_NULL);
241
242 // sanity check for size
243 {
244 int64_t size = sk_64_mul(origWidth, origHeight);
245 // now check that if we are 4-bytes per pixel, we also don't overflow
246 if (size < 0 || size > (0x7FFFFFFF >> 2)) {
247 return NULL;
248 }
249 }
250
251 // Tell libpng to strip 16 bit/color files down to 8 bits/color
252 if (bitDepth == 16) {
253 png_set_strip_16(png_ptr);
254 }
255#ifdef PNG_READ_PACK_SUPPORTED
256 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
257 // byte into separate bytes (useful for paletted and grayscale images).
258 if (bitDepth < 8) {
259 png_set_packing(png_ptr);
260 }
261#endif
262 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
263 if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) {
264 png_set_expand_gray_1_2_4_to_8(png_ptr);
265 }
266
267
268 // Now determine the default SkColorType and SkAlphaType.
269 SkColorType skColorType;
270 SkAlphaType skAlphaType;
271 switch (colorType) {
272 case PNG_COLOR_TYPE_PALETTE:
273 // Technically, this is true of the data, but I don't think we want
274 // to support it.
275 // skColorType = kIndex8_SkColorType;
276 skColorType = kN32_SkColorType;
277 skAlphaType = has_transparency_in_palette(png_ptr, info_ptr) ?
278 kUnpremul_SkAlphaType : kOpaque_SkAlphaType;
279 break;
280 case PNG_COLOR_TYPE_GRAY:
281 if (false) {
282 // FIXME: Is this the wrong default behavior? This means if the
283 // caller supplies the info we gave them, they'll get Alpha 8.
284 skColorType = kAlpha_8_SkColorType;
285 // FIXME: Strangely, the canonical type for Alpha 8 is Premul.
286 skAlphaType = kPremul_SkAlphaType;
287 } else {
288 skColorType = kN32_SkColorType;
289 skAlphaType = kOpaque_SkAlphaType;
290 }
291 break;
292 default:
293 // Note: This *almost* mimics the code in SkImageDecoder_libpng.
294 // has_transparency_in_palette makes an additional check - whether
295 // numTrans is greater than 0. Why does the other code not make that
296 // check?
297 if (has_transparency_in_palette(png_ptr, info_ptr)
298 || PNG_COLOR_TYPE_RGB_ALPHA == colorType
299 || PNG_COLOR_TYPE_GRAY_ALPHA == colorType)
300 {
301 skAlphaType = kUnpremul_SkAlphaType;
302 } else {
303 skAlphaType = kOpaque_SkAlphaType;
304 }
305 skColorType = kN32_SkColorType;
306 break;
307 }
308
309 {
310 // FIXME: Again, this block needs to go into onGetPixels.
311 bool convertGrayToRGB = PNG_COLOR_TYPE_GRAY == colorType && skColorType != kAlpha_8_SkColorType;
312
313 // Unless the user is requesting A8, convert a grayscale image into RGB.
314 // GRAY_ALPHA will always be converted to RGB
315 if (convertGrayToRGB || colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
316 png_set_gray_to_rgb(png_ptr);
317 }
318
319 // Add filler (or alpha) byte (after each RGB triplet) if necessary.
320 // FIXME: It seems like we could just use RGB as the SrcConfig here.
321 if (colorType == PNG_COLOR_TYPE_RGB || convertGrayToRGB) {
322 png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
323 }
324 }
325
326 // FIXME: Also need to check for sRGB (skbug.com/3471).
327
328 SkImageInfo info = SkImageInfo::Make(origWidth, origHeight, skColorType,
329 skAlphaType);
330 SkCodec* codec = SkNEW_ARGS(SkPngCodec, (info, stream, png_ptr, info_ptr));
331 autoClean.detach();
332 return codec;
333}
334
335SkPngCodec::SkPngCodec(const SkImageInfo& info, SkStream* stream,
336 png_structp png_ptr, png_infop info_ptr)
337 : INHERITED(info, stream)
338 , fPng_ptr(png_ptr)
339 , fInfo_ptr(info_ptr) {}
340
341SkPngCodec::~SkPngCodec() {
342 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, png_infopp_NULL);
343}
344
345///////////////////////////////////////////////////////////////////////////////
346// Getting the pixels
347///////////////////////////////////////////////////////////////////////////////
348
349static bool premul_and_unpremul(SkAlphaType A, SkAlphaType B) {
350 return kPremul_SkAlphaType == A && kUnpremul_SkAlphaType == B;
351}
352
353static bool conversion_possible(const SkImageInfo& A, const SkImageInfo& B) {
354 // TODO: Support other conversions
355 if (A.colorType() != B.colorType()) {
356 return false;
357 }
358 if (A.profileType() != B.profileType()) {
359 return false;
360 }
361 if (A.alphaType() == B.alphaType()) {
362 return true;
363 }
364 return premul_and_unpremul(A.alphaType(), B.alphaType())
365 || premul_and_unpremul(B.alphaType(), A.alphaType());
366}
367
368SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& requestedInfo, void* dst,
369 size_t rowBytes, SkPMColor ctable[],
370 int* ctableCount) {
371 if (!this->rewindIfNeeded()) {
372 return kCouldNotRewind;
373 }
374 if (requestedInfo.dimensions() != this->getOriginalInfo().dimensions()) {
375 return kInvalidScale;
376 }
377 if (!conversion_possible(requestedInfo, this->getOriginalInfo())) {
378 return kInvalidConversion;
379 }
380
381 SkBitmap decodedBitmap;
382 // If installPixels would have failed, getPixels should have failed before
383 // calling onGetPixels.
384 SkAssertResult(decodedBitmap.installPixels(requestedInfo, dst, rowBytes));
385
386 // Initialize all non-trivial objects before setjmp.
387 SkAutoTUnref<SkColorTable> colorTable;
388 SkAutoTDelete<SkSwizzler> swizzler;
389 SkAutoMalloc storage; // Scratch memory for pre-swizzled rows.
390
391 // FIXME: Could we use the return value of setjmp to specify the type of
392 // error?
393 if (setjmp(png_jmpbuf(fPng_ptr))) {
394 SkDebugf("setjmp long jump!\n");
395 return kInvalidInput;
396 }
397
398 // FIXME: We already retrieved this information. Store it in SkPngCodec?
399 png_uint_32 origWidth, origHeight;
400 int bitDepth, pngColorType, interlaceType;
401 png_get_IHDR(fPng_ptr, fInfo_ptr, &origWidth, &origHeight, &bitDepth,
402 &pngColorType, &interlaceType, int_p_NULL, int_p_NULL);
403
404 const int numberPasses = (interlaceType != PNG_INTERLACE_NONE) ?
405 png_set_interlace_handling(fPng_ptr) : 1;
406
407 SkSwizzler::SrcConfig sc;
408 bool reallyHasAlpha = false;
409 if (PNG_COLOR_TYPE_PALETTE == pngColorType) {
410 sc = SkSwizzler::kIndex;
411 SkAlphaType at = requestedInfo.alphaType();
412 colorTable.reset(decode_palette(fPng_ptr, fInfo_ptr,
413 kPremul_SkAlphaType == at,
414 &at));
415 if (!colorTable) {
416 return kInvalidInput;
417 }
418
419 reallyHasAlpha = (at != kOpaque_SkAlphaType);
420
421 if (at != requestedInfo.alphaType()) {
422 // It turns out the image is opaque.
423 SkASSERT(kOpaque_SkAlphaType == at);
424 }
425 } else if (kAlpha_8_SkColorType == requestedInfo.colorType()) {
426 // Note: we check the destination, since otherwise we would have
427 // told png to upscale.
428 SkASSERT(PNG_COLOR_TYPE_GRAY == pngColorType);
429 sc = SkSwizzler::kGray;
430 } else if (this->getOriginalInfo().alphaType() == kOpaque_SkAlphaType) {
431 sc = SkSwizzler::kRGBX;
432 } else {
433 sc = SkSwizzler::kRGBA;
434 }
435 const SkPMColor* colors = colorTable ? colorTable->readColors() : NULL;
436 // TODO: Support skipZeroes.
437 swizzler.reset(SkSwizzler::CreateSwizzler(sc, colors, requestedInfo,
438 dst, rowBytes, false));
439 if (!swizzler) {
440 // FIXME: CreateSwizzler could fail for another reason.
441 return kUnimplemented;
442 }
443
444 // FIXME: Here is where we should likely insert some of the modifications
445 // made in the factory.
446 png_read_update_info(fPng_ptr, fInfo_ptr);
447
448 if (numberPasses > 1) {
449 const int width = requestedInfo.width();
450 const int height = requestedInfo.height();
451 const int bpp = SkSwizzler::BytesPerPixel(sc);
452 const size_t rowBytes = width * bpp;
453
454 storage.reset(width * height * bpp);
455 uint8_t* const base = static_cast<uint8_t*>(storage.get());
456
457 for (int i = 0; i < numberPasses; i++) {
458 uint8_t* row = base;
459 for (int y = 0; y < height; y++) {
460 uint8_t* bmRow = row;
461 png_read_rows(fPng_ptr, &bmRow, png_bytepp_NULL, 1);
462 row += rowBytes;
463 }
464 }
465
466 // Now swizzle it.
467 uint8_t* row = base;
468 for (int y = 0; y < height; y++) {
469 reallyHasAlpha |= swizzler->next(row);
470 row += rowBytes;
471 }
472 } else {
473 storage.reset(requestedInfo.width() * SkSwizzler::BytesPerPixel(sc));
474 uint8_t* srcRow = static_cast<uint8_t*>(storage.get());
475 for (int y = 0; y < requestedInfo.height(); y++) {
476 png_read_rows(fPng_ptr, &srcRow, png_bytepp_NULL, 1);
477 reallyHasAlpha |= swizzler->next(srcRow);
478 }
479 }
480
481 /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
482 png_read_end(fPng_ptr, fInfo_ptr);
483
484 // FIXME: do we need substituteTranspColor?
485
486 if (reallyHasAlpha && requestedInfo.alphaType() != kOpaque_SkAlphaType) {
487 // FIXME: We want to alert the caller. Is this the right way?
488 SkImageInfo* modInfo = const_cast<SkImageInfo*>(&requestedInfo);
489 *modInfo = requestedInfo.makeAlphaType(kOpaque_SkAlphaType);
490 }
491 return kSuccess;
492}