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/. */
7 * SurfaceCache is a service for caching temporary surfaces in imagelib.
10 #include "SurfaceCache.h"
15 #include "ISurfaceProvider.h"
17 #include "LookupResult.h"
18 #include "ShutdownTracker.h"
19 #include "gfx2DGlue.h"
20 #include "gfxPlatform.h"
22 #include "mozilla/Assertions.h"
23 #include "mozilla/Attributes.h"
24 #include "mozilla/CheckedInt.h"
25 #include "mozilla/DebugOnly.h"
26 #include "mozilla/Likely.h"
27 #include "mozilla/RefPtr.h"
28 #include "mozilla/StaticMutex.h"
29 #include "mozilla/StaticPrefs_image.h"
30 #include "mozilla/StaticPtr.h"
31 #include "mozilla/Tuple.h"
32 #include "nsExpirationTracker.h"
33 #include "nsHashKeys.h"
34 #include "nsIMemoryReporter.h"
35 #include "nsRefPtrHashtable.h"
38 #include "Orientation.h"
50 MOZ_DEFINE_MALLOC_SIZE_OF(SurfaceCacheMallocSizeOf
)
53 class SurfaceCacheImpl
;
55 ///////////////////////////////////////////////////////////////////////////////
57 ///////////////////////////////////////////////////////////////////////////////
59 // The single surface cache instance.
60 static StaticRefPtr
<SurfaceCacheImpl
> sInstance
;
62 // The mutex protecting the surface cache.
63 static StaticMutex sInstanceMutex
;
65 ///////////////////////////////////////////////////////////////////////////////
66 // SurfaceCache Implementation
67 ///////////////////////////////////////////////////////////////////////////////
70 * Cost models the cost of storing a surface in the cache. Right now, this is
71 * simply an estimate of the size of the surface in bytes, but in the future it
72 * may be worth taking into account the cost of rematerializing the surface as
77 static Cost
ComputeCost(const IntSize
& aSize
, uint32_t aBytesPerPixel
) {
78 MOZ_ASSERT(aBytesPerPixel
== 1 || aBytesPerPixel
== 4);
79 return aSize
.width
* aSize
.height
* aBytesPerPixel
;
83 * Since we want to be able to make eviction decisions based on cost, we need to
84 * be able to look up the CachedSurface which has a certain cost as well as the
85 * cost associated with a certain CachedSurface. To make this possible, in data
86 * structures we actually store a CostEntry, which contains a weak pointer to
87 * its associated surface.
89 * To make usage of the weak pointer safe, SurfaceCacheImpl always calls
90 * StartTracking after a surface is stored in the cache and StopTracking before
95 CostEntry(NotNull
<CachedSurface
*> aSurface
, Cost aCost
)
96 : mSurface(aSurface
), mCost(aCost
) {}
98 NotNull
<CachedSurface
*> Surface() const { return mSurface
; }
99 Cost
GetCost() const { return mCost
; }
101 bool operator==(const CostEntry
& aOther
) const {
102 return mSurface
== aOther
.mSurface
&& mCost
== aOther
.mCost
;
105 bool operator<(const CostEntry
& aOther
) const {
106 return mCost
< aOther
.mCost
||
107 (mCost
== aOther
.mCost
&& mSurface
< aOther
.mSurface
);
111 NotNull
<CachedSurface
*> mSurface
;
116 * A CachedSurface associates a surface with a key that uniquely identifies that
119 class CachedSurface
{
123 MOZ_DECLARE_REFCOUNTED_TYPENAME(CachedSurface
)
124 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CachedSurface
)
126 explicit CachedSurface(NotNull
<ISurfaceProvider
*> aProvider
)
127 : mProvider(aProvider
), mIsLocked(false) {}
129 DrawableSurface
GetDrawableSurface() const {
130 if (MOZ_UNLIKELY(IsPlaceholder())) {
131 MOZ_ASSERT_UNREACHABLE("Called GetDrawableSurface() on a placeholder");
132 return DrawableSurface();
135 return mProvider
->Surface();
138 void SetLocked(bool aLocked
) {
139 if (IsPlaceholder()) {
140 return; // Can't lock a placeholder.
143 // Update both our state and our provider's state. Some surface providers
144 // are permanently locked; maintaining our own locking state enables us to
145 // respect SetLocked() even when it's meaningless from the provider's
148 mProvider
->SetLocked(aLocked
);
151 bool IsLocked() const {
152 return !IsPlaceholder() && mIsLocked
&& mProvider
->IsLocked();
155 void SetCannotSubstitute() {
156 mProvider
->Availability().SetCannotSubstitute();
158 bool CannotSubstitute() const {
159 return mProvider
->Availability().CannotSubstitute();
162 bool IsPlaceholder() const {
163 return mProvider
->Availability().IsPlaceholder();
165 bool IsDecoded() const { return !IsPlaceholder() && mProvider
->IsFinished(); }
167 ImageKey
GetImageKey() const { return mProvider
->GetImageKey(); }
168 const SurfaceKey
& GetSurfaceKey() const { return mProvider
->GetSurfaceKey(); }
169 nsExpirationState
* GetExpirationState() { return &mExpirationState
; }
171 CostEntry
GetCostEntry() {
172 return image::CostEntry(WrapNotNull(this), mProvider
->LogicalSizeInBytes());
175 size_t ShallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf
) const {
176 return aMallocSizeOf(this) + aMallocSizeOf(mProvider
.get());
179 // A helper type used by SurfaceCacheImpl::CollectSizeOfSurfaces.
180 struct MOZ_STACK_CLASS SurfaceMemoryReport
{
181 SurfaceMemoryReport(nsTArray
<SurfaceMemoryCounter
>& aCounters
,
182 MallocSizeOf aMallocSizeOf
)
183 : mCounters(aCounters
), mMallocSizeOf(aMallocSizeOf
) {}
185 void Add(NotNull
<CachedSurface
*> aCachedSurface
, bool aIsFactor2
) {
186 if (aCachedSurface
->IsPlaceholder()) {
190 // Record the memory used by the ISurfaceProvider. This may not have a
191 // straightforward relationship to the size of the surface that
192 // DrawableRef() returns if the surface is generated dynamically. (i.e.,
193 // for surfaces with PlaybackType::eAnimated.)
194 aCachedSurface
->mProvider
->AddSizeOfExcludingThis(
195 mMallocSizeOf
, [&](ISurfaceProvider::AddSizeOfCbData
& aMetadata
) {
196 SurfaceMemoryCounter
counter(aCachedSurface
->GetSurfaceKey(),
197 aCachedSurface
->IsLocked(),
198 aCachedSurface
->CannotSubstitute(),
199 aIsFactor2
, aMetadata
.mFinished
);
201 counter
.Values().SetDecodedHeap(aMetadata
.mHeapBytes
);
202 counter
.Values().SetDecodedNonHeap(aMetadata
.mNonHeapBytes
);
203 counter
.Values().SetDecodedUnknown(aMetadata
.mUnknownBytes
);
204 counter
.Values().SetExternalHandles(aMetadata
.mExternalHandles
);
205 counter
.Values().SetFrameIndex(aMetadata
.mIndex
);
206 counter
.Values().SetExternalId(aMetadata
.mExternalId
);
207 counter
.Values().SetSurfaceTypes(aMetadata
.mTypes
);
209 mCounters
.AppendElement(counter
);
214 nsTArray
<SurfaceMemoryCounter
>& mCounters
;
215 MallocSizeOf mMallocSizeOf
;
219 nsExpirationState mExpirationState
;
220 NotNull
<RefPtr
<ISurfaceProvider
>> mProvider
;
224 static int64_t AreaOfIntSize(const IntSize
& aSize
) {
225 return static_cast<int64_t>(aSize
.width
) * static_cast<int64_t>(aSize
.height
);
229 * An ImageSurfaceCache is a per-image surface cache. For correctness we must be
230 * able to remove all surfaces associated with an image when the image is
231 * destroyed or invalidated. Since this will happen frequently, it makes sense
232 * to make it cheap by storing the surfaces for each image separately.
234 * ImageSurfaceCache also keeps track of whether its associated image is locked
237 * The cache may also enter "factor of 2" mode which occurs when the number of
238 * surfaces in the cache exceeds the "image.cache.factor2.threshold-surfaces"
239 * pref plus the number of native sizes of the image. When in "factor of 2"
240 * mode, the cache will strongly favour sizes which are a factor of 2 of the
241 * largest native size. It accomplishes this by suggesting a factor of 2 size
242 * when lookups fail and substituting the nearest factor of 2 surface to the
243 * ideal size as the "best" available (as opposed to substitution but not
244 * found). This allows us to minimize memory consumption and CPU time spent
245 * decoding when a website requires many variants of the same surface.
247 class ImageSurfaceCache
{
248 ~ImageSurfaceCache() {}
251 explicit ImageSurfaceCache(const ImageKey aImageKey
)
254 mFactor2Pruned(false),
255 mIsVectorImage(aImageKey
->GetType() == imgIContainer::TYPE_VECTOR
) {}
257 MOZ_DECLARE_REFCOUNTED_TYPENAME(ImageSurfaceCache
)
258 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ImageSurfaceCache
)
260 typedef nsRefPtrHashtable
<nsGenericHashKey
<SurfaceKey
>, CachedSurface
>
263 bool IsEmpty() const { return mSurfaces
.Count() == 0; }
265 size_t ShallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf
) const {
266 size_t bytes
= aMallocSizeOf(this) +
267 mSurfaces
.ShallowSizeOfExcludingThis(aMallocSizeOf
);
268 for (auto iter
= ConstIter(); !iter
.Done(); iter
.Next()) {
269 bytes
+= iter
.UserData()->ShallowSizeOfIncludingThis(aMallocSizeOf
);
274 [[nodiscard
]] bool Insert(NotNull
<CachedSurface
*> aSurface
) {
275 MOZ_ASSERT(!mLocked
|| aSurface
->IsPlaceholder() || aSurface
->IsLocked(),
276 "Inserting an unlocked surface for a locked image");
277 return mSurfaces
.Put(aSurface
->GetSurfaceKey(),
278 RefPtr
<CachedSurface
>{aSurface
}, fallible
);
281 already_AddRefed
<CachedSurface
> Remove(NotNull
<CachedSurface
*> aSurface
) {
282 MOZ_ASSERT(mSurfaces
.GetWeak(aSurface
->GetSurfaceKey()),
283 "Should not be removing a surface we don't have");
285 RefPtr
<CachedSurface
> surface
;
286 mSurfaces
.Remove(aSurface
->GetSurfaceKey(), getter_AddRefs(surface
));
288 return surface
.forget();
291 already_AddRefed
<CachedSurface
> Lookup(const SurfaceKey
& aSurfaceKey
,
293 RefPtr
<CachedSurface
> surface
;
294 mSurfaces
.Get(aSurfaceKey
, getter_AddRefs(surface
));
298 // We don't want to allow factor of 2 mode pruning to release surfaces
299 // for which the callers will accept no substitute.
300 surface
->SetCannotSubstitute();
301 } else if (!mFactor2Mode
) {
302 // If no exact match is found, and this is for use rather than internal
303 // accounting (i.e. insert and removal), we know this will trigger a
304 // decode. Make sure we switch now to factor of 2 mode if necessary.
305 MaybeSetFactor2Mode();
309 return surface
.forget();
313 * @returns A tuple containing the best matching CachedSurface if available,
314 * a MatchType describing how the CachedSurface was selected, and
315 * an IntSize which is the size the caller should choose to decode
316 * at should it attempt to do so.
318 Tuple
<already_AddRefed
<CachedSurface
>, MatchType
, IntSize
> LookupBestMatch(
319 const SurfaceKey
& aIdealKey
) {
320 // Try for an exact match first.
321 RefPtr
<CachedSurface
> exactMatch
;
322 mSurfaces
.Get(aIdealKey
, getter_AddRefs(exactMatch
));
324 if (exactMatch
->IsDecoded()) {
325 return MakeTuple(exactMatch
.forget(), MatchType::EXACT
, IntSize());
327 } else if (!mFactor2Mode
) {
328 // If no exact match is found, and we are not in factor of 2 mode, then
329 // we know that we will trigger a decode because at best we will provide
330 // a substitute. Make sure we switch now to factor of 2 mode if necessary.
331 MaybeSetFactor2Mode();
334 // Try for a best match second, if using compact.
335 IntSize suggestedSize
= SuggestedSize(aIdealKey
.Size());
336 if (suggestedSize
!= aIdealKey
.Size()) {
338 SurfaceKey compactKey
= aIdealKey
.CloneWithSize(suggestedSize
);
339 mSurfaces
.Get(compactKey
, getter_AddRefs(exactMatch
));
340 if (exactMatch
&& exactMatch
->IsDecoded()) {
341 MOZ_ASSERT(suggestedSize
!= aIdealKey
.Size());
342 return MakeTuple(exactMatch
.forget(),
343 MatchType::SUBSTITUTE_BECAUSE_BEST
, suggestedSize
);
348 // There's no perfect match, so find the best match we can.
349 RefPtr
<CachedSurface
> bestMatch
;
350 for (auto iter
= ConstIter(); !iter
.Done(); iter
.Next()) {
351 NotNull
<CachedSurface
*> current
= WrapNotNull(iter
.UserData());
352 const SurfaceKey
& currentKey
= current
->GetSurfaceKey();
354 // We never match a placeholder.
355 if (current
->IsPlaceholder()) {
358 // Matching the playback type and SVG context is required.
359 if (currentKey
.Playback() != aIdealKey
.Playback() ||
360 currentKey
.SVGContext() != aIdealKey
.SVGContext()) {
363 // Matching the flags is required.
364 if (currentKey
.Flags() != aIdealKey
.Flags()) {
367 // Anything is better than nothing! (Within the constraints we just
368 // checked, of course.)
374 MOZ_ASSERT(bestMatch
, "Should have a current best match");
376 // Always prefer completely decoded surfaces.
377 bool bestMatchIsDecoded
= bestMatch
->IsDecoded();
378 if (bestMatchIsDecoded
&& !current
->IsDecoded()) {
381 if (!bestMatchIsDecoded
&& current
->IsDecoded()) {
386 SurfaceKey bestMatchKey
= bestMatch
->GetSurfaceKey();
387 if (CompareArea(aIdealKey
.Size(), bestMatchKey
.Size(),
388 currentKey
.Size())) {
396 // No exact match, neither ideal nor factor of 2.
397 MOZ_ASSERT(suggestedSize
!= bestMatch
->GetSurfaceKey().Size(),
398 "No exact match despite the fact the sizes match!");
399 matchType
= MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND
;
400 } else if (exactMatch
!= bestMatch
) {
401 // The exact match is still decoding, but we found a substitute.
402 matchType
= MatchType::SUBSTITUTE_BECAUSE_PENDING
;
403 } else if (aIdealKey
.Size() != bestMatch
->GetSurfaceKey().Size()) {
404 // The best factor of 2 match is still decoding, but the best we've got.
405 MOZ_ASSERT(suggestedSize
!= aIdealKey
.Size());
406 MOZ_ASSERT(mFactor2Mode
|| mIsVectorImage
);
407 matchType
= MatchType::SUBSTITUTE_BECAUSE_BEST
;
409 // The exact match is still decoding, but it's the best we've got.
410 matchType
= MatchType::EXACT
;
414 // We found an "exact match"; it must have been a placeholder.
415 MOZ_ASSERT(exactMatch
->IsPlaceholder());
416 matchType
= MatchType::PENDING
;
418 // We couldn't find an exact match *or* a substitute.
419 matchType
= MatchType::NOT_FOUND
;
423 return MakeTuple(bestMatch
.forget(), matchType
, suggestedSize
);
426 void MaybeSetFactor2Mode() {
427 MOZ_ASSERT(!mFactor2Mode
);
429 // Typically an image cache will not have too many size-varying surfaces, so
430 // if we exceed the given threshold, we should consider using a subset.
431 int32_t thresholdSurfaces
=
432 StaticPrefs::image_cache_factor2_threshold_surfaces();
433 if (thresholdSurfaces
< 0 ||
434 mSurfaces
.Count() <= static_cast<uint32_t>(thresholdSurfaces
)) {
438 // Determine how many native surfaces this image has. If it is zero, and it
439 // is a vector image, then we should impute a single native size. Otherwise,
440 // it may be zero because we don't know yet, or the image has an error, or
441 // it isn't supported.
442 auto first
= ConstIter();
443 NotNull
<CachedSurface
*> current
= WrapNotNull(first
.UserData());
444 Image
* image
= static_cast<Image
*>(current
->GetImageKey());
445 size_t nativeSizes
= image
->GetNativeSizesLength();
446 if (mIsVectorImage
) {
447 MOZ_ASSERT(nativeSizes
== 0);
449 } else if (nativeSizes
== 0) {
453 // Increase the threshold by the number of native sizes. This ensures that
454 // we do not prevent decoding of the image at all its native sizes. It does
455 // not guarantee we will provide a surface at that size however (i.e. many
456 // other sized surfaces are requested, in addition to the native sizes).
457 thresholdSurfaces
+= nativeSizes
;
458 if (mSurfaces
.Count() <= static_cast<uint32_t>(thresholdSurfaces
)) {
462 // Get our native size. While we know the image should be fully decoded,
463 // if it is an SVG, it is valid to have a zero size. We can't do compacting
464 // in that case because we need to know the width/height ratio to define a
467 if (NS_FAILED(image
->GetWidth(&nativeSize
.width
)) ||
468 NS_FAILED(image
->GetHeight(&nativeSize
.height
)) ||
469 nativeSize
.IsEmpty()) {
473 // We have a valid size, we can change modes.
477 template <typename Function
>
478 void Prune(Function
&& aRemoveCallback
) {
479 if (!mFactor2Mode
|| mFactor2Pruned
) {
483 // Attempt to discard any surfaces which are not factor of 2 and the best
484 // factor of 2 match exists.
485 bool hasNotFactorSize
= false;
486 for (auto iter
= mSurfaces
.Iter(); !iter
.Done(); iter
.Next()) {
487 NotNull
<CachedSurface
*> current
= WrapNotNull(iter
.UserData());
488 const SurfaceKey
& currentKey
= current
->GetSurfaceKey();
489 const IntSize
& currentSize
= currentKey
.Size();
491 // First we check if someone requested this size and would not accept
492 // an alternatively sized surface.
493 if (current
->CannotSubstitute()) {
497 // Next we find the best factor of 2 size for this surface. If this
498 // surface is a factor of 2 size, then we want to keep it.
499 IntSize bestSize
= SuggestedSize(currentSize
);
500 if (bestSize
== currentSize
) {
504 // Check the cache for a surface with the same parameters except for the
505 // size which uses the closest factor of 2 size.
506 SurfaceKey compactKey
= currentKey
.CloneWithSize(bestSize
);
507 RefPtr
<CachedSurface
> compactMatch
;
508 mSurfaces
.Get(compactKey
, getter_AddRefs(compactMatch
));
509 if (compactMatch
&& compactMatch
->IsDecoded()) {
510 aRemoveCallback(current
);
513 hasNotFactorSize
= true;
517 // We have no surfaces that are not factor of 2 sized, so we can stop
518 // pruning henceforth, because we avoid the insertion of new surfaces that
519 // don't match our sizing set (unless the caller won't accept a
521 if (!hasNotFactorSize
) {
522 mFactor2Pruned
= true;
525 // We should never leave factor of 2 mode due to pruning in of itself, but
526 // if we discarded surfaces due to the volatile buffers getting released,
531 IntSize
SuggestedSize(const IntSize
& aSize
) const {
532 IntSize suggestedSize
= SuggestedSizeInternal(aSize
);
533 if (mIsVectorImage
) {
534 suggestedSize
= SurfaceCache::ClampVectorSize(suggestedSize
);
536 return suggestedSize
;
539 IntSize
SuggestedSizeInternal(const IntSize
& aSize
) const {
540 // When not in factor of 2 mode, we can always decode at the given size.
545 // We cannot enter factor of 2 mode unless we have a minimum number of
546 // surfaces, and we should have left it if the cache was emptied.
547 if (MOZ_UNLIKELY(IsEmpty())) {
548 MOZ_ASSERT_UNREACHABLE("Should not be empty and in factor of 2 mode!");
552 // This bit of awkwardness gets the largest native size of the image.
553 auto iter
= ConstIter();
554 NotNull
<CachedSurface
*> firstSurface
= WrapNotNull(iter
.UserData());
555 Image
* image
= static_cast<Image
*>(firstSurface
->GetImageKey());
557 if (NS_FAILED(image
->GetWidth(&factorSize
.width
)) ||
558 NS_FAILED(image
->GetHeight(&factorSize
.height
)) ||
559 factorSize
.IsEmpty()) {
560 // We should not have entered factor of 2 mode without a valid size, and
561 // several successfully decoded surfaces. Note that valid vector images
562 // may have a default size of 0x0, and those are not yet supported.
563 MOZ_ASSERT_UNREACHABLE("Expected valid native size!");
566 if (image
->GetOrientation().SwapsWidthAndHeight() &&
567 image
->HandledOrientation()) {
568 std::swap(factorSize
.width
, factorSize
.height
);
571 if (mIsVectorImage
) {
572 // Ensure the aspect ratio matches the native size before forcing the
573 // caller to accept a factor of 2 size. The difference between the aspect
576 // delta = nativeWidth/nativeHeight - desiredWidth/desiredHeight
578 // delta*nativeHeight*desiredHeight = nativeWidth*desiredHeight
579 // - desiredWidth*nativeHeight
581 // Using the maximum accepted delta as a constant, we can avoid the
582 // floating point division and just compare after some integer ops.
584 factorSize
.width
* aSize
.height
- aSize
.width
* factorSize
.height
;
585 int32_t maxDelta
= (factorSize
.height
* aSize
.height
) >> 4;
586 if (delta
> maxDelta
|| delta
< -maxDelta
) {
590 // If the requested size is bigger than the native size, we actually need
591 // to grow the native size instead of shrinking it.
592 if (factorSize
.width
< aSize
.width
) {
594 IntSize
candidate(factorSize
.width
* 2, factorSize
.height
* 2);
595 if (!SurfaceCache::IsLegalSize(candidate
)) {
599 factorSize
= candidate
;
600 } while (factorSize
.width
< aSize
.width
);
605 // Otherwise we can find the best fit as normal.
608 // Start with the native size as the best first guess.
609 IntSize bestSize
= factorSize
;
610 factorSize
.width
/= 2;
611 factorSize
.height
/= 2;
613 while (!factorSize
.IsEmpty()) {
614 if (!CompareArea(aSize
, bestSize
, factorSize
)) {
615 // This size is not better than the last. Since we proceed from largest
616 // to smallest, we know that the next size will not be better if the
617 // previous size was rejected. Break early.
621 // The current factor of 2 size is better than the last selected size.
622 bestSize
= factorSize
;
623 factorSize
.width
/= 2;
624 factorSize
.height
/= 2;
630 bool CompareArea(const IntSize
& aIdealSize
, const IntSize
& aBestSize
,
631 const IntSize
& aSize
) const {
632 // Compare sizes. We use an area-based heuristic here instead of computing a
633 // truly optimal answer, since it seems very unlikely to make a difference
634 // for realistic sizes.
635 int64_t idealArea
= AreaOfIntSize(aIdealSize
);
636 int64_t currentArea
= AreaOfIntSize(aSize
);
637 int64_t bestMatchArea
= AreaOfIntSize(aBestSize
);
639 // If the best match is smaller than the ideal size, prefer bigger sizes.
640 if (bestMatchArea
< idealArea
) {
641 if (currentArea
> bestMatchArea
) {
647 // Other, prefer sizes closer to the ideal size, but still not smaller.
648 if (idealArea
<= currentArea
&& currentArea
< bestMatchArea
) {
652 // This surface isn't an improvement over the current best match.
656 template <typename Function
>
657 void CollectSizeOfSurfaces(nsTArray
<SurfaceMemoryCounter
>& aCounters
,
658 MallocSizeOf aMallocSizeOf
,
659 Function
&& aRemoveCallback
) {
660 CachedSurface::SurfaceMemoryReport
report(aCounters
, aMallocSizeOf
);
661 for (auto iter
= mSurfaces
.Iter(); !iter
.Done(); iter
.Next()) {
662 NotNull
<CachedSurface
*> surface
= WrapNotNull(iter
.UserData());
664 // We don't need the drawable surface for ourselves, but adding a surface
665 // to the report will trigger this indirectly. If the surface was
666 // discarded by the OS because it was in volatile memory, we should remove
667 // it from the cache immediately rather than include it in the report.
668 DrawableSurface drawableSurface
;
669 if (!surface
->IsPlaceholder()) {
670 drawableSurface
= surface
->GetDrawableSurface();
671 if (!drawableSurface
) {
672 aRemoveCallback(surface
);
678 const IntSize
& size
= surface
->GetSurfaceKey().Size();
679 bool factor2Size
= false;
681 factor2Size
= (size
== SuggestedSize(size
));
683 report
.Add(surface
, factor2Size
);
689 SurfaceTable::Iterator
ConstIter() const { return mSurfaces
.ConstIter(); }
690 uint32_t Count() const { return mSurfaces
.Count(); }
692 void SetLocked(bool aLocked
) { mLocked
= aLocked
; }
693 bool IsLocked() const { return mLocked
; }
696 void AfterMaybeRemove() {
697 if (IsEmpty() && mFactor2Mode
) {
698 // The last surface for this cache was removed. This can happen if the
699 // surface was stored in a volatile buffer and got purged, or the surface
700 // expired from the cache. If the cache itself lingers for some reason
701 // (e.g. in the process of performing a lookup, the cache itself is
702 // locked), then we need to reset the factor of 2 state because it
703 // requires at least one surface present to get the native size
704 // information from the image.
705 mFactor2Mode
= mFactor2Pruned
= false;
709 SurfaceTable mSurfaces
;
713 // True in "factor of 2" mode.
716 // True if all non-factor of 2 surfaces have been removed from the cache. Note
717 // that this excludes unsubstitutable sizes.
720 // True if the surfaces are produced from a vector image. If so, it must match
721 // the aspect ratio when using factor of 2 mode.
726 * SurfaceCacheImpl is responsible for determining which surfaces will be cached
727 * and managing the surface cache data structures. Rather than interact with
728 * SurfaceCacheImpl directly, client code interacts with SurfaceCache, which
729 * maintains high-level invariants and encapsulates the details of the surface
730 * cache's implementation.
732 class SurfaceCacheImpl final
: public nsIMemoryReporter
{
736 SurfaceCacheImpl(uint32_t aSurfaceCacheExpirationTimeMS
,
737 uint32_t aSurfaceCacheDiscardFactor
,
738 uint32_t aSurfaceCacheSize
)
739 : mExpirationTracker(aSurfaceCacheExpirationTimeMS
),
740 mMemoryPressureObserver(new MemoryPressureObserver
),
741 mDiscardFactor(aSurfaceCacheDiscardFactor
),
742 mMaxCost(aSurfaceCacheSize
),
743 mAvailableCost(aSurfaceCacheSize
),
746 mAlreadyPresentCount(0),
747 mTableFailureCount(0),
748 mTrackingFailureCount(0) {
749 nsCOMPtr
<nsIObserverService
> os
= services::GetObserverService();
751 os
->AddObserver(mMemoryPressureObserver
, "memory-pressure", false);
756 virtual ~SurfaceCacheImpl() {
757 nsCOMPtr
<nsIObserverService
> os
= services::GetObserverService();
759 os
->RemoveObserver(mMemoryPressureObserver
, "memory-pressure");
762 UnregisterWeakMemoryReporter(this);
766 void InitMemoryReporter() { RegisterWeakMemoryReporter(this); }
768 InsertOutcome
Insert(NotNull
<ISurfaceProvider
*> aProvider
, bool aSetAvailable
,
769 const StaticMutexAutoLock
& aAutoLock
) {
770 // If this is a duplicate surface, refuse to replace the original.
771 // XXX(seth): Calling Lookup() and then RemoveEntry() does the lookup
772 // twice. We'll make this more efficient in bug 1185137.
773 LookupResult result
=
774 Lookup(aProvider
->GetImageKey(), aProvider
->GetSurfaceKey(), aAutoLock
,
775 /* aMarkUsed = */ false);
776 if (MOZ_UNLIKELY(result
)) {
777 mAlreadyPresentCount
++;
778 return InsertOutcome::FAILURE_ALREADY_PRESENT
;
781 if (result
.Type() == MatchType::PENDING
) {
782 RemoveEntry(aProvider
->GetImageKey(), aProvider
->GetSurfaceKey(),
786 MOZ_ASSERT(result
.Type() == MatchType::NOT_FOUND
||
787 result
.Type() == MatchType::PENDING
,
788 "A LookupResult with no surface should be NOT_FOUND or PENDING");
790 // If this is bigger than we can hold after discarding everything we can,
791 // refuse to cache it.
792 Cost cost
= aProvider
->LogicalSizeInBytes();
793 if (MOZ_UNLIKELY(!CanHoldAfterDiscarding(cost
))) {
795 return InsertOutcome::FAILURE
;
798 // Remove elements in order of cost until we can fit this in the cache. Note
799 // that locked surfaces aren't in mCosts, so we never remove them here.
800 while (cost
> mAvailableCost
) {
801 MOZ_ASSERT(!mCosts
.IsEmpty(),
802 "Removed everything and it still won't fit");
803 Remove(mCosts
.LastElement().Surface(), /* aStopTracking */ true,
807 // Locate the appropriate per-image cache. If there's not an existing cache
808 // for this image, create it.
809 const ImageKey imageKey
= aProvider
->GetImageKey();
810 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(imageKey
);
812 cache
= new ImageSurfaceCache(imageKey
);
813 if (!mImageCaches
.Put(aProvider
->GetImageKey(), RefPtr
{cache
},
815 mTableFailureCount
++;
816 return InsertOutcome::FAILURE
;
820 // If we were asked to mark the cache entry available, do so.
822 aProvider
->Availability().SetAvailable();
825 auto surface
= MakeNotNull
<RefPtr
<CachedSurface
>>(aProvider
);
827 // We require that locking succeed if the image is locked and we're not
828 // inserting a placeholder; the caller may need to know this to handle
830 bool mustLock
= cache
->IsLocked() && !surface
->IsPlaceholder();
832 surface
->SetLocked(true);
833 if (!surface
->IsLocked()) {
834 return InsertOutcome::FAILURE
;
839 MOZ_ASSERT(cost
<= mAvailableCost
, "Inserting despite too large a cost");
840 if (!cache
->Insert(surface
)) {
841 mTableFailureCount
++;
843 surface
->SetLocked(false);
845 return InsertOutcome::FAILURE
;
848 if (MOZ_UNLIKELY(!StartTracking(surface
, aAutoLock
))) {
849 MOZ_ASSERT(!mustLock
);
850 Remove(surface
, /* aStopTracking */ false, aAutoLock
);
851 return InsertOutcome::FAILURE
;
854 return InsertOutcome::SUCCESS
;
857 void Remove(NotNull
<CachedSurface
*> aSurface
, bool aStopTracking
,
858 const StaticMutexAutoLock
& aAutoLock
) {
859 ImageKey imageKey
= aSurface
->GetImageKey();
861 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(imageKey
);
862 MOZ_ASSERT(cache
, "Shouldn't try to remove a surface with no image cache");
864 // If the surface was not a placeholder, tell its image that we discarded
866 if (!aSurface
->IsPlaceholder()) {
867 static_cast<Image
*>(imageKey
)->OnSurfaceDiscarded(
868 aSurface
->GetSurfaceKey());
871 // If we failed during StartTracking, we can skip this step.
873 StopTracking(aSurface
, /* aIsTracked */ true, aAutoLock
);
876 // Individual surfaces must be freed outside the lock.
877 mCachedSurfacesDiscard
.AppendElement(cache
->Remove(aSurface
));
879 MaybeRemoveEmptyCache(imageKey
, cache
);
882 bool StartTracking(NotNull
<CachedSurface
*> aSurface
,
883 const StaticMutexAutoLock
& aAutoLock
) {
884 CostEntry costEntry
= aSurface
->GetCostEntry();
885 MOZ_ASSERT(costEntry
.GetCost() <= mAvailableCost
,
886 "Cost too large and the caller didn't catch it");
888 if (aSurface
->IsLocked()) {
889 mLockedCost
+= costEntry
.GetCost();
890 MOZ_ASSERT(mLockedCost
<= mMaxCost
, "Locked more than we can hold?");
892 if (NS_WARN_IF(!mCosts
.InsertElementSorted(costEntry
, fallible
))) {
893 mTrackingFailureCount
++;
897 // This may fail during XPCOM shutdown, so we need to ensure the object is
898 // tracked before calling RemoveObject in StopTracking.
899 nsresult rv
= mExpirationTracker
.AddObjectLocked(aSurface
, aAutoLock
);
900 if (NS_WARN_IF(NS_FAILED(rv
))) {
901 DebugOnly
<bool> foundInCosts
= mCosts
.RemoveElementSorted(costEntry
);
902 MOZ_ASSERT(foundInCosts
, "Lost track of costs for this surface");
903 mTrackingFailureCount
++;
908 mAvailableCost
-= costEntry
.GetCost();
912 void StopTracking(NotNull
<CachedSurface
*> aSurface
, bool aIsTracked
,
913 const StaticMutexAutoLock
& aAutoLock
) {
914 CostEntry costEntry
= aSurface
->GetCostEntry();
916 if (aSurface
->IsLocked()) {
917 MOZ_ASSERT(mLockedCost
>= costEntry
.GetCost(), "Costs don't balance");
918 mLockedCost
-= costEntry
.GetCost();
919 // XXX(seth): It'd be nice to use an O(log n) lookup here. This is O(n).
920 MOZ_ASSERT(!mCosts
.Contains(costEntry
),
921 "Shouldn't have a cost entry for a locked surface");
923 if (MOZ_LIKELY(aSurface
->GetExpirationState()->IsTracked())) {
924 MOZ_ASSERT(aIsTracked
, "Expiration-tracking a surface unexpectedly!");
925 mExpirationTracker
.RemoveObjectLocked(aSurface
, aAutoLock
);
927 // Our call to AddObject must have failed in StartTracking; most likely
928 // we're in XPCOM shutdown right now.
929 MOZ_ASSERT(!aIsTracked
, "Not expiration-tracking an unlocked surface!");
932 DebugOnly
<bool> foundInCosts
= mCosts
.RemoveElementSorted(costEntry
);
933 MOZ_ASSERT(foundInCosts
, "Lost track of costs for this surface");
936 mAvailableCost
+= costEntry
.GetCost();
937 MOZ_ASSERT(mAvailableCost
<= mMaxCost
,
938 "More available cost than we started with");
941 LookupResult
Lookup(const ImageKey aImageKey
, const SurfaceKey
& aSurfaceKey
,
942 const StaticMutexAutoLock
& aAutoLock
, bool aMarkUsed
) {
943 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
945 // No cached surfaces for this image.
946 return LookupResult(MatchType::NOT_FOUND
);
949 RefPtr
<CachedSurface
> surface
= cache
->Lookup(aSurfaceKey
, aMarkUsed
);
951 // Lookup in the per-image cache missed.
952 return LookupResult(MatchType::NOT_FOUND
);
955 if (surface
->IsPlaceholder()) {
956 return LookupResult(MatchType::PENDING
);
959 DrawableSurface drawableSurface
= surface
->GetDrawableSurface();
960 if (!drawableSurface
) {
961 // The surface was released by the operating system. Remove the cache
963 Remove(WrapNotNull(surface
), /* aStopTracking */ true, aAutoLock
);
964 return LookupResult(MatchType::NOT_FOUND
);
968 !MarkUsed(WrapNotNull(surface
), WrapNotNull(cache
), aAutoLock
)) {
969 Remove(WrapNotNull(surface
), /* aStopTracking */ false, aAutoLock
);
970 return LookupResult(MatchType::NOT_FOUND
);
973 MOZ_ASSERT(surface
->GetSurfaceKey() == aSurfaceKey
,
974 "Lookup() not returning an exact match?");
975 return LookupResult(std::move(drawableSurface
), MatchType::EXACT
);
978 LookupResult
LookupBestMatch(const ImageKey aImageKey
,
979 const SurfaceKey
& aSurfaceKey
,
980 const StaticMutexAutoLock
& aAutoLock
,
982 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
984 // No cached surfaces for this image.
986 MatchType::NOT_FOUND
,
987 SurfaceCache::ClampSize(aImageKey
, aSurfaceKey
.Size()));
990 // Repeatedly look up the best match, trying again if the resulting surface
991 // has been freed by the operating system, until we can either lock a
992 // surface for drawing or there are no matching surfaces left.
993 // XXX(seth): This is O(N^2), but N is expected to be very small. If we
994 // encounter a performance problem here we can revisit this.
996 RefPtr
<CachedSurface
> surface
;
997 DrawableSurface drawableSurface
;
998 MatchType matchType
= MatchType::NOT_FOUND
;
999 IntSize suggestedSize
;
1001 Tie(surface
, matchType
, suggestedSize
) =
1002 cache
->LookupBestMatch(aSurfaceKey
);
1005 return LookupResult(
1006 matchType
, suggestedSize
); // Lookup in the per-image cache missed.
1009 drawableSurface
= surface
->GetDrawableSurface();
1010 if (drawableSurface
) {
1014 // The surface was released by the operating system. Remove the cache
1016 Remove(WrapNotNull(surface
), /* aStopTracking */ true, aAutoLock
);
1019 MOZ_ASSERT_IF(matchType
== MatchType::EXACT
,
1020 surface
->GetSurfaceKey() == aSurfaceKey
);
1022 matchType
== MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND
||
1023 matchType
== MatchType::SUBSTITUTE_BECAUSE_PENDING
,
1024 surface
->GetSurfaceKey().SVGContext() == aSurfaceKey
.SVGContext() &&
1025 surface
->GetSurfaceKey().Playback() == aSurfaceKey
.Playback() &&
1026 surface
->GetSurfaceKey().Flags() == aSurfaceKey
.Flags());
1028 if (matchType
== MatchType::EXACT
||
1029 matchType
== MatchType::SUBSTITUTE_BECAUSE_BEST
) {
1031 !MarkUsed(WrapNotNull(surface
), WrapNotNull(cache
), aAutoLock
)) {
1032 Remove(WrapNotNull(surface
), /* aStopTracking */ false, aAutoLock
);
1036 return LookupResult(std::move(drawableSurface
), matchType
, suggestedSize
);
1039 bool CanHold(const Cost aCost
) const { return aCost
<= mMaxCost
; }
1041 size_t MaximumCapacity() const { return size_t(mMaxCost
); }
1043 void SurfaceAvailable(NotNull
<ISurfaceProvider
*> aProvider
,
1044 const StaticMutexAutoLock
& aAutoLock
) {
1045 if (!aProvider
->Availability().IsPlaceholder()) {
1046 MOZ_ASSERT_UNREACHABLE("Calling SurfaceAvailable on non-placeholder");
1050 // Reinsert the provider, requesting that Insert() mark it available. This
1051 // may or may not succeed, depending on whether some other decoder has
1052 // beaten us to the punch and inserted a non-placeholder version of this
1053 // surface first, but it's fine either way.
1054 // XXX(seth): This could be implemented more efficiently; we should be able
1055 // to just update our data structures without reinserting.
1056 Insert(aProvider
, /* aSetAvailable = */ true, aAutoLock
);
1059 void LockImage(const ImageKey aImageKey
) {
1060 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1062 cache
= new ImageSurfaceCache(aImageKey
);
1063 mImageCaches
.Put(aImageKey
, RefPtr
{cache
});
1066 cache
->SetLocked(true);
1068 // We don't relock this image's existing surfaces right away; instead, the
1069 // image should arrange for Lookup() to touch them if they are still useful.
1072 void UnlockImage(const ImageKey aImageKey
,
1073 const StaticMutexAutoLock
& aAutoLock
) {
1074 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1075 if (!cache
|| !cache
->IsLocked()) {
1076 return; // Already unlocked.
1079 cache
->SetLocked(false);
1080 DoUnlockSurfaces(WrapNotNull(cache
), /* aStaticOnly = */ false, aAutoLock
);
1083 void UnlockEntries(const ImageKey aImageKey
,
1084 const StaticMutexAutoLock
& aAutoLock
) {
1085 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1086 if (!cache
|| !cache
->IsLocked()) {
1087 return; // Already unlocked.
1090 // (Note that we *don't* unlock the per-image cache here; that's the
1091 // difference between this and UnlockImage.)
1092 DoUnlockSurfaces(WrapNotNull(cache
),
1094 !StaticPrefs::image_mem_animated_discardable_AtStartup(),
1098 already_AddRefed
<ImageSurfaceCache
> RemoveImage(
1099 const ImageKey aImageKey
, const StaticMutexAutoLock
& aAutoLock
) {
1100 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1102 return nullptr; // No cached surfaces for this image, so nothing to do.
1105 // Discard all of the cached surfaces for this image.
1106 // XXX(seth): This is O(n^2) since for each item in the cache we are
1107 // removing an element from the costs array. Since n is expected to be
1108 // small, performance should be good, but if usage patterns change we should
1109 // change the data structure used for mCosts.
1110 for (auto iter
= cache
->ConstIter(); !iter
.Done(); iter
.Next()) {
1111 StopTracking(WrapNotNull(iter
.UserData()),
1112 /* aIsTracked */ true, aAutoLock
);
1115 // The per-image cache isn't needed anymore, so remove it as well.
1116 // This implicitly unlocks the image if it was locked.
1117 mImageCaches
.Remove(aImageKey
);
1119 // Since we did not actually remove any of the surfaces from the cache
1120 // itself, only stopped tracking them, we should free it outside the lock.
1121 return cache
.forget();
1124 void PruneImage(const ImageKey aImageKey
,
1125 const StaticMutexAutoLock
& aAutoLock
) {
1126 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1128 return; // No cached surfaces for this image, so nothing to do.
1131 cache
->Prune([this, &aAutoLock
](NotNull
<CachedSurface
*> aSurface
) -> void {
1132 StopTracking(aSurface
, /* aIsTracked */ true, aAutoLock
);
1133 // Individual surfaces must be freed outside the lock.
1134 mCachedSurfacesDiscard
.AppendElement(aSurface
);
1137 MaybeRemoveEmptyCache(aImageKey
, cache
);
1140 void DiscardAll(const StaticMutexAutoLock
& aAutoLock
) {
1141 // Remove in order of cost because mCosts is an array and the other data
1142 // structures are all hash tables. Note that locked surfaces are not
1143 // removed, since they aren't present in mCosts.
1144 while (!mCosts
.IsEmpty()) {
1145 Remove(mCosts
.LastElement().Surface(), /* aStopTracking */ true,
1150 void DiscardForMemoryPressure(const StaticMutexAutoLock
& aAutoLock
) {
1151 // Compute our discardable cost. Since locked surfaces aren't discardable,
1153 const Cost discardableCost
= (mMaxCost
- mAvailableCost
) - mLockedCost
;
1154 MOZ_ASSERT(discardableCost
<= mMaxCost
, "Discardable cost doesn't add up");
1156 // Our target is to raise our available cost by (1 / mDiscardFactor) of our
1157 // discardable cost - in other words, we want to end up with about
1158 // (discardableCost / mDiscardFactor) fewer bytes stored in the surface
1159 // cache after we're done.
1160 const Cost targetCost
= mAvailableCost
+ (discardableCost
/ mDiscardFactor
);
1162 if (targetCost
> mMaxCost
- mLockedCost
) {
1163 MOZ_ASSERT_UNREACHABLE("Target cost is more than we can discard");
1164 DiscardAll(aAutoLock
);
1168 // Discard surfaces until we've reduced our cost to our target cost.
1169 while (mAvailableCost
< targetCost
) {
1170 MOZ_ASSERT(!mCosts
.IsEmpty(), "Removed everything and still not done");
1171 Remove(mCosts
.LastElement().Surface(), /* aStopTracking */ true,
1176 void TakeDiscard(nsTArray
<RefPtr
<CachedSurface
>>& aDiscard
,
1177 const StaticMutexAutoLock
& aAutoLock
) {
1178 MOZ_ASSERT(aDiscard
.IsEmpty());
1179 aDiscard
= std::move(mCachedSurfacesDiscard
);
1182 void LockSurface(NotNull
<CachedSurface
*> aSurface
,
1183 const StaticMutexAutoLock
& aAutoLock
) {
1184 if (aSurface
->IsPlaceholder() || aSurface
->IsLocked()) {
1188 StopTracking(aSurface
, /* aIsTracked */ true, aAutoLock
);
1190 // Lock the surface. This can fail.
1191 aSurface
->SetLocked(true);
1192 DebugOnly
<bool> tracked
= StartTracking(aSurface
, aAutoLock
);
1193 MOZ_ASSERT(tracked
);
1196 size_t ShallowSizeOfIncludingThis(
1197 MallocSizeOf aMallocSizeOf
, const StaticMutexAutoLock
& aAutoLock
) const {
1199 aMallocSizeOf(this) + mCosts
.ShallowSizeOfExcludingThis(aMallocSizeOf
) +
1200 mImageCaches
.ShallowSizeOfExcludingThis(aMallocSizeOf
) +
1201 mCachedSurfacesDiscard
.ShallowSizeOfExcludingThis(aMallocSizeOf
) +
1202 mExpirationTracker
.ShallowSizeOfExcludingThis(aMallocSizeOf
);
1203 for (auto iter
= mImageCaches
.ConstIter(); !iter
.Done(); iter
.Next()) {
1204 bytes
+= iter
.UserData()->ShallowSizeOfIncludingThis(aMallocSizeOf
);
1210 CollectReports(nsIHandleReportCallback
* aHandleReport
, nsISupports
* aData
,
1211 bool aAnonymize
) override
{
1212 StaticMutexAutoLock
lock(sInstanceMutex
);
1214 uint32_t lockedImageCount
= 0;
1215 uint32_t totalSurfaceCount
= 0;
1216 uint32_t lockedSurfaceCount
= 0;
1217 for (auto iter
= mImageCaches
.ConstIter(); !iter
.Done(); iter
.Next()) {
1218 totalSurfaceCount
+= iter
.UserData()->Count();
1219 if (iter
.UserData()->IsLocked()) {
1222 for (auto surfIter
= iter
.UserData()->ConstIter(); !surfIter
.Done();
1224 if (surfIter
.UserData()->IsLocked()) {
1225 ++lockedSurfaceCount
;
1231 // We have explicit memory reporting for the surface cache which is more
1232 // accurate than the cost metrics we report here, but these metrics are
1233 // still useful to report, since they control the cache's behavior.
1235 "explicit/images/cache/overhead", KIND_HEAP
, UNITS_BYTES
,
1236 ShallowSizeOfIncludingThis(SurfaceCacheMallocSizeOf
, lock
),
1237 "Memory used by the surface cache data structures, excluding surface data.");
1240 "imagelib-surface-cache-estimated-total",
1241 KIND_OTHER
, UNITS_BYTES
, (mMaxCost
- mAvailableCost
),
1242 "Estimated total memory used by the imagelib surface cache.");
1245 "imagelib-surface-cache-estimated-locked",
1246 KIND_OTHER
, UNITS_BYTES
, mLockedCost
,
1247 "Estimated memory used by locked surfaces in the imagelib surface cache.");
1250 "imagelib-surface-cache-tracked-cost-count",
1251 KIND_OTHER
, UNITS_COUNT
, mCosts
.Length(),
1252 "Total number of surfaces tracked for cost (and expiry) in the imagelib surface cache.");
1255 "imagelib-surface-cache-tracked-expiry-count",
1256 KIND_OTHER
, UNITS_COUNT
, mExpirationTracker
.Length(lock
),
1257 "Total number of surfaces tracked for expiry (and cost) in the imagelib surface cache.");
1260 "imagelib-surface-cache-image-count",
1261 KIND_OTHER
, UNITS_COUNT
, mImageCaches
.Count(),
1262 "Total number of images in the imagelib surface cache.");
1265 "imagelib-surface-cache-locked-image-count",
1266 KIND_OTHER
, UNITS_COUNT
, lockedImageCount
,
1267 "Total number of locked images in the imagelib surface cache.");
1270 "imagelib-surface-cache-image-surface-count",
1271 KIND_OTHER
, UNITS_COUNT
, totalSurfaceCount
,
1272 "Total number of surfaces in the imagelib surface cache.");
1275 "imagelib-surface-cache-locked-surfaces-count",
1276 KIND_OTHER
, UNITS_COUNT
, lockedSurfaceCount
,
1277 "Total number of locked surfaces in the imagelib surface cache.");
1280 "imagelib-surface-cache-overflow-count",
1281 KIND_OTHER
, UNITS_COUNT
, mOverflowCount
,
1282 "Count of how many times the surface cache has hit its capacity and been "
1283 "unable to insert a new surface.");
1286 "imagelib-surface-cache-tracking-failure-count",
1287 KIND_OTHER
, UNITS_COUNT
, mTrackingFailureCount
,
1288 "Count of how many times the surface cache has failed to begin tracking a "
1292 "imagelib-surface-cache-already-present-count",
1293 KIND_OTHER
, UNITS_COUNT
, mAlreadyPresentCount
,
1294 "Count of how many times the surface cache has failed to insert a surface "
1295 "because it is already present.");
1298 "imagelib-surface-cache-table-failure-count",
1299 KIND_OTHER
, UNITS_COUNT
, mTableFailureCount
,
1300 "Count of how many times the surface cache has failed to insert a surface "
1301 "because a hash table could not accept an entry.");
1307 void CollectSizeOfSurfaces(const ImageKey aImageKey
,
1308 nsTArray
<SurfaceMemoryCounter
>& aCounters
,
1309 MallocSizeOf aMallocSizeOf
,
1310 const StaticMutexAutoLock
& aAutoLock
) {
1311 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1313 return; // No surfaces for this image.
1316 // Report all surfaces in the per-image cache.
1317 cache
->CollectSizeOfSurfaces(
1318 aCounters
, aMallocSizeOf
,
1319 [this, &aAutoLock
](NotNull
<CachedSurface
*> aSurface
) -> void {
1320 StopTracking(aSurface
, /* aIsTracked */ true, aAutoLock
);
1321 // Individual surfaces must be freed outside the lock.
1322 mCachedSurfacesDiscard
.AppendElement(aSurface
);
1325 MaybeRemoveEmptyCache(aImageKey
, cache
);
1328 void ReleaseImageOnMainThread(already_AddRefed
<image::Image
>&& aImage
,
1329 const StaticMutexAutoLock
& aAutoLock
) {
1330 RefPtr
<image::Image
> image
= aImage
;
1335 bool needsDispatch
= mReleasingImagesOnMainThread
.IsEmpty();
1336 mReleasingImagesOnMainThread
.AppendElement(image
);
1338 if (!needsDispatch
) {
1339 // There is already a ongoing task for ClearReleasingImages().
1343 NS_DispatchToMainThread(NS_NewRunnableFunction(
1344 "SurfaceCacheImpl::ReleaseImageOnMainThread",
1345 []() -> void { SurfaceCache::ClearReleasingImages(); }));
1348 void TakeReleasingImages(nsTArray
<RefPtr
<image::Image
>>& aImage
,
1349 const StaticMutexAutoLock
& aAutoLock
) {
1350 MOZ_ASSERT(NS_IsMainThread());
1351 aImage
.SwapElements(mReleasingImagesOnMainThread
);
1355 already_AddRefed
<ImageSurfaceCache
> GetImageCache(const ImageKey aImageKey
) {
1356 RefPtr
<ImageSurfaceCache
> imageCache
;
1357 mImageCaches
.Get(aImageKey
, getter_AddRefs(imageCache
));
1358 return imageCache
.forget();
1361 void MaybeRemoveEmptyCache(const ImageKey aImageKey
,
1362 ImageSurfaceCache
* aCache
) {
1363 // Remove the per-image cache if it's unneeded now. Keep it if the image is
1364 // locked, since the per-image cache is where we store that state. Note that
1365 // we don't push it into mImageCachesDiscard because all of its surfaces
1366 // have been removed, so it is safe to free while holding the lock.
1367 if (aCache
->IsEmpty() && !aCache
->IsLocked()) {
1368 mImageCaches
.Remove(aImageKey
);
1372 // This is similar to CanHold() except that it takes into account the costs of
1373 // locked surfaces. It's used internally in Insert(), but it's not exposed
1374 // publicly because we permit multithreaded access to the surface cache, which
1375 // means that the result would be meaningless: another thread could insert a
1376 // surface or lock an image at any time.
1377 bool CanHoldAfterDiscarding(const Cost aCost
) const {
1378 return aCost
<= mMaxCost
- mLockedCost
;
1381 bool MarkUsed(NotNull
<CachedSurface
*> aSurface
,
1382 NotNull
<ImageSurfaceCache
*> aCache
,
1383 const StaticMutexAutoLock
& aAutoLock
) {
1384 if (aCache
->IsLocked()) {
1385 LockSurface(aSurface
, aAutoLock
);
1389 nsresult rv
= mExpirationTracker
.MarkUsedLocked(aSurface
, aAutoLock
);
1390 if (NS_WARN_IF(NS_FAILED(rv
))) {
1391 // If mark used fails, it is because it failed to reinsert the surface
1392 // after removing it from the tracker. Thus we need to update our
1393 // own accounting but otherwise expect it to be untracked.
1394 StopTracking(aSurface
, /* aIsTracked */ false, aAutoLock
);
1400 void DoUnlockSurfaces(NotNull
<ImageSurfaceCache
*> aCache
, bool aStaticOnly
,
1401 const StaticMutexAutoLock
& aAutoLock
) {
1402 AutoTArray
<NotNull
<CachedSurface
*>, 8> discard
;
1404 // Unlock all the surfaces the per-image cache is holding.
1405 for (auto iter
= aCache
->ConstIter(); !iter
.Done(); iter
.Next()) {
1406 NotNull
<CachedSurface
*> surface
= WrapNotNull(iter
.UserData());
1407 if (surface
->IsPlaceholder() || !surface
->IsLocked()) {
1411 surface
->GetSurfaceKey().Playback() != PlaybackType::eStatic
) {
1414 StopTracking(surface
, /* aIsTracked */ true, aAutoLock
);
1415 surface
->SetLocked(false);
1416 if (MOZ_UNLIKELY(!StartTracking(surface
, aAutoLock
))) {
1417 discard
.AppendElement(surface
);
1421 // Discard any that we failed to track.
1422 for (auto iter
= discard
.begin(); iter
!= discard
.end(); ++iter
) {
1423 Remove(*iter
, /* aStopTracking */ false, aAutoLock
);
1427 void RemoveEntry(const ImageKey aImageKey
, const SurfaceKey
& aSurfaceKey
,
1428 const StaticMutexAutoLock
& aAutoLock
) {
1429 RefPtr
<ImageSurfaceCache
> cache
= GetImageCache(aImageKey
);
1431 return; // No cached surfaces for this image.
1434 RefPtr
<CachedSurface
> surface
=
1435 cache
->Lookup(aSurfaceKey
, /* aForAccess = */ false);
1437 return; // Lookup in the per-image cache missed.
1440 Remove(WrapNotNull(surface
), /* aStopTracking */ true, aAutoLock
);
1443 class SurfaceTracker final
1444 : public ExpirationTrackerImpl
<CachedSurface
, 2, StaticMutex
,
1445 StaticMutexAutoLock
> {
1447 explicit SurfaceTracker(uint32_t aSurfaceCacheExpirationTimeMS
)
1448 : ExpirationTrackerImpl
<CachedSurface
, 2, StaticMutex
,
1449 StaticMutexAutoLock
>(
1450 aSurfaceCacheExpirationTimeMS
, "SurfaceTracker") {}
1453 void NotifyExpiredLocked(CachedSurface
* aSurface
,
1454 const StaticMutexAutoLock
& aAutoLock
) override
{
1455 sInstance
->Remove(WrapNotNull(aSurface
), /* aStopTracking */ true,
1459 void NotifyHandlerEndLocked(const StaticMutexAutoLock
& aAutoLock
) override
{
1460 sInstance
->TakeDiscard(mDiscard
, aAutoLock
);
1463 void NotifyHandlerEnd() override
{
1464 nsTArray
<RefPtr
<CachedSurface
>> discard(std::move(mDiscard
));
1467 StaticMutex
& GetMutex() override
{ return sInstanceMutex
; }
1469 nsTArray
<RefPtr
<CachedSurface
>> mDiscard
;
1472 class MemoryPressureObserver final
: public nsIObserver
{
1476 NS_IMETHOD
Observe(nsISupports
*, const char* aTopic
,
1477 const char16_t
*) override
{
1478 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1480 StaticMutexAutoLock
lock(sInstanceMutex
);
1481 if (sInstance
&& strcmp(aTopic
, "memory-pressure") == 0) {
1482 sInstance
->DiscardForMemoryPressure(lock
);
1483 sInstance
->TakeDiscard(discard
, lock
);
1490 virtual ~MemoryPressureObserver() {}
1493 nsTArray
<CostEntry
> mCosts
;
1494 nsRefPtrHashtable
<nsPtrHashKey
<Image
>, ImageSurfaceCache
> mImageCaches
;
1495 nsTArray
<RefPtr
<CachedSurface
>> mCachedSurfacesDiscard
;
1496 SurfaceTracker mExpirationTracker
;
1497 RefPtr
<MemoryPressureObserver
> mMemoryPressureObserver
;
1498 nsTArray
<RefPtr
<image::Image
>> mReleasingImagesOnMainThread
;
1499 const uint32_t mDiscardFactor
;
1500 const Cost mMaxCost
;
1501 Cost mAvailableCost
;
1503 size_t mOverflowCount
;
1504 size_t mAlreadyPresentCount
;
1505 size_t mTableFailureCount
;
1506 size_t mTrackingFailureCount
;
1509 NS_IMPL_ISUPPORTS(SurfaceCacheImpl
, nsIMemoryReporter
)
1510 NS_IMPL_ISUPPORTS(SurfaceCacheImpl::MemoryPressureObserver
, nsIObserver
)
1512 ///////////////////////////////////////////////////////////////////////////////
1514 ///////////////////////////////////////////////////////////////////////////////
1517 void SurfaceCache::Initialize() {
1518 // Initialize preferences.
1519 MOZ_ASSERT(NS_IsMainThread());
1520 MOZ_ASSERT(!sInstance
, "Shouldn't initialize more than once");
1522 // See StaticPrefs for the default values of these preferences.
1524 // Length of time before an unused surface is removed from the cache, in
1526 uint32_t surfaceCacheExpirationTimeMS
=
1527 StaticPrefs::image_mem_surfacecache_min_expiration_ms_AtStartup();
1529 // What fraction of the memory used by the surface cache we should discard
1530 // when we get a memory pressure notification. This value is interpreted as
1531 // 1/N, so 1 means to discard everything, 2 means to discard about half of the
1532 // memory we're using, and so forth. We clamp it to avoid division by zero.
1533 uint32_t surfaceCacheDiscardFactor
=
1534 max(StaticPrefs::image_mem_surfacecache_discard_factor_AtStartup(), 1u);
1536 // Maximum size of the surface cache, in kilobytes.
1537 uint64_t surfaceCacheMaxSizeKB
=
1538 StaticPrefs::image_mem_surfacecache_max_size_kb_AtStartup();
1540 if (sizeof(uintptr_t) <= 4) {
1541 // Limit surface cache to 1 GB if our address space is 32 bit.
1542 surfaceCacheMaxSizeKB
= 1024 * 1024;
1545 // A knob determining the actual size of the surface cache. Currently the
1546 // cache is (size of main memory) / (surface cache size factor) KB
1547 // or (surface cache max size) KB, whichever is smaller. The formula
1548 // may change in the future, though.
1549 // For example, a value of 4 would yield a 256MB cache on a 1GB machine.
1550 // The smallest machines we are likely to run this code on have 256MB
1551 // of memory, which would yield a 64MB cache on this setting.
1552 // We clamp this value to avoid division by zero.
1553 uint32_t surfaceCacheSizeFactor
=
1554 max(StaticPrefs::image_mem_surfacecache_size_factor_AtStartup(), 1u);
1556 // Compute the size of the surface cache.
1557 uint64_t memorySize
= PR_GetPhysicalMemorySize();
1558 if (memorySize
== 0) {
1559 MOZ_ASSERT_UNREACHABLE("PR_GetPhysicalMemorySize not implemented here");
1560 memorySize
= 256 * 1024 * 1024; // Fall back to 256MB.
1562 uint64_t proposedSize
= memorySize
/ surfaceCacheSizeFactor
;
1563 uint64_t surfaceCacheSizeBytes
=
1564 min(proposedSize
, surfaceCacheMaxSizeKB
* 1024);
1565 uint32_t finalSurfaceCacheSizeBytes
=
1566 min(surfaceCacheSizeBytes
, uint64_t(UINT32_MAX
));
1568 // Create the surface cache singleton with the requested settings. Note that
1569 // the size is a limit that the cache may not grow beyond, but we do not
1570 // actually allocate any storage for surfaces at this time.
1571 sInstance
= new SurfaceCacheImpl(surfaceCacheExpirationTimeMS
,
1572 surfaceCacheDiscardFactor
,
1573 finalSurfaceCacheSizeBytes
);
1574 sInstance
->InitMemoryReporter();
1578 void SurfaceCache::Shutdown() {
1579 RefPtr
<SurfaceCacheImpl
> cache
;
1581 StaticMutexAutoLock
lock(sInstanceMutex
);
1582 MOZ_ASSERT(NS_IsMainThread());
1583 MOZ_ASSERT(sInstance
, "No singleton - was Shutdown() called twice?");
1584 cache
= sInstance
.forget();
1589 LookupResult
SurfaceCache::Lookup(const ImageKey aImageKey
,
1590 const SurfaceKey
& aSurfaceKey
,
1592 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1593 LookupResult
rv(MatchType::NOT_FOUND
);
1596 StaticMutexAutoLock
lock(sInstanceMutex
);
1601 rv
= sInstance
->Lookup(aImageKey
, aSurfaceKey
, lock
, aMarkUsed
);
1602 sInstance
->TakeDiscard(discard
, lock
);
1609 LookupResult
SurfaceCache::LookupBestMatch(const ImageKey aImageKey
,
1610 const SurfaceKey
& aSurfaceKey
,
1612 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1613 LookupResult
rv(MatchType::NOT_FOUND
);
1616 StaticMutexAutoLock
lock(sInstanceMutex
);
1621 rv
= sInstance
->LookupBestMatch(aImageKey
, aSurfaceKey
, lock
, aMarkUsed
);
1622 sInstance
->TakeDiscard(discard
, lock
);
1629 InsertOutcome
SurfaceCache::Insert(NotNull
<ISurfaceProvider
*> aProvider
) {
1630 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1631 InsertOutcome
rv(InsertOutcome::FAILURE
);
1634 StaticMutexAutoLock
lock(sInstanceMutex
);
1639 rv
= sInstance
->Insert(aProvider
, /* aSetAvailable = */ false, lock
);
1640 sInstance
->TakeDiscard(discard
, lock
);
1647 bool SurfaceCache::CanHold(const IntSize
& aSize
,
1648 uint32_t aBytesPerPixel
/* = 4 */) {
1649 StaticMutexAutoLock
lock(sInstanceMutex
);
1654 Cost cost
= ComputeCost(aSize
, aBytesPerPixel
);
1655 return sInstance
->CanHold(cost
);
1659 bool SurfaceCache::CanHold(size_t aSize
) {
1660 StaticMutexAutoLock
lock(sInstanceMutex
);
1665 return sInstance
->CanHold(aSize
);
1669 void SurfaceCache::SurfaceAvailable(NotNull
<ISurfaceProvider
*> aProvider
) {
1670 StaticMutexAutoLock
lock(sInstanceMutex
);
1675 sInstance
->SurfaceAvailable(aProvider
, lock
);
1679 void SurfaceCache::LockImage(const ImageKey aImageKey
) {
1680 StaticMutexAutoLock
lock(sInstanceMutex
);
1682 return sInstance
->LockImage(aImageKey
);
1687 void SurfaceCache::UnlockImage(const ImageKey aImageKey
) {
1688 StaticMutexAutoLock
lock(sInstanceMutex
);
1690 return sInstance
->UnlockImage(aImageKey
, lock
);
1695 void SurfaceCache::UnlockEntries(const ImageKey aImageKey
) {
1696 StaticMutexAutoLock
lock(sInstanceMutex
);
1698 return sInstance
->UnlockEntries(aImageKey
, lock
);
1703 void SurfaceCache::RemoveImage(const ImageKey aImageKey
) {
1704 RefPtr
<ImageSurfaceCache
> discard
;
1706 StaticMutexAutoLock
lock(sInstanceMutex
);
1708 discard
= sInstance
->RemoveImage(aImageKey
, lock
);
1714 void SurfaceCache::PruneImage(const ImageKey aImageKey
) {
1715 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1717 StaticMutexAutoLock
lock(sInstanceMutex
);
1719 sInstance
->PruneImage(aImageKey
, lock
);
1720 sInstance
->TakeDiscard(discard
, lock
);
1726 void SurfaceCache::DiscardAll() {
1727 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1729 StaticMutexAutoLock
lock(sInstanceMutex
);
1731 sInstance
->DiscardAll(lock
);
1732 sInstance
->TakeDiscard(discard
, lock
);
1738 void SurfaceCache::CollectSizeOfSurfaces(
1739 const ImageKey aImageKey
, nsTArray
<SurfaceMemoryCounter
>& aCounters
,
1740 MallocSizeOf aMallocSizeOf
) {
1741 nsTArray
<RefPtr
<CachedSurface
>> discard
;
1743 StaticMutexAutoLock
lock(sInstanceMutex
);
1748 sInstance
->CollectSizeOfSurfaces(aImageKey
, aCounters
, aMallocSizeOf
, lock
);
1749 sInstance
->TakeDiscard(discard
, lock
);
1754 size_t SurfaceCache::MaximumCapacity() {
1755 StaticMutexAutoLock
lock(sInstanceMutex
);
1760 return sInstance
->MaximumCapacity();
1764 bool SurfaceCache::IsLegalSize(const IntSize
& aSize
) {
1765 // reject over-wide or over-tall images
1766 const int32_t k64KLimit
= 0x0000FFFF;
1767 if (MOZ_UNLIKELY(aSize
.width
> k64KLimit
|| aSize
.height
> k64KLimit
)) {
1768 NS_WARNING("image too big");
1772 // protect against invalid sizes
1773 if (MOZ_UNLIKELY(aSize
.height
<= 0 || aSize
.width
<= 0)) {
1777 // check to make sure we don't overflow a 32-bit
1778 CheckedInt32 requiredBytes
=
1779 CheckedInt32(aSize
.width
) * CheckedInt32(aSize
.height
) * 4;
1780 if (MOZ_UNLIKELY(!requiredBytes
.isValid())) {
1781 NS_WARNING("width or height too large");
1787 IntSize
SurfaceCache::ClampVectorSize(const IntSize
& aSize
) {
1788 // If we exceed the maximum, we need to scale the size downwards to fit.
1789 // It shouldn't get here if it is significantly larger because
1790 // VectorImage::UseSurfaceCacheForSize should prevent us from requesting
1791 // a rasterized version of a surface greater than 4x the maximum.
1793 StaticPrefs::image_cache_max_rasterized_svg_threshold_kb();
1794 if (maxSizeKB
<= 0) {
1798 int64_t proposedKB
= int64_t(aSize
.width
) * aSize
.height
/ 256;
1799 if (maxSizeKB
>= proposedKB
) {
1803 double scale
= sqrt(double(maxSizeKB
) / proposedKB
);
1804 return IntSize(int32_t(scale
* aSize
.width
), int32_t(scale
* aSize
.height
));
1807 IntSize
SurfaceCache::ClampSize(ImageKey aImageKey
, const IntSize
& aSize
) {
1808 if (aImageKey
->GetType() != imgIContainer::TYPE_VECTOR
) {
1812 return ClampVectorSize(aSize
);
1816 void SurfaceCache::ReleaseImageOnMainThread(
1817 already_AddRefed
<image::Image
> aImage
, bool aAlwaysProxy
) {
1818 if (NS_IsMainThread() && !aAlwaysProxy
) {
1819 RefPtr
<image::Image
> image
= std::move(aImage
);
1823 StaticMutexAutoLock
lock(sInstanceMutex
);
1825 sInstance
->ReleaseImageOnMainThread(std::move(aImage
), lock
);
1827 NS_ReleaseOnMainThread("SurfaceCache::ReleaseImageOnMainThread",
1828 std::move(aImage
), /* aAlwaysProxy */ true);
1833 void SurfaceCache::ClearReleasingImages() {
1834 MOZ_ASSERT(NS_IsMainThread());
1836 nsTArray
<RefPtr
<image::Image
>> images
;
1838 StaticMutexAutoLock
lock(sInstanceMutex
);
1840 sInstance
->TakeReleasingImages(images
, lock
);
1845 } // namespace image
1846 } // namespace mozilla