1 /*
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 "SkBitmap.h"
9 #include "SkCodecPriv.h"
10 #include "SkColorPriv.h"
11 #include "SkColorSpace.h"
12 #include "SkColorSpacePriv.h"
13 #include "SkColorTable.h"
14 #include "SkMath.h"
15 #include "SkOpts.h"
16 #include "SkPngCodec.h"
17 #include "SkPoint3.h"
18 #include "SkSize.h"
19 #include "SkStream.h"
20 #include "SkSwizzler.h"
21 #include "SkTemplates.h"
22 #include "SkUtils.h"
23
24 #include "png.h"
25 #include <algorithm>
26
27 // This warning triggers false postives way too often in here.
28 #if defined(__GNUC__) && !defined(__clang__)
29 #pragma GCC diagnostic ignored "-Wclobbered"
30 #endif
31
32 // FIXME (scroggo): We can use png_jumpbuf directly once Google3 is on 1.6
33 #define PNG_JMPBUF(x) png_jmpbuf((png_structp) x)
34
35 ///////////////////////////////////////////////////////////////////////////////
36 // Callback functions
37 ///////////////////////////////////////////////////////////////////////////////
38
39 // When setjmp is first called, it returns 0, meaning longjmp was not called.
40 constexpr int kSetJmpOkay = 0;
41 // An error internal to libpng.
42 constexpr int kPngError = 1;
43 // Passed to longjmp when we have decoded as many lines as we need.
44 constexpr int kStopDecoding = 2;
45
sk_error_fn(png_structp png_ptr,png_const_charp msg)46 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
47 SkCodecPrintf("------ png error %s\n", msg);
48 longjmp(PNG_JMPBUF(png_ptr), kPngError);
49 }
50
sk_warning_fn(png_structp,png_const_charp msg)51 void sk_warning_fn(png_structp, png_const_charp msg) {
52 SkCodecPrintf("----- png warning %s\n", msg);
53 }
54
55 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
sk_read_user_chunk(png_structp png_ptr,png_unknown_chunkp chunk)56 static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
57 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(png_ptr);
58 // readChunk() returning true means continue decoding
59 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk->size) ? 1 : -1;
60 }
61 #endif
62
63 ///////////////////////////////////////////////////////////////////////////////
64 // Helpers
65 ///////////////////////////////////////////////////////////////////////////////
66
67 class AutoCleanPng : public SkNoncopyable {
68 public:
69 /*
70 * This class does not take ownership of stream or reader, but if codecPtr
71 * is non-NULL, and decodeBounds succeeds, it will have created a new
72 * SkCodec (pointed to by *codecPtr) which will own/ref them, as well as
73 * the png_ptr and info_ptr.
74 */
AutoCleanPng(png_structp png_ptr,SkStream * stream,SkPngChunkReader * reader,SkCodec ** codecPtr)75 AutoCleanPng(png_structp png_ptr, SkStream* stream, SkPngChunkReader* reader,
76 SkCodec** codecPtr)
77 : fPng_ptr(png_ptr)
78 , fInfo_ptr(nullptr)
79 , fStream(stream)
80 , fChunkReader(reader)
81 , fOutCodec(codecPtr)
82 {}
83
~AutoCleanPng()84 ~AutoCleanPng() {
85 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
86 if (fPng_ptr) {
87 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
88 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
89 }
90 }
91
setInfoPtr(png_infop info_ptr)92 void setInfoPtr(png_infop info_ptr) {
93 SkASSERT(nullptr == fInfo_ptr);
94 fInfo_ptr = info_ptr;
95 }
96
97 /**
98 * Reads enough of the input stream to decode the bounds.
99 * @return false if the stream is not a valid PNG (or too short).
100 * true if it read enough of the stream to determine the bounds.
101 * In the latter case, the stream may have been read beyond the
102 * point to determine the bounds, and the png_ptr will have saved
103 * any extra data. Further, if the codecPtr supplied to the
104 * constructor was not NULL, it will now point to a new SkCodec,
105 * which owns (or refs, in the case of the SkPngChunkReader) the
106 * inputs. If codecPtr was NULL, the png_ptr and info_ptr are
107 * unowned, and it is up to the caller to destroy them.
108 */
109 bool decodeBounds();
110
111 private:
112 png_structp fPng_ptr;
113 png_infop fInfo_ptr;
114 SkStream* fStream;
115 SkPngChunkReader* fChunkReader;
116 SkCodec** fOutCodec;
117
118 void infoCallback(size_t idatLength);
119
releasePngPtrs()120 void releasePngPtrs() {
121 fPng_ptr = nullptr;
122 fInfo_ptr = nullptr;
123 }
124 };
125 #define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
126
is_chunk(const png_byte * chunk,const char * tag)127 static inline bool is_chunk(const png_byte* chunk, const char* tag) {
128 return memcmp(chunk + 4, tag, 4) == 0;
129 }
130
process_data(png_structp png_ptr,png_infop info_ptr,SkStream * stream,void * buffer,size_t bufferSize,size_t length)131 static inline bool process_data(png_structp png_ptr, png_infop info_ptr,
132 SkStream* stream, void* buffer, size_t bufferSize, size_t length) {
133 while (length > 0) {
134 const size_t bytesToProcess = std::min(bufferSize, length);
135 const size_t bytesRead = stream->read(buffer, bytesToProcess);
136 png_process_data(png_ptr, info_ptr, (png_bytep) buffer, bytesRead);
137 if (bytesRead < bytesToProcess) {
138 return false;
139 }
140 length -= bytesToProcess;
141 }
142 return true;
143 }
144
decodeBounds()145 bool AutoCleanPng::decodeBounds() {
146 if (setjmp(PNG_JMPBUF(fPng_ptr))) {
147 return false;
148 }
149
150 png_set_progressive_read_fn(fPng_ptr, nullptr, nullptr, nullptr, nullptr);
151
152 // Arbitrary buffer size, though note that it matches (below)
153 // SkPngCodec::processData(). FIXME: Can we better suit this to the size of
154 // the PNG header?
155 constexpr size_t kBufferSize = 4096;
156 char buffer[kBufferSize];
157
158 {
159 // Parse the signature.
160 if (fStream->read(buffer, 8) < 8) {
161 return false;
162 }
163
164 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, 8);
165 }
166
167 while (true) {
168 // Parse chunk length and type.
169 if (fStream->read(buffer, 8) < 8) {
170 // We have read to the end of the input without decoding bounds.
171 break;
172 }
173
174 png_byte* chunk = reinterpret_cast<png_byte*>(buffer);
175 const size_t length = png_get_uint_32(chunk);
176
177 if (is_chunk(chunk, "IDAT")) {
178 this->infoCallback(length);
179 return true;
180 }
181
182 png_process_data(fPng_ptr, fInfo_ptr, chunk, 8);
183 // Process the full chunk + CRC.
184 if (!process_data(fPng_ptr, fInfo_ptr, fStream, buffer, kBufferSize, length + 4)) {
185 return false;
186 }
187 }
188
189 return false;
190 }
191
processData()192 void SkPngCodec::processData() {
193 switch (setjmp(PNG_JMPBUF(fPng_ptr))) {
194 case kPngError:
195 // There was an error. Stop processing data.
196 // FIXME: Do we need to discard png_ptr?
197 return;
198 case kStopDecoding:
199 // We decoded all the lines we want.
200 return;
201 case kSetJmpOkay:
202 // Everything is okay.
203 break;
204 default:
205 // No other values should be passed to longjmp.
206 SkASSERT(false);
207 }
208
209 // Arbitrary buffer size
210 constexpr size_t kBufferSize = 4096;
211 char buffer[kBufferSize];
212
213 bool iend = false;
214 while (true) {
215 size_t length;
216 if (fDecodedIdat) {
217 // Parse chunk length and type.
218 if (this->stream()->read(buffer, 8) < 8) {
219 break;
220 }
221
222 png_byte* chunk = reinterpret_cast<png_byte*>(buffer);
223 png_process_data(fPng_ptr, fInfo_ptr, chunk, 8);
224 if (is_chunk(chunk, "IEND")) {
225 iend = true;
226 }
227
228 length = png_get_uint_32(chunk);
229 } else {
230 length = fIdatLength;
231 png_byte idat[] = {0, 0, 0, 0, 'I', 'D', 'A', 'T'};
232 png_save_uint_32(idat, length);
233 png_process_data(fPng_ptr, fInfo_ptr, idat, 8);
234 fDecodedIdat = true;
235 }
236
237 // Process the full chunk + CRC.
238 if (!process_data(fPng_ptr, fInfo_ptr, this->stream(), buffer, kBufferSize, length + 4)
239 || iend) {
240 break;
241 }
242 }
243 }
244
245 static const SkColorType kXformSrcColorType = kRGBA_8888_SkColorType;
246
247 // Note: SkColorTable claims to store SkPMColors, which is not necessarily the case here.
createColorTable(const SkImageInfo & dstInfo)248 bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo) {
249
250 int numColors;
251 png_color* palette;
252 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
253 return false;
254 }
255
256 // Contents depend on tableColorType and our choice of if/when to premultiply:
257 // { kPremul, kUnpremul, kOpaque } x { RGBA, BGRA }
258 SkPMColor colorTable[256];
259 SkColorType tableColorType = this->colorXform() ? kXformSrcColorType : dstInfo.colorType();
260
261 png_bytep alphas;
262 int numColorsWithAlpha = 0;
263 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
264 // If we are performing a color xform, it will handle the premultiply. Otherwise,
265 // we'll do it here.
266 bool premultiply = !this->colorXform() && needs_premul(dstInfo, this->getEncodedInfo());
267
268 // Choose which function to use to create the color table. If the final destination's
269 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
270 PackColorProc proc = choose_pack_color_proc(premultiply, tableColorType);
271
272 for (int i = 0; i < numColorsWithAlpha; i++) {
273 // We don't have a function in SkOpts that combines a set of alphas with a set
274 // of RGBs. We could write one, but it's hardly worth it, given that this
275 // is such a small fraction of the total decode time.
276 colorTable[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
277 palette++;
278 }
279 }
280
281 if (numColorsWithAlpha < numColors) {
282 // The optimized code depends on a 3-byte png_color struct with the colors
283 // in RGB order. These checks make sure it is safe to use.
284 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
285 #ifdef SK_DEBUG
286 SkASSERT(&palette->red < &palette->green);
287 SkASSERT(&palette->green < &palette->blue);
288 #endif
289
290 if (is_rgba(tableColorType)) {
291 SkOpts::RGB_to_RGB1(colorTable + numColorsWithAlpha, palette,
292 numColors - numColorsWithAlpha);
293 } else {
294 SkOpts::RGB_to_BGR1(colorTable + numColorsWithAlpha, palette,
295 numColors - numColorsWithAlpha);
296 }
297 }
298
299 if (this->colorXform() && !this->xformOnDecode()) {
300 this->applyColorXform(colorTable, colorTable, numColors);
301 }
302
303 // Pad the color table with the last color in the table (or black) in the case that
304 // invalid pixel indices exceed the number of colors in the table.
305 const int maxColors = 1 << fBitDepth;
306 if (numColors < maxColors) {
307 SkPMColor lastColor = numColors > 0 ? colorTable[numColors - 1] : SK_ColorBLACK;
308 sk_memset32(colorTable + numColors, lastColor, maxColors - numColors);
309 }
310
311 fColorTable.reset(new SkColorTable(colorTable, maxColors));
312 return true;
313 }
314
315 ///////////////////////////////////////////////////////////////////////////////
316 // Creation
317 ///////////////////////////////////////////////////////////////////////////////
318
IsPng(const char * buf,size_t bytesRead)319 bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
320 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
321 }
322
323 #if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
324
png_fixed_point_to_float(png_fixed_point x)325 static float png_fixed_point_to_float(png_fixed_point x) {
326 // We multiply by the same factor that libpng used to convert
327 // fixed point -> double. Since we want floats, we choose to
328 // do the conversion ourselves rather than convert
329 // fixed point -> double -> float.
330 return ((float) x) * 0.00001f;
331 }
332
png_inverted_fixed_point_to_float(png_fixed_point x)333 static float png_inverted_fixed_point_to_float(png_fixed_point x) {
334 // This is necessary because the gAMA chunk actually stores 1/gamma.
335 return 1.0f / png_fixed_point_to_float(x);
336 }
337
338 #endif // LIBPNG >= 1.6
339
340 // Returns a colorSpace object that represents any color space information in
341 // the encoded data. If the encoded data contains an invalid/unsupported color space,
342 // this will return NULL. If there is no color space information, it will guess sRGB
read_color_space(png_structp png_ptr,png_infop info_ptr,SkColorSpace_Base::ICCTypeFlag iccType)343 sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr,
344 SkColorSpace_Base::ICCTypeFlag iccType) {
345
346 #if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
347
348 // First check for an ICC profile
349 png_bytep profile;
350 png_uint_32 length;
351 // The below variables are unused, however, we need to pass them in anyway or
352 // png_get_iCCP() will return nothing.
353 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
354 png_charp name;
355 // The |compression| is uninteresting since:
356 // (1) libpng has already decompressed the profile for us.
357 // (2) "deflate" is the only mode of decompression that libpng supports.
358 int compression;
359 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
360 &length)) {
361 return SkColorSpace_Base::MakeICC(profile, length, iccType);
362 }
363
364 // Second, check for sRGB.
365 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
366
367 // sRGB chunks also store a rendering intent: Absolute, Relative,
368 // Perceptual, and Saturation.
369 // FIXME (msarett): Extract this information from the sRGB chunk once
370 // we are able to handle this information in
371 // SkColorSpace.
372 return SkColorSpace::MakeSRGB();
373 }
374
375 // Next, check for chromaticities.
376 png_fixed_point chrm[8];
377 png_fixed_point gamma;
378 if (png_get_cHRM_fixed(png_ptr, info_ptr, &chrm[0], &chrm[1], &chrm[2], &chrm[3], &chrm[4],
379 &chrm[5], &chrm[6], &chrm[7]))
380 {
381 SkColorSpacePrimaries primaries;
382 primaries.fRX = png_fixed_point_to_float(chrm[2]);
383 primaries.fRY = png_fixed_point_to_float(chrm[3]);
384 primaries.fGX = png_fixed_point_to_float(chrm[4]);
385 primaries.fGY = png_fixed_point_to_float(chrm[5]);
386 primaries.fBX = png_fixed_point_to_float(chrm[6]);
387 primaries.fBY = png_fixed_point_to_float(chrm[7]);
388 primaries.fWX = png_fixed_point_to_float(chrm[0]);
389 primaries.fWY = png_fixed_point_to_float(chrm[1]);
390
391 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
392 if (!primaries.toXYZD50(&toXYZD50)) {
393 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
394 }
395
396 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
397 SkColorSpaceTransferFn fn;
398 fn.fA = 1.0f;
399 fn.fB = fn.fC = fn.fD = fn.fE = fn.fF = 0.0f;
400 fn.fG = png_inverted_fixed_point_to_float(gamma);
401
402 return SkColorSpace::MakeRGB(fn, toXYZD50);
403 }
404
405 // Default to sRGB gamma if the image has color space information,
406 // but does not specify gamma.
407 return SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma, toXYZD50);
408 }
409
410 // Last, check for gamma.
411 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
412 SkColorSpaceTransferFn fn;
413 fn.fA = 1.0f;
414 fn.fB = fn.fC = fn.fD = fn.fE = fn.fF = 0.0f;
415 fn.fG = png_inverted_fixed_point_to_float(gamma);
416
417 // Since there is no cHRM, we will guess sRGB gamut.
418 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
419 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
420
421 return SkColorSpace::MakeRGB(fn, toXYZD50);
422 }
423
424 #endif // LIBPNG >= 1.6
425
426 // Report that there is no color space information in the PNG.
427 // Guess sRGB in this case.
428 return SkColorSpace::MakeSRGB();
429 }
430
allocateStorage(const SkImageInfo & dstInfo)431 void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
432 switch (fXformMode) {
433 case kSwizzleOnly_XformMode:
434 break;
435 case kColorOnly_XformMode:
436 // Intentional fall through. A swizzler hasn't been created yet, but one will
437 // be created later if we are sampling. We'll go ahead and allocate
438 // enough memory to swizzle if necessary.
439 case kSwizzleColor_XformMode: {
440 const int bitsPerPixel = this->getEncodedInfo().bitsPerPixel();
441
442 // If we have more than 8-bits (per component) of precision, we will keep that
443 // extra precision. Otherwise, we will swizzle to RGBA_8888 before transforming.
444 const size_t bytesPerPixel = (bitsPerPixel > 32) ? bitsPerPixel / 8 : 4;
445 const size_t colorXformBytes = dstInfo.width() * bytesPerPixel;
446 fStorage.reset(colorXformBytes);
447 fColorXformSrcRow = fStorage.get();
448 break;
449 }
450 }
451 }
452
png_select_xform_format(const SkEncodedInfo & info)453 static SkColorSpaceXform::ColorFormat png_select_xform_format(const SkEncodedInfo& info) {
454 // We use kRGB and kRGBA formats because color PNGs are always RGB or RGBA.
455 if (16 == info.bitsPerComponent()) {
456 if (SkEncodedInfo::kRGBA_Color == info.color()) {
457 return SkColorSpaceXform::kRGBA_U16_BE_ColorFormat;
458 } else if (SkEncodedInfo::kRGB_Color == info.color()) {
459 return SkColorSpaceXform::kRGB_U16_BE_ColorFormat;
460 }
461 }
462
463 return SkColorSpaceXform::kRGBA_8888_ColorFormat;
464 }
465
applyXformRow(void * dst,const void * src)466 void SkPngCodec::applyXformRow(void* dst, const void* src) {
467 switch (fXformMode) {
468 case kSwizzleOnly_XformMode:
469 fSwizzler->swizzle(dst, (const uint8_t*) src);
470 break;
471 case kColorOnly_XformMode:
472 this->applyColorXform(dst, src, fXformWidth);
473 break;
474 case kSwizzleColor_XformMode:
475 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src);
476 this->applyColorXform(dst, fColorXformSrcRow, fXformWidth);
477 break;
478 }
479 }
480
481 class SkPngNormalDecoder : public SkPngCodec {
482 public:
SkPngNormalDecoder(const SkEncodedInfo & info,const SkImageInfo & imageInfo,SkStream * stream,SkPngChunkReader * reader,png_structp png_ptr,png_infop info_ptr,int bitDepth)483 SkPngNormalDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo, SkStream* stream,
484 SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr, int bitDepth)
485 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
486 , fRowsWrittenToOutput(0)
487 , fDst(nullptr)
488 , fRowBytes(0)
489 , fFirstRow(0)
490 , fLastRow(0)
491 {}
492
AllRowsCallback(png_structp png_ptr,png_bytep row,png_uint_32 rowNum,int)493 static void AllRowsCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
494 GetDecoder(png_ptr)->allRowsCallback(row, rowNum);
495 }
496
RowCallback(png_structp png_ptr,png_bytep row,png_uint_32 rowNum,int)497 static void RowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
498 GetDecoder(png_ptr)->rowCallback(row, rowNum);
499 }
500
501 private:
502 int fRowsWrittenToOutput;
503 void* fDst;
504 size_t fRowBytes;
505
506 // Variables for partial decode
507 int fFirstRow; // FIXME: Move to baseclass?
508 int fLastRow;
509 int fRowsNeeded;
510
511 typedef SkPngCodec INHERITED;
512
GetDecoder(png_structp png_ptr)513 static SkPngNormalDecoder* GetDecoder(png_structp png_ptr) {
514 return static_cast<SkPngNormalDecoder*>(png_get_progressive_ptr(png_ptr));
515 }
516
decodeAllRows(void * dst,size_t rowBytes,int * rowsDecoded)517 Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
518 const int height = this->getInfo().height();
519 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, AllRowsCallback, nullptr);
520 fDst = dst;
521 fRowBytes = rowBytes;
522
523 fRowsWrittenToOutput = 0;
524 fFirstRow = 0;
525 fLastRow = height - 1;
526
527 this->processData();
528
529 if (fRowsWrittenToOutput == height) {
530 return SkCodec::kSuccess;
531 }
532
533 if (rowsDecoded) {
534 *rowsDecoded = fRowsWrittenToOutput;
535 }
536
537 return SkCodec::kIncompleteInput;
538 }
539
allRowsCallback(png_bytep row,int rowNum)540 void allRowsCallback(png_bytep row, int rowNum) {
541 SkASSERT(rowNum == fRowsWrittenToOutput);
542 fRowsWrittenToOutput++;
543 this->applyXformRow(fDst, row);
544 fDst = SkTAddOffset<void>(fDst, fRowBytes);
545 }
546
setRange(int firstRow,int lastRow,void * dst,size_t rowBytes)547 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
548 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, RowCallback, nullptr);
549 fFirstRow = firstRow;
550 fLastRow = lastRow;
551 fDst = dst;
552 fRowBytes = rowBytes;
553 fRowsWrittenToOutput = 0;
554 fRowsNeeded = fLastRow - fFirstRow + 1;
555 }
556
decode(int * rowsDecoded)557 SkCodec::Result decode(int* rowsDecoded) override {
558 if (this->swizzler()) {
559 const int sampleY = this->swizzler()->sampleY();
560 fRowsNeeded = get_scaled_dimension(fLastRow - fFirstRow + 1, sampleY);
561 }
562 this->processData();
563
564 if (fRowsWrittenToOutput == fRowsNeeded) {
565 return SkCodec::kSuccess;
566 }
567
568 if (rowsDecoded) {
569 *rowsDecoded = fRowsWrittenToOutput;
570 }
571
572 return SkCodec::kIncompleteInput;
573 }
574
rowCallback(png_bytep row,int rowNum)575 void rowCallback(png_bytep row, int rowNum) {
576 if (rowNum < fFirstRow) {
577 // Ignore this row.
578 return;
579 }
580
581 SkASSERT(rowNum <= fLastRow);
582 SkASSERT(fRowsWrittenToOutput < fRowsNeeded);
583
584 // If there is no swizzler, all rows are needed.
585 if (!this->swizzler() || this->swizzler()->rowNeeded(rowNum - fFirstRow)) {
586 this->applyXformRow(fDst, row);
587 fDst = SkTAddOffset<void>(fDst, fRowBytes);
588 fRowsWrittenToOutput++;
589 }
590
591 if (fRowsWrittenToOutput == fRowsNeeded) {
592 // Fake error to stop decoding scanlines.
593 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
594 }
595 }
596 };
597
598 class SkPngInterlacedDecoder : public SkPngCodec {
599 public:
SkPngInterlacedDecoder(const SkEncodedInfo & info,const SkImageInfo & imageInfo,SkStream * stream,SkPngChunkReader * reader,png_structp png_ptr,png_infop info_ptr,int bitDepth,int numberPasses)600 SkPngInterlacedDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo,
601 SkStream* stream, SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr,
602 int bitDepth, int numberPasses)
603 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth)
604 , fNumberPasses(numberPasses)
605 , fFirstRow(0)
606 , fLastRow(0)
607 , fLinesDecoded(0)
608 , fInterlacedComplete(false)
609 , fPng_rowbytes(0)
610 {}
611
InterlacedRowCallback(png_structp png_ptr,png_bytep row,png_uint_32 rowNum,int pass)612 static void InterlacedRowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int pass) {
613 auto decoder = static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr));
614 decoder->interlacedRowCallback(row, rowNum, pass);
615 }
616
617 private:
618 const int fNumberPasses;
619 int fFirstRow;
620 int fLastRow;
621 void* fDst;
622 size_t fRowBytes;
623 int fLinesDecoded;
624 bool fInterlacedComplete;
625 size_t fPng_rowbytes;
626 SkAutoTMalloc<png_byte> fInterlaceBuffer;
627
628 typedef SkPngCodec INHERITED;
629
630 // FIXME: Currently sharing interlaced callback for all rows and subset. It's not
631 // as expensive as the subset version of non-interlaced, but it still does extra
632 // work.
interlacedRowCallback(png_bytep row,int rowNum,int pass)633 void interlacedRowCallback(png_bytep row, int rowNum, int pass) {
634 if (rowNum < fFirstRow || rowNum > fLastRow || fInterlacedComplete) {
635 // Ignore this row
636 return;
637 }
638
639 png_bytep oldRow = fInterlaceBuffer.get() + (rowNum - fFirstRow) * fPng_rowbytes;
640 png_progressive_combine_row(this->png_ptr(), oldRow, row);
641
642 if (0 == pass) {
643 // The first pass initializes all rows.
644 SkASSERT(row);
645 SkASSERT(fLinesDecoded == rowNum - fFirstRow);
646 fLinesDecoded++;
647 } else {
648 SkASSERT(fLinesDecoded == fLastRow - fFirstRow + 1);
649 if (fNumberPasses - 1 == pass && rowNum == fLastRow) {
650 // Last pass, and we have read all of the rows we care about.
651 fInterlacedComplete = true;
652 if (fLastRow != this->getInfo().height() - 1 ||
653 (this->swizzler() && this->swizzler()->sampleY() != 1)) {
654 // Fake error to stop decoding scanlines. Only stop if we're not decoding the
655 // whole image, in which case processing the rest of the image might be
656 // expensive. When decoding the whole image, read through the IEND chunk to
657 // preserve Android behavior of leaving the input stream in the right place.
658 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
659 }
660 }
661 }
662 }
663
decodeAllRows(void * dst,size_t rowBytes,int * rowsDecoded)664 SkCodec::Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
665 const int height = this->getInfo().height();
666 this->setUpInterlaceBuffer(height);
667 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, InterlacedRowCallback,
668 nullptr);
669
670 fFirstRow = 0;
671 fLastRow = height - 1;
672 fLinesDecoded = 0;
673
674 this->processData();
675
676 png_bytep srcRow = fInterlaceBuffer.get();
677 // FIXME: When resuming, this may rewrite rows that did not change.
678 for (int rowNum = 0; rowNum < fLinesDecoded; rowNum++) {
679 this->applyXformRow(dst, srcRow);
680 dst = SkTAddOffset<void>(dst, rowBytes);
681 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes);
682 }
683 if (fInterlacedComplete) {
684 return SkCodec::kSuccess;
685 }
686
687 if (rowsDecoded) {
688 *rowsDecoded = fLinesDecoded;
689 }
690
691 return SkCodec::kIncompleteInput;
692 }
693
setRange(int firstRow,int lastRow,void * dst,size_t rowBytes)694 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) override {
695 // FIXME: We could skip rows in the interlace buffer that we won't put in the output.
696 this->setUpInterlaceBuffer(lastRow - firstRow + 1);
697 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, InterlacedRowCallback, nullptr);
698 fFirstRow = firstRow;
699 fLastRow = lastRow;
700 fDst = dst;
701 fRowBytes = rowBytes;
702 fLinesDecoded = 0;
703 }
704
decode(int * rowsDecoded)705 SkCodec::Result decode(int* rowsDecoded) override {
706 this->processData();
707
708 // Now apply Xforms on all the rows that were decoded.
709 if (!fLinesDecoded) {
710 if (rowsDecoded) {
711 *rowsDecoded = 0;
712 }
713 return SkCodec::kIncompleteInput;
714 }
715
716 const int sampleY = this->swizzler() ? this->swizzler()->sampleY() : 1;
717 const int rowsNeeded = get_scaled_dimension(fLastRow - fFirstRow + 1, sampleY);
718 int rowsWrittenToOutput = 0;
719
720 // FIXME: For resuming interlace, we may swizzle a row that hasn't changed. But it
721 // may be too tricky/expensive to handle that correctly.
722
723 // Offset srcRow by get_start_coord rows. We do not need to account for fFirstRow,
724 // since the first row in fInterlaceBuffer corresponds to fFirstRow.
725 png_bytep srcRow = SkTAddOffset<png_byte>(fInterlaceBuffer.get(),
726 fPng_rowbytes * get_start_coord(sampleY));
727 void* dst = fDst;
728 for (; rowsWrittenToOutput < rowsNeeded; rowsWrittenToOutput++) {
729 this->applyXformRow(dst, srcRow);
730 dst = SkTAddOffset<void>(dst, fRowBytes);
731 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes * sampleY);
732 }
733
734 if (fInterlacedComplete) {
735 return SkCodec::kSuccess;
736 }
737
738 if (rowsDecoded) {
739 *rowsDecoded = rowsWrittenToOutput;
740 }
741 return SkCodec::kIncompleteInput;
742 }
743
setUpInterlaceBuffer(int height)744 void setUpInterlaceBuffer(int height) {
745 fPng_rowbytes = png_get_rowbytes(this->png_ptr(), this->info_ptr());
746 fInterlaceBuffer.reset(fPng_rowbytes * height);
747 fInterlacedComplete = false;
748 }
749 };
750
751 // Reads the header and initializes the output fields, if not NULL.
752 //
753 // @param stream Input data. Will be read to get enough information to properly
754 // setup the codec.
755 // @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
756 // If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
757 // expected to continue to own it for the lifetime of the png_ptr.
758 // @param outCodec Optional output variable. If non-NULL, will be set to a new
759 // SkPngCodec on success.
760 // @param png_ptrp Optional output variable. If non-NULL, will be set to a new
761 // png_structp on success.
762 // @param info_ptrp Optional output variable. If non-NULL, will be set to a new
763 // png_infop on success;
764 // @return if kSuccess, the caller is responsible for calling
765 // png_destroy_read_struct(png_ptrp, info_ptrp).
766 // Otherwise, the passed in fields (except stream) are unchanged.
read_header(SkStream * stream,SkPngChunkReader * chunkReader,SkCodec ** outCodec,png_structp * png_ptrp,png_infop * info_ptrp)767 static SkCodec::Result read_header(SkStream* stream, SkPngChunkReader* chunkReader,
768 SkCodec** outCodec,
769 png_structp* png_ptrp, png_infop* info_ptrp) {
770 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
771 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
772 sk_error_fn, sk_warning_fn);
773 if (!png_ptr) {
774 return SkCodec::kInternalError;
775 }
776
777 AutoCleanPng autoClean(png_ptr, stream, chunkReader, outCodec);
778
779 png_infop info_ptr = png_create_info_struct(png_ptr);
780 if (info_ptr == nullptr) {
781 return SkCodec::kInternalError;
782 }
783
784 autoClean.setInfoPtr(info_ptr);
785
786 if (setjmp(PNG_JMPBUF(png_ptr))) {
787 return SkCodec::kInvalidInput;
788 }
789
790 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
791 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
792 // This needs to be installed before we read the png header. Android may store ninepatch
793 // chunks in the header.
794 if (chunkReader) {
795 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
796 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
797 }
798 #endif
799
800 const bool decodedBounds = autoClean.decodeBounds();
801
802 if (!decodedBounds) {
803 return SkCodec::kIncompleteInput;
804 }
805
806 // On success, decodeBounds releases ownership of png_ptr and info_ptr.
807 if (png_ptrp) {
808 *png_ptrp = png_ptr;
809 }
810 if (info_ptrp) {
811 *info_ptrp = info_ptr;
812 }
813
814 // decodeBounds takes care of setting outCodec
815 if (outCodec) {
816 SkASSERT(*outCodec);
817 }
818 return SkCodec::kSuccess;
819 }
820
infoCallback(size_t idatLength)821 void AutoCleanPng::infoCallback(size_t idatLength) {
822 png_uint_32 origWidth, origHeight;
823 int bitDepth, encodedColorType;
824 png_get_IHDR(fPng_ptr, fInfo_ptr, &origWidth, &origHeight, &bitDepth,
825 &encodedColorType, nullptr, nullptr, nullptr);
826
827 // TODO: Should we support 16-bits of precision for gray images?
828 if (bitDepth == 16 && (PNG_COLOR_TYPE_GRAY == encodedColorType ||
829 PNG_COLOR_TYPE_GRAY_ALPHA == encodedColorType)) {
830 bitDepth = 8;
831 png_set_strip_16(fPng_ptr);
832 }
833
834 // Now determine the default colorType and alphaType and set the required transforms.
835 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
836 // still depend on libpng for many of the rare and PNG-specific cases.
837 SkEncodedInfo::Color color;
838 SkEncodedInfo::Alpha alpha;
839 switch (encodedColorType) {
840 case PNG_COLOR_TYPE_PALETTE:
841 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
842 // byte into separate bytes (useful for paletted and grayscale images).
843 if (bitDepth < 8) {
844 // TODO: Should we use SkSwizzler here?
845 bitDepth = 8;
846 png_set_packing(fPng_ptr);
847 }
848
849 color = SkEncodedInfo::kPalette_Color;
850 // Set the alpha depending on if a transparency chunk exists.
851 alpha = png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS) ?
852 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
853 break;
854 case PNG_COLOR_TYPE_RGB:
855 if (png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS)) {
856 // Convert to RGBA if transparency chunk exists.
857 png_set_tRNS_to_alpha(fPng_ptr);
858 color = SkEncodedInfo::kRGBA_Color;
859 alpha = SkEncodedInfo::kBinary_Alpha;
860 } else {
861 color = SkEncodedInfo::kRGB_Color;
862 alpha = SkEncodedInfo::kOpaque_Alpha;
863 }
864 break;
865 case PNG_COLOR_TYPE_GRAY:
866 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
867 if (bitDepth < 8) {
868 // TODO: Should we use SkSwizzler here?
869 bitDepth = 8;
870 png_set_expand_gray_1_2_4_to_8(fPng_ptr);
871 }
872
873 if (png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS)) {
874 png_set_tRNS_to_alpha(fPng_ptr);
875 color = SkEncodedInfo::kGrayAlpha_Color;
876 alpha = SkEncodedInfo::kBinary_Alpha;
877 } else {
878 color = SkEncodedInfo::kGray_Color;
879 alpha = SkEncodedInfo::kOpaque_Alpha;
880 }
881 break;
882 case PNG_COLOR_TYPE_GRAY_ALPHA:
883 color = SkEncodedInfo::kGrayAlpha_Color;
884 alpha = SkEncodedInfo::kUnpremul_Alpha;
885 break;
886 case PNG_COLOR_TYPE_RGBA:
887 color = SkEncodedInfo::kRGBA_Color;
888 alpha = SkEncodedInfo::kUnpremul_Alpha;
889 break;
890 default:
891 // All the color types have been covered above.
892 SkASSERT(false);
893 color = SkEncodedInfo::kRGBA_Color;
894 alpha = SkEncodedInfo::kUnpremul_Alpha;
895 }
896
897 const int numberPasses = png_set_interlace_handling(fPng_ptr);
898
899 if (fOutCodec) {
900 SkASSERT(nullptr == *fOutCodec);
901 SkColorSpace_Base::ICCTypeFlag iccType = SkColorSpace_Base::kRGB_ICCTypeFlag;
902 if (SkEncodedInfo::kGray_Color == color || SkEncodedInfo::kGrayAlpha_Color == color) {
903 iccType |= SkColorSpace_Base::kGray_ICCTypeFlag;
904 }
905 sk_sp<SkColorSpace> colorSpace = read_color_space(fPng_ptr, fInfo_ptr, iccType);
906 if (!colorSpace) {
907 // Treat unsupported/invalid color spaces as sRGB.
908 colorSpace = SkColorSpace::MakeSRGB();
909 }
910
911 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, bitDepth);
912 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
913
914 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
915 png_color_8p sigBits;
916 if (png_get_sBIT(fPng_ptr, fInfo_ptr, &sigBits)) {
917 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->blue) {
918 // Recommend a decode to 565 if the sBIT indicates 565.
919 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
920 }
921 }
922 }
923
924 if (1 == numberPasses) {
925 *fOutCodec = new SkPngNormalDecoder(encodedInfo, imageInfo, fStream,
926 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth);
927 } else {
928 *fOutCodec = new SkPngInterlacedDecoder(encodedInfo, imageInfo, fStream,
929 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth, numberPasses);
930 }
931 static_cast<SkPngCodec*>(*fOutCodec)->setIdatLength(idatLength);
932 }
933
934 // Release the pointers, which are now owned by the codec or the caller is expected to
935 // take ownership.
936 this->releasePngPtrs();
937 }
938
SkPngCodec(const SkEncodedInfo & encodedInfo,const SkImageInfo & imageInfo,SkStream * stream,SkPngChunkReader * chunkReader,void * png_ptr,void * info_ptr,int bitDepth)939 SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
940 SkStream* stream, SkPngChunkReader* chunkReader, void* png_ptr,
941 void* info_ptr, int bitDepth)
942 : INHERITED(encodedInfo, imageInfo, png_select_xform_format(encodedInfo), stream)
943 , fPngChunkReader(SkSafeRef(chunkReader))
944 , fPng_ptr(png_ptr)
945 , fInfo_ptr(info_ptr)
946 , fColorXformSrcRow(nullptr)
947 , fBitDepth(bitDepth)
948 , fIdatLength(0)
949 , fDecodedIdat(false)
950 {}
951
~SkPngCodec()952 SkPngCodec::~SkPngCodec() {
953 this->destroyReadStruct();
954 }
955
destroyReadStruct()956 void SkPngCodec::destroyReadStruct() {
957 if (fPng_ptr) {
958 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
959 SkASSERT(fInfo_ptr);
960 png_destroy_read_struct((png_struct**)&fPng_ptr, (png_info**)&fInfo_ptr, nullptr);
961 fPng_ptr = nullptr;
962 fInfo_ptr = nullptr;
963 }
964 }
965
966 ///////////////////////////////////////////////////////////////////////////////
967 // Getting the pixels
968 ///////////////////////////////////////////////////////////////////////////////
969
initializeXforms(const SkImageInfo & dstInfo,const Options & options)970 SkCodec::Result SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& options) {
971 if (setjmp(PNG_JMPBUF((png_struct*)fPng_ptr))) {
972 SkCodecPrintf("Failed on png_read_update_info.\n");
973 return kInvalidInput;
974 }
975 png_read_update_info(fPng_ptr, fInfo_ptr);
976
977 // Reset fSwizzler and this->colorXform(). We can't do this in onRewind() because the
978 // interlaced scanline decoder may need to rewind.
979 fSwizzler.reset(nullptr);
980
981 if (!this->initializeColorXform(dstInfo, options.fPremulBehavior)) {
982 return kInvalidConversion;
983 }
984
985 // If SkColorSpaceXform directly supports the encoded PNG format, we should skip format
986 // conversion in the swizzler (or skip swizzling altogether).
987 bool skipFormatConversion = false;
988 switch (this->getEncodedInfo().color()) {
989 case SkEncodedInfo::kRGB_Color:
990 if (this->getEncodedInfo().bitsPerComponent() != 16) {
991 break;
992 }
993
994 // Fall through
995 case SkEncodedInfo::kRGBA_Color:
996 skipFormatConversion = this->colorXform();
997 break;
998 default:
999 break;
1000 }
1001 if (skipFormatConversion && !options.fSubset) {
1002 fXformMode = kColorOnly_XformMode;
1003 return kSuccess;
1004 }
1005
1006 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
1007 if (!this->createColorTable(dstInfo)) {
1008 return kInvalidInput;
1009 }
1010 }
1011
1012 this->initializeSwizzler(dstInfo, options, skipFormatConversion);
1013 return kSuccess;
1014 }
1015
initializeXformParams()1016 void SkPngCodec::initializeXformParams() {
1017 switch (fXformMode) {
1018 case kColorOnly_XformMode:
1019 fXformWidth = this->dstInfo().width();
1020 break;
1021 case kSwizzleColor_XformMode:
1022 fXformWidth = this->swizzler()->swizzleWidth();
1023 break;
1024 default:
1025 break;
1026 }
1027 }
1028
initializeSwizzler(const SkImageInfo & dstInfo,const Options & options,bool skipFormatConversion)1029 void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& options,
1030 bool skipFormatConversion) {
1031 SkImageInfo swizzlerInfo = dstInfo;
1032 Options swizzlerOptions = options;
1033 fXformMode = kSwizzleOnly_XformMode;
1034 if (this->colorXform() && this->xformOnDecode()) {
1035 swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
1036 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
1037 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
1038 }
1039
1040 fXformMode = kSwizzleColor_XformMode;
1041
1042 // Here, we swizzle into temporary memory, which is not zero initialized.
1043 // FIXME (msarett):
1044 // Is this a problem?
1045 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
1046 }
1047
1048 if (skipFormatConversion) {
1049 // We cannot skip format conversion when there is a color table.
1050 SkASSERT(!fColorTable);
1051 int srcBPP = 0;
1052 switch (this->getEncodedInfo().color()) {
1053 case SkEncodedInfo::kRGB_Color:
1054 SkASSERT(this->getEncodedInfo().bitsPerComponent() == 16);
1055 srcBPP = 6;
1056 break;
1057 case SkEncodedInfo::kRGBA_Color:
1058 srcBPP = this->getEncodedInfo().bitsPerComponent() / 2;
1059 break;
1060 case SkEncodedInfo::kGray_Color:
1061 srcBPP = 1;
1062 break;
1063 default:
1064 SkASSERT(false);
1065 break;
1066 }
1067 fSwizzler = SkSwizzler::MakeSimple(srcBPP, swizzlerInfo, swizzlerOptions);
1068 } else {
1069 const SkPMColor* colors = get_color_ptr(fColorTable.get());
1070 fSwizzler = SkSwizzler::Make(this->getEncodedInfo(), colors, swizzlerInfo,
1071 swizzlerOptions);
1072 }
1073 SkASSERT(fSwizzler);
1074 }
1075
getSampler(bool createIfNecessary)1076 SkSampler* SkPngCodec::getSampler(bool createIfNecessary) {
1077 if (fSwizzler || !createIfNecessary) {
1078 return fSwizzler.get();
1079 }
1080
1081 this->initializeSwizzler(this->dstInfo(), this->options(), true);
1082 return fSwizzler.get();
1083 }
1084
onRewind()1085 bool SkPngCodec::onRewind() {
1086 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
1087 // succeeds, they will be repopulated, and if it fails, they will
1088 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
1089 // come through this function which will rewind and again attempt
1090 // to reinitialize them.
1091 this->destroyReadStruct();
1092
1093 png_structp png_ptr;
1094 png_infop info_ptr;
1095 if (kSuccess != read_header(this->stream(), fPngChunkReader.get(), nullptr,
1096 &png_ptr, &info_ptr)) {
1097 return false;
1098 }
1099
1100 fPng_ptr = png_ptr;
1101 fInfo_ptr = info_ptr;
1102 fDecodedIdat = false;
1103 return true;
1104 }
1105
onGetPixels(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,const Options & options,int * rowsDecoded)1106 SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
1107 size_t rowBytes, const Options& options,
1108 int* rowsDecoded) {
1109 if (!conversion_possible(dstInfo, this->getInfo())) {
1110 return kInvalidConversion;
1111 }
1112
1113 Result result = this->initializeXforms(dstInfo, options);
1114 if (kSuccess != result) {
1115 return result;
1116 }
1117
1118 if (options.fSubset) {
1119 return kUnimplemented;
1120 }
1121
1122 this->allocateStorage(dstInfo);
1123 this->initializeXformParams();
1124 return this->decodeAllRows(dst, rowBytes, rowsDecoded);
1125 }
1126
onStartIncrementalDecode(const SkImageInfo & dstInfo,void * dst,size_t rowBytes,const SkCodec::Options & options)1127 SkCodec::Result SkPngCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
1128 void* dst, size_t rowBytes, const SkCodec::Options& options) {
1129 if (!conversion_possible(dstInfo, this->getInfo())) {
1130 return kInvalidConversion;
1131 }
1132
1133 Result result = this->initializeXforms(dstInfo, options);
1134 if (kSuccess != result) {
1135 return result;
1136 }
1137
1138 this->allocateStorage(dstInfo);
1139
1140 int firstRow, lastRow;
1141 if (options.fSubset) {
1142 firstRow = options.fSubset->top();
1143 lastRow = options.fSubset->bottom() - 1;
1144 } else {
1145 firstRow = 0;
1146 lastRow = dstInfo.height() - 1;
1147 }
1148 this->setRange(firstRow, lastRow, dst, rowBytes);
1149 return kSuccess;
1150 }
1151
onIncrementalDecode(int * rowsDecoded)1152 SkCodec::Result SkPngCodec::onIncrementalDecode(int* rowsDecoded) {
1153 // FIXME: Only necessary on the first call.
1154 this->initializeXformParams();
1155
1156 return this->decode(rowsDecoded);
1157 }
1158
onGetFillValue(const SkImageInfo & dstInfo) const1159 uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
1160 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
1161 if (colorPtr) {
1162 SkAlphaType alphaType = select_xform_alpha(dstInfo.alphaType(),
1163 this->getInfo().alphaType());
1164 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorPtr, 0,
1165 this->colorXform(), true);
1166 }
1167 return INHERITED::onGetFillValue(dstInfo);
1168 }
1169
NewFromStream(SkStream * stream,Result * result,SkPngChunkReader * chunkReader)1170 SkCodec* SkPngCodec::NewFromStream(SkStream* stream, Result* result, SkPngChunkReader* chunkReader) {
1171 std::unique_ptr<SkStream> streamDeleter(stream);
1172
1173 SkCodec* outCodec = nullptr;
1174 *result = read_header(stream, chunkReader, &outCodec, nullptr, nullptr);
1175 if (kSuccess == *result) {
1176 // Codec has taken ownership of the stream.
1177 SkASSERT(outCodec);
1178 streamDeleter.release();
1179 }
1180 return outCodec;
1181 }
1182