SurfaceCache.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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/. */
  5. /**
  6. * SurfaceCache is a service for caching temporary surfaces and decoded image
  7. * data in imagelib.
  8. */
  9. #ifndef mozilla_image_SurfaceCache_h
  10. #define mozilla_image_SurfaceCache_h
  11. #include "mozilla/Maybe.h" // for Maybe
  12. #include "mozilla/NotNull.h"
  13. #include "mozilla/MemoryReporting.h" // for MallocSizeOf
  14. #include "mozilla/HashFunctions.h" // for HashGeneric and AddToHash
  15. #include "gfx2DGlue.h"
  16. #include "gfxPoint.h" // for gfxSize
  17. #include "nsCOMPtr.h" // for already_AddRefed
  18. #include "mozilla/gfx/Point.h" // for mozilla::gfx::IntSize
  19. #include "mozilla/gfx/2D.h" // for SourceSurface
  20. #include "PlaybackType.h"
  21. #include "SurfaceFlags.h"
  22. #include "SVGImageContext.h" // for SVGImageContext
  23. namespace mozilla {
  24. namespace image {
  25. class Image;
  26. class ISurfaceProvider;
  27. class LookupResult;
  28. class SurfaceCacheImpl;
  29. struct SurfaceMemoryCounter;
  30. /*
  31. * ImageKey contains the information we need to look up all SurfaceCache entries
  32. * for a particular image.
  33. */
  34. typedef Image* ImageKey;
  35. /*
  36. * SurfaceKey contains the information we need to look up a specific
  37. * SurfaceCache entry. Together with an ImageKey, this uniquely identifies the
  38. * surface.
  39. *
  40. * Callers should construct a SurfaceKey using the appropriate helper function
  41. * for their image type - either RasterSurfaceKey or VectorSurfaceKey.
  42. */
  43. class SurfaceKey
  44. {
  45. typedef gfx::IntSize IntSize;
  46. public:
  47. bool operator==(const SurfaceKey& aOther) const
  48. {
  49. return aOther.mSize == mSize &&
  50. aOther.mSVGContext == mSVGContext &&
  51. aOther.mPlayback == mPlayback &&
  52. aOther.mFlags == mFlags;
  53. }
  54. uint32_t Hash() const
  55. {
  56. uint32_t hash = HashGeneric(mSize.width, mSize.height);
  57. hash = AddToHash(hash, mSVGContext.map(HashSIC).valueOr(0));
  58. hash = AddToHash(hash, uint8_t(mPlayback), uint32_t(mFlags));
  59. return hash;
  60. }
  61. const IntSize& Size() const { return mSize; }
  62. Maybe<SVGImageContext> SVGContext() const { return mSVGContext; }
  63. PlaybackType Playback() const { return mPlayback; }
  64. SurfaceFlags Flags() const { return mFlags; }
  65. private:
  66. SurfaceKey(const IntSize& aSize,
  67. const Maybe<SVGImageContext>& aSVGContext,
  68. PlaybackType aPlayback,
  69. SurfaceFlags aFlags)
  70. : mSize(aSize)
  71. , mSVGContext(aSVGContext)
  72. , mPlayback(aPlayback)
  73. , mFlags(aFlags)
  74. { }
  75. static uint32_t HashSIC(const SVGImageContext& aSIC) {
  76. return aSIC.Hash();
  77. }
  78. friend SurfaceKey RasterSurfaceKey(const IntSize&, SurfaceFlags, PlaybackType);
  79. friend SurfaceKey VectorSurfaceKey(const IntSize&,
  80. const Maybe<SVGImageContext>&);
  81. IntSize mSize;
  82. Maybe<SVGImageContext> mSVGContext;
  83. PlaybackType mPlayback;
  84. SurfaceFlags mFlags;
  85. };
  86. inline SurfaceKey
  87. RasterSurfaceKey(const gfx::IntSize& aSize,
  88. SurfaceFlags aFlags,
  89. PlaybackType aPlayback)
  90. {
  91. return SurfaceKey(aSize, Nothing(), aPlayback, aFlags);
  92. }
  93. inline SurfaceKey
  94. VectorSurfaceKey(const gfx::IntSize& aSize,
  95. const Maybe<SVGImageContext>& aSVGContext)
  96. {
  97. // We don't care about aFlags for VectorImage because none of the flags we
  98. // have right now influence VectorImage's rendering. If we add a new flag that
  99. // *does* affect how a VectorImage renders, we'll have to change this.
  100. // Similarly, we don't accept a PlaybackType parameter because we don't
  101. // currently cache frames of animated SVG images.
  102. return SurfaceKey(aSize, aSVGContext, PlaybackType::eStatic,
  103. DefaultSurfaceFlags());
  104. }
  105. /**
  106. * AvailabilityState is used to track whether an ISurfaceProvider has a surface
  107. * available or is just a placeholder.
  108. *
  109. * To ensure that availability changes are atomic (and especially that internal
  110. * SurfaceCache code doesn't have to deal with asynchronous availability
  111. * changes), an ISurfaceProvider which starts as a placeholder can only reveal
  112. * the fact that it now has a surface available via a call to
  113. * SurfaceCache::SurfaceAvailable().
  114. */
  115. class AvailabilityState
  116. {
  117. public:
  118. static AvailabilityState StartAvailable() { return AvailabilityState(true); }
  119. static AvailabilityState StartAsPlaceholder() { return AvailabilityState(false); }
  120. bool IsAvailable() const { return mIsAvailable; }
  121. bool IsPlaceholder() const { return !mIsAvailable; }
  122. private:
  123. friend class SurfaceCacheImpl;
  124. explicit AvailabilityState(bool aIsAvailable) : mIsAvailable(aIsAvailable) { }
  125. void SetAvailable() { mIsAvailable = true; }
  126. bool mIsAvailable;
  127. };
  128. enum class InsertOutcome : uint8_t {
  129. SUCCESS, // Success (but see Insert documentation).
  130. FAILURE, // Couldn't insert (e.g., for capacity reasons).
  131. FAILURE_ALREADY_PRESENT // A surface with the same key is already present.
  132. };
  133. /**
  134. * SurfaceCache is an ImageLib-global service that allows caching of decoded
  135. * image surfaces, temporary surfaces (e.g. for caching rotated or clipped
  136. * versions of images), or dynamically generated surfaces (e.g. for animations).
  137. * SurfaceCache entries normally expire from the cache automatically if they go
  138. * too long without being accessed.
  139. *
  140. * Because SurfaceCache must support both normal surfaces and dynamically
  141. * generated surfaces, it does not actually hold surfaces directly. Instead, it
  142. * holds ISurfaceProvider objects which can provide access to a surface when
  143. * requested; SurfaceCache doesn't care about the details of how this is
  144. * accomplished.
  145. *
  146. * Sometime it's useful to temporarily prevent entries from expiring from the
  147. * cache. This is most often because losing the data could harm the user
  148. * experience (for example, we often don't want to allow surfaces that are
  149. * currently visible to expire) or because it's not possible to rematerialize
  150. * the surface. SurfaceCache supports this through the use of image locking; see
  151. * the comments for Insert() and LockImage() for more details.
  152. *
  153. * Any image which stores surfaces in the SurfaceCache *must* ensure that it
  154. * calls RemoveImage() before it is destroyed. See the comments for
  155. * RemoveImage() for more details.
  156. */
  157. struct SurfaceCache
  158. {
  159. typedef gfx::IntSize IntSize;
  160. /**
  161. * Initialize static data. Called during imagelib module initialization.
  162. */
  163. static void Initialize();
  164. /**
  165. * Release static data. Called during imagelib module shutdown.
  166. */
  167. static void Shutdown();
  168. /**
  169. * Looks up the requested cache entry and returns a drawable reference to its
  170. * associated surface.
  171. *
  172. * If the image associated with the cache entry is locked, then the entry will
  173. * be locked before it is returned.
  174. *
  175. * If a matching ISurfaceProvider was found in the cache, but SurfaceCache
  176. * couldn't obtain a surface from it (e.g. because it had stored its surface
  177. * in a volatile buffer which was discarded by the OS) then it is
  178. * automatically removed from the cache and an empty LookupResult is returned.
  179. * Note that this will never happen to ISurfaceProviders associated with a
  180. * locked image; SurfaceCache tells such ISurfaceProviders to keep a strong
  181. * references to their data internally.
  182. *
  183. * @param aImageKey Key data identifying which image the cache entry
  184. * belongs to.
  185. * @param aSurfaceKey Key data which uniquely identifies the requested
  186. * cache entry.
  187. * @return a LookupResult which will contain a DrawableSurface
  188. * if the cache entry was found.
  189. */
  190. static LookupResult Lookup(const ImageKey aImageKey,
  191. const SurfaceKey& aSurfaceKey);
  192. /**
  193. * Looks up the best matching cache entry and returns a drawable reference to
  194. * its associated surface.
  195. *
  196. * The result may vary from the requested cache entry only in terms of size.
  197. *
  198. * @param aImageKey Key data identifying which image the cache entry
  199. * belongs to.
  200. * @param aSurfaceKey Key data which uniquely identifies the requested
  201. * cache entry.
  202. * @return a LookupResult which will contain a DrawableSurface
  203. * if a cache entry similar to the one the caller
  204. * requested could be found. Callers can use
  205. * LookupResult::IsExactMatch() to check whether the
  206. * returned surface exactly matches @aSurfaceKey.
  207. */
  208. static LookupResult LookupBestMatch(const ImageKey aImageKey,
  209. const SurfaceKey& aSurfaceKey);
  210. /**
  211. * Insert an ISurfaceProvider into the cache. If an entry with the same
  212. * ImageKey and SurfaceKey is already in the cache, Insert returns
  213. * FAILURE_ALREADY_PRESENT. If a matching placeholder is already present, it
  214. * is replaced.
  215. *
  216. * Cache entries will never expire as long as they remain locked, but if they
  217. * become unlocked, they can expire either because the SurfaceCache runs out
  218. * of capacity or because they've gone too long without being used. When it
  219. * is first inserted, a cache entry is locked if its associated image is
  220. * locked. When that image is later unlocked, the cache entry becomes
  221. * unlocked too. To become locked again at that point, two things must happen:
  222. * the image must become locked again (via LockImage()), and the cache entry
  223. * must be touched again (via one of the Lookup() functions).
  224. *
  225. * All of this means that a very particular procedure has to be followed for
  226. * cache entries which cannot be rematerialized. First, they must be inserted
  227. * *after* the image is locked with LockImage(); if you use the other order,
  228. * the cache entry might expire before LockImage() gets called or before the
  229. * entry is touched again by Lookup(). Second, the image they are associated
  230. * with must never be unlocked.
  231. *
  232. * If a cache entry cannot be rematerialized, it may be important to know
  233. * whether it was inserted into the cache successfully. Insert() returns
  234. * FAILURE if it failed to insert the cache entry, which could happen because
  235. * of capacity reasons, or because it was already freed by the OS. If the
  236. * cache entry isn't associated with a locked image, checking for SUCCESS or
  237. * FAILURE is useless: the entry might expire immediately after being
  238. * inserted, even though Insert() returned SUCCESS. Thus, many callers do not
  239. * need to check the result of Insert() at all.
  240. *
  241. * @param aProvider The new cache entry to insert into the cache.
  242. * @return SUCCESS if the cache entry was inserted successfully. (But see above
  243. * for more information about when you should check this.)
  244. * FAILURE if the cache entry could not be inserted, e.g. for capacity
  245. * reasons. (But see above for more information about when you
  246. * should check this.)
  247. * FAILURE_ALREADY_PRESENT if an entry with the same ImageKey and
  248. * SurfaceKey already exists in the cache.
  249. */
  250. static InsertOutcome Insert(NotNull<ISurfaceProvider*> aProvider);
  251. /**
  252. * Mark the cache entry @aProvider as having an available surface. This turns
  253. * a placeholder cache entry into a normal cache entry. The cache entry
  254. * becomes locked if the associated image is locked; otherwise, it starts in
  255. * the unlocked state.
  256. *
  257. * If the cache entry containing @aProvider has already been evicted from the
  258. * surface cache, this function has no effect.
  259. *
  260. * It's illegal to call this function if @aProvider is not a placeholder; by
  261. * definition, non-placeholder ISurfaceProviders should have a surface
  262. * available already.
  263. *
  264. * @param aProvider The cache entry that now has a surface available.
  265. */
  266. static void SurfaceAvailable(NotNull<ISurfaceProvider*> aProvider);
  267. /**
  268. * Checks if a surface of a given size could possibly be stored in the cache.
  269. * If CanHold() returns false, Insert() will always fail to insert the
  270. * surface, but the inverse is not true: Insert() may take more information
  271. * into account than just image size when deciding whether to cache the
  272. * surface, so Insert() may still fail even if CanHold() returns true.
  273. *
  274. * Use CanHold() to avoid the need to create a temporary surface when we know
  275. * for sure the cache can't hold it.
  276. *
  277. * @param aSize The dimensions of a surface in pixels.
  278. * @param aBytesPerPixel How many bytes each pixel of the surface requires.
  279. * Defaults to 4, which is appropriate for RGBA or RGBX
  280. * images.
  281. *
  282. * @return false if the surface cache can't hold a surface of that size.
  283. */
  284. static bool CanHold(const IntSize& aSize, uint32_t aBytesPerPixel = 4);
  285. static bool CanHold(size_t aSize);
  286. /**
  287. * Locks an image. Any of the image's cache entries which are either inserted
  288. * or accessed while the image is locked will not expire.
  289. *
  290. * Locking an image does not automatically lock that image's existing cache
  291. * entries. A call to LockImage() guarantees that entries which are inserted
  292. * afterward will not expire before the next call to UnlockImage() or
  293. * UnlockSurfaces() for that image. Cache entries that are accessed via
  294. * Lookup() or LookupBestMatch() after a LockImage() call will also not expire
  295. * until the next UnlockImage() or UnlockSurfaces() call for that image. Any
  296. * other cache entries owned by the image may expire at any time.
  297. *
  298. * All of an image's cache entries are removed by RemoveImage(), whether the
  299. * image is locked or not.
  300. *
  301. * It's safe to call LockImage() on an image that's already locked; this has
  302. * no effect.
  303. *
  304. * You must always unlock any image you lock. You may do this explicitly by
  305. * calling UnlockImage(), or implicitly by calling RemoveImage(). Since you're
  306. * required to call RemoveImage() when you destroy an image, this doesn't
  307. * impose any additional requirements, but it's preferable to call
  308. * UnlockImage() earlier if it's possible.
  309. *
  310. * @param aImageKey The image to lock.
  311. */
  312. static void LockImage(const ImageKey aImageKey);
  313. /**
  314. * Unlocks an image, allowing any of its cache entries to expire at any time.
  315. *
  316. * It's OK to call UnlockImage() on an image that's already unlocked; this has
  317. * no effect.
  318. *
  319. * @param aImageKey The image to unlock.
  320. */
  321. static void UnlockImage(const ImageKey aImageKey);
  322. /**
  323. * Unlocks the existing cache entries of an image, allowing them to expire at
  324. * any time.
  325. *
  326. * This does not unlock the image itself, so accessing the cache entries via
  327. * Lookup() or LookupBestMatch() will lock them again, and prevent them from
  328. * expiring.
  329. *
  330. * This is intended to be used in situations where it's no longer clear that
  331. * all of the cache entries owned by an image are needed. Calling
  332. * UnlockSurfaces() and then taking some action that will cause Lookup() to
  333. * touch any cache entries that are still useful will permit the remaining
  334. * entries to expire from the cache.
  335. *
  336. * If the image is unlocked, this has no effect.
  337. *
  338. * @param aImageKey The image which should have its existing cache entries
  339. * unlocked.
  340. */
  341. static void UnlockEntries(const ImageKey aImageKey);
  342. /**
  343. * Removes all cache entries (including placeholders) associated with the
  344. * given image from the cache. If the image is locked, it is automatically
  345. * unlocked.
  346. *
  347. * This MUST be called, at a minimum, when an Image which could be storing
  348. * entries in the surface cache is destroyed. If another image were allocated
  349. * at the same address it could result in subtle, difficult-to-reproduce bugs.
  350. *
  351. * @param aImageKey The image which should be removed from the cache.
  352. */
  353. static void RemoveImage(const ImageKey aImageKey);
  354. /**
  355. * Evicts all evictable entries from the cache.
  356. *
  357. * All entries are evictable except for entries associated with locked images.
  358. * Non-evictable entries can only be removed by RemoveImage().
  359. */
  360. static void DiscardAll();
  361. /**
  362. * Collects an accounting of the surfaces contained in the SurfaceCache for
  363. * the given image, along with their size and various other metadata.
  364. *
  365. * This is intended for use with memory reporting.
  366. *
  367. * @param aImageKey The image to report memory usage for.
  368. * @param aCounters An array into which the report for each surface will
  369. * be written.
  370. * @param aMallocSizeOf A fallback malloc memory reporting function.
  371. */
  372. static void CollectSizeOfSurfaces(const ImageKey aImageKey,
  373. nsTArray<SurfaceMemoryCounter>& aCounters,
  374. MallocSizeOf aMallocSizeOf);
  375. /**
  376. * @return maximum capacity of the SurfaceCache in bytes. This is only exposed
  377. * for use by tests; normal code should use CanHold() instead.
  378. */
  379. static size_t MaximumCapacity();
  380. private:
  381. virtual ~SurfaceCache() = 0; // Forbid instantiation.
  382. };
  383. } // namespace image
  384. } // namespace mozilla
  385. #endif // mozilla_image_SurfaceCache_h