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

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

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

Powered by Google App Engine
This is Rietveld 408576698