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

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

Issue 2386453003: WIP: Implement APNG (Closed)
Patch Set: Fix feedback on previous patches 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 side-by-side diff with in-line comments
Download patch
« no previous file with comments | « third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.h ('k') | no next file » | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.cpp
diff --git a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.cpp b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.cpp
index 177b58af86dbbebe6f631714da4501214ac11b31..e914fe7d19b484c2e66e20603808b1c8eff821df 100644
--- a/third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.cpp
+++ b/third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.cpp
@@ -38,7 +38,9 @@
#include "platform/image-decoders/png/PNGImageReader.h"
+#include "platform/image-decoders/FastSharedBufferReader.h"
#include "platform/image-decoders/SegmentReader.h"
+#include "platform/image-decoders/png/PNGImageDecoder.h"
#include "png.h"
#include "wtf/PtrUtil.h"
#include <memory>
@@ -72,45 +74,632 @@ void PNGAPI pngFailed(png_structp png, png_const_charp) {
namespace blink {
-PNGImageReader::PNGImageReader(PNGImageDecoder* decoder, size_t readOffset)
+// This is the callback function for unknown PNG chunks, which is used to
+// extract the animation chunks.
+static int readAnimationChunk(png_structp pngPtr, png_unknown_chunkp chunk) {
+ PNGImageReader* reader = (PNGImageReader*)png_get_user_chunk_ptr(pngPtr);
+ reader->parseAnimationChunk((const char*)chunk->name, chunk->data,
+ chunk->size);
+ return 1;
+}
+
+PNGImageReader::PNGImageReader(PNGImageDecoder* decoder, size_t initialOffset)
: m_decoder(decoder),
- m_readOffset(readOffset),
- m_currentBufferSize(0),
- m_decodingSizeOnly(false),
- m_hasAlpha(false) {
+ m_initialOffset(initialOffset),
+ m_readOffset(initialOffset),
+ m_progressiveDecodeOffset(0),
+ m_idatOffset(0),
+ m_idatIsPartOfAnimation(false),
+ m_isAnimated(false),
+ m_parsedSignature(false),
+ m_parseCompleted(false) {
m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
m_info = png_create_info_struct(m_png);
png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable,
pngRowAvailable, pngComplete);
+
+ // Keep the chunks which are of interest for APNG. This is solely used to
+ // parse the contents of the acTL and fcTL chunks - the fdAT chunks are
+ // manually converted to IDAT chunks when frames are decoded. We can omit
+ // this and pass the data part of the chunk directly to the
+ // parseAnimationChunk() when we detect an acTL or fcTL chunk, but this is
+ // more robust since it uses all libpng checks.
+ //
+ // We can't solely depend on this method for handling APNG chunks since it
+ // does not provide an offset for the chunks - and we need that to handle
+ // decode calls for specific frames.
+ png_byte apngChunks[] = {"acTL\0fcTL\0"};
+ png_set_keep_unknown_chunks(m_png, PNG_HANDLE_CHUNK_NEVER, apngChunks, 2);
+ png_set_read_user_chunk_fn(m_png, (png_voidp)this, readAnimationChunk);
}
PNGImageReader::~PNGImageReader() {
png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0);
DCHECK(!m_png && !m_info);
+}
+
+// This method reads from the FastSharedBufferReader, starting at offset,
+// and returns |length| bytes in the form of a pointer to a const png_byte*.
+// This function is used to make it easy to access data from the reader in a
+// png friendly way, and pass it to libpng for decoding.
+//
+// Pre-conditions before using this:
+// - |reader|.size() >= |readOffset| + |length|
+// - |buffer|.size() >= |length|
+// - |length| <= |kBufferSize|
+//
+// The reason for the last two precondition is that currently the png signature
+// plus IHDR chunk (8B + 25B = 33B) is the largest chunk that is read using this
+// method. If the data is not consecutive, it is stored in |buffer|, which must
+// have the size of (at least) |length|, but there's no need for it to be larger
+// than |kBufferSize|.
+static constexpr size_t kBufferSize = 33;
+const png_byte* readAsConstPngBytep(const FastSharedBufferReader& reader,
+ size_t readOffset,
+ size_t length,
+ char* buffer) {
+ DCHECK(length <= kBufferSize);
+ return reinterpret_cast<const png_byte*>(
+ reader.getConsecutiveData(readOffset, length, buffer));
+}
+
+// This is used as a value for the byteLength of a frameInfo struct to
+// indicate that it is the first frame, and we still need to set byteLength
+// to the correct value as soon as the parser knows it. 1 is a safe value
+// since the byteLength field of a frame is at least 12, in the case of an
+// empty fdAT or IDAT chunk.
+static constexpr size_t kFirstFrameIndicator = 1;
+
+void PNGImageReader::decode(SegmentReader& data, size_t index) {
+ if (index >= m_frameInfo.size())
+ return;
+
+ // By defining |reader| here, we're making sure it gets correctly destroyed
+ // when libpng throws an error and jumps back to a setjmp. When |reader| is
+ // created *after* the setjmp definition, it would not be properly destroyed
+ // since regular stack unwinding does not occur [1]. The result of this would
+ // be that the reference count of the data pointer is not properly decreased,
+ // which will result in memory leaks.
+ //
+ // Since both non-animated and animated PNGs use |reader|, this is the most
+ // convenient place to define it, with the above in mind.
+ //
+ // [1] https://en.wikipedia.org/wiki/Setjmp.h#Caveats_and_limitations
+ const FastSharedBufferReader reader(&data);
+
+ // For non animated PNGs, resume decoding where we left off in parse(), at
+ // the beginning of the IDAT chunk. Recreating a png struct would either
+ // result in wasted work, by reprocessing all header bytes, or decoding the
+ // wrong data.
+ if (!m_isAnimated) {
+ if (setjmp(JMPBUF(m_png))) {
+ m_decoder->setFailed();
+ return;
+ }
+ m_progressiveDecodeOffset += processData(
+ reader, m_frameInfo[0].startOffset + m_progressiveDecodeOffset, 0);
+ return;
+ }
+
+ // When a non-first frame is decoded, and the previous decode call was a
+ // progressive decode of frame 0 which did not completely finish, set
+ // |m_progressiveDecodeOffset| to 0. This ensures that when a later call to
+ // decode frame 0 comes in, it will correctly decode the frame from the
+ // beginning. It is better to re-decode from the start than to try continuing
+ // where we left off, because:
+ // - A row may have been partially decoded, but it is hard to find where
+ // that row starts in the data. But we need to continue decoding from the
+ // beginning of the row, otherwise the pixels will be shifted and the final
+ // row won't be complete.
+ // - The |m_png| struct will be reset for this decode call, so it needs to
+ // be recreated when decoding for frame 0 continues. Since the header chunks
+ // need to be re-processed anyway, the added benefit of continuing
+ // progressive decoding may be very slim. Especially since this is already
+ // an edge case.
+ if (index > 0 && m_progressiveDecodeOffset > 0)
+ m_progressiveDecodeOffset = 0;
+
+ // Progressive decoding is only done if both of the following are true:
+ // - It is the first frame, thus |index| == 0, AND
+ // - The byteLength of the first frame is not yet known, *or* it is known
+ // but we're only partway in a progressive decode, started earlier.
+ bool firstFrameLengthKnown = firstFrameFullyReceived();
+ bool progressiveDecodingAlreadyStarted = m_progressiveDecodeOffset > 0;
+ bool progressiveDecode = (index == 0 && (!firstFrameLengthKnown ||
+ progressiveDecodingAlreadyStarted));
+ bool decodeAsNewPNG =
+ !progressiveDecode || !progressiveDecodingAlreadyStarted;
+
+ // Initialize a new png struct for this frame. For a progressive decode of
+ // the first frame, we only need to do this once.
+ // @FIXME(joostouwerling) check if the existing png struct can be reused.
+ if (decodeAsNewPNG)
+ resetPNGStruct();
+
+ // Before processing any PNG bytes, set setjmp with the current |m_png|
+ // struct. This has to be done after resetPNGStruct(), which will have
+ // replaced |m_png|.
+ if (setjmp(JMPBUF(m_png))) {
+ m_decoder->setFailed();
+ return;
+ }
+
+ // Process the png header chunks with a modified size, reflecting the size of
+ // this frame. This only needs to be done once for a progressive decode of
+ // the first frame.
+ if (decodeAsNewPNG)
+ startFrameDecoding(reader, index);
+
+ bool decodedFrameCompletely;
+ if (progressiveDecode) {
+ decodedFrameCompletely = progressivelyDecodeFirstFrame(reader);
+ // If progressive decoding processed all data for this frame, reset
+ // |m_progressiveDecodeOffset|, so |progressiveDecodingAlreadyStarted|
+ // will be false for later calls to decode frame 0.
+ if (decodedFrameCompletely)
+ m_progressiveDecodeOffset = 0;
+ } else {
+ decodeFrame(reader, index);
+ // For a non-progressive decode, we already have all the data we are
+ // going to get, so consider the frame complete.
+ decodedFrameCompletely = true;
+ }
+
+ // Send the IEND chunk if the frame is completely decoded, so the complete
+ // callback in |m_decoder| will be called.
+ if (decodedFrameCompletely)
+ endFrameDecoding();
+}
+
+void PNGImageReader::resetPNGStruct() {
+ // Each frame is processed as if it were a complete, single frame png image.
+ // To accomplish this, destroy the current |m_png| and |m_info| structs and
+ // create new ones. CRC errors are ignored, so fdAT chunks can be processed
+ // as IDATs without recalculating the CRC value.
+ png_destroy_read_struct(m_png ? &m_png : 0, m_info ? &m_info : 0, 0);
+ m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, pngFailed, 0);
+ m_info = png_create_info_struct(m_png);
+ png_set_crc_action(m_png, PNG_CRC_QUIET_USE, PNG_CRC_QUIET_USE);
+ png_set_progressive_read_fn(m_png, m_decoder, pngHeaderAvailable,
+ pngRowAvailable, pngComplete);
+}
+
+void PNGImageReader::startFrameDecoding(const FastSharedBufferReader& reader,
+ size_t index) {
+ // If the frame is the size of the whole image, we don't need to modify any
+ // data in the IHDR chunk. This means it suffices to re-process all header
+ // data up to the first frame, for mimicking a png image.
+ const IntRect& frameRect = m_frameInfo[index].frameRect;
+ if (frameRect.location() == IntPoint() &&
+ frameRect.size() == m_decoder->size()) {
+ processData(reader, m_initialOffset, m_idatOffset);
+ return;
+ }
+
+ // Process the IHDR chunk, but change the width and height so it reflects
+ // the frame's width and height. Image Decoder will apply the x,y offset.
+ // This step is omitted if the width and height are equal to the image size,
+ // which is done in the block above.
+ char readBuffer[kBufferSize];
+
+ // |headerSize| is equal to |kBufferSize|, but adds more semantic insight.
+ constexpr size_t headerSize = 33;
+ png_byte header[headerSize];
+ const png_byte* chunk =
+ readAsConstPngBytep(reader, m_initialOffset, headerSize, readBuffer);
+ memcpy(header, chunk, headerSize);
+
+ // Write the unclipped width and height. Clipping happens in the decoder.
+ png_save_uint_32(header + 16, frameRect.width());
+ png_save_uint_32(header + 20, frameRect.height());
+ png_process_data(m_png, m_info, header, headerSize);
+
+ // Process the rest of the header chunks. Start after the PNG signature and
+ // IHDR chunk, 33B, and process up to the first data chunk. The number of
+ // bytes up to the first data chunk is stored in |m_idatOffset|.
+ processData(reader, m_initialOffset + headerSize, m_idatOffset - headerSize);
+}
- m_readOffset = 0;
+// Determine if the bytes 4 to 7 of |chunk| indicate that it is a |tag| chunk.
+// - The length of |chunk| must be >= 8
+// - The length of |tag| must be = 4
+static inline bool isChunk(const png_byte* chunk, const char* tag) {
+ return memcmp(chunk + 4, tag, 4) == 0;
}
-bool PNGImageReader::decode(const SegmentReader& data, bool sizeOnly) {
- m_decodingSizeOnly = sizeOnly;
+bool PNGImageReader::progressivelyDecodeFirstFrame(
+ const FastSharedBufferReader& reader) {
+ char readBuffer[8]; // large enough to identify a chunk.
+ size_t offset = m_frameInfo[0].startOffset;
+
+ // Loop while there is enough data to do progressive decoding.
+ while (reader.size() >= offset + 8) {
+ // At the beginning of each loop, the offset is at the start of a chunk.
+ const png_byte* chunk = readAsConstPngBytep(reader, offset, 8, readBuffer);
+ const png_uint_32 length = png_get_uint_32(chunk);
+
+ // When an fcTL or IEND chunk is encountered, the frame data has ended.
+ // Return true, since all frame data is decoded.
+ if (isChunk(chunk, "fcTL") || isChunk(chunk, "IEND"))
+ return true;
+
+ // If this chunk was already decoded, move on to the next.
+ if (m_progressiveDecodeOffset >= offset + length + 12) {
+ offset += length + 12;
+ continue;
+ }
+
+ // At this point, three scenarios are possible:
+ // 1) Some bytes of this chunk were already decoded in a previous call,
+ // so we need to continue from there.
+ // 2) This is an fdAT chunk, so we need to convert it to an IDAT chunk
+ // before we can decode it.
+ // 3) This is any other chunk, most likely an IDAT chunk.
+ //
+ // In each scenario, we want to decode as much data as possible. In each
+ // one, do the scenario specific work and set |offset| to where decoding
+ // needs to continue. From there, decode until the end of the chunk, if
+ // possible. If the whole chunk is decoded, continue to the next loop.
+ // Otherwise, store how far we've come in |m_progressiveDecodeOffset| and
+ // return false to indicate to the caller that the frame is partially
+ // decoded.
+
+ size_t endOffsetChunk = offset + length + 12;
+
+ // Scenario 1: |m_progressiveDecodeOffset| is ahead of the chunk tag.
+ if (m_progressiveDecodeOffset >= offset + 8) {
+ offset = m_progressiveDecodeOffset;
+
+ // Scenario 2: we need to convert the fdAT to an IDAT chunk. For an
+ // explanation of the numbers, see the comments in decodeFrame().
+ } else if (isChunk(chunk, "fdAT")) {
+ png_byte chunkIDAT[] = {0, 0, 0, 0, 'I', 'D', 'A', 'T'};
+ png_save_uint_32(chunkIDAT, length - 4);
+ png_process_data(m_png, m_info, chunkIDAT, 8);
+ // Skip the sequence number
+ offset += 12;
+
+ // Scenario 3: for any other chunk type, process the first 8 bytes.
+ } else {
+ png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
+ offset += 8;
+ }
+
+ size_t bytesLeftInChunk = endOffsetChunk - offset;
+ size_t bytesDecoded = processData(reader, offset, bytesLeftInChunk);
+ m_progressiveDecodeOffset = offset + bytesDecoded;
+ if (bytesDecoded < bytesLeftInChunk)
+ return false;
+ offset += bytesDecoded;
+ }
+
+ return false;
+}
+
+void PNGImageReader::decodeFrame(const FastSharedBufferReader& reader,
+ size_t index) {
+ // From the frame info that was gathered during parsing, it is known at
+ // what offset the frame data starts and how many bytes are in the stream
+ // before the frame ends. Using this, we process all chunks that fall in
+ // this interval. We catch every fdAT chunk and transform it to an IDAT
+ // chunk, so libpng will decode it like a non-animated PNG image.
+ size_t offset = m_frameInfo[index].startOffset;
+ size_t endOffset = offset + m_frameInfo[index].byteLength;
+ char readBuffer[8];
+
+ while (offset < endOffset) {
+ const png_byte* chunk = readAsConstPngBytep(reader, offset, 8, readBuffer);
+ const png_uint_32 length = png_get_uint_32(chunk);
+ if (isChunk(chunk, "fdAT")) {
+ // An fdAT chunk is build up as follows:
+ // - |length| (4B)
+ // - fdAT tag (4B)
+ // - sequence number (4B)
+ // - frame data (|length| - 4B)
+ // - CRC (4B)
+ // Thus, to reformat this into an IDAT chunk, we need to:
+ // - write |length| - 4 as the new length, since the sequence number
+ // must be removed.
+ // - change the tag to IDAT.
+ // - omit the sequence number from the data part of the chunk.
+ png_byte chunkIDAT[] = {0, 0, 0, 0, 'I', 'D', 'A', 'T'};
+ png_save_uint_32(chunkIDAT, length - 4);
+ png_process_data(m_png, m_info, chunkIDAT, 8);
+ // The frame data and the CRC span |length| bytes, so skip the
+ // sequence number and process |length| bytes to decode the frame.
+ processData(reader, offset + 12, length);
+ } else {
+ png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
+ processData(reader, offset + 8, length + 4);
+ }
+ offset += 12 + length;
+ }
+}
+
+void PNGImageReader::endFrameDecoding() {
+ png_byte IEND[12] = {0, 0, 0, 0, 'I', 'E', 'N', 'D', 174, 66, 96, 130};
+ png_process_data(m_png, m_info, IEND, 12);
+}
+
+bool PNGImageReader::parse(SegmentReader& data, PNGParseQuery query) {
+ if (m_parseCompleted)
+ return true;
+
+ // |reader| is defined here to prevent memory leaks. For a detailed
+ // explanation, see the definition of |reader| in PNGImageReader::decode. In
+ // this case, both parseSize() and this method use |reader|.
+ const FastSharedBufferReader reader(&data);
+
+ // If the size has not been parsed, do that first, since it's necessary
+ // for both the Size and MetaData query. If parseSize returns false,
+ // it failed because of a lack of data so we can return false at this point.
+ if (!m_decoder->isDecodedSizeAvailable() && !parseSize(reader))
+ return false;
+
+ if (query == PNGParseQuery::PNGSizeQuery)
+ return m_decoder->isDecodedSizeAvailable();
+
+ // For non animated images (identified by no acTL chunk before the IDAT),
+ // we create one frame. This saves some processing time since we don't need
+ // to go over the stream to find chunks.
+ if (!m_isAnimated) {
+ if (m_frameInfo.isEmpty()) {
+ FrameInfo frame;
+ // This needs to be plus 8 since the first 8 bytes of the IDAT chunk
+ // are already processed in parseSize().
+ frame.startOffset = m_readOffset + 8;
+ frame.frameRect = IntRect(IntPoint(), m_decoder->size());
+ frame.duration = 0;
+ frame.alphaBlend = kAPNGAlphaBlendBgcolor;
+ frame.disposalMethod = kAPNGDisposeKeep;
+ m_frameInfo.append(frame);
+ // When the png is not animated, no extra parsing is necessary.
+ m_parseCompleted = true;
+ }
+ return true;
+ }
+
+ char readBuffer[kBufferSize];
- // We need to do the setjmp here. Otherwise bad things will happen.
if (setjmp(JMPBUF(m_png)))
return m_decoder->setFailed();
+ // At this point, the query is FrameMetaDataQuery. Loop over the data and
+ // register all frames we can find. A frame is registered on the next fcTL
+ // chunk or when the IEND chunk is found. This ensures that only complete
+ // frames are reported, unless there is an error in the stream.
+ while (reader.size() >= m_readOffset + 8) {
+ const png_byte* chunk =
+ readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
+ const size_t length = png_get_uint_32(chunk);
+
+ // When we find an IDAT chunk (when the IDAT is part of the animation),
+ // or an fdAT chunk, and the readOffset field of the newFrame is 0,
+ // we have found the beginning of a new block of frame data.
+ const bool isFrameData =
+ isChunk(chunk, "fdAT") ||
+ (isChunk(chunk, "IDAT") && m_idatIsPartOfAnimation);
+ if (m_newFrame.startOffset == 0 && isFrameData) {
+ m_newFrame.startOffset = m_readOffset;
+
+ // When the |frameInfo| vector is empty, the first frame needs to be
+ // reported as soon as possible, even before all frame data is in
+ // |data|, so the first frame can be decoded progressively.
+ if (m_frameInfo.isEmpty()) {
+ m_newFrame.byteLength = kFirstFrameIndicator;
+ m_frameInfo.append(m_newFrame);
+ }
+
+ // An fcTL or IEND marks the end of the previous frame. Thus, the
+ // FrameInfo data in m_newFrame is submitted to the m_frameInfo vector.
+ //
+ // Furthermore, an fcTL chunk indicates a new frame is coming,
+ // so the m_newFrame variable is prepared accordingly by setting the
+ // readOffset field to 0, which indicates that the frame control info
+ // is available but that we haven't seen any frame data yet.
+ } else if (isChunk(chunk, "fcTL") || isChunk(chunk, "IEND")) {
+ if (m_newFrame.startOffset != 0) {
+ m_newFrame.byteLength = m_readOffset - m_newFrame.startOffset;
+ if (m_frameInfo[0].byteLength == kFirstFrameIndicator)
+ m_frameInfo[0].byteLength = m_newFrame.byteLength;
+ else
+ m_frameInfo.append(m_newFrame);
+
+ m_newFrame.startOffset = 0;
+ }
+
+ if (reader.size() < m_readOffset + 12 + length)
+ return false;
+
+ if (isChunk(chunk, "IEND")) {
+ // The PNG image ends at the IEND chunk, so all parsing is completed.
+ m_parseCompleted = true;
+ return true;
+ }
+
+ // At this point, we're dealing with an fcTL chunk, since the above
+ // statement already returns on IEND chunks.
+
+ // If the fcTL chunk is not 26 bytes long, we can't process it.
+ if (length != 26)
+ return m_decoder->setFailed();
+
+ chunk = readAsConstPngBytep(reader, m_readOffset + 8, length, readBuffer);
+ parseFrameInfo(chunk);
+ }
+ m_readOffset += 12 + length;
+ }
+ return false;
+}
+
+// If |length| == 0, read until the stream ends.
+// @return: number of bytes processed.
+size_t PNGImageReader::processData(const FastSharedBufferReader& reader,
+ size_t offset,
+ size_t length) {
const char* segment;
- while (size_t segmentLength = data.getSomeData(segment, m_readOffset)) {
- m_readOffset += segmentLength;
- m_currentBufferSize = m_readOffset;
+ size_t totalProcessedBytes = 0;
+ while (reader.size() > offset) {
+ size_t segmentLength = reader.getSomeData(segment, offset);
+ if (length > 0 && segmentLength + totalProcessedBytes > length)
+ segmentLength = length - totalProcessedBytes;
+
png_process_data(m_png, m_info,
- reinterpret_cast<png_bytep>(const_cast<char*>(segment)),
+ reinterpret_cast<png_byte*>(const_cast<char*>(segment)),
segmentLength);
- if (sizeOnly ? m_decoder->isDecodedSizeAvailable()
- : m_decoder->frameIsCompleteAtIndex(0))
+ offset += segmentLength;
+ totalProcessedBytes += segmentLength;
+ if (totalProcessedBytes == length)
+ return length;
+ }
+ return totalProcessedBytes;
+}
+
+// This methods reads through the stream until it has parsed the image size.
+// @return true when it succeeds in parsing the size.
+// false when:
+// A) not enough data is provided
+// B) decoding by libpng fails. In the this case, it will also call
+// setFailed on m_decoder.
+bool PNGImageReader::parseSize(const FastSharedBufferReader& reader) {
+ char readBuffer[kBufferSize];
+
+ if (setjmp(JMPBUF(m_png)))
+ return m_decoder->setFailed();
+
+ // Process the PNG signature and the IHDR with libpng, such that this code
+ // does not need to parse the contents. This also enables the reader to use
+ // the existing headerAvailable callback in the decoder.
+ //
+ // When we already have decoded the signature, we don't need to do it again.
+ // By setting a flag for this we allow for byte by byte parsing.
+ if (!m_parsedSignature) {
+ if (reader.size() < m_readOffset + 8)
+ return false;
+
+ const png_byte* chunk =
+ readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
+ png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
+ m_readOffset += 8;
+ m_parsedSignature = true;
+ // Initialize the newFrame by setting the readOffset to 0.
+ m_newFrame.startOffset = 0;
+ }
+
+ // This loop peeks at the chunk tag until the IDAT chunk is found. When
+ // a different tag is encountered, pass it on to libpng for general parsing.
+ // We can peek at chunks by looking at the first 8 bytes, which contain the
+ // length and the chunk tag.
+ //
+ // When an fcTL (frame control) is encountered before the IDAT, the frame
+ // data in the IDAT chunk is part of the animation. This case is flagged
+ // and the frame info is stored by parsing the fcTL chunk.
+ while (reader.size() >= m_readOffset + 8) {
+ const png_byte* chunk =
+ readAsConstPngBytep(reader, m_readOffset, 8, readBuffer);
+ const png_uint_32 length = png_get_uint_32(chunk);
+
+ // If we encounter the IDAT chunk, we're done with the png header
+ // chunks. Indicate this to libpng by sending the beginning of the IDAT
+ // chunk, which will trigger libpng to call the headerAvailable
+ // callback on m_decoder. This provides the size to the decoder.
+ if (isChunk(chunk, "IDAT")) {
+ m_idatOffset = m_readOffset;
+ png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
return true;
+ }
+
+ // Consider the PNG image animated if an acTL chunk of the correct
+ // length is present. Parsing the acTL content is done by
+ // parseAnimationControl, called by libpng's png_process_data.
+ if (isChunk(chunk, "acTL") && length == 8)
+ m_isAnimated = true;
+
+ // We don't need to check for |length| here, because the decoder will
+ // fail later on for invalid fcTL chunks.
+ else if (isChunk(chunk, "fcTL"))
+ m_idatIsPartOfAnimation = true;
+
+ // 12 is the length, tag and crc part of the chunk, which are all 4B.
+ if (reader.size() < m_readOffset + length + 12)
+ break;
+
+ png_process_data(m_png, m_info, const_cast<png_byte*>(chunk), 8);
+ processData(reader, m_readOffset + 8, length + 4);
+ m_readOffset += length + 12;
}
+ // If we end up here, not enough data was available for the IDAT chunk
+ // So libpng would not have called headerAvailable yet.
return false;
}
-} // namespace blink
+void PNGImageReader::parseAnimationChunk(const char tag[],
+ const void* dataChunk,
+ size_t length) {
+ const png_byte* data = static_cast<const png_byte*>(dataChunk);
+
+ // The number of frames as indicated in the animation control chunk (acTL)
+ // is ignored, and the number of frames that are actually present is used.
+ // For now, when the number of indicated frames is different from the
+ // number of supplied frames, the number of supplied frames is what is
+ // provided to the decoder. Therefore, it does not add any benefit of
+ // looking at the value of the indicated framecount. A note here is that
+ // there may be optimisations available, for example, prescaling vectors.
+ if (strcmp(tag, "acTL") == 0 && length == 8) {
+ png_uint_32 repetitionCount = png_get_uint_32(data + 4);
+ m_decoder->setRepetitionCount(repetitionCount);
+
+ // For fcTL, decoding fails if it does not have the correct length. It is
+ // impossible to make a guess about the frame if not all data is available.
+ // Use longjmp to get back to parse(), which is necessary since this method
+ // is called by a libpng callback.
+ } else if (strcmp(tag, "fcTL") == 0) {
+ if (length != 26)
+ longjmp(JMPBUF(m_png), 1);
+ parseFrameInfo(data);
+ }
+}
+
+bool PNGImageReader::firstFrameFullyReceived() const {
+ DCHECK_GT(m_frameInfo.size(), 0u);
+ return m_frameInfo[0].byteLength != kFirstFrameIndicator;
+}
+
+void PNGImageReader::clearDecodeState(size_t frameIndex) {
+ if (frameIndex == 0)
+ m_progressiveDecodeOffset = 0;
+}
+
+size_t PNGImageReader::frameCount() const {
+ return m_frameInfo.size();
+}
+
+const PNGImageReader::FrameInfo& PNGImageReader::frameInfo(size_t index) const {
+ DCHECK(index < m_frameInfo.size());
+ return m_frameInfo[index];
+}
+
+// Extract the frame control info and store it in m_newFrame. The length check
+// on the data chunk has been done in parseAnimationChunk.
+// The fcTL specification used can be found at:
+// https://wiki.mozilla.org/APNG_Specification#.60fcTL.60:_The_Frame_Control_Chunk
+void PNGImageReader::parseFrameInfo(const png_byte* data) {
+ png_uint_32 width, height, xOffset, yOffset;
+ png_uint_16 delayNumerator, delayDenominator;
+ width = png_get_uint_32(data + 4);
+ height = png_get_uint_32(data + 8);
+ xOffset = png_get_uint_32(data + 12);
+ yOffset = png_get_uint_32(data + 16);
+ delayNumerator = png_get_uint_16(data + 20);
+ delayDenominator = png_get_uint_16(data + 22);
+
+ m_newFrame.duration = (delayDenominator == 0)
+ ? delayNumerator * 10
+ : delayNumerator * 1000 / delayDenominator;
+ m_newFrame.frameRect = IntRect(xOffset, yOffset, width, height);
+ m_newFrame.disposalMethod = data[24];
+ m_newFrame.alphaBlend = data[25];
+}
+
+}; // namespace blink
« no previous file with comments | « third_party/WebKit/Source/platform/image-decoders/png/PNGImageReader.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698