2 * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "GIFImageDecoder.h"
28 #include "GIFImageReader.h"
30 #if PLATFORM(CAIRO) || PLATFORM(QT) || PLATFORM(WX)
34 class GIFImageDecoderPrivate
37 GIFImageDecoderPrivate(GIFImageDecoder* decoder = 0)
43 ~GIFImageDecoderPrivate()
48 bool decode(const Vector<char>& data,
49 GIFImageDecoder::GIFQuery query = GIFImageDecoder::GIFFullQuery,
50 unsigned int haltFrame = -1)
52 return m_reader.read((const unsigned char*)data.data() + m_readOffset, data.size() - m_readOffset,
57 unsigned frameCount() const { return m_reader.images_count; }
58 int repetitionCount() const { return m_reader.loop_count; }
60 void setReadOffset(unsigned o) { m_readOffset = o; }
62 bool isTransparent() const { return m_reader.frame_reader->is_transparent; }
64 void getColorMap(unsigned char*& map, unsigned& size) const {
65 if (m_reader.frame_reader->is_local_colormap_defined) {
66 map = m_reader.frame_reader->local_colormap;
67 size = (unsigned)m_reader.frame_reader->local_colormap_size;
69 map = m_reader.global_colormap;
70 size = m_reader.global_colormap_size;
74 unsigned frameXOffset() const { return m_reader.frame_reader->x_offset; }
75 unsigned frameYOffset() const { return m_reader.frame_reader->y_offset; }
76 unsigned frameWidth() const { return m_reader.frame_reader->width; }
77 unsigned frameHeight() const { return m_reader.frame_reader->height; }
79 int transparentPixel() const { return m_reader.frame_reader->tpixel; }
81 unsigned duration() const { return m_reader.frame_reader->delay_time; }
84 GIFImageReader m_reader;
85 unsigned m_readOffset;
88 GIFImageDecoder::GIFImageDecoder()
89 : m_frameCountValid(true), m_repetitionCount(cAnimationLoopOnce), m_reader(0)
92 GIFImageDecoder::~GIFImageDecoder()
97 // Take the data and store it.
98 void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
103 // Cache our new data.
104 ImageDecoder::setData(data, allDataReceived);
106 // Our frame count is now unknown.
107 m_frameCountValid = false;
109 // Create the GIF reader.
110 if (!m_reader && !m_failed)
111 m_reader = new GIFImageDecoderPrivate(this);
114 // Whether or not the size information has been decoded yet.
115 bool GIFImageDecoder::isSizeAvailable() const
117 // If we have pending data to decode, send it to the GIF reader now.
118 if (!m_sizeAvailable && m_reader) {
122 // The decoder will go ahead and aggressively consume everything up until the first
123 // size is encountered.
124 decode(GIFSizeQuery, 0);
127 return m_sizeAvailable;
130 // The total number of frames for the image. Will scan the image data for the answer
131 // (without necessarily decoding all of the individual frames).
132 int GIFImageDecoder::frameCount()
134 // If the decoder had an earlier error, we will just return what we had decoded
136 if (!m_frameCountValid) {
137 // FIXME: Scanning all the data has O(n^2) behavior if the data were to come in really
138 // slowly. Might be interesting to try to clone our existing read session to preserve
139 // state, but for now we just crawl all the data. Note that this is no worse than what
140 // ImageIO does on Mac right now (it also crawls all the data again).
141 GIFImageDecoderPrivate reader;
142 reader.decode(m_data->buffer(), GIFFrameCountQuery);
143 m_frameCountValid = true;
144 m_frameBufferCache.resize(reader.frameCount());
147 return m_frameBufferCache.size();
150 // The number of repetitions to perform for an animation loop.
151 int GIFImageDecoder::repetitionCount() const
153 // This value can arrive at any point in the image data stream. Most GIFs
154 // in the wild declare it near the beginning of the file, so it usually is
155 // set by the time we've decoded the size, but (depending on the GIF and the
156 // packets sent back by the webserver) not always. Our caller is
157 // responsible for waiting until image decoding has finished to ask this if
158 // it needs an authoritative answer. In the meantime, we should default to
161 // Added wrinkle: ImageSource::clear() may destroy the reader, making
162 // the result from the reader _less_ authoritative on future calls. To
163 // detect this, the reader returns cLoopCountNotSeen (-2) instead of
164 // cAnimationLoopOnce (-1) when its current incarnation hasn't actually
165 // seen a loop count yet; in this case we return our previously-cached
167 const int repetitionCount = m_reader->repetitionCount();
168 if (repetitionCount != cLoopCountNotSeen)
169 m_repetitionCount = repetitionCount;
171 return m_repetitionCount;
174 RGBA32Buffer* GIFImageDecoder::frameBufferAtIndex(size_t index)
176 if (index >= frameCount())
179 RGBA32Buffer& frame = m_frameBufferCache[index];
180 if (frame.status() != RGBA32Buffer::FrameComplete && m_reader)
181 // Decode this frame.
182 decode(GIFFullQuery, index+1);
186 void GIFImageDecoder::clearFrameBufferCache(size_t clearBeforeFrame)
188 // In some cases, like if the decoder was destroyed while animating, we
189 // can be asked to clear more frames than we currently have.
190 if (m_frameBufferCache.isEmpty())
191 return; // Nothing to do.
192 // The "-1" here is tricky. It does not mean that |clearBeforeFrame| is the
193 // last frame we wish to preserve, but rather that we never want to clear
194 // the very last frame in the cache: it's empty (so clearing it is
195 // pointless), it's partial (so we don't want to clear it anyway), or the
196 // cache could be enlarged with a future setData() call and it could be
197 // needed to construct the next frame (see comments below). Callers can
198 // always use ImageSource::clear(true, ...) to completely free the memory in
200 clearBeforeFrame = std::min(clearBeforeFrame, m_frameBufferCache.size() - 1);
201 const Vector<RGBA32Buffer>::iterator end(m_frameBufferCache.begin() + clearBeforeFrame);
202 for (Vector<RGBA32Buffer>::iterator i(m_frameBufferCache.begin()); i != end; ++i) {
203 if (i->status() == RGBA32Buffer::FrameEmpty)
204 continue; // Nothing to do.
206 // The layout of frames is:
207 // [empty frames][complete frames][partial frame][empty frames]
208 // ...where each of these groups may be empty. We should not clear a
209 // partial frame since that's what's being decoded right now, and we
210 // also should not clear the last complete frame, since it may be needed
211 // when constructing the next frame. Note that "i + 1" is safe since
212 // i < end < m_frameBufferCache.end().
213 if ((i->status() == RGBA32Buffer::FramePartial) || ((i + 1)->status() != RGBA32Buffer::FrameComplete))
220 // Feed data to the GIF reader.
221 void GIFImageDecoder::decode(GIFQuery query, unsigned haltAtFrame) const
226 m_failed = !m_reader->decode(m_data->buffer(), query, haltAtFrame);
234 // Callbacks from the GIF reader.
235 void GIFImageDecoder::sizeNowAvailable(unsigned width, unsigned height)
237 m_size = IntSize(width, height);
238 m_sizeAvailable = true;
241 void GIFImageDecoder::decodingHalted(unsigned bytesLeft)
243 m_reader->setReadOffset(m_data->size() - bytesLeft);
246 void GIFImageDecoder::initFrameBuffer(unsigned frameIndex)
248 // Initialize the frame rect in our buffer.
249 IntRect frameRect(m_reader->frameXOffset(), m_reader->frameYOffset(),
250 m_reader->frameWidth(), m_reader->frameHeight());
252 // Make sure the frameRect doesn't extend past the bottom-right of the buffer.
253 if (frameRect.right() > m_size.width())
254 frameRect.setWidth(m_size.width() - m_reader->frameXOffset());
255 if (frameRect.bottom() > m_size.height())
256 frameRect.setHeight(m_size.height() - m_reader->frameYOffset());
258 RGBA32Buffer* const buffer = &m_frameBufferCache[frameIndex];
259 buffer->setRect(frameRect);
261 if (frameIndex == 0) {
262 // This is the first frame, so we're not relying on any previous data.
263 prepEmptyFrameBuffer(buffer);
265 // The starting state for this frame depends on the previous frame's
268 // Frames that use the DisposeOverwritePrevious method are effectively
269 // no-ops in terms of changing the starting state of a frame compared to
270 // the starting state of the previous frame, so skip over them. (If the
271 // first frame specifies this method, it will get treated like
272 // DisposeOverwriteBgcolor below and reset to a completely empty image.)
273 const RGBA32Buffer* prevBuffer = &m_frameBufferCache[--frameIndex];
274 ASSERT(prevBuffer->status() == RGBA32Buffer::FrameComplete);
275 RGBA32Buffer::FrameDisposalMethod prevMethod =
276 prevBuffer->disposalMethod();
277 while ((frameIndex > 0) &&
278 (prevMethod == RGBA32Buffer::DisposeOverwritePrevious)) {
279 prevBuffer = &m_frameBufferCache[--frameIndex];
280 prevMethod = prevBuffer->disposalMethod();
283 if ((prevMethod == RGBA32Buffer::DisposeNotSpecified) ||
284 (prevMethod == RGBA32Buffer::DisposeKeep)) {
285 // Preserve the last frame as the starting state for this frame.
286 buffer->bytes() = prevBuffer->bytes();
287 buffer->setHasAlpha(prevBuffer->hasAlpha());
289 // We want to clear the previous frame to transparent, without
290 // affecting pixels in the image outside of the frame.
291 const IntRect& prevRect = prevBuffer->rect();
292 if ((frameIndex == 0) ||
293 prevRect.contains(IntRect(IntPoint(0, 0), m_size))) {
294 // Clearing the first frame, or a frame the size of the whole
295 // image, results in a completely empty image.
296 prepEmptyFrameBuffer(buffer);
298 // Copy the whole previous buffer, then clear just its frame.
299 buffer->bytes() = prevBuffer->bytes();
300 buffer->setHasAlpha(prevBuffer->hasAlpha());
301 for (int y = prevRect.y(); y < prevRect.bottom(); ++y) {
302 unsigned* const currentRow =
303 buffer->bytes().data() + (y * m_size.width());
304 for (int x = prevRect.x(); x < prevRect.right(); ++x)
305 buffer->setRGBA(*(currentRow + x), 0, 0, 0, 0);
307 if ((prevRect.width() > 0) && (prevRect.height() > 0))
308 buffer->setHasAlpha(true);
313 // Update our status to be partially complete.
314 buffer->setStatus(RGBA32Buffer::FramePartial);
316 // Reset the alpha pixel tracker for this frame.
317 m_currentBufferSawAlpha = false;
320 void GIFImageDecoder::prepEmptyFrameBuffer(RGBA32Buffer* buffer) const
322 buffer->bytes().resize(m_size.width() * m_size.height());
323 buffer->bytes().fill(0);
324 buffer->setHasAlpha(true);
327 void GIFImageDecoder::haveDecodedRow(unsigned frameIndex,
328 unsigned char* rowBuffer, // Pointer to single scanline temporary buffer
329 unsigned char* rowEnd,
330 unsigned rowNumber, // The row index
331 unsigned repeatCount, // How many times to repeat the row
332 bool writeTransparentPixels)
334 // Initialize the frame if necessary.
335 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
336 if (buffer.status() == RGBA32Buffer::FrameEmpty)
337 initFrameBuffer(frameIndex);
339 // Do nothing for bogus data.
340 if (rowBuffer == 0 || static_cast<int>(m_reader->frameYOffset() + rowNumber) >= m_size.height())
343 unsigned colorMapSize;
344 unsigned char* colorMap;
345 m_reader->getColorMap(colorMap, colorMapSize);
349 // The buffers that we draw are the entire image's width and height, so a final output frame is
350 // width * height RGBA32 values in size.
352 // A single GIF frame, however, can be smaller than the entire image, i.e., it can represent some sub-rectangle
353 // within the overall image. The rows we are decoding are within this
354 // sub-rectangle. This means that if the GIF frame's sub-rectangle is (x,y,w,h) then row 0 is really row
355 // y, and each row goes from x to x+w.
356 unsigned dstPos = (m_reader->frameYOffset() + rowNumber) * m_size.width() + m_reader->frameXOffset();
357 unsigned* dst = buffer.bytes().data() + dstPos;
358 unsigned* dstEnd = dst + m_size.width() - m_reader->frameXOffset();
359 unsigned* currDst = dst;
360 unsigned char* currentRowByte = rowBuffer;
362 while (currentRowByte != rowEnd && currDst < dstEnd) {
363 if ((!m_reader->isTransparent() || *currentRowByte != m_reader->transparentPixel()) && *currentRowByte < colorMapSize) {
364 unsigned colorIndex = *currentRowByte * 3;
365 unsigned red = colorMap[colorIndex];
366 unsigned green = colorMap[colorIndex + 1];
367 unsigned blue = colorMap[colorIndex + 2];
368 RGBA32Buffer::setRGBA(*currDst, red, green, blue, 255);
370 m_currentBufferSawAlpha = true;
371 // We may or may not need to write transparent pixels to the buffer.
372 // If we're compositing against a previous image, it's wrong, and if
373 // we're writing atop a cleared, fully transparent buffer, it's
374 // unnecessary; but if we're decoding an interlaced gif and
375 // displaying it "Haeberli"-style, we must write these for passes
376 // beyond the first, or the initial passes will "show through" the
378 if (writeTransparentPixels)
379 RGBA32Buffer::setRGBA(*currDst, 0, 0, 0, 0);
385 if (repeatCount > 1) {
386 // Copy the row |repeatCount|-1 times.
387 unsigned num = currDst - dst;
388 unsigned size = num * sizeof(unsigned);
389 unsigned width = m_size.width();
390 unsigned* end = buffer.bytes().data() + width * m_size.height();
391 currDst = dst + width;
392 for (unsigned i = 1; i < repeatCount; i++) {
393 if (currDst + num > end) // Protect against a buffer overrun from a bogus repeatCount.
395 memcpy(currDst, dst, size);
400 // Our partial height is rowNumber + 1, e.g., row 2 is the 3rd row, so that's a height of 3.
401 // Adding in repeatCount - 1 to rowNumber + 1 works out to just be rowNumber + repeatCount.
402 buffer.ensureHeight(rowNumber + repeatCount);
405 void GIFImageDecoder::frameComplete(unsigned frameIndex, unsigned frameDuration, RGBA32Buffer::FrameDisposalMethod disposalMethod)
407 // Initialize the frame if necessary. Some GIFs insert do-nothing frames,
408 // in which case we never reach haveDecodedRow() before getting here.
409 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
410 if (buffer.status() == RGBA32Buffer::FrameEmpty)
411 initFrameBuffer(frameIndex);
413 buffer.ensureHeight(m_size.height());
414 buffer.setStatus(RGBA32Buffer::FrameComplete);
415 buffer.setDuration(frameDuration);
416 buffer.setDisposalMethod(disposalMethod);
418 if (!m_currentBufferSawAlpha) {
419 // The whole frame was non-transparent, so it's possible that the entire
420 // resulting buffer was non-transparent, and we can setHasAlpha(false).
421 if (buffer.rect().contains(IntRect(IntPoint(0, 0), m_size))) {
422 buffer.setHasAlpha(false);
423 } else if (frameIndex > 0) {
424 // Tricky case. This frame does not have alpha only if everywhere
425 // outside its rect doesn't have alpha. To know whether this is
426 // true, we check the start state of the frame -- if it doesn't have
427 // alpha, we're safe.
429 // First skip over prior DisposeOverwritePrevious frames (since they
430 // don't affect the start state of this frame) the same way we do in
431 // initFrameBuffer().
432 const RGBA32Buffer* prevBuffer = &m_frameBufferCache[--frameIndex];
433 while ((frameIndex > 0) &&
434 (prevBuffer->disposalMethod() ==
435 RGBA32Buffer::DisposeOverwritePrevious))
436 prevBuffer = &m_frameBufferCache[--frameIndex];
438 // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
439 // we can say we have no alpha if that frame had no alpha. But
440 // since in initFrameBuffer() we already copied that frame's alpha
441 // state into the current frame's, we need do nothing at all here.
443 // The only remaining case is a DisposeOverwriteBgcolor frame. If
444 // it had no alpha, and its rect is contained in the current frame's
445 // rect, we know the current frame has no alpha.
446 if ((prevBuffer->disposalMethod() ==
447 RGBA32Buffer::DisposeOverwriteBgcolor) &&
448 !prevBuffer->hasAlpha() &&
449 buffer.rect().contains(prevBuffer->rect()))
450 buffer.setHasAlpha(false);
455 void GIFImageDecoder::gifComplete()
458 m_repetitionCount = m_reader->repetitionCount();
465 #endif // PLATFORM(CAIRO)