From 6b17d25b65432d6408fcbf3740409589fa442a92 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Fri, 26 Jun 2026 17:51:16 +0800 Subject: [PATCH] feat: auto metering with highlights --- .../com/hinnka/mycamera/raw/MeteringSystem.kt | 115 +++++++++++++++++- .../mycamera/raw/RawDemosaicProcessor.kt | 27 +++- .../mycamera/ui/gallery/GalleryEditScreen.kt | 4 +- .../mycamera/ui/settings/SettingsScreen.kt | 4 + .../mycamera/viewmodel/CameraViewModel.kt | 38 ++---- .../mycamera/viewmodel/GalleryViewModel.kt | 3 + .../hinnka/mycamera/raw/MeteringSystemTest.kt | 73 +++++++++++ 7 files changed, 225 insertions(+), 39 deletions(-) create mode 100644 app/src/test/java/com/hinnka/mycamera/raw/MeteringSystemTest.kt diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt index fa4c5b70..ae38a410 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt @@ -4,6 +4,7 @@ import kotlin.math.abs import kotlin.math.exp import kotlin.math.ln import kotlin.math.pow +import kotlin.math.sqrt /** * 评价测光与场景分析系统 @@ -19,6 +20,15 @@ object MeteringSystem { private const val SRGB_TRANSFER_GAMMA = 2.4f private const val CENTER_WEIGHT_SIGMA = 0.32f private const val MIN_METERING_SAMPLE_COUNT = 32 + private const val CLIP_LOW_LUMA = 0.002f + private const val CLIP_HIGH_LUMA = 0.995f + private const val HIGHLIGHT_COMPRESSION_START_LUMA = 0.62f + private const val HIGHLIGHT_COMPRESSION_FULL_LUMA = 0.96f + private const val HIGHLIGHT_COMPRESSION_AMOUNT_MIN = 0.015f + private const val HIGHLIGHT_COMPRESSION_AMOUNT_FULL = 0.18f + private const val HIGHLIGHT_COMPRESSION_STRENGTH_MIN = 0.32f + private const val HIGHLIGHT_COMPRESSION_STRENGTH_FULL = 0.86f + private const val AUTO_HIGHLIGHTS_MAX_REDUCTION = 0.70f data class MeteringResult( val meteredEv: Float, @@ -26,7 +36,8 @@ object MeteringSystem { val avgLuma: Float, val clipLow: Float, val clipHigh: Float, - val curveWhitePoint: Float + val curveWhitePoint: Float, + val highlightCompression: HighlightCompressionEstimate = HighlightCompressionEstimate.NEUTRAL ) { companion object { val EMPTY = MeteringResult( @@ -40,6 +51,22 @@ object MeteringSystem { } } + data class HighlightCompressionEstimate( + val amount: Float, + val strength: Float, + val reductionThreshold: Float, + val autoHighlightsAdjustment: Float + ) { + companion object { + val NEUTRAL = HighlightCompressionEstimate( + amount = 0f, + strength = 0f, + reductionThreshold = 0f, + autoHighlightsAdjustment = 0f + ) + } + } + data class ShadowsHighlightsParams( val highlights: Float, val shadows: Float, @@ -57,7 +84,10 @@ object MeteringSystem { val weightSum: Double, val sampleCount: Int, val sanitizedSampleCount: Int, - val midToneLinearLuma: Float + val midToneLinearLuma: Float, + val clipLow: Float, + val clipHigh: Float, + val highlightCompression: HighlightCompressionEstimate ) fun hasManualRawDevelopAdjustments( @@ -83,6 +113,10 @@ object MeteringSystem { var weightSum = 0.0 var sampleCount = 0 var sanitizedSampleCount = 0 + var clipLowWeightSum = 0.0 + var clipHighWeightSum = 0.0 + var highlightCompressionWeightSum = 0.0 + var highlightCompressionStrengthSum = 0.0 for (y in 0 until height) { val yFraction = (y + 0.5f) / height.toFloat() @@ -105,6 +139,27 @@ object MeteringSystem { val weight = centerWeight(xFraction, yFraction) weightedLogLumaSum += log2(luma.coerceAtLeast(LUMA_FLOOR)).toDouble() * weight.toDouble() weightSum += weight.toDouble() + if (luma <= CLIP_LOW_LUMA) { + clipLowWeightSum += weight.toDouble() + } + if (luma >= CLIP_HIGH_LUMA) { + clipHighWeightSum += weight.toDouble() + } + val compressionWeight = smoothStep( + HIGHLIGHT_COMPRESSION_START_LUMA, + HIGHLIGHT_COMPRESSION_FULL_LUMA, + luma + ) + if (compressionWeight > 0f) { + val weightedCompression = weight.toDouble() * compressionWeight.toDouble() + val compressionStrength = smoothStep( + HIGHLIGHT_COMPRESSION_START_LUMA, + 1f, + luma + ) + highlightCompressionWeightSum += weightedCompression + highlightCompressionStrengthSum += weightedCompression * compressionStrength.toDouble() + } sampleCount++ } } @@ -117,12 +172,27 @@ object MeteringSystem { exp2((weightedLogLumaSum / weightSum).toFloat()), DISPLAY_TARGET_LUMA ) + val clipLow = (clipLowWeightSum / weightSum).toFloat().coerceIn(0f, 1f) + val clipHigh = (clipHighWeightSum / weightSum).toFloat().coerceIn(0f, 1f) + val highlightCompressionAmount = + (highlightCompressionWeightSum / weightSum).toFloat().coerceIn(0f, 1f) + val highlightCompressionStrength = if (highlightCompressionWeightSum > 0.0) { + (highlightCompressionStrengthSum / highlightCompressionWeightSum).toFloat().coerceIn(0f, 1f) + } else { + 0f + } return SrgbThumbnailMeteringStats( weightedLogLumaSum = weightedLogLumaSum, weightSum = weightSum, sampleCount = sampleCount, sanitizedSampleCount = sanitizedSampleCount, - midToneLinearLuma = midToneLinearLuma + midToneLinearLuma = midToneLinearLuma, + clipLow = clipLow, + clipHigh = clipHigh, + highlightCompression = estimateHighlightCompression( + amount = highlightCompressionAmount, + strength = highlightCompressionStrength + ) ) } @@ -158,6 +228,45 @@ object MeteringSystem { } } + fun estimateHighlightCompression( + amount: Float, + strength: Float + ): HighlightCompressionEstimate { + val safeAmount = sanitizeUnit(amount) + val safeStrength = sanitizeUnit(strength) + val amountPressure = smoothStep( + HIGHLIGHT_COMPRESSION_AMOUNT_MIN, + HIGHLIGHT_COMPRESSION_AMOUNT_FULL, + safeAmount + ) + val strengthPressure = smoothStep( + HIGHLIGHT_COMPRESSION_STRENGTH_MIN, + HIGHLIGHT_COMPRESSION_STRENGTH_FULL, + safeStrength + ) + val reductionThreshold = sqrt(amountPressure * strengthPressure).coerceIn(0f, 1f) + val autoHighlightsAdjustment = if (reductionThreshold <= 0f) { + 0f + } else { + (-AUTO_HIGHLIGHTS_MAX_REDUCTION * reductionThreshold).coerceIn(-1f, 0f) + } + return HighlightCompressionEstimate( + amount = safeAmount, + strength = safeStrength, + reductionThreshold = reductionThreshold, + autoHighlightsAdjustment = autoHighlightsAdjustment + ) + } + + private fun sanitizeUnit(value: Float): Float { + return if (value.isFinite()) value.coerceIn(0f, 1f) else 0f + } + + private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float { + val t = ((value - edge0) / (edge1 - edge0).coerceAtLeast(0.000001f)).coerceIn(0f, 1f) + return t * t * (3f - 2f * t) + } + private fun log2(value: Float): Float { return (ln(value.toDouble()) / ln(2.0)).toFloat() } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index b687011e..558433d9 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -860,6 +860,9 @@ class RawDemosaicProcessor { PLog.d( TAG, "RAW auto exposure thumbnail stats: luma=${stats.midToneLinearLuma} " + + "clipLow=${stats.clipLow} clipHigh=${stats.clipHigh} " + + "highlightAmount=${stats.highlightCompression.amount} " + + "highlightStrength=${stats.highlightCompression.strength} " + "samples=${stats.sampleCount} sanitized=${stats.sanitizedSampleCount}" ) } @@ -1207,6 +1210,11 @@ class RawDemosaicProcessor { } else { rawExposureCompensation } + val effectiveHighlightsAdjustment = if (useAutoDevelopAdjustments) { + meteringResult.highlightCompression.autoHighlightsAdjustment + } else { + rawHighlightsAdjustment + } val engineDefaultExposureCompensation = colorEngine.defaultExposureCompensationEv val profileExposureCompensation = effectiveExposureCompensation + engineDefaultExposureCompensation @@ -1225,7 +1233,7 @@ class RawDemosaicProcessor { profileLinearExposureGain } val shadowsHighlightsParams = ShadowsHighlightsParams( - highlights = rawHighlightsAdjustment, + highlights = effectiveHighlightsAdjustment, shadows = rawShadowsAdjustment, ) RawAutoAdjustments( @@ -1240,7 +1248,10 @@ class RawDemosaicProcessor { "autoMeteringApplied=$useAutoDevelopAdjustments " + "engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " + "engineMeteringEv=${colorEngine.meteringCompensationEv} " + - "engineCompensationDomain=${colorEngine.exposureCompensationDomain}" + "engineCompensationDomain=${colorEngine.exposureCompensationDomain} " + + "highlightCompressionAmount=${meteringResult.highlightCompression.amount} " + + "highlightCompressionStrength=${meteringResult.highlightCompression.strength} " + + "highlightReductionThreshold=${meteringResult.highlightCompression.reductionThreshold}" ) if (useAutoDevelopAdjustments) { onRawAutoAdjustments?.invoke(adjustments) @@ -4733,6 +4744,11 @@ class RawDemosaicProcessor { "Tone-mapped RAW AE: mode=ViewfinderThumbnail target=$targetLuma " + "autoEv=$meteredEv renderedLuma=${best.renderedMidToneLinearLuma} " + "errorEv=${best.errorEv} profileExposureEv=${best.profileExposureEv} " + + "clipLow=${best.stats.clipLow} clipHigh=${best.stats.clipHigh} " + + "highlightCompressionAmount=${best.stats.highlightCompression.amount} " + + "highlightCompressionStrength=${best.stats.highlightCompression.strength} " + + "highlightReductionThreshold=${best.stats.highlightCompression.reductionThreshold} " + + "autoHighlights=${best.stats.highlightCompression.autoHighlightsAdjustment} " + "baselineExposure=${metadata.baselineExposure} " + "dcpBaselineExposureOffset=$dcpBaselineExposureOffset " + "engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " + @@ -4752,9 +4768,10 @@ class RawDemosaicProcessor { meteredEv = meteredEv, dynamicRangeGap = 0f, avgLuma = best.renderedMidToneLinearLuma, - clipLow = 0f, - clipHigh = 0f, - curveWhitePoint = 1f + clipLow = best.stats.clipLow, + clipHigh = best.stats.clipHigh, + curveWhitePoint = 1f, + highlightCompression = best.stats.highlightCompression ) } finally { LargeDirectBuffer.free(readbackBuffer) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt index 6889aeba..99a3ad45 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt @@ -1161,12 +1161,12 @@ fun GalleryEditScreen( } }, onRawAutoExposureChange = { - if (it) { + /*if (it) { viewModel.saveRawExposureCompensationValue(currentPhoto, 0f) } viewModel.saveRawAutoExposureValue(currentPhoto, it) { requestRawPreviewRefresh() - } + }*/ }, onRawHighlightsAdjustmentChange = { viewModel.saveRawHighlightsAdjustmentValue(currentPhoto, it) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 9046a848..c4ff89b3 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -1640,11 +1640,15 @@ fun SettingsScreen( if (it) { rawExposureCompensationUi = 0f viewModel.setRawExposureCompensation(0f) + viewModel.setRawHighlightsAdjustment(0f) } viewModel.setRawAutoExposure(it) }, onRawHighlightsAdjustmentChange = { rawHighlightsAdjustmentUi = it + if (it != 0f && rawAutoExposure) { + viewModel.setRawAutoExposure(false) + } }, onRawShadowsAdjustmentChange = { rawShadowsAdjustmentUi = it diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 2c95118c..22eed385 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -131,19 +131,15 @@ private data class RawSpectralFilmSettings( ) private fun resolveEffectiveRawAutoExposure( - userPrefs: UserPreferences?, - isRawCapture: Boolean, - exposureBias: Float + userPrefs: UserPreferences? ): Boolean { - val rawAutoExposure = userPrefs?.rawAutoExposure ?: true - if (!isRawCapture || abs(exposureBias) <= 0.0001f) return rawAutoExposure - return false + return userPrefs?.rawAutoExposure ?: true } private data class PresetMatchSnapshot( val lutId: String?, val colorRecipe: ColorRecipeParams, - val effects: com.hinnka.mycamera.model.EffectParams, + val effects: EffectParams, val aspectRatio: String, val useRaw: Boolean, val useMFNR: Boolean, @@ -226,7 +222,7 @@ private data class ActivePresetMatchState( val aspectRatio: String, val lutId: String, val recipe: ColorRecipeParams, - val effects: com.hinnka.mycamera.model.EffectParams + val effects: EffectParams ) private data class SettingValue(val value: T) @@ -234,7 +230,7 @@ private data class SettingValue(val value: T) private data class CameraFeatureUpdate( val lutId: SettingValue? = null, val colorRecipe: SettingValue? = null, - val effects: SettingValue? = null, + val effects: SettingValue? = null, val aspectRatio: SettingValue? = null, val useRaw: SettingValue? = null, val useMFNR: SettingValue? = null, @@ -342,9 +338,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) ) } - val currentEffectParams: StateFlow = userPreferencesRepository.userPreferences + val currentEffectParams: StateFlow = userPreferencesRepository.userPreferences .map { it.activeEffectParams } - .stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.model.EffectParams.DEFAULT) + .stateIn(viewModelScope, SharingStarted.Eagerly, EffectParams.DEFAULT) val customPresets: StateFlow> = userPreferencesRepository.userPreferences .map { it.customPresets } @@ -444,7 +440,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) return currentEffectParams.value.applyTo(recipe) } - fun setEffectParams(effects: com.hinnka.mycamera.model.EffectParams) { + fun setEffectParams(effects: EffectParams) { viewModelScope.launch { applyCameraFeatureUpdate( CameraFeatureUpdate(effects = SettingValue(effects)) @@ -1965,8 +1961,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) ) val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = baselineTarget == BaselineColorCorrectionTarget.RAW, - exposureBias = state.value.exposureBias, ) val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs) @@ -4280,7 +4274,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val photoQualityValue = photoQuality.firstOrNull() ?: 95 val droModeString = droMode.value val droModeForProcessing = - com.hinnka.mycamera.raw.RawProcessingPreferences.DROMode.fromPersistedName(droModeString) + RawProcessingPreferences.DROMode.fromPersistedName(droModeString) val currentCameraId = cameraController.getCurrentCameraId() // 计算旋转角度 @@ -4318,8 +4312,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs) val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = baselineTarget == BaselineColorCorrectionTarget.RAW, - exposureBias = state.value.exposureBias, ) val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs) @@ -4478,8 +4470,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val currentCameraId = cameraController.getCurrentCameraId() val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = false, - exposureBias = currentState.exposureBias, ) val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs) val captureInfo = cameraController.rebuildCaptureInfo( @@ -4623,8 +4613,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val currentCameraId = cameraController.getCurrentCameraId() val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = false, - exposureBias = currentState.exposureBias, ) val captureInfo = cameraController.rebuildCaptureInfo( result = null, @@ -4804,8 +4792,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs) val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = baselineTarget == BaselineColorCorrectionTarget.RAW, - exposureBias = state.value.exposureBias, ) val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs) @@ -5337,8 +5323,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs) val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure( userPrefs = userPrefs, - isRawCapture = baselineTarget == BaselineColorCorrectionTarget.RAW, - exposureBias = state.value.exposureBias, ) val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs) @@ -5604,10 +5588,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) ) ) } - - if (prefs.rawAutoExposure) { - userPreferencesRepository.saveRawAutoExposure(false) - } } if (enabled) { val previousTonemapMode = if (prefs.naturalLightEnabled) { diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index 03a503cc..fd054858 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -2072,6 +2072,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) fun saveRawHighlightsAdjustmentValue(mediaData: MediaData, value: Float, onComplete: ((Boolean) -> Unit)? = null) { editRawHighlightsAdjustment.value = value + if (value != 0f) { + editRawAutoExposure.value = false + } persistRawEditMetadata(mediaData, onComplete) } diff --git a/app/src/test/java/com/hinnka/mycamera/raw/MeteringSystemTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/MeteringSystemTest.kt new file mode 100644 index 00000000..70eb1617 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/raw/MeteringSystemTest.kt @@ -0,0 +1,73 @@ +package com.hinnka.mycamera.raw + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.pow +import kotlin.math.roundToInt + +class MeteringSystemTest { + @Test + fun neutralThumbnailKeepsAutoHighlightsNeutral() { + val pixels = grayscalePixels(width = 64, height = 64, linearLuma = 0.18f) + + val stats = MeteringSystem.analyzeSrgbThumbnail(64, 64, pixels) + ?: error("Expected metering stats") + + assertEquals(0f, stats.highlightCompression.amount, 0.0001f) + assertEquals(0f, stats.highlightCompression.autoHighlightsAdjustment, 0.0001f) + } + + @Test + fun tinySpecularHighlightDoesNotDominateAutoHighlights() { + val width = 64 + val height = 64 + val pixels = grayscalePixels(width, height, linearLuma = 0.18f) + pixels[(height / 2) * width + width / 2] = grayscaleArgb(0.99f) + + val stats = MeteringSystem.analyzeSrgbThumbnail(width, height, pixels) + ?: error("Expected metering stats") + + assertTrue(stats.highlightCompression.amount < 0.01f) + assertEquals(0f, stats.highlightCompression.autoHighlightsAdjustment, 0.0001f) + } + + @Test + fun broadCompressedHighlightsProduceNegativeAutoHighlights() { + val width = 64 + val height = 64 + val pixels = grayscalePixels(width, height, linearLuma = 0.18f) + for (y in 16 until 48) { + for (x in 16 until 48) { + pixels[y * width + x] = grayscaleArgb(0.98f) + } + } + + val stats = MeteringSystem.analyzeSrgbThumbnail(width, height, pixels) + ?: error("Expected metering stats") + + assertTrue(stats.highlightCompression.amount > 0.18f) + assertTrue(stats.highlightCompression.strength > 0.85f) + assertTrue(stats.highlightCompression.reductionThreshold > 0.90f) + assertTrue(stats.highlightCompression.autoHighlightsAdjustment < -0.60f) + } + + private fun grayscalePixels(width: Int, height: Int, linearLuma: Float): IntArray { + return IntArray(width * height) { grayscaleArgb(linearLuma) } + } + + private fun grayscaleArgb(linearLuma: Float): Int { + val byte = linearToSrgbByte(linearLuma) + return (0xff shl 24) or (byte shl 16) or (byte shl 8) or byte + } + + private fun linearToSrgbByte(linear: Float): Int { + val clamped = linear.coerceIn(0f, 1f) + val srgb = if (clamped <= 0.0031308f) { + clamped * 12.92f + } else { + 1.055f * clamped.pow(1f / 2.4f) - 0.055f + } + return (srgb * 255f).roundToInt().coerceIn(0, 255) + } +}