feat: remove apple proraw

This commit is contained in:
zhoubinjia committed 2026-07-09 19:35:24 +08:00
1 parent e2a2678e1a
commit 4a0d170a17
23 files changed
+40 -1589

No files matched your search

@@ -296,7 +296,6 @@ class UserPreferencesRepository(private val context: Context) {
private val RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_filmic_white_relative_exposure")
private val RAW_GOOGLE_PIXEL_TONE_MAP_KEY = booleanPreferencesKey("raw_google_pixel_tone_map")
private val RAW_OPPO_MASTER_TONE_MAP_KEY = booleanPreferencesKey("raw_oppo_master_tone_map")
private val RAW_APPLE_PRO_RAW_TONE_MAP_KEY = booleanPreferencesKey("raw_apple_pro_raw_tone_map")
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")
@@ -471,8 +470,7 @@ class UserPreferencesRepository(private val context: Context) {
filmicWhiteRelativeExposure = preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
useGooglePixelToneMap = preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] ?: false,
useOppoMasterToneMap = preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] ?: false,
useAppleProRawToneMap = preferences[RAW_APPLE_PRO_RAW_TONE_MAP_KEY] ?: false
useOppoMasterToneMap = preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] ?: false
).normalized(),
rawNlmNoiseFactor = preferences[RAW_NLM_NOISE_FACTOR_KEY] ?: 0f,
rawExposureCompensation = preferences[RAW_EXPOSURE_COMPENSATION_KEY] ?: 0f,
@@ -974,7 +972,6 @@ class UserPreferencesRepository(private val context: Context) {
preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.filmicWhiteRelativeExposure
preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] = normalized.useGooglePixelToneMap
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
preferences[RAW_APPLE_PRO_RAW_TONE_MAP_KEY] = normalized.useAppleProRawToneMap
}
}
@@ -2028,7 +2025,6 @@ class UserPreferencesRepository(private val context: Context) {
preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.filmicWhiteRelativeExposure
preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] = normalized.useGooglePixelToneMap
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
preferences[RAW_APPLE_PRO_RAW_TONE_MAP_KEY] = normalized.useAppleProRawToneMap
}
update.rawSpectralFilmStock?.let {
if (it.value != null) {
@@ -340,8 +340,7 @@ data class MediaMetadata(
obj.optDouble("rawFilmicWhiteRelativeExposure").toFloat()
},
useGooglePixelToneMap = obj.optBoolean("rawGooglePixelToneMap", false),
useOppoMasterToneMap = obj.optBoolean("rawOppoMasterToneMap", false),
useAppleProRawToneMap = obj.optBoolean("rawAppleProRawToneMap", false)
useOppoMasterToneMap = obj.optBoolean("rawOppoMasterToneMap", false)
).normalized(),
rawBlackLevelMode = if (obj.isNull("rawBlackLevelMode")) null else obj.optString("rawBlackLevelMode"),
rawCustomBlackLevel = if (obj.isNull("rawCustomBlackLevel")) null else obj.optDouble("rawCustomBlackLevel").toFloat(),
@@ -237,7 +237,7 @@ object GalleryMediaStore {
rawFilmicWhiteRelativeExposure = metadata.rawToneMappingParameters.filmicWhiteRelativeExposure,
rawGooglePixelToneMap = metadata.rawToneMappingParameters.useGooglePixelToneMap,
rawOppoMasterToneMap = metadata.rawToneMappingParameters.useOppoMasterToneMap,
rawAppleProRawToneMap = metadata.rawToneMappingParameters.useAppleProRawToneMap,
rawAppleProRawToneMap = false,
frameId = metadata.frameId,
width = metadata.width,
height = metadata.height,
@@ -418,8 +418,7 @@ object GalleryMediaStore {
filmicBlackRelativeExposure = rawFilmicBlackRelativeExposure,
filmicWhiteRelativeExposure = rawFilmicWhiteRelativeExposure,
useGooglePixelToneMap = rawGooglePixelToneMap,
useOppoMasterToneMap = rawOppoMasterToneMap,
useAppleProRawToneMap = rawAppleProRawToneMap
useOppoMasterToneMap = rawOppoMasterToneMap
).normalized(),
frameId = frameId,
width = width,
@@ -27,7 +27,6 @@ data class CameraPreset(
val rawRenderingEngine: String = RawRenderingEngine.AdobeCurve.name,
val rawGooglePixelToneMap: Boolean = false,
val rawOppoMasterToneMap: Boolean = false,
val rawAppleProRawToneMap: Boolean = false,
val rawSpectralFilmStock: String? = null,
val rawSpectralFilmPrint: String? = null,
val rawDROMode: String = "OFF",
@@ -74,8 +73,8 @@ data class CameraPreset(
.withoutLegacyHdf()
.copy(
rawDcpIdsByLens = normalizeRawDcpIdsByLens(rawDcpIdsByLens),
rawGooglePixelToneMap = rawGooglePixelToneMap && !rawOppoMasterToneMap && !rawAppleProRawToneMap,
rawOppoMasterToneMap = rawOppoMasterToneMap && !rawAppleProRawToneMap
rawGooglePixelToneMap = rawGooglePixelToneMap && !rawOppoMasterToneMap,
rawOppoMasterToneMap = rawOppoMasterToneMap
)
}
@@ -56,7 +56,6 @@ internal object CameraPresetJsonCodec {
),
rawGooglePixelToneMap = obj.boolean("rawGooglePixelToneMap", false),
rawOppoMasterToneMap = obj.boolean("rawOppoMasterToneMap", false),
rawAppleProRawToneMap = obj.boolean("rawAppleProRawToneMap", false),
rawSpectralFilmStock = obj.stringOrNull("rawSpectralFilmStock"),
rawSpectralFilmPrint = obj.stringOrNull("rawSpectralFilmPrint"),
rawDROMode = parseDroMode(obj.stringOrNull("rawDROMode")),
@@ -1,338 +0,0 @@
package com.hinnka.mycamera.raw
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
internal object DngAppleProRawExposureNormalizer {
private const val TARGET_AVERAGE_EV = 0.7f
private const val TARGET_TOLERANCE_EV = 0.05f
private const val MIN_ADDITIONAL_OFFSET_EV = -2.75f
private const val SOLVE_STEPS = 22
private const val MIN_OUTPUT_FOR_EV = 1e-5f
private const val MAX_OUTPUT_FOR_EV = 0.985f
private const val DEFAULT_BLACK_RENDER_SHADOWS = 5f
private const val DEFAULT_BLACK_RENDER_SHADOW_SCALE = 1f
private const val DEFAULT_BLACK_RENDER_STAGE3_GAIN = 1f
private const val PROFILE_HIGHLIGHT_SHOULDER_START = 0.58f
private const val PROFILE_HIGHLIGHT_SHOULDER_SOFTNESS = 0.30f
private val NEUTRAL_GRAY_SAMPLES = floatArrayOf(
0.010f,
0.015f,
0.022f,
0.032f,
0.046f,
0.065f,
0.090f,
0.125f,
0.180f,
0.250f,
0.360f,
0.500f,
0.700f
)
data class Result(
val additionalExposureOffsetEv: Float,
val measuredAverageEv: Float,
val normalizedAverageEv: Float,
val targetAverageEv: Float
)
fun resolveExposureOffset(
profileGainTableMap: DngProfileGainTableMap?,
baselineExposureEv: Float,
toneCurveLut: FloatArray?,
existingExposureOffsetEv: Float = 0f,
defaultBlackRender: DcpDefaultBlackRender = DcpDefaultBlackRender.None,
shadowScale: Float = 1f,
targetAverageEv: Float = TARGET_AVERAGE_EV
): Result {
val target = targetAverageEv.takeIf { it.isFinite() } ?: TARGET_AVERAGE_EV
val samples = neutralSamples(profileGainTableMap, baselineExposureEv)
val sourceLut = toneCurveLut?.takeIf { it.isNotEmpty() }
if (samples.isEmpty() || sourceLut == null) {
return Result(
additionalExposureOffsetEv = 0f,
measuredAverageEv = Float.NaN,
normalizedAverageEv = Float.NaN,
targetAverageEv = target
)
}
val baseOffset = existingExposureOffsetEv.takeIf { it.isFinite() } ?: 0f
val measured = averageRenderedExposureEv(
samples = samples,
toneCurveLut = sourceLut,
profileExposureOffsetEv = baseOffset,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
) ?: return Result(
additionalExposureOffsetEv = 0f,
measuredAverageEv = Float.NaN,
normalizedAverageEv = Float.NaN,
targetAverageEv = target
)
if (measured <= target + TARGET_TOLERANCE_EV) {
return Result(
additionalExposureOffsetEv = 0f,
measuredAverageEv = measured,
normalizedAverageEv = measured,
targetAverageEv = target
)
}
val darkestAverage = averageRenderedExposureEv(
samples = samples,
toneCurveLut = sourceLut,
profileExposureOffsetEv = baseOffset + MIN_ADDITIONAL_OFFSET_EV,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
) ?: measured
if (darkestAverage > target) {
return Result(
additionalExposureOffsetEv = MIN_ADDITIONAL_OFFSET_EV,
measuredAverageEv = measured,
normalizedAverageEv = darkestAverage,
targetAverageEv = target
)
}
var darkOffset = MIN_ADDITIONAL_OFFSET_EV
var brightOffset = 0f
repeat(SOLVE_STEPS) {
val midOffset = (darkOffset + brightOffset) * 0.5f
val midAverage = averageRenderedExposureEv(
samples = samples,
toneCurveLut = sourceLut,
profileExposureOffsetEv = baseOffset + midOffset,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
) ?: measured
if (midAverage > target) {
brightOffset = midOffset
} else {
darkOffset = midOffset
}
}
val additionalOffset = ((darkOffset + brightOffset) * 0.5f)
.coerceIn(MIN_ADDITIONAL_OFFSET_EV, 0f)
.let { if (it > -0.02f) 0f else it }
val normalized = averageRenderedExposureEv(
samples = samples,
toneCurveLut = sourceLut,
profileExposureOffsetEv = baseOffset + additionalOffset,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
) ?: measured
return Result(
additionalExposureOffsetEv = additionalOffset,
measuredAverageEv = measured,
normalizedAverageEv = normalized,
targetAverageEv = target
)
}
fun estimateAverageExposureEv(
profileGainTableMap: DngProfileGainTableMap?,
baselineExposureEv: Float,
toneCurveLut: FloatArray?,
profileExposureOffsetEv: Float = 0f,
defaultBlackRender: DcpDefaultBlackRender = DcpDefaultBlackRender.None,
shadowScale: Float = 1f
): Float? {
val sourceLut = toneCurveLut?.takeIf { it.isNotEmpty() } ?: return null
val samples = neutralSamples(profileGainTableMap, baselineExposureEv)
if (samples.isEmpty()) return null
return averageRenderedExposureEv(
samples = samples,
toneCurveLut = sourceLut,
profileExposureOffsetEv = profileExposureOffsetEv,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
)
}
private fun neutralSamples(
profileGainTableMap: DngProfileGainTableMap?,
baselineExposureEv: Float
): List<NeutralSample> {
val map = profileGainTableMap?.takeIf { it.isValid } ?: return emptyList()
val baselineGain = DngBaselineExposure.exactGain(baselineExposureEv)
val weightSum = map.mapInputWeights.sum()
.takeIf { it.isFinite() && it > 0f }
?: return emptyList()
val gamma = map.gamma.coerceIn(0.125f, 8.0f)
val samples = ArrayList<NeutralSample>(NEUTRAL_GRAY_SAMPLES.size)
for (gray in NEUTRAL_GRAY_SAMPLES) {
val tableInput = (gray * baselineGain * weightSum)
.coerceIn(0f, 1f)
.pow(gamma)
val pgtmGain = medianGainAtTableInput(map, tableInput)
val linearValue = gray * baselineGain * pgtmGain
if (linearValue.isFinite() && linearValue > 0f) {
samples += NeutralSample(gray = gray, linearValue = linearValue)
}
}
return samples
}
private fun averageRenderedExposureEv(
samples: List<NeutralSample>,
toneCurveLut: FloatArray,
profileExposureOffsetEv: Float,
defaultBlackRender: DcpDefaultBlackRender,
shadowScale: Float
): Float? {
val exposure = profileExposureParams(
exposureEv = profileExposureOffsetEv.takeIf { it.isFinite() } ?: 0f,
defaultBlackRender = defaultBlackRender,
shadowScale = shadowScale
)
var sum = 0f
var count = 0
samples.forEach { sample ->
val exposed = applyProfileExposure(sample.linearValue, exposure)
val output = sampleToneCurve(toneCurveLut, exposed)
if (output.isFinite() && output in MIN_OUTPUT_FOR_EV..MAX_OUTPUT_FOR_EV) {
sum += log2(output / sample.gray)
count++
}
}
if (count > 0) return sum / count.toFloat()
val middle = samples.minByOrNull { kotlin.math.abs(it.gray - 0.18f) } ?: return null
val exposed = applyProfileExposure(middle.linearValue, exposure)
val output = sampleToneCurve(toneCurveLut, exposed)
return if (output.isFinite() && output > 0f) log2(output / middle.gray) else null
}
private fun medianGainAtTableInput(map: DngProfileGainTableMap, tableInput: Float): Float {
val pointCount = map.mapPointsN
val cellCount = map.mapPointsH * map.mapPointsV
if (pointCount <= 0 || cellCount <= 0) return 1f
val tableIndex = (tableInput * pointCount.toFloat())
.coerceIn(0f, (pointCount - 1).toFloat())
val index0 = floor(tableIndex).toInt().coerceIn(0, pointCount - 1)
val index1 = min(index0 + 1, pointCount - 1)
val t = tableIndex - index0.toFloat()
val values = FloatArray(cellCount) { cell ->
val offset = cell * pointCount
lerp(map.gains[offset + index0], map.gains[offset + index1], t)
}
values.sort()
return values[(values.size - 1) / 2].takeIf { it.isFinite() && it > 0f } ?: 1f
}
private fun profileExposureParams(
exposureEv: Float,
defaultBlackRender: DcpDefaultBlackRender,
shadowScale: Float
): ProfileExposureParams {
val safeShadowScale = if (shadowScale.isFinite() && shadowScale > 0f && shadowScale <= 1f) {
shadowScale
} else {
DEFAULT_BLACK_RENDER_SHADOW_SCALE
}
val positiveExposureEv = max(0f, exposureEv)
val white = 1f / 2.0f.pow(positiveExposureEv)
val black = when (defaultBlackRender) {
DcpDefaultBlackRender.Auto -> DEFAULT_BLACK_RENDER_SHADOWS *
safeShadowScale *
DEFAULT_BLACK_RENDER_STAGE3_GAIN *
0.001f
DcpDefaultBlackRender.None -> 0f
}.coerceIn(0f, 0.99f * white)
val slope = 1f / max(white - black, 1e-6f)
val radius = min(0.5f * black, (1f / 16f) / max(slope, 1e-6f))
val qScale = if (radius > 0f) slope / (4f * radius) else 0f
val toneEnabled = exposureEv < 0f
val toneSlope = 2.0f.pow(exposureEv)
val toneA = (16f / 9f) * (1f - toneSlope)
val toneB = toneSlope - 0.5f * toneA
val toneC = 1f - toneA - toneB
return ProfileExposureParams(
rampSlope = slope,
rampBlack = black,
rampRadius = radius,
rampQScale = qScale,
toneEnabled = toneEnabled,
toneSlope = toneSlope,
toneA = toneA,
toneB = toneB,
toneC = toneC
)
}
private fun applyProfileExposure(value: Float, exposure: ProfileExposureParams): Float {
val ramped = applyProfileExposureRamp(value, exposure)
return applyProfileExposureTone(ramped, exposure)
}
private fun applyProfileExposureRamp(value: Float, exposure: ProfileExposureParams): Float {
val black = exposure.rampBlack
val radius = exposure.rampRadius
val ramped = when {
value <= black - radius -> 0f
value >= black + radius -> max((value - black) * exposure.rampSlope, 0f)
else -> {
val y = value - (black - radius)
exposure.rampQScale * y * y
}
}
if (ramped <= PROFILE_HIGHLIGHT_SHOULDER_START) return ramped
val shoulderInput = ramped - PROFILE_HIGHLIGHT_SHOULDER_START
val shoulderAmount = shoulderInput / (shoulderInput + PROFILE_HIGHLIGHT_SHOULDER_SOFTNESS)
return PROFILE_HIGHLIGHT_SHOULDER_START +
(1f - PROFILE_HIGHLIGHT_SHOULDER_START) * shoulderAmount
}
private fun applyProfileExposureTone(value: Float, exposure: ProfileExposureParams): Float {
if (!exposure.toneEnabled) return value
return if (value <= 0.25f) {
value * exposure.toneSlope
} else {
(exposure.toneA * value + exposure.toneB) * value + exposure.toneC
}
}
private fun sampleToneCurve(lut: FloatArray, input: Float): Float {
if (lut.isEmpty()) return input
if (lut.size == 1) return lut[0]
val x = input.coerceIn(0f, 1f) * (lut.size - 1).toFloat()
val index0 = floor(x).toInt().coerceIn(0, lut.size - 1)
val index1 = min(index0 + 1, lut.size - 1)
return lerp(lut[index0], lut[index1], x - index0.toFloat())
}
private fun log2(value: Float): Float {
return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat()
}
private fun lerp(a: Float, b: Float, t: Float): Float {
return a + (b - a) * t.coerceIn(0f, 1f)
}
private data class NeutralSample(
val gray: Float,
val linearValue: Float
)
private data class ProfileExposureParams(
val rampSlope: Float,
val rampBlack: Float,
val rampRadius: Float,
val rampQScale: Float,
val toneEnabled: Boolean,
val toneSlope: Float,
val toneA: Float,
val toneB: Float,
val toneC: Float
)
}
@@ -1,555 +0,0 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
internal object DngAppleProRawProfileGainTableGenerator {
private const val TAG = "DngAppleProRawPgtmGenerator"
private const val MAP_INPUT_WEIGHT_COUNT = 5
private const val DEFAULT_TABLE_POINTS = 257
private const val MIN_TABLE_POINTS = 257
private const val MAX_TABLE_POINTS = 257
private const val TARGET_TILE_PX = 64
private const val GRID_MIN_H = 8
private const val GRID_MIN_V = 6
private const val GRID_MAX_H = 64
private const val GRID_MAX_V = 48
private const val MIN_INPUT_SCALE = 1f / 13.5f
private const val MAX_INPUT_SCALE = 1f
private const val MIN_GAIN_VALUE = 0.05f
private const val MAX_GAIN_VALUE = 12.0f
private const val MIN_CURVE_INPUT = 1e-6f
private const val LOCAL_CURVE_MAX_BLEND = 0.22f
private const val LOCAL_CURVE_SMOOTH_PASSES = 4
internal const val BASE_INPUT_WEIGHT_RED = 0.1063f
internal const val BASE_INPUT_WEIGHT_GREEN = 0.3576f
internal const val BASE_INPUT_WEIGHT_BLUE = 0.0361f
internal const val BASE_INPUT_WEIGHT_MIN = 0.0f
internal const val BASE_INPUT_WEIGHT_MAX = 0.5f
private val BASE_INPUT_WEIGHTS = floatArrayOf(
BASE_INPUT_WEIGHT_RED,
BASE_INPUT_WEIGHT_GREEN,
BASE_INPUT_WEIGHT_BLUE,
BASE_INPUT_WEIGHT_MIN,
BASE_INPUT_WEIGHT_MAX
)
fun sceneInputFromLinearRgb(
red: Float,
green: Float,
blue: Float,
baselineGain: Float,
colorCorrectionMatrix: FloatArray? = null,
): Float {
val profileRgb = if (colorCorrectionMatrix != null && colorCorrectionMatrix.size >= 9) {
floatArrayOf(
colorCorrectionMatrix[0] * red + colorCorrectionMatrix[1] * green + colorCorrectionMatrix[2] * blue,
colorCorrectionMatrix[3] * red + colorCorrectionMatrix[4] * green + colorCorrectionMatrix[5] * blue,
colorCorrectionMatrix[6] * red + colorCorrectionMatrix[7] * green + colorCorrectionMatrix[8] * blue
)
} else {
floatArrayOf(red, green, blue)
}
return sceneInputFromProfileRgb(
red = profileRgb[0],
green = profileRgb[1],
blue = profileRgb[2],
baselineGain = baselineGain
)
}
fun sceneInputFromProfileRgb(
red: Float,
green: Float,
blue: Float,
baselineGain: Float,
): Float {
val r = red * baselineGain
val g = green * baselineGain
val b = blue * baselineGain
val rgbMin = min(r, min(g, b))
val rgbMax = max(r, max(g, b))
return max(
BASE_INPUT_WEIGHT_RED * r +
BASE_INPUT_WEIGHT_GREEN * g +
BASE_INPUT_WEIGHT_BLUE * b +
BASE_INPUT_WEIGHT_MIN * rgbMin +
BASE_INPUT_WEIGHT_MAX * rgbMax,
0f
)
}
fun forCellStats(
width: Int,
height: Int,
baselineExposureEv: Float,
packedCellStats: FloatArray,
tablePointCount: Int = DEFAULT_TABLE_POINTS,
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand? = null,
): DngProfileGainTableMap? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) {
return null
}
val grid = chooseGrid(width, height)
val cellCount = grid.mapPointsH * grid.mapPointsV
if (packedCellStats.size < cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) {
PLog.w(
TAG,
"Apple PGTM stats too small: ${packedCellStats.size}, " +
"expected=${cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE}"
)
return null
}
val safePointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS)
val cells = Array<HdrPgtmCellStats?>(cellCount) { index ->
val offset = index * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
val sampleWeight = packedCellStats[offset + 5].takeIf { it.isFinite() && it > 0f } ?: 0f
if (sampleWeight <= 0f) {
null
} else {
packedStatsAt(packedCellStats, offset, sampleWeight)
}
}
val global = weightedGlobalStats(cells)
val inputScale = appleInputScaleForStats(global)
val sceneMax = 1f / sanitizeInputScale(inputScale)
val globalParams = buildCurveParams(
cell = global,
global = global,
inputScale = inputScale,
sceneMax = sceneMax
)
val params = smoothCurveParams(
source = Array(cellCount) { index ->
val cell = cells[index]
if (cell == null || cell.sampleWeight <= 0f) {
globalParams
} else {
val localParams = buildCurveParams(
cell = cell,
global = global,
inputScale = inputScale,
sceneMax = sceneMax
)
blendCurveParams(
first = globalParams,
second = localParams,
amount = localCurveBlend(cell = cell, global = global, sceneMax = sceneMax)
)
}
},
grid = grid
)
val map = buildMap(
grid = grid,
safePointCount = safePointCount,
inputScale = inputScale,
sceneMax = sceneMax,
params = params
)
return DngHdrProfileGainTableGenerator.withDiagnosticBand(
map,
diagnosticBand?.sanitized()
)
}
private fun packedStatsAt(stats: FloatArray, offset: Int, sampleWeight: Float): HdrPgtmCellStats {
val p10 = safe01(stats[offset])
val p50 = max(p10, safe01(stats[offset + 1]))
val p90 = max(p50, safe01(stats[offset + 2]))
val p98 = max(p90, safePositive(stats[offset + 3], p90))
val p995Input = max(p98, safePositive(stats[offset + 6], p98))
val p999Input = max(p995Input, safePositive(stats[offset + 7], p995Input))
return HdrPgtmCellStats(
p10 = p10,
p50 = p50,
p90 = p90,
p98 = p98,
highlightFraction = safe01(stats[offset + 4]),
p995Input = p995Input,
p999Input = p999Input,
inputTailP95 = p995Input,
inputTailP98 = p995Input,
inputTailP99 = p999Input,
maxInput = p999Input,
sampleWeight = sampleWeight
)
}
private fun weightedGlobalStats(cells: Array<HdrPgtmCellStats?>): HdrPgtmCellStats {
var weightSum = 0f
var p10 = 0f
var p50 = 0f
var p90 = 0f
var p98 = 0f
var highlightFraction = 0f
var p995Input = 0f
var p999Input = 0f
val valid = ArrayList<HdrPgtmCellStats>(cells.size)
cells.forEach { cell ->
if (cell != null && cell.sampleWeight > 0f) {
val weight = cell.sampleWeight
valid += cell
weightSum += weight
p10 += cell.p10 * weight
p50 += cell.p50 * weight
p90 += cell.p90 * weight
p98 += cell.p98 * weight
highlightFraction += cell.highlightFraction * weight
p995Input += cell.p995Input * weight
p999Input += cell.p999Input * weight
}
}
if (weightSum <= 0f) {
return HdrPgtmCellStats(
p10 = 0.03f,
p50 = 0.18f,
p90 = 0.48f,
p98 = 0.72f,
highlightFraction = 0f,
p995Input = 0.82f,
p999Input = 0.82f,
inputTailP95 = 0.82f,
inputTailP98 = 0.82f,
inputTailP99 = 0.82f,
maxInput = 0.82f,
sampleWeight = 1f
)
}
val inputTailP95 = weightedPercentile(valid, 0.95f) { it.p995Input }
val inputTailP98 = weightedPercentile(valid, 0.98f) { it.p995Input }
val inputTailP99 = weightedPercentile(valid, 0.99f) { it.p999Input }
val maxInput = valid.maxOfOrNull { it.p999Input } ?: (p999Input / weightSum)
return HdrPgtmCellStats(
p10 = p10 / weightSum,
p50 = p50 / weightSum,
p90 = p90 / weightSum,
p98 = p98 / weightSum,
highlightFraction = highlightFraction / weightSum,
p995Input = p995Input / weightSum,
p999Input = p999Input / weightSum,
inputTailP95 = inputTailP95,
inputTailP98 = inputTailP98,
inputTailP99 = inputTailP99,
maxInput = maxInput,
sampleWeight = weightSum
)
}
private fun appleInputScaleForStats(global: HdrPgtmCellStats): Float {
val directSceneMax = max(
1f,
max(global.inputTailP98, global.inputTailP99 * 0.98f).takeIf { it.isFinite() && it > 0f } ?: 1f
)
val brightMedian = smoothStep(0.16f, 0.24f, global.p50)
val brightUpper = smoothStep(0.50f, 0.78f, global.p98)
val denseHighlight = smoothStep(0.050f, 0.120f, global.highlightFraction)
val highlightTail = smoothStep(1.30f, 4.50f, global.inputTailP95) *
smoothStep(0.030f, 0.080f, global.highlightFraction)
val expansion = max(max(brightMedian, brightUpper * max(denseHighlight, 0.45f)), highlightTail)
.coerceIn(0f, 1f)
val overBrightMedian = smoothStep(0.72f, 1.05f, global.p50)
val expandedSceneMax = lerp(1f, 12.6f, expansion) *
lerp(1f, 0.74f, overBrightMedian)
val sceneMax = max(directSceneMax, expandedSceneMax).coerceIn(1f, 13.5f)
return sanitizeInputScale(1f / sceneMax)
}
private fun buildCurveParams(
cell: HdrPgtmCellStats,
global: HdrPgtmCellStats,
inputScale: Float,
sceneMax: Float,
): AppleCurveParams {
val expandedScene = smoothStep(2.0f, 8.5f, sceneMax)
val darkCell = 1f - smoothStep(0.035f, 0.120f, cell.p10)
val highlightTailPressure = (
smoothStep(1.30f, 4.00f, global.inputTailP95) *
smoothStep(0.035f, 0.090f, global.highlightFraction) +
smoothStep(0.80f, 1.40f, global.p98) *
smoothStep(0.040f, 0.120f, global.highlightFraction)
).coerceIn(0f, 1f)
val compactLowGain = lerp(
6.85f,
4.95f,
smoothStep(0.085f, 0.135f, global.p50)
)
val expandedLowGain = (
1.30f +
4.15f * darkCell * (1f - highlightTailPressure) +
0.36f * (1f - smoothStep(0.22f, 0.42f, cell.p50))
).coerceIn(1.15f, 5.65f)
val lowGain = lerp(compactLowGain, expandedLowGain, expandedScene)
.coerceIn(1.05f, MAX_GAIN_VALUE)
val compactKnee = lerp(0.178f, 0.225f, smoothStep(0.10f, 0.28f, global.p98))
val expandedKnee = lerp(0.095f, 0.98f, smoothStep(0.11f, 0.36f, cell.p50)) *
lerp(1f, 0.64f, highlightTailPressure)
val knee = lerp(compactKnee, expandedKnee.coerceIn(0.055f, 1.10f), expandedScene)
.coerceIn(0.035f, sceneMax)
val power = (
lerp(1.70f, 1.18f, expandedScene) +
0.28f * highlightTailPressure +
0.10f * smoothStep(2.0f, 5.0f, localRangeEv(cell))
).coerceIn(0.92f, 2.25f)
return AppleCurveParams(
lowGain = lowGain,
knee = knee,
power = power,
terminalGain = inputScale
)
}
private fun smoothCurveParams(
source: Array<AppleCurveParams>,
grid: HdrPgtmGrid,
): Array<AppleCurveParams> {
var current = source
repeat(LOCAL_CURVE_SMOOTH_PASSES) {
current = Array(current.size) { index ->
val x = index % grid.mapPointsH
val y = index / grid.mapPointsH
var weightSum = 0f
var lowGain = 0f
var knee = 0f
var power = 0f
var terminalGain = 0f
for (dy in -1..1) {
val yy = y + dy
if (yy !in 0 until grid.mapPointsV) continue
for (dx in -1..1) {
val xx = x + dx
if (xx !in 0 until grid.mapPointsH) continue
val weight = when {
dx == 0 && dy == 0 -> 4f
dx == 0 || dy == 0 -> 2f
else -> 1f
}
val params = current[yy * grid.mapPointsH + xx]
weightSum += weight
lowGain += params.lowGain * weight
knee += params.knee * weight
power += params.power * weight
terminalGain += params.terminalGain * weight
}
}
AppleCurveParams(
lowGain = lowGain / weightSum,
knee = knee / weightSum,
power = power / weightSum,
terminalGain = terminalGain / weightSum
)
}
}
return current
}
private fun localCurveBlend(
cell: HdrPgtmCellStats,
global: HdrPgtmCellStats,
sceneMax: Float,
): Float {
val expandedScene = smoothStep(2.0f, 8.5f, sceneMax)
if (expandedScene <= 0f) return 0f
val confidence = smoothStep(64f, 192f, cell.sampleWeight)
val localRange = localRangeEv(cell)
val detailGate = smoothStep(0.70f, 2.20f, localRange)
val toneDistance = (
absLogRatio(cell.p50 + 0.006f, global.p50 + 0.006f) * 0.34f +
absLogRatio(cell.p90 + 0.006f, global.p90 + 0.006f) * 0.28f +
absLogRatio(cell.p98 + 0.006f, global.p98 + 0.006f) * 0.24f +
absLogRatio(cell.p999Input + 0.04f, global.inputTailP99 + 0.04f) * 0.18f +
kotlin.math.abs(cell.highlightFraction - global.highlightFraction) * 0.70f
)
val toneVariation = smoothStep(0.48f, 1.85f, toneDistance)
val highlightPressure = smoothStep(0.025f, 0.16f, cell.highlightFraction) *
smoothStep(0.45f, 1.40f, toneDistance)
val flatAreaDamping = lerp(0.12f, 1f, detailGate)
val localSignal = max(toneVariation * flatAreaDamping, highlightPressure * 0.55f)
return (LOCAL_CURVE_MAX_BLEND * expandedScene * confidence * localSignal)
.coerceIn(0f, LOCAL_CURVE_MAX_BLEND)
}
private fun blendCurveParams(
first: AppleCurveParams,
second: AppleCurveParams,
amount: Float,
): AppleCurveParams {
val t = amount.coerceIn(0f, 1f)
return AppleCurveParams(
lowGain = lerp(first.lowGain, second.lowGain, t),
knee = lerp(first.knee, second.knee, t),
power = lerp(first.power, second.power, t),
terminalGain = lerp(first.terminalGain, second.terminalGain, t)
)
}
private fun buildMap(
grid: HdrPgtmGrid,
safePointCount: Int,
inputScale: Float,
sceneMax: Float,
params: Array<AppleCurveParams>,
): DngProfileGainTableMap {
val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * safePointCount)
val safeInputScale = sanitizeInputScale(inputScale)
for (cellIndex in 0 until grid.mapPointsH * grid.mapPointsV) {
writeAppleCurve(
output = gains,
outputOffset = cellIndex * safePointCount,
pointCount = safePointCount,
inputScale = safeInputScale,
sceneMax = sceneMax,
params = params[cellIndex]
)
}
return DngProfileGainTableMap(
mapPointsV = grid.mapPointsV,
mapPointsH = grid.mapPointsH,
mapSpacingV = grid.mapSpacingV,
mapSpacingH = grid.mapSpacingH,
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = safePointCount,
mapInputWeights = appleInputWeights(safeInputScale),
gamma = 1f,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
)
}
private fun writeAppleCurve(
output: FloatArray,
outputOffset: Int,
pointCount: Int,
inputScale: Float,
sceneMax: Float,
params: AppleCurveParams,
) {
var previousOutput = 0f
for (index in 0 until pointCount) {
val tableInput = tableInputForIndex(index, pointCount)
if (tableInput <= MIN_CURVE_INPUT) {
output[outputOffset + index] = params.lowGain.coerceIn(MIN_GAIN_VALUE, MAX_GAIN_VALUE)
continue
}
val scene = tableInput / inputScale
val rawGain = appleGainForScene(scene, sceneMax, params)
val targetOutput = (scene * rawGain).coerceIn(0f, 1f)
val monotonicOutput = max(previousOutput, targetOutput)
output[outputOffset + index] = (monotonicOutput / max(scene, MIN_CURVE_INPUT))
.coerceIn(MIN_GAIN_VALUE, MAX_GAIN_VALUE)
previousOutput = monotonicOutput
}
}
private fun appleGainForScene(
scene: Float,
sceneMax: Float,
params: AppleCurveParams,
): Float {
val safeScene = max(scene, MIN_CURVE_INPUT)
val rolloff = 1f / (1f + (safeScene / max(params.knee, 1e-4f)).pow(params.power))
val baseGain = params.terminalGain + (params.lowGain - params.terminalGain) * rolloff
val whiteGain = 1f / max(safeScene, MIN_CURVE_INPUT)
val whiteBlend = smoothStep(sceneMax * 0.62f, sceneMax, safeScene)
return lerp(baseGain, whiteGain, whiteBlend).coerceIn(MIN_GAIN_VALUE, MAX_GAIN_VALUE)
}
private fun appleInputWeights(inputScale: Float): FloatArray {
val scale = sanitizeInputScale(inputScale)
return FloatArray(MAP_INPUT_WEIGHT_COUNT) { index ->
BASE_INPUT_WEIGHTS[index] * scale
}
}
private fun chooseGrid(width: Int, height: Int): HdrPgtmGrid {
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
.coerceIn(GRID_MIN_H, GRID_MAX_H)
val mapPointsV = ((height + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
.coerceIn(GRID_MIN_V, GRID_MAX_V)
return HdrPgtmGrid(
mapPointsH = mapPointsH,
mapPointsV = mapPointsV,
mapSpacingH = if (mapPointsH > 1) 1.0 / (mapPointsH - 1).toDouble() else 1.0,
mapSpacingV = if (mapPointsV > 1) 1.0 / (mapPointsV - 1).toDouble() else 1.0
)
}
private fun weightedPercentile(
cells: List<HdrPgtmCellStats>,
percentile: Float,
selector: (HdrPgtmCellStats) -> Float,
): Float {
if (cells.isEmpty()) return 0f
val sorted = cells
.mapNotNull { cell ->
val value = selector(cell)
if (value.isFinite() && cell.sampleWeight > 0f) value to cell.sampleWeight else null
}
.sortedBy { it.first }
if (sorted.isEmpty()) return 0f
val totalWeight = sorted.sumOf { it.second.toDouble() }.toFloat()
val target = totalWeight * percentile.coerceIn(0f, 1f)
var cumulative = 0f
sorted.forEach { (value, weight) ->
cumulative += weight
if (cumulative >= target) return value
}
return sorted.last().first
}
private fun localRangeEv(cell: HdrPgtmCellStats): Float {
return log2((cell.p98 + 0.006f) / (cell.p10 + 0.006f)).coerceIn(0f, 8f)
}
private fun sanitizeInputScale(inputScale: Float): Float {
return inputScale.takeIf { it.isFinite() }
?.coerceIn(MIN_INPUT_SCALE, MAX_INPUT_SCALE)
?: MAX_INPUT_SCALE
}
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
if (pointCount <= 1) return 0f
return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat()
}
private fun safe01(value: Float): Float {
return value.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f
}
private fun safePositive(value: Float, fallback: Float): Float {
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
}
private fun smoothStep(edge0: Float, edge1: Float, x: Float): Float {
val t = ((x - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
private fun lerp(a: Float, b: Float, t: Float): Float {
return a + (b - a) * min(max(t, 0f), 1f)
}
private fun log2(value: Float): Float {
return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat()
}
private fun absLogRatio(first: Float, second: Float): Float {
return kotlin.math.abs(log2(first / max(second, 1e-6f)))
}
private data class AppleCurveParams(
val lowGain: Float,
val knee: Float,
val power: Float,
val terminalGain: Float,
)
}
@@ -104,12 +104,6 @@ internal object DngEmbeddedProfile {
return profileName?.contains("google", ignoreCase = true) == true
}
fun isAppleProRawProfileName(profileName: String?): Boolean {
if (profileName.isNullOrBlank()) return false
return profileName.contains("apple", ignoreCase = true) ||
profileName.contains("proraw", ignoreCase = true)
}
private fun decodeProfile(
raf: RandomAccessFile,
ifd: Map<Int, TiffEntry>,
@@ -75,30 +75,6 @@ internal object DngProfileToneCurve {
0.97638f, 0.99517f, 0.98425f, 0.99686f, 0.99213f, 0.99845f, 1f, 1f
)
private val APPLE_PRO_RAW_FITTED_TONE_CURVE_ANCHORS = floatArrayOf(
0.00000000f, 0.000000000f,
0.00390625f, 0.000012401f,
0.00781250f, 0.000072635f,
0.01171875f, 0.000206685f,
0.01562500f, 0.000553325f,
0.01953125f, 0.001360578f,
0.02343750f, 0.002622200f,
0.02734375f, 0.004144829f,
0.03125000f, 0.005831674f,
0.04687500f, 0.013821328f,
0.06250000f, 0.023228984f,
0.09375000f, 0.045079457f,
0.12500000f, 0.069945026f,
0.17968750f, 0.118763626f,
0.25000000f, 0.188884780f,
0.37500000f, 0.327727005f,
0.50000000f, 0.479043320f,
0.62500000f, 0.636591673f,
0.75000000f, 0.779041231f,
0.87500000f, 0.896886647f,
1.00000000f, 1.000000000f
)
fun googleHdrToneCurvePoints(): FloatArray {
return FloatArray(GOOGLE_HDR_TONE_CURVE_Y.size * 2) { index ->
val pointIndex = index / 2
@@ -122,14 +98,6 @@ internal object DngProfileToneCurve {
return DcpToneCurve(oppoEmbeddedToneCurvePoints()).toLut(sampleCount)
}
fun appleProRawFittedToneCurvePoints(): FloatArray {
return fittedToneCurvePoints(APPLE_PRO_RAW_FITTED_TONE_CURVE_ANCHORS)
}
fun appleProRawFittedToneCurveLut(sampleCount: Int = 256): FloatArray {
return DcpToneCurve(appleProRawFittedToneCurvePoints()).toLut(sampleCount)
}
fun isGoogleHdrToneCurve(toneCurve: DcpToneCurve?): Boolean {
if (toneCurve?.isValid != true) return false
val googlePoints = googleHdrToneCurvePoints()
@@ -168,30 +136,4 @@ internal object DngProfileToneCurve {
}
}
private fun fittedToneCurvePoints(anchors: FloatArray, pointCount: Int = 257): FloatArray {
return FloatArray(pointCount * 2) { index ->
val pointIndex = index / 2
val x = pointIndex.toFloat() / (pointCount - 1).toFloat()
if ((index and 1) == 0) {
x
} else {
sampleAnchoredCurve(anchors, x)
}
}
}
private fun sampleAnchoredCurve(anchors: FloatArray, input: Float): Float {
val x = input.coerceIn(0f, 1f)
var segment = 0
val lastSegment = anchors.size / 2 - 2
while (segment < lastSegment && x > anchors[(segment + 1) * 2]) {
segment++
}
val x0 = anchors[segment * 2]
val y0 = anchors[segment * 2 + 1]
val x1 = anchors[(segment + 1) * 2]
val y1 = anchors[(segment + 1) * 2 + 1]
val t = if (x1 == x0) 0f else ((x - x0) / (x1 - x0)).coerceIn(0f, 1f)
return y0 + (y1 - y0) * t
}
}
@@ -1415,32 +1415,22 @@ class RawDemosaicProcessor {
DngProfileToneCurve.isGoogleHdrToneCurveLut(it) ||
DngEmbeddedProfile.isGoogleProfileName(embeddedDngProfileName)
}
val embeddedAppleProfileAvailable = DngEmbeddedProfile.isAppleProRawProfileName(embeddedDngProfileName)
val embeddedAppleToneCurveLut = embeddedDngRenderPlan?.toneCurveLut
?.takeIf { embeddedAppleProfileAvailable }
val embeddedProfileGainTableMap = actualMetadata.profileGainTableMap?.takeIf { it.isValid }
val embeddedDngHdrToneMapAvailable = embeddedGoogleToneCurveLut != null &&
embeddedProfileGainTableMap != null
val embeddedAppleProRawToneMapAvailable = embeddedAppleProfileAvailable &&
embeddedProfileGainTableMap != null
val inactiveEmbeddedProfileGainTableMapAvailable = embeddedProfileGainTableMap != null &&
!embeddedDngHdrToneMapAvailable
val normalizedToneMappingParameters = rawToneMappingParameters.normalized()
val googlePixelToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.useGooglePixelToneMap
val oppoMasterToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.useOppoMasterToneMap
val appleProRawToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.useAppleProRawToneMap
val embeddedDngHdrToneMapDisabledByUser = embeddedDngHdrToneMapAvailable &&
useAdobeProfilePipeline &&
!oppoMasterToneMapRequested &&
!googlePixelToneMapRequested
val embeddedDngHdrToneMapDisabledByOppo = embeddedDngHdrToneMapAvailable &&
oppoMasterToneMapRequested
val embeddedDngHdrToneMapDisabledByApple = embeddedDngHdrToneMapAvailable &&
appleProRawToneMapRequested
val embeddedAppleToneMapDisabledByMode = embeddedAppleProfileAvailable &&
useAdobeProfilePipeline &&
!appleProRawToneMapRequested
if (embeddedDngHdrToneMapAvailable) {
PLog.d(
TAG,
@@ -1451,41 +1441,20 @@ class RawDemosaicProcessor {
"googleTone=${normalizedToneMappingParameters.useGooglePixelToneMap}"
)
}
if (embeddedAppleProRawToneMapAvailable) {
PLog.d(
TAG,
"Embedded Apple ProRAW PGTM/ProfileToneCurve available: " +
"tag=${embeddedProfileGainTableMap.sourceTag} " +
"grid=${embeddedProfileGainTableMap.mapPointsH}x" +
"${embeddedProfileGainTableMap.mapPointsV}x${embeddedProfileGainTableMap.mapPointsN} " +
"appleTone=${normalizedToneMappingParameters.useAppleProRawToneMap} " +
"profile=$embeddedDngProfileName"
)
}
val embeddedDngHdrToneMapOverriddenByDcp = embeddedDngHdrToneMapAvailable &&
useAdobeProfilePipeline &&
hasDcpSelection &&
resolvedDcpRenderPlan?.toneCurveLut != null
val embeddedAppleToneMapOverriddenByDcp = embeddedAppleProRawToneMapAvailable &&
useAdobeProfilePipeline &&
hasDcpSelection &&
resolvedDcpRenderPlan?.toneCurveLut != null
val embeddedDngHdrToneMapRenderable = embeddedDngHdrToneMapAvailable &&
useAdobeProfilePipeline &&
googlePixelToneMapRequested &&
!embeddedDngHdrToneMapOverriddenByDcp &&
!embeddedDngHdrToneMapDisabledByUser &&
!embeddedDngHdrToneMapDisabledByOppo &&
!embeddedDngHdrToneMapDisabledByApple
val embeddedAppleToneMapRenderable = embeddedAppleProRawToneMapAvailable &&
useAdobeProfilePipeline &&
appleProRawToneMapRequested &&
!embeddedAppleToneMapOverriddenByDcp
!embeddedDngHdrToneMapDisabledByOppo
if (embeddedDngHdrToneMapAvailable && !embeddedDngHdrToneMapRenderable) {
val reason = when {
embeddedDngHdrToneMapDisabledByUser -> "Pixel-style tone map disabled for this photo"
embeddedDngHdrToneMapDisabledByOppo -> "OPPO master tone map requested"
embeddedDngHdrToneMapDisabledByApple -> "Apple ProRAW tone map requested"
!useAdobeProfilePipeline -> "color engine $colorEngine does not use Adobe/DNG profile tone map"
embeddedDngHdrToneMapOverriddenByDcp -> "selected DCP has tone curve: ${resolvedDcpRenderPlan.profileName}"
else -> "current render pipeline does not use embedded DNG HDR tone map"
@@ -1496,17 +1465,11 @@ class RawDemosaicProcessor {
"Embedded DNG PGTM/ProfileToneCurve not rendered: reason=$reason"
)
}
if (embeddedAppleProRawToneMapAvailable && !embeddedAppleToneMapRenderable) {
val reason = when {
embeddedAppleToneMapDisabledByMode -> "Apple ProRAW tone map disabled for this photo"
!useAdobeProfilePipeline -> "color engine $colorEngine does not use Adobe/DNG profile tone map"
embeddedAppleToneMapOverriddenByDcp -> "selected DCP has tone curve: ${resolvedDcpRenderPlan.profileName}"
else -> "current render pipeline does not use embedded Apple ProRAW tone map"
}
if (inactiveEmbeddedProfileGainTableMapAvailable) {
actualMetadata = actualMetadata.copy(profileGainTableMap = null)
PLog.d(
TAG,
"Embedded Apple ProRAW PGTM/ProfileToneCurve not rendered: reason=$reason"
"Embedded DNG ProfileGainTableMap ignored: profile=$embeddedDngProfileName"
)
}
val requestedGeneratedPixelToneMap = googlePixelToneMapRequested &&
@@ -1516,13 +1479,6 @@ class RawDemosaicProcessor {
resolvedDcpRenderPlan?.toneCurveLut != null
val generatePixelToneMap = requestedGeneratedPixelToneMap &&
!generatedPixelToneMapOverriddenByDcp
val requestedGeneratedAppleToneMap = appleProRawToneMapRequested &&
!embeddedAppleProRawToneMapAvailable
val generatedAppleToneMapOverriddenByDcp = requestedGeneratedAppleToneMap &&
hasDcpSelection &&
resolvedDcpRenderPlan?.toneCurveLut != null
val generateAppleToneMap = requestedGeneratedAppleToneMap &&
!generatedAppleToneMapOverriddenByDcp
if (generatedPixelToneMapOverriddenByDcp) {
PLog.d(
TAG,
@@ -1530,19 +1486,9 @@ class RawDemosaicProcessor {
"profile=${resolvedDcpRenderPlan.profileName}"
)
}
if (generatedAppleToneMapOverriddenByDcp) {
PLog.d(
TAG,
"Generated Apple ProRAW PGTM/ProfileToneCurve not rendered because selected DCP has tone curve: " +
"profile=${resolvedDcpRenderPlan.profileName}"
)
}
if (embeddedDngHdrToneMapRenderable) {
PLog.d(TAG, "Using embedded Pixel-style DNG PGTM/ProfileToneCurve")
}
if (embeddedAppleToneMapRenderable) {
PLog.d(TAG, "Using embedded Apple ProRAW PGTM/ProfileToneCurve")
}
if (generatePixelToneMap) {
val generatedProfileGainTableMap = RawProfileGainTableMapBuilder.build(
rawData = actualRawData,
@@ -1551,8 +1497,7 @@ class RawDemosaicProcessor {
rowStride = actualRowStride,
metadata = actualMetadata,
samplesPerPixel = actualSamplesPerPixel,
statsBounds = outputSourceBounds,
toneMapMode = RawProfileToneMapMode.GooglePixel
statsBounds = outputSourceBounds
)
if (generatedProfileGainTableMap?.isValid == true) {
actualMetadata = actualMetadata.copy(profileGainTableMap = generatedProfileGainTableMap)
@@ -1571,44 +1516,12 @@ class RawDemosaicProcessor {
PLog.w(TAG, "Google Pixel tone map requested but PGTM stats generation failed")
}
}
if (generateAppleToneMap) {
val generatedProfileGainTableMap = RawProfileGainTableMapBuilder.build(
rawData = actualRawData,
width = actualWidth,
height = actualHeight,
rowStride = actualRowStride,
metadata = actualMetadata,
samplesPerPixel = actualSamplesPerPixel,
statsBounds = outputSourceBounds,
toneMapMode = RawProfileToneMapMode.AppleProRaw
)
if (generatedProfileGainTableMap?.isValid == true) {
actualMetadata = actualMetadata.copy(profileGainTableMap = generatedProfileGainTableMap)
PLog.d(
TAG,
"Generated Apple ProRAW tone map PGTM for RAW: " +
"grid=${generatedProfileGainTableMap.mapPointsH}x" +
"${generatedProfileGainTableMap.mapPointsV}x" +
"${generatedProfileGainTableMap.mapPointsN}"
)
DngPgtmDebugRewriter.rewriteGeneratedPgtmOnRawRefreshIfEnabled(
dngFile = dngFile,
profileGainTableMap = generatedProfileGainTableMap
)
} else {
PLog.w(TAG, "Apple ProRAW tone map requested but PGTM stats generation failed")
}
}
val googlePixelToneMapActive = (embeddedDngHdrToneMapRenderable || generatePixelToneMap) &&
actualMetadata.profileGainTableMap?.isValid == true
val appleProRawToneMapActive = (embeddedAppleToneMapRenderable || generateAppleToneMap) &&
actualMetadata.profileGainTableMap?.isValid == true
val oppoMasterToneMapActive = oppoMasterToneMapRequested
val embeddedProfileToneCurveDisabled = (
embeddedDngHdrToneMapDisabledByUser ||
embeddedDngHdrToneMapDisabledByOppo ||
embeddedDngHdrToneMapDisabledByApple ||
embeddedAppleToneMapDisabledByMode
embeddedDngHdrToneMapDisabledByOppo
)
val profileBaseDcpRenderPlan = if (
embeddedProfileToneCurveDisabled &&
@@ -1619,8 +1532,6 @@ class RawDemosaicProcessor {
resolvedDcpRenderPlan,
reason = when {
embeddedDngHdrToneMapDisabledByOppo -> "OPPO master tone map requested"
embeddedDngHdrToneMapDisabledByApple -> "Apple ProRAW tone map requested"
embeddedAppleToneMapDisabledByMode -> "Apple ProRAW tone map disabled for this photo"
else -> "Pixel-style tone map disabled for this photo"
}
)
@@ -1636,14 +1547,6 @@ class RawDemosaicProcessor {
preferredToneCurveLut = embeddedGoogleToneCurveLut.takeIf { embeddedDngHdrToneMapRenderable }
)
}
appleProRawToneMapActive -> {
appleProRawToneMapRenderPlan(
basePlan = profileBaseDcpRenderPlan,
metadata = actualMetadata,
workingColorSpace = profileWorkingColorSpace,
preferredToneCurveLut = embeddedAppleToneCurveLut.takeIf { embeddedAppleProfileAvailable }
)
}
oppoMasterToneMapActive -> {
oppoMasterToneMapRenderPlan(
basePlan = profileBaseDcpRenderPlan,
@@ -1660,12 +1563,6 @@ class RawDemosaicProcessor {
!hasDcpSelection && embeddedDngRenderPlan != null -> "embedded-dng+google-pixel-tone-map"
else -> "google-pixel-tone-map"
}
appleProRawToneMapActive -> when {
dcpRenderPlan != null -> "provided+apple-proraw-tone-map"
rawDcpId != null -> "$rawDcpId+apple-proraw-tone-map"
!hasDcpSelection && embeddedDngRenderPlan != null -> "embedded-dng+apple-proraw-tone-map"
else -> "apple-proraw-tone-map"
}
oppoMasterToneMapActive -> when {
dcpRenderPlan != null -> "provided+oppo-master-tone-map"
rawDcpId != null -> "$rawDcpId+oppo-master-tone-map"
@@ -7094,48 +6991,6 @@ class RawDemosaicProcessor {
)
}
private fun appleProRawToneMapRenderPlan(
basePlan: DcpRenderPlan?,
metadata: RawMetadata,
workingColorSpace: ColorSpace,
preferredToneCurveLut: FloatArray? = null,
): DcpRenderPlan {
val appleToneCurve = preferredToneCurveLut?.copyOf() ?: DngProfileToneCurve.appleProRawFittedToneCurveLut()
val baseExposureOffset = basePlan?.baselineExposureOffset ?: 0f
val defaultBlackRender = DcpDefaultBlackRender.None
val exposureNormalization = DngAppleProRawExposureNormalizer.resolveExposureOffset(
profileGainTableMap = metadata.profileGainTableMap,
baselineExposureEv = metadata.baselineExposure,
toneCurveLut = appleToneCurve,
existingExposureOffsetEv = baseExposureOffset,
defaultBlackRender = defaultBlackRender,
shadowScale = metadata.shadowScale
)
val appleExposureOffset = baseExposureOffset + exposureNormalization.additionalExposureOffsetEv
if (exposureNormalization.additionalExposureOffsetEv < -0.01f) {
PLog.d(
TAG,
"Apple ProRAW exposure normalized: " +
"averageEv=${formatEv(exposureNormalization.measuredAverageEv)} " +
"targetEv=${formatEv(exposureNormalization.targetAverageEv)} " +
"normalizedEv=${formatEv(exposureNormalization.normalizedAverageEv)} " +
"offsetEv=${formatEv(exposureNormalization.additionalExposureOffsetEv)}"
)
}
return DcpRenderPlan(
profileName = basePlan?.profileName?.let { "$it + Apple ProRAW Tone Map" }
?: "Apple ProRAW Tone Map",
workingColorSpace = basePlan?.workingColorSpace ?: workingColorSpace,
baselineExposureOffset = appleExposureOffset,
defaultBlackRender = defaultBlackRender,
colorCorrectionMatrix = basePlan?.colorCorrectionMatrix ?: metadata.colorCorrectionMatrix,
cameraWhite = basePlan?.cameraWhite ?: metadata.cameraWhite,
hueSatMap = basePlan?.hueSatMap,
lookTable = basePlan?.lookTable,
toneCurveLut = appleToneCurve
)
}
private fun withoutProfileToneCurve(
plan: DcpRenderPlan?,
reason: String
@@ -7145,14 +7000,6 @@ class RawDemosaicProcessor {
return plan.copy(toneCurveLut = null)
}
private fun formatEv(value: Float): String {
return if (value.isFinite()) {
String.format(Locale.US, "%.3f", value)
} else {
"n/a"
}
}
private fun resolveLinearColorCorrectionMatrix(
metadata: RawMetadata,
dcpRenderPlan: DcpRenderPlan?
@@ -21,7 +21,6 @@ internal object RawProfileGainTableMapBuilder {
metadata: RawMetadata,
samplesPerPixel: Int = 1,
statsBounds: Rect? = null,
toneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.GooglePixel,
): DngProfileGainTableMap? {
val stats = buildPackedCellStats(
rawData = rawData,
@@ -30,27 +29,16 @@ internal object RawProfileGainTableMapBuilder {
rowStride = rowStride,
metadata = metadata,
samplesPerPixel = samplesPerPixel,
statsBounds = statsBounds,
toneMapMode = toneMapMode
statsBounds = statsBounds
) ?: return null
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG)
return when (toneMapMode) {
RawProfileToneMapMode.AppleProRaw -> DngAppleProRawProfileGainTableGenerator.forCellStats(
width = width,
height = height,
baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure),
packedCellStats = stats,
diagnosticBand = diagnosticBand
)
else -> DngHdrProfileGainTableGenerator.forCellStats(
width = width,
height = height,
baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure),
packedCellStats = stats,
diagnosticBand = diagnosticBand
)
}
return DngHdrProfileGainTableGenerator.forCellStats(
width = width,
height = height,
baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure),
packedCellStats = stats,
diagnosticBand = diagnosticBand
)
}
private fun buildPackedCellStats(
@@ -61,7 +49,6 @@ internal object RawProfileGainTableMapBuilder {
metadata: RawMetadata,
samplesPerPixel: Int,
statsBounds: Rect?,
toneMapMode: RawProfileToneMapMode,
): FloatArray? {
if (width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) return null
val sampleCountPerPixel = samplesPerPixel.coerceAtLeast(1)
@@ -131,8 +118,7 @@ internal object RawProfileGainTableMapBuilder {
baseX = x,
baseY = y,
baselineGain = baselineGain,
samplesPerPixel = sampleCountPerPixel,
toneMapMode = toneMapMode
samplesPerPixel = sampleCountPerPixel
)
inputSamples[sampleCount] = inputValue
val clampedInput = inputValue.coerceIn(0f, 1f)
@@ -195,7 +181,6 @@ internal object RawProfileGainTableMapBuilder {
baseY: Int,
baselineGain: Float,
samplesPerPixel: Int,
toneMapMode: RawProfileToneMapMode,
): Float {
if (samplesPerPixel >= 3) {
return linearRgbPgtmInputAt(
@@ -207,8 +192,7 @@ internal object RawProfileGainTableMapBuilder {
x = baseX,
y = baseY,
baselineGain = baselineGain,
samplesPerPixel = samplesPerPixel,
toneMapMode = toneMapMode
samplesPerPixel = samplesPerPixel
)
}
var r = 0f
@@ -245,7 +229,6 @@ internal object RawProfileGainTableMapBuilder {
val green = if (gc > 0f) g / gc else fallback
val blue = if (bc > 0f) b / bc else fallback
return sceneInputFromLinearRgb(
toneMapMode = toneMapMode,
red = red,
green = green,
blue = blue,
@@ -264,7 +247,6 @@ internal object RawProfileGainTableMapBuilder {
y: Int,
baselineGain: Float,
samplesPerPixel: Int,
toneMapMode: RawProfileToneMapMode,
): Float {
val clampedX = x.coerceIn(0, width - 1)
val clampedY = y.coerceIn(0, height - 1)
@@ -273,7 +255,6 @@ internal object RawProfileGainTableMapBuilder {
val green = normalizedLinearRgbAt(rawData, pixelOffset + 2, metadata, 1)
val blue = normalizedLinearRgbAt(rawData, pixelOffset + 4, metadata, 2)
return sceneInputFromLinearRgb(
toneMapMode = toneMapMode,
red = red,
green = green,
blue = blue,
@@ -283,30 +264,19 @@ internal object RawProfileGainTableMapBuilder {
}
private fun sceneInputFromLinearRgb(
toneMapMode: RawProfileToneMapMode,
red: Float,
green: Float,
blue: Float,
baselineGain: Float,
colorCorrectionMatrix: FloatArray?,
): Float {
return when (toneMapMode) {
RawProfileToneMapMode.AppleProRaw -> DngAppleProRawProfileGainTableGenerator.sceneInputFromLinearRgb(
red = red,
green = green,
blue = blue,
baselineGain = baselineGain,
colorCorrectionMatrix = colorCorrectionMatrix
)
else -> DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
red = red,
green = green,
blue = blue,
baselineGain = baselineGain,
colorCorrectionMatrix = colorCorrectionMatrix
)
}
return DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
red = red,
green = green,
blue = blue,
baselineGain = baselineGain,
colorCorrectionMatrix = colorCorrectionMatrix
)
}
private fun normalizedLinearRgbAt(
@@ -11,10 +11,6 @@ object RawToneMappingGl {
DngProfileToneCurve.oppoEmbeddedToneCurveLut()
}
private val APPLE_PRO_RAW_ADOBE_CURVE by lazy {
DngProfileToneCurve.appleProRawFittedToneCurveLut()
}
data class FilmicToneCurveUniforms(
val blackRelativeExposure: Float,
val whiteRelativeExposure: Float,
@@ -34,7 +30,6 @@ object RawToneMappingGl {
val normalized = params.normalized()
return when (normalized.profileToneMapMode) {
RawProfileToneMapMode.OppoMaster -> OPPO_MASTER_ADOBE_CURVE
RawProfileToneMapMode.AppleProRaw -> APPLE_PRO_RAW_ADOBE_CURVE
else -> ACR3Curve.samples()
}
}
@@ -8,12 +8,10 @@ data class RawToneMappingParameters(
val filmicBlackRelativeExposure: Float = FILMIC_BLACK_RELATIVE_EXPOSURE_DEFAULT,
val filmicWhiteRelativeExposure: Float = FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
val useGooglePixelToneMap: Boolean = false,
val useOppoMasterToneMap: Boolean = false,
val useAppleProRawToneMap: Boolean = false
val useOppoMasterToneMap: Boolean = false
) {
val profileToneMapMode: RawProfileToneMapMode
get() = when {
useAppleProRawToneMap -> RawProfileToneMapMode.AppleProRaw
useOppoMasterToneMap -> RawProfileToneMapMode.OppoMaster
useGooglePixelToneMap -> RawProfileToneMapMode.GooglePixel
else -> RawProfileToneMapMode.Default
@@ -36,9 +34,8 @@ data class RawToneMappingParameters(
FILMIC_WHITE_RELATIVE_EXPOSURE_MIN,
FILMIC_WHITE_RELATIVE_EXPOSURE_MAX
)
val appleTone = useAppleProRawToneMap
val oppoTone = useOppoMasterToneMap && !appleTone
val googleTone = useGooglePixelToneMap && !oppoTone && !appleTone
val oppoTone = useOppoMasterToneMap
val googleTone = useGooglePixelToneMap && !oppoTone
return copy(
agxBlackRelativeExposure = minOf(blackAgx, whiteAgx - MIN_DYNAMIC_RANGE_EV),
agxWhiteRelativeExposure = maxOf(whiteAgx, blackAgx + MIN_DYNAMIC_RANGE_EV),
@@ -47,40 +44,28 @@ data class RawToneMappingParameters(
filmicBlackRelativeExposure = minOf(blackFilmic, whiteFilmic - MIN_DYNAMIC_RANGE_EV),
filmicWhiteRelativeExposure = maxOf(whiteFilmic, blackFilmic + MIN_DYNAMIC_RANGE_EV),
useGooglePixelToneMap = googleTone,
useOppoMasterToneMap = oppoTone,
useAppleProRawToneMap = appleTone
useOppoMasterToneMap = oppoTone
)
}
fun withGooglePixelToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
useGooglePixelToneMap = enabled,
useOppoMasterToneMap = if (enabled) false else useOppoMasterToneMap,
useAppleProRawToneMap = if (enabled) false else useAppleProRawToneMap
useOppoMasterToneMap = if (enabled) false else useOppoMasterToneMap
).normalized()
}
fun withOppoMasterToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
useOppoMasterToneMap = enabled,
useGooglePixelToneMap = if (enabled) false else useGooglePixelToneMap,
useAppleProRawToneMap = if (enabled) false else useAppleProRawToneMap
).normalized()
}
fun withAppleProRawToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
useAppleProRawToneMap = enabled,
useGooglePixelToneMap = if (enabled) false else useGooglePixelToneMap,
useOppoMasterToneMap = if (enabled) false else useOppoMasterToneMap
useGooglePixelToneMap = if (enabled) false else useGooglePixelToneMap
).normalized()
}
fun withProfileToneMapMode(mode: RawProfileToneMapMode): RawToneMappingParameters {
return copy(
useGooglePixelToneMap = mode == RawProfileToneMapMode.GooglePixel,
useOppoMasterToneMap = mode == RawProfileToneMapMode.OppoMaster,
useAppleProRawToneMap = mode == RawProfileToneMapMode.AppleProRaw
useOppoMasterToneMap = mode == RawProfileToneMapMode.OppoMaster
).normalized()
}
@@ -113,7 +98,6 @@ data class RawToneMappingParameters(
enum class RawProfileToneMapMode {
Default,
AppleProRaw,
OppoMaster,
GooglePixel,
}
@@ -444,7 +444,6 @@ private fun RawProfileToneMapSwitches(
description = stringResource(R.string.settings_raw_profile_tone_map_description),
levels = listOf(
RawProfileToneMapMode.Default.name to stringResource(R.string.settings_raw_profile_tone_map_default),
RawProfileToneMapMode.AppleProRaw.name to stringResource(R.string.settings_raw_profile_tone_map_apple_proraw),
RawProfileToneMapMode.OppoMaster.name to stringResource(R.string.settings_raw_profile_tone_map_oppo_master),
RawProfileToneMapMode.GooglePixel.name to stringResource(R.string.settings_raw_profile_tone_map_google_pixel),
),
@@ -108,7 +108,6 @@ fun PresetEditorScreen(
}
var rawGooglePixelToneMap by remember { mutableStateOf(sourcePreset?.rawGooglePixelToneMap ?: false) }
var rawOppoMasterToneMap by remember { mutableStateOf(sourcePreset?.rawOppoMasterToneMap ?: false) }
var rawAppleProRawToneMap by remember { mutableStateOf(sourcePreset?.rawAppleProRawToneMap ?: false) }
var rawSpectralFilmStock by remember { mutableStateOf(sourcePreset?.rawSpectralFilmStock ?: "kodak_portra_400") }
var rawSpectralFilmPrint by remember { mutableStateOf(sourcePreset?.rawSpectralFilmPrint ?: "kodak_2383") }
var rawDROMode by remember { mutableStateOf(sourcePreset?.rawDROMode ?: "OFF") }
@@ -148,7 +147,6 @@ fun PresetEditorScreen(
rawRenderingEngine = rawRenderingEngine.name,
rawGooglePixelToneMap = rawGooglePixelToneMap,
rawOppoMasterToneMap = rawOppoMasterToneMap,
rawAppleProRawToneMap = rawAppleProRawToneMap,
rawSpectralFilmStock = rawSpectralFilmStock,
rawSpectralFilmPrint = rawSpectralFilmPrint,
rawDROMode = rawDROMode,
@@ -444,12 +442,10 @@ fun PresetEditorScreen(
val toneMapLabels = mapOf(
RawProfileToneMapMode.Default to stringResource(R.string.settings_raw_profile_tone_map_default),
RawProfileToneMapMode.AppleProRaw to stringResource(R.string.settings_raw_profile_tone_map_apple_proraw),
RawProfileToneMapMode.OppoMaster to stringResource(R.string.settings_raw_profile_tone_map_oppo_master),
RawProfileToneMapMode.GooglePixel to stringResource(R.string.settings_raw_profile_tone_map_google_pixel),
)
val selectedToneMapMode = when {
rawAppleProRawToneMap -> RawProfileToneMapMode.AppleProRaw
rawOppoMasterToneMap -> RawProfileToneMapMode.OppoMaster
rawGooglePixelToneMap -> RawProfileToneMapMode.GooglePixel
else -> RawProfileToneMapMode.Default
@@ -468,7 +464,6 @@ fun PresetEditorScreen(
?: RawProfileToneMapMode.Default
rawGooglePixelToneMap = selectedMode == RawProfileToneMapMode.GooglePixel
rawOppoMasterToneMap = selectedMode == RawProfileToneMapMode.OppoMaster
rawAppleProRawToneMap = selectedMode == RawProfileToneMapMode.AppleProRaw
}
)
@@ -155,7 +155,6 @@ private data class PresetMatchSnapshot(
val rawRenderingEngine: RawRenderingEngine,
val rawGooglePixelToneMap: Boolean,
val rawOppoMasterToneMap: Boolean,
val rawAppleProRawToneMap: Boolean,
val rawSpectralFilmStock: String?,
val rawSpectralFilmPrint: String?,
val rawDROMode: String,
@@ -180,7 +179,6 @@ private data class PresetMatchSnapshot(
rawRenderingEngine == RawRenderingEngine.fromPersistedName(preset.rawRenderingEngine) &&
rawGooglePixelToneMap == preset.rawGooglePixelToneMap &&
rawOppoMasterToneMap == preset.rawOppoMasterToneMap &&
rawAppleProRawToneMap == preset.rawAppleProRawToneMap &&
rawSpectralFilmStock == preset.rawSpectralFilmStock &&
rawSpectralFilmPrint == preset.rawSpectralFilmPrint &&
rawDROMode == preset.rawDROMode &&
@@ -222,12 +220,6 @@ private data class PresetMatchSnapshot(
"preset=${preset.rawOppoMasterToneMap}"
)
}
if (rawAppleProRawToneMap != preset.rawAppleProRawToneMap) {
add(
"rawAppleProRawToneMap current=$rawAppleProRawToneMap " +
"preset=${preset.rawAppleProRawToneMap}"
)
}
if (rawSpectralFilmStock != preset.rawSpectralFilmStock) {
add("rawSpectralFilmStock current=$rawSpectralFilmStock preset=${preset.rawSpectralFilmStock}")
}
@@ -275,7 +267,6 @@ private data class CameraFeatureUpdate(
val rawRenderingEngine: SettingValue<RawRenderingEngine>? = null,
val rawGooglePixelToneMap: SettingValue<Boolean>? = null,
val rawOppoMasterToneMap: SettingValue<Boolean>? = null,
val rawAppleProRawToneMap: SettingValue<Boolean>? = null,
val rawSpectralFilmStock: SettingValue<String?>? = null,
val rawSpectralFilmPrint: SettingValue<String?>? = null,
val droMode: SettingValue<String>? = null,
@@ -400,7 +391,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawRenderingEngine = saved.rawRenderingEngine,
rawGooglePixelToneMap = saved.rawGooglePixelToneMap,
rawOppoMasterToneMap = saved.rawOppoMasterToneMap,
rawAppleProRawToneMap = saved.rawAppleProRawToneMap,
rawSpectralFilmStock = saved.rawSpectralFilmStock,
rawSpectralFilmPrint = saved.rawSpectralFilmPrint,
rawDROMode = saved.rawDROMode,
@@ -464,7 +454,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawRenderingEngine = rawRenderingEngine.value.name,
rawGooglePixelToneMap = rawToneMappingParameters.value.useGooglePixelToneMap,
rawOppoMasterToneMap = rawToneMappingParameters.value.useOppoMasterToneMap,
rawAppleProRawToneMap = rawToneMappingParameters.value.useAppleProRawToneMap,
rawSpectralFilmStock = rawSpectralFilmStock.value,
rawSpectralFilmPrint = rawSpectralFilmPrint.value,
rawDROMode = droMode.value,
@@ -539,7 +528,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawRenderingEngine = SettingValue(RawRenderingEngine.fromPersistedName(this?.rawRenderingEngine)),
rawGooglePixelToneMap = SettingValue(this?.rawGooglePixelToneMap ?: false),
rawOppoMasterToneMap = SettingValue(this?.rawOppoMasterToneMap ?: false),
rawAppleProRawToneMap = SettingValue(this?.rawAppleProRawToneMap ?: false),
rawSpectralFilmStock = SettingValue(this?.rawSpectralFilmStock),
rawSpectralFilmPrint = SettingValue(this?.rawSpectralFilmPrint),
droMode = SettingValue(this?.rawDROMode ?: RawProcessingPreferences.DROMode.OFF.name),
@@ -669,8 +657,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val rawToneMappingUpdate = if (
update.rawGooglePixelToneMap != null ||
update.rawOppoMasterToneMap != null ||
update.rawAppleProRawToneMap != null
update.rawOppoMasterToneMap != null
) {
var toneMappingParameters = prefs.rawToneMappingParameters
update.rawGooglePixelToneMap?.let {
@@ -679,9 +666,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
update.rawOppoMasterToneMap?.let {
toneMappingParameters = toneMappingParameters.withOppoMasterToneMap(it.value)
}
update.rawAppleProRawToneMap?.let {
toneMappingParameters = toneMappingParameters.withAppleProRawToneMap(it.value)
}
PreferenceUpdateValue(toneMappingParameters)
} else {
null
@@ -943,7 +927,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawRenderingEngine = rawRenderingEngine.value,
rawGooglePixelToneMap = rawToneMappingParameters.value.useGooglePixelToneMap,
rawOppoMasterToneMap = rawToneMappingParameters.value.useOppoMasterToneMap,
rawAppleProRawToneMap = rawToneMappingParameters.value.useAppleProRawToneMap,
rawSpectralFilmStock = rawSpectralFilmStock.value,
rawSpectralFilmPrint = rawSpectralFilmPrint.value,
rawDROMode = droMode.value,
@@ -969,7 +952,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawRenderingEngine = prefs.rawRenderingEngine,
rawGooglePixelToneMap = prefs.rawToneMappingParameters.useGooglePixelToneMap,
rawOppoMasterToneMap = prefs.rawToneMappingParameters.useOppoMasterToneMap,
rawAppleProRawToneMap = prefs.rawToneMappingParameters.useAppleProRawToneMap,
rawSpectralFilmStock = prefs.rawSpectralFilmStock,
rawSpectralFilmPrint = prefs.rawSpectralFilmPrint,
rawDROMode = prefs.droMode,
@@ -751,7 +751,6 @@
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_apple_proraw">Apple ProRAW</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
@@ -756,7 +756,6 @@
<string name="settings_raw_profile_tone_map_default">默认</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大师</string>
<string name="settings_raw_profile_tone_map_apple_proraw">Apple ProRAW</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相对曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相对曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
@@ -756,7 +756,6 @@
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_apple_proraw">Apple ProRAW</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
@@ -751,7 +751,6 @@
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_apple_proraw">Apple ProRAW</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
-1
View File
@@ -740,7 +740,6 @@
<string name="settings_raw_profile_tone_map_default">Default</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO Master</string>
<string name="settings_raw_profile_tone_map_apple_proraw">Apple ProRAW</string>
<string name="settings_raw_agx_white_relative_exposure">AgX White Relative Exposure</string>
<string name="settings_raw_agx_black_relative_exposure">AgX Black Relative Exposure</string>
<string name="settings_raw_agx_shoulder">AgX Shoulder</string>
@@ -1,352 +0,0 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.ceil
class DngAppleProRawProfileGainTableGeneratorTest {
@Test
fun appleProRawFittedToneCurveKeepsLowAnchors() {
val curve = DngProfileToneCurve.appleProRawFittedToneCurvePoints()
assertEquals(514, curve.size)
assertEquals(0f, curve[0], 0f)
assertEquals(0f, curve[1], 0f)
assertEquals(0.000012401f, toneCurveYAtIndex(curve, 1), 1e-8f)
assertEquals(0.000553325f, toneCurveYAtIndex(curve, 4), 1e-7f)
assertEquals(0.005831674f, toneCurveYAtIndex(curve, 8), 1e-7f)
assertEquals(0.069945026f, toneCurveYAtIndex(curve, 32), 1e-6f)
assertEquals(0.479043320f, toneCurveYAtIndex(curve, 128), 1e-6f)
assertEquals(1f, curve[curve.lastIndex - 1], 0f)
assertEquals(1f, curve[curve.lastIndex], 0f)
}
@Test
fun compactAppleProRawStatsKeepShadowLift() {
val map = DngAppleProRawProfileGainTableGenerator.forCellStats(
width = 6048,
height = 8064,
baselineExposureEv = -0.491214842f,
packedCellStats = packedStatsForAppleProfile(
width = 6048,
height = 8064,
p10 = 0.05317f,
p50 = 0.07299f,
p90 = 0.10034f,
p98 = 0.11416f,
highlightFraction = 0f,
tailP95 = 0.39022f,
tailP98 = 0.52531f,
tailP99 = 0.58001f,
maxInput = 0.70506f
)
) ?: error("Expected Apple ProRAW PGTM")
assertTrue(map.isValid)
assertToneOutputMonotonic(map)
assertAppleInputWeights(map)
assertEquals(1f, map.mapInputWeights.sum(), 0.001f)
assertGainAtIndexIn(map, 0, 5.6f..7.2f)
assertGainAtIndexIn(map, 8, 5.5f..7.2f)
assertGainAtIndexIn(map, 16, 4.8f..7.0f)
assertGainAtIndexIn(map, 32, 3.7f..6.1f)
assertGainAtIndexIn(map, 64, 1.7f..3.9f)
assertGainAtIndexIn(map, 128, 1.0f..2.6f)
assertGainAtIndexIn(map, 256, 0.96f..1.04f)
}
@Test
fun brightAppleProRawStatsCompressLowAndWhitePoints() {
val map = DngAppleProRawProfileGainTableGenerator.forCellStats(
width = 6048,
height = 8064,
baselineExposureEv = -0.645403624f,
packedCellStats = packedStatsForAppleProfile(
width = 6048,
height = 8064,
p10 = 0.28629f,
p50 = 0.31120f,
p90 = 0.33687f,
p98 = 0.34596f,
highlightFraction = 0f,
tailP95 = 0.43744f,
tailP98 = 0.46330f,
tailP99 = 0.48841f,
maxInput = 0.60448f
)
) ?: error("Expected Apple ProRAW PGTM")
assertTrue(map.isValid)
assertToneOutputMonotonic(map)
assertAppleInputWeights(map)
assertTrue("weightSum=${map.mapInputWeights.sum()}", map.mapInputWeights.sum() in 0.070f..0.090f)
assertGainAtIndexIn(map, 0, 1.2f..1.9f)
assertGainAtIndexIn(map, 8, 1.1f..1.9f)
assertGainAtIndexIn(map, 16, 0.8f..1.6f)
assertGainAtIndexIn(map, 32, 0.35f..0.85f)
assertGainAtIndexIn(map, 64, 0.18f..0.45f)
assertGainAtIndexIn(map, 256, 0.070f..0.090f)
}
@Test
fun appleProRawFlatGradientStatsAvoidVisibleTileSteps() {
val map = DngAppleProRawProfileGainTableGenerator.forCellStats(
width = 1024,
height = 768,
baselineExposureEv = 0.2f,
packedCellStats = packedFlatGradientStats(
width = 1024,
height = 768
)
) ?: error("Expected Apple ProRAW PGTM")
assertTrue(map.isValid)
assertToneOutputMonotonic(map)
assertTrue(
"lowInputAdjacentDelta=${maxAdjacentGainDelta(map, 0.06f)}",
maxAdjacentGainDelta(map, 0.06f) < 0.18f
)
assertTrue(
"midInputAdjacentDelta=${maxAdjacentGainDelta(map, 0.18f)}",
maxAdjacentGainDelta(map, 0.18f) < 0.10f
)
}
@Test
fun appleProRawExposureNormalizerReducesBrightProfileBias() {
val map = DngAppleProRawProfileGainTableGenerator.forCellStats(
width = 6048,
height = 8064,
baselineExposureEv = -0.491214842f,
packedCellStats = packedStatsForAppleProfile(
width = 6048,
height = 8064,
p10 = 0.05317f,
p50 = 0.07299f,
p90 = 0.10034f,
p98 = 0.11416f,
highlightFraction = 0f,
tailP95 = 0.39022f,
tailP98 = 0.52531f,
tailP99 = 0.58001f,
maxInput = 0.70506f
)
) ?: error("Expected Apple ProRAW PGTM")
val curve = DngProfileToneCurve.appleProRawFittedToneCurveLut()
val sourceEv = DngAppleProRawExposureNormalizer.estimateAverageExposureEv(
profileGainTableMap = map,
baselineExposureEv = -0.491214842f,
toneCurveLut = curve
) ?: error("Expected source exposure EV")
val normalization = DngAppleProRawExposureNormalizer.resolveExposureOffset(
profileGainTableMap = map,
baselineExposureEv = -0.491214842f,
toneCurveLut = curve
)
val normalizedEv = DngAppleProRawExposureNormalizer.estimateAverageExposureEv(
profileGainTableMap = map,
baselineExposureEv = -0.491214842f,
toneCurveLut = curve,
profileExposureOffsetEv = normalization.additionalExposureOffsetEv
) ?: error("Expected normalized exposure EV")
assertTrue("sourceEv=$sourceEv", sourceEv > 1.2f)
assertTrue(
"offset=${normalization.additionalExposureOffsetEv}",
normalization.additionalExposureOffsetEv < -0.25f
)
assertTrue("normalizedEv=$normalizedEv", normalizedEv in 0.85f..1.05f)
assertEquals(normalizedEv, normalization.normalizedAverageEv, 0.02f)
}
@Test
fun appleProRawExposureNormalizerDoesNotBrightenDarkProfileBias() {
val map = DngAppleProRawProfileGainTableGenerator.forCellStats(
width = 6048,
height = 8064,
baselineExposureEv = -0.645403624f,
packedCellStats = packedStatsForAppleProfile(
width = 6048,
height = 8064,
p10 = 0.28629f,
p50 = 0.31120f,
p90 = 0.33687f,
p98 = 0.34596f,
highlightFraction = 0f,
tailP95 = 0.43744f,
tailP98 = 0.46330f,
tailP99 = 0.48841f,
maxInput = 0.60448f
)
) ?: error("Expected Apple ProRAW PGTM")
val curve = DngProfileToneCurve.appleProRawFittedToneCurveLut()
val sourceEv = DngAppleProRawExposureNormalizer.estimateAverageExposureEv(
profileGainTableMap = map,
baselineExposureEv = -0.645403624f,
toneCurveLut = curve
) ?: error("Expected source exposure EV")
val normalization = DngAppleProRawExposureNormalizer.resolveExposureOffset(
profileGainTableMap = map,
baselineExposureEv = -0.645403624f,
toneCurveLut = curve
)
assertTrue("sourceEv=$sourceEv", sourceEv < normalization.targetAverageEv)
assertEquals(0f, normalization.additionalExposureOffsetEv, 0f)
assertEquals(sourceEv, normalization.normalizedAverageEv, 0f)
}
private fun packedStatsForAppleProfile(
width: Int,
height: Int,
p10: Float,
p50: Float,
p90: Float,
p98: Float,
highlightFraction: Float,
tailP95: Float,
tailP98: Float,
tailP99: Float,
maxInput: Float,
): FloatArray {
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
val cellCount = grid[0] * grid[1]
return FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE).also { stats ->
for (cell in 0 until cellCount) {
val rank = (cell + 1).toFloat() / cellCount.toFloat()
val tail = when {
rank <= 0.95f -> lerp(p98, tailP95, rank / 0.95f)
rank <= 0.98f -> lerp(tailP95, tailP98, (rank - 0.95f) / 0.03f)
rank <= 0.99f -> lerp(tailP98, tailP99, (rank - 0.98f) / 0.01f)
else -> lerp(tailP99, maxInput, (rank - 0.99f) / 0.01f)
}
val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
stats[offset] = p10
stats[offset + 1] = p50
stats[offset + 2] = p90
stats[offset + 3] = p98.coerceIn(0f, 1f)
stats[offset + 4] = highlightFraction
stats[offset + 5] = 64f
stats[offset + 6] = tail
stats[offset + 7] = tail
}
}
}
private fun packedFlatGradientStats(width: Int, height: Int): FloatArray {
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
val gridWidth = grid[0]
val gridHeight = grid[1]
val cellCount = gridWidth * gridHeight
return FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE).also { stats ->
for (cell in 0 until cellCount) {
val x = cell % gridWidth
val t = if (gridWidth <= 1) 0f else x.toFloat() / (gridWidth - 1).toFloat()
val p50 = lerp(0.055f, 0.315f, t)
val p10 = (p50 - 0.018f).coerceAtLeast(0.005f)
val p90 = p50 + 0.018f
val p98 = p50 + 0.026f
val tail = lerp(3.2f, 4.6f, t)
val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
stats[offset] = p10
stats[offset + 1] = p50
stats[offset + 2] = p90
stats[offset + 3] = p98
stats[offset + 4] = 0.055f
stats[offset + 5] = 256f
stats[offset + 6] = tail
stats[offset + 7] = tail
}
}
}
private fun assertAppleInputWeights(map: DngProfileGainTableMap) {
val normalizedWeights = map.mapInputWeights.map { it / map.mapInputWeights.sum() }
assertEquals(0.1063f, normalizedWeights[0], 0.0001f)
assertEquals(0.3576f, normalizedWeights[1], 0.0001f)
assertEquals(0.0361f, normalizedWeights[2], 0.0001f)
assertEquals(0.0f, normalizedWeights[3], 0.0001f)
assertEquals(0.5f, normalizedWeights[4], 0.0001f)
}
private fun assertToneOutputMonotonic(map: DngProfileGainTableMap) {
val pointCount = map.mapPointsN
val cellCount = map.mapPointsH * map.mapPointsV
for (cell in 0 until cellCount) {
var previousOutput = 0f
val offset = cell * pointCount
for (index in 0 until pointCount) {
val input = tableInputForIndex(index, pointCount)
val output = input * map.gains[offset + index]
assertTrue(
"cell=$cell index=$index output=$output previous=$previousOutput",
output + 0.0001f >= previousOutput
)
previousOutput = maxOf(previousOutput, output)
}
}
}
private fun assertGainAtIndexIn(
map: DngProfileGainTableMap,
index: Int,
expectedRange: ClosedFloatingPointRange<Float>,
) {
val actual = medianGainAtIndex(map, index)
assertTrue("index=$index actual=$actual expected=$expectedRange", actual in expectedRange)
}
private fun medianGainAtIndex(map: DngProfileGainTableMap, index: Int): Float {
val pointIndex = index.coerceIn(0, map.mapPointsN - 1)
val cellCount = map.mapPointsH * map.mapPointsV
val values = FloatArray(cellCount) { cell -> map.gains[cell * map.mapPointsN + pointIndex] }
values.sort()
val medianIndex = ceil(values.size * 0.5f).toInt().coerceIn(1, values.size) - 1
return values[medianIndex]
}
private fun maxAdjacentGainDelta(map: DngProfileGainTableMap, tableInput: Float): Float {
var maxDelta = 0f
for (y in 0 until map.mapPointsV) {
for (x in 0 until map.mapPointsH) {
val cell = y * map.mapPointsH + x
val gain = gainAtTableInput(map, cell, tableInput)
if (x + 1 < map.mapPointsH) {
maxDelta = maxOf(maxDelta, kotlin.math.abs(gain - gainAtTableInput(map, cell + 1, tableInput)))
}
if (y + 1 < map.mapPointsV) {
maxDelta = maxOf(maxDelta, kotlin.math.abs(gain - gainAtTableInput(map, cell + map.mapPointsH, tableInput)))
}
}
}
return maxDelta
}
private fun gainAtTableInput(
map: DngProfileGainTableMap,
cell: Int,
tableInput: Float
): Float {
val tableIndex = (tableInput.coerceIn(0f, 1f) * map.mapPointsN)
.coerceIn(0f, (map.mapPointsN - 1).toFloat())
val index0 = kotlin.math.floor(tableIndex).toInt().coerceIn(0, map.mapPointsN - 1)
val index1 = (index0 + 1).coerceAtMost(map.mapPointsN - 1)
val t = tableIndex - index0.toFloat()
val offset = cell * map.mapPointsN
return lerp(map.gains[offset + index0], map.gains[offset + index1], t)
}
private fun toneCurveYAtIndex(points: FloatArray, pointIndex: Int): Float {
return points[pointIndex * 2 + 1]
}
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
if (pointCount <= 1) return 0f
return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat()
}
private fun lerp(a: Float, b: Float, t: Float): Float {
return a + (b - a) * t.coerceIn(0f, 1f)
}
}