feat: new google/photon pgtm

This commit is contained in:
Hinnka committed 2026-07-18 14:49:54 +08:00
1 parent 150bfe51f8
commit 7795b5b547
13 files changed
+1961 -1912

No files matched your search

@@ -11,8 +11,9 @@ data class GlesRawHdrInputFrame(
internal object GlesRawHdrConfig {
const val RGB_STRIPE_ROWS = 256
const val WEIGHT_SMOOTH_RADIUS = 2
const val WEIGHT_SMOOTH_HALO_ROWS = WEIGHT_SMOOTH_RADIUS
const val WEIGHT_SMOOTH_RADIUS = 3
const val WEIGHT_SMOOTH_PASSES = 2
const val WEIGHT_SMOOTH_HALO_ROWS = WEIGHT_SMOOTH_RADIUS * WEIGHT_SMOOTH_PASSES
const val SHORT_ALIGNMENT_SCORE_BUFFER_BINDING = 8
const val SHORT_ALIGNMENT_SCORE_STRIDE = 4
const val ALIGN_LEVEL = 2
@@ -142,8 +143,6 @@ internal object GlesRawHdrShaders {
uniform float uReferenceExposureScale;
uniform int uDebugOutputSource;
const float MIN_EFFECTIVE_FUSION_WEIGHT = 0.02;
bool finiteFloat(float value) {
return !isnan(value) && !isinf(value);
}
@@ -157,7 +156,7 @@ internal object GlesRawHdrShaders {
p = clamp(p, ivec2(0), size - ivec2(1));
vec2 weights = unpackHalf2x16(texelFetch(uWeightMap, p, 0).r);
if (!finiteFloat(weights.x) || !finiteFloat(weights.y)) {
return vec2(0.0);
return vec2(1.0, 0.0);
}
return clamp(weights, vec2(0.0), vec2(1.0));
}
@@ -208,19 +207,6 @@ internal object GlesRawHdrShaders {
);
}
bool shortRgbAvailableAtGlobal(vec2 globalPos) {
vec2 shortGlobal = globalPos + uShortRawOffset;
vec2 local = vec2(
shortGlobal.x,
shortGlobal.y - float(uShortSourceRowOffset)
);
ivec2 imageSize = textureSize(uWeightMap, 0);
return all(greaterThanEqual(shortGlobal, vec2(0.0))) &&
all(lessThanEqual(shortGlobal, vec2(imageSize - ivec2(1)))) &&
all(greaterThanEqual(local, vec2(0.0))) &&
all(lessThanEqual(local, vec2(uShortSourceSize - ivec2(1))));
}
vec3 referenceRgbAtGlobal(vec2 globalPos) {
vec2 local = vec2(globalPos.x, globalPos.y - float(uNormalSourceRowOffset));
return clamp(
@@ -246,24 +232,20 @@ internal object GlesRawHdrShaders {
vec3(1.0)
);
vec3 referenceRgb = referenceRgbAtGlobal(vec2(outputPos));
bool shortAvailable = shortRgbAvailableAtGlobal(vec2(outputPos));
vec3 shortRgb = shortAvailable ?
shortRgbAtGlobal(vec2(outputPos)) : vec3(0.0);
vec3 shortRgb = shortRgbAtGlobal(vec2(outputPos));
if (!finiteRgb(referenceRgb)) referenceRgb = accumulatedNormalRgb;
if (!finiteRgb(accumulatedNormalRgb)) accumulatedNormalRgb = referenceRgb;
vec2 frameWeights = fusionWeightsAt(outputPos);
if (!shortAvailable || !finiteRgb(shortRgb)) {
shortRgb = vec3(0.0);
if (!finiteRgb(shortRgb)) {
shortRgb = accumulatedNormalRgb;
frameWeights.y = 0.0;
}
float weightSum = frameWeights.x + frameWeights.y;
vec3 rgb = weightSum > MIN_EFFECTIVE_FUSION_WEIGHT ?
(
accumulatedNormalRgb * frameWeights.x +
shortRgb * frameWeights.y
) / weightSum :
referenceRgb;
if (!finiteRgb(rgb)) rgb = referenceRgb;
float weightSum = max(frameWeights.x + frameWeights.y, 1e-6);
vec3 rgb = (
accumulatedNormalRgb * frameWeights.x +
shortRgb * frameWeights.y
) / weightSum;
if (!finiteRgb(rgb)) rgb = accumulatedNormalRgb;
if (uDebugOutputSource == 1) {
rgb = accumulatedNormalRgb;
} else if (uDebugOutputSource == 2) {
@@ -540,23 +522,47 @@ internal class GlesRawHdrWeightMap(
GLES31.glDispatchCompute(groupCount(width), groupCount(inputs.weightRowCount), 1)
publishWeightTexture("calculate HDR RGB weights")
smooth(
sourceTexture = weightTextureA,
targetTexture = weightTextureB,
referenceRgbTexture = inputs.referenceRgbTexture,
referenceRawTexture = inputs.referenceRawTexture,
lensShadingTexture = inputs.lensShadingTexture,
referenceSourceWidth = inputs.referenceSourceWidth,
referenceSourceHeight = inputs.referenceSourceHeight,
referenceSourceRowOffset = inputs.referenceSourceRowOffset,
weightRowOffset = inputs.weightRowOffset,
weightRowCount = inputs.weightRowCount,
noiseFloorVariance = inputs.noiseFloorVariance,
lscNoiseGainMax = inputs.lscNoiseGainMax,
label = "smooth HDR weights 5x5 joint bilateral",
)
outputTexture = weightTextureB
return weightTextureB
var sourceTexture = weightTextureA
var targetTexture = weightTextureB
repeat(GlesRawHdrConfig.WEIGHT_SMOOTH_PASSES) { pass ->
smooth(
sourceTexture = sourceTexture,
targetTexture = targetTexture,
referenceRgbTexture = inputs.referenceRgbTexture,
referenceRawTexture = inputs.referenceRawTexture,
referenceSourceWidth = inputs.referenceSourceWidth,
referenceSourceHeight = inputs.referenceSourceHeight,
referenceSourceRowOffset = inputs.referenceSourceRowOffset,
weightRowOffset = inputs.weightRowOffset,
weightRowCount = inputs.weightRowCount,
directionX = 1,
directionY = 0,
label = "smooth HDR weights horizontal pass $pass",
)
val horizontalSource = sourceTexture
sourceTexture = targetTexture
targetTexture = horizontalSource
smooth(
sourceTexture = sourceTexture,
targetTexture = targetTexture,
referenceRgbTexture = inputs.referenceRgbTexture,
referenceRawTexture = inputs.referenceRawTexture,
referenceSourceWidth = inputs.referenceSourceWidth,
referenceSourceHeight = inputs.referenceSourceHeight,
referenceSourceRowOffset = inputs.referenceSourceRowOffset,
weightRowOffset = inputs.weightRowOffset,
weightRowCount = inputs.weightRowCount,
directionX = 0,
directionY = 1,
label = "smooth HDR weights vertical pass $pass",
)
val verticalSource = sourceTexture
sourceTexture = targetTexture
targetTexture = verticalSource
}
outputTexture = sourceTexture
return sourceTexture
}
private fun smooth(
@@ -564,21 +570,19 @@ internal class GlesRawHdrWeightMap(
targetTexture: Int,
referenceRgbTexture: Int,
referenceRawTexture: Int,
lensShadingTexture: Int,
referenceSourceWidth: Int,
referenceSourceHeight: Int,
referenceSourceRowOffset: Int,
weightRowOffset: Int,
weightRowCount: Int,
noiseFloorVariance: Float,
lscNoiseGainMax: Float,
directionX: Int,
directionY: Int,
label: String,
) {
GLES31.glUseProgram(smoothProgram)
backend.bindTexture(smoothProgram, "uSourceWeights", 0, sourceTexture)
backend.bindTexture(smoothProgram, "uReferenceRgb", 1, referenceRgbTexture)
backend.bindTexture(smoothProgram, "uReferenceRaw", 2, referenceRawTexture)
backend.bindTexture(smoothProgram, "uLensShadingMap", 3, lensShadingTexture)
backend.bindImage(0, targetTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI)
backend.setCommonUniforms(smoothProgram)
GLES31.glUniform2i(
@@ -603,13 +607,10 @@ internal class GlesRawHdrWeightMap(
backend.uniformLocation(smoothProgram, "uWeightRowCount"),
weightRowCount,
)
GLES31.glUniform1f(
backend.uniformLocation(smoothProgram, "uNoiseFloorVariance"),
noiseFloorVariance.coerceAtLeast(0f),
)
GLES31.glUniform1f(
backend.uniformLocation(smoothProgram, "uLscNoiseGainMax"),
lscNoiseGainMax.coerceAtLeast(1f),
GLES31.glUniform2i(
backend.uniformLocation(smoothProgram, "uDirection"),
directionX,
directionY,
)
GLES31.glUniform1f(
backend.uniformLocation(smoothProgram, "uFullyUnsaturatedThreshold"),
@@ -772,18 +773,6 @@ internal class GlesRawHdrWeightMap(
);
}
bool shortAvailableAt(vec2 globalPos) {
vec2 shortGlobal = globalPos + uShortRawOffset;
vec2 local = vec2(
shortGlobal.x,
shortGlobal.y - float(uShortSourceRowOffset)
);
return all(greaterThanEqual(shortGlobal, vec2(0.0))) &&
all(lessThanEqual(shortGlobal, vec2(uImageSize - ivec2(1)))) &&
all(greaterThanEqual(local, vec2(0.0))) &&
all(lessThanEqual(local, vec2(uShortSourceSize - ivec2(1))));
}
vec3 rgbNoiseVariance(
vec2 globalPos,
vec3 referenceNative,
@@ -893,14 +882,14 @@ internal class GlesRawHdrWeightMap(
);
}
void storeWeightInputs(ivec2 p, vec2 inputs) {
if (any(isnan(inputs)) || any(isinf(inputs))) {
inputs = vec2(0.0);
void storeWeights(ivec2 p, vec2 weights) {
if (any(isnan(weights)) || any(isinf(weights))) {
weights = vec2(1.0, 0.0);
}
imageStore(
uOutputWeights,
p,
uvec4(packHalf2x16(clamp(inputs, vec2(0.0), vec2(1.0))))
uvec4(packHalf2x16(clamp(weights, vec2(0.0), vec2(1.0))))
);
}
@@ -915,8 +904,12 @@ internal class GlesRawHdrWeightMap(
bool fullyUnsaturated =
referenceSaturation <= uFullyUnsaturatedThreshold;
if (fullySaturated) {
storeWeights(p, vec2(0.0, 1.0));
return;
}
if (fullyUnsaturated) {
storeWeightInputs(p, vec2(0.0, 1.0));
storeWeights(p, vec2(1.0, 0.0));
return;
}
@@ -925,24 +918,19 @@ internal class GlesRawHdrWeightMap(
uFullySaturatedThreshold,
referenceSaturation
);
float reliability = 0.0;
if (shortAvailableAt(globalPos)) {
// Once the reference is clipped, photometric residuals are no longer
// comparable. Structural alignment remains useful and deliberately
// allows a poor short-frame candidate to fall back to the reference.
reliability = fullySaturated ?
alignmentConfidence(globalPos) :
pow(
max(
noiseConfidence(globalPos) *
alignmentConfidence(globalPos) *
motionConfidence(globalPos),
0.0
),
1.0 / 3.0
);
}
storeWeightInputs(p, vec2(saturationWeight, reliability));
float reliability = pow(
max(
noiseConfidence(globalPos) *
alignmentConfidence(globalPos) *
motionConfidence(globalPos),
0.0
),
1.0 / 3.0
);
float saturationTrust = saturationWeight * saturationWeight;
float shortWeight = saturationWeight *
mix(reliability, 1.0, saturationTrust);
storeWeights(p, vec2(1.0, shortWeight));
}
""".trimIndent()
@@ -955,39 +943,20 @@ internal class GlesRawHdrWeightMap(
uniform highp usampler2D uSourceWeights;
uniform sampler2D uReferenceRgb;
uniform highp usampler2D uReferenceRaw;
uniform sampler2D uLensShadingMap;
layout(r32ui, binding = 0) writeonly uniform highp uimage2D uOutputWeights;
uniform ivec2 uImageSize;
uniform ivec2 uReferenceSourceSize;
uniform int uReferenceSourceRowOffset;
uniform int uWeightRowOffset;
uniform int uWeightRowCount;
uniform ivec2 uDirection;
uniform int uCfaPattern;
uniform float uBlackLevel[4];
uniform float uWhiteLevel;
uniform float uNoiseAlphaByChannel[4];
uniform float uNoiseBetaByChannel[4];
uniform float uNoiseFloorVariance;
uniform float uLscNoiseGainMax;
uniform float uFullyUnsaturatedThreshold;
uniform float uFullySaturatedThreshold;
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
const vec3 LUMA_SQUARED = LUMA * LUMA;
const float LOG_LUMA_SCALE = 8.0;
const float INVERSE_LOG_TWO = 1.44269504089;
const float LOG_LUMA_MODEL_VARIANCE = 0.0025;
const float CHROMA_MODEL_VARIANCE = 0.0036;
const float SATURATION_MODEL_VARIANCE = 0.1225;
const float SATURATION_GUIDE_STRENGTH = 0.20;
struct GuideStats {
float logLuma;
float logLumaVariance;
vec2 chroma;
float chromaTrust;
float saturationWeight;
};
bool finiteFloat(float value) {
return !isnan(value) && !isinf(value);
@@ -1033,125 +1002,30 @@ internal class GlesRawHdrWeightMap(
vec3(0.0) : max(value, vec3(0.0));
}
vec3 rgbLensShadingGainAt(ivec2 globalPos) {
vec2 uv = (vec2(globalPos) + vec2(0.5)) / vec2(uImageSize);
vec4 gains = texture(
uLensShadingMap,
clamp(uv, vec2(0.0), vec2(1.0))
);
vec3 rgbGains = vec3(
gains.r,
0.5 * (gains.g + gains.b),
gains.a
);
if (any(isnan(rgbGains)) || any(isinf(rgbGains))) {
return vec3(1.0);
}
return clamp(
rgbGains,
vec3(1e-3),
vec3(max(uLscNoiseGainMax, 1.0))
);
}
vec3 referenceRgbVarianceAt(ivec2 globalPos, vec3 referenceRgb) {
vec3 alpha = vec3(
uNoiseAlphaByChannel[0],
0.5 * (uNoiseAlphaByChannel[1] + uNoiseAlphaByChannel[2]),
uNoiseAlphaByChannel[3]
);
vec3 beta = vec3(
uNoiseBetaByChannel[0],
0.5 * (uNoiseBetaByChannel[1] + uNoiseBetaByChannel[2]),
uNoiseBetaByChannel[3]
);
vec3 gain = rgbLensShadingGainAt(globalPos);
vec3 variance =
alpha * clamp(referenceRgb, vec3(0.0), vec3(1.0)) * gain +
(beta + vec3(max(uNoiseFloorVariance, 0.0))) * gain * gain;
if (any(isnan(variance)) || any(isinf(variance))) {
return vec3(1e-4);
}
return max(variance, vec3(1e-10));
}
vec2 weightInputsAt(ivec2 p) {
vec2 weightsAt(ivec2 p) {
p.x = clamp(p.x, 0, uImageSize.x - 1);
p.y = clamp(
p.y,
uWeightRowOffset,
uWeightRowOffset + uWeightRowCount - 1
);
vec2 inputs = unpackHalf2x16(texelFetch(uSourceWeights, p, 0).r);
return finiteFloat(inputs.x) && finiteFloat(inputs.y) ?
clamp(inputs, vec2(0.0), vec2(1.0)) :
vec2(0.0);
vec2 weights = unpackHalf2x16(texelFetch(uSourceWeights, p, 0).r);
return finiteFloat(weights.x) && finiteFloat(weights.y) ?
clamp(weights, vec2(0.0), vec2(1.0)) :
vec2(1.0, 0.0);
}
GuideStats guideStatsAt(ivec2 globalPos, float saturationWeight) {
vec3 rgb = referenceNativeAt(globalPos);
vec3 variance = referenceRgbVarianceAt(globalPos, rgb);
float luma = max(dot(rgb, LUMA), 0.0);
float lumaVariance = max(dot(variance, LUMA_SQUARED), 1e-10);
float logArgument = 1.0 + LOG_LUMA_SCALE * luma;
float logSlope = LOG_LUMA_SCALE * INVERSE_LOG_TWO /
max(logArgument, 1e-4);
float rgbSum = max(rgb.r + rgb.g + rgb.b, 1e-4);
float lumaSnr = luma / sqrt(lumaVariance);
GuideStats result;
result.logLuma = log2(logArgument);
result.logLumaVariance = max(
lumaVariance * logSlope * logSlope,
1e-8
);
result.chroma = vec2(rgb.r, rgb.b) / rgbSum;
result.chromaTrust =
smoothstep(2.0, 8.0, lumaSnr) *
(1.0 - smoothstep(0.15, 0.85, saturationWeight));
result.saturationWeight = saturationWeight;
return result;
}
float spatialWeight(ivec2 offset) {
int distanceSquared = offset.x * offset.x + offset.y * offset.y;
if (distanceSquared == 0) return 1.0;
if (distanceSquared == 1) return 0.80;
if (distanceSquared == 2) return 0.64;
if (distanceSquared == 4) return 0.41;
if (distanceSquared == 5) return 0.33;
return 0.17;
}
float guideWeight(GuideStats center, GuideStats neighbor) {
float logLumaDifference = neighbor.logLuma - center.logLuma;
float logLumaVariance =
center.logLumaVariance + neighbor.logLumaVariance +
LOG_LUMA_MODEL_VARIANCE;
float lumaDistance =
logLumaDifference * logLumaDifference /
max(logLumaVariance, 1e-6);
vec2 chromaDifference = neighbor.chroma - center.chroma;
float chromaDistance = dot(chromaDifference, chromaDifference) /
CHROMA_MODEL_VARIANCE;
float chromaTrust = min(center.chromaTrust, neighbor.chromaTrust);
float saturationDifference =
neighbor.saturationWeight - center.saturationWeight;
float saturationDistance =
saturationDifference * saturationDifference /
SATURATION_MODEL_VARIANCE;
float distance =
lumaDistance +
chromaTrust * chromaDistance +
SATURATION_GUIDE_STRENGTH * saturationDistance;
return exp(-0.5 * clamp(distance, 0.0, 24.0));
float spatialWeight(int offset) {
int distance = abs(offset);
if (distance == 0) return 20.0;
if (distance == 1) return 15.0;
if (distance == 2) return 6.0;
return 1.0;
}
void storeWeights(ivec2 p, vec2 weights) {
if (!finiteFloat(weights.x) || !finiteFloat(weights.y)) {
weights = vec2(0.0);
weights = vec2(1.0, 0.0);
}
imageStore(
uOutputWeights,
@@ -1164,43 +1038,495 @@ internal class GlesRawHdrWeightMap(
ivec2 local = ivec2(gl_GlobalInvocationID.xy);
if (local.x >= uImageSize.x || local.y >= uWeightRowCount) return;
ivec2 p = ivec2(local.x, local.y + uWeightRowOffset);
vec3 referenceCenter = referenceNativeAt(p);
float referenceSaturation = referenceSaturationAt(p);
if (referenceSaturation >= uFullySaturatedThreshold) {
storeWeights(p, vec2(0.0, 1.0));
return;
}
if (referenceSaturation <= uFullyUnsaturatedThreshold) {
storeWeights(p, vec2(1.0, 0.0));
return;
}
vec2 centerInputs = weightInputsAt(p);
GuideStats centerGuide = guideStatsAt(p, centerInputs.x);
float shortPreferenceSum = 0.0;
float centerLuma = dot(referenceCenter, LUMA);
float shortWeightSum = 0.0;
float filterWeightSum = 0.0;
for (int y = -${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS};
y <= ${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS}; ++y) {
for (int x = -${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS};
x <= ${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS}; ++x) {
ivec2 offset = ivec2(x, y);
ivec2 q = p + offset;
vec2 sampleInputs = weightInputsAt(q);
GuideStats sampleGuide = guideStatsAt(q, sampleInputs.x);
float weight = spatialWeight(offset) *
guideWeight(centerGuide, sampleGuide);
shortPreferenceSum +=
sampleInputs.x * sampleInputs.y * weight;
filterWeightSum += weight;
}
for (
int offset = -${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS};
offset <= ${GlesRawHdrConfig.WEIGHT_SMOOTH_RADIUS};
++offset
) {
ivec2 q = p + uDirection * offset;
float guideDifference = abs(
dot(referenceNativeAt(q), LUMA) - centerLuma
);
float weight = spatialWeight(offset) *
exp(-12.0 * guideDifference);
shortWeightSum += weightsAt(q).y * weight;
filterWeightSum += weight;
}
// Smooth the actual short-frame preference, not only the clipping mask.
// Low-confidence candidates therefore fade continuously to the normal
// accumulation even when that means leaving a highlight clipped.
float shortWeight = clamp(
shortPreferenceSum / max(filterWeightSum, 1e-6),
0.0,
1.0
);
float referenceWeight = 1.0 - shortWeight;
storeWeights(p, vec2(referenceWeight, shortWeight));
float shortWeight = shortWeightSum / max(filterWeightSum, 1e-6);
storeWeights(p, vec2(1.0, shortWeight));
}
""".trimIndent()
private fun calculateWeightShader(rawCommon: String): String = """
#version 310 es
$rawCommon
layout(local_size_x = 16, local_size_y = 16) in;
uniform highp usampler2D uReferenceRaw;
uniform highp usampler2D uShortRaw;
uniform sampler2D uLensShadingMap;
layout(r32ui, binding = 0) writeonly uniform highp uimage2D uOutputWeights;
uniform ivec2 uImageSize;
uniform int uCfaPattern;
uniform float uBlackLevel[4];
uniform float uWhiteLevel;
uniform float uNoiseAlphaByChannel[4];
uniform float uNoiseBetaByChannel[4];
uniform float uReferenceExposureScale;
uniform vec2 uShortRawOffset;
uniform vec3 uCalculationGains;
uniform float uNoiseFloorVariance;
uniform float uLscNoiseGainMax;
uniform float uFullyUnsaturatedThreshold;
uniform float uFullySaturatedThreshold;
struct SampleStats {
float value;
float variance;
float sensor;
};
float finiteOr(float value, float fallback) {
return isnan(value) || isinf(value) ? fallback : value;
}
float finiteUnit(float value, float fallback) {
return clamp(finiteOr(value, fallback), 0.0, 1.0);
}
ivec2 phaseOffsetAt(ivec2 p, int period) {
return ivec2(p.x % period, p.y % period);
}
ivec2 maxLatticeForPhase(ivec2 phaseOffset, int period) {
return max((uImageSize - ivec2(1) - phaseOffset) / ivec2(period), ivec2(0));
}
SampleStats statsAtSample(
highp usampler2D source,
ivec2 p,
int channel
) {
p = clamp(p, ivec2(0), uImageSize - ivec2(1));
float raw = float(texelFetch(source, p, 0).r);
float range = max(uWhiteLevel - uBlackLevel[channel], 1.0);
float sensor = clamp(max(raw - uBlackLevel[channel], 0.0) / range, 0.0, 1.0);
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uImageSize);
vec4 lsc = texture(uLensShadingMap, clamp(uv, vec2(0.0), vec2(1.0)));
float lscValue = max(
finiteOr(lsc[lensShadingChannelAt(uCfaPattern, p)], 1.0),
1e-3
);
float noiseGain = clamp(lscValue, 1e-3, max(uLscNoiseGainMax, 1.0));
SampleStats result;
result.value = finiteOr(sensor * lscValue, sensor);
float variance = max(
uNoiseAlphaByChannel[channel] * clamp(sensor * noiseGain, 0.0, 1.0) *
noiseGain +
uNoiseBetaByChannel[channel] * noiseGain * noiseGain,
max(uNoiseFloorVariance, 0.0) * noiseGain * noiseGain
);
result.variance = max(finiteOr(variance, 1e-10), 1e-10);
result.sensor = finiteUnit(sensor, 0.0);
return result;
}
SampleStats mixStats(
SampleStats a,
SampleStats b,
float weight
) {
SampleStats result;
result.value = mix(a.value, b.value, weight);
result.variance = mix(a.variance, b.variance, weight);
result.sensor = mix(a.sensor, b.sensor, weight);
return result;
}
SampleStats sampleSamePhase(
highp usampler2D source,
vec2 rawPos,
ivec2 phaseOffset,
int period,
int channel
) {
ivec2 maxLattice = maxLatticeForPhase(phaseOffset, period);
vec2 phase = vec2(phaseOffset);
vec2 latticePos = clamp(
(rawPos - phase) / float(period),
vec2(0.0),
vec2(maxLattice)
);
ivec2 p0 = ivec2(floor(latticePos));
ivec2 p1 = min(p0 + ivec2(1), maxLattice);
vec2 f = latticePos - vec2(p0);
SampleStats s00 = statsAtSample(
source,
phaseOffset + p0 * period,
channel
);
SampleStats s10 = statsAtSample(
source,
phaseOffset + ivec2(p1.x, p0.y) * period,
channel
);
SampleStats s01 = statsAtSample(
source,
phaseOffset + ivec2(p0.x, p1.y) * period,
channel
);
SampleStats s11 = statsAtSample(
source,
phaseOffset + p1 * period,
channel
);
return mixStats(
mixStats(s00, s10, f.x),
mixStats(s01, s11, f.x),
f.y
);
}
SampleStats workingReferenceAt(
ivec2 p,
ivec2 phaseOffset,
int period,
int channel
) {
SampleStats result = sampleSamePhase(
uReferenceRaw,
vec2(p),
phaseOffset,
period,
channel
);
float gain = channel == 0 ? uCalculationGains.r :
(channel == 3 ? uCalculationGains.b : uCalculationGains.g);
result.value *= gain * uReferenceExposureScale;
result.variance *= gain * gain *
uReferenceExposureScale * uReferenceExposureScale;
return result;
}
SampleStats workingShortAt(
vec2 p,
ivec2 phaseOffset,
int period,
int channel
) {
SampleStats result = sampleSamePhase(
uShortRaw,
p + uShortRawOffset,
phaseOffset,
period,
channel
);
float gain = channel == 0 ? uCalculationGains.r :
(channel == 3 ? uCalculationGains.b : uCalculationGains.g);
result.value *= gain;
result.variance *= gain * gain;
return result;
}
float normalizedResidual(
SampleStats referenceStats,
SampleStats shortStats
) {
float signal = max(referenceStats.value, shortStats.value);
float toleranceVariance = referenceStats.variance + shortStats.variance +
pow(0.012 + 0.025 * signal, 2.0);
float residual = abs(referenceStats.value - shortStats.value) /
sqrt(max(toleranceVariance, 1e-10));
return max(finiteOr(residual, 1e6), 0.0);
}
float noiseConfidence(
ivec2 p,
ivec2 phaseOffset,
int period,
int channel
) {
SampleStats referenceStats = workingReferenceAt(
p,
phaseOffset,
period,
channel
);
SampleStats shortStats = workingShortAt(
vec2(p),
phaseOffset,
period,
channel
);
float residual = max(normalizedResidual(referenceStats, shortStats) - 1.0, 0.0);
return finiteUnit(exp(-0.5 * pow(residual / 2.5, 2.0)), 0.0);
}
float alignmentConfidence(
ivec2 p,
ivec2 phaseOffset,
int period,
int channel
) {
ivec2 dx = ivec2(period, 0);
ivec2 dy = ivec2(0, period);
SampleStats referenceLeft = workingReferenceAt(
p - dx,
phaseOffset,
period,
channel
);
SampleStats referenceRight = workingReferenceAt(
p + dx,
phaseOffset,
period,
channel
);
SampleStats referenceTop = workingReferenceAt(
p - dy,
phaseOffset,
period,
channel
);
SampleStats referenceBottom = workingReferenceAt(
p + dy,
phaseOffset,
period,
channel
);
SampleStats shortLeft = workingShortAt(
vec2(p - dx),
phaseOffset,
period,
channel
);
SampleStats shortRight = workingShortAt(
vec2(p + dx),
phaseOffset,
period,
channel
);
SampleStats shortTop = workingShortAt(
vec2(p - dy),
phaseOffset,
period,
channel
);
SampleStats shortBottom = workingShortAt(
vec2(p + dy),
phaseOffset,
period,
channel
);
vec2 referenceGradient = vec2(
referenceRight.value - referenceLeft.value,
referenceBottom.value - referenceTop.value
);
vec2 shortGradient = vec2(
shortRight.value - shortLeft.value,
shortBottom.value - shortTop.value
);
float gradientVariance =
referenceLeft.variance + referenceRight.variance +
referenceTop.variance + referenceBottom.variance +
shortLeft.variance + shortRight.variance +
shortTop.variance + shortBottom.variance;
float residual = length(referenceGradient - shortGradient) /
sqrt(max(gradientVariance + 0.0004, 1e-10));
residual = max(residual - 1.0, 0.0);
return finiteUnit(exp(-0.5 * pow(residual / 3.0, 2.0)), 0.0);
}
float motionConfidence(
ivec2 p,
ivec2 phaseOffset,
int period,
int channel
) {
float residualSum = 0.0;
float residualSquaredSum = 0.0;
float weightSum = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
ivec2 samplePos = p + ivec2(x, y) * period;
SampleStats referenceStats = workingReferenceAt(
samplePos,
phaseOffset,
period,
channel
);
SampleStats shortStats = workingShortAt(
vec2(samplePos),
phaseOffset,
period,
channel
);
float usableReference = 1.0 - smoothstep(
uFullyUnsaturatedThreshold,
uFullySaturatedThreshold,
referenceStats.sensor
);
float residual = normalizedResidual(referenceStats, shortStats);
residualSum += residual * usableReference;
residualSquaredSum += residual * residual * usableReference;
weightSum += usableReference;
}
}
if (weightSum < 0.5) return 1.0;
float meanResidual = residualSum / weightSum;
float residualVariance = max(
residualSquaredSum / weightSum - meanResidual * meanResidual,
0.0
);
float motionEvidence = max(meanResidual - 1.5, 0.0) +
0.35 * sqrt(residualVariance);
return finiteUnit(exp(-0.5 * pow(motionEvidence / 2.5, 2.0)), 0.0);
}
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= uImageSize.x || p.y >= uImageSize.y) return;
int channel = bayerIndexAt(uCfaPattern, p);
int period = cfaPeriod(uCfaPattern);
ivec2 phaseOffset = phaseOffsetAt(p, period);
float referenceSensor = statsAtSample(uReferenceRaw, p, channel).sensor;
bool fullyUnsaturated = referenceSensor <= uFullyUnsaturatedThreshold;
bool fullySaturated = referenceSensor >= uFullySaturatedThreshold;
float referenceWeight = fullySaturated ? 0.0 : 1.0;
float shortWeight = 0.0;
if (fullySaturated) {
shortWeight = 1.0;
} else if (fullyUnsaturated) {
shortWeight = 0.0;
} else {
float saturationWeight = smoothstep(
uFullyUnsaturatedThreshold,
uFullySaturatedThreshold,
referenceSensor
);
float noise = noiseConfidence(p, phaseOffset, period, channel);
float alignment = alignmentConfidence(p, phaseOffset, period, channel);
float motion = motionConfidence(p, phaseOffset, period, channel);
float reliability = pow(
max(noise * alignment * motion, 0.0),
1.0 / 3.0
);
float saturationTrust = saturationWeight * saturationWeight;
shortWeight = saturationWeight *
mix(reliability, 1.0, saturationTrust);
}
shortWeight = finiteUnit(shortWeight, 0.0);
imageStore(
uOutputWeights,
p,
uvec4(packHalf2x16(vec2(
referenceWeight,
clamp(shortWeight, 0.0, 1.0)
)))
);
}
""".trimIndent()
private fun smoothWeightShader(rawCommon: String): String = """
#version 310 es
$rawCommon
precision highp float;
precision highp int;
layout(local_size_x = 16, local_size_y = 16) in;
uniform highp usampler2D uSourceWeights;
uniform highp usampler2D uReferenceRaw;
layout(r32ui, binding = 0) writeonly uniform highp uimage2D uOutputWeights;
uniform ivec2 uImageSize;
uniform ivec2 uDirection;
uniform int uCfaPattern;
uniform float uBlackLevel[4];
uniform float uWhiteLevel;
uniform float uFullyUnsaturatedThreshold;
uniform float uFullySaturatedThreshold;
float finiteOr(float value, float fallback) {
return isnan(value) || isinf(value) ? fallback : value;
}
float spatialWeight(int offset) {
int distance = abs(offset);
if (distance == 0) return 20.0;
if (distance == 1) return 15.0;
if (distance == 2) return 6.0;
return 1.0;
}
float referenceSensorAt(ivec2 p) {
p = clamp(p, ivec2(0), uImageSize - ivec2(1));
int channel = bayerIndexAt(uCfaPattern, p);
float raw = float(texelFetch(uReferenceRaw, p, 0).r);
float range = max(uWhiteLevel - uBlackLevel[channel], 1.0);
return clamp(max(raw - uBlackLevel[channel], 0.0) / range, 0.0, 1.0);
}
vec2 weightsAt(ivec2 p) {
p = clamp(p, ivec2(0), uImageSize - ivec2(1));
vec2 weights = unpackHalf2x16(texelFetch(uSourceWeights, p, 0).r);
if (any(isnan(weights)) || any(isinf(weights))) {
return vec2(1.0, 0.0);
}
return clamp(weights, vec2(0.0), vec2(1.0));
}
void storeWeights(ivec2 p, vec2 weights) {
weights = vec2(
finiteOr(weights.x, 1.0),
finiteOr(weights.y, 0.0)
);
imageStore(
uOutputWeights,
p,
uvec4(packHalf2x16(clamp(weights, vec2(0.0), vec2(1.0))))
);
}
void main() {
ivec2 p = ivec2(gl_GlobalInvocationID.xy);
if (p.x >= uImageSize.x || p.y >= uImageSize.y) return;
float referenceSensor = referenceSensorAt(p);
if (referenceSensor >= uFullySaturatedThreshold) {
storeWeights(p, vec2(0.0, 1.0));
return;
}
if (referenceSensor <= uFullyUnsaturatedThreshold) {
storeWeights(p, vec2(1.0, 0.0));
return;
}
float shortWeightSum = 0.0;
float filterWeightSum = 0.0;
for (int offset = -3; offset <= 3; ++offset) {
ivec2 q = clamp(
p + uDirection * offset,
ivec2(0),
uImageSize - ivec2(1)
);
float weight = spatialWeight(offset);
shortWeightSum += weightsAt(q).y * weight;
filterWeightSum += weight;
}
float shortWeight = shortWeightSum / max(filterWeightSum, 1e-6);
storeWeights(p, vec2(1.0, shortWeight));
}
""".trimIndent()
}
}
@@ -5,187 +5,139 @@ import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Spatial LTM stage fitted against Google PGTM cells from the Skyyking regression set.
*
* Each local synthetic-exposure stack is biased from local luminance and highlight topology.
* Google-compatible plans adjust the brightest member; centered Photon plans translate both
* endpoints to preserve their EV span. A normalized 3x3 convolution gives these decisions the
* same spatial support as the profile map; exposure fusion still produces the final gain curve.
*/
/** PXLs2-trained Gaussian parameter pyramid for PGTM black gain and shoulder shape. */
internal object DngHdrLtmSpatialModel {
private const val LEVEL_EPS = 0.006f
private const val TAIL_EPS = 0.04f
private const val MAX_LOCAL_EXPOSURE_OFFSET_EV = 1.25f
private const val TAIL_EPS = 0.040f
private const val FEATURE_COUNT = 11
fun buildExposurePlans(
private val BLACK_FINE = floatArrayOf(
0.080100003f, 0.038598747f, -0.009591165f, 0.040930166f,
-0.032663656f, 0.003484404f, -0.036142493f, -0.013543239f,
0.221111670f, -0.056745937f, 0.022797185f,
)
private val BLACK_REGIONAL = floatArrayOf(
0.050453932f, -0.164809241f, -0.025868995f, 0.024685689f,
-0.169930713f, 0.082901192f, 0.057923125f, 0.054644468f,
-0.628739524f, -0.120014771f, 0.272379151f,
)
private val SHAPE_FINE = floatArrayOf(
-0.042331190f, -0.002069818f, -0.003614245f, -0.011158727f,
0.025782988f, -0.011451446f, 0.188099210f, -0.026559214f,
-0.048570362f, 0.027670583f, -0.014421700f,
)
private val SHAPE_REGIONAL = floatArrayOf(
0.032147274f, 0.012769699f, -0.005806728f, -0.042285077f,
0.097232112f, -0.041291256f, 0.005268769f, -0.025812120f,
0.213336867f, 0.033524746f, -0.045624738f,
)
fun buildCurvePlans(
cells: Array<HdrPgtmCellStats?>,
grid: HdrPgtmGrid,
global: HdrPgtmCellStats,
globalPlan: HdrLtmExposurePlan,
minimumExposureGain: Float = globalPlan.darkestExposureGain,
maxExposureGain: Float,
preserveExposureSpan: Boolean = false,
): Array<HdrLtmExposurePlan> {
val globalFeature = ToneFeature.from(global)
val features = Array(cells.size) { index ->
cells[index]?.takeIf { it.sampleWeight > 0f }?.let(ToneFeature::from) ?: globalFeature
}
val neighborhoods = smoothFeatures(features, grid)
// The global exposure plan represents a robust scene median. Center local residuals on
// the same statistic;
// a feature built from arithmetic-mean percentiles is biased in strongly bimodal scenes.
val referenceFeature = medianFeature(neighborhoods)
val saturatedScene = smoothStep(0.55f, 0.72f, global.highlightFraction) *
smoothStep(0.70f, 0.84f, global.p50)
val sparseSeparatedTail =
(1f - smoothStep(0.21f, 0.24f, global.p98)) *
(1f - smoothStep(1.15f, 1.45f, global.inputTailP95)) *
smoothStep(
0.75f,
1.20f,
log2((global.inputTailP99 + TAIL_EPS) / (global.inputTailP95 + TAIL_EPS))
)
val residualScale = 1f + 2.20f * saturatedScene + 1.00f * sparseSeparatedTail
return Array(cells.size) { index ->
val cell = cells[index]
if (cell == null || cell.sampleWeight <= 0f) {
globalPlan
} else {
planLocalExposureRange(
globalPlan = globalPlan,
referenceFeature = referenceFeature,
localFeature = neighborhoods[index],
sampleWeight = cell.sampleWeight,
residualScale = residualScale,
minimumExposureGain = minimumExposureGain,
maxExposureGain = maxExposureGain,
preserveExposureSpan = preserveExposureSpan,
)
}
}
}
private fun planLocalExposureRange(
globalPlan: HdrLtmExposurePlan,
referenceFeature: ToneFeature,
localFeature: ToneFeature,
sampleWeight: Float,
residualScale: Float,
minimumExposureGain: Float,
maxExposureGain: Float,
preserveExposureSpan: Boolean,
): HdrLtmExposurePlan {
val residualEv =
0.0070524f * (localFeature.logP10 - referenceFeature.logP10) +
0.0018840f * (localFeature.logP50 - referenceFeature.logP50) -
0.1109007f * (localFeature.logP90 - referenceFeature.logP90) +
0.0874353f * (localFeature.logP98 - referenceFeature.logP98) -
0.0166212f * (localFeature.fullRangeEv - referenceFeature.fullRangeEv) -
0.0036315f * (localFeature.upperRangeEv - referenceFeature.upperRangeEv) -
0.2828567f * (localFeature.sqrtHighlightFraction - referenceFeature.sqrtHighlightFraction) +
0.0116745f * (localFeature.tail995Ev - referenceFeature.tail995Ev) -
0.1805684f * (localFeature.tail999Ev - referenceFeature.tail999Ev)
val confidence = smoothStep(16f, 64f, sampleWeight)
val exposureOffsetEv = (residualEv * confidence * residualScale)
.coerceIn(-MAX_LOCAL_EXPOSURE_OFFSET_EV, MAX_LOCAL_EXPOSURE_OFFSET_EV)
if (!preserveExposureSpan) {
return globalPlan.copy(
brightestExposureGain = (
globalPlan.brightestExposureGain * 2.0f.pow(exposureOffsetEv)
).coerceIn(globalPlan.darkestExposureGain, maxExposureGain)
globalPlan: HdrPgtmCurvePlan,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
curveParameters: HdrPgtmCurveParameters,
): Array<HdrPgtmCurvePlan> {
val boundedGlobalPlan = globalPlan.copy(
blackGain = globalPlan.blackGain.coerceIn(
curveParameters.minBlackGain,
curveParameters.maxTableGain,
),
shapePower = globalPlan.shapePower.coerceIn(
curveParameters.minShapePower,
curveParameters.maxShapePower,
),
)
val fallbackStats = cells.filterNotNull().firstOrNull()
?: return Array(cells.size) { boundedGlobalPlan }
val raw = Array(cells.size) { index ->
featureVector(
stats = cells[index] ?: fallbackStats,
baselineExposureEv = baselineExposureEv,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
)
}
val minimumEv = log2(minimumExposureGain)
val maximumEv = log2(maxExposureGain)
val darkestEv = log2(globalPlan.darkestExposureGain)
val brightestEv = log2(globalPlan.brightestExposureGain)
val halfSpanEv = (brightestEv - darkestEv).coerceAtLeast(0f) * 0.5f
val requestedCenterEv = (darkestEv + brightestEv) * 0.5f + exposureOffsetEv
val centerEv = requestedCenterEv.coerceIn(
minimumEv + halfSpanEv,
maximumEv - halfSpanEv,
)
return HdrLtmExposurePlan(
brightestExposureGain = 2.0f.pow(centerEv + halfSpanEv),
darkestExposureGain = 2.0f.pow(centerEv - halfSpanEv),
val fine = smoothFeatures(raw, grid)
var regional = fine
repeat(3) { regional = smoothFeatures(regional, grid) }
val reference = medianFeature(regional)
return Array(cells.size) { index ->
if (cells[index] == null) {
boundedGlobalPlan
} else {
var blackOffsetEv = 0f
var shapeOffset = 0f
for (feature in 0 until FEATURE_COUNT) {
val fineResidual = fine[index][feature] - regional[index][feature]
val regionalResidual = regional[index][feature] - reference[feature]
blackOffsetEv +=
BLACK_FINE[feature] * fineResidual +
BLACK_REGIONAL[feature] * regionalResidual
shapeOffset +=
SHAPE_FINE[feature] * fineResidual +
SHAPE_REGIONAL[feature] * regionalResidual
}
globalPlan.copy(
blackGain = (globalPlan.blackGain * 2.0f.pow(blackOffsetEv))
.coerceIn(curveParameters.minBlackGain, curveParameters.maxTableGain),
shapePower = (globalPlan.shapePower + shapeOffset).coerceIn(
curveParameters.minShapePower,
curveParameters.maxShapePower,
),
)
}
}
}
private fun featureVector(
stats: HdrPgtmCellStats,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
): FloatArray {
val logP10 = log2(stats.p10 + LEVEL_EPS)
val logP50 = log2(stats.p50 + LEVEL_EPS)
val logP90 = log2(stats.p90 + LEVEL_EPS)
val logP98 = log2(stats.p98 + LEVEL_EPS)
return floatArrayOf(
logP10,
logP50,
logP90,
logP98,
logP98 - logP10,
logP98 - logP50,
sqrt(stats.highlightFraction.coerceIn(0f, 1f)),
log2((stats.p995Input + TAIL_EPS) / (stats.p98 + TAIL_EPS)),
log2((stats.p999Input + TAIL_EPS) / (stats.p995Input + TAIL_EPS)),
snrFeature(stats.p10, baselineExposureEv, noiseSlope, noiseOffset),
snrFeature(stats.p50, baselineExposureEv, noiseSlope, noiseOffset),
)
}
private fun medianFeature(source: Array<ToneFeature>): ToneFeature {
fun median(selector: (ToneFeature) -> Float): Float {
val values = FloatArray(source.size) { selector(source[it]) }
values.sort()
val center = values.size / 2
return if (values.size % 2 == 0) {
0.5f * (values[center - 1] + values[center])
} else {
values[center]
}
}
return ToneFeature(
logP10 = median { it.logP10 },
logP50 = median { it.logP50 },
logP90 = median { it.logP90 },
logP98 = median { it.logP98 },
fullRangeEv = median { it.fullRangeEv },
upperRangeEv = median { it.upperRangeEv },
sqrtHighlightFraction = median { it.sqrtHighlightFraction },
tail995Ev = median { it.tail995Ev },
tail999Ev = median { it.tail999Ev }
)
private fun snrFeature(
signal: Float,
baselineExposureEv: Float,
noiseSlope: Float,
noiseOffset: Float,
): Float {
val sourceSignal = max(signal / DngBaselineExposure.exactGain(baselineExposureEv), 0f)
val variance = max(noiseSlope * sourceSignal + noiseOffset, 1e-12f)
return log2(1f + sourceSignal / sqrt(variance))
}
private fun smoothFeatures(
source: Array<ToneFeature>,
source: Array<FloatArray>,
grid: HdrPgtmGrid,
): Array<ToneFeature> {
return Array(source.size) { index ->
val x = index % grid.mapPointsH
val y = index / grid.mapPointsH
var weightSum = 0f
var logP10 = 0f
var logP50 = 0f
var logP90 = 0f
var logP98 = 0f
var fullRangeEv = 0f
var upperRangeEv = 0f
var sqrtHighlightFraction = 0f
var tail995Ev = 0f
var tail999Ev = 0f
forEachNeighbor(x, y, grid) { neighbor, weight ->
val feature = source[neighbor]
weightSum += weight
logP10 += feature.logP10 * weight
logP50 += feature.logP50 * weight
logP90 += feature.logP90 * weight
logP98 += feature.logP98 * weight
fullRangeEv += feature.fullRangeEv * weight
upperRangeEv += feature.upperRangeEv * weight
sqrtHighlightFraction += feature.sqrtHighlightFraction * weight
tail995Ev += feature.tail995Ev * weight
tail999Ev += feature.tail999Ev * weight
}
ToneFeature(
logP10 = logP10 / weightSum,
logP50 = logP50 / weightSum,
logP90 = logP90 / weightSum,
logP98 = logP98 / weightSum,
fullRangeEv = fullRangeEv / weightSum,
upperRangeEv = upperRangeEv / weightSum,
sqrtHighlightFraction = sqrtHighlightFraction / weightSum,
tail995Ev = tail995Ev / weightSum,
tail999Ev = tail999Ev / weightSum
)
}
}
private inline fun forEachNeighbor(
x: Int,
y: Int,
grid: HdrPgtmGrid,
block: (index: Int, weight: Float) -> Unit,
) {
): Array<FloatArray> = Array(source.size) { index ->
val x = index % grid.mapPointsH
val y = index / grid.mapPointsH
val result = FloatArray(FEATURE_COUNT)
var weightSum = 0f
for (dy in -1..1) {
val yy = (y + dy).coerceIn(0, grid.mapPointsV - 1)
for (dx in -1..1) {
@@ -195,51 +147,31 @@ internal object DngHdrLtmSpatialModel {
dx == 0 || dy == 0 -> 2f
else -> 1f
}
block(yy * grid.mapPointsH + xx, weight)
val feature = source[yy * grid.mapPointsH + xx]
weightSum += weight
for (component in 0 until FEATURE_COUNT) {
result[component] += feature[component] * weight
}
}
}
for (component in 0 until FEATURE_COUNT) result[component] /= weightSum
result
}
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
val t = ((value - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
private fun log2(value: Float): Float {
return (ln(max(value, 1e-6f).toDouble()) / ln(2.0)).toFloat()
}
private data class ToneFeature(
val logP10: Float,
val logP50: Float,
val logP90: Float,
val logP98: Float,
val fullRangeEv: Float,
val upperRangeEv: Float,
val sqrtHighlightFraction: Float,
val tail995Ev: Float,
val tail999Ev: Float,
) {
companion object {
fun from(stats: HdrPgtmCellStats): ToneFeature {
val logP10 = log2(stats.p10 + LEVEL_EPS)
val logP50 = log2(stats.p50 + LEVEL_EPS)
val logP90 = log2(stats.p90 + LEVEL_EPS)
val logP98 = log2(stats.p98 + LEVEL_EPS)
return ToneFeature(
logP10 = logP10,
logP50 = logP50,
logP90 = logP90,
logP98 = logP98,
fullRangeEv = logP98 - logP10,
upperRangeEv = logP98 - logP50,
sqrtHighlightFraction = sqrt(stats.highlightFraction.coerceIn(0f, 1f)),
tail995Ev = log2((stats.p995Input + TAIL_EPS) / (stats.p98 + TAIL_EPS)),
tail999Ev = log2((stats.p999Input + TAIL_EPS) / (stats.p995Input + TAIL_EPS))
)
private fun medianFeature(source: Array<FloatArray>): FloatArray =
FloatArray(FEATURE_COUNT) { component ->
val values = FloatArray(source.size) { source[it][component] }
values.sort()
val center = values.size / 2
if (values.size % 2 == 0) {
0.5f * (values[center - 1] + values[center])
} else {
values[center]
}
}
}
private fun log2(value: Float): Float =
(ln(max(value, 1e-8f).toDouble()) / ln(2.0)).toFloat()
}
internal data class HdrPgtmGrid(
@@ -263,8 +195,3 @@ internal data class HdrPgtmCellStats(
val maxInput: Float,
val sampleWeight: Float,
)
internal data class HdrLtmExposurePlan(
val brightestExposureGain: Float,
val darkestExposureGain: Float,
)
@@ -1,47 +1,30 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Plans a DNG profile gain table from GPU-produced spatial statistics.
*
* 1. estimate the scene-white range from BaselineExposure and robust spatial tail statistics;
* 2. plan the local synthetic-exposure range for every map cell;
* 3. package gain curves generated by [DngHdrProfileGainTableGpuShaders].
*/
/** Plans a constrained DNG profile gain table from GPU-produced spatial RAW statistics. */
internal object DngHdrProfileGainTableGenerator {
private const val TAG = "DngHdrProfileGainTableGenerator"
const val CELL_STATS_FLOAT_STRIDE = 8
private const val MAP_INPUT_WEIGHT_COUNT = 5
private const val DEFAULT_TABLE_POINTS = 257
private const val MIN_TABLE_POINTS = 257
private const val MAX_TABLE_POINTS = 257
private const val TABLE_POINTS = 257
private const val TARGET_TILE_PX = 64
private const val GRID_MIN_H = 8
private const val GRID_MIN_V = 6
private const val GRID_MAX_H = 64
private const val GRID_MAX_V = 48
private const val MAX_SCENE_WHITE = 64f
private const val MAX_LTM_GAIN = 6.18f
private const val AUTO_EXPOSURE_TARGET = 0.278f
private const val WELL_EXPOSED_KEY = 0.525f
private const val WELL_EXPOSED_SIGMA_EV = 0.750f
// Official Pixel maps broaden the exposure fusion only in the shoulder:
// the last trustworthy highlights stay close to white while the toe and
// midtones retain the narrower local-exposure weighting.
private const val HIGHLIGHT_WELL_EXPOSED_SIGMA_EV = 1.200f
private const val HIGHLIGHT_FUSION_START = 0.45f
private const val HIGHLIGHT_FUSION_END = 0.65f
private const val WEIGHT_LUT_STEPS_PER_EV = 256f
private const val WEIGHT_LUT_MAX_DISTANCE_EV = 12f
private const val LEVEL_EPS = 0.006f
private const val TAIL_EPS = 0.040f
private const val CURVE_EPS = 1e-6f
private const val FALLBACK_NOISE_SLOPE = 1e-4f
private const val FALLBACK_NOISE_OFFSET = 4.5e-7f
internal const val BASE_INPUT_WEIGHT_RED = 0.1495f
internal const val BASE_INPUT_WEIGHT_GREEN = 0.2935f
@@ -54,50 +37,36 @@ internal object DngHdrProfileGainTableGenerator {
BASE_INPUT_WEIGHT_GREEN,
BASE_INPUT_WEIGHT_BLUE,
BASE_INPUT_WEIGHT_MIN,
BASE_INPUT_WEIGHT_MAX
)
internal val GOOGLE_FUSION_PARAMETERS = HdrExposureFusionParameters(
autoExposureTarget = AUTO_EXPOSURE_TARGET,
wellExposedKey = WELL_EXPOSED_KEY,
maxExposureGain = MAX_LTM_GAIN,
highlightFusionStart = HIGHLIGHT_FUSION_START,
highlightFusionEnd = HIGHLIGHT_FUSION_END,
BASE_INPUT_WEIGHT_MAX,
)
internal val PHOTON_FUSION_PARAMETERS = HdrExposureFusionParameters(
autoExposureTarget = 0.35f,
wellExposedKey = 0.5f,
maxExposureGain = MAX_LTM_GAIN,
highlightFusionStart = HIGHLIGHT_FUSION_START,
highlightFusionEnd = HIGHLIGHT_FUSION_END,
// Keep complete, independent parameter sets even while values match. Google fitting and
// Photon look development can then change curve limits without adding mode branches.
internal val GOOGLE_CURVE_PARAMETERS = HdrPgtmCurveParameters(
minTableGain = 0.01f,
maxTableGain = 4.80f,
minBlackGain = 0.50f,
// The stored table uses point/257 for non-terminal inputs. Extending the measured 0.020
// toe plateau through the next grid point keeps a DNG lookup at 0.020 on that plateau.
toeEnd = 0.024f,
shapeQ = 1.50f,
minShapePower = 1.0f,
maxShapePower = 1.425f,
minInputScale = 0.25f,
maxInputScale = 1.05f,
)
private val WELL_EXPOSED_WEIGHT_LUT = FloatArray(
(WEIGHT_LUT_MAX_DISTANCE_EV * WEIGHT_LUT_STEPS_PER_EV).toInt() + 1
) { index ->
val distanceEv = index.toFloat() / WEIGHT_LUT_STEPS_PER_EV
exp((-0.5f * (distanceEv / WELL_EXPOSED_SIGMA_EV).pow(2f)).toDouble()).toFloat()
}
private val HIGHLIGHT_WELL_EXPOSED_WEIGHT_LUT = FloatArray(
(WEIGHT_LUT_MAX_DISTANCE_EV * WEIGHT_LUT_STEPS_PER_EV).toInt() + 1
) { index ->
val distanceEv = index.toFloat() / WEIGHT_LUT_STEPS_PER_EV
exp(
(-0.5f * (distanceEv / HIGHLIGHT_WELL_EXPOSED_SIGMA_EV).pow(2f)).toDouble()
).toFloat()
}
/** Interleaved normal/highlight weights uploaded once for the GPU curve generator. */
internal fun interleavedWellExposedWeightLut(): FloatArray {
return FloatArray(WELL_EXPOSED_WEIGHT_LUT.size * 2) { index ->
val lutIndex = index / 2
if ((index and 1) == 0) {
WELL_EXPOSED_WEIGHT_LUT[lutIndex]
} else {
HIGHLIGHT_WELL_EXPOSED_WEIGHT_LUT[lutIndex]
}
}
}
internal val PHOTON_CURVE_PARAMETERS = HdrPgtmCurveParameters(
minTableGain = 0.01f,
maxTableGain = 4.80f,
minBlackGain = 0.50f,
toeEnd = 0.015f,
shapeQ = 2.445f,
minShapePower = 1.05f,
maxShapePower = 1.25f,
minInputScale = 0.05f,
maxInputScale = 1.05f,
)
fun gridSizeFor(width: Int, height: Int): IntArray {
val grid = chooseLtmGrid(width, height)
@@ -109,13 +78,13 @@ internal object DngHdrProfileGainTableGenerator {
height: Int,
baselineExposureEv: Float,
packedCellStats: FloatArray,
tablePointCount: Int = DEFAULT_TABLE_POINTS,
noiseSlope: Float = FALLBACK_NOISE_SLOPE,
noiseOffset: Float = FALLBACK_NOISE_OFFSET,
tablePointCount: Int = TABLE_POINTS,
diagnosticBand: DiagnosticBand? = null,
fusionParameters: HdrExposureFusionParameters = GOOGLE_FUSION_PARAMETERS,
curveParameters: HdrPgtmCurveParameters = GOOGLE_CURVE_PARAMETERS,
): HdrProfileGainTablePlan? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) {
return null
}
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) return null
val grid = chooseLtmGrid(width, height)
val cellCount = grid.mapPointsH * grid.mapPointsV
val requiredStats = cellCount * CELL_STATS_FLOAT_STRIDE
@@ -129,35 +98,36 @@ internal object DngHdrProfileGainTableGenerator {
val sampleWeight = packedCellStats[offset + 5]
.takeIf { it.isFinite() && it > 0f }
?: 0f
if (sampleWeight > 0f) {
packedStatsAt(packedCellStats, offset, sampleWeight)
} else {
null
}
if (sampleWeight > 0f) packedStatsAt(packedCellStats, offset, sampleWeight) else null
}
val spatialStats = weightedGlobalStats(cells)
val inputScale = estimateInputScale(spatialStats, baselineExposureEv)
val globalPlan = buildGlobalExposurePlan(
stats = spatialStats,
val global = weightedGlobalStats(cells)
val safeNoiseSlope = noiseSlope.takeIf { it.isFinite() && it > 0f }
?: FALLBACK_NOISE_SLOPE
val safeNoiseOffset = noiseOffset.takeIf { it.isFinite() && it > 0f }
?: FALLBACK_NOISE_OFFSET
val inputScale = estimateInputScale(global, baselineExposureEv, curveParameters)
val globalPlan = buildGlobalCurvePlan(
stats = global,
inputScale = inputScale,
fusionParameters = fusionParameters,
noiseOffset = safeNoiseOffset,
curveParameters = curveParameters,
)
val cellPlans = DngHdrLtmSpatialModel.buildExposurePlans(
val cellPlans = DngHdrLtmSpatialModel.buildCurvePlans(
cells = cells,
grid = grid,
global = spatialStats,
globalPlan = globalPlan,
minimumExposureGain = inputScale,
maxExposureGain = fusionParameters.maxExposureGain,
preserveExposureSpan = false,
baselineExposureEv = baselineExposureEv,
noiseSlope = safeNoiseSlope,
noiseOffset = safeNoiseOffset,
curveParameters = curveParameters,
)
return HdrProfileGainTablePlan(
grid = grid,
pointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS),
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
inputScale = inputScale,
curveParameters = curveParameters,
cellPlans = cellPlans,
diagnosticBand = diagnosticBand?.sanitized(),
fusionParameters = fusionParameters,
)
}
@@ -165,9 +135,13 @@ internal object DngHdrProfileGainTableGenerator {
plan: HdrProfileGainTablePlan,
gains: FloatArray,
): DngProfileGainTableMap? {
val expectedGainCount = plan.grid.mapPointsH * plan.grid.mapPointsV * plan.pointCount
if (gains.size != expectedGainCount) {
PLog.e(TAG, "GPU PGTM gain count=${gains.size}, expected=$expectedGainCount")
val expected = plan.grid.mapPointsH * plan.grid.mapPointsV * plan.pointCount
if (gains.size != expected) {
PLog.e(TAG, "GPU PGTM gain count=${gains.size}, expected=$expected")
return null
}
if (gains.any { !it.isFinite() || it <= 0f }) {
PLog.e(TAG, "GPU PGTM contains a non-finite or non-positive gain")
return null
}
return createMap(plan, gains)
@@ -188,15 +162,12 @@ internal object DngHdrProfileGainTableGenerator {
start = safeStart,
end = safeEnd,
feather = feather.coerceIn(0f, 0.12f),
mode = mode
mode = mode,
)
}
}
enum class DiagnosticMode {
PASS_ONLY,
BLOCK_ONLY,
}
enum class DiagnosticMode { PASS_ONLY, BLOCK_ONLY }
private fun packedStatsAt(
stats: FloatArray,
@@ -207,21 +178,21 @@ internal object DngHdrProfileGainTableGenerator {
val p50 = max(p10, safe01(stats[offset + 1]))
val p90 = max(p50, safe01(stats[offset + 2]))
val p98 = max(p90, safe01(stats[offset + 3]))
val p995Input = max(p98, safePositive(stats[offset + 6], p98))
val p999Input = max(p995Input, safePositive(stats[offset + 7], p995Input))
val p995 = max(p98, safePositive(stats[offset + 6], p98))
val p999 = max(p995, safePositive(stats[offset + 7], p995))
return HdrPgtmCellStats(
p10 = p10,
p50 = p50,
p90 = p90,
p98 = p98,
highlightFraction = safe01(stats[offset + 4]),
p995Input = p995Input,
p999Input = p999Input,
inputTailP95 = p995Input,
inputTailP98 = p995Input,
inputTailP99 = p999Input,
maxInput = p999Input,
sampleWeight = sampleWeight
p995Input = p995,
p999Input = p999,
inputTailP95 = p995,
inputTailP98 = p995,
inputTailP99 = p999,
maxInput = p999,
sampleWeight = sampleWeight,
)
}
@@ -230,9 +201,8 @@ internal object DngHdrProfileGainTableGenerator {
val weightSum = valid.sumOf { it.sampleWeight.toDouble() }.toFloat()
if (weightSum <= 0f) return fallbackStats()
fun weightedMean(selector: (HdrPgtmCellStats) -> Float): Float {
return valid.sumOf { (selector(it) * it.sampleWeight).toDouble() }.toFloat() / weightSum
}
fun weightedMean(selector: (HdrPgtmCellStats) -> Float): Float =
valid.sumOf { (selector(it) * it.sampleWeight).toDouble() }.toFloat() / weightSum
return HdrPgtmCellStats(
p10 = weightedMean { it.p10 },
@@ -246,36 +216,31 @@ internal object DngHdrProfileGainTableGenerator {
inputTailP98 = weightedPercentile(valid, 0.98f) { it.p995Input },
inputTailP99 = weightedPercentile(valid, 0.99f) { it.p999Input },
maxInput = valid.maxOf { it.p999Input },
sampleWeight = weightSum
sampleWeight = weightSum,
)
}
private fun fallbackStats(): HdrPgtmCellStats {
return HdrPgtmCellStats(
p10 = 0.02f,
p50 = 0.18f,
p90 = 0.55f,
p98 = 0.82f,
highlightFraction = 0f,
p995Input = 0.82f,
p999Input = 0.82f,
inputTailP95 = 0.82f,
inputTailP98 = 0.82f,
inputTailP99 = 0.82f,
maxInput = 0.82f,
sampleWeight = 1f
)
}
private fun fallbackStats() = HdrPgtmCellStats(
p10 = 0.02f,
p50 = 0.18f,
p90 = 0.55f,
p98 = 0.82f,
highlightFraction = 0f,
p995Input = 0.82f,
p999Input = 0.82f,
inputTailP95 = 0.82f,
inputTailP98 = 0.82f,
inputTailP99 = 0.82f,
maxInput = 0.82f,
sampleWeight = 1f,
)
private fun weightedPercentile(
cells: List<HdrPgtmCellStats>,
percentile: Float,
selector: (HdrPgtmCellStats) -> Float,
): Float {
val sorted = cells.mapNotNull { cell ->
selector(cell).takeIf { it.isFinite() }?.let { it to cell.sampleWeight }
}.sortedBy { it.first }
if (sorted.isEmpty()) return 0f
val sorted = cells.map { selector(it) to it.sampleWeight }.sortedBy { it.first }
val target = sorted.sumOf { it.second.toDouble() }.toFloat() * percentile.coerceIn(0f, 1f)
var accumulated = 0f
for ((value, weight) in sorted) {
@@ -285,127 +250,69 @@ internal object DngHdrProfileGainTableGenerator {
return sorted.last().first
}
/**
* Predicts the PGTM table endpoint in exposure space. BaselineExposure supplies the physical
* scale. The remaining headroom is a compact regression over the robust spatial histogram;
* coefficients were selected with leave-one-scene-out validation on the checked-in fixtures.
*
* Two continuous residual terms cover histogram topologies that the linear model cannot
* represent: a flat body with a broad long tail, and a dense mid-high body that must not be
* mistaken for additional headroom.
*/
private fun estimateInputScale(stats: HdrPgtmCellStats, baselineExposureEv: Float): Float {
val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f)
val tailP98 = max(tailP95, positiveOr(stats.inputTailP98, tailP95))
val tailP99 = max(tailP98, positiveOr(stats.inputTailP99, stats.p999Input, tailP98))
val maxInput = max(tailP99, positiveOr(stats.maxInput, tailP99))
val logTailP95 = log2(tailP95 + 0.04f)
val logMaxToP95 = log2((maxInput + 0.04f) / (tailP95 + 0.04f))
val fittedHeadroomEv =
-0.4469043f -
0.9742824f * baselineExposureEv +
3.2402040f * stats.p10 +
0.6675254f * logTailP95 +
0.9039767f * logMaxToP95
val tailStructureEv = log2((tailP99 + 0.04f) / (tailP95 + 0.04f))
val flatLongTail =
(1f - smoothStep(0.28f, 0.34f, stats.p98)) *
smoothStep(7f, 10f, tailP95) *
(1f - smoothStep(0.72f, 1.02f, tailStructureEv))
val denseMidHigh =
smoothStep(0.42f, 0.48f, stats.p50) *
(1f - smoothStep(0.70f, 0.78f, stats.p50)) *
smoothStep(0.20f, 0.28f, stats.highlightFraction)
val headroomEv = (fittedHeadroomEv + 0.50f * flatLongTail - 0.41f * denseMidHigh)
.coerceIn(-0.25f, 2.25f)
return sanitizeInputScale(2.0f.pow(headroomEv - baselineExposureEv))
}
private fun buildGlobalExposurePlan(
/** PXLs2 leave-one-scene-out fit of total headroom, without a reciprocal-baseline clamp. */
private fun estimateInputScale(
stats: HdrPgtmCellStats,
inputScale: Float,
fusionParameters: HdrExposureFusionParameters,
): HdrLtmExposurePlan {
baselineExposureEv: Float,
curveParameters: HdrPgtmCurveParameters,
): Float {
val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f)
val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95))
val tailStructureEv = log2((tailP99 + 0.04f) / (tailP95 + 0.04f))
val maxInput = max(tailP99, positiveOr(stats.maxInput, tailP99))
// This value plans the brightest member of the synthetic exposure stack. It is not a
// fitted output gain: the final curve is produced by exposure weighting and fusion below.
var brightestExposureEv = log2(
fusionParameters.autoExposureTarget / max(stats.p50, CURVE_EPS)
val totalHeadroomEv =
0.643521568f +
1.043402671f * baselineExposureEv +
0.437326319f * log2(stats.p98 + LEVEL_EPS) -
1.796161979f * sqrt(stats.highlightFraction.coerceIn(0f, 1f)) -
0.362162094f * log2(tailP95 + TAIL_EPS) -
0.431998130f * log2((tailP99 + TAIL_EPS) / (tailP95 + TAIL_EPS))
return sanitizeInputScale(
value = 2.0f.pow(totalHeadroomEv - baselineExposureEv),
curveParameters = curveParameters,
)
val sparseSeparatedTail =
(1f - smoothStep(0.21f, 0.24f, stats.p98)) *
(1f - smoothStep(1.15f, 1.45f, tailP95)) *
smoothStep(0.75f, 1.20f, tailStructureEv)
val lowKeyLongTail =
smoothStep(0.215f, 0.232f, stats.p98) *
(1f - smoothStep(0.18f, 0.205f, stats.p50)) *
smoothStep(2.8f, 4.0f, tailP95)
val denseMidHigh =
smoothStep(0.42f, 0.48f, stats.p50) *
(1f - smoothStep(0.70f, 0.78f, stats.p50)) *
smoothStep(0.20f, 0.28f, stats.highlightFraction)
val saturatedScene =
smoothStep(0.70f, 0.84f, stats.p50) *
smoothStep(0.50f, 0.70f, stats.highlightFraction)
val isolatedSdrTail =
(1f - smoothStep(0.01f, 0.03f, stats.highlightFraction)) *
(1f - smoothStep(0.70f, 0.90f, tailP95)) *
smoothStep(1.50f, 2.20f, log2((maxInput + 0.04f) / (tailP99 + 0.04f)))
val broadHighlightBody =
smoothStep(0.28f, 0.34f, stats.p98) *
smoothStep(0.08f, 0.15f, stats.highlightFraction) *
(1f - saturatedScene)
val compactHdrBody =
smoothStep(0.32f, 0.40f, stats.p98) *
(1f - smoothStep(1.40f, 1.80f, tailP95)) *
(1f - smoothStep(0.14f, 0.20f, stats.highlightFraction))
val quietLongTail =
(1f - smoothStep(0.06f, 0.09f, stats.highlightFraction)) *
smoothStep(0.18f, 0.20f, stats.p50) *
(1f - smoothStep(0.23f, 0.25f, stats.p50)) *
smoothStep(4f, 5f, tailP95)
brightestExposureEv +=
1.28f * sparseSeparatedTail -
0.85f * lowKeyLongTail -
0.37f * saturatedScene -
1.43f * isolatedSdrTail +
0.20f * broadHighlightBody +
fusionParameters.compactHdrExposureOffsetEv * compactHdrBody -
0.30f * quietLongTail -
0.03f * denseMidHigh
brightestExposureEv = brightestExposureEv.coerceIn(
log2(inputScale),
log2(fusionParameters.maxExposureGain),
)
return HdrLtmExposurePlan(
brightestExposureGain = 2.0f.pow(brightestExposureEv)
.coerceIn(inputScale, fusionParameters.maxExposureGain),
darkestExposureGain = inputScale
}
private fun buildGlobalCurvePlan(
stats: HdrPgtmCellStats,
inputScale: Float,
noiseOffset: Float,
curveParameters: HdrPgtmCurveParameters,
): HdrPgtmCurvePlan {
val tailP95 = positiveOr(stats.inputTailP95, stats.p995Input, stats.p98, 1f)
val tailP99 = max(tailP95, positiveOr(stats.inputTailP99, stats.p999Input, tailP95))
val blackGainEv =
-0.943690137f -
0.310687278f * log2(stats.p50 + LEVEL_EPS) +
2.373225506f * sqrt(stats.highlightFraction.coerceIn(0f, 1f)) -
0.058252151f * log2Noise(noiseOffset)
val shapePower =
1.033760023f +
0.029590443f * log2(tailP95 + TAIL_EPS) +
0.042870987f * log2((tailP99 + TAIL_EPS) / (tailP95 + TAIL_EPS))
return HdrPgtmCurvePlan(
// Spatial residuals are part of the fitted predictor. Apply the physical bounds only
// after those residuals are added in DngHdrLtmSpatialModel.
blackGain = 2.0f.pow(blackGainEv),
endpointGain = inputScale,
shapePower = shapePower,
)
}
private fun createMap(
plan: HdrProfileGainTablePlan,
gains: FloatArray,
): DngProfileGainTableMap {
return DngProfileGainTableMap(
mapPointsV = plan.grid.mapPointsV,
mapPointsH = plan.grid.mapPointsH,
mapSpacingV = plan.grid.mapSpacingV,
mapSpacingH = plan.grid.mapSpacingH,
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = plan.pointCount,
mapInputWeights = ltmInputWeights(plan.inputScale),
gamma = 1f,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
)
}
) = DngProfileGainTableMap(
mapPointsV = plan.grid.mapPointsV,
mapPointsH = plan.grid.mapPointsH,
mapSpacingV = plan.grid.mapSpacingV,
mapSpacingH = plan.grid.mapSpacingH,
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = plan.pointCount,
mapInputWeights = ltmInputWeights(plan.inputScale, plan.curveParameters),
gamma = 1f,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2,
)
private fun chooseLtmGrid(width: Int, height: Int): HdrPgtmGrid {
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
@@ -415,69 +322,75 @@ internal object DngHdrProfileGainTableGenerator {
return HdrPgtmGrid(
mapPointsH = mapPointsH,
mapPointsV = mapPointsV,
mapSpacingH = if (mapPointsH > 1) 1.0 / (mapPointsH - 1).toDouble() else 1.0,
mapSpacingV = if (mapPointsV > 1) 1.0 / (mapPointsV - 1).toDouble() else 1.0
mapSpacingH = if (mapPointsH > 1) 1.0 / (mapPointsH - 1) else 1.0,
mapSpacingV = if (mapPointsV > 1) 1.0 / (mapPointsV - 1) else 1.0,
)
}
private fun ltmInputWeights(inputScale: Float): FloatArray {
val scale = sanitizeInputScale(inputScale)
private fun ltmInputWeights(
inputScale: Float,
curveParameters: HdrPgtmCurveParameters,
): FloatArray {
val scale = sanitizeInputScale(inputScale, curveParameters)
return FloatArray(MAP_INPUT_WEIGHT_COUNT) { BASE_INPUT_WEIGHTS[it] * scale }
}
private fun sanitizeInputScale(inputScale: Float): Float {
return inputScale.takeIf { it.isFinite() }
?.coerceIn(1f / MAX_SCENE_WHITE, 1f)
?: 1f / MAX_SCENE_WHITE
}
private fun sanitizeInputScale(
value: Float,
curveParameters: HdrPgtmCurveParameters,
): Float = value.takeIf { it.isFinite() }?.coerceIn(
curveParameters.minInputScale,
curveParameters.maxInputScale,
) ?: curveParameters.minInputScale
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
val t = ((value - edge0) / max(edge1 - edge0, CURVE_EPS)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
private fun log2(value: Float): Float =
(ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat()
private fun log2(value: Float): Float {
return (ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat()
}
private fun safe01(value: Float): Float {
return value.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f
}
private fun safePositive(value: Float, fallback: Float): Float {
return value.takeIf { it.isFinite() && it > 0f } ?: fallback
}
private fun positiveOr(vararg values: Float): Float {
return values.firstOrNull { it.isFinite() && it > 0f } ?: 1f
}
private fun log2Noise(value: Float): Float =
(ln(max(value, 1e-12f).toDouble()) / ln(2.0)).toFloat()
private fun safe01(value: Float) = value.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f
private fun safePositive(value: Float, fallback: Float) =
value.takeIf { it.isFinite() && it > 0f } ?: fallback
private fun positiveOr(vararg values: Float) =
values.firstOrNull { it.isFinite() && it > 0f } ?: 1f
}
internal data class HdrProfileGainTablePlan(
val grid: HdrPgtmGrid,
val pointCount: Int,
val inputScale: Float,
val cellPlans: Array<HdrLtmExposurePlan>,
val curveParameters: HdrPgtmCurveParameters,
val cellPlans: Array<HdrPgtmCurvePlan>,
val diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
val fusionParameters: HdrExposureFusionParameters,
)
internal data class HdrExposureFusionParameters(
val autoExposureTarget: Float,
val wellExposedKey: Float,
val maxExposureGain: Float,
val compactHdrExposureOffsetEv: Float = -0.40f,
val highlightFusionStart: Float = 0.45f,
val highlightFusionEnd: Float = 0.65f,
internal data class HdrPgtmCurveParameters(
val minTableGain: Float,
val maxTableGain: Float,
val minBlackGain: Float,
val toeEnd: Float,
val shapeQ: Float,
val minShapePower: Float,
val maxShapePower: Float,
val minInputScale: Float,
val maxInputScale: Float,
) {
init {
require(autoExposureTarget.isFinite() && autoExposureTarget > 0f)
require(wellExposedKey.isFinite() && wellExposedKey > 0f)
require(maxExposureGain.isFinite() && maxExposureGain >= 1f)
require(compactHdrExposureOffsetEv.isFinite())
require(highlightFusionStart.isFinite() && highlightFusionStart in 0f..1f)
require(highlightFusionEnd.isFinite() && highlightFusionEnd in 0f..1f)
require(highlightFusionEnd > highlightFusionStart)
require(minTableGain.isFinite() && minTableGain > 0f)
require(maxTableGain.isFinite() && maxTableGain >= minTableGain)
require(minBlackGain.isFinite() && minBlackGain in minTableGain..maxTableGain)
require(toeEnd.isFinite() && toeEnd >= 0f && toeEnd < 1f)
require(shapeQ.isFinite() && shapeQ > 0f)
require(minShapePower.isFinite() && minShapePower > 0f)
require(maxShapePower.isFinite() && maxShapePower >= minShapePower)
require(minInputScale.isFinite() && minInputScale > 0f)
require(maxInputScale.isFinite() && maxInputScale >= minInputScale)
}
}
internal data class HdrPgtmCurvePlan(
val blackGain: Float,
val endpointGain: Float,
val shapePower: Float,
)
@@ -240,54 +240,33 @@ internal object DngHdrProfileGainTableGpuShaders {
precision highp float;
precision highp int;
layout(std430, binding = 0) readonly buffer ExposurePlanBuffer {
float exposurePlans[];
layout(std430, binding = 0) readonly buffer CurvePlanBuffer {
float curvePlans[];
};
layout(std430, binding = 1) writeonly buffer GainCurveBuffer {
float gainCurves[];
};
layout(std430, binding = 2) readonly buffer WeightLutBuffer {
float weightLut[];
};
uniform int uCellCount;
uniform int uPointCount;
uniform float uInputScale;
uniform float uWellExposedKey;
uniform float uMaxExposureGain;
uniform float uHighlightFusionStart;
uniform float uHighlightFusionEnd;
uniform float uMinTableGain;
uniform float uMaxTableGain;
uniform float uToeEnd;
uniform float uShapeQ;
uniform float uMinShapePower;
uniform float uMaxShapePower;
uniform int uDiagnosticMode;
uniform float uDiagnosticStart;
uniform float uDiagnosticEnd;
uniform float uDiagnosticFeather;
const float MIN_TABLE_GAIN = 0.05;
const float CURVE_EPS = 1e-6;
const float EXPOSURE_STEPS_PER_EV = 128.0;
const float WEIGHT_STEPS_PER_EV = 256.0;
const float WEIGHT_MAX_DISTANCE_EV = 12.0;
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 quantizedExposureGain(float gain) {
float key = floor(log2(max(gain, CURVE_EPS)) * EXPOSURE_STEPS_PER_EV + 0.5);
return exp2(key / EXPOSURE_STEPS_PER_EV);
}
float sampledWeight(float distanceEv, int component) {
float scaled = abs(distanceEv) * WEIGHT_STEPS_PER_EV;
if (scaled >= WEIGHT_MAX_DISTANCE_EV * WEIGHT_STEPS_PER_EV) return 0.0;
int index = int(floor(scaled));
float fraction = scaled - float(index);
float first = weightLut[index * 2 + component];
float second = weightLut[(index + 1) * 2 + component];
return mix(first, second, fraction);
}
float diagnosticMask(float inputValue) {
float enter = uDiagnosticStart <= 0.0 || uDiagnosticFeather <= 0.0
? (inputValue >= uDiagnosticStart ? 1.0 : 0.0)
@@ -310,81 +289,36 @@ internal object DngHdrProfileGainTableGpuShaders {
int cellIndex = int(gl_GlobalInvocationID.x);
if (cellIndex >= uCellCount) return;
// Some GLES drivers preserve the SSBO member's readonly qualifier when it is used
// directly as a function argument. Copy to ordinary locals before quantization.
float brightestPlanGain = exposurePlans[cellIndex * 2];
float darkestPlanGain = exposurePlans[cellIndex * 2 + 1];
float brightestGain = clamp(
quantizedExposureGain(brightestPlanGain),
uInputScale,
uMaxExposureGain
int planOffset = cellIndex * 3;
float blackGain = clamp(
curvePlans[planOffset], uMinTableGain, uMaxTableGain
);
float darkestGain = clamp(
quantizedExposureGain(darkestPlanGain),
uInputScale,
brightestGain
float endpointGain = clamp(
curvePlans[planOffset + 1], uMinTableGain, uMaxTableGain
);
float exposureGains[8];
float exposureGainEvs[8];
for (int exposure = 0; exposure < 8; ++exposure) {
float amount = float(exposure) / 7.0;
exposureGains[exposure] = exp2(mix(
log2(brightestGain),
log2(darkestGain),
amount
));
exposureGainEvs[exposure] = log2(exposureGains[exposure]);
}
float previousTrueOutput = 0.0;
float shapePower = clamp(
curvePlans[planOffset + 2], uMinShapePower, uMaxShapePower
);
float endpointRatio = blackGain / max(endpointGain, CURVE_EPS);
float shoulderAmount = pow(endpointRatio, uShapeQ) - 1.0;
float previousFinalOutput = 0.0;
int outputOffset = cellIndex * uPointCount;
for (int point = 0; point < uPointCount; ++point) {
float tableInput = point == uPointCount - 1
? 1.0
: float(point) / float(uPointCount);
float trueGain;
if (tableInput <= CURVE_EPS) {
trueGain = brightestGain;
} else {
float sceneInput = tableInput / uInputScale;
float sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / uWellExposedKey);
float highlightStrength = smoothUnit(
uHighlightFusionStart,
uHighlightFusionEnd,
sceneInput * exposureGains[7]
);
float weightSum = 0.0;
float outputSum = 0.0;
float nearestDistanceEv = 3.402823466e+38;
float nearestOutput = 0.0;
for (int exposure = 0; exposure < 8; ++exposure) {
float exposed = max(sceneInput * exposureGains[exposure], CURVE_EPS);
float distanceEv = sceneFromKeyEv + exposureGainEvs[exposure];
float weight = mix(
sampledWeight(distanceEv, 0),
sampledWeight(distanceEv, 1),
highlightStrength
);
float clippedOutput = min(exposed, 1.0);
weightSum += weight;
outputSum += weight * clippedOutput;
if (abs(distanceEv) < nearestDistanceEv) {
nearestDistanceEv = abs(distanceEv);
nearestOutput = clippedOutput;
}
}
float fusedOutput = weightSum <= 0.0
? nearestOutput
: clamp(outputSum / weightSum, 0.0, 1.0);
float monotonicOutput = max(previousTrueOutput, fusedOutput);
trueGain = clamp(
monotonicOutput / sceneInput,
MIN_TABLE_GAIN,
uMaxExposureGain
);
previousTrueOutput = monotonicOutput;
}
float shoulderInput = clamp(
(tableInput - uToeEnd) / max(1.0 - uToeEnd, CURVE_EPS),
0.0,
1.0
);
float denominator = pow(
max(1.0 + shoulderAmount * pow(shoulderInput, shapePower), CURVE_EPS),
1.0 / uShapeQ
);
float trueGain = point == uPointCount - 1
? uInputScale
: clamp(blackGain / denominator, uMinTableGain, uMaxTableGain);
float finalGain = trueGain;
if (uDiagnosticMode >= 0) {
@@ -394,11 +328,11 @@ internal object DngHdrProfileGainTableGpuShaders {
: mix(trueGain, 1.0, mask);
float monotonicOutput = max(previousFinalOutput, tableInput * mixedGain);
finalGain = tableInput <= CURVE_EPS
? clamp(mixedGain, MIN_TABLE_GAIN, uMaxExposureGain)
? clamp(mixedGain, uMinTableGain, uMaxTableGain)
: clamp(
monotonicOutput / tableInput,
MIN_TABLE_GAIN,
uMaxExposureGain
uMinTableGain,
uMaxTableGain
);
previousFinalOutput = monotonicOutput;
}
@@ -277,7 +277,6 @@ class RawDemosaicProcessor {
private var quadWriteOutputProgram = 0
private var pgtmCellStatsProgram = 0
private var pgtmGainCurvesProgram = 0
private var pgtmWeightLutBufferId = 0
private var linearRcdProgram = 0
private var warpRectilinearProgram = 0
private var linearRawRgbProgram = 0
@@ -2118,20 +2117,17 @@ class RawDemosaicProcessor {
)
return null
}
if (pgtmCellStatsProgram == 0 ||
pgtmGainCurvesProgram == 0 ||
pgtmWeightLutBufferId == 0
) {
if (pgtmCellStatsProgram == 0 || pgtmGainCurvesProgram == 0) {
PLog.e(
TAG,
"GPU RAW PGTM programs unavailable: stats=$pgtmCellStatsProgram " +
"curves=$pgtmGainCurvesProgram weights=$pgtmWeightLutBufferId",
"curves=$pgtmGainCurvesProgram",
)
return null
}
val fusionParameters = when (profileToneMapMode) {
RawProfileToneMapMode.Photon -> DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS
RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS
val curveParameters = when (profileToneMapMode) {
RawProfileToneMapMode.Photon -> DngHdrProfileGainTableGenerator.PHOTON_CURVE_PARAMETERS
RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.GOOGLE_CURVE_PARAMETERS
else -> return null
}
val safeStatsBounds = sanitizePgtmStatsBounds(statsBounds, width, height) ?: run {
@@ -2272,8 +2268,10 @@ class RawDemosaicProcessor {
height = height,
baselineExposureEv = baselineExposureEv,
packedCellStats = packedCellStats,
noiseSlope = metadata.noiseProfile.getOrElse(0) { 0f },
noiseOffset = metadata.noiseProfile.getOrElse(1) { 0f },
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU capture"),
fusionParameters = fusionParameters,
curveParameters = curveParameters,
) ?: return null
val planReadyNs = System.nanoTime()
if (plan.cellPlans.size != cellCount) {
@@ -2284,20 +2282,21 @@ class RawDemosaicProcessor {
return null
}
val exposurePlanBuffer = ByteBuffer.allocateDirect(cellCount * 2 * Float.SIZE_BYTES)
val curvePlanBuffer = ByteBuffer.allocateDirect(cellCount * 3 * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
plan.cellPlans.forEach { cellPlan ->
exposurePlanBuffer.put(cellPlan.brightestExposureGain)
exposurePlanBuffer.put(cellPlan.darkestExposureGain)
curvePlanBuffer.put(cellPlan.blackGain)
curvePlanBuffer.put(cellPlan.endpointGain)
curvePlanBuffer.put(cellPlan.shapePower)
}
exposurePlanBuffer.position(0)
curvePlanBuffer.position(0)
val planBufferId = bufferIds[1]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, planBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
cellCount * 2 * Float.SIZE_BYTES,
exposurePlanBuffer,
cellCount * 3 * Float.SIZE_BYTES,
curvePlanBuffer,
GLES31.GL_STATIC_DRAW,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, planBufferId)
@@ -2312,12 +2311,6 @@ class RawDemosaicProcessor {
GLES31.GL_DYNAMIC_READ,
)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, gainBufferId)
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
2,
pgtmWeightLutBufferId,
)
GLES31.glUseProgram(pgtmGainCurvesProgram)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uCellCount"),
@@ -2332,20 +2325,28 @@ class RawDemosaicProcessor {
plan.inputScale,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uWellExposedKey"),
plan.fusionParameters.wellExposedKey,
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMinTableGain"),
plan.curveParameters.minTableGain,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxExposureGain"),
plan.fusionParameters.maxExposureGain,
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxTableGain"),
plan.curveParameters.maxTableGain,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uHighlightFusionStart"),
plan.fusionParameters.highlightFusionStart,
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uToeEnd"),
plan.curveParameters.toeEnd,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uHighlightFusionEnd"),
plan.fusionParameters.highlightFusionEnd,
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uShapeQ"),
plan.curveParameters.shapeQ,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMinShapePower"),
plan.curveParameters.minShapePower,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxShapePower"),
plan.curveParameters.maxShapePower,
)
val diagnosticMode = when (plan.diagnosticBand?.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
@@ -3406,7 +3407,6 @@ class RawDemosaicProcessor {
"DNG_PGTM_GAIN_CURVES",
)
if (pgtmCellStatsProgram != 0 && pgtmGainCurvesProgram != 0) {
initPgtmWeightLutBuffer()
}
val fShaderLinearRcd = compileShader(
@@ -3452,28 +3452,6 @@ class RawDemosaicProcessor {
)
}
private fun initPgtmWeightLutBuffer() {
if (pgtmWeightLutBufferId != 0) return
val weights = DngHdrProfileGainTableGenerator.interleavedWellExposedWeightLut()
val buffer = ByteBuffer.allocateDirect(weights.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
buffer.put(weights)
buffer.position(0)
val ids = IntArray(1)
GLES31.glGenBuffers(1, ids, 0)
pgtmWeightLutBufferId = ids[0]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, pgtmWeightLutBufferId)
GLES31.glBufferData(
GLES31.GL_SHADER_STORAGE_BUFFER,
weights.size * Float.SIZE_BYTES,
buffer,
GLES31.GL_STATIC_DRAW,
)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
checkGlError("initPgtmWeightLutBuffer")
}
private fun linkFragmentProgram(
vShader: Int,
fragmentSource: String,
@@ -8858,10 +8836,6 @@ class RawDemosaicProcessor {
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
if (pgtmCellStatsProgram != 0) GLES31.glDeleteProgram(pgtmCellStatsProgram)
if (pgtmGainCurvesProgram != 0) GLES31.glDeleteProgram(pgtmGainCurvesProgram)
if (pgtmWeightLutBufferId != 0) {
GLES31.glDeleteBuffers(1, intArrayOf(pgtmWeightLutBufferId), 0)
pgtmWeightLutBufferId = 0
}
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
if (warpRectilinearProgram != 0) GLES31.glDeleteProgram(warpRectilinearProgram)
if (linearRawRgbProgram != 0) GLES31.glDeleteProgram(linearRawRgbProgram)
@@ -119,7 +119,8 @@ internal object RawViewfinderExposureMatcher {
"matchLog2Error=${match.matchLog2Error} " +
"medianLog2Error=${match.medianLog2Error} " +
"trimmedMeanLog2Error=${match.trimmedMeanLog2Error} " +
"sampleCount=${match.sampleCount}"
"sampleCount=${match.sampleCount} " +
"perceptualWeightSum=${match.perceptualWeightSum}"
)
return match.matchLog2Error
}
@@ -10,7 +10,9 @@ import kotlin.math.pow
* Both inputs are tone-mapped 8-bit sRGB previews. Converting their surviving code values back
* to display-linear light does not recover scene-linear RAW data; it only makes the logarithmic
* ratio describe a ratio of displayed light. Reference pixels clipped near black or white are
* excluded once and the same fixed sample set is used for every rendered candidate.
* excluded once and the same fixed sample set is used for every rendered candidate. Errors are
* weighted by the reference pixel's perceptual brightness so large dark regions cannot dominate
* a high-contrast scene merely because the logarithmic domain expands their residuals.
*/
internal object RawViewfinderExposureMath {
private const val DISPLAY_LINEAR_LUMA_FLOOR = 0.001f
@@ -37,9 +39,12 @@ internal object RawViewfinderExposureMath {
val height: Int,
val pixelIndices: IntArray,
val targetLog2DisplayLinearLumas: FloatArray,
val perceptualWeights: FloatArray,
) {
init {
require(pixelIndices.size == targetLog2DisplayLinearLumas.size)
require(pixelIndices.size == perceptualWeights.size)
require(perceptualWeights.all { it.isFinite() && it > 0f })
}
val sampleCount: Int
@@ -51,6 +56,7 @@ internal object RawViewfinderExposureMath {
val medianLog2Error: Float,
val trimmedMeanLog2Error: Float,
val sampleCount: Int,
val perceptualWeightSum: Float,
)
private data class SolverSample(
@@ -77,6 +83,7 @@ internal object RawViewfinderExposureMath {
val capacity = (safeRight - safeLeft) * (safeBottom - safeTop)
val pixelIndices = IntArray(capacity)
val targetLogLumas = FloatArray(capacity)
val perceptualWeights = FloatArray(capacity)
var sampleCount = 0
for (y in safeTop until safeBottom) {
for (x in safeLeft until safeRight) {
@@ -89,6 +96,7 @@ internal object RawViewfinderExposureMath {
}
pixelIndices[sampleCount] = pixelIndex
targetLogLumas[sampleCount] = log2(targetLuma)
perceptualWeights[sampleCount] = linearToSrgb(targetLuma)
sampleCount++
}
}
@@ -98,6 +106,7 @@ internal object RawViewfinderExposureMath {
height = height,
pixelIndices = pixelIndices.copyOf(sampleCount),
targetLog2DisplayLinearLumas = targetLogLumas.copyOf(sampleCount),
perceptualWeights = perceptualWeights.copyOf(sampleCount),
)
}
@@ -116,6 +125,7 @@ internal object RawViewfinderExposureMath {
}
val log2Errors = FloatArray(reference.sampleCount)
val perceptualWeights = reference.perceptualWeights.copyOf()
for (sampleIndex in reference.pixelIndices.indices) {
val pixelIndex = reference.pixelIndices[sampleIndex]
val renderedLuma = displayLinearLuma(pixels[pixelIndex])
@@ -124,11 +134,16 @@ internal object RawViewfinderExposureMath {
log2Errors[sampleIndex] =
log2(renderedLuma) - reference.targetLog2DisplayLinearLumas[sampleIndex]
}
log2Errors.sort()
sortPairsByFirst(log2Errors, perceptualWeights)
val median = median(log2Errors)
val trimmedMean = trimmedMean(
var weightSum = 0.0
for (weight in perceptualWeights) weightSum += weight.toDouble()
if (!weightSum.isFinite() || weightSum <= 0.0) return null
val median = weightedMedian(log2Errors, perceptualWeights, weightSum)
val trimmedMean = weightedTrimmedMean(
sortedValues = log2Errors,
sortedWeights = perceptualWeights,
weightSum = weightSum,
lowFraction = TRIM_LOW_FRACTION,
highFraction = TRIM_HIGH_FRACTION,
)
@@ -139,6 +154,7 @@ internal object RawViewfinderExposureMath {
medianLog2Error = median,
trimmedMeanLog2Error = trimmedMean,
sampleCount = reference.sampleCount,
perceptualWeightSum = weightSum.toFloat(),
)
}
@@ -257,28 +273,100 @@ internal object RawViewfinderExposureMath {
}
}
private fun median(sortedValues: FloatArray): Float {
val middle = sortedValues.size / 2
return if (sortedValues.size % 2 == 0) {
(sortedValues[middle - 1] + sortedValues[middle]) * 0.5f
} else {
sortedValues[middle]
private fun weightedMedian(
sortedValues: FloatArray,
sortedWeights: FloatArray,
weightSum: Double,
): Float {
val targetWeight = weightSum * 0.5
val boundaryTolerance = maxOf(1e-12, weightSum * 1e-9)
var cumulativeWeight = 0.0
for (index in sortedValues.indices) {
cumulativeWeight += sortedWeights[index].toDouble()
if (cumulativeWeight < targetWeight - boundaryTolerance) continue
return if (kotlin.math.abs(cumulativeWeight - targetWeight) <= boundaryTolerance &&
index < sortedValues.lastIndex
) {
(sortedValues[index] + sortedValues[index + 1]) * 0.5f
} else {
sortedValues[index]
}
}
return sortedValues.last()
}
private fun trimmedMean(
private fun weightedTrimmedMean(
sortedValues: FloatArray,
sortedWeights: FloatArray,
weightSum: Double,
lowFraction: Float,
highFraction: Float,
): Float {
val start = (sortedValues.size * lowFraction.coerceIn(0f, 1f)).toInt()
val endExclusive = (sortedValues.size * highFraction.coerceIn(0f, 1f)).toInt()
.coerceIn(start + 1, sortedValues.size)
var sum = 0.0
for (index in start until endExclusive) {
sum += sortedValues[index].toDouble()
val startWeight = weightSum * lowFraction.coerceIn(0f, 1f).toDouble()
val endWeight = weightSum * highFraction.coerceIn(0f, 1f).toDouble()
.coerceAtLeast(startWeight)
var cumulativeWeight = 0.0
var includedWeight = 0.0
var weightedSum = 0.0
for (index in sortedValues.indices) {
val nextCumulativeWeight = cumulativeWeight + sortedWeights[index].toDouble()
val overlapStart = maxOf(cumulativeWeight, startWeight)
val overlapEnd = minOf(nextCumulativeWeight, endWeight)
val overlapWeight = (overlapEnd - overlapStart).coerceAtLeast(0.0)
if (overlapWeight > 0.0) {
includedWeight += overlapWeight
weightedSum += sortedValues[index].toDouble() * overlapWeight
}
cumulativeWeight = nextCumulativeWeight
if (cumulativeWeight >= endWeight) break
}
return if (includedWeight > 0.0) {
(weightedSum / includedWeight).toFloat()
} else {
weightedMedian(sortedValues, sortedWeights, weightSum)
}
}
private fun sortPairsByFirst(values: FloatArray, weights: FloatArray) {
require(values.size == weights.size)
if (values.size < 2) return
quickSortPairs(values, weights, 0, values.lastIndex)
}
private fun quickSortPairs(
values: FloatArray,
weights: FloatArray,
left: Int,
right: Int,
) {
var low = left
var high = right
val pivot = values[(left + right) ushr 1]
while (low <= high) {
while (values[low] < pivot) low++
while (values[high] > pivot) high--
if (low <= high) {
val value = values[low]
values[low] = values[high]
values[high] = value
val weight = weights[low]
weights[low] = weights[high]
weights[high] = weight
low++
high--
}
}
if (left < high) quickSortPairs(values, weights, left, high)
if (low < right) quickSortPairs(values, weights, low, right)
}
private fun linearToSrgb(value: Float): Float {
val clamped = value.coerceIn(0f, 1f)
return if (clamped <= 0.0031308f) {
clamped * SRGB_LINEAR_SCALE
} else {
(1f + SRGB_TRANSFER_A) * clamped.pow(1f / SRGB_TRANSFER_GAMMA) - SRGB_TRANSFER_A
}
return (sum / (endExclusive - start)).toFloat()
}
private fun log2(value: Float): Float {
@@ -1,150 +1,55 @@
package com.hinnka.mycamera.raw
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
/** Deterministic JVM mirror of [DngHdrProfileGainTableGpuShaders.GAIN_CURVES]. */
/** Float CPU mirror of the production PGTM curve shader. */
internal object DngHdrProfileGainTableCpuReference {
private const val SYNTHETIC_EXPOSURE_COUNT = 8
private const val MIN_TABLE_GAIN = 0.05f
private const val CURVE_EPS = 1e-6f
private const val EXPOSURE_STEPS_PER_EV = 128f
private const val WEIGHT_STEPS_PER_EV = 256f
private const val WEIGHT_MAX_DISTANCE_EV = 12f
fun generate(plan: HdrProfileGainTablePlan): FloatArray {
val cellCount = plan.grid.mapPointsH * plan.grid.mapPointsV
val output = FloatArray(cellCount * plan.pointCount)
val weightLut = DngHdrProfileGainTableGenerator.interleavedWellExposedWeightLut()
val curveCache = HashMap<Long, FloatArray>()
val result = FloatArray(plan.cellPlans.size * plan.pointCount)
val curveParameters = plan.curveParameters
plan.cellPlans.forEachIndexed { cell, cellPlan ->
val brightestKey = quantizedExposureKey(cellPlan.brightestExposureGain)
val darkestKey = quantizedExposureKey(cellPlan.darkestExposureGain)
val cacheKey = (brightestKey.toLong() shl 32) xor
(darkestKey.toLong() and 0xffffffffL)
val curve = curveCache.getOrPut(cacheKey) {
generateCurve(plan, cellPlan, weightLut)
}
curve.copyInto(output, destinationOffset = cell * plan.pointCount)
}
return output
}
private fun generateCurve(
plan: HdrProfileGainTablePlan,
cellPlan: HdrLtmExposurePlan,
weightLut: FloatArray,
): FloatArray {
val brightestGain = quantizedExposureGain(cellPlan.brightestExposureGain)
.coerceIn(plan.inputScale, plan.fusionParameters.maxExposureGain)
val darkestGain = quantizedExposureGain(cellPlan.darkestExposureGain)
.coerceIn(plan.inputScale, brightestGain)
val brightestEv = log2(brightestGain)
val darkestEv = log2(darkestGain)
val exposureGains = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
2.0f.pow(lerp(brightestEv, darkestEv, amount))
}
val exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
log2(exposureGains[exposure])
}
var previousTrueOutput = 0f
var previousFinalOutput = 0f
return FloatArray(plan.pointCount) { point ->
val tableInput = if (point == plan.pointCount - 1) {
1f
} else {
point.toFloat() / plan.pointCount.toFloat()
}
val trueGain = if (tableInput <= CURVE_EPS) {
brightestGain
} else {
val sceneInput = tableInput / plan.inputScale
val sceneFromKeyEv = log2(
max(sceneInput, CURVE_EPS) / plan.fusionParameters.wellExposedKey
)
val highlightStrength = smoothStep(
plan.fusionParameters.highlightFusionStart,
plan.fusionParameters.highlightFusionEnd,
sceneInput * exposureGains.last(),
)
var weightSum = 0f
var outputSum = 0f
var nearestDistanceEv = Float.MAX_VALUE
var nearestOutput = 0f
exposureGains.indices.forEach { exposure ->
val exposed = max(sceneInput * exposureGains[exposure], CURVE_EPS)
val distanceEv = sceneFromKeyEv + exposureGainEvs[exposure]
val weight = lerp(
sampledWeight(distanceEv, component = 0, weightLut),
sampledWeight(distanceEv, component = 1, weightLut),
highlightStrength,
)
val clippedOutput = min(exposed, 1f)
weightSum += weight
outputSum += weight * clippedOutput
if (abs(distanceEv) < nearestDistanceEv) {
nearestDistanceEv = abs(distanceEv)
nearestOutput = clippedOutput
}
}
val fusedOutput = if (weightSum <= 0f) {
nearestOutput
val ratio = cellPlan.blackGain / max(cellPlan.endpointGain, 1e-6f)
val shoulderAmount = ratio.pow(curveParameters.shapeQ) - 1f
var previousFinalOutput = 0f
repeat(plan.pointCount) { point ->
val tableInput = tableInput(point, plan.pointCount)
val shoulderInput = (
(tableInput - curveParameters.toeEnd) /
(1f - curveParameters.toeEnd)
).coerceIn(0f, 1f)
val denominator = max(
1f + shoulderAmount * shoulderInput.pow(cellPlan.shapePower),
1e-6f,
).pow(1f / curveParameters.shapeQ)
val trueGain = if (point == plan.pointCount - 1) {
plan.inputScale
} else {
(outputSum / weightSum).coerceIn(0f, 1f)
}
val monotonicOutput = max(previousTrueOutput, fusedOutput)
previousTrueOutput = monotonicOutput
(monotonicOutput / sceneInput).coerceIn(
MIN_TABLE_GAIN,
plan.fusionParameters.maxExposureGain,
)
}
val band = plan.diagnosticBand
if (band == null) {
trueGain
} else {
val mask = diagnosticMask(tableInput, band)
val mixedGain = when (band.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> {
lerp(1f, trueGain, mask)
}
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> {
lerp(trueGain, 1f, mask)
}
}
val monotonicOutput = max(previousFinalOutput, tableInput * mixedGain)
previousFinalOutput = monotonicOutput
if (tableInput <= CURVE_EPS) {
mixedGain.coerceIn(MIN_TABLE_GAIN, plan.fusionParameters.maxExposureGain)
} else {
(monotonicOutput / tableInput).coerceIn(
MIN_TABLE_GAIN,
plan.fusionParameters.maxExposureGain,
(cellPlan.blackGain / denominator).coerceIn(
curveParameters.minTableGain,
curveParameters.maxTableGain,
)
}
val finalGain = plan.diagnosticBand?.let { band ->
val mask = diagnosticMask(tableInput, band)
val mixed = when (band.mode) {
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
lerp(1f, trueGain, mask)
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
lerp(trueGain, 1f, mask)
}
val output = max(previousFinalOutput, tableInput * mixed)
previousFinalOutput = output
if (tableInput <= 1e-6f) mixed else output / tableInput
} ?: trueGain
result[cell * plan.pointCount + point] = finalGain
}
}
return result
}
private fun sampledWeight(
distanceEv: Float,
component: Int,
weightLut: FloatArray,
): Float {
val scaled = abs(distanceEv) * WEIGHT_STEPS_PER_EV
if (scaled >= WEIGHT_MAX_DISTANCE_EV * WEIGHT_STEPS_PER_EV) return 0f
val index = floor(scaled).toInt()
val fraction = scaled - index.toFloat()
val first = weightLut[index * 2 + component]
val second = weightLut[(index + 1) * 2 + component]
return lerp(first, second, fraction)
}
private fun tableInput(point: Int, count: Int): Float =
if (point == count - 1) 1f else point.toFloat() / count.toFloat()
private fun diagnosticMask(
input: Float,
@@ -160,27 +65,14 @@ internal object DngHdrProfileGainTableCpuReference {
} else {
1f - smoothStep(band.end - band.feather, band.end + band.feather, input)
}
return min(enter, exit).coerceIn(0f, 1f)
}
private fun quantizedExposureKey(gain: Float): Int {
return floor(log2(max(gain, CURVE_EPS)) * EXPOSURE_STEPS_PER_EV + 0.5f).toInt()
}
private fun quantizedExposureGain(gain: Float): Float {
return 2.0f.pow(quantizedExposureKey(gain).toFloat() / EXPOSURE_STEPS_PER_EV)
return minOf(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)
val t = ((value - edge0) / max(edge1 - edge0, 1e-6f)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
private fun lerp(first: Float, second: Float, amount: Float): Float {
return first + (second - first) * amount
}
private fun log2(value: Float): Float {
return (ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat()
}
private fun lerp(start: Float, end: Float, amount: Float) =
start + (end - start) * amount
}
@@ -1,505 +1,242 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.floor
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.sqrt
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DngHdrProfileGainTableGeneratorTest {
@Test
fun bimodalPhotonCaptureKeepsAUsableBrightSyntheticExposure() {
val fixture = loadFixture(BIMODAL_CAPTURE_RESOURCE)
val map = generateMap(
fixture = fixture,
fusionParameters = DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS,
)
val blackGains = actualAnchorGains(fixture, map, ToneAnchor.BLACK)
val medianGains = actualAnchorGains(fixture, map, ToneAnchor.MEDIAN)
val medianOutputs = FloatArray(fixture.cellCount) { cell ->
val p50 = sceneSignalForAnchor(
fixture = fixture,
cell = cell,
anchor = ToneAnchor.MEDIAN,
inputScale = map.mapInputWeights.sum()
)
p50 * medianGains[cell]
}
val blackGainMedian = percentile(blackGains, 0.50f)
val medianOutputMean = medianOutputs.average().toFloat()
assertTrue(
"inputScale=${map.mapInputWeights.sum()}",
map.mapInputWeights.sum() in 0.095f..0.120f
)
assertTrue("blackGainMedian=$blackGainMedian", blackGainMedian > 1.0f)
assertTrue(
"medianOutputMean=$medianOutputMean blackGainMedian=$blackGainMedian",
medianOutputMean > 0.18f
)
fun corpusContainsOnlyTheCompletePxls2TrainingSet() {
val fixtures = fixtures()
assertEquals(27, fixtures.size)
assertTrue(fixtures.all { it.sourceName.startsWith("PXL_202607") })
assertTrue(fixtures.all { it.tableInputs.size == 33 })
assertTrue(fixtures.all { it.noiseSlope > 0f && it.noiseOffset > 0f })
assertTrue(fixtures.none { it.sourceName.contains("pxls/", ignoreCase = true) })
}
@Test
fun skyykingFixturesCoverRealBlackMedianHighlightAndWhiteCases() {
val fixtures = loadFixtures()
assertEquals(12, fixtures.size)
val inputScales = fixtures.map { it.inputScale }
val globalMedians = fixtures.map { fixture ->
percentile(cellStats(fixture, STAT_P50), 0.50f)
}
val blackGains = fixtures.flatMap { fixture ->
anchorGains(fixture.expectedGains, fixture.cellCount, ToneAnchor.BLACK).asIterable()
}
assertTrue("inputScales=$inputScales", inputScales.min() < 0.07f)
assertTrue("inputScales=$inputScales", inputScales.max() > 0.33f)
assertTrue("globalMedians=$globalMedians", globalMedians.min() < 0.10f)
assertTrue("globalMedians=$globalMedians", globalMedians.max() > 0.80f)
assertTrue("blackGainMin=${blackGains.min()}", blackGains.min() < 0.30f)
assertTrue("blackGainMax=${blackGains.max()}", blackGains.max() > 4.50f)
fixtures.forEach { fixture ->
assertEquals(64, fixture.mapPointsH)
assertEquals(48, fixture.mapPointsV)
assertEquals(ToneAnchor.entries.size, fixture.anchorCount)
assertEquals(fixture.cellCount * CELL_STATS_STRIDE, fixture.packedStats.size)
assertEquals(fixture.cellCount * fixture.anchorCount, fixture.expectedGains.size)
assertEquals(1f, fixture.gamma, 0f)
assertOfficialInputWeights(fixture.inputWeights, fixture.sourceName)
assertEmbeddedSemanticOutputsMonotonic(fixture)
}
}
@Test
fun official184953TrustedHighlightTailStaysNearWhite() {
val fixture = loadFixture(
"/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture"
)
val map = generateMap(fixture)
val expectedSpecular = anchorGains(
source = fixture.expectedGains,
cellCount = fixture.cellCount,
anchor = ToneAnchor.SPECULAR
)
val actualSpecular = actualAnchorGains(fixture, map, ToneAnchor.SPECULAR)
val trustedShoulderCells = actualSpecular.indices.filter { cell ->
fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999] in 2f..3f
}
assertTrue("Expected trusted shoulder cells", trustedShoulderCells.isNotEmpty())
trustedShoulderCells.forEach { cell ->
val p999 = fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999]
val expectedOutput = p999 * expectedSpecular[cell]
val actualOutput = p999 * actualSpecular[cell]
assertTrue(
"cell=$cell p999=$p999 expectedOutput=$expectedOutput actualOutput=$actualOutput",
actualOutput + 0.025f >= expectedOutput
)
}
}
@Test
fun fixedFusionPreservesOfficialShouldersAcrossSkyykingSet() {
val fixturesByName = loadFixtures().associateBy { it.sourceName }
val results = denseShoulderCases().flatMap { case ->
val fixture = fixturesByName[case.name] ?: error("Missing fixture ${case.name}")
val map = DngHdrProfileGainTableGenerator.forCellStats(
width = fixture.width,
height = fixture.height,
baselineExposureEv = fixture.baselineExposureEv,
packedCellStats = fixture.packedStats,
fusionParameters = DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS,
) ?: error("Expected Google PGTM for ${case.name}")
listOf(0.25f, 0.50f, 0.75f).mapIndexed { index, tableInput ->
val actual = percentile(
FloatArray(fixture.cellCount) { cell -> sampleGain(map, tableInput, cell) },
0.50f,
)
DenseShoulderResult(
name = case.name,
tableInput = tableInput,
expectedGain = case.officialMedianGains[index],
actualGain = actual,
errorEv = abs(log2(actual / case.officialMedianGains[index])),
)
}
}
assertTrue(
results.joinToString("\n") { result ->
"${result.name} t=${result.tableInput} expected=${result.expectedGain} " +
"actual=${result.actualGain} errorEv=${result.errorEv}"
},
results.all { it.errorEv <= 0.38f },
)
}
@Test
fun generatedMapsMatchEmbeddedSemanticToneDistributions() {
val failures = mutableListOf<String>()
loadFixtures().forEach { fixture ->
val map = generateMap(fixture)
assertTrue("${fixture.sourceName} invalid map", map.isValid)
assertMapOutputsMonotonic(map, fixture.sourceName)
assertOfficialInputWeights(map.mapInputWeights, fixture.sourceName)
val scaleError = relativeError(map.mapInputWeights.sum(), fixture.inputScale)
if (scaleError > MAX_INPUT_SCALE_RELATIVE_ERROR) {
failures += "${fixture.sourceName} inputScale expected=${fixture.inputScale} " +
"actual=${map.mapInputWeights.sum()} relativeError=$scaleError"
}
ToneAnchor.entries.forEach { anchor ->
val expected = anchorGains(
source = fixture.expectedGains,
cellCount = fixture.cellCount,
anchor = anchor
)
val actual = actualAnchorGains(fixture, map, anchor)
DISTRIBUTION_PERCENTILES.forEach { percentile ->
val expectedGain = percentile(expected, percentile)
val actualGain = percentile(actual, percentile)
val errorEv = gainErrorEv(actualGain, expectedGain)
val tolerance = when (percentile) {
0.50f -> MAX_MEDIAN_GAIN_ERROR_EV
else -> MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV
}
if (errorEv > tolerance) {
failures += "${fixture.sourceName} ${anchor.label} " +
"p${(percentile * 100).toInt()} expected=$expectedGain " +
"actual=$actualGain errorEv=$errorEv toleranceEv=$tolerance"
}
}
}
}
assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty())
}
@Test
fun generatedMapsMatchEmbeddedPerCellToneShape() {
val failures = mutableListOf<String>()
loadFixtures().forEach { fixture ->
val map = generateMap(fixture)
ToneAnchor.entries
.filterNot { it == ToneAnchor.ENDPOINT }
.forEach { anchor ->
val expected = anchorGains(
source = fixture.expectedGains,
cellCount = fixture.cellCount,
anchor = anchor
fun densePxls2CurvesStayWithinTrainedErrorEnvelope() {
var squaredErrorSum = 0.0
var errorCount = 0
val absoluteErrors = ArrayList<Float>(2_700_000)
fixtures().forEach { fixture ->
val plan = plan(fixture)
val generated = DngHdrProfileGainTableCpuReference.generate(plan)
fixture.expectedGains.forEachIndexed { cell, expectedCurve ->
fixture.tableInputs.forEachIndexed { inputIndex, tableInput ->
val predicted = sampleCurve(
generated,
cell,
plan.pointCount,
tableInput,
)
val actual = actualAnchorGains(fixture, map, anchor)
val rmseEv = logGainRmseEv(actual, expected)
if (rmseEv > MAX_PER_CELL_GAIN_RMSE_EV) {
failures += "${fixture.sourceName} ${anchor.label} " +
"perCellRmseEv=$rmseEv toleranceEv=$MAX_PER_CELL_GAIN_RMSE_EV"
}
val errorEv = log2(
max(predicted, 1e-8f) / max(expectedCurve[inputIndex], 1e-8f)
)
squaredErrorSum += errorEv * errorEv
absoluteErrors += abs(errorEv)
errorCount++
}
}
}
assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty())
absoluteErrors.sort()
val rmse = sqrt(squaredErrorSum / errorCount)
val p95 = absoluteErrors[(absoluteErrors.size * 0.95).toInt()]
assertTrue("PXLs2 dense curve RMSE=$rmse EV", rmse <= 0.155)
assertTrue("PXLs2 dense curve p95=$p95 EV", p95 <= 0.290f)
}
private fun generateMap(
fixture: PgtmFixture,
fusionParameters: HdrExposureFusionParameters =
DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS,
): DngProfileGainTableMap {
return DngHdrProfileGainTableGenerator.forCellStats(
@Test
fun generatedCurvesEnforceBlackToeShoulderAndEndpointRules() {
fixtures().forEach { fixture ->
val plan = plan(fixture)
val gains = DngHdrProfileGainTableCpuReference.generate(plan)
val curveParameters = plan.curveParameters
plan.cellPlans.forEachIndexed { cell, cellPlan ->
assertEquals(plan.inputScale, cellPlan.endpointGain, 0f)
assertTrue(
cellPlan.blackGain in
curveParameters.minBlackGain..curveParameters.maxTableGain
)
assertTrue(
cellPlan.shapePower in
curveParameters.minShapePower..curveParameters.maxShapePower
)
var previousOutput = 0f
repeat(plan.pointCount) { point ->
val tableInput = tableInput(point, plan.pointCount)
val gain = gains[cell * plan.pointCount + point]
val output = tableInput * gain
assertTrue("${fixture.sourceName} gain=$gain", gain.isFinite() && gain > 0f)
assertTrue(
"${fixture.sourceName} output reversal at point=$point",
output + 2e-6f >= previousOutput,
)
assertTrue(
"${fixture.sourceName} output overflow=$output",
output <= max(1f, plan.inputScale) + 2e-6f,
)
if (tableInput <= curveParameters.toeEnd) {
assertEquals(cellPlan.blackGain, gain, 2e-6f)
}
previousOutput = output
}
assertEquals(
plan.inputScale,
gains[cell * plan.pointCount + plan.pointCount - 1],
1e-6f,
)
}
}
}
@Test
fun baselineExposureDoesNotReciprocallyClampTheLearnedDomain() {
val fixtures = fixtures()
val plans = fixtures.map(::plan)
assertTrue(
fixtures.zip(plans).any { (fixture, plan) ->
plan.inputScale * DngBaselineExposure.exactGain(
fixture.baselineExposureEv
) > 1.25f
}
)
assertTrue(plans.maxOf { it.inputScale } > 0.95f)
assertTrue(plans.minOf { it.inputScale } < 0.45f)
}
@Test
fun largerNoiseFloorReducesUnsupportedBlackLift() {
val fixture = fixtures().first()
val quieter = plan(fixture, noiseOffset = fixture.noiseOffset * 0.25f)
val noisier = plan(fixture, noiseOffset = fixture.noiseOffset * 4f)
assertTrue(
median(noisier.cellPlans.map { it.blackGain }) <
median(quieter.cellPlans.map { it.blackGain })
)
}
private fun plan(
fixture: Fixture,
noiseOffset: Float = fixture.noiseOffset,
): HdrProfileGainTablePlan = requireNotNull(
DngHdrProfileGainTableGenerator.planForCellStats(
width = fixture.width,
height = fixture.height,
baselineExposureEv = fixture.baselineExposureEv,
packedCellStats = fixture.packedStats,
fusionParameters = fusionParameters,
) ?: error("Expected PGTM for ${fixture.sourceName}")
}
private fun actualAnchorGains(
fixture: PgtmFixture,
map: DngProfileGainTableMap,
anchor: ToneAnchor,
): FloatArray {
val inputScale = map.mapInputWeights.sum()
return FloatArray(fixture.cellCount) { cell ->
val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, inputScale)
val tableInput = if (anchor == ToneAnchor.ENDPOINT) 1f else sceneSignal * inputScale
sampleGain(map, tableInput, cell)
}
}
private fun assertEmbeddedSemanticOutputsMonotonic(fixture: PgtmFixture) {
for (cell in 0 until fixture.cellCount) {
var previousOutput = 0f
ToneAnchor.entries.forEach { anchor ->
val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, fixture.inputScale)
val gain = fixture.expectedGains[cell * fixture.anchorCount + anchor.ordinal]
val tableInput = if (anchor == ToneAnchor.ENDPOINT) {
1f
} else {
(sceneSignal * fixture.inputScale).coerceIn(0f, 1f)
}
val output = tableInput * gain
assertTrue(
"${fixture.sourceName} cell=$cell anchor=${anchor.label} output=$output previous=$previousOutput",
output + OUTPUT_EPS >= previousOutput
)
previousOutput = max(previousOutput, output)
}
}
}
private fun assertMapOutputsMonotonic(map: DngProfileGainTableMap, sourceName: String) {
for (cell in 0 until map.mapPointsH * map.mapPointsV) {
var previousOutput = 0f
for (index in 0 until map.mapPointsN) {
val input = tableInputForIndex(index, map.mapPointsN)
val output = input * map.gains[cell * map.mapPointsN + index]
assertTrue(
"$sourceName cell=$cell index=$index output=$output previous=$previousOutput",
output + OUTPUT_EPS >= previousOutput
)
previousOutput = max(previousOutput, output)
}
}
}
private fun sceneSignalForAnchor(
fixture: PgtmFixture,
cell: Int,
anchor: ToneAnchor,
inputScale: Float,
): Float {
val offset = cell * CELL_STATS_STRIDE
val p10 = fixture.packedStats[offset + STAT_P10].coerceIn(0f, 1f)
val p50 = max(p10, fixture.packedStats[offset + STAT_P50].coerceIn(0f, 1f))
val p90 = max(p50, fixture.packedStats[offset + STAT_P90].coerceIn(0f, 1f))
val p98 = max(p90, fixture.packedStats[offset + STAT_P98].coerceIn(0f, 1f))
val p995 = max(p98, fixture.packedStats[offset + STAT_P995].takeIf { it > 0f } ?: p98)
val p999 = max(p995, fixture.packedStats[offset + STAT_P999].takeIf { it > 0f } ?: p995)
return when (anchor) {
ToneAnchor.BLACK -> 0f
ToneAnchor.SHADOW -> p10
ToneAnchor.DARK -> 0.5f * (p10 + p50)
ToneAnchor.MEDIAN -> p50
ToneAnchor.BRIGHT -> p90
ToneAnchor.HIGHLIGHT -> p98
ToneAnchor.WHITE -> p995
ToneAnchor.SPECULAR -> p999
ToneAnchor.ENDPOINT -> 1f / inputScale.coerceAtLeast(1e-6f)
}
}
private fun anchorGains(
source: FloatArray,
cellCount: Int,
anchor: ToneAnchor,
): FloatArray {
return FloatArray(cellCount) { cell ->
source[cell * ToneAnchor.entries.size + anchor.ordinal]
}
}
private fun cellStats(fixture: PgtmFixture, stat: Int): FloatArray {
return FloatArray(fixture.cellCount) { cell ->
fixture.packedStats[cell * CELL_STATS_STRIDE + stat]
}
}
private fun sampleGain(map: DngProfileGainTableMap, input: Float, cell: Int): Float {
val scaled = input.coerceIn(0f, 1f) * map.mapPointsN.coerceAtLeast(1)
val index0 = scaled.toInt().coerceIn(0, map.mapPointsN - 1)
val index1 = (index0 + 1).coerceIn(0, map.mapPointsN - 1)
val fraction = scaled - index0
val offset = cell.coerceIn(0, map.mapPointsH * map.mapPointsV - 1) * map.mapPointsN
return map.gains[offset + index0] * (1f - fraction) +
map.gains[offset + index1] * fraction
}
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
if (pointCount <= 1) return 0f
return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat()
}
private fun assertOfficialInputWeights(weights: FloatArray, sourceName: String) {
val sum = weights.sum()
assertTrue("$sourceName invalid weight sum=$sum", sum.isFinite() && sum > 0f)
OFFICIAL_INPUT_WEIGHTS.forEachIndexed { index, expected ->
assertEquals("$sourceName weight[$index]", expected, weights[index] / sum, 0.0001f)
}
}
private fun percentile(values: FloatArray, percentile: Float): Float {
if (values.isEmpty()) return 0f
val sorted = values.copyOf().also { it.sort() }
val rank = (sorted.size - 1).toFloat() * percentile.coerceIn(0f, 1f)
val lower = floor(rank).toInt()
val upper = ceil(rank).toInt()
if (lower == upper) return sorted[lower]
return sorted[lower] * (upper - rank) + sorted[upper] * (rank - lower)
}
private fun relativeError(actual: Float, expected: Float): Float {
return abs(actual - expected) / max(abs(expected), 1e-6f)
}
private fun gainErrorEv(actual: Float, expected: Float): Float {
return abs(log2(actual.coerceAtLeast(1e-6f) / expected.coerceAtLeast(1e-6f)))
}
private fun logGainRmseEv(actual: FloatArray, expected: FloatArray): Float {
require(actual.size == expected.size)
val meanSquare = actual.indices.sumOf { index ->
val error = log2(
actual[index].coerceAtLeast(1e-6f) /
expected[index].coerceAtLeast(1e-6f)
)
(error * error).toDouble()
} / actual.size.coerceAtLeast(1).toDouble()
return sqrt(meanSquare).toFloat()
}
private fun log2(value: Float): Float {
return (ln(value.coerceAtLeast(1e-6f).toDouble()) / ln(2.0)).toFloat()
}
private fun denseShoulderCases(): List<DenseShoulderCase> = listOf(
denseShoulderCase("Skyyking_20260711_184627.RAW-02.ORIGINAL", 0.331765622f, 0.205544580f, 0.152909992f),
denseShoulderCase("Skyyking_20260711_184751.RAW-02.ORIGINAL", 0.462672237f, 0.337412789f, 0.272237092f),
denseShoulderCase("Skyyking_20260711_184953.RAW-02.ORIGINAL", 0.915177912f, 0.544002324f, 0.395905923f),
denseShoulderCase("Skyyking_20260711_185653.RAW-02.ORIGINAL", 0.213499438f, 0.181819726f, 0.162513237f),
denseShoulderCase("Skyyking_20260711_185704.RAW-02.ORIGINAL", 0.163654307f, 0.101506390f, 0.075539880f),
denseShoulderCase("Skyyking_20260711_185836.RAW-02.ORIGINAL", 0.522830814f, 0.433588199f, 0.374911249f),
denseShoulderCase("Skyyking_20260712_105529.RAW-02.ORIGINAL", 0.332546350f, 0.203987684f, 0.150961947f),
denseShoulderCase("Skyyking_20260713_232945.RAW-02.ORIGINAL", 0.504472025f, 0.425721936f, 0.372749154f),
denseShoulderCase("Skyyking_20260714_083737.RAW-02.ORIGINAL", 0.735527232f, 0.438027993f, 0.319880389f),
denseShoulderCase("Skyyking_20260714_092416.RAW-02.ORIGINAL", 0.243842043f, 0.142250773f, 0.102864855f),
denseShoulderCase("Skyyking_20260714_123251.RAW-02.ORIGINAL", 0.259386316f, 0.154736947f, 0.113109255f),
denseShoulderCase("Skyyking_20260714_151021.RAW-02.ORIGINAL", 0.411366213f, 0.272355564f, 0.209032677f),
noiseSlope = fixture.noiseSlope,
noiseOffset = noiseOffset,
)
)
private fun denseShoulderCase(
name: String,
gain25: Float,
gain50: Float,
gain75: Float,
) = DenseShoulderCase(name, floatArrayOf(gain25, gain50, gain75))
private fun fixtures(): List<Fixture> = fixtureCache
private fun loadFixtures(): List<PgtmFixture> = FIXTURE_RESOURCES.map(::loadFixture)
private fun loadFixture(resourceName: String): PgtmFixture {
val bytes = requireNotNull(javaClass.getResourceAsStream(resourceName)) {
"Missing PGTM fixture $resourceName"
}.use { it.readBytes() }
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val magic = ByteArray(FIXTURE_MAGIC.size).also(buffer::get)
require(magic.contentEquals(FIXTURE_MAGIC)) { "Invalid PGTM fixture $resourceName" }
val width = buffer.int
val height = buffer.int
val baselineExposureEv = buffer.float
val mapPointsH = buffer.int
val mapPointsV = buffer.int
val anchorCount = buffer.int
val statCount = buffer.int
val gainCount = buffer.int
val weights = FloatArray(5) { buffer.float }
val gamma = buffer.float
val packedStats = FloatArray(statCount) { buffer.float }
val expectedGains = FloatArray(gainCount) { buffer.float }
require(!buffer.hasRemaining()) { "Unexpected trailing data in $resourceName" }
return PgtmFixture(
sourceName = resourceName.substringAfterLast('/').substringBefore(".pgtfixture"),
width = width,
height = height,
baselineExposureEv = baselineExposureEv,
mapPointsH = mapPointsH,
mapPointsV = mapPointsV,
anchorCount = anchorCount,
inputWeights = weights,
gamma = gamma,
packedStats = packedStats,
expectedGains = expectedGains
)
private fun sampleCurve(
gains: FloatArray,
cell: Int,
pointCount: Int,
tableInput: Float,
): Float {
if (tableInput >= 1f) return gains[cell * pointCount + pointCount - 1]
val scaled = tableInput.coerceIn(0f, 1f) * pointCount
val first = scaled.toInt().coerceIn(0, pointCount - 1)
val second = (first + 1).coerceAtMost(pointCount - 1)
val amount = scaled - first
val offset = cell * pointCount
return gains[offset + first] * (1f - amount) + gains[offset + second] * amount
}
private enum class ToneAnchor(val label: String) {
BLACK("black"),
SHADOW("shadow-p10"),
DARK("dark-p10-p50"),
MEDIAN("median-p50"),
BRIGHT("bright-p90"),
HIGHLIGHT("highlight-p98"),
WHITE("white-p995"),
SPECULAR("specular-p999"),
ENDPOINT("table-endpoint"),
private fun tableInput(point: Int, pointCount: Int): Float =
if (point == pointCount - 1) 1f else point.toFloat() / pointCount.toFloat()
private fun median(values: List<Float>): Float {
val sorted = values.sorted()
val center = sorted.size / 2
return if (sorted.size % 2 == 0) {
0.5f * (sorted[center - 1] + sorted[center])
} else {
sorted[center]
}
}
private data class PgtmFixture(
private fun log2(value: Float): Float = (ln(value.toDouble()) / ln(2.0)).toFloat()
private data class Fixture(
val sourceName: String,
val width: Int,
val height: Int,
val baselineExposureEv: Float,
val mapPointsH: Int,
val mapPointsV: Int,
val anchorCount: Int,
val mapH: Int,
val mapV: Int,
val inputWeights: FloatArray,
val gamma: Float,
val noiseSlope: Float,
val noiseOffset: Float,
val tableInputs: FloatArray,
val packedStats: FloatArray,
val expectedGains: FloatArray,
) {
val cellCount: Int get() = mapPointsH * mapPointsV
val inputScale: Float get() = inputWeights.sum()
}
private data class DenseShoulderCase(
val name: String,
val officialMedianGains: FloatArray,
val expectedGains: Array<FloatArray>,
)
private data class DenseShoulderResult(
val name: String,
val tableInput: Float,
val expectedGain: Float,
val actualGain: Float,
val errorEv: Float,
)
companion object {
private val MAGIC = "PGTFIX3\u0000".toByteArray(Charsets.US_ASCII)
private companion object {
private const val CELL_STATS_STRIDE = 8
private const val STAT_P10 = 0
private const val STAT_P50 = 1
private const val STAT_P90 = 2
private const val STAT_P98 = 3
private const val STAT_P995 = 6
private const val STAT_P999 = 7
private const val OUTPUT_EPS = 0.0001f
private const val MAX_INPUT_SCALE_RELATIVE_ERROR = 0.12f
private const val MAX_MEDIAN_GAIN_ERROR_EV = 0.22f
private const val MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV = 0.38f
private const val MAX_PER_CELL_GAIN_RMSE_EV = 0.48f
private val FIXTURE_MAGIC = "PGTFIX2\u0000".toByteArray(Charsets.US_ASCII)
private const val BIMODAL_CAPTURE_RESOURCE =
"/pgtm/captures/PhotonCamera_20260715_173013.pgtfixture"
private val DISTRIBUTION_PERCENTILES =
floatArrayOf(0.10f, 0.25f, 0.50f, 0.75f, 0.90f, 0.98f)
private val OFFICIAL_INPUT_WEIGHTS = floatArrayOf(0.1495f, 0.2935f, 0.0570f, 0.1250f, 0.3750f)
private val FIXTURE_RESOURCES = listOf(
"/pgtm/skyyking/Skyyking_20260711_184627.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260711_184751.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260711_185653.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260711_185704.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260711_185836.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260712_105529.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260713_232945.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260714_083737.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260714_092416.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260714_123251.RAW-02.ORIGINAL.pgtfixture",
"/pgtm/skyyking/Skyyking_20260714_151021.RAW-02.ORIGINAL.pgtfixture",
)
private val fixtureCache: List<Fixture> by lazy {
val loader = requireNotNull(
DngHdrProfileGainTableGeneratorTest::class.java.classLoader
)
val resource = requireNotNull(loader.getResource("pgtm/pxls2"))
File(resource.toURI()).listFiles()
.orEmpty()
.filter { it.isFile && it.extension == "pgtfix" }
.sortedBy { it.name }
.map(::readFixture)
}
private fun readFixture(file: File): Fixture {
val buffer = ByteBuffer.wrap(file.readBytes()).order(ByteOrder.LITTLE_ENDIAN)
val magic = ByteArray(MAGIC.size).also(buffer::get)
require(magic.contentEquals(MAGIC)) { "invalid fixture ${file.name}" }
val width = buffer.int
val height = buffer.int
val baseline = buffer.float
val mapH = buffer.int
val mapV = buffer.int
val inputCount = buffer.int
val statCount = buffer.int
val gainCount = buffer.int
val weights = FloatArray(5) { buffer.float }
val gamma = buffer.float
require(gamma == 1f)
val noiseSlope = buffer.float
val noiseOffset = buffer.float
val tableInputs = FloatArray(inputCount) { buffer.float }
val packedStats = FloatArray(statCount) { buffer.float }
require(gainCount == mapH * mapV * inputCount)
val expected = Array(mapH * mapV) {
FloatArray(inputCount) { buffer.float }
}
return Fixture(
sourceName = file.name,
width = width,
height = height,
baselineExposureEv = baseline,
mapH = mapH,
mapV = mapV,
inputWeights = weights,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
tableInputs = tableInputs,
packedStats = packedStats,
expectedGains = expected,
)
}
}
}
@@ -1,24 +1,22 @@
package com.hinnka.mycamera.raw
/** JVM-only bridge that exercises the production planner with a deterministic curve stage. */
internal fun DngHdrProfileGainTableGenerator.forCellStats(
internal fun DngHdrProfileGainTableGenerator.generateForCellStats(
width: Int,
height: Int,
baselineExposureEv: Float,
packedCellStats: FloatArray,
tablePointCount: Int = 257,
noiseSlope: Float,
noiseOffset: Float,
diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand? = null,
fusionParameters: HdrExposureFusionParameters =
DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS,
): DngProfileGainTableMap? {
val plan = planForCellStats(
width = width,
height = height,
baselineExposureEv = baselineExposureEv,
packedCellStats = packedCellStats,
tablePointCount = tablePointCount,
noiseSlope = noiseSlope,
noiseOffset = noiseOffset,
diagnosticBand = diagnosticBand,
fusionParameters = fusionParameters,
) ?: return null
return mapFromGpuGains(plan, DngHdrProfileGainTableCpuReference.generate(plan))
}
@@ -72,6 +72,51 @@ class RawViewfinderExposureMathTest {
assertTrue(match!!.matchLog2Error < -1f)
}
@Test
fun crushedShadowsDoNotDriveHighContrastSceneTowardOverexposure() {
val width = 8
val height = 8
val referencePixels = grayscalePixels(width, height, linearLuma = 0.01f)
val candidatePixels = grayscalePixels(width, height, linearLuma = 0.001f)
for (index in 48 until referencePixels.size) {
referencePixels[index] = grayscaleArgb(0.64f)
candidatePixels[index] = grayscaleArgb(0.64f)
}
val reference = buildReference(referencePixels, width, height)
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertEquals(0f, match!!.medianLog2Error, 0.001f)
assertEquals(0f, match.matchLog2Error, 0.1f)
val solvedEv = RawViewfinderExposureMath.solve { exposureEv ->
val exposureGain = 2f.pow(exposureEv)
val renderedPixels = grayscalePixels(
width,
height,
linearLuma = 0.001f * exposureGain,
)
for (index in 48 until renderedPixels.size) {
renderedPixels[index] = grayscaleArgb(0.64f * exposureGain)
}
RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = renderedPixels,
width = width,
height = height,
)?.matchLog2Error
}
assertNotNull(solvedEv)
assertEquals(0f, solvedEv!!, 0.15f)
}
@Test
fun referenceWithOnlyClippedPixelsIsRejected() {
val pixels = IntArray(64) { index ->