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.
26 #include "GIFImageDecoder.h"
27 #include "GIFImageReader.h"
29 #if PLATFORM(CAIRO) || PLATFORM(QT) || PLATFORM(WX)
33 class GIFImageDecoderPrivate
36 GIFImageDecoderPrivate(GIFImageDecoder* decoder = 0)
42 ~GIFImageDecoderPrivate()
47 bool decode(const Vector<char>& data,
48 GIFImageDecoder::GIFQuery query = GIFImageDecoder::GIFFullQuery,
49 unsigned int haltFrame = -1)
51 return m_reader.read((const unsigned char*)data.data() + m_readOffset, data.size() - m_readOffset,
56 unsigned frameCount() const { return m_reader.images_count; }
57 int repetitionCount() const { return m_reader.loop_count; }
59 void setReadOffset(unsigned o) { m_readOffset = o; }
61 bool isTransparent() const { return m_reader.frame_reader->is_transparent; }
63 void getColorMap(unsigned char*& map, unsigned& size) const {
64 if (m_reader.frame_reader->is_local_colormap_defined) {
65 map = m_reader.frame_reader->local_colormap;
66 size = (unsigned)m_reader.frame_reader->local_colormap_size;
68 map = m_reader.global_colormap;
69 size = m_reader.global_colormap_size;
73 unsigned frameXOffset() const { return m_reader.frame_reader->x_offset; }
74 unsigned frameYOffset() const { return m_reader.frame_reader->y_offset; }
75 unsigned frameWidth() const { return m_reader.frame_reader->width; }
76 unsigned frameHeight() const { return m_reader.frame_reader->height; }
78 int transparentPixel() const { return m_reader.frame_reader->tpixel; }
80 unsigned duration() const { return m_reader.frame_reader->delay_time; }
83 GIFImageReader m_reader;
84 unsigned m_readOffset;
87 GIFImageDecoder::GIFImageDecoder()
88 : m_frameCountValid(true), m_reader(0)
91 GIFImageDecoder::~GIFImageDecoder()
96 // Take the data and store it.
97 void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
102 // Cache our new data.
103 ImageDecoder::setData(data, allDataReceived);
105 // Our frame count is now unknown.
106 m_frameCountValid = false;
108 // Create the GIF reader.
109 if (!m_reader && !m_failed)
110 m_reader = new GIFImageDecoderPrivate(this);
113 // Whether or not the size information has been decoded yet.
114 bool GIFImageDecoder::isSizeAvailable() const
116 // If we have pending data to decode, send it to the GIF reader now.
117 if (!m_sizeAvailable && m_reader) {
121 // The decoder will go ahead and aggressively consume everything up until the first
122 // size is encountered.
123 decode(GIFSizeQuery, 0);
126 return m_sizeAvailable;
129 // The total number of frames for the image. Will scan the image data for the answer
130 // (without necessarily decoding all of the individual frames).
131 int GIFImageDecoder::frameCount()
133 // If the decoder had an earlier error, we will just return what we had decoded
135 if (!m_frameCountValid) {
136 // FIXME: Scanning all the data has O(n^2) behavior if the data were to come in really
137 // slowly. Might be interesting to try to clone our existing read session to preserve
138 // state, but for now we just crawl all the data. Note that this is no worse than what
139 // ImageIO does on Mac right now (it also crawls all the data again).
140 GIFImageDecoderPrivate reader;
141 reader.decode(m_data->buffer(), GIFFrameCountQuery);
142 m_frameCountValid = true;
143 m_frameBufferCache.resize(reader.frameCount());
146 return m_frameBufferCache.size();
149 // The number of repetitions to perform for an animation loop.
150 int GIFImageDecoder::repetitionCount() const
152 // We don't have to do any decoding to determine this, since the loop count was determined after
153 // the initial query for size.
155 return m_reader->repetitionCount();
156 return cAnimationNone;
159 RGBA32Buffer* GIFImageDecoder::frameBufferAtIndex(size_t index)
161 if (index >= frameCount())
164 RGBA32Buffer& frame = m_frameBufferCache[index];
165 if (frame.status() != RGBA32Buffer::FrameComplete && m_reader)
166 // Decode this frame.
167 decode(GIFFullQuery, index+1);
171 // Feed data to the GIF reader.
172 void GIFImageDecoder::decode(GIFQuery query, unsigned haltAtFrame) const
177 m_failed = !m_reader->decode(m_data->buffer(), query, haltAtFrame);
185 // Callbacks from the GIF reader.
186 void GIFImageDecoder::sizeNowAvailable(unsigned width, unsigned height)
188 m_size = IntSize(width, height);
189 m_sizeAvailable = true;
192 void GIFImageDecoder::decodingHalted(unsigned bytesLeft)
194 m_reader->setReadOffset(m_data->size() - bytesLeft);
197 void GIFImageDecoder::initFrameBuffer(unsigned frameIndex)
199 // Initialize the frame rect in our buffer.
200 IntRect frameRect(m_reader->frameXOffset(), m_reader->frameYOffset(),
201 m_reader->frameWidth(), m_reader->frameHeight());
203 // Make sure the frameRect doesn't extend past the bottom-right of the buffer.
204 if (frameRect.right() > m_size.width())
205 frameRect.setWidth(m_size.width() - m_reader->frameXOffset());
206 if (frameRect.bottom() > m_size.height())
207 frameRect.setHeight(m_size.height() - m_reader->frameYOffset());
209 RGBA32Buffer* const buffer = &m_frameBufferCache[frameIndex];
210 buffer->setRect(frameRect);
212 if (frameIndex == 0) {
213 // This is the first frame, so we're not relying on any previous data.
214 prepEmptyFrameBuffer(buffer);
216 // The starting state for this frame depends on the previous frame's
219 // Frames that use the DisposeOverwritePrevious method are effectively
220 // no-ops in terms of changing the starting state of a frame compared to
221 // the starting state of the previous frame, so skip over them. (If the
222 // first frame specifies this method, it will get treated like
223 // DisposeOverwriteBgcolor below and reset to a completely empty image.)
224 const RGBA32Buffer* prevBuffer = &m_frameBufferCache[--frameIndex];
225 RGBA32Buffer::FrameDisposalMethod prevMethod =
226 prevBuffer->disposalMethod();
227 while ((frameIndex > 0) &&
228 (prevMethod == RGBA32Buffer::DisposeOverwritePrevious)) {
229 prevBuffer = &m_frameBufferCache[--frameIndex];
230 prevMethod = prevBuffer->disposalMethod();
233 if ((prevMethod == RGBA32Buffer::DisposeNotSpecified) ||
234 (prevMethod == RGBA32Buffer::DisposeKeep)) {
235 // Preserve the last frame as the starting state for this frame.
236 buffer->bytes() = prevBuffer->bytes();
238 // We want to clear the previous frame to transparent, without
239 // affecting pixels in the image outside of the frame.
240 const IntRect& prevRect = prevBuffer->rect();
241 if ((frameIndex == 0) ||
242 prevRect.contains(IntRect(IntPoint(0, 0), m_size))) {
243 // Clearing the first frame, or a frame the size of the whole
244 // image, results in a completely empty image.
245 prepEmptyFrameBuffer(buffer);
247 // Copy the whole previous buffer, then clear just its frame.
248 buffer->bytes() = prevBuffer->bytes();
249 for (int y = prevRect.y(); y < prevRect.bottom(); ++y) {
250 unsigned* const currentRow =
251 buffer->bytes().data() + (y * m_size.width());
252 for (int x = prevRect.x(); x < prevRect.right(); ++x)
253 buffer->setRGBA(*(currentRow + x), 0, 0, 0, 0);
255 if ((prevRect.width() > 0) && (prevRect.height() > 0))
256 buffer->setHasAlpha(true);
261 // Update our status to be partially complete.
262 buffer->setStatus(RGBA32Buffer::FramePartial);
264 // Reset the alpha pixel tracker for this frame.
265 m_currentBufferSawAlpha = false;
268 void GIFImageDecoder::prepEmptyFrameBuffer(RGBA32Buffer* buffer) const
270 buffer->bytes().resize(m_size.width() * m_size.height());
271 buffer->bytes().fill(0);
272 buffer->setHasAlpha(true);
275 void GIFImageDecoder::haveDecodedRow(unsigned frameIndex,
276 unsigned char* rowBuffer, // Pointer to single scanline temporary buffer
277 unsigned char* rowEnd,
278 unsigned rowNumber, // The row index
279 unsigned repeatCount) // How many times to repeat the row
281 // Initialize the frame if necessary.
282 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
283 if (buffer.status() == RGBA32Buffer::FrameEmpty)
284 initFrameBuffer(frameIndex);
286 // Do nothing for bogus data.
287 if (rowBuffer == 0 || static_cast<int>(m_reader->frameYOffset() + rowNumber) >= m_size.height())
290 unsigned colorMapSize;
291 unsigned char* colorMap;
292 m_reader->getColorMap(colorMap, colorMapSize);
296 // The buffers that we draw are the entire image's width and height, so a final output frame is
297 // width * height RGBA32 values in size.
299 // A single GIF frame, however, can be smaller than the entire image, i.e., it can represent some sub-rectangle
300 // within the overall image. The rows we are decoding are within this
301 // sub-rectangle. This means that if the GIF frame's sub-rectangle is (x,y,w,h) then row 0 is really row
302 // y, and each row goes from x to x+w.
303 unsigned dstPos = (m_reader->frameYOffset() + rowNumber) * m_size.width() + m_reader->frameXOffset();
304 unsigned* dst = buffer.bytes().data() + dstPos;
305 unsigned* dstEnd = dst + m_size.width() - m_reader->frameXOffset();
306 unsigned* currDst = dst;
307 unsigned char* currentRowByte = rowBuffer;
309 while (currentRowByte != rowEnd && currDst < dstEnd) {
310 if ((!m_reader->isTransparent() || *currentRowByte != m_reader->transparentPixel()) && *currentRowByte < colorMapSize) {
311 unsigned colorIndex = *currentRowByte * 3;
312 unsigned red = colorMap[colorIndex];
313 unsigned green = colorMap[colorIndex + 1];
314 unsigned blue = colorMap[colorIndex + 2];
315 RGBA32Buffer::setRGBA(*currDst, red, green, blue, 255);
317 m_currentBufferSawAlpha = true;
323 if (repeatCount > 1) {
324 // Copy the row |repeatCount|-1 times.
325 unsigned num = currDst - dst;
326 unsigned size = num * sizeof(unsigned);
327 unsigned width = m_size.width();
328 unsigned* end = buffer.bytes().data() + width * m_size.height();
329 currDst = dst + width;
330 for (unsigned i = 1; i < repeatCount; i++) {
331 if (currDst + num > end) // Protect against a buffer overrun from a bogus repeatCount.
333 memcpy(currDst, dst, size);
338 // Our partial height is rowNumber + 1, e.g., row 2 is the 3rd row, so that's a height of 3.
339 // Adding in repeatCount - 1 to rowNumber + 1 works out to just be rowNumber + repeatCount.
340 buffer.ensureHeight(rowNumber + repeatCount);
343 void GIFImageDecoder::frameComplete(unsigned frameIndex, unsigned frameDuration, RGBA32Buffer::FrameDisposalMethod disposalMethod)
345 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
346 buffer.ensureHeight(m_size.height());
347 buffer.setStatus(RGBA32Buffer::FrameComplete);
348 buffer.setDuration(frameDuration);
349 buffer.setDisposalMethod(disposalMethod);
351 if (!m_currentBufferSawAlpha) {
352 // The whole frame was non-transparent, so it's possible that the entire
353 // resulting buffer was non-transparent, and we can setHasAlpha(false).
354 if (buffer.rect().contains(IntRect(IntPoint(0, 0), m_size))) {
355 buffer.setHasAlpha(false);
356 } else if (frameIndex > 0) {
357 // Tricky case. This frame does not have alpha only if everywhere
358 // outside its rect doesn't have alpha. To know whether this is
359 // true, we check the start state of the frame -- if it doesn't have
360 // alpha, we're safe.
362 // First skip over prior DisposeOverwritePrevious frames (since they
363 // don't affect the start state of this frame) the same way we do in
364 // initFrameBuffer().
365 const RGBA32Buffer* prevBuffer = &m_frameBufferCache[--frameIndex];
366 while ((frameIndex > 0) &&
367 (prevBuffer->disposalMethod() ==
368 RGBA32Buffer::DisposeOverwritePrevious))
369 prevBuffer = &m_frameBufferCache[--frameIndex];
371 // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
372 // we can say we have no alpha if that frame had no alpha. But
373 // since in initFrameBuffer() we already copied that frame's alpha
374 // state into the current frame's, we need do nothing at all here.
376 // The only remaining case is a DisposeOverwriteBgcolor frame. If
377 // it had no alpha, and its rect is contained in the current frame's
378 // rect, we know the current frame has no alpha.
379 if ((prevBuffer->disposalMethod() ==
380 RGBA32Buffer::DisposeOverwriteBgcolor) &&
381 !prevBuffer->hasAlpha() &&
382 buffer.rect().contains(prevBuffer->rect()))
383 buffer.setHasAlpha(false);
388 void GIFImageDecoder::gifComplete()
396 #endif // PLATFORM(CAIRO)