2 * Copyright 2013 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkChecksum.h"
9 #include "SkMessageBus.h"
11 #include "SkPixelRef.h"
12 #include "SkResourceCache.h"
16 DECLARE_SKMESSAGEBUS_MESSAGE(SkResourceCache::PurgeSharedIDMessage)
18 // This can be defined by the caller's build system
19 //#define SK_USE_DISCARDABLE_SCALEDIMAGECACHE
21 #ifndef SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT
22 # define SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT 1024
25 #ifndef SK_DEFAULT_IMAGE_CACHE_LIMIT
26 #define SK_DEFAULT_IMAGE_CACHE_LIMIT (2 * 1024 * 1024)
29 void SkResourceCache::Key::init(void* nameSpace, uint64_t sharedID, size_t length) {
30 SkASSERT(SkAlign4(length) == length);
32 // fCount32 and fHash are not hashed
33 static const int kUnhashedLocal32s = 2; // fCache32 + fHash
34 static const int kSharedIDLocal32s = 2; // fSharedID_lo + fSharedID_hi
35 static const int kHashedLocal32s = kSharedIDLocal32s + (sizeof(fNamespace) >> 2);
36 static const int kLocal32s = kUnhashedLocal32s + kHashedLocal32s;
38 SK_COMPILE_ASSERT(sizeof(Key) == (kLocal32s << 2), unaccounted_key_locals);
39 SK_COMPILE_ASSERT(sizeof(Key) == offsetof(Key, fNamespace) + sizeof(fNamespace),
40 namespace_field_must_be_last);
42 fCount32 = SkToS32(kLocal32s + (length >> 2));
43 fSharedID_lo = (uint32_t)sharedID;
44 fSharedID_hi = (uint32_t)(sharedID >> 32);
45 fNamespace = nameSpace;
46 // skip unhashed fields when computing the murmur
47 fHash = SkChecksum::Murmur3(this->as32() + kUnhashedLocal32s,
48 (fCount32 - kUnhashedLocal32s) << 2);
51 #include "SkTDynamicHash.h"
53 class SkResourceCache::Hash :
54 public SkTDynamicHash<SkResourceCache::Rec, SkResourceCache::Key> {};
57 ///////////////////////////////////////////////////////////////////////////////
59 void SkResourceCache::init() {
65 fSingleAllocationByteLimit = 0;
68 // One of these should be explicit set by the caller after we return.
70 fDiscardableFactory = NULL;
73 #include "SkDiscardableMemory.h"
75 class SkOneShotDiscardablePixelRef : public SkPixelRef {
77 SK_DECLARE_INST_COUNT(SkOneShotDiscardablePixelRef)
78 // Ownership of the discardablememory is transfered to the pixelref
79 SkOneShotDiscardablePixelRef(const SkImageInfo&, SkDiscardableMemory*, size_t rowBytes);
80 ~SkOneShotDiscardablePixelRef();
83 bool onNewLockPixels(LockRec*) SK_OVERRIDE;
84 void onUnlockPixels() SK_OVERRIDE;
85 size_t getAllocatedSizeInBytes() const SK_OVERRIDE;
88 SkDiscardableMemory* fDM;
92 typedef SkPixelRef INHERITED;
95 SkOneShotDiscardablePixelRef::SkOneShotDiscardablePixelRef(const SkImageInfo& info,
96 SkDiscardableMemory* dm,
102 SkASSERT(dm->data());
106 SkOneShotDiscardablePixelRef::~SkOneShotDiscardablePixelRef() {
110 bool SkOneShotDiscardablePixelRef::onNewLockPixels(LockRec* rec) {
112 // we're already locked
113 SkASSERT(fDM->data());
118 // A previous call to onUnlock may have deleted our DM, so check for that
124 // since it failed, we delete it now, to free-up the resource
131 rec->fPixels = fDM->data();
132 rec->fColorTable = NULL;
133 rec->fRowBytes = fRB;
137 void SkOneShotDiscardablePixelRef::onUnlockPixels() {
138 SkASSERT(!fFirstTime);
142 size_t SkOneShotDiscardablePixelRef::getAllocatedSizeInBytes() const {
143 return this->info().getSafeSize(fRB);
146 class SkResourceCacheDiscardableAllocator : public SkBitmap::Allocator {
148 SkResourceCacheDiscardableAllocator(SkResourceCache::DiscardableFactory factory) {
153 bool allocPixelRef(SkBitmap*, SkColorTable*) SK_OVERRIDE;
156 SkResourceCache::DiscardableFactory fFactory;
159 bool SkResourceCacheDiscardableAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
160 size_t size = bitmap->getSize();
161 uint64_t size64 = bitmap->computeSize64();
162 if (0 == size || size64 > (uint64_t)size) {
166 SkDiscardableMemory* dm = fFactory(size);
171 // can we relax this?
172 if (kN32_SkColorType != bitmap->colorType()) {
176 SkImageInfo info = bitmap->info();
177 bitmap->setPixelRef(SkNEW_ARGS(SkOneShotDiscardablePixelRef,
178 (info, dm, bitmap->rowBytes())))->unref();
179 bitmap->lockPixels();
180 return bitmap->readyToDraw();
183 SkResourceCache::SkResourceCache(DiscardableFactory factory) {
185 fDiscardableFactory = factory;
187 fAllocator = SkNEW_ARGS(SkResourceCacheDiscardableAllocator, (factory));
190 SkResourceCache::SkResourceCache(size_t byteLimit) {
192 fTotalByteLimit = byteLimit;
195 SkResourceCache::~SkResourceCache() {
196 SkSafeUnref(fAllocator);
200 Rec* next = rec->fNext;
207 ////////////////////////////////////////////////////////////////////////////////
209 bool SkResourceCache::find(const Key& key, FindVisitor visitor, void* context) {
210 this->checkMessages();
212 Rec* rec = fHash->find(key);
214 if (visitor(*rec, context)) {
215 this->moveToHead(rec); // for our LRU
218 this->remove(rec); // stale
225 static void make_size_str(size_t size, SkString* str) {
226 const char suffix[] = { 'b', 'k', 'm', 'g', 't', 0 };
228 while (suffix[i] && (size > 1024)) {
232 str->printf("%zu%c", size, suffix[i]);
235 static bool gDumpCacheTransactions;
237 void SkResourceCache::add(Rec* rec) {
238 this->checkMessages();
241 // See if we already have this key (racy inserts, etc.)
242 Rec* existing = fHash->find(rec->getKey());
248 this->addToHead(rec);
251 if (gDumpCacheTransactions) {
252 SkString bytesStr, totalStr;
253 make_size_str(rec->bytesUsed(), &bytesStr);
254 make_size_str(fTotalBytesUsed, &totalStr);
255 SkDebugf("RC: add %5s %12p key %08x -- total %5s, count %d\n",
256 bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
259 // since the new rec may push us over-budget, we perform a purge check now
260 this->purgeAsNeeded();
263 void SkResourceCache::remove(Rec* rec) {
264 size_t used = rec->bytesUsed();
265 SkASSERT(used <= fTotalBytesUsed);
268 fHash->remove(rec->getKey());
270 fTotalBytesUsed -= used;
273 if (gDumpCacheTransactions) {
274 SkString bytesStr, totalStr;
275 make_size_str(used, &bytesStr);
276 make_size_str(fTotalBytesUsed, &totalStr);
277 SkDebugf("RC: remove %5s %12p key %08x -- total %5s, count %d\n",
278 bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
284 void SkResourceCache::purgeAsNeeded(bool forcePurge) {
288 if (fDiscardableFactory) {
289 countLimit = SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT;
290 byteLimit = SK_MaxU32; // no limit based on bytes
292 countLimit = SK_MaxS32; // no limit based on count
293 byteLimit = fTotalByteLimit;
298 if (!forcePurge && fTotalBytesUsed < byteLimit && fCount < countLimit) {
302 Rec* prev = rec->fPrev;
308 //#define SK_TRACK_PURGE_SHAREDID_HITRATE
310 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
311 static int gPurgeCallCounter;
312 static int gPurgeHitCounter;
315 void SkResourceCache::purgeSharedID(uint64_t sharedID) {
320 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
321 gPurgeCallCounter += 1;
324 // go backwards, just like purgeAsNeeded, just to make the code similar.
325 // could iterate either direction and still be correct.
328 Rec* prev = rec->fPrev;
329 if (rec->getKey().getSharedID() == sharedID) {
330 // SkDebugf("purgeSharedID id=%llx rec=%p\n", sharedID, rec);
332 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
339 #ifdef SK_TRACK_PURGE_SHAREDID_HITRATE
341 gPurgeHitCounter += 1;
344 SkDebugf("PurgeShared calls=%d hits=%d rate=%g\n", gPurgeCallCounter, gPurgeHitCounter,
345 gPurgeHitCounter * 100.0 / gPurgeCallCounter);
349 size_t SkResourceCache::setTotalByteLimit(size_t newLimit) {
350 size_t prevLimit = fTotalByteLimit;
351 fTotalByteLimit = newLimit;
352 if (newLimit < prevLimit) {
353 this->purgeAsNeeded();
358 SkCachedData* SkResourceCache::newCachedData(size_t bytes) {
359 this->checkMessages();
361 if (fDiscardableFactory) {
362 SkDiscardableMemory* dm = fDiscardableFactory(bytes);
363 return dm ? SkNEW_ARGS(SkCachedData, (bytes, dm)) : NULL;
365 return SkNEW_ARGS(SkCachedData, (sk_malloc_throw(bytes), bytes));
369 ///////////////////////////////////////////////////////////////////////////////
371 void SkResourceCache::detach(Rec* rec) {
372 Rec* prev = rec->fPrev;
373 Rec* next = rec->fNext;
376 SkASSERT(fHead == rec);
388 rec->fNext = rec->fPrev = NULL;
391 void SkResourceCache::moveToHead(Rec* rec) {
410 void SkResourceCache::addToHead(Rec* rec) {
422 fTotalBytesUsed += rec->bytesUsed();
428 ///////////////////////////////////////////////////////////////////////////////
431 void SkResourceCache::validate() const {
433 SkASSERT(NULL == fTail);
434 SkASSERT(0 == fTotalBytesUsed);
438 if (fHead == fTail) {
439 SkASSERT(NULL == fHead->fPrev);
440 SkASSERT(NULL == fHead->fNext);
441 SkASSERT(fHead->bytesUsed() == fTotalBytesUsed);
445 SkASSERT(NULL == fHead->fPrev);
446 SkASSERT(fHead->fNext);
447 SkASSERT(NULL == fTail->fNext);
448 SkASSERT(fTail->fPrev);
452 const Rec* rec = fHead;
455 used += rec->bytesUsed();
456 SkASSERT(used <= fTotalBytesUsed);
459 SkASSERT(fCount == count);
465 SkASSERT(used >= rec->bytesUsed());
466 used -= rec->bytesUsed();
470 SkASSERT(0 == count);
475 void SkResourceCache::dump() const {
478 SkDebugf("SkResourceCache: count=%d bytes=%d %s\n",
479 fCount, fTotalBytesUsed, fDiscardableFactory ? "discardable" : "malloc");
482 size_t SkResourceCache::setSingleAllocationByteLimit(size_t newLimit) {
483 size_t oldLimit = fSingleAllocationByteLimit;
484 fSingleAllocationByteLimit = newLimit;
488 size_t SkResourceCache::getSingleAllocationByteLimit() const {
489 return fSingleAllocationByteLimit;
492 size_t SkResourceCache::getEffectiveSingleAllocationByteLimit() const {
493 // fSingleAllocationByteLimit == 0 means the caller is asking for our default
494 size_t limit = fSingleAllocationByteLimit;
496 // if we're not discardable (i.e. we are fixed-budget) then cap the single-limit
498 if (NULL == fDiscardableFactory) {
500 limit = fTotalByteLimit;
502 limit = SkTMin(limit, fTotalByteLimit);
508 void SkResourceCache::checkMessages() {
509 SkTArray<PurgeSharedIDMessage> msgs;
510 fPurgeSharedIDInbox.poll(&msgs);
511 for (int i = 0; i < msgs.count(); ++i) {
512 this->purgeSharedID(msgs[i].fSharedID);
516 ///////////////////////////////////////////////////////////////////////////////
518 #include "SkThread.h"
520 SK_DECLARE_STATIC_MUTEX(gMutex);
521 static SkResourceCache* gResourceCache = NULL;
522 static void cleanup_gResourceCache() {
523 // We'll clean this up in our own tests, but disable for clients.
524 // Chrome seems to have funky multi-process things going on in unit tests that
525 // makes this unsafe to delete when the main process atexit()s.
526 // SkLazyPtr does the same sort of thing.
528 SkDELETE(gResourceCache);
532 /** Must hold gMutex when calling. */
533 static SkResourceCache* get_cache() {
534 // gMutex is always held when this is called, so we don't need to be fancy in here.
536 if (NULL == gResourceCache) {
537 #ifdef SK_USE_DISCARDABLE_SCALEDIMAGECACHE
538 gResourceCache = SkNEW_ARGS(SkResourceCache, (SkDiscardableMemory::Create));
540 gResourceCache = SkNEW_ARGS(SkResourceCache, (SK_DEFAULT_IMAGE_CACHE_LIMIT));
542 atexit(cleanup_gResourceCache);
544 return gResourceCache;
547 size_t SkResourceCache::GetTotalBytesUsed() {
548 SkAutoMutexAcquire am(gMutex);
549 return get_cache()->getTotalBytesUsed();
552 size_t SkResourceCache::GetTotalByteLimit() {
553 SkAutoMutexAcquire am(gMutex);
554 return get_cache()->getTotalByteLimit();
557 size_t SkResourceCache::SetTotalByteLimit(size_t newLimit) {
558 SkAutoMutexAcquire am(gMutex);
559 return get_cache()->setTotalByteLimit(newLimit);
562 SkResourceCache::DiscardableFactory SkResourceCache::GetDiscardableFactory() {
563 SkAutoMutexAcquire am(gMutex);
564 return get_cache()->discardableFactory();
567 SkBitmap::Allocator* SkResourceCache::GetAllocator() {
568 SkAutoMutexAcquire am(gMutex);
569 return get_cache()->allocator();
572 SkCachedData* SkResourceCache::NewCachedData(size_t bytes) {
573 SkAutoMutexAcquire am(gMutex);
574 return get_cache()->newCachedData(bytes);
577 void SkResourceCache::Dump() {
578 SkAutoMutexAcquire am(gMutex);
582 size_t SkResourceCache::SetSingleAllocationByteLimit(size_t size) {
583 SkAutoMutexAcquire am(gMutex);
584 return get_cache()->setSingleAllocationByteLimit(size);
587 size_t SkResourceCache::GetSingleAllocationByteLimit() {
588 SkAutoMutexAcquire am(gMutex);
589 return get_cache()->getSingleAllocationByteLimit();
592 size_t SkResourceCache::GetEffectiveSingleAllocationByteLimit() {
593 SkAutoMutexAcquire am(gMutex);
594 return get_cache()->getEffectiveSingleAllocationByteLimit();
597 void SkResourceCache::PurgeAll() {
598 SkAutoMutexAcquire am(gMutex);
599 return get_cache()->purgeAll();
602 bool SkResourceCache::Find(const Key& key, FindVisitor visitor, void* context) {
603 SkAutoMutexAcquire am(gMutex);
604 return get_cache()->find(key, visitor, context);
607 void SkResourceCache::Add(Rec* rec) {
608 SkAutoMutexAcquire am(gMutex);
609 get_cache()->add(rec);
612 void SkResourceCache::PostPurgeSharedID(uint64_t sharedID) {
614 SkMessageBus<PurgeSharedIDMessage>::Post(PurgeSharedIDMessage(sharedID));
618 ///////////////////////////////////////////////////////////////////////////////
620 #include "SkGraphics.h"
622 size_t SkGraphics::GetResourceCacheTotalBytesUsed() {
623 return SkResourceCache::GetTotalBytesUsed();
626 size_t SkGraphics::GetResourceCacheTotalByteLimit() {
627 return SkResourceCache::GetTotalByteLimit();
630 size_t SkGraphics::SetResourceCacheTotalByteLimit(size_t newLimit) {
631 return SkResourceCache::SetTotalByteLimit(newLimit);
634 size_t SkGraphics::GetResourceCacheSingleAllocationByteLimit() {
635 return SkResourceCache::GetSingleAllocationByteLimit();
638 size_t SkGraphics::SetResourceCacheSingleAllocationByteLimit(size_t newLimit) {
639 return SkResourceCache::SetSingleAllocationByteLimit(newLimit);
642 void SkGraphics::PurgeResourceCache() {
643 return SkResourceCache::PurgeAll();