feat: new metering system

This commit is contained in:
zhoubinjia committed 2026-06-26 13:06:02 +08:00
1 parent 8090311ef2
commit 702b5def01
4 files changed
+283 -49

No files matched your search

@@ -1819,6 +1819,7 @@ object GalleryManager {
rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
capturePreviewThumbnail = thumbnail,
spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint, spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning( spectralFilmTuning = SpectralFilmTuning(
@@ -2543,7 +2544,8 @@ object GalleryManager {
superResolutionScale: Float = 1.0f, superResolutionScale: Float = 1.0f,
useGpuAcceleration: Boolean = true, useGpuAcceleration: Boolean = true,
exposureBias: Float? = null, exposureBias: Float? = null,
exportDngWithRawExport: Boolean = false exportDngWithRawExport: Boolean = false,
capturePreviewThumbnail: Bitmap? = null
) = withContext(Dispatchers.IO) { ) = withContext(Dispatchers.IO) {
try { try {
val photoDir = getPhotoDir(context, photoId, true) val photoDir = getPhotoDir(context, photoId, true)
@@ -2684,6 +2686,7 @@ object GalleryManager {
rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
capturePreviewThumbnail = capturePreviewThumbnail,
spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint, spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning( spectralFilmTuning = SpectralFilmTuning(
@@ -2798,7 +2801,8 @@ object GalleryManager {
photoQuality: Int = 95, photoQuality: Int = 95,
useGpuAcceleration: Boolean = true, useGpuAcceleration: Boolean = true,
exposureBias: Float? = null, exposureBias: Float? = null,
exportDngWithRawExport: Boolean = false exportDngWithRawExport: Boolean = false,
capturePreviewThumbnail: Bitmap? = null
): Boolean = withContext(Dispatchers.IO) { ): Boolean = withContext(Dispatchers.IO) {
var rawHdrStackResult: com.hinnka.mycamera.processor.RawStackResult? = null var rawHdrStackResult: com.hinnka.mycamera.processor.RawStackResult? = null
val imagesToClose = images.toMutableSet() val imagesToClose = images.toMutableSet()
@@ -2976,7 +2980,8 @@ object GalleryManager {
noiseReductionValue = noiseReductionValue, noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue, chromaNoiseReductionValue = chromaNoiseReductionValue,
photoQuality = photoQuality, photoQuality = photoQuality,
shouldAutoSave = shouldAutoSave shouldAutoSave = shouldAutoSave,
capturePreviewThumbnail = capturePreviewThumbnail
) )
PLog.d(TAG, "RAW HDR denoise DNG saved: $photoId") PLog.d(TAG, "RAW HDR denoise DNG saved: $photoId")
return@withContext true return@withContext true
@@ -3058,6 +3063,7 @@ object GalleryManager {
chromaNoiseReductionValue: Float, chromaNoiseReductionValue: Float,
photoQuality: Int, photoQuality: Int,
shouldAutoSave: Boolean, shouldAutoSave: Boolean,
capturePreviewThumbnail: Bitmap? = null,
) { ) {
val photoDir = getPhotoDir(context, photoId, true) val photoDir = getPhotoDir(context, photoId, true)
val photoFile = File(photoDir, PHOTO_FILE) val photoFile = File(photoDir, PHOTO_FILE)
@@ -3090,6 +3096,7 @@ object GalleryManager {
rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawRenderingEngine = updatedMetadata.rawRenderingEngine,
rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters,
rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode,
capturePreviewThumbnail = capturePreviewThumbnail,
spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmStock = updatedMetadata.spectralFilmStock,
spectralFilmPrint = updatedMetadata.spectralFilmPrint, spectralFilmPrint = updatedMetadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning( spectralFilmTuning = SpectralFilmTuning(
@@ -3312,7 +3319,8 @@ object GalleryManager {
superResolutionScale: Float = 1.0f, superResolutionScale: Float = 1.0f,
useGpuAcceleration: Boolean = true, useGpuAcceleration: Boolean = true,
exposureBias: Float? = null, exposureBias: Float? = null,
exportDngWithRawExport: Boolean = false exportDngWithRawExport: Boolean = false,
capturePreviewThumbnail: Bitmap? = null
) = withContext(Dispatchers.IO) { ) = withContext(Dispatchers.IO) {
when (val format = images[0].format) { when (val format = images[0].format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> { ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
@@ -3353,7 +3361,8 @@ object GalleryManager {
superResolutionScale, superResolutionScale,
useGpuAcceleration, useGpuAcceleration,
exposureBias, exposureBias,
exportDngWithRawExport exportDngWithRawExport,
capturePreviewThumbnail
) )
} }
@@ -4,6 +4,7 @@ import com.hinnka.mycamera.utils.PLog
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.exp import kotlin.math.exp
import kotlin.math.ln import kotlin.math.ln
import kotlin.math.pow
/** /**
* 评价测光与场景分析系统 * 评价测光与场景分析系统
@@ -17,6 +18,14 @@ object MeteringSystem {
private const val RAW_CURVE_NEUTRAL_WHITE_POINT = 1.0f private const val RAW_CURVE_NEUTRAL_WHITE_POINT = 1.0f
private const val AUTO_DEVELOP_EPSILON = 0.0001f private const val AUTO_DEVELOP_EPSILON = 0.0001f
private const val AUTO_CLIP_FRACTION = 0.0002f private const val AUTO_CLIP_FRACTION = 0.0002f
private const val SRGB_TRANSFER_THRESHOLD = 0.04045f
private const val SRGB_LINEAR_SCALE = 12.92f
private const val SRGB_TRANSFER_A = 0.055f
private const val SRGB_TRANSFER_GAMMA = 2.4f
private const val CENTER_WEIGHT_SIGMA = 0.32f
private const val MIN_METERING_SAMPLE_COUNT = 32
const val VIEWFINDER_METERING_HIGHLIGHT_EXCLUSION_LUMA = 0.95f
data class MeteringResult( data class MeteringResult(
@@ -62,6 +71,15 @@ object MeteringSystem {
val groupCount: Int val groupCount: Int
) )
data class SrgbThumbnailMeteringStats(
val weightedLogLumaSum: Double,
val weightSum: Double,
val sampleCount: Int,
val sanitizedSampleCount: Int,
val highlightRejectedSampleCount: Int,
val midToneLinearLuma: Float
)
class GpuRawAutoExposurePlan internal constructor( class GpuRawAutoExposurePlan internal constructor(
val compensatedExposureScale: Float, val compensatedExposureScale: Float,
val clipLow: Float, val clipLow: Float,
@@ -87,6 +105,12 @@ object MeteringSystem {
val midToneGain: Float, val midToneGain: Float,
val highlightAnchorGain: Float, val highlightAnchorGain: Float,
val adaptiveGain: Float, val adaptiveGain: Float,
val viewfinderTargetLuma: Float,
val viewfinderSampleCount: Int,
val viewfinderSanitizedSampleCount: Int,
val dcpBaselineExposureOffset: Float,
val renderingEngineMeteringCompensationEv: Float,
val totalBaseExposureEv: Float,
val rawMeteredEv: Float, val rawMeteredEv: Float,
val dynamicRangeGap: Float, val dynamicRangeGap: Float,
val sanitizedSampleCount: Int, val sanitizedSampleCount: Int,
@@ -105,9 +129,74 @@ object MeteringSystem {
abs(rawShadowsAdjustment) > AUTO_DEVELOP_EPSILON abs(rawShadowsAdjustment) > AUTO_DEVELOP_EPSILON
} }
fun analyzeSrgbThumbnail(
width: Int,
height: Int,
argbPixels: IntArray
): SrgbThumbnailMeteringStats? {
if (width <= 0 || height <= 0 || argbPixels.size < width * height) {
return null
}
var weightedLogLumaSum = 0.0
var weightSum = 0.0
var sampleCount = 0
var sanitizedSampleCount = 0
var highlightRejectedSampleCount = 0
for (y in 0 until height) {
val yFraction = (y + 0.5f) / height.toFloat()
for (x in 0 until width) {
val pixel = argbPixels[y * width + x]
val alpha = (pixel ushr 24) and 0xff
if (alpha == 0) continue
val alphaScale = alpha / 255f
val r = srgbToLinear(((pixel ushr 16) and 0xff) / 255f)
val g = srgbToLinear(((pixel ushr 8) and 0xff) / 255f)
val b = srgbToLinear((pixel and 0xff) / 255f)
val rawLuma = (0.2126f * r + 0.7152f * g + 0.0722f * b) * alphaScale
val luma = sanitizeLinearLuma(rawLuma)
if (luma != rawLuma) {
sanitizedSampleCount++
}
if (isHighlightExcludedFromMetering(luma)) {
highlightRejectedSampleCount++
continue
}
val xFraction = (x + 0.5f) / width.toFloat()
val weight = centerWeight(xFraction, yFraction)
weightedLogLumaSum += log2(luma.coerceAtLeast(LUMA_FLOOR)).toDouble() * weight.toDouble()
weightSum += weight.toDouble()
sampleCount++
}
}
if (sampleCount < MIN_METERING_SAMPLE_COUNT || weightSum <= 0.0) {
return null
}
val midToneLinearLuma = sanitizeAverageLuma(
exp2((weightedLogLumaSum / weightSum).toFloat()),
DISPLAY_TARGET_LUMA
)
return SrgbThumbnailMeteringStats(
weightedLogLumaSum = weightedLogLumaSum,
weightSum = weightSum,
sampleCount = sampleCount,
sanitizedSampleCount = sanitizedSampleCount,
highlightRejectedSampleCount = highlightRejectedSampleCount,
midToneLinearLuma = midToneLinearLuma
)
}
fun prepareGpuLinearRawAutoExposure( fun prepareGpuLinearRawAutoExposure(
stats: GpuRawAutoExposureBaseStats, stats: GpuRawAutoExposureBaseStats,
baselineExposure: Float, baselineExposure: Float,
viewfinderThumbnailStats: SrgbThumbnailMeteringStats,
dcpBaselineExposureOffset: Float,
renderingEngineMeteringCompensationEv: Float,
meteringCompensationEv: Float = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, meteringCompensationEv: Float = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV,
tag: String = "Linear RAW AE GPU" tag: String = "Linear RAW AE GPU"
): GpuRawAutoExposurePlan? { ): GpuRawAutoExposurePlan? {
@@ -116,7 +205,7 @@ object MeteringSystem {
} }
val safeMeteringCompensationEv = sanitizeMeteringCompensationEv(meteringCompensationEv) val safeMeteringCompensationEv = sanitizeMeteringCompensationEv(meteringCompensationEv)
val targetLuma = resolveDisplayTargetLuma(safeMeteringCompensationEv) val targetLuma = viewfinderThumbnailStats.midToneLinearLuma
val midToneLuma = if (stats.weightSum > 0.0) { val midToneLuma = if (stats.weightSum > 0.0) {
exp2((stats.weightedLogLumaSum / stats.weightSum).toFloat()) exp2((stats.weightedLogLumaSum / stats.weightSum).toFloat())
} else { } else {
@@ -141,7 +230,15 @@ object MeteringSystem {
logMax = stats.histogramLogMax logMax = stats.histogramLogMax
) )
val baselineExposureScale = exposureScaleFromEv(baselineExposure) val safeDcpBaselineExposureOffset = sanitizeExposureEv(dcpBaselineExposureOffset)
val safeRenderingEngineMeteringCompensationEv =
sanitizeExposureEv(renderingEngineMeteringCompensationEv)
val totalBaseExposureEv = resolveViewfinderMeteringBaseExposureEv(
baselineExposure = baselineExposure,
dcpBaselineExposureOffset = safeDcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = safeRenderingEngineMeteringCompensationEv
)
val baselineExposureScale = exposureScaleFromEv(totalBaseExposureEv)
val meteringClipLow = (clipLow * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA) val meteringClipLow = (clipLow * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA)
val meteringP05 = (p05 * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA) val meteringP05 = (p05 * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA)
val meteringP25 = (p25 * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA) val meteringP25 = (p25 * baselineExposureScale).coerceIn(0f, MAX_LINEAR_LUMA)
@@ -154,8 +251,7 @@ object MeteringSystem {
val highlightAnchorGain = maxOf(1f, meteringClipHigh) / meteringClipHigh.coerceAtLeast(0.01f) val highlightAnchorGain = maxOf(1f, meteringClipHigh) / meteringClipHigh.coerceAtLeast(0.01f)
val midToneGain = targetLuma / meteringMidToneLuma.coerceAtLeast(LUMA_FLOOR) val midToneGain = targetLuma / meteringMidToneLuma.coerceAtLeast(LUMA_FLOOR)
val dynamicRangeGap = evDifference(meteringClipHigh, meteringClipLow) val dynamicRangeGap = evDifference(meteringClipHigh, meteringClipLow)
val extra = smoothStep(4f, 12f, dynamicRangeGap) val adaptiveGain = midToneGain
val adaptiveGain = lerp(midToneGain * 1.2f, highlightAnchorGain * 1.1f, extra)
val autoExposureScale = adaptiveGain.coerceIn(0.25f, 4.0f) val autoExposureScale = adaptiveGain.coerceIn(0.25f, 4.0f)
val rawMeteredEv = log2(autoExposureScale) val rawMeteredEv = log2(autoExposureScale)
val compensatedExposureScale = baselineExposureScale * autoExposureScale val compensatedExposureScale = baselineExposureScale * autoExposureScale
@@ -185,6 +281,12 @@ object MeteringSystem {
midToneGain = midToneGain, midToneGain = midToneGain,
highlightAnchorGain = highlightAnchorGain, highlightAnchorGain = highlightAnchorGain,
adaptiveGain = adaptiveGain, adaptiveGain = adaptiveGain,
viewfinderTargetLuma = targetLuma,
viewfinderSampleCount = viewfinderThumbnailStats.sampleCount,
viewfinderSanitizedSampleCount = viewfinderThumbnailStats.sanitizedSampleCount,
dcpBaselineExposureOffset = safeDcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = safeRenderingEngineMeteringCompensationEv,
totalBaseExposureEv = totalBaseExposureEv,
rawMeteredEv = rawMeteredEv, rawMeteredEv = rawMeteredEv,
dynamicRangeGap = dynamicRangeGap, dynamicRangeGap = dynamicRangeGap,
sanitizedSampleCount = stats.sanitizedSampleCount, sanitizedSampleCount = stats.sanitizedSampleCount,
@@ -210,8 +312,14 @@ object MeteringSystem {
"compClipLow=${plan.compensatedClipLow} compClipHigh=${plan.compensatedClipHigh} " + "compClipLow=${plan.compensatedClipLow} compClipHigh=${plan.compensatedClipHigh} " +
"compP05=${plan.compensatedP05} compP25=${plan.compensatedP25} " + "compP05=${plan.compensatedP05} compP25=${plan.compensatedP25} " +
"compP75=${plan.compensatedP75} compP90=${plan.compensatedP90} compP99=${plan.compensatedP99} " + "compP75=${plan.compensatedP75} compP90=${plan.compensatedP90} compP99=${plan.compensatedP99} " +
"baselineExposure=${plan.baselineExposure} " + "mode=ViewfinderThumbnail baselineExposure=${plan.baselineExposure} " +
"dcpBaselineExposureOffset=${plan.dcpBaselineExposureOffset} " +
"engineMeteringEv=${plan.renderingEngineMeteringCompensationEv} " +
"totalBaseExposureEv=${plan.totalBaseExposureEv} " +
"target=${plan.targetLuma} meteringCompensationEv=${plan.meteringCompensationEv} " + "target=${plan.targetLuma} meteringCompensationEv=${plan.meteringCompensationEv} " +
"viewfinderTarget=${plan.viewfinderTargetLuma} " +
"viewfinderSamples=${plan.viewfinderSampleCount} " +
"viewfinderSanitizedSamples=${plan.viewfinderSanitizedSampleCount} " +
"midToneLuma=${plan.midToneLuma} " + "midToneLuma=${plan.midToneLuma} " +
"midToneGain=${plan.midToneGain} highlightAnchorGain=${plan.highlightAnchorGain} " + "midToneGain=${plan.midToneGain} highlightAnchorGain=${plan.highlightAnchorGain} " +
"gain=${plan.adaptiveGain} ev=${plan.rawMeteredEv} gap=${plan.dynamicRangeGap} " + "gain=${plan.adaptiveGain} ev=${plan.rawMeteredEv} gap=${plan.dynamicRangeGap} " +
@@ -245,6 +353,52 @@ object MeteringSystem {
} }
} }
fun resolveViewfinderMeteringBaseExposureEv(
baselineExposure: Float,
dcpBaselineExposureOffset: Float,
renderingEngineMeteringCompensationEv: Float
): Float {
return sanitizeExposureEv(
sanitizeExposureEv(baselineExposure) +
sanitizeExposureEv(dcpBaselineExposureOffset) +
sanitizeExposureEv(renderingEngineMeteringCompensationEv)
)
}
fun resolveViewfinderMeteringBaseExposureScale(
baselineExposure: Float,
dcpBaselineExposureOffset: Float,
renderingEngineMeteringCompensationEv: Float
): Float {
return exposureScaleFromEv(
resolveViewfinderMeteringBaseExposureEv(
baselineExposure = baselineExposure,
dcpBaselineExposureOffset = dcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = renderingEngineMeteringCompensationEv
)
)
}
private fun isHighlightExcludedFromMetering(luma: Float): Boolean {
return luma.isFinite() && luma >= VIEWFINDER_METERING_HIGHLIGHT_EXCLUSION_LUMA
}
private fun centerWeight(xFraction: Float, yFraction: Float): Float {
val dx = (xFraction - 0.5f) / CENTER_WEIGHT_SIGMA
val dy = (yFraction - 0.5f) / CENTER_WEIGHT_SIGMA
val gaussian = exp((-0.5f * (dx * dx + dy * dy)).toDouble()).toFloat()
return 0.35f + gaussian * 0.65f
}
private fun srgbToLinear(value: Float): Float {
val clamped = value.coerceIn(0f, 1f)
return if (clamped <= SRGB_TRANSFER_THRESHOLD) {
clamped / SRGB_LINEAR_SCALE
} else {
((clamped + SRGB_TRANSFER_A) / (1f + SRGB_TRANSFER_A)).pow(SRGB_TRANSFER_GAMMA)
}
}
private fun percentileFromLogHistogram( private fun percentileFromLogHistogram(
histogram: IntArray, histogram: IntArray,
percentile: Float, percentile: Float,
@@ -281,15 +435,6 @@ object MeteringSystem {
return exp2(logMax).coerceIn(0f, MAX_LINEAR_LUMA) return exp2(logMax).coerceIn(0f, MAX_LINEAR_LUMA)
} }
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 evDifference(brighter: Float, darker: Float): Float { private fun evDifference(brighter: Float, darker: Float): Float {
val safeBrighter = sanitizeLinearLuma(brighter).coerceAtLeast(LUMA_FLOOR) val safeBrighter = sanitizeLinearLuma(brighter).coerceAtLeast(LUMA_FLOOR)
val safeDarker = sanitizeLinearLuma(darker).coerceAtLeast(1e-5f) val safeDarker = sanitizeLinearLuma(darker).coerceAtLeast(1e-5f)
@@ -312,8 +457,12 @@ object MeteringSystem {
} }
} }
private fun resolveDisplayTargetLuma(meteringCompensationEv: Float): Float { private fun sanitizeExposureEv(ev: Float): Float {
return DISPLAY_TARGET_LUMA * exp2(-sanitizeMeteringCompensationEv(meteringCompensationEv)) return if (ev.isFinite()) {
ev.coerceIn(-MAX_METERING_COMPENSATION_EV, MAX_METERING_COMPENSATION_EV)
} else {
0f
}
} }
private fun sanitizeMeteringCompensationEv(meteringCompensationEv: Float): Float { private fun sanitizeMeteringCompensationEv(meteringCompensationEv: Float): Float {
@@ -324,19 +473,4 @@ object MeteringSystem {
} }
} }
private fun lerp(start: Float, end: Float, fraction: Float): Float {
return start + (end - start) * fraction.coerceIn(0f, 1f)
}
private fun smoothStep(edge0: Float, edge1: Float, x: Float): Float {
if (!edge0.isFinite() || !edge1.isFinite() || !x.isFinite()) {
return 0f
}
val width = edge1 - edge0
if (kotlin.math.abs(width) < 0.000001f) {
return if (x >= edge1) 1f else 0f
}
val t = ((x - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
} }
@@ -421,6 +421,22 @@ class RawDemosaicProcessor {
) )
} }
private fun analyzeSrgbThumbnailForMetering(bitmap: Bitmap?): MeteringSystem.SrgbThumbnailMeteringStats? {
if (bitmap == null || bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) {
return null
}
return try {
val width = bitmap.width
val height = bitmap.height
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
MeteringSystem.analyzeSrgbThumbnail(width, height, pixels)
} catch (e: Exception) {
PLog.e(TAG, "Failed to analyze capture preview thumbnail for RAW AE", e)
null
}
}
/** /**
* 处理 DNG 文件 * 处理 DNG 文件
* *
@@ -459,6 +475,7 @@ class RawDemosaicProcessor {
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
rawCfaCorrectionMode: String? = null, rawCfaCorrectionMode: String? = null,
capturePreviewThumbnail: Bitmap? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null onMetadata: ((RawMetadata) -> Unit)? = null
): Bitmap? = withContext(glDispatcher) { ): Bitmap? = withContext(glDispatcher) {
@@ -497,6 +514,7 @@ class RawDemosaicProcessor {
rawRenderingEngine = rawRenderingEngine, rawRenderingEngine = rawRenderingEngine,
rawToneMappingParameters = rawToneMappingParameters, rawToneMappingParameters = rawToneMappingParameters,
rawCfaCorrectionMode = rawCfaCorrectionMode, rawCfaCorrectionMode = rawCfaCorrectionMode,
capturePreviewThumbnail = capturePreviewThumbnail,
dngFile = dngFile, dngFile = dngFile,
onRawAutoAdjustments = onRawAutoAdjustments, onRawAutoAdjustments = onRawAutoAdjustments,
onMetadata = onMetadata onMetadata = onMetadata
@@ -611,6 +629,7 @@ class RawDemosaicProcessor {
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
rawCfaCorrectionMode: String? = null, rawCfaCorrectionMode: String? = null,
capturePreviewThumbnail: Bitmap? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null onMetadata: ((RawMetadata) -> Unit)? = null
): RawHdrRenderResult? = withContext(glDispatcher) { ): RawHdrRenderResult? = withContext(glDispatcher) {
@@ -649,6 +668,7 @@ class RawDemosaicProcessor {
rawRenderingEngine = rawRenderingEngine, rawRenderingEngine = rawRenderingEngine,
rawToneMappingParameters = rawToneMappingParameters, rawToneMappingParameters = rawToneMappingParameters,
rawCfaCorrectionMode = rawCfaCorrectionMode, rawCfaCorrectionMode = rawCfaCorrectionMode,
capturePreviewThumbnail = capturePreviewThumbnail,
dngFile = dngFile, dngFile = dngFile,
onRawAutoAdjustments = onRawAutoAdjustments, onRawAutoAdjustments = onRawAutoAdjustments,
onMetadata = onMetadata, onMetadata = onMetadata,
@@ -696,6 +716,7 @@ class RawDemosaicProcessor {
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
rawCfaCorrectionMode: String? = null, rawCfaCorrectionMode: String? = null,
capturePreviewThumbnail: Bitmap? = null,
dngFile: File? = null, dngFile: File? = null,
onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null,
onMetadata: ((RawMetadata) -> Unit)? = null, onMetadata: ((RawMetadata) -> Unit)? = null,
@@ -832,6 +853,22 @@ class RawDemosaicProcessor {
"toneCurve=false baselineExposureOffset=false" "toneCurve=false baselineExposureOffset=false"
) )
} }
val viewfinderThumbnailStats = if (rawAutoExposure) {
analyzeSrgbThumbnailForMetering(capturePreviewThumbnail).also { stats ->
if (stats == null) {
PLog.d(TAG, "RAW auto exposure disabled: capture preview thumbnail unavailable")
} else {
PLog.d(
TAG,
"RAW auto exposure thumbnail stats: luma=${stats.midToneLinearLuma} " +
"samples=${stats.sampleCount} sanitized=${stats.sanitizedSampleCount} " +
"highlightRejected=${stats.highlightRejectedSampleCount}"
)
}
}
} else {
null
}
PLog.d( PLog.d(
TAG, TAG,
@@ -1145,15 +1182,25 @@ class RawDemosaicProcessor {
// Keep the metering pass in scene-linear RAW space so HDR PGTM does not // Keep the metering pass in scene-linear RAW space so HDR PGTM does not
// alter the histogram used to choose exposure. // alter the histogram used to choose exposure.
applyDngBaselineExposure = false, applyDngBaselineExposure = false,
viewfinderThumbnailStats = viewfinderThumbnailStats,
dcpBaselineExposureOffset = if (applyDcpBaselineExposureOffset) {
resolvedDcpRenderPlan.baselineExposureOffset
} else {
0f
},
renderingEngineMeteringCompensationEv = colorEngine.meteringCompensationEv,
meteringCompensationEv = colorEngine.meteringCompensationEv, meteringCompensationEv = colorEngine.meteringCompensationEv,
useDepthWeighting = rawAutoExposure useDepthWeighting = false
) )
val useAutoDevelopAdjustments = rawAutoExposure && !MeteringSystem.hasManualRawDevelopAdjustments( val useAutoDevelopAdjustments = rawAutoExposure &&
rawExposureCompensation = rawExposureCompensation, viewfinderThumbnailStats != null &&
rawHighlightsAdjustment = rawHighlightsAdjustment, meteringResult != MeteringSystem.MeteringResult.EMPTY &&
rawShadowsAdjustment = rawShadowsAdjustment !MeteringSystem.hasManualRawDevelopAdjustments(
) rawExposureCompensation = rawExposureCompensation,
rawHighlightsAdjustment = rawHighlightsAdjustment,
rawShadowsAdjustment = rawShadowsAdjustment
)
val effectiveExposureCompensation = if (useAutoDevelopAdjustments) { val effectiveExposureCompensation = if (useAutoDevelopAdjustments) {
meteringResult.meteredEv meteringResult.meteredEv
} else { } else {
@@ -1189,11 +1236,14 @@ class RawDemosaicProcessor {
TAG, TAG,
"RAW auto develop sliders: exposure=${adjustments.exposureCompensation} " + "RAW auto develop sliders: exposure=${adjustments.exposureCompensation} " +
"highlights=${adjustments.highlights} shadows=${adjustments.shadows} " + "highlights=${adjustments.highlights} shadows=${adjustments.shadows} " +
"autoMeteringApplied=$useAutoDevelopAdjustments " +
"engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " + "engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " +
"engineMeteringEv=${colorEngine.meteringCompensationEv} " + "engineMeteringEv=${colorEngine.meteringCompensationEv} " +
"engineCompensationDomain=${colorEngine.exposureCompensationDomain}" "engineCompensationDomain=${colorEngine.exposureCompensationDomain}"
) )
onRawAutoAdjustments?.invoke(adjustments) if (useAutoDevelopAdjustments) {
onRawAutoAdjustments?.invoke(adjustments)
}
} }
PLog.d( PLog.d(
TAG, TAG,
@@ -1798,6 +1848,8 @@ class RawDemosaicProcessor {
uniform ivec2 uImageSize; uniform ivec2 uImageSize;
uniform int uGroupsX; uniform int uGroupsX;
uniform int uUseDepthWeight; uniform int uUseDepthWeight;
uniform float uMeteringExposureScale;
uniform float uHighlightExclusionLuma;
layout(std430, binding = 0) buffer HistogramOut { layout(std430, binding = 0) buffer HistogramOut {
uint histogram[]; uint histogram[];
@@ -1868,8 +1920,13 @@ class RawDemosaicProcessor {
atomicAdd(localHistogram[bin], 1u); atomicAdd(localHistogram[bin], 1u);
vec2 uv = (vec2(coord) + vec2(0.5)) / vec2(uImageSize); vec2 uv = (vec2(coord) + vec2(0.5)) / vec2(uImageSize);
float weight = centerWeight(uv) * depthWeight(uv); float meteredLuma = luma * max(uMeteringExposureScale, 0.0);
localStats[localIndex] = vec4(logLuma * weight, weight, 1.0, sanitized); bool includeSample = uHighlightExclusionLuma <= 0.0 ||
meteredLuma < uHighlightExclusionLuma;
if (includeSample) {
float weight = centerWeight(uv) * depthWeight(uv);
localStats[localIndex] = vec4(logLuma * weight, weight, 1.0, sanitized);
}
} }
barrier(); barrier();
@@ -4544,9 +4601,15 @@ class RawDemosaicProcessor {
dcpRenderPlan: DcpRenderPlan?, dcpRenderPlan: DcpRenderPlan?,
applyDcpBaselineExposureOffset: Boolean, applyDcpBaselineExposureOffset: Boolean,
applyDngBaselineExposure: Boolean, applyDngBaselineExposure: Boolean,
viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats?,
dcpBaselineExposureOffset: Float,
renderingEngineMeteringCompensationEv: Float,
meteringCompensationEv: Float, meteringCompensationEv: Float,
useDepthWeighting: Boolean = true useDepthWeighting: Boolean = true
): MeteringSystem.MeteringResult { ): MeteringSystem.MeteringResult {
if (viewfinderThumbnailStats == null) {
return MeteringSystem.MeteringResult.EMPTY
}
val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1) val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1)
val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1) val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1)
return try { return try {
@@ -4615,6 +4678,9 @@ class RawDemosaicProcessor {
height = meteringHeight, height = meteringHeight,
depthTextureId = depthTextureId, depthTextureId = depthTextureId,
baselineExposure = metadata.baselineExposure, baselineExposure = metadata.baselineExposure,
viewfinderThumbnailStats = viewfinderThumbnailStats,
dcpBaselineExposureOffset = dcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = renderingEngineMeteringCompensationEv,
meteringCompensationEv = meteringCompensationEv meteringCompensationEv = meteringCompensationEv
) ?: MeteringSystem.MeteringResult.EMPTY ) ?: MeteringSystem.MeteringResult.EMPTY
@@ -4648,6 +4714,9 @@ class RawDemosaicProcessor {
height: Int, height: Int,
depthTextureId: Int, depthTextureId: Int,
baselineExposure: Float, baselineExposure: Float,
viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats,
dcpBaselineExposureOffset: Float,
renderingEngineMeteringCompensationEv: Float,
meteringCompensationEv: Float meteringCompensationEv: Float
): MeteringSystem.MeteringResult? { ): MeteringSystem.MeteringResult? {
if (rawAeBaseProgram == 0) { if (rawAeBaseProgram == 0) {
@@ -4658,15 +4727,25 @@ class RawDemosaicProcessor {
return null return null
} }
val meteringBaseExposureScale = MeteringSystem.resolveViewfinderMeteringBaseExposureScale(
baselineExposure = baselineExposure,
dcpBaselineExposureOffset = dcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = renderingEngineMeteringCompensationEv
)
val baseStats = dispatchRawAeBaseStats( val baseStats = dispatchRawAeBaseStats(
linearTextureId = linearTextureId, linearTextureId = linearTextureId,
width = width, width = width,
height = height, height = height,
depthTextureId = depthTextureId depthTextureId = depthTextureId,
meteringBaseExposureScale = meteringBaseExposureScale,
highlightExclusionLuma = MeteringSystem.VIEWFINDER_METERING_HIGHLIGHT_EXCLUSION_LUMA
) ?: return null ) ?: return null
val plan = MeteringSystem.prepareGpuLinearRawAutoExposure( val plan = MeteringSystem.prepareGpuLinearRawAutoExposure(
stats = baseStats, stats = baseStats,
baselineExposure = baselineExposure, baselineExposure = baselineExposure,
viewfinderThumbnailStats = viewfinderThumbnailStats,
dcpBaselineExposureOffset = dcpBaselineExposureOffset,
renderingEngineMeteringCompensationEv = renderingEngineMeteringCompensationEv,
meteringCompensationEv = meteringCompensationEv, meteringCompensationEv = meteringCompensationEv,
tag = "Linear RAW AE GPU" tag = "Linear RAW AE GPU"
) ?: return null ) ?: return null
@@ -4677,7 +4756,9 @@ class RawDemosaicProcessor {
linearTextureId: Int, linearTextureId: Int,
width: Int, width: Int,
height: Int, height: Int,
depthTextureId: Int depthTextureId: Int,
meteringBaseExposureScale: Float,
highlightExclusionLuma: Float
): MeteringSystem.GpuRawAutoExposureBaseStats? { ): MeteringSystem.GpuRawAutoExposureBaseStats? {
val groupsX = roundUp(width, RAW_AE_LOCAL_SIZE_X) / RAW_AE_LOCAL_SIZE_X val groupsX = roundUp(width, RAW_AE_LOCAL_SIZE_X) / RAW_AE_LOCAL_SIZE_X
val groupsY = roundUp(height, RAW_AE_LOCAL_SIZE_Y) / RAW_AE_LOCAL_SIZE_Y val groupsY = roundUp(height, RAW_AE_LOCAL_SIZE_Y) / RAW_AE_LOCAL_SIZE_Y
@@ -4727,6 +4808,14 @@ class RawDemosaicProcessor {
GLES31.glGetUniformLocation(rawAeBaseProgram, "uUseDepthWeight"), GLES31.glGetUniformLocation(rawAeBaseProgram, "uUseDepthWeight"),
if (depthTextureId != 0) 1 else 0 if (depthTextureId != 0) 1 else 0
) )
GLES31.glUniform1f(
GLES31.glGetUniformLocation(rawAeBaseProgram, "uMeteringExposureScale"),
meteringBaseExposureScale
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(rawAeBaseProgram, "uHighlightExclusionLuma"),
highlightExclusionLuma
)
GLES31.glDispatchCompute(groupsX, groupsY, 1) GLES31.glDispatchCompute(groupsX, groupsY, 1)
GLES31.glMemoryBarrier( GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
@@ -4914,7 +4914,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
superResolutionScale = superResScale, superResolutionScale = superResScale,
useGpuAcceleration = useGpuAcceleration.value, useGpuAcceleration = useGpuAcceleration.value,
exposureBias = state.value.exposureBias, exposureBias = state.value.exposureBias,
exportDngWithRawExport = exportDngWithRawExport.value exportDngWithRawExport = exportDngWithRawExport.value,
capturePreviewThumbnail = previewThumbnail
) )
} }
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave") PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
@@ -5276,7 +5277,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
photoQuality = photoQualityValue, photoQuality = photoQualityValue,
useGpuAcceleration = useGpuAcceleration.firstOrNull() ?: DeviceUtil.defaultGpuAcceleration, useGpuAcceleration = useGpuAcceleration.firstOrNull() ?: DeviceUtil.defaultGpuAcceleration,
exposureBias = state.value.exposureBias, exposureBias = state.value.exposureBias,
exportDngWithRawExport = exportDngWithRawExport.firstOrNull() ?: false exportDngWithRawExport = exportDngWithRawExport.firstOrNull() ?: false,
capturePreviewThumbnail = previewThumbnail
) )
} }
PLog.d(TAG, "RAW HDR bracket image saved: $photoId, mode=$captureMode") PLog.d(TAG, "RAW HDR bracket image saved: $photoId, mode=$captureMode")