blob: 0d73ad03f4793a985447c6e26dc5fd5453c1796d [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
msarettdcd5e652016-08-22 08:48:40 -070095static inline SkAlphaType xform_alpha_type(SkAlphaType dstAlphaType, SkAlphaType srcAlphaType) {
96 return (kOpaque_SkAlphaType == srcAlphaType) ? kOpaque_SkAlphaType : dstAlphaType;
97}
98
msarettd1ec89b2016-08-03 12:59:27 -070099// Note: SkColorTable claims to store SkPMColors, which is not necessarily the case here.
msarettdcd5e652016-08-22 08:48:40 -0700100bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) {
scroggof24f2242015-03-03 08:59:20 -0800101
msarett13a91232016-02-01 08:03:29 -0800102 int numColors;
103 png_color* palette;
104 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
scroggo05245902015-03-25 11:11:52 -0700105 return false;
scroggof24f2242015-03-03 08:59:20 -0800106 }
107
msarettdcd5e652016-08-22 08:48:40 -0700108 // Contents depend on tableColorType and our choice of if/when to premultiply:
109 // { kPremul, kUnpremul, kOpaque } x { RGBA, BGRA }
110 SkPMColor colorTable[256];
111 SkColorType tableColorType = fColorXform ? kRGBA_8888_SkColorType : dstInfo.colorType();
scroggof24f2242015-03-03 08:59:20 -0800112
msarett13a91232016-02-01 08:03:29 -0800113 png_bytep alphas;
114 int numColorsWithAlpha = 0;
115 if (png_get_tRNS(fPng_ptr, fInfo_ptr, &alphas, &numColorsWithAlpha, nullptr)) {
msarettdcd5e652016-08-22 08:48:40 -0700116 // If we are performing a color xform, it will handle the premultiply. Otherwise,
117 // we'll do it here.
118 bool premultiply = !fColorXform && needs_premul(dstInfo, this->getInfo());
119
msarett13a91232016-02-01 08:03:29 -0800120 // Choose which function to use to create the color table. If the final destination's
121 // colortype is unpremultiplied, the color table will store unpremultiplied colors.
msarettdcd5e652016-08-22 08:48:40 -0700122 PackColorProc proc = choose_pack_color_proc(premultiply, tableColorType);
msarett13a91232016-02-01 08:03:29 -0800123
124 for (int i = 0; i < numColorsWithAlpha; i++) {
125 // We don't have a function in SkOpts that combines a set of alphas with a set
126 // of RGBs. We could write one, but it's hardly worth it, given that this
127 // is such a small fraction of the total decode time.
msarettdcd5e652016-08-22 08:48:40 -0700128 colorTable[i] = proc(alphas[i], palette->red, palette->green, palette->blue);
msarett13a91232016-02-01 08:03:29 -0800129 palette++;
130 }
scroggof24f2242015-03-03 08:59:20 -0800131 }
132
msarett13a91232016-02-01 08:03:29 -0800133 if (numColorsWithAlpha < numColors) {
134 // The optimized code depends on a 3-byte png_color struct with the colors
135 // in RGB order. These checks make sure it is safe to use.
136 static_assert(3 == sizeof(png_color), "png_color struct has changed. Opts are broken.");
137#ifdef SK_DEBUG
138 SkASSERT(&palette->red < &palette->green);
139 SkASSERT(&palette->green < &palette->blue);
140#endif
141
msarettdcd5e652016-08-22 08:48:40 -0700142 if (is_rgba(tableColorType)) {
143 SkOpts::RGB_to_RGB1(colorTable + numColorsWithAlpha, palette,
msarett34e0ec42016-04-22 16:27:24 -0700144 numColors - numColorsWithAlpha);
145 } else {
msarettdcd5e652016-08-22 08:48:40 -0700146 SkOpts::RGB_to_BGR1(colorTable + numColorsWithAlpha, palette,
msarett34e0ec42016-04-22 16:27:24 -0700147 numColors - numColorsWithAlpha);
148 }
scroggof24f2242015-03-03 08:59:20 -0800149 }
150
msarettdcd5e652016-08-22 08:48:40 -0700151 // If we are not decoding to F16, we can color xform now and store the results
152 // in the color table.
153 if (fColorXform && kRGBA_F16_SkColorType != dstInfo.colorType()) {
154 SkColorType xformColorType = is_rgba(dstInfo.colorType()) ?
155 kRGBA_8888_SkColorType : kBGRA_8888_SkColorType;
156 SkAlphaType xformAlphaType = xform_alpha_type(dstInfo.alphaType(),
157 this->getInfo().alphaType());
158 fColorXform->apply(colorTable, colorTable, numColors, xformColorType, xformAlphaType);
159 }
160
msarett13a91232016-02-01 08:03:29 -0800161 // Pad the color table with the last color in the table (or black) in the case that
162 // invalid pixel indices exceed the number of colors in the table.
163 const int maxColors = 1 << fBitDepth;
164 if (numColors < maxColors) {
msarettdcd5e652016-08-22 08:48:40 -0700165 SkPMColor lastColor = numColors > 0 ? colorTable[numColors - 1] : SK_ColorBLACK;
166 sk_memset32(colorTable + numColors, lastColor, maxColors - numColors);
scroggof24f2242015-03-03 08:59:20 -0800167 }
168
msarett13a91232016-02-01 08:03:29 -0800169 // Set the new color count.
halcanary96fcdcc2015-08-27 07:41:13 -0700170 if (ctableCount != nullptr) {
msarett13a91232016-02-01 08:03:29 -0800171 *ctableCount = maxColors;
scroggof24f2242015-03-03 08:59:20 -0800172 }
173
msarettdcd5e652016-08-22 08:48:40 -0700174 fColorTable.reset(new SkColorTable(colorTable, maxColors));
scroggo05245902015-03-25 11:11:52 -0700175 return true;
scroggof24f2242015-03-03 08:59:20 -0800176}
177
178///////////////////////////////////////////////////////////////////////////////
179// Creation
180///////////////////////////////////////////////////////////////////////////////
181
scroggodb30be22015-12-08 18:54:13 -0800182bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
183 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
scroggof24f2242015-03-03 08:59:20 -0800184}
185
msarett6a738212016-03-04 13:27:35 -0800186static float png_fixed_point_to_float(png_fixed_point x) {
187 // We multiply by the same factor that libpng used to convert
188 // fixed point -> double. Since we want floats, we choose to
189 // do the conversion ourselves rather than convert
190 // fixed point -> double -> float.
191 return ((float) x) * 0.00001f;
192}
193
msarett128245c2016-03-30 12:01:47 -0700194static float png_inverted_fixed_point_to_float(png_fixed_point x) {
195 // This is necessary because the gAMA chunk actually stores 1/gamma.
196 return 1.0f / png_fixed_point_to_float(x);
197}
198
msarettc4ce6b52016-06-16 07:37:41 -0700199static constexpr float gSRGB_toXYZD50[] {
200 0.4358f, 0.2224f, 0.0139f, // * R
201 0.3853f, 0.7170f, 0.0971f, // * G
202 0.1430f, 0.0606f, 0.7139f, // * B
203};
204
msarett55447952016-07-22 14:07:23 -0700205static bool convert_to_D50(SkMatrix44* toXYZD50, float toXYZ[9], float whitePoint[2]) {
206 float wX = whitePoint[0];
207 float wY = whitePoint[1];
208 if (wX < 0.0f || wY < 0.0f || (wX + wY > 1.0f)) {
209 return false;
210 }
211
212 // Calculate the XYZ illuminant. Call this the src illuminant.
213 float wZ = 1.0f - wX - wY;
214 float scale = 1.0f / wY;
215 // TODO (msarett):
216 // What are common src illuminants? I'm guessing we will almost always see D65. Should
217 // we go ahead and save a precomputed D65->D50 Bradford matrix? Should we exit early if
218 // if the src illuminant is D50?
219 SkVector3 srcXYZ = SkVector3::Make(wX * scale, 1.0f, wZ * scale);
220
221 // The D50 illuminant.
222 SkVector3 dstXYZ = SkVector3::Make(0.96422f, 1.0f, 0.82521f);
223
224 // Calculate the chromatic adaptation matrix. We will use the Bradford method, thus
225 // the matrices below. The Bradford method is used by Adobe and is widely considered
226 // to be the best.
227 // http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html
228 SkMatrix mA, mAInv;
229 mA.setAll(0.8951f, 0.2664f, -0.1614f, -0.7502f, 1.7135f, 0.0367f, 0.0389f, -0.0685f, 1.0296f);
230 mAInv.setAll(0.9869929f, -0.1470543f, 0.1599627f, 0.4323053f, 0.5183603f, 0.0492912f,
231 -0.0085287f, 0.0400428f, 0.9684867f);
232
233 // Map illuminant into cone response domain.
234 SkVector3 srcCone;
235 srcCone.fX = mA[0] * srcXYZ.fX + mA[1] * srcXYZ.fY + mA[2] * srcXYZ.fZ;
236 srcCone.fY = mA[3] * srcXYZ.fX + mA[4] * srcXYZ.fY + mA[5] * srcXYZ.fZ;
237 srcCone.fZ = mA[6] * srcXYZ.fX + mA[7] * srcXYZ.fY + mA[8] * srcXYZ.fZ;
238 SkVector3 dstCone;
239 dstCone.fX = mA[0] * dstXYZ.fX + mA[1] * dstXYZ.fY + mA[2] * dstXYZ.fZ;
240 dstCone.fY = mA[3] * dstXYZ.fX + mA[4] * dstXYZ.fY + mA[5] * dstXYZ.fZ;
241 dstCone.fZ = mA[6] * dstXYZ.fX + mA[7] * dstXYZ.fY + mA[8] * dstXYZ.fZ;
242
243 SkMatrix DXToD50;
244 DXToD50.setIdentity();
245 DXToD50[0] = dstCone.fX / srcCone.fX;
246 DXToD50[4] = dstCone.fY / srcCone.fY;
247 DXToD50[8] = dstCone.fZ / srcCone.fZ;
248 DXToD50.postConcat(mAInv);
249 DXToD50.preConcat(mA);
250
251 SkMatrix toXYZ3x3;
252 toXYZ3x3.setAll(toXYZ[0], toXYZ[3], toXYZ[6], toXYZ[1], toXYZ[4], toXYZ[7], toXYZ[2], toXYZ[5],
253 toXYZ[8]);
254 toXYZ3x3.postConcat(DXToD50);
255
256 toXYZD50->set3x3(toXYZ3x3[0], toXYZ3x3[1], toXYZ3x3[2], toXYZ3x3[3], toXYZ3x3[4], toXYZ3x3[5],
257 toXYZ3x3[6], toXYZ3x3[7], toXYZ3x3[8]);
258 return true;
259}
260
msarett6a738212016-03-04 13:27:35 -0800261// Returns a colorSpace object that represents any color space information in
262// the encoded data. If the encoded data contains no color space, this will
263// return NULL.
msarettad8bcfe2016-03-07 07:09:03 -0800264sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
msarett6a738212016-03-04 13:27:35 -0800265
msarette2443222016-03-04 14:20:49 -0800266#if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 6)
267
msarett6a738212016-03-04 13:27:35 -0800268 // First check for an ICC profile
269 png_bytep profile;
270 png_uint_32 length;
271 // The below variables are unused, however, we need to pass them in anyway or
272 // png_get_iCCP() will return nothing.
273 // Could knowing the |name| of the profile ever be interesting? Maybe for debugging?
274 png_charp name;
275 // The |compression| is uninteresting since:
276 // (1) libpng has already decompressed the profile for us.
277 // (2) "deflate" is the only mode of decompression that libpng supports.
278 int compression;
279 if (PNG_INFO_iCCP == png_get_iCCP(png_ptr, info_ptr, &name, &compression, &profile,
280 &length)) {
281 return SkColorSpace::NewICC(profile, length);
282 }
283
284 // Second, check for sRGB.
285 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB)) {
286
287 // sRGB chunks also store a rendering intent: Absolute, Relative,
288 // Perceptual, and Saturation.
289 // FIXME (msarett): Extract this information from the sRGB chunk once
290 // we are able to handle this information in
291 // SkColorSpace.
292 return SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
293 }
294
295 // Next, check for chromaticities.
msarett55447952016-07-22 14:07:23 -0700296 png_fixed_point toXYZFixed[9];
297 float toXYZ[9];
298 png_fixed_point whitePointFixed[2];
299 float whitePoint[2];
msarett6a738212016-03-04 13:27:35 -0800300 png_fixed_point gamma;
msarettbb9f7742016-05-17 09:31:20 -0700301 float gammas[3];
msarett55447952016-07-22 14:07:23 -0700302 if (png_get_cHRM_XYZ_fixed(png_ptr, info_ptr, &toXYZFixed[0], &toXYZFixed[1], &toXYZFixed[2],
303 &toXYZFixed[3], &toXYZFixed[4], &toXYZFixed[5], &toXYZFixed[6],
304 &toXYZFixed[7], &toXYZFixed[8]) &&
305 png_get_cHRM_fixed(png_ptr, info_ptr, &whitePointFixed[0], &whitePointFixed[1], nullptr,
306 nullptr, nullptr, nullptr, nullptr, nullptr))
307 {
msarett6a738212016-03-04 13:27:35 -0800308 for (int i = 0; i < 9; i++) {
msarett55447952016-07-22 14:07:23 -0700309 toXYZ[i] = png_fixed_point_to_float(toXYZFixed[i]);
msarett6a738212016-03-04 13:27:35 -0800310 }
msarett55447952016-07-22 14:07:23 -0700311 whitePoint[0] = png_fixed_point_to_float(whitePointFixed[0]);
312 whitePoint[1] = png_fixed_point_to_float(whitePointFixed[1]);
313
314 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
315 if (!convert_to_D50(&toXYZD50, toXYZ, whitePoint)) {
316 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
317 }
msarett6a738212016-03-04 13:27:35 -0800318
msarett128245c2016-03-30 12:01:47 -0700319 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
msarettffc2aea2016-05-02 11:12:14 -0700320 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700321 gammas[0] = value;
322 gammas[1] = value;
323 gammas[2] = value;
msarettffc2aea2016-05-02 11:12:14 -0700324
msarett55447952016-07-22 14:07:23 -0700325 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800326 }
msarett128245c2016-03-30 12:01:47 -0700327
msarettc4ce6b52016-06-16 07:37:41 -0700328 // Default to sRGB gamma if the image has color space information,
329 // but does not specify gamma.
msarett55447952016-07-22 14:07:23 -0700330 return SkColorSpace::NewRGB(SkColorSpace::kSRGB_GammaNamed, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800331 }
332
333 // Last, check for gamma.
334 if (PNG_INFO_gAMA == png_get_gAMA_fixed(png_ptr, info_ptr, &gamma)) {
335
msarett6a738212016-03-04 13:27:35 -0800336 // Set the gammas.
msarettffc2aea2016-05-02 11:12:14 -0700337 float value = png_inverted_fixed_point_to_float(gamma);
msarettbb9f7742016-05-17 09:31:20 -0700338 gammas[0] = value;
339 gammas[1] = value;
340 gammas[2] = value;
msarett6a738212016-03-04 13:27:35 -0800341
msarettc4ce6b52016-06-16 07:37:41 -0700342 // Since there is no cHRM, we will guess sRGB gamut.
msarett55447952016-07-22 14:07:23 -0700343 SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
344 toXYZD50.set3x3RowMajorf(gSRGB_toXYZD50);
msarettc4ce6b52016-06-16 07:37:41 -0700345
msarett55447952016-07-22 14:07:23 -0700346 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
msarett6a738212016-03-04 13:27:35 -0800347 }
348
msarette2443222016-03-04 14:20:49 -0800349#endif // LIBPNG >= 1.6
350
msarettc4ce6b52016-06-16 07:37:41 -0700351 // Report that there is no color space information in the PNG. SkPngCodec is currently
352 // implemented to guess sRGB in this case.
msarett6a738212016-03-04 13:27:35 -0800353 return nullptr;
354}
355
scroggod8d68552016-06-06 11:26:17 -0700356static int bytes_per_pixel(int bitsPerPixel) {
357 // Note that we will have to change this implementation if we start
358 // supporting outputs from libpng that are less than 8-bits per component.
359 return bitsPerPixel / 8;
360}
361
msarettd1ec89b2016-08-03 12:59:27 -0700362static bool png_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {
363 // Ensure the alpha type is valid
364 if (!valid_alpha(dst.alphaType(), src.alphaType())) {
365 return false;
366 }
367
368 // Check for supported color types
369 switch (dst.colorType()) {
370 case kRGBA_8888_SkColorType:
371 case kBGRA_8888_SkColorType:
372 case kRGBA_F16_SkColorType:
373 return true;
374 case kRGB_565_SkColorType:
375 return kOpaque_SkAlphaType == src.alphaType();
376 default:
377 return dst.colorType() == src.colorType();
378 }
379}
380
msarett35bb74b2016-08-22 07:41:28 -0700381void SkPngCodec::allocateStorage() {
382 size_t colorXformBytes = fColorXform ? fSwizzler->swizzleWidth() * sizeof(uint32_t) : 0;
msarettd1ec89b2016-08-03 12:59:27 -0700383
384 fStorage.reset(SkAlign4(fSrcRowBytes) + colorXformBytes);
385 fSwizzlerSrcRow = fStorage.get();
386 fColorXformSrcRow =
387 fColorXform ? SkTAddOffset<uint32_t>(fSwizzlerSrcRow, SkAlign4(fSrcRowBytes)) : 0;
388}
389
msarettdcd5e652016-08-22 08:48:40 -0700390static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo::Color srcColor) {
391 // We will apply the color xform when reading the color table, unless F16 is requested.
392 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType;
393}
394
msarettd1ec89b2016-08-03 12:59:27 -0700395class SkPngNormalCodec : public SkPngCodec {
scroggo05245902015-03-25 11:11:52 -0700396public:
msarett549ca322016-08-17 08:54:08 -0700397 SkPngNormalCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
398 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
399 png_infop info_ptr, int bitDepth)
400 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth, 1)
scroggo1c005e42015-08-04 09:24:45 -0700401 {}
402
scroggod8d68552016-06-06 11:26:17 -0700403 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
404 SkPMColor ctable[], int* ctableCount) override {
msarettd1ec89b2016-08-03 12:59:27 -0700405 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
406 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
407 {
scroggod8d68552016-06-06 11:26:17 -0700408 return kInvalidConversion;
409 }
410
msarett35bb74b2016-08-22 07:41:28 -0700411 this->allocateStorage();
scroggod8d68552016-06-06 11:26:17 -0700412 return kSuccess;
scroggo05245902015-03-25 11:11:52 -0700413 }
414
msarettd1ec89b2016-08-03 12:59:27 -0700415 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, int startRow)
416 override {
417 SkASSERT(0 == startRow);
418
scroggod8d68552016-06-06 11:26:17 -0700419 // Assume that an error in libpng indicates an incomplete input.
msarettd1ec89b2016-08-03 12:59:27 -0700420 int y = 0;
421 if (setjmp(png_jmpbuf(fPng_ptr))) {
422 SkCodecPrintf("Failed to read row.\n");
423 return y;
scroggod8d68552016-06-06 11:26:17 -0700424 }
425
msarettd1ec89b2016-08-03 12:59:27 -0700426 void* swizzlerDstRow = dst;
427 size_t swizzlerDstRowBytes = rowBytes;
msarettdcd5e652016-08-22 08:48:40 -0700428
429 bool colorXform = fColorXform &&
430 apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color());
431 if (colorXform) {
msarettd1ec89b2016-08-03 12:59:27 -0700432 swizzlerDstRow = fColorXformSrcRow;
433 swizzlerDstRowBytes = 0;
scroggod8d68552016-06-06 11:26:17 -0700434 }
435
msarettdcd5e652016-08-22 08:48:40 -0700436 SkAlphaType xformAlphaType = xform_alpha_type(dstInfo.alphaType(),
437 this->getInfo().alphaType());
msarettd1ec89b2016-08-03 12:59:27 -0700438 for (; y < count; y++) {
439 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
440 fSwizzler->swizzle(swizzlerDstRow, fSwizzlerSrcRow);
441
msarettdcd5e652016-08-22 08:48:40 -0700442 if (colorXform) {
msarett35bb74b2016-08-22 07:41:28 -0700443 fColorXform->apply(dst, (const uint32_t*) swizzlerDstRow, fSwizzler->swizzleWidth(),
msarettd1ec89b2016-08-03 12:59:27 -0700444 dstInfo.colorType(), xformAlphaType);
445 dst = SkTAddOffset<void>(dst, rowBytes);
446 }
447
448 swizzlerDstRow = SkTAddOffset<void>(swizzlerDstRow, swizzlerDstRowBytes);
449 }
450
451 return y;
452 }
453
454 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
455 return this->readRows(this->dstInfo(), dst, rowBytes, count, 0);
scroggo05245902015-03-25 11:11:52 -0700456 }
scroggod8d68552016-06-06 11:26:17 -0700457
458 bool onSkipScanlines(int count) override {
msarettd1ec89b2016-08-03 12:59:27 -0700459 if (setjmp(png_jmpbuf(fPng_ptr))) {
460 SkCodecPrintf("Failed to skip row.\n");
scroggod8d68552016-06-06 11:26:17 -0700461 return false;
462 }
463
464 for (int row = 0; row < count; row++) {
msarettd1ec89b2016-08-03 12:59:27 -0700465 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
scroggod8d68552016-06-06 11:26:17 -0700466 }
467 return true;
468 }
469
scroggo46c57472015-09-30 08:57:13 -0700470 typedef SkPngCodec INHERITED;
scroggo05245902015-03-25 11:11:52 -0700471};
472
msarettd1ec89b2016-08-03 12:59:27 -0700473class SkPngInterlacedCodec : public SkPngCodec {
scroggod8d68552016-06-06 11:26:17 -0700474public:
msarett549ca322016-08-17 08:54:08 -0700475 SkPngInterlacedCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
scroggod8d68552016-06-06 11:26:17 -0700476 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
msarett549ca322016-08-17 08:54:08 -0700477 png_infop info_ptr, int bitDepth, int numberPasses)
478 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_ptr, bitDepth,
479 numberPasses)
scroggod8d68552016-06-06 11:26:17 -0700480 , fCanSkipRewind(false)
481 {
482 SkASSERT(numberPasses != 1);
483 }
484
485 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& options,
486 SkPMColor ctable[], int* ctableCount) override {
msarettd1ec89b2016-08-03 12:59:27 -0700487 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
488 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
489 {
scroggod8d68552016-06-06 11:26:17 -0700490 return kInvalidConversion;
491 }
492
msarett35bb74b2016-08-22 07:41:28 -0700493 this->allocateStorage();
scroggod8d68552016-06-06 11:26:17 -0700494 fCanSkipRewind = true;
scroggod8d68552016-06-06 11:26:17 -0700495 return SkCodec::kSuccess;
496 }
497
msarettd1ec89b2016-08-03 12:59:27 -0700498 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int count, int startRow)
499 override {
500 if (setjmp(png_jmpbuf(fPng_ptr))) {
501 SkCodecPrintf("Failed to get scanlines.\n");
502 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
503 // we may be able to report that all of the memory has been initialized. Even if we
504 // fail on the first pass, we can still report than some scanlines are initialized.
505 return 0;
506 }
507
508 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
509 uint8_t* srcRow;
510 for (int i = 0; i < fNumberPasses; i++) {
511 // Discard rows that we planned to skip.
512 for (int y = 0; y < startRow; y++){
513 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
514 }
515 // Read rows we care about into storage.
516 srcRow = storage.get();
517 for (int y = 0; y < count; y++) {
518 png_read_row(fPng_ptr, srcRow, nullptr);
519 srcRow += fSrcRowBytes;
520 }
521 // Discard rows that we don't need.
522 for (int y = 0; y < this->getInfo().height() - startRow - count; y++) {
523 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
524 }
525 }
526
527 // Swizzle and xform the rows we care about
528 void* swizzlerDstRow = dst;
529 size_t swizzlerDstRowBytes = rowBytes;
msarettdcd5e652016-08-22 08:48:40 -0700530
531 bool colorXform = fColorXform &&
532 apply_xform_on_decode(dstInfo.colorType(), this->getEncodedInfo().color());
533 if (colorXform) {
msarettd1ec89b2016-08-03 12:59:27 -0700534 swizzlerDstRow = fColorXformSrcRow;
535 swizzlerDstRowBytes = 0;
536 }
537
msarettdcd5e652016-08-22 08:48:40 -0700538 SkAlphaType xformAlphaType = xform_alpha_type(dstInfo.alphaType(),
539 this->getInfo().alphaType());
msarettd1ec89b2016-08-03 12:59:27 -0700540 srcRow = storage.get();
541 for (int y = 0; y < count; y++) {
542 fSwizzler->swizzle(swizzlerDstRow, srcRow);
543 srcRow = SkTAddOffset<uint8_t>(srcRow, fSrcRowBytes);
544
msarettdcd5e652016-08-22 08:48:40 -0700545 if (colorXform) {
546 fColorXform->apply(dst, (const uint32_t*) swizzlerDstRow, fSwizzler->swizzleWidth(),
547 dstInfo.colorType(), xformAlphaType);
548 dst = SkTAddOffset<void>(dst, rowBytes);
msarettd1ec89b2016-08-03 12:59:27 -0700549 }
550
551 swizzlerDstRow = SkTAddOffset<void>(swizzlerDstRow, swizzlerDstRowBytes);
552 }
553
554 return count;
555 }
556
557 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
scroggod8d68552016-06-06 11:26:17 -0700558 // rewind stream if have previously called onGetScanlines,
559 // since we need entire progressive image to get scanlines
560 if (fCanSkipRewind) {
561 // We already rewound in onStartScanlineDecode, so there is no reason to rewind.
562 // Next time onGetScanlines is called, we will need to rewind.
563 fCanSkipRewind = false;
564 } else {
565 // rewindIfNeeded resets fCurrScanline, since it assumes that start
566 // needs to be called again before scanline decoding. PNG scanline
567 // decoding is the exception, since it needs to rewind between
568 // calls to getScanlines. Keep track of fCurrScanline, to undo the
569 // reset.
570 const int currScanline = this->nextScanline();
571 // This method would never be called if currScanline is -1
572 SkASSERT(currScanline != -1);
573
574 if (!this->rewindIfNeeded()) {
575 return kCouldNotRewind;
576 }
577 this->updateCurrScanline(currScanline);
578 }
579
msarettd1ec89b2016-08-03 12:59:27 -0700580 return this->readRows(this->dstInfo(), dst, rowBytes, count, this->nextScanline());
scroggod8d68552016-06-06 11:26:17 -0700581 }
582
583 bool onSkipScanlines(int count) override {
584 // The non-virtual version will update fCurrScanline.
585 return true;
586 }
587
588 SkScanlineOrder onGetScanlineOrder() const override {
589 return kNone_SkScanlineOrder;
emmaleer8f4ba762015-08-14 07:44:46 -0700590 }
591
emmaleer0a4c3cb2015-06-22 10:40:21 -0700592private:
scroggod8d68552016-06-06 11:26:17 -0700593 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
594 // is called whenever some action is taken that reads the stream and
595 // therefore the next call will require a rewind. So it modifies a boolean
596 // to note that the *next* time it is called a rewind is needed.
msarettd1ec89b2016-08-03 12:59:27 -0700597 // SkPngInterlacedCodec has an extra wrinkle - calling
scroggod8d68552016-06-06 11:26:17 -0700598 // onStartScanlineDecode followed by onGetScanlines does *not* require a
599 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
600 // add another layer.
601 bool fCanSkipRewind;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700602
scroggo46c57472015-09-30 08:57:13 -0700603 typedef SkPngCodec INHERITED;
emmaleer0a4c3cb2015-06-22 10:40:21 -0700604};
605
msarettac6c7502016-04-25 09:30:24 -0700606// Reads the header and initializes the output fields, if not NULL.
607//
608// @param stream Input data. Will be read to get enough information to properly
609// setup the codec.
610// @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
611// If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
612// expected to continue to own it for the lifetime of the png_ptr.
613// @param outCodec Optional output variable. If non-NULL, will be set to a new
614// SkPngCodec on success.
615// @param png_ptrp Optional output variable. If non-NULL, will be set to a new
616// png_structp on success.
617// @param info_ptrp Optional output variable. If non-NULL, will be set to a new
618// png_infop on success;
619// @return true on success, in which case the caller is responsible for calling
620// png_destroy_read_struct(png_ptrp, info_ptrp).
621// If it returns false, the passed in fields (except stream) are unchanged.
622static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec** outCodec,
623 png_structp* png_ptrp, png_infop* info_ptrp) {
624 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
625 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
626 sk_error_fn, sk_warning_fn);
627 if (!png_ptr) {
628 return false;
629 }
630
scroggod8d68552016-06-06 11:26:17 -0700631 AutoCleanPng autoClean(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700632
633 png_infop info_ptr = png_create_info_struct(png_ptr);
634 if (info_ptr == nullptr) {
635 return false;
636 }
637
638 autoClean.setInfoPtr(info_ptr);
639
640 // FIXME: Could we use the return value of setjmp to specify the type of
641 // error?
642 if (setjmp(png_jmpbuf(png_ptr))) {
643 return false;
644 }
645
scroggod8d68552016-06-06 11:26:17 -0700646 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
647
msarettac6c7502016-04-25 09:30:24 -0700648#ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
649 // Hookup our chunkReader so we can see any user-chunks the caller may be interested in.
650 // This needs to be installed before we read the png header. Android may store ninepatch
651 // chunks in the header.
652 if (chunkReader) {
653 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte*)"", 0);
654 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_user_chunk);
655 }
656#endif
657
scroggod8d68552016-06-06 11:26:17 -0700658 // The call to png_read_info() gives us all of the information from the
659 // PNG file before the first IDAT (image data chunk).
660 png_read_info(png_ptr, info_ptr);
msarettac6c7502016-04-25 09:30:24 -0700661 png_uint_32 origWidth, origHeight;
662 int bitDepth, encodedColorType;
scroggod8d68552016-06-06 11:26:17 -0700663 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
msarettac6c7502016-04-25 09:30:24 -0700664 &encodedColorType, nullptr, nullptr, nullptr);
665
666 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
667 // TODO: Should we handle this in SkSwizzler? Could this also benefit
668 // RAW decodes?
669 if (bitDepth == 16) {
670 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
scroggod8d68552016-06-06 11:26:17 -0700671 png_set_strip_16(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700672 }
673
674 // Now determine the default colorType and alphaType and set the required transforms.
675 // Often, we depend on SkSwizzler to perform any transforms that we need. However, we
676 // still depend on libpng for many of the rare and PNG-specific cases.
677 SkEncodedInfo::Color color;
678 SkEncodedInfo::Alpha alpha;
679 switch (encodedColorType) {
680 case PNG_COLOR_TYPE_PALETTE:
681 // Extract multiple pixels with bit depths of 1, 2, and 4 from a single
682 // byte into separate bytes (useful for paletted and grayscale images).
683 if (bitDepth < 8) {
684 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700685 png_set_packing(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700686 }
687
688 color = SkEncodedInfo::kPalette_Color;
689 // Set the alpha depending on if a transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700690 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ?
msarettac6c7502016-04-25 09:30:24 -0700691 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
692 break;
693 case PNG_COLOR_TYPE_RGB:
scroggod8d68552016-06-06 11:26:17 -0700694 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
msarettac6c7502016-04-25 09:30:24 -0700695 // Convert to RGBA if transparency chunk exists.
scroggod8d68552016-06-06 11:26:17 -0700696 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700697 color = SkEncodedInfo::kRGBA_Color;
698 alpha = SkEncodedInfo::kBinary_Alpha;
699 } else {
700 color = SkEncodedInfo::kRGB_Color;
701 alpha = SkEncodedInfo::kOpaque_Alpha;
702 }
703 break;
704 case PNG_COLOR_TYPE_GRAY:
705 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel.
706 if (bitDepth < 8) {
707 // TODO: Should we use SkSwizzler here?
scroggod8d68552016-06-06 11:26:17 -0700708 png_set_expand_gray_1_2_4_to_8(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700709 }
710
scroggod8d68552016-06-06 11:26:17 -0700711 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
712 png_set_tRNS_to_alpha(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700713 color = SkEncodedInfo::kGrayAlpha_Color;
714 alpha = SkEncodedInfo::kBinary_Alpha;
715 } else {
716 color = SkEncodedInfo::kGray_Color;
717 alpha = SkEncodedInfo::kOpaque_Alpha;
718 }
719 break;
720 case PNG_COLOR_TYPE_GRAY_ALPHA:
721 color = SkEncodedInfo::kGrayAlpha_Color;
722 alpha = SkEncodedInfo::kUnpremul_Alpha;
723 break;
724 case PNG_COLOR_TYPE_RGBA:
725 color = SkEncodedInfo::kRGBA_Color;
726 alpha = SkEncodedInfo::kUnpremul_Alpha;
727 break;
728 default:
729 // All the color types have been covered above.
730 SkASSERT(false);
731 color = SkEncodedInfo::kRGBA_Color;
732 alpha = SkEncodedInfo::kUnpremul_Alpha;
733 }
734
scroggod8d68552016-06-06 11:26:17 -0700735 int numberPasses = png_set_interlace_handling(png_ptr);
msarettac6c7502016-04-25 09:30:24 -0700736
scroggod8d68552016-06-06 11:26:17 -0700737 autoClean.release();
738 if (png_ptrp) {
739 *png_ptrp = png_ptr;
scroggo9a89a092016-05-31 13:52:47 -0700740 }
scroggod8d68552016-06-06 11:26:17 -0700741 if (info_ptrp) {
742 *info_ptrp = info_ptr;
743 }
744
745 if (outCodec) {
746 sk_sp<SkColorSpace> colorSpace = read_color_space(png_ptr, info_ptr);
msarettf34cd632016-05-25 10:13:53 -0700747 if (!colorSpace) {
748 // Treat unmarked pngs as sRGB.
749 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
750 }
scroggod8d68552016-06-06 11:26:17 -0700751
msarett549ca322016-08-17 08:54:08 -0700752 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
753 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
754
755 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
756 png_color_8p sigBits;
757 if (png_get_sBIT(png_ptr, info_ptr, &sigBits)) {
758 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->blue) {
759 // Recommend a decode to 565 if the sBIT indicates 565.
760 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
761 }
762 }
763 }
scroggod8d68552016-06-06 11:26:17 -0700764
msarettac6c7502016-04-25 09:30:24 -0700765 if (1 == numberPasses) {
msarett549ca322016-08-17 08:54:08 -0700766 *outCodec = new SkPngNormalCodec(encodedInfo, imageInfo, stream,
767 chunkReader, png_ptr, info_ptr, bitDepth);
msarettac6c7502016-04-25 09:30:24 -0700768 } else {
msarett549ca322016-08-17 08:54:08 -0700769 *outCodec = new SkPngInterlacedCodec(encodedInfo, imageInfo, stream,
770 chunkReader, png_ptr, info_ptr, bitDepth, numberPasses);
msarettac6c7502016-04-25 09:30:24 -0700771 }
772 }
773
scroggod8d68552016-06-06 11:26:17 -0700774 return true;
msarettac6c7502016-04-25 09:30:24 -0700775}
776
msarett549ca322016-08-17 08:54:08 -0700777SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageInfo,
778 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr,
779 png_infop info_ptr, int bitDepth, int numberPasses)
780 : INHERITED(encodedInfo, imageInfo, stream)
msarettac6c7502016-04-25 09:30:24 -0700781 , fPngChunkReader(SkSafeRef(chunkReader))
782 , fPng_ptr(png_ptr)
783 , fInfo_ptr(info_ptr)
msarettd1ec89b2016-08-03 12:59:27 -0700784 , fSwizzlerSrcRow(nullptr)
785 , fColorXformSrcRow(nullptr)
msarett549ca322016-08-17 08:54:08 -0700786 , fSrcRowBytes(imageInfo.width() * (bytes_per_pixel(this->getEncodedInfo().bitsPerPixel())))
scroggod8d68552016-06-06 11:26:17 -0700787 , fNumberPasses(numberPasses)
msarettac6c7502016-04-25 09:30:24 -0700788 , fBitDepth(bitDepth)
789{}
790
791SkPngCodec::~SkPngCodec() {
792 this->destroyReadStruct();
793}
794
795void SkPngCodec::destroyReadStruct() {
796 if (fPng_ptr) {
797 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
798 SkASSERT(fInfo_ptr);
799 png_destroy_read_struct(&fPng_ptr, &fInfo_ptr, nullptr);
800 fPng_ptr = nullptr;
801 fInfo_ptr = nullptr;
802 }
803}
804
805///////////////////////////////////////////////////////////////////////////////
806// Getting the pixels
807///////////////////////////////////////////////////////////////////////////////
808
msarettd1ec89b2016-08-03 12:59:27 -0700809bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& options,
810 SkPMColor ctable[], int* ctableCount) {
msarettac6c7502016-04-25 09:30:24 -0700811 if (setjmp(png_jmpbuf(fPng_ptr))) {
msarettd1ec89b2016-08-03 12:59:27 -0700812 SkCodecPrintf("Failed on png_read_update_info.\n");
813 return false;
msarettac6c7502016-04-25 09:30:24 -0700814 }
815 png_read_update_info(fPng_ptr, fInfo_ptr);
816
msarettd1ec89b2016-08-03 12:59:27 -0700817 // It's important to reset fColorXform to nullptr. We don't do this on rewinding
818 // because the interlaced scanline decoder may need to rewind.
819 fColorXform = nullptr;
820 SkImageInfo swizzlerInfo = dstInfo;
msarettd3317422016-08-22 13:00:05 -0700821 Options swizzlerOptions = options;
msarettd1ec89b2016-08-03 12:59:27 -0700822 bool needsColorXform = needs_color_xform(dstInfo, this->getInfo());
823 if (needsColorXform) {
824 switch (dstInfo.colorType()) {
825 case kRGBA_8888_SkColorType:
826 case kBGRA_8888_SkColorType:
827 case kRGBA_F16_SkColorType:
828 swizzlerInfo = swizzlerInfo.makeColorType(kRGBA_8888_SkColorType);
829 if (kPremul_SkAlphaType == dstInfo.alphaType()) {
830 swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
831 }
832 break;
msarettdcd5e652016-08-22 08:48:40 -0700833 case kIndex_8_SkColorType:
834 break;
msarettd1ec89b2016-08-03 12:59:27 -0700835 default:
836 return false;
837 }
838
839 fColorXform = SkColorSpaceXform::New(sk_ref_sp(this->getInfo().colorSpace()),
840 sk_ref_sp(dstInfo.colorSpace()));
841
842 if (!fColorXform && kRGBA_F16_SkColorType == dstInfo.colorType()) {
843 return false;
844 }
msarettd3317422016-08-22 13:00:05 -0700845
846 // When there is a color xform, we swizzle into temporary memory, which is not
847 // zero initialized.
848 // FIXME (msarett):
849 // Is this a problem?
850 swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
msarettd1ec89b2016-08-03 12:59:27 -0700851 }
852
msarettac6c7502016-04-25 09:30:24 -0700853 if (SkEncodedInfo::kPalette_Color == this->getEncodedInfo().color()) {
msarettdcd5e652016-08-22 08:48:40 -0700854 if (!this->createColorTable(dstInfo, ctableCount)) {
msarettd1ec89b2016-08-03 12:59:27 -0700855 return false;
msarettac6c7502016-04-25 09:30:24 -0700856 }
857 }
858
859 // Copy the color table to the client if they request kIndex8 mode
msarettd1ec89b2016-08-03 12:59:27 -0700860 copy_color_table(swizzlerInfo, fColorTable, ctable, ctableCount);
msarettac6c7502016-04-25 09:30:24 -0700861
862 // Create the swizzler. SkPngCodec retains ownership of the color table.
863 const SkPMColor* colors = get_color_ptr(fColorTable.get());
msarettd1ec89b2016-08-03 12:59:27 -0700864 fSwizzler.reset(SkSwizzler::CreateSwizzler(this->getEncodedInfo(), colors, swizzlerInfo,
msarettd3317422016-08-22 13:00:05 -0700865 swizzlerOptions));
msarettac6c7502016-04-25 09:30:24 -0700866 SkASSERT(fSwizzler);
msarettd1ec89b2016-08-03 12:59:27 -0700867 return true;
msarettac6c7502016-04-25 09:30:24 -0700868}
869
msarettac6c7502016-04-25 09:30:24 -0700870bool SkPngCodec::onRewind() {
871 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
872 // succeeds, they will be repopulated, and if it fails, they will
873 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
874 // come through this function which will rewind and again attempt
875 // to reinitialize them.
876 this->destroyReadStruct();
877
scroggo46c57472015-09-30 08:57:13 -0700878 png_structp png_ptr;
879 png_infop info_ptr;
msarettac6c7502016-04-25 09:30:24 -0700880 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, &info_ptr)) {
881 return false;
scroggo05245902015-03-25 11:11:52 -0700882 }
883
msarettac6c7502016-04-25 09:30:24 -0700884 fPng_ptr = png_ptr;
885 fInfo_ptr = info_ptr;
886 return true;
887}
msarett6a738212016-03-04 13:27:35 -0800888
msarettd1ec89b2016-08-03 12:59:27 -0700889SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
890 size_t rowBytes, const Options& options,
msarettac6c7502016-04-25 09:30:24 -0700891 SkPMColor ctable[], int* ctableCount,
892 int* rowsDecoded) {
msarettd1ec89b2016-08-03 12:59:27 -0700893 if (!png_conversion_possible(dstInfo, this->getInfo()) ||
894 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
895 {
msarettac6c7502016-04-25 09:30:24 -0700896 return kInvalidConversion;
897 }
msarettd1ec89b2016-08-03 12:59:27 -0700898
msarettac6c7502016-04-25 09:30:24 -0700899 if (options.fSubset) {
msarettac6c7502016-04-25 09:30:24 -0700900 return kUnimplemented;
scroggo05245902015-03-25 11:11:52 -0700901 }
902
msarett35bb74b2016-08-22 07:41:28 -0700903 this->allocateStorage();
msarettd1ec89b2016-08-03 12:59:27 -0700904 int count = this->readRows(dstInfo, dst, rowBytes, dstInfo.height(), 0);
905 if (count > dstInfo.height()) {
906 *rowsDecoded = count;
907 return kIncompleteInput;
msarettac6c7502016-04-25 09:30:24 -0700908 }
909
scroggod8d68552016-06-06 11:26:17 -0700910 return kSuccess;
scroggo6fb23912016-06-02 14:16:43 -0700911}
912
msarettac6c7502016-04-25 09:30:24 -0700913uint32_t SkPngCodec::onGetFillValue(SkColorType colorType) const {
914 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
915 if (colorPtr) {
916 return get_color_table_fill_value(colorType, colorPtr, 0);
917 }
918 return INHERITED::onGetFillValue(colorType);
919}
920
921SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkReader) {
922 SkAutoTDelete<SkStream> streamDeleter(stream);
923
scroggod8d68552016-06-06 11:26:17 -0700924 SkCodec* outCodec;
msarettac6c7502016-04-25 09:30:24 -0700925 if (read_header(stream, chunkReader, &outCodec, nullptr, nullptr)) {
926 // Codec has taken ownership of the stream.
927 SkASSERT(outCodec);
928 streamDeleter.release();
929 return outCodec;
930 }
931
932 return nullptr;
scroggo05245902015-03-25 11:11:52 -0700933}