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

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

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

Powered by Google App Engine
This is Rietveld 408576698