TextureCache.cpp revision 011550e1f2f20e66c429c2d854dcaf18c1f6c30c
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() { 123 LruCache<uint32_t, Texture*>::Iterator iter(mCache); 124 while (iter.next()) { 125 iter.value()->isInUse = false; 126 } 127} 128 129bool TextureCache::canMakeTextureFromBitmap(const SkBitmap* bitmap) { 130 if (bitmap->width() > mMaxTextureSize || bitmap->height() > mMaxTextureSize) { 131 ALOGW("Bitmap too large to be uploaded into a texture (%dx%d, max=%dx%d)", 132 bitmap->width(), bitmap->height(), mMaxTextureSize, mMaxTextureSize); 133 return false; 134 } 135 return true; 136} 137 138// Returns a prepared Texture* that either is already in the cache or can fit 139// in the cache (and is thus added to the cache) 140Texture* TextureCache::getCachedTexture(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) { 141 if (CC_LIKELY(mAssetAtlas != nullptr) && atlasUsageType == AtlasUsageType::Use) { 142 AssetAtlas::Entry* entry = mAssetAtlas->getEntry(bitmap); 143 if (CC_UNLIKELY(entry)) { 144 return entry->texture; 145 } 146 } 147 148 Texture* texture = mCache.get(bitmap->pixelRef()->getStableID()); 149 150 if (!texture) { 151 if (!canMakeTextureFromBitmap(bitmap)) { 152 return nullptr; 153 } 154 155 const uint32_t size = bitmap->rowBytes() * bitmap->height(); 156 bool canCache = size < mMaxSize; 157 // Don't even try to cache a bitmap that's bigger than the cache 158 while (canCache && mSize + size > mMaxSize) { 159 Texture* oldest = mCache.peekOldestValue(); 160 if (oldest && !oldest->isInUse) { 161 mCache.removeOldest(); 162 } else { 163 canCache = false; 164 } 165 } 166 167 if (canCache) { 168 texture = new Texture(Caches::getInstance()); 169 texture->bitmapSize = size; 170 generateTexture(bitmap, texture, false); 171 172 mSize += size; 173 TEXTURE_LOGD("TextureCache::get: create texture(%p): name, size, mSize = %d, %d, %d", 174 bitmap, texture->id, size, mSize); 175 if (mDebugEnabled) { 176 ALOGD("Texture created, size = %d", size); 177 } 178 mCache.put(bitmap->pixelRef()->getStableID(), texture); 179 } 180 } else if (!texture->isInUse && bitmap->getGenerationID() != texture->generation) { 181 // Texture was in the cache but is dirty, re-upload 182 // TODO: Re-adjust the cache size if the bitmap's dimensions have changed 183 generateTexture(bitmap, texture, true); 184 } 185 186 return texture; 187} 188 189bool TextureCache::prefetchAndMarkInUse(const SkBitmap* bitmap) { 190 Texture* texture = getCachedTexture(bitmap, AtlasUsageType::Use); 191 if (texture) { 192 texture->isInUse = true; 193 } 194 return texture; 195} 196 197Texture* TextureCache::get(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) { 198 Texture* texture = getCachedTexture(bitmap, atlasUsageType); 199 200 if (!texture) { 201 if (!canMakeTextureFromBitmap(bitmap)) { 202 return nullptr; 203 } 204 205 const uint32_t size = bitmap->rowBytes() * bitmap->height(); 206 texture = new Texture(Caches::getInstance()); 207 texture->bitmapSize = size; 208 generateTexture(bitmap, texture, false); 209 texture->cleanup = true; 210 } 211 212 return texture; 213} 214 215void TextureCache::releaseTexture(uint32_t pixelRefStableID) { 216 Mutex::Autolock _l(mLock); 217 mGarbage.push(pixelRefStableID); 218} 219 220void TextureCache::clearGarbage() { 221 Mutex::Autolock _l(mLock); 222 size_t count = mGarbage.size(); 223 for (size_t i = 0; i < count; i++) { 224 uint32_t pixelRefId = mGarbage.itemAt(i); 225 mCache.remove(pixelRefId); 226 } 227 mGarbage.clear(); 228} 229 230void TextureCache::clear() { 231 mCache.clear(); 232 TEXTURE_LOGD("TextureCache:clear(), mSize = %d", mSize); 233} 234 235void TextureCache::flush() { 236 if (mFlushRate >= 1.0f || mCache.size() == 0) return; 237 if (mFlushRate <= 0.0f) { 238 clear(); 239 return; 240 } 241 242 uint32_t targetSize = uint32_t(mSize * mFlushRate); 243 TEXTURE_LOGD("TextureCache::flush: target size: %d", targetSize); 244 245 while (mSize > targetSize) { 246 mCache.removeOldest(); 247 } 248} 249 250void TextureCache::generateTexture(const SkBitmap* bitmap, Texture* texture, bool regenerate) { 251 SkAutoLockPixels alp(*bitmap); 252 253 if (!bitmap->readyToDraw()) { 254 ALOGE("Cannot generate texture from bitmap"); 255 return; 256 } 257 258 ATRACE_FORMAT("Upload %ux%u Texture", bitmap->width(), bitmap->height()); 259 260 // We could also enable mipmapping if both bitmap dimensions are powers 261 // of 2 but we'd have to deal with size changes. Let's keep this simple 262 const bool canMipMap = Caches::getInstance().extensions().hasNPot(); 263 264 // If the texture had mipmap enabled but not anymore, 265 // force a glTexImage2D to discard the mipmap levels 266 const bool resize = !regenerate || bitmap->width() != int(texture->width) || 267 bitmap->height() != int(texture->height) || 268 (regenerate && canMipMap && texture->mipMap && !bitmap->hasHardwareMipMap()); 269 270 if (!regenerate) { 271 glGenTextures(1, &texture->id); 272 } 273 274 texture->generation = bitmap->getGenerationID(); 275 texture->width = bitmap->width(); 276 texture->height = bitmap->height(); 277 278 Caches::getInstance().textureState().bindTexture(texture->id); 279 280 switch (bitmap->colorType()) { 281 case kAlpha_8_SkColorType: 282 uploadToTexture(resize, GL_ALPHA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(), 283 texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels()); 284 texture->blend = true; 285 break; 286 case kRGB_565_SkColorType: 287 uploadToTexture(resize, GL_RGB, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(), 288 texture->width, texture->height, GL_UNSIGNED_SHORT_5_6_5, bitmap->getPixels()); 289 texture->blend = false; 290 break; 291 case kN32_SkColorType: 292 uploadToTexture(resize, GL_RGBA, bitmap->rowBytesAsPixels(), bitmap->bytesPerPixel(), 293 texture->width, texture->height, GL_UNSIGNED_BYTE, bitmap->getPixels()); 294 // Do this after calling getPixels() to make sure Skia's deferred 295 // decoding happened 296 texture->blend = !bitmap->isOpaque(); 297 break; 298 case kARGB_4444_SkColorType: 299 case kIndex_8_SkColorType: 300 uploadLoFiTexture(resize, bitmap, texture->width, texture->height); 301 texture->blend = !bitmap->isOpaque(); 302 break; 303 default: 304 ALOGW("Unsupported bitmap colorType: %d", bitmap->colorType()); 305 break; 306 } 307 308 if (canMipMap) { 309 texture->mipMap = bitmap->hasHardwareMipMap(); 310 if (texture->mipMap) { 311 glGenerateMipmap(GL_TEXTURE_2D); 312 } 313 } 314 315 if (!regenerate) { 316 texture->setFilter(GL_NEAREST); 317 texture->setWrap(GL_CLAMP_TO_EDGE); 318 } 319} 320 321void TextureCache::uploadLoFiTexture(bool resize, const SkBitmap* bitmap, 322 uint32_t width, uint32_t height) { 323 SkBitmap rgbaBitmap; 324 rgbaBitmap.allocPixels(SkImageInfo::MakeN32(width, height, bitmap->alphaType())); 325 rgbaBitmap.eraseColor(0); 326 327 SkCanvas canvas(rgbaBitmap); 328 canvas.drawBitmap(*bitmap, 0.0f, 0.0f, nullptr); 329 330 uploadToTexture(resize, GL_RGBA, rgbaBitmap.rowBytesAsPixels(), rgbaBitmap.bytesPerPixel(), 331 width, height, GL_UNSIGNED_BYTE, rgbaBitmap.getPixels()); 332} 333 334void TextureCache::uploadToTexture(bool resize, GLenum format, GLsizei stride, GLsizei bpp, 335 GLsizei width, GLsizei height, GLenum type, const GLvoid * data) { 336 glPixelStorei(GL_UNPACK_ALIGNMENT, bpp); 337 const bool useStride = stride != width 338 && Caches::getInstance().extensions().hasUnpackRowLength(); 339 if ((stride == width) || useStride) { 340 if (useStride) { 341 glPixelStorei(GL_UNPACK_ROW_LENGTH, stride); 342 } 343 344 if (resize) { 345 glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, data); 346 } else { 347 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data); 348 } 349 350 if (useStride) { 351 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); 352 } 353 } else { 354 // With OpenGL ES 2.0 we need to copy the bitmap in a temporary buffer 355 // if the stride doesn't match the width 356 357 GLvoid * temp = (GLvoid *) malloc(width * height * bpp); 358 if (!temp) return; 359 360 uint8_t * pDst = (uint8_t *)temp; 361 uint8_t * pSrc = (uint8_t *)data; 362 for (GLsizei i = 0; i < height; i++) { 363 memcpy(pDst, pSrc, width * bpp); 364 pDst += width * bpp; 365 pSrc += stride * bpp; 366 } 367 368 if (resize) { 369 glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, type, temp); 370 } else { 371 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, temp); 372 } 373 374 free(temp); 375 } 376} 377 378}; // namespace uirenderer 379}; // namespace android 380