在高性能場景 (相機預覽、視頻編解碼、音頻處理、圖像算法、文件傳輸) 中,Java 層與 Native 層 (C/C++) 之間的數據拷貝是主要性能瓶頸。java.nio.ByteBuffer (特別是直接緩衝區 Direct ByteBuffer) 配合 JNI GetDirectBufferAddress / NewDirectByteBuffer,實現零拷貝共享內存,是 Android 高性能開發的核心技能。本文系統講解 ByteBuffer 原理、JNI 交互 API、實戰封裝與避坑指南。
| 屬性 | 含義 | 關鍵點 |
|---|---|---|
| capacity | 容量 (不可變) | 分配時確定,buffer.capacity() |
| position | 下一個讀/寫位置 | 初始 0,put/get 後自動增加 |
| limit | 第一個不應讀/寫的位置 | 寫模式下 = capacity;flip() 後 = 已寫數據長度 |
| mark | 標記位置 | mark() 記錄,reset() 恢復 |
ByteBuffer.allocate(capacity),數據在 Java 堆,JNI 訪問需拷貝 (GetByteArrayElements)ByteBuffer.allocateDirect(capacity),數據在 Native 堆 (malloc),JNI 可直接訪問指針,零拷貝// jni.h 定義
// 1. 從 Native 指針創建 Direct ByteBuffer 返回 Java
jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity);
// address: Native 內存地址 (malloc/new/mmap 獲得)
// capacity: 容量 (bytes)
// 返回: java.nio.ByteBuffer 對象,或 NULL (OOM/不支持)
// 2. 獲取 Direct ByteBuffer 的 Native 起始地址
void* GetDirectBufferAddress(JNIEnv* env, jobject buf);
// 返回: 起始地址指針,非 Direct Buffer 返回 NULL
// 3. 獲取 Direct ByteBuffer 容量
jlong GetDirectBufferCapacity(JNIEnv* env, jobject buf);
// 返回: 容量 (bytes),非 Direct Buffer 返回 -1
public class FrameProcessor {
static { System.loadLibrary("frame_processor"); }
// Native 方法簽名:接收 Direct ByteBuffer,返回處理後的 Direct ByteBuffer
public native ByteBuffer processFrame(ByteBuffer inputFrame, int width, int height, int format);
// 或 void 返回,直接修改輸入 Buffer (in-place)
public native void processFrameInPlace(ByteBuffer frame, int width, int height, int format);
// 工具:從 YUV_420_888 Image 創建 Direct ByteBuffer (API 26+ Image.getPlanes())
public static ByteBuffer createDirectBufferFromImage(Image image) {
// 僅取 Y 平面示例
Image.Plane yPlane = image.getPlanes()[0];
ByteBuffer buffer = yPlane.getBuffer(); // 已經是 Direct ByteBuffer!
// 注意:buffer.position/limit 需正確設置
return buffer;
}
}
#include
#include
#define TAG "FrameProcessor"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
extern "C" JNIEXPORT jobject JNICALL
Java_com_example_FrameProcessor_processFrame(
JNIEnv* env, jobject thiz,
jobject inputBuffer, jint width, jint height, jint format) {
// 1. 獲取輸入 Direct Buffer 地址
void* inputPtr = env->GetDirectBufferAddress(inputBuffer);
if (!inputPtr) {
LOGD("Input is not a Direct ByteBuffer!");
return nullptr;
}
jlong inputCapacity = env->GetDirectBufferCapacity(inputBuffer);
// 2. 分配輸出 Direct Buffer (Native 內存)
size_t outSize = width * height * 3 / 2; // YUV420SP 大小估算
void* outPtr = malloc(outSize);
if (!outPtr) {
LOGD("Native malloc failed!");
return nullptr;
}
// 3. Native 處理邏輯 (此處為示例:YUV420P -> NV21 格式轉換)
// 實際場景:OpenCV 處理、FFmpeg 編碼、自定義濾鏡、人臉檢測...
processYuvInNative(static_cast(inputPtr), static_cast(outPtr), width, height);
// 4. 將 Native 內存包裝為 Direct ByteBuffer 返回 Java
jobject outputBuffer = env->NewDirectByteBuffer(outPtr, outSize);
if (!outputBuffer) {
free(outPtr); // 創建失敗需手動釋放
return nullptr;
}
// 關鍵:Java 端無法自動釋放 Native 內存!
// 必須提供 release 方法,或使用 Cleaner/PhantomReference 註冊釋放回調
return outputBuffer;
}
// In-place 修改版本 (更常用,避免雙倍內存)
extern "C" JNIEXPORT void JNICALL
Java_com_example_FrameProcessor_processFrameInPlace(
JNIEnv* env, jobject thiz,
jobject buffer, jint width, jint height, jint format) {
void* ptr = env->GetDirectBufferAddress(buffer);
if (!ptr) return;
// 直接修改 buffer 內容
processYuvInPlace(static_cast(ptr), width, height);
}
// Native 內存釋放輔助 (Java 調用)
extern "C" JNIEXPORT void JNICALL
Java_com_example_FrameProcessor_releaseNativeBuffer(
JNIEnv* env, jobject thiz, jobject buffer) {
void* ptr = env->GetDirectBufferAddress(buffer);
if (ptr) free(ptr);
}
public class NativeBufferManager {
// 方案 1: 顯式釋放 (最可控)
public static void release(ByteBuffer buffer) {
if (buffer != null && buffer.isDirect()) {
FrameProcessor.releaseNativeBuffer(buffer);
}
}
// 方案 2: Cleaner 機制 (Java 9+ / API 26+)
// 自動在 GC 時釋放,但時機不可控
public static void registerCleaner(ByteBuffer buffer, Runnable releaseAction) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Cleaner.create(buffer, releaseAction); // 需要 Java 9 API
}
}
// 方案 3: PhantomReference + ReferenceQueue (通用、可靠)
private static final ReferenceQueue REF_QUEUE = new ReferenceQueue<>();
private static final Set> REFERENCES = ConcurrentHashMap.newKeySet();
private static final Thread CLEANER_THREAD = new Thread(() -> {
while (true) {
try {
PhantomReference ref = (PhantomReference) REF_QUEUE.remove();
REFERENCES.remove(ref);
// 此處無法直接獲取 buffer,需在創建時綁定 Native 指針
// 建議維護 Map nativePtrMap
} catch (InterruptedException ignored) {}
}
}, "NativeBufferCleaner");
static { CLEANER_THREAD.setDaemon(true); CLEANER_THREAD.start(); }
}
// byte[] -> Direct ByteBuffer (拷貝)
ByteBuffer directBuf = ByteBuffer.allocateDirect(bytes.length);
directBuf.put(bytes);
directBuf.flip(); // 讀模式
// Direct ByteBuffer -> byte[] (拷貝)
byte[] bytes = new byte[directBuf.remaining()];
directBuf.get(bytes); // 從 position 讀取
// 或
byte[] bytes = new byte[directBuf.capacity()];
directBuf.duplicate().get(bytes); // 不改變 position
// Heap ByteBuffer (wrap) 零拷貝包裝 byte[]
ByteBuffer heapBuf = ByteBuffer.wrap(bytes); // 修改 heapBuf 直接影響 bytes
// 注意:wrap 不支持 allocateDirect 類型操作
GetByteArrayElements 會拷貝/釘住內存,極大增加延遲| 問題 | 原因 | 解決 |
|---|---|---|
| GetDirectBufferAddress 返回 NULL | 傳入的是 Heap ByteBuffer (allocate/wrap) | 強制使用 allocateDirect、Image.Plane.getBuffer()、FileChannel.map() |
| Native 內存洩漏 (OOM: native) | Java GC 不管理 Native 內存,無 release 調用 | 顯式 release、Cleaner、PhantomReference、內存池統一管理 |
| 數據競爭/撕裂 | Java 線程讀、Native 線程寫同一 Buffer 無同步 | 雙緩衝/環形隊列、fence 同步、Vulkan/EGL 同步對象 |
| Buffer 容量不足 | Native 寫入超過 capacity | 預分配足夠大小、動態擴容策略 (reallocate + copy) |
| 直接緩衝區分配失敗 | Native 內存碎片/耗盡 (不受 Java Heap 限制) | 監控 Debug.getNativeHeapAllocatedSize()、內存池、減少峰值併發 |
// 進程間共享內存 (零拷貝跨進程)
MemoryFile memoryFile = new MemoryFile("shared_buffer", size);
FileDescriptor fd = memoryFile.getFileDescriptor();
// Native: mmap(fd) 獲取指針
// Java: memoryFile.getInputStream()/getOutputStream()
// 適用於:相機服務 → 應用進程、編碼服務 → 應用進程
ByteBuffer + JNI 零拷貝是 Android 高性能多媒體、計算機視覺、實時音視頻的基石。深度理解其內存模型、生命週期管理、線程同步機制,構建健壯的 Native 內存管理體系,是資深 Android 工程師的核心競爭力之一。