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

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

Issue 2386453003: WIP: Implement APNG (Closed)
Patch Set: Fix feedback on patch set 14 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) {}
163 68
164 PNGImageDecoder::~PNGImageDecoder() {} 69 PNGImageDecoder::~PNGImageDecoder() {}
165 70
71 size_t PNGImageDecoder::decodeFrameCount() {
72 parse(PNGParseQuery::PNGMetaDataQuery);
73 return m_frameCount;
74 }
75
76 void PNGImageDecoder::decode(size_t index) {
77 parse(PNGParseQuery::PNGMetaDataQuery);
78
79 // @TODO(joostouwerling): show complete frames even if a later frame fails.
80 if (failed())
81 return;
82
83 updateAggressivePurging(index);
84
85 Vector<size_t> framesToDecode;
86 size_t frameToDecode = index;
87
88 // This method is only called by ImageDecoder::frameBufferAtIndex if the frame
89 // status of frame |index| is not ImageFrame::FrameComplete. Therefore, it is
90 // OK that the do-while loop always appends |index| to |m_framesToDecode|,
91 // without checking for its status.
92 //
93 // The requiredPreviousFrameIndex for each frame is set in
94 // PNGImageDecoder::initializeNewFrame().
95 do {
96 framesToDecode.append(frameToDecode);
97 frameToDecode =
98 m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
99 } while (frameToDecode != kNotFound &&
100 m_frameBufferCache[frameToDecode].getStatus() !=
101 ImageFrame::FrameComplete);
102
103 for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); i++) {
104 m_currentFrame = *i;
105 m_reader->decode(*m_data, *i);
106 if (failed())
107 return;
108
109 // If the frame is not yet complete, we need more data to continue.
110 if (m_frameBufferCache[*i].getStatus() != ImageFrame::FrameComplete)
111 break;
112
113 if (m_purgeAggressively)
114 clearCacheExceptFrame(*i);
115 }
116 }
117
118 // @TODO(joostouwerling) Consolidate this with a proposed change in
119 // ImageDecoder::clearCacheExceptFrame. See
120 // crrev.com/2468233002
121 size_t PNGImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) {
122 // As per the comments at ImageDecoder::clearCacheExceptFrame
123 if (m_frameBufferCache.size() <= 1)
124 return 0;
125
126 // We expect that after this call, we'll be asked to decode frames after
127 // this one. So we want to avoid clearing frames such that those requests
128 // would force re-decoding from the beginning of the image.
129 //
130 // When |clearExceptFrame| is e.g. DisposeKeep, simply not clearing that
131 // frame is sufficient, as the next frame will be based on it, and in
132 // general future frames can't be based on anything previous.
133 //
134 // However, if this frame is DisposeOverwritePrevious, then subsequent
135 // frames will depend on this frame's required previous frame. In this
136 // case, we need to preserve both this frame and that one.
137 size_t clearExceptFrame2 = kNotFound;
138 if (clearExceptFrame < m_frameBufferCache.size()) {
139 const ImageFrame& frame = m_frameBufferCache[clearExceptFrame];
140 if (frame.getStatus() != ImageFrame::FrameEmpty &&
141 frame.getDisposalMethod() == ImageFrame::DisposeOverwritePrevious) {
142 clearExceptFrame2 = clearExceptFrame;
143 clearExceptFrame = frame.requiredPreviousFrameIndex();
144 }
145 }
146
147 // Now |clearExceptFrame| indicates the frame that future frames will
148 // depend on. But if decoding is skipping forward past intermediate frames,
149 // this frame may be FrameEmpty. So we need to keep traversing back through
150 // the required previous frames until we find the nearest non-empty
151 // ancestor. Preserving that will minimize the amount of future decoding
152 // needed.
153 while (clearExceptFrame < m_frameBufferCache.size() &&
154 m_frameBufferCache[clearExceptFrame].getStatus() ==
155 ImageFrame::FrameEmpty)
156 clearExceptFrame =
157 m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
158
159 return clearCacheExceptTwoFrames(clearExceptFrame, clearExceptFrame2);
160 }
161
162 size_t PNGImageDecoder::clearCacheExceptTwoFrames(size_t clearExceptFrame1,
163 size_t clearExceptFrame2) {
164 size_t frameBytesCleared = 0;
165 for (size_t i = 0; i < m_frameBufferCache.size(); ++i) {
166 if (m_frameBufferCache[i].getStatus() != ImageFrame::FrameEmpty &&
167 i != clearExceptFrame1 && i != clearExceptFrame2) {
168 frameBytesCleared += frameBytesAtIndex(i);
169 clearFrameBuffer(i);
170 }
171 }
172 return frameBytesCleared;
173 }
174
175 void PNGImageDecoder::clearFrameBuffer(size_t frameIndex) {
176 if (m_frameBufferCache[frameIndex].getStatus() == ImageFrame::FramePartial)
177 m_reader->clearDecodeState(frameIndex);
178
179 m_frameBufferCache[frameIndex].clearPixelData();
180 }
181
182 void PNGImageDecoder::parse(PNGParseQuery query) {
183 if (failed())
184 return;
185
186 if (!m_reader)
187 m_reader = wrapUnique(new PNGImageReader(this, m_offset));
188
189 if (!m_reader->parse(*m_data, query) && isAllDataReceived())
190 setFailed();
191
192 if (query == PNGParseQuery::PNGMetaDataQuery)
193 m_frameCount = m_reader->frameCount();
194 }
195
196 void PNGImageDecoder::setRepetitionCount(size_t repetitionCount) {
197 m_repetitionCount =
198 (repetitionCount == 0) ? cAnimationLoopInfinite : repetitionCount;
199 }
200
201 // This matches the existing behavior to loop once if decoding fails, but this
202 // should be changed to stick with m_repetitionCount to match other browsers.
203 // See crbug.com/267883
204 int PNGImageDecoder::repetitionCount() const {
205 if (m_reader->parseCompleted() && m_reader->frameCount() == 1)
206 return cAnimationNone;
207 return failed() ? cAnimationLoopOnce : m_repetitionCount;
208 }
209
210 // These are mapped according to:
211 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chu nk
212 static inline ImageFrame::DisposalMethod getDisposalMethod(
213 uint8_t disposalMethod) {
214 switch (disposalMethod) {
215 case 0:
216 return ImageFrame::DisposalMethod::DisposeKeep;
217 case 1:
218 return ImageFrame::DisposalMethod::DisposeOverwriteBgcolor;
219 case 2:
220 return ImageFrame::DisposalMethod::DisposeOverwritePrevious;
221 default:
222 return ImageFrame::DisposalMethod::DisposeNotSpecified;
223 }
224 }
225
226 // These are mapped according to:
227 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chu nk
228 static inline ImageFrame::AlphaBlendSource getAlphaBlend(uint8_t alphaBlend) {
229 if (alphaBlend == 1)
230 return ImageFrame::AlphaBlendSource::BlendAtopPreviousFrame;
231 return ImageFrame::AlphaBlendSource::BlendAtopBgcolor;
232 }
233
234 void PNGImageDecoder::initializeNewFrame(size_t index) {
235 const PNGImageReader::FrameInfo& frameInfo = m_reader->frameInfo(index);
236 ImageFrame* buffer = &m_frameBufferCache[index];
237
238 IntRect frameRectWithinSize =
239 intersection(frameInfo.frameRect, {IntPoint(), size()});
240 buffer->setOriginalFrameRect(frameRectWithinSize);
241 buffer->setDuration(frameInfo.duration);
242 buffer->setDisposalMethod(getDisposalMethod(frameInfo.disposalMethod));
243 buffer->setAlphaBlendSource(getAlphaBlend(frameInfo.alphaBlend));
244 buffer->setRequiredPreviousFrameIndex(
245 findRequiredPreviousFrame(index, false));
246 }
247
248 // Initialize the frame buffer before decoding. The returned boolean indicates
249 // whether initialisation succeeded when it is true, false otherwise.
250 bool PNGImageDecoder::initFrameBuffer(size_t index) {
251 ImageFrame* const buffer = &m_frameBufferCache[index];
252
253 // Return true if the frame is already initialised.
254 if (buffer->getStatus() != ImageFrame::FrameEmpty)
255 return true;
256
257 if (!buffer->setSizeAndColorSpace(size().width(), size().height(),
258 colorSpace()))
259 return false;
260
261 unsigned colorChannels = m_reader->hasAlpha() ? 4 : 3;
262 png_structp png = m_reader->pngPtr();
263 if (PNG_INTERLACE_ADAM7 == png_get_interlace_type(png, m_reader->infoPtr())) {
264 m_reader->createInterlaceBuffer(colorChannels * size().width() *
265 size().height());
266 if (!m_reader->interlaceBuffer())
267 return false;
268 }
269
270 buffer->setHasAlpha(false);
271 size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
272
273 // If frame |index| does not depend on any other frame, ensure the frame is
274 // fully transparent black after initialisation.
275 if (requiredPreviousFrameIndex == kNotFound) {
276 buffer->zeroFillPixelData();
277 } else {
278 ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
279 ASSERT(prevBuffer->getStatus() == ImageFrame::FrameComplete);
280
281 // We try to reuse |prevBuffer| as starting state to avoid copying.
282 // For DisposeOverwritePrevious, the next frame will also use
283 // |prevBuffer| as its starting state, so we can't take over its image
284 // data using takeBitmapDataIfWritable. Copy the data instead.
285 if ((buffer->getDisposalMethod() == ImageFrame::DisposeOverwritePrevious ||
286 !buffer->takeBitmapDataIfWritable(prevBuffer)) &&
287 !buffer->copyBitmapData(*prevBuffer))
288 return false;
289
290 // We want to clear the previous frame to transparent, without affecting
291 // pixels in the image outside of the frame.
292 if (prevBuffer->getDisposalMethod() ==
293 ImageFrame::DisposeOverwriteBgcolor) {
294 const IntRect& prevRect = prevBuffer->originalFrameRect();
295 ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
296 buffer->zeroFillFrameRect(prevRect);
297 }
298 }
299
300 buffer->setStatus(ImageFrame::FramePartial);
301 return true;
302 }
303
166 inline float pngFixedToFloat(png_fixed_point x) { 304 inline float pngFixedToFloat(png_fixed_point x) {
167 return ((float)x) * 0.00001f; 305 return ((float)x) * 0.00001f;
168 } 306 }
169 307
170 inline sk_sp<SkColorSpace> readColorSpace(png_structp png, png_infop info) { 308 inline sk_sp<SkColorSpace> readColorSpace(png_structp png, png_infop info) {
171 if (png_get_valid(png, info, PNG_INFO_sRGB)) { 309 if (png_get_valid(png, info, PNG_INFO_sRGB)) {
172 return SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named); 310 return SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named);
173 } 311 }
174 312
175 png_charp name = nullptr; 313 png_charp name = nullptr;
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
216 354
217 return nullptr; 355 return nullptr;
218 } 356 }
219 357
220 void PNGImageDecoder::headerAvailable() { 358 void PNGImageDecoder::headerAvailable() {
221 png_structp png = m_reader->pngPtr(); 359 png_structp png = m_reader->pngPtr();
222 png_infop info = m_reader->infoPtr(); 360 png_infop info = m_reader->infoPtr();
223 png_uint_32 width = png_get_image_width(png, info); 361 png_uint_32 width = png_get_image_width(png, info);
224 png_uint_32 height = png_get_image_height(png, info); 362 png_uint_32 height = png_get_image_height(png, info);
225 363
226 // Protect against large PNGs. See http://bugzil.la/251381 for more details. 364 // Only set the size of the image once. Since single frames also use this
227 const unsigned long maxPNGSize = 1000000UL; 365 // method, we don't want them to override the size to their frame rect.
228 if (width > maxPNGSize || height > maxPNGSize) { 366 if (!isDecodedSizeAvailable()) {
229 longjmp(JMPBUF(png), 1); 367 // Protect against large PNGs. See http://bugzil.la/251381 for more details.
230 return; 368 const unsigned long maxPNGSize = 1000000UL;
231 } 369 if (width > maxPNGSize || height > maxPNGSize) {
370 longjmp(JMPBUF(png), 1);
371 return;
372 }
232 373
233 // Set the image size now that the image header is available. 374 // Set the image size now that the image header is available.
234 if (!setSize(width, height)) { 375 if (!setSize(width, height)) {
235 longjmp(JMPBUF(png), 1); 376 longjmp(JMPBUF(png), 1);
236 return; 377 return;
378 }
237 } 379 }
238 380
239 int bitDepth, colorType, interlaceType, compressionType, filterType, channels; 381 int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
240 png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, 382 png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType,
241 &interlaceType, &compressionType, &filterType); 383 &interlaceType, &compressionType, &filterType);
242 384
243 // The options we set here match what Mozilla does. 385 // The options we set here match what Mozilla does.
244 386
245 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA. 387 // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
246 if (colorType == PNG_COLOR_TYPE_PALETTE || 388 if (colorType == PNG_COLOR_TYPE_PALETTE ||
247 (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8)) 389 (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
248 png_set_expand(png); 390 png_set_expand(png);
249 391
250 png_bytep trns = 0; 392 png_bytep trns = 0;
251 int trnsCount = 0; 393 int trnsCount = 0;
252 if (png_get_valid(png, info, PNG_INFO_tRNS)) { 394 if (png_get_valid(png, info, PNG_INFO_tRNS)) {
253 png_get_tRNS(png, info, &trns, &trnsCount, 0); 395 png_get_tRNS(png, info, &trns, &trnsCount, 0);
254 png_set_expand(png); 396 png_set_expand(png);
255 } 397 }
256 398
257 if (bitDepth == 16) 399 if (bitDepth == 16)
258 png_set_strip_16(png); 400 png_set_strip_16(png);
259 401
260 if (colorType == PNG_COLOR_TYPE_GRAY || 402 if (colorType == PNG_COLOR_TYPE_GRAY ||
261 colorType == PNG_COLOR_TYPE_GRAY_ALPHA) 403 colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
262 png_set_gray_to_rgb(png); 404 png_set_gray_to_rgb(png);
263 405
264 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace) { 406 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace &&
407 !m_colorSpaceSet) {
scroggo_chromium 2016/11/29 16:30:51 It's too bad we had to introduce a new variable fo
joostouwerling 2016/12/02 16:08:41 I think that it works fine when some blocks are mo
scroggo_chromium 2016/12/02 21:28:49 Exactly what I was thinking :)
265 // We only support color profiles for color PALETTE and RGB[A] PNG. 408 // We only support color profiles for color PALETTE and RGB[A] PNG.
266 // Supporting color profiles for gray-scale images is slightly tricky, at 409 // Supporting color profiles for gray-scale images is slightly tricky, at
267 // least using the CoreGraphics ICC library, because we expand gray-scale 410 // 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 411 // 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 412 // 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. 413 // gray-scale image buffer and hand that to CoreGraphics.
271 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info); 414 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info);
272 if (colorSpace) { 415 if (colorSpace) {
273 setColorSpaceAndComputeTransform(colorSpace); 416 setColorSpaceAndComputeTransform(colorSpace);
274 } 417 }
418
419 // For animated PNGs, we only need to set the color space once, since frames
420 // don't have their own color space. Set |m_colorSpaceSet| to true.
421 m_colorSpaceSet = true;
275 } 422 }
276 423
277 if (!hasEmbeddedColorSpace()) { 424 if (!hasEmbeddedColorSpace()) {
278 // TODO (msarett): 425 // TODO (msarett):
279 // Applying the transfer function (gamma) should be handled by 426 // Applying the transfer function (gamma) should be handled by
280 // SkColorSpaceXform. Here we always convert to a transfer function that 427 // 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 428 // is a 2.2 exponential. This is a little strange given that the dst
282 // transfer function is not necessarily a 2.2 exponential. 429 // transfer function is not necessarily a 2.2 exponential.
283 // TODO (msarett): 430 // TODO (msarett):
284 // Often, PNGs that specify their transfer function with the gAMA tag will 431 // Often, PNGs that specify their transfer function with the gAMA tag will
(...skipping 17 matching lines...) Expand all
302 // Tell libpng to send us rows for interlaced pngs. 449 // Tell libpng to send us rows for interlaced pngs.
303 if (interlaceType == PNG_INTERLACE_ADAM7) 450 if (interlaceType == PNG_INTERLACE_ADAM7)
304 png_set_interlace_handling(png); 451 png_set_interlace_handling(png);
305 452
306 // Update our info now. 453 // Update our info now.
307 png_read_update_info(png, info); 454 png_read_update_info(png, info);
308 channels = png_get_channels(png, info); 455 channels = png_get_channels(png, info);
309 ASSERT(channels == 3 || channels == 4); 456 ASSERT(channels == 3 || channels == 4);
310 457
311 m_reader->setHasAlpha(channels == 4); 458 m_reader->setHasAlpha(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 } 459 }
326 460
327 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, 461 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer,
328 unsigned rowIndex, 462 unsigned rowIndex,
329 int) { 463 int) {
330 if (m_frameBufferCache.isEmpty()) 464 if (m_frameBufferCache.isEmpty())
331 return; 465 return;
332 466
333 // Initialize the framebuffer if needed. 467 if (!initFrameBuffer(m_currentFrame)) {
334 ImageFrame& buffer = m_frameBufferCache[0]; 468 setFailed();
335 if (buffer.getStatus() == ImageFrame::FrameEmpty) { 469 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 } 470 }
360 471
472 // This frameRect is already clipped, so that it fits within the size of the
473 // image. This is done in initializeNewFrame() after a frameCount() call.
474 ImageFrame& buffer = m_frameBufferCache[m_currentFrame];
475 const IntRect& frameRect = buffer.originalFrameRect();
476
361 /* libpng comments (here to explain what follows). 477 /* libpng comments (here to explain what follows).
362 * 478 *
363 * this function is called for every row in the image. If the 479 * this function is called for every row in the image. If the
364 * image is interlacing, and you turned on the interlace handler, 480 * image is interlacing, and you turned on the interlace handler,
365 * this function will be called for every row in every pass. 481 * this function will be called for every row in every pass.
366 * Some of these rows will not be changed from the previous pass. 482 * 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. 483 * 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 484 * 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 485 * need the row_num and pass, but I'm supplying them because it
370 * may make your life easier. 486 * may make your life easier.
371 */ 487 */
372 488
373 // Nothing to do if the row is unchanged, or the row is outside 489 // 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 490 // the image bounds: libpng may send extra rows, ignore them to
375 // make our lives easier. 491 // make our lives easier.
376 if (!rowBuffer) 492 if (!rowBuffer)
377 return; 493 return;
378 int y = rowIndex; 494 int y = rowIndex + frameRect.y();
379 if (y < 0 || y >= size().height()) 495 ASSERT(y >= 0);
496 if (y >= size().height())
380 return; 497 return;
381 498
382 /* libpng comments (continued). 499 /* libpng comments (continued).
383 * 500 *
384 * For the non-NULL rows of interlaced images, you must call 501 * For the non-NULL rows of interlaced images, you must call
385 * png_progressive_combine_row() passing in the row and the 502 * png_progressive_combine_row() passing in the row and the
386 * old row. You can call this function for NULL rows (it will 503 * old row. You can call this function for NULL rows (it will
387 * just return) and for non-interlaced images (it just does the 504 * just return) and for non-interlaced images (it just does the
388 * memcpy for you) if it will make the code easier. Thus, you 505 * memcpy for you) if it will make the code easier. Thus, you
389 * can just do this for all cases: 506 * can just do this for all cases:
390 * 507 *
391 * png_progressive_combine_row(png_ptr, old_row, new_row); 508 * png_progressive_combine_row(png_ptr, old_row, new_row);
392 * 509 *
393 * where old_row is what was displayed for previous rows. Note 510 * where old_row is what was displayed for previous rows. Note
394 * that the first pass (pass == 0 really) will completely cover 511 * that the first pass (pass == 0 really) will completely cover
395 * the old row, so the rows do not have to be initialized. After 512 * 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 513 * the first pass (and only for interlaced images), you will have
397 * to pass the current row, and the function will combine the 514 * to pass the current row, and the function will combine the
398 * old row and the new row. 515 * old row and the new row.
399 */ 516 */
400 517
401 bool hasAlpha = m_reader->hasAlpha(); 518 bool hasAlpha = m_reader->hasAlpha();
402 png_bytep row = rowBuffer; 519 png_bytep row = rowBuffer;
403 520
404 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) { 521 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
405 unsigned colorChannels = hasAlpha ? 4 : 3; 522 unsigned colorChannels = hasAlpha ? 4 : 3;
406 row = interlaceBuffer + (rowIndex * colorChannels * size().width()); 523 row = interlaceBuffer + (rowIndex * colorChannels * size().width());
407 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer); 524 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
408 } 525 }
409 526
410 // Write the decoded row pixels to the frame buffer. The repetitive 527 // Write the decoded row pixels to the frame buffer. The repetitive
411 // form of the row write loops is for speed. 528 // form of the row write loops is for speed.
412 ImageFrame::PixelData* const dstRow = buffer.getAddr(0, y); 529 ImageFrame::PixelData* const dstRow = buffer.getAddr(frameRect.x(), y);
413 unsigned alphaMask = 255; 530 unsigned alphaMask = 255;
414 int width = size().width(); 531 int width = frameRect.width();
415 532
416 png_bytep srcPtr = row; 533 png_bytep srcPtr = row;
417 if (hasAlpha) { 534 if (hasAlpha) {
418 // Here we apply the color space transformation to the dst space. 535 // Here we apply the color space transformation to the dst space.
419 // It does not really make sense to transform to a gamma-encoded 536 // It does not really make sense to transform to a gamma-encoded
420 // space and then immediately after, perform a linear premultiply. 537 // space and then immediately after, perform a linear premultiply.
421 // Ideally we would pass kPremul_SkAlphaType to xform->apply(), 538 // Ideally we would pass kPremul_SkAlphaType to xform->apply(),
422 // instructing SkColorSpaceXform to perform the linear premultiply 539 // instructing SkColorSpaceXform to perform the linear premultiply
423 // while the pixels are a linear space. 540 // while the pixels are a linear space.
424 // We cannot do this because when we apply the gamma encoding after 541 // We cannot do this because when we apply the gamma encoding after
425 // the premultiply, we will very likely end up with valid pixels 542 // 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 543 // where R, G, and/or B are greater than A. The legacy drawing
427 // pipeline does not know how to handle this. 544 // pipeline does not know how to handle this.
428 if (SkColorSpaceXform* xform = colorTransform()) { 545 if (SkColorSpaceXform* xform = colorTransform()) {
429 SkColorSpaceXform::ColorFormat colorFormat = 546 SkColorSpaceXform::ColorFormat colorFormat =
430 SkColorSpaceXform::kRGBA_8888_ColorFormat; 547 SkColorSpaceXform::kRGBA_8888_ColorFormat;
431 xform->apply(colorFormat, dstRow, colorFormat, srcPtr, size().width(), 548 xform->apply(colorFormat, dstRow, colorFormat, srcPtr, size().width(),
432 kUnpremul_SkAlphaType); 549 kUnpremul_SkAlphaType);
433 srcPtr = (png_bytep)dstRow; 550 srcPtr = (png_bytep)dstRow;
434 } 551 }
435 552
436 if (buffer.premultiplyAlpha()) { 553 if (m_frameBufferCache[m_currentFrame].getAlphaBlendSource() ==
437 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 554 ImageFrame::BlendAtopBgcolor) {
438 dstPixel++, srcPtr += 4) { 555 if (buffer.premultiplyAlpha()) {
439 buffer.setRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 556 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
scroggo_chromium 2016/11/29 16:30:51 nit: auto* instead of auto * (here and below)
joostouwerling 2016/12/02 16:08:41 Done.
440 srcPtr[3]); 557 dstPixel++, srcPtr += 4) {
441 alphaMask &= srcPtr[3]; 558 buffer.setRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2],
559 srcPtr[3]);
560 alphaMask &= srcPtr[3];
561 }
562 } else {
563 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
564 dstPixel++, srcPtr += 4) {
565 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[3] );
566 alphaMask &= srcPtr[3];
567 }
442 } 568 }
443 } else { 569 } else {
scroggo_chromium 2016/11/29 16:30:51 Maybe add a comment that this is ImageFrame::Blend
joostouwerling 2016/12/02 16:08:41 Done. I prefer the if-else since there are only tw
scroggo_chromium 2016/12/02 21:28:49 Sgtm.
444 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 570 if (buffer.premultiplyAlpha()) {
445 dstPixel++, srcPtr += 4) { 571 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
446 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[3]); 572 dstPixel++, srcPtr += 4) {
447 alphaMask &= srcPtr[3]; 573 buffer.blendRGBAPremultiply(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2],
574 srcPtr[3]);
575 alphaMask &= srcPtr[3];
576 }
577 } else {
578 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
579 dstPixel++, srcPtr += 4) {
580 buffer.blendRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], srcPtr[ 3]);
581 alphaMask &= srcPtr[3];
582 }
448 } 583 }
449 } 584 }
450 } else { 585 } else {
451 for (auto *dstPixel = dstRow; dstPixel < dstRow + width; 586 for (auto *dstPixel = dstRow; dstPixel < dstRow + width;
452 dstPixel++, srcPtr += 3) { 587 dstPixel++, srcPtr += 3) {
453 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 255); 588 buffer.setRGBARaw(dstPixel, srcPtr[0], srcPtr[1], srcPtr[2], 255);
454 } 589 }
455 590
456 // We'll apply the color space xform to opaque pixels after they have been 591 // We'll apply the color space xform to opaque pixels after they have been
457 // written to the ImageFrame, purely because SkColorSpaceXform supports 592 // written to the ImageFrame, purely because SkColorSpaceXform supports
458 // RGBA (and not RGB). 593 // RGBA (and not RGB).
459 if (SkColorSpaceXform* xform = colorTransform()) { 594 if (SkColorSpaceXform* xform = colorTransform()) {
460 xform->apply(xformColorFormat(), dstRow, xformColorFormat(), dstRow, 595 xform->apply(xformColorFormat(), dstRow, xformColorFormat(), dstRow,
461 size().width(), kOpaque_SkAlphaType); 596 size().width(), kOpaque_SkAlphaType);
462 } 597 }
463 } 598 }
464 599
465 if (alphaMask != 255 && !buffer.hasAlpha()) 600 if (alphaMask != 255 && !buffer.hasAlpha())
466 buffer.setHasAlpha(true); 601 buffer.setHasAlpha(true);
467 602
468 buffer.setPixelsChanged(true); 603 buffer.setPixelsChanged(true);
469 } 604 }
470 605
606 bool PNGImageDecoder::frameIsCompleteAtIndex(size_t index) const {
607 // @TODO(joostouwerling): show complete frames even if a later frame fails.
608 if (failed())
609 return false;
610 if (index == 0)
611 return ImageDecoder::frameIsCompleteAtIndex(index);
612
613 // For non-first frames, the frame is considered complete if all frame data
614 // has been received. Non-first frames are reported by |m_reader| once it has
615 // parsed all data for that frame, so we can simply return if the index
616 // exists in |m_frameBufferCache| here.
617 return (index < m_frameBufferCache.size());
618 }
619
620 float PNGImageDecoder::frameDurationAtIndex(size_t index) const {
621 return (index < m_frameBufferCache.size()
622 ? m_frameBufferCache[index].duration()
623 : 0);
624 }
625
471 void PNGImageDecoder::complete() { 626 void PNGImageDecoder::complete() {
472 if (m_frameBufferCache.isEmpty()) 627 if (m_frameBufferCache.isEmpty())
473 return; 628 return;
474 629
475 m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete); 630 // @TODO(joostouwerling) if necessary, do a check if all expected data has
476 } 631 // been received. This is because the IEND chunk is sent
632 // artificially. The necessity of this check depends on
633 // how libpng handles in- and overcomplete frame data.
477 634
478 inline bool isComplete(const PNGImageDecoder* decoder) { 635 if (m_reader->interlaceBuffer())
479 return decoder->frameIsCompleteAtIndex(0); 636 m_reader->clearInterlaceBuffer();
480 } 637
638 m_frameBufferCache[m_currentFrame].setStatus(ImageFrame::FrameComplete);
481 639
482 void PNGImageDecoder::decode(bool onlySize) {
483 if (failed())
484 return;
485
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 } 640 }
498 641
499 } // namespace blink 642 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698