tizen beta release
[profile/ivi/webkit-efl.git] / Source / WebCore / platform / graphics / BitmapImage.cpp
1 /*
2  * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
3  * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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. 
25  */
26
27 #include "config.h"
28 #include "BitmapImage.h"
29
30 #include "FloatRect.h"
31 #include "ImageObserver.h"
32 #include "IntRect.h"
33 #include "MIMETypeRegistry.h"
34 #include "PlatformString.h"
35 #include "Timer.h"
36 #include <wtf/CurrentTime.h>
37 #include <wtf/Vector.h>
38
39 namespace WebCore {
40
41 static int frameBytes(const IntSize& frameSize)
42 {
43     return frameSize.width() * frameSize.height() * 4;
44 }
45
46 BitmapImage::BitmapImage(ImageObserver* observer)
47     : Image(observer)
48     , m_currentFrame(0)
49     , m_frames(0)
50     , m_frameTimer(0)
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)
59     , m_haveSize(false)
60     , m_sizeAvailable(false)
61     , m_hasUniformFrameSize(true)
62     , m_decodedSize(0)
63     , m_decodedPropertiesSize(0)
64     , m_haveFrameCount(false)
65     , m_frameCount(0)
66 {
67     initPlatformData();
68 }
69
70 BitmapImage::~BitmapImage()
71 {
72     invalidatePlatformData();
73     stopAnimation();
74 }
75
76 void BitmapImage::destroyDecodedData(bool destroyAll)
77 {
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
83         // the metadata.
84         if (m_frames[i].clear(false))
85           ++framesCleared;
86     }
87
88     destroyMetadataAndNotify(framesCleared);
89
90     m_source.clear(destroyAll, clearBeforeFrame, data(), m_allDataReceived);
91     return;
92 }
93
94 void BitmapImage::destroyDecodedDataIfNecessary(bool destroyAll)
95 {
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);
101 }
102
103 void BitmapImage::destroyMetadataAndNotify(int framesCleared)
104 {
105     m_isSolidColor = false;
106     m_checkedForSolidColor = false;
107     invalidatePlatformData();
108
109     int deltaBytes = framesCleared * -frameBytes(m_size);
110     m_decodedSize += deltaBytes;
111     if (framesCleared > 0) {
112         deltaBytes -= m_decodedPropertiesSize;
113         m_decodedPropertiesSize = 0;
114     }
115     if (deltaBytes && imageObserver())
116         imageObserver()->decodedSizeChanged(this, deltaBytes);
117 }
118
119 void BitmapImage::cacheFrame(size_t index)
120 {
121     size_t numFrames = frameCount();
122     ASSERT(m_decodedSize == 0 || numFrames > 1);
123     
124     if (m_frames.size() < numFrames)
125         m_frames.grow(numFrames);
126
127     m_frames[index].m_frame = m_source.createFrameAtIndex(index);
128     if (numFrames == 1 && m_frames[index].m_frame)
129         checkForSolidColor();
130
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);
136
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;
147         if (imageObserver())
148             imageObserver()->decodedSizeChanged(this, deltaBytes);
149     }
150 }
151
152 #if ENABLE(TIZEN_WEBCORE_SELECTIVE_RENDERING)
153 bool BitmapImage::hasDecodedFrame()
154 {
155     if (m_currentFrame >= frameCount())
156         return false;
157
158     if (m_currentFrame >= m_frames.size() || !m_frames[m_currentFrame].m_frame)
159         return false;
160
161     return m_frames[m_currentFrame].m_frame;
162 }
163 #endif
164
165 void BitmapImage::didDecodeProperties() const
166 {
167     if (m_decodedSize)
168         return;
169     size_t updatedSize = m_source.bytesDecodedToDetermineProperties();
170     if (m_decodedPropertiesSize == updatedSize)
171         return;
172     int deltaBytes = updatedSize - m_decodedPropertiesSize;
173 #if !ASSERT_DISABLED
174     bool overflow = updatedSize > m_decodedPropertiesSize && deltaBytes < 0;
175     bool underflow = updatedSize < m_decodedPropertiesSize && deltaBytes > 0;
176     ASSERT(!overflow && !underflow);
177 #endif
178     m_decodedPropertiesSize = updatedSize;
179     if (imageObserver())
180         imageObserver()->decodedSizeChanged(this, deltaBytes);
181 }
182
183 IntSize BitmapImage::size() const
184 {
185     if (m_sizeAvailable && !m_haveSize) {
186         m_size = m_source.size();
187         m_haveSize = true;
188         didDecodeProperties();
189     }
190     return m_size;
191 }
192
193 IntSize BitmapImage::currentFrameSize() const
194 {
195     if (!m_currentFrame || m_hasUniformFrameSize)
196         return size();
197     IntSize frameSize = m_source.frameSizeAtIndex(m_currentFrame);
198     didDecodeProperties();
199     return frameSize;
200 }
201
202 bool BitmapImage::getHotSpot(IntPoint& hotSpot) const
203 {
204     bool result = m_source.getHotSpot(hotSpot);
205     didDecodeProperties();
206     return result;
207 }
208
209 bool BitmapImage::dataChanged(bool allDataReceived)
210 {
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.
218     //
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);
235     }
236     destroyMetadataAndNotify(framesCleared);
237     
238     // Feed all the data we've seen so far to the image decoder.
239     m_allDataReceived = allDataReceived;
240     m_source.setData(data(), allDataReceived);
241     
242     m_haveFrameCount = false;
243     m_hasUniformFrameSize = true;
244     return isSizeAvailable();
245 }
246
247 String BitmapImage::filenameExtension() const
248 {
249     return m_source.filenameExtension();
250 }
251
252 size_t BitmapImage::frameCount()
253 {
254     if (!m_haveFrameCount) {
255         m_haveFrameCount = true;
256         m_frameCount = m_source.frameCount();
257         didDecodeProperties();
258     }
259     return m_frameCount;
260 }
261
262 bool BitmapImage::isSizeAvailable()
263 {
264     if (m_sizeAvailable)
265         return true;
266
267     m_sizeAvailable = m_source.isSizeAvailable();
268     didDecodeProperties();
269
270     return m_sizeAvailable;
271 }
272
273 NativeImagePtr BitmapImage::frameAtIndex(size_t index)
274 {
275     if (index >= frameCount())
276         return 0;
277
278     if (index >= m_frames.size() || !m_frames[index].m_frame)
279         cacheFrame(index);
280
281     return m_frames[index].m_frame;
282 }
283
284 bool BitmapImage::frameIsCompleteAtIndex(size_t index)
285 {
286     if (index >= frameCount())
287         return true;
288
289     if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
290         cacheFrame(index);
291
292     return m_frames[index].m_isComplete;
293 }
294
295 float BitmapImage::frameDurationAtIndex(size_t index)
296 {
297     if (index >= frameCount())
298         return 0;
299
300     if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
301         cacheFrame(index);
302
303     return m_frames[index].m_duration;
304 }
305
306 bool BitmapImage::frameHasAlphaAtIndex(size_t index)
307 {
308     if (index >= frameCount())
309         return true;
310
311     if (index >= m_frames.size() || !m_frames[index].m_haveMetadata)
312         cacheFrame(index);
313
314     return m_frames[index].m_hasAlpha;
315 }
316
317 int BitmapImage::repetitionCount(bool imageKnownToBeComplete)
318 {
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;
327     }
328     return m_repetitionCount;
329 }
330
331 bool BitmapImage::shouldAnimate()
332 {
333     return (repetitionCount(false) != cAnimationNone && !m_animationFinished && imageObserver());
334 }
335
336 void BitmapImage::startAnimation(bool catchUpIfNecessary)
337 {
338     if (m_frameTimer || !shouldAnimate() || frameCount() <= 1)
339         return;
340
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;
345
346     // Don't advance the animation to an incomplete frame.
347     size_t nextFrame = (m_currentFrame + 1) % frameCount();
348     if (!m_allDataReceived && !frameIsCompleteAtIndex(nextFrame))
349         return;
350
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
354     // wait on it.
355     if (!m_allDataReceived && repetitionCount(false) == cAnimationLoopOnce && m_currentFrame >= (frameCount() - 1))
356         return;
357
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;
363
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;
370
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;
383
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.));
388     } else {
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)
397                 break;
398
399             // Yes; skip over it without notifying our observers.
400             if (!internalAdvanceAnimation(true))
401                 return;
402             m_desiredFrameStartTime = frameAfterNextStartTime;
403             nextFrame = frameAfterNext;
404         }
405
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
409         // suggest.
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);
428         }
429     }
430 }
431
432 void BitmapImage::stopAnimation()
433 {
434     // This timer is used to animate all occurrences of this image.  Don't invalidate
435     // the timer unless all renderers have stopped drawing.
436     delete m_frameTimer;
437     m_frameTimer = 0;
438 }
439
440 void BitmapImage::resetAnimation()
441 {
442     stopAnimation();
443     m_currentFrame = 0;
444     m_repetitionsComplete = 0;
445     m_desiredFrameStartTime = 0;
446     m_animationFinished = false;
447     
448     // For extremely large animations, when the animation is reset, we just throw everything away.
449     destroyDecodedDataIfNecessary(true);
450 }
451
452 void BitmapImage::advanceAnimation(Timer<BitmapImage>*)
453 {
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.
458 }
459
460 bool BitmapImage::internalAdvanceAnimation(bool skippingFrames)
461 {
462     // Stop the animation.
463     stopAnimation();
464     
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))
468         return false;
469
470     ++m_currentFrame;
471     bool advancedAnimation = true;
472     bool destroyAll = false;
473     if (m_currentFrame >= frameCount()) {
474         ++m_repetitionsComplete;
475
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;
484             --m_currentFrame;
485             advancedAnimation = false;
486         } else {
487             m_currentFrame = 0;
488             destroyAll = true;
489         }
490     }
491     destroyDecodedDataIfNecessary(destroyAll);
492
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;
498 }
499
500 }