feat: photon pgtm gpu
This commit is contained in:
1 parent
b0373dacda
commit
d1e3340bf2
5 files changed
+945
-43
No files matched your search
@@ -41,6 +41,114 @@ internal data class DngPgtmGlobalStats(
|
||||
private const val SHADOW_SEARCH_MAX_QUANTILE = 0.40f
|
||||
private const val SHADOW_FOOT_DENSITY_RATIO = 0.15f
|
||||
|
||||
/**
|
||||
* Builds the scene-wide statistics from the compact log-EV histogram
|
||||
* produced by the GLES PGTM statistics pass. Dense image sampling and
|
||||
* percentile population counting stay on the GPU; only this small
|
||||
* histogram and per-workgroup sums cross back to the CPU.
|
||||
*/
|
||||
fun fromLogHistogram(
|
||||
logHistogram: IntArray,
|
||||
histogramMinEv: Float,
|
||||
histogramMaxEv: Float,
|
||||
sampleCount: Int,
|
||||
zeroCount: Int,
|
||||
highlightCount: Int,
|
||||
maxInput: Float,
|
||||
linearSum: Double,
|
||||
logSum: Double,
|
||||
): DngPgtmGlobalStats? {
|
||||
if (logHistogram.isEmpty() ||
|
||||
!histogramMinEv.isFinite() ||
|
||||
!histogramMaxEv.isFinite() ||
|
||||
histogramMaxEv <= histogramMinEv ||
|
||||
sampleCount <= 0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val safeZeroCount = zeroCount.coerceIn(0, sampleCount)
|
||||
val positiveCount = logHistogram.sumOf { it.coerceAtLeast(0).toLong() }
|
||||
.coerceAtMost((sampleCount - safeZeroCount).toLong())
|
||||
.toInt()
|
||||
val coarseHistogram = FloatArray(LOG_HISTOGRAM_BIN_COUNT)
|
||||
val fineBinEv = (histogramMaxEv - histogramMinEv) / logHistogram.size.toFloat()
|
||||
logHistogram.forEachIndexed { index, rawCount ->
|
||||
val count = rawCount.coerceAtLeast(0)
|
||||
if (count == 0) return@forEachIndexed
|
||||
val ev = histogramMinEv + (index.toFloat() + 0.5f) * fineBinEv
|
||||
val coarseBin = floor(
|
||||
(ev - LOG_HISTOGRAM_MIN_EV) / LOG_HISTOGRAM_BIN_EV
|
||||
).toInt().coerceIn(0, coarseHistogram.lastIndex)
|
||||
coarseHistogram[coarseBin] += count.toFloat()
|
||||
}
|
||||
val shadowSlope = shadowSlopeFromHistogram(coarseHistogram, positiveCount)
|
||||
val safeMaxInput = maxInput.takeIf { it.isFinite() && it >= 0f } ?: 0f
|
||||
val p10 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.10f
|
||||
).coerceAtMost(safeMaxInput)
|
||||
val p50 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.50f
|
||||
).coerceIn(p10, safeMaxInput)
|
||||
val p90 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.90f
|
||||
).coerceIn(p50, safeMaxInput)
|
||||
val p98 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.98f
|
||||
).coerceIn(p90, safeMaxInput)
|
||||
val p995 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.995f
|
||||
).coerceIn(p98, safeMaxInput)
|
||||
val p999 = percentileFromLogHistogram(
|
||||
logHistogram,
|
||||
histogramMinEv,
|
||||
histogramMaxEv,
|
||||
sampleCount,
|
||||
safeZeroCount,
|
||||
0.999f
|
||||
).coerceIn(p995, safeMaxInput)
|
||||
return DngPgtmGlobalStats(
|
||||
p10 = p10,
|
||||
p50 = p50,
|
||||
p90 = p90,
|
||||
p98 = p98,
|
||||
p995 = p995,
|
||||
p999 = p999,
|
||||
maxInput = safeMaxInput,
|
||||
highlightFraction = highlightCount.coerceIn(0, sampleCount).toFloat() /
|
||||
sampleCount.toFloat(),
|
||||
linearMean = (linearSum / sampleCount.toDouble()).toFloat(),
|
||||
logAverage = exp(logSum / sampleCount.toDouble()).toFloat(),
|
||||
shadowEdge = shadowSlope.edge,
|
||||
shadowFoot = shadowSlope.foot,
|
||||
sampleCount = sampleCount
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Compacts and sorts [samples] in place. The caller must not reuse the
|
||||
* original sample order after this call.
|
||||
@@ -112,6 +220,18 @@ internal data class DngPgtmGlobalStats(
|
||||
return ShadowSlope(edge = minimum, foot = minimum)
|
||||
}
|
||||
|
||||
return shadowSlopeFromHistogram(histogram, positiveCount)
|
||||
}
|
||||
|
||||
private fun shadowSlopeFromHistogram(
|
||||
histogram: FloatArray,
|
||||
positiveCount: Int,
|
||||
): ShadowSlope {
|
||||
if (positiveCount <= 0) {
|
||||
val minimum = 2.0f.pow(LOG_HISTOGRAM_MIN_EV)
|
||||
return ShadowSlope(edge = minimum, foot = minimum)
|
||||
}
|
||||
|
||||
val smoothed = smoothHistogram(histogram)
|
||||
val searchStart = percentileBin(
|
||||
histogram,
|
||||
@@ -165,6 +285,36 @@ internal data class DngPgtmGlobalStats(
|
||||
)
|
||||
}
|
||||
|
||||
private fun percentileFromLogHistogram(
|
||||
histogram: IntArray,
|
||||
histogramMinEv: Float,
|
||||
histogramMaxEv: Float,
|
||||
sampleCount: Int,
|
||||
zeroCount: Int,
|
||||
percentile: Float,
|
||||
): Float {
|
||||
val target = ceil(sampleCount.toFloat() * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceIn(1, sampleCount)
|
||||
if (target <= zeroCount) return 0f
|
||||
val positiveTarget = target - zeroCount
|
||||
var cumulative = 0
|
||||
val binWidthEv = (histogramMaxEv - histogramMinEv) / histogram.size.toFloat()
|
||||
for (index in histogram.indices) {
|
||||
val count = histogram[index].coerceAtLeast(0)
|
||||
if (count == 0) continue
|
||||
val previous = cumulative
|
||||
cumulative += count
|
||||
if (cumulative >= positiveTarget) {
|
||||
val withinBin = ((positiveTarget - previous).toFloat() - 0.5f) /
|
||||
count.toFloat()
|
||||
val ev = histogramMinEv +
|
||||
(index.toFloat() + withinBin.coerceIn(0f, 1f)) * binWidthEv
|
||||
return 2.0f.pow(ev)
|
||||
}
|
||||
}
|
||||
return 2.0f.pow(histogramMaxEv)
|
||||
}
|
||||
|
||||
private fun smoothHistogram(histogram: FloatArray): FloatArray {
|
||||
val kernel = FloatArray(LOG_HISTOGRAM_SMOOTH_RADIUS * 2 + 1)
|
||||
var kernelSum = 0.0
|
||||
|
||||
@@ -103,13 +103,17 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
baselineExposureEv = safeBaselineEv
|
||||
)
|
||||
val inputScale = sanitizeInputScale(1f / toneAnchors.whitePoint)
|
||||
val curveSamples = buildPhotonCurveSamples(
|
||||
pointCount = safePointCount,
|
||||
inputScale = inputScale,
|
||||
toneAnchors = toneAnchors
|
||||
)
|
||||
val gains = FloatArray(cellCount * safePointCount)
|
||||
for (cellIndex in 0 until cellCount) {
|
||||
writePhotonCurve(
|
||||
output = gains,
|
||||
outputOffset = cellIndex * safePointCount,
|
||||
pointCount = safePointCount,
|
||||
inputScale = inputScale,
|
||||
curveSamples = curveSamples,
|
||||
toneAnchors = toneAnchors,
|
||||
global = global,
|
||||
local = cells[cellIndex] ?: global
|
||||
@@ -436,26 +440,41 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
private fun writePhotonCurve(
|
||||
output: FloatArray,
|
||||
outputOffset: Int,
|
||||
pointCount: Int,
|
||||
inputScale: Float,
|
||||
curveSamples: PhotonCurveSamples,
|
||||
toneAnchors: PhotonToneAnchors,
|
||||
global: PhotonPgtmCellStats,
|
||||
local: PhotonPgtmCellStats,
|
||||
) {
|
||||
val safeInputScale = sanitizeInputScale(inputScale)
|
||||
val pointCount = curveSamples.sceneLinear.size
|
||||
val localParams = buildLocalMicroContrastParams(
|
||||
toneAnchors = toneAnchors,
|
||||
global = global,
|
||||
local = local
|
||||
)
|
||||
var previousOutput = 0f
|
||||
val lowTableInput = 1f / max(pointCount - 1, 1).toFloat()
|
||||
val lowSceneLinear = sceneLinearForTableInput(lowTableInput, safeInputScale)
|
||||
val lowGain = (photonToneOutput(lowSceneLinear, toneAnchors, global, local) / lowSceneLinear)
|
||||
val lowSceneLinear = sceneLinearForTableInput(lowTableInput, curveSamples.inputScale)
|
||||
val lowBaseOutput = photonGlobalToneOutput(lowSceneLinear, toneAnchors)
|
||||
val lowOutput = applyLocalMicroContrast(
|
||||
baseOutput = lowBaseOutput,
|
||||
sceneLog2 = log2(lowSceneLinear),
|
||||
tonalWindow = localMicroContrastTonalWindow(lowSceneLinear, toneAnchors),
|
||||
params = localParams
|
||||
)
|
||||
val lowGain = (lowOutput / lowSceneLinear)
|
||||
.coerceIn(0.05f, MAX_GAIN_VALUE)
|
||||
for (index in 0 until pointCount) {
|
||||
val tableInput = tableInputForIndex(index, pointCount)
|
||||
if (tableInput <= MIN_CURVE_INPUT) {
|
||||
val sceneLinear = curveSamples.sceneLinear[index]
|
||||
if (sceneLinear <= MIN_CURVE_INPUT) {
|
||||
output[outputOffset + index] = lowGain
|
||||
continue
|
||||
}
|
||||
val sceneLinear = sceneLinearForTableInput(tableInput, safeInputScale)
|
||||
val targetOutput = photonToneOutput(sceneLinear, toneAnchors, global, local)
|
||||
val targetOutput = applyLocalMicroContrast(
|
||||
baseOutput = curveSamples.baseOutput[index],
|
||||
sceneLog2 = curveSamples.sceneLog2[index],
|
||||
tonalWindow = curveSamples.tonalWindow[index],
|
||||
params = localParams
|
||||
)
|
||||
val monotonicOutput = max(previousOutput, targetOutput)
|
||||
output[outputOffset + index] = (monotonicOutput / max(sceneLinear, MIN_CURVE_INPUT))
|
||||
.coerceIn(0.05f, MAX_GAIN_VALUE)
|
||||
@@ -463,6 +482,33 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildPhotonCurveSamples(
|
||||
pointCount: Int,
|
||||
inputScale: Float,
|
||||
toneAnchors: PhotonToneAnchors,
|
||||
): PhotonCurveSamples {
|
||||
val safeInputScale = sanitizeInputScale(inputScale)
|
||||
val sceneLinear = FloatArray(pointCount)
|
||||
val baseOutput = FloatArray(pointCount)
|
||||
val sceneLog2 = FloatArray(pointCount)
|
||||
val tonalWindow = FloatArray(pointCount)
|
||||
for (index in 0 until pointCount) {
|
||||
val tableInput = tableInputForIndex(index, pointCount)
|
||||
val scene = sceneLinearForTableInput(tableInput, safeInputScale)
|
||||
sceneLinear[index] = scene
|
||||
baseOutput[index] = photonGlobalToneOutput(scene, toneAnchors)
|
||||
sceneLog2[index] = if (scene > 0f) log2(scene) else Float.NEGATIVE_INFINITY
|
||||
tonalWindow[index] = localMicroContrastTonalWindow(scene, toneAnchors)
|
||||
}
|
||||
return PhotonCurveSamples(
|
||||
inputScale = safeInputScale,
|
||||
sceneLinear = sceneLinear,
|
||||
baseOutput = baseOutput,
|
||||
sceneLog2 = sceneLog2,
|
||||
tonalWindow = tonalWindow
|
||||
)
|
||||
}
|
||||
|
||||
private fun photonToneOutput(
|
||||
sceneLinear: Float,
|
||||
toneAnchors: PhotonToneAnchors,
|
||||
@@ -558,6 +604,20 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
local: PhotonPgtmCellStats,
|
||||
): Float {
|
||||
if (baseOutput <= 0f || baseOutput >= 1f) return baseOutput
|
||||
val params = buildLocalMicroContrastParams(toneAnchors, global, local)
|
||||
return applyLocalMicroContrast(
|
||||
baseOutput = baseOutput,
|
||||
sceneLog2 = log2(sceneLinear),
|
||||
tonalWindow = localMicroContrastTonalWindow(sceneLinear, toneAnchors),
|
||||
params = params
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildLocalMicroContrastParams(
|
||||
toneAnchors: PhotonToneAnchors,
|
||||
global: PhotonPgtmCellStats,
|
||||
local: PhotonPgtmCellStats,
|
||||
): LocalMicroContrastParams {
|
||||
val localRangeEv = log2((local.p90 + 0.008f) / (local.p10 + 0.008f))
|
||||
.coerceIn(0f, 8f)
|
||||
val globalRangeEv = log2((global.p90 + 0.008f) / (global.p10 + 0.008f))
|
||||
@@ -567,21 +627,44 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
val highlightDamping = 1f - 0.38f * smoothStep(0.14f, 0.38f, global.highlightFraction)
|
||||
val strengthEv = MAX_LOCAL_MICRO_CONTRAST_EV * localDetail *
|
||||
lerp(0.72f, 1f, relativeDetail) * highlightDamping
|
||||
if (strengthEv <= 1e-4f) return baseOutput
|
||||
if (strengthEv <= 1e-4f) {
|
||||
return LocalMicroContrastParams(strengthEv = 0f, pivotLog2 = 0f)
|
||||
}
|
||||
|
||||
val localPivot = local.p50.coerceIn(
|
||||
toneAnchors.middleGrayPoint * 0.45f,
|
||||
toneAnchors.middleGrayPoint * 1.65f
|
||||
)
|
||||
val pivot = 2.0f.pow(
|
||||
lerp(
|
||||
return LocalMicroContrastParams(
|
||||
strengthEv = strengthEv,
|
||||
pivotLog2 = lerp(
|
||||
log2(toneAnchors.middleGrayPoint),
|
||||
log2(localPivot),
|
||||
0.35f
|
||||
)
|
||||
)
|
||||
val signedDistance = (log2(sceneLinear / pivot) / 1.45f)
|
||||
}
|
||||
|
||||
private fun applyLocalMicroContrast(
|
||||
baseOutput: Float,
|
||||
sceneLog2: Float,
|
||||
tonalWindow: Float,
|
||||
params: LocalMicroContrastParams,
|
||||
): Float {
|
||||
if (baseOutput <= 0f || baseOutput >= 1f || params.strengthEv <= 1e-4f) {
|
||||
return baseOutput
|
||||
}
|
||||
val signedDistance = ((sceneLog2 - params.pivotLog2) / 1.45f)
|
||||
.coerceIn(-1f, 1f)
|
||||
val adjusted = baseOutput * 2.0f.pow(params.strengthEv * signedDistance * tonalWindow)
|
||||
return adjusted.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun localMicroContrastTonalWindow(
|
||||
sceneLinear: Float,
|
||||
toneAnchors: PhotonToneAnchors,
|
||||
): Float {
|
||||
if (sceneLinear <= 0f) return 0f
|
||||
val blackFeatherEnd = max(toneAnchors.blackPoint * 4f, 0.018f)
|
||||
val highlightFeatherStart = max(
|
||||
toneAnchors.middleGrayPoint * 2.4f,
|
||||
@@ -591,10 +674,8 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
highlightFeatherStart + 1e-4f,
|
||||
toneAnchors.whitePoint * 0.82f
|
||||
)
|
||||
val tonalWindow = smoothStep(toneAnchors.blackPoint, blackFeatherEnd, sceneLinear) *
|
||||
return smoothStep(toneAnchors.blackPoint, blackFeatherEnd, sceneLinear) *
|
||||
(1f - smoothStep(highlightFeatherStart, highlightFeatherEnd, sceneLinear))
|
||||
val adjusted = baseOutput * 2.0f.pow(strengthEv * signedDistance * tonalWindow)
|
||||
return adjusted.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun photonPgtmInputWeights(inputScale: Float): FloatArray {
|
||||
@@ -696,6 +777,19 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
val sampleWeight: Float,
|
||||
)
|
||||
|
||||
private data class PhotonCurveSamples(
|
||||
val inputScale: Float,
|
||||
val sceneLinear: FloatArray,
|
||||
val baseOutput: FloatArray,
|
||||
val sceneLog2: FloatArray,
|
||||
val tonalWindow: FloatArray,
|
||||
)
|
||||
|
||||
private data class LocalMicroContrastParams(
|
||||
val strengthEv: Float,
|
||||
val pivotLog2: Float,
|
||||
)
|
||||
|
||||
private data class PhotonToneAnchors(
|
||||
val tailHighlightRangeEv: Float,
|
||||
val exposureHighlightRangeEv: Float,
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Computes dense RAW PGTM statistics on the current GLES context.
|
||||
*
|
||||
* One 16x16 workgroup owns one PGTM cell. Samples are converted to profile
|
||||
* RGB and sorted in shared memory on the GPU. The CPU receives only cell
|
||||
* percentiles, a compact scene-wide EV histogram, and two sums per cell.
|
||||
*/
|
||||
internal class GlesRawProfileGainTableMapBuilder {
|
||||
private var statsProgram = 0
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (statsProgram != 0) return true
|
||||
statsProgram = compileComputeProgram(PGTM_STATS_COMPUTE_SHADER)
|
||||
return statsProgram != 0
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (statsProgram != 0) {
|
||||
GLES31.glDeleteProgram(statsProgram)
|
||||
statsProgram = 0
|
||||
}
|
||||
}
|
||||
|
||||
fun build(
|
||||
rawTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
metadata: RawMetadata,
|
||||
samplesPerPixel: Int,
|
||||
statsBounds: Rect?,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
): DngProfileGainTableMap? {
|
||||
if (statsProgram == 0 || rawTextureId == 0 || width <= 0 || height <= 0) return null
|
||||
if (profileToneMapMode != RawProfileToneMapMode.Photon &&
|
||||
profileToneMapMode != RawProfileToneMapMode.GooglePixel
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
|
||||
val gridWidth = grid.getOrElse(0) { 0 }
|
||||
val gridHeight = grid.getOrElse(1) { 0 }
|
||||
if (gridWidth <= 0 || gridHeight <= 0) return null
|
||||
|
||||
val safeBounds = sanitizeStatsBounds(statsBounds, width, height) ?: return null
|
||||
val cellCount = gridWidth * gridHeight
|
||||
val cellStatsWordCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
val cellSumsOffset = cellStatsWordCount
|
||||
val globalHistogramOffset = cellSumsOffset + cellCount * CELL_SUM_FLOAT_STRIDE
|
||||
val globalCountersOffset = globalHistogramOffset + GLOBAL_HISTOGRAM_BIN_COUNT
|
||||
val totalWordCount = globalCountersOffset + GLOBAL_COUNTER_COUNT
|
||||
val totalBytes = totalWordCount * Int.SIZE_BYTES
|
||||
val buffers = IntArray(1)
|
||||
GLES31.glGenBuffers(1, buffers, 0)
|
||||
val bufferId = buffers[0]
|
||||
if (bufferId == 0) return null
|
||||
|
||||
val totalStartNs = System.nanoTime()
|
||||
return try {
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId)
|
||||
val zeroData = ByteBuffer.allocateDirect(totalBytes).order(ByteOrder.nativeOrder())
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
totalBytes,
|
||||
zeroData,
|
||||
GLES31.GL_DYNAMIC_READ
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, BUFFER_BINDING, bufferId)
|
||||
GLES31.glUseProgram(statsProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId)
|
||||
GLES31.glUniform1i(uniform("uRawTexture"), 0)
|
||||
GLES31.glUniform2i(uniform("uImageSize"), width, height)
|
||||
GLES31.glUniform4i(
|
||||
uniform("uStatsBounds"),
|
||||
safeBounds.left,
|
||||
safeBounds.top,
|
||||
safeBounds.right,
|
||||
safeBounds.bottom
|
||||
)
|
||||
GLES31.glUniform2i(uniform("uGridSize"), gridWidth, gridHeight)
|
||||
GLES31.glUniform1i(uniform("uSamplesPerPixel"), samplesPerPixel.coerceAtLeast(1))
|
||||
GLES31.glUniform1i(uniform("uCfaPattern"), metadata.cfaPattern)
|
||||
GLES31.glUniform4fv(uniform("uBlackLevel"), 1, safeBlackLevel(metadata), 0)
|
||||
GLES31.glUniform1f(uniform("uWhiteLevel"), metadata.whiteLevel.coerceAtLeast(1f))
|
||||
GLES31.glUniform1f(
|
||||
uniform("uBaselineExposureGain"),
|
||||
2.0f.pow(DngBaselineExposure.sanitize(metadata.baselineExposure).coerceIn(0f, 8f))
|
||||
)
|
||||
GLES31.glUniformMatrix3fv(
|
||||
uniform("uColorCorrectionMatrix"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(metadata.colorCorrectionMatrix),
|
||||
0
|
||||
)
|
||||
GLES31.glUniform1i(uniform("uCellSumsOffset"), cellSumsOffset)
|
||||
GLES31.glUniform1i(uniform("uGlobalHistogramOffset"), globalHistogramOffset)
|
||||
GLES31.glUniform1i(uniform("uGlobalCountersOffset"), globalCountersOffset)
|
||||
|
||||
val dispatchStartNs = System.nanoTime()
|
||||
GLES31.glDispatchCompute(gridWidth, gridHeight, 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
|
||||
)
|
||||
checkGlError("dispatch")
|
||||
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId)
|
||||
val mapped = GLES31.glMapBufferRange(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
0,
|
||||
totalBytes,
|
||||
GLES31.GL_MAP_READ_BIT
|
||||
) as? ByteBuffer ?: error("GPU RAW PGTM stats buffer map failed")
|
||||
val words = try {
|
||||
IntArray(totalWordCount).also { values ->
|
||||
mapped.order(ByteOrder.nativeOrder()).asIntBuffer().get(values)
|
||||
}
|
||||
} finally {
|
||||
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
|
||||
}
|
||||
val statsReadyNs = System.nanoTime()
|
||||
|
||||
val packedCellStats = FloatArray(cellStatsWordCount) { index ->
|
||||
Float.fromBits(words[index])
|
||||
}
|
||||
val sampleCount = words[globalCountersOffset + COUNTER_SAMPLE_COUNT]
|
||||
.coerceIn(0, cellCount * SAMPLE_COUNT_PER_CELL)
|
||||
val zeroCount = words[globalCountersOffset + COUNTER_ZERO_COUNT]
|
||||
.coerceIn(0, sampleCount)
|
||||
val highlightCount = words[globalCountersOffset + COUNTER_HIGHLIGHT_COUNT]
|
||||
.coerceIn(0, sampleCount)
|
||||
val maxInput = Float.fromBits(words[globalCountersOffset + COUNTER_MAX_INPUT_BITS])
|
||||
var linearSum = 0.0
|
||||
var logSum = 0.0
|
||||
for (cellIndex in 0 until cellCount) {
|
||||
val offset = cellSumsOffset + cellIndex * CELL_SUM_FLOAT_STRIDE
|
||||
linearSum += Float.fromBits(words[offset]).toDouble()
|
||||
logSum += Float.fromBits(words[offset + 1]).toDouble()
|
||||
}
|
||||
val globalHistogram = IntArray(GLOBAL_HISTOGRAM_BIN_COUNT) { index ->
|
||||
words[globalHistogramOffset + index].coerceAtLeast(0)
|
||||
}
|
||||
val globalStats = DngPgtmGlobalStats.fromLogHistogram(
|
||||
logHistogram = globalHistogram,
|
||||
histogramMinEv = GLOBAL_HISTOGRAM_MIN_EV,
|
||||
histogramMaxEv = GLOBAL_HISTOGRAM_MAX_EV,
|
||||
sampleCount = sampleCount,
|
||||
zeroCount = zeroCount,
|
||||
highlightCount = highlightCount,
|
||||
maxInput = maxInput,
|
||||
linearSum = linearSum,
|
||||
logSum = logSum
|
||||
)
|
||||
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU RAW")
|
||||
val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure)
|
||||
val map = when (profileToneMapMode) {
|
||||
RawProfileToneMapMode.Photon -> DngPhotonProfileGainTableGenerator.forCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
globalStats = globalStats ?: error("GPU RAW PGTM global stats are empty"),
|
||||
diagnosticBand = diagnosticBand
|
||||
)
|
||||
|
||||
RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
diagnosticBand = diagnosticBand
|
||||
)
|
||||
|
||||
RawProfileToneMapMode.Default,
|
||||
RawProfileToneMapMode.OppoMaster -> null
|
||||
}
|
||||
val completeNs = System.nanoTime()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU RAW PGTM built: mode=$profileToneMapMode grid=${gridWidth}x${gridHeight} " +
|
||||
"samples=$sampleCount readbackBytes=$totalBytes " +
|
||||
"gpuAndReadbackMs=${(statsReadyNs - dispatchStartNs) / 1_000_000.0} " +
|
||||
"curveMs=${(completeNs - statsReadyNs) / 1_000_000.0} " +
|
||||
"totalMs=${(completeNs - totalStartNs) / 1_000_000.0}"
|
||||
)
|
||||
map
|
||||
} catch (error: Exception) {
|
||||
PLog.w(TAG, "GPU RAW PGTM generation failed", error)
|
||||
null
|
||||
} finally {
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, BUFFER_BINDING, 0)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
GLES31.glUseProgram(0)
|
||||
GLES31.glDeleteBuffers(1, buffers, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun uniform(name: String): Int = GLES31.glGetUniformLocation(statsProgram, name)
|
||||
|
||||
private fun sanitizeStatsBounds(statsBounds: Rect?, width: Int, height: Int): Rect? {
|
||||
val imageBounds = Rect(0, 0, width, height)
|
||||
if (statsBounds == null) return imageBounds
|
||||
if (statsBounds.isEmpty) return null
|
||||
return Rect(statsBounds).takeIf {
|
||||
it.intersect(imageBounds) && it.width() >= 2 && it.height() >= 2
|
||||
}
|
||||
}
|
||||
|
||||
private fun safeBlackLevel(metadata: RawMetadata): FloatArray {
|
||||
val fallback = metadata.blackLevel.firstOrNull() ?: 0f
|
||||
return FloatArray(4) { index -> metadata.blackLevel.getOrElse(index) { fallback } }
|
||||
}
|
||||
|
||||
private fun transposeMatrix3x3(matrix: FloatArray): FloatArray {
|
||||
if (matrix.size < 9) {
|
||||
return floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
|
||||
}
|
||||
return floatArrayOf(
|
||||
matrix[0], matrix[3], matrix[6],
|
||||
matrix[1], matrix[4], matrix[7],
|
||||
matrix[2], matrix[5], matrix[8]
|
||||
)
|
||||
}
|
||||
|
||||
private fun compileComputeProgram(source: String): Int {
|
||||
val shader = GLES31.glCreateShader(GLES31.GL_COMPUTE_SHADER)
|
||||
GLES31.glShaderSource(shader, source)
|
||||
GLES31.glCompileShader(shader)
|
||||
val compiled = IntArray(1)
|
||||
GLES31.glGetShaderiv(shader, GLES31.GL_COMPILE_STATUS, compiled, 0)
|
||||
if (compiled[0] == 0) {
|
||||
PLog.e(TAG, "GPU RAW PGTM shader compilation failed: ${GLES31.glGetShaderInfoLog(shader)}")
|
||||
GLES31.glDeleteShader(shader)
|
||||
return 0
|
||||
}
|
||||
val program = GLES31.glCreateProgram()
|
||||
GLES31.glAttachShader(program, shader)
|
||||
GLES31.glLinkProgram(program)
|
||||
GLES31.glDeleteShader(shader)
|
||||
val linked = IntArray(1)
|
||||
GLES31.glGetProgramiv(program, GLES31.GL_LINK_STATUS, linked, 0)
|
||||
if (linked[0] == 0) {
|
||||
PLog.e(TAG, "GPU RAW PGTM program linking failed: ${GLES31.glGetProgramInfoLog(program)}")
|
||||
GLES31.glDeleteProgram(program)
|
||||
return 0
|
||||
}
|
||||
return program
|
||||
}
|
||||
|
||||
private fun checkGlError(stage: String) {
|
||||
val error = GLES31.glGetError()
|
||||
if (error != GLES31.GL_NO_ERROR) error("GPU RAW PGTM $stage failed: glError=$error")
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val TAG = "GlesRawPgtmBuilder"
|
||||
private const val BUFFER_BINDING = 7
|
||||
private const val SAMPLE_GRID = 16
|
||||
private const val SAMPLE_COUNT_PER_CELL = SAMPLE_GRID * SAMPLE_GRID
|
||||
private const val CELL_SUM_FLOAT_STRIDE = 2
|
||||
private const val GLOBAL_HISTOGRAM_BIN_COUNT = 2048
|
||||
private const val GLOBAL_HISTOGRAM_MIN_EV = -16f
|
||||
private const val GLOBAL_HISTOGRAM_MAX_EV = 8f
|
||||
private const val GLOBAL_COUNTER_COUNT = 4
|
||||
private const val COUNTER_SAMPLE_COUNT = 0
|
||||
private const val COUNTER_ZERO_COUNT = 1
|
||||
private const val COUNTER_HIGHLIGHT_COUNT = 2
|
||||
private const val COUNTER_MAX_INPUT_BITS = 3
|
||||
|
||||
private val PGTM_STATS_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
|
||||
uniform highp usampler2D uRawTexture;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
uniform ivec2 uGridSize;
|
||||
uniform int uSamplesPerPixel;
|
||||
uniform int uCfaPattern;
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
uniform float uBaselineExposureGain;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform int uCellSumsOffset;
|
||||
uniform int uGlobalHistogramOffset;
|
||||
uniform int uGlobalCountersOffset;
|
||||
|
||||
layout(std430, binding = $BUFFER_BINDING) buffer PgtmData {
|
||||
uint data[];
|
||||
};
|
||||
|
||||
const int SAMPLE_GRID = 16;
|
||||
const int SAMPLE_COUNT = 256;
|
||||
const int STATS_STRIDE = 8;
|
||||
const int CELL_SUM_STRIDE = 2;
|
||||
const int GLOBAL_HISTOGRAM_BINS = 2048;
|
||||
const float GLOBAL_HISTOGRAM_MIN_EV = -16.0;
|
||||
const float GLOBAL_HISTOGRAM_MAX_EV = 8.0;
|
||||
const float INV_LOG_2 = 1.4426950408889634;
|
||||
const int COUNTER_SAMPLE_COUNT = 0;
|
||||
const int COUNTER_ZERO_COUNT = 1;
|
||||
const int COUNTER_HIGHLIGHT_COUNT = 2;
|
||||
const int COUNTER_MAX_INPUT_BITS = 3;
|
||||
|
||||
shared float inputSamples[SAMPLE_COUNT];
|
||||
|
||||
int baseBayerPattern() {
|
||||
return uCfaPattern >= 8 ? uCfaPattern - 8 :
|
||||
(uCfaPattern >= 4 ? uCfaPattern - 4 : uCfaPattern);
|
||||
}
|
||||
|
||||
int cfaBlockSize() {
|
||||
return uCfaPattern >= 8 ? 4 : (uCfaPattern >= 4 ? 2 : 1);
|
||||
}
|
||||
|
||||
int channelIndexAt(ivec2 p) {
|
||||
int blockSize = cfaBlockSize();
|
||||
int xp = (p.x / blockSize) & 1;
|
||||
int yp = (p.y / blockSize) & 1;
|
||||
int pattern = baseBayerPattern();
|
||||
if (pattern == 1) {
|
||||
if (yp == 0 && xp == 0) return 1;
|
||||
if (yp == 0 && xp == 1) return 0;
|
||||
if (yp == 1 && xp == 0) return 3;
|
||||
return 2;
|
||||
}
|
||||
if (pattern == 2) {
|
||||
if (yp == 0 && xp == 0) return 2;
|
||||
if (yp == 0 && xp == 1) return 3;
|
||||
if (yp == 1 && xp == 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
if (pattern == 3) {
|
||||
if (yp == 0 && xp == 0) return 3;
|
||||
if (yp == 0 && xp == 1) return 2;
|
||||
if (yp == 1 && xp == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
if (yp == 0 && xp == 0) return 0;
|
||||
if (yp == 0 && xp == 1) return 1;
|
||||
if (yp == 1 && xp == 0) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
float normalizeRaw(uint raw, int channel) {
|
||||
float black = uBlackLevel[clamp(channel, 0, 3)];
|
||||
return clamp((float(raw) - black) / max(uWhiteLevel - black, 1.0), 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec3 cameraRgbAt(ivec2 base) {
|
||||
if (uSamplesPerPixel >= 3) {
|
||||
ivec2 p = clamp(base, ivec2(0), uImageSize - ivec2(1));
|
||||
uvec3 raw = texelFetch(uRawTexture, p, 0).rgb;
|
||||
return vec3(
|
||||
normalizeRaw(raw.r, 0),
|
||||
normalizeRaw(raw.g, 1),
|
||||
normalizeRaw(raw.b, 2)
|
||||
);
|
||||
}
|
||||
vec3 sums = vec3(0.0);
|
||||
vec3 counts = vec3(0.0);
|
||||
for (int y = 0; y <= 1; ++y) {
|
||||
for (int x = 0; x <= 1; ++x) {
|
||||
ivec2 p = clamp(base + ivec2(x, y), ivec2(0), uImageSize - ivec2(1));
|
||||
int channel = channelIndexAt(p);
|
||||
float value = normalizeRaw(texelFetch(uRawTexture, p, 0).r, channel);
|
||||
if (channel == 0) {
|
||||
sums.r += value;
|
||||
counts.r += 1.0;
|
||||
} else if (channel == 3) {
|
||||
sums.b += value;
|
||||
counts.b += 1.0;
|
||||
} else {
|
||||
sums.g += value;
|
||||
counts.g += 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
float fallback = (sums.r + sums.g + sums.b) /
|
||||
max(counts.r + counts.g + counts.b, 1.0);
|
||||
return vec3(
|
||||
counts.r > 0.0 ? sums.r / counts.r : fallback,
|
||||
counts.g > 0.0 ? sums.g / counts.g : fallback,
|
||||
counts.b > 0.0 ? sums.b / counts.b : fallback
|
||||
);
|
||||
}
|
||||
|
||||
float pgtmInputAt(ivec2 base) {
|
||||
vec3 profileRgb = uColorCorrectionMatrix * cameraRgbAt(base) *
|
||||
uBaselineExposureGain;
|
||||
float minChannel = min(profileRgb.r, min(profileRgb.g, profileRgb.b));
|
||||
float maxChannel = max(profileRgb.r, max(profileRgb.g, profileRgb.b));
|
||||
float value =
|
||||
0.1495 * profileRgb.r +
|
||||
0.2935 * profileRgb.g +
|
||||
0.0570 * profileRgb.b +
|
||||
0.1250 * minChannel +
|
||||
0.3750 * maxChannel;
|
||||
return isnan(value) || isinf(value) ? 0.0 : max(value, 0.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 cell = ivec2(gl_WorkGroupID.xy);
|
||||
if (cell.x >= uGridSize.x || cell.y >= uGridSize.y) return;
|
||||
ivec2 localId = ivec2(gl_LocalInvocationID.xy);
|
||||
int localIndex = localId.y * SAMPLE_GRID + localId.x;
|
||||
int cellIndex = cell.y * uGridSize.x + cell.x;
|
||||
|
||||
ivec2 statsMin = clamp(uStatsBounds.xy, ivec2(0), uImageSize - ivec2(1));
|
||||
ivec2 statsMax = clamp(uStatsBounds.zw, statsMin + ivec2(1), uImageSize);
|
||||
ivec2 statsSize = max(statsMax - statsMin, ivec2(2));
|
||||
int startX = statsMin.x + (cell.x * statsSize.x) / uGridSize.x;
|
||||
int endX = statsMin.x + ((cell.x + 1) * statsSize.x + uGridSize.x - 1) /
|
||||
uGridSize.x;
|
||||
int startY = statsMin.y + (cell.y * statsSize.y) / uGridSize.y;
|
||||
int endY = statsMin.y + ((cell.y + 1) * statsSize.y + uGridSize.y - 1) /
|
||||
uGridSize.y;
|
||||
startX += startX & 1;
|
||||
startY += startY & 1;
|
||||
endX = min(statsMax.x, endX - (endX & 1));
|
||||
endY = min(statsMax.y, endY - (endY & 1));
|
||||
|
||||
if (endX - startX < 2 || endY - startY < 2) {
|
||||
if (localIndex == 0) {
|
||||
int offset = cellIndex * STATS_STRIDE;
|
||||
for (int i = 0; i < STATS_STRIDE; ++i) data[offset + i] = 0u;
|
||||
int sumOffset = uCellSumsOffset + cellIndex * CELL_SUM_STRIDE;
|
||||
data[sumOffset] = floatBitsToUint(0.0);
|
||||
data[sumOffset + 1] = floatBitsToUint(0.0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
int cellWidth = max(endX - startX, 2);
|
||||
int cellHeight = max(endY - startY, 2);
|
||||
int x = startX + ((localId.x * 2 + 1) * cellWidth) / (SAMPLE_GRID * 2);
|
||||
int y = startY + ((localId.y * 2 + 1) * cellHeight) / (SAMPLE_GRID * 2);
|
||||
x = clamp(x - (x & 1), startX, max(startX, endX - 2));
|
||||
y = clamp(y - (y & 1), startY, max(startY, endY - 2));
|
||||
float inputValue = pgtmInputAt(ivec2(x, y));
|
||||
inputSamples[localIndex] = inputValue;
|
||||
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_SAMPLE_COUNT], 1u);
|
||||
if (inputValue <= 0.0) {
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_ZERO_COUNT], 1u);
|
||||
} else {
|
||||
float ev = clamp(
|
||||
log(inputValue) * INV_LOG_2,
|
||||
GLOBAL_HISTOGRAM_MIN_EV,
|
||||
GLOBAL_HISTOGRAM_MAX_EV - 1e-5
|
||||
);
|
||||
int bin = clamp(
|
||||
int(floor(
|
||||
(ev - GLOBAL_HISTOGRAM_MIN_EV) /
|
||||
(GLOBAL_HISTOGRAM_MAX_EV - GLOBAL_HISTOGRAM_MIN_EV) *
|
||||
float(GLOBAL_HISTOGRAM_BINS)
|
||||
)),
|
||||
0,
|
||||
GLOBAL_HISTOGRAM_BINS - 1
|
||||
);
|
||||
atomicAdd(data[uGlobalHistogramOffset + bin], 1u);
|
||||
}
|
||||
if (inputValue >= 0.92) {
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_HIGHLIGHT_COUNT], 1u);
|
||||
}
|
||||
atomicMax(
|
||||
data[uGlobalCountersOffset + COUNTER_MAX_INPUT_BITS],
|
||||
floatBitsToUint(inputValue)
|
||||
);
|
||||
barrier();
|
||||
|
||||
for (uint sequence = 2u; sequence <= 256u; sequence <<= 1u) {
|
||||
for (uint distance = sequence >> 1u; distance > 0u; distance >>= 1u) {
|
||||
uint index = uint(localIndex);
|
||||
uint peer = index ^ distance;
|
||||
if (peer > index) {
|
||||
float own = inputSamples[index];
|
||||
float other = inputSamples[peer];
|
||||
bool ascending = (index & sequence) == 0u;
|
||||
if ((ascending && own > other) || (!ascending && own < other)) {
|
||||
inputSamples[index] = other;
|
||||
inputSamples[peer] = own;
|
||||
}
|
||||
}
|
||||
barrier();
|
||||
}
|
||||
}
|
||||
|
||||
if (localIndex != 0) return;
|
||||
float linearSum = 0.0;
|
||||
float logSum = 0.0;
|
||||
int highlightCount = 0;
|
||||
for (int i = 0; i < SAMPLE_COUNT; ++i) {
|
||||
float value = inputSamples[i];
|
||||
linearSum += value;
|
||||
logSum += log(max(value, 1e-6));
|
||||
if (value >= 0.92) highlightCount += 1;
|
||||
}
|
||||
int offset = cellIndex * STATS_STRIDE;
|
||||
data[offset + 0] = floatBitsToUint(inputSamples[25]);
|
||||
data[offset + 1] = floatBitsToUint(inputSamples[127]);
|
||||
data[offset + 2] = floatBitsToUint(inputSamples[230]);
|
||||
data[offset + 3] = floatBitsToUint(inputSamples[250]);
|
||||
data[offset + 4] = floatBitsToUint(float(highlightCount) / float(SAMPLE_COUNT));
|
||||
data[offset + 5] = floatBitsToUint(float(SAMPLE_COUNT));
|
||||
data[offset + 6] = floatBitsToUint(inputSamples[254]);
|
||||
data[offset + 7] = floatBitsToUint(inputSamples[255]);
|
||||
int sumOffset = uCellSumsOffset + cellIndex * CELL_SUM_STRIDE;
|
||||
data[sumOffset] = floatBitsToUint(linearSum);
|
||||
data[sumOffset + 1] = floatBitsToUint(logSum);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -270,6 +270,7 @@ class RawDemosaicProcessor {
|
||||
private var rawHdrLinearAccumulateProgram = 0
|
||||
private var rawHdrLinearNormalizeProgram = 0
|
||||
private var rawHdrLinearPreviewProgram = 0
|
||||
private val rawProfileGainTableGpuBuilder = GlesRawProfileGainTableMapBuilder()
|
||||
private var filmicHrMaskProgram = 0
|
||||
private var filmicHrInpaintNoiseProgram = 0
|
||||
private var filmicHrInitReconstructProgram = 0
|
||||
@@ -1279,6 +1280,7 @@ class RawDemosaicProcessor {
|
||||
var dngRawDataCleanup: DngRawData? = null
|
||||
var embeddedDngJpegPreview: Bitmap? = null
|
||||
var dngWarpRectilinear: FloatArray? = null
|
||||
var rawTexturePreparedForPgtm = false
|
||||
val requestedColorEngine = rawRenderingEngine
|
||||
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
|
||||
val profileWorkingColorSpace = ColorSpace.ProPhoto
|
||||
@@ -1450,9 +1452,6 @@ class RawDemosaicProcessor {
|
||||
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
|
||||
val autoExposurePreview = capturePreviewThumbnail
|
||||
?: embeddedDngJpegPreview.takeIf { useEmbeddedPreviewForAutoExposure }
|
||||
if (capturePreviewThumbnail == null && autoExposurePreview != null) {
|
||||
PLog.d(TAG, "Using embedded DNG JPEG preview for RAW auto exposure")
|
||||
}
|
||||
val rawAeContentBounds = resolveRawAeContentBounds(
|
||||
rawSourceBounds = outputSourceBounds,
|
||||
outputRotation = actualRotation,
|
||||
@@ -1564,16 +1563,48 @@ class RawDemosaicProcessor {
|
||||
PLog.d(TAG, "Using embedded $embeddedProfileToneMapMode DNG PGTM/ProfileToneCurve")
|
||||
}
|
||||
if (generateProfileGainToneMap) {
|
||||
val generatedProfileGainTableMap = RawProfileGainTableMapBuilder.build(
|
||||
rawData = actualRawData,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
rowStride = actualRowStride,
|
||||
metadata = actualMetadata,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
statsBounds = outputSourceBounds,
|
||||
profileToneMapMode = requestedProfileToneMapMode
|
||||
)
|
||||
val generatedProfileGainTableMap = try {
|
||||
val initialized = isInitialized || initialize()
|
||||
if (!initialized) {
|
||||
null
|
||||
} else if (actualWidth > maxTextureSize || actualHeight > maxTextureSize) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU PGTM input ${actualWidth}x$actualHeight exceeds " +
|
||||
"GL_MAX_TEXTURE_SIZE=$maxTextureSize"
|
||||
)
|
||||
null
|
||||
} else {
|
||||
if (actualSamplesPerPixel >= 3) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
} else {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
}
|
||||
rawTexturePreparedForPgtm = true
|
||||
rawProfileGainTableGpuBuilder.build(
|
||||
rawTextureId = rawTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
metadata = actualMetadata,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
statsBounds = outputSourceBounds,
|
||||
profileToneMapMode = requestedProfileToneMapMode
|
||||
)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
PLog.w(TAG, "Failed to prepare GPU RAW PGTM generation", error)
|
||||
null
|
||||
}
|
||||
if (generatedProfileGainTableMap?.isValid == true) {
|
||||
actualMetadata = actualMetadata.copy(profileGainTableMap = generatedProfileGainTableMap)
|
||||
PLog.d(
|
||||
@@ -1634,6 +1665,9 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
else -> profileBaseDcpRenderPlan
|
||||
}
|
||||
val photonToneCurveActive = DngProfileToneCurve.isPhotonPgtmToneCurveLut(
|
||||
activeDcpRenderPlan?.toneCurveLut
|
||||
)
|
||||
val profilePlanSource = when {
|
||||
profileGainToneMapActive -> when {
|
||||
dcpRenderPlan != null -> "provided+${requestedProfileToneMapMode.name.lowercase()}-tone-map"
|
||||
@@ -1693,7 +1727,14 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
val viewfinderThumbnailMeteringImage = when {
|
||||
!rawAutoExposure -> null
|
||||
photonToneCurveActive -> {
|
||||
PLog.d(TAG, "RAW auto exposure disabled: Photon tone curve is active")
|
||||
null
|
||||
}
|
||||
else -> {
|
||||
if (capturePreviewThumbnail == null && autoExposurePreview != null) {
|
||||
PLog.d(TAG, "Using embedded DNG JPEG preview for RAW auto exposure")
|
||||
}
|
||||
analyzeSrgbThumbnailForMetering(
|
||||
autoExposurePreview,
|
||||
rawAeContentBounds?.thumbnailBounds
|
||||
@@ -1739,12 +1780,14 @@ class RawDemosaicProcessor {
|
||||
// 4. 第一步:全分辨率处理 (Linear CCM / RCD Compute Shader Demosaic)
|
||||
setupFullResFramebuffer(actualWidth, actualHeight)
|
||||
if (actualSamplesPerPixel == 3) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
if (!rawTexturePreparedForPgtm) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
}
|
||||
actualRawData = null
|
||||
renderLinearRawRgbToFramebuffer(
|
||||
sourceTextureId = rawTextureId,
|
||||
@@ -1758,12 +1801,14 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
PLog.d(TAG, "LinearRaw RGB input prepared on GPU: ${actualWidth}x${actualHeight}")
|
||||
} else {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
if (!rawTexturePreparedForPgtm) {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
}
|
||||
// GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB)
|
||||
actualRawData = null
|
||||
|
||||
@@ -3316,6 +3361,7 @@ class RawDemosaicProcessor {
|
||||
quadChromaProgram = compileComputeProgram(QuadBayerShaders.CHROMA, "QUAD_CHROMA")
|
||||
quadRefineProgram = compileComputeProgram(QuadBayerShaders.REFINE, "QUAD_REFINE")
|
||||
quadWriteOutputProgram = compileComputeProgram(QuadBayerShaders.WRITE_OUTPUT, "QUAD_WRITE_OUTPUT")
|
||||
rawProfileGainTableGpuBuilder.initialize()
|
||||
|
||||
val fShaderLinearRcd = compileShader(
|
||||
GLES30.GL_FRAGMENT_SHADER,
|
||||
@@ -8582,6 +8628,7 @@ class RawDemosaicProcessor {
|
||||
if (rawHdrLinearAccumulateProgram != 0) GLES31.glDeleteProgram(rawHdrLinearAccumulateProgram)
|
||||
if (rawHdrLinearNormalizeProgram != 0) GLES31.glDeleteProgram(rawHdrLinearNormalizeProgram)
|
||||
if (rawHdrLinearPreviewProgram != 0) GLES31.glDeleteProgram(rawHdrLinearPreviewProgram)
|
||||
rawProfileGainTableGpuBuilder.release()
|
||||
|
||||
// darktable denoiseprofile compute programs
|
||||
if (denoisePreconditionV2Program != 0) GLES31.glDeleteProgram(denoisePreconditionV2Program)
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.pow
|
||||
|
||||
@@ -66,7 +67,90 @@ class DngPgtmGlobalStatsTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gpuLogHistogramPreservesSceneWideStatistics() {
|
||||
val samples = FloatArray(1_000) { index -> (index + 1).toFloat() / 1_000f }
|
||||
val histogram = buildGpuLogHistogram(samples)
|
||||
val linearSum = samples.sumOf { it.toDouble() }
|
||||
val logSum = samples.sumOf { ln(it.coerceAtLeast(1e-6f).toDouble()) }
|
||||
|
||||
val stats = DngPgtmGlobalStats.fromLogHistogram(
|
||||
logHistogram = histogram,
|
||||
histogramMinEv = GPU_HISTOGRAM_MIN_EV,
|
||||
histogramMaxEv = GPU_HISTOGRAM_MAX_EV,
|
||||
sampleCount = samples.size,
|
||||
zeroCount = 0,
|
||||
highlightCount = samples.count { it >= 0.92f },
|
||||
maxInput = samples.max(),
|
||||
linearSum = linearSum,
|
||||
logSum = logSum
|
||||
) ?: error("Expected GPU histogram stats")
|
||||
|
||||
assertEquals(0.100f, stats.p10, 0.002f)
|
||||
assertEquals(0.500f, stats.p50, 0.004f)
|
||||
assertEquals(0.900f, stats.p90, 0.006f)
|
||||
assertEquals(0.980f, stats.p98, 0.008f)
|
||||
assertEquals(0.995f, stats.p995, 0.008f)
|
||||
assertEquals(0.999f, stats.p999, 0.008f)
|
||||
assertEquals(1.000f, stats.maxInput, 1e-6f)
|
||||
assertEquals(0.081f, stats.highlightFraction, 1e-6f)
|
||||
assertEquals(0.5005f, stats.linearMean, 1e-6f)
|
||||
assertEquals(
|
||||
exp(logSum / samples.size.toDouble()).toFloat(),
|
||||
stats.logAverage,
|
||||
1e-6f
|
||||
)
|
||||
assertEquals(samples.size, stats.sampleCount)
|
||||
assertTrue(stats.shadowFoot in 0f..stats.shadowEdge)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gpuLogHistogramKeepsZerosInLinearPercentilesOnly() {
|
||||
val samples = FloatArray(100) { index -> if (index < 20) 0f else 0.25f }
|
||||
val histogram = buildGpuLogHistogram(samples)
|
||||
val stats = DngPgtmGlobalStats.fromLogHistogram(
|
||||
logHistogram = histogram,
|
||||
histogramMinEv = GPU_HISTOGRAM_MIN_EV,
|
||||
histogramMaxEv = GPU_HISTOGRAM_MAX_EV,
|
||||
sampleCount = samples.size,
|
||||
zeroCount = 20,
|
||||
highlightCount = 0,
|
||||
maxInput = 0.25f,
|
||||
linearSum = samples.sumOf { it.toDouble() },
|
||||
logSum = samples.sumOf { ln(it.coerceAtLeast(1e-6f).toDouble()) }
|
||||
) ?: error("Expected GPU histogram stats")
|
||||
|
||||
assertEquals(0f, stats.p10, 0f)
|
||||
assertEquals(0.25f, stats.p50, 0.003f)
|
||||
assertTrue(stats.shadowEdge > 0f)
|
||||
assertTrue(stats.shadowFoot in 0f..stats.shadowEdge)
|
||||
}
|
||||
|
||||
private fun buildGpuLogHistogram(samples: FloatArray): IntArray {
|
||||
val histogram = IntArray(GPU_HISTOGRAM_BIN_COUNT)
|
||||
samples.forEach { value ->
|
||||
if (value <= 0f) return@forEach
|
||||
val ev = log2(value).coerceIn(
|
||||
GPU_HISTOGRAM_MIN_EV,
|
||||
GPU_HISTOGRAM_MAX_EV - 1e-5f
|
||||
)
|
||||
val bin = floor(
|
||||
(ev - GPU_HISTOGRAM_MIN_EV) /
|
||||
(GPU_HISTOGRAM_MAX_EV - GPU_HISTOGRAM_MIN_EV) *
|
||||
GPU_HISTOGRAM_BIN_COUNT.toFloat()
|
||||
).toInt().coerceIn(0, histogram.lastIndex)
|
||||
histogram[bin] += 1
|
||||
}
|
||||
return histogram
|
||||
}
|
||||
|
||||
private fun log2(value: Float): Float {
|
||||
return (ln(value.toDouble()) / ln(2.0)).toFloat()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val GPU_HISTOGRAM_BIN_COUNT = 2048
|
||||
private const val GPU_HISTOGRAM_MIN_EV = -16f
|
||||
private const val GPU_HISTOGRAM_MAX_EV = 8f
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user