CanvasImageCache.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. #include "CanvasImageCache.h"
  6. #include "nsAutoPtr.h"
  7. #include "nsIImageLoadingContent.h"
  8. #include "nsExpirationTracker.h"
  9. #include "imgIContainer.h"
  10. #include "imgIRequest.h"
  11. #include "mozilla/dom/Element.h"
  12. #include "nsTHashtable.h"
  13. #include "mozilla/dom/HTMLCanvasElement.h"
  14. #include "nsContentUtils.h"
  15. #include "mozilla/Preferences.h"
  16. #include "mozilla/gfx/2D.h"
  17. #include "gfx2DGlue.h"
  18. namespace mozilla {
  19. using namespace dom;
  20. using namespace gfx;
  21. /**
  22. * Used for images specific to this one canvas. Required
  23. * due to CORS security.
  24. */
  25. struct ImageCacheKey
  26. {
  27. ImageCacheKey(imgIContainer* aImage,
  28. HTMLCanvasElement* aCanvas,
  29. bool aIsAccelerated)
  30. : mImage(aImage)
  31. , mCanvas(aCanvas)
  32. , mIsAccelerated(aIsAccelerated)
  33. {}
  34. nsCOMPtr<imgIContainer> mImage;
  35. HTMLCanvasElement* mCanvas;
  36. bool mIsAccelerated;
  37. };
  38. /**
  39. * Cache data needs to be separate from the entry
  40. * for nsExpirationTracker.
  41. */
  42. struct ImageCacheEntryData
  43. {
  44. ImageCacheEntryData(const ImageCacheEntryData& aOther)
  45. : mImage(aOther.mImage)
  46. , mCanvas(aOther.mCanvas)
  47. , mIsAccelerated(aOther.mIsAccelerated)
  48. , mSourceSurface(aOther.mSourceSurface)
  49. , mSize(aOther.mSize)
  50. {}
  51. explicit ImageCacheEntryData(const ImageCacheKey& aKey)
  52. : mImage(aKey.mImage)
  53. , mCanvas(aKey.mCanvas)
  54. , mIsAccelerated(aKey.mIsAccelerated)
  55. {}
  56. nsExpirationState* GetExpirationState() { return &mState; }
  57. size_t SizeInBytes() { return mSize.width * mSize.height * 4; }
  58. // Key
  59. nsCOMPtr<imgIContainer> mImage;
  60. HTMLCanvasElement* mCanvas;
  61. bool mIsAccelerated;
  62. // Value
  63. RefPtr<SourceSurface> mSourceSurface;
  64. IntSize mSize;
  65. nsExpirationState mState;
  66. };
  67. class ImageCacheEntry : public PLDHashEntryHdr
  68. {
  69. public:
  70. typedef ImageCacheKey KeyType;
  71. typedef const ImageCacheKey* KeyTypePointer;
  72. explicit ImageCacheEntry(const KeyType* aKey) :
  73. mData(new ImageCacheEntryData(*aKey)) {}
  74. ImageCacheEntry(const ImageCacheEntry& toCopy) :
  75. mData(new ImageCacheEntryData(*toCopy.mData)) {}
  76. ~ImageCacheEntry() {}
  77. bool KeyEquals(KeyTypePointer key) const
  78. {
  79. return mData->mImage == key->mImage &&
  80. mData->mCanvas == key->mCanvas &&
  81. mData->mIsAccelerated == key->mIsAccelerated;
  82. }
  83. static KeyTypePointer KeyToPointer(KeyType& key) { return &key; }
  84. static PLDHashNumber HashKey(KeyTypePointer key)
  85. {
  86. return HashGeneric(key->mImage.get(), key->mCanvas, key->mIsAccelerated);
  87. }
  88. enum { ALLOW_MEMMOVE = true };
  89. nsAutoPtr<ImageCacheEntryData> mData;
  90. };
  91. /**
  92. * Used for all images across all canvases.
  93. */
  94. struct AllCanvasImageCacheKey
  95. {
  96. AllCanvasImageCacheKey(imgIContainer* aImage,
  97. bool aIsAccelerated)
  98. : mImage(aImage)
  99. , mIsAccelerated(aIsAccelerated)
  100. {}
  101. nsCOMPtr<imgIContainer> mImage;
  102. bool mIsAccelerated;
  103. };
  104. class AllCanvasImageCacheEntry : public PLDHashEntryHdr {
  105. public:
  106. typedef AllCanvasImageCacheKey KeyType;
  107. typedef const AllCanvasImageCacheKey* KeyTypePointer;
  108. explicit AllCanvasImageCacheEntry(const KeyType* aKey)
  109. : mImage(aKey->mImage)
  110. , mIsAccelerated(aKey->mIsAccelerated)
  111. {}
  112. AllCanvasImageCacheEntry(const AllCanvasImageCacheEntry &toCopy)
  113. : mImage(toCopy.mImage)
  114. , mIsAccelerated(toCopy.mIsAccelerated)
  115. , mSourceSurface(toCopy.mSourceSurface)
  116. {}
  117. ~AllCanvasImageCacheEntry() {}
  118. bool KeyEquals(KeyTypePointer key) const
  119. {
  120. return mImage == key->mImage &&
  121. mIsAccelerated == key->mIsAccelerated;
  122. }
  123. static KeyTypePointer KeyToPointer(KeyType& key) { return &key; }
  124. static PLDHashNumber HashKey(KeyTypePointer key)
  125. {
  126. return HashGeneric(key->mImage.get(), key->mIsAccelerated);
  127. }
  128. enum { ALLOW_MEMMOVE = true };
  129. nsCOMPtr<imgIContainer> mImage;
  130. bool mIsAccelerated;
  131. RefPtr<SourceSurface> mSourceSurface;
  132. };
  133. static bool sPrefsInitialized = false;
  134. static int32_t sCanvasImageCacheLimit = 0;
  135. class ImageCacheObserver;
  136. class ImageCache final : public nsExpirationTracker<ImageCacheEntryData,4>
  137. {
  138. public:
  139. // We use 3 generations of 1 second each to get a 2-3 seconds timeout.
  140. enum { GENERATION_MS = 1000 };
  141. ImageCache();
  142. ~ImageCache();
  143. virtual void NotifyExpired(ImageCacheEntryData* aObject)
  144. {
  145. mTotal -= aObject->SizeInBytes();
  146. RemoveObject(aObject);
  147. // Remove from the all canvas cache entry first since nsExpirationTracker
  148. // will delete aObject.
  149. mAllCanvasCache.RemoveEntry(AllCanvasImageCacheKey(aObject->mImage, aObject->mIsAccelerated));
  150. // Deleting the entry will delete aObject since the entry owns aObject.
  151. mCache.RemoveEntry(ImageCacheKey(aObject->mImage, aObject->mCanvas, aObject->mIsAccelerated));
  152. }
  153. nsTHashtable<ImageCacheEntry> mCache;
  154. nsTHashtable<AllCanvasImageCacheEntry> mAllCanvasCache;
  155. size_t mTotal;
  156. RefPtr<ImageCacheObserver> mImageCacheObserver;
  157. };
  158. static ImageCache* gImageCache = nullptr;
  159. // Listen memory-pressure event for image cache purge.
  160. class ImageCacheObserver final : public nsIObserver
  161. {
  162. public:
  163. NS_DECL_ISUPPORTS
  164. explicit ImageCacheObserver(ImageCache* aImageCache)
  165. : mImageCache(aImageCache)
  166. {
  167. RegisterMemoryPressureEvent();
  168. }
  169. void Destroy()
  170. {
  171. UnregisterMemoryPressureEvent();
  172. mImageCache = nullptr;
  173. }
  174. NS_IMETHOD Observe(nsISupports* aSubject,
  175. const char* aTopic,
  176. const char16_t* aSomeData) override
  177. {
  178. if (!mImageCache || strcmp(aTopic, "memory-pressure")) {
  179. return NS_OK;
  180. }
  181. mImageCache->AgeAllGenerations();
  182. return NS_OK;
  183. }
  184. private:
  185. virtual ~ImageCacheObserver()
  186. {
  187. }
  188. void RegisterMemoryPressureEvent()
  189. {
  190. nsCOMPtr<nsIObserverService> observerService =
  191. mozilla::services::GetObserverService();
  192. MOZ_ASSERT(observerService);
  193. if (observerService) {
  194. observerService->AddObserver(this, "memory-pressure", false);
  195. }
  196. }
  197. void UnregisterMemoryPressureEvent()
  198. {
  199. nsCOMPtr<nsIObserverService> observerService =
  200. mozilla::services::GetObserverService();
  201. // Do not assert on observerService here. This might be triggered by
  202. // the cycle collector at a late enough time, that XPCOM services are
  203. // no longer available. See bug 1029504.
  204. if (observerService) {
  205. observerService->RemoveObserver(this, "memory-pressure");
  206. }
  207. }
  208. ImageCache* mImageCache;
  209. };
  210. NS_IMPL_ISUPPORTS(ImageCacheObserver, nsIObserver)
  211. class CanvasImageCacheShutdownObserver final : public nsIObserver
  212. {
  213. ~CanvasImageCacheShutdownObserver() {}
  214. public:
  215. NS_DECL_ISUPPORTS
  216. NS_DECL_NSIOBSERVER
  217. };
  218. ImageCache::ImageCache()
  219. : nsExpirationTracker<ImageCacheEntryData,4>(GENERATION_MS, "ImageCache")
  220. , mTotal(0)
  221. {
  222. if (!sPrefsInitialized) {
  223. sPrefsInitialized = true;
  224. Preferences::AddIntVarCache(&sCanvasImageCacheLimit, "canvas.image.cache.limit", 0);
  225. }
  226. mImageCacheObserver = new ImageCacheObserver(this);
  227. MOZ_RELEASE_ASSERT(mImageCacheObserver, "GFX: Can't alloc ImageCacheObserver");
  228. }
  229. ImageCache::~ImageCache() {
  230. AgeAllGenerations();
  231. mImageCacheObserver->Destroy();
  232. }
  233. static already_AddRefed<imgIContainer>
  234. GetImageContainer(dom::Element* aImage)
  235. {
  236. nsCOMPtr<imgIRequest> request;
  237. nsCOMPtr<nsIImageLoadingContent> ilc = do_QueryInterface(aImage);
  238. if (!ilc) {
  239. return nullptr;
  240. }
  241. ilc->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
  242. getter_AddRefs(request));
  243. if (!request) {
  244. return nullptr;
  245. }
  246. nsCOMPtr<imgIContainer> imgContainer;
  247. request->GetImage(getter_AddRefs(imgContainer));
  248. if (!imgContainer) {
  249. return nullptr;
  250. }
  251. return imgContainer.forget();
  252. }
  253. void
  254. CanvasImageCache::NotifyDrawImage(Element* aImage,
  255. HTMLCanvasElement* aCanvas,
  256. SourceSurface* aSource,
  257. const IntSize& aSize,
  258. bool aIsAccelerated)
  259. {
  260. if (!gImageCache) {
  261. gImageCache = new ImageCache();
  262. nsContentUtils::RegisterShutdownObserver(new CanvasImageCacheShutdownObserver());
  263. }
  264. nsCOMPtr<imgIContainer> imgContainer = GetImageContainer(aImage);
  265. if (!imgContainer) {
  266. return;
  267. }
  268. AllCanvasImageCacheKey allCanvasCacheKey(imgContainer, aIsAccelerated);
  269. ImageCacheKey canvasCacheKey(imgContainer, aCanvas, aIsAccelerated);
  270. ImageCacheEntry* entry = gImageCache->mCache.PutEntry(canvasCacheKey);
  271. if (entry) {
  272. if (entry->mData->mSourceSurface) {
  273. // We are overwriting an existing entry.
  274. gImageCache->mTotal -= entry->mData->SizeInBytes();
  275. gImageCache->RemoveObject(entry->mData);
  276. gImageCache->mAllCanvasCache.RemoveEntry(allCanvasCacheKey);
  277. }
  278. gImageCache->AddObject(entry->mData);
  279. entry->mData->mSourceSurface = aSource;
  280. entry->mData->mSize = aSize;
  281. gImageCache->mTotal += entry->mData->SizeInBytes();
  282. AllCanvasImageCacheEntry* allEntry = gImageCache->mAllCanvasCache.PutEntry(allCanvasCacheKey);
  283. if (allEntry) {
  284. allEntry->mSourceSurface = aSource;
  285. }
  286. }
  287. if (!sCanvasImageCacheLimit)
  288. return;
  289. // Expire the image cache early if its larger than we want it to be.
  290. while (gImageCache->mTotal > size_t(sCanvasImageCacheLimit))
  291. gImageCache->AgeOneGeneration();
  292. }
  293. SourceSurface*
  294. CanvasImageCache::LookupAllCanvas(Element* aImage,
  295. bool aIsAccelerated)
  296. {
  297. if (!gImageCache) {
  298. return nullptr;
  299. }
  300. nsCOMPtr<imgIContainer> imgContainer = GetImageContainer(aImage);
  301. if (!imgContainer) {
  302. return nullptr;
  303. }
  304. AllCanvasImageCacheEntry* entry =
  305. gImageCache->mAllCanvasCache.GetEntry(AllCanvasImageCacheKey(imgContainer, aIsAccelerated));
  306. if (!entry) {
  307. return nullptr;
  308. }
  309. return entry->mSourceSurface;
  310. }
  311. SourceSurface*
  312. CanvasImageCache::LookupCanvas(Element* aImage,
  313. HTMLCanvasElement* aCanvas,
  314. IntSize* aSizeOut,
  315. bool aIsAccelerated)
  316. {
  317. if (!gImageCache) {
  318. return nullptr;
  319. }
  320. nsCOMPtr<imgIContainer> imgContainer = GetImageContainer(aImage);
  321. if (!imgContainer) {
  322. return nullptr;
  323. }
  324. ImageCacheEntry* entry =
  325. gImageCache->mCache.GetEntry(ImageCacheKey(imgContainer, aCanvas, aIsAccelerated));
  326. if (!entry) {
  327. return nullptr;
  328. }
  329. MOZ_ASSERT(aSizeOut);
  330. gImageCache->MarkUsed(entry->mData);
  331. *aSizeOut = entry->mData->mSize;
  332. return entry->mData->mSourceSurface;
  333. }
  334. NS_IMPL_ISUPPORTS(CanvasImageCacheShutdownObserver, nsIObserver)
  335. NS_IMETHODIMP
  336. CanvasImageCacheShutdownObserver::Observe(nsISupports *aSubject,
  337. const char *aTopic,
  338. const char16_t *aData)
  339. {
  340. if (strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
  341. delete gImageCache;
  342. gImageCache = nullptr;
  343. nsContentUtils::UnregisterShutdownObserver(this);
  344. }
  345. return NS_OK;
  346. }
  347. } // namespace mozilla