feat: gpu based auto exposure

This commit is contained in:
Hinnka committed 2026-06-14 11:00:47 +08:00
1 parent e63ec50be4
commit 5ba66f0498
4 files changed
+1447 -169

No files matched your search

@@ -141,17 +141,32 @@ object GalleryManager {
adjustments: RawDemosaicProcessor.RawAutoAdjustments
): MediaMetadata {
return copy(
rawAutoExposure = true,
rawExposureCompensation = adjustments.exposureCompensation,
rawHighlightsAdjustment = adjustments.highlights,
rawShadowsAdjustment = adjustments.shadows
)
}
data class PhotoMetadataUpdate(
val photoId: String,
val metadata: MediaMetadata
)
private val _photoMetadataUpdatedEvents =
MutableSharedFlow<PhotoMetadataUpdate>(extraBufferCapacity = 16)
val photoMetadataUpdatedEvents: SharedFlow<PhotoMetadataUpdate> =
_photoMetadataUpdatedEvents.asSharedFlow()
private val _photoLibraryChangedEvents = MutableSharedFlow<Unit>(extraBufferCapacity = 16)
val photoLibraryChangedEvents: SharedFlow<Unit> = _photoLibraryChangedEvents.asSharedFlow()
private val hdrWorkLock = Any()
private val hdrWorkCounts = ConcurrentHashMap<String, Int>()
private fun notifyPhotoMetadataUpdated(photoId: String, metadata: MediaMetadata) {
_photoMetadataUpdatedEvents.tryEmit(PhotoMetadataUpdate(photoId, metadata))
}
fun notifyPhotoLibraryChanged() {
_photoLibraryChangedEvents.tryEmit(Unit)
}
@@ -3000,7 +3015,9 @@ object GalleryManager {
*/
suspend fun saveMetadata(context: Context, photoId: String, metadata: MediaMetadata): Boolean {
return metadataMutex.withLock {
saveMetadataInternal(context, photoId, metadata)
saveMetadataInternal(context, photoId, metadata).also { saved ->
if (saved) notifyPhotoMetadataUpdated(photoId, metadata)
}
}
}
@@ -3018,7 +3035,9 @@ object GalleryManager {
update: (MediaMetadata) -> MediaMetadata
): MediaMetadata? {
return metadataMutex.withLock {
GalleryMediaStore.updateMetadata(context, photoId, update)
GalleryMediaStore.updateMetadata(context, photoId, update).also { updated ->
if (updated != null) notifyPhotoMetadataUpdated(photoId, updated)
}
}
}
@@ -36,7 +36,6 @@ object MeteringSystem {
private const val RAW_AUTO_HDR_SHADOW_LIMIT = 0.9f
private const val RAW_AUTO_HDR_BASELINE_START = 1.0f
private const val RAW_AUTO_HDR_BASELINE_FULL = 2.0f
private const val RAW_AUTO_FULL_ADJUSTMENT_EV = 1.6f
private const val RAW_AUTO_LOW_KEY_P75_RATIO_FULL = 0.45f
private const val RAW_AUTO_LOW_KEY_P75_RATIO_START = 0.85f
private const val RAW_AUTO_LOW_KEY_P90_RATIO_FULL = 0.70f
@@ -44,8 +43,16 @@ object MeteringSystem {
private const val RAW_AUTO_LOW_KEY_MAX_SHADOW_ATTENUATION = 0.78f
private const val MERTENS_WELL_EXPOSED_CENTER = 0.5f
private const val MERTENS_WELL_EXPOSED_SIGMA = 0.2f
private const val MERTENS_TARGET_TO_MID_INTENSITY_SCALE = 2f
private const val MERTENS_SHADOW_MASK_START = 0.04f
private const val MERTENS_SHADOW_MASK_END = 0.45f
private const val MERTENS_HIGHLIGHT_MASK_START = 0.55f
private const val MERTENS_HIGHLIGHT_MASK_END = 0.92f
private const val MERTENS_CONTRAST_WEIGHT_EXPONENT = 1f
private const val MERTENS_SATURATION_WEIGHT_EXPONENT = 1f
private const val MERTENS_EXPOSURE_WEIGHT_EXPONENT = 1f
private const val MERTENS_MIN_TONE_WEIGHT = 0.0001f
private const val MERTENS_EV_INTENSITY_FLOOR = 0.0005f
private const val MERTENS_TONE_STATS_MAX_SAMPLES = 4096
private val MERTENS_VIRTUAL_EXPOSURE_EVS = floatArrayOf(-2f, -1f, 0f, 1f, 2f)
@@ -96,6 +103,61 @@ object MeteringSystem {
}
}
data class GpuRawAutoExposureBaseStats(
val histogram: IntArray,
val histogramLogMin: Float,
val histogramLogMax: Float,
val weightedLogLumaSum: Double,
val weightSum: Double,
val sampleCount: Int,
val sanitizedSampleCount: Int,
val groupCount: Int
)
data class GpuRawAutoExposureToneStats(
val highlightDeltaEnergySum: Double,
val shadowDeltaEnergySum: Double,
val highlightWeightSum: Double,
val shadowWeightSum: Double,
val mertensContrastSum: Double,
val mertensSaturationSum: Double,
val mertensWellExposednessSum: Double,
val sampleCount: Int,
val sampleStep: Int,
val groupCount: Int
)
class GpuRawAutoExposurePlan internal constructor(
val compensatedExposureScale: Float,
val sampleStep: Int,
val clipLow: Float,
val clipHigh: Float,
val p05: Float,
val p25: Float,
val p75: Float,
val p90: Float,
val p99: Float,
val compensatedClipLow: Float,
val compensatedClipHigh: Float,
val compensatedP05: Float,
val compensatedP25: Float,
val compensatedP75: Float,
val compensatedP90: Float,
val compensatedP99: Float,
val baselineExposure: Float,
val targetLuma: Float,
val midToneLuma: Float,
val midToneGain: Float,
val highlightAnchorGain: Float,
val adaptiveGain: Float,
val rawMeteredEv: Float,
val dynamicRangeGap: Float,
val sanitizedSampleCount: Int,
val histogramSampleCount: Int,
val histogramGroupCount: Int,
val tag: String
)
private data class DepthWeightMap(
val weights: FloatArray,
val separation: Float,
@@ -126,14 +188,41 @@ object MeteringSystem {
val weight: Float
)
private data class ExposureFusionToneStats(
val highlightAdjustmentEv: Float,
val shadowAdjustmentEv: Float,
val highlightRegionWeight: Float,
val shadowRegionWeight: Float
private data class LinearRgbImage(
val width: Int,
val height: Int,
val red: FloatArray,
val green: FloatArray,
val blue: FloatArray,
val lumas: FloatArray,
val sanitizedSampleCount: Int
)
private data class ExposureFusionToneStats(
val highlightFusionDelta: Float,
val shadowFusionDelta: Float,
val highlightRegionWeight: Float,
val shadowRegionWeight: Float,
val mertensContrastMean: Float,
val mertensSaturationMean: Float,
val mertensWellExposednessMean: Float,
val sampleCount: Int,
val sampleStep: Int
)
private data class MertensVirtualExposureResult(
val intensity: Float,
val contrastMean: Float,
val saturationMean: Float,
val wellExposednessMean: Float
)
private data class MertensFusionWeight(
val weight: Float,
val contrast: Float,
val saturation: Float,
val wellExposedness: Float
)
@SuppressLint("HalfFloat")
fun analyzeLinearHalfFloatExposureEv(
@@ -143,20 +232,20 @@ object MeteringSystem {
weightBuffer: ByteBuffer? = null, // Optional weight mask (e.g. depth map)
baselineExposure: Float = 0f
): MeteringResult {
val source = decodeLinearHalfFloatRgbImage(
pixelBuffer = pixelBuffer,
width = width,
height = height
)
return analyzeExposureEv(
width = width,
height = height,
weightBuffer = weightBuffer,
targetLuma = DISPLAY_TARGET_LUMA * 2f.pow(-ACR3_AVERAGE_TONE_CURVE_EV),
baselineExposure = baselineExposure,
tag = "Linear RAW AE"
) { index ->
val base = index * 4
val r = Half.toFloat(pixelBuffer.get(base))
val g = Half.toFloat(pixelBuffer.get(base + 1))
val b = Half.toFloat(pixelBuffer.get(base + 2))
r * 0.2126f + g * 0.7152f + b * 0.0722f
}
tag = "Linear RAW AE",
source = source
)
}
fun hasManualRawDevelopAdjustments(
@@ -169,36 +258,206 @@ object MeteringSystem {
abs(rawShadowsAdjustment) > AUTO_DEVELOP_EPSILON
}
private inline fun analyzeExposureEv(
fun prepareGpuLinearRawAutoExposure(
stats: GpuRawAutoExposureBaseStats,
baselineExposure: Float,
tag: String = "Linear RAW AE GPU"
): GpuRawAutoExposurePlan? {
if (stats.histogram.isEmpty() || stats.sampleCount <= 0) {
return null
}
val targetLuma = DISPLAY_TARGET_LUMA * 2f.pow(-ACR3_AVERAGE_TONE_CURVE_EV)
val midToneLuma = if (stats.weightSum > 0.0) {
exp2((stats.weightedLogLumaSum / stats.weightSum).toFloat())
} else {
targetLuma
}.let { sanitizeAverageLuma(it, targetLuma) }
val clipLow = percentileFromLogHistogram(
histogram = stats.histogram,
percentile = AUTO_CLIP_FRACTION,
logMin = stats.histogramLogMin,
logMax = stats.histogramLogMax
)
val p05 = percentileFromLogHistogram(stats.histogram, 0.05f, stats.histogramLogMin, stats.histogramLogMax)
val p25 = percentileFromLogHistogram(stats.histogram, 0.25f, stats.histogramLogMin, stats.histogramLogMax)
val p75 = percentileFromLogHistogram(stats.histogram, 0.75f, stats.histogramLogMin, stats.histogramLogMax)
val p90 = percentileFromLogHistogram(stats.histogram, 0.90f, stats.histogramLogMin, stats.histogramLogMax)
val p99 = percentileFromLogHistogram(stats.histogram, 0.99f, stats.histogramLogMin, stats.histogramLogMax)
val clipHigh = percentileFromLogHistogram(
histogram = stats.histogram,
percentile = 1f - AUTO_CLIP_FRACTION,
logMin = stats.histogramLogMin,
logMax = stats.histogramLogMax
)
val highlightAnchorGain = maxOf(1f, clipHigh) / clipHigh.coerceAtLeast(0.01f)
val midToneGain = targetLuma / midToneLuma.coerceAtLeast(LUMA_FLOOR)
val dynamicRangeGap = evDifference(clipHigh, clipLow)
val extra = smoothStep(4f, 12f, dynamicRangeGap)
val adaptiveGain = lerp(midToneGain * 1.2f, highlightAnchorGain * 1.1f, extra)
val rawMeteredEv = log2(adaptiveGain.coerceIn(0.25f, 4.0f))
val compensatedExposureScale = exp2(rawMeteredEv)
val sampleStep = calculateMertensToneSampleStep(stats.sampleCount)
return GpuRawAutoExposurePlan(
compensatedExposureScale = compensatedExposureScale,
sampleStep = sampleStep,
clipLow = clipLow,
clipHigh = clipHigh,
p05 = p05,
p25 = p25,
p75 = p75,
p90 = p90,
p99 = p99,
compensatedClipLow = (clipLow * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedClipHigh = (clipHigh * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedP05 = (p05 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedP25 = (p25 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedP75 = (p75 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedP90 = (p90 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
compensatedP99 = (p99 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA),
baselineExposure = baselineExposure,
targetLuma = targetLuma,
midToneLuma = midToneLuma,
midToneGain = midToneGain,
highlightAnchorGain = highlightAnchorGain,
adaptiveGain = adaptiveGain,
rawMeteredEv = rawMeteredEv,
dynamicRangeGap = dynamicRangeGap,
sanitizedSampleCount = stats.sanitizedSampleCount,
histogramSampleCount = stats.sampleCount,
histogramGroupCount = stats.groupCount,
tag = tag
)
}
fun finishGpuLinearRawAutoExposure(
plan: GpuRawAutoExposurePlan,
stats: GpuRawAutoExposureToneStats
): MeteringResult {
val exposureFusionToneStats = exposureFusionToneStatsFromGpu(stats)
val highlights = -calculateAutoHighlightCompression(exposureFusionToneStats.highlightFusionDelta)
val shadowLimit = resolveAutoShadowLimit(plan.baselineExposure)
val unprotectedShadows = calculateAutoShadowLift(
stats = exposureFusionToneStats,
shadowLimit = shadowLimit
)
val lowKeyShadowProtection = calculateLowKeyShadowProtection(
compensatedP75 = plan.compensatedP75,
compensatedP90 = plan.compensatedP90,
targetLuma = plan.targetLuma
)
val shadows = applyLowKeyShadowProtection(
shadows = unprotectedShadows,
protection = lowKeyShadowProtection,
shadowLimit = shadowLimit
)
val curveWhitePoint = if (plan.compensatedClipHigh > 1f) {
plan.compensatedClipHigh.coerceIn(1.05f, 4.0f)
} else {
RAW_CURVE_NEUTRAL_WHITE_POINT
}
PLog.d(
TAG,
"${plan.tag}: clipLow=${plan.clipLow} clipHigh=${plan.clipHigh} " +
"p05=${plan.p05} p25=${plan.p25} p75=${plan.p75} p90=${plan.p90} p99=${plan.p99} " +
"compScale=${plan.compensatedExposureScale} " +
"compClipLow=${plan.compensatedClipLow} compClipHigh=${plan.compensatedClipHigh} " +
"compP05=${plan.compensatedP05} compP25=${plan.compensatedP25} " +
"compP75=${plan.compensatedP75} compP90=${plan.compensatedP90} compP99=${plan.compensatedP99} " +
"highlightFusionDelta=${exposureFusionToneStats.highlightFusionDelta} " +
"shadowFusionDelta=${exposureFusionToneStats.shadowFusionDelta} " +
"highlightRegionWeight=${exposureFusionToneStats.highlightRegionWeight} " +
"shadowRegionWeight=${exposureFusionToneStats.shadowRegionWeight} " +
"mertensContrastMean=${exposureFusionToneStats.mertensContrastMean} " +
"mertensSaturationMean=${exposureFusionToneStats.mertensSaturationMean} " +
"mertensWellExposednessMean=${exposureFusionToneStats.mertensWellExposednessMean} " +
"mertensSamples=${exposureFusionToneStats.sampleCount} " +
"mertensSampleStep=${exposureFusionToneStats.sampleStep} " +
"lowKeyShadowProtection=$lowKeyShadowProtection " +
"baselineExposure=${plan.baselineExposure} shadowLimit=$shadowLimit " +
"highlights=$highlights shadows=$shadows unprotectedShadows=$unprotectedShadows " +
"target=${plan.targetLuma} midToneLuma=${plan.midToneLuma} " +
"midToneGain=${plan.midToneGain} highlightAnchorGain=${plan.highlightAnchorGain} " +
"gain=${plan.adaptiveGain} ev=${plan.rawMeteredEv} gap=${plan.dynamicRangeGap} " +
"sanitizedSamples=${plan.sanitizedSampleCount} histogramSamples=${plan.histogramSampleCount} " +
"histogramGroups=${plan.histogramGroupCount} mertensGroups=${stats.groupCount}"
)
return MeteringResult(
meteredEv = plan.rawMeteredEv.coerceIn(-2f, 2f),
dynamicRangeGap = plan.dynamicRangeGap,
avgLuma = plan.midToneLuma,
clipLow = plan.clipLow,
clipHigh = plan.clipHigh,
highlights = highlights,
shadows = shadows,
curveWhitePoint = curveWhitePoint
)
}
@SuppressLint("HalfFloat")
private fun decodeLinearHalfFloatRgbImage(
pixelBuffer: ShortBuffer,
width: Int,
height: Int
): LinearRgbImage {
val pixelCount = (width * height).coerceAtLeast(0)
val red = FloatArray(pixelCount)
val green = FloatArray(pixelCount)
val blue = FloatArray(pixelCount)
val lumas = FloatArray(pixelCount)
var sanitizedSampleCount = 0
for (index in 0 until pixelCount) {
val base = index * 4
val rawR = Half.toFloat(pixelBuffer.get(base))
val rawG = Half.toFloat(pixelBuffer.get(base + 1))
val rawB = Half.toFloat(pixelBuffer.get(base + 2))
val r = sanitizeLinearLuma(rawR)
val g = sanitizeLinearLuma(rawG)
val b = sanitizeLinearLuma(rawB)
val luma = sanitizeLinearLuma(r * 0.2126f + g * 0.7152f + b * 0.0722f)
if (rawR != r || rawG != g || rawB != b) {
sanitizedSampleCount++
}
red[index] = r
green[index] = g
blue[index] = b
lumas[index] = luma
}
return LinearRgbImage(
width = width,
height = height,
red = red,
green = green,
blue = blue,
lumas = lumas,
sanitizedSampleCount = sanitizedSampleCount
)
}
private fun analyzeExposureEv(
width: Int,
height: Int,
weightBuffer: ByteBuffer?,
targetLuma: Float,
baselineExposure: Float,
tag: String,
lumaAt: (Int) -> Float
source: LinearRgbImage
): MeteringResult {
val pixelCount = width * height
if (pixelCount == 0) return MeteringResult.EMPTY
if (pixelCount == 0 || source.lumas.isEmpty()) return MeteringResult.EMPTY
val depthWeights = decodeDepthWeights(weightBuffer, pixelCount)
val lumas = FloatArray(pixelCount)
var sanitizedSampleCount = 0
for (y in 0 until height) {
for (x in 0 until width) {
val idx = y * width + x
val rawLuma = lumaAt(idx)
val luma = sanitizeLinearLuma(rawLuma)
if (rawLuma != luma) {
sanitizedSampleCount++
}
lumas[idx] = luma
}
}
val midToneReference = calculateMidToneReferenceLuma(
lumas = lumas,
lumas = source.lumas,
width = width,
height = height,
depthWeights = depthWeights?.weights,
@@ -206,14 +465,15 @@ object MeteringSystem {
)
val midToneLuma = midToneReference.luma
lumas.sort()
val clipLow = percentile(lumas, AUTO_CLIP_FRACTION)
val p05 = percentile(lumas, 0.05f)
val p25 = percentile(lumas, 0.25f)
val p75 = percentile(lumas, 0.75f)
val p90 = percentile(lumas, 0.90f)
val p99 = percentile(lumas, 0.99f)
val clipHigh = percentile(lumas, 1f - AUTO_CLIP_FRACTION)
val sortedLumas = source.lumas.copyOf()
sortedLumas.sort()
val clipLow = percentile(sortedLumas, AUTO_CLIP_FRACTION)
val p05 = percentile(sortedLumas, 0.05f)
val p25 = percentile(sortedLumas, 0.25f)
val p75 = percentile(sortedLumas, 0.75f)
val p90 = percentile(sortedLumas, 0.90f)
val p99 = percentile(sortedLumas, 0.99f)
val clipHigh = percentile(sortedLumas, 1f - AUTO_CLIP_FRACTION)
val highlightAnchorGain = maxOf(1f, clipHigh) / clipHigh.coerceAtLeast(0.01f)
val midToneGain = targetLuma / midToneLuma.coerceAtLeast(LUMA_FLOOR)
@@ -232,11 +492,11 @@ object MeteringSystem {
val compensatedP99 = (p99 * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA)
val compensatedClipHigh = (clipHigh * compensatedExposureScale).coerceIn(0f, MAX_LINEAR_LUMA)
val exposureFusionToneStats = calculateExposureFusionToneStats(
sortedLumas = lumas,
source = source,
exposureScale = compensatedExposureScale,
targetLuma = targetLuma
)
val highlights = -calculateAutoHighlightCompression(exposureFusionToneStats.highlightAdjustmentEv)
val highlights = -calculateAutoHighlightCompression(exposureFusionToneStats.highlightFusionDelta)
val shadowLimit = resolveAutoShadowLimit(baselineExposure)
val unprotectedShadows = calculateAutoShadowLift(
stats = exposureFusionToneStats,
@@ -268,16 +528,22 @@ object MeteringSystem {
"compClipLow=$compensatedClipLow compClipHigh=$compensatedClipHigh " +
"compP05=$compensatedP05 compP25=$compensatedP25 " +
"compP75=$compensatedP75 compP90=$compensatedP90 compP99=$compensatedP99 " +
"highlightAdjustmentEv=${exposureFusionToneStats.highlightAdjustmentEv} " +
"shadowAdjustmentEv=${exposureFusionToneStats.shadowAdjustmentEv} " +
"highlightFusionDelta=${exposureFusionToneStats.highlightFusionDelta} " +
"shadowFusionDelta=${exposureFusionToneStats.shadowFusionDelta} " +
"highlightRegionWeight=${exposureFusionToneStats.highlightRegionWeight} " +
"shadowRegionWeight=${exposureFusionToneStats.shadowRegionWeight} " +
"mertensContrastMean=${exposureFusionToneStats.mertensContrastMean} " +
"mertensSaturationMean=${exposureFusionToneStats.mertensSaturationMean} " +
"mertensWellExposednessMean=${exposureFusionToneStats.mertensWellExposednessMean} " +
"mertensSamples=${exposureFusionToneStats.sampleCount} " +
"mertensSampleStep=${exposureFusionToneStats.sampleStep} " +
"lowKeyShadowProtection=$lowKeyShadowProtection " +
"baselineExposure=$baselineExposure shadowLimit=$shadowLimit " +
"highlights=$highlights shadows=$shadows unprotectedShadows=$unprotectedShadows " +
"target=$targetLuma midToneLuma=$midToneLuma " +
"midToneGain=$midToneGain highlightAnchorGain=$highlightAnchorGain gain=$adaptiveGain " +
"ev=$rawMeteredEv gap=$dynamicRangeGap "
"ev=$rawMeteredEv gap=$dynamicRangeGap " +
"sanitizedSamples=${source.sanitizedSampleCount}"
)
return MeteringResult(
@@ -692,17 +958,12 @@ object MeteringSystem {
}
private fun calculateExposureFusionToneStats(
sortedLumas: FloatArray,
source: LinearRgbImage,
exposureScale: Float,
targetLuma: Float
): ExposureFusionToneStats {
if (sortedLumas.isEmpty()) {
return ExposureFusionToneStats(
highlightAdjustmentEv = 0f,
shadowAdjustmentEv = 0f,
highlightRegionWeight = 0f,
shadowRegionWeight = 0f
)
if (source.lumas.isEmpty()) {
return emptyExposureFusionToneStats()
}
val safeExposureScale = if (exposureScale.isFinite() && exposureScale > 0f) {
@@ -710,59 +971,80 @@ object MeteringSystem {
} else {
1f
}
var highlightEvEnergySum = 0.0
var shadowEvEnergySum = 0.0
val virtualExposureScales = buildMertensVirtualExposureScales(safeExposureScale)
val sampleStep = calculateMertensToneSampleStep(source.lumas.size)
val startOffset = sampleStep / 2
var highlightDeltaEnergySum = 0.0
var shadowDeltaEnergySum = 0.0
var highlightWeightSum = 0.0
var shadowWeightSum = 0.0
for (luma in sortedLumas) {
val baseLuma = sanitizeLinearLuma(luma * safeExposureScale)
val baseIntensity = linearLumaToExposureFusionIntensity(
luma = baseLuma,
targetLuma = targetLuma
)
val fusedIntensity = calculateVirtualMertensFusionIntensity(
baseLuma = baseLuma,
targetLuma = targetLuma
)
val fusionDelta = fusedIntensity - baseIntensity
val highlightMask = smoothStep(
targetLuma,
0.78f,
baseIntensity
)
val shadowMask = 1f - smoothStep(
0.005f,
targetLuma,
baseIntensity
)
val highlightAdjustmentEv = if (fusionDelta < 0f) {
log2(baseIntensity.coerceAtLeast(MERTENS_EV_INTENSITY_FLOOR) /
fusedIntensity.coerceAtLeast(MERTENS_EV_INTENSITY_FLOOR))
} else {
0f
var mertensContrastSum = 0.0
var mertensSaturationSum = 0.0
var mertensWellExposednessSum = 0.0
var sampledCount = 0
var y = startOffset.coerceAtMost(source.height - 1)
while (y < source.height) {
var x = startOffset.coerceAtMost(source.width - 1)
val rowOffset = y * source.width
while (x < source.width) {
val index = rowOffset + x
val baseIntensity = calculateExposureFusionIntensity(
source = source,
index = index,
exposureScale = safeExposureScale,
targetLuma = targetLuma
)
val fusionResult = calculateVirtualMertensFusionIntensity(
source = source,
index = index,
baseIntensity = baseIntensity,
virtualExposureScales = virtualExposureScales,
targetLuma = targetLuma
)
val fusionDelta = fusionResult.intensity - baseIntensity
val highlightMask = smoothStep(
MERTENS_HIGHLIGHT_MASK_START,
MERTENS_HIGHLIGHT_MASK_END,
baseIntensity
)
val shadowMask = 1f - smoothStep(
MERTENS_SHADOW_MASK_START,
MERTENS_SHADOW_MASK_END,
baseIntensity
)
val highlightFusionDelta = if (fusionDelta < 0f) {
-fusionDelta
} else {
0f
}
val shadowFusionDelta = if (fusionDelta > 0f) {
fusionDelta
} else {
0f
}
highlightDeltaEnergySum += (highlightFusionDelta * highlightFusionDelta * highlightMask).toDouble()
shadowDeltaEnergySum += (shadowFusionDelta * shadowFusionDelta * shadowMask).toDouble()
highlightWeightSum += highlightMask.toDouble()
shadowWeightSum += shadowMask.toDouble()
mertensContrastSum += fusionResult.contrastMean.toDouble()
mertensSaturationSum += fusionResult.saturationMean.toDouble()
mertensWellExposednessSum += fusionResult.wellExposednessMean.toDouble()
sampledCount++
x += sampleStep
}
val shadowAdjustmentEv = if (fusionDelta > 0f) {
log2(fusedIntensity.coerceAtLeast(MERTENS_EV_INTENSITY_FLOOR) /
baseIntensity.coerceAtLeast(MERTENS_EV_INTENSITY_FLOOR))
} else {
0f
}
highlightEvEnergySum += (highlightAdjustmentEv * highlightAdjustmentEv * highlightMask).toDouble()
shadowEvEnergySum += (shadowAdjustmentEv * shadowAdjustmentEv * shadowMask).toDouble()
highlightWeightSum += highlightMask.toDouble()
shadowWeightSum += shadowMask.toDouble()
y += sampleStep
}
val sampleCount = sortedLumas.size.toFloat().coerceAtLeast(1f)
val highlightAdjustmentEv = if (highlightWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(highlightEvEnergySum / highlightWeightSum)
val sampleCount = sampledCount.toDouble().coerceAtLeast(1.0)
val highlightFusionDelta = if (highlightWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(highlightDeltaEnergySum / highlightWeightSum)
.toFloat()
.coerceAtLeast(0f)
} else {
0f
}
val shadowAdjustmentEv = if (shadowWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(shadowEvEnergySum / shadowWeightSum)
val shadowFusionDelta = if (shadowWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(shadowDeltaEnergySum / shadowWeightSum)
.toFloat()
.coerceAtLeast(0f)
} else {
@@ -770,49 +1052,313 @@ object MeteringSystem {
}
return ExposureFusionToneStats(
highlightAdjustmentEv = highlightAdjustmentEv,
shadowAdjustmentEv = shadowAdjustmentEv,
highlightFusionDelta = highlightFusionDelta,
shadowFusionDelta = shadowFusionDelta,
highlightRegionWeight = (highlightWeightSum / sampleCount).toFloat().coerceIn(0f, 1f),
shadowRegionWeight = (shadowWeightSum / sampleCount).toFloat().coerceIn(0f, 1f)
shadowRegionWeight = (shadowWeightSum / sampleCount).toFloat().coerceIn(0f, 1f),
mertensContrastMean = (mertensContrastSum / sampleCount).toFloat().coerceAtLeast(0f),
mertensSaturationMean = (mertensSaturationSum / sampleCount).toFloat().coerceAtLeast(0f),
mertensWellExposednessMean = (mertensWellExposednessSum / sampleCount).toFloat().coerceIn(0f, 1f),
sampleCount = sampledCount,
sampleStep = sampleStep
)
}
private fun calculateVirtualMertensFusionIntensity(
baseLuma: Float,
targetLuma: Float
): Float {
val baseIntensity = linearLumaToExposureFusionIntensity(
luma = baseLuma,
targetLuma = targetLuma
private fun emptyExposureFusionToneStats(): ExposureFusionToneStats {
return ExposureFusionToneStats(
highlightFusionDelta = 0f,
shadowFusionDelta = 0f,
highlightRegionWeight = 0f,
shadowRegionWeight = 0f,
mertensContrastMean = 0f,
mertensSaturationMean = 0f,
mertensWellExposednessMean = 0f,
sampleCount = 0,
sampleStep = 1
)
var weightedIntensitySum = 0.0
var weightSum = 0.0
for (ev in MERTENS_VIRTUAL_EXPOSURE_EVS) {
val virtualIntensity = linearLumaToExposureFusionIntensity(
luma = baseLuma * exp2(ev),
targetLuma = targetLuma
)
val weight = mertensWellExposedness(virtualIntensity)
weightedIntensitySum += (virtualIntensity * weight).toDouble()
weightSum += weight.toDouble()
}
private fun exposureFusionToneStatsFromGpu(stats: GpuRawAutoExposureToneStats): ExposureFusionToneStats {
if (stats.sampleCount <= 0) {
return emptyExposureFusionToneStats()
}
return if (weightSum > 0.0) {
val highlightFusionDelta = if (stats.highlightWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(stats.highlightDeltaEnergySum / stats.highlightWeightSum)
.toFloat()
.coerceAtLeast(0f)
} else {
0f
}
val shadowFusionDelta = if (stats.shadowWeightSum > MERTENS_MIN_TONE_WEIGHT) {
sqrt(stats.shadowDeltaEnergySum / stats.shadowWeightSum)
.toFloat()
.coerceAtLeast(0f)
} else {
0f
}
val sampleCount = stats.sampleCount.toDouble().coerceAtLeast(1.0)
return ExposureFusionToneStats(
highlightFusionDelta = highlightFusionDelta,
shadowFusionDelta = shadowFusionDelta,
highlightRegionWeight = (stats.highlightWeightSum / sampleCount).toFloat().coerceIn(0f, 1f),
shadowRegionWeight = (stats.shadowWeightSum / sampleCount).toFloat().coerceIn(0f, 1f),
mertensContrastMean = (stats.mertensContrastSum / sampleCount).toFloat().coerceAtLeast(0f),
mertensSaturationMean = (stats.mertensSaturationSum / sampleCount).toFloat().coerceAtLeast(0f),
mertensWellExposednessMean = (stats.mertensWellExposednessSum / sampleCount).toFloat().coerceIn(0f, 1f),
sampleCount = stats.sampleCount,
sampleStep = stats.sampleStep
)
}
private fun calculateMertensToneSampleStep(pixelCount: Int): Int {
if (pixelCount <= MERTENS_TONE_STATS_MAX_SAMPLES) {
return 1
}
var step = 1
while ((pixelCount + step * step - 1) / (step * step) > MERTENS_TONE_STATS_MAX_SAMPLES) {
step++
}
return step
}
private fun percentileFromLogHistogram(
histogram: IntArray,
percentile: Float,
logMin: Float,
logMax: Float
): Float {
if (histogram.isEmpty()) {
return 0f
}
var total = 0L
for (count in histogram) {
if (count > 0) {
total += count.toLong()
}
}
if (total <= 0L) {
return 0f
}
val targetIndex = ((total - 1L) * percentile.coerceIn(0f, 1f)).toLong()
var cumulative = 0L
for (i in histogram.indices) {
val count = histogram[i]
if (count <= 0) continue
cumulative += count.toLong()
if (cumulative > targetIndex) {
val fraction = (i + 0.5f) / histogram.size.toFloat()
val logLuma = logMin + (logMax - logMin) * fraction
return exp2(logLuma).coerceIn(0f, MAX_LINEAR_LUMA)
}
}
return exp2(logMax).coerceIn(0f, MAX_LINEAR_LUMA)
}
private fun buildMertensVirtualExposureScales(exposureScale: Float): FloatArray {
val scales = FloatArray(MERTENS_VIRTUAL_EXPOSURE_EVS.size)
for (i in MERTENS_VIRTUAL_EXPOSURE_EVS.indices) {
scales[i] = exposureScale * exp2(MERTENS_VIRTUAL_EXPOSURE_EVS[i])
}
return scales
}
private fun calculateVirtualMertensFusionIntensity(
source: LinearRgbImage,
index: Int,
baseIntensity: Float,
virtualExposureScales: FloatArray,
targetLuma: Float
): MertensVirtualExposureResult {
var weightedIntensitySum = 0.0
var weightSum = 0.0
var contrastSum = 0.0
var saturationSum = 0.0
var wellExposednessSum = 0.0
for (virtualExposureScale in virtualExposureScales) {
val virtualIntensity = calculateExposureFusionIntensity(
source = source,
index = index,
exposureScale = virtualExposureScale,
targetLuma = targetLuma
)
val weight = calculateMertensFusionWeight(
source = source,
index = index,
exposureScale = virtualExposureScale,
targetLuma = targetLuma
)
weightedIntensitySum += (virtualIntensity * weight.weight).toDouble()
weightSum += weight.weight.toDouble()
contrastSum += weight.contrast.toDouble()
saturationSum += weight.saturation.toDouble()
wellExposednessSum += weight.wellExposedness.toDouble()
}
val virtualExposureCount = MERTENS_VIRTUAL_EXPOSURE_EVS.size.toDouble().coerceAtLeast(1.0)
val intensity = if (weightSum > 0.0) {
(weightedIntensitySum / weightSum).toFloat().coerceIn(0f, 1f)
} else {
baseIntensity
}
return MertensVirtualExposureResult(
intensity = intensity,
contrastMean = (contrastSum / virtualExposureCount).toFloat().coerceAtLeast(0f),
saturationMean = (saturationSum / virtualExposureCount).toFloat().coerceAtLeast(0f),
wellExposednessMean = (wellExposednessSum / virtualExposureCount).toFloat().coerceIn(0f, 1f)
)
}
private fun calculateMertensFusionWeight(
source: LinearRgbImage,
index: Int,
exposureScale: Float,
targetLuma: Float
): MertensFusionWeight {
val r = linearLumaToExposureFusionIntensity(source.red[index] * exposureScale, targetLuma)
val g = linearLumaToExposureFusionIntensity(source.green[index] * exposureScale, targetLuma)
val b = linearLumaToExposureFusionIntensity(source.blue[index] * exposureScale, targetLuma)
val contrast = calculateMertensContrast(
source = source,
index = index,
exposureScale = exposureScale,
targetLuma = targetLuma
)
val saturation = calculateMertensSaturation(r, g, b)
val wellExposedness = (mertensWellExposedness(r) *
mertensWellExposedness(g) *
mertensWellExposedness(b))
.coerceIn(0f, 1f)
val contrastWeight = mertensWeightComponent(
value = contrast,
exponent = MERTENS_CONTRAST_WEIGHT_EXPONENT
)
val saturationWeight = mertensWeightComponent(
value = saturation,
exponent = MERTENS_SATURATION_WEIGHT_EXPONENT
)
val exposureWeight = mertensWeightComponent(
value = wellExposedness,
exponent = MERTENS_EXPOSURE_WEIGHT_EXPONENT
)
val weight = (contrastWeight * saturationWeight * exposureWeight)
.takeIf { it.isFinite() && it > 0f }
?: 0f
return MertensFusionWeight(
weight = weight,
contrast = contrast,
saturation = saturation,
wellExposedness = wellExposedness
)
}
private fun mertensWeightComponent(
value: Float,
exponent: Float
): Float {
if (exponent <= 0f) {
return 1f
}
val safeValue = if (value.isFinite()) value.coerceAtLeast(0f) else 0f
if (exponent == 1f) {
return safeValue
}
return safeValue
.pow(exponent)
.takeIf { it.isFinite() && it >= 0f }
?: 0f
}
private fun calculateExposureFusionIntensity(
source: LinearRgbImage,
index: Int,
exposureScale: Float,
targetLuma: Float
): Float {
val r = linearLumaToExposureFusionIntensity(source.red[index] * exposureScale, targetLuma)
val g = linearLumaToExposureFusionIntensity(source.green[index] * exposureScale, targetLuma)
val b = linearLumaToExposureFusionIntensity(source.blue[index] * exposureScale, targetLuma)
return (r * 0.2126f + g * 0.7152f + b * 0.0722f).coerceIn(0f, 1f)
}
private fun calculateMertensContrast(
source: LinearRgbImage,
index: Int,
exposureScale: Float,
targetLuma: Float
): Float {
if (source.width <= 0 || source.height <= 0) {
return 0f
}
val x = index % source.width
val y = index / source.width
val center = calculateExposureFusionIntensityAt(source, x, y, exposureScale, targetLuma)
val left = calculateExposureFusionIntensityAt(source, x - 1, y, exposureScale, targetLuma)
val right = calculateExposureFusionIntensityAt(source, x + 1, y, exposureScale, targetLuma)
val up = calculateExposureFusionIntensityAt(source, x, y - 1, exposureScale, targetLuma)
val down = calculateExposureFusionIntensityAt(source, x, y + 1, exposureScale, targetLuma)
return abs(left + right + up + down - center * 4f).coerceAtLeast(0f)
}
private fun calculateExposureFusionIntensityAt(
source: LinearRgbImage,
x: Int,
y: Int,
exposureScale: Float,
targetLuma: Float
): Float {
val sampleX = reflect101(x, source.width)
val sampleY = reflect101(y, source.height)
return calculateExposureFusionIntensity(
source = source,
index = sampleY * source.width + sampleX,
exposureScale = exposureScale,
targetLuma = targetLuma
)
}
private fun calculateMertensSaturation(
r: Float,
g: Float,
b: Float
): Float {
val mean = (r + g + b) / 3f
val dr = r - mean
val dg = g - mean
val db = b - mean
return sqrt((dr * dr + dg * dg + db * db).toDouble())
.toFloat()
.coerceAtLeast(0f)
}
private fun reflect101(position: Int, size: Int): Int {
if (size <= 1) {
return 0
}
val period = size * 2 - 2
var value = position
if (value < 0) {
value = -value
}
value %= period
return if (value >= size) period - value else value
}
private fun linearLumaToExposureFusionIntensity(
luma: Float,
targetLuma: Float
): Float {
if (!luma.isFinite()) {
return 0f
}
val safeTarget = targetLuma.coerceAtLeast(LUMA_FLOOR)
return (sanitizeLinearLuma(luma) / (safeTarget * 2f)).coerceIn(0f, 1f)
return (sanitizeLinearLuma(luma) / (safeTarget * MERTENS_TARGET_TO_MID_INTENSITY_SCALE))
.coerceIn(0f, 1f)
}
private fun mertensWellExposedness(intensity: Float): Float {
@@ -821,9 +1367,8 @@ object MeteringSystem {
return exp((-0.5f * offset * offset / sigma2).toDouble()).toFloat().coerceIn(0f, 1f)
}
private fun calculateAutoHighlightCompression(highlightAdjustmentEv: Float): Float {
return (highlightAdjustmentEv / RAW_AUTO_FULL_ADJUSTMENT_EV)
.coerceIn(0f, RAW_AUTO_HIGHLIGHT_LIMIT)
private fun calculateAutoHighlightCompression(highlightFusionDelta: Float): Float {
return highlightFusionDelta.coerceIn(0f, RAW_AUTO_HIGHLIGHT_LIMIT)
}
private fun resolveAutoShadowLimit(baselineExposure: Float): Float {
@@ -843,7 +1388,7 @@ object MeteringSystem {
stats: ExposureFusionToneStats,
shadowLimit: Float
): Float {
return (stats.shadowAdjustmentEv / RAW_AUTO_FULL_ADJUSTMENT_EV)
return stats.shadowFusionDelta
.coerceIn(0f, shadowLimit.coerceAtLeast(0f))
}
@@ -12,6 +12,7 @@ import android.opengl.EGLDisplay
import android.opengl.EGLSurface
import android.opengl.GLES30
import android.opengl.GLES31
import android.opengl.GLUtils
import android.util.Half
import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.camera.AspectRatio
@@ -165,6 +166,14 @@ class RawDemosaicProcessor {
private const val RCD_VH_DIR_BINDING = 4
private const val RCD_HIGHLIGHT_RECONSTRUCTION_THRESHOLD = 0.985f
private const val RCD_HIGHLIGHT_RECONSTRUCTION_CEILING = 8.0f
private const val RAW_AE_LOCAL_SIZE_X = 16
private const val RAW_AE_LOCAL_SIZE_Y = 16
private const val RAW_AE_HISTOGRAM_BINS = 256
private const val RAW_AE_HISTOGRAM_LOG_MIN = -10f
private const val RAW_AE_HISTOGRAM_LOG_MAX = 4f
private const val RAW_AE_HISTOGRAM_BINDING = 0
private const val RAW_AE_BASE_STATS_BINDING = 1
private const val RAW_AE_TONE_STATS_BINDING = 0
init {
// 加载 JNI 库
@@ -210,6 +219,8 @@ class RawDemosaicProcessor {
private var rcdStep43Program = 0
private var rcdWriteOutputProgram = 0
private var linearRcdProgram = 0
private var rawAeBaseProgram = 0
private var rawAeMertensProgram = 0
private var rawTextureId = 0
@@ -1410,6 +1421,318 @@ class RawDemosaicProcessor {
}
""".trimIndent()
private val RAW_AE_BASE_COMPUTE_SHADER = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
const int HISTOGRAM_BINS = 256;
const int LOCAL_SIZE = 256;
const float LUMA_FLOOR = 0.001;
const float MAX_LINEAR_LUMA = 16.0;
const float LOG_LUMA_MIN = -10.0;
const float LOG_LUMA_MAX = 4.0;
uniform sampler2D uLinearTexture;
uniform sampler2D uDepthTexture;
uniform ivec2 uImageSize;
uniform int uGroupsX;
uniform int uUseDepthWeight;
layout(std430, binding = 0) buffer HistogramOut {
uint histogram[];
};
layout(std430, binding = 1) buffer BaseStatsOut {
vec4 baseStats[];
};
shared uint localHistogram[HISTOGRAM_BINS];
shared vec4 localStats[LOCAL_SIZE];
float smoothStepRaw(float edge0, float edge1, float x) {
float width = edge1 - edge0;
if (abs(width) < 0.000001) {
return x >= edge1 ? 1.0 : 0.0;
}
float t = clamp((x - edge0) / width, 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
float sanitizeLuma(float value, out float sanitized) {
sanitized = 0.0;
if (!(value >= 0.0)) {
sanitized = 1.0;
return 0.0;
}
if (value > MAX_LINEAR_LUMA) {
sanitized = 1.0;
return MAX_LINEAR_LUMA;
}
return value;
}
float centerWeight(vec2 uv) {
vec2 d = (uv - vec2(0.5)) / 0.32;
float gaussian = exp(-0.5 * dot(d, d));
return 0.35 + gaussian * 0.65;
}
float depthWeight(vec2 uv) {
if (uUseDepthWeight == 0) {
return 1.0;
}
float depth = texture(uDepthTexture, uv).r;
float separation = abs(depth - 0.5) / 0.5;
float saliency = smoothStepRaw(0.18, 0.88, separation);
return mix(0.88, 1.55, saliency);
}
void main() {
int localIndex = int(gl_LocalInvocationIndex);
if (localIndex < HISTOGRAM_BINS) {
localHistogram[localIndex] = 0u;
}
localStats[localIndex] = vec4(0.0);
barrier();
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x < uImageSize.x && coord.y < uImageSize.y) {
vec3 rgb = texelFetch(uLinearTexture, coord, 0).rgb;
float sanitized = 0.0;
float luma = sanitizeLuma(dot(rgb, vec3(0.2126, 0.7152, 0.0722)), sanitized);
float safeLuma = max(luma, LUMA_FLOOR);
float logLuma = log2(safeLuma);
float histogramT = clamp((logLuma - LOG_LUMA_MIN) / (LOG_LUMA_MAX - LOG_LUMA_MIN), 0.0, 0.999999);
int bin = int(histogramT * float(HISTOGRAM_BINS));
atomicAdd(localHistogram[bin], 1u);
vec2 uv = (vec2(coord) + vec2(0.5)) / vec2(uImageSize);
float weight = centerWeight(uv) * depthWeight(uv);
localStats[localIndex] = vec4(logLuma * weight, weight, 1.0, sanitized);
}
barrier();
for (int stride = LOCAL_SIZE / 2; stride > 0; stride = stride / 2) {
if (localIndex < stride) {
localStats[localIndex] += localStats[localIndex + stride];
}
barrier();
}
int groupIndex = int(gl_WorkGroupID.y) * uGroupsX + int(gl_WorkGroupID.x);
if (localIndex == 0) {
baseStats[groupIndex] = localStats[0];
}
if (localIndex < HISTOGRAM_BINS) {
histogram[groupIndex * HISTOGRAM_BINS + localIndex] = localHistogram[localIndex];
}
}
""".trimIndent()
private val RAW_AE_MERTENS_COMPUTE_SHADER = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
const int LOCAL_SIZE = 256;
const float LUMA_FLOOR = 0.001;
const float MAX_LINEAR_LUMA = 16.0;
const float MERTENS_TARGET_TO_MID_INTENSITY_SCALE = 2.0;
const float MERTENS_WELL_EXPOSED_CENTER = 0.5;
const float MERTENS_WELL_EXPOSED_SIGMA = 0.2;
const float MERTENS_SHADOW_MASK_START = 0.04;
const float MERTENS_SHADOW_MASK_END = 0.45;
const float MERTENS_HIGHLIGHT_MASK_START = 0.55;
const float MERTENS_HIGHLIGHT_MASK_END = 0.92;
uniform sampler2D uLinearTexture;
uniform ivec2 uImageSize;
uniform int uGroupsX;
uniform int uSampleStep;
uniform int uSampleOffset;
uniform float uExposureScale;
uniform float uTargetLuma;
layout(std430, binding = 0) buffer ToneStatsOut {
vec4 toneStats[];
};
shared vec4 localToneA[LOCAL_SIZE];
shared vec4 localToneB[LOCAL_SIZE];
float smoothStepRaw(float edge0, float edge1, float x) {
float width = edge1 - edge0;
if (abs(width) < 0.000001) {
return x >= edge1 ? 1.0 : 0.0;
}
float t = clamp((x - edge0) / width, 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
float sanitizeLinearLuma(float value) {
if (!(value >= 0.0)) {
return 0.0;
}
return clamp(value, 0.0, MAX_LINEAR_LUMA);
}
int reflect101(int position, int size) {
if (size <= 1) {
return 0;
}
int period = size * 2 - 2;
int value = position;
if (value < 0) {
value = -value;
}
value = value - (value / period) * period;
return value >= size ? period - value : value;
}
vec3 exposureFusionRgb(ivec2 coord, float exposureScale) {
vec3 rgb = texelFetch(uLinearTexture, coord, 0).rgb * exposureScale;
float divisor = max(uTargetLuma, LUMA_FLOOR) * MERTENS_TARGET_TO_MID_INTENSITY_SCALE;
return clamp(vec3(
sanitizeLinearLuma(rgb.r) / divisor,
sanitizeLinearLuma(rgb.g) / divisor,
sanitizeLinearLuma(rgb.b) / divisor
), vec3(0.0), vec3(1.0));
}
float exposureFusionIntensityAt(int x, int y, float exposureScale) {
ivec2 coord = ivec2(
reflect101(x, uImageSize.x),
reflect101(y, uImageSize.y)
);
vec3 rgb = exposureFusionRgb(coord, exposureScale);
return clamp(dot(rgb, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0);
}
float exposureFusionIntensity(ivec2 coord, float exposureScale) {
vec3 rgb = exposureFusionRgb(coord, exposureScale);
return clamp(dot(rgb, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0);
}
float mertensContrast(ivec2 coord, float exposureScale) {
int x = coord.x;
int y = coord.y;
float center = exposureFusionIntensityAt(x, y, exposureScale);
float left = exposureFusionIntensityAt(x - 1, y, exposureScale);
float right = exposureFusionIntensityAt(x + 1, y, exposureScale);
float up = exposureFusionIntensityAt(x, y - 1, exposureScale);
float down = exposureFusionIntensityAt(x, y + 1, exposureScale);
return max(abs(left + right + up + down - center * 4.0), 0.0);
}
float mertensSaturation(vec3 rgb) {
float mean = (rgb.r + rgb.g + rgb.b) / 3.0;
vec3 delta = rgb - vec3(mean);
return max(sqrt(dot(delta, delta)), 0.0);
}
float mertensWellExposedness(float intensity) {
float offset = clamp(intensity, 0.0, 1.0) - MERTENS_WELL_EXPOSED_CENTER;
float sigma2 = MERTENS_WELL_EXPOSED_SIGMA * MERTENS_WELL_EXPOSED_SIGMA;
return clamp(exp(-0.5 * offset * offset / sigma2), 0.0, 1.0);
}
vec4 mertensWeight(ivec2 coord, float exposureScale) {
vec3 rgb = exposureFusionRgb(coord, exposureScale);
float contrast = mertensContrast(coord, exposureScale);
float saturation = mertensSaturation(rgb);
float wellExposedness = clamp(
mertensWellExposedness(rgb.r) *
mertensWellExposedness(rgb.g) *
mertensWellExposedness(rgb.b),
0.0,
1.0
);
float weight = contrast * saturation * wellExposedness;
if (!(weight > 0.0)) {
weight = 0.0;
}
return vec4(weight, contrast, saturation, wellExposedness);
}
void main() {
int localIndex = int(gl_LocalInvocationIndex);
localToneA[localIndex] = vec4(0.0);
localToneB[localIndex] = vec4(0.0);
ivec2 sampleCoord = ivec2(gl_GlobalInvocationID.xy) * uSampleStep + ivec2(uSampleOffset);
if (sampleCoord.x < uImageSize.x && sampleCoord.y < uImageSize.y) {
float baseIntensity = exposureFusionIntensity(sampleCoord, uExposureScale);
float weightedIntensitySum = 0.0;
float weightSum = 0.0;
float contrastSum = 0.0;
float saturationSum = 0.0;
float wellExposednessSum = 0.0;
for (int i = 0; i < 5; i++) {
float ev = float(i) - 2.0;
float virtualExposureScale = uExposureScale * exp2(ev);
float virtualIntensity = exposureFusionIntensity(sampleCoord, virtualExposureScale);
vec4 weight = mertensWeight(sampleCoord, virtualExposureScale);
weightedIntensitySum += virtualIntensity * weight.x;
weightSum += weight.x;
contrastSum += weight.y;
saturationSum += weight.z;
wellExposednessSum += weight.w;
}
float fusedIntensity = weightSum > 0.0
? clamp(weightedIntensitySum / weightSum, 0.0, 1.0)
: baseIntensity;
float fusionDelta = fusedIntensity - baseIntensity;
float highlightMask = smoothStepRaw(
MERTENS_HIGHLIGHT_MASK_START,
MERTENS_HIGHLIGHT_MASK_END,
baseIntensity
);
float shadowMask = 1.0 - smoothStepRaw(
MERTENS_SHADOW_MASK_START,
MERTENS_SHADOW_MASK_END,
baseIntensity
);
float highlightFusionDelta = fusionDelta < 0.0 ? -fusionDelta : 0.0;
float shadowFusionDelta = fusionDelta > 0.0 ? fusionDelta : 0.0;
localToneA[localIndex] = vec4(
highlightFusionDelta * highlightFusionDelta * highlightMask,
shadowFusionDelta * shadowFusionDelta * shadowMask,
highlightMask,
shadowMask
);
localToneB[localIndex] = vec4(
contrastSum / 5.0,
saturationSum / 5.0,
wellExposednessSum / 5.0,
1.0
);
}
barrier();
for (int stride = LOCAL_SIZE / 2; stride > 0; stride = stride / 2) {
if (localIndex < stride) {
localToneA[localIndex] += localToneA[localIndex + stride];
localToneB[localIndex] += localToneB[localIndex + stride];
}
barrier();
}
if (localIndex == 0) {
int groupIndex = int(gl_WorkGroupID.y) * uGroupsX + int(gl_WorkGroupID.x);
toneStats[groupIndex * 2] = localToneA[0];
toneStats[groupIndex * 2 + 1] = localToneB[0];
}
}
""".trimIndent()
private fun initRcdPrograms(vShader: Int) {
rcdPopulateProgram = compileComputeProgram(RcdShaders.POPULATE, "POPULATE")
rcdStep1Program = compileComputeProgram(RcdShaders.STEP_1, "STEP_1")
@@ -1420,6 +1743,8 @@ class RawDemosaicProcessor {
rcdStep42Program = compileComputeProgram(RcdShaders.STEP_4_2, "STEP_4_2")
rcdStep43Program = compileComputeProgram(RcdShaders.STEP_4_3, "STEP_4_3")
rcdWriteOutputProgram = compileComputeProgram(RcdShaders.WRITE_OUTPUT, "WRITE_OUTPUT")
rawAeBaseProgram = compileComputeProgram(RAW_AE_BASE_COMPUTE_SHADER, "RAW_AE_BASE")
rawAeMertensProgram = compileComputeProgram(RAW_AE_MERTENS_COMPUTE_SHADER, "RAW_AE_MERTENS")
val fShaderLinearRcd = compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_LINEAR_RCD)
if (vShader != 0 && fShaderLinearRcd != 0) {
@@ -3669,52 +3994,56 @@ class RawDemosaicProcessor {
dcpRenderPlan = dcpRenderPlan,
label = "LinearMeteringPass"
)
val buffer = LargeDirectBuffer.allocate(
meteringWidth.toLong() * meteringHeight.toLong() * 4L * 2L,
"RAW auto exposure metering"
) ?: return MeteringSystem.MeteringResult.EMPTY
var weightBuffer: ByteBuffer? = null
var bitmap: Bitmap? = null
var depthMap: Bitmap? = null
var depthTextureId = 0
try {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearMeteringFramebufferId)
GLES30.glReadPixels(
0,
0,
meteringWidth,
meteringHeight,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
buffer
)
checkGlError("resolveRawAutoExposureEv")
buffer.position(0)
val linearPixels = buffer.asShortBuffer()
if (useDepthWeighting) {
// Calculate depth weighting from a display-encoded preview, while AE uses linear RAW luma.
bitmap = createLinearMeteringPreviewBitmap(linearPixels, meteringWidth, meteringHeight)
depthMap = SharedDepthEstimator.estimateDepth(context, bitmap)
weightBuffer = depthMap?.let {
val wb = LargeDirectBuffer.allocate(
it.byteCount.toLong(),
"RAW auto exposure depth weight"
val depthPreviewBuffer = LargeDirectBuffer.allocate(
meteringWidth.toLong() * meteringHeight.toLong() * 4L * 2L,
"RAW auto exposure depth preview"
) ?: return MeteringSystem.MeteringResult.EMPTY
try {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearMeteringFramebufferId)
GLES30.glReadPixels(
0,
0,
meteringWidth,
meteringHeight,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
depthPreviewBuffer
)
?: return@let null
it.copyPixelsToBuffer(wb)
wb.position(0)
wb
checkGlError("resolveRawAutoExposureEv depth preview")
depthPreviewBuffer.position(0)
bitmap = createLinearMeteringPreviewBitmap(
depthPreviewBuffer.asShortBuffer(),
meteringWidth,
meteringHeight
)
} finally {
LargeDirectBuffer.free(depthPreviewBuffer)
}
depthMap = SharedDepthEstimator.estimateDepth(context, bitmap)
depthTextureId = depthMap?.let {
uploadRawAutoExposureDepthTexture(it)
} ?: 0
if (depthTextureId == 0) {
PLog.w(TAG, "RAW AE depth weighting skipped: depth texture unavailable")
}
}
val meteringResult = MeteringSystem.analyzeLinearHalfFloatExposureEv(
pixelBuffer = linearPixels,
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT
)
val meteringResult = resolveRawAutoExposureEvGpu(
linearTextureId = linearMeteringTextureId,
width = meteringWidth,
height = meteringHeight,
weightBuffer = weightBuffer,
depthTextureId = depthTextureId,
baselineExposure = metadata.baselineExposure
)
) ?: MeteringSystem.MeteringResult.EMPTY
if (depthMap != null && !depthMap.isRecycled) {
depthMap.recycle()
@@ -3724,14 +4053,15 @@ class RawDemosaicProcessor {
}
meteringResult
} finally {
if (depthTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(depthTextureId), 0)
}
if (depthMap != null && !depthMap.isRecycled) {
depthMap.recycle()
}
if (bitmap != null && !bitmap.isRecycled) {
bitmap.recycle()
}
LargeDirectBuffer.free(weightBuffer)
LargeDirectBuffer.free(buffer)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to resolve RAW auto exposure", e)
@@ -3739,6 +4069,342 @@ class RawDemosaicProcessor {
}
}
private fun resolveRawAutoExposureEvGpu(
linearTextureId: Int,
width: Int,
height: Int,
depthTextureId: Int,
baselineExposure: Float
): MeteringSystem.MeteringResult? {
if (rawAeBaseProgram == 0 || rawAeMertensProgram == 0) {
PLog.e(
TAG,
"RAW AE GPU programs unavailable: base=$rawAeBaseProgram mertens=$rawAeMertensProgram"
)
return null
}
val baseStats = dispatchRawAeBaseStats(
linearTextureId = linearTextureId,
width = width,
height = height,
depthTextureId = depthTextureId
) ?: return null
val plan = MeteringSystem.prepareGpuLinearRawAutoExposure(
stats = baseStats,
baselineExposure = baselineExposure,
tag = "Linear RAW AE GPU"
) ?: return null
val toneStats = dispatchRawAeMertensStats(
linearTextureId = linearTextureId,
width = width,
height = height,
plan = plan
) ?: return null
return MeteringSystem.finishGpuLinearRawAutoExposure(plan, toneStats)
}
private fun dispatchRawAeBaseStats(
linearTextureId: Int,
width: Int,
height: Int,
depthTextureId: Int
): MeteringSystem.GpuRawAutoExposureBaseStats? {
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 groupCount = (groupsX * groupsY).coerceAtLeast(1)
val histogramByteCount = groupCount * RAW_AE_HISTOGRAM_BINS * 4
val baseStatsByteCount = groupCount * 4 * 4
val buffers = IntArray(2)
GLES31.glGenBuffers(2, buffers, 0)
return try {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[0])
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
histogramByteCount,
null,
GLES31.GL_DYNAMIC_READ
)
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
RAW_AE_HISTOGRAM_BINDING,
buffers[0]
)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[1])
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
baseStatsByteCount,
null,
GLES31.GL_DYNAMIC_READ
)
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
RAW_AE_BASE_STATS_BINDING,
buffers[1]
)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glUseProgram(rawAeBaseProgram)
bindComputeSampler(rawAeBaseProgram, "uLinearTexture", 0, linearTextureId)
bindComputeSampler(rawAeBaseProgram, "uDepthTexture", 1, depthTextureId)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(rawAeBaseProgram, "uImageSize"),
width,
height
)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rawAeBaseProgram, "uGroupsX"), groupsX)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(rawAeBaseProgram, "uUseDepthWeight"),
if (depthTextureId != 0) 1 else 0
)
GLES31.glDispatchCompute(groupsX, groupsY, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
)
checkGlError("RAW AE base stats")
readRawAeBaseStats(
histogramBufferId = buffers[0],
baseStatsBufferId = buffers[1],
histogramByteCount = histogramByteCount,
baseStatsByteCount = baseStatsByteCount,
groupCount = groupCount
)
} finally {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, RAW_AE_HISTOGRAM_BINDING, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, RAW_AE_BASE_STATS_BINDING, 0)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glDeleteBuffers(2, buffers, 0)
}
}
private fun readRawAeBaseStats(
histogramBufferId: Int,
baseStatsBufferId: Int,
histogramByteCount: Int,
baseStatsByteCount: Int,
groupCount: Int
): MeteringSystem.GpuRawAutoExposureBaseStats? {
val histogram = IntArray(RAW_AE_HISTOGRAM_BINS)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBufferId)
val mappedHistogram = GLES31.glMapBufferRange(
GLES31.GL_SHADER_STORAGE_BUFFER,
0,
histogramByteCount,
GLES31.GL_MAP_READ_BIT
) as? ByteBuffer
if (mappedHistogram == null) {
PLog.e(TAG, "RAW AE base histogram map failed")
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return null
}
mappedHistogram.order(ByteOrder.nativeOrder())
val histogramInts = mappedHistogram.asIntBuffer()
for (group in 0 until groupCount) {
val groupOffset = group * RAW_AE_HISTOGRAM_BINS
for (bin in 0 until RAW_AE_HISTOGRAM_BINS) {
histogram[bin] += histogramInts.get(groupOffset + bin)
}
}
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, baseStatsBufferId)
val mappedBaseStats = GLES31.glMapBufferRange(
GLES31.GL_SHADER_STORAGE_BUFFER,
0,
baseStatsByteCount,
GLES31.GL_MAP_READ_BIT
) as? ByteBuffer
if (mappedBaseStats == null) {
PLog.e(TAG, "RAW AE base stats map failed")
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return null
}
mappedBaseStats.order(ByteOrder.nativeOrder())
val baseFloats = mappedBaseStats.asFloatBuffer()
var weightedLogLumaSum = 0.0
var weightSum = 0.0
var sampleCount = 0
var sanitizedSampleCount = 0
for (group in 0 until groupCount) {
val base = group * 4
weightedLogLumaSum += baseFloats.get(base).toDouble()
weightSum += baseFloats.get(base + 1).toDouble()
sampleCount += baseFloats.get(base + 2).toInt()
sanitizedSampleCount += baseFloats.get(base + 3).toInt()
}
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return MeteringSystem.GpuRawAutoExposureBaseStats(
histogram = histogram,
histogramLogMin = RAW_AE_HISTOGRAM_LOG_MIN,
histogramLogMax = RAW_AE_HISTOGRAM_LOG_MAX,
weightedLogLumaSum = weightedLogLumaSum,
weightSum = weightSum,
sampleCount = sampleCount,
sanitizedSampleCount = sanitizedSampleCount,
groupCount = groupCount
)
}
private fun dispatchRawAeMertensStats(
linearTextureId: Int,
width: Int,
height: Int,
plan: MeteringSystem.GpuRawAutoExposurePlan
): MeteringSystem.GpuRawAutoExposureToneStats? {
val sampleStep = plan.sampleStep.coerceAtLeast(1)
val sampleOffset = (sampleStep / 2).coerceAtMost(minOf(width, height) - 1)
val sampleGridWidth = sampledGridSize(width, sampleStep, sampleOffset)
val sampleGridHeight = sampledGridSize(height, sampleStep, sampleOffset)
if (sampleGridWidth <= 0 || sampleGridHeight <= 0) {
PLog.e(TAG, "RAW AE Mertens sample grid is empty: ${sampleGridWidth}x$sampleGridHeight")
return null
}
val groupsX = roundUp(sampleGridWidth, RAW_AE_LOCAL_SIZE_X) / RAW_AE_LOCAL_SIZE_X
val groupsY = roundUp(sampleGridHeight, RAW_AE_LOCAL_SIZE_Y) / RAW_AE_LOCAL_SIZE_Y
val groupCount = (groupsX * groupsY).coerceAtLeast(1)
val toneStatsByteCount = groupCount * 2 * 4 * 4
val buffers = IntArray(1)
GLES31.glGenBuffers(1, buffers, 0)
return try {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[0])
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
toneStatsByteCount,
null,
GLES31.GL_DYNAMIC_READ
)
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
RAW_AE_TONE_STATS_BINDING,
buffers[0]
)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glUseProgram(rawAeMertensProgram)
bindComputeSampler(rawAeMertensProgram, "uLinearTexture", 0, linearTextureId)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(rawAeMertensProgram, "uImageSize"),
width,
height
)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rawAeMertensProgram, "uGroupsX"), groupsX)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(rawAeMertensProgram, "uSampleStep"),
sampleStep
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(rawAeMertensProgram, "uSampleOffset"),
sampleOffset
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(rawAeMertensProgram, "uExposureScale"),
plan.compensatedExposureScale
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(rawAeMertensProgram, "uTargetLuma"),
plan.targetLuma
)
GLES31.glDispatchCompute(groupsX, groupsY, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
)
checkGlError("RAW AE Mertens stats")
readRawAeMertensStats(
toneStatsBufferId = buffers[0],
toneStatsByteCount = toneStatsByteCount,
groupCount = groupCount,
sampleStep = sampleStep
)
} finally {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, RAW_AE_TONE_STATS_BINDING, 0)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glDeleteBuffers(1, buffers, 0)
}
}
private fun readRawAeMertensStats(
toneStatsBufferId: Int,
toneStatsByteCount: Int,
groupCount: Int,
sampleStep: Int
): MeteringSystem.GpuRawAutoExposureToneStats? {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, toneStatsBufferId)
val mappedToneStats = GLES31.glMapBufferRange(
GLES31.GL_SHADER_STORAGE_BUFFER,
0,
toneStatsByteCount,
GLES31.GL_MAP_READ_BIT
) as? ByteBuffer
if (mappedToneStats == null) {
PLog.e(TAG, "RAW AE Mertens stats map failed")
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return null
}
mappedToneStats.order(ByteOrder.nativeOrder())
val toneFloats = mappedToneStats.asFloatBuffer()
var highlightDeltaEnergySum = 0.0
var shadowDeltaEnergySum = 0.0
var highlightWeightSum = 0.0
var shadowWeightSum = 0.0
var mertensContrastSum = 0.0
var mertensSaturationSum = 0.0
var mertensWellExposednessSum = 0.0
var sampleCount = 0
for (group in 0 until groupCount) {
val base = group * 8
highlightDeltaEnergySum += toneFloats.get(base).toDouble()
shadowDeltaEnergySum += toneFloats.get(base + 1).toDouble()
highlightWeightSum += toneFloats.get(base + 2).toDouble()
shadowWeightSum += toneFloats.get(base + 3).toDouble()
mertensContrastSum += toneFloats.get(base + 4).toDouble()
mertensSaturationSum += toneFloats.get(base + 5).toDouble()
mertensWellExposednessSum += toneFloats.get(base + 6).toDouble()
sampleCount += toneFloats.get(base + 7).toInt()
}
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return MeteringSystem.GpuRawAutoExposureToneStats(
highlightDeltaEnergySum = highlightDeltaEnergySum,
shadowDeltaEnergySum = shadowDeltaEnergySum,
highlightWeightSum = highlightWeightSum,
shadowWeightSum = shadowWeightSum,
mertensContrastSum = mertensContrastSum,
mertensSaturationSum = mertensSaturationSum,
mertensWellExposednessSum = mertensWellExposednessSum,
sampleCount = sampleCount,
sampleStep = sampleStep,
groupCount = groupCount
)
}
private fun sampledGridSize(size: Int, sampleStep: Int, sampleOffset: Int): Int {
if (size <= 0 || sampleStep <= 0 || sampleOffset >= size) {
return 0
}
return ((size - 1 - sampleOffset) / sampleStep) + 1
}
private fun uploadRawAutoExposureDepthTexture(depthMap: Bitmap): Int {
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
val textureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, depthMap, 0)
checkGlError("uploadRawAutoExposureDepthTexture")
return textureId
}
@SuppressLint("HalfFloat")
private fun createLinearMeteringPreviewBitmap(
linearPixels: ShortBuffer,
@@ -4017,6 +4683,8 @@ class RawDemosaicProcessor {
if (rcdStep43Program != 0) GLES31.glDeleteProgram(rcdStep43Program)
if (rcdWriteOutputProgram != 0) GLES31.glDeleteProgram(rcdWriteOutputProgram)
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
if (rawAeBaseProgram != 0) GLES31.glDeleteProgram(rawAeBaseProgram)
if (rawAeMertensProgram != 0) GLES31.glDeleteProgram(rawAeMertensProgram)
// darktable denoiseprofile compute programs
if (denoisePreconditionY0U0V0Program != 0) GLES31.glDeleteProgram(
@@ -682,6 +682,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
viewModelScope.launch {
GalleryManager.photoMetadataUpdatedEvents.collect { update ->
applyPhotoMetadataUpdateToMemory(update.photoId, update.metadata)
}
}
// 订阅 ContentRepository 的 StateFlow,结合用户自定义排序
viewModelScope.launch {
contentRepository.availableLuts.combine(
@@ -908,10 +914,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
fun refreshLatestPhoto() {
viewModelScope.launch {
val photo = repository.getLatestPhoto()
photo?.let {
_latestPhoto.value = it
if (_photos.value.none { existing -> existing.id == it.id }) {
_photos.value = listOf(it) + _photos.value
photo?.let { latest ->
_latestPhoto.value = latest
_photos.update { current ->
if (current.none { existing -> existing.id == latest.id }) {
listOf(latest) + current
} else {
current.map { existing -> if (existing.id == latest.id) latest else existing }
}
}
if (!isEditing && currentPhotoMetadataId == latest.id && latest.metadata != null) {
applyMetadataToEditState(latest.metadata)
}
}
if (!_isInitialized.value) {
@@ -921,6 +934,39 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
}
private fun applyPhotoMetadataUpdateToMemory(photoId: String, metadata: MediaMetadata) {
_photos.update { current ->
current.map { photo ->
if (photo.id == photoId) photo.copy(metadata = metadata) else photo
}
}
_latestPhoto.update { latest ->
if (latest?.id == photoId) latest.copy(metadata = metadata) else latest
}
val isCurrentPhoto = getCurrentPhoto()?.id == photoId
if (!isCurrentPhoto) return
val previousMetadata = currentMediaMetadata
val canRefreshRawDevelopState = rawDevelopEditStateMatches(previousMetadata)
currentPhotoMetadataId = photoId
currentMediaMetadata = metadata
if (!isEditing) {
applyMetadataToEditState(metadata)
} else if (canRefreshRawDevelopState) {
applyRawDevelopMetadataToEditState(metadata)
}
}
private fun rawDevelopEditStateMatches(metadata: MediaMetadata?): Boolean {
if (metadata == null) return false
return editRawExposureCompensation.value == (metadata.rawExposureCompensation ?: 0f) &&
editRawAutoExposure.value == (metadata.rawAutoExposure ?: true) &&
editRawHighlightsAdjustment.value == (metadata.rawHighlightsAdjustment ?: 0f) &&
editRawShadowsAdjustment.value == (metadata.rawShadowsAdjustment ?: 0f)
}
/**
* 导入从系统相册分享的照片
*/