feat: new auto exposure algo

This commit is contained in:
zhoubinjia committed 2026-07-13 19:42:17 +08:00
1 parent 2c5f119e17
commit ccd833c68d
3 files changed
+280 -38

No files matched your search

@@ -107,6 +107,23 @@ object MeteringSystem {
val highlightCompression: HighlightCompressionEstimate
)
/**
* 全图 sRGB 显示亮度直方图。
*
* [meanEv] 是以 256 个亮度区间中心值计算的平均 log2 亮度。两张图的
* meanEv 差值可直接作为显示亮度域中的平均 EV 增益。
*/
data class SrgbDisplayLumaHistogram(
val binCounts: IntArray,
val sampleCount: Int,
val meanEv: Float
) {
init {
require(binCounts.size == DISPLAY_LUMA_HISTOGRAM_BIN_COUNT)
require(sampleCount >= 0)
}
}
fun hasManualRawDevelopAdjustments(
rawExposureCompensation: Float,
rawHighlightsAdjustment: Float,
@@ -258,6 +275,69 @@ object MeteringSystem {
)
}
/**
* 统计整张图的 256 档 sRGB 显示亮度直方图,不应用中心权重或区域裁切。
*/
fun analyzeFullFrameSrgbHistogram(
width: Int,
height: Int,
argbPixels: IntArray
): SrgbDisplayLumaHistogram? {
if (width <= 0 || height <= 0 || argbPixels.size < width * height) {
return null
}
val binCounts = IntArray(DISPLAY_LUMA_HISTOGRAM_BIN_COUNT)
var sampleCount = 0
for (index in 0 until width * height) {
val pixel = argbPixels[index]
val alpha = (pixel ushr 24) and 0xff
if (alpha == 0) continue
val alphaScale = alpha / 255f
val displayR = ((pixel ushr 16) and 0xff) / 255f
val displayG = ((pixel ushr 8) and 0xff) / 255f
val displayB = (pixel and 0xff) / 255f
val displayLuma = sanitizeDisplayLuma(
(0.2126f * displayR + 0.7152f * displayG + 0.0722f * displayB) * alphaScale
)
val binIndex = fullRangeDisplayHistogramIndex(displayLuma)
binCounts[binIndex]++
sampleCount++
}
if (sampleCount < MIN_METERING_SAMPLE_COUNT) {
return null
}
var weightedEvSum = 0.0
for (binIndex in binCounts.indices) {
val count = binCounts[binIndex]
if (count <= 0) continue
val representativeLuma = displayHistogramBinCenter(binIndex)
weightedEvSum += log2(representativeLuma).toDouble() * count.toDouble()
}
val meanEv = (weightedEvSum / sampleCount.toDouble()).toFloat()
if (!meanEv.isFinite()) return null
return SrgbDisplayLumaHistogram(
binCounts = binCounts,
sampleCount = sampleCount,
meanEv = meanEv
)
}
/**
* 返回把 [rendered] 提升到 [reference] 平均直方图亮度所需的 EV 增益。
*/
fun histogramAverageEvGain(
reference: SrgbDisplayLumaHistogram,
rendered: SrgbDisplayLumaHistogram
): Float? {
if (reference.sampleCount <= 0 || rendered.sampleCount <= 0) return null
val gain = reference.meanEv - rendered.meanEv
return gain.takeIf { it.isFinite() }
}
private fun logLumaHistogramIndex(logLuma: Float): Int {
val normalized = (logLuma - LOG_LUMA_HISTOGRAM_MIN) / LOG_LUMA_HISTOGRAM_RANGE
return (normalized * (LOG_LUMA_HISTOGRAM_BIN_COUNT - 1))
@@ -271,6 +351,18 @@ object MeteringSystem {
.coerceIn(0, DISPLAY_LUMA_HISTOGRAM_BIN_COUNT - 1)
}
private fun fullRangeDisplayHistogramIndex(displayLuma: Float): Int {
return (displayLuma.coerceIn(0f, 1f) * DISPLAY_LUMA_HISTOGRAM_BIN_COUNT)
.toInt()
.coerceIn(0, DISPLAY_LUMA_HISTOGRAM_BIN_COUNT - 1)
}
private fun displayHistogramBinCenter(binIndex: Int): Float {
return ((binIndex.coerceIn(0, DISPLAY_LUMA_HISTOGRAM_BIN_COUNT - 1) + 0.5f) /
DISPLAY_LUMA_HISTOGRAM_BIN_COUNT.toFloat())
.coerceAtLeast(LUMA_FLOOR)
}
private fun robustMidToneDisplayLuma(
displayLumaHistogramWeightSums: DoubleArray,
displayLumaHistogramWeightedSums: DoubleArray,
@@ -191,6 +191,8 @@ class RawDemosaicProcessor {
private const val RAW_TONE_MAPPED_AE_MAX_SOLVE_STEPS = 3
private const val RAW_TONE_MAPPED_AE_EV_TOLERANCE = 0.05f
private const val RAW_TONE_MAPPED_AE_MIN_STEP_EV = 0.025f
// 编译期开关:true=全图 256 档直方图平均 EV;false=中心 2/3 普通平均亮度。
private const val RAW_AE_USE_FULL_FRAME_HISTOGRAM = true
private const val FILMIC_GREY_SOURCE = 0.1845f
private const val FILMIC_OUTPUT_POWER = 3.614815775f
private const val FILMIC_DISPLAY_BLACK = 0.0001517634f
@@ -634,20 +636,63 @@ class RawDemosaicProcessor {
val stats: MeteringSystem.SrgbThumbnailMeteringStats
)
private sealed interface RawAeMeteringReference {
val width: Int
val height: Int
}
private data class RawAeCenterAverageReference(
val width: Int,
val height: Int,
override val width: Int,
override val height: Int,
val bounds: Rect,
val targetDisplayLuma: Float,
val pixelCount: Int
) : RawAeMeteringReference
private data class RawAeFullFrameHistogramReference(
override val width: Int,
override val height: Int,
val histogram: MeteringSystem.SrgbDisplayLumaHistogram
) : RawAeMeteringReference
private data class RawAeMeteringMatch(
val errorEv: Float,
val targetMetric: Float,
val renderedMetric: Float,
val renderedDisplayLuma: Float,
val pixelCount: Int,
val mode: String
)
private data class RawAeCenterAverageMatch(
val errorEv: Float,
val targetDisplayLuma: Float,
val renderedDisplayLuma: Float,
val pixelCount: Int
)
private fun buildRawAeMeteringReference(
image: RawAeMeteringImage
): RawAeMeteringReference? {
return if (RAW_AE_USE_FULL_FRAME_HISTOGRAM) {
val histogram = MeteringSystem.analyzeFullFrameSrgbHistogram(
width = image.width,
height = image.height,
argbPixels = image.argbPixels
) ?: return null
PLog.d(
TAG,
"RAW AE reference: mode=full-frame-histogram-256 " +
"meanEv=${histogram.meanEv} samples=${histogram.sampleCount}"
)
RawAeFullFrameHistogramReference(
width = image.width,
height = image.height,
histogram = histogram
)
} else {
buildRawAeCenterAverageReference(image)?.also { reference ->
PLog.d(
TAG,
"RAW AE reference: mode=center-two-thirds-average " +
"displayLuma=${reference.targetDisplayLuma} samples=${reference.pixelCount}"
)
}
}
}
private fun buildRawAeCenterAverageReference(
image: RawAeMeteringImage
@@ -666,24 +711,51 @@ class RawDemosaicProcessor {
return reference
}
private fun matchRawAeCenterAverage(
reference: RawAeCenterAverageReference,
private fun matchRawAeMeteringReference(
reference: RawAeMeteringReference,
rendered: RawAeMeteringImage
): RawAeCenterAverageMatch? {
): RawAeMeteringMatch? {
if (reference.width != rendered.width || reference.height != rendered.height) {
return null
}
val renderedDisplayLuma = averageSrgbDisplayLuma(rendered, reference.bounds)
?: return null
return RawAeCenterAverageMatch(
errorEv = displayLumaErrorEv(
renderedLuma = renderedDisplayLuma,
targetLuma = reference.targetDisplayLuma
),
targetDisplayLuma = reference.targetDisplayLuma,
renderedDisplayLuma = renderedDisplayLuma,
pixelCount = reference.pixelCount
)
return when (reference) {
is RawAeCenterAverageReference -> {
val renderedDisplayLuma = averageSrgbDisplayLuma(rendered, reference.bounds)
?: return null
RawAeMeteringMatch(
errorEv = displayLumaErrorEv(
renderedLuma = renderedDisplayLuma,
targetLuma = reference.targetDisplayLuma
),
targetMetric = reference.targetDisplayLuma,
renderedMetric = renderedDisplayLuma,
renderedDisplayLuma = renderedDisplayLuma,
pixelCount = reference.pixelCount,
mode = "center-two-thirds-average"
)
}
is RawAeFullFrameHistogramReference -> {
val renderedHistogram = MeteringSystem.analyzeFullFrameSrgbHistogram(
width = rendered.width,
height = rendered.height,
argbPixels = rendered.argbPixels
) ?: return null
val requiredEvGain = MeteringSystem.histogramAverageEvGain(
reference = reference.histogram,
rendered = renderedHistogram
) ?: return null
RawAeMeteringMatch(
// 求解器的 errorEv 约定为“渲染值 - 目标值”,与所需增益符号相反。
errorEv = -requiredEvGain,
targetMetric = reference.histogram.meanEv,
renderedMetric = renderedHistogram.meanEv,
renderedDisplayLuma = 2.0.pow(renderedHistogram.meanEv.toDouble()).toFloat(),
pixelCount = renderedHistogram.sampleCount,
mode = "full-frame-histogram-256"
)
}
}
}
private fun rawAeCenterTwoThirdsBounds(width: Int, height: Int): Rect? {
@@ -1705,8 +1777,8 @@ class RawDemosaicProcessor {
}
}
val viewfinderThumbnailStats = viewfinderThumbnailMeteringImage?.stats
val viewfinderCenterAverageReference = viewfinderThumbnailMeteringImage
?.let { buildRawAeCenterAverageReference(it) }
val viewfinderMeteringReference = viewfinderThumbnailMeteringImage
?.let { buildRawAeMeteringReference(it) }
PLog.d(
TAG,
@@ -2093,7 +2165,7 @@ class RawDemosaicProcessor {
applyProfileGainTableMap = hasProfileGainTableMap,
clampProfileRgb = useAdobeProfilePipeline,
viewfinderThumbnailStats = viewfinderThumbnailStats,
viewfinderCenterAverageReference = viewfinderCenterAverageReference,
viewfinderMeteringReference = viewfinderMeteringReference,
outputBounds = rawAeContentBounds?.rawRenderBounds ?: bounds,
outputRotation = actualRotation,
spectralFilmLut = spektrafilmLut,
@@ -7684,7 +7756,7 @@ class RawDemosaicProcessor {
applyProfileGainTableMap: Boolean,
clampProfileRgb: Boolean,
viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats?,
viewfinderCenterAverageReference: RawAeCenterAverageReference?,
viewfinderMeteringReference: RawAeMeteringReference?,
outputBounds: Rect,
outputRotation: Int,
spectralFilmLut: SpectralFilmLut?,
@@ -7748,7 +7820,7 @@ class RawDemosaicProcessor {
readbackHeight = viewfinderThumbnailStats.height.coerceAtLeast(1),
outputRotation = outputRotation,
viewfinderThumbnailStats = viewfinderThumbnailStats,
viewfinderCenterAverageReference = viewfinderCenterAverageReference,
viewfinderMeteringReference = viewfinderMeteringReference,
dcpRenderPlan = dcpRenderPlan,
spectralFilmLut = spectralFilmLut,
colorEngine = colorEngine,
@@ -7772,7 +7844,7 @@ class RawDemosaicProcessor {
val profileExposureEv: Float,
val renderedLuma: Float,
val errorEv: Float,
val centerAverageMatch: RawAeCenterAverageMatch,
val meteringMatch: RawAeMeteringMatch,
val stats: MeteringSystem.SrgbThumbnailMeteringStats,
val argbPixels: IntArray
)
@@ -7854,7 +7926,7 @@ class RawDemosaicProcessor {
readbackHeight: Int,
outputRotation: Int,
viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats,
viewfinderCenterAverageReference: RawAeCenterAverageReference?,
viewfinderMeteringReference: RawAeMeteringReference?,
dcpRenderPlan: DcpRenderPlan?,
spectralFilmLut: SpectralFilmLut?,
colorEngine: RawRenderingEngine,
@@ -7867,8 +7939,8 @@ class RawDemosaicProcessor {
applyProfileDcpBaselineExposureOffset: Boolean,
applyProfileDngBaselineExposure: Boolean
): MeteringSystem.MeteringResult? {
val centerAverageReference = viewfinderCenterAverageReference ?: run {
PLog.d(TAG, "RAW auto exposure disabled: center average reference unavailable")
val meteringReference = viewfinderMeteringReference ?: run {
PLog.d(TAG, "RAW auto exposure disabled: metering reference unavailable")
return null
}
val pixelCount = readbackWidth * readbackHeight
@@ -7884,7 +7956,7 @@ class RawDemosaicProcessor {
width = width,
height = height,
autoEv = 0f,
centerAverageReference = centerAverageReference,
meteringReference = meteringReference,
dcpRenderPlan = dcpRenderPlan,
spectralFilmLut = spectralFilmLut,
colorEngine = colorEngine,
@@ -7909,7 +7981,7 @@ class RawDemosaicProcessor {
width = width,
height = height,
autoEv = autoEv,
centerAverageReference = centerAverageReference,
meteringReference = meteringReference,
dcpRenderPlan = dcpRenderPlan,
spectralFilmLut = spectralFilmLut,
colorEngine = colorEngine,
@@ -8083,7 +8155,7 @@ class RawDemosaicProcessor {
width: Int,
height: Int,
autoEv: Float,
centerAverageReference: RawAeCenterAverageReference,
meteringReference: RawAeMeteringReference,
dcpRenderPlan: DcpRenderPlan?,
spectralFilmLut: SpectralFilmLut?,
colorEngine: RawRenderingEngine,
@@ -8151,16 +8223,22 @@ class RawDemosaicProcessor {
pixelBuffer = readbackBuffer
) ?: return null
val stats = image.stats
val centerAverageMatch = matchRawAeCenterAverage(centerAverageReference, image)
val meteringMatch = matchRawAeMeteringReference(meteringReference, image)
?: return null
val renderedLuma = centerAverageMatch.renderedDisplayLuma
val errorEv = centerAverageMatch.errorEv
val renderedLuma = meteringMatch.renderedDisplayLuma
val errorEv = meteringMatch.errorEv
PLog.d(
TAG,
"RAW AE sample: mode=${meteringMatch.mode} autoEv=$clampedAutoEv " +
"target=${meteringMatch.targetMetric} rendered=${meteringMatch.renderedMetric} " +
"requiredEvGain=${-errorEv} samples=${meteringMatch.pixelCount}"
)
return ToneMappedRawAeSample(
autoEv = clampedAutoEv,
profileExposureEv = profileExposureUniforms.exposureEv,
renderedLuma = renderedLuma,
errorEv = errorEv,
centerAverageMatch = centerAverageMatch,
meteringMatch = meteringMatch,
stats = stats,
argbPixels = image.argbPixels
)
@@ -52,10 +52,82 @@ class MeteringSystemTest {
assertTrue(stats.highlightCompression.autoHighlightsAdjustment < -0.60f)
}
@Test
fun fullFrameHistogramIncludesPixelsOutsideCenterRegion() {
val width = 32
val height = 32
val pixels = IntArray(width * height) { displayGrayscaleArgb(255) }
for (y in 8 until 24) {
for (x in 8 until 24) {
pixels[y * width + x] = displayGrayscaleArgb(0)
}
}
val histogram = MeteringSystem.analyzeFullFrameSrgbHistogram(width, height, pixels)
?: error("Expected full-frame histogram")
assertEquals(width * height, histogram.sampleCount)
assertEquals(16 * 16, histogram.binCounts[0])
assertEquals(width * height - 16 * 16, histogram.binCounts[255])
}
@Test
fun histogramAverageEvGainTracksOneStopDisplayLumaChange() {
val width = 32
val height = 32
val reference = MeteringSystem.analyzeFullFrameSrgbHistogram(
width,
height,
IntArray(width * height) { displayGrayscaleArgb(128) }
) ?: error("Expected reference histogram")
val rendered = MeteringSystem.analyzeFullFrameSrgbHistogram(
width,
height,
IntArray(width * height) { displayGrayscaleArgb(64) }
) ?: error("Expected rendered histogram")
val gain = MeteringSystem.histogramAverageEvGain(reference, rendered)
?: error("Expected EV gain")
assertEquals(1f, gain, 0.02f)
}
@Test
fun histogramAverageEvGainAveragesMixedSceneInEvDomain() {
val width = 32
val height = 32
val referencePixels = IntArray(width * height) { index ->
displayGrayscaleArgb(if (index < width * height / 2) 64 else 128)
}
val renderedPixels = IntArray(width * height) { index ->
displayGrayscaleArgb(if (index < width * height / 2) 32 else 64)
}
val reference = MeteringSystem.analyzeFullFrameSrgbHistogram(
width,
height,
referencePixels
) ?: error("Expected reference histogram")
val rendered = MeteringSystem.analyzeFullFrameSrgbHistogram(
width,
height,
renderedPixels
) ?: error("Expected rendered histogram")
val gain = MeteringSystem.histogramAverageEvGain(reference, rendered)
?: error("Expected EV gain")
assertEquals(1f, gain, 0.03f)
}
private fun grayscalePixels(width: Int, height: Int, linearLuma: Float): IntArray {
return IntArray(width * height) { grayscaleArgb(linearLuma) }
}
private fun displayGrayscaleArgb(value: Int): Int {
val byte = value.coerceIn(0, 255)
return (0xff shl 24) or (byte shl 16) or (byte shl 8) or byte
}
private fun grayscaleArgb(linearLuma: Float): Int {
val byte = linearToSrgbByte(linearLuma)
return (0xff shl 24) or (byte shl 16) or (byte shl 8) or byte