TextureCache.cpp revision 3d4eed7f1aa99401dabe2e45b82f98fb4fc2d754
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(nullptr) {
45    char property[PROPERTY_VALUE_MAX];
46    if (property_get(PROPERTY_TEXTURE_CACHE_SIZE, property, nullptr) > 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, nullptr) > 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(nullptr) {
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 nullptr;
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 nullptr;
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(uint32_t pixelRefStableID) {
237    Mutex::Autolock _l(mLock);
238    mGarbage.push(pixelRefStableID);
239}
240
241void TextureCache::clearGarbage() {
242    Mutex::Autolock _l(mLock);
243    size_t count = mGarbage.size();
244    for (size_t i = 0; i < count; i++) {
245        uint32_t pixelRefId = mGarbage.itemAt(i);
246        mCache.remove(pixelRefId);
247    }
248    mGarbage.clear();
249}
250
251void TextureCache::clear() {
252    mCache.clear();
253    TEXTURE_LOGD("TextureCache:clear(), mSize = %d", mSize);
254}
255
256void TextureCache::flush() {
257    if (mFlushRate >= 1.0f || mCache.size() == 0) return;
258    if (mFlushRate <= 0.0f) {
259        clear();
260        return;
261    }
262
263    uint32_t targetSize = uint32_t(mSize * mFlushRate);
264    TEXTURE_LOGD("TextureCache::flush: target size: %d", targetSize);
265
266    while (mSize > targetSize) {
267        mCache.removeOldest();
268    }
269}
270
271void TextureCache::generateTexture(const SkBitmap* bitmap, Texture* texture, bool regenerate) {
272    SkAutoLockPixels alp(*bitmap);
273
274    if (!bitmap->readyToDraw()) {
275        ALOGE("Cannot generate texture from bitmap");
276        return;
277    }
278
279    ATRACE_FORMAT("Upload %ux%u Texture", bitmap->width(), bitmap->height());
280
281    // We could also enable mipmapping if both bitmap dimensions are powers
282    // of 2 but we'd have to deal with size changes. Let's keep this simple
283    const bool canMipMap = Extensions::getInstance().hasNPot();
284
285    // If the texture had mipmap enabled but not anymore,
286    // force a glTexImage2D to discard the mipmap levels
287    const bool resize = !regenerate || bitmap->width() != int(texture->width) ||
288            bitmap->height() != int(texture->height) ||
289            (regenerate && canMipMap && texture->mipMap && !bitmap->hasHardwareMipMap());
290
291    if (!regenerate) {
292        glGenTextures(1, &texture->id);
293    }
294
295    texture->generation = bitmap->getGenerationID();
296    texture->width = bitmap->width();
297    texture->height = bitmap->height();
298
299    Caches::getInstance().bindTexture(texture->id);
300
301    switch (bitmap->colorType()) {
302    case kAlpha_8_SkColorType:
303        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
304        uploadToTexture(resize, GL_ALPHA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
305                texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels());
306        texture->blend = true;
307        break;
308    case kRGB_565_SkColorType:
309        glPixelStorei(GL_UNPACK_ALIGNMENT, bitmap->bytesPerPixel());
310        uploadToTexture(resize, GL_RGB, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
311                texture->width, texture->height, GL_UNSIGNED_SHORT_5_6_5, bitmap->getPixels());
312        texture->blend = false;
313        break;
314    case kN32_SkColorType:
315        glPixelStorei(GL_UNPACK_ALIGNMENT, bitmap->bytesPerPixel());
316        uploadToTexture(resize, GL_RGBA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(),
317                texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels());
318        // Do this after calling getPixels() to make sure Skia's deferred
319        // decoding happened
320        texture->blend = !bitmap->isOpaque();
321        break;
322    case kARGB_4444_SkColorType:
323    case kIndex_8_SkColorType:
324        glPixelStorei(GL_UNPACK_ALIGNMENT, bitmap->bytesPerPixel());
325        uploadLoFiTexture(resize, bitmap, texture->width, texture->height);
326        texture->blend = !bitmap->isOpaque();
327        break;
328    default:
329        ALOGW("Unsupported bitmap colorType: %d", bitmap->colorType());
330        break;
331    }
332
333    if (canMipMap) {
334        texture->mipMap = bitmap->hasHardwareMipMap();
335        if (texture->mipMap) {
336            glGenerateMipmap(GL_TEXTURE_2D);
337        }
338    }
339
340    if (!regenerate) {
341        texture->setFilter(GL_NEAREST);
342        texture->setWrap(GL_CLAMP_TO_EDGE);
343    }
344}
345
346void TextureCache::uploadLoFiTexture(bool resize, const SkBitmap* bitmap,
347        uint32_t width, uint32_t height) {
348    SkBitmap rgbaBitmap;
349    rgbaBitmap.allocPixels(SkImageInfo::MakeN32(width, height, bitmap->alphaType()));
350    rgbaBitmap.eraseColor(0);
351
352    SkCanvas canvas(rgbaBitmap);
353    canvas.drawBitmap(*bitmap, 0.0f, 0.0f, nullptr);
354
355    uploadToTexture(resize, GL_RGBA, rgbaBitmap.rowBytesAsPixels(), rgbaBitmap.bytesPerPixel(),
356            width, height, GL_UNSIGNED_BYTE, rgbaBitmap.getPixels());
357}
358
359void TextureCache::uploadToTexture(bool resize, GLenum format, GLsizei stride, GLsizei bpp,
360        GLsizei width, GLsizei height, GLenum type, const GLvoid * data) {
361    const bool useStride = stride != width && Extensions::getInstance().hasUnpackRowLength();
362    if ((stride == width) || useStride) {
363        if (useStride) {
364            glPixelStorei(GL_UNPACK_ROW_LENGTH, stride);
365        }
366
367        if (resize) {
368            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, data);
369        } else {
370            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data);
371        }
372
373        if (useStride) {
374            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
375        }
376    } else {
377        //  With OpenGL ES 2.0 we need to copy the bitmap in a temporary buffer
378        //  if the stride doesn't match the width
379
380        GLvoid * temp = (GLvoid *) malloc(width * height * bpp);
381        if (!temp) return;
382
383        uint8_t * pDst = (uint8_t *)temp;
384        uint8_t * pSrc = (uint8_t *)data;
385        for (GLsizei i = 0; i < height; i++) {
386            memcpy(pDst, pSrc, width * bpp);
387            pDst += width * bpp;
388            pSrc += stride * bpp;
389        }
390
391        if (resize) {
392            glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, temp);
393        } else {
394            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, temp);
395        }
396
397        free(temp);
398    }
399}
400
401}; // namespace uirenderer
402}; // namespace android
403