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

Side by Side Diff: third_party/WebKit/Source/platform/image-decoders/png/PNGImageDecoder.cpp

Issue 2386453003: WIP: Implement APNG (Closed)
Patch Set: Change behavior on failure during decoding or parsing. Created 4 years 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 (C) 2006 Apple Computer, Inc. 2 * Copyright (C) 2006 Apple Computer, Inc.
3 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved. 3 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
4 * 4 *
5 * Portions are Copyright (C) 2001 mozilla.org 5 * Portions are Copyright (C) 2001 mozilla.org
6 * 6 *
7 * Other contributors: 7 * Other contributors:
8 * Stuart Parmenter <stuart@mozilla.com> 8 * Stuart Parmenter <stuart@mozilla.com>
9 * 9 *
10 * This library is free software; you can redistribute it and/or 10 * This library is free software; you can redistribute it and/or
(...skipping 20 matching lines...) Expand all
31 * licenses (the MPL or the GPL) and not to allow others to use your 31 * licenses (the MPL or the GPL) and not to allow others to use your
32 * version of this file under the LGPL, indicate your decision by 32 * version of this file under the LGPL, indicate your decision by
33 * deletingthe provisions above and replace them with the notice and 33 * deletingthe provisions above and replace them with the notice and
34 * other provisions required by the MPL or the GPL, as the case may be. 34 * other provisions required by the MPL or the GPL, as the case may be.
35 * If you do not delete the provisions above, a recipient may use your 35 * If you do not delete the provisions above, a recipient may use your
36 * version of this file under any of the LGPL, the MPL or the GPL. 36 * version of this file under any of the LGPL, the MPL or the GPL.
37 */ 37 */
38 38
39 #include "platform/image-decoders/png/PNGImageDecoder.h" 39 #include "platform/image-decoders/png/PNGImageDecoder.h"
40 40
41 #include "platform/image-decoders/png/PNGImageReader.h"
41 #include "png.h" 42 #include "png.h"
42 #include "wtf/PtrUtil.h"
43 #include <memory> 43 #include <memory>
44 44
45 #if !defined(PNG_LIBPNG_VER_MAJOR) || !defined(PNG_LIBPNG_VER_MINOR) 45 #if !defined(PNG_LIBPNG_VER_MAJOR) || !defined(PNG_LIBPNG_VER_MINOR)
46 #error version error: compile against a versioned libpng. 46 #error version error: compile against a versioned libpng.
47 #endif 47 #endif
48 48
49 #if PNG_LIBPNG_VER_MAJOR > 1 || \ 49 #if PNG_LIBPNG_VER_MAJOR > 1 || \
50 (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4) 50 (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4)
51 #define JMPBUF(png_ptr) png_jmpbuf(png_ptr) 51 #define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
52 #else 52 #else
53 #define JMPBUF(png_ptr) png_ptr->jmpbuf 53 #define JMPBUF(png_ptr) png_ptr->jmpbuf
54 #endif 54 #endif
55 55
56 namespace {
57
58 inline blink::PNGImageDecoder* imageDecoder(png_structp png) {
59 return static_cast<blink::PNGImageDecoder*>(png_get_progressive_ptr(png));
60 }
61
62 void PNGAPI pngHeaderAvailable(png_structp png, png_infop) {
63 imageDecoder(png)->headerAvailable();
64 }
65
66 void PNGAPI pngRowAvailable(png_structp png,
67 png_bytep row,
68 png_uint_32 rowIndex,
69 int state) {
70 imageDecoder(png)->rowAvailable(row, rowIndex, state);
71 }
72
73 void PNGAPI pngComplete(png_structp png, png_infop) {
74 imageDecoder(png)->complete();
75 }
76
77 void PNGAPI pngFailed(png_structp png, png_const_charp) {
78 longjmp(JMPBUF(png), 1);
79 }
80
81 } // namespace
82
83 namespace blink { 56 namespace blink {
84 57
85 class PNGImageReader final {
86 USING_FAST_MALLOC(PNGImageReader);
87 WTF_MAKE_NONCOPYABLE(PNGImageReader);
88
89 public:
90 PNGImageReader(PNGImageDecoder* decoder, size_t readOffset)
91 : m_decoder(decoder),
92 m_readOffset(readOffset),
93 m_currentBufferSize(0),
94 m_decodingSizeOnly(false),
95 m_hasAlpha(false) {
96 m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
97 m_info = png_create_info_struct(m_png);
98 png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable,
99 pngRowAvailable, pngComplete);
100 }
101
102 ~PNGImageReader() {
103 png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0);
104 ASSERT(!m_png && !m_info);
105
106 m_readOffset = 0;
107 }
108
109 bool decode(const SegmentReader& data, bool sizeOnly) {
110 m_decodingSizeOnly = sizeOnly;
111
112 // We need to do the setjmp here. Otherwise bad things will happen.
113 if (setjmp(JMPBUF(m_png)))
114 return m_decoder->setFailed();
115
116 const char* segment;
117 while (size_t segmentLength = data.getSomeData(segment, m_readOffset)) {
118 m_readOffset += segmentLength;
119 m_currentBufferSize = m_readOffset;
120 png_process_data(m_png, m_info,
121 reinterpret_cast<png_bytep>(const_cast<char*>(segment)),
122 segmentLength);
123 if (sizeOnly ? m_decoder->isDecodedSizeAvailable()
124 : m_decoder->frameIsCompleteAtIndex(0))
125 return true;
126 }
127
128 return false;
129 }
130
131 png_structp pngPtr() const { return m_png; }
132 png_infop infoPtr() const { return m_info; }
133
134 size_t getReadOffset() const { return m_readOffset; }
135 void setReadOffset(size_t offset) { m_readOffset = offset; }
136 size_t currentBufferSize() const { return m_currentBufferSize; }
137 bool decodingSizeOnly() const { return m_decodingSizeOnly; }
138 void setHasAlpha(bool hasAlpha) { m_hasAlpha = hasAlpha; }
139 bool hasAlpha() const { return m_hasAlpha; }
140
141 png_bytep interlaceBuffer() const { return m_interlaceBuffer.get(); }
142 void createInterlaceBuffer(int size) {
143 m_interlaceBuffer = wrapArrayUnique(new png_byte[size]);
144 }
145
146 private:
147 png_structp m_png;
148 png_infop m_info;
149 PNGImageDecoder* m_decoder;
150 size_t m_readOffset;
151 size_t m_currentBufferSize;
152 bool m_decodingSizeOnly;
153 bool m_hasAlpha;
154 std::unique_ptr<png_byte[]> m_interlaceBuffer;
155 };
156
157 PNGImageDecoder::PNGImageDecoder(AlphaOption alphaOption, 58 PNGImageDecoder::PNGImageDecoder(AlphaOption alphaOption,
158 ColorSpaceOption colorOptions, 59 ColorSpaceOption colorOptions,
159 size_t maxDecodedBytes, 60 size_t maxDecodedBytes,
160 size_t offset) 61 size_t offset)
161 : ImageDecoder(alphaOption, colorOptions, maxDecodedBytes), 62 : ImageDecoder(alphaOption, colorOptions, maxDecodedBytes),
162 m_offset(offset) {} 63 m_offset(offset),
64 m_frameCount(0),
65 m_currentFrame(0),
66 m_repetitionCount(cAnimationLoopOnce),
67 m_colorSpaceSet(false),
68 m_hasAlphaChannel(false),
69 m_currentBufferSawAlpha(false),
70 m_isParsing(false),
71 m_failedWithCorrectFrames(false) {}
163 72
164 PNGImageDecoder::~PNGImageDecoder() {} 73 PNGImageDecoder::~PNGImageDecoder() {}
165 74
75 bool PNGImageDecoder::setFailed() {
76 // Update the frame count to make sure it reflects the most up to date number
77 // of frames there were parsed. We don't want to set the decoder to the failed
78 // state if the reader was able to successfully parse some frames.
79 if (m_isParsing)
scroggo_chromium 2016/11/29 16:30:52 It seems awkward that the reader calls a method th
joostouwerling 2016/12/02 16:08:42 I considered this, but this implementation is a li
scroggo_chromium 2016/12/02 21:28:49 I'm curious to see what that looks like.
joostouwerling 2016/12/05 15:32:46 As discussed in person, one obstacle for this impl
80 m_frameCount = m_reader->frameCount();
81
82 // There are three cases in which the decoder is invalidated:
83 // 1) No frames are received so far.
84 // 2) The image is not animated.
85 // 3) Decoding for the first frame fails.
86 if (m_frameCount == 0 ||
87 (m_reader->parseCompleted() && m_frameCount == 1) ||
88 (!m_isParsing && m_currentFrame == 0))
89 return ImageDecoder::setFailed();
90
91 // If decoding fails for later frames, we still want to show earlier frames,
92 // but the frame count needs to be adjusted. We do not want to shrink
93 // |m_frameBufferCache|, since clients may store pointers to later frames.
94 if (!m_isParsing) {
95 m_frameBufferCache[m_currentFrame].clearPixelData();
96 m_frameBufferCache[m_currentFrame].setStatus(ImageFrame::FrameEmpty);
97 m_frameCount = m_currentFrame;
98 }
99
100 m_failedWithCorrectFrames = true;
101 return false;
102 }
103
104 size_t PNGImageDecoder::decodeFrameCount() {
105 parse(PNGParseQuery::PNGMetaDataQuery);
106 return m_frameCount;
107 }
108
109 void PNGImageDecoder::decode(size_t index) {
scroggo_chromium 2016/11/29 16:30:52 If a client calls frameBufferAtIndex() without cal
joostouwerling 2016/12/02 16:08:42 Yes, that is done already in ImageDecoder::frameBu
110 if (failed())
111 return;
112
113 updateAggressivePurging(index);
114
115 Vector<size_t> framesToDecode;
116 size_t frameToDecode = index;
117
118 // This method is only called by ImageDecoder::frameBufferAtIndex if the frame
119 // status of frame |index| is not ImageFrame::FrameComplete. Therefore, it is
120 // OK that the do-while loop always appends |index| to |m_framesToDecode|,
121 // without checking for its status.
122 //
123 // The requiredPreviousFrameIndex for each frame is set in
124 // PNGImageDecoder::initializeNewFrame().
125 do {
126 framesToDecode.append(frameToDecode);
127 frameToDecode =
128 m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
129 } while (frameToDecode != kNotFound &&
130 m_frameBufferCache[frameToDecode].getStatus() !=
131 ImageFrame::FrameComplete);
132
133 for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); i++) {
134 m_currentFrame = *i;
135 m_reader->decode(*m_data, *i);
136 if (failed())
137 return;
138
139 // If the frame is not yet complete, we need more data to continue.
140 if (m_frameBufferCache[*i].getStatus() != ImageFrame::FrameComplete)
141 break;
142
143 if (m_purgeAggressively)
144 clearCacheExceptFrame(*i);
145 }
146 }
147
148 // @TODO(joostouwerling) Consolidate this with a proposed change in
149 // ImageDecoder::clearCacheExceptFrame. See
150 // crrev.com/2468233002
151 size_t PNGImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) {
152 // As per the comments at ImageDecoder::clearCacheExceptFrame
153 if (m_frameBufferCache.size() <= 1)
154 return 0;
155
156 // We expect that after this call, we'll be asked to decode frames after
157 // this one. So we want to avoid clearing frames such that those requests
158 // would force re-decoding from the beginning of the image.
159 //
160 // When |clearExceptFrame| is e.g. DisposeKeep, simply not clearing that
161 // frame is sufficient, as the next frame will be based on it, and in
162 // general future frames can't be based on anything previous.
163 //
164 // However, if this frame is DisposeOverwritePrevious, then subsequent
165 // frames will depend on this frame's required previous frame. In this
166 // case, we need to preserve both this frame and that one.
167 size_t clearExceptFrame2 = kNotFound;
168 if (clearExceptFrame < m_frameBufferCache.size()) {
169 const ImageFrame& frame = m_frameBufferCache[clearExceptFrame];
170 if (frame.getStatus() != ImageFrame::FrameEmpty &&
171 frame.getDisposalMethod() == ImageFrame::DisposeOverwritePrevious) {
172 clearExceptFrame2 = clearExceptFrame;
173 clearExceptFrame = frame.requiredPreviousFrameIndex();
174 }
175 }
176
177 // Now |clearExceptFrame| indicates the frame that future frames will
178 // depend on. But if decoding is skipping forward past intermediate frames,
179 // this frame may be FrameEmpty. So we need to keep traversing back through
180 // the required previous frames until we find the nearest non-empty
181 // ancestor. Preserving that will minimize the amount of future decoding
182 // needed.
183 while (clearExceptFrame < m_frameBufferCache.size() &&
184 m_frameBufferCache[clearExceptFrame].getStatus() ==
185 ImageFrame::FrameEmpty)
186 clearExceptFrame =
187 m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
188
189 return clearCacheExceptTwoFrames(clearExceptFrame, clearExceptFrame2);
190 }
191
192 size_t PNGImageDecoder::clearCacheExceptTwoFrames(size_t clearExceptFrame1,
193 size_t clearExceptFrame2) {
194 size_t frameBytesCleared = 0;
195 for (size_t i = 0; i < m_frameBufferCache.size(); ++i) {
196 if (m_frameBufferCache[i].getStatus() != ImageFrame::FrameEmpty &&
197 i != clearExceptFrame1 && i != clearExceptFrame2) {
198 frameBytesCleared += frameBytesAtIndex(i);
199 clearFrameBuffer(i);
200 }
201 }
202 return frameBytesCleared;
203 }
204
205 void PNGImageDecoder::clearFrameBuffer(size_t frameIndex) {
206 if (m_frameBufferCache[frameIndex].getStatus() == ImageFrame::FramePartial)
207 m_reader->clearDecodeState(frameIndex);
208
209 m_frameBufferCache[frameIndex].clearPixelData();
210 }
211
212 void PNGImageDecoder::parse(PNGParseQuery query) {
213 if (failed() || m_failedWithCorrectFrames)
214 return;
215
216 if (!m_reader)
217 m_reader = wrapUnique(new PNGImageReader(this, m_offset));
218
219 m_isParsing = true;
220 if (!m_reader->parse(*m_data, query) && isAllDataReceived())
221 setFailed();
222 else if (query == PNGParseQuery::PNGMetaDataQuery)
scroggo_chromium 2016/11/29 16:30:52 I guess you changed this to an else because we wil
joostouwerling 2016/12/02 16:08:42 Yes.
223 m_frameCount = m_reader->frameCount();
224
225 m_isParsing = false;
226 }
227
228 void PNGImageDecoder::setRepetitionCount(size_t repetitionCount) {
229 m_repetitionCount =
230 (repetitionCount == 0) ? cAnimationLoopInfinite : repetitionCount;
231 }
232
233 // This matches the existing behavior to loop once if decoding fails, but this
234 // should be changed to stick with m_repetitionCount to match other browsers.
235 // See crbug.com/267883
236 int PNGImageDecoder::repetitionCount() const {
237 if (m_reader->parseCompleted() && m_reader->frameCount() == 1)
238 return cAnimationNone;
239 return failed() ? cAnimationLoopOnce : m_repetitionCount;
240 }
241
242 // These are mapped according to:
243 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chu nk
244 static inline ImageFrame::DisposalMethod getDisposalMethod(
245 uint8_t disposalMethod) {
246 switch (disposalMethod) {
247 case 0:
248 return ImageFrame::DisposalMethod::DisposeKeep;
249 case 1:
250 return ImageFrame::DisposalMethod::DisposeOverwriteBgcolor;
251 case 2:
252 return ImageFrame::DisposalMethod::DisposeOverwritePrevious;
253 default:
254 return ImageFrame::DisposalMethod::DisposeNotSpecified;
255 }
256 }
257
258 // These are mapped according to:
259 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chu nk
260 static inline ImageFrame::AlphaBlendSource getAlphaBlend(uint8_t alphaBlend) {
261 if (alphaBlend == 1)
262 return ImageFrame::AlphaBlendSource::BlendAtopPreviousFrame;
263 return ImageFrame::AlphaBlendSource::BlendAtopBgcolor;
264 }
265
266 void PNGImageDecoder::initializeNewFrame(size_t index) {
267 const PNGImageReader::FrameInfo& frameInfo = m_reader->frameInfo(index);
268 ImageFrame* buffer = &m_frameBufferCache[index];
269
270 IntRect frameRectWithinSize =
271 intersection(frameInfo.frameRect, {IntPoint(), size()});
272 buffer->setOriginalFrameRect(frameRectWithinSize);
273 buffer->setDuration(frameInfo.duration);
274 buffer->setDisposalMethod(getDisposalMethod(frameInfo.disposalMethod));
275 buffer->setAlphaBlendSource(getAlphaBlend(frameInfo.alphaBlend));
276 buffer->setRequiredPreviousFrameIndex(
277 findRequiredPreviousFrame(index, false));
278 }
279
280 // Initialize the frame buffer before decoding. The returned boolean indicates
281 // whether initialisation succeeded when it is true, false otherwise.
282 bool PNGImageDecoder::initFrameBuffer(size_t index) {
283 ImageFrame* const buffer = &m_frameBufferCache[index];
284
285 // Return true if the frame is already initialised.
286 if (buffer->getStatus() != ImageFrame::FrameEmpty)
287 return true;
288
289 if (!buffer->setSizeAndColorSpace(size().width(), size().height(),
290 colorSpace()))
291 return false;
292
293 unsigned colorChannels = m_hasAlphaChannel ? 4 : 3;
294 png_structp png = m_reader->pngPtr();
295 if (PNG_INTERLACE_ADAM7 == png_get_interlace_type(png, m_reader->infoPtr())) {
296 m_reader->createInterlaceBuffer(colorChannels * size().width() *
297 size().height());
298 if (!m_reader->interlaceBuffer())
299 return false;
300 }
301
302 buffer->setHasAlpha(true);
303 size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
304
305 // If frame |index| does not depend on any other frame, ensure the frame is
306 // fully transparent black after initialisation.
307 if (requiredPreviousFrameIndex == kNotFound) {
308 buffer->zeroFillPixelData();
309 } else {
310 ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
311 ASSERT(prevBuffer->getStatus() == ImageFrame::FrameComplete);
312
313 // We try to reuse |prevBuffer| as starting state to avoid copying.
314 // For DisposeOverwritePrevious, the next frame will also use
315 // |prevBuffer| as its starting state, so we can't take over its image
316 // data using takeBitmapDataIfWritable. Copy the data instead.
317 if ((buffer->getDisposalMethod() == ImageFrame::DisposeOverwritePrevious ||
318 !buffer->takeBitmapDataIfWritable(prevBuffer)) &&
319 !buffer->copyBitmapData(*prevBuffer))
320 return false;
321
322 // We want to clear the previous frame to transparent, without affecting
323 // pixels in the image outside of the frame.
324 if (prevBuffer->getDisposalMethod() ==
325 ImageFrame::DisposeOverwriteBgcolor) {
326 const IntRect& prevRect = prevBuffer->originalFrameRect();
327 ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
328 buffer->zeroFillFrameRect(prevRect);
329 }
330 }
331
332 buffer->setStatus(ImageFrame::FramePartial);
333 m_currentBufferSawAlpha = false;
334 return true;
335 }
336
166 inline float pngFixedToFloat(png_fixed_point x) { 337 inline float pngFixedToFloat(png_fixed_point x) {
167 return ((float)x) * 0.00001f; 338 return ((float)x) * 0.00001f;
168 } 339 }
169 340
170 inline sk_sp<SkColorSpace> readColorSpace(png_structp png, png_infop info) { 341 inline sk_sp<SkColorSpace> readColorSpace(png_structp png, png_infop info) {
171 if (png_get_valid(png, info, PNG_INFO_sRGB)) { 342 if (png_get_valid(png, info, PNG_INFO_sRGB)) {
172 return SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named); 343 return SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named);
173 } 344 }
174 345
175 png_charp name = nullptr; 346 png_charp name = nullptr;
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
216 387
217 return nullptr; 388 return nullptr;
218 } 389 }
219 390
220 void PNGImageDecoder::headerAvailable() { 391 void PNGImageDecoder::headerAvailable() {
221 png_structp png = m_reader->pngPtr(); 392 png_structp png = m_reader->pngPtr();
222 png_infop info = m_reader->infoPtr(); 393 png_infop info = m_reader->infoPtr();
223 png_uint_32 width = png_get_image_width(png, info); 394 png_uint_32 width = png_get_image_width(png, info);
224 png_uint_32 height = png_get_image_height(png, info); 395 png_uint_32 height = png_get_image_height(png, info);
225 396
226 // Protect against large PNGs. See http://bugzil.la/251381 for more details. 397 // Only set the size of the image once. Since single frames also use this
227 const unsigned long maxPNGSize = 1000000UL; 398 // method, we don't want them to override the size to their frame rect.
228 if (width > maxPNGSize || height > maxPNGSize) { 399 if (!isDecodedSizeAvailable()) {
229 longjmp(JMPBUF(png), 1); 400 // Protect against large PNGs. See http://bugzil.la/251381 for more details.
230 return; 401 const unsigned long maxPNGSize = 1000000UL;
231 } 402 if (width > maxPNGSize || height > maxPNGSize) {
403 longjmp(JMPBUF(png), 1);
404 return;
405 }
232 406
233 // Set the image size now that the image header is available. 407 // Set the image size now that the image header is available.
234 if (!setSize(width, height)) { 408 if (!setSize(width, height)) {
235 longjmp(JMPBUF(png), 1); 409 longjmp(JMPBUF(png), 1);
236 return; 410 return;
411 }
237 } 412 }
238 413
239 int bitDepth, colorType, interlaceType, compressionType, filterType, channels; 414 int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
240 png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, 415 png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType,
241 &interlaceType, &compressionType, &filterType); 416 &interlaceType, &compressionType, &filterType);
242 417
243 // The options we set here match what Mozilla does. 418 // The options we set here match what Mozilla does.
244 419
245 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA. 420 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
246 if (colorType == PNG_COLOR_TYPE_PALETTE || 421 if (colorType == PNG_COLOR_TYPE_PALETTE ||
247 (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8)) 422 (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
248 png_set_expand(png); 423 png_set_expand(png);
249 424
250 png_bytep trns = 0; 425 png_bytep trns = 0;
251 int trnsCount = 0; 426 int trnsCount = 0;
252 if (png_get_valid(png, info, PNG_INFO_tRNS)) { 427 if (png_get_valid(png, info, PNG_INFO_tRNS)) {
253 png_get_tRNS(png, info, &trns, &trnsCount, 0); 428 png_get_tRNS(png, info, &trns, &trnsCount, 0);
254 png_set_expand(png); 429 png_set_expand(png);
255 } 430 }
256 431
257 if (bitDepth == 16) 432 if (bitDepth == 16)
258 png_set_strip_16(png); 433 png_set_strip_16(png);
259 434
260 if (colorType == PNG_COLOR_TYPE_GRAY || 435 if (colorType == PNG_COLOR_TYPE_GRAY ||
261 colorType == PNG_COLOR_TYPE_GRAY_ALPHA) 436 colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
262 png_set_gray_to_rgb(png); 437 png_set_gray_to_rgb(png);
263 438
264 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace) { 439 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace &&
440 !m_colorSpaceSet) {
265 // We only support color profiles for color PALETTE and RGB[A] PNG. 441 // We only support color profiles for color PALETTE and RGB[A] PNG.
266 // Supporting color profiles for gray-scale images is slightly tricky, at 442 // Supporting color profiles for gray-scale images is slightly tricky, at
267 // least using the CoreGraphics ICC library, because we expand gray-scale 443 // least using the CoreGraphics ICC library, because we expand gray-scale
268 // images to RGB but we do not similarly transform the color profile. We'd 444 // images to RGB but we do not similarly transform the color profile. We'd
269 // either need to transform the color profile or we'd need to decode into a 445 // either need to transform the color profile or we'd need to decode into a
270 // gray-scale image buffer and hand that to CoreGraphics. 446 // gray-scale image buffer and hand that to CoreGraphics.
271 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info); 447 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info);
272 if (colorSpace) { 448 if (colorSpace) {
273 setColorSpaceAndComputeTransform(colorSpace); 449 setColorSpaceAndComputeTransform(colorSpace);
274 } 450 }
451
452 // For animated PNGs, we only need to set the color space once, since frames
453 // don't have their own color space. Set |m_colorSpaceSet| to true.
454 m_colorSpaceSet = true;
275 } 455 }
276 456
277 if (!hasEmbeddedColorSpace()) { 457 if (!hasEmbeddedColorSpace()) {
278 // TODO (msarett): 458 // TODO (msarett):
279 // Applying the transfer function (gamma) should be handled by 459 // Applying the transfer function (gamma) should be handled by
280 // SkColorSpaceXform. Here we always convert to a transfer function that 460 // SkColorSpaceXform. Here we always convert to a transfer function that
281 // is a 2.2 exponential. This is a little strange given that the dst 461 // is a 2.2 exponential. This is a little strange given that the dst
282 // transfer function is not necessarily a 2.2 exponential. 462 // transfer function is not necessarily a 2.2 exponential.
283 // TODO (msarett): 463 // TODO (msarett):
284 // Often, PNGs that specify their transfer function with the gAMA tag will 464 // Often, PNGs that specify their transfer function with the gAMA tag will
(...skipping 16 matching lines...) Expand all
301 481
302 // Tell libpng to send us rows for interlaced pngs. 482 // Tell libpng to send us rows for interlaced pngs.
303 if (interlaceType == PNG_INTERLACE_ADAM7) 483 if (interlaceType == PNG_INTERLACE_ADAM7)
304 png_set_interlace_handling(png); 484 png_set_interlace_handling(png);
305 485
306 // Update our info now. 486 // Update our info now.
307 png_read_update_info(png, info); 487 png_read_update_info(png, info);
308 channels = png_get_channels(png, info); 488 channels = png_get_channels(png, info);
309 ASSERT(channels == 3 || channels == 4); 489 ASSERT(channels == 3 || channels == 4);
310 490
311 m_reader->setHasAlpha(channels == 4); 491 m_hasAlphaChannel = (channels == 4);
312
313 if (m_reader->decodingSizeOnly()) {
314 // If we only needed the size, halt the reader.
315 #if PNG_LIBPNG_VER_MAJOR > 1 || \
316 (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5)
317 // Passing '0' tells png_process_data_pause() not to cache unprocessed data.
318 m_reader->setReadOffset(m_reader->currentBufferSize() -
319 png_process_data_pause(png, 0));
320 #else
321 m_reader->setReadOffset(m_reader->currentBufferSize() - png->buffer_size);
322 png->buffer_size = 0;
323 #endif
324 }
325 } 492 }
326 493
327 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, 494 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer,
328 unsigned rowIndex, 495 unsigned rowIndex,
329 int) { 496 int) {
330 if (m_frameBufferCache.isEmpty()) 497 if (m_frameBufferCache.isEmpty())
331 return; 498 return;
332 499
333 // Initialize the framebuffer if needed. 500 if (!initFrameBuffer(m_currentFrame)) {
334 ImageFrame& buffer = m_frameBufferCache[0]; 501 setFailed();
335 if (buffer.getStatus() == ImageFrame::FrameEmpty) { 502 return;
336 png_structp png = m_reader->pngPtr();
337 if (!buffer.setSizeAndColorSpace(size().width(), size().height(),
338 colorSpace())) {
339 longjmp(JMPBUF(png), 1);
340 return;
341 }
342
343 unsigned colorChannels = m_reader->hasAlpha() ? 4 : 3;
344 if (PNG_INTERLACE_ADAM7 ==
345 png_get_interlace_type(png, m_reader->infoPtr())) {
346 m_reader->createInterlaceBuffer(colorChannels * size().width() *
347 size().height());
348 if (!m_reader->interlaceBuffer()) {
349 longjmp(JMPBUF(png), 1);
350 return;
351 }
352 }
353
354 buffer.setStatus(ImageFrame::FramePartial);
355 buffer.setHasAlpha(false);
356
357 // For PNGs, the frame always fills the entire image.
358 buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
359 } 503 }
360 504
505 // This frameRect is already clipped, so that it fits within the size of the
506 // image. This is done in initializeNewFrame() after a frameCount() call.
507 ImageFrame& buffer = m_frameBufferCache[m_currentFrame];
508 const IntRect& frameRect = buffer.originalFrameRect();
509
361 /* libpng comments (here to explain what follows). 510 /* libpng comments (here to explain what follows).
362 * 511 *
363 * this function is called for every row in the image. If the 512 * this function is called for every row in the image. If the
364 * image is interlacing, and you turned on the interlace handler, 513 * image is interlacing, and you turned on the interlace handler,
365 * this function will be called for every row in every pass. 514 * this function will be called for every row in every pass.
366 * Some of these rows will not be changed from the previous pass. 515 * Some of these rows will not be changed from the previous pass.
367 * When the row is not changed, the new_row variable will be NULL. 516 * When the row is not changed, the new_row variable will be NULL.
368 * The rows and passes are called in order, so you don't really 517 * The rows and passes are called in order, so you don't really
369 * need the row_num and pass, but I'm supplying them because it 518 * need the row_num and pass, but I'm supplying them because it
370 * may make your life easier. 519 * may make your life easier.
371 */ 520 */
372 521
373 // Nothing to do if the row is unchanged, or the row is outside 522 // Nothing to do if the row is unchanged, or the row is outside
374 // the image bounds: libpng may send extra rows, ignore them to 523 // the image bounds: libpng may send extra rows, ignore them to
375 // make our lives easier. 524 // make our lives easier.
376 if (!rowBuffer) 525 if (!rowBuffer)
377 return; 526 return;
378 int y = rowIndex; 527 int y = rowIndex + frameRect.y();
379 if (y < 0 || y >= size().height()) 528 ASSERT(y >= 0);
529 if (y >= size().height())
380 return; 530 return;
381 531
382 /* libpng comments (continued). 532 /* libpng comments (continued).
383 * 533 *
384 * For the non-NULL rows of interlaced images, you must call 534 * For the non-NULL rows of interlaced images, you must call
385 * png_progressive_combine_row() passing in the row and the 535 * png_progressive_combine_row() passing in the row and the
386 * old row. You can call this function for NULL rows (it will 536 * old row. You can call this function for NULL rows (it will
387 * just return) and for non-interlaced images (it just does the 537 * just return) and for non-interlaced images (it just does the
388 * memcpy for you) if it will make the code easier. Thus, you 538 * memcpy for you) if it will make the code easier. Thus, you
389 * can just do this for all cases: 539 * can just do this for all cases:
390 * 540 *
391 * png_progressive_combine_row(png_ptr, old_row, new_row); 541 * png_progressive_combine_row(png_ptr, old_row, new_row);
392 * 542 *
393 * where old_row is what was displayed for previous rows. Note 543 * where old_row is what was displayed for previous rows. Note
394 * that the first pass (pass == 0 really) will completely cover 544 * that the first pass (pass == 0 really) will completely cover
395 * the old row, so the rows do not have to be initialized. After 545 * the old row, so the rows do not have to be initialized. After
396 * the first pass (and only for interlaced images), you will have 546 * the first pass (and only for interlaced images), you will have
397 * to pass the current row, and the function will combine the 547 * to pass the current row, and the function will combine the
398 * old row and the new row. 548 * old row and the new row.
399 */ 549 */
400 550
401 bool hasAlpha = m_reader->hasAlpha(); 551 bool hasAlpha = m_hasAlphaChannel;
402 png_bytep row = rowBuffer; 552 png_bytep row = rowBuffer;
403 553
404 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) { 554 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
405 unsigned colorChannels = hasAlpha ? 4 : 3; 555 unsigned colorChannels = hasAlpha ? 4 : 3;
406 row = interlaceBuffer + (rowIndex * colorChannels * size().width()); 556 row = interlaceBuffer + (rowIndex * colorChannels * size().width());
407 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer); 557 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
408 } 558 }
409 559
410 // Write the decoded row pixels to the frame buffer. The repetitive 560 // Write the decoded row pixels to the frame buffer. The repetitive
411 // form of the row write loops is for speed. 561 // form of the row write loops is for speed.
412 ImageFrame::PixelData* const dstRow = buffer.getAddr(0, y); 562 ImageFrame::PixelData* const dstRow = buffer.getAddr(frameRect.x(), y);
413 unsigned alphaMask = 255; 563 unsigned alphaMask = 255;
414 int width = size().width(); 564 int width = frameRect.width();
415 565
416 png_bytep srcPtr = row; 566 png_bytep srcPtr = row;
417 if (hasAlpha) { 567 if (hasAlpha) {
418 // Here we apply the color space transformation to the dst space. 568 // Here we apply the color space transformation to the dst space.
419 // It does not really make sense to transform to a gamma-encoded 569 // It does not really make sense to transform to a gamma-encoded
420 // space and then immediately after, perform a linear premultiply. 570 // space and then immediately after, perform a linear premultiply.
421 // Ideally we would pass kPremul_SkAlphaType to xform->apply(), 571 // Ideally we would pass kPremul_SkAlphaType to xform->apply(),
422 // instructing SkColorSpaceXform to perform the linear premultiply 572 // instructing SkColorSpaceXform to perform the linear premultiply
423 // while the pixels are a linear space. 573 // while the pixels are a linear space.
424 // We cannot do this because when we apply the gamma encoding after 574 // We cannot do this because when we apply the gamma encoding after
425 // the premultiply, we will very likely end up with valid pixels 575 // the premultiply, we will very likely end up with valid pixels
426 // where R, G, and/or B are greater than A. The legacy drawing 576 // where R, G, and/or B are greater than A. The legacy drawing
427 // pipeline does not know how to handle this. 577 // pipeline does not know how to handle this.
428 if (SkColorSpaceXform* xform = colorTransform()) { 578 if (SkColorSpaceXform* xform = colorTransform()) {
429 SkColorSpaceXform::ColorFormat colorFormat = 579 SkColorSpaceXform::ColorFormat colorFormat =
430 SkColorSpaceXform::kRGBA_8888_ColorFormat; 580 SkColorSpaceXform::kRGBA_8888_ColorFormat;
431 xform->apply(colorFormat, dstRow, colorFormat, srcPtr, size().width(), 581 xform->apply(colorFormat, dstRow, colorFormat, srcPtr, size().width(),
432 kUnpremul_SkAlphaType); 582 kUnpremul_SkAlphaType);
433 srcPtr = (png_bytep)dstRow; 583 srcPtr = (png_bytep)dstRow;
434 } 584 }
435 585
436 if (buffer.premultiplyAlpha()) { 586 if (m_frameBufferCache[m_currentFrame].getAlphaBlendSource() ==
437 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 587 ImageFrame::BlendAtopBgcolor) {
438 dstPixel++, srcPtr += 4) { 588 if (buffer.premultiplyAlpha()) {
439 buffer.setRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 589 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
440 srcPtr[3]); 590 dstPixel++, srcPtr += 4) {
441 alphaMask &= srcPtr[3]; 591 buffer.setRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2],
592 srcPtr[3]);
593 alphaMask &= srcPtr[3];
594 }
595 } else {
596 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
597 dstPixel++, srcPtr += 4) {
598 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[3] );
599 alphaMask &= srcPtr[3];
600 }
442 } 601 }
443 } else { 602 } else {
444 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 603 if (buffer.premultiplyAlpha()) {
445 dstPixel++, srcPtr += 4) { 604 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
446 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[3]); 605 dstPixel++, srcPtr += 4) {
447 alphaMask &= srcPtr[3]; 606 buffer.blendRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2],
607 srcPtr[3]);
608 alphaMask &= srcPtr[3];
609 }
610 } else {
611 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
612 dstPixel++, srcPtr += 4) {
613 buffer.blendRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[ 3]);
614 alphaMask &= srcPtr[3];
615 }
448 } 616 }
449 } 617 }
618
619 if (alphaMask != 255 && !m_currentBufferSawAlpha)
620 m_currentBufferSawAlpha = true;
621
450 } else { 622 } else {
451 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 623 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
452 dstPixel++, srcPtr += 3) { 624 dstPixel++, srcPtr += 3) {
453 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 255); 625 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 255);
454 } 626 }
455 627
456 // We'll apply the color space xform to opaque pixels after they have been 628 // We'll apply the color space xform to opaque pixels after they have been
457 // written to the ImageFrame, purely because SkColorSpaceXform supports 629 // written to the ImageFrame, purely because SkColorSpaceXform supports
458 // RGBA (and not RGB). 630 // RGBA (and not RGB).
459 if (SkColorSpaceXform* xform = colorTransform()) { 631 if (SkColorSpaceXform* xform = colorTransform()) {
460 xform->apply(xformColorFormat(), dstRow, xformColorFormat(), dstRow, 632 xform->apply(xformColorFormat(), dstRow, xformColorFormat(), dstRow,
461 size().width(), kOpaque_SkAlphaType); 633 size().width(), kOpaque_SkAlphaType);
462 } 634 }
463 } 635 }
464 636
465 if (alphaMask != 255 && !buffer.hasAlpha()) 637 buffer.setPixelsChanged(true);
466 buffer.setHasAlpha(true); 638 }
467 639
468 buffer.setPixelsChanged(true); 640 bool PNGImageDecoder::frameIsCompleteAtIndex(size_t index) const {
641 if (failed())
642 return false;
643 if (index == 0)
644 return ImageDecoder::frameIsCompleteAtIndex(index);
645
646 // For non-first frames, the frame is considered complete if all frame data
647 // has been received. Non-first frames are reported by |m_reader| once it has
648 // parsed all data for that frame, so we can simply return if the index is
649 // below the reported frame count.
scroggo_chromium 2016/11/29 16:30:52 Maybe add a comment explaining why we cannot use m
joostouwerling 2016/12/02 16:08:42 Done.
650 return (index < m_frameCount);
651 }
652
653 float PNGImageDecoder::frameDurationAtIndex(size_t index) const {
654 return (index < m_frameCount
655 ? m_frameBufferCache[index].duration()
656 : 0);
469 } 657 }
470 658
471 void PNGImageDecoder::complete() { 659 void PNGImageDecoder::complete() {
472 if (m_frameBufferCache.isEmpty()) 660 if (m_frameBufferCache.isEmpty())
473 return; 661 return;
474 662
475 m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete); 663 // @TODO(joostouwerling) if necessary, do a check if all expected data has
476 } 664 // been received. This is because the IEND chunk is sent
665 // artificially. The necessity of this check depends on
666 // how libpng handles in- and overcomplete frame data.
477 667
478 inline bool isComplete(const PNGImageDecoder* decoder) { 668 if (m_reader->interlaceBuffer())
479 return decoder->frameIsCompleteAtIndex(0); 669 m_reader->clearInterlaceBuffer();
480 } 670
671 ImageFrame& buffer = m_frameBufferCache[m_currentFrame];
672 buffer.setStatus(ImageFrame::FrameComplete);
673
674 if (!m_currentBufferSawAlpha) {
675 // The whole frame was non-transparent, so it's possible that the entire
676 // resulting buffer was non-transparent, and we can setHasAlpha(false).
677 if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
678 buffer.setHasAlpha(false);
679 buffer.setRequiredPreviousFrameIndex(kNotFound);
680 } else if (buffer.requiredPreviousFrameIndex() != kNotFound) {
681 // Tricky case. This frame does not have alpha only if everywhere
682 // outside its rect doesn't have alpha. To know whether this is
683 // true, we check the start state of the frame -- if it doesn't have
684 // alpha, we're safe.
685 const ImageFrame* prevBuffer =
686 &m_frameBufferCache[buffer.requiredPreviousFrameIndex()];
687 ASSERT(prevBuffer->getDisposalMethod() !=
688 ImageFrame::DisposeOverwritePrevious);
481 689
482 void PNGImageDecoder::decode(bool onlySize) { 690 // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
483 if (failed()) 691 // we can say we have no alpha if that frame had no alpha. But
484 return; 692 // since in initFrameBuffer() we already copied that frame's alpha
693 // state into the current frame's, we need do nothing at all here.
694 //
695 // The only remaining case is a DisposeOverwriteBgcolor frame. If
696 // it had no alpha, and its rect is contained in the current frame's
697 // rect, we know the current frame has no alpha.
698 if ((prevBuffer->getDisposalMethod() ==
699 ImageFrame::DisposeOverwriteBgcolor) &&
700 !prevBuffer->hasAlpha() &&
701 buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
702 buffer.setHasAlpha(false);
703 }
704 }
485 705
486 if (!m_reader)
487 m_reader = wrapUnique(new PNGImageReader(this, m_offset));
488
489 // If we couldn't decode the image but have received all the data, decoding
490 // has failed.
491 if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
492 setFailed();
493
494 // If decoding is done or failed, we don't need the PNGImageReader anymore.
495 if (isComplete(this) || failed())
496 m_reader.reset();
497 } 706 }
498 707
499 } // namespace blink 708 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698