feat: Photon denoiser (2)

This commit is contained in:
zhoubinjia committed 2026-10-29 14:17:45 +08:00
1 parent bef83e201d
commit 5491b494d7
11 files changed
+1042 -211

No files matched your search

@@ -14,6 +14,7 @@ import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import com.hinnka.mycamera.processor.DenoiseStrength
import com.hinnka.mycamera.raw.denoise.PhotonDenoiseDump
import com.hinnka.mycamera.raw.denoise.PhotonMultiScaleDenoiser
import com.hinnka.mycamera.raw.denoise.PhotonNoiseModel
import com.hinnka.mycamera.utils.LargeDirectBuffer
@@ -83,7 +84,6 @@ class LutImageProcessor(context: Context? = null) {
private var texCoordBuffer: FloatBuffer? = null
private var indexBuffer: ShortBuffer? = null
private var bitmapSrgbTransferProgram = 0
private var bitmapDenoisePassthroughProgram = 0
private var computeCapabilitiesChecked = false
private var computeCapabilitiesSupported = false
@@ -1271,7 +1271,7 @@ class LutImageProcessor(context: Context? = null) {
)
}
/** The Photon denoiser and the sRGB transfer passes around it (docs/photon-multiscale-denoise.md §9). */
/** The Photon denoiser and the copy passes around it (docs/photon-multiscale-denoise.md §9). */
private fun ensureBitmapPhotonDenoisePrograms(): Boolean {
if (!computeCapabilitiesChecked) {
computeCapabilitiesSupported = logAndValidateComputeCapabilities()
@@ -1279,14 +1279,7 @@ class LutImageProcessor(context: Context? = null) {
}
if (!computeCapabilitiesSupported) return false
ensureBitmapDenoisePassthroughProgram()
if (bitmapSrgbTransferProgram == 0) {
bitmapSrgbTransferProgram = createFragmentProgram(
IMAGE_VERTEX_SHADER,
SRGB_TRANSFER_SHADER,
"BitmapDenoise_SrgbTransfer",
)
}
return bitmapSrgbTransferProgram != 0 && bitmapDenoisePassthroughProgram != 0 &&
return bitmapDenoisePassthroughProgram != 0 &&
bitmapPhotonDenoiser.initialize()
}
@@ -1405,9 +1398,11 @@ class LutImageProcessor(context: Context? = null) {
}
/**
* §9: sRGB → linear, the Photon denoiser on the nominal Bitmap profile, linear → sRGB.
* The result is in bitmapDenoiseTexId[1]; returns false (result not written) when either
* strength is zero for both or the compute path is unavailable.
* §9 blind denoise of an ISP-processed Bitmap: the Photon denoiser runs on the sRGB-encoded
* values with the fixed BITMAP strengths (no noise model of the source). The input is copied to
* RGBA16F first so the denoiser (and the debug dump) read the same texture. The result is in
* bitmapDenoiseTexId[1]; returns false (result not written) when both strengths are zero or
* the compute path is unavailable.
*/
private fun renderBitmapPhotonDenoise(
sourceTextureId: Int,
@@ -1424,13 +1419,19 @@ class LutImageProcessor(context: Context? = null) {
return false
}
setupBitmapDenoiseFramebuffers(width, height)
renderSrgbTransfer(sourceTextureId, bitmapDenoiseFboId[0], width, height, encode = false)
renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[0], width, height)
val params = PhotonNoiseModel.buildBitmap(width, height, lumaStrength, chromaStrength)
if (PhotonDenoiseDump.enabled) {
appContext?.let { context ->
PhotonDenoiseDump.write(context, "${params.pipeline.name}_EDIT", bitmapDenoiseTexId[0], width, height,
metadata = null, params = params, lensShadingSource = null)
} ?: PLog.w(TAG, "Bitmap denoise dump skipped: LutImageProcessor has no context")
}
val denoised = checkNotNull(bitmapPhotonDenoiser.denoise(bitmapDenoiseTexId[0], width, height, params)) {
"Photon denoise programs are unavailable"
}
try {
renderSrgbTransfer(denoised, bitmapDenoiseFboId[1], width, height, encode = true)
renderTexturePassthrough(denoised, bitmapDenoiseFboId[1], width, height)
} finally {
GLES30.glDeleteTextures(1, intArrayOf(denoised), 0)
}
@@ -1438,26 +1439,6 @@ class LutImageProcessor(context: Context? = null) {
return true
}
private fun renderSrgbTransfer(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int, encode: Boolean) {
GLES30.glUseProgram(bitmapSrgbTransferProgram)
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(bitmapSrgbTransferProgram, "uInputTexture"), 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapSrgbTransferProgram, "uEncode"), if (encode) 1 else 0)
val identityMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(identityMatrix, 0)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(bitmapSrgbTransferProgram, "uMVPMatrix"),
1,
false,
identityMatrix,
0
)
drawQuad(bitmapSrgbTransferProgram)
}
private fun renderTexturePassthrough(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int) {
GLES30.glUseProgram(bitmapDenoisePassthroughProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
@@ -2246,7 +2227,6 @@ class LutImageProcessor(context: Context? = null) {
}
releaseReadbackBuffer()
if (bitmapSrgbTransferProgram != 0) GLES30.glDeleteProgram(bitmapSrgbTransferProgram)
if (bitmapDenoisePassthroughProgram != 0) GLES30.glDeleteProgram(bitmapDenoisePassthroughProgram)
bitmapPhotonDenoiser.release()
if (lutSharpenProgram != 0) {
@@ -2331,32 +2311,6 @@ class LutImageProcessor(context: Context? = null) {
}
""".trimIndent()
/** sRGB transfer curve, decode (uEncode = 0) or encode, on RGB; alpha passes through. */
private val SRGB_TRANSFER_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform highp sampler2D uInputTexture;
uniform int uEncode;
vec3 decode(vec3 v) {
return mix(v / 12.92, pow((v + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), v));
}
vec3 encode(vec3 v) {
v = max(v, vec3(0.0));
return mix(v * 12.92, 1.055 * pow(v, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), v));
}
void main() {
vec4 c = texture(uInputTexture, vTexCoord);
fragColor = vec4(uEncode == 1 ? encode(c.rgb) : decode(max(c.rgb, vec3(0.0))), c.a);
}
""".trimIndent()
private val LUT_LUMINANCE_GAIN_SHADER = """
#version 300 es
precision highp float;
@@ -518,6 +518,9 @@ internal class GlesMgcRawSpatialStacker(
private var sabreCopyMaskProgram = 0
private var sabreCopyAlphaProgram = 0
private var sabreDehomogenizeProgram = 0
/** §2.2 merge variance accumulator of the merge in flight; released with the merge. */
private var mergeNoise: PhotonMergeNoise? = null
private var sabreOutputTransformProgram = 0
private var currentMergeCovariance = 0
private var mergeRgbProgram = 0
@@ -820,11 +823,15 @@ internal class GlesMgcRawSpatialStacker(
RawDenoisePipeline.SPATIAL,
referenceCalibration.cameraRgbReadNoise,
referenceCalibration.cameraRgbShotNoise,
)
fun admitMergeNoise(calibration: FrameCalibration) = photonMergeNoise.add(
width,
height,
).also { mergeNoise = it }
// [acceptance] is the weight texture the merge samples for this frame (0: none).
fun admitMergeNoise(calibration: FrameCalibration, acceptance: Int) = photonMergeNoise.add(
calibration.globalFrameWeight,
calibration.cameraRgbReadNoise,
calibration.cameraRgbShotNoise,
acceptance,
)
PLog.i(
TAG,
@@ -1539,18 +1546,19 @@ internal class GlesMgcRawSpatialStacker(
),
)
}
admitMergeNoise(referenceCalibration)
val baseAcceptance = when {
identityTemporalWeights -> identityWeight
outputMode == MgcSpatialOutputMode.RGB -> bentoRgbBaseRejection
else -> bentoBaseWeight
}
admitMergeNoise(referenceCalibration, baseAcceptance)
strengthCapture?.let { capture ->
captureStrengthFrame(
capture = capture,
frameIndex = capturedFrameIndex++,
calibration = referenceCalibration,
alignmentTexture = zeroFlow,
rejectionTexture = when {
identityTemporalWeights -> identityWeight
outputMode == MgcSpatialOutputMode.RGB -> bentoRgbBaseRejection
else -> bentoBaseWeight
},
rejectionTexture = baseAcceptance,
identityRejection = identityTemporalWeights,
)
}
@@ -1580,23 +1588,23 @@ internal class GlesMgcRawSpatialStacker(
),
)
}
admitMergeNoise(checkNotNull(bentoCalibration))
val shortAcceptance = when {
identityTemporalWeights -> identityWeight
// bentoMask is on the RAW/2 guide domain. RGB AOT consumes an
// exact RAW/4 rejection/acceptance plane, so use the already
// resampled selected-short weight instead of cropping the RAW/2
// texture through strengthRejection's exact-domain texelFetch.
outputMode == MgcSpatialOutputMode.RGB -> diagnosticBentoShortWeight
else -> bentoShortWeight
}
admitMergeNoise(checkNotNull(bentoCalibration), shortAcceptance)
strengthCapture?.let { capture ->
captureStrengthFrame(
capture = capture,
frameIndex = capturedFrameIndex++,
calibration = checkNotNull(bentoCalibration),
alignmentTexture = bentoBayerAlignmentTexture,
rejectionTexture = when {
identityTemporalWeights -> identityWeight
// bentoMask is on the RAW/2 guide domain. RGB AOT consumes an
// exact RAW/4 rejection/acceptance plane, so use the already
// resampled selected-short weight instead of cropping the RAW/2
// texture through strengthRejection's exact-domain texelFetch.
outputMode == MgcSpatialOutputMode.RGB ->
diagnosticBentoShortWeight
else -> bentoShortWeight
},
rejectionTexture = shortAcceptance,
identityRejection = identityTemporalWeights,
)
}
@@ -1627,7 +1635,8 @@ internal class GlesMgcRawSpatialStacker(
),
)
}
admitMergeNoise(referenceCalibration)
// Merged without a frame weight texture: acceptance 1 everywhere.
admitMergeNoise(referenceCalibration, 0)
strengthCapture?.let { capture ->
captureStrengthFrame(
capture = capture,
@@ -1806,18 +1815,19 @@ internal class GlesMgcRawSpatialStacker(
),
)
}
admitMergeNoise(prepared.calibration)
val frameAcceptance = if (outputMode == MgcSpatialOutputMode.RGB) {
rgbAotRejection
} else {
mergeWeight
}
admitMergeNoise(prepared.calibration, frameAcceptance)
strengthCapture?.let { capture ->
captureStrengthFrame(
capture = capture,
frameIndex = capturedFrameIndex++,
calibration = prepared.calibration,
alignmentTexture = prepared.bayerAlignmentTexture,
rejectionTexture = if (outputMode == MgcSpatialOutputMode.RGB) {
rgbAotRejection
} else {
mergeWeight
},
rejectionTexture = frameAcceptance,
identityRejection = identityTemporalWeights,
)
}
@@ -1971,7 +1981,10 @@ internal class GlesMgcRawSpatialStacker(
},
lensShadingCorrectionApplied = lensShadingCorrectionApplied,
mergedFrameCount = mergedFrames,
denoiseHistory = photonMergeNoise.history(outputExposure.normalizationScale),
denoiseHistory = photonMergeNoise.history(
bayerKernelTuning.referenceSignal,
outputExposure.normalizationScale,
),
mgcSharpenTuningSnr = bayerKernelTuning.referenceSnr,
mgcSharpenAttenuationScale = finishRawSharpenAttenuationScale,
mgcSpatialReferenceOnlyDiagnostic = referenceOnly,
@@ -2155,8 +2168,11 @@ internal class GlesMgcRawSpatialStacker(
RawDenoisePipeline.SABRE,
referenceCalibration.cameraRgbReadNoise,
referenceCalibration.cameraRgbShotNoise,
).apply {
add(1f, referenceCalibration.cameraRgbReadNoise, referenceCalibration.cameraRgbShotNoise)
width,
height,
).also { mergeNoise = it }.apply {
// The reference merges without a frame weight texture (useFrameWeight = false).
add(1f, referenceCalibration.cameraRgbReadNoise, referenceCalibration.cameraRgbShotNoise, 0)
}
val sabreResolveFinalBlackLevel =
sabreResolveBlackLevel(referenceCalibration.blackLevels)
@@ -2229,7 +2245,6 @@ internal class GlesMgcRawSpatialStacker(
referenceExposure / validExposureProduct(frame.exposureProduct)
).toFloat().coerceIn(MIN_EXPOSURE_SCALE, MAX_EXPOSURE_SCALE)
val calibration = calibrationForFrame(frame, exposureScale, kernelTuning)
photonMergeNoise.add(1f, calibration.cameraRgbReadNoise, calibration.cameraRgbShotNoise)
uploadRaw(images[index], currentRaw, "Sabre frame $index")
renderSabreExtract(currentRaw, currentExtracted, extractedWidth, extractedHeight)
val noiseTexture = createSabreNoiseLut(referenceCalibration, calibration)
@@ -2304,6 +2319,7 @@ internal class GlesMgcRawSpatialStacker(
coverageHeight,
accumulatedWeightScale,
)
photonMergeNoise.add(1f, calibration.cameraRgbReadNoise, calibration.cameraRgbShotNoise, frameWeight)
renderSabreMerge(
extracted = currentExtracted,
flow = flow,
@@ -2497,7 +2513,7 @@ internal class GlesMgcRawSpatialStacker(
},
lensShadingCorrectionApplied = hasLensShading(),
mergedFrameCount = frames.size,
denoiseHistory = photonMergeNoise.history(),
denoiseHistory = photonMergeNoise.history(kernelTuning.referenceSignal),
mgcSharpenTuningSnr = kernelTuning.referenceSnr,
mgcSharpenAttenuationScale = sabreResolveParameters.demosaicSharpness,
)
@@ -9082,6 +9098,8 @@ internal class GlesMgcRawSpatialStacker(
private fun release() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
mergeNoise?.release()
mergeNoise = null
noiseLutCache.clear()
globalAlignment?.release()
globalAlignment = null
@@ -1222,11 +1222,13 @@ class RawDemosaicProcessor {
width, height, metadata, params, lensShadingSource)
}
val denoiseStartNs = System.nanoTime()
// §5.1: the table applied here is recorded for later passes over the output.
val strength = FloatArray(params.levels * RawDenoiseHistory.STRENGTH_ENTRIES)
denoisedTexture = checkNotNull(
photonDenoiser.denoise(workingFloatTexture, width, height, params),
photonDenoiser.denoise(workingFloatTexture, width, height, params, strength),
) { "Photon $mode denoise programs are unavailable" }
denoiseMs = (System.nanoTime() - denoiseStartNs) / 1_000_000L
outputHistory = params.outputHistory()
outputHistory = params.outputHistory(strength)
} else {
PLog.i(
TAG,
@@ -7637,14 +7639,20 @@ class RawDemosaicProcessor {
) { "RAW HDR reference pass failed" }
}
/** MGC sharpen tuning SNR from one native RAW measurement; merged captures carry the reference frame's. */
/**
* One native measurement of the mean green signal (MGC EstimateSnr's mean): the MGC sharpen
* tuning SNR (merged captures carry the reference frame's) and the denoiser's image SNR signal
* (docs/photon-multiscale-denoise.md §5.1).
*/
private fun RawMetadata.withMgcRenderTuning(
rawData: ByteBuffer?,
rowStride: Int,
samplesPerPixel: Int,
): RawMetadata {
// Guided reconstruction is still required when the sharpening slider is zero.
if (mgcSharpenTuningSnr != null) return this
val needsSharpenSnr = mgcSharpenTuningSnr == null
val needsDenoiseSignal = denoiseSignal == null
if (!needsSharpenSnr && !needsDenoiseSignal) return this
val signalStartNs = System.nanoTime()
val measuredSignal = rawData?.let { estimateMgcReferenceSignal(
rawData = it,
@@ -7655,6 +7663,8 @@ class RawDemosaicProcessor {
// Photon does not carry MGC's unapplied gain; do not substitute display EV.
val signal = measuredSignal ?: 0.18f
val signalElapsedMs = (System.nanoTime() - signalStartNs) / 1_000_000L
val measured = if (needsDenoiseSignal && measuredSignal != null) copy(denoiseSignal = measuredSignal) else this
if (!needsSharpenSnr) return measured
val noiseModel = when (noiseProfileLayout) {
RawNoiseProfileLayout.CAMERA2_CFA ->
RawNoiseModel.fromCamera2NoiseProfile(channelNoiseProfile)
@@ -7692,7 +7702,7 @@ class RawDemosaicProcessor {
"signalSource=${if (measuredSignal != null) "NATIVE_OMP" else "MGC_MISSING_MEAN"} " +
"signalMs=$signalElapsedMs",
)
return copy(mgcSharpenTuningSnr = snr)
return measured.copy(mgcSharpenTuningSnr = snr)
}
private fun RawMetadata.estimateMgcReferenceSignal(
@@ -1,27 +1,74 @@
package com.hinnka.mycamera.raw
import android.util.Base64
import android.util.Half
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** Pipelines with separate denoise tuning tables (docs/photon-multiscale-denoise.md §5). */
enum class RawDenoisePipeline { VGN, QUAD, SABRE, SPATIAL, BITMAP }
/**
* Per-pixel merge variance ratios (docs/photon-multiscale-denoise.md §2.2): [values] holds
* (m_r, m_s) interleaved on a [width] × [height] grid spanning the whole image; cell (i, j)
* covers the normalized rectangle [i, i + 1) / width × [j, j + 1) / height and is sampled
* bilinearly at cell centres.
*/
data class RawMergeVarianceMap(
val width: Int,
val height: Int,
val values: FloatArray,
) {
val isValid: Boolean
get() = width > 0 && height > 0 && values.size == width * height * 2 &&
values.all { it.isFinite() && it > 0f }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is RawMergeVarianceMap) return false
return width == other.width && height == other.height && values.contentEquals(other.values)
}
override fun hashCode(): Int {
var result = values.contentHashCode()
result = 31 * result + width
result = 31 * result + height
return result
}
}
/**
* Noise state of pixels produced by a merge and/or an earlier denoise
* (docs/photon-multiscale-denoise.md §2.2, §2.4).
*
* [pipeline] is the pipeline that produced the pixels, which selects the tuning table.
* [mergeRead] / [mergeShot] scale the reference frame's read / shot coefficients to the merged
* pixels (§2.2, including the merge's output exposure). [residual] holds the residual variance
* pixels when every frame is accepted (§2.2, including the merge's output exposure); they select
* pixel-independent quantities. [mergeMap] holds the per-pixel ratios (null: the scalars hold
* everywhere). [signal] is the mean green signal of the merged pixels (MGC EstimateSnr's mean at
* the reference frame, times the output exposure), the §5.1 image SNR signal when the pixels are not
* on the CPU. [residual] holds the residual variance
* ratio t² per pyramid level as (Y, Cb, Cr); null means the pixels have not been denoised.
* Levels beyond [residual] were left untouched and keep ratio 1.
* Levels beyond [residual] were left untouched and keep ratio 1. [strength] is the §5.1 strength
* table of the source noise, [STRENGTH_ENTRIES] values per level as (bin, Y / Cb / Cr), recorded
* when the pixels were denoised (null: estimated again from the pixels).
*/
data class RawDenoiseHistory(
val pipeline: RawDenoisePipeline,
val mergeRead: Float,
val mergeShot: Float,
val residual: List<FloatArray>? = null,
val mergeMap: RawMergeVarianceMap? = null,
val signal: Float? = null,
val strength: FloatArray? = null,
) {
val isValid: Boolean
get() = mergeRead.isFinite() && mergeRead > 0f && mergeShot.isFinite() && mergeShot > 0f &&
residual?.all { level -> level.size == 3 && level.all { it.isFinite() && it in 0f..1f } } != false
mergeMap?.isValid != false && signal?.let { it.isFinite() && it >= 0f } != false &&
residual?.all { level -> level.size == 3 && level.all { it.isFinite() && it in 0f..1f } } != false &&
strength?.let { table ->
table.isNotEmpty() && table.size % STRENGTH_ENTRIES == 0 && table.all { it.isFinite() && it >= 0f }
} != false
/** t² of [level] as (Y, Cb, Cr). */
fun residualAt(level: Int): FloatArray = residual?.getOrNull(level)?.copyOf() ?: floatArrayOf(1f, 1f, 1f)
@@ -30,6 +77,8 @@ data class RawDenoiseHistory(
if (this === other) return true
if (other !is RawDenoiseHistory) return false
if (pipeline != other.pipeline || mergeRead != other.mergeRead || mergeShot != other.mergeShot) return false
if (mergeMap != other.mergeMap || signal != other.signal) return false
if (!(strength contentEquals other.strength)) return false
val a = residual
val b = other.residual
if (a == null || b == null) return a == b
@@ -41,10 +90,17 @@ data class RawDenoiseHistory(
result = 31 * result + mergeRead.hashCode()
result = 31 * result + mergeShot.hashCode()
result = 31 * result + (residual?.fold(0) { acc, level -> 31 * acc + level.contentHashCode() } ?: 0)
result = 31 * result + (mergeMap?.hashCode() ?: 0)
result = 31 * result + (signal?.hashCode() ?: 0)
result = 31 * result + (strength?.contentHashCode() ?: 0)
return result
}
companion object {
/** §5.1 luma bins × (Y, Cb, Cr) per level of [strength]. */
const val STRENGTH_BINS = 8
const val STRENGTH_ENTRIES = STRENGTH_BINS * 3
/** A single, not yet denoised frame of [pipeline]. */
fun singleFrame(pipeline: RawDenoisePipeline) = RawDenoiseHistory(pipeline, 1f, 1f)
}
@@ -55,14 +111,25 @@ internal object RawDenoiseHistoryMetadata {
private const val PIPELINE_PROPERTY = "photonDenoisePipeline"
private const val MERGE_PROPERTY = "photonDenoiseMerge"
private const val RESIDUAL_PROPERTY = "photonDenoiseResidual"
private const val MERGE_MAP_PROPERTY = "photonDenoiseMergeMap"
private const val MERGE_MAP_SIZE_PROPERTY = "photonDenoiseMergeMapSize"
private const val SIGNAL_PROPERTY = "photonDenoiseSignal"
private const val STRENGTH_PROPERTY = "photonDenoiseStrength"
private const val CONTRACT_PROPERTY = "photonDenoiseHistoryContract"
private const val CURRENT_CONTRACT = "pipeline_merge_read_shot_residual_level_y_cb_cr_v1"
private const val CURRENT_CONTRACT = "pipeline_merge_read_shot_residual_level_y_cb_cr_map_rg_f16le_signal_strength_level_bin_y_cb_cr_v4"
// Same fields without the §5.1 strength table, which is then estimated from the pixels.
private const val CONTRACT_V3 = "pipeline_merge_read_shot_residual_level_y_cb_cr_map_rg_f16le_signal_v3"
fun write(properties: Map<String, String>, value: RawDenoiseHistory?): Map<String, String> {
val out = properties.toMutableMap()
out.remove(PIPELINE_PROPERTY)
out.remove(MERGE_PROPERTY)
out.remove(RESIDUAL_PROPERTY)
out.remove(MERGE_MAP_PROPERTY)
out.remove(MERGE_MAP_SIZE_PROPERTY)
out.remove(SIGNAL_PROPERTY)
out.remove(STRENGTH_PROPERTY)
out.remove(CONTRACT_PROPERTY)
if (value == null) return out
require(value.isValid) { "Denoise history is malformed" }
@@ -71,12 +138,21 @@ internal object RawDenoiseHistoryMetadata {
value.residual?.let { levels ->
out[RESIDUAL_PROPERTY] = levels.joinToString(";") { it.joinToString(",") }
}
value.mergeMap?.let { map ->
val bytes = ByteBuffer.allocate(map.values.size * 2).order(ByteOrder.LITTLE_ENDIAN)
map.values.forEach { bytes.putShort(Half.toHalf(it)) }
out[MERGE_MAP_PROPERTY] = Base64.encodeToString(bytes.array(), Base64.NO_WRAP)
out[MERGE_MAP_SIZE_PROPERTY] = "${map.width}x${map.height}"
}
value.signal?.let { out[SIGNAL_PROPERTY] = it.toString() }
value.strength?.let { out[STRENGTH_PROPERTY] = it.joinToString(",") }
out[CONTRACT_PROPERTY] = CURRENT_CONTRACT
return out
}
fun read(properties: Map<String, String>): RawDenoiseHistory? {
if (properties[CONTRACT_PROPERTY] != CURRENT_CONTRACT) return null
val contract = properties[CONTRACT_PROPERTY]
if (contract != CURRENT_CONTRACT && contract != CONTRACT_V3) return null
val pipeline = RawDenoisePipeline.entries.firstOrNull { it.name == properties[PIPELINE_PROPERTY] }
?: return null
val merge = properties[MERGE_PROPERTY]?.split(',')?.mapNotNull(String::toFloatOrNull)
@@ -86,6 +162,19 @@ internal object RawDenoiseHistoryMetadata {
level.split(',').mapNotNull(String::toFloatOrNull).toFloatArray()
}
}
return RawDenoiseHistory(pipeline, merge[0], merge[1], residual).takeIf { it.isValid }
val mergeMap = properties[MERGE_MAP_PROPERTY]?.let { encoded ->
val size = properties[MERGE_MAP_SIZE_PROPERTY]?.split('x')?.mapNotNull(String::toIntOrNull)
?.takeIf { it.size == 2 } ?: return null
val bytes = runCatching { Base64.decode(encoded, Base64.NO_WRAP) }.getOrNull() ?: return null
if (bytes.size % 2 != 0) return null
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
RawMergeVarianceMap(size[0], size[1], FloatArray(bytes.size / 2) { Half.toFloat(buffer.getShort()) })
}
val signal = properties[SIGNAL_PROPERTY]?.let { it.toFloatOrNull() ?: return null }
val strength = properties[STRENGTH_PROPERTY]?.takeIf { contract == CURRENT_CONTRACT }?.let { encoded ->
encoded.split(',').map { it.toFloatOrNull() ?: return null }.toFloatArray()
}
return RawDenoiseHistory(pipeline, merge[0], merge[1], residual, mergeMap, signal, strength)
.takeIf { it.isValid }
}
}
@@ -161,6 +161,12 @@ data class RawMetadata(
*/
val denoiseHistory: RawDenoiseHistory? = null,
/**
* 本次渲染测得的平均绿色信号(归一化、未白平衡,MGC EstimateSnr 的均值),用于降噪的整图 SNR,
* 见 docs/photon-multiscale-denoise.md §5.1。仅进程内;没有 CPU 像素时为 null。
*/
val denoiseSignal: Float? = null,
/**
* 数字增益 (Post RAW Boost)
*/
@@ -1172,6 +1178,7 @@ data class RawMetadata(
if (!cameraWhite.contentEquals(other.cameraWhite)) return false
if (appliedLensShading != other.appliedLensShading) return false
if (denoiseHistory != other.denoiseHistory) return false
if (denoiseSignal != other.denoiseSignal) return false
if (baselineExposure != other.baselineExposure) return false
if (shadowScale != other.shadowScale) return false
if (iso != other.iso) return false
@@ -1208,6 +1215,7 @@ data class RawMetadata(
result = 31 * result + (lensShadingMapGrid?.contentHashCode() ?: 0)
result = 31 * result + (appliedLensShading?.hashCode() ?: 0)
result = 31 * result + (denoiseHistory?.hashCode() ?: 0)
result = 31 * result + (denoiseSignal?.hashCode() ?: 0)
result = 31 * result + postRawSensitivityBoost.hashCode()
result = 31 * result + baselineExposure.hashCode()
result = 31 * result + shadowScale.hashCode()
@@ -32,7 +32,8 @@ internal object PhotonDenoiseDump {
SystemPropertiesUtil.get("debug.photon.denoise.dump")?.toBooleanStrictOrNull() == true
/**
* Dumps [inputTexture] (RGBA16F camera RGB as the denoiser receives it) with its metadata
* Dumps [inputTexture] (RGBA16F camera RGB, or linear sRGB for a Bitmap with [metadata] null,
* as the denoiser receives it) with its metadata
* and the noise model [params] (`<stem>.params.json`, read by tools/photon_denoise), and,
* when [parityEnabled], the pass-by-pass parity dump. [lensShadingSource] names where the
* LSC gains in the pixels come from ("merge", "demosaic"). Must run on the GL thread that
@@ -44,7 +45,7 @@ internal object PhotonDenoiseDump {
inputTexture: Int,
width: Int,
height: Int,
metadata: RawMetadata,
metadata: RawMetadata?,
params: PhotonDenoiseParams,
lensShadingSource: String?,
) {
@@ -101,21 +102,31 @@ internal object PhotonDenoiseDump {
val denoiser = PhotonMultiScaleDenoiser()
val startNs = System.nanoTime()
runCatching {
val output = denoiser.denoise(inputTexture, width, height, params) { name, texture, w, h, float32 ->
val buffer = readTexture(texture, w, h, float32)
val suffix = if (float32) "f32" else "f16"
FileOutputStream(File(directory, "$stem.$name.$suffix")).use { Channels.newChannel(it).write(buffer) }
passes.put(JSONObject().apply {
put("name", name)
put("width", w)
put("height", h)
put("format", suffix)
})
} ?: error("Photon denoiser programs are unavailable")
var strength: FloatArray? = null
val sink = object : PhotonMultiScaleDenoiser.PassSink {
override fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean) {
val buffer = readTexture(textureId, width, height, float32)
val suffix = if (float32) "f32" else "f16"
FileOutputStream(File(directory, "$stem.$name.$suffix")).use { Channels.newChannel(it).write(buffer) }
passes.put(JSONObject().apply {
put("name", name)
put("width", width)
put("height", height)
put("format", suffix)
})
}
override fun onStrength(table: FloatArray) {
strength = table
}
}
val output = denoiser.denoise(inputTexture, width, height, params, sink = sink)
?: error("Photon denoiser programs are unavailable")
GLES30.glDeleteTextures(1, intArrayOf(output), 0)
File(directory, "$stem.photon.json").writeText(JSONObject().apply {
put("params", params.toJson())
put("passes", passes)
strength?.let { put("strength", JSONArray(it.map(Float::toDouble))) }
}.toString(2))
PLog.i(TAG, "Photon parity dumped: $stem passes=${passes.length()} " +
"ms=${(System.nanoTime() - startNs) / 1_000_000L}")
@@ -126,7 +137,7 @@ internal object PhotonDenoiseDump {
private fun describe(
width: Int,
height: Int,
metadata: RawMetadata,
metadata: RawMetadata?,
params: PhotonDenoiseParams,
lensShadingSource: String?,
): JSONObject = JSONObject().apply {
@@ -138,12 +149,19 @@ internal object PhotonDenoiseDump {
put("originY", params.originY)
put("fullWidth", params.fullWidth)
put("fullHeight", params.fullHeight)
put("cfaPattern", metadata.cfaPattern)
put("frameCount", metadata.frameCount)
put("iso", metadata.iso)
put("whiteBalanceGains", JSONArray(metadata.whiteBalanceGains.toList()))
put("noiseProfileLayout", metadata.noiseProfileLayout.name)
put("channelNoiseProfile", JSONArray(metadata.channelNoiseProfile.toList()))
// A Bitmap input (§9) has no RAW metadata: its pixels are linear sRGB and its profile is the
// nominal one in params.
if (metadata != null) {
put("cfaPattern", metadata.cfaPattern)
put("frameCount", metadata.frameCount)
put("iso", metadata.iso)
put("whiteBalanceGains", JSONArray(metadata.whiteBalanceGains.toList()))
put("noiseProfileLayout", metadata.noiseProfileLayout.name)
put("channelNoiseProfile", JSONArray(metadata.channelNoiseProfile.toList()))
} else {
put("frameCount", 1)
put("whiteBalanceGains", JSONArray(listOf(1.0, 1.0, 1.0, 1.0)))
}
put("profileRgbRead", JSONArray(params.read.toList()))
put("profileRgbShot", JSONArray(params.shot.toList()))
val lensShading = params.lensShading
@@ -1,6 +1,7 @@
package com.hinnka.mycamera.raw.denoise
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import com.hinnka.mycamera.raw.RawDenoiseHistory
/**
* GLES 3.1 compute passes of the Photon denoiser (docs/photon-multiscale-denoise.md §3–§8, §10).
@@ -12,6 +13,21 @@ import com.hinnka.mycamera.processor.GlesComputeWorkGroup
internal object PhotonDenoiseShaders {
private const val LOCAL = GlesComputeWorkGroup.IMAGE_TILE_SIZE
// §5.1 strength table and estimate; mirrored by tools/photon_denoise/photon_denoise.py.
const val STRENGTH_BINS = RawDenoiseHistory.STRENGTH_BINS
const val HIST_BUCKETS = 64
const val ESTIMATE_BLOCK = 8
private const val STRENGTH_LOW = "-8.0"
private const val HIST_LOW = "-12.0"
private const val HIST_HIGH = "8.0"
private const val MIN_SAMPLES = 200
private const val CHI2_MEDIAN = "0.45493642"
const val MAX_STRENGTH = 4096f
const val ESTIMATE_PASSES = 3
private const val FLAT_GATE = "0.5"
private const val SPIKE = "1.5"
private const val MAX_GROWTH = "2.0"
private val COMMON = """
precision highp float;
precision highp int;
@@ -80,6 +96,21 @@ internal object PhotonDenoiseShaders {
return vec3(g.r, 0.5 * (g.g + g.b), g.a);
}
// §2.2 merge variance ratios (m_r, m_s): manual bilinear (clamp to edge) of the whole-image map.
uniform sampler2D uMergeMap;
uniform ivec2 uMergeSize;
vec2 mergeRatio(vec2 globalCentre) {
vec2 mapSize = vec2(uMergeSize);
vec2 t = clamp(globalCentre / vec2(uFullSize) * mapSize - 0.5, vec2(0.0), mapSize - 1.0);
ivec2 i0 = ivec2(floor(t));
ivec2 i1 = min(i0 + 1, uMergeSize - 1);
vec2 f = t - vec2(i0);
vec2 top = mix(texelFetch(uMergeMap, i0, 0).rg, texelFetch(uMergeMap, ivec2(i1.x, i0.y), 0).rg, f.x);
vec2 bottom = mix(texelFetch(uMergeMap, ivec2(i0.x, i1.y), 0).rg, texelFetch(uMergeMap, i1, 0).rg, f.x);
return mix(top, bottom, f.y);
}
// Level-l pixel centre in the full frame: origin + (p + 0.5) * 2^l.
vec2 levelCentre(ivec2 p, int level) {
return vec2(uOrigin) + (vec2(p) + 0.5) * float(1 << level);
@@ -97,6 +128,59 @@ internal object PhotonDenoiseShaders {
}
"""
/** ↑2 of a coarse level at a fine pixel (uCoarseSize is the coarse level's size). */
private val UPSAMPLE = """
vec3 upAt(sampler2D coarse, ivec2 p) {
float y = 0.0;
vec2 c = vec2(0.0);
for (int j = -3; j <= 3; ++j) {
if (((p.y - j) & 1) != 0) continue;
int cy = mirrorIndex((p.y - j) / 2, uCoarseSize.y);
for (int i = -3; i <= 3; ++i) {
if (((p.x - i) & 1) != 0) continue;
int cx = mirrorIndex((p.x - i) / 2, uCoarseSize.x);
vec3 v = texelFetch(coarse, ivec2(cx, cy), 0).rgb;
y += 4.0 * LUMA_TAPS[i + 3] * LUMA_TAPS[j + 3] * v.x;
if (abs(i) <= 2 && abs(j) <= 2) c += 4.0 * CHROMA_TAPS[i + 2] * CHROMA_TAPS[j + 2] * v.yz;
}
}
return vec3(y, c);
}
"""
/** §2.1 (with §2.2, §2.4) noise at signal base without the §5.1 strength, zero where clipped. */
private val MODEL_NOISE = """
uniform int uLevel;
uniform vec3 uRead;
uniform vec3 uShot;
uniform vec3 uResidual;
uniform float uKappaLuma[4];
uniform float uKappaChroma[4];
// (σ²_Y, σ²_Cb, σ²_Cr, σ_CbCr) at level pixel p; mu receives the camera signal.
vec4 modelNoise(ivec2 p, vec3 base, out vec3 mu) {
mu = max(rgbFromYcc(base) / uScale / uWb, vec3(0.0));
vec2 merge = mergeRatio(levelCentre(p, uLevel));
vec3 v = merge.x * uRead + merge.y * uShot * mu;
vec3 aY = uScale * vec3(0.25, 0.5, 0.25) * uWb;
vec3 aCb = uScale * vec3(0.0, -1.0, 1.0) * uWb;
vec3 aCr = uScale * vec3(1.0, -1.0, 0.0) * uWb;
int phase = (p.y & 1) * 2 + (p.x & 1);
float kl = uKappaLuma[phase];
float kc = uKappaChroma[phase];
vec3 t = sqrt(uResidual);
float pointLuma = dot(aY * aY, v);
vec4 noise = vec4(
kl * pointLuma * t.x * t.x,
kc * dot(aCb * aCb, v) * t.y * t.y,
kc * dot(aCr * aCr, v) * t.z * t.z,
kc * dot(aCb * aCr, v) * t.y * t.z);
vec3 camera = mu * lscGain(levelCentre(p, uLevel));
if (any(greaterThanEqual(camera, vec3(CLIP_LEVEL)))) noise = vec4(0.0);
return noise;
}
"""
/** Analyze: G_{l+1} = ↓2(h * G_l), luma taps on Y and chroma taps on Cb/Cr. */
val ANALYZE = """
#version 310 es
@@ -171,6 +255,229 @@ internal object PhotonDenoiseShaders {
}
"""
/**
* §5.1 estimate, steps 1–3 at one level: a work group histograms ESTIMATE_BLOCK² samples per
* invocation into shared memory and adds its non-zero counts to the global histogram
* [level][bin][Y, Cb, Cr][bucket]. Samples: every uStride-th pixel, each 2×2 block of samples
* offset so that all four Bayer phases occur. After the first pass the flat gate's noise is
* scaled by the median luma strength of this level in the previous pass's table.
*/
val ESTIMATE = """
#version 310 es
$COMMON
$LENS_SHADING
$WORKING
uniform sampler2D uFine;
uniform int uFineIsInput;
uniform sampler2D uCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
uniform int uStride;
$UPSAMPLE
$MODEL_NOISE
layout(std430, binding = 0) buffer Histogram { uint uHistogram[]; };
layout(std430, binding = 1) readonly buffer PreviousTable { float uPrevious[]; };
uniform int uHasPrevious;
const int ENTRIES = $STRENGTH_BINS * 3 * $HIST_BUCKETS;
const int BLOCK = $ESTIMATE_BLOCK;
shared uint sHistogram[ENTRIES];
$MEDIAN8
float gateScale() {
if (uHasPrevious == 0) return 1.0;
float v[8];
for (int b = 0; b < 8; ++b) {
float value = uPrevious[(uLevel * $STRENGTH_BINS + b) * 3];
v[b] = value;
}
return median8(v);
}
void addSample(ivec2 p, float gate) {
vec3 fine = uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
vec3 base = upAt(uCoarse, p);
vec3 lap = fine - base;
vec3 mu;
vec4 noise = modelNoise(p, base, mu);
if (!(noise.x > 0.0 && noise.y > 0.0 && noise.z > 0.0 && mu.g > 0.0)) return;
ivec2 c = p / 2;
float gx = 0.25 * (texelFetch(uCoarse, ivec2(mirrorIndex(c.x + 1, uCoarseSize.x), c.y), 0).x -
texelFetch(uCoarse, ivec2(mirrorIndex(c.x - 1, uCoarseSize.x), c.y), 0).x);
float gy = 0.25 * (texelFetch(uCoarse, ivec2(c.x, mirrorIndex(c.y + 1, uCoarseSize.y)), 0).x -
texelFetch(uCoarse, ivec2(c.x, mirrorIndex(c.y - 1, uCoarseSize.y)), 0).x);
if (!(sqrt(gx * gx + gy * gy) < $FLAT_GATE * sqrt(gate * noise.x))) return;
int bin = clamp(int(floor(log2(max(base.x / uScale, 1e-12)) - $STRENGTH_LOW)), 0, $STRENGTH_BINS - 1);
const float BUCKET_SCALE = float($HIST_BUCKETS) / ($HIST_HIGH - $HIST_LOW);
for (int ch = 0; ch < 3; ++ch) {
float v = lap[ch] * lap[ch] / noise[ch];
int k = clamp(int(floor((log2(max(v, 1e-30)) - $HIST_LOW) * BUCKET_SCALE)), 0, $HIST_BUCKETS - 1);
atomicAdd(sHistogram[(bin * 3 + ch) * $HIST_BUCKETS + k], 1u);
}
}
void main() {
int lid = int(gl_LocalInvocationIndex);
for (int i = lid; i < ENTRIES; i += $LOCAL * $LOCAL) sHistogram[i] = 0u;
memoryBarrierShared();
barrier();
ivec2 sampleSize = (uSize + uStride - 1) / uStride;
ivec2 origin = ivec2(gl_WorkGroupID.xy) * ($LOCAL * BLOCK);
ivec2 lane = ivec2(gl_LocalInvocationID.xy);
float gate = gateScale();
for (int by = 0; by < BLOCK; ++by) {
for (int bx = 0; bx < BLOCK; ++bx) {
ivec2 q = origin + ivec2(bx, by) * $LOCAL + lane;
if (any(greaterThanEqual(q, sampleSize))) continue;
ivec2 p = uStride > 1 ? q * uStride + ivec2(q.y & 1, q.x & 1) : q;
if (any(greaterThanEqual(p, uSize))) continue;
addSample(p, gate);
}
}
memoryBarrierShared();
barrier();
for (int i = lid; i < ENTRIES; i += $LOCAL * $LOCAL) {
uint n = sHistogram[i];
if (n != 0u) atomicAdd(uHistogram[uLevel * ENTRIES + i], n);
}
}
""".trimIndent()
/** Median of eight values (sorted copy, mean of the middle pair). */
private const val MEDIAN8 = """
float median8(float v[8]) {
for (int i = 1; i < 8; ++i) {
float x = v[i];
int j = i - 1;
while (j >= 0 && v[j] > x) {
v[j + 1] = v[j];
--j;
}
v[j + 1] = x;
}
return (v[3] + v[4]) * 0.5;
}
"""
/**
* §5.1 estimate, step 4: one lane per channel turns the histograms into the table — medians,
* fill across bins, bound against the 5-bin neighbourhood median, growth continuation for an
* unmeasured level, clamp and cap.
*/
val RESOLVE = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = 128) in;
layout(std430, binding = 0) readonly buffer Histogram { uint uHistogram[]; };
layout(std430, binding = 1) writeonly buffer StrengthTable { float uStrength[]; };
uniform int uLevels;
uniform float uCapLuma[${PhotonDenoiseTuning.MAX_LEVELS}];
uniform float uCapChroma[${PhotonDenoiseTuning.MAX_LEVELS}];
const int BINS = $STRENGTH_BINS;
const int BUCKETS = $HIST_BUCKETS;
const float WIDTH = ($HIST_HIGH - $HIST_LOW) / float(BUCKETS);
$MEDIAN8
// Median of filled[lo..hi] (at most five values).
float windowMedian(float filled[BINS], int lo, int hi) {
float w[5];
int n = 0;
for (int i = lo; i <= hi; ++i) {
float x = filled[i];
int j = n - 1;
while (j >= 0 && w[j] > x) {
w[j + 1] = w[j];
--j;
}
w[j + 1] = x;
++n;
}
return (n & 1) == 1 ? w[n / 2] : (w[n / 2 - 1] + w[n / 2]) * 0.5;
}
void main() {
int ch = int(gl_LocalInvocationID.x);
if (ch >= 3) return;
float upper[BINS];
float upper2[BINS];
for (int level = 0; level < uLevels; ++level) {
float measured[BINS];
int first = -1;
int last = -1;
for (int b = 0; b < BINS; ++b) {
int offset = ((level * BINS + b) * 3 + ch) * BUCKETS;
uint n = 0u;
for (int k = 0; k < BUCKETS; ++k) {
uint h = uHistogram[offset + k];
n += h;
}
measured[b] = -1.0;
if (n >= ${MIN_SAMPLES}u) {
float target = 0.5 * float(n);
uint cumulative = 0u;
for (int k = 0; k < BUCKETS; ++k) {
uint h = uHistogram[offset + k];
if (float(cumulative + h) >= target) {
float f = (target - float(cumulative)) / float(h);
measured[b] = exp2($HIST_LOW + (float(k) + f) * WIDTH) / $CHI2_MEDIAN;
break;
}
cumulative += h;
}
}
if (measured[b] >= 0.0) {
if (first < 0) first = b;
last = b;
}
}
float row[BINS];
if (first < 0) {
// A level without samples continues the growth of the two levels above.
float growth = 1.0;
if (level >= 2) {
float ratios[8];
for (int b = 0; b < BINS; ++b) ratios[b] = upper2[b] > 0.0 ? upper[b] / upper2[b] : 1.0;
growth = clamp(median8(ratios), 1.0, $MAX_GROWTH);
}
for (int b = 0; b < BINS; ++b) row[b] = level == 0 ? 1.0 : upper[b] * growth;
} else {
float filled[BINS];
for (int b = 0; b < BINS; ++b) {
if (measured[b] >= 0.0) {
filled[b] = measured[b];
} else if (b <= first) {
filled[b] = measured[first];
} else if (b >= last) {
filled[b] = measured[last];
} else {
int lo = b - 1;
while (measured[lo] < 0.0) --lo;
int hi = b + 1;
while (measured[hi] < 0.0) ++hi;
float f = float(b - lo) / float(hi - lo);
filled[b] = measured[lo] + f * (measured[hi] - measured[lo]);
}
}
for (int b = 0; b < BINS; ++b) {
float m = windowMedian(filled, max(b - 2, 0), min(b + 2, BINS - 1));
row[b] = min(max(filled[b], m / $SPIKE), m * $SPIKE);
}
}
float cap = min(${MAX_STRENGTH}, ch == 0 ? uCapLuma[level] : uCapChroma[level]);
for (int b = 0; b < BINS; ++b) {
float value = clamp(row[b], 0.0, cap);
uStrength[(level * BINS + b) * 3 + ch] = value;
upper2[b] = level > 0 ? upper[b] : 0.0;
upper[b] = value;
}
}
}
""".trimIndent()
fun synthesize(debugOutputs: Boolean): String = """
#version 310 es
$COMMON
@@ -182,14 +489,10 @@ internal object PhotonDenoiseShaders {
uniform sampler2D uDenoisedCoarse;
uniform ivec2 uSize;
uniform ivec2 uCoarseSize;
uniform int uLevel;
uniform vec3 uRead;
uniform vec3 uShot;
uniform float uMergeRead;
uniform float uMergeShot;
uniform vec3 uResidual;
uniform float uKappaLuma[4];
uniform float uKappaChroma[4];
$UPSAMPLE
$MODEL_NOISE
// §5.1 strength table: per level, STRENGTH_BINS luma bins of (S_Y, S_Cb, S_Cr).
layout(std430, binding = 0) readonly buffer StrengthTable { float uStrength[]; };
uniform float uOutlier;
uniform float uAlpha;
uniform int uLumaEnabled;
@@ -222,44 +525,27 @@ internal object PhotonDenoiseShaders {
int bandIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - BAND_BORDER); return r.y * BAND_SIDE + r.x; }
int pilotIndex(ivec2 c) { ivec2 r = c - (tileOrigin() - PILOT_BORDER); return r.y * PILOT_SIDE + r.x; }
vec3 upAt(sampler2D coarse, ivec2 p) {
float y = 0.0;
vec2 c = vec2(0.0);
for (int j = -3; j <= 3; ++j) {
if (((p.y - j) & 1) != 0) continue;
int cy = mirrorIndex((p.y - j) / 2, uCoarseSize.y);
for (int i = -3; i <= 3; ++i) {
if (((p.x - i) & 1) != 0) continue;
int cx = mirrorIndex((p.x - i) / 2, uCoarseSize.x);
vec3 v = texelFetch(coarse, ivec2(cx, cy), 0).rgb;
y += 4.0 * LUMA_TAPS[i + 3] * LUMA_TAPS[j + 3] * v.x;
if (abs(i) <= 2 && abs(j) <= 2) c += 4.0 * CHROMA_TAPS[i + 2] * CHROMA_TAPS[j + 2] * v.yz;
}
}
return vec3(y, c);
// §5.1 (S_Y, S_Cb, S_Cr) of this level at base luma y: bins interpolated in log2(y / K).
vec3 strengthAt(float y) {
float x = clamp(log2(max(y / uScale, 1e-12)) - $STRENGTH_LOW - 0.5, 0.0, float($STRENGTH_BINS - 1));
int i0 = int(floor(x));
int i1 = min(i0 + 1, $STRENGTH_BINS - 1);
float f = x - float(i0);
int o0 = (uLevel * $STRENGTH_BINS + i0) * 3;
int o1 = (uLevel * $STRENGTH_BINS + i1) * 3;
vec3 s0 = vec3(uStrength[o0], uStrength[o0 + 1], uStrength[o0 + 2]);
vec3 s1 = vec3(uStrength[o1], uStrength[o1 + 1], uStrength[o1 + 2]);
return s0 + f * (s1 - s0);
}
// Band at image pixel p: L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1.
// Band at image pixel p: L = G_l − ↑G_{l+1}, base = ↑G̃_{l+1}, noise = §2.1 × §5.1.
void computeBand(ivec2 p) {
vec3 fine = uFineIsInput == 1 ? working0(p) : texelFetch(uFine, p, 0).rgb;
vec3 base = upAt(uDenoisedCoarse, p);
vec3 lap = fine - upAt(uNoisyCoarse, p);
vec3 mu = max(rgbFromYcc(base) / uScale / uWb, vec3(0.0));
vec3 v = uMergeRead * uRead + uMergeShot * uShot * mu;
vec3 aY = uScale * vec3(0.25, 0.5, 0.25) * uWb;
vec3 aCb = uScale * vec3(0.0, -1.0, 1.0) * uWb;
vec3 aCr = uScale * vec3(1.0, -1.0, 0.0) * uWb;
int phase = (p.y & 1) * 2 + (p.x & 1);
float kl = uKappaLuma[phase];
float kc = uKappaChroma[phase];
vec3 t = sqrt(uResidual);
vec4 noise = vec4(
kl * dot(aY * aY, v) * t.x * t.x,
kc * dot(aCb * aCb, v) * t.y * t.y,
kc * dot(aCr * aCr, v) * t.z * t.z,
kc * dot(aCb * aCr, v) * t.y * t.z);
vec3 camera = mu * lscGain(levelCentre(p, uLevel));
if (any(greaterThanEqual(camera, vec3(CLIP_LEVEL)))) noise = vec4(0.0);
vec3 mu;
vec3 s = strengthAt(base.x);
vec4 noise = modelNoise(p, base, mu) * vec4(s, sqrt(s.y * s.z));
int index = bandIndex(p);
sLapBase[index] = uvec3(packHalf2x16(lap.xy), packHalf2x16(vec2(lap.z, base.x)), packHalf2x16(base.yz));
sNoise[index] = noise;
@@ -42,17 +42,18 @@ internal object PhotonDenoiseTuning {
}
/**
* §9 nominal Bitmap noise profile (r_bm, s_bm), applied to all three channels of linear
* sRGB and scaled by s². Pre-tuning value: a 1/255 standard deviation at mid grey, split
* evenly between read and shot terms; the BITMAP table's PSNR optimisation replaces it.
* §9 Bitmap blind denoise: an ISP-processed image has no usable noise model, so the denoiser
* runs on the sRGB-encoded values with a constant reference noise of one 8-bit code value
* (read term only); the §5.1 per-image estimate, uncapped, sets the amount per level and
* luma bin relative to it.
*/
const val BITMAP_READ = 0.5f / (255f * 255f)
const val BITMAP_SHOT = 0.5f / (255f * 255f * 0.18f)
const val BITMAP_READ = 1f / (255f * 255f)
const val BITMAP_SHOT = 0f
private val DEFAULT_NODE = Node(
n = 1f,
alpha = floatArrayOf(1f, 1f, 1f, 1.2f, 1.2f, 1.2f, 1.2f),
grain = floatArrayOf(0.30f, 0.20f, 0.15f, 0.10f, 0.10f, 0.10f, 0.10f),
grain = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f),
outlier = floatArrayOf(2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f, 2.5f),
gateLuma = floatArrayOf(16.919f, 27.877f),
gateChroma = floatArrayOf(5.991f, 13.816f),
@@ -61,6 +62,68 @@ internal object PhotonDenoiseTuning {
bilateralChroma = 4f,
)
/**
* §5.1 per-level table over image SNR (MGC's tuning nodes 5 / 20 / 40), luma and chroma rows
* L0–L4 (deeper levels use L4), linear in ln SNR between nodes and clamped at the ends.
*/
class SnrTable(
val snr: FloatArray,
val luma: Array<FloatArray>,
val chroma: Array<FloatArray>,
) {
init {
require(snr.size == SNR_NODES && snr[0] < snr[1] && snr[1] < snr[2])
require(luma.size == SNR_TABLE_LEVELS && luma.all { it.size == SNR_NODES })
require(chroma.size == SNR_TABLE_LEVELS && chroma.all { it.size == SNR_NODES })
}
fun luma(level: Int, snr: Float): Float = at(luma[minOf(level, SNR_TABLE_LEVELS - 1)], snr)
fun chroma(level: Int, snr: Float): Float = at(chroma[minOf(level, SNR_TABLE_LEVELS - 1)], snr)
private fun at(row: FloatArray, snr: Float): Float {
val x = ln(snr.coerceAtLeast(1e-6f))
val nodes = FloatArray(SNR_NODES) { ln(this.snr[it]) }
if (x <= nodes[0]) return row[0]
if (x >= nodes[SNR_NODES - 1]) return row[SNR_NODES - 1]
val upper = (1 until SNR_NODES).first { x < nodes[it] }
val f = (x - nodes[upper - 1]) / (nodes[upper] - nodes[upper - 1])
return row[upper - 1] + f * (row[upper] - row[upper - 1])
}
}
private const val SNR_TABLE_LEVELS = 5
private const val SNR_NODES = 3
private fun rows(vararg values: Float) = Array(SNR_TABLE_LEVELS) { level ->
FloatArray(SNR_NODES) { values[level * SNR_NODES + it] }
}
/**
* §5.1 cap of the per-image strength estimate of a RAW source. Blind estimation takes fine
* texture as noise; the error matters where texture and noise are of similar size, i.e. at
* high SNR, so the cap tightens with the image SNR. Node 40 keeps 1793243503594 (ISO 100,
* SNR 91) as textured as the measured table did; nodes 5 / 20 stay above the estimates of the
* 10x merges 1793253607706 / 1793253630461 (ISO 9100, SNR 12–16), whose coarse chroma reaches
* 7–13.
*/
val ESTIMATE_CAP = SnrTable(
snr = floatArrayOf(5f, 20f, 40f),
luma = rows(
2f, 1.5f, 0.75f,
4f, 3f, 1.25f,
8f, 6f, 2.5f,
16f, 12f, 5f,
24f, 18f, 6f,
),
chroma = rows(
1f, 1f, 1f,
1f, 1f, 1f,
4f, 3f, 0.75f,
12f, 8f, 1.5f,
24f, 16f, 2f,
),
)
private val TABLES: Map<RawDenoisePipeline, List<Node>> =
RawDenoisePipeline.entries.associateWith { listOf(DEFAULT_NODE) }
@@ -1,21 +1,35 @@
package com.hinnka.mycamera.raw.denoise
import android.opengl.GLES30
import android.opengl.GLES31
import android.util.Half
import com.hinnka.mycamera.raw.RawDenoiseHistory
import com.hinnka.mycamera.raw.RawDenoisePipeline
import com.hinnka.mycamera.raw.RawGlesProgram
import com.hinnka.mycamera.raw.RawMergeVarianceMap
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* §2.2 merge variance ratios from the merge's nominal frame weights
* (docs/photon-multiscale-denoise.md).
* §2.2 merge variance ratios (docs/photon-multiscale-denoise.md).
*
* Every frame is described by its camera-RGB read / shot coefficients already scaled to the
* reference exposure; the reference frame's coefficients are the profile the denoiser reads
* from the metadata. A merge output multiplied by [outputScale] scales read variance by its
* reference exposure; the reference frame's coefficients are the profile the denoiser reads from
* the metadata. A frame's weight at a pixel is its global weight times its acceptance there, read
* from the same weight texture the merge shader multiplies in. The per-pixel sums are accumulated
* on the GPU on the RAW/4 grid of the [imageWidth] × [imageHeight] frame and reduced to the
* RAW/32 map by averaging the ratios of 8 × 8 cells. The nominal scalars assume every frame is
* accepted everywhere. A merge output multiplied by `outputScale` scales read variance by its
* square and the shot coefficient by itself.
*
* Must be created, fed and finished on the GL thread of the merge.
*/
internal class PhotonMergeNoise(
private val pipeline: RawDenoisePipeline,
referenceRead: FloatArray,
referenceShot: FloatArray,
imageWidth: Int,
imageHeight: Int,
) {
private val referenceRead = referenceRead.sum()
private val referenceShot = referenceShot.sum()
@@ -23,24 +37,180 @@ internal class PhotonMergeNoise(
private var readSum = 0.0
private var shotSum = 0.0
fun add(weight: Float, read: FloatArray, shot: FloatArray) {
require(weight.isFinite() && weight > 0f) { "Merge frame weight must be positive, got $weight" }
val w = weight.toDouble()
weightSum += w
readSum += w * w * ratio(read.sum(), referenceRead)
shotSum += w * w * ratio(shot.sum(), referenceShot)
private val gridWidth = (imageWidth + GRID_STEP - 1) / GRID_STEP
private val gridHeight = (imageHeight + GRID_STEP - 1) / GRID_STEP
private val mapWidth = (gridWidth + MAP_CELLS - 1) / MAP_CELLS
private val mapHeight = (gridHeight + MAP_CELLS - 1) / MAP_CELLS
private var accumulateProgram = 0
private var reduceProgram = 0
private val buffers = IntArray(2)
private var frames = 0
init {
require(imageWidth > 0 && imageHeight > 0)
accumulateProgram = RawGlesProgram.compileCompute(ACCUMULATE, "PhotonMergeNoiseAccumulate")
reduceProgram = RawGlesProgram.compileCompute(REDUCE, "PhotonMergeNoiseReduce")
check(accumulateProgram != 0 && reduceProgram != 0) { "Photon merge noise programs are unavailable" }
GLES31.glGenBuffers(2, buffers, 0)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[0])
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, gridWidth * gridHeight * 16, null, GLES31.GL_DYNAMIC_COPY)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[1])
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, mapWidth * mapHeight * 8, null, GLES31.GL_STREAM_READ)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
fun history(outputScale: Float = 1f): RawDenoiseHistory {
check(weightSum > 0.0) { "No merge frame was added" }
val norm = weightSum * weightSum
return RawDenoiseHistory(
pipeline = pipeline,
mergeRead = (outputScale.toDouble() * outputScale * readSum / norm).toFloat(),
mergeShot = (outputScale.toDouble() * shotSum / norm).toFloat(),
)
/**
* [acceptance]: the frame's weight texture as the merge samples it (R channel in [0, 1]);
* 0 for a frame merged without one (weight 1 everywhere).
*/
fun add(weight: Float, read: FloatArray, shot: FloatArray, acceptance: Int) {
require(weight.isFinite() && weight > 0f) { "Merge frame weight must be positive, got $weight" }
val readRatio = ratio(read.sum(), referenceRead)
val shotRatio = ratio(shot.sum(), referenceShot)
val w = weight.toDouble()
weightSum += w
readSum += w * w * readRatio
shotSum += w * w * shotRatio
GLES31.glUseProgram(accumulateProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffers[0])
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, acceptance)
GLES31.glUniform1i(location(accumulateProgram, "uAcceptance"), 0)
GLES31.glUniform1i(location(accumulateProgram, "uHasAcceptance"), if (acceptance != 0) 1 else 0)
GLES31.glUniform2i(location(accumulateProgram, "uGrid"), gridWidth, gridHeight)
GLES31.glUniform3f(location(accumulateProgram, "uFrame"), weight, readRatio.toFloat(), shotRatio.toFloat())
GLES31.glUniform1i(location(accumulateProgram, "uFirst"), if (frames == 0) 1 else 0)
dispatch(gridWidth, gridHeight)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
GLES31.glUseProgram(0)
frames++
}
/** Reduces the sums to the RAW/32 map, reads it back (a few hundred KB) and releases the GPU state. */
/** [referenceSignal]: the reference frame's mean green signal (MGC EstimateSnr's mean). */
fun history(referenceSignal: Float, outputScale: Float = 1f): RawDenoiseHistory {
check(frames > 0) { "No merge frame was added" }
val readScale = outputScale * outputScale
val norm = weightSum * weightSum
try {
GLES31.glUseProgram(reduceProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, buffers[0])
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, buffers[1])
GLES31.glUniform2i(location(reduceProgram, "uGrid"), gridWidth, gridHeight)
GLES31.glUniform2i(location(reduceProgram, "uMap"), mapWidth, mapHeight)
GLES31.glUniform2f(location(reduceProgram, "uScale"), readScale, outputScale)
dispatch(mapWidth, mapHeight)
GLES31.glMemoryBarrier(GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
GLES31.glUseProgram(0)
val values = readMap()
return RawDenoiseHistory(
pipeline = pipeline,
mergeRead = (readScale * readSum / norm).toFloat(),
mergeShot = (outputScale * shotSum / norm).toFloat(),
mergeMap = RawMergeVarianceMap(mapWidth, mapHeight, values),
signal = referenceSignal * outputScale,
)
} finally {
release()
}
}
fun release() {
if (accumulateProgram != 0) GLES31.glDeleteProgram(accumulateProgram)
if (reduceProgram != 0) GLES31.glDeleteProgram(reduceProgram)
accumulateProgram = 0
reduceProgram = 0
if (buffers[0] != 0) GLES31.glDeleteBuffers(2, buffers, 0)
buffers.fill(0)
}
/** Values are rounded to float16, the persisted precision, so later passes see the same map. */
private fun readMap(): FloatArray {
val count = mapWidth * mapHeight * 2
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffers[1])
try {
val mapped = GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, count * 4, GLES31.GL_MAP_READ_BIT)
as? ByteBuffer ?: error("Photon merge variance map readback failed")
val floats = mapped.order(ByteOrder.nativeOrder()).asFloatBuffer()
return FloatArray(count) { Half.toFloat(Half.toHalf(floats.get(it))) }
} finally {
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
}
private fun dispatch(width: Int, height: Int) {
GLES31.glDispatchCompute((width + LOCAL - 1) / LOCAL, (height + LOCAL - 1) / LOCAL, 1)
}
private fun location(program: Int, name: String) = GLES31.glGetUniformLocation(program, name)
private fun ratio(value: Float, reference: Float): Double =
if (reference > 0f) value.toDouble() / reference else 1.0
private companion object {
const val GRID_STEP = 4
const val MAP_CELLS = 8
const val LOCAL = 8
// Per RAW/4 cell: (Σ w, Σ w² ρ_r, Σ w² ρ_s), w = global weight × acceptance.
val ACCUMULATE = """
#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
layout(std430, binding = 0) buffer Sums { vec4 sums[]; };
uniform sampler2D uAcceptance;
uniform int uHasAcceptance;
uniform ivec2 uGrid;
uniform vec3 uFrame; // global weight, ρ_r, ρ_s
uniform int uFirst;
void main() {
ivec2 c = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(c, uGrid))) return;
float a = uHasAcceptance == 1
? clamp(texture(uAcceptance, (vec2(c) + 0.5) / vec2(uGrid)).r, 0.0, 1.0)
: 1.0;
float w = uFrame.x * a;
vec4 v = vec4(w, w * w * uFrame.y, w * w * uFrame.z, 0.0);
int i = c.y * uGrid.x + c.x;
sums[i] = uFirst == 1 ? v : sums[i] + v;
}
""".trimIndent()
// Per RAW/32 cell: mean over its RAW/4 cells of (e² Σw²ρ_r, e Σw²ρ_s) / (Σw)².
val REDUCE = """
#version 310 es
precision highp float;
precision highp int;
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
layout(std430, binding = 0) readonly buffer Sums { vec4 sums[]; };
layout(std430, binding = 1) writeonly buffer Map { vec2 ratios[]; };
uniform ivec2 uGrid;
uniform ivec2 uMap;
uniform vec2 uScale; // e², e
void main() {
ivec2 m = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(m, uMap))) return;
vec2 total = vec2(0.0);
float count = 0.0;
for (int j = 0; j < $MAP_CELLS; ++j) {
for (int i = 0; i < $MAP_CELLS; ++i) {
ivec2 c = m * $MAP_CELLS + ivec2(i, j);
if (any(greaterThanEqual(c, uGrid))) continue;
vec4 s = sums[c.y * uGrid.x + c.x];
// No frame weight at all: the merge keeps the reference frame there.
total += s.x > 0.0 ? s.yz / (s.x * s.x) : vec2(1.0);
count += 1.0;
}
}
ratios[m.y * uMap.x + m.x] = uScale * total / count;
}
""".trimIndent()
}
}
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.raw.denoise
import android.opengl.GLES30
import android.opengl.GLES31
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import com.hinnka.mycamera.raw.RawDenoiseHistory
import com.hinnka.mycamera.raw.RawGlesProgram
import java.nio.ByteBuffer
import java.nio.ByteOrder
@@ -10,7 +11,8 @@ import java.nio.ByteOrder
/**
* GLES orchestration of the Photon denoiser (docs/photon-multiscale-denoise.md §4.3, §10).
*
* Analyze builds G_1..G_N (G_0 is computed from the input on the fly); synthesis runs the fused
* Analyze builds G_1..G_N (G_0 is computed from the input on the fly); the §5.1 strength table is
* then estimated from G_0..G_N unless the params carry one; synthesis runs the fused
* Band → Pilot → Final dispatch per level from coarse to fine, and level 0 writes camera RGB with
* the LSC gains restored. Only the Gaussian levels and two adjacent denoised levels are held
* (§10.2). A [PassSink] receives every pass output for parity checks; it adds a parity dispatch
@@ -20,38 +22,56 @@ internal class PhotonMultiScaleDenoiser {
/** Receives pass outputs while their textures are alive (debug parity, §12.4). */
fun interface PassSink {
fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean)
/** The §5.1 strength table the synthesis used. */
fun onStrength(table: FloatArray) {}
}
private var analyzeProgram = 0
private var synthesizeProgram = 0
private var synthesizeDebugProgram = 0
private var estimateProgram = 0
private var resolveProgram = 0
fun initialize(debug: Boolean = false): Boolean {
if (analyzeProgram == 0) analyzeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.ANALYZE, "PhotonDenoiseAnalyze")
if (synthesizeProgram == 0) {
synthesizeProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(false), "PhotonDenoiseSynthesize")
}
if (estimateProgram == 0) estimateProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.ESTIMATE, "PhotonDenoiseEstimate")
if (resolveProgram == 0) resolveProgram = RawGlesProgram.compileCompute(PhotonDenoiseShaders.RESOLVE, "PhotonDenoiseResolve")
if (debug && synthesizeDebugProgram == 0) {
synthesizeDebugProgram =
RawGlesProgram.compileCompute(PhotonDenoiseShaders.synthesize(true), "PhotonDenoiseSynthesizeDebug")
}
return analyzeProgram != 0 && synthesizeProgram != 0 && (!debug || synthesizeDebugProgram != 0)
return analyzeProgram != 0 && synthesizeProgram != 0 && estimateProgram != 0 && resolveProgram != 0 &&
(!debug || synthesizeDebugProgram != 0)
}
fun release() {
intArrayOf(analyzeProgram, synthesizeProgram, synthesizeDebugProgram).forEach {
intArrayOf(analyzeProgram, synthesizeProgram, synthesizeDebugProgram, estimateProgram, resolveProgram).forEach {
if (it != 0) GLES31.glDeleteProgram(it)
}
analyzeProgram = 0
synthesizeProgram = 0
synthesizeDebugProgram = 0
estimateProgram = 0
resolveProgram = 0
}
/**
* Denoises [inputTexture] (RGBA16F camera RGB, [width] × [height]) and returns a new RGBA16F
* texture owned by the caller, or null when the programs are unavailable.
* texture owned by the caller, or null when the programs are unavailable. [strengthOut]
* ([RawDenoiseHistory.STRENGTH_ENTRIES] per level) receives the §5.1 table the synthesis used.
*/
fun denoise(inputTexture: Int, width: Int, height: Int, params: PhotonDenoiseParams, sink: PassSink? = null): Int? {
fun denoise(
inputTexture: Int,
width: Int,
height: Int,
params: PhotonDenoiseParams,
strengthOut: FloatArray? = null,
sink: PassSink? = null,
): Int? {
if (!initialize(debug = sink != null)) return null
val sizes = ArrayList<IntArray>(params.levels + 1)
sizes += intArrayOf(width, height)
@@ -59,7 +79,12 @@ internal class PhotonMultiScaleDenoiser {
val owned = ArrayList<Int>()
fun texture(size: IntArray, format: Int) = createTexture(size[0], size[1], format).also(owned::add)
val lscTexture = params.lensShading?.let { createLscTexture(it).also(owned::add) } ?: 0
val mergeTexture = createMergeTexture(params).also(owned::add)
val output = createTexture(width, height, GLES30.GL_RGBA16F)
val buffers = IntArray(2)
GLES31.glGenBuffers(2, buffers, 0)
val strengthBuffer = buffers[0]
val histogramBuffer = buffers[1]
try {
val gaussians = IntArray(params.levels + 1)
for (level in 0 until params.levels) {
@@ -76,6 +101,22 @@ internal class PhotonMultiScaleDenoiser {
sink?.onPass("G${level + 1}", gaussians[level + 1], coarse[0], coarse[1], false)
}
val tableSize = params.levels * RawDenoiseHistory.STRENGTH_ENTRIES
val fixedTable = params.strengthTable
if (fixedTable != null) {
require(fixedTable.size == tableSize) { "Strength table has ${fixedTable.size} values, expected $tableSize" }
uploadBuffer(strengthBuffer, floatBuffer(fixedTable))
} else {
estimateStrength(inputTexture, lscTexture, mergeTexture, gaussians, sizes, params,
histogramBuffer, strengthBuffer)
}
if (strengthOut != null || sink != null) {
val table = readStrength(strengthBuffer, tableSize)
strengthOut?.let { table.copyInto(it, 0, 0, minOf(it.size, tableSize)) }
sink?.onStrength(table)
}
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, strengthBuffer)
var denoisedCoarse = gaussians[params.levels]
for (level in params.levels - 1 downTo 0) {
val size = sizes[level]
@@ -88,8 +129,8 @@ internal class PhotonMultiScaleDenoiser {
val noise = texture(size, GLES30.GL_RGBA32F)
val pilot = if (lumaEnabled) texture(size, GLES30.GL_RGBA16F) else band
GLES31.glUseProgram(synthesizeDebugProgram)
bindSynthesize(synthesizeDebugProgram, inputTexture, lscTexture, gaussians, denoisedCoarse,
sizes, level, lumaEnabled, params)
bindSynthesize(synthesizeDebugProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, lumaEnabled, params)
bindImage(0, band, GLES30.GL_RGBA16F)
bindImage(1, base, GLES30.GL_RGBA16F)
bindImage(2, noise, GLES30.GL_RGBA32F)
@@ -107,8 +148,8 @@ internal class PhotonMultiScaleDenoiser {
val result = if (level == 0) output else texture(size, GLES30.GL_RGBA16F)
GLES31.glUseProgram(synthesizeProgram)
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, gaussians, denoisedCoarse,
sizes, level, lumaEnabled, params)
bindSynthesize(synthesizeProgram, inputTexture, lscTexture, mergeTexture, gaussians,
denoisedCoarse, sizes, level, lumaEnabled, params)
bindImage(0, result, GLES30.GL_RGBA16F)
dispatch(size)
sink?.onPass(if (level == 0) "output" else "denoised$level", result, size[0], size[1], false)
@@ -126,10 +167,110 @@ internal class PhotonMultiScaleDenoiser {
throw error
} finally {
if (owned.isNotEmpty()) GLES30.glDeleteTextures(owned.size, owned.toIntArray(), 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
GLES31.glDeleteBuffers(2, buffers, 0)
GLES31.glUseProgram(0)
}
}
/**
* §5.1: [PhotonDenoiseShaders.ESTIMATE_PASSES] rounds of histograms of every level followed by
* the resolve into [strengthBuffer]; every round after the first gates with the table of the
* round before.
*/
private fun estimateStrength(
inputTexture: Int,
lscTexture: Int,
mergeTexture: Int,
gaussians: IntArray,
sizes: List<IntArray>,
params: PhotonDenoiseParams,
histogramBuffer: Int,
strengthBuffer: Int,
) {
val entries = PhotonDenoiseShaders.STRENGTH_BINS * 3 * PhotonDenoiseShaders.HIST_BUCKETS
val zeros = ByteBuffer.allocateDirect(params.levels * entries * Int.SIZE_BYTES).order(ByteOrder.nativeOrder())
uploadBuffer(strengthBuffer, ByteBuffer.allocateDirect(
params.levels * RawDenoiseHistory.STRENGTH_ENTRIES * Float.SIZE_BYTES).order(ByteOrder.nativeOrder()))
val capLuma = FloatArray(PhotonDenoiseTuning.MAX_LEVELS).also { params.strengthCapLuma.copyInto(it) }
val capChroma = FloatArray(PhotonDenoiseTuning.MAX_LEVELS).also { params.strengthCapChroma.copyInto(it) }
val span = GlesComputeWorkGroup.IMAGE_TILE_SIZE * PhotonDenoiseShaders.ESTIMATE_BLOCK
repeat(PhotonDenoiseShaders.ESTIMATE_PASSES) { pass ->
// glBufferData(null) leaves the contents undefined: the counts start from explicit zeros.
uploadBuffer(histogramBuffer, zeros)
GLES31.glUseProgram(estimateProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, histogramBuffer)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, strengthBuffer)
for (level in 0 until params.levels) {
bindCommon(estimateProgram, inputTexture, lscTexture, params)
bindModelNoise(estimateProgram, mergeTexture, level, params)
bindSampler(estimateProgram, "uFine", UNIT_FINE, if (level == 0) inputTexture else gaussians[level])
bindSampler(estimateProgram, "uCoarse", UNIT_NOISY_COARSE, gaussians[level + 1])
uniform1i(estimateProgram, "uFineIsInput", if (level == 0) 1 else 0)
uniform2i(estimateProgram, "uSize", sizes[level])
uniform2i(estimateProgram, "uCoarseSize", sizes[level + 1])
uniform1i(estimateProgram, "uHasPrevious", if (pass > 0) 1 else 0)
val stride = when (level) {
0 -> 4
1 -> 2
else -> 1
}
uniform1i(estimateProgram, "uStride", stride)
val samplesX = (sizes[level][0] + stride - 1) / stride
val samplesY = (sizes[level][1] + stride - 1) / stride
GLES31.glDispatchCompute((samplesX + span - 1) / span, (samplesY + span - 1) / span, 1)
}
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
GLES31.glUseProgram(resolveProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, histogramBuffer)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, strengthBuffer)
uniform1i(resolveProgram, "uLevels", params.levels)
GLES31.glUniform1fv(location(resolveProgram, "uCapLuma"), capLuma.size, capLuma, 0)
GLES31.glUniform1fv(location(resolveProgram, "uCapChroma"), capChroma.size, capChroma, 0)
GLES31.glDispatchCompute(1, 1, 1)
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT)
}
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
}
private fun readStrength(buffer: Int, size: Int): FloatArray {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer)
val mapped = GLES31.glMapBufferRange(GLES31.GL_SHADER_STORAGE_BUFFER, 0, size * Float.SIZE_BYTES,
GLES31.GL_MAP_READ_BIT) as? ByteBuffer
try {
val values = checkNotNull(mapped) { "Strength table is not mappable" }
return FloatArray(size).also { values.order(ByteOrder.nativeOrder()).asFloatBuffer().get(it) }
} finally {
if (mapped != null) GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
}
private fun uploadBuffer(buffer: Int, data: ByteBuffer) {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer)
GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, data.capacity(), data, GLES31.GL_DYNAMIC_COPY)
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
}
private fun floatBuffer(values: FloatArray): ByteBuffer =
ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES).order(ByteOrder.nativeOrder()).also {
it.asFloatBuffer().put(values)
}
/** Uniforms of the §2.1 model-noise snippet at [level]. */
private fun bindModelNoise(program: Int, mergeTexture: Int, level: Int, params: PhotonDenoiseParams) {
uniform1i(program, "uLevel", level)
uniform3f(program, "uRead", params.read)
uniform3f(program, "uShot", params.shot)
bindSampler(program, "uMergeMap", UNIT_MERGE, mergeTexture)
GLES31.glUniform2i(location(program, "uMergeSize"), params.mergeMapWidth, params.mergeMapHeight)
uniform3f(program, "uResidual", params.residual[level])
GLES31.glUniform1fv(location(program, "uKappaLuma"), 4, params.kappaLuma[level], 0)
GLES31.glUniform1fv(location(program, "uKappaChroma"), 4, params.kappaChroma[level], 0)
}
private fun bindCommon(program: Int, inputTexture: Int, lscTexture: Int, params: PhotonDenoiseParams) {
bindSampler(program, "uInput", UNIT_INPUT, inputTexture)
uniform1f(program, "uScale", params.scale)
@@ -151,6 +292,7 @@ internal class PhotonMultiScaleDenoiser {
program: Int,
inputTexture: Int,
lscTexture: Int,
mergeTexture: Int,
gaussians: IntArray,
denoisedCoarse: Int,
sizes: List<IntArray>,
@@ -165,14 +307,7 @@ internal class PhotonMultiScaleDenoiser {
uniform1i(program, "uFineIsInput", if (level == 0) 1 else 0)
uniform2i(program, "uSize", sizes[level])
uniform2i(program, "uCoarseSize", sizes[level + 1])
uniform1i(program, "uLevel", level)
uniform3f(program, "uRead", params.read)
uniform3f(program, "uShot", params.shot)
uniform1f(program, "uMergeRead", params.mergeRead)
uniform1f(program, "uMergeShot", params.mergeShot)
uniform3f(program, "uResidual", params.residual[level])
GLES31.glUniform1fv(location(program, "uKappaLuma"), 4, params.kappaLuma[level], 0)
GLES31.glUniform1fv(location(program, "uKappaChroma"), 4, params.kappaChroma[level], 0)
bindModelNoise(program, mergeTexture, level, params)
uniform1f(program, "uOutlier", params.outlier[level])
uniform1f(program, "uAlpha", params.lumaAlpha(level))
uniform1i(program, "uLumaEnabled", if (lumaEnabled) 1 else 0)
@@ -215,6 +350,20 @@ internal class PhotonMultiScaleDenoiser {
return texture
}
/** §2.2 (m_r, m_s) map as RG32F; a 1×1 map of the scalars when the pixels carry none. */
private fun createMergeTexture(params: PhotonDenoiseParams): Int {
val texture = createTexture(params.mergeMapWidth, params.mergeMapHeight, GLES30.GL_RG32F)
val values = params.mergeMapValues()
val data = ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
data.asFloatBuffer().put(values)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, params.mergeMapWidth, params.mergeMapHeight,
GLES30.GL_RG, GLES30.GL_FLOAT, data)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return texture
}
private fun dispatch(size: IntArray) {
GLES31.glDispatchCompute(
GlesComputeWorkGroup.imageGroupCount(size[0]),
@@ -251,5 +400,6 @@ internal class PhotonMultiScaleDenoiser {
const val UNIT_FINE = 2
const val UNIT_NOISY_COARSE = 3
const val UNIT_DENOISED_COARSE = 4
const val UNIT_MERGE = 5
}
}
@@ -4,6 +4,7 @@ import com.hinnka.mycamera.processor.RawNoiseModel
import com.hinnka.mycamera.raw.RawAppliedLensShading
import com.hinnka.mycamera.raw.RawDenoiseHistory
import com.hinnka.mycamera.raw.RawDenoisePipeline
import com.hinnka.mycamera.raw.RawMergeVarianceMap
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawNoiseProfileLayout
import org.json.JSONArray
@@ -51,6 +52,8 @@ internal class PhotonDenoiseParams(
val shot: FloatArray,
val mergeRead: Float,
val mergeShot: Float,
/** §2.2 per-pixel (m_r, m_s); null: [mergeRead] / [mergeShot] everywhere. */
val mergeMap: RawMergeVarianceMap?,
/** §2.4 t² per level as (Y, Cb, Cr). */
val residual: Array<FloatArray>,
val kappaLuma: Array<FloatArray>,
@@ -65,6 +68,19 @@ internal class PhotonDenoiseParams(
val bilateralLevels: Int,
val bilateralLuma: Float,
val bilateralChroma: Float,
/** §5.1 image SNR and the mean green signal it was computed at. */
val imageSnr: Float,
val signal: Float,
/** §5.1 caps of the per-image strength estimate per level at [imageSnr], luma and chroma. */
val strengthCapLuma: FloatArray,
val strengthCapChroma: FloatArray,
/**
* §5.1 strength table, [RawDenoiseHistory.STRENGTH_ENTRIES] values per level; null: estimated
* from the pixels before synthesis.
*/
val strengthTable: FloatArray?,
/** Mean green signal recorded with the input's history, carried to the output history. */
val historySignal: Float?,
val lumaStrength: Float,
val chromaStrength: Float,
val lensShading: PhotonLensShading?,
@@ -73,6 +89,12 @@ internal class PhotonDenoiseParams(
val fullWidth: Int,
val fullHeight: Int,
) {
val mergeMapWidth: Int get() = mergeMap?.width ?: 1
val mergeMapHeight: Int get() = mergeMap?.height ?: 1
/** (m_r, m_s) interleaved, row-major over [mergeMapWidth] × [mergeMapHeight]. */
fun mergeMapValues(): FloatArray = mergeMap?.values?.copyOf() ?: floatArrayOf(mergeRead, mergeShot)
/** §8: residual ratio t_l(s). */
fun lumaGrain(level: Int): Float {
val t = grain[level]
@@ -89,9 +111,10 @@ internal class PhotonDenoiseParams(
/**
* §2.4: noise state of this pass's output. Flat-region worst case per level: luma keeps
* t_l(s)² of its input variance where it is shrunk; chroma detail keeps (1 − min(s, 1))²
* (gate closed). Levels this pass does not process keep their input ratio.
* (gate closed). Levels this pass does not process keep their input ratio. [strength] is the
* table this pass applied, recorded for later passes over the output.
*/
fun outputHistory(): RawDenoiseHistory {
fun outputHistory(strength: FloatArray?): RawDenoiseHistory {
val chromaKept = (1f - min(chromaStrength, 1f)).let { it * it }
val residualOut = List(max(levels, residual.size)) { level ->
val input = residual.getOrNull(level) ?: floatArrayOf(1f, 1f, 1f)
@@ -100,7 +123,7 @@ internal class PhotonDenoiseParams(
val chroma = if (chromaStrength > 0f) chromaKept else 1f
floatArrayOf(input[0] * luma, input[1] * chroma, input[2] * chroma)
}
return RawDenoiseHistory(pipeline, mergeRead, mergeShot, residualOut)
return RawDenoiseHistory(pipeline, mergeRead, mergeShot, residualOut, mergeMap, historySignal, strength)
}
fun toJson(): JSONObject = JSONObject().apply {
@@ -112,6 +135,11 @@ internal class PhotonDenoiseParams(
put("shot", JSONArray(shot.map(Float::toDouble)))
put("mergeRead", mergeRead.toDouble())
put("mergeShot", mergeShot.toDouble())
put("mergeMap", JSONObject().apply {
put("width", mergeMapWidth)
put("height", mergeMapHeight)
put("values", JSONArray(mergeMapValues().map(Float::toDouble)))
})
put("residual", JSONArray(residual.map { row -> JSONArray(row.map(Float::toDouble)) }))
put("kappaLuma", JSONArray(kappaLuma.map { row -> JSONArray(row.map(Float::toDouble)) }))
put("kappaChroma", JSONArray(kappaChroma.map { row -> JSONArray(row.map(Float::toDouble)) }))
@@ -125,6 +153,11 @@ internal class PhotonDenoiseParams(
put("bilateralLevels", bilateralLevels)
put("bilateralLuma", bilateralLuma.toDouble())
put("bilateralChroma", bilateralChroma.toDouble())
put("imageSnr", imageSnr.toDouble())
put("signal", signal.toDouble())
put("strengthCapLuma", JSONArray(strengthCapLuma.map(Float::toDouble)))
put("strengthCapChroma", JSONArray(strengthCapChroma.map(Float::toDouble)))
strengthTable?.let { put("strengthTable", JSONArray(it.map(Float::toDouble))) }
put("lumaStrength", lumaStrength.toDouble())
put("chromaStrength", chromaStrength.toDouble())
put("originX", originX)
@@ -147,10 +180,13 @@ internal object PhotonNoiseModel {
private const val MAX_WORKING_SIGNAL = 32768f
private const val MAX_SCALE = 4096f
private const val LSB_FRACTION = 0.25f
private const val MISSING_SIGNAL = 0.18f
private const val MIN_LEVEL_SIZE = 4
/**
* RAW input. [history]: §2.2 merge ratios, §2.4 residual ratios and pipeline of the pixels.
* The §5.1 image SNR uses the mean green signal measured on these pixels, else the one
* recorded with the merge, else MGC EstimateSnr's missing-mean value 0.18.
*/
fun build(
metadata: RawMetadata,
@@ -173,13 +209,14 @@ internal object PhotonNoiseModel {
1f,
(if (gains.size >= 4) gains[3] else gains.getOrElse(2) { 1f }) / green,
)
val signal = metadata.denoiseSignal ?: history.signal ?: MISSING_SIGNAL
return build(noise.read, noise.shot, whiteBalance, width, height, originX, originY, fullWidth, fullHeight,
history, lumaStrength, chromaStrength, lensShading)
history, signal, lumaStrength, chromaStrength, lensShading)
}
/**
* §9 Bitmap input: linear sRGB with the nominal profile of the BITMAP table, no white
* balance, no LSC, no merge.
* §9 Bitmap input: sRGB-encoded values with the constant reference noise of the BITMAP table
* (blind strengths, no source noise model), no white balance, no LSC, no merge.
*/
fun buildBitmap(width: Int, height: Int, lumaStrength: Float, chromaStrength: Float): PhotonDenoiseParams = build(
read = FloatArray(3) { PhotonDenoiseTuning.BITMAP_READ },
@@ -192,6 +229,7 @@ internal object PhotonNoiseModel {
fullWidth = width,
fullHeight = height,
history = RawDenoiseHistory.singleFrame(RawDenoisePipeline.BITMAP),
signal = MISSING_SIGNAL,
lumaStrength = lumaStrength,
chromaStrength = chromaStrength,
lensShading = null,
@@ -228,6 +266,15 @@ internal object PhotonNoiseModel {
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) RawDenoisePipeline.QUAD else RawDenoisePipeline.VGN,
)
/**
* §5.1 image SNR, MGC FinishRaw's definition with the §2.2 nominal merge ratios:
* S / √(m_s · s_G · S + m_r · r_G) at the mean green signal S.
*/
fun imageSnr(read: FloatArray, shot: FloatArray, history: RawDenoiseHistory, signal: Float): Float {
val variance = history.mergeShot * shot[1] * signal + history.mergeRead * read[1]
return if (variance > 0f) signal / sqrt(variance) else 0f
}
/** §5: n = √(m · v_Y(0.18)) / 0.18, v_Y the luma point variance without K. */
fun noiseCoordinate(read: FloatArray, shot: FloatArray, whiteBalance: FloatArray, history: RawDenoiseHistory): Float {
val luma = floatArrayOf(0.25f, 0.5f, 0.25f)
@@ -250,6 +297,7 @@ internal object PhotonNoiseModel {
fullWidth: Int,
fullHeight: Int,
history: RawDenoiseHistory,
signal: Float,
lumaStrength: Float,
chromaStrength: Float,
lensShading: PhotonLensShading?,
@@ -269,6 +317,16 @@ internal object PhotonNoiseModel {
}
val n = noiseCoordinate(read, shot, whiteBalance, history)
val tuning = PhotonDenoiseTuning.at(history.pipeline, n)
val snr = imageSnr(read, shot, history, signal)
val entries = RawDenoiseHistory.STRENGTH_ENTRIES
val strengthTable = history.strength?.takeIf { it.size >= levels * entries }?.copyOf(levels * entries)
// §9: a Bitmap has no image SNR (its reference noise is nominal), so its estimate is uncapped.
val bitmap = history.pipeline == RawDenoisePipeline.BITMAP
fun cap(level: Int, luma: Boolean) = when {
bitmap -> PhotonDenoiseShaders.MAX_STRENGTH
luma -> PhotonDenoiseTuning.ESTIMATE_CAP.luma(level, snr)
else -> PhotonDenoiseTuning.ESTIMATE_CAP.chroma(level, snr)
}
return PhotonDenoiseParams(
pipeline = history.pipeline,
noiseCoordinate = n,
@@ -278,6 +336,7 @@ internal object PhotonNoiseModel {
shot = shot.copyOf(),
mergeRead = mergeRead,
mergeShot = mergeShot,
mergeMap = history.mergeMap,
residual = Array(levels) { history.residualAt(it) },
kappaLuma = rows(lumaTable),
kappaChroma = rows(chromaTable),
@@ -291,6 +350,12 @@ internal object PhotonNoiseModel {
bilateralLevels = tuning.bilateralLevels,
bilateralLuma = tuning.bilateralLuma,
bilateralChroma = tuning.bilateralChroma,
imageSnr = snr,
signal = signal,
strengthCapLuma = FloatArray(levels) { cap(it, luma = true) },
strengthCapChroma = FloatArray(levels) { cap(it, luma = false) },
strengthTable = strengthTable,
historySignal = history.signal,
lumaStrength = lumaStrength,
chromaStrength = chromaStrength,
lensShading = lensShading,