feat: MGC full-resolution bitmap denoiser

This commit is contained in:
zhoubinjia committed 2026-11-09 16:17:20 +08:00
1 parent d185a1961d
commit e878262aa4
19 files changed
+3030 -2917

No files matched your search

+1
View File
@@ -359,6 +359,7 @@ add_library(my-native-lib SHARED
dcp_parser.cpp
mgc_denoise_static/mgc_halide_runtime.cpp
mgc_denoise_static/mgc_denoise_static.cpp
mgc_denoise_static/mgc_full_resolution_denoise.cpp
mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp
mgc_denoise_static/mgc_spatial_strength_jni.cpp
raw_float_texture_transfer_jni.cpp
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,94 @@
#pragma once
#include <cstdint>
namespace photon::mgc_denoise {
/**
* One MGC full-resolution luma/chroma denoise call on an RGBA16F (or normalized
* Bayer16) buffer. Every array is owned by the caller and must outlive the call.
* Kept free of JNI so the app, offline calibration and oracle tools share it.
*/
struct FullResolutionDenoiseRequest {
// In/out pixels: width * height * 4 half floats (or Bayer16 samples).
uint16_t* rgba = nullptr;
int width = 0;
int height = 0;
int global_origin_x = 0;
int global_origin_y = 0;
int full_width = 0;
int full_height = 0;
bool input_is_bayer = false;
int cfa_pattern = 0;
bool measure_moire_enabled = false;
bool apply_lens_shading_in_bayer_aot = false;
// lens_width * lens_height * 4 gains, or null.
const float* lens_shading = nullptr;
int lens_width = 0;
int lens_height = 0;
float normalized_rgb_shot[3] = {};
float normalized_rgb_read[3] = {};
float normalized_rgb_white_balance[3] = {1.0f, 1.0f, 1.0f};
bool has_prepared_yuv_noise = false;
float prepared_normalized_yuv_read[3] = {};
float prepared_normalized_luma_shot = 0.0f;
float prepared_normalized_luma_quadratic = 0.0f;
float prepared_normalized_chroma_shot = 0.0f;
float prepared_normalized_chroma_quadratic = 0.0f;
float luma_correlation[128] = {};
float chroma_correlation[128] = {};
float denoise_response_offset = 0.0f;
float denoise_response_cosine_offset = 0.0f;
// spatial_strength_width * spatial_strength_height Q8 values over the full image, or null.
const uint16_t* spatial_strength_q8 = nullptr;
int spatial_strength_width = 0;
int spatial_strength_height = 0;
bool luma_enabled = false;
bool chroma_enabled = false;
float luma_strength[5] = {};
float luma_outlier[5] = {};
float luma_revert[5] = {};
float chroma_strength[5] = {};
float chroma_outlier[5] = {};
bool diagnostics_enabled = false;
int low_frequency_log2_downsample = 0;
int chroma_median_filter_type = 0;
};
/** Returns 0 on success, a negative stage code otherwise. */
int RunFullResolutionDenoise(const FullResolutionDenoiseRequest& request);
/**
* GCam ProcessRaw's low-frequency chroma branch as a separate whole-image pass, for callers
* that run the full-resolution denoise in tiles (the in-call branch needs the whole image).
*
* [rgba] holds the full-resolution denoised linear RGB box-downsampled by 2^log2_downsample
* (low_width x low_height = ceil(full / 2^L)), white balance 1. It is replaced in place by the
* linear RGB correction to add at full resolution after bilinear upsampling (alpha 0): the
* difference ChromaDenoise (after the optional chroma median) makes to Cb/Cr at that scale.
*/
struct LowFrequencyChromaRequest {
uint16_t* rgba = nullptr;
int low_width = 0;
int low_height = 0;
int full_width = 0;
int full_height = 0;
int log2_downsample = 1;
float prepared_normalized_yuv_read[3] = {};
float prepared_normalized_chroma_shot = 0.0f;
float prepared_normalized_chroma_quadratic = 0.0f;
float chroma_correlation[128] = {};
float denoise_response_offset = 0.0f;
float denoise_response_cosine_offset = 0.0f;
// ((full+3)/4) Q8 strength over the full image, or null for identity.
const uint16_t* spatial_strength_q8 = nullptr;
int spatial_strength_width = 0;
int spatial_strength_height = 0;
float chroma_strength[5] = {};
float chroma_outlier[5] = {};
int chroma_median_filter_type = 0;
};
int RunLowFrequencyChromaCorrection(const LowFrequencyChromaRequest& request);
} // namespace photon::mgc_denoise
File diff suppressed because it is too large. Load diff
@@ -39,6 +39,7 @@ import com.hinnka.mycamera.raw.fotufilm.FotufilmDocumentStorage
import com.hinnka.mycamera.utils.PLog
import android.net.Uri
import com.hinnka.mycamera.processor.DenoiseStrength
import com.hinnka.mycamera.raw.MgcBitmapNoiseModel
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
@@ -105,6 +106,7 @@ class PhotoProcessor(
source: File,
noiseReduction: Float,
chromaNoiseReduction: Float,
sensorIso: Int?,
onBuild: () -> Unit = {},
): Boolean {
val luma = DenoiseStrength.clamp(noiseReduction)
@@ -112,12 +114,12 @@ class PhotoProcessor(
if (luma <= 0f && chroma <= 0f) return false
val dir = GalleryManager.getPhotonDenoiseDir(context, photoId)
photonDenoiseBaseMutex.withLock {
val key = withContext(Dispatchers.IO) { photonDenoiseKey(source, luma, chroma) }
val key = withContext(Dispatchers.IO) { photonDenoiseKey(source, luma, chroma, sensorIso) }
if (withContext(Dispatchers.IO) { findPhotonDenoiseEntry(dir, key)?.touch() } != null) return false
onBuild()
val input = GalleryManager.loadBitmap(context, Uri.fromFile(source)) ?: return false
val denoised = try {
lutImageProcessor.applyBitmapDenoise(input, luma, chroma)
lutImageProcessor.applyBitmapDenoise(input, luma, chroma, sensorIso)
} catch (e: Throwable) {
input.recycle()
throw e
@@ -155,6 +157,7 @@ class PhotoProcessor(
source: File,
noiseReduction: Float,
chromaNoiseReduction: Float,
sensorIso: Int?,
maxEdge: Int? = null,
): Bitmap? {
val luma = DenoiseStrength.clamp(noiseReduction)
@@ -163,7 +166,7 @@ class PhotoProcessor(
val dir = GalleryManager.getPhotonDenoiseDir(context, photoId)
return photonDenoiseBaseMutex.withLock {
withContext(Dispatchers.IO) {
findPhotonDenoiseEntry(dir, photonDenoiseKey(source, luma, chroma))?.touch()?.let {
findPhotonDenoiseEntry(dir, photonDenoiseKey(source, luma, chroma, sensorIso))?.touch()?.let {
GalleryManager.loadBitmap(context, Uri.fromFile(it.image), maxEdge)
}
}
@@ -202,7 +205,7 @@ class PhotoProcessor(
* 源文件以内容 CRC32 标识(按路径、修改时间、大小缓存):bokeh.jpg 等派生文件会被原样重写,
* 只看修改时间会让内容未变的基底失效。
*/
private fun photonDenoiseKey(source: File, luma: Float, chroma: Float): String {
private fun photonDenoiseKey(source: File, luma: Float, chroma: Float, sensorIso: Int?): String {
val stamp = "${source.absolutePath}|${source.lastModified()}|${source.length()}"
val crc = photonDenoiseSourceCrc[stamp] ?: CRC32().run {
source.inputStream().use { input ->
@@ -218,7 +221,9 @@ class PhotoProcessor(
if (photonDenoiseSourceCrc.size > 64) photonDenoiseSourceCrc.clear()
photonDenoiseSourceCrc[stamp] = it
}
return "v2|${source.name}|${source.length()}|$crc|$luma|$chroma"
// The noise model signature retires bases built by another denoiser or calibration.
val model = MgcBitmapNoiseModel.cacheSignature(sensorIso)
return "v3|${source.name}|${source.length()}|$crc|$luma|$chroma|$model"
}
private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float {
@@ -439,8 +444,6 @@ class PhotoProcessor(
sdrBitmap,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f,
luminanceGainDownsample = RawGainmapMath.DOWNSAMPLE,
)
sdrBitmap = lutStackResult.bitmap
@@ -688,6 +691,7 @@ class PhotoProcessor(
source = if (bokehBaked) bokehFile else source,
noiseReduction = resolveNoiseReduction(metadata, 0f),
chromaNoiseReduction = resolveChromaNoiseReduction(metadata, 0f),
sensorIso = metadata.iso,
)
return processBitmap(
context = context,
@@ -862,9 +866,7 @@ class PhotoProcessor(
lutImageProcessor.applyLutStack(
b,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f
colorCorrection.creativeLayer
)
}
@@ -917,8 +919,6 @@ class PhotoProcessor(
result,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f,
luminanceGainDownsample = lutLuminanceGainDownsample,
)
result = lutStackResult.bitmap
@@ -927,9 +927,7 @@ class PhotoProcessor(
result = lutImageProcessor.applyLutStack(
result,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f
colorCorrection.creativeLayer
)
}
@@ -0,0 +1,649 @@
package com.hinnka.mycamera.lut
import android.content.Context
import android.opengl.GLES30
import android.util.Half
import com.hinnka.mycamera.processor.DenoiseStrength
import com.hinnka.mycamera.raw.MgcBitmapNoiseModel
import com.hinnka.mycamera.raw.MgcFullResolutionDenoise
import com.hinnka.mycamera.raw.RawFloatTextureTransfer
import com.hinnka.mycamera.raw.RawFullscreenQuad
import com.hinnka.mycamera.raw.RawGlesProgram
import com.hinnka.mycamera.utils.PLog
import kotlin.math.ceil
import kotlin.math.min
import kotlin.math.roundToInt
/**
* MGC luma/chroma denoise for ISP-rendered bitmaps on the caller's GL context.
*
* The source texture holds sRGB-transfer encoded RGB (sRGB, Display P3 or extended sRGB, as
* LutImageProcessor interprets it). The pass order:
* 1. the mean linear luma gives the MGC tuning SNR under the [MgcBitmapNoiseModel] for the ISO;
* 2. a noise-aware detail map: local luma variance at 2x and 4x box scales against the model
* (scaled by its measured box variance ratios). Where structure clearly exceeds noise the
* map lowers MGC's spatial strength (a Q8 noise scale), so Pecan and ChromaDenoise keep
* texture; in noise it stays 1. At low SNR structure cannot be told from noise and the map
* stays near 1;
* 3. tiles, each with [TILE_SUPPORT_PX] of overlap, are decoded to linear RGBA16F, denoised by
* [MgcFullResolutionDenoise.denoiseLinearBitmap] and their cores written to a full linear image;
* 4. GCam's low-frequency chroma branch over the whole image: the linear result box-downsampled
* by 2^[LOW_FREQUENCY_LOG2] is chroma-denoised again and its correction upsampled back;
* 5. the linear result plus that correction is encoded into the output, keeping source alpha.
*/
internal class BitmapMgcDenoiser {
private val quad = RawFullscreenQuad()
private val transfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF)
private val programs = HashMap<String, Int>()
/** An immutable RGBA16F texture with its framebuffer (the transfer's upload requires immutability). */
private class Surface(val label: String) {
var texture = 0
var framebuffer = 0
var width = 0
var height = 0
}
private val linear = Surface("bitmap MGC linear")
private val output = Surface("bitmap MGC output")
private val tile = Surface("bitmap MGC tile")
private val half = Surface("bitmap MGC half")
private val quarter = Surface("bitmap MGC quarter")
private val map = Surface("bitmap MGC detail map")
private val mean = Surface("bitmap MGC mean")
private val outputTexture get() = output.texture
private data class Tile(
val coreLeft: Int,
val coreTop: Int,
val coreRight: Int,
val coreBottom: Int,
val workLeft: Int,
val workTop: Int,
val workRight: Int,
val workBottom: Int,
) {
val workWidth get() = workRight - workLeft
val workHeight get() = workBottom - workTop
}
/**
* Returns a texture owned by this denoiser holding the denoised, re-encoded image, or
* [sourceTextureId] itself when both strengths are zero. [sensorIso] is the capture's ISO
* (EXIF/metadata), or null when unknown.
*/
fun denoise(
context: Context,
sourceTextureId: Int,
width: Int,
height: Int,
lumaStrength: Float,
chromaStrength: Float,
sensorIso: Int?,
): Int {
val luma = DenoiseStrength.clamp(lumaStrength)
val chroma = DenoiseStrength.clamp(chromaStrength)
if (luma <= 0f && chroma <= 0f) return sourceTextureId
require(width > 0 && height > 0)
check(MgcFullResolutionDenoise.ensureInitialized(context)) {
"MGC RunFullResolutionDenoise is not initialized"
}
val startNs = System.nanoTime()
val tiles = planTiles(width, height)
val maxWorkWidth = tiles.maxOf { it.workWidth }
val maxWorkHeight = tiles.maxOf { it.workHeight }
ensureFullTextures(width, height)
ensureTile(maxWorkWidth, maxWorkHeight)
val noiseModel = MgcBitmapNoiseModel.forIso(sensorIso)
val snr = noiseModel.tuningSnr(meanLinearLuma(sourceTextureId, width, height))
val strengthMap = detailStrengthMap(sourceTextureId, width, height, noiseModel)
try {
transfer.prepare(maxWorkWidth, maxWorkHeight)
for (tile in tiles) {
decodeTile(sourceTextureId, tile)
var succeeded = false
transfer.read(
texture = this.tile.texture,
width = tile.workWidth,
height = tile.workHeight,
capacityPixels = maxWorkWidth.toLong() * maxWorkHeight,
label = "MGC bitmap tile",
) { mapped ->
succeeded = MgcFullResolutionDenoise.denoiseLinearBitmap(
rgba16f = mapped,
width = tile.workWidth,
height = tile.workHeight,
globalOriginX = tile.workLeft,
globalOriginY = tile.workTop,
fullWidth = width,
fullHeight = height,
noiseModel = noiseModel.denoiserModel,
spatialStrengthQ8 = strengthMap,
tuningSnr = snr,
lumaStrengthScale = luma,
chromaStrengthScale = chroma,
)
}
check(succeeded) { "MGC bitmap denoise failed for tile $tile of ${width}x$height" }
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
transfer.upload(this.tile.texture, tile.workWidth, tile.workHeight)
copyTileCore(tile)
}
} finally {
transfer.releaseBuffers()
}
val lowFrequency = chroma > 0f &&
lowFrequencyChroma(width, height, noiseModel, strengthMap, snr, chroma)
encodeOutput(sourceTextureId, width, height, lowFrequency)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
RawGlesProgram.logErrors("BitmapMgcDenoiser")
PLog.i(
TAG,
"MGC bitmap denoise ${width}x$height tiles=${tiles.size} iso=$sensorIso " +
"modelIso=${noiseModel.iso} snr=$snr luma=$luma chroma=$chroma " +
"detailMap=${strengthMap.averageQ8()} lowFrequency=$lowFrequency " +
"took=${(System.nanoTime() - startNs) / 1_000_000}ms",
)
return outputTexture
}
fun release() {
programs.values.forEach { program -> if (program != 0) GLES30.glDeleteProgram(program) }
programs.clear()
listOf(linear, output, tile, half, quarter, map, mean).forEach(::releaseSurface)
transfer.release()
}
private fun planTiles(width: Int, height: Int): List<Tile> {
val columns = ceil(width / TILE_CORE_PX.toDouble()).toInt()
val rows = ceil(height / TILE_CORE_PX.toDouble()).toInt()
return buildList {
for (row in 0 until rows) {
val coreTop = row * height / rows
val coreBottom = (row + 1) * height / rows
for (column in 0 until columns) {
val coreLeft = column * width / columns
val coreRight = (column + 1) * width / columns
add(
Tile(
coreLeft = coreLeft,
coreTop = coreTop,
coreRight = coreRight,
coreBottom = coreBottom,
workLeft = (coreLeft - TILE_SUPPORT_PX).coerceAtLeast(0),
workTop = (coreTop - TILE_SUPPORT_PX).coerceAtLeast(0),
workRight = min(coreRight + TILE_SUPPORT_PX, width),
workBottom = min(coreBottom + TILE_SUPPORT_PX, height),
),
)
}
}
}
}
/** Mean linear MGC luma of the whole image: a GPU cell reduction read back as halves. */
private fun meanLinearLuma(sourceTextureId: Int, width: Int, height: Int): Float {
ensureSurface(mean, MEAN_GRID, MEAN_GRID)
val cellWidth = ceil(width / MEAN_GRID.toDouble()).toInt()
val cellHeight = ceil(height / MEAN_GRID.toDouble()).toInt()
draw("mean", MEAN_SHADER, mean, 0, 0, MEAN_GRID, MEAN_GRID) { program ->
bindTexture(program, "uSource", 0, sourceTextureId)
GLES30.glUniform2i(location(program, "uImageSize"), width, height)
GLES30.glUniform2i(location(program, "uCellSize"), cellWidth, cellHeight)
}
var weightedSum = 0.0
var totalWeight = 0.0
readHalves(mean, "MGC bitmap mean") { halves ->
for (cell in 0 until MEAN_GRID * MEAN_GRID) {
val cellMean = Half.toFloat(halves.get(cell * 4)).toDouble()
val weight = Half.toFloat(halves.get(cell * 4 + 1)).toDouble()
if (weight > 0.0 && cellMean.isFinite()) {
weightedSum += cellMean * weight
totalWeight += weight
}
}
}
check(totalWeight > 0.0) { "Bitmap luma reduction covered no pixels" }
return (weightedSum / totalWeight).toFloat()
}
/**
* Q8 spatial strength over the ((width + 3) / 4) x ((height + 3) / 4) grid MGC expects:
* 256 where the local luma variance is explained by noise, down to [DETAIL_MIN_STRENGTH] where
* structure exceeds it by [DETAIL_HIGH_EXCESS] at both the 2x and 4x box scales.
*/
private fun detailStrengthMap(
sourceTextureId: Int,
width: Int,
height: Int,
model: MgcBitmapNoiseModel.Calibration,
): ShortArray {
val halfWidth = (width + 1) / 2
val halfHeight = (height + 1) / 2
val gridWidth = (width + 3) / 4
val gridHeight = (height + 3) / 4
ensureSurface(half, halfWidth, halfHeight)
ensureSurface(quarter, gridWidth, gridHeight)
ensureSurface(map, gridWidth, gridHeight)
for ((surface, factor) in listOf(half to 2, quarter to 4)) {
draw("boxLuma", BOX_LUMA_SHADER, surface, 0, 0, surface.width, surface.height) { program ->
bindTexture(program, "uSource", 0, sourceTextureId)
GLES30.glUniform2i(location(program, "uImageSize"), width, height)
GLES30.glUniform1i(location(program, "uFactor"), factor)
}
}
draw("structure", STRUCTURE_SHADER, map, 0, 0, gridWidth, gridHeight) { program ->
bindTexture(program, "uBox2", 0, half.texture)
bindTexture(program, "uBox4", 1, quarter.texture)
GLES30.glUniform2i(location(program, "uBox2Size"), halfWidth, halfHeight)
GLES30.glUniform2i(location(program, "uBox4Size"), gridWidth, gridHeight)
GLES30.glUniform3f(
location(program, "uLumaNoise"),
model.lumaRead,
model.lumaShot,
model.lumaQuadratic,
)
GLES30.glUniform2f(
location(program, "uBoxVarianceRatio"),
model.boxVarianceRatio2,
model.boxVarianceRatio4,
)
GLES30.glUniform3f(
location(program, "uDetail"),
DETAIL_MIN_STRENGTH,
kotlin.math.ln(DETAIL_LOW_EXCESS),
kotlin.math.ln(DETAIL_HIGH_EXCESS),
)
}
val strength = FloatArray(gridWidth * gridHeight)
readHalves(map, "MGC bitmap detail map") { halves ->
for (index in strength.indices) strength[index] = Half.toFloat(halves.get(index * 4))
}
// 3x3 box with edge clamp: no block-shaped steps between neighbouring map cells.
return ShortArray(strength.size) { index ->
val x = index % gridWidth
val y = index / gridWidth
var sum = 0f
for (dy in -1..1) {
val yy = (y + dy).coerceIn(0, gridHeight - 1)
for (dx in -1..1) {
sum += strength[yy * gridWidth + (x + dx).coerceIn(0, gridWidth - 1)]
}
}
(sum / 9f * 256f).roundToInt().coerceIn(0, 256).toShort()
}
}
private fun decodeTile(sourceTextureId: Int, tile: Tile) {
draw("decode", DECODE_SHADER, this.tile, 0, 0, tile.workWidth, tile.workHeight) { program ->
bindTexture(program, "uSource", 0, sourceTextureId)
GLES30.glUniform2i(location(program, "uSourceOffset"), tile.workLeft, tile.workTop)
}
}
private fun copyTileCore(tile: Tile) {
draw(
"copyCore", COPY_CORE_SHADER, linear,
tile.coreLeft, tile.coreTop, tile.coreRight - tile.coreLeft, tile.coreBottom - tile.coreTop,
) { program ->
bindTexture(program, "uTile", 0, this.tile.texture)
GLES30.glUniform2i(location(program, "uTileOrigin"), tile.workLeft, tile.workTop)
}
}
/** Leaves the upsampling correction in [half]; returns whether it ran. */
private fun lowFrequencyChroma(
width: Int,
height: Int,
model: MgcBitmapNoiseModel.Calibration,
strengthMap: ShortArray,
snr: Float,
chroma: Float,
): Boolean {
val factor = 1 shl LOW_FREQUENCY_LOG2
val lowWidth = (width + factor - 1) / factor
val lowHeight = (height + factor - 1) / factor
ensureSurface(half, lowWidth, lowHeight)
draw("boxRgb", BOX_RGB_SHADER, half, 0, 0, lowWidth, lowHeight) { program ->
bindTexture(program, "uLinear", 0, linear.texture)
GLES30.glUniform2i(location(program, "uImageSize"), width, height)
GLES30.glUniform1i(location(program, "uFactor"), factor)
}
var succeeded = false
try {
transfer.read(half.texture, lowWidth, lowHeight, label = "MGC bitmap low frequency") { mapped ->
succeeded = MgcFullResolutionDenoise.lowFrequencyChromaBitmap(
rgba16f = mapped,
lowWidth = lowWidth,
lowHeight = lowHeight,
fullWidth = width,
fullHeight = height,
log2Downsample = LOW_FREQUENCY_LOG2,
noiseModel = model.denoiserModel,
spatialStrengthQ8 = strengthMap,
tuningSnr = snr,
chromaStrengthScale = chroma,
)
}
check(succeeded) { "MGC bitmap low-frequency chroma failed for ${width}x$height" }
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
transfer.upload(half.texture, lowWidth, lowHeight)
} finally {
transfer.releaseBuffers()
}
return true
}
private fun encodeOutput(sourceTextureId: Int, width: Int, height: Int, lowFrequency: Boolean) {
draw("encode", ENCODE_SHADER, output, 0, 0, width, height) { program ->
bindTexture(program, "uLinear", 0, linear.texture)
bindTexture(program, "uSource", 1, sourceTextureId)
bindTexture(program, "uCorrection", 2, if (lowFrequency) half.texture else linear.texture)
GLES30.glUniform1i(location(program, "uApplyCorrection"), if (lowFrequency) 1 else 0)
GLES30.glUniform2i(location(program, "uCorrectionSize"), half.width, half.height)
GLES30.glUniform1i(location(program, "uFactor"), 1 shl LOW_FREQUENCY_LOG2)
}
}
private fun draw(
name: String,
shader: String,
target: Surface,
x: Int,
y: Int,
width: Int,
height: Int,
setup: (Int) -> Unit,
) {
val program = programs.getOrPut(name) {
quad.createProgram(shader, "BitmapMgc_$name").also {
check(it != 0) { "Bitmap MGC program $name failed to link" }
}
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer)
GLES30.glViewport(x, y, width, height)
GLES30.glUseProgram(program)
quad.bindIdentityTextureMatrix(program)
setup(program)
quad.draw(program)
}
private inline fun readHalves(surface: Surface, label: String, crossinline consume: (java.nio.ShortBuffer) -> Unit) {
try {
transfer.read(surface.texture, surface.width, surface.height, label = label, writable = false) {
consume(it.asShortBuffer())
}
} finally {
transfer.releaseBuffers()
}
}
private fun location(program: Int, name: String) = GLES30.glGetUniformLocation(program, name)
private fun bindTexture(program: Int, name: String, unit: Int, texture: Int) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glUniform1i(location(program, name), unit)
}
private fun ensureFullTextures(width: Int, height: Int) {
ensureSurface(linear, width, height)
ensureSurface(output, width, height)
}
private fun ensureTile(width: Int, height: Int) = ensureSurface(tile, width, height)
private fun ensureSurface(surface: Surface, width: Int, height: Int) {
if (surface.texture != 0 && surface.width == width && surface.height == height) return
releaseSurface(surface)
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[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)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, textures[0], 0,
)
check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"${surface.label} framebuffer is incomplete"
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
surface.texture = textures[0]
surface.framebuffer = framebuffers[0]
surface.width = width
surface.height = height
}
private fun releaseSurface(surface: Surface) {
if (surface.framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(surface.framebuffer), 0)
if (surface.texture != 0) GLES30.glDeleteTextures(1, intArrayOf(surface.texture), 0)
surface.framebuffer = 0
surface.texture = 0
surface.width = 0
surface.height = 0
}
private fun ShortArray.averageQ8(): String =
"%.3f".format(if (isEmpty()) 1.0 else sumOf { it.toInt() } / (size * 256.0))
companion object {
private const val TAG = "BitmapMgcDenoiser"
/** Tile core edge; with its apron a tile stays near 2.3k px (about 40 MiB of PBO). */
private const val TILE_CORE_PX = 2048
/** MGC pyramid reach, the same apron RAW tiles give the full-resolution denoise. */
private const val TILE_SUPPORT_PX = 112
private const val MEAN_GRID = 64
/** GCam's low-frequency chroma branch factor (2x): 4x drains small saturated detail. */
private const val LOW_FREQUENCY_LOG2 = 1
/** Spatial strength in confirmed structure (tools/bitmap_noise_calibration/experiments.py). */
private const val DETAIL_MIN_STRENGTH = 0.35f
/** Structure/noise variance ratio where protection starts and where it is complete. */
private const val DETAIL_LOW_EXCESS = 1.5f
private const val DETAIL_HIGH_EXCESS = 6f
// Sign-symmetric sRGB transfer, so extended-range (F16) values keep their sign.
private const val SRGB_TRANSFER = """
vec3 srgbDecode(vec3 encoded) {
vec3 magnitude = abs(encoded);
vec3 linear = mix(
magnitude / 12.92,
pow((magnitude + 0.055) / 1.055, vec3(2.4)),
step(vec3(0.04045), magnitude)
);
return sign(encoded) * linear;
}
vec3 srgbEncode(vec3 linear) {
vec3 magnitude = abs(linear);
vec3 encoded = mix(
magnitude * 12.92,
1.055 * pow(magnitude, vec3(1.0 / 2.4)) - 0.055,
step(vec3(0.0031308), magnitude)
);
return sign(linear) * encoded;
}
const vec3 MGC_LUMA = vec3(0.2125999927520752, 0.7152000069618225, 0.07219959795475006);
"""
// Prepended, not interpolated: #version must be the first line of the source.
private const val PREAMBLE = "#version 300 es\n" +
"precision highp float;\n" +
"precision highp int;\n" +
"in vec2 vTexCoord;\n" +
"out vec4 fragColor;\n"
private val DECODE_SHADER = PREAMBLE + """
uniform highp sampler2D uSource;
uniform ivec2 uSourceOffset;
$SRGB_TRANSFER
void main() {
ivec2 p = ivec2(gl_FragCoord.xy) + uSourceOffset;
fragColor = vec4(srgbDecode(texelFetch(uSource, p, 0).rgb), 1.0);
}
""".trimIndent()
private val COPY_CORE_SHADER = PREAMBLE + """
uniform highp sampler2D uTile;
uniform ivec2 uTileOrigin;
void main() {
fragColor = vec4(texelFetch(uTile, ivec2(gl_FragCoord.xy) - uTileOrigin, 0).rgb, 1.0);
}
""".trimIndent()
// Adds the low-frequency correction with AddUpsampledChromaCorrection's bilinear sampling.
private val ENCODE_SHADER = PREAMBLE + """
uniform highp sampler2D uLinear;
uniform highp sampler2D uSource;
uniform highp sampler2D uCorrection;
uniform int uApplyCorrection;
uniform ivec2 uCorrectionSize;
uniform int uFactor;
$SRGB_TRANSFER
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec3 linear = texelFetch(uLinear, p, 0).rgb;
if (uApplyCorrection != 0) {
vec2 l = clamp((vec2(p) + 0.5) / float(uFactor) - 0.5, vec2(0.0),
vec2(uCorrectionSize - ivec2(1)));
ivec2 p0 = ivec2(l);
ivec2 p1 = min(p0 + ivec2(1), uCorrectionSize - ivec2(1));
vec2 f = l - vec2(p0);
vec3 top = mix(texelFetch(uCorrection, p0, 0).rgb,
texelFetch(uCorrection, ivec2(p1.x, p0.y), 0).rgb, f.x);
vec3 bottom = mix(texelFetch(uCorrection, ivec2(p0.x, p1.y), 0).rgb,
texelFetch(uCorrection, p1, 0).rgb, f.x);
linear += mix(top, bottom, f.y);
}
fragColor = vec4(srgbEncode(linear), texelFetch(uSource, p, 0).a);
}
""".trimIndent()
// Mean decoded linear luma of each uFactor x uFactor block (partial edge blocks included).
private val BOX_LUMA_SHADER = PREAMBLE + """
uniform highp sampler2D uSource;
uniform ivec2 uImageSize;
uniform int uFactor;
$SRGB_TRANSFER
void main() {
ivec2 origin = ivec2(gl_FragCoord.xy) * uFactor;
ivec2 end = min(origin + ivec2(uFactor), uImageSize);
float sum = 0.0;
float count = 0.0;
for (int y = origin.y; y < end.y; ++y) {
for (int x = origin.x; x < end.x; ++x) {
sum += dot(srgbDecode(texelFetch(uSource, ivec2(x, y), 0).rgb), MGC_LUMA);
count += 1.0;
}
}
fragColor = vec4(sum / max(count, 1.0), 0.0, 0.0, 1.0);
}
""".trimIndent()
// Mean linear RGB of each uFactor x uFactor block of the denoised image.
private val BOX_RGB_SHADER = PREAMBLE + """
uniform highp sampler2D uLinear;
uniform ivec2 uImageSize;
uniform int uFactor;
void main() {
ivec2 origin = ivec2(gl_FragCoord.xy) * uFactor;
ivec2 end = min(origin + ivec2(uFactor), uImageSize);
vec3 sum = vec3(0.0);
float count = 0.0;
for (int y = origin.y; y < end.y; ++y) {
for (int x = origin.x; x < end.x; ++x) {
sum += texelFetch(uLinear, ivec2(x, y), 0).rgb;
count += 1.0;
}
}
fragColor = vec4(sum / max(count, 1.0), 1.0);
}
""".trimIndent()
// Per quarter-resolution cell: local 5x5 variance of the 2x and 4x luma blocks against the
// noise model scaled by its box variance ratio; their geometric mean is the structure
// excess, mapped smoothly from uDetail.y..uDetail.z (log) to strength 1..uDetail.x.
private val STRUCTURE_SHADER = PREAMBLE + """
uniform highp sampler2D uBox2;
uniform highp sampler2D uBox4;
uniform ivec2 uBox2Size;
uniform ivec2 uBox4Size;
uniform vec3 uLumaNoise;
uniform vec2 uBoxVarianceRatio;
uniform vec3 uDetail;
float noiseVariance(float signal) {
float s = max(signal, 0.0);
return uLumaNoise.x + uLumaNoise.y * s + uLumaNoise.z * s * s;
}
float excess(highp sampler2D boxes, ivec2 size, ivec2 center, float ratio) {
float sum = 0.0;
float sumSquares = 0.0;
for (int dy = -2; dy <= 2; ++dy) {
for (int dx = -2; dx <= 2; ++dx) {
ivec2 q = clamp(center + ivec2(dx, dy), ivec2(0), size - ivec2(1));
float value = texelFetch(boxes, q, 0).r;
sum += value;
sumSquares += value * value;
}
}
float mean = sum / 25.0;
float variance = max(sumSquares / 25.0 - mean * mean, 0.0);
return variance / max(noiseVariance(mean) * ratio, 1e-20);
}
void main() {
ivec2 cell = ivec2(gl_FragCoord.xy);
float excess4 = excess(uBox4, uBox4Size, cell, uBoxVarianceRatio.y);
float excess2 = 0.0;
for (int sy = 0; sy < 2; ++sy) {
for (int sx = 0; sx < 2; ++sx) {
ivec2 q = min(cell * 2 + ivec2(sx, sy), uBox2Size - ivec2(1));
excess2 += excess(uBox2, uBox2Size, q, uBoxVarianceRatio.x);
}
}
excess2 *= 0.25;
float structure = sqrt(excess2 * excess4);
float t = clamp((log(max(structure, 1e-6)) - uDetail.y) / (uDetail.z - uDetail.y), 0.0, 1.0);
float confidence = t * t * (3.0 - 2.0 * t);
fragColor = vec4(1.0 - confidence * (1.0 - uDetail.x), 0.0, 0.0, 1.0);
}
""".trimIndent()
// r: mean linear luma of the cell (MGC RGB->YUV row 0); g: covered fraction of the cell.
private val MEAN_SHADER = PREAMBLE + """
uniform highp sampler2D uSource;
uniform ivec2 uImageSize;
uniform ivec2 uCellSize;
$SRGB_TRANSFER
void main() {
ivec2 origin = ivec2(gl_FragCoord.xy) * uCellSize;
ivec2 end = min(origin + uCellSize, uImageSize);
float sum = 0.0;
float count = 0.0;
for (int y = origin.y; y < end.y; ++y) {
for (int x = origin.x; x < end.x; ++x) {
sum += dot(srgbDecode(texelFetch(uSource, ivec2(x, y), 0).rgb), MGC_LUMA);
count += 1.0;
}
}
float area = float(uCellSize.x * uCellSize.y);
fragColor = vec4(count > 0.0 ? sum / count : 0.0, count / area, 0.0, 1.0);
}
""".trimIndent()
}
}
@@ -4,43 +4,8 @@ import com.hinnka.mycamera.processor.DenoiseStrength
object ChromaDenoiseDefaults {
const val RAW_CAPTURE_DEFAULT_STRENGTH = 0.0f
private const val MIN_ACTIVE_NOISE_BANDWIDTH = 1.0f
private const val STRENGTH_ONE_NOISE_BANDWIDTH = 8.0f
private const val FULL_OUTPUT_STRENGTH_POINT = 0.5f
private const val EDGE_GUIDANCE_START_POINT = 0.75f
fun forRawCapture(requested: Float): Float = DenoiseStrength.clamp(
maxOf(requested, RAW_CAPTURE_DEFAULT_STRENGTH)
)
/**
* Keeps the bilateral kernel wide enough to recognize noise at every active
* slider value. Once output mixing reaches full strength, the remaining slider
* range continues widening chroma similarity. Strength 2 therefore extends the
* noise bandwidth beyond the former strength-1 endpoint instead of saturating.
*/
fun noiseBandwidth(strength: Float): Float {
val clamped = DenoiseStrength.clamp(strength)
if (clamped <= 0f) return 0f
return MIN_ACTIVE_NOISE_BANDWIDTH +
clamped * (STRENGTH_ONE_NOISE_BANDWIDTH - MIN_ACTIVE_NOISE_BANDWIDTH)
}
/** Smoothly reaches full filter output at strength 0.5. */
fun outputStrength(strength: Float): Float {
val t = (DenoiseStrength.clamp(strength) / FULL_OUTPUT_STRENGTH_POINT)
.coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
/**
* Uses strict edge rejection through the lower part of the slider. Above 0.75
* the guide is relaxed smoothly so stronger settings can cross weak or noisy
* pseudo-edges and establish enough support for dense chroma noise.
*/
fun edgeGuidanceRelaxation(strength: Float): Float {
val t = ((DenoiseStrength.clamp(strength) - EDGE_GUIDANCE_START_POINT) /
(1f - EDGE_GUIDANCE_START_POINT)).coerceIn(0f, 1f)
return t * t * (3f - 2f * t)
}
}
@@ -1,293 +0,0 @@
package com.hinnka.mycamera.lut
/**
* Shared multi-scale edge-guided chroma denoise shader.
*
* RAW input is filtered in linear camera RGB opponent space before white
* balance and color conversion. Bitmap input retains its luma/chroma transform.
* Both paths use a prefiltered luminance guide. RAW luminance is the symmetric
* camera-RGB mean; bitmap luminance retains its display-space coefficients.
*/
object ChromaDenoiseShaders {
val PASS_EDGE_GUIDE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform int uCameraRgbInput;
float guideSignal(vec3 rgb) {
if (uCameraRgbInput != 0) {
return (rgb.r + rgb.g + rgb.b) / 3.0;
}
return dot(rgb, vec3(0.2126, 0.7152, 0.0722));
}
float guideAt(vec2 coord) {
return guideSignal(texture(uInputTexture, coord).rgb);
}
void main() {
float guide = guideAt(vTexCoord) * 0.5;
guide += guideAt(vTexCoord + vec2( uTexelSize.x, 0.0)) * 0.125;
guide += guideAt(vTexCoord + vec2(-uTexelSize.x, 0.0)) * 0.125;
guide += guideAt(vTexCoord + vec2(0.0, uTexelSize.y)) * 0.125;
guide += guideAt(vTexCoord + vec2(0.0, -uTexelSize.y)) * 0.125;
fragColor = vec4(guide, 0.0, 0.0, 1.0);
}
""".trimIndent()
val PASS_CHROMA_DENOISE = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform sampler2D uGuideTexture;
uniform vec2 uTexelSize;
uniform float uH;
uniform float uOutputStrength;
uniform float uEdgeGuidanceRelaxation;
uniform int uCameraRgbInput;
// Camera-domain variance models. RB order is
// [red slope, red offset, blue slope, blue offset].
uniform vec4 uNoiseModelRB;
// [green slope, green offset].
uniform vec2 uNoiseModelG;
vec3 rgb2ycbcr(vec3 rgb) {
float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
return vec3(y,
dot(rgb, vec3(-0.114572, -0.385428, 0.5 )),
dot(rgb, vec3( 0.5, -0.454153, -0.045847)));
}
vec3 ycbcr2rgb(vec3 yuv) {
return vec3(yuv.x + 1.5748 * yuv.z,
yuv.x - 0.187324 * yuv.y - 0.468124 * yuv.z,
yuv.x + 1.8556 * yuv.y);
}
vec3 channelNoiseVariance(vec3 rgb) {
return max(
vec3(
uNoiseModelRB.x * max(rgb.r, 0.0) + uNoiseModelRB.y,
uNoiseModelG.x * max(rgb.g, 0.0) + uNoiseModelG.y,
uNoiseModelRB.z * max(rgb.b, 0.0) + uNoiseModelRB.w
),
vec3(1e-10)
);
}
vec3 rgbToFilterSpace(vec3 rgb) {
if (uCameraRgbInput != 0) {
// Keep every sample in one linear camera-RGB coordinate system.
// Exposure invariance is restored after each weighted mean, not
// by averaging unstable per-pixel ratios in the shadows.
return vec3(
(rgb.r + rgb.g + rgb.b) / 3.0,
rgb.r - rgb.g,
rgb.b - rgb.g
);
}
return rgb2ycbcr(rgb);
}
vec3 filterSpaceToRgb(vec3 value) {
if (uCameraRgbInput != 0) {
// value.x is the symmetric camera-RGB mean, not green. Recover
// the three channels from mean, R-G and B-G without giving any
// channel a privileged luminance role.
float green = value.x - (value.y + value.z) / 3.0;
return max(
vec3(
green + value.y,
green,
green + value.z
),
vec3(0.0)
);
}
return ycbcr2rgb(value);
}
vec2 chromaNoiseSigma(vec3 rgb) {
vec3 variance = channelNoiseVariance(rgb);
if (uCameraRgbInput != 0) {
// Var(R-G) = Var(R) + Var(G), likewise for B-G.
return sqrt(max(variance.rb + variance.gg, vec2(1e-10)));
}
const vec3 cb = vec3(-0.114572, -0.385428, 0.5);
const vec3 cr = vec3(0.5, -0.454153, -0.045847);
return sqrt(max(
vec2(dot(cb * cb, variance), dot(cr * cr, variance)),
vec2(1e-10)
));
}
float guideNoiseSigma(vec3 rgb) {
vec3 variance = channelNoiseVariance(rgb);
if (uCameraRgbInput != 0) {
return sqrt(max((variance.r + variance.g + variance.b) / 9.0, 1e-10));
}
const vec3 luma = vec3(0.2126, 0.7152, 0.0722);
return sqrt(max(dot(luma * luma, variance), 1e-10));
}
void filterScale(
float radius,
float centerGuide,
float centerSignal,
vec2 baseChroma,
vec2 chromaGuide,
float invGuideH2,
vec2 invChromaH2,
out vec2 filteredChroma,
out float edgeSupport
) {
// The center estimate anchors each wider scale and prevents a sparse
// coarse neighborhood from replacing a small valid color feature.
vec2 sumChroma = baseChroma;
float sumSignal = centerSignal;
float sumWeight = 1.0;
float acceptedLumaSupport = 0.0;
float totalSupport = 0.0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (x == 0 && y == 0) continue;
vec2 gridOffset = vec2(float(x), float(y));
float distance2 = dot(gridOffset, gridOffset);
float spatialWeight = exp(-0.72 * distance2);
vec2 offset = gridOffset * uTexelSize * radius;
vec2 sampleCoord = vTexCoord + offset;
vec3 sampleValue = rgbToFilterSpace(
texture(uInputTexture, sampleCoord).rgb
);
float guideDelta =
texture(uGuideTexture, sampleCoord).r - centerGuide;
float guideWeight =
exp(-(guideDelta * guideDelta) * invGuideH2);
vec2 chromaDelta = sampleValue.yz - chromaGuide;
float chromaDistance =
dot(chromaDelta * chromaDelta, invChromaH2);
float chromaWeight = exp(-chromaDistance);
float weight = spatialWeight * guideWeight * chromaWeight;
sumChroma += sampleValue.yz * weight;
sumSignal += sampleValue.x * weight;
sumWeight += weight;
acceptedLumaSupport += spatialWeight * guideWeight;
totalSupport += spatialWeight;
}
}
vec2 averageChroma = sumChroma / max(sumWeight, 1e-6);
if (uCameraRgbInput != 0) {
// averageChroma is the opponent component of the weighted RGB
// mean. Scale that mean back to the center RGB mean so exposure
// differences in sparse/coarse samples cannot turn into color.
// This ratio-of-means is stable in shadows and exactly preserves
// a constant camera chromaticity across an exposure gradient.
float averageSignal = sumSignal / max(sumWeight, 1e-6);
float signalScale = centerSignal / max(averageSignal, 1e-6);
filteredChroma = averageChroma * signalScale;
} else {
filteredChroma = averageChroma;
}
// Support reflects the shared luminance guide in both input domains.
edgeSupport = acceptedLumaSupport / max(totalSupport, 1e-6);
}
float featheredEdgeSupport(float support, float exponent) {
return pow(clamp(support, 0.0, 1.0), exponent);
}
void main() {
vec4 source = texture(uInputTexture, vTexCoord);
if (uH <= 0.00001) {
fragColor = source;
return;
}
vec3 centerValue = rgbToFilterSpace(source.rgb);
vec2 noiseSigma = chromaNoiseSigma(source.rgb);
float centerGuide = texture(uGuideTexture, vTexCoord).r;
float guideSigma = guideNoiseSigma(source.rgb);
float guideBandwidthScale =
mix(1.0, 4.0, uEdgeGuidanceRelaxation);
float guideH =
guideSigma * 4.0 * guideBandwidthScale;
float invGuideH2 = 1.0 / max(guideH * guideH, 1e-8);
// Denoise strength may relax the range threshold slightly, but every
// spatial scale shares the same bounded color-edge bandwidth. Large
// radii must never gain permission to cross a red/blue boundary.
float strengthT = clamp((uH - 1.0) / 7.0, 0.0, 1.0);
float chromaEdgeSigmaMultiplier = mix(2.75, 3.5, strengthT);
vec2 chromaEdgeH =
max(noiseSigma * chromaEdgeSigmaMultiplier, vec2(1e-5));
vec2 invChromaEdgeH2 =
1.0 / max(chromaEdgeH * chromaEdgeH, vec2(1e-8));
vec2 fineCandidate;
float fineSupport;
// Radius one directly covers the one-to-two-pixel sensor grain that
// was skipped by the previous sparse fine scale.
filterScale(
1.0,
centerGuide,
centerValue.x,
centerValue.yz,
centerValue.yz,
invGuideH2,
invChromaEdgeH2,
fineCandidate,
fineSupport
);
vec2 fineChroma =
mix(centerValue.yz, fineCandidate, uOutputStrength);
vec2 mediumCandidate;
float mediumSupport;
filterScale(
4.0,
centerGuide,
centerValue.x,
fineChroma,
fineChroma,
invGuideH2,
invChromaEdgeH2,
mediumCandidate,
mediumSupport
);
float mediumMix =
uOutputStrength * featheredEdgeSupport(mediumSupport, 1.5);
vec2 mediumChroma = mix(fineChroma, mediumCandidate, mediumMix);
vec2 coarseCandidate;
float coarseSupport;
filterScale(
14.0,
centerGuide,
centerValue.x,
mediumChroma,
mediumChroma,
invGuideH2,
invChromaEdgeH2,
coarseCandidate,
coarseSupport
);
float coarseMix =
uOutputStrength * featheredEdgeSupport(coarseSupport, 2.0);
vec2 coarseChroma = mix(mediumChroma, coarseCandidate, coarseMix);
centerValue.yz = coarseChroma;
fragColor = vec4(filterSpaceToRgb(centerValue), source.a);
}
""".trimIndent()
}
@@ -12,11 +12,8 @@ import android.opengl.GLES30
import android.opengl.GLES31
import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.lut.ChromaDenoiseShaders
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import com.hinnka.mycamera.processor.DenoiseStrength
import com.hinnka.mycamera.raw.DenoiseProfileNlmConfig
import com.hinnka.mycamera.raw.DenoiseProfileShaders
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.asCoroutineDispatcher
@@ -84,24 +81,9 @@ class LutImageProcessor(context: Context? = null) {
private var texCoordBuffer: FloatBuffer? = null
private var indexBuffer: ShortBuffer? = null
private var bitmapDenoisePreconditionProgram = 0
private var bitmapDenoiseNlmInitProgram = 0
private var bitmapDenoiseNlmFusedAccuProgram = 0
private var bitmapDenoiseNlmFinishProgram = 0
private var bitmapDenoisePassthroughProgram = 0
private var computeCapabilitiesChecked = false
private var computeCapabilitiesSupported = false
private var bitmapChromaDenoiseGuideProgram = 0
private var bitmapChromaDenoiseProgram = 0
private val bitmapMgcDenoiser = BitmapMgcDenoiser()
private var lutSharpenProgram = 0
private var lutLuminanceGainProgram = 0
private val bitmapDenoiseTexId = IntArray(2)
private val bitmapDenoiseFboId = IntArray(2)
private var bitmapDenoiseNlmU2BufferId = 0
private var bitmapDenoiseNlmBufferPixels = 0
private var bitmapDenoiseWidth = 0
private var bitmapDenoiseHeight = 0
private var lutSharpenTextureId = 0
private var lutSharpenFboId = 0
private var lutSharpenWidth = 0
@@ -311,8 +293,6 @@ class LutImageProcessor(context: Context? = null) {
* @param argbData RGBA 16-bit 格式的像素数据 (ShortBuffer) [width, height, r1, g1, b1, a1, ...]
* @param lutConfig LUT 配置
* @param colorRecipeParams 色彩配方参数
* @param noiseReductionValue 降噪强度
* @param chromaNoiseReductionValue 减少杂色强度
*/
suspend fun applyLut(
argbData: ShortBuffer,
@@ -321,8 +301,6 @@ class LutImageProcessor(context: Context? = null) {
colorSpace: ColorSpace,
lutConfig: LutConfig?,
colorRecipeParams: ColorRecipeParams?,
noiseReductionValue: Float = 0f,
chromaNoiseReductionValue: Float = 0f,
lutMaskType: Int = 0,
): Bitmap = withContext(glDispatcher) {
currentCoroutineContext().ensureActive()
@@ -339,9 +317,6 @@ class LutImageProcessor(context: Context? = null) {
// 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。
val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f
val noiseReduction: Float = noiseReductionValue
val chromaNoiseReduction: Float = chromaNoiseReductionValue
val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction)
// 激活上下文
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
@@ -354,15 +329,13 @@ class LutImageProcessor(context: Context? = null) {
uploadImageTextureFromArgb(argbData, width, height)
currentCoroutineContext().ensureActive()
val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, noiseReduction, chromaDenoiseStrength)
currentCoroutineContext().ensureActive()
// 上传 LUT 纹理
if (lutConfig != null) {
uploadLutTexture(lutConfig)
}
val inputTexId = denoisedTexId
val inputTexId = imageTextureId
// HDF 光晕效果预处理(在主 shader 之前,需要模糊的光晕纹理)
if (halation > 0f) {
@@ -395,8 +368,6 @@ class LutImageProcessor(context: Context? = null) {
colorSpace: ColorSpace,
baselineLayer: LutRenderLayer?,
creativeLayer: LutRenderLayer?,
noiseReductionValue: Float = 0f,
chromaNoiseReductionValue: Float = 0f,
): Bitmap {
val hasBaseline = baselineLayer?.lutConfig != null || baselineLayer?.colorRecipeParams != null
val hasCreative = creativeLayer?.lutConfig != null || creativeLayer?.colorRecipeParams != null
@@ -408,16 +379,12 @@ class LutImageProcessor(context: Context? = null) {
height = height,
colorSpace = colorSpace,
lutConfig = baselineLayer.lutConfig,
colorRecipeParams = baselineLayer.colorRecipeParams,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f,
colorRecipeParams = baselineLayer.colorRecipeParams
)
applyLut(
bitmap = baseBitmap,
lutConfig = creativeLayer.lutConfig,
colorRecipeParams = creativeLayer.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = creativeLayer.colorRecipeParams
)
}
hasBaseline -> applyLut(
@@ -426,9 +393,7 @@ class LutImageProcessor(context: Context? = null) {
height = height,
colorSpace = colorSpace,
lutConfig = baselineLayer.lutConfig,
colorRecipeParams = baselineLayer.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = baselineLayer.colorRecipeParams
)
else -> applyLut(
argbData = argbData,
@@ -436,9 +401,7 @@ class LutImageProcessor(context: Context? = null) {
height = height,
colorSpace = colorSpace,
lutConfig = creativeLayer?.lutConfig,
colorRecipeParams = creativeLayer?.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = creativeLayer?.colorRecipeParams
)
}
}
@@ -449,15 +412,11 @@ class LutImageProcessor(context: Context? = null) {
* @param bitmap 输入图片
* @param lutConfig LUT 配置
* @param colorRecipeParams 色彩配方参数
* @param noiseReductionValue 降噪强度
* @param chromaNoiseReductionValue 减少杂色强度
*/
suspend fun applyLut(
bitmap: Bitmap,
lutConfig: LutConfig?,
colorRecipeParams: ColorRecipeParams?,
noiseReductionValue: Float = 0f,
chromaNoiseReductionValue: Float = 0f,
lutMaskType: Int = 0,
): Bitmap = withContext(glDispatcher) {
currentCoroutineContext().ensureActive()
@@ -473,9 +432,6 @@ class LutImageProcessor(context: Context? = null) {
// 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。
val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f
val noiseReduction: Float = noiseReductionValue
val chromaNoiseReduction: Float = chromaNoiseReductionValue
val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction)
// 确保上下文激活
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
@@ -491,15 +447,13 @@ class LutImageProcessor(context: Context? = null) {
uploadImageTexture(bitmap)
currentCoroutineContext().ensureActive()
val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, noiseReduction, chromaDenoiseStrength)
currentCoroutineContext().ensureActive()
// 上传 LUT 纹理
if (lutConfig != null) {
uploadLutTexture(lutConfig)
}
val inputTexId = denoisedTexId
val inputTexId = imageTextureId
val renderColorSpace = bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB)
// HDF 光晕效果预处理
@@ -530,8 +484,6 @@ class LutImageProcessor(context: Context? = null) {
bitmap: Bitmap,
baselineLayer: LutRenderLayer?,
creativeLayer: LutRenderLayer?,
noiseReductionValue: Float = 0f,
chromaNoiseReductionValue: Float = 0f,
): Bitmap {
val hasBaseline = baselineLayer?.lutConfig != null || baselineLayer?.colorRecipeParams != null
val hasCreative = creativeLayer?.lutConfig != null || creativeLayer?.colorRecipeParams != null
@@ -540,31 +492,23 @@ class LutImageProcessor(context: Context? = null) {
val baseBitmap = applyLut(
bitmap = bitmap,
lutConfig = baselineLayer.lutConfig,
colorRecipeParams = baselineLayer.colorRecipeParams,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f,
colorRecipeParams = baselineLayer.colorRecipeParams
)
applyLut(
bitmap = baseBitmap,
lutConfig = creativeLayer.lutConfig,
colorRecipeParams = creativeLayer.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = creativeLayer.colorRecipeParams
)
}
hasBaseline -> applyLut(
bitmap = bitmap,
lutConfig = baselineLayer.lutConfig,
colorRecipeParams = baselineLayer.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = baselineLayer.colorRecipeParams
)
else -> applyLut(
bitmap = bitmap,
lutConfig = creativeLayer?.lutConfig,
colorRecipeParams = creativeLayer?.colorRecipeParams,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue
colorRecipeParams = creativeLayer?.colorRecipeParams
)
}
}
@@ -578,16 +522,12 @@ class LutImageProcessor(context: Context? = null) {
bitmap: Bitmap,
baselineLayer: LutRenderLayer?,
creativeLayer: LutRenderLayer?,
noiseReductionValue: Float = 0f,
chromaNoiseReductionValue: Float = 0f,
luminanceGainDownsample: Int = 1,
): LutStackRenderResult {
val rendered = applyLutStack(
bitmap = bitmap,
baselineLayer = baselineLayer,
creativeLayer = creativeLayer,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue,
creativeLayer = creativeLayer
)
val luminanceGainMap = if (!bitmap.colorSpace.isEncodedSrgbFamily() ||
!rendered.colorSpace.isEncodedSrgbFamily()
@@ -741,14 +681,18 @@ class LutImageProcessor(context: Context? = null) {
if (uploadBitmap !== bitmap) uploadBitmap.recycle()
}
suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float = 0.1f): Bitmap =
applyBitmapDenoise(bitmap, 0f, strength)
suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float, sensorIso: Int?): Bitmap =
applyBitmapDenoise(bitmap, 0f, strength, sensorIso)
/** Bitmap 降噪(不含 LUT/配方):色度降噪 + NLM 亮度降噪,两个强度都为 0 时原样返回。 */
/**
* Bitmap 降噪(不含 LUT/配方):MGC 亮度/色度降噪,两个强度都为 0 时原样返回。
* [sensorIso] 为拍摄 ISO(元数据/EXIF),选择对应的噪声模型;未知时为 null。
*/
suspend fun applyBitmapDenoise(
bitmap: Bitmap,
lumaStrength: Float,
chromaStrength: Float,
sensorIso: Int?,
): Bitmap = withContext(glDispatcher) {
currentCoroutineContext().ensureActive()
val luma = DenoiseStrength.clamp(lumaStrength)
@@ -767,7 +711,7 @@ class LutImageProcessor(context: Context? = null) {
setupFramebuffer(width, height)
uploadImageTexture(bitmap)
val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, luma, chroma)
val denoisedTexId = renderBitmapDenoise(width, height, luma, chroma, sensorIso)
performRender(
width = width,
height = height,
@@ -1328,77 +1272,34 @@ class LutImageProcessor(context: Context? = null) {
)
}
private fun ensureBitmapDenoiseProfilePrograms() {
if (!computeCapabilitiesChecked) {
computeCapabilitiesSupported = logAndValidateComputeCapabilities()
computeCapabilitiesChecked = true
/**
* MGC luma/chroma denoise of the uploaded image ([imageTextureId]); returns the texture the
* render consumes: the denoiser's output, or [imageTextureId] when both strengths are zero.
*/
private fun renderBitmapDenoise(
width: Int,
height: Int,
lumaStrength: Float,
chromaStrength: Float,
sensorIso: Int?,
): Int {
if (DenoiseStrength.clamp(lumaStrength) <= 0f && DenoiseStrength.clamp(chromaStrength) <= 0f) {
return imageTextureId
}
if (!computeCapabilitiesSupported) {
ensureBitmapDenoisePassthroughProgram()
return
val context = checkNotNull(appContext) {
"Bitmap MGC denoise requires the LutImageProcessor application context"
}
if (bitmapDenoisePreconditionProgram == 0) {
bitmapDenoisePreconditionProgram = compileComputeProgram(
DenoiseProfileShaders.PRECONDITION_V2,
"BitmapDenoise_PreconditionV2",
)
}
if (bitmapDenoiseNlmInitProgram == 0) {
bitmapDenoiseNlmInitProgram = compileComputeProgram(
DenoiseProfileShaders.INIT,
"BitmapDenoise_NLM_Init",
)
}
if (bitmapDenoiseNlmFusedAccuProgram == 0) {
bitmapDenoiseNlmFusedAccuProgram = compileComputeProgram(
DenoiseProfileShaders.FUSED_ACCU,
"BitmapDenoise_NLM_FusedAccu",
)
}
if (bitmapDenoiseNlmFinishProgram == 0) {
bitmapDenoiseNlmFinishProgram = compileComputeProgram(
DenoiseProfileShaders.FINISH_V2,
"BitmapDenoise_NLM_FinishV2",
)
}
ensureBitmapDenoisePassthroughProgram()
PLog.d(
TAG,
"Bitmap denoiseprofile programs initialized: pre=$bitmapDenoisePreconditionProgram " +
"init=$bitmapDenoiseNlmInitProgram fusedAccu=$bitmapDenoiseNlmFusedAccuProgram " +
"finish=$bitmapDenoiseNlmFinishProgram " +
"pass=$bitmapDenoisePassthroughProgram"
return bitmapMgcDenoiser.denoise(
context = context,
sourceTextureId = imageTextureId,
width = width,
height = height,
lumaStrength = lumaStrength,
chromaStrength = chromaStrength,
sensorIso = sensorIso,
)
}
private fun ensureBitmapDenoisePassthroughProgram() {
if (bitmapDenoisePassthroughProgram == 0) {
bitmapDenoisePassthroughProgram = createFragmentProgram(
IMAGE_VERTEX_SHADER,
TEXTURE_PASSTHROUGH_SHADER,
"BitmapDenoise_Passthrough",
)
}
}
private fun ensureBitmapChromaDenoisePrograms() {
ensureBitmapDenoisePassthroughProgram()
if (bitmapChromaDenoiseGuideProgram == 0) {
bitmapChromaDenoiseGuideProgram = createFragmentProgram(
IMAGE_VERTEX_SHADER,
ChromaDenoiseShaders.PASS_EDGE_GUIDE,
"BitmapChromaDenoise_EdgeGuide",
)
}
if (bitmapChromaDenoiseProgram == 0) {
bitmapChromaDenoiseProgram = createFragmentProgram(
IMAGE_VERTEX_SHADER,
ChromaDenoiseShaders.PASS_CHROMA_DENOISE,
"BitmapChromaDenoise_MultiScale",
)
}
}
private fun ensureLutSharpenProgram() {
if (lutSharpenProgram == 0) {
lutSharpenProgram = createFragmentProgram(
@@ -1463,245 +1364,6 @@ class LutImageProcessor(context: Context? = null) {
)
}
private fun setupBitmapDenoiseFramebuffers(width: Int, height: Int) {
if (bitmapDenoiseWidth == width && bitmapDenoiseHeight == height && bitmapDenoiseTexId[0] != 0) return
bitmapDenoiseWidth = width
bitmapDenoiseHeight = height
for (i in 0..1) {
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 0..1) {
val t = IntArray(1)
val f = 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)
GLES30.glGenFramebuffers(1, f, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
t[0],
0
)
bitmapDenoiseTexId[i] = t[0]
bitmapDenoiseFboId[i] = f[0]
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(TAG, "Bitmap denoiseprofile FBO $i incomplete: $status")
}
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
/**
* 色度降噪(写入 bitmapDenoiseTexId[0])后接 NLM 亮度降噪(写入 bitmapDenoiseTexId[1]),
* 返回降噪结果所在纹理;两个强度都为 0 时返回 [sourceTextureId]。
*/
private fun renderBitmapDenoise(
sourceTextureId: Int,
width: Int,
height: Int,
lumaStrength: Float,
chromaStrength: Float,
): Int {
var current = sourceTextureId
if (chromaStrength > 0f) {
renderBitmapChromaDenoise(current, width, height, chromaStrength)
current = bitmapDenoiseTexId[0]
}
if (lumaStrength > 0f) {
renderBitmapDenoiseProfile(current, width, height, lumaStrength)
current = bitmapDenoiseTexId[1]
}
return current
}
private fun renderBitmapDenoiseProfile(
sourceTextureId: Int,
width: Int,
height: Int,
noiseReduction: Float
) {
ensureBitmapDenoiseProfilePrograms()
setupBitmapDenoiseFramebuffers(width, height)
val strength = DenoiseStrength.clamp(noiseReduction)
if (strength <= 0f || width * height < 2) {
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
return
}
if (!isBitmapDenoiseProfileReady()) {
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height)
return
}
setupBitmapDenoiseResources(width, height)
val preconditionTextureId = if (sourceTextureId == bitmapDenoiseTexId[0]) {
bitmapDenoiseTexId[1]
} else {
bitmapDenoiseTexId[0]
}
val params = buildBitmapDenoiseParams(strength)
dispatchBitmapDenoisePreconditionV2(sourceTextureId, preconditionTextureId, width, height, params)
dispatchBitmapDenoiseNlm(sourceTextureId, preconditionTextureId, bitmapDenoiseTexId[1], width, height, params)
checkGlError("renderBitmapDenoiseProfile")
}
private fun renderBitmapChromaDenoise(
sourceTextureId: Int,
width: Int,
height: Int,
chromaNoiseReduction: Float,
targetIndex: Int = 0
) {
ensureBitmapChromaDenoisePrograms()
setupBitmapDenoiseFramebuffers(width, height)
val strength = DenoiseStrength.clamp(chromaNoiseReduction)
val target = targetIndex.coerceIn(0, bitmapDenoiseTexId.lastIndex)
val edgeGuidanceRelaxation =
ChromaDenoiseDefaults.edgeGuidanceRelaxation(strength)
if (strength <= 0f || bitmapChromaDenoiseProgram == 0 ||
bitmapChromaDenoiseGuideProgram == 0
) {
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[target], width, height)
return
}
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
val h = ChromaDenoiseDefaults.noiseBandwidth(strength)
val guideIndex = if (target == 0) 1 else 0
renderBitmapChromaDenoiseEdgeGuide(
sourceTextureId,
bitmapDenoiseFboId[guideIndex],
width,
height
)
val guideTextureId = bitmapDenoiseTexId[guideIndex]
GLES30.glUseProgram(bitmapChromaDenoiseProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bitmapDenoiseFboId[target])
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, guideTextureId)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uGuideTexture"),
1
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uTexelSize"),
1.0f / width,
1.0f / height
)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uOutputStrength"),
ChromaDenoiseDefaults.outputStrength(strength)
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(
bitmapChromaDenoiseProgram,
"uEdgeGuidanceRelaxation"
),
edgeGuidanceRelaxation
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uCameraRgbInput"),
0
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uH"), h)
GLES30.glUniform4f(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelRB"),
BITMAP_DENOISE_A * 2f,
BITMAP_DENOISE_B * 2f,
BITMAP_DENOISE_A * 2f,
BITMAP_DENOISE_B * 2f
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelG"),
BITMAP_DENOISE_A * 2f,
BITMAP_DENOISE_B * 2f
)
drawQuad(bitmapChromaDenoiseProgram)
checkGlError("renderBitmapChromaDenoise")
}
private fun renderBitmapChromaDenoiseEdgeGuide(
sourceTextureId: Int,
targetFramebufferId: Int,
width: Int,
height: Int,
) {
GLES30.glUseProgram(bitmapChromaDenoiseGuideProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebufferId)
GLES30.glViewport(0, 0, width, height)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uInputTexture"),
0
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uTexelSize"),
1.0f / width,
1.0f / height
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uCameraRgbInput"),
0
)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
drawQuad(bitmapChromaDenoiseGuideProgram)
checkGlError("renderBitmapChromaDenoiseEdgeGuide")
}
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(bitmapDenoisePassthroughProgram, "uInputTexture"), 0)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(bitmapDenoisePassthroughProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
drawQuad(bitmapDenoisePassthroughProgram)
}
private fun setupLutSharpenFramebuffer(width: Int, height: Int): Boolean {
if (lutSharpenFboId != 0 &&
lutSharpenTextureId != 0 &&
@@ -1828,220 +1490,6 @@ class LutImageProcessor(context: Context? = null) {
lutSharpenHeight = 0
}
private data class BitmapDenoiseParams(
val strength: Float,
val patchRadius: Int,
val expectedFineDistance: Float,
val expectedGuideDistance: Float,
val inverseBandwidth: Float,
val coarseGuideWeight: Float,
val centralPixelWeight: Float,
val p: FloatArray,
val signalScale: FloatArray,
val aa: FloatArray,
val bb: FloatArray,
val bias: Float,
val scale: Float
)
private fun isBitmapDenoiseProfileReady(): Boolean {
return bitmapDenoisePreconditionProgram != 0 &&
bitmapDenoiseNlmInitProgram != 0 &&
bitmapDenoiseNlmFusedAccuProgram != 0 &&
bitmapDenoiseNlmFinishProgram != 0 &&
bitmapDenoisePassthroughProgram != 0
}
private fun setupBitmapDenoiseResources(width: Int, height: Int) {
val pixelCount = width * height
if (
bitmapDenoiseNlmBufferPixels == pixelCount &&
bitmapDenoiseNlmU2BufferId != 0
) {
return
}
if (bitmapDenoiseNlmU2BufferId != 0) {
GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0)
bitmapDenoiseNlmU2BufferId = 0
}
val buffers = IntArray(1)
GLES31.glGenBuffers(buffers.size, buffers, 0)
bitmapDenoiseNlmU2BufferId = buffers[0]
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseNlmU2BufferId)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, pixelCount * 4 * 4, null, GLES31.GL_DYNAMIC_DRAW)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
bitmapDenoiseNlmBufferPixels = pixelCount
}
private fun buildBitmapDenoiseParams(strengthValue: Float): BitmapDenoiseParams {
val strength = DenoiseStrength.clamp(strengthValue)
val varianceScale = DenoiseStrength.noiseVarianceScale(strength)
val a = BITMAP_DENOISE_A * varianceScale
val b = BITMAP_DENOISE_B * varianceScale
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 patchRadius = DenoiseProfileShaders.PATCH_RADIUS
val weightTuning = DenoiseProfileNlmConfig.weightTuning(patchRadius)
val centralPixelWeight = 0.1f * scale
return BitmapDenoiseParams(
strength = DenoiseStrength.outputMix(strength),
patchRadius = patchRadius,
expectedFineDistance = weightTuning.expectedFineDistance,
expectedGuideDistance = weightTuning.expectedGuideDistance,
inverseBandwidth = weightTuning.inverseBandwidth,
coarseGuideWeight = weightTuning.coarseGuideWeight,
centralPixelWeight = centralPixelWeight,
p = floatArrayOf(shadows, shadows, shadows, 1.0f),
signalScale = floatArrayOf(
scale,
scale,
scale,
1.0f
),
aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1.0f),
bb = floatArrayOf(b, b, b, 1.0f),
bias = bias,
scale = scale
)
}
private fun dispatchBitmapDenoisePreconditionV2(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)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM precondition")
}
private fun dispatchBitmapDenoiseNlm(
originalTextureId: Int,
preconditionedTextureId: Int,
outputTextureId: Int,
width: Int,
height: Int,
params: BitmapDenoiseParams
) {
dispatchBitmapDenoiseNlmInit(width, height)
for (offset in DenoiseProfileNlmConfig.searchOffsets) {
dispatchBitmapDenoiseNlmFusedAccumulate(
preconditionedTextureId,
width,
height,
offset.x,
offset.y,
params
)
}
dispatchBitmapDenoiseNlmFinish(originalTextureId, outputTextureId, width, height, params)
}
private fun dispatchBitmapDenoiseNlmInit(width: Int, height: Int) {
GLES31.glUseProgram(bitmapDenoiseNlmInitProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmInitProgram, "uImageSize"), width, height)
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmInitProgram, height)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM init")
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
}
private fun dispatchBitmapDenoiseNlmFusedAccumulate(
input: Int,
width: Int,
height: Int,
qx: Int,
qy: Int,
params: BitmapDenoiseParams
) {
GLES31.glUseProgram(bitmapDenoiseNlmFusedAccuProgram)
bindComputeSampler(bitmapDenoiseNlmFusedAccuProgram, "uInput", 0, input)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uImageSize"), width, height)
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFusedAccuProgram, height)
GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uQ"), qx, qy)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedFineDistance"),
params.expectedFineDistance
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedGuideDistance"),
params.expectedGuideDistance
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uInverseBandwidth"),
params.inverseBandwidth
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCoarseGuideWeight"),
params.coarseGuideWeight
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCentralPixelWeight"),
params.centralPixelWeight
)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM fused accu q=($qx,$qy)")
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
}
private fun dispatchBitmapDenoiseNlmFinish(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) {
GLES31.glUseProgram(bitmapDenoiseNlmFinishProgram)
bindComputeSampler(bitmapDenoiseNlmFinishProgram, "uInput", 0, input)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId)
GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F)
setBitmapDenoiseCommonUniforms(bitmapDenoiseNlmFinishProgram, width, height, params)
setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFinishProgram, height)
GLES31.glUniform1f(GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uBias"), params.bias - 0.5f * ln(params.scale))
GLES31.glUniform1f(
GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uDenoiseMix"),
params.strength
)
dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM finish")
}
private fun setBitmapDenoiseStripeUniforms(program: Int, height: Int) {
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowOffset"), 0)
GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowCount"), height)
}
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, "uSignalScale"),
1,
params.signalScale,
0
)
}
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(
GlesComputeWorkGroup.imageGroupCount(width),
GlesComputeWorkGroup.imageGroupCount(height),
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)
}
/**
* 设置 HDF 光晕效果 FBO
* 使用 1/4 分辨率进行模糊,然后在全分辨率合成
@@ -2685,13 +2133,7 @@ class LutImageProcessor(context: Context? = null) {
}
releaseReadbackBuffer()
if (bitmapDenoisePreconditionProgram != 0) GLES31.glDeleteProgram(bitmapDenoisePreconditionProgram)
if (bitmapDenoiseNlmInitProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmInitProgram)
if (bitmapDenoiseNlmFusedAccuProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFusedAccuProgram)
if (bitmapDenoiseNlmFinishProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFinishProgram)
if (bitmapDenoisePassthroughProgram != 0) GLES30.glDeleteProgram(bitmapDenoisePassthroughProgram)
if (bitmapChromaDenoiseGuideProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseGuideProgram)
if (bitmapChromaDenoiseProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseProgram)
bitmapMgcDenoiser.release()
if (lutSharpenProgram != 0) {
GLES30.glDeleteProgram(lutSharpenProgram)
lutSharpenProgram = 0
@@ -2700,16 +2142,7 @@ class LutImageProcessor(context: Context? = null) {
GLES30.glDeleteProgram(lutLuminanceGainProgram)
lutLuminanceGainProgram = 0
}
for (i in 0..1) {
if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0)
if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0)
}
releaseLutSharpenFramebuffer()
if (bitmapDenoiseNlmU2BufferId != 0) {
GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0)
bitmapDenoiseNlmU2BufferId = 0
}
bitmapDenoiseNlmBufferPixels = 0
// 释放 HDF 资源
if (hdfExtractBlurHProgram != 0) GLES30.glDeleteProgram(hdfExtractBlurHProgram)
@@ -2742,8 +2175,6 @@ class LutImageProcessor(context: Context? = null) {
companion object {
private const val TAG = "LutImageProcessor"
private const val BITMAP_DENOISE_A = 0.008f
private const val BITMAP_DENOISE_B = 0.0005f
private const val LUT_LUMINANCE_OFFSET = 1e-4f
private const val CLARITY_PYRAMID_LEVELS = 3
private const val EGL_CONTEXT_PRIORITY_LEVEL_IMG = 0x3100
@@ -12,15 +12,4 @@ object DenoiseStrength {
?.takeIf { it.isFinite() }
?.coerceIn(MIN_VALUE, MAX_VALUE)
?: MIN_VALUE
/**
* Bitmap NLM reaches a full output mix at 1. Values above 1 strengthen its
* assumed noise standard deviation, so the corresponding variance is squared.
*/
fun noiseVarianceScale(value: Float): Float {
val sigmaScale = clamp(value).coerceAtLeast(1.0f)
return sigmaScale * sigmaScale
}
fun outputMix(value: Float): Float = clamp(value).coerceAtMost(1.0f)
}
@@ -1,72 +0,0 @@
package com.hinnka.mycamera.raw
import kotlin.math.max
internal data class DenoiseProfileOffset(
val x: Int,
val y: Int,
)
internal data class DenoiseProfileWeightTuning(
val expectedFineDistance: Float,
val expectedGuideDistance: Float,
val inverseBandwidth: Float,
val coarseGuideWeight: Float,
)
/**
* Statistical and traversal configuration shared by the RAW and bitmap NLM hosts.
*
* The variance-stabilizing transform targets unit noise variance per color channel. The
* difference between two independent samples therefore has variance two. Noise-only patch
* energy is removed before applying the NLM bandwidth so that the weight curve starts falling
* as soon as a candidate contains energy that the sensor noise model cannot explain.
*/
internal object DenoiseProfileNlmConfig {
private const val COLOR_CHANNEL_COUNT = 3
private const val DIFFERENCE_VARIANCE = 2.0f
// Squared-energy of the separable 3x3 Gaussian kernel [1 2 1]^T[1 2 1] / 16.
private const val GUIDE_FILTER_ENERGY = 36.0f / 256.0f
// Coarse guide differences describe structure rather than independent RGB noise. Give them
// enough leverage to reject low-contrast contours without turning the decision into a hard
// threshold.
const val COARSE_GUIDE_WEIGHT = 8.0f
val searchOffsets: List<DenoiseProfileOffset> = buildSearchOffsets(
DenoiseProfileShaders.SEARCH_RADIUS
)
fun buildSearchOffsets(radius: Int): List<DenoiseProfileOffset> {
require(radius >= 0) { "radius must be non-negative" }
return buildList {
for (qy in -radius..0) {
// FUSED_ACCU evaluates +q and -q together. At y == 0 only one horizontal
// half-axis is needed; visiting both halves would double horizontal weights.
val qxEnd = if (qy == 0) 0 else radius
for (qx in -radius..qxEnd) {
add(DenoiseProfileOffset(qx, qy))
}
}
}
}
fun weightTuning(patchRadius: Int): DenoiseProfileWeightTuning {
require(patchRadius >= 0) { "patchRadius must be non-negative" }
val patchWidth = 2 * patchRadius + 1
val patchPixels = patchWidth * patchWidth
val expectedFineDistance =
DIFFERENCE_VARIANCE * COLOR_CHANNEL_COUNT * patchPixels.toFloat()
val expectedGuideDistance =
DIFFERENCE_VARIANCE * GUIDE_FILTER_ENERGY * patchPixels.toFloat()
return DenoiseProfileWeightTuning(
expectedFineDistance = expectedFineDistance,
expectedGuideDistance = expectedGuideDistance,
// One additional noise-floor worth of unexplained RGB energy halves the weight.
inverseBandwidth = 1.0f / max(expectedFineDistance, 1.0f),
coarseGuideWeight = COARSE_GUIDE_WEIGHT,
)
}
}
@@ -1,276 +0,0 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
/**
* OpenGL ES 3.1 compute port of darktable's denoiseprofile NLM path.
*
* Input and output stay in un-white-balanced camera RGB. The host keeps darktable's
* white-balance-adaptive exponent, but removes WB from the reversible signal scale.
* The pipeline mirrors darktable process_nlmeans_cl with a mobile fused accumulator and a
* low-frequency green guide used to keep low-contrast structure out of the noise estimate:
* precondition_v2 -> init -> repeated local-tile accu -> finish_v2.
*/
object DenoiseProfileShaders {
const val SEARCH_RADIUS = 5
const val PATCH_RADIUS = 1
// darktable's neutral bias setting makes finish_v2 the exact inverse when NLM leaves a
// transformed sample unchanged. This is required to keep sensor black and channel ratios.
const val BLACK_PRESERVING_BIAS = 0.0f
const val IMAGE_LOCAL_X = GlesComputeWorkGroup.IMAGE_TILE_SIZE
const val IMAGE_LOCAL_Y = GlesComputeWorkGroup.IMAGE_TILE_SIZE
private const val FUSED_TILE_X = IMAGE_LOCAL_X + SEARCH_RADIUS + 2 * PATCH_RADIUS
private const val FUSED_TILE_Y = IMAGE_LOCAL_Y + SEARCH_RADIUS + 2 * PATCH_RADIUS
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);
}
float fastMexp2(float x) {
const float i1 = float(0x3f800000u);
const float i2 = float(0x3f000000u);
float k0 = i1 + x * (i2 - i1);
uint bits = (k0 >= float(0x800000u)) ? uint(k0) : 0u;
return uintBitsToFloat(bits);
}
float ddirac(ivec2 q) {
return (q.x != 0 || q.y != 0) ? 1.0 : 0.0;
}
int pixelIndex(ivec2 coord, ivec2 size) {
return coord.y * size.x + coord.x;
}
"""
val PRECONDITION_V2 = """
#version 310 es
$COMMON
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) 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 uSignalScale;
vec4 preconditionSignal(vec4 pixel) {
return max(
2.0 * dtPow(max(vec4(0.0), pixel / uSignalScale + uB), 1.0 - uP / 2.0) /
((-uP + 2.0) * sqrt(uA)),
vec4(0.0)
);
}
float preconditionGreen(float signal) {
return max(
2.0 * pow(max(0.0, signal / uSignalScale.g + uB.g), 1.0 - uP.g / 2.0) /
((-uP.g + 2.0) * sqrt(uA.g)),
0.0
);
}
void main() {
ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return;
vec4 t = preconditionSignal(readPixel(uInput, coord, uImageSize));
// Alpha is scratch space after preconditioning: FUSED_ACCU replaces it with the
// accumulated weight and FINISH_V2 restores alpha from the original input. A 3x3
// Gaussian green guide expands the effective structural support of the 3x3 RGB
// patch without another full-resolution intermediate texture.
float guide =
preconditionGreen(readPixel(uInput, coord + ivec2(-1, -1), uImageSize).g) +
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, -1), uImageSize).g) +
preconditionGreen(readPixel(uInput, coord + ivec2(1, -1), uImageSize).g) +
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(-1, 0), uImageSize).g) +
4.0 * t.g +
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(1, 0), uImageSize).g) +
preconditionGreen(readPixel(uInput, coord + ivec2(-1, 1), uImageSize).g) +
2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, 1), uImageSize).g) +
preconditionGreen(readPixel(uInput, coord + ivec2(1, 1), uImageSize).g);
t.a = guide * (1.0 / 16.0);
imageStore(uOutput, coord, t);
}
""".trimIndent()
val INIT = """
#version 310 es
$COMMON
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; };
uniform ivec2 uImageSize;
uniform int uStripeRowCount;
void main() {
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
u2[stripeCoord.y * uImageSize.x + stripeCoord.x] = vec4(0.0);
}
""".trimIndent()
val FUSED_ACCU = """
#version 310 es
$COMMON
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; };
shared vec2 sDistance[$FUSED_TILE_X * $FUSED_TILE_Y];
uniform ivec2 uImageSize;
uniform int uStripeRowOffset;
uniform int uStripeRowCount;
uniform ivec2 uQ;
uniform float uExpectedFineDistance;
uniform float uExpectedGuideDistance;
uniform float uInverseBandwidth;
uniform float uCoarseGuideWeight;
uniform float uCentralPixelWeight;
vec2 pixelDistance(ivec2 coord, ivec2 q) {
ivec2 shifted = coord + q;
bool inBounds = shifted.x >= 0 && shifted.x < uImageSize.x &&
shifted.y >= 0 && shifted.y < uImageSize.y;
if (!inBounds) return vec2(0.0);
vec4 p1 = readPixel(uInput, coord, uImageSize);
vec4 p2 = readPixel(uInput, shifted, uImageSize);
vec4 tmp = (p1 - p2) * (p1 - p2);
return vec2(tmp.x + tmp.y + tmp.z, tmp.a);
}
vec2 tileDistance(ivec2 imageCoord, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) {
ivec2 tileCoord = imageCoord - groupOrigin - tileMin;
return sDistance[tileCoord.y * tileWidth + tileCoord.x];
}
float patchWeight(ivec2 center, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) {
vec2 distacc = vec2(0.0);
for (int pj = -$PATCH_RADIUS; pj <= $PATCH_RADIUS; pj++) {
for (int pi = -$PATCH_RADIUS; pi <= $PATCH_RADIUS; pi++) {
ivec2 patchCoord = clamp(
center + ivec2(pi, pj),
ivec2(0),
uImageSize - ivec2(1)
);
distacc += tileDistance(patchCoord, groupOrigin, tileMin, tileWidth);
}
}
float patchPixels = float((2 * $PATCH_RADIUS + 1) * (2 * $PATCH_RADIUS + 1));
distacc += tileDistance(center, groupOrigin, tileMin, tileWidth) *
patchPixels * uCentralPixelWeight;
distacc /= 1.0 + uCentralPixelWeight;
float unexplainedFine = max(distacc.x - uExpectedFineDistance, 0.0);
float unexplainedGuide = max(distacc.y - uExpectedGuideDistance, 0.0);
float unexplainedDistance =
unexplainedFine + uCoarseGuideWeight * unexplainedGuide;
return fastMexp2(unexplainedDistance * uInverseBandwidth);
}
void main() {
ivec2 groupOrigin = ivec2(
int(gl_WorkGroupID.x) * $IMAGE_LOCAL_X,
uStripeRowOffset + int(gl_WorkGroupID.y) * $IMAGE_LOCAL_Y
);
ivec2 tileMin = min(ivec2(-$PATCH_RADIUS), -uQ - ivec2($PATCH_RADIUS));
ivec2 tileMax = max(ivec2($PATCH_RADIUS), -uQ + ivec2($PATCH_RADIUS));
int tileWidth = $IMAGE_LOCAL_X + tileMax.x - tileMin.x;
int tileHeight = $IMAGE_LOCAL_Y + tileMax.y - tileMin.y;
int tilePixels = tileWidth * tileHeight;
int localIndex = int(gl_LocalInvocationID.y) * $IMAGE_LOCAL_X +
int(gl_LocalInvocationID.x);
int localCount = $IMAGE_LOCAL_X * $IMAGE_LOCAL_Y;
for (int i = localIndex; i < tilePixels; i += localCount) {
int tileX = i - (i / tileWidth) * tileWidth;
int tileY = i / tileWidth;
ivec2 imageCoord = groupOrigin + ivec2(tileX, tileY) + tileMin;
imageCoord = clamp(imageCoord, ivec2(0), uImageSize - ivec2(1));
sDistance[i] = pixelDistance(imageCoord, uQ);
}
memoryBarrierShared();
barrier();
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset);
ivec2 plusCoord = coord + uQ;
ivec2 minusCoord = coord - uQ;
bool plusInBounds = plusCoord.x >= 0 && plusCoord.x < uImageSize.x &&
plusCoord.y >= 0 && plusCoord.y < uImageSize.y;
bool minusInBounds = minusCoord.x >= 0 && minusCoord.x < uImageSize.x &&
minusCoord.y >= 0 && minusCoord.y < uImageSize.y;
float weight = plusInBounds ? patchWeight(coord, groupOrigin, tileMin, tileWidth) : 0.0;
float weightMinus = (minusInBounds && ddirac(uQ) > 0.0)
? patchWeight(minusCoord, groupOrigin, tileMin, tileWidth)
: 0.0;
vec4 u1Pq = plusInBounds ? readPixel(uInput, plusCoord, uImageSize) : vec4(0.0);
vec4 u1Mq = minusInBounds ? readPixel(uInput, minusCoord, uImageSize) : vec4(0.0);
vec4 accu = weight * u1Pq + weightMinus * u1Mq;
accu.a = weight + weightMinus;
int idx = stripeCoord.y * uImageSize.x + stripeCoord.x;
u2[idx] = u2[idx] + accu;
}
""".trimIndent()
val FINISH_V2 = """
#version 310 es
$COMMON
layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in;
layout(binding = 0) uniform highp sampler2D uInput;
layout(std430, binding = 0) readonly buffer AccuBuffer { vec4 u2[]; };
layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput;
uniform ivec2 uImageSize;
uniform int uStripeRowOffset;
uniform int uStripeRowCount;
uniform vec4 uA;
uniform vec4 uP;
uniform vec4 uB;
uniform float uBias;
uniform float uDenoiseMix;
uniform vec4 uSignalScale;
void main() {
ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy);
if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return;
ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset);
int idx = stripeCoord.y * uImageSize.x + stripeCoord.x;
vec4 accu = u2[idx];
vec4 original = readPixel(uInput, coord, uImageSize);
vec4 px = accu.a > 0.0 ? accu / accu.a : vec4(0.0);
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 *= uSignalScale;
px.rgb = mix(original.rgb, px.rgb, clamp(uDenoiseMix, 0.0, 1.0));
px.a = original.a;
imageStore(uOutput, coord, px);
}
""".trimIndent()
}
@@ -0,0 +1,137 @@
package com.hinnka.mycamera.raw
// Generated by tools/bitmap_noise_calibration/generate_kotlin.py. Do not edit by hand.
/** Offline bitmap noise calibrations (calibrate.py), ascending by ISO. */
internal object MgcBitmapNoiseCalibrations {
val ENTRIES: List<MgcBitmapNoiseModel.Calibration> = listOf(
// PhotonCamera_20261109_143038.标准.jpg, ISO 270; source: tools/bitmap_noise_calibration/oppo_a3x_iso270.json
MgcBitmapNoiseModel.Calibration(
iso = 270,
lumaRead = 0f,
lumaShot = 0.001698564f,
lumaQuadratic = 0.004053289f,
boxVarianceRatio2 = 0.727823f,
boxVarianceRatio4 = 0.5807647f,
denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel(
normalizedRead = floatArrayOf(0f, 0f, 0f),
normalizedLumaShot = 0.003397128f,
normalizedLumaQuadratic = 0.004053289f,
normalizedChromaShot = 0.003397128f,
normalizedChromaQuadratic = 0.004053289f,
lumaCorrelation = floatArrayOf(
0.2370727f, 0.1647024f, 0.148228f, 0.1472644f, 0.1499985f, 0.1517085f,
0.1549584f, 0.1657112f, 0.1775394f, 0.1784397f, 0.18351f, 0.1879864f,
0.2059089f, 0.2247925f, 0.2308894f, 0.2439626f, 0.259771f, 0.2635828f,
0.2835664f, 0.3082006f, 0.3315156f, 0.3533951f, 0.3773934f, 0.3827962f,
0.4088563f, 0.4331712f, 0.4276295f, 0.4717214f, 0.4892584f, 0.4880814f,
0.5357004f, 0.547161f, 0.5904874f, 0.5569481f, 0.5757658f, 0.5865457f,
0.6105018f, 0.6066094f, 0.6293522f, 0.633817f, 0.6595704f, 0.6663031f,
0.6572506f, 0.6542949f, 0.6885165f, 0.6695643f, 0.7106166f, 0.7547786f,
0.7965492f, 0.8218433f, 0.8018763f, 0.7723972f, 0.8399447f, 0.9354574f,
0.9923136f, 0.9620705f, 1.024072f, 1.341096f, 1.744655f, 2.065495f,
2.493847f, 3.902611f, 10.66583f, 14.27455f, 14.27455f, 10.66583f,
3.902611f, 2.493847f, 2.065495f, 1.744655f, 1.341096f, 1.024072f,
0.9620705f, 0.9923136f, 0.9354574f, 0.8399447f, 0.7723972f, 0.8018763f,
0.8218433f, 0.7965492f, 0.7547786f, 0.7106166f, 0.6695643f, 0.6885165f,
0.6542949f, 0.6572506f, 0.6663031f, 0.6595704f, 0.633817f, 0.6293522f,
0.6066094f, 0.6105018f, 0.5865457f, 0.5757658f, 0.5569481f, 0.5904874f,
0.547161f, 0.5357004f, 0.4880814f, 0.4892584f, 0.4717214f, 0.4276295f,
0.4331712f, 0.4088563f, 0.3827962f, 0.3773934f, 0.3533951f, 0.3315156f,
0.3082006f, 0.2835664f, 0.2635828f, 0.259771f, 0.2439626f, 0.2308894f,
0.2247925f, 0.2059089f, 0.1879864f, 0.18351f, 0.1784397f, 0.1775394f,
0.1657112f, 0.1549584f, 0.1517085f, 0.1499985f, 0.1472644f, 0.148228f,
0.1647024f, 0.2370727f,
),
chromaCorrelation = floatArrayOf(
0.06788593f, 0.04708519f, 0.0448037f, 0.0443403f, 0.04515055f, 0.0465143f,
0.04816711f, 0.048743f, 0.05081074f, 0.05199204f, 0.05242346f, 0.05159559f,
0.05145567f, 0.05259706f, 0.05406489f, 0.05264108f, 0.05425233f, 0.05361206f,
0.05616313f, 0.05854646f, 0.0609109f, 0.06033442f, 0.06400992f, 0.06591436f,
0.07099266f, 0.07149659f, 0.07550936f, 0.07692385f, 0.08176214f, 0.0822932f,
0.08955874f, 0.09599174f, 0.09952724f, 0.09897214f, 0.1072705f, 0.1150873f,
0.1228051f, 0.1300161f, 0.1424562f, 0.1541165f, 0.1646127f, 0.1805898f,
0.1988008f, 0.2354062f, 0.2731975f, 0.3227035f, 0.4231182f, 0.560808f,
0.6988397f, 0.9792791f, 1.143923f, 1.429045f, 1.847879f, 2.044252f,
2.464851f, 3.085948f, 3.432729f, 3.76707f, 4.198544f, 4.649198f,
5.634794f, 5.948845f, 8.49351f, 8.923265f, 8.923265f, 8.49351f,
5.948845f, 5.634794f, 4.649198f, 4.198544f, 3.76707f, 3.432729f,
3.085948f, 2.464851f, 2.044252f, 1.847879f, 1.429045f, 1.143923f,
0.9792791f, 0.6988397f, 0.560808f, 0.4231182f, 0.3227035f, 0.2731975f,
0.2354062f, 0.1988008f, 0.1805898f, 0.1646127f, 0.1541165f, 0.1424562f,
0.1300161f, 0.1228051f, 0.1150873f, 0.1072705f, 0.09897214f, 0.09952724f,
0.09599174f, 0.08955874f, 0.0822932f, 0.08176214f, 0.07692385f, 0.07550936f,
0.07149659f, 0.07099266f, 0.06591436f, 0.06400992f, 0.06033442f, 0.0609109f,
0.05854646f, 0.05616313f, 0.05361206f, 0.05425233f, 0.05264108f, 0.05406489f,
0.05259706f, 0.05145567f, 0.05159559f, 0.05242346f, 0.05199204f, 0.05081074f,
0.048743f, 0.04816711f, 0.0465143f, 0.04515055f, 0.0443403f, 0.0448037f,
0.04708519f, 0.06788593f,
),
),
),
// PhotonCamera_20261109_134217.标准.jpg, ISO 6400; source: tools/bitmap_noise_calibration/oppo_a3x_iso6400.json
MgcBitmapNoiseModel.Calibration(
iso = 6400,
lumaRead = 0.001729636f,
lumaShot = 0.01133283f,
lumaQuadratic = 0f,
boxVarianceRatio2 = 0.5546569f,
boxVarianceRatio4 = 0.2427601f,
denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel(
normalizedRead = floatArrayOf(0.006918545f, 0.004793569f, 0.03163469f),
normalizedLumaShot = 0.02266566f,
normalizedLumaQuadratic = 0f,
normalizedChromaShot = 0.02266566f,
normalizedChromaQuadratic = 0f,
lumaCorrelation = floatArrayOf(
0.2849099f, 0.1892967f, 0.1856172f, 0.1941112f, 0.1857321f, 0.206578f,
0.209216f, 0.2139979f, 0.2192574f, 0.2341152f, 0.2418339f, 0.2551319f,
0.2721379f, 0.2833573f, 0.3124941f, 0.3128699f, 0.3319263f, 0.3623236f,
0.400154f, 0.4215496f, 0.4444607f, 0.4679012f, 0.4761536f, 0.5215382f,
0.5808329f, 0.600072f, 0.6346785f, 0.6624425f, 0.7013004f, 0.7358205f,
0.8115942f, 0.8074724f, 0.866868f, 0.9058378f, 0.8829234f, 0.945763f,
0.9880208f, 1.004558f, 1.02639f, 1.096725f, 1.076676f, 1.110294f,
1.180143f, 1.210591f, 1.277392f, 1.230035f, 1.270713f, 1.331771f,
1.327f, 1.400249f, 1.44426f, 1.448319f, 1.476424f, 1.590698f,
1.652265f, 1.652337f, 1.776714f, 1.870995f, 1.98167f, 2.042017f,
2.373291f, 2.872722f, 3.461228f, 5.464234f, 5.464234f, 3.461228f,
2.872722f, 2.373291f, 2.042017f, 1.98167f, 1.870995f, 1.776714f,
1.652337f, 1.652265f, 1.590698f, 1.476424f, 1.448319f, 1.44426f,
1.400249f, 1.327f, 1.331771f, 1.270713f, 1.230035f, 1.277392f,
1.210591f, 1.180143f, 1.110294f, 1.076676f, 1.096725f, 1.02639f,
1.004558f, 0.9880208f, 0.945763f, 0.8829234f, 0.9058378f, 0.866868f,
0.8074724f, 0.8115942f, 0.7358205f, 0.7013004f, 0.6624425f, 0.6346785f,
0.600072f, 0.5808329f, 0.5215382f, 0.4761536f, 0.4679012f, 0.4444607f,
0.4215496f, 0.400154f, 0.3623236f, 0.3319263f, 0.3128699f, 0.3124941f,
0.2833573f, 0.2721379f, 0.2551319f, 0.2418339f, 0.2341152f, 0.2192574f,
0.2139979f, 0.209216f, 0.206578f, 0.1857321f, 0.1941112f, 0.1856172f,
0.1892967f, 0.2849099f,
),
chromaCorrelation = floatArrayOf(
0.03265955f, 0.02332009f, 0.02302547f, 0.02278608f, 0.02277681f, 0.02413007f,
0.023925f, 0.02569323f, 0.0272321f, 0.02778324f, 0.02920323f, 0.03051508f,
0.03303627f, 0.03560619f, 0.03806804f, 0.0404683f, 0.0431758f, 0.04475632f,
0.0497294f, 0.05260224f, 0.05709018f, 0.06007614f, 0.06085153f, 0.06537153f,
0.06918297f, 0.07286539f, 0.07363435f, 0.07909254f, 0.08658081f, 0.09007621f,
0.09224977f, 0.09544551f, 0.1036612f, 0.1127405f, 0.1157037f, 0.1242169f,
0.13441f, 0.1482904f, 0.1671728f, 0.1864466f, 0.2154091f, 0.2479165f,
0.3079063f, 0.3778761f, 0.4747187f, 0.5914111f, 0.7651589f, 0.8794243f,
1.11843f, 1.362278f, 1.645642f, 1.920733f, 2.219147f, 2.690244f,
3.124821f, 3.475304f, 3.766885f, 4.445485f, 4.78106f, 4.952844f,
5.220719f, 5.672083f, 5.685087f, 5.413767f, 5.413767f, 5.685087f,
5.672083f, 5.220719f, 4.952844f, 4.78106f, 4.445485f, 3.766885f,
3.475304f, 3.124821f, 2.690244f, 2.219147f, 1.920733f, 1.645642f,
1.362278f, 1.11843f, 0.8794243f, 0.7651589f, 0.5914111f, 0.4747187f,
0.3778761f, 0.3079063f, 0.2479165f, 0.2154091f, 0.1864466f, 0.1671728f,
0.1482904f, 0.13441f, 0.1242169f, 0.1157037f, 0.1127405f, 0.1036612f,
0.09544551f, 0.09224977f, 0.09007621f, 0.08658081f, 0.07909254f, 0.07363435f,
0.07286539f, 0.06918297f, 0.06537153f, 0.06085153f, 0.06007614f, 0.05709018f,
0.05260224f, 0.0497294f, 0.04475632f, 0.0431758f, 0.0404683f, 0.03806804f,
0.03560619f, 0.03303627f, 0.03051508f, 0.02920323f, 0.02778324f, 0.0272321f,
0.02569323f, 0.023925f, 0.02413007f, 0.02277681f, 0.02278608f, 0.02302547f,
0.02332009f, 0.03265955f,
),
),
),
)
}
@@ -0,0 +1,129 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
import kotlin.math.ln
import kotlin.math.sqrt
/**
* ISO-indexed MGC noise model for ISP-rendered bitmaps (JPEG/HEIF/YUV captures), in the linear
* (inverse sRGB transfer) working RGB with white balance (1, 1, 1).
*
* Each [Calibration] comes from tools/bitmap_noise_calibration/calibrate.py and follows the
* DemosaicNoisePropagationCalibrator conventions: MGC RGB->YUV matrix, NoiseModel.Scale(2)
* (read x4, shot x2), Cb/Cr sharing the luma signal-dependent slice, and 128-bin half-bin
* directional spectra normalized to mean 1. Between calibrated ISOs every coefficient and
* spectrum bin is interpolated linearly in log(ISO); outside the calibrated range the nearest
* calibration applies.
*/
internal object MgcBitmapNoiseModel {
private const val TAG = "MgcBitmapNoiseModel"
data class Calibration(
val iso: Int,
/** Un-scaled linear luma variance: read + shot * s + quadratic * s^2, for the tuning SNR. */
val lumaRead: Float,
val lumaShot: Float,
val lumaQuadratic: Float,
/**
* Luma noise variance kept by a factor-2 / factor-4 box downsample. The noise is spatially
* correlated, so these exceed 1/4 and 1/16; the detail map compares coarse local
* variance against the model scaled by them.
*/
val boxVarianceRatio2: Float,
val boxVarianceRatio4: Float,
val denoiserModel: MgcFullResolutionDenoise.PreparedYuvNoiseModel,
) {
/** Un-scaled linear luma noise variance at [signal]. */
fun lumaVariance(signal: Float): Float {
val s = signal.coerceAtLeast(0f)
return lumaRead + lumaShot * s + lumaQuadratic * s * s
}
/** MGC tuning coordinate at the image's mean linear luma, as withMgcRenderTuning() for RAW. */
fun tuningSnr(meanLinearLuma: Float): Float {
val signal = meanLinearLuma.coerceAtLeast(0f)
val variance = lumaRead + lumaShot * signal + lumaQuadratic * signal * signal
return if (variance > 0f) signal / sqrt(variance) else 0f
}
}
/**
* The model for a capture at [iso]. Without an ISO the lowest calibration applies: it assumes
* the least noise and so removes the least detail.
*/
fun forIso(iso: Int?): Calibration {
val calibrations = MgcBitmapNoiseCalibrations.ENTRIES
check(calibrations.isNotEmpty() && calibrations.zipWithNext().all { (a, b) -> a.iso < b.iso }) {
"Bitmap noise calibrations must be non-empty and strictly ascending by ISO"
}
val validIso = iso?.takeIf { it > 0 }
if (validIso == null) {
PLog.w(TAG, "Bitmap has no ISO; using the ISO ${calibrations.first().iso} calibration")
return calibrations.first()
}
if (validIso <= calibrations.first().iso) return calibrations.first()
if (validIso >= calibrations.last().iso) return calibrations.last()
val upperIndex = calibrations.indexOfFirst { it.iso >= validIso }
val lower = calibrations[upperIndex - 1]
val upper = calibrations[upperIndex]
if (upper.iso == validIso) return upper
val amount = ((ln(validIso.toFloat()) - ln(lower.iso.toFloat())) /
(ln(upper.iso.toFloat()) - ln(lower.iso.toFloat()))).coerceIn(0f, 1f)
return interpolate(lower, upper, amount, validIso)
}
/** Identifies the model [forIso] resolves to, for caches of denoised output. */
fun cacheSignature(iso: Int?): String {
val model = forIso(iso)
val crc = java.util.zip.CRC32()
fun add(value: Float) {
val bits = value.toRawBits()
crc.update(byteArrayOf((bits ushr 24).toByte(), (bits ushr 16).toByte(), (bits ushr 8).toByte(), bits.toByte()))
}
add(model.lumaRead)
add(model.lumaShot)
add(model.lumaQuadratic)
add(model.boxVarianceRatio2)
add(model.boxVarianceRatio4)
with(model.denoiserModel) {
normalizedRead.forEach(::add)
add(normalizedLumaShot)
add(normalizedLumaQuadratic)
add(normalizedChromaShot)
add(normalizedChromaQuadratic)
lumaCorrelation.forEach(::add)
chromaCorrelation.forEach(::add)
}
return "mgc-${model.iso}-${java.lang.Long.toHexString(crc.value)}"
}
private fun interpolate(lower: Calibration, upper: Calibration, amount: Float, iso: Int): Calibration {
fun mix(a: Float, b: Float) = a + (b - a) * amount
fun mixArray(a: FloatArray, b: FloatArray) = FloatArray(a.size) { mix(a[it], b[it]) }
fun mixSpectrum(a: FloatArray, b: FloatArray): FloatArray {
val mixed = mixArray(a, b)
val mean = mixed.average().toFloat()
check(mean > 0f) { "Interpolated bitmap noise spectrum has no power" }
return FloatArray(mixed.size) { mixed[it] / mean }
}
val a = lower.denoiserModel
val b = upper.denoiserModel
return Calibration(
iso = iso,
lumaRead = mix(lower.lumaRead, upper.lumaRead),
lumaShot = mix(lower.lumaShot, upper.lumaShot),
lumaQuadratic = mix(lower.lumaQuadratic, upper.lumaQuadratic),
boxVarianceRatio2 = mix(lower.boxVarianceRatio2, upper.boxVarianceRatio2),
boxVarianceRatio4 = mix(lower.boxVarianceRatio4, upper.boxVarianceRatio4),
denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel(
normalizedRead = mixArray(a.normalizedRead, b.normalizedRead),
normalizedLumaShot = mix(a.normalizedLumaShot, b.normalizedLumaShot),
normalizedLumaQuadratic = mix(a.normalizedLumaQuadratic, b.normalizedLumaQuadratic),
normalizedChromaShot = mix(a.normalizedChromaShot, b.normalizedChromaShot),
normalizedChromaQuadratic = mix(a.normalizedChromaQuadratic, b.normalizedChromaQuadratic),
lumaCorrelation = mixSpectrum(a.lumaCorrelation, b.lumaCorrelation),
chromaCorrelation = mixSpectrum(a.chromaCorrelation, b.chromaCorrelation),
),
)
}
}
@@ -415,6 +415,186 @@ internal object MgcFullResolutionDenoise {
return true
}
/**
* Denoises linear RGBA16F produced from an ISP-rendered bitmap (white balance 1, 1, 1) with
* the [MgcBitmapNoiseModel] calibration for its ISO. Tunings follow the USER_ADJUSTMENT pass; there is no CFA
* (no MeasureMoire) and no lens shading. [spatialStrengthQ8] is the bitmap detail map over the
* whole image ((full + 3) / 4 Q8 noise scale), or null. The low-frequency chroma branch runs
* separately over the whole image ([lowFrequencyChromaBitmap]).
*/
fun denoiseLinearBitmap(
rgba16f: ByteBuffer,
width: Int,
height: Int,
globalOriginX: Int,
globalOriginY: Int,
fullWidth: Int,
fullHeight: Int,
noiseModel: PreparedYuvNoiseModel,
spatialStrengthQ8: ShortArray?,
tuningSnr: Float,
lumaStrengthScale: Float,
chromaStrengthScale: Float,
): Boolean {
val finiteLumaScale = DenoiseStrength.clamp(lumaStrengthScale)
val finiteChromaScale = DenoiseStrength.clamp(chromaStrengthScale)
val lumaEnabled = finiteLumaScale > 0f
val chromaEnabled = finiteChromaScale > 0f
if (!initialized || !rgba16f.isDirect || width <= 0 || height <= 0 ||
(!lumaEnabled && !chromaEnabled)
) {
return false
}
val model = noiseModel
check(validPreparedYuvNoise(model) && validCorrelation(model.lumaCorrelation) &&
validCorrelation(model.chromaCorrelation)) { "Malformed bitmap MGC noise model" }
val strengthWidth = (fullWidth + 3) / 4
val strengthHeight = (fullHeight + 3) / 4
check(spatialStrengthQ8 == null || spatialStrengthQ8.size == strengthWidth * strengthHeight) {
"Bitmap strength map does not cover ${fullWidth}x$fullHeight"
}
val coreTuning = PhotonCoreImagingTuning
val lumaTuning = bitmapLumaTuning(tuningSnr, finiteLumaScale)
val chromaTuning = bitmapChromaTuning(tuningSnr, finiteChromaScale)
rgba16f.clear()
val result = nativeDenoiseRgba16f(
rgbaBuffer = rgba16f,
width = width,
height = height,
globalOriginX = globalOriginX,
globalOriginY = globalOriginY,
fullWidth = fullWidth,
fullHeight = fullHeight,
inputIsBayer = false,
cfaPattern = 0,
measureMoireEnabled = false,
applyLensShadingInBayerAot = false,
lensShading = null,
lensWidth = 0,
lensHeight = 0,
// The prepared YUV model replaces the analytic RGB model in the native bridge.
normalizedRgbShot = FloatArray(3),
normalizedRgbRead = FloatArray(3),
normalizedRgbWhiteBalance = floatArrayOf(1f, 1f, 1f),
preparedNormalizedYuvRead = model.normalizedRead,
preparedNormalizedLumaShot = model.normalizedLumaShot,
preparedNormalizedLumaQuadratic = model.normalizedLumaQuadratic,
preparedNormalizedChromaShot = model.normalizedChromaShot,
preparedNormalizedChromaQuadratic = model.normalizedChromaQuadratic,
lumaCorrelation = model.lumaCorrelation,
chromaCorrelation = model.chromaCorrelation,
denoiseResponseOffset = coreTuning.denoise.frequencyResponse.responseOffset,
denoiseResponseCosineOffset = coreTuning.denoise.frequencyResponse.cosineOffset,
spatialStrengthQ8 = spatialStrengthQ8,
spatialStrengthWidth = if (spatialStrengthQ8 != null) strengthWidth else 0,
spatialStrengthHeight = if (spatialStrengthQ8 != null) strengthHeight else 0,
lumaEnabled = lumaEnabled,
chromaEnabled = chromaEnabled,
lumaStrength = lumaTuning.strength,
lumaOutlierDistance = lumaTuning.outlierDistance,
lumaRevertFactor = lumaTuning.revertFactor,
chromaStrength = chromaTuning.strength,
chromaOutlierThreshold = chromaTuning.outlierDistance,
diagnosticsEnabled = RawStackRuntimeDebug.mgcFullResolutionDenoiseDiagnosticsEnabled,
lowFrequencyLog2Downsample = 0,
chromaMedianFilterType = coreTuning.denoise.chromaMedianFilterType,
)
rgba16f.position(0)
if (result != 0) {
PLog.e(
TAG,
"MGC bitmap denoise kernel failed: result=0x${result.toString(16)} " +
"size=${width}x$height origin=($globalOriginX,$globalOriginY)",
)
return false
}
PLog.d(
TAG,
"MGC bitmap denoise complete: size=${width}x$height " +
"origin=($globalOriginX,$globalOriginY) full=${fullWidth}x$fullHeight " +
"snr=$tuningSnr luma=$lumaEnabled($finiteLumaScale) " +
"chroma=$chromaEnabled($finiteChromaScale) " +
"lumaStrength=${lumaTuning.strength.contentToString()} " +
"chromaStrength=${chromaTuning.strength.contentToString()}",
)
return true
}
private fun bitmapLumaTuning(tuningSnr: Float, scale: Float): Tuning {
val coreTuning = PhotonCoreImagingTuning
return applyCoreDenoiseScales(
tuning = interpolateTuning(tuningSnr, lumaTuningPoints),
globalStrengthScale = scale,
strengthLevelScales = coreTuning.denoise.lumaStrengthScale.toFloatArray(),
revertLevelScales = coreTuning.denoise.detailReconstructionScale.toFloatArray(),
outlierLevelScales = coreTuning.denoise.outlierRejectionScale.toFloatArray(),
)
}
private fun bitmapChromaTuning(tuningSnr: Float, scale: Float): Tuning =
applyCoreDenoiseScales(
tuning = interpolateTuning(tuningSnr, chromaTuningPoints),
globalStrengthScale = scale,
strengthLevelScales = PhotonCoreImagingTuning.denoise.chromaStrengthScale.toFloatArray(),
revertLevelScales = FloatArray(5) { 1f },
outlierLevelScales = FloatArray(5) { 1f },
)
/**
* GCam's low-frequency chroma branch for a tiled bitmap denoise: [rgba16f] holds the whole
* denoised linear image box-downsampled by 2^[log2Downsample] (lowWidth x lowHeight =
* ceil(full / 2^L)) and is replaced by the linear RGB correction to upsample bilinearly and
* add at full resolution. Uses the same model, chroma tuning and strength map as the tiles.
*/
fun lowFrequencyChromaBitmap(
rgba16f: ByteBuffer,
lowWidth: Int,
lowHeight: Int,
fullWidth: Int,
fullHeight: Int,
log2Downsample: Int,
noiseModel: PreparedYuvNoiseModel,
spatialStrengthQ8: ShortArray?,
tuningSnr: Float,
chromaStrengthScale: Float,
): Boolean {
val chromaScale = DenoiseStrength.clamp(chromaStrengthScale)
if (!initialized || !rgba16f.isDirect || chromaScale <= 0f) return false
val chromaTuning = bitmapChromaTuning(tuningSnr, chromaScale)
val coreTuning = PhotonCoreImagingTuning
rgba16f.clear()
val result = nativeLowFrequencyChromaCorrection(
rgbaBuffer = rgba16f,
lowWidth = lowWidth,
lowHeight = lowHeight,
fullWidth = fullWidth,
fullHeight = fullHeight,
log2Downsample = log2Downsample,
preparedNormalizedYuvRead = noiseModel.normalizedRead,
preparedNormalizedChromaShot = noiseModel.normalizedChromaShot,
preparedNormalizedChromaQuadratic = noiseModel.normalizedChromaQuadratic,
chromaCorrelation = noiseModel.chromaCorrelation,
denoiseResponseOffset = coreTuning.denoise.frequencyResponse.responseOffset,
denoiseResponseCosineOffset = coreTuning.denoise.frequencyResponse.cosineOffset,
spatialStrengthQ8 = spatialStrengthQ8,
spatialStrengthWidth = if (spatialStrengthQ8 != null) (fullWidth + 3) / 4 else 0,
spatialStrengthHeight = if (spatialStrengthQ8 != null) (fullHeight + 3) / 4 else 0,
chromaStrength = chromaTuning.strength,
chromaOutlierThreshold = chromaTuning.outlierDistance,
chromaMedianFilterType = coreTuning.denoise.chromaMedianFilterType,
)
rgba16f.position(0)
if (result != 0) {
PLog.e(
TAG,
"MGC bitmap low-frequency chroma failed: result=0x${result.toString(16)} " +
"low=${lowWidth}x$lowHeight full=${fullWidth}x$fullHeight",
)
return false
}
return true
}
private fun validPreparedYuvNoise(model: PreparedYuvNoiseModel): Boolean =
validRgbNoise(model.normalizedRead) &&
model.normalizedLumaShot.isFinite() && model.normalizedLumaShot >= 0f &&
@@ -769,6 +949,27 @@ internal object MgcFullResolutionDenoise {
return result.sortedBy(TuningPoint::snr)
}
private external fun nativeLowFrequencyChromaCorrection(
rgbaBuffer: ByteBuffer,
lowWidth: Int,
lowHeight: Int,
fullWidth: Int,
fullHeight: Int,
log2Downsample: Int,
preparedNormalizedYuvRead: FloatArray,
preparedNormalizedChromaShot: Float,
preparedNormalizedChromaQuadratic: Float,
chromaCorrelation: FloatArray,
denoiseResponseOffset: Float,
denoiseResponseCosineOffset: Float,
spatialStrengthQ8: ShortArray?,
spatialStrengthWidth: Int,
spatialStrengthHeight: Int,
chromaStrength: FloatArray,
chromaOutlierThreshold: FloatArray,
chromaMedianFilterType: Int,
): Int
private external fun nativeDenoiseRgba16f(
rgbaBuffer: ByteBuffer,
width: Int,
@@ -653,8 +653,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
if (!isRawInGallery(photo.id)) {
// 非 RAW 照片,先进行一次色度降噪
val lutProcessor = com.hinnka.mycamera.lut.LutImageProcessor()
val chromaDenoised = lutProcessor.applyChromaDenoise(bitmap, strength = 0.8f)
val lutProcessor = com.hinnka.mycamera.lut.LutImageProcessor(context)
val chromaDenoised = lutProcessor.applyChromaDenoise(
bitmap,
strength = 0.8f,
sensorIso = (photo.metadata ?: GalleryManager.loadMetadata(context, photo.id))?.iso,
)
lutProcessor.release()
if (chromaDenoised !== bitmap) {
bitmap.recycle()
@@ -3477,6 +3481,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val source = photonDenoiseSource(context, photo.id, metadata) ?: return@launch
val built = contentRepository.photoProcessor.updatePhotonDenoiseBase(
context, photo.id, source, noiseReduction, chromaNoiseReduction,
sensorIso = metadata.iso,
onBuild = { _isPhotonDenoising.value = true },
)
val strengths = noiseReduction to chromaNoiseReduction
@@ -3681,7 +3686,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val source = photonDenoiseSource(context, photo.id, finalMetadata)
if (strengths != null && source != null) {
contentRepository.photoProcessor.loadPhotonDenoiseBase(
context, photo.id, source, strengths.first, strengths.second, maxEdge,
context, photo.id, source, strengths.first, strengths.second,
sensorIso = finalMetadata.iso,
maxEdge = maxEdge,
)
} else {
null
@@ -1,60 +0,0 @@
package com.hinnka.mycamera.lut
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ChromaDenoiseShadersTest {
@Test
fun rawOpponentValuesStayInOneLinearCameraRgbDomain() {
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
assertTrue(shader.contains("rgb.r - rgb.g"))
assertTrue(shader.contains("rgb.b - rgb.g"))
assertTrue(shader.contains("(rgb.r + rgb.g + rgb.b) / 3.0"))
assertTrue(shader.contains("value.x - (value.y + value.z) / 3.0"))
assertTrue(shader.contains("green + value.y"))
assertTrue(shader.contains("green + value.z"))
assertFalse(shader.contains("cameraChromaScale"))
}
@Test
fun rawNeighborMeanIsNormalizedBackToTheCenterSignal() {
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
assertTrue(shader.contains("sumSignal += sampleValue.x * weight"))
assertTrue(shader.contains("centerSignal / max(averageSignal, 1e-6)"))
assertTrue(shader.contains("averageChroma * signalScale"))
}
@Test
fun rawOpponentAndGuideBandwidthsIncludeGreenNoise() {
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
assertTrue(shader.contains("uniform vec2 uNoiseModelG;"))
assertTrue(shader.contains("variance.rb + variance.gg"))
assertTrue(shader.contains("variance.r + variance.g + variance.b"))
}
@Test
fun everyScaleUsesTheSameBoundedChromaEdgeThreshold() {
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
assertTrue(shader.contains("exp(-chromaDistance)"))
assertTrue(shader.contains("float chromaEdgeSigmaMultiplier"))
assertFalse(shader.contains("signalSnr"))
assertFalse(shader.contains("cloudRadius"))
assertFalse(shader.contains("vec2 cloudH"))
}
@Test
fun rawCameraRgbUsesSymmetricLuminanceInsteadOfGreenGuide() {
val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE
assertTrue(shader.contains("texture(uGuideTexture, sampleCoord).r - centerGuide"))
assertTrue(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains(
"(rgb.r + rgb.g + rgb.b) / 3.0"
))
assertFalse(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains("return rgb.g"))
}
}
@@ -1,6 +1,5 @@
package com.hinnka.mycamera.processor
import com.hinnka.mycamera.lut.ChromaDenoiseDefaults
import org.junit.Assert.assertEquals
import org.junit.Test
@@ -13,20 +12,4 @@ class DenoiseStrengthTest {
assertEquals(0f, DenoiseStrength.clamp(Float.NaN), 0f)
assertEquals(0f, DenoiseStrength.clamp(Float.POSITIVE_INFINITY), 0f)
}
@Test
fun strengthAboveOneScalesNoiseVarianceQuadratically() {
assertEquals(1f, DenoiseStrength.noiseVarianceScale(0.5f), 0f)
assertEquals(1f, DenoiseStrength.noiseVarianceScale(1f), 0f)
assertEquals(2.25f, DenoiseStrength.noiseVarianceScale(1.5f), 0f)
assertEquals(4f, DenoiseStrength.noiseVarianceScale(2f), 0f)
assertEquals(1f, DenoiseStrength.outputMix(2f), 0f)
}
@Test
fun chromaBandwidthContinuesGrowingAboveOne() {
assertEquals(8f, ChromaDenoiseDefaults.noiseBandwidth(1f), 0f)
assertEquals(15f, ChromaDenoiseDefaults.noiseBandwidth(2f), 0f)
assertEquals(15f, ChromaDenoiseDefaults.noiseBandwidth(3f), 0f)
}
}
@@ -178,87 +178,4 @@ class RawNoiseProfileSelectionTest {
0f,
)
}
@Test
fun denoiseProfileShaderUsesCameraDomainSignalScaleInsteadOfWhiteBalanceScale() {
val shader = DenoiseProfileShaders.PRECONDITION_V2 + DenoiseProfileShaders.FINISH_V2
assertTrue(shader.contains("uniform vec4 uSignalScale;"))
assertTrue(shader.contains("pixel / uSignalScale"))
assertTrue(shader.contains("px *= uSignalScale"))
assertFalse(shader.contains("uWb"))
}
@Test
fun nlmSearchOffsetsCoverSymmetricWindowExactlyOnce() {
val radius = DenoiseProfileShaders.SEARCH_RADIUS
val candidates = buildList {
DenoiseProfileNlmConfig.buildSearchOffsets(radius).forEach { q ->
add(q.x to q.y)
if (q.x != 0 || q.y != 0) {
add(-q.x to -q.y)
}
}
}
val windowWidth = 2 * radius + 1
assertEquals(windowWidth * windowWidth, candidates.size)
assertEquals(candidates.size, candidates.toSet().size)
assertTrue(candidates.all { (x, y) -> x in -radius..radius && y in -radius..radius })
}
@Test
fun nlmWeightTuningSubtractsVarianceStabilizedNoiseFloor() {
val tuning = DenoiseProfileNlmConfig.weightTuning(
DenoiseProfileShaders.PATCH_RADIUS
)
assertEquals(54f, tuning.expectedFineDistance, 0f)
assertEquals(2.53125f, tuning.expectedGuideDistance, 1e-6f)
assertEquals(1f / 54f, tuning.inverseBandwidth, 1e-7f)
assertEquals(8f, tuning.coarseGuideWeight, 0f)
}
@Test
fun nlmShaderUsesCoarseGuideAndExplicitNoiseFloor() {
val shader = DenoiseProfileShaders.PRECONDITION_V2 +
DenoiseProfileShaders.FUSED_ACCU +
DenoiseProfileShaders.FINISH_V2
assertTrue(shader.contains("t.a = guide"))
assertTrue(shader.contains("uExpectedFineDistance"))
assertTrue(shader.contains("uExpectedGuideDistance"))
assertTrue(shader.contains("uCoarseGuideWeight"))
assertTrue(shader.contains("uDenoiseMix"))
assertFalse(shader.contains("distacc * uNorm - 2.0"))
}
@Test
fun zeroBiasBacktransformExactlyPreservesAnUnchangedDarkSample() {
val input = 0.003f
val signalScale = 0.38f
val a = 0.0089f
val b = 3.55e-7f
val p = 0.62f
val transformed = 2f * max(input / signalScale + b, 0f).pow(1f - p / 2f) /
((2f - p) * sqrt(a))
val delta = transformed * transformed + DenoiseProfileShaders.BLACK_PRESERVING_BIAS
val denominator = 4f / (sqrt(a) * (2f - p))
val z1 = (transformed + sqrt(max(delta, 0f))) / denominator
val restored = max(z1.pow(1f / (1f - p / 2f)) - b, 0f) * signalScale
assertEquals(0f, DenoiseProfileShaders.BLACK_PRESERVING_BIAS, 0f)
assertEquals(input, restored, 1e-6f)
}
@Test
fun nlmStripeShaderKeepsSamplingInFullImageCoordinates() {
val shader = DenoiseProfileShaders.FUSED_ACCU + DenoiseProfileShaders.FINISH_V2
assertTrue(shader.contains("uStripeRowOffset"))
assertTrue(shader.contains("coord = stripeCoord + ivec2(0, uStripeRowOffset)"))
assertTrue(shader.contains("stripeCoord.y * uImageSize.x + stripeCoord.x"))
assertFalse(shader.contains("pixelIndex(coord, uImageSize)"))
}
}