perf: optimize memory usage in RAW processing

This commit is contained in:
zhoubinjia committed 2026-04-07 18:14:04 +08:00
1 parent ff76003166
commit 4e2f1c1eea
4 files changed
+158 -26

No files matched your search

+2 -1
View File
@@ -10,4 +10,5 @@
local.properties
app/*/release
app/release.jks
.gradle-home
.gradle-home
MGC
@@ -1488,7 +1488,7 @@ object PhotoManager {
)
var bitmap = RawDemosaicProcessor.getInstance().process(
context,
finalStackResult.stackedRgbBuffer,
finalStackResult.stackedRgbBuffer ?: return@run null,
finalWidth,
finalHeight,
finalWidth * 6, // 3 channels * 2 bytes
@@ -1500,6 +1500,9 @@ object PhotoManager {
denoiseValue = 0.2f,
chromaDenoiseValue = 0.2f
)
// GPU 已消费 stackedRgbBuffer,立即释放引用(超分时约 288 MB)
// fusedBayerBuffer 仍由 finalStackResult 持有,用于后续 DNG 保存
finalStackResult.stackedRgbBuffer = null
if (metadata.isMirrored && bitmap != null) {
bitmap = BitmapUtils.flipHorizontal(bitmap)
@@ -14,7 +14,9 @@ import java.nio.ByteOrder
import kotlin.math.roundToInt
data class RawStackResult(
val stackedRgbBuffer: ByteBuffer,
// var 以便调用方在 process() 返回后及时置 null,释放 ~288 MB(超分时),
// fusedBayerBuffer 需持续到 DNG 保存完成,stackedRgbBuffer 不需要。
var stackedRgbBuffer: ByteBuffer?,
val fusedBayerBuffer: ByteBuffer,
val width: Int,
val height: Int,
@@ -189,6 +191,9 @@ object MultiFrameStacker {
)
if (vulkanStackerPtr != 0L) {
PLog.i(TAG, "Using Vulkan RAW stacker + native LibRaw demosaic")
// 声明在 try 外层,以便 fallback 时可显式置 null 触发 GC
var vulkanFusedBayer: ByteBuffer? = null
var vulkanStacked: ByteBuffer? = null
try {
for (image in images) {
image.use {
@@ -201,7 +206,7 @@ object MultiFrameStacker {
val outWidth = (width * outputScale).roundToInt()
val outHeight = (height * outputScale).roundToInt()
val fusedBayerBuffer = try {
vulkanFusedBayer = try {
ByteBuffer.allocateDirect(outWidth * outHeight * 2)
.order(ByteOrder.nativeOrder())
} catch (e: OutOfMemoryError) {
@@ -209,7 +214,7 @@ object MultiFrameStacker {
return null
}
val stackedBuffer = try {
vulkanStacked = try {
ByteBuffer.allocateDirect(outWidth * outHeight * 6)
.order(ByteOrder.nativeOrder())
} catch (e: OutOfMemoryError) {
@@ -217,25 +222,25 @@ object MultiFrameStacker {
return null
}
val fusedOk = processVulkanRawStackNative(vulkanStackerPtr, fusedBayerBuffer)
val fusedOk = processVulkanRawStackNative(vulkanStackerPtr, vulkanFusedBayer)
if (fusedOk) {
val demosaicOk = demosaicStackedRawWithLibRawNative(
fusedBayerBuffer,
vulkanFusedBayer,
outWidth,
outHeight,
cfaPattern,
floatArrayOf(0f, 0f, 0f, 0f),
65535,
whiteBalanceGains,
stackedBuffer
vulkanStacked
)
if (demosaicOk) {
fusedBayerBuffer.rewind()
stackedBuffer.rewind()
vulkanFusedBayer.rewind()
vulkanStacked.rewind()
PLog.i(TAG, "Vulkan RAW stacking and native LibRaw demosaic completed successfully")
return RawStackResult(
stackedRgbBuffer = stackedBuffer,
fusedBayerBuffer = fusedBayerBuffer,
stackedRgbBuffer = vulkanStacked,
fusedBayerBuffer = vulkanFusedBayer,
width = outWidth,
height = outHeight,
isNormalizedSensorData = true
@@ -250,6 +255,12 @@ object MultiFrameStacker {
} finally {
releaseVulkanRawStackerNative(vulkanStackerPtr)
}
// fallback 到 CPU 路径前显式释放 Vulkan buffer 引用,避免与 CPU 路径的分配叠加
// (两者合计 outW*outH*(2+6)*2 字节,超分时可达 768 MB,极易触发 OOM)
vulkanFusedBayer = null
vulkanStacked = null
@Suppress("ExplicitGarbageCollectionCall")
System.gc()
} else {
PLog.w(TAG, "Failed to create Vulkan RAW stacker, falling back to CPU")
}
@@ -544,7 +544,14 @@ class RawDemosaicProcessor {
actualRowStride,
RawMetadata.CFA_LINEAR_RGB
)
// GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB)
actualRawData = null
renderLinearPass(actualMetadata)
// rawTextureId 已被 linearPass 消费,提前释放 GPU 显存
if (rawTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
rawTextureId = 0
}
val calcExposureGain =
analyzeFromGpuTexture(
@@ -565,6 +572,32 @@ class RawDemosaicProcessor {
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
)
// demosaicTextureId / gfChromaTexId / gfTexId[0] 已被 NLM Pass 消费,提前释放
if (demosaicTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(demosaicTextureId), 0)
demosaicTextureId = 0
}
if (demosaicFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(demosaicFramebufferId), 0)
demosaicFramebufferId = 0
}
demosaicWidth = 0; demosaicHeight = 0
if (gfChromaTexId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfChromaTexId), 0)
gfChromaTexId = 0
}
if (gfChromaFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(gfChromaFboId), 0)
gfChromaFboId = 0
}
if (gfTexId[0] != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfTexId[0]), 0)
gfTexId[0] = 0
}
if (gfFboId[0] != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(gfFboId[0]), 0)
gfFboId[0] = 0
}
val outputTexture = gfTexId[1]
@@ -582,7 +615,18 @@ class RawDemosaicProcessor {
bounds,
hdrReferenceTextureId
)
readPixels(finalWidth, finalHeight, workingColorSpace)
val hdrPixels = readPixels(finalWidth, finalHeight, workingColorSpace)
// hdrReferenceTextureId 已被 outputPass 消费
if (hdrReferenceTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(hdrReferenceTextureId), 0)
hdrReferenceTextureId = 0
}
if (hdrReferenceFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(hdrReferenceFramebufferId), 0)
hdrReferenceFramebufferId = 0
}
hdrReferenceWidth = 0; hdrReferenceHeight = 0
hdrPixels
} else {
null
}
@@ -592,12 +636,32 @@ class RawDemosaicProcessor {
val combinedStart = System.currentTimeMillis()
renderCombinedPass(actualMetadata, calcExposureGain, baseLut, logCurve, inputTextureId = outputTexture)
PLog.d(TAG, "Combined Pass took: ${System.currentTimeMillis() - combinedStart}ms")
// outputTexture (gfTexId[1]) 已被 combinedPass 消费,提前释放
if (gfTexId[1] != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfTexId[1]), 0)
gfTexId[1] = 0
}
if (gfFboId[1] != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(gfFboId[1]), 0)
gfFboId[1] = 0
}
gfWidth = 0; gfHeight = 0
// 6. 第三步:锐化 (Sharpen Pass)
setupSharpenFramebuffer(actualWidth, actualHeight)
val sharpenStart = System.currentTimeMillis()
renderSharpenPass(actualMetadata, sharpeningValue, combinedTextureId)
PLog.d(TAG, "Sharpen Pass took: ${System.currentTimeMillis() - sharpenStart}ms")
// combinedTextureId 已被 sharpenPass 消费,提前释放
if (combinedTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(combinedTextureId), 0)
combinedTextureId = 0
}
if (combinedFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(combinedFramebufferId), 0)
combinedFramebufferId = 0
}
combinedWidth = 0; combinedHeight = 0
val sourceTextureForOutput = sharpenTextureId
@@ -612,6 +676,16 @@ class RawDemosaicProcessor {
sourceTextureForOutput
)
PLog.d(TAG, "Output Pass took: ${System.currentTimeMillis() - outputStart}ms")
// sharpenTextureId 已被 outputPass 消费,在 readPixels 前释放以降低峰值内存
if (sharpenTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(sharpenTextureId), 0)
sharpenTextureId = 0
}
if (sharpenFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(sharpenFramebufferId), 0)
sharpenFramebufferId = 0
}
sharpenWidth = 0; sharpenHeight = 0
// 8. 读取结果
val readStart = System.currentTimeMillis()
@@ -1776,25 +1850,68 @@ class RawDemosaicProcessor {
if (texCoordHandle >= 0) GLES30.glDisableVertexAttribArray(texCoordHandle)
}
/**
* 从当前 outputFramebuffer 读取像素并创建 Bitmap。
*
* 优先使用 PBO(Pixel Buffer Object):像素数据存放在 GPU 内存(通过 glMapBufferRange 映射为
* native ByteBuffer),完全不占用 Java 堆,避免超分时 stackedRgbBuffer + fusedBayerBuffer +
* pixelBuffer 同时存活导致 Java 堆 OOM(512 MB 设备上三者合计可达 768 MB)。
* 若 PBO 分配或 map 失败则降级为直接分配 ByteBuffer。
*/
private fun readPixels(width: Int, height: Int, colorSpace: android.graphics.ColorSpace): Bitmap? {
val pixelSize = width * height * 8
val pixelBuffer = ByteBuffer.allocateDirect(pixelSize).order(ByteOrder.nativeOrder())
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
GLES30.glReadPixels(
0,
0,
width,
height,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
pixelBuffer
)
pixelBuffer.position(0)
checkGlError("readPixels")
// --- PBO 路径(避免 Java 堆分配)---
if (pboId == 0) {
val ids = IntArray(1)
GLES30.glGenBuffers(1, ids, 0)
pboId = ids[0]
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, pboId)
// glBufferData(null) 重新分配 GPU 缓冲区(旧数据自动孤立释放)
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, pixelSize, null, GLES30.GL_STREAM_READ)
val pboReady = GLES30.glGetError() == GLES30.GL_NO_ERROR
if (pboReady) {
// offset=0:读取写入已绑定的 PBO(GPU→GPU DMA,不阻塞 Java 堆)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, 0)
checkGlError("readPixels PBO glReadPixels")
// 映射 PBO 为 native ByteBuffer(不占用 Java 堆)
val mappedBuffer = GLES30.glMapBufferRange(
GLES30.GL_PIXEL_PACK_BUFFER, 0, pixelSize, GLES30.GL_MAP_READ_BIT
) as? ByteBuffer
if (mappedBuffer != null) {
return try {
createBitmap(width, height, Bitmap.Config.RGBA_F16, colorSpace = colorSpace).also { bmp ->
bmp.copyPixelsFromBuffer(mappedBuffer.order(ByteOrder.nativeOrder()))
}
} catch (e: OutOfMemoryError) {
PLog.e(TAG, "OOM creating output bitmap ($width x $height)", e)
null
} finally {
GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
}
}
PLog.w(TAG, "glMapBufferRange returned null, falling back to direct readPixels")
} else {
PLog.w(TAG, "PBO glBufferData failed for ${pixelSize}B, falling back to direct readPixels")
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
// --- 降级路径:直接分配 ByteBuffer(Java 堆)---
val pixelBuffer = try {
ByteBuffer.allocateDirect(pixelSize).order(ByteOrder.nativeOrder())
} catch (e: OutOfMemoryError) {
PLog.e(TAG, "OOM allocating pixel buffer ($width x $height, ${pixelSize}B)", e)
return null
}
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, pixelBuffer)
pixelBuffer.position(0)
checkGlError("readPixels direct")
return try {
createBitmap(width, height, Bitmap.Config.RGBA_F16, colorSpace = colorSpace).also { bitmap ->
bitmap.copyPixelsFromBuffer(pixelBuffer)