~ubuntu-branches/ubuntu/raring/qtwebkit-source/raring-proposed

« back to all changes in this revision

Viewing changes to Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell
  • Date: 2013-02-18 14:24:18 UTC
  • Revision ID: package-import@ubuntu.com-20130218142418-eon0jmjg3nj438uy
Tags: upstream-2.3
ImportĀ upstreamĀ versionĀ 2.3

Show diffs side-by-side

added added

removed removed

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