diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt index e30ef293..71062689 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt @@ -16,7 +16,6 @@ import kotlin.math.sqrt internal object DngHdrLtmSpatialModel { private const val LEVEL_EPS = 0.006f private const val TAIL_EPS = 0.04f - private const val MAX_LTM_GAIN = 6.18f private const val MAX_LOCAL_EXPOSURE_OFFSET_EV = 1.25f fun buildExposurePlans( @@ -24,6 +23,7 @@ internal object DngHdrLtmSpatialModel { grid: HdrPgtmGrid, global: HdrPgtmCellStats, globalPlan: HdrLtmExposurePlan, + maxExposureGain: Float, ): Array { val globalFeature = ToneFeature.from(global) val features = Array(cells.size) { index -> @@ -55,7 +55,8 @@ internal object DngHdrLtmSpatialModel { referenceFeature = referenceFeature, localFeature = neighborhoods[index], sampleWeight = cell.sampleWeight, - residualScale = residualScale + residualScale = residualScale, + maxExposureGain = maxExposureGain, ) } } @@ -67,6 +68,7 @@ internal object DngHdrLtmSpatialModel { localFeature: ToneFeature, sampleWeight: Float, residualScale: Float, + maxExposureGain: Float, ): HdrLtmExposurePlan { val residualEv = 0.0070524f * (localFeature.logP10 - referenceFeature.logP10) + @@ -83,7 +85,7 @@ internal object DngHdrLtmSpatialModel { .coerceIn(-MAX_LOCAL_EXPOSURE_OFFSET_EV, MAX_LOCAL_EXPOSURE_OFFSET_EV) return globalPlan.copy( brightestExposureGain = (globalPlan.brightestExposureGain * 2.0f.pow(exposureOffsetEv)) - .coerceIn(globalPlan.darkestExposureGain, MAX_LTM_GAIN) + .coerceIn(globalPlan.darkestExposureGain, maxExposureGain) ) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt index e09d2f42..dfb07b04 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt @@ -42,6 +42,7 @@ internal object DngHdrProfileGainTableGenerator { private const val MIN_TABLE_GAIN = 0.05f private const val AUTO_EXPOSURE_TARGET = 0.278f private const val WELL_EXPOSED_KEY = 0.525f + private const val RISKY_HIGHLIGHT_WELL_EXPOSED_KEY = 0.720f private const val WELL_EXPOSED_SIGMA_EV = 0.750f // Official Pixel maps broaden the exposure fusion only in the shoulder: // the last trustworthy highlights stay close to white while the toe and @@ -67,6 +68,14 @@ internal object DngHdrProfileGainTableGenerator { BASE_INPUT_WEIGHT_MIN, BASE_INPUT_WEIGHT_MAX ) + internal val GOOGLE_FUSION_PARAMETERS = HdrExposureFusionParameters( + autoExposureTarget = AUTO_EXPOSURE_TARGET, + wellExposedKey = WELL_EXPOSED_KEY, + riskyHighlightWellExposedKey = RISKY_HIGHLIGHT_WELL_EXPOSED_KEY, + maxExposureGain = MAX_LTM_GAIN, + highlightFusionStart = HIGHLIGHT_FUSION_START, + highlightFusionEnd = HIGHLIGHT_FUSION_END, + ) private val WELL_EXPOSED_WEIGHT_LUT = FloatArray( (WEIGHT_LUT_MAX_DISTANCE_EV * WEIGHT_LUT_STEPS_PER_EV).toInt() + 1 ) { index -> @@ -137,8 +146,10 @@ internal object DngHdrProfileGainTableGenerator { height: Int, baselineExposureEv: Float, packedCellStats: FloatArray, + denseGlobalStats: DngPgtmGlobalStats? = null, tablePointCount: Int = DEFAULT_TABLE_POINTS, diagnosticBand: DiagnosticBand? = null, + fusionParameters: HdrExposureFusionParameters = GOOGLE_FUSION_PARAMETERS, ): DngProfileGainTableMap? { if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < 0f) { return null @@ -162,24 +173,76 @@ internal object DngHdrProfileGainTableGenerator { null } } - val globalStats = weightedGlobalStats(cells) - val inputScale = estimateInputScale(globalStats, baselineExposureEv) + val spatialStats = weightedGlobalStats(cells) + val inputScale = estimateInputScale(spatialStats, baselineExposureEv) + val highlightRiskBand = denseGlobalStats?.let { stats -> + highlightRiskBandFor(stats, inputScale) + } + ?: HdrHighlightRiskBand( + start = fusionParameters.highlightFusionStart, + end = fusionParameters.highlightFusionEnd, + strength = 0f, + ) val globalPlan = buildGlobalExposurePlan( - stats = globalStats, - inputScale = inputScale + stats = spatialStats, + inputScale = inputScale, + fusionParameters = fusionParameters, ) val cellPlans = DngHdrLtmSpatialModel.buildExposurePlans( cells = cells, grid = grid, - global = globalStats, - globalPlan = globalPlan + global = spatialStats, + globalPlan = globalPlan, + maxExposureGain = fusionParameters.maxExposureGain, ) return buildMap( grid = grid, pointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS), inputScale = inputScale, cellPlans = cellPlans, - diagnosticBand = diagnosticBand?.sanitized() + diagnosticBand = diagnosticBand?.sanitized(), + fusionParameters = fusionParameters, + highlightRiskBand = highlightRiskBand, + ) + } + + internal fun highlightRiskBandFor( + stats: DngPgtmGlobalStats, + inputScale: Float, + ): HdrHighlightRiskBand = with(stats) { + val safeScale = sanitizeInputScale(inputScale) + val safeP90 = p90.takeIf { it.isFinite() && it >= 0f } ?: 0f + val safeP98 = max(safeP90, p98.takeIf { it.isFinite() && it >= 0f } ?: safeP90) + val safeP995 = max(safeP98, p995.takeIf { it.isFinite() && it > 0f } ?: safeP98) + val safeP999 = max(safeP995, p999.takeIf { it.isFinite() && it > 0f } ?: safeP995) + val detectedStart = (safeP90 * safeScale).coerceIn(0f, 1f - 2f * CURVE_EPS) + val detectedEnd = safeP98 * safeScale + val tailGapEv = log2( + (safeP999 + 0.04f) / (safeP995 + 0.04f) + ) + // Preserve the pre-exposure-fusion tail-usability rule: a large p999-to-p995 gap is a + // sparse outlier tail, not trustworthy highlight detail. Dense highlights are retained + // because their population provides enough color support to treat the tail as real. + val outlierRisk = smoothStep(0.48f, 0.72f, tailGapEv) + val safeHighlightFraction = highlightFraction.takeIf { it.isFinite() } + ?.coerceIn(0f, 1f) + ?: 0f + val sparseTail = 1f - smoothStep(0.10f, 0.18f, safeHighlightFraction) + val riskStrength = (outlierRisk * sparseTail).coerceIn(0f, 1f) + val start = lerp( + GOOGLE_FUSION_PARAMETERS.highlightFusionStart, + detectedStart, + riskStrength, + ) + val end = lerp( + GOOGLE_FUSION_PARAMETERS.highlightFusionEnd, + detectedEnd, + riskStrength, + ).coerceIn(start + CURVE_EPS, 1f) + HdrHighlightRiskBand( + start = start, + end = end, + strength = riskStrength, ) } @@ -360,6 +423,7 @@ internal object DngHdrProfileGainTableGenerator { private fun buildGlobalExposurePlan( stats: HdrPgtmCellStats, inputScale: Float, + fusionParameters: HdrExposureFusionParameters, ): HdrLtmExposurePlan { val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f) val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95)) @@ -367,7 +431,9 @@ internal object DngHdrProfileGainTableGenerator { val maxInput = max(tailP99, positiveOr(stats.maxInput, tailP99)) // This value plans the brightest member of the synthetic exposure stack. It is not a // fitted output gain: the final curve is produced by exposure weighting and fusion below. - var brightestExposureEv = log2(AUTO_EXPOSURE_TARGET / max(stats.p50, CURVE_EPS)) + var brightestExposureEv = log2( + fusionParameters.autoExposureTarget / max(stats.p50, CURVE_EPS) + ) val sparseSeparatedTail = (1f - smoothStep(0.21f, 0.24f, stats.p98)) * (1f - smoothStep(1.15f, 1.45f, tailP95)) * @@ -405,14 +471,17 @@ internal object DngHdrProfileGainTableGenerator { 0.85f * lowKeyLongTail - 0.37f * saturatedScene - 1.43f * isolatedSdrTail + - 0.20f * broadHighlightBody - - 0.40f * compactHdrBody - + 0.20f * broadHighlightBody + + fusionParameters.compactHdrExposureOffsetEv * compactHdrBody - 0.30f * quietLongTail - 0.03f * denseMidHigh - brightestExposureEv = brightestExposureEv.coerceIn(log2(inputScale), log2(MAX_LTM_GAIN)) + brightestExposureEv = brightestExposureEv.coerceIn( + log2(inputScale), + log2(fusionParameters.maxExposureGain), + ) return HdrLtmExposurePlan( brightestExposureGain = 2.0f.pow(brightestExposureEv) - .coerceIn(inputScale, MAX_LTM_GAIN), + .coerceIn(inputScale, fusionParameters.maxExposureGain), darkestExposureGain = inputScale ) } @@ -423,6 +492,8 @@ internal object DngHdrProfileGainTableGenerator { inputScale: Float, cellPlans: Array, diagnosticBand: DiagnosticBand?, + fusionParameters: HdrExposureFusionParameters, + highlightRiskBand: HdrHighlightRiskBand, ): DngProfileGainTableMap { val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * pointCount) // Local exposure plans vary smoothly. Quantizing only the brightest exposure to 1/128 EV @@ -436,13 +507,15 @@ internal object DngHdrProfileGainTableGenerator { val curve = curveCache.getOrPut(planKey) { val quantizedBrightestGain = 2.0f.pow( planKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV - ).coerceIn(plan.darkestExposureGain, MAX_LTM_GAIN) + ).coerceIn(plan.darkestExposureGain, fusionParameters.maxExposureGain) FloatArray(pointCount).also { cachedCurve -> writeExposureFusionCurve( output = cachedCurve, outputOffset = 0, pointCount = pointCount, - plan = plan.copy(brightestExposureGain = quantizedBrightestGain) + plan = plan.copy(brightestExposureGain = quantizedBrightestGain), + fusionParameters = fusionParameters, + highlightRiskBand = highlightRiskBand, ) } } @@ -455,7 +528,8 @@ internal object DngHdrProfileGainTableGenerator { output = gains, outputOffset = cell * pointCount, pointCount = pointCount, - band = band + band = band, + maxGainValue = fusionParameters.maxExposureGain, ) } } @@ -485,8 +559,13 @@ internal object DngHdrProfileGainTableGenerator { outputOffset: Int, pointCount: Int, plan: HdrLtmExposurePlan, + fusionParameters: HdrExposureFusionParameters, + highlightRiskBand: HdrHighlightRiskBand, ) { - val brightestGain = plan.brightestExposureGain.coerceIn(MIN_TABLE_GAIN, MAX_LTM_GAIN) + 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() @@ -506,11 +585,13 @@ internal object DngHdrProfileGainTableGenerator { val fusedOutput = fuseSyntheticExposures( sceneInput = sceneInput, exposureGains = exposureGains, - exposureGainEvs = exposureGainEvs + exposureGainEvs = exposureGainEvs, + fusionParameters = fusionParameters, + highlightRiskBand = highlightRiskBand, ) val monotonicOutput = max(previousOutput, fusedOutput) output[outputOffset + index] = (monotonicOutput / sceneInput) - .coerceIn(MIN_TABLE_GAIN, MAX_LTM_GAIN) + .coerceIn(MIN_TABLE_GAIN, fusionParameters.maxExposureGain) previousOutput = monotonicOutput } } @@ -519,13 +600,20 @@ internal object DngHdrProfileGainTableGenerator { sceneInput: Float, exposureGains: FloatArray, exposureGainEvs: FloatArray, + fusionParameters: HdrExposureFusionParameters, + highlightRiskBand: HdrHighlightRiskBand, ): Float { - val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / WELL_EXPOSED_KEY) + val effectiveWellExposedKey = lerp( + fusionParameters.wellExposedKey, + fusionParameters.riskyHighlightWellExposedKey, + highlightRiskBand.strength, + ) + val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / effectiveWellExposedKey) val darkestExposureGain = exposureGains.lastOrNull() ?: return 0f val tableInput = sceneInput * darkestExposureGain val highlightFusionStrength = smoothStep( - HIGHLIGHT_FUSION_START, - HIGHLIGHT_FUSION_END, + highlightRiskBand.start, + highlightRiskBand.end, tableInput ) var weightSum = 0f @@ -664,3 +752,30 @@ internal object DngHdrProfileGainTableGenerator { } } + +internal data class HdrExposureFusionParameters( + val autoExposureTarget: Float, + val wellExposedKey: Float, + val riskyHighlightWellExposedKey: Float = wellExposedKey, + val maxExposureGain: Float, + val compactHdrExposureOffsetEv: Float = -0.40f, + val highlightFusionStart: Float = 0.45f, + val highlightFusionEnd: Float = 0.65f, +) { + init { + require(autoExposureTarget.isFinite() && autoExposureTarget > 0f) + require(wellExposedKey.isFinite() && wellExposedKey > 0f) + require(riskyHighlightWellExposedKey.isFinite() && riskyHighlightWellExposedKey > 0f) + require(maxExposureGain.isFinite() && maxExposureGain >= 1f) + require(compactHdrExposureOffsetEv.isFinite()) + require(highlightFusionStart.isFinite() && highlightFusionStart in 0f..1f) + require(highlightFusionEnd.isFinite() && highlightFusionEnd in 0f..1f) + require(highlightFusionEnd > highlightFusionStart) + } +} + +internal data class HdrHighlightRiskBand( + val start: Float, + val end: Float, + val strength: Float, +) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt index c0c22cb1..eae64166 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt @@ -1,60 +1,24 @@ 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 +/** + * 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. + */ internal object DngPhotonProfileGainTableGenerator { private const val TAG = "DngPhotonProfileGainTableGenerator" - private const val DEFAULT_TABLE_POINTS = 257 - private const val MIN_TABLE_POINTS = 257 - private const val MAX_TABLE_POINTS = 257 - private const val MIN_BASELINE_EV = 0f - private const val MAX_BASELINE_EV = 8f - private const val MIN_CURVE_INPUT = 1e-6f - private const val BASE_WHITE_POINT = 1f - private const val MAX_WHITE_POINT_ADJUSTMENT = 1.30f - private const val MAX_GAIN_VALUE = 32f - private const val MAP_INPUT_WEIGHT_COUNT = 5 - // A square-root table domain resolves more than 9.5 EV below white with - // 257 points; a linear table would place its first sample only 8 EV down. - private const val TABLE_INPUT_GAMMA = 0.5f - private const val MAX_SCENE_MIDDLE_GRAY = 0.18f - internal const val SHADOW_FOOT_HEADROOM_EV = 1.2f - private const val MIN_SOURCE_COMPRESSION_EV = 0.75f - private const val MAX_SOURCE_DYNAMIC_RANGE_EV = 12.5f - 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 MIN_DYNAMIC_RANGE_EV = STANDARD_DYNAMIC_RANGE_EV - private const val MAX_DYNAMIC_RANGE_EV = EXTENDED_HDR_DYNAMIC_RANGE_EV - private const val STANDARD_DISPLAY_MIDDLE_GRAY = 0.26f - private const val WIDE_DISPLAY_MIDDLE_GRAY = 0.28f - private const val HDR_DISPLAY_MIDDLE_GRAY = 0.30f - private const val EXTENDED_HDR_DISPLAY_MIDDLE_GRAY = 0.32f - 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 - private const val MIN_HIGHLIGHT_ENDPOINT_SLOPE_RATIO = 0.65f - private const val MAX_HIGHLIGHT_ENDPOINT_SLOPE_RATIO = 0.88f - private const val MAX_LOCAL_MICRO_CONTRAST_EV = 0.22f - private val BASE_INPUT_WEIGHTS = floatArrayOf( - DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHT_RED, - DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHT_GREEN, - DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHT_BLUE, - DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHT_MIN, - DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHT_MAX + internal val PHOTON_FUSION_PARAMETERS = HdrExposureFusionParameters( + autoExposureTarget = 0.230f, + wellExposedKey = 0.720f, + maxExposureGain = 9.50f, + compactHdrExposureOffsetEv = 0.920f, + highlightFusionStart = 0.200f, + highlightFusionEnd = 0.650f, ) fun forCellStats( @@ -68,757 +32,34 @@ internal object DngPhotonProfileGainTableGenerator { emitDiagnostics: Boolean = true, statsSource: String = "global-samples", ): DngProfileGainTableMap? { - if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < MIN_BASELINE_EV) { - return null - } - val gridSize = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val gridWidth = gridSize.getOrElse(0) { 0 } - val gridHeight = gridSize.getOrElse(1) { 0 } - if (gridWidth <= 0 || gridHeight <= 0) return null - val cellCount = gridWidth * gridHeight - if (packedCellStats.size < cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) { - PLog.w( - TAG, - "Photon PGTM stats too small: ${packedCellStats.size}, " + - "expected=${cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE}" - ) - return null - } + val map = DngHdrProfileGainTableGenerator.forCellStats( + width = width, + height = height, + baselineExposureEv = baselineExposureEv, + packedCellStats = packedCellStats, + denseGlobalStats = globalStats, + tablePointCount = tablePointCount, + diagnosticBand = diagnosticBand, + fusionParameters = PHOTON_FUSION_PARAMETERS, + ) ?: return null - val cells = Array(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 = globalStats.toPhotonCellStats() ?: return null - val safeBaselineEv = baselineExposureEv.coerceIn(0f, MAX_BASELINE_EV) - val safePointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS) - val toneAnchors = buildPhotonToneAnchors( - global = global, - exposureAnchor = globalStats.logAverage, - shadowFoot = globalStats.shadowFoot, - baselineExposureEv = safeBaselineEv - ) - val inputScale = sanitizeInputScale(1f / toneAnchors.whitePoint) - val curveSamples = buildPhotonCurveSamples( - pointCount = safePointCount, - inputScale = inputScale, - toneAnchors = toneAnchors - ) - val gains = FloatArray(cellCount * safePointCount) - for (cellIndex in 0 until cellCount) { - writePhotonCurve( - output = gains, - outputOffset = cellIndex * safePointCount, - curveSamples = curveSamples, - toneAnchors = toneAnchors, - global = global, - local = cells[cellIndex] ?: global - ) - } - - val map = DngProfileGainTableMap( - mapPointsV = gridHeight, - mapPointsH = gridWidth, - mapSpacingV = if (gridHeight > 1) 1.0 / (gridHeight - 1).toDouble() else 1.0, - mapSpacingH = if (gridWidth > 1) 1.0 / (gridWidth - 1).toDouble() else 1.0, - mapOriginV = 0.0, - mapOriginH = 0.0, - mapPointsN = safePointCount, - mapInputWeights = photonPgtmInputWeights(inputScale), - gamma = TABLE_INPUT_GAMMA, - gains = gains, - sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 - ) if (emitDiagnostics) { - val p50Input = max(global.p50, MIN_CURVE_INPUT) - val requestedP50Output = photonToneOutput( - sceneLinear = p50Input, - toneAnchors = toneAnchors, - global = global, - local = global - ) - val requestedP50Gain = requestedP50Output / p50Input - val appliedP50Gain = requestedP50Gain.coerceIn(0.05f, MAX_GAIN_VALUE) - val appliedP50Output = p50Input * appliedP50Gain - val finalDisplayP50 = photonProfileOutputForInput(appliedP50Output) - val anchorMiddleGain = toneAnchors.middleGrayOutput / toneAnchors.middleGrayPoint - val exposureLiftEv = displayExposureLiftEv(toneAnchors.exposureHighlightRangeEv) - val domainOverflowEv = log2( - max(global.p999, toneAnchors.whitePoint) / toneAnchors.whitePoint - ).coerceAtLeast(0f) - val observedShadowRangeEv = log2( - max(globalStats.logAverage, globalStats.shadowFoot) / - max(globalStats.shadowFoot, MIN_CURVE_INPUT) - ) + val inputScale = map.mapInputWeights.sum() + val sceneWhite = 1f / inputScale + val p50Input = globalStats.p50.takeIf { it.isFinite() && it > 0f } ?: 0f PLog.d( TAG, - "Built Photon PGTM: grid=${gridWidth}x${gridHeight}x$safePointCount " + - "statsSource=$statsSource globalSampleCount=${globalStats.sampleCount} " + - "baselineEv=$safeBaselineEv " + - "tailRangeEv=${toneAnchors.tailHighlightRangeEv} " + - "exposureRangeEv=${toneAnchors.exposureHighlightRangeEv} " + - "curveRangeEv=${toneAnchors.curveDynamicRangeEv} " + - "targetRangeEv=${toneAnchors.targetDynamicRangeEv} " + - "shadowRangeEv=$observedShadowRangeEv " + - "relativeEv=${toneAnchors.blackRelativeExposure}.." + - "${toneAnchors.whiteRelativeExposure} " + - "source=${toneAnchors.blackPoint},${toneAnchors.middleGrayPoint}," + - "${toneAnchors.whitePoint} pgtm=${toneAnchors.blackOutput}," + - "${toneAnchors.middleGrayOutput},1.0 display=${toneAnchors.displayBlackPoint}," + - "${toneAnchors.displayMiddleGray},1.0 " + - "tierDisplayMiddle=${toneAnchors.tierDisplayMiddleGray} " + - "rawRight=${toneAnchors.rawWhitePoint} inputScale=$inputScale " + - "domainOverflowEv=$domainOverflowEv " + - "p10=${global.p10} p50=${global.p50} p90=${global.p90} " + - "p98=${global.p98} p995=${global.p995} p999=${global.p999} " + - "maxInput=${global.maxInput} " + - "linearMean=${globalStats.linearMean} logAverage=${globalStats.logAverage} " + - "shadowEdge=${globalStats.shadowEdge} shadowFoot=${globalStats.shadowFoot} " + - "exposureHighlight=${toneAnchors.exposureHighlightReference} " + - "highlightGapEv=${toneAnchors.highlightGapEv} " + - "sparseHighlightStrength=${toneAnchors.sparseHighlightStrength} " + - "highlightFraction=${global.highlightFraction}" - ) - PLog.d( - TAG, - "Photon PGTM exposure: p50Input=${global.p50} " + - "logAverageInput=${globalStats.logAverage} " + - "sourceMiddle=${toneAnchors.middleGrayPoint} " + - "anchorMiddleGain=$anchorMiddleGain requestedP50Gain=$requestedP50Gain " + - "appliedP50Gain=$appliedP50Gain pgtmP50=$appliedP50Output " + - "displayP50=$finalDisplayP50 targetDisplayMiddle=${toneAnchors.displayMiddleGray} " + - "tierDisplayMiddle=${toneAnchors.tierDisplayMiddleGray} " + - "tailRangeEv=${toneAnchors.tailHighlightRangeEv} " + - "exposureRangeEv=${toneAnchors.exposureHighlightRangeEv} " + - "exposureLiftEv=$exposureLiftEv " + - "whiteAdjustment=${toneAnchors.whitePoint / BASE_WHITE_POINT} " + - "maxGain=$MAX_GAIN_VALUE" + "Built 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} " + + "wellExposedKey=${PHOTON_FUSION_PARAMETERS.wellExposedKey} " + + "maxExposureGain=${PHOTON_FUSION_PARAMETERS.maxExposureGain} " + + "compactHdrOffsetEv=${PHOTON_FUSION_PARAMETERS.compactHdrExposureOffsetEv} " + + "inputScale=$inputScale sceneWhite=$sceneWhite " + + "p50Input=$p50Input" ) } - return DngHdrProfileGainTableGenerator.withDiagnosticBand(map, diagnosticBand) + return map } - - private fun packedStatsAt(stats: FloatArray, offset: Int, sampleWeight: Float): PhotonPgtmCellStats { - val p10 = safePositive(stats[offset], 0f) - val p50 = max(p10, safePositive(stats[offset + 1], p10)) - val p90 = max(p50, safePositive(stats[offset + 2], p50)) - val p98 = max(p90, safePositive(stats[offset + 3], p90)) - val p995 = max(p98, safePositive(stats[offset + 6], p98)) - val p999 = max(p995, safePositive(stats[offset + 7], p995)) - return PhotonPgtmCellStats( - p10 = p10, - p50 = p50, - p90 = p90, - p98 = p98, - highlightFraction = safe01(stats[offset + 4]), - p995 = p995, - p999 = p999, - maxInput = p999, - sampleWeight = sampleWeight - ) - } - - private fun DngPgtmGlobalStats.toPhotonCellStats(): PhotonPgtmCellStats? { - if (sampleCount <= 0) return null - val safeP10 = safePositive(p10, 0f) - val safeP50 = max(safeP10, safePositive(p50, safeP10)) - val safeP90 = max(safeP50, safePositive(p90, safeP50)) - val safeP98 = max(safeP90, safePositive(p98, safeP90)) - val safeP995 = max(safeP98, safePositive(p995, safeP98)) - val safeP999 = max(safeP995, safePositive(p999, safeP995)) - return PhotonPgtmCellStats( - p10 = safeP10, - p50 = safeP50, - p90 = safeP90, - p98 = safeP98, - highlightFraction = safe01(highlightFraction), - p995 = safeP995, - p999 = safeP999, - maxInput = max(safeP999, safePositive(maxInput, safeP999)), - sampleWeight = sampleCount.toFloat() - ) - } - - private fun buildPhotonToneAnchors( - global: PhotonPgtmCellStats, - exposureAnchor: Float, - shadowFoot: Float, - baselineExposureEv: Float, - ): PhotonToneAnchors { - val highlightRanges = photonHighlightRanges( - p90 = global.p90, - p98 = global.p98, - p995 = global.p995, - p999 = global.p999, - sceneMiddle = exposureAnchor - ) - val targetDynamicRangeEv = photonDynamicRangeTier(highlightRanges.tailRangeEv) - val displayBlackPoint = 1f / 2.0f.pow(targetDynamicRangeEv) - val tierDisplayMiddleGray = displayMiddleGrayForTier(targetDynamicRangeEv) - val displayMiddleGray = displayMiddleGrayForHighlightRange( - exposureAnchor = exposureAnchor, - highlightRangeEv = highlightRanges.exposureRangeEv, - displayBlackPoint = displayBlackPoint, - tierDisplayMiddleGray = tierDisplayMiddleGray - ) - val blackOutput = photonProfileInputForDisplay(displayBlackPoint) - val middleGrayOutput = photonProfileInputForDisplay(displayMiddleGray) - val whitePointAdjustment = photonWhitePointAdjustment(global, targetDynamicRangeEv) - val baselineGain = 2.0f.pow(baselineExposureEv.coerceIn(MIN_BASELINE_EV, MAX_BASELINE_EV)) - - // ProfileGainTableMap lookup is evaluated after BaselineExposure even - // when the gain itself is applied before it. Its right edge belongs to - // that post-baseline profile domain and must not be expanded by the - // baseline gain a second time. Doing so would map sensor saturation to - // an output below white and make clipped channel ratios visible. Keep a - // small, statistics-driven profile overrange, while values beyond it - // reuse the terminal gain and naturally remain above display white. - val blackRangeWhiteReference = BASE_WHITE_POINT * whitePointAdjustment - val whitePoint = blackRangeWhiteReference - val rawWhitePoint = whitePoint / baselineGain - - // The EV-histogram foot identifies the perceptual shadow onset. Keep a - // short toe reserve below it; unlike p10, this point is based on image - // structure and never participates in exposure lift. Black placement is - // normalized to the raw-white reference, not to the expanded Baseline- - // Exposure lookup domain, so extending highlights cannot move exposure. - val slopeBlackPoint = max(shadowFoot, MIN_CURVE_INPUT) / - 2.0f.pow(SHADOW_FOOT_HEADROOM_EV) - val compressionBlackPoint = blackRangeWhiteReference / - 2.0f.pow(targetDynamicRangeEv + MIN_SOURCE_COMPRESSION_EV) - val gainLimitedBlackPoint = blackOutput / MAX_GAIN_VALUE - val minimumBlackPoint = max( - blackRangeWhiteReference / 2.0f.pow(MAX_SOURCE_DYNAMIC_RANGE_EV), - gainLimitedBlackPoint - ) - val blackPoint = max(slopeBlackPoint, compressionBlackPoint) - .coerceIn(minimumBlackPoint, blackRangeWhiteReference * 0.25f) - - // Exposure normalization is global: map the perceptual log-average - // luminance (never a value above canonical 18% gray) through the - // highlight-range exposure curve, within the selected tier's ceiling. - val minimumMiddleGrayPoint = max( - blackPoint * 4f, - middleGrayOutput / MAX_GAIN_VALUE - ) - val maximumMiddleGrayPoint = min(MAX_SCENE_MIDDLE_GRAY, whitePoint * 0.5f) - val middleGrayPoint = exposureAnchor.coerceIn( - min(minimumMiddleGrayPoint, maximumMiddleGrayPoint), - maximumMiddleGrayPoint - ) - val whiteRelativeExposure = log2(whitePoint / middleGrayPoint) - val blackRelativeExposure = log2(blackPoint / middleGrayPoint) - val curveDynamicRangeEv = whiteRelativeExposure - blackRelativeExposure - return PhotonToneAnchors( - tailHighlightRangeEv = highlightRanges.tailRangeEv, - exposureHighlightRangeEv = highlightRanges.exposureRangeEv, - exposureHighlightReference = highlightRanges.exposureReference, - highlightGapEv = highlightRanges.highlightGapEv, - sparseHighlightStrength = highlightRanges.sparseStrength, - targetDynamicRangeEv = targetDynamicRangeEv, - curveDynamicRangeEv = curveDynamicRangeEv, - blackRelativeExposure = blackRelativeExposure, - whiteRelativeExposure = whiteRelativeExposure, - blackPoint = blackPoint, - blackOutput = blackOutput, - middleGrayPoint = middleGrayPoint, - middleGrayOutput = middleGrayOutput, - displayBlackPoint = displayBlackPoint, - displayMiddleGray = displayMiddleGray, - tierDisplayMiddleGray = tierDisplayMiddleGray, - whitePoint = whitePoint, - rawWhitePoint = rawWhitePoint - ) - } - - private fun displayMiddleGrayForTier(dynamicRangeEv: Float): Float { - return when (dynamicRangeEv) { - STANDARD_DYNAMIC_RANGE_EV -> STANDARD_DISPLAY_MIDDLE_GRAY - WIDE_DYNAMIC_RANGE_EV -> WIDE_DISPLAY_MIDDLE_GRAY - HDR_DYNAMIC_RANGE_EV -> HDR_DISPLAY_MIDDLE_GRAY - else -> EXTENDED_HDR_DISPLAY_MIDDLE_GRAY - } - } - - private fun displayMiddleGrayForHighlightRange( - exposureAnchor: Float, - highlightRangeEv: Float, - displayBlackPoint: Float, - tierDisplayMiddleGray: Float, - ): Float { - val exposureLiftEv = displayExposureLiftEv(highlightRangeEv) - return (exposureAnchor * 2.0f.pow(exposureLiftEv)).coerceIn( - displayBlackPoint * 4f, - tierDisplayMiddleGray - ) - } - - internal fun displayExposureLiftEv(highlightRangeEv: Float): Float { - val rangeStrength = smoothStep( - DISPLAY_EXPOSURE_TRANSITION_START_EV, - DISPLAY_EXPOSURE_TRANSITION_END_EV, - highlightRangeEv - ) - return lerp( - MIN_DISPLAY_EXPOSURE_LIFT_EV, - MAX_DISPLAY_EXPOSURE_LIFT_EV, - rangeStrength - ) - } - - internal fun photonHighlightRanges( - p90: Float, - p98: Float, - p995: Float, - p999: Float, - sceneMiddle: Float, - ): PhotonHighlightRanges { - val safeMiddle = max(sceneMiddle, MIN_CURVE_INPUT) - val safeP90 = max(p90, safeMiddle) - val safeP98 = max(p98, safeP90) - val safeP995 = max(p995, safeP98) - val safeP999 = max(p999, safeP995) - val highlightGapEv = log2(safeP98 / safeP90).coerceAtLeast(0f) - val sparseStrength = smoothStep( - SPARSE_HIGHLIGHT_GAP_START_EV, - SPARSE_HIGHLIGHT_GAP_FULL_EV, - highlightGapEv - ) - - // p999 remains the compression endpoint. When the upper 2% is - // separated from the main highlight population by a large EV gap, - // drive whole-frame exposure from the log-center across that gap - // instead of from percentiles that are both inside the sparse bright - // population. This preserves the tail without letting a window or - // specular region brighten the rest of the image. - val denseHighlightReference = 2.0f.pow( - 0.5f * (log2(safeP90) + log2(safeP98)) - ) - val exposureReference = 2.0f.pow( - lerp(log2(safeP999), log2(denseHighlightReference), sparseStrength) - ) - return PhotonHighlightRanges( - tailRangeEv = log2(safeP999 / safeMiddle).coerceAtLeast(0f), - exposureRangeEv = log2(exposureReference / safeMiddle).coerceAtLeast(0f), - exposureReference = exposureReference, - highlightGapEv = highlightGapEv, - sparseStrength = sparseStrength - ) - } - - private fun photonDynamicRangeTier(highlightRangeEv: Float): Float { - val tier = 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 - } - return tier.coerceIn(MIN_DYNAMIC_RANGE_EV, MAX_DYNAMIC_RANGE_EV) - } - - private fun photonWhitePointAdjustment( - global: PhotonPgtmCellStats, - dynamicRangeEv: Float, - ): Float { - val p995 = max(global.p995, global.p98) - val p999 = max(global.p999, p995) - val representativeTail = lerp(p995, p999, 0.65f) - val sparseTailPressure = smoothStep(0.94f, 1.32f, representativeTail) - val denseHighlightPressure = smoothStep(0.07f, 0.24f, global.highlightFraction) * - smoothStep(0.84f, 1.12f, p995) - val rangeTierStrength = (dynamicRangeEv - MIN_DYNAMIC_RANGE_EV) / - (MAX_DYNAMIC_RANGE_EV - MIN_DYNAMIC_RANGE_EV) - val pressure = max(sparseTailPressure, denseHighlightPressure) * - lerp(0.82f, 1f, rangeTierStrength) - return lerp(BASE_WHITE_POINT, MAX_WHITE_POINT_ADJUSTMENT, pressure) - .coerceIn(BASE_WHITE_POINT, MAX_WHITE_POINT_ADJUSTMENT) - } - - private fun writePhotonCurve( - output: FloatArray, - outputOffset: Int, - curveSamples: PhotonCurveSamples, - toneAnchors: PhotonToneAnchors, - global: PhotonPgtmCellStats, - local: PhotonPgtmCellStats, - ) { - val pointCount = curveSamples.sceneLinear.size - val localParams = buildLocalMicroContrastParams( - toneAnchors = toneAnchors, - global = global, - local = local - ) - var previousOutput = 0f - val lowTableInput = 1f / max(pointCount - 1, 1).toFloat() - val lowSceneLinear = sceneLinearForTableInput(lowTableInput, curveSamples.inputScale) - val lowBaseOutput = photonGlobalToneOutput(lowSceneLinear, toneAnchors) - val lowOutput = applyLocalMicroContrast( - baseOutput = lowBaseOutput, - sceneLog2 = log2(lowSceneLinear), - tonalWindow = localMicroContrastTonalWindow(lowSceneLinear, toneAnchors), - params = localParams - ) - val lowGain = (lowOutput / lowSceneLinear) - .coerceIn(0.05f, MAX_GAIN_VALUE) - for (index in 0 until pointCount) { - val sceneLinear = curveSamples.sceneLinear[index] - if (sceneLinear <= MIN_CURVE_INPUT) { - output[outputOffset + index] = lowGain - continue - } - val targetOutput = applyLocalMicroContrast( - baseOutput = curveSamples.baseOutput[index], - sceneLog2 = curveSamples.sceneLog2[index], - tonalWindow = curveSamples.tonalWindow[index], - params = localParams - ) - val monotonicOutput = max(previousOutput, targetOutput) - output[outputOffset + index] = (monotonicOutput / max(sceneLinear, MIN_CURVE_INPUT)) - .coerceIn(0.05f, MAX_GAIN_VALUE) - previousOutput = monotonicOutput - } - } - - private fun buildPhotonCurveSamples( - pointCount: Int, - inputScale: Float, - toneAnchors: PhotonToneAnchors, - ): PhotonCurveSamples { - val safeInputScale = sanitizeInputScale(inputScale) - val sceneLinear = FloatArray(pointCount) - val baseOutput = FloatArray(pointCount) - val sceneLog2 = FloatArray(pointCount) - val tonalWindow = FloatArray(pointCount) - for (index in 0 until pointCount) { - val tableInput = tableInputForIndex(index, pointCount) - val scene = sceneLinearForTableInput(tableInput, safeInputScale) - sceneLinear[index] = scene - baseOutput[index] = photonGlobalToneOutput(scene, toneAnchors) - sceneLog2[index] = if (scene > 0f) log2(scene) else Float.NEGATIVE_INFINITY - tonalWindow[index] = localMicroContrastTonalWindow(scene, toneAnchors) - } - return PhotonCurveSamples( - inputScale = safeInputScale, - sceneLinear = sceneLinear, - baseOutput = baseOutput, - sceneLog2 = sceneLog2, - tonalWindow = tonalWindow - ) - } - - private fun photonToneOutput( - sceneLinear: Float, - toneAnchors: PhotonToneAnchors, - global: PhotonPgtmCellStats, - local: PhotonPgtmCellStats, - ): Float { - if (sceneLinear <= 0f) return 0f - val baseOutput = photonGlobalToneOutput(sceneLinear, toneAnchors) - return photonLocalMicroContrastOutput( - baseOutput = baseOutput, - sceneLinear = sceneLinear, - toneAnchors = toneAnchors, - global = global, - local = local - ) - } - - private fun photonGlobalToneOutput( - sceneLinear: Float, - toneAnchors: PhotonToneAnchors, - ): Float { - if (sceneLinear <= 0f) return 0f - if (sceneLinear < toneAnchors.blackPoint) { - return toneAnchors.blackOutput * (sceneLinear / toneAnchors.blackPoint) - } - if (sceneLinear >= toneAnchors.whitePoint) return 1f - - val encoded = ( - (log2(sceneLinear / toneAnchors.middleGrayPoint) - toneAnchors.blackRelativeExposure) / - toneAnchors.curveDynamicRangeEv - ).coerceIn(0f, 1f) - val pivotX = (-toneAnchors.blackRelativeExposure / toneAnchors.curveDynamicRangeEv) - .coerceIn(1e-4f, 1f - 1e-4f) - val pivotY = toneAnchors.middleGrayOutput - val leftSecant = (pivotY - toneAnchors.blackOutput) / pivotX - val rightSecant = (1f - pivotY) / (1f - pivotX) - val rangeStrength = (toneAnchors.targetDynamicRangeEv - MIN_DYNAMIC_RANGE_EV) / - (MAX_DYNAMIC_RANGE_EV - MIN_DYNAMIC_RANGE_EV) - val desiredPivotSlope = lerp(0.84f, 0.94f, rangeStrength) - val monotoneSlopeLimit = 0.92f * 3f * min(leftSecant, rightSecant) - val pivotSlope = min(desiredPivotSlope, monotoneSlopeLimit) - val highlightEndpointSlopeRatio = lerp( - MIN_HIGHLIGHT_ENDPOINT_SLOPE_RATIO, - MAX_HIGHLIGHT_ENDPOINT_SLOPE_RATIO, - rangeStrength - ) - - return if (encoded <= pivotX) { - val segmentT = encoded / pivotX - cubicHermite( - start = toneAnchors.blackOutput, - end = pivotY, - startSlope = leftSecant * 0.06f * pivotX, - endSlope = pivotSlope * pivotX, - t = segmentT - ) - } else { - val segmentLength = 1f - pivotX - val segmentT = (encoded - pivotX) / segmentLength - cubicHermite( - start = pivotY, - end = 1f, - startSlope = pivotSlope * segmentLength, - endSlope = rightSecant * highlightEndpointSlopeRatio * segmentLength, - t = segmentT - ) - } - } - - private fun cubicHermite( - start: Float, - end: Float, - startSlope: Float, - endSlope: Float, - t: Float, - ): Float { - val u = t.coerceIn(0f, 1f) - val u2 = u * u - val u3 = u2 * u - val h00 = 2f * u3 - 3f * u2 + 1f - val h10 = u3 - 2f * u2 + u - val h01 = -2f * u3 + 3f * u2 - val h11 = u3 - u2 - return (h00 * start + h10 * startSlope + h01 * end + h11 * endSlope) - .coerceIn(start, end) - } - - private fun photonLocalMicroContrastOutput( - baseOutput: Float, - sceneLinear: Float, - toneAnchors: PhotonToneAnchors, - global: PhotonPgtmCellStats, - local: PhotonPgtmCellStats, - ): Float { - if (baseOutput <= 0f || baseOutput >= 1f) return baseOutput - val params = buildLocalMicroContrastParams(toneAnchors, global, local) - return applyLocalMicroContrast( - baseOutput = baseOutput, - sceneLog2 = log2(sceneLinear), - tonalWindow = localMicroContrastTonalWindow(sceneLinear, toneAnchors), - params = params - ) - } - - private fun buildLocalMicroContrastParams( - toneAnchors: PhotonToneAnchors, - global: PhotonPgtmCellStats, - local: PhotonPgtmCellStats, - ): LocalMicroContrastParams { - val localRangeEv = log2((local.p90 + 0.008f) / (local.p10 + 0.008f)) - .coerceIn(0f, 8f) - val globalRangeEv = log2((global.p90 + 0.008f) / (global.p10 + 0.008f)) - .coerceIn(0f, 8f) - val localDetail = smoothStep(0.90f, 3.15f, localRangeEv) - val relativeDetail = smoothStep(-0.35f, 0.80f, localRangeEv - globalRangeEv) - val highlightDamping = 1f - 0.38f * smoothStep(0.14f, 0.38f, global.highlightFraction) - val strengthEv = MAX_LOCAL_MICRO_CONTRAST_EV * localDetail * - lerp(0.72f, 1f, relativeDetail) * highlightDamping - if (strengthEv <= 1e-4f) { - return LocalMicroContrastParams(strengthEv = 0f, pivotLog2 = 0f) - } - - val localPivot = local.p50.coerceIn( - toneAnchors.middleGrayPoint * 0.45f, - toneAnchors.middleGrayPoint * 1.65f - ) - return LocalMicroContrastParams( - strengthEv = strengthEv, - pivotLog2 = lerp( - log2(toneAnchors.middleGrayPoint), - log2(localPivot), - 0.35f - ) - ) - } - - private fun applyLocalMicroContrast( - baseOutput: Float, - sceneLog2: Float, - tonalWindow: Float, - params: LocalMicroContrastParams, - ): Float { - if (baseOutput <= 0f || baseOutput >= 1f || params.strengthEv <= 1e-4f) { - return baseOutput - } - val signedDistance = ((sceneLog2 - params.pivotLog2) / 1.45f) - .coerceIn(-1f, 1f) - val adjusted = baseOutput * 2.0f.pow(params.strengthEv * signedDistance * tonalWindow) - return adjusted.coerceIn(0f, 1f) - } - - private fun localMicroContrastTonalWindow( - sceneLinear: Float, - toneAnchors: PhotonToneAnchors, - ): Float { - if (sceneLinear <= 0f) return 0f - val blackFeatherEnd = max(toneAnchors.blackPoint * 4f, 0.018f) - val highlightFeatherStart = max( - toneAnchors.middleGrayPoint * 2.4f, - toneAnchors.whitePoint * 0.48f - ) - val highlightFeatherEnd = max( - highlightFeatherStart + 1e-4f, - toneAnchors.whitePoint * 0.82f - ) - return smoothStep(toneAnchors.blackPoint, blackFeatherEnd, sceneLinear) * - (1f - smoothStep(highlightFeatherStart, highlightFeatherEnd, sceneLinear)) - } - - private fun photonPgtmInputWeights(inputScale: Float): FloatArray { - val scale = sanitizeInputScale(inputScale) - return FloatArray(MAP_INPUT_WEIGHT_COUNT) { index -> - BASE_INPUT_WEIGHTS[index] * 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 sceneLinearForTableInput(tableInput: Float, inputScale: Float): Float { - val encodedInput = tableInput.coerceIn(0f, 1f) - val normalizedScene = encodedInput.pow(1f / TABLE_INPUT_GAMMA) - return normalizedScene / sanitizeInputScale(inputScale) - } - - private fun sanitizeInputScale(inputScale: Float): Float { - return inputScale.takeIf { it.isFinite() } - ?.coerceIn(MIN_CURVE_INPUT, 1.0f) - ?: 1.0f - } - - 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 t = if (y1 > y0) (target - y0) / (y1 - y0) else 0f - return lerp(x0, x1, t) - } - index += 2 - } - return points[points.size - 2].coerceIn(0f, 1f) - } - - private fun photonProfileOutputForInput(inputValue: Float): Float { - val input = inputValue.coerceIn(0f, 1f) - val points = DngProfileToneCurve.photonPgtmToneCurvePoints() - if (points.size < 4) return input - 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 (input <= x1) { - val t = if (x1 > x0) (input - x0) / (x1 - x0) else 0f - return lerp(y0, y1, t) - } - index += 2 - } - return points.last().coerceIn(0f, 1f) - } - - 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 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 data class PhotonPgtmCellStats( - val p10: Float, - val p50: Float, - val p90: Float, - val p98: Float, - val highlightFraction: Float, - val p995: Float, - val p999: Float, - val maxInput: Float, - val sampleWeight: Float, - ) - - private data class PhotonCurveSamples( - val inputScale: Float, - val sceneLinear: FloatArray, - val baseOutput: FloatArray, - val sceneLog2: FloatArray, - val tonalWindow: FloatArray, - ) - - private data class LocalMicroContrastParams( - val strengthEv: Float, - val pivotLog2: Float, - ) - - private data class PhotonToneAnchors( - val tailHighlightRangeEv: Float, - val exposureHighlightRangeEv: Float, - val exposureHighlightReference: Float, - val highlightGapEv: Float, - val sparseHighlightStrength: Float, - val targetDynamicRangeEv: Float, - val curveDynamicRangeEv: Float, - val blackRelativeExposure: Float, - val whiteRelativeExposure: Float, - val blackPoint: Float, - val blackOutput: Float, - val middleGrayPoint: Float, - val middleGrayOutput: Float, - val displayBlackPoint: Float, - val displayMiddleGray: Float, - val tierDisplayMiddleGray: Float, - val whitePoint: Float, - val rawWhitePoint: Float, - ) - - internal data class PhotonHighlightRanges( - val tailRangeEv: Float, - val exposureRangeEv: Float, - val exposureReference: Float, - val highlightGapEv: Float, - val sparseStrength: Float, - ) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt b/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt index 2fe914a9..1c2e5515 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt @@ -160,7 +160,7 @@ internal class GlesRawProfileGainTableMapBuilder { maxInput = maxInput, linearSum = linearSum, logSum = logSum - ) + ) ?: error("GPU RAW PGTM global stats are empty") val diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU RAW") val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure) val map = when (profileToneMapMode) { @@ -169,7 +169,7 @@ internal class GlesRawProfileGainTableMapBuilder { height = height, baselineExposureEv = baselineExposureEv, packedCellStats = packedCellStats, - globalStats = globalStats ?: error("GPU RAW PGTM global stats are empty"), + globalStats = globalStats, diagnosticBand = diagnosticBand, statsSource = "gpu-log-histogram-$GLOBAL_HISTOGRAM_BIN_COUNT" ) @@ -179,6 +179,7 @@ internal class GlesRawProfileGainTableMapBuilder { height = height, baselineExposureEv = baselineExposureEv, packedCellStats = packedCellStats, + denseGlobalStats = globalStats, diagnosticBand = diagnosticBand ) @@ -186,6 +187,19 @@ internal class GlesRawProfileGainTableMapBuilder { RawProfileToneMapMode.OppoMaster -> null } val completeNs = System.nanoTime() + if (map != null && profileToneMapMode == RawProfileToneMapMode.GooglePixel) { + val risk = DngHdrProfileGainTableGenerator.highlightRiskBandFor( + stats = globalStats, + inputScale = map.mapInputWeights.sum(), + ) + PLog.d( + TAG, + "Google PGTM highlight risk: strength=${risk.strength} " + + "tableBand=${risk.start}..${risk.end} p90=${globalStats.p90} " + + "p98=${globalStats.p98} p995=${globalStats.p995} " + + "p999=${globalStats.p999} fraction=${globalStats.highlightFraction}" + ) + } PLog.d( TAG, "GPU RAW PGTM built: mode=$profileToneMapMode grid=${gridWidth}x${gridHeight} " + diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt index b7928073..dca854fa 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt @@ -34,7 +34,8 @@ internal object RawProfileGainTableMapBuilder { metadata = metadata, samplesPerPixel = samplesPerPixel, statsBounds = statsBounds, - collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon + collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon || + profileToneMapMode == RawProfileToneMapMode.GooglePixel ) ?: return null val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG) val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure) @@ -44,6 +45,7 @@ internal object RawProfileGainTableMapBuilder { height = height, baselineExposureEv = baselineExposureEv, packedCellStats = stats.packedCellStats, + denseGlobalStats = stats.globalStats ?: return null, diagnosticBand = diagnosticBand ) diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt index b2ca7623..257154db 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt @@ -99,6 +99,150 @@ class DngHdrProfileGainTableGeneratorTest { actualOutput + 0.025f >= expectedOutput ) } + + } + + @Test + fun denseSceneStatsMatchOfficial184953HighlightShoulder() { + val fixture = loadFixture( + "/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture" + ) + val map = DngHdrProfileGainTableGenerator.forCellStats( + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats, + denseGlobalStats = DngPgtmGlobalStats( + p10 = 0.005191058f, + p50 = 0.018155192f, + p90 = 0.551834350f, + p98 = 1.162652485f, + p995 = 3.329099033f, + p999 = 8.389943569f, + maxInput = 8.389943569f, + highlightFraction = 0.034409841f, + linearMean = 0.206666246f, + logAverage = 0.039490954f, + shadowEdge = 0.005191058f, + shadowFoot = 0.005191058f, + sampleCount = 786_432, + ), + ) ?: error("Expected Google PGTM for ${fixture.sourceName}") + val expectedSpecular = anchorGains( + source = fixture.expectedGains, + cellCount = fixture.cellCount, + anchor = ToneAnchor.SPECULAR + ) + val actualSpecular = actualAnchorGains(fixture, map, ToneAnchor.SPECULAR) + val trustedShoulderCells = actualSpecular.indices.filter { cell -> + fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999] in 2f..3f + } + + assertTrue("Expected trusted shoulder cells", trustedShoulderCells.isNotEmpty()) + val trustedShoulderResults = trustedShoulderCells.map { cell -> + val p999 = fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999] + val expectedOutput = p999 * expectedSpecular[cell] + val actualOutput = p999 * actualSpecular[cell] + TrustedShoulderResult(cell, p999, expectedOutput, actualOutput) + } + + val fixedShoulderResults = listOf( + FixedShoulderReference(tableInput = 0.25f, officialMedianGain = 0.915178f), + FixedShoulderReference(tableInput = 0.50f, officialMedianGain = 0.544002f), + FixedShoulderReference(tableInput = 0.75f, officialMedianGain = 0.395906f), + ).map { reference -> + val actualMedianGain = percentile( + FloatArray(fixture.cellCount) { cell -> + sampleGain(map, reference.tableInput, cell) + }, + 0.50f, + ) + FixedShoulderResult( + reference = reference, + actualMedianGain = actualMedianGain, + ) + } + assertTrue( + trustedShoulderResults.joinToString("\n") { result -> + "cell=${result.cell} p999=${result.p999} expectedOutput=" + + "${result.expectedOutput} actualOutput=${result.actualOutput}" + } + "\n" + fixedShoulderResults.joinToString("\n") { result -> + "tableInput=${result.reference.tableInput} officialMedianGain=" + + "${result.reference.officialMedianGain} " + + "actualMedianGain=${result.actualMedianGain}" + }, + trustedShoulderResults.all { result -> + result.actualOutput + 0.025f >= result.expectedOutput + } && + fixedShoulderResults.all { result -> + abs(result.actualMedianGain - result.reference.officialMedianGain) <= 0.03f + }, + ) + } + + @Test + fun denseSceneRiskPreservesOfficialShouldersAcrossSkyykingSet() { + val fixturesByName = loadFixtures().associateBy { it.sourceName } + val results = denseShoulderCases().flatMap { case -> + val fixture = fixturesByName[case.name] ?: error("Missing fixture ${case.name}") + val map = DngHdrProfileGainTableGenerator.forCellStats( + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats, + denseGlobalStats = case.globalStats, + ) ?: error("Expected Google PGTM for ${case.name}") + listOf(0.25f, 0.50f, 0.75f).mapIndexed { index, tableInput -> + val actual = percentile( + FloatArray(fixture.cellCount) { cell -> sampleGain(map, tableInput, cell) }, + 0.50f, + ) + DenseShoulderResult( + name = case.name, + tableInput = tableInput, + expectedGain = case.officialMedianGains[index], + actualGain = actual, + errorEv = abs(log2(actual / case.officialMedianGains[index])), + ) + } + } + assertTrue( + results.joinToString("\n") { result -> + "${result.name} t=${result.tableInput} expected=${result.expectedGain} " + + "actual=${result.actualGain} errorEv=${result.errorEv}" + }, + results.all { it.errorEv <= 0.38f }, + ) + } + + @Test + fun denseTailRiskSeparatesSparseOutliersFromSupportedHighlights() { + val fixturesByName = loadFixtures().associateBy { it.sourceName } + val casesByName = denseShoulderCases().associateBy { it.name } + + fun risk(name: String): HdrHighlightRiskBand { + val fixture = fixturesByName[name] ?: error("Missing fixture $name") + val case = casesByName[name] ?: error("Missing dense stats $name") + return DngHdrProfileGainTableGenerator.highlightRiskBandFor( + stats = case.globalStats, + inputScale = fixture.inputScale, + ) + } + + val sparseBrokenTail = risk("Skyyking_20260711_184953.RAW-02.ORIGINAL") + val denseSupportedHighlights = risk("Skyyking_20260711_185704.RAW-02.ORIGINAL") + val continuousTail = risk("Skyyking_20260711_184627.RAW-02.ORIGINAL") + + assertTrue("sparseBrokenTail=$sparseBrokenTail", sparseBrokenTail.strength > 0.99f) + assertTrue( + "sparseBrokenTail=$sparseBrokenTail", + sparseBrokenTail.start in 0.17f..0.18f && sparseBrokenTail.end in 0.36f..0.37f, + ) + assertTrue( + "denseSupportedHighlights=$denseSupportedHighlights", + denseSupportedHighlights.strength < 0.01f, + ) + assertTrue("continuousTail=$continuousTail", continuousTail.strength < 0.01f) } @Test @@ -319,6 +463,56 @@ class DngHdrProfileGainTableGeneratorTest { return (ln(value.coerceAtLeast(1e-6f).toDouble()) / ln(2.0)).toFloat() } + private fun denseShoulderCases(): List = listOf( + denseShoulderCase("Skyyking_20260711_184627.RAW-02.ORIGINAL", 0.020172335f, 0.124901251f, 0.875294007f, 5.471382292f, 10.767577893f, 14.655574315f, 20.611095419f, 0.099154154f, 0.499043244f, 0.125733883f, 0.331765622f, 0.205544580f, 0.152909992f), + denseShoulderCase("Skyyking_20260711_184751.RAW-02.ORIGINAL", 0.061056067f, 0.314396789f, 1.012212430f, 1.605002744f, 2.246847243f, 3.700378549f, 4.366255744f, 0.124490102f, 0.437985919f, 0.264671714f, 0.462672237f, 0.337412789f, 0.272237092f), + denseShoulderCase("Skyyking_20260711_184953.RAW-02.ORIGINAL", 0.005191058f, 0.018155192f, 0.551834350f, 1.162652485f, 3.329099033f, 8.389943569f, 8.389943569f, 0.034409841f, 0.206666246f, 0.039490954f, 0.915177912f, 0.544002324f, 0.395905923f), + denseShoulderCase("Skyyking_20260711_185653.RAW-02.ORIGINAL", 0.370311566f, 2.512482396f, 3.813213919f, 5.120475517f, 5.567614998f, 5.790177933f, 38.276195401f, 0.746487935f, 2.251304119f, 1.571741688f, 0.213499438f, 0.181819726f, 0.162513237f), + denseShoulderCase("Skyyking_20260711_185704.RAW-02.ORIGINAL", 0.145013743f, 0.316054048f, 3.469537212f, 8.847691807f, 14.915796129f, 29.121761960f, 29.121761960f, 0.301193237f, 1.294745890f, 0.479610381f, 0.163654307f, 0.101506390f, 0.075539880f), + denseShoulderCase("Skyyking_20260711_185836.RAW-02.ORIGINAL", 0.012206823f, 0.126480593f, 0.355587152f, 0.432792685f, 0.462650502f, 0.493159692f, 2.637294839f, 0.000026703f, 0.156404806f, 0.089910030f, 0.522830814f, 0.433588199f, 0.374911249f), + denseShoulderCase("Skyyking_20260712_105529.RAW-02.ORIGINAL", 0.010147940f, 0.107563684f, 1.562283487f, 4.157630135f, 6.125361249f, 8.462417930f, 18.567126558f, 0.154716492f, 0.510046194f, 0.124380931f, 0.332546350f, 0.203987684f, 0.150961947f), + denseShoulderCase("Skyyking_20260713_232945.RAW-02.ORIGINAL", 0.038518862f, 0.254915462f, 0.947498705f, 1.376204882f, 1.562541283f, 1.695016885f, 6.936506958f, 0.107442220f, 0.378671069f, 0.221436961f, 0.504472025f, 0.425721936f, 0.372749154f), + denseShoulderCase("Skyyking_20260714_083737.RAW-02.ORIGINAL", 0.003378016f, 0.008042096f, 0.294214780f, 4.110145986f, 5.340132478f, 5.523095724f, 5.645071221f, 0.037193298f, 0.192204495f, 0.017270404f, 0.735527232f, 0.438027993f, 0.319880389f), + denseShoulderCase("Skyyking_20260714_092416.RAW-02.ORIGINAL", 0.004266809f, 0.063950656f, 2.126153418f, 3.981748021f, 4.972982040f, 6.020569097f, 20.924798021f, 0.187920888f, 0.539285387f, 0.071365597f, 0.243842043f, 0.142250773f, 0.102864855f), + denseShoulderCase("Skyyking_20260714_123251.RAW-02.ORIGINAL", 0.017058925f, 0.120602039f, 0.471383246f, 4.107495723f, 7.774886715f, 20.029784120f, 20.287619715f, 0.045697530f, 0.362590556f, 0.109233882f, 0.259386316f, 0.154736947f, 0.113109255f), + denseShoulderCase("Skyyking_20260714_151021.RAW-02.ORIGINAL", 0.005190248f, 0.084016346f, 0.313368077f, 2.072844313f, 4.232514755f, 7.760019339f, 10.563597493f, 0.050816854f, 0.222183756f, 0.064319970f, 0.411366213f, 0.272355564f, 0.209032677f), + ) + + private fun denseShoulderCase( + name: String, + p10: Float, + p50: Float, + p90: Float, + p98: Float, + p995: Float, + p999: Float, + maxInput: Float, + highlightFraction: Float, + linearMean: Float, + logAverage: Float, + gain25: Float, + gain50: Float, + gain75: Float, + ) = DenseShoulderCase( + name = name, + globalStats = DngPgtmGlobalStats( + p10 = p10, + p50 = p50, + p90 = p90, + p98 = p98, + p995 = p995, + p999 = p999, + maxInput = maxInput, + highlightFraction = highlightFraction, + linearMean = linearMean, + logAverage = logAverage, + shadowEdge = p10, + shadowFoot = p10, + sampleCount = 786_432, + ), + officialMedianGains = floatArrayOf(gain25, gain50, gain75), + ) + private fun loadFixtures(): List = FIXTURE_RESOURCES.map(::loadFixture) private fun loadFixture(resourceName: String): PgtmFixture { @@ -385,6 +579,37 @@ class DngHdrProfileGainTableGeneratorTest { val inputScale: Float get() = inputWeights.sum() } + private data class FixedShoulderReference( + val tableInput: Float, + val officialMedianGain: Float, + ) + + private data class FixedShoulderResult( + val reference: FixedShoulderReference, + val actualMedianGain: Float, + ) + + private data class TrustedShoulderResult( + val cell: Int, + val p999: Float, + val expectedOutput: Float, + val actualOutput: Float, + ) + + private data class DenseShoulderCase( + val name: String, + val globalStats: DngPgtmGlobalStats, + val officialMedianGains: FloatArray, + ) + + private data class DenseShoulderResult( + val name: String, + val tableInput: Float, + val expectedGain: Float, + val actualGain: Float, + val errorEv: Float, + ) + private companion object { private const val CELL_STATS_STRIDE = 8 private const val STAT_P10 = 0 diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt index 0d3b0a74..d1fb2c4d 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt @@ -1,8 +1,11 @@ package com.hinnka.mycamera.raw -import org.junit.Ignore +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test +import kotlin.math.abs import kotlin.math.floor import kotlin.math.ln import kotlin.math.max @@ -10,571 +13,187 @@ import kotlin.math.pow class DngPhotonProfileGainTableGeneratorTest { @Test - fun compatibleWideRangeFieldCalibrationStaysWithinPointTwelveEv() { - assertFieldCalibrationCases( - listOf( - ExposureCalibrationCase( - name = "14:22 baseline-0 wide-range", - baselineExposureEv = 0f, - 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, - reportedObservedRangeEv = 6.6257324f, - reportedExposureLiftEv = 2.47f, - reportedBrightnessErrorEv = 0.23f - ) - ) + fun photonIsGoogleExposureFusionWithPhotonParameters() { + val fixture = uniformFixture( + p10 = 0.015f, + p50 = 0.08f, + p90 = 0.55f, + p98 = 0.80f, + p995 = 1.058f, + p999 = 1.15f, ) - } + val photon = generatePhotonMap(fixture) + val directGoogle = DngHdrProfileGainTableGenerator.forCellStats( + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats, + denseGlobalStats = fixture.globalStats, + fusionParameters = DngPhotonProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS, + ) ?: error("Expected direct Google PGTM") - @Ignore( - "This persisted field case predates log-average diagnostics. The new " + - "exposure model requires the measured log average and must not " + - "reconstruct it from p50." - ) - @Test - fun lowRangeFieldCalibrationWithoutLogAverage() { - assertFieldCalibrationCases( - listOf( - ExposureCalibrationCase( - name = "14:18 baseline-0 low-range", - baselineExposureEv = 0f, - p10 = 0.035187688f, - p50 = 0.08524494f, - p90 = 0.14404307f, - p98 = 0.16417652f, - p995 = 0.17360601f, - p999 = 0.18164334f, - maxInput = 0.20776238f, - linearMean = null, - logAverage = null, - highlightFraction = 0f, - reportedObservedRangeEv = 2.3679657f, - reportedExposureLiftEv = 0.66f, - reportedBrightnessErrorEv = 0.39f - ) - ) - ) + 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) } @Test - fun highlightRangeSeparatesOldScenesAndStabilizesNearIdenticalDngs() { - val oldWideRange = log2(0.5752382f / 0.09985464f) - val oldNarrowRange = log2(0.2313348f / 0.07818398f) - assertTrue( - "oldWide=$oldWideRange oldNarrow=$oldNarrowRange", - oldWideRange - oldNarrowRange > 0.90f - ) - - val dng2840LogAverage = 0.0932018935f - val dng2840P999 = 0.3981607637f - val dng2842LogAverage = 0.07615876645f - val dng2842P999 = 0.3566421426f - val dng2840Range = log2(dng2840P999 / dng2840LogAverage) - val dng2842Range = log2(dng2842P999 / dng2842LogAverage) - assertTrue( - "dng2840=$dng2840Range dng2842=$dng2842Range", - kotlin.math.abs(dng2842Range - dng2840Range) < 0.15f - ) - - val dng2840DisplayEv = log2(dng2840LogAverage) + - DngPhotonProfileGainTableGenerator.displayExposureLiftEv(dng2840Range) - val dng2842DisplayEv = log2(dng2842LogAverage) + - DngPhotonProfileGainTableGenerator.displayExposureLiftEv(dng2842Range) - assertTrue( - "dng2840DisplayEv=$dng2840DisplayEv dng2842DisplayEv=$dng2842DisplayEv", - kotlin.math.abs(dng2842DisplayEv - dng2840DisplayEv) <= 0.12f - ) - - val normalHighlightCases = listOf( - DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.263932749f, - p98 = 0.3304134763f, - p995 = 0.3685588609f, - p999 = 0.3981607637f, - sceneMiddle = 0.0932018935f - ), - DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.2486532208f, - p98 = 0.2975876967f, - p995 = 0.3287509693f, - p999 = 0.3566421426f, - sceneMiddle = 0.07615876645f - ), - DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.35547075f, - p98 = 0.4203099f, - p995 = 0.44679728f, - p999 = 0.46304873f, - sceneMiddle = 0.039605092f - ), - DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.21021318f, - p98 = 0.24911182f, - p995 = 0.27169982f, - p999 = 0.5752382f, - sceneMiddle = 0.09985464f - ), - DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.13890508f, - p98 = 0.18092623f, - p995 = 0.2126976f, - p999 = 0.2313348f, - sceneMiddle = 0.07818398f - ) - ) - normalHighlightCases.forEach { ranges -> - assertTrue("sparseStrength=${ranges.sparseStrength}", ranges.sparseStrength == 0f) - assertTrue( - "tail=${ranges.tailRangeEv} exposure=${ranges.exposureRangeEv}", - kotlin.math.abs(ranges.exposureRangeEv - ranges.tailRangeEv) < 1e-5f - ) - } - } - - @Test - fun separatedSparseHighlightsUseLogCenterAcrossHighlightGap() { - val ranges = DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.20524885f, - p98 = 0.45892385f, - p995 = 0.5724387f, - p999 = 0.6364626f, - sceneMiddle = 0.09018845f - ) - val tailLift = DngPhotonProfileGainTableGenerator.displayExposureLiftEv( - ranges.tailRangeEv - ) - val exposureLift = DngPhotonProfileGainTableGenerator.displayExposureLiftEv( - ranges.exposureRangeEv - ) - - assertTrue("tailRange=${ranges.tailRangeEv}", ranges.tailRangeEv in 2.81f..2.83f) - assertTrue( - "exposureRange=${ranges.exposureRangeEv}", - ranges.exposureRangeEv in 1.76f..1.78f - ) - assertTrue("sparseStrength=${ranges.sparseStrength}", ranges.sparseStrength == 1f) - assertTrue( - "tailLift=$tailLift exposureLift=$exposureLift", - exposureLift - tailLift in -1.39f..-1.37f - ) - } - - @Test - fun stronglySeparatedNearWhiteHighlightsDoNotForceMaximumExposureLift() { - val ranges = DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = 0.21023509f, - p98 = 0.8875543f, - p995 = 1.0032426f, - p999 = 1.0724883f, - sceneMiddle = 0.06121027f - ) - val exposureLift = DngPhotonProfileGainTableGenerator.displayExposureLiftEv( - ranges.exposureRangeEv - ) - val displayMiddle = 0.06121027f * 2.0f.pow(exposureLift) - - assertTrue("gap=${ranges.highlightGapEv}", ranges.highlightGapEv in 2.07f..2.09f) - assertTrue("sparseStrength=${ranges.sparseStrength}", ranges.sparseStrength == 1f) - assertTrue( - "exposureReference=${ranges.exposureReference}", - ranges.exposureReference in 0.431f..0.433f - ) - assertTrue( - "exposureRange=${ranges.exposureRangeEv}", - ranges.exposureRangeEv in 2.81f..2.83f - ) - assertTrue("exposureLift=$exposureLift", exposureLift in 1.65f..1.67f) - assertTrue("displayMiddle=$displayMiddle", displayMiddle in 0.192f..0.194f) - } - - @Test - fun baselineExposureDoesNotExpandProfileGainTablePastTrustedWhite() { - val width = 1280 - val height = 960 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - val stats = FloatArray( - cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - ) - repeat(cellCount) { cell -> - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = 0.008017952f - stats[offset + 1] = 0.06326936f - stats[offset + 2] = 1f - stats[offset + 3] = 1f - stats[offset + 4] = 0.13241959f - stats[offset + 5] = 256f - stats[offset + 6] = 12.278543f - stats[offset + 7] = 14.262961f - } - val baselineGain = 2.0f.pow(3.000001f) - val map = DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, + fun photonKeepsGoogleDomainAndWhiteEndpoint() { + val fixture = uniformFixture( baselineExposureEv = 3.000001f, - packedCellStats = stats, - globalStats = testGlobalStats( - p10 = 0.008017952f, - p50 = 0.06326936f, - p90 = 1f, - p98 = 1f, - p995 = 12.278543f, - p999 = 14.262961f, - maxInput = 14.262961f, - highlightFraction = 0.13241959f, - linearMean = 0.51709765f, - logAverage = 0.07712941f, - shadowEdge = 0.025163911f, - shadowFoot = 0.0035361373f - ), - emitDiagnostics = false - ) ?: error("Expected Photon PGTM") + p10 = 0.008017952f, + p50 = 0.06326936f, + p90 = 1f, + p98 = 1f, + p995 = 12.278543f, + p999 = 14.262961f, + highlightFraction = 0.13241959f, + ) + val photon = generatePhotonMap(fixture) + val google = DngHdrProfileGainTableGenerator.forCellStats( + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats, + ) ?: error("Expected Google PGTM") - val inputScale = map.mapInputWeights.sum() + assertEquals(google.gamma, photon.gamma, 0f) + assertArrayEquals(google.mapInputWeights, photon.mapInputWeights, 0f) + val inputScale = photon.mapInputWeights.sum() val sceneWhite = 1f / inputScale - val rawRight = sceneWhite / baselineGain - val terminalGain = medianGain(map, tableInput = 1f) - val pgtmAtRawWhite = baselineGain * terminalGain - val displayAtDomainRight = finalOutputForScene(map, inputScale, sceneWhite) - - assertTrue("sceneWhite=$sceneWhite", sceneWhite in 1.299f..1.301f) - assertTrue("rawRight=$rawRight", rawRight in 0.1623f..0.1627f) - assertTrue( - "terminalGain=$terminalGain pgtmAtRawWhite=$pgtmAtRawWhite", - pgtmAtRawWhite > 1.5f - ) - assertTrue("domainRight=$displayAtDomainRight", displayAtDomainRight in 0.99f..1.01f) - assertCurvesAreFiniteAndMonotonic(map, sceneWhite) - } - - @Ignore( - "Conflicting field feedback: the baseline-3 low-range case has nearly " + - "the same observed range and p50 as the active 14:18 case but " + - "requires 0.51 EV more exposure. Keep both cases without changing " + - "the stable one-dimensional range model." - ) - @Test - fun conflictingBaselineThreeFieldCalibrationScenes() { - assertFieldCalibrationCases( - listOf( - ExposureCalibrationCase( - name = "18:53 baseline-3 sparse-tail", - baselineExposureEv = 3f, - p10 = 0.022204947f, - p50 = 0.13993193f, - p90 = 0.21021318f, - p98 = 0.24911182f, - p995 = 0.27169982f, - p999 = 0.5752382f, - maxInput = 1.249979f, - linearMean = 0.1295324f, - logAverage = 0.09985464f, - highlightFraction = 6.739298E-5f, - reportedObservedRangeEv = 4.6952066f, - reportedExposureLiftEv = 0.2878443f, - reportedBrightnessErrorEv = 0.28f - ), - ExposureCalibrationCase( - name = "18:54 baseline-3 low-range", - baselineExposureEv = 3f, - p10 = 0.045957692f, - p50 = 0.08537395f, - p90 = 0.13890508f, - p98 = 0.18092623f, - p995 = 0.2126976f, - p999 = 0.2313348f, - maxInput = 0.27256522f, - linearMean = 0.08850919f, - logAverage = 0.07818398f, - highlightFraction = 0f, - reportedObservedRangeEv = 2.331604f, - reportedExposureLiftEv = 0.27f, - reportedBrightnessErrorEv = -0.51f - ) - ) - ) - } - - @Test - fun sparseHighlightTailSelectsNineEvAndRaisesSceneMedian() { - val width = 2800 - val height = 2102 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - val stats = FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) - repeat(cellCount) { cell -> - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = 0.045098f - stats[offset + 1] = 0.113744f - stats[offset + 2] = 0.243189f - stats[offset + 3] = 0.277654f - stats[offset + 4] = 0.023916f - stats[offset + 5] = 64f - stats[offset + 6] = 1.290788f - stats[offset + 7] = 1.469952f + repeat(photon.mapPointsH * photon.mapPointsV) { cell -> + val photonTerminalGain = photon.gains[(cell + 1) * photon.mapPointsN - 1] + val googleTerminalGain = google.gains[(cell + 1) * google.mapPointsN - 1] + assertEquals(googleTerminalGain, photonTerminalGain, 1e-6f) + assertEquals(1f, sceneWhite * photonTerminalGain, 2e-4f) } - - val map = DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = 0.64f, - packedCellStats = stats, - globalStats = testGlobalStats( - p10 = 0.045098f, - p50 = 0.113744f, - p90 = 0.243189f, - p98 = 0.277654f, - p995 = 1.290788f, - p999 = 1.469952f, - maxInput = 1.469952f, - highlightFraction = 0.023916f - ), - emitDiagnostics = false - ) ?: error("Expected Photon PGTM") - - val inputScale = map.mapInputWeights.sum() - val sceneWhite = 1f / inputScale - val baselineGain = 2.0f.pow(0.64f) - val rawRight = sceneWhite / baselineGain - val sourceBlackPoint = max( - 0.045098f / 2.0f.pow( - DngPhotonProfileGainTableGenerator.SHADOW_FOOT_HEADROOM_EV - ), - sceneWhite / 2.0f.pow(9.75f) - ) - val blackOutput = sourceBlackPoint * medianGain( - map, - tableInputForScene(map, inputScale, sourceBlackPoint) - ) - val finalBlackOutput = samplePhotonProfileCurve(blackOutput) - val sceneMedian = 0.113744f - val middleOutput = sceneMedian * medianGain( - map, - tableInputForScene(map, inputScale, sceneMedian) - ) - val finalMiddleOutput = samplePhotonProfileCurve(middleOutput) - val whiteOutput = sceneWhite * medianGain(map, tableInput = 1f) - val finalWhiteOutput = samplePhotonProfileCurve(whiteOutput) - val outputDynamicRangeEv = log2(finalWhiteOutput / finalBlackOutput) - - assertTrue("gamma=${map.gamma}", map.gamma == 0.5f) - assertTrue( - "sceneWhite=$sceneWhite baselineGain=$baselineGain", - sceneWhite in 1f..1.3001f - ) - assertTrue( - "rawRight=$rawRight", - rawRight in (1f / baselineGain)..(1.3001f / baselineGain) - ) - assertTrue("outputDynamicRangeEv=$outputDynamicRangeEv", outputDynamicRangeEv in 8.8f..9.2f) - assertTrue("finalMiddleOutput=$finalMiddleOutput", finalMiddleOutput in 0.285f..0.305f) - assertTrue( - "sceneMedian=$sceneMedian finalMiddleOutput=$finalMiddleOutput", - finalMiddleOutput > sceneMedian * 1.45f - ) - assertTrue("whiteOutput=$whiteOutput", whiteOutput in 0.98f..1.01f) - assertCurvesAreFiniteAndMonotonic(map, sceneWhite) + assertCurvesAreFiniteAndMonotonic(photon, sceneWhite) } @Test - fun detailedCellGetsMoreLocalMicroContrastThanFlatCell() { - val width = 1280 - val height = 960 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - val stats = FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) - repeat(cellCount) { cell -> - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = 0.12f - stats[offset + 1] = 0.18f - stats[offset + 2] = 0.24f - stats[offset + 3] = 0.30f - stats[offset + 4] = 0f - stats[offset + 5] = 64f - stats[offset + 6] = 0.35f - stats[offset + 7] = 0.40f - } - stats[0] = 0.03f - stats[1] = 0.18f - stats[2] = 0.55f - stats[3] = 0.72f - stats[6] = 0.82f - stats[7] = 0.90f - - val map = DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = 0f, - packedCellStats = stats, - globalStats = testGlobalStats( - p10 = 0.12f, - p50 = 0.18f, - p90 = 0.24f, - p98 = 0.30f, - p995 = 0.35f, - p999 = 0.40f, - maxInput = 0.90f - ), - emitDiagnostics = false - ) ?: error("Expected Photon PGTM") - val inputScale = map.mapInputWeights.sum() - val lowScene = 0.11f - val highScene = 0.28f - val lowTableInput = tableInputForScene(map, inputScale, lowScene) - val highTableInput = tableInputForScene(map, inputScale, highScene) - val detailedContrast = highScene * gainForCell(map, 0, highTableInput) / - (lowScene * gainForCell(map, 0, lowTableInput)) - val flatContrast = highScene * gainForCell(map, 1, highTableInput) / - (lowScene * gainForCell(map, 1, lowTableInput)) - - assertTrue( - "detailedContrast=$detailedContrast flatContrast=$flatContrast", - detailedContrast > flatContrast * 1.08f - ) - } - - @Test - fun everyTierCompressesToItsDisplayRangeAndUsesHighlightAwareMiddle() { - val cases = listOf( - TierCase(0.10f, 0.15f, 0.40f, 0.60f, 0.75f, 8f, 0.26f), - TierCase(0.020f, 0.10f, 0.50f, 0.75f, 1.05f, 8.5f, 0.28f), - TierCase(0.015f, 0.08f, 0.55f, 0.80f, 1.15f, 9f, 0.30f), - TierCase(0.012f, 0.07f, 0.55f, 0.85f, 1.20f, 9.5f, 0.32f) - ) - cases.forEach { tier -> - val map = buildUniformMap(tier) - val inputScale = map.mapInputWeights.sum() - val sceneWhite = 1f / inputScale - val sourceBlack = max( - (tier.p10 * 0.25f) / 2.0f.pow( - DngPhotonProfileGainTableGenerator.SHADOW_FOOT_HEADROOM_EV - ), - sceneWhite / 2.0f.pow(tier.dynamicRangeEv + 0.75f) + fun tunedGoogleFusionKeepsP50NearLegacyPhotonBrightness() { + val cases = legacyP50Cases() + val results = cases.map { 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, ) - val pgtmBlack = sourceBlack * medianGain( - map, - tableInputForScene(map, inputScale, sourceBlack) - ) - val pgtmMiddle = tier.p50 * medianGain( - map, - tableInputForScene(map, inputScale, tier.p50) - ) - val pgtmWhite = sceneWhite * medianGain(map, 1f) - val finalBlack = samplePhotonProfileCurve(pgtmBlack) - val finalMiddle = samplePhotonProfileCurve(pgtmMiddle) - val finalWhite = samplePhotonProfileCurve(pgtmWhite) - val outputRangeEv = log2(finalWhite / finalBlack) - val highlightRanges = DngPhotonProfileGainTableGenerator.photonHighlightRanges( - p90 = tier.p90, - p98 = tier.p98, - p995 = tier.tailP99 * 0.92f, - p999 = tier.tailP99, - sceneMiddle = tier.p50 - ) - val expectedLift = DngPhotonProfileGainTableGenerator.displayExposureLiftEv( - highlightRanges.exposureRangeEv - ) - val expectedMiddle = (tier.p50 * 2.0f.pow(expectedLift)).coerceIn( - 4f / 2.0f.pow(tier.dynamicRangeEv), - tier.displayMiddleGray - ) - - assertTrue( - "tier=${tier.dynamicRangeEv} outputRangeEv=$outputRangeEv", - outputRangeEv in (tier.dynamicRangeEv - 0.20f)..(tier.dynamicRangeEv + 0.20f) - ) - assertTrue( - "tier=${tier.dynamicRangeEv} finalMiddle=$finalMiddle expectedMiddle=$expectedMiddle", - finalMiddle in (expectedMiddle - 0.015f)..(expectedMiddle + 0.015f) - ) - assertTrue( - "tier=${tier.dynamicRangeEv} p50=${tier.p50} finalMiddle=$finalMiddle", - finalMiddle > tier.p50 + val map = generatePhotonMap(fixture) + val actual = finalPhotonOutputForScene(map, case.p50) + val errorEv = abs(log2(actual / case.legacyDisplayP50)) + LegacyP50Result( + case = case, + actualDisplayP50 = actual, + errorEv = errorEv, ) } + assertTrue( + results.joinToString(separator = "\n") { result -> + "${result.case.name}: expected=${result.case.legacyDisplayP50} " + + "actual=${result.actualDisplayP50} errorEv=${result.errorEv}" + }, + results.all { it.errorEv <= 0.32f }, + ) } @Test - fun extendedHdrShoulderKeepsSeparationNearWhite() { - val tier = TierCase(0.012f, 0.07f, 0.55f, 0.85f, 1.20f, 9.5f, 0.32f) - val map = buildUniformMap(tier) - val inputScale = map.mapInputWeights.sum() - val sceneWhite = 1f / inputScale - val output85 = finalOutputForScene(map, inputScale, sceneWhite * 0.85f) - val output95 = finalOutputForScene(map, inputScale, sceneWhite * 0.95f) - val output100 = finalOutputForScene(map, inputScale, 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 + fun invalidInputStillUsesGoogleValidation() { + assertNull( + DngPhotonProfileGainTableGenerator.forCellStats( + width = 0, + height = 480, + baselineExposureEv = 0f, + packedCellStats = FloatArray(0), + globalStats = testGlobalStats(0.1f), + emitDiagnostics = false, + ) ) } - private fun buildUniformMap(tier: TierCase): DngProfileGainTableMap { - val width = 640 - val height = 480 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - val stats = FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) - repeat(cellCount) { cell -> - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = tier.p10 - stats[offset + 1] = tier.p50 - stats[offset + 2] = tier.p90 - stats[offset + 3] = tier.p98 - stats[offset + 4] = 0.02f - stats[offset + 5] = 64f - stats[offset + 6] = tier.tailP99 * 0.92f - stats[offset + 7] = tier.tailP99 - } + private fun generatePhotonMap(fixture: UniformFixture): DngProfileGainTableMap { return DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = 0f, - packedCellStats = stats, - globalStats = testGlobalStats( - p10 = tier.p10, - p50 = tier.p50, - p90 = tier.p90, - p98 = tier.p98, - p995 = tier.tailP99 * 0.92f, - p999 = tier.tailP99, - maxInput = tier.tailP99, - highlightFraction = 0f, - shadowEdge = tier.p10 * 0.5f, - shadowFoot = tier.p10 * 0.25f - ), - emitDiagnostics = false - ) ?: error("Expected Photon PGTM for tier ${tier.dynamicRangeEv}") + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats, + globalStats = fixture.globalStats, + emitDiagnostics = false, + ) ?: error("Expected Photon PGTM") } - private fun testGlobalStats( + private fun legacyP50Cases(): List = 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), + ) + + private fun uniformFixture( + baselineExposureEv: Float = 0f, p10: Float, p50: Float, p90: Float, p98: Float, p995: Float, p999: Float, - maxInput: Float, + highlightFraction: Float = 0.02f, + ): UniformFixture { + val width = 640 + val height = 480 + val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) + val cellCount = grid[0] * grid[1] + val packedStats = FloatArray( + cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE + ) + repeat(cellCount) { cell -> + val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE + packedStats[offset] = p10 + packedStats[offset + 1] = p50 + packedStats[offset + 2] = p90 + packedStats[offset + 3] = p98 + packedStats[offset + 4] = highlightFraction + packedStats[offset + 5] = 64f + packedStats[offset + 6] = p995 + packedStats[offset + 7] = p999 + } + return UniformFixture( + width = width, + height = height, + baselineExposureEv = baselineExposureEv, + packedStats = packedStats, + globalStats = testGlobalStats( + p50 = p50, + p10 = p10, + p90 = p90, + p98 = p98, + p995 = p995, + p999 = p999, + highlightFraction = highlightFraction, + ), + ) + } + + private fun testGlobalStats( + p50: Float, + p10: Float = p50, + p90: Float = p50, + p98: Float = p90, + p995: Float = p98, + p999: Float = p995, highlightFraction: Float = 0f, - linearMean: Float = p50, - logAverage: Float = p50, - shadowEdge: Float = p10, - shadowFoot: Float = p10, ): DngPgtmGlobalStats { return DngPgtmGlobalStats( p10 = p10, @@ -583,33 +202,23 @@ class DngPhotonProfileGainTableGeneratorTest { p98 = p98, p995 = p995, p999 = p999, - maxInput = maxInput, + maxInput = p999, highlightFraction = highlightFraction, - linearMean = linearMean, - logAverage = logAverage, - shadowEdge = shadowEdge, - shadowFoot = shadowFoot, - sampleCount = 256 + linearMean = p50, + logAverage = p50, + shadowEdge = p10, + shadowFoot = p10, + sampleCount = 256, ) } - private fun tableInputForScene( + private fun finalPhotonOutputForScene( map: DngProfileGainTableMap, - inputScale: Float, sceneLinear: Float, ): Float { - return (sceneLinear * inputScale).coerceIn(0f, 1f).pow(map.gamma) - } - - private fun finalOutputForScene( - map: DngProfileGainTableMap, - inputScale: Float, - sceneLinear: Float, - ): Float { - val pgtmOutput = sceneLinear * medianGain( - map, - tableInputForScene(map, inputScale, sceneLinear) - ) + val inputScale = map.mapInputWeights.sum() + val tableInput = (sceneLinear * inputScale).coerceIn(0f, 1f).pow(map.gamma) + val pgtmOutput = sceneLinear * medianGain(map, tableInput) return samplePhotonProfileCurve(pgtmOutput) } @@ -622,14 +231,32 @@ class DngPhotonProfileGainTableGeneratorTest { val x1 = points[index + 2] val y1 = points[index + 3] if (input <= x1) { - val t = ((input - x0) / (x1 - x0)).coerceIn(0f, 1f) - return y0 + (y1 - y0) * t + val amount = ((input - x0) / (x1 - x0)).coerceIn(0f, 1f) + return y0 + (y1 - y0) * amount } index += 2 } return points.last() } + private fun medianGain(map: DngProfileGainTableMap, tableInput: Float): Float { + val values = FloatArray(map.mapPointsH * map.mapPointsV) { cell -> + gainForCell(map, cell, tableInput) + } + values.sort() + return values[values.size / 2] + } + + private fun gainForCell(map: DngProfileGainTableMap, cell: Int, tableInput: Float): Float { + val position = tableInput.coerceIn(0f, 1f) * map.mapPointsN + val lower = floor(position).toInt().coerceIn(0, map.mapPointsN - 1) + val upper = (lower + 1).coerceAtMost(map.mapPointsN - 1) + val fraction = position - lower + val offset = cell * map.mapPointsN + return map.gains[offset + lower] * (1f - fraction) + + map.gains[offset + upper] * fraction + } + private fun assertCurvesAreFiniteAndMonotonic( map: DngProfileGainTableMap, sceneWhite: Float, @@ -645,83 +272,29 @@ class DngPhotonProfileGainTableGeneratorTest { val sceneLinear = sceneWhite * tableInput.pow(1f / map.gamma) val gain = map.gains[cell * map.mapPointsN + index] val output = sceneLinear * gain - assertTrue("cell=$cell index=$index gain=$gain", gain.isFinite() && gain in 0.05f..32f) + assertTrue("cell=$cell index=$index gain=$gain", gain.isFinite() && gain >= 0.05f) assertTrue( "cell=$cell index=$index previous=$previousOutput output=$output", - output + 1e-5f >= previousOutput + output + 1e-5f >= previousOutput, ) - previousOutput = output + previousOutput = max(previousOutput, output) } } } - private fun medianGain(map: DngProfileGainTableMap, tableInput: Float): Float { - val values = FloatArray(map.mapPointsH * map.mapPointsV) { cell -> - gainForCell(map, cell, tableInput) - } - values.sort() - return values[values.size / 2] - } - - private fun gainForCell(map: DngProfileGainTableMap, cell: Int, tableInput: Float): Float { - val position = tableInput.coerceIn(0f, 1f) * map.mapPointsN - val i0 = floor(position).toInt().coerceIn(0, map.mapPointsN - 1) - val i1 = (i0 + 1).coerceAtMost(map.mapPointsN - 1) - val fraction = position - i0 - val offset = cell * map.mapPointsN - return map.gains[offset + i0] * (1f - fraction) + - map.gains[offset + i1] * fraction - } - private fun log2(value: Float): Float { return (ln(value.toDouble()) / ln(2.0)).toFloat() } - private fun assertFieldCalibrationCases(cases: List) { - cases.forEach { case -> - val calculatedLegacyRangeEv = log2( - max(case.p999, max(case.p995, case.p98)) / - max(case.p10, 0.002f) - ) - val logAverage = case.logAverage - ?: error("${case.name}: logAverage is required by the highlight-range model") - val calculatedHighlightRangeEv = log2( - max(case.p999, logAverage) / logAverage - ) - val actualExposureLiftEv = - DngPhotonProfileGainTableGenerator.displayExposureLiftEv(calculatedHighlightRangeEv) - val expectedExposureLiftEv = - case.reportedExposureLiftEv - case.reportedBrightnessErrorEv - val residualEv = actualExposureLiftEv - expectedExposureLiftEv - - assertTrue( - "${case.name}: legacyObserved=$calculatedLegacyRangeEv " + - "reported=${case.reportedObservedRangeEv}", - kotlin.math.abs( - calculatedLegacyRangeEv - case.reportedObservedRangeEv - ) <= 0.002f - ) - assertTrue( - "${case.name}: highlightRange=$calculatedHighlightRangeEv " + - "actualLift=$actualExposureLiftEv " + - "expectedLift=$expectedExposureLiftEv residual=$residualEv", - residualEv in -0.12f..0.12f - ) - } - } - - private data class TierCase( - val p10: Float, - val p50: Float, - val p90: Float, - val p98: Float, - val tailP99: Float, - val dynamicRangeEv: Float, - val displayMiddleGray: Float, + private data class UniformFixture( + val width: Int, + val height: Int, + val baselineExposureEv: Float, + val packedStats: FloatArray, + val globalStats: DngPgtmGlobalStats, ) - @Suppress("unused") - private data class ExposureCalibrationCase( + private data class LegacyP50Case( val name: String, val baselineExposureEv: Float, val p10: Float, @@ -730,12 +303,14 @@ class DngPhotonProfileGainTableGeneratorTest { val p98: Float, val p995: Float, val p999: Float, - val maxInput: Float, - val linearMean: Float?, - val logAverage: Float?, val highlightFraction: Float, - val reportedObservedRangeEv: Float, - val reportedExposureLiftEv: Float, - val reportedBrightnessErrorEv: Float, + val legacyDisplayP50: Float, ) + + private data class LegacyP50Result( + val case: LegacyP50Case, + val actualDisplayP50: Float, + val errorEv: Float, + ) + }