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

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

Issue 2386453003: WIP: Implement APNG (Closed)
Patch Set: Decode later frames row by row Created 4 years, 1 month 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) {}
163 67
164 PNGImageDecoder::~PNGImageDecoder() {} 68 PNGImageDecoder::~PNGImageDecoder() {}
165 69
70 size_t PNGImageDecoder::decodeFrameCount() {
71 parse(PNGParseQuery::PNGMetaDataQuery);
72 return m_frameCount;
73 }
74
75 void PNGImageDecoder::decode(size_t index) {
76 parse(PNGParseQuery::PNGMetaDataQuery);
77
78 // @TODO(joostouwerling): show complete frames even if a later frame fails.
79 if (failed())
80 return;
81
82 updateAggressivePurging(index);
83
84 Vector<size_t> framesToDecode;
85 size_t frameToDecode = index;
86
87 // This method is only called by ImageDecoder::frameBufferAtIndex if the frame
88 // status of frame |index| is not ImageFrame::FrameComplete. Therefore, it is
89 // OK that the do-while loop always appends |index| to |m_framesToDecode|,
90 // without checking for its status.
91 //
92 // The requiredPreviousFrameIndex for each frame is set in
93 // PNGImageDecoder::initializeNewFrame().
94 do {
95 framesToDecode.append(frameToDecode);
96 frameToDecode =
97 m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
98 } while (frameToDecode != kNotFound &&
99 m_frameBufferCache[frameToDecode].getStatus() !=
100 ImageFrame::FrameComplete);
101
102 for (auto i = framesToDecode.rbegin(); i != framesToDecode.rend(); i++) {
103 m_currentFrame = *i;
104 m_reader->decode(*m_data, *i);
105 if (failed())
106 return;
107
108 // If the frame is not yet complete, we need more data to continue.
109 if (m_frameBufferCache[*i].getStatus() != ImageFrame::FrameComplete)
110 break;
111
112 if (m_purgeAggressively)
113 clearCacheExceptFrame(*i);
114 }
115 }
116
117 // @TODO(joostouwerling) Consolidate this with a proposed change in
118 // ImageDecoder::clearCacheExceptFrame. See
119 // crrev.com/2468233002
120 size_t PNGImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame) {
121 // As per the comments at ImageDecoder::clearCacheExceptFrame
122 if (m_frameBufferCache.size() <= 1)
123 return 0;
124
125 // We expect that after this call, we'll be asked to decode frames after
126 // this one. So we want to avoid clearing frames such that those requests
127 // would force re-decoding from the beginning of the image.
128 //
129 // When |clearExceptFrame| is e.g. DisposeKeep, simply not clearing that
130 // frame is sufficient, as the next frame will be based on it, and in
131 // general future frames can't be based on anything previous.
132 //
133 // However, if this frame is DisposeOverwritePrevious, then subsequent
134 // frames will depend on this frame's required previous frame. In this
135 // case, we need to preserve both this frame and that one.
136 size_t clearExceptFrame2 = kNotFound;
137 if (clearExceptFrame < m_frameBufferCache.size()) {
138 const ImageFrame& frame = m_frameBufferCache[clearExceptFrame];
139 if (frame.getStatus() != ImageFrame::FrameEmpty &&
140 frame.getDisposalMethod() == ImageFrame::DisposeOverwritePrevious) {
141 clearExceptFrame2 = clearExceptFrame;
142 clearExceptFrame = frame.requiredPreviousFrameIndex();
143 }
144 }
145
146 // Now |clearExceptFrame| indicates the frame that future frames will
147 // depend on. But if decoding is skipping forward past intermediate frames,
148 // this frame may be FrameEmpty. So we need to keep traversing back through
149 // the required previous frames until we find the nearest non-empty
150 // ancestor. Preserving that will minimize the amount of future decoding
151 // needed.
152 while (clearExceptFrame < m_frameBufferCache.size() &&
153 m_frameBufferCache[clearExceptFrame].getStatus() ==
154 ImageFrame::FrameEmpty)
155 clearExceptFrame =
156 m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
157
158 return clearCacheExceptTwoFrames(clearExceptFrame, clearExceptFrame2);
159 }
160
161 size_t PNGImageDecoder::clearCacheExceptTwoFrames(size_t clearExceptFrame1,
162 size_t clearExceptFrame2) {
163 size_t frameBytesCleared = 0;
164 for (size_t i = 0; i < m_frameBufferCache.size(); ++i) {
165 if (m_frameBufferCache[i].getStatus() != ImageFrame::FrameEmpty &&
166 i != clearExceptFrame1 && i != clearExceptFrame2) {
167 frameBytesCleared += frameBytesAtIndex(i);
168 clearFrameBuffer(i);
169 }
170 }
171 return frameBytesCleared;
172 }
173
174 void PNGImageDecoder::clearFrameBuffer(size_t frameIndex) {
175 if (m_frameBufferCache[frameIndex].getStatus() == ImageFrame::FramePartial)
176 m_reader->clearDecodeState(frameIndex);
177
178 m_frameBufferCache[frameIndex].clearPixelData();
179 }
180
181 void PNGImageDecoder::parse(PNGParseQuery query) {
182 if (failed())
183 return;
184
185 if (!m_reader)
186 m_reader = wrapUnique(new PNGImageReader(this, m_offset));
187
188 if (!m_reader->parse(*m_data, query) && isAllDataReceived())
189 setFailed();
scroggo_chromium 2016/11/11 21:31:06 Should we also return here? Do we want to read the
joostouwerling 2016/11/21 20:27:44 I think this is better. Say the parse call returns
190
191 if (query == PNGParseQuery::PNGMetaDataQuery)
192 m_frameCount = m_reader->frameCount();
193 }
194
195 void PNGImageDecoder::setRepetitionCount(size_t repetitionCount) {
196 m_repetitionCount =
197 (repetitionCount == 0) ? cAnimationLoopInfinite : repetitionCount;
198 }
199
200 // This matches the existing behavior to loop once if decoding fails, but this
201 // should be changed to stick with m_repetitionCount to match other browsers.
202 // See crbug.com/267883
203 int PNGImageDecoder::repetitionCount() const {
204 if (m_reader->parseCompleted() && isAllDataReceived() &&
205 m_reader->frameCount() == 1)
scroggo_chromium 2016/11/11 21:31:06 This seems complicated. Don't we know long before
joostouwerling 2016/11/21 20:27:44 Yeah, you're right - once parseCompleted() is true
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);
scroggo_chromium 2016/11/11 21:31:06 Most of our buffers are set to true initially, sin
joostouwerling 2016/11/21 20:27:44 The original PNG implementation used it in this wa
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 ||
(...skipping 16 matching lines...) Expand all
263 405
264 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace) { 406 if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreColorSpace) {
265 // We only support color profiles for color PALETTE and RGB[A] PNG. 407 // We only support color profiles for color PALETTE and RGB[A] PNG.
266 // Supporting color profiles for gray-scale images is slightly tricky, at 408 // Supporting color profiles for gray-scale images is slightly tricky, at
267 // least using the CoreGraphics ICC library, because we expand gray-scale 409 // 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 410 // 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 411 // 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. 412 // gray-scale image buffer and hand that to CoreGraphics.
271 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info); 413 sk_sp<SkColorSpace> colorSpace = readColorSpace(png, info);
272 if (colorSpace) { 414 if (colorSpace) {
273 setColorSpaceAndComputeTransform(colorSpace); 415 setColorSpaceAndComputeTransform(colorSpace);
scroggo_chromium 2016/11/11 21:31:06 This method will be called for each frame, right?
joostouwerling 2016/11/21 20:27:44 Afaik there is only color space information in the
274 } 416 }
275 } 417 }
276 418
277 if (!hasEmbeddedColorSpace()) { 419 if (!hasEmbeddedColorSpace()) {
278 // TODO (msarett): 420 // TODO (msarett):
279 // Applying the transfer function (gamma) should be handled by 421 // Applying the transfer function (gamma) should be handled by
280 // SkColorSpaceXform. Here we always convert to a transfer function that 422 // 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 423 // is a 2.2 exponential. This is a little strange given that the dst
282 // transfer function is not necessarily a 2.2 exponential. 424 // transfer function is not necessarily a 2.2 exponential.
283 // TODO (msarett): 425 // TODO (msarett):
284 // Often, PNGs that specify their transfer function with the gAMA tag will 426 // Often, PNGs that specify their transfer function with the gAMA tag will
285 // also specify their gamut with the cHRM tag. We should read this tag 427 // also specify their gamut with the cHRM tag. We should read this tag
286 // and do a full color space transformation if it is present. 428 // and do a full color space transformation if it is present.
287 const double inverseGamma = 0.45455; 429 const double inverseGamma = 0.45455;
288 const double defaultGamma = 2.2; 430 const double defaultGamma = 2.2;
289 double gamma; 431 double gamma;
290 if (!m_ignoreColorSpace && png_get_gAMA(png, info, &gamma)) { 432 if (!m_ignoreColorSpace && png_get_gAMA(png, info, &gamma)) {
291 const double maxGamma = 21474.83; 433 const double maxGamma = 21474.83;
292 if ((gamma <= 0.0) || (gamma > maxGamma)) { 434 if ((gamma <= 0.0) || (gamma > maxGamma)) {
293 gamma = inverseGamma; 435 gamma = inverseGamma;
294 png_set_gAMA(png, info, gamma); 436 png_set_gAMA(png, info, gamma);
295 } 437 }
296 png_set_gamma(png, defaultGamma, gamma); 438 png_set_gamma(png, defaultGamma, gamma);
297 } else { 439 } else {
298 png_set_gamma(png, defaultGamma, inverseGamma); 440 png_set_gamma(png, defaultGamma, inverseGamma);
299 } 441 }
300 } 442 }
301 443
302 // Tell libpng to send us rows for interlaced pngs. 444 // Tell libpng to send us rows for interlaced pngs.
scroggo_chromium 2016/11/11 21:31:06 Is this added whitespace?
joostouwerling 2016/11/21 20:27:44 Yes. Removed in ps 16.
303 if (interlaceType == PNG_INTERLACE_ADAM7) 445 if (interlaceType == PNG_INTERLACE_ADAM7)
304 png_set_interlace_handling(png); 446 png_set_interlace_handling(png);
305 447
306 // Update our info now. 448 // Update our info now.
307 png_read_update_info(png, info); 449 png_read_update_info(png, info);
308 channels = png_get_channels(png, info); 450 channels = png_get_channels(png, info);
309 ASSERT(channels == 3 || channels == 4); 451 ASSERT(channels == 3 || channels == 4);
310 452
311 m_reader->setHasAlpha(channels == 4); 453 m_reader->setHasAlpha(channels == 4);
312
313 if (m_reader->decodingSizeOnly()) {
scroggo_chromium 2016/11/11 21:31:06 Why is this no longer necessary? It looks to me l
joostouwerling 2016/11/21 20:27:44 As discussed in person: since I'm structurally par
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 } 454 }
326 455
327 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, 456 void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer,
328 unsigned rowIndex, 457 unsigned rowIndex,
329 int) { 458 int) {
330 if (m_frameBufferCache.isEmpty()) 459 if (m_frameBufferCache.isEmpty())
331 return; 460 return;
332 461
333 // Initialize the framebuffer if needed. 462 ImageFrame& buffer = m_frameBufferCache[m_currentFrame];
scroggo_chromium 2016/11/11 21:31:06 Move this below the if check, which does not use i
joostouwerling 2016/11/21 20:27:44 Done.
334 ImageFrame& buffer = m_frameBufferCache[0]; 463 if (!initFrameBuffer(m_currentFrame)) {
335 if (buffer.getStatus() == ImageFrame::FrameEmpty) { 464 setFailed();
336 png_structp png = m_reader->pngPtr(); 465 return;
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 } 466 }
360 467
468 // This frameRect is already clipped, so that it fits within the size of the
469 // image. This is done in initializeNewFrame() after a frameCount() call.
470 const IntRect& frameRect = buffer.originalFrameRect();
471
361 /* libpng comments (here to explain what follows). 472 /* libpng comments (here to explain what follows).
362 * 473 *
363 * this function is called for every row in the image. If the 474 * this function is called for every row in the image. If the
364 * image is interlacing, and you turned on the interlace handler, 475 * image is interlacing, and you turned on the interlace handler,
365 * this function will be called for every row in every pass. 476 * this function will be called for every row in every pass.
366 * Some of these rows will not be changed from the previous pass. 477 * 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. 478 * 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 479 * 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 480 * need the row_num and pass, but I'm supplying them because it
370 * may make your life easier. 481 * may make your life easier.
371 */ 482 */
372 483
373 // Nothing to do if the row is unchanged, or the row is outside 484 // 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 485 // the image bounds: libpng may send extra rows, ignore them to
375 // make our lives easier. 486 // make our lives easier.
376 if (!rowBuffer) 487 if (!rowBuffer)
377 return; 488 return;
378 int y = rowIndex; 489 int y = rowIndex + frameRect.y();
379 if (y < 0 || y >= size().height()) 490 ASSERT(y >= 0);
491 if (y >= size().height())
380 return; 492 return;
381 493
382 /* libpng comments (continued). 494 /* libpng comments (continued).
383 * 495 *
384 * For the non-NULL rows of interlaced images, you must call 496 * For the non-NULL rows of interlaced images, you must call
385 * png_progressive_combine_row() passing in the row and the 497 * png_progressive_combine_row() passing in the row and the
386 * old row. You can call this function for NULL rows (it will 498 * old row. You can call this function for NULL rows (it will
387 * just return) and for non-interlaced images (it just does the 499 * just return) and for non-interlaced images (it just does the
388 * memcpy for you) if it will make the code easier. Thus, you 500 * memcpy for you) if it will make the code easier. Thus, you
389 * can just do this for all cases: 501 * can just do this for all cases:
390 * 502 *
391 * png_progressive_combine_row(png_ptr, old_row, new_row); 503 * png_progressive_combine_row(png_ptr, old_row, new_row);
392 * 504 *
393 * where old_row is what was displayed for previous rows. Note 505 * where old_row is what was displayed for previous rows. Note
394 * that the first pass (pass == 0 really) will completely cover 506 * that the first pass (pass == 0 really) will completely cover
395 * the old row, so the rows do not have to be initialized. After 507 * 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 508 * the first pass (and only for interlaced images), you will have
397 * to pass the current row, and the function will combine the 509 * to pass the current row, and the function will combine the
398 * old row and the new row. 510 * old row and the new row.
399 */ 511 */
400 512
401 bool hasAlpha = m_reader->hasAlpha(); 513 bool hasAlpha = m_reader->hasAlpha();
402 png_bytep row = rowBuffer; 514 png_bytep row = rowBuffer;
403 515
404 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) { 516 if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
405 unsigned colorChannels = hasAlpha ? 4 : 3; 517 unsigned colorChannels = hasAlpha ? 4 : 3;
406 row = interlaceBuffer + (rowIndex * colorChannels * size().width()); 518 row = interlaceBuffer + (rowIndex * colorChannels * size().width());
407 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer); 519 png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
408 } 520 }
409 521
410 // Write the decoded row pixels to the frame buffer. The repetitive 522 // Write the decoded row pixels to the frame buffer. The repetitive
411 // form of the row write loops is for speed. 523 // form of the row write loops is for speed.
412 ImageFrame::PixelData* const dstRow = buffer.getAddr(0, y); 524 ImageFrame::PixelData* const dstRow = buffer.getAddr(frameRect.x(), y);
413 unsigned alphaMask = 255; 525 unsigned alphaMask = 255;
414 int width = size().width(); 526 int width = frameRect.width();
415 527
416 png_bytep srcPtr = row; 528 png_bytep srcPtr = row;
417 if (hasAlpha) { 529 if (hasAlpha) {
418 // Here we apply the color space transformation to the dst space. 530 // Here we apply the color space transformation to the dst space.
419 // It does not really make sense to transform to a gamma-encoded 531 // It does not really make sense to transform to a gamma-encoded
420 // space and then immediately after, perform a linear premultiply. 532 // space and then immediately after, perform a linear premultiply.
421 // Ideally we would pass kPremul_SkAlphaType to xform->apply(), 533 // Ideally we would pass kPremul_SkAlphaType to xform->apply(),
422 // instructing SkColorSpaceXform to perform the linear premultiply 534 // instructing SkColorSpaceXform to perform the linear premultiply
423 // while the pixels are a linear space. 535 // while the pixels are a linear space.
424 // We cannot do this because when we apply the gamma encoding after 536 // We cannot do this because when we apply the gamma encoding after
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
461 size().width(), kOpaque_SkAlphaType); 573 size().width(), kOpaque_SkAlphaType);
462 } 574 }
463 } 575 }
464 576
465 if (alphaMask != 255 && !buffer.hasAlpha()) 577 if (alphaMask != 255 && !buffer.hasAlpha())
466 buffer.setHasAlpha(true); 578 buffer.setHasAlpha(true);
467 579
468 buffer.setPixelsChanged(true); 580 buffer.setPixelsChanged(true);
469 } 581 }
470 582
583 bool PNGImageDecoder::frameIsCompleteAtIndex(size_t index) const {
584 // @TODO(joostouwerling): show complete frames even if a later frame fails.
585 if (failed())
586 return false;
587 if (index == 0)
588 return ImageDecoder::frameIsCompleteAtIndex(index);
589
590 // For non-first frames, the frame is considered complete if all frame data
591 // has been received. Non-first frames are reported by |m_reader| once it has
592 // parsed all data for that frame, so we can simply return if the index
593 // exists in |m_frameBufferCache| here.
594 return (index < m_frameBufferCache.size());
595 }
596
597 float PNGImageDecoder::frameDurationAtIndex(size_t index) const {
598 return (index < m_frameBufferCache.size()
599 ? m_frameBufferCache[index].duration()
600 : 0);
601 }
602
471 void PNGImageDecoder::complete() { 603 void PNGImageDecoder::complete() {
472 if (m_frameBufferCache.isEmpty()) 604 if (m_frameBufferCache.isEmpty())
473 return; 605 return;
474 606
475 m_frameBufferCache[0].setStatus(ImageFrame::FrameComplete); 607 // @TODO(joostouwerling) if necessary, do a check if all expected data has
476 } 608 // been received. This is because the IEND chunk is sent
609 // artificially. The necessity of this check depends on
610 // how libpng handles in- and overcomplete frame data.
477 611
478 inline bool isComplete(const PNGImageDecoder* decoder) { 612 if (m_reader->interlaceBuffer())
479 return decoder->frameIsCompleteAtIndex(0); 613 m_reader->clearInterlaceBuffer();
480 } 614
615 m_frameBufferCache[m_currentFrame].setStatus(ImageFrame::FrameComplete);
481 616
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 } 617 }
498 618
499 } // namespace blink 619 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698