feat: hdr fusion deghost

This commit is contained in:
Hinnka committed 2026-06-14 21:54:53 +08:00
1 parent c61b426206
commit 003ffbb4d6
4 files changed
+235 -21

No files matched your search

@@ -1621,6 +1621,8 @@ object GalleryManager {
suspend fun composeHdrBracketPhoto(
images: List<SafeImage>,
captureResults: List<CaptureResult?> = emptyList(),
zeroEvFrameCount: Int = (images.size - 2).coerceAtLeast(1),
rotation: Int,
aspectRatio: AspectRatio,
shouldMirror: Boolean,
@@ -1634,15 +1636,20 @@ object GalleryManager {
return@withContext null
}
val bitmaps = ArrayList<Bitmap>(images.size)
val bitmaps = ArrayList<Bitmap>(3)
try {
if (useSuperResolution) {
PLog.w(TAG, "HDR bracket Mertens fusion uses 0EV stacking without super resolution")
}
if (!useGpuAcceleration) {
PLog.w(TAG, "HDR bracket 0EV denoise uses GLES stacker; ignoring disabled GPU acceleration setting")
}
val zeroEvBitmap = processHdrBracketZeroEvFrames(
images = images.subList(1, images.lastIndex),
rotation = rotation,
aspectRatio = aspectRatio,
shouldMirror = shouldMirror,
useGpuAcceleration = useGpuAcceleration,
useSuperResolution = useSuperResolution,
useSuperResolution = false,
colorSpace = colorSpace
)
val targetWidth = zeroEvBitmap.width
@@ -1662,7 +1669,20 @@ object GalleryManager {
targetHeight
)
)
MertensExposureFusionProcessor.fuse(bitmaps)
val exposureProducts = buildHdrMertensExposureProducts(
captureResults = captureResults,
zeroEvFrameCount = zeroEvFrameCount,
frameCount = images.size,
)
PLog.d(
TAG,
"Composing HDR with Mertens fusion and validity-aware deghost mask, exposureScales=${formatRelativeExposureScales(exposureProducts)}"
)
MertensExposureFusionProcessor.fuse(
frames = bitmaps,
exposureProducts = exposureProducts,
enableDeghostMask = true,
)
} catch (e: Exception) {
images.forEach { it.close() }
PLog.e(TAG, "Failed to compose HDR bracket photo", e)
@@ -1693,7 +1713,6 @@ object GalleryManager {
rotation: Int,
aspectRatio: AspectRatio,
shouldMirror: Boolean,
useGpuAcceleration: Boolean,
useSuperResolution: Boolean,
colorSpace: ColorSpace
): Bitmap {
@@ -1708,7 +1727,7 @@ object GalleryManager {
aspectRatio = aspectRatio,
outputPath = null,
enableSuperResolution = useSuperResolution,
useVulkan = useGpuAcceleration,
useVulkan = true,
colorSpace = colorSpace
)
} finally {
@@ -1724,6 +1743,57 @@ object GalleryManager {
return scaled
}
private fun buildHdrMertensExposureProducts(
captureResults: List<CaptureResult?>,
zeroEvFrameCount: Int,
frameCount: Int,
): FloatArray {
val zeroIndices = 1 until (1 + zeroEvFrameCount.coerceAtLeast(1)).coerceAtMost(frameCount - 1)
val lowProduct = captureExposureProduct(captureResults.getOrNull(0))
val measuredZeroProduct = zeroIndices
.mapNotNull { captureExposureProduct(captureResults.getOrNull(it)) }
.takeIf { it.isNotEmpty() }
?.average()
?.toFloat()
?.takeIf { it.isFinite() && it > 0f }
val highProduct = captureExposureProduct(captureResults.getOrNull(frameCount - 1))
val zeroProduct = measuredZeroProduct ?: 1f
return floatArrayOf(
lowProduct ?: zeroProduct * fallbackHdrExposureProduct(0, zeroEvFrameCount, frameCount),
zeroProduct,
highProduct ?: zeroProduct * fallbackHdrExposureProduct(frameCount - 1, zeroEvFrameCount, frameCount),
)
}
private fun formatRelativeExposureScales(exposureProducts: FloatArray): String {
val reference = exposureProducts.getOrNull(1)
?.takeIf { it.isFinite() && it > 0f }
?: 1f
return exposureProducts.joinToString(prefix = "[", postfix = "]") { product ->
"%.2f".format((product / reference).coerceAtLeast(0f))
}
}
private fun captureExposureProduct(result: CaptureResult?): Float? {
val exposureTime = result?.get(CaptureResult.SENSOR_EXPOSURE_TIME)
?.takeIf { it > 0L }
?: return null
val iso = result.get(CaptureResult.SENSOR_SENSITIVITY)
?.takeIf { it > 0 }
?: return null
val product = exposureTime.toDouble() * iso.toDouble()
return product.toFloat().takeIf { it.isFinite() && it > 0f }
}
private fun fallbackHdrExposureProduct(index: Int, zeroEvFrameCount: Int, frameCount: Int): Float {
val clampedZeroCount = zeroEvFrameCount.coerceIn(1, (frameCount - 2).coerceAtLeast(1))
return when {
index == 0 -> Math.pow(2.0, -2.5).toFloat()
index in 1..clampedZeroCount -> 1f
else -> Math.pow(2.0, 2.5).toFloat()
}
}
private fun mirrorBitmapIfNeeded(bitmap: Bitmap, shouldMirror: Boolean): Bitmap {
if (!shouldMirror) return bitmap
return BitmapUtils.flipHorizontal(bitmap).also {
@@ -54,6 +54,8 @@ object MertensExposureFusionProcessor {
contrastWeight: Float = DEFAULT_CONTRAST_WEIGHT,
saturationWeight: Float = DEFAULT_SATURATION_WEIGHT,
exposureWeight: Float = DEFAULT_EXPOSURE_WEIGHT,
exposureProducts: FloatArray? = null,
enableDeghostMask: Boolean = false,
): Bitmap? = withContext(dispatcher) {
if (frames.size != HDR_FRAME_COUNT) {
PLog.w(TAG, "Expected $HDR_FRAME_COUNT frames, got ${frames.size}")
@@ -70,12 +72,15 @@ object MertensExposureFusionProcessor {
var result: Bitmap? = null
val elapsed = measureTimeMillis {
result = runCatching {
renderFusion(frames, contrastWeight, saturationWeight, exposureWeight)
renderFusion(frames, contrastWeight, saturationWeight, exposureWeight, exposureProducts, enableDeghostMask)
}.onFailure {
PLog.e(TAG, "Mertens exposure fusion failed", it)
}.getOrNull()
}
PLog.d(TAG, "Mertens exposure fusion took ${elapsed}ms, size=${width}x${height}, success=${result != null}")
PLog.d(
TAG,
"Mertens exposure fusion took ${elapsed}ms, size=${width}x${height}, deghostMask=$enableDeghostMask, success=${result != null}"
)
result
}
@@ -84,21 +89,34 @@ object MertensExposureFusionProcessor {
contrastWeight: Float,
saturationWeight: Float,
exposureWeight: Float,
exposureProducts: FloatArray?,
enableDeghostMask: Boolean,
): Bitmap? {
val width = frames.first().width
val height = frames.first().height
val maxLevel = (ln(min(width, height).toFloat()) / ln(2f)).toInt().coerceAtLeast(0)
val uploads = frames.map { prepareUploadBitmap(it) }
val inputTextures = uploads.map { uploadBitmapTexture(it.bitmap) }
val exposureScales = normalizeExposureProducts(exposureProducts)
val resultPyramid = ArrayList<RenderTarget>(maxLevel + 1)
var currentImages = inputTextures.map { TextureLevel(width, height, it, owned = false) }
var currentWeights: RenderTarget? = null
var reconstructed: RenderTarget? = null
try {
val rawWeights = inputTextures.map { texture ->
val referenceTexture = inputTextures[1]
val rawWeights = inputTextures.mapIndexed { index, texture ->
createRenderTarget(width, height, halfFloat = true).also {
renderWeight(texture, it, contrastWeight, saturationWeight, exposureWeight)
renderWeight(
imageTexture = texture,
referenceTexture = referenceTexture,
target = it,
contrastWeight = contrastWeight,
saturationWeight = saturationWeight,
exposureWeight = exposureWeight,
exposureScale = exposureScales[index],
useDeghostMask = enableDeghostMask && index != 1,
)
}
}
currentWeights = createRenderTarget(width, height, halfFloat = true)
@@ -193,22 +211,42 @@ object MertensExposureFusionProcessor {
private fun renderWeight(
imageTexture: Int,
referenceTexture: Int,
target: RenderTarget,
contrastWeight: Float,
saturationWeight: Float,
exposureWeight: Float,
exposureScale: Float,
useDeghostMask: Boolean,
) {
GLES30.glUseProgram(weightProgram)
bindTarget(target)
bindTexture(weightProgram, "uImage", 0, imageTexture)
bindTexture(weightProgram, "uReferenceImage", 1, referenceTexture)
GLES30.glUniform2i(GLES30.glGetUniformLocation(weightProgram, "uImageSize"), target.width, target.height)
GLES30.glUniform1f(GLES30.glGetUniformLocation(weightProgram, "uContrastWeight"), contrastWeight)
GLES30.glUniform1f(GLES30.glGetUniformLocation(weightProgram, "uSaturationWeight"), saturationWeight)
GLES30.glUniform1f(GLES30.glGetUniformLocation(weightProgram, "uExposureWeight"), exposureWeight)
GLES30.glUniform1f(GLES30.glGetUniformLocation(weightProgram, "uExposureScale"), exposureScale)
GLES30.glUniform1i(GLES30.glGetUniformLocation(weightProgram, "uUseDeghostMask"), if (useDeghostMask) 1 else 0)
drawQuad(weightProgram)
checkGlError("renderWeight")
}
private fun normalizeExposureProducts(exposureProducts: FloatArray?): FloatArray {
val reference = exposureProducts
?.getOrNull(1)
?.takeIf { it.isFinite() && it > 0f }
?: 1f
return FloatArray(HDR_FRAME_COUNT) { index ->
val product = exposureProducts
?.getOrNull(index)
?.takeIf { it.isFinite() && it > 0f }
?: reference
(product / reference).coerceIn(1f / 32f, 32f)
}
}
private fun renderNormalizeWeights(rawWeights: List<RenderTarget>, target: RenderTarget) {
GLES30.glUseProgram(normalizeProgram)
bindTarget(target)
@@ -616,10 +654,13 @@ object MertensExposureFusionProcessor {
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uImage;
uniform sampler2D uReferenceImage;
uniform ivec2 uImageSize;
uniform float uContrastWeight;
uniform float uSaturationWeight;
uniform float uExposureWeight;
uniform float uExposureScale;
uniform int uUseDeghostMask;
int reflect101(int p, int size) {
if (size <= 1) return 0;
@@ -637,6 +678,88 @@ object MertensExposureFusionProcessor {
return dot(rgb, vec3(0.299, 0.587, 0.114));
}
float luma(vec3 rgb) {
return dot(rgb, vec3(0.299, 0.587, 0.114));
}
float max3(vec3 value) {
return max(max(value.r, value.g), value.b);
}
float validity(vec3 rgb) {
float y = luma(rgb);
float blackGate = smoothstep(0.055, 0.145, y);
float whiteGate = 1.0 - smoothstep(0.865, 0.975, max3(rgb));
return clamp(blackGate * whiteGate, 0.0, 1.0);
}
float referenceStructure(ivec2 coord) {
float c = luma(texelFetch(uReferenceImage, coord, 0).rgb);
float l = luma(texelFetch(uReferenceImage, ivec2(reflect101(coord.x - 1, uImageSize.x), coord.y), 0).rgb);
float r = luma(texelFetch(uReferenceImage, ivec2(reflect101(coord.x + 1, uImageSize.x), coord.y), 0).rgb);
float u = luma(texelFetch(uReferenceImage, ivec2(coord.x, reflect101(coord.y - 1, uImageSize.y)), 0).rgb);
float d = luma(texelFetch(uReferenceImage, ivec2(coord.x, reflect101(coord.y + 1, uImageSize.y)), 0).rgb);
float gradient = abs(r - l) + abs(d - u);
float laplacian = abs(l + r + u + d - 4.0 * c);
return smoothstep(0.030, 0.095, gradient + 0.5 * laplacian);
}
float censusMismatch(ivec2 coord, float refCenter, float sideCenter) {
float mismatch = 0.0;
float count = 0.0;
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if (x == 0 && y == 0) {
continue;
}
ivec2 p = ivec2(reflect101(coord.x + x, uImageSize.x), reflect101(coord.y + y, uImageSize.y));
float refNeighbor = luma(texelFetch(uReferenceImage, p, 0).rgb);
float sideNeighbor = luma(texelFetch(uImage, p, 0).rgb);
float refRank = refNeighbor > refCenter ? 1.0 : 0.0;
float sideRank = sideNeighbor > sideCenter ? 1.0 : 0.0;
mismatch += abs(refRank - sideRank);
count += 1.0;
}
}
return mismatch / max(count, 1.0);
}
float deghostScoreAt(ivec2 coord) {
int x = reflect101(coord.x, uImageSize.x);
int y = reflect101(coord.y, uImageSize.y);
vec3 side = texelFetch(uImage, ivec2(x, y), 0).rgb;
vec3 reference = texelFetch(uReferenceImage, ivec2(x, y), 0).rgb;
float scale = clamp(uExposureScale, 0.03125, 32.0);
float sideLuma = luma(side);
float referenceLuma = luma(reference);
float comparable = validity(side) * validity(reference) * referenceStructure(ivec2(x, y));
if (comparable <= 0.001) {
return 0.0;
}
float exposureGap = abs(log2(scale));
float logResidual = abs(log(max(sideLuma, 1e-4)) - log(max(referenceLuma, 1e-4)) - log(scale));
float logMotion = smoothstep(0.28 + 0.04 * min(exposureGap, 3.0), 0.72, logResidual);
float rankMotion = smoothstep(0.32, 0.68, censusMismatch(ivec2(x, y), referenceLuma, sideLuma));
float score = max(logMotion, rankMotion);
return comparable * score;
}
float computeDeghostAlpha(ivec2 coord) {
if (uUseDeghostMask == 0) {
return 1.0;
}
float score = 0.0;
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
score = max(score, deghostScoreAt(coord + ivec2(x, y)));
}
}
float reject = smoothstep(0.48, 0.86, score);
return mix(1.0, 0.015, reject);
}
void main() {
ivec2 coord = ivec2(gl_FragCoord.xy);
vec3 rgb = texelFetch(uImage, coord, 0).rgb;
@@ -660,8 +783,8 @@ object MertensExposureFusionProcessor {
float weight =
pow(max(contrast, 0.0), uContrastWeight) *
pow(max(saturation, 0.0), uSaturationWeight) *
pow(max(wellExposedness, 0.0), uExposureWeight) +
1e-12;
pow(max(wellExposedness, 0.0), uExposureWeight);
weight = weight * computeDeghostAlpha(coord) + 1e-12;
fragColor = vec4(weight, weight, weight, 1.0);
}
""".trimIndent()
@@ -107,7 +107,8 @@ class GlesYuvStacker(
initResources()
PLog.d(
TAG,
"GLES stack format=${formatName(inputFormat)} internal=${if (highPrecisionInput) "R16F/RG16F" else "R8/RG8"} flowGrid=${FLOW_GRID_SPACING}px grid=${gridWidth}x${gridHeight}"
"GLES stack format=${formatName(inputFormat)} internal=${if (highPrecisionInput) "R16F/RG16F" else "R8/RG8"} " +
"flowGrid=${FLOW_GRID_SPACING}px grid=${gridWidth}x${gridHeight}"
)
if (!uploadImagePlanes(images.first(), refY, refCbCr, refYStaging, refCbCrStaging, "reference")) {
@@ -671,7 +672,11 @@ class GlesYuvStacker(
finishFramebufferPass("computeTileMask")
}
private fun accumulateFrame(yTexture: Int, cbCrTexture: Int, isReference: Boolean) {
private fun accumulateFrame(
yTexture: Int,
cbCrTexture: Int,
isReference: Boolean,
) {
val outputAccumulator = if (currentAccumulatorTexture == accumulatorTexture) {
accumulatorScratchTexture
} else {
@@ -691,7 +696,10 @@ class GlesYuvStacker(
GLES31.glUniform2i(GLES31.glGetUniformLocation(accumulateProgram, "uGridSize"), gridWidth, gridHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(accumulateProgram, "uTileSize"), FLOW_GRID_SPACING)
GLES31.glUniform1i(GLES31.glGetUniformLocation(accumulateProgram, "uIsReference"), if (isReference) 1 else 0)
GLES31.glUniform1f(GLES31.glGetUniformLocation(accumulateProgram, "uFrameWeight"), if (isReference) 1.0f else NON_REFERENCE_FRAME_WEIGHT)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(accumulateProgram, "uFrameWeight"),
if (isReference) 1.0f else NON_REFERENCE_FRAME_WEIGHT,
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("accumulateFrame")
currentAccumulatorTexture = outputAccumulator
@@ -1280,11 +1288,15 @@ class GlesYuvStacker(
return texelFetch(uReferenceY, p, 0).r;
}
float curY(vec2 pixel) {
float curYRaw(vec2 pixel) {
vec2 uv = (pixel + vec2(0.5)) / vec2(uImageSize);
return texture(uCurrentY, clamp(uv, vec2(0.0), vec2(1.0))).r;
}
float curYNorm(vec2 pixel) {
return curYRaw(pixel);
}
vec2 chromaUv(vec2 pixel) {
ivec2 chromaSize = (uImageSize + ivec2(1)) / 2;
vec2 chromaPixel = floor(pixel * 0.5);
@@ -1312,7 +1324,8 @@ class GlesYuvStacker(
for (int x = -1; x <= 1; ++x) {
ivec2 rp = p + ivec2(x, y);
float ry = refY(rp);
float cy = curY(curPixel + vec2(x, y));
vec2 cp = curPixel + vec2(x, y);
float cy = curYNorm(cp);
float d = ry - cy;
float sigmaNoise = max(uNoiseAlpha * max(ry, 0.05) + uNoiseBeta, 1e-10);
float sigma = max(sigmaNoise, 0.0004);
@@ -1455,7 +1468,8 @@ class GlesYuvStacker(
vec4 prev = texelFetch(uAccumulatorInput, p, 0);
if (uIsReference != 0) {
vec3 ycc = sampleYcc(vec2(p));
fragColor = prev + vec4(ycc, 1.0);
float weight = max(uFrameWeight, 1e-6);
fragColor = prev + vec4(ycc * weight, weight);
return;
}
@@ -1483,8 +1497,9 @@ class GlesYuvStacker(
for (int x = -1; x <= 1; ++x) {
vec2 tap = vec2(x, y);
float kw = kernelWeight(tap, kp);
vec3 ycc = sampleYcc(source + tap);
float w = baseWeight * kw;
sum += sampleYcc(source + tap) * w;
sum += ycc * w;
weight += w;
}
}
@@ -1571,6 +1586,7 @@ class GlesYuvStacker(
);
srcP = sourceTexel(src);
}
vec3 ycc = readYcc(srcP);
float accumWeight = readWeight(srcP);
@@ -4255,8 +4255,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val chromaNoiseReductionValue = chromaNoiseReduction.firstOrNull() ?: 0f
val photoQualityValue = photoQuality.firstOrNull() ?: 95
val baseImage = orderedImages[1]
val useSuperRes = state.value.useMFSR
val superResScale = if (useSuperRes) 2f else 1.0f
if (state.value.useMFSR) {
PLog.w(TAG, "YUV HDR bracket uses Mertens fusion without super resolution")
}
val useSuperRes = false
val superResScale = 1.0f
val captureMode = if (zeroEvFrameCount > 1) "hdr_mfnr" else "hdr_bracket"
val metadata = buildPhotoMetadata(
width = (baseImage.width.toFloat() * superResScale).roundToInt(),
@@ -4289,6 +4292,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
try {
fusedBitmap = GalleryManager.composeHdrBracketPhoto(
images = orderedImages,
captureResults = orderedCaptureResults,
zeroEvFrameCount = zeroEvFrameCount,
rotation = metadata.rotation,
aspectRatio = aspectRatio,
shouldMirror = metadata.isMirrored,