feat: merge legacy palette saturation

This commit is contained in:
Hinnka committed 2026-09-05 18:08:33 +08:00
1 parent 9d91dd48ac
commit 2cf1e3cb89
12 files changed
+198 -49

No files matched your search

@@ -14,6 +14,7 @@ import com.hinnka.mycamera.gallery.MediaMetadata
import com.hinnka.mycamera.gallery.MediaType
import com.hinnka.mycamera.hdr.HdrGainmapStrength
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
import com.hinnka.mycamera.model.ColorPaletteMapper
import com.hinnka.mycamera.raw.HncsFilmCurveMode
import com.hinnka.mycamera.raw.HncsRenderIntent
import com.hinnka.mycamera.raw.RawRenderingEngine
@@ -213,10 +214,10 @@ object GalleryMediaStore {
version = metadata.version,
lutId = metadata.lutId,
tonemapMode = metadata.tonemapMode,
colorRecipeParams = metadata.colorRecipeParams,
colorRecipeParams = metadata.colorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams),
baselineTarget = metadata.baselineTarget?.name,
baselineLutId = metadata.baselineLutId,
baselineColorRecipeParams = metadata.baselineColorRecipeParams,
baselineColorRecipeParams = metadata.baselineColorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams),
sharpening = metadata.sharpening,
noiseReduction = metadata.noiseReduction,
chromaNoiseReduction = metadata.chromaNoiseReduction,
@@ -414,10 +415,10 @@ object GalleryMediaStore {
mediaType = runCatching { MediaType.valueOf(mediaType) }.getOrDefault(MediaType.IMAGE),
lutId = lutId,
tonemapMode = tonemapMode,
colorRecipeParams = colorRecipeParams,
colorRecipeParams = colorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams),
baselineTarget = baselineTarget?.let { runCatching { BaselineColorCorrectionTarget.valueOf(it) }.getOrNull() },
baselineLutId = baselineLutId,
baselineColorRecipeParams = baselineColorRecipeParams,
baselineColorRecipeParams = baselineColorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams),
sharpening = sharpening,
noiseReduction = noiseReduction,
chromaNoiseReduction = chromaNoiseReduction,
@@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.hinnka.mycamera.data.CustomImportManager
import com.hinnka.mycamera.mgc.PhotonLookContract
import com.hinnka.mycamera.model.ColorPaletteMapper
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.flow.Flow
@@ -140,13 +141,26 @@ class LutManager(private val context: Context) {
gradingBlending = f("gradingBlending", 0.5f),
lutIntensity = f("lutIntensity", 1f),
remarks = s("remarks"),
)
).let(ColorPaletteMapper::mergeIntoEffectiveParams)
}
private fun androidx.datastore.preferences.core.MutablePreferences.removeLegacyKeys(lutId: String) {
legacyFieldNames.forEach { name -> remove(floatPreferencesKey("${lutId}_$name")) }
remove(stringPreferencesKey("${lutId}_remarks"))
}
private fun readSavedColorRecipeParams(
preferences: Preferences,
lutId: String,
target: BaselineColorCorrectionTarget?
): ColorRecipeParams? {
preferences[recipeKey(lutId, target)]?.let { return ColorRecipeParams.fromJson(it) }
if (target != null) return null
val hasLegacyRecipe = legacyFieldNames.any { name ->
preferences[floatPreferencesKey("${lutId}_$name")] != null
} || preferences[stringPreferencesKey("${lutId}_remarks")] != null
return if (hasLegacyRecipe) readLegacyParams(preferences, lutId) else null
}
}
// LUT 缓存
@@ -169,9 +183,7 @@ class LutManager(private val context: Context) {
target: BaselineColorCorrectionTarget? = null
): Flow<ColorRecipeParams> {
return context.colorRecipeDataStore.data.map { preferences ->
val json = preferences[recipeKey(lutId, target)]
if (json != null) ColorRecipeParams.fromJson(json)
else if (target == null) readLegacyParams(preferences, lutId) else ColorRecipeParams.DEFAULT
readSavedColorRecipeParams(preferences, lutId, target) ?: ColorRecipeParams.DEFAULT
}
}
@@ -350,11 +362,16 @@ class LutManager(private val context: Context) {
lutId: String,
target: BaselineColorCorrectionTarget? = null
): ColorRecipeParams {
return context.colorRecipeDataStore.data.map { preferences ->
val json = preferences[recipeKey(lutId, target)]
if (json != null) ColorRecipeParams.fromJson(json)
else if (target == null) readLegacyParams(preferences, lutId) else ColorRecipeParams.DEFAULT
}.firstOrNull() ?: ColorRecipeParams.DEFAULT
return loadSavedColorRecipeParams(lutId, target) ?: ColorRecipeParams.DEFAULT
}
/** null 表示没有绑定配方,与用户明确保存的默认配方区分。 */
suspend fun loadSavedColorRecipeParams(
lutId: String,
target: BaselineColorCorrectionTarget? = null
): ColorRecipeParams? {
val preferences = context.colorRecipeDataStore.data.firstOrNull() ?: return null
return readSavedColorRecipeParams(preferences, lutId, target)
}
/**
@@ -120,8 +120,10 @@ data class CameraPreset(
}
fun normalizedForPersistence(): CameraPreset {
return withoutLegacyHdf()
val normalized = withoutLegacyHdf()
return normalized
.copy(
colorRecipe = ColorPaletteMapper.mergeIntoEffectiveParams(normalized.colorRecipe),
lutId = normalizeLutId(lutId),
rawDcpId = rawDcpId?.takeIf { it.isNotBlank() },
rawDcpIdsByLens = normalizeRawDcpIdsByLens(rawDcpIdsByLens),
@@ -41,33 +41,31 @@ object ColorPaletteMapper {
)
}
fun mergeIntoEffectiveParams(manualParams: ColorRecipeParams): ColorRecipeParams {
fun effectiveSaturation(params: ColorRecipeParams): Float {
if (params.paletteX == ColorPaletteState.DEFAULT.x) {
return RecipeParam.SATURATION.clamp(params.saturation)
}
val paletteContribution = buildPaletteContribution(
ColorPaletteState(
x = manualParams.paletteX,
y = manualParams.paletteY,
density = manualParams.paletteDensity
x = params.paletteX,
y = params.paletteY,
density = params.paletteDensity
)
)
return RecipeParam.SATURATION.clamp(
params.saturation + paletteContribution.saturation - RecipeParam.SATURATION.defaultValue
)
}
fun combine(
manualValue: Float,
paletteValue: Float,
defaultValue: Float,
minValue: Float,
maxValue: Float
): Float {
return (manualValue + paletteValue - defaultValue).coerceIn(minValue, maxValue)
/** 将旧横轴的饱和度分量并入唯一的饱和度参数,可在读取、保存和渲染边界重复调用。 */
fun mergeIntoEffectiveParams(manualParams: ColorRecipeParams): ColorRecipeParams {
val saturation = effectiveSaturation(manualParams)
if (manualParams.paletteX == ColorPaletteState.DEFAULT.x && manualParams.saturation == saturation) {
return manualParams
}
return manualParams.copy(
saturation = combine(
manualValue = manualParams.saturation,
paletteValue = paletteContribution.saturation,
defaultValue = RecipeParam.SATURATION.defaultValue,
minValue = RecipeParam.SATURATION.minValue,
maxValue = RecipeParam.SATURATION.maxValue
)
saturation = saturation,
paletteX = ColorPaletteState.DEFAULT.x
)
}
@@ -24,7 +24,7 @@ data class ColorRecipeParams(
val toneToe: Float = 0f, // -1.0 ~ +1.0 (影调曲线暗部塑形)
val toneShoulder: Float = 0f, // -1.0 ~ +1.0 (影调曲线亮部塑形)
val tonePivot: Float = 0f, // -1.0 ~ +1.0 (影调曲线中点偏移)
val paletteX: Float = 0.5f, // 调色盘横向落点
val paletteX: Float = 0.5f, // 旧调色盘横向落点,读取和保存时合并入 saturation
val paletteY: Float = 0.5f, // 调色盘纵向落点
val paletteDensity: Float = 1f, // 调色盘浓度
val filmGrain: Float = 0f, // 0.0 ~ 1.0 (颗粒强度,0为无颗粒)
@@ -269,7 +269,9 @@ data class ColorRecipeParams(
/**
* 序列化为 JSON 字符串
*/
fun toJson(): String = gson.toJson(copy(halation = 0f))
fun toJson(): String = gson.toJson(
ColorPaletteMapper.mergeIntoEffectiveParams(this).copy(halation = 0f)
)
companion object {
private val gson = Gson()
@@ -290,7 +292,7 @@ data class ColorRecipeParams(
} else {
DEFAULT.gradingBlending
}
)
).let(ColorPaletteMapper::mergeIntoEffectiveParams)
} catch (_: Exception) {
DEFAULT
}
@@ -388,7 +390,7 @@ enum class RecipeParam(
return when (this) {
EXPOSURE -> params.exposure
CONTRAST -> params.contrast
SATURATION -> params.saturation
SATURATION -> ColorPaletteMapper.effectiveSaturation(params)
TEMPERATURE -> params.temperature
TINT -> params.tint
FADE -> params.fade
@@ -456,7 +458,7 @@ enum class RecipeParam(
return when (this) {
EXPOSURE -> params.copy(exposure = clampedValue)
CONTRAST -> params.copy(contrast = clampedValue)
SATURATION -> params.copy(saturation = clampedValue)
SATURATION -> params.copy(saturation = clampedValue, paletteX = ColorPaletteState.DEFAULT.x)
TEMPERATURE -> params.copy(temperature = clampedValue)
TINT -> params.copy(tint = clampedValue)
FADE -> params.copy(fade = clampedValue)
@@ -150,7 +150,7 @@ fun LutEditBottomSheet(
)
},
imageHistogram = imageHistogram,
showLutIntensity = editorTarget == LutEditorTarget.CREATIVE_GLOBAL,
showLutIntensity = editorTarget == LutEditorTarget.CREATIVE_GLOBAL && lutId != "none",
currentEffects = editingParams.toEffectParams().takeIf { showEffects },
onEffectsChange = if (showEffects) {
{ effects -> onParamsUpdated(effects.applyTo(editingParams)) }
@@ -333,6 +333,11 @@ fun ColorRecipePanel(
}
fun setBasicRawValue(control: BasicRecipeControl, value: Float) {
if (control == BasicRecipeControl.SATURATION) {
// 同时更新配方和调色盘状态,避免随后调节影调时重新带回旧横轴。
onParamsChange(RecipeParam.SATURATION.setValue(currentParams, value))
return
}
if (control == BasicRecipeControl.TONE) {
onPaletteStateChange(
paletteState.withValues(
@@ -339,7 +339,7 @@ fun LutSelector(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
if (onEditClick != null && activeLutId != null && activeLutId != "none") {
if (onEditClick != null && activeLutId != null) {
LutEditButton(onClick = onEditClick)
}
@@ -1496,6 +1496,7 @@ fun FilterManagementScreen(
if (showColorRecipeSheet && editingLutId != null) {
LutEditBottomSheet(
lutId = editingLutId!!,
containerColor = backgroundColor,
onDismiss = {
showColorRecipeSheet = false
editingLutId = null
@@ -285,10 +285,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
initialValue = ColorRecipeParams.DEFAULT
)
/** 照片独立的色彩配方;仅开启同步并切换 LUT 时,null 表示读取该 LUT 的配方。 */
/** 当前预览、保存使用的完整配方,与独立调节草稿分开保存。 */
var editPhotoRecipeParams = MutableStateFlow<ColorRecipeParams?>(null)
private set
private var independentEditPhotoRecipeParams = ColorRecipeParams.DEFAULT
var editLutConfig: LutConfig? by mutableStateOf(null)
private set
@@ -2016,11 +2018,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
isEditing = true
editSyncAdjustmentsToLut = false
independentEditPhotoRecipeParams = ColorRecipeParams.DEFAULT
// 从当前元数据恢复编辑状态
currentMediaMetadata?.let { metadata ->
editLutId.value = metadata.lutId
editFrameId.value = metadata.frameId
editPhotoRecipeParams.value = snapshotEditRecipe(metadata.colorRecipeParams, metadata.lutId)
val recipe = snapshotEditRecipe(metadata.colorRecipeParams, metadata.lutId)
editPhotoRecipeParams.value = recipe
independentEditPhotoRecipeParams = recipe.deepCopy()
editApplyEffectsToVideo.value = metadata.applyEffectsToVideo
if (!targetPhoto.isVideo) {
@@ -2200,6 +2205,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editLutConfig = null
editFrameId.value = null
editPhotoRecipeParams.value = null
independentEditPhotoRecipeParams = ColorRecipeParams.DEFAULT
editApplyEffectsToVideo.value = false
editCropRect.value = null
editCropAspectOption.value = CropAspectOption.Free
@@ -2243,7 +2249,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val params = snapshotEditRecipe(editPhotoRecipeParams.value, editLutId.value)
editSyncAdjustmentsToLut = shouldSync
setPhotoRecipeParams(params)
if (shouldSync) {
setPhotoRecipeParams(params)
} else {
editPhotoRecipeParams.value = params
}
}
private fun snapshotEditRecipe(params: ColorRecipeParams?, lutId: String?): ColorRecipeParams {
@@ -2260,6 +2270,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
/** 设置照片调节,并根据本次编辑的绑定状态同步到 LUT。 */
fun setPhotoRecipeParams(params: ColorRecipeParams) {
editPhotoRecipeParams.value = params
if (!editSyncAdjustmentsToLut) {
independentEditPhotoRecipeParams = params.deepCopy()
}
if (editSyncAdjustmentsToLut) {
val lutId = editLutId.value ?: return
pendingEditLutRecipeSync[lutId] = params.deepCopy()
@@ -2292,10 +2305,22 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
*/
fun setEditLut(lutId: String?) {
if (lutId == null) {
setSyncAdjustmentsToLut(false)
editSyncAdjustmentsToLut = false
}
if (editLutId.value != lutId && editSyncAdjustmentsToLut) {
editPhotoRecipeParams.value = null
if (editLutId.value != lutId) {
val lutRecipe = lutId?.let { id ->
pendingEditLutRecipeSync[id] ?: runBlocking(Dispatchers.IO) {
contentRepository.lutManager.loadSavedColorRecipeParams(id)
}
}
// LUT 配方完整应用,但不能覆盖独立调节草稿;离开带配方的 LUT 后恢复草稿。
editPhotoRecipeParams.value = (
lutRecipe ?: if (editSyncAdjustmentsToLut) {
ColorRecipeParams.DEFAULT
} else {
independentEditPhotoRecipeParams
}
).deepCopy()
}
editLutId.value = lutId
if (lutId == null) {
@@ -2304,9 +2329,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
viewModelScope.launch {
editLutConfig = withContext(Dispatchers.IO) {
val config = withContext(Dispatchers.IO) {
contentRepository.lutManager.loadLut(lutId)
}
if (editLutId.value == lutId) {
editLutConfig = config
}
}
}
@@ -2489,7 +2517,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editSyncAdjustmentsToLut = false
editLutId.value = settings.lutId
editPhotoRecipeParams.value = snapshotEditRecipe(settings.colorRecipeParams, settings.lutId)
val recipe = snapshotEditRecipe(settings.colorRecipeParams, settings.lutId)
editPhotoRecipeParams.value = recipe
independentEditPhotoRecipeParams = recipe.deepCopy()
editFrameId.value = settings.frameId
val targetIsRaw = getCurrentPhoto()?.let(::isRawMedia) == true
if (!targetIsRaw) {
@@ -10,6 +10,42 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class CameraPresetJsonCodecTest {
@Test
fun legacyPaletteSaturation_isMergedWhenReadingAndSavingPresets() {
val legacyJson = """
{
"id": "legacy_palette",
"name": "Legacy Palette",
"colorRecipe": {
"saturation": 0.8,
"paletteX": 1.0,
"paletteY": 0.25,
"paletteDensity": 0.5
}
}
""".trimIndent()
val parsed = requireNotNull(CameraPreset.fromJson(legacyJson))
val inMemory = parsed.copy(
colorRecipe = ColorRecipeParams(
saturation = 0.8f,
paletteX = 1f,
paletteY = 0.25f,
paletteDensity = 0.5f,
)
)
val roundTripped = requireNotNull(CameraPreset.fromJson(inMemory.toJson()))
for (preset in listOf(parsed, roundTripped)) {
assertEquals(1.1f, preset.colorRecipe.saturation, 0.0001f)
assertEquals(0.5f, preset.colorRecipe.paletteX, 0f)
assertEquals(0.25f, ColorPaletteMapper.basicToneAmount(preset.colorRecipe), 0.0001f)
assertEquals(
1.1f,
ColorPaletteMapper.mergeIntoEffectiveParams(preset.colorRecipe).saturation,
0.0001f,
)
}
}
@Test
fun contentReferences_includeAndRemapProfessionalLutSlots() {
val source = CameraPreset(
@@ -4,6 +4,63 @@ import org.junit.Assert.assertEquals
import org.junit.Test
class ColorPaletteMapperTest {
@Test
fun legacySaturation_matchesSliderAndSurvivesSerializationWithoutDoubleApplication() {
val legacy = ColorRecipeParams(
saturation = 0.9f,
paletteX = 0.75f,
paletteY = 0.125f,
paletteDensity = 0.5f,
)
assertEquals(1.05f, RecipeParam.SATURATION.getValue(legacy), 0.0001f)
val restored = ColorRecipeParams.fromJson(
"""{"saturation":0.9,"paletteX":0.75,"paletteY":0.125,"paletteDensity":0.5}"""
)
val roundTripped = ColorRecipeParams.fromJson(legacy.toJson())
for (recipe in listOf(restored, roundTripped)) {
assertEquals(1.05f, recipe.saturation, 0.0001f)
assertEquals(0.5f, recipe.paletteX, 0f)
assertEquals(0.375f, ColorPaletteMapper.basicToneAmount(recipe), 0.0001f)
val rendered = ColorPaletteMapper.mergeIntoEffectiveParams(recipe)
val renderedAgain = ColorPaletteMapper.mergeIntoEffectiveParams(rendered)
assertEquals(recipe.saturation, renderedAgain.saturation, 0f)
}
}
@Test
fun saturationEdit_replacesLegacyOffsetAndToneEditDoesNotRestoreIt() {
val legacy = ColorRecipeParams(paletteX = 1f, paletteDensity = 0.5f)
val edited = RecipeParam.SATURATION.setValue(legacy, 0f)
assertEquals(0f, ColorPaletteMapper.mergeIntoEffectiveParams(edited).saturation, 0f)
val toneEdited = ColorPaletteMapper.updatePaletteState(
edited,
ColorPaletteMapper.deriveFromParams(edited).withValues(tone = 80f),
)
val rendered = ColorPaletteMapper.mergeIntoEffectiveParams(toneEdited)
assertEquals(0f, rendered.saturation, 0f)
assertEquals(0.4f, ColorPaletteMapper.basicToneAmount(rendered), 0.0001f)
val reset = RecipeParam.SATURATION.setValue(legacy, RecipeParam.SATURATION.defaultValue)
assertEquals(1f, ColorPaletteMapper.mergeIntoEffectiveParams(reset).saturation, 0f)
}
@Test
fun legacySaturation_respectsDensityAndExistingRange() {
val cases = listOf(
ColorRecipeParams(saturation = 0.2f, paletteX = 0f) to 0f,
ColorRecipeParams(saturation = 1.8f, paletteX = 1f) to 2f,
ColorRecipeParams(saturation = 1.2f, paletteX = 0f, paletteDensity = 0f) to 1.2f,
)
for ((legacy, expected) in cases) {
assertEquals(expected, RecipeParam.SATURATION.getValue(legacy), 0.0001f)
val migrated = ColorPaletteMapper.mergeIntoEffectiveParams(legacy)
assertEquals(expected, migrated.saturation, 0.0001f)
assertEquals(0.5f, migrated.paletteX, 0f)
}
}
@Test
fun paletteAxes_useContinuousOplusValueRange() {
assertEquals(-100f, ColorPaletteState(x = 0f).saturationValue, 0.0001f)