feat: refactor RAW auto exposure to use rendered output

This commit is contained in:
Hinnka committed 2026-05-02 14:03:46 +08:00
1 parent 9e2a3d9bb5
commit 972bc2d023
2 files changed
+125 -54

No files matched your search

@@ -1,8 +1,11 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.color.TransferCurve
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.FloatBuffer
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.pow
/**
@@ -10,6 +13,8 @@ import kotlin.math.pow
*/
object MeteringSystem {
private const val TAG = "MeteringSystem"
private const val DISPLAY_TARGET_LUMA = 0.52f
private const val DISPLAY_HIGHLIGHT_LIMIT = 0.98f
fun analyze(
floatBuffer: FloatBuffer,
@@ -142,6 +147,101 @@ object MeteringSystem {
return gain.coerceIn(0.25f, 16f)
}
fun analyzeRenderedExposureEv(
byteBuffer: ByteBuffer,
width: Int,
height: Int,
centerWeight: Float = 0f
): Float {
val gridRows = 12
val gridCols = 12
val zoneSum = DoubleArray(gridRows * gridCols)
val zonePixCount = IntArray(gridRows * gridCols)
val lumas = FloatArray(width * height)
var validPixelCount = 0
byteBuffer.position(0)
for (y in 0 until height) {
val gy = (y.toFloat() / height * gridRows).toInt().coerceIn(0, gridRows - 1)
for (x in 0 until width) {
val gx = (x.toFloat() / width * gridCols).toInt().coerceIn(0, gridCols - 1)
val zi = gy * gridCols + gx
val r = (byteBuffer.get().toInt() and 0xFF) / 255f
val g = (byteBuffer.get().toInt() and 0xFF) / 255f
val b = (byteBuffer.get().toInt() and 0xFF) / 255f
byteBuffer.get()
val luma = r * 0.2126f + g * 0.7152f + b * 0.0722f
lumas[validPixelCount++] = luma
zoneSum[zi] += luma.toDouble()
zonePixCount[zi]++
}
}
if (validPixelCount == 0) {
return 0f
}
var totalWeight = 0.0
var weightedSum = 0.0
val normalizedCenterWeight = centerWeight.coerceIn(0f, 1f).toDouble()
val centerInfluence = normalizedCenterWeight * normalizedCenterWeight
for (i in 0 until gridRows * gridCols) {
if (zonePixCount[i] == 0) continue
val gy = i / gridCols
val gx = i % gridCols
val pzx = (gx + 0.5f) / gridCols
val pzy = (gy + 0.5f) / gridRows
val distSqC = (pzx - 0.5f).let { it * it } + (pzy - 0.5f).let { it * it }
val weight = calculateSpatialMeteringWeight(distSqC.toDouble(), centerInfluence)
val zoneAvg = zoneSum[i] / zonePixCount[i]
weightedSum += zoneAvg * weight
totalWeight += weight
}
if (totalWeight <= 0.0) {
return 0f
}
val averageLuma = (weightedSum / totalWeight).toFloat()
if (averageLuma <= 0.000001f) {
return 0f
}
// val histogram = lumas.copyOf(validPixelCount)
// histogram.sort()
// val highlightPercentile = percentile(histogram, 0.995f)
val meteredEv = log2(DISPLAY_TARGET_LUMA / averageLuma)
// val highlightLimitedEv = if (meteredEv > 0f && highlightPercentile > 0f) {
// minOf(meteredEv, log2(DISPLAY_HIGHLIGHT_LIMIT / highlightPercentile).coerceAtLeast(0f))
// } else {
// meteredEv
// }
// PLog.d(
// TAG,
// "Rendered metering: avg=$averageLuma p99.5=$highlightPercentile ev=$meteredEv limited=$highlightLimitedEv"
// )
// return highlightLimitedEv.coerceIn(-2f, 2f)
return meteredEv.coerceIn(-2f, 4f)
}
private fun percentile(sortedValues: FloatArray, percentile: Float): Float {
if (sortedValues.isEmpty()) {
return 0f
}
val index = ((sortedValues.size - 1) * percentile.coerceIn(0f, 1f)).toInt()
return sortedValues[index]
}
private fun log2(value: Float): Float {
return (ln(value.toDouble()) / ln(2.0)).toFloat()
}
private fun calculateSpatialMeteringWeight(distSqC: Double, centerInfluence: Double): Double {
if (centerInfluence <= 0.0) {
return 1.0
@@ -5,7 +5,6 @@ import android.graphics.Bitmap
import android.graphics.Rect
import android.media.Image
import android.opengl.*
import android.util.Half
import android.util.Log
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.camera.AspectRatio
@@ -22,7 +21,6 @@ import java.nio.FloatBuffer
import java.nio.ShortBuffer
import java.util.concurrent.Executors
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.sqrt
import android.opengl.Matrix as GlMatrix
@@ -590,7 +588,9 @@ class RawDemosaicProcessor {
val autoExposureEv = if (rawAutoExposure) {
resolveRawAutoExposureEv(
metadata = actualMetadata,
rawMeteringCenterWeight = rawMeteringCenterWeight
rawMeteringCenterWeight = rawMeteringCenterWeight,
sourceTextureId = demosaicTextureId,
dcpRenderPlan = resolvedDcpRenderPlan
)
} else {
0f
@@ -1821,7 +1821,9 @@ class RawDemosaicProcessor {
private fun renderCombinedPass(
metadata: RawMetadata,
inputTextureId: Int = demosaicTextureId,
dcpRenderPlan: DcpRenderPlan? = null
dcpRenderPlan: DcpRenderPlan? = null,
viewportWidth: Int = metadata.width,
viewportHeight: Int = metadata.height
) {
val curveLut = ACR3Curve.samples()
val outputTransform = computeWorkingToOutputTransform(ColorSpace.ProPhoto, ColorSpace.SRGB)
@@ -1831,7 +1833,7 @@ class RawDemosaicProcessor {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, combinedFramebufferId)
checkGlError("renderCombinedPass glBindFramebuffer")
GLES30.glViewport(0, 0, metadata.width, metadata.height)
GLES30.glViewport(0, 0, viewportWidth, viewportHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
checkGlError("renderCombinedPass clear")
@@ -2116,52 +2118,45 @@ class RawDemosaicProcessor {
private fun resolveRawAutoExposureEv(
metadata: RawMetadata,
rawMeteringCenterWeight: Float
rawMeteringCenterWeight: Float,
sourceTextureId: Int,
dcpRenderPlan: DcpRenderPlan?
): Float {
val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1)
val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1)
return try {
setupOutputFramebuffer(meteringWidth, meteringHeight)
renderMeteringPass(
width = meteringWidth,
height = meteringHeight,
sourceTextureId = demosaicTextureId
setupCombinedFramebuffer(meteringWidth, meteringHeight)
renderCombinedPass(
metadata = metadata,
inputTextureId = sourceTextureId,
dcpRenderPlan = dcpRenderPlan,
viewportWidth = meteringWidth,
viewportHeight = meteringHeight
)
val halfBuffer = ByteBuffer
.allocateDirect(meteringWidth * meteringHeight * 4 * 2)
val buffer = ByteBuffer
.allocateDirect(meteringWidth * meteringHeight * 4)
.order(ByteOrder.nativeOrder())
.asShortBuffer()
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, combinedFramebufferId)
GLES30.glReadPixels(
0,
0,
meteringWidth,
meteringHeight,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
halfBuffer
GLES30.GL_UNSIGNED_BYTE,
buffer
)
checkGlError("resolveRawAutoExposureEv")
halfBuffer.position(0)
val buffer = ByteBuffer
.allocateDirect(meteringWidth * meteringHeight * 4 * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
while (halfBuffer.hasRemaining()) {
buffer.put(Half.toFloat(halfBuffer.get()))
}
buffer.position(0)
val gain = MeteringSystem.analyze(
floatBuffer = buffer,
val ev = MeteringSystem.analyzeRenderedExposureEv(
byteBuffer = buffer,
width = meteringWidth,
height = meteringHeight,
metadata = metadata,
centerWeight = rawMeteringCenterWeight
)
val ev = (ln(gain) / ln(2f)).coerceIn(-2f, 4f)
PLog.d(
TAG,
"RAW auto exposure: gain=$gain ev=$ev centerWeight=${rawMeteringCenterWeight.coerceIn(0f, 1f)}"
"RAW auto exposure: renderedEv=$ev centerWeight=${rawMeteringCenterWeight.coerceIn(0f, 1f)}"
)
ev
} catch (e: Exception) {
@@ -2170,30 +2165,6 @@ class RawDemosaicProcessor {
}
}
private fun renderMeteringPass(
width: Int,
height: Int,
sourceTextureId: Int
) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(passthroughProgram)
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(passthroughProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(passthroughProgram, "uTexture"), 0)
drawQuad(passthroughProgram)
checkGlError("renderMeteringPass")
}
private fun resolveLinearInputLevels(
metadata: RawMetadata,
rawBlackPointCorrection: Float,