feat: replace BM3D and NLM with wavelet-based profile denoising

This commit is contained in:
zhoubinjia committed 2026-05-20 16:11:24 +08:00
1 parent d525292103
commit 56c25b0532
9 files changed
+1273 -1069

No files matched your search

+1 -1
View File
@@ -112,7 +112,7 @@ void main() {
// ── Y-guided spatial chroma denoising ──
// Chroma noise is LOW-FREQUENCY (large color blobs), so we must sample
// widely spaced pixels to break the spatial correlation.
// Matches BM3D PASS0 approach: 5×5 window with large step scale.
// 5×5 guided window with large step scale.
{
int cx = int(floor(localFx));
int cy = int(floor(localFy));
@@ -8,9 +8,10 @@ import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.opengl.EGLSurface
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.ColorPaletteMapper
import com.hinnka.mycamera.raw.BM3DShaders
import com.hinnka.mycamera.raw.DenoiseProfileShaders
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.currentCoroutineContext
@@ -22,6 +23,9 @@ import java.nio.FloatBuffer
import java.nio.ShortBuffer
import java.util.concurrent.Executors
import androidx.core.graphics.createBitmap
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
@@ -51,16 +55,23 @@ class LutImageProcessor {
private var texCoordBuffer: FloatBuffer? = null
private var indexBuffer: ShortBuffer? = null
private var nlmChromaProgram = 0
private var nlmPassHProgram = 0
private var nlmPassVProgram = 0
private var bitmapDenoisePreconditionProgram = 0
private var bitmapDenoiseDecomposeProgram = 0
private var bitmapDenoiseSynthesizeProgram = 0
private var bitmapDenoiseReduceFirstProgram = 0
private var bitmapDenoiseReduceSecondProgram = 0
private var bitmapDenoiseBacktransformProgram = 0
private var bitmapDenoisePassthroughProgram = 0
private var nlmChromaTexId = 0
private var nlmChromaFboId = 0
private val nlmPassTexId = IntArray(2)
private val nlmPassFboId = IntArray(2)
private var nlmWidth = 0
private var nlmHeight = 0
private val bitmapDenoiseTexId = IntArray(2)
private val bitmapDenoiseFboId = IntArray(2)
private val bitmapDenoiseDetailTexIds = IntArray(DenoiseProfileShaders.BANDS)
private var bitmapDenoiseReduceMBufferId = 0
private var bitmapDenoiseReduceRBufferId = 0
private var bitmapDenoiseReduceBufSize = 0
private var bitmapDenoiseReduceSize = 0
private var bitmapDenoiseWidth = 0
private var bitmapDenoiseHeight = 0
// HDF (Highlight Diffusion) 光晕效果资源
private var hdfExtractBlurHProgram = 0
@@ -199,7 +210,7 @@ class LutImageProcessor {
// 初始化 shader 和缓冲区
initShaderProgram()
initNLMPrograms()
initBitmapDenoiseProfilePrograms()
initHDFPrograms()
initBuffers()
@@ -221,7 +232,7 @@ class LutImageProcessor {
* @param colorRecipeParams 色彩配方参数
* @param sharpeningValue 锐化强度
* @param noiseReductionValue 降噪强度
* @param chromaNoiseReductionValue 减少杂色强度
* @param chromaNoiseReductionValue 兼容旧元数据,bitmap denoiseprofile 使用 noiseReductionValue 统一控制亮度和色度
*/
suspend fun applyLut(
argbData: ShortBuffer,
@@ -251,7 +262,6 @@ class LutImageProcessor {
// 后期处理参数
val sharpening: Float = sharpeningValue
val noiseReduction: Float = noiseReductionValue
val chromaNoiseReduction: Float = chromaNoiseReductionValue
// 激活上下文
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
@@ -264,8 +274,8 @@ class LutImageProcessor {
uploadImageTextureFromArgb(argbData, width, height)
currentCoroutineContext().ensureActive()
if (noiseReduction > 0 || chromaNoiseReduction > 0) {
renderNLMDenoise(imageTextureId, width, height, noiseReduction, chromaNoiseReduction)
if (noiseReduction > 0) {
renderBitmapDenoiseProfile(imageTextureId, width, height, noiseReduction)
currentCoroutineContext().ensureActive()
}
@@ -274,7 +284,7 @@ class LutImageProcessor {
uploadLutTexture(lutConfig)
}
val inputTexId = if (noiseReduction > 0 || chromaNoiseReduction > 0) nlmPassTexId[1] else imageTextureId
val inputTexId = if (noiseReduction > 0) bitmapDenoiseTexId[1] else imageTextureId
// HDF 光晕效果预处理(在主 shader 之前,需要模糊的光晕纹理)
if (halation > 0f) {
@@ -369,7 +379,7 @@ class LutImageProcessor {
* @param colorRecipeParams 色彩配方参数
* @param sharpeningValue 锐化强度
* @param noiseReductionValue 降噪强度
* @param chromaNoiseReductionValue 减少杂色强度
* @param chromaNoiseReductionValue 兼容旧元数据,bitmap denoiseprofile 使用 noiseReductionValue 统一控制亮度和色度
*/
suspend fun applyLut(
bitmap: Bitmap,
@@ -395,7 +405,6 @@ class LutImageProcessor {
// 后期处理参数(仅在软件处理模式下生效)
val sharpening: Float = sharpeningValue
val noiseReduction: Float = noiseReductionValue
val chromaNoiseReduction: Float = chromaNoiseReductionValue
// 确保上下文激活
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
@@ -411,8 +420,8 @@ class LutImageProcessor {
uploadImageTexture(bitmap)
currentCoroutineContext().ensureActive()
if (noiseReduction > 0 || chromaNoiseReduction > 0) {
renderNLMDenoise(imageTextureId, width, height, noiseReduction, chromaNoiseReduction)
if (noiseReduction > 0) {
renderBitmapDenoiseProfile(imageTextureId, width, height, noiseReduction)
currentCoroutineContext().ensureActive()
}
@@ -421,7 +430,7 @@ class LutImageProcessor {
uploadLutTexture(lutConfig)
}
val inputTexId = if (noiseReduction > 0 || chromaNoiseReduction > 0) nlmPassTexId[1] else imageTextureId
val inputTexId = if (noiseReduction > 0) bitmapDenoiseTexId[1] else imageTextureId
// HDF 光晕效果预处理
if (halation > 0f) {
@@ -511,35 +520,8 @@ class LutImageProcessor {
setupFramebuffer(width, height)
uploadImageTexture(bitmap)
val texelW = 1.0f / width
val texelH = 1.0f / height
val ch = strength * strength * BM3DShaders.SIGMA_STRENGTH_AT_SLIDER_ONE
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
// Pass 0: Chroma Denoise
GLES30.glUseProgram(nlmChromaProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, imageTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmChromaProgram, "uInputTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmChromaProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmChromaProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmChromaProgram, "uH"), ch)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(nlmChromaProgram, "uNoiseModel"),
SRGB_DENOISE_NOISE_S,
SRGB_DENOISE_NOISE_O
)
drawQuad(nlmChromaProgram)
renderBitmapDenoiseProfile(imageTextureId, width, height, strength)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bitmapDenoiseFboId[1])
val pixelSize = width * height * 4
val pixelBuffer = com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(pixelSize.toLong())?.order(ByteOrder.nativeOrder())
@@ -1010,25 +992,21 @@ class LutImageProcessor {
uTexelSizeLoc = GLES30.glGetUniformLocation(shaderProgram, "uTexelSize")
}
private fun initNLMPrograms() {
fun createProgram(vShader: Int, fSource: String): Int {
val fShader = compileShader(GLES30.GL_FRAGMENT_SHADER, fSource)
if (vShader == 0 || fShader == 0) return 0
val program = GLES30.glCreateProgram()
GLES30.glAttachShader(program, vShader)
GLES30.glAttachShader(program, fShader)
GLES30.glLinkProgram(program)
GLES30.glDeleteShader(fShader)
return program
}
val vShader = compileShader(GLES30.GL_VERTEX_SHADER, IMAGE_VERTEX_SHADER)
nlmChromaProgram = createProgram(vShader, BM3DShaders.PASS0_CHROMA_DENOISE)
nlmPassHProgram = createProgram(vShader, BM3DShaders.PASS1_BASIC_ESTIMATE)
nlmPassVProgram = createProgram(vShader, BM3DShaders.PASS2_WIENER)
GLES30.glDeleteShader(vShader)
PLog.d(TAG, "BM3D programs initialized: Pass0=$nlmChromaProgram Pass1=$nlmPassHProgram Pass2=$nlmPassVProgram")
private fun initBitmapDenoiseProfilePrograms() {
bitmapDenoisePreconditionProgram = compileComputeProgram(DenoiseProfileShaders.PRECONDITION_Y0U0V0, "BitmapDenoise_Precondition")
bitmapDenoiseDecomposeProgram = compileComputeProgram(DenoiseProfileShaders.DECOMPOSE, "BitmapDenoise_Decompose")
bitmapDenoiseSynthesizeProgram = compileComputeProgram(DenoiseProfileShaders.SYNTHESIZE, "BitmapDenoise_Synthesize")
bitmapDenoiseReduceFirstProgram = compileComputeProgram(DenoiseProfileShaders.REDUCE_FIRST, "BitmapDenoise_ReduceFirst")
bitmapDenoiseReduceSecondProgram = compileComputeProgram(DenoiseProfileShaders.REDUCE_SECOND, "BitmapDenoise_ReduceSecond")
bitmapDenoiseBacktransformProgram = compileComputeProgram(DenoiseProfileShaders.BACKTRANSFORM_Y0U0V0, "BitmapDenoise_Backtransform")
bitmapDenoisePassthroughProgram = createFragmentProgram(IMAGE_VERTEX_SHADER, TEXTURE_PASSTHROUGH_SHADER, "BitmapDenoise_Passthrough")
PLog.d(
TAG,
"Bitmap denoiseprofile programs initialized: pre=$bitmapDenoisePreconditionProgram " +
"decompose=$bitmapDenoiseDecomposeProgram synth=$bitmapDenoiseSynthesizeProgram " +
"reduce1=$bitmapDenoiseReduceFirstProgram reduce2=$bitmapDenoiseReduceSecondProgram " +
"back=$bitmapDenoiseBacktransformProgram pass=$bitmapDenoisePassthroughProgram"
)
}
private fun initHDFPrograms() {
@@ -1056,75 +1034,24 @@ class LutImageProcessor {
)
}
private fun setupNLMFramebuffers(width: Int, height: Int) {
if (nlmWidth == width && nlmHeight == height && nlmChromaTexId != 0) return
nlmWidth = width
nlmHeight = height
private fun setupBitmapDenoiseFramebuffers(width: Int, height: Int) {
if (bitmapDenoiseWidth == width && bitmapDenoiseHeight == height && bitmapDenoiseTexId[0] != 0) return
bitmapDenoiseWidth = width
bitmapDenoiseHeight = height
// 清理旧资源
if (nlmChromaTexId != 0) GLES30.glDeleteTextures(1, intArrayOf(nlmChromaTexId), 0)
if (nlmChromaFboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(nlmChromaFboId), 0)
for (i in 0..1) {
if (nlmPassTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(nlmPassTexId[i]), 0)
if (nlmPassFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(nlmPassFboId[i]), 0)
if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0)
if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0)
}
// 创建色度降噪 FBO
val ct = IntArray(1)
val cf = IntArray(1)
GLES30.glGenTextures(1, ct, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ct[0])
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
GLES30.GL_RGBA16F,
width,
height,
0,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glGenFramebuffers(1, cf, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, cf[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
ct[0],
0
)
nlmChromaTexId = ct[0]
nlmChromaFboId = cf[0]
var status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(TAG, "NLM Chroma Framebuffer not complete: $status")
}
// 创建 NLM ping-pong FBO
for (i in 0..1) {
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,
width,
height,
0,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
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)
GLES30.glGenFramebuffers(1, f, 0)
@@ -1136,101 +1063,355 @@ class LutImageProcessor {
t[0],
0
)
nlmPassTexId[i] = t[0]
nlmPassFboId[i] = f[0]
bitmapDenoiseTexId[i] = t[0]
bitmapDenoiseFboId[i] = f[0]
status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(TAG, "NLM Pass $i Framebuffer not complete: $status")
PLog.e(TAG, "Bitmap denoiseprofile FBO $i incomplete: $status")
}
}
setupBitmapDenoiseResources(width, height)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
private fun renderNLMDenoise(
private fun renderBitmapDenoiseProfile(
sourceTextureId: Int,
width: Int,
height: Int,
noiseReduction: Float,
chromaNoiseReduction: Float
noiseReduction: Float
) {
setupNLMFramebuffers(width, height)
setupBitmapDenoiseFramebuffers(width, height)
if (nlmChromaProgram == 0 || nlmPassHProgram == 0 || nlmPassVProgram == 0) return
val force = noiseReduction.coerceIn(0f, 1f)
val strength = force
if (strength <= 0f || width * height < 2) {
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
return
}
if (!isBitmapDenoiseProfileReady()) {
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
return
}
val texelW = 1.0f / width
val texelH = 1.0f / height
val h = noiseReduction * noiseReduction * BM3DShaders.SIGMA_STRENGTH_AT_SLIDER_ONE
val ch = chromaNoiseReduction * chromaNoiseReduction * BM3DShaders.SIGMA_STRENGTH_AT_SLIDER_ONE
val params = buildBitmapDenoiseParams(width, height, strength, force)
dispatchBitmapDenoisePrecondition(sourceTextureId, bitmapDenoiseTexId[0], width, height, params)
var buf1 = bitmapDenoiseTexId[0]
var buf2 = bitmapDenoiseTexId[1]
val s = SRGB_DENOISE_NOISE_S
val o = SRGB_DENOISE_NOISE_O
for (scale in 0 until params.maxScale) {
dispatchBitmapDenoiseDecompose(buf1, buf2, bitmapDenoiseDetailTexIds[scale], width, height, scale)
val tmp = buf2
buf2 = buf1
buf1 = tmp
}
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
for (scale in params.maxScale - 1 downTo 0) {
val threshold = computeBitmapDenoiseThreshold(bitmapDenoiseDetailTexIds[scale], width, height, scale, params)
dispatchBitmapDenoiseSynthesize(buf1, bitmapDenoiseDetailTexIds[scale], buf2, width, height, threshold)
val tmp = buf2
buf2 = buf1
buf1 = tmp
}
// Pass 0: Chroma Denoise
GLES30.glUseProgram(nlmChromaProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, nlmChromaFboId)
val finalInput = if (buf1 == bitmapDenoiseTexId[1]) {
renderTexturePassthrough(buf1, bitmapDenoiseFboId[0], width, height)
bitmapDenoiseTexId[0]
} else {
buf1
}
dispatchBitmapDenoiseBacktransform(finalInput, bitmapDenoiseTexId[1], width, height, params)
checkGlError("renderBitmapDenoiseProfile")
}
private fun renderTexturePassthrough(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int) {
GLES30.glUseProgram(bitmapDenoisePassthroughProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmChromaProgram, "uInputTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmChromaProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapDenoisePassthroughProgram, "uInputTexture"), 0)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmChromaProgram, "uMVPMatrix"),
GLES30.glGetUniformLocation(bitmapDenoisePassthroughProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmChromaProgram, "uH"), ch)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmChromaProgram, "uNoiseModel"), s, o)
drawQuad(nlmChromaProgram)
drawQuad(bitmapDenoisePassthroughProgram)
}
// NLM Pass H
GLES30.glUseProgram(nlmPassHProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, nlmPassFboId[0])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nlmChromaTexId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassHProgram, "uInputTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmPassHProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
private data class BitmapDenoiseParams(
val strength: Float,
val maxScale: Int,
val lumaForce: Float,
val chromaForce: Float,
val p: FloatArray,
val wb: FloatArray,
val aa: FloatArray,
val bb: FloatArray,
val toY0U0V0: FloatArray,
val toRgb: FloatArray,
val bias: Float,
val scale: Float
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassHProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassHProgram)
// NLM Pass V
GLES30.glUseProgram(nlmPassVProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, nlmPassFboId[1])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nlmChromaTexId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, nlmPassTexId[0])
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBasicTexture"), 1)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmPassVProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
private fun isBitmapDenoiseProfileReady(): Boolean {
return bitmapDenoisePreconditionProgram != 0 &&
bitmapDenoiseDecomposeProgram != 0 &&
bitmapDenoiseSynthesizeProgram != 0 &&
bitmapDenoiseReduceFirstProgram != 0 &&
bitmapDenoiseReduceSecondProgram != 0 &&
bitmapDenoiseBacktransformProgram != 0 &&
bitmapDenoisePassthroughProgram != 0
}
private fun setupBitmapDenoiseResources(width: Int, height: Int) {
for (i in bitmapDenoiseDetailTexIds.indices) {
if (bitmapDenoiseDetailTexIds[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseDetailTexIds[i]), 0)
val t = IntArray(1)
GLES30.glGenTextures(1, t, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0])
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_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)
bitmapDenoiseDetailTexIds[i] = t[0]
}
val groupsX = roundUp(width, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X
val groupsY = roundUp(height, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y
bitmapDenoiseReduceBufSize = groupsX * groupsY
bitmapDenoiseReduceSize = kotlin.math.min(
DenoiseProfileShaders.REDUCE_SIZE,
roundUp(bitmapDenoiseReduceBufSize, DenoiseProfileShaders.REDUCE_SECOND_LOCAL_X) / DenoiseProfileShaders.REDUCE_SECOND_LOCAL_X
).coerceAtLeast(1)
if (bitmapDenoiseReduceMBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseReduceMBufferId), 0)
if (bitmapDenoiseReduceRBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseReduceRBufferId), 0)
val buffers = IntArray(2)
GLES31.glGenBuffers(2, buffers, 0)
bitmapDenoiseReduceMBufferId = buffers[0]
bitmapDenoiseReduceRBufferId = buffers[1]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseReduceMBufferId)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseReduceBufSize * 4 * 4, null, GLES31.GL_DYNAMIC_DRAW)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseReduceRBufferId)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseReduceSize * 4 * 4, null, GLES31.GL_DYNAMIC_READ)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
private fun buildBitmapDenoiseParams(
width: Int,
height: Int,
strengthValue: Float,
force: Float
): BitmapDenoiseParams {
val a = BITMAP_DENOISE_A
val b = BITMAP_DENOISE_B
val scale = 1.0f
val shadows = max(0.1f - 0.1f * ln(a), 0.7f).coerceAtMost(1.8f)
val bias = -max(5f + 0.5f * ln(a), 0.0f)
val compensateP = 0.05f / 0.05f.pow(shadows)
val compensateStrength = 2.5f
val strength = strengthValue.coerceAtLeast(1e-6f)
val wbBase = floatArrayOf(1f, 1f, 1f, 0f)
val (toY, toRgbBase) = computeBitmapY0U0V0Matrices(wbBase)
val toYScaled = FloatArray(9)
val toRgbScaled = FloatArray(9)
for (i in 0 until 9) {
toYScaled[i] = toY[i] / (strength * compensateStrength * scale)
toRgbScaled[i] = toRgbBase[i] * strength * compensateStrength * scale
}
return BitmapDenoiseParams(
strength = strength,
maxScale = computeBitmapDenoiseMaxScale(width, height),
lumaForce = force,
chromaForce = force,
p = floatArrayOf(shadows, shadows, shadows, 1.0f),
wb = floatArrayOf(
strength * compensateStrength * scale,
strength * compensateStrength * scale,
strength * compensateStrength * scale,
0.0f
),
aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1.0f),
bb = floatArrayOf(b, b, b, 1.0f),
toY0U0V0 = toYScaled,
toRgb = toRgbScaled,
bias = bias,
scale = scale
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassVProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassVProgram)
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("renderNLMDenoise")
private fun computeBitmapDenoiseMaxScale(width: Int, height: Int): Int {
val maxMaxScale = DenoiseProfileShaders.BANDS
val supp0 = kotlin.math.min((2 * (2 shl (maxMaxScale - 1)) + 1).toFloat(), max(width, height).toFloat() * 0.2f)
val i0 = ln((supp0 - 1.0f) * 0.5f) / ln(2.0f)
var maxScale = 0
while (maxScale < maxMaxScale) {
val supp = (2 * (2 shl maxScale) + 1).toFloat()
val iIn = ln((supp - 1.0f) * 0.5f) / ln(2.0f) - 1.0f
if (1.0f - (iIn + 0.5f) / i0 < 0.0f) break
maxScale++
}
return maxScale.coerceIn(1, DenoiseProfileShaders.BANDS)
}
private fun computeBitmapY0U0V0Matrices(wb: FloatArray): Pair<FloatArray, FloatArray> {
val toY = floatArrayOf(
1f / 3f, 1f / 3f, 1f / 3f,
0.5f, 0.0f, -0.5f,
0.25f, -0.5f, 0.25f
)
var sumInvWb = 1.0f / wb[0] + 1.0f / wb[1] + 1.0f / wb[2]
sumInvWb *= sqrt(3.0f)
toY[0] = sumInvWb / wb[0]
toY[1] = sumInvWb / wb[1]
toY[2] = sumInvWb / wb[2]
val stddevU0 = sqrt(0.25f * wb[0] * wb[0] + 0.25f * wb[2] * wb[2]).coerceAtLeast(1e-6f)
val stddevV0 = sqrt(0.0625f * wb[0] * wb[0] + 0.25f * wb[1] * wb[1] + 0.0625f * wb[2] * wb[2]).coerceAtLeast(1e-6f)
for (i in 3..5) toY[i] /= stddevU0
for (i in 6..8) toY[i] /= stddevV0
return toY to (invertBitmapMatrix3x3(toY) ?: floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f))
}
private fun invertBitmapMatrix3x3(m: FloatArray): FloatArray? {
val a = m[4] * m[8] - m[5] * m[7]
val b = -m[3] * m[8] + m[5] * m[6]
val c = m[3] * m[7] - m[4] * m[6]
val d = -m[1] * m[8] + m[2] * m[7]
val e = m[0] * m[8] - m[2] * m[6]
val f = -m[0] * m[7] + m[1] * m[6]
val g = m[1] * m[5] - m[2] * m[4]
val h = -m[0] * m[5] + m[2] * m[3]
val i = m[0] * m[4] - m[1] * m[3]
val det = m[0] * a + m[1] * b + m[2] * c
if (det == 0f) return null
val inv = 1.0f / det
return floatArrayOf(inv * a, inv * d, inv * g, inv * b, inv * e, inv * h, inv * c, inv * f, inv * i)
}
private fun matrix3ToGl(m: FloatArray): FloatArray {
return floatArrayOf(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
}
private fun dispatchBitmapDenoisePrecondition(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
GLES31.glUseProgram(bitmapDenoisePreconditionProgram)
bindComputeSampler(bitmapDenoisePreconditionProgram, "uInput", 0, input)
GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
setBitmapDenoiseCommonUniforms(bitmapDenoisePreconditionProgram, width, height, params)
GLES31.glUniformMatrix3fv(GLES31.glGetUniformLocation(bitmapDenoisePreconditionProgram, "uToY0U0V0"), 1, false, matrix3ToGl(params.toY0U0V0), 0)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise precondition")
}
private fun dispatchBitmapDenoiseDecompose(input: Int, coarse: Int, detail: Int, width: Int, height: Int, scale: Int) {
GLES31.glUseProgram(bitmapDenoiseDecomposeProgram)
bindComputeSampler(bitmapDenoiseDecomposeProgram, "uInput", 0, input)
GLES31.glBindImageTexture(1, coarse, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glBindImageTexture(2, detail, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseDecomposeProgram, "uImageSize"), width, height)
GLES31.glUniform1i(GLES31.glGetUniformLocation(bitmapDenoiseDecomposeProgram, "uScale"), scale)
val varf = sqrt(2.0f + 2.0f * 4.0f * 4.0f + 6.0f * 6.0f) / 16.0f
val sigmaBand = varf.pow(scale)
GLES31.glUniform1f(GLES31.glGetUniformLocation(bitmapDenoiseDecomposeProgram, "uInvSigma2"), 1.0f / (sigmaBand * sigmaBand))
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise decompose $scale")
}
private fun dispatchBitmapDenoiseSynthesize(coarse: Int, detail: Int, output: Int, width: Int, height: Int, threshold: FloatArray) {
GLES31.glUseProgram(bitmapDenoiseSynthesizeProgram)
bindComputeSampler(bitmapDenoiseSynthesizeProgram, "uCoarse", 0, coarse)
bindComputeSampler(bitmapDenoiseSynthesizeProgram, "uDetail", 1, detail)
GLES31.glBindImageTexture(2, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseSynthesizeProgram, "uImageSize"), width, height)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(bitmapDenoiseSynthesizeProgram, "uThreshold"), 1, threshold, 0)
GLES31.glUniform4f(GLES31.glGetUniformLocation(bitmapDenoiseSynthesizeProgram, "uBoost"), 1f, 1f, 1f, 1f)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise synthesize")
}
private fun dispatchBitmapDenoiseBacktransform(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
GLES31.glUseProgram(bitmapDenoiseBacktransformProgram)
bindComputeSampler(bitmapDenoiseBacktransformProgram, "uInput", 0, input)
GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
setBitmapDenoiseCommonUniforms(bitmapDenoiseBacktransformProgram, width, height, params)
GLES31.glUniform1f(GLES31.glGetUniformLocation(bitmapDenoiseBacktransformProgram, "uBias"), params.bias - 0.5f * ln(params.scale))
GLES31.glUniformMatrix3fv(GLES31.glGetUniformLocation(bitmapDenoiseBacktransformProgram, "uToRgb"), 1, false, matrix3ToGl(params.toRgb), 0)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise backtransform")
}
private fun setBitmapDenoiseCommonUniforms(program: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uA"), 1, params.aa, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uP"), 1, params.p, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uB"), 1, params.bb, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uWb"), 1, params.wb, 0)
}
private fun computeBitmapDenoiseThreshold(textureId: Int, width: Int, height: Int, scale: Int, params: BitmapDenoiseParams): FloatArray {
val groupsX = roundUp(width, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X
val groupsY = roundUp(height, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y
GLES31.glUseProgram(bitmapDenoiseReduceFirstProgram)
bindComputeSampler(bitmapDenoiseReduceFirstProgram, "uInput", 0, textureId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseReduceMBufferId)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseReduceFirstProgram, "uImageSize"), width, height)
GLES31.glDispatchCompute(groupsX, groupsY, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
GLES31.glUseProgram(bitmapDenoiseReduceSecondProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseReduceMBufferId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bitmapDenoiseReduceRBufferId)
GLES31.glUniform1i(GLES31.glGetUniformLocation(bitmapDenoiseReduceSecondProgram, "uLength"), bitmapDenoiseReduceBufSize)
GLES31.glDispatchCompute(bitmapDenoiseReduceSize, 1, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
val sumY2 = readBitmapDenoiseReduceResult(bitmapDenoiseReduceSize)
val npixels = (width * height).toFloat()
val varf = sqrt(2.0f + 2.0f * 4.0f * 4.0f + 6.0f * 6.0f) / 16.0f
val sb2 = varf.pow(scale) * varf.pow(scale)
val std0 = sqrt(max(1e-6f, sumY2[0] / (npixels - 1.0f) - sb2))
val std1 = sqrt(max(1e-6f, sumY2[1] / (npixels - 1.0f) - sb2))
val std2 = sqrt(max(1e-6f, sumY2[2] / (npixels - 1.0f) - sb2))
val adjY = 8.0f * params.lumaForce * params.lumaForce * 4.0f
val adjC = 8.0f * params.chromaForce * params.chromaForce * 4.0f
return floatArrayOf(adjY * sb2 / std0, adjC * sb2 / std1, adjC * sb2 / std2, 0.0f)
}
private fun readBitmapDenoiseReduceResult(reduceSize: Int): FloatArray {
val out = FloatArray(4)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseReduceRBufferId)
val mapped = GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, reduceSize * 4 * 4, GLES31.GL_MAP_READ_BIT) as? ByteBuffer
if (mapped != null) {
mapped.order(ByteOrder.nativeOrder())
val floats = mapped.asFloatBuffer()
for (i in 0 until reduceSize) {
out[0] += floats.get(i * 4)
out[1] += floats.get(i * 4 + 1)
out[2] += floats.get(i * 4 + 2)
}
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
}
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return out
}
private fun bindComputeSampler(program: Int, name: String, unit: Int, textureId: Int) {
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureId)
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit)
}
private fun dispatchBitmapDenoiseImage(width: Int, height: Int, tag: String) {
GLES31.glDispatchCompute((width + 15) / 16, (height + 15) / 16, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT
)
checkGlError(tag)
}
private fun roundUp(value: Int, multiple: Int): Int {
return ((value + multiple - 1) / multiple) * multiple
}
/**
@@ -1473,6 +1654,54 @@ class LutImageProcessor {
return shader
}
private fun createFragmentProgram(vSource: String, fSource: String, name: String): Int {
val vShader = compileShader(GLES30.GL_VERTEX_SHADER, vSource)
val fShader = compileShader(GLES30.GL_FRAGMENT_SHADER, fSource)
if (vShader == 0 || fShader == 0) return 0
val program = GLES30.glCreateProgram()
GLES30.glAttachShader(program, vShader)
GLES30.glAttachShader(program, fShader)
GLES30.glLinkProgram(program)
val linked = IntArray(1)
GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linked, 0)
if (linked[0] == 0) {
PLog.e(TAG, "Program $name linking failed: ${GLES30.glGetProgramInfoLog(program)}")
GLES30.glDeleteProgram(program)
GLES30.glDeleteShader(vShader)
GLES30.glDeleteShader(fShader)
return 0
}
GLES30.glDeleteShader(vShader)
GLES30.glDeleteShader(fShader)
return program
}
private fun compileComputeProgram(source: String, name: String): Int {
val shader = GLES31.glCreateShader(GLES31.GL_COMPUTE_SHADER)
GLES31.glShaderSource(shader, source)
GLES31.glCompileShader(shader)
val compiled = IntArray(1)
GLES31.glGetShaderiv(shader, GLES31.GL_COMPILE_STATUS, compiled, 0)
if (compiled[0] == 0) {
PLog.e(TAG, "Compute shader $name compilation failed: ${GLES31.glGetShaderInfoLog(shader)}")
GLES31.glDeleteShader(shader)
return 0
}
val program = GLES31.glCreateProgram()
GLES31.glAttachShader(program, shader)
GLES31.glLinkProgram(program)
val linked = IntArray(1)
GLES31.glGetProgramiv(program, GLES31.GL_LINK_STATUS, linked, 0)
if (linked[0] == 0) {
PLog.e(TAG, "Compute program $name linking failed: ${GLES31.glGetProgramInfoLog(program)}")
GLES31.glDeleteProgram(program)
GLES31.glDeleteShader(shader)
return 0
}
GLES31.glDeleteShader(shader)
return program
}
private fun initBuffers() {
// 顶点缓冲
vertexBuffer = ByteBuffer.allocateDirect(Shaders.FULL_QUAD_VERTICES.size * 4)
@@ -1530,25 +1759,23 @@ class LutImageProcessor {
pboId = 0
}
if (nlmChromaProgram != 0) {
GLES30.glDeleteProgram(nlmChromaProgram)
}
if (nlmPassHProgram != 0) {
GLES30.glDeleteProgram(nlmPassHProgram)
}
if (nlmPassVProgram != 0) {
GLES30.glDeleteProgram(nlmPassVProgram)
}
if (nlmChromaTexId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(nlmChromaTexId), 0)
}
if (nlmChromaFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(nlmChromaFboId), 0)
}
if (bitmapDenoisePreconditionProgram != 0) GLES31.glDeleteProgram(bitmapDenoisePreconditionProgram)
if (bitmapDenoiseDecomposeProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseDecomposeProgram)
if (bitmapDenoiseSynthesizeProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseSynthesizeProgram)
if (bitmapDenoiseReduceFirstProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseReduceFirstProgram)
if (bitmapDenoiseReduceSecondProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseReduceSecondProgram)
if (bitmapDenoiseBacktransformProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseBacktransformProgram)
if (bitmapDenoisePassthroughProgram != 0) GLES30.glDeleteProgram(bitmapDenoisePassthroughProgram)
for (i in 0..1) {
if (nlmPassTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(nlmPassTexId[i]), 0)
if (nlmPassFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(nlmPassFboId[i]), 0)
if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0)
if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0)
}
for (i in bitmapDenoiseDetailTexIds.indices) {
if (bitmapDenoiseDetailTexIds[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseDetailTexIds[i]), 0)
bitmapDenoiseDetailTexIds[i] = 0
}
if (bitmapDenoiseReduceMBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseReduceMBufferId), 0)
if (bitmapDenoiseReduceRBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseReduceRBufferId), 0)
// 释放 HDF 资源
if (hdfExtractBlurHProgram != 0) GLES30.glDeleteProgram(hdfExtractBlurHProgram)
@@ -1576,8 +1803,8 @@ class LutImageProcessor {
companion object {
private const val TAG = "LutImageProcessor"
private const val SRGB_DENOISE_NOISE_S = 0.015f
private const val SRGB_DENOISE_NOISE_O = 0.001f
private const val BITMAP_DENOISE_A = 0.015f
private const val BITMAP_DENOISE_B = 0.001f
private const val LCH_COLOR_BAND_COUNT = 9
// 2D 图片版本的顶点着色器
@@ -1597,6 +1824,20 @@ class LutImageProcessor {
}
""".trimIndent()
private val TEXTURE_PASSTHROUGH_SHADER = """
#version 300 es
precision mediump float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
void main() {
fragColor = texture(uInputTexture, vTexCoord);
}
""".trimIndent()
private val SHADER_BODY = """
in vec2 vTexCoord;
out vec4 fragColor;
@@ -1,430 +0,0 @@
package com.hinnka.mycamera.raw
/**
* Mobile-optimised BM3D (Block-Matching 3D Filtering) denoising shaders.
*
* Replaces [NLMShaders] with a two-step BM3D approximation that trades slightly
* higher ALU/texture cost for significantly better detail retention and noise
* reduction, particularly in high-ISO shots.
*
* Pipeline (same FBO bindings as NLM):
* PASS0_CHROMA_DENOISE → gfChromaFboId
* PASS1_BASIC_ESTIMATE → gfFboId[0] (RGB = basic estimate, A = match fraction)
* PASS2_WIENER → gfFboId[1] (final Wiener-filtered result)
*
* Uniform interface (caller side):
* Pass 0 uInputTexture=source, uH=chromaH, uNoiseModel=(S,O)
* Pass 1 uInputTexture=chromaTex, uH=h, uNoiseModel=(S,O)
* Pass 2 uInputTexture=chromaTex (noisy),
* uBasicTexture=gfTexId[0] (basic), uH=h, uNoiseModel=(S,O)
*
* Performance budget (5×5 search, 3×3 luma patch):
* Pass 1 ≈ 234 tex reads/px Pass 2 ≈ 260 tex reads/px
* Total ≈ 520 reads/px (vs ≈ 122 for NLM — 4× cost, substantially higher quality)
*/
object BM3DShaders {
const val SIGMA_STRENGTH_AT_SLIDER_ONE = 5.0f
// ─── Pass 0 : Chroma Denoise ──────────────────────────────────────────────
/**
* Cross-bilateral filter on the chroma channels guided by luma.
* Runs before luma denoising to supply a cleaner guide image.
* Wide chroma tolerance + tight luma tolerance prevents halo/bleed.
*/
val PASS0_CHROMA_DENOISE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
vec3 rgb2ycbcr(vec3 rgb) {
float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
return vec3(y,
dot(rgb, vec3(-0.169, -0.331, 0.5 )) + 0.5,
dot(rgb, vec3( 0.5, -0.419, -0.081 )) + 0.5);
}
vec3 ycbcr2rgb(vec3 yuv) {
float cb = yuv.y - 0.5, cr = yuv.z - 0.5;
return vec3(yuv.x + 1.402 * cr,
yuv.x - 0.3441 * cb - 0.7141 * cr,
yuv.x + 1.772 * cb);
}
float noiseSigmaForLuma(float luma) {
return sqrt(max(uNoiseModel.x * max(luma, 0.0) + uNoiseModel.y, 1e-10));
}
void main() {
vec3 oriRgb = texture(uInputTexture, vTexCoord).rgb;
if (uH <= 0.00001) { fragColor = vec4(oriRgb, 1.0); return; }
vec3 yuv = rgb2ycbcr(oriRgb);
vec2 sumUV = vec2(0.0);
float sumW = 0.0;
// Chroma noise is low-frequency → large spatial step scale
float stepScale = 6.5;
float localH = uH * noiseSigmaForLuma(yuv.x);
float invChromaH2 = 1.0 / max((localH * 1.5) * (localH * 1.5), 1e-6);
float invLumaH2 = 1.0 / max((localH * 0.5) * (localH * 0.5), 1e-6);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
vec2 ofs = vec2(float(x), float(y)) * uTexelSize * stepScale;
vec3 sYuv = rgb2ycbcr(texture(uInputTexture, vTexCoord + ofs).rgb);
float wS = exp(-float(x*x + y*y) * 0.25);
float dL = sYuv.x - yuv.x;
vec2 dC = sYuv.yz - yuv.yz;
float wR = exp(-(dL * dL) * invLumaH2 - dot(dC, dC) * invChromaH2);
float w = wS * wR;
if (x == 0 && y == 0) w = max(w, 0.1);
sumUV += sYuv.yz * w;
sumW += w;
}
}
yuv.yz = sumUV / sumW;
fragColor = vec4(ycbcr2rgb(yuv), 1.0);
}
""".trimIndent()
// ─── Pass 1 : BM3D Basic Estimate ────────────────────────────────────────
/**
* Hard-threshold block matching in a 5×5 search window with 3×3 luma patches.
*
* Matches the BM3D Step-1 philosophy: a candidate block is either in the group
* (ssd ≤ τ) or out (weight = 0), producing a collaborative average that acts as
* a spatial hard-threshold in the transform domain.
*
* Output alpha = match fraction (0–1), forwarded to Pass 2 for noise estimation.
*/
val PASS1_BASIC_ESTIMATE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
// 5×5 search window, 3×3 luma patch
#define SEARCH_RADIUS 2
#define PATCH_RADIUS 1
const vec3 LW = vec3(0.2126, 0.7152, 0.0722);
vec3 rgb2ycbcr(vec3 rgb) {
return vec3(dot(rgb, LW),
dot(rgb, vec3(-0.169, -0.331, 0.5 )) + 0.5,
dot(rgb, vec3( 0.5, -0.419, -0.081 )) + 0.5);
}
vec3 ycbcr2rgb(vec3 yuv) {
float cb = yuv.y - 0.5, cr = yuv.z - 0.5;
return vec3(yuv.x + 1.402 * cr,
yuv.x - 0.3441 * cb - 0.7141 * cr,
yuv.x + 1.772 * cb);
}
float softMatchWeight(float ssd, float threshold) {
float t = max(threshold, 1e-6);
float soft = exp(-ssd / t);
float gate = 1.0 - smoothstep(t * 0.35, t * 1.55, ssd);
return soft * gate;
}
float noiseSigmaForLuma(float luma) {
return sqrt(max(uNoiseModel.x * max(luma, 0.0) + uNoiseModel.y, 1e-10));
}
void main() {
vec3 centerVal = texture(uInputTexture, vTexCoord).rgb;
if (uH <= 0.00001) { fragColor = vec4(centerVal, 1.0); return; }
vec2 T = uTexelSize;
vec3 centerYuv = rgb2ycbcr(centerVal);
// Pre-fetch the 3×3 center-patch luma values (unrolled to avoid
// dynamic-array indexing, which can be slow on some mobile GPUs)
float c00 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0,-1.0)*T).rgb, LW);
float c01 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0, 0.0)*T).rgb, LW);
float c02 = dot(texture(uInputTexture, vTexCoord + vec2(-1.0, 1.0)*T).rgb, LW);
float c10 = dot(texture(uInputTexture, vTexCoord + vec2( 0.0,-1.0)*T).rgb, LW);
float c11 = dot(centerVal, LW);
float c12 = dot(texture(uInputTexture, vTexCoord + vec2( 0.0, 1.0)*T).rgb, LW);
float c20 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0,-1.0)*T).rgb, LW);
float c21 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0, 0.0)*T).rgb, LW);
float c22 = dot(texture(uInputTexture, vTexCoord + vec2( 1.0, 1.0)*T).rgb, LW);
float localH = uH * noiseSigmaForLuma(c11);
// BM3D hard threshold: τ = factor × σ² × patch_size
// factor 2.7 is the standard BM3D constant, tuned here for 3×3 patches
float threshold = localH * localH * 9.0 * 2.7;
float sumLuma = 0.0;
vec2 sumChroma = vec2(0.0);
float sumWeight = 0.0;
for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dy = -SEARCH_RADIUS; dy <= SEARCH_RADIUS; dy++) {
vec2 nUV = vTexCoord + vec2(float(dx), float(dy)) * T;
// Cache the neighbor center pixel for reuse in SSD + accumulation
vec3 nC = texture(uInputTexture, nUV).rgb;
float nL = dot(nC, LW);
// 3×3 luma SSD – center pixel reuses nL from the cached fetch
float ssd = 0.0;
float d;
d = c00 - dot(texture(uInputTexture, nUV + vec2(-1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c01 - dot(texture(uInputTexture, nUV + vec2(-1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c02 - dot(texture(uInputTexture, nUV + vec2(-1.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c10 - dot(texture(uInputTexture, nUV + vec2( 0.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c11 - nL; ssd += d*d;
d = c12 - dot(texture(uInputTexture, nUV + vec2( 0.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c20 - dot(texture(uInputTexture, nUV + vec2( 1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c21 - dot(texture(uInputTexture, nUV + vec2( 1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c22 - dot(texture(uInputTexture, nUV + vec2( 1.0, 1.0)*T).rgb, LW); ssd += d*d;
float w = softMatchWeight(ssd, threshold);
if (dx == 0 && dy == 0) w = max(w, 1.0);
vec3 nYuv = rgb2ycbcr(nC);
sumLuma += nYuv.x * w;
sumChroma += nYuv.yz * w;
sumWeight += w;
}
}
// Store normalised match count in alpha → Pass 2 uses it to refine noise estimate
float maxCandidates = float((2*SEARCH_RADIUS+1) * (2*SEARCH_RADIUS+1)); // 25
float invWeight = 1.0 / max(sumWeight, 1.0);
float basicLuma = sumLuma * invWeight;
// Fallback for low-match cases (edges/isolated noise) to break up clusters.
// Uses a tiny 3x3 guided luma average since we already have the patch data.
float lwSum = 1.0; float lvalSum = c11;
float invH2 = 1.0 / max(localH * localH * 2.0, 1e-5);
float w;
w = exp(-(c00-c11)*(c00-c11)*invH2); lwSum += w; lvalSum += c00*w;
w = exp(-(c01-c11)*(c01-c11)*invH2); lwSum += w; lvalSum += c01*w;
w = exp(-(c02-c11)*(c02-c11)*invH2); lwSum += w; lvalSum += c02*w;
w = exp(-(c10-c11)*(c10-c11)*invH2); lwSum += w; lvalSum += c10*w;
w = exp(-(c12-c11)*(c12-c11)*invH2); lwSum += w; lvalSum += c12*w;
w = exp(-(c20-c11)*(c20-c11)*invH2); lwSum += w; lvalSum += c20*w;
w = exp(-(c21-c11)*(c21-c11)*invH2); lwSum += w; lvalSum += c21*w;
w = exp(-(c22-c11)*(c22-c11)*invH2); lwSum += w; lvalSum += c22*w;
float localGuided = lvalSum / lwSum;
float edgeFallback = clamp(3.0 - sumWeight, 0.0, 1.0);
basicLuma = mix(basicLuma, localGuided, edgeFallback * 0.35);
vec3 outYuv = vec3(basicLuma, mix(centerYuv.yz, sumChroma * invWeight, 0.35));
fragColor = vec4(clamp(ycbcr2rgb(outYuv), 0.0, 1.0), clamp(sumWeight / maxCandidates, 0.0, 1.0));
}
""".trimIndent()
// ─── Pass 2 : BM3D Wiener Refinement ─────────────────────────────────────
/**
* Uses the basic estimate (Pass 1) as a noise-reduced guide for block matching.
* For each matched group, estimates the local signal variance from the basic
* estimate and computes the Wiener-optimal blend weight:
*
* w = σ_s² / (σ_s² + σ_n²/N)
*
* where σ_s² = signal variance in the group, σ_n² = noise variance (uH²),
* N = number of matched patches.
*
* The final pixel is mixed between the basic estimate (near-noise-free prior)
* and the average of matched noisy patches (structure-preserving signal estimate).
*
* Uniforms:
* uInputTexture – original (chroma-denoised) noisy image
* uBasicTexture – Pass-1 output (RGB = basic estimate, A = match fraction)
*/
val PASS2_WIENER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture; // chroma-denoised noisy image
uniform sampler2D uBasicTexture; // Pass-1 basic estimate (A = match fraction)
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
uniform vec2 uNoiseModel;
// Same search / patch geometry as Pass 1
#define SEARCH_RADIUS 2
#define PATCH_RADIUS 1
const vec3 LW = vec3(0.2126, 0.7152, 0.0722);
vec3 rgb2ycbcr(vec3 rgb) {
return vec3(dot(rgb, LW),
dot(rgb, vec3(-0.169, -0.331, 0.5 )) + 0.5,
dot(rgb, vec3( 0.5, -0.419, -0.081 )) + 0.5);
}
vec3 ycbcr2rgb(vec3 yuv) {
float cb = yuv.y - 0.5, cr = yuv.z - 0.5;
return vec3(yuv.x + 1.402 * cr,
yuv.x - 0.3441 * cb - 0.7141 * cr,
yuv.x + 1.772 * cb);
}
float softMatchWeight(float ssd, float threshold) {
float t = max(threshold, 1e-6);
float soft = exp(-ssd / t);
float gate = 1.0 - smoothstep(t * 0.35, t * 1.55, ssd);
return soft * gate;
}
float noiseSigmaForLuma(float luma) {
return sqrt(max(uNoiseModel.x * max(luma, 0.0) + uNoiseModel.y, 1e-10));
}
float wideGuidedLumaBase(vec2 uv, vec2 texelSize, float centerGuideLuma, float sigma_n2) {
float sumY = 0.0;
float sumW = 0.0;
float stepScale = 3.5;
float guideSigma2 = max(sigma_n2 * 48.0, 8e-5);
for (int dx = -2; dx <= 2; dx++) {
for (int dy = -2; dy <= 2; dy++) {
vec2 ofs = vec2(float(dx), float(dy)) * texelSize * stepScale;
vec2 suv = uv + ofs;
float guideY = dot(texture(uBasicTexture, suv).rgb, LW);
float noisyY = dot(texture(uInputTexture, suv).rgb, LW);
float dGuide = guideY - centerGuideLuma;
float wSpatial = exp(-float(dx * dx + dy * dy) * 0.18);
float wRange = exp(-(dGuide * dGuide) / guideSigma2);
float w = wSpatial * wRange;
if (dx == 0 && dy == 0) w = max(w, 0.25);
sumY += noisyY * w;
sumW += w;
}
}
return sumY / max(sumW, 1e-5);
}
void main() {
vec3 noisyCenter = texture(uInputTexture, vTexCoord).rgb;
vec4 basicSample = texture(uBasicTexture, vTexCoord);
vec3 basicCenter = basicSample.rgb;
// alpha from Pass 1: fraction of the 25 candidates that were merged
// → approximates N_basic, the effective patch count in the basic estimate
float N_basic = basicSample.a * 25.0 + 1.0;
if (uH <= 0.00001) { fragColor = vec4(noisyCenter, 1.0); return; }
vec2 T = uTexelSize;
// Pre-fetch 3×3 center-patch luma from BASIC estimate (less noisy guide)
float c00 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0,-1.0)*T).rgb, LW);
float c01 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0, 0.0)*T).rgb, LW);
float c02 = dot(texture(uBasicTexture, vTexCoord + vec2(-1.0, 1.0)*T).rgb, LW);
float c10 = dot(texture(uBasicTexture, vTexCoord + vec2( 0.0,-1.0)*T).rgb, LW);
float c11 = dot(basicCenter, LW);
float c12 = dot(texture(uBasicTexture, vTexCoord + vec2( 0.0, 1.0)*T).rgb, LW);
float c20 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0,-1.0)*T).rgb, LW);
float c21 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0, 0.0)*T).rgb, LW);
float c22 = dot(texture(uBasicTexture, vTexCoord + vec2( 1.0, 1.0)*T).rgb, LW);
// Sensor noise model in this pass' linear-light domain:
// variance = S * luma + O. uH is a dimensionless strength multiplier.
float localH = uH * noiseSigmaForLuma(c11);
float sigma_n2 = localH * localH;
float threshold = sigma_n2 * 9.0 * 2.7; // same τ as Pass 1, adapted by luma
vec3 basicYuv = rgb2ycbcr(basicCenter);
float sumNoisyY = 0.0;
vec2 sumNoisyC = vec2(0.0);
float sumWeight = 0.0;
float sumL = 0.0; // luma sum for variance estimation
float sumL2 = 0.0; // luma² sum for variance estimation
for (int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
for (int dy = -SEARCH_RADIUS; dy <= SEARCH_RADIUS; dy++) {
vec2 nUV = vTexCoord + vec2(float(dx), float(dy)) * T;
// Cache basic estimate center for SSD + variance stats
vec3 nBasic = texture(uBasicTexture, nUV).rgb;
float nL = dot(nBasic, LW);
// Patch SSD over BASIC estimate – cleaner matching than noisy image
float ssd = 0.0;
float d;
d = c00 - dot(texture(uBasicTexture, nUV + vec2(-1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c01 - dot(texture(uBasicTexture, nUV + vec2(-1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c02 - dot(texture(uBasicTexture, nUV + vec2(-1.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c10 - dot(texture(uBasicTexture, nUV + vec2( 0.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c11 - nL; ssd += d*d;
d = c12 - dot(texture(uBasicTexture, nUV + vec2( 0.0, 1.0)*T).rgb, LW); ssd += d*d;
d = c20 - dot(texture(uBasicTexture, nUV + vec2( 1.0,-1.0)*T).rgb, LW); ssd += d*d;
d = c21 - dot(texture(uBasicTexture, nUV + vec2( 1.0, 0.0)*T).rgb, LW); ssd += d*d;
d = c22 - dot(texture(uBasicTexture, nUV + vec2( 1.0, 1.0)*T).rgb, LW); ssd += d*d;
float w = softMatchWeight(ssd, threshold);
if (dx == 0 && dy == 0) w = max(w, 1.0);
// Accumulate signal-variance statistics from basic estimate
sumL += nL * w;
sumL2 += nL * nL * w;
// Filter the NOISY image with weights derived from basic-estimate matching
vec3 nNoisyYuv = rgb2ycbcr(texture(uInputTexture, nUV).rgb);
sumNoisyY += nNoisyYuv.x * w;
sumNoisyC += nNoisyYuv.yz * w;
sumWeight += w;
}
}
// ── Wiener weight computation ────────────────────────────────────
// Estimate signal variance from the matched group in the basic estimate.
// var_total(basic group) ≈ var_signal + σ_n²/N_basic (residual noise)
float N = max(sumWeight, 1.0);
float meanL = sumL / N;
float varTotal = sumL2 / N - meanL * meanL;
// Subtract residual noise in basic estimate (σ_n² / N_basic)
float varSignal = max(0.0, varTotal - sigma_n2 / N_basic);
// Wiener weight: w = σ_s² / (σ_s² + σ_n²/N)
float noiseOfAvg = sigma_n2 / N;
float wienerW = varSignal / max(varSignal + noiseOfAvg, 1e-6);
// Enhanced edge/detail protection:
// Trust the noisy image more at edges, but only if we have enough matches (N)
// to actually reduce noise. If N is small, we favor the basic estimate.
float relN = smoothstep(1.0, 5.0, N);
float edgeSq = (c21 - c01) * (c21 - c01) + (c12 - c10) * (c12 - c10);
float detailProtect = smoothstep(sigma_n2 * 20.0, sigma_n2 * 100.0, edgeSq + varSignal);
float maxTrust = mix(0.65, 0.92, relN);
wienerW = mix(wienerW * 0.70, min(wienerW, maxTrust), detailProtect);
vec3 avgNoisyYuv = vec3(sumNoisyY / N, sumNoisyC / N);
float fullResY = mix(basicYuv.x, avgNoisyYuv.x, clamp(wienerW, 0.0, 1.0));
// Low-frequency luma residual suppression. This does not replace the
// signal with a blurred image: it only removes a bounded residual, and
// only where the basic-estimate guide says the area is flat.
float lowFreqY = wideGuidedLumaBase(vTexCoord, T, c11, sigma_n2);
float flatness = 1.0 - smoothstep(
max(sigma_n2 * 18.0, 2e-5),
max(sigma_n2 * 120.0, 1.2e-4),
edgeSq + varSignal
);
float matchConfidence = smoothstep(2.5, 8.0, N) * smoothstep(0.08, 0.36, basicSample.a);
float residualLimit = max(localH * 0.65, 0.003);
float residualPull = clamp(fullResY - lowFreqY, -residualLimit, residualLimit);
float lowFreqStrength = 0.35 * flatness * matchConfidence * (1.0 - detailProtect * 0.65);
float finalY = fullResY - residualPull * clamp(lowFreqStrength, 0.0, 0.35);
vec3 outYuv = vec3(
finalY,
mix(basicYuv.yz, avgNoisyYuv.yz, clamp(wienerW * 0.25, 0.0, 0.45))
);
fragColor = vec4(clamp(ycbcr2rgb(outYuv), 0.0, 1.0), 1.0);
}
""".trimIndent()
}
@@ -0,0 +1,302 @@
package com.hinnka.mycamera.raw
/**
* OpenGL ES 3.1 compute port of darktable's denoiseprofile.cl wavelets path.
*
* The pipeline mirrors darktable process_wavelets_cl:
* precondition -> repeated decompose -> repeated reduce/synthesize -> backtransform.
*/
object DenoiseProfileShaders {
const val BANDS = 7
const val REDUCE_FIRST_LOCAL_X = 16
const val REDUCE_FIRST_LOCAL_Y = 16
const val REDUCE_SECOND_LOCAL_X = 256
const val REDUCE_SIZE = 64
private const val COMMON = """
precision highp float;
precision highp int;
vec4 readPixel(sampler2D image, ivec2 coord, ivec2 size) {
ivec2 c = clamp(coord, ivec2(0), size - ivec2(1));
return texelFetch(image, c, 0);
}
vec4 dtPow(vec4 a, vec4 b) {
return pow(a, b);
}
"""
val PRECONDITION_Y0U0V0 = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform vec4 uA;
uniform vec4 uP;
uniform vec4 uB;
uniform mat3 uToY0U0V0;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 pixel = readPixel(uInput, coord, uImageSize);
float alpha = pixel.a;
vec4 t = max(
2.0 * dtPow(max(vec4(0.0), pixel + uB), 1.0 - uP / 2.0) /
((-uP + 2.0) * sqrt(uA)),
vec4(0.0)
);
vec3 outRgb = uToY0U0V0 * t.rgb;
imageStore(uOutput, coord, vec4(outRgb, alpha));
}
""".trimIndent()
val PRECONDITION_V2 = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform vec4 uA;
uniform vec4 uP;
uniform vec4 uB;
uniform vec4 uWb;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 pixel = readPixel(uInput, coord, uImageSize);
float alpha = pixel.a;
vec4 t = max(
2.0 * dtPow(max(vec4(0.0), pixel / uWb + uB), 1.0 - uP / 2.0) /
((-uP + 2.0) * sqrt(uA)),
vec4(0.0)
);
t.a = alpha;
imageStore(uOutput, coord, t);
}
""".trimIndent()
val DECOMPOSE = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uCoarse;
layout(rgba16f, binding = 2) writeonly uniform highp image2D uDetail;
uniform ivec2 uImageSize;
uniform int uScale;
uniform float uInvSigma2;
const float uFilter[25] = float[25](
0.00390625, 0.015625, 0.0234375, 0.015625, 0.00390625,
0.015625, 0.0625, 0.09375, 0.0625, 0.015625,
0.0234375, 0.09375, 0.140625, 0.09375, 0.0234375,
0.015625, 0.0625, 0.09375, 0.0625, 0.015625,
0.00390625, 0.015625, 0.0234375, 0.015625, 0.00390625
);
vec4 weight(vec4 c1, vec4 c2, float invSigma2) {
vec4 sqr = (c1 - c2) * (c1 - c2);
float dt = (sqr.x + sqr.y + sqr.z) * invSigma2;
float r = exp2(-max(0.0, dt * 0.02 - 9.0));
return vec4(r);
}
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
int mult = 1 << uScale;
vec4 pixel = readPixel(uInput, coord, uImageSize);
vec4 sum = vec4(0.0);
vec4 wgt = vec4(0.0);
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
ivec2 sampleCoord = coord + ivec2(mult * (i - 2), mult * (j - 2));
int k = j * 5 + i;
vec4 px = readPixel(uInput, sampleCoord, uImageSize);
vec4 w = uFilter[k] * weight(pixel, px, uInvSigma2);
sum += w * px;
wgt += w;
}
}
sum /= max(wgt, vec4(1e-20));
sum.a = pixel.a;
imageStore(uDetail, coord, pixel - sum);
imageStore(uCoarse, coord, sum);
}
""".trimIndent()
val SYNTHESIZE = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uCoarse;
layout(binding = 1) uniform highp sampler2D uDetail;
layout(rgba16f, binding = 2) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform vec4 uThreshold;
uniform vec4 uBoost;
vec4 copySign(vec4 x, vec4 y) {
return abs(x) * sign(y);
}
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 c = readPixel(uCoarse, coord, uImageSize);
vec4 d = readPixel(uDetail, coord, uImageSize);
vec4 amount = copySign(max(vec4(0.0), abs(d) - uThreshold), d);
vec4 sum = c + uBoost * amount;
sum.a = c.a;
imageStore(uOutput, coord, sum);
}
""".trimIndent()
val REDUCE_FIRST = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(std430, binding = 0) buffer AccuBuffer { vec4 accu[]; };
shared vec4 sBuffer[${REDUCE_FIRST_LOCAL_X * REDUCE_FIRST_LOCAL_Y}];
uniform ivec2 uImageSize;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
int lid = int(gl_LocalInvocationID.y) * int(gl_WorkGroupSize.x) + int(gl_LocalInvocationID.x);
bool inImage = coord.x < uImageSize.x && coord.y < uImageSize.y;
vec4 pixel = inImage ? readPixel(uInput, coord, uImageSize) : vec4(0.0);
sBuffer[lid] = inImage ? pixel * pixel : vec4(0.0);
barrier();
memoryBarrierShared();
for (int offset = ${REDUCE_FIRST_LOCAL_X * REDUCE_FIRST_LOCAL_Y} / 2; offset > 0; offset /= 2) {
if (lid < offset) sBuffer[lid] += sBuffer[lid + offset];
barrier();
memoryBarrierShared();
}
if (lid == 0) {
int groupsX = int(gl_NumWorkGroups.x);
int m = int(gl_WorkGroupID.y) * groupsX + int(gl_WorkGroupID.x);
accu[m] = sBuffer[0];
}
}
""".trimIndent()
val REDUCE_SECOND = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = $REDUCE_SECOND_LOCAL_X, local_size_y = 1) in;
layout(std430, binding = 0) readonly buffer InputBuffer { vec4 inputVals[]; };
layout(std430, binding = 1) writeonly buffer ResultBuffer { vec4 resultVals[]; };
shared vec4 sBuffer[$REDUCE_SECOND_LOCAL_X];
uniform int uLength;
void main() {
int x = int(gl_GlobalInvocationID.x);
vec4 sumY2 = vec4(0.0);
int globalSize = int(gl_NumWorkGroups.x) * int(gl_WorkGroupSize.x);
while (x < uLength) {
sumY2 += inputVals[x];
x += globalSize;
}
int lid = int(gl_LocalInvocationID.x);
sBuffer[lid] = sumY2;
barrier();
memoryBarrierShared();
for (int offset = $REDUCE_SECOND_LOCAL_X / 2; offset > 0; offset /= 2) {
if (lid < offset) sBuffer[lid] += sBuffer[lid + offset];
barrier();
memoryBarrierShared();
}
if (lid == 0) {
resultVals[int(gl_WorkGroupID.x)] = sBuffer[0];
}
}
""".trimIndent()
val BACKTRANSFORM_Y0U0V0 = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform vec4 uA;
uniform vec4 uP;
uniform vec4 uB;
uniform float uBias;
uniform vec4 uWb;
uniform mat3 uToRgb;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 t = readPixel(uInput, coord, uImageSize);
float alpha = t.a;
vec4 px = vec4(uToRgb * t.rgb, alpha);
px = max(vec4(0.0), px);
vec4 delta = px * px + vec4(uBias) * uWb;
vec4 denominator = 4.0 / (sqrt(uA) * (2.0 - uP));
vec4 z1 = (px + sqrt(max(vec4(0.0), delta))) / denominator;
px = max(dtPow(z1, 1.0 / (1.0 - uP / 2.0)) - uB, vec4(0.0));
px.a = alpha;
imageStore(uOutput, coord, px);
}
""".trimIndent()
val BACKTRANSFORM_V2 = """
#version 310 es
$COMMON
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform vec4 uA;
uniform vec4 uP;
uniform vec4 uB;
uniform float uBias;
uniform vec4 uWb;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 px = max(vec4(0.0), readPixel(uInput, coord, uImageSize));
float alpha = px.a;
vec4 delta = px * px + vec4(uBias);
vec4 denominator = 4.0 / (sqrt(uA) * (2.0 - uP));
vec4 z1 = (px + sqrt(max(vec4(0.0), delta))) / denominator;
px = max(dtPow(z1, 1.0 / (1.0 - uP / 2.0)) - uB, vec4(0.0));
px *= uWb;
px.a = alpha;
imageStore(uOutput, coord, px);
}
""".trimIndent()
}
@@ -1,232 +0,0 @@
package com.hinnka.mycamera.raw
object NLMShaders {
/**
* Pass 0: 色度降噪 (在亮度降噪前执行,提供更干净的引导图)
*/
val PASS0_CHROMA_DENOISE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
float getLuma(vec3 rgb) {
return dot(rgb, vec3(0.2126, 0.7152, 0.0722));
}
vec3 rgb2ycbcr(vec3 rgb) {
float y = getLuma(rgb);
return vec3(y, dot(rgb, vec3(-0.169, -0.331, 0.5)) + 0.5, dot(rgb, vec3(0.5, -0.419, -0.081)) + 0.5);
}
vec3 ycbcr2rgb(vec3 y) {
float cb = y.y - 0.5, cr = y.z - 0.5;
return vec3(y.x + 1.402 * cr, y.x - 0.3441 * cb - 0.7141 * cr, y.x + 1.772 * cb);
}
void main() {
vec3 oriRgb = texture(uInputTexture, vTexCoord).rgb;
vec3 yuv = rgb2ycbcr(oriRgb);
vec2 sumUV = vec2(0.0); float sumW = 0.0;
// 采样步长随强度增加,色度噪声通常是低频的大色块
float stepScale = 6.5;
// 动态计算权重参数
// 色度权重容差稍微放宽,以消除色度噪点
float chromaH = uH * 1.5;
// 亮度权重容差必须严格,以保边并防止跨边缘渗色 (光晕)
float lumaH = uH * 0.5;
float invChromaH2 = 1.0 / max(chromaH * chromaH, 1e-6);
float invLumaH2 = 1.0 / max(lumaH * lumaH, 1e-6);
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
vec2 offset = vec2(float(x), float(y)) * uTexelSize * stepScale;
vec3 s = texture(uInputTexture, vTexCoord + offset).rgb;
vec3 sYuv = rgb2ycbcr(s);
// 空间权重 (Gaussian)
float wS = exp(-float(x*x+y*y)/4.0);
// 相似性权重 (Cross-Bilateral)
float dL = sYuv.x - yuv.x;
vec2 dC = sYuv.yz - yuv.yz;
float wR = exp(-(dL * dL) * invLumaH2 - dot(dC, dC) * invChromaH2);
float w = wS * wR;
// 中心像素保证一定权重
if (x == 0 && y == 0) w = max(w, 0.1);
sumUV += sYuv.yz * w;
sumW += w;
}
}
yuv.yz = sumUV / sumW;
fragColor = vec4(ycbcr2rgb(yuv), 1.0);
}
""".trimIndent()
/**
* NLM 降噪 Shader
* 使用 Non-Local Means 算法进行降噪
*/
// -----------------------------------------------------------------------------------------
// Separable NLM (Approximation)
// -----------------------------------------------------------------------------------------
/**
* NLM Pass 1: 水平方向
* 输入: uInputTexture (源图像/色度降噪后的图像)
* 输出: 水平模糊后的图像
*/
val NLM_PASS_H = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
#define SEARCH_RADIUS 3
#define PATCH_RADIUS 1
void main() {
vec3 centerVal = texture(uInputTexture, vTexCoord).rgb;
if (uH <= 0.00001) {
fragColor = vec4(centerVal, 1.0);
return;
}
float h2 = max(uH * uH, 1e-5);
float patchArea = float((2 * PATCH_RADIUS + 1) * (2 * PATCH_RADIUS + 1));
float invH2 = 1.0 / (h2 * patchArea);
const vec3 W = vec3(0.2126, 0.7152, 0.0722);
vec3 sumColor = vec3(0.0);
float sumWeight = 0.0;
float maxWeight = 0.0;
// 水平搜索
for(int dx = -SEARCH_RADIUS; dx <= SEARCH_RADIUS; dx++) {
if(dx == 0) continue;
vec2 neighborUV = vTexCoord + vec2(float(dx), 0.0) * uTexelSize;
// 计算 Patch 相似度 (Luma SSD)
float dist = 0.0;
for(int px = -PATCH_RADIUS; px <= PATCH_RADIUS; px++) {
for(int py = -PATCH_RADIUS; py <= PATCH_RADIUS; py++) {
vec2 offset = vec2(float(px), float(py)) * uTexelSize;
vec3 c1 = texture(uInputTexture, vTexCoord + offset).rgb;
vec3 c2 = texture(uInputTexture, neighborUV + offset).rgb;
float l1 = dot(c1, W);
float l2 = dot(c2, W);
float d = l1 - l2;
dist += d * d;
}
}
float w = exp(-dist * invH2);
vec3 neighborVal = texture(uInputTexture, neighborUV).rgb;
sumColor += neighborVal * w;
sumWeight += w;
maxWeight = max(maxWeight, w);
}
// 中心像素:使用邻域内的最大权重,若最大权重太小(找不到匹配),则强制设为 1.0 以保留原像素
float centerWeight = max(maxWeight, 0.1);
sumColor += centerVal * centerWeight;
sumWeight += centerWeight;
fragColor = vec4(sumColor / sumWeight, 1.0);
}
""".trimIndent()
/**
* NLM Pass 2: 垂直方向
* 输入:
* - uInputTexture: 原始图像 (用于计算权重,保持结构)
* - uBlurTexture: Pass 1 输出 (用于模糊累加)
* 输出: 最终降噪图像
*/
val NLM_PASS_V = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture; // 用于计算权重的 Guide
uniform sampler2D uBlurTexture; // 需要模糊的 Buffer
uniform vec2 uTexelSize;
uniform mat4 uTexMatrix;
uniform float uH;
#define SEARCH_RADIUS 3
#define PATCH_RADIUS 1
void main() {
vec3 centerValBlur = texture(uBlurTexture, vTexCoord).rgb;
if (uH <= 0.00001) {
fragColor = vec4(centerValBlur, 1.0);
return;
}
float h2 = max(uH * uH, 1e-5);
float patchArea = float((2 * PATCH_RADIUS + 1) * (2 * PATCH_RADIUS + 1));
float invH2 = 1.0 / (h2 * patchArea);
const vec3 W = vec3(0.2126, 0.7152, 0.0722);
vec3 sumColor = vec3(0.0);
float sumWeight = 0.0;
float maxWeight = 0.0;
// 垂直搜索
for(int dy = -SEARCH_RADIUS; dy <= SEARCH_RADIUS; dy++) {
if(dy == 0) continue;
vec2 neighborUV = vTexCoord + vec2(0.0, float(dy)) * uTexelSize;
// 计算 Patch 相似度 (必须使用 uInputTexture 保持结构!)
float dist = 0.0;
for(int px = -PATCH_RADIUS; px <= PATCH_RADIUS; px++) {
for(int py = -PATCH_RADIUS; py <= PATCH_RADIUS; py++) {
vec2 offset = vec2(float(px), float(py)) * uTexelSize;
vec3 c1 = texture(uInputTexture, vTexCoord + offset).rgb;
vec3 c2 = texture(uInputTexture, neighborUV + offset).rgb;
float l1 = dot(c1, W);
float l2 = dot(c2, W);
float d = l1 - l2;
dist += d * d;
}
}
float w = exp(-dist * invH2);
// 累加的是 uBlurTexture
vec3 neighborVal = texture(uBlurTexture, neighborUV).rgb;
sumColor += neighborVal * w;
sumWeight += w;
maxWeight = max(maxWeight, w);
}
// 中心像素
float centerWeight = max(maxWeight, 0.1);
sumColor += centerValBlur * centerWeight;
sumWeight += centerWeight;
fragColor = vec4(sumColor / sumWeight, 1.0);
}
""".trimIndent()
}
@@ -138,7 +138,6 @@ class RawDemosaicProcessor {
private const val TAG = "RawDemosaicProcessor"
private const val RAW_HDR_HIGHLIGHT_START = 0.72f
private const val RAW_HDR_WHITE_POINT_SCENE_LUMA = 2.4f
private const val BM3D_REFERENCE_MID_GRAY_SIGMA = 0.012f
init {
// 加载 JNI 库
@@ -216,17 +215,21 @@ class RawDemosaicProcessor {
private var dummyDcp3DTextureId = 0
private var dummyDcpToneCurveTextureId = 0
// (Chroma) & NLM 降噪资源
private var gfPass0Program = 0
private var nlmPassHProgram = 0
private var nlmPassVProgram = 0
// darktable denoiseprofile 降噪资源
private var denoisePreconditionY0U0V0Program = 0
private var denoisePreconditionV2Program = 0
private var denoiseDecomposeProgram = 0
private var denoiseSynthesizeProgram = 0
private var denoiseReduceFirstProgram = 0
private var denoiseReduceSecondProgram = 0
private var denoiseBacktransformY0U0V0Program = 0
private var denoiseBacktransformV2Program = 0
// NLM 中间纹理: ping-pong (RGBA16F)
// denoiseprofile 中间纹理: ping-pong (RGBA16F)
private var gfTexId = intArrayOf(0, 0)
private var gfFboId = intArrayOf(0, 0)
private var gfWidth = 0
private var gfHeight = 0
private var gfChromaTexId = 0
suspend fun prewarmDepthEstimator(context: Context) = withContext(Dispatchers.Default) {
val start = System.currentTimeMillis()
@@ -234,7 +237,11 @@ class RawDemosaicProcessor {
PLog.d(TAG, "RAW DepthEstimator prewarmed, took=${System.currentTimeMillis() - start}ms")
}
private var gfChromaFboId = 0
private val denoiseDetailTexIds = IntArray(DenoiseProfileShaders.BANDS)
private var denoiseReduceMBufferId = 0
private var denoiseReduceRBufferId = 0
private var denoiseReduceBufSize = 0
private var denoiseReduceSize = 0
// 缓冲区
private var vertexBuffer: FloatBuffer? = null
@@ -769,15 +776,14 @@ class RawDemosaicProcessor {
}
val workingColorSpace = resolveWorkingColorSpace()
// NLM 降噪
renderNLMPass(
// darktable denoiseprofile 降噪
renderDenoiseProfilePass(
sourceTextureId = demosaicTextureId,
width = actualWidth,
height = actualHeight,
metadata = actualMetadata,
linearExposureGain = computeLinearExposureGain(actualMetadata, effectiveExposureCompensation, resolvedDcpRenderPlan),
denoiseValue = denoiseValue,
chromaDenoiseValue = denoiseValue,
)
val outputTexture = gfTexId[1]
@@ -787,14 +793,6 @@ class RawDemosaicProcessor {
// demosaicFramebufferId = 0
// }
// demosaicWidth = 0; demosaicHeight = 0
if (gfChromaTexId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfChromaTexId), 0)
gfChromaTexId = 0
}
if (gfChromaFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(gfChromaFboId), 0)
gfChromaFboId = 0
}
if (gfTexId[0] != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfTexId[0]), 0)
gfTexId[0] = 0
@@ -1218,31 +1216,24 @@ class RawDemosaicProcessor {
}
/**
* 初始化 Guided Filter Pass 0 和 NLM 着色器
* 初始化 darktable denoiseprofile compute 着色器。
*/
private fun initNLMPrograms(vShader: Int) {
fun createGfProgram(vShader: Int, fSource: String, name: String): Int {
val fShader = compileShader(GLES30.GL_FRAGMENT_SHADER, fSource)
if (vShader == 0 || fShader == 0) return 0
val program = GLES30.glCreateProgram()
GLES30.glAttachShader(program, vShader)
GLES30.glAttachShader(program, fShader)
GLES30.glLinkProgram(program)
if (!logProgramLinkResult(program, name)) {
GLES30.glDeleteShader(fShader)
return 0
}
GLES30.glDeleteShader(fShader)
return program
}
gfPass0Program = createGfProgram(vShader, BM3DShaders.PASS0_CHROMA_DENOISE, "BM3D_Pass0")
nlmPassHProgram = createGfProgram(vShader, BM3DShaders.PASS1_BASIC_ESTIMATE, "BM3D_Pass1")
nlmPassVProgram = createGfProgram(vShader, BM3DShaders.PASS2_WIENER, "BM3D_Pass2")
denoisePreconditionY0U0V0Program = compileComputeProgram(DenoiseProfileShaders.PRECONDITION_Y0U0V0, "DenoiseProfile_Precondition_Y0U0V0")
denoisePreconditionV2Program = compileComputeProgram(DenoiseProfileShaders.PRECONDITION_V2, "DenoiseProfile_Precondition_V2")
denoiseDecomposeProgram = compileComputeProgram(DenoiseProfileShaders.DECOMPOSE, "DenoiseProfile_Decompose")
denoiseSynthesizeProgram = compileComputeProgram(DenoiseProfileShaders.SYNTHESIZE, "DenoiseProfile_Synthesize")
denoiseReduceFirstProgram = compileComputeProgram(DenoiseProfileShaders.REDUCE_FIRST, "DenoiseProfile_ReduceFirst")
denoiseReduceSecondProgram = compileComputeProgram(DenoiseProfileShaders.REDUCE_SECOND, "DenoiseProfile_ReduceSecond")
denoiseBacktransformY0U0V0Program = compileComputeProgram(DenoiseProfileShaders.BACKTRANSFORM_Y0U0V0, "DenoiseProfile_Backtransform_Y0U0V0")
denoiseBacktransformV2Program = compileComputeProgram(DenoiseProfileShaders.BACKTRANSFORM_V2, "DenoiseProfile_Backtransform_V2")
PLog.d(
TAG,
"Denoise programs: BM3D_Pass0=$gfPass0Program BM3D_Pass1=$nlmPassHProgram BM3D_Pass2=$nlmPassVProgram"
"DenoiseProfile programs: preY=$denoisePreconditionY0U0V0Program preRgb=$denoisePreconditionV2Program " +
"decompose=$denoiseDecomposeProgram synthesize=$denoiseSynthesizeProgram " +
"reduce1=$denoiseReduceFirstProgram reduce2=$denoiseReduceSecondProgram " +
"backY=$denoiseBacktransformY0U0V0Program backRgb=$denoiseBacktransformV2Program"
)
}
@@ -1256,51 +1247,14 @@ class RawDemosaicProcessor {
if (gfTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(gfTexId[i]), 0)
if (gfFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(gfFboId[i]), 0)
}
if (gfChromaTexId != 0) GLES30.glDeleteTextures(1, intArrayOf(gfChromaTexId), 0)
if (gfChromaFboId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(gfChromaFboId), 0)
// 创建独立纹理用于色度降噪结果
val ct = IntArray(1)
val cf = IntArray(1)
GLES30.glGenTextures(1, ct, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ct[0])
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
GLES30.GL_RGBA16F,
width,
height,
0,
GLES30.GL_RGBA,
GLES30.GL_HALF_FLOAT,
null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_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)
GLES30.glGenFramebuffers(1, cf, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, cf[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
ct[0],
0
)
gfChromaTexId = ct[0]; gfChromaFboId = cf[0]
// 创建双缓冲 (RGBA16F) 用于中间 pass
// 创建双缓冲 (RGBA16F) 用于 denoiseprofile 中间 pass
for (i in 0..1) {
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, width, height, 0,
GLES30.GL_RGBA, GLES30.GL_HALF_FLOAT, null
)
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_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)
@@ -1314,117 +1268,499 @@ class RawDemosaicProcessor {
t[0],
0
)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(TAG, "DenoiseProfile ping-pong FBO $i incomplete: $status")
}
gfTexId[i] = t[0]; gfFboId[i] = f[0]
}
setupDenoiseProfileResources(width, height)
checkGlError("setupGuidedFilterFramebuffers")
}
private fun setupDenoiseProfileResources(width: Int, height: Int) {
for (i in denoiseDetailTexIds.indices) {
if (denoiseDetailTexIds[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(denoiseDetailTexIds[i]), 0)
val t = IntArray(1)
GLES30.glGenTextures(1, t, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0])
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_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)
denoiseDetailTexIds[i] = t[0]
}
val groupsX = roundUp(width, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X
val groupsY = roundUp(height, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y
denoiseReduceBufSize = groupsX * groupsY
denoiseReduceSize = kotlin.math.min(
DenoiseProfileShaders.REDUCE_SIZE,
roundUp(denoiseReduceBufSize, DenoiseProfileShaders.REDUCE_SECOND_LOCAL_X) / DenoiseProfileShaders.REDUCE_SECOND_LOCAL_X
).coerceAtLeast(1)
if (denoiseReduceMBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(denoiseReduceMBufferId), 0)
if (denoiseReduceRBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(denoiseReduceRBufferId), 0)
val buffers = IntArray(2)
GLES31.glGenBuffers(2, buffers, 0)
denoiseReduceMBufferId = buffers[0]
denoiseReduceRBufferId = buffers[1]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, denoiseReduceMBufferId)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, denoiseReduceBufSize * 4 * 4, null, GLES31.GL_DYNAMIC_DRAW)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, denoiseReduceRBufferId)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, denoiseReduceSize * 4 * 4, null, GLES31.GL_DYNAMIC_READ)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
/**
* 渲染 BM3D 降噪
* 渲染 darktable denoiseprofile wavelets 降噪。
*
* 管线: tonemapTexture → [Pass0 Chroma] → [BM3D Basic] → [BM3D Wiener] → gfFboId[1]
*
* @param sourceTextureId 输入纹理 (ToneMap 输出)
* 管线: linear RGB → variance-stabilizing transform → wavelet decompose/synthesize → inverse transform → gfFboId[1]
*/
private fun renderNLMPass(
private fun renderDenoiseProfilePass(
sourceTextureId: Int,
width: Int,
height: Int,
metadata: RawMetadata,
linearExposureGain: Float,
denoiseValue: Float?,
chromaDenoiseValue: Float?,
) {
setupNLMFramebuffers(width, height)
if (gfPass0Program == 0 || nlmPassHProgram == 0 || nlmPassVProgram == 0) {
PLog.w(TAG, "Denoise programs not initialized, skipping denoise")
if (!isDenoiseProfileReady()) {
PLog.w(TAG, "DenoiseProfile programs not initialized, falling back to passthrough")
renderPassthroughToTexture(sourceTextureId, width, height, gfFboId[1])
return
}
val texelW = 1.0f / width
val texelH = 1.0f / height
val params = buildDenoiseProfileParams(metadata, linearExposureGain, denoiseValue ?: 0f)
if (params.strength <= 0f || width * height < 2) {
renderPassthroughToTexture(sourceTextureId, width, height, gfFboId[1])
return
}
// Camera2 SENSOR_NOISE_PROFILE is defined in the linear RAW domain.
// Convert it into the linear RGB texture domain consumed by BM3D, so
// the user strength remains a dimensionless multiplier of measured sigma.
val isoGain = metadata.iso / 100.0f
val digitalGain = metadata.postRawSensitivityBoost
val fallbackGain = (isoGain * digitalGain).coerceAtLeast(1f)
val (s, o) = resolveDenoiseNoiseModel(metadata, linearExposureGain, fallbackGain)
val denoiseValue = denoiseValue ?: 0f
val chromaDenoiseValue = chromaDenoiseValue ?: 0f
val noiseAdaptiveScale = computeDenoiseStrengthScale(s, o)
val h = denoiseValue.coerceAtLeast(0f) * BM3DShaders.SIGMA_STRENGTH_AT_SLIDER_ONE * noiseAdaptiveScale
val ch = chromaDenoiseValue.coerceAtLeast(0f) * BM3DShaders.SIGMA_STRENGTH_AT_SLIDER_ONE * noiseAdaptiveScale + 0.5f
PLog.d(
TAG,
"Dynamic BM3D: s=$s o=$o, h=$h ch=$ch scale=$noiseAdaptiveScale iso=${metadata.iso} linearGain=$linearExposureGain"
"DenoiseProfile wavelets: strength=${params.strength} a=${params.a} b=${params.b} " +
"shadows=${params.shadows} bias=${params.bias} maxScale=${params.maxScale} wb=${params.wb.contentToString()}"
)
dispatchDenoisePrecondition(sourceTextureId, gfTexId[0], width, height, params)
var buf1 = gfTexId[0]
var buf2 = gfTexId[1]
for (scale in 0 until params.maxScale) {
dispatchDenoiseDecompose(buf1, buf2, denoiseDetailTexIds[scale], width, height, scale)
val tmp = buf2
buf2 = buf1
buf1 = tmp
}
for (scale in params.maxScale - 1 downTo 0) {
val threshold = computeDenoiseProfileThreshold(
textureId = denoiseDetailTexIds[scale],
width = width,
height = height,
scale = scale,
params = params
)
dispatchDenoiseSynthesize(buf1, denoiseDetailTexIds[scale], buf2, width, height, threshold)
val tmp = buf2
buf2 = buf1
buf1 = tmp
}
val finalInput = if (buf1 == gfTexId[1]) {
renderPassthroughToTexture(buf1, width, height, gfFboId[0])
gfTexId[0]
} else {
buf1
}
dispatchDenoiseBacktransform(finalInput, gfTexId[1], width, height, params)
checkGlError("renderDenoiseProfile")
}
private data class DenoiseProfileParams(
val strength: Float,
val a: Float,
val b: Float,
val shadows: Float,
val bias: Float,
val scale: Float,
val maxScale: Int,
val p: FloatArray,
val wb: FloatArray,
val aa: FloatArray,
val bb: FloatArray,
val toY0U0V0: FloatArray,
val toRgb: FloatArray
)
private fun isDenoiseProfileReady(): Boolean {
return denoisePreconditionY0U0V0Program != 0 &&
denoiseDecomposeProgram != 0 &&
denoiseSynthesizeProgram != 0 &&
denoiseReduceFirstProgram != 0 &&
denoiseReduceSecondProgram != 0 &&
denoiseBacktransformY0U0V0Program != 0
}
private fun buildDenoiseProfileParams(
metadata: RawMetadata,
linearExposureGain: Float,
strengthValue: Float
): DenoiseProfileParams {
val profileGain = (metadata.iso / 100.0f * metadata.postRawSensitivityBoost).coerceAtLeast(1f)
val (noiseA, noiseB) = resolveDenoiseNoiseModel(metadata, linearExposureGain, profileGain)
val a = noiseA.coerceAtLeast(1e-10f)
val b = noiseB.coerceAtLeast(1e-10f)
val strength = strengthValue.coerceAtLeast(0f)
val scale = 1.0f
val shadows = inferDenoiseProfileShadows(a)
val bias = inferDenoiseProfileBias(a)
val wb = computeDenoiseProfileWb(metadata)
val p = floatArrayOf(
max(shadows + 0.1f * ln(scale / wb[0]), 0.0f),
max(shadows + 0.1f * ln(scale / wb[1]), 0.0f),
max(shadows + 0.1f * ln(scale / wb[2]), 0.0f),
1.0f
)
val compensateP = 0.05f / 0.05f.pow(shadows)
val compensateStrength = 2.5f
val scaledWb = floatArrayOf(
wb[0] * strength * compensateStrength * scale,
wb[1] * strength * compensateStrength * scale,
wb[2] * strength * compensateStrength * scale,
0.0f
)
val aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1.0f)
val bb = floatArrayOf(b, b, b, 1.0f)
val (toY, toRgbBase) = computeDenoiseProfileY0U0V0Matrices(wb)
val toYScaled = FloatArray(9)
val toRgbScaled = FloatArray(9)
for (k in 0 until 3) {
for (c in 0 until 3) {
val idx = k * 3 + c
toYScaled[idx] = toY[idx] / (strength * compensateStrength * scale).coerceAtLeast(1e-10f)
toRgbScaled[idx] = toRgbBase[idx] * strength * compensateStrength * scale
}
}
return DenoiseProfileParams(
strength = strength,
a = a,
b = b,
shadows = shadows,
bias = bias,
scale = scale,
maxScale = computeDenoiseProfileMaxScale(metadata.width, metadata.height, metadata.width, metadata.height),
p = p,
wb = scaledWb,
aa = aa,
bb = bb,
toY0U0V0 = toYScaled,
toRgb = toRgbScaled
)
}
private fun inferDenoiseProfileShadows(a: Float): Float {
return max(0.1f - 0.1f * ln(a), 0.7f).coerceAtMost(1.8f)
}
private fun inferDenoiseProfileBias(a: Float): Float {
return -max(5f + 0.5f * ln(a), 0.0f)
}
private fun computeDenoiseProfileWb(metadata: RawMetadata): FloatArray {
val r = metadata.whiteBalanceGains.getOrElse(0) { 1f }.coerceAtLeast(1e-6f)
val g = ((metadata.whiteBalanceGains.getOrElse(1) { 1f } + metadata.whiteBalanceGains.getOrElse(2) { 1f }) * 0.5f)
.coerceAtLeast(1e-6f)
val b = metadata.whiteBalanceGains.getOrElse(3) { 1f }.coerceAtLeast(1e-6f)
return floatArrayOf(r, g, b, 0f)
}
private fun computeDenoiseProfileMaxScale(width: Int, height: Int, fullWidth: Int, fullHeight: Int): Int {
val scale = 1.0f
val maxMaxScale = DenoiseProfileShaders.BANDS
val supp0 = kotlin.math.min(
(2 * (2 shl (maxMaxScale - 1)) + 1).toFloat(),
max(fullHeight.toFloat(), fullWidth.toFloat()) * 0.2f
)
val i0 = ln((supp0 - 1.0f) * 0.5f) / ln(2.0f)
var maxScale = 0
while (maxScale < maxMaxScale) {
val supp = (2 * (2 shl maxScale) + 1).toFloat()
val suppIn = supp * (1.0f / scale)
val iIn = ln((suppIn - 1.0f) * 0.5f) / ln(2.0f) - 1.0f
val t = 1.0f - (iIn + 0.5f) / i0
if (t < 0.0f) break
maxScale++
}
return maxScale.coerceIn(1, DenoiseProfileShaders.BANDS)
}
private fun computeDenoiseProfileY0U0V0Matrices(wb: FloatArray): Pair<FloatArray, FloatArray> {
val toY = floatArrayOf(
1f / 3f, 1f / 3f, 1f / 3f,
0.5f, 0.0f, -0.5f,
0.25f, -0.5f, 0.25f
)
var sumInvWb = 1.0f / wb[0] + 1.0f / wb[1] + 1.0f / wb[2]
sumInvWb *= sqrt(3.0f)
toY[0] = sumInvWb / wb[0]
toY[1] = sumInvWb / wb[1]
toY[2] = sumInvWb / wb[2]
val stddevU0 = sqrt(0.25f * wb[0] * wb[0] + 0.25f * wb[2] * wb[2]).coerceAtLeast(1e-6f)
val stddevV0 = sqrt(0.0625f * wb[0] * wb[0] + 0.25f * wb[1] * wb[1] + 0.0625f * wb[2] * wb[2]).coerceAtLeast(1e-6f)
for (i in 3..5) toY[i] /= stddevU0
for (i in 6..8) toY[i] /= stddevV0
val toRgb = invertMatrix3x3RowMajor(toY) ?: run {
val fallback = toY.copyOf()
val stddevY0 = sqrt((wb[0] * wb[0] + wb[1] * wb[1] + wb[2] * wb[2]) / 9.0f).coerceAtLeast(1e-6f)
fallback[0] = 1.0f / (3.0f * stddevY0)
fallback[1] = fallback[0]
fallback[2] = fallback[0]
invertMatrix3x3RowMajor(fallback) ?: identityMatrix3x3()
}
return toY to toRgb
}
private fun invertMatrix3x3RowMajor(m: FloatArray): FloatArray? {
val bigA = m[4] * m[8] - m[5] * m[7]
val bigB = -m[3] * m[8] + m[5] * m[6]
val bigC = m[3] * m[7] - m[4] * m[6]
val bigD = -m[1] * m[8] + m[2] * m[7]
val bigE = m[0] * m[8] - m[2] * m[6]
val bigF = -m[0] * m[7] + m[1] * m[6]
val bigG = m[1] * m[5] - m[2] * m[4]
val bigH = -m[0] * m[5] + m[2] * m[3]
val bigI = m[0] * m[4] - m[1] * m[3]
val det = m[0] * bigA + m[1] * bigB + m[2] * bigC
if (det == 0f) return null
val invDet = 1.0f / det
return floatArrayOf(
invDet * bigA, invDet * bigD, invDet * bigG,
invDet * bigB, invDet * bigE, invDet * bigH,
invDet * bigC, invDet * bigF, invDet * bigI
)
}
private fun matrix3RowMajorToGlColumnMajor(m: FloatArray): FloatArray {
return floatArrayOf(
m[0], m[3], m[6],
m[1], m[4], m[7],
m[2], m[5], m[8]
)
}
private fun dispatchDenoisePrecondition(
sourceTextureId: Int,
outputTextureId: Int,
width: Int,
height: Int,
params: DenoiseProfileParams
) {
val program = denoisePreconditionY0U0V0Program
GLES31.glUseProgram(program)
bindComputeSampler(program, "uInput", 0, sourceTextureId)
GLES31.glBindImageTexture(1, outputTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
setDenoiseCommonUniforms(program, width, height, params)
GLES31.glUniformMatrix3fv(
GLES31.glGetUniformLocation(program, "uToY0U0V0"),
1, false, matrix3RowMajorToGlColumnMajor(params.toY0U0V0), 0
)
dispatchDenoiseImage(width, height, "DenoiseProfile precondition")
}
private fun dispatchDenoiseDecompose(
inputTextureId: Int,
coarseTextureId: Int,
detailTextureId: Int,
width: Int,
height: Int,
scale: Int
) {
val program = denoiseDecomposeProgram
GLES31.glUseProgram(program)
bindComputeSampler(program, "uInput", 0, inputTextureId)
GLES31.glBindImageTexture(1, coarseTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glBindImageTexture(2, detailTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uScale"), scale)
val varf = sqrt(2.0f + 2.0f * 4.0f * 4.0f + 6.0f * 6.0f) / 16.0f
val sigmaBand = varf.pow(scale)
GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uInvSigma2"), 1.0f / (sigmaBand * sigmaBand))
dispatchDenoiseImage(width, height, "DenoiseProfile decompose $scale")
}
private fun dispatchDenoiseSynthesize(
coarseTextureId: Int,
detailTextureId: Int,
outputTextureId: Int,
width: Int,
height: Int,
threshold: FloatArray
) {
val program = denoiseSynthesizeProgram
GLES31.glUseProgram(program)
bindComputeSampler(program, "uCoarse", 0, coarseTextureId)
bindComputeSampler(program, "uDetail", 1, detailTextureId)
GLES31.glBindImageTexture(2, outputTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uThreshold"), 1, threshold, 0)
GLES31.glUniform4f(GLES31.glGetUniformLocation(program, "uBoost"), 1f, 1f, 1f, 1f)
dispatchDenoiseImage(width, height, "DenoiseProfile synthesize")
}
private fun dispatchDenoiseBacktransform(
inputTextureId: Int,
outputTextureId: Int,
width: Int,
height: Int,
params: DenoiseProfileParams
) {
val program = denoiseBacktransformY0U0V0Program
GLES31.glUseProgram(program)
bindComputeSampler(program, "uInput", 0, inputTextureId)
GLES31.glBindImageTexture(1, outputTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
setDenoiseCommonUniforms(program, width, height, params)
GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uBias"), params.bias - 0.5f * ln(params.scale))
GLES31.glUniformMatrix3fv(
GLES31.glGetUniformLocation(program, "uToRgb"),
1, false, matrix3RowMajorToGlColumnMajor(params.toRgb), 0
)
dispatchDenoiseImage(width, height, "DenoiseProfile backtransform")
}
private fun setDenoiseCommonUniforms(
program: Int,
width: Int,
height: Int,
params: DenoiseProfileParams
) {
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uA"), 1, params.aa, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uP"), 1, params.p, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uB"), 1, params.bb, 0)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uWb"), 1, params.wb, 0)
}
private fun computeDenoiseProfileThreshold(
textureId: Int,
width: Int,
height: Int,
scale: Int,
params: DenoiseProfileParams
): FloatArray {
val groupsX = roundUp(width, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X
val groupsY = roundUp(height, DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y) / DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y
val bWidth = groupsX * DenoiseProfileShaders.REDUCE_FIRST_LOCAL_X
val bHeight = groupsY * DenoiseProfileShaders.REDUCE_FIRST_LOCAL_Y
GLES31.glUseProgram(denoiseReduceFirstProgram)
bindComputeSampler(denoiseReduceFirstProgram, "uInput", 0, textureId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, denoiseReduceMBufferId)
GLES31.glUniform2i(GLES31.glGetUniformLocation(denoiseReduceFirstProgram, "uImageSize"), width, height)
GLES31.glDispatchCompute(groupsX, groupsY, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("DenoiseProfile reduce_first")
GLES31.glUseProgram(denoiseReduceSecondProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, denoiseReduceMBufferId)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, denoiseReduceRBufferId)
GLES31.glUniform1i(GLES31.glGetUniformLocation(denoiseReduceSecondProgram, "uLength"), denoiseReduceBufSize)
GLES31.glDispatchCompute(denoiseReduceSize, 1, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
checkGlError("DenoiseProfile reduce_second")
val sumY2 = readDenoiseReduceResult(denoiseReduceSize)
val npixels = (width * height).toFloat()
val varf = sqrt(2.0f + 2.0f * 4.0f * 4.0f + 6.0f * 6.0f) / 16.0f
val sigmaBand = varf.pow(scale)
val sb2 = sigmaBand * sigmaBand
val varY0 = sumY2[0] / (npixels - 1.0f)
val varY1 = sumY2[1] / (npixels - 1.0f)
val varY2 = sumY2[2] / (npixels - 1.0f)
val stdX0 = sqrt(max(1e-6f, varY0 - sb2))
val stdX1 = sqrt(max(1e-6f, varY1 - sb2))
val stdX2 = sqrt(max(1e-6f, varY2 - sb2))
val bandIndex = DenoiseProfileShaders.BANDS - (scale + (DenoiseProfileShaders.BANDS - params.maxScale) + 1)
val forceY0 = 0.5f
val forceU0V0 = 0.5f
val adjY = 8.0f * forceY0 * forceY0 * 4.0f
val adjC = 8.0f * forceU0V0 * forceU0V0 * 4.0f
return floatArrayOf(
adjY * sb2 / stdX0,
adjC * sb2 / stdX1,
adjC * sb2 / stdX2,
0.0f
).also {
PLog.d(TAG, "DenoiseProfile threshold scale=$scale band=$bandIndex thrs=${it.contentToString()} b=${bWidth}x$bHeight")
}
}
private fun readDenoiseReduceResult(reduceSize: Int): FloatArray {
val byteCount = reduceSize * 4 * 4
val out = FloatArray(4)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, denoiseReduceRBufferId)
val mapped = GLES31.glMapBufferRange(
GLES31.GL_SHADER_STORAGE_BUFFER,
0,
byteCount,
GLES31.GL_MAP_READ_BIT
) as? ByteBuffer
if (mapped != null) {
mapped.order(ByteOrder.nativeOrder())
val floats = mapped.asFloatBuffer()
for (i in 0 until reduceSize) {
out[0] += floats.get(i * 4)
out[1] += floats.get(i * 4 + 1)
out[2] += floats.get(i * 4 + 2)
}
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
} else {
PLog.w(TAG, "DenoiseProfile reduce result map failed")
}
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
return out
}
private fun bindComputeSampler(program: Int, name: String, unit: Int, textureId: Int) {
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureId)
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit)
}
private fun dispatchDenoiseImage(width: Int, height: Int, tag: String) {
GLES31.glDispatchCompute((width + 15) / 16, (height + 15) / 16, 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT
)
checkGlError(tag)
}
private fun renderPassthroughToTexture(sourceTextureId: Int, width: Int, height: Int, framebufferId: Int) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(passthroughProgram)
val identityMatrix = FloatArray(16)
GlMatrix.setIdentityM(identityMatrix, 0)
// ===== Pass 0: 色度降噪 (输出到 gfChromaFboId) =====
GLES30.glUseProgram(gfPass0Program)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfChromaFboId)
GLES30.glViewport(0, 0, width, height)
GLES30.glUniformMatrix4fv(GLES30.glGetUniformLocation(passthroughProgram, "uTexMatrix"), 1, false, identityMatrix, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(gfPass0Program, "uInputTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(gfPass0Program, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(gfPass0Program, "uTexMatrix"),
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(gfPass0Program, "uH"), ch)
GLES30.glUniform2f(GLES30.glGetUniformLocation(gfPass0Program, "uNoiseModel"), s, o)
drawQuad(gfPass0Program)
GLES30.glUniform1i(GLES30.glGetUniformLocation(passthroughProgram, "uTexture"), 0)
drawQuad(passthroughProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("DenoiseProfile passthrough")
}
// ===== BM3D Pass 1: Basic Estimate (gfChromaTexId -> gfFboId[0]) =====
GLES30.glUseProgram(nlmPassHProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfFboId[0])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfChromaTexId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassHProgram, "uInputTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmPassHProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassHProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassHProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassHProgram)
// ===== BM3D Pass 2: Wiener Refinement (gfChromaTexId + gfTexId[0] -> gfFboId[1]) =====
GLES30.glUseProgram(nlmPassVProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, gfFboId[1])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfChromaTexId) // Original noisy (chroma-denoised)
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, gfTexId[0]) // Pass-1 basic estimate
GLES30.glUniform1i(GLES30.glGetUniformLocation(nlmPassVProgram, "uBasicTexture"), 1)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uTexelSize"), texelW, texelH)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(nlmPassVProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(nlmPassVProgram, "uH"), h)
GLES30.glUniform2f(GLES30.glGetUniformLocation(nlmPassVProgram, "uNoiseModel"), s, o)
drawQuad(nlmPassVProgram)
checkGlError("renderNLMDenoise")
private fun roundUp(value: Int, multiple: Int): Int {
return ((value + multiple - 1) / multiple) * multiple
}
private fun resolveDenoiseNoiseModel(
@@ -1447,11 +1783,6 @@ class RawDemosaicProcessor {
return transformedS.coerceAtLeast(1e-10f) to transformedO.coerceAtLeast(1e-10f)
}
private fun computeDenoiseStrengthScale(s: Float, o: Float): Float {
val midGraySigma = sqrt((s * 0.18f + o).coerceAtLeast(1e-10f))
return (midGraySigma / BM3D_REFERENCE_MID_GRAY_SIGMA).coerceIn(1f, 2.8f)
}
private fun dhtSetCommonUniforms(program: Int, metadata: RawMetadata) {
val loc = GLES30.glGetUniformLocation(program, "uImageSize")
if (loc >= 0) GLES30.glUniform2f(loc, metadata.width.toFloat(), metadata.height.toFloat())
@@ -2700,14 +3031,28 @@ class RawDemosaicProcessor {
if (rcdWriteOutputProgram != 0) GLES31.glDeleteProgram(rcdWriteOutputProgram)
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
// Guided Filter & NLM programs
if (nlmPassHProgram != 0) GLES30.glDeleteProgram(nlmPassHProgram)
if (nlmPassVProgram != 0) GLES30.glDeleteProgram(nlmPassVProgram)
// Guided Filter textures and FBOs
// darktable denoiseprofile compute programs
if (denoisePreconditionY0U0V0Program != 0) GLES31.glDeleteProgram(denoisePreconditionY0U0V0Program)
if (denoisePreconditionV2Program != 0) GLES31.glDeleteProgram(denoisePreconditionV2Program)
if (denoiseDecomposeProgram != 0) GLES31.glDeleteProgram(denoiseDecomposeProgram)
if (denoiseSynthesizeProgram != 0) GLES31.glDeleteProgram(denoiseSynthesizeProgram)
if (denoiseReduceFirstProgram != 0) GLES31.glDeleteProgram(denoiseReduceFirstProgram)
if (denoiseReduceSecondProgram != 0) GLES31.glDeleteProgram(denoiseReduceSecondProgram)
if (denoiseBacktransformY0U0V0Program != 0) GLES31.glDeleteProgram(denoiseBacktransformY0U0V0Program)
if (denoiseBacktransformV2Program != 0) GLES31.glDeleteProgram(denoiseBacktransformV2Program)
// denoiseprofile textures and FBOs
for (i in 0..1) {
if (gfTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(gfTexId[i]), 0)
if (gfFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(gfFboId[i]), 0)
}
for (i in denoiseDetailTexIds.indices) {
if (denoiseDetailTexIds[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(denoiseDetailTexIds[i]), 0)
denoiseDetailTexIds[i] = 0
}
if (denoiseReduceMBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(denoiseReduceMBufferId), 0)
if (denoiseReduceRBufferId != 0) GLES31.glDeleteBuffers(1, intArrayOf(denoiseReduceRBufferId), 0)
denoiseReduceMBufferId = 0
denoiseReduceRBufferId = 0
if (rawTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
if (demosaicTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(demosaicTextureId), 0)
@@ -91,7 +91,6 @@ private data class PreviewRenderSignature(
val editFrameCustomProperties: Map<String, String>,
val editSharpening: Float,
val editNoiseReduction: Float,
val editChromaNoiseReduction: Float,
val editRawDenoise: Float,
val editRawExposureCompensation: Float,
val editRawAutoExposure: Boolean,
@@ -164,7 +163,6 @@ fun PhotoEditScreen(
val editSharpening by viewModel.editSharpening.collectAsState()
val editNoiseReduction by viewModel.editNoiseReduction.collectAsState()
val editChromaNoiseReduction by viewModel.editChromaNoiseReduction.collectAsState()
val editRawNlmNoiseFactor by viewModel.editRawDenoise.collectAsState()
val editRawExposureCompensation by viewModel.editRawExposureCompensation.collectAsState()
val editRawAutoExposure by viewModel.editRawAutoExposure.collectAsState()
@@ -215,7 +213,6 @@ fun PhotoEditScreen(
editFrameCustomProperties = editFrameCustomProperties.toMap(),
editSharpening = editSharpening,
editNoiseReduction = editNoiseReduction,
editChromaNoiseReduction = editChromaNoiseReduction,
editRawDenoise = editRawNlmNoiseFactor,
editRawExposureCompensation = editRawExposureCompensation,
editRawAutoExposure = editRawAutoExposure,
@@ -1005,14 +1002,6 @@ fun PhotoEditScreen(
onValueChange = { viewModel.setNoiseReduction(it) },
onValueChangeFinished = { }
)
SliderSettingItem(
title = stringResource(R.string.settings_chroma_noise_reduction),
value = editChromaNoiseReduction,
valueRange = 0f..1f,
resetValue = 0f,
onValueChange = { viewModel.setChromaNoiseReduction(it) },
onValueChangeFinished = { }
)
}
2 -> {
RawEditPanel(
@@ -198,7 +198,6 @@ fun SettingsScreen(
// 软件处理参数
val sharpening by viewModel.sharpening.collectAsState(initial = 0f)
val noiseReduction by viewModel.noiseReduction.collectAsState(initial = 0f)
val chromaNoiseReduction by viewModel.chromaNoiseReduction.collectAsState(initial = 0f)
val defaultFocalLength by viewModel.defaultFocalLength.collectAsState(initial = 0f)
val customLensIds by viewModel.customLensIds.collectAsState(initial = emptyList())
val multiFrameCount by viewModel.multiFrameCount.collectAsState()
@@ -1291,17 +1290,6 @@ fun SettingsScreen(
resetValue = 0f,
onValueChange = { viewModel.setNoiseReduction(it) }
)
Spacer(modifier = Modifier.height(12.dp))
SliderSettingItem(
title = stringResource(R.string.settings_chroma_noise_reduction),
description = stringResource(R.string.settings_chroma_noise_reduction_description),
value = chromaNoiseReduction,
valueRange = 0f..1f,
resetValue = 0f,
onValueChange = { viewModel.setChromaNoiseReduction(it) }
)
}
Spacer(modifier = Modifier.height(24.dp))
@@ -1727,6 +1727,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
*/
fun setNoiseReduction(value: Float) {
editNoiseReduction.value = value
editChromaNoiseReduction.value = value
}
/**
@@ -2054,7 +2055,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
colorRecipeParams = recipeParamsOverride ?: editPhotoRecipeParams.value ?: editLutRecipeParams.value,
sharpening = editSharpening.value,
noiseReduction = editNoiseReduction.value,
chromaNoiseReduction = editChromaNoiseReduction.value,
chromaNoiseReduction = editNoiseReduction.value,
rawDenoiseValue = editRawDenoise.value,
rawExposureCompensation = editRawExposureCompensation.value,
rawAutoExposure = editRawAutoExposure.value,
@@ -2086,7 +2087,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
finalS = editSharpening.value
finalNR = editNoiseReduction.value
finalCNR = editChromaNoiseReduction.value
finalCNR = editNoiseReduction.value
} else {
finalMetadata = metadata
@@ -2346,7 +2347,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
colorRecipeParams = editPhotoRecipeParams.value,
sharpening = editSharpening.value,
noiseReduction = editNoiseReduction.value,
chromaNoiseReduction = editChromaNoiseReduction.value,
chromaNoiseReduction = editNoiseReduction.value,
rawDenoiseValue = editRawDenoise.value,
rawExposureCompensation = editRawExposureCompensation.value,
rawAutoExposure = editRawAutoExposure.value,