Bug 1733130 [wpt PR 30935] - Fix ttwf-transform-translatex-001.html., a=testonly
[gecko.git] / image / SurfaceCache.cpp
blob1f647a729bf6918052de8a4a447f07bd2ef1f051
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 /**
7 * SurfaceCache is a service for caching temporary surfaces in imagelib.
8 */
10 #include "SurfaceCache.h"
12 #include <algorithm>
13 #include <utility>
15 #include "ISurfaceProvider.h"
16 #include "Image.h"
17 #include "LookupResult.h"
18 #include "ShutdownTracker.h"
19 #include "gfx2DGlue.h"
20 #include "gfxPlatform.h"
21 #include "imgFrame.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"
36 #include "nsSize.h"
37 #include "nsTArray.h"
38 #include "Orientation.h"
39 #include "prsystem.h"
41 using std::max;
42 using std::min;
44 namespace mozilla {
46 using namespace gfx;
48 namespace image {
50 MOZ_DEFINE_MALLOC_SIZE_OF(SurfaceCacheMallocSizeOf)
52 class CachedSurface;
53 class SurfaceCacheImpl;
55 ///////////////////////////////////////////////////////////////////////////////
56 // Static Data
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 ///////////////////////////////////////////////////////////////////////////////
69 /**
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
73 * well.
75 typedef size_t Cost;
77 static Cost ComputeCost(const IntSize& aSize, uint32_t aBytesPerPixel) {
78 MOZ_ASSERT(aBytesPerPixel == 1 || aBytesPerPixel == 4);
79 return aSize.width * aSize.height * aBytesPerPixel;
82 /**
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
91 * it is removed.
93 class CostEntry {
94 public:
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);
110 private:
111 NotNull<CachedSurface*> mSurface;
112 Cost mCost;
116 * A CachedSurface associates a surface with a key that uniquely identifies that
117 * surface.
119 class CachedSurface {
120 ~CachedSurface() {}
122 public:
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
146 // perspective.
147 mIsLocked = aLocked;
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()) {
187 return;
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(
197 aCachedSurface->GetSurfaceKey(), aMetadata.mSurface,
198 aCachedSurface->IsLocked(), 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);
213 private:
214 nsTArray<SurfaceMemoryCounter>& mCounters;
215 MallocSizeOf mMallocSizeOf;
218 private:
219 nsExpirationState mExpirationState;
220 NotNull<RefPtr<ISurfaceProvider>> mProvider;
221 bool mIsLocked;
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
235 * or unlocked.
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() {}
250 public:
251 explicit ImageSurfaceCache(const ImageKey aImageKey)
252 : mLocked(false),
253 mFactor2Mode(false),
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>
261 SurfaceTable;
263 auto Values() const { return mSurfaces.Values(); }
264 uint32_t Count() const { return mSurfaces.Count(); }
265 bool IsEmpty() const { return mSurfaces.Count() == 0; }
267 size_t ShallowSizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
268 size_t bytes = aMallocSizeOf(this) +
269 mSurfaces.ShallowSizeOfExcludingThis(aMallocSizeOf);
270 for (const auto& value : Values()) {
271 bytes += value->ShallowSizeOfIncludingThis(aMallocSizeOf);
273 return bytes;
276 [[nodiscard]] bool Insert(NotNull<CachedSurface*> aSurface) {
277 MOZ_ASSERT(!mLocked || aSurface->IsPlaceholder() || aSurface->IsLocked(),
278 "Inserting an unlocked surface for a locked image");
279 return mSurfaces.InsertOrUpdate(aSurface->GetSurfaceKey(),
280 RefPtr<CachedSurface>{aSurface}, fallible);
283 already_AddRefed<CachedSurface> Remove(NotNull<CachedSurface*> aSurface) {
284 MOZ_ASSERT(mSurfaces.GetWeak(aSurface->GetSurfaceKey()),
285 "Should not be removing a surface we don't have");
287 RefPtr<CachedSurface> surface;
288 mSurfaces.Remove(aSurface->GetSurfaceKey(), getter_AddRefs(surface));
289 AfterMaybeRemove();
290 return surface.forget();
293 already_AddRefed<CachedSurface> Lookup(const SurfaceKey& aSurfaceKey,
294 bool aForAccess) {
295 RefPtr<CachedSurface> surface;
296 mSurfaces.Get(aSurfaceKey, getter_AddRefs(surface));
298 if (aForAccess) {
299 if (surface) {
300 // We don't want to allow factor of 2 mode pruning to release surfaces
301 // for which the callers will accept no substitute.
302 surface->SetCannotSubstitute();
303 } else if (!mFactor2Mode) {
304 // If no exact match is found, and this is for use rather than internal
305 // accounting (i.e. insert and removal), we know this will trigger a
306 // decode. Make sure we switch now to factor of 2 mode if necessary.
307 MaybeSetFactor2Mode();
311 return surface.forget();
315 * @returns A tuple containing the best matching CachedSurface if available,
316 * a MatchType describing how the CachedSurface was selected, and
317 * an IntSize which is the size the caller should choose to decode
318 * at should it attempt to do so.
320 Tuple<already_AddRefed<CachedSurface>, MatchType, IntSize> LookupBestMatch(
321 const SurfaceKey& aIdealKey) {
322 // Try for an exact match first.
323 RefPtr<CachedSurface> exactMatch;
324 mSurfaces.Get(aIdealKey, getter_AddRefs(exactMatch));
325 if (exactMatch) {
326 if (exactMatch->IsDecoded()) {
327 return MakeTuple(exactMatch.forget(), MatchType::EXACT, IntSize());
329 } else if (!mFactor2Mode) {
330 // If no exact match is found, and we are not in factor of 2 mode, then
331 // we know that we will trigger a decode because at best we will provide
332 // a substitute. Make sure we switch now to factor of 2 mode if necessary.
333 MaybeSetFactor2Mode();
336 // Try for a best match second, if using compact.
337 IntSize suggestedSize = SuggestedSize(aIdealKey.Size());
338 if (suggestedSize != aIdealKey.Size()) {
339 if (!exactMatch) {
340 SurfaceKey compactKey = aIdealKey.CloneWithSize(suggestedSize);
341 mSurfaces.Get(compactKey, getter_AddRefs(exactMatch));
342 if (exactMatch && exactMatch->IsDecoded()) {
343 MOZ_ASSERT(suggestedSize != aIdealKey.Size());
344 return MakeTuple(exactMatch.forget(),
345 MatchType::SUBSTITUTE_BECAUSE_BEST, suggestedSize);
350 // There's no perfect match, so find the best match we can.
351 RefPtr<CachedSurface> bestMatch;
352 for (const auto& value : Values()) {
353 NotNull<CachedSurface*> current = WrapNotNull(value);
354 const SurfaceKey& currentKey = current->GetSurfaceKey();
356 // We never match a placeholder.
357 if (current->IsPlaceholder()) {
358 continue;
360 // Matching the playback type and SVG context is required.
361 if (currentKey.Playback() != aIdealKey.Playback() ||
362 currentKey.SVGContext() != aIdealKey.SVGContext()) {
363 continue;
365 // Matching the flags is required.
366 if (currentKey.Flags() != aIdealKey.Flags()) {
367 continue;
369 // Anything is better than nothing! (Within the constraints we just
370 // checked, of course.)
371 if (!bestMatch) {
372 bestMatch = current;
373 continue;
376 MOZ_ASSERT(bestMatch, "Should have a current best match");
378 // Always prefer completely decoded surfaces.
379 bool bestMatchIsDecoded = bestMatch->IsDecoded();
380 if (bestMatchIsDecoded && !current->IsDecoded()) {
381 continue;
383 if (!bestMatchIsDecoded && current->IsDecoded()) {
384 bestMatch = current;
385 continue;
388 SurfaceKey bestMatchKey = bestMatch->GetSurfaceKey();
389 if (CompareArea(aIdealKey.Size(), bestMatchKey.Size(),
390 currentKey.Size())) {
391 bestMatch = current;
395 MatchType matchType;
396 if (bestMatch) {
397 if (!exactMatch) {
398 // No exact match, neither ideal nor factor of 2.
399 MOZ_ASSERT(suggestedSize != bestMatch->GetSurfaceKey().Size(),
400 "No exact match despite the fact the sizes match!");
401 matchType = MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND;
402 } else if (exactMatch != bestMatch) {
403 // The exact match is still decoding, but we found a substitute.
404 matchType = MatchType::SUBSTITUTE_BECAUSE_PENDING;
405 } else if (aIdealKey.Size() != bestMatch->GetSurfaceKey().Size()) {
406 // The best factor of 2 match is still decoding, but the best we've got.
407 MOZ_ASSERT(suggestedSize != aIdealKey.Size());
408 MOZ_ASSERT(mFactor2Mode || mIsVectorImage);
409 matchType = MatchType::SUBSTITUTE_BECAUSE_BEST;
410 } else {
411 // The exact match is still decoding, but it's the best we've got.
412 matchType = MatchType::EXACT;
414 } else {
415 if (exactMatch) {
416 // We found an "exact match"; it must have been a placeholder.
417 MOZ_ASSERT(exactMatch->IsPlaceholder());
418 matchType = MatchType::PENDING;
419 } else {
420 // We couldn't find an exact match *or* a substitute.
421 matchType = MatchType::NOT_FOUND;
425 return MakeTuple(bestMatch.forget(), matchType, suggestedSize);
428 void MaybeSetFactor2Mode() {
429 MOZ_ASSERT(!mFactor2Mode);
431 // Typically an image cache will not have too many size-varying surfaces, so
432 // if we exceed the given threshold, we should consider using a subset.
433 int32_t thresholdSurfaces =
434 StaticPrefs::image_cache_factor2_threshold_surfaces();
435 if (thresholdSurfaces < 0 ||
436 mSurfaces.Count() <= static_cast<uint32_t>(thresholdSurfaces)) {
437 return;
440 // Determine how many native surfaces this image has. If it is zero, and it
441 // is a vector image, then we should impute a single native size. Otherwise,
442 // it may be zero because we don't know yet, or the image has an error, or
443 // it isn't supported.
444 NotNull<CachedSurface*> current =
445 WrapNotNull(mSurfaces.ConstIter().UserData());
446 Image* image = static_cast<Image*>(current->GetImageKey());
447 size_t nativeSizes = image->GetNativeSizesLength();
448 if (mIsVectorImage) {
449 MOZ_ASSERT(nativeSizes == 0);
450 nativeSizes = 1;
451 } else if (nativeSizes == 0) {
452 return;
455 // Increase the threshold by the number of native sizes. This ensures that
456 // we do not prevent decoding of the image at all its native sizes. It does
457 // not guarantee we will provide a surface at that size however (i.e. many
458 // other sized surfaces are requested, in addition to the native sizes).
459 thresholdSurfaces += nativeSizes;
460 if (mSurfaces.Count() <= static_cast<uint32_t>(thresholdSurfaces)) {
461 return;
464 // Get our native size. While we know the image should be fully decoded,
465 // if it is an SVG, it is valid to have a zero size. We can't do compacting
466 // in that case because we need to know the width/height ratio to define a
467 // candidate set.
468 IntSize nativeSize;
469 if (NS_FAILED(image->GetWidth(&nativeSize.width)) ||
470 NS_FAILED(image->GetHeight(&nativeSize.height)) ||
471 nativeSize.IsEmpty()) {
472 return;
475 // We have a valid size, we can change modes.
476 mFactor2Mode = true;
479 template <typename Function>
480 void Prune(Function&& aRemoveCallback) {
481 if (!mFactor2Mode || mFactor2Pruned) {
482 return;
485 // Attempt to discard any surfaces which are not factor of 2 and the best
486 // factor of 2 match exists.
487 bool hasNotFactorSize = false;
488 for (auto iter = mSurfaces.Iter(); !iter.Done(); iter.Next()) {
489 NotNull<CachedSurface*> current = WrapNotNull(iter.UserData());
490 const SurfaceKey& currentKey = current->GetSurfaceKey();
491 const IntSize& currentSize = currentKey.Size();
493 // First we check if someone requested this size and would not accept
494 // an alternatively sized surface.
495 if (current->CannotSubstitute()) {
496 continue;
499 // Next we find the best factor of 2 size for this surface. If this
500 // surface is a factor of 2 size, then we want to keep it.
501 IntSize bestSize = SuggestedSize(currentSize);
502 if (bestSize == currentSize) {
503 continue;
506 // Check the cache for a surface with the same parameters except for the
507 // size which uses the closest factor of 2 size.
508 SurfaceKey compactKey = currentKey.CloneWithSize(bestSize);
509 RefPtr<CachedSurface> compactMatch;
510 mSurfaces.Get(compactKey, getter_AddRefs(compactMatch));
511 if (compactMatch && compactMatch->IsDecoded()) {
512 aRemoveCallback(current);
513 iter.Remove();
514 } else {
515 hasNotFactorSize = true;
519 // We have no surfaces that are not factor of 2 sized, so we can stop
520 // pruning henceforth, because we avoid the insertion of new surfaces that
521 // don't match our sizing set (unless the caller won't accept a
522 // substitution.)
523 if (!hasNotFactorSize) {
524 mFactor2Pruned = true;
527 // We should never leave factor of 2 mode due to pruning in of itself, but
528 // if we discarded surfaces due to the volatile buffers getting released,
529 // it is possible.
530 AfterMaybeRemove();
533 IntSize SuggestedSize(const IntSize& aSize) const {
534 IntSize suggestedSize = SuggestedSizeInternal(aSize);
535 if (mIsVectorImage) {
536 suggestedSize = SurfaceCache::ClampVectorSize(suggestedSize);
538 return suggestedSize;
541 IntSize SuggestedSizeInternal(const IntSize& aSize) const {
542 // When not in factor of 2 mode, we can always decode at the given size.
543 if (!mFactor2Mode) {
544 return aSize;
547 // We cannot enter factor of 2 mode unless we have a minimum number of
548 // surfaces, and we should have left it if the cache was emptied.
549 if (MOZ_UNLIKELY(IsEmpty())) {
550 MOZ_ASSERT_UNREACHABLE("Should not be empty and in factor of 2 mode!");
551 return aSize;
554 // This bit of awkwardness gets the largest native size of the image.
555 NotNull<CachedSurface*> firstSurface =
556 WrapNotNull(mSurfaces.ConstIter().UserData());
557 Image* image = static_cast<Image*>(firstSurface->GetImageKey());
558 IntSize factorSize;
559 if (NS_FAILED(image->GetWidth(&factorSize.width)) ||
560 NS_FAILED(image->GetHeight(&factorSize.height)) ||
561 factorSize.IsEmpty()) {
562 // We should not have entered factor of 2 mode without a valid size, and
563 // several successfully decoded surfaces. Note that valid vector images
564 // may have a default size of 0x0, and those are not yet supported.
565 MOZ_ASSERT_UNREACHABLE("Expected valid native size!");
566 return aSize;
569 if (image->GetOrientation().SwapsWidthAndHeight()) {
570 std::swap(factorSize.width, factorSize.height);
573 if (mIsVectorImage) {
574 // Ensure the aspect ratio matches the native size before forcing the
575 // caller to accept a factor of 2 size. The difference between the aspect
576 // ratios is:
578 // delta = nativeWidth/nativeHeight - desiredWidth/desiredHeight
580 // delta*nativeHeight*desiredHeight = nativeWidth*desiredHeight
581 // - desiredWidth*nativeHeight
583 // Using the maximum accepted delta as a constant, we can avoid the
584 // floating point division and just compare after some integer ops.
585 int32_t delta =
586 factorSize.width * aSize.height - aSize.width * factorSize.height;
587 int32_t maxDelta = (factorSize.height * aSize.height) >> 4;
588 if (delta > maxDelta || delta < -maxDelta) {
589 return aSize;
592 // If the requested size is bigger than the native size, we actually need
593 // to grow the native size instead of shrinking it.
594 if (factorSize.width < aSize.width) {
595 do {
596 IntSize candidate(factorSize.width * 2, factorSize.height * 2);
597 if (!SurfaceCache::IsLegalSize(candidate)) {
598 break;
601 factorSize = candidate;
602 } while (factorSize.width < aSize.width);
604 return factorSize;
607 // Otherwise we can find the best fit as normal.
610 // Start with the native size as the best first guess.
611 IntSize bestSize = factorSize;
612 factorSize.width /= 2;
613 factorSize.height /= 2;
615 while (!factorSize.IsEmpty()) {
616 if (!CompareArea(aSize, bestSize, factorSize)) {
617 // This size is not better than the last. Since we proceed from largest
618 // to smallest, we know that the next size will not be better if the
619 // previous size was rejected. Break early.
620 break;
623 // The current factor of 2 size is better than the last selected size.
624 bestSize = factorSize;
625 factorSize.width /= 2;
626 factorSize.height /= 2;
629 return bestSize;
632 bool CompareArea(const IntSize& aIdealSize, const IntSize& aBestSize,
633 const IntSize& aSize) const {
634 // Compare sizes. We use an area-based heuristic here instead of computing a
635 // truly optimal answer, since it seems very unlikely to make a difference
636 // for realistic sizes.
637 int64_t idealArea = AreaOfIntSize(aIdealSize);
638 int64_t currentArea = AreaOfIntSize(aSize);
639 int64_t bestMatchArea = AreaOfIntSize(aBestSize);
641 // If the best match is smaller than the ideal size, prefer bigger sizes.
642 if (bestMatchArea < idealArea) {
643 if (currentArea > bestMatchArea) {
644 return true;
646 return false;
649 // Other, prefer sizes closer to the ideal size, but still not smaller.
650 if (idealArea <= currentArea && currentArea < bestMatchArea) {
651 return true;
654 // This surface isn't an improvement over the current best match.
655 return false;
658 template <typename Function>
659 void CollectSizeOfSurfaces(nsTArray<SurfaceMemoryCounter>& aCounters,
660 MallocSizeOf aMallocSizeOf,
661 Function&& aRemoveCallback) {
662 CachedSurface::SurfaceMemoryReport report(aCounters, aMallocSizeOf);
663 for (auto iter = mSurfaces.Iter(); !iter.Done(); iter.Next()) {
664 NotNull<CachedSurface*> surface = WrapNotNull(iter.UserData());
666 // We don't need the drawable surface for ourselves, but adding a surface
667 // to the report will trigger this indirectly. If the surface was
668 // discarded by the OS because it was in volatile memory, we should remove
669 // it from the cache immediately rather than include it in the report.
670 DrawableSurface drawableSurface;
671 if (!surface->IsPlaceholder()) {
672 drawableSurface = surface->GetDrawableSurface();
673 if (!drawableSurface) {
674 aRemoveCallback(surface);
675 iter.Remove();
676 continue;
680 const IntSize& size = surface->GetSurfaceKey().Size();
681 bool factor2Size = false;
682 if (mFactor2Mode) {
683 factor2Size = (size == SuggestedSize(size));
685 report.Add(surface, factor2Size);
688 AfterMaybeRemove();
691 void SetLocked(bool aLocked) { mLocked = aLocked; }
692 bool IsLocked() const { return mLocked; }
694 private:
695 void AfterMaybeRemove() {
696 if (IsEmpty() && mFactor2Mode) {
697 // The last surface for this cache was removed. This can happen if the
698 // surface was stored in a volatile buffer and got purged, or the surface
699 // expired from the cache. If the cache itself lingers for some reason
700 // (e.g. in the process of performing a lookup, the cache itself is
701 // locked), then we need to reset the factor of 2 state because it
702 // requires at least one surface present to get the native size
703 // information from the image.
704 mFactor2Mode = mFactor2Pruned = false;
708 SurfaceTable mSurfaces;
710 bool mLocked;
712 // True in "factor of 2" mode.
713 bool mFactor2Mode;
715 // True if all non-factor of 2 surfaces have been removed from the cache. Note
716 // that this excludes unsubstitutable sizes.
717 bool mFactor2Pruned;
719 // True if the surfaces are produced from a vector image. If so, it must match
720 // the aspect ratio when using factor of 2 mode.
721 bool mIsVectorImage;
725 * SurfaceCacheImpl is responsible for determining which surfaces will be cached
726 * and managing the surface cache data structures. Rather than interact with
727 * SurfaceCacheImpl directly, client code interacts with SurfaceCache, which
728 * maintains high-level invariants and encapsulates the details of the surface
729 * cache's implementation.
731 class SurfaceCacheImpl final : public nsIMemoryReporter {
732 public:
733 NS_DECL_ISUPPORTS
735 SurfaceCacheImpl(uint32_t aSurfaceCacheExpirationTimeMS,
736 uint32_t aSurfaceCacheDiscardFactor,
737 uint32_t aSurfaceCacheSize)
738 : mExpirationTracker(aSurfaceCacheExpirationTimeMS),
739 mMemoryPressureObserver(new MemoryPressureObserver),
740 mDiscardFactor(aSurfaceCacheDiscardFactor),
741 mMaxCost(aSurfaceCacheSize),
742 mAvailableCost(aSurfaceCacheSize),
743 mLockedCost(0),
744 mOverflowCount(0),
745 mAlreadyPresentCount(0),
746 mTableFailureCount(0),
747 mTrackingFailureCount(0) {
748 nsCOMPtr<nsIObserverService> os = services::GetObserverService();
749 if (os) {
750 os->AddObserver(mMemoryPressureObserver, "memory-pressure", false);
754 private:
755 virtual ~SurfaceCacheImpl() {
756 nsCOMPtr<nsIObserverService> os = services::GetObserverService();
757 if (os) {
758 os->RemoveObserver(mMemoryPressureObserver, "memory-pressure");
761 UnregisterWeakMemoryReporter(this);
764 public:
765 void InitMemoryReporter() { RegisterWeakMemoryReporter(this); }
767 InsertOutcome Insert(NotNull<ISurfaceProvider*> aProvider, bool aSetAvailable,
768 const StaticMutexAutoLock& aAutoLock) {
769 // If this is a duplicate surface, refuse to replace the original.
770 // XXX(seth): Calling Lookup() and then RemoveEntry() does the lookup
771 // twice. We'll make this more efficient in bug 1185137.
772 LookupResult result =
773 Lookup(aProvider->GetImageKey(), aProvider->GetSurfaceKey(), aAutoLock,
774 /* aMarkUsed = */ false);
775 if (MOZ_UNLIKELY(result)) {
776 mAlreadyPresentCount++;
777 return InsertOutcome::FAILURE_ALREADY_PRESENT;
780 if (result.Type() == MatchType::PENDING) {
781 RemoveEntry(aProvider->GetImageKey(), aProvider->GetSurfaceKey(),
782 aAutoLock);
785 MOZ_ASSERT(result.Type() == MatchType::NOT_FOUND ||
786 result.Type() == MatchType::PENDING,
787 "A LookupResult with no surface should be NOT_FOUND or PENDING");
789 // If this is bigger than we can hold after discarding everything we can,
790 // refuse to cache it.
791 Cost cost = aProvider->LogicalSizeInBytes();
792 if (MOZ_UNLIKELY(!CanHoldAfterDiscarding(cost))) {
793 mOverflowCount++;
794 return InsertOutcome::FAILURE;
797 // Remove elements in order of cost until we can fit this in the cache. Note
798 // that locked surfaces aren't in mCosts, so we never remove them here.
799 while (cost > mAvailableCost) {
800 MOZ_ASSERT(!mCosts.IsEmpty(),
801 "Removed everything and it still won't fit");
802 Remove(mCosts.LastElement().Surface(), /* aStopTracking */ true,
803 aAutoLock);
806 // Locate the appropriate per-image cache. If there's not an existing cache
807 // for this image, create it.
808 const ImageKey imageKey = aProvider->GetImageKey();
809 RefPtr<ImageSurfaceCache> cache = GetImageCache(imageKey);
810 if (!cache) {
811 cache = new ImageSurfaceCache(imageKey);
812 if (!mImageCaches.InsertOrUpdate(aProvider->GetImageKey(), RefPtr{cache},
813 fallible)) {
814 mTableFailureCount++;
815 return InsertOutcome::FAILURE;
819 // If we were asked to mark the cache entry available, do so.
820 if (aSetAvailable) {
821 aProvider->Availability().SetAvailable();
824 auto surface = MakeNotNull<RefPtr<CachedSurface>>(aProvider);
826 // We require that locking succeed if the image is locked and we're not
827 // inserting a placeholder; the caller may need to know this to handle
828 // errors correctly.
829 bool mustLock = cache->IsLocked() && !surface->IsPlaceholder();
830 if (mustLock) {
831 surface->SetLocked(true);
832 if (!surface->IsLocked()) {
833 return InsertOutcome::FAILURE;
837 // Insert.
838 MOZ_ASSERT(cost <= mAvailableCost, "Inserting despite too large a cost");
839 if (!cache->Insert(surface)) {
840 mTableFailureCount++;
841 if (mustLock) {
842 surface->SetLocked(false);
844 return InsertOutcome::FAILURE;
847 if (MOZ_UNLIKELY(!StartTracking(surface, aAutoLock))) {
848 MOZ_ASSERT(!mustLock);
849 Remove(surface, /* aStopTracking */ false, aAutoLock);
850 return InsertOutcome::FAILURE;
853 return InsertOutcome::SUCCESS;
856 void Remove(NotNull<CachedSurface*> aSurface, bool aStopTracking,
857 const StaticMutexAutoLock& aAutoLock) {
858 ImageKey imageKey = aSurface->GetImageKey();
860 RefPtr<ImageSurfaceCache> cache = GetImageCache(imageKey);
861 MOZ_ASSERT(cache, "Shouldn't try to remove a surface with no image cache");
863 // If the surface was not a placeholder, tell its image that we discarded
864 // it.
865 if (!aSurface->IsPlaceholder()) {
866 static_cast<Image*>(imageKey)->OnSurfaceDiscarded(
867 aSurface->GetSurfaceKey());
870 // If we failed during StartTracking, we can skip this step.
871 if (aStopTracking) {
872 StopTracking(aSurface, /* aIsTracked */ true, aAutoLock);
875 // Individual surfaces must be freed outside the lock.
876 mCachedSurfacesDiscard.AppendElement(cache->Remove(aSurface));
878 MaybeRemoveEmptyCache(imageKey, cache);
881 bool StartTracking(NotNull<CachedSurface*> aSurface,
882 const StaticMutexAutoLock& aAutoLock) {
883 CostEntry costEntry = aSurface->GetCostEntry();
884 MOZ_ASSERT(costEntry.GetCost() <= mAvailableCost,
885 "Cost too large and the caller didn't catch it");
887 if (aSurface->IsLocked()) {
888 mLockedCost += costEntry.GetCost();
889 MOZ_ASSERT(mLockedCost <= mMaxCost, "Locked more than we can hold?");
890 } else {
891 if (NS_WARN_IF(!mCosts.InsertElementSorted(costEntry, fallible))) {
892 mTrackingFailureCount++;
893 return false;
896 // This may fail during XPCOM shutdown, so we need to ensure the object is
897 // tracked before calling RemoveObject in StopTracking.
898 nsresult rv = mExpirationTracker.AddObjectLocked(aSurface, aAutoLock);
899 if (NS_WARN_IF(NS_FAILED(rv))) {
900 DebugOnly<bool> foundInCosts = mCosts.RemoveElementSorted(costEntry);
901 MOZ_ASSERT(foundInCosts, "Lost track of costs for this surface");
902 mTrackingFailureCount++;
903 return false;
907 mAvailableCost -= costEntry.GetCost();
908 return true;
911 void StopTracking(NotNull<CachedSurface*> aSurface, bool aIsTracked,
912 const StaticMutexAutoLock& aAutoLock) {
913 CostEntry costEntry = aSurface->GetCostEntry();
915 if (aSurface->IsLocked()) {
916 MOZ_ASSERT(mLockedCost >= costEntry.GetCost(), "Costs don't balance");
917 mLockedCost -= costEntry.GetCost();
918 // XXX(seth): It'd be nice to use an O(log n) lookup here. This is O(n).
919 MOZ_ASSERT(!mCosts.Contains(costEntry),
920 "Shouldn't have a cost entry for a locked surface");
921 } else {
922 if (MOZ_LIKELY(aSurface->GetExpirationState()->IsTracked())) {
923 MOZ_ASSERT(aIsTracked, "Expiration-tracking a surface unexpectedly!");
924 mExpirationTracker.RemoveObjectLocked(aSurface, aAutoLock);
925 } else {
926 // Our call to AddObject must have failed in StartTracking; most likely
927 // we're in XPCOM shutdown right now.
928 MOZ_ASSERT(!aIsTracked, "Not expiration-tracking an unlocked surface!");
931 DebugOnly<bool> foundInCosts = mCosts.RemoveElementSorted(costEntry);
932 MOZ_ASSERT(foundInCosts, "Lost track of costs for this surface");
935 mAvailableCost += costEntry.GetCost();
936 MOZ_ASSERT(mAvailableCost <= mMaxCost,
937 "More available cost than we started with");
940 LookupResult Lookup(const ImageKey aImageKey, const SurfaceKey& aSurfaceKey,
941 const StaticMutexAutoLock& aAutoLock, bool aMarkUsed) {
942 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
943 if (!cache) {
944 // No cached surfaces for this image.
945 return LookupResult(MatchType::NOT_FOUND);
948 RefPtr<CachedSurface> surface = cache->Lookup(aSurfaceKey, aMarkUsed);
949 if (!surface) {
950 // Lookup in the per-image cache missed.
951 return LookupResult(MatchType::NOT_FOUND);
954 if (surface->IsPlaceholder()) {
955 return LookupResult(MatchType::PENDING);
958 DrawableSurface drawableSurface = surface->GetDrawableSurface();
959 if (!drawableSurface) {
960 // The surface was released by the operating system. Remove the cache
961 // entry as well.
962 Remove(WrapNotNull(surface), /* aStopTracking */ true, aAutoLock);
963 return LookupResult(MatchType::NOT_FOUND);
966 if (aMarkUsed &&
967 !MarkUsed(WrapNotNull(surface), WrapNotNull(cache), aAutoLock)) {
968 Remove(WrapNotNull(surface), /* aStopTracking */ false, aAutoLock);
969 return LookupResult(MatchType::NOT_FOUND);
972 MOZ_ASSERT(surface->GetSurfaceKey() == aSurfaceKey,
973 "Lookup() not returning an exact match?");
974 return LookupResult(std::move(drawableSurface), MatchType::EXACT);
977 LookupResult LookupBestMatch(const ImageKey aImageKey,
978 const SurfaceKey& aSurfaceKey,
979 const StaticMutexAutoLock& aAutoLock,
980 bool aMarkUsed) {
981 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
982 if (!cache) {
983 // No cached surfaces for this image.
984 return LookupResult(
985 MatchType::NOT_FOUND,
986 SurfaceCache::ClampSize(aImageKey, aSurfaceKey.Size()));
989 // Repeatedly look up the best match, trying again if the resulting surface
990 // has been freed by the operating system, until we can either lock a
991 // surface for drawing or there are no matching surfaces left.
992 // XXX(seth): This is O(N^2), but N is expected to be very small. If we
993 // encounter a performance problem here we can revisit this.
995 RefPtr<CachedSurface> surface;
996 DrawableSurface drawableSurface;
997 MatchType matchType = MatchType::NOT_FOUND;
998 IntSize suggestedSize;
999 while (true) {
1000 Tie(surface, matchType, suggestedSize) =
1001 cache->LookupBestMatch(aSurfaceKey);
1003 if (!surface) {
1004 return LookupResult(
1005 matchType, suggestedSize); // Lookup in the per-image cache missed.
1008 drawableSurface = surface->GetDrawableSurface();
1009 if (drawableSurface) {
1010 break;
1013 // The surface was released by the operating system. Remove the cache
1014 // entry as well.
1015 Remove(WrapNotNull(surface), /* aStopTracking */ true, aAutoLock);
1018 MOZ_ASSERT_IF(matchType == MatchType::EXACT,
1019 surface->GetSurfaceKey() == aSurfaceKey);
1020 MOZ_ASSERT_IF(
1021 matchType == MatchType::SUBSTITUTE_BECAUSE_NOT_FOUND ||
1022 matchType == MatchType::SUBSTITUTE_BECAUSE_PENDING,
1023 surface->GetSurfaceKey().SVGContext() == aSurfaceKey.SVGContext() &&
1024 surface->GetSurfaceKey().Playback() == aSurfaceKey.Playback() &&
1025 surface->GetSurfaceKey().Flags() == aSurfaceKey.Flags());
1027 if (matchType == MatchType::EXACT ||
1028 matchType == MatchType::SUBSTITUTE_BECAUSE_BEST) {
1029 if (aMarkUsed &&
1030 !MarkUsed(WrapNotNull(surface), WrapNotNull(cache), aAutoLock)) {
1031 Remove(WrapNotNull(surface), /* aStopTracking */ false, aAutoLock);
1035 return LookupResult(std::move(drawableSurface), matchType, suggestedSize);
1038 bool CanHold(const Cost aCost) const { return aCost <= mMaxCost; }
1040 size_t MaximumCapacity() const { return size_t(mMaxCost); }
1042 void SurfaceAvailable(NotNull<ISurfaceProvider*> aProvider,
1043 const StaticMutexAutoLock& aAutoLock) {
1044 if (!aProvider->Availability().IsPlaceholder()) {
1045 MOZ_ASSERT_UNREACHABLE("Calling SurfaceAvailable on non-placeholder");
1046 return;
1049 // Reinsert the provider, requesting that Insert() mark it available. This
1050 // may or may not succeed, depending on whether some other decoder has
1051 // beaten us to the punch and inserted a non-placeholder version of this
1052 // surface first, but it's fine either way.
1053 // XXX(seth): This could be implemented more efficiently; we should be able
1054 // to just update our data structures without reinserting.
1055 Insert(aProvider, /* aSetAvailable = */ true, aAutoLock);
1058 void LockImage(const ImageKey aImageKey) {
1059 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1060 if (!cache) {
1061 cache = new ImageSurfaceCache(aImageKey);
1062 mImageCaches.InsertOrUpdate(aImageKey, RefPtr{cache});
1065 cache->SetLocked(true);
1067 // We don't relock this image's existing surfaces right away; instead, the
1068 // image should arrange for Lookup() to touch them if they are still useful.
1071 void UnlockImage(const ImageKey aImageKey,
1072 const StaticMutexAutoLock& aAutoLock) {
1073 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1074 if (!cache || !cache->IsLocked()) {
1075 return; // Already unlocked.
1078 cache->SetLocked(false);
1079 DoUnlockSurfaces(WrapNotNull(cache), /* aStaticOnly = */ false, aAutoLock);
1082 void UnlockEntries(const ImageKey aImageKey,
1083 const StaticMutexAutoLock& aAutoLock) {
1084 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1085 if (!cache || !cache->IsLocked()) {
1086 return; // Already unlocked.
1089 // (Note that we *don't* unlock the per-image cache here; that's the
1090 // difference between this and UnlockImage.)
1091 DoUnlockSurfaces(WrapNotNull(cache),
1092 /* aStaticOnly = */
1093 !StaticPrefs::image_mem_animated_discardable_AtStartup(),
1094 aAutoLock);
1097 already_AddRefed<ImageSurfaceCache> RemoveImage(
1098 const ImageKey aImageKey, const StaticMutexAutoLock& aAutoLock) {
1099 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1100 if (!cache) {
1101 return nullptr; // No cached surfaces for this image, so nothing to do.
1104 // Discard all of the cached surfaces for this image.
1105 // XXX(seth): This is O(n^2) since for each item in the cache we are
1106 // removing an element from the costs array. Since n is expected to be
1107 // small, performance should be good, but if usage patterns change we should
1108 // change the data structure used for mCosts.
1109 for (const auto& value : cache->Values()) {
1110 StopTracking(WrapNotNull(value),
1111 /* aIsTracked */ true, aAutoLock);
1114 // The per-image cache isn't needed anymore, so remove it as well.
1115 // This implicitly unlocks the image if it was locked.
1116 mImageCaches.Remove(aImageKey);
1118 // Since we did not actually remove any of the surfaces from the cache
1119 // itself, only stopped tracking them, we should free it outside the lock.
1120 return cache.forget();
1123 void PruneImage(const ImageKey aImageKey,
1124 const StaticMutexAutoLock& aAutoLock) {
1125 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1126 if (!cache) {
1127 return; // No cached surfaces for this image, so nothing to do.
1130 cache->Prune([this, &aAutoLock](NotNull<CachedSurface*> aSurface) -> void {
1131 StopTracking(aSurface, /* aIsTracked */ true, aAutoLock);
1132 // Individual surfaces must be freed outside the lock.
1133 mCachedSurfacesDiscard.AppendElement(aSurface);
1136 MaybeRemoveEmptyCache(aImageKey, cache);
1139 void DiscardAll(const StaticMutexAutoLock& aAutoLock) {
1140 // Remove in order of cost because mCosts is an array and the other data
1141 // structures are all hash tables. Note that locked surfaces are not
1142 // removed, since they aren't present in mCosts.
1143 while (!mCosts.IsEmpty()) {
1144 Remove(mCosts.LastElement().Surface(), /* aStopTracking */ true,
1145 aAutoLock);
1149 void DiscardForMemoryPressure(const StaticMutexAutoLock& aAutoLock) {
1150 // Compute our discardable cost. Since locked surfaces aren't discardable,
1151 // we exclude them.
1152 const Cost discardableCost = (mMaxCost - mAvailableCost) - mLockedCost;
1153 MOZ_ASSERT(discardableCost <= mMaxCost, "Discardable cost doesn't add up");
1155 // Our target is to raise our available cost by (1 / mDiscardFactor) of our
1156 // discardable cost - in other words, we want to end up with about
1157 // (discardableCost / mDiscardFactor) fewer bytes stored in the surface
1158 // cache after we're done.
1159 const Cost targetCost = mAvailableCost + (discardableCost / mDiscardFactor);
1161 if (targetCost > mMaxCost - mLockedCost) {
1162 MOZ_ASSERT_UNREACHABLE("Target cost is more than we can discard");
1163 DiscardAll(aAutoLock);
1164 return;
1167 // Discard surfaces until we've reduced our cost to our target cost.
1168 while (mAvailableCost < targetCost) {
1169 MOZ_ASSERT(!mCosts.IsEmpty(), "Removed everything and still not done");
1170 Remove(mCosts.LastElement().Surface(), /* aStopTracking */ true,
1171 aAutoLock);
1175 void TakeDiscard(nsTArray<RefPtr<CachedSurface>>& aDiscard,
1176 const StaticMutexAutoLock& aAutoLock) {
1177 MOZ_ASSERT(aDiscard.IsEmpty());
1178 aDiscard = std::move(mCachedSurfacesDiscard);
1181 void LockSurface(NotNull<CachedSurface*> aSurface,
1182 const StaticMutexAutoLock& aAutoLock) {
1183 if (aSurface->IsPlaceholder() || aSurface->IsLocked()) {
1184 return;
1187 StopTracking(aSurface, /* aIsTracked */ true, aAutoLock);
1189 // Lock the surface. This can fail.
1190 aSurface->SetLocked(true);
1191 DebugOnly<bool> tracked = StartTracking(aSurface, aAutoLock);
1192 MOZ_ASSERT(tracked);
1195 size_t ShallowSizeOfIncludingThis(
1196 MallocSizeOf aMallocSizeOf, const StaticMutexAutoLock& aAutoLock) const {
1197 size_t bytes =
1198 aMallocSizeOf(this) + mCosts.ShallowSizeOfExcludingThis(aMallocSizeOf) +
1199 mImageCaches.ShallowSizeOfExcludingThis(aMallocSizeOf) +
1200 mCachedSurfacesDiscard.ShallowSizeOfExcludingThis(aMallocSizeOf) +
1201 mExpirationTracker.ShallowSizeOfExcludingThis(aMallocSizeOf);
1202 for (const auto& data : mImageCaches.Values()) {
1203 bytes += data->ShallowSizeOfIncludingThis(aMallocSizeOf);
1205 return bytes;
1208 NS_IMETHOD
1209 CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData,
1210 bool aAnonymize) override {
1211 StaticMutexAutoLock lock(sInstanceMutex);
1213 uint32_t lockedImageCount = 0;
1214 uint32_t totalSurfaceCount = 0;
1215 uint32_t lockedSurfaceCount = 0;
1216 for (const auto& cache : mImageCaches.Values()) {
1217 totalSurfaceCount += cache->Count();
1218 if (cache->IsLocked()) {
1219 ++lockedImageCount;
1221 for (const auto& value : cache->Values()) {
1222 if (value->IsLocked()) {
1223 ++lockedSurfaceCount;
1228 // clang-format off
1229 // We have explicit memory reporting for the surface cache which is more
1230 // accurate than the cost metrics we report here, but these metrics are
1231 // still useful to report, since they control the cache's behavior.
1232 MOZ_COLLECT_REPORT(
1233 "explicit/images/cache/overhead", KIND_HEAP, UNITS_BYTES,
1234 ShallowSizeOfIncludingThis(SurfaceCacheMallocSizeOf, lock),
1235 "Memory used by the surface cache data structures, excluding surface data.");
1237 MOZ_COLLECT_REPORT(
1238 "imagelib-surface-cache-estimated-total",
1239 KIND_OTHER, UNITS_BYTES, (mMaxCost - mAvailableCost),
1240 "Estimated total memory used by the imagelib surface cache.");
1242 MOZ_COLLECT_REPORT(
1243 "imagelib-surface-cache-estimated-locked",
1244 KIND_OTHER, UNITS_BYTES, mLockedCost,
1245 "Estimated memory used by locked surfaces in the imagelib surface cache.");
1247 MOZ_COLLECT_REPORT(
1248 "imagelib-surface-cache-tracked-cost-count",
1249 KIND_OTHER, UNITS_COUNT, mCosts.Length(),
1250 "Total number of surfaces tracked for cost (and expiry) in the imagelib surface cache.");
1252 MOZ_COLLECT_REPORT(
1253 "imagelib-surface-cache-tracked-expiry-count",
1254 KIND_OTHER, UNITS_COUNT, mExpirationTracker.Length(lock),
1255 "Total number of surfaces tracked for expiry (and cost) in the imagelib surface cache.");
1257 MOZ_COLLECT_REPORT(
1258 "imagelib-surface-cache-image-count",
1259 KIND_OTHER, UNITS_COUNT, mImageCaches.Count(),
1260 "Total number of images in the imagelib surface cache.");
1262 MOZ_COLLECT_REPORT(
1263 "imagelib-surface-cache-locked-image-count",
1264 KIND_OTHER, UNITS_COUNT, lockedImageCount,
1265 "Total number of locked images in the imagelib surface cache.");
1267 MOZ_COLLECT_REPORT(
1268 "imagelib-surface-cache-image-surface-count",
1269 KIND_OTHER, UNITS_COUNT, totalSurfaceCount,
1270 "Total number of surfaces in the imagelib surface cache.");
1272 MOZ_COLLECT_REPORT(
1273 "imagelib-surface-cache-locked-surfaces-count",
1274 KIND_OTHER, UNITS_COUNT, lockedSurfaceCount,
1275 "Total number of locked surfaces in the imagelib surface cache.");
1277 MOZ_COLLECT_REPORT(
1278 "imagelib-surface-cache-overflow-count",
1279 KIND_OTHER, UNITS_COUNT, mOverflowCount,
1280 "Count of how many times the surface cache has hit its capacity and been "
1281 "unable to insert a new surface.");
1283 MOZ_COLLECT_REPORT(
1284 "imagelib-surface-cache-tracking-failure-count",
1285 KIND_OTHER, UNITS_COUNT, mTrackingFailureCount,
1286 "Count of how many times the surface cache has failed to begin tracking a "
1287 "given surface.");
1289 MOZ_COLLECT_REPORT(
1290 "imagelib-surface-cache-already-present-count",
1291 KIND_OTHER, UNITS_COUNT, mAlreadyPresentCount,
1292 "Count of how many times the surface cache has failed to insert a surface "
1293 "because it is already present.");
1295 MOZ_COLLECT_REPORT(
1296 "imagelib-surface-cache-table-failure-count",
1297 KIND_OTHER, UNITS_COUNT, mTableFailureCount,
1298 "Count of how many times the surface cache has failed to insert a surface "
1299 "because a hash table could not accept an entry.");
1300 // clang-format on
1302 return NS_OK;
1305 void CollectSizeOfSurfaces(const ImageKey aImageKey,
1306 nsTArray<SurfaceMemoryCounter>& aCounters,
1307 MallocSizeOf aMallocSizeOf,
1308 const StaticMutexAutoLock& aAutoLock) {
1309 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1310 if (!cache) {
1311 return; // No surfaces for this image.
1314 // Report all surfaces in the per-image cache.
1315 cache->CollectSizeOfSurfaces(
1316 aCounters, aMallocSizeOf,
1317 [this, &aAutoLock](NotNull<CachedSurface*> aSurface) -> void {
1318 StopTracking(aSurface, /* aIsTracked */ true, aAutoLock);
1319 // Individual surfaces must be freed outside the lock.
1320 mCachedSurfacesDiscard.AppendElement(aSurface);
1323 MaybeRemoveEmptyCache(aImageKey, cache);
1326 void ReleaseImageOnMainThread(already_AddRefed<image::Image>&& aImage,
1327 const StaticMutexAutoLock& aAutoLock) {
1328 RefPtr<image::Image> image = aImage;
1329 if (!image) {
1330 return;
1333 bool needsDispatch = mReleasingImagesOnMainThread.IsEmpty();
1334 mReleasingImagesOnMainThread.AppendElement(image);
1336 if (!needsDispatch || gXPCOMThreadsShutDown) {
1337 // Either there is already a ongoing task for ClearReleasingImages() or
1338 // it's too late in shutdown to dispatch.
1339 return;
1342 NS_DispatchToMainThread(NS_NewRunnableFunction(
1343 "SurfaceCacheImpl::ReleaseImageOnMainThread",
1344 []() -> void { SurfaceCache::ClearReleasingImages(); }));
1347 void TakeReleasingImages(nsTArray<RefPtr<image::Image>>& aImage,
1348 const StaticMutexAutoLock& aAutoLock) {
1349 MOZ_ASSERT(NS_IsMainThread());
1350 aImage.SwapElements(mReleasingImagesOnMainThread);
1353 private:
1354 already_AddRefed<ImageSurfaceCache> GetImageCache(const ImageKey aImageKey) {
1355 RefPtr<ImageSurfaceCache> imageCache;
1356 mImageCaches.Get(aImageKey, getter_AddRefs(imageCache));
1357 return imageCache.forget();
1360 void MaybeRemoveEmptyCache(const ImageKey aImageKey,
1361 ImageSurfaceCache* aCache) {
1362 // Remove the per-image cache if it's unneeded now. Keep it if the image is
1363 // locked, since the per-image cache is where we store that state. Note that
1364 // we don't push it into mImageCachesDiscard because all of its surfaces
1365 // have been removed, so it is safe to free while holding the lock.
1366 if (aCache->IsEmpty() && !aCache->IsLocked()) {
1367 mImageCaches.Remove(aImageKey);
1371 // This is similar to CanHold() except that it takes into account the costs of
1372 // locked surfaces. It's used internally in Insert(), but it's not exposed
1373 // publicly because we permit multithreaded access to the surface cache, which
1374 // means that the result would be meaningless: another thread could insert a
1375 // surface or lock an image at any time.
1376 bool CanHoldAfterDiscarding(const Cost aCost) const {
1377 return aCost <= mMaxCost - mLockedCost;
1380 bool MarkUsed(NotNull<CachedSurface*> aSurface,
1381 NotNull<ImageSurfaceCache*> aCache,
1382 const StaticMutexAutoLock& aAutoLock) {
1383 if (aCache->IsLocked()) {
1384 LockSurface(aSurface, aAutoLock);
1385 return true;
1388 nsresult rv = mExpirationTracker.MarkUsedLocked(aSurface, aAutoLock);
1389 if (NS_WARN_IF(NS_FAILED(rv))) {
1390 // If mark used fails, it is because it failed to reinsert the surface
1391 // after removing it from the tracker. Thus we need to update our
1392 // own accounting but otherwise expect it to be untracked.
1393 StopTracking(aSurface, /* aIsTracked */ false, aAutoLock);
1394 return false;
1396 return true;
1399 void DoUnlockSurfaces(NotNull<ImageSurfaceCache*> aCache, bool aStaticOnly,
1400 const StaticMutexAutoLock& aAutoLock) {
1401 AutoTArray<NotNull<CachedSurface*>, 8> discard;
1403 // Unlock all the surfaces the per-image cache is holding.
1404 for (const auto& value : aCache->Values()) {
1405 NotNull<CachedSurface*> surface = WrapNotNull(value);
1406 if (surface->IsPlaceholder() || !surface->IsLocked()) {
1407 continue;
1409 if (aStaticOnly &&
1410 surface->GetSurfaceKey().Playback() != PlaybackType::eStatic) {
1411 continue;
1413 StopTracking(surface, /* aIsTracked */ true, aAutoLock);
1414 surface->SetLocked(false);
1415 if (MOZ_UNLIKELY(!StartTracking(surface, aAutoLock))) {
1416 discard.AppendElement(surface);
1420 // Discard any that we failed to track.
1421 for (auto iter = discard.begin(); iter != discard.end(); ++iter) {
1422 Remove(*iter, /* aStopTracking */ false, aAutoLock);
1426 void RemoveEntry(const ImageKey aImageKey, const SurfaceKey& aSurfaceKey,
1427 const StaticMutexAutoLock& aAutoLock) {
1428 RefPtr<ImageSurfaceCache> cache = GetImageCache(aImageKey);
1429 if (!cache) {
1430 return; // No cached surfaces for this image.
1433 RefPtr<CachedSurface> surface =
1434 cache->Lookup(aSurfaceKey, /* aForAccess = */ false);
1435 if (!surface) {
1436 return; // Lookup in the per-image cache missed.
1439 Remove(WrapNotNull(surface), /* aStopTracking */ true, aAutoLock);
1442 class SurfaceTracker final
1443 : public ExpirationTrackerImpl<CachedSurface, 2, StaticMutex,
1444 StaticMutexAutoLock> {
1445 public:
1446 explicit SurfaceTracker(uint32_t aSurfaceCacheExpirationTimeMS)
1447 : ExpirationTrackerImpl<CachedSurface, 2, StaticMutex,
1448 StaticMutexAutoLock>(
1449 aSurfaceCacheExpirationTimeMS, "SurfaceTracker") {}
1451 protected:
1452 void NotifyExpiredLocked(CachedSurface* aSurface,
1453 const StaticMutexAutoLock& aAutoLock) override {
1454 sInstance->Remove(WrapNotNull(aSurface), /* aStopTracking */ true,
1455 aAutoLock);
1458 void NotifyHandlerEndLocked(const StaticMutexAutoLock& aAutoLock) override {
1459 sInstance->TakeDiscard(mDiscard, aAutoLock);
1462 void NotifyHandlerEnd() override {
1463 nsTArray<RefPtr<CachedSurface>> discard(std::move(mDiscard));
1466 StaticMutex& GetMutex() override { return sInstanceMutex; }
1468 nsTArray<RefPtr<CachedSurface>> mDiscard;
1471 class MemoryPressureObserver final : public nsIObserver {
1472 public:
1473 NS_DECL_ISUPPORTS
1475 NS_IMETHOD Observe(nsISupports*, const char* aTopic,
1476 const char16_t*) override {
1477 nsTArray<RefPtr<CachedSurface>> discard;
1479 StaticMutexAutoLock lock(sInstanceMutex);
1480 if (sInstance && strcmp(aTopic, "memory-pressure") == 0) {
1481 sInstance->DiscardForMemoryPressure(lock);
1482 sInstance->TakeDiscard(discard, lock);
1485 return NS_OK;
1488 private:
1489 virtual ~MemoryPressureObserver() {}
1492 nsTArray<CostEntry> mCosts;
1493 nsRefPtrHashtable<nsPtrHashKey<Image>, ImageSurfaceCache> mImageCaches;
1494 nsTArray<RefPtr<CachedSurface>> mCachedSurfacesDiscard;
1495 SurfaceTracker mExpirationTracker;
1496 RefPtr<MemoryPressureObserver> mMemoryPressureObserver;
1497 nsTArray<RefPtr<image::Image>> mReleasingImagesOnMainThread;
1498 const uint32_t mDiscardFactor;
1499 const Cost mMaxCost;
1500 Cost mAvailableCost;
1501 Cost mLockedCost;
1502 size_t mOverflowCount;
1503 size_t mAlreadyPresentCount;
1504 size_t mTableFailureCount;
1505 size_t mTrackingFailureCount;
1508 NS_IMPL_ISUPPORTS(SurfaceCacheImpl, nsIMemoryReporter)
1509 NS_IMPL_ISUPPORTS(SurfaceCacheImpl::MemoryPressureObserver, nsIObserver)
1511 ///////////////////////////////////////////////////////////////////////////////
1512 // Public API
1513 ///////////////////////////////////////////////////////////////////////////////
1515 /* static */
1516 void SurfaceCache::Initialize() {
1517 // Initialize preferences.
1518 MOZ_ASSERT(NS_IsMainThread());
1519 MOZ_ASSERT(!sInstance, "Shouldn't initialize more than once");
1521 // See StaticPrefs for the default values of these preferences.
1523 // Length of time before an unused surface is removed from the cache, in
1524 // milliseconds.
1525 uint32_t surfaceCacheExpirationTimeMS =
1526 StaticPrefs::image_mem_surfacecache_min_expiration_ms_AtStartup();
1528 // What fraction of the memory used by the surface cache we should discard
1529 // when we get a memory pressure notification. This value is interpreted as
1530 // 1/N, so 1 means to discard everything, 2 means to discard about half of the
1531 // memory we're using, and so forth. We clamp it to avoid division by zero.
1532 uint32_t surfaceCacheDiscardFactor =
1533 max(StaticPrefs::image_mem_surfacecache_discard_factor_AtStartup(), 1u);
1535 // Maximum size of the surface cache, in kilobytes.
1536 uint64_t surfaceCacheMaxSizeKB =
1537 StaticPrefs::image_mem_surfacecache_max_size_kb_AtStartup();
1539 if (sizeof(uintptr_t) <= 4) {
1540 // Limit surface cache to 1 GB if our address space is 32 bit.
1541 surfaceCacheMaxSizeKB = 1024 * 1024;
1544 // A knob determining the actual size of the surface cache. Currently the
1545 // cache is (size of main memory) / (surface cache size factor) KB
1546 // or (surface cache max size) KB, whichever is smaller. The formula
1547 // may change in the future, though.
1548 // For example, a value of 4 would yield a 256MB cache on a 1GB machine.
1549 // The smallest machines we are likely to run this code on have 256MB
1550 // of memory, which would yield a 64MB cache on this setting.
1551 // We clamp this value to avoid division by zero.
1552 uint32_t surfaceCacheSizeFactor =
1553 max(StaticPrefs::image_mem_surfacecache_size_factor_AtStartup(), 1u);
1555 // Compute the size of the surface cache.
1556 uint64_t memorySize = PR_GetPhysicalMemorySize();
1557 if (memorySize == 0) {
1558 MOZ_ASSERT_UNREACHABLE("PR_GetPhysicalMemorySize not implemented here");
1559 memorySize = 256 * 1024 * 1024; // Fall back to 256MB.
1561 uint64_t proposedSize = memorySize / surfaceCacheSizeFactor;
1562 uint64_t surfaceCacheSizeBytes =
1563 min(proposedSize, surfaceCacheMaxSizeKB * 1024);
1564 uint32_t finalSurfaceCacheSizeBytes =
1565 min(surfaceCacheSizeBytes, uint64_t(UINT32_MAX));
1567 // Create the surface cache singleton with the requested settings. Note that
1568 // the size is a limit that the cache may not grow beyond, but we do not
1569 // actually allocate any storage for surfaces at this time.
1570 sInstance = new SurfaceCacheImpl(surfaceCacheExpirationTimeMS,
1571 surfaceCacheDiscardFactor,
1572 finalSurfaceCacheSizeBytes);
1573 sInstance->InitMemoryReporter();
1576 /* static */
1577 void SurfaceCache::Shutdown() {
1578 RefPtr<SurfaceCacheImpl> cache;
1580 StaticMutexAutoLock lock(sInstanceMutex);
1581 MOZ_ASSERT(NS_IsMainThread());
1582 MOZ_ASSERT(sInstance, "No singleton - was Shutdown() called twice?");
1583 cache = sInstance.forget();
1587 /* static */
1588 LookupResult SurfaceCache::Lookup(const ImageKey aImageKey,
1589 const SurfaceKey& aSurfaceKey,
1590 bool aMarkUsed) {
1591 nsTArray<RefPtr<CachedSurface>> discard;
1592 LookupResult rv(MatchType::NOT_FOUND);
1595 StaticMutexAutoLock lock(sInstanceMutex);
1596 if (!sInstance) {
1597 return rv;
1600 rv = sInstance->Lookup(aImageKey, aSurfaceKey, lock, aMarkUsed);
1601 sInstance->TakeDiscard(discard, lock);
1604 return rv;
1607 /* static */
1608 LookupResult SurfaceCache::LookupBestMatch(const ImageKey aImageKey,
1609 const SurfaceKey& aSurfaceKey,
1610 bool aMarkUsed) {
1611 nsTArray<RefPtr<CachedSurface>> discard;
1612 LookupResult rv(MatchType::NOT_FOUND);
1615 StaticMutexAutoLock lock(sInstanceMutex);
1616 if (!sInstance) {
1617 return rv;
1620 rv = sInstance->LookupBestMatch(aImageKey, aSurfaceKey, lock, aMarkUsed);
1621 sInstance->TakeDiscard(discard, lock);
1624 return rv;
1627 /* static */
1628 InsertOutcome SurfaceCache::Insert(NotNull<ISurfaceProvider*> aProvider) {
1629 nsTArray<RefPtr<CachedSurface>> discard;
1630 InsertOutcome rv(InsertOutcome::FAILURE);
1633 StaticMutexAutoLock lock(sInstanceMutex);
1634 if (!sInstance) {
1635 return rv;
1638 rv = sInstance->Insert(aProvider, /* aSetAvailable = */ false, lock);
1639 sInstance->TakeDiscard(discard, lock);
1642 return rv;
1645 /* static */
1646 bool SurfaceCache::CanHold(const IntSize& aSize,
1647 uint32_t aBytesPerPixel /* = 4 */) {
1648 StaticMutexAutoLock lock(sInstanceMutex);
1649 if (!sInstance) {
1650 return false;
1653 Cost cost = ComputeCost(aSize, aBytesPerPixel);
1654 return sInstance->CanHold(cost);
1657 /* static */
1658 bool SurfaceCache::CanHold(size_t aSize) {
1659 StaticMutexAutoLock lock(sInstanceMutex);
1660 if (!sInstance) {
1661 return false;
1664 return sInstance->CanHold(aSize);
1667 /* static */
1668 void SurfaceCache::SurfaceAvailable(NotNull<ISurfaceProvider*> aProvider) {
1669 StaticMutexAutoLock lock(sInstanceMutex);
1670 if (!sInstance) {
1671 return;
1674 sInstance->SurfaceAvailable(aProvider, lock);
1677 /* static */
1678 void SurfaceCache::LockImage(const ImageKey aImageKey) {
1679 StaticMutexAutoLock lock(sInstanceMutex);
1680 if (sInstance) {
1681 return sInstance->LockImage(aImageKey);
1685 /* static */
1686 void SurfaceCache::UnlockImage(const ImageKey aImageKey) {
1687 StaticMutexAutoLock lock(sInstanceMutex);
1688 if (sInstance) {
1689 return sInstance->UnlockImage(aImageKey, lock);
1693 /* static */
1694 void SurfaceCache::UnlockEntries(const ImageKey aImageKey) {
1695 StaticMutexAutoLock lock(sInstanceMutex);
1696 if (sInstance) {
1697 return sInstance->UnlockEntries(aImageKey, lock);
1701 /* static */
1702 void SurfaceCache::RemoveImage(const ImageKey aImageKey) {
1703 RefPtr<ImageSurfaceCache> discard;
1705 StaticMutexAutoLock lock(sInstanceMutex);
1706 if (sInstance) {
1707 discard = sInstance->RemoveImage(aImageKey, lock);
1712 /* static */
1713 void SurfaceCache::PruneImage(const ImageKey aImageKey) {
1714 nsTArray<RefPtr<CachedSurface>> discard;
1716 StaticMutexAutoLock lock(sInstanceMutex);
1717 if (sInstance) {
1718 sInstance->PruneImage(aImageKey, lock);
1719 sInstance->TakeDiscard(discard, lock);
1724 /* static */
1725 void SurfaceCache::DiscardAll() {
1726 nsTArray<RefPtr<CachedSurface>> discard;
1728 StaticMutexAutoLock lock(sInstanceMutex);
1729 if (sInstance) {
1730 sInstance->DiscardAll(lock);
1731 sInstance->TakeDiscard(discard, lock);
1736 /* static */
1737 void SurfaceCache::CollectSizeOfSurfaces(
1738 const ImageKey aImageKey, nsTArray<SurfaceMemoryCounter>& aCounters,
1739 MallocSizeOf aMallocSizeOf) {
1740 nsTArray<RefPtr<CachedSurface>> discard;
1742 StaticMutexAutoLock lock(sInstanceMutex);
1743 if (!sInstance) {
1744 return;
1747 sInstance->CollectSizeOfSurfaces(aImageKey, aCounters, aMallocSizeOf, lock);
1748 sInstance->TakeDiscard(discard, lock);
1752 /* static */
1753 size_t SurfaceCache::MaximumCapacity() {
1754 StaticMutexAutoLock lock(sInstanceMutex);
1755 if (!sInstance) {
1756 return 0;
1759 return sInstance->MaximumCapacity();
1762 /* static */
1763 bool SurfaceCache::IsLegalSize(const IntSize& aSize) {
1764 // reject over-wide or over-tall images
1765 const int32_t k64KLimit = 0x0000FFFF;
1766 if (MOZ_UNLIKELY(aSize.width > k64KLimit || aSize.height > k64KLimit)) {
1767 NS_WARNING("image too big");
1768 return false;
1771 // protect against invalid sizes
1772 if (MOZ_UNLIKELY(aSize.height <= 0 || aSize.width <= 0)) {
1773 return false;
1776 // check to make sure we don't overflow a 32-bit
1777 CheckedInt32 requiredBytes =
1778 CheckedInt32(aSize.width) * CheckedInt32(aSize.height) * 4;
1779 if (MOZ_UNLIKELY(!requiredBytes.isValid())) {
1780 NS_WARNING("width or height too large");
1781 return false;
1783 return true;
1786 IntSize SurfaceCache::ClampVectorSize(const IntSize& aSize) {
1787 // If we exceed the maximum, we need to scale the size downwards to fit.
1788 // It shouldn't get here if it is significantly larger because
1789 // VectorImage::UseSurfaceCacheForSize should prevent us from requesting
1790 // a rasterized version of a surface greater than 4x the maximum.
1791 int32_t maxSizeKB =
1792 StaticPrefs::image_cache_max_rasterized_svg_threshold_kb();
1793 if (maxSizeKB <= 0) {
1794 return aSize;
1797 int64_t proposedKB = int64_t(aSize.width) * aSize.height / 256;
1798 if (maxSizeKB >= proposedKB) {
1799 return aSize;
1802 double scale = sqrt(double(maxSizeKB) / proposedKB);
1803 return IntSize(int32_t(scale * aSize.width), int32_t(scale * aSize.height));
1806 IntSize SurfaceCache::ClampSize(ImageKey aImageKey, const IntSize& aSize) {
1807 if (aImageKey->GetType() != imgIContainer::TYPE_VECTOR) {
1808 return aSize;
1811 return ClampVectorSize(aSize);
1814 /* static */
1815 void SurfaceCache::ReleaseImageOnMainThread(
1816 already_AddRefed<image::Image> aImage, bool aAlwaysProxy) {
1817 if (NS_IsMainThread() && !aAlwaysProxy) {
1818 RefPtr<image::Image> image = std::move(aImage);
1819 return;
1822 // Don't try to dispatch the release after shutdown, we'll just leak the
1823 // runnable.
1824 if (gXPCOMThreadsShutDown) {
1825 return;
1828 StaticMutexAutoLock lock(sInstanceMutex);
1829 if (sInstance) {
1830 sInstance->ReleaseImageOnMainThread(std::move(aImage), lock);
1831 } else {
1832 NS_ReleaseOnMainThread("SurfaceCache::ReleaseImageOnMainThread",
1833 std::move(aImage), /* aAlwaysProxy */ true);
1837 /* static */
1838 void SurfaceCache::ClearReleasingImages() {
1839 MOZ_ASSERT(NS_IsMainThread());
1841 nsTArray<RefPtr<image::Image>> images;
1843 StaticMutexAutoLock lock(sInstanceMutex);
1844 if (sInstance) {
1845 sInstance->TakeReleasingImages(images, lock);
1850 } // namespace image
1851 } // namespace mozilla