2 * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
3 * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "BitmapImage.h"
30 #include "FloatRect.h"
31 #include "ImageObserver.h"
33 #include "MIMETypeRegistry.h"
34 #include "PlatformString.h"
36 #include <wtf/CurrentTime.h>
37 #include <wtf/Vector.h>
41 static int frameBytes(const IntSize& frameSize)
43 return frameSize.width() * frameSize.height() * 4;
46 BitmapImage::BitmapImage(ImageObserver* observer)
51 , m_repetitionCount(cAnimationNone)
52 , m_repetitionCountStatus(Unknown)
53 , m_repetitionsComplete(0)
54 , m_desiredFrameStartTime(0)
55 , m_isSolidColor(false)
56 , m_checkedForSolidColor(false)
57 , m_animationFinished(false)
58 , m_allDataReceived(false)
60 , m_sizeAvailable(false)
61 , m_hasUniformFrameSize(true)
63 , m_decodedPropertiesSize(0)
64 , m_haveFrameCount(false)
70 BitmapImage::~BitmapImage()
72 invalidatePlatformData();
76 void BitmapImage::destroyDecodedData(bool destroyAll)
78 int framesCleared = 0;
79 const size_t clearBeforeFrame = destroyAll ? m_frames.size() : m_currentFrame;
80 for (size_t i = 0; i < clearBeforeFrame; ++i) {
81 // The underlying frame isn't actually changing (we're just trying to
82 // save the memory for the framebuffer data), so we don't need to clear
84 if (m_frames[i].clear(false))
88 destroyMetadataAndNotify(framesCleared);
90 m_source.clear(destroyAll, clearBeforeFrame, data(), m_allDataReceived);
94 void BitmapImage::destroyDecodedDataIfNecessary(bool destroyAll)
96 // Animated images >5MB are considered large enough that we'll only hang on
97 // to one frame at a time.
98 static const unsigned cLargeAnimationCutoff = 5242880;
99 if (m_frames.size() * frameBytes(m_size) > cLargeAnimationCutoff)
100 destroyDecodedData(destroyAll);
103 void BitmapImage::destroyMetadataAndNotify(int framesCleared)
105 m_isSolidColor = false;
106 m_checkedForSolidColor = false;
107 invalidatePlatformData();
109 int deltaBytes = framesCleared * -frameBytes(m_size);
110 m_decodedSize += deltaBytes;
111 if (framesCleared > 0) {
112 deltaBytes -= m_decodedPropertiesSize;
113 m_decodedPropertiesSize = 0;
115 if (deltaBytes && imageObserver())
116 imageObserver()->decodedSizeChanged(this, deltaBytes);
119 void BitmapImage::cacheFrame(size_t index)
121 size_t numFrames = frameCount();
122 ASSERT(m_decodedSize == 0 || numFrames > 1);
124 if (m_frames.size() < numFrames)
125 m_frames.grow(numFrames);
127 m_frames[index].m_frame = m_source.createFrameAtIndex(index);
128 if (numFrames == 1 && m_frames[index].m_frame)
129 checkForSolidColor();
131 m_frames[index].m_haveMetadata = true;
132 m_frames[index].m_isComplete = m_source.frameIsCompleteAtIndex(index);
133 if (repetitionCount(false) != cAnimationNone)
134 m_frames[index].m_duration = m_source.frameDurationAtIndex(index);
135 m_frames[index].m_hasAlpha = m_source.frameHasAlphaAtIndex(index);
137 const IntSize frameSize(index ? m_source.frameSizeAtIndex(index) : m_size);
138 if (frameSize != m_size)
139 m_hasUniformFrameSize = false;
140 if (m_frames[index].m_frame) {
141 int deltaBytes = frameBytes(frameSize);
142 m_decodedSize += deltaBytes;
143 // The fully-decoded frame will subsume the partially decoded data used
144 // to determine image properties.
145 deltaBytes -= m_decodedPropertiesSize;
146 m_decodedPropertiesSize = 0;
148 imageObserver()->decodedSizeChanged(this, deltaBytes);
152 #if ENABLE(TIZEN_WEBCORE_SELECTIVE_RENDERING)
153 bool BitmapImage::hasDecodedFrame()
155 if (m_currentFrame >= frameCount())
158 if (m_currentFrame >= m_frames.size() || !m_frames[m_currentFrame].m_frame)
161 return m_frames[m_currentFrame].m_frame;
165 void BitmapImage::didDecodeProperties() const
169 size_t updatedSize = m_source.bytesDecodedToDetermineProperties();
170 if (m_decodedPropertiesSize == updatedSize)
172 int deltaBytes = updatedSize - m_decodedPropertiesSize;
174 bool overflow = updatedSize > m_decodedPropertiesSize && deltaBytes < 0;
175 bool underflow = updatedSize < m_decodedPropertiesSize && deltaBytes > 0;
176 ASSERT(!overflow && !underflow);
178 m_decodedPropertiesSize = updatedSize;
180 imageObserver()->decodedSizeChanged(this, deltaBytes);
183 IntSize BitmapImage::size() const
185 if (m_sizeAvailable && !m_haveSize) {
186 m_size = m_source.size();
188 didDecodeProperties();
193 IntSize BitmapImage::currentFrameSize() const
195 if (!m_currentFrame || m_hasUniformFrameSize)
197 IntSize frameSize = m_source.frameSizeAtIndex(m_currentFrame);
198 didDecodeProperties();
202 bool BitmapImage::getHotSpot(IntPoint& hotSpot) const
204 bool result = m_source.getHotSpot(hotSpot);
205 didDecodeProperties();
209 bool BitmapImage::dataChanged(bool allDataReceived)
211 // Clear all partially-decoded frames. For most image formats, there is only
212 // one frame, but at least GIF and ICO can have more. With GIFs, the frames
213 // come in order and we ask to decode them in order, waiting to request a
214 // subsequent frame until the prior one is complete. Given that we clear
215 // incomplete frames here, this means there is at most one incomplete frame
216 // (even if we use destroyDecodedData() -- since it doesn't reset the
217 // metadata), and it is after all the complete frames.
219 // With ICOs, on the other hand, we may ask for arbitrary frames at
220 // different times (e.g. because we're displaying a higher-resolution image
221 // in the content area and using a lower-resolution one for the favicon),
222 // and the frames aren't even guaranteed to appear in the file in the same
223 // order as in the directory, so an arbitrary number of the frames might be
224 // incomplete (if we ask for frames for which we've not yet reached the
225 // start of the frame data), and any or none of them might be the particular
226 // frame affected by appending new data here. Thus we have to clear all the
227 // incomplete frames to be safe.
228 int framesCleared = 0;
229 for (size_t i = 0; i < m_frames.size(); ++i) {
230 // NOTE: Don't call frameIsCompleteAtIndex() here, that will try to
231 // decode any uncached (i.e. never-decoded or
232 // cleared-on-a-previous-pass) frames!
233 if (m_frames[i].m_haveMetadata && !m_frames[i].m_isComplete)
234 framesCleared += (m_frames[i].clear(true) ? 1 : 0);
236 destroyMetadataAndNotify(framesCleared);
238 // Feed all the data we've seen so far to the image decoder.
239 m_allDataReceived = allDataReceived;
240 m_source.setData(data(), allDataReceived);
242 m_haveFrameCount = false;
243 m_hasUniformFrameSize = true;
244 return isSizeAvailable();
247 String BitmapImage::filenameExtension() const
249 return m_source.filenameExtension();
252 size_t BitmapImage::frameCount()
254 if (!m_haveFrameCount) {
255 m_haveFrameCount = true;
256 m_frameCount = m_source.frameCount();
257 didDecodeProperties();
262 bool BitmapImage::isSizeAvailable()
267 m_sizeAvailable = m_source.isSizeAvailable();
268 didDecodeProperties();
270 return m_sizeAvailable;
273 NativeImagePtr BitmapImage::frameAtIndex(size_t index)
275 if (index >= frameCount())
278 if (index >= m_frames.size() || !m_frames[index].m_frame)
281 return m_frames[index].m_frame;
284 bool BitmapImage::frameIsCompleteAtIndex(size_t index)
286 if (index >= frameCount())
289 if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
292 return m_frames[index].m_isComplete;
295 float BitmapImage::frameDurationAtIndex(size_t index)
297 if (index >= frameCount())
300 if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
303 return m_frames[index].m_duration;
306 bool BitmapImage::frameHasAlphaAtIndex(size_t index)
308 if (index >= frameCount())
311 if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
314 return m_frames[index].m_hasAlpha;
317 int BitmapImage::repetitionCount(bool imageKnownToBeComplete)
319 if ((m_repetitionCountStatus == Unknown) || ((m_repetitionCountStatus == Uncertain) && imageKnownToBeComplete)) {
320 // Snag the repetition count. If |imageKnownToBeComplete| is false, the
321 // repetition count may not be accurate yet for GIFs; in this case the
322 // decoder will default to cAnimationLoopOnce, and we'll try and read
323 // the count again once the whole image is decoded.
324 m_repetitionCount = m_source.repetitionCount();
325 didDecodeProperties();
326 m_repetitionCountStatus = (imageKnownToBeComplete || m_repetitionCount == cAnimationNone) ? Certain : Uncertain;
328 return m_repetitionCount;
331 bool BitmapImage::shouldAnimate()
333 return (repetitionCount(false) != cAnimationNone && !m_animationFinished && imageObserver());
336 void BitmapImage::startAnimation(bool catchUpIfNecessary)
338 if (m_frameTimer || !shouldAnimate() || frameCount() <= 1)
341 // If we aren't already animating, set now as the animation start time.
342 const double time = monotonicallyIncreasingTime();
343 if (!m_desiredFrameStartTime)
344 m_desiredFrameStartTime = time;
346 // Don't advance the animation to an incomplete frame.
347 size_t nextFrame = (m_currentFrame + 1) % frameCount();
348 if (!m_allDataReceived && !frameIsCompleteAtIndex(nextFrame))
351 // Don't advance past the last frame if we haven't decoded the whole image
352 // yet and our repetition count is potentially unset. The repetition count
353 // in a GIF can potentially come after all the rest of the image data, so
355 if (!m_allDataReceived && repetitionCount(false) == cAnimationLoopOnce && m_currentFrame >= (frameCount() - 1))
358 // Determine time for next frame to start. By ignoring paint and timer lag
359 // in this calculation, we make the animation appear to run at its desired
360 // rate regardless of how fast it's being repainted.
361 const double currentDuration = frameDurationAtIndex(m_currentFrame);
362 m_desiredFrameStartTime += currentDuration;
364 // When an animated image is more than five minutes out of date, the
365 // user probably doesn't care about resyncing and we could burn a lot of
366 // time looping through frames below. Just reset the timings.
367 const double cAnimationResyncCutoff = 5 * 60;
368 if ((time - m_desiredFrameStartTime) > cAnimationResyncCutoff)
369 m_desiredFrameStartTime = time + currentDuration;
371 // The image may load more slowly than it's supposed to animate, so that by
372 // the time we reach the end of the first repetition, we're well behind.
373 // Clamp the desired frame start time in this case, so that we don't skip
374 // frames (or whole iterations) trying to "catch up". This is a tradeoff:
375 // It guarantees users see the whole animation the second time through and
376 // don't miss any repetitions, and is closer to what other browsers do; on
377 // the other hand, it makes animations "less accurate" for pages that try to
378 // sync an image and some other resource (e.g. audio), especially if users
379 // switch tabs (and thus stop drawing the animation, which will pause it)
380 // during that initial loop, then switch back later.
381 if (nextFrame == 0 && m_repetitionsComplete == 0 && m_desiredFrameStartTime < time)
382 m_desiredFrameStartTime = time;
384 if (!catchUpIfNecessary || time < m_desiredFrameStartTime) {
385 // Haven't yet reached time for next frame to start; delay until then.
386 m_frameTimer = new Timer<BitmapImage>(this, &BitmapImage::advanceAnimation);
387 m_frameTimer->startOneShot(std::max(m_desiredFrameStartTime - time, 0.));
389 // We've already reached or passed the time for the next frame to start.
390 // See if we've also passed the time for frames after that to start, in
391 // case we need to skip some frames entirely. Remember not to advance
392 // to an incomplete frame.
393 for (size_t frameAfterNext = (nextFrame + 1) % frameCount(); frameIsCompleteAtIndex(frameAfterNext); frameAfterNext = (nextFrame + 1) % frameCount()) {
394 // Should we skip the next frame?
395 double frameAfterNextStartTime = m_desiredFrameStartTime + frameDurationAtIndex(nextFrame);
396 if (time < frameAfterNextStartTime)
399 // Yes; skip over it without notifying our observers.
400 if (!internalAdvanceAnimation(true))
402 m_desiredFrameStartTime = frameAfterNextStartTime;
403 nextFrame = frameAfterNext;
406 // Draw the next frame immediately. Note that m_desiredFrameStartTime
407 // may be in the past, meaning the next time through this function we'll
408 // kick off the next advancement sooner than this frame's duration would
410 if (internalAdvanceAnimation(false)) {
411 // The image region has been marked dirty, but once we return to our
412 // caller, draw() will clear it, and nothing will cause the
413 // animation to advance again. We need to start the timer for the
414 // next frame running, or the animation can hang. (Compare this
415 // with when advanceAnimation() is called, and the region is dirtied
416 // while draw() is not in the callstack, meaning draw() gets called
417 // to update the region and thus startAnimation() is reached again.)
418 // NOTE: For large images with slow or heavily-loaded systems,
419 // throwing away data as we go (see destroyDecodedData()) means we
420 // can spend so much time re-decoding data above that by the time we
421 // reach here we're behind again. If we let startAnimation() run
422 // the catch-up code again, we can get long delays without painting
423 // as we race the timer, or even infinite recursion. In this
424 // situation the best we can do is to simply change frames as fast
425 // as possible, so force startAnimation() to set a zero-delay timer
426 // and bail out if we're not caught up.
427 startAnimation(false);
432 void BitmapImage::stopAnimation()
434 // This timer is used to animate all occurrences of this image. Don't invalidate
435 // the timer unless all renderers have stopped drawing.
440 void BitmapImage::resetAnimation()
444 m_repetitionsComplete = 0;
445 m_desiredFrameStartTime = 0;
446 m_animationFinished = false;
448 // For extremely large animations, when the animation is reset, we just throw everything away.
449 destroyDecodedDataIfNecessary(true);
452 void BitmapImage::advanceAnimation(Timer<BitmapImage>*)
454 internalAdvanceAnimation(false);
455 // At this point the image region has been marked dirty, and if it's
456 // onscreen, we'll soon make a call to draw(), which will call
457 // startAnimation() again to keep the animation moving.
460 bool BitmapImage::internalAdvanceAnimation(bool skippingFrames)
462 // Stop the animation.
465 // See if anyone is still paying attention to this animation. If not, we don't
466 // advance and will remain suspended at the current frame until the animation is resumed.
467 if (!skippingFrames && imageObserver()->shouldPauseAnimation(this))
471 bool advancedAnimation = true;
472 bool destroyAll = false;
473 if (m_currentFrame >= frameCount()) {
474 ++m_repetitionsComplete;
476 // Get the repetition count again. If we weren't able to get a
477 // repetition count before, we should have decoded the whole image by
478 // now, so it should now be available.
479 // Note that we don't need to special-case cAnimationLoopOnce here
480 // because it is 0 (see comments on its declaration in ImageSource.h).
481 if (repetitionCount(true) != cAnimationLoopInfinite && m_repetitionsComplete > m_repetitionCount) {
482 m_animationFinished = true;
483 m_desiredFrameStartTime = 0;
485 advancedAnimation = false;
491 destroyDecodedDataIfNecessary(destroyAll);
493 // We need to draw this frame if we advanced to it while not skipping, or if
494 // while trying to skip frames we hit the last frame and thus had to stop.
495 if (skippingFrames != advancedAnimation)
496 imageObserver()->animationAdvanced(this);
497 return advancedAnimation;