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