1 /*
2 * Copyright 2014 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 "Test.h"
9 #include "SkBitmapCache.h"
10 #include "SkBitmapProvider.h"
11 #include "SkCanvas.h"
12 #include "SkDiscardableMemoryPool.h"
13 #include "SkGraphics.h"
14 #include "SkMakeUnique.h"
15 #include "SkMipMap.h"
16 #include "SkPicture.h"
17 #include "SkPictureRecorder.h"
18 #include "SkResourceCache.h"
19 #include "SkSurface.h"
20
21 ////////////////////////////////////////////////////////////////////////////////////////
22
23 enum LockedState {
24 kNotLocked,
25 kLocked,
26 };
27
28 enum CachedState {
29 kNotInCache,
30 kInCache,
31 };
32
check_data(skiatest::Reporter * reporter,const SkCachedData * data,int refcnt,CachedState cacheState,LockedState lockedState)33 static void check_data(skiatest::Reporter* reporter, const SkCachedData* data,
34 int refcnt, CachedState cacheState, LockedState lockedState) {
35 REPORTER_ASSERT(reporter, data->testing_only_getRefCnt() == refcnt);
36 REPORTER_ASSERT(reporter, data->testing_only_isInCache() == (kInCache == cacheState));
37 bool isLocked = (data->data() != nullptr);
38 REPORTER_ASSERT(reporter, isLocked == (lockedState == kLocked));
39 }
40
test_mipmapcache(skiatest::Reporter * reporter,SkResourceCache * cache)41 static void test_mipmapcache(skiatest::Reporter* reporter, SkResourceCache* cache) {
42 cache->purgeAll();
43
44 SkBitmap src;
45 src.allocN32Pixels(5, 5);
46 src.setImmutable();
47 sk_sp<SkImage> img = SkImage::MakeFromBitmap(src);
48 SkBitmapProvider provider(img.get());
49 const auto desc = provider.makeCacheDesc();
50
51 const SkMipMap* mipmap = SkMipMapCache::FindAndRef(desc, cache);
52 REPORTER_ASSERT(reporter, nullptr == mipmap);
53
54 mipmap = SkMipMapCache::AddAndRef(provider, cache);
55 REPORTER_ASSERT(reporter, mipmap);
56
57 {
58 const SkMipMap* mm = SkMipMapCache::FindAndRef(desc, cache);
59 REPORTER_ASSERT(reporter, mm);
60 REPORTER_ASSERT(reporter, mm == mipmap);
61 mm->unref();
62 }
63
64 check_data(reporter, mipmap, 2, kInCache, kLocked);
65
66 mipmap->unref();
67 // tricky, since technically after this I'm no longer an owner, but since the cache is
68 // local, I know it won't get purged behind my back
69 check_data(reporter, mipmap, 1, kInCache, kNotLocked);
70
71 // find us again
72 mipmap = SkMipMapCache::FindAndRef(desc, cache);
73 check_data(reporter, mipmap, 2, kInCache, kLocked);
74
75 cache->purgeAll();
76 check_data(reporter, mipmap, 1, kNotInCache, kLocked);
77
78 mipmap->unref();
79 }
80
test_mipmap_notify(skiatest::Reporter * reporter,SkResourceCache * cache)81 static void test_mipmap_notify(skiatest::Reporter* reporter, SkResourceCache* cache) {
82 const int N = 3;
83
84 SkBitmap src[N];
85 sk_sp<SkImage> img[N];
86 SkBitmapCacheDesc desc[N];
87 for (int i = 0; i < N; ++i) {
88 src[i].allocN32Pixels(5, 5);
89 src[i].setImmutable();
90 img[i] = SkImage::MakeFromBitmap(src[i]);
91 SkBitmapProvider provider(img[i].get());
92 SkMipMapCache::AddAndRef(provider, cache)->unref();
93 desc[i] = provider.makeCacheDesc();
94 }
95
96 for (int i = 0; i < N; ++i) {
97 const SkMipMap* mipmap = SkMipMapCache::FindAndRef(desc[i], cache);
98 // We're always using a local cache, so we know we won't be purged by other threads
99 REPORTER_ASSERT(reporter, mipmap);
100 SkSafeUnref(mipmap);
101
102 img[i].reset(); // delete the image, which *should not* remove us from the cache
103 mipmap = SkMipMapCache::FindAndRef(desc[i], cache);
104 REPORTER_ASSERT(reporter, mipmap);
105 SkSafeUnref(mipmap);
106
107 src[i].reset(); // delete the underlying pixelref, which *should* remove us from the cache
108 mipmap = SkMipMapCache::FindAndRef(desc[i], cache);
109 REPORTER_ASSERT(reporter, !mipmap);
110 }
111 }
112
113 #include "SkDiscardableMemoryPool.h"
114
115 static SkDiscardableMemoryPool* gPool = nullptr;
pool_factory(size_t bytes)116 static SkDiscardableMemory* pool_factory(size_t bytes) {
117 SkASSERT(gPool);
118 return gPool->create(bytes);
119 }
120
testBitmapCache_discarded_bitmap(skiatest::Reporter * reporter,SkResourceCache * cache,SkResourceCache::DiscardableFactory factory)121 static void testBitmapCache_discarded_bitmap(skiatest::Reporter* reporter, SkResourceCache* cache,
122 SkResourceCache::DiscardableFactory factory) {
123 test_mipmapcache(reporter, cache);
124 test_mipmap_notify(reporter, cache);
125 }
126
DEF_TEST(BitmapCache_discarded_bitmap,reporter)127 DEF_TEST(BitmapCache_discarded_bitmap, reporter) {
128 const size_t byteLimit = 100 * 1024;
129 {
130 SkResourceCache cache(byteLimit);
131 testBitmapCache_discarded_bitmap(reporter, &cache, nullptr);
132 }
133 {
134 sk_sp<SkDiscardableMemoryPool> pool(SkDiscardableMemoryPool::Make(byteLimit));
135 gPool = pool.get();
136 SkResourceCache::DiscardableFactory factory = pool_factory;
137 SkResourceCache cache(factory);
138 testBitmapCache_discarded_bitmap(reporter, &cache, factory);
139 }
140 }
141
test_discarded_image(skiatest::Reporter * reporter,const SkMatrix & transform,sk_sp<SkImage> (* buildImage)())142 static void test_discarded_image(skiatest::Reporter* reporter, const SkMatrix& transform,
143 sk_sp<SkImage> (*buildImage)()) {
144 auto surface(SkSurface::MakeRasterN32Premul(10, 10));
145 SkCanvas* canvas = surface->getCanvas();
146
147 // SkBitmapCache is global, so other threads could be evicting our bitmaps. Loop a few times
148 // to mitigate this risk.
149 const unsigned kRepeatCount = 42;
150 for (unsigned i = 0; i < kRepeatCount; ++i) {
151 SkAutoCanvasRestore acr(canvas, true);
152
153 sk_sp<SkImage> image(buildImage());
154
155 // always use high quality to ensure caching when scaled
156 SkPaint paint;
157 paint.setFilterQuality(kHigh_SkFilterQuality);
158
159 // draw the image (with a transform, to tickle different code paths) to ensure
160 // any associated resources get cached
161 canvas->concat(transform);
162 canvas->drawImage(image, 0, 0, &paint);
163
164 const auto desc = SkBitmapCacheDesc::Make(image.get());
165
166 // delete the image
167 image.reset(nullptr);
168
169 // all resources should have been purged
170 SkBitmap result;
171 REPORTER_ASSERT(reporter, !SkBitmapCache::Find(desc, &result));
172 }
173 }
174
175
176 // Verify that associated bitmap cache entries are purged on SkImage destruction.
DEF_TEST(BitmapCache_discarded_image,reporter)177 DEF_TEST(BitmapCache_discarded_image, reporter) {
178 // Cache entries associated with SkImages fall into two categories:
179 //
180 // 1) generated image bitmaps (managed by the image cacherator)
181 // 2) scaled/resampled bitmaps (cached when HQ filters are used)
182 //
183 // To exercise the first cache type, we use generated/picture-backed SkImages.
184 // To exercise the latter, we draw scaled bitmap images using HQ filters.
185
186 const SkMatrix xforms[] = {
187 SkMatrix::MakeScale(1, 1),
188 SkMatrix::MakeScale(1.7f, 0.5f),
189 };
190
191 for (size_t i = 0; i < SK_ARRAY_COUNT(xforms); ++i) {
192 test_discarded_image(reporter, xforms[i], []() {
193 auto surface(SkSurface::MakeRasterN32Premul(10, 10));
194 surface->getCanvas()->clear(SK_ColorCYAN);
195 return surface->makeImageSnapshot();
196 });
197
198 test_discarded_image(reporter, xforms[i], []() {
199 SkPictureRecorder recorder;
200 SkCanvas* canvas = recorder.beginRecording(10, 10);
201 canvas->clear(SK_ColorCYAN);
202 return SkImage::MakeFromPicture(recorder.finishRecordingAsPicture(),
203 SkISize::Make(10, 10), nullptr, nullptr,
204 SkImage::BitDepth::kU8,
205 SkColorSpace::MakeSRGB());
206 });
207 }
208 }
209
210 ///////////////////////////////////////////////////////////////////////////////////////////////////
211
212 static void* gTestNamespace;
213
214 struct TestKey : SkResourceCache::Key {
215 int32_t fData;
216
TestKeyTestKey217 TestKey(int sharedID, int32_t data) : fData(data) {
218 this->init(&gTestNamespace, sharedID, sizeof(fData));
219 }
220 };
221
222 struct TestRec : SkResourceCache::Rec {
223 enum {
224 kDidInstall = 1 << 0,
225 };
226
227 TestKey fKey;
228 int* fFlags;
229 bool fCanBePurged;
230
TestRecTestRec231 TestRec(int sharedID, int32_t data, int* flagPtr) : fKey(sharedID, data), fFlags(flagPtr) {
232 fCanBePurged = false;
233 }
234
getKeyTestRec235 const Key& getKey() const override { return fKey; }
bytesUsedTestRec236 size_t bytesUsed() const override { return 1024; /* just need a value */ }
canBePurgedTestRec237 bool canBePurged() override { return fCanBePurged; }
postAddInstallTestRec238 void postAddInstall(void*) override {
239 *fFlags |= kDidInstall;
240 }
getCategoryTestRec241 const char* getCategory() const override { return "test-category"; }
242 };
243
test_duplicate_add(SkResourceCache * cache,skiatest::Reporter * reporter,bool purgable)244 static void test_duplicate_add(SkResourceCache* cache, skiatest::Reporter* reporter,
245 bool purgable) {
246 int sharedID = 1;
247 int data = 0;
248
249 int flags0 = 0, flags1 = 0;
250
251 auto rec0 = skstd::make_unique<TestRec>(sharedID, data, &flags0);
252 auto rec1 = skstd::make_unique<TestRec>(sharedID, data, &flags1);
253 SkASSERT(rec0->getKey() == rec1->getKey());
254
255 TestRec* r0 = rec0.get(); // save the bare-pointer since we will release rec0
256 r0->fCanBePurged = purgable;
257
258 REPORTER_ASSERT(reporter, !(flags0 & TestRec::kDidInstall));
259 REPORTER_ASSERT(reporter, !(flags1 & TestRec::kDidInstall));
260
261 cache->add(rec0.release(), nullptr);
262 REPORTER_ASSERT(reporter, flags0 & TestRec::kDidInstall);
263 REPORTER_ASSERT(reporter, !(flags1 & TestRec::kDidInstall));
264 flags0 = 0; // reset the flag
265
266 cache->add(rec1.release(), nullptr);
267 if (purgable) {
268 // we purged rec0, and did install rec1
269 REPORTER_ASSERT(reporter, !(flags0 & TestRec::kDidInstall));
270 REPORTER_ASSERT(reporter, flags1 & TestRec::kDidInstall);
271 } else {
272 // we re-used rec0 and did not install rec1
273 REPORTER_ASSERT(reporter, flags0 & TestRec::kDidInstall);
274 REPORTER_ASSERT(reporter, !(flags1 & TestRec::kDidInstall));
275 r0->fCanBePurged = true; // so we can cleanup the cache
276 }
277 }
278
279 /*
280 * Test behavior when the same key is added more than once.
281 */
DEF_TEST(ResourceCache_purge,reporter)282 DEF_TEST(ResourceCache_purge, reporter) {
283 for (bool purgable : { false, true }) {
284 {
285 SkResourceCache cache(1024 * 1024);
286 test_duplicate_add(&cache, reporter, purgable);
287 }
288 {
289 SkResourceCache cache(SkDiscardableMemory::Create);
290 test_duplicate_add(&cache, reporter, purgable);
291 }
292 }
293 }
294