fix: raw highlight
This commit is contained in:
1 parent
3e320e2292
commit
c3ed146ba7
12 files changed
+700
-296
No files matched your search
@@ -1598,6 +1598,28 @@ static bool dngSdkCameraToPcsForWhite(const DngSdkPreparedColor &prepared,
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool dngSdkCameraWhiteForWhite(
|
||||
const DngSdkPreparedColor &prepared,
|
||||
const std::array<float, 2> &whiteXy,
|
||||
std::array<float, 3> &cameraWhite) {
|
||||
std::array<float, 3> whiteXyz;
|
||||
if (!xyToXyz(whiteXy, whiteXyz)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const DngSdkMatrixForWhite matrices =
|
||||
dngSdkFindXyzToCamera(prepared, whiteXy);
|
||||
cameraWhite = multiplyMatrixVector(matrices.colorMatrix, whiteXyz);
|
||||
const float scale = 1.0f / std::max(maxVectorEntry(cameraWhite), 1e-6f);
|
||||
for (float &value : cameraWhite) {
|
||||
value = std::clamp(value * scale, 0.001f, 1.0f);
|
||||
if (!std::isfinite(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool computeDngSdkCameraToPcsD50(
|
||||
const Matrix3x3 &colorMatrix1, bool hasColor1,
|
||||
const Matrix3x3 &colorMatrix2, bool hasColor2,
|
||||
@@ -1606,7 +1628,8 @@ static bool computeDngSdkCameraToPcsD50(
|
||||
int illuminant2, const float wb[4], const Matrix3x3 &cameraCalibration1,
|
||||
const Matrix3x3 &cameraCalibration2,
|
||||
const std::array<float, 3> &analogBalance, Matrix3x3 &cameraToPcs,
|
||||
std::array<float, 2> *outWhiteXy = nullptr) {
|
||||
std::array<float, 2> *outWhiteXy = nullptr,
|
||||
std::array<float, 3> *outCameraWhite = nullptr) {
|
||||
DngSdkPreparedColor prepared;
|
||||
if (!prepareDngSdkColor(colorMatrix1, hasColor1, colorMatrix2, hasColor2,
|
||||
forwardMatrix1, hasForward1, forwardMatrix2,
|
||||
@@ -1630,6 +1653,10 @@ static bool computeDngSdkCameraToPcsD50(
|
||||
if (outWhiteXy) {
|
||||
*outWhiteXy = whiteXy;
|
||||
}
|
||||
if (outCameraWhite &&
|
||||
!dngSdkCameraWhiteForWhite(prepared, whiteXy, *outCameraWhite)) {
|
||||
return false;
|
||||
}
|
||||
return dngSdkCameraToPcsForWhite(prepared, whiteXy, cameraToPcs);
|
||||
}
|
||||
|
||||
@@ -3398,7 +3425,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
|
||||
jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData");
|
||||
jmethodID constructor =
|
||||
env->GetMethodID(dngDataClass, "<init>",
|
||||
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[FIIFF[FII[FFIJF[I[I[F[FLandroid/graphics/Bitmap;)V");
|
||||
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[F[FIIFF[FII[FFIJF[I[I[F[FLandroid/graphics/Bitmap;)V");
|
||||
|
||||
jfloatArray blackLevelArray = env->NewFloatArray(4);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
@@ -3503,16 +3530,29 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
|
||||
|
||||
Matrix3x3 camToXYZ = Matrix3x3::identity();
|
||||
std::array<float, 2> sdkWhiteXy = {0.3457f, 0.3585f};
|
||||
const float cameraGreen =
|
||||
std::max((wb[1] + (wb[3] > 0.0f ? wb[3] : wb[1])) * 0.5f, 1e-6f);
|
||||
std::array<float, 3> sdkCameraWhite = {
|
||||
cameraGreen / std::max(wb[0], 1e-6f),
|
||||
1.0f,
|
||||
cameraGreen / std::max(wb[2], 1e-6f),
|
||||
};
|
||||
const float cameraWhiteScale =
|
||||
1.0f / std::max(maxVectorEntry(sdkCameraWhite), 1e-6f);
|
||||
for (float &value : sdkCameraWhite) {
|
||||
value = std::clamp(value * cameraWhiteScale, 0.001f, 1.0f);
|
||||
}
|
||||
bool hasSdkMatrix = computeDngSdkCameraToPcsD50(
|
||||
colorMatrix1, hasColor1, colorMatrix2, hasColor2, forwardMatrix1,
|
||||
hasForward1, forwardMatrix2, hasForward2,
|
||||
RawProcessor.imgdata.color.dng_color[0].illuminant,
|
||||
RawProcessor.imgdata.color.dng_color[1].illuminant, wb,
|
||||
cameraCalibration1, cameraCalibration2, analogBalance, camToXYZ,
|
||||
&sdkWhiteXy);
|
||||
&sdkWhiteXy, &sdkCameraWhite);
|
||||
if (hasSdkMatrix) {
|
||||
LOGI("Using DNG color spec path: whiteXY=%f,%f", sdkWhiteXy[0],
|
||||
sdkWhiteXy[1]);
|
||||
LOGI("Using DNG color spec path: whiteXY=%f,%f cameraWhite=%f,%f,%f",
|
||||
sdkWhiteXy[0], sdkWhiteXy[1], sdkCameraWhite[0],
|
||||
sdkCameraWhite[1], sdkCameraWhite[2]);
|
||||
} else if (!isDngInput &&
|
||||
computeLibRawCameraToXyzD50(RawProcessor, wb, camToXYZ)) {
|
||||
hasSdkMatrix = true;
|
||||
@@ -3527,7 +3567,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
|
||||
if (computeDngSdkCameraToPcsD50(
|
||||
xyzToCam, true, identity, false, identity, false, identity,
|
||||
false, 21, 0, wb, identity, identity, unityAnalog, camToXYZ,
|
||||
&fallbackWhiteXy)) {
|
||||
&fallbackWhiteXy, &sdkCameraWhite)) {
|
||||
LOGI("Using %s fallback via DNG ColorMatrix path: whiteXY=%f,%f",
|
||||
sourceName, fallbackWhiteXy[0], fallbackWhiteXy[1]);
|
||||
return true;
|
||||
@@ -3597,6 +3637,8 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
|
||||
Matrix3x3 finalCCM = targetTransform.multiply(camToXYZ);
|
||||
jfloatArray colorMatrixArray = env->NewFloatArray(9);
|
||||
env->SetFloatArrayRegion(colorMatrixArray, 0, 9, finalCCM.m);
|
||||
jfloatArray cameraWhiteArray = env->NewFloatArray(3);
|
||||
env->SetFloatArrayRegion(cameraWhiteArray, 0, 3, sdkCameraWhite.data());
|
||||
|
||||
LOGI("finalCCM: %f, %f, %f, %f, %f, %f, %f, %f, %f", finalCCM.m[0],
|
||||
finalCCM.m[1], finalCCM.m[2], finalCCM.m[3], finalCCM.m[4],
|
||||
@@ -3683,8 +3725,10 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
|
||||
|
||||
jobject dngData = env->NewObject(
|
||||
dngDataClass, constructor, rawDataBuffer, width, height, rowStride,
|
||||
samplesPerPixel, whiteLevel, blackLevelArray, preMulArray, wbArray, colorMatrixArray,
|
||||
cfaPattern, ed.rotation, baselineExposure, shadowScale, exportedLscArray, exportedLscWidth, exportedLscHeight,
|
||||
samplesPerPixel, whiteLevel, blackLevelArray, preMulArray, wbArray,
|
||||
colorMatrixArray, cameraWhiteArray, cfaPattern, ed.rotation,
|
||||
baselineExposure, shadowScale, exportedLscArray, exportedLscWidth,
|
||||
exportedLscHeight,
|
||||
exportedLscGridArray, exposureBias, iso,
|
||||
shutterSpeedLong, aperture, activeArray, defaultCropArray, noiseProfileArray,
|
||||
warpRectilinearArray,
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** Shared DNG profile Hue/Sat map implementation for every pre-PGTM GPU path. */
|
||||
internal object DcpHueSatMapGl {
|
||||
val SHADER_FUNCTIONS = """
|
||||
float dngClampTableCoordinate(float value) {
|
||||
return clamp(value, 0.0, 1.0);
|
||||
}
|
||||
|
||||
float dngLinearToSrgbValue(float value) {
|
||||
value = max(value, 0.0);
|
||||
return value <= 0.0031308
|
||||
? value * 12.92
|
||||
: 1.055 * pow(value, 1.0 / 2.4) - 0.055;
|
||||
}
|
||||
|
||||
float dngSrgbToLinearValue(float value) {
|
||||
value = max(value, 0.0);
|
||||
return value <= 0.04045
|
||||
? value / 12.92
|
||||
: pow((value + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
float dngEncodeLookupValue(float value, int encoding) {
|
||||
value = dngClampTableCoordinate(value);
|
||||
return encoding == 1 ? dngLinearToSrgbValue(value) : value;
|
||||
}
|
||||
|
||||
float dngEncodeScaledValue(float value, int encoding) {
|
||||
value = max(value, 0.0);
|
||||
return encoding == 1 ? dngLinearToSrgbValue(value) : value;
|
||||
}
|
||||
|
||||
float dngDecodeScaledValue(float value, int encoding) {
|
||||
value = max(value, 0.0);
|
||||
return encoding == 1 ? dngSrgbToLinearValue(value) : value;
|
||||
}
|
||||
|
||||
vec3 dngRgbToHsv(vec3 rgb) {
|
||||
float maxValue = max(rgb.r, max(rgb.g, rgb.b));
|
||||
float minValue = min(rgb.r, min(rgb.g, rgb.b));
|
||||
float delta = maxValue - minValue;
|
||||
float hue = 0.0;
|
||||
if (delta > 1e-6) {
|
||||
if (maxValue == rgb.r) {
|
||||
hue = mod((rgb.g - rgb.b) / delta, 6.0);
|
||||
} else if (maxValue == rgb.g) {
|
||||
hue = ((rgb.b - rgb.r) / delta) + 2.0;
|
||||
} else {
|
||||
hue = ((rgb.r - rgb.g) / delta) + 4.0;
|
||||
}
|
||||
}
|
||||
if (hue < 0.0) hue += 6.0;
|
||||
float saturation = maxValue > 1e-6 ? delta / maxValue : 0.0;
|
||||
return vec3(hue, saturation, maxValue);
|
||||
}
|
||||
|
||||
vec3 dngHsvToRgb(vec3 hsv) {
|
||||
float hue = mod(hsv.x, 6.0);
|
||||
if (hue < 0.0) hue += 6.0;
|
||||
float saturation = max(hsv.y, 0.0);
|
||||
float value = max(hsv.z, 0.0);
|
||||
float chroma = value * saturation;
|
||||
float x = chroma * (1.0 - abs(mod(hue, 2.0) - 1.0));
|
||||
vec3 rgb;
|
||||
if (hue < 1.0) rgb = vec3(chroma, x, 0.0);
|
||||
else if (hue < 2.0) rgb = vec3(x, chroma, 0.0);
|
||||
else if (hue < 3.0) rgb = vec3(0.0, chroma, x);
|
||||
else if (hue < 4.0) rgb = vec3(0.0, x, chroma);
|
||||
else if (hue < 5.0) rgb = vec3(x, 0.0, chroma);
|
||||
else rgb = vec3(chroma, 0.0, x);
|
||||
return rgb + vec3(value - chroma);
|
||||
}
|
||||
|
||||
vec3 dngSampleHueSatMap(sampler3D tableTexture, ivec3 divisions, vec3 hsv) {
|
||||
int hueDivisions = divisions.x;
|
||||
int satDivisions = divisions.y;
|
||||
int valueDivisions = divisions.z;
|
||||
if (hueDivisions <= 0 || satDivisions <= 0 || valueDivisions <= 0) {
|
||||
return vec3(0.0, 1.0, 1.0);
|
||||
}
|
||||
|
||||
float hScaled = hsv.x * float(hueDivisions) / 6.0;
|
||||
float sScaled = hsv.y * float(max(satDivisions - 1, 0));
|
||||
float vScaled = hsv.z * float(max(valueDivisions - 1, 0));
|
||||
int h0 = int(floor(hScaled));
|
||||
int s0 = min(int(floor(sScaled)), max(satDivisions - 2, 0));
|
||||
int v0 = min(int(floor(vScaled)), max(valueDivisions - 2, 0));
|
||||
int h1 = h0 + 1;
|
||||
if (h0 >= hueDivisions - 1) {
|
||||
h0 = hueDivisions - 1;
|
||||
h1 = 0;
|
||||
}
|
||||
int s1 = min(s0 + 1, satDivisions - 1);
|
||||
int v1 = min(v0 + 1, valueDivisions - 1);
|
||||
float hf = hScaled - float(h0);
|
||||
float sf = sScaled - float(s0);
|
||||
float vf = vScaled - float(v0);
|
||||
|
||||
vec3 p000 = texelFetch(tableTexture, ivec3(s0, h0, v0), 0).rgb;
|
||||
vec3 p001 = texelFetch(tableTexture, ivec3(s0, h1, v0), 0).rgb;
|
||||
vec3 p010 = texelFetch(tableTexture, ivec3(s1, h0, v0), 0).rgb;
|
||||
vec3 p011 = texelFetch(tableTexture, ivec3(s1, h1, v0), 0).rgb;
|
||||
if (valueDivisions > 1) {
|
||||
p000 = mix(p000, texelFetch(tableTexture, ivec3(s0, h0, v1), 0).rgb, vf);
|
||||
p001 = mix(p001, texelFetch(tableTexture, ivec3(s0, h1, v1), 0).rgb, vf);
|
||||
p010 = mix(p010, texelFetch(tableTexture, ivec3(s1, h0, v1), 0).rgb, vf);
|
||||
p011 = mix(p011, texelFetch(tableTexture, ivec3(s1, h1, v1), 0).rgb, vf);
|
||||
}
|
||||
return mix(mix(p000, p001, hf), mix(p010, p011, hf), sf);
|
||||
}
|
||||
|
||||
vec3 dngApplyHueSatMap(
|
||||
vec3 color,
|
||||
sampler3D tableTexture,
|
||||
ivec3 divisions,
|
||||
int encoding
|
||||
) {
|
||||
vec3 hsv = dngRgbToHsv(color);
|
||||
float encodedValue = hsv.z;
|
||||
float lookupValue = hsv.z;
|
||||
// RefBaselineHueSatMap uses the encoded value axis only for a true 3D map.
|
||||
// The common 2.5D map (one value division) keeps the input value linear here,
|
||||
// although its scaled result is still decoded below when an encoding is present.
|
||||
if (encoding == 1 && divisions.z > 1) {
|
||||
encodedValue = dngEncodeScaledValue(hsv.z, encoding);
|
||||
lookupValue = dngEncodeLookupValue(hsv.z, encoding);
|
||||
}
|
||||
vec3 modify = dngSampleHueSatMap(
|
||||
tableTexture,
|
||||
divisions,
|
||||
vec3(hsv.x, hsv.y, dngClampTableCoordinate(lookupValue))
|
||||
);
|
||||
hsv.x = mod(hsv.x + modify.x * 6.0 / 360.0, 6.0);
|
||||
if (hsv.x < 0.0) hsv.x += 6.0;
|
||||
hsv.y = dngClampTableCoordinate(hsv.y * modify.y);
|
||||
encodedValue = clamp(encodedValue * modify.z, 0.0, 1.0);
|
||||
hsv.z = dngDecodeScaledValue(encodedValue, encoding);
|
||||
return dngHsvToRgb(hsv);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -42,7 +42,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
private const val MIN_TABLE_GAIN = 0.05f
|
||||
private const val AUTO_EXPOSURE_TARGET = 0.278f
|
||||
private const val WELL_EXPOSED_KEY = 0.525f
|
||||
private const val RISKY_HIGHLIGHT_WELL_EXPOSED_KEY = 0.720f
|
||||
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
|
||||
@@ -71,7 +70,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
internal val GOOGLE_FUSION_PARAMETERS = HdrExposureFusionParameters(
|
||||
autoExposureTarget = AUTO_EXPOSURE_TARGET,
|
||||
wellExposedKey = WELL_EXPOSED_KEY,
|
||||
riskyHighlightWellExposedKey = RISKY_HIGHLIGHT_WELL_EXPOSED_KEY,
|
||||
maxExposureGain = MAX_LTM_GAIN,
|
||||
highlightFusionStart = HIGHLIGHT_FUSION_START,
|
||||
highlightFusionEnd = HIGHLIGHT_FUSION_END,
|
||||
@@ -102,16 +100,17 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
cameraWhite: FloatArray? = null,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): Float {
|
||||
val profileRgb = if (colorCorrectionMatrix != null && colorCorrectionMatrix.size >= 9) {
|
||||
floatArrayOf(
|
||||
colorCorrectionMatrix[0] * red + colorCorrectionMatrix[1] * green + colorCorrectionMatrix[2] * blue,
|
||||
colorCorrectionMatrix[3] * red + colorCorrectionMatrix[4] * green + colorCorrectionMatrix[5] * blue,
|
||||
colorCorrectionMatrix[6] * red + colorCorrectionMatrix[7] * green + colorCorrectionMatrix[8] * blue
|
||||
)
|
||||
} else {
|
||||
floatArrayOf(red, green, blue)
|
||||
}
|
||||
val profileRgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
return sceneInputFromProfileRgb(
|
||||
red = profileRgb[0],
|
||||
green = profileRgb[1],
|
||||
@@ -126,9 +125,12 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
): Float {
|
||||
val r = red * baselineGain
|
||||
val g = green * baselineGain
|
||||
val b = blue * baselineGain
|
||||
// dng_render obtains this RGB from BaselineABCtoRGB, which pins RIMM to [0, 1]
|
||||
// before ProfileGainTableMap. BaselineExposure scales only the five-weight lookup input.
|
||||
val profileRgb = DngSdkProfileRgbTransform.clampProfileRgb(red, green, blue)
|
||||
val r = profileRgb[0] * baselineGain
|
||||
val g = profileRgb[1] * baselineGain
|
||||
val b = profileRgb[2] * baselineGain
|
||||
val rgbMin = min(r, min(g, b))
|
||||
val rgbMax = max(r, max(g, b))
|
||||
return max(
|
||||
@@ -146,7 +148,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
height: Int,
|
||||
baselineExposureEv: Float,
|
||||
packedCellStats: FloatArray,
|
||||
denseGlobalStats: DngPgtmGlobalStats? = null,
|
||||
tablePointCount: Int = DEFAULT_TABLE_POINTS,
|
||||
diagnosticBand: DiagnosticBand? = null,
|
||||
fusionParameters: HdrExposureFusionParameters = GOOGLE_FUSION_PARAMETERS,
|
||||
@@ -175,14 +176,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
}
|
||||
val spatialStats = weightedGlobalStats(cells)
|
||||
val inputScale = estimateInputScale(spatialStats, baselineExposureEv)
|
||||
val highlightRiskBand = denseGlobalStats?.let { stats ->
|
||||
highlightRiskBandFor(stats, inputScale)
|
||||
}
|
||||
?: HdrHighlightRiskBand(
|
||||
start = fusionParameters.highlightFusionStart,
|
||||
end = fusionParameters.highlightFusionEnd,
|
||||
strength = 0f,
|
||||
)
|
||||
val globalPlan = buildGlobalExposurePlan(
|
||||
stats = spatialStats,
|
||||
inputScale = inputScale,
|
||||
@@ -202,47 +195,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
cellPlans = cellPlans,
|
||||
diagnosticBand = diagnosticBand?.sanitized(),
|
||||
fusionParameters = fusionParameters,
|
||||
highlightRiskBand = highlightRiskBand,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun highlightRiskBandFor(
|
||||
stats: DngPgtmGlobalStats,
|
||||
inputScale: Float,
|
||||
): HdrHighlightRiskBand = with(stats) {
|
||||
val safeScale = sanitizeInputScale(inputScale)
|
||||
val safeP90 = p90.takeIf { it.isFinite() && it >= 0f } ?: 0f
|
||||
val safeP98 = max(safeP90, p98.takeIf { it.isFinite() && it >= 0f } ?: safeP90)
|
||||
val safeP995 = max(safeP98, p995.takeIf { it.isFinite() && it > 0f } ?: safeP98)
|
||||
val safeP999 = max(safeP995, p999.takeIf { it.isFinite() && it > 0f } ?: safeP995)
|
||||
val detectedStart = (safeP90 * safeScale).coerceIn(0f, 1f - 2f * CURVE_EPS)
|
||||
val detectedEnd = safeP98 * safeScale
|
||||
val tailGapEv = log2(
|
||||
(safeP999 + 0.04f) / (safeP995 + 0.04f)
|
||||
)
|
||||
// Preserve the pre-exposure-fusion tail-usability rule: a large p999-to-p995 gap is a
|
||||
// sparse outlier tail, not trustworthy highlight detail. Dense highlights are retained
|
||||
// because their population provides enough color support to treat the tail as real.
|
||||
val outlierRisk = smoothStep(0.48f, 0.72f, tailGapEv)
|
||||
val safeHighlightFraction = highlightFraction.takeIf { it.isFinite() }
|
||||
?.coerceIn(0f, 1f)
|
||||
?: 0f
|
||||
val sparseTail = 1f - smoothStep(0.10f, 0.18f, safeHighlightFraction)
|
||||
val riskStrength = (outlierRisk * sparseTail).coerceIn(0f, 1f)
|
||||
val start = lerp(
|
||||
GOOGLE_FUSION_PARAMETERS.highlightFusionStart,
|
||||
detectedStart,
|
||||
riskStrength,
|
||||
)
|
||||
val end = lerp(
|
||||
GOOGLE_FUSION_PARAMETERS.highlightFusionEnd,
|
||||
detectedEnd,
|
||||
riskStrength,
|
||||
).coerceIn(start + CURVE_EPS, 1f)
|
||||
HdrHighlightRiskBand(
|
||||
start = start,
|
||||
end = end,
|
||||
strength = riskStrength,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -493,7 +445,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
cellPlans: Array<HdrLtmExposurePlan>,
|
||||
diagnosticBand: DiagnosticBand?,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
highlightRiskBand: HdrHighlightRiskBand,
|
||||
): DngProfileGainTableMap {
|
||||
val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * pointCount)
|
||||
// Local exposure plans vary smoothly. Quantizing only the brightest exposure to 1/128 EV
|
||||
@@ -515,7 +466,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
pointCount = pointCount,
|
||||
plan = plan.copy(brightestExposureGain = quantizedBrightestGain),
|
||||
fusionParameters = fusionParameters,
|
||||
highlightRiskBand = highlightRiskBand,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -560,7 +510,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
pointCount: Int,
|
||||
plan: HdrLtmExposurePlan,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
highlightRiskBand: HdrHighlightRiskBand,
|
||||
) {
|
||||
val brightestGain = plan.brightestExposureGain.coerceIn(
|
||||
MIN_TABLE_GAIN,
|
||||
@@ -587,7 +536,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
exposureGains = exposureGains,
|
||||
exposureGainEvs = exposureGainEvs,
|
||||
fusionParameters = fusionParameters,
|
||||
highlightRiskBand = highlightRiskBand,
|
||||
)
|
||||
val monotonicOutput = max(previousOutput, fusedOutput)
|
||||
output[outputOffset + index] = (monotonicOutput / sceneInput)
|
||||
@@ -601,19 +549,13 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
exposureGains: FloatArray,
|
||||
exposureGainEvs: FloatArray,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
highlightRiskBand: HdrHighlightRiskBand,
|
||||
): Float {
|
||||
val effectiveWellExposedKey = lerp(
|
||||
fusionParameters.wellExposedKey,
|
||||
fusionParameters.riskyHighlightWellExposedKey,
|
||||
highlightRiskBand.strength,
|
||||
)
|
||||
val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / effectiveWellExposedKey)
|
||||
val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / fusionParameters.wellExposedKey)
|
||||
val darkestExposureGain = exposureGains.lastOrNull() ?: return 0f
|
||||
val tableInput = sceneInput * darkestExposureGain
|
||||
val highlightFusionStrength = smoothStep(
|
||||
highlightRiskBand.start,
|
||||
highlightRiskBand.end,
|
||||
fusionParameters.highlightFusionStart,
|
||||
fusionParameters.highlightFusionEnd,
|
||||
tableInput
|
||||
)
|
||||
var weightSum = 0f
|
||||
@@ -756,7 +698,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
internal data class HdrExposureFusionParameters(
|
||||
val autoExposureTarget: Float,
|
||||
val wellExposedKey: Float,
|
||||
val riskyHighlightWellExposedKey: Float = wellExposedKey,
|
||||
val maxExposureGain: Float,
|
||||
val compactHdrExposureOffsetEv: Float = -0.40f,
|
||||
val highlightFusionStart: Float = 0.45f,
|
||||
@@ -765,7 +706,6 @@ internal data class HdrExposureFusionParameters(
|
||||
init {
|
||||
require(autoExposureTarget.isFinite() && autoExposureTarget > 0f)
|
||||
require(wellExposedKey.isFinite() && wellExposedKey > 0f)
|
||||
require(riskyHighlightWellExposedKey.isFinite() && riskyHighlightWellExposedKey > 0f)
|
||||
require(maxExposureGain.isFinite() && maxExposureGain >= 1f)
|
||||
require(compactHdrExposureOffsetEv.isFinite())
|
||||
require(highlightFusionStart.isFinite() && highlightFusionStart in 0f..1f)
|
||||
@@ -773,9 +713,3 @@ internal data class HdrExposureFusionParameters(
|
||||
require(highlightFusionEnd > highlightFusionStart)
|
||||
}
|
||||
}
|
||||
|
||||
internal data class HdrHighlightRiskBand(
|
||||
val start: Float,
|
||||
val end: Float,
|
||||
val strength: Float,
|
||||
)
|
||||
@@ -37,7 +37,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
denseGlobalStats = globalStats,
|
||||
tablePointCount = tablePointCount,
|
||||
diagnosticBand = diagnosticBand,
|
||||
fusionParameters = PHOTON_FUSION_PARAMETERS,
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.nio.ByteBuffer
|
||||
* @param blackLevel 黑电平值数组 [R, Gr, Gb, B]
|
||||
* @param whiteBalance 白平衡增益 [R, Gr, Gb, B]
|
||||
* @param colorMatrix 色彩校正矩阵 (3x3 = 9个元素,行主序)
|
||||
* @param cameraWhite DNG SDK 色彩规格在当前白点下计算出的相机空间白色 [R, G, B]
|
||||
* @param rotation 旋转角度 (0, 90, 180, 270)
|
||||
* @param shadowScale DNG ShadowScale,用于 Adobe DefaultBlackRender Auto 的暗部黑点计算
|
||||
* @param lensShadingMap Lens Shading Map (LSC) 增益表,null表示无LSC数据
|
||||
@@ -40,6 +41,7 @@ data class DngRawData @Keep constructor(
|
||||
val preMul: FloatArray,
|
||||
val whiteBalance: FloatArray,
|
||||
val colorMatrix: FloatArray,
|
||||
val cameraWhite: FloatArray,
|
||||
val cfaPattern: Int, // 0..3=Bayer, 4..7=4x4 expanded Bayer, 8..11=8x8 expanded Bayer
|
||||
val rotation: Int,
|
||||
val baselineExposure: Float,
|
||||
@@ -100,6 +102,7 @@ data class DngRawData @Keep constructor(
|
||||
if (!preMul.contentEquals(other.preMul)) return false
|
||||
if (!whiteBalance.contentEquals(other.whiteBalance)) return false
|
||||
if (!colorMatrix.contentEquals(other.colorMatrix)) return false
|
||||
if (!cameraWhite.contentEquals(other.cameraWhite)) return false
|
||||
if (cfaPattern != other.cfaPattern) return false
|
||||
if (rotation != other.rotation) return false
|
||||
if (baselineExposure != other.baselineExposure) return false
|
||||
@@ -141,6 +144,7 @@ data class DngRawData @Keep constructor(
|
||||
result = 31 * result + preMul.contentHashCode()
|
||||
result = 31 * result + whiteBalance.contentHashCode()
|
||||
result = 31 * result + colorMatrix.contentHashCode()
|
||||
result = 31 * result + cameraWhite.contentHashCode()
|
||||
result = 31 * result + cfaPattern
|
||||
result = 31 * result + rotation
|
||||
result = 31 * result + baselineExposure.hashCode()
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
|
||||
/** CPU reference for the DNG SDK Camera RGB -> RIMM steps that precede PGTM. */
|
||||
internal object DngSdkProfileRgbTransform {
|
||||
fun fromCameraRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
colorCorrectionMatrix: FloatArray?,
|
||||
cameraWhite: FloatArray? = null,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): FloatArray {
|
||||
val white = sanitizedCameraWhite(cameraWhite)
|
||||
val cameraRed = min(red, white[0])
|
||||
val cameraGreen = min(green, white[1])
|
||||
val cameraBlue = min(blue, white[2])
|
||||
val matrix = colorCorrectionMatrix?.takeIf { it.size >= 9 }
|
||||
val profileRgb = if (matrix != null) {
|
||||
floatArrayOf(
|
||||
matrix[0] * cameraRed + matrix[1] * cameraGreen + matrix[2] * cameraBlue,
|
||||
matrix[3] * cameraRed + matrix[4] * cameraGreen + matrix[5] * cameraBlue,
|
||||
matrix[6] * cameraRed + matrix[7] * cameraGreen + matrix[8] * cameraBlue,
|
||||
)
|
||||
} else {
|
||||
floatArrayOf(cameraRed, cameraGreen, cameraBlue)
|
||||
}
|
||||
for (index in profileRgb.indices) {
|
||||
profileRgb[index] = profileRgb[index].takeIf { it.isFinite() }
|
||||
?.coerceIn(0f, 1f)
|
||||
?: 0f
|
||||
}
|
||||
return applyHueSatMap(profileRgb, hueSatMap)
|
||||
}
|
||||
|
||||
fun clampProfileRgb(red: Float, green: Float, blue: Float): FloatArray = floatArrayOf(
|
||||
red.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
green.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
blue.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
)
|
||||
|
||||
private fun sanitizedCameraWhite(cameraWhite: FloatArray?): FloatArray {
|
||||
if (cameraWhite == null || cameraWhite.size < 3) return floatArrayOf(1f, 1f, 1f)
|
||||
return FloatArray(3) { index ->
|
||||
cameraWhite[index].takeIf { it.isFinite() }?.coerceIn(0.001f, 1f) ?: 1f
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyHueSatMap(rgb: FloatArray, map: DcpHueSatMap?): FloatArray {
|
||||
val table = map?.takeIf { it.isValid } ?: return rgb
|
||||
val hsv = rgbToHsv(rgb)
|
||||
var encodedValue = hsv[2]
|
||||
var lookupValue = hsv[2]
|
||||
if (table.encoding == DcpHueSatMap.ENCODING_SRGB && table.valueDivisions > 1) {
|
||||
encodedValue = encodeScaledValue(hsv[2], table.encoding)
|
||||
lookupValue = encodeLookupValue(hsv[2], table.encoding)
|
||||
}
|
||||
val modify = sampleMap(
|
||||
table,
|
||||
hsv[0],
|
||||
hsv[1],
|
||||
lookupValue.coerceIn(0f, 1f),
|
||||
)
|
||||
hsv[0] = positiveModulo(hsv[0] + modify[0] * 6f / 360f, 6f)
|
||||
hsv[1] = (hsv[1] * modify[1]).coerceIn(0f, 1f)
|
||||
hsv[2] = decodeScaledValue((encodedValue * modify[2]).coerceIn(0f, 1f), table.encoding)
|
||||
return hsvToRgb(hsv)
|
||||
}
|
||||
|
||||
private fun sampleMap(map: DcpHueSatMap, hue: Float, saturation: Float, value: Float): FloatArray {
|
||||
val hScaled = hue * map.hueDivisions.toFloat() / 6f
|
||||
val sScaled = saturation * max(map.satDivisions - 1, 0).toFloat()
|
||||
val vScaled = value * max(map.valueDivisions - 1, 0).toFloat()
|
||||
var h0 = floor(hScaled).toInt()
|
||||
var h1 = h0 + 1
|
||||
if (h0 >= map.hueDivisions - 1) {
|
||||
h0 = map.hueDivisions - 1
|
||||
h1 = 0
|
||||
}
|
||||
val s0 = min(floor(sScaled).toInt(), max(map.satDivisions - 2, 0))
|
||||
val v0 = min(floor(vScaled).toInt(), max(map.valueDivisions - 2, 0))
|
||||
val s1 = min(s0 + 1, map.satDivisions - 1)
|
||||
val v1 = min(v0 + 1, map.valueDivisions - 1)
|
||||
val hf = hScaled - h0.toFloat()
|
||||
val sf = sScaled - s0.toFloat()
|
||||
val vf = vScaled - v0.toFloat()
|
||||
|
||||
fun entry(h: Int, s: Int, v: Int): FloatArray {
|
||||
val offset = ((v * map.hueDivisions + h) * map.satDivisions + s) * 3
|
||||
return floatArrayOf(map.values[offset], map.values[offset + 1], map.values[offset + 2])
|
||||
}
|
||||
|
||||
fun mix(first: FloatArray, second: FloatArray, amount: Float): FloatArray =
|
||||
FloatArray(3) { index -> first[index] + (second[index] - first[index]) * amount }
|
||||
|
||||
val p000 = mix(entry(h0, s0, v0), entry(h0, s0, v1), vf)
|
||||
val p001 = mix(entry(h1, s0, v0), entry(h1, s0, v1), vf)
|
||||
val p010 = mix(entry(h0, s1, v0), entry(h0, s1, v1), vf)
|
||||
val p011 = mix(entry(h1, s1, v0), entry(h1, s1, v1), vf)
|
||||
return mix(mix(p000, p001, hf), mix(p010, p011, hf), sf)
|
||||
}
|
||||
|
||||
private fun rgbToHsv(rgb: FloatArray): FloatArray {
|
||||
val maxValue = max(rgb[0], max(rgb[1], rgb[2]))
|
||||
val minValue = min(rgb[0], min(rgb[1], rgb[2]))
|
||||
val delta = maxValue - minValue
|
||||
val hue = if (delta <= 1e-6f) {
|
||||
0f
|
||||
} else when (maxValue) {
|
||||
rgb[0] -> positiveModulo((rgb[1] - rgb[2]) / delta, 6f)
|
||||
rgb[1] -> (rgb[2] - rgb[0]) / delta + 2f
|
||||
else -> (rgb[0] - rgb[1]) / delta + 4f
|
||||
}
|
||||
return floatArrayOf(hue, if (maxValue > 1e-6f) delta / maxValue else 0f, maxValue)
|
||||
}
|
||||
|
||||
private fun hsvToRgb(hsv: FloatArray): FloatArray {
|
||||
val hue = positiveModulo(hsv[0], 6f)
|
||||
val chroma = max(hsv[2], 0f) * max(hsv[1], 0f)
|
||||
val x = chroma * (1f - abs(positiveModulo(hue, 2f) - 1f))
|
||||
val base = when {
|
||||
hue < 1f -> floatArrayOf(chroma, x, 0f)
|
||||
hue < 2f -> floatArrayOf(x, chroma, 0f)
|
||||
hue < 3f -> floatArrayOf(0f, chroma, x)
|
||||
hue < 4f -> floatArrayOf(0f, x, chroma)
|
||||
hue < 5f -> floatArrayOf(x, 0f, chroma)
|
||||
else -> floatArrayOf(chroma, 0f, x)
|
||||
}
|
||||
val match = max(hsv[2], 0f) - chroma
|
||||
return FloatArray(3) { index -> base[index] + match }
|
||||
}
|
||||
|
||||
private fun encodeLookupValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) linearToSrgb(value.coerceIn(0f, 1f)) else value
|
||||
|
||||
private fun encodeScaledValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) linearToSrgb(max(value, 0f)) else max(value, 0f)
|
||||
|
||||
private fun decodeScaledValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) srgbToLinear(max(value, 0f)) else max(value, 0f)
|
||||
|
||||
private fun linearToSrgb(value: Float): Float = if (value <= 0.0031308f) {
|
||||
value * 12.92f
|
||||
} else {
|
||||
1.055f * value.toDouble().pow(1.0 / 2.4).toFloat() - 0.055f
|
||||
}
|
||||
|
||||
private fun srgbToLinear(value: Float): Float = if (value <= 0.04045f) {
|
||||
value / 12.92f
|
||||
} else {
|
||||
((value + 0.055f) / 1.055f).toDouble().pow(2.4).toFloat()
|
||||
}
|
||||
|
||||
private fun positiveModulo(value: Float, modulus: Float): Float {
|
||||
val result = value % modulus
|
||||
return if (result < 0f) result + modulus else result
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,10 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
samplesPerPixel: Int,
|
||||
statsBounds: Rect?,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
colorCorrectionMatrix: FloatArray = metadata.colorCorrectionMatrix,
|
||||
cameraWhite: FloatArray = metadata.cameraWhite,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
hueSatTextureId: Int = 0,
|
||||
): DngProfileGainTableMap? {
|
||||
if (statsProgram == 0 || rawTextureId == 0 || width <= 0 || height <= 0) return null
|
||||
if (profileToneMapMode != RawProfileToneMapMode.Photon &&
|
||||
@@ -100,9 +104,31 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
uniform("uColorCorrectionMatrix"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(metadata.colorCorrectionMatrix),
|
||||
transposeMatrix3x3(colorCorrectionMatrix),
|
||||
0
|
||||
)
|
||||
val safeCameraWhite = safeCameraWhite(cameraWhite)
|
||||
GLES31.glUniform3f(
|
||||
uniform("uCameraWhite"),
|
||||
safeCameraWhite[0],
|
||||
safeCameraWhite[1],
|
||||
safeCameraWhite[2],
|
||||
)
|
||||
val activeHueSatMap = hueSatMap?.takeIf { it.isValid && hueSatTextureId != 0 }
|
||||
GLES31.glUniform1i(uniform("uHueSatMapEnabled"), if (activeHueSatMap != null) 1 else 0)
|
||||
GLES31.glUniform3i(
|
||||
uniform("uHueSatMapDivisions"),
|
||||
activeHueSatMap?.hueDivisions ?: 1,
|
||||
activeHueSatMap?.satDivisions ?: 1,
|
||||
activeHueSatMap?.valueDivisions ?: 1,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
uniform("uHueSatMapEncoding"),
|
||||
activeHueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR,
|
||||
)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE1)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, hueSatTextureId)
|
||||
GLES31.glUniform1i(uniform("uHueSatMap"), 1)
|
||||
GLES31.glUniform1i(uniform("uCellSumsOffset"), cellSumsOffset)
|
||||
GLES31.glUniform1i(uniform("uGlobalHistogramOffset"), globalHistogramOffset)
|
||||
GLES31.glUniform1i(uniform("uGlobalCountersOffset"), globalCountersOffset)
|
||||
@@ -179,7 +205,6 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
denseGlobalStats = globalStats,
|
||||
diagnosticBand = diagnosticBand
|
||||
)
|
||||
|
||||
@@ -187,19 +212,6 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
RawProfileToneMapMode.OppoMaster -> null
|
||||
}
|
||||
val completeNs = System.nanoTime()
|
||||
if (map != null && profileToneMapMode == RawProfileToneMapMode.GooglePixel) {
|
||||
val risk = DngHdrProfileGainTableGenerator.highlightRiskBandFor(
|
||||
stats = globalStats,
|
||||
inputScale = map.mapInputWeights.sum(),
|
||||
)
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Google PGTM highlight risk: strength=${risk.strength} " +
|
||||
"tableBand=${risk.start}..${risk.end} p90=${globalStats.p90} " +
|
||||
"p98=${globalStats.p98} p995=${globalStats.p995} " +
|
||||
"p999=${globalStats.p999} fraction=${globalStats.highlightFraction}"
|
||||
)
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU RAW PGTM built: mode=$profileToneMapMode grid=${gridWidth}x${gridHeight} " +
|
||||
@@ -236,6 +248,13 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
return FloatArray(4) { index -> metadata.blackLevel.getOrElse(index) { fallback } }
|
||||
}
|
||||
|
||||
private fun safeCameraWhite(cameraWhite: FloatArray): FloatArray = FloatArray(3) { index ->
|
||||
cameraWhite.getOrElse(index) { 1f }
|
||||
.takeIf { it.isFinite() }
|
||||
?.coerceIn(0.001f, 1f)
|
||||
?: 1f
|
||||
}
|
||||
|
||||
private fun transposeMatrix3x3(matrix: FloatArray): FloatArray {
|
||||
if (matrix.size < 9) {
|
||||
return floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
|
||||
@@ -309,6 +328,11 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
uniform float uWhiteLevel;
|
||||
uniform float uBaselineExposureGain;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform sampler3D uHueSatMap;
|
||||
uniform int uHueSatMapEnabled;
|
||||
uniform ivec3 uHueSatMapDivisions;
|
||||
uniform int uHueSatMapEncoding;
|
||||
uniform int uCellSumsOffset;
|
||||
uniform int uGlobalHistogramOffset;
|
||||
uniform int uGlobalCountersOffset;
|
||||
@@ -332,6 +356,8 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
|
||||
shared float inputSamples[SAMPLE_COUNT];
|
||||
|
||||
${DcpHueSatMapGl.SHADER_FUNCTIONS}
|
||||
|
||||
int baseBayerPattern() {
|
||||
return uCfaPattern >= 8 ? uCfaPattern - 8 :
|
||||
(uCfaPattern >= 4 ? uCfaPattern - 4 : uCfaPattern);
|
||||
@@ -414,8 +440,17 @@ internal class GlesRawProfileGainTableMapBuilder {
|
||||
}
|
||||
|
||||
float pgtmInputAt(ivec2 base) {
|
||||
vec3 profileRgb = uColorCorrectionMatrix * cameraRgbAt(base) *
|
||||
uBaselineExposureGain;
|
||||
vec3 cameraRgb = min(cameraRgbAt(base), max(uCameraWhite, vec3(0.001)));
|
||||
vec3 profileRgb = clamp(uColorCorrectionMatrix * cameraRgb, vec3(0.0), vec3(1.0));
|
||||
if (uHueSatMapEnabled != 0) {
|
||||
profileRgb = dngApplyHueSatMap(
|
||||
profileRgb,
|
||||
uHueSatMap,
|
||||
uHueSatMapDivisions,
|
||||
uHueSatMapEncoding
|
||||
);
|
||||
}
|
||||
profileRgb *= uBaselineExposureGain;
|
||||
float minChannel = min(profileRgb.r, min(profileRgb.g, profileRgb.b));
|
||||
float maxChannel = max(profileRgb.r, max(profileRgb.g, profileRgb.b));
|
||||
float value =
|
||||
|
||||
@@ -12,6 +12,7 @@ import android.opengl.EGLSurface
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import androidx.core.graphics.createBitmap
|
||||
import com.hinnka.mycamera.BuildConfig
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.camera.RawBlackBorderCrop
|
||||
import com.hinnka.mycamera.data.ContentRepository
|
||||
@@ -99,6 +100,13 @@ class RawDemosaicProcessor {
|
||||
0.0f, 0.0f, 1.0f
|
||||
)
|
||||
}
|
||||
val cameraWhite = dngRawData.cameraWhite
|
||||
.takeIf { values ->
|
||||
values.size >= 3 && values.take(3).all { value -> value.isFinite() && value > 0f }
|
||||
}
|
||||
?.copyOf(3)
|
||||
?: baseMetadata?.cameraWhite
|
||||
?: floatArrayOf(1f, 1f, 1f)
|
||||
|
||||
val activeArray = if (dngRawData.activeArray != null && dngRawData.activeArray.size == 4) {
|
||||
Rect(
|
||||
@@ -123,7 +131,7 @@ class RawDemosaicProcessor {
|
||||
whiteBalanceGains = whiteBalanceGains,
|
||||
preMul = preMul,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = baseMetadata?.cameraWhite ?: floatArrayOf(1f, 1f, 1f),
|
||||
cameraWhite = cameraWhite,
|
||||
lensShadingMap = dngRawData.lensShadingMap,
|
||||
lensShadingMapWidth = dngRawData.lensShadingMapWidth,
|
||||
lensShadingMapHeight = dngRawData.lensShadingMapHeight,
|
||||
@@ -175,6 +183,7 @@ class RawDemosaicProcessor {
|
||||
private const val EGL_CONTEXT_PRIORITY_LEVEL_IMG = 0x3100
|
||||
private const val EGL_CONTEXT_PRIORITY_LOW_IMG = 0x3103
|
||||
private const val PROFILE_GAIN_TABLE_TEXTURE_UNIT = 2
|
||||
private const val LINEAR_DCP_HUE_SAT_TEXTURE_UNIT = 3
|
||||
private const val RCD_RAW_TEXTURE_UNIT = 0
|
||||
private const val RCD_LENS_SHADING_TEXTURE_UNIT = 1
|
||||
private const val RCD_OUTPUT_IMAGE_UNIT = 0
|
||||
@@ -1350,7 +1359,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation
|
||||
embeddedDngRenderPlan = if (hasClassicTiffHeader) {
|
||||
embeddedDngRenderPlan = if (hasClassicTiffHeader && !BuildConfig.DEBUG) {
|
||||
DngEmbeddedProfile.resolveRenderPlan(
|
||||
file = dngFile,
|
||||
metadata = actualMetadata,
|
||||
@@ -1590,6 +1599,19 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
rawTexturePreparedForPgtm = true
|
||||
val generationColorMatrix = resolvedDcpRenderPlan?.colorCorrectionMatrix
|
||||
?: actualMetadata.colorCorrectionMatrix
|
||||
val generationCameraWhite = resolvedDcpRenderPlan?.cameraWhite
|
||||
?: actualMetadata.cameraWhite
|
||||
val generationHueSatMap = resolvedDcpRenderPlan?.hueSatMap
|
||||
?.takeIf { it.isValid }
|
||||
val generationHueSatTextureId = generationHueSatMap?.let { map ->
|
||||
uploadDcp3DTexture(
|
||||
textureIdProvider = { dcpHueSatTextureId },
|
||||
assignTextureId = { dcpHueSatTextureId = it },
|
||||
table = map,
|
||||
)
|
||||
} ?: ensureDummyDcp3DTexture()
|
||||
rawProfileGainTableGpuBuilder.build(
|
||||
rawTextureId = rawTextureId,
|
||||
width = actualWidth,
|
||||
@@ -1597,7 +1619,11 @@ class RawDemosaicProcessor {
|
||||
metadata = actualMetadata,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
statsBounds = outputSourceBounds,
|
||||
profileToneMapMode = requestedProfileToneMapMode
|
||||
profileToneMapMode = requestedProfileToneMapMode,
|
||||
colorCorrectionMatrix = generationColorMatrix,
|
||||
cameraWhite = generationCameraWhite,
|
||||
hueSatMap = generationHueSatMap,
|
||||
hueSatTextureId = generationHueSatTextureId,
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
@@ -2226,6 +2252,7 @@ class RawDemosaicProcessor {
|
||||
"profileRampBlack=${profileExposureUniforms.rampBlack} " +
|
||||
"dngShadowScale=${actualMetadata.shadowScale} " +
|
||||
"dngBaselineExposure=${actualMetadata.baselineExposure} " +
|
||||
"linearCameraWhite=${linearCameraWhite.contentToString()} " +
|
||||
"dngBaselineExposureInLinear=$applyLinearDngBaselineExposure " +
|
||||
"profileGainTableMapActive=$hasProfileGainTableMap " +
|
||||
"dcpBaselineExposureOffsetApplied=$applyDcpBaselineExposureOffset"
|
||||
@@ -2244,6 +2271,7 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
applyDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
applyProfileGainTableMap = hasProfileGainTableMap,
|
||||
clampProfileRgb = useAdobeProfilePipeline,
|
||||
@@ -2373,6 +2401,7 @@ class RawDemosaicProcessor {
|
||||
metadata = actualMetadata,
|
||||
inputTextureId = combinedInputTexture,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = false,
|
||||
profileExposureUniforms = combinedProfileExposureUniforms,
|
||||
spectralFilmLut = spektrafilmLut,
|
||||
colorEngine = colorEngine,
|
||||
@@ -2927,6 +2956,7 @@ class RawDemosaicProcessor {
|
||||
|
||||
uniform sampler2D uDemosaickedTexture;
|
||||
uniform sampler2D uProfileGainTableMap;
|
||||
uniform sampler3D uLinearDcpHueSatMap;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform float uExposureGain;
|
||||
@@ -2939,6 +2969,11 @@ class RawDemosaicProcessor {
|
||||
uniform float uProfileGainGamma;
|
||||
uniform float uProfileGainBaselineGain;
|
||||
uniform int uProfileGainDebugOverlay;
|
||||
uniform int uLinearDcpHueSatEnabled;
|
||||
uniform ivec3 uLinearDcpHueSatDivisions;
|
||||
uniform int uLinearDcpHueSatEncoding;
|
||||
|
||||
${DcpHueSatMapGl.SHADER_FUNCTIONS}
|
||||
|
||||
float profileGainTableValue(int tableX, int tableY, float tableIndex) {
|
||||
int pointCount = max(uProfileGainTableSize.z, 1);
|
||||
@@ -3007,6 +3042,18 @@ class RawDemosaicProcessor {
|
||||
rgb = min(rgb, max(uCameraWhite, vec3(0.001)));
|
||||
}
|
||||
rgb = uColorCorrectionMatrix * rgb;
|
||||
if (uClampProfileRgb != 0) {
|
||||
// dng_reference::RefBaselineABCtoRGB pins RIMM before Hue/Sat Map and PGTM.
|
||||
rgb = clamp(rgb, vec3(0.0), vec3(1.0));
|
||||
}
|
||||
if (uLinearDcpHueSatEnabled != 0) {
|
||||
rgb = dngApplyHueSatMap(
|
||||
rgb,
|
||||
uLinearDcpHueSatMap,
|
||||
uLinearDcpHueSatDivisions,
|
||||
uLinearDcpHueSatEncoding
|
||||
);
|
||||
}
|
||||
vec3 profileInputRgb = rgb * uProfileGainBaselineGain;
|
||||
float tableInput = profileGainTableInput(profileInputRgb);
|
||||
rgb *= profileGain(profileInputRgb, tableInput);
|
||||
@@ -6100,8 +6147,12 @@ class RawDemosaicProcessor {
|
||||
return textureId
|
||||
}
|
||||
|
||||
private fun bindDcpCombinedResources(program: Int, dcpRenderPlan: DcpRenderPlan?) {
|
||||
val hueSatMap = dcpRenderPlan?.hueSatMap?.takeIf { it.isValid }
|
||||
private fun bindDcpCombinedResources(
|
||||
program: Int,
|
||||
dcpRenderPlan: DcpRenderPlan?,
|
||||
applyHueSatMap: Boolean,
|
||||
) {
|
||||
val hueSatMap = dcpRenderPlan?.hueSatMap?.takeIf { applyHueSatMap && it.isValid }
|
||||
val lookTable = dcpRenderPlan?.lookTable?.takeIf { it.isValid }
|
||||
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uDcpHueSatTexture"), 2)
|
||||
@@ -6277,6 +6328,7 @@ class RawDemosaicProcessor {
|
||||
metadata: RawMetadata,
|
||||
inputTextureId: Int = demosaicTextureId,
|
||||
dcpRenderPlan: DcpRenderPlan? = null,
|
||||
applyDcpHueSatMap: Boolean = true,
|
||||
spectralFilmLut: SpectralFilmLut? = null,
|
||||
colorEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
|
||||
outputWorkingColorSpace: ColorSpace = ColorSpace.ProPhoto,
|
||||
@@ -6294,6 +6346,7 @@ class RawDemosaicProcessor {
|
||||
if (!renderEngineTonePass(
|
||||
inputTextureId = inputTextureId,
|
||||
dcpRenderPlan = dcpRenderPlan,
|
||||
applyDcpHueSatMap = applyDcpHueSatMap,
|
||||
spectralFilmLut = spectralFilmLut,
|
||||
colorEngine = colorEngine,
|
||||
profileToEngineTransform = profileToEngineTransform,
|
||||
@@ -6341,6 +6394,7 @@ class RawDemosaicProcessor {
|
||||
private fun renderEngineTonePass(
|
||||
inputTextureId: Int,
|
||||
dcpRenderPlan: DcpRenderPlan?,
|
||||
applyDcpHueSatMap: Boolean,
|
||||
spectralFilmLut: SpectralFilmLut?,
|
||||
colorEngine: RawRenderingEngine,
|
||||
profileToEngineTransform: FloatArray,
|
||||
@@ -6374,7 +6428,7 @@ class RawDemosaicProcessor {
|
||||
|
||||
when (colorEngine) {
|
||||
RawRenderingEngine.AdobeCurve -> {
|
||||
bindDcpCombinedResources(program, dcpRenderPlan)
|
||||
bindDcpCombinedResources(program, dcpRenderPlan, applyDcpHueSatMap)
|
||||
bindProfileExposureUniforms(program, profileExposureUniforms)
|
||||
val baseCurve = dcpRenderPlan?.toneCurveLut ?: ACR3Curve.samples()
|
||||
bindCurveCombinedResource(program, baseCurve)
|
||||
@@ -7402,6 +7456,7 @@ class RawDemosaicProcessor {
|
||||
PLog.w(TAG, "RAW DCP render plan is not ProPhoto: planSpace=$planSpace")
|
||||
}
|
||||
val hueSatEnabled = dcpRenderPlan?.hueSatMap?.isValid == true
|
||||
val hueSatMap = dcpRenderPlan?.hueSatMap?.takeIf { it.isValid }
|
||||
val lookEnabled = dcpRenderPlan?.lookTable?.isValid == true
|
||||
val profileToneCurveEnabled = useAdobeProfilePipeline && dcpRenderPlan?.toneCurveLut != null
|
||||
val defaultBlackRender = dcpDefaultBlackRenderOrAuto(dcpRenderPlan)
|
||||
@@ -7421,7 +7476,10 @@ class RawDemosaicProcessor {
|
||||
"profileSpace=$profileWorkingColorSpace engineSpace=$engineWorkingColorSpace " +
|
||||
"requestedEngine=$requestedColorEngine actualEngine=$colorEngine " +
|
||||
"profileMapsBeforeEngine=$profileMapsBeforeEngine " +
|
||||
"hueSat=$hueSatEnabled look=$lookEnabled " +
|
||||
"hueSat=$hueSatEnabled " +
|
||||
"hueSatDims=${hueSatMap?.let { "${it.hueDivisions}x${it.satDivisions}x${it.valueDivisions}" } ?: "none"} " +
|
||||
"hueSatEncoding=${hueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR} " +
|
||||
"look=$lookEnabled " +
|
||||
"profileToneCurve=$profileToneCurveEnabled " +
|
||||
"profileExposureRamp=$useProfileExposureRamp " +
|
||||
"defaultBlackRender=$defaultBlackRender " +
|
||||
@@ -7521,6 +7579,7 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation: Float,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray = metadata.cameraWhite,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
applyDngBaselineExposure: Boolean,
|
||||
applyProfileGainTableMap: Boolean,
|
||||
clampProfileRgb: Boolean,
|
||||
@@ -7558,6 +7617,10 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation,
|
||||
applyDngBaselineExposure
|
||||
)
|
||||
bindLinearDcpHueSatMap(
|
||||
program = linearRcdProgram,
|
||||
hueSatMap = hueSatMap?.takeIf { clampProfileRgb },
|
||||
)
|
||||
bindProfileGainTableMapForLinearRcd(
|
||||
linearRcdProgram,
|
||||
metadata,
|
||||
@@ -7583,6 +7646,40 @@ class RawDemosaicProcessor {
|
||||
checkGlError("$label drawQuad")
|
||||
}
|
||||
|
||||
private fun bindLinearDcpHueSatMap(
|
||||
program: Int,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
) {
|
||||
val activeMap = hueSatMap?.takeIf { it.isValid }
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(program, "uLinearDcpHueSatEnabled"),
|
||||
if (activeMap != null) 1 else 0,
|
||||
)
|
||||
GLES30.glUniform3i(
|
||||
GLES30.glGetUniformLocation(program, "uLinearDcpHueSatDivisions"),
|
||||
activeMap?.hueDivisions ?: 1,
|
||||
activeMap?.satDivisions ?: 1,
|
||||
activeMap?.valueDivisions ?: 1,
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(program, "uLinearDcpHueSatEncoding"),
|
||||
activeMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR,
|
||||
)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
|
||||
val textureId = activeMap?.let { map ->
|
||||
uploadDcp3DTexture(
|
||||
textureIdProvider = { dcpHueSatTextureId },
|
||||
assignTextureId = { dcpHueSatTextureId = it },
|
||||
table = map,
|
||||
)
|
||||
} ?: ensureDummyDcp3DTexture()
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(program, "uLinearDcpHueSatMap"),
|
||||
LINEAR_DCP_HUE_SAT_TEXTURE_UNIT,
|
||||
)
|
||||
}
|
||||
|
||||
private fun bindProfileGainTableMapForLinearRcd(
|
||||
program: Int,
|
||||
metadata: RawMetadata,
|
||||
@@ -7763,6 +7860,7 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = dcpRenderPlan?.hueSatMap,
|
||||
applyDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
applyProfileGainTableMap = applyProfileGainTableMap,
|
||||
clampProfileRgb = clampProfileRgb,
|
||||
@@ -8164,6 +8262,7 @@ class RawDemosaicProcessor {
|
||||
metadata = metadata,
|
||||
inputTextureId = linearTextureId,
|
||||
dcpRenderPlan = dcpRenderPlan,
|
||||
applyDcpHueSatMap = false,
|
||||
spectralFilmLut = spectralFilmLut,
|
||||
colorEngine = colorEngine,
|
||||
outputWorkingColorSpace = outputWorkingColorSpace,
|
||||
|
||||
@@ -25,6 +25,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
samplesPerPixel: Int = 1,
|
||||
statsBounds: Rect? = null,
|
||||
profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon,
|
||||
colorCorrectionMatrix: FloatArray = metadata.colorCorrectionMatrix,
|
||||
cameraWhite: FloatArray = metadata.cameraWhite,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): DngProfileGainTableMap? {
|
||||
val stats = buildPackedCellStats(
|
||||
rawData = rawData,
|
||||
@@ -34,8 +37,10 @@ internal object RawProfileGainTableMapBuilder {
|
||||
metadata = metadata,
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
statsBounds = statsBounds,
|
||||
collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
profileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon
|
||||
) ?: return null
|
||||
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG)
|
||||
val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure)
|
||||
@@ -45,7 +50,6 @@ internal object RawProfileGainTableMapBuilder {
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = stats.packedCellStats,
|
||||
denseGlobalStats = stats.globalStats ?: return null,
|
||||
diagnosticBand = diagnosticBand
|
||||
)
|
||||
|
||||
@@ -71,6 +75,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
metadata: RawMetadata,
|
||||
samplesPerPixel: Int,
|
||||
statsBounds: Rect?,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
collectGlobalStats: Boolean,
|
||||
): BuiltPgtmStats? {
|
||||
if (width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) return null
|
||||
@@ -145,7 +152,10 @@ internal object RawProfileGainTableMapBuilder {
|
||||
baseX = x,
|
||||
baseY = y,
|
||||
baselineGain = baselineGain,
|
||||
samplesPerPixel = sampleCountPerPixel
|
||||
samplesPerPixel = sampleCountPerPixel,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
inputSamples[sampleCount] = inputValue
|
||||
if (globalSamples != null) {
|
||||
@@ -217,6 +227,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
baseY: Int,
|
||||
baselineGain: Float,
|
||||
samplesPerPixel: Int,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
if (samplesPerPixel >= 3) {
|
||||
return linearRgbPgtmInputAt(
|
||||
@@ -228,7 +241,10 @@ internal object RawProfileGainTableMapBuilder {
|
||||
x = baseX,
|
||||
y = baseY,
|
||||
baselineGain = baselineGain,
|
||||
samplesPerPixel = samplesPerPixel
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
var r = 0f
|
||||
@@ -269,7 +285,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = metadata.colorCorrectionMatrix
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -283,6 +301,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
y: Int,
|
||||
baselineGain: Float,
|
||||
samplesPerPixel: Int,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
val clampedX = x.coerceIn(0, width - 1)
|
||||
val clampedY = y.coerceIn(0, height - 1)
|
||||
@@ -295,7 +316,9 @@ internal object RawProfileGainTableMapBuilder {
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = metadata.colorCorrectionMatrix
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -305,13 +328,17 @@ internal object RawProfileGainTableMapBuilder {
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
colorCorrectionMatrix: FloatArray?,
|
||||
cameraWhite: FloatArray?,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
return DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -103,85 +103,7 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun denseSceneStatsMatchOfficial184953HighlightShoulder() {
|
||||
val fixture = loadFixture(
|
||||
"/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture"
|
||||
)
|
||||
val map = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = fixture.width,
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = fixture.packedStats,
|
||||
denseGlobalStats = DngPgtmGlobalStats(
|
||||
p10 = 0.005191058f,
|
||||
p50 = 0.018155192f,
|
||||
p90 = 0.551834350f,
|
||||
p98 = 1.162652485f,
|
||||
p995 = 3.329099033f,
|
||||
p999 = 8.389943569f,
|
||||
maxInput = 8.389943569f,
|
||||
highlightFraction = 0.034409841f,
|
||||
linearMean = 0.206666246f,
|
||||
logAverage = 0.039490954f,
|
||||
shadowEdge = 0.005191058f,
|
||||
shadowFoot = 0.005191058f,
|
||||
sampleCount = 786_432,
|
||||
),
|
||||
) ?: error("Expected Google PGTM for ${fixture.sourceName}")
|
||||
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())
|
||||
val trustedShoulderResults = trustedShoulderCells.map { cell ->
|
||||
val p999 = fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999]
|
||||
val expectedOutput = p999 * expectedSpecular[cell]
|
||||
val actualOutput = p999 * actualSpecular[cell]
|
||||
TrustedShoulderResult(cell, p999, expectedOutput, actualOutput)
|
||||
}
|
||||
|
||||
val fixedShoulderResults = listOf(
|
||||
FixedShoulderReference(tableInput = 0.25f, officialMedianGain = 0.915178f),
|
||||
FixedShoulderReference(tableInput = 0.50f, officialMedianGain = 0.544002f),
|
||||
FixedShoulderReference(tableInput = 0.75f, officialMedianGain = 0.395906f),
|
||||
).map { reference ->
|
||||
val actualMedianGain = percentile(
|
||||
FloatArray(fixture.cellCount) { cell ->
|
||||
sampleGain(map, reference.tableInput, cell)
|
||||
},
|
||||
0.50f,
|
||||
)
|
||||
FixedShoulderResult(
|
||||
reference = reference,
|
||||
actualMedianGain = actualMedianGain,
|
||||
)
|
||||
}
|
||||
assertTrue(
|
||||
trustedShoulderResults.joinToString("\n") { result ->
|
||||
"cell=${result.cell} p999=${result.p999} expectedOutput=" +
|
||||
"${result.expectedOutput} actualOutput=${result.actualOutput}"
|
||||
} + "\n" + fixedShoulderResults.joinToString("\n") { result ->
|
||||
"tableInput=${result.reference.tableInput} officialMedianGain=" +
|
||||
"${result.reference.officialMedianGain} " +
|
||||
"actualMedianGain=${result.actualMedianGain}"
|
||||
},
|
||||
trustedShoulderResults.all { result ->
|
||||
result.actualOutput + 0.025f >= result.expectedOutput
|
||||
} &&
|
||||
fixedShoulderResults.all { result ->
|
||||
abs(result.actualMedianGain - result.reference.officialMedianGain) <= 0.03f
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun denseSceneRiskPreservesOfficialShouldersAcrossSkyykingSet() {
|
||||
fun fixedFusionPreservesOfficialShouldersAcrossSkyykingSet() {
|
||||
val fixturesByName = loadFixtures().associateBy { it.sourceName }
|
||||
val results = denseShoulderCases().flatMap { case ->
|
||||
val fixture = fixturesByName[case.name] ?: error("Missing fixture ${case.name}")
|
||||
@@ -190,7 +112,6 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = fixture.packedStats,
|
||||
denseGlobalStats = case.globalStats,
|
||||
) ?: error("Expected Google PGTM for ${case.name}")
|
||||
listOf(0.25f, 0.50f, 0.75f).mapIndexed { index, tableInput ->
|
||||
val actual = percentile(
|
||||
@@ -215,36 +136,6 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun denseTailRiskSeparatesSparseOutliersFromSupportedHighlights() {
|
||||
val fixturesByName = loadFixtures().associateBy { it.sourceName }
|
||||
val casesByName = denseShoulderCases().associateBy { it.name }
|
||||
|
||||
fun risk(name: String): HdrHighlightRiskBand {
|
||||
val fixture = fixturesByName[name] ?: error("Missing fixture $name")
|
||||
val case = casesByName[name] ?: error("Missing dense stats $name")
|
||||
return DngHdrProfileGainTableGenerator.highlightRiskBandFor(
|
||||
stats = case.globalStats,
|
||||
inputScale = fixture.inputScale,
|
||||
)
|
||||
}
|
||||
|
||||
val sparseBrokenTail = risk("Skyyking_20260711_184953.RAW-02.ORIGINAL")
|
||||
val denseSupportedHighlights = risk("Skyyking_20260711_185704.RAW-02.ORIGINAL")
|
||||
val continuousTail = risk("Skyyking_20260711_184627.RAW-02.ORIGINAL")
|
||||
|
||||
assertTrue("sparseBrokenTail=$sparseBrokenTail", sparseBrokenTail.strength > 0.99f)
|
||||
assertTrue(
|
||||
"sparseBrokenTail=$sparseBrokenTail",
|
||||
sparseBrokenTail.start in 0.17f..0.18f && sparseBrokenTail.end in 0.36f..0.37f,
|
||||
)
|
||||
assertTrue(
|
||||
"denseSupportedHighlights=$denseSupportedHighlights",
|
||||
denseSupportedHighlights.strength < 0.01f,
|
||||
)
|
||||
assertTrue("continuousTail=$continuousTail", continuousTail.strength < 0.01f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun generatedMapsMatchEmbeddedSemanticToneDistributions() {
|
||||
val failures = mutableListOf<String>()
|
||||
@@ -464,54 +355,26 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
|
||||
private fun denseShoulderCases(): List<DenseShoulderCase> = listOf(
|
||||
denseShoulderCase("Skyyking_20260711_184627.RAW-02.ORIGINAL", 0.020172335f, 0.124901251f, 0.875294007f, 5.471382292f, 10.767577893f, 14.655574315f, 20.611095419f, 0.099154154f, 0.499043244f, 0.125733883f, 0.331765622f, 0.205544580f, 0.152909992f),
|
||||
denseShoulderCase("Skyyking_20260711_184751.RAW-02.ORIGINAL", 0.061056067f, 0.314396789f, 1.012212430f, 1.605002744f, 2.246847243f, 3.700378549f, 4.366255744f, 0.124490102f, 0.437985919f, 0.264671714f, 0.462672237f, 0.337412789f, 0.272237092f),
|
||||
denseShoulderCase("Skyyking_20260711_184953.RAW-02.ORIGINAL", 0.005191058f, 0.018155192f, 0.551834350f, 1.162652485f, 3.329099033f, 8.389943569f, 8.389943569f, 0.034409841f, 0.206666246f, 0.039490954f, 0.915177912f, 0.544002324f, 0.395905923f),
|
||||
denseShoulderCase("Skyyking_20260711_185653.RAW-02.ORIGINAL", 0.370311566f, 2.512482396f, 3.813213919f, 5.120475517f, 5.567614998f, 5.790177933f, 38.276195401f, 0.746487935f, 2.251304119f, 1.571741688f, 0.213499438f, 0.181819726f, 0.162513237f),
|
||||
denseShoulderCase("Skyyking_20260711_185704.RAW-02.ORIGINAL", 0.145013743f, 0.316054048f, 3.469537212f, 8.847691807f, 14.915796129f, 29.121761960f, 29.121761960f, 0.301193237f, 1.294745890f, 0.479610381f, 0.163654307f, 0.101506390f, 0.075539880f),
|
||||
denseShoulderCase("Skyyking_20260711_185836.RAW-02.ORIGINAL", 0.012206823f, 0.126480593f, 0.355587152f, 0.432792685f, 0.462650502f, 0.493159692f, 2.637294839f, 0.000026703f, 0.156404806f, 0.089910030f, 0.522830814f, 0.433588199f, 0.374911249f),
|
||||
denseShoulderCase("Skyyking_20260712_105529.RAW-02.ORIGINAL", 0.010147940f, 0.107563684f, 1.562283487f, 4.157630135f, 6.125361249f, 8.462417930f, 18.567126558f, 0.154716492f, 0.510046194f, 0.124380931f, 0.332546350f, 0.203987684f, 0.150961947f),
|
||||
denseShoulderCase("Skyyking_20260713_232945.RAW-02.ORIGINAL", 0.038518862f, 0.254915462f, 0.947498705f, 1.376204882f, 1.562541283f, 1.695016885f, 6.936506958f, 0.107442220f, 0.378671069f, 0.221436961f, 0.504472025f, 0.425721936f, 0.372749154f),
|
||||
denseShoulderCase("Skyyking_20260714_083737.RAW-02.ORIGINAL", 0.003378016f, 0.008042096f, 0.294214780f, 4.110145986f, 5.340132478f, 5.523095724f, 5.645071221f, 0.037193298f, 0.192204495f, 0.017270404f, 0.735527232f, 0.438027993f, 0.319880389f),
|
||||
denseShoulderCase("Skyyking_20260714_092416.RAW-02.ORIGINAL", 0.004266809f, 0.063950656f, 2.126153418f, 3.981748021f, 4.972982040f, 6.020569097f, 20.924798021f, 0.187920888f, 0.539285387f, 0.071365597f, 0.243842043f, 0.142250773f, 0.102864855f),
|
||||
denseShoulderCase("Skyyking_20260714_123251.RAW-02.ORIGINAL", 0.017058925f, 0.120602039f, 0.471383246f, 4.107495723f, 7.774886715f, 20.029784120f, 20.287619715f, 0.045697530f, 0.362590556f, 0.109233882f, 0.259386316f, 0.154736947f, 0.113109255f),
|
||||
denseShoulderCase("Skyyking_20260714_151021.RAW-02.ORIGINAL", 0.005190248f, 0.084016346f, 0.313368077f, 2.072844313f, 4.232514755f, 7.760019339f, 10.563597493f, 0.050816854f, 0.222183756f, 0.064319970f, 0.411366213f, 0.272355564f, 0.209032677f),
|
||||
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),
|
||||
)
|
||||
|
||||
private fun denseShoulderCase(
|
||||
name: String,
|
||||
p10: Float,
|
||||
p50: Float,
|
||||
p90: Float,
|
||||
p98: Float,
|
||||
p995: Float,
|
||||
p999: Float,
|
||||
maxInput: Float,
|
||||
highlightFraction: Float,
|
||||
linearMean: Float,
|
||||
logAverage: Float,
|
||||
gain25: Float,
|
||||
gain50: Float,
|
||||
gain75: Float,
|
||||
) = DenseShoulderCase(
|
||||
name = name,
|
||||
globalStats = DngPgtmGlobalStats(
|
||||
p10 = p10,
|
||||
p50 = p50,
|
||||
p90 = p90,
|
||||
p98 = p98,
|
||||
p995 = p995,
|
||||
p999 = p999,
|
||||
maxInput = maxInput,
|
||||
highlightFraction = highlightFraction,
|
||||
linearMean = linearMean,
|
||||
logAverage = logAverage,
|
||||
shadowEdge = p10,
|
||||
shadowFoot = p10,
|
||||
sampleCount = 786_432,
|
||||
),
|
||||
officialMedianGains = floatArrayOf(gain25, gain50, gain75),
|
||||
)
|
||||
) = DenseShoulderCase(name, floatArrayOf(gain25, gain50, gain75))
|
||||
|
||||
private fun loadFixtures(): List<PgtmFixture> = FIXTURE_RESOURCES.map(::loadFixture)
|
||||
|
||||
@@ -579,26 +442,8 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
val inputScale: Float get() = inputWeights.sum()
|
||||
}
|
||||
|
||||
private data class FixedShoulderReference(
|
||||
val tableInput: Float,
|
||||
val officialMedianGain: Float,
|
||||
)
|
||||
|
||||
private data class FixedShoulderResult(
|
||||
val reference: FixedShoulderReference,
|
||||
val actualMedianGain: Float,
|
||||
)
|
||||
|
||||
private data class TrustedShoulderResult(
|
||||
val cell: Int,
|
||||
val p999: Float,
|
||||
val expectedOutput: Float,
|
||||
val actualOutput: Float,
|
||||
)
|
||||
|
||||
private data class DenseShoulderCase(
|
||||
val name: String,
|
||||
val globalStats: DngPgtmGlobalStats,
|
||||
val officialMedianGains: FloatArray,
|
||||
)
|
||||
|
||||
|
||||
@@ -28,7 +28,6 @@ class DngPhotonProfileGainTableGeneratorTest {
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = fixture.packedStats,
|
||||
denseGlobalStats = fixture.globalStats,
|
||||
fusionParameters = DngPhotonProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS,
|
||||
) ?: error("Expected direct Google PGTM")
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class DngSdkProfileRgbTransformTest {
|
||||
@Test
|
||||
fun cameraWhiteAndRimmClampMatchBaselineAbcToRgbOrder() {
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.9f,
|
||||
green = 0.9f,
|
||||
blue = 0.9f,
|
||||
colorCorrectionMatrix = floatArrayOf(
|
||||
3f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 2f,
|
||||
),
|
||||
cameraWhite = floatArrayOf(0.5f, 1f, 0.75f),
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(1f, 0.9f, 1f), rgb, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun neutralOverrangeIsClampedBeforeCompressivePgtmGain() {
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 1f,
|
||||
green = 1f,
|
||||
blue = 1f,
|
||||
colorCorrectionMatrix = floatArrayOf(
|
||||
1.35f, 0f, 0f,
|
||||
0f, 0.96f, 0f,
|
||||
0f, 0f, 1.28f,
|
||||
),
|
||||
)
|
||||
val gain = 0.45f
|
||||
val output = FloatArray(3) { index -> rgb[index] * gain }
|
||||
|
||||
assertArrayEquals(floatArrayOf(0.45f, 0.432f, 0.45f), output, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun identityHueSatMapKeepsProfileRgbUnchanged() {
|
||||
val identityMap = DcpHueSatMap(
|
||||
hueDivisions = 1,
|
||||
satDivisions = 1,
|
||||
valueDivisions = 1,
|
||||
values = floatArrayOf(0f, 1f, 1f),
|
||||
)
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.72f,
|
||||
green = 0.41f,
|
||||
blue = 0.18f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
hueSatMap = identityMap,
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(0.72f, 0.41f, 0.18f), rgb, 1e-5f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun srgbEncodedTwoPointFiveDimensionalMapKeepsValueLinearUntilScale() {
|
||||
val map = DcpHueSatMap(
|
||||
hueDivisions = 1,
|
||||
satDivisions = 1,
|
||||
valueDivisions = 1,
|
||||
values = floatArrayOf(0f, 1f, 0.5f),
|
||||
encoding = DcpHueSatMap.ENCODING_SRGB,
|
||||
)
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.8f,
|
||||
green = 0.4f,
|
||||
blue = 0.2f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
hueSatMap = map,
|
||||
)
|
||||
val sdkDecodedValue = srgbToLinear(0.4f)
|
||||
|
||||
assertArrayEquals(
|
||||
floatArrayOf(sdkDecodedValue, sdkDecodedValue * 0.5f, sdkDecodedValue * 0.25f),
|
||||
rgb,
|
||||
1e-5f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun baselineExposureScalesOnlyClampedFiveWeightInput() {
|
||||
val input = DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = 2f,
|
||||
green = 3f,
|
||||
blue = 4f,
|
||||
baselineGain = 2f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
)
|
||||
|
||||
assertEquals(2f, input, 1e-6f)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val IDENTITY_MATRIX = floatArrayOf(
|
||||
1f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 1f,
|
||||
)
|
||||
|
||||
fun srgbToLinear(value: Float): Float = if (value <= 0.04045f) {
|
||||
value / 12.92f
|
||||
} else {
|
||||
Math.pow(((value + 0.055f) / 1.055f).toDouble(), 2.4).toFloat()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user