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

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

Issue 2386453003: WIP: Implement APNG (Closed)
Patch Set: Fix memory leaks by using FastSharedReadBuffer and defining it smartly 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/PNGImageReader.h" 39 #include "platform/image-decoders/png/PNGImageReader.h"
40 40
41 #include "platform/image-decoders/FastSharedBufferReader.h"
41 #include "platform/image-decoders/SegmentReader.h" 42 #include "platform/image-decoders/SegmentReader.h"
43 #include "platform/image-decoders/png/PNGImageDecoder.h"
42 #include "png.h" 44 #include "png.h"
43 #include "wtf/PtrUtil.h" 45 #include "wtf/PtrUtil.h"
44 #include <memory> 46 #include <memory>
45 47
46 namespace { 48 namespace {
47 49
48 inline blink::PNGImageDecoder* imageDecoder(png_structp png) { 50 inline blink::PNGImageDecoder* imageDecoder(png_structp png) {
49 return static_cast<blink::PNGImageDecoder*>(png_get_progressive_ptr(png)); 51 return static_cast<blink::PNGImageDecoder*>(png_get_progressive_ptr(png));
50 } 52 }
51 53
(...skipping 13 matching lines...) Expand all
65 } 67 }
66 68
67 void PNGAPI pngFailed(png_structp png, png_const_charp) { 69 void PNGAPI pngFailed(png_structp png, png_const_charp) {
68 longjmp(JMPBUF(png), 1); 70 longjmp(JMPBUF(png), 1);
69 } 71 }
70 72
71 } // namespace 73 } // namespace
72 74
73 namespace blink { 75 namespace blink {
74 76
75 PNGImageReader::PNGImageReader(PNGImageDecoder* decoder, size_t readOffset) 77 // This is the callback function for unknown PNG chunks, which is used to
78 // extract the animation chunks.
79 static int readAnimationChunk(png_structp pngPtr, png_unknown_chunkp chunk) {
80 PNGImageReader* reader = (PNGImageReader*)png_get_user_chunk_ptr(pngPtr);
81 reader->parseAnimationChunk((const char*)chunk->name, chunk->data,
82 chunk->size);
83 return 1;
84 }
85
86 PNGImageReader::PNGImageReader(PNGImageDecoder* decoder, size_t initialOffset)
76 : m_decoder(decoder), 87 : m_decoder(decoder),
77 m_readOffset(readOffset), 88 m_initialOffset(initialOffset),
78 m_currentBufferSize(0), 89 m_readOffset(initialOffset),
79 m_decodingSizeOnly(false), 90 m_progressiveDecodeOffset(0),
80 m_hasAlpha(false) { 91 m_idatOffset(0),
92 m_idatIsPartOfAnimation(false),
93 m_isAnimated(false),
94 m_parsedSignature(false),
95 m_parseCompleted(false) {
81 m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0); 96 m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
82 m_info = png_create_info_struct(m_png); 97 m_info = png_create_info_struct(m_png);
83 png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable, 98 png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable,
84 pngRowAvailable, pngComplete); 99 pngRowAvailable, pngComplete);
100
101 // Keep the chunks which are of interest for APNG. This is solely used to
102 // parse the contents of the acTL and fcTL chunks - the fdAT chunks are
103 // manually converted to IDAT chunks when frames are decoded. We can omit
104 // this and pass the data part of the chunk directly to the
105 // parseAnimationChunk() when we detect an acTL or fcTL chunk, but this is
106 // more robust since it uses all libpng checks.
107 //
108 // We can't solely depend on this method for handling APNG chunks since it
109 // does not provide an offset for the chunks - and we need that to handle
110 // decode calls for specific frames.
111 png_byte apngChunks[] = {"acTL\0fcTL\0"};
112 png_set_keep_unknown_chunks(m_png, PNG_HANDLE_CHUNK_NEVER, apngChunks, 2);
113 png_set_read_user_chunk_fn(m_png, (png_voidp)this, readAnimationChunk);
85 } 114 }
86 115
87 PNGImageReader::~PNGImageReader() { 116 PNGImageReader::~PNGImageReader() {
88 png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0); 117 png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0);
89 DCHECK(!m_png && !m_info); 118 DCHECK(!m_png && !m_info);
90 119 }
91 m_readOffset = 0; 120
92 } 121 // This method reads from the FastSharedBufferReader, starting at offset,
93 122 // and returns |length| bytes in the form of a pointer to a const png_byte*.
94 bool PNGImageReader::decode(const SegmentReader& data, bool sizeOnly) { 123 // This function is used to make it easy to access data from the reader in a
95 m_decodingSizeOnly = sizeOnly; 124 // png friendly way, and pass it to libpng for decoding.
96 125 //
97 // We need to do the setjmp here. Otherwise bad things will happen. 126 // Pre-conditions before using this:
127 // - |reader|.size() >= |readOffset| + |length|
128 // - |buffer|.size() >= |length|
129 // - |length| <= |kBufferSize|
130 //
131 // The reason for the last two precondition is that currently the png signature
132 // plus IHDR chunk (8B + 25B = 33B) is the largest chunk that is read using this
133 // method. If the data is not consecutive, it is stored in |buffer|, which must
134 // have the size of (at least) |length|, but there's no need for it to be larger
135 // than |kBufferSize|.
136 static constexpr size_t kBufferSize = 33;
137 const png_byte* readAsConstPngBytep(const FastSharedBufferReader& reader,
138 size_t readOffset,
139 size_t length,
140 char* buffer) {
141 DCHECK(length <= kBufferSize);
142 return reinterpret_cast<const png_byte*>(
143 reader.getConsecutiveData(readOffset, length, buffer));
144 }
145
146 // This is used as a value for the byteLength of a frameInfo struct to
147 // indicate that it is the first frame, and we still need to set byteLength
148 // to the correct value as soon as the parser knows it. 1 is a safe value
149 // since the byteLength field of a frame is at least 12, in the case of an
150 // empty fdAT or IDAT chunk.
151 static constexpr size_t kFirstFrameIndicator = 1;
152
153 void PNGImageReader::decode(SegmentReader& data, size_t index) {
154 if (index >= m_frameInfo.size())
155 return;
156
157 // By defining |reader| here, we're making sure it gets correctly destroyed
158 // when libpng throws an error and jumps back to a setjmp. When |reader| is
159 // created *after* the setjmp definition, it would not be properly destroyed
160 // since regular stack unwinding does not occur [1]. The result of this would
161 // be that the reference count of the data pointer is not properly decreased,
162 // which will result in memory leaks.
163 //
164 // Since both non-animated and animated PNGs use |reader|, this is the most
165 // convenient place to define it, with the above in mind.
166 //
167 // [1] https://en.wikipedia.org/wiki/Setjmp.h#Caveats_and_limitations
168 const FastSharedBufferReader reader(&data);
169
170 // For non animated PNGs, resume decoding where we left off in parse(), at
171 // the beginning of the IDAT chunk. Recreating a png struct would either
172 // result in wasted work, by reprocessing all header bytes, or decoding the
173 // wrong data.
174 if (!m_isAnimated) {
175 if (setjmp(JMPBUF(m_png))) {
176 m_decoder->setFailed();
177 return;
178 }
179 m_progressiveDecodeOffset += processData(
180 reader, m_frameInfo[0].startOffset + m_progressiveDecodeOffset, 0);
181 return;
182 }
183
184 // When a non-first frame is decoded, and the previous decode call was a
185 // progressive decode of frame 0 which did not completely finish, set
186 // |m_progressiveDecodeOffset| to 0. This ensures that when a later call to
187 // decode frame 0 comes in, it will correctly decode the frame from the
188 // beginning. It is better to re-decode from the start than to try continuing
189 // where we left off, because:
190 // - A row may have been partially decoded, but it is hard to find where
191 // that row starts in the data. But we need to continue decoding from the
192 // beginning of the row, otherwise the pixels will be shifted and the final
193 // row won't be complete.
194 // - The |m_png| struct will be reset for this decode call, so it needs to
195 // be recreated when decoding for frame 0 continues. Since the header chunks
196 // need to be re-processed anyway, the added benefit of continuing
197 // progressive decoding may be very slim. Especially since this is already
198 // an edge case.
199 if (index > 0 && m_progressiveDecodeOffset > 0)
200 m_progressiveDecodeOffset = 0;
201
202 // Progressive decoding is only done if both of the following are true:
203 // - It is the first frame, thus |index| == 0, AND
204 // - The byteLength of the first frame is not yet known, *or* it is known
205 // but we're only partway in a progressive decode, started earlier.
206 bool firstFrameLengthKnown = firstFrameFullyReceived();
207 bool progressiveDecodingAlreadyStarted = m_progressiveDecodeOffset > 0;
208 bool progressiveDecode = (index == 0 && (!firstFrameLengthKnown ||
209 progressiveDecodingAlreadyStarted));
210 bool decodeAsNewPNG =
211 !progressiveDecode || !progressiveDecodingAlreadyStarted;
212
213 // Initialize a new png struct for this frame. For a progressive decode of
214 // the first frame, we only need to do this once.
215 // @FIXME(joostouwerling) check if the existing png struct can be reused.
216 if (decodeAsNewPNG)
217 resetPNGStruct();
218
219 // Before processing any PNG bytes, set setjmp with the current |m_png|
220 // struct. This has to be done after resetPNGStruct(), which will have
221 // replaced |m_png|.
222 if (setjmp(JMPBUF(m_png))) {
223 m_decoder->setFailed();
224 return;
225 }
226
227 // Process the png header chunks with a modified size, reflecting the size of
228 // this frame. This only needs to be done once for a progressive decode of
229 // the first frame.
230 if (decodeAsNewPNG)
231 startFrameDecoding(reader, index);
232
233 bool decodedFrameCompletely;
234 if (progressiveDecode) {
235 decodedFrameCompletely = progressivelyDecodeFirstFrame(reader);
236 // If progressive decoding processed all data for this frame, reset
237 // |m_progressiveDecodeOffset|, so |progressiveDecodingAlreadyStarted|
238 // will be false for later calls to decode frame 0.
239 if (decodedFrameCompletely)
240 m_progressiveDecodeOffset = 0;
241 } else {
242 decodeFrame(reader, index);
243 // For a non-progressive decode, we already have all the data we are
244 // going to get, so consider the frame complete.
245 decodedFrameCompletely = true;
246 }
247
248 // Send the IEND chunk if the frame is completely decoded, so the complete
249 // callback in |m_decoder| will be called.
250 if (decodedFrameCompletely)
251 endFrameDecoding();
252 }
253
254 void PNGImageReader::resetPNGStruct() {
255 // Each frame is processed as if it were a complete, single frame png image.
256 // To accomplish this, destroy the current |m_png| and |m_info| structs and
257 // create new ones. CRC errors are ignored, so fdAT chunks can be processed
258 // as IDATs without recalculating the CRC value.
259 png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0);
260 m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
261 m_info = png_create_info_struct(m_png);
262 png_set_crc_action(m_png, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
263 png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable,
264 pngRowAvailable, pngComplete);
265 }
266
267 void PNGImageReader::startFrameDecoding(const FastSharedBufferReader& reader,
268 size_t index) {
269 // If the frame is the size of the whole image, we don't need to modify any
270 // data in the IHDR chunk. This means it suffices to re-process all header
271 // data up to the first frame, for mimicking a png image.
272 const IntRect& frameRect = m_frameInfo[index].frameRect;
273 if (frameRect.location() == IntPoint() &&
274 frameRect.size() == m_decoder->size()) {
275 processData(reader, m_initialOffset, m_idatOffset);
276 return;
277 }
278
279 // Process the IHDR chunk, but change the width and height so it reflects
280 // the frame's width and height. Image Decoder will apply the x,y offset.
281 // This step is omitted if the width and height are equal to the image size,
282 // which is done in the block above.
283 char readBuffer[kBufferSize];
284
285 // |headerSize| is equal to |kBufferSize|, but adds more semantic insight.
286 constexpr size_t headerSize = 33;
287 png_byte header[headerSize];
288 const png_byte* chunk =
289 readAsConstPngBytep(reader, m_initialOffset, headerSize, readBuffer);
290 memcpy(header, chunk, headerSize);
291
292 // Write the unclipped width and height. Clipping happens in the decoder.
293 png_save_uint_32(header + 16, frameRect.width());
294 png_save_uint_32(header + 20, frameRect.height());
295 png_process_data(m_png, m_info, header, headerSize);
296
297 // Process the rest of the header chunks. Start after the PNG signature and
298 // IHDR chunk, 33B, and process up to the first data chunk. The number of
299 // bytes up to the first data chunk is stored in |m_idatOffset|.
300 processData(reader, m_initialOffset + headerSize, m_idatOffset - headerSize);
301 }
302
303 // Determine if the bytes 4 to 7 of |chunk| indicate that it is a |tag| chunk.
304 // - The length of |chunk| must be >= 8
305 // - The length of |tag| must be = 4
306 static inline bool isChunk(const png_byte* chunk, const char* tag) {
307 return memcmp(chunk + 4, tag, 4) == 0;
308 }
309
310 bool PNGImageReader::progressivelyDecodeFirstFrame(
311 const FastSharedBufferReader& reader) {
312 char readBuffer[8]; // large enough to identify a chunk.
313 size_t offset = m_frameInfo[0].startOffset;
314
315 // Loop while there is enough data to do progressive decoding.
316 while (reader.size() >= offset + 8) {
317 // At the beginning of each loop, the offset is at the start of a chunk.
318 const png_byte* chunk = readAsConstPngBytep(reader, offset, 8, readBuffer);
319 const png_uint_32 length = png_get_uint_32(chunk);
320
321 // When an fcTL or IEND chunk is encountered, the frame data has ended.
322 // Return true, since all frame data is decoded.
323 if (isChunk(chunk, "fcTL") || isChunk(chunk, "IEND"))
324 return true;
325
326 // If this chunk was already decoded, move on to the next.
327 if (m_progressiveDecodeOffset >= offset + length + 12) {
328 offset += length + 12;
329 continue;
330 }
331
332 // At this point, three scenarios are possible:
333 // 1) Some bytes of this chunk were already decoded in a previous call,
334 // so we need to continue from there.
335 // 2) This is an fdAT chunk, so we need to convert it to an IDAT chunk
336 // before we can decode it.
337 // 3) This is any other chunk, most likely an IDAT chunk.
338 //
339 // In each scenario, we want to decode as much data as possible. In each
340 // one, do the scenario specific work and set |offset| to where decoding
341 // needs to continue. From there, decode until the end of the chunk, if
342 // possible. If the whole chunk is decoded, continue to the next loop.
343 // Otherwise, store how far we've come in |m_progressiveDecodeOffset| and
344 // return false to indicate to the caller that the frame is partially
345 // decoded.
346
347 size_t endOffsetChunk = offset + length + 12;
348
349 // Scenario 1: |m_progressiveDecodeOffset| is ahead of the chunk tag.
350 if (m_progressiveDecodeOffset >= offset + 8) {
351 offset = m_progressiveDecodeOffset;
352
353 // Scenario 2: we need to convert the fdAT to an IDAT chunk. For an
354 // explanation of the numbers, see the comments in decodeFrame().
355 } else if (isChunk(chunk, "fdAT")) {
356 png_byte chunkIDAT[] = {0, 0, 0, 0, 'I', 'D', 'A', 'T'};
357 png_save_uint_32(chunkIDAT, length - 4);
358 png_process_data(m_png, m_info, chunkIDAT, 8);
359 // Skip the sequence number
360 offset += 12;
361
362 // Scenario 3: for any other chunk type, process the first 8 bytes.
363 } else {
364 png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
365 offset += 8;
366 }
367
368 size_t bytesLeftInChunk = endOffsetChunk - offset;
369 size_t bytesDecoded = processData(reader, offset, bytesLeftInChunk);
370 m_progressiveDecodeOffset = offset + bytesDecoded;
371 if (bytesDecoded < bytesLeftInChunk)
372 return false;
373 offset += bytesDecoded;
374 }
375
376 return false;
377 }
378
379 void PNGImageReader::decodeFrame(const FastSharedBufferReader& reader,
380 size_t index) {
381 // From the frame info that was gathered during parsing, it is known at
382 // what offset the frame data starts and how many bytes are in the stream
383 // before the frame ends. Using this, we process all chunks that fall in
384 // this interval. We catch every fdAT chunk and transform it to an IDAT
385 // chunk, so libpng will decode it like a non-animated PNG image.
386 size_t offset = m_frameInfo[index].startOffset;
387 size_t endOffset = offset + m_frameInfo[index].byteLength;
388 char readBuffer[8];
389
390 while (offset < endOffset) {
391 const png_byte* chunk = readAsConstPngBytep(reader, offset, 8, readBuffer);
392 const png_uint_32 length = png_get_uint_32(chunk);
393 if (isChunk(chunk, "fdAT")) {
394 // An fdAT chunk is build up as follows:
395 // - |length| (4B)
396 // - fdAT tag (4B)
397 // - sequence number (4B)
398 // - frame data (|length| - 4B)
399 // - CRC (4B)
400 // Thus, to reformat this into an IDAT chunk, we need to:
401 // - write |length| - 4 as the new length, since the sequence number
402 // must be removed.
403 // - change the tag to IDAT.
404 // - omit the sequence number from the data part of the chunk.
405 png_byte chunkIDAT[] = {0, 0, 0, 0, 'I', 'D', 'A', 'T'};
406 png_save_uint_32(chunkIDAT, length - 4);
407 png_process_data(m_png, m_info, chunkIDAT, 8);
408 // The frame data and the CRC span |length| bytes, so skip the
409 // sequence number and process |length| bytes to decode the frame.
410 processData(reader, offset + 12, length);
411 } else {
412 png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
413 processData(reader, offset + 8, length + 4);
414 }
415 offset += 12 + length;
416 }
417 }
418
419 void PNGImageReader::endFrameDecoding() {
420 png_byte IEND[12] = {0, 0, 0, 0, 'I', 'E', 'N', 'D', 174, 66, 96, 130};
421 png_process_data(m_png, m_info, IEND, 12);
422 }
423
424 bool PNGImageReader::parse(SegmentReader& data, PNGParseQuery query) {
425 if (m_parseCompleted)
426 return true;
427
428 // |reader| is defined here to prevent memory leaks. For a detailed
429 // explanation, see the definition of |reader| in PNGImageReader::decode. In
430 // this case, both parseSize() and this method use |reader|.
431 const FastSharedBufferReader reader(&data);
432
433 // If the size has not been parsed, do that first, since it's necessary
434 // for both the Size and MetaData query. If parseSize returns false,
435 // it failed because of a lack of data so we can return false at this point.
436 if (!m_decoder->isDecodedSizeAvailable() && !parseSize(reader))
437 return false;
438
439 if (query == PNGParseQuery::PNGSizeQuery)
440 return m_decoder->isDecodedSizeAvailable();
441
442 // For non animated images (identified by no acTL chunk before the IDAT),
443 // we create one frame. This saves some processing time since we don't need
444 // to go over the stream to find chunks.
445 if (!m_isAnimated) {
446 if (m_frameInfo.isEmpty()) {
447 FrameInfo frame;
448 // This needs to be plus 8 since the first 8 bytes of the IDAT chunk
449 // are already processed in parseSize().
450 frame.startOffset = m_readOffset + 8;
451 frame.frameRect = IntRect(IntPoint(), m_decoder->size());
452 frame.duration = 0;
453 frame.alphaBlend = kAPNGAlphaBlendBgcolor;
454 frame.disposalMethod = kAPNGDisposeKeep;
455 m_frameInfo.append(frame);
456 // When the png is not animated, no extra parsing is necessary.
457 m_parseCompleted = true;
458 }
459 return true;
460 }
461
462 char readBuffer[kBufferSize];
463
98 if (setjmp(JMPBUF(m_png))) 464 if (setjmp(JMPBUF(m_png)))
99 return m_decoder->setFailed(); 465 return m_decoder->setFailed();
100 466
467 // At this point, the query is FrameMetaDataQuery. Loop over the data and
468 // register all frames we can find. A frame is registered on the next fcTL
469 // chunk or when the IEND chunk is found. This ensures that only complete
470 // frames are reported, unless there is an error in the stream.
471 while (reader.size() >= m_readOffset + 8) {
472 const png_byte* chunk =
473 readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
474 const size_t length = png_get_uint_32(chunk);
475
476 // When we find an IDAT chunk (when the IDAT is part of the animation),
477 // or an fdAT chunk, and the readOffset field of the newFrame is 0,
478 // we have found the beginning of a new block of frame data.
479 const bool isFrameData =
480 isChunk(chunk, "fdAT") ||
481 (isChunk(chunk, "IDAT") && m_idatIsPartOfAnimation);
482 if (m_newFrame.startOffset == 0 && isFrameData) {
483 m_newFrame.startOffset = m_readOffset;
484
485 // When the |frameInfo| vector is empty, the first frame needs to be
486 // reported as soon as possible, even before all frame data is in
487 // |data|, so the first frame can be decoded progressively.
488 if (m_frameInfo.isEmpty()) {
489 m_newFrame.byteLength = kFirstFrameIndicator;
490 m_frameInfo.append(m_newFrame);
491 }
492
493 // An fcTL or IEND marks the end of the previous frame. Thus, the
494 // FrameInfo data in m_newFrame is submitted to the m_frameInfo vector.
495 //
496 // Furthermore, an fcTL chunk indicates a new frame is coming,
497 // so the m_newFrame variable is prepared accordingly by setting the
498 // readOffset field to 0, which indicates that the frame control info
499 // is available but that we haven't seen any frame data yet.
500 } else if (isChunk(chunk, "fcTL") || isChunk(chunk, "IEND")) {
501 if (m_newFrame.startOffset != 0) {
502 m_newFrame.byteLength = m_readOffset - m_newFrame.startOffset;
503 if (m_frameInfo[0].byteLength == kFirstFrameIndicator)
504 m_frameInfo[0].byteLength = m_newFrame.byteLength;
505 else
506 m_frameInfo.append(m_newFrame);
507
508 m_newFrame.startOffset = 0;
509 }
510
511 if (reader.size() < m_readOffset + 12 + length)
512 return false;
513
514 if (isChunk(chunk, "IEND")) {
515 // The PNG image ends at the IEND chunk, so all parsing is completed.
516 m_parseCompleted = true;
517 return true;
518 }
519
520 // At this point, we're dealing with an fcTL chunk, since the above
521 // statement already returns on IEND chunks.
522
523 // If the fcTL chunk is not 26 bytes long, we can't process it.
524 if (length != 26)
525 return m_decoder->setFailed();
526
527 chunk = readAsConstPngBytep(reader, m_readOffset + 8, length, readBuffer);
528 parseFrameInfo(chunk);
529 }
530 m_readOffset += 12 + length;
531 }
532 return false;
533 }
534
535 // If |length| == 0, read until the stream ends.
536 // @return: number of bytes processed.
537 size_t PNGImageReader::processData(const FastSharedBufferReader& reader,
538 size_t offset,
539 size_t length) {
101 const char* segment; 540 const char* segment;
102 while (size_t segmentLength = data.getSomeData(segment, m_readOffset)) { 541 size_t totalProcessedBytes = 0;
103 m_readOffset += segmentLength; 542 while (reader.size() > offset) {
104 m_currentBufferSize = m_readOffset; 543 size_t segmentLength = reader.getSomeData(segment, offset);
544 if (length > 0 && segmentLength + totalProcessedBytes > length)
545 segmentLength = length - totalProcessedBytes;
546
105 png_process_data(m_png, m_info, 547 png_process_data(m_png, m_info,
106 reinterpret_cast<png_bytep>(const_cast<char*>(segment)), 548 reinterpret_cast<png_byte*>(const_cast<char*>(segment)),
107 segmentLength); 549 segmentLength);
108 if (sizeOnly ? m_decoder->isDecodedSizeAvailable() 550 offset += segmentLength;
109 : m_decoder->frameIsCompleteAtIndex(0)) 551 totalProcessedBytes += segmentLength;
552 if (totalProcessedBytes == length)
553 return length;
554 }
555 return totalProcessedBytes;
556 }
557
558 // This methods reads through the stream until it has parsed the image size.
559 // @return true when it succeeds in parsing the size.
560 // false when:
561 // A) not enough data is provided
562 // B) decoding by libpng fails. In the this case, it will also call
563 // setFailed on m_decoder.
564 bool PNGImageReader::parseSize(const FastSharedBufferReader& reader) {
565 char readBuffer[kBufferSize];
566
567 if (setjmp(JMPBUF(m_png)))
568 return m_decoder->setFailed();
569
570 // Process the PNG signature and the IHDR with libpng, such that this code
571 // does not need to parse the contents. This also enables the reader to use
572 // the existing headerAvailable callback in the decoder.
573 //
574 // When we already have decoded the signature, we don't need to do it again.
575 // By setting a flag for this we allow for byte by byte parsing.
576 if (!m_parsedSignature) {
577 if (reader.size() < m_readOffset + 8)
578 return false;
579
580 const png_byte* chunk =
581 readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
582 png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
583 m_readOffset += 8;
584 m_parsedSignature = true;
585 // Initialize the newFrame by setting the readOffset to 0.
586 m_newFrame.startOffset = 0;
587 }
588
589 // This loop peeks at the chunk tag until the IDAT chunk is found. When
590 // a different tag is encountered, pass it on to libpng for general parsing.
591 // We can peek at chunks by looking at the first 8 bytes, which contain the
592 // length and the chunk tag.
593 //
594 // When an fcTL (frame control) is encountered before the IDAT, the frame
595 // data in the IDAT chunk is part of the animation. This case is flagged
596 // and the frame info is stored by parsing the fcTL chunk.
597 while (reader.size() >= m_readOffset + 8) {
598 const png_byte* chunk =
599 readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
600 const png_uint_32 length = png_get_uint_32(chunk);
601
602 // If we encounter the IDAT chunk, we're done with the png header
603 // chunks. Indicate this to libpng by sending the beginning of the IDAT
604 // chunk, which will trigger libpng to call the headerAvailable
605 // callback on m_decoder. This provides the size to the decoder.
606 if (isChunk(chunk, "IDAT")) {
607 m_idatOffset = m_readOffset;
608 png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
110 return true; 609 return true;
111 } 610 }
112 611
612 // Consider the PNG image animated if an acTL chunk of the correct
613 // length is present. Parsing the acTL content is done by
614 // parseAnimationControl, called by libpng's png_process_data.
615 if (isChunk(chunk, "acTL") && length == 8)
616 m_isAnimated = true;
617
618 // We don't need to check for |length| here, because the decoder will
619 // fail later on for invalid fcTL chunks.
620 else if (isChunk(chunk, "fcTL"))
621 m_idatIsPartOfAnimation = true;
622
623 // 12 is the length, tag and crc part of the chunk, which are all 4B.
624 if (reader.size() < m_readOffset + length + 12)
625 break;
626
627 png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
628 processData(reader, m_readOffset + 8, length + 4);
629 m_readOffset += length + 12;
630 }
631
632 // If we end up here, not enough data was available for the IDAT chunk
633 // So libpng would not have called headerAvailable yet.
113 return false; 634 return false;
114 } 635 }
115 636
116 } // namespace blink 637 void PNGImageReader::parseAnimationChunk(const char tag[],
638 const void* dataChunk,
639 size_t length) {
640 const png_byte* data = static_cast<const png_byte*>(dataChunk);
641
642 // The number of frames as indicated in the animation control chunk (acTL)
643 // is ignored, and the number of frames that are actually present is used.
644 // For now, when the number of indicated frames is different from the
645 // number of supplied frames, the number of supplied frames is what is
646 // provided to the decoder. Therefore, it does not add any benefit of
647 // looking at the value of the indicated framecount. A note here is that
648 // there may be optimisations available, for example, prescaling vectors.
649 if (strcmp(tag, "acTL") == 0 && length == 8) {
650 png_uint_32 repetitionCount = png_get_uint_32(data + 4);
651 m_decoder->setRepetitionCount(repetitionCount);
652
653 // For fcTL, decoding fails if it does not have the correct length. It is
654 // impossible to make a guess about the frame if not all data is available.
655 // Use longjmp to get back to parse(), which is necessary since this method
656 // is called by a libpng callback.
657 } else if (strcmp(tag, "fcTL") == 0) {
658 if (length != 26)
659 longjmp(JMPBUF(m_png), 1);
660 parseFrameInfo(data);
661 }
662 }
663
664 bool PNGImageReader::firstFrameFullyReceived() const {
665 DCHECK_GT(m_frameInfo.size(), 0u);
666 return m_frameInfo[0].byteLength != kFirstFrameIndicator;
667 }
668
669 void PNGImageReader::clearDecodeState(size_t frameIndex) {
670 if (frameIndex == 0)
671 m_progressiveDecodeOffset = 0;
672 }
673
674 size_t PNGImageReader::frameCount() const {
675 return m_frameInfo.size();
676 }
677
678 const PNGImageReader::FrameInfo& PNGImageReader::frameInfo(size_t index) const {
679 DCHECK(index < m_frameInfo.size());
680 return m_frameInfo[index];
681 }
682
683 // Extract the frame control info and store it in m_newFrame. The length check
684 // on the data chunk has been done in parseAnimationChunk.
685 // The fcTL specification used can be found at:
686 // https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chu nk
687 void PNGImageReader::parseFrameInfo(const png_byte* data) {
688 png_uint_32 width, height, xOffset, yOffset;
689 png_uint_16 delayNumerator, delayDenominator;
690 width = png_get_uint_32(data + 4);
691 height = png_get_uint_32(data + 8);
692 xOffset = png_get_uint_32(data + 12);
693 yOffset = png_get_uint_32(data + 16);
694 delayNumerator = png_get_uint_16(data + 20);
695 delayDenominator = png_get_uint_16(data + 22);
696
697 m_newFrame.duration = (delayDenominator == 0)
698 ? delayNumerator * 10
699 : delayNumerator * 1000 / delayDenominator;
700 m_newFrame.frameRect = IntRect(xOffset, yOffset, width, height);
701 m_newFrame.disposalMethod = data[24];
702 m_newFrame.alphaBlend = data[25];
703 }
704
705 }; // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698