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

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

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

Powered by Google App Engine
This is Rietveld 408576698