Backed out changeset 177eae915693 (bug 1206581) for bustage
[gecko.git] / image / SurfaceCache.h
blobd6fafa48b09128432cd6f1cf8bb0d562deae532b
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 and decoded image
8 * data in imagelib.
9 */
11 #ifndef mozilla_image_SurfaceCache_h
12 #define mozilla_image_SurfaceCache_h
14 #include "mozilla/Maybe.h" // for Maybe
15 #include "mozilla/MemoryReporting.h" // for MallocSizeOf
16 #include "mozilla/HashFunctions.h" // for HashGeneric and AddToHash
17 #include "gfx2DGlue.h"
18 #include "gfxPoint.h" // for gfxSize
19 #include "nsCOMPtr.h" // for already_AddRefed
20 #include "mozilla/gfx/Point.h" // for mozilla::gfx::IntSize
21 #include "mozilla/gfx/2D.h" // for SourceSurface
22 #include "SurfaceFlags.h"
23 #include "SVGImageContext.h" // for SVGImageContext
25 namespace mozilla {
26 namespace image {
28 class Image;
29 class imgFrame;
30 class LookupResult;
31 struct SurfaceMemoryCounter;
34 * ImageKey contains the information we need to look up all cached surfaces for
35 * a particular image.
37 typedef Image* ImageKey;
40 * SurfaceKey contains the information we need to look up a specific cached
41 * surface. Together with an ImageKey, this uniquely identifies the surface.
43 * Callers should construct a SurfaceKey using the appropriate helper function
44 * for their image type - either RasterSurfaceKey or VectorSurfaceKey.
46 class SurfaceKey
48 typedef gfx::IntSize IntSize;
50 public:
51 bool operator==(const SurfaceKey& aOther) const
53 return aOther.mSize == mSize &&
54 aOther.mSVGContext == mSVGContext &&
55 aOther.mAnimationTime == mAnimationTime &&
56 aOther.mFlags == mFlags;
59 uint32_t Hash() const
61 uint32_t hash = HashGeneric(mSize.width, mSize.height);
62 hash = AddToHash(hash, mSVGContext.map(HashSIC).valueOr(0));
63 hash = AddToHash(hash, mAnimationTime, uint32_t(mFlags));
64 return hash;
67 IntSize Size() const { return mSize; }
68 Maybe<SVGImageContext> SVGContext() const { return mSVGContext; }
69 float AnimationTime() const { return mAnimationTime; }
70 SurfaceFlags Flags() const { return mFlags; }
72 private:
73 SurfaceKey(const IntSize& aSize,
74 const Maybe<SVGImageContext>& aSVGContext,
75 const float aAnimationTime,
76 const SurfaceFlags aFlags)
77 : mSize(aSize)
78 , mSVGContext(aSVGContext)
79 , mAnimationTime(aAnimationTime)
80 , mFlags(aFlags)
81 { }
83 static uint32_t HashSIC(const SVGImageContext& aSIC) {
84 return aSIC.Hash();
87 friend SurfaceKey RasterSurfaceKey(const IntSize&,
88 SurfaceFlags,
89 uint32_t);
90 friend SurfaceKey VectorSurfaceKey(const IntSize&,
91 const Maybe<SVGImageContext>&,
92 float);
94 IntSize mSize;
95 Maybe<SVGImageContext> mSVGContext;
96 float mAnimationTime;
97 SurfaceFlags mFlags;
100 inline SurfaceKey
101 RasterSurfaceKey(const gfx::IntSize& aSize,
102 SurfaceFlags aFlags,
103 uint32_t aFrameNum)
105 return SurfaceKey(aSize, Nothing(), float(aFrameNum), aFlags);
108 inline SurfaceKey
109 VectorSurfaceKey(const gfx::IntSize& aSize,
110 const Maybe<SVGImageContext>& aSVGContext,
111 float aAnimationTime)
113 // We don't care about aFlags for VectorImage because none of the flags we
114 // have right now influence VectorImage's rendering. If we add a new flag that
115 // *does* affect how a VectorImage renders, we'll have to change this.
116 return SurfaceKey(aSize, aSVGContext, aAnimationTime, DefaultSurfaceFlags());
119 enum class InsertOutcome : uint8_t {
120 SUCCESS, // Success (but see Insert documentation).
121 FAILURE, // Couldn't insert (e.g., for capacity reasons).
122 FAILURE_ALREADY_PRESENT // A surface with the same key is already present.
126 * SurfaceCache is an imagelib-global service that allows caching of temporary
127 * surfaces. Surfaces normally expire from the cache automatically if they go
128 * too long without being accessed.
130 * SurfaceCache does not hold surfaces directly; instead, it holds imgFrame
131 * objects, which hold surfaces but also layer on additional features specific
132 * to imagelib's needs like animation, padding support, and transparent support
133 * for volatile buffers.
135 * Sometime it's useful to temporarily prevent surfaces from expiring from the
136 * cache. This is most often because losing the data could harm the user
137 * experience (for example, we often don't want to allow surfaces that are
138 * currently visible to expire) or because it's not possible to rematerialize
139 * the surface. SurfaceCache supports this through the use of image locking; see
140 * the comments for Insert() and LockImage() for more details.
142 * Any image which stores surfaces in the SurfaceCache *must* ensure that it
143 * calls RemoveImage() before it is destroyed. See the comments for
144 * RemoveImage() for more details.
146 struct SurfaceCache
148 typedef gfx::IntSize IntSize;
151 * Initialize static data. Called during imagelib module initialization.
153 static void Initialize();
156 * Release static data. Called during imagelib module shutdown.
158 static void Shutdown();
161 * Look up the imgFrame containing a surface in the cache and returns a
162 * drawable reference to that imgFrame.
164 * If the image associated with the surface is locked, then the surface will
165 * be locked before it is returned.
167 * If the imgFrame was found in the cache, but had stored its surface in a
168 * volatile buffer which was discarded by the OS, then it is automatically
169 * removed from the cache and an empty LookupResult is returned. Note that
170 * this will never happen to surfaces associated with a locked image; the
171 * cache keeps a strong reference to such surfaces internally.
173 * @param aImageKey Key data identifying which image the surface belongs
174 * to.
176 * @param aSurfaceKey Key data which uniquely identifies the requested
177 * surface.
179 * @return a LookupResult, which will either contain a
180 * DrawableFrameRef to the requested surface, or an
181 * empty DrawableFrameRef if the surface was not found.
183 static LookupResult Lookup(const ImageKey aImageKey,
184 const SurfaceKey& aSurfaceKey);
187 * Looks up the best matching surface in the cache and returns a drawable
188 * reference to the imgFrame containing it.
190 * Returned surfaces may vary from the requested surface only in terms of
191 * size.
193 * @param aImageKey Key data identifying which image the surface belongs
194 * to.
196 * @param aSurfaceKey Key data which identifies the ideal surface to return.
198 * @return a LookupResult, which will either contain a
199 * DrawableFrameRef to a surface similar to the
200 * requested surface, or an empty DrawableFrameRef if
201 * the surface was not found. Callers can use
202 * LookupResult::IsExactMatch() to check whether the
203 * returned surface exactly matches @aSurfaceKey.
205 static LookupResult LookupBestMatch(const ImageKey aImageKey,
206 const SurfaceKey& aSurfaceKey);
209 * Insert a surface into the cache. If a surface with the same ImageKey and
210 * SurfaceKey is already in the cache, Insert returns FAILURE_ALREADY_PRESENT.
211 * If a matching placeholder is already present, the placeholder is removed.
213 * Surfaces will never expire as long as they remain locked, but if they
214 * become unlocked, they can expire either because the SurfaceCache runs out
215 * of capacity or because they've gone too long without being used. When it
216 * is first inserted, a surface is locked if its associated image is locked.
217 * When that image is later unlocked, the surface becomes unlocked too. To
218 * become locked again at that point, two things must happen: the image must
219 * become locked again (via LockImage()), and the surface must be touched
220 * again (via one of the Lookup() functions).
222 * All of this means that a very particular procedure has to be followed for
223 * surfaces which cannot be rematerialized. First, they must be inserted
224 * *after* the image is locked with LockImage(); if you use the other order,
225 * the surfaces might expire before LockImage() gets called or before the
226 * surface is touched again by Lookup(). Second, the image they are associated
227 * with must never be unlocked.
229 * If a surface cannot be rematerialized, it may be important to know whether
230 * it was inserted into the cache successfully. Insert() returns FAILURE if it
231 * failed to insert the surface, which could happen because of capacity
232 * reasons, or because it was already freed by the OS. If the surface isn't
233 * associated with a locked image, checking for SUCCESS or FAILURE is useless:
234 * the surface might expire immediately after being inserted, even though
235 * Insert() returned SUCCESS. Thus, many callers do not need to check the
236 * result of Insert() at all.
238 * @param aTarget The new surface (wrapped in an imgFrame) to insert into
239 * the cache.
240 * @param aImageKey Key data identifying which image the surface belongs
241 * to.
242 * @param aSurfaceKey Key data which uniquely identifies the requested
243 * surface.
244 * @return SUCCESS if the surface was inserted successfully. (But see above
245 * for more information about when you should check this.)
246 * FAILURE if the surface could not be inserted, e.g. for capacity
247 * reasons. (But see above for more information about when you
248 * should check this.)
249 * FAILURE_ALREADY_PRESENT if a surface with the same ImageKey and
250 * SurfaceKey already exists in the cache.
252 static InsertOutcome Insert(imgFrame* aSurface,
253 const ImageKey aImageKey,
254 const SurfaceKey& aSurfaceKey);
257 * Insert a placeholder for a surface into the cache. If a surface with the
258 * same ImageKey and SurfaceKey is already in the cache, InsertPlaceholder()
259 * returns FAILURE_ALREADY_PRESENT.
261 * Placeholders exist to allow lazy allocation of surfaces. The Lookup*()
262 * methods will report whether a placeholder for an exactly matching surface
263 * existed by returning a MatchType of PENDING or SUBSTITUTE_BECAUSE_PENDING,
264 * but they will never return a placeholder directly. (They couldn't, since
265 * placeholders don't have an associated surface.)
267 * Once inserted, placeholders can be removed using RemoveSurface() or
268 * RemoveImage(), just like a surface. They're automatically removed when a
269 * real surface that matches the placeholder is inserted with Insert().
271 * @param aImageKey Key data identifying which image the placeholder
272 * belongs to.
273 * @param aSurfaceKey Key data which uniquely identifies the surface the
274 * placeholder stands in for.
275 * @return SUCCESS if the placeholder was inserted successfully.
276 * FAILURE if the placeholder could not be inserted for some reason.
277 * FAILURE_ALREADY_PRESENT if a surface with the same ImageKey and
278 * SurfaceKey already exists in the cache.
280 static InsertOutcome InsertPlaceholder(const ImageKey aImageKey,
281 const SurfaceKey& aSurfaceKey);
284 * Checks if a surface of a given size could possibly be stored in the cache.
285 * If CanHold() returns false, Insert() will always fail to insert the
286 * surface, but the inverse is not true: Insert() may take more information
287 * into account than just image size when deciding whether to cache the
288 * surface, so Insert() may still fail even if CanHold() returns true.
290 * Use CanHold() to avoid the need to create a temporary surface when we know
291 * for sure the cache can't hold it.
293 * @param aSize The dimensions of a surface in pixels.
294 * @param aBytesPerPixel How many bytes each pixel of the surface requires.
295 * Defaults to 4, which is appropriate for RGBA or RGBX
296 * images.
298 * @return false if the surface cache can't hold a surface of that size.
300 static bool CanHold(const IntSize& aSize, uint32_t aBytesPerPixel = 4);
301 static bool CanHold(size_t aSize);
304 * Locks an image. Any of the image's surfaces which are either inserted or
305 * accessed while the image is locked will not expire.
307 * Locking an image does not automatically lock that image's existing
308 * surfaces. A call to LockImage() guarantees that surfaces which are inserted
309 * afterward will not expire before the next call to UnlockImage() or
310 * UnlockSurfaces() for that image. Surfaces that are accessed via Lookup() or
311 * LookupBestMatch() after a LockImage() call will also not expire until the
312 * next UnlockImage() or UnlockSurfaces() call for that image. Any other
313 * surfaces owned by the image may expire at any time.
315 * Regardless of locking, any of an image's surfaces may be removed using
316 * RemoveSurface(), and all of an image's surfaces are removed by
317 * RemoveImage(), whether the image is locked or not.
319 * It's safe to call LockImage() on an image that's already locked; this has
320 * no effect.
322 * You must always unlock any image you lock. You may do this explicitly by
323 * calling UnlockImage(), or implicitly by calling RemoveImage(). Since you're
324 * required to call RemoveImage() when you destroy an image, this doesn't
325 * impose any additional requirements, but it's preferable to call
326 * UnlockImage() earlier if it's possible.
328 * @param aImageKey The image to lock.
330 static void LockImage(const ImageKey aImageKey);
333 * Unlocks an image, allowing any of its surfaces to expire at any time.
335 * It's OK to call UnlockImage() on an image that's already unlocked; this has
336 * no effect.
338 * @param aImageKey The image to unlock.
340 static void UnlockImage(const ImageKey aImageKey);
343 * Unlocks the existing surfaces of an image, allowing them to expire at any
344 * time.
346 * This does not unlock the image itself, so accessing the surfaces via
347 * Lookup() or LookupBestMatch() will lock them again, and prevent them from
348 * expiring.
350 * This is intended to be used in situations where it's no longer clear that
351 * all of the surfaces owned by an image are needed. Calling UnlockSurfaces()
352 * and then taking some action that will cause Lookup() to touch any surfaces
353 * that are still useful will permit the remaining surfaces to expire from the
354 * cache.
356 * If the image is unlocked, this has no effect.
358 * @param aImageKey The image which should have its existing surfaces
359 * unlocked.
361 static void UnlockSurfaces(const ImageKey aImageKey);
364 * Removes a surface or placeholder from the cache, if it's present. If it's
365 * not present, RemoveSurface() has no effect.
367 * Use this function to remove individual surfaces that have become invalid.
368 * Prefer RemoveImage() or DiscardAll() when they're applicable, as they have
369 * much better performance than calling this function repeatedly.
371 * @param aImageKey Key data identifying which image the surface belongs
373 * @param aSurfaceKey Key data which uniquely identifies the requested
374 surface.
376 static void RemoveSurface(const ImageKey aImageKey,
377 const SurfaceKey& aSurfaceKey);
380 * Removes all cached surfaces and placeholders associated with the given
381 * image from the cache. If the image is locked, it is automatically
382 * unlocked.
384 * This MUST be called, at a minimum, when an Image which could be storing
385 * surfaces in the surface cache is destroyed. If another image were allocated
386 * at the same address it could result in subtle, difficult-to-reproduce bugs.
388 * @param aImageKey The image which should be removed from the cache.
390 static void RemoveImage(const ImageKey aImageKey);
393 * Evicts all evictable surfaces from the cache.
395 * All surfaces are evictable except for surfaces associated with locked
396 * images. Non-evictable surfaces can only be removed by RemoveSurface() or
397 * RemoveImage().
399 static void DiscardAll();
402 * Collects an accounting of the surfaces contained in the SurfaceCache for
403 * the given image, along with their size and various other metadata.
405 * This is intended for use with memory reporting.
407 * @param aImageKey The image to report memory usage for.
408 * @param aCounters An array into which the report for each surface will
409 * be written.
410 * @param aMallocSizeOf A fallback malloc memory reporting function.
412 static void CollectSizeOfSurfaces(const ImageKey aImageKey,
413 nsTArray<SurfaceMemoryCounter>& aCounters,
414 MallocSizeOf aMallocSizeOf);
416 private:
417 virtual ~SurfaceCache() = 0; // Forbid instantiation.
420 } // namespace image
421 } // namespace mozilla
423 #endif // mozilla_image_SurfaceCache_h