feat: new photon tone curve (3)

This commit is contained in:
Hinnka committed 2026-07-15 23:54:48 +08:00
1 parent c3ed146ba7
commit 01f4d8f353
5 files changed
+781 -63

No files matched your search

@@ -8,10 +8,10 @@ import kotlin.math.sqrt
/**
* Spatial LTM stage fitted against Google PGTM cells from the Skyyking regression set.
*
* The brightest member of each local synthetic-exposure stack is biased from local luminance and
* highlight topology. Absolute percentile levels, ranges and tail descriptors are retained. A
* single normalized 3x3 convolution gives these exposure decisions the same spatial support as
* the profile map; the final gain curve is produced later by exposure fusion, not by this stage.
* Each local synthetic-exposure stack is biased from local luminance and highlight topology.
* Google-compatible plans adjust the brightest member; centered Photon plans translate both
* endpoints to preserve their EV span. A normalized 3x3 convolution gives these decisions the
* same spatial support as the profile map; exposure fusion still produces the final gain curve.
*/
internal object DngHdrLtmSpatialModel {
private const val LEVEL_EPS = 0.006f
@@ -23,7 +23,9 @@ internal object DngHdrLtmSpatialModel {
grid: HdrPgtmGrid,
global: HdrPgtmCellStats,
globalPlan: HdrLtmExposurePlan,
minimumExposureGain: Float = globalPlan.darkestExposureGain,
maxExposureGain: Float,
preserveExposureSpan: Boolean = false,
): Array<HdrLtmExposurePlan> {
val globalFeature = ToneFeature.from(global)
val features = Array(cells.size) { index ->
@@ -56,7 +58,9 @@ internal object DngHdrLtmSpatialModel {
localFeature = neighborhoods[index],
sampleWeight = cell.sampleWeight,
residualScale = residualScale,
minimumExposureGain = minimumExposureGain,
maxExposureGain = maxExposureGain,
preserveExposureSpan = preserveExposureSpan,
)
}
}
@@ -68,7 +72,9 @@ internal object DngHdrLtmSpatialModel {
localFeature: ToneFeature,
sampleWeight: Float,
residualScale: Float,
minimumExposureGain: Float,
maxExposureGain: Float,
preserveExposureSpan: Boolean,
): HdrLtmExposurePlan {
val residualEv =
0.0070524f * (localFeature.logP10 - referenceFeature.logP10) +
@@ -83,9 +89,26 @@ internal object DngHdrLtmSpatialModel {
val confidence = smoothStep(16f, 64f, sampleWeight)
val exposureOffsetEv = (residualEv * confidence * residualScale)
.coerceIn(-MAX_LOCAL_EXPOSURE_OFFSET_EV, MAX_LOCAL_EXPOSURE_OFFSET_EV)
return globalPlan.copy(
brightestExposureGain = (globalPlan.brightestExposureGain * 2.0f.pow(exposureOffsetEv))
.coerceIn(globalPlan.darkestExposureGain, maxExposureGain)
if (!preserveExposureSpan) {
return globalPlan.copy(
brightestExposureGain = (
globalPlan.brightestExposureGain * 2.0f.pow(exposureOffsetEv)
).coerceIn(globalPlan.darkestExposureGain, maxExposureGain)
)
}
val minimumEv = log2(minimumExposureGain)
val maximumEv = log2(maxExposureGain)
val darkestEv = log2(globalPlan.darkestExposureGain)
val brightestEv = log2(globalPlan.brightestExposureGain)
val halfSpanEv = (brightestEv - darkestEv).coerceAtLeast(0f) * 0.5f
val requestedCenterEv = (darkestEv + brightestEv) * 0.5f + exposureOffsetEv
val centerEv = requestedCenterEv.coerceIn(
minimumEv + halfSpanEv,
maximumEv - halfSpanEv,
)
return HdrLtmExposurePlan(
brightestExposureGain = 2.0f.pow(centerEv + halfSpanEv),
darkestExposureGain = 2.0f.pow(centerEv - halfSpanEv),
)
}
@@ -53,6 +53,8 @@ internal object DngHdrProfileGainTableGenerator {
private const val WEIGHT_LUT_STEPS_PER_EV = 256f
private const val WEIGHT_LUT_MAX_DISTANCE_EV = 12f
private const val CURVE_EPS = 1e-6f
private const val BRIGHTNESS_PLAN_SEARCH_STEPS = 256
private const val BRIGHTNESS_PLAN_REFINEMENT_ITERATIONS = 16
internal const val BASE_INPUT_WEIGHT_RED = 0.1495f
internal const val BASE_INPUT_WEIGHT_GREEN = 0.2935f
@@ -151,6 +153,8 @@ internal object DngHdrProfileGainTableGenerator {
tablePointCount: Int = DEFAULT_TABLE_POINTS,
diagnosticBand: DiagnosticBand? = null,
fusionParameters: HdrExposureFusionParameters = GOOGLE_FUSION_PARAMETERS,
brightnessTarget: HdrExposureFusionBrightnessTarget? = null,
resolutionDiagnostics: ((HdrExposureFusionResolutionDiagnostics) -> Unit)? = null,
): DngProfileGainTableMap? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < 0f) {
return null
@@ -181,12 +185,20 @@ internal object DngHdrProfileGainTableGenerator {
inputScale = inputScale,
fusionParameters = fusionParameters,
)
val resolvedFusion = resolveBrightnessTarget(
plan = globalPlan,
fusionParameters = fusionParameters,
brightnessTarget = brightnessTarget,
)
resolvedFusion.diagnostics?.let { resolutionDiagnostics?.invoke(it) }
val cellPlans = DngHdrLtmSpatialModel.buildExposurePlans(
cells = cells,
grid = grid,
global = spatialStats,
globalPlan = globalPlan,
globalPlan = resolvedFusion.plan,
minimumExposureGain = inputScale,
maxExposureGain = fusionParameters.maxExposureGain,
preserveExposureSpan = resolvedFusion.preserveExposureSpan,
)
return buildMap(
grid = grid,
@@ -194,7 +206,8 @@ internal object DngHdrProfileGainTableGenerator {
inputScale = inputScale,
cellPlans = cellPlans,
diagnosticBand = diagnosticBand?.sanitized(),
fusionParameters = fusionParameters,
fusionParameters = resolvedFusion.parameters,
protectedExposureGain = resolvedFusion.protectedExposureGain,
)
}
@@ -438,6 +451,149 @@ internal object DngHdrProfileGainTableGenerator {
)
}
/**
* Solves the center of the synthetic exposure stack while preserving the span planned by the
* current PGTM model. The well-exposed key, exposure spacing, and stack width therefore keep
* defining one stable curve shape; scene brightness only translates that stack in EV.
*/
private fun resolveBrightnessTarget(
plan: HdrLtmExposurePlan,
fusionParameters: HdrExposureFusionParameters,
brightnessTarget: HdrExposureFusionBrightnessTarget?,
): ResolvedExposureFusion {
val fallback = ResolvedExposureFusion(
plan = plan,
parameters = fusionParameters,
preserveExposureSpan = false,
protectedExposureGain = null,
diagnostics = null,
)
val target = brightnessTarget ?: return fallback
if (!target.sceneInput.isFinite() || target.sceneInput <= 0f ||
!target.targetOutput.isFinite() || target.targetOutput <= 0f
) {
return fallback
}
val desiredOutput = target.targetOutput.coerceIn(0f, 1f)
val darkestGain = plan.darkestExposureGain.coerceIn(
MIN_TABLE_GAIN,
fusionParameters.maxExposureGain,
)
val baseDarkestEv = log2(darkestGain)
val baseBrightestEv = log2(
plan.brightestExposureGain.coerceIn(darkestGain, fusionParameters.maxExposureGain)
)
val minimumExposureEv = baseDarkestEv
val maximumExposureEv = log2(fusionParameters.maxExposureGain)
val fullExposureSpanEv = (baseBrightestEv - baseDarkestEv).coerceIn(
0f,
maximumExposureEv - minimumExposureEv,
)
// Keep one exposure fixed at inputScale for highlight reconstruction. The other seven
// retain exactly the span occupied by the brightest seven members of the original
// equally-spaced eight-exposure stack.
val exposureIntervalEv = fullExposureSpanEv / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
val centeredExposureSpanEv = fullExposureSpanEv - exposureIntervalEv
val halfSpanEv = centeredExposureSpanEv * 0.5f
val minimumCenterEv = minimumExposureEv + halfSpanEv
val maximumCenterEv = maximumExposureEv - halfSpanEv
val referenceCenterEv = (
baseDarkestEv + exposureIntervalEv + halfSpanEv
).coerceIn(minimumCenterEv, maximumCenterEv)
val protectedExposureGain = darkestGain
fun fusionOutput(centerEv: Float): Float {
val resolvedCenterEv = centerEv.coerceIn(minimumCenterEv, maximumCenterEv)
val resolvedDarkestEv = resolvedCenterEv - halfSpanEv
val resolvedBrightestEv = resolvedCenterEv + halfSpanEv
val resolvedDarkestGain = 2.0f.pow(resolvedDarkestEv)
val resolvedBrightestGain = 2.0f.pow(resolvedBrightestEv)
val exposureGains = syntheticExposureGains(
resolvedBrightestGain,
resolvedDarkestGain,
protectedExposureGain = protectedExposureGain,
)
val exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
log2(exposureGains[exposure])
}
return fuseSyntheticExposures(
sceneInput = target.sceneInput,
exposureGains = exposureGains,
exposureGainEvs = exposureGainEvs,
fusionParameters = fusionParameters,
)
}
fun evaluate(centerEv: Float): ExposureCenterEvaluation {
val output = fusionOutput(centerEv)
return ExposureCenterEvaluation(
centerEv = centerEv.coerceIn(minimumCenterEv, maximumCenterEv),
brightnessErrorEv = abs(
log2(max(output, CURVE_EPS) / max(desiredOutput, CURVE_EPS))
),
)
}
var bestStep = 0
var bestEvaluation = evaluate(minimumCenterEv)
for (step in 0..BRIGHTNESS_PLAN_SEARCH_STEPS) {
val amount = step.toFloat() / BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat()
val candidateEv = lerp(minimumCenterEv, maximumCenterEv, amount)
val candidateEvaluation = evaluate(candidateEv)
if (candidateEvaluation.brightnessErrorEv < bestEvaluation.brightnessErrorEv) {
bestEvaluation = candidateEvaluation
bestStep = step
}
}
var lowerEv = lerp(
minimumCenterEv,
maximumCenterEv,
(bestStep - 1).coerceAtLeast(0).toFloat() / BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat(),
)
var upperEv = lerp(
minimumCenterEv,
maximumCenterEv,
(bestStep + 1).coerceAtMost(BRIGHTNESS_PLAN_SEARCH_STEPS).toFloat() /
BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat(),
)
repeat(BRIGHTNESS_PLAN_REFINEMENT_ITERATIONS) {
val firstEv = lerp(lowerEv, upperEv, 1f / 3f)
val secondEv = lerp(lowerEv, upperEv, 2f / 3f)
val firstEvaluation = evaluate(firstEv)
val secondEvaluation = evaluate(secondEv)
if (firstEvaluation.brightnessErrorEv < secondEvaluation.brightnessErrorEv) {
upperEv = secondEv
} else {
lowerEv = firstEv
}
}
val resolvedEvaluation = listOf(
evaluate(lowerEv),
evaluate((lowerEv + upperEv) * 0.5f),
evaluate(upperEv),
).reduce { best, candidate ->
if (candidate.brightnessErrorEv < best.brightnessErrorEv) candidate else best
}
val resolvedCenterEv = resolvedEvaluation.centerEv
return ResolvedExposureFusion(
plan = HdrLtmExposurePlan(
brightestExposureGain = 2.0f.pow(resolvedCenterEv + halfSpanEv),
darkestExposureGain = 2.0f.pow(resolvedCenterEv - halfSpanEv),
),
parameters = fusionParameters,
preserveExposureSpan = true,
protectedExposureGain = protectedExposureGain,
diagnostics = HdrExposureFusionResolutionDiagnostics(
referenceCenterEv = referenceCenterEv,
resolvedCenterEv = resolvedCenterEv,
centeredExposureSpanEv = centeredExposureSpanEv,
brightnessErrorEv = resolvedEvaluation.brightnessErrorEv,
protectedExposureGain = protectedExposureGain,
),
)
}
private fun buildMap(
grid: HdrPgtmGrid,
pointCount: Int,
@@ -445,27 +601,40 @@ internal object DngHdrProfileGainTableGenerator {
cellPlans: Array<HdrLtmExposurePlan>,
diagnosticBand: DiagnosticBand?,
fusionParameters: HdrExposureFusionParameters,
protectedExposureGain: Float?,
): DngProfileGainTableMap {
val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * pointCount)
// Local exposure plans vary smoothly. Quantizing only the brightest exposure to 1/128 EV
// limits the maximum planning error to 1/256 EV while allowing neighboring cells to share
// the complete 257-point fused curve.
val curveCache = HashMap<Int, FloatArray>()
// Local exposure plans vary smoothly. Quantizing both stack endpoints to 1/128 EV limits
// the maximum planning error to 1/256 EV while allowing neighboring cells to share the
// complete 257-point fused curve.
val curveCache = HashMap<Long, FloatArray>()
for (cell in cellPlans.indices) {
val plan = cellPlans[cell]
val planKey = (log2(plan.brightestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV)
val brightestKey = (log2(plan.brightestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV)
.roundToInt()
val darkestKey = (log2(plan.darkestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV)
.roundToInt()
val planKey = (brightestKey.toLong() shl 32) xor
(darkestKey.toLong() and 0xffffffffL)
val curve = curveCache.getOrPut(planKey) {
val quantizedBrightestGain = 2.0f.pow(
planKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV
).coerceIn(plan.darkestExposureGain, fusionParameters.maxExposureGain)
brightestKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV
).coerceIn(inputScale, fusionParameters.maxExposureGain)
val quantizedDarkestGain = 2.0f.pow(
darkestKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV
).coerceIn(inputScale, quantizedBrightestGain)
FloatArray(pointCount).also { cachedCurve ->
writeExposureFusionCurve(
output = cachedCurve,
outputOffset = 0,
pointCount = pointCount,
plan = plan.copy(brightestExposureGain = quantizedBrightestGain),
inputScale = inputScale,
plan = HdrLtmExposurePlan(
brightestExposureGain = quantizedBrightestGain,
darkestExposureGain = quantizedDarkestGain,
),
fusionParameters = fusionParameters,
protectedExposureGain = protectedExposureGain,
)
}
}
@@ -499,27 +668,30 @@ internal object DngHdrProfileGainTableGenerator {
}
/**
* Renders eight exposure levels equally spaced in EV. For each table input, weights are
* computed from the distance of every rendered exposure to the well-exposed key, normalized,
* and used to fuse the rendered values. The PGTM gain is then recovered from fusedOutput /
* sceneInput. Monotonic enforcement only removes numerical or exposure-switching reversals.
* Renders eight exposure levels. The standard path spaces all eight equally in EV; an
* adaptive centered stack spaces seven equally and reserves one inputScale exposure for
* highlight reconstruction. Weights are computed from each rendered exposure's distance to
* the well-exposed key. Monotonic enforcement only removes numerical or switching reversals.
*/
private fun writeExposureFusionCurve(
output: FloatArray,
outputOffset: Int,
pointCount: Int,
inputScale: Float,
plan: HdrLtmExposurePlan,
fusionParameters: HdrExposureFusionParameters,
protectedExposureGain: Float?,
) {
val brightestGain = plan.brightestExposureGain.coerceIn(
MIN_TABLE_GAIN,
fusionParameters.maxExposureGain,
)
val darkestGain = plan.darkestExposureGain.coerceIn(MIN_TABLE_GAIN, brightestGain)
val exposureGains = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
2.0f.pow(lerp(log2(brightestGain), log2(darkestGain), amount))
}
val exposureGains = syntheticExposureGains(
brightestGain,
darkestGain,
protectedExposureGain,
)
val exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
log2(exposureGains[exposure])
}
@@ -530,7 +702,7 @@ internal object DngHdrProfileGainTableGenerator {
output[outputOffset + index] = brightestGain
continue
}
val sceneInput = tableInput / darkestGain
val sceneInput = tableInput / inputScale
val fusedOutput = fuseSyntheticExposures(
sceneInput = sceneInput,
exposureGains = exposureGains,
@@ -544,6 +716,28 @@ internal object DngHdrProfileGainTableGenerator {
}
}
private fun syntheticExposureGains(
brightestGain: Float,
darkestGain: Float,
protectedExposureGain: Float? = null,
): FloatArray {
val protectedGain = protectedExposureGain
?.takeIf { it.isFinite() && it > 0f }
?.coerceAtMost(darkestGain)
?: return FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
2.0f.pow(lerp(log2(brightestGain), log2(darkestGain), amount))
}
return FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
if (exposure == SYNTHETIC_EXPOSURE_COUNT - 1) {
protectedGain
} else {
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 2).toFloat()
2.0f.pow(lerp(log2(brightestGain), log2(darkestGain), amount))
}
}
}
private fun fuseSyntheticExposures(
sceneInput: Float,
exposureGains: FloatArray,
@@ -693,8 +887,34 @@ internal object DngHdrProfileGainTableGenerator {
return values.firstOrNull { it.isFinite() && it > 0f } ?: 1f
}
private data class ResolvedExposureFusion(
val plan: HdrLtmExposurePlan,
val parameters: HdrExposureFusionParameters,
val preserveExposureSpan: Boolean,
val protectedExposureGain: Float?,
val diagnostics: HdrExposureFusionResolutionDiagnostics?,
)
private data class ExposureCenterEvaluation(
val centerEv: Float,
val brightnessErrorEv: Float,
)
}
internal data class HdrExposureFusionBrightnessTarget(
val sceneInput: Float,
val targetOutput: Float,
)
internal data class HdrExposureFusionResolutionDiagnostics(
val referenceCenterEv: Float,
val resolvedCenterEv: Float,
val centeredExposureSpanEv: Float,
val brightnessErrorEv: Float,
val protectedExposureGain: Float,
)
internal data class HdrExposureFusionParameters(
val autoExposureTarget: Float,
val wellExposedKey: Float,
@@ -3,10 +3,9 @@ package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
/**
* Photon uses Google's PGTM implementation directly. The only Photon-specific values are
* exposure-fusion planning parameters selected to keep its median brightness close to the
* previous Photon rendering. Input scale estimation, spatial planning, synthetic-exposure
* fusion, highlight shoulder, and the table endpoint all remain the Google implementation.
* Photon uses Google's current PGTM implementation and translates a fixed-span synthetic
* exposure stack from the historical Photon scene-brightness target. The fusion key remains a
* curve-shape parameter; one exposure stays pinned to inputScale to protect highlight layers.
*/
internal object DngPhotonProfileGainTableGenerator {
private const val TAG = "DngPhotonProfileGainTableGenerator"
@@ -32,6 +31,8 @@ internal object DngPhotonProfileGainTableGenerator {
emitDiagnostics: Boolean = true,
statsSource: String = "global-samples",
): DngProfileGainTableMap? {
val brightnessTarget = PhotonPgtmBrightnessModel.resolve(globalStats)
var fusionResolution: HdrExposureFusionResolutionDiagnostics? = null
val map = DngHdrProfileGainTableGenerator.forCellStats(
width = width,
height = height,
@@ -40,6 +41,8 @@ internal object DngPhotonProfileGainTableGenerator {
tablePointCount = tablePointCount,
diagnosticBand = diagnosticBand,
fusionParameters = PHOTON_FUSION_PARAMETERS,
brightnessTarget = brightnessTarget?.fusionTarget,
resolutionDiagnostics = { fusionResolution = it },
) ?: return null
if (emitDiagnostics) {
@@ -48,7 +51,7 @@ internal object DngPhotonProfileGainTableGenerator {
val p50Input = globalStats.p50.takeIf { it.isFinite() && it > 0f } ?: 0f
PLog.d(
TAG,
"Built Photon with Google PGTM: grid=${map.mapPointsH}x${map.mapPointsV}x" +
"Built adaptive Photon with Google PGTM: grid=${map.mapPointsH}x${map.mapPointsV}x" +
"${map.mapPointsN} statsSource=$statsSource " +
"globalSampleCount=${globalStats.sampleCount} baselineEv=$baselineExposureEv " +
"autoExposureTarget=${PHOTON_FUSION_PARAMETERS.autoExposureTarget} " +
@@ -56,7 +59,21 @@ internal object DngPhotonProfileGainTableGenerator {
"maxExposureGain=${PHOTON_FUSION_PARAMETERS.maxExposureGain} " +
"compactHdrOffsetEv=${PHOTON_FUSION_PARAMETERS.compactHdrExposureOffsetEv} " +
"inputScale=$inputScale sceneWhite=$sceneWhite " +
"p50Input=$p50Input"
"p50Input=$p50Input " +
"brightnessAnchor=${brightnessTarget?.sceneAnchor} " +
"anchorSource=${brightnessTarget?.anchorSource} " +
"displayTarget=${brightnessTarget?.displayTarget} " +
"exposureLiftEv=${brightnessTarget?.exposureLiftEv} " +
"tailRangeEv=${brightnessTarget?.tailRangeEv} " +
"exposureRangeEv=${brightnessTarget?.exposureRangeEv} " +
"highlightGapEv=${brightnessTarget?.highlightGapEv} " +
"sparseStrength=${brightnessTarget?.sparseHighlightStrength} " +
"dynamicRangeEv=${brightnessTarget?.dynamicRangeEv} " +
"referenceCenterEv=${fusionResolution?.referenceCenterEv} " +
"resolvedCenterEv=${fusionResolution?.resolvedCenterEv} " +
"centeredSpanEv=${fusionResolution?.centeredExposureSpanEv} " +
"brightnessErrorEv=${fusionResolution?.brightnessErrorEv} " +
"protectedExposureGain=${fusionResolution?.protectedExposureGain}"
)
}
return map
@@ -0,0 +1,183 @@
package com.hinnka.mycamera.raw
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.pow
/**
* Restores the scene-brightness target used by Photon before 3e320e229 without restoring its
* old gain-curve generator. The returned pre-profile target is consumed by Google's current
* eight-exposure fusion implementation.
*/
internal object PhotonPgtmBrightnessModel {
private const val MIN_SCENE_INPUT = 1e-6f
private const val STANDARD_DYNAMIC_RANGE_EV = 8f
private const val WIDE_DYNAMIC_RANGE_EV = 8.5f
private const val HDR_DYNAMIC_RANGE_EV = 9f
private const val EXTENDED_HDR_DYNAMIC_RANGE_EV = 9.5f
private const val WIDE_HIGHLIGHT_RANGE_THRESHOLD_EV = 2.5f
private const val HDR_HIGHLIGHT_RANGE_THRESHOLD_EV = 3.5f
private const val EXTENDED_HDR_HIGHLIGHT_RANGE_THRESHOLD_EV = 4f
private const val MAX_DISPLAY_MIDDLE_GRAY = 0.26f
private const val MIN_DISPLAY_EXPOSURE_LIFT_EV = 0.27f
private const val MAX_DISPLAY_EXPOSURE_LIFT_EV = 2.24f
private const val DISPLAY_EXPOSURE_TRANSITION_START_EV = 1.7f
private const val DISPLAY_EXPOSURE_TRANSITION_END_EV = 3.45f
private const val SPARSE_HIGHLIGHT_GAP_START_EV = 0.45f
private const val SPARSE_HIGHLIGHT_GAP_FULL_EV = 0.90f
fun resolve(globalStats: DngPgtmGlobalStats): PhotonPgtmBrightnessTarget? {
val logAverage = globalStats.logAverage.takeIf { it.isFinite() && it > 0f }
val p50 = globalStats.p50.takeIf { it.isFinite() && it > 0f }
val sceneAnchor = logAverage ?: p50 ?: return null
val anchorSource = if (logAverage != null) {
PhotonPgtmBrightnessAnchorSource.LOG_AVERAGE
} else {
PhotonPgtmBrightnessAnchorSource.P50_FALLBACK
}
val ranges = highlightRanges(
p90 = globalStats.p90,
p98 = globalStats.p98,
p995 = globalStats.p995,
p999 = globalStats.p999,
sceneMiddle = sceneAnchor,
)
val dynamicRangeEv = dynamicRangeTier(ranges.tailRangeEv)
val displayBlackPoint = 1f / 2.0f.pow(dynamicRangeEv)
val exposureLiftEv = displayExposureLiftEv(ranges.exposureRangeEv)
val displayTarget = (sceneAnchor * 2.0f.pow(exposureLiftEv)).coerceIn(
displayBlackPoint * 4f,
MAX_DISPLAY_MIDDLE_GRAY,
)
return PhotonPgtmBrightnessTarget(
fusionTarget = HdrExposureFusionBrightnessTarget(
sceneInput = sceneAnchor,
targetOutput = photonProfileInputForDisplay(displayTarget),
),
anchorSource = anchorSource,
sceneAnchor = sceneAnchor,
displayTarget = displayTarget,
exposureLiftEv = exposureLiftEv,
tailRangeEv = ranges.tailRangeEv,
exposureRangeEv = ranges.exposureRangeEv,
highlightGapEv = ranges.highlightGapEv,
sparseHighlightStrength = ranges.sparseStrength,
dynamicRangeEv = dynamicRangeEv,
)
}
internal fun highlightRanges(
p90: Float,
p98: Float,
p995: Float,
p999: Float,
sceneMiddle: Float,
): PhotonPgtmHighlightRanges {
val safeMiddle = max(sceneMiddle, MIN_SCENE_INPUT)
val safeP90 = max(p90.takeIf { it.isFinite() } ?: safeMiddle, safeMiddle)
val safeP98 = max(p98.takeIf { it.isFinite() } ?: safeP90, safeP90)
val safeP995 = max(p995.takeIf { it.isFinite() } ?: safeP98, safeP98)
val safeP999 = max(p999.takeIf { it.isFinite() } ?: safeP995, safeP995)
val highlightGapEv = log2(safeP98 / safeP90).coerceAtLeast(0f)
val sparseStrength = smoothStep(
SPARSE_HIGHLIGHT_GAP_START_EV,
SPARSE_HIGHLIGHT_GAP_FULL_EV,
highlightGapEv,
)
val exposureReference = 2.0f.pow(
lerp(log2(safeP999), log2(safeP90), sparseStrength)
)
return PhotonPgtmHighlightRanges(
tailRangeEv = log2(safeP999 / safeMiddle).coerceAtLeast(0f),
exposureRangeEv = log2(exposureReference / safeMiddle).coerceAtLeast(0f),
exposureReference = exposureReference,
highlightGapEv = highlightGapEv,
sparseStrength = sparseStrength,
)
}
internal fun displayExposureLiftEv(highlightRangeEv: Float): Float {
return lerp(
MIN_DISPLAY_EXPOSURE_LIFT_EV,
MAX_DISPLAY_EXPOSURE_LIFT_EV,
smoothStep(
DISPLAY_EXPOSURE_TRANSITION_START_EV,
DISPLAY_EXPOSURE_TRANSITION_END_EV,
highlightRangeEv,
),
)
}
private fun dynamicRangeTier(highlightRangeEv: Float): Float {
return when {
highlightRangeEv >= EXTENDED_HDR_HIGHLIGHT_RANGE_THRESHOLD_EV ->
EXTENDED_HDR_DYNAMIC_RANGE_EV
highlightRangeEv >= HDR_HIGHLIGHT_RANGE_THRESHOLD_EV -> HDR_DYNAMIC_RANGE_EV
highlightRangeEv >= WIDE_HIGHLIGHT_RANGE_THRESHOLD_EV -> WIDE_DYNAMIC_RANGE_EV
else -> STANDARD_DYNAMIC_RANGE_EV
}
}
private fun photonProfileInputForDisplay(displayValue: Float): Float {
val target = displayValue.coerceIn(0f, 1f)
val points = DngProfileToneCurve.photonPgtmToneCurvePoints()
if (points.size < 4) return target
var index = 0
while (index + 3 < points.size) {
val x0 = points[index]
val y0 = points[index + 1]
val x1 = points[index + 2]
val y1 = points[index + 3]
if (target <= y1) {
val amount = if (y1 > y0) (target - y0) / (y1 - y0) else 0f
return lerp(x0, x1, amount)
}
index += 2
}
return points[points.size - 2].coerceIn(0f, 1f)
}
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
if (edge1 <= edge0) return if (value >= edge1) 1f else 0f
val amount = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
return amount * amount * (3f - 2f * amount)
}
private fun lerp(start: Float, end: Float, amount: Float): Float {
return start + (end - start) * amount
}
private fun log2(value: Float): Float {
return (ln(max(value, MIN_SCENE_INPUT).toDouble()) / ln(2.0)).toFloat()
}
}
internal data class PhotonPgtmBrightnessTarget(
val fusionTarget: HdrExposureFusionBrightnessTarget,
val anchorSource: PhotonPgtmBrightnessAnchorSource,
val sceneAnchor: Float,
val displayTarget: Float,
val exposureLiftEv: Float,
val tailRangeEv: Float,
val exposureRangeEv: Float,
val highlightGapEv: Float,
val sparseHighlightStrength: Float,
val dynamicRangeEv: Float,
)
internal enum class PhotonPgtmBrightnessAnchorSource {
LOG_AVERAGE,
P50_FALLBACK,
}
internal data class PhotonPgtmHighlightRanges(
val tailRangeEv: Float,
val exposureRangeEv: Float,
val exposureReference: Float,
val highlightGapEv: Float,
val sparseStrength: Float,
)
@@ -13,7 +13,7 @@ import kotlin.math.pow
class DngPhotonProfileGainTableGeneratorTest {
@Test
fun photonIsGoogleExposureFusionWithPhotonParameters() {
fun photonKeepsGoogleDomainWhileAdaptingItsSceneBrightness() {
val fixture = uniformFixture(
p10 = 0.015f,
p50 = 0.08f,
@@ -31,12 +31,16 @@ class DngPhotonProfileGainTableGeneratorTest {
fusionParameters = DngPhotonProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS,
) ?: error("Expected direct Google PGTM")
assertEquals(directGoogle.mapPointsH, photon.mapPointsH)
assertEquals(directGoogle.mapPointsV, photon.mapPointsV)
assertEquals(directGoogle.mapPointsN, photon.mapPointsN)
assertEquals(directGoogle.gamma, photon.gamma, 0f)
assertArrayEquals(directGoogle.mapInputWeights, photon.mapInputWeights, 0f)
assertArrayEquals(directGoogle.gains, photon.gains, 0f)
assertTrue(
"Brightness target must change the fusion curve",
!directGoogle.gains.contentEquals(photon.gains),
)
val target = PhotonPgtmBrightnessModel.resolve(fixture.globalStats)
?: error("Expected Photon brightness target")
val actual = finalPhotonOutputForScene(photon, target.sceneAnchor)
assertEquals(target.displayTarget, actual, 0.004f)
}
@Test
@@ -73,8 +77,8 @@ class DngPhotonProfileGainTableGeneratorTest {
}
@Test
fun tunedGoogleFusionKeepsP50NearLegacyPhotonBrightness() {
val cases = legacyP50Cases()
fun centeredFusionHitsPre3e320SceneBrightnessTargets() {
val cases = historicalBrightnessCases()
val results = cases.map { case ->
val fixture = uniformFixture(
baselineExposureEv = case.baselineExposureEv,
@@ -85,25 +89,219 @@ class DngPhotonProfileGainTableGeneratorTest {
p995 = case.p995,
p999 = case.p999,
highlightFraction = case.highlightFraction,
maxInput = case.maxInput,
linearMean = case.linearMean,
logAverage = case.logAverage,
)
val map = generatePhotonMap(fixture)
val actual = finalPhotonOutputForScene(map, case.p50)
val errorEv = abs(log2(actual / case.legacyDisplayP50))
LegacyP50Result(
val target = PhotonPgtmBrightnessModel.resolve(fixture.globalStats)
?: error("Expected target for ${case.name}")
val actual = finalPhotonOutputForScene(map, target.sceneAnchor)
val errorEv = abs(log2(actual / target.displayTarget))
HistoricalBrightnessResult(
case = case,
actualDisplayP50 = actual,
targetDisplayAnchor = target.displayTarget,
actualDisplayAnchor = actual,
errorEv = errorEv,
)
}
assertTrue(
results.joinToString(separator = "\n") { result ->
"${result.case.name}: expected=${result.case.legacyDisplayP50} " +
"actual=${result.actualDisplayP50} errorEv=${result.errorEv}"
"${result.case.name}: expected=${result.targetDisplayAnchor} " +
"actual=${result.actualDisplayAnchor} errorEv=${result.errorEv}"
},
results.all { it.errorEv <= 0.32f },
results.all { it.errorEv <= 0.04f },
)
}
@Test
fun pre3e320WideFieldUsesHistoricalLogAverageLift() {
val stats = testGlobalStats(
p10 = 0.0046890248f,
p50 = 0.035560552f,
p90 = 0.35547075f,
p98 = 0.4203099f,
p995 = 0.44679728f,
p999 = 0.46304873f,
maxInput = 0.5280757f,
linearMean = 0.114991106f,
logAverage = 0.039605092f,
highlightFraction = 0f,
)
val target = PhotonPgtmBrightnessModel.resolve(stats) ?: error("Expected target")
assertEquals(
PhotonPgtmBrightnessAnchorSource.LOG_AVERAGE,
target.anchorSource,
)
assertEquals(2.24f, target.exposureLiftEv, 1e-5f)
assertEquals(0.039605092f * 2.0f.pow(2.24f), target.displayTarget, 1e-5f)
assertEquals(9f, target.dynamicRangeEv, 0f)
}
@Test
fun sparseHighlightsUseTheMainHighlightPopulationForExposure() {
val ranges = PhotonPgtmBrightnessModel.highlightRanges(
p90 = 0.20524885f,
p98 = 0.45892385f,
p995 = 0.5724387f,
p999 = 0.6364626f,
sceneMiddle = 0.09018845f,
)
val tailLift = PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.tailRangeEv)
val exposureLift = PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.exposureRangeEv)
assertTrue(ranges.tailRangeEv in 2.81f..2.83f)
assertTrue(ranges.exposureRangeEv in 1.18f..1.20f)
assertEquals(0.20524885f, ranges.exposureReference, 1e-6f)
assertEquals(1f, ranges.sparseStrength, 0f)
assertTrue(exposureLift - tailLift in -1.39f..-1.37f)
}
@Test
fun separatedHighlightScenesDoNotRaiseTheWholeFrameExposure() {
val saturatedTarget = PhotonPgtmBrightnessModel.resolve(
testGlobalStats(
p10 = 0.01f,
p50 = 0.064226665f,
p90 = 2.1271088f,
p98 = 3.989237f,
p995 = 5f,
p999 = 6.0202312f,
logAverage = 0.07215811f,
)
) ?: error("Expected saturated sparse-highlight target")
val separatedTarget = PhotonPgtmBrightnessModel.resolve(
testGlobalStats(
p10 = 0.01f,
p50 = 0.0600047f,
p90 = 0.21020813f,
p98 = 0.88294554f,
p995 = 0.94f,
p999 = 0.9819474f,
logAverage = 0.06115667f,
)
) ?: error("Expected separated sparse-highlight target")
assertEquals(0.26f, saturatedTarget.displayTarget, 0f)
assertTrue(separatedTarget.exposureRangeEv in 1.77f..1.79f)
assertTrue(separatedTarget.displayTarget < 0.08f)
}
@Test
fun pre3e320DngPairRetainsItsMeasuredBrightnessRelationship() {
fun displayEv(
logAverage: Float,
p90: Float,
p98: Float,
p995: Float,
p999: Float,
): Float {
val ranges = PhotonPgtmBrightnessModel.highlightRanges(
p90 = p90,
p98 = p98,
p995 = p995,
p999 = p999,
sceneMiddle = logAverage,
)
return log2(logAverage) +
PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.exposureRangeEv)
}
val dng2840DisplayEv = displayEv(
logAverage = 0.0932018935f,
p90 = 0.263932749f,
p98 = 0.3304134763f,
p995 = 0.3685588609f,
p999 = 0.3981607637f,
)
val dng2842DisplayEv = displayEv(
logAverage = 0.07615876645f,
p90 = 0.2486532208f,
p98 = 0.2975876967f,
p995 = 0.3287509693f,
p999 = 0.3566421426f,
)
assertTrue(abs(dng2842DisplayEv - dng2840DisplayEv) <= 0.12f)
}
@Test
fun missingLogAverageFallsBackToP50WithoutChangingTheModel() {
val target = PhotonPgtmBrightnessModel.resolve(
testGlobalStats(
p10 = 0.035187688f,
p50 = 0.08524494f,
p90 = 0.14404307f,
p98 = 0.16417652f,
p995 = 0.17360601f,
p999 = 0.18164334f,
maxInput = 0.20776238f,
logAverage = Float.NaN,
)
) ?: error("Expected P50 fallback")
assertEquals(PhotonPgtmBrightnessAnchorSource.P50_FALLBACK, target.anchorSource)
assertEquals(0.08524494f, target.sceneAnchor, 0f)
}
@Test
fun pre3e320ExtendedHdrShoulderKeepsSeparationNearWhite() {
val map = generatePhotonMap(fixtureFor(dynamicRangeTiers().last()))
val sceneWhite = 1f / map.mapInputWeights.sum()
val output85 = finalPhotonOutputForScene(map, sceneWhite * 0.85f)
val output95 = finalPhotonOutputForScene(map, sceneWhite * 0.95f)
val output100 = finalPhotonOutputForScene(map, sceneWhite)
val lowerHighlightSpan = output95 - output85
val endpointSpan = output100 - output95
assertTrue(
"output85=$output85 output95=$output95 output100=$output100",
endpointSpan > 0.008f,
)
assertTrue(
"lowerHighlightSpan=$lowerHighlightSpan endpointSpan=$endpointSpan",
endpointSpan > lowerHighlightSpan * 0.30f,
)
}
@Test
fun adaptiveBrightnessKeepsAnIntrinsicToeAndShoulder() {
historicalBrightnessCases().forEach { case ->
val fixture = uniformFixture(
baselineExposureEv = case.baselineExposureEv,
p10 = case.p10,
p50 = case.p50,
p90 = case.p90,
p98 = case.p98,
p995 = case.p995,
p999 = case.p999,
highlightFraction = case.highlightFraction,
maxInput = case.maxInput,
linearMean = case.linearMean,
logAverage = case.logAverage,
)
val map = generatePhotonMap(fixture)
val sceneWhite = 1f / map.mapInputWeights.sum()
val shadowSpanEv = log2(
finalPhotonOutputForScene(map, sceneWhite / 16f) /
finalPhotonOutputForScene(map, sceneWhite / 64f)
)
val output85 = finalPhotonOutputForScene(map, sceneWhite * 0.85f)
val output95 = finalPhotonOutputForScene(map, sceneWhite * 0.95f)
val output100 = finalPhotonOutputForScene(map, sceneWhite)
assertTrue(
"${case.name}: shadowSpanEv=$shadowSpanEv",
shadowSpanEv >= 0.8f,
)
assertTrue(
"${case.name}: output85=$output85 output95=$output95 output100=$output100",
output85 < output95 && output95 < output100,
)
assertCurvesAreFiniteAndMonotonic(map, sceneWhite)
}
}
@Test
fun invalidInputStillUsesGoogleValidation() {
assertNull(
@@ -129,17 +327,73 @@ class DngPhotonProfileGainTableGeneratorTest {
) ?: error("Expected Photon PGTM")
}
private fun legacyP50Cases(): List<LegacyP50Case> = listOf(
LegacyP50Case("field-wide", 0f, 0.0046890248f, 0.035560552f, 0.35547075f, 0.4203099f, 0.44679728f, 0.46304873f, 0f, 0.16989206f),
LegacyP50Case("device-baseline3", 3.000001f, 0.0013647672f, 0.01069319f, 0.08506412f, 0.28084078f, 0.508f, 0.7334936f, 0.005f, 0.04490788f),
LegacyP50Case("dng2840", 0f, 0.020f, 0.085f, 0.263932749f, 0.3304134763f, 0.3685588609f, 0.3981607637f, 0f, 0.12226473f),
LegacyP50Case("dng2842", 0f, 0.018f, 0.070f, 0.2486532208f, 0.2975876967f, 0.3287509693f, 0.3566421426f, 0f, 0.11336776f),
LegacyP50Case("range8", 0f, 0.10f, 0.15f, 0.40f, 0.60f, 0.69f, 0.75f, 0f, 0.2347192f),
LegacyP50Case("range8.5", 0f, 0.020f, 0.10f, 0.50f, 0.75f, 0.966f, 1.05f, 0f, 0.28000832f),
LegacyP50Case("range9", 0f, 0.015f, 0.08f, 0.55f, 0.80f, 1.058f, 1.15f, 0f, 0.30003452f),
LegacyP50Case("range9.5", 0f, 0.012f, 0.07f, 0.55f, 0.85f, 1.104f, 1.20f, 0f, 0.32003647f),
// Fixtures recovered from 3e320e229^, before Photon was replaced by fixed fusion parameters.
private fun historicalBrightnessCases(): List<HistoricalBrightnessCase> = listOf(
HistoricalBrightnessCase(
"14:22 baseline-0 wide",
0f,
0.0046890248f,
0.035560552f,
0.35547075f,
0.4203099f,
0.44679728f,
0.46304873f,
0.5280757f,
0.114991106f,
0.039605092f,
0f,
),
HistoricalBrightnessCase(
"18:53 baseline-3 sparse-tail",
3f,
0.022204947f,
0.13993193f,
0.21021318f,
0.24911182f,
0.27169982f,
0.5752382f,
1.249979f,
0.1295324f,
0.09985464f,
6.739298E-5f,
),
HistoricalBrightnessCase(
"18:54 baseline-3 low-range",
3f,
0.045957692f,
0.08537395f,
0.13890508f,
0.18092623f,
0.2126976f,
0.2313348f,
0.27256522f,
0.08850919f,
0.07818398f,
0f,
),
)
private fun dynamicRangeTiers(): List<DynamicRangeTier> = listOf(
DynamicRangeTier(0.10f, 0.15f, 0.40f, 0.60f, 0.75f, 8f),
DynamicRangeTier(0.020f, 0.10f, 0.50f, 0.75f, 1.05f, 8.5f),
DynamicRangeTier(0.015f, 0.08f, 0.55f, 0.80f, 1.15f, 9f),
DynamicRangeTier(0.012f, 0.07f, 0.55f, 0.85f, 1.20f, 9.5f),
)
private fun fixtureFor(tier: DynamicRangeTier): UniformFixture {
return uniformFixture(
p10 = tier.p10,
p50 = tier.p50,
p90 = tier.p90,
p98 = tier.p98,
p995 = tier.p999 * 0.92f,
p999 = tier.p999,
highlightFraction = 0f,
maxInput = tier.p999,
logAverage = tier.p50,
)
}
private fun uniformFixture(
baselineExposureEv: Float = 0f,
p10: Float,
@@ -149,6 +403,9 @@ class DngPhotonProfileGainTableGeneratorTest {
p995: Float,
p999: Float,
highlightFraction: Float = 0.02f,
maxInput: Float = p999,
linearMean: Float = p50,
logAverage: Float = p50,
): UniformFixture {
val width = 640
val height = 480
@@ -180,7 +437,10 @@ class DngPhotonProfileGainTableGeneratorTest {
p98 = p98,
p995 = p995,
p999 = p999,
maxInput = maxInput,
highlightFraction = highlightFraction,
linearMean = linearMean,
logAverage = logAverage,
),
)
}
@@ -192,7 +452,10 @@ class DngPhotonProfileGainTableGeneratorTest {
p98: Float = p90,
p995: Float = p98,
p999: Float = p995,
maxInput: Float = p999,
highlightFraction: Float = 0f,
linearMean: Float = p50,
logAverage: Float = p50,
): DngPgtmGlobalStats {
return DngPgtmGlobalStats(
p10 = p10,
@@ -201,10 +464,10 @@ class DngPhotonProfileGainTableGeneratorTest {
p98 = p98,
p995 = p995,
p999 = p999,
maxInput = p999,
maxInput = maxInput,
highlightFraction = highlightFraction,
linearMean = p50,
logAverage = p50,
linearMean = linearMean,
logAverage = logAverage,
shadowEdge = p10,
shadowFoot = p10,
sampleCount = 256,
@@ -293,7 +556,7 @@ class DngPhotonProfileGainTableGeneratorTest {
val globalStats: DngPgtmGlobalStats,
)
private data class LegacyP50Case(
private data class HistoricalBrightnessCase(
val name: String,
val baselineExposureEv: Float,
val p10: Float,
@@ -302,14 +565,26 @@ class DngPhotonProfileGainTableGeneratorTest {
val p98: Float,
val p995: Float,
val p999: Float,
val maxInput: Float,
val linearMean: Float,
val logAverage: Float,
val highlightFraction: Float,
val legacyDisplayP50: Float,
)
private data class LegacyP50Result(
val case: LegacyP50Case,
val actualDisplayP50: Float,
private data class HistoricalBrightnessResult(
val case: HistoricalBrightnessCase,
val targetDisplayAnchor: Float,
val actualDisplayAnchor: Float,
val errorEv: Float,
)
private data class DynamicRangeTier(
val p10: Float,
val p50: Float,
val p90: Float,
val p98: Float,
val p999: Float,
val dynamicRangeEv: Float,
)
}