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