fix: yuv hdr fusion

This commit is contained in:
Hinnka committed 2026-07-18 15:24:25 +08:00
1 parent 5da1db1824
commit 0713be10aa
2 files changed
+203 -10

No files matched your search

@@ -0,0 +1,157 @@
package com.hinnka.mycamera.processor
import android.graphics.ColorSpace
import android.graphics.ImageFormat
import android.opengl.GLES30
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.nio.ByteBuffer
import java.nio.ByteOrder
@RunWith(AndroidJUnit4::class)
class GlesYuvStackerShaderTest {
@Test
fun clippedHighlightsUseRecoverableShortExposure() {
withStacker { stacker ->
val weights = renderNormalizedWeights(
stacker = stacker,
colors = listOf(
floatArrayOf(1f, 1f, 1f, 1f),
floatArrayOf(1f, 1f, 1f, 1f),
floatArrayOf(0.75f, 0.25f, 0.25f, 1f),
),
)
assertEquals(0, weights[0])
assertEquals(0, weights[1])
assertEquals(255, weights[2])
}
}
@Test
fun fullyClippedBracketFallsBackToZeroEvReference() {
withStacker { stacker ->
val weights = renderNormalizedWeights(
stacker = stacker,
colors = List(3) { floatArrayOf(1f, 1f, 1f, 1f) },
)
assertEquals(255, weights[0])
assertEquals(0, weights[1])
assertEquals(0, weights[2])
}
}
private fun withStacker(block: (GlesYuvStacker) -> Unit) {
val stacker = GlesYuvStacker(
width = 4,
height = 4,
outputWidth = 4,
outputHeight = 4,
rotation = 0,
colorSpace = ColorSpace.get(ColorSpace.Named.SRGB),
inputFormat = ImageFormat.YUV_420_888,
)
try {
invokePrivate(stacker, "initEgl")
invokePrivate(stacker, "ensureGles31")
invokePrivate(stacker, "initPrograms")
invokePrivate(stacker, "initHdrPrograms")
block(stacker)
} finally {
invokePrivate(stacker, "release")
}
}
private fun renderNormalizedWeights(
stacker: GlesYuvStacker,
colors: List<FloatArray>,
): IntArray {
val imageTextures = colors.map(::createRgbaTexture)
val rawTargets = List(3) { createMertensTarget(stacker, halfFloat = true) }
val normalizedTarget = createMertensTarget(stacker, halfFloat = false)
try {
rawTargets.forEachIndexed { index, target ->
invokePrivate(
stacker,
"renderMertensWeight",
imageTextures[index],
imageTextures[0],
target,
1f,
false,
)
}
invokePrivate(stacker, "renderMertensNormalizeWeights", rawTargets, normalizedTarget)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readPrivateInt(normalizedTarget, "framebufferId"))
val pixel = ByteBuffer.allocateDirect(4)
GLES30.glReadPixels(0, 0, 1, 1, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, pixel)
return IntArray(3) { index -> pixel.get(index).toInt() and 0xff }
} finally {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
rawTargets.forEach(::releaseTarget)
releaseTarget(normalizedTarget)
GLES30.glDeleteTextures(imageTextures.size, imageTextures.toIntArray(), 0)
}
}
private fun createRgbaTexture(color: FloatArray): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
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 pixels = ByteBuffer.allocateDirect(color.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(color)
position(0)
}
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
GLES30.GL_RGBA16F,
1,
1,
0,
GLES30.GL_RGBA,
GLES30.GL_FLOAT,
pixels,
)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return ids[0]
}
private fun createMertensTarget(stacker: GlesYuvStacker, halfFloat: Boolean): Any {
return requireNotNull(invokePrivate(stacker, "createMertensRenderTarget", 1, 1, halfFloat))
}
private fun releaseTarget(target: Any) {
target.javaClass.getDeclaredMethod("release").run {
isAccessible = true
invoke(target)
}
}
private fun invokePrivate(target: Any, methodName: String, vararg args: Any): Any? {
return target.javaClass.declaredMethods.first {
it.name == methodName && it.parameterCount == args.size
}.run {
isAccessible = true
invoke(target, *args)
}
}
private fun readPrivateInt(target: Any, fieldName: String): Int {
return target.javaClass.getDeclaredField(fieldName).run {
isAccessible = true
getInt(target)
}
}
}
@@ -2880,13 +2880,21 @@ class GlesYuvStacker(
return max(max(value.r, value.g), value.b);
}
float validity(vec3 rgb) {
float deghostValidity(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 highlightValidity(vec3 rgb) {
// Fusion happens after YCbCr-to-RGB conversion has clamped every
// channel to [0, 1]. Once any channel reaches the shoulder there
// is no reliable chroma left in that exposure. Reject the clipped
// observation and let a shorter exposure provide the highlight.
return 1.0 - smoothstep(0.960, 0.995, max3(rgb));
}
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);
@@ -2927,7 +2935,7 @@ class GlesYuvStacker(
float sideLuma = luma(side);
float referenceLuma = luma(reference);
float comparable = validity(side) * validity(reference) * referenceStructure(ivec2(x, y));
float comparable = deghostValidity(side) * deghostValidity(reference) * referenceStructure(ivec2(x, y));
if (comparable <= 0.001) {
return 0.0;
}
@@ -2977,12 +2985,20 @@ class GlesYuvStacker(
vec3 expo = exp(-(expoDelta * expoDelta) / 0.08);
float wellExposedness = expo.r * expo.g * expo.b;
float weight =
float qualityWeight =
pow(max(contrast, 0.0), uContrastWeight) *
pow(max(saturation, 0.0), uSaturationWeight) *
pow(max(wellExposedness, 0.0), uExposureWeight);
weight = weight * computeDeghostAlpha(coord) + 1e-12;
fragColor = vec4(weight, weight, weight, 1.0);
float admissibility = highlightValidity(rgb) * computeDeghostAlpha(coord);
// Store independent weight tiers. Flat or neutral regions have no
// contrast/saturation and therefore no quality weight; the next
// pass can then fall back to well-exposedness without assigning an
// equal share to clipped frames. The final tier preserves a valid
// deterministic choice if all quality metrics become too small.
float primaryWeight = qualityWeight * admissibility;
float fallbackWeight = wellExposedness * admissibility;
fragColor = vec4(primaryWeight, fallbackWeight, admissibility, 1.0);
}
""".trimIndent()
@@ -2995,11 +3011,31 @@ class GlesYuvStacker(
uniform sampler2D uWeight1;
uniform sampler2D uWeight2;
void main() {
float w0 = texture(uWeight0, vTexCoord).r;
float w1 = texture(uWeight1, vTexCoord).r;
float w2 = texture(uWeight2, vTexCoord).r;
float sum = max(w0 + w1 + w2, 1e-12);
fragColor = vec4(w0 / sum, w1 / sum, w2 / sum, 1.0);
vec3 raw0 = texture(uWeight0, vTexCoord).rgb;
vec3 raw1 = texture(uWeight1, vTexCoord).rgb;
vec3 raw2 = texture(uWeight2, vTexCoord).rgb;
vec3 weights;
float primarySum = raw0.r + raw1.r + raw2.r;
if (primarySum > 1e-6) {
weights = vec3(raw0.r, raw1.r, raw2.r) / primarySum;
} else {
float fallbackSum = raw0.g + raw1.g + raw2.g;
if (fallbackSum > 1e-6) {
weights = vec3(raw0.g, raw1.g, raw2.g) / fallbackSum;
} else {
float admissibleSum = raw0.b + raw1.b + raw2.b;
if (admissibleSum > 1e-6) {
weights = vec3(raw0.b, raw1.b, raw2.b) / admissibleSum;
} else {
// No exposure contains recoverable highlight data.
// Preserve the denoised zero-EV reference instead of
// averaging equally with clipped side frames.
weights = vec3(1.0, 0.0, 0.0);
}
}
}
fragColor = vec4(weights, 1.0);
}
""".trimIndent()