feat: implement highlight rolloff and optimize RAW processing performance

This commit is contained in:
Hinnka committed 2026-05-24 23:00:45 +08:00
1 parent 196678d637
commit 4a702d2bd0
6 files changed
+429 -123

No files matched your search

+2 -1
View File
@@ -1,2 +1,3 @@
1. 查阅 AGENTS.md
2. 多文件修改必须编译后再交付
2. 多文件修改必须编译后再交付
3. 禁止使用git进行任何破坏性变更,包括但不限于git checkout/git restore/git rm
+3 -32
View File
@@ -54,38 +54,9 @@ vec3 sanitizeRgb(vec3 rgb) {
}
vec4 sampleBicubic(sampler2D s, vec2 uv, vec2 size) {
vec2 texelPos = uv * size - 0.5;
ivec2 base = ivec2(floor(texelPos));
vec2 f = texelPos - vec2(base);
float wx[4];
float wy[4];
float fx = f.x;
float fy = f.y;
wx[0] = -0.5 * fx + fx * fx - 0.5 * fx * fx * fx;
wx[1] = 1.0 - 2.5 * fx * fx + 1.5 * fx * fx * fx;
wx[2] = 0.5 * fx + 2.0 * fx * fx - 1.5 * fx * fx * fx;
wx[3] = -0.5 * fx * fx + 0.5 * fx * fx * fx;
wy[0] = -0.5 * fy + fy * fy - 0.5 * fy * fy * fy;
wy[1] = 1.0 - 2.5 * fy * fy + 1.5 * fy * fy * fy;
wy[2] = 0.5 * fy + 2.0 * fy * fy - 1.5 * fy * fy * fy;
wy[3] = -0.5 * fy * fy + 0.5 * fy * fy * fy;
vec4 accum = vec4(0.0);
float weightSum = 0.0;
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 4; ++i) {
ivec2 p = base + ivec2(i - 1, j - 1);
p = clamp(p, ivec2(0), ivec2(size) - ivec2(1));
float w = wx[i] * wy[j];
accum += vec4(sanitizeRgb(texelFetch(s, p, 0).rgb), 1.0) * w;
weightSum += w;
}
}
vec4 color = (abs(weightSum) > 1e-6) ? (accum / weightSum) : accum;
return vec4(sanitizeRgb(color.rgb), 1.0);
// Redefined to use hardware-accelerated bilinear filtering (texture)
// to resolve the 500+ texelFetch software instruction bottleneck.
return vec4(sanitizeRgb(texture(s, uv).rgb), 1.0);
}
vec3 rgb2ycbcr(vec3 rgb) {
@@ -166,6 +166,7 @@ class RawDemosaicProcessor {
// GL 资源
private var combinedProgram = 0
private var highlightBaseProgram = 0
private var sharpenProgram = 0
private var passthroughProgram = 0
private var hdrReferenceProgram = 0
@@ -196,6 +197,16 @@ class RawDemosaicProcessor {
private var combinedWidth = 0
private var combinedHeight = 0
private var linearMeteringFramebufferId = 0
private var linearMeteringTextureId = 0
private var linearMeteringWidth = 0
private var linearMeteringHeight = 0
private var highlightBaseFramebufferId = 0
private var highlightBaseTextureId = 0
private var highlightBaseWidth = 0
private var highlightBaseHeight = 0
private var hdrReferenceFramebufferId = 0
private var hdrReferenceTextureId = 0
private var hdrReferenceWidth = 0
@@ -570,7 +581,7 @@ class RawDemosaicProcessor {
// GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB)
actualRawData = null
var shadowLift = 0f
var highlightWhitePoint = 0f
var effectiveExposureCompensation = rawExposureCompensation
// Bayer RCD Compute Shader 处理路径 (1:1 直接映射自 darktable RCD)
@@ -700,20 +711,26 @@ class RawDemosaicProcessor {
// 处理自动曝光测光
if (rawAutoExposure) {
val droEv = when (rawDROMode) {
DROMode.DR200 -> 1f
DROMode.DR400 -> 2f
else -> 0f
}
effectiveExposureCompensation += droEv
val meteringResult = resolveRawAutoExposureEv(
context = context,
metadata = actualMetadata,
sourceTextureId = demosaicTextureId,
meteringExposureCompensation = effectiveExposureCompensation,
rawDROMode = rawDROMode,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan
)
val autoExposureEv = meteringResult.meteredEv
if (rawDROMode.isEnabled && autoExposureEv > 0f && meteringResult.dynamicRangeGap > 1.2f) {
val maxLinearGainEv = ln(1.0f / meteringResult.p998.coerceAtLeast(0.01f)) / ln(2.0f)
val linearEv = autoExposureEv.coerceAtMost(maxLinearGainEv).coerceAtLeast(0f)
val remainingEv = autoExposureEv - linearEv
shadowLift = ((2.0f.pow(remainingEv) - 1.0f) / 0.67f).coerceIn(0f, 5.0f)
effectiveExposureCompensation += linearEv
if (rawDROMode.isEnabled && autoExposureEv > 0f) {
effectiveExposureCompensation += autoExposureEv
highlightWhitePoint = meteringResult.p998 * 2f.pow(effectiveExposureCompensation)
} else {
effectiveExposureCompensation += autoExposureEv
}
@@ -722,41 +739,18 @@ class RawDemosaicProcessor {
// 运行 linearRcdProgram 将 CCM & Exposure 应用在已解马赛克的浮点 RCD 图像上
checkGlError("Before LinearRcdPass")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearOutputFramebufferId)
checkGlError("LinearRcdPass setup framebuffer")
GLES30.glUseProgram(linearRcdProgram)
GLES30.glViewport(0, 0, actualWidth, actualHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, demosaicTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(linearRcdProgram, "uDemosaickedTexture"), 0)
val transposedCCM = transposeMatrix3x3(resolvedDcpRenderPlan?.colorCorrectionMatrix ?: actualMetadata.colorCorrectionMatrix)
GLES30.glUniformMatrix3fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uColorCorrectionMatrix"),
1, false, transposedCCM, 0
renderLinearRcdPass(
metadata = actualMetadata,
sourceTextureId = demosaicTextureId,
targetFramebufferId = linearOutputFramebufferId,
viewportWidth = actualWidth,
viewportHeight = actualHeight,
rawExposureCompensation = effectiveExposureCompensation,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan,
label = "LinearRcdPass"
)
val exposureGain = computeLinearExposureGain(actualMetadata, effectiveExposureCompensation, resolvedDcpRenderPlan)
GLES30.glUniform1f(GLES30.glGetUniformLocation(linearRcdProgram, "uExposureGain"), exposureGain)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(linearRcdProgram, "uBlackPoint"),
rawBlackPointCorrection.coerceIn(0f, 0.99f)
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(linearRcdProgram, "uWhitePoint"),
(1f + rawWhitePointCorrection).coerceAtLeast(rawBlackPointCorrection.coerceIn(0f, 0.99f) + 0.01f)
)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
drawQuad(linearRcdProgram)
checkGlError("LinearRcdPass drawQuad")
// 重点:使用双缓冲交换 (Swap),既不销毁任何纹理,也不需要 glGenTextures/glDeleteTextures
val tempTex = demosaicTextureId
@@ -837,13 +831,19 @@ class RawDemosaicProcessor {
}
// 5. 第二步:Combined Pass (HDR Linear -> LDR sRGB + LUT)
setupHighlightBaseFramebuffer(actualWidth, actualHeight)
renderHighlightBasePass(
metadata = actualMetadata,
inputTextureId = outputTexture
)
setupCombinedFramebuffer(actualWidth, actualHeight)
val combinedStart = System.currentTimeMillis()
renderCombinedPass(
metadata = actualMetadata,
inputTextureId = outputTexture,
dcpRenderPlan = resolvedDcpRenderPlan,
shadowLift = shadowLift
highlightWhitePoint = highlightWhitePoint,
highlightBaseTextureId = highlightBaseTextureId
)
PLog.d(TAG, "Combined Pass took: ${System.currentTimeMillis() - combinedStart}ms")
// outputTexture 已被 combinedPass 消费,提前释放
@@ -990,13 +990,13 @@ class RawDemosaicProcessor {
// 初始化着色器和缓冲区
initShaderProgram()
if (combinedProgram == 0 || sharpenProgram == 0 || passthroughProgram == 0 ||
if (combinedProgram == 0 || highlightBaseProgram == 0 || sharpenProgram == 0 || passthroughProgram == 0 ||
rcdPopulateProgram == 0 || rcdStep1Program == 0 || rcdStep2Program == 0 ||
rcdStep3Program == 0 || rcdStep40Program == 0 || rcdStep41Program == 0 ||
rcdStep42Program == 0 || rcdStep43Program == 0 || rcdWriteOutputProgram == 0 ||
linearRcdProgram == 0) {
PLog.e(TAG, "Critical shader programs failed to compile or link. " +
"combined=$combinedProgram sharpen=$sharpenProgram pass=$passthroughProgram " +
"combined=$combinedProgram highlightBase=$highlightBaseProgram sharpen=$sharpenProgram pass=$passthroughProgram " +
"populate=$rcdPopulateProgram step1=$rcdStep1Program step2=$rcdStep2Program " +
"step3=$rcdStep3Program step40=$rcdStep40Program step41=$rcdStep41Program " +
"step42=$rcdStep42Program step43=$rcdStep43Program write=$rcdWriteOutputProgram " +
@@ -1044,6 +1044,19 @@ class RawDemosaicProcessor {
GLES30.glDeleteShader(fShaderCombined)
}
val fShaderHighlightBase = compileShader(GLES30.GL_FRAGMENT_SHADER, RawShaders.HIGHLIGHT_BASE_FRAGMENT_SHADER)
if (vShader != 0 && fShaderHighlightBase != 0) {
highlightBaseProgram = GLES30.glCreateProgram()
GLES30.glAttachShader(highlightBaseProgram, vShader)
GLES30.glAttachShader(highlightBaseProgram, fShaderHighlightBase)
GLES30.glLinkProgram(highlightBaseProgram)
if (!logProgramLinkResult(highlightBaseProgram, "highlightBaseProgram")) {
highlightBaseProgram = 0
}
GLES30.glDeleteShader(fShaderHighlightBase)
}
val fShaderHdrReference = compileShader(GLES30.GL_FRAGMENT_SHADER, RawShaders.HDR_REFERENCE_FRAGMENT_SHADER)
if (vShader != 0 && fShaderHdrReference != 0) {
hdrReferenceProgram = GLES30.glCreateProgram()
@@ -2039,6 +2052,89 @@ class RawDemosaicProcessor {
checkGlError("setupCombinedFramebuffer")
}
private fun setupLinearMeteringFramebuffer(width: Int, height: Int) {
if (linearMeteringWidth == width && linearMeteringHeight == height && linearMeteringFramebufferId != 0) {
return
}
if (linearMeteringTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(linearMeteringTextureId), 0)
}
if (linearMeteringFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(linearMeteringFramebufferId), 0)
}
linearMeteringWidth = width
linearMeteringHeight = height
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
linearMeteringTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, linearMeteringTextureId)
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
linearMeteringFramebufferId = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearMeteringFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
linearMeteringTextureId,
0
)
checkGlError("setupLinearMeteringFramebuffer")
}
private fun setupHighlightBaseFramebuffer(sourceWidth: Int, sourceHeight: Int) {
val width = maxOf(1, sourceWidth / 16)
val height = maxOf(1, sourceHeight / 16)
if (highlightBaseWidth == width && highlightBaseHeight == height && highlightBaseFramebufferId != 0) {
return
}
if (highlightBaseTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(highlightBaseTextureId), 0)
}
if (highlightBaseFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(highlightBaseFramebufferId), 0)
}
highlightBaseWidth = width
highlightBaseHeight = height
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
highlightBaseTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highlightBaseTextureId)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, width, height, 0,
GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
highlightBaseFramebufferId = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, highlightBaseFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
highlightBaseTextureId,
0
)
checkGlError("setupHighlightBaseFramebuffer")
}
private fun setupHdrReferenceFramebuffer(width: Int, height: Int) {
if (hdrReferenceWidth == width && hdrReferenceHeight == height && hdrReferenceFramebufferId != 0) {
return
@@ -2408,7 +2504,6 @@ class RawDemosaicProcessor {
checkGlError("bindDcpCombinedResources")
}
/**
* Combined Processing Pass: ToneMap + LUT + Sharpening
*/
@@ -2418,28 +2513,10 @@ class RawDemosaicProcessor {
dcpRenderPlan: DcpRenderPlan? = null,
viewportWidth: Int = metadata.width,
viewportHeight: Int = metadata.height,
shadowLift: Float = 0f
highlightWhitePoint: Float = 0f,
highlightBaseTextureId: Int = 0
) {
val baseCurve = dcpRenderPlan?.toneCurveLut ?: ACR3Curve.samples()
val combinedLut = if (shadowLift > 0f) {
FloatArray(baseCurve.size) { i ->
val v = baseCurve[i]
val x = shadowLift.coerceIn(0f, 5f)
val boost = smoothstep(1f, 5f, x)
val gammaPower = 0.75f + 0.13f * boost
val shadowRangeEnd = 0.6f + 0.25f * boost
val liftStrength = 1.35f - 0.25f * boost
val blackProtectStart = 0.02f
val black = 0.004f
val liftBase = (v.pow(gammaPower) - v).coerceAtLeast(0f)
val shadowMask = smoothstep(shadowRangeEnd, 0.02f, v)
val blackProtect = smoothstep(black, blackProtectStart, v)
val lift = x * liftBase * liftStrength * shadowMask * blackProtect
(v + lift - black).coerceIn(0f, 1f)
}
} else {
baseCurve
}
val outputTransform = computeWorkingToOutputTransform(ColorSpace.ProPhoto, ColorSpace.SRGB)
GLES30.glUseProgram(combinedProgram)
@@ -2456,17 +2533,28 @@ class RawDemosaicProcessor {
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
uploadCurveTexture(combinedLut)
uploadCurveTexture(baseCurve)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uCurveTexture"), 1)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(combinedProgram, "uCurveSize"),
combinedLut.size.toFloat()
baseCurve.size.toFloat()
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(combinedProgram, "uCurveEnabled"),
1
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(combinedProgram, "uHighlightWhitePoint"),
highlightWhitePoint
)
GLES30.glActiveTexture(GLES30.GL_TEXTURE5)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highlightBaseTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(combinedProgram, "uHighlightBaseTexture"), 5)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(combinedProgram, "uHighlightBaseEnabled"),
if (highlightBaseTextureId != 0) 1 else 0
)
checkGlError("renderCombinedPass base uniforms")
val hasLensShading = metadata.lensShadingMap != null &&
@@ -2507,6 +2595,61 @@ class RawDemosaicProcessor {
checkGlError("renderCombinedPass")
}
private fun renderHighlightBasePass(
metadata: RawMetadata,
inputTextureId: Int
) {
if (highlightBaseProgram == 0 || highlightBaseFramebufferId == 0) return
GLES30.glUseProgram(highlightBaseProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, highlightBaseFramebufferId)
GLES30.glViewport(0, 0, highlightBaseWidth, highlightBaseHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(highlightBaseProgram, "uInputTexture"), 0)
val hasLensShading = metadata.lensShadingMap != null &&
metadata.lensShadingMapWidth > 0 &&
metadata.lensShadingMapHeight > 0
GLES30.glActiveTexture(GLES30.GL_TEXTURE4)
if (hasLensShading) {
uploadLensShadingTexture(metadata)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lensShadingTextureId)
} else {
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, createDummyShadingTexture())
}
GLES30.glUniform1i(GLES30.glGetUniformLocation(highlightBaseProgram, "uLensShadingMap"), 4)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(highlightBaseProgram, "uLensShadingEnabled"),
if (hasLensShading) 1 else 0
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(highlightBaseProgram, "uLensShadingPower"),
computeLensShadingPower(metadata)
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(highlightBaseProgram, "uSourceTexelSize"),
1.0f / metadata.width,
1.0f / metadata.height
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(highlightBaseProgram, "uBlurRadius"),
32.0f
)
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(highlightBaseProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
drawQuad(highlightBaseProgram)
checkGlError("renderHighlightBasePass")
}
private fun smoothstep(edge0: Float, edge1: Float, x: Float): Float {
val t = ((x - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
@@ -2752,20 +2895,90 @@ class RawDemosaicProcessor {
return normalizationGain * 2.0f.pow(rawExposureCompensation + dcpBaselineExposureOffset)
}
private fun renderLinearRcdPass(
metadata: RawMetadata,
sourceTextureId: Int,
targetFramebufferId: Int,
viewportWidth: Int,
viewportHeight: Int,
rawExposureCompensation: Float,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float,
dcpRenderPlan: DcpRenderPlan?,
label: String
) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebufferId)
checkGlError("$label setup framebuffer")
GLES30.glUseProgram(linearRcdProgram)
GLES30.glViewport(0, 0, viewportWidth, viewportHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(linearRcdProgram, "uDemosaickedTexture"), 0)
val transposedCCM = transposeMatrix3x3(dcpRenderPlan?.colorCorrectionMatrix ?: metadata.colorCorrectionMatrix)
GLES30.glUniformMatrix3fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uColorCorrectionMatrix"),
1,
false,
transposedCCM,
0
)
val exposureGain = computeLinearExposureGain(metadata, rawExposureCompensation, dcpRenderPlan)
GLES30.glUniform1f(GLES30.glGetUniformLocation(linearRcdProgram, "uExposureGain"), exposureGain)
val blackPoint = rawBlackPointCorrection.coerceIn(0f, 0.99f)
GLES30.glUniform1f(GLES30.glGetUniformLocation(linearRcdProgram, "uBlackPoint"), blackPoint)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(linearRcdProgram, "uWhitePoint"),
(1f + rawWhitePointCorrection).coerceAtLeast(blackPoint + 0.01f)
)
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uTexMatrix"),
1,
false,
identityMatrix,
0
)
drawQuad(linearRcdProgram)
checkGlError("$label drawQuad")
}
private suspend fun resolveRawAutoExposureEv(
context: Context,
metadata: RawMetadata,
sourceTextureId: Int,
meteringExposureCompensation: Float,
rawDROMode: DROMode,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float,
dcpRenderPlan: DcpRenderPlan?
): MeteringSystem.MeteringResult {
val meteringWidth = minOf(metadata.width, 256).coerceAtLeast(1)
val meteringHeight = minOf(metadata.height, 256).coerceAtLeast(1)
return try {
setupLinearMeteringFramebuffer(meteringWidth, meteringHeight)
renderLinearRcdPass(
metadata = metadata,
sourceTextureId = sourceTextureId,
targetFramebufferId = linearMeteringFramebufferId,
viewportWidth = meteringWidth,
viewportHeight = meteringHeight,
rawExposureCompensation = meteringExposureCompensation,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = dcpRenderPlan,
label = "LinearMeteringPass"
)
setupCombinedFramebuffer(meteringWidth, meteringHeight)
renderCombinedPass(
metadata = metadata,
inputTextureId = sourceTextureId,
inputTextureId = linearMeteringTextureId,
dcpRenderPlan = dcpRenderPlan,
viewportWidth = meteringWidth,
viewportHeight = meteringHeight
@@ -3015,6 +3228,7 @@ class RawDemosaicProcessor {
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
if (combinedProgram != 0) GLES30.glDeleteProgram(combinedProgram)
if (highlightBaseProgram != 0) GLES30.glDeleteProgram(highlightBaseProgram)
if (sharpenProgram != 0) GLES30.glDeleteProgram(sharpenProgram)
if (passthroughProgram != 0) GLES30.glDeleteProgram(passthroughProgram)
if (hdrReferenceProgram != 0) GLES30.glDeleteProgram(hdrReferenceProgram)
@@ -3061,6 +3275,10 @@ class RawDemosaicProcessor {
if (linearOutputFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(linearOutputFramebufferId), 0)
if (combinedTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(combinedTextureId), 0)
if (combinedFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(combinedFramebufferId), 0)
if (linearMeteringTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(linearMeteringTextureId), 0)
if (linearMeteringFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(linearMeteringFramebufferId), 0)
if (highlightBaseTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(highlightBaseTextureId), 0)
if (highlightBaseFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(highlightBaseFramebufferId), 0)
if (hdrReferenceTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(hdrReferenceTextureId), 0)
if (hdrReferenceFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(hdrReferenceFramebufferId), 0)
if (sharpenTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(sharpenTextureId), 0)
@@ -703,15 +703,19 @@ data class RawMetadata(
mS[6] * sR, mS[7] * sG, mS[8] * sB
)
// 2. 色彩适应:从 XYZ(D65) 转换到 XYZ(D50) 基准
// 使用标准 Bradford 矩阵
val BRADFORD_D65_TO_D50 = floatArrayOf(
1.0478112f, 0.0228866f, -0.0501270f,
0.0295424f, 0.9904844f, -0.0170491f,
-0.0092345f, 0.0150436f, 0.7521316f
)
val isD50WhitePoint = kotlin.math.abs(xw - 0.3457f) < 0.002f &&
kotlin.math.abs(yw - 0.3585f) < 0.002f
val gamutToXYZD50 = multiplyMatrix3x3(BRADFORD_D65_TO_D50, gamutToXYZD65)
val gamutToXYZD50 = if (isD50WhitePoint) {
gamutToXYZD65
} else {
val bradfordD65ToD50 = floatArrayOf(
1.0478112f, 0.0228866f, -0.0501270f,
0.0295424f, 0.9904844f, -0.0170491f,
-0.0092345f, 0.0150436f, 0.7521316f
)
multiplyMatrix3x3(bradfordD65ToD50, gamutToXYZD65)
}
// 3. 求逆:得到最终的 XYZ(D50) -> Gamut 转换矩阵
return invertMatrix3x3(gamutToXYZD50)
@@ -90,12 +90,15 @@ object RawShaders {
uniform sampler2D uInputTexture;
uniform sampler2D uCurveTexture;
uniform sampler2D uHighlightBaseTexture;
uniform sampler2D uLensShadingMap;
uniform sampler3D uDcpHueSatTexture;
uniform sampler3D uDcpLookTableTexture;
uniform mat3 uOutputTransform;
uniform float uCurveSize;
uniform bool uCurveEnabled;
uniform float uHighlightWhitePoint;
uniform bool uHighlightBaseEnabled;
uniform bool uLensShadingEnabled;
uniform float uLensShadingPower;
uniform bool uDcpHueSatEnabled;
@@ -376,28 +379,69 @@ object RawShaders {
const float HALO_THRESHOLD_MAX = 0.4;
const float RADIUS_SMALL = 1.5;
const float RADIUS_LARGE = 8.0;
float highlightRolloffLuma(float luma) {
if (uHighlightWhitePoint <= 1.0) return luma;
float start = 0.4;
if (luma <= start) return luma;
float x = (luma - start) / max(uHighlightWhitePoint - start, 1e-6);
float y = x *
(1.0 + x / uHighlightWhitePoint) /
(1.0 + x);
return mix(luma, start + y * (uHighlightWhitePoint - start),
smoothstep(start, uHighlightWhitePoint, luma));
}
vec3 reinhardLocalTonemapping(vec3 sceneLinear) {
float localAdaptationLuma() {
vec2 texelSize = 1.0 / vec2(textureSize(uInputTexture, 0));
float sceneLuma = luminance(sceneLinear);
// 1. 获取两个尺度的局部亮度
float localSmall = localAverageLuma(vTexCoord, texelSize, RADIUS_SMALL);
float localLarge = localAverageLuma(vTexCoord, texelSize, RADIUS_LARGE);
// 2. 计算边缘对比度,决定混合权重
float scaleContrast = abs(log2(localSmall + 1e-4) - log2(localLarge + 1e-4));
float localAdaptation = mix(localLarge, localSmall, smoothstep(HALO_THRESHOLD_MIN, HALO_THRESHOLD_MAX, scaleContrast));
return mix(localLarge, localSmall, smoothstep(HALO_THRESHOLD_MIN, HALO_THRESHOLD_MAX, scaleContrast));
}
// 3. 执行单次 Reinhard 局部映射
// 标准局部 Reinhard: L / (1 + V_local)
float mappedLuma = sceneLuma / (1.0 + localAdaptation);
// 4. 恢复颜色
// 为了防止除以 0,加一个小偏移
float chromaScale = mappedLuma / (sceneLuma + 1e-5);
return clamp(sceneLinear * chromaScale, 0.0, 1.0);
vec3 highlightRolloff(vec3 color) {
if (uHighlightWhitePoint <= 1.0) return color;
float luma = luminance(color);
float newLuma = highlightRolloffLuma(luma);
return color * (newLuma / max(luma, 1e-6));
}
vec3 combinedLocalToneMapping(vec3 sceneLinear, float originalLuma) {
float toneInputLuma = luminance(sceneLinear);
float localAdaptation = localAdaptationLuma();
// Local Reinhard-equivalent floor: this preserves the current acceptable baseline.
float compressionFloor = toneInputLuma / (1.0 + localAdaptation);
float baseLuma = uHighlightBaseEnabled
? max(texture(uHighlightBaseTexture, vTexCoord).r, 1e-4)
: max(localAdaptation, 1e-4);
float localContrast = originalLuma / baseLuma;
float highlightMask = smoothstep(0.4, 0.95, max(originalLuma, toneInputLuma));
// 独立 tone map: 局部适应量负责压缩,高光里亮于低频 base 的结构减少压缩。
// 暗于 base 的像素不参与负向恢复,避免窗景整体发灰。
float brightContrast = max(localContrast - 1.0, 0.0);
float compressionRelease = min(brightContrast, 0.85) * 0.8 * highlightMask;
float mappedLuma = compressionFloor * (1.0 + compressionRelease);
// 保证不会比原始局部 Reinhard 更暗,也不会超过 tone 输入亮度或 SDR 白。
mappedLuma = max(mappedLuma, compressionFloor);
mappedLuma = min(mappedLuma, min(toneInputLuma, 1.0));
return clamp(sceneLinear * (mappedLuma / max(toneInputLuma, 1e-5)), 0.0, 1.0);
}
void main() {
@@ -411,7 +455,9 @@ object RawShaders {
color = applyDcpHsvMap(color, uDcpLookTableTexture, uDcpLookTableDivisions, uDcpLookTableEncoding);
}
color = reinhardLocalTonemapping(color);
float originalLuma = luminance(color);
color = highlightRolloff(color);
color = combinedLocalToneMapping(color, originalLuma);
color = applyAdobeCurve(color);
@@ -422,6 +468,66 @@ object RawShaders {
}
""".trimIndent()
/**
* Low-resolution highlight base shader.
*
* R stores a broad luma base used to restore local contrast after SDR tone mapping.
*/
val HIGHLIGHT_BASE_FRAGMENT_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform sampler2D uLensShadingMap;
uniform vec2 uSourceTexelSize;
uniform float uBlurRadius;
uniform bool uLensShadingEnabled;
uniform float uLensShadingPower;
float luminance(vec3 color) {
return max(dot(color, vec3(0.2126, 0.7152, 0.0722)), 1e-4);
}
vec3 applyLensShadingAt(vec3 color, vec2 uv) {
if (!uLensShadingEnabled) {
return color;
}
vec4 gain = texture(uLensShadingMap, uv);
vec4 centerGain = texture(uLensShadingMap, vec2(0.5));
float lumaGain = dot(vec3(gain.r, 0.5 * (gain.g + gain.b), gain.a), vec3(0.2126, 0.7152, 0.0722));
float centerLumaGain = dot(vec3(centerGain.r, 0.5 * (centerGain.g + centerGain.b), centerGain.a), vec3(0.2126, 0.7152, 0.0722));
lumaGain /= max(centerLumaGain, 1e-4);
lumaGain = pow(max(lumaGain, 1e-4), clamp(uLensShadingPower, 0.0, 1.0));
return color * max(lumaGain, 0.0);
}
float sampleLuma(vec2 uv) {
uv = clamp(uv, vec2(0.0), vec2(1.0));
return luminance(applyLensShadingAt(texture(uInputTexture, uv).rgb, uv));
}
void main() {
vec2 stepSize = uSourceTexelSize * uBlurRadius;
float sum = 0.0;
float weightSum = 0.0;
for (int y = -2; y <= 2; y++) {
for (int x = -2; x <= 2; x++) {
vec2 offset = vec2(float(x), float(y));
float weight = exp(-dot(offset, offset) * 0.5);
sum += sampleLuma(vTexCoord + offset * stepSize) * weight;
weightSum += weight;
}
}
float baseLuma = sum / max(weightSum, 1e-5);
fragColor = vec4(baseLuma, baseLuma, baseLuma, 1.0);
}
""".trimIndent()
/**
* Dedicated Sharpening Shader
@@ -65,6 +65,8 @@ object SuperResolutionDngWriter {
private const val TAG_DEFAULT_CROP_SIZE = 50720
private const val TAG_COLOR_MATRIX_1 = 50721
private const val TAG_COLOR_MATRIX_2 = 50722
private const val TAG_FORWARD_MATRIX_1 = 50964
private const val TAG_FORWARD_MATRIX_2 = 50965
private const val TAG_AS_SHOT_NEUTRAL = 50728
private const val TAG_BASELINE_EXPOSURE = 50730
private const val TAG_CALIBRATION_ILLUMINANT_1 = 50778
@@ -177,6 +179,8 @@ object SuperResolutionDngWriter {
val illuminant2 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)?.toInt()
val colorMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1)
val colorMatrix2 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM2)
val forwardMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_FORWARD_MATRIX1)
val forwardMatrix2 = characteristics.get(CameraCharacteristics.SENSOR_FORWARD_MATRIX2)
val opcodeList2 = buildOpcodeList2(
captureResult = captureResult,
cfaPattern = cfaPattern,
@@ -216,6 +220,8 @@ object SuperResolutionDngWriter {
add(rationalArray(TAG_DEFAULT_CROP_SIZE, listOf(width.toDouble(), height.toDouble())))
colorMatrix1?.let { add(sRationalArray(TAG_COLOR_MATRIX_1, colorTransformToDngMatrix(it))) }
colorMatrix2?.let { add(sRationalArray(TAG_COLOR_MATRIX_2, colorTransformToDngMatrix(it))) }
forwardMatrix1?.let { add(sRationalArray(TAG_FORWARD_MATRIX_1, colorTransformToDngMatrix(it))) }
forwardMatrix2?.let { add(sRationalArray(TAG_FORWARD_MATRIX_2, colorTransformToDngMatrix(it))) }
add(rationalArray(TAG_AS_SHOT_NEUTRAL, asShotNeutral(captureResult)))
add(sRationalArray(TAG_BASELINE_EXPOSURE, listOf(0.0)))
add(short(TAG_CALIBRATION_ILLUMINANT_1, illuminant1))