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 < 0 || 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(RGBA32Buffer& buffer,
198 RGBA32Buffer* previousBuffer,
199 bool compositeWithPreviousFrame)
201 // Initialize the frame rect in our buffer.
202 IntRect frameRect(m_reader->frameXOffset(), m_reader->frameYOffset(),
203 m_reader->frameWidth(), m_reader->frameHeight());
205 // Make sure the frameRect doesn't extend past the bottom-right of the buffer.
206 if (frameRect.right() > m_size.width())
207 frameRect.setWidth(m_size.width() - m_reader->frameXOffset());
208 if (frameRect.bottom() > m_size.height())
209 frameRect.setHeight(m_size.height() - m_reader->frameYOffset());
211 buffer.setRect(frameRect);
213 bool isSubRect = (frameRect.x() > 0 || frameRect.y() > 0 ||
214 frameRect.width() < m_size.width() ||
215 frameRect.height() < m_size.height());
217 // Let's resize our buffer now to the correct width/height and then
218 // initialize portions of it if needed.
219 RGBA32Array& bytes = buffer.bytes();
221 // If the disposal method of the previous frame said to stick around, then we need
222 // to copy that frame into our frame. We also dont want to have any impact on
223 // anything outside our frame's rect, so if we don't overlay the entire image,
224 // then also composite with the previous frame.
225 if (previousBuffer && (compositeWithPreviousFrame || isSubRect)) {
226 bytes = previousBuffer->bytes();
227 buffer.ensureHeight(m_size.height());
228 buffer.setHasAlpha(previousBuffer->hasAlpha());
230 else // Resize to the width and height of the image.
231 bytes.resize(m_size.width() * m_size.height());
234 // We need to go ahead and initialize the first frame to make sure
235 // that areas outside the subrect start off transparent.
236 if (!previousBuffer) {
238 buffer.setHasAlpha(true);
239 } else if (!compositeWithPreviousFrame) {
240 // Now this is an interesting case. In the case where we fill
241 // the entire image, we effectively do a full clear of the image (and thus
242 // don't have to initialize anything in our buffer).
244 // However in the case where we only fill a piece of the image, two problems occur:
245 // (1) We need to wipe out the area occupied by the previous frame, which
246 // could also have been a subrect.
247 // (2) Anything outside the previous frame's rect *and* outside our current
248 // frame's rect should be left alone.
249 // We have handled (2) by just initializing our buffer from the previous frame.
250 // Our subrect will correctly overwrite the previous frame's contents as we
251 // decode rows. However that still leaves the problem of having to wipe out
252 // the area occupied by the previous frame that does not overlap with
254 if (previousBuffer->rect() != frameRect) {
255 // We have to restore the entire previous subframe with the first frame's contents.
256 RGBA32Buffer* firstBuffer = &m_frameBufferCache[0];
257 bool sawAlpha = buffer.hasAlpha();
258 IntRect prevRect = previousBuffer->rect();
259 unsigned end = prevRect.y() + prevRect.height();
261 // Given that we allocate buffers to be the same size as previous buffers,
262 // I think this assert should be valid.
263 ASSERT(IntRect(IntPoint(0,0), m_size).contains(firstBuffer->rect()));
265 for (unsigned i = prevRect.y(); i < end; i++) {
266 unsigned* curr = buffer.bytes().data() + (i * m_size.width() + prevRect.x());
267 unsigned* orig = firstBuffer->bytes().data() + (i * m_size.width() + prevRect.x());
268 unsigned* end = curr + prevRect.width();
269 unsigned* origEnd = orig + firstBuffer->rect().width();
271 while (curr != end && orig != origEnd) {
274 buffer.setHasAlpha(true);
283 // Update our status to be partially complete.
284 buffer.setStatus(RGBA32Buffer::FramePartial);
287 void GIFImageDecoder::haveDecodedRow(unsigned frameIndex,
288 unsigned char* rowBuffer, // Pointer to single scanline temporary buffer
289 unsigned char* rowEnd,
290 unsigned rowNumber, // The row index
291 unsigned repeatCount) // How many times to repeat the row
293 // Resize to the width and height of the image.
294 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
295 RGBA32Buffer* previousBuffer = (frameIndex > 0) ? &m_frameBufferCache[frameIndex-1] : 0;
296 bool compositeWithPreviousFrame = previousBuffer && previousBuffer->includeInNextFrame();
298 if (buffer.status() == RGBA32Buffer::FrameEmpty)
299 initFrameBuffer(buffer, previousBuffer, compositeWithPreviousFrame);
301 // Do nothing for bogus data.
302 if (rowBuffer == 0 || static_cast<int>(m_reader->frameYOffset() + rowNumber) >= m_size.height())
305 unsigned colorMapSize;
306 unsigned char* colorMap;
307 m_reader->getColorMap(colorMap, colorMapSize);
311 // The buffers that we draw are the entire image's width and height, so a final output frame is
312 // width * height RGBA32 values in size.
314 // A single GIF frame, however, can be smaller than the entire image, i.e., it can represent some sub-rectangle
315 // within the overall image. The rows we are decoding are within this
316 // sub-rectangle. This means that if the GIF frame's sub-rectangle is (x,y,w,h) then row 0 is really row
317 // y, and each row goes from x to x+w.
318 unsigned dstPos = (m_reader->frameYOffset() + rowNumber) * m_size.width() + m_reader->frameXOffset();
319 unsigned* dst = buffer.bytes().data() + dstPos;
320 unsigned* dstEnd = dst + m_size.width() - m_reader->frameXOffset();
321 unsigned* currDst = dst;
322 unsigned char* currentRowByte = rowBuffer;
324 bool hasAlpha = m_reader->isTransparent();
325 bool sawAlpha = false;
326 while (currentRowByte != rowEnd && currDst < dstEnd) {
327 if ((!hasAlpha || *currentRowByte != m_reader->transparentPixel()) && *currentRowByte < colorMapSize) {
328 unsigned colorIndex = *currentRowByte * 3;
329 unsigned red = colorMap[colorIndex];
330 unsigned green = colorMap[colorIndex + 1];
331 unsigned blue = colorMap[colorIndex + 2];
332 RGBA32Buffer::setRGBA(*currDst, red, green, blue, 255);
336 buffer.setHasAlpha(true);
339 if (!compositeWithPreviousFrame)
340 RGBA32Buffer::setRGBA(*currDst, 0, 0, 0, 0);
346 if (repeatCount > 1) {
347 // Copy the row |repeatCount|-1 times.
348 unsigned num = currDst - dst;
349 unsigned size = num * sizeof(unsigned);
350 unsigned width = m_size.width();
351 unsigned* end = buffer.bytes().data() + width * m_size.height();
352 currDst = dst + width;
353 for (unsigned i = 1; i < repeatCount; i++) {
354 if (currDst + num > end) // Protect against a buffer overrun from a bogus repeatCount.
356 memcpy(currDst, dst, size);
361 // Our partial height is rowNumber + 1, e.g., row 2 is the 3rd row, so that's a height of 3.
362 // Adding in repeatCount - 1 to rowNumber + 1 works out to just be rowNumber + repeatCount.
363 buffer.ensureHeight(rowNumber + repeatCount);
366 void GIFImageDecoder::frameComplete(unsigned frameIndex, unsigned frameDuration, bool includeInNextFrame)
368 RGBA32Buffer& buffer = m_frameBufferCache[frameIndex];
369 buffer.setStatus(RGBA32Buffer::FrameComplete);
370 buffer.setDuration(frameDuration);
371 buffer.setIncludeInNextFrame(includeInNextFrame);
372 buffer.ensureHeight(m_size.height());
375 void GIFImageDecoder::gifComplete()
383 #endif // PLATFORM(CAIRO)