Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(23)

Side by Side Diff: Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp

Issue 99103006: Moving GraphicsContext and dependencies from core to platform. (Closed) Base URL: svn://svn.chromium.org/blink/trunk
Patch Set: Final patch - fixes Android Created 7 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 "core/platform/image-decoders/gif/GIFImageDecoder.h"
28
29 #include <limits>
30 #include "core/platform/image-decoders/gif/GIFImageReader.h"
31 #include "platform/PlatformInstrumentation.h"
32 #include "wtf/NotFound.h"
33 #include "wtf/PassOwnPtr.h"
34
35 namespace WebCore {
36
37 GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
38 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
39 size_t maxDecodedBytes)
40 : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
41 , m_repetitionCount(cAnimationLoopOnce)
42 {
43 }
44
45 GIFImageDecoder::~GIFImageDecoder()
46 {
47 }
48
49 void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
50 {
51 if (failed())
52 return;
53
54 ImageDecoder::setData(data, allDataReceived);
55 if (m_reader)
56 m_reader->setData(data);
57 }
58
59 bool GIFImageDecoder::isSizeAvailable()
60 {
61 if (!ImageDecoder::isSizeAvailable())
62 parse(GIFSizeQuery);
63
64 return ImageDecoder::isSizeAvailable();
65 }
66
67 size_t GIFImageDecoder::frameCount()
68 {
69 parse(GIFFrameCountQuery);
70 return m_frameBufferCache.size();
71 }
72
73 int GIFImageDecoder::repetitionCount() const
74 {
75 // This value can arrive at any point in the image data stream. Most GIFs
76 // in the wild declare it near the beginning of the file, so it usually is
77 // set by the time we've decoded the size, but (depending on the GIF and the
78 // packets sent back by the webserver) not always. If the reader hasn't
79 // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
80 // should default to looping once (the initial value for
81 // |m_repetitionCount|).
82 //
83 // There are some additional wrinkles here. First, ImageSource::clear()
84 // may destroy the reader, making the result from the reader _less_
85 // authoritative on future calls if the recreated reader hasn't seen the
86 // loop count. We don't need to special-case this because in this case the
87 // new reader will once again return cLoopCountNotSeen, and we won't
88 // overwrite the cached correct value.
89 //
90 // Second, a GIF might never set a loop count at all, in which case we
91 // should continue to treat it as a "loop once" animation. We don't need
92 // special code here either, because in this case we'll never change
93 // |m_repetitionCount| from its default value.
94 //
95 // Third, we use the same GIFImageReader for counting frames and we might
96 // see the loop count and then encounter a decoding error which happens
97 // later in the stream. It is also possible that no frames are in the
98 // stream. In these cases we should just loop once.
99 if (failed() || (m_reader && (!m_reader->imagesCount())))
100 m_repetitionCount = cAnimationLoopOnce;
101 else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
102 m_repetitionCount = m_reader->loopCount();
103 return m_repetitionCount;
104 }
105
106 ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
107 {
108 if (index >= frameCount())
109 return 0;
110
111 ImageFrame& frame = m_frameBufferCache[index];
112 if (frame.status() != ImageFrame::FrameComplete) {
113 PlatformInstrumentation::willDecodeImage("GIF");
114 decode(index);
115 PlatformInstrumentation::didDecodeImage();
116 }
117
118 frame.notifyBitmapIfPixelsChanged();
119 return &frame;
120 }
121
122 bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const
123 {
124 return m_reader && (index < m_reader->imagesCount()) && m_reader->frameConte xt(index)->isComplete();
125 }
126
127 float GIFImageDecoder::frameDurationAtIndex(size_t index) const
128 {
129 return (m_reader && (index < m_reader->imagesCount()) &&
130 m_reader->frameContext(index)->isHeaderDefined()) ?
131 m_reader->frameContext(index)->delayTime() : 0;
132 }
133
134 bool GIFImageDecoder::setFailed()
135 {
136 m_reader.clear();
137 return ImageDecoder::setFailed();
138 }
139
140 bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, GIFRow::const_iterator r owBegin, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTranspa rentPixels)
141 {
142 const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
143 // The pixel data and coordinates supplied to us are relative to the frame's
144 // origin within the entire image size, i.e.
145 // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
146 // that width == (size().width() - frameContext->xOffset), so
147 // we must ensure we don't run off the end of either the source data or the
148 // row's X-coordinates.
149 const int xBegin = frameContext->xOffset();
150 const int yBegin = frameContext->yOffset() + rowNumber;
151 const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width), size().width());
152 const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumb er + repeatCount), size().height());
153 if (!width || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= y Begin))
154 return true;
155
156 const GIFColorMap::Table& colorTable = frameContext->localColorMap().isDefin ed() ? frameContext->localColorMap().table() : m_reader->globalColorMap().table( );
157
158 if (colorTable.isEmpty())
159 return true;
160
161 GIFColorMap::Table::const_iterator colorTableIter = colorTable.begin();
162
163 // Initialize the frame if necessary.
164 ImageFrame& buffer = m_frameBufferCache[frameIndex];
165 if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameInd ex))
166 return false;
167
168 const size_t transparentPixel = frameContext->transparentPixel();
169 GIFRow::const_iterator rowEnd = rowBegin + (xEnd - xBegin);
170 ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
171
172 // We may or may not need to write transparent pixels to the buffer.
173 // If we're compositing against a previous image, it's wrong, and if
174 // we're writing atop a cleared, fully transparent buffer, it's
175 // unnecessary; but if we're decoding an interlaced gif and
176 // displaying it "Haeberli"-style, we must write these for passes
177 // beyond the first, or the initial passes will "show through" the
178 // later ones.
179 //
180 // The loops below are almost identical. One writes a transparent pixel
181 // and one doesn't based on the value of |writeTransparentPixels|.
182 // The condition check is taken out of the loop to enhance performance.
183 // This optimization reduces decoding time by about 15% for a 3MB image.
184 if (writeTransparentPixels) {
185 for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
186 const size_t sourceValue = *rowBegin;
187 if ((sourceValue != transparentPixel) && (sourceValue < colorTable.s ize())) {
188 *currentAddress = colorTableIter[sourceValue];
189 } else {
190 *currentAddress = 0;
191 m_currentBufferSawAlpha = true;
192 }
193 }
194 } else {
195 for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
196 const size_t sourceValue = *rowBegin;
197 if ((sourceValue != transparentPixel) && (sourceValue < colorTable.s ize()))
198 *currentAddress = colorTableIter[sourceValue];
199 else
200 m_currentBufferSawAlpha = true;
201 }
202 }
203
204 // Tell the frame to copy the row data if need be.
205 if (repeatCount > 1)
206 buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);
207
208 buffer.setPixelsChanged(true);
209 return true;
210 }
211
212 bool GIFImageDecoder::parseCompleted() const
213 {
214 return m_reader && m_reader->parseCompleted();
215 }
216
217 bool GIFImageDecoder::frameComplete(size_t frameIndex)
218 {
219 // Initialize the frame if necessary. Some GIFs insert do-nothing frames,
220 // in which case we never reach haveDecodedRow() before getting here.
221 ImageFrame& buffer = m_frameBufferCache[frameIndex];
222 if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameInd ex))
223 return false; // initFrameBuffer() has already called setFailed().
224
225 buffer.setStatus(ImageFrame::FrameComplete);
226
227 if (!m_currentBufferSawAlpha) {
228 // The whole frame was non-transparent, so it's possible that the entire
229 // resulting buffer was non-transparent, and we can setHasAlpha(false).
230 if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
231 buffer.setHasAlpha(false);
232 buffer.setRequiredPreviousFrameIndex(kNotFound);
233 } else if (buffer.requiredPreviousFrameIndex() != kNotFound) {
234 // Tricky case. This frame does not have alpha only if everywhere
235 // outside its rect doesn't have alpha. To know whether this is
236 // true, we check the start state of the frame -- if it doesn't have
237 // alpha, we're safe.
238 const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPr eviousFrameIndex()];
239 ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwriteP revious);
240
241 // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
242 // we can say we have no alpha if that frame had no alpha. But
243 // since in initFrameBuffer() we already copied that frame's alpha
244 // state into the current frame's, we need do nothing at all here.
245 //
246 // The only remaining case is a DisposeOverwriteBgcolor frame. If
247 // it had no alpha, and its rect is contained in the current frame's
248 // rect, we know the current frame has no alpha.
249 if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgc olor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuff er->originalFrameRect()))
250 buffer.setHasAlpha(false);
251 }
252 }
253
254 return true;
255 }
256
257 size_t GIFImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
258 {
259 // We need to preserve frames such that:
260 // 1. We don't clear |clearExceptFrame|;
261 // 2. We don't clear any frame from which a future initFrameBuffer() call
262 // will copy bitmap data.
263 // All other frames can be cleared.
264 while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache [clearExceptFrame].status() == ImageFrame::FrameEmpty))
265 clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPrevious FrameIndex();
266
267 return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
268 }
269
270 void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
271 {
272 if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::Frame Partial) {
273 // Reset the state of the partial frame in the reader so that the frame
274 // can be decoded again when requested.
275 m_reader->clearDecodeState(frameIndex);
276 }
277 ImageDecoder::clearFrameBuffer(frameIndex);
278 }
279
280 void GIFImageDecoder::parse(GIFParseQuery query)
281 {
282 if (failed())
283 return;
284
285 if (!m_reader) {
286 m_reader = adoptPtr(new GIFImageReader(this));
287 m_reader->setData(m_data);
288 }
289
290 if (!m_reader->parse(query)) {
291 setFailed();
292 return;
293 }
294
295 const size_t oldSize = m_frameBufferCache.size();
296 m_frameBufferCache.resize(m_reader->imagesCount());
297
298 for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) {
299 ImageFrame& buffer = m_frameBufferCache[i];
300 const GIFFrameContext* frameContext = m_reader->frameContext(i);
301 buffer.setPremultiplyAlpha(m_premultiplyAlpha);
302 buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i, false) );
303 buffer.setDuration(frameContext->delayTime());
304 buffer.setDisposalMethod(frameContext->disposalMethod());
305
306 // Initialize the frame rect in our buffer.
307 IntRect frameRect = frameContext->frameRect();
308
309 // Make sure the frameRect doesn't extend outside the buffer.
310 if (frameRect.maxX() > size().width())
311 frameRect.setWidth(size().width() - frameRect.x());
312 if (frameRect.maxY() > size().height())
313 frameRect.setHeight(size().height() - frameRect.y());
314
315 buffer.setOriginalFrameRect(frameRect);
316 }
317 }
318
319 void GIFImageDecoder::decode(size_t frameIndex)
320 {
321 parse(GIFFrameCountQuery);
322
323 if (failed())
324 return;
325
326 Vector<size_t> framesToDecode;
327 size_t frameToDecode = frameIndex;
328 do {
329 framesToDecode.append(frameToDecode);
330 frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameI ndex();
331 } while (frameToDecode != kNotFound && m_frameBufferCache[frameToDecode].sta tus() != ImageFrame::FrameComplete);
332
333 for (size_t i = framesToDecode.size(); i > 0; --i) {
334 size_t frameIndex = framesToDecode[i - 1];
335 if (!m_reader->decode(frameIndex)) {
336 setFailed();
337 return;
338 }
339
340 // We need more data to continue decoding.
341 if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete )
342 break;
343 }
344
345 // It is also a fatal error if all data is received and we have decoded all
346 // frames available but the file is truncated.
347 if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_ reader && !m_reader->parseCompleted())
348 setFailed();
349 }
350
351 bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
352 {
353 // Initialize the frame rect in our buffer.
354 ImageFrame* const buffer = &m_frameBufferCache[frameIndex];
355
356 size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
357 if (requiredPreviousFrameIndex == kNotFound) {
358 // This frame doesn't rely on any previous data.
359 if (!buffer->setSize(size().width(), size().height()))
360 return setFailed();
361 } else {
362 const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrame Index];
363 ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);
364
365 // Preserve the last frame as the starting state for this frame.
366 if (!buffer->copyBitmapData(*prevBuffer))
367 return setFailed();
368
369 if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
370 // We want to clear the previous frame to transparent, without
371 // affecting pixels in the image outside of the frame.
372 const IntRect& prevRect = prevBuffer->originalFrameRect();
373 ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
374 buffer->zeroFillFrameRect(prevRect);
375 }
376 }
377
378 // Update our status to be partially complete.
379 buffer->setStatus(ImageFrame::FramePartial);
380
381 // Reset the alpha pixel tracker for this frame.
382 m_currentBufferSawAlpha = false;
383 return true;
384 }
385
386 } // namespace WebCore
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698