Home | History | Annotate | Download | only in gif
      1 /*
      2  * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions
      6  * are met:
      7  * 1. Redistributions of source code must retain the above copyright
      8  *    notice, this list of conditions and the following disclaimer.
      9  * 2. Redistributions in binary form must reproduce the above copyright
     10  *    notice, this list of conditions and the following disclaimer in the
     11  *    documentation and/or other materials provided with the distribution.
     12  *
     13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
     14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     24  */
     25 
     26 #include "config.h"
     27 #include "platform/image-decoders/gif/GIFImageDecoder.h"
     28 
     29 #include <limits>
     30 #include "platform/PlatformInstrumentation.h"
     31 #include "platform/image-decoders/gif/GIFImageReader.h"
     32 #include "wtf/NotFound.h"
     33 #include "wtf/PassOwnPtr.h"
     34 
     35 namespace blink {
     36 
     37 GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
     38     ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
     39     size_t maxDecodedBytes)
     40     : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
     41     , m_repetitionCount(cAnimationLoopOnce)
     42 {
     43 }
     44 
     45 GIFImageDecoder::~GIFImageDecoder()
     46 {
     47 }
     48 
     49 void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
     50 {
     51     if (failed())
     52         return;
     53 
     54     ImageDecoder::setData(data, allDataReceived);
     55     if (m_reader)
     56         m_reader->setData(data);
     57 }
     58 
     59 bool GIFImageDecoder::isSizeAvailable()
     60 {
     61     if (!ImageDecoder::isSizeAvailable())
     62         parse(GIFSizeQuery);
     63 
     64     return ImageDecoder::isSizeAvailable();
     65 }
     66 
     67 size_t GIFImageDecoder::frameCount()
     68 {
     69     parse(GIFFrameCountQuery);
     70     return m_frameBufferCache.size();
     71 }
     72 
     73 int GIFImageDecoder::repetitionCount() const
     74 {
     75     // This value can arrive at any point in the image data stream.  Most GIFs
     76     // in the wild declare it near the beginning of the file, so it usually is
     77     // set by the time we've decoded the size, but (depending on the GIF and the
     78     // packets sent back by the webserver) not always.  If the reader hasn't
     79     // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
     80     // should default to looping once (the initial value for
     81     // |m_repetitionCount|).
     82     //
     83     // There are some additional wrinkles here. First, ImageSource::clear()
     84     // may destroy the reader, making the result from the reader _less_
     85     // authoritative on future calls if the recreated reader hasn't seen the
     86     // loop count.  We don't need to special-case this because in this case the
     87     // new reader will once again return cLoopCountNotSeen, and we won't
     88     // overwrite the cached correct value.
     89     //
     90     // Second, a GIF might never set a loop count at all, in which case we
     91     // should continue to treat it as a "loop once" animation.  We don't need
     92     // special code here either, because in this case we'll never change
     93     // |m_repetitionCount| from its default value.
     94     //
     95     // Third, we use the same GIFImageReader for counting frames and we might
     96     // see the loop count and then encounter a decoding error which happens
     97     // later in the stream. It is also possible that no frames are in the
     98     // stream. In these cases we should just loop once.
     99     if (isAllDataReceived() && parseCompleted() && m_reader->imagesCount() == 1)
    100         m_repetitionCount = cAnimationNone;
    101     else if (failed() || (m_reader && (!m_reader->imagesCount())))
    102         m_repetitionCount = cAnimationLoopOnce;
    103     else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
    104         m_repetitionCount = m_reader->loopCount();
    105     return m_repetitionCount;
    106 }
    107 
    108 ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
    109 {
    110     if (index >= frameCount())
    111         return 0;
    112 
    113     ImageFrame& frame = m_frameBufferCache[index];
    114     if (frame.status() != ImageFrame::FrameComplete) {
    115         PlatformInstrumentation::willDecodeImage("GIF");
    116         decode(index);
    117         PlatformInstrumentation::didDecodeImage();
    118     }
    119 
    120     frame.notifyBitmapIfPixelsChanged();
    121     return &frame;
    122 }
    123 
    124 bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const
    125 {
    126     return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete();
    127 }
    128 
    129 float GIFImageDecoder::frameDurationAtIndex(size_t index) const
    130 {
    131     return (m_reader && (index < m_reader->imagesCount()) &&
    132         m_reader->frameContext(index)->isHeaderDefined()) ?
    133         m_reader->frameContext(index)->delayTime() : 0;
    134 }
    135 
    136 bool GIFImageDecoder::setFailed()
    137 {
    138     m_reader.clear();
    139     return ImageDecoder::setFailed();
    140 }
    141 
    142 bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, GIFRow::const_iterator rowBegin, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
    143 {
    144     const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
    145     // The pixel data and coordinates supplied to us are relative to the frame's
    146     // origin within the entire image size, i.e.
    147     // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
    148     // that width == (size().width() - frameContext->xOffset), so
    149     // we must ensure we don't run off the end of either the source data or the
    150     // row's X-coordinates.
    151     const int xBegin = frameContext->xOffset();
    152     const int yBegin = frameContext->yOffset() + rowNumber;
    153     const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width), size().width());
    154     const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount), size().height());
    155     if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
    156         return true;
    157 
    158     const GIFColorMap::Table& colorTable = frameContext->localColorMap().isDefined() ? frameContext->localColorMap().table() : m_reader->globalColorMap().table();
    159 
    160     if (colorTable.isEmpty())
    161         return true;
    162 
    163     GIFColorMap::Table::const_iterator colorTableIter = colorTable.begin();
    164 
    165     // Initialize the frame if necessary.
    166     ImageFrame& buffer = m_frameBufferCache[frameIndex];
    167     if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
    168         return false;
    169 
    170     const size_t transparentPixel = frameContext->transparentPixel();
    171     GIFRow::const_iterator rowEnd = rowBegin + (xEnd - xBegin);
    172     ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
    173 
    174     // We may or may not need to write transparent pixels to the buffer.
    175     // If we're compositing against a previous image, it's wrong, and if
    176     // we're writing atop a cleared, fully transparent buffer, it's
    177     // unnecessary; but if we're decoding an interlaced gif and
    178     // displaying it "Haeberli"-style, we must write these for passes
    179     // beyond the first, or the initial passes will "show through" the
    180     // later ones.
    181     //
    182     // The loops below are almost identical. One writes a transparent pixel
    183     // and one doesn't based on the value of |writeTransparentPixels|.
    184     // The condition check is taken out of the loop to enhance performance.
    185     // This optimization reduces decoding time by about 15% for a 3MB image.
    186     if (writeTransparentPixels) {
    187         for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
    188             const size_t sourceValue = *rowBegin;
    189             if ((sourceValue != transparentPixel) && (sourceValue < colorTable.size())) {
    190                 *currentAddress = colorTableIter[sourceValue];
    191             } else {
    192                 *currentAddress = 0;
    193                 m_currentBufferSawAlpha = true;
    194             }
    195         }
    196     } else {
    197         for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
    198             const size_t sourceValue = *rowBegin;
    199             if ((sourceValue != transparentPixel) && (sourceValue < colorTable.size()))
    200                 *currentAddress = colorTableIter[sourceValue];
    201             else
    202                 m_currentBufferSawAlpha = true;
    203         }
    204     }
    205 
    206     // Tell the frame to copy the row data if need be.
    207     if (repeatCount > 1)
    208         buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);
    209 
    210     buffer.setPixelsChanged(true);
    211     return true;
    212 }
    213 
    214 bool GIFImageDecoder::parseCompleted() const
    215 {
    216     return m_reader && m_reader->parseCompleted();
    217 }
    218 
    219 bool GIFImageDecoder::frameComplete(size_t frameIndex)
    220 {
    221     // Initialize the frame if necessary.  Some GIFs insert do-nothing frames,
    222     // in which case we never reach haveDecodedRow() before getting here.
    223     ImageFrame& buffer = m_frameBufferCache[frameIndex];
    224     if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
    225         return false; // initFrameBuffer() has already called setFailed().
    226 
    227     buffer.setStatus(ImageFrame::FrameComplete);
    228 
    229     if (!m_currentBufferSawAlpha) {
    230         // The whole frame was non-transparent, so it's possible that the entire
    231         // resulting buffer was non-transparent, and we can setHasAlpha(false).
    232         if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
    233             buffer.setHasAlpha(false);
    234             buffer.setRequiredPreviousFrameIndex(kNotFound);
    235         } else if (buffer.requiredPreviousFrameIndex() != kNotFound) {
    236             // Tricky case.  This frame does not have alpha only if everywhere
    237             // outside its rect doesn't have alpha.  To know whether this is
    238             // true, we check the start state of the frame -- if it doesn't have
    239             // alpha, we're safe.
    240             const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()];
    241             ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious);
    242 
    243             // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
    244             // we can say we have no alpha if that frame had no alpha.  But
    245             // since in initFrameBuffer() we already copied that frame's alpha
    246             // state into the current frame's, we need do nothing at all here.
    247             //
    248             // The only remaining case is a DisposeOverwriteBgcolor frame.  If
    249             // it had no alpha, and its rect is contained in the current frame's
    250             // rect, we know the current frame has no alpha.
    251             if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
    252                 buffer.setHasAlpha(false);
    253         }
    254     }
    255 
    256     return true;
    257 }
    258 
    259 size_t GIFImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
    260 {
    261     // We need to preserve frames such that:
    262     //  1. We don't clear |clearExceptFrame|;
    263     //  2. We don't clear any frame from which a future initFrameBuffer() call
    264     //     will copy bitmap data.
    265     // All other frames can be cleared.
    266     while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() == ImageFrame::FrameEmpty))
    267         clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
    268 
    269     return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
    270 }
    271 
    272 void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
    273 {
    274     if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
    275         // Reset the state of the partial frame in the reader so that the frame
    276         // can be decoded again when requested.
    277         m_reader->clearDecodeState(frameIndex);
    278     }
    279     ImageDecoder::clearFrameBuffer(frameIndex);
    280 }
    281 
    282 void GIFImageDecoder::parse(GIFParseQuery query)
    283 {
    284     if (failed())
    285         return;
    286 
    287     if (!m_reader) {
    288         m_reader = adoptPtr(new GIFImageReader(this));
    289         m_reader->setData(m_data);
    290     }
    291 
    292     if (!m_reader->parse(query)) {
    293         setFailed();
    294         return;
    295     }
    296 
    297     const size_t oldSize = m_frameBufferCache.size();
    298     m_frameBufferCache.resize(m_reader->imagesCount());
    299 
    300     for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) {
    301         ImageFrame& buffer = m_frameBufferCache[i];
    302         const GIFFrameContext* frameContext = m_reader->frameContext(i);
    303         buffer.setPremultiplyAlpha(m_premultiplyAlpha);
    304         buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i, false));
    305         buffer.setDuration(frameContext->delayTime());
    306         buffer.setDisposalMethod(frameContext->disposalMethod());
    307 
    308         // Initialize the frame rect in our buffer.
    309         IntRect frameRect = frameContext->frameRect();
    310 
    311         // Make sure the frameRect doesn't extend outside the buffer.
    312         if (frameRect.maxX() > size().width())
    313             frameRect.setWidth(size().width() - frameRect.x());
    314         if (frameRect.maxY() > size().height())
    315             frameRect.setHeight(size().height() - frameRect.y());
    316 
    317         buffer.setOriginalFrameRect(frameRect);
    318     }
    319 }
    320 
    321 void GIFImageDecoder::decode(size_t frameIndex)
    322 {
    323     parse(GIFFrameCountQuery);
    324 
    325     if (failed())
    326         return;
    327 
    328     Vector<size_t> framesToDecode;
    329     size_t frameToDecode = frameIndex;
    330     do {
    331         framesToDecode.append(frameToDecode);
    332         frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
    333     } while (frameToDecode != kNotFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);
    334 
    335     for (size_t i = framesToDecode.size(); i > 0; --i) {
    336         size_t frameIndex = framesToDecode[i - 1];
    337         if (!m_reader->decode(frameIndex)) {
    338             setFailed();
    339             return;
    340         }
    341 
    342         // We need more data to continue decoding.
    343         if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
    344             break;
    345     }
    346 
    347     // It is also a fatal error if all data is received and we have decoded all
    348     // frames available but the file is truncated.
    349     if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted())
    350         setFailed();
    351 }
    352 
    353 bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
    354 {
    355     // Initialize the frame rect in our buffer.
    356     ImageFrame* const buffer = &m_frameBufferCache[frameIndex];
    357 
    358     size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
    359     if (requiredPreviousFrameIndex == kNotFound) {
    360         // This frame doesn't rely on any previous data.
    361         if (!buffer->setSize(size().width(), size().height()))
    362             return setFailed();
    363     } else {
    364         const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
    365         ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);
    366 
    367         // Preserve the last frame as the starting state for this frame.
    368         if (!buffer->copyBitmapData(*prevBuffer))
    369             return setFailed();
    370 
    371         if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
    372             // We want to clear the previous frame to transparent, without
    373             // affecting pixels in the image outside of the frame.
    374             const IntRect& prevRect = prevBuffer->originalFrameRect();
    375             ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
    376             buffer->zeroFillFrameRect(prevRect);
    377         }
    378     }
    379 
    380     // Update our status to be partially complete.
    381     buffer->setStatus(ImageFrame::FramePartial);
    382 
    383     // Reset the alpha pixel tracker for this frame.
    384     m_currentBufferSawAlpha = false;
    385     return true;
    386 }
    387 
    388 } // namespace blink
    389