Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / core / SkResourceCache.cpp
1 /*
2  * Copyright 2013 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7
8 #include "SkChecksum.h"
9 #include "SkResourceCache.h"
10 #include "SkMipMap.h"
11 #include "SkPixelRef.h"
12
13 #include <stddef.h>
14
15 // This can be defined by the caller's build system
16 //#define SK_USE_DISCARDABLE_SCALEDIMAGECACHE
17
18 #ifndef SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT
19 #   define SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT   1024
20 #endif
21
22 #ifndef SK_DEFAULT_IMAGE_CACHE_LIMIT
23     #define SK_DEFAULT_IMAGE_CACHE_LIMIT     (2 * 1024 * 1024)
24 #endif
25
26 void SkResourceCache::Key::init(void* nameSpace, size_t length) {
27     SkASSERT(SkAlign4(length) == length);
28
29     // fCount32 and fHash are not hashed
30     static const int kUnhashedLocal32s = 2;
31     static const int kLocal32s = kUnhashedLocal32s + (sizeof(fNamespace) >> 2);
32
33     SK_COMPILE_ASSERT(sizeof(Key) == (kLocal32s << 2), unaccounted_key_locals);
34     SK_COMPILE_ASSERT(sizeof(Key) == offsetof(Key, fNamespace) + sizeof(fNamespace),
35                       namespace_field_must_be_last);
36
37     fCount32 = SkToS32(kLocal32s + (length >> 2));
38     fNamespace = nameSpace;
39     // skip unhashed fields when computing the murmur
40     fHash = SkChecksum::Murmur3(this->as32() + kUnhashedLocal32s,
41                                 (fCount32 - kUnhashedLocal32s) << 2);
42 }
43
44 #include "SkTDynamicHash.h"
45
46 class SkResourceCache::Hash :
47     public SkTDynamicHash<SkResourceCache::Rec, SkResourceCache::Key> {};
48
49
50 ///////////////////////////////////////////////////////////////////////////////
51
52 void SkResourceCache::init() {
53     fHead = NULL;
54     fTail = NULL;
55     fHash = new Hash;
56     fTotalBytesUsed = 0;
57     fCount = 0;
58     fSingleAllocationByteLimit = 0;
59     fAllocator = NULL;
60
61     // One of these should be explicit set by the caller after we return.
62     fTotalByteLimit = 0;
63     fDiscardableFactory = NULL;
64 }
65
66 #include "SkDiscardableMemory.h"
67
68 class SkOneShotDiscardablePixelRef : public SkPixelRef {
69 public:
70     SK_DECLARE_INST_COUNT(SkOneShotDiscardablePixelRef)
71     // Ownership of the discardablememory is transfered to the pixelref
72     SkOneShotDiscardablePixelRef(const SkImageInfo&, SkDiscardableMemory*, size_t rowBytes);
73     ~SkOneShotDiscardablePixelRef();
74
75 protected:
76     virtual bool onNewLockPixels(LockRec*) SK_OVERRIDE;
77     virtual void onUnlockPixels() SK_OVERRIDE;
78     virtual size_t getAllocatedSizeInBytes() const SK_OVERRIDE;
79
80 private:
81     SkDiscardableMemory* fDM;
82     size_t               fRB;
83     bool                 fFirstTime;
84
85     typedef SkPixelRef INHERITED;
86 };
87
88 SkOneShotDiscardablePixelRef::SkOneShotDiscardablePixelRef(const SkImageInfo& info,
89                                              SkDiscardableMemory* dm,
90                                              size_t rowBytes)
91     : INHERITED(info)
92     , fDM(dm)
93     , fRB(rowBytes)
94 {
95     SkASSERT(dm->data());
96     fFirstTime = true;
97 }
98
99 SkOneShotDiscardablePixelRef::~SkOneShotDiscardablePixelRef() {
100     SkDELETE(fDM);
101 }
102
103 bool SkOneShotDiscardablePixelRef::onNewLockPixels(LockRec* rec) {
104     if (fFirstTime) {
105         // we're already locked
106         SkASSERT(fDM->data());
107         fFirstTime = false;
108         goto SUCCESS;
109     }
110
111     // A previous call to onUnlock may have deleted our DM, so check for that
112     if (NULL == fDM) {
113         return false;
114     }
115
116     if (!fDM->lock()) {
117         // since it failed, we delete it now, to free-up the resource
118         delete fDM;
119         fDM = NULL;
120         return false;
121     }
122
123 SUCCESS:
124     rec->fPixels = fDM->data();
125     rec->fColorTable = NULL;
126     rec->fRowBytes = fRB;
127     return true;
128 }
129
130 void SkOneShotDiscardablePixelRef::onUnlockPixels() {
131     SkASSERT(!fFirstTime);
132     fDM->unlock();
133 }
134
135 size_t SkOneShotDiscardablePixelRef::getAllocatedSizeInBytes() const {
136     return this->info().getSafeSize(fRB);
137 }
138
139 class SkResourceCacheDiscardableAllocator : public SkBitmap::Allocator {
140 public:
141     SkResourceCacheDiscardableAllocator(SkResourceCache::DiscardableFactory factory) {
142         SkASSERT(factory);
143         fFactory = factory;
144     }
145
146     virtual bool allocPixelRef(SkBitmap*, SkColorTable*) SK_OVERRIDE;
147
148 private:
149     SkResourceCache::DiscardableFactory fFactory;
150 };
151
152 bool SkResourceCacheDiscardableAllocator::allocPixelRef(SkBitmap* bitmap, SkColorTable* ctable) {
153     size_t size = bitmap->getSize();
154     uint64_t size64 = bitmap->computeSize64();
155     if (0 == size || size64 > (uint64_t)size) {
156         return false;
157     }
158
159     SkDiscardableMemory* dm = fFactory(size);
160     if (NULL == dm) {
161         return false;
162     }
163
164     // can we relax this?
165     if (kN32_SkColorType != bitmap->colorType()) {
166         return false;
167     }
168
169     SkImageInfo info = bitmap->info();
170     bitmap->setPixelRef(SkNEW_ARGS(SkOneShotDiscardablePixelRef,
171                                    (info, dm, bitmap->rowBytes())))->unref();
172     bitmap->lockPixels();
173     return bitmap->readyToDraw();
174 }
175
176 SkResourceCache::SkResourceCache(DiscardableFactory factory) {
177     this->init();
178     fDiscardableFactory = factory;
179
180     fAllocator = SkNEW_ARGS(SkResourceCacheDiscardableAllocator, (factory));
181 }
182
183 SkResourceCache::SkResourceCache(size_t byteLimit) {
184     this->init();
185     fTotalByteLimit = byteLimit;
186 }
187
188 SkResourceCache::~SkResourceCache() {
189     SkSafeUnref(fAllocator);
190
191     Rec* rec = fHead;
192     while (rec) {
193         Rec* next = rec->fNext;
194         SkDELETE(rec);
195         rec = next;
196     }
197     delete fHash;
198 }
199
200 ////////////////////////////////////////////////////////////////////////////////
201
202 bool SkResourceCache::find(const Key& key, VisitorProc visitor, void* context) {
203     Rec* rec = fHash->find(key);
204     if (rec) {
205         if (visitor(*rec, context)) {
206             this->moveToHead(rec);  // for our LRU
207             return true;
208         } else {
209             this->remove(rec);  // stale
210             return false;
211         }
212     }
213     return false;
214 }
215
216 static void make_size_str(size_t size, SkString* str) {
217     const char suffix[] = { 'b', 'k', 'm', 'g', 't', 0 };
218     int i = 0;
219     while (suffix[i] && (size > 1024)) {
220         i += 1;
221         size >>= 10;
222     }
223     str->printf("%zu%c", size, suffix[i]);
224 }
225
226 static bool gDumpCacheTransactions;
227
228 void SkResourceCache::add(Rec* rec) {
229     SkASSERT(rec);
230     // See if we already have this key (racy inserts, etc.)
231     Rec* existing = fHash->find(rec->getKey());
232     if (existing) {
233         SkDELETE(rec);
234         return;
235     }
236     
237     this->addToHead(rec);
238     fHash->add(rec);
239
240     if (gDumpCacheTransactions) {
241         SkString bytesStr, totalStr;
242         make_size_str(rec->bytesUsed(), &bytesStr);
243         make_size_str(fTotalBytesUsed, &totalStr);
244         SkDebugf("RC:    add %5s %12p key %08x -- total %5s, count %d\n",
245                  bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
246     }
247
248     // since the new rec may push us over-budget, we perform a purge check now
249     this->purgeAsNeeded();
250 }
251
252 void SkResourceCache::remove(Rec* rec) {
253     size_t used = rec->bytesUsed();
254     SkASSERT(used <= fTotalBytesUsed);
255
256     this->detach(rec);
257     fHash->remove(rec->getKey());
258
259     fTotalBytesUsed -= used;
260     fCount -= 1;
261
262     if (gDumpCacheTransactions) {
263         SkString bytesStr, totalStr;
264         make_size_str(used, &bytesStr);
265         make_size_str(fTotalBytesUsed, &totalStr);
266         SkDebugf("RC: remove %5s %12p key %08x -- total %5s, count %d\n",
267                  bytesStr.c_str(), rec, rec->getHash(), totalStr.c_str(), fCount);
268     }
269
270     SkDELETE(rec);
271 }
272
273 void SkResourceCache::purgeAsNeeded(bool forcePurge) {
274     size_t byteLimit;
275     int    countLimit;
276
277     if (fDiscardableFactory) {
278         countLimit = SK_DISCARDABLEMEMORY_SCALEDIMAGECACHE_COUNT_LIMIT;
279         byteLimit = SK_MaxU32;  // no limit based on bytes
280     } else {
281         countLimit = SK_MaxS32; // no limit based on count
282         byteLimit = fTotalByteLimit;
283     }
284
285     Rec* rec = fTail;
286     while (rec) {
287         if (!forcePurge && fTotalBytesUsed < byteLimit && fCount < countLimit) {
288             break;
289         }
290
291         Rec* prev = rec->fPrev;
292         this->remove(rec);
293         rec = prev;
294     }
295 }
296
297 size_t SkResourceCache::setTotalByteLimit(size_t newLimit) {
298     size_t prevLimit = fTotalByteLimit;
299     fTotalByteLimit = newLimit;
300     if (newLimit < prevLimit) {
301         this->purgeAsNeeded();
302     }
303     return prevLimit;
304 }
305
306 SkCachedData* SkResourceCache::newCachedData(size_t bytes) {
307     if (fDiscardableFactory) {
308         SkDiscardableMemory* dm = fDiscardableFactory(bytes);
309         return dm ? SkNEW_ARGS(SkCachedData, (bytes, dm)) : NULL;
310     } else {
311         return SkNEW_ARGS(SkCachedData, (sk_malloc_throw(bytes), bytes));
312     }
313 }
314
315 ///////////////////////////////////////////////////////////////////////////////
316
317 void SkResourceCache::detach(Rec* rec) {
318     Rec* prev = rec->fPrev;
319     Rec* next = rec->fNext;
320
321     if (!prev) {
322         SkASSERT(fHead == rec);
323         fHead = next;
324     } else {
325         prev->fNext = next;
326     }
327
328     if (!next) {
329         fTail = prev;
330     } else {
331         next->fPrev = prev;
332     }
333
334     rec->fNext = rec->fPrev = NULL;
335 }
336
337 void SkResourceCache::moveToHead(Rec* rec) {
338     if (fHead == rec) {
339         return;
340     }
341
342     SkASSERT(fHead);
343     SkASSERT(fTail);
344
345     this->validate();
346
347     this->detach(rec);
348
349     fHead->fPrev = rec;
350     rec->fNext = fHead;
351     fHead = rec;
352
353     this->validate();
354 }
355
356 void SkResourceCache::addToHead(Rec* rec) {
357     this->validate();
358
359     rec->fPrev = NULL;
360     rec->fNext = fHead;
361     if (fHead) {
362         fHead->fPrev = rec;
363     }
364     fHead = rec;
365     if (!fTail) {
366         fTail = rec;
367     }
368     fTotalBytesUsed += rec->bytesUsed();
369     fCount += 1;
370
371     this->validate();
372 }
373
374 ///////////////////////////////////////////////////////////////////////////////
375
376 #ifdef SK_DEBUG
377 void SkResourceCache::validate() const {
378     if (NULL == fHead) {
379         SkASSERT(NULL == fTail);
380         SkASSERT(0 == fTotalBytesUsed);
381         return;
382     }
383
384     if (fHead == fTail) {
385         SkASSERT(NULL == fHead->fPrev);
386         SkASSERT(NULL == fHead->fNext);
387         SkASSERT(fHead->bytesUsed() == fTotalBytesUsed);
388         return;
389     }
390
391     SkASSERT(NULL == fHead->fPrev);
392     SkASSERT(fHead->fNext);
393     SkASSERT(NULL == fTail->fNext);
394     SkASSERT(fTail->fPrev);
395
396     size_t used = 0;
397     int count = 0;
398     const Rec* rec = fHead;
399     while (rec) {
400         count += 1;
401         used += rec->bytesUsed();
402         SkASSERT(used <= fTotalBytesUsed);
403         rec = rec->fNext;
404     }
405     SkASSERT(fCount == count);
406
407     rec = fTail;
408     while (rec) {
409         SkASSERT(count > 0);
410         count -= 1;
411         SkASSERT(used >= rec->bytesUsed());
412         used -= rec->bytesUsed();
413         rec = rec->fPrev;
414     }
415
416     SkASSERT(0 == count);
417     SkASSERT(0 == used);
418 }
419 #endif
420
421 void SkResourceCache::dump() const {
422     this->validate();
423
424     SkDebugf("SkResourceCache: count=%d bytes=%d %s\n",
425              fCount, fTotalBytesUsed, fDiscardableFactory ? "discardable" : "malloc");
426 }
427
428 size_t SkResourceCache::setSingleAllocationByteLimit(size_t newLimit) {
429     size_t oldLimit = fSingleAllocationByteLimit;
430     fSingleAllocationByteLimit = newLimit;
431     return oldLimit;
432 }
433
434 size_t SkResourceCache::getSingleAllocationByteLimit() const {
435     return fSingleAllocationByteLimit;
436 }
437
438 ///////////////////////////////////////////////////////////////////////////////
439
440 #include "SkThread.h"
441
442 SK_DECLARE_STATIC_MUTEX(gMutex);
443 static SkResourceCache* gResourceCache = NULL;
444 static void cleanup_gResourceCache() {
445     // We'll clean this up in our own tests, but disable for clients.
446     // Chrome seems to have funky multi-process things going on in unit tests that
447     // makes this unsafe to delete when the main process atexit()s.
448     // SkLazyPtr does the same sort of thing.
449 #if SK_DEVELOPER
450     SkDELETE(gResourceCache);
451 #endif
452 }
453
454 /** Must hold gMutex when calling. */
455 static SkResourceCache* get_cache() {
456     // gMutex is always held when this is called, so we don't need to be fancy in here.
457     gMutex.assertHeld();
458     if (NULL == gResourceCache) {
459 #ifdef SK_USE_DISCARDABLE_SCALEDIMAGECACHE
460         gResourceCache = SkNEW_ARGS(SkResourceCache, (SkDiscardableMemory::Create));
461 #else
462         gResourceCache = SkNEW_ARGS(SkResourceCache, (SK_DEFAULT_IMAGE_CACHE_LIMIT));
463 #endif
464         atexit(cleanup_gResourceCache);
465     }
466     return gResourceCache;
467 }
468
469 size_t SkResourceCache::GetTotalBytesUsed() {
470     SkAutoMutexAcquire am(gMutex);
471     return get_cache()->getTotalBytesUsed();
472 }
473
474 size_t SkResourceCache::GetTotalByteLimit() {
475     SkAutoMutexAcquire am(gMutex);
476     return get_cache()->getTotalByteLimit();
477 }
478
479 size_t SkResourceCache::SetTotalByteLimit(size_t newLimit) {
480     SkAutoMutexAcquire am(gMutex);
481     return get_cache()->setTotalByteLimit(newLimit);
482 }
483
484 SkResourceCache::DiscardableFactory SkResourceCache::GetDiscardableFactory() {
485     SkAutoMutexAcquire am(gMutex);
486     return get_cache()->discardableFactory();
487 }
488
489 SkBitmap::Allocator* SkResourceCache::GetAllocator() {
490     SkAutoMutexAcquire am(gMutex);
491     return get_cache()->allocator();
492 }
493
494 SkCachedData* SkResourceCache::NewCachedData(size_t bytes) {
495     SkAutoMutexAcquire am(gMutex);
496     return get_cache()->newCachedData(bytes);
497 }
498
499 void SkResourceCache::Dump() {
500     SkAutoMutexAcquire am(gMutex);
501     get_cache()->dump();
502 }
503
504 size_t SkResourceCache::SetSingleAllocationByteLimit(size_t size) {
505     SkAutoMutexAcquire am(gMutex);
506     return get_cache()->setSingleAllocationByteLimit(size);
507 }
508
509 size_t SkResourceCache::GetSingleAllocationByteLimit() {
510     SkAutoMutexAcquire am(gMutex);
511     return get_cache()->getSingleAllocationByteLimit();
512 }
513
514 void SkResourceCache::PurgeAll() {
515     SkAutoMutexAcquire am(gMutex);
516     return get_cache()->purgeAll();
517 }
518
519 bool SkResourceCache::Find(const Key& key, VisitorProc visitor, void* context) {
520     SkAutoMutexAcquire am(gMutex);
521     return get_cache()->find(key, visitor, context);
522 }
523
524 void SkResourceCache::Add(Rec* rec) {
525     SkAutoMutexAcquire am(gMutex);
526     get_cache()->add(rec);
527 }
528
529 ///////////////////////////////////////////////////////////////////////////////
530
531 #include "SkGraphics.h"
532
533 size_t SkGraphics::GetResourceCacheTotalBytesUsed() {
534     return SkResourceCache::GetTotalBytesUsed();
535 }
536
537 size_t SkGraphics::GetResourceCacheTotalByteLimit() {
538     return SkResourceCache::GetTotalByteLimit();
539 }
540
541 size_t SkGraphics::SetResourceCacheTotalByteLimit(size_t newLimit) {
542     return SkResourceCache::SetTotalByteLimit(newLimit);
543 }
544
545 size_t SkGraphics::GetResourceCacheSingleAllocationByteLimit() {
546     return SkResourceCache::GetSingleAllocationByteLimit();
547 }
548
549 size_t SkGraphics::SetResourceCacheSingleAllocationByteLimit(size_t newLimit) {
550     return SkResourceCache::SetSingleAllocationByteLimit(newLimit);
551 }
552
553 void SkGraphics::PurgeResourceCache() {
554     return SkResourceCache::PurgeAll();
555 }
556