feat: implement RAW Dynamic Range Optimization (DRO) with shadow lifting

This commit is contained in:
zhoubinjia committed 2026-05-12 13:27:47 +08:00
1 parent ae03a224d7
commit 3d1be62d74
19 files changed
+199 -88

No files matched your search

@@ -60,6 +60,7 @@ data class UserPreferences(
val rawNlmNoiseFactor: Float = 0f,
val rawExposureCompensation: Float = 0f,
val rawAutoExposure: Boolean = true,
val rawDROEnabled: Boolean = false,
val rawBlackPointCorrection: Float = 0f,
val rawWhitePointCorrection: Float = 0f,
val rawAutoWhiteBalanceEstimate: Boolean = false,
@@ -156,6 +157,7 @@ class UserPreferencesRepository(private val context: Context) {
private val RAW_NLM_NOISE_FACTOR_KEY = floatPreferencesKey("raw_nlm_noise_factor")
private val RAW_EXPOSURE_COMPENSATION_KEY = floatPreferencesKey("raw_exposure_compensation")
private val RAW_AUTO_EXPOSURE_KEY = booleanPreferencesKey("raw_auto_exposure")
private val RAW_DRO_ENABLED_KEY = booleanPreferencesKey("raw_dro_enabled")
private val RAW_BLACK_POINT_CORRECTION_KEY = floatPreferencesKey("raw_black_point_correction")
private val RAW_WHITE_POINT_CORRECTION_KEY = floatPreferencesKey("raw_white_point_correction")
private val RAW_AUTO_WHITE_BALANCE_ESTIMATE_KEY = booleanPreferencesKey("raw_auto_white_balance_estimate")
@@ -261,6 +263,7 @@ class UserPreferencesRepository(private val context: Context) {
rawNlmNoiseFactor = preferences[RAW_NLM_NOISE_FACTOR_KEY] ?: 0f,
rawExposureCompensation = preferences[RAW_EXPOSURE_COMPENSATION_KEY] ?: 0f,
rawAutoExposure = preferences[RAW_AUTO_EXPOSURE_KEY] ?: true,
rawDROEnabled = preferences[RAW_DRO_ENABLED_KEY] ?: false,
rawBlackPointCorrection = preferences[RAW_BLACK_POINT_CORRECTION_KEY] ?: 0f,
rawWhitePointCorrection = preferences[RAW_WHITE_POINT_CORRECTION_KEY] ?: 0f,
rawAutoWhiteBalanceEstimate = preferences[RAW_AUTO_WHITE_BALANCE_ESTIMATE_KEY] ?: false,
@@ -547,6 +550,12 @@ class UserPreferencesRepository(private val context: Context) {
}
}
suspend fun updateRawDROEnabled(enabled: Boolean) {
context.dataStore.edit { preferences ->
preferences[RAW_DRO_ENABLED_KEY] = enabled
}
}
suspend fun saveRawBlackPointCorrection(value: Float) {
context.dataStore.edit { preferences ->
preferences[RAW_BLACK_POINT_CORRECTION_KEY] = value
@@ -1181,6 +1181,7 @@ object GalleryManager {
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
rawDROEnabled = metadata.rawDROEnabled ?: false,
sharpeningValue = 0.4f,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
@@ -1740,6 +1741,7 @@ object GalleryManager {
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
rawDROEnabled = metadata.rawDROEnabled ?: false,
sharpeningValue = 0.4f,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
@@ -2654,6 +2656,7 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawDROEnabled = updatedMetadata.rawDROEnabled ?: false,
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
@@ -2767,6 +2770,7 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawDROEnabled = (updatedMetadata ?: metadata)?.rawDROEnabled ?: false,
sharpeningValue = 0.4f,
denoiseValue = (updatedMetadata ?: MediaMetadata()).rawDenoiseValue,
rawDcpId = updatedMetadata?.rawDcpId,
@@ -42,6 +42,7 @@ data class MediaMetadata(
val rawBlackPointCorrection: Float? = null,
val rawWhitePointCorrection: Float? = null,
val rawAutoWhiteBalanceEstimate: Boolean? = null,
val rawDROEnabled: Boolean? = null,
val rawDcpId: String? = null,
// 边框水印配置
val frameId: String? = null,
@@ -250,6 +251,7 @@ data class MediaMetadata(
rawBlackPointCorrection = if (obj.isNull("rawBlackPointCorrection")) null else obj.optDouble("rawBlackPointCorrection").toFloat(),
rawWhitePointCorrection = if (obj.isNull("rawWhitePointCorrection")) null else obj.optDouble("rawWhitePointCorrection").toFloat(),
rawAutoWhiteBalanceEstimate = if (obj.isNull("rawAutoWhiteBalanceEstimate")) null else obj.optBoolean("rawAutoWhiteBalanceEstimate"),
rawDROEnabled = if (obj.isNull("rawDROEnabled")) null else obj.optBoolean("rawDROEnabled"),
rawDcpId = if (obj.isNull("rawDcpId")) null else obj.optString("rawDcpId"),
rawBlackLevelMode = if (obj.isNull("rawBlackLevelMode")) null else obj.optString("rawBlackLevelMode"),
rawCustomBlackLevel = if (obj.isNull("rawCustomBlackLevel")) null else obj.optDouble("rawCustomBlackLevel").toFloat(),
@@ -63,6 +63,11 @@ class PhotoProcessor(
?: (userPreferencesRepository.userPreferences.firstOrNull()?.rawAutoExposure ?: true)
}
private suspend fun resolveRawDROEnabled(metadata: MediaMetadata): Boolean {
return metadata.rawDROEnabled
?: (userPreferencesRepository.userPreferences.firstOrNull()?.rawDROEnabled ?: false)
}
suspend fun prepareUltraHdrSource(
context: Context,
photoId: String,
@@ -445,6 +450,7 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawDROEnabled = resolveRawDROEnabled(metadata),
sharpeningValue = 0.4f,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
@@ -506,6 +512,7 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawDROEnabled = resolveRawDROEnabled(metadata),
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
)
@@ -7,7 +7,7 @@ import androidx.room.RoomDatabase
@Database(
entities = [GalleryMediaEntity::class],
version = 1,
version = 2,
exportSchema = false
)
@androidx.room.TypeConverters(GalleryConverters::class)
@@ -18,6 +18,12 @@ abstract class GalleryDatabase : RoomDatabase() {
@Volatile
private var INSTANCE: GalleryDatabase? = null
private val MIGRATION_1_2 = object : androidx.room.migration.Migration(1, 2) {
override fun migrate(db: androidx.sqlite.db.SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE gallery_media ADD COLUMN rawDROEnabled INTEGER")
}
}
fun getInstance(context: Context): GalleryDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
@@ -25,6 +31,7 @@ abstract class GalleryDatabase : RoomDatabase() {
GalleryDatabase::class.java,
"gallery_media.db"
)
.addMigrations(MIGRATION_1_2)
.build()
.also { INSTANCE = it }
}
@@ -105,5 +105,6 @@ data class GalleryMediaEntity(
val aiDenoiseStrength: Float?,
val rawBlackLevelMode: String?,
val rawCustomBlackLevel: Float?,
val rawDROEnabled: Boolean?,
val cameraId: String?
)
@@ -258,6 +258,7 @@ object GalleryMediaStore {
aiDenoiseStrength = metadata.aiDenoiseStrength,
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
rawDROEnabled = metadata.rawDROEnabled,
cameraId = metadata.cameraId
)
}
@@ -383,6 +384,7 @@ object GalleryMediaStore {
aiDenoiseStrength = aiDenoiseStrength,
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
rawDROEnabled = rawDROEnabled,
cameraId = cameraId
)
}
@@ -16,14 +16,21 @@ object MeteringSystem {
private const val DISPLAY_TARGET_LUMA = 0.46f
data class MeteringResult(
val meteredEv: Float,
val dynamicRangeGap: Float,
val avgLuma: Float,
val p998: Float
)
fun analyzeRenderedExposureEv(
byteBuffer: ByteBuffer,
width: Int,
height: Int,
weightBuffer: ByteBuffer? = null // Optional weight mask (e.g. depth map)
): Float {
): MeteringResult {
val pixelCount = width * height
if (pixelCount == 0) return 0f
if (pixelCount == 0) return MeteringResult(0f, 0f, 0f, 0f)
val lumas = FloatArray(pixelCount)
var weightedLumaSum = 0f
@@ -93,9 +100,14 @@ object MeteringSystem {
val meteredEv = log2(adaptiveGain.coerceIn(0.25f, 4.0f))
PLog.d("MeteringSystem", "Smart AE: p998=$p998 avg=$avgLuma midToneGain=$midToneGain highlightAnchorGain=$highlightAnchorGain gain=$adaptiveGain ev=$meteredEv")
PLog.d("MeteringSystem", "Smart AE: p998=$p998 avg=$avgLuma midToneGain=$midToneGain highlightAnchorGain=$highlightAnchorGain gain=$adaptiveGain ev=$meteredEv gap=$dynamicRangeGap")
return meteredEv.coerceIn(-2f, 2f)
return MeteringResult(
meteredEv = meteredEv.coerceIn(-2f, 2f),
dynamicRangeGap = dynamicRangeGap,
avgLuma = avgLuma,
p998 = p998
)
}
private fun percentile(sortedValues: FloatArray, percentile: Float): Float {
@@ -5,6 +5,7 @@ import android.graphics.Bitmap
import android.graphics.Rect
import android.media.Image
import android.opengl.*
import android.util.Log
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.ml.SharedDepthEstimator
@@ -26,6 +27,8 @@ import kotlin.math.pow
import kotlin.math.sqrt
import android.opengl.Matrix as GlMatrix
import androidx.core.graphics.createBitmap
import kotlin.math.ln
import kotlin.math.pow
/**
* RAW 图像解马赛克处理器
@@ -101,12 +104,14 @@ class RawDemosaicProcessor {
lensShadingMap = dngRawData.lensShadingMap,
lensShadingMapWidth = dngRawData.lensShadingMapWidth,
lensShadingMapHeight = dngRawData.lensShadingMapHeight,
baselineExposure = if (dngRawData.baselineExposure == 0f) (baseMetadata?.baselineExposure ?: 0f) else dngRawData.baselineExposure,
baselineExposure = if (dngRawData.baselineExposure == 0f) (baseMetadata?.baselineExposure
?: 0f) else dngRawData.baselineExposure,
exposureBias = if (dngRawData.exposureBias == 0f) {
if (baseMetadata != null && baseMetadata.exposureBias != 0f) baseMetadata.exposureBias else exposureBias
} else dngRawData.exposureBias,
iso = if (dngRawData.iso == 0) (baseMetadata?.iso ?: 100) else dngRawData.iso,
shutterSpeed = if (dngRawData.shutterSpeed == 0L) (baseMetadata?.shutterSpeed ?: 0L) else dngRawData.shutterSpeed,
shutterSpeed = if (dngRawData.shutterSpeed == 0L) (baseMetadata?.shutterSpeed
?: 0L) else dngRawData.shutterSpeed,
aperture = if (dngRawData.aperture == 0f) (baseMetadata?.aperture ?: 0f) else dngRawData.aperture,
activeArray = activeArray,
noiseProfile = dngRawData.noiseProfile ?: baseMetadata?.noiseProfile ?: floatArrayOf(0f, 0f),
@@ -273,6 +278,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawDROEnabled: Boolean = false,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -297,6 +303,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawDROEnabled = rawDROEnabled,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -329,6 +336,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawDROEnabled: Boolean = false,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -358,6 +366,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawDROEnabled = rawDROEnabled,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
@@ -382,6 +391,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawDROEnabled: Boolean = false,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -406,6 +416,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawDROEnabled = rawDROEnabled,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -439,6 +450,7 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawDROEnabled: Boolean = false,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -534,7 +546,8 @@ class RawDemosaicProcessor {
srcBuf.position(0)
val src = srcBuf.asShortBuffer()
val dstSize = newWidth * newHeight * 3 * 2 // 3 channels * 2 bytes
val dstByteBuf = com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(dstSize.toLong())?.order(java.nio.ByteOrder.nativeOrder())
val dstByteBuf = com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(dstSize.toLong())
?.order(java.nio.ByteOrder.nativeOrder())
?: throw OutOfMemoryError("Failed to allocate native direct buffer")
val dst = dstByteBuf.asShortBuffer()
@@ -601,24 +614,38 @@ class RawDemosaicProcessor {
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan
)
val autoExposureEv = if (rawAutoExposure) {
resolveRawAutoExposureEv(
var shadowLift = 0f
var effectiveExposureCompensation = rawExposureCompensation
if (rawAutoExposure) {
val meteringResult = resolveRawAutoExposureEv(
context = context,
metadata = actualMetadata,
sourceTextureId = demosaicTextureId,
dcpRenderPlan = resolvedDcpRenderPlan
)
} else {
0f
}
if (autoExposureEv != 0f) {
renderLinearPass(
metadata = actualMetadata,
rawExposureCompensation = rawExposureCompensation + autoExposureEv,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan
)
val autoExposureEv = meteringResult.meteredEv
if (rawDROEnabled && autoExposureEv > 0f && meteringResult.dynamicRangeGap > 1.2f) {
val maxLinearGainEv = ln(1.0f / meteringResult.p998.coerceAtLeast(0.01f)) / ln(2.0f)
val linearEv = autoExposureEv.coerceAtMost(maxLinearGainEv).coerceAtLeast(0f)
val remainingEv = autoExposureEv - linearEv
shadowLift = ((2.0f.pow(remainingEv) - 1.0f) / 0.67f).coerceIn(0f, 1.0f)
PLog.d(TAG, "Raw DRO enabled linearEv = $linearEv shadowLift=$shadowLift")
effectiveExposureCompensation += linearEv
} else {
effectiveExposureCompensation += autoExposureEv
}
if (effectiveExposureCompensation != rawExposureCompensation) {
renderLinearPass(
metadata = actualMetadata,
rawExposureCompensation = effectiveExposureCompensation,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan
)
}
}
// rawTextureId 已被 linearPass 消费,提前释放 GPU 显存
if (rawTextureId != 0) {
@@ -702,7 +729,12 @@ class RawDemosaicProcessor {
// 5. 第二步:Combined Pass (HDR Linear -> LDR sRGB + LUT)
setupCombinedFramebuffer(actualWidth, actualHeight)
val combinedStart = System.currentTimeMillis()
renderCombinedPass(actualMetadata, inputTextureId = outputTexture, dcpRenderPlan = resolvedDcpRenderPlan)
renderCombinedPass(
metadata = actualMetadata,
inputTextureId = outputTexture,
dcpRenderPlan = resolvedDcpRenderPlan,
shadowLift = shadowLift
)
PLog.d(TAG, "Combined Pass took: ${System.currentTimeMillis() - combinedStart}ms")
// outputTexture (gfTexId[1]) 已被 combinedPass 消费,提前释放
if (gfTexId[1] != 0) {
@@ -1011,9 +1043,12 @@ class RawDemosaicProcessor {
gfPass0Program = createGfProgram(vShader, BM3DShaders.PASS0_CHROMA_DENOISE, "BM3D_Pass0")
nlmPassHProgram = createGfProgram(vShader, BM3DShaders.PASS1_BASIC_ESTIMATE, "BM3D_Pass1")
nlmPassVProgram = createGfProgram(vShader, BM3DShaders.PASS2_WIENER, "BM3D_Pass2")
nlmPassVProgram = createGfProgram(vShader, BM3DShaders.PASS2_WIENER, "BM3D_Pass2")
PLog.d(TAG, "Denoise programs: BM3D_Pass0=$gfPass0Program BM3D_Pass1=$nlmPassHProgram BM3D_Pass2=$nlmPassVProgram")
PLog.d(
TAG,
"Denoise programs: BM3D_Pass0=$gfPass0Program BM3D_Pass1=$nlmPassHProgram BM3D_Pass2=$nlmPassVProgram"
)
}
private fun setupNLMFramebuffers(width: Int, height: Int) {
@@ -1137,7 +1172,7 @@ class RawDemosaicProcessor {
val baseNoise = if (noiseBase > 0f) {
noiseBase * 0.8f
} else {
0.010f * gainSqrt
0.010f * gainSqrt
}
val noise = baseNoise + gainNoise
@@ -1693,7 +1728,11 @@ class RawDemosaicProcessor {
return dummyDcpToneCurveTextureId
}
private fun uploadDcp3DTexture(textureIdProvider: () -> Int, assignTextureId: (Int) -> Unit, table: DcpHueSatMap): Int {
private fun uploadDcp3DTexture(
textureIdProvider: () -> Int,
assignTextureId: (Int) -> Unit,
table: DcpHueSatMap
): Int {
var textureId = textureIdProvider()
if (textureId == 0) {
val textures = IntArray(1)
@@ -1743,19 +1782,20 @@ class RawDemosaicProcessor {
private fun bindDcpCombinedResources(dcpRenderPlan: DcpRenderPlan?) {
val hueSatMap = dcpRenderPlan?.hueSatMap?.takeIf { it.isValid }
val lookTable = dcpRenderPlan?.lookTable?.takeIf { it.isValid }
val toneCurveLut = dcpRenderPlan?.toneCurveLut
PLog.d(TAG, "bindDcpCombinedResources: hueSatMap=${hueSatMap?.values?.size}")
PLog.d(TAG, "bindDcpCombinedResources: lookTable=${lookTable?.values?.size}")
PLog.d(TAG, "bindDcpCombinedResources: toneCurveLut=${toneCurveLut?.size}")
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpHueSatTexture"), 2)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpLookTableTexture"), 3)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpToneCurveTexture"), 4)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpHueSatEnabled"), if (hueSatMap != null) 1 else 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpLookTableEnabled"), if (lookTable != null) 1 else 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uDcpToneCurveEnabled"), if (toneCurveLut != null) 1 else 0)
GLES30.glUniform1f(GLES30.glGetUniformLocation(combinedProgram, "uDcpToneCurveSize"), toneCurveLut?.size?.toFloat() ?: 0f)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(combinedProgram, "uDcpHueSatEnabled"),
if (hueSatMap != null) 1 else 0
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(combinedProgram, "uDcpLookTableEnabled"),
if (lookTable != null) 1 else 0
)
if (hueSatMap != null) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE2)
@@ -1814,19 +1854,6 @@ class RawDemosaicProcessor {
DcpHueSatMap.ENCODING_LINEAR
)
}
if (toneCurveLut != null) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE4)
uploadDcpToneCurveTexture(toneCurveLut)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, dcpToneCurveTextureId)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(combinedProgram, "uDcpToneCurveSize"),
toneCurveLut.size.toFloat()
)
} else {
GLES30.glActiveTexture(GLES30.GL_TEXTURE4)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ensureDummyDcpToneCurveTexture())
}
checkGlError("bindDcpCombinedResources")
}
@@ -1839,9 +1866,21 @@ class RawDemosaicProcessor {
inputTextureId: Int = demosaicTextureId,
dcpRenderPlan: DcpRenderPlan? = null,
viewportWidth: Int = metadata.width,
viewportHeight: Int = metadata.height
viewportHeight: Int = metadata.height,
shadowLift: Float = 0f
) {
val curveLut = ACR3Curve.samples()
val baseCurve = dcpRenderPlan?.toneCurveLut ?: ACR3Curve.samples()
val combinedLut = if (shadowLift > 0f) {
FloatArray(baseCurve.size) { i ->
val v = baseCurve[i]
val liftBase = v.toDouble().pow(0.75).toFloat() - v
val blackToe = (v / 0.01f).coerceAtMost(1.0f)
val lift = shadowLift * liftBase * (1.0f - v) * blackToe
(v + lift * 1.5f).coerceIn(0f, 1f)
}
} else {
baseCurve
}
val outputTransform = computeWorkingToOutputTransform(ColorSpace.ProPhoto, ColorSpace.SRGB)
GLES30.glUseProgram(combinedProgram)
@@ -1858,12 +1897,12 @@ class RawDemosaicProcessor {
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
uploadCurveTexture(curveLut)
uploadCurveTexture(combinedLut)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uCurveTexture"), 1)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(combinedProgram, "uCurveSize"),
curveLut.size.toFloat()
combinedLut.size.toFloat()
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(combinedProgram, "uCurveEnabled"),
@@ -1974,15 +2013,15 @@ class RawDemosaicProcessor {
val row = index / 3
val col = index % 3
lhs[row * 3] * rhs[col] +
lhs[row * 3 + 1] * rhs[3 + col] +
lhs[row * 3 + 2] * rhs[6 + col]
lhs[row * 3 + 1] * rhs[3 + col] +
lhs[row * 3 + 2] * rhs[6 + col]
}
}
private fun invertMatrix3x3(matrix: FloatArray): FloatArray? {
val det = matrix[0] * (matrix[4] * matrix[8] - matrix[5] * matrix[7]) -
matrix[1] * (matrix[3] * matrix[8] - matrix[5] * matrix[6]) +
matrix[2] * (matrix[3] * matrix[7] - matrix[4] * matrix[6])
matrix[1] * (matrix[3] * matrix[8] - matrix[5] * matrix[6]) +
matrix[2] * (matrix[3] * matrix[7] - matrix[4] * matrix[6])
if (abs(det) < 1e-12f) {
PLog.e(TAG, "Matrix is singular, cannot invert")
@@ -2137,7 +2176,7 @@ class RawDemosaicProcessor {
metadata: RawMetadata,
sourceTextureId: Int,
dcpRenderPlan: DcpRenderPlan?
): Float {
): MeteringSystem.MeteringResult {
val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1)
val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1)
return try {
@@ -2178,13 +2217,13 @@ class RawDemosaicProcessor {
wb
}
val ev = MeteringSystem.analyzeRenderedExposureEv(
val meteringResult = MeteringSystem.analyzeRenderedExposureEv(
byteBuffer = buffer,
width = meteringWidth,
height = meteringHeight,
weightBuffer = weightBuffer
)
// Clean up temporary bitmaps
if (depthMap != null && !depthMap.isRecycled) {
depthMap.recycle()
@@ -2194,12 +2233,12 @@ class RawDemosaicProcessor {
}
PLog.d(
TAG,
"RAW auto exposure: renderedEv=$ev"
"RAW auto exposure: renderedEv=${meteringResult.meteredEv} gap=${meteringResult.dynamicRangeGap}"
)
ev
meteringResult
} catch (e: Exception) {
PLog.e(TAG, "Failed to resolve RAW auto exposure", e)
0f
MeteringSystem.MeteringResult(0f, 0f, 0f, 0f)
}
}
@@ -2355,13 +2394,14 @@ class RawDemosaicProcessor {
// --- 降级路径:直接分配 ByteBuffer(Java 堆)---
val pixelBuffer = try {
com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(pixelSize.toLong())?.order(ByteOrder.nativeOrder())
com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(pixelSize.toLong())
?.order(ByteOrder.nativeOrder())
?: throw OutOfMemoryError("Failed to allocate native direct buffer")
} catch (e: OutOfMemoryError) {
PLog.e(TAG, "OOM allocating pixel buffer ($width x $height, ${pixelSize}B)", e)
return null
}
try {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glReadPixels(0, 0, width, height, GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, pixelBuffer)
@@ -134,14 +134,11 @@ object RawShaders {
uniform sampler2D uInputTexture;
uniform sampler2D uCurveTexture;
uniform sampler2D uDcpToneCurveTexture;
uniform sampler3D uDcpHueSatTexture;
uniform sampler3D uDcpLookTableTexture;
uniform mat3 uOutputTransform;
uniform float uCurveSize;
uniform float uDcpToneCurveSize;
uniform bool uCurveEnabled;
uniform bool uDcpToneCurveEnabled;
uniform bool uDcpHueSatEnabled;
uniform bool uDcpLookTableEnabled;
uniform ivec3 uDcpHueSatDivisions;
@@ -166,23 +163,6 @@ object RawShaders {
);
}
float sampleDcpToneCurve(float value) {
if (!uDcpToneCurveEnabled || uDcpToneCurveSize <= 1.0) {
return value;
}
float clampedValue = clamp(value, 0.0, 1.0);
float coordX = clampedValue * ((uDcpToneCurveSize - 1.0) / uDcpToneCurveSize) + (0.5 / uDcpToneCurveSize);
return texture(uDcpToneCurveTexture, vec2(coordX, 0.5)).r;
}
vec3 applyDcpToneCurve(vec3 color) {
return vec3(
sampleDcpToneCurve(color.r),
sampleDcpToneCurve(color.g),
sampleDcpToneCurve(color.b)
);
}
vec3 linearToSrgb(vec3 color) {
vec3 clampedColor = max(color, vec3(0.0));
vec3 low = clampedColor * 12.92;
@@ -399,7 +379,7 @@ object RawShaders {
return clamp(sceneLinear * chromaScale, 0.0, 1.0);
}
void main() {
vec3 color = texture(uInputTexture, vTexCoord).rgb;
color = reinhardLocalTonemapping(color);
@@ -410,11 +390,9 @@ object RawShaders {
if (uDcpLookTableEnabled) {
color = applyDcpHsvMap(color, uDcpLookTableTexture, uDcpLookTableDivisions, uDcpLookTableEncoding);
}
if (uDcpToneCurveEnabled) {
color = applyDcpToneCurve(color);
} else {
color = applyCurve(color);
}
color = applyCurve(color);
color = uOutputTransform * color;
color = linearToSrgb(color);
@@ -137,6 +137,7 @@ fun CameraScreen(
val rawAutoExposure by viewModel.rawAutoExposure.collectAsState()
val rawBlackPointCorrection by viewModel.rawBlackPointCorrection.collectAsState()
val rawWhitePointCorrection by viewModel.rawWhitePointCorrection.collectAsState()
val rawDROEnabled by viewModel.rawDROEnabled.collectAsState()
val multipleExposureState = viewModel.multipleExposureState
val canStartShutterAnimation by viewModel.canStartShutterAnimation.collectAsState()
var previewRecipeParamsOverride by remember(currentLutId) { mutableStateOf<ColorRecipeParams?>(null) }
@@ -1184,6 +1185,7 @@ fun CameraScreen(
rawNlmNoiseFactor = rawNlmNoiseFactor,
rawExposureCompensation = rawExposureCompensation,
rawAutoExposure = rawAutoExposure,
rawDROEnabled = rawDROEnabled,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
onSelectDcp = { viewModel.setRawDcpId(it) },
@@ -1192,6 +1194,7 @@ fun CameraScreen(
onRawNlmNoiseFactorChange = { viewModel.setRawNlmNoiseFactor(it) },
onRawExposureCompensationChange = { viewModel.setRawExposureCompensation(it) },
onRawAutoExposureChange = { viewModel.setRawAutoExposure(it) },
onRawDROEnabledChange = { viewModel.setRawDROEnabled(it) },
onRawBlackPointCorrectionChange = { viewModel.setRawBlackPointCorrection(it) },
onRawWhitePointCorrectionChange = { viewModel.setRawWhitePointCorrection(it) },
onAdjustmentStart = { },
@@ -87,6 +87,7 @@ fun CameraTopSheet(
rawNlmNoiseFactor: Float,
rawExposureCompensation: Float,
rawAutoExposure: Boolean,
rawDROEnabled: Boolean,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float,
onSelectDcp: (String?) -> Unit,
@@ -95,6 +96,7 @@ fun CameraTopSheet(
onRawNlmNoiseFactorChange: (Float) -> Unit,
onRawExposureCompensationChange: (Float) -> Unit,
onRawAutoExposureChange: (Boolean) -> Unit,
onRawDROEnabledChange: (Boolean) -> Unit,
onRawBlackPointCorrectionChange: (Float) -> Unit,
onRawWhitePointCorrectionChange: (Float) -> Unit,
onAdjustmentStart: () -> Unit,
@@ -520,6 +522,7 @@ fun CameraTopSheet(
rawNlmNoiseFactor = rawNlmNoiseFactor,
rawExposureCompensation = rawExposureCompensation,
rawAutoExposure = rawAutoExposure,
rawDROEnabled = rawDROEnabled,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
onSelectDcp = onSelectDcp,
@@ -528,6 +531,7 @@ fun CameraTopSheet(
onRawNlmNoiseFactorChange = onRawNlmNoiseFactorChange,
onRawExposureCompensationChange = onRawExposureCompensationChange,
onRawAutoExposureChange = onRawAutoExposureChange,
onRawDROEnabledChange = onRawDROEnabledChange,
onRawBlackPointCorrectionChange = onRawBlackPointCorrectionChange,
onRawWhitePointCorrectionChange = onRawWhitePointCorrectionChange,
onAdjustmentStart = onAdjustmentStart,
@@ -39,6 +39,7 @@ fun RawEditPanel(
rawNlmNoiseFactor: Float,
rawExposureCompensation: Float,
rawAutoExposure: Boolean,
rawDROEnabled: Boolean,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float,
onSelectDcp: (String?) -> Unit,
@@ -47,6 +48,7 @@ fun RawEditPanel(
onRawNlmNoiseFactorChange: (Float) -> Unit,
onRawExposureCompensationChange: (Float) -> Unit,
onRawAutoExposureChange: (Boolean) -> Unit,
onRawDROEnabledChange: (Boolean) -> Unit,
onRawBlackPointCorrectionChange: (Float) -> Unit,
onRawWhitePointCorrectionChange: (Float) -> Unit,
onAdjustmentStart: () -> Unit,
@@ -81,6 +83,12 @@ fun RawEditPanel(
checked = rawAutoExposure,
onCheckedChange = onRawAutoExposureChange
)
RawSwitchSettingItem(
title = stringResource(R.string.settings_raw_dro),
description = stringResource(R.string.settings_raw_dro_description),
checked = rawDROEnabled,
onCheckedChange = onRawDROEnabledChange
)
SliderSettingItem(
title = stringResource(R.string.settings_raw_exposure_compensation),
value = rawExposureCompensation,
@@ -91,6 +91,7 @@ private data class PreviewRenderSignature(
val editRawAutoExposure: Boolean,
val editRawBlackPointCorrection: Float,
val editRawWhitePointCorrection: Float,
val editRawDROEnabled: Boolean,
val editRawDcpId: String?,
val editRawBaselineLutId: String?,
val editComputationalAperture: Float?,
@@ -156,6 +157,7 @@ fun PhotoEditScreen(
val editRawAutoExposure by viewModel.editRawAutoExposure.collectAsState()
val editRawBlackPointCorrection by viewModel.editRawBlackPointCorrection.collectAsState()
val editRawWhitePointCorrection by viewModel.editRawWhitePointCorrection.collectAsState()
val editRawDROEnabled by viewModel.editRawDROEnabled.collectAsState()
val editRawDcpId by viewModel.editRawDcpId.collectAsState()
val editRawBaselineLutId by viewModel.editRawBaselineLutId.collectAsState()
val availableDcps = viewModel.availableDcps
@@ -205,6 +207,7 @@ fun PhotoEditScreen(
editRawAutoExposure = editRawAutoExposure,
editRawBlackPointCorrection = editRawBlackPointCorrection,
editRawWhitePointCorrection = editRawWhitePointCorrection,
editRawDROEnabled = editRawDROEnabled,
editRawDcpId = editRawDcpId,
editRawBaselineLutId = editRawBaselineLutId,
editComputationalAperture = editComputationalAperture,
@@ -877,6 +880,7 @@ fun PhotoEditScreen(
rawNlmNoiseFactor = editRawNlmNoiseFactor,
rawExposureCompensation = editRawExposureCompensation,
rawAutoExposure = editRawAutoExposure,
rawDROEnabled = editRawDROEnabled,
rawBlackPointCorrection = editRawBlackPointCorrection,
rawWhitePointCorrection = editRawWhitePointCorrection,
onSelectDcp = { dcpId ->
@@ -903,6 +907,9 @@ fun PhotoEditScreen(
onRawAutoExposureChange = {
viewModel.saveRawAutoExposureValue(currentPhoto, it)
},
onRawDROEnabledChange = {
viewModel.saveRawDROEnabledValue(currentPhoto, it)
},
onRawBlackPointCorrectionChange = {
viewModel.saveRawBlackPointCorrectionValue(currentPhoto, it)
},
@@ -199,6 +199,7 @@ fun SettingsScreen(
val rawNlmNoiseFactor by viewModel.rawNlmNoiseFactor.collectAsState()
val rawExposureCompensation by viewModel.rawExposureCompensation.collectAsState()
val rawAutoExposure by viewModel.rawAutoExposure.collectAsState()
val rawDROEnabled by viewModel.rawDROEnabled.collectAsState()
val rawBlackPointCorrection by viewModel.rawBlackPointCorrection.collectAsState()
val rawWhitePointCorrection by viewModel.rawWhitePointCorrection.collectAsState()
val rawAutoWhiteBalanceEstimate by viewModel.rawAutoWhiteBalanceEstimate.collectAsState()
@@ -1213,6 +1214,7 @@ fun SettingsScreen(
rawNlmNoiseFactor = rawNlmNoiseFactorUi,
rawExposureCompensation = rawExposureCompensationUi,
rawAutoExposure = rawAutoExposure,
rawDROEnabled = rawDROEnabled,
rawBlackPointCorrection = rawBlackPointCorrectionUi,
rawWhitePointCorrection = rawWhitePointCorrectionUi,
onSelectDcp = { viewModel.setRawDcpId(it) },
@@ -1229,6 +1231,7 @@ fun SettingsScreen(
onRawNlmNoiseFactorChange = { rawNlmNoiseFactorUi = it },
onRawExposureCompensationChange = { rawExposureCompensationUi = it },
onRawAutoExposureChange = { viewModel.setRawAutoExposure(it) },
onRawDROEnabledChange = { viewModel.setRawDROEnabled(it) },
onRawBlackPointCorrectionChange = { rawBlackPointCorrectionUi = it },
onRawWhitePointCorrectionChange = { rawWhitePointCorrectionUi = it },
onAdjustmentStart = { isRawSliderAdjusting = true },
@@ -245,6 +245,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val rawAutoExposure: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.rawAutoExposure }
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
val rawDROEnabled: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.rawDROEnabled }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
val rawBlackPointCorrection: StateFlow<Float> = userPreferencesRepository.userPreferences
.map { it.rawBlackPointCorrection }
.stateIn(viewModelScope, SharingStarted.Eagerly, 0f)
@@ -745,6 +748,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun setRawAutoExposure(enabled: Boolean) {
viewModelScope.launch { userPreferencesRepository.saveRawAutoExposure(enabled) }
}
fun setRawDROEnabled(enabled: Boolean) {
viewModelScope.launch { userPreferencesRepository.updateRawDROEnabled(enabled) }
}
fun setRawBlackPointCorrection(value: Float) {
viewModelScope.launch { userPreferencesRepository.saveRawBlackPointCorrection(value) }
}
@@ -2702,6 +2708,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawDenoiseValue = userPrefs?.rawNlmNoiseFactor ?: 0f,
rawExposureCompensation = userPrefs?.rawExposureCompensation ?: 0f,
rawAutoExposure = userPrefs?.rawAutoExposure ?: true,
rawDROEnabled = userPrefs?.rawDROEnabled ?: false,
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
@@ -2966,6 +2973,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawDenoiseValue = userPrefs?.rawNlmNoiseFactor ?: 0f,
rawExposureCompensation = userPrefs?.rawExposureCompensation ?: 0f,
rawAutoExposure = userPrefs?.rawAutoExposure ?: true,
rawDROEnabled = userPrefs?.rawDROEnabled ?: false,
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
@@ -297,6 +297,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
var editRawWhitePointCorrection = MutableStateFlow(0f)
private set
var editRawDROEnabled = MutableStateFlow(false)
private set
var editRawDcpId = MutableStateFlow<String?>(null)
private set
var editRawBaselineLutId = MutableStateFlow<String?>(null)
@@ -1565,6 +1567,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRawAutoExposure.value = metadata.rawAutoExposure ?: true
editRawBlackPointCorrection.value = metadata.rawBlackPointCorrection ?: 0f
editRawWhitePointCorrection.value = metadata.rawWhitePointCorrection ?: 0f
editRawDROEnabled.value = metadata.rawDROEnabled ?: false
editComputationalAperture.value = metadata.computationalAperture
editFocusPointX.value = metadata.focusPointX
@@ -1581,6 +1584,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRawAutoExposure.value = true
editRawBlackPointCorrection.value = 0f
editRawWhitePointCorrection.value = 0f
editRawDROEnabled.value = false
editRawDcpId.value = null
editRawBaselineLutId.value = null
editComputationalAperture.value = null
@@ -1615,6 +1619,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRawAutoExposure.value = true
editRawBlackPointCorrection.value = 0f
editRawWhitePointCorrection.value = 0f
editRawDROEnabled.value = false
editRawDcpId.value = null
editRawBaselineLutId.value = null
}
@@ -1718,6 +1723,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val autoExposure = editRawAutoExposure.value
val blackPoint = editRawBlackPointCorrection.value
val whitePoint = editRawWhitePointCorrection.value
val droEnabled = editRawDROEnabled.value
val dcpId = editRawDcpId.value
val baselineLutId = editRawBaselineLutId.value
@@ -1730,6 +1736,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
rawAutoExposure = autoExposure,
rawBlackPointCorrection = blackPoint,
rawWhitePointCorrection = whitePoint,
rawDROEnabled = droEnabled,
rawDcpId = dcpId,
baselineLutId = baselineLutId
)
@@ -1764,6 +1771,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
persistRawEditMetadata(mediaData)
}
fun saveRawDROEnabledValue(mediaData: MediaData, enabled: Boolean) {
editRawDROEnabled.value = enabled
persistRawEditMetadata(mediaData)
}
fun saveRawBlackPointCorrectionValue(mediaData: MediaData, value: Float) {
editRawBlackPointCorrection.value = value
persistRawEditMetadata(mediaData)
@@ -674,6 +674,8 @@
<string name="settings_raw_exposure_compensation">曝光补偿</string>
<string name="settings_raw_auto_exposure">自动曝光</string>
<string name="settings_raw_auto_exposure_description">显影时对 RAW 线性数据自动测光并应用曝光补偿。</string>
<string name="settings_raw_dro">动态范围优化</string>
<string name="settings_raw_dro_description">在高光比场景中,智能提升阴影细节并保护高光。</string>
<string name="settings_raw_metering_center_weight">RAW 测光中心权重</string>
<string name="settings_raw_metering_center_weight_description">数值越低越接近评价测光,越高越接近中央重点测光。</string>
<string name="settings_raw_black_point_correction">黑点校正</string>
+2
View File
@@ -658,6 +658,8 @@
<string name="settings_raw_exposure_compensation">Exposure Compensation</string>
<string name="settings_raw_auto_exposure">Auto Exposure</string>
<string name="settings_raw_auto_exposure_description">Automatically meters RAW linear data during development and applies exposure compensation.</string>
<string name="settings_raw_dro">Dynamic Range Optimization</string>
<string name="settings_raw_dro_description">Intelligently lifts shadows while protecting highlights in high-contrast scenes.</string>
<string name="settings_raw_metering_center_weight">RAW Metering Center Weight</string>
<string name="settings_raw_metering_center_weight_description">Lower values are closer to evaluative metering; higher values tighten and emphasize the center area.</string>
<string name="settings_raw_black_point_correction">Black Point Correction</string>