feat: new photon pgtm
This commit is contained in:
1 parent
52d86fe1c7
commit
ea1bb6ce74
14 files changed
+3052
-1110
No files matched your search
@@ -179,8 +179,37 @@ internal data class HdrPgtmGrid(
|
||||
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,
|
||||
|
||||
@@ -69,6 +69,7 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
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)
|
||||
@@ -78,6 +79,15 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
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
|
||||
@@ -91,18 +101,6 @@ 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)
|
||||
@@ -311,8 +309,8 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
mapPointsH = plan.grid.mapPointsH,
|
||||
mapSpacingV = plan.grid.mapSpacingV,
|
||||
mapSpacingH = plan.grid.mapSpacingH,
|
||||
mapOriginV = 0.0,
|
||||
mapOriginH = 0.0,
|
||||
mapOriginV = plan.grid.mapOriginV,
|
||||
mapOriginH = plan.grid.mapOriginH,
|
||||
mapPointsN = plan.pointCount,
|
||||
mapInputWeights = plan.mapInputWeights,
|
||||
gamma = plan.gamma,
|
||||
|
||||
@@ -13,6 +13,7 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
precision highp sampler3D;
|
||||
|
||||
uniform highp usampler2D uRawTexture;
|
||||
uniform sampler2D uLensShadingMap;
|
||||
uniform sampler3D uHueSatMap;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
@@ -25,13 +26,27 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
uniform float uHighlightThreshold;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform int uLensShadingEnabled;
|
||||
uniform int uLensShadingUsesDngGrid;
|
||||
uniform vec2 uLensShadingMapSize;
|
||||
uniform vec4 uLensShadingGrid;
|
||||
uniform vec2 uLensShadingBoundsOrigin;
|
||||
uniform vec2 uLensShadingBoundsSize;
|
||||
uniform int uHueSatEnabled;
|
||||
uniform ivec3 uHueSatDivisions;
|
||||
uniform int uHueSatEncoding;
|
||||
uniform int uWriteCellSamples;
|
||||
uniform int uWarpCount;
|
||||
|
||||
layout(std430, binding = 0) writeonly buffer CellStatsBuffer {
|
||||
float cellStats[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer CellSampleBuffer {
|
||||
float cellSamples[];
|
||||
};
|
||||
layout(std430, binding = 2) readonly buffer WarpRectilinearBuffer {
|
||||
float warpParameters[];
|
||||
};
|
||||
|
||||
shared float inputSamples[256];
|
||||
|
||||
@@ -89,6 +104,28 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
return clamp((float(raw) - black) / range, 0.0, 1.0);
|
||||
}
|
||||
|
||||
int lensShadingChannelAt(int channelIndex, ivec2 coord) {
|
||||
if (uLensShadingUsesDngGrid != 0 || channelIndex == 0 || channelIndex == 3) {
|
||||
return channelIndex;
|
||||
}
|
||||
return (coord.y & 1) == 0 ? 1 : 2;
|
||||
}
|
||||
|
||||
float lensShadingGainAt(int channelIndex, ivec2 coord) {
|
||||
if (uLensShadingEnabled == 0) return 1.0;
|
||||
vec2 norm = (vec2(coord) + vec2(0.5)) / vec2(uImageSize);
|
||||
vec2 uv = norm;
|
||||
if (uLensShadingUsesDngGrid != 0) {
|
||||
vec2 boundsSize = max(uLensShadingBoundsSize, vec2(1.0));
|
||||
norm = (vec2(coord) + vec2(0.5) - uLensShadingBoundsOrigin) / boundsSize;
|
||||
vec2 mapIndex = (norm - uLensShadingGrid.xy) /
|
||||
max(uLensShadingGrid.zw, vec2(1e-8));
|
||||
uv = (mapIndex + vec2(0.5)) / max(uLensShadingMapSize, vec2(1.0));
|
||||
}
|
||||
vec4 gains = texture(uLensShadingMap, uv);
|
||||
return max(gains[lensShadingChannelAt(channelIndex, coord)], 0.0);
|
||||
}
|
||||
|
||||
float profileSceneInput(vec3 cameraRgb) {
|
||||
vec3 boundedCameraRgb = min(cameraRgb, uCameraWhite);
|
||||
vec3 profileRgb = clamp(uColorCorrectionMatrix * boundedCameraRgb, 0.0, 1.0);
|
||||
@@ -119,9 +156,9 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
ivec2 coord = clamp(baseCoord, ivec2(0), uImageSize - ivec2(1));
|
||||
uvec3 rawRgb = texelFetch(uRawTexture, coord, 0).rgb;
|
||||
return profileSceneInput(vec3(
|
||||
normalizeRaw(rawRgb.r, 0),
|
||||
normalizeRaw(rawRgb.g, 1),
|
||||
normalizeRaw(rawRgb.b, 2)
|
||||
normalizeRaw(rawRgb.r, 0) * lensShadingGainAt(0, coord),
|
||||
normalizeRaw(rawRgb.g, 1) * lensShadingGainAt(1, coord),
|
||||
normalizeRaw(rawRgb.b, 3) * lensShadingGainAt(3, coord)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -131,7 +168,9 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
for (int dx = 0; dx < 2; ++dx) {
|
||||
ivec2 coord = clamp(baseCoord + ivec2(dx, dy), ivec2(0), uImageSize - ivec2(1));
|
||||
int channel = channelIndexForPixel(coord);
|
||||
float value = normalizeRaw(texelFetch(uRawTexture, coord, 0).r, channel);
|
||||
float value =
|
||||
normalizeRaw(texelFetch(uRawTexture, coord, 0).r, channel) *
|
||||
lensShadingGainAt(channel, coord);
|
||||
if (channel == 0) {
|
||||
sums.r += value;
|
||||
counts.r += 1.0;
|
||||
@@ -153,6 +192,47 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
));
|
||||
}
|
||||
|
||||
vec2 warpDestinationToSource(vec2 destinationPixel) {
|
||||
vec2 sourcePixel = destinationPixel;
|
||||
// Rendering applies opcodes in file order. Sampling the original RAW from the final
|
||||
// output coordinate composes their destination-to-source mappings in reverse order.
|
||||
for (int warpIndex = uWarpCount - 1; warpIndex >= 0; --warpIndex) {
|
||||
int offset = warpIndex * 8;
|
||||
vec4 radial = vec4(
|
||||
warpParameters[offset],
|
||||
warpParameters[offset + 1],
|
||||
warpParameters[offset + 2],
|
||||
warpParameters[offset + 3]
|
||||
);
|
||||
vec2 tangential = vec2(
|
||||
warpParameters[offset + 4],
|
||||
warpParameters[offset + 5]
|
||||
);
|
||||
vec2 center = vec2(
|
||||
warpParameters[offset + 6],
|
||||
warpParameters[offset + 7]
|
||||
) * vec2(uImageSize);
|
||||
vec2 difference = sourcePixel - center;
|
||||
vec2 farthest = max(center, vec2(uImageSize) - center);
|
||||
float normalizationRadius = max(length(farthest), 1.0);
|
||||
vec2 normalized = difference / normalizationRadius;
|
||||
float radiusSquared = min(dot(normalized, normalized), 1.0);
|
||||
float ratio = radial.x + radial.y * radiusSquared +
|
||||
radial.z * radiusSquared * radiusSquared +
|
||||
radial.w * radiusSquared * radiusSquared * radiusSquared;
|
||||
float horizontal = normalized.x;
|
||||
float vertical = normalized.y;
|
||||
vec2 tangent = vec2(
|
||||
tangential.y * (radiusSquared + 2.0 * horizontal * horizontal) +
|
||||
2.0 * tangential.x * horizontal * vertical,
|
||||
tangential.x * (radiusSquared + 2.0 * vertical * vertical) +
|
||||
2.0 * tangential.y * horizontal * vertical
|
||||
);
|
||||
sourcePixel = center + normalizationRadius * (normalized * ratio + tangent);
|
||||
}
|
||||
return clamp(sourcePixel, vec2(0.0), vec2(uImageSize - ivec2(1)));
|
||||
}
|
||||
|
||||
void sortSamples(uint localIndex) {
|
||||
for (uint sequenceSize = 2u; sequenceSize <= 256u; sequenceSize <<= 1u) {
|
||||
for (uint compareDistance = sequenceSize >> 1u;
|
||||
@@ -202,9 +282,13 @@ internal object DngHdrProfileGainTableGpuShaders {
|
||||
int cellHeight = max(endY - startY, 2);
|
||||
int x = startX + ((localX * 2 + 1) * cellWidth) / 32;
|
||||
int y = startY + ((localY * 2 + 1) * cellHeight) / 32;
|
||||
x = clamp(x & ~1, startX, max(startX, endX - 2));
|
||||
y = clamp(y & ~1, startY, max(startY, endY - 2));
|
||||
inputValue = sampleSceneInput(ivec2(x, y));
|
||||
vec2 sourcePixel = warpDestinationToSource(vec2(x, y));
|
||||
ivec2 sourceCoord = ivec2(round(sourcePixel)) & ~ivec2(1);
|
||||
sourceCoord = clamp(sourceCoord, ivec2(0), uImageSize - ivec2(2));
|
||||
inputValue = sampleSceneInput(sourceCoord);
|
||||
}
|
||||
if (uWriteCellSamples != 0) {
|
||||
cellSamples[cellIndex * 256 + int(localIndex)] = inputValue;
|
||||
}
|
||||
inputSamples[localIndex] = inputValue;
|
||||
barrier();
|
||||
@@ -342,176 +426,4 @@ 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 highlightRecovery
|
||||
) {
|
||||
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(
|
||||
(exposedInput - uExposedPivot) /
|
||||
max(endpoint - uExposedPivot, CURVE_EPS),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float contrasted = 1.0 - pow(1.0 - normalized, contrastExponent);
|
||||
// Move the crowded shoulder midrange down while preserving both the gray pivot and
|
||||
// source-white endpoint. k < 1 keeps this quadratic warp strictly monotonic and its
|
||||
// finite endpoint slope avoids amplifying clipped/noisy samples.
|
||||
float recovered = contrasted -
|
||||
highlightRecovery * contrasted * (1.0 - contrasted);
|
||||
return uExposedPivot +
|
||||
(endpoint - uExposedPivot) * clamp(recovered, 0.0, 1.0);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
int planOffset = cellIndex * 2;
|
||||
float contrastExponent = clamp(curvePlans[planOffset], 1.0, 1.18);
|
||||
float highlightRecovery = clamp(curvePlans[planOffset + 1], 0.0, 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 sourceInput = pow(max(tableInput, 0.0), 1.0 / uMapGamma);
|
||||
float exposedInput = uExposureGain * sourceInput;
|
||||
float warpedInput = localContrastWarp(
|
||||
exposedInput,
|
||||
contrastExponent,
|
||||
highlightRecovery
|
||||
);
|
||||
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,843 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* GLES 3.1 compute passes for the Photon Local Laplacian + scalar Google BGU pipeline.
|
||||
*
|
||||
* The equations and boundary handling intentionally mirror [DngPhotonLocalToneMapper]. Each
|
||||
* pyramid level occupies a disjoint range in one SSBO so a pass can read one level and write the
|
||||
* next without allocating or copying full-resolution CPU arrays.
|
||||
*/
|
||||
internal object DngPhotonLocalToneMapGpuShaders {
|
||||
enum class Pass {
|
||||
PREPARE_SOURCE,
|
||||
NORMALIZE_LOG,
|
||||
CLEAR_UINT,
|
||||
DOWNSAMPLE,
|
||||
REMAP,
|
||||
ACCUMULATE_LAPLACIAN,
|
||||
COPY_RANGE,
|
||||
RECONSTRUCT,
|
||||
LOG_HISTOGRAM,
|
||||
FINALIZE_SDR_TARGET,
|
||||
BGU_HISTOGRAM,
|
||||
BGU_BLUR_Z,
|
||||
BGU_BLUR_Y,
|
||||
BGU_BLUR_X,
|
||||
BGU_SOLVE,
|
||||
GAIN_CURVES,
|
||||
}
|
||||
|
||||
const val HISTOGRAM_BIN_COUNT = 32_768
|
||||
const val BGU_FILTER_RADIUS = 3
|
||||
const val BGU_COMPONENT_COUNT = 5
|
||||
|
||||
val sources: Array<String> by lazy {
|
||||
arrayOf(
|
||||
prepareSource,
|
||||
normalizeLog,
|
||||
clearUint,
|
||||
downsample,
|
||||
remap,
|
||||
accumulateLaplacian,
|
||||
copyRange,
|
||||
reconstruct,
|
||||
logHistogram,
|
||||
finalizeSdrTarget,
|
||||
bguHistogram,
|
||||
bguBlurZ,
|
||||
bguBlurY,
|
||||
bguBlurX,
|
||||
bguSolve,
|
||||
gainCurves,
|
||||
).also { require(it.size == Pass.entries.size) }
|
||||
}
|
||||
|
||||
private val prepareSource = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer CellSamples {
|
||||
float cellSamples[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer LinearSource {
|
||||
float sourceValues[];
|
||||
};
|
||||
layout(std430, binding = 2) buffer SourceRange {
|
||||
uint sourceRange[];
|
||||
};
|
||||
uniform ivec2 uGridSize;
|
||||
uniform ivec2 uSampleSize;
|
||||
|
||||
void main() {
|
||||
ivec2 position = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(position, uSampleSize))) return;
|
||||
ivec2 cell = position >> 4;
|
||||
ivec2 localPosition = position & 15;
|
||||
int cellIndex = cell.y * uGridSize.x + cell.x;
|
||||
int localIndex = localPosition.y * 16 + localPosition.x;
|
||||
float value = max(cellSamples[cellIndex * 256 + localIndex], 0.0);
|
||||
sourceValues[position.y * uSampleSize.x + position.x] = value;
|
||||
// Source values are non-negative, so IEEE-754 bit order is numerical order.
|
||||
uint bits = floatBitsToUint(value);
|
||||
atomicMin(sourceRange[0], bits);
|
||||
atomicMax(sourceRange[1], bits);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val normalizeLog = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer LinearSource {
|
||||
float sourceValues[];
|
||||
};
|
||||
layout(std430, binding = 1) readonly buffer SourceRange {
|
||||
uint sourceRange[];
|
||||
};
|
||||
layout(std430, binding = 2) writeonly buffer GaussianPyramid {
|
||||
float gaussian[];
|
||||
};
|
||||
uniform ivec2 uSampleSize;
|
||||
uniform int uOutputOffset;
|
||||
uniform float uExposureGain;
|
||||
const float SOURCE_EPS = 1e-6;
|
||||
|
||||
void main() {
|
||||
ivec2 position = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(position, uSampleSize))) return;
|
||||
int index = position.y * uSampleSize.x + position.x;
|
||||
float minimumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[0]) + SOURCE_EPS
|
||||
);
|
||||
float maximumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[1]) + SOURCE_EPS
|
||||
);
|
||||
float logRange = maximumLog - minimumLog;
|
||||
float value = log(uExposureGain * sourceValues[index] + SOURCE_EPS);
|
||||
gaussian[uOutputOffset + index] = logRange > SOURCE_EPS
|
||||
? clamp((value - minimumLog) / logRange, 0.0, 1.0)
|
||||
: 1.0;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val clearUint = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) writeonly buffer Destination {
|
||||
uint values[];
|
||||
};
|
||||
uniform int uCount;
|
||||
uniform uint uValue;
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index < uCount) values[index] = uValue;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val downsample = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer SourceBuffer {
|
||||
float sourceValues[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer DestinationBuffer {
|
||||
float destinationValues[];
|
||||
};
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uDestinationSize;
|
||||
uniform int uSourceOffset;
|
||||
uniform int uDestinationOffset;
|
||||
|
||||
float filterWeight(int delta) {
|
||||
int distance = abs(delta);
|
||||
return distance == 0 ? 0.40 : (distance == 1 ? 0.25 : 0.05);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 outputPosition = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(outputPosition, uDestinationSize))) return;
|
||||
ivec2 center = outputPosition * 2;
|
||||
float sum = 0.0;
|
||||
float weightSum = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
int sourceY = center.y + dy;
|
||||
if (sourceY < 0 || sourceY >= uSourceSize.y) continue;
|
||||
float wy = filterWeight(dy);
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
int sourceX = center.x + dx;
|
||||
if (sourceX < 0 || sourceX >= uSourceSize.x) continue;
|
||||
float weight = wy * filterWeight(dx);
|
||||
sum += sourceValues[
|
||||
uSourceOffset + sourceY * uSourceSize.x + sourceX
|
||||
] * weight;
|
||||
weightSum += weight;
|
||||
}
|
||||
}
|
||||
int outputIndex =
|
||||
uDestinationOffset + outputPosition.y * uDestinationSize.x + outputPosition.x;
|
||||
destinationValues[outputIndex] = sum / max(weightSum, 1e-8);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val remap = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer GaussianPyramid {
|
||||
float gaussian[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer RemappedPyramid {
|
||||
float remapped[];
|
||||
};
|
||||
layout(std430, binding = 2) readonly buffer SourceRange {
|
||||
uint sourceRange[];
|
||||
};
|
||||
uniform int uCount;
|
||||
uniform int uSourceOffset;
|
||||
uniform int uDestinationOffset;
|
||||
uniform float uReference;
|
||||
uniform float uRangeSigma;
|
||||
uniform float uDetailExponent;
|
||||
uniform float uEdgeSlope;
|
||||
uniform float uExposureGain;
|
||||
const float SOURCE_EPS = 1e-6;
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uCount) return;
|
||||
float minimumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[0]) + SOURCE_EPS
|
||||
);
|
||||
float maximumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[1]) + SOURCE_EPS
|
||||
);
|
||||
float sigma = uRangeSigma / max(maximumLog - minimumLog, SOURCE_EPS);
|
||||
float delta = gaussian[uSourceOffset + index] - uReference;
|
||||
float magnitude = abs(delta);
|
||||
float direction = sign(delta);
|
||||
float remappedMagnitude = magnitude <= sigma
|
||||
? sigma * pow(magnitude / max(sigma, SOURCE_EPS), uDetailExponent)
|
||||
: sigma + uEdgeSlope * (magnitude - sigma);
|
||||
remapped[uDestinationOffset + index] = direction * remappedMagnitude;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val accumulateLaplacian = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer GuidePyramid {
|
||||
float guideValues[];
|
||||
};
|
||||
layout(std430, binding = 1) readonly buffer RemappedPyramid {
|
||||
float remappedValues[];
|
||||
};
|
||||
layout(std430, binding = 2) buffer OutputLaplacian {
|
||||
float outputValues[];
|
||||
};
|
||||
uniform ivec2 uCurrentSize;
|
||||
uniform ivec2 uNextSize;
|
||||
uniform int uGuideOffset;
|
||||
uniform int uCurrentOffset;
|
||||
uniform int uNextOffset;
|
||||
uniform int uOutputOffset;
|
||||
uniform float uReference;
|
||||
uniform float uIntensityStep;
|
||||
|
||||
float filterWeight(int delta) {
|
||||
int distance = abs(delta);
|
||||
return distance == 0 ? 0.40 : (distance == 1 ? 0.25 : 0.05);
|
||||
}
|
||||
|
||||
float expandedValue(ivec2 position) {
|
||||
float sum = 0.0;
|
||||
float weightSum = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
int insertedY = position.y + dy;
|
||||
if ((insertedY & 1) != 0) continue;
|
||||
int sourceY = insertedY / 2;
|
||||
if (sourceY < 0 || sourceY >= uNextSize.y) continue;
|
||||
float wy = filterWeight(dy);
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
int insertedX = position.x + dx;
|
||||
if ((insertedX & 1) != 0) continue;
|
||||
int sourceX = insertedX / 2;
|
||||
if (sourceX < 0 || sourceX >= uNextSize.x) continue;
|
||||
float weight = wy * filterWeight(dx);
|
||||
sum += remappedValues[
|
||||
uNextOffset + sourceY * uNextSize.x + sourceX
|
||||
] * weight;
|
||||
weightSum += weight;
|
||||
}
|
||||
}
|
||||
return sum / max(weightSum, 1e-8);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 position = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(position, uCurrentSize))) return;
|
||||
int index = position.y * uCurrentSize.x + position.x;
|
||||
float distance = abs(guideValues[uGuideOffset + index] - uReference);
|
||||
if (distance >= uIntensityStep) return;
|
||||
float interpolationWeight = 1.0 - distance / uIntensityStep;
|
||||
float laplacian = remappedValues[uCurrentOffset + index] -
|
||||
expandedValue(position);
|
||||
outputValues[uOutputOffset + index] += interpolationWeight * laplacian;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val copyRange = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer SourceBuffer {
|
||||
float sourceValues[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer DestinationBuffer {
|
||||
float destinationValues[];
|
||||
};
|
||||
uniform int uCount;
|
||||
uniform int uSourceOffset;
|
||||
uniform int uDestinationOffset;
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index < uCount) {
|
||||
destinationValues[uDestinationOffset + index] =
|
||||
sourceValues[uSourceOffset + index];
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val reconstruct = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer OutputLaplacian {
|
||||
float laplacianValues[];
|
||||
};
|
||||
layout(std430, binding = 1) buffer ReconstructedPyramid {
|
||||
float reconstructedValues[];
|
||||
};
|
||||
uniform ivec2 uCurrentSize;
|
||||
uniform ivec2 uNextSize;
|
||||
uniform int uLaplacianOffset;
|
||||
uniform int uCurrentOffset;
|
||||
uniform int uNextOffset;
|
||||
|
||||
float filterWeight(int delta) {
|
||||
int distance = abs(delta);
|
||||
return distance == 0 ? 0.40 : (distance == 1 ? 0.25 : 0.05);
|
||||
}
|
||||
|
||||
float expandedValue(ivec2 position) {
|
||||
float sum = 0.0;
|
||||
float weightSum = 0.0;
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
int insertedY = position.y + dy;
|
||||
if ((insertedY & 1) != 0) continue;
|
||||
int sourceY = insertedY / 2;
|
||||
if (sourceY < 0 || sourceY >= uNextSize.y) continue;
|
||||
float wy = filterWeight(dy);
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
int insertedX = position.x + dx;
|
||||
if ((insertedX & 1) != 0) continue;
|
||||
int sourceX = insertedX / 2;
|
||||
if (sourceX < 0 || sourceX >= uNextSize.x) continue;
|
||||
float weight = wy * filterWeight(dx);
|
||||
sum += reconstructedValues[
|
||||
uNextOffset + sourceY * uNextSize.x + sourceX
|
||||
] * weight;
|
||||
weightSum += weight;
|
||||
}
|
||||
}
|
||||
return sum / max(weightSum, 1e-8);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 position = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(position, uCurrentSize))) return;
|
||||
int index = position.y * uCurrentSize.x + position.x;
|
||||
reconstructedValues[uCurrentOffset + index] =
|
||||
expandedValue(position) + laplacianValues[uLaplacianOffset + index];
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val logHistogram = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer ReconstructedPyramid {
|
||||
float reconstructed[];
|
||||
};
|
||||
layout(std430, binding = 1) readonly buffer SourceRange {
|
||||
uint sourceRange[];
|
||||
};
|
||||
layout(std430, binding = 2) readonly buffer HistogramRange {
|
||||
uint histogramRange[];
|
||||
};
|
||||
layout(std430, binding = 3) buffer Histogram {
|
||||
uint histogram[];
|
||||
};
|
||||
uniform int uCount;
|
||||
uniform int uSourceOffset;
|
||||
uniform int uBinCount;
|
||||
uniform float uExposureGain;
|
||||
const float SOURCE_EPS = 1e-6;
|
||||
|
||||
float orderedFloatValue(uint ordered) {
|
||||
uint bits = (ordered & 0x80000000u) != 0u
|
||||
? (ordered ^ 0x80000000u)
|
||||
: ~ordered;
|
||||
return uintBitsToFloat(bits);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uCount) return;
|
||||
float minimumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[0]) + SOURCE_EPS
|
||||
);
|
||||
float maximumLog = log(
|
||||
uExposureGain * uintBitsToFloat(sourceRange[1]) + SOURCE_EPS
|
||||
);
|
||||
float filteredLog = minimumLog +
|
||||
reconstructed[uSourceOffset + index] * (maximumLog - minimumLog);
|
||||
float rangeMinimum = orderedFloatValue(histogramRange[0]);
|
||||
float rangeMaximum = orderedFloatValue(histogramRange[1]);
|
||||
float coordinate = (filteredLog - rangeMinimum) /
|
||||
max(rangeMaximum - rangeMinimum, SOURCE_EPS);
|
||||
int binIndex = int(floor(clamp(coordinate, 0.0, 1.0) * float(uBinCount - 1)));
|
||||
atomicAdd(histogram[binIndex], 1u);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val finalizeSdrTarget = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer ReconstructedPyramid {
|
||||
float reconstructed[];
|
||||
};
|
||||
layout(std430, binding = 1) readonly buffer SourceRange {
|
||||
uint sourceRange[];
|
||||
};
|
||||
layout(std430, binding = 2) writeonly buffer ToneMappedTarget {
|
||||
float target[];
|
||||
};
|
||||
uniform int uCount;
|
||||
uniform int uSourceOffset;
|
||||
uniform float uPreToneMapExposureGain;
|
||||
const float SOURCE_EPS = 1e-6;
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uCount) return;
|
||||
float minimumLog = log(
|
||||
uPreToneMapExposureGain * uintBitsToFloat(sourceRange[0]) + SOURCE_EPS
|
||||
);
|
||||
float maximumLog = log(
|
||||
uPreToneMapExposureGain * uintBitsToFloat(sourceRange[1]) + SOURCE_EPS
|
||||
);
|
||||
float filteredLog = minimumLog +
|
||||
reconstructed[uSourceOffset + index] * (maximumLog - minimumLog);
|
||||
// Local Laplacian operates on the already-exposed input. Its reconstructed
|
||||
// linear radiance is the definitive SDR target; no second global curve follows it.
|
||||
target[index] = clamp(exp(filteredLog) - SOURCE_EPS, 0.0, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val bguHistogram = """
|
||||
#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 LinearSource {
|
||||
float sourceValues[];
|
||||
};
|
||||
layout(std430, binding = 1) readonly buffer ToneMappedTarget {
|
||||
float targetValues[];
|
||||
};
|
||||
layout(std430, binding = 2) writeonly buffer BilateralHistogram {
|
||||
float histogram[];
|
||||
};
|
||||
uniform ivec2 uSampleSize;
|
||||
uniform ivec2 uExtendedGridSize;
|
||||
uniform int uRangeBinCount;
|
||||
uniform int uRangePlaneCount;
|
||||
uniform float uGuideAlpha;
|
||||
uniform float uBaselineExposureGain;
|
||||
|
||||
float curvedGuide(float value) {
|
||||
float x = clamp(value, 0.0, 1.0);
|
||||
return clamp(x / max((1.0 - uGuideAlpha) + uGuideAlpha * x, 1e-6), 0.0, 1.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int item = int(gl_LocalInvocationIndex);
|
||||
int itemCount = uRangePlaneCount * 5;
|
||||
if (item >= itemCount) return;
|
||||
ivec2 extendedCell = ivec2(gl_WorkGroupID.xy);
|
||||
int z = item / 5;
|
||||
int component = item - z * 5;
|
||||
ivec2 gridCell = extendedCell - ivec2(3);
|
||||
float sum = 0.0;
|
||||
for (int localY = 0; localY < 16; ++localY) {
|
||||
int sampleY = clamp(gridCell.y * 16 + localY, 0, uSampleSize.y - 1);
|
||||
for (int localX = 0; localX < 16; ++localX) {
|
||||
int sampleX = clamp(gridCell.x * 16 + localX, 0, uSampleSize.x - 1);
|
||||
int sampleIndex = sampleY * uSampleSize.x + sampleX;
|
||||
float sourceValue = clamp(sourceValues[sampleIndex], 0.0, 1.0);
|
||||
int sampleZ = clamp(
|
||||
int(round(curvedGuide(sourceValue) * float(uRangeBinCount))),
|
||||
0,
|
||||
uRangeBinCount
|
||||
);
|
||||
if (sampleZ != z) continue;
|
||||
// Fit the final Local Laplacian SDR target directly. The renderer applies
|
||||
// BaselineExposure after PGTM, so divide it out of the fit target here.
|
||||
float x = sourceValue;
|
||||
float y = max(
|
||||
targetValues[sampleIndex] / uBaselineExposureGain,
|
||||
0.0
|
||||
);
|
||||
if (component == 0) sum += x * x;
|
||||
else if (component == 1) sum += x;
|
||||
else if (component == 2) sum += 1.0;
|
||||
else if (component == 3) sum += y * x;
|
||||
else sum += y;
|
||||
}
|
||||
}
|
||||
int cellIndex = extendedCell.y * uExtendedGridSize.x + extendedCell.x;
|
||||
histogram[(cellIndex * uRangePlaneCount + z) * 5 + component] = sum;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val bguBlurZ = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer InputGrid {
|
||||
float inputValues[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer OutputGrid {
|
||||
float outputValues[];
|
||||
};
|
||||
uniform ivec2 uGridSize;
|
||||
uniform int uRangePlaneCount;
|
||||
uniform int uElementCount;
|
||||
|
||||
float blurWeight(int distance) {
|
||||
return distance == 0 ? 1.0 :
|
||||
(distance == 1 ? 0.125 :
|
||||
(distance == 2 ? (1.0 / 27.0) : (1.0 / 64.0)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uElementCount) return;
|
||||
int component = index % 5;
|
||||
int planeIndex = index / 5;
|
||||
int z = planeIndex % uRangePlaneCount;
|
||||
int cellIndex = planeIndex / uRangePlaneCount;
|
||||
float sum = 0.0;
|
||||
for (int delta = -3; delta <= 3; ++delta) {
|
||||
int sampleZ = z + delta;
|
||||
if (sampleZ < 0 || sampleZ >= uRangePlaneCount) continue;
|
||||
int sourceIndex =
|
||||
(cellIndex * uRangePlaneCount + sampleZ) * 5 + component;
|
||||
sum += inputValues[sourceIndex] * blurWeight(abs(delta));
|
||||
}
|
||||
outputValues[index] = sum;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val bguBlurY = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer InputGrid {
|
||||
float inputValues[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer OutputGrid {
|
||||
float outputValues[];
|
||||
};
|
||||
uniform ivec2 uExtendedGridSize;
|
||||
uniform int uOutputHeight;
|
||||
uniform int uRangePlaneCount;
|
||||
uniform int uElementCount;
|
||||
|
||||
float blurWeight(int distance) {
|
||||
return distance == 0 ? 1.0 :
|
||||
(distance == 1 ? 0.125 :
|
||||
(distance == 2 ? (1.0 / 27.0) : (1.0 / 64.0)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uElementCount) return;
|
||||
int component = index % 5;
|
||||
int planeIndex = index / 5;
|
||||
int z = planeIndex % uRangePlaneCount;
|
||||
int cellIndex = planeIndex / uRangePlaneCount;
|
||||
int x = cellIndex % uExtendedGridSize.x;
|
||||
int y = cellIndex / uExtendedGridSize.x;
|
||||
float sum = 0.0;
|
||||
for (int delta = -3; delta <= 3; ++delta) {
|
||||
int sourceY = y + 3 + delta;
|
||||
int sourceCell = sourceY * uExtendedGridSize.x + x;
|
||||
int sourceIndex =
|
||||
(sourceCell * uRangePlaneCount + z) * 5 + component;
|
||||
sum += inputValues[sourceIndex] * blurWeight(abs(delta));
|
||||
}
|
||||
outputValues[index] = sum;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val bguBlurX = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer InputGrid {
|
||||
float inputValues[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer OutputGrid {
|
||||
float outputValues[];
|
||||
};
|
||||
uniform ivec2 uOutputGridSize;
|
||||
uniform int uInputWidth;
|
||||
uniform int uRangePlaneCount;
|
||||
uniform int uElementCount;
|
||||
|
||||
float blurWeight(int distance) {
|
||||
return distance == 0 ? 1.0 :
|
||||
(distance == 1 ? 0.125 :
|
||||
(distance == 2 ? (1.0 / 27.0) : (1.0 / 64.0)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uElementCount) return;
|
||||
int component = index % 5;
|
||||
int planeIndex = index / 5;
|
||||
int z = planeIndex % uRangePlaneCount;
|
||||
int cellIndex = planeIndex / uRangePlaneCount;
|
||||
int x = cellIndex % uOutputGridSize.x;
|
||||
int y = cellIndex / uOutputGridSize.x;
|
||||
float sum = 0.0;
|
||||
for (int delta = -3; delta <= 3; ++delta) {
|
||||
int sourceX = x + 3 + delta;
|
||||
int sourceCell = y * uInputWidth + sourceX;
|
||||
int sourceIndex =
|
||||
(sourceCell * uRangePlaneCount + z) * 5 + component;
|
||||
sum += inputValues[sourceIndex] * blurWeight(abs(delta));
|
||||
}
|
||||
outputValues[index] = sum;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val bguSolve = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer BlurredGrid {
|
||||
float blurred[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer GainCoefficients {
|
||||
float coefficients[];
|
||||
};
|
||||
uniform int uCoefficientCount;
|
||||
uniform float uRegularization;
|
||||
uniform float uIdentitySlope;
|
||||
|
||||
void main() {
|
||||
int index = int(gl_GlobalInvocationID.x);
|
||||
if (index >= uCoefficientCount) return;
|
||||
int offset = index * 5;
|
||||
float sumXX = blurred[offset];
|
||||
float sumYX = blurred[offset + 3];
|
||||
// ProfileGainTableMap can only express y = gain * x. Fit that model
|
||||
// directly instead of fitting an affine intercept that would later
|
||||
// become the unstable term intercept / x.
|
||||
coefficients[index] =
|
||||
(sumYX + uRegularization * uIdentitySlope) /
|
||||
(sumXX + uRegularization);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val gainCurves = """
|
||||
#version 310 es
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer GainCoefficients {
|
||||
float coefficients[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer GainCurves {
|
||||
float gainCurves[];
|
||||
};
|
||||
uniform int uCellCount;
|
||||
uniform int uPointCount;
|
||||
uniform int uRangeBinCount;
|
||||
uniform int uRangePlaneCount;
|
||||
uniform float uGuideAlpha;
|
||||
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);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int outputIndex = int(gl_GlobalInvocationID.x);
|
||||
int outputCount = uCellCount * uPointCount;
|
||||
if (outputIndex >= outputCount) return;
|
||||
int cell = outputIndex / uPointCount;
|
||||
int point = outputIndex - cell * uPointCount;
|
||||
// Exact black has zero output in a multiplicative DNG map. Reusing the first positive
|
||||
// interval's gain keeps the curve continuous without inventing a nonzero intercept.
|
||||
int evaluatedPoint = point == 0 ? 1 : point;
|
||||
float sourceInput = evaluatedPoint == uPointCount - 1
|
||||
? 1.0
|
||||
: float(evaluatedPoint) / float(uPointCount);
|
||||
float guide = clamp(
|
||||
sourceInput /
|
||||
max((1.0 - uGuideAlpha) + uGuideAlpha * sourceInput, CURVE_EPS),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float rangeCoordinate = guide * float(uRangeBinCount);
|
||||
int first = clamp(int(floor(rangeCoordinate)), 0, uRangeBinCount);
|
||||
int second = first + 1;
|
||||
float amount = rangeCoordinate - float(first);
|
||||
int coefficientOffset = cell * uRangePlaneCount;
|
||||
float fittedGain = mix(
|
||||
coefficients[coefficientOffset + first],
|
||||
coefficients[coefficientOffset + second],
|
||||
amount
|
||||
);
|
||||
float trueGain = clamp(
|
||||
fittedGain,
|
||||
uMinTableGain,
|
||||
uMaxTableGain
|
||||
);
|
||||
float finalGain = trueGain;
|
||||
if (uDiagnosticMode >= 0) {
|
||||
float mask = diagnosticMask(sourceInput);
|
||||
finalGain = uDiagnosticMode == 0
|
||||
? mix(1.0, trueGain, mask)
|
||||
: mix(trueGain, 1.0, mask);
|
||||
}
|
||||
gainCurves[outputIndex] = clamp(
|
||||
finalGain,
|
||||
uMinTableGain,
|
||||
uMaxTableGain
|
||||
);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
}
|
||||
|
||||
internal data class PhotonGpuPyramidLevel(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val offset: Int,
|
||||
) {
|
||||
val size: Int
|
||||
get() = width * height
|
||||
}
|
||||
|
||||
internal data class PhotonGpuPyramidLayout(
|
||||
val levels: List<PhotonGpuPyramidLevel>,
|
||||
val floatCount: Int,
|
||||
) {
|
||||
companion object {
|
||||
fun create(width: Int, height: Int): PhotonGpuPyramidLayout {
|
||||
require(width > 0 && height > 0)
|
||||
val minimumDimension = min(width, height)
|
||||
val requested = ceil(ln(minimumDimension.toDouble()) - ln(2.0)).toInt() + 2
|
||||
var possible = 1
|
||||
var dimension = minimumDimension
|
||||
while (dimension > 1) {
|
||||
possible++
|
||||
dimension = (dimension + 1) / 2
|
||||
}
|
||||
val levelCount = requested.coerceIn(1, possible)
|
||||
val levels = ArrayList<PhotonGpuPyramidLevel>(levelCount)
|
||||
var levelWidth = width
|
||||
var levelHeight = height
|
||||
var offset = 0
|
||||
repeat(levelCount) {
|
||||
levels += PhotonGpuPyramidLevel(levelWidth, levelHeight, offset)
|
||||
offset += levelWidth * levelHeight
|
||||
levelWidth = (levelWidth + 1) / 2
|
||||
levelHeight = (levelHeight + 1) / 2
|
||||
}
|
||||
return PhotonGpuPyramidLayout(levels, offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/*
|
||||
* Local Laplacian portions are based on the MIT-licensed reference implementation:
|
||||
* Copyright (c) 2011 Sam Hasinoff.
|
||||
*
|
||||
* Halide and Google BGU portions are based on the MIT/Apache-2.0 reference implementations:
|
||||
* Copyright (c) 2012-2020 MIT CSAIL, Google, Facebook, Adobe, NVIDIA CORPORATION,
|
||||
* and other contributors; Copyright 2016 Google Inc.
|
||||
*
|
||||
* Full notices and the exact pinned-source comparison are in
|
||||
* docs/third-party/local-tone-mapping and docs/photon-local-tone-mapping.md.
|
||||
*/
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Photon local tone mapping for DNG ProfileGainTableMap.
|
||||
*
|
||||
* Algorithm lineage:
|
||||
* 1. Paris/Hasinoff/Kautz Local Laplacian HDR remapping in log luminance.
|
||||
* 2. Aubry et al. intensity-discretized Local Laplacian evaluation.
|
||||
* 3. Google's fit-and-slice affine bilateral grid (BGU).
|
||||
*
|
||||
* BGU's RGB 3x4 matrix is reduced to the multiplicative scalar model that DNG PGTM can represent.
|
||||
* The curved guide, histogram, 7-tap blur, fixed identity regularization, and range slicing follow
|
||||
* the pinned Google implementation plus the regularizer correction in current Halide BGU.
|
||||
*/
|
||||
internal object DngPhotonLocalToneMapper {
|
||||
private const val TAG = "DngPhotonLocalToneMapper"
|
||||
|
||||
const val SAMPLES_PER_CELL_SIDE = 16
|
||||
const val SAMPLES_PER_CELL = SAMPLES_PER_CELL_SIDE * SAMPLES_PER_CELL_SIDE
|
||||
|
||||
private const val PYRAMID_FILTER_RADIUS = 2
|
||||
private const val BILATERAL_FILTER_RADIUS = 3
|
||||
private const val BILATERAL_COMPONENTS = 5
|
||||
internal const val SOURCE_EPSILON = 1e-6f
|
||||
private const val CURVE_EPS = 1e-6f
|
||||
|
||||
// pyramid_filter.m: [.05, .25, .4, .25, .05].
|
||||
internal val localLaplacianPyramidFilter =
|
||||
floatArrayOf(0.05f, 0.25f, 0.40f, 0.25f, 0.05f)
|
||||
|
||||
// Google BGU: center=1, distance 1=1/8, distance 2=1/27, distance 3=1/64.
|
||||
internal val bilateralBlurWeights =
|
||||
floatArrayOf(1f, 1f / 8f, 1f / 27f, 1f / 64f)
|
||||
|
||||
fun generate(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
cellSamples: FloatArray,
|
||||
packedCellStats: FloatArray,
|
||||
): FloatArray? {
|
||||
if (plan.curveModel != HdrPgtmCurveModel.PHOTON) return null
|
||||
val photonPlan = plan.photonPlan ?: return null
|
||||
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
|
||||
}
|
||||
|
||||
val sampleWidth = plan.grid.mapPointsH * SAMPLES_PER_CELL_SIDE
|
||||
val sampleHeight = plan.grid.mapPointsV * SAMPLES_PER_CELL_SIDE
|
||||
val source = unpackCellMajorSamples(
|
||||
samples = cellSamples,
|
||||
gridWidth = plan.grid.mapPointsH,
|
||||
gridHeight = plan.grid.mapPointsV,
|
||||
)
|
||||
val preToneMapExposureGain = photonPlan.exposureGain *
|
||||
2.0f.pow(photonPlan.parameters.preToneMapExposureBoostEv)
|
||||
val localToneMap = localLaplacianToneMap(
|
||||
source = source,
|
||||
width = sampleWidth,
|
||||
height = sampleHeight,
|
||||
exposureGain = preToneMapExposureGain,
|
||||
parameters = photonPlan.parameters,
|
||||
)
|
||||
val targetBeforeBaselineExposure = FloatArray(source.size) { index ->
|
||||
localToneMap.target[index] / photonPlan.exposureGain
|
||||
}
|
||||
val gainGrid = fitScalarGainBilateralGrid(
|
||||
source = source,
|
||||
fitInput = source,
|
||||
target = targetBeforeBaselineExposure,
|
||||
width = sampleWidth,
|
||||
height = sampleHeight,
|
||||
gridWidth = plan.grid.mapPointsH,
|
||||
gridHeight = plan.grid.mapPointsV,
|
||||
identitySlope = 1f,
|
||||
parameters = photonPlan.parameters,
|
||||
)
|
||||
return buildGainCurves(
|
||||
plan = plan,
|
||||
photonPlan = photonPlan,
|
||||
gainGrid = gainGrid,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Fast general Local Laplacian evaluation from llf_general.m. [exposureGain] already contains
|
||||
* BaselineExposure and the fixed ACR3 +1.1 EV placement. The middle 99% determines only the
|
||||
* Local Laplacian large-edge slope; reconstructed linear radiance is the final SDR target.
|
||||
*/
|
||||
internal fun localLaplacianToneMap(
|
||||
source: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
exposureGain: Float,
|
||||
parameters: PhotonLocalToneMappingParameters,
|
||||
): PhotonLocalToneMapResult {
|
||||
require(width > 0 && height > 0 && source.size == width * height)
|
||||
require(source.all { it.isFinite() && it >= 0f })
|
||||
require(exposureGain.isFinite() && exposureGain > 0f)
|
||||
|
||||
val exposedInput = FloatArray(source.size)
|
||||
val logInput = FloatArray(source.size)
|
||||
var logMinimum = Float.POSITIVE_INFINITY
|
||||
var logMaximum = Float.NEGATIVE_INFINITY
|
||||
source.forEachIndexed { index, value ->
|
||||
// Retaining the epsilon through postprocessing gives RAW black a defined finite
|
||||
// intensity. MATLAB's HDR inputs are strictly positive, while normalized RAW can be 0.
|
||||
val exposedValue =
|
||||
exposureGain.toDouble() * value.toDouble() + SOURCE_EPSILON.toDouble()
|
||||
exposedInput[index] = exposedValue.toFloat()
|
||||
val logValue = ln(exposedValue).toFloat()
|
||||
logInput[index] = logValue
|
||||
logMinimum = min(logMinimum, logValue)
|
||||
logMaximum = max(logMaximum, logValue)
|
||||
}
|
||||
val sortedInput = exposedInput.copyOf().also { it.sort() }
|
||||
val inputLower = percentile(sortedInput, parameters.percentileClip)
|
||||
.coerceAtLeast(SOURCE_EPSILON)
|
||||
val inputUpper = percentile(sortedInput, 1f - parameters.percentileClip)
|
||||
.coerceAtLeast(inputLower)
|
||||
val targetLogDynamicRange = ln(parameters.targetDynamicRange.toDouble()).toFloat()
|
||||
val inputLogDynamicRange = ln(
|
||||
(inputUpper / inputLower).toDouble()
|
||||
).toFloat()
|
||||
val edgeSlope = if (!inputLogDynamicRange.isFinite() ||
|
||||
inputLogDynamicRange <= CURVE_EPS
|
||||
) {
|
||||
1f
|
||||
} else {
|
||||
min(1f, targetLogDynamicRange / inputLogDynamicRange)
|
||||
}
|
||||
val logRange = logMaximum - logMinimum
|
||||
if (!logRange.isFinite() || logRange <= CURVE_EPS) {
|
||||
return PhotonLocalToneMapResult(
|
||||
target = FloatArray(source.size) { index ->
|
||||
(exposedInput[index] - SOURCE_EPSILON).coerceIn(0f, 1f)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val normalized = FloatArray(logInput.size) { index ->
|
||||
((logInput[index] - logMinimum) / logRange).coerceIn(0f, 1f)
|
||||
}
|
||||
val levelCount = referencePyramidLevelCount(width, height)
|
||||
val inputGaussian = gaussianPyramid(normalized, width, height, levelCount)
|
||||
val outputLaplacian = Array(levelCount) { level ->
|
||||
FloatArray(inputGaussian[level].data.size)
|
||||
}
|
||||
outputLaplacian[levelCount - 1] = inputGaussian[levelCount - 1].data.copyOf()
|
||||
|
||||
val intensityLevels = parameters.localLaplacianIntensityLevels
|
||||
val intensityStep = 1f / (intensityLevels - 1)
|
||||
val normalizedSigma = parameters.localLaplacianRangeSigma / logRange
|
||||
repeat(intensityLevels) { referenceIndex ->
|
||||
val reference = referenceIndex * intensityStep
|
||||
val remapped = FloatArray(normalized.size) { index ->
|
||||
remapLocalLaplacianDelta(
|
||||
delta = normalized[index] - reference,
|
||||
sigma = normalizedSigma,
|
||||
detailExponent = parameters.localLaplacianDetailExponent,
|
||||
edgeSlope = edgeSlope,
|
||||
)
|
||||
}
|
||||
val remappedGaussian = gaussianPyramid(remapped, width, height, levelCount)
|
||||
for (level in 0 until levelCount - 1) {
|
||||
val current = remappedGaussian[level]
|
||||
val expanded = upsample(
|
||||
source = remappedGaussian[level + 1],
|
||||
targetWidth = current.width,
|
||||
targetHeight = current.height,
|
||||
)
|
||||
val guide = inputGaussian[level].data
|
||||
val output = outputLaplacian[level]
|
||||
for (index in output.indices) {
|
||||
val distance = abs(guide[index] - reference)
|
||||
if (distance < intensityStep) {
|
||||
val interpolationWeight = 1f - distance / intensityStep
|
||||
output[index] += interpolationWeight *
|
||||
(current.data[index] - expanded[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var reconstructed = Plane(
|
||||
width = inputGaussian.last().width,
|
||||
height = inputGaussian.last().height,
|
||||
data = outputLaplacian.last(),
|
||||
)
|
||||
for (level in levelCount - 2 downTo 0) {
|
||||
val guide = inputGaussian[level]
|
||||
val expanded = upsample(reconstructed, guide.width, guide.height)
|
||||
val laplacian = outputLaplacian[level]
|
||||
for (index in expanded.indices) expanded[index] += laplacian[index]
|
||||
reconstructed = Plane(guide.width, guide.height, expanded)
|
||||
}
|
||||
|
||||
return PhotonLocalToneMapResult(
|
||||
target = FloatArray(source.size) { index ->
|
||||
val filteredLog = logMinimum + reconstructed.data[index] * logRange
|
||||
(exp(filteredLog.toDouble()) - SOURCE_EPSILON).toFloat().also { value ->
|
||||
require(value.isFinite()) {
|
||||
"Local Laplacian produced invalid radiance at $index: $value"
|
||||
}
|
||||
}.coerceIn(0f, 1f)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* DNG-constrained scalar form of Google BGU. [source] is the guide and [fitInput]/[target] are
|
||||
* the source/SDR pairs being encoded. Each bilateral cell directly solves
|
||||
* `target = gain * fitInput`; no second tone-mapping curve is introduced after Local
|
||||
* Laplacian. ProfileGainTableMap has no additive term, so the affine BGU intercept is omitted
|
||||
* instead of later turning it into the unstable term `intercept / input`.
|
||||
*
|
||||
* Spatial grid coordinates are translated by half a bin so the interior histogram windows are
|
||||
* the non-overlapping GPU sample tiles. Translation does not alter the filter; the DNG map
|
||||
* origin carries the same half-bin offset.
|
||||
*/
|
||||
internal fun fitScalarGainBilateralGrid(
|
||||
source: FloatArray,
|
||||
fitInput: FloatArray = source,
|
||||
target: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
gridWidth: Int,
|
||||
gridHeight: Int,
|
||||
identitySlope: Float = 1f,
|
||||
parameters: PhotonLocalToneMappingParameters,
|
||||
): ScalarGainBilateralGrid {
|
||||
require(width > 0 && height > 0 && source.size == width * height)
|
||||
require(fitInput.size == source.size)
|
||||
require(target.size == source.size)
|
||||
require(gridWidth > 0 && gridHeight > 0)
|
||||
require(identitySlope.isFinite() && identitySlope > 0f)
|
||||
require(parameters.bilateralSpatialBinSize == SAMPLES_PER_CELL_SIDE)
|
||||
require(width == gridWidth * parameters.bilateralSpatialBinSize)
|
||||
require(height == gridHeight * parameters.bilateralSpatialBinSize)
|
||||
|
||||
val spatialRadius = BILATERAL_FILTER_RADIUS
|
||||
val extendedWidth = gridWidth + 2 * spatialRadius
|
||||
val extendedHeight = gridHeight + 2 * spatialRadius
|
||||
val rangeBinCount = (1f / parameters.bilateralRangeSigma).roundToInt()
|
||||
val rangePlaneCount = rangeBinCount + 2
|
||||
val histogram = FloatArray(
|
||||
extendedWidth * extendedHeight * rangePlaneCount * BILATERAL_COMPONENTS
|
||||
)
|
||||
for (extendedY in 0 until extendedHeight) {
|
||||
val gridY = extendedY - spatialRadius
|
||||
for (extendedX in 0 until extendedWidth) {
|
||||
val gridX = extendedX - spatialRadius
|
||||
for (localY in 0 until parameters.bilateralSpatialBinSize) {
|
||||
val sampleY = (
|
||||
gridY * parameters.bilateralSpatialBinSize + localY
|
||||
).coerceIn(0, height - 1)
|
||||
for (localX in 0 until parameters.bilateralSpatialBinSize) {
|
||||
val sampleX = (
|
||||
gridX * parameters.bilateralSpatialBinSize + localX
|
||||
).coerceIn(0, width - 1)
|
||||
val sampleIndex = sampleY * width + sampleX
|
||||
val sourceValue = source[sampleIndex].coerceIn(0f, 1f)
|
||||
val x = fitInput[sampleIndex].coerceAtLeast(0f)
|
||||
val y = target[sampleIndex].coerceAtLeast(0f)
|
||||
val guide = curvedBilateralGuide(
|
||||
value = sourceValue,
|
||||
alpha = parameters.bilateralGuideCurveAlpha,
|
||||
)
|
||||
val z = (guide * rangeBinCount).roundToInt()
|
||||
.coerceIn(0, rangeBinCount)
|
||||
val offset = bilateralIndex(
|
||||
x = extendedX,
|
||||
y = extendedY,
|
||||
z = z,
|
||||
component = 0,
|
||||
width = extendedWidth,
|
||||
rangePlanes = rangePlaneCount,
|
||||
)
|
||||
// Sufficient statistics for the constrained model y = gain * x.
|
||||
histogram[offset] += x * x
|
||||
histogram[offset + 1] += x
|
||||
histogram[offset + 2] += 1f
|
||||
histogram[offset + 3] += y * x
|
||||
histogram[offset + 4] += y
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val blurredZ = FloatArray(histogram.size)
|
||||
for (y in 0 until extendedHeight) {
|
||||
for (x in 0 until extendedWidth) {
|
||||
for (z in 0 until rangePlaneCount) {
|
||||
for (component in 0 until BILATERAL_COMPONENTS) {
|
||||
var sum = 0f
|
||||
for (delta in -BILATERAL_FILTER_RADIUS..BILATERAL_FILTER_RADIUS) {
|
||||
val sampleZ = z + delta
|
||||
if (sampleZ !in 0 until rangePlaneCount) continue
|
||||
sum += histogram[
|
||||
bilateralIndex(
|
||||
x,
|
||||
y,
|
||||
sampleZ,
|
||||
component,
|
||||
extendedWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] * bilateralBlurWeights[abs(delta)]
|
||||
}
|
||||
blurredZ[
|
||||
bilateralIndex(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
component,
|
||||
extendedWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] = sum
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val blurredY = FloatArray(
|
||||
extendedWidth * gridHeight * rangePlaneCount * BILATERAL_COMPONENTS
|
||||
)
|
||||
for (y in 0 until gridHeight) {
|
||||
for (x in 0 until extendedWidth) {
|
||||
for (z in 0 until rangePlaneCount) {
|
||||
for (component in 0 until BILATERAL_COMPONENTS) {
|
||||
var sum = 0f
|
||||
for (delta in -BILATERAL_FILTER_RADIUS..BILATERAL_FILTER_RADIUS) {
|
||||
sum += blurredZ[
|
||||
bilateralIndex(
|
||||
x,
|
||||
y + spatialRadius + delta,
|
||||
z,
|
||||
component,
|
||||
extendedWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] * bilateralBlurWeights[abs(delta)]
|
||||
}
|
||||
blurredY[
|
||||
bilateralIndex(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
component,
|
||||
extendedWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] = sum
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val blurred = FloatArray(
|
||||
gridWidth * gridHeight * rangePlaneCount * BILATERAL_COMPONENTS
|
||||
)
|
||||
for (y in 0 until gridHeight) {
|
||||
for (x in 0 until gridWidth) {
|
||||
for (z in 0 until rangePlaneCount) {
|
||||
for (component in 0 until BILATERAL_COMPONENTS) {
|
||||
var sum = 0f
|
||||
for (delta in -BILATERAL_FILTER_RADIUS..BILATERAL_FILTER_RADIUS) {
|
||||
sum += blurredY[
|
||||
bilateralIndex(
|
||||
x + spatialRadius + delta,
|
||||
y,
|
||||
z,
|
||||
component,
|
||||
extendedWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] * bilateralBlurWeights[abs(delta)]
|
||||
}
|
||||
blurred[
|
||||
bilateralIndex(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
component,
|
||||
gridWidth,
|
||||
rangePlaneCount,
|
||||
)
|
||||
] = sum
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val gains = FloatArray(gridWidth * gridHeight * rangePlaneCount)
|
||||
val lambda = parameters.bilateralRegularization
|
||||
for (y in 0 until gridHeight) {
|
||||
for (x in 0 until gridWidth) {
|
||||
for (z in 0 until rangePlaneCount) {
|
||||
val sourceOffset = bilateralIndex(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
component = 0,
|
||||
width = gridWidth,
|
||||
rangePlanes = rangePlaneCount,
|
||||
)
|
||||
val sumXX = blurred[sourceOffset]
|
||||
val sumYX = blurred[sourceOffset + 3]
|
||||
val coefficientOffset = (y * gridWidth + x) * rangePlaneCount + z
|
||||
val gain = (
|
||||
sumYX + lambda * identitySlope
|
||||
) / (
|
||||
sumXX + lambda
|
||||
)
|
||||
require(gain.isFinite() && gain >= 0f) {
|
||||
"Invalid scalar BGU gain at ($x,$y,$z): $gain"
|
||||
}
|
||||
gains[coefficientOffset] = gain
|
||||
}
|
||||
}
|
||||
}
|
||||
return ScalarGainBilateralGrid(
|
||||
width = gridWidth,
|
||||
height = gridHeight,
|
||||
rangeBinCount = rangeBinCount,
|
||||
rangePlaneCount = rangePlaneCount,
|
||||
guideCurveAlpha = parameters.bilateralGuideCurveAlpha,
|
||||
gains = gains,
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildGainCurves(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
photonPlan: PhotonPgtmPlan,
|
||||
gainGrid: ScalarGainBilateralGrid,
|
||||
): FloatArray {
|
||||
val result = FloatArray(plan.cellCount * plan.pointCount)
|
||||
repeat(plan.cellCount) { cell ->
|
||||
val outputOffset = cell * plan.pointCount
|
||||
for (point in 0 until plan.pointCount) {
|
||||
val evaluatedPoint = if (point == 0) 1 else point
|
||||
val sourceInput = tableInput(evaluatedPoint, plan.pointCount)
|
||||
val fittedGain = gainGrid.gain(cell, sourceInput).coerceIn(
|
||||
photonPlan.minTableGain,
|
||||
photonPlan.maxTableGain,
|
||||
)
|
||||
val diagnosticGain = applyDiagnostic(
|
||||
trueGain = fittedGain,
|
||||
tableInput = sourceInput,
|
||||
plan = plan,
|
||||
)
|
||||
result[outputOffset + point] = diagnosticGain.coerceIn(
|
||||
photonPlan.minTableGain,
|
||||
photonPlan.maxTableGain,
|
||||
)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun applyDiagnostic(
|
||||
trueGain: Float,
|
||||
tableInput: Float,
|
||||
plan: HdrProfileGainTablePlan,
|
||||
): Float {
|
||||
val band = plan.diagnosticBand ?: return trueGain
|
||||
val mask = diagnosticMask(tableInput, band)
|
||||
return when (band.mode) {
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
|
||||
lerp(1f, trueGain, mask)
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
|
||||
lerp(trueGain, 1f, mask)
|
||||
}
|
||||
}
|
||||
|
||||
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 min(enter, exit).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val amount = ((value - edge0) / max(edge1 - edge0, CURVE_EPS)).coerceIn(0f, 1f)
|
||||
return amount * amount * (3f - 2f * amount)
|
||||
}
|
||||
|
||||
private fun curvedBilateralGuide(value: Float, alpha: Float): Float {
|
||||
val clamped = value.coerceIn(0f, 1f)
|
||||
return (
|
||||
clamped / ((1f - alpha) + alpha * clamped).coerceAtLeast(CURVE_EPS)
|
||||
).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun unpackCellMajorSamples(
|
||||
samples: FloatArray,
|
||||
gridWidth: Int,
|
||||
gridHeight: Int,
|
||||
): FloatArray {
|
||||
val width = gridWidth * SAMPLES_PER_CELL_SIDE
|
||||
val output = FloatArray(width * gridHeight * SAMPLES_PER_CELL_SIDE)
|
||||
repeat(gridHeight) { cellY ->
|
||||
repeat(gridWidth) { cellX ->
|
||||
val cellOffset = (cellY * gridWidth + cellX) * SAMPLES_PER_CELL
|
||||
repeat(SAMPLES_PER_CELL_SIDE) { localY ->
|
||||
val outputOffset =
|
||||
(cellY * SAMPLES_PER_CELL_SIDE + localY) * width +
|
||||
cellX * SAMPLES_PER_CELL_SIDE
|
||||
samples.copyInto(
|
||||
destination = output,
|
||||
destinationOffset = outputOffset,
|
||||
startIndex = cellOffset + localY * SAMPLES_PER_CELL_SIDE,
|
||||
endIndex = cellOffset + (localY + 1) * SAMPLES_PER_CELL_SIDE,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun remapLocalLaplacianDelta(
|
||||
delta: Float,
|
||||
sigma: Float,
|
||||
detailExponent: Float,
|
||||
edgeSlope: Float,
|
||||
): Float {
|
||||
val magnitude = abs(delta)
|
||||
val direction = when {
|
||||
delta > 0f -> 1f
|
||||
delta < 0f -> -1f
|
||||
else -> 0f
|
||||
}
|
||||
val remappedMagnitude = if (magnitude <= sigma) {
|
||||
sigma * (magnitude / max(sigma, SOURCE_EPSILON)).toDouble()
|
||||
.pow(detailExponent.toDouble())
|
||||
.toFloat()
|
||||
} else {
|
||||
sigma + edgeSlope * (magnitude - sigma)
|
||||
}
|
||||
return direction * remappedMagnitude
|
||||
}
|
||||
|
||||
private fun referencePyramidLevelCount(width: Int, height: Int): Int {
|
||||
val minimumDimension = min(width, height).coerceAtLeast(1)
|
||||
// llf_general.m: ceil(log(min(height,width))-log(2))+2.
|
||||
val requested = ceil(
|
||||
ln(minimumDimension.toDouble()) - ln(2.0)
|
||||
).toInt() + 2
|
||||
var possible = 1
|
||||
var dimension = minimumDimension
|
||||
while (dimension > 1) {
|
||||
possible++
|
||||
dimension = (dimension + 1) / 2
|
||||
}
|
||||
return requested.coerceIn(1, possible)
|
||||
}
|
||||
|
||||
private fun gaussianPyramid(
|
||||
input: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
levelCount: Int,
|
||||
): Array<Plane> {
|
||||
val result = ArrayList<Plane>(levelCount)
|
||||
var current = Plane(width, height, input)
|
||||
result += current
|
||||
repeat(levelCount - 1) {
|
||||
current = downsample(current)
|
||||
result += current
|
||||
}
|
||||
return result.toTypedArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Separable five-tap filtering, valid-sample reweighting, and even-coordinate decimation from
|
||||
* the published MATLAB downsample.m.
|
||||
*/
|
||||
private fun downsample(source: Plane): Plane {
|
||||
val outputWidth = (source.width + 1) / 2
|
||||
val outputHeight = (source.height + 1) / 2
|
||||
val horizontal = FloatArray(outputWidth * source.height)
|
||||
for (y in 0 until source.height) {
|
||||
for (outputX in 0 until outputWidth) {
|
||||
val centerX = outputX * 2
|
||||
var sum = 0f
|
||||
var weightSum = 0f
|
||||
for (delta in -PYRAMID_FILTER_RADIUS..PYRAMID_FILTER_RADIUS) {
|
||||
val sourceX = centerX + delta
|
||||
if (sourceX !in 0 until source.width) continue
|
||||
val weight = localLaplacianPyramidFilter[delta + PYRAMID_FILTER_RADIUS]
|
||||
sum += source.data[y * source.width + sourceX] * weight
|
||||
weightSum += weight
|
||||
}
|
||||
horizontal[y * outputWidth + outputX] = sum / weightSum
|
||||
}
|
||||
}
|
||||
val output = FloatArray(outputWidth * outputHeight)
|
||||
for (outputY in 0 until outputHeight) {
|
||||
val centerY = outputY * 2
|
||||
for (x in 0 until outputWidth) {
|
||||
var sum = 0f
|
||||
var weightSum = 0f
|
||||
for (delta in -PYRAMID_FILTER_RADIUS..PYRAMID_FILTER_RADIUS) {
|
||||
val sourceY = centerY + delta
|
||||
if (sourceY !in 0 until source.height) continue
|
||||
val weight = localLaplacianPyramidFilter[delta + PYRAMID_FILTER_RADIUS]
|
||||
sum += horizontal[sourceY * outputWidth + x] * weight
|
||||
weightSum += weight
|
||||
}
|
||||
output[outputY * outputWidth + x] = sum / weightSum
|
||||
}
|
||||
}
|
||||
return Plane(outputWidth, outputHeight, output)
|
||||
}
|
||||
|
||||
/**
|
||||
* Zero insertion, five-tap filtering, and valid-inserted-sample reweighting from upsample.m.
|
||||
*/
|
||||
private fun upsample(
|
||||
source: Plane,
|
||||
targetWidth: Int,
|
||||
targetHeight: Int,
|
||||
): FloatArray {
|
||||
val horizontal = FloatArray(targetWidth * source.height)
|
||||
for (y in 0 until source.height) {
|
||||
for (targetX in 0 until targetWidth) {
|
||||
var sum = 0f
|
||||
var weightSum = 0f
|
||||
for (delta in -PYRAMID_FILTER_RADIUS..PYRAMID_FILTER_RADIUS) {
|
||||
val insertedX = targetX + delta
|
||||
if ((insertedX and 1) != 0) continue
|
||||
val sourceX = insertedX / 2
|
||||
if (sourceX !in 0 until source.width) continue
|
||||
val weight = localLaplacianPyramidFilter[delta + PYRAMID_FILTER_RADIUS]
|
||||
sum += source.data[y * source.width + sourceX] * weight
|
||||
weightSum += weight
|
||||
}
|
||||
horizontal[y * targetWidth + targetX] = sum / weightSum
|
||||
}
|
||||
}
|
||||
val output = FloatArray(targetWidth * targetHeight)
|
||||
for (targetY in 0 until targetHeight) {
|
||||
for (x in 0 until targetWidth) {
|
||||
var sum = 0f
|
||||
var weightSum = 0f
|
||||
for (delta in -PYRAMID_FILTER_RADIUS..PYRAMID_FILTER_RADIUS) {
|
||||
val insertedY = targetY + delta
|
||||
if ((insertedY and 1) != 0) continue
|
||||
val sourceY = insertedY / 2
|
||||
if (sourceY !in 0 until source.height) continue
|
||||
val weight = localLaplacianPyramidFilter[delta + PYRAMID_FILTER_RADIUS]
|
||||
sum += horizontal[sourceY * targetWidth + x] * weight
|
||||
weightSum += weight
|
||||
}
|
||||
output[targetY * targetWidth + x] = sum / weightSum
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun percentile(sorted: FloatArray, quantile: Float): Float {
|
||||
if (sorted.size == 1) return sorted[0]
|
||||
val position = quantile.coerceIn(0f, 1f) * (sorted.size - 1)
|
||||
val lower = floor(position).toInt()
|
||||
val upper = min(lower + 1, sorted.lastIndex)
|
||||
return lerp(sorted[lower], sorted[upper], position - lower)
|
||||
}
|
||||
|
||||
private fun bilateralIndex(
|
||||
x: Int,
|
||||
y: Int,
|
||||
z: Int,
|
||||
component: Int,
|
||||
width: Int,
|
||||
rangePlanes: Int,
|
||||
): Int = (((y * width + x) * rangePlanes + z) * BILATERAL_COMPONENTS) + component
|
||||
|
||||
private fun tableInput(point: Int, count: Int): Float =
|
||||
if (point == count - 1) 1f else point.toFloat() / count.toFloat()
|
||||
|
||||
private fun lerp(start: Float, end: Float, amount: Float): Float =
|
||||
start + (end - start) * amount
|
||||
|
||||
private data class Plane(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val data: FloatArray,
|
||||
)
|
||||
}
|
||||
|
||||
internal data class PhotonLocalToneMapResult(
|
||||
val target: FloatArray,
|
||||
) {
|
||||
init {
|
||||
require(target.all { it.isFinite() && it in 0f..1f })
|
||||
}
|
||||
}
|
||||
|
||||
internal data class ScalarGainBilateralGrid(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val rangeBinCount: Int,
|
||||
val rangePlaneCount: Int,
|
||||
val guideCurveAlpha: Float,
|
||||
val gains: FloatArray,
|
||||
) {
|
||||
init {
|
||||
val expected = width * height * rangePlaneCount
|
||||
require(width > 0 && height > 0 && rangeBinCount > 0)
|
||||
require(rangePlaneCount == rangeBinCount + 2)
|
||||
require(guideCurveAlpha.isFinite() && guideCurveAlpha in 0f..1f)
|
||||
require(gains.size == expected)
|
||||
}
|
||||
|
||||
fun gain(cell: Int, source: Float): Float {
|
||||
require(cell in 0 until width * height)
|
||||
val linearSource = source.coerceIn(0f, 1f)
|
||||
val curvedGuide = (
|
||||
linearSource /
|
||||
((1f - guideCurveAlpha) + guideCurveAlpha * linearSource).coerceAtLeast(1e-6f)
|
||||
).coerceIn(0f, 1f)
|
||||
val rangeCoordinate = curvedGuide * rangeBinCount
|
||||
val first = floor(rangeCoordinate).toInt().coerceIn(0, rangeBinCount)
|
||||
val second = first + 1
|
||||
val amount = rangeCoordinate - first
|
||||
val offset = cell * rangePlaneCount
|
||||
return gains[offset + first] +
|
||||
(gains[offset + second] - gains[offset + first]) * amount
|
||||
}
|
||||
}
|
||||
@@ -1,330 +1,114 @@
|
||||
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. */
|
||||
/**
|
||||
* Plans Photon PGTM 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 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
|
||||
private const val MAX_LOCAL_HIGHLIGHT_RECOVERY = 0.42f
|
||||
private const val LOCAL_LEVEL_EPS = 0.006f
|
||||
private const val RECOVERY_EDGE_SIGMA_EV = 0.75f
|
||||
|
||||
// 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,
|
||||
samplingArea: HdrPgtmSamplingArea = HdrPgtmSamplingArea.FULL,
|
||||
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)
|
||||
// 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.
|
||||
val spacingH = samplingArea.extentH / grid.mapPointsH
|
||||
val spacingV = samplingArea.extentV / grid.mapPointsV
|
||||
val centeredGrid = grid.copy(
|
||||
mapSpacingH = spacingH,
|
||||
mapSpacingV = spacingV,
|
||||
mapOriginH = samplingArea.originH + 0.5 * spacingH,
|
||||
mapOriginV = samplingArea.originV + 0.5 * spacingV,
|
||||
)
|
||||
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.
|
||||
// DNG renderers include BaselineExposure before calculating the table coordinate.
|
||||
// Dividing the weights by that exact gain makes the BGU guide the sampled source-linear
|
||||
// scene input, while the gain itself still acts on the exposed signal.
|
||||
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,
|
||||
grid = centeredGrid,
|
||||
pointCount = pointCount,
|
||||
mapInputWeights = mapWeights,
|
||||
gamma = gamma,
|
||||
gamma = 1f,
|
||||
googlePlan = null,
|
||||
photonPlan = photonPlan,
|
||||
photonPlan = PhotonPgtmPlan(
|
||||
exposureGain = exposureGain,
|
||||
minTableGain = MIN_TABLE_GAIN,
|
||||
maxTableGain = MAX_TABLE_GAIN,
|
||||
parameters = PhotonLocalToneMappingParameters(),
|
||||
),
|
||||
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
|
||||
/**
|
||||
* 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.1 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.
|
||||
* 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 = 1.25f,
|
||||
// Google BGU production estimates.
|
||||
val bilateralSpatialBinSize: Int = 16,
|
||||
val bilateralRangeSigma: Float = 1f / 8f,
|
||||
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,
|
||||
) {
|
||||
init {
|
||||
require(localLaplacianRangeSigma.isFinite() && localLaplacianRangeSigma > 0f)
|
||||
require(localLaplacianDetailExponent.isFinite() && localLaplacianDetailExponent > 0f)
|
||||
require(localLaplacianIntensityLevels >= 2)
|
||||
require(percentileClip.isFinite() && percentileClip in 0f..<0.5f)
|
||||
require(targetDynamicRange.isFinite() && targetDynamicRange > 1f)
|
||||
require(preToneMapExposureBoostEv.isFinite())
|
||||
require(bilateralSpatialBinSize > 0)
|
||||
require(bilateralRangeSigma.isFinite() && bilateralRangeSigma > 0f)
|
||||
require(bilateralGuideCurveAlpha.isFinite() && bilateralGuideCurveAlpha in 0f..1f)
|
||||
require(bilateralRegularization.isFinite() && bilateralRegularization > 0f)
|
||||
}
|
||||
|
||||
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 cellLevelEv = FloatArray(cells.size) { index ->
|
||||
log2((cells[index] ?: global).p50 + LOCAL_LEVEL_EPS)
|
||||
}
|
||||
val rawContrast = 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)
|
||||
// Highlight-rich cells still need texture separation. Reducing this to 20% made
|
||||
// foliage and architecture behind a bright window collapse into one pale band.
|
||||
val highlightDetailGate = 1f - 0.35f * smoothStep(
|
||||
0.08f,
|
||||
0.55f,
|
||||
cell.highlightFraction,
|
||||
)
|
||||
((0.08f + 0.10f * lowContrastOpportunity) * snrGate * highlightDetailGate)
|
||||
.coerceIn(0f, MAX_LOCAL_CONTRAST)
|
||||
}
|
||||
val rawHighlightRecovery = 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 medianOffsetEv = log2(
|
||||
(cell.p50 + LOCAL_LEVEL_EPS) / (global.p50 + LOCAL_LEVEL_EPS)
|
||||
)
|
||||
val upperOffsetEv = log2(
|
||||
(cell.p90 + LOCAL_LEVEL_EPS) / (global.p90 + LOCAL_LEVEL_EPS)
|
||||
)
|
||||
val brightRegion = smoothStep(
|
||||
0.20f,
|
||||
1.25f,
|
||||
max(medianOffsetEv, 0.5f * upperOffsetEv),
|
||||
)
|
||||
val highlightOccupancy = smoothStep(0.08f, 0.65f, cell.highlightFraction)
|
||||
(MAX_LOCAL_HIGHLIGHT_RECOVERY * brightRegion * highlightOccupancy * snrGate)
|
||||
.coerceIn(0f, MAX_LOCAL_HIGHLIGHT_RECOVERY)
|
||||
}
|
||||
val smoothedContrast = smoothScalarField(rawContrast, grid)
|
||||
// Bilateral weighting prevents the recovery field from spilling across a strong window
|
||||
// boundary. The DNG renderer supplies the final continuous interpolation between cells.
|
||||
val smoothedHighlightRecovery = smoothScalarField(
|
||||
source = rawHighlightRecovery,
|
||||
grid = grid,
|
||||
guide = cellLevelEv,
|
||||
edgeSigma = RECOVERY_EDGE_SIGMA_EV,
|
||||
)
|
||||
return Array(cells.size) { index ->
|
||||
val contrastExponent = (
|
||||
1f + smoothedContrast[index].coerceIn(0f, MAX_LOCAL_CONTRAST)
|
||||
).coerceIn(1f, MAX_LOCAL_CONTRAST_EXPONENT)
|
||||
PhotonPgtmCellPlan(
|
||||
contrastExponent = contrastExponent,
|
||||
highlightRecovery = smoothedHighlightRecovery[index]
|
||||
.coerceIn(0f, MAX_LOCAL_HIGHLIGHT_RECOVERY),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun smoothScalarField(
|
||||
source: FloatArray,
|
||||
grid: HdrPgtmGrid,
|
||||
guide: FloatArray? = null,
|
||||
edgeSigma: Float = 1f,
|
||||
): 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
|
||||
}
|
||||
val neighbor = yy * grid.mapPointsH + xx
|
||||
val edgeWeight = if (guide == null) {
|
||||
1f
|
||||
} else {
|
||||
exp(
|
||||
(-kotlin.math.abs(guide[neighbor] - guide[index]) /
|
||||
edgeSigma.coerceAtLeast(SOURCE_EPS)).toDouble()
|
||||
).toFloat()
|
||||
}
|
||||
val combinedWeight = weight * edgeWeight
|
||||
weightedSum += source[neighbor] * combinedWeight
|
||||
weightSum += combinedWeight
|
||||
}
|
||||
}
|
||||
weightedSum / weightSum.coerceAtLeast(SOURCE_EPS)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>,
|
||||
val parameters: PhotonLocalToneMappingParameters,
|
||||
) {
|
||||
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 ||
|
||||
!cellPlan.highlightRecovery.isFinite() ||
|
||||
cellPlan.highlightRecovery !in 0f..0.42f
|
||||
}
|
||||
require(invalidCell < 0) {
|
||||
"Invalid Photon PGTM cell[$invalidCell]=${cellPlans.getOrNull(invalidCell)} " +
|
||||
"globalEndpoint=$endpointOutput"
|
||||
}
|
||||
require(minTableGain.isFinite() && minTableGain > 0f)
|
||||
require(maxTableGain.isFinite() && maxTableGain >= minTableGain)
|
||||
}
|
||||
}
|
||||
|
||||
internal data class PhotonPgtmCellPlan(
|
||||
val contrastExponent: Float,
|
||||
val highlightRecovery: Float,
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.util.Half
|
||||
import com.hinnka.mycamera.BuildConfig
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
@@ -134,6 +135,7 @@ data class DngProfileGainTableMap(
|
||||
* sent through DNG-only metadata readers.
|
||||
*/
|
||||
fun hasClassicTiffHeader(file: File): Boolean {
|
||||
if (BuildConfig.DEBUG) return false
|
||||
if (!file.exists() || file.length() < 8L) return false
|
||||
return runCatching {
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,5 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
|
||||
@@ -9,7 +7,8 @@ import kotlin.math.pow
|
||||
internal object DngHdrProfileGainTableCpuReference {
|
||||
fun generate(plan: HdrProfileGainTablePlan): FloatArray = when (plan.curveModel) {
|
||||
HdrPgtmCurveModel.GOOGLE -> generateGoogle(plan, requireNotNull(plan.googlePlan))
|
||||
HdrPgtmCurveModel.PHOTON -> generatePhoton(plan, requireNotNull(plan.photonPlan))
|
||||
HdrPgtmCurveModel.PHOTON ->
|
||||
error("Photon curves require the sampled image; use DngPhotonLocalToneMapper.generate")
|
||||
}
|
||||
|
||||
private fun generateGoogle(
|
||||
@@ -58,102 +57,6 @@ internal object DngHdrProfileGainTableCpuReference {
|
||||
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,
|
||||
highlightRecovery = cellPlan.highlightRecovery,
|
||||
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,
|
||||
highlightRecovery: 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 = (
|
||||
(exposedInput - pivot) / max(endpoint - pivot, CURVE_EPS)
|
||||
).coerceIn(0f, 1f)
|
||||
val contrasted = 1f - (1f - normalized).pow(contrastExponent)
|
||||
val recovered = contrasted -
|
||||
highlightRecovery * contrasted * (1f - contrasted)
|
||||
pivot + (endpoint - pivot) * recovered.coerceIn(0f, 1f)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
+98
-396
@@ -1,419 +1,121 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.ln
|
||||
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,
|
||||
fun parametersAndKernelsMatchPublishedReferences() {
|
||||
val parameters = PhotonLocalToneMappingParameters()
|
||||
assertEquals(ln(2.5).toFloat(), parameters.localLaplacianRangeSigma, 0f)
|
||||
assertEquals(1f, parameters.localLaplacianDetailExponent, 0f)
|
||||
assertEquals(20, parameters.localLaplacianIntensityLevels)
|
||||
assertEquals(0.005f, parameters.percentileClip, 0f)
|
||||
assertEquals(100f, parameters.targetDynamicRange, 0f)
|
||||
assertEquals(16, parameters.bilateralSpatialBinSize)
|
||||
assertEquals(1f / 8f, parameters.bilateralRangeSigma, 0f)
|
||||
assertEquals(0.8f, parameters.bilateralGuideCurveAlpha, 0f)
|
||||
assertEquals(0.1f, parameters.bilateralRegularization, 0f)
|
||||
assertFloatArrayEquals(
|
||||
floatArrayOf(0.05f, 0.25f, 0.4f, 0.25f, 0.05f),
|
||||
DngPhotonLocalToneMapper.localLaplacianPyramidFilter,
|
||||
0f,
|
||||
)
|
||||
assertFloatArrayEquals(
|
||||
floatArrayOf(1f, 1f / 8f, 1f / 27f, 1f / 64f),
|
||||
DngPhotonLocalToneMapper.bilateralBlurWeights,
|
||||
0f,
|
||||
)
|
||||
}
|
||||
|
||||
assertTrue("lifted=$actualOutput linear=$linearOutput", actualOutput > linearOutput)
|
||||
assertEquals(expectedOutput, actualOutput, 2e-3f)
|
||||
assertEquals(
|
||||
photonPlan.pivotOutput,
|
||||
samplePhysicalOutput(
|
||||
@Test
|
||||
fun dngCoordinatesUseSourceLinearGuideAtTileCenters() {
|
||||
val plan = plan(
|
||||
gridWidth = 4,
|
||||
gridHeight = 2,
|
||||
baselineExposureEv = 3f,
|
||||
samplingArea = HdrPgtmSamplingArea(
|
||||
originH = 0.25,
|
||||
originV = 0.125,
|
||||
extentH = 0.5,
|
||||
extentV = 0.75,
|
||||
),
|
||||
)
|
||||
val exposureGain = 8f
|
||||
assertEquals(1f, plan.gamma, 0f)
|
||||
assertEquals(0.125, plan.grid.mapSpacingH, 0.0)
|
||||
assertEquals(0.375, plan.grid.mapSpacingV, 0.0)
|
||||
assertEquals(0.3125, plan.grid.mapOriginH, 0.0)
|
||||
assertEquals(0.3125, plan.grid.mapOriginV, 0.0)
|
||||
DngHdrProfileGainTableGenerator.BASE_INPUT_WEIGHTS.forEachIndexed { index, weight ->
|
||||
assertEquals(weight / exposureGain, plan.mapInputWeights[index], 1e-7f)
|
||||
}
|
||||
val map = requireNotNull(
|
||||
DngHdrProfileGainTableGenerator.mapFromGpuGains(
|
||||
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 localPlansUseBoundedSContrastAndHighlightRecovery() {
|
||||
val plan = photonPlan(3f)
|
||||
val cellPlans = requireNotNull(plan.photonPlan).cellPlans
|
||||
assertTrue(cellPlans.all { it.contrastExponent in 1f..1.18f })
|
||||
assertTrue(cellPlans.all { it.highlightRecovery in 0f..0.42f })
|
||||
assertTrue(cellPlans.any { it.contrastExponent > 1.01f })
|
||||
assertTrue(cellPlans.all { it.highlightRecovery == 0f })
|
||||
}
|
||||
|
||||
@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 })
|
||||
assertTrue(cellPlans.all { it.highlightRecovery in 0f..0.42f })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun locallyBrightBroadHighlightsRecoverShoulderSeparationWithoutMovingAnchors() {
|
||||
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(WIDTH, HEIGHT)
|
||||
val brightStart = grid[0] / 2
|
||||
val plan = photonPlanByCell(baselineExposureEv = 3f) { cell ->
|
||||
val x = cell % grid[0]
|
||||
if (x >= brightStart) {
|
||||
Stats(
|
||||
p10 = 0.16f,
|
||||
p50 = 0.46f,
|
||||
p90 = 0.78f,
|
||||
p98 = 0.94f,
|
||||
p999 = 0.99f,
|
||||
highlightFraction = 0.82f,
|
||||
)
|
||||
} else {
|
||||
Stats(
|
||||
p10 = 0.015f,
|
||||
p50 = 0.07f,
|
||||
p90 = 0.18f,
|
||||
p98 = 0.28f,
|
||||
p999 = 0.42f,
|
||||
highlightFraction = 0.02f,
|
||||
)
|
||||
}
|
||||
}
|
||||
val photonPlan = requireNotNull(plan.photonPlan)
|
||||
val brightCell = brightStart + grid[0] * (grid[1] / 2)
|
||||
val cellPlan = photonPlan.cellPlans[brightCell]
|
||||
assertTrue("recovery=${cellPlan.highlightRecovery}", cellPlan.highlightRecovery > 0.10f)
|
||||
|
||||
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
|
||||
val withoutRecoveryPlan = plan.copy(
|
||||
photonPlan = photonPlan.copy(
|
||||
cellPlans = photonPlan.cellPlans.copyOf().also { cellPlans ->
|
||||
cellPlans[brightCell] = cellPlan.copy(highlightRecovery = 0f)
|
||||
}
|
||||
FloatArray(plan.cellCount * plan.pointCount) { 1f },
|
||||
)
|
||||
)
|
||||
val gainsWithoutRecovery = DngHdrProfileGainTableCpuReference.generate(
|
||||
withoutRecoveryPlan
|
||||
)
|
||||
val shoulderInput = 1.25f
|
||||
val recoveredOutput = samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = brightCell,
|
||||
exposedInput = shoulderInput,
|
||||
)
|
||||
val unrecoveredOutput = samplePhysicalOutput(
|
||||
withoutRecoveryPlan,
|
||||
gainsWithoutRecovery,
|
||||
cell = brightCell,
|
||||
exposedInput = shoulderInput,
|
||||
)
|
||||
assertTrue(
|
||||
"recovered=$recoveredOutput unrecovered=$unrecoveredOutput",
|
||||
recoveredOutput < unrecoveredOutput - 0.015f,
|
||||
)
|
||||
val recoveredSpan = samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = brightCell,
|
||||
exposedInput = 1.6f,
|
||||
) - samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = brightCell,
|
||||
exposedInput = 0.8f,
|
||||
)
|
||||
val unrecoveredSpan = samplePhysicalOutput(
|
||||
withoutRecoveryPlan,
|
||||
gainsWithoutRecovery,
|
||||
cell = brightCell,
|
||||
exposedInput = 1.6f,
|
||||
) - samplePhysicalOutput(
|
||||
withoutRecoveryPlan,
|
||||
gainsWithoutRecovery,
|
||||
cell = brightCell,
|
||||
exposedInput = 0.8f,
|
||||
)
|
||||
assertTrue(
|
||||
"recoveredSpan=$recoveredSpan unrecoveredSpan=$unrecoveredSpan",
|
||||
recoveredSpan >= 0.95f * unrecoveredSpan,
|
||||
)
|
||||
assertEquals(
|
||||
photonPlan.pivotOutput,
|
||||
samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = brightCell,
|
||||
exposedInput = photonPlan.exposedPivot,
|
||||
),
|
||||
2e-3f,
|
||||
)
|
||||
assertEquals(
|
||||
photonPlan.endpointOutput,
|
||||
samplePhysicalOutput(
|
||||
plan,
|
||||
gains,
|
||||
cell = brightCell,
|
||||
exposedInput = photonPlan.exposureGain,
|
||||
),
|
||||
2e-5f,
|
||||
)
|
||||
var previousOutput = 0f
|
||||
repeat(plan.pointCount) { point ->
|
||||
val tableInput = tableInput(point, plan.pointCount)
|
||||
val sourceInput = tableInput.pow(1f / plan.gamma)
|
||||
val exposedInput = photonPlan.exposureGain * sourceInput
|
||||
val output = exposedInput * gains[brightCell * plan.pointCount + point]
|
||||
assertTrue(
|
||||
"bright-cell reversal at point=$point output=$output previous=$previousOutput",
|
||||
output + 2e-5f >= previousOutput,
|
||||
)
|
||||
previousOutput = output
|
||||
}
|
||||
assertEquals(plan.grid.mapOriginH, map.mapOriginH, 0.0)
|
||||
assertEquals(plan.grid.mapOriginV, map.mapOriginV, 0.0)
|
||||
assertEquals(plan.grid.mapSpacingH, map.mapSpacingH, 0.0)
|
||||
assertEquals(plan.grid.mapSpacingV, map.mapSpacingV, 0.0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun logarithmicShoulderKeepsMultipleHdrStopsBelowWhite() {
|
||||
val plan = photonPlan(
|
||||
baselineExposureEv = 3f,
|
||||
stats = Stats(highlightFraction = 0.005f),
|
||||
fun scalarGainBilateralGridPreservesIdentityGain() {
|
||||
val gridWidth = 2
|
||||
val gridHeight = 2
|
||||
val width = gridWidth * DngPhotonLocalToneMapper.SAMPLES_PER_CELL_SIDE
|
||||
val height = gridHeight * DngPhotonLocalToneMapper.SAMPLES_PER_CELL_SIDE
|
||||
val source = FloatArray(width * height) { index ->
|
||||
val x = index % width
|
||||
(x + 0.5f) / width
|
||||
}
|
||||
val grid = DngPhotonLocalToneMapper.fitScalarGainBilateralGrid(
|
||||
source = source,
|
||||
target = source.copyOf(),
|
||||
width = width,
|
||||
height = height,
|
||||
gridWidth = gridWidth,
|
||||
gridHeight = gridHeight,
|
||||
parameters = PhotonLocalToneMappingParameters(),
|
||||
)
|
||||
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)
|
||||
repeat(gridWidth * gridHeight) { cell ->
|
||||
listOf(0f, 0.125f, 0.5f, 0.875f, 1f).forEach { guide ->
|
||||
val gain = grid.gain(cell, guide)
|
||||
assertEquals("cell=$cell guide=$guide", 1f, gain, 2e-4f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun photonPlan(
|
||||
private fun plan(
|
||||
gridWidth: Int,
|
||||
gridHeight: Int,
|
||||
baselineExposureEv: Float,
|
||||
stats: Stats = Stats(),
|
||||
): HdrProfileGainTablePlan = photonPlanByCell(baselineExposureEv) { stats }
|
||||
|
||||
private fun photonPlanByCell(
|
||||
baselineExposureEv: Float,
|
||||
statsForCell: (Int) -> 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 stats = statsForCell(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,
|
||||
samplingArea: HdrPgtmSamplingArea = HdrPgtmSamplingArea.FULL,
|
||||
): HdrProfileGainTablePlan = DngPhotonProfileGainTableGenerator.plan(
|
||||
grid = HdrPgtmGrid(
|
||||
mapPointsH = gridWidth,
|
||||
mapPointsV = gridHeight,
|
||||
mapSpacingH = if (gridWidth > 1) 1.0 / (gridWidth - 1) else 1.0,
|
||||
mapSpacingV = if (gridHeight > 1) 1.0 / (gridHeight - 1) else 1.0,
|
||||
),
|
||||
pointCount = 257,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
samplingArea = samplingArea,
|
||||
diagnosticBand = null,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val WIDTH = 512
|
||||
const val HEIGHT = 384
|
||||
const val REFERENCE_GRAY = 0.18f
|
||||
private fun assertFloatArrayEquals(
|
||||
expected: FloatArray,
|
||||
actual: FloatArray,
|
||||
tolerance: Float,
|
||||
) {
|
||||
assertEquals(expected.size, actual.size)
|
||||
expected.indices.forEach { index ->
|
||||
assertEquals("index=$index", expected[index], actual[index], tolerance)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user