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