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

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: Workaround bug 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
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"
(...skipping 13 matching lines...) Expand all
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 /////////////////////////////////////////////////////////////////////////////// 30 ///////////////////////////////////////////////////////////////////////////////
31 // Callback functions 31 // Callback functions
32 /////////////////////////////////////////////////////////////////////////////// 32 ///////////////////////////////////////////////////////////////////////////////
33 33
34 // When setjmp is first called, it returns 0, meaning longjmp was not called.
35 constexpr int kSetJmpOkay = 0;
36 // An error internal to libpng.
37 constexpr int kPngError = 1;
38 // Passed to longjmp when we have decoded as many lines as we need.
39 constexpr int kStopDecoding = 2;
40
34 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) { 41 static void sk_error_fn(png_structp png_ptr, png_const_charp msg) {
35 SkCodecPrintf("------ png error %s\n", msg); 42 SkCodecPrintf("------ png error %s\n", msg);
36 longjmp(png_jmpbuf(png_ptr), 1); 43 longjmp(png_jmpbuf(png_ptr), kPngError);
37 } 44 }
38 45
39 void sk_warning_fn(png_structp, png_const_charp msg) { 46 void sk_warning_fn(png_structp, png_const_charp msg) {
40 SkCodecPrintf("----- png warning %s\n", msg); 47 SkCodecPrintf("----- png warning %s\n", msg);
41 } 48 }
42 49
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 50 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
56 static int sk_read_user_chunk(png_structp png_ptr, png_unknown_chunkp chunk) { 51 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); 52 SkPngChunkReader* chunkReader = (SkPngChunkReader*)png_get_user_chunk_ptr(pn g_ptr);
58 // readChunk() returning true means continue decoding 53 // readChunk() returning true means continue decoding
59 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk-> size) ? 1 : -1; 54 return chunkReader->readChunk((const char*)chunk->name, chunk->data, chunk-> size) ? 1 : -1;
60 } 55 }
61 #endif 56 #endif
62 57
63 /////////////////////////////////////////////////////////////////////////////// 58 ///////////////////////////////////////////////////////////////////////////////
64 // Helpers 59 // Helpers
65 /////////////////////////////////////////////////////////////////////////////// 60 ///////////////////////////////////////////////////////////////////////////////
66 61
67 class AutoCleanPng : public SkNoncopyable { 62 class AutoCleanPng : public SkNoncopyable {
68 public: 63 public:
69 AutoCleanPng(png_structp png_ptr) 64 /*
65 * This class does not take ownership of stream or reader, but if codecPtr
66 * is non-NULL, and decodeBounds succeeds, it will have created a new
67 * SkCodec (pointed to by *codecPtr) which will own/ref them, as well as
68 * the png_ptr and info_ptr.
69 */
70 AutoCleanPng(png_structp png_ptr, SkStream* stream, SkPngChunkReader* reader ,
71 SkCodec** codecPtr)
70 : fPng_ptr(png_ptr) 72 : fPng_ptr(png_ptr)
71 , fInfo_ptr(nullptr) {} 73 , fInfo_ptr(nullptr)
74 , fDecodedBounds(false)
75 , fReadHeader(false)
76 , fStream(stream)
77 , fChunkReader(reader)
78 , fOutCodec(codecPtr)
79 {}
72 80
73 ~AutoCleanPng() { 81 ~AutoCleanPng() {
74 // fInfo_ptr will never be non-nullptr unless fPng_ptr is. 82 // fInfo_ptr will never be non-nullptr unless fPng_ptr is.
75 if (fPng_ptr) { 83 if (fPng_ptr) {
76 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr; 84 png_infopp info_pp = fInfo_ptr ? &fInfo_ptr : nullptr;
77 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr); 85 png_destroy_read_struct(&fPng_ptr, info_pp, nullptr);
78 } 86 }
79 } 87 }
80 88
81 void setInfoPtr(png_infop info_ptr) { 89 void setInfoPtr(png_infop info_ptr) {
82 SkASSERT(nullptr == fInfo_ptr); 90 SkASSERT(nullptr == fInfo_ptr);
83 fInfo_ptr = info_ptr; 91 fInfo_ptr = info_ptr;
84 } 92 }
85 93
86 void release() { 94 /**
95 * Reads enough of the input stream to decode the bounds.
96 * @return false if the stream is not a valid PNG (or too short).
97 * true if it read enough of the stream to determine the bounds.
98 * In the latter case, the stream may have been read beyond the
99 * point to determine the bounds, and the png_ptr will have saved
100 * any extra data. Further, if the codecPtr supplied to the
101 * constructor was not NULL, it will now point to a new SkCodec,
102 * which owns (or refs, in the case of the SkPngChunkReader) the
103 * inputs. If codecPtr was NULL, the png_ptr and info_ptr are
104 * unowned, and it is up to the caller to destroy them.
105 */
106 bool decodeBounds();
107
108 private:
109 png_structp fPng_ptr;
110 png_infop fInfo_ptr;
111 bool fDecodedBounds;
112 bool fReadHeader;
113 SkStream* fStream;
114 SkPngChunkReader* fChunkReader;
115 SkCodec** fOutCodec;
116
117 /**
118 * Supplied to libpng to call when it has read enough data to determine
119 * bounds.
120 */
121 static void InfoCallback(png_structp png_ptr, png_infop info_ptr) {
122 // png_get_progressive_ptr returns the pointer we set on the png_ptr wit h
123 // png_set_progressive_read_fn
124 static_cast<AutoCleanPng*>(png_get_progressive_ptr(png_ptr))->infoCallba ck();
125 }
126
127 void infoCallback();
128
129 void releasePngPtrs() {
87 fPng_ptr = nullptr; 130 fPng_ptr = nullptr;
88 fInfo_ptr = nullptr; 131 fInfo_ptr = nullptr;
89 } 132 }
90
91 private:
92 png_structp fPng_ptr;
93 png_infop fInfo_ptr;
94 }; 133 };
95 #define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng) 134 #define AutoCleanPng(...) SK_REQUIRE_LOCAL_VAR(AutoCleanPng)
96 135
136 bool AutoCleanPng::decodeBounds() {
137 if (setjmp(png_jmpbuf(fPng_ptr))) {
138 return false;
139 }
140
141 png_set_progressive_read_fn(fPng_ptr, this, InfoCallback, nullptr, nullptr);
142
143 // Arbitrary buffer size, though note that it matches (below)
144 // SkPngCodec::processData(). FIXME: Can we better suit this to the size of
145 // the PNG header?
146 constexpr size_t kBufferSize = 4096;
147 char buffer[kBufferSize];
148
149 while (true) {
150 const size_t bytesRead = fStream->read(buffer, kBufferSize);
151 if (!bytesRead) {
152 // We have read to the end of the input without decoding bounds.
153 break;
154 }
155
156 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
157 if (fReadHeader) {
158 break;
159 }
160 }
161
162 // For safety, clear the pointer to this object.
163 png_set_progressive_read_fn(fPng_ptr, nullptr, nullptr, nullptr, nullptr);
164 return fDecodedBounds;
165 }
166
167 void SkPngCodec::processData() {
168 switch (setjmp(png_jmpbuf(fPng_ptr))) {
169 case kPngError:
170 // There was an error. Stop processing data.
171 // FIXME: Do we need to discard png_ptr?
172 return;
173 case kStopDecoding:
174 // We decoded all the lines we want.
175 return;
176 case kSetJmpOkay:
177 // Everything is okay.
178 break;
179 default:
180 // No other values should be passed to longjmp.
181 SkASSERT(false);
182 }
183
184 // Arbitrary buffer size
185 constexpr size_t kBufferSize = 4096;
186 char buffer[kBufferSize];
187
188 while (true) {
189 const size_t bytesRead = this->stream()->read(buffer, kBufferSize);
190 png_process_data(fPng_ptr, fInfo_ptr, (png_bytep) buffer, bytesRead);
191
192 if (!bytesRead) {
193 // We have read to the end of the input. Note that we quit *after*
194 // calling png_process_data, because decodeBounds may have told
195 // libpng to save the remainder of the buffer, in which case
196 // png_process_data will process the saved buffer, though the
197 // stream has no more to read.
198 break;
199 }
200 }
201 }
202
97 // Note: SkColorTable claims to store SkPMColors, which is not necessarily the c ase here. 203 // Note: SkColorTable claims to store SkPMColors, which is not necessarily the c ase here.
98 bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) { 204 bool SkPngCodec::createColorTable(const SkImageInfo& dstInfo, int* ctableCount) {
99 205
100 int numColors; 206 int numColors;
101 png_color* palette; 207 png_color* palette;
102 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) { 208 if (!png_get_PLTE(fPng_ptr, fInfo_ptr, &palette, &numColors)) {
103 return false; 209 return false;
104 } 210 }
105 211
106 // Contents depend on tableColorType and our choice of if/when to premultipl y: 212 // Contents depend on tableColorType and our choice of if/when to premultipl y:
(...skipping 238 matching lines...) Expand 10 before | Expand all | Expand 10 after
345 return SkColorSpace_Base::NewRGB(gammas, toXYZD50); 451 return SkColorSpace_Base::NewRGB(gammas, toXYZD50);
346 } 452 }
347 453
348 #endif // LIBPNG >= 1.6 454 #endif // LIBPNG >= 1.6
349 455
350 // Report that there is no color space information in the PNG. SkPngCodec i s currently 456 // Report that there is no color space information in the PNG. SkPngCodec i s currently
351 // implemented to guess sRGB in this case. 457 // implemented to guess sRGB in this case.
352 return nullptr; 458 return nullptr;
353 } 459 }
354 460
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) { 461 void SkPngCodec::allocateStorage(const SkImageInfo& dstInfo) {
362 switch (fXformMode) { 462 switch (fXformMode) {
363 case kSwizzleOnly_XformMode: 463 case kSwizzleOnly_XformMode:
364 fStorage.reset(SkAlign4(fSrcRowBytes));
365 fSwizzlerSrcRow = fStorage.get();
366 break; 464 break;
367 case kColorOnly_XformMode: 465 case kColorOnly_XformMode:
368 // Intentional fall through. A swizzler hasn't been created yet, bu t one will 466 // 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 467 // be created later if we are sampling. We'll go ahead and allocate
370 // enough memory to swizzle if necessary. 468 // enough memory to swizzle if necessary.
371 case kSwizzleColor_XformMode: { 469 case kSwizzleColor_XformMode: {
372 size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t); 470 const size_t colorXformBytes = dstInfo.width() * sizeof(uint32_t);
373 fStorage.reset(SkAlign4(fSrcRowBytes) + colorXformBytes); 471 fStorage.reset(colorXformBytes);
374 fSwizzlerSrcRow = fStorage.get(); 472 fColorXformSrcRow = (uint32_t*) fStorage.get();
375 fColorXformSrcRow = SkTAddOffset<uint32_t>(fSwizzlerSrcRow, SkAlign4 (fSrcRowBytes));
376 break; 473 break;
377 } 474 }
378 } 475 }
379 } 476 }
380 477
381 void SkPngCodec::applyXformRow(void* dst, const void* src, SkColorType colorType , 478 void SkPngCodec::applyXformRow(void* dst, const void* src) {
382 SkAlphaType alphaType, int width) { 479 const SkColorType colorType = this->dstInfo().colorType();
383 switch (fXformMode) { 480 switch (fXformMode) {
384 case kSwizzleOnly_XformMode: 481 case kSwizzleOnly_XformMode:
385 fSwizzler->swizzle(dst, (const uint8_t*) src); 482 fSwizzler->swizzle(dst, (const uint8_t*) src);
386 break; 483 break;
387 case kColorOnly_XformMode: 484 case kColorOnly_XformMode:
388 fColorXform->apply(dst, (const uint32_t*) src, width, colorType, alp haType); 485 fColorXform->apply(dst, (const uint32_t*) src, fXformWidth, colorTyp e, fXformAlphaType);
389 break; 486 break;
390 case kSwizzleColor_XformMode: 487 case kSwizzleColor_XformMode:
391 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src); 488 fSwizzler->swizzle(fColorXformSrcRow, (const uint8_t*) src);
392 fColorXform->apply(dst, fColorXformSrcRow, width, colorType, alphaTy pe); 489 fColorXform->apply(dst, fColorXformSrcRow, fXformWidth, colorType, f XformAlphaType);
393 break; 490 break;
394 } 491 }
395 } 492 }
396 493
397 class SkPngNormalCodec : public SkPngCodec { 494 class SkPngNormalDecoder : public SkPngCodec {
398 public: 495 public:
399 SkPngNormalCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imageI nfo, 496 SkPngNormalDecoder(const SkEncodedInfo& info, const SkImageInfo& imageInfo, SkStream* stream,
400 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr , 497 SkPngChunkReader* reader, png_structp png_ptr, png_infop info_ptr, i nt bitDepth)
401 png_infop info_ptr, int bitDepth) 498 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth )
402 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_p tr, bitDepth, 1) 499 , fLinesDecoded(0)
500 , fDst(nullptr)
501 , fRowBytes(0)
502 , fFirstRow(0)
503 , fLastRow(0)
403 {} 504 {}
404 505
405 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& opti ons, 506 static void AllRowsCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowNum, int /*pass*/) {
406 SkPMColor ctable[], int* ctableCount) override { 507 GetDecoder(png_ptr)->allRowsCallback(row, rowNum);
407 if (!conversion_possible(dstInfo, this->getInfo()) || 508 }
408 !this->initializeXforms(dstInfo, options, ctable, ctableCount)) 509
409 { 510 static void RowCallback(png_structp png_ptr, png_bytep row, png_uint_32 rowN um, int /*pass*/) {
410 return kInvalidConversion; 511 GetDecoder(png_ptr)->rowCallback(row, rowNum);
411 } 512 }
412 513 private:
413 this->allocateStorage(dstInfo); 514 int fLinesDecoded; // FIXME: Move to baseclass?
414 return kSuccess; 515 void* fDst;
415 } 516 size_t fRowBytes;
416 517
417 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int cou nt, int startRow) 518 // Variables for partial decode
418 override { 519 int fFirstRow; // FIXME: Move to baseclass?
419 SkASSERT(0 == startRow); 520 int fLastRow;
420 521
421 // Assume that an error in libpng indicates an incomplete input. 522 typedef SkPngCodec INHERITED;
422 int y = 0; 523
423 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 524 static SkPngNormalDecoder* GetDecoder(png_structp png_ptr) {
424 SkCodecPrintf("Failed to read row.\n"); 525 return static_cast<SkPngNormalDecoder*>(png_get_progressive_ptr(png_ptr) );
425 return y; 526 }
426 } 527
427 528 Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
428 SkAlphaType xformAlphaType = select_alpha_xform(dstInfo.alphaType(), 529 const int height = this->getInfo().height();
429 this->getInfo().alphaTyp e()); 530 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, AllRowsCallb ack, nullptr);
430 int width = fSwizzler ? fSwizzler->swizzleWidth() : dstInfo.width(); 531 fDst = dst;
431 532 fRowBytes = rowBytes;
432 for (; y < count; y++) { 533
433 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr); 534 fLinesDecoded = 0;
434 this->applyXformRow(dst, fSwizzlerSrcRow, dstInfo.colorType(), xform AlphaType, width); 535
536 this->processData();
537
538 if (fLinesDecoded == height) {
539 return SkCodec::kSuccess;
540 }
541
542 if (rowsDecoded) {
543 *rowsDecoded = fLinesDecoded;
544 }
545
546 return SkCodec::kIncompleteInput;
547 }
548
549 void allRowsCallback(png_bytep row, int rowNum) {
550 SkASSERT(rowNum - fFirstRow == fLinesDecoded);
551 fLinesDecoded++;
552 this->applyXformRow(fDst, row);
553 fDst = SkTAddOffset<void>(fDst, fRowBytes);
554 }
555
556 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) overrid e {
557 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, RowCallback, nullptr);
558 fFirstRow = firstRow;
559 fLastRow = lastRow;
560 fDst = dst;
561 fRowBytes = rowBytes;
562 fLinesDecoded = 0;
563 }
564
565 SkCodec::Result decode(int* rowsDecoded) override {
566 this->processData();
567
568 if (fLinesDecoded == fLastRow - fFirstRow + 1) {
569 return SkCodec::kSuccess;
570 }
571
572 if (rowsDecoded) {
573 *rowsDecoded = fLinesDecoded;
574 }
575
576 return SkCodec::kIncompleteInput;
577 }
578
579 void rowCallback(png_bytep row, int rowNum) {
580 if (rowNum < fFirstRow) {
581 // Ignore this row.
582 return;
583 }
584
585 SkASSERT(rowNum <= fLastRow);
586
587 // If there is no swizzler, all rows are needed.
588 if (!this->swizzler() || this->swizzler()->rowNeeded(fLinesDecoded)) {
589 this->applyXformRow(fDst, row);
590 fDst = SkTAddOffset<void>(fDst, fRowBytes);
591 }
592
593 fLinesDecoded++;
594
595 if (rowNum == fLastRow) {
596 // Fake error to stop decoding scanlines.
597 longjmp(png_jmpbuf(this->png_ptr()), kStopDecoding);
598 }
599 }
600 };
601
602 class SkPngInterlacedDecoder : public SkPngCodec {
603 public:
604 SkPngInterlacedDecoder(const SkEncodedInfo& info, const SkImageInfo& imageIn fo,
605 SkStream* stream, SkPngChunkReader* reader, png_structp png_ptr, png _infop info_ptr,
606 int bitDepth, int numberPasses)
607 : INHERITED(info, imageInfo, stream, reader, png_ptr, info_ptr, bitDepth )
608 , fNumberPasses(numberPasses)
609 , fFirstRow(0)
610 , fLastRow(0)
611 , fLinesDecoded(0)
612 , fInterlacedComplete(false)
613 , fPng_rowbytes(0)
614 {}
615
616 static void InterlacedRowCallback(png_structp png_ptr, png_bytep row, png_ui nt_32 rowNum, int pass) {
617 auto decoder = static_cast<SkPngInterlacedDecoder*>(png_get_progressive_ ptr(png_ptr));
618 decoder->interlacedRowCallback(row, rowNum, pass);
619 }
620
621 private:
622 const int fNumberPasses;
623 int fFirstRow;
624 int fLastRow;
625 void* fDst;
626 size_t fRowBytes;
627 int fLinesDecoded;
628 bool fInterlacedComplete;
629 size_t fPng_rowbytes;
630 SkAutoTMalloc<png_byte> fInterlaceBuffer;
631
632 typedef SkPngCodec INHERITED;
633
634 // FIXME: Currently sharing interlaced callback for all rows and subset. It' s not
635 // as expensive as the subset version of non-interlaced, but it still does e xtra
636 // work.
637 void interlacedRowCallback(png_bytep row, int rowNum, int pass) {
638 if (rowNum < fFirstRow || rowNum > fLastRow) {
639 // Ignore this row
640 return;
641 }
642
643 png_bytep oldRow = fInterlaceBuffer.get() + (rowNum - fFirstRow) * fPng_ rowbytes;
644 png_progressive_combine_row(this->png_ptr(), oldRow, row);
645
646 if (0 == pass) {
647 // The first pass initializes all rows.
648 SkASSERT(row);
649 SkASSERT(fLinesDecoded == rowNum - fFirstRow);
650 fLinesDecoded++;
651 } else {
652 SkASSERT(fLinesDecoded == fLastRow - fFirstRow + 1);
653 if (fNumberPasses - 1 == pass && rowNum == fLastRow) {
654 // Last pass, and we have read all of the rows we care about. No te that
655 // we do not care about reading anything beyond the end of the i mage (or
656 // beyond the last scanline requested).
657 fInterlacedComplete = true;
658 // Fake error to stop decoding scanlines.
659 longjmp(png_jmpbuf(this->png_ptr()), kStopDecoding);
660 }
661 }
662 }
663
664 SkCodec::Result decodeAllRows(void* dst, size_t rowBytes, int* rowsDecoded) override {
665 const int height = this->getInfo().height();
666 this->setUpInterlaceBuffer(height);
667 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, InterlacedRo wCallback, nullptr);
668
669 fFirstRow = 0;
670 fLastRow = height - 1;
671 fLinesDecoded = 0;
672
673 this->processData();
674
675 png_bytep srcRow = fInterlaceBuffer.get();
676 // FIXME: When resuming, this may rewrite rows that did not change.
677 for (int rowNum = 0; rowNum < fLinesDecoded; rowNum++) {
678 this->applyXformRow(dst, srcRow);
435 dst = SkTAddOffset<void>(dst, rowBytes); 679 dst = SkTAddOffset<void>(dst, rowBytes);
436 } 680 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes);
437 681 }
438 return y; 682 if (fInterlacedComplete) {
439 } 683 return SkCodec::kSuccess;
440 684 }
441 int onGetScanlines(void* dst, int count, size_t rowBytes) override { 685
442 return this->readRows(this->dstInfo(), dst, rowBytes, count, 0); 686 if (rowsDecoded) {
443 } 687 *rowsDecoded = fLinesDecoded;
444 688 }
445 bool onSkipScanlines(int count) override { 689
446 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) { 690 return SkCodec::kIncompleteInput;
447 SkCodecPrintf("Failed to skip row.\n"); 691 }
448 return false; 692
449 } 693 void setRange(int firstRow, int lastRow, void* dst, size_t rowBytes) overrid e {
450 694 // 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++) { 695 this->setUpInterlaceBuffer(lastRow - firstRow + 1);
452 png_read_row(fPng_ptr, fSwizzlerSrcRow, nullptr); 696 png_set_progressive_read_fn(this->png_ptr(), this, nullptr, InterlacedRo wCallback, nullptr);
453 } 697 fFirstRow = firstRow;
454 return true; 698 fLastRow = lastRow;
455 } 699 fDst = dst;
456 700 fRowBytes = rowBytes;
457 typedef SkPngCodec INHERITED; 701 fLinesDecoded = 0;
702 }
703
704 SkCodec::Result decode(int* rowsDecoded) override {
705 this->processData();
706
707 // Now apply Xforms on all the rows that were decoded.
708 if (!fLinesDecoded) {
709 return SkCodec::kIncompleteInput;
710 }
711 const int lastRow = fLinesDecoded + fFirstRow - 1;
712 SkASSERT(lastRow <= fLastRow);
713
714 // FIXME: For resuming interlace, we may swizzle a row that hasn't chang ed. But it
715 // may be too tricky/expensive to handle that correctly.
716 png_bytep srcRow = fInterlaceBuffer.get();
717 const int sampleY = this->swizzler() ? this->swizzler()->sampleY() : 1;
718 void* dst = fDst;
719 for (int rowNum = fFirstRow; rowNum <= lastRow; rowNum += sampleY) {
720 this->applyXformRow(dst, srcRow);
721 dst = SkTAddOffset<void>(dst, fRowBytes);
722 srcRow = SkTAddOffset<png_byte>(srcRow, fPng_rowbytes * sampleY);
723 }
724
725 if (fInterlacedComplete) {
726 return SkCodec::kSuccess;
727 }
728
729 if (rowsDecoded) {
730 *rowsDecoded = fLinesDecoded;
731 }
732 return SkCodec::kIncompleteInput;
733 }
734
735 void setUpInterlaceBuffer(int height) {
736 fPng_rowbytes = png_get_rowbytes(this->png_ptr(), this->info_ptr());
737 fInterlaceBuffer.reset(fPng_rowbytes * height);
738 fInterlacedComplete = false;
739 }
458 }; 740 };
459 741
460 class SkPngInterlacedCodec : public SkPngCodec {
461 public:
462 SkPngInterlacedCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& im ageInfo,
463 SkStream* stream, SkPngChunkReader* chunkReader, png_structp png_ptr ,
464 png_infop info_ptr, int bitDepth, int numberPasses)
465 : INHERITED(encodedInfo, imageInfo, stream, chunkReader, png_ptr, info_p tr, bitDepth,
466 numberPasses)
467 , fCanSkipRewind(false)
468 {
469 SkASSERT(numberPasses != 1);
470 }
471
472 Result onStartScanlineDecode(const SkImageInfo& dstInfo, const Options& opti ons,
473 SkPMColor ctable[], int* ctableCount) override {
474 if (!conversion_possible(dstInfo, this->getInfo()) ||
475 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
476 {
477 return kInvalidConversion;
478 }
479
480 this->allocateStorage(dstInfo);
481 fCanSkipRewind = true;
482 return SkCodec::kSuccess;
483 }
484
485 int readRows(const SkImageInfo& dstInfo, void* dst, size_t rowBytes, int cou nt, int startRow)
486 override {
487 if (setjmp(png_jmpbuf((png_struct*)fPng_ptr))) {
488 SkCodecPrintf("Failed to get scanlines.\n");
489 // FIXME (msarett): Returning 0 is pessimistic. If we can complete a single pass,
490 // we may be able to report that all of the memory has been initiali zed. Even if we
491 // fail on the first pass, we can still report than some scanlines a re initialized.
492 return 0;
493 }
494
495 SkAutoTMalloc<uint8_t> storage(count * fSrcRowBytes);
496 uint8_t* srcRow;
497 for (int i = 0; i < fNumberPasses; i++) {
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
576 // Reads the header and initializes the output fields, if not NULL. 742 // Reads the header and initializes the output fields, if not NULL.
577 // 743 //
578 // @param stream Input data. Will be read to get enough information to properly 744 // @param stream Input data. Will be read to get enough information to properly
579 // setup the codec. 745 // setup the codec.
580 // @param chunkReader SkPngChunkReader, for reading unknown chunks. May be NULL. 746 // @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 747 // 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. 748 // 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 749 // @param outCodec Optional output variable. If non-NULL, will be set to a new
584 // SkPngCodec on success. 750 // SkPngCodec on success.
585 // @param png_ptrp Optional output variable. If non-NULL, will be set to a new 751 // @param png_ptrp Optional output variable. If non-NULL, will be set to a new
586 // png_structp on success. 752 // png_structp on success.
587 // @param info_ptrp Optional output variable. If non-NULL, will be set to a new 753 // @param info_ptrp Optional output variable. If non-NULL, will be set to a new
588 // png_infop on success; 754 // png_infop on success;
589 // @return true on success, in which case the caller is responsible for calling 755 // @return true on success, in which case the caller is responsible for calling
590 // png_destroy_read_struct(png_ptrp, info_ptrp). 756 // png_destroy_read_struct(png_ptrp, info_ptrp).
591 // If it returns false, the passed in fields (except stream) are unchanged. 757 // If it returns false, the passed in fields (except stream) are unchanged.
592 static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec ** outCodec, 758 static bool read_header(SkStream* stream, SkPngChunkReader* chunkReader, SkCodec ** outCodec,
593 png_structp* png_ptrp, png_infop* info_ptrp) { 759 png_structp* png_ptrp, png_infop* info_ptrp) {
594 // The image is known to be a PNG. Decode enough to know the SkImageInfo. 760 // 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, 761 png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
596 sk_error_fn, sk_warning_fn); 762 sk_error_fn, sk_warning_fn);
597 if (!png_ptr) { 763 if (!png_ptr) {
598 return false; 764 return false;
599 } 765 }
600 766
601 AutoCleanPng autoClean(png_ptr); 767 AutoCleanPng autoClean(png_ptr, stream, chunkReader, outCodec);
602 768
603 png_infop info_ptr = png_create_info_struct(png_ptr); 769 png_infop info_ptr = png_create_info_struct(png_ptr);
604 if (info_ptr == nullptr) { 770 if (info_ptr == nullptr) {
605 return false; 771 return false;
606 } 772 }
607 773
608 autoClean.setInfoPtr(info_ptr); 774 autoClean.setInfoPtr(info_ptr);
609 775
610 // FIXME: Could we use the return value of setjmp to specify the type of 776 // FIXME: Could we use the return value of setjmp to specify the type of
611 // error? 777 // error?
612 if (setjmp(png_jmpbuf(png_ptr))) { 778 if (setjmp(png_jmpbuf(png_ptr))) {
613 return false; 779 return false;
614 } 780 }
615 781
616 png_set_read_fn(png_ptr, static_cast<void*>(stream), sk_read_fn);
617
618 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED 782 #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
619 // Hookup our chunkReader so we can see any user-chunks the caller may be in terested in. 783 // 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 784 // This needs to be installed before we read the png header. Android may st ore ninepatch
621 // chunks in the header. 785 // chunks in the header.
622 if (chunkReader) { 786 if (chunkReader) {
623 png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, (png_byte* )"", 0); 787 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); 788 png_set_read_user_chunk_fn(png_ptr, (png_voidp) chunkReader, sk_read_use r_chunk);
625 } 789 }
626 #endif 790 #endif
627 791
628 // The call to png_read_info() gives us all of the information from the 792 const bool decodedBounds = autoClean.decodeBounds();
629 // PNG file before the first IDAT (image data chunk). 793
630 png_read_info(png_ptr, info_ptr); 794 if (!decodedBounds) {
795 return false;
796 }
797
798 // On success, decodeBounds releases ownership of png_ptr and info_ptr.
799 if (png_ptrp) {
800 *png_ptrp = png_ptr;
801 }
802 if (info_ptrp) {
803 *info_ptrp = info_ptr;
804 }
805
806 // decodeBounds takes care of setting outCodec
807 if (outCodec) {
808 SkASSERT(*outCodec);
809 }
810 return true;
811 }
812
813 void AutoCleanPng::infoCallback() {
631 png_uint_32 origWidth, origHeight; 814 png_uint_32 origWidth, origHeight;
632 int bitDepth, encodedColorType; 815 int bitDepth, encodedColorType;
633 png_get_IHDR(png_ptr, info_ptr, &origWidth, &origHeight, &bitDepth, 816 png_get_IHDR(fPng_ptr, fInfo_ptr, &origWidth, &origHeight, &bitDepth,
634 &encodedColorType, nullptr, nullptr, nullptr); 817 &encodedColorType, nullptr, nullptr, nullptr);
635 818
636 // Tell libpng to strip 16 bit/color files down to 8 bits/color. 819 // 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 820 // TODO: Should we handle this in SkSwizzler? Could this also benefit
638 // RAW decodes? 821 // RAW decodes?
639 if (bitDepth == 16) { 822 if (bitDepth == 16) {
640 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType); 823 SkASSERT(PNG_COLOR_TYPE_PALETTE != encodedColorType);
641 png_set_strip_16(png_ptr); 824 png_set_strip_16(fPng_ptr);
642 } 825 }
643 826
644 // Now determine the default colorType and alphaType and set the required tr ansforms. 827 // Now determine the default colorType and alphaType and set the required tr ansforms.
645 // Often, we depend on SkSwizzler to perform any transforms that we need. H owever, we 828 // Often, we depend on SkSwizzler to perform any transforms that we need. H owever, we
646 // still depend on libpng for many of the rare and PNG-specific cases. 829 // still depend on libpng for many of the rare and PNG-specific cases.
647 SkEncodedInfo::Color color; 830 SkEncodedInfo::Color color;
648 SkEncodedInfo::Alpha alpha; 831 SkEncodedInfo::Alpha alpha;
649 switch (encodedColorType) { 832 switch (encodedColorType) {
650 case PNG_COLOR_TYPE_PALETTE: 833 case PNG_COLOR_TYPE_PALETTE:
651 // Extract multiple pixels with bit depths of 1, 2, and 4 from a sin gle 834 // Extract multiple pixels with bit depths of 1, 2, and 4 from a sin gle
652 // byte into separate bytes (useful for paletted and grayscale image s). 835 // byte into separate bytes (useful for paletted and grayscale image s).
653 if (bitDepth < 8) { 836 if (bitDepth < 8) {
654 // TODO: Should we use SkSwizzler here? 837 // TODO: Should we use SkSwizzler here?
655 png_set_packing(png_ptr); 838 png_set_packing(fPng_ptr);
656 } 839 }
657 840
658 color = SkEncodedInfo::kPalette_Color; 841 color = SkEncodedInfo::kPalette_Color;
659 // Set the alpha depending on if a transparency chunk exists. 842 // Set the alpha depending on if a transparency chunk exists.
660 alpha = png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ? 843 alpha = png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS) ?
661 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alph a; 844 SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alph a;
662 break; 845 break;
663 case PNG_COLOR_TYPE_RGB: 846 case PNG_COLOR_TYPE_RGB:
664 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { 847 if (png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS)) {
665 // Convert to RGBA if transparency chunk exists. 848 // Convert to RGBA if transparency chunk exists.
666 png_set_tRNS_to_alpha(png_ptr); 849 png_set_tRNS_to_alpha(fPng_ptr);
667 color = SkEncodedInfo::kRGBA_Color; 850 color = SkEncodedInfo::kRGBA_Color;
668 alpha = SkEncodedInfo::kBinary_Alpha; 851 alpha = SkEncodedInfo::kBinary_Alpha;
669 } else { 852 } else {
670 color = SkEncodedInfo::kRGB_Color; 853 color = SkEncodedInfo::kRGB_Color;
671 alpha = SkEncodedInfo::kOpaque_Alpha; 854 alpha = SkEncodedInfo::kOpaque_Alpha;
672 } 855 }
673 break; 856 break;
674 case PNG_COLOR_TYPE_GRAY: 857 case PNG_COLOR_TYPE_GRAY:
675 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/p ixel. 858 // Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/p ixel.
676 if (bitDepth < 8) { 859 if (bitDepth < 8) {
677 // TODO: Should we use SkSwizzler here? 860 // TODO: Should we use SkSwizzler here?
678 png_set_expand_gray_1_2_4_to_8(png_ptr); 861 png_set_expand_gray_1_2_4_to_8(fPng_ptr);
679 } 862 }
680 863
681 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { 864 if (png_get_valid(fPng_ptr, fInfo_ptr, PNG_INFO_tRNS)) {
682 png_set_tRNS_to_alpha(png_ptr); 865 png_set_tRNS_to_alpha(fPng_ptr);
683 color = SkEncodedInfo::kGrayAlpha_Color; 866 color = SkEncodedInfo::kGrayAlpha_Color;
684 alpha = SkEncodedInfo::kBinary_Alpha; 867 alpha = SkEncodedInfo::kBinary_Alpha;
685 } else { 868 } else {
686 color = SkEncodedInfo::kGray_Color; 869 color = SkEncodedInfo::kGray_Color;
687 alpha = SkEncodedInfo::kOpaque_Alpha; 870 alpha = SkEncodedInfo::kOpaque_Alpha;
688 } 871 }
689 break; 872 break;
690 case PNG_COLOR_TYPE_GRAY_ALPHA: 873 case PNG_COLOR_TYPE_GRAY_ALPHA:
691 color = SkEncodedInfo::kGrayAlpha_Color; 874 color = SkEncodedInfo::kGrayAlpha_Color;
692 alpha = SkEncodedInfo::kUnpremul_Alpha; 875 alpha = SkEncodedInfo::kUnpremul_Alpha;
693 break; 876 break;
694 case PNG_COLOR_TYPE_RGBA: 877 case PNG_COLOR_TYPE_RGBA:
695 color = SkEncodedInfo::kRGBA_Color; 878 color = SkEncodedInfo::kRGBA_Color;
696 alpha = SkEncodedInfo::kUnpremul_Alpha; 879 alpha = SkEncodedInfo::kUnpremul_Alpha;
697 break; 880 break;
698 default: 881 default:
699 // All the color types have been covered above. 882 // All the color types have been covered above.
700 SkASSERT(false); 883 SkASSERT(false);
701 color = SkEncodedInfo::kRGBA_Color; 884 color = SkEncodedInfo::kRGBA_Color;
702 alpha = SkEncodedInfo::kUnpremul_Alpha; 885 alpha = SkEncodedInfo::kUnpremul_Alpha;
703 } 886 }
704 887
705 int numberPasses = png_set_interlace_handling(png_ptr); 888 const int numberPasses = png_set_interlace_handling(fPng_ptr);
706 889
707 autoClean.release(); 890 fReadHeader = true;
708 if (png_ptrp) { 891 // 1 tells libpng to save any extra data. We may be able to be more efficien t by saving
709 *png_ptrp = png_ptr; 892 // it ourselves.
710 } 893 png_process_data_pause(fPng_ptr, 1);
711 if (info_ptrp) { 894 fDecodedBounds = true;
712 *info_ptrp = info_ptr; 895 if (fOutCodec) {
713 } 896 SkASSERT(nullptr == *fOutCodec);
714 897 sk_sp<SkColorSpace> colorSpace = read_color_space(fPng_ptr, fInfo_ptr);
715 if (outCodec) {
716 sk_sp<SkColorSpace> colorSpace = read_color_space(png_ptr, info_ptr);
717 if (!colorSpace) { 898 if (!colorSpace) {
718 // Treat unmarked pngs as sRGB. 899 // Treat unmarked pngs as sRGB.
719 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named); 900 colorSpace = SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named);
720 } 901 }
721 902
722 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8); 903 SkEncodedInfo encodedInfo = SkEncodedInfo::Make(color, alpha, 8);
723 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace); 904 SkImageInfo imageInfo = encodedInfo.makeImageInfo(origWidth, origHeight, colorSpace);
724 905
725 if (SkEncodedInfo::kOpaque_Alpha == alpha) { 906 if (SkEncodedInfo::kOpaque_Alpha == alpha) {
726 png_color_8p sigBits; 907 png_color_8p sigBits;
727 if (png_get_sBIT(png_ptr, info_ptr, &sigBits)) { 908 if (png_get_sBIT(fPng_ptr, fInfo_ptr, &sigBits)) {
728 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->bl ue) { 909 if (5 == sigBits->red && 6 == sigBits->green && 5 == sigBits->bl ue) {
729 // Recommend a decode to 565 if the sBIT indicates 565. 910 // Recommend a decode to 565 if the sBIT indicates 565.
730 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType); 911 imageInfo = imageInfo.makeColorType(kRGB_565_SkColorType);
731 } 912 }
732 } 913 }
733 } 914 }
734 915
735 if (1 == numberPasses) { 916 if (1 == numberPasses) {
736 *outCodec = new SkPngNormalCodec(encodedInfo, imageInfo, stream, 917 *fOutCodec = new SkPngNormalDecoder(encodedInfo, imageInfo, fStream,
737 chunkReader, png_ptr, info_ptr, bitDepth); 918 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth);
738 } else { 919 } else {
739 *outCodec = new SkPngInterlacedCodec(encodedInfo, imageInfo, stream, 920 *fOutCodec = new SkPngInterlacedDecoder(encodedInfo, imageInfo, fStr eam,
740 chunkReader, png_ptr, info_ptr, bitDepth, numberPasses); 921 fChunkReader, fPng_ptr, fInfo_ptr, bitDepth, numberPasses);
741 } 922 }
742 } 923 }
743 924
744 return true; 925
926 // Release the pointers, which are now owned by the codec or the caller is e xpected to
927 // take ownership.
928 this->releasePngPtrs();
745 } 929 }
746 930
747 SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imag eInfo, 931 SkPngCodec::SkPngCodec(const SkEncodedInfo& encodedInfo, const SkImageInfo& imag eInfo,
748 SkStream* stream, SkPngChunkReader* chunkReader, void* pn g_ptr, 932 SkStream* stream, SkPngChunkReader* chunkReader, void* pn g_ptr,
749 void* info_ptr, int bitDepth, int numberPasses) 933 void* info_ptr, int bitDepth)
750 : INHERITED(encodedInfo, imageInfo, stream) 934 : INHERITED(encodedInfo, imageInfo, stream)
751 , fPngChunkReader(SkSafeRef(chunkReader)) 935 , fPngChunkReader(SkSafeRef(chunkReader))
752 , fPng_ptr(png_ptr) 936 , fPng_ptr(png_ptr)
753 , fInfo_ptr(info_ptr) 937 , fInfo_ptr(info_ptr)
754 , fSwizzlerSrcRow(nullptr)
755 , fColorXformSrcRow(nullptr) 938 , fColorXformSrcRow(nullptr)
756 , fSrcRowBytes(imageInfo.width() * (bytes_per_pixel(this->getEncodedInfo().b itsPerPixel())))
757 , fNumberPasses(numberPasses)
758 , fBitDepth(bitDepth) 939 , fBitDepth(bitDepth)
759 {} 940 {}
760 941
761 SkPngCodec::~SkPngCodec() { 942 SkPngCodec::~SkPngCodec() {
762 this->destroyReadStruct(); 943 this->destroyReadStruct();
763 } 944 }
764 945
765 void SkPngCodec::destroyReadStruct() { 946 void SkPngCodec::destroyReadStruct() {
766 if (fPng_ptr) { 947 if (fPng_ptr) {
767 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr 948 // We will never have a nullptr fInfo_ptr with a non-nullptr fPng_ptr
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
811 } 992 }
812 } 993 }
813 994
814 // Copy the color table to the client if they request kIndex8 mode. 995 // Copy the color table to the client if they request kIndex8 mode.
815 copy_color_table(dstInfo, fColorTable, ctable, ctableCount); 996 copy_color_table(dstInfo, fColorTable, ctable, ctableCount);
816 997
817 this->initializeSwizzler(dstInfo, options); 998 this->initializeSwizzler(dstInfo, options);
818 return true; 999 return true;
819 } 1000 }
820 1001
1002 void SkPngCodec::initializeXformAlphaAndWidth() {
1003 fXformAlphaType = select_alpha_xform(this->dstInfo().alphaType(), this->getI nfo().alphaType());
1004 fXformWidth = this->swizzler() ? this->swizzler()->swizzleWidth() : this->ds tInfo().width();
1005 }
1006
821 static inline bool apply_xform_on_decode(SkColorType dstColorType, SkEncodedInfo ::Color srcColor) { 1007 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. 1008 // 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; 1009 return SkEncodedInfo::kPalette_Color != srcColor || kRGBA_F16_SkColorType == dstColorType;
824 } 1010 }
825 1011
826 void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o ptions) { 1012 void SkPngCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& o ptions) {
827 SkImageInfo swizzlerInfo = dstInfo; 1013 SkImageInfo swizzlerInfo = dstInfo;
828 Options swizzlerOptions = options; 1014 Options swizzlerOptions = options;
829 fXformMode = kSwizzleOnly_XformMode; 1015 fXformMode = kSwizzleOnly_XformMode;
830 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncod edInfo().color())) { 1016 if (fColorXform && apply_xform_on_decode(dstInfo.colorType(), this->getEncod edInfo().color())) {
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
883 !this->initializeXforms(dstInfo, options, ctable, ctableCount)) 1069 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
884 { 1070 {
885 return kInvalidConversion; 1071 return kInvalidConversion;
886 } 1072 }
887 1073
888 if (options.fSubset) { 1074 if (options.fSubset) {
889 return kUnimplemented; 1075 return kUnimplemented;
890 } 1076 }
891 1077
892 this->allocateStorage(dstInfo); 1078 this->allocateStorage(dstInfo);
893 int count = this->readRows(dstInfo, dst, rowBytes, dstInfo.height(), 0); 1079 this->initializeXformAlphaAndWidth();
894 if (count > dstInfo.height()) { 1080 return this->decodeAllRows(dst, rowBytes, rowsDecoded);
895 *rowsDecoded = count; 1081 }
896 return kIncompleteInput; 1082
1083 SkCodec::Result SkPngCodec::onStartIncrementalDecode(const SkImageInfo& dstInfo,
1084 void* dst, size_t rowBytes, const SkCodec::Options& options,
1085 SkPMColor* ctable, int* ctableCount) {
1086 if (!conversion_possible(dstInfo, this->getInfo()) ||
1087 !this->initializeXforms(dstInfo, options, ctable, ctableCount))
1088 {
1089 return kInvalidConversion;
897 } 1090 }
898 1091
1092 this->allocateStorage(dstInfo);
1093
1094 int firstRow, lastRow;
1095 if (options.fSubset) {
1096 firstRow = options.fSubset->top();
1097 lastRow = options.fSubset->bottom() - 1;
1098 } else {
1099 firstRow = 0;
1100 lastRow = dstInfo.height() - 1;
1101 }
1102 this->setRange(firstRow, lastRow, dst, rowBytes);
899 return kSuccess; 1103 return kSuccess;
900 } 1104 }
901 1105
1106 SkCodec::Result SkPngCodec::onIncrementalDecode(int* rowsDecoded) {
1107 // FIXME: Only necessary on the first call.
1108 this->initializeXformAlphaAndWidth();
1109
1110 return this->decode(rowsDecoded);
1111 }
1112
902 uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const { 1113 uint64_t SkPngCodec::onGetFillValue(const SkImageInfo& dstInfo) const {
903 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get()); 1114 const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
904 if (colorPtr) { 1115 if (colorPtr) {
905 SkAlphaType alphaType = select_alpha_xform(dstInfo.alphaType(), 1116 SkAlphaType alphaType = select_alpha_xform(dstInfo.alphaType(),
906 this->getInfo().alphaType()); 1117 this->getInfo().alphaType());
907 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorP tr, 0, 1118 return get_color_table_fill_value(dstInfo.colorType(), alphaType, colorP tr, 0,
908 fColorXform.get()); 1119 fColorXform.get());
909 } 1120 }
910 return INHERITED::onGetFillValue(dstInfo); 1121 return INHERITED::onGetFillValue(dstInfo);
911 } 1122 }
912 1123
913 SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkRead er) { 1124 SkCodec* SkPngCodec::NewFromStream(SkStream* stream, SkPngChunkReader* chunkRead er) {
914 SkAutoTDelete<SkStream> streamDeleter(stream); 1125 SkAutoTDelete<SkStream> streamDeleter(stream);
915 1126
916 SkCodec* outCodec; 1127 SkCodec* outCodec = nullptr;
917 if (read_header(stream, chunkReader, &outCodec, nullptr, nullptr)) { 1128 if (read_header(stream, chunkReader, &outCodec, nullptr, nullptr)) {
918 // Codec has taken ownership of the stream. 1129 // Codec has taken ownership of the stream.
919 SkASSERT(outCodec); 1130 SkASSERT(outCodec);
920 streamDeleter.release(); 1131 streamDeleter.release();
921 return outCodec; 1132 return outCodec;
922 } 1133 }
923 1134
924 return nullptr; 1135 return nullptr;
925 } 1136 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698