Bug 1647268 [wpt PR 24278] - Python 3: port xhr tests [part 6], a=testonly
[gecko.git] / image / FrameAnimator.cpp
blob139d17377fe69806fe337ee4369297065900b4f4
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "FrameAnimator.h"
8 #include <utility>
10 #include "LookupResult.h"
11 #include "RasterImage.h"
12 #include "imgIContainer.h"
13 #include "mozilla/CheckedInt.h"
14 #include "mozilla/StaticPrefs_image.h"
16 namespace mozilla {
18 using namespace gfx;
20 namespace image {
22 ///////////////////////////////////////////////////////////////////////////////
23 // AnimationState implementation.
24 ///////////////////////////////////////////////////////////////////////////////
26 const gfx::IntRect AnimationState::UpdateState(
27 RasterImage* aImage, const gfx::IntSize& aSize,
28 bool aAllowInvalidation /* = true */) {
29 LookupResult result = SurfaceCache::Lookup(
30 ImageKey(aImage),
31 RasterSurfaceKey(aSize, DefaultSurfaceFlags(), PlaybackType::eAnimated),
32 /* aMarkUsed = */ false);
34 return UpdateStateInternal(result, aSize, aAllowInvalidation);
37 const gfx::IntRect AnimationState::UpdateStateInternal(
38 LookupResult& aResult, const gfx::IntSize& aSize,
39 bool aAllowInvalidation /* = true */) {
40 // Update mDiscarded and mIsCurrentlyDecoded.
41 if (aResult.Type() == MatchType::NOT_FOUND) {
42 // no frames, we've either been discarded, or never been decoded before.
43 mDiscarded = mHasBeenDecoded;
44 mIsCurrentlyDecoded = false;
45 } else if (aResult.Type() == MatchType::PENDING) {
46 // no frames yet, but a decoder is or will be working on it.
47 mDiscarded = false;
48 mIsCurrentlyDecoded = false;
49 mHasRequestedDecode = true;
50 } else {
51 MOZ_ASSERT(aResult.Type() == MatchType::EXACT);
52 mDiscarded = false;
53 mHasRequestedDecode = true;
55 // If we can seek to the current animation frame we consider it decoded.
56 // Animated images are never fully decoded unless very short.
57 mIsCurrentlyDecoded =
58 bool(aResult.Surface()) &&
59 NS_SUCCEEDED(aResult.Surface().Seek(mCurrentAnimationFrameIndex));
62 gfx::IntRect ret;
64 if (aAllowInvalidation) {
65 // Update the value of mCompositedFrameInvalid.
66 if (mIsCurrentlyDecoded) {
67 // It is safe to clear mCompositedFrameInvalid safe to do for images that
68 // are fully decoded but aren't finished animating because before we paint
69 // the refresh driver will call into us to advance to the correct frame,
70 // and that will succeed because we have all the frames.
71 if (mCompositedFrameInvalid) {
72 // Invalidate if we are marking the composited frame valid.
73 ret.SizeTo(aSize);
75 mCompositedFrameInvalid = false;
76 } else if (aResult.Type() == MatchType::NOT_FOUND ||
77 aResult.Type() == MatchType::PENDING) {
78 if (mHasRequestedDecode) {
79 MOZ_ASSERT(StaticPrefs::image_mem_animated_discardable_AtStartup());
80 mCompositedFrameInvalid = true;
83 // Otherwise don't change the value of mCompositedFrameInvalid, it will be
84 // updated by RequestRefresh.
87 return ret;
90 void AnimationState::NotifyDecodeComplete() { mHasBeenDecoded = true; }
92 void AnimationState::ResetAnimation() { mCurrentAnimationFrameIndex = 0; }
94 void AnimationState::SetAnimationMode(uint16_t aAnimationMode) {
95 mAnimationMode = aAnimationMode;
98 void AnimationState::UpdateKnownFrameCount(uint32_t aFrameCount) {
99 if (aFrameCount <= mFrameCount) {
100 // Nothing to do. Since we can redecode animated images, we may see the same
101 // sequence of updates replayed again, so seeing a smaller frame count than
102 // what we already know about doesn't indicate an error.
103 return;
106 MOZ_ASSERT(!mHasBeenDecoded, "Adding new frames after decoding is finished?");
107 MOZ_ASSERT(aFrameCount <= mFrameCount + 1, "Skipped a frame?");
109 mFrameCount = aFrameCount;
112 Maybe<uint32_t> AnimationState::FrameCount() const {
113 return mHasBeenDecoded ? Some(mFrameCount) : Nothing();
116 void AnimationState::SetFirstFrameRefreshArea(const IntRect& aRefreshArea) {
117 mFirstFrameRefreshArea = aRefreshArea;
120 void AnimationState::InitAnimationFrameTimeIfNecessary() {
121 if (mCurrentAnimationFrameTime.IsNull()) {
122 mCurrentAnimationFrameTime = TimeStamp::Now();
126 void AnimationState::SetAnimationFrameTime(const TimeStamp& aTime) {
127 mCurrentAnimationFrameTime = aTime;
130 bool AnimationState::MaybeAdvanceAnimationFrameTime(const TimeStamp& aTime) {
131 if (!StaticPrefs::image_animated_resume_from_last_displayed() ||
132 mCurrentAnimationFrameTime >= aTime) {
133 return false;
136 // We are configured to stop an animation when it is out of view, and restart
137 // it from the same point when it comes back into view. The same applies if it
138 // was discarded while out of view.
139 mCurrentAnimationFrameTime = aTime;
140 return true;
143 uint32_t AnimationState::GetCurrentAnimationFrameIndex() const {
144 return mCurrentAnimationFrameIndex;
147 FrameTimeout AnimationState::LoopLength() const {
148 // If we don't know the loop length yet, we have to treat it as infinite.
149 if (!mLoopLength) {
150 return FrameTimeout::Forever();
153 MOZ_ASSERT(mHasBeenDecoded,
154 "We know the loop length but decoding isn't done?");
156 // If we're not looping, a single loop time has no meaning.
157 if (mAnimationMode != imgIContainer::kNormalAnimMode) {
158 return FrameTimeout::Forever();
161 return *mLoopLength;
164 ///////////////////////////////////////////////////////////////////////////////
165 // FrameAnimator implementation.
166 ///////////////////////////////////////////////////////////////////////////////
168 TimeStamp FrameAnimator::GetCurrentImgFrameEndTime(
169 AnimationState& aState, FrameTimeout aCurrentTimeout) const {
170 if (aCurrentTimeout == FrameTimeout::Forever()) {
171 // We need to return a sentinel value in this case, because our logic
172 // doesn't work correctly if we have an infinitely long timeout. We use one
173 // year in the future as the sentinel because it works with the loop in
174 // RequestRefresh() below.
175 // XXX(seth): It'd be preferable to make our logic work correctly with
176 // infinitely long timeouts.
177 return TimeStamp::NowLoRes() + TimeDuration::FromMilliseconds(31536000.0);
180 TimeDuration durationOfTimeout =
181 TimeDuration::FromMilliseconds(double(aCurrentTimeout.AsMilliseconds()));
182 return aState.mCurrentAnimationFrameTime + durationOfTimeout;
185 RefreshResult FrameAnimator::AdvanceFrame(AnimationState& aState,
186 DrawableSurface& aFrames,
187 RefPtr<imgFrame>& aCurrentFrame,
188 TimeStamp aTime) {
189 AUTO_PROFILER_LABEL("FrameAnimator::AdvanceFrame", GRAPHICS);
191 RefreshResult ret;
193 // Determine what the next frame is, taking into account looping.
194 uint32_t currentFrameIndex = aState.mCurrentAnimationFrameIndex;
195 uint32_t nextFrameIndex = currentFrameIndex + 1;
197 // Check if we're at the end of the loop. (FrameCount() returns Nothing() if
198 // we don't know the total count yet.)
199 if (aState.FrameCount() == Some(nextFrameIndex)) {
200 // If we are not looping forever, initialize the loop counter
201 if (aState.mLoopRemainingCount < 0 && aState.LoopCount() >= 0) {
202 aState.mLoopRemainingCount = aState.LoopCount();
205 // If animation mode is "loop once", or we're at end of loop counter,
206 // it's time to stop animating.
207 if (aState.mAnimationMode == imgIContainer::kLoopOnceAnimMode ||
208 aState.mLoopRemainingCount == 0) {
209 ret.mAnimationFinished = true;
212 nextFrameIndex = 0;
214 if (aState.mLoopRemainingCount > 0) {
215 aState.mLoopRemainingCount--;
218 // If we're done, exit early.
219 if (ret.mAnimationFinished) {
220 return ret;
224 if (nextFrameIndex >= aState.KnownFrameCount()) {
225 // We've already advanced to the last decoded frame, nothing more we can do.
226 // We're blocked by network/decoding from displaying the animation at the
227 // rate specified, so that means the frame we are displaying (the latest
228 // available) is the frame we want to be displaying at this time. So we
229 // update the current animation time. If we didn't update the current
230 // animation time then it could lag behind, which would indicate that we are
231 // behind in the animation and should try to catch up. When we are done
232 // decoding (and thus can loop around back to the start of the animation) we
233 // would then jump to a random point in the animation to try to catch up.
234 // But we were never behind in the animation.
235 aState.mCurrentAnimationFrameTime = aTime;
236 return ret;
239 // There can be frames in the surface cache with index >= KnownFrameCount()
240 // which GetRawFrame() can access because an async decoder has decoded them,
241 // but which AnimationState doesn't know about yet because we haven't received
242 // the appropriate notification on the main thread. Make sure we stay in sync
243 // with AnimationState.
244 MOZ_ASSERT(nextFrameIndex < aState.KnownFrameCount());
245 RefPtr<imgFrame> nextFrame = aFrames.GetFrame(nextFrameIndex);
247 // We should always check to see if we have the next frame even if we have
248 // previously finished decoding. If we needed to redecode (e.g. due to a draw
249 // failure) we would have discarded all the old frames and may not yet have
250 // the new ones. DrawableSurface::RawAccessRef promises to only return
251 // finished frames.
252 if (!nextFrame) {
253 // Uh oh, the frame we want to show is currently being decoded (partial).
254 // Similar to the above case, we could be blocked by network or decoding,
255 // and so we should advance our current time rather than risk jumping
256 // through the animation. We will wait until the next refresh driver tick
257 // and try again.
258 aState.mCurrentAnimationFrameTime = aTime;
259 return ret;
262 if (nextFrame->GetTimeout() == FrameTimeout::Forever()) {
263 ret.mAnimationFinished = true;
266 if (nextFrameIndex == 0) {
267 ret.mDirtyRect = aState.FirstFrameRefreshArea();
268 } else {
269 ret.mDirtyRect = nextFrame->GetDirtyRect();
272 aState.mCurrentAnimationFrameTime =
273 GetCurrentImgFrameEndTime(aState, aCurrentFrame->GetTimeout());
275 // If we can get closer to the current time by a multiple of the image's loop
276 // time, we should. We can only do this if we're done decoding; otherwise, we
277 // don't know the full loop length, and LoopLength() will have to return
278 // FrameTimeout::Forever(). We also skip this for images with a finite loop
279 // count if we have initialized mLoopRemainingCount (it only gets initialized
280 // after one full loop).
281 FrameTimeout loopTime = aState.LoopLength();
282 if (loopTime != FrameTimeout::Forever() &&
283 (aState.LoopCount() < 0 || aState.mLoopRemainingCount >= 0)) {
284 TimeDuration delay = aTime - aState.mCurrentAnimationFrameTime;
285 if (delay.ToMilliseconds() > loopTime.AsMilliseconds()) {
286 // Explicitly use integer division to get the floor of the number of
287 // loops.
288 uint64_t loops = static_cast<uint64_t>(delay.ToMilliseconds()) /
289 loopTime.AsMilliseconds();
291 // If we have a finite loop count limit the number of loops we advance.
292 if (aState.mLoopRemainingCount >= 0) {
293 MOZ_ASSERT(aState.LoopCount() >= 0);
294 loops =
295 std::min(loops, CheckedUint64(aState.mLoopRemainingCount).value());
298 aState.mCurrentAnimationFrameTime +=
299 TimeDuration::FromMilliseconds(loops * loopTime.AsMilliseconds());
301 if (aState.mLoopRemainingCount >= 0) {
302 MOZ_ASSERT(loops <= CheckedUint64(aState.mLoopRemainingCount).value());
303 aState.mLoopRemainingCount -= CheckedInt32(loops).value();
308 // Set currentAnimationFrameIndex at the last possible moment
309 aState.mCurrentAnimationFrameIndex = nextFrameIndex;
310 aState.mCompositedFrameRequested = false;
311 aCurrentFrame = std::move(nextFrame);
312 aFrames.Advance(nextFrameIndex);
314 // If we're here, we successfully advanced the frame.
315 ret.mFrameAdvanced = true;
317 return ret;
320 void FrameAnimator::ResetAnimation(AnimationState& aState) {
321 aState.ResetAnimation();
323 // Our surface provider is synchronized to our state, so we need to reset its
324 // state as well, if we still have one.
325 LookupResult result = SurfaceCache::Lookup(
326 ImageKey(mImage),
327 RasterSurfaceKey(mSize, DefaultSurfaceFlags(), PlaybackType::eAnimated),
328 /* aMarkUsed = */ false);
329 if (!result) {
330 return;
333 result.Surface().Reset();
336 RefreshResult FrameAnimator::RequestRefresh(AnimationState& aState,
337 const TimeStamp& aTime) {
338 // By default, an empty RefreshResult.
339 RefreshResult ret;
341 if (aState.IsDiscarded()) {
342 aState.MaybeAdvanceAnimationFrameTime(aTime);
343 return ret;
346 // Get the animation frames once now, and pass them down to callees because
347 // the surface could be discarded at anytime on a different thread. This is
348 // must easier to reason about then trying to write code that is safe to
349 // having the surface disappear at anytime.
350 LookupResult result = SurfaceCache::Lookup(
351 ImageKey(mImage),
352 RasterSurfaceKey(mSize, DefaultSurfaceFlags(), PlaybackType::eAnimated),
353 /* aMarkUsed = */ true);
355 ret.mDirtyRect = aState.UpdateStateInternal(result, mSize);
356 if (aState.IsDiscarded() || !result) {
357 aState.MaybeAdvanceAnimationFrameTime(aTime);
358 return ret;
361 RefPtr<imgFrame> currentFrame =
362 result.Surface().GetFrame(aState.mCurrentAnimationFrameIndex);
364 // only advance the frame if the current time is greater than or
365 // equal to the current frame's end time.
366 if (!currentFrame) {
367 MOZ_ASSERT(StaticPrefs::image_mem_animated_discardable_AtStartup());
368 MOZ_ASSERT(aState.GetHasRequestedDecode() &&
369 !aState.GetIsCurrentlyDecoded());
370 MOZ_ASSERT(aState.mCompositedFrameInvalid);
371 // Nothing we can do but wait for our previous current frame to be decoded
372 // again so we can determine what to do next.
373 aState.MaybeAdvanceAnimationFrameTime(aTime);
374 return ret;
377 TimeStamp currentFrameEndTime =
378 GetCurrentImgFrameEndTime(aState, currentFrame->GetTimeout());
380 // If nothing has accessed the composited frame since the last time we
381 // advanced, then there is no point in continuing to advance the animation.
382 // This has the effect of freezing the animation while not in view.
383 if (!aState.mCompositedFrameRequested &&
384 aState.MaybeAdvanceAnimationFrameTime(aTime)) {
385 return ret;
388 while (currentFrameEndTime <= aTime) {
389 TimeStamp oldFrameEndTime = currentFrameEndTime;
391 RefreshResult frameRes =
392 AdvanceFrame(aState, result.Surface(), currentFrame, aTime);
394 // Accumulate our result for returning to callers.
395 ret.Accumulate(frameRes);
397 // currentFrame was updated by AdvanceFrame so it is still current.
398 currentFrameEndTime =
399 GetCurrentImgFrameEndTime(aState, currentFrame->GetTimeout());
401 // If we didn't advance a frame, and our frame end time didn't change,
402 // then we need to break out of this loop & wait for the frame(s)
403 // to finish downloading.
404 if (!frameRes.mFrameAdvanced && currentFrameEndTime == oldFrameEndTime) {
405 break;
409 // We should only mark the composited frame as valid and reset the dirty rect
410 // if we advanced (meaning the next frame was actually produced somehow), the
411 // composited frame was previously invalid (so we may need to repaint
412 // everything) and either the frame index is valid (to know we were doing
413 // blending on the main thread, instead of on the decoder threads in advance),
414 // or the current frame is a full frame (blends off the main thread).
416 // If for some reason we forget to reset aState.mCompositedFrameInvalid, then
417 // GetCompositedFrame will fail, even if we have all the data available for
418 // display.
419 if (currentFrameEndTime > aTime && aState.mCompositedFrameInvalid) {
420 aState.mCompositedFrameInvalid = false;
421 ret.mDirtyRect = IntRect(IntPoint(0, 0), mSize);
424 MOZ_ASSERT(!aState.mIsCurrentlyDecoded || !aState.mCompositedFrameInvalid);
426 return ret;
429 LookupResult FrameAnimator::GetCompositedFrame(AnimationState& aState,
430 bool aMarkUsed) {
431 aState.mCompositedFrameRequested = true;
433 LookupResult result = SurfaceCache::Lookup(
434 ImageKey(mImage),
435 RasterSurfaceKey(mSize, DefaultSurfaceFlags(), PlaybackType::eAnimated),
436 aMarkUsed);
438 if (aState.mCompositedFrameInvalid) {
439 MOZ_ASSERT(StaticPrefs::image_mem_animated_discardable_AtStartup());
440 MOZ_ASSERT(aState.GetHasRequestedDecode());
441 MOZ_ASSERT(!aState.GetIsCurrentlyDecoded());
443 if (result.Type() == MatchType::EXACT) {
444 // If our composited frame is marked as invalid but our frames are in the
445 // surface cache we might just have not updated our internal state yet.
446 // This can happen if the image is not in a document so that
447 // RequestRefresh is not getting called to advance the frame.
448 // RequestRefresh would result in our composited frame getting marked as
449 // valid either at the end of RequestRefresh when we are able to advance
450 // to the current time or if advancing frames eventually causes us to
451 // decode all of the frames of the image resulting in DecodeComplete
452 // getting called which calls UpdateState. The reason we care about this
453 // is that img.decode promises won't resolve until GetCompositedFrame
454 // returns a frame.
455 UnorientedIntRect rect = UnorientedIntRect::FromUnknownRect(
456 aState.UpdateStateInternal(result, mSize));
458 if (!rect.IsEmpty()) {
459 nsCOMPtr<nsIEventTarget> eventTarget = do_GetMainThread();
460 RefPtr<RasterImage> image = mImage;
461 nsCOMPtr<nsIRunnable> ev = NS_NewRunnableFunction(
462 "FrameAnimator::GetCompositedFrame",
463 [=]() -> void { image->NotifyProgress(NoProgress, rect); });
464 eventTarget->Dispatch(ev.forget(), NS_DISPATCH_NORMAL);
468 // If it's still invalid we have to return.
469 if (aState.mCompositedFrameInvalid) {
470 if (result.Type() == MatchType::NOT_FOUND) {
471 return result;
473 return LookupResult(MatchType::PENDING);
477 // Otherwise return the raw frame. DoBlend is required to ensure that we only
478 // hit this case if the frame is not paletted and doesn't require compositing.
479 if (!result) {
480 return result;
483 // Seek to the appropriate frame. If seeking fails, it means that we couldn't
484 // get the frame we're looking for; treat this as if the lookup failed.
485 if (NS_FAILED(result.Surface().Seek(aState.mCurrentAnimationFrameIndex))) {
486 if (result.Type() == MatchType::NOT_FOUND) {
487 return result;
489 return LookupResult(MatchType::PENDING);
492 return result;
495 } // namespace image
496 } // namespace mozilla