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

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

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

Powered by Google App Engine
This is Rietveld 408576698