Bug 523950 - Part 9. Integrate AnimationSurfaceProvider with AnimationFrameBuffer. r=tnikkel
authorAndrew Osmond <aosmond@mozilla.com>
Wed, 28 Feb 2018 13:34:53 -0500
changeset 405773 5bf2391a0e6ab6ce75e842aaf6cee9c15c010078
parent 405772 8170b0d61fc800d62f7662d87d4ac2edbe47ad46
child 405774 58a2ebce44c3861da96b968fcbbf7ae6ef5e3da6
push id33531
push usercsabou@mozilla.com
push dateWed, 28 Feb 2018 21:49:08 +0000
treeherdermozilla-central@17e47288c224 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerstnikkel
bugs523950
milestone60.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 523950 - Part 9. Integrate AnimationSurfaceProvider with AnimationFrameBuffer. r=tnikkel
image/AnimationSurfaceProvider.cpp
image/AnimationSurfaceProvider.h
--- a/image/AnimationSurfaceProvider.cpp
+++ b/image/AnimationSurfaceProvider.cpp
@@ -3,16 +3,17 @@
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "AnimationSurfaceProvider.h"
 
 #include "gfxPrefs.h"
 #include "nsProxyRelease.h"
 
+#include "DecodePool.h"
 #include "Decoder.h"
 
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace image {
 
 AnimationSurfaceProvider::AnimationSurfaceProvider(NotNull<RasterImage*> aImage,
@@ -25,16 +26,32 @@ AnimationSurfaceProvider::AnimationSurfa
   , mDecodingMutex("AnimationSurfaceProvider::mDecoder")
   , mDecoder(aDecoder.get())
   , mFramesMutex("AnimationSurfaceProvider::mFrames")
 {
   MOZ_ASSERT(!mDecoder->IsMetadataDecode(),
              "Use MetadataDecodingTask for metadata decodes");
   MOZ_ASSERT(!mDecoder->IsFirstFrameDecode(),
              "Use DecodedSurfaceProvider for single-frame image decodes");
+
+  // We still produce paletted surfaces for GIF which means the frames are
+  // smaller than one would expect for APNG. This may be removed if/when
+  // bug 1337111 lands and it is enabled by default.
+  size_t pixelSize = aDecoder->GetType() == DecoderType::GIF
+                     ? sizeof(uint8_t) : sizeof(uint32_t);
+
+  // Calculate how many frames we need to decode in this animation before we
+  // enter decode-on-demand mode.
+  IntSize frameSize = aSurfaceKey.Size();
+  size_t threshold =
+    (size_t(gfxPrefs::ImageAnimatedDecodeOnDemandThresholdKB()) * 1024) /
+    (pixelSize * frameSize.width * frameSize.height);
+  size_t batch = gfxPrefs::ImageAnimatedDecodeOnDemandBatchSize();
+
+  mFrames.Initialize(threshold, batch, aCurrentFrame);
 }
 
 AnimationSurfaceProvider::~AnimationSurfaceProvider()
 {
   DropImageReference();
 }
 
 void
@@ -44,58 +61,111 @@ AnimationSurfaceProvider::DropImageRefer
     return;  // Nothing to do.
   }
 
   // RasterImage objects need to be destroyed on the main thread.
   NS_ReleaseOnMainThreadSystemGroup("AnimationSurfaceProvider::mImage",
                                     mImage.forget());
 }
 
+void
+AnimationSurfaceProvider::Reset()
+{
+  // We want to go back to the beginning.
+  bool mayDiscard;
+  bool restartDecoder;
+
+  {
+    MutexAutoLock lock(mFramesMutex);
+
+    // If we have not crossed the threshold, we know we haven't discarded any
+    // frames, and thus we know it is safe move our display index back to the
+    // very beginning. It would be cleaner to let the frame buffer make this
+    // decision inside the AnimationFrameBuffer::Reset method, but if we have
+    // crossed the threshold, we need to hold onto the decoding mutex too. We
+    // should avoid blocking the main thread on the decoder threads.
+    mayDiscard = mFrames.MayDiscard();
+    if (!mayDiscard) {
+      restartDecoder = mFrames.Reset();
+    }
+  }
+
+  if (mayDiscard) {
+    // We are over the threshold and have started discarding old frames. In
+    // that case we need to seize the decoding mutex. Thankfully we know that
+    // we are in the process of decoding at most the batch size frames, so
+    // this should not take too long to acquire.
+    MutexAutoLock lock(mDecodingMutex);
+
+    // Recreate the decoder so we can regenerate the frames again.
+    mDecoder = DecoderFactory::CloneAnimationDecoder(mDecoder);
+    MOZ_ASSERT(mDecoder);
+
+    MutexAutoLock lock2(mFramesMutex);
+    restartDecoder = mFrames.Reset();
+  }
+
+  if (restartDecoder) {
+    DecodePool::Singleton()->AsyncRun(this);
+  }
+}
+
+void
+AnimationSurfaceProvider::Advance(size_t aFrame)
+{
+  bool restartDecoder;
+
+  {
+    // Typical advancement of a frame.
+    MutexAutoLock lock(mFramesMutex);
+    restartDecoder = mFrames.AdvanceTo(aFrame);
+  }
+
+  if (restartDecoder) {
+    DecodePool::Singleton()->AsyncRun(this);
+  }
+}
+
 DrawableFrameRef
 AnimationSurfaceProvider::DrawableRef(size_t aFrame)
 {
   MutexAutoLock lock(mFramesMutex);
 
   if (Availability().IsPlaceholder()) {
     MOZ_ASSERT_UNREACHABLE("Calling DrawableRef() on a placeholder");
     return DrawableFrameRef();
   }
 
-  if (mFrames.IsEmpty()) {
-    MOZ_ASSERT_UNREACHABLE("Calling DrawableRef() when we have no frames");
-    return DrawableFrameRef();
-  }
-
-  // If we don't have that frame, return an empty frame ref.
-  if (aFrame >= mFrames.Length()) {
-    return DrawableFrameRef();
-  }
-
-  // We've got the requested frame. Return it.
-  MOZ_ASSERT(mFrames[aFrame]);
-  return mFrames[aFrame]->DrawableRef();
+  return mFrames.Get(aFrame);
 }
 
 bool
 AnimationSurfaceProvider::IsFinished() const
 {
   MutexAutoLock lock(mFramesMutex);
 
   if (Availability().IsPlaceholder()) {
     MOZ_ASSERT_UNREACHABLE("Calling IsFinished() on a placeholder");
     return false;
   }
 
-  if (mFrames.IsEmpty()) {
+  if (mFrames.Frames().IsEmpty()) {
     MOZ_ASSERT_UNREACHABLE("Calling IsFinished() when we have no frames");
     return false;
   }
 
   // As long as we have at least one finished frame, we're finished.
-  return mFrames[0]->IsFinished();
+  return mFrames.Frames()[0]->IsFinished();
+}
+
+bool
+AnimationSurfaceProvider::IsFullyDecoded() const
+{
+  MutexAutoLock lock(mFramesMutex);
+  return mFrames.SizeKnown() && !mFrames.MayDiscard();
 }
 
 size_t
 AnimationSurfaceProvider::LogicalSizeInBytes() const
 {
   // When decoding animated images, we need at most three live surfaces: the
   // composited surface, the previous composited surface for
   // DisposalMethod::RESTORE_PREVIOUS, and the surface we're currently decoding
@@ -117,132 +187,154 @@ AnimationSurfaceProvider::AddSizeOfExclu
                                                  size_t& aNonHeapSizeOut,
                                                  size_t& aExtHandlesOut)
 {
   // Note that the surface cache lock is already held here, and then we acquire
   // mFramesMutex. For this method, this ordering is unavoidable, which means
   // that we must be careful to always use the same ordering elsewhere.
   MutexAutoLock lock(mFramesMutex);
 
-  for (const RawAccessFrameRef& frame : mFrames) {
-    frame->AddSizeOfExcludingThis(aMallocSizeOf, aHeapSizeOut,
-                                  aNonHeapSizeOut, aExtHandlesOut);
+  for (const RawAccessFrameRef& frame : mFrames.Frames()) {
+    if (frame) {
+      frame->AddSizeOfExcludingThis(aMallocSizeOf, aHeapSizeOut,
+                                    aNonHeapSizeOut, aExtHandlesOut);
+    }
   }
 }
 
 void
 AnimationSurfaceProvider::Run()
 {
   MutexAutoLock lock(mDecodingMutex);
 
-  if (!mDecoder || !mImage) {
+  if (!mDecoder) {
     MOZ_ASSERT_UNREACHABLE("Running after decoding finished?");
     return;
   }
 
   while (true) {
     // Run the decoder.
     LexerResult result = mDecoder->Decode(WrapNotNull(this));
 
     if (result.is<TerminalState>()) {
       // We may have a new frame now, but it's not guaranteed - a decoding
       // failure or truncated data may mean that no new frame got produced.
       // Since we're not sure, rather than call CheckForNewFrameAtYield() here
       // we call CheckForNewFrameAtTerminalState(), which handles both of these
       // possibilities.
-      CheckForNewFrameAtTerminalState();
+      bool continueDecoding = CheckForNewFrameAtTerminalState();
+      FinishDecoding();
 
-      // We're done!
-      FinishDecoding();
+      // Even if it is the last frame, we may not have enough frames buffered
+      // ahead of the current.
+      if (continueDecoding) {
+        MOZ_ASSERT(mDecoder);
+        continue;
+      }
+
       return;
     }
 
     // Notify for the progress we've made so far.
-    if (mDecoder->HasProgress()) {
+    if (mImage && mDecoder->HasProgress()) {
       NotifyProgress(WrapNotNull(mImage), WrapNotNull(mDecoder));
     }
 
     if (result == LexerResult(Yield::NEED_MORE_DATA)) {
       // We can't make any more progress right now. The decoder itself will ensure
       // that we get reenqueued when more data is available; just return for now.
       return;
     }
 
-    // There's new output available - a new frame! Grab it.
+    // There's new output available - a new frame! Grab it. If we don't need any
+    // more for the moment we can break out of the loop.
     MOZ_ASSERT(result == LexerResult(Yield::OUTPUT_AVAILABLE));
-    CheckForNewFrameAtYield();
+    if (!CheckForNewFrameAtYield()) {
+      return;
+    }
   }
 }
 
-void
+bool
 AnimationSurfaceProvider::CheckForNewFrameAtYield()
 {
   mDecodingMutex.AssertCurrentThreadOwns();
   MOZ_ASSERT(mDecoder);
 
   bool justGotFirstFrame = false;
+  bool continueDecoding;
 
   {
     MutexAutoLock lock(mFramesMutex);
 
     // Try to get the new frame from the decoder.
     RawAccessFrameRef frame = mDecoder->GetCurrentFrameRef();
     if (!frame) {
       MOZ_ASSERT_UNREACHABLE("Decoder yielded but didn't produce a frame?");
-      return;
+      return true;
     }
 
     // We should've gotten a different frame than last time.
-    MOZ_ASSERT_IF(!mFrames.IsEmpty(),
-                  mFrames.LastElement().get() != frame.get());
+    MOZ_ASSERT_IF(!mFrames.Frames().IsEmpty(),
+                  mFrames.Frames().LastElement().get() != frame.get());
 
     // Append the new frame to the list.
-    mFrames.AppendElement(Move(frame));
+    continueDecoding = mFrames.Insert(Move(frame));
 
-    if (mFrames.Length() == 1) {
+    // We only want to handle the first frame if it is the first pass for the
+    // animation decoder. The owning image will be cleared after that.
+    size_t frameCount = mFrames.Frames().Length();
+    if (frameCount == 1 && mImage) {
       justGotFirstFrame = true;
     }
   }
 
   if (justGotFirstFrame) {
     AnnounceSurfaceAvailable();
   }
+
+  return continueDecoding;
 }
 
-void
+bool
 AnimationSurfaceProvider::CheckForNewFrameAtTerminalState()
 {
   mDecodingMutex.AssertCurrentThreadOwns();
   MOZ_ASSERT(mDecoder);
 
   bool justGotFirstFrame = false;
+  bool continueDecoding;
 
   {
     MutexAutoLock lock(mFramesMutex);
 
+    // The decoder may or may not have a new frame for us at this point. Avoid
+    // reinserting the same frame again.
     RawAccessFrameRef frame = mDecoder->GetCurrentFrameRef();
-    if (!frame) {
-      return;
-    }
-
-    if (!mFrames.IsEmpty() && mFrames.LastElement().get() == frame.get()) {
-      return;  // We already have this one.
+    if (!frame || (!mFrames.Frames().IsEmpty() &&
+                   mFrames.Frames().LastElement().get() == frame.get())) {
+      return mFrames.MarkComplete();
     }
 
     // Append the new frame to the list.
-    mFrames.AppendElement(Move(frame));
+    mFrames.Insert(Move(frame));
+    continueDecoding = mFrames.MarkComplete();
 
-    if (mFrames.Length() == 1) {
+    // We only want to handle the first frame if it is the first pass for the
+    // animation decoder. The owning image will be cleared after that.
+    if (mFrames.Frames().Length() == 1 && mImage) {
       justGotFirstFrame = true;
     }
   }
 
   if (justGotFirstFrame) {
     AnnounceSurfaceAvailable();
   }
+
+  return continueDecoding;
 }
 
 void
 AnimationSurfaceProvider::AnnounceSurfaceAvailable()
 {
   mFramesMutex.AssertNotCurrentThreadOwns();
   MOZ_ASSERT(mImage);
 
@@ -253,24 +345,37 @@ AnimationSurfaceProvider::AnnounceSurfac
   // acquire the surface cache lock and then mFramesMutex.
   SurfaceCache::SurfaceAvailable(WrapNotNull(this));
 }
 
 void
 AnimationSurfaceProvider::FinishDecoding()
 {
   mDecodingMutex.AssertCurrentThreadOwns();
-  MOZ_ASSERT(mImage);
   MOZ_ASSERT(mDecoder);
 
-  // Send notifications.
-  NotifyDecodeComplete(WrapNotNull(mImage), WrapNotNull(mDecoder));
+  if (mImage) {
+    // Send notifications.
+    NotifyDecodeComplete(WrapNotNull(mImage), WrapNotNull(mDecoder));
+  }
 
   // Destroy our decoder; we don't need it anymore.
-  mDecoder = nullptr;
+  bool mayDiscard;
+  {
+    MutexAutoLock lock(mFramesMutex);
+    mayDiscard = mFrames.MayDiscard();
+  }
+
+  if (mayDiscard) {
+    // Recreate the decoder so we can regenerate the frames again.
+    mDecoder = DecoderFactory::CloneAnimationDecoder(mDecoder);
+    MOZ_ASSERT(mDecoder);
+  } else {
+    mDecoder = nullptr;
+  }
 
   // We don't need a reference to our image anymore, either, and we don't want
   // one. We may be stored in the surface cache for a long time after decoding
   // finishes. If we don't drop our reference to the image, we'll end up
   // keeping it alive as long as we remain in the surface cache, which could
   // greatly extend the image's lifetime - in fact, if the image isn't
   // discardable, it'd result in a leak!
   DropImageReference();
--- a/image/AnimationSurfaceProvider.h
+++ b/image/AnimationSurfaceProvider.h
@@ -8,16 +8,17 @@
  */
 
 #ifndef mozilla_image_AnimationSurfaceProvider_h
 #define mozilla_image_AnimationSurfaceProvider_h
 
 #include "FrameAnimator.h"
 #include "IDecodingTask.h"
 #include "ISurfaceProvider.h"
+#include "AnimationFrameBuffer.h"
 
 namespace mozilla {
 namespace image {
 
 /**
  * An ISurfaceProvider that manages the decoding of animated images and
  * dynamically generates surfaces for the current playback state of the
  * animation.
@@ -40,21 +41,24 @@ public:
   //////////////////////////////////////////////////////////////////////////////
 
 public:
   // We use the ISurfaceProvider constructor of DrawableSurface to indicate that
   // our surfaces are computed lazily.
   DrawableSurface Surface() override { return DrawableSurface(WrapNotNull(this)); }
 
   bool IsFinished() const override;
+  bool IsFullyDecoded() const override;
   size_t LogicalSizeInBytes() const override;
   void AddSizeOfExcludingThis(MallocSizeOf aMallocSizeOf,
                               size_t& aHeapSizeOut,
                               size_t& aNonHeapSizeOut,
                               size_t& aExtHandlesOut) override;
+  void Reset() override;
+  void Advance(size_t aFrame) override;
 
 protected:
   DrawableFrameRef DrawableRef(size_t aFrame) override;
 
   // Animation frames are always locked. This is because we only want to release
   // their memory atomically (due to the surface cache discarding them). If they
   // were unlocked, the OS could end up releasing the memory of random frames
   // from the middle of the animation, which is not worth the complexity of
@@ -74,33 +78,37 @@ public:
   // Full decodes are low priority compared to metadata decodes because they
   // don't block layout or page load.
   TaskPriority Priority() const override { return TaskPriority::eLow; }
 
 private:
   virtual ~AnimationSurfaceProvider();
 
   void DropImageReference();
-  void CheckForNewFrameAtYield();
-  void CheckForNewFrameAtTerminalState();
   void AnnounceSurfaceAvailable();
   void FinishDecoding();
 
+  // @returns Whether or not we should continue decoding.
+  bool CheckForNewFrameAtYield();
+
+  // @returns Whether or not we should restart decoding.
+  bool CheckForNewFrameAtTerminalState();
+
   /// The image associated with our decoder.
   RefPtr<RasterImage> mImage;
 
   /// A mutex to protect mDecoder. Always taken before mFramesMutex.
   mutable Mutex mDecodingMutex;
 
   /// The decoder used to decode this animation.
   RefPtr<Decoder> mDecoder;
 
   /// A mutex to protect mFrames. Always taken after mDecodingMutex.
   mutable Mutex mFramesMutex;
 
   /// The frames of this animation, in order.
-  nsTArray<RawAccessFrameRef> mFrames;
+  AnimationFrameBuffer mFrames;
 };
 
 } // namespace image
 } // namespace mozilla
 
 #endif // mozilla_image_AnimationSurfaceProvider_h