feat: new photon pgtm
This commit is contained in:
1 parent
f154e877ad
commit
2dc800bcc2
9 files changed
+1142
-125
No files matched your search
@@ -32,7 +32,7 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
internal const val BASE_INPUT_WEIGHT_MIN = 0.1250f
|
||||
internal const val BASE_INPUT_WEIGHT_MAX = 0.3750f
|
||||
|
||||
private val BASE_INPUT_WEIGHTS = floatArrayOf(
|
||||
internal val BASE_INPUT_WEIGHTS = floatArrayOf(
|
||||
BASE_INPUT_WEIGHT_RED,
|
||||
BASE_INPUT_WEIGHT_GREEN,
|
||||
BASE_INPUT_WEIGHT_BLUE,
|
||||
@@ -40,8 +40,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
BASE_INPUT_WEIGHT_MAX,
|
||||
)
|
||||
|
||||
// Keep complete, independent parameter sets even while values match. Google fitting and
|
||||
// Photon look development can then change curve limits without adding mode branches.
|
||||
internal val GOOGLE_CURVE_PARAMETERS = HdrPgtmCurveParameters(
|
||||
minTableGain = 0.01f,
|
||||
maxTableGain = 4.80f,
|
||||
@@ -56,18 +54,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
maxInputScale = 1.05f,
|
||||
)
|
||||
|
||||
internal val PHOTON_CURVE_PARAMETERS = HdrPgtmCurveParameters(
|
||||
minTableGain = 0.01f,
|
||||
maxTableGain = 4.80f,
|
||||
minBlackGain = 0.50f,
|
||||
toeEnd = 0.015f,
|
||||
shapeQ = 2.445f,
|
||||
minShapePower = 1.05f,
|
||||
maxShapePower = 1.25f,
|
||||
minInputScale = 0.05f,
|
||||
maxInputScale = 1.05f,
|
||||
)
|
||||
|
||||
fun gridSizeFor(width: Int, height: Int): IntArray {
|
||||
val grid = chooseLtmGrid(width, height)
|
||||
return intArrayOf(grid.mapPointsH, grid.mapPointsV)
|
||||
@@ -82,7 +68,7 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
noiseOffset: Float = FALLBACK_NOISE_OFFSET,
|
||||
tablePointCount: Int = TABLE_POINTS,
|
||||
diagnosticBand: DiagnosticBand? = null,
|
||||
curveParameters: HdrPgtmCurveParameters = GOOGLE_CURVE_PARAMETERS,
|
||||
curveModel: HdrPgtmCurveModel = HdrPgtmCurveModel.GOOGLE,
|
||||
): HdrProfileGainTablePlan? {
|
||||
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) return null
|
||||
val grid = chooseLtmGrid(width, height)
|
||||
@@ -105,6 +91,20 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
?: FALLBACK_NOISE_SLOPE
|
||||
val safeNoiseOffset = noiseOffset.takeIf { it.isFinite() && it > 0f }
|
||||
?: FALLBACK_NOISE_OFFSET
|
||||
if (curveModel == HdrPgtmCurveModel.PHOTON) {
|
||||
return DngPhotonProfileGainTableGenerator.plan(
|
||||
grid = grid,
|
||||
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
cells = cells,
|
||||
global = global,
|
||||
noiseSlope = safeNoiseSlope,
|
||||
noiseOffset = safeNoiseOffset,
|
||||
diagnosticBand = diagnosticBand?.sanitized(),
|
||||
)
|
||||
}
|
||||
|
||||
val curveParameters = GOOGLE_CURVE_PARAMETERS
|
||||
val inputScale = estimateInputScale(global, baselineExposureEv, curveParameters)
|
||||
val globalPlan = buildGlobalCurvePlan(
|
||||
stats = global,
|
||||
@@ -122,11 +122,17 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
curveParameters = curveParameters,
|
||||
)
|
||||
return HdrProfileGainTablePlan(
|
||||
curveModel = HdrPgtmCurveModel.GOOGLE,
|
||||
grid = grid,
|
||||
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
|
||||
inputScale = inputScale,
|
||||
curveParameters = curveParameters,
|
||||
cellPlans = cellPlans,
|
||||
mapInputWeights = ltmInputWeights(inputScale, curveParameters),
|
||||
gamma = 1f,
|
||||
googlePlan = GooglePgtmPlan(
|
||||
inputScale = inputScale,
|
||||
curveParameters = curveParameters,
|
||||
cellPlans = cellPlans,
|
||||
),
|
||||
photonPlan = null,
|
||||
diagnosticBand = diagnosticBand?.sanitized(),
|
||||
)
|
||||
}
|
||||
@@ -308,8 +314,8 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
mapOriginV = 0.0,
|
||||
mapOriginH = 0.0,
|
||||
mapPointsN = plan.pointCount,
|
||||
mapInputWeights = ltmInputWeights(plan.inputScale, plan.curveParameters),
|
||||
gamma = 1f,
|
||||
mapInputWeights = plan.mapInputWeights,
|
||||
gamma = plan.gamma,
|
||||
gains = gains,
|
||||
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2,
|
||||
)
|
||||
@@ -357,12 +363,37 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
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>,
|
||||
val diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
|
||||
)
|
||||
|
||||
internal data class HdrPgtmCurveParameters(
|
||||
|
||||
@@ -22,6 +22,7 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
uniform float uBaselineGain;
|
||||
uniform float uHighlightThreshold;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform int uHueSatEnabled;
|
||||
@@ -218,7 +219,7 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
}
|
||||
int highlightCount = 0;
|
||||
for (int sampleIndex = 0; sampleIndex < 256; ++sampleIndex) {
|
||||
if (inputSamples[sampleIndex] >= 0.92) ++highlightCount;
|
||||
if (inputSamples[sampleIndex] >= uHighlightThreshold) ++highlightCount;
|
||||
}
|
||||
cellStats[statsOffset] = inputSamples[25];
|
||||
cellStats[statsOffset + 1] = inputSamples[127];
|
||||
@@ -232,7 +233,7 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val GAIN_CURVES = """
|
||||
val GOOGLE_GAIN_CURVES = """
|
||||
#version 310 es
|
||||
|
||||
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
|
||||
@@ -340,4 +341,161 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val PHOTON_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 uExposureGain;
|
||||
uniform float uMapGamma;
|
||||
uniform float uExposedPivot;
|
||||
uniform float uPivotOutput;
|
||||
uniform float uEndpointOutput;
|
||||
uniform float uLowSlope;
|
||||
uniform float uLowCurveLift;
|
||||
uniform float uShoulderParameter;
|
||||
uniform float uMinTableGain;
|
||||
uniform float uMaxTableGain;
|
||||
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);
|
||||
}
|
||||
|
||||
float localContrastWarp(float exposedInput, float contrastExponent) {
|
||||
float endpoint = max(uExposureGain, uExposedPivot + CURVE_EPS);
|
||||
if (exposedInput <= uExposedPivot) {
|
||||
float normalized = clamp(
|
||||
exposedInput / max(uExposedPivot, CURVE_EPS),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
return uExposedPivot * pow(normalized, contrastExponent);
|
||||
}
|
||||
float normalized = clamp(
|
||||
(endpoint - exposedInput) /
|
||||
max(endpoint - uExposedPivot, CURVE_EPS),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
return endpoint -
|
||||
(endpoint - uExposedPivot) * pow(normalized, contrastExponent);
|
||||
}
|
||||
|
||||
float lowCurve(float exposedInput) {
|
||||
float x = clamp(
|
||||
exposedInput / max(uExposedPivot, CURVE_EPS),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float oneMinusX = 1.0 - x;
|
||||
float lifted = x +
|
||||
uLowCurveLift * x * x * oneMinusX * oneMinusX;
|
||||
return uPivotOutput * lifted;
|
||||
}
|
||||
|
||||
float shoulderCurve(float exposedInput) {
|
||||
float span = max(uExposureGain - uExposedPivot, CURVE_EPS);
|
||||
float r = clamp((exposedInput - uExposedPivot) / span, 0.0, 1.0);
|
||||
float shaped;
|
||||
if (uShoulderParameter > 1e-4) {
|
||||
shaped = log(1.0 + uShoulderParameter * r) /
|
||||
log(1.0 + uShoulderParameter);
|
||||
} else if (uShoulderParameter < -1e-4) {
|
||||
float convexA = -uShoulderParameter;
|
||||
shaped = (exp(convexA * r) - 1.0) / (exp(convexA) - 1.0);
|
||||
} else {
|
||||
shaped = r;
|
||||
}
|
||||
return uPivotOutput + (uEndpointOutput - uPivotOutput) * shaped;
|
||||
}
|
||||
|
||||
float globalCurve(float exposedInput) {
|
||||
return exposedInput <= uExposedPivot
|
||||
? lowCurve(exposedInput)
|
||||
: shoulderCurve(exposedInput);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int cellIndex = int(gl_GlobalInvocationID.x);
|
||||
if (cellIndex >= uCellCount) return;
|
||||
|
||||
float contrastExponent = clamp(curvePlans[cellIndex], 1.0, 1.18);
|
||||
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 sourceInput = pow(max(tableInput, 0.0), 1.0 / uMapGamma);
|
||||
float exposedInput = uExposureGain * sourceInput;
|
||||
float warpedInput = localContrastWarp(exposedInput, contrastExponent);
|
||||
float mappedOutput = globalCurve(warpedInput);
|
||||
float trueGain = exposedInput <= CURVE_EPS
|
||||
? clamp(uLowSlope, uMinTableGain, uMaxTableGain)
|
||||
: clamp(mappedOutput / exposedInput, 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,
|
||||
exposedInput * mixedGain
|
||||
);
|
||||
finalGain = exposedInput <= CURVE_EPS
|
||||
? clamp(mixedGain, uMinTableGain, uMaxTableGain)
|
||||
: clamp(
|
||||
monotonicOutput / exposedInput,
|
||||
uMinTableGain,
|
||||
uMaxTableGain
|
||||
);
|
||||
previousFinalOutput = monotonicOutput;
|
||||
}
|
||||
gainCurves[outputOffset + point] = finalGain;
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/** Photon-owned analytic PGTM planner. Google fitting is intentionally not reused here. */
|
||||
internal object DngPhotonProfileGainTableGenerator {
|
||||
private const val REFERENCE_GRAY = 0.18f
|
||||
private const val REFERENCE_GRAY_EV = 1.1f
|
||||
private const val TABLE_PIVOT = 0.18f
|
||||
private const val MAX_ENDPOINT_OUTPUT = 1.30f
|
||||
private const val MIN_MAP_GAMMA = 0.125f
|
||||
private const val MAX_MAP_GAMMA = 8.0f
|
||||
private const val MIN_TABLE_GAIN = 1f / 4096f
|
||||
private const val MAX_TABLE_GAIN = 4096f
|
||||
private const val FIXED_GRAY_SOURCE_LIMIT = 0.995f
|
||||
private const val SOURCE_EPS = 1e-6f
|
||||
private const val LOW_CURVE_LIFT = 1.50f
|
||||
private const val MAX_LOCAL_CONTRAST = 0.18f
|
||||
private const val MAX_LOCAL_CONTRAST_EXPONENT = 1.18f
|
||||
|
||||
// Invert the exact LUT used by the renderer so PGTM + ProfileToneCurve, as a pair,
|
||||
// places exposed 18% gray at +1.1 EV.
|
||||
internal val referenceGrayOutput: Float by lazy {
|
||||
DngProfileToneCurve.photonPgtmInputForOutput(
|
||||
REFERENCE_GRAY * 2.0f.pow(REFERENCE_GRAY_EV)
|
||||
)
|
||||
}
|
||||
|
||||
fun plan(
|
||||
grid: HdrPgtmGrid,
|
||||
pointCount: Int,
|
||||
baselineExposureEv: Float,
|
||||
cells: Array<HdrPgtmCellStats?>,
|
||||
global: HdrPgtmCellStats,
|
||||
noiseSlope: Float,
|
||||
noiseOffset: Float,
|
||||
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
|
||||
): HdrProfileGainTablePlan {
|
||||
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
|
||||
val referenceSourcePivot = REFERENCE_GRAY / exposureGain
|
||||
// Below log2(0.18) EV, exposed 18% lies beyond the captured source domain. There is no
|
||||
// exact fixed-gray solution, so anchor the same output level at the scene median instead.
|
||||
val usesFixedGray = referenceSourcePivot.isFinite() &&
|
||||
referenceSourcePivot > SOURCE_EPS &&
|
||||
referenceSourcePivot < FIXED_GRAY_SOURCE_LIMIT
|
||||
val sourcePivot = if (usesFixedGray) {
|
||||
referenceSourcePivot
|
||||
} else {
|
||||
global.p50.coerceIn(0.05f, 0.75f)
|
||||
}
|
||||
val gamma = adaptiveGamma(sourcePivot)
|
||||
val tablePivot = sourcePivot.pow(gamma).coerceIn(1e-4f, 0.999f)
|
||||
val exposedPivot = (exposureGain * sourcePivot).coerceAtLeast(SOURCE_EPS)
|
||||
val endpointOutput = (
|
||||
1f + (MAX_ENDPOINT_OUTPUT - 1f) * highlightPressure(
|
||||
global = global,
|
||||
exposureGain = exposureGain,
|
||||
)
|
||||
).coerceIn(1f, MAX_ENDPOINT_OUTPUT)
|
||||
val pivotOutput = referenceGrayOutput.coerceIn(0.05f, endpointOutput - 1e-4f)
|
||||
val lowSlope = pivotOutput / exposedPivot
|
||||
val shoulderSecant = (endpointOutput - pivotOutput) /
|
||||
(exposureGain - exposedPivot).coerceAtLeast(SOURCE_EPS)
|
||||
val shoulderParameter = solveShoulderParameter(
|
||||
normalizedInitialSlope = lowSlope / shoulderSecant.coerceAtLeast(SOURCE_EPS)
|
||||
)
|
||||
val cellPlans = buildCellPlans(
|
||||
cells = cells,
|
||||
grid = grid,
|
||||
global = global,
|
||||
noiseSlope = noiseSlope,
|
||||
noiseOffset = noiseOffset,
|
||||
)
|
||||
// DNG renderers include BaselineExposure while calculating the table coordinate.
|
||||
// Dividing the weights by that gain keeps Photon table sampling in source-linear space.
|
||||
val mapWeights = FloatArray(DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHTS.size) {
|
||||
DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHTS[it] / exposureGain
|
||||
}
|
||||
val photonPlan = PhotonPgtmPlan(
|
||||
exposureGain = exposureGain,
|
||||
sourcePivot = sourcePivot,
|
||||
exposedPivot = exposedPivot,
|
||||
tablePivot = tablePivot,
|
||||
pivotOutput = pivotOutput,
|
||||
endpointOutput = endpointOutput,
|
||||
lowSlope = lowSlope,
|
||||
lowCurveLift = LOW_CURVE_LIFT,
|
||||
shoulderParameter = shoulderParameter,
|
||||
minTableGain = MIN_TABLE_GAIN,
|
||||
maxTableGain = MAX_TABLE_GAIN,
|
||||
usesFixedGray = usesFixedGray,
|
||||
cellPlans = cellPlans,
|
||||
)
|
||||
return HdrProfileGainTablePlan(
|
||||
curveModel = HdrPgtmCurveModel.PHOTON,
|
||||
grid = grid,
|
||||
pointCount = pointCount,
|
||||
mapInputWeights = mapWeights,
|
||||
gamma = gamma,
|
||||
googlePlan = null,
|
||||
photonPlan = photonPlan,
|
||||
diagnosticBand = diagnosticBand,
|
||||
)
|
||||
}
|
||||
|
||||
private fun adaptiveGamma(sourcePivot: Float): Float {
|
||||
val safePivot = sourcePivot.coerceIn(SOURCE_EPS, 1f - SOURCE_EPS)
|
||||
val value = ln(TABLE_PIVOT.toDouble()) / ln(safePivot.toDouble())
|
||||
return value.toFloat().takeIf { it.isFinite() }
|
||||
?.coerceIn(MIN_MAP_GAMMA, MAX_MAP_GAMMA)
|
||||
?: 1f
|
||||
}
|
||||
|
||||
private fun highlightPressure(
|
||||
global: HdrPgtmCellStats,
|
||||
exposureGain: Float,
|
||||
): Float {
|
||||
val exposedTail = exposureGain * max(global.p999Input, global.p98)
|
||||
val tailStrength = smoothStep(1.0f, 2.5f, exposedTail)
|
||||
val tailSpanEv = log2(
|
||||
(global.p999Input + 0.01f) / (global.p98 + 0.01f)
|
||||
)
|
||||
val tailSeparation = smoothStep(0.15f, 1.50f, tailSpanEv)
|
||||
val exposedHighlightPresence = smoothStep(0.85f, 1.10f, exposedTail)
|
||||
val broadHighlight = smoothStep(0.02f, 0.20f, global.highlightFraction)
|
||||
val sparsePreference = 1f - 0.75f * broadHighlight
|
||||
return max(tailStrength, tailSeparation * exposedHighlightPresence)
|
||||
.coerceIn(0f, 1f) * sparsePreference
|
||||
}
|
||||
|
||||
private fun buildCellPlans(
|
||||
cells: Array<HdrPgtmCellStats?>,
|
||||
grid: HdrPgtmGrid,
|
||||
global: HdrPgtmCellStats,
|
||||
noiseSlope: Float,
|
||||
noiseOffset: Float,
|
||||
): Array<PhotonPgtmCellPlan> {
|
||||
val rawStrength = FloatArray(cells.size) { index ->
|
||||
val cell = cells[index] ?: global
|
||||
val signal = cell.p50.coerceAtLeast(0f)
|
||||
val variance = max(noiseSlope * signal + noiseOffset, 1e-12f)
|
||||
val snr = signal / sqrt(variance)
|
||||
val snrGate = smoothStep(3f, 16f, snr)
|
||||
val rangeEv = log2((cell.p90 + 0.006f) / (cell.p10 + 0.006f))
|
||||
val lowContrastOpportunity = 1f - smoothStep(2.5f, 6f, rangeEv)
|
||||
val highlightGate = 1f - 0.80f * smoothStep(
|
||||
0.08f,
|
||||
0.55f,
|
||||
cell.highlightFraction,
|
||||
)
|
||||
((0.08f + 0.10f * lowContrastOpportunity) * snrGate * highlightGate)
|
||||
.coerceIn(0f, MAX_LOCAL_CONTRAST)
|
||||
}
|
||||
val smoothedContrast = smoothScalarField(rawStrength, grid)
|
||||
return Array(cells.size) { index ->
|
||||
val contrastExponent = (
|
||||
1f + smoothedContrast[index].coerceIn(0f, MAX_LOCAL_CONTRAST)
|
||||
).coerceIn(1f, MAX_LOCAL_CONTRAST_EXPONENT)
|
||||
PhotonPgtmCellPlan(
|
||||
contrastExponent = contrastExponent,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun smoothScalarField(
|
||||
source: FloatArray,
|
||||
grid: HdrPgtmGrid,
|
||||
): FloatArray = FloatArray(source.size) { index ->
|
||||
val x = index % grid.mapPointsH
|
||||
val y = index / grid.mapPointsH
|
||||
var weightedSum = 0f
|
||||
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
|
||||
}
|
||||
weightedSum += source[yy * grid.mapPointsH + xx] * weight
|
||||
weightSum += weight
|
||||
}
|
||||
}
|
||||
weightedSum / weightSum
|
||||
}
|
||||
|
||||
/**
|
||||
* Positive values select a logarithmic shoulder: q = c / ln(1 + c). This distributes
|
||||
* compressed HDR stops much more evenly than an exponential saturation curve. Negative
|
||||
* values retain a convex exponential branch for the uncommon q < 1 case.
|
||||
*/
|
||||
private fun solveShoulderParameter(normalizedInitialSlope: Float): Float {
|
||||
val target = normalizedInitialSlope.coerceIn(1e-4f, 2048f).toDouble()
|
||||
if (kotlin.math.abs(target - 1.0) < 1e-6) return 0f
|
||||
if (target > 1.0) {
|
||||
var low = 0.0
|
||||
var high = 1.0
|
||||
while (high / ln(1.0 + high) < target && high < 1e8) high *= 2.0
|
||||
repeat(80) {
|
||||
val mid = 0.5 * (low + high)
|
||||
val ratio = if (mid < 1e-8) 1.0 else mid / ln(1.0 + mid)
|
||||
if (ratio < target) low = mid else high = mid
|
||||
}
|
||||
return (0.5 * (low + high)).toFloat()
|
||||
}
|
||||
|
||||
var low = 0.0
|
||||
var high = 64.0
|
||||
repeat(80) {
|
||||
val mid = 0.5 * (low + high)
|
||||
val ratio = if (mid < 1e-8) {
|
||||
1.0
|
||||
} else {
|
||||
mid / (exp(mid) - 1.0)
|
||||
}
|
||||
if (ratio > target) low = mid else high = mid
|
||||
}
|
||||
return -(0.5 * (low + high)).toFloat()
|
||||
}
|
||||
|
||||
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val amount = ((value - edge0) / (edge1 - edge0).coerceAtLeast(1e-6f))
|
||||
.coerceIn(0f, 1f)
|
||||
return amount * amount * (3f - 2f * amount)
|
||||
}
|
||||
|
||||
private fun log2(value: Float): Float =
|
||||
(ln(max(value, 1e-8f).toDouble()) / ln(2.0)).toFloat()
|
||||
}
|
||||
|
||||
internal data class PhotonPgtmPlan(
|
||||
val exposureGain: Float,
|
||||
val sourcePivot: Float,
|
||||
val exposedPivot: Float,
|
||||
val tablePivot: Float,
|
||||
val pivotOutput: Float,
|
||||
val endpointOutput: Float,
|
||||
val lowSlope: Float,
|
||||
val lowCurveLift: Float,
|
||||
val shoulderParameter: Float,
|
||||
val minTableGain: Float,
|
||||
val maxTableGain: Float,
|
||||
val usesFixedGray: Boolean,
|
||||
val cellPlans: Array<PhotonPgtmCellPlan>,
|
||||
) {
|
||||
init {
|
||||
require(exposureGain.isFinite() && exposureGain > 0f)
|
||||
require(sourcePivot.isFinite() && sourcePivot in 0f..1f)
|
||||
require(exposedPivot.isFinite() && exposedPivot > 0f)
|
||||
require(tablePivot.isFinite() && tablePivot in 0f..1f)
|
||||
require(pivotOutput.isFinite() && endpointOutput.isFinite())
|
||||
require(pivotOutput in 0f..endpointOutput && endpointOutput in 1f..1.3f)
|
||||
require(lowSlope.isFinite() && lowSlope > 0f)
|
||||
require(lowCurveLift.isFinite() && lowCurveLift in 0f..5f)
|
||||
require(shoulderParameter.isFinite())
|
||||
require(minTableGain > 0f && maxTableGain >= minTableGain)
|
||||
val invalidCell = cellPlans.indexOfFirst { cellPlan ->
|
||||
!cellPlan.contrastExponent.isFinite() || cellPlan.contrastExponent !in 1f..1.18f
|
||||
}
|
||||
require(invalidCell < 0) {
|
||||
"Invalid Photon PGTM cell[$invalidCell]=${cellPlans.getOrNull(invalidCell)} " +
|
||||
"globalEndpoint=$endpointOutput"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class PhotonPgtmCellPlan(
|
||||
val contrastExponent: Float,
|
||||
)
|
||||
@@ -108,6 +108,10 @@ internal object DngProfileToneCurve {
|
||||
1.00000000f, 1.000000000f
|
||||
)
|
||||
|
||||
private val PHOTON_PGTM_TONE_CURVE_LUT by lazy {
|
||||
DcpToneCurve(photonPgtmToneCurvePoints()).toLut(256)
|
||||
}
|
||||
|
||||
fun googleHdrToneCurvePoints(): FloatArray {
|
||||
return FloatArray(GOOGLE_HDR_TONE_CURVE_Y.size * 2) { index ->
|
||||
val pointIndex = index / 2
|
||||
@@ -145,7 +149,30 @@ internal object DngProfileToneCurve {
|
||||
}
|
||||
|
||||
fun photonPgtmToneCurveLut(sampleCount: Int = 256): FloatArray {
|
||||
return DcpToneCurve(photonPgtmToneCurvePoints()).toLut(sampleCount)
|
||||
return if (sampleCount == PHOTON_PGTM_TONE_CURVE_LUT.size) {
|
||||
PHOTON_PGTM_TONE_CURVE_LUT.copyOf()
|
||||
} else {
|
||||
DcpToneCurve(photonPgtmToneCurvePoints()).toLut(sampleCount)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun photonPgtmInputForOutput(output: Float): Float {
|
||||
val target = output.coerceIn(0f, 1f)
|
||||
val lut = PHOTON_PGTM_TONE_CURVE_LUT
|
||||
if (target <= lut.first()) return 0f
|
||||
if (target >= lut.last()) return 1f
|
||||
for (index in 1 until lut.size) {
|
||||
val upper = lut[index]
|
||||
if (upper < target) continue
|
||||
val lower = lut[index - 1]
|
||||
val amount = if (upper > lower) {
|
||||
(target - lower) / (upper - lower)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
return (index - 1 + amount) / (lut.size - 1f)
|
||||
}
|
||||
return 1f
|
||||
}
|
||||
|
||||
fun oppoEmbeddedToneCurvePoints(): FloatArray {
|
||||
|
||||
@@ -276,7 +276,8 @@ class RawDemosaicProcessor {
|
||||
private var quadRefineProgram = 0
|
||||
private var quadWriteOutputProgram = 0
|
||||
private var pgtmCellStatsProgram = 0
|
||||
private var pgtmGainCurvesProgram = 0
|
||||
private var pgtmGoogleGainCurvesProgram = 0
|
||||
private var pgtmPhotonGainCurvesProgram = 0
|
||||
private var linearRcdProgram = 0
|
||||
private var warpRectilinearProgram = 0
|
||||
private var linearRawRgbProgram = 0
|
||||
@@ -1284,10 +1285,9 @@ class RawDemosaicProcessor {
|
||||
if (generated != null) {
|
||||
profileGainTableMap = generated
|
||||
profileGainTableMapSource = "generated-gpu"
|
||||
} else if (profileGainTableMap != null) {
|
||||
// PGTM maps are curve-independent. A valid embedded map remains usable when the
|
||||
// user switches between the Photon and Google profile curves.
|
||||
profileGainTableMapSource = "embedded-reused"
|
||||
} else if (profileToneMapMode != requestedProfileToneMapMode) {
|
||||
profileGainTableMap = null
|
||||
profileGainTableMapSource = "generation-failed"
|
||||
}
|
||||
if (profileGainTableMap != null) {
|
||||
profileToneMapMode = requestedProfileToneMapMode
|
||||
@@ -1387,8 +1387,15 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
val hasProfileGainTableMap = actualMetadata.profileGainTableMap?.isValid == true
|
||||
val hasDngBaselineExposure = shouldApplyLinearDngBaselineExposure(actualMetadata)
|
||||
val applyLinearDngBaselineExposure = !useAdobeProfilePipeline && hasDngBaselineExposure
|
||||
val applyProfileDngBaselineExposure = useAdobeProfilePipeline
|
||||
// Photon curves are authored in the physical BaselineExposure domain. Apply that exact
|
||||
// 2^EV gain after PGTM in the linear pass for both EV signs; the generic Adobe negative
|
||||
// exposure tone preserves white and would otherwise invalidate the analytic curve.
|
||||
val photonPgtmExactBaseline = profileGainToneMapActive &&
|
||||
requestedProfileToneMapMode == RawProfileToneMapMode.Photon
|
||||
val applyLinearDngBaselineExposure = hasDngBaselineExposure &&
|
||||
(!useAdobeProfilePipeline || photonPgtmExactBaseline)
|
||||
val applyProfileDngBaselineExposure = useAdobeProfilePipeline &&
|
||||
!photonPgtmExactBaseline
|
||||
val applyDcpBaselineExposureOffset =
|
||||
shouldApplyDcpBaselineExposureOffset(activeDcpRenderPlan)
|
||||
val useProfileExposureRamp = useAdobeProfilePipeline
|
||||
@@ -2117,19 +2124,24 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
return null
|
||||
}
|
||||
if (pgtmCellStatsProgram == 0 || pgtmGainCurvesProgram == 0) {
|
||||
val curveModel = when (profileToneMapMode) {
|
||||
RawProfileToneMapMode.Photon -> HdrPgtmCurveModel.PHOTON
|
||||
RawProfileToneMapMode.GooglePixel -> HdrPgtmCurveModel.GOOGLE
|
||||
else -> return null
|
||||
}
|
||||
val curveProgram = when (curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> pgtmGoogleGainCurvesProgram
|
||||
HdrPgtmCurveModel.PHOTON -> pgtmPhotonGainCurvesProgram
|
||||
}
|
||||
if (pgtmCellStatsProgram == 0 || curveProgram == 0) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW PGTM programs unavailable: stats=$pgtmCellStatsProgram " +
|
||||
"curves=$pgtmGainCurvesProgram",
|
||||
"model=$curveModel curves=$curveProgram",
|
||||
)
|
||||
return null
|
||||
}
|
||||
val curveParameters = when (profileToneMapMode) {
|
||||
RawProfileToneMapMode.Photon -> DngHdrProfileGainTableGenerator.PHOTON_CURVE_PARAMETERS
|
||||
RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.GOOGLE_CURVE_PARAMETERS
|
||||
else -> return null
|
||||
}
|
||||
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
|
||||
val safeStatsBounds = sanitizePgtmStatsBounds(statsBounds, width, height) ?: run {
|
||||
PLog.e(TAG, "GPU RAW PGTM stats bounds invalid: source=${width}x$height bounds=$statsBounds")
|
||||
return null
|
||||
@@ -2228,7 +2240,11 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uBaselineGain"),
|
||||
DngBaselineExposure.exactGain(baselineExposureEv),
|
||||
if (curveModel == HdrPgtmCurveModel.PHOTON) 1f else exposureGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHighlightThreshold"),
|
||||
if (curveModel == HdrPgtmCurveModel.PHOTON) 1f / exposureGain else 0.92f,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uCameraWhite"),
|
||||
@@ -2271,31 +2287,49 @@ class RawDemosaicProcessor {
|
||||
noiseSlope = metadata.noiseProfile.getOrElse(0) { 0f },
|
||||
noiseOffset = metadata.noiseProfile.getOrElse(1) { 0f },
|
||||
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU capture"),
|
||||
curveParameters = curveParameters,
|
||||
curveModel = curveModel,
|
||||
) ?: return null
|
||||
val planReadyNs = System.nanoTime()
|
||||
if (plan.cellPlans.size != cellCount) {
|
||||
if (plan.cellCount != cellCount) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW PGTM plan count=${plan.cellPlans.size}, expected=$cellCount",
|
||||
"GPU RAW PGTM plan count=${plan.cellCount}, expected=$cellCount",
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
val curvePlanBuffer = ByteBuffer.allocateDirect(cellCount * 3 * Float.SIZE_BYTES)
|
||||
val curvePlanFloatCount = when (plan.curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> cellCount * 3
|
||||
HdrPgtmCurveModel.PHOTON -> cellCount
|
||||
}
|
||||
val curvePlanBuffer = ByteBuffer.allocateDirect(
|
||||
curvePlanFloatCount * Float.SIZE_BYTES
|
||||
)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer()
|
||||
plan.cellPlans.forEach { cellPlan ->
|
||||
curvePlanBuffer.put(cellPlan.blackGain)
|
||||
curvePlanBuffer.put(cellPlan.endpointGain)
|
||||
curvePlanBuffer.put(cellPlan.shapePower)
|
||||
when (plan.curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> {
|
||||
val googlePlan = requireNotNull(plan.googlePlan)
|
||||
googlePlan.cellPlans.forEach { cellPlan ->
|
||||
curvePlanBuffer.put(cellPlan.blackGain)
|
||||
curvePlanBuffer.put(cellPlan.endpointGain)
|
||||
curvePlanBuffer.put(cellPlan.shapePower)
|
||||
}
|
||||
}
|
||||
|
||||
HdrPgtmCurveModel.PHOTON -> {
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
photonPlan.cellPlans.forEach { cellPlan ->
|
||||
curvePlanBuffer.put(cellPlan.contrastExponent)
|
||||
}
|
||||
}
|
||||
}
|
||||
curvePlanBuffer.position(0)
|
||||
val planBufferId = bufferIds[1]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, planBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
cellCount * 3 * Float.SIZE_BYTES,
|
||||
curvePlanFloatCount * Float.SIZE_BYTES,
|
||||
curvePlanBuffer,
|
||||
GLES31.GL_STATIC_DRAW,
|
||||
)
|
||||
@@ -2311,62 +2345,112 @@ class RawDemosaicProcessor {
|
||||
GLES31.GL_DYNAMIC_READ,
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, gainBufferId)
|
||||
GLES31.glUseProgram(pgtmGainCurvesProgram)
|
||||
GLES31.glUseProgram(curveProgram)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uCellCount"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uCellCount"),
|
||||
cellCount,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uPointCount"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uPointCount"),
|
||||
plan.pointCount,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uInputScale"),
|
||||
plan.inputScale,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMinTableGain"),
|
||||
plan.curveParameters.minTableGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxTableGain"),
|
||||
plan.curveParameters.maxTableGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uToeEnd"),
|
||||
plan.curveParameters.toeEnd,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uShapeQ"),
|
||||
plan.curveParameters.shapeQ,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMinShapePower"),
|
||||
plan.curveParameters.minShapePower,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxShapePower"),
|
||||
plan.curveParameters.maxShapePower,
|
||||
)
|
||||
when (plan.curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> {
|
||||
val googlePlan = requireNotNull(plan.googlePlan)
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
HdrPgtmCurveModel.PHOTON -> {
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uExposureGain"),
|
||||
photonPlan.exposureGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uMapGamma"),
|
||||
plan.gamma,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uExposedPivot"),
|
||||
photonPlan.exposedPivot,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uPivotOutput"),
|
||||
photonPlan.pivotOutput,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uEndpointOutput"),
|
||||
photonPlan.endpointOutput,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uLowSlope"),
|
||||
photonPlan.lowSlope,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uLowCurveLift"),
|
||||
photonPlan.lowCurveLift,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uShoulderParameter"),
|
||||
photonPlan.shoulderParameter,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uMinTableGain"),
|
||||
photonPlan.minTableGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(curveProgram, "uMaxTableGain"),
|
||||
photonPlan.maxTableGain,
|
||||
)
|
||||
}
|
||||
}
|
||||
val diagnosticMode = when (plan.diagnosticBand?.mode) {
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
|
||||
null -> -1
|
||||
}
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticMode"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticMode"),
|
||||
diagnosticMode,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticStart"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticStart"),
|
||||
plan.diagnosticBand?.start ?: 0f,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticEnd"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticEnd"),
|
||||
plan.diagnosticBand?.end ?: 1f,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticFeather"),
|
||||
GLES31.glGetUniformLocation(curveProgram, "uDiagnosticFeather"),
|
||||
plan.diagnosticBand?.feather ?: 0f,
|
||||
)
|
||||
val curveGpuStartNs = System.nanoTime()
|
||||
@@ -2382,10 +2466,18 @@ class RawDemosaicProcessor {
|
||||
) ?: return null
|
||||
val curvesGpuReadyNs = System.nanoTime()
|
||||
val map = DngHdrProfileGainTableGenerator.mapFromGpuGains(plan, gains) ?: return null
|
||||
val photonSummary = plan.photonPlan?.let { photonPlan ->
|
||||
" photonBaselineGain=${photonPlan.exposureGain} " +
|
||||
"photonPivotSource=${photonPlan.sourcePivot} " +
|
||||
"photonFixedGray=${photonPlan.usesFixedGray} " +
|
||||
"photonGamma=${plan.gamma} " +
|
||||
"photonEndpoint=${photonPlan.endpointOutput} "
|
||||
}.orEmpty()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU RAW PGTM prepared: mode=$profileToneMapMode size=${width}x$height " +
|
||||
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
|
||||
photonSummary +
|
||||
"statsGpuMs=${(statsGpuReadyNs - statsGpuStartNs) / 1_000_000.0} " +
|
||||
"planCpuMs=${(planReadyNs - statsGpuReadyNs) / 1_000_000.0} " +
|
||||
"curvesGpuMs=${(curvesGpuReadyNs - curveGpuStartNs) / 1_000_000.0} " +
|
||||
@@ -2858,7 +2950,8 @@ class RawDemosaicProcessor {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Shader programs created: passthrough=$passthroughProgram " +
|
||||
"pgtmStats=$pgtmCellStatsProgram pgtmCurves=$pgtmGainCurvesProgram"
|
||||
"pgtmStats=$pgtmCellStatsProgram googlePgtmCurves=$pgtmGoogleGainCurvesProgram " +
|
||||
"photonPgtmCurves=$pgtmPhotonGainCurvesProgram"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3402,12 +3495,14 @@ class RawDemosaicProcessor {
|
||||
DngHdrProfileGainTableGpuShaders.CELL_STATS,
|
||||
"DNG_PGTM_CELL_STATS",
|
||||
)
|
||||
pgtmGainCurvesProgram = compileComputeProgram(
|
||||
DngHdrProfileGainTableGpuShaders.GAIN_CURVES,
|
||||
"DNG_PGTM_GAIN_CURVES",
|
||||
pgtmGoogleGainCurvesProgram = compileComputeProgram(
|
||||
DngHdrProfileGainTableGpuShaders.GOOGLE_GAIN_CURVES,
|
||||
"DNG_GOOGLE_PGTM_GAIN_CURVES",
|
||||
)
|
||||
pgtmPhotonGainCurvesProgram = compileComputeProgram(
|
||||
DngHdrProfileGainTableGpuShaders.PHOTON_GAIN_CURVES,
|
||||
"DNG_PHOTON_PGTM_GAIN_CURVES",
|
||||
)
|
||||
if (pgtmCellStatsProgram != 0 && pgtmGainCurvesProgram != 0) {
|
||||
}
|
||||
|
||||
val fShaderLinearRcd = compileShader(
|
||||
GLES30.GL_FRAGMENT_SHADER,
|
||||
@@ -7646,7 +7741,10 @@ class RawDemosaicProcessor {
|
||||
workingColorSpace = basePlan?.workingColorSpace ?: workingColorSpace,
|
||||
baselineExposureOffset = basePlan?.baselineExposureOffset ?: 0f,
|
||||
defaultBlackRender = basePlan?.defaultBlackRender ?: DcpDefaultBlackRender.None,
|
||||
supportsOverrange = basePlan?.supportsOverrange ?: false,
|
||||
// Photon endpoint normalization may require a value above 1 before a negative
|
||||
// BaselineExposure gain. Preserve it until exposure and the tone curve are applied.
|
||||
supportsOverrange = mode == RawProfileToneMapMode.Photon ||
|
||||
basePlan?.supportsOverrange == true,
|
||||
colorCorrectionMatrix = basePlan?.colorCorrectionMatrix ?: metadata.colorCorrectionMatrix,
|
||||
cameraWhite = basePlan?.cameraWhite ?: metadata.cameraWhite,
|
||||
hueSatMap = basePlan?.hueSatMap,
|
||||
@@ -8167,8 +8265,9 @@ class RawDemosaicProcessor {
|
||||
val previewHeight = previewSize.height
|
||||
return try {
|
||||
setupLinearExposurePreviewFramebuffer(previewWidth, previewHeight)
|
||||
val useAdobeSdkExposure =
|
||||
colorEngine == RawRenderingEngine.AdobeCurve && useProfileExposureRamp
|
||||
val useAdobeSdkExposure = colorEngine == RawRenderingEngine.AdobeCurve &&
|
||||
useProfileExposureRamp &&
|
||||
!applyLinearDngBaselineExposure
|
||||
val profileBaselineExposureOffsetEv = if (applyProfileDcpBaselineExposureOffset) {
|
||||
dcpBaselineExposureOffsetOrZero(dcpRenderPlan)
|
||||
} else {
|
||||
@@ -8835,7 +8934,12 @@ class RawDemosaicProcessor {
|
||||
if (quadRefineProgram != 0) GLES31.glDeleteProgram(quadRefineProgram)
|
||||
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
|
||||
if (pgtmCellStatsProgram != 0) GLES31.glDeleteProgram(pgtmCellStatsProgram)
|
||||
if (pgtmGainCurvesProgram != 0) GLES31.glDeleteProgram(pgtmGainCurvesProgram)
|
||||
if (pgtmGoogleGainCurvesProgram != 0) {
|
||||
GLES31.glDeleteProgram(pgtmGoogleGainCurvesProgram)
|
||||
}
|
||||
if (pgtmPhotonGainCurvesProgram != 0) {
|
||||
GLES31.glDeleteProgram(pgtmPhotonGainCurvesProgram)
|
||||
}
|
||||
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
|
||||
if (warpRectilinearProgram != 0) GLES31.glDeleteProgram(warpRectilinearProgram)
|
||||
if (linearRawRgbProgram != 0) GLES31.glDeleteProgram(linearRawRgbProgram)
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
|
||||
/** Float CPU mirror of the production PGTM curve shader. */
|
||||
/** Float CPU mirror of the production PGTM curve shaders. */
|
||||
internal object DngHdrProfileGainTableCpuReference {
|
||||
fun generate(plan: HdrProfileGainTablePlan): FloatArray {
|
||||
val result = FloatArray(plan.cellPlans.size * plan.pointCount)
|
||||
val curveParameters = plan.curveParameters
|
||||
plan.cellPlans.forEachIndexed { cell, cellPlan ->
|
||||
val ratio = cellPlan.blackGain / max(cellPlan.endpointGain, 1e-6f)
|
||||
fun generate(plan: HdrProfileGainTablePlan): FloatArray = when (plan.curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> generateGoogle(plan, requireNotNull(plan.googlePlan))
|
||||
HdrPgtmCurveModel.PHOTON -> generatePhoton(plan, requireNotNull(plan.photonPlan))
|
||||
}
|
||||
|
||||
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 ->
|
||||
@@ -20,34 +30,150 @@ internal object DngHdrProfileGainTableCpuReference {
|
||||
).coerceIn(0f, 1f)
|
||||
val denominator = max(
|
||||
1f + shoulderAmount * shoulderInput.pow(cellPlan.shapePower),
|
||||
1e-6f,
|
||||
CURVE_EPS,
|
||||
).pow(1f / curveParameters.shapeQ)
|
||||
val trueGain = if (point == plan.pointCount - 1) {
|
||||
plan.inputScale
|
||||
googlePlan.inputScale
|
||||
} else {
|
||||
(cellPlan.blackGain / denominator).coerceIn(
|
||||
curveParameters.minTableGain,
|
||||
curveParameters.maxTableGain,
|
||||
)
|
||||
}
|
||||
val finalGain = plan.diagnosticBand?.let { band ->
|
||||
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, tableInput * mixed)
|
||||
previousFinalOutput = output
|
||||
if (tableInput <= 1e-6f) mixed else output / tableInput
|
||||
} ?: trueGain
|
||||
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 generatePhoton(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
photonPlan: PhotonPgtmPlan,
|
||||
): FloatArray {
|
||||
val result = FloatArray(photonPlan.cellPlans.size * plan.pointCount)
|
||||
photonPlan.cellPlans.forEachIndexed { cell, cellPlan ->
|
||||
var previousFinalOutput = 0f
|
||||
repeat(plan.pointCount) { point ->
|
||||
val tableInput = tableInput(point, plan.pointCount)
|
||||
val sourceInput = max(tableInput, 0f).pow(1f / plan.gamma)
|
||||
val exposedInput = photonPlan.exposureGain * sourceInput
|
||||
val warpedInput = localContrastWarp(
|
||||
exposedInput = exposedInput,
|
||||
contrastExponent = cellPlan.contrastExponent,
|
||||
photonPlan = photonPlan,
|
||||
)
|
||||
val output = globalCurve(warpedInput, photonPlan)
|
||||
val trueGain = if (exposedInput <= CURVE_EPS) {
|
||||
photonPlan.lowSlope.coerceIn(
|
||||
photonPlan.minTableGain,
|
||||
photonPlan.maxTableGain,
|
||||
)
|
||||
} else {
|
||||
(output / exposedInput).coerceIn(
|
||||
photonPlan.minTableGain,
|
||||
photonPlan.maxTableGain,
|
||||
)
|
||||
}
|
||||
val finalGain = applyDiagnostic(
|
||||
trueGain = trueGain,
|
||||
tableInput = tableInput,
|
||||
physicalInput = exposedInput,
|
||||
previousFinalOutput = previousFinalOutput,
|
||||
plan = plan,
|
||||
minGain = photonPlan.minTableGain,
|
||||
maxGain = photonPlan.maxTableGain,
|
||||
)
|
||||
if (plan.diagnosticBand != null) {
|
||||
previousFinalOutput = max(previousFinalOutput, exposedInput * finalGain)
|
||||
}
|
||||
result[cell * plan.pointCount + point] = finalGain
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun localContrastWarp(
|
||||
exposedInput: Float,
|
||||
contrastExponent: Float,
|
||||
photonPlan: PhotonPgtmPlan,
|
||||
): Float {
|
||||
val pivot = photonPlan.exposedPivot
|
||||
val endpoint = max(photonPlan.exposureGain, pivot + CURVE_EPS)
|
||||
return if (exposedInput <= pivot) {
|
||||
val normalized = (exposedInput / max(pivot, CURVE_EPS)).coerceIn(0f, 1f)
|
||||
pivot * normalized.pow(contrastExponent)
|
||||
} else {
|
||||
val normalized = (
|
||||
(endpoint - exposedInput) / max(endpoint - pivot, CURVE_EPS)
|
||||
).coerceIn(0f, 1f)
|
||||
endpoint - (endpoint - pivot) * normalized.pow(contrastExponent)
|
||||
}
|
||||
}
|
||||
|
||||
private fun globalCurve(
|
||||
input: Float,
|
||||
plan: PhotonPgtmPlan,
|
||||
): Float {
|
||||
if (input <= plan.exposedPivot) {
|
||||
val x = (input / max(plan.exposedPivot, CURVE_EPS)).coerceIn(0f, 1f)
|
||||
val oneMinusX = 1f - x
|
||||
val lifted = x + plan.lowCurveLift * x * x * oneMinusX * oneMinusX
|
||||
return plan.pivotOutput * lifted
|
||||
}
|
||||
val span = max(plan.exposureGain - plan.exposedPivot, CURVE_EPS)
|
||||
val r = ((input - plan.exposedPivot) / span).coerceIn(0f, 1f)
|
||||
val parameter = plan.shoulderParameter
|
||||
val shaped = when {
|
||||
parameter > 1e-4f -> (
|
||||
ln(1.0 + parameter * r) / ln(1.0 + parameter)
|
||||
).toFloat()
|
||||
parameter < -1e-4f -> {
|
||||
val convexA = -parameter
|
||||
((exp((convexA * r).toDouble()) - 1.0) /
|
||||
(exp(convexA.toDouble()) - 1.0)).toFloat()
|
||||
}
|
||||
else -> r
|
||||
}
|
||||
return plan.pivotOutput + (plan.endpointOutput - plan.pivotOutput) * shaped
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
@@ -69,10 +195,12 @@ internal object DngHdrProfileGainTableCpuReference {
|
||||
}
|
||||
|
||||
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val t = ((value - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f)
|
||||
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
|
||||
}
|
||||
@@ -59,9 +59,10 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
fixtures().forEach { fixture ->
|
||||
val plan = plan(fixture)
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val curveParameters = plan.curveParameters
|
||||
plan.cellPlans.forEachIndexed { cell, cellPlan ->
|
||||
assertEquals(plan.inputScale, cellPlan.endpointGain, 0f)
|
||||
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
|
||||
@@ -82,7 +83,7 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
)
|
||||
assertTrue(
|
||||
"${fixture.sourceName} output overflow=$output",
|
||||
output <= max(1f, plan.inputScale) + 2e-6f,
|
||||
output <= max(1f, googlePlan.inputScale) + 2e-6f,
|
||||
)
|
||||
if (tableInput <= curveParameters.toeEnd) {
|
||||
assertEquals(cellPlan.blackGain, gain, 2e-6f)
|
||||
@@ -90,7 +91,7 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
previousOutput = output
|
||||
}
|
||||
assertEquals(
|
||||
plan.inputScale,
|
||||
googlePlan.inputScale,
|
||||
gains[cell * plan.pointCount + plan.pointCount - 1],
|
||||
1e-6f,
|
||||
)
|
||||
@@ -104,13 +105,13 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
val plans = fixtures.map(::plan)
|
||||
assertTrue(
|
||||
fixtures.zip(plans).any { (fixture, plan) ->
|
||||
plan.inputScale * DngBaselineExposure.exactGain(
|
||||
requireNotNull(plan.googlePlan).inputScale * DngBaselineExposure.exactGain(
|
||||
fixture.baselineExposureEv
|
||||
) > 1.25f
|
||||
}
|
||||
)
|
||||
assertTrue(plans.maxOf { it.inputScale } > 0.95f)
|
||||
assertTrue(plans.minOf { it.inputScale } < 0.45f)
|
||||
assertTrue(plans.maxOf { requireNotNull(it.googlePlan).inputScale } > 0.95f)
|
||||
assertTrue(plans.minOf { requireNotNull(it.googlePlan).inputScale } < 0.45f)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,8 +120,8 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
val quieter = plan(fixture, noiseOffset = fixture.noiseOffset * 0.25f)
|
||||
val noisier = plan(fixture, noiseOffset = fixture.noiseOffset * 4f)
|
||||
assertTrue(
|
||||
median(noisier.cellPlans.map { it.blackGain }) <
|
||||
median(quieter.cellPlans.map { it.blackGain })
|
||||
median(requireNotNull(noisier.googlePlan).cellPlans.map { it.blackGain }) <
|
||||
median(requireNotNull(quieter.googlePlan).cellPlans.map { it.blackGain })
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ internal fun DngHdrProfileGainTableGenerator.generateForCellStats(
|
||||
noiseSlope: Float,
|
||||
noiseOffset: Float,
|
||||
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand? = null,
|
||||
curveModel: HdrPgtmCurveModel = HdrPgtmCurveModel.GOOGLE,
|
||||
): DngProfileGainTableMap? {
|
||||
val plan = planForCellStats(
|
||||
width = width,
|
||||
@@ -17,6 +18,7 @@ internal fun DngHdrProfileGainTableGenerator.generateForCellStats(
|
||||
noiseSlope = noiseSlope,
|
||||
noiseOffset = noiseOffset,
|
||||
diagnosticBand = diagnosticBand,
|
||||
curveModel = curveModel,
|
||||
) ?: return null
|
||||
return mapFromGpuGains(plan, DngHdrProfileGainTableCpuReference.generate(plan))
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class DngPhotonProfileGainTableGeneratorTest {
|
||||
@Test
|
||||
fun fixedGrayReachesOnePointOneEvAfterPhotonToneCurve() {
|
||||
listOf(-2f, 0f, 3f, 7f).forEach { baselineExposureEv ->
|
||||
val plan = photonPlan(baselineExposureEv)
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
assertTrue("EV=$baselineExposureEv", photonPlan.usesFixedGray)
|
||||
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val sourceGray = REFERENCE_GRAY / photonPlan.exposureGain
|
||||
val tableGray = sourceGray.pow(plan.gamma)
|
||||
val gain = sampleCurve(gains, plan.pointCount, tableGray)
|
||||
val preToneGray = REFERENCE_GRAY * gain
|
||||
val finalGray = sampleLut(
|
||||
DngProfileToneCurve.photonPgtmToneCurveLut(),
|
||||
preToneGray,
|
||||
)
|
||||
val expected = REFERENCE_GRAY * 2f.pow(1.1f)
|
||||
assertEquals("EV=$baselineExposureEv", expected, finalGray, 1.5e-3f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun globalLowSegmentUsesSmoothEndpointPreservingLift() {
|
||||
listOf(-2f, 0f, 3f, 7f).forEach { baselineExposureEv ->
|
||||
val photonPlan = requireNotNull(photonPlan(baselineExposureEv).photonPlan)
|
||||
assertEquals("EV=$baselineExposureEv", 1.5f, photonPlan.lowCurveLift, 0f)
|
||||
assertEquals(
|
||||
"EV=$baselineExposureEv",
|
||||
photonPlan.pivotOutput / photonPlan.exposedPivot,
|
||||
photonPlan.lowSlope,
|
||||
1e-6f,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun smoothLowLiftRaisesInteriorWithoutMovingGray() {
|
||||
val plan = photonPlan(3f)
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val cellPlan = photonPlan.cellPlans.first()
|
||||
val exposedInput = photonPlan.exposedPivot * 0.5f
|
||||
val warpedNormalized = 0.5f.pow(cellPlan.contrastExponent)
|
||||
val oneMinus = 1f - warpedNormalized
|
||||
val linearOutput = photonPlan.pivotOutput * warpedNormalized
|
||||
val expectedOutput = photonPlan.pivotOutput * (
|
||||
warpedNormalized +
|
||||
photonPlan.lowCurveLift * warpedNormalized * warpedNormalized *
|
||||
oneMinus * oneMinus
|
||||
)
|
||||
val actualOutput = samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = 0,
|
||||
exposedInput = exposedInput,
|
||||
)
|
||||
|
||||
assertTrue("lifted=$actualOutput linear=$linearOutput", actualOutput > linearOutput)
|
||||
assertEquals(expectedOutput, actualOutput, 2e-3f)
|
||||
assertEquals(
|
||||
photonPlan.pivotOutput,
|
||||
samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = 0,
|
||||
exposedInput = photonPlan.exposedPivot,
|
||||
),
|
||||
2e-3f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mapWeightsCancelPositiveAndNegativeBaselineExposure() {
|
||||
listOf(-4f, -2f, 0f, 3f, 7f).forEach { baselineExposureEv ->
|
||||
val plan = photonPlan(baselineExposureEv)
|
||||
val exposureGain = requireNotNull(plan.photonPlan).exposureGain
|
||||
plan.mapInputWeights.forEachIndexed { index, weight ->
|
||||
assertEquals(
|
||||
"EV=$baselineExposureEv weight=$index",
|
||||
DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHTS[index],
|
||||
weight * exposureGain,
|
||||
2e-6f,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun endpointUsesAdaptiveOneToOnePointThreeNormalization() {
|
||||
val sparse = photonPlan(
|
||||
baselineExposureEv = 3f,
|
||||
stats = Stats(p98 = 0.42f, p999 = 0.98f, highlightFraction = 0.005f),
|
||||
)
|
||||
val broad = photonPlan(
|
||||
baselineExposureEv = 3f,
|
||||
stats = Stats(p98 = 0.82f, p999 = 0.98f, highlightFraction = 0.45f),
|
||||
)
|
||||
val sparsePhoton = requireNotNull(sparse.photonPlan)
|
||||
val broadPhoton = requireNotNull(broad.photonPlan)
|
||||
assertTrue(sparsePhoton.endpointOutput in 1f..1.3f)
|
||||
assertTrue(broadPhoton.endpointOutput in 1f..1.3f)
|
||||
assertTrue(sparsePhoton.endpointOutput > broadPhoton.endpointOutput)
|
||||
|
||||
listOf(sparse, broad).forEach { plan ->
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val expectedEndpointGain = photonPlan.endpointOutput / photonPlan.exposureGain
|
||||
repeat(plan.cellCount) { cell ->
|
||||
assertEquals(
|
||||
expectedEndpointGain,
|
||||
gains[cell * plan.pointCount + plan.pointCount - 1],
|
||||
2e-5f,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unreachableGrayFallsBackWithoutBreakingNegativeBaselineCurve() {
|
||||
val reachable = photonPlan(-2f)
|
||||
val unreachable = photonPlan(-3f)
|
||||
assertTrue(requireNotNull(reachable.photonPlan).usesFixedGray)
|
||||
assertFalse(requireNotNull(unreachable.photonPlan).usesFixedGray)
|
||||
|
||||
listOf(-4f, -3f, -2f, 0f, 3f, 7f).forEach { baselineExposureEv ->
|
||||
val plan = photonPlan(baselineExposureEv)
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val map = requireNotNull(
|
||||
DngHdrProfileGainTableGenerator.mapFromGpuGains(plan, gains)
|
||||
)
|
||||
assertTrue("EV=$baselineExposureEv map invalid", map.isValid)
|
||||
assertTrue("EV=$baselineExposureEv gamma=${plan.gamma}", plan.gamma in 0.125f..8f)
|
||||
var previousOutput = 0f
|
||||
repeat(plan.pointCount) { point ->
|
||||
val tableInput = tableInput(point, plan.pointCount)
|
||||
val sourceInput = max(tableInput, 0f).pow(1f / plan.gamma)
|
||||
val exposedInput = photonPlan.exposureGain * sourceInput
|
||||
val gain = gains[point]
|
||||
val output = exposedInput * gain
|
||||
assertTrue("EV=$baselineExposureEv point=$point gain=$gain", gain.isFinite() && gain > 0f)
|
||||
assertTrue(
|
||||
"EV=$baselineExposureEv reversal at point=$point",
|
||||
output + 2e-5f >= previousOutput,
|
||||
)
|
||||
previousOutput = output
|
||||
}
|
||||
assertEquals(photonPlan.endpointOutput, previousOutput, 2e-5f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun localPlansUseBoundedSContrast() {
|
||||
val plan = photonPlan(3f)
|
||||
val cellPlans = requireNotNull(plan.photonPlan).cellPlans
|
||||
assertTrue(cellPlans.all { it.contrastExponent in 1f..1.18f })
|
||||
assertTrue(cellPlans.any { it.contrastExponent > 1.01f })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun saturatedLocalParametersRemainInsideClosedFloatBounds() {
|
||||
val maximumContrast = photonPlan(
|
||||
baselineExposureEv = 3f,
|
||||
stats = Stats(
|
||||
p10 = 0.18f,
|
||||
p50 = 0.19f,
|
||||
p90 = 0.20f,
|
||||
p98 = 0.22f,
|
||||
p999 = 0.30f,
|
||||
highlightFraction = 0f,
|
||||
),
|
||||
)
|
||||
val cellPlans = requireNotNull(maximumContrast.photonPlan).cellPlans
|
||||
assertTrue(cellPlans.all { it.contrastExponent in 1f..1.18f })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun logarithmicShoulderKeepsMultipleHdrStopsBelowWhite() {
|
||||
val plan = photonPlan(
|
||||
baselineExposureEv = 3f,
|
||||
stats = Stats(highlightFraction = 0.005f),
|
||||
)
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val atOne = samplePhysicalOutput(plan, gains, cell = 0, exposedInput = 1f)
|
||||
val atTwo = samplePhysicalOutput(plan, gains, cell = 0, exposedInput = 2f)
|
||||
val atFour = samplePhysicalOutput(plan, gains, cell = 0, exposedInput = 4f)
|
||||
assertTrue("one-stop output=$atOne", atOne < 1f)
|
||||
assertTrue("1..2 stop separation=${atTwo - atOne}", atTwo - atOne > 0.10f)
|
||||
assertTrue("2..4 stop separation=${atFour - atTwo}", atFour - atTwo > 0.10f)
|
||||
}
|
||||
|
||||
private fun photonPlan(
|
||||
baselineExposureEv: Float,
|
||||
stats: Stats = Stats(),
|
||||
): HdrProfileGainTablePlan {
|
||||
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(WIDTH, HEIGHT)
|
||||
val cellCount = grid[0] * grid[1]
|
||||
val packed = FloatArray(
|
||||
cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
)
|
||||
repeat(cellCount) { cell ->
|
||||
val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
packed[offset] = stats.p10
|
||||
packed[offset + 1] = stats.p50
|
||||
packed[offset + 2] = stats.p90
|
||||
packed[offset + 3] = stats.p98
|
||||
packed[offset + 4] = stats.highlightFraction
|
||||
packed[offset + 5] = 256f
|
||||
packed[offset + 6] = max(stats.p98, stats.p999 * 0.96f)
|
||||
packed[offset + 7] = stats.p999
|
||||
}
|
||||
return requireNotNull(
|
||||
DngHdrProfileGainTableGenerator.planForCellStats(
|
||||
width = WIDTH,
|
||||
height = HEIGHT,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packed,
|
||||
noiseSlope = 1e-4f,
|
||||
noiseOffset = 4.5e-7f,
|
||||
curveModel = HdrPgtmCurveModel.PHOTON,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private fun sampleCurve(gains: FloatArray, pointCount: Int, input: Float): Float {
|
||||
return sampleCurve(gains, pointCount, cell = 0, input = input)
|
||||
}
|
||||
|
||||
private fun sampleCurve(
|
||||
gains: FloatArray,
|
||||
pointCount: Int,
|
||||
cell: Int,
|
||||
input: Float,
|
||||
): Float {
|
||||
val offset = cell * pointCount
|
||||
if (input >= 1f) return gains[offset + pointCount - 1]
|
||||
val scaled = input.coerceIn(0f, 1f) * pointCount
|
||||
val first = scaled.toInt().coerceIn(0, pointCount - 1)
|
||||
val second = (first + 1).coerceAtMost(pointCount - 1)
|
||||
val amount = scaled - first
|
||||
return gains[offset + first] * (1f - amount) + gains[offset + second] * amount
|
||||
}
|
||||
|
||||
private fun samplePhysicalOutput(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
gains: FloatArray,
|
||||
cell: Int,
|
||||
exposedInput: Float,
|
||||
): Float {
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
val sourceInput = exposedInput / photonPlan.exposureGain
|
||||
val tableInput = sourceInput.coerceIn(0f, 1f).pow(plan.gamma)
|
||||
return exposedInput * sampleCurve(gains, plan.pointCount, cell, tableInput)
|
||||
}
|
||||
|
||||
private fun sampleLut(lut: FloatArray, input: Float): Float {
|
||||
val scaled = input.coerceIn(0f, 1f) * (lut.size - 1f)
|
||||
val first = scaled.toInt().coerceIn(0, lut.lastIndex)
|
||||
val second = (first + 1).coerceAtMost(lut.lastIndex)
|
||||
val amount = scaled - first
|
||||
return lut[first] * (1f - amount) + lut[second] * amount
|
||||
}
|
||||
|
||||
private fun tableInput(point: Int, pointCount: Int): Float =
|
||||
if (point == pointCount - 1) 1f else point.toFloat() / pointCount.toFloat()
|
||||
|
||||
private data class Stats(
|
||||
val p10: Float = 0.025f,
|
||||
val p50: Float = 0.16f,
|
||||
val p90: Float = 0.52f,
|
||||
val p98: Float = 0.82f,
|
||||
val p999: Float = 0.98f,
|
||||
val highlightFraction: Float = 0.03f,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val WIDTH = 512
|
||||
const val HEIGHT = 384
|
||||
const val REFERENCE_GRAY = 0.18f
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user