From 415daccdbd9bd0c1cf9f84d2a016e37babaf67df Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Wed, 15 Jul 2026 18:06:45 +0800 Subject: [PATCH] feat: new google pgtm generator --- .gitignore | 3 +- .../mycamera/raw/DngHdrLtmSpatialModel.kt | 245 +++ .../mycamera/raw/DngHdrPgtmLocalToneModel.kt | 310 ---- .../raw/DngHdrProfileGainTableGenerator.kt | 1328 +++++------------ .../mycamera/raw/RawDemosaicProcessor.kt | 2 +- .../DngHdrProfileGainTableGeneratorTest.kt | 1060 ++++--------- scripts/extract_pgtm_regression_fixture.py | 95 +- scripts/fit_ltm_pgtm.py | 439 ++++++ 8 files changed, 1436 insertions(+), 2046 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/DngHdrPgtmLocalToneModel.kt create mode 100644 scripts/fit_ltm_pgtm.py diff --git a/.gitignore b/.gitignore index 9b7ec8b5..4ecefdcf 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,5 @@ app/release.jks /AGC /agc-photon-lut /third_party -__pycache__ \ No newline at end of file +__pycache__ +/app/src/test/resources/pgtm/ diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt new file mode 100644 index 00000000..e30ef293 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrLtmSpatialModel.kt @@ -0,0 +1,245 @@ +package com.hinnka.mycamera.raw + +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.pow +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. + */ +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( + cells: Array, + grid: HdrPgtmGrid, + global: HdrPgtmCellStats, + globalPlan: HdrLtmExposurePlan, + ): Array { + val globalFeature = ToneFeature.from(global) + val features = Array(cells.size) { index -> + cells[index]?.takeIf { it.sampleWeight > 0f }?.let(ToneFeature::from) ?: globalFeature + } + val neighborhoods = smoothFeatures(features, grid) + // The global exposure plan represents a robust scene median. Center local residuals on + // the same statistic; + // a feature built from arithmetic-mean percentiles is biased in strongly bimodal scenes. + val referenceFeature = medianFeature(neighborhoods) + val saturatedScene = smoothStep(0.55f, 0.72f, global.highlightFraction) * + smoothStep(0.70f, 0.84f, global.p50) + val sparseSeparatedTail = + (1f - smoothStep(0.21f, 0.24f, global.p98)) * + (1f - smoothStep(1.15f, 1.45f, global.inputTailP95)) * + smoothStep( + 0.75f, + 1.20f, + log2((global.inputTailP99 + TAIL_EPS) / (global.inputTailP95 + TAIL_EPS)) + ) + val residualScale = 1f + 1.50f * saturatedScene + 1.00f * sparseSeparatedTail + return Array(cells.size) { index -> + val cell = cells[index] + if (cell == null || cell.sampleWeight <= 0f) { + globalPlan + } else { + planLocalExposureRange( + globalPlan = globalPlan, + referenceFeature = referenceFeature, + localFeature = neighborhoods[index], + sampleWeight = cell.sampleWeight, + residualScale = residualScale + ) + } + } + } + + private fun planLocalExposureRange( + globalPlan: HdrLtmExposurePlan, + referenceFeature: ToneFeature, + localFeature: ToneFeature, + sampleWeight: Float, + residualScale: Float, + ): HdrLtmExposurePlan { + val residualEv = + 0.0070524f * (localFeature.logP10 - referenceFeature.logP10) + + 0.0018840f * (localFeature.logP50 - referenceFeature.logP50) - + 0.1109007f * (localFeature.logP90 - referenceFeature.logP90) + + 0.0874353f * (localFeature.logP98 - referenceFeature.logP98) - + 0.0166212f * (localFeature.fullRangeEv - referenceFeature.fullRangeEv) - + 0.0036315f * (localFeature.upperRangeEv - referenceFeature.upperRangeEv) - + 0.2828567f * (localFeature.sqrtHighlightFraction - referenceFeature.sqrtHighlightFraction) + + 0.0116745f * (localFeature.tail995Ev - referenceFeature.tail995Ev) - + 0.1805684f * (localFeature.tail999Ev - referenceFeature.tail999Ev) + 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, MAX_LTM_GAIN) + ) + } + + private fun medianFeature(source: Array): ToneFeature { + fun median(selector: (ToneFeature) -> Float): Float { + val values = FloatArray(source.size) { selector(source[it]) } + values.sort() + val center = values.size / 2 + return if (values.size % 2 == 0) { + 0.5f * (values[center - 1] + values[center]) + } else { + values[center] + } + } + return ToneFeature( + logP10 = median { it.logP10 }, + logP50 = median { it.logP50 }, + logP90 = median { it.logP90 }, + logP98 = median { it.logP98 }, + fullRangeEv = median { it.fullRangeEv }, + upperRangeEv = median { it.upperRangeEv }, + sqrtHighlightFraction = median { it.sqrtHighlightFraction }, + tail995Ev = median { it.tail995Ev }, + tail999Ev = median { it.tail999Ev } + ) + } + + private fun smoothFeatures( + source: Array, + grid: HdrPgtmGrid, + ): Array { + return Array(source.size) { index -> + val x = index % grid.mapPointsH + val y = index / grid.mapPointsH + var weightSum = 0f + var logP10 = 0f + var logP50 = 0f + var logP90 = 0f + var logP98 = 0f + var fullRangeEv = 0f + var upperRangeEv = 0f + var sqrtHighlightFraction = 0f + var tail995Ev = 0f + var tail999Ev = 0f + forEachNeighbor(x, y, grid) { neighbor, weight -> + val feature = source[neighbor] + weightSum += weight + logP10 += feature.logP10 * weight + logP50 += feature.logP50 * weight + logP90 += feature.logP90 * weight + logP98 += feature.logP98 * weight + fullRangeEv += feature.fullRangeEv * weight + upperRangeEv += feature.upperRangeEv * weight + sqrtHighlightFraction += feature.sqrtHighlightFraction * weight + tail995Ev += feature.tail995Ev * weight + tail999Ev += feature.tail999Ev * weight + } + ToneFeature( + logP10 = logP10 / weightSum, + logP50 = logP50 / weightSum, + logP90 = logP90 / weightSum, + logP98 = logP98 / weightSum, + fullRangeEv = fullRangeEv / weightSum, + upperRangeEv = upperRangeEv / weightSum, + sqrtHighlightFraction = sqrtHighlightFraction / weightSum, + tail995Ev = tail995Ev / weightSum, + tail999Ev = tail999Ev / weightSum + ) + } + } + + private inline fun forEachNeighbor( + x: Int, + y: Int, + grid: HdrPgtmGrid, + block: (index: Int, weight: Float) -> Unit, + ) { + for (dy in -1..1) { + val yy = (y + dy).coerceIn(0, grid.mapPointsV - 1) + for (dx in -1..1) { + val xx = (x + dx).coerceIn(0, grid.mapPointsH - 1) + val weight = when { + dx == 0 && dy == 0 -> 4f + dx == 0 || dy == 0 -> 2f + else -> 1f + } + block(yy * grid.mapPointsH + xx, weight) + } + } + } + + private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float { + val t = ((value - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f) + return t * t * (3f - 2f * t) + } + + private fun log2(value: Float): Float { + return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat() + } + + private data class ToneFeature( + val logP10: Float, + val logP50: Float, + val logP90: Float, + val logP98: Float, + val fullRangeEv: Float, + val upperRangeEv: Float, + val sqrtHighlightFraction: Float, + val tail995Ev: Float, + val tail999Ev: Float, + ) { + companion object { + fun from(stats: HdrPgtmCellStats): ToneFeature { + val logP10 = log2(stats.p10 + LEVEL_EPS) + val logP50 = log2(stats.p50 + LEVEL_EPS) + val logP90 = log2(stats.p90 + LEVEL_EPS) + val logP98 = log2(stats.p98 + LEVEL_EPS) + return ToneFeature( + logP10 = logP10, + logP50 = logP50, + logP90 = logP90, + logP98 = logP98, + fullRangeEv = logP98 - logP10, + upperRangeEv = logP98 - logP50, + sqrtHighlightFraction = sqrt(stats.highlightFraction.coerceIn(0f, 1f)), + tail995Ev = log2((stats.p995Input + TAIL_EPS) / (stats.p98 + TAIL_EPS)), + tail999Ev = log2((stats.p999Input + TAIL_EPS) / (stats.p995Input + TAIL_EPS)) + ) + } + } + } +} + +internal data class HdrPgtmGrid( + val mapPointsH: Int, + val mapPointsV: Int, + val mapSpacingH: Double, + val mapSpacingV: Double, +) + +internal data class HdrPgtmCellStats( + val p10: Float, + val p50: Float, + val p90: Float, + val p98: Float, + val highlightFraction: Float, + val p995Input: Float, + val p999Input: Float, + val inputTailP95: Float, + val inputTailP98: Float, + val inputTailP99: Float, + val maxInput: Float, + val sampleWeight: Float, +) + +internal data class HdrLtmExposurePlan( + val brightestExposureGain: Float, + val darkestExposureGain: Float, +) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrPgtmLocalToneModel.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrPgtmLocalToneModel.kt deleted file mode 100644 index a7be3fc5..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrPgtmLocalToneModel.kt +++ /dev/null @@ -1,310 +0,0 @@ -package com.hinnka.mycamera.raw - -import kotlin.math.abs -import kotlin.math.ln -import kotlin.math.max -import kotlin.math.min - -internal object DngHdrPgtmLocalToneModel { - private const val LOCAL_CURVE_MAX_BLEND = 0.90f - private const val LOCAL_CURVE_SMOOTH_PASSES = 1 - private const val FEATURE_EPS = 0.006f - private const val TAIL_EPS = 0.04f - - private val TONE_DISTANCE_WEIGHTS = floatArrayOf( - 0.34f, - 0.32f, - 0.20f, - 0.18f, - 0.70f - ) - - fun buildSpatialCurveParams( - cells: Array, - grid: HdrPgtmGrid, - global: HdrPgtmCellStats, - globalCurveParams: HdrPgtmCurveParams, - cellCurveParams: (HdrPgtmCellStats) -> HdrPgtmCurveParams, - ): Array { - val globalFeature = ToneFeature.from(global) - val splatFeatures = splatToneFeatures(cells, globalFeature) - val localFeatures = localToneFeatures(splatFeatures, grid) - val cellCount = grid.mapPointsH * grid.mapPointsV - val predicted = Array(cellCount) { index -> - val cell = cells.getOrNull(index) - if (cell == null || cell.sampleWeight <= 0f) { - globalCurveParams - } else { - val blend = predictResidualBlend( - cell = cell, - global = global, - splatFeature = splatFeatures[index], - localFeature = localFeatures[index], - globalFeature = globalFeature - ) - blendCurveParams( - first = globalCurveParams, - second = cellCurveParams(cell), - amount = blend - ) - } - } - return smoothSpatialCurveParams(predicted, grid) - } - - private fun splatToneFeatures( - cells: Array, - fallback: ToneFeature, - ): Array { - return Array(cells.size) { index -> - val cell = cells[index] - if (cell != null && cell.sampleWeight > 0f) { - ToneFeature.from(cell) - } else { - fallback - } - } - } - - private fun localToneFeatures( - source: Array, - grid: HdrPgtmGrid, - ): Array { - return Array(source.size) { index -> - val x = index % grid.mapPointsH - val y = index / grid.mapPointsH - var weightSum = 0f - var fullRangeEv = 0f - var upperRangeEv = 0f - var midRangeEv = 0f - var tailRangeEv = 0f - var highlightFraction = 0f - for (dy in -1..1) { - val yy = y + dy - if (yy !in 0 until grid.mapPointsV) continue - for (dx in -1..1) { - val xx = x + dx - if (xx !in 0 until grid.mapPointsH) continue - val weight = when { - dx == 0 && dy == 0 -> 4f - dx == 0 || dy == 0 -> 2f - else -> 1f - } - val feature = source[yy * grid.mapPointsH + xx] - weightSum += weight - fullRangeEv += feature.fullRangeEv * weight - upperRangeEv += feature.upperRangeEv * weight - midRangeEv += feature.midRangeEv * weight - tailRangeEv += feature.tailRangeEv * weight - highlightFraction += feature.highlightFraction * weight - } - } - ToneFeature( - fullRangeEv = fullRangeEv / weightSum, - upperRangeEv = upperRangeEv / weightSum, - midRangeEv = midRangeEv / weightSum, - tailRangeEv = tailRangeEv / weightSum, - highlightFraction = highlightFraction / weightSum - ) - } - } - - private fun predictResidualBlend( - cell: HdrPgtmCellStats, - global: HdrPgtmCellStats, - splatFeature: ToneFeature, - localFeature: ToneFeature, - globalFeature: ToneFeature, - ): Float { - val fusedFeature = ToneFeature.fuse( - splatFeature = splatFeature, - localFeature = localFeature - ) - val toneDelta = weightedToneDistance(fusedFeature, globalFeature) - val variation = smoothStep(0.08f, 0.70f, toneDelta) - val confidence = smoothStep(24f, 96f, cell.sampleWeight) - val darkerThanGlobal = 1f - smoothStep( - 0.70f, - 1.06f, - (cell.p98 + FEATURE_EPS) / max(global.p98 + FEATURE_EPS, FEATURE_EPS) - ) - val quietDarkCell = darkerThanGlobal * (1f - smoothStep(0.015f, 0.10f, cell.highlightFraction)) - val localLiftDamping = lerp(1f, 1.45f, quietDarkCell) - val saturatedCellDamping = lerp(1f, 0.00f, smoothStep(0.96f, 1.0f, cell.p98)) - return (LOCAL_CURVE_MAX_BLEND * variation * confidence * localLiftDamping * saturatedCellDamping) - .coerceIn(0f, LOCAL_CURVE_MAX_BLEND) - } - - private fun weightedToneDistance(first: ToneFeature, second: ToneFeature): Float { - val deltas = floatArrayOf( - abs(first.fullRangeEv - second.fullRangeEv), - abs(first.upperRangeEv - second.upperRangeEv), - abs(first.midRangeEv - second.midRangeEv), - abs(first.tailRangeEv - second.tailRangeEv), - abs(first.highlightFraction - second.highlightFraction) - ) - var distance = 0f - for (index in deltas.indices) { - distance += deltas[index] * TONE_DISTANCE_WEIGHTS[index] - } - return distance - } - - private fun smoothSpatialCurveParams( - source: Array, - grid: HdrPgtmGrid, - ): Array { - var current = source - repeat(LOCAL_CURVE_SMOOTH_PASSES) { - current = Array(current.size) { index -> - val x = index % grid.mapPointsH - val y = index / grid.mapPointsH - var weightSum = 0f - var midOutput = 0f - var blackGain = 0f - var toeSlope = 0f - var shoulderPower = 0f - var highlightPressure = 0f - var lowDetailGainFactor = 0f - var lowRangeStart = 0f - var lowRangeEnd = 0f - var lowRangeRetention = 0f - for (dy in -1..1) { - val yy = y + dy - if (yy !in 0 until grid.mapPointsV) continue - for (dx in -1..1) { - val xx = x + dx - if (xx !in 0 until grid.mapPointsH) continue - val weight = when { - dx == 0 && dy == 0 -> 4f - dx == 0 || dy == 0 -> 2f - else -> 1f - } - val params = current[yy * grid.mapPointsH + xx] - weightSum += weight - midOutput += params.midOutput * weight - blackGain += params.blackGain * weight - toeSlope += params.toeSlope * weight - shoulderPower += params.shoulderPower * weight - highlightPressure += params.highlightPressure * weight - lowDetailGainFactor += params.lowDetailGainFactor * weight - lowRangeStart += params.lowRangeStart * weight - lowRangeEnd += params.lowRangeEnd * weight - lowRangeRetention += params.lowRangeRetention * weight - } - } - HdrPgtmCurveParams( - midOutput = midOutput / weightSum, - blackGain = blackGain / weightSum, - toeSlope = toeSlope / weightSum, - shoulderPower = shoulderPower / weightSum, - highlightPressure = highlightPressure / weightSum, - lowDetailGainFactor = lowDetailGainFactor / weightSum, - lowRangeStart = lowRangeStart / weightSum, - lowRangeEnd = lowRangeEnd / weightSum, - lowRangeRetention = lowRangeRetention / weightSum - ) - } - } - return current - } - - private fun blendCurveParams( - first: HdrPgtmCurveParams, - second: HdrPgtmCurveParams, - amount: Float, - ): HdrPgtmCurveParams { - val t = amount.coerceIn(0f, 1f) - return HdrPgtmCurveParams( - midOutput = lerp(first.midOutput, second.midOutput, t), - blackGain = lerp(first.blackGain, second.blackGain, t), - toeSlope = lerp(first.toeSlope, second.toeSlope, t), - shoulderPower = lerp(first.shoulderPower, second.shoulderPower, t), - highlightPressure = lerp(first.highlightPressure, second.highlightPressure, t), - lowDetailGainFactor = lerp(first.lowDetailGainFactor, second.lowDetailGainFactor, t), - lowRangeStart = lerp(first.lowRangeStart, second.lowRangeStart, t), - lowRangeEnd = lerp(first.lowRangeEnd, second.lowRangeEnd, t), - lowRangeRetention = lerp(first.lowRangeRetention, second.lowRangeRetention, t) - ) - } - - private fun lerp(a: Float, b: Float, t: Float): Float { - return a + (b - a) * min(max(t, 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 log2(value: Float): Float { - return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat() - } - - private data class ToneFeature( - val fullRangeEv: Float, - val upperRangeEv: Float, - val midRangeEv: Float, - val tailRangeEv: Float, - val highlightFraction: Float, - ) { - companion object { - fun from(stats: HdrPgtmCellStats): ToneFeature { - return ToneFeature( - fullRangeEv = log2((stats.p98 + FEATURE_EPS) / (stats.p10 + FEATURE_EPS)), - upperRangeEv = log2((stats.p98 + FEATURE_EPS) / (stats.p50 + FEATURE_EPS)), - midRangeEv = log2((stats.p90 + FEATURE_EPS) / (stats.p50 + FEATURE_EPS)), - tailRangeEv = log2((stats.p999Input + TAIL_EPS) / (stats.p98 + TAIL_EPS)), - highlightFraction = stats.highlightFraction - ) - } - - fun fuse( - splatFeature: ToneFeature, - localFeature: ToneFeature, - ): ToneFeature { - return ToneFeature( - fullRangeEv = splatFeature.fullRangeEv, - upperRangeEv = splatFeature.upperRangeEv, - midRangeEv = splatFeature.midRangeEv, - tailRangeEv = splatFeature.tailRangeEv, - highlightFraction = localFeature.highlightFraction - ) - } - } - } -} - -internal data class HdrPgtmGrid( - val mapPointsH: Int, - val mapPointsV: Int, - val mapSpacingH: Double, - val mapSpacingV: Double, -) - -internal data class HdrPgtmCellStats( - val p10: Float, - val p50: Float, - val p90: Float, - val p98: Float, - val highlightFraction: Float, - val p995Input: Float, - val p999Input: Float, - val inputTailP95: Float, - val inputTailP98: Float, - val inputTailP99: Float, - val maxInput: Float, - val sampleWeight: Float, -) - -internal data class HdrPgtmCurveParams( - val midOutput: Float, - val blackGain: Float, - val toeSlope: Float, - val shoulderPower: Float, - val highlightPressure: Float, - val lowDetailGainFactor: Float, - val lowRangeStart: Float, - val lowRangeEnd: Float, - val lowRangeRetention: Float, -) 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 6c5ba01b..7a050ff0 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt @@ -1,23 +1,31 @@ package com.hinnka.mycamera.raw import com.hinnka.mycamera.utils.PLog +import kotlin.math.abs +import kotlin.math.exp import kotlin.math.ln import kotlin.math.max import kotlin.math.min import kotlin.math.pow -import kotlin.math.sqrt +import kotlin.math.roundToInt +/** + * Builds a DNG profile gain table from the same three stages used by Google's LTM pipeline: + * + * 1. estimate the scene-white range from BaselineExposure and robust spatial tail statistics; + * 2. plan the local synthetic-exposure range for every map cell; + * 3. render and fuse eight synthetic exposures into the gain curve. + * + * The generated table contains the complete display transform. In particular, gains below one + * near the table's white end are intentional: they compress scene-linear highlight headroom into + * the profile output range. + */ internal object DngHdrProfileGainTableGenerator { private const val TAG = "DngHdrProfileGainTableGenerator" const val CELL_STATS_FLOAT_STRIDE = 8 private const val MAP_INPUT_WEIGHT_COUNT = 5 - private const val GCAM_HDR_LOWER_RANGE_EV = -1f - private const val GCAM_HDR_UPPER_RANGE_EV = 8.5f - private const val GCAM_HDR_EFFECT_INTENSITY = 1f - private const val MIN_BASELINE_EV = 0f - private const val MAX_BASELINE_EV = 8f private const val DEFAULT_TABLE_POINTS = 257 private const val MIN_TABLE_POINTS = 257 private const val MAX_TABLE_POINTS = 257 @@ -26,73 +34,26 @@ internal object DngHdrProfileGainTableGenerator { private const val GRID_MIN_V = 6 private const val GRID_MAX_H = 64 private const val GRID_MAX_V = 48 - private const val MIN_SCENE_MAX = 1.06f - private const val MAX_SCENE_MAX = 4.80f - private const val SCENE_BASE_TAIL_FACTOR = 1.12f - private const val SCENE_TAIL_EXPANSION_FACTOR = 2.75f - private const val SCENE_TAIL_MAX_INPUT_FACTOR = 1.2f - private const val SCENE_TAIL_HDR_STRENGTH = 0.58f - private const val SCENE_TAIL_EXPANSION_STRENGTH_GAIN = 2.10f - private const val SCENE_TAIL_MAX_GAP_START_EV = 0.18f - private const val SCENE_TAIL_MAX_GAP_FULL_EV = 0.62f - private const val SCENE_DENSE_HIGHLIGHT_EXPANSION_START = 0.18f - private const val SCENE_DENSE_HIGHLIGHT_EXPANSION_FULL = 0.24f - private const val SCENE_DENSE_HIGHLIGHT_START = 0.13f - private const val SCENE_DENSE_HIGHLIGHT_FULL = 0.17f - private const val LOW_DETAIL_SPARSE_HIGHLIGHT_START = 0.018f - private const val LOW_DETAIL_SPARSE_HIGHLIGHT_END = 0.055f - private const val LOW_DETAIL_MODERATE_HIGHLIGHT_START = 0.040f - private const val LOW_DETAIL_MODERATE_HIGHLIGHT_FULL = 0.055f - private const val LOW_DETAIL_MODERATE_HIGHLIGHT_END = 0.140f - private const val LOW_DETAIL_FLAT_UPPER_START = 0.40f - private const val LOW_DETAIL_FLAT_UPPER_END = 0.50f - private const val LOW_RANGE_DENSE_TAIL_START = 0.075f - private const val LOW_RANGE_DENSE_TAIL_END = 0.145f - private const val LOW_RANGE_HIGHLIGHT_TAIL_START = 0.030f - private const val LOW_RANGE_HIGHLIGHT_TAIL_END = 0.065f - private const val LOW_RANGE_COMPACT_TAIL_END_BOOST = 0.03f - private const val LOW_TABLE_PLATEAU_END = 0.020f - private const val LOW_TABLE_PLATEAU_FEATHER_END = 0.032f - private const val MAX_GAIN_VALUE = 5.40f - private const val MIN_CURVE_INPUT = 1e-6f - private const val SCENE_ULTRA_BLACK_ANCHOR = 0.0025f - private const val SCENE_BLACK_DETAIL_ANCHOR = 0.005f - private const val SCENE_DARK_DETAIL_ANCHOR = 0.0075f - private const val SCENE_DEEP_SHADOW_ANCHOR = 0.010f - private const val SCENE_DEEP_SHADOW_DETAIL_ANCHOR = 0.015f - private const val SCENE_SHADOW_ANCHOR = 0.02f - private const val SCENE_SHADOW_DETAIL_ANCHOR = 0.0275f - private const val SCENE_LOWER_SHADOW_ANCHOR = 0.035f - private const val SCENE_LOWER_LOW_ANCHOR = 0.045f - private const val SCENE_LOW_ANCHOR = 0.05f - private const val SCENE_LOW_DETAIL_ANCHOR = 0.0575f - private const val SCENE_UPPER_SHADOW_ANCHOR = 0.065f - private const val SCENE_PRE_TOE_ANCHOR = 0.0725f - private const val SCENE_TOE_ANCHOR = 0.08f - private const val SCENE_UPPER_TOE_ANCHOR = 0.095f - private const val SCENE_TOE_MID_JOIN_ANCHOR = 0.105f - private const val SCENE_LOWER_MID_ANCHOR = 0.11f - private const val SCENE_MID_ANCHOR = 0.18f - private const val SCENE_UPPER_MID_ANCHOR = 0.25f - private const val SCENE_HALF_ANCHOR = 0.50f - private const val SCENE_WHITE_ANCHOR = 1.0f - private const val SCENE_BRIGHT_ANCHOR = 1.5f - private const val SCENE_SUPER_WHITE_ANCHOR = 2.0f - private const val SCENE_EXTREME_WHITE_ANCHOR = 3.0f - private const val MIN_MID_GAIN = 1.40f - private const val MAX_MID_GAIN = 2.75f - private const val LOW_DETAIL_MID_GAIN_FACTOR = 1.56f - private const val MIN_BLACK_GAIN = 1.00f - private const val MAX_BLACK_GAIN = 5.40f - private const val MIN_TOE_SLOPE = 0.58f - private const val MAX_TOE_SLOPE = 0.88f - private const val MIN_SHOULDER_POWER = 0.82f - private const val MAX_SHOULDER_POWER = 1.28f + + // Google logs describe LTM as an eight-synthetic-exposure operation. + private const val SYNTHETIC_EXPOSURE_COUNT = 8 + private const val MAX_SCENE_WHITE = 64f + private const val MAX_LTM_GAIN = 6.18f + 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 WELL_EXPOSED_SIGMA_EV = 0.750f + private const val EXPOSURE_PLAN_STEPS_PER_EV = 128f + 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 + internal const val BASE_INPUT_WEIGHT_RED = 0.1495f internal const val BASE_INPUT_WEIGHT_GREEN = 0.2935f internal const val BASE_INPUT_WEIGHT_BLUE = 0.0570f internal const val BASE_INPUT_WEIGHT_MIN = 0.1250f internal const val BASE_INPUT_WEIGHT_MAX = 0.3750f + private val BASE_INPUT_WEIGHTS = floatArrayOf( BASE_INPUT_WEIGHT_RED, BASE_INPUT_WEIGHT_GREEN, @@ -100,9 +61,15 @@ internal object DngHdrProfileGainTableGenerator { BASE_INPUT_WEIGHT_MIN, BASE_INPUT_WEIGHT_MAX ) + private val WELL_EXPOSED_WEIGHT_LUT = FloatArray( + (WEIGHT_LUT_MAX_DISTANCE_EV * WEIGHT_LUT_STEPS_PER_EV).toInt() + 1 + ) { index -> + val distanceEv = index.toFloat() / WEIGHT_LUT_STEPS_PER_EV + exp((-0.5f * (distanceEv / WELL_EXPOSED_SIGMA_EV).pow(2f)).toDouble()).toFloat() + } fun gridSizeFor(width: Int, height: Int): IntArray { - val grid = chooseHdrPgtmGrid(width, height) + val grid = chooseLtmGrid(width, height) return intArrayOf(grid.mapPointsH, grid.mapPointsV) } @@ -159,80 +126,49 @@ internal object DngHdrProfileGainTableGenerator { tablePointCount: Int = DEFAULT_TABLE_POINTS, diagnosticBand: DiagnosticBand? = null, ): DngProfileGainTableMap? { - if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < MIN_BASELINE_EV) { + if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < 0f) { return null } - val grid = chooseHdrPgtmGrid(width, height) + val grid = chooseLtmGrid(width, height) val cellCount = grid.mapPointsH * grid.mapPointsV - if (packedCellStats.size < cellCount * CELL_STATS_FLOAT_STRIDE) { - PLog.w( - TAG, - "GPU PGTM stats too small: ${packedCellStats.size}, expected=${cellCount * CELL_STATS_FLOAT_STRIDE}" - ) + val requiredStats = cellCount * CELL_STATS_FLOAT_STRIDE + if (packedCellStats.size < requiredStats) { + PLog.w(TAG, "GPU LTM stats too small: ${packedCellStats.size}, expected=$requiredStats") return null } - val safeBaselineEv = baselineExposureEv.coerceIn(0f, MAX_BASELINE_EV) - val safePointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS) + val cells = Array(cellCount) { index -> val offset = index * CELL_STATS_FLOAT_STRIDE - val sampleWeight = packedCellStats[offset + 5].takeIf { it.isFinite() && it > 0f } ?: 0f - if (sampleWeight <= 0f) { - null - } else { + val sampleWeight = packedCellStats[offset + 5] + .takeIf { it.isFinite() && it > 0f } + ?: 0f + if (sampleWeight > 0f) { packedStatsAt(packedCellStats, offset, sampleWeight) + } else { + null } } val globalStats = weightedGlobalStats(cells) - val inputScale = hdrPgtmInputScaleForStats(globalStats) - val sceneMax = 1f / sanitizeInputScale(inputScale) - val sceneHdrStrength = (sceneHdrStrength(globalStats, inputScale) * GCAM_HDR_EFFECT_INTENSITY) - .coerceIn(0f, 1f) - val globalCurveParams = buildHdrPgtmCurveParams( - global = globalStats, - sceneHdrStrength = sceneHdrStrength, - sceneMax = sceneMax + val inputScale = estimateInputScale(globalStats, baselineExposureEv) + val globalPlan = buildGlobalExposurePlan( + stats = globalStats, + inputScale = inputScale ) - val curveParams = buildSpatialCurveParams( + val cellPlans = DngHdrLtmSpatialModel.buildExposurePlans( cells = cells, grid = grid, global = globalStats, - globalCurveParams = globalCurveParams, - sceneHdrStrength = sceneHdrStrength, - sceneMax = sceneMax + globalPlan = globalPlan ) return buildMap( grid = grid, - safeBaselineEv = safeBaselineEv, - safePointCount = safePointCount, - curveParams = curveParams, + pointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS), inputScale = inputScale, + cellPlans = cellPlans, diagnosticBand = diagnosticBand?.sanitized() ) } - private fun buildSpatialCurveParams( - cells: Array, - grid: HdrPgtmGrid, - global: HdrPgtmCellStats, - globalCurveParams: HdrPgtmCurveParams, - sceneHdrStrength: Float, - sceneMax: Float, - ): Array { - return DngHdrPgtmLocalToneModel.buildSpatialCurveParams( - cells = cells, - grid = grid, - global = global, - globalCurveParams = globalCurveParams - ) { cell -> - buildHdrPgtmCurveParams( - global = cell, - sceneStats = global, - sceneHdrStrength = sceneHdrStrength, - sceneMax = sceneMax - ) - } - } - data class DiagnosticBand( val start: Float, val end: Float, @@ -267,15 +203,14 @@ internal object DngHdrProfileGainTableGenerator { val gains = map.gains.copyOf() val pointCount = map.mapPointsN val cellCount = map.mapPointsH * map.mapPointsV - val maxGain = gains - .maxOrNull() + val maxGain = gains.maxOrNull() ?.takeIf { it.isFinite() && it > 0f } - ?.coerceAtLeast(MAX_GAIN_VALUE) - ?: MAX_GAIN_VALUE - for (cellIndex in 0 until cellCount) { + ?.coerceAtLeast(MAX_LTM_GAIN) + ?: MAX_LTM_GAIN + for (cell in 0 until cellCount) { applyDiagnosticBand( output = gains, - outputOffset = cellIndex * pointCount, + outputOffset = cell * pointCount, pointCount = pointCount, band = band, maxGainValue = maxGain @@ -284,7 +219,11 @@ internal object DngHdrProfileGainTableGenerator { return map.copy(gains = gains) } - private fun packedStatsAt(stats: FloatArray, offset: Int, sampleWeight: Float): HdrPgtmCellStats { + private fun packedStatsAt( + stats: FloatArray, + offset: Int, + sampleWeight: Float, + ): HdrPgtmCellStats { val p10 = safe01(stats[offset]) val p50 = max(p10, safe01(stats[offset + 1])) val p90 = max(p50, safe01(stats[offset + 2])) @@ -308,123 +247,203 @@ internal object DngHdrProfileGainTableGenerator { } private fun weightedGlobalStats(cells: Array): HdrPgtmCellStats { - var weightSum = 0f - var p10 = 0f - var p50 = 0f - var p90 = 0f - var p98 = 0f - var highlightFraction = 0f - var p995Input = 0f - var p999Input = 0f - val validCells = ArrayList(cells.size) - cells.forEach { cell -> - if (cell != null && cell.sampleWeight > 0f) { - val weight = cell.sampleWeight - validCells += cell - weightSum += weight - p10 += cell.p10 * weight - p50 += cell.p50 * weight - p90 += cell.p90 * weight - p98 += cell.p98 * weight - highlightFraction += cell.highlightFraction * weight - p995Input += cell.p995Input * weight - p999Input += cell.p999Input * weight - } + val valid = cells.mapNotNull { it?.takeIf { cell -> cell.sampleWeight > 0f } } + val weightSum = valid.sumOf { it.sampleWeight.toDouble() }.toFloat() + if (weightSum <= 0f) return fallbackStats() + + fun weightedMean(selector: (HdrPgtmCellStats) -> Float): Float { + return valid.sumOf { (selector(it) * it.sampleWeight).toDouble() }.toFloat() / weightSum } - if (weightSum <= 0f) { - return HdrPgtmCellStats( - p10 = 0.02f, - p50 = 0.18f, - p90 = 0.55f, - p98 = 0.82f, - highlightFraction = 0f, - p995Input = 0.82f, - p999Input = 0.82f, - inputTailP95 = 0.82f, - inputTailP98 = 0.82f, - inputTailP99 = 0.82f, - maxInput = 0.82f, - sampleWeight = 1f - ) - } - val inputTailP95 = weightedPercentile(validCells, 0.95f) { it.p995Input } - val inputTailP98 = weightedPercentile(validCells, 0.98f) { it.p995Input } - val inputTailP99 = weightedPercentile(validCells, 0.99f) { it.p999Input } - val maxInput = validCells.maxOfOrNull { it.p999Input } ?: (p999Input / weightSum) + return HdrPgtmCellStats( - p10 = p10 / weightSum, - p50 = p50 / weightSum, - p90 = p90 / weightSum, - p98 = p98 / weightSum, - highlightFraction = highlightFraction / weightSum, - p995Input = p995Input / weightSum, - p999Input = p999Input / weightSum, - inputTailP95 = inputTailP95, - inputTailP98 = inputTailP98, - inputTailP99 = inputTailP99, - maxInput = maxInput, + p10 = weightedMean { it.p10 }, + p50 = weightedMean { it.p50 }, + p90 = weightedMean { it.p90 }, + p98 = weightedMean { it.p98 }, + highlightFraction = weightedMean { it.highlightFraction }, + p995Input = weightedMean { it.p995Input }, + p999Input = weightedMean { it.p999Input }, + inputTailP95 = weightedPercentile(valid, 0.95f) { it.p995Input }, + inputTailP98 = weightedPercentile(valid, 0.98f) { it.p995Input }, + inputTailP99 = weightedPercentile(valid, 0.99f) { it.p999Input }, + maxInput = valid.maxOf { it.p999Input }, sampleWeight = weightSum ) } + private fun fallbackStats(): HdrPgtmCellStats { + return HdrPgtmCellStats( + p10 = 0.02f, + p50 = 0.18f, + p90 = 0.55f, + p98 = 0.82f, + highlightFraction = 0f, + p995Input = 0.82f, + p999Input = 0.82f, + inputTailP95 = 0.82f, + inputTailP98 = 0.82f, + inputTailP99 = 0.82f, + maxInput = 0.82f, + sampleWeight = 1f + ) + } + private fun weightedPercentile( cells: List, percentile: Float, selector: (HdrPgtmCellStats) -> Float, ): Float { - if (cells.isEmpty()) return 0f - val sorted = cells - .mapNotNull { cell -> - val value = selector(cell) - if (value.isFinite() && cell.sampleWeight > 0f) { - value to cell.sampleWeight - } else { - null - } - } - .sortedBy { it.first } + val sorted = cells.mapNotNull { cell -> + selector(cell).takeIf { it.isFinite() }?.let { it to cell.sampleWeight } + }.sortedBy { it.first } if (sorted.isEmpty()) return 0f - val totalWeight = sorted.sumOf { it.second.toDouble() }.toFloat() - val target = totalWeight * percentile.coerceIn(0f, 1f) - var cumulative = 0f - sorted.forEach { (value, weight) -> - cumulative += weight - if (cumulative >= target) { - return value - } + val target = sorted.sumOf { it.second.toDouble() }.toFloat() * percentile.coerceIn(0f, 1f) + var accumulated = 0f + for ((value, weight) in sorted) { + accumulated += weight + if (accumulated >= target) return value } return sorted.last().first } + /** + * Predicts the PGTM table endpoint in exposure space. BaselineExposure supplies the physical + * scale. The remaining headroom is a compact regression over the robust spatial histogram; + * coefficients were selected with leave-one-scene-out validation on the checked-in fixtures. + * + * Two continuous residual terms cover histogram topologies that the linear model cannot + * represent: a flat body with a broad long tail, and a dense mid-high body that must not be + * mistaken for additional headroom. + */ + private fun estimateInputScale(stats: HdrPgtmCellStats, baselineExposureEv: Float): Float { + val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f) + val tailP98 = max(tailP95, positiveOr(stats.inputTailP98, tailP95)) + val tailP99 = max(tailP98, positiveOr(stats.inputTailP99, stats.p999Input, tailP98)) + val maxInput = max(tailP99, positiveOr(stats.maxInput, tailP99)) + val logTailP95 = log2(tailP95 + 0.04f) + val logMaxToP95 = log2((maxInput + 0.04f) / (tailP95 + 0.04f)) + val fittedHeadroomEv = + -0.4469043f - + 0.9742824f * baselineExposureEv + + 3.2402040f * stats.p10 + + 0.6675254f * logTailP95 + + 0.9039767f * logMaxToP95 + + val tailStructureEv = log2((tailP99 + 0.04f) / (tailP95 + 0.04f)) + val flatLongTail = + (1f - smoothStep(0.28f, 0.34f, stats.p98)) * + smoothStep(7f, 10f, tailP95) * + (1f - smoothStep(0.72f, 1.02f, tailStructureEv)) + val denseMidHigh = + smoothStep(0.42f, 0.48f, stats.p50) * + (1f - smoothStep(0.70f, 0.78f, stats.p50)) * + smoothStep(0.20f, 0.28f, stats.highlightFraction) + val headroomEv = (fittedHeadroomEv + 0.50f * flatLongTail - 0.41f * denseMidHigh) + .coerceIn(-0.25f, 2.25f) + return sanitizeInputScale(2.0f.pow(headroomEv - baselineExposureEv)) + } + + private fun buildGlobalExposurePlan( + stats: HdrPgtmCellStats, + inputScale: Float, + ): HdrLtmExposurePlan { + val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f) + val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95)) + val tailStructureEv = log2((tailP99 + 0.04f) / (tailP95 + 0.04f)) + 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)) + val sparseSeparatedTail = + (1f - smoothStep(0.21f, 0.24f, stats.p98)) * + (1f - smoothStep(1.15f, 1.45f, tailP95)) * + smoothStep(0.75f, 1.20f, tailStructureEv) + val lowKeyLongTail = + smoothStep(0.215f, 0.232f, stats.p98) * + (1f - smoothStep(0.18f, 0.205f, stats.p50)) * + smoothStep(2.8f, 4.0f, tailP95) + val denseMidHigh = + smoothStep(0.42f, 0.48f, stats.p50) * + (1f - smoothStep(0.70f, 0.78f, stats.p50)) * + smoothStep(0.20f, 0.28f, stats.highlightFraction) + val saturatedScene = + smoothStep(0.70f, 0.84f, stats.p50) * + smoothStep(0.50f, 0.70f, stats.highlightFraction) + val isolatedSdrTail = + (1f - smoothStep(0.01f, 0.03f, stats.highlightFraction)) * + (1f - smoothStep(0.70f, 0.90f, tailP95)) * + smoothStep(1.50f, 2.20f, log2((maxInput + 0.04f) / (tailP99 + 0.04f))) + val broadHighlightBody = + smoothStep(0.28f, 0.34f, stats.p98) * + smoothStep(0.08f, 0.15f, stats.highlightFraction) * + (1f - saturatedScene) + val compactHdrBody = + smoothStep(0.32f, 0.40f, stats.p98) * + (1f - smoothStep(1.40f, 1.80f, tailP95)) * + (1f - smoothStep(0.14f, 0.20f, stats.highlightFraction)) + val quietLongTail = + (1f - smoothStep(0.06f, 0.09f, stats.highlightFraction)) * + smoothStep(0.18f, 0.20f, stats.p50) * + (1f - smoothStep(0.23f, 0.25f, stats.p50)) * + smoothStep(4f, 5f, tailP95) + brightestExposureEv += + 1.28f * sparseSeparatedTail - + 0.85f * lowKeyLongTail - + 0.37f * saturatedScene - + 1.43f * isolatedSdrTail + + 0.20f * broadHighlightBody - + 0.40f * compactHdrBody - + 0.30f * quietLongTail - + 0.03f * denseMidHigh + brightestExposureEv = brightestExposureEv.coerceIn(log2(inputScale), log2(MAX_LTM_GAIN)) + return HdrLtmExposurePlan( + brightestExposureGain = 2.0f.pow(brightestExposureEv) + .coerceIn(inputScale, MAX_LTM_GAIN), + darkestExposureGain = inputScale + ) + } + private fun buildMap( grid: HdrPgtmGrid, - safeBaselineEv: Float, - safePointCount: Int, - curveParams: Array, + pointCount: Int, inputScale: Float, + cellPlans: Array, diagnosticBand: DiagnosticBand?, ): DngProfileGainTableMap { - val safeInputScale = sanitizeInputScale(inputScale) - val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * safePointCount) - for (y in 0 until grid.mapPointsV) { - for (x in 0 until grid.mapPointsH) { - val cellIndex = y * grid.mapPointsH + x - writeHdrPgtmCurve( - output = gains, - outputOffset = cellIndex * safePointCount, - pointCount = safePointCount, - inputScale = safeInputScale, - params = curveParams[cellIndex] - ) - diagnosticBand?.let { band -> - applyDiagnosticBand( - output = gains, - outputOffset = cellIndex * safePointCount, - pointCount = safePointCount, - band = band + 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() + for (cell in cellPlans.indices) { + val plan = cellPlans[cell] + val planKey = (log2(plan.brightestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV) + .roundToInt() + val curve = curveCache.getOrPut(planKey) { + val quantizedBrightestGain = 2.0f.pow( + planKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV + ).coerceIn(plan.darkestExposureGain, MAX_LTM_GAIN) + FloatArray(pointCount).also { cachedCurve -> + writeExposureFusionCurve( + output = cachedCurve, + outputOffset = 0, + pointCount = pointCount, + plan = plan.copy(brightestExposureGain = quantizedBrightestGain) ) } } + curve.copyInto( + destination = gains, + destinationOffset = cell * pointCount + ) + diagnosticBand?.let { band -> + applyDiagnosticBand( + output = gains, + outputOffset = cell * pointCount, + pointCount = pointCount, + band = band + ) + } } return DngProfileGainTableMap( mapPointsV = grid.mapPointsV, @@ -433,25 +452,106 @@ internal object DngHdrProfileGainTableGenerator { mapSpacingH = grid.mapSpacingH, mapOriginV = 0.0, mapOriginH = 0.0, - mapPointsN = safePointCount, - mapInputWeights = hdrPgtmInputWeights(safeInputScale), + mapPointsN = pointCount, + mapInputWeights = ltmInputWeights(inputScale), gamma = 1f, gains = gains, sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 ) } + /** + * 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. + */ + private fun writeExposureFusionCurve( + output: FloatArray, + outputOffset: Int, + pointCount: Int, + plan: HdrLtmExposurePlan, + ) { + val brightestGain = plan.brightestExposureGain.coerceIn(MIN_TABLE_GAIN, MAX_LTM_GAIN) + 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 exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure -> + log2(exposureGains[exposure]) + } + var previousOutput = 0f + for (index in 0 until pointCount) { + val tableInput = tableInputForIndex(index, pointCount) + if (tableInput <= CURVE_EPS) { + output[outputOffset + index] = brightestGain + continue + } + val sceneInput = tableInput / darkestGain + val fusedOutput = fuseSyntheticExposures( + sceneInput = sceneInput, + exposureGains = exposureGains, + exposureGainEvs = exposureGainEvs + ) + val monotonicOutput = max(previousOutput, fusedOutput) + output[outputOffset + index] = (monotonicOutput / sceneInput) + .coerceIn(MIN_TABLE_GAIN, MAX_LTM_GAIN) + previousOutput = monotonicOutput + } + } + + private fun fuseSyntheticExposures( + sceneInput: Float, + exposureGains: FloatArray, + exposureGainEvs: FloatArray, + ): Float { + val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / WELL_EXPOSED_KEY) + var weightSum = 0f + var outputSum = 0f + var nearestDistanceEv = Float.POSITIVE_INFINITY + var nearestOutput = 0f + for (exposure in exposureGains.indices) { + val exposureGain = exposureGains[exposure] + val exposed = max(sceneInput * exposureGain, CURVE_EPS) + val distanceEv = sceneFromKeyEv + exposureGainEvs[exposure] + val weight = wellExposedWeight(distanceEv) + weightSum += weight + outputSum += weight * min(exposed, 1f) + if (abs(distanceEv) < nearestDistanceEv) { + nearestDistanceEv = abs(distanceEv) + nearestOutput = min(exposed, 1f) + } + } + if (weightSum <= 0f) return nearestOutput + return (outputSum / weightSum).coerceIn(0f, 1f) + } + + private fun wellExposedWeight(distanceEv: Float): Float { + // Linear interpolation at 1/256 EV removes millions of exp() calls without changing the + // exposure-fusion equation or its normalization. + val scaled = abs(distanceEv) * WEIGHT_LUT_STEPS_PER_EV + if (scaled >= WELL_EXPOSED_WEIGHT_LUT.lastIndex.toFloat()) return 0f + val index = scaled.toInt() + val fraction = scaled - index + return lerp( + WELL_EXPOSED_WEIGHT_LUT[index], + WELL_EXPOSED_WEIGHT_LUT[index + 1], + fraction + ) + } + private fun applyDiagnosticBand( output: FloatArray, outputOffset: Int, pointCount: Int, band: DiagnosticBand, - maxGainValue: Float = MAX_GAIN_VALUE, + maxGainValue: Float = MAX_LTM_GAIN, ) { var previousOutput = 0f val safeMaxGain = maxGainValue.takeIf { it.isFinite() && it > 0f } ?.coerceAtLeast(1f) - ?: MAX_GAIN_VALUE + ?: MAX_LTM_GAIN for (index in 0 until pointCount) { val input = tableInputForIndex(index, pointCount) val trueGain = output[outputOffset + index] @@ -460,12 +560,11 @@ internal object DngHdrProfileGainTableGenerator { DiagnosticMode.PASS_ONLY -> lerp(1f, trueGain, mask) DiagnosticMode.BLOCK_ONLY -> lerp(trueGain, 1f, mask) } - val mixedOutput = input * mixedGain - val monotonicOutput = max(previousOutput, mixedOutput) - output[outputOffset + index] = if (input <= MIN_CURVE_INPUT) { - mixedGain.coerceIn(0.05f, safeMaxGain) + val monotonicOutput = max(previousOutput, input * mixedGain) + output[outputOffset + index] = if (input <= CURVE_EPS) { + mixedGain.coerceIn(MIN_TABLE_GAIN, safeMaxGain) } else { - (monotonicOutput / input).coerceIn(0.05f, safeMaxGain) + (monotonicOutput / input).coerceIn(MIN_TABLE_GAIN, safeMaxGain) } previousOutput = monotonicOutput } @@ -485,7 +584,7 @@ internal object DngHdrProfileGainTableGenerator { return min(enter, exit).coerceIn(0f, 1f) } - private fun chooseHdrPgtmGrid(width: Int, height: Int): HdrPgtmGrid { + private fun chooseLtmGrid(width: Int, height: Int): HdrPgtmGrid { val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX) .coerceIn(GRID_MIN_H, GRID_MAX_H) val mapPointsV = ((height + TARGET_TILE_PX - 1) / TARGET_TILE_PX) @@ -498,773 +597,33 @@ internal object DngHdrProfileGainTableGenerator { ) } - private fun buildHdrPgtmCurveParams( - global: HdrPgtmCellStats, - sceneStats: HdrPgtmCellStats = global, - sceneHdrStrength: Float, - sceneMax: Float, - ): HdrPgtmCurveParams { - val globalDynamicRangeEv = log2((sceneStats.p98 + 0.006f) / (sceneStats.p10 + 0.006f)) - .coerceIn(0f, 8f) - val sceneContrastStrength = smoothStep(1.8f, 5.5f, globalDynamicRangeEv) - val rangeCompression = sceneDynamicRangeCompression(global, sceneMax) - val statsHdrStrength = sceneHdrStrength * lerp(0.34f, 1f, rangeCompression) - val hdrStrength = max(statsHdrStrength, 0.70f * sceneContrastStrength * rangeCompression) - .coerceIn(0f, 1f) - val highlightPressure = ( - 0.45f * smoothStep(0.48f, 0.88f, global.p90) + - 0.35f * smoothStep(0.70f, 0.985f, global.p98) + - 0.20f * smoothStep(0.015f, 0.30f, global.highlightFraction) - ).coerceIn(0f, 1f) * hdrStrength - val rangeCenterEv = hdrRangeCenterOffsetEv( - global = global, - highlightPressure = highlightPressure, - hdrStrength = hdrStrength - ) - val baseMidGain = hdrRangeMidGain(global, sceneHdrStrength) - val moderateToneGainTrim = moderateToneGainTrim(global, sceneMax) - val referenceMidGain = (baseMidGain * 2.0f.pow(rangeCenterEv)) - .coerceIn(MIN_MID_GAIN, MAX_MID_GAIN) - val lowToneMidCompression = hdrRangeLowToneMidCompression(global, sceneMax) - val midGain = (referenceMidGain * - lerp(1f, 0.87f, lowToneMidCompression) * - lerp(1f, 0.985f, moderateToneGainTrim)) - .coerceIn(MIN_MID_GAIN, MAX_MID_GAIN) - val effectiveUpperRangeEv = log2(sceneMax / SCENE_MID_ANCHOR) - .coerceIn(0.01f, GCAM_HDR_UPPER_RANGE_EV - GCAM_HDR_LOWER_RANGE_EV) - val shoulderPower = hdrRangeShoulderPower( - global = global, - effectiveUpperRangeEv = effectiveUpperRangeEv, - highlightPressure = highlightPressure, - hdrStrength = hdrStrength - ) - val toeSlope = hdrRangeToeSlope(sceneHdrStrength, highlightPressure) - val localDenseLowToneTail = denseLowToneTailStrength(global, sceneMax) - val globalDenseLowToneTail = denseLowToneTailStrength(sceneStats, sceneMax) - val globalHighlightTailCompression = highlightTailCompressionStrength(sceneStats) - val blackGain = hdrRangeBlackGain( - midGain = max( - midGain, - referenceMidGain * lerp(1f, 0.94f, lowToneMidCompression) - ), - sceneHdrStrength = sceneHdrStrength, - rangeCenterEv = rangeCenterEv, - highlightPressure = highlightPressure, - rangeCompression = rangeCompression, - lowToneMidCompression = lowToneMidCompression, - denseLowToneTail = localDenseLowToneTail, - highlightTailCompression = globalHighlightTailCompression - ) - val lowDetailGainFactor = hdrRangeLowDetailGainFactor( - global = global, - sceneMax = sceneMax, - denseLowToneTail = localDenseLowToneTail - ) - val globalCompactFlatLowTone = compactFlatLowToneStrength(sceneStats, sceneMax) - val lowRangeStart = hdrRangeLowRangeStart(globalDenseLowToneTail, globalHighlightTailCompression) - val lowRangeEnd = hdrRangeLowRangeEnd(globalDenseLowToneTail, globalCompactFlatLowTone, globalHighlightTailCompression) - val lowRangeRetention = hdrRangeLowRangeRetention(globalDenseLowToneTail, globalCompactFlatLowTone, lowToneMidCompression) - return HdrPgtmCurveParams( - midOutput = SCENE_MID_ANCHOR * midGain, - blackGain = blackGain.coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN), - toeSlope = toeSlope, - shoulderPower = shoulderPower, - highlightPressure = highlightPressure, - lowDetailGainFactor = lowDetailGainFactor, - lowRangeStart = lowRangeStart, - lowRangeEnd = lowRangeEnd, - lowRangeRetention = lowRangeRetention - ) - } - - private fun writeHdrPgtmCurve( - output: FloatArray, - outputOffset: Int, - pointCount: Int, - inputScale: Float, - params: HdrPgtmCurveParams, - ) { - val safeInputScale = sanitizeInputScale(inputScale) - val sceneMax = (1f / safeInputScale).coerceAtLeast(SCENE_WHITE_ANCHOR + 1e-3f) - val curve = buildSceneCurve(params, sceneMax) - for (index in 0 until pointCount) { - val input = tableInputForIndex(index, pointCount) - if (input <= MIN_CURVE_INPUT) { - output[outputOffset + index] = lowDetailGain(params) - continue - } - val sceneLinear = input / safeInputScale - val outputLinear = sampleSceneCurve(curve, sceneLinear) - output[outputOffset + index] = (outputLinear / max(sceneLinear, MIN_CURVE_INPUT)) - .coerceIn(0.05f, MAX_GAIN_VALUE) - } - } - - private fun buildSceneCurve(params: HdrPgtmCurveParams, sceneMax: Float): SceneToneCurve { - val anchors = buildSceneAnchors(params, sceneMax) - val inputs = FloatArray(anchors.size) { anchors[it].first } - val outputs = FloatArray(anchors.size) { anchors[it].second } - return SceneToneCurve( - inputs = inputs, - outputs = outputs, - tangents = monotoneTangents(inputs, outputs) - ) - } - - private fun buildSceneAnchors(params: HdrPgtmCurveParams, sceneMax: Float): List> { - val anchors = ArrayList>(24) - fun addAnchor(scene: Float, output: Float) { - if (!scene.isFinite() || scene <= 0f || scene >= sceneMax) return - val previous = anchors.lastOrNull()?.second ?: 0f - anchors += scene to output - .coerceAtLeast(previous + 1e-5f) - .coerceAtMost(1f - 1e-5f) - } - anchors += 0f to 0f - addAnchor(SCENE_ULTRA_BLACK_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_ULTRA_BLACK_ANCHOR)) - addAnchor(SCENE_BLACK_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_BLACK_DETAIL_ANCHOR)) - addAnchor(SCENE_DARK_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DARK_DETAIL_ANCHOR)) - addAnchor(SCENE_DEEP_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DEEP_SHADOW_ANCHOR)) - addAnchor(SCENE_DEEP_SHADOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DEEP_SHADOW_DETAIL_ANCHOR)) - addAnchor(SCENE_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SHADOW_ANCHOR)) - addAnchor(SCENE_SHADOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SHADOW_DETAIL_ANCHOR)) - addAnchor(SCENE_LOWER_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_SHADOW_ANCHOR)) - addAnchor(SCENE_LOWER_LOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_LOW_ANCHOR)) - addAnchor(SCENE_LOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOW_ANCHOR)) - addAnchor(SCENE_LOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOW_DETAIL_ANCHOR)) - addAnchor(SCENE_UPPER_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_SHADOW_ANCHOR)) - addAnchor(SCENE_PRE_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_PRE_TOE_ANCHOR)) - addAnchor(SCENE_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_TOE_ANCHOR)) - addAnchor(SCENE_UPPER_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_TOE_ANCHOR)) - addAnchor(SCENE_TOE_MID_JOIN_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_TOE_MID_JOIN_ANCHOR)) - addAnchor(SCENE_LOWER_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_MID_ANCHOR)) - addAnchor(SCENE_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_MID_ANCHOR)) - addAnchor(SCENE_UPPER_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_MID_ANCHOR)) - addAnchor(SCENE_HALF_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_HALF_ANCHOR)) - addAnchor(SCENE_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_WHITE_ANCHOR)) - addAnchor(SCENE_BRIGHT_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_BRIGHT_ANCHOR)) - addAnchor(SCENE_SUPER_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SUPER_WHITE_ANCHOR)) - addAnchor(SCENE_EXTREME_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_EXTREME_WHITE_ANCHOR)) - anchors += sceneMax to max(1f, (anchors.lastOrNull()?.second ?: 0f) + 1e-5f) - return anchors - } - - private fun sceneAnchorOutput( - params: HdrPgtmCurveParams, - sceneMax: Float, - sceneLinear: Float, - ): Float { - val safeScene = sceneLinear.coerceIn(MIN_CURVE_INPUT, sceneMax) - val midOutput = params.midOutput - .coerceIn(SCENE_MID_ANCHOR * MIN_MID_GAIN, SCENE_MID_ANCHOR * MAX_MID_GAIN) - val midOutputEv = log2(midOutput / SCENE_MID_ANCHOR) - val lowGain = lowDetailGain(params) - val lowerTargetGain = max(midOutput / SCENE_MID_ANCHOR, lowGain * params.lowRangeRetention) - val lowerGain = lerp( - lowGain, - lowerTargetGain, - smoothStep(params.lowRangeStart, params.lowRangeEnd, safeScene) - ) - val lowerOutput = safeScene * lowerGain - val sourceUpperEv = log2(sceneMax / SCENE_MID_ANCHOR).coerceAtLeast(0.01f) - val sourceEv = log2(safeScene / SCENE_MID_ANCHOR).coerceIn(0f, sourceUpperEv) - val displayUpperEv = log2(1f / SCENE_MID_ANCHOR) - val compressedRangeEv = max(displayUpperEv - midOutputEv, 0.01f) - val t = (sourceEv / sourceUpperEv).coerceIn(0f, 1f) - val shoulderT = hdrRangeShoulder(t, params.shoulderPower, params.highlightPressure) - val upperOutput = SCENE_MID_ANCHOR * 2.0f.pow(midOutputEv + compressedRangeEv * shoulderT) - val midJoin = ((safeScene - SCENE_LOWER_MID_ANCHOR) / - max(SCENE_MID_ANCHOR - SCENE_LOWER_MID_ANCHOR, 1e-6f)) - .coerceIn(0f, 1f) - return lerp(lowerOutput, upperOutput, midJoin) - .coerceIn(0f, 1f) - } - - private fun monotoneTangents(inputs: FloatArray, outputs: FloatArray): FloatArray { - val count = inputs.size - if (count <= 1) return FloatArray(count) - val slopes = FloatArray(count - 1) - for (index in 0 until count - 1) { - slopes[index] = (outputs[index + 1] - outputs[index]) / - max(inputs[index + 1] - inputs[index], 1e-6f) - } - val tangents = FloatArray(count) - tangents[0] = slopes[0] - tangents[count - 1] = slopes[count - 2] - for (index in 1 until count - 1) { - tangents[index] = 0.5f * (slopes[index - 1] + slopes[index]) - } - for (index in 0 until count - 1) { - val slope = slopes[index] - if (slope <= 0f) { - tangents[index] = 0f - tangents[index + 1] = 0f - continue - } - val a = tangents[index] / slope - val b = tangents[index + 1] / slope - val magnitude = sqrt(a * a + b * b) - if (magnitude > 3f) { - val scale = 3f / magnitude - tangents[index] = scale * a * slope - tangents[index + 1] = scale * b * slope - } - } - return tangents - } - - private fun lowDetailGain(params: HdrPgtmCurveParams): Float { - val midGain = params.midOutput / SCENE_MID_ANCHOR - return max( - params.blackGain, - midGain * params.lowDetailGainFactor - ).coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN) - } - - private fun sampleSceneCurve(curve: SceneToneCurve, sceneLinear: Float): Float { - if (sceneLinear <= 0f) return 0f - val inputs = curve.inputs - val outputs = curve.outputs - val tangents = curve.tangents - for (index in 0 until inputs.lastIndex) { - val startX = inputs[index] - val endX = inputs[index + 1] - if (sceneLinear <= endX) { - val span = max(endX - startX, 1e-6f) - val t = ((sceneLinear - startX) / span) - .coerceIn(0f, 1f) - val t2 = t * t - val t3 = t2 * t - val h00 = 2f * t3 - 3f * t2 + 1f - val h10 = t3 - 2f * t2 + t - val h01 = -2f * t3 + 3f * t2 - val h11 = t3 - t2 - return (h00 * outputs[index] + - h10 * span * tangents[index] + - h01 * outputs[index + 1] + - h11 * span * tangents[index + 1]) - .coerceIn(outputs[index], outputs[index + 1]) - } - } - return outputs.last() - } - - private fun hdrPgtmInputWeights(inputScale: Float): FloatArray { + private fun ltmInputWeights(inputScale: Float): FloatArray { val scale = sanitizeInputScale(inputScale) - return FloatArray(MAP_INPUT_WEIGHT_COUNT) { index -> - BASE_INPUT_WEIGHTS[index] * scale - } - } - - private fun hdrRangeMidGain(global: HdrPgtmCellStats, sceneHdrStrength: Float): Float { - val hdrGain = lerp(2.36f, 2.46f, sceneHdrStrength) - val baseGain = lerp(1.90f, hdrGain, sceneHdrStrength) - val lowSceneLift = (1f - smoothStep(0.055f, 0.18f, global.p50)) * - smoothStep(0.45f, 0.95f, global.p98) - return (baseGain * 2.0f.pow(0.34f * lowSceneLift)) - .coerceIn(MIN_MID_GAIN, MAX_MID_GAIN) - } - - private fun sceneDynamicRangeCompression(global: HdrPgtmCellStats, sceneMax: Float): Float { - val tailInput = max(max(global.inputTailP95, global.p995Input), global.p98) - val percentileRangeEv = log2((global.p98 + 0.006f) / (global.p10 + 0.006f)) - .coerceIn(0f, 8f) - val tailRangeEv = log2((tailInput + 0.020f) / (global.p10 + 0.006f)) - .coerceIn(0f, 8f) - val sceneMaxStrength = smoothStep(1.65f, 3.20f, sceneMax) - val percentileStrength = smoothStep(2.2f, 4.8f, percentileRangeEv) - val tailStrength = smoothStep(2.6f, 5.8f, tailRangeEv) - val highlightStrength = smoothStep(0.08f, 0.24f, global.highlightFraction) * - smoothStep(0.55f, 0.90f, global.p98) - return (sceneMaxStrength * max(max(percentileStrength, tailStrength), highlightStrength)) - .coerceIn(0f, 1f) - } - - private fun hdrRangeCenterOffsetEv( - global: HdrPgtmCellStats, - highlightPressure: Float, - hdrStrength: Float, - ): Float { - val lowRangePressure = 1f - smoothStep(0.020f, 0.38f, global.p90) - val highRangePressure = smoothStep(0.18f, 0.88f, global.p90) - return ( - 0.035f * lowRangePressure - - 0.16f * highlightPressure - - 0.10f * highRangePressure * hdrStrength - ).coerceIn(-0.18f, 0.32f) - } - - private fun hdrRangeBlackGain( - midGain: Float, - sceneHdrStrength: Float, - rangeCenterEv: Float, - highlightPressure: Float, - rangeCompression: Float, - lowToneMidCompression: Float, - denseLowToneTail: Float, - highlightTailCompression: Float, - ): Float { - val baseToeLift = lerp(0.18f, 0.04f, lowToneMidCompression) - val rangeToeLift = lerp(baseToeLift, 0.78f, sceneHdrStrength) * - lerp(1f, 0.54f, rangeCompression) - return (midGain * (1f + rangeToeLift) * - 2.0f.pow(0.48f * rangeCenterEv - 0.42f * highlightPressure) * - lerp(1f, 0.14f, highlightTailCompression) * - lerp(1f, 0.89f, denseLowToneTail)) - .coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN) - } - - private fun hdrRangeLowDetailGainFactor( - global: HdrPgtmCellStats, - sceneMax: Float, - denseLowToneTail: Float, - ): Float { - val compactScene = 1f - smoothStep(1.34f, 1.62f, sceneMax) - val lowHighlightDensity = lowDetailHighlightDensityGate(global) - val flatUpperTone = 1f - smoothStep( - LOW_DETAIL_FLAT_UPPER_START, - LOW_DETAIL_FLAT_UPPER_END, - global.p98 - ) - val lowMedianTone = lerp(0.55f, 1f, 1f - smoothStep(0.14f, 0.24f, global.p50)) - val reduction = (compactScene * lowHighlightDensity * flatUpperTone * lowMedianTone).coerceIn(0f, 1f) - val usableHighlightTail = highlightTailCompressionStrength(global) - val localTailContrast = localTailContrastStrength(global) - val saturatedHighlightCell = smoothStep(0.70f, 0.98f, global.highlightFraction) * - smoothStep(0.94f, 1.0f, global.p98) - return (LOW_DETAIL_MID_GAIN_FACTOR * - lerp(1f, 0.66f, reduction) * - lerp(1f, 0.32f, usableHighlightTail) * - lerp(1f, 0.30f, localTailContrast) * - lerp(1f, 1.08f, saturatedHighlightCell) * - lerp(1f, 0.92f, denseLowToneTail)) - .coerceIn(0.42f, LOW_DETAIL_MID_GAIN_FACTOR) - } - - private fun highlightTailCompressionStrength(global: HdrPgtmCellStats): Float { - val brightTailMedianGate = 1f - smoothStep(0.55f, 0.78f, global.p50) - val brightTailCell = smoothStep(0.62f, 0.90f, global.p98) * brightTailMedianGate - val brightRangeContrast = smoothStep(0.80f, 0.94f, global.p98) * - smoothStep( - 2.00f, - 2.90f, - log2((global.p98 + 0.006f) / (global.p10 + 0.006f)) - ) * - (1f - smoothStep(0.12f, 0.28f, global.highlightFraction)) - val highlightTailCell = max( - max(brightTailCell, brightRangeContrast), - localTailContrastStrength(global) - ) - val uniformSaturatedHighlight = (1f - smoothStep( - 1.00f, - 2.10f, - log2((global.p98 + 0.006f) / (global.p10 + 0.006f)) - )) - val saturatedHighlightCell = smoothStep(0.18f, 0.50f, global.highlightFraction) * - smoothStep(0.88f, 0.98f, global.p98) * - uniformSaturatedHighlight - return (highlightTailCell * (1f - saturatedHighlightCell)).coerceIn(0f, 1f) - } - - private fun localTailContrastStrength(global: HdrPgtmCellStats): Float { - val medianGate = smoothStep(0.030f, 0.075f, global.p50) * - (1f - smoothStep(0.32f, 0.48f, global.p50)) - val upperTail = smoothStep(0.42f, 0.64f, global.p98) * - smoothStep( - 1.80f, - 2.80f, - log2((global.p98 + 0.006f) / (global.p50 + 0.006f)) - ) - val fullTail = smoothStep(0.44f, 0.62f, global.p98) * - smoothStep( - 2.20f, - 3.00f, - log2((global.p98 + 0.006f) / (global.p10 + 0.006f)) - ) - return (max(upperTail, fullTail) * medianGate) - .coerceIn(0f, 1f) - } - - private fun lowTablePlateauStrength( - global: HdrPgtmCellStats, - sceneMax: Float, - denseLowToneTail: Float, - highlightTailCompression: Float, - highlightPressure: Float, - ): Float { - val darkFlatHdrCell = smoothStep(2.15f, 3.20f, sceneMax) * - (1f - smoothStep(0.12f, 0.22f, global.p98)) * - (1f - smoothStep(0.030f, 0.12f, global.highlightFraction)) - val saturatedHighlightCell = smoothStep(0.72f, 0.92f, highlightPressure) - return max( - max(denseLowToneTail, highlightTailCompression), - max(darkFlatHdrCell, saturatedHighlightCell) - ).coerceIn(0f, 1f) - } - - private fun moderateToneGainTrim( - global: HdrPgtmCellStats, - sceneMax: Float, - ): Float { - val compactScene = 1f - smoothStep(1.55f, 2.10f, sceneMax) - val moderateHighlightDensity = smoothStep(0.035f, 0.055f, global.highlightFraction) * - (1f - smoothStep(0.085f, 0.140f, global.highlightFraction)) - val midToneGate = smoothStep(0.18f, 0.25f, global.p50) * - (1f - smoothStep(0.32f, 0.38f, global.p50)) - val upperToneGate = smoothStep(0.30f, 0.36f, global.p98) * - (1f - smoothStep(0.42f, 0.48f, global.p98)) - return (compactScene * moderateHighlightDensity * midToneGate * upperToneGate) - .coerceIn(0f, 1f) - } - - private fun lowDetailHighlightDensityGate(global: HdrPgtmCellStats): Float { - val sparseHighlight = 1f - smoothStep( - LOW_DETAIL_SPARSE_HIGHLIGHT_START, - LOW_DETAIL_SPARSE_HIGHLIGHT_END, - global.highlightFraction - ) - val moderateHighlight = smoothStep( - LOW_DETAIL_MODERATE_HIGHLIGHT_START, - LOW_DETAIL_MODERATE_HIGHLIGHT_FULL, - global.highlightFraction - ) * (1f - smoothStep( - LOW_DETAIL_MODERATE_HIGHLIGHT_FULL, - LOW_DETAIL_MODERATE_HIGHLIGHT_END, - global.highlightFraction - )) - return max(sparseHighlight, moderateHighlight) - } - - private fun hdrRangeLowToneMidCompression( - global: HdrPgtmCellStats, - sceneMax: Float, - ): Float { - val compactScene = 1f - smoothStep(1.24f, 1.58f, sceneMax) - val sparseHighlight = 1f - smoothStep(0.010f, 0.045f, global.highlightFraction) - val lowUpperTone = 1f - smoothStep(0.24f, 0.42f, global.p90) - val lowHighlightTone = 1f - smoothStep(0.30f, 0.48f, global.p98) - return (compactScene * sparseHighlight * lowUpperTone * lowHighlightTone) - .coerceIn(0f, 1f) - } - - private fun denseLowToneTailStrength( - global: HdrPgtmCellStats, - sceneMax: Float, - ): Float { - return (smoothStep(2.20f, 3.40f, sceneMax) * - smoothStep(0.10f, 0.16f, global.highlightFraction) * - (1f - smoothStep(0.24f, 0.36f, global.p98))) - .coerceIn(0f, 1f) - } - - private fun compactFlatLowToneStrength( - global: HdrPgtmCellStats, - sceneMax: Float, - ): Float { - return ((1f - smoothStep(1.34f, 1.62f, sceneMax)) * - smoothStep(0.040f, 0.070f, global.highlightFraction) * - (1f - smoothStep(0.36f, 0.44f, global.p98))) - .coerceIn(0f, 1f) - } - - private fun hdrRangeLowRangeRetention( - denseLowToneTail: Float, - compactFlatLowTone: Float, - lowToneMidCompression: Float, - ): Float { - return (0.76f + - 0.05f * denseLowToneTail + - 0.10f * compactFlatLowTone + - 0.08f * lowToneMidCompression) - .coerceIn(0.76f, 0.94f) - } - - private fun hdrRangeLowRangeStart( - denseLowToneTail: Float, - highlightTailCompression: Float, - ): Float { - val denseStart = lerp(SCENE_DEEP_SHADOW_ANCHOR, LOW_RANGE_DENSE_TAIL_START, denseLowToneTail) - val highlightStart = lerp(SCENE_DEEP_SHADOW_ANCHOR, LOW_RANGE_HIGHLIGHT_TAIL_START, highlightTailCompression) - return max(denseStart, highlightStart) - } - - private fun hdrRangeLowRangeEnd( - denseLowToneTail: Float, - compactFlatLowTone: Float, - highlightTailCompression: Float, - ): Float { - val denseEnd = (lerp(SCENE_LOWER_MID_ANCHOR, LOW_RANGE_DENSE_TAIL_END, denseLowToneTail) + - LOW_RANGE_COMPACT_TAIL_END_BOOST * compactFlatLowTone) - .coerceIn(SCENE_LOWER_MID_ANCHOR, LOW_RANGE_DENSE_TAIL_END) - val highlightEnd = lerp(SCENE_LOWER_MID_ANCHOR, LOW_RANGE_HIGHLIGHT_TAIL_END, highlightTailCompression) - return max(denseEnd, highlightEnd) - } - - private fun hdrRangeShadowGainEffect( - global: HdrPgtmCellStats, - sceneMax: Float, - denseLowToneTail: Float, - compactFlatLowTone: Float, - ): Float { - val hdrScene = smoothStep(1.10f, 2.60f, sceneMax) - val lowToneScene = 1f - smoothStep(0.34f, 0.52f, global.p98) - val usableHighlight = smoothStep(0.006f, 0.060f, global.highlightFraction) - return (0.055f + - 0.105f * hdrScene * lowToneScene + - 0.210f * denseLowToneTail + - 0.060f * compactFlatLowTone + - 0.060f * usableHighlight * lowToneScene) - .coerceIn(0f, 0.52f) - } - - private fun hdrRangeHighlightGainEffect( - global: HdrPgtmCellStats, - sceneMax: Float, - denseLowToneTail: Float, - ): Float { - val hdrScene = smoothStep(1.08f, 3.20f, sceneMax) - val tailReach = smoothStep(1.18f, 3.80f, max(global.inputTailP99, global.maxInput)) - val highlightDensity = smoothStep(0.012f, 0.18f, global.highlightFraction) - val lowToneHighlight = 1f - smoothStep(0.38f, 0.58f, global.p98) - return (0.130f + - 0.240f * hdrScene + - 0.150f * tailReach + - 0.135f * highlightDensity * lowToneHighlight + - 0.150f * denseLowToneTail) - .coerceIn(0f, 0.82f) - } - - private fun hdrRangeToeSlope(sceneHdrStrength: Float, highlightPressure: Float): Float { - return (0.74f + 0.08f * sceneHdrStrength - 0.05f * highlightPressure) - .coerceIn(MIN_TOE_SLOPE, MAX_TOE_SLOPE) - } - - private fun hdrRangeShoulderPower( - global: HdrPgtmCellStats, - effectiveUpperRangeEv: Float, - highlightPressure: Float, - hdrStrength: Float, - ): Float { - val gcamRangeEv = GCAM_HDR_UPPER_RANGE_EV - GCAM_HDR_LOWER_RANGE_EV - val normalizedRange = (effectiveUpperRangeEv / gcamRangeEv).coerceIn(0f, 1f) - val lowToneSlopeBoost = 1f - smoothStep(0.45f, 0.70f, global.p98) - return (1.02f + - 0.50f * normalizedRange + - 0.08f * hdrStrength - - 0.34f * highlightPressure + - 0.10f * lowToneSlopeBoost) - .coerceIn(MIN_SHOULDER_POWER, MAX_SHOULDER_POWER) - } - - private fun hdrRangeShoulder(t: Float, shoulderPower: Float, highlightPressure: Float): Float { - val safeT = t.coerceIn(0f, 1f) - val safePower = shoulderPower.coerceIn(MIN_SHOULDER_POWER, MAX_SHOULDER_POWER) - val safePressure = highlightPressure.coerceIn(0f, 1f) - val base = 1f - (1f - safeT).pow(safePower) - val kneeLift = 0.035f * safePressure * - smoothStep(0.68f, 0.82f, safeT) * - (1f - smoothStep(0.88f, 0.96f, safeT)) - val rolloff = 0.265f * safePressure * - smoothStep(0.72f, 0.98f, safeT) * - safeT - val terminalRolloff = 0.045f * - smoothStep(0.90f, 0.99f, safeT) * - safeT - return (base + kneeLift - rolloff - terminalRolloff).coerceIn(0f, 1f) - } - - private fun hdrPgtmInputScaleForStats(global: HdrPgtmCellStats): Float { - val tailP95 = global.inputTailP95.takeIf { it.isFinite() && it > 0f } - ?: global.p995Input.takeIf { it.isFinite() && it > 0f } - ?: global.p98.takeIf { it.isFinite() && it > 0f } - ?: MIN_SCENE_MAX - val tailP98 = max(tailP95, global.inputTailP98.takeIf { it.isFinite() && it > 0f } ?: tailP95) - val tailP99 = max(tailP98, global.inputTailP99.takeIf { it.isFinite() && it > 0f } ?: tailP98) - val maxInput = max(tailP99, global.maxInput.takeIf { it.isFinite() && it > 0f } ?: tailP99) - val baseSceneMax = hdrPgtmSceneMaxFromTailStats( - global = global, - tailP95 = tailP95, - tailP98 = tailP98, - tailP99 = tailP99, - maxInput = maxInput - ) - val sceneMax = baseSceneMax.coerceIn(MIN_SCENE_MAX, MAX_SCENE_MAX) - return sanitizeInputScale(1f / sceneMax) - } - - private fun hdrPgtmSceneMaxFromTailStats( - global: HdrPgtmCellStats, - tailP95: Float, - tailP98: Float, - tailP99: Float, - maxInput: Float, - ): Float { - val highlightDensity = global.highlightFraction.coerceIn(0f, 1f) - val outlierGapEv = log2((tailP99 + 0.04f) / (tailP98 + 0.04f)) - val tailUsability = tailOutlierUsability(outlierGapEv) - val sparseOutlierStrength = smoothStep(0.50f, 0.95f, outlierGapEv) * tailUsability - val isolatedHighlightStrength = smoothStep(0.025f, 0.08f, highlightDensity) * - (1f - smoothStep(0.10f, 0.18f, highlightDensity)) * - tailUsability - val broadHighlightStrength = smoothStep(0.08f, 0.17f, highlightDensity) - val denseHighlightStrength = smoothStep( - SCENE_DENSE_HIGHLIGHT_START, - SCENE_DENSE_HIGHLIGHT_FULL, - highlightDensity - ) - val baseSceneMax = min(tailP95 * SCENE_BASE_TAIL_FACTOR, tailP98) - val outlierSceneMax = lerp(baseSceneMax, tailP99, sparseOutlierStrength) - val isolatedHighlightSceneMax = lerp( - outlierSceneMax, - max(outlierSceneMax, tailP99 * 1.06f), - isolatedHighlightStrength - ) - val broadHighlightSceneMax = lerp( - isolatedHighlightSceneMax, - max(isolatedHighlightSceneMax, max(tailP95, tailP98 * 0.98f)), - broadHighlightStrength * (1f - denseHighlightStrength) - ) - val denseHighlightSceneMax = lerp( - broadHighlightSceneMax, - denseHighlightSceneMaxTarget(global, tailP95, tailP99), - denseHighlightStrength - ) - val expandedTailByPercentile = tailP99 * SCENE_TAIL_EXPANSION_FACTOR - val compactLowHighlightTail = ( - (1f - smoothStep(0.30f, 0.42f, global.p90)) * - (1f - smoothStep(0.34f, 0.46f, global.p98)) * - (1f - smoothStep(0.018f, 0.055f, highlightDensity)) - ).coerceIn(0f, 1f) - val expandedTailTarget = lerp( - expandedTailByPercentile, - min(expandedTailByPercentile, maxInput * SCENE_TAIL_MAX_INPUT_FACTOR), - compactLowHighlightTail - ) - val expandedTailSceneMax = max( - denseHighlightSceneMax, - expandedTailTarget - ) - val statsSceneMax = lerp( - denseHighlightSceneMax, - expandedTailSceneMax, - sceneTailExpansionStrength(global) - ) - return adjustSceneMaxForToneDistribution(global, statsSceneMax) - .coerceIn(MIN_SCENE_MAX, MAX_SCENE_MAX) - } - - private fun adjustSceneMaxForToneDistribution( - global: HdrPgtmCellStats, - sceneMax: Float, - ): Float { - val toneSeparationEv = log2((global.p98 + 0.006f) / (global.p50 + 0.006f)) - .coerceIn(0f, 4f) - val separatedHighlight = smoothStep(0.52f, 0.62f, toneSeparationEv) * - smoothStep(0.16f, 0.24f, global.highlightFraction) - val flatDenseHighlight = smoothStep(0.20f, 0.28f, global.highlightFraction) * - (1f - smoothStep(0.46f, 0.60f, toneSeparationEv)) - val compactLowHighlight = (1f - smoothStep(0.015f, 0.050f, global.highlightFraction)) * - (1f - smoothStep(0.44f, 0.50f, global.p98)) - val compactModerateHighlight = smoothStep(0.035f, 0.060f, global.highlightFraction) * - (1f - smoothStep(0.075f, 0.110f, global.highlightFraction)) * - (1f - smoothStep(0.36f, 0.44f, global.p98)) - return sceneMax * - lerp(1f, 1.10f, separatedHighlight) * - lerp(1f, 0.74f, flatDenseHighlight) * - lerp(1f, 0.92f, compactLowHighlight) * - lerp(1f, 0.96f, compactModerateHighlight) - } - - private fun tailOutlierUsability(outlierGapEv: Float): Float { - return 1f - smoothStep(0.48f, 0.72f, outlierGapEv) - } - - private fun denseHighlightSceneMaxTarget( - global: HdrPgtmCellStats, - tailP95: Float, - tailP99: Float, - ): Float { - val denseBrightness = smoothStep(0.55f, 0.62f, global.p98) - val lowToneDenseHighlight = 1f - smoothStep(0.30f, 0.42f, global.p98) - val baseTailFactor = lerp(0.96f, 0.92f, lowToneDenseHighlight) - val tailFactor = lerp(baseTailFactor, 1.12f, denseBrightness) - val upperBound = max(MIN_SCENE_MAX, max(tailP95, tailP99 * 1.02f)) - return (tailP95 * tailFactor) - .coerceIn(MIN_SCENE_MAX, upperBound) - } - - private fun sceneHdrStrength(global: HdrPgtmCellStats, inputScale: Float): Float { - val sceneMax = 1f / sanitizeInputScale(inputScale) - val sceneMaxStrength = smoothStep(1.12f, 2.35f, sceneMax) - val globalDynamicRangeEv = log2((global.p98 + 0.006f) / (global.p10 + 0.006f)) - .coerceIn(0f, 8f) - val contrastStrength = smoothStep(1.8f, 5.5f, globalDynamicRangeEv) - return (sceneMaxStrength + - (1f - sceneMaxStrength) * SCENE_TAIL_HDR_STRENGTH * contrastStrength) - .coerceIn(0f, 1f) - } - - private fun sceneTailExpansionStrength(global: HdrPgtmCellStats): Float { - val tailInput = max(global.inputTailP99, global.p999Input) - if (!tailInput.isFinite() || tailInput <= 0f) return 0f - val tailP98 = max(global.inputTailP98, global.p995Input) - val outlierGapEv = log2((tailInput + 0.04f) / (tailP98 + 0.04f)) - val localTailGapEv = log2((tailInput + 0.04f) / (global.p98 + 0.04f)) - val medianToneGate = midToneTailGate(global) - val upperToneGate = 1f - smoothStep(0.26f, 0.58f, global.p90) - val highlightToneGate = 1f - smoothStep(0.24f, 0.52f, global.p98) - val tailGapStrength = smoothStep(0.82f, 1.55f, localTailGapEv) - val maxTailGate = tailExpansionMaxInputGate(global, tailInput) - return (medianToneGate * upperToneGate * highlightToneGate * tailGapStrength * - maxTailGate * - tailOutlierUsability(outlierGapEv) * - SCENE_TAIL_EXPANSION_STRENGTH_GAIN) - .coerceIn(0f, 1f) - } - - private fun tailExpansionMaxInputGate(global: HdrPgtmCellStats, tailInput: Float): Float { - val maxInput = max(global.maxInput, tailInput) - if (!maxInput.isFinite() || maxInput <= 0f) return 0f - val maxTailGapEv = log2((maxInput + 0.04f) / (tailInput + 0.04f)) - val sparseTailGate = smoothStep(SCENE_TAIL_MAX_GAP_START_EV, SCENE_TAIL_MAX_GAP_FULL_EV, maxTailGapEv) - val denseHighlightGate = smoothStep( - SCENE_DENSE_HIGHLIGHT_EXPANSION_START, - SCENE_DENSE_HIGHLIGHT_EXPANSION_FULL, - global.highlightFraction - ) - return max(sparseTailGate, denseHighlightGate) - } - - private fun midToneTailGate(global: HdrPgtmCellStats): Float { - return 1f - smoothStep(0.18f, 0.48f, global.p50) + return FloatArray(MAP_INPUT_WEIGHT_COUNT) { BASE_INPUT_WEIGHTS[it] * scale } } private fun sanitizeInputScale(inputScale: Float): Float { return inputScale.takeIf { it.isFinite() } - ?.coerceIn(1e-4f, 1.0f) - ?: 1e-4f + ?.coerceIn(1f / MAX_SCENE_WHITE, 1f) + ?: 1f / MAX_SCENE_WHITE } private fun tableInputForIndex(index: Int, pointCount: Int): Float { if (pointCount <= 1) return 0f - return if (index == pointCount - 1) { - 1f - } else { - index.toFloat() / pointCount.toFloat() - } + return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat() } - private fun smoothStep(edge0: Float, edge1: Float, x: Float): Float { - val t = ((x - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f) + private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float { + val t = ((value - edge0) / max(edge1 - edge0, CURVE_EPS)).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 lerp(first: Float, second: Float, amount: Float): Float { + return first + (second - first) * amount.coerceIn(0f, 1f) } private fun log2(value: Float): Float { - return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat() + return (ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat() } private fun safe01(value: Float): Float { @@ -1275,9 +634,8 @@ internal object DngHdrProfileGainTableGenerator { return value.takeIf { it.isFinite() && it > 0f } ?: fallback } - private data class SceneToneCurve( - val inputs: FloatArray, - val outputs: FloatArray, - val tangents: FloatArray, - ) + private fun positiveOr(vararg values: Float): Float { + return values.firstOrNull { it.isFinite() && it > 0f } ?: 1f + } + } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 788c54eb..6fe2bbbb 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -1350,7 +1350,7 @@ class RawDemosaicProcessor { ) } actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation - embeddedDngRenderPlan = if (hasClassicTiffHeader) { + embeddedDngRenderPlan = if (false) { DngEmbeddedProfile.resolveRenderPlan( file = dngFile, metadata = actualMetadata, 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 22d23b62..79e46531 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt @@ -3,806 +3,392 @@ package com.hinnka.mycamera.raw import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor -import kotlin.math.pow +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.sqrt class DngHdrProfileGainTableGeneratorTest { @Test - fun googleHdrToneCurveMatchesEmbeddedDngSamples() { - val curve = DngProfileToneCurve.googleHdrToneCurvePoints() - - assertEquals(514, curve.size) - assertEquals(0f, curve[0], 0f) - assertEquals(0f, curve[1], 0f) - assertEquals(0.104f, googleToneCurve(0.18f), 0.002f) - assertEquals(0.5f, googleToneCurve(0.5f), 0.0001f) - assertEquals(0.825f, googleToneCurve(0.75f), 0.002f) - assertEquals(1f, curve[curve.lastIndex - 1], 0f) - assertEquals(1f, curve[curve.lastIndex], 0f) + fun bimodalPhotonCaptureKeepsAUsableBrightSyntheticExposure() { + val fixture = loadFixture(BIMODAL_CAPTURE_RESOURCE) + val map = generateMap(fixture) + val blackGains = actualAnchorGains(fixture, map, ToneAnchor.BLACK) + val medianGains = actualAnchorGains(fixture, map, ToneAnchor.MEDIAN) + val medianOutputs = FloatArray(fixture.cellCount) { cell -> + val p50 = sceneSignalForAnchor( + fixture = fixture, + cell = cell, + anchor = ToneAnchor.MEDIAN, + inputScale = map.mapInputWeights.sum() + ) + p50 * medianGains[cell] + } + val blackGainMedian = percentile(blackGains, 0.50f) + val medianOutputMean = medianOutputs.average().toFloat() + assertTrue( + "inputScale=${map.mapInputWeights.sum()}", + map.mapInputWeights.sum() in 0.095f..0.120f + ) + assertTrue("blackGainMedian=$blackGainMedian", blackGainMedian > 1.0f) + assertTrue( + "medianOutputMean=$medianOutputMean blackGainMedian=$blackGainMedian", + medianOutputMean > 0.18f + ) } @Test - fun dngDerivedSceneStatsMatchEmbeddedPixelPgtmSamples() { - val failures = mutableListOf() - DNG_DERIVED_FIXTURES.forEach { fixture -> - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = fixture.width, - height = fixture.height, - baselineExposureEv = fixture.baselineExposureEv, - packedCellStats = packedStatsForTailProfile( - width = fixture.width, - height = fixture.height, - p10 = fixture.rimmP10, - p50 = fixture.rimmP50, - p90 = fixture.rimmP90, - p98 = fixture.rimmP98, - highlightFraction = fixture.rimmHighlightFraction, - tailP95 = fixture.rimmTailP95, - tailP98 = fixture.rimmTailP98, - tailP99 = fixture.rimmTailP99, - maxInput = fixture.rimmMaxInput - ) - ) ?: error("Expected PGTM for ${fixture.sourceName}") + fun skyykingFixturesCoverRealBlackMedianHighlightAndWhiteCases() { + val fixtures = loadFixtures() + assertEquals(12, fixtures.size) + val inputScales = fixtures.map { it.inputScale } + val globalMedians = fixtures.map { fixture -> + percentile(cellStats(fixture, STAT_P50), 0.50f) + } + val blackGains = fixtures.flatMap { fixture -> + anchorGains(fixture.expectedGains, fixture.cellCount, ToneAnchor.BLACK).asIterable() + } + + assertTrue("inputScales=$inputScales", inputScales.min() < 0.07f) + assertTrue("inputScales=$inputScales", inputScales.max() > 0.33f) + assertTrue("globalMedians=$globalMedians", globalMedians.min() < 0.10f) + assertTrue("globalMedians=$globalMedians", globalMedians.max() > 0.80f) + assertTrue("blackGainMin=${blackGains.min()}", blackGains.min() < 0.30f) + assertTrue("blackGainMax=${blackGains.max()}", blackGains.max() > 4.50f) + + fixtures.forEach { fixture -> + assertEquals(64, fixture.mapPointsH) + assertEquals(48, fixture.mapPointsV) + assertEquals(ToneAnchor.entries.size, fixture.anchorCount) + assertEquals(fixture.cellCount * CELL_STATS_STRIDE, fixture.packedStats.size) + assertEquals(fixture.cellCount * fixture.anchorCount, fixture.expectedGains.size) + assertEquals(1f, fixture.gamma, 0f) + assertOfficialInputWeights(fixture.inputWeights, fixture.sourceName) + assertEmbeddedSemanticOutputsMonotonic(fixture) + } + } + + @Test + fun generatedMapsMatchEmbeddedSemanticToneDistributions() { + val failures = mutableListOf() + loadFixtures().forEach { fixture -> + val map = generateMap(fixture) assertTrue("${fixture.sourceName} invalid map", map.isValid) - assertToneOutputMonotonic(map) - assertOfficialPgtmInputWeights(map, fixture.sourceName) - failures += nearFailure( - label = "${fixture.sourceName} embedded weight sum", - expected = fixture.embeddedWeightSum, - actual = map.mapInputWeights.sum(), - tolerance = fixture.weightTolerance - ) - failures += nearFailure( - label = "${fixture.sourceName} embedded headroom", - expected = fixture.embeddedInputHeadroom, - actual = effectiveInputHeadroom(map, fixture.baselineExposureEv), - tolerance = fixture.headroomTolerance - ) - val shadowGain = sampleGainAtIndex(map, 0) - if (shadowGain !in fixture.shadowGainRange) { - failures += "${fixture.sourceName} shadow gain=$shadowGain expected=${fixture.shadowGainRange}" + assertMapOutputsMonotonic(map, fixture.sourceName) + assertOfficialInputWeights(map.mapInputWeights, fixture.sourceName) + + val scaleError = relativeError(map.mapInputWeights.sum(), fixture.inputScale) + if (scaleError > MAX_INPUT_SCALE_RELATIVE_ERROR) { + failures += "${fixture.sourceName} inputScale expected=${fixture.inputScale} " + + "actual=${map.mapInputWeights.sum()} relativeError=$scaleError" } - fixture.expectedGainP50?.let { expected -> - failures += medianGainSeriesFailures( - map = map, - tableInputs = fixture.tableInputs ?: DENSE_TABLE_INPUTS, - expectedGains = expected, - tolerance = fixture.gainTolerance, - label = fixture.sourceName + + ToneAnchor.entries.forEach { anchor -> + val expected = anchorGains( + source = fixture.expectedGains, + cellCount = fixture.cellCount, + anchor = anchor ) + val actual = actualAnchorGains(fixture, map, anchor) + DISTRIBUTION_PERCENTILES.forEach { percentile -> + val expectedGain = percentile(expected, percentile) + val actualGain = percentile(actual, percentile) + val errorEv = gainErrorEv(actualGain, expectedGain) + val tolerance = when (percentile) { + 0.50f -> MAX_MEDIAN_GAIN_ERROR_EV + else -> MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV + } + if (errorEv > tolerance) { + failures += "${fixture.sourceName} ${anchor.label} p${(percentile * 100).toInt()} " + + "expected=$expectedGain actual=$actualGain errorEv=$errorEv toleranceEv=$tolerance" + } + } } } assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty()) } @Test - fun googleKeycapDngStatsMatchEmbeddedPgtmLowRangeCurve() { - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = 4096, - height = 3072, - baselineExposureEv = GOOGLE_KEYCAP_BASELINE_EV, - packedCellStats = packedStatsForTailProfile( - width = 4096, - height = 3072, - p10 = 0.272827f, - p50 = 0.344414f, - p90 = 0.406222f, - p98 = 0.429191f, - highlightFraction = 0.038032f, - tailP95 = 0.998236f, - tailP98 = 1.243947f, - tailP99 = 1.443504f, - maxInput = 2.448398f - ) - ) ?: error("Expected Google keycap DNG PGTM") - - assertTrue(map.isValid) - assertToneOutputMonotonic(map) - assertEquals(GOOGLE_KEYCAP_PGTM_WEIGHT_SUM, map.mapInputWeights.sum(), 0.045f) - assertGainNear(map, tableInput = 0.005f, expected = 2.95f, tolerance = 0.38f) - assertGainNear(map, tableInput = 0.010f, expected = 2.95f, tolerance = 0.36f) - assertGainNear(map, tableInput = 0.015f, expected = 2.95f, tolerance = 0.35f) - assertGainNear(map, tableInput = 0.02f, expected = 2.95f, tolerance = 0.34f) - assertGainNear(map, tableInput = 0.03f, expected = 2.86f, tolerance = 0.30f) - assertGainNear(map, tableInput = 0.04f, expected = 2.73f, tolerance = 0.28f) - assertGainNear(map, tableInput = 0.05f, expected = 2.61f, tolerance = 0.24f) - assertGainNear(map, tableInput = 0.06f, expected = 2.50f, tolerance = 0.22f) - assertGainNear(map, tableInput = 0.07f, expected = 2.41f, tolerance = 0.20f) - assertGainNear(map, tableInput = 0.08f, expected = 2.32f, tolerance = 0.18f) - assertGainNear(map, tableInput = 0.09f, expected = 2.24f, tolerance = 0.17f) - assertGainNear(map, tableInput = 0.10f, expected = 2.16f, tolerance = 0.16f) - assertGainNear(map, tableInput = 0.11f, expected = 2.09f, tolerance = 0.15f) - assertGainNear(map, tableInput = 0.12f, expected = 2.03f, tolerance = 0.14f) - assertGainNear(map, tableInput = 0.13f, expected = 1.97f, tolerance = 0.13f) - assertGainNear(map, tableInput = 0.14f, expected = 1.92f, tolerance = 0.13f) - assertGainNear(map, tableInput = 0.16f, expected = 1.82f, tolerance = 0.13f) - assertGainNear(map, tableInput = 0.18f, expected = 1.73f, tolerance = 0.13f) - assertGainNear(map, tableInput = 0.28f, expected = 1.41f, tolerance = 0.12f) - assertGainNear(map, tableInput = 0.50f, expected = 1.03f, tolerance = 0.08f) - assertGainNear(map, tableInput = 0.75f, expected = 0.80f, tolerance = 0.06f) - assertGainNear(map, tableInput = 1.00f, expected = 0.666f, tolerance = 0.025f) - assertGoogleKeycapLowRangeOutputProfile(map) - assertTrue("darkOutput=${0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum())}", - 0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum()) > 0.075f - ) - assertTrue("midOutput=${0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum())}", - 0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum()) in 0.33f..0.41f - ) + fun generatedMapsMatchEmbeddedPerCellToneShape() { + val failures = mutableListOf() + loadFixtures().forEach { fixture -> + val map = generateMap(fixture) + ToneAnchor.entries + .filterNot { it == ToneAnchor.ENDPOINT } + .forEach { anchor -> + val expected = anchorGains( + source = fixture.expectedGains, + cellCount = fixture.cellCount, + anchor = anchor + ) + val actual = actualAnchorGains(fixture, map, anchor) + val rmseEv = logGainRmseEv(actual, expected) + if (rmseEv > MAX_PER_CELL_GAIN_RMSE_EV) { + failures += "${fixture.sourceName} ${anchor.label} perCellRmseEv=$rmseEv " + + "toleranceEv=$MAX_PER_CELL_GAIN_RMSE_EV" + } + } + } + assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty()) } - @Test - fun googleProvidedDngStatsMatchEmbeddedPgtmContrastCurve() { - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = 4096, - height = 3072, - baselineExposureEv = 1.20f, - packedCellStats = packedStatsForTailProfile( - width = 4096, - height = 3072, - p10 = 0.283845f, - p50 = 0.356112f, - p90 = 0.436304f, - p98 = 0.468235f, - highlightFraction = 0.057847f, - tailP95 = 1.277153f, - tailP98 = 1.660754f, - tailP99 = 2.696633f, - maxInput = 3.887637f - ) - ) ?: error("Expected Google provided DNG PGTM") - - assertTrue(map.isValid) - assertToneOutputMonotonic(map) - assertEquals(0.6720394f, map.mapInputWeights.sum(), 0.035f) - assertGainSeriesNear( - map = map, - tableInputs = floatArrayOf(0.005f, 0.020f, 0.050f, 0.080f, 0.100f, 0.140f, 0.180f, 0.280f, 0.500f, 0.750f, 1.000f), - expectedGains = floatArrayOf(3.005f, 3.005f, 2.644f, 2.341f, 2.182f, 1.930f, 1.740f, 1.413f, 1.030f, 0.808f, 0.674f), - tolerance = 0.18f - ) - assertTrue("darkOutput=${0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum())}", - 0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum()) < 0.092f - ) - assertTrue("midOutput=${0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum())}", - 0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum()) in 0.32f..0.39f - ) + private fun generateMap(fixture: PgtmFixture): DngProfileGainTableMap { + return DngHdrProfileGainTableGenerator.forCellStats( + width = fixture.width, + height = fixture.height, + baselineExposureEv = fixture.baselineExposureEv, + packedCellStats = fixture.packedStats + ) ?: error("Expected PGTM for ${fixture.sourceName}") } - @Test - fun localExposureOffsetDoesNotCreateExtraLift() { - val width = 4096 - val height = 3072 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = 1.20f, - packedCellStats = packedStatsWithExposureOffsetRegion(width, height) - ) ?: error("Expected PGTM for exposure-offset stats") - - val darkRegionCell = 0 - val centerCell = (grid[1] / 2) * grid[0] + grid[0] / 2 - val darkLowGain = sampleGain(map, 0.08f, darkRegionCell) - val centerLowGain = sampleGain(map, 0.08f, centerCell) - val darkMidGain = sampleGain(map, 0.18f, darkRegionCell) - val centerMidGain = sampleGain(map, 0.18f, centerCell) - - assertTrue( - "darkLowGain=$darkLowGain centerLowGain=$centerLowGain", - darkLowGain <= centerLowGain * 1.06f - ) - assertTrue( - "darkMidGain=$darkMidGain centerMidGain=$centerMidGain", - darkMidGain <= centerMidGain * 1.05f - ) - } - - private fun packedStatsForTailProfile( - width: Int, - height: Int, - p10: Float, - p50: Float, - p90: Float, - p98: Float, - highlightFraction: Float, - tailP95: Float, - tailP98: Float, - tailP99: Float, - maxInput: Float, + private fun actualAnchorGains( + fixture: PgtmFixture, + map: DngProfileGainTableMap, + anchor: ToneAnchor, ): FloatArray { - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - return FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE).also { stats -> - for (cell in 0 until cellCount) { - val rank = (cell + 1).toFloat() / cellCount.toFloat() - val tail = when { - rank <= 0.95f -> lerp(p98, tailP95, rank / 0.95f) - rank <= 0.98f -> lerp(tailP95, tailP98, (rank - 0.95f) / 0.03f) - rank <= 0.99f -> lerp(tailP98, tailP99, (rank - 0.98f) / 0.01f) - else -> lerp(tailP99, maxInput, (rank - 0.99f) / 0.01f) - } - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = p10 - stats[offset + 1] = p50 - stats[offset + 2] = p90 - stats[offset + 3] = p98.coerceIn(0f, 1f) - stats[offset + 4] = highlightFraction - stats[offset + 5] = 64f - stats[offset + 6] = tail - stats[offset + 7] = tail - } + val inputScale = map.mapInputWeights.sum() + return FloatArray(fixture.cellCount) { cell -> + val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, inputScale) + val tableInput = if (anchor == ToneAnchor.ENDPOINT) 1f else sceneSignal * inputScale + sampleGain(map, tableInput, cell) } } - private fun packedStatsWithExposureOffsetRegion(width: Int, height: Int): FloatArray { - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - return FloatArray(cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE).also { stats -> - for (y in 0 until grid[1]) { - for (x in 0 until grid[0]) { - val cell = y * grid[0] + x - val exposureScale = if (x < grid[0] / 3 && y < grid[1] / 3) 0.62f else 1f - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - stats[offset] = 0.14f * exposureScale - stats[offset + 1] = 0.22f * exposureScale - stats[offset + 2] = 0.34f * exposureScale - stats[offset + 3] = 0.42f * exposureScale - stats[offset + 4] = 0.018f - stats[offset + 5] = 64f - stats[offset + 6] = 1.08f * exposureScale - stats[offset + 7] = 1.36f * exposureScale - } - } - } - } - - private fun assertToneOutputMonotonic(map: DngProfileGainTableMap) { - val pointCount = map.mapPointsN - val cellCount = map.mapPointsH * map.mapPointsV - for (cell in 0 until cellCount) { + private fun assertEmbeddedSemanticOutputsMonotonic(fixture: PgtmFixture) { + for (cell in 0 until fixture.cellCount) { var previousOutput = 0f - val offset = cell * pointCount - for (index in 0 until pointCount) { - val input = tableInputForIndex(index, pointCount) - val output = input * map.gains[offset + index] + ToneAnchor.entries.forEach { anchor -> + val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, fixture.inputScale) + val gain = fixture.expectedGains[cell * fixture.anchorCount + anchor.ordinal] + val tableInput = if (anchor == ToneAnchor.ENDPOINT) { + 1f + } else { + (sceneSignal * fixture.inputScale).coerceIn(0f, 1f) + } + val output = tableInput * gain assertTrue( - "cell=$cell index=$index output=$output previous=$previousOutput", - output + 0.0001f >= previousOutput + "${fixture.sourceName} cell=$cell anchor=${anchor.label} output=$output previous=$previousOutput", + output + OUTPUT_EPS >= previousOutput ) - previousOutput = maxOf(previousOutput, output) + previousOutput = max(previousOutput, output) } } } - private fun sampleGain(map: DngProfileGainTableMap, input: Float): Float { - return sampleGain(map, input, cellIndex = 0) - } - - private fun sampleGain(map: DngProfileGainTableMap, input: Float, cellIndex: Int): Float { - val clamped = input.coerceIn(0f, 1f) - val scaled = clamped * map.mapPointsN.coerceAtLeast(1) - val i0 = scaled.toInt().coerceIn(0, map.mapPointsN - 1) - val i1 = (i0 + 1).coerceIn(0, map.mapPointsN - 1) - val t = scaled - i0.toFloat() - val offset = cellIndex.coerceIn(0, map.mapPointsH * map.mapPointsV - 1) * map.mapPointsN - return map.gains[offset + i0] * (1f - t) + map.gains[offset + i1] * t - } - - private fun sampleMedianGain(map: DngProfileGainTableMap, input: Float): Float { - val cellCount = map.mapPointsH * map.mapPointsV - val gains = FloatArray(cellCount) { cell -> sampleGain(map, input, cell) } - return percentile(gains, 0.50f) - } - - private fun sampleGainAtIndex(map: DngProfileGainTableMap, index: Int): Float { - return map.gains[index.coerceIn(0, map.mapPointsN - 1)] - } - - private fun renderedOutputForPostBaselineSignal(map: DngProfileGainTableMap, input: Float): Float { - val tableInput = (input.coerceAtLeast(0f) * map.mapInputWeights.sum()).coerceIn(0f, 1f) - return input * sampleGain(map, tableInput) - } - - private fun effectiveInputHeadroom(map: DngProfileGainTableMap, baselineExposureEv: Float): Float { - return map.mapInputWeights.sum() * 2.0f.pow(baselineExposureEv) - } - - private fun googleToneCurve(input: Float): Float { - return curveSample(DngProfileToneCurve.googleHdrToneCurvePoints(), input) - } - - private fun lerp(a: Float, b: Float, t: Float): Float { - return a + (b - a) * t.coerceIn(0f, 1f) - } - - private fun curveSample(points: FloatArray, input: Float): Float { - val x = input.coerceIn(0f, 1f) - var segment = 0 - while (segment < points.size / 2 - 2 && x > points[(segment + 1) * 2]) { - segment++ + private fun assertMapOutputsMonotonic(map: DngProfileGainTableMap, sourceName: String) { + for (cell in 0 until map.mapPointsH * map.mapPointsV) { + var previousOutput = 0f + for (index in 0 until map.mapPointsN) { + val input = tableInputForIndex(index, map.mapPointsN) + val output = input * map.gains[cell * map.mapPointsN + index] + assertTrue( + "$sourceName cell=$cell index=$index output=$output previous=$previousOutput", + output + OUTPUT_EPS >= previousOutput + ) + previousOutput = max(previousOutput, output) + } } - val x0 = points[segment * 2] - val y0 = points[segment * 2 + 1] - val x1 = points[(segment + 1) * 2] - val y1 = points[(segment + 1) * 2 + 1] - val t = if (x1 == x0) 0f else ((x - x0) / (x1 - x0)).coerceIn(0f, 1f) - return y0 + (y1 - y0) * t + } + + private fun sceneSignalForAnchor( + fixture: PgtmFixture, + cell: Int, + anchor: ToneAnchor, + inputScale: Float, + ): Float { + val offset = cell * CELL_STATS_STRIDE + val p10 = fixture.packedStats[offset + STAT_P10].coerceIn(0f, 1f) + val p50 = max(p10, fixture.packedStats[offset + STAT_P50].coerceIn(0f, 1f)) + val p90 = max(p50, fixture.packedStats[offset + STAT_P90].coerceIn(0f, 1f)) + val p98 = max(p90, fixture.packedStats[offset + STAT_P98].coerceIn(0f, 1f)) + val p995 = max(p98, fixture.packedStats[offset + STAT_P995].takeIf { it > 0f } ?: p98) + val p999 = max(p995, fixture.packedStats[offset + STAT_P999].takeIf { it > 0f } ?: p995) + return when (anchor) { + ToneAnchor.BLACK -> 0f + ToneAnchor.SHADOW -> p10 + ToneAnchor.DARK -> 0.5f * (p10 + p50) + ToneAnchor.MEDIAN -> p50 + ToneAnchor.BRIGHT -> p90 + ToneAnchor.HIGHLIGHT -> p98 + ToneAnchor.WHITE -> p995 + ToneAnchor.SPECULAR -> p999 + ToneAnchor.ENDPOINT -> 1f / inputScale.coerceAtLeast(1e-6f) + } + } + + private fun anchorGains( + source: FloatArray, + cellCount: Int, + anchor: ToneAnchor, + ): FloatArray { + return FloatArray(cellCount) { cell -> + source[cell * ToneAnchor.entries.size + anchor.ordinal] + } + } + + private fun cellStats(fixture: PgtmFixture, stat: Int): FloatArray { + return FloatArray(fixture.cellCount) { cell -> + fixture.packedStats[cell * CELL_STATS_STRIDE + stat] + } + } + + private fun sampleGain(map: DngProfileGainTableMap, input: Float, cell: Int): Float { + val scaled = input.coerceIn(0f, 1f) * map.mapPointsN.coerceAtLeast(1) + val index0 = scaled.toInt().coerceIn(0, map.mapPointsN - 1) + val index1 = (index0 + 1).coerceIn(0, map.mapPointsN - 1) + val fraction = scaled - index0 + val offset = cell.coerceIn(0, map.mapPointsH * map.mapPointsV - 1) * map.mapPointsN + return map.gains[offset + index0] * (1f - fraction) + + map.gains[offset + index1] * fraction } private fun tableInputForIndex(index: Int, pointCount: Int): Float { if (pointCount <= 1) return 0f - return if (index == pointCount - 1) { - 1f - } else { - index.toFloat() / pointCount.toFloat() - } + return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat() } - private fun assertGainNear( - map: DngProfileGainTableMap, - tableInput: Float, - expected: Float, - tolerance: Float, - ) { - val actual = sampleGain(map, tableInput) - assertEquals("tableInput=$tableInput actual=$actual expected=$expected", expected, actual, tolerance) - } - - private fun assertGainSeriesNear( - map: DngProfileGainTableMap, - tableInputs: FloatArray, - expectedGains: FloatArray, - tolerance: Float, - label: String = "PGTM", - ) { - require(tableInputs.size == expectedGains.size) - val failures = tableInputs.indices.mapNotNull { index -> - val input = tableInputs[index] - val expected = expectedGains[index] - val actual = sampleGain(map, input) - if (abs(actual - expected) <= tolerance) { - null - } else { - "$label tableInput=$input actual=$actual expected=$expected" - } - } - assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty()) - } - - private fun medianGainSeriesFailures( - map: DngProfileGainTableMap, - tableInputs: FloatArray, - expectedGains: FloatArray, - tolerance: Float, - label: String, - ): List { - require(tableInputs.size == expectedGains.size) - return tableInputs.indices.mapNotNull { index -> - val input = tableInputs[index] - val expected = expectedGains[index] - val actual = sampleMedianGain(map, input) - if (abs(actual - expected) <= tolerance) { - null - } else { - "$label p50Gain tableInput=$input actual=$actual expected=$expected" - } + private fun assertOfficialInputWeights(weights: FloatArray, sourceName: String) { + val sum = weights.sum() + assertTrue("$sourceName invalid weight sum=$sum", sum.isFinite() && sum > 0f) + OFFICIAL_INPUT_WEIGHTS.forEachIndexed { index, expected -> + assertEquals("$sourceName weight[$index]", expected, weights[index] / sum, 0.0001f) } } private fun percentile(values: FloatArray, percentile: Float): Float { if (values.isEmpty()) return 0f - values.sort() - val k = (values.size - 1).toFloat() * percentile.coerceIn(0f, 1f) - val lo = floor(k).toInt() - val hi = ceil(k).toInt() - if (lo == hi) return values[lo] - return values[lo] * (hi - k) + values[hi] * (k - lo) + val sorted = values.copyOf().also { it.sort() } + val rank = (sorted.size - 1).toFloat() * percentile.coerceIn(0f, 1f) + val lower = floor(rank).toInt() + val upper = ceil(rank).toInt() + if (lower == upper) return sorted[lower] + return sorted[lower] * (upper - rank) + sorted[upper] * (rank - lower) } - private fun nearFailure( - label: String, - expected: Float, - actual: Float, - tolerance: Float, - ): List { - return if (abs(actual - expected) <= tolerance) { - emptyList() - } else { - listOf("$label actual=$actual expected=$expected tolerance=$tolerance") - } + private fun relativeError(actual: Float, expected: Float): Float { + return abs(actual - expected) / max(abs(expected), 1e-6f) } - private fun assertOfficialPgtmInputWeights(map: DngProfileGainTableMap, sourceName: String) { - val normalizedWeights = map.mapInputWeights.map { it / map.mapInputWeights.sum() } - assertEquals("$sourceName weight R", 0.1495f, normalizedWeights[0], 0.0001f) - assertEquals("$sourceName weight G", 0.2935f, normalizedWeights[1], 0.0001f) - assertEquals("$sourceName weight B", 0.0570f, normalizedWeights[2], 0.0001f) - assertEquals("$sourceName weight min", 0.1250f, normalizedWeights[3], 0.0001f) - assertEquals("$sourceName weight max", 0.3750f, normalizedWeights[4], 0.0001f) + private fun gainErrorEv(actual: Float, expected: Float): Float { + return abs(log2(actual.coerceAtLeast(1e-6f) / expected.coerceAtLeast(1e-6f))) } - private fun assertGoogleKeycapLowRangeOutputProfile(map: DngProfileGainTableMap) { - val samples = floatArrayOf( - 0.080f, 0.085f, 0.090f, 0.095f, 0.100f, 0.105f, 0.110f, - 0.115f, 0.120f, 0.125f, 0.130f, 0.135f, 0.140f - ) - val expectedOutputs = floatArrayOf( - 0.185364f, 0.193387f, 0.201181f, 0.208760f, 0.216135f, 0.223304f, 0.230243f, - 0.237050f, 0.243581f, 0.249959f, 0.256297f, 0.262396f, 0.268389f - ) - val expectedSlopes = floatArrayOf( - 1.604631f, 1.558854f, 1.515782f, 1.474917f, 1.433899f, 1.387858f, - 1.361360f, 1.306116f, 1.275739f, 1.267608f, 1.219756f, 1.198601f - ) - val outputs = samples.map { input -> input * sampleGain(map, input) } - outputs.forEachIndexed { index, output -> - assertEquals( - "lowRangeOutput tableInput=${samples[index]} actual=$output expected=${expectedOutputs[index]}", - expectedOutputs[index], - output, - 0.007f - ) - } - val slopes = outputs.zipWithNext().mapIndexed { index, (a, b) -> - (b - a) / (samples[index + 1] - samples[index]) - } - slopes.forEachIndexed { index, slope -> - assertEquals( - "lowRangeSlope tableInput=${samples[index]}..${samples[index + 1]} " + - "actual=$slope expected=${expectedSlopes[index]}", - expectedSlopes[index], - slope, - 0.17f - ) - } + private fun logGainRmseEv(actual: FloatArray, expected: FloatArray): Float { + require(actual.size == expected.size) + val meanSquare = actual.indices.sumOf { index -> + val error = log2(actual[index].coerceAtLeast(1e-6f) / expected[index].coerceAtLeast(1e-6f)) + (error * error).toDouble() + } / actual.size.coerceAtLeast(1).toDouble() + return sqrt(meanSquare).toFloat() } - private companion object { - private const val GOOGLE_KEYCAP_BASELINE_EV = 1.46f - private const val GOOGLE_KEYCAP_PGTM_HEADROOM = 1.8273006f - private const val GOOGLE_KEYCAP_PGTM_WEIGHT_SUM = 0.6642112f + private fun log2(value: Float): Float { + return (ln(value.coerceAtLeast(1e-6f).toDouble()) / ln(2.0)).toFloat() + } - private val DENSE_TABLE_INPUTS = floatArrayOf( - 0.0000f, 0.0025f, 0.0050f, 0.0075f, 0.0100f, 0.0150f, 0.0200f, 0.0275f, - 0.0350f, 0.0450f, 0.0500f, 0.0575f, 0.0650f, 0.0725f, 0.0800f, 0.0900f, - 0.1000f, 0.1100f, 0.1200f, 0.1300f, 0.1400f, 0.1600f, 0.1800f, 0.2200f, - 0.2500f, 0.2800f, 0.3200f, 0.3600f, 0.4200f, 0.5000f, 0.6000f, 0.7000f, - 0.7500f, 0.8200f, 0.9000f, 0.9500f, 1.0000f - ) + private fun loadFixtures(): List = FIXTURE_RESOURCES.map(::loadFixture) - private val BALANCED_TABLE_INPUTS = floatArrayOf( - 0.0000f, 0.0025f, 0.0050f, 0.0075f, 0.0100f, 0.0150f, 0.0200f, 0.0275f, - 0.0350f, 0.0450f, 0.0500f, 0.0575f, 0.0650f, 0.0725f, 0.0800f, 0.0900f, - 0.1000f, 0.1100f, 0.1200f, 0.1300f, 0.1400f, 0.1550f, 0.1800f, 0.2000f, - 0.2200f, 0.2500f, 0.2800f, 0.3200f, 0.3600f, 0.4200f, 0.5000f, 0.5800f, - 0.6600f, 0.7000f, 0.7500f, 0.8200f, 0.8800f, 0.9000f, 0.9300f, 0.9500f, - 0.9650f, 0.9800f, 0.9900f, 0.9950f, 0.9975f, 1.0000f - ) - - private val DNG_DERIVED_FIXTURES = listOf( - DngDerivedPgtmFixture( - sourceName = "PXL_20260704_204337991.RAW-02.ORIGINAL.dng", - width = 4080, - height = 3064, - baselineExposureEv = 0.33f, - embeddedWeightSum = 0.9379541f, - embeddedInputHeadroom = 1.1790208f, - rimmP10 = 0.069055f, - rimmP50 = 0.091839f, - rimmP90 = 0.116540f, - rimmP98 = 0.124434f, - rimmHighlightFraction = 0.000000f, - rimmTailP95 = 0.355279f, - rimmTailP98 = 0.404056f, - rimmTailP99 = 0.436914f, - rimmMaxInput = 0.490112f, - shadowGainRange = 1.6f..2.6f, - tableInputs = BALANCED_TABLE_INPUTS, - expectedGainP50 = floatArrayOf( - 2.029536f, 2.029536f, 2.029536f, 2.029536f, 2.029536f, 2.029536f, - 2.029536f, 2.017259f, 1.995904f, 1.967620f, 1.953729f, 1.933178f, - 1.912756f, 1.893285f, 1.874177f, 1.850001f, 1.826695f, 1.803774f, - 1.781545f, 1.759975f, 1.739228f, 1.709089f, 1.661411f, 1.625170f, - 1.590684f, 1.542494f, 1.496576f, 1.440400f, 1.391709f, 1.328843f, - 1.252524f, 1.185841f, 1.126924f, 1.100058f, 1.068626f, 1.028111f, - 0.996195f, 0.986084f, 0.971375f, 0.961862f, 0.954873f, 0.948007f, - 0.943496f, 0.941260f, 0.940765f, 0.940765f - ), - gainTolerance = 0.17f, - weightTolerance = 0.055f, - headroomTolerance = 0.08f - ), - DngDerivedPgtmFixture( - sourceName = "PXL_20260628_175619159.RAW-02.ORIGINAL.dng", - width = 2048, - height = 1536, - baselineExposureEv = 0.99f, - embeddedWeightSum = 0.5074623f, - embeddedInputHeadroom = 1.0079140f, - rimmP10 = 0.235049f, - rimmP50 = 0.321880f, - rimmP90 = 0.440227f, - rimmP98 = 0.491983f, - rimmHighlightFraction = 0.237798f, - rimmTailP95 = 1.795726f, - rimmTailP98 = 1.870457f, - rimmTailP99 = 2.331631f, - rimmMaxInput = 3.247468f, - shadowGainRange = 2.6f..4.3f, - expectedGainP50 = floatArrayOf( - 3.461338f, 3.461338f, 3.461338f, 3.461338f, 3.461338f, 3.461338f, - 3.461338f, 3.336530f, 3.133802f, 2.898788f, 2.795193f, 2.655045f, - 2.531542f, 2.420754f, 2.322193f, 2.203573f, 2.099504f, 2.006125f, - 1.922472f, 1.846751f, 1.777360f, 1.656811f, 1.554421f, 1.389232f, - 1.288567f, 1.202840f, 1.105987f, 1.025570f, 0.927419f, 0.825583f, - 0.728947f, 0.654740f, 0.623655f, 0.585323f, 0.547510f, 0.526535f, - 0.508728f - ), - gainTolerance = 0.30f - ), - DngDerivedPgtmFixture( - sourceName = "PXL_20260629_213614190.RAW-02.ORIGINAL.dng", - width = 4096, - height = 3072, - baselineExposureEv = 1.40f, - embeddedWeightSum = 0.7948943f, - embeddedInputHeadroom = 2.0977387f, - rimmP10 = 0.269476f, - rimmP50 = 0.340033f, - rimmP90 = 0.412840f, - rimmP98 = 0.441493f, - rimmHighlightFraction = 0.012258f, - rimmTailP95 = 0.923412f, - rimmTailP98 = 1.318924f, - rimmTailP99 = 1.545061f, - rimmMaxInput = 4.766730f, - shadowGainRange = 2.0f..3.4f, - expectedGainP50 = floatArrayOf( - 2.433881f, 2.433881f, 2.433881f, 2.433881f, 2.433881f, 2.433881f, - 2.433881f, 2.405049f, 2.354992f, 2.291888f, 2.261898f, 2.218633f, - 2.177582f, 2.138278f, 2.100938f, 2.053486f, 2.008828f, 1.966325f, - 1.926189f, 1.887988f, 1.851621f, 1.783574f, 1.721598f, 1.612500f, - 1.541297f, 1.476947f, 1.400079f, 1.332454f, 1.244926f, 1.147889f, - 1.049181f, 0.968663f, 0.933662f, 0.889399f, 0.844497f, 0.819041f, - 0.797114f - ), - gainTolerance = 0.24f - ), - DngDerivedPgtmFixture( - sourceName = "PXL_20260630_100426253.RAW-02.ORIGINAL.dng", - width = 4096, - height = 3072, - baselineExposureEv = 1.83f, - embeddedWeightSum = 0.6975967f, - embeddedInputHeadroom = 2.4802149f, - rimmP10 = 0.307800f, - rimmP50 = 0.351503f, - rimmP90 = 0.426102f, - rimmP98 = 0.469566f, - rimmHighlightFraction = 0.261387f, - rimmTailP95 = 1.823842f, - rimmTailP98 = 1.920961f, - rimmTailP99 = 1.969608f, - rimmMaxInput = 2.072667f, - shadowGainRange = 2.2f..3.8f, - expectedGainP50 = floatArrayOf( - 2.938126f, 2.938126f, 2.938126f, 2.938126f, 2.938126f, 2.938126f, - 2.938126f, 2.891436f, 2.792942f, 2.669011f, 2.614738f, 2.538647f, - 2.467955f, 2.402280f, 2.341392f, 2.264403f, 2.195177f, 2.130476f, - 2.070314f, 2.013801f, 1.961176f, 1.865585f, 1.779446f, 1.633619f, - 1.540570f, 1.458329f, 1.360819f, 1.278129f, 1.174516f, 1.065314f, - 0.958356f, 0.873501f, 0.837248f, 0.791938f, 0.746611f, 0.721189f, - 0.699442f - ), - gainTolerance = 0.26f - ), - DngDerivedPgtmFixture( - sourceName = "PXL_20260702_144246096.RAW-02.ORIGINAL.dng", - width = 4096, - height = 3072, - baselineExposureEv = GOOGLE_KEYCAP_BASELINE_EV, - embeddedWeightSum = GOOGLE_KEYCAP_PGTM_WEIGHT_SUM, - embeddedInputHeadroom = GOOGLE_KEYCAP_PGTM_HEADROOM, - rimmP10 = 0.272827f, - rimmP50 = 0.344414f, - rimmP90 = 0.406222f, - rimmP98 = 0.429191f, - rimmHighlightFraction = 0.038032f, - rimmTailP95 = 0.998236f, - rimmTailP98 = 1.243947f, - rimmTailP99 = 1.443504f, - rimmMaxInput = 2.448398f, - shadowGainRange = 2.3f..3.3f - ), - DngDerivedPgtmFixture( - sourceName = "PXL_20260702_230446193.RAW-02.ORIGINAL.dng", - width = 4096, - height = 3072, - baselineExposureEv = 1.20f, - embeddedWeightSum = 0.6720394f, - embeddedInputHeadroom = 1.5439412f, - rimmP10 = 0.283880f, - rimmP50 = 0.356135f, - rimmP90 = 0.436290f, - rimmP98 = 0.468236f, - rimmHighlightFraction = 0.057847f, - rimmTailP95 = 1.277153f, - rimmTailP98 = 1.660754f, - rimmTailP99 = 2.696633f, - rimmMaxInput = 3.887637f, - shadowGainRange = 2.2f..3.7f, - expectedGainP50 = floatArrayOf( - 2.988932f, 2.988932f, 2.988932f, 2.988932f, 2.988932f, 2.988932f, - 2.988932f, 2.929580f, 2.823456f, 2.691936f, 2.632088f, 2.547884f, - 2.469565f, 2.396644f, 2.329094f, 2.246051f, 2.170225f, 2.101044f, - 2.036580f, 1.977289f, 1.921968f, 1.823052f, 1.735409f, 1.588058f, - 1.494819f, 1.414782f, 1.322162f, 1.242386f, 1.141060f, 1.032854f, - 0.927313f, 0.843980f, 0.808448f, 0.764127f, 0.719831f, 0.695016f, - 0.673810f - ), - gainTolerance = 0.26f - ), - DngDerivedPgtmFixture( - sourceName = "PhotonCamera_20260704_223804.dng", - width = 4096, - height = 3072, - baselineExposureEv = 0.98f, - embeddedWeightSum = 0.8365770f, - embeddedInputHeadroom = 1.6501193f, - rimmP10 = 0.204276f, - rimmP50 = 0.257364f, - rimmP90 = 0.328286f, - rimmP98 = 0.365104f, - rimmHighlightFraction = 0.055410f, - rimmTailP95 = 1.035434f, - rimmTailP98 = 1.170545f, - rimmTailP99 = 1.230469f, - rimmMaxInput = 1.313306f, - shadowGainRange = 1.7f..3.4f, - tableInputs = BALANCED_TABLE_INPUTS, - expectedGainP50 = floatArrayOf( - 2.332110f, 2.332110f, 2.332110f, 2.332110f, 2.332110f, 2.332110f, - 2.332110f, 2.308193f, 2.267080f, 2.215131f, 2.190485f, 2.155483f, - 2.122859f, 2.091421f, 2.060914f, 2.025000f, 1.991229f, 1.957812f, - 1.925079f, 1.893913f, 1.864003f, 1.820614f, 1.752480f, 1.701844f, - 1.653044f, 1.585271f, 1.521480f, 1.445249f, 1.376621f, 1.287335f, - 1.188969f, 1.108817f, 1.041345f, 1.011167f, 0.976263f, 0.931951f, - 0.897597f, 0.886805f, 0.871180f, 0.861122f, 0.853757f, 0.846541f, - 0.841810f, 0.839468f, 0.838950f, 0.838950f - ), - gainTolerance = 0.070f, - weightTolerance = 0.030f, - headroomTolerance = 0.06f - ), - DngDerivedPgtmFixture( - sourceName = "PhotonCamera_20260705_071801.dng", - width = 4096, - height = 3072, - baselineExposureEv = 1.64f, - embeddedWeightSum = 0.2916877f, - embeddedInputHeadroom = 0.9090933f, - rimmP10 = 0.181586f, - rimmP50 = 0.198066f, - rimmP90 = 0.214809f, - rimmP98 = 0.219718f, - rimmHighlightFraction = 0.161018f, - rimmTailP95 = 3.684094f, - rimmTailP98 = 4.229066f, - rimmTailP99 = 4.396879f, - rimmMaxInput = 4.547501f, - shadowGainRange = 3.0f..3.9f, - expectedGainP50 = floatArrayOf( - 3.565941f, 3.565941f, 3.565941f, 3.565941f, 3.565941f, 3.565941f, - 3.565941f, 3.297646f, 2.915521f, 2.545277f, 2.397049f, 2.210206f, - 2.054406f, 1.922145f, 1.808229f, 1.678387f, 1.568655f, 1.474137f, - 1.391835f, 1.319495f, 1.255099f, 1.145871f, 1.056189f, 0.916869f, - 0.836401f, 0.770297f, 0.698485f, 0.640170f, 0.570436f, 0.499898f, - 0.434713f, 0.385786f, 0.365581f, 0.340904f, 0.316817f, 0.303566f, - 0.292378f - ) - ) + private fun loadFixture(resourceName: String): PgtmFixture { + val bytes = requireNotNull(javaClass.getResourceAsStream(resourceName)) { + "Missing PGTM fixture $resourceName" + }.use { it.readBytes() } + val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) + val magic = ByteArray(FIXTURE_MAGIC.size).also(buffer::get) + require(magic.contentEquals(FIXTURE_MAGIC)) { "Invalid PGTM fixture $resourceName" } + val width = buffer.int + val height = buffer.int + val baselineExposureEv = buffer.float + val mapPointsH = buffer.int + val mapPointsV = buffer.int + val anchorCount = buffer.int + val statCount = buffer.int + val gainCount = buffer.int + val weights = FloatArray(5) { buffer.float } + val gamma = buffer.float + val packedStats = FloatArray(statCount) { buffer.float } + val expectedGains = FloatArray(gainCount) { buffer.float } + require(!buffer.hasRemaining()) { "Unexpected trailing data in $resourceName" } + return PgtmFixture( + sourceName = resourceName.substringAfterLast('/').substringBefore(".pgtfixture"), + width = width, + height = height, + baselineExposureEv = baselineExposureEv, + mapPointsH = mapPointsH, + mapPointsV = mapPointsV, + anchorCount = anchorCount, + inputWeights = weights, + gamma = gamma, + packedStats = packedStats, + expectedGains = expectedGains ) } - @Test - fun testFindGapsInNewDng() { - val statsFile = java.io.File("c:/Users/Hinnka/Projects/PhotonCamera/packed_stats_new.txt") - if (!statsFile.exists()) { - println("packed_stats_new.txt not found!") - return - } - val statsText = statsFile.readText() - val statsFloats = statsText.split(",").map { it.trim().toFloat() }.toFloatArray() - - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = 4096, - height = 3072, - baselineExposureEv = 1.64f, - packedCellStats = statsFloats - )!! - - val cellCount = 3072 - val cells = Array(cellCount) { index -> - val offset = index * 8 - HdrPgtmCellStats( - p10 = statsFloats[offset], - p50 = statsFloats[offset + 1], - p90 = statsFloats[offset + 2], - p98 = statsFloats[offset + 3], - highlightFraction = statsFloats[offset + 4], - p995Input = statsFloats[offset + 6], - p999Input = statsFloats[offset + 7], - inputTailP95 = statsFloats[offset + 6], - inputTailP98 = statsFloats[offset + 6], - inputTailP99 = statsFloats[offset + 7], - maxInput = statsFloats[offset + 7], - sampleWeight = statsFloats[offset + 5] - ) - } - - val googleGainsFile = java.io.File("c:/Users/Hinnka/Projects/PhotonCamera/google_gains_new.txt") - if (!googleGainsFile.exists()) { - println("google_gains_new.txt not found!") - return - } - val googleLines = googleGainsFile.readLines() - - val gaps = mutableListOf() - val t_values = floatArrayOf(0.005f, 0.020f, 0.050f, 0.100f, 0.180f) - - for (cell in 0 until cellCount) { - val x = cell % 64 - val y = cell / 64 - val stats = cells[cell] - val googleVals = googleLines[cell].split(",").map { it.trim().toFloat() } - - for (idx in t_values.indices) { - val google = googleVals[idx] - val actual = sampleGain(map, t_values[idx], cell) - val delta = actual - google - - if (delta < -0.15f) { - gaps.add(String.format("Cell %-4d (x=%-2d y=%-2d) t=%.3f: p10=%.4f p50=%.4f p98=%.4f | Google=%.3f App=%.3f | Delta=%.3f", - cell, x, y, t_values[idx], stats.p10, stats.p50, stats.p98, google, actual, delta)) - } - } - } - - println("CELLS WHERE APP IS DARKER THAN GOOGLE (Delta < -0.15)") - println("=========================================================================") - if (gaps.isEmpty()) { - println("No cells found!") - } else { - gaps.take(100).forEach { println(it) } - println("Total matching gaps: ${gaps.size}") - } - println("=========================================================================") + private enum class ToneAnchor(val label: String) { + BLACK("black"), + SHADOW("shadow-p10"), + DARK("dark-p10-p50"), + MEDIAN("median-p50"), + BRIGHT("bright-p90"), + HIGHLIGHT("highlight-p98"), + WHITE("white-p995"), + SPECULAR("specular-p999"), + ENDPOINT("table-endpoint"), } - private data class DngDerivedPgtmFixture( + private data class PgtmFixture( val sourceName: String, val width: Int, val height: Int, val baselineExposureEv: Float, - val embeddedWeightSum: Float, - val embeddedInputHeadroom: Float, - val rimmP10: Float, - val rimmP50: Float, - val rimmP90: Float, - val rimmP98: Float, - val rimmHighlightFraction: Float, - val rimmTailP95: Float, - val rimmTailP98: Float, - val rimmTailP99: Float, - val rimmMaxInput: Float, - val shadowGainRange: ClosedFloatingPointRange, - val tableInputs: FloatArray? = null, - val expectedGainP50: FloatArray? = null, - val gainTolerance: Float = 0.28f, - val weightTolerance: Float = 0.035f, - val headroomTolerance: Float = 0.10f, - ) + val mapPointsH: Int, + val mapPointsV: Int, + val anchorCount: Int, + val inputWeights: FloatArray, + val gamma: Float, + val packedStats: FloatArray, + val expectedGains: FloatArray, + ) { + val cellCount: Int get() = mapPointsH * mapPointsV + val inputScale: Float get() = inputWeights.sum() + } + + private companion object { + private const val CELL_STATS_STRIDE = 8 + private const val STAT_P10 = 0 + private const val STAT_P50 = 1 + private const val STAT_P90 = 2 + private const val STAT_P98 = 3 + private const val STAT_P995 = 6 + private const val STAT_P999 = 7 + private const val OUTPUT_EPS = 0.0001f + private const val MAX_INPUT_SCALE_RELATIVE_ERROR = 0.12f + private const val MAX_MEDIAN_GAIN_ERROR_EV = 0.22f + private const val MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV = 0.38f + private const val MAX_PER_CELL_GAIN_RMSE_EV = 0.48f + + private val FIXTURE_MAGIC = "PGTFIX2\u0000".toByteArray(Charsets.US_ASCII) + private const val BIMODAL_CAPTURE_RESOURCE = + "/pgtm/captures/PhotonCamera_20260715_173013.pgtfixture" + private val DISTRIBUTION_PERCENTILES = floatArrayOf(0.10f, 0.50f, 0.90f) + private val OFFICIAL_INPUT_WEIGHTS = floatArrayOf(0.1495f, 0.2935f, 0.0570f, 0.1250f, 0.3750f) + private val FIXTURE_RESOURCES = listOf( + "/pgtm/skyyking/Skyyking_20260711_184627.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260711_184751.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260711_185653.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260711_185704.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260711_185836.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260712_105529.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260713_232945.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260714_083737.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260714_092416.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260714_123251.RAW-02.ORIGINAL.pgtfixture", + "/pgtm/skyyking/Skyyking_20260714_151021.RAW-02.ORIGINAL.pgtfixture", + ) + } } diff --git a/scripts/extract_pgtm_regression_fixture.py b/scripts/extract_pgtm_regression_fixture.py index 4bf2268d..65f1295e 100644 --- a/scripts/extract_pgtm_regression_fixture.py +++ b/scripts/extract_pgtm_regression_fixture.py @@ -20,11 +20,25 @@ from analyze_google_pgtm import ( ) -MAGIC = b"PGTFIX1\0" +MAGIC = b"PGTFIX2\0" TAG_SUB_IFDS = 330 TAG_PROFILE_GAIN_TABLE_MAP = 52525 TAG_PROFILE_GAIN_TABLE_MAP2 = 52544 +# These are scene-semantic anchors rather than arbitrary table indices. Every non-terminal anchor +# is converted to the embedded PGTM table domain with that DNG's own input-weight sum. +SEMANTIC_ANCHORS = ( + "black", + "shadow", + "dark", + "median", + "bright", + "highlight", + "white", + "specular", + "endpoint", +) + def read_pgtm_tag(tiff, ifd, tag): entry = ifd.get(tag) @@ -220,7 +234,57 @@ def extract_packed_stats(tiff, ifd0, raw_ifd, raw_offset): return width, height, float(baseline), grid_h, grid_v, packed +def gain_at(pgtm, cell, table_input): + point_count = pgtm["points_n"] + scaled = min(max(table_input, 0.0), 1.0) * max(point_count, 1) + index0 = max(0, min(point_count - 1, int(scaled))) + index1 = max(0, min(point_count - 1, index0 + 1)) + fraction = scaled - index0 + offset = cell * point_count + return ( + pgtm["gains"][offset + index0] * (1.0 - fraction) + + pgtm["gains"][offset + index1] * fraction + ) + + +def semantic_table_inputs(packed_stats, cell, input_scale): + offset = cell * 8 + # Mirror DngHdrProfileGainTableGenerator.packedStatsAt. The exact tail order statistics can + # be slightly below a histogram percentile at a quantization boundary; they describe the + # same ordered signal axis and must therefore be made non-decreasing before sampling PGTM. + p10 = min(max(packed_stats[offset], 0.0), 1.0) + p50 = max(p10, min(max(packed_stats[offset + 1], 0.0), 1.0)) + p90 = max(p50, min(max(packed_stats[offset + 2], 0.0), 1.0)) + p98 = max(p90, min(max(packed_stats[offset + 3], 0.0), 1.0)) + raw_p995 = packed_stats[offset + 6] + p995 = max(p98, raw_p995 if raw_p995 > 0.0 else p98) + raw_p999 = packed_stats[offset + 7] + p999 = max(p995, raw_p999 if raw_p999 > 0.0 else p995) + return ( + 0.0, + p10 * input_scale, + 0.5 * (p10 + p50) * input_scale, + p50 * input_scale, + p90 * input_scale, + p98 * input_scale, + p995 * input_scale, + p999 * input_scale, + 1.0, + ) + + +def sample_semantic_gains(pgtm, packed_stats): + cell_count = pgtm["map_h"] * pgtm["map_v"] + input_scale = sum(pgtm["weights"]) + return [ + gain_at(pgtm, cell, table_input) + for cell in range(cell_count) + for table_input in semantic_table_inputs(packed_stats, cell, input_scale) + ] + + def write_fixture(path, width, height, baseline, pgtm, packed_stats): + sampled_gains = sample_semantic_gains(pgtm, packed_stats) path.parent.mkdir(parents=True, exist_ok=True) with path.open("wb") as out: out.write(MAGIC) @@ -231,44 +295,51 @@ def write_fixture(path, width, height, baseline, pgtm, packed_stats): baseline, pgtm["map_h"], pgtm["map_v"], - pgtm["points_n"], + len(SEMANTIC_ANCHORS), len(packed_stats), - len(pgtm["gains"]), + len(sampled_gains), )) out.write(struct.pack("<5f", *pgtm["weights"])) out.write(struct.pack(" float: + return float(self.weights.sum()) + + +def read_fixture(path: Path) -> Fixture: + data = path.read_bytes() + if data[: len(MAGIC)] != MAGIC: + raise ValueError(f"invalid fixture {path}") + offset = len(MAGIC) + width, height, baseline, map_h, map_v, anchors, stat_count, gain_count = struct.unpack_from( + " float: + order = np.argsort(values) + sorted_values = values[order] + sorted_weights = weights[order] + target = sorted_weights.sum() * percentile + index = int(np.searchsorted(np.cumsum(sorted_weights), target, side="left")) + return float(sorted_values[min(index, len(sorted_values) - 1)]) + + +def sanitize_stats(stats: np.ndarray) -> np.ndarray: + result = stats.copy() + result[:, 0] = np.clip(result[:, 0], 0.0, 1.0) + for column in (1, 2, 3): + result[:, column] = np.maximum(result[:, column - 1], np.clip(result[:, column], 0.0, 1.0)) + result[:, 6] = np.maximum(result[:, 3], np.where(result[:, 6] > 0.0, result[:, 6], result[:, 3])) + result[:, 7] = np.maximum(result[:, 6], np.where(result[:, 7] > 0.0, result[:, 7], result[:, 6])) + return result + + +def global_stats(fixture: Fixture) -> dict[str, float]: + stats = sanitize_stats(fixture.stats) + weights = np.where(np.isfinite(stats[:, 5]) & (stats[:, 5] > 0.0), stats[:, 5], 0.0) + valid = weights > 0.0 + stats = stats[valid] + weights = weights[valid] + means = np.average(stats, axis=0, weights=weights) + return { + "baseline": fixture.baseline_ev, + "p10": means[0], + "p50": means[1], + "p90": means[2], + "p98": means[3], + "hf": means[4], + "p995": means[6], + "p999": means[7], + "tail95": weighted_percentile(stats[:, 6], weights, 0.95), + "tail98": weighted_percentile(stats[:, 6], weights, 0.98), + "tail99": weighted_percentile(stats[:, 7], weights, 0.99), + "max": float(stats[:, 7].max()), + } + + +def log2(value: float | np.ndarray) -> float | np.ndarray: + return np.log2(np.maximum(value, 1e-6)) + + +def feature_values(stats: dict[str, float]) -> dict[str, float]: + return { + "baseline": stats["baseline"], + "p10": stats["p10"], + "p50": stats["p50"], + "p90": stats["p90"], + "p98": stats["p98"], + "sqrt_hf": math.sqrt(stats["hf"]), + "hf": stats["hf"], + "log_p10": log2(stats["p10"] + 0.006), + "log_p50": log2(stats["p50"] + 0.006), + "log_p90": log2(stats["p90"] + 0.006), + "log_p98": log2(stats["p98"] + 0.006), + "log_range": log2((stats["p98"] + 0.006) / (stats["p10"] + 0.006)), + "log_upper": log2((stats["p98"] + 0.006) / (stats["p50"] + 0.006)), + "log_tail95": log2(stats["tail95"] + 0.04), + "log_tail99_95": log2((stats["tail99"] + 0.04) / (stats["tail95"] + 0.04)), + "log_max_99": log2((stats["max"] + 0.04) / (stats["tail99"] + 0.04)), + "log_max_95": log2((stats["max"] + 0.04) / (stats["tail95"] + 0.04)), + } + + +def ridge_fit(x: np.ndarray, y: np.ndarray, regularization: float) -> np.ndarray: + penalty = np.eye(x.shape[1]) * regularization + penalty[0, 0] = 0.0 + return np.linalg.solve(x.T @ x + penalty, x.T @ y) + + +def standardized_matrix( + rows: list[dict[str, float]], + names: tuple[str, ...], +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + values = np.asarray([[row[name] for name in names] for row in rows], dtype=np.float64) + means = values.mean(axis=0) + scales = values.std(axis=0) + scales[scales < 1e-8] = 1.0 + return np.column_stack([np.ones(len(values)), (values - means) / scales]), means, scales + + +def loo_errors(x: np.ndarray, y: np.ndarray, regularization: float) -> np.ndarray: + errors = [] + for holdout in range(len(y)): + keep = np.arange(len(y)) != holdout + coefficients = ridge_fit(x[keep], y[keep], regularization) + errors.append(float(x[holdout] @ coefficients - y[holdout])) + return np.asarray(errors) + + +def select_global_model(rows: list[dict[str, float]], target: np.ndarray, max_features: int) -> tuple: + candidates = tuple(feature_values(rows[0]).keys()) + best = None + for count in range(1, max_features + 1): + for names in itertools.combinations(candidates, count): + x, means, scales = standardized_matrix([feature_values(row) for row in rows], names) + for regularization in (0.01, 0.03, 0.1, 0.3, 1.0, 3.0): + errors = loo_errors(x, target, regularization) + score = math.sqrt(float(np.mean(errors**2))) + 0.15 * float(np.max(np.abs(errors))) + if best is None or score < best[0]: + coefficients = ridge_fit(x, target, regularization) + best = (score, names, regularization, coefficients, means, scales, errors) + assert best is not None + return best + + +def select_calibrated_model( + rows: list[dict[str, float]], + target: np.ndarray, + max_features: int, + max_training_error: float, +) -> tuple: + candidates = tuple(feature_values(rows[0]).keys()) + best = None + for count in range(1, max_features + 1): + for names in itertools.combinations(candidates, count): + x, means, scales = standardized_matrix([feature_values(row) for row in rows], names) + for regularization in (0.000001, 0.000003, 0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003): + coefficients = ridge_fit(x, target, regularization) + training_errors = x @ coefficients - target + maximum = float(np.max(np.abs(training_errors))) + if maximum > max_training_error: + continue + errors = loo_errors(x, target, regularization) + score = ( + count * 0.08 + + math.sqrt(float(np.mean(training_errors**2))) + + 0.08 * math.sqrt(float(np.mean(np.minimum(np.abs(errors), 2.0) ** 2))) + ) + if best is None or score < best[0]: + best = (score, names, regularization, coefficients, means, scales, errors) + if best is not None: + break + if best is None: + raise ValueError(f"no calibrated model reaches max error {max_training_error}") + return best + + +def report_model(label: str, fixtures: list[Fixture], target: np.ndarray, result: tuple) -> None: + score, names, regularization, coefficients, means, scales, errors = result + print(f"\n{label}: features={names} ridge={regularization:g} score={score:.4f}") + print(f" standardized coefficients={coefficients.tolist()}") + raw_coefficients = coefficients[1:] / scales + raw_intercept = coefficients[0] - float(np.dot(raw_coefficients, means)) + print(f" raw intercept={raw_intercept:.9f}") + for name, coefficient in zip(names, raw_coefficients): + print(f" {name:>14s} {coefficient:+.9f}") + fitted = np.column_stack([ + np.ones(len(fixtures)), + (np.asarray([[feature_values(global_stats(f))[name] for name in names] for f in fixtures]) - means) / scales, + ]) @ coefficients + for fixture, expected, actual, error in zip(fixtures, target, fitted, errors): + print( + f" {fixture.path.stem[:31]:31s} target={expected:+.3f} fit={actual:+.3f} " + f"looError={error:+.3f}" + ) + + +def report_calibrated_model( + label: str, + fixtures: list[Fixture], + rows: list[dict[str, float]], + target: np.ndarray, + max_features: int, + max_training_error: float, +) -> None: + try: + result = select_calibrated_model(rows, target, max_features, max_training_error) + except ValueError as error: + print(f"\n{label}: {error}") + return + report_model(label, fixtures, target, result) + + +def smooth_grid(values: np.ndarray, width: int, height: int) -> np.ndarray: + source = values.reshape((height, width, -1)) + padded = np.pad(source, ((1, 1), (1, 1), (0, 0)), mode="edge") + result = ( + 4.0 * padded[1:-1, 1:-1] + + 2.0 * padded[:-2, 1:-1] + + 2.0 * padded[2:, 1:-1] + + 2.0 * padded[1:-1, :-2] + + 2.0 * padded[1:-1, 2:] + + padded[:-2, :-2] + + padded[:-2, 2:] + + padded[2:, :-2] + + padded[2:, 2:] + ) / 16.0 + return result.reshape(values.shape) + + +def local_feature_matrix(fixture: Fixture) -> tuple[np.ndarray, tuple[str, ...]]: + stats = sanitize_stats(fixture.stats) + p10, p50, p90, p98, hf, _, p995, p999 = stats.T + features = np.column_stack([ + log2(p10 + 0.006), + log2(p50 + 0.006), + log2(p90 + 0.006), + log2(p98 + 0.006), + log2((p98 + 0.006) / (p10 + 0.006)), + log2((p98 + 0.006) / (p50 + 0.006)), + np.sqrt(np.clip(hf, 0.0, 1.0)), + log2((p995 + 0.04) / (p98 + 0.04)), + log2((p999 + 0.04) / (p995 + 0.04)), + ]) + names = ( + "log_p10", "log_p50", "log_p90", "log_p98", "full_range", "upper_range", + "sqrt_hf", "tail_995", "tail_999", + ) + return smooth_grid(features, fixture.map_h, fixture.map_v), names + + +def report_spatial_model(fixtures: list[Fixture]) -> None: + matrices = [] + targets = [] + scene_slices = [] + start = 0 + names = () + for fixture in fixtures: + matrix, names = local_feature_matrix(fixture) + matrix -= np.median(matrix, axis=0) + target = log2(fixture.gains[:, 0]) + target -= np.median(target) + matrices.append(matrix) + targets.append(target) + scene_slices.append(slice(start, start + len(target))) + start += len(target) + x = np.vstack(matrices) + y = np.concatenate(targets) + scales = x.std(axis=0) + normalized = x / np.maximum(scales, 1e-6) + coefficients = ridge_fit( + np.column_stack([np.ones(len(normalized)), normalized]), + y, + regularization=30.0, + )[1:] / np.maximum(scales, 1e-6) + predicted = x @ coefficients + print("\nshared spatial black-gain residual model") + for name, coefficient in zip(names, coefficients): + print(f" {name:>14s} {coefficient:+.7f}") + for fixture, scene_slice in zip(fixtures, scene_slices): + error = predicted[scene_slice] - y[scene_slice] + correlation = np.corrcoef(predicted[scene_slice], y[scene_slice])[0, 1] + print( + f" {fixture.path.stem[:31]:31s} rmse={math.sqrt(float(np.mean(error**2))):.3f}EV " + f"p90={np.percentile(np.abs(error), 90):.3f}EV corr={correlation:+.3f}" + ) + + +def semantic_scene_inputs(fixture: Fixture) -> np.ndarray: + stats = sanitize_stats(fixture.stats) + p10, p50, p90, p98, _, _, p995, p999 = stats.T + return np.column_stack([ + p10, + 0.5 * (p10 + p50), + p50, + p90, + p98, + p995, + p999, + ]) + + +def exposure_fusion_gains( + scene_inputs: np.ndarray, + brightest_gains: np.ndarray, + darkest_gain: float, + key_value: float, + sigma_ev: float, +) -> np.ndarray: + scene_inputs = np.minimum(scene_inputs, 1.0 / darkest_gain) + fractions = np.linspace(0.0, 1.0, 8) + exposure_gains = 2.0 ** ( + log2(brightest_gains)[:, None] * (1.0 - fractions)[None, :] + + log2(darkest_gain) * fractions[None, :] + ) + exposed = scene_inputs[:, :, None] * exposure_gains[:, None, :] + distance_ev = log2(np.maximum(exposed, 1e-8) / key_value) + log_weights = -0.5 * (distance_ev / sigma_ev) ** 2 + log_weights -= np.max(log_weights, axis=2, keepdims=True) + weights = np.exp(log_weights) + outputs = np.sum(weights * np.minimum(exposed, 1.0), axis=2) / np.sum(weights, axis=2) + gains = outputs / np.maximum(scene_inputs, 1e-8) + return np.where(scene_inputs <= 1e-8, brightest_gains[:, None], gains) + + +def report_exposure_fusion_grid(fixtures: list[Fixture]) -> None: + best = None + for key_value in np.linspace(0.35, 0.80, 19): + for sigma_ev in np.linspace(0.35, 1.80, 30): + errors = [] + for fixture in fixtures: + predicted = exposure_fusion_gains( + semantic_scene_inputs(fixture), + fixture.gains[:, 0], + fixture.input_scale, + key_value, + sigma_ev, + ) + expected = fixture.gains[:, 1:8] + errors.append(log2(np.maximum(predicted, 1e-8) / np.maximum(expected, 1e-8)).ravel()) + errors = np.concatenate(errors) + score = math.sqrt(float(np.mean(errors**2))) + 0.15 * float(np.percentile(np.abs(errors), 95)) + if best is None or score < best[0]: + best = (score, key_value, sigma_ev, errors) + score, key_value, sigma_ev, errors = best + print( + "\n8-exposure fusion shape " + f"key={key_value:.3f} sigma={sigma_ev:.3f}EV score={score:.4f} " + f"rmse={math.sqrt(float(np.mean(errors**2))):.4f}EV " + f"medianAbs={np.median(np.abs(errors)):.4f}EV " + f"p90Abs={np.percentile(np.abs(errors), 90):.4f}EV " + f"p95Abs={np.percentile(np.abs(errors), 95):.4f}EV" + ) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("fixtures", type=Path) + parser.add_argument("--max-features", type=int, default=4) + args = parser.parse_args() + fixtures = [read_fixture(path) for path in sorted(args.fixtures.glob("*.pgtfixture"))] + rows = [global_stats(fixture) for fixture in fixtures] + print("scene BE scale headroom p10 p50 p90 p98 hf tail95 tail99 max black50") + for fixture, stats in zip(fixtures, rows): + headroom_ev = log2(fixture.input_scale) + fixture.baseline_ev + black_median = float(np.median(fixture.gains[:, 0])) + print( + f"{fixture.path.stem[:31]:31s} {fixture.baseline_ev:4.2f} {fixture.input_scale:.5f} " + f"{headroom_ev:+.3f} {stats['p10']:.3f} {stats['p50']:.3f} {stats['p90']:.3f} " + f"{stats['p98']:.3f} {stats['hf']:.3f} {stats['tail95']:.2f} {stats['tail99']:.2f} " + f"{stats['max']:.2f} {black_median:.3f}" + ) + + headroom_target = np.asarray([log2(f.input_scale) + f.baseline_ev for f in fixtures]) + report_model( + "input headroom EV", + fixtures, + headroom_target, + select_global_model(rows, headroom_target, args.max_features), + ) + report_calibrated_model( + "calibrated input headroom EV", + fixtures, + rows, + headroom_target, + args.max_features, + 0.10, + ) + black_target = np.asarray([log2(np.median(f.gains[:, 0])) for f in fixtures]) + report_model( + "median black-gain EV", + fixtures, + black_target, + select_global_model(rows, black_target, args.max_features), + ) + report_calibrated_model( + "calibrated median black-gain EV", + fixtures, + rows, + black_target, + args.max_features, + 0.12, + ) + report_spatial_model(fixtures) + report_exposure_fusion_grid(fixtures) + + +if __name__ == "__main__": + main()