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