refactor: combine Photon HDR tone mapping and remove Google Pixel profile

(cherry picked from commit 811ad4ef24)
This commit is contained in:
Hinnka committed 2026-08-01 13:13:02 +08:00
1 parent b6fb42e3e5
commit ef4db92971
41 files changed
+616 -4296

No files matched your search

@@ -319,7 +319,7 @@ class UserPreferencesRepository(private val context: Context) {
private val RAW_AGX_SHOULDER_KEY = floatPreferencesKey("raw_agx_shoulder")
private val RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_filmic_black_relative_exposure")
private val RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY = floatPreferencesKey("raw_filmic_white_relative_exposure")
private val RAW_GOOGLE_PIXEL_TONE_MAP_KEY = booleanPreferencesKey("raw_google_pixel_tone_map")
private val LEGACY_PROFILE_TONE_MAP_KEY = booleanPreferencesKey("raw_google_pixel_tone_map")
private val RAW_OPPO_MASTER_TONE_MAP_KEY = booleanPreferencesKey("raw_oppo_master_tone_map")
private val RAW_PHOTON_PGTM_TONE_MAP_KEY = booleanPreferencesKey("raw_photon_pgtm_tone_map")
private val RAW_NLM_NOISE_FACTOR_KEY = floatPreferencesKey("raw_nlm_noise_factor")
@@ -531,9 +531,10 @@ class UserPreferencesRepository(private val context: Context) {
?: RawToneMappingParameters.FILMIC_BLACK_RELATIVE_EXPOSURE_DEFAULT,
filmicWhiteRelativeExposure = preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY]
?: RawToneMappingParameters.FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
useGooglePixelToneMap = preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] ?: false,
useOppoMasterToneMap = preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] ?: false,
usePhotonPgtmToneMap = preferences[RAW_PHOTON_PGTM_TONE_MAP_KEY] ?: false
usePhotonPgtmToneMap =
(preferences[RAW_PHOTON_PGTM_TONE_MAP_KEY] ?: false) ||
(preferences[LEGACY_PROFILE_TONE_MAP_KEY] ?: false)
).normalized(),
rawNlmNoiseFactor = preferences[RAW_NLM_NOISE_FACTOR_KEY] ?: 0f,
rawExposureCompensation = preferences[RAW_EXPOSURE_COMPENSATION_KEY] ?: 0f,
@@ -1073,7 +1074,7 @@ class UserPreferencesRepository(private val context: Context) {
preferences[RAW_AGX_SHOULDER_KEY] = normalized.agxShoulder
preferences[RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY] = normalized.filmicBlackRelativeExposure
preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.filmicWhiteRelativeExposure
preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] = normalized.useGooglePixelToneMap
preferences[LEGACY_PROFILE_TONE_MAP_KEY] = false
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
preferences[RAW_PHOTON_PGTM_TONE_MAP_KEY] = normalized.usePhotonPgtmToneMap
}
@@ -2242,7 +2243,7 @@ class UserPreferencesRepository(private val context: Context) {
preferences[RAW_AGX_SHOULDER_KEY] = normalized.agxShoulder
preferences[RAW_FILMIC_BLACK_RELATIVE_EXPOSURE_KEY] = normalized.filmicBlackRelativeExposure
preferences[RAW_FILMIC_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.filmicWhiteRelativeExposure
preferences[RAW_GOOGLE_PIXEL_TONE_MAP_KEY] = normalized.useGooglePixelToneMap
preferences[LEGACY_PROFILE_TONE_MAP_KEY] = false
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
preferences[RAW_PHOTON_PGTM_TONE_MAP_KEY] = normalized.usePhotonPgtmToneMap
}
@@ -3775,8 +3775,7 @@ object GalleryManager {
!mainFlashFired &&
resolveRawAutoExposure(context, metadata) &&
kotlin.math.abs(metadata.rawExposureCompensation ?: 0f) <= 0.0001f
val profileGainTableRequired = profileToneMapMode == RawProfileToneMapMode.Photon ||
profileToneMapMode == RawProfileToneMapMode.GooglePixel
val profileGainTableRequired = profileToneMapMode == RawProfileToneMapMode.Photon
val captureProfilePreparer = if (viewfinderMatchEnabled || profileGainTableRequired) {
RawDngCaptureProfilePreparer { input ->
RawViewfinderExposureMatcher.prepareCaptureProfile(
@@ -3841,17 +3840,13 @@ object GalleryManager {
}
private fun profileNameForPgtmMode(mode: RawProfileToneMapMode): String {
return when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
else -> DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME
}
require(mode == RawProfileToneMapMode.Photon)
return DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
}
private fun profileToneCurveForPgtmMode(mode: RawProfileToneMapMode): FloatArray {
return when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.photonPgtmToneCurvePoints()
else -> DngProfileToneCurve.googleHdrToneCurvePoints()
}
require(mode == RawProfileToneMapMode.Photon)
return DngProfileToneCurve.photonPgtmToneCurvePoints()
}
/**
@@ -4585,10 +4580,6 @@ object GalleryManager {
rawToneMappingParameters.withPhotonPgtmToneMap(true)
}
DngEmbeddedProfile.hasGoogleToneMapProfile(dngFile) -> {
rawToneMappingParameters.withGooglePixelToneMap(true)
}
else -> return this
}
if (toneMappingParameters == rawToneMappingParameters && manualHdrEffectEnabled) return this
@@ -377,9 +377,10 @@ data class MediaMetadata(
} else {
obj.optDouble("rawFilmicWhiteRelativeExposure").toFloat()
},
useGooglePixelToneMap = obj.optBoolean("rawGooglePixelToneMap", false),
useOppoMasterToneMap = obj.optBoolean("rawOppoMasterToneMap", false),
usePhotonPgtmToneMap = obj.optBoolean("rawPhotonPgtmToneMap", false)
usePhotonPgtmToneMap =
obj.optBoolean("rawPhotonPgtmToneMap", false) ||
obj.optBoolean("rawGooglePixelToneMap", false)
).normalized(),
rawBlackLevelMode = if (obj.isNull("rawBlackLevelMode")) null else obj.optString("rawBlackLevelMode"),
rawCustomBlackLevel = if (obj.isNull("rawCustomBlackLevel")) null else obj.optDouble("rawCustomBlackLevel").toFloat(),
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.gallery.db
import androidx.room.ColumnInfo
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.Index
@@ -65,7 +66,8 @@ data class GalleryMediaEntity(
val rawAgxShoulder: Float,
val rawFilmicBlackRelativeExposure: Float,
val rawFilmicWhiteRelativeExposure: Float,
val rawGooglePixelToneMap: Boolean,
@ColumnInfo(name = "rawGooglePixelToneMap")
val legacyPhotonToneMap: Boolean,
val rawOppoMasterToneMap: Boolean,
val rawPhotonPgtmToneMap: Boolean,
val rawAppleProRawToneMap: Boolean,
@@ -241,7 +241,7 @@ object GalleryMediaStore {
rawAgxShoulder = metadata.rawToneMappingParameters.agxShoulder,
rawFilmicBlackRelativeExposure = metadata.rawToneMappingParameters.filmicBlackRelativeExposure,
rawFilmicWhiteRelativeExposure = metadata.rawToneMappingParameters.filmicWhiteRelativeExposure,
rawGooglePixelToneMap = metadata.rawToneMappingParameters.useGooglePixelToneMap,
legacyPhotonToneMap = false,
rawOppoMasterToneMap = metadata.rawToneMappingParameters.useOppoMasterToneMap,
rawPhotonPgtmToneMap = metadata.rawToneMappingParameters.usePhotonPgtmToneMap,
rawAppleProRawToneMap = false,
@@ -434,9 +434,8 @@ object GalleryMediaStore {
agxShoulder = rawAgxShoulder,
filmicBlackRelativeExposure = rawFilmicBlackRelativeExposure,
filmicWhiteRelativeExposure = rawFilmicWhiteRelativeExposure,
useGooglePixelToneMap = rawGooglePixelToneMap,
useOppoMasterToneMap = rawOppoMasterToneMap,
usePhotonPgtmToneMap = rawPhotonPgtmToneMap
usePhotonPgtmToneMap = rawPhotonPgtmToneMap || legacyPhotonToneMap
).normalized(),
frameId = frameId,
width = width,
@@ -29,7 +29,6 @@ data class CameraPreset(
val rawHncsRenderIntent: String = HncsRenderIntent.Standard.assetValue,
val rawHncsFilmCurveMode: String = HncsFilmCurveMode.Standard.persistedValue,
val rawRenderingEngine: String = RawRenderingEngine.AdobeCurve.name,
val rawGooglePixelToneMap: Boolean = false,
val rawOppoMasterToneMap: Boolean = false,
val rawPhotonPgtmToneMap: Boolean = false,
val rawSpectralFilmStock: String? = null,
@@ -97,7 +96,6 @@ data class CameraPreset(
rawHncsFilmCurveMode = HncsFilmCurveMode.fromPersistedValue(
rawHncsFilmCurveMode
).persistedValue,
rawGooglePixelToneMap = rawGooglePixelToneMap && !rawOppoMasterToneMap && !rawPhotonPgtmToneMap,
rawOppoMasterToneMap = rawOppoMasterToneMap,
rawPhotonPgtmToneMap = rawPhotonPgtmToneMap && !rawOppoMasterToneMap
)
@@ -73,9 +73,10 @@ internal object CameraPresetJsonCodec {
rawRenderingEngine = parseRawRenderingEngine(
obj.stringOrNull("rawRenderingEngine") ?: obj.stringOrNull("rawColorEngine")
),
rawGooglePixelToneMap = obj.boolean("rawGooglePixelToneMap", false),
rawOppoMasterToneMap = obj.boolean("rawOppoMasterToneMap", false),
rawPhotonPgtmToneMap = obj.boolean("rawPhotonPgtmToneMap", false),
rawPhotonPgtmToneMap =
obj.boolean("rawPhotonPgtmToneMap", false) ||
obj.boolean("rawGooglePixelToneMap", false),
rawSpectralFilmStock = obj.stringOrNull("rawSpectralFilmStock"),
rawSpectralFilmPrint = obj.stringOrNull("rawSpectralFilmPrint"),
rawDROMode = parseDroMode(obj.stringOrNull("rawDROMode")),
@@ -92,25 +92,11 @@ internal object DngEmbeddedProfile {
}.getOrNull()
}
fun hasGoogleToneMapProfile(file: File): Boolean {
val profile = readFrom(file) ?: return false
return isGoogleProfileName(profile.profileName) && profile.toneCurve?.isValid == true
}
fun hasPhotonPgtmProfile(file: File): Boolean {
val profile = readFrom(file) ?: return false
return DngProfileToneCurve.isPhotonPgtmToneCurve(profile.toneCurve)
}
fun hasGoogleHdrToneCurve(file: File): Boolean {
val profile = readFrom(file) ?: return false
return DngProfileToneCurve.isGoogleHdrToneCurve(profile.toneCurve)
}
fun isGoogleProfileName(profileName: String?): Boolean {
return profileName?.contains("google", ignoreCase = true) == true
}
fun isPhotonPgtmProfileName(profileName: String?): Boolean {
val normalizedName = profileName?.trim()?.takeIf { it.isNotEmpty() } ?: return false
return normalizedName.equals(
@@ -1,226 +0,0 @@
package com.hinnka.mycamera.raw
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/** PXLs2-trained Gaussian parameter pyramid for PGTM black gain and shoulder shape. */
internal object DngHdrLtmSpatialModel {
private const val LEVEL_EPS = 0.006f
private const val TAIL_EPS = 0.040f
private const val FEATURE_COUNT = 11
private val BLACK_FINE = floatArrayOf(
0.080100003f, 0.038598747f, -0.009591165f, 0.040930166f,
-0.032663656f, 0.003484404f, -0.036142493f, -0.013543239f,
0.221111670f, -0.056745937f, 0.022797185f,
)
private val BLACK_REGIONAL = floatArrayOf(
0.050453932f, -0.164809241f, -0.025868995f, 0.024685689f,
-0.169930713f, 0.082901192f, 0.057923125f, 0.054644468f,
-0.628739524f, -0.120014771f, 0.272379151f,
)
private val SHAPE_FINE = floatArrayOf(
-0.042331190f, -0.002069818f, -0.003614245f, -0.011158727f,
0.025782988f, -0.011451446f, 0.188099210f, -0.026559214f,
-0.048570362f, 0.027670583f, -0.014421700f,
)
private val SHAPE_REGIONAL = floatArrayOf(
0.032147274f, 0.012769699f, -0.005806728f, -0.042285077f,
0.097232112f, -0.041291256f, 0.005268769f, -0.025812120f,
0.213336867f, 0.033524746f, -0.045624738f,
)
fun buildCurvePlans(
cells: Array<HdrPgtmCellStats?>,
grid: HdrPgtmGrid,
globalPlan: HdrPgtmCurvePlan,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
curveParameters: HdrPgtmCurveParameters,
): Array<HdrPgtmCurvePlan> {
val boundedGlobalPlan = globalPlan.copy(
blackGain = globalPlan.blackGain.coerceIn(
curveParameters.minBlackGain,
curveParameters.maxTableGain,
),
shapePower = globalPlan.shapePower.coerceIn(
curveParameters.minShapePower,
curveParameters.maxShapePower,
),
)
val fallbackStats = cells.filterNotNull().firstOrNull()
?: return Array(cells.size) { boundedGlobalPlan }
val raw = Array(cells.size) { index ->
featureVector(
stats = cells[index] ?: fallbackStats,
baselineExposureEv = baselineExposureEv,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
)
}
val fine = smoothFeatures(raw, grid)
var regional = fine
repeat(3) { regional = smoothFeatures(regional, grid) }
val reference = medianFeature(regional)
return Array(cells.size) { index ->
if (cells[index] == null) {
boundedGlobalPlan
} else {
var blackOffsetEv = 0f
var shapeOffset = 0f
for (feature in 0 until FEATURE_COUNT) {
val fineResidual = fine[index][feature] - regional[index][feature]
val regionalResidual = regional[index][feature] - reference[feature]
blackOffsetEv +=
BLACK_FINE[feature] * fineResidual +
BLACK_REGIONAL[feature] * regionalResidual
shapeOffset +=
SHAPE_FINE[feature] * fineResidual +
SHAPE_REGIONAL[feature] * regionalResidual
}
globalPlan.copy(
blackGain = (globalPlan.blackGain * 2.0f.pow(blackOffsetEv))
.coerceIn(curveParameters.minBlackGain, curveParameters.maxTableGain),
shapePower = (globalPlan.shapePower + shapeOffset).coerceIn(
curveParameters.minShapePower,
curveParameters.maxShapePower,
),
)
}
}
}
private fun featureVector(
stats: HdrPgtmCellStats,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
): FloatArray {
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 floatArrayOf(
logP10,
logP50,
logP90,
logP98,
logP98 - logP10,
logP98 - logP50,
sqrt(stats.highlightFraction.coerceIn(0f, 1f)),
log2((stats.p995Input + TAIL_EPS) / (stats.p98 + TAIL_EPS)),
log2((stats.p999Input + TAIL_EPS) / (stats.p995Input + TAIL_EPS)),
snrFeature(stats.p10, baselineExposureEv, noiseSlope, noiseOffset),
snrFeature(stats.p50, baselineExposureEv, noiseSlope, noiseOffset),
)
}
private fun snrFeature(
signal: Float,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
): Float {
val sourceSignal = max(signal / DngBaselineExposure.exactGain(baselineExposureEv), 0f)
val variance = max(noiseSlope * sourceSignal + noiseOffset, 1e-12f)
return log2(1f + sourceSignal / sqrt(variance))
}
private fun smoothFeatures(
source: Array<FloatArray>,
grid: HdrPgtmGrid,
): Array<FloatArray> = Array(source.size) { index ->
val x = index % grid.mapPointsH
val y = index / grid.mapPointsH
val result = FloatArray(FEATURE_COUNT)
var weightSum = 0f
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
}
val feature = source[yy * grid.mapPointsH + xx]
weightSum += weight
for (component in 0 until FEATURE_COUNT) {
result[component] += feature[component] * weight
}
}
}
for (component in 0 until FEATURE_COUNT) result[component] /= weightSum
result
}
private fun medianFeature(source: Array<FloatArray>): FloatArray =
FloatArray(FEATURE_COUNT) { component ->
val values = FloatArray(source.size) { source[it][component] }
values.sort()
val center = values.size / 2
if (values.size % 2 == 0) {
0.5f * (values[center - 1] + values[center])
} else {
values[center]
}
}
private fun log2(value: Float): Float =
(ln(max(value, 1e-8f).toDouble()) / ln(2.0)).toFloat()
}
internal data class HdrPgtmGrid(
val mapPointsH: Int,
val mapPointsV: Int,
val mapSpacingH: Double,
val mapSpacingV: Double,
val mapOriginH: Double = 0.0,
val mapOriginV: Double = 0.0,
)
internal data class HdrPgtmSamplingArea(
val originH: Double,
val originV: Double,
val extentH: Double,
val extentV: Double,
) {
init {
require(originH.isFinite() && originV.isFinite())
require(extentH.isFinite() && extentH > 0.0)
require(extentV.isFinite() && extentV > 0.0)
require(originH >= 0.0 && originV >= 0.0)
require(originH + extentH <= 1.0 + COORDINATE_EPS)
require(originV + extentV <= 1.0 + COORDINATE_EPS)
}
companion object {
val FULL = HdrPgtmSamplingArea(
originH = 0.0,
originV = 0.0,
extentH = 1.0,
extentV = 1.0,
)
private const val COORDINATE_EPS = 1e-9
}
}
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,
)
@@ -1,425 +0,0 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/** Plans a constrained DNG profile gain table from GPU-produced spatial RAW statistics. */
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 TABLE_POINTS = 257
private const val TARGET_TILE_PX = 64
private const val GRID_MIN_H = 8
private const val GRID_MIN_V = 6
private const val GRID_MAX_H = 64
private const val GRID_MAX_V = 48
private const val LEVEL_EPS = 0.006f
private const val TAIL_EPS = 0.040f
private const val CURVE_EPS = 1e-6f
private const val FALLBACK_NOISE_SLOPE = 1e-4f
private const val FALLBACK_NOISE_OFFSET = 4.5e-7f
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
internal val BASE_INPUT_WEIGHTS = floatArrayOf(
BASE_INPUT_WEIGHT_RED,
BASE_INPUT_WEIGHT_GREEN,
BASE_INPUT_WEIGHT_BLUE,
BASE_INPUT_WEIGHT_MIN,
BASE_INPUT_WEIGHT_MAX,
)
internal val GOOGLE_CURVE_PARAMETERS = HdrPgtmCurveParameters(
minTableGain = 0.01f,
maxTableGain = 4.80f,
minBlackGain = 0.50f,
// The stored table uses point/257 for non-terminal inputs. Extending the measured 0.020
// toe plateau through the next grid point keeps a DNG lookup at 0.020 on that plateau.
toeEnd = 0.024f,
shapeQ = 1.50f,
minShapePower = 1.0f,
maxShapePower = 1.425f,
minInputScale = 0.25f,
maxInputScale = 1.05f,
)
fun gridSizeFor(width: Int, height: Int): IntArray {
val grid = chooseLtmGrid(width, height)
return intArrayOf(grid.mapPointsH, grid.mapPointsV)
}
internal fun planForCellStats(
width: Int,
height: Int,
baselineExposureEv: Float,
packedCellStats: FloatArray,
noiseSlope: Float = FALLBACK_NOISE_SLOPE,
noiseOffset: Float = FALLBACK_NOISE_OFFSET,
tablePointCount: Int = TABLE_POINTS,
diagnosticBand: DiagnosticBand? = null,
curveModel: HdrPgtmCurveModel = HdrPgtmCurveModel.GOOGLE,
samplingArea: HdrPgtmSamplingArea = HdrPgtmSamplingArea.FULL,
): HdrProfileGainTablePlan? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) return null
val grid = chooseLtmGrid(width, height)
val cellCount = grid.mapPointsH * grid.mapPointsV
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
}
if (curveModel == HdrPgtmCurveModel.PHOTON) {
return DngPhotonProfileGainTableGenerator.plan(
grid = grid,
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
baselineExposureEv = baselineExposureEv,
samplingArea = samplingArea,
diagnosticBand = diagnosticBand?.sanitized(),
)
}
val cells = Array<HdrPgtmCellStats?>(cellCount) { index ->
val offset = index * CELL_STATS_FLOAT_STRIDE
val sampleWeight = packedCellStats[offset + 5]
.takeIf { it.isFinite() && it > 0f }
?: 0f
if (sampleWeight > 0f) packedStatsAt(packedCellStats, offset, sampleWeight) else null
}
val global = weightedGlobalStats(cells)
val safeNoiseSlope = noiseSlope.takeIf { it.isFinite() && it > 0f }
?: FALLBACK_NOISE_SLOPE
val safeNoiseOffset = noiseOffset.takeIf { it.isFinite() && it > 0f }
?: FALLBACK_NOISE_OFFSET
val curveParameters = GOOGLE_CURVE_PARAMETERS
val inputScale = estimateInputScale(global, baselineExposureEv, curveParameters)
val globalPlan = buildGlobalCurvePlan(
stats = global,
inputScale = inputScale,
noiseOffset = safeNoiseOffset,
curveParameters = curveParameters,
)
val cellPlans = DngHdrLtmSpatialModel.buildCurvePlans(
cells = cells,
grid = grid,
globalPlan = globalPlan,
baselineExposureEv = baselineExposureEv,
noiseSlope = safeNoiseSlope,
noiseOffset = safeNoiseOffset,
curveParameters = curveParameters,
)
return HdrProfileGainTablePlan(
curveModel = HdrPgtmCurveModel.GOOGLE,
grid = grid,
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
mapInputWeights = ltmInputWeights(inputScale, curveParameters),
gamma = 1f,
googlePlan = GooglePgtmPlan(
inputScale = inputScale,
curveParameters = curveParameters,
cellPlans = cellPlans,
),
photonPlan = null,
diagnosticBand = diagnosticBand?.sanitized(),
)
}
internal fun mapFromGpuGains(
plan: HdrProfileGainTablePlan,
gains: FloatArray,
): DngProfileGainTableMap? {
val expected = plan.grid.mapPointsH * plan.grid.mapPointsV * plan.pointCount
if (gains.size != expected) {
PLog.e(TAG, "GPU PGTM gain count=${gains.size}, expected=$expected")
return null
}
if (gains.any { !it.isFinite() || it <= 0f }) {
PLog.e(TAG, "GPU PGTM contains a non-finite or non-positive gain")
return null
}
return createMap(plan, gains)
}
data class DiagnosticBand(
val start: Float,
val end: Float,
val feather: Float = 0.02f,
val mode: DiagnosticMode = DiagnosticMode.PASS_ONLY,
) {
internal fun sanitized(): DiagnosticBand? {
if (!start.isFinite() || !end.isFinite() || !feather.isFinite()) return null
val safeStart = start.coerceIn(0f, 1f)
val safeEnd = end.coerceIn(0f, 1f)
if (safeEnd <= safeStart) return null
return DiagnosticBand(
start = safeStart,
end = safeEnd,
feather = feather.coerceIn(0f, 0.12f),
mode = mode,
)
}
}
enum class DiagnosticMode { PASS_ONLY, BLOCK_ONLY }
private fun packedStatsAt(
stats: FloatArray,
offset: Int,
sampleWeight: Float,
): HdrPgtmCellStats {
val p10 = safe01(stats[offset])
val p50 = max(p10, safe01(stats[offset + 1]))
val p90 = max(p50, safe01(stats[offset + 2]))
val p98 = max(p90, safe01(stats[offset + 3]))
val p995 = max(p98, safePositive(stats[offset + 6], p98))
val p999 = max(p995, safePositive(stats[offset + 7], p995))
return HdrPgtmCellStats(
p10 = p10,
p50 = p50,
p90 = p90,
p98 = p98,
highlightFraction = safe01(stats[offset + 4]),
p995Input = p995,
p999Input = p999,
inputTailP95 = p995,
inputTailP98 = p995,
inputTailP99 = p999,
maxInput = p999,
sampleWeight = sampleWeight,
)
}
private fun weightedGlobalStats(cells: Array<HdrPgtmCellStats?>): HdrPgtmCellStats {
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 =
valid.sumOf { (selector(it) * it.sampleWeight).toDouble() }.toFloat() / weightSum
return HdrPgtmCellStats(
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(
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<HdrPgtmCellStats>,
percentile: Float,
selector: (HdrPgtmCellStats) -> Float,
): Float {
val sorted = cells.map { selector(it) to it.sampleWeight }.sortedBy { it.first }
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
}
/** PXLs2 leave-one-scene-out fit of total headroom, without a reciprocal-baseline clamp. */
private fun estimateInputScale(
stats: HdrPgtmCellStats,
baselineExposureEv: Float,
curveParameters: HdrPgtmCurveParameters,
): Float {
val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f)
val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95))
val totalHeadroomEv =
0.643521568f +
1.043402671f * baselineExposureEv +
0.437326319f * log2(stats.p98 + LEVEL_EPS) -
1.796161979f * sqrt(stats.highlightFraction.coerceIn(0f, 1f)) -
0.362162094f * log2(tailP95 + TAIL_EPS) -
0.431998130f * log2((tailP99 + TAIL_EPS) / (tailP95 + TAIL_EPS))
return sanitizeInputScale(
value = 2.0f.pow(totalHeadroomEv - baselineExposureEv),
curveParameters = curveParameters,
)
}
private fun buildGlobalCurvePlan(
stats: HdrPgtmCellStats,
inputScale: Float,
noiseOffset: Float,
curveParameters: HdrPgtmCurveParameters,
): HdrPgtmCurvePlan {
val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f)
val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95))
val blackGainEv =
-0.943690137f -
0.310687278f * log2(stats.p50 + LEVEL_EPS) +
2.373225506f * sqrt(stats.highlightFraction.coerceIn(0f, 1f)) -
0.058252151f * log2Noise(noiseOffset)
val shapePower =
1.033760023f +
0.029590443f * log2(tailP95 + TAIL_EPS) +
0.042870987f * log2((tailP99 + TAIL_EPS) / (tailP95 + TAIL_EPS))
return HdrPgtmCurvePlan(
// Spatial residuals are part of the fitted predictor. Apply the physical bounds only
// after those residuals are added in DngHdrLtmSpatialModel.
blackGain = 2.0f.pow(blackGainEv),
endpointGain = inputScale,
shapePower = shapePower,
)
}
private fun createMap(
plan: HdrProfileGainTablePlan,
gains: FloatArray,
) = DngProfileGainTableMap(
mapPointsV = plan.grid.mapPointsV,
mapPointsH = plan.grid.mapPointsH,
mapSpacingV = plan.grid.mapSpacingV,
mapSpacingH = plan.grid.mapSpacingH,
mapOriginV = plan.grid.mapOriginV,
mapOriginH = plan.grid.mapOriginH,
mapPointsN = plan.pointCount,
mapInputWeights = plan.mapInputWeights,
gamma = plan.gamma,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2,
)
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)
.coerceIn(GRID_MIN_V, GRID_MAX_V)
return HdrPgtmGrid(
mapPointsH = mapPointsH,
mapPointsV = mapPointsV,
mapSpacingH = if (mapPointsH > 1) 1.0 / (mapPointsH - 1) else 1.0,
mapSpacingV = if (mapPointsV > 1) 1.0 / (mapPointsV - 1) else 1.0,
)
}
private fun ltmInputWeights(
inputScale: Float,
curveParameters: HdrPgtmCurveParameters,
): FloatArray {
val scale = sanitizeInputScale(inputScale, curveParameters)
return FloatArray(MAP_INPUT_WEIGHT_COUNT) { BASE_INPUT_WEIGHTS[it] * scale }
}
private fun sanitizeInputScale(
value: Float,
curveParameters: HdrPgtmCurveParameters,
): Float = value.takeIf { it.isFinite() }?.coerceIn(
curveParameters.minInputScale,
curveParameters.maxInputScale,
) ?: curveParameters.minInputScale
private fun log2(value: Float): Float =
(ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat()
private fun log2Noise(value: Float): Float =
(ln(max(value, 1e-12f).toDouble()) / ln(2.0)).toFloat()
private fun safe01(value: Float) = value.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f
private fun safePositive(value: Float, fallback: Float) =
value.takeIf { it.isFinite() && it > 0f } ?: fallback
private fun positiveOr(vararg values: Float) =
values.firstOrNull { it.isFinite() && it > 0f } ?: 1f
}
internal data class HdrProfileGainTablePlan(
val curveModel: HdrPgtmCurveModel,
val grid: HdrPgtmGrid,
val pointCount: Int,
val mapInputWeights: FloatArray,
val gamma: Float,
val googlePlan: GooglePgtmPlan?,
val photonPlan: PhotonPgtmPlan?,
val diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
) {
init {
require(mapInputWeights.size == 5 && mapInputWeights.all { it.isFinite() })
require(gamma.isFinite() && gamma in 0.125f..8f)
require((googlePlan != null) xor (photonPlan != null))
require(
when (curveModel) {
HdrPgtmCurveModel.GOOGLE -> googlePlan != null
HdrPgtmCurveModel.PHOTON -> photonPlan != null
}
)
}
val cellCount: Int
get() = grid.mapPointsH * grid.mapPointsV
}
internal enum class HdrPgtmCurveModel { GOOGLE, PHOTON }
internal data class GooglePgtmPlan(
val inputScale: Float,
val curveParameters: HdrPgtmCurveParameters,
val cellPlans: Array<HdrPgtmCurvePlan>,
)
internal data class HdrPgtmCurveParameters(
val minTableGain: Float,
val maxTableGain: Float,
val minBlackGain: Float,
val toeEnd: Float,
val shapeQ: Float,
val minShapePower: Float,
val maxShapePower: Float,
val minInputScale: Float,
val maxInputScale: Float,
) {
init {
require(minTableGain.isFinite() && minTableGain > 0f)
require(maxTableGain.isFinite() && maxTableGain >= minTableGain)
require(minBlackGain.isFinite() && minBlackGain in minTableGain..maxTableGain)
require(toeEnd.isFinite() && toeEnd >= 0f && toeEnd < 1f)
require(shapeQ.isFinite() && shapeQ > 0f)
require(minShapePower.isFinite() && minShapePower > 0f)
require(maxShapePower.isFinite() && maxShapePower >= minShapePower)
require(minInputScale.isFinite() && minInputScale > 0f)
require(maxInputScale.isFinite() && maxInputScale >= minInputScale)
}
}
internal data class HdrPgtmCurvePlan(
val blackGain: Float,
val endpointGain: Float,
val shapePower: Float,
)
@@ -7,14 +7,15 @@ internal object DngPgtmDiagnostic {
// 0 disables gain mutation. For halo isolation, use BLOCK_ONLY and sweep 7..18.
private const val PGTM_DIAGNOSTIC_BAND_INDEX = 0
private val PGTM_DIAGNOSTIC_MODE = DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY
private val PGTM_DIAGNOSTIC_MODE =
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY
// Draws tableInput 0.080..0.140 as 0.005-wide false-color bands in RAW preview.
private const val PGTM_VISUAL_OVERLAY_MODE = 0
private var visualOverlayLogged = false
fun activeBandForSource(source: String): DngHdrProfileGainTableGenerator.DiagnosticBand? {
fun activeBandForSource(source: String): DngPhotonProfileGainTableGenerator.DiagnosticBand? {
val band = activeBand() ?: return null
PLog.w(
TAG,
@@ -37,7 +38,7 @@ internal object DngPgtmDiagnostic {
return PGTM_VISUAL_OVERLAY_MODE
}
private fun activeBand(): DngHdrProfileGainTableGenerator.DiagnosticBand? {
private fun activeBand(): DngPhotonProfileGainTableGenerator.DiagnosticBand? {
return when (PGTM_DIAGNOSTIC_BAND_INDEX) {
1 -> band(0.000f, 0.005f, feather = 0.0010f)
2 -> band(0.005f, 0.010f, feather = 0.0010f)
@@ -69,8 +70,8 @@ internal object DngPgtmDiagnostic {
start: Float,
end: Float,
feather: Float = 0.0010f,
): DngHdrProfileGainTableGenerator.DiagnosticBand {
return DngHdrProfileGainTableGenerator.DiagnosticBand(
): DngPhotonProfileGainTableGenerator.DiagnosticBand {
return DngPhotonProfileGainTableGenerator.DiagnosticBand(
start = start,
end = end,
feather = feather,
@@ -56,33 +56,16 @@ internal object DngPhotonLocalToneMapper {
floatArrayOf(1f, 1f / 8f, 1f / 27f, 1f / 64f)
fun generate(
plan: HdrProfileGainTablePlan,
plan: PhotonProfileGainTablePlan,
cellSamples: FloatArray,
packedCellStats: FloatArray,
): FloatArray? {
if (plan.curveModel != HdrPgtmCurveModel.PHOTON) return null
val photonPlan = plan.photonPlan ?: return null
val photonPlan = plan.photonPlan
val cellCount = plan.cellCount
val expectedSamples = cellCount * SAMPLES_PER_CELL
if (cellSamples.size != expectedSamples) {
PLog.e(TAG, "Photon sample count=${cellSamples.size}, expected=$expectedSamples")
return null
}
val expectedStats =
cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
if (packedCellStats.size < expectedStats) {
PLog.e(TAG, "Photon stats count=${packedCellStats.size}, expected=$expectedStats")
return null
}
repeat(cellCount) { cell ->
val sampleWeight = packedCellStats[
cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE + 5
]
if (!sampleWeight.isFinite() || sampleWeight <= 0f) {
PLog.e(TAG, "Photon cell $cell has no valid RAW samples")
return null
}
}
if (cellSamples.any { !it.isFinite() || it < 0f }) {
PLog.e(TAG, "Photon sample buffer contains invalid scene input")
return null
@@ -127,9 +110,9 @@ internal object DngPhotonLocalToneMapper {
/**
* Fast general Local Laplacian evaluation from llf_general.m. The caller supplies max-RGB
* intensity, and [exposureGain] already contains BaselineExposure and the fixed ACR3 +1.25 EV
* placement. The middle 99% determines the Local Laplacian large-edge slope. Reconstructed
* max-RGB intensity is bounded to Photon PGTM's normalized SDR output contract.
* intensity, and [exposureGain] already contains BaselineExposure and the selected preset's
* gray-placement boost. The middle 99% determines the Local Laplacian large-edge slope.
* Reconstructed max-RGB intensity is bounded to Photon PGTM's normalized SDR output contract.
*/
internal fun localLaplacianToneMap(
source: FloatArray,
@@ -506,7 +489,7 @@ internal object DngPhotonLocalToneMapper {
}
private fun buildGainCurves(
plan: HdrProfileGainTablePlan,
plan: PhotonProfileGainTablePlan,
photonPlan: PhotonPgtmPlan,
gainGrid: ScalarGainBilateralGrid,
): FloatArray {
@@ -537,21 +520,21 @@ internal object DngPhotonLocalToneMapper {
private fun applyDiagnostic(
trueGain: Float,
tableInput: Float,
plan: HdrProfileGainTablePlan,
plan: PhotonProfileGainTablePlan,
): Float {
val band = plan.diagnosticBand ?: return trueGain
val mask = diagnosticMask(tableInput, band)
return when (band.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
DngPhotonProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
lerp(1f, trueGain, mask)
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
lerp(trueGain, 1f, mask)
}
}
private fun diagnosticMask(
input: Float,
band: DngHdrProfileGainTableGenerator.DiagnosticBand,
band: DngPhotonProfileGainTableGenerator.DiagnosticBand,
): Float {
val enter = if (band.start <= 0f || band.feather <= 0f) {
if (input >= band.start) 1f else 0f
@@ -1,31 +1,63 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
import kotlin.math.ln
/**
* Plans Photon PGTM metadata for the sampled Local Laplacian + bilateral-grid pipeline.
* Plans Photon HDR metadata for the sampled Local Laplacian + bilateral-grid pipeline.
*
* The image-dependent mapping is generated by the compute passes in
* [DngPhotonLocalToneMapGpuShaders]. [DngPhotonLocalToneMapper] remains the readable CPU reference
* used to compare equations and constants; it is not used by the capture path.
*/
internal object DngPhotonProfileGainTableGenerator {
private const val TAG = "DngPhotonProfileGainTableGenerator"
private const val TABLE_POINTS = 257
private const val TARGET_TILE_PX = 64
private const val GRID_MIN_H = 8
private const val GRID_MIN_V = 6
private const val GRID_MAX_H = 64
private const val GRID_MAX_V = 48
private const val MIN_TABLE_GAIN = 1f / 4096f
private const val MAX_TABLE_GAIN = 4096f
internal val MAX_RGB_INPUT_WEIGHTS = floatArrayOf(0f, 0f, 0f, 0f, 1f)
fun gridSizeFor(width: Int, height: Int): IntArray {
val grid = chooseGrid(width, height)
return intArrayOf(grid.mapPointsH, grid.mapPointsV)
}
fun plan(
grid: HdrPgtmGrid,
width: Int,
height: Int,
baselineExposureEv: Float,
tablePointCount: Int = TABLE_POINTS,
diagnosticBand: DiagnosticBand? = null,
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
): PhotonProfileGainTablePlan? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) return null
return plan(
grid = chooseGrid(width, height),
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
baselineExposureEv = baselineExposureEv,
samplingArea = samplingArea,
diagnosticBand = diagnosticBand?.sanitized(),
)
}
fun plan(
grid: PhotonPgtmGrid,
pointCount: Int,
baselineExposureEv: Float,
samplingArea: HdrPgtmSamplingArea = HdrPgtmSamplingArea.FULL,
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
): HdrProfileGainTablePlan {
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
diagnosticBand: DiagnosticBand?,
): PhotonProfileGainTablePlan {
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
// CELL_STATS samples one non-overlapping 16x16 block per spatial table entry. Locate the
// entries at those block centers; values outside the first/last center are edge-clamped by
// DNG renderers, matching the BGU input boundary condition.
// The input shader samples one non-overlapping 16x16 block per spatial table entry.
// Locate entries at those block centers; values outside the first/last center are
// edge-clamped by DNG renderers, matching the BGU input boundary condition.
val spacingH = samplingArea.extentH / grid.mapPointsH
val spacingV = samplingArea.extentV / grid.mapPointsV
val centeredGrid = grid.copy(
@@ -40,13 +72,11 @@ internal object DngPhotonProfileGainTableGenerator {
val mapWeights = FloatArray(MAX_RGB_INPUT_WEIGHTS.size) {
MAX_RGB_INPUT_WEIGHTS[it] / exposureGain
}
return HdrProfileGainTablePlan(
curveModel = HdrPgtmCurveModel.PHOTON,
return PhotonProfileGainTablePlan(
grid = centeredGrid,
pointCount = pointCount,
mapInputWeights = mapWeights,
gamma = 1f,
googlePlan = null,
photonPlan = PhotonPgtmPlan(
exposureGain = exposureGain,
minTableGain = MIN_TABLE_GAIN,
@@ -56,41 +86,92 @@ internal object DngPhotonProfileGainTableGenerator {
diagnosticBand = diagnosticBand,
)
}
fun mapFromGpuGains(
plan: PhotonProfileGainTablePlan,
gains: FloatArray,
): DngProfileGainTableMap? {
val expected = plan.cellCount * plan.pointCount
if (gains.size != expected) {
PLog.e(TAG, "GPU Photon HDR gain count=${gains.size}, expected=$expected")
return null
}
if (gains.any { !it.isFinite() || it <= 0f }) {
PLog.e(TAG, "GPU Photon HDR contains a non-finite or non-positive gain")
return null
}
return DngProfileGainTableMap(
mapPointsV = plan.grid.mapPointsV,
mapPointsH = plan.grid.mapPointsH,
mapSpacingV = plan.grid.mapSpacingV,
mapSpacingH = plan.grid.mapSpacingH,
mapOriginV = plan.grid.mapOriginV,
mapOriginH = plan.grid.mapOriginH,
mapPointsN = plan.pointCount,
mapInputWeights = plan.mapInputWeights,
gamma = plan.gamma,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2,
)
}
data class DiagnosticBand(
val start: Float,
val end: Float,
val feather: Float = 0.02f,
val mode: DiagnosticMode = DiagnosticMode.PASS_ONLY,
) {
internal fun sanitized(): DiagnosticBand? {
if (!start.isFinite() || !end.isFinite() || !feather.isFinite()) return null
val safeStart = start.coerceIn(0f, 1f)
val safeEnd = end.coerceIn(0f, 1f)
if (safeEnd <= safeStart) return null
return DiagnosticBand(
start = safeStart,
end = safeEnd,
feather = feather.coerceIn(0f, 0.12f),
mode = mode,
)
}
}
enum class DiagnosticMode { PASS_ONLY, BLOCK_ONLY }
private fun chooseGrid(width: Int, height: Int): PhotonPgtmGrid {
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
.coerceIn(GRID_MIN_H, GRID_MAX_H)
val mapPointsV = ((height + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
.coerceIn(GRID_MIN_V, GRID_MAX_V)
return PhotonPgtmGrid(
mapPointsH = mapPointsH,
mapPointsV = mapPointsV,
mapSpacingH = if (mapPointsH > 1) 1.0 / (mapPointsH - 1) else 1.0,
mapSpacingV = if (mapPointsV > 1) 1.0 / (mapPointsV - 1) else 1.0,
)
}
}
/**
* Parameters copied from the published Local Laplacian and Google BGU reference code.
*
* The Local Laplacian edge slope is the compression ratio required to reach the reference target
* dynamic range. ACR3's fixed +1.25 EV gray placement is applied to scene-linear input before Local
* Laplacian; scene highlights therefore do not determine exposure. The resulting SDR target is
* then projected directly into ProfileGainTableMap's RGB-uniform multiplicative representation.
* Photon uses max RGB as both the Local Laplacian intensity and the DNG table coordinate, so the
* gain follows and bounds the brightest channel without changing RGB ratios. A luma-like guide
* can reach one while a saturated channel is still far above one after gain, which turns
* downstream profile rendering into a color-changing operation.
* The MATLAB example's final display gamma is omitted because output encoding is performed by the
* renderer after the DNG profile pipeline.
* The Local Laplacian edge slope is the compression ratio required to reach the target dynamic
* range. A fixed exposure boost is applied to scene-linear input before Local Laplacian; scene
* highlights therefore do not determine exposure. Photon uses max RGB as both the Local Laplacian
* intensity and the DNG table coordinate, so the gain follows and bounds the brightest channel
* without changing RGB ratios. The MATLAB example's final display gamma is omitted because output
* encoding is performed by the renderer after the DNG profile pipeline.
*/
internal data class PhotonLocalToneMappingParameters(
// Paris, Hasinoff, Kautz 2011 HDR example: sigma=2.5 in linear space and alpha=1.
val localLaplacianRangeSigma: Float = ln(2.5).toFloat(),
val localLaplacianDetailExponent: Float = 1f,
// Aubry et al. llf_general.m example for a general remapping function.
val localLaplacianIntensityLevels: Int = 20,
// Paris et al. tone-map postprocessing.
val percentileClip: Float = 0.005f,
val targetDynamicRange: Float = 100f,
// Places scene-linear 0.18 at 0.18 * 2^1.25 before Local Laplacian processing.
val preToneMapExposureBoostEv: Float = 0.7f,
// Google BGU production estimates.
val preToneMapExposureBoostEv: Float = 1.15f,
val bilateralSpatialBinSize: Int = 16,
val bilateralRangeSigma: Float = 1f / 8f,
val bilateralRangeSigma: Float = 1f / 12f,
val bilateralGuideCurveAlpha: Float = 0.8f,
// Current Halide BGU uses a fixed 1/10-sample identity prior. The older
// count-scaled average-gain prior was removed upstream because it regularized
// well-populated cells more strongly and under-populated cells less strongly.
val bilateralRegularization: Float = 0.1f,
val bilateralRegularization: Float = 1f,
) {
init {
require(localLaplacianRangeSigma.isFinite() && localLaplacianRangeSigma > 0f)
@@ -118,3 +199,56 @@ internal data class PhotonPgtmPlan(
require(maxTableGain.isFinite() && maxTableGain >= minTableGain)
}
}
internal data class PhotonProfileGainTablePlan(
val grid: PhotonPgtmGrid,
val pointCount: Int,
val mapInputWeights: FloatArray,
val gamma: Float,
val photonPlan: PhotonPgtmPlan,
val diagnosticBand: DngPhotonProfileGainTableGenerator.DiagnosticBand?,
) {
init {
require(mapInputWeights.size == 5 && mapInputWeights.all { it.isFinite() })
require(gamma.isFinite() && gamma in 0.125f..8f)
}
val cellCount: Int
get() = grid.mapPointsH * grid.mapPointsV
}
internal data class PhotonPgtmGrid(
val mapPointsH: Int,
val mapPointsV: Int,
val mapSpacingH: Double,
val mapSpacingV: Double,
val mapOriginH: Double = 0.0,
val mapOriginV: Double = 0.0,
)
internal data class PhotonPgtmSamplingArea(
val originH: Double,
val originV: Double,
val extentH: Double,
val extentV: Double,
) {
init {
require(originH.isFinite() && originV.isFinite())
require(extentH.isFinite() && extentH > 0.0)
require(extentV.isFinite() && extentV > 0.0)
require(originH >= 0.0 && originV >= 0.0)
require(originH + extentH <= 1.0 + COORDINATE_EPS)
require(originV + extentV <= 1.0 + COORDINATE_EPS)
}
companion object {
val FULL = PhotonPgtmSamplingArea(
originH = 0.0,
originV = 0.0,
extentH = 1.0,
extentV = 1.0,
)
private const val COORDINATE_EPS = 1e-9
}
}
@@ -1,8 +1,8 @@
package com.hinnka.mycamera.raw
/** Compute shaders for capture-time DNG ProfileGainTableMap preparation. */
internal object DngHdrProfileGainTableGpuShaders {
val CELL_STATS = """
internal object DngPhotonProfileGainTableInputShader {
val CELL_SAMPLES = """
#version 310 es
layout(local_size_x = 16, local_size_y = 8, local_size_z = 1) in;
@@ -22,8 +22,6 @@ internal object DngHdrProfileGainTableGpuShaders {
uniform int uCfaPattern;
uniform vec4 uBlackLevel;
uniform float uWhiteLevel;
uniform float uBaselineGain;
uniform float uHighlightThreshold;
uniform vec3 uCameraWhite;
uniform mat3 uColorCorrectionMatrix;
uniform int uLensShadingEnabled;
@@ -36,23 +34,17 @@ internal object DngHdrProfileGainTableGpuShaders {
uniform ivec3 uHueSatDivisions;
uniform int uHueSatEncoding;
uniform int uHueSatSupportOverrange;
uniform int uUseMaxRgbInput;
uniform int uWriteCellSamples;
uniform int uWarpCount;
layout(std430, binding = 0) writeonly buffer CellStatsBuffer {
float cellStats[];
};
layout(std430, binding = 1) writeonly buffer CellSampleBuffer {
layout(std430, binding = 0) writeonly buffer CellSampleBuffer {
float cellSamples[];
};
layout(std430, binding = 2) readonly buffer WarpRectilinearBuffer {
layout(std430, binding = 1) readonly buffer WarpRectilinearBuffer {
float warpParameters[];
};
const uint CELL_SAMPLE_COUNT = 256u;
const uint CELL_LANE_COUNT = 128u;
shared float inputSamples[256];
${DcpHueSatMapGl.SHADER_FUNCTIONS}
@@ -142,18 +134,8 @@ internal object DngHdrProfileGainTableGpuShaders {
uHueSatSupportOverrange != 0
);
}
profileRgb = clamp(profileRgb, 0.0, 1.0) * uBaselineGain;
float rgbMin = min(profileRgb.r, min(profileRgb.g, profileRgb.b));
float rgbMax = max(profileRgb.r, max(profileRgb.g, profileRgb.b));
if (uUseMaxRgbInput != 0) return rgbMax;
return max(
0.1495 * profileRgb.r +
0.2935 * profileRgb.g +
0.0570 * profileRgb.b +
0.1250 * rgbMin +
0.3750 * rgbMax,
0.0
);
profileRgb = clamp(profileRgb, 0.0, 1.0);
return max(profileRgb.r, max(profileRgb.g, profileRgb.b));
}
float sampleSceneInput(ivec2 baseCoord) {
@@ -238,38 +220,10 @@ internal object DngHdrProfileGainTableGpuShaders {
return clamp(sourcePixel, vec2(0.0), vec2(uImageSize - ivec2(1)));
}
void sortSamples(uint laneIndex) {
for (uint sequenceSize = 2u; sequenceSize <= 256u; sequenceSize <<= 1u) {
for (uint compareDistance = sequenceSize >> 1u;
compareDistance > 0u;
compareDistance >>= 1u
) {
for (
uint localIndex = laneIndex;
localIndex < CELL_SAMPLE_COUNT;
localIndex += CELL_LANE_COUNT
) {
uint partner = localIndex ^ compareDistance;
if (partner > localIndex) {
float first = inputSamples[localIndex];
float second = inputSamples[partner];
bool ascending = (localIndex & sequenceSize) == 0u;
if ((first > second) == ascending) {
inputSamples[localIndex] = second;
inputSamples[partner] = first;
}
}
}
barrier();
}
}
}
void main() {
ivec2 cell = ivec2(gl_WorkGroupID.xy);
uint localIndex = gl_LocalInvocationIndex;
int cellIndex = cell.y * uGridSize.x + cell.x;
int statsOffset = cellIndex * 8;
int statsWidth = uStatsBounds.z - uStatsBounds.x;
int statsHeight = uStatsBounds.w - uStatsBounds.y;
@@ -303,142 +257,7 @@ internal object DngHdrProfileGainTableGpuShaders {
sourceCoord = clamp(sourceCoord, ivec2(0), uImageSize - ivec2(2));
inputValue = sampleSceneInput(sourceCoord);
}
if (uWriteCellSamples != 0) {
cellSamples[cellIndex * 256 + int(sampleIndex)] = inputValue;
}
inputSamples[sampleIndex] = inputValue;
}
barrier();
sortSamples(localIndex);
if (localIndex == 0u) {
if (!validCell) {
for (int component = 0; component < 8; ++component) {
cellStats[statsOffset + component] = 0.0;
}
return;
}
int highlightCount = 0;
for (int sampleIndex = 0; sampleIndex < 256; ++sampleIndex) {
if (inputSamples[sampleIndex] >= uHighlightThreshold) ++highlightCount;
}
cellStats[statsOffset] = inputSamples[25];
cellStats[statsOffset + 1] = inputSamples[127];
cellStats[statsOffset + 2] = inputSamples[230];
cellStats[statsOffset + 3] = inputSamples[250];
cellStats[statsOffset + 4] = float(highlightCount) / 256.0;
cellStats[statsOffset + 5] = 256.0;
cellStats[statsOffset + 6] = inputSamples[254];
cellStats[statsOffset + 7] = inputSamples[255];
}
}
""".trimIndent()
val GOOGLE_GAIN_CURVES = """
#version 310 es
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
precision highp float;
precision highp int;
layout(std430, binding = 0) readonly buffer CurvePlanBuffer {
float curvePlans[];
};
layout(std430, binding = 1) writeonly buffer GainCurveBuffer {
float gainCurves[];
};
uniform int uCellCount;
uniform int uPointCount;
uniform float uInputScale;
uniform float uMinTableGain;
uniform float uMaxTableGain;
uniform float uToeEnd;
uniform float uShapeQ;
uniform float uMinShapePower;
uniform float uMaxShapePower;
uniform int uDiagnosticMode;
uniform float uDiagnosticStart;
uniform float uDiagnosticEnd;
uniform float uDiagnosticFeather;
const float CURVE_EPS = 1e-6;
float smoothUnit(float edge0, float edge1, float value) {
float amount = clamp((value - edge0) / max(edge1 - edge0, CURVE_EPS), 0.0, 1.0);
return amount * amount * (3.0 - 2.0 * amount);
}
float diagnosticMask(float inputValue) {
float enter = uDiagnosticStart <= 0.0 || uDiagnosticFeather <= 0.0
? (inputValue >= uDiagnosticStart ? 1.0 : 0.0)
: smoothUnit(
uDiagnosticStart - uDiagnosticFeather,
uDiagnosticStart + uDiagnosticFeather,
inputValue
);
float exit = uDiagnosticEnd >= 1.0 || uDiagnosticFeather <= 0.0
? (inputValue <= uDiagnosticEnd ? 1.0 : 0.0)
: 1.0 - smoothUnit(
uDiagnosticEnd - uDiagnosticFeather,
uDiagnosticEnd + uDiagnosticFeather,
inputValue
);
return clamp(min(enter, exit), 0.0, 1.0);
}
void main() {
int cellIndex = int(gl_GlobalInvocationID.x);
if (cellIndex >= uCellCount) return;
int planOffset = cellIndex * 3;
float blackGain = clamp(
curvePlans[planOffset], uMinTableGain, uMaxTableGain
);
float endpointGain = clamp(
curvePlans[planOffset + 1], uMinTableGain, uMaxTableGain
);
float shapePower = clamp(
curvePlans[planOffset + 2], uMinShapePower, uMaxShapePower
);
float endpointRatio = blackGain / max(endpointGain, CURVE_EPS);
float shoulderAmount = pow(endpointRatio, uShapeQ) - 1.0;
float previousFinalOutput = 0.0;
int outputOffset = cellIndex * uPointCount;
for (int point = 0; point < uPointCount; ++point) {
float tableInput = point == uPointCount - 1
? 1.0
: float(point) / float(uPointCount);
float shoulderInput = clamp(
(tableInput - uToeEnd) / max(1.0 - uToeEnd, CURVE_EPS),
0.0,
1.0
);
float denominator = pow(
max(1.0 + shoulderAmount * pow(shoulderInput, shapePower), CURVE_EPS),
1.0 / uShapeQ
);
float trueGain = point == uPointCount - 1
? uInputScale
: clamp(blackGain / denominator, uMinTableGain, uMaxTableGain);
float finalGain = trueGain;
if (uDiagnosticMode >= 0) {
float mask = diagnosticMask(tableInput);
float mixedGain = uDiagnosticMode == 0
? mix(1.0, trueGain, mask)
: mix(trueGain, 1.0, mask);
float monotonicOutput = max(previousFinalOutput, tableInput * mixedGain);
finalGain = tableInput <= CURVE_EPS
? clamp(mixedGain, uMinTableGain, uMaxTableGain)
: clamp(
monotonicOutput / tableInput,
uMinTableGain,
uMaxTableGain
);
previousFinalOutput = monotonicOutput;
}
gainCurves[outputOffset + point] = finalGain;
cellSamples[cellIndex * 256 + int(sampleIndex)] = inputValue;
}
}
""".trimIndent()
@@ -1,7 +1,8 @@
package com.hinnka.mycamera.raw
import kotlin.math.pow
internal object DngProfileToneCurve {
const val GOOGLE_HDR_PROFILE_NAME = "Google Pixel HDR Tone Map"
const val PHOTON_PGTM_PROFILE_NAME = "Photon HDR"
private const val POINT_TOLERANCE = 2e-4f
@@ -81,32 +82,14 @@ internal object DngProfileToneCurve {
0.97638f, 0.99517f, 0.98425f, 0.99686f, 0.99213f, 0.99845f, 1f, 1f
)
// Monotonic output-domain rebase of the original curve, pinned at 18% middle gray.
// The original asymmetric toe/shoulder relationship is retained; scene-dependent contrast
// and exposure belong to PGTM.
private val PHOTON_PGTM_TONE_CURVE_POINTS = floatArrayOf(
0.00000000f, 0.000000000f,
0.00390625f, 0.000111219f,
0.00781250f, 0.000462170f,
0.01171875f, 0.001073441f,
0.01562500f, 0.002373597f,
0.01953125f, 0.004900927f,
0.02343750f, 0.008315577f,
0.02734375f, 0.012026066f,
0.03125000f, 0.015834956f,
0.04687500f, 0.031739906f,
0.06250000f, 0.048228501f,
0.09375000f, 0.082288715f,
0.12500000f, 0.117239616f,
0.18000000f, 0.180000000f,
0.25000000f, 0.261059978f,
0.37500000f, 0.406992955f,
0.50000000f, 0.552633896f,
0.62500000f, 0.694937822f,
0.75000000f, 0.817742418f,
0.87500000f, 0.916040488f,
1.00000000f, 1.000000000f
)
// Larger toe power deepens the lowest shadows; toe width extends that behavior upward.
// Mid power controls the body contrast. Larger shoulder power softens the approach to white.
// Balance moves the curve vertically without changing either endpoint.
private const val PHOTON_PGTM_TOE_POWER = 1.5
private const val PHOTON_PGTM_TOE_WIDTH = 0.01
private const val PHOTON_PGTM_MID_POWER = 1.25
private const val PHOTON_PGTM_SHOULDER_POWER = 1.2
private const val PHOTON_PGTM_BALANCE = 0.97
private val PHOTON_PGTM_TONE_CURVE_LUT by lazy {
DcpToneCurve(photonPgtmToneCurvePoints()).toLut(256)
@@ -123,10 +106,6 @@ internal object DngProfileToneCurve {
}
}
fun googleHdrToneCurveLut(sampleCount: Int = 256): FloatArray {
return DcpToneCurve(googleHdrToneCurvePoints()).toLut(sampleCount)
}
fun linearToneCurvePoints(): FloatArray {
return LINEAR_TONE_CURVE_POINTS.copyOf()
}
@@ -136,18 +115,33 @@ internal object DngProfileToneCurve {
}
fun photonPgtmToneCurvePoints(): FloatArray {
val values = DcpToneCurve(PHOTON_PGTM_TONE_CURVE_POINTS)
.toLut(DNG_PROFILE_TONE_CURVE_POINT_COUNT)
return FloatArray(DNG_PROFILE_TONE_CURVE_POINT_COUNT * 2) { index ->
val pointIndex = index / 2
val input = pointIndex.toDouble() / (DNG_PROFILE_TONE_CURVE_POINT_COUNT - 1).toDouble()
if ((index and 1) == 0) {
pointIndex.toFloat() / (DNG_PROFILE_TONE_CURVE_POINT_COUNT - 1).toFloat()
input.toFloat()
} else {
values[pointIndex]
photonPgtmToneCurve(input).toFloat()
}
}
}
private fun photonPgtmToneCurve(input: Double): Double {
if (input <= 0.0) return 0.0
if (input >= 1.0) return 1.0
// n(x) is strictly increasing and s(x) is strictly decreasing for positive parameters.
// Therefore n(x) / (n(x) + s(x)) is smooth and strictly increasing on (0, 1).
val normalizedToeInput =
(input + PHOTON_PGTM_TOE_WIDTH) / (1.0 + PHOTON_PGTM_TOE_WIDTH)
val toeTransition = normalizedToeInput
.pow(PHOTON_PGTM_MID_POWER - PHOTON_PGTM_TOE_POWER)
val numerator = input.pow(PHOTON_PGTM_TOE_POWER) * toeTransition
val shoulder = PHOTON_PGTM_BALANCE *
(1.0 - input).pow(PHOTON_PGTM_SHOULDER_POWER)
return numerator / (numerator + shoulder)
}
fun photonPgtmToneCurveLut(sampleCount: Int = 256): FloatArray {
return if (sampleCount == PHOTON_PGTM_TONE_CURVE_LUT.size) {
PHOTON_PGTM_TONE_CURVE_LUT.copyOf()
@@ -183,17 +177,6 @@ internal object DngProfileToneCurve {
return DcpToneCurve(oppoEmbeddedToneCurvePoints()).toLut(sampleCount)
}
fun isGoogleHdrToneCurve(toneCurve: DcpToneCurve?): Boolean {
if (toneCurve?.isValid != true) return false
val googlePoints = googleHdrToneCurvePoints()
if (toneCurve.points.size == googlePoints.size) {
return toneCurve.points.indices.all { index ->
kotlin.math.abs(toneCurve.points[index] - googlePoints[index]) <= POINT_TOLERANCE
}
}
return isGoogleHdrToneCurveLut(toneCurve.toLut())
}
fun isOppoEmbeddedToneCurve(toneCurve: DcpToneCurve?): Boolean {
if (toneCurve?.isValid != true) return false
val oppoPoints = OPPO_EMBEDDED_TONE_CURVE_POINTS
@@ -227,14 +210,6 @@ internal object DngProfileToneCurve {
return isPhotonPgtmToneCurveLut(toneCurve.toLut())
}
fun isGoogleHdrToneCurveLut(lut: FloatArray?): Boolean {
if (lut == null || lut.isEmpty()) return false
val googleLut = googleHdrToneCurveLut(lut.size)
return lut.indices.all { index ->
kotlin.math.abs(lut[index] - googleLut[index]) <= LUT_TOLERANCE
}
}
fun isOppoEmbeddedToneCurveLut(lut: FloatArray?): Boolean {
if (lut == null || lut.isEmpty()) return false
val oppoLut = oppoEmbeddedToneCurveLut(lut.size)
@@ -482,8 +482,7 @@ class RawDemosaicProcessor {
hueSatMapSupportsOverrange = false,
) != null
val warmedProfileMap = when (profileToneMapMode) {
RawProfileToneMapMode.Photon,
RawProfileToneMapMode.GooglePixel -> generateProfileGainTableMapOnGpu(
RawProfileToneMapMode.Photon -> generateProfileGainTableMapOnGpu(
rawTextureId = linearRawTexture,
width = programSize.width,
height = programSize.height,
@@ -491,7 +490,6 @@ class RawDemosaicProcessor {
metadata = metadata,
statsBounds = Rect(0, 0, programSize.width, programSize.height),
baselineExposureEv = 0f,
profileToneMapMode = profileToneMapMode,
colorCorrectionMatrix = identity,
cameraWhite = metadata.cameraWhite,
hueSatMap = null,
@@ -501,8 +499,7 @@ class RawDemosaicProcessor {
else -> null
}
val profileReady = when (profileToneMapMode) {
RawProfileToneMapMode.Photon,
RawProfileToneMapMode.GooglePixel -> warmedProfileMap != null
RawProfileToneMapMode.Photon -> warmedProfileMap != null
else -> true
}
@@ -865,8 +862,7 @@ class RawDemosaicProcessor {
private var quadChromaProgram = 0
private var quadRefineProgram = 0
private var quadWriteOutputProgram = 0
private var pgtmCellStatsProgram = 0
private var pgtmGoogleGainCurvesProgram = 0
private var pgtmCellSamplesProgram = 0
private val pgtmPhotonPrograms =
IntArray(DngPhotonLocalToneMapGpuShaders.Pass.entries.size)
private var meteringHalfResolutionProgram = 0
@@ -2051,15 +2047,8 @@ class RawDemosaicProcessor {
actualRawData = null
}
val embeddedDngProfileName = embeddedDngRenderPlan?.profileName
val embeddedProfileToneCurveLut = embeddedDngRenderPlan?.toneCurveLut
val embeddedProfileToneMapMode = when {
embeddedProfileToneCurveLut != null &&
(DngProfileToneCurve.isGoogleHdrToneCurveLut(embeddedProfileToneCurveLut) ||
DngEmbeddedProfile.isGoogleProfileName(embeddedDngProfileName)) -> {
RawProfileToneMapMode.GooglePixel
}
embeddedProfileToneCurveLut != null &&
DngProfileToneCurve.isPhotonPgtmToneCurveLut(embeddedProfileToneCurveLut) -> {
RawProfileToneMapMode.Photon
@@ -2068,18 +2057,15 @@ class RawDemosaicProcessor {
else -> RawProfileToneMapMode.Default
}
val normalizedToneMappingParameters = rawToneMappingParameters.normalized()
val googlePixelToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.useGooglePixelToneMap
val photonPgtmToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.usePhotonPgtmToneMap
val oppoMasterToneMapRequested = useAdobeProfilePipeline &&
normalizedToneMappingParameters.useOppoMasterToneMap
val requestedProfileToneMapMode = when {
googlePixelToneMapRequested -> RawProfileToneMapMode.GooglePixel
photonPgtmToneMapRequested -> RawProfileToneMapMode.Photon
else -> RawProfileToneMapMode.Default
}
val profileGainToneMapRequested = requestedProfileToneMapMode == RawProfileToneMapMode.GooglePixel ||
val profileGainToneMapRequested =
requestedProfileToneMapMode == RawProfileToneMapMode.Photon
val embeddedProfileGainTableMap = actualMetadata.profileGainTableMap?.takeIf { it.isValid }
var profileGainTableMap = embeddedProfileGainTableMap
@@ -2098,14 +2084,11 @@ class RawDemosaicProcessor {
metadata = actualMetadata.copy(profileGainTableMap = null),
statsBounds = outputSourceBounds,
baselineExposureEv = DngBaselineExposure.sanitize(actualMetadata.baselineExposure),
profileToneMapMode = requestedProfileToneMapMode,
colorCorrectionMatrix = resolvedDcpRenderPlan?.colorCorrectionMatrix
?: actualMetadata.colorCorrectionMatrix,
cameraWhite = resolvedDcpRenderPlan?.cameraWhite ?: actualMetadata.cameraWhite,
hueSatMap = resolvedDcpRenderPlan?.hueSatMap,
hueSatMapSupportsOverrange =
requestedProfileToneMapMode != RawProfileToneMapMode.Photon &&
resolvedDcpRenderPlan?.supportsOverrange == true,
hueSatMapSupportsOverrange = false,
warpRectilinear = applicableDngWarpRectilinear,
)?.takeIf { it.isValid }
if (generated != null) {
@@ -2452,8 +2435,7 @@ class RawDemosaicProcessor {
actualMetadata.baselineExposure + (solvedExposureEv ?: 0f)
)
val captureProfileGainTableMap = when (captureProfileToneMapMode) {
RawProfileToneMapMode.Photon,
RawProfileToneMapMode.GooglePixel -> generateProfileGainTableMapOnGpu(
RawProfileToneMapMode.Photon -> generateProfileGainTableMapOnGpu(
rawTextureId = rawTextureId,
width = actualWidth,
height = actualHeight,
@@ -2461,7 +2443,6 @@ class RawDemosaicProcessor {
metadata = actualMetadata,
statsBounds = captureProfileStatsBounds,
baselineExposureEv = finalBaselineExposureEv,
profileToneMapMode = captureProfileToneMapMode,
colorCorrectionMatrix = linearColorCorrectionMatrix,
cameraWhite = linearCameraWhite,
hueSatMap = activeDcpRenderPlan?.hueSatMap,
@@ -2470,8 +2451,7 @@ class RawDemosaicProcessor {
)
else -> null
}
val profileRequired = captureProfileToneMapMode == RawProfileToneMapMode.Photon ||
captureProfileToneMapMode == RawProfileToneMapMode.GooglePixel
val profileRequired = captureProfileToneMapMode == RawProfileToneMapMode.Photon
val captureResult = if (profileRequired && captureProfileGainTableMap == null) {
null
} else {
@@ -3376,7 +3356,6 @@ class RawDemosaicProcessor {
metadata: RawMetadata,
statsBounds: Rect?,
baselineExposureEv: Float,
profileToneMapMode: RawProfileToneMapMode,
colorCorrectionMatrix: FloatArray,
cameraWhite: FloatArray,
hueSatMap: DcpHueSatMap?,
@@ -3393,25 +3372,15 @@ class RawDemosaicProcessor {
)
return null
}
val curveModel = when (profileToneMapMode) {
RawProfileToneMapMode.Photon -> HdrPgtmCurveModel.PHOTON
RawProfileToneMapMode.GooglePixel -> HdrPgtmCurveModel.GOOGLE
else -> return null
}
val photonProgramsReady = pgtmPhotonPrograms.all { it != 0 }
if (pgtmCellStatsProgram == 0 ||
(curveModel == HdrPgtmCurveModel.GOOGLE && pgtmGoogleGainCurvesProgram == 0) ||
(curveModel == HdrPgtmCurveModel.PHOTON && !photonProgramsReady)
) {
if (pgtmCellSamplesProgram == 0 || !photonProgramsReady) {
PLog.e(
TAG,
"GPU RAW PGTM programs unavailable: stats=$pgtmCellStatsProgram " +
"model=$curveModel googleCurves=$pgtmGoogleGainCurvesProgram " +
"GPU RAW PGTM programs unavailable: samples=$pgtmCellSamplesProgram " +
"photonProgramsReady=$photonProgramsReady",
)
return null
}
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
val safeStatsBounds = sanitizePgtmStatsBounds(
statsBounds,
rawTextureWidth,
@@ -3424,7 +3393,7 @@ class RawDemosaicProcessor {
)
return null
}
val gridSize = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
val gridSize = DngPhotonProfileGainTableGenerator.gridSizeFor(width, height)
val gridWidth = gridSize.getOrElse(0) { 0 }
val gridHeight = gridSize.getOrElse(1) { 0 }
if (gridWidth <= 0 || gridHeight <= 0) return null
@@ -3437,30 +3406,15 @@ class RawDemosaicProcessor {
if (isNoOpWarpRectilinear(parameters)) continue
parameters.forEach { activeWarpParameters += it }
}
}
}
val cellCount = gridWidth * gridHeight
val statsFloatCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
val sampleFloatCount = if (curveModel == HdrPgtmCurveModel.PHOTON) {
cellCount * DngPhotonLocalToneMapper.SAMPLES_PER_CELL
} else {
1
}
val bufferIds = IntArray(5)
val sampleFloatCount = cellCount * DngPhotonLocalToneMapper.SAMPLES_PER_CELL
val bufferIds = IntArray(2)
val totalStartNs = System.nanoTime()
GLES31.glGenBuffers(bufferIds.size, bufferIds, 0)
try {
val statsBufferId = bufferIds[0]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, statsBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
statsFloatCount * Float.SIZE_BYTES,
null,
GLES31.GL_DYNAMIC_READ,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, statsBufferId)
val sampleBufferId = bufferIds[1]
val sampleBufferId = bufferIds[0]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, sampleBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
@@ -3468,9 +3422,9 @@ class RawDemosaicProcessor {
null,
GLES31.GL_DYNAMIC_READ,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, sampleBufferId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, sampleBufferId)
val warpBufferId = bufferIds[4]
val warpBufferId = bufferIds[1]
val warpBuffer = ByteBuffer.allocateDirect(
max(activeWarpParameters.size, 1) * Float.SIZE_BYTES
)
@@ -3489,19 +3443,19 @@ class RawDemosaicProcessor {
warpBuffer,
GLES31.GL_STATIC_DRAW,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, warpBufferId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, warpBufferId)
GLES31.glUseProgram(pgtmCellStatsProgram)
GLES31.glUseProgram(pgtmCellSamplesProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uRawTexture"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uRawTexture"),
RCD_RAW_TEXTURE_UNIT,
)
// PGTM is later applied to the demosaicked camera-linear image, whose RAW samples
// already include lens-shading correction. Build its statistics in the same domain;
// already include lens-shading correction. Build its samples in the same domain;
// otherwise the local map reintroduces lens vignetting into already-corrected flats.
bindLensShadingForProgram(pgtmCellStatsProgram, metadata)
bindLensShadingForProgram(pgtmCellSamplesProgram, metadata)
val activeHueSatMap = hueSatMap?.takeIf { it.isValid }
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
val hueSatTextureId = activeHueSatMap?.let { map ->
@@ -3509,50 +3463,50 @@ class RawDemosaicProcessor {
} ?: ensureDummyDcp3DTexture()
GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, hueSatTextureId)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatMap"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uHueSatMap"),
LINEAR_DCP_HUE_SAT_TEXTURE_UNIT,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatEnabled"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uHueSatEnabled"),
if (activeHueSatMap != null) 1 else 0,
)
GLES31.glUniform3i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatDivisions"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uHueSatDivisions"),
activeHueSatMap?.hueDivisions ?: 1,
activeHueSatMap?.satDivisions ?: 1,
activeHueSatMap?.valueDivisions ?: 1,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatEncoding"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uHueSatEncoding"),
activeHueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatSupportOverrange"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uHueSatSupportOverrange"),
if (hueSatMapSupportsOverrange) 1 else 0,
)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uImageSize"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uImageSize"),
rawTextureWidth,
rawTextureHeight,
)
GLES31.glUniform4i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uStatsBounds"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uStatsBounds"),
safeStatsBounds.left,
safeStatsBounds.top,
safeStatsBounds.right,
safeStatsBounds.bottom,
)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uGridSize"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uGridSize"),
gridWidth,
gridHeight,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uSamplesPerPixel"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uSamplesPerPixel"),
samplesPerPixel.coerceAtLeast(1),
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uCfaPattern"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uCfaPattern"),
metadata.cfaPattern,
)
val blackLevel4 = FloatArray(4) { index ->
@@ -3561,37 +3515,21 @@ class RawDemosaicProcessor {
}
}
GLES31.glUniform4fv(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uBlackLevel"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uBlackLevel"),
1,
blackLevel4,
0,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uWhiteLevel"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uWhiteLevel"),
metadata.whiteLevel,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uBaselineGain"),
if (curveModel == HdrPgtmCurveModel.PHOTON) 1f else exposureGain,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uUseMaxRgbInput"),
if (curveModel == HdrPgtmCurveModel.PHOTON) 1 else 0,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHighlightThreshold"),
if (curveModel == HdrPgtmCurveModel.PHOTON) 1f / exposureGain else 0.92f,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uWriteCellSamples"),
if (curveModel == HdrPgtmCurveModel.PHOTON) 1 else 0,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uWarpCount"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uWarpCount"),
activeWarpParameters.size / 8,
)
GLES31.glUniform3fv(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uCameraWhite"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uCameraWhite"),
1,
sanitizeCameraWhite(cameraWhite),
0,
@@ -3604,35 +3542,26 @@ class RawDemosaicProcessor {
0f, 0f, 1f,
)
GLES31.glUniformMatrix3fv(
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uColorCorrectionMatrix"),
GLES31.glGetUniformLocation(pgtmCellSamplesProgram, "uColorCorrectionMatrix"),
1,
false,
transposeMatrix3x3(safeColorCorrectionMatrix),
0,
)
val statsGpuStartNs = System.nanoTime()
val samplesGpuStartNs = System.nanoTime()
GLES31.glDispatchCompute(gridWidth, gridHeight, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
)
checkGlError("generateProfileGainTableMapOnGpu stats dispatch")
val packedCellStats = readFloatStorageBuffer(
bufferId = statsBufferId,
floatCount = statsFloatCount,
label = "PGTM cell stats",
) ?: return null
val statsGpuReadyNs = System.nanoTime()
checkGlError("generateProfileGainTableMapOnGpu sample dispatch")
val samplesGpuReadyNs = System.nanoTime()
val plan = DngHdrProfileGainTableGenerator.planForCellStats(
val plan = DngPhotonProfileGainTableGenerator.plan(
width = width,
height = height,
baselineExposureEv = baselineExposureEv,
packedCellStats = packedCellStats,
noiseSlope = metadata.noiseProfile.getOrElse(0) { 0f },
noiseOffset = metadata.noiseProfile.getOrElse(1) { 0f },
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU capture"),
curveModel = curveModel,
samplingArea = HdrPgtmSamplingArea(
samplingArea = PhotonPgtmSamplingArea(
originH = safeStatsBounds.left.toDouble() / rawTextureWidth,
originV = safeStatsBounds.top.toDouble() / rawTextureHeight,
extentH = safeStatsBounds.width().toDouble() / rawTextureWidth,
@@ -3648,159 +3577,37 @@ class RawDemosaicProcessor {
return null
}
if (plan.curveModel == HdrPgtmCurveModel.PHOTON) {
val localToneMapGpuStartNs = System.nanoTime()
val gains = generatePhotonProfileGainCurvesOnGpu(
plan = plan,
sampleBufferId = sampleBufferId,
) ?: return null
val localToneMapGpuReadyNs = System.nanoTime()
val map = DngHdrProfileGainTableGenerator.mapFromGpuGains(plan, gains)
?: return null
val photonPlan = requireNotNull(plan.photonPlan)
val photonPreToneMapGain = photonPlan.exposureGain *
2.0f.pow(photonPlan.parameters.preToneMapExposureBoostEv)
PLog.d(
TAG,
"GPU RAW PGTM prepared: mode=$profileToneMapMode size=${width}x$height " +
"source=${rawTextureWidth}x$rawTextureHeight " +
"statsBounds=$safeStatsBounds " +
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
"lsc=${lensShadingLogString(metadata)} " +
"warpCount=${activeWarpParameters.size / 8} " +
"photonGuide=maxRgb " +
"hueSatOverrange=$hueSatMapSupportsOverrange " +
"photonBaselineGain=${photonPlan.exposureGain} " +
"photonPreToneMapGain=$photonPreToneMapGain " +
"photonLlfLevels=${photonPlan.parameters.localLaplacianIntensityLevels} " +
"photonRangeSigma=${photonPlan.parameters.localLaplacianRangeSigma} " +
"photonBguRangeSigma=${photonPlan.parameters.bilateralRangeSigma} " +
"statsGpuMs=${(statsGpuReadyNs - statsGpuStartNs) / 1_000_000.0} " +
"planCpuMs=${(planReadyNs - statsGpuReadyNs) / 1_000_000.0} " +
"localToneMapGpuMs=" +
"${(localToneMapGpuReadyNs - localToneMapGpuStartNs) / 1_000_000.0} " +
"totalMs=${(localToneMapGpuReadyNs - totalStartNs) / 1_000_000.0}",
)
return map
}
val curveProgram = pgtmGoogleGainCurvesProgram
val googlePlan = requireNotNull(plan.googlePlan)
val curvePlanFloatCount = cellCount * 3
val curvePlanBuffer = ByteBuffer.allocateDirect(
curvePlanFloatCount * Float.SIZE_BYTES
)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
googlePlan.cellPlans.forEach { cellPlan ->
curvePlanBuffer.put(cellPlan.blackGain)
curvePlanBuffer.put(cellPlan.endpointGain)
curvePlanBuffer.put(cellPlan.shapePower)
}
curvePlanBuffer.position(0)
val planBufferId = bufferIds[2]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, planBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
curvePlanFloatCount * Float.SIZE_BYTES,
curvePlanBuffer,
GLES31.GL_STATIC_DRAW,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, planBufferId)
val gainFloatCount = cellCount * plan.pointCount
val gainBufferId = bufferIds[3]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, gainBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
gainFloatCount * Float.SIZE_BYTES,
null,
GLES31.GL_DYNAMIC_READ,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, gainBufferId)
GLES31.glUseProgram(curveProgram)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(curveProgram, "uCellCount"),
cellCount,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(curveProgram, "uPointCount"),
plan.pointCount,
)
val parameters = googlePlan.curveParameters
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uInputScale"),
googlePlan.inputScale,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uMinTableGain"),
parameters.minTableGain,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uMaxTableGain"),
parameters.maxTableGain,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uToeEnd"),
parameters.toeEnd,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uShapeQ"),
parameters.shapeQ,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uMinShapePower"),
parameters.minShapePower,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uMaxShapePower"),
parameters.maxShapePower,
)
val diagnosticMode = when (plan.diagnosticBand?.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
null -> -1
}
GLES31.glUniform1i(
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticMode"),
diagnosticMode,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticStart"),
plan.diagnosticBand?.start ?: 0f,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticEnd"),
plan.diagnosticBand?.end ?: 1f,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticFeather"),
plan.diagnosticBand?.feather ?: 0f,
)
val curveGpuStartNs = System.nanoTime()
GLES31.glDispatchCompute((cellCount + 63) / 64, 1, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
)
checkGlError("generateProfileGainTableMapOnGpu curve dispatch")
val gains = readFloatStorageBuffer(
bufferId = gainBufferId,
floatCount = gainFloatCount,
label = "PGTM gain curves",
val localToneMapGpuStartNs = System.nanoTime()
val gains = generatePhotonProfileGainCurvesOnGpu(
plan = plan,
sampleBufferId = sampleBufferId,
) ?: return null
val curvesGpuReadyNs = System.nanoTime()
val map = DngHdrProfileGainTableGenerator.mapFromGpuGains(plan, gains) ?: return null
val localToneMapGpuReadyNs = System.nanoTime()
val map =
DngPhotonProfileGainTableGenerator.mapFromGpuGains(plan, gains) ?: return null
val photonPlan = plan.photonPlan
val photonPreToneMapGain = photonPlan.exposureGain *
2.0f.pow(photonPlan.parameters.preToneMapExposureBoostEv)
PLog.d(
TAG,
"GPU RAW PGTM prepared: mode=$profileToneMapMode size=${width}x$height " +
"GPU Photon HDR prepared: size=${width}x$height " +
"source=${rawTextureWidth}x$rawTextureHeight " +
"statsBounds=$safeStatsBounds " +
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
"lsc=${lensShadingLogString(metadata)} " +
"warpCount=${activeWarpParameters.size / 8} " +
"statsGpuMs=${(statsGpuReadyNs - statsGpuStartNs) / 1_000_000.0} " +
"planCpuMs=${(planReadyNs - statsGpuReadyNs) / 1_000_000.0} " +
"curvesGpuMs=${(curvesGpuReadyNs - curveGpuStartNs) / 1_000_000.0} " +
"totalMs=${(curvesGpuReadyNs - totalStartNs) / 1_000_000.0}",
"photonGuide=maxRgb " +
"hueSatOverrange=$hueSatMapSupportsOverrange " +
"photonBaselineGain=${photonPlan.exposureGain} " +
"photonPreToneMapGain=$photonPreToneMapGain " +
"photonLlfLevels=${photonPlan.parameters.localLaplacianIntensityLevels} " +
"photonRangeSigma=${photonPlan.parameters.localLaplacianRangeSigma} " +
"photonBguRangeSigma=${photonPlan.parameters.bilateralRangeSigma} " +
"samplesGpuMs=${(samplesGpuReadyNs - samplesGpuStartNs) / 1_000_000.0} " +
"planCpuMs=${(planReadyNs - samplesGpuReadyNs) / 1_000_000.0} " +
"localToneMapGpuMs=" +
"${(localToneMapGpuReadyNs - localToneMapGpuStartNs) / 1_000_000.0} " +
"totalMs=${(localToneMapGpuReadyNs - totalStartNs) / 1_000_000.0}",
)
return map
} catch (error: Exception) {
@@ -3810,7 +3617,6 @@ class RawDemosaicProcessor {
GLES31.glUseProgram(0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, 0)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, 0)
@@ -3823,10 +3629,10 @@ class RawDemosaicProcessor {
}
private fun generatePhotonProfileGainCurvesOnGpu(
plan: HdrProfileGainTablePlan,
plan: PhotonProfileGainTablePlan,
sampleBufferId: Int,
): FloatArray? {
val photonPlan = plan.photonPlan ?: return null
val photonPlan = plan.photonPlan
val parameters = photonPlan.parameters
val preToneMapExposureGain = photonPlan.exposureGain *
2.0f.pow(parameters.preToneMapExposureBoostEv)
@@ -4378,8 +4184,8 @@ class RawDemosaicProcessor {
uniform1f(activeProgram, "uMinTableGain", photonPlan.minTableGain)
uniform1f(activeProgram, "uMaxTableGain", photonPlan.maxTableGain)
val diagnosticMode = when (plan.diagnosticBand?.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
DngPhotonProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
null -> -1
}
uniform1i(activeProgram, "uDiagnosticMode", diagnosticMode)
@@ -4424,10 +4230,10 @@ class RawDemosaicProcessor {
* adjacent range/spatial gain ratios distinguish that from a misplaced spatial grid.
*/
private fun summarizePhotonGainCurves(
plan: HdrProfileGainTablePlan,
plan: PhotonProfileGainTablePlan,
gains: FloatArray,
): String {
val photonPlan = requireNotNull(plan.photonPlan)
val photonPlan = plan.photonPlan
val pointCount = plan.pointCount
val gridWidth = plan.grid.mapPointsH
val gridHeight = plan.grid.mapPointsV
@@ -4977,8 +4783,8 @@ class RawDemosaicProcessor {
TAG,
"Shader programs created: passthrough=$passthroughProgram " +
"meteringHalf=$meteringHalfResolutionProgram " +
"pgtmStats=$pgtmCellStatsProgram googlePgtmCurves=$pgtmGoogleGainCurvesProgram " +
"photonPgtm=localLaplacianBgu"
"pgtmSamples=$pgtmCellSamplesProgram " +
"photonPgtm=localLaplacianBgu",
)
}
@@ -5321,13 +5127,9 @@ class RawDemosaicProcessor {
""".trimIndent()
private fun initLinearRawPrograms(vShader: Int) {
pgtmCellStatsProgram = compileComputeProgram(
DngHdrProfileGainTableGpuShaders.CELL_STATS,
"DNG_PGTM_CELL_STATS",
)
pgtmGoogleGainCurvesProgram = compileComputeProgram(
DngHdrProfileGainTableGpuShaders.GOOGLE_GAIN_CURVES,
"DNG_GOOGLE_PGTM_GAIN_CURVES",
pgtmCellSamplesProgram = compileComputeProgram(
DngPhotonProfileGainTableInputShader.CELL_SAMPLES,
"DNG_PGTM_CELL_SAMPLES",
)
DngPhotonLocalToneMapGpuShaders.sources.forEachIndexed { index, source ->
val pass = DngPhotonLocalToneMapGpuShaders.Pass.entries[index]
@@ -10822,14 +10624,10 @@ class RawDemosaicProcessor {
mode: RawProfileToneMapMode,
preferredToneCurveLut: FloatArray? = null,
): DcpRenderPlan {
val toneCurve = preferredToneCurveLut?.copyOf() ?: when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.photonPgtmToneCurveLut()
else -> DngProfileToneCurve.googleHdrToneCurveLut()
}
val modeName = when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
else -> "Google Pixel Tone Map"
}
require(mode == RawProfileToneMapMode.Photon)
val toneCurve =
preferredToneCurveLut?.copyOf() ?: DngProfileToneCurve.photonPgtmToneCurveLut()
val modeName = DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
return DcpRenderPlan(
profileName = basePlan?.profileName?.let { "$it + $modeName" } ?: modeName,
workingColorSpace = basePlan?.workingColorSpace ?: workingColorSpace,
@@ -10837,8 +10635,7 @@ class RawDemosaicProcessor {
defaultBlackRender = basePlan?.defaultBlackRender ?: DcpDefaultBlackRender.None,
// Photon PGTM has a normalized SDR contract. Do not inherit profile overrange:
// later nonlinear profile stages would otherwise change highlight channel ratios.
supportsOverrange = mode != RawProfileToneMapMode.Photon &&
basePlan?.supportsOverrange == true,
supportsOverrange = false,
colorCorrectionMatrix = basePlan?.colorCorrectionMatrix ?: metadata.colorCorrectionMatrix,
cameraWhite = basePlan?.cameraWhite ?: metadata.cameraWhite,
hueSatMap = basePlan?.hueSatMap,
@@ -12143,14 +11940,11 @@ class RawDemosaicProcessor {
if (quadChromaProgram != 0) GLES31.glDeleteProgram(quadChromaProgram)
if (quadRefineProgram != 0) GLES31.glDeleteProgram(quadRefineProgram)
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
if (pgtmCellStatsProgram != 0) GLES31.glDeleteProgram(pgtmCellStatsProgram)
if (pgtmCellSamplesProgram != 0) GLES31.glDeleteProgram(pgtmCellSamplesProgram)
if (meteringHalfResolutionProgram != 0) {
GLES31.glDeleteProgram(meteringHalfResolutionProgram)
meteringHalfResolutionProgram = 0
}
if (pgtmGoogleGainCurvesProgram != 0) {
GLES31.glDeleteProgram(pgtmGoogleGainCurvesProgram)
}
pgtmPhotonPrograms.forEachIndexed { index, program ->
if (program != 0) GLES31.glDeleteProgram(program)
pgtmPhotonPrograms[index] = 0
@@ -7,7 +7,6 @@ data class RawToneMappingParameters(
val agxShoulder: Float = AGX_SHOULDER_DEFAULT,
val filmicBlackRelativeExposure: Float = FILMIC_BLACK_RELATIVE_EXPOSURE_DEFAULT,
val filmicWhiteRelativeExposure: Float = FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
val useGooglePixelToneMap: Boolean = false,
val useOppoMasterToneMap: Boolean = false,
val usePhotonPgtmToneMap: Boolean = false
) {
@@ -15,7 +14,6 @@ data class RawToneMappingParameters(
get() = when {
useOppoMasterToneMap -> RawProfileToneMapMode.OppoMaster
usePhotonPgtmToneMap -> RawProfileToneMapMode.Photon
useGooglePixelToneMap -> RawProfileToneMapMode.GooglePixel
else -> RawProfileToneMapMode.Default
}
@@ -38,7 +36,6 @@ data class RawToneMappingParameters(
)
val oppoTone = useOppoMasterToneMap
val photonTone = usePhotonPgtmToneMap && !oppoTone
val googleTone = useGooglePixelToneMap && !oppoTone && !photonTone
return copy(
agxBlackRelativeExposure = minOf(blackAgx, whiteAgx - MIN_DYNAMIC_RANGE_EV),
agxWhiteRelativeExposure = maxOf(whiteAgx, blackAgx + MIN_DYNAMIC_RANGE_EV),
@@ -46,24 +43,14 @@ data class RawToneMappingParameters(
agxShoulder = agxShoulder.coerceIn(AGX_SHOULDER_MIN, AGX_SHOULDER_MAX),
filmicBlackRelativeExposure = minOf(blackFilmic, whiteFilmic - MIN_DYNAMIC_RANGE_EV),
filmicWhiteRelativeExposure = maxOf(whiteFilmic, blackFilmic + MIN_DYNAMIC_RANGE_EV),
useGooglePixelToneMap = googleTone,
useOppoMasterToneMap = oppoTone,
usePhotonPgtmToneMap = photonTone
)
}
fun withGooglePixelToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
useGooglePixelToneMap = enabled,
useOppoMasterToneMap = if (enabled) false else useOppoMasterToneMap,
usePhotonPgtmToneMap = if (enabled) false else usePhotonPgtmToneMap
).normalized()
}
fun withOppoMasterToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
useOppoMasterToneMap = enabled,
useGooglePixelToneMap = if (enabled) false else useGooglePixelToneMap,
usePhotonPgtmToneMap = if (enabled) false else usePhotonPgtmToneMap
).normalized()
}
@@ -71,14 +58,12 @@ data class RawToneMappingParameters(
fun withPhotonPgtmToneMap(enabled: Boolean): RawToneMappingParameters {
return copy(
usePhotonPgtmToneMap = enabled,
useGooglePixelToneMap = if (enabled) false else useGooglePixelToneMap,
useOppoMasterToneMap = if (enabled) false else useOppoMasterToneMap
).normalized()
}
fun withProfileToneMapMode(mode: RawProfileToneMapMode): RawToneMappingParameters {
return copy(
useGooglePixelToneMap = mode == RawProfileToneMapMode.GooglePixel,
useOppoMasterToneMap = mode == RawProfileToneMapMode.OppoMaster,
usePhotonPgtmToneMap = mode == RawProfileToneMapMode.Photon
).normalized()
@@ -115,5 +100,4 @@ enum class RawProfileToneMapMode {
Default,
Photon,
OppoMaster,
GooglePixel,
}
@@ -571,7 +571,6 @@ private fun RawProfileToneMapSwitches(
RawProfileToneMapMode.Default.name to stringResource(R.string.settings_raw_profile_tone_map_default),
RawProfileToneMapMode.Photon.name to stringResource(R.string.settings_raw_profile_tone_map_photon_pgtm),
RawProfileToneMapMode.OppoMaster.name to stringResource(R.string.settings_raw_profile_tone_map_oppo_master),
RawProfileToneMapMode.GooglePixel.name to stringResource(R.string.settings_raw_profile_tone_map_google_pixel),
),
currentLevel = params.profileToneMapMode.name,
onLevelSelected = { selected ->
@@ -111,7 +111,6 @@ fun PresetEditorScreen(
var rawRenderingEngine by remember {
mutableStateOf(RawRenderingEngine.fromPersistedName(sourcePreset?.rawRenderingEngine))
}
var rawGooglePixelToneMap by remember { mutableStateOf(sourcePreset?.rawGooglePixelToneMap ?: false) }
var rawOppoMasterToneMap by remember { mutableStateOf(sourcePreset?.rawOppoMasterToneMap ?: false) }
var rawPhotonPgtmToneMap by remember { mutableStateOf(sourcePreset?.rawPhotonPgtmToneMap ?: false) }
var rawSpectralFilmStock by remember { mutableStateOf(sourcePreset?.rawSpectralFilmStock ?: "kodak_portra_400") }
@@ -151,7 +150,6 @@ fun PresetEditorScreen(
rawHncsProfileId = rawHncsProfileId,
rawHncsFilmCurveMode = rawHncsFilmCurveMode,
rawRenderingEngine = rawRenderingEngine.name,
rawGooglePixelToneMap = rawGooglePixelToneMap,
rawOppoMasterToneMap = rawOppoMasterToneMap,
rawPhotonPgtmToneMap = rawPhotonPgtmToneMap,
rawSpectralFilmStock = rawSpectralFilmStock,
@@ -459,12 +457,10 @@ fun PresetEditorScreen(
RawProfileToneMapMode.Default to stringResource(R.string.settings_raw_profile_tone_map_default),
RawProfileToneMapMode.Photon to stringResource(R.string.settings_raw_profile_tone_map_photon_pgtm),
RawProfileToneMapMode.OppoMaster to stringResource(R.string.settings_raw_profile_tone_map_oppo_master),
RawProfileToneMapMode.GooglePixel to stringResource(R.string.settings_raw_profile_tone_map_google_pixel),
)
val selectedToneMapMode = when {
rawOppoMasterToneMap -> RawProfileToneMapMode.OppoMaster
rawPhotonPgtmToneMap -> RawProfileToneMapMode.Photon
rawGooglePixelToneMap -> RawProfileToneMapMode.GooglePixel
else -> RawProfileToneMapMode.Default
}
DropdownSettingItem(
@@ -479,7 +475,6 @@ fun PresetEditorScreen(
.firstOrNull { it.value == selectedLabel }
?.key
?: RawProfileToneMapMode.Default
rawGooglePixelToneMap = selectedMode == RawProfileToneMapMode.GooglePixel
rawOppoMasterToneMap = selectedMode == RawProfileToneMapMode.OppoMaster
rawPhotonPgtmToneMap = selectedMode == RawProfileToneMapMode.Photon
}
@@ -585,8 +585,7 @@ object RawProcessor {
val finalBaselineExposureEv = DngBaselineExposure.sanitize(
sourceBaselineExposureEv + (exposureOffsetEv ?: 0f)
)
val profileRequired = options.profileToneMapMode == RawProfileToneMapMode.Photon ||
options.profileToneMapMode == RawProfileToneMapMode.GooglePixel
val profileRequired = options.profileToneMapMode == RawProfileToneMapMode.Photon
if (profileRequired && captureProfile?.profileGainTableMap == null) {
PLog.e(
TAG,
@@ -784,14 +783,14 @@ object RawProcessor {
}
}
private fun profileNameForToneMapMode(mode: RawProfileToneMapMode): String = when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
else -> DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME
private fun profileNameForToneMapMode(mode: RawProfileToneMapMode): String {
require(mode == RawProfileToneMapMode.Photon)
return DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
}
private fun profileToneCurveForToneMapMode(mode: RawProfileToneMapMode): FloatArray = when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.photonPgtmToneCurvePoints()
else -> DngProfileToneCurve.googleHdrToneCurvePoints()
private fun profileToneCurveForToneMapMode(mode: RawProfileToneMapMode): FloatArray {
require(mode == RawProfileToneMapMode.Photon)
return DngProfileToneCurve.photonPgtmToneCurvePoints()
}
internal fun denormalizeNormalizedRawBufferInPlace(
@@ -543,7 +543,7 @@ object SuperResolutionDngWriter {
listOf(red, green, blue)
}
val profileLookName = profileName?.takeIf { it.isNotBlank() }
?: DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME
?: DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
val cameraRawProfileXmp = profileGainTableMap?.let {
DngCameraRawProfileXmp.build(
profileLookName = profileLookName,
@@ -643,7 +643,7 @@ object SuperResolutionDngWriter {
add(sRationalArray(TAG_BASELINE_EXPOSURE, listOf(resolvedBaselineExposureEv.toDouble())))
if (profileGainTableMap != null) {
add(floatArray(TAG_PROFILE_TONE_CURVE, profileToneCurve?.takeIf { it.size >= 4 }
?: DngProfileToneCurve.googleHdrToneCurvePoints()))
?: DngProfileToneCurve.photonPgtmToneCurvePoints()))
}
add(short(TAG_CALIBRATION_ILLUMINANT_1, illuminant1))
if (illuminant2 != null && colorMatrix2 != null) {
@@ -170,7 +170,6 @@ private data class PresetMatchSnapshot(
val rawHncsRenderIntent: HncsRenderIntent,
val rawHncsFilmCurveMode: HncsFilmCurveMode,
val rawRenderingEngine: RawRenderingEngine,
val rawGooglePixelToneMap: Boolean,
val rawOppoMasterToneMap: Boolean,
val rawPhotonPgtmToneMap: Boolean,
val rawSpectralFilmStock: String?,
@@ -201,7 +200,6 @@ private data class PresetMatchSnapshot(
preset.rawHncsFilmCurveMode
) &&
rawRenderingEngine == RawRenderingEngine.fromPersistedName(preset.rawRenderingEngine) &&
rawGooglePixelToneMap == preset.rawGooglePixelToneMap &&
rawOppoMasterToneMap == preset.rawOppoMasterToneMap &&
rawPhotonPgtmToneMap == preset.rawPhotonPgtmToneMap &&
rawSpectralFilmStock == preset.rawSpectralFilmStock &&
@@ -251,12 +249,6 @@ private data class PresetMatchSnapshot(
if (rawRenderingEngine != presetRawRenderingEngine) {
add("rawRenderingEngine current=$rawRenderingEngine preset=$presetRawRenderingEngine")
}
if (rawGooglePixelToneMap != preset.rawGooglePixelToneMap) {
add(
"rawGooglePixelToneMap current=$rawGooglePixelToneMap " +
"preset=${preset.rawGooglePixelToneMap}"
)
}
if (rawOppoMasterToneMap != preset.rawOppoMasterToneMap) {
add(
"rawOppoMasterToneMap current=$rawOppoMasterToneMap " +
@@ -329,7 +321,6 @@ private data class CameraFeatureUpdate(
val rawHncsRenderIntent: SettingValue<HncsRenderIntent>? = null,
val rawHncsFilmCurveMode: SettingValue<HncsFilmCurveMode>? = null,
val rawRenderingEngine: SettingValue<RawRenderingEngine>? = null,
val rawGooglePixelToneMap: SettingValue<Boolean>? = null,
val rawOppoMasterToneMap: SettingValue<Boolean>? = null,
val rawPhotonPgtmToneMap: SettingValue<Boolean>? = null,
val rawSpectralFilmStock: SettingValue<String?>? = null,
@@ -456,7 +447,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawHncsRenderIntent = saved.rawHncsRenderIntent,
rawHncsFilmCurveMode = saved.rawHncsFilmCurveMode,
rawRenderingEngine = saved.rawRenderingEngine,
rawGooglePixelToneMap = saved.rawGooglePixelToneMap,
rawOppoMasterToneMap = saved.rawOppoMasterToneMap,
rawPhotonPgtmToneMap = saved.rawPhotonPgtmToneMap,
rawSpectralFilmStock = saved.rawSpectralFilmStock,
@@ -522,7 +512,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawHncsRenderIntent = rawHncsRenderIntent.value.assetValue,
rawHncsFilmCurveMode = rawHncsFilmCurveMode.value.persistedValue,
rawRenderingEngine = rawRenderingEngine.value.name,
rawGooglePixelToneMap = rawToneMappingParameters.value.useGooglePixelToneMap,
rawOppoMasterToneMap = rawToneMappingParameters.value.useOppoMasterToneMap,
rawPhotonPgtmToneMap = rawToneMappingParameters.value.usePhotonPgtmToneMap,
rawSpectralFilmStock = rawSpectralFilmStock.value,
@@ -603,7 +592,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
HncsFilmCurveMode.fromPersistedValue(this?.rawHncsFilmCurveMode)
),
rawRenderingEngine = SettingValue(RawRenderingEngine.fromPersistedName(this?.rawRenderingEngine)),
rawGooglePixelToneMap = SettingValue(this?.rawGooglePixelToneMap ?: false),
rawOppoMasterToneMap = SettingValue(this?.rawOppoMasterToneMap ?: false),
rawPhotonPgtmToneMap = SettingValue(this?.rawPhotonPgtmToneMap ?: false),
rawSpectralFilmStock = SettingValue(this?.rawSpectralFilmStock),
@@ -723,14 +711,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
val rawToneMappingUpdate = if (
update.rawGooglePixelToneMap != null ||
update.rawOppoMasterToneMap != null ||
update.rawPhotonPgtmToneMap != null
) {
var toneMappingParameters = prefs.rawToneMappingParameters
update.rawGooglePixelToneMap?.let {
toneMappingParameters = toneMappingParameters.withGooglePixelToneMap(it.value)
}
update.rawOppoMasterToneMap?.let {
toneMappingParameters = toneMappingParameters.withOppoMasterToneMap(it.value)
}
@@ -984,7 +968,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawHncsRenderIntent = rawHncsRenderIntent.value,
rawHncsFilmCurveMode = rawHncsFilmCurveMode.value,
rawRenderingEngine = rawRenderingEngine.value,
rawGooglePixelToneMap = rawToneMappingParameters.value.useGooglePixelToneMap,
rawOppoMasterToneMap = rawToneMappingParameters.value.useOppoMasterToneMap,
rawPhotonPgtmToneMap = rawToneMappingParameters.value.usePhotonPgtmToneMap,
rawSpectralFilmStock = rawSpectralFilmStock.value,
@@ -1012,7 +995,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawHncsRenderIntent = prefs.rawHncsRenderIntent,
rawHncsFilmCurveMode = prefs.rawHncsFilmCurveMode,
rawRenderingEngine = prefs.rawRenderingEngine,
rawGooglePixelToneMap = prefs.rawToneMappingParameters.useGooglePixelToneMap,
rawOppoMasterToneMap = prefs.rawToneMappingParameters.useOppoMasterToneMap,
rawPhotonPgtmToneMap = prefs.rawToneMappingParameters.usePhotonPgtmToneMap,
rawSpectralFilmStock = prefs.rawSpectralFilmStock,
@@ -2541,7 +2523,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawToneMappingParameters: RawToneMappingParameters? = null
): Boolean {
if (hasEmbeddedGainmap) return true
if (rawToneMappingParameters?.normalized()?.useGooglePixelToneMap == true) return true
return userPrefs?.autoEnableHdr ?: true
}
@@ -2570,7 +2570,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val updated = value.normalized()
val shouldEnableHdrGainmap =
previous.profileToneMapMode != updated.profileToneMapMode &&
(updated.useGooglePixelToneMap || updated.usePhotonPgtmToneMap)
updated.usePhotonPgtmToneMap
editRawToneMappingParameters.value = updated
persistRawEditMetadata(
mediaData = mediaData,
@@ -817,16 +817,13 @@
<string name="settings_raw_hncs_film_curve_description">選擇響應曲線</string>
<string name="settings_raw_hncs_film_curve_standard">標準</string>
<string name="settings_raw_hncs_film_curve_reproduction">色彩復刻</string>
<string name="settings_raw_google_pixel_tone_map">Google Pixel 風格色調映射</string>
<string name="settings_raw_google_pixel_tone_map_description">使用 Google Pixel 風格的影調渲染</string>
<string name="settings_raw_oppo_master_tone_map">OPPO 大師影調</string>
<string name="settings_raw_oppo_master_tone_map_description">使用 OPPO 內嵌的大師影調渲染。</string>
<string name="settings_raw_profile_tone_map">RAW 影調曲線</string>
<string name="settings_raw_profile_tone_map_description">選擇影調曲線渲染</string>
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子影調</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子HDR</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
+1 -4
View File
@@ -817,16 +817,13 @@
<string name="settings_raw_hncs_film_curve_description">选择响应曲线</string>
<string name="settings_raw_hncs_film_curve_standard">标准</string>
<string name="settings_raw_hncs_film_curve_reproduction">色彩复刻</string>
<string name="settings_raw_google_pixel_tone_map">Google Pixel 风格色调映射</string>
<string name="settings_raw_google_pixel_tone_map_description">使用 Google Pixel 风格的影调渲染</string>
<string name="settings_raw_oppo_master_tone_map">OPPO 大师影调</string>
<string name="settings_raw_oppo_master_tone_map_description">使用 OPPO 内嵌的大师影调渲染。</string>
<string name="settings_raw_profile_tone_map">RAW 影调曲线</string>
<string name="settings_raw_profile_tone_map_description">选择影调曲线渲染</string>
<string name="settings_raw_profile_tone_map_default">默认</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大师</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子影调</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子HDR</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相对曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相对曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
+1 -4
View File
@@ -817,16 +817,13 @@
<string name="settings_raw_hncs_film_curve_description">選擇響應曲線</string>
<string name="settings_raw_hncs_film_curve_standard">標準</string>
<string name="settings_raw_hncs_film_curve_reproduction">色彩復刻</string>
<string name="settings_raw_google_pixel_tone_map">Google Pixel 風格色調映射</string>
<string name="settings_raw_google_pixel_tone_map_description">使用 Google Pixel 風格的影調渲染</string>
<string name="settings_raw_oppo_master_tone_map">OPPO 大師影調</string>
<string name="settings_raw_oppo_master_tone_map_description">使用 OPPO 內嵌的大師影調渲染。</string>
<string name="settings_raw_profile_tone_map">RAW 影調曲線</string>
<string name="settings_raw_profile_tone_map_description">選擇影調曲線渲染</string>
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子影調</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子HDR</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
+1 -4
View File
@@ -817,16 +817,13 @@
<string name="settings_raw_hncs_film_curve_description">選擇響應曲線</string>
<string name="settings_raw_hncs_film_curve_standard">標準</string>
<string name="settings_raw_hncs_film_curve_reproduction">色彩復刻</string>
<string name="settings_raw_google_pixel_tone_map">Google Pixel 風格色調映射</string>
<string name="settings_raw_google_pixel_tone_map_description">使用 Google Pixel 風格的影調渲染</string>
<string name="settings_raw_oppo_master_tone_map">OPPO 大師影調</string>
<string name="settings_raw_oppo_master_tone_map_description">使用 OPPO 內嵌的大師影調渲染。</string>
<string name="settings_raw_profile_tone_map">RAW 影調曲線</string>
<string name="settings_raw_profile_tone_map_description">選擇影調曲線渲染</string>
<string name="settings_raw_profile_tone_map_default">預設</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子影調</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">光子HDR</string>
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
+1 -4
View File
@@ -801,16 +801,13 @@
<string name="settings_raw_hncs_film_curve_description">Choose a response curve.</string>
<string name="settings_raw_hncs_film_curve_standard">Standard</string>
<string name="settings_raw_hncs_film_curve_reproduction">Reproduction</string>
<string name="settings_raw_google_pixel_tone_map">Google Pixel-style tone mapping</string>
<string name="settings_raw_google_pixel_tone_map_description">Use Google Pixel-style tonal rendering.</string>
<string name="settings_raw_oppo_master_tone_map">OPPO Master tone mapping</string>
<string name="settings_raw_oppo_master_tone_map_description">Use OPPO embedded master tonal rendering.</string>
<string name="settings_raw_profile_tone_map">RAW tone curve</string>
<string name="settings_raw_profile_tone_map_description">Choose the tone curve rendering.</string>
<string name="settings_raw_profile_tone_map_default">Default</string>
<string name="settings_raw_profile_tone_map_google_pixel">Google Pixel</string>
<string name="settings_raw_profile_tone_map_oppo_master">OPPO Master</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">Photon</string>
<string name="settings_raw_profile_tone_map_photon_pgtm">Photon HDR</string>
<string name="settings_raw_agx_white_relative_exposure">AgX White Relative Exposure</string>
<string name="settings_raw_agx_black_relative_exposure">AgX Black Relative Exposure</string>
<string name="settings_raw_agx_shoulder">AgX Shoulder</string>
@@ -1,114 +0,0 @@
package com.hinnka.mycamera.raw
import kotlin.math.max
import kotlin.math.pow
/** Float CPU mirror of the production PGTM curve shaders. */
internal object DngHdrProfileGainTableCpuReference {
fun generate(plan: HdrProfileGainTablePlan): FloatArray = when (plan.curveModel) {
HdrPgtmCurveModel.GOOGLE -> generateGoogle(plan, requireNotNull(plan.googlePlan))
HdrPgtmCurveModel.PHOTON ->
error("Photon curves require the sampled image; use DngPhotonLocalToneMapper.generate")
}
private fun generateGoogle(
plan: HdrProfileGainTablePlan,
googlePlan: GooglePgtmPlan,
): FloatArray {
val result = FloatArray(googlePlan.cellPlans.size * plan.pointCount)
val curveParameters = googlePlan.curveParameters
googlePlan.cellPlans.forEachIndexed { cell, cellPlan ->
val ratio = cellPlan.blackGain / max(cellPlan.endpointGain, CURVE_EPS)
val shoulderAmount = ratio.pow(curveParameters.shapeQ) - 1f
var previousFinalOutput = 0f
repeat(plan.pointCount) { point ->
val tableInput = tableInput(point, plan.pointCount)
val shoulderInput = (
(tableInput - curveParameters.toeEnd) /
(1f - curveParameters.toeEnd)
).coerceIn(0f, 1f)
val denominator = max(
1f + shoulderAmount * shoulderInput.pow(cellPlan.shapePower),
CURVE_EPS,
).pow(1f / curveParameters.shapeQ)
val trueGain = if (point == plan.pointCount - 1) {
googlePlan.inputScale
} else {
(cellPlan.blackGain / denominator).coerceIn(
curveParameters.minTableGain,
curveParameters.maxTableGain,
)
}
val finalGain = applyDiagnostic(
trueGain = trueGain,
tableInput = tableInput,
physicalInput = tableInput,
previousFinalOutput = previousFinalOutput,
plan = plan,
minGain = curveParameters.minTableGain,
maxGain = curveParameters.maxTableGain,
)
if (plan.diagnosticBand != null) {
previousFinalOutput = max(previousFinalOutput, tableInput * finalGain)
}
result[cell * plan.pointCount + point] = finalGain
}
}
return result
}
private fun applyDiagnostic(
trueGain: Float,
tableInput: Float,
physicalInput: Float,
previousFinalOutput: Float,
plan: HdrProfileGainTablePlan,
minGain: Float,
maxGain: Float,
): Float {
val band = plan.diagnosticBand ?: return trueGain
val mask = diagnosticMask(tableInput, band)
val mixed = when (band.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
lerp(1f, trueGain, mask)
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
lerp(trueGain, 1f, mask)
}
val output = max(previousFinalOutput, physicalInput * mixed)
return if (physicalInput <= CURVE_EPS) {
mixed.coerceIn(minGain, maxGain)
} else {
(output / physicalInput).coerceIn(minGain, maxGain)
}
}
private fun tableInput(point: Int, count: Int): Float =
if (point == count - 1) 1f else point.toFloat() / count.toFloat()
private fun diagnosticMask(
input: Float,
band: DngHdrProfileGainTableGenerator.DiagnosticBand,
): Float {
val enter = if (band.start <= 0f || band.feather <= 0f) {
if (input >= band.start) 1f else 0f
} else {
smoothStep(band.start - band.feather, band.start + band.feather, input)
}
val exit = if (band.end >= 1f || band.feather <= 0f) {
if (input <= band.end) 1f else 0f
} else {
1f - smoothStep(band.end - band.feather, band.end + band.feather, input)
}
return minOf(enter, exit).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(start: Float, end: Float, amount: Float) =
start + (end - start) * amount
private const val CURVE_EPS = 1e-6f
}
@@ -1,243 +0,0 @@
package com.hinnka.mycamera.raw
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.sqrt
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DngHdrProfileGainTableGeneratorTest {
@Test
fun corpusContainsOnlyTheCompletePxls2TrainingSet() {
val fixtures = fixtures()
assertEquals(27, fixtures.size)
assertTrue(fixtures.all { it.sourceName.startsWith("PXL_202607") })
assertTrue(fixtures.all { it.tableInputs.size == 33 })
assertTrue(fixtures.all { it.noiseSlope > 0f && it.noiseOffset > 0f })
assertTrue(fixtures.none { it.sourceName.contains("pxls/", ignoreCase = true) })
}
@Test
fun densePxls2CurvesStayWithinTrainedErrorEnvelope() {
var squaredErrorSum = 0.0
var errorCount = 0
val absoluteErrors = ArrayList<Float>(2_700_000)
fixtures().forEach { fixture ->
val plan = plan(fixture)
val generated = DngHdrProfileGainTableCpuReference.generate(plan)
fixture.expectedGains.forEachIndexed { cell, expectedCurve ->
fixture.tableInputs.forEachIndexed { inputIndex, tableInput ->
val predicted = sampleCurve(
generated,
cell,
plan.pointCount,
tableInput,
)
val errorEv = log2(
max(predicted, 1e-8f) / max(expectedCurve[inputIndex], 1e-8f)
)
squaredErrorSum += errorEv * errorEv
absoluteErrors += abs(errorEv)
errorCount++
}
}
}
absoluteErrors.sort()
val rmse = sqrt(squaredErrorSum / errorCount)
val p95 = absoluteErrors[(absoluteErrors.size * 0.95).toInt()]
assertTrue("PXLs2 dense curve RMSE=$rmse EV", rmse <= 0.155)
assertTrue("PXLs2 dense curve p95=$p95 EV", p95 <= 0.290f)
}
@Test
fun generatedCurvesEnforceBlackToeShoulderAndEndpointRules() {
fixtures().forEach { fixture ->
val plan = plan(fixture)
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
val googlePlan = requireNotNull(plan.googlePlan)
val curveParameters = googlePlan.curveParameters
googlePlan.cellPlans.forEachIndexed { cell, cellPlan ->
assertEquals(googlePlan.inputScale, cellPlan.endpointGain, 0f)
assertTrue(
cellPlan.blackGain in
curveParameters.minBlackGain..curveParameters.maxTableGain
)
assertTrue(
cellPlan.shapePower in
curveParameters.minShapePower..curveParameters.maxShapePower
)
var previousOutput = 0f
repeat(plan.pointCount) { point ->
val tableInput = tableInput(point, plan.pointCount)
val gain = gains[cell * plan.pointCount + point]
val output = tableInput * gain
assertTrue("${fixture.sourceName} gain=$gain", gain.isFinite() && gain > 0f)
assertTrue(
"${fixture.sourceName} output reversal at point=$point",
output + 2e-6f >= previousOutput,
)
assertTrue(
"${fixture.sourceName} output overflow=$output",
output <= max(1f, googlePlan.inputScale) + 2e-6f,
)
if (tableInput <= curveParameters.toeEnd) {
assertEquals(cellPlan.blackGain, gain, 2e-6f)
}
previousOutput = output
}
assertEquals(
googlePlan.inputScale,
gains[cell * plan.pointCount + plan.pointCount - 1],
1e-6f,
)
}
}
}
@Test
fun baselineExposureDoesNotReciprocallyClampTheLearnedDomain() {
val fixtures = fixtures()
val plans = fixtures.map(::plan)
assertTrue(
fixtures.zip(plans).any { (fixture, plan) ->
requireNotNull(plan.googlePlan).inputScale * DngBaselineExposure.exactGain(
fixture.baselineExposureEv
) > 1.25f
}
)
assertTrue(plans.maxOf { requireNotNull(it.googlePlan).inputScale } > 0.95f)
assertTrue(plans.minOf { requireNotNull(it.googlePlan).inputScale } < 0.45f)
}
@Test
fun largerNoiseFloorReducesUnsupportedBlackLift() {
val fixture = fixtures().first()
val quieter = plan(fixture, noiseOffset = fixture.noiseOffset * 0.25f)
val noisier = plan(fixture, noiseOffset = fixture.noiseOffset * 4f)
assertTrue(
median(requireNotNull(noisier.googlePlan).cellPlans.map { it.blackGain }) <
median(requireNotNull(quieter.googlePlan).cellPlans.map { it.blackGain })
)
}
private fun plan(
fixture: Fixture,
noiseOffset: Float = fixture.noiseOffset,
): HdrProfileGainTablePlan = requireNotNull(
DngHdrProfileGainTableGenerator.planForCellStats(
width = fixture.width,
height = fixture.height,
baselineExposureEv = fixture.baselineExposureEv,
packedCellStats = fixture.packedStats,
noiseSlope = fixture.noiseSlope,
noiseOffset = noiseOffset,
)
)
private fun fixtures(): List<Fixture> = fixtureCache
private fun sampleCurve(
gains: FloatArray,
cell: Int,
pointCount: Int,
tableInput: Float,
): Float {
if (tableInput >= 1f) return gains[cell * pointCount + pointCount - 1]
val scaled = tableInput.coerceIn(0f, 1f) * pointCount
val first = scaled.toInt().coerceIn(0, pointCount - 1)
val second = (first + 1).coerceAtMost(pointCount - 1)
val amount = scaled - first
val offset = cell * pointCount
return gains[offset + first] * (1f - amount) + gains[offset + second] * amount
}
private fun tableInput(point: Int, pointCount: Int): Float =
if (point == pointCount - 1) 1f else point.toFloat() / pointCount.toFloat()
private fun median(values: List<Float>): Float {
val sorted = values.sorted()
val center = sorted.size / 2
return if (sorted.size % 2 == 0) {
0.5f * (sorted[center - 1] + sorted[center])
} else {
sorted[center]
}
}
private fun log2(value: Float): Float = (ln(value.toDouble()) / ln(2.0)).toFloat()
private data class Fixture(
val sourceName: String,
val width: Int,
val height: Int,
val baselineExposureEv: Float,
val mapH: Int,
val mapV: Int,
val inputWeights: FloatArray,
val noiseSlope: Float,
val noiseOffset: Float,
val tableInputs: FloatArray,
val packedStats: FloatArray,
val expectedGains: Array<FloatArray>,
)
companion object {
private val MAGIC = "PGTFIX3\u0000".toByteArray(Charsets.US_ASCII)
private val fixtureCache: List<Fixture> by lazy {
val loader = requireNotNull(
DngHdrProfileGainTableGeneratorTest::class.java.classLoader
)
val resource = requireNotNull(loader.getResource("pgtm/pxls2"))
File(resource.toURI()).listFiles()
.orEmpty()
.filter { it.isFile && it.extension == "pgtfix" }
.sortedBy { it.name }
.map(::readFixture)
}
private fun readFixture(file: File): Fixture {
val buffer = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN)
val magic = ByteArray(MAGIC.size).also(buffer::get)
require(magic.contentEquals(MAGIC)) { "invalid fixture ${file.name}" }
val width = buffer.int
val height = buffer.int
val baseline = buffer.float
val mapH = buffer.int
val mapV = buffer.int
val inputCount = buffer.int
val statCount = buffer.int
val gainCount = buffer.int
val weights = FloatArray(5) { buffer.float }
val gamma = buffer.float
require(gamma == 1f)
val noiseSlope = buffer.float
val noiseOffset = buffer.float
val tableInputs = FloatArray(inputCount) { buffer.float }
val packedStats = FloatArray(statCount) { buffer.float }
require(gainCount == mapH * mapV * inputCount)
val expected = Array(mapH * mapV) {
FloatArray(inputCount) { buffer.float }
}
return Fixture(
sourceName = file.name,
width = width,
height = height,
baselineExposureEv = baseline,
mapH = mapH,
mapV = mapV,
inputWeights = weights,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
tableInputs = tableInputs,
packedStats = packedStats,
expectedGains = expected,
)
}
}
}
@@ -1,24 +0,0 @@
package com.hinnka.mycamera.raw
internal fun DngHdrProfileGainTableGenerator.generateForCellStats(
width: Int,
height: Int,
baselineExposureEv: Float,
packedCellStats: FloatArray,
noiseSlope: Float,
noiseOffset: Float,
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand? = null,
curveModel: HdrPgtmCurveModel = HdrPgtmCurveModel.GOOGLE,
): DngProfileGainTableMap? {
val plan = planForCellStats(
width = width,
height = height,
baselineExposureEv = baselineExposureEv,
packedCellStats = packedCellStats,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
diagnosticBand = diagnosticBand,
curveModel = curveModel,
) ?: return null
return mapFromGpuGains(plan, DngHdrProfileGainTableCpuReference.generate(plan))
}
@@ -38,7 +38,7 @@ class DngPhotonProfileGainTableGeneratorTest {
gridWidth = 4,
gridHeight = 2,
baselineExposureEv = 3f,
samplingArea = HdrPgtmSamplingArea(
samplingArea = PhotonPgtmSamplingArea(
originH = 0.25,
originV = 0.125,
extentH = 0.5,
@@ -55,7 +55,7 @@ class DngPhotonProfileGainTableGeneratorTest {
assertEquals(weight / exposureGain, plan.mapInputWeights[index], 1e-7f)
}
val map = requireNotNull(
DngHdrProfileGainTableGenerator.mapFromGpuGains(
DngPhotonProfileGainTableGenerator.mapFromGpuGains(
plan,
FloatArray(plan.cellCount * plan.pointCount) { 1f },
)
@@ -253,9 +253,9 @@ class DngPhotonProfileGainTableGeneratorTest {
gridWidth: Int,
gridHeight: Int,
baselineExposureEv: Float,
samplingArea: HdrPgtmSamplingArea = HdrPgtmSamplingArea.FULL,
): HdrProfileGainTablePlan = DngPhotonProfileGainTableGenerator.plan(
grid = HdrPgtmGrid(
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
): PhotonProfileGainTablePlan = DngPhotonProfileGainTableGenerator.plan(
grid = PhotonPgtmGrid(
mapPointsH = gridWidth,
mapPointsV = gridHeight,
mapSpacingH = if (gridWidth > 1) 1.0 / (gridWidth - 1) else 1.0,
@@ -7,10 +7,10 @@ import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
class DngHdrProfileGainTableGpuShadersTest {
class DngPhotonProfileGainTableInputShaderTest {
@Test
fun cellStatsKeeps256SamplesWith128CooperativeLanes() {
val shader = DngHdrProfileGainTableGpuShaders.CELL_STATS
fun cellSamplesKeeps256SamplesWith128CooperativeLanes() {
val shader = DngPhotonProfileGainTableInputShader.CELL_SAMPLES
assertEquals(
GlesComputeWorkGroup.Size(x = 16, y = 8, z = 1),
@@ -19,13 +19,13 @@ class DngHdrProfileGainTableGpuShadersTest {
assertTrue(shader.contains("const uint CELL_SAMPLE_COUNT = 256u;"))
assertTrue(shader.contains("const uint CELL_LANE_COUNT = 128u;"))
assertTrue(shader.contains("sampleIndex += CELL_LANE_COUNT"))
assertTrue(shader.contains("localIndex += CELL_LANE_COUNT"))
assertTrue(shader.contains("sortSamples(localIndex);"))
GlesComputeWorkGroup.requireBaselineCompatible(shader, "DNG_PGTM_CELL_STATS")
assertTrue(!shader.contains("sortSamples"))
assertTrue(!shader.contains("shared "))
GlesComputeWorkGroup.requireBaselineCompatible(shader, "DNG_PGTM_CELL_SAMPLES")
}
@Test
fun cellStatsPassesAvailableNdkValidator() {
fun cellSamplesPassesAvailableNdkValidator() {
val sdkRoot = System.getenv("ANDROID_SDK_ROOT") ?: System.getenv("ANDROID_HOME")
val validator = sdkRoot?.let(::File)
?.resolve("ndk")
@@ -40,10 +40,10 @@ class DngHdrProfileGainTableGpuShadersTest {
?.firstOrNull()
assumeTrue("Android NDK glslc is unavailable", validator != null)
val sourceFile = File.createTempFile("dng-pgtm-cell-stats-", ".compute")
val outputFile = File.createTempFile("dng-pgtm-cell-stats-", ".spv")
val sourceFile = File.createTempFile("dng-pgtm-cell-samples-", ".compute")
val outputFile = File.createTempFile("dng-pgtm-cell-samples-", ".spv")
try {
sourceFile.writeText(DngHdrProfileGainTableGpuShaders.CELL_STATS)
sourceFile.writeText(DngPhotonProfileGainTableInputShader.CELL_SAMPLES)
val process = ProcessBuilder(
checkNotNull(validator).absolutePath,
"--target-env=opengl",
@@ -0,0 +1,42 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DngProfileToneCurveTest {
@Test
fun photonPgtmFormulaIsMonotonicAndRetainsToneShape() {
val points = DngProfileToneCurve.photonPgtmToneCurvePoints()
assertEquals(257 * 2, points.size)
assertEquals(0f, points[0], 0f)
assertEquals(0f, points[1], 0f)
assertEquals(1f, points[points.lastIndex - 1], 0f)
assertEquals(1f, points.last(), 0f)
var previousX = -1f
var previousY = -1f
for (index in points.indices step 2) {
val x = points[index]
val y = points[index + 1]
assertTrue("x must increase at point ${index / 2}", x > previousX)
assertTrue("y must increase at point ${index / 2}", y > previousY)
assertTrue("y must stay normalized at point ${index / 2}", y in 0f..1f)
previousX = x
previousY = y
}
assertEquals(0.000008f, outputAt(points, 1f / 256f), 0.000004f)
assertEquals(0.0053f, outputAt(points, 0.03125f), 0.001f)
assertEquals(0.483f, outputAt(points, 0.5f), 0.01f)
assertEquals(0.900f, outputAt(points, 0.875f), 0.01f)
assertTrue(outputAt(points, 0.125f) < 0.125f)
assertTrue(outputAt(points, 0.75f) > 0.75f)
}
private fun outputAt(points: FloatArray, input: Float): Float {
val pointIndex = (input * 256f).toInt()
assertEquals(input, points[pointIndex * 2], 1e-7f)
return points[pointIndex * 2 + 1]
}
}