TextureCache.cpp revision 00e79c9947b741194ff6c0d08ede9b3befbf9c9d
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <GLES2/gl2.h>
21
22#include <SkCanvas.h>
23#include <SkPixelRef.h>
24
25#include <utils/Mutex.h>
26
27#include "AssetAtlas.h"
28#include "Caches.h"
29#include "Texture.h"
30#include "TextureCache.h"
31#include "Properties.h"
32#include "utils/TraceUtils.h"
33
34namespace android {
35namespace uirenderer {
36
37///////////////////////////////////////////////////////////////////////////////
38// Constructors/destructor
39///////////////////////////////////////////////////////////////////////////////
40
41TextureCache::TextureCache()
42        : mCache(LruCache<uint32_t, Texture*>::kUnlimitedCapacity)
43        , mSize(0)
44        , mMaxSize(MB(DEFAULT_TEXTURE_CACHE_SIZE))
45        , mFlushRate(DEFAULT_TEXTURE_CACHE_FLUSH_RATE)
46        , mAssetAtlas(nullptr) {
47    char property[PROPERTY_VALUE_MAX];
48    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, nullptr) > 0) {
49        INIT_LOGD("  Setting texture cache size to %sMB", property);
50        setMaxSize(MB(atof(property)));
51    } else {
52        INIT_LOGD("  Using default texture cache size of %.2fMB", DEFAULT_TEXTURE_CACHE_SIZE);
53    }
54
55    if (property_get(PROPERTY_TEXTURE_CACHE_FLUSH_RATE, property, nullptr) > 0) {
56        float flushRate = atof(property);
57        INIT_LOGD("  Setting texture cache flush rate to %.2f%%", flushRate * 100.0f);
58        setFlushRate(flushRate);
59    } else {
60        INIT_LOGD("  Using default texture cache flush rate of %.2f%%",
61                DEFAULT_TEXTURE_CACHE_FLUSH_RATE * 100.0f);
62    }
63
64    mCache.setOnEntryRemovedListener(this);
65
66    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
67    INIT_LOGD("    Maximum texture dimension is %d pixels", mMaxTextureSize);
68
69    mDebugEnabled = Properties::debugLevel & kDebugCaches;
70}
71
72TextureCache::~TextureCache() {
73    mCache.clear();
74}
75
76///////////////////////////////////////////////////////////////////////////////
77// Size management
78///////////////////////////////////////////////////////////////////////////////
79
80uint32_t TextureCache::getSize() {
81    return mSize;
82}
83
84uint32_t TextureCache::getMaxSize() {
85    return mMaxSize;
86}
87
88void TextureCache::setMaxSize(uint32_t maxSize) {
89    mMaxSize = maxSize;
90    while (mSize > mMaxSize) {
91        mCache.removeOldest();
92    }
93}
94
95void TextureCache::setFlushRate(float flushRate) {
96    mFlushRate = std::max(0.0f, std::min(1.0f, flushRate));
97}
98
99///////////////////////////////////////////////////////////////////////////////
100// Callbacks
101///////////////////////////////////////////////////////////////////////////////
102
103void TextureCache::operator()(uint32_t&, Texture*& texture) {
104    // This will be called already locked
105    if (texture) {
106        mSize -= texture->bitmapSize;
107        TEXTURE_LOGD("TextureCache::callback: name, removed size, mSize = %d, %d, %d",
108                texture->id, texture->bitmapSize, mSize);
109        if (mDebugEnabled) {
110            ALOGD("Texture deleted, size = %d", texture->bitmapSize);
111        }
112        texture->deleteTexture();
113        delete texture;
114    }
115}
116
117///////////////////////////////////////////////////////////////////////////////
118// Caching
119///////////////////////////////////////////////////////////////////////////////
120
121void TextureCache::setAssetAtlas(AssetAtlas* assetAtlas) {
122    mAssetAtlas = assetAtlas;
123}
124
125void TextureCache::resetMarkInUse(void* ownerToken) {
126    LruCache<uint32_t, Texture*>::Iterator iter(mCache);
127    while (iter.next()) {
128        if (iter.value()->isInUse == ownerToken) {
129            iter.value()->isInUse = nullptr;
130        }
131    }
132}
133
134bool TextureCache::canMakeTextureFromBitmap(const SkBitmap* bitmap) {
135    if (bitmap->width() > mMaxTextureSize || bitmap->height() > mMaxTextureSize) {
136        ALOGW("Bitmap too large to be uploaded into a texture (%dx%d, max=%dx%d)",
137                bitmap->width(), bitmap->height(), mMaxTextureSize, mMaxTextureSize);
138        return false;
139    }
140    return true;
141}
142
143// Returns a prepared Texture* that either is already in the cache or can fit
144// in the cache (and is thus added to the cache)
145Texture* TextureCache::getCachedTexture(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) {
146    if (CC_LIKELY(mAssetAtlas != nullptr) && atlasUsageType == AtlasUsageType::Use) {
147        AssetAtlas::Entry* entry = mAssetAtlas->getEntry(bitmap);
148        if (CC_UNLIKELY(entry)) {
149            return entry->texture;
150        }
151    }
152
153    Texture* texture = mCache.get(bitmap->pixelRef()->getStableID());
154
155    if (!texture) {
156        if (!canMakeTextureFromBitmap(bitmap)) {
157            return nullptr;
158        }
159
160        const uint32_t size = bitmap->rowBytes() * bitmap->height();
161        bool canCache = size < mMaxSize;
162        // Don't even try to cache a bitmap that's bigger than the cache
163        while (canCache && mSize + size > mMaxSize) {
164            Texture* oldest = mCache.peekOldestValue();
165            if (oldest && !oldest->isInUse) {
166                mCache.removeOldest();
167            } else {
168                canCache = false;
169            }
170        }
171
172        if (canCache) {
173            texture = new Texture(Caches::getInstance());
174            texture->bitmapSize = size;
175            generateTexture(bitmap, texture, false);
176
177            mSize += size;
178            TEXTURE_LOGD("TextureCache::get: create texture(%p): name, size, mSize = %d, %d, %d",
179                     bitmap, texture->id, size, mSize);
180            if (mDebugEnabled) {
181                ALOGD("Texture created, size = %d", size);
182            }
183            mCache.put(bitmap->pixelRef()->getStableID(), texture);
184        }
185    } else if (!texture->isInUse && bitmap->getGenerationID() != texture->generation) {
186        // Texture was in the cache but is dirty, re-upload
187        // TODO: Re-adjust the cache size if the bitmap's dimensions have changed
188        generateTexture(bitmap, texture, true);
189    }
190
191    return texture;
192}
193
194bool TextureCache::prefetchAndMarkInUse(void* ownerToken, const SkBitmap* bitmap) {
195    Texture* texture = getCachedTexture(bitmap, AtlasUsageType::Use);
196    if (texture) {
197        texture->isInUse = ownerToken;
198    }
199    return texture;
200}
201
202Texture* TextureCache::get(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) {
203    Texture* texture = getCachedTexture(bitmap, atlasUsageType);
204
205    if (!texture) {
206        if (!canMakeTextureFromBitmap(bitmap)) {
207            return nullptr;
208        }
209
210        const uint32_t size = bitmap->rowBytes() * bitmap->height();
211        texture = new Texture(Caches::getInstance());
212        texture->bitmapSize = size;
213        generateTexture(bitmap, texture, false);
214        texture->cleanup = true;
215    }
216
217    return texture;
218}
219
220void TextureCache::releaseTexture(uint32_t pixelRefStableID) {
221    Mutex::Autolock _l(mLock);
222    mGarbage.push(pixelRefStableID);
223}
224
225void TextureCache::clearGarbage() {
226    Mutex::Autolock _l(mLock);
227    size_t count = mGarbage.size();
228    for (size_t i = 0; i < count; i++) {
229        uint32_t pixelRefId = mGarbage.itemAt(i);
230        mCache.remove(pixelRefId);
231    }
232    mGarbage.clear();
233}
234
235void TextureCache::clear() {
236    mCache.clear();
237    TEXTURE_LOGD("TextureCache:clear(), mSize = %d", mSize);
238}
239
240void TextureCache::flush() {
241    if (mFlushRate >= 1.0f || mCache.size() == 0) return;
242    if (mFlushRate <= 0.0f) {
243        clear();
244        return;
245    }
246
247    uint32_t targetSize = uint32_t(mSize * mFlushRate);
248    TEXTURE_LOGD("TextureCache::flush: target size: %d", targetSize);
249
250    while (mSize > targetSize) {
251        mCache.removeOldest();
252    }
253}
254
255void TextureCache::generateTexture(const SkBitmap* bitmap, Texture* texture, bool regenerate) {
256    SkAutoLockPixels alp(*bitmap);
257
258    if (!bitmap->readyToDraw()) {
259        ALOGE("Cannot generate texture from bitmap");
260        return;
261    }
262
263    ATRACE_FORMAT("Upload %ux%u Texture", bitmap->width(), bitmap->height());
264
265    // We could also enable mipmapping if both bitmap dimensions are powers
266    // of 2 but we'd have to deal with size changes. Let's keep this simple
267    const bool canMipMap = Caches::getInstance().extensions().hasNPot();
268
269    // If the texture had mipmap enabled but not anymore,
270    // force a glTexImage2D to discard the mipmap levels
271    const bool resize = !regenerate || bitmap->width() != int(texture->width) ||
272            bitmap->height() != int(texture->height) ||
273            (regenerate && canMipMap && texture->mipMap && !bitmap->hasHardwareMipMap());
274
275    if (!regenerate) {
276        glGenTextures(1, &texture->id);
277    }
278
279    texture->generation = bitmap->getGenerationID();
280    texture->width = bitmap->width();
281    texture->height = bitmap->height();
282
283    Caches::getInstance().textureState().bindTexture(texture->id);
284
285    switch (bitmap->colorType()) {
286    case kAlpha_8_SkColorType:
287        uploadToTexture(resize, GL_ALPHA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
288                texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels());
289        texture->blend = true;
290        break;
291    case kRGB_565_SkColorType:
292        uploadToTexture(resize, GL_RGB, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
293                texture->width, texture->height, GL_UNSIGNED_SHORT_5_6_5, bitmap->getPixels());
294        texture->blend = false;
295        break;
296    case kN32_SkColorType:
297        uploadToTexture(resize, GL_RGBA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
298                texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels());
299        // Do this after calling getPixels() to make sure Skia's deferred
300        // decoding happened
301        texture->blend = !bitmap->isOpaque();
302        break;
303    case kARGB_4444_SkColorType:
304    case kIndex_8_SkColorType:
305        uploadLoFiTexture(resize, bitmap, texture->width, texture->height);
306        texture->blend = !bitmap->isOpaque();
307        break;
308    default:
309        ALOGW("Unsupported bitmap colorType: %d", bitmap->colorType());
310        break;
311    }
312
313    if (canMipMap) {
314        texture->mipMap = bitmap->hasHardwareMipMap();
315        if (texture->mipMap) {
316            glGenerateMipmap(GL_TEXTURE_2D);
317        }
318    }
319
320    if (!regenerate) {
321        texture->setFilter(GL_NEAREST);
322        texture->setWrap(GL_CLAMP_TO_EDGE);
323    }
324}
325
326void TextureCache::uploadLoFiTexture(bool resize, const SkBitmap* bitmap,
327        uint32_t width, uint32_t height) {
328    SkBitmap rgbaBitmap;
329    rgbaBitmap.allocPixels(SkImageInfo::MakeN32(width, height, bitmap->alphaType()));
330    rgbaBitmap.eraseColor(0);
331
332    SkCanvas canvas(rgbaBitmap);
333    canvas.drawBitmap(*bitmap, 0.0f, 0.0f, nullptr);
334
335    uploadToTexture(resize, GL_RGBA, rgbaBitmap.rowBytesAsPixels(), rgbaBitmap.bytesPerPixel(),
336            width, height, GL_UNSIGNED_BYTE, rgbaBitmap.getPixels());
337}
338
339void TextureCache::uploadToTexture(bool resize, GLenum format, GLsizei stride, GLsizei bpp,
340        GLsizei width, GLsizei height, GLenum type, const GLvoid * data) {
341    glPixelStorei(GL_UNPACK_ALIGNMENT, bpp);
342    const bool useStride = stride != width
343            && Caches::getInstance().extensions().hasUnpackRowLength();
344    if ((stride == width) || useStride) {
345        if (useStride) {
346            glPixelStorei(GL_UNPACK_ROW_LENGTH, stride);
347        }
348
349        if (resize) {
350            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, data);
351        } else {
352            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data);
353        }
354
355        if (useStride) {
356            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
357        }
358    } else {
359        //  With OpenGL ES 2.0 we need to copy the bitmap in a temporary buffer
360        //  if the stride doesn't match the width
361
362        GLvoid * temp = (GLvoid *) malloc(width * height * bpp);
363        if (!temp) return;
364
365        uint8_t * pDst = (uint8_t *)temp;
366        uint8_t * pSrc = (uint8_t *)data;
367        for (GLsizei i = 0; i < height; i++) {
368            memcpy(pDst, pSrc, width * bpp);
369            pDst += width * bpp;
370            pSrc += stride * bpp;
371        }
372
373        if (resize) {
374            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, temp);
375        } else {
376            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, temp);
377        }
378
379        free(temp);
380    }
381}
382
383}; // namespace uirenderer
384}; // namespace android
385