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