Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(349)

Side by Side Diff: src/codec/SkPngCodec.cpp

Issue 1997703003: Make SkPngCodec decode progressively. (Closed) Base URL: https://skia.googlesource.com/skia.git@foil
Patch Set: Rebase Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/codec/SkPngCodec.h ('k') | src/codec/SkSampledCodec.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 /* 1 /*
2 * Copyright 2015 Google Inc. 2 * Copyright 2015 Google Inc.
3 * 3 *
4 * Use of this source code is governed by a BSD-style license that can be 4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file. 5 * found in the LICENSE file.
6 */ 6 */
7 7
8 #include "SkBitmap.h" 8 #include "SkBitmap.h"
9 #include "SkCodecPriv.h" 9 #include "SkCodecPriv.h"
10 #include "SkColorPriv.h" 10 #include "SkColorPriv.h"
11 #include "SkColorSpace_Base.h" 11 #include "SkColorSpace_Base.h"
12 #include "SkColorTable.h" 12 #include "SkColorTable.h"
13 #include "SkMath.h" 13 #include "SkMath.h"
14 #include "SkOpts.h" 14 #include "SkOpts.h"
15 #include "SkPngCodec.h" 15 #include "SkPngCodec.h"
16 #include "SkPoint3.h" 16 #include "SkPoint3.h"
17 #include "SkSize.h" 17 #include "SkSize.h"
18 #include "SkStream.h" 18 #include "SkStream.h"
19 #include "SkSwizzler.h" 19 #include "SkSwizzler.h"
20 #include "SkTemplates.h" 20 #include "SkTemplates.h"
21 #include "SkUtils.h" 21 #include "SkUtils.h"
22 22
23 #include "png.h" 23 #include "png.h"
24 24
25 // This warning triggers false postives way too often in here. 25 // This warning triggers false postives way too often in here.
26 #if defined(__GNUC__) && !defined(__clang__) 26 #if defined(__GNUC__) && !defined(__clang__)
27 #pragma GCC diagnostic ignored "-Wclobbered" 27 #pragma GCC diagnostic ignored "-Wclobbered"
28 #endif 28 #endif
29 29
30 #if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MIN OR >= 5)
31 // This is not needed with version 1.5
32 #undef SK_GOOGLE3_PNG_HACK
33 #endif
34
35 // FIXME (scroggo): We can use png_jumpbuf directly once Google3 is on 1.6
36 #define PNG_JMPBUF(x) png_jmpbuf((png_structp) x)
37
30 /////////////////////////////////////////////////////////////////////////////// 38 ///////////////////////////////////////////////////////////////////////////////
31 // Callback functions 39 // Callback functions
32 /////////////////////////////////////////////////////////////////////////////// 40 ///////////////////////////////////////////////////////////////////////////////
33 41
42 // When setjmp is first called, it returns 0, meaning longjmp was not called.
43 constexpr int kSetJmpOkay = 0;
44 // An error internal to libpng.
45 constexpr int kPngError = 1;
46 // Passed to longjmp when we have decoded as many lines as we need.
47 constexpr int kStopDecoding = 2;
48
34 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) { 49 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
35 SkCodecPrintf("------ png error %s\n", msg); 50 SkCodecPrintf("------ png error %s\n", msg);
36 longjmp(png_jmpbuf(png_ptr), 1); 51 longjmp(PNG_JMPBUF(png_ptr), kPngError);
37 } 52 }
38 53
39 void sk_warning_fn(png_structp, png_const_charp msg) { 54 void sk_warning_fn(png_structp, png_const_charp msg) {
40 SkCodecPrintf("----- png warning %s\n", msg); 55 SkCodecPrintf("----- png warning %s\n", msg);
41 } 56 }
42 57
43 static void sk_read_fn(png_structp png_ptr, png_bytep data,
44 png_size_t length) {
45 SkStream* stream = static_cast<SkStream*>(png_get_io_ptr(png_ptr));
46 const size_t bytes = stream->read(data, length);
47 if (bytes != length) {
48 // FIXME: We want to report the fact that the stream was truncated.
49 // One way to do that might be to pass a enum to longjmp so setjmp can
50 // specify the failure.
51 png_error(png_ptr, "Read Error!");
52 }
53 }
54
55 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED 58 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
56 static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) { 59 static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) {
57 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(pn g_ptr); 60 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(pn g_ptr);
58 // readChunk() returning true means continue decoding 61 // readChunk() returning true means continue decoding
59 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk-> size) ? 1 : -1; 62 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk-> size) ? 1 : -1;
60 } 63 }
61 #endif 64 #endif
62 65
63 /////////////////////////////////////////////////////////////////////////////// 66 ///////////////////////////////////////////////////////////////////////////////
64 // Helpers 67 // Helpers
65 /////////////////////////////////////////////////////////////////////////////// 68 ///////////////////////////////////////////////////////////////////////////////
66 69
67 class AutoCleanPng : public SkNoncopyable { 70 class AutoCleanPng : public SkNoncopyable {
68 public: 71 public:
69 AutoCleanPng(png_structp png_ptr) 72 /*
73 * This class does not take ownership of stream or reader, but if codecPtr
74 * is non-NULL, and decodeBounds succeeds, it will have created a new
75 * SkCodec (pointed to by *codecPtr) which will own/ref them, as well as
76 * the png_ptr and info_ptr.
77 */
78 AutoCleanPng(png_structp png_ptr, SkStream* stream, SkPngChunkReader* reader ,
79 SkCodec** codecPtr)
70 : fPng_ptr(png_ptr) 80 : fPng_ptr(png_ptr)
71 , fInfo_ptr(nullptr) {} 81 , fInfo_ptr(nullptr)
82 , fDecodedBounds(false)
83 , fReadHeader(false)
84 , fStream(stream)
85 , fChunkReader(reader)
86 , fOutCodec(codecPtr)
87 {}
72 88
73 ~AutoCleanPng() { 89 ~AutoCleanPng() {
74 // fInfo_ptr will never be non-nullptr unless fPng_ptr is. 90 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
75 if (fPng_ptr) { 91 if (fPng_ptr) {
76 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr; 92 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
77 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr); 93 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
78 } 94 }
79 } 95 }
80 96
81 void setInfoPtr(png_infop info_ptr) { 97 void setInfoPtr(png_infop info_ptr) {
82 SkASSERT(nullptr == fInfo_ptr); 98 SkASSERT(nullptr == fInfo_ptr);
83 fInfo_ptr = info_ptr; 99 fInfo_ptr = info_ptr;
84 } 100 }
85 101
86 void release() { 102 /**
103 * Reads enough of the input stream to decode the bounds.
104 * @return false if the stream is not a valid PNG (or too short).
105 * true if it read enough of the stream to determine the bounds.
106 * In the latter case, the stream may have been read beyond the
107 * point to determine the bounds, and the png_ptr will have saved
108 * any extra data. Further, if the codecPtr supplied to the
109 * constructor was not NULL, it will now point to a new SkCodec,
110 * which owns (or refs, in the case of the SkPngChunkReader) the
111 * inputs. If codecPtr was NULL, the png_ptr and info_ptr are
112 * unowned, and it is up to the caller to destroy them.
113 */
114 bool decodeBounds();
115
116 private:
117 png_structp fPng_ptr;
118 png_infop fInfo_ptr;
119 bool fDecodedBounds;
120 bool fReadHeader;
121 SkStream* fStream;
122 SkPngChunkReader* fChunkReader;
123 SkCodec** fOutCodec;
124
125 /**
126 * Supplied to libpng to call when it has read enough data to determine
127 * bounds.
128 */
129 static void InfoCallback(png_structp png_ptr, png_infop) {
130 // png_get_progressive_ptr returns the pointer we set on the png_ptr wit h
131 // png_set_progressive_read_fn
132 static_cast<AutoCleanPng*>(png_get_progressive_ptr(png_ptr))->infoCallba ck();
133 }
134
135 void infoCallback();
136
137 #ifdef SK_GOOGLE3_PNG_HACK
138 // public so it can be called by SkPngCodec::rereadHeaderIfNecessary().
139 public:
140 #endif
141 void releasePngPtrs() {
87 fPng_ptr = nullptr; 142 fPng_ptr = nullptr;
88 fInfo_ptr = nullptr; 143 fInfo_ptr = nullptr;
89 } 144 }
90
91 private:
92 png_structp fPng_ptr;
93 png_infop fInfo_ptr;
94 }; 145 };
95 #define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng) 146 #define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
96 147
148 bool AutoCleanPng::decodeBounds() {
149 if (setjmp(PNG_JMPBUF(fPng_ptr))) {
150 return false;
151 }
152
153 png_set_progressive_read_fn(fPng_ptr, this, InfoCallback, nullptr, nullptr);
154
155 // Arbitrary buffer size, though note that it matches (below)
156 // SkPngCodec::processData(). FIXME: Can we better suit this to the size of
157 // the PNG header?
158 constexpr size_t kBufferSize = 4096;
159 char buffer[kBufferSize];
160
161 while (true) {
162 const size_t bytesRead = fStream->read(buffer, kBufferSize);
163 if (!bytesRead) {
164 // We have read to the end of the input without decoding bounds.
165 break;
166 }
167
168 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
169 if (fReadHeader) {
170 break;
171 }
172 }
173
174 // For safety, clear the pointer to this object.
175 png_set_progressive_read_fn(fPng_ptr, nullptr, nullptr, nullptr, nullptr);
176 return fDecodedBounds;
177 }
178
179 void SkPngCodec::processData() {
180 switch (setjmp(PNG_JMPBUF(fPng_ptr))) {
181 case kPngError:
182 // There was an error. Stop processing data.
183 // FIXME: Do we need to discard png_ptr?
184 return;
185 case kStopDecoding:
186 // We decoded all the lines we want.
187 return;
188 case kSetJmpOkay:
189 // Everything is okay.
190 break;
191 default:
192 // No other values should be passed to longjmp.
193 SkASSERT(false);
194 }
195
196 // Arbitrary buffer size
197 constexpr size_t kBufferSize = 4096;
198 char buffer[kBufferSize];
199
200 while (true) {
201 const size_t bytesRead = this->stream()->read(buffer, kBufferSize);
202 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
203
204 if (!bytesRead) {
205 // We have read to the end of the input. Note that we quit *after*
206 // calling png_process_data, because decodeBounds may have told
207 // libpng to save the remainder of the buffer, in which case
208 // png_process_data will process the saved buffer, though the
209 // stream has no more to read.
210 break;
211 }
212 }
213 }
214
97 // Note: SkColorTable claims to store SkPMColors, which is not necessarily the c ase here. 215 // Note: SkColorTable claims to store SkPMColors, which is not necessarily the c ase here.
98 bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) { 216 bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) {
99 217
100 int numColors; 218 int numColors;
101 png_color* palette; 219 png_color* palette;
102 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) { 220 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
103 return false; 221 return false;
104 } 222 }
105 223
106 // Contents depend on tableColorType and our choice of if/when to premultipl y: 224 // Contents depend on tableColorType and our choice of if/when to premultipl y:
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
174 } 292 }
175 293
176 /////////////////////////////////////////////////////////////////////////////// 294 ///////////////////////////////////////////////////////////////////////////////
177 // Creation 295 // Creation
178 /////////////////////////////////////////////////////////////////////////////// 296 ///////////////////////////////////////////////////////////////////////////////
179 297
180 bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) { 298 bool SkPngCodec::IsPng(const char* buf, size_t bytesRead) {
181 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead); 299 return !png_sig_cmp((png_bytep) buf, (png_size_t)0, bytesRead);
182 } 300 }
183 301
302 #if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_M INOR >= 6)
303
184 static float png_fixed_point_to_float(png_fixed_point x) { 304 static float png_fixed_point_to_float(png_fixed_point x) {
185 // We multiply by the same factor that libpng used to convert 305 // We multiply by the same factor that libpng used to convert
186 // fixed point -> double. Since we want floats, we choose to 306 // fixed point -> double. Since we want floats, we choose to
187 // do the conversion ourselves rather than convert 307 // do the conversion ourselves rather than convert
188 // fixed point -> double -> float. 308 // fixed point -> double -> float.
189 return ((float) x) * 0.00001f; 309 return ((float) x) * 0.00001f;
190 } 310 }
191 311
192 static float png_inverted_fixed_point_to_float(png_fixed_point x) { 312 static float png_inverted_fixed_point_to_float(png_fixed_point x) {
193 // This is necessary because the gAMA chunk actually stores 1/gamma. 313 // This is necessary because the gAMA chunk actually stores 1/gamma.
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
250 toXYZ3x3.setAll(toXYZ[0], toXYZ[3], toXYZ[6], toXYZ[1], toXYZ[4], toXYZ[7], toXYZ[2], toXYZ[5], 370 toXYZ3x3.setAll(toXYZ[0], toXYZ[3], toXYZ[6], toXYZ[1], toXYZ[4], toXYZ[7], toXYZ[2], toXYZ[5],
251 toXYZ[8]); 371 toXYZ[8]);
252 toXYZ3x3.postConcat(DXToD50); 372 toXYZ3x3.postConcat(DXToD50);
253 373
254 toXYZD50->set3x3(toXYZ3x3[0], toXYZ3x3[3], toXYZ3x3[6], 374 toXYZD50->set3x3(toXYZ3x3[0], toXYZ3x3[3], toXYZ3x3[6],
255 toXYZ3x3[1], toXYZ3x3[4], toXYZ3x3[7], 375 toXYZ3x3[1], toXYZ3x3[4], toXYZ3x3[7],
256 toXYZ3x3[2], toXYZ3x3[5], toXYZ3x3[8]); 376 toXYZ3x3[2], toXYZ3x3[5], toXYZ3x3[8]);
257 return true; 377 return true;
258 } 378 }
259 379
380 #endif // LIBPNG >= 1.6
381
260 // Returns a colorSpace object that represents any color space information in 382 // Returns a colorSpace object that represents any color space information in
261 // the encoded data. If the encoded data contains no color space, this will 383 // the encoded data. If the encoded data contains no color space, this will
262 // return NULL. 384 // return NULL.
263 sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) { 385 sk_sp<SkColorSpace> read_color_space(png_structp png_ptr, png_infop info_ptr) {
264 386
265 #if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_M INOR >= 6) 387 #if (PNG_LIBPNG_VER_MAJOR > 1) || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_M INOR >= 6)
266 388
267 // First check for an ICC profile 389 // First check for an ICC profile
268 png_bytep profile; 390 png_bytep profile;
269 png_uint_32 length; 391 png_uint_32 length;
(...skipping 75 matching lines...) Expand 10 before | Expand all | Expand 10 after
345 return SkColorSpace_Base::NewRGB(gammas, toXYZD50); 467 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
346 } 468 }
347 469
348 #endif // LIBPNG >= 1.6 470 #endif // LIBPNG >= 1.6
349 471
350 // Report that there is no color space information in the PNG. SkPngCodec i s currently 472 // Report that there is no color space information in the PNG. SkPngCodec i s currently
351 // implemented to guess sRGB in this case. 473 // implemented to guess sRGB in this case.
352 return nullptr; 474 return nullptr;
353 } 475 }
354 476
355 static int bytes_per_pixel(int bitsPerPixel) {
356 // Note that we will have to change this implementation if we start
357 // supporting outputs from libpng that are less than 8-bits per component.
358 return bitsPerPixel / 8;
359 }
360
361 void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) { 477 void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
362 switch (fXformMode) { 478 switch (fXformMode) {
363 case kSwizzleOnly_XformMode: 479 case kSwizzleOnly_XformMode:
364 fStorage.reset(SkAlign4(fSrcRowBytes));
365 fSwizzlerSrcRow = fStorage.get();
366 break; 480 break;
367 case kColorOnly_XformMode: 481 case kColorOnly_XformMode:
368 // Intentional fall through. A swizzler hasn't been created yet, bu t one will 482 // Intentional fall through. A swizzler hasn't been created yet, bu t one will
369 // be created later if we are sampling. We'll go ahead and allocate 483 // be created later if we are sampling. We'll go ahead and allocate
370 // enough memory to swizzle if necessary. 484 // enough memory to swizzle if necessary.
371 case kSwizzleColor_XformMode: { 485 case kSwizzleColor_XformMode: {
372 size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t); 486 const size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t);
373 fStorage.reset(SkAlign4(fSrcRowBytes) + colorXformBytes); 487 fStorage.reset(colorXformBytes);
374 fSwizzlerSrcRow = fStorage.get(); 488 fColorXformSrcRow = (uint32_t*) fStorage.get();
375 fColorXformSrcRow = SkTAddOffset<uint32_t>(fSwizzlerSrcRow, SkAlign4 (fSrcRowBytes));
376 break; 489 break;
377 } 490 }
378 } 491 }
379 } 492 }
380 493
381 void SkPngCodec::applyXformRow(void* dst, const void* src, SkColorType colorType , 494 void SkPngCodec::applyXformRow(void* dst, const void* src) {
382 SkAlphaType alphaType, int width) { 495 const SkColorType colorType = this->dstInfo().colorType();
383 switch (fXformMode) { 496 switch (fXformMode) {
384 case kSwizzleOnly_XformMode: 497 case kSwizzleOnly_XformMode:
385 fSwizzler->swizzle(dst, (const uint8_t*) src); 498 fSwizzler->swizzle(dst, (const uint8_t*) src);
386 break; 499 break;
387 case kColorOnly_XformMode: 500 case kColorOnly_XformMode:
388 fColorXform->apply(dst, (const uint32_t*) src, width, colorType, alp haType); 501 fColorXform->apply(dst, (const uint32_t*) src, fXformWidth, colorTyp e, fXformAlphaType);
389 break; 502 break;
390 case kSwizzleColor_XformMode: 503 case kSwizzleColor_XformMode:
391 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src); 504 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src);
392 fColorXform->apply(dst, fColorXformSrcRow, width, colorType, alphaTy pe); 505 fColorXform->apply(dst, fColorXformSrcRow, fXformWidth, colorType, f XformAlphaType);
393 break; 506 break;
394 } 507 }
395 } 508 }
396 509
397 class SkPngNormalCodec : public SkPngCodec { 510 class SkPngNormalDecoder : public SkPngCodec {
398 public: 511 public:
399 SkPngNormalCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageI nfo, 512 SkPngNormalDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo, SkStream* stream,
400 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr , 513 SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr, i nt bitDepth)
401 png_infop info_ptr, int bitDepth) 514 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth )
402 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_p tr, bitDepth, 1) 515 , fLinesDecoded(0)
516 , fDst(nullptr)
517 , fRowBytes(0)
518 , fFirstRow(0)
519 , fLastRow(0)
403 {} 520 {}
404 521
405 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& opti ons, 522 static void AllRowsCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
406 SkPMColor ctable[], int* ctableCount) override { 523 GetDecoder(png_ptr)->allRowsCallback(row, rowNum);
407 if (!conversion_possible(dstInfo, this->getInfo()) || 524 }
408 !this->initializeXforms(dstInfo, options, ctable, ctableCount)) 525
409 { 526 static void RowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowN um, int /*pass*/) {
410 return kInvalidConversion; 527 GetDecoder(png_ptr)->rowCallback(row, rowNum);
411 } 528 }
412 529
413 this->allocateStorage(dstInfo); 530 #ifdef SK_GOOGLE3_PNG_HACK
414 return kSuccess; 531 static void RereadInfoCallback(png_structp png_ptr, png_infop) {
415 } 532 GetDecoder(png_ptr)->rereadInfoCallback();
416 533 }
417 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int cou nt, int startRow) 534 #endif
418 override { 535
419 SkASSERT(0 == startRow); 536 private:
420 537 int fLinesDecoded; // FIXME: Move to baseclass?
421 // Assume that an error in libpng indicates an incomplete input. 538 void* fDst;
422 int y = 0; 539 size_t fRowBytes;
423 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 540
424 SkCodecPrintf("Failed to read row.\n"); 541 // Variables for partial decode
425 return y; 542 int fFirstRow; // FIXME: Move to baseclass?
426 } 543 int fLastRow;
427 544
428 SkAlphaType xformAlphaType = select_alpha_xform(dstInfo.alphaType(), 545 typedef SkPngCodec INHERITED;
429 this->getInfo().alphaTyp e()); 546
430 int width = fSwizzler ? fSwizzler->swizzleWidth() : dstInfo.width(); 547 static SkPngNormalDecoder* GetDecoder(png_structp png_ptr) {
431 548 return static_cast<SkPngNormalDecoder*>(png_get_progressive_ptr(png_ptr) );
432 for (; y < count; y++) { 549 }
433 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr); 550
434 this->applyXformRow(dst, fSwizzlerSrcRow, dstInfo.colorType(), xform AlphaType, width); 551 Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
552 const int height = this->getInfo().height();
553 png_progressive_info_ptr callback = nullptr;
554 #ifdef SK_GOOGLE3_PNG_HACK
555 callback = RereadInfoCallback;
556 #endif
557 png_set_progressive_read_fn(this->png_ptr(), this, callback, AllRowsCall back, nullptr);
558 fDst = dst;
559 fRowBytes = rowBytes;
560
561 fLinesDecoded = 0;
562
563 this->processData();
564
565 if (fLinesDecoded == height) {
566 return SkCodec::kSuccess;
567 }
568
569 if (rowsDecoded) {
570 *rowsDecoded = fLinesDecoded;
571 }
572
573 return SkCodec::kIncompleteInput;
574 }
575
576 void allRowsCallback(png_bytep row, int rowNum) {
577 SkASSERT(rowNum - fFirstRow == fLinesDecoded);
578 fLinesDecoded++;
579 this->applyXformRow(fDst, row);
580 fDst = SkTAddOffset<void>(fDst, fRowBytes);
581 }
582
583 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) overrid e {
584 png_progressive_info_ptr callback = nullptr;
585 #ifdef SK_GOOGLE3_PNG_HACK
586 callback = RereadInfoCallback;
587 #endif
588 png_set_progressive_read_fn(this->png_ptr(), this, callback, RowCallback , nullptr);
589 fFirstRow = firstRow;
590 fLastRow = lastRow;
591 fDst = dst;
592 fRowBytes = rowBytes;
593 fLinesDecoded = 0;
594 }
595
596 SkCodec::Result decode(int* rowsDecoded) override {
597 this->processData();
598
599 if (fLinesDecoded == fLastRow - fFirstRow + 1) {
600 return SkCodec::kSuccess;
601 }
602
603 if (rowsDecoded) {
604 *rowsDecoded = fLinesDecoded;
605 }
606
607 return SkCodec::kIncompleteInput;
608 }
609
610 void rowCallback(png_bytep row, int rowNum) {
611 if (rowNum < fFirstRow) {
612 // Ignore this row.
613 return;
614 }
615
616 SkASSERT(rowNum <= fLastRow);
617
618 // If there is no swizzler, all rows are needed.
619 if (!this->swizzler() || this->swizzler()->rowNeeded(fLinesDecoded)) {
620 this->applyXformRow(fDst, row);
621 fDst = SkTAddOffset<void>(fDst, fRowBytes);
622 }
623
624 fLinesDecoded++;
625
626 if (rowNum == fLastRow) {
627 // Fake error to stop decoding scanlines.
628 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
629 }
630 }
631 };
632
633 class SkPngInterlacedDecoder : public SkPngCodec {
634 public:
635 SkPngInterlacedDecoder(const SkEncodedInfo& info, const SkImageInfo& imageIn fo,
636 SkStream* stream, SkPngChunkReader* reader, png_structp png_ptr, png _infop info_ptr,
637 int bitDepth, int numberPasses)
638 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth )
639 , fNumberPasses(numberPasses)
640 , fFirstRow(0)
641 , fLastRow(0)
642 , fLinesDecoded(0)
643 , fInterlacedComplete(false)
644 , fPng_rowbytes(0)
645 {}
646
647 static void InterlacedRowCallback(png_structp png_ptr, png_bytep row, png_ui nt_32 rowNum, int pass) {
648 auto decoder = static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ ptr(png_ptr));
649 decoder->interlacedRowCallback(row, rowNum, pass);
650 }
651
652 #ifdef SK_GOOGLE3_PNG_HACK
653 static void RereadInfoInterlacedCallback(png_structp png_ptr, png_infop) {
654 static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ptr(png_ptr))-> rereadInfoInterlaced();
655 }
656 #endif
657
658 private:
659 const int fNumberPasses;
660 int fFirstRow;
661 int fLastRow;
662 void* fDst;
663 size_t fRowBytes;
664 int fLinesDecoded;
665 bool fInterlacedComplete;
666 size_t fPng_rowbytes;
667 SkAutoTMalloc<png_byte> fInterlaceBuffer;
668
669 typedef SkPngCodec INHERITED;
670
671 #ifdef SK_GOOGLE3_PNG_HACK
672 void rereadInfoInterlaced() {
673 this->rereadInfoCallback();
674 // Note: This allocates more memory than necessary, if we are sampling/s ubset.
675 this->setUpInterlaceBuffer(this->getInfo().height());
676 }
677 #endif
678
679 // FIXME: Currently sharing interlaced callback for all rows and subset. It' s not
680 // as expensive as the subset version of non-interlaced, but it still does e xtra
681 // work.
682 void interlacedRowCallback(png_bytep row, int rowNum, int pass) {
683 if (rowNum < fFirstRow || rowNum > fLastRow) {
684 // Ignore this row
685 return;
686 }
687
688 png_bytep oldRow = fInterlaceBuffer.get() + (rowNum - fFirstRow) * fPng_ rowbytes;
689 png_progressive_combine_row(this->png_ptr(), oldRow, row);
690
691 if (0 == pass) {
692 // The first pass initializes all rows.
693 SkASSERT(row);
694 SkASSERT(fLinesDecoded == rowNum - fFirstRow);
695 fLinesDecoded++;
696 } else {
697 SkASSERT(fLinesDecoded == fLastRow - fFirstRow + 1);
698 if (fNumberPasses - 1 == pass && rowNum == fLastRow) {
699 // Last pass, and we have read all of the rows we care about. No te that
700 // we do not care about reading anything beyond the end of the i mage (or
701 // beyond the last scanline requested).
702 fInterlacedComplete = true;
703 // Fake error to stop decoding scanlines.
704 longjmp(PNG_JMPBUF(this->png_ptr()), kStopDecoding);
705 }
706 }
707 }
708
709 SkCodec::Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
710 const int height = this->getInfo().height();
711 this->setUpInterlaceBuffer(height);
712 png_progressive_info_ptr callback = nullptr;
713 #ifdef SK_GOOGLE3_PNG_HACK
714 callback = RereadInfoInterlacedCallback;
715 #endif
716 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedR owCallback,
717 nullptr);
718
719 fFirstRow = 0;
720 fLastRow = height - 1;
721 fLinesDecoded = 0;
722
723 this->processData();
724
725 png_bytep srcRow = fInterlaceBuffer.get();
726 // FIXME: When resuming, this may rewrite rows that did not change.
727 for (int rowNum = 0; rowNum < fLinesDecoded; rowNum++) {
728 this->applyXformRow(dst, srcRow);
435 dst = SkTAddOffset<void>(dst, rowBytes); 729 dst = SkTAddOffset<void>(dst, rowBytes);
436 } 730 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes);
437 731 }
438 return y; 732 if (fInterlacedComplete) {
439 } 733 return SkCodec::kSuccess;
440 734 }
441 int onGetScanlines(void* dst, int count, size_t rowBytes) override { 735
442 return this->readRows(this->dstInfo(), dst, rowBytes, count, 0); 736 if (rowsDecoded) {
443 } 737 *rowsDecoded = fLinesDecoded;
444 738 }
445 bool onSkipScanlines(int count) override { 739
446 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 740 return SkCodec::kIncompleteInput;
447 SkCodecPrintf("Failed to skip row.\n"); 741 }
448 return false; 742
449 } 743 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) overrid e {
450 744 // FIXME: We could skip rows in the interlace buffer that we won't put i n the output.
451 for (int row = 0; row < count; row++) { 745 this->setUpInterlaceBuffer(lastRow - firstRow + 1);
452 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr); 746 png_progressive_info_ptr callback = nullptr;
453 } 747 #ifdef SK_GOOGLE3_PNG_HACK
748 callback = RereadInfoInterlacedCallback;
749 #endif
750 png_set_progressive_read_fn(this->png_ptr(), this, callback, InterlacedR owCallback, nullptr);
751 fFirstRow = firstRow;
752 fLastRow = lastRow;
753 fDst = dst;
754 fRowBytes = rowBytes;
755 fLinesDecoded = 0;
756 }
757
758 SkCodec::Result decode(int* rowsDecoded) override {
759 this->processData();
760
761 // Now apply Xforms on all the rows that were decoded.
762 if (!fLinesDecoded) {
763 return SkCodec::kIncompleteInput;
764 }
765 const int lastRow = fLinesDecoded + fFirstRow - 1;
766 SkASSERT(lastRow <= fLastRow);
767
768 // FIXME: For resuming interlace, we may swizzle a row that hasn't chang ed. But it
769 // may be too tricky/expensive to handle that correctly.
770 png_bytep srcRow = fInterlaceBuffer.get();
771 const int sampleY = this->swizzler() ? this->swizzler()->sampleY() : 1;
772 void* dst = fDst;
773 for (int rowNum = fFirstRow; rowNum <= lastRow; rowNum += sampleY) {
774 this->applyXformRow(dst, srcRow);
775 dst = SkTAddOffset<void>(dst, fRowBytes);
776 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes * sampleY);
777 }
778
779 if (fInterlacedComplete) {
780 return SkCodec::kSuccess;
781 }
782
783 if (rowsDecoded) {
784 *rowsDecoded = fLinesDecoded;
785 }
786 return SkCodec::kIncompleteInput;
787 }
788
789 void setUpInterlaceBuffer(int height) {
790 fPng_rowbytes = png_get_rowbytes(this->png_ptr(), this->info_ptr());
791 fInterlaceBuffer.reset(fPng_rowbytes * height);
792 fInterlacedComplete = false;
793 }
794 };
795
796 #ifdef SK_GOOGLE3_PNG_HACK
797 bool SkPngCodec::rereadHeaderIfNecessary() {
798 if (!fNeedsToRereadHeader) {
454 return true; 799 return true;
455 } 800 }
456 801
457 typedef SkPngCodec INHERITED; 802 // On the first call, we'll need to rewind ourselves. Future calls will
458 }; 803 // have already rewound in rewindIfNecessary.
459 804 if (this->stream()->getPosition() > 0) {
460 class SkPngInterlacedCodec : public SkPngCodec { 805 this->stream()->rewind();
461 public: 806 }
462 SkPngInterlacedCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& im ageInfo, 807
463 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr , 808 this->destroyReadStruct();
464 png_infop info_ptr, int bitDepth, int numberPasses) 809 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
465 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_p tr, bitDepth, 810 sk_error_fn, sk_warning_fn);
466 numberPasses) 811 if (!png_ptr) {
467 , fCanSkipRewind(false) 812 return false;
468 { 813 }
469 SkASSERT(numberPasses != 1); 814
470 } 815 // Only use the AutoCleanPng to delete png_ptr as necessary.
471 816 // (i.e. not for reading bounds etc.)
472 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& opti ons, 817 AutoCleanPng autoClean(png_ptr, nullptr, nullptr, nullptr);
473 SkPMColor ctable[], int* ctableCount) override { 818
474 if (!conversion_possible(dstInfo, this->getInfo()) || 819 png_infop info_ptr = png_create_info_struct(png_ptr);
475 !this->initializeXforms(dstInfo, options, ctable, ctableCount)) 820 if (info_ptr == nullptr) {
476 { 821 return false;
477 return kInvalidConversion; 822 }
478 } 823
479 824 autoClean.setInfoPtr(info_ptr);
480 this->allocateStorage(dstInfo); 825
481 fCanSkipRewind = true; 826 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
482 return SkCodec::kSuccess; 827 // Hookup our chunkReader so we can see any user-chunks the caller may be in terested in.
483 } 828 // This needs to be installed before we read the png header. Android may st ore ninepatch
484 829 // chunks in the header.
485 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int cou nt, int startRow) 830 if (fPngChunkReader.get()) {
486 override { 831 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte* )"", 0);
487 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 832 png_set_read_user_chunk_fn(png_ptr, (png_voidp) fPngChunkReader.get(), s k_read_user_chunk);
488 SkCodecPrintf("Failed to get scanlines.\n"); 833 }
489 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass, 834 #endif
490 // we may be able to report that all of the memory has been initiali zed. Even if we 835
491 // fail on the first pass, we can still report than some scanlines a re initialized. 836 fPng_ptr = png_ptr;
492 return 0; 837 fInfo_ptr = info_ptr;
493 } 838 autoClean.releasePngPtrs();
494 839 fNeedsToRereadHeader = false;
495 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes); 840 return true;
496 uint8_t* srcRow; 841 }
497 for (int i = 0; i < fNumberPasses; i++) { 842 #endif // SK_GOOGLE3_PNG_HACK
498 // Discard rows that we planned to skip.
499 for (int y = 0; y < startRow; y++){
500 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
501 }
502 // Read rows we care about into storage.
503 srcRow = storage.get();
504 for (int y = 0; y < count; y++) {
505 png_read_row(fPng_ptr, srcRow, nullptr);
506 srcRow += fSrcRowBytes;
507 }
508 // Discard rows that we don't need.
509 for (int y = 0; y < this->getInfo().height() - startRow - count; y++ ) {
510 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr);
511 }
512 }
513
514 SkAlphaType xformAlphaType = select_alpha_xform(dstInfo.alphaType(),
515 this->getInfo().alphaTyp e());
516 int width = fSwizzler ? fSwizzler->swizzleWidth() : dstInfo.width();
517 srcRow = storage.get();
518 for (int y = 0; y < count; y++) {
519 this->applyXformRow(dst, srcRow, dstInfo.colorType(), xformAlphaType , width);
520 srcRow = SkTAddOffset<uint8_t>(srcRow, fSrcRowBytes);
521 dst = SkTAddOffset<void>(dst, rowBytes);
522 }
523
524 return count;
525 }
526
527 int onGetScanlines(void* dst, int count, size_t rowBytes) override {
528 // rewind stream if have previously called onGetScanlines,
529 // since we need entire progressive image to get scanlines
530 if (fCanSkipRewind) {
531 // We already rewound in onStartScanlineDecode, so there is no reaso n to rewind.
532 // Next time onGetScanlines is called, we will need to rewind.
533 fCanSkipRewind = false;
534 } else {
535 // rewindIfNeeded resets fCurrScanline, since it assumes that start
536 // needs to be called again before scanline decoding. PNG scanline
537 // decoding is the exception, since it needs to rewind between
538 // calls to getScanlines. Keep track of fCurrScanline, to undo the
539 // reset.
540 const int currScanline = this->nextScanline();
541 // This method would never be called if currScanline is -1
542 SkASSERT(currScanline != -1);
543
544 if (!this->rewindIfNeeded()) {
545 return kCouldNotRewind;
546 }
547 this->updateCurrScanline(currScanline);
548 }
549
550 return this->readRows(this->dstInfo(), dst, rowBytes, count, this->nextS canline());
551 }
552
553 bool onSkipScanlines(int count) override {
554 // The non-virtual version will update fCurrScanline.
555 return true;
556 }
557
558 SkScanlineOrder onGetScanlineOrder() const override {
559 return kNone_SkScanlineOrder;
560 }
561
562 private:
563 // FIXME: This imitates behavior in SkCodec::rewindIfNeeded. That function
564 // is called whenever some action is taken that reads the stream and
565 // therefore the next call will require a rewind. So it modifies a boolean
566 // to note that the *next* time it is called a rewind is needed.
567 // SkPngInterlacedCodec has an extra wrinkle - calling
568 // onStartScanlineDecode followed by onGetScanlines does *not* require a
569 // rewind. Since rewindIfNeeded does not have this flexibility, we need to
570 // add another layer.
571 bool fCanSkipRewind;
572
573 typedef SkPngCodec INHERITED;
574 };
575 843
576 // Reads the header and initializes the output fields, if not NULL. 844 // Reads the header and initializes the output fields, if not NULL.
577 // 845 //
578 // @param stream Input data. Will be read to get enough information to properly 846 // @param stream Input data. Will be read to get enough information to properly
579 // setup the codec. 847 // setup the codec.
580 // @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL. 848 // @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL.
581 // If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is 849 // If not NULL, png_ptr will hold an *unowned* pointer to it. The caller is
582 // expected to continue to own it for the lifetime of the png_ptr. 850 // expected to continue to own it for the lifetime of the png_ptr.
583 // @param outCodec Optional output variable. If non-NULL, will be set to a new 851 // @param outCodec Optional output variable. If non-NULL, will be set to a new
584 // SkPngCodec on success. 852 // SkPngCodec on success.
585 // @param png_ptrp Optional output variable. If non-NULL, will be set to a new 853 // @param png_ptrp Optional output variable. If non-NULL, will be set to a new
586 // png_structp on success. 854 // png_structp on success.
587 // @param info_ptrp Optional output variable. If non-NULL, will be set to a new 855 // @param info_ptrp Optional output variable. If non-NULL, will be set to a new
588 // png_infop on success; 856 // png_infop on success;
589 // @return true on success, in which case the caller is responsible for calling 857 // @return true on success, in which case the caller is responsible for calling
590 // png_destroy_read_struct(png_ptrp, info_ptrp). 858 // png_destroy_read_struct(png_ptrp, info_ptrp).
591 // If it returns false, the passed in fields (except stream) are unchanged. 859 // If it returns false, the passed in fields (except stream) are unchanged.
592 static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec ** outCodec, 860 static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec ** outCodec,
593 png_structp* png_ptrp, png_infop* info_ptrp) { 861 png_structp* png_ptrp, png_infop* info_ptrp) {
594 // The image is known to be a PNG. Decode enough to know the SkImageInfo. 862 // The image is known to be a PNG. Decode enough to know the SkImageInfo.
595 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, 863 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
596 sk_error_fn, sk_warning_fn); 864 sk_error_fn, sk_warning_fn);
597 if (!png_ptr) { 865 if (!png_ptr) {
598 return false; 866 return false;
599 } 867 }
600 868
601 AutoCleanPng autoClean(png_ptr); 869 AutoCleanPng autoClean(png_ptr, stream, chunkReader, outCodec);
602 870
603 png_infop info_ptr = png_create_info_struct(png_ptr); 871 png_infop info_ptr = png_create_info_struct(png_ptr);
604 if (info_ptr == nullptr) { 872 if (info_ptr == nullptr) {
605 return false; 873 return false;
606 } 874 }
607 875
608 autoClean.setInfoPtr(info_ptr); 876 autoClean.setInfoPtr(info_ptr);
609 877
610 // FIXME: Could we use the return value of setjmp to specify the type of 878 // FIXME: Could we use the return value of setjmp to specify the type of
611 // error? 879 // error?
612 if (setjmp(png_jmpbuf(png_ptr))) { 880 if (setjmp(PNG_JMPBUF(png_ptr))) {
613 return false; 881 return false;
614 } 882 }
615 883
616 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
617
618 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED 884 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
619 // Hookup our chunkReader so we can see any user-chunks the caller may be in terested in. 885 // Hookup our chunkReader so we can see any user-chunks the caller may be in terested in.
620 // This needs to be installed before we read the png header. Android may st ore ninepatch 886 // This needs to be installed before we read the png header. Android may st ore ninepatch
621 // chunks in the header. 887 // chunks in the header.
622 if (chunkReader) { 888 if (chunkReader) {
623 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte* )"", 0); 889 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte* )"", 0);
624 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_use r_chunk); 890 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_use r_chunk);
625 } 891 }
626 #endif 892 #endif
627 893
628 // The call to png_read_info() gives us all of the information from the 894 const bool decodedBounds = autoClean.decodeBounds();
629 // PNG file before the first IDAT (image data chunk). 895
630 png_read_info(png_ptr, info_ptr); 896 if (!decodedBounds) {
897 return false;
898 }
899
900 // On success, decodeBounds releases ownership of png_ptr and info_ptr.
901 if (png_ptrp) {
902 *png_ptrp = png_ptr;
903 }
904 if (info_ptrp) {
905 *info_ptrp = info_ptr;
906 }
907
908 // decodeBounds takes care of setting outCodec
909 if (outCodec) {
910 SkASSERT(*outCodec);
911 }
912 return true;
913 }
914
915 // FIXME (scroggo): Once SK_GOOGLE3_PNG_HACK is no more, this method can be inli ne in
916 // AutoCleanPng::infoCallback
917 static void general_info_callback(png_structp png_ptr, png_infop info_ptr,
918 SkEncodedInfo::Color* outColor, SkEncodedInfo: :Alpha* outAlpha) {
631 png_uint_32 origWidth, origHeight; 919 png_uint_32 origWidth, origHeight;
632 int bitDepth, encodedColorType; 920 int bitDepth, encodedColorType;
633 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth, 921 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth,
634 &encodedColorType, nullptr, nullptr, nullptr); 922 &encodedColorType, nullptr, nullptr, nullptr);
635 923
636 // Tell libpng to strip 16 bit/color files down to 8 bits/color. 924 // Tell libpng to strip 16 bit/color files down to 8 bits/color.
637 // TODO: Should we handle this in SkSwizzler? Could this also benefit 925 // TODO: Should we handle this in SkSwizzler? Could this also benefit
638 // RAW decodes? 926 // RAW decodes?
639 if (bitDepth == 16) { 927 if (bitDepth == 16) {
640 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType); 928 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after
694 case PNG_COLOR_TYPE_RGBA: 982 case PNG_COLOR_TYPE_RGBA:
695 color = SkEncodedInfo::kRGBA_Color; 983 color = SkEncodedInfo::kRGBA_Color;
696 alpha = SkEncodedInfo::kUnpremul_Alpha; 984 alpha = SkEncodedInfo::kUnpremul_Alpha;
697 break; 985 break;
698 default: 986 default:
699 // All the color types have been covered above. 987 // All the color types have been covered above.
700 SkASSERT(false); 988 SkASSERT(false);
701 color = SkEncodedInfo::kRGBA_Color; 989 color = SkEncodedInfo::kRGBA_Color;
702 alpha = SkEncodedInfo::kUnpremul_Alpha; 990 alpha = SkEncodedInfo::kUnpremul_Alpha;
703 } 991 }
992 if (outColor) {
993 *outColor = color;
994 }
995 if (outAlpha) {
996 *outAlpha = alpha;
997 }
998 }
704 999
705 int numberPasses = png_set_interlace_handling(png_ptr); 1000 #ifdef SK_GOOGLE3_PNG_HACK
1001 void SkPngCodec::rereadInfoCallback() {
1002 general_info_callback(fPng_ptr, fInfo_ptr, nullptr, nullptr);
1003 png_set_interlace_handling(fPng_ptr);
1004 png_read_update_info(fPng_ptr, fInfo_ptr);
1005 }
1006 #endif
706 1007
707 autoClean.release(); 1008 void AutoCleanPng::infoCallback() {
708 if (png_ptrp) { 1009 SkEncodedInfo::Color color;
709 *png_ptrp = png_ptr; 1010 SkEncodedInfo::Alpha alpha;
710 } 1011 general_info_callback(fPng_ptr, fInfo_ptr, &color, &alpha);
711 if (info_ptrp) {
712 *info_ptrp = info_ptr;
713 }
714 1012
715 if (outCodec) { 1013 const int numberPasses = png_set_interlace_handling(fPng_ptr);
716 sk_sp<SkColorSpace> colorSpace = read_color_space(png_ptr, info_ptr); 1014
1015 fReadHeader = true;
1016 fDecodedBounds = true;
1017 #ifndef SK_GOOGLE3_PNG_HACK
1018 // 1 tells libpng to save any extra data. We may be able to be more efficien t by saving
1019 // it ourselves.
1020 png_process_data_pause(fPng_ptr, 1);
1021 #else
1022 // Hack to make png_process_data stop.
1023 fPng_ptr->buffer_size = 0;
1024 #endif
1025 if (fOutCodec) {
1026 SkASSERT(nullptr == *fOutCodec);
1027 sk_sp<SkColorSpace> colorSpace = read_color_space(fPng_ptr, fInfo_ptr);
717 if (!colorSpace) { 1028 if (!colorSpace) {
718 // Treat unmarked pngs as sRGB. 1029 // Treat unmarked pngs as sRGB.
719 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); 1030 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
720 } 1031 }
721 1032
722 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8); 1033 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
1034 // FIXME (scroggo): Once we get rid of SK_GOOGLE3_PNG_HACK, general_info _callback can
1035 // be inlined, so these values will already be set.
1036 png_uint_32 origWidth = png_get_image_width(fPng_ptr, fInfo_ptr);
1037 png_uint_32 origHeight = png_get_image_height(fPng_ptr, fInfo_ptr);
1038 png_byte bitDepth = png_get_bit_depth(fPng_ptr, fInfo_ptr);
723 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace); 1039 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
724 1040
725 if (SkEncodedInfo::kOpaque_Alpha == alpha) { 1041 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
726 png_color_8p sigBits; 1042 png_color_8p sigBits;
727 if (png_get_sBIT(png_ptr, info_ptr, &sigBits)) { 1043 if (png_get_sBIT(fPng_ptr, fInfo_ptr, &sigBits)) {
728 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->bl ue) { 1044 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->bl ue) {
729 // Recommend a decode to 565 if the sBIT indicates 565. 1045 // Recommend a decode to 565 if the sBIT indicates 565.
730 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType); 1046 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
731 } 1047 }
732 } 1048 }
733 } 1049 }
734 1050
735 if (1 == numberPasses) { 1051 if (1 == numberPasses) {
736 *outCodec = new SkPngNormalCodec(encodedInfo, imageInfo, stream, 1052 *fOutCodec = new SkPngNormalDecoder(encodedInfo, imageInfo, fStream,
737 chunkReader, png_ptr, info_ptr, bitDepth); 1053 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth);
738 } else { 1054 } else {
739 *outCodec = new SkPngInterlacedCodec(encodedInfo, imageInfo, stream, 1055 *fOutCodec = new SkPngInterlacedDecoder(encodedInfo, imageInfo, fStr eam,
740 chunkReader, png_ptr, info_ptr, bitDepth, numberPasses); 1056 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth, numberPasses);
741 } 1057 }
742 } 1058 }
743 1059
744 return true; 1060
1061 // Release the pointers, which are now owned by the codec or the caller is e xpected to
1062 // take ownership.
1063 this->releasePngPtrs();
745 } 1064 }
746 1065
747 SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imag eInfo, 1066 SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imag eInfo,
748 SkStream* stream, SkPngChunkReader* chunkReader, void* pn g_ptr, 1067 SkStream* stream, SkPngChunkReader* chunkReader, void* pn g_ptr,
749 void* info_ptr, int bitDepth, int numberPasses) 1068 void* info_ptr, int bitDepth)
750 : INHERITED(encodedInfo, imageInfo, stream) 1069 : INHERITED(encodedInfo, imageInfo, stream)
751 , fPngChunkReader(SkSafeRef(chunkReader)) 1070 , fPngChunkReader(SkSafeRef(chunkReader))
752 , fPng_ptr(png_ptr) 1071 , fPng_ptr(png_ptr)
753 , fInfo_ptr(info_ptr) 1072 , fInfo_ptr(info_ptr)
754 , fSwizzlerSrcRow(nullptr)
755 , fColorXformSrcRow(nullptr) 1073 , fColorXformSrcRow(nullptr)
756 , fSrcRowBytes(imageInfo.width() * (bytes_per_pixel(this->getEncodedInfo().b itsPerPixel())))
757 , fNumberPasses(numberPasses)
758 , fBitDepth(bitDepth) 1074 , fBitDepth(bitDepth)
1075 #ifdef SK_GOOGLE3_PNG_HACK
1076 , fNeedsToRereadHeader(true)
1077 #endif
759 {} 1078 {}
760 1079
761 SkPngCodec::~SkPngCodec() { 1080 SkPngCodec::~SkPngCodec() {
762 this->destroyReadStruct(); 1081 this->destroyReadStruct();
763 } 1082 }
764 1083
765 void SkPngCodec::destroyReadStruct() { 1084 void SkPngCodec::destroyReadStruct() {
766 if (fPng_ptr) { 1085 if (fPng_ptr) {
767 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr 1086 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
768 SkASSERT(fInfo_ptr); 1087 SkASSERT(fInfo_ptr);
769 png_destroy_read_struct((png_struct**)&fPng_ptr, (png_info**)&fInfo_ptr, nullptr); 1088 png_destroy_read_struct((png_struct**)&fPng_ptr, (png_info**)&fInfo_ptr, nullptr);
770 fPng_ptr = nullptr; 1089 fPng_ptr = nullptr;
771 fInfo_ptr = nullptr; 1090 fInfo_ptr = nullptr;
772 } 1091 }
773 } 1092 }
774 1093
775 /////////////////////////////////////////////////////////////////////////////// 1094 ///////////////////////////////////////////////////////////////////////////////
776 // Getting the pixels 1095 // Getting the pixels
777 /////////////////////////////////////////////////////////////////////////////// 1096 ///////////////////////////////////////////////////////////////////////////////
778 1097
779 bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& opt ions, 1098 bool SkPngCodec::initializeXforms(const SkImageInfo& dstInfo, const Options& opt ions,
780 SkPMColor ctable[], int* ctableCount) { 1099 SkPMColor ctable[], int* ctableCount) {
781 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 1100 if (setjmp(PNG_JMPBUF((png_struct*)fPng_ptr))) {
782 SkCodecPrintf("Failed on png_read_update_info.\n"); 1101 SkCodecPrintf("Failed on png_read_update_info.\n");
783 return false; 1102 return false;
784 } 1103 }
785 png_read_update_info(fPng_ptr, fInfo_ptr); 1104 png_read_update_info(fPng_ptr, fInfo_ptr);
786 1105
787 // Reset fSwizzler and fColorXform. We can't do this in onRewind() because the 1106 // Reset fSwizzler and fColorXform. We can't do this in onRewind() because the
788 // interlaced scanline decoder may need to rewind. 1107 // interlaced scanline decoder may need to rewind.
789 fSwizzler.reset(nullptr); 1108 fSwizzler.reset(nullptr);
790 fColorXform = nullptr; 1109 fColorXform = nullptr;
791 1110
(...skipping 19 matching lines...) Expand all
811 } 1130 }
812 } 1131 }
813 1132
814 // Copy the color table to the client if they request kIndex8 mode. 1133 // Copy the color table to the client if they request kIndex8 mode.
815 copy_color_table(dstInfo, fColorTable, ctable, ctableCount); 1134 copy_color_table(dstInfo, fColorTable, ctable, ctableCount);
816 1135
817 this->initializeSwizzler(dstInfo, options); 1136 this->initializeSwizzler(dstInfo, options);
818 return true; 1137 return true;
819 } 1138 }
820 1139
1140 void SkPngCodec::initializeXformAlphaAndWidth() {
1141 fXformAlphaType = select_alpha_xform(this->dstInfo().alphaType(), this->getI nfo().alphaType());
1142 fXformWidth = this->swizzler() ? this->swizzler()->swizzleWidth() : this->ds tInfo().width();
1143 }
1144
821 static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo ::Color srcColor) { 1145 static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo ::Color srcColor) {
822 // We will apply the color xform when reading the color table, unless F16 is requested. 1146 // We will apply the color xform when reading the color table, unless F16 is requested.
823 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType; 1147 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType;
824 } 1148 }
825 1149
826 void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o ptions) { 1150 void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o ptions) {
827 SkImageInfo swizzlerInfo = dstInfo; 1151 SkImageInfo swizzlerInfo = dstInfo;
828 Options swizzlerOptions = options; 1152 Options swizzlerOptions = options;
829 fXformMode = kSwizzleOnly_XformMode; 1153 fXformMode = kSwizzleOnly_XformMode;
830 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncod edInfo().color())) { 1154 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncod edInfo().color())) {
(...skipping 19 matching lines...) Expand all
850 SkSampler* SkPngCodec::getSampler(bool createIfNecessary) { 1174 SkSampler* SkPngCodec::getSampler(bool createIfNecessary) {
851 if (fSwizzler || !createIfNecessary) { 1175 if (fSwizzler || !createIfNecessary) {
852 return fSwizzler; 1176 return fSwizzler;
853 } 1177 }
854 1178
855 this->initializeSwizzler(this->dstInfo(), this->options()); 1179 this->initializeSwizzler(this->dstInfo(), this->options());
856 return fSwizzler; 1180 return fSwizzler;
857 } 1181 }
858 1182
859 bool SkPngCodec::onRewind() { 1183 bool SkPngCodec::onRewind() {
1184 #ifdef SK_GOOGLE3_PNG_HACK
1185 fNeedsToRereadHeader = true;
1186 return true;
1187 #else
860 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header 1188 // This sets fPng_ptr and fInfo_ptr to nullptr. If read_header
861 // succeeds, they will be repopulated, and if it fails, they will 1189 // succeeds, they will be repopulated, and if it fails, they will
862 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will 1190 // remain nullptr. Any future accesses to fPng_ptr and fInfo_ptr will
863 // come through this function which will rewind and again attempt 1191 // come through this function which will rewind and again attempt
864 // to reinitialize them. 1192 // to reinitialize them.
865 this->destroyReadStruct(); 1193 this->destroyReadStruct();
866 1194
867 png_structp png_ptr; 1195 png_structp png_ptr;
868 png_infop info_ptr; 1196 png_infop info_ptr;
869 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, & info_ptr)) { 1197 if (!read_header(this->stream(), fPngChunkReader.get(), nullptr, &png_ptr, & info_ptr)) {
870 return false; 1198 return false;
871 } 1199 }
872 1200
873 fPng_ptr = png_ptr; 1201 fPng_ptr = png_ptr;
874 fInfo_ptr = info_ptr; 1202 fInfo_ptr = info_ptr;
875 return true; 1203 return true;
1204 #endif
876 } 1205 }
877 1206
878 SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, 1207 SkCodec::Result SkPngCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst,
879 size_t rowBytes, const Options& options, 1208 size_t rowBytes, const Options& options,
880 SkPMColor ctable[], int* ctableCount, 1209 SkPMColor ctable[], int* ctableCount,
881 int* rowsDecoded) { 1210 int* rowsDecoded) {
882 if (!conversion_possible(dstInfo, this->getInfo()) || 1211 if (!conversion_possible(dstInfo, this->getInfo()) ||
883 !this->initializeXforms(dstInfo, options, ctable, ctableCount)) 1212 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
884 { 1213 {
885 return kInvalidConversion; 1214 return kInvalidConversion;
886 } 1215 }
1216 #ifdef SK_GOOGLE3_PNG_HACK
1217 // Note that this is done after initializeXforms. Otherwise that method
1218 // would not have png_ptr to use.
1219 if (!this->rereadHeaderIfNecessary()) {
1220 return kCouldNotRewind;
1221 }
1222 #endif
887 1223
888 if (options.fSubset) { 1224 if (options.fSubset) {
889 return kUnimplemented; 1225 return kUnimplemented;
890 } 1226 }
891 1227
892 this->allocateStorage(dstInfo); 1228 this->allocateStorage(dstInfo);
893 int count = this->readRows(dstInfo, dst, rowBytes, dstInfo.height(), 0); 1229 this->initializeXformAlphaAndWidth();
894 if (count > dstInfo.height()) { 1230 return this->decodeAllRows(dst, rowBytes, rowsDecoded);
895 *rowsDecoded = count; 1231 }
896 return kIncompleteInput; 1232
1233 SkCodec::Result SkPngCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
1234 void* dst, size_t rowBytes, const SkCodec::Options& options,
1235 SkPMColor* ctable, int* ctableCount) {
1236 if (!conversion_possible(dstInfo, this->getInfo()) ||
1237 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1238 {
1239 return kInvalidConversion;
897 } 1240 }
1241 #ifdef SK_GOOGLE3_PNG_HACK
1242 // See note in onGetPixels.
1243 if (!this->rereadHeaderIfNecessary()) {
1244 return kCouldNotRewind;
1245 }
1246 #endif
898 1247
1248 this->allocateStorage(dstInfo);
1249
1250 int firstRow, lastRow;
1251 if (options.fSubset) {
1252 firstRow = options.fSubset->top();
1253 lastRow = options.fSubset->bottom() - 1;
1254 } else {
1255 firstRow = 0;
1256 lastRow = dstInfo.height() - 1;
1257 }
1258 this->setRange(firstRow, lastRow, dst, rowBytes);
899 return kSuccess; 1259 return kSuccess;
900 } 1260 }
901 1261
1262 SkCodec::Result SkPngCodec::onIncrementalDecode(int* rowsDecoded) {
1263 // FIXME: Only necessary on the first call.
1264 this->initializeXformAlphaAndWidth();
1265
1266 return this->decode(rowsDecoded);
1267 }
1268
902 uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 1269 uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
903 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 1270 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
904 if (colorPtr) { 1271 if (colorPtr) {
905 SkAlphaType alphaType = select_alpha_xform(dstInfo.alphaType(), 1272 SkAlphaType alphaType = select_alpha_xform(dstInfo.alphaType(),
906 this->getInfo().alphaType()); 1273 this->getInfo().alphaType());
907 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorP tr, 0, 1274 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorP tr, 0,
908 fColorXform.get()); 1275 fColorXform.get());
909 } 1276 }
910 return INHERITED::onGetFillValue(dstInfo); 1277 return INHERITED::onGetFillValue(dstInfo);
911 } 1278 }
912 1279
913 SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkRead er) { 1280 SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkRead er) {
914 SkAutoTDelete<SkStream> streamDeleter(stream); 1281 SkAutoTDelete<SkStream> streamDeleter(stream);
915 1282
916 SkCodec* outCodec; 1283 SkCodec* outCodec = nullptr;
917 if (read_header(stream, chunkReader, &outCodec, nullptr, nullptr)) { 1284 if (read_header(streamDeleter.get(), chunkReader, &outCodec, nullptr, nullpt r)) {
918 // Codec has taken ownership of the stream. 1285 // Codec has taken ownership of the stream.
919 SkASSERT(outCodec); 1286 SkASSERT(outCodec);
920 streamDeleter.release(); 1287 streamDeleter.release();
921 return outCodec; 1288 return outCodec;
922 } 1289 }
923 1290
924 return nullptr; 1291 return nullptr;
925 } 1292 }
OLDNEW
« no previous file with comments | « src/codec/SkPngCodec.h ('k') | src/codec/SkSampledCodec.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698