1/*
2 * Copyright (C) 2006 Apple 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 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 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 "GIFImageDecoder.h"
28
29#include "GIFImageReader.h"
30#include <limits>
31#include <wtf/PassOwnPtr.h>
32
33namespace WebCore {
34
35GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
36                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
37    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
38    , m_repetitionCount(cAnimationLoopOnce)
39{
40}
41
42GIFImageDecoder::~GIFImageDecoder()
43{
44}
45
46void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
47{
48    if (failed())
49        return;
50
51    ImageDecoder::setData(data, allDataReceived);
52    if (m_reader)
53        m_reader->setData(data);
54}
55
56bool GIFImageDecoder::isSizeAvailable()
57{
58    if (!ImageDecoder::isSizeAvailable())
59         decode(0, GIFSizeQuery);
60
61    return ImageDecoder::isSizeAvailable();
62}
63
64bool GIFImageDecoder::setSize(unsigned width, unsigned height)
65{
66    if (ImageDecoder::isSizeAvailable() && size() == IntSize(width, height))
67        return true;
68
69    if (!ImageDecoder::setSize(width, height))
70        return false;
71
72    prepareScaleDataIfNecessary();
73    return true;
74}
75
76size_t GIFImageDecoder::frameCount()
77{
78    decode(std::numeric_limits<unsigned>::max(), GIFFrameCountQuery);
79    return m_frameBufferCache.size();
80}
81
82int GIFImageDecoder::repetitionCount() const
83{
84    // This value can arrive at any point in the image data stream.  Most GIFs
85    // in the wild declare it near the beginning of the file, so it usually is
86    // set by the time we've decoded the size, but (depending on the GIF and the
87    // packets sent back by the webserver) not always.  If the reader hasn't
88    // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
89    // should default to looping once (the initial value for
90    // |m_repetitionCount|).
91    //
92    // There are some additional wrinkles here. First, ImageSource::clear()
93    // may destroy the reader, making the result from the reader _less_
94    // authoritative on future calls if the recreated reader hasn't seen the
95    // loop count.  We don't need to special-case this because in this case the
96    // new reader will once again return cLoopCountNotSeen, and we won't
97    // overwrite the cached correct value.
98    //
99    // Second, a GIF might never set a loop count at all, in which case we
100    // should continue to treat it as a "loop once" animation.  We don't need
101    // special code here either, because in this case we'll never change
102    // |m_repetitionCount| from its default value.
103    //
104    // Third, we use the same GIFImageReader for counting frames and we might
105    // see the loop count and then encounter a decoding error which happens
106    // later in the stream. It is also possible that no frames are in the
107    // stream. In these cases we should just loop once.
108    if (failed() || (m_reader && (!m_reader->imagesCount())))
109        m_repetitionCount = cAnimationLoopOnce;
110    else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
111        m_repetitionCount = m_reader->loopCount();
112    return m_repetitionCount;
113}
114
115ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
116{
117    if (index >= frameCount())
118        return 0;
119
120    ImageFrame& frame = m_frameBufferCache[index];
121    if (frame.status() != ImageFrame::FrameComplete)
122        decode(index + 1, GIFFullQuery);
123    return &frame;
124}
125
126bool GIFImageDecoder::setFailed()
127{
128    m_reader.clear();
129    return ImageDecoder::setFailed();
130}
131
132void GIFImageDecoder::clearFrameBufferCache(size_t clearBeforeFrame)
133{
134    // In some cases, like if the decoder was destroyed while animating, we
135    // can be asked to clear more frames than we currently have.
136    if (m_frameBufferCache.isEmpty())
137        return; // Nothing to do.
138
139    // The "-1" here is tricky.  It does not mean that |clearBeforeFrame| is the
140    // last frame we wish to preserve, but rather that we never want to clear
141    // the very last frame in the cache: it's empty (so clearing it is
142    // pointless), it's partial (so we don't want to clear it anyway), or the
143    // cache could be enlarged with a future setData() call and it could be
144    // needed to construct the next frame (see comments below).  Callers can
145    // always use ImageSource::clear(true, ...) to completely free the memory in
146    // this case.
147    clearBeforeFrame = std::min(clearBeforeFrame, m_frameBufferCache.size() - 1);
148    const Vector<ImageFrame>::iterator end(m_frameBufferCache.begin() + clearBeforeFrame);
149
150    // We need to preserve frames such that:
151    //   * We don't clear |end|
152    //   * We don't clear the frame we're currently decoding
153    //   * We don't clear any frame from which a future initFrameBuffer() call
154    //     will copy bitmap data
155    // All other frames can be cleared.  Because of the constraints on when
156    // ImageSource::clear() can be called (see ImageSource.h), we're guaranteed
157    // not to have non-empty frames after the frame we're currently decoding.
158    // So, scan backwards from |end| as follows:
159    //   * If the frame is empty, we're still past any frames we care about.
160    //   * If the frame is complete, but is DisposeOverwritePrevious, we'll
161    //     skip over it in future initFrameBuffer() calls.  We can clear it
162    //     unless it's |end|, and keep scanning.  For any other disposal method,
163    //     stop scanning, as we've found the frame initFrameBuffer() will need
164    //     next.
165    //   * If the frame is partial, we're decoding it, so don't clear it; if it
166    //     has a disposal method other than DisposeOverwritePrevious, stop
167    //     scanning, as we'll only need this frame when decoding the next one.
168    Vector<ImageFrame>::iterator i(end);
169    for (; (i != m_frameBufferCache.begin()) && ((i->status() == ImageFrame::FrameEmpty) || (i->disposalMethod() == ImageFrame::DisposeOverwritePrevious)); --i) {
170        if ((i->status() == ImageFrame::FrameComplete) && (i != end))
171            i->clearPixelData();
172    }
173
174    // Now |i| holds the last frame we need to preserve; clear prior frames.
175    for (Vector<ImageFrame>::iterator j(m_frameBufferCache.begin()); j != i; ++j) {
176        ASSERT(j->status() != ImageFrame::FramePartial);
177        if (j->status() != ImageFrame::FrameEmpty)
178            j->clearPixelData();
179    }
180}
181
182bool GIFImageDecoder::haveDecodedRow(unsigned frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
183{
184    const GIFFrameContext* frameContext = m_reader->frameContext();
185    // The pixel data and coordinates supplied to us are relative to the frame's
186    // origin within the entire image size, i.e.
187    // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
188    // that width == (size().width() - frameContext->xOffset), so
189    // we must ensure we don't run off the end of either the source data or the
190    // row's X-coordinates.
191    int xBegin = upperBoundScaledX(frameContext->xOffset);
192    int yBegin = upperBoundScaledY(frameContext->yOffset + rowNumber);
193    int xEnd = lowerBoundScaledX(std::min(static_cast<int>(frameContext->xOffset + width), size().width()) - 1, xBegin + 1) + 1;
194    int yEnd = lowerBoundScaledY(std::min(static_cast<int>(frameContext->yOffset + rowNumber + repeatCount), size().height()) - 1, yBegin + 1) + 1;
195    if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
196        return true;
197
198    // Get the colormap.
199    const unsigned char* colorMap;
200    unsigned colorMapSize;
201    if (frameContext->isLocalColormapDefined) {
202        colorMap = m_reader->localColormap(frameContext);
203        colorMapSize = m_reader->localColormapSize(frameContext);
204    } else {
205        colorMap = m_reader->globalColormap();
206        colorMapSize = m_reader->globalColormapSize();
207    }
208    if (!colorMap)
209        return true;
210
211    // Initialize the frame if necessary.
212    ImageFrame& buffer = m_frameBufferCache[frameIndex];
213    if (((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) || !buffer.hasPixelData())
214        return false;
215
216    ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
217    // Write one row's worth of data into the frame.
218    for (int x = xBegin; x < xEnd; ++x) {
219        const unsigned char sourceValue = rowBuffer[(m_scaled ? m_scaledColumns[x] : x) - frameContext->xOffset];
220        if ((!frameContext->isTransparent || (sourceValue != frameContext->tpixel)) && (sourceValue < colorMapSize)) {
221            const size_t colorIndex = static_cast<size_t>(sourceValue) * 3;
222            buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255);
223        } else {
224            m_currentBufferSawAlpha = true;
225            // We may or may not need to write transparent pixels to the buffer.
226            // If we're compositing against a previous image, it's wrong, and if
227            // we're writing atop a cleared, fully transparent buffer, it's
228            // unnecessary; but if we're decoding an interlaced gif and
229            // displaying it "Haeberli"-style, we must write these for passes
230            // beyond the first, or the initial passes will "show through" the
231            // later ones.
232            if (writeTransparentPixels)
233                buffer.setRGBA(currentAddress, 0, 0, 0, 0);
234        }
235        ++currentAddress;
236    }
237
238    // Tell the frame to copy the row data if need be.
239    if (repeatCount > 1)
240        buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);
241
242    return true;
243}
244
245bool GIFImageDecoder::frameComplete(unsigned frameIndex, unsigned frameDuration, ImageFrame::FrameDisposalMethod disposalMethod)
246{
247    // Initialize the frame if necessary.  Some GIFs insert do-nothing frames,
248    // in which case we never reach haveDecodedRow() before getting here.
249    ImageFrame& buffer = m_frameBufferCache[frameIndex];
250    if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
251        return false; // initFrameBuffer() has already called setFailed().
252
253    buffer.setStatus(ImageFrame::FrameComplete);
254    buffer.setDuration(frameDuration);
255    buffer.setDisposalMethod(disposalMethod);
256
257    if (!m_currentBufferSawAlpha) {
258        // The whole frame was non-transparent, so it's possible that the entire
259        // resulting buffer was non-transparent, and we can setHasAlpha(false).
260        if (buffer.originalFrameRect().contains(IntRect(IntPoint(), scaledSize())))
261            buffer.setHasAlpha(false);
262        else if (frameIndex) {
263            // Tricky case.  This frame does not have alpha only if everywhere
264            // outside its rect doesn't have alpha.  To know whether this is
265            // true, we check the start state of the frame -- if it doesn't have
266            // alpha, we're safe.
267            //
268            // First skip over prior DisposeOverwritePrevious frames (since they
269            // don't affect the start state of this frame) the same way we do in
270            // initFrameBuffer().
271            const ImageFrame* prevBuffer = &m_frameBufferCache[--frameIndex];
272            while (frameIndex && (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwritePrevious))
273                prevBuffer = &m_frameBufferCache[--frameIndex];
274
275            // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
276            // we can say we have no alpha if that frame had no alpha.  But
277            // since in initFrameBuffer() we already copied that frame's alpha
278            // state into the current frame's, we need do nothing at all here.
279            //
280            // The only remaining case is a DisposeOverwriteBgcolor frame.  If
281            // it had no alpha, and its rect is contained in the current frame's
282            // rect, we know the current frame has no alpha.
283            if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
284                buffer.setHasAlpha(false);
285        }
286    }
287
288    return true;
289}
290
291void GIFImageDecoder::gifComplete()
292{
293    // Cache the repetition count, which is now as authoritative as it's ever
294    // going to be.
295    repetitionCount();
296
297    m_reader.clear();
298}
299
300void GIFImageDecoder::decode(unsigned haltAtFrame, GIFQuery query)
301{
302    if (failed())
303        return;
304
305    if (!m_reader) {
306        m_reader = adoptPtr(new GIFImageReader(this));
307        m_reader->setData(m_data);
308    }
309
310    if (query == GIFSizeQuery) {
311        if (!m_reader->decode(GIFSizeQuery, haltAtFrame))
312            setFailed();
313        return;
314    }
315
316    if (!m_reader->decode(GIFFrameCountQuery, haltAtFrame)) {
317        setFailed();
318        return;
319    }
320
321    const size_t oldSize = m_frameBufferCache.size();
322    m_frameBufferCache.resize(m_reader->imagesCount());
323    for (size_t i = oldSize; i < m_reader->imagesCount(); ++i)
324        m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
325
326    if (query == GIFFrameCountQuery)
327        return;
328
329    if (!m_reader->decode(GIFFullQuery, haltAtFrame)) {
330        setFailed();
331        return;
332    }
333
334    // It is also a fatal error if all data is received but we failed to decode
335    // all frames completely.
336    if (isAllDataReceived() && haltAtFrame >= m_frameBufferCache.size() && m_reader)
337        setFailed();
338}
339
340bool GIFImageDecoder::initFrameBuffer(unsigned frameIndex)
341{
342    // Initialize the frame rect in our buffer.
343    const GIFFrameContext* frameContext = m_reader->frameContext();
344    IntRect frameRect(frameContext->xOffset, frameContext->yOffset, frameContext->width, frameContext->height);
345
346    // Make sure the frameRect doesn't extend outside the buffer.
347    if (frameRect.maxX() > size().width())
348        frameRect.setWidth(size().width() - frameContext->xOffset);
349    if (frameRect.maxY() > size().height())
350        frameRect.setHeight(size().height() - frameContext->yOffset);
351
352    ImageFrame* const buffer = &m_frameBufferCache[frameIndex];
353    int left = upperBoundScaledX(frameRect.x());
354    int right = lowerBoundScaledX(frameRect.maxX(), left);
355    int top = upperBoundScaledY(frameRect.y());
356    int bottom = lowerBoundScaledY(frameRect.maxY(), top);
357    buffer->setOriginalFrameRect(IntRect(left, top, right - left, bottom - top));
358
359    if (!frameIndex) {
360        // This is the first frame, so we're not relying on any previous data.
361        if (!buffer->setSize(scaledSize().width(), scaledSize().height()))
362            return setFailed();
363    } else {
364        // The starting state for this frame depends on the previous frame's
365        // disposal method.
366        //
367        // Frames that use the DisposeOverwritePrevious method are effectively
368        // no-ops in terms of changing the starting state of a frame compared to
369        // the starting state of the previous frame, so skip over them.  (If the
370        // first frame specifies this method, it will get treated like
371        // DisposeOverwriteBgcolor below and reset to a completely empty image.)
372        const ImageFrame* prevBuffer = &m_frameBufferCache[--frameIndex];
373        ImageFrame::FrameDisposalMethod prevMethod = prevBuffer->disposalMethod();
374        while (frameIndex && (prevMethod == ImageFrame::DisposeOverwritePrevious)) {
375            prevBuffer = &m_frameBufferCache[--frameIndex];
376            prevMethod = prevBuffer->disposalMethod();
377        }
378        ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);
379
380        if ((prevMethod == ImageFrame::DisposeNotSpecified) || (prevMethod == ImageFrame::DisposeKeep)) {
381            // Preserve the last frame as the starting state for this frame.
382            if (!buffer->copyBitmapData(*prevBuffer))
383                return setFailed();
384        } else {
385            // We want to clear the previous frame to transparent, without
386            // affecting pixels in the image outside of the frame.
387            const IntRect& prevRect = prevBuffer->originalFrameRect();
388            const IntSize& bufferSize = scaledSize();
389            if (!frameIndex || prevRect.contains(IntRect(IntPoint(), scaledSize()))) {
390                // Clearing the first frame, or a frame the size of the whole
391                // image, results in a completely empty image.
392                if (!buffer->setSize(bufferSize.width(), bufferSize.height()))
393                    return setFailed();
394            } else {
395                // Copy the whole previous buffer, then clear just its frame.
396                if (!buffer->copyBitmapData(*prevBuffer))
397                    return setFailed();
398                buffer->zeroFillFrameRect(prevRect);
399            }
400        }
401    }
402
403    // Update our status to be partially complete.
404    buffer->setStatus(ImageFrame::FramePartial);
405
406    // Reset the alpha pixel tracker for this frame.
407    m_currentBufferSawAlpha = false;
408    return true;
409}
410
411} // namespace WebCore
412