演变:

关于Bitmap内存分配的变化

On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. As of Android 3.0 (API level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap.

  • Android 3.0之前 Bitmap对象存在Java堆 像素数据存在Native内存中
    不手动调用recycle Bitmap Native内存的回收完全依赖finalize 时机不太可控

  • Android 3.0~Android 7.0 Bitmap对象和像素数据统一放到Java堆中 不调用recycle Bitmap内存也会是随对象一起被回收
    不过Bitmap消耗内存太大 还是不合适

  • Android 8.0 利用NativeAllocationRegistry实现像素数据存放到Native中 并且新增了硬件位图 Hardware Bitmap 可以减少图片内存并且提升绘制效率
    NativeAllocationRegistry:
    一种实现 可以将 Bitmap内存放到 Native中 也可以做到和对象一起快速释放 同时GC的时候也能考虑到这些内存防止被滥用

位图在Android中的存储策略被划分为了两个部分,一个是基本信息相关的数据结构,存放在Dalvik heap中,而像素相关的数据结构则存放在另外一个内存空间,而Android版本演变改变的,则是这个内存空间的位置,在native层中同样会有一个位图的数据结构SkBitmap(是不是瞬间想到了Android使用的图形渲染引擎Skia),同义于java层的Bitmap:

我们现在直接分析Android O以后的Bitmap存储策略:

首先我们需要在Java层创建一个Bitmap,Bitmap.createBitmap(),最终所有的重载方法都会走向下面的JNI调用:

  1. public static Bitmap createBitmap(@Nullable DisplayMetrics display, int width, int height,
  2. @NonNull Config config, boolean hasAlpha, @NonNull ColorSpace colorSpace) {
  3. if (width <= 0 || height <= 0) {
  4. throw new IllegalArgumentException("width and height must be > 0");
  5. }
  6. if (config == Config.HARDWARE) {
  7. throw new IllegalArgumentException("can't create mutable bitmap with Config.HARDWARE");
  8. }
  9. if (colorSpace == null) {
  10. throw new IllegalArgumentException("can't create bitmap without a color space");
  11. }
  12. Bitmap bm;
  13. // nullptr color spaces have a particular meaning in native and are interpreted as sRGB
  14. // (we also avoid the unnecessary extra work of the else branch)
  15. if (config != Config.ARGB_8888 || colorSpace == ColorSpace.get(ColorSpace.Named.SRGB)) {
  16. bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true, null, null);
  17. } else {
  18. if (!(colorSpace instanceof ColorSpace.Rgb)) {
  19. throw new IllegalArgumentException("colorSpace must be an RGB color space");
  20. }
  21. ColorSpace.Rgb rgb = (ColorSpace.Rgb) colorSpace;
  22. ColorSpace.Rgb.TransferParameters parameters = rgb.getTransferParameters();
  23. if (parameters == null) {
  24. throw new IllegalArgumentException("colorSpace must use an ICC "
  25. + "parametric transfer function");
  26. }
  27. ColorSpace.Rgb d50 = (ColorSpace.Rgb) ColorSpace.adapt(rgb, ColorSpace.ILLUMINANT_D50);
  28. bm = nativeCreate(null, 0, width, width, height, config.nativeInt, true,
  29. d50.getTransform(), parameters);
  30. }
  31. if (display != null) {
  32. bm.mDensity = display.densityDpi;
  33. }
  34. bm.setHasAlpha(hasAlpha);
  35. if ((config == Config.ARGB_8888 || config == Config.RGBA_F16) && !hasAlpha) {
  36. nativeErase(bm.mNativePtr, 0xff000000);
  37. }
  38. // No need to initialize the bitmap to zeroes with other configs;
  39. // it is backed by a VM byte array which is by definition preinitialized
  40. // to all zeroes.
  41. return bm;
  42. }

最终会走到JNI的nativeCreate()方法,无论是Android O以前还是以后,其实在java层的代码都没有变化,那么改变一定就出现在了native层的调用上:

  1. private static native Bitmap nativeCreate(int[] colors, int offset,
  2. int stride, int width, int height,
  3. int nativeConfig, boolean mutable,
  4. @Nullable @Size(9) float[] xyzD50,
  5. @Nullable ColorSpace.Rgb.TransferParameters p);

那么大家是不是很好奇在native层是怎么处理Bitmap的?
关于Android版本更新引发的Bitmap回收血案 - 图1

这里的nativeCreate()指向了方法Bitmap_creator,我们继续往下看这个方法:

Android O版本以下的native调用:

xref: /frameworks/base/core/jni/android/graphics/Bitmap.cpp

  1. static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
  2. 706 jint offset, jint stride, jint width, jint height,
  3. 707 jint configHandle, jboolean isMutable) {
  4. 708 SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
  5. 709 if (NULL != jColors) {
  6. 710 size_t n = env->GetArrayLength(jColors);
  7. 711 if (n < SkAbs32(stride) * (size_t)height) {
  8. 712 doThrowAIOOBE(env);
  9. 713 return NULL;
  10. 714 }
  11. 715 }
  12. 716
  13. 717 // ARGB_4444 is a deprecated format, convert automatically to 8888
  14. 718 if (colorType == kARGB_4444_SkColorType) {
  15. 719 colorType = kN32_SkColorType;
  16. 720 }
  17. 721
  18. 722 SkBitmap bitmap;
  19. 723 bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType));
  20. 724
  21. 725 Bitmap* nativeBitmap = GraphicsJNI::allocateJavaPixelRef(env, &bitmap, NULL);
  22. 726 if (!nativeBitmap) {
  23. 727 return NULL;
  24. 728 }
  25. 729
  26. 730 if (jColors != NULL) {
  27. 731 GraphicsJNI::SetPixels(env, jColors, offset, stride,
  28. 732 0, 0, width, height, bitmap);
  29. 733 }
  30. 734
  31. 735 return GraphicsJNI::createBitmap(env, nativeBitmap,
  32. 736 getPremulBitmapCreateFlags(isMutable));
  33. 737}

大家注意到nativeBitmap的创建方式是利用GraphicsJNI::allocateJavaPixelRef(env, &bitmap, NULL)来进行构建,最后返回给上层的位图也是以nativeBitmap为基准来调用GraphicsJNI图像渲染引擎接口进行图片绘制,很显然,我们需要知道在allocateJavaPixelRef中,接下来我们点进去看一看:
xref: /frameworks/base/core/jni/android/graphics/Graphics.cpp

  1. 486 android::Bitmap* GraphicsJNI::allocateJavaPixelRef(JNIEnv* env, SkBitmap* bitmap,
  2. 487 SkColorTable* ctable) {
  3. 488 const SkImageInfo& info = bitmap->info();
  4. 489 if (info.colorType() == kUnknown_SkColorType) {
  5. 490 doThrowIAE(env, "unknown bitmap configuration");
  6. 491 return NULL;
  7. 492 }
  8. 493
  9. 494 size_t size;
  10. 495 if (!computeAllocationSize(*bitmap, &size)) {
  11. 496 return NULL;
  12. 497 }
  13. 498
  14. 499 // we must respect the rowBytes value already set on the bitmap instead of
  15. 500 // attempting to compute our own.
  16. 501 const size_t rowBytes = bitmap->rowBytes();
  17. 502
  18. 503 jbyteArray arrayObj = (jbyteArray) env->CallObjectMethod(gVMRuntime,
  19. 504 gVMRuntime_newNonMovableArray,
  20. 505 gByte_class, size);
  21. 506 if (env->ExceptionCheck() != 0) {
  22. 507 return NULL;
  23. 508 }
  24. 509 SkASSERT(arrayObj);
  25. 510 jbyte* addr = (jbyte*) env->CallLongMethod(gVMRuntime, gVMRuntime_addressOf, arrayObj);
  26. 511 if (env->ExceptionCheck() != 0) {
  27. 512 return NULL;
  28. 513 }
  29. 514 SkASSERT(addr);
  30. 515 android::Bitmap* wrapper = new android::Bitmap(env, arrayObj, (void*) addr,
  31. 516 info, rowBytes, ctable);
  32. 517 wrapper->getSkBitmap(bitmap);
  33. 518 // since we're already allocated, we lockPixels right away
  34. 519 // HeapAllocator behaves this way too
  35. 520 bitmap->lockPixels();
  36. 521
  37. 522 return wrapper;
  38. 523}

wrapper顾名思义,就是返回的一个位图包装,它通过JNI创建并弱引用jweakRef了一个java层的位图对象,并且申明了一个nullPtr(空)的强引用jstrongRef,Bitmap``::Bitmap对应代码如下:
xref: /frameworks/base/core/jni/android/graphics/Bitmap.cpp

  1. Bitmap::Bitmap(JNIEnv* env, jbyteArray storageObj, void* address,
  2. const SkImageInfo& info, size_t rowBytes, SkColorTable* ctable)
  3. : mPixelStorageType(PixelStorageType::Java) {
  4. env->GetJavaVM(&mPixelStorage.java.jvm);
  5. mPixelStorage.java.jweakRef = env->NewWeakGlobalRef(storageObj);//创建对Java层对象的弱引用
  6. mPixelStorage.java.jstrongRef = nullptr;
  7. mPixelRef.reset(new WrappedPixelRef(this, address, info, rowBytes, ctable));
  8. // Note: this will trigger a call to onStrongRefDestroyed(), but
  9. // we want the pixel ref to have a ref count of 0 at this point
  10. mPixelRef->unref();
  11. }

利用wrapper->getSkBitmap(bitmap)来进行强引用和弱引用的控制切换:
xref: /frameworks/base/core/jni/android/graphics/Bitmap.cpp

  1. 353void Bitmap::getSkBitmap(SkBitmap* outBitmap) {
  2. 354 assertValid();
  3. 355 android::AutoMutex _lock(mLock);
  4. 356 // Safe because mPixelRef is a WrappedPixelRef type, otherwise rowBytes()
  5. 357 // would require locking the pixels first.
  6. 358 outBitmap->setInfo(mPixelRef->info(), mPixelRef->rowBytes());
  7. 359 outBitmap->setPixelRef(refPixelRefLocked())->unref();
  8. 360 outBitmap->setHasHardwareMipMap(hasHardwareMipMap());
  9. 361}
  10. 240 SkPixelRef* Bitmap::refPixelRefLocked() {
  11. 241 mPixelRef->ref();
  12. 242 if (mPixelRef->unique()) {
  13. 243 // We just restored this from 0, pin the pixels and inc the strong count
  14. 244 // Note that there *might be* an incoming onStrongRefDestroyed from whatever
  15. 245 // last unref'd
  16. 246 pinPixelsLocked();
  17. 247 mPinnedRefCount++;
  18. 248 }
  19. 249 return mPixelRef.get();
  20. 250}
  21. !!!在refPixelRefLocked中会调用pinPixelsLocked
  22. 310 void Bitmap::pinPixelsLocked() {
  23. 311 switch (mPixelStorageType) {
  24. 312 case PixelStorageType::Invalid:
  25. 313 LOG_ALWAYS_FATAL("Cannot pin invalid pixels!");
  26. 314 break;
  27. 315 case PixelStorageType::External:
  28. 316 case PixelStorageType::Ashmem:
  29. 317 // Nothing to do
  30. 318 break;
  31. 319 case PixelStorageType::Java: {
  32. 320 JNIEnv* env = jniEnv();
  33. 321 if (!mPixelStorage.java.jstrongRef) {
  34. 322 mPixelStorage.java.jstrongRef = reinterpret_cast<jbyteArray>(
  35. 323 env->NewGlobalRef(mPixelStorage.java.jweakRef));
  36. 324 if (!mPixelStorage.java.jstrongRef) {
  37. 325 LOG_ALWAYS_FATAL("Failed to acquire strong reference to pixels");
  38. 326 }
  39. 327 }
  40. 328 break;
  41. 329 }
  42. 330 }
  43. 331}

在native层随时添加删除一个强引用,这样有利于更好地配合Java堆的垃圾回收。
最后调用:

  1. GraphicsJNI::createBitmap(env, nativeBitmap,getPremulBitmapCreateFlags(isMutable));

来返回一个位图。

Android O版本以上的native调用:

首先同样看一看在native层的Bitmap_creator是如何在底层构建一个Bitmap:

  1. 652 static jobject Bitmap_creator(JNIEnv* env, jobject, jintArray jColors,
  2. 653 jint offset, jint stride, jint width, jint height,
  3. 654 jint configHandle, jboolean isMutable,
  4. 655 jfloatArray xyzD50, jobject transferParameters) {
  5. 656 SkColorType colorType = GraphicsJNI::legacyBitmapConfigToColorType(configHandle);
  6. 657 if (NULL != jColors) {
  7. 658 size_t n = env->GetArrayLength(jColors);
  8. 659 if (n < SkAbs32(stride) * (size_t)height) {
  9. 660 doThrowAIOOBE(env);
  10. 661 return NULL;
  11. 662 }
  12. 663 }
  13. 664
  14. 665 // ARGB_4444 is a deprecated format, convert automatically to 8888
  15. 666 if (colorType == kARGB_4444_SkColorType) {
  16. 667 colorType = kN32_SkColorType;
  17. 668 }
  18. 669
  19. 670 SkBitmap bitmap;
  20. 671 sk_sp<SkColorSpace> colorSpace;
  21. 672
  22. 673 if (colorType != kN32_SkColorType || xyzD50 == nullptr || transferParameters == nullptr) {
  23. 674 colorSpace = GraphicsJNI::colorSpaceForType(colorType);
  24. 675 } else {
  25. 676 SkColorSpaceTransferFn p = GraphicsJNI::getNativeTransferParameters(env, transferParameters);
  26. 677 SkMatrix44 xyzMatrix = GraphicsJNI::getNativeXYZMatrix(env, xyzD50);
  27. 678 colorSpace = SkColorSpace::MakeRGB(p, xyzMatrix);
  28. 679 }
  29. 680
  30. 681 bitmap.setInfo(SkImageInfo::Make(width, height, colorType, kPremul_SkAlphaType, colorSpace));
  31. 682
  32. 683 sk_sp<Bitmap> nativeBitmap = Bitmap::allocateHeapBitmap(&bitmap);
  33. 684 if (!nativeBitmap) {
  34. 685 ALOGE("OOM allocating Bitmap with dimensions %i x %i", width, height);
  35. 686 doThrowOOME(env);
  36. 687 return NULL;
  37. 688 }
  38. 689
  39. 690 if (jColors != NULL) {
  40. 691 GraphicsJNI::SetPixels(env, jColors, offset, stride, 0, 0, width, height, bitmap);
  41. 692 }
  42. 693
  43. 694 return createBitmap(env, nativeBitmap.release(), getPremulBitmapCreateFlags(isMutable));
  44. 695}

咋眼一看,和Android O以下的构建方式大同小异,但是眼尖的同学可能已经发现了最主要的区别,那就是nativeBitmap的构建方式发生了变化Bitmap::allocateHeapBitmap(&bitmap),让我们点进去一探究竟:

  1. 91sk_sp<Bitmap> Bitmap::allocateHeapBitmap(SkBitmap* bitmap) {
  2. 92 return allocateBitmap(bitmap, &android::allocateHeapBitmap);
  3. 93}

我们继续点进allocateBitmap(bitmap, &android::allocateHeapBitmap)

  1. 50 typedef sk_sp<Bitmap> (*AllocPixelRef)(size_t allocSize, const SkImageInfo& info, size_t rowBytes);
  2. 52 static sk_sp<Bitmap> allocateBitmap(SkBitmap* bitmap, AllocPixelRef alloc) {
  3. 53 const SkImageInfo& info = bitmap->info();
  4. 54 if (info.colorType() == kUnknown_SkColorType) {
  5. 55 LOG_ALWAYS_FATAL("unknown bitmap configuration");
  6. 56 return nullptr;
  7. 57 }
  8. 58
  9. 59 size_t size;
  10. 60
  11. 61 // we must respect the rowBytes value already set on the bitmap instead of
  12. 62 // attempting to compute our own.
  13. 63 const size_t rowBytes = bitmap->rowBytes();
  14. 64 if (!computeAllocationSize(rowBytes, bitmap->height(), &size)) {
  15. 65 return nullptr;
  16. 66 }
  17. 67
  18. 68 auto wrapper = alloc(size, info, rowBytes);
  19. 69 if (wrapper) {
  20. 70 wrapper->getSkBitmap(bitmap);
  21. 71 }
  22. 72 return wrapper;
  23. 73}

注意!!!!
大家有没有发现,warpper的引用相对于Android O发生了变化,auto wrapper = alloc(size, info, rowBytes),warpper是上面typedefine的一个SkBitmap结构体,因此Android O以上和以下的版本在Bitmap的构建过程中的主要区别就在于此,当将结构体封装好数据并传递给wrapper以后,wrapper会通过wrapper->getSkBitmap(bitmap)来设置位图:

  1. 288 void Bitmap::getSkBitmap(SkBitmap* outBitmap) {
  2. 289 outBitmap->setHasHardwareMipMap(mHasHardwareMipMap);
  3. 290 if (isHardware()) {
  4. 291 if (uirenderer::Properties::isSkiaEnabled()) {
  5. 292 outBitmap->allocPixels(SkImageInfo::Make(info().width(), info().height(),
  6. 293 info().colorType(), info().alphaType(),
  7. 294 nullptr));
  8. 295 } else {
  9. 296 outBitmap->allocPixels(info());
  10. 297 }
  11. 298 uirenderer::renderthread::RenderProxy::copyGraphicBufferInto(graphicBuffer(), outBitmap);
  12. 299 if (mInfo.colorSpace()) {
  13. 300 sk_sp<SkPixelRef> pixelRef = sk_ref_sp(outBitmap->pixelRef());
  14. 301 outBitmap->setInfo(mInfo);
  15. 302 outBitmap->setPixelRef(std::move(pixelRef), 0, 0);
  16. 303 }
  17. 304 return;
  18. 305 }
  19. 306 outBitmap->setInfo(mInfo, rowBytes());
  20. 307 outBitmap->setPixelRef(sk_ref_sp(this), 0, 0);
  21. 308}

在这个方法中,就在native层分配了内存来存储像素信息以及传入了像素数组引用指针sk_ref_sp,后面就会调用

  1. 690 if (jColors != NULL) {
  2. 691 GraphicsJNI::SetPixels(env, jColors, offset, stride, 0, 0, width, height, bitmap);
  3. 692 }

去在引擎中设置像素和位图的相关信息,并返回位图给java上层。