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