feat: implement GPU-accelerated RCD demosaicking and unsharp mask sharpening

This commit is contained in:
zhoubinjia committed 2026-05-20 14:27:22 +08:00
1 parent 36d12908c9
commit d525292103
5 files changed
+1113 -336

No files matched your search

+59 -19
View File
@@ -1860,6 +1860,7 @@ struct ExifData {
bool hasNoiseProfile = false;
int subjectLocation[4] = {0, 0, 0, 0};
int subjectLocationLen = 0;
int rotation = 0;
};
static int sget2(unsigned int ord, LibRaw_abstract_datastream *stream) {
@@ -1905,6 +1906,20 @@ static void exif_callback(void *datap, int tag, int type, int len,
else if (type == 4)
ed->iso = sget4(ord, stream);
}
} else if (actual_tag == 0x0112) { // Orientation
if (len > 0) {
int orientation = 0;
if (type == 3)
orientation = sget2(ord, stream);
else if (type == 4)
orientation = sget4(ord, stream);
if (orientation == 3) ed->rotation = 180;
else if (orientation == 6) ed->rotation = 90;
else if (orientation == 8) ed->rotation = 270;
else ed->rotation = 0;
LOGI("processDngNative: EXIF orientation parsed tag 0x0112 = %d -> rotation = %d", orientation, ed->rotation);
}
} else if (actual_tag == 0xC635 || actual_tag == 0xC761) { // NoiseProfile
if (len > 0) {
int count = std::min(len, 8);
@@ -2058,25 +2073,32 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
LOGI("raw awb estimate: disabled, using camera wb");
}
ret = RawProcessor.dcraw_process();
if (ret != LIBRAW_SUCCESS) {
LOGE("processDngNative: Failed to process %s, ret=%d", path, ret);
if (!RawProcessor.imgdata.rawdata.raw_image) {
LOGE("processDngNative: raw_image is null after unpack");
env->ReleaseStringUTFChars(filePath, path);
return nullptr;
}
// 获取处理后的图像
libraw_processed_image_t *image = RawProcessor.dcraw_make_mem_image(&ret);
if (!image || ret != 0) {
LOGE("processDngNative: Failed to make mem image, ret=%d", ret);
env->ReleaseStringUTFChars(filePath, path);
return nullptr;
}
int left = RawProcessor.imgdata.sizes.left_margin;
int top = RawProcessor.imgdata.sizes.top_margin;
int width = RawProcessor.imgdata.sizes.width;
int height = RawProcessor.imgdata.sizes.height;
int rawWidth = RawProcessor.imgdata.sizes.raw_width;
// 准备返回结果
size_t outputSize = (size_t)image->width * image->height * 3 * 2;
// 准备返回结果:仅拷贝有效 Bayer 像素区域的单通道数据,以极大地减少 JNI 开销
size_t outputSize = (size_t)width * height * 2; // 16-bit single channel
void *outData = malloc(outputSize);
memcpy(outData, image->data, outputSize);
if (!outData) {
LOGE("processDngNative: Out of memory");
env->ReleaseStringUTFChars(filePath, path);
return nullptr;
}
unsigned short *src = RawProcessor.imgdata.rawdata.raw_image;
unsigned short *dst = (unsigned short *)outData;
for (int y = 0; y < height; y++) {
memcpy(dst + y * width, src + (y + top) * rawWidth + left, width * 2);
}
jobject rawDataBuffer = env->NewDirectByteBuffer(outData, outputSize);
// 提取元数据
@@ -2355,14 +2377,33 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
finalCCM.m[5], finalCCM.m[6], finalCCM.m[7], finalCCM.m[8]);
// 其它
jint width = image->width;
jint height = image->height;
jint rowStride = width * 6; // RGB16
jint rowStride = width * 2; // Single channel 16-bit Bayer
jfloat whiteLevel =
(jfloat)RawProcessor.imgdata.color.dng_levels.dng_whitelevel[0];
if (whiteLevel <= 0)
whiteLevel = (jfloat)RawProcessor.imgdata.color.maximum;
jint cfaPattern = -1; // CFA_LINEAR_RGB
// 判定 CFA 模式
int c00 = RawProcessor.COLOR(top, left);
int c01 = RawProcessor.COLOR(top, left + 1);
int c10 = RawProcessor.COLOR(top + 1, left);
int c11 = RawProcessor.COLOR(top + 1, left + 1);
jint cfaPattern = -1;
auto isG = [](int c) { return c == 1 || c == 3; };
if (c00 == 0 && isG(c01) && isG(c10) && c11 == 2) {
cfaPattern = 0; // RGGB
} else if (isG(c00) && c01 == 0 && c10 == 2 && isG(c11)) {
cfaPattern = 1; // GRBG
} else if (isG(c00) && c01 == 2 && c10 == 0 && isG(c11)) {
cfaPattern = 2; // GBRG
} else if (c00 == 2 && isG(c01) && isG(c10) && c11 == 0) {
cfaPattern = 3; // BGGR
}
if (cfaPattern == -1) {
LOGW("processDngNative: Unknown CFA matrix (%d,%d,%d,%d), fallback to RGGB(0) to avoid GPU out-of-bounds crash", c00, c01, c10, c11);
cfaPattern = 0;
}
LOGI("processDngNative: CFA pattern identified from pixel [%d,%d] color matrix: (%d,%d,%d,%d) -> %d", top, left, c00, c01, c10, c11, cfaPattern);
jfloat baselineExposure =
RawProcessor.imgdata.color.dng_levels.baseline_exposure;
@@ -2403,12 +2444,11 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
jobject dngData = env->NewObject(
dngDataClass, constructor, rawDataBuffer, width, height, rowStride,
whiteLevel, blackLevelArray, preMulArray, wbArray, colorMatrixArray,
cfaPattern, 0, baselineExposure, exportedLscArray, exportedLscWidth, exportedLscHeight, exposureBias, iso,
cfaPattern, ed.rotation, baselineExposure, exportedLscArray, exportedLscWidth, exportedLscHeight, exposureBias, iso,
shutterSpeedLong, aperture, activeArray, noiseProfileArray,
embeddedPreviewBitmap);
// 释放资源
LibRaw::dcraw_clear_mem(image);
env->ReleaseStringUTFChars(filePath, path);
return dngData;
@@ -171,12 +171,26 @@ class RawDemosaicProcessor {
private var passthroughProgram = 0
private var hdrReferenceProgram = 0
// RCD Compute Shader Programs
private var rcdPopulateProgram = 0
private var rcdStep1Program = 0
private var rcdStep2Program = 0
private var rcdStep3Program = 0
private var rcdStep40Program = 0
private var rcdStep41Program = 0
private var rcdStep42Program = 0
private var rcdStep43Program = 0
private var rcdWriteOutputProgram = 0
private var linearRcdProgram = 0
private var rawTextureId = 0
private var demosaicFramebufferId = 0
private var demosaicTextureId = 0
private var demosaicWidth = 0
private var demosaicHeight = 0
private var linearOutputFramebufferId = 0
private var linearOutputTextureId = 0
private var combinedFramebufferId = 0
private var combinedTextureId = 0
@@ -228,12 +242,13 @@ class RawDemosaicProcessor {
private var indexBuffer: ShortBuffer? = null
private var pboId = 0
// Linear Program (New)
private var linearProgram = 0
private var lensShadingTextureId = 0
private var dummyShadingTextureId = 0
private val defaultUsmRadius = 2.0f
private val defaultUsmAmount = 0.5f
private val defaultUsmThreshold = 0.005f
data class SceneStats(
val exposureGain: Float,
val curveLut: FloatArray? = null
@@ -488,7 +503,7 @@ class RawDemosaicProcessor {
actualHeight = dngRawData.height
actualRowStride = dngRawData.rowStride
actualMetadata = convertDngRawDataToMetadata(dngRawData, exposureBias, actualMetadata)
actualRotation = dngRawData.rotation
actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation
onMetadata?.invoke(actualMetadata)
}
@@ -523,66 +538,13 @@ class RawDemosaicProcessor {
}
}
// Check GL_MAX_TEXTURE_SIZE and downscale if needed
var downscaledBuffer: ByteBuffer? = null
// Check GL_MAX_TEXTURE_SIZE. Oversized Bayer RCD inputs are rejected.
if (actualWidth > maxTextureSize || actualHeight > maxTextureSize) {
PLog.w(
PLog.e(
TAG,
"Input ${actualWidth}x${actualHeight} exceeds GL_MAX_TEXTURE_SIZE=$maxTextureSize, downscaling"
"Input ${actualWidth}x${actualHeight} exceeds GL_MAX_TEXTURE_SIZE=$maxTextureSize"
)
val scaleX = maxTextureSize.toFloat() / actualWidth
val scaleY = maxTextureSize.toFloat() / actualHeight
val scaleFactor = minOf(scaleX, scaleY, 1f)
val newWidth = (actualWidth * scaleFactor).toInt() and 0xFFFFFFFE.toInt() // align to even
val newHeight = (actualHeight * scaleFactor).toInt() and 0xFFFFFFFE.toInt()
val isLinearRGB = actualMetadata.cfaPattern == RawMetadata.CFA_LINEAR_RGB
if (isLinearRGB) {
// CPU bilinear downscale for interleaved RGB16 buffer
val srcBuf = actualRawData.duplicate().order(java.nio.ByteOrder.nativeOrder())
srcBuf.position(0)
val src = srcBuf.asShortBuffer()
val dstSize = newWidth * newHeight * 3 * 2 // 3 channels * 2 bytes
val dstByteBuf = com.hinnka.mycamera.utils.DirectBufferAllocator.allocateNative(dstSize.toLong())
?.order(java.nio.ByteOrder.nativeOrder())
?: throw OutOfMemoryError("Failed to allocate native direct buffer")
val dst = dstByteBuf.asShortBuffer()
val srcChannels = 3
for (dy in 0 until newHeight) {
val sy = dy.toFloat() / newHeight * actualHeight
val sy0 = sy.toInt().coerceIn(0, actualHeight - 1)
val sy1 = (sy0 + 1).coerceIn(0, actualHeight - 1)
val fy = sy - sy0
for (dx in 0 until newWidth) {
val sx = dx.toFloat() / newWidth * actualWidth
val sx0 = sx.toInt().coerceIn(0, actualWidth - 1)
val sx1 = (sx0 + 1).coerceIn(0, actualWidth - 1)
val fx = sx - sx0
for (c in 0 until srcChannels) {
val v00 =
(src.get((sy0 * actualWidth + sx0) * srcChannels + c).toInt() and 0xFFFF).toFloat()
val v10 =
(src.get((sy0 * actualWidth + sx1) * srcChannels + c).toInt() and 0xFFFF).toFloat()
val v01 =
(src.get((sy1 * actualWidth + sx0) * srcChannels + c).toInt() and 0xFFFF).toFloat()
val v11 =
(src.get((sy1 * actualWidth + sx1) * srcChannels + c).toInt() and 0xFFFF).toFloat()
val v =
v00 * (1 - fx) * (1 - fy) + v10 * fx * (1 - fy) + v01 * (1 - fx) * fy + v11 * fx * fy
dst.put((dy * newWidth + dx) * srcChannels + c, v.toInt().coerceIn(0, 65535).toShort())
}
}
}
actualRawData = dstByteBuf
downscaledBuffer = dstByteBuf
actualRowStride = newWidth * 6
PLog.d(TAG, "Downscaled to ${newWidth}x${newHeight}")
}
actualWidth = newWidth
actualHeight = newHeight
// Update metadata dimensions
actualMetadata = actualMetadata.copy(width = newWidth, height = newHeight)
return@withContext null
}
val bounds =
@@ -590,63 +552,217 @@ class RawDemosaicProcessor {
val finalWidth = bounds.width()
val finalHeight = bounds.height()
// 4. 第一步:全分辨率处理 (Linear CCM)
// 4. 第一步:全分辨率处理 (Linear CCM / RCD Compute Shader Demosaic)
setupFullResFramebuffer(actualWidth, actualHeight)
uploadRawTextureFromBuffer(
actualRawData,
actualWidth,
actualHeight,
actualRowStride,
RawMetadata.CFA_LINEAR_RGB
actualRowStride
)
// GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB)
actualRawData = null
downscaledBuffer?.let {
com.hinnka.mycamera.utils.DirectBufferAllocator.freeNative(it)
}
renderLinearPass(
metadata = actualMetadata,
rawExposureCompensation = rawExposureCompensation,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
dcpRenderPlan = resolvedDcpRenderPlan
)
var shadowLift = 0f
var effectiveExposureCompensation = rawExposureCompensation
if (rawAutoExposure) {
val meteringResult = resolveRawAutoExposureEv(
context = context,
metadata = actualMetadata,
sourceTextureId = demosaicTextureId,
rawDROMode = rawDROMode,
dcpRenderPlan = resolvedDcpRenderPlan
// Bayer RCD Compute Shader 处理路径 (1:1 直接映射自 darktable RCD)
val ssboIds = IntArray(9)
GLES31.glGenBuffers(9, ssboIds, 0)
val extraMargin = 1024 * 1024 // 1MB 额外余量,彻底防止移动端 GPU 推测性越界读取越界崩溃
val fullSize = actualWidth * actualHeight * 4 + extraMargin
val sizes = intArrayOf(
fullSize, // CFA_Buf (0)
fullSize, // RGB0_Buf (1)
fullSize, // RGB1_Buf (2)
fullSize, // RGB2_Buf (3)
fullSize, // VH_Dir_Buf (4)
fullSize, // LPF_Buf (5)
fullSize, // P_Diff_Buf (6)
fullSize, // Q_Diff_Buf (7)
fullSize // PQ_Dir_Buf (8)
)
val autoExposureEv = meteringResult.meteredEv
if (rawDROMode.isEnabled && autoExposureEv > 0f && meteringResult.dynamicRangeGap > 1.2f) {
val maxLinearGainEv = ln(1.0f / meteringResult.p998.coerceAtLeast(0.01f)) / ln(2.0f)
val linearEv = autoExposureEv.coerceAtMost(maxLinearGainEv).coerceAtLeast(0f)
val remainingEv = autoExposureEv - linearEv
shadowLift = ((2.0f.pow(remainingEv) - 1.0f) / 0.67f).coerceIn(0f, 5.0f)
for (i in 0 until 9) {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, ssboIds[i])
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, sizes[i], null, GLES31.GL_DYNAMIC_DRAW)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, i, ssboIds[i])
}
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
PLog.d(TAG, "Raw DRO ${rawDROMode.name} linearEv=$linearEv shadowLift=$shadowLift")
effectiveExposureCompensation += linearEv
} else {
effectiveExposureCompensation += autoExposureEv
// 2.0 Populate (黑电平扣除与通道归一化)
val blackLevel4 = FloatArray(4) { idx ->
actualMetadata.blackLevel.getOrElse(idx) { actualMetadata.blackLevel.firstOrNull() ?: 0f }
.coerceAtLeast(0f)
}
if (effectiveExposureCompensation != rawExposureCompensation) {
PLog.d(TAG, "final auto exposure compensation = $effectiveExposureCompensation")
renderLinearPass(
GLES31.glUseProgram(rcdPopulateProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE10)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdPopulateProgram, "uRawTexture"), 10) // 对应 RcdShaders.POPULATE 中的 binding = 10
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdPopulateProgram, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdPopulateProgram, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(rcdPopulateProgram, "uBlackLevel"), 1, blackLevel4, 0)
GLES31.glUniform1f(GLES31.glGetUniformLocation(rcdPopulateProgram, "uWhiteLevel"), actualMetadata.whiteLevel)
val wbGains = actualMetadata.whiteBalanceGains
PLog.d(
TAG,
"RCD populate: cfa=${actualMetadata.cfaPattern} black=${blackLevel4.contentToString()} " +
"white=${actualMetadata.whiteLevel} wb=${wbGains.contentToString()} " +
"linearBlackPoint=${rawBlackPointCorrection.coerceIn(0f, 0.99f)} " +
"linearWhitePoint=${(1f + rawWhitePointCorrection).coerceAtLeast(rawBlackPointCorrection.coerceIn(0f, 0.99f) + 0.01f)}"
)
GLES31.glUniform4fv(GLES31.glGetUniformLocation(rcdPopulateProgram, "uWhiteBalanceGains"), 1, wbGains, 0)
GLES31.glDispatchCompute((actualWidth + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Populate")
// 2.1 Step 1 (共享内存垂直与水平梯度估计)
GLES31.glUseProgram(rcdStep1Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep1Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glDispatchCompute((actualWidth + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 1")
// 2.2 Step 2 (低通滤波 LPF 计算)
GLES31.glUseProgram(rcdStep2Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep2Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStep2Program, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 2")
// 2.3 Step 3 (绿通道在红蓝位置的边缘自适应插值)
GLES31.glUseProgram(rcdStep3Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep3Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStep3Program, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 3")
// 2.4 Step 4_0 (对角线高通滤波差分计算)
GLES31.glUseProgram(rcdStep40Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep40Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 4_0")
// 2.5 Step 4_1 (对角线方向强弱度选择)
GLES31.glUseProgram(rcdStep41Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep41Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStep41Program, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 4_1")
// 2.6 Step 4_2 (红蓝通道在红蓝位置色差引导插值)
GLES31.glUseProgram(rcdStep42Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep42Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStep42Program, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 4_2")
// 2.7 Step 4_3 (红蓝通道在绿色位置插值)
GLES31.glUseProgram(rcdStep43Program)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStep43Program, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStep43Program, "uCfaPattern"), actualMetadata.cfaPattern)
GLES31.glDispatchCompute((actualWidth / 2 + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
checkGlError("RCD Step 4_3")
// 2.8 Write Output (组合输出到 RGBA16F 纹理)
GLES31.glUseProgram(rcdWriteOutputProgram)
GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdWriteOutputProgram, "uImageSize"), actualWidth, actualHeight)
GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdWriteOutputProgram, "uBorder"), 4)
GLES31.glBindImageTexture(11, demosaicTextureId, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F) // 对应 RcdShaders.WRITE_OUTPUT 中的 binding = 11
GLES31.glDispatchCompute((actualWidth + 15) / 16, (actualHeight + 15) / 16, 1)
GLES31.glMemoryBarrier(GLES31.GL_ALL_BARRIER_BITS)
checkGlError("RCD Write Output")
// 解绑 Image Texture 11,避免后续与常规纹理采样单元(glBindTexture)发生绑定冲突
GLES31.glBindImageTexture(11, 0, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
// 强制等待 GPU 彻底完成所有之前的渲染和计算指令,确保 SSBO 被 GPU 完全读取完毕后再进行安全删除
GLES30.glFinish()
// 清理 SSBO
GLES31.glDeleteBuffers(9, ssboIds, 0)
for (i in 0 until 9) {
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, i, 0)
}
// 处理自动曝光测光
if (rawAutoExposure) {
val meteringResult = resolveRawAutoExposureEv(
context = context,
metadata = actualMetadata,
rawExposureCompensation = effectiveExposureCompensation,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
sourceTextureId = demosaicTextureId,
rawDROMode = rawDROMode,
dcpRenderPlan = resolvedDcpRenderPlan
)
val autoExposureEv = meteringResult.meteredEv
if (rawDROMode.isEnabled && autoExposureEv > 0f && meteringResult.dynamicRangeGap > 1.2f) {
val maxLinearGainEv = ln(1.0f / meteringResult.p998.coerceAtLeast(0.01f)) / ln(2.0f)
val linearEv = autoExposureEv.coerceAtMost(maxLinearGainEv).coerceAtLeast(0f)
val remainingEv = autoExposureEv - linearEv
shadowLift = ((2.0f.pow(remainingEv) - 1.0f) / 0.67f).coerceIn(0f, 5.0f)
effectiveExposureCompensation += linearEv
} else {
effectiveExposureCompensation += autoExposureEv
}
}
}
// rawTextureId 已被 linearPass 消费,提前释放 GPU 显存
// 运行 linearRcdProgram 将 CCM & Exposure 应用在已解马赛克的浮点 RCD 图像上
checkGlError("Before LinearRcdPass")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearOutputFramebufferId)
checkGlError("LinearRcdPass setup framebuffer")
GLES30.glUseProgram(linearRcdProgram)
GLES30.glViewport(0, 0, actualWidth, actualHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, demosaicTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(linearRcdProgram, "uDemosaickedTexture"), 0)
val transposedCCM = transposeMatrix3x3(resolvedDcpRenderPlan?.colorCorrectionMatrix ?: actualMetadata.colorCorrectionMatrix)
GLES30.glUniformMatrix3fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uColorCorrectionMatrix"),
1, false, transposedCCM, 0
)
val exposureGain = computeLinearExposureGain(actualMetadata, effectiveExposureCompensation, resolvedDcpRenderPlan)
GLES30.glUniform1f(GLES30.glGetUniformLocation(linearRcdProgram, "uExposureGain"), exposureGain)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(linearRcdProgram, "uBlackPoint"),
rawBlackPointCorrection.coerceIn(0f, 0.99f)
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(linearRcdProgram, "uWhitePoint"),
(1f + rawWhitePointCorrection).coerceAtLeast(rawBlackPointCorrection.coerceIn(0f, 0.99f) + 0.01f)
)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(linearRcdProgram, "uTexMatrix"),
1, false, identityMatrix, 0
)
drawQuad(linearRcdProgram)
checkGlError("LinearRcdPass drawQuad")
// 重点:使用双缓冲交换 (Swap),既不销毁任何纹理,也不需要 glGenTextures/glDeleteTextures
val tempTex = demosaicTextureId
demosaicTextureId = linearOutputTextureId
linearOutputTextureId = tempTex
val tempFbo = demosaicFramebufferId
demosaicFramebufferId = linearOutputFramebufferId
linearOutputFramebufferId = tempFbo
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
checkGlError("After LinearRcdPass Swap")
// rawTextureId 已被 RCD populate 消费,提前释放 GPU 显存
if (rawTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
rawTextureId = 0
@@ -663,16 +779,14 @@ class RawDemosaicProcessor {
denoiseValue = denoiseValue,
chromaDenoiseValue = denoiseValue,
)
// demosaicTextureId / gfChromaTexId / gfTexId[0] 已被 NLM Pass 消费,提前释放
if (demosaicTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(demosaicTextureId), 0)
demosaicTextureId = 0
}
if (demosaicFramebufferId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(demosaicFramebufferId), 0)
demosaicFramebufferId = 0
}
demosaicWidth = 0; demosaicHeight = 0
val outputTexture = gfTexId[1]
// 重点:不要在此处销毁常驻双缓冲的 framebuffer,由 setupFullResFramebuffer 或 release() 统一管理其生命周期
// if (demosaicFramebufferId != 0) {
// GLES30.glDeleteFramebuffers(1, intArrayOf(demosaicFramebufferId), 0)
// demosaicFramebufferId = 0
// }
// demosaicWidth = 0; demosaicHeight = 0
if (gfChromaTexId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfChromaTexId), 0)
gfChromaTexId = 0
@@ -690,8 +804,6 @@ class RawDemosaicProcessor {
gfFboId[0] = 0
}
val outputTexture = gfTexId[1]
val hdrReferenceBitmap = if (includeHdrReference) {
setupHdrReferenceFramebuffer(actualWidth, actualHeight)
renderHdrReferencePass(
@@ -736,7 +848,7 @@ class RawDemosaicProcessor {
shadowLift = shadowLift
)
PLog.d(TAG, "Combined Pass took: ${System.currentTimeMillis() - combinedStart}ms")
// outputTexture (gfTexId[1]) 已被 combinedPass 消费,提前释放
// outputTexture 已被 combinedPass 消费,提前释放
if (gfTexId[1] != 0) {
GLES30.glDeleteTextures(1, intArrayOf(gfTexId[1]), 0)
gfTexId[1] = 0
@@ -880,6 +992,19 @@ class RawDemosaicProcessor {
// 初始化着色器和缓冲区
initShaderProgram()
if (combinedProgram == 0 || sharpenProgram == 0 || passthroughProgram == 0 ||
rcdPopulateProgram == 0 || rcdStep1Program == 0 || rcdStep2Program == 0 ||
rcdStep3Program == 0 || rcdStep40Program == 0 || rcdStep41Program == 0 ||
rcdStep42Program == 0 || rcdStep43Program == 0 || rcdWriteOutputProgram == 0 ||
linearRcdProgram == 0) {
PLog.e(TAG, "Critical shader programs failed to compile or link. " +
"combined=$combinedProgram sharpen=$sharpenProgram pass=$passthroughProgram " +
"populate=$rcdPopulateProgram step1=$rcdStep1Program step2=$rcdStep2Program " +
"step3=$rcdStep3Program step40=$rcdStep40Program step41=$rcdStep41Program " +
"step42=$rcdStep42Program step43=$rcdStep43Program write=$rcdWriteOutputProgram " +
"linearRcd=$linearRcdProgram")
return false
}
initBuffers()
// 创建静默遮挡图
@@ -907,20 +1032,6 @@ class RawDemosaicProcessor {
// 1. DHT Multi-Pass Programs (替代旧的单 pass AHD)
// initDhtPrograms(vShader)
// 1.5 Linear Program (For Stacked RGB, 保留)
val fShaderLinear = compileShader(GLES30.GL_FRAGMENT_SHADER, RawShaders.FRAGMENT_SHADER_LINEAR)
if (vShader != 0 && fShaderLinear != 0) {
linearProgram = GLES30.glCreateProgram()
GLES30.glAttachShader(linearProgram, vShader)
GLES30.glAttachShader(linearProgram, fShaderLinear)
GLES30.glLinkProgram(linearProgram)
if (!logProgramLinkResult(linearProgram, "linearProgram")) {
linearProgram = 0
}
GLES30.glDeleteShader(fShaderLinear)
}
// 2. Combined Processing Program
val fShaderCombined = compileShader(GLES30.GL_FRAGMENT_SHADER, RawShaders.COMBINED_FRAGMENT_SHADER)
if (vShader != 0 && fShaderCombined != 0) {
@@ -979,6 +1090,9 @@ class RawDemosaicProcessor {
GLES30.glDeleteShader(fShaderPass)
}
// 2.8 RCD Programs
initRcdPrograms(vShader)
GLES30.glDeleteShader(vShader)
PLog.d(
TAG,
@@ -986,6 +1100,87 @@ class RawDemosaicProcessor {
)
}
private val FRAGMENT_SHADER_LINEAR_RCD = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uDemosaickedTexture;
uniform mat3 uColorCorrectionMatrix;
uniform float uExposureGain;
uniform float uBlackPoint;
uniform float uWhitePoint;
void main() {
vec3 rgb = texture(uDemosaickedTexture, vTexCoord).rgb;
float blackPoint = clamp(uBlackPoint, 0.0, 0.99);
float whitePoint = max(uWhitePoint, blackPoint + 0.01);
rgb = clamp((rgb - vec3(blackPoint)) / max(whitePoint - blackPoint, 1e-5), 0.0, 1.0);
// 应用色彩转换 CCM 矩阵和曝光值增益
rgb = uColorCorrectionMatrix * rgb * uExposureGain;
fragColor = vec4(rgb, 1.0);
}
""".trimIndent()
private fun initRcdPrograms(vShader: Int) {
rcdPopulateProgram = compileComputeProgram(RcdShaders.POPULATE, "POPULATE")
rcdStep1Program = compileComputeProgram(RcdShaders.STEP_1, "STEP_1")
rcdStep2Program = compileComputeProgram(RcdShaders.STEP_2, "STEP_2")
rcdStep3Program = compileComputeProgram(RcdShaders.STEP_3, "STEP_3")
rcdStep40Program = compileComputeProgram(RcdShaders.STEP_4_0, "STEP_4_0")
rcdStep41Program = compileComputeProgram(RcdShaders.STEP_4_1, "STEP_4_1")
rcdStep42Program = compileComputeProgram(RcdShaders.STEP_4_2, "STEP_4_2")
rcdStep43Program = compileComputeProgram(RcdShaders.STEP_4_3, "STEP_4_3")
rcdWriteOutputProgram = compileComputeProgram(RcdShaders.WRITE_OUTPUT, "WRITE_OUTPUT")
val fShaderLinearRcd = compileShader(GLES30.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_LINEAR_RCD)
if (vShader != 0 && fShaderLinearRcd != 0) {
linearRcdProgram = GLES30.glCreateProgram()
GLES30.glAttachShader(linearRcdProgram, vShader)
GLES30.glAttachShader(linearRcdProgram, fShaderLinearRcd)
GLES30.glLinkProgram(linearRcdProgram)
if (!logProgramLinkResult(linearRcdProgram, "linearRcdProgram")) {
linearRcdProgram = 0
}
GLES30.glDeleteShader(fShaderLinearRcd)
}
}
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) {
val error = GLES31.glGetShaderInfoLog(shader)
PLog.e(TAG, "Compute Shader $name compilation failed: $error")
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) {
val error = GLES31.glGetProgramInfoLog(program)
PLog.e(TAG, "Compute Program $name linking failed: $error")
GLES31.glDeleteProgram(program)
GLES31.glDeleteShader(shader)
return 0
}
GLES31.glDeleteShader(shader)
PLog.d(TAG, "Compute Program $name created: $program")
return program
}
private fun compileShader(type: Int, source: String): Int {
val shader = GLES30.glCreateShader(type)
GLES30.glShaderSource(shader, source)
@@ -1080,8 +1275,8 @@ class RawDemosaicProcessor {
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_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)
@@ -1276,8 +1471,7 @@ class RawDemosaicProcessor {
buffer: ByteBuffer,
width: Int,
height: Int,
rowStride: Int,
cfaPattern: Int
rowStride: Int
) {
if (rawTextureId == 0) {
val textures = IntArray(1)
@@ -1295,24 +1489,20 @@ class RawDemosaicProcessor {
buffer.position(0)
// 关键优化:使用 GL_UNPACK_ROW_LENGTH 处理 padding
val isLinearRGB = cfaPattern == RawMetadata.CFA_LINEAR_RGB
val bytesPerPixel = if (isLinearRGB) 6 else 2 // 16-bit (x3 for RGB)
val bytesPerPixel = 2 // 16-bit single-channel Bayer
val rowLength = rowStride / bytesPerPixel
val internalFormat = if (isLinearRGB) GLES30.GL_RGB16UI else GLES30.GL_R16UI
val format = if (isLinearRGB) GLES30.GL_RGB_INTEGER else GLES30.GL_RED_INTEGER
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 2)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, rowLength)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
internalFormat,
GLES30.GL_R16UI,
width,
height,
0,
format,
GLES30.GL_RED_INTEGER,
GLES30.GL_UNSIGNED_SHORT,
buffer
)
@@ -1424,43 +1614,58 @@ class RawDemosaicProcessor {
return
}
// Size mismatch, destroy and recreate
GLES30.glDeleteTextures(1, intArrayOf(demosaicTextureId), 0)
GLES30.glDeleteFramebuffers(1, intArrayOf(demosaicFramebufferId), 0)
GLES30.glDeleteTextures(2, intArrayOf(demosaicTextureId, linearOutputTextureId), 0)
GLES30.glDeleteFramebuffers(2, intArrayOf(demosaicFramebufferId, linearOutputFramebufferId), 0)
demosaicTextureId = 0
linearOutputTextureId = 0
demosaicFramebufferId = 0
linearOutputFramebufferId = 0
}
demosaicWidth = width
demosaicHeight = height
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
val textures = IntArray(2)
GLES30.glGenTextures(2, textures, 0)
demosaicTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, demosaicTextureId)
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)
linearOutputTextureId = textures[1]
val fbos = IntArray(1)
GLES30.glGenFramebuffers(1, fbos, 0)
val fbos = IntArray(2)
GLES30.glGenFramebuffers(2, fbos, 0)
demosaicFramebufferId = fbos[0]
linearOutputFramebufferId = fbos[1]
// 分配并配置第一个 Immutable 纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, demosaicTextureId)
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.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, demosaicFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
demosaicTextureId,
0
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, demosaicTextureId, 0
)
checkGlError("setupFullResFramebuffer")
// 分配并配置第二个 Immutable 纹理
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, linearOutputTextureId)
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.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearOutputFramebufferId)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, linearOutputTextureId, 0
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
checkGlError("setupFullResFramebuffer Double Buffered")
}
private fun setupCombinedFramebuffer(width: Int, height: Int) {
@@ -2184,7 +2389,15 @@ class RawDemosaicProcessor {
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(sharpenProgram, "uSharpening"),
sharpeningValue
if (sharpeningValue > 0f) sharpeningValue else defaultUsmAmount
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(sharpenProgram, "uRadius"),
defaultUsmRadius
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(sharpenProgram, "uThreshold"),
defaultUsmThreshold
)
val identityMatrix = FloatArray(16)
@@ -2198,60 +2411,6 @@ class RawDemosaicProcessor {
checkGlError("renderSharpenPass")
}
private fun renderLinearPass(
metadata: RawMetadata,
rawExposureCompensation: Float,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float,
dcpRenderPlan: DcpRenderPlan? = null
) {
GLES30.glUseProgram(linearProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, demosaicFramebufferId)
GLES30.glViewport(0, 0, metadata.width, metadata.height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rawTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(linearProgram, "uRawTexture"), 0)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(linearProgram, "uImageSize"),
metadata.width.toFloat(), metadata.height.toFloat()
)
val transposedCCM = transposeMatrix3x3(dcpRenderPlan?.colorCorrectionMatrix ?: metadata.colorCorrectionMatrix)
GLES30.glUniformMatrix3fv(
GLES30.glGetUniformLocation(linearProgram, "uColorCorrectionMatrix"),
1, false, transposedCCM, 0
)
val identity = FloatArray(16)
GlMatrix.setIdentityM(identity, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(linearProgram, "uTexMatrix"),
1, false, identity, 0
)
val normalizationGain = ExposureNormalization.compute(metadata)
val dcpBaselineExposureOffset = dcpRenderPlan?.baselineExposureOffset ?: 0f
PLog.d(
TAG,
"compute: normalizationGain=$normalizationGain baseline=${metadata.baselineExposure} dcpBaselineOffset=$dcpBaselineExposureOffset"
)
val exposureGain = computeLinearExposureGain(metadata, rawExposureCompensation, dcpRenderPlan)
GLES30.glUniform1f(GLES30.glGetUniformLocation(linearProgram, "uExposureGain"), exposureGain)
val (blackLevel, whiteLevel) = resolveLinearInputLevels(
metadata = metadata,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection
)
GLES30.glUniform3f(
GLES30.glGetUniformLocation(linearProgram, "uBlackLevel"),
blackLevel[0], blackLevel[1], blackLevel[2]
)
GLES30.glUniform3f(
GLES30.glGetUniformLocation(linearProgram, "uWhiteLevel"),
whiteLevel[0], whiteLevel[1], whiteLevel[2]
)
drawQuad(linearProgram)
}
private fun computeLinearExposureGain(
metadata: RawMetadata,
rawExposureCompensation: Float,
@@ -2331,43 +2490,6 @@ class RawDemosaicProcessor {
}
}
private fun resolveLinearInputLevels(
metadata: RawMetadata,
rawBlackPointCorrection: Float,
rawWhitePointCorrection: Float
): Pair<FloatArray, FloatArray> {
val fixedRawBlackPoint = (rawBlackPointCorrection + 0.004f).coerceAtMost(1f)
if (metadata.cfaPattern == RawMetadata.CFA_LINEAR_RGB) {
val encodedMax = 65535f
val blackLevel = FloatArray(3) { (encodedMax * fixedRawBlackPoint).coerceAtLeast(0f) }
val whiteBase = encodedMax * (1f + rawWhitePointCorrection)
val whiteLevel = FloatArray(3) { channel -> maxOf(whiteBase, blackLevel[channel] + 1f) }
return blackLevel to whiteLevel
}
val sensorRange = metadata.whiteLevel - metadata.blackLevel.average().toFloat()
val blackPointOffset = sensorRange * fixedRawBlackPoint
val whitePointOffset = sensorRange * rawWhitePointCorrection
val blackLevel = FloatArray(3) { channel ->
val sourceIndex = channelToCfaChannelIndex(channel)
(metadata.blackLevel.getOrElse(sourceIndex) { metadata.blackLevel.firstOrNull() ?: 0f } + blackPointOffset)
.coerceAtLeast(0f)
}
val whiteLevel = FloatArray(3) { channel ->
val level = metadata.whiteLevel + whitePointOffset
maxOf(level, blackLevel[channel] + 1f)
}
return blackLevel to whiteLevel
}
private fun channelToCfaChannelIndex(channel: Int): Int {
return when (channel) {
0 -> 0
1 -> 1
else -> 3
}
}
private fun renderOutputPass(rotation: Int, width: Int, height: Int, bounds: Rect, sourceTextureId: Int) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, outputFramebufferId)
GLES30.glViewport(0, 0, bounds.width(), bounds.height())
@@ -2566,6 +2688,18 @@ class RawDemosaicProcessor {
if (passthroughProgram != 0) GLES30.glDeleteProgram(passthroughProgram)
if (hdrReferenceProgram != 0) GLES30.glDeleteProgram(hdrReferenceProgram)
// RCD Compute Programs
if (rcdPopulateProgram != 0) GLES31.glDeleteProgram(rcdPopulateProgram)
if (rcdStep1Program != 0) GLES31.glDeleteProgram(rcdStep1Program)
if (rcdStep2Program != 0) GLES31.glDeleteProgram(rcdStep2Program)
if (rcdStep3Program != 0) GLES31.glDeleteProgram(rcdStep3Program)
if (rcdStep40Program != 0) GLES31.glDeleteProgram(rcdStep40Program)
if (rcdStep41Program != 0) GLES31.glDeleteProgram(rcdStep41Program)
if (rcdStep42Program != 0) GLES31.glDeleteProgram(rcdStep42Program)
if (rcdStep43Program != 0) GLES31.glDeleteProgram(rcdStep43Program)
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)
@@ -2577,11 +2711,9 @@ class RawDemosaicProcessor {
if (rawTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
if (demosaicTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(demosaicTextureId), 0)
if (demosaicFramebufferId != 0) GLES30.glDeleteFramebuffers(
1,
intArrayOf(demosaicFramebufferId),
0
)
if (linearOutputTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(linearOutputTextureId), 0)
if (demosaicFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(demosaicFramebufferId), 0)
if (linearOutputFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(linearOutputFramebufferId), 0)
if (combinedTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(combinedTextureId), 0)
if (combinedFramebufferId != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(combinedFramebufferId), 0)
if (hdrReferenceTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(hdrReferenceTextureId), 0)
@@ -89,7 +89,6 @@ data class RawMetadata(
const val CFA_GRBG = 1
const val CFA_GBRG = 2
const val CFA_BGGR = 3
const val CFA_LINEAR_RGB = -1
/**
* 从 CameraCharacteristics 和 CaptureResult 创建 RawMetadata
@@ -31,50 +31,6 @@ object RawShaders {
}
""".trimIndent()
/**
* 片元着色器 - Linear RGB 处理管线 (用于 Stacked RAW)
* 跳过解马赛克,但保留 CCM/Gamma/ToneMapping/Sharpening
*/
val FRAGMENT_SHADER_LINEAR = """
#version 300 es
precision highp float;
precision highp int;
precision highp usampler2D;
in vec2 vTexCoord;
out vec4 fragColor;
uniform usampler2D uRawTexture; // RGB16UI
uniform vec2 uImageSize;
uniform mat3 uColorCorrectionMatrix;
uniform sampler2D uLensShadingMap;
uniform float uExposureGain; // 曝光增益
uniform vec3 uBlackLevel; // Sensor black level or encoded-domain black point
uniform vec3 uWhiteLevel; // Sensor white level or encoded-domain full scale
void main() {
ivec2 coord = ivec2(gl_FragCoord.xy);
// 直接读取 Linear RGB (16-bit Normalized to 0..1)
// Stack output is 0..65535
uvec3 raw = texelFetch(uRawTexture, coord, 0).rgb;
vec3 sensor = vec3(raw);
vec3 safeWhiteLevel = max(uWhiteLevel, uBlackLevel + vec3(1.0));
vec3 rgb = clamp((sensor - uBlackLevel) / (safeWhiteLevel - uBlackLevel), 0.0, 1.0);
// 1. CCM
rgb = uColorCorrectionMatrix * rgb;
rgb = rgb * uExposureGain;
// Output Linear (由下一步 ToneMap Pass 处理)
fragColor = vec4(rgb, 1.0);
}
""".trimIndent()
/**
* 全屏四边形顶点坐标
*/
@@ -418,7 +374,7 @@ object RawShaders {
/**
* Dedicated Sharpening Shader
* Using a Laplacian-style mask for detail enhancement
* Lightweight UnSharp Mask inspired by darktable's default sharpen preset.
*/
val SHARPEN_FRAGMENT_SHADER = """
#version 300 es
@@ -430,6 +386,12 @@ object RawShaders {
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform float uSharpening;
uniform float uRadius;
uniform float uThreshold;
float luminance(vec3 color) {
return dot(color, vec3(0.2126, 0.7152, 0.0722));
}
void main() {
vec3 center = texture(uInputTexture, vTexCoord).rgb;
@@ -437,16 +399,30 @@ object RawShaders {
fragColor = vec4(center, 1.0);
return;
}
// Simple Laplacian Sharpening
vec3 left = texture(uInputTexture, vTexCoord + vec2(-uTexelSize.x, 0.0)).rgb;
vec3 right = texture(uInputTexture, vTexCoord + vec2( uTexelSize.x, 0.0)).rgb;
vec3 top = texture(uInputTexture, vTexCoord + vec2(0.0, -uTexelSize.y)).rgb;
vec3 bottom = texture(uInputTexture, vTexCoord + vec2(0.0, uTexelSize.y)).rgb;
vec3 edge = 4.0 * center - left - right - top - bottom;
vec3 result = center + edge * (uSharpening * 0.5);
float r = max(uRadius, 0.001);
float sigma = max(r * 0.5, 0.001);
float twoSigma2 = 2.0 * sigma * sigma;
vec3 blur = vec3(0.0);
float weightSum = 0.0;
for (int y = -2; y <= 2; y++) {
for (int x = -2; x <= 2; x++) {
vec2 offset = vec2(float(x), float(y));
float dist2 = dot(offset, offset);
float weight = exp(-dist2 / twoSigma2);
blur += texture(uInputTexture, vTexCoord + offset * uTexelSize * r).rgb * weight;
weightSum += weight;
}
}
blur /= max(weightSum, 1e-5);
float centerLuma = luminance(center);
float blurLuma = luminance(blur);
float delta = centerLuma - blurLuma;
float detail = sign(delta) * max(abs(delta) - uThreshold, 0.0);
vec3 result = center + center * (detail / max(centerLuma, 1e-5)) * uSharpening;
fragColor = vec4(clamp(result, 0.0, 1.0), 1.0);
}
""".trimIndent()
@@ -0,0 +1,630 @@
package com.hinnka.mycamera.raw
/**
* GPU RCD 解马赛克计算着色器库 (1:1 高保真直接移植版)
*
* 逐行平移自 darktable 的 demosaic_rcd.cl 核心算子
* 使用 SSBO (Shader Storage Buffer Object) 在全局显存中共享像素差分与梯度状态,
* 彻底避免手写算法简化引起的图像拉链与边缘杂色!
*/
object RcdShaders {
/**
* 1. 初始化与归一化片元导入 (rcd_populate.comp)
*/
val POPULATE = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout (binding = 10) uniform highp usampler2D uRawTexture; // 单通道 R16UI 原始图像,移至 binding = 10 避开 SSBO
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 1) buffer RGB0_Buf { float rgb0[]; }; // R
layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; // G
layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; // B
uniform ivec2 uImageSize;
uniform int uCfaPattern;
uniform vec4 uBlackLevel; // R, Gr, Gb, B 或 [0,1,2,3] 四通道黑电平
uniform float uWhiteLevel;
uniform vec4 uWhiteBalanceGains; // R, Gr, Gb, B 或 [0,1,2,3] 四通道白平衡增益
#define RED 0
#define GREEN 1
#define BLUE 2
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
int getBlackLevelIndex(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1; // R, Gr
else return (c == 0) ? 2 : 3; // Gb, B
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0; // Gr, R
else return (c == 0) ? 3 : 2; // B, Gb
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 2 : 3; // Gb, B
else return (c == 0) ? 0 : 1; // R, Gr
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 3 : 2; // B, Gb
else return (c == 0) ? 1 : 0; // Gr, R
}
}
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
int idx = coord.y * uImageSize.x + coord.x;
uint rawVal = texelFetch(uRawTexture, coord, 0).r;
float val = float(rawVal);
int blIdx = getBlackLevelIndex(uCfaPattern, coord.x, coord.y);
float bl = uBlackLevel[blIdx];
float wl = max(uWhiteLevel, bl + 1.0);
val = min(clamp((val - bl) / (wl - bl), 0.0, 1.0) * uWhiteBalanceGains[blIdx], 1.0);
cfa[idx] = val;
int color = getBayerColor(uCfaPattern, coord.x, coord.y);
if (color == RED) {
rgb0[idx] = val;
rgb1[idx] = 0.0;
rgb2[idx] = 0.0;
} else if (color == GREEN) {
rgb0[idx] = 0.0;
rgb1[idx] = val;
rgb2[idx] = 0.0;
} else { // BLUE
rgb0[idx] = 0.0;
rgb1[idx] = 0.0;
rgb2[idx] = val;
}
}
""".trimIndent()
/**
* 2. 共享内存梯度估计与水平/垂直选择 (rcd_step_1.comp)
*/
val STEP_1 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 4) buffer VH_Dir_Buf { float VH_dir[]; };
uniform ivec2 uImageSize;
#define epssq 1e-10f
shared float sh_buffer[576]; // 24 * 24
float fsquare(float x) {
return x * x;
}
float rcd_vdiff_local(int offset, int stride) {
float val = sh_buffer[offset - 3 * stride] - sh_buffer[offset - stride] - sh_buffer[offset + stride] + sh_buffer[offset + 3 * stride]
- 3.0f * (sh_buffer[offset - 2 * stride] + sh_buffer[offset + 2 * stride]) + 6.0f * sh_buffer[offset];
return fsquare(val);
}
float rcd_hdiff_local(int offset) {
float val = sh_buffer[offset - 3] - sh_buffer[offset - 1] - sh_buffer[offset + 1] + sh_buffer[offset + 3]
- 3.0f * (sh_buffer[offset - 2] + sh_buffer[offset + 2]) + 6.0f * sh_buffer[offset];
return fsquare(val);
}
void main() {
int xlsz = 16;
int ylsz = 16;
int xlid = int(gl_LocalInvocationID.x);
int ylid = int(gl_LocalInvocationID.y);
int xgid = int(gl_WorkGroupID.x);
int ygid = int(gl_WorkGroupID.y);
int l = ylid * xlsz + xlid;
int lsz = xlsz * ylsz; // 256
int stride = 24;
int maxbuf = 576;
int xul = xgid * xlsz - 2;
int yul = ygid * ylsz - 2;
for (int n = 0; n <= maxbuf / lsz; n++) {
int bufidx = n * lsz + l;
if (bufidx >= maxbuf) continue;
int xx = clamp(xul + bufidx % stride, 0, uImageSize.x - 1);
int yy = clamp(yul + bufidx / stride, 0, uImageSize.y - 1);
sh_buffer[bufidx] = cfa[yy * uImageSize.x + xx];
}
memoryBarrierShared();
barrier();
int col = 2 + int(gl_GlobalInvocationID.x);
int row = 2 + int(gl_GlobalInvocationID.y);
if (row >= uImageSize.y - 2 || col >= uImageSize.x - 2) return;
int idx = row * uImageSize.x + col;
int buf_offset = (ylid + 4) * stride + (xlid + 4);
float V_Stat = max(epssq, rcd_vdiff_local(buf_offset - stride, stride)
+ rcd_vdiff_local(buf_offset, stride)
+ rcd_vdiff_local(buf_offset + stride, stride));
float H_Stat = max(epssq, rcd_hdiff_local(buf_offset - 1)
+ rcd_hdiff_local(buf_offset)
+ rcd_hdiff_local(buf_offset + 1));
VH_dir[idx] = V_Stat / (V_Stat + H_Stat);
}
""".trimIndent()
/**
* 3. 邻域低通滤波 LPF (rcd_step_2.comp)
*/
val STEP_2 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 5) buffer LPF_Buf { float lpf[]; };
uniform ivec2 uImageSize;
uniform int uCfaPattern;
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
void main() {
int row = 2 + int(gl_GlobalInvocationID.y);
int col = 2 + (getBayerColor(uCfaPattern, 0, row) & 1) + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 2 || row >= uImageSize.y - 2) return;
int idx = row * uImageSize.x + col;
int w = uImageSize.x;
lpf[idx / 2] = cfa[idx]
+ 0.5f * (cfa[idx - w] + cfa[idx + w] + cfa[idx - 1] + cfa[idx + 1])
+ 0.25f * (cfa[idx - w - 1] + cfa[idx - w + 1] + cfa[idx + w - 1] + cfa[idx + w + 1]);
}
""".trimIndent()
/**
* 4. 绿色通道在红蓝 CFA 位置插值 (rcd_step_3.comp)
*/
val STEP_3 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; };
layout(std430, binding = 4) buffer VH_Dir_Buf { float VH_dir[]; };
layout(std430, binding = 5) buffer LPF_Buf { float lpf[]; };
uniform ivec2 uImageSize;
uniform int uCfaPattern;
#define eps 1e-5f
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
void main() {
int row = 4 + int(gl_GlobalInvocationID.y);
int col = 4 + (getBayerColor(uCfaPattern, 0, row) & 1) + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 5 || row >= uImageSize.y - 5) return;
int w = uImageSize.x;
int idx = row * w + col;
int lidx = idx / 2;
int w2 = 2 * w;
int w3 = 3 * w;
int w4 = 4 * w;
float VH_Central_Value = VH_dir[idx];
float VH_Neighbourhood_Value = 0.25f * (VH_dir[idx - w - 1] + VH_dir[idx - w + 1] + VH_dir[idx + w - 1] + VH_dir[idx + w + 1]);
float VH_Disc = (abs(0.5f - VH_Central_Value) < abs(0.5f - VH_Neighbourhood_Value)) ? VH_Neighbourhood_Value : VH_Central_Value;
float cfai = cfa[idx];
float N_Grad = eps + abs(cfa[idx - w] - cfa[idx + w]) + abs(cfai - cfa[idx - w2]) + abs(cfa[idx - w] - cfa[idx - w3]) + abs(cfa[idx - w2] - cfa[idx - w4]);
float S_Grad = eps + abs(cfa[idx + w] - cfa[idx - w]) + abs(cfai - cfa[idx + w2]) + abs(cfa[idx + w] - cfa[idx + w3]) + abs(cfa[idx + w2] - cfa[idx + w4]);
float W_Grad = eps + abs(cfa[idx - 1] - cfa[idx + 1]) + abs(cfai - cfa[idx - 2]) + abs(cfa[idx - 1] - cfa[idx - 3]) + abs(cfa[idx - 2] - cfa[idx - 4]);
float E_Grad = eps + abs(cfa[idx + 1] - cfa[idx - 1]) + abs(cfai - cfa[idx + 2]) + abs(cfa[idx + 1] - cfa[idx + 3]) + abs(cfa[idx + 2] - cfa[idx + 4]);
float lfpi = lpf[lidx];
float N_Est = cfa[idx - w] * (lfpi + lfpi) / (eps + lfpi + lpf[lidx - w]);
float S_Est = cfa[idx + w] * (lfpi + lfpi) / (eps + lfpi + lpf[lidx + w]);
float W_Est = cfa[idx - 1] * (lfpi + lfpi) / (eps + lfpi + lpf[lidx - 1]);
float E_Est = cfa[idx + 1] * (lfpi + lfpi) / (eps + lfpi + lpf[lidx + 1]);
float V_Est = (S_Grad * N_Est + N_Grad * S_Est) / (N_Grad + S_Grad);
float H_Est = (W_Grad * E_Est + E_Grad * W_Est) / (E_Grad + W_Grad);
rgb1[idx] = mix(V_Est, H_Est, clamp(VH_Disc, 0.0, 1.0));
}
""".trimIndent()
/**
* 5. 对角线差分计算 (rcd_step_4_0.comp)
*/
val STEP_4_0 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 6) buffer P_Diff_Buf { float p_diff[]; };
layout(std430, binding = 7) buffer Q_Diff_Buf { float q_diff[]; };
uniform ivec2 uImageSize;
float fsquare(float x) {
return x * x;
}
void main() {
int row = 3 + int(gl_GlobalInvocationID.y);
int col = 3 + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 4 || row >= uImageSize.y - 4) return;
int w = uImageSize.x;
int idx = row * w + col;
int idx2 = idx / 2;
int w2 = 2 * w;
int w3 = 3 * w;
p_diff[idx2] = fsquare((cfa[idx - w3 - 3] - cfa[idx - w - 1] - cfa[idx + w + 1] + cfa[idx + w3 + 3]) - 3.0f * (cfa[idx - w2 - 2] + cfa[idx + w2 + 2]) + 6.0f * cfa[idx]);
q_diff[idx2] = fsquare((cfa[idx - w3 + 3] - cfa[idx - w + 1] - cfa[idx + w - 1] + cfa[idx + w3 - 3]) - 3.0f * (cfa[idx - w2 + 2] + cfa[idx + w2 - 2]) + 6.0f * cfa[idx]);
}
""".trimIndent()
/**
* 6. 对角线方向选择强弱度 (rcd_step_4_1.comp)
*/
val STEP_4_1 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 6) buffer P_Diff_Buf { float p_diff[]; };
layout(std430, binding = 7) buffer Q_Diff_Buf { float q_diff[]; };
layout(std430, binding = 8) buffer PQ_Dir_Buf { float PQ_dir[]; };
uniform ivec2 uImageSize;
uniform int uCfaPattern;
#define epssq 1e-10f
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
void main() {
int row = 2 + int(gl_GlobalInvocationID.y);
int col = 2 + (getBayerColor(uCfaPattern, 0, row) & 1) + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 3 || row >= uImageSize.y - 3) return;
int w = uImageSize.x;
int idx = row * w + col;
int idx2 = idx / 2;
int idx3 = (idx - w - 1) / 2;
int idx4 = (idx + w - 1) / 2;
float P_Stat = max(epssq, p_diff[idx3] + p_diff[idx2] + p_diff[idx4 + 1]);
float Q_Stat = max(epssq, q_diff[idx3 + 1] + q_diff[idx2] + q_diff[idx4]);
PQ_dir[idx2] = P_Stat / (P_Stat + Q_Stat);
}
""".trimIndent()
/**
* 7. 红蓝通道在红蓝 CFA 位置根据对角线插值 (rcd_step_4_2.comp)
*/
val STEP_4_2 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 1) buffer RGB0_Buf { float rgb0[]; }; // R
layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; // G
layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; // B
layout(std430, binding = 8) buffer PQ_Dir_Buf { float PQ_dir[]; };
uniform ivec2 uImageSize;
uniform int uCfaPattern;
#define eps 1e-5f
#define RED 0
#define GREEN 1
#define BLUE 2
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
void main() {
int row = 4 + int(gl_GlobalInvocationID.y);
int col = 4 + (getBayerColor(uCfaPattern, 0, row) & 1) + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 4 || row >= uImageSize.y - 4) return;
int w = uImageSize.x;
int idx = row * w + col;
int pqidx = idx / 2;
int pqidx2 = (idx - w - 1) / 2;
int pqidx3 = (idx + w - 1) / 2;
int w2 = 2 * w;
int w3 = 3 * w;
int targetColor = 2 - getBayerColor(uCfaPattern, col, row);
float PQ_Central_Value = PQ_dir[pqidx];
float PQ_Neighbourhood_Value = 0.25f * (PQ_dir[pqidx2] + PQ_dir[pqidx2 + 1] + PQ_dir[pqidx3] + PQ_dir[pqidx3 + 1]);
float PQ_Disc = (abs(0.5f - PQ_Central_Value) < abs(0.5f - PQ_Neighbourhood_Value)) ? PQ_Neighbourhood_Value : PQ_Central_Value;
float PQ_Disc_Clamped = clamp(PQ_Disc, 0.0f, 1.0f);
if (targetColor == RED) {
float NW_Grad = eps + abs(rgb0[idx - w - 1] - rgb0[idx + w + 1]) + abs(rgb0[idx - w - 1] - rgb0[idx - w3 - 3]) + abs(rgb1[idx] - rgb1[idx - w2 - 2]);
float NE_Grad = eps + abs(rgb0[idx - w + 1] - rgb0[idx + w - 1]) + abs(rgb0[idx - w + 1] - rgb0[idx - w3 + 3]) + abs(rgb1[idx] - rgb1[idx - w2 + 2]);
float SW_Grad = eps + abs(rgb0[idx - w + 1] - rgb0[idx + w - 1]) + abs(rgb0[idx + w - 1] - rgb0[idx + w3 - 3]) + abs(rgb1[idx] - rgb1[idx + w2 - 2]);
float SE_Grad = eps + abs(rgb0[idx - w - 1] - rgb0[idx + w + 1]) + abs(rgb0[idx + w + 1] - rgb0[idx + w3 + 3]) + abs(rgb1[idx] - rgb1[idx + w2 + 2]);
float NW_Est = rgb0[idx - w - 1] - rgb1[idx - w - 1];
float NE_Est = rgb0[idx - w + 1] - rgb1[idx - w + 1];
float SW_Est = rgb0[idx + w - 1] - rgb1[idx + w - 1];
float SE_Est = rgb0[idx + w + 1] - rgb1[idx + w + 1];
float P_Est = (NW_Grad * SE_Est + SE_Grad * NW_Est) / (NW_Grad + SE_Grad);
float Q_Est = (NE_Grad * SW_Est + SW_Grad * NE_Est) / (NE_Grad + SW_Grad);
rgb0[idx] = rgb1[idx] + mix(P_Est, Q_Est, PQ_Disc_Clamped);
} else if (targetColor == BLUE) {
float NW_Grad = eps + abs(rgb2[idx - w - 1] - rgb2[idx + w + 1]) + abs(rgb2[idx - w - 1] - rgb2[idx - w3 - 3]) + abs(rgb1[idx] - rgb1[idx - w2 - 2]);
float NE_Grad = eps + abs(rgb2[idx - w + 1] - rgb2[idx + w - 1]) + abs(rgb2[idx - w + 1] - rgb2[idx - w3 + 3]) + abs(rgb1[idx] - rgb1[idx - w2 + 2]);
float SW_Grad = eps + abs(rgb2[idx - w + 1] - rgb2[idx + w - 1]) + abs(rgb2[idx + w - 1] - rgb2[idx + w3 - 3]) + abs(rgb1[idx] - rgb1[idx + w2 - 2]);
float SE_Grad = eps + abs(rgb2[idx - w - 1] - rgb2[idx + w + 1]) + abs(rgb2[idx + w + 1] - rgb2[idx + w3 + 3]) + abs(rgb1[idx] - rgb1[idx + w2 + 2]);
float NW_Est = rgb2[idx - w - 1] - rgb1[idx - w - 1];
float NE_Est = rgb2[idx - w + 1] - rgb1[idx - w + 1];
float SW_Est = rgb2[idx + w - 1] - rgb1[idx + w - 1];
float SE_Est = rgb2[idx + w + 1] - rgb1[idx + w + 1];
float P_Est = (NW_Grad * SE_Est + SE_Grad * NW_Est) / (NW_Grad + SE_Grad);
float Q_Est = (NE_Grad * SW_Est + SW_Grad * NE_Est) / (NE_Grad + SW_Grad);
rgb2[idx] = rgb1[idx] + mix(P_Est, Q_Est, PQ_Disc_Clamped);
}
}
""".trimIndent()
/**
* 8. 红蓝通道在 G CFA 位置插值 (rcd_step_4_3.comp)
*/
val STEP_4_3 = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; };
layout(std430, binding = 1) buffer RGB0_Buf { float rgb0[]; }; // R
layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; // G
layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; // B
layout(std430, binding = 4) buffer VH_Dir_Buf { float VH_dir[]; };
uniform ivec2 uImageSize;
uniform int uCfaPattern;
#define eps 1e-5f
int getBayerColor(int cfaPattern, int col, int row) {
int r = row % 2;
int c = col % 2;
if (cfaPattern == 0) { // RGGB
if (r == 0) return (c == 0) ? 0 : 1;
else return (c == 0) ? 1 : 2;
} else if (cfaPattern == 1) { // GRBG
if (r == 0) return (c == 0) ? 1 : 0;
else return (c == 0) ? 2 : 1;
} else if (cfaPattern == 2) { // GBRG
if (r == 0) return (c == 0) ? 1 : 2;
else return (c == 0) ? 0 : 1;
} else { // BGGR (3)
if (r == 0) return (c == 0) ? 2 : 1;
else return (c == 0) ? 1 : 0;
}
}
void main() {
int row = 4 + int(gl_GlobalInvocationID.y);
int col = 4 + (getBayerColor(uCfaPattern, 1, row) & 1) + 2 * int(gl_GlobalInvocationID.x);
if (col >= uImageSize.x - 4 || row >= uImageSize.y - 4) return;
int w = uImageSize.x;
int idx = row * w + col;
int w2 = 2 * w;
int w3 = 3 * w;
float VH_Central_Value = VH_dir[idx];
float VH_Neighbourhood_Value = 0.25f * (VH_dir[idx - w - 1] + VH_dir[idx - w + 1] + VH_dir[idx + w - 1] + VH_dir[idx + w + 1]);
float VH_Disc = (abs(0.5f - VH_Central_Value) < abs(0.5f - VH_Neighbourhood_Value)) ? VH_Neighbourhood_Value : VH_Central_Value;
float VH_Disc_Clamped = clamp(VH_Disc, 0.0f, 1.0f);
float rgbi1 = rgb1[idx];
float N1 = eps + abs(rgbi1 - rgb1[idx - w2]);
float S1 = eps + abs(rgbi1 - rgb1[idx + w2]);
float W1 = eps + abs(rgbi1 - rgb1[idx - 2]);
float E1 = eps + abs(rgbi1 - rgb1[idx + 2]);
float rgb1mw1 = rgb1[idx - w];
float rgb1pw1 = rgb1[idx + w];
float rgb1m1 = rgb1[idx - 1];
float rgb1p1 = rgb1[idx + 1];
// 1. 红色通道插值
{
float SNabs = abs(rgb0[idx - w] - rgb0[idx + w]);
float EWabs = abs(rgb0[idx - 1] - rgb0[idx + 1]);
float N_Grad = N1 + SNabs + abs(rgb0[idx - w] - rgb0[idx - w3]);
float S_Grad = S1 + SNabs + abs(rgb0[idx + w] - rgb0[idx + w3]);
float W_Grad = W1 + EWabs + abs(rgb0[idx - 1] - rgb0[idx - 3]);
float E_Grad = E1 + EWabs + abs(rgb0[idx + 1] - rgb0[idx + 3]);
float N_Est = rgb0[idx - w] - rgb1mw1;
float S_Est = rgb0[idx + w] - rgb1pw1;
float W_Est = rgb0[idx - 1] - rgb1m1;
float E_Est = rgb0[idx + 1] - rgb1p1;
float V_Est = (N_Grad * S_Est + S_Grad * N_Est) / (N_Grad + S_Grad);
float H_Est = (E_Grad * W_Est + W_Grad * E_Est) / (E_Grad + W_Grad);
rgb0[idx] = rgb1[idx] + mix(V_Est, H_Est, VH_Disc_Clamped);
}
// 2. 蓝色通道插值
{
float SNabs = abs(rgb2[idx - w] - rgb2[idx + w]);
float EWabs = abs(rgb2[idx - 1] - rgb2[idx + 1]);
float N_Grad = N1 + SNabs + abs(rgb2[idx - w] - rgb2[idx - w3]);
float S_Grad = S1 + SNabs + abs(rgb2[idx + w] - rgb2[idx + w3]);
float W_Grad = W1 + EWabs + abs(rgb2[idx - 1] - rgb2[idx - 3]);
float E_Grad = E1 + EWabs + abs(rgb2[idx + 1] - rgb2[idx + 3]);
float N_Est = rgb2[idx - w] - rgb1mw1;
float S_Est = rgb2[idx + w] - rgb1pw1;
float W_Est = rgb2[idx - 1] - rgb1m1;
float E_Est = rgb2[idx + 1] - rgb1p1;
float V_Est = (N_Grad * S_Est + S_Grad * N_Est) / (N_Grad + S_Grad);
float H_Est = (E_Grad * W_Est + W_Grad * E_Est) / (E_Grad + W_Grad);
rgb2[idx] = rgb1[idx] + mix(V_Est, H_Est, VH_Disc_Clamped);
}
}
""".trimIndent()
/**
* 9. 合并 RGB 重建结果写出到 RGBA16F 纹理 (rcd_write_output.comp)
*/
val WRITE_OUTPUT = """
#version 310 es
precision highp float;
precision highp int;
layout (local_size_x = 16, local_size_y = 16) in;
layout(std430, binding = 1) buffer RGB0_Buf { float rgb0[]; }; // R
layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; // G
layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; // B
layout (rgba16f, binding = 11) writeonly uniform highp image2D uOutputImage;
uniform ivec2 uImageSize;
uniform int uBorder;
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 color = vec4(0.0, 0.0, 0.0, 1.0);
if (coord.x >= uBorder && coord.x < uImageSize.x - uBorder &&
coord.y >= uBorder && coord.y < uImageSize.y - uBorder) {
int idx = coord.y * uImageSize.x + coord.x;
color.r = max(0.0f, rgb0[idx]);
color.g = max(0.0f, rgb1[idx]);
color.b = max(0.0f, rgb2[idx]);
}
imageStore(uOutputImage, coord, color);
}
""".trimIndent()
}