diff --git a/app/src/main/java/com/hinnka/mycamera/lut/BloomLdrSettings.kt b/app/src/main/java/com/hinnka/mycamera/lut/BloomLdrSettings.kt deleted file mode 100644 index e1727d3b..00000000 --- a/app/src/main/java/com/hinnka/mycamera/lut/BloomLdrSettings.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.hinnka.mycamera.lut - -internal object BloomLdrSettings { - const val MAX_MIP_DIMENSION = 512 - const val MIP_COUNT = 10 - - private const val HIGHLIGHT_THRESHOLD = 0.9f - private const val HIGHLIGHT_THRESHOLD_SOFTNESS = 0.2f - private const val MAX_COMPOSITE_STRENGTH = 0.8f - - fun thresholdPrecomputations(): FloatArray { - val knee = HIGHLIGHT_THRESHOLD * HIGHLIGHT_THRESHOLD_SOFTNESS.coerceIn(0f, 1f) - return floatArrayOf( - HIGHLIGHT_THRESHOLD, - HIGHLIGHT_THRESHOLD - knee, - 2.0f * knee, - 0.25f / (knee + 0.00001f) - ) - } - - fun mipAddWeight(sourceMip: Int, mipCount: Int, bloom: Float): Float { - if (mipCount <= 1) return 1f - val radius = smooth01(bloom.coerceIn(0f, 1f)) - val mipPosition = sourceMip.toFloat() / (mipCount - 1).toFloat() - val localDamping = 0.45f + mipPosition * 0.75f - val radiusBoost = 0.7f + radius * 0.8f - return (localDamping * radiusBoost).coerceIn(0.25f, 1.5f) - } - - fun compositeMipLowerIndex(mipCount: Int, bloom: Float): Int { - return compositeMipPosition(mipCount, bloom).toInt() - } - - fun compositeMipUpperIndex(mipCount: Int, bloom: Float): Int { - val lower = compositeMipLowerIndex(mipCount, bloom) - val maxMip = (mipCount - 1).coerceAtLeast(0) - return (lower + 1).coerceAtMost(maxMip) - } - - fun compositeMipBlend(mipCount: Int, bloom: Float): Float { - val position = compositeMipPosition(mipCount, bloom) - return (position - position.toInt().toFloat()).coerceIn(0f, 1f) - } - - fun compositeStrength(bloom: Float): Float { - val strength = bloom.coerceIn(0f, 1f) - return (strength * strength * MAX_COMPOSITE_STRENGTH).coerceIn(0f, 1f) - } - - private fun compositeMipPosition(mipCount: Int, bloom: Float): Float { - val maxMip = (mipCount - 1).coerceAtLeast(0) - if (maxMip == 0) return 0f - val maxSelectableMip = minOf(maxMip, 5) - val radius = smooth01(bloom.coerceIn(0f, 1f)) - return radius * maxSelectableMip.toFloat() - } - - private fun smooth01(value: Float): Float { - return value * value * (3f - 2f * value) - } -} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionGl.kt b/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionGl.kt new file mode 100644 index 00000000..ea23577b --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionGl.kt @@ -0,0 +1,227 @@ +package com.hinnka.mycamera.lut + +import android.opengl.GLES30 +import com.hinnka.mycamera.utils.PLog +import kotlin.math.exp +import kotlin.math.roundToInt + +internal data class HighlightDiffusionOutput(val textureId: Int, val framebufferId: Int) + +/** + * Context-local Bloom and Halation shared by preview, recording and photo export. + * Order: display-encoded color -> Halation -> Bloom -> film grain. + * Fixed reference defaults: Bloom size 70/source 40/softness 50; + * Halation size 25/source 20/hardness 20/grain 50/destination 100/hue 0/shift 0. + * Float working maps avoid quantizing weak highlights before peak normalization. + */ +internal class HighlightDiffusionGl(private val logTag: String) { + private class Program(val source: String) { + var id = 0 + private val locations = mutableMapOf() + fun location(name: String) = locations.getOrPut(name) { GLES30.glGetUniformLocation(id, name) } + fun reset() { id = 0; locations.clear() } + } + + private class Target(val floating: Boolean) { + var texture = 0 + var framebuffer = 0 + var width = 0 + var height = 0 + fun reset() { texture = 0; framebuffer = 0; width = 0; height = 0 } + fun release() { + if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0) + if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0) + reset() + } + } + + private class Effect(val halation: Boolean, val edge: Int, sigma: Double) { + val work = Target(true) + val ping = Target(true) + val map = Target(!halation) + val output = Target(false) + val reductions = mutableListOf() + val center: Float + val pairs: FloatArray + init { + val radius = (3.0 * sigma).toInt() + val weights = DoubleArray(radius + 1) { exp(-it.toDouble() * it / (2.0 * sigma * sigma)) } + val total = weights[0] + 2.0 * weights.drop(1).sum() + center = (weights[0] / total).toFloat() + pairs = FloatArray(((radius + 1) / 2) * 2) + for (i in 1..radius step 2) { + val a = weights[i] / total + val b = if (i + 1 <= radius) weights[i + 1] / total else 0.0 + val index = (i - 1) / 2 * 2 + pairs[index] = (i + b / (a + b)).toFloat() + pairs[index + 1] = (a + b).toFloat() + } + } + fun targets() = listOf(work, ping, map, output) + reductions + } + + private val extract = Program(HighlightDiffusionShaders.EXTRACT) + private val blur = Program(HighlightDiffusionShaders.BLUR) + private val reduce = Program(HighlightDiffusionShaders.REDUCE) + private val normalize = Program(HighlightDiffusionShaders.NORMALIZE) + private val composite = Program(HighlightDiffusionShaders.COMPOSITE) + private val programs = listOf(extract, blur, reduce, normalize, composite) + private val halationEffect = Effect(true, 512, 5.0) + private val bloomEffect = Effect(false, 256, 17.5) + + fun renderToTexture( + sourceTextureId: Int, + width: Int, + height: Int, + bloom: Float, + halation: Float, + drawQuad: (Int) -> Unit, + ): HighlightDiffusionOutput? { + if (bloom <= 0.001f && halation <= 0.001f) return null + return try { + checkGl("upstream") + ensurePrograms() + var source = sourceTextureId + var output: Target? = null + if (halation > 0.001f) { + output = render(halationEffect, source, width, height, halation.coerceIn(0f, 1f), drawQuad) + source = output.texture + } + if (bloom > 0.001f) { + output = render(bloomEffect, source, width, height, bloom.coerceIn(0f, 1f), drawQuad) + } + output?.let { HighlightDiffusionOutput(it.texture, it.framebuffer) } + } catch (failure: IllegalStateException) { + PLog.e(logTag, "Highlight diffusion failed: ${failure.message}") + null + } finally { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + GLES30.glUseProgram(0) + } + } + + private fun render( + effect: Effect, source: Int, width: Int, height: Int, strength: Float, drawQuad: (Int) -> Unit, + ): Target { + val scale = minOf(1.0, effect.edge.toDouble() / maxOf(width, height)) + val w = (width * scale).roundToInt().coerceAtLeast(1) + val h = (height * scale).roundToInt().coerceAtLeast(1) + ensureTarget(effect.work, w, h) + ensureTarget(effect.ping, w, h) + ensureTarget(effect.map, w, h) + ensureTarget(effect.output, width, height) + check(source != effect.output.texture) { "Source aliases diffusion output" } + pass(extract, effect.work, source, drawQuad) { + GLES30.glUniform1f(extract.location("uThreshold"), if (effect.halation) 0.794f else 0.598f) + GLES30.glUniform1i(extract.location("uHalation"), if (effect.halation) 1 else 0) + } + fun blurPass(target: Target, input: Int, dx: Float, dy: Float) { + pass(blur, target, input, drawQuad) { + GLES30.glUniform2f(blur.location("uStep"), dx, dy) + GLES30.glUniform1f(blur.location("uCenter"), effect.center) + GLES30.glUniform1i(blur.location("uPairCount"), effect.pairs.size / 2) + GLES30.glUniform2fv(blur.location("uPairs[0]"), effect.pairs.size / 2, effect.pairs, 0) + } + } + blurPass(effect.ping, effect.work.texture, 1f / w, 0f) + blurPass(effect.work, effect.ping.texture, 0f, 1f / h) + var peak = effect.work + var level = 0 + while (peak.width > 1 || peak.height > 1) { + if (level == effect.reductions.size) effect.reductions.add(Target(true)) + val next = effect.reductions[level++] + ensureTarget(next, (peak.width + 1) / 2, (peak.height + 1) / 2) + pass(reduce, next, peak.texture, drawQuad) + peak = next + } + pass(normalize, effect.map, effect.work.texture, drawQuad) { + bind(normalize, "uPeak", 1, peak.texture) + GLES30.glUniform1i(normalize.location("uHalation"), if (effect.halation) 1 else 0) + } + pass(composite, effect.output, source, drawQuad) { + bind(composite, "uMap", 1, effect.map.texture) + GLES30.glUniform1i(composite.location("uHalation"), if (effect.halation) 1 else 0) + GLES30.glUniform1f(composite.location("uStrength"), strength) + } + return effect.output + } + + private fun pass(program: Program, target: Target, input: Int, drawQuad: (Int) -> Unit, uniforms: () -> Unit = {}) { + GLES30.glDisable(GLES30.GL_BLEND) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer) + GLES30.glViewport(0, 0, target.width, target.height) + GLES30.glUseProgram(program.id) + bind(program, "uInput", 0, input) + uniforms() + drawQuad(program.id) + checkGl("draw program=${program.id} target=${target.width}x${target.height}") + } + + private fun bind(program: Program, name: String, unit: Int, texture: Int) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glUniform1i(program.location(name), unit) + } + + private fun ensurePrograms() { + for (program in programs) { + if (program.id != 0) continue + val vertex = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER) + val fragment = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, program.source) + if (vertex != 0 && fragment != 0) program.id = GlUtils.linkProgram(vertex, fragment) + if (vertex != 0) GLES30.glDeleteShader(vertex) + if (fragment != 0) GLES30.glDeleteShader(fragment) + check(program.id != 0) { "Shader compile/link failed (${programs.indexOf(program)})" } + } + } + + private fun ensureTarget(target: Target, width: Int, height: Int) { + if (target.texture != 0 && target.width == width && target.height == height) return + val limit = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0) + check(width in 1..limit[0] && height in 1..limit[0]) { "Invalid target ${width}x$height, limit=${limit[0]}" } + target.release() + try { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + target.texture = ids[0] + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, target.texture) + val format = if (target.floating) GLES30.GL_RGBA16F else GLES30.GL_RGBA8 + GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, 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) + GLES30.glGenFramebuffers(1, ids, 0) + target.framebuffer = ids[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, target.texture, 0) + val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) + checkGl("allocation ${width}x$height format=$format") + check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) { "Framebuffer status=$status format=$format" } + target.width = width + target.height = height + } catch (failure: IllegalStateException) { + target.release() + throw failure + } + } + + private fun checkGl(stage: String) { + val error = GLES30.glGetError() + check(error == GLES30.GL_NO_ERROR) { "$stage glError=$error" } + } + + fun release() { + programs.forEach { GlUtils.deleteProgram(it.id); it.reset() } + listOf(halationEffect, bloomEffect).forEach { effect -> effect.targets().forEach { it.release() } } + } + + fun resetAfterContextLoss() { + programs.forEach { it.reset() } + listOf(halationEffect, bloomEffect).forEach { effect -> effect.targets().forEach { it.reset() } } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionShaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionShaders.kt new file mode 100644 index 00000000..204d5a41 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/HighlightDiffusionShaders.kt @@ -0,0 +1,127 @@ +package com.hinnka.mycamera.lut + +/** Snapseed Bloom/Halation equations, evaluated on display-encoded RGB. */ +internal object HighlightDiffusionShaders { + val EXTRACT = """ + #version 300 es + precision highp float; + precision highp sampler2D; + in vec2 vTexCoord; + uniform sampler2D uInput; + uniform float uThreshold; + uniform bool uHalation; + out vec4 fragColor; + void main() { + ivec2 size = textureSize(uInput, 0); + ivec2 pixel = clamp(ivec2(vTexCoord * vec2(size)), ivec2(0), size - 1); + vec3 color = texelFetch(uInput, pixel, 0).rgb; + float y = dot(color, vec3(0.299, 0.587, 0.114)); + float mask = clamp((y - uThreshold) / (1.0 - uThreshold), 0.0, 1.0); + fragColor = vec4(uHalation ? vec3(mask) : color * mask, 1.0); + } + """.trimIndent() + + // Adjacent Gaussian taps share one bilinear fetch; the kernel is still a single Gaussian. + val BLUR = """ + #version 300 es + precision highp float; + precision highp sampler2D; + in vec2 vTexCoord; + uniform sampler2D uInput; + uniform vec2 uStep; + uniform float uCenter; + uniform int uPairCount; + uniform vec2 uPairs[26]; + out vec4 fragColor; + void main() { + vec3 sum = texture(uInput, vTexCoord).rgb * uCenter; + for (int i = 0; i < 26; ++i) { + if (i >= uPairCount) break; + vec2 offset = uStep * uPairs[i].x; + sum += (texture(uInput, vTexCoord + offset).rgb + + texture(uInput, vTexCoord - offset).rgb) * uPairs[i].y; + } + fragColor = vec4(sum, 1.0); + } + """.trimIndent() + + val REDUCE = """ + #version 300 es + precision highp float; + precision highp sampler2D; + uniform sampler2D uInput; + out vec4 fragColor; + void main() { + ivec2 limit = textureSize(uInput, 0) - 1; + ivec2 p = ivec2(gl_FragCoord.xy) * 2; + vec3 peak = vec3(0.0); + for (int y = 0; y < 2; ++y) { + for (int x = 0; x < 2; ++x) { + peak = max(peak, texelFetch(uInput, min(p + ivec2(x, y), limit), 0).rgb); + } + } + fragColor = vec4(peak, 1.0); + } + """.trimIndent() + + val NORMALIZE = """ + #version 300 es + precision highp float; + precision highp sampler2D; + uniform sampler2D uInput; + uniform sampler2D uPeak; + uniform bool uHalation; + out vec4 fragColor; + void main() { + vec3 peakRgb = texelFetch(uPeak, ivec2(0), 0).rgb; + float peak = max(peakRgb.r, max(peakRgb.g, peakRgb.b)); + vec3 value = texelFetch(uInput, ivec2(gl_FragCoord.xy), 0).rgb; + value = peak > 0.0 ? clamp(value / peak, 0.0, 1.0) : vec3(0.0); + if (uHalation) { + float x = min(value.r * 3.0, 1.0); + float a = x < 0.4 ? 0.4 * pow(x / 0.4, 1.25) + : 0.4 + 0.6 * pow((x - 0.4) / 0.6, 0.8); + // The reference stores a truncated byte mask before full-resolution interpolation. + value = vec3(floor(clamp(a, 0.0, 1.0) * 255.0) / 255.0); + } + fragColor = vec4(value, 1.0); + } + """.trimIndent() + + val COMPOSITE = """ + #version 300 es + precision highp float; + precision highp sampler2D; + in vec2 vTexCoord; + uniform sampler2D uInput; + uniform sampler2D uMap; + uniform float uStrength; + uniform bool uHalation; + out vec4 fragColor; + void main() { + vec4 source = texture(uInput, vTexCoord); + vec3 color = source.rgb; + vec3 map = texture(uMap, vTexCoord).rgb; + vec3 linearColor = pow(max(color, vec3(0.0)), vec3(2.2)); + vec3 result; + if (uHalation) { + float y = dot(color, vec3(0.299, 0.587, 0.114)); + vec2 pixel = vTexCoord * vec2(textureSize(uInput, 0)); + float noise = fract(sin(dot(pixel, vec2(12.9898, 78.233))) * 43758.5453); + float grain = 1.0 - noise * (1.0 - map.r) * 0.5; + float destination = 1.0 / (1.0 + exp(-50.0 * (1.0 - y))); + vec3 glow = map.r * vec3(1.0, 0.05, 0.05) * uStrength * grain * destination; + result = pow(clamp(linearColor + glow, 0.0, 1.0), vec3(1.0 / 2.2)); + } else { + vec3 linearBloom = pow(max(map, vec3(0.0)), vec3(2.2)); + if (uStrength <= 0.5) { + vec3 full = pow(clamp(linearColor + linearBloom, 0.0, 1.0), vec3(1.0 / 2.2)); + result = mix(color, full, uStrength * 2.0); + } else { + result = pow(linearColor + linearBloom * (uStrength * 2.0), vec3(1.0 / 2.2)); + } + } + fragColor = vec4(result, source.a); + } + """.trimIndent() +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt index b423679b..adeed384 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt @@ -108,6 +108,7 @@ class LutImageProcessor(context: Context? = null) { private var lutSharpenWidth = 0 private var lutSharpenHeight = 0 private val filmGrainGl = FilmGrainGl(TAG) + private val highlightDiffusionGl = HighlightDiffusionGl(TAG) // HDF (Highlight Diffusion) 光晕效果资源 private var hdfExtractBlurHProgram = 0 @@ -134,29 +135,6 @@ class LutImageProcessor(context: Context? = null) { private var clarityOutputWidth = 0 private var clarityOutputHeight = 0 - // Halation (胶片红晕) 效果资源 - private var halationExtractBlurHProgram = 0 - private var halationBlurVProgram = 0 - private var halationTexId = IntArray(2) - private var halationFboId = IntArray(2) - private var halationWidth = 0 - private var halationHeight = 0 - private var bloomDownsampleFirstProgram = 0 - private var bloomDownsampleProgram = 0 - private var bloomUpsampleProgram = 0 - private var bloomCompositeProgram = 0 - private var bloomTexId = IntArray(0) - private var bloomFboId = IntArray(0) - private var bloomMipWidths = IntArray(0) - private var bloomMipHeights = IntArray(0) - private var bloomMipCount = 0 - private var bloomSourceWidth = 0 - private var bloomSourceHeight = 0 - private var bloomOutputTextureId = 0 - private var bloomOutputFboId = 0 - private var bloomOutputWidth = 0 - private var bloomOutputHeight = 0 - private var isInitialized = false // Uniform 位置 @@ -362,7 +340,6 @@ class LutImageProcessor(context: Context? = null) { val effectiveRecipeParams = colorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams) val halation = 0f val softLight = effectiveRecipeParams?.softLight ?: 0f - val redHalation = effectiveRecipeParams?.redHalation ?: 0f // 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。 val sharpening: Float = effectiveRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f @@ -412,10 +389,6 @@ class LutImageProcessor(context: Context? = null) { renderSoftLightBlur(inputTexId, width, height) currentCoroutineContext().ensureActive() } - if (redHalation > 0f) { - renderHalationBlur(inputTexId, width, height, redHalation) - currentCoroutineContext().ensureActive() - } // 执行渲染 val outputBitmap = performRender( @@ -514,7 +487,6 @@ class LutImageProcessor(context: Context? = null) { val effectiveRecipeParams = colorRecipeParams?.let(ColorPaletteMapper::mergeIntoEffectiveParams) val halation = 0f val softLight = effectiveRecipeParams?.softLight ?: 0f - val redHalation = effectiveRecipeParams?.redHalation ?: 0f // 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。 val sharpening: Float = effectiveRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f @@ -568,10 +540,6 @@ class LutImageProcessor(context: Context? = null) { renderSoftLightBlur(inputTexId, width, height) currentCoroutineContext().ensureActive() } - if (redHalation > 0f) { - renderHalationBlur(inputTexId, width, height, redHalation) - currentCoroutineContext().ensureActive() - } // 执行渲染 val outputBitmap = performRender( @@ -1006,14 +974,6 @@ class LutImageProcessor(context: Context? = null) { GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, if (softLight > 0f) softLightTexId[1] else 0) GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSoftLightTexture"), 5) - // 设置 Halation 参数 - GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uRedHalation"), redHalation) - if (redHalation > 0f) { - GLES30.glActiveTexture(GLES30.GL_TEXTURE4) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, halationTexId[1]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uRedHalationTexture"), 4) - } - // 设置色散参数 GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uChromaticAberration"), chromaticAberration) GLES30.glUniform2f(GLES30.glGetUniformLocation(program, "uTexelSize"), 1.0f / width, 1.0f / height) @@ -1060,12 +1020,14 @@ class LutImageProcessor(context: Context? = null) { val postSharpenTextureId = if (sharpened) lutSharpenTextureId else postClarityTextureId val postSharpenFramebufferId = if (sharpened) lutSharpenFboId else postClarityFramebufferId - val bloomApplied = bloom > 0.001f && renderLdrBloom(postSharpenTextureId, width, height, bloom) - val postBloomTextureId = if (bloomApplied) bloomOutputTextureId else postSharpenTextureId - val postBloomFramebufferId = if (bloomApplied) bloomOutputFboId else postSharpenFramebufferId + val diffusionOutput = highlightDiffusionGl.renderToTexture( + postSharpenTextureId, width, height, bloom, redHalation, ::drawQuad, + ) + val postDiffusionTextureId = diffusionOutput?.textureId ?: postSharpenTextureId + val postDiffusionFramebufferId = diffusionOutput?.framebufferId ?: postSharpenFramebufferId val filmGrainOutput = if (filmGrain > 0.001f) { filmGrainGl.renderToTexture( - sourceTextureId = postBloomTextureId, + sourceTextureId = postDiffusionTextureId, width = width, height = height, amount = filmGrain, @@ -1075,7 +1037,7 @@ class LutImageProcessor(context: Context? = null) { } else { null } - val readFramebufferId = filmGrainOutput?.framebufferId ?: postBloomFramebufferId + val readFramebufferId = filmGrainOutput?.framebufferId ?: postDiffusionFramebufferId GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readFramebufferId) val pixelSize = width * height * 4 @@ -1470,56 +1432,6 @@ class LutImageProcessor(context: Context? = null) { } } - private fun ensureHalationPrograms() { - if (halationExtractBlurHProgram == 0) { - halationExtractBlurHProgram = createFragmentProgram( - IMAGE_VERTEX_SHADER, - HALATION_EXTRACT_BLUR_H_SHADER, - "HalationExtractBlurH", - ) - } - if (halationBlurVProgram == 0) { - halationBlurVProgram = createFragmentProgram( - IMAGE_VERTEX_SHADER, - HDF_BLUR_V_SHADER, - "HalationBlurV", - ) - } - } - - private fun ensureBloomPrograms() { - // Bloom composite copies the source before adding highlights, even when denoise is disabled. - ensureBitmapDenoisePassthroughProgram() - if (bloomDownsampleFirstProgram == 0) { - bloomDownsampleFirstProgram = createFragmentProgram( - Shaders.SIMPLE_VERTEX_SHADER, - Shaders.BEVY_BLOOM_DOWNSAMPLE_FIRST, - "BloomDownsampleFirst", - ) - } - if (bloomDownsampleProgram == 0) { - bloomDownsampleProgram = createFragmentProgram( - Shaders.SIMPLE_VERTEX_SHADER, - Shaders.BEVY_BLOOM_DOWNSAMPLE, - "BloomDownsample", - ) - } - if (bloomUpsampleProgram == 0) { - bloomUpsampleProgram = createFragmentProgram( - Shaders.SIMPLE_VERTEX_SHADER, - Shaders.BEVY_BLOOM_UPSAMPLE, - "BloomUpsample", - ) - } - if (bloomCompositeProgram == 0) { - bloomCompositeProgram = createFragmentProgram( - Shaders.SIMPLE_VERTEX_SHADER, - Shaders.BEVY_BLOOM_COMPOSITE, - "BloomComposite", - ) - } - } - private fun ensureClarityPrograms() { if (clarityDownsampleProgram == 0) { clarityDownsampleProgram = createFragmentProgram( @@ -2409,41 +2321,6 @@ class LutImageProcessor(context: Context? = null) { return true } - private fun setupHalationFramebuffers(width: Int, height: Int) { - val dsW = width / 4 - val dsH = height / 4 - if (halationWidth == dsW && halationHeight == dsH && halationTexId[0] != 0) return - halationWidth = dsW - halationHeight = dsH - - for (i in 0..1) { - if (halationTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(halationTexId[i]), 0) - if (halationFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(halationFboId[i]), 0) - val t = IntArray(1) - val f = IntArray(1) - GLES30.glGenTextures(1, t, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexImage2D( - GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, - dsW, dsH, 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) - GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D( - GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, - GLES30.GL_TEXTURE_2D, t[0], 0 - ) - halationTexId[i] = t[0] - halationFboId[i] = f[0] - } - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - private fun renderSoftLightBlur( sourceTexId: Int, width: Int, @@ -2489,61 +2366,6 @@ class LutImageProcessor(context: Context? = null) { checkGlError("renderSoftLightBlur") } - private fun renderHalationBlur( - sourceTexId: Int, - width: Int, - height: Int, - halation: Float - ) { - ensureHalationPrograms() - setupHalationFramebuffers(width, height) - if (halationExtractBlurHProgram == 0 || halationBlurVProgram == 0) return - - val dsW = width / 4 - val dsH = height / 4 - val texelW = 1.0f / dsW - val texelH = 1.0f / dsH - - val threshold = 0.72f - halation.coerceIn(0f, 1f) * 0.22f - - val identityMatrix = FloatArray(16) - android.opengl.Matrix.setIdentityM(identityMatrix, 0) - - // Pass 1: Extract + Blur H - GLES30.glUseProgram(halationExtractBlurHProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, halationFboId[0]) - GLES30.glViewport(0, 0, dsW, dsH) - - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTexId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uTexelSize"), texelW, texelH) - GLES30.glUniform1f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uThreshold"), threshold) - GLES30.glUniform1f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uStrength"), halation) - - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uMVPMatrix"), 1, false, identityMatrix, 0 - ) - drawQuad(halationExtractBlurHProgram) - - // Pass 2: Blur V - GLES30.glUseProgram(halationBlurVProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, halationFboId[1]) - GLES30.glViewport(0, 0, dsW, dsH) - - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, halationTexId[0]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(halationBlurVProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(halationBlurVProgram, "uTexelSize"), texelW, texelH) - - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(halationBlurVProgram, "uMVPMatrix"), 1, false, identityMatrix, 0 - ) - drawQuad(halationBlurVProgram) - - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - /** * 渲染 HDF 光晕效果 * 3 pass: 高光提取+水平模糊 → 垂直模糊 → 全分辨率合成 @@ -2600,237 +2422,6 @@ class LutImageProcessor(context: Context? = null) { checkGlError("renderHDFBlur") } - private fun setupBloomOutputFramebuffer(width: Int, height: Int): Boolean { - if (bloomOutputFboId != 0 && - bloomOutputTextureId != 0 && - bloomOutputWidth == width && - bloomOutputHeight == height - ) { - return true - } - if (bloomOutputFboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bloomOutputFboId), 0) - if (bloomOutputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(bloomOutputTextureId), 0) - val f = IntArray(1) - val t = IntArray(1) - GLES30.glGenTextures(1, t, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, width, height, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, 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) - GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, t[0], 0) - val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) - if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { - PLog.e(TAG, "Bloom output framebuffer not complete: $status") - if (f[0] != 0) GLES30.glDeleteFramebuffers(1, f, 0) - if (t[0] != 0) GLES30.glDeleteTextures(1, t, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return false - } - bloomOutputTextureId = t[0] - bloomOutputFboId = f[0] - bloomOutputWidth = width - bloomOutputHeight = height - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return true - } - - private fun setupBloomFramebuffers(width: Int, height: Int): Boolean { - val maxMipDimension = BloomLdrSettings.MAX_MIP_DIMENSION - val scale = maxMipDimension.toFloat() / maxOf(1, height).toFloat() - var mipWidth = (width * scale).toInt().coerceAtLeast(1) - var mipHeight = (height * scale).toInt().coerceAtLeast(1) - val widths = mutableListOf() - val heights = mutableListOf() - repeat(BloomLdrSettings.MIP_COUNT) { - widths += mipWidth - heights += mipHeight - mipWidth = maxOf(1, mipWidth / 2) - mipHeight = maxOf(1, mipHeight / 2) - } - val nextWidths = widths.toIntArray() - val nextHeights = heights.toIntArray() - if (bloomSourceWidth == width && - bloomSourceHeight == height && - bloomTexId.isNotEmpty() && - bloomMipWidths.contentEquals(nextWidths) && - bloomMipHeights.contentEquals(nextHeights) - ) { - return true - } - releaseBloomFramebuffers() - bloomSourceWidth = width - bloomSourceHeight = height - bloomMipCount = nextWidths.size - bloomMipWidths = nextWidths - bloomMipHeights = nextHeights - bloomTexId = IntArray(bloomMipCount) - bloomFboId = IntArray(bloomMipCount) - for (i in 0 until bloomMipCount) { - val t = IntArray(1) - val f = IntArray(1) - GLES30.glGenTextures(1, t, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexImage2D( - GLES30.GL_TEXTURE_2D, - 0, - GLES30.GL_RGBA16F, - bloomMipWidths[i], - bloomMipHeights[i], - 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) - GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, t[0], 0) - bloomTexId[i] = t[0] - bloomFboId[i] = f[0] - val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) - if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { - PLog.e(TAG, "Bloom mip framebuffer[$i] not complete: $status") - releaseBloomFramebuffers() - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return false - } - } - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return true - } - - private fun releaseBloomFramebuffers() { - for (textureId in bloomTexId) { - if (textureId != 0) GLES30.glDeleteTextures(1, intArrayOf(textureId), 0) - } - for (fboId in bloomFboId) { - if (fboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(fboId), 0) - } - bloomTexId = IntArray(0) - bloomFboId = IntArray(0) - bloomMipWidths = IntArray(0) - bloomMipHeights = IntArray(0) - bloomMipCount = 0 - bloomSourceWidth = 0 - bloomSourceHeight = 0 - } - - private fun renderLdrBloom(sourceTextureId: Int, width: Int, height: Int, bloomStrength: Float): Boolean { - ensureBloomPrograms() - if (bitmapDenoisePassthroughProgram == 0 || bloomDownsampleFirstProgram == 0 || - bloomDownsampleProgram == 0 || bloomUpsampleProgram == 0 || bloomCompositeProgram == 0 - ) { - PLog.e( - TAG, - "Bloom programs unavailable: passthrough=$bitmapDenoisePassthroughProgram " + - "first=$bloomDownsampleFirstProgram downsample=$bloomDownsampleProgram " + - "upsample=$bloomUpsampleProgram composite=$bloomCompositeProgram" - ) - return false - } - if (!setupBloomFramebuffers(width, height)) { - return false - } - if (!setupBloomOutputFramebuffer(width, height)) { - return false - } - if (bloomMipCount <= 0) { - return false - } - - GLES30.glDisable(GLES30.GL_BLEND) - GLES30.glUseProgram(bloomDownsampleFirstProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[0]) - GLES30.glViewport(0, 0, bloomMipWidths[0], bloomMipHeights[0]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uInputTexelSize"), 1f / width, 1f / height) - val thresholdPrecomputations = BloomLdrSettings.thresholdPrecomputations() - GLES30.glUniform4f( - GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uThreshold"), - thresholdPrecomputations[0], - thresholdPrecomputations[1], - thresholdPrecomputations[2], - thresholdPrecomputations[3] - ) - drawQuad(bloomDownsampleFirstProgram) - - for (mip in 1 until bloomMipCount) { - GLES30.glUseProgram(bloomDownsampleProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[mip]) - GLES30.glViewport(0, 0, bloomMipWidths[mip], bloomMipHeights[mip]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[mip - 1]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomDownsampleProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(bloomDownsampleProgram, "uInputTexelSize"), 1f / bloomMipWidths[mip - 1], 1f / bloomMipHeights[mip - 1]) - drawQuad(bloomDownsampleProgram) - } - - GLES30.glEnable(GLES30.GL_BLEND) - GLES30.glBlendEquation(GLES30.GL_FUNC_ADD) - GLES30.glBlendFunc(GLES30.GL_CONSTANT_COLOR, GLES30.GL_ONE) - GLES30.glUseProgram(bloomUpsampleProgram) - for (mip in bloomMipCount - 1 downTo 1) { - val blend = BloomLdrSettings.mipAddWeight(mip, bloomMipCount, bloomStrength) - GLES30.glBlendColor(blend, blend, blend, blend) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[mip - 1]) - GLES30.glViewport(0, 0, bloomMipWidths[mip - 1], bloomMipHeights[mip - 1]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[mip]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomUpsampleProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(bloomUpsampleProgram, "uInputTexelSize"), 1f / bloomMipWidths[mip], 1f / bloomMipHeights[mip]) - drawQuad(bloomUpsampleProgram) - } - GLES30.glDisable(GLES30.GL_BLEND) - - val finalBlend = BloomLdrSettings.compositeStrength(bloomStrength) - val compositeMipLower = BloomLdrSettings.compositeMipLowerIndex(bloomMipCount, bloomStrength) - val compositeMipUpper = BloomLdrSettings.compositeMipUpperIndex(bloomMipCount, bloomStrength) - val compositeMipBlend = BloomLdrSettings.compositeMipBlend(bloomMipCount, bloomStrength) - renderTexturePassthrough(sourceTextureId, bloomOutputFboId, width, height) - GLES30.glEnable(GLES30.GL_BLEND) - GLES30.glBlendEquation(GLES30.GL_FUNC_ADD) - GLES30.glBlendFunc(GLES30.GL_ONE, GLES30.GL_ONE) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomOutputFboId) - GLES30.glViewport(0, 0, width, height) - GLES30.glUseProgram(bloomCompositeProgram) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[compositeMipLower]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexture"), 0) - GLES30.glActiveTexture(GLES30.GL_TEXTURE1) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[compositeMipUpper]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTextureNext"), 1) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexelSize"), - 1f / bloomMipWidths[compositeMipLower], - 1f / bloomMipHeights[compositeMipLower] - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexelSizeNext"), - 1f / bloomMipWidths[compositeMipUpper], - 1f / bloomMipHeights[compositeMipUpper] - ) - GLES30.glUniform1f(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBlend"), finalBlend) - GLES30.glUniform1f(GLES30.glGetUniformLocation(bloomCompositeProgram, "uMipBlend"), compositeMipBlend) - drawQuad(bloomCompositeProgram) - GLES30.glDisable(GLES30.GL_BLEND) - val error = GLES30.glGetError() - if (error != GLES30.GL_NO_ERROR) { - PLog.e(TAG, "renderLdrBloom final composite glError $error") - return false - } - return true - } - private fun checkGlError(op: String) { val error = GLES30.glGetError() if (error != GLES30.GL_NO_ERROR) { @@ -2990,7 +2581,6 @@ class LutImageProcessor(context: Context? = null) { .put(Shaders.FULL_QUAD_VERTICES) vertexBuffer?.position(0) - val flippedTexCoords = floatArrayOf( 0.0f, 0.0f, 1.0f, 0.0f, @@ -3097,6 +2687,7 @@ class LutImageProcessor(context: Context? = null) { if (clarityCompositeProgram != 0) GLES30.glDeleteProgram(clarityCompositeProgram) releaseClarityFramebuffers() filmGrainGl.release() + highlightDiffusionGl.release() for (i in 0..1) { if (hdfTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(hdfTexId[i]), 0) if (hdfFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(hdfFboId[i]), 0) @@ -3104,19 +2695,6 @@ class LutImageProcessor(context: Context? = null) { if (softLightFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(softLightFboId[i]), 0) } - if (halationExtractBlurHProgram != 0) GLES30.glDeleteProgram(halationExtractBlurHProgram) - if (halationBlurVProgram != 0) GLES30.glDeleteProgram(halationBlurVProgram) - for (i in 0..1) { - if (halationTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(halationTexId[i]), 0) - if (halationFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(halationFboId[i]), 0) - } - if (bloomDownsampleFirstProgram != 0) GLES30.glDeleteProgram(bloomDownsampleFirstProgram) - if (bloomDownsampleProgram != 0) GLES30.glDeleteProgram(bloomDownsampleProgram) - if (bloomUpsampleProgram != 0) GLES30.glDeleteProgram(bloomUpsampleProgram) - if (bloomCompositeProgram != 0) GLES30.glDeleteProgram(bloomCompositeProgram) - releaseBloomFramebuffers() - if (bloomOutputFboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bloomOutputFboId), 0) - if (bloomOutputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(bloomOutputTextureId), 0) EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) EGL14.eglDestroySurface(eglDisplay, eglSurface) @@ -3259,8 +2837,6 @@ class LutImageProcessor(context: Context? = null) { uniform sampler2D uHdfTexture; // 光晕合成纹理 uniform float uSoftLight; // 0.0 ~ 1.0 (柔光扩散强度) uniform sampler2D uSoftLightTexture; // 柔光扩散纹理 - uniform float uRedHalation; // 0.0 ~ 1.0 (胶片红晕强度) - uniform sampler2D uRedHalationTexture; // 胶片红晕合成纹理 // 色散效果 uniform float uChromaticAberration; // 0.0 ~ 1.0 (色散强度) @@ -3314,7 +2890,6 @@ class LutImageProcessor(context: Context? = null) { ${ShadowsHighlightsShader.GLSL} - float applyToneCurveToLuma(float luma, float toe, float shoulder, float pivot) { float safeLuma = clamp(luma, 0.0, 1.0); float pivotPoint = clamp(0.5 + pivot * 0.12, 0.2, 0.8); @@ -3588,12 +3163,6 @@ class LutImageProcessor(context: Context? = null) { color.rgb = (color.rgb - 0.5) * (1.0 - uHalation * 0.08) + 0.5; } - if (uRedHalation > 0.0) { - vec3 halationBlur = texture(uRedHalationTexture, uvCoord).rgb; - float halationMask = smoothstep(0.001, 0.06, dot(halationBlur, vec3(0.2126, 0.7152, 0.0722))); - vec3 halationStrength = vec3(0.42, 0.14, 0.02) * uRedHalation; - color.rgb += halationBlur * halationStrength * halationMask; - } // === LUT 处理(在色彩配方之后) === if (uLutEnabled && uLutIntensity > 0.0) { @@ -3646,41 +3215,7 @@ class LutImageProcessor(context: Context? = null) { "vec4 sampleImage(vec2 uv) { return texture(uImageTexture, uv); }\n" + SHADER_BODY - // === HDF (Highlight Diffusion Filter) \u0026 Halation Shaders === - - private val HALATION_EXTRACT_BLUR_H_SHADER = """ - #version 300 es - precision highp float; - - in vec2 vTexCoord; - out vec4 fragColor; - - uniform sampler2D uInputTexture; - uniform vec2 uTexelSize; - uniform float uThreshold; - uniform float uStrength; - - void main() { - vec3 tint = vec3(1.0, 0.28, 0.04); - - #define EXTRACT(sampleColor) \ - (max(sampleColor - vec3(uThreshold), vec3(0.0)) * tint * (1.5 + uStrength * 3.0) * smoothstep(uThreshold - 0.24, uThreshold + 0.36, max(sampleColor.r, max(sampleColor.g, sampleColor.b)))) - - vec3 color = texture(uInputTexture, vTexCoord).rgb; - vec3 sum = EXTRACT(color) * 0.204164; - - float weights[5] = float[](0.204164, 0.304005, 0.093910, 0.010416, 0.000005); - float offsets[5] = float[](0.0, 1.407333, 3.294215, 5.176470, 7.058823); - - for (int i = 1; i < 5; i++) { - float offset = offsets[i] * uTexelSize.x * 2.0; - sum += EXTRACT(texture(uInputTexture, vTexCoord + vec2(offset, 0.0)).rgb) * weights[i]; - sum += EXTRACT(texture(uInputTexture, vTexCoord - vec2(offset, 0.0)).rgb) * weights[i]; - } - - fragColor = vec4(sum, 1.0); - } - """.trimIndent() + // === HDF (Highlight Diffusion Filter) Shaders === /** * Pass 1: 提取高光区域 + 水平高斯模糊 diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index 188588a0..84284aa3 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -174,23 +174,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private var softLightFboId = IntArray(2) private var softLightWidth: Int = 0 private var softLightHeight: Int = 0 - private var halationExtractBlurHProgram: Int = 0 - private var halationBlurVProgram: Int = 0 - private var halationTexId = IntArray(2) - private var halationFboId = IntArray(2) - private var halationWidth: Int = 0 - private var halationHeight: Int = 0 - private var bloomDownsampleFirstProgram: Int = 0 - private var bloomDownsampleProgram: Int = 0 - private var bloomUpsampleProgram: Int = 0 - private var bloomCompositeProgram: Int = 0 - private var bloomTexId = IntArray(0) - private var bloomFboId = IntArray(0) - private var bloomMipWidths = IntArray(0) - private var bloomMipHeights = IntArray(0) - private var bloomMipCount: Int = 0 - private var bloomSourceWidth: Int = 0 - private var bloomSourceHeight: Int = 0 private var postProcessScratchFboId: Int = 0 private var postProcessScratchTextureId: Int = 0 private var postProcessScratchWidth: Int = 0 @@ -208,6 +191,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private var clarityOutputWidth: Int = 0 private var clarityOutputHeight: Int = 0 private val filmGrainGl = FilmGrainGl(TAG) + private val highlightDiffusionGl = HighlightDiffusionGl(TAG) private var filmGrainSourceTextureId: Int = 0 private var filmGrainSourceFboId: Int = 0 private var filmGrainSourceWidth: Int = 0 @@ -644,23 +628,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { softLightFboId = IntArray(2) softLightWidth = 0 softLightHeight = 0 - halationExtractBlurHProgram = 0 - halationBlurVProgram = 0 - halationTexId = IntArray(2) - halationFboId = IntArray(2) - halationWidth = 0 - halationHeight = 0 - bloomDownsampleFirstProgram = 0 - bloomDownsampleProgram = 0 - bloomUpsampleProgram = 0 - bloomCompositeProgram = 0 - bloomTexId = IntArray(0) - bloomFboId = IntArray(0) - bloomMipWidths = IntArray(0) - bloomMipHeights = IntArray(0) - bloomMipCount = 0 - bloomSourceWidth = 0 - bloomSourceHeight = 0 postProcessScratchFboId = 0 postProcessScratchTextureId = 0 postProcessScratchWidth = 0 @@ -676,6 +643,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { clarityOutputWidth = 0 clarityOutputHeight = 0 filmGrainGl.resetAfterContextLoss() + highlightDiffusionGl.resetAfterContextLoss() filmGrainSourceTextureId = 0 filmGrainSourceFboId = 0 filmGrainSourceWidth = 0 @@ -1533,28 +1501,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { return program } - private fun setupHalationFbos(width: Int, height: Int) { - val dsW = width / 4; val dsH = height / 4 - if (halationWidth == dsW && halationHeight == dsH && halationTexId[0] != 0) return - halationWidth = dsW; halationHeight = dsH - for (i in 0..1) { - if (halationTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(halationTexId[i]), 0) - if (halationFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(halationFboId[i]), 0) - val t = IntArray(1); val f = IntArray(1) - GLES30.glGenTextures(1, t, 0); GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA16F, dsW, dsH, 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) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, t[0], 0) - halationTexId[i] = t[0]; halationFboId[i] = f[0] - } - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - private fun setupHdfFbos(width: Int, height: Int) { val dsW = width / 4 val dsH = height / 4 @@ -1704,240 +1650,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) } - private fun renderHalationPreviewBlur(sourceTexId: Int, width: Int, height: Int) { - if (!ensureHalationPrograms()) return - setupHalationFbos(width, height) - if (halationExtractBlurHProgram == 0 || halationBlurVProgram == 0) return - val dsW = width / 4; val dsH = height / 4 - val spatialScale = getPreviewSpatialEffectScale(width, height) - val texelW = spatialScale / dsW; val texelH = spatialScale / dsH - val threshold = 0.72f - redHalation.coerceIn(0f, 1f) * 0.22f - - GLES30.glUseProgram(halationExtractBlurHProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, halationFboId[0]) - GLES30.glViewport(0, 0, dsW, dsH) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTexId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uTexelSize"), texelW, texelH) - GLES30.glUniform1f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uThreshold"), threshold) - GLES30.glUniform1f(GLES30.glGetUniformLocation(halationExtractBlurHProgram, "uStrength"), redHalation) - drawSimpleQuad(halationExtractBlurHProgram) - - GLES30.glUseProgram(halationBlurVProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, halationFboId[1]) - GLES30.glViewport(0, 0, dsW, dsH) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, halationTexId[0]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(halationBlurVProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(halationBlurVProgram, "uTexelSize"), texelW, texelH) - drawSimpleQuad(halationBlurVProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - - private fun setupBloomFbos(width: Int, height: Int): Boolean { - val maxMipDimension = BloomLdrSettings.MAX_MIP_DIMENSION - val scale = maxMipDimension.toFloat() / maxOf(1, height).toFloat() - var mipWidth = (width * scale).toInt().coerceAtLeast(1) - var mipHeight = (height * scale).toInt().coerceAtLeast(1) - val widths = mutableListOf() - val heights = mutableListOf() - repeat(BloomLdrSettings.MIP_COUNT) { - widths += mipWidth - heights += mipHeight - mipWidth = maxOf(1, mipWidth / 2) - mipHeight = maxOf(1, mipHeight / 2) - } - val count = widths.size - if (bloomSourceWidth == width && - bloomSourceHeight == height && - bloomMipCount == count && - bloomTexId.isNotEmpty() && - bloomMipWidths.contentEquals(widths.toIntArray()) && - bloomMipHeights.contentEquals(heights.toIntArray()) - ) { - return true - } - - releaseBloomFbos() - bloomSourceWidth = width - bloomSourceHeight = height - bloomMipCount = count - bloomMipWidths = widths.toIntArray() - bloomMipHeights = heights.toIntArray() - bloomTexId = IntArray(count) - bloomFboId = IntArray(count) - - for (i in 0 until count) { - val t = IntArray(1) - val f = IntArray(1) - GLES30.glGenTextures(1, t, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexImage2D( - GLES30.GL_TEXTURE_2D, - 0, - GLES30.GL_RGBA16F, - bloomMipWidths[i], - bloomMipHeights[i], - 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) - GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D( - GLES30.GL_FRAMEBUFFER, - GLES30.GL_COLOR_ATTACHMENT0, - GLES30.GL_TEXTURE_2D, - t[0], - 0 - ) - bloomTexId[i] = t[0] - bloomFboId[i] = f[0] - val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) - if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { - PLog.e(TAG, "Bloom mip framebuffer[$i] not complete: $status") - releaseBloomFbos() - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return false - } - } - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - return true - } - - private fun releaseBloomFbos() { - for (textureId in bloomTexId) { - if (textureId != 0) GLES30.glDeleteTextures(1, intArrayOf(textureId), 0) - } - for (fboId in bloomFboId) { - if (fboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(fboId), 0) - } - bloomTexId = IntArray(0) - bloomFboId = IntArray(0) - bloomMipWidths = IntArray(0) - bloomMipHeights = IntArray(0) - bloomMipCount = 0 - bloomSourceWidth = 0 - bloomSourceHeight = 0 - } - - private fun renderLdrBloom(targetFboId: Int, width: Int, height: Int, sourceTexId: Int) { - if (!ensureBloomPrograms()) { - drawFboToScreen(targetFboId, width, height, sourceTexId) - return - } - if (bloom <= 0.001f || bloomDownsampleFirstProgram == 0 || bloomDownsampleProgram == 0 || - bloomUpsampleProgram == 0 || bloomCompositeProgram == 0 - ) { - drawFboToScreen(targetFboId, width, height, sourceTexId) - return - } - if (!setupBloomFbos(width, height)) { - drawFboToScreen(targetFboId, width, height, sourceTexId) - return - } - if (bloomMipCount <= 0) { - drawFboToScreen(targetFboId, width, height, sourceTexId) - return - } - - val thresholdPrecomputations = BloomLdrSettings.thresholdPrecomputations() - - GLES30.glDisable(GLES30.GL_BLEND) - GLES30.glUseProgram(bloomDownsampleFirstProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[0]) - GLES30.glViewport(0, 0, bloomMipWidths[0], bloomMipHeights[0]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTexId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uInputTexture"), 0) - GLES30.glUniform2f(GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uInputTexelSize"), 1f / width, 1f / height) - GLES30.glUniform4f( - GLES30.glGetUniformLocation(bloomDownsampleFirstProgram, "uThreshold"), - thresholdPrecomputations[0], - thresholdPrecomputations[1], - thresholdPrecomputations[2], - thresholdPrecomputations[3] - ) - drawSimpleQuad(bloomDownsampleFirstProgram) - - for (mip in 1 until bloomMipCount) { - GLES30.glUseProgram(bloomDownsampleProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[mip]) - GLES30.glViewport(0, 0, bloomMipWidths[mip], bloomMipHeights[mip]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[mip - 1]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomDownsampleProgram, "uInputTexture"), 0) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomDownsampleProgram, "uInputTexelSize"), - 1f / bloomMipWidths[mip - 1], - 1f / bloomMipHeights[mip - 1] - ) - drawSimpleQuad(bloomDownsampleProgram) - } - - GLES30.glEnable(GLES30.GL_BLEND) - GLES30.glBlendEquation(GLES30.GL_FUNC_ADD) - GLES30.glBlendFunc(GLES30.GL_CONSTANT_COLOR, GLES30.GL_ONE) - GLES30.glUseProgram(bloomUpsampleProgram) - for (mip in bloomMipCount - 1 downTo 1) { - val blend = BloomLdrSettings.mipAddWeight(mip, bloomMipCount, bloom) - GLES30.glBlendColor(blend, blend, blend, blend) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bloomFboId[mip - 1]) - GLES30.glViewport(0, 0, bloomMipWidths[mip - 1], bloomMipHeights[mip - 1]) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[mip]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomUpsampleProgram, "uInputTexture"), 0) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomUpsampleProgram, "uInputTexelSize"), - 1f / bloomMipWidths[mip], - 1f / bloomMipHeights[mip] - ) - drawSimpleQuad(bloomUpsampleProgram) - } - GLES30.glDisable(GLES30.GL_BLEND) - - val finalBlend = BloomLdrSettings.compositeStrength(bloom) - val compositeMipLower = BloomLdrSettings.compositeMipLowerIndex(bloomMipCount, bloom) - val compositeMipUpper = BloomLdrSettings.compositeMipUpperIndex(bloomMipCount, bloom) - val compositeMipBlend = BloomLdrSettings.compositeMipBlend(bloomMipCount, bloom) - drawFboToScreen(targetFboId, width, height, sourceTexId) - GLES30.glEnable(GLES30.GL_BLEND) - GLES30.glBlendEquation(GLES30.GL_FUNC_ADD) - GLES30.glBlendFunc(GLES30.GL_ONE, GLES30.GL_ONE) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId) - GLES30.glViewport(0, 0, width, height) - GLES30.glUseProgram(bloomCompositeProgram) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[compositeMipLower]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexture"), 0) - GLES30.glActiveTexture(GLES30.GL_TEXTURE1) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bloomTexId[compositeMipUpper]) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTextureNext"), 1) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexelSize"), - 1f / bloomMipWidths[compositeMipLower], - 1f / bloomMipHeights[compositeMipLower] - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bloomCompositeProgram, "uBloomTexelSizeNext"), - 1f / bloomMipWidths[compositeMipUpper], - 1f / bloomMipHeights[compositeMipUpper] - ) - GLES30.glUniform1f(GLES30.glGetUniformLocation(bloomCompositeProgram, "uBlend"), finalBlend) - GLES30.glUniform1f(GLES30.glGetUniformLocation(bloomCompositeProgram, "uMipBlend"), compositeMipBlend) - drawSimpleQuad(bloomCompositeProgram) - GLES30.glDisable(GLES30.GL_BLEND) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - private fun setupPostProcessScratchFbo(width: Int, height: Int) { if (postProcessScratchFboId != 0 && postProcessScratchTextureId != 0 && @@ -2288,27 +2000,21 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private fun drawPostProcessEffects(targetFboId: Int, width: Int, height: Int, sourceTextureId: Int) { val hdfEnabled = halation > 0.001f - val halationEnabled = redHalation > 0.001f - val bloomEnabled = bloom > 0.001f val softLightEnabled = softLight > 0.001f - val compositeEnabled = hdfEnabled || halationEnabled || softLightEnabled + val compositeEnabled = hdfEnabled || softLightEnabled + val diffusionEnabled = bloom > 0.001f || redHalation > 0.001f - if (hdfEnabled) { - renderHdfPreviewBlur(sourceTextureId, width, height) - } - if (softLightEnabled) { - renderSoftLightPreviewBlur(sourceTextureId, width, height) - } - if (halationEnabled) { - renderHalationPreviewBlur(sourceTextureId, width, height) - } + if (hdfEnabled) renderHdfPreviewBlur(sourceTextureId, width, height) + if (softLightEnabled) renderSoftLightPreviewBlur(sourceTextureId, width, height) - if (compositeEnabled && bloomEnabled) { - setupPostProcessScratchFbo(width, height) - drawPostProcessComposite(postProcessScratchFboId, width, height, sourceTextureId) - renderLdrBloom(targetFboId, width, height, postProcessScratchTextureId) - } else if (bloomEnabled) { - renderLdrBloom(targetFboId, width, height, sourceTextureId) + if (diffusionEnabled) { + val source = if (compositeEnabled) { + setupPostProcessScratchFbo(width, height) + drawPostProcessComposite(postProcessScratchFboId, width, height, sourceTextureId) + postProcessScratchTextureId + } else sourceTextureId + val output = highlightDiffusionGl.renderToTexture(source, width, height, bloom, redHalation, ::drawSimpleQuad) + drawFboToScreen(targetFboId, width, height, output?.textureId ?: source) } else if (compositeEnabled) { drawPostProcessComposite(targetFboId, width, height, sourceTextureId) } else { @@ -2327,16 +2033,12 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(hdfCompositeProgram, "uOriginalTexture"), 0) GLES30.glActiveTexture(GLES30.GL_TEXTURE1) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdfTexId[1]) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, if (halation > 0.001f) hdfTexId[1] else sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(hdfCompositeProgram, "uBloomTexture"), 1) GLES30.glUniform1f(GLES30.glGetUniformLocation(hdfCompositeProgram, "uHalation"), halation) - GLES30.glActiveTexture(GLES30.GL_TEXTURE2) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, if (redHalation > 0f) halationTexId[1] else 0) - GLES30.glUniform1i(GLES30.glGetUniformLocation(hdfCompositeProgram, "uRedHalationTexture"), 2) - GLES30.glUniform1f(GLES30.glGetUniformLocation(hdfCompositeProgram, "uRedHalation"), redHalation) GLES30.glActiveTexture(GLES30.GL_TEXTURE3) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, if (softLight > 0f) softLightTexId[1] else 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, if (softLight > 0.001f) softLightTexId[1] else sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(hdfCompositeProgram, "uSoftLightTexture"), 3) GLES30.glUniform1f(GLES30.glGetUniformLocation(hdfCompositeProgram, "uSoftLight"), softLight) drawSimpleQuad(hdfCompositeProgram) @@ -2363,13 +2065,15 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) GLES30.glEnableVertexAttribArray(posLoc) GLES30.glVertexAttribPointer(posLoc, POSITION_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) - GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) - GLES30.glEnableVertexAttribArray(texLoc) - GLES30.glVertexAttribPointer(texLoc, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + if (texLoc >= 0) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + GLES30.glEnableVertexAttribArray(texLoc) + GLES30.glVertexAttribPointer(texLoc, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + } GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) GLES30.glDrawElements(GLES30.GL_TRIANGLES, Shaders.DRAW_ORDER.size, GLES30.GL_UNSIGNED_SHORT, 0) GLES30.glDisableVertexAttribArray(posLoc) - GLES30.glDisableVertexAttribArray(texLoc) + if (texLoc >= 0) GLES30.glDisableVertexAttribArray(texLoc) GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) } @@ -3448,6 +3152,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { clarityCompositeProgram = 0 releaseClarityPreviewFramebuffers() filmGrainGl.release() + highlightDiffusionGl.release() releaseFilmGrainSourceFramebuffer() // 释放 HDF 实时预览资源 @@ -3466,15 +3171,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { softLightTexId = IntArray(2); softLightFboId = IntArray(2) hdfWidth = 0; hdfHeight = 0 softLightWidth = 0; softLightHeight = 0 - if (bloomDownsampleFirstProgram != 0) GLES30.glDeleteProgram(bloomDownsampleFirstProgram) - if (bloomDownsampleProgram != 0) GLES30.glDeleteProgram(bloomDownsampleProgram) - if (bloomUpsampleProgram != 0) GLES30.glDeleteProgram(bloomUpsampleProgram) - if (bloomCompositeProgram != 0) GLES30.glDeleteProgram(bloomCompositeProgram) - bloomDownsampleFirstProgram = 0 - bloomDownsampleProgram = 0 - bloomUpsampleProgram = 0 - bloomCompositeProgram = 0 - releaseBloomFbos() if (postProcessScratchFboId != 0) { GLES30.glDeleteFramebuffers(1, intArrayOf(postProcessScratchFboId), 0) postProcessScratchFboId = 0 @@ -3777,51 +3473,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { return softLightBlurHProgram != 0 && hdfBlurVProgram != 0 } - private fun ensureHalationPrograms(): Boolean { - if (halationExtractBlurHProgram == 0) { - halationExtractBlurHProgram = createPostProcessProgram( - Shaders.HALATION_PREVIEW_EXTRACT_BLUR_H, - "halation extract/blur", - ) - } - if (halationBlurVProgram == 0) { - halationBlurVProgram = createPostProcessProgram( - Shaders.HALATION_PREVIEW_BLUR_V, - "halation vertical blur", - ) - } - return halationExtractBlurHProgram != 0 && halationBlurVProgram != 0 - } - - private fun ensureBloomPrograms(): Boolean { - if (bloomDownsampleFirstProgram == 0) { - bloomDownsampleFirstProgram = createPostProcessProgram( - Shaders.BEVY_BLOOM_DOWNSAMPLE_FIRST, - "bloom first downsample", - ) - } - if (bloomDownsampleProgram == 0) { - bloomDownsampleProgram = createPostProcessProgram( - Shaders.BEVY_BLOOM_DOWNSAMPLE, - "bloom downsample", - ) - } - if (bloomUpsampleProgram == 0) { - bloomUpsampleProgram = createPostProcessProgram( - Shaders.BEVY_BLOOM_UPSAMPLE, - "bloom upsample", - ) - } - if (bloomCompositeProgram == 0) { - bloomCompositeProgram = createPostProcessProgram( - Shaders.BEVY_BLOOM_COMPOSITE, - "bloom composite", - ) - } - return bloomDownsampleFirstProgram != 0 && bloomDownsampleProgram != 0 && - bloomUpsampleProgram != 0 && bloomCompositeProgram != 0 - } - private fun ensurePostProcessCompositeProgram(): Boolean { if (hdfCompositeProgram == 0) { hdfCompositeProgram = createPostProcessProgram( diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt index 9b80277d..6bb858ab 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt @@ -76,8 +76,6 @@ internal object PreviewColorShader { uniform sampler2D uCurveTexture; uniform bool uCurveEnabled; ${if (variant.includeSpatialRecipeEffects) """ - uniform sampler2D uRedHalationTexture; - uniform float uRedHalation; uniform sampler2D uSoftLightTexture; uniform float uSoftLight; """ else ""} @@ -328,15 +326,6 @@ internal object PreviewColorShader { color.rgb = sanitizeColor(vec3(r, g, b)); } - ${if (variant.includeSpatialRecipeEffects) """ - if (uRedHalation > 0.0) { - vec3 halationBlur = texture(uRedHalationTexture, uvCoord).rgb; - float halationMask = smoothstep(0.001, 0.06, dot(halationBlur, W)); - vec3 halationStrength = vec3(0.42, 0.14, 0.02) * uRedHalation; - color.rgb += halationBlur * halationStrength * halationMask; - color.rgb = sanitizeColor(color.rgb); - } - """ else ""} ${if (variant.includePreLogFilmGrain) """ if (uFilmGrain > 0.001) { diff --git a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt index 0dfbd33e..8683733b 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt @@ -170,7 +170,7 @@ object Shaders { } """.trimIndent() - /** HDF 合成:原图 + HDF 扩散 + spektrafilm 风格红色 halation */ + /** HDF 合成:原图 + HDF 扩散 + 柔光 */ val HDF_PREVIEW_COMPOSITE = """ #version 300 es precision highp float; @@ -179,8 +179,6 @@ object Shaders { uniform sampler2D uOriginalTexture; uniform sampler2D uBloomTexture; uniform float uHalation; - uniform sampler2D uRedHalationTexture; - uniform float uRedHalation; uniform sampler2D uSoftLightTexture; uniform float uSoftLight; @@ -208,249 +206,11 @@ object Shaders { color.rgb = (color.rgb - 0.5) * (1.0 - uHalation * 0.08) + 0.5; } - if (uRedHalation > 0.0) { - vec3 halationBlur = texture(uRedHalationTexture, vTexCoord).rgb; - float halationMask = smoothstep(0.001, 0.06, dot(halationBlur, vec3(0.2126, 0.7152, 0.0722))); - vec3 halationStrength = vec3(0.42, 0.14, 0.02) * uRedHalation; - color.rgb += halationBlur * halationStrength * halationMask; - } fragColor = clamp(color, 0.0, 1.0); } """.trimIndent() - /** Bevy Bloom: first downsample pass with Karis firefly reduction and soft threshold. */ - val BEVY_BLOOM_DOWNSAMPLE_FIRST = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform vec2 uInputTexelSize; - uniform vec4 uThreshold; - - float tonemappingLuminance(vec3 v) { - return dot(v, vec3(0.2126, 0.7152, 0.0722)); - } - - float karisAverage(vec3 color) { - float luma = tonemappingLuminance(pow(max(color, vec3(0.0)), vec3(1.0 / 2.2))) / 4.0; - return 1.0 / (1.0 + luma); - } - - vec3 thresholdHighlight(vec3 color) { - float luma = tonemappingLuminance(color); - float mask = 0.0; - if (uThreshold.z > 0.0) { - mask = smoothstep(uThreshold.y, uThreshold.y + uThreshold.z, luma); - } else { - mask = step(uThreshold.x, luma); - } - return color * mask; - } - - vec3 sampleInput(vec2 uv) { - vec3 color = texture(uInputTexture, uv).rgb; - if (uThreshold.x > 0.0 || uThreshold.z > 0.0) { - color = thresholdHighlight(color); - } - return color; - } - - vec3 sample13Tap(vec2 uv) { - vec2 ps = uInputTexelSize; - vec2 pl = 2.0 * ps; - vec2 ns = -ps; - vec2 nl = -pl; - vec3 a = sampleInput(uv + vec2(nl.x, pl.y)); - vec3 b = sampleInput(uv + vec2(0.0, pl.y)); - vec3 c = sampleInput(uv + vec2(pl.x, pl.y)); - vec3 d = sampleInput(uv + vec2(nl.x, 0.0)); - vec3 e = sampleInput(uv); - vec3 f = sampleInput(uv + vec2(pl.x, 0.0)); - vec3 g = sampleInput(uv + vec2(nl.x, nl.y)); - vec3 h = sampleInput(uv + vec2(0.0, nl.y)); - vec3 i = sampleInput(uv + vec2(pl.x, nl.y)); - vec3 j = sampleInput(uv + vec2(ns.x, ps.y)); - vec3 k = sampleInput(uv + vec2(ps.x, ps.y)); - vec3 l = sampleInput(uv + vec2(ns.x, ns.y)); - vec3 m = sampleInput(uv + vec2(ps.x, ns.y)); - - vec3 group0 = (a + b + d + e) * (0.125 / 4.0); - vec3 group1 = (b + c + e + f) * (0.125 / 4.0); - vec3 group2 = (d + e + g + h) * (0.125 / 4.0); - vec3 group3 = (e + f + h + i) * (0.125 / 4.0); - vec3 group4 = (j + k + l + m) * (0.5 / 4.0); - group0 *= karisAverage(group0); - group1 *= karisAverage(group1); - group2 *= karisAverage(group2); - group3 *= karisAverage(group3); - group4 *= karisAverage(group4); - return group0 + group1 + group2 + group3 + group4; - } - - void main() { - vec3 sampleColor = sample13Tap(vTexCoord); - fragColor = vec4(clamp(sampleColor, vec3(0.0), vec3(1.0)), 1.0); - } - """.trimIndent() - - /** Bevy Bloom: subsequent 13-tap downsample passes. */ - val BEVY_BLOOM_DOWNSAMPLE = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform vec2 uInputTexelSize; - - vec3 sample13Tap(vec2 uv) { - vec2 ps = uInputTexelSize; - vec2 pl = 2.0 * ps; - vec2 ns = -ps; - vec2 nl = -pl; - vec3 a = texture(uInputTexture, uv + vec2(nl.x, pl.y)).rgb; - vec3 b = texture(uInputTexture, uv + vec2(0.0, pl.y)).rgb; - vec3 c = texture(uInputTexture, uv + vec2(pl.x, pl.y)).rgb; - vec3 d = texture(uInputTexture, uv + vec2(nl.x, 0.0)).rgb; - vec3 e = texture(uInputTexture, uv).rgb; - vec3 f = texture(uInputTexture, uv + vec2(pl.x, 0.0)).rgb; - vec3 g = texture(uInputTexture, uv + vec2(nl.x, nl.y)).rgb; - vec3 h = texture(uInputTexture, uv + vec2(0.0, nl.y)).rgb; - vec3 i = texture(uInputTexture, uv + vec2(pl.x, nl.y)).rgb; - vec3 j = texture(uInputTexture, uv + vec2(ns.x, ps.y)).rgb; - vec3 k = texture(uInputTexture, uv + vec2(ps.x, ps.y)).rgb; - vec3 l = texture(uInputTexture, uv + vec2(ns.x, ns.y)).rgb; - vec3 m = texture(uInputTexture, uv + vec2(ps.x, ns.y)).rgb; - vec3 sampleColor = (a + c + g + i) * 0.03125; - sampleColor += (b + d + f + h) * 0.0625; - sampleColor += (e + j + k + l + m) * 0.125; - return sampleColor; - } - - void main() { - fragColor = vec4(sample13Tap(vTexCoord), 1.0); - } - """.trimIndent() - - /** Bevy Bloom: 3x3 tent upsample pass. */ - val BEVY_BLOOM_UPSAMPLE = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform vec2 uInputTexelSize; - - void main() { - float x = uInputTexelSize.x; - float y = uInputTexelSize.y; - vec2 uv = vTexCoord; - vec3 a = texture(uInputTexture, vec2(uv.x - x, uv.y + y)).rgb; - vec3 b = texture(uInputTexture, vec2(uv.x, uv.y + y)).rgb; - vec3 c = texture(uInputTexture, vec2(uv.x + x, uv.y + y)).rgb; - vec3 d = texture(uInputTexture, vec2(uv.x - x, uv.y)).rgb; - vec3 e = texture(uInputTexture, vec2(uv.x, uv.y)).rgb; - vec3 f = texture(uInputTexture, vec2(uv.x + x, uv.y)).rgb; - vec3 g = texture(uInputTexture, vec2(uv.x - x, uv.y - y)).rgb; - vec3 h = texture(uInputTexture, vec2(uv.x, uv.y - y)).rgb; - vec3 i = texture(uInputTexture, vec2(uv.x + x, uv.y - y)).rgb; - vec3 sampleColor = e * 0.25; - sampleColor += (b + d + f + h) * 0.125; - sampleColor += (a + c + g + i) * 0.0625; - fragColor = vec4(sampleColor, 1.0); - } - """.trimIndent() - - /** LDR Bloom: final blurred highlight contribution. */ - val BEVY_BLOOM_COMPOSITE = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uBloomTexture; - uniform sampler2D uBloomTextureNext; - uniform vec2 uBloomTexelSize; - uniform vec2 uBloomTexelSizeNext; - uniform float uBlend; - uniform float uMipBlend; - - vec3 sampleTentLower(vec2 uv) { - float x = uBloomTexelSize.x; - float y = uBloomTexelSize.y; - vec3 a = texture(uBloomTexture, vec2(uv.x - x, uv.y + y)).rgb; - vec3 b = texture(uBloomTexture, vec2(uv.x, uv.y + y)).rgb; - vec3 c = texture(uBloomTexture, vec2(uv.x + x, uv.y + y)).rgb; - vec3 d = texture(uBloomTexture, vec2(uv.x - x, uv.y)).rgb; - vec3 e = texture(uBloomTexture, vec2(uv.x, uv.y)).rgb; - vec3 f = texture(uBloomTexture, vec2(uv.x + x, uv.y)).rgb; - vec3 g = texture(uBloomTexture, vec2(uv.x - x, uv.y - y)).rgb; - vec3 h = texture(uBloomTexture, vec2(uv.x, uv.y - y)).rgb; - vec3 i = texture(uBloomTexture, vec2(uv.x + x, uv.y - y)).rgb; - vec3 sampleColor = e * 0.25; - sampleColor += (b + d + f + h) * 0.125; - sampleColor += (a + c + g + i) * 0.0625; - return sampleColor; - } - - vec3 sampleTentUpper(vec2 uv) { - float x = uBloomTexelSizeNext.x; - float y = uBloomTexelSizeNext.y; - vec3 a = texture(uBloomTextureNext, vec2(uv.x - x, uv.y + y)).rgb; - vec3 b = texture(uBloomTextureNext, vec2(uv.x, uv.y + y)).rgb; - vec3 c = texture(uBloomTextureNext, vec2(uv.x + x, uv.y + y)).rgb; - vec3 d = texture(uBloomTextureNext, vec2(uv.x - x, uv.y)).rgb; - vec3 e = texture(uBloomTextureNext, vec2(uv.x, uv.y)).rgb; - vec3 f = texture(uBloomTextureNext, vec2(uv.x + x, uv.y)).rgb; - vec3 g = texture(uBloomTextureNext, vec2(uv.x - x, uv.y - y)).rgb; - vec3 h = texture(uBloomTextureNext, vec2(uv.x, uv.y - y)).rgb; - vec3 i = texture(uBloomTextureNext, vec2(uv.x + x, uv.y - y)).rgb; - vec3 sampleColor = e * 0.25; - sampleColor += (b + d + f + h) * 0.125; - sampleColor += (a + c + g + i) * 0.0625; - return sampleColor; - } - - void main() { - vec3 lowerBloom = sampleTentLower(vTexCoord); - vec3 upperBloom = sampleTentUpper(vTexCoord); - vec3 bloom = mix(lowerBloom, upperBloom, uMipBlend) * uBlend; - fragColor = vec4(clamp(bloom, 0.0, 1.0), 1.0); - } - """.trimIndent() - - /** Halation Pass 1: 高光重建 + 暖红背反射种子 + 水平高斯模糊 */ - val HALATION_PREVIEW_EXTRACT_BLUR_H = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform vec2 uTexelSize; - uniform float uThreshold; - uniform float uStrength; - void main() { - vec3 tint = vec3(1.0, 0.28, 0.04); - - #define EXTRACT(sampleColor) \ - (max(sampleColor - vec3(uThreshold), vec3(0.0)) * tint * (1.5 + uStrength * 3.0) * smoothstep(uThreshold - 0.24, uThreshold + 0.36, max(sampleColor.r, max(sampleColor.g, sampleColor.b)))) - - vec3 color = texture(uInputTexture, vTexCoord).rgb; - vec3 sum = EXTRACT(color) * 0.204164; - - float blurOffsets[4] = float[](1.407333, 3.294215, 5.176470, 7.058823); - float blurWeights[4] = float[](0.304005, 0.093910, 0.010416, 0.000005); - for (int i = 0; i < 4; i++) { - float off = blurOffsets[i] * uTexelSize.x * 2.0; - sum += EXTRACT(texture(uInputTexture, vTexCoord + vec2(off, 0.0)).rgb) * blurWeights[i]; - sum += EXTRACT(texture(uInputTexture, vTexCoord - vec2(off, 0.0)).rgb) * blurWeights[i]; - } - fragColor = vec4(sum, 1.0); - } - """.trimIndent() - - /** Halation Pass 2: 垂直高斯模糊 */ - val HALATION_PREVIEW_BLUR_V = HDF_PREVIEW_BLUR_V /** * Focus Peaking Shader diff --git a/app/src/main/java/com/hinnka/mycamera/lut/VideoHighlightDiffusionGl.kt b/app/src/main/java/com/hinnka/mycamera/lut/VideoHighlightDiffusionGl.kt new file mode 100644 index 00000000..7eb2a244 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/VideoHighlightDiffusionGl.kt @@ -0,0 +1,123 @@ +package com.hinnka.mycamera.lut + +import android.opengl.GLES30 + +/** Adapts display-encoded diffusion passes to Media3's caller-owned output framebuffer. */ +internal class VideoHighlightDiffusionGl(logTag: String) { + private val diffusion = HighlightDiffusionGl(logTag) + private val grain = FilmGrainGl(logTag) + private var colorTexture = 0 + private var colorFramebuffer = 0 + private var colorWidth = 0 + private var colorHeight = 0 + private val drawFramebuffer = IntArray(1) + private val readFramebuffer = IntArray(1) + private val viewport = IntArray(4) + + /** Called only when Bloom or Halation is enabled. [drawColor] must defer film grain. */ + fun drawFrame( + width: Int, + height: Int, + bloom: Float, + halation: Float, + filmGrain: Float, + presentationTimeUs: Long, + drawQuad: (Int) -> Unit, + drawColor: () -> Unit, + ) { + GLES30.glGetIntegerv(GLES30.GL_DRAW_FRAMEBUFFER_BINDING, drawFramebuffer, 0) + GLES30.glGetIntegerv(GLES30.GL_READ_FRAMEBUFFER_BINDING, readFramebuffer, 0) + GLES30.glGetIntegerv(GLES30.GL_VIEWPORT, viewport, 0) + try { + ensureColorTarget(width, height) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, colorFramebuffer) + GLES30.glViewport(0, 0, width, height) + GLES30.glDisable(GLES30.GL_BLEND) + drawColor() + checkGl("video color pass") + val output = checkNotNull( + diffusion.renderToTexture(colorTexture, width, height, bloom, halation, drawQuad) + ) { "Video highlight diffusion produced no output" } + if (filmGrain > 0.001f) { + check(grain.drawToFramebuffer( + targetFramebufferId = drawFramebuffer[0], + sourceTextureId = output.textureId, + width = width, + height = height, + amount = filmGrain, + frameSeed = FilmGrainShaders.videoFrameSeed(presentationTimeUs), + drawQuad = drawQuad, + )) { "Video film grain pass failed" } + } else { + GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, output.framebufferId) + GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, drawFramebuffer[0]) + GLES30.glBlitFramebuffer( + 0, 0, width, height, 0, 0, width, height, + GLES30.GL_COLOR_BUFFER_BIT, GLES30.GL_NEAREST, + ) + checkGl("video diffusion output") + } + } finally { + // Media3 owns this framebuffer, including its lifetime and downstream texture consumers. + GLES30.glBindFramebuffer(GLES30.GL_DRAW_FRAMEBUFFER, drawFramebuffer[0]) + GLES30.glBindFramebuffer(GLES30.GL_READ_FRAMEBUFFER, readFramebuffer[0]) + GLES30.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]) + } + } + + private fun ensureColorTarget(width: Int, height: Int) { + if (colorTexture != 0 && width == colorWidth && height == colorHeight) return + val limit = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, limit, 0) + check(width in 1..limit[0] && height in 1..limit[0]) { + "Video color target ${width}x$height exceeds texture limit ${limit[0]}" + } + releaseColorTarget() + try { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + colorTexture = ids[0] + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, colorTexture) + GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA8, 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) + GLES30.glGenFramebuffers(1, ids, 0) + colorFramebuffer = ids[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, colorFramebuffer) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, colorTexture, 0, + ) + val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) + checkGl("video RGBA8 color target allocation") + check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) { "Video color framebuffer status=$status" } + colorWidth = width + colorHeight = height + } catch (failure: IllegalStateException) { + releaseColorTarget() + throw failure + } + } + + private fun checkGl(stage: String) { + val error = GLES30.glGetError() + check(error == GLES30.GL_NO_ERROR) { "$stage glError=$error" } + } + + private fun releaseColorTarget() { + if (colorFramebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(colorFramebuffer), 0) + if (colorTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(colorTexture), 0) + colorFramebuffer = 0 + colorTexture = 0 + colorWidth = 0 + colorHeight = 0 + } + + fun release() { + diffusion.release() + grain.release() + releaseColorTarget() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt b/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt index 6cedcf33..1e322173 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/VideoLutEffect.kt @@ -64,7 +64,7 @@ class VideoLutEffect( @UnstableApi private class VideoLutShaderProgram( private val context: Context, - useHdr: Boolean, + private val useHdr: Boolean, private val effect: VideoLutEffect ) : BaseGlShaderProgram(useHdr, /* texturePoolCapacity= */ 1) { @@ -737,6 +737,7 @@ private class VideoLutShaderProgram( private var curveTextureId = 0 private val basicToneTextures = BasicToneGlTextures() private val logInput = LogInputGl() + private val highlightDiffusion = VideoHighlightDiffusionGl(TAG) private var lastLutConfig: LutConfig? = null private var lastRecipeParams: ColorRecipeParams? = null @@ -747,6 +748,8 @@ private class VideoLutShaderProgram( val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER) val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER) programId = GlUtils.linkProgram(vertexShader, fragmentShader) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) positionVbo = GlUtils.createBuffer(positionBuffer) texCoordVbo = GlUtils.createBuffer(texCoordBuffer) @@ -775,12 +778,46 @@ private class VideoLutShaderProgram( } override fun drawFrame(inputTexId: Int, presentationTimeUs: Long) { -// PLog.v("VideoLutShaderProgram", "drawFrame called, inputTexId: $inputTexId, presentationTimeUs: $presentationTimeUs") - if (programId == 0) return - + if (programId == 0) throw VideoFrameProcessingException("Video color program unavailable", presentationTimeUs) val currentLutConfig = effect.lutConfig val currentRecipeParams = effect.recipeParams + val bloom = currentRecipeParams?.bloom ?: 0f + val halation = currentRecipeParams?.redHalation ?: 0f + val diffusionEnabled = bloom > 0.001f || halation > 0.001f + // Media3 1.10 defaults to display-encoded SDR, but uses linear RGB for HDR output. + if (diffusionEnabled && useHdr) { + throw VideoFrameProcessingException("Bloom and Halation require an SDR video working space", presentationTimeUs) + } + val previousVao = IntArray(1) + if (isGles3Context) { + GLES30.glGetIntegerv(GLES30.GL_VERTEX_ARRAY_BINDING, previousVao, 0) + GLES30.glBindVertexArray(0) + } + try { + if (diffusionEnabled) { + highlightDiffusion.drawFrame( + inputWidth, inputHeight, bloom, halation, + currentRecipeParams?.filmGrain ?: 0f, presentationTimeUs, ::drawQuad, + ) { + drawColorFrame(inputTexId, presentationTimeUs, currentLutConfig, currentRecipeParams, deferFilmGrain = true) + } + } else { + drawColorFrame(inputTexId, presentationTimeUs, currentLutConfig, currentRecipeParams, deferFilmGrain = false) + } + } catch (failure: IllegalStateException) { + throw VideoFrameProcessingException(failure, presentationTimeUs) + } finally { + if (isGles3Context) GLES30.glBindVertexArray(previousVao[0]) + } + } + private fun drawColorFrame( + inputTexId: Int, + presentationTimeUs: Long, + currentLutConfig: LutConfig?, + currentRecipeParams: ColorRecipeParams?, + deferFilmGrain: Boolean, + ) { // 检查并重新上传 LUT 纹理 if (currentLutConfig != lastLutConfig || hasPendingUpdate) { lastLutConfig = currentLutConfig @@ -811,30 +848,6 @@ private class VideoLutShaderProgram( GLES30.glUseProgram(programId) logInput.bind(GLES30.glGetUniformLocation(programId, "uInverseAcr3Texture"), textureUnit = 4) - var previousVao = 0 - if (isGles3Context) { - val params = IntArray(1) - GLES30.glGetIntegerv(GLES30.GL_VERTEX_ARRAY_BINDING, params, 0) - previousVao = params[0] - if (previousVao != 0) { - GLES30.glBindVertexArray(0) - } - } - - // 绑定位置属性 (VBO) - val aPositionLoc = GLES30.glGetAttribLocation(programId, "aPosition") - GLES30.glEnableVertexAttribArray(aPositionLoc) - GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, positionVbo) - GLES30.glVertexAttribPointer(aPositionLoc, 2, GLES30.GL_FLOAT, false, 0, 0) - - // 绑定纹理坐标属性 (VBO) - val aTexCoordLoc = GLES30.glGetAttribLocation(programId, "aTexCoord") - GLES30.glEnableVertexAttribArray(aTexCoordLoc) - GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordVbo) - GLES30.glVertexAttribPointer(aTexCoordLoc, 2, GLES30.GL_FLOAT, false, 0, 0) - - GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) - // 绑定输入视频纹理 (GL_TEXTURE0) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTexId) @@ -883,7 +896,7 @@ private class VideoLutShaderProgram( GLES30.glUniform1i(GLES30.glGetUniformLocation(programId, "uColorRecipeEnabled"), if (colorRecipeEnabled) 1 else 0) GLES30.glUniform1f( GLES30.glGetUniformLocation(programId, "uFilmGrain"), - currentRecipeParams?.filmGrain ?: 0f, + if (deferFilmGrain) 0f else currentRecipeParams?.filmGrain ?: 0f, ) GLES30.glUniform1f( GLES30.glGetUniformLocation(programId, "uFilmGrainSeed"), @@ -990,11 +1003,29 @@ private class VideoLutShaderProgram( currentRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f, ) - GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4) - checkGlError("glDrawArrays") - if (isGles3Context && previousVao != 0) { - GLES30.glBindVertexArray(previousVao) + drawQuad(programId) + val error = GLES30.glGetError() + check(error == GLES30.GL_NO_ERROR) { "Video color draw failed: glError=$error" } + } + + private fun drawQuad(program: Int) { + val position = GLES30.glGetAttribLocation(program, "aPosition") + val texCoord = GLES30.glGetAttribLocation(program, "aTexCoord") + if (position >= 0) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, positionVbo) + GLES30.glEnableVertexAttribArray(position) + GLES30.glVertexAttribPointer(position, 2, GLES30.GL_FLOAT, false, 0, 0) } + // Reduction shaders can optimize away the texture-coordinate attribute. + if (texCoord >= 0) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordVbo) + GLES30.glEnableVertexAttribArray(texCoord) + GLES30.glVertexAttribPointer(texCoord, 2, GLES30.GL_FLOAT, false, 0, 0) + } + GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4) + if (position >= 0) GLES30.glDisableVertexAttribArray(position) + if (texCoord >= 0) GLES30.glDisableVertexAttribArray(texCoord) + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0) } private fun uploadLutTexture(lutConfig: LutConfig) { @@ -1007,6 +1038,7 @@ private class VideoLutShaderProgram( PLog.d("VideoLutShaderProgram", "Generated new 3D LUT texture ID: $lutTextureId") } + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, lutTextureId) checkGlError("glBindTexture 3D") GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) @@ -1068,6 +1100,7 @@ private class VideoLutShaderProgram( GLES30.glGenTextures(1, ids, 0) curveTextureId = ids[0] } + GLES30.glActiveTexture(GLES30.GL_TEXTURE3) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, curveTextureId) 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) @@ -1089,11 +1122,19 @@ private class VideoLutShaderProgram( } override fun release() { - super.release() + try { + super.release() + } finally { + releaseOwnedResources() + } + } + + private fun releaseOwnedResources() { deleteLutTexture() deleteCurveTexture() basicToneTextures.release() logInput.release() + highlightDiffusion.release() if (positionVbo != 0) { GLES30.glDeleteBuffers(1, intArrayOf(positionVbo), 0) positionVbo = 0 diff --git a/app/src/main/java/com/hinnka/mycamera/model/ColorRecipe.kt b/app/src/main/java/com/hinnka/mycamera/model/ColorRecipe.kt index b421c4bf..49b57d57 100644 --- a/app/src/main/java/com/hinnka/mycamera/model/ColorRecipe.kt +++ b/app/src/main/java/com/hinnka/mycamera/model/ColorRecipe.kt @@ -33,10 +33,10 @@ data class ColorRecipeParams( val bleachBypass: Float = 0f, // 0.0 ~ 1.0 (留银冲洗强度,0为无效果) val clarity: Float = 0f, // -1.0 ~ 1.0 (局部对比度,0为无效果) val sharpness: Float = 0f, // -1.0 ~ 1.0 (sRGB 锐度,负值柔化,正值锐化) - val bloom: Float = 0f, // 0.0 ~ 1.0 (Bevy Bloom 泛光强度,0为无效果) + val bloom: Float = 0f, // 0.0 ~ 1.0 (高光颜色扩散泛光强度,0为无效果) val softLight: Float = 0f, // 0.0 ~ 1.0 (柔光扩散强度,0为无效果) - val halation: Float = 0f, // 0.0 ~ 1.0 (高光扩散强度,0为无效果,模拟 GR3 HDF) - val redHalation: Float = 0f, // 0.0 ~ 1.0 (胶片暖红色边缘光晕强度,0为无效果) + val halation: Float = 0f, // 历史 HDF 字段,配方读写时归零;当前光晕使用 redHalation + val redHalation: Float = 0f, // 0.0 ~ 1.0 (高光遮罩扩散红色光晕强度,0为无效果) val chromaticAberration: Float = 0f, // 0.0 ~ 1.0 (色散/边缘溢色强度,0为无效果) val noise: Float = 0f, // 0.0 ~ 1.0 (噪点强度,包含亮度和色彩噪点,0为无效果) val lowRes: Float = 0f, // 0.0 ~ 1.0 (低像素强度,0为无效果) diff --git a/app/src/main/java/com/hinnka/mycamera/model/EffectParams.kt b/app/src/main/java/com/hinnka/mycamera/model/EffectParams.kt index a38f918b..9b120cf9 100644 --- a/app/src/main/java/com/hinnka/mycamera/model/EffectParams.kt +++ b/app/src/main/java/com/hinnka/mycamera/model/EffectParams.kt @@ -12,7 +12,7 @@ data class EffectParams( val flash: Float = 0f, // 镜头轴向直闪模拟 (0.0 ~ 1.0) val filmGrain: Float = 0f, // 胶片颗粒 (0.0 ~ 1.0) val clarity: Float = 0f, // 清晰度 (-1.0 ~ 1.0) - val bloom: Float = 0f, // Bevy Bloom 泛光 (0.0 ~ 1.0) + val bloom: Float = 0f, // 高光颜色扩散泛光 (0.0 ~ 1.0) val softLight: Float = 0f, // 柔光扩散 (0.0 ~ 1.0) val hdf: Float = 0f, // 高光扩散 HDF (0.0 ~ 1.0) val halation: Float = 0f, // 边缘红晕 Halation (0.0 ~ 1.0) diff --git a/docs/highlight-diffusion.md b/docs/highlight-diffusion.md new file mode 100644 index 00000000..e4fda71b --- /dev/null +++ b/docs/highlight-diffusion.md @@ -0,0 +1,90 @@ +# 泛光与光晕 + +`ColorRecipeParams.bloom` 控制泛光,`redHalation` 控制界面中的光晕,范围仍为 +0–1;0 表示关闭。JSON、预设和数据库字段保持兼容,旧配方加载后使用新算法,因此 +相同强度的外观会改变。历史 `halation` 字段属于已停用的 HDF,并非当前光晕入口。 + +预览、录像和照片导出共用 `HighlightDiffusionGl`。两种效果均从完成调色的二维纹理 +生成扩散图,先光晕、后泛光,再进入原有最终颗粒步骤。原有 Video Log 的前置颗粒 +策略保持不变。光晕不再在照片导出的调色前提取高光。 + +## 算法与参数 + +依据本地 Snapseed 4.1.6 的 Bloom / Halation 静态分析,保留其默认形态参数,现有 +滑杆只改变合成强度。输入是显示编码 RGB;合成时使用参考实现的 2.2 次幂转换。 + +| 参数 | 泛光 Bloom | 光晕 Halation | +| --- | --- | --- | +| 工作图最长边 | 256,保持比例,不放大小图 | 512,保持比例,不放大小图 | +| 高光来源范围 | 40 | 20 | +| 高光阈值 | 0.598 | 0.794 | +| 模糊尺寸参数 | 70 | 25 | +| 高斯 σ / 截断半径 | 17.5 / 52 像素 | 5 / 15 像素 | +| 形态参数 | softness 50,合成 gamma 2.2 | hardness 20,幂指数 1.25 | +| 颜色与其他参数 | 保留高光颜色 | hue 0 → RGB (1, 0.05, 0.05),graininess 50,destinationRange 100,globalShift 0 | + +共同高光遮罩:`M = clamp((Y − T) / (1 − T), 0, 1)`,其中 +`Y = dot(C, (0.299, 0.587, 0.114))`,按工作图像素中心最近邻提取输入。 + +- 泛光对 `C × M` 做高斯模糊,再除以全图 RGB 最大值。强度 ≤ 0.5 时,在原图与 + gamma 域完整泛光之间插值;强度 > 0.5 时,提高 gamma 域的泛光能量。 +- 光晕只模糊 `M`,以全图最大值的三分之一归一化,施加以 0.4 为分界的硬度曲线。 + 遮罩截断为 8 位值后再进行全分辨率插值;合成时叠加红色、空间颗粒和目标亮度门控。 +- 峰值为零时明确生成全零扩散图,避免除零。强度 ≤ 0.001 时不执行对应效果,与现有 + 预览开关精度保持一致。 + +## GPU 实现 + +高光提取、水平/垂直模糊、最大值归约、归一化、合成均在同一 GLES context 完成, +不回读峰值。高斯核用相邻权重配对及线性采样减少采样次数;边界为 clamp-to-edge。 +最大值逐级以 2×2 归约到 1×1,奇数尺寸向上取整并覆盖末行、末列。 + +模糊及归约使用 RGBA16F,光晕遮罩及最终输出使用 RGBA8;泛光归一化图使用 RGBA16F。 +这保留弱高光,但与参考 CPU 浮点计算存在半精度舍入差异,不承诺逐像素一致。 +各 pass 读写不同纹理;两效果分别拥有输出纹理,避免同时开启时产生纹理反馈。 +尺寸变化重建目标,context 丢失清空句柄,正常释放删除 program / texture / framebuffer。 + +## 验证 + +2026-09-09:`./gradlew compileDefaultDebugKotlin` 通过。 + +在 PMA110 / Adreno 840 / GLES 3.2 V@0842.44 上,以独立可执行程序运行生产 GLSL, +验证实际 compile/link、RGBA16F 分配、draw、归约、后续采样与 readback。 +60 组检查涵盖黑图、低亮度图、白图、彩色高光、边缘高光、横竖图、奇数尺寸、1×1、 +1×33,以及 0 / 0.25 / 0.5 / 0.75 / 1 强度。 + +- 泛光归一化图与独立双精度逐 tap CPU 实现最大误差 0.001363;最终输出最大误差 + 0.003202(归一化 RGB)。 +- 光晕遮罩最大误差 1/255;最终输出通过 CPU 公式的颗粒上下界检查,最大超界误差 + 0.003405。未将 CPU `sin` 的随机数结果作为跨驱动逐像素判据。 +- 所有输出有限;零强度、黑图和阈值以下图像保持不变。 + +此外,通过 `app_process` 加载项目实际编译的 `HighlightDiffusionGl` 与着色器类, +验证 1×1、17×9、513×259、259×513、1920×1080 尺寸切换、效果开关、连续帧复用、 +两效果组合与分别串联的像素一致性,以及 context 丢失和 release 后重建。 +诊断仅替换日志和基础 shader 编译包装,不替换生产组件的调度与资源管理逻辑。 + +上述诊断不安装 APK、不运行 Android Test。尚未进行 App 内取景与成片目视对比, +也未验证 Mali 等其他驱动上的实际渲染表现。 + +## Media3 视频播放与导出 + +后续检查发现,相机录像使用的 `LutRenderer` 和相册使用的 `VideoLutEffect` 是独立 +链路;上面的首次重构只接通前者。现已在 `VideoLutEffect` 中读取 `bloom` / +`redHalation`,通过 `VideoHighlightDiffusionGl` 接入同一扩散组件。覆盖调用此 effect 的 +相册视频播放、动态照片播放、视频编辑预览、视频导出和动态照片视频片段处理。 + +启用时,色彩/LUT/锐化先写入 RGBA8 中间纹理,随后执行光晕、泛光和最终颗粒,再写回 +Media3 管理的输出 framebuffer。主调色 pass 暂停颗粒,避免重复添加或让颗粒参与 +高光提取。关闭两项时保留原单 pass 路径。输出 framebuffer、read framebuffer、 +viewport 和外部 VAO 在返回及异常路径恢复;处理失败转换为带时间戳的 +`VideoFrameProcessingException`,不静默输出缺失效果的视频。 + +已核对项目依赖的 Media3 1.10.0 本地源码:默认 SDR 工作空间使用显示编码 RGB, +与此算法一致;HDR 输出使用线性工作空间。当前两项只支持 SDR;若 `useHdr=true` +且启用了任一项,会明确报告不支持,不能把此实现视为 HDR 泛光算法。 + +接入后 Kotlin 编译通过。新增 Media3 适配层的独立设备诊断进程被系统以 SIGKILL +终止(exit 137,限制 Java 堆重试亦然),日志未确认具体原因,不能认定为渲染验证 +通过。未进行完整的视频解码、播放和编码导出验证;先前的 60 组检查与 context 恢复 +结果仅证明共用扩散组件,不能替代该视频适配层的端到端验证。