blob: 0d13e6ac2e70fc73606e99e65e3e15c36f67f6db [file] [log] [blame]
scroggof24f2242015-03-03 08:59:20 -08001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
msarettad8bcfe2016-03-07 07:09:03 -08008#include "SkBitmap.h"
msarett74114382015-03-16 11:55:18 -07009#include "SkCodecPriv.h"
scroggof24f2242015-03-03 08:59:20 -080010#include "SkColorPriv.h"
msarettc4ce6b52016-06-16 07:37:41 -070011#include "SkColorSpace_Base.h"
scroggof24f2242015-03-03 08:59:20 -080012#include "SkColorTable.h"
scroggof24f2242015-03-03 08:59:20 -080013#include "SkMath.h"
msarett13a91232016-02-01 08:03:29 -080014#include "SkOpts.h"
msarettbe1d5552016-01-21 09:05:23 -080015#include "SkPngCodec.h"
msarett55447952016-07-22 14:07:23 -070016#include "SkPoint3.h"
scroggof24f2242015-03-03 08:59:20 -080017#include "SkSize.h"
18#include "SkStream.h"
19#include "SkSwizzler.h"
scroggo565901d2015-12-10 10:44:13 -080020#include "SkTemplates.h"
bungeman5d2cd6e2016-02-23 07:34:25 -080021#include "SkUtils.h"
scroggof24f2242015-03-03 08:59:20 -080022
mtkleindc90b532016-07-28 14:45:28 -070023// This warning triggers false postives way too often in here.
24#if defined(__GNUC__) && !defined(__clang__)
25 #pragma GCC diagnostic ignored "-Wclobbered"
26#endif
27
scroggof24f2242015-03-03 08:59:20 -080028///////////////////////////////////////////////////////////////////////////////
scroggof24f2242015-03-03 08:59:20 -080029// Callback functions
30///////////////////////////////////////////////////////////////////////////////
31
32static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
scroggo230d4ac2015-03-26 07:15:55 -070033 SkCodecPrintf("------ png error %s\n", msg);
scroggod8d68552016-06-06 11:26:17 -070034 longjmp(png_jmpbuf(png_ptr), 1);
scroggof24f2242015-03-03 08:59:20 -080035}
36
scroggo0eed6df2015-03-26 10:07:56 -070037void sk_warning_fn(png_structp, png_const_charp msg) {
38 SkCodecPrintf("----- png warning %s\n", msg);
39}
40
scroggod8d68552016-06-06 11:26:17 -070041static void sk_read_fn(png_structp png_ptr, png_bytep data,
42 png_size_t length) {
43 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
44 const size_t bytes = stream->read(data, length);
45 if (bytes != length) {
46 // FIXME: We want to report the fact that the stream was truncated.
47 // One way to do that might be to pass a enum to longjmp so setjmp can
48 // specify the failure.
49 png_error(png_ptr, "Read Error!");
50 }
51}
52
scroggocf98fa92015-11-23 08:14:40 -080053#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
54static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
55 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(png_ptr);
56 // readChunk() returning true means continue decoding
57 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk->size) ? 1 : -1;
58}
59#endif
60
scroggof24f2242015-03-03 08:59:20 -080061///////////////////////////////////////////////////////////////////////////////
62// Helpers
63///////////////////////////////////////////////////////////////////////////////
64
65class AutoCleanPng : public SkNoncopyable {
66public:
scroggod8d68552016-06-06 11:26:17 -070067 AutoCleanPng(png_structp png_ptr)
scroggof24f2242015-03-03 08:59:20 -080068 : fPng_ptr(png_ptr)
scroggod8d68552016-06-06 11:26:17 -070069 , fInfo_ptr(nullptr) {}
scroggof24f2242015-03-03 08:59:20 -080070
71 ~AutoCleanPng() {
halcanary96fcdcc2015-08-27 07:41:13 -070072 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
scroggof24f2242015-03-03 08:59:20 -080073 if (fPng_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070074 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
msarett13a91232016-02-01 08:03:29 -080075 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
scroggof24f2242015-03-03 08:59:20 -080076 }
77 }
78
79 void setInfoPtr(png_infop info_ptr) {
halcanary96fcdcc2015-08-27 07:41:13 -070080 SkASSERT(nullptr == fInfo_ptr);
scroggof24f2242015-03-03 08:59:20 -080081 fInfo_ptr = info_ptr;
82 }
83
scroggod8d68552016-06-06 11:26:17 -070084 void release() {
halcanary96fcdcc2015-08-27 07:41:13 -070085 fPng_ptr = nullptr;
86 fInfo_ptr = nullptr;
scroggof24f2242015-03-03 08:59:20 -080087 }
scroggod8d68552016-06-06 11:26:17 -070088
89private:
90 png_structp fPng_ptr;
91 png_infop fInfo_ptr;
scroggof24f2242015-03-03 08:59:20 -080092};
93#define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
94
msarettd1ec89b2016-08-03 12:59:27 -070095// Note: SkColorTable claims to store SkPMColors, which is not necessarily the case here.
msarett34e0ec42016-04-22 16:27:24 -070096bool SkPngCodec::createColorTable(SkColorType dstColorType, bool premultiply, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -080097
msarett13a91232016-02-01 08:03:29 -080098 int numColors;
99 png_color* palette;
100 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -0700101 return false;
scroggof24f2242015-03-03 08:59:20 -0800102 }
103
msarett13a91232016-02-01 08:03:29 -0800104 // Note: These are not necessarily SkPMColors.
105 SkPMColor colorPtr[256];
scroggof24f2242015-03-03 08:59:20 -0800106
msarett13a91232016-02-01 08:03:29 -0800107 png_bytep alphas;
108 int numColorsWithAlpha = 0;
109 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
110 // Choose which function to use to create the color table. If the final destination's
111 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
msarett34e0ec42016-04-22 16:27:24 -0700112 PackColorProc proc = choose_pack_color_proc(premultiply, dstColorType);
msarett13a91232016-02-01 08:03:29 -0800113
114 for (int i = 0; i < numColorsWithAlpha; i++) {
115 // We don't have a function in SkOpts that combines a set of alphas with a set
116 // of RGBs. We could write one, but it's hardly worth it, given that this
117 // is such a small fraction of the total decode time.
118 colorPtr[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
119 palette++;
120 }
scroggof24f2242015-03-03 08:59:20 -0800121 }
122
msarett13a91232016-02-01 08:03:29 -0800123 if (numColorsWithAlpha < numColors) {
124 // The optimized code depends on a 3-byte png_color struct with the colors
125 // in RGB order. These checks make sure it is safe to use.
126 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
127#ifdef SK_DEBUG
128 SkASSERT(&palette->red < &palette->green);
129 SkASSERT(&palette->green < &palette->blue);
130#endif
131
msarett34e0ec42016-04-22 16:27:24 -0700132 if (is_rgba(dstColorType)) {
133 SkOpts::RGB_to_RGB1(colorPtr + numColorsWithAlpha, palette,
134 numColors - numColorsWithAlpha);
135 } else {
136 SkOpts::RGB_to_BGR1(colorPtr + numColorsWithAlpha, palette,
137 numColors - numColorsWithAlpha);
138 }
scroggof24f2242015-03-03 08:59:20 -0800139 }
140
msarett13a91232016-02-01 08:03:29 -0800141 // Pad the color table with the last color in the table (or black) in the case that
142 // invalid pixel indices exceed the number of colors in the table.
143 const int maxColors = 1 << fBitDepth;
144 if (numColors < maxColors) {
145 SkPMColor lastColor = numColors > 0 ? colorPtr[numColors - 1] : SK_ColorBLACK;
146 sk_memset32(colorPtr + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800147 }
148
msarett13a91232016-02-01 08:03:29 -0800149 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700150 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800151 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800152 }
153
msarett13a91232016-02-01 08:03:29 -0800154 fColorTable.reset(new SkColorTable(colorPtr, maxColors));
scroggo05245902015-03-25 11:11:52 -0700155 return true;
scroggof24f2242015-03-03 08:59:20 -0800156}
157
158///////////////////////////////////////////////////////////////////////////////
159// Creation
160///////////////////////////////////////////////////////////////////////////////
161
scroggodb30be22015-12-08 18:54:13 -0800162bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
163 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800164}
165
msarett6a738212016-03-04 13:27:35 -0800166static float png_fixed_point_to_float(png_fixed_point x) {
167 // We multiply by the same factor that libpng used to convert
168 // fixed point -> double. Since we want floats, we choose to
169 // do the conversion ourselves rather than convert
170 // fixed point -> double -> float.
171 return ((float) x) * 0.00001f;
172}
173
msarett128245c2016-03-30 12:01:47 -0700174static float png_inverted_fixed_point_to_float(png_fixed_point x) {
175 // This is necessary because the gAMA chunk actually stores 1/gamma.
176 return 1.0f / png_fixed_point_to_float(x);
177}
178
msarettc4ce6b52016-06-16 07:37:41 -0700179static constexpr float gSRGB_toXYZD50[] {
180 0.4358f, 0.2224f, 0.0139f, // * R
181 0.3853f, 0.7170f, 0.0971f, // * G
182 0.1430f, 0.0606f, 0.7139f, // * B
183};
184
msarett55447952016-07-22 14:07:23 -0700185static bool convert_to_D50(SkMatrix44* toXYZD50, float toXYZ[9], float whitePoint[2]) {
186 float wX = whitePoint[0];
187 float wY = whitePoint[1];
188 if (wX < 0.0f || wY < 0.0f || (wX + wY > 1.0f)) {
189 return false;
190 }
191
192 // Calculate the XYZ illuminant. Call this the src illuminant.
193 float wZ = 1.0f - wX - wY;
194 float scale = 1.0f / wY;
195 // TODO (msarett):
196 // What are common src illuminants? I'm guessing we will almost always see D65. Should
197 // we go ahead and save a precomputed D65->D50 Bradford matrix? Should we exit early if
198 // if the src illuminant is D50?
199 SkVector3 srcXYZ = SkVector3::Make(wX * scale, 1.0f, wZ * scale);
200
201 // The D50 illuminant.
202 SkVector3 dstXYZ = SkVector3::Make(0.96422f, 1.0f, 0.82521f);
203
204 // Calculate the chromatic adaptation matrix. We will use the Bradford method, thus
205 // the matrices below. The Bradford method is used by Adobe and is widely considered
206 // to be the best.
207 // http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
208 SkMatrix mA, mAInv;
209 mA.setAll(0.8951f, 0.2664f, -0.1614f, -0.7502f, 1.7135f, 0.0367f, 0.0389f, -0.0685f, 1.0296f);
210 mAInv.setAll(0.9869929f, -0.1470543f, 0.1599627f, 0.4323053f, 0.5183603f, 0.0492912f,
211 -0.0085287f, 0.0400428f, 0.9684867f);
212
213 // Map illuminant into cone response domain.
214 SkVector3 srcCone;
215 srcCone.fX = mA[0] * srcXYZ.fX + mA[1] * srcXYZ.fY + mA[2] * srcXYZ.fZ;
216 srcCone.fY = mA[3] * srcXYZ.fX + mA[4] * srcXYZ.fY + mA[5] * srcXYZ.fZ;
217 srcCone.fZ = mA[6] * srcXYZ.fX + mA[7] * srcXYZ.fY + mA[8] * srcXYZ.fZ;
218 SkVector3 dstCone;
219 dstCone.fX = mA[0] * dstXYZ.fX + mA[1] * dstXYZ.fY + mA[2] * dstXYZ.fZ;
220 dstCone.fY = mA[3] * dstXYZ.fX + mA[4] * dstXYZ.fY + mA[5] * dstXYZ.fZ;
221 dstCone.fZ = mA[6] * dstXYZ.fX + mA[7] * dstXYZ.fY + mA[8] * dstXYZ.fZ;
222
223 SkMatrix DXToD50;
224 DXToD50.setIdentity();
225 DXToD50[0] = dstCone.fX / srcCone.fX;
226 DXToD50[4] = dstCone.fY / srcCone.fY;
227 DXToD50[8] = dstCone.fZ / srcCone.fZ;
228 DXToD50.postConcat(mAInv);
229 DXToD50.preConcat(mA);
230
231 SkMatrix toXYZ3x3;
232 toXYZ3x3.setAll(toXYZ[0], toXYZ[3], toXYZ[6], toXYZ[1], toXYZ[4], toXYZ[7], toXYZ[2], toXYZ[5],
233 toXYZ[8]);
234 toXYZ3x3.postConcat(DXToD50);
235
236 toXYZD50->set3x3(toXYZ3x3[0], toXYZ3x3[1], toXYZ3x3[2], toXYZ3x3[3], toXYZ3x3[4], toXYZ3x3[5],
237 toXYZ3x3[6], toXYZ3x3[7], toXYZ3x3[8]);
238 return true;
239}
240
msarett6a738212016-03-04 13:27:35 -0800241// Returns a colorSpace object that represents any color space information in
242// the encoded data. If the encoded data contains no color space, this will
243// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800244sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800245
msarette2443222016-03-04 14:20:49 -0800246#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
247
msarett6a738212016-03-04 13:27:35 -0800248 // First check for an ICC profile
249 png_bytep profile;
250 png_uint_32 length;
251 // The below variables are unused, however, we need to pass them in anyway or
252 // png_get_iCCP() will return nothing.
253 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
254 png_charp name;
255 // The |compression| is uninteresting since:
256 // (1) libpng has already decompressed the profile for us.
257 // (2) "deflate" is the only mode of decompression that libpng supports.
258 int compression;
259 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
260 &length)) {
261 return SkColorSpace::NewICC(profile, length);
262 }
263
264 // Second, check for sRGB.
265 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
266
267 // sRGB chunks also store a rendering intent: Absolute, Relative,
268 // Perceptual, and Saturation.
269 // FIXME (msarett): Extract this information from the sRGB chunk once
270 // we are able to handle this information in
271 // SkColorSpace.
272 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
273 }
274
275 // Next, check for chromaticities.
msarett55447952016-07-22 14:07:23 -0700276 png_fixed_point toXYZFixed[9];
277 float toXYZ[9];
278 png_fixed_point whitePointFixed[2];
279 float whitePoint[2];
msarett6a738212016-03-04 13:27:35 -0800280 png_fixed_point gamma;
msarettbb9f7742016-05-17 09:31:20 -0700281 float gammas[3];
msarett55447952016-07-22 14:07:23 -0700282 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &toXYZFixed[0], &toXYZFixed[1], &toXYZFixed[2],
283 &toXYZFixed[3], &toXYZFixed[4], &toXYZFixed[5], &toXYZFixed[6],
284 &toXYZFixed[7], &toXYZFixed[8]) &&
285 png_get_cHRM_fixed(png_ptr, info_ptr, &whitePointFixed[0], &whitePointFixed[1], nullptr,
286 nullptr, nullptr, nullptr, nullptr, nullptr))
287 {
msarett6a738212016-03-04 13:27:35 -0800288 for (int i = 0; i < 9; i++) {
msarett55447952016-07-22 14:07:23 -0700289 toXYZ[i] = png_fixed_point_to_float(toXYZFixed[i]);
msarett6a738212016-03-04 13:27:35 -0800290 }
msarett55447952016-07-22 14:07:23 -0700291 whitePoint[0] = png_fixed_point_to_float(whitePointFixed[0]);
292 whitePoint[1] = png_fixed_point_to_float(whitePointFixed[1]);
293
294 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
295 if (!convert_to_D50(&toXYZD50, toXYZ, whitePoint)) {
296 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
297 }
msarett6a738212016-03-04 13:27:35 -0800298
msarett128245c2016-03-30 12:01:47 -0700299 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
msarettffc2aea2016-05-02 11:12:14 -0700300 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700301 gammas[0] = value;
302 gammas[1] = value;
303 gammas[2] = value;
msarettffc2aea2016-05-02 11:12:14 -0700304
msarett55447952016-07-22 14:07:23 -0700305 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800306 }
msarett128245c2016-03-30 12:01:47 -0700307
msarettc4ce6b52016-06-16 07:37:41 -0700308 // Default to sRGB gamma if the image has color space information,
309 // but does not specify gamma.
msarett55447952016-07-22 14:07:23 -0700310 return SkColorSpace::NewRGB(SkColorSpace::kSRGB_GammaNamed, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800311 }
312
313 // Last, check for gamma.
314 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
315
msarett6a738212016-03-04 13:27:35 -0800316 // Set the gammas.
msarettffc2aea2016-05-02 11:12:14 -0700317 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700318 gammas[0] = value;
319 gammas[1] = value;
320 gammas[2] = value;
msarett6a738212016-03-04 13:27:35 -0800321
msarettc4ce6b52016-06-16 07:37:41 -0700322 // Since there is no cHRM, we will guess sRGB gamut.
msarett55447952016-07-22 14:07:23 -0700323 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
324 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
msarettc4ce6b52016-06-16 07:37:41 -0700325
msarett55447952016-07-22 14:07:23 -0700326 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800327 }
328
msarette2443222016-03-04 14:20:49 -0800329#endif // LIBPNG >= 1.6
330
msarettc4ce6b52016-06-16 07:37:41 -0700331 // Report that there is no color space information in the PNG. SkPngCodec is currently
332 // implemented to guess sRGB in this case.
msarett6a738212016-03-04 13:27:35 -0800333 return nullptr;
334}
335
scroggod8d68552016-06-06 11:26:17 -0700336static int bytes_per_pixel(int bitsPerPixel) {
337 // Note that we will have to change this implementation if we start
338 // supporting outputs from libpng that are less than 8-bits per component.
339 return bitsPerPixel / 8;
340}
341
msarettd1ec89b2016-08-03 12:59:27 -0700342static bool png_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
343 // Ensure the alpha type is valid
344 if (!valid_alpha(dst.alphaType(), src.alphaType())) {
345 return false;
346 }
347
348 // Check for supported color types
349 switch (dst.colorType()) {
350 case kRGBA_8888_SkColorType:
351 case kBGRA_8888_SkColorType:
352 case kRGBA_F16_SkColorType:
353 return true;
354 case kRGB_565_SkColorType:
355 return kOpaque_SkAlphaType == src.alphaType();
356 default:
357 return dst.colorType() == src.colorType();
358 }
359}
360
361void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
362 const int width = this->getInfo().width();
363 size_t colorXformBytes = fColorXform ? width * sizeof(uint32_t) : 0;
364
365 fStorage.reset(SkAlign4(fSrcRowBytes) + colorXformBytes);
366 fSwizzlerSrcRow = fStorage.get();
367 fColorXformSrcRow =
368 fColorXform ? SkTAddOffset<uint32_t>(fSwizzlerSrcRow, SkAlign4(fSrcRowBytes)) : 0;
369}
370
371class SkPngNormalCodec : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700372public:
msarett549ca322016-08-17 08:54:08 -0700373 SkPngNormalCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
374 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
375 png_infop info_ptr, int bitDepth)
376 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, 1)
scroggo1c005e42015-08-04 09:24:45 -0700377 {}
378
scroggod8d68552016-06-06 11:26:17 -0700379 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
380 SkPMColor ctable[], int* ctableCount) override {
msarettd1ec89b2016-08-03 12:59:27 -0700381 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
382 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
383 {
scroggod8d68552016-06-06 11:26:17 -0700384 return kInvalidConversion;
385 }
386
msarettd1ec89b2016-08-03 12:59:27 -0700387 this->allocateStorage(dstInfo);
scroggod8d68552016-06-06 11:26:17 -0700388 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700389 }
390
msarettd1ec89b2016-08-03 12:59:27 -0700391 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, int startRow)
392 override {
393 SkASSERT(0 == startRow);
394
scroggod8d68552016-06-06 11:26:17 -0700395 // Assume that an error in libpng indicates an incomplete input.
msarettd1ec89b2016-08-03 12:59:27 -0700396 int y = 0;
397 if (setjmp(png_jmpbuf(fPng_ptr))) {
398 SkCodecPrintf("Failed to read row.\n");
399 return y;
scroggod8d68552016-06-06 11:26:17 -0700400 }
401
msarettd1ec89b2016-08-03 12:59:27 -0700402 void* swizzlerDstRow = dst;
403 size_t swizzlerDstRowBytes = rowBytes;
404 if (fColorXform) {
405 swizzlerDstRow = fColorXformSrcRow;
406 swizzlerDstRowBytes = 0;
scroggod8d68552016-06-06 11:26:17 -0700407 }
408
msarettd1ec89b2016-08-03 12:59:27 -0700409 SkAlphaType xformAlphaType = (kOpaque_SkAlphaType == this->getInfo().alphaType()) ?
410 kOpaque_SkAlphaType : dstInfo.alphaType();
411 for (; y < count; y++) {
412 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
413 fSwizzler->swizzle(swizzlerDstRow, fSwizzlerSrcRow);
414
415 if (fColorXform) {
416 fColorXform->apply(dst, (const uint32_t*) swizzlerDstRow, dstInfo.width(),
417 dstInfo.colorType(), xformAlphaType);
418 dst = SkTAddOffset<void>(dst, rowBytes);
419 }
420
421 swizzlerDstRow = SkTAddOffset<void>(swizzlerDstRow, swizzlerDstRowBytes);
422 }
423
424 return y;
425 }
426
427 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
428 return this->readRows(this->dstInfo(), dst, rowBytes, count, 0);
scroggo05245902015-03-25 11:11:52 -0700429 }
scroggod8d68552016-06-06 11:26:17 -0700430
431 bool onSkipScanlines(int count) override {
msarettd1ec89b2016-08-03 12:59:27 -0700432 if (setjmp(png_jmpbuf(fPng_ptr))) {
433 SkCodecPrintf("Failed to skip row.\n");
scroggod8d68552016-06-06 11:26:17 -0700434 return false;
435 }
436
437 for (int row = 0; row < count; row++) {
msarettd1ec89b2016-08-03 12:59:27 -0700438 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
scroggod8d68552016-06-06 11:26:17 -0700439 }
440 return true;
441 }
442
scroggo46c57472015-09-30 08:57:13 -0700443 typedef SkPngCodec INHERITED;
scroggo05245902015-03-25 11:11:52 -0700444};
445
scroggo26694c32016-06-01 12:08:23 -0700446
msarettd1ec89b2016-08-03 12:59:27 -0700447class SkPngInterlacedCodec : public SkPngCodec {
scroggod8d68552016-06-06 11:26:17 -0700448public:
msarett549ca322016-08-17 08:54:08 -0700449 SkPngInterlacedCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
scroggod8d68552016-06-06 11:26:17 -0700450 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
msarett549ca322016-08-17 08:54:08 -0700451 png_infop info_ptr, int bitDepth, int numberPasses)
452 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth,
453 numberPasses)
scroggod8d68552016-06-06 11:26:17 -0700454 , fCanSkipRewind(false)
455 {
456 SkASSERT(numberPasses != 1);
457 }
458
459 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
460 SkPMColor ctable[], int* ctableCount) override {
msarettd1ec89b2016-08-03 12:59:27 -0700461 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
462 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
463 {
scroggod8d68552016-06-06 11:26:17 -0700464 return kInvalidConversion;
465 }
466
msarettd1ec89b2016-08-03 12:59:27 -0700467 this->allocateStorage(dstInfo);
scroggod8d68552016-06-06 11:26:17 -0700468 fCanSkipRewind = true;
scroggod8d68552016-06-06 11:26:17 -0700469 return SkCodec::kSuccess;
470 }
471
msarettd1ec89b2016-08-03 12:59:27 -0700472 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, int startRow)
473 override {
474 if (setjmp(png_jmpbuf(fPng_ptr))) {
475 SkCodecPrintf("Failed to get scanlines.\n");
476 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
477 // we may be able to report that all of the memory has been initialized. Even if we
478 // fail on the first pass, we can still report than some scanlines are initialized.
479 return 0;
480 }
481
482 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
483 uint8_t* srcRow;
484 for (int i = 0; i < fNumberPasses; i++) {
485 // Discard rows that we planned to skip.
486 for (int y = 0; y < startRow; y++){
487 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
488 }
489 // Read rows we care about into storage.
490 srcRow = storage.get();
491 for (int y = 0; y < count; y++) {
492 png_read_row(fPng_ptr, srcRow, nullptr);
493 srcRow += fSrcRowBytes;
494 }
495 // Discard rows that we don't need.
496 for (int y = 0; y < this->getInfo().height() - startRow - count; y++) {
497 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
498 }
499 }
500
501 // Swizzle and xform the rows we care about
502 void* swizzlerDstRow = dst;
503 size_t swizzlerDstRowBytes = rowBytes;
504 if (fColorXform) {
505 swizzlerDstRow = fColorXformSrcRow;
506 swizzlerDstRowBytes = 0;
507 }
508
509 SkAlphaType xformAlphaType = (kOpaque_SkAlphaType == this->getInfo().alphaType()) ?
510 kOpaque_SkAlphaType : dstInfo.alphaType();
511 srcRow = storage.get();
512 for (int y = 0; y < count; y++) {
513 fSwizzler->swizzle(swizzlerDstRow, srcRow);
514 srcRow = SkTAddOffset<uint8_t>(srcRow, fSrcRowBytes);
515
516 if (fColorXform) {
517 if (fColorXform) {
518 fColorXform->apply(dst, (const uint32_t*) swizzlerDstRow, dstInfo.width(),
519 dstInfo.colorType(), xformAlphaType);
520 dst = SkTAddOffset<void>(dst, rowBytes);
521 }
522 }
523
524 swizzlerDstRow = SkTAddOffset<void>(swizzlerDstRow, swizzlerDstRowBytes);
525 }
526
527 return count;
528 }
529
530 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
scroggod8d68552016-06-06 11:26:17 -0700531 // rewind stream if have previously called onGetScanlines,
532 // since we need entire progressive image to get scanlines
533 if (fCanSkipRewind) {
534 // We already rewound in onStartScanlineDecode, so there is no reason to rewind.
535 // Next time onGetScanlines is called, we will need to rewind.
536 fCanSkipRewind = false;
537 } else {
538 // rewindIfNeeded resets fCurrScanline, since it assumes that start
539 // needs to be called again before scanline decoding. PNG scanline
540 // decoding is the exception, since it needs to rewind between
541 // calls to getScanlines. Keep track of fCurrScanline, to undo the
542 // reset.
543 const int currScanline = this->nextScanline();
544 // This method would never be called if currScanline is -1
545 SkASSERT(currScanline != -1);
546
547 if (!this->rewindIfNeeded()) {
548 return kCouldNotRewind;
549 }
550 this->updateCurrScanline(currScanline);
551 }
552
msarettd1ec89b2016-08-03 12:59:27 -0700553 return this->readRows(this->dstInfo(), dst, rowBytes, count, this->nextScanline());
scroggod8d68552016-06-06 11:26:17 -0700554 }
555
556 bool onSkipScanlines(int count) override {
557 // The non-virtual version will update fCurrScanline.
558 return true;
559 }
560
561 SkScanlineOrder onGetScanlineOrder() const override {
562 return kNone_SkScanlineOrder;
emmaleer8f4ba762015-08-14 07:44:46 -0700563 }
564
emmaleer0a4c3cb2015-06-22 10:40:21 -0700565private:
scroggod8d68552016-06-06 11:26:17 -0700566 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
567 // is called whenever some action is taken that reads the stream and
568 // therefore the next call will require a rewind. So it modifies a boolean
569 // to note that the *next* time it is called a rewind is needed.
msarettd1ec89b2016-08-03 12:59:27 -0700570 // SkPngInterlacedCodec has an extra wrinkle - calling
scroggod8d68552016-06-06 11:26:17 -0700571 // onStartScanlineDecode followed by onGetScanlines does *not* require a
572 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
573 // add another layer.
574 bool fCanSkipRewind;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700575
scroggo46c57472015-09-30 08:57:13 -0700576 typedef SkPngCodec INHERITED;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700577};
578
msarettac6c7502016-04-25 09:30:24 -0700579// Reads the header and initializes the output fields, if not NULL.
580//
581// @param stream Input data. Will be read to get enough information to properly
582// setup the codec.
583// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
584// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
585// expected to continue to own it for the lifetime of the png_ptr.
586// @param outCodec Optional output variable. If non-NULL, will be set to a new
587// SkPngCodec on success.
588// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
589// png_structp on success.
590// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
591// png_infop on success;
592// @return true on success, in which case the caller is responsible for calling
593// png_destroy_read_struct(png_ptrp, info_ptrp).
594// If it returns false, the passed in fields (except stream) are unchanged.
595static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec** outCodec,
596 png_structp* png_ptrp, png_infop* info_ptrp) {
597 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
598 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
599 sk_error_fn, sk_warning_fn);
600 if (!png_ptr) {
601 return false;
602 }
603
scroggod8d68552016-06-06 11:26:17 -0700604 AutoCleanPng autoClean(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700605
606 png_infop info_ptr = png_create_info_struct(png_ptr);
607 if (info_ptr == nullptr) {
608 return false;
609 }
610
611 autoClean.setInfoPtr(info_ptr);
612
613 // FIXME: Could we use the return value of setjmp to specify the type of
614 // error?
615 if (setjmp(png_jmpbuf(png_ptr))) {
616 return false;
617 }
618
scroggod8d68552016-06-06 11:26:17 -0700619 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
620
msarettac6c7502016-04-25 09:30:24 -0700621#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
622 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
623 // This needs to be installed before we read the png header. Android may store ninepatch
624 // chunks in the header.
625 if (chunkReader) {
626 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
627 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
628 }
629#endif
630
scroggod8d68552016-06-06 11:26:17 -0700631 // The call to png_read_info() gives us all of the information from the
632 // PNG file before the first IDAT (image data chunk).
633 png_read_info(png_ptr, info_ptr);
msarettac6c7502016-04-25 09:30:24 -0700634 png_uint_32 origWidth, origHeight;
635 int bitDepth, encodedColorType;
scroggod8d68552016-06-06 11:26:17 -0700636 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarettac6c7502016-04-25 09:30:24 -0700637 &encodedColorType, nullptr, nullptr, nullptr);
638
639 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
640 // TODO: Should we handle this in SkSwizzler? Could this also benefit
641 // RAW decodes?
642 if (bitDepth == 16) {
643 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggod8d68552016-06-06 11:26:17 -0700644 png_set_strip_16(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700645 }
646
647 // Now determine the default colorType and alphaType and set the required transforms.
648 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
649 // still depend on libpng for many of the rare and PNG-specific cases.
650 SkEncodedInfo::Color color;
651 SkEncodedInfo::Alpha alpha;
652 switch (encodedColorType) {
653 case PNG_COLOR_TYPE_PALETTE:
654 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
655 // byte into separate bytes (useful for paletted and grayscale images).
656 if (bitDepth < 8) {
657 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700658 png_set_packing(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700659 }
660
661 color = SkEncodedInfo::kPalette_Color;
662 // Set the alpha depending on if a transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700663 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
msarettac6c7502016-04-25 09:30:24 -0700664 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
665 break;
666 case PNG_COLOR_TYPE_RGB:
scroggod8d68552016-06-06 11:26:17 -0700667 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
msarettac6c7502016-04-25 09:30:24 -0700668 // Convert to RGBA if transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700669 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700670 color = SkEncodedInfo::kRGBA_Color;
671 alpha = SkEncodedInfo::kBinary_Alpha;
672 } else {
673 color = SkEncodedInfo::kRGB_Color;
674 alpha = SkEncodedInfo::kOpaque_Alpha;
675 }
676 break;
677 case PNG_COLOR_TYPE_GRAY:
678 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
679 if (bitDepth < 8) {
680 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700681 png_set_expand_gray_1_2_4_to_8(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700682 }
683
scroggod8d68552016-06-06 11:26:17 -0700684 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
685 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700686 color = SkEncodedInfo::kGrayAlpha_Color;
687 alpha = SkEncodedInfo::kBinary_Alpha;
688 } else {
689 color = SkEncodedInfo::kGray_Color;
690 alpha = SkEncodedInfo::kOpaque_Alpha;
691 }
692 break;
693 case PNG_COLOR_TYPE_GRAY_ALPHA:
694 color = SkEncodedInfo::kGrayAlpha_Color;
695 alpha = SkEncodedInfo::kUnpremul_Alpha;
696 break;
697 case PNG_COLOR_TYPE_RGBA:
698 color = SkEncodedInfo::kRGBA_Color;
699 alpha = SkEncodedInfo::kUnpremul_Alpha;
700 break;
701 default:
702 // All the color types have been covered above.
703 SkASSERT(false);
704 color = SkEncodedInfo::kRGBA_Color;
705 alpha = SkEncodedInfo::kUnpremul_Alpha;
706 }
707
scroggod8d68552016-06-06 11:26:17 -0700708 int numberPasses = png_set_interlace_handling(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700709
scroggod8d68552016-06-06 11:26:17 -0700710 autoClean.release();
711 if (png_ptrp) {
712 *png_ptrp = png_ptr;
scroggo9a89a092016-05-31 13:52:47 -0700713 }
scroggod8d68552016-06-06 11:26:17 -0700714 if (info_ptrp) {
715 *info_ptrp = info_ptr;
716 }
717
718 if (outCodec) {
719 sk_sp<SkColorSpace> colorSpace = read_color_space(png_ptr, info_ptr);
msarettf34cd632016-05-25 10:13:53 -0700720 if (!colorSpace) {
721 // Treat unmarked pngs as sRGB.
722 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
723 }
scroggod8d68552016-06-06 11:26:17 -0700724
msarett549ca322016-08-17 08:54:08 -0700725 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
726 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
727
728 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
729 png_color_8p sigBits;
730 if (png_get_sBIT(png_ptr, info_ptr, &sigBits)) {
731 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->blue) {
732 // Recommend a decode to 565 if the sBIT indicates 565.
733 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
734 }
735 }
736 }
scroggod8d68552016-06-06 11:26:17 -0700737
msarettac6c7502016-04-25 09:30:24 -0700738 if (1 == numberPasses) {
msarett549ca322016-08-17 08:54:08 -0700739 *outCodec = new SkPngNormalCodec(encodedInfo, imageInfo, stream,
740 chunkReader, png_ptr, info_ptr, bitDepth);
msarettac6c7502016-04-25 09:30:24 -0700741 } else {
msarett549ca322016-08-17 08:54:08 -0700742 *outCodec = new SkPngInterlacedCodec(encodedInfo, imageInfo, stream,
743 chunkReader, png_ptr, info_ptr, bitDepth, numberPasses);
msarettac6c7502016-04-25 09:30:24 -0700744 }
745 }
746
scroggod8d68552016-06-06 11:26:17 -0700747 return true;
msarettac6c7502016-04-25 09:30:24 -0700748}
749
msarett549ca322016-08-17 08:54:08 -0700750SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
751 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
752 png_infop info_ptr, int bitDepth, int numberPasses)
753 : INHERITED(encodedInfo, imageInfo, stream)
msarettac6c7502016-04-25 09:30:24 -0700754 , fPngChunkReader(SkSafeRef(chunkReader))
755 , fPng_ptr(png_ptr)
756 , fInfo_ptr(info_ptr)
msarettd1ec89b2016-08-03 12:59:27 -0700757 , fSwizzlerSrcRow(nullptr)
758 , fColorXformSrcRow(nullptr)
msarett549ca322016-08-17 08:54:08 -0700759 , fSrcRowBytes(imageInfo.width() * (bytes_per_pixel(this->getEncodedInfo().bitsPerPixel())))
scroggod8d68552016-06-06 11:26:17 -0700760 , fNumberPasses(numberPasses)
msarettac6c7502016-04-25 09:30:24 -0700761 , fBitDepth(bitDepth)
762{}
763
764SkPngCodec::~SkPngCodec() {
765 this->destroyReadStruct();
766}
767
768void SkPngCodec::destroyReadStruct() {
769 if (fPng_ptr) {
770 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
771 SkASSERT(fInfo_ptr);
772 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, nullptr);
773 fPng_ptr = nullptr;
774 fInfo_ptr = nullptr;
775 }
776}
777
778///////////////////////////////////////////////////////////////////////////////
779// Getting the pixels
780///////////////////////////////////////////////////////////////////////////////
781
msarettd1ec89b2016-08-03 12:59:27 -0700782bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& options,
783 SkPMColor ctable[], int* ctableCount) {
msarettac6c7502016-04-25 09:30:24 -0700784 if (setjmp(png_jmpbuf(fPng_ptr))) {
msarettd1ec89b2016-08-03 12:59:27 -0700785 SkCodecPrintf("Failed on png_read_update_info.\n");
786 return false;
msarettac6c7502016-04-25 09:30:24 -0700787 }
788 png_read_update_info(fPng_ptr, fInfo_ptr);
789
msarettd1ec89b2016-08-03 12:59:27 -0700790 // It's important to reset fColorXform to nullptr. We don't do this on rewinding
791 // because the interlaced scanline decoder may need to rewind.
792 fColorXform = nullptr;
793 SkImageInfo swizzlerInfo = dstInfo;
794 bool needsColorXform = needs_color_xform(dstInfo, this->getInfo());
795 if (needsColorXform) {
796 switch (dstInfo.colorType()) {
797 case kRGBA_8888_SkColorType:
798 case kBGRA_8888_SkColorType:
799 case kRGBA_F16_SkColorType:
800 swizzlerInfo = swizzlerInfo.makeColorType(kRGBA_8888_SkColorType);
801 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
802 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
803 }
804 break;
805 default:
806 return false;
807 }
808
809 fColorXform = SkColorSpaceXform::New(sk_ref_sp(this->getInfo().colorSpace()),
810 sk_ref_sp(dstInfo.colorSpace()));
811
812 if (!fColorXform && kRGBA_F16_SkColorType == dstInfo.colorType()) {
813 return false;
814 }
815 }
816
msarettac6c7502016-04-25 09:30:24 -0700817 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
msarettd1ec89b2016-08-03 12:59:27 -0700818 if (!this->createColorTable(swizzlerInfo.colorType(),
819 kPremul_SkAlphaType == swizzlerInfo.alphaType(), ctableCount)) {
820 return false;
msarettac6c7502016-04-25 09:30:24 -0700821 }
822 }
823
824 // Copy the color table to the client if they request kIndex8 mode
msarettd1ec89b2016-08-03 12:59:27 -0700825 copy_color_table(swizzlerInfo, fColorTable, ctable, ctableCount);
msarettac6c7502016-04-25 09:30:24 -0700826
827 // Create the swizzler. SkPngCodec retains ownership of the color table.
828 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettd1ec89b2016-08-03 12:59:27 -0700829 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colors, swizzlerInfo,
830 options));
msarettac6c7502016-04-25 09:30:24 -0700831 SkASSERT(fSwizzler);
msarettd1ec89b2016-08-03 12:59:27 -0700832 return true;
msarettac6c7502016-04-25 09:30:24 -0700833}
834
msarettac6c7502016-04-25 09:30:24 -0700835bool SkPngCodec::onRewind() {
836 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
837 // succeeds, they will be repopulated, and if it fails, they will
838 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
839 // come through this function which will rewind and again attempt
840 // to reinitialize them.
841 this->destroyReadStruct();
842
scroggo46c57472015-09-30 08:57:13 -0700843 png_structp png_ptr;
844 png_infop info_ptr;
msarettac6c7502016-04-25 09:30:24 -0700845 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, &info_ptr)) {
846 return false;
scroggo05245902015-03-25 11:11:52 -0700847 }
848
msarettac6c7502016-04-25 09:30:24 -0700849 fPng_ptr = png_ptr;
850 fInfo_ptr = info_ptr;
851 return true;
852}
msarett6a738212016-03-04 13:27:35 -0800853
msarettd1ec89b2016-08-03 12:59:27 -0700854SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
855 size_t rowBytes, const Options& options,
msarettac6c7502016-04-25 09:30:24 -0700856 SkPMColor ctable[], int* ctableCount,
857 int* rowsDecoded) {
msarettd1ec89b2016-08-03 12:59:27 -0700858 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
859 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
860 {
msarettac6c7502016-04-25 09:30:24 -0700861 return kInvalidConversion;
862 }
msarettd1ec89b2016-08-03 12:59:27 -0700863
msarettac6c7502016-04-25 09:30:24 -0700864 if (options.fSubset) {
msarettac6c7502016-04-25 09:30:24 -0700865 return kUnimplemented;
scroggo05245902015-03-25 11:11:52 -0700866 }
867
msarettd1ec89b2016-08-03 12:59:27 -0700868 this->allocateStorage(dstInfo);
869 int count = this->readRows(dstInfo, dst, rowBytes, dstInfo.height(), 0);
870 if (count > dstInfo.height()) {
871 *rowsDecoded = count;
872 return kIncompleteInput;
msarettac6c7502016-04-25 09:30:24 -0700873 }
874
scroggod8d68552016-06-06 11:26:17 -0700875 return kSuccess;
scroggo6fb23912016-06-02 14:16:43 -0700876}
877
msarettac6c7502016-04-25 09:30:24 -0700878uint32_t SkPngCodec::onGetFillValue(SkColorType colorType) const {
879 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
880 if (colorPtr) {
881 return get_color_table_fill_value(colorType, colorPtr, 0);
882 }
883 return INHERITED::onGetFillValue(colorType);
884}
885
886SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
887 SkAutoTDelete<SkStream> streamDeleter(stream);
888
scroggod8d68552016-06-06 11:26:17 -0700889 SkCodec* outCodec;
msarettac6c7502016-04-25 09:30:24 -0700890 if (read_header(stream, chunkReader, &outCodec, nullptr, nullptr)) {
891 // Codec has taken ownership of the stream.
892 SkASSERT(outCodec);
893 streamDeleter.release();
894 return outCodec;
895 }
896
897 return nullptr;
scroggo05245902015-03-25 11:11:52 -0700898}