feat: gpu pgtm generator
This commit is contained in:
1 parent
d5e504f718
commit
4c1413847e
17 files changed
+1064
-2897
No files matched your search
@@ -42,7 +42,7 @@ import com.hinnka.mycamera.raw.DngProfileGainTableMap
|
||||
import com.hinnka.mycamera.raw.DngProfileToneCurve
|
||||
import com.hinnka.mycamera.raw.RawDefaultCropOverride
|
||||
import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions
|
||||
import com.hinnka.mycamera.raw.RawDngViewfinderExposureMatcher
|
||||
import com.hinnka.mycamera.raw.RawDngCaptureProfilePreparer
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
@@ -3036,18 +3036,6 @@ object GalleryManager {
|
||||
if (!useGpuAcceleration) {
|
||||
PLog.w(TAG, "RAW HDR denoise requires GLES stacker; ignoring disabled GPU acceleration setting")
|
||||
}
|
||||
val rawHdrPgtmStatsBounds = resolveRawStatsBounds(
|
||||
width = rawMetadataImage.width,
|
||||
height = rawMetadataImage.height,
|
||||
defaultCrop = RawDefaultCropOverride.resolveRawBlackBorderDefaultCrop(
|
||||
width = rawMetadataImage.width,
|
||||
height = rawMetadataImage.height,
|
||||
rotation = rotation,
|
||||
rawBlackBorderCrop = metadata.rawBlackBorderCrop,
|
||||
metadataDefaultCrop = rawMetadata.defaultCrop
|
||||
),
|
||||
cropRegion = metadata.cropRegion
|
||||
)
|
||||
rawHdrStackResult = MultiFrameStacker.processHdrBurstRaw(
|
||||
shortFrame = RawHdrStackFrame(
|
||||
image = shortCandidate.image,
|
||||
@@ -3070,11 +3058,6 @@ object GalleryManager {
|
||||
lensShadingWidth = rawMetadata.lensShadingMapWidth,
|
||||
lensShadingHeight = rawMetadata.lensShadingMapHeight,
|
||||
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, metadata),
|
||||
colorCorrectionMatrix = rawMetadata.colorCorrectionMatrix,
|
||||
pgtmStatsBounds = rawHdrPgtmStatsBounds,
|
||||
// The shared DNG writer prepares baseline/PGTM from the fused buffer. Disable
|
||||
// the stacker's legacy generator so the write path owns the calculation once.
|
||||
profileToneMapMode = RawProfileToneMapMode.Default,
|
||||
)
|
||||
closeImagesNow(images)
|
||||
|
||||
@@ -3633,20 +3616,32 @@ object GalleryManager {
|
||||
rotation: Int,
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
): RawDngProfilePreparationOptions {
|
||||
val profileToneMapMode = rawDngPgtmModeForMetadata(metadata)
|
||||
val statsBounds = resolveRawStatsBounds(
|
||||
width = width,
|
||||
height = height,
|
||||
defaultCrop = defaultCrop,
|
||||
cropRegion = metadata.cropRegion,
|
||||
)
|
||||
val viewfinderMatchEnabled = capturePreviewThumbnail != null &&
|
||||
resolveRawAutoExposure(context, metadata) &&
|
||||
kotlin.math.abs(metadata.rawExposureCompensation ?: 0f) <= 0.0001f
|
||||
val viewfinderExposureMatcher = if (viewfinderMatchEnabled) {
|
||||
val preview = requireNotNull(capturePreviewThumbnail)
|
||||
RawDngViewfinderExposureMatcher { input ->
|
||||
RawViewfinderExposureMatcher.match(
|
||||
val profileGainTableRequired = profileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
profileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
val captureProfilePreparer = if (viewfinderMatchEnabled || profileGainTableRequired) {
|
||||
RawDngCaptureProfilePreparer { input ->
|
||||
RawViewfinderExposureMatcher.prepareCaptureProfile(
|
||||
renderer = RawDemosaicProcessor.getInstance(),
|
||||
context = context,
|
||||
input = input,
|
||||
aspectRatio = aspectRatio,
|
||||
cropRegion = metadata.cropRegion,
|
||||
rotation = rotation,
|
||||
capturePreviewThumbnail = preview,
|
||||
capturePreviewThumbnail = capturePreviewThumbnail.takeIf {
|
||||
viewfinderMatchEnabled
|
||||
},
|
||||
profileToneMapMode = profileToneMapMode,
|
||||
statsBounds = statsBounds,
|
||||
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
|
||||
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
|
||||
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(
|
||||
@@ -3666,18 +3661,14 @@ object GalleryManager {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_VIEWFINDER_BASELINE stage=DNG_PREPARE enabled=$viewfinderMatchEnabled " +
|
||||
"curve=DEFAULT pgtmDuringMatch=false sourceAutoExposure=${metadata.rawAutoExposure} " +
|
||||
"curve=DEFAULT pgtmOnGpu=$profileGainTableRequired " +
|
||||
"sourceAutoExposure=${metadata.rawAutoExposure} " +
|
||||
"manualExposureEv=${metadata.rawExposureCompensation ?: 0f}"
|
||||
)
|
||||
return RawDngProfilePreparationOptions(
|
||||
profileToneMapMode = rawDngPgtmModeForMetadata(metadata),
|
||||
statsBounds = resolveRawStatsBounds(
|
||||
width = width,
|
||||
height = height,
|
||||
defaultCrop = defaultCrop,
|
||||
cropRegion = metadata.cropRegion,
|
||||
),
|
||||
viewfinderExposureMatcher = viewfinderExposureMatcher,
|
||||
profileToneMapMode = profileToneMapMode,
|
||||
statsBounds = statsBounds,
|
||||
captureProfilePreparer = captureProfilePreparer,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.ImageFormat
|
||||
import android.graphics.Rect
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLConfig
|
||||
import android.opengl.EGLContext
|
||||
@@ -10,9 +9,6 @@ import android.opengl.EGLSurface
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.model.SafeImage
|
||||
import com.hinnka.mycamera.raw.DngHdrProfileGainTableGenerator
|
||||
import com.hinnka.mycamera.raw.DngPgtmDiagnostic
|
||||
import com.hinnka.mycamera.raw.DngPgtmGlobalStats
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.RcdShaders
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
@@ -22,7 +18,6 @@ import java.nio.ByteOrder
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class GlesRawStacker(
|
||||
@@ -37,9 +32,6 @@ class GlesRawStacker(
|
||||
private val lensShading: FloatArray?,
|
||||
private val lensShadingWidth: Int,
|
||||
private val lensShadingHeight: Int,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
pgtmStatsBounds: Rect? = null,
|
||||
private val profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon,
|
||||
private val tuning: RawStackTuningProfile = RawStackTuningResolver.resolve(RawStackMode.MFNR),
|
||||
debugConfig: RawStackDebugConfig = RawStackDebugConfig.Disabled,
|
||||
) {
|
||||
@@ -167,13 +159,6 @@ class GlesRawStacker(
|
||||
private val normalizedNoiseBetaByChannel = rawNoiseModel.normalizedReadNoiseForShader()
|
||||
private val noiseAlpha = rawNoiseModel.greenShotNoise.coerceAtLeast(0f) / 65535.0f
|
||||
private val noiseBeta = rawNoiseModel.greenReadNoise.coerceAtLeast(0f) / (65535.0f * 65535.0f)
|
||||
private val pgtmColorCorrectionMatrix = FloatArray(9) { index ->
|
||||
colorCorrectionMatrix
|
||||
?.getOrNull(index)
|
||||
?.takeIf { it.isFinite() }
|
||||
?: if (index % 4 == 0) 1f else 0f
|
||||
}
|
||||
private val pgtmStatsBounds = sanitizePgtmStatsBounds(pgtmStatsBounds)
|
||||
private val hwmfPrefilter = tuning.prefilter
|
||||
private val hwmfBlend = tuning.blend
|
||||
private val hwmfPostfilter = tuning.postfilter
|
||||
@@ -250,7 +235,6 @@ class GlesRawStacker(
|
||||
private var hdrNormalCfaInputProgram = 0
|
||||
private var hdrWorkingRgbStoreProgram = 0
|
||||
private var hdrRgbFusionProgram = 0
|
||||
private var pgtmStatsProgram = 0
|
||||
private var diagnosticAlignmentProgram = 0
|
||||
private var diagnosticFinalProgram = 0
|
||||
private var diagnosticBuffer = 0
|
||||
@@ -1299,204 +1283,6 @@ class GlesRawStacker(
|
||||
}.coerceIn(0f, 8f)
|
||||
}
|
||||
|
||||
private fun computeHdrProfileGainTableMap(
|
||||
baselineExposureEv: Float,
|
||||
): com.hinnka.mycamera.raw.DngProfileGainTableMap? {
|
||||
if (!baselineExposureEv.isFinite() || baselineExposureEv <= 0.05f || pgtmStatsProgram == 0) {
|
||||
return null
|
||||
}
|
||||
if (profileToneMapMode != RawProfileToneMapMode.GooglePixel &&
|
||||
profileToneMapMode != RawProfileToneMapMode.Photon
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
|
||||
val pgtmGridWidth = grid.getOrElse(0) { 0 }
|
||||
val pgtmGridHeight = grid.getOrElse(1) { 0 }
|
||||
if (pgtmGridWidth <= 0 || pgtmGridHeight <= 0) return null
|
||||
if (!pgtmStatsBounds.isFullImage()) {
|
||||
RawStackRuntimeDebug.d(TAG) {
|
||||
"GPU HDR PGTM stats bounds: source=${width}x$height bounds=$pgtmStatsBounds"
|
||||
}
|
||||
}
|
||||
|
||||
val cellCount = pgtmGridWidth * pgtmGridHeight
|
||||
val collectGlobalStats = false
|
||||
val cellStatsWordCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
val cellSumsOffset = if (collectGlobalStats) cellStatsWordCount else -1
|
||||
val globalHistogramOffset = if (collectGlobalStats) {
|
||||
cellSumsOffset + cellCount * PGTM_CELL_SUM_FLOAT_STRIDE
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
val globalCountersOffset = if (collectGlobalStats) {
|
||||
globalHistogramOffset + PGTM_GLOBAL_HISTOGRAM_BIN_COUNT
|
||||
} else {
|
||||
-1
|
||||
}
|
||||
val wordCount = if (collectGlobalStats) {
|
||||
globalCountersOffset + PGTM_GLOBAL_COUNTER_COUNT
|
||||
} else {
|
||||
cellStatsWordCount
|
||||
}
|
||||
val byteCount = wordCount * Int.SIZE_BYTES
|
||||
val totalStartNs = System.nanoTime()
|
||||
return try {
|
||||
val statsBufferId = prepareReadbackScratchBuffer(byteCount)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, statsBufferId)
|
||||
val zeroData = ByteBuffer.allocateDirect(byteCount).order(ByteOrder.nativeOrder())
|
||||
GLES31.glBufferSubData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
0,
|
||||
byteCount,
|
||||
zeroData,
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, PGTM_STATS_BUFFER_BINDING, statsBufferId)
|
||||
GLES31.glUseProgram(pgtmStatsProgram)
|
||||
bindTexture(pgtmStatsProgram, "uLinearRgb", 0, hdrLinearOutputTexture)
|
||||
GLES31.glUniform2i(uniformLocation(pgtmStatsProgram, "uImageSize"), width, height)
|
||||
GLES31.glUniform4i(
|
||||
uniformLocation(pgtmStatsProgram, "uStatsBounds"),
|
||||
pgtmStatsBounds.left,
|
||||
pgtmStatsBounds.top,
|
||||
pgtmStatsBounds.right,
|
||||
pgtmStatsBounds.bottom,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
uniformLocation(pgtmStatsProgram, "uGridSize"),
|
||||
pgtmGridWidth,
|
||||
pgtmGridHeight,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
uniformLocation(pgtmStatsProgram, "uCellSumsOffset"),
|
||||
cellSumsOffset
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
uniformLocation(pgtmStatsProgram, "uGlobalHistogramOffset"),
|
||||
globalHistogramOffset
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
uniformLocation(pgtmStatsProgram, "uGlobalCountersOffset"),
|
||||
globalCountersOffset
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
uniformLocation(pgtmStatsProgram, "uBaselineExposureGain"),
|
||||
2.0f.pow(baselineExposureEv.coerceIn(0f, 8f))
|
||||
)
|
||||
GLES31.glUniformMatrix3fv(
|
||||
uniformLocation(pgtmStatsProgram, "uColorCorrectionMatrix"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(pgtmColorCorrectionMatrix),
|
||||
0
|
||||
)
|
||||
val dispatchStartNs = System.nanoTime()
|
||||
GLES31.glDispatchCompute(pgtmGridWidth, pgtmGridHeight, 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
|
||||
)
|
||||
checkGlError("computeHdrProfileGainTableMap dispatch")
|
||||
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, statsBufferId)
|
||||
val mapped = GLES31.glMapBufferRange(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
0,
|
||||
byteCount,
|
||||
GLES31.GL_MAP_READ_BIT
|
||||
) ?: throw IllegalStateException("PGTM stats buffer map failed")
|
||||
val words = try {
|
||||
IntArray(wordCount).also { values ->
|
||||
val byteBuffer = mapped as? ByteBuffer
|
||||
?: throw IllegalStateException("PGTM stats buffer is not ByteBuffer")
|
||||
byteBuffer.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 globalStats = if (collectGlobalStats) {
|
||||
val sampleCount = words[globalCountersOffset + PGTM_COUNTER_SAMPLE_COUNT]
|
||||
.coerceIn(0, cellCount * PGTM_STATS_SAMPLE_COUNT)
|
||||
val zeroCount = words[globalCountersOffset + PGTM_COUNTER_ZERO_COUNT]
|
||||
.coerceIn(0, sampleCount)
|
||||
val highlightCount = words[globalCountersOffset + PGTM_COUNTER_HIGHLIGHT_COUNT]
|
||||
.coerceIn(0, sampleCount)
|
||||
val maxInput = Float.fromBits(
|
||||
words[globalCountersOffset + PGTM_COUNTER_MAX_INPUT_BITS]
|
||||
)
|
||||
var linearSum = 0.0
|
||||
var logSum = 0.0
|
||||
for (cellIndex in 0 until cellCount) {
|
||||
val offset = cellSumsOffset + cellIndex * PGTM_CELL_SUM_FLOAT_STRIDE
|
||||
linearSum += Float.fromBits(words[offset]).toDouble()
|
||||
logSum += Float.fromBits(words[offset + 1]).toDouble()
|
||||
}
|
||||
val globalHistogram = IntArray(PGTM_GLOBAL_HISTOGRAM_BIN_COUNT) { index ->
|
||||
words[globalHistogramOffset + index].coerceAtLeast(0)
|
||||
}
|
||||
DngPgtmGlobalStats.fromLogHistogram(
|
||||
logHistogram = globalHistogram,
|
||||
histogramMinEv = PGTM_GLOBAL_HISTOGRAM_MIN_EV,
|
||||
histogramMaxEv = PGTM_GLOBAL_HISTOGRAM_MAX_EV,
|
||||
sampleCount = sampleCount,
|
||||
zeroCount = zeroCount,
|
||||
highlightCount = highlightCount,
|
||||
maxInput = maxInput,
|
||||
linearSum = linearSum,
|
||||
logSum = logSum,
|
||||
)
|
||||
?: throw IllegalStateException("GPU Photon PGTM global stats are empty")
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU stacker")
|
||||
val generation = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
diagnosticBand = diagnosticBand,
|
||||
fusionParameters = if (profileToneMapMode == RawProfileToneMapMode.Photon) {
|
||||
DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS
|
||||
} else {
|
||||
DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS
|
||||
},
|
||||
)
|
||||
val completeNs = System.nanoTime()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU HDR PGTM built: mode=$profileToneMapMode grid=${pgtmGridWidth}x${pgtmGridHeight} " +
|
||||
"samples=${globalStats?.sampleCount ?: cellCount * PGTM_STATS_SAMPLE_COUNT} " +
|
||||
"readbackBytes=$byteCount " +
|
||||
"gpuAndReadbackMs=${(statsReadyNs - dispatchStartNs) / 1_000_000.0} " +
|
||||
"curveMs=${(completeNs - statsReadyNs) / 1_000_000.0} " +
|
||||
"totalMs=${(completeNs - totalStartNs) / 1_000_000.0}"
|
||||
)
|
||||
generation
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to compute GPU HDR PGTM stats", e)
|
||||
null
|
||||
} finally {
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, PGTM_STATS_BUFFER_BINDING, 0)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sanitizePgtmStatsBounds(bounds: Rect?): Rect {
|
||||
val imageBounds = Rect(0, 0, width.coerceAtLeast(1), height.coerceAtLeast(1))
|
||||
if (bounds == null || bounds.isEmpty) return imageBounds
|
||||
return Rect(bounds).takeIf {
|
||||
it.intersect(imageBounds) && it.width() >= 2 && it.height() >= 2
|
||||
} ?: imageBounds
|
||||
}
|
||||
|
||||
private fun Rect.isFullImage(): Boolean {
|
||||
return left == 0 && top == 0 && right == width && bottom == height
|
||||
}
|
||||
|
||||
private fun buildProxy(
|
||||
rawTexture: Int,
|
||||
proxyTexture: Int,
|
||||
@@ -5188,17 +4974,6 @@ class GlesRawStacker(
|
||||
private const val SUPER_RESOLUTION_STRIPE_ROWS = 256
|
||||
private const val SUPER_RESOLUTION_SPATIAL_RADIUS = 2
|
||||
private const val READBACK_STRIPE_ROWS = 128
|
||||
private const val PGTM_STATS_BUFFER_BINDING = 7
|
||||
private const val PGTM_STATS_SAMPLE_COUNT = 16 * 16
|
||||
private const val PGTM_CELL_SUM_FLOAT_STRIDE = 2
|
||||
private const val PGTM_GLOBAL_HISTOGRAM_BIN_COUNT = 1024
|
||||
private const val PGTM_GLOBAL_HISTOGRAM_MIN_EV = -16f
|
||||
private const val PGTM_GLOBAL_HISTOGRAM_MAX_EV = 8f
|
||||
private const val PGTM_GLOBAL_COUNTER_COUNT = 4
|
||||
private const val PGTM_COUNTER_SAMPLE_COUNT = 0
|
||||
private const val PGTM_COUNTER_ZERO_COUNT = 1
|
||||
private const val PGTM_COUNTER_HIGHLIGHT_COUNT = 2
|
||||
private const val PGTM_COUNTER_MAX_INPUT_BITS = 3
|
||||
private const val DIAGNOSTIC_BUFFER_BINDING = 9
|
||||
private const val REGISTRATION_SAMPLE_BUFFER_BINDING = 10
|
||||
private const val REGISTRATION_GLOBAL_SCORE_BUFFER_BINDING = 11
|
||||
@@ -7537,259 +7312,6 @@ class GlesRawStacker(
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val PGTM_STATS_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
$RAW_COMMON
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
uniform highp usampler2D uLinearRgb;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
uniform ivec2 uGridSize;
|
||||
uniform int uCellSumsOffset;
|
||||
uniform int uGlobalHistogramOffset;
|
||||
uniform int uGlobalCountersOffset;
|
||||
uniform float uBaselineExposureGain;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
layout(std430, binding = $PGTM_STATS_BUFFER_BINDING) buffer PgtmStats {
|
||||
uint data[];
|
||||
};
|
||||
|
||||
const int HIST_BINS = 256;
|
||||
const int STATS_STRIDE = 8;
|
||||
const int SAMPLE_GRID = 16;
|
||||
const int CELL_SUM_STRIDE = $PGTM_CELL_SUM_FLOAT_STRIDE;
|
||||
const int GLOBAL_HISTOGRAM_BINS = $PGTM_GLOBAL_HISTOGRAM_BIN_COUNT;
|
||||
const float GLOBAL_HISTOGRAM_MIN_EV = $PGTM_GLOBAL_HISTOGRAM_MIN_EV;
|
||||
const float GLOBAL_HISTOGRAM_MAX_EV = $PGTM_GLOBAL_HISTOGRAM_MAX_EV;
|
||||
const float INV_LOG_2 = 1.4426950408889634;
|
||||
const int COUNTER_SAMPLE_COUNT = $PGTM_COUNTER_SAMPLE_COUNT;
|
||||
const int COUNTER_ZERO_COUNT = $PGTM_COUNTER_ZERO_COUNT;
|
||||
const int COUNTER_HIGHLIGHT_COUNT = $PGTM_COUNTER_HIGHLIGHT_COUNT;
|
||||
const int COUNTER_MAX_INPUT_BITS = $PGTM_COUNTER_MAX_INPUT_BITS;
|
||||
shared uint hist[HIST_BINS];
|
||||
shared uint globalLogHist[GLOBAL_HISTOGRAM_BINS];
|
||||
shared float inputSamples[HIST_BINS];
|
||||
shared uint sampleCount;
|
||||
shared uint highlightCount;
|
||||
shared uint zeroCount;
|
||||
|
||||
vec3 linearRgbAt(ivec2 p) {
|
||||
p = clamp(p, ivec2(0), uImageSize - ivec2(1));
|
||||
return vec3(texelFetch(uLinearRgb, p, 0).rgb) * (1.0 / 65535.0);
|
||||
}
|
||||
|
||||
vec3 blockRgbAt(ivec2 base) {
|
||||
vec3 sum = 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));
|
||||
sum += linearRgbAt(p);
|
||||
}
|
||||
}
|
||||
return sum * 0.25;
|
||||
}
|
||||
|
||||
float pgtmInputAt(ivec2 base) {
|
||||
vec3 rgb = blockRgbAt(base);
|
||||
vec3 profileRgb = uColorCorrectionMatrix * rgb * uBaselineExposureGain;
|
||||
float minChannel = min(profileRgb.r, min(profileRgb.g, profileRgb.b));
|
||||
float maxChannel = max(profileRgb.r, max(profileRgb.g, profileRgb.b));
|
||||
return max(
|
||||
0.1495 * profileRgb.r +
|
||||
0.2935 * profileRgb.g +
|
||||
0.0570 * profileRgb.b +
|
||||
0.1250 * minChannel +
|
||||
0.3750 * maxChannel,
|
||||
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;
|
||||
|
||||
if (localIndex < HIST_BINS) {
|
||||
hist[localIndex] = 0u;
|
||||
}
|
||||
for (int bin = localIndex; bin < GLOBAL_HISTOGRAM_BINS; bin += HIST_BINS) {
|
||||
globalLogHist[bin] = 0u;
|
||||
}
|
||||
if (localIndex == 0) {
|
||||
sampleCount = 0u;
|
||||
highlightCount = 0u;
|
||||
zeroCount = 0u;
|
||||
}
|
||||
barrier();
|
||||
|
||||
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 cellIndex = cell.y * uGridSize.x + cell.x;
|
||||
int offset = cellIndex * STATS_STRIDE;
|
||||
for (int i = 0; i < STATS_STRIDE; ++i) {
|
||||
data[offset + i] = floatBitsToUint(0.0);
|
||||
}
|
||||
if (uCellSumsOffset >= 0) {
|
||||
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;
|
||||
if (uGlobalHistogramOffset >= 0) {
|
||||
if (inputValue <= 0.0) {
|
||||
atomicAdd(zeroCount, 1u);
|
||||
} else {
|
||||
float ev = clamp(
|
||||
log(inputValue) * INV_LOG_2,
|
||||
GLOBAL_HISTOGRAM_MIN_EV,
|
||||
GLOBAL_HISTOGRAM_MAX_EV - 1e-5
|
||||
);
|
||||
int globalBin = 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(globalLogHist[globalBin], 1u);
|
||||
}
|
||||
}
|
||||
float clampedInput = clamp(inputValue, 0.0, 1.0);
|
||||
uint bin = uint(clamp(int(floor(clampedInput * float(HIST_BINS - 1) + 0.5)), 0, HIST_BINS - 1));
|
||||
atomicAdd(hist[bin], 1u);
|
||||
atomicAdd(sampleCount, 1u);
|
||||
if (inputValue >= 0.92) {
|
||||
atomicAdd(highlightCount, 1u);
|
||||
}
|
||||
memoryBarrierShared();
|
||||
barrier();
|
||||
|
||||
if (uGlobalHistogramOffset >= 0) {
|
||||
for (int globalBin = localIndex;
|
||||
globalBin < GLOBAL_HISTOGRAM_BINS;
|
||||
globalBin += HIST_BINS
|
||||
) {
|
||||
uint count = globalLogHist[globalBin];
|
||||
if (count > 0u) {
|
||||
atomicAdd(data[uGlobalHistogramOffset + globalBin], count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (localIndex != 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
int samples = int(sampleCount);
|
||||
int target10 = max(1, int(ceil(float(samples) * 0.10)));
|
||||
int target50 = max(1, int(ceil(float(samples) * 0.50)));
|
||||
int target90 = max(1, int(ceil(float(samples) * 0.90)));
|
||||
int target98 = max(1, int(ceil(float(samples) * 0.98)));
|
||||
uint cumulative = 0u;
|
||||
float p10 = 1.0;
|
||||
float p50 = 1.0;
|
||||
float p90 = 1.0;
|
||||
float p98 = 1.0;
|
||||
float p995Input = 0.0;
|
||||
float p999Input = 0.0;
|
||||
bool got10 = false;
|
||||
bool got50 = false;
|
||||
bool got90 = false;
|
||||
bool got98 = false;
|
||||
for (int i = 0; i < HIST_BINS; ++i) {
|
||||
cumulative += hist[i];
|
||||
float value = float(i) / float(HIST_BINS - 1);
|
||||
if (!got10 && cumulative >= uint(target10)) {
|
||||
p10 = value;
|
||||
got10 = true;
|
||||
}
|
||||
if (!got50 && cumulative >= uint(target50)) {
|
||||
p50 = value;
|
||||
got50 = true;
|
||||
}
|
||||
if (!got90 && cumulative >= uint(target90)) {
|
||||
p90 = value;
|
||||
got90 = true;
|
||||
}
|
||||
if (!got98 && cumulative >= uint(target98)) {
|
||||
p98 = value;
|
||||
got98 = true;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < HIST_BINS; ++i) {
|
||||
float value = inputSamples[i];
|
||||
if (value >= p999Input) {
|
||||
p995Input = p999Input;
|
||||
p999Input = value;
|
||||
} else if (value > p995Input) {
|
||||
p995Input = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (uGlobalCountersOffset >= 0) {
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_SAMPLE_COUNT], sampleCount);
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_ZERO_COUNT], zeroCount);
|
||||
atomicAdd(data[uGlobalCountersOffset + COUNTER_HIGHLIGHT_COUNT], highlightCount);
|
||||
atomicMax(
|
||||
data[uGlobalCountersOffset + COUNTER_MAX_INPUT_BITS],
|
||||
floatBitsToUint(p999Input)
|
||||
);
|
||||
}
|
||||
|
||||
if (uCellSumsOffset >= 0) {
|
||||
float linearSum = 0.0;
|
||||
float logSum = 0.0;
|
||||
for (int i = 0; i < HIST_BINS; ++i) {
|
||||
float value = inputSamples[i];
|
||||
linearSum += value;
|
||||
logSum += log(max(value, 1e-6));
|
||||
}
|
||||
int sumOffset = uCellSumsOffset + cellIndex * CELL_SUM_STRIDE;
|
||||
data[sumOffset] = floatBitsToUint(linearSum);
|
||||
data[sumOffset + 1] = floatBitsToUint(logSum);
|
||||
}
|
||||
|
||||
int offset = cellIndex * STATS_STRIDE;
|
||||
data[offset + 0] = floatBitsToUint(samples > 0 ? p10 : 0.0);
|
||||
data[offset + 1] = floatBitsToUint(samples > 0 ? p50 : 0.0);
|
||||
data[offset + 2] = floatBitsToUint(samples > 0 ? p90 : 0.0);
|
||||
data[offset + 3] = floatBitsToUint(samples > 0 ? p98 : 0.0);
|
||||
data[offset + 4] = floatBitsToUint(
|
||||
samples > 0 ? float(highlightCount) / float(samples) : 0.0
|
||||
);
|
||||
data[offset + 5] = floatBitsToUint(float(samples));
|
||||
data[offset + 6] = floatBitsToUint(samples > 0 ? p995Input : 0.0);
|
||||
data[offset + 7] = floatBitsToUint(samples > 0 ? p999Input : 0.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val DIAGNOSTIC_ALIGNMENT_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.ColorSpace
|
||||
import android.graphics.Rect
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import androidx.core.graphics.createBitmap
|
||||
@@ -242,9 +241,6 @@ object MultiFrameStacker {
|
||||
lensShadingWidth: Int = 0,
|
||||
lensShadingHeight: Int = 0,
|
||||
applyLensShadingCorrection: Boolean = true,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
pgtmStatsBounds: Rect? = null,
|
||||
profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon,
|
||||
): RawStackResult? {
|
||||
if (normalFrames.isEmpty()) {
|
||||
shortFrame.image.close()
|
||||
@@ -283,9 +279,6 @@ object MultiFrameStacker {
|
||||
lensShading = stackLensShading,
|
||||
lensShadingWidth = if (stackLensShading != null) lensShadingWidth else 0,
|
||||
lensShadingHeight = if (stackLensShading != null) lensShadingHeight else 0,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
pgtmStatsBounds = pgtmStatsBounds,
|
||||
profileToneMapMode = profileToneMapMode,
|
||||
tuning = tuning,
|
||||
debugConfig = RawStackRuntimeDebug.debugConfig,
|
||||
).processHdr(
|
||||
|
||||
@@ -1,24 +1,17 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Builds a DNG profile gain table from the same three stages used by Google's LTM pipeline:
|
||||
* Plans a DNG profile gain table from GPU-produced spatial statistics.
|
||||
*
|
||||
* 1. estimate the scene-white range from BaselineExposure and robust spatial tail statistics;
|
||||
* 2. plan the local synthetic-exposure range for every map cell;
|
||||
* 3. render and fuse eight synthetic exposures into the gain curve.
|
||||
*
|
||||
* The generated table contains the complete display transform. In particular, gains below one
|
||||
* near the table's white end are intentional: they compress scene-linear highlight headroom into
|
||||
* the profile output range.
|
||||
* 3. package gain curves generated by [DngHdrProfileGainTableGpuShaders].
|
||||
*/
|
||||
internal object DngHdrProfileGainTableGenerator {
|
||||
private const val TAG = "DngHdrProfileGainTableGenerator"
|
||||
@@ -35,11 +28,8 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
private const val GRID_MAX_H = 64
|
||||
private const val GRID_MAX_V = 48
|
||||
|
||||
// Google logs describe LTM as an eight-synthetic-exposure operation.
|
||||
private const val SYNTHETIC_EXPOSURE_COUNT = 8
|
||||
private const val MAX_SCENE_WHITE = 64f
|
||||
private const val MAX_LTM_GAIN = 6.18f
|
||||
private const val MIN_TABLE_GAIN = 0.05f
|
||||
private const val AUTO_EXPOSURE_TARGET = 0.278f
|
||||
private const val WELL_EXPOSED_KEY = 0.525f
|
||||
private const val WELL_EXPOSED_SIGMA_EV = 0.750f
|
||||
@@ -49,12 +39,9 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
private const val HIGHLIGHT_WELL_EXPOSED_SIGMA_EV = 1.200f
|
||||
private const val HIGHLIGHT_FUSION_START = 0.45f
|
||||
private const val HIGHLIGHT_FUSION_END = 0.65f
|
||||
private const val EXPOSURE_PLAN_STEPS_PER_EV = 128f
|
||||
private const val WEIGHT_LUT_STEPS_PER_EV = 256f
|
||||
private const val WEIGHT_LUT_MAX_DISTANCE_EV = 12f
|
||||
private const val CURVE_EPS = 1e-6f
|
||||
private const val BRIGHTNESS_PLAN_SEARCH_STEPS = 256
|
||||
private const val BRIGHTNESS_PLAN_REFINEMENT_ITERATIONS = 16
|
||||
|
||||
internal const val BASE_INPUT_WEIGHT_RED = 0.1495f
|
||||
internal const val BASE_INPUT_WEIGHT_GREEN = 0.2935f
|
||||
@@ -100,61 +87,24 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
).toFloat()
|
||||
}
|
||||
|
||||
/** Interleaved normal/highlight weights uploaded once for the GPU curve generator. */
|
||||
internal fun interleavedWellExposedWeightLut(): FloatArray {
|
||||
return FloatArray(WELL_EXPOSED_WEIGHT_LUT.size * 2) { index ->
|
||||
val lutIndex = index / 2
|
||||
if ((index and 1) == 0) {
|
||||
WELL_EXPOSED_WEIGHT_LUT[lutIndex]
|
||||
} else {
|
||||
HIGHLIGHT_WELL_EXPOSED_WEIGHT_LUT[lutIndex]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun gridSizeFor(width: Int, height: Int): IntArray {
|
||||
val grid = chooseLtmGrid(width, height)
|
||||
return intArrayOf(grid.mapPointsH, grid.mapPointsV)
|
||||
}
|
||||
|
||||
fun sceneInputFromLinearRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
cameraWhite: FloatArray? = null,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): Float {
|
||||
val profileRgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
return sceneInputFromProfileRgb(
|
||||
red = profileRgb[0],
|
||||
green = profileRgb[1],
|
||||
blue = profileRgb[2],
|
||||
baselineGain = baselineGain
|
||||
)
|
||||
}
|
||||
|
||||
fun sceneInputFromProfileRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
): Float {
|
||||
// dng_render obtains this RGB from BaselineABCtoRGB, which pins RIMM to [0, 1]
|
||||
// before ProfileGainTableMap. BaselineExposure scales only the five-weight lookup input.
|
||||
val profileRgb = DngSdkProfileRgbTransform.clampProfileRgb(red, green, blue)
|
||||
val r = profileRgb[0] * baselineGain
|
||||
val g = profileRgb[1] * baselineGain
|
||||
val b = profileRgb[2] * baselineGain
|
||||
val rgbMin = min(r, min(g, b))
|
||||
val rgbMax = max(r, max(g, b))
|
||||
return max(
|
||||
BASE_INPUT_WEIGHT_RED * r +
|
||||
BASE_INPUT_WEIGHT_GREEN * g +
|
||||
BASE_INPUT_WEIGHT_BLUE * b +
|
||||
BASE_INPUT_WEIGHT_MIN * rgbMin +
|
||||
BASE_INPUT_WEIGHT_MAX * rgbMax,
|
||||
0f
|
||||
)
|
||||
}
|
||||
|
||||
fun forCellStats(
|
||||
internal fun planForCellStats(
|
||||
width: Int,
|
||||
height: Int,
|
||||
baselineExposureEv: Float,
|
||||
@@ -162,9 +112,7 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
tablePointCount: Int = DEFAULT_TABLE_POINTS,
|
||||
diagnosticBand: DiagnosticBand? = null,
|
||||
fusionParameters: HdrExposureFusionParameters = GOOGLE_FUSION_PARAMETERS,
|
||||
brightnessTarget: HdrExposureFusionBrightnessTarget? = null,
|
||||
resolutionDiagnostics: ((HdrExposureFusionResolutionDiagnostics) -> Unit)? = null,
|
||||
): DngProfileGainTableMap? {
|
||||
): HdrProfileGainTablePlan? {
|
||||
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) {
|
||||
return null
|
||||
}
|
||||
@@ -194,32 +142,37 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
inputScale = inputScale,
|
||||
fusionParameters = fusionParameters,
|
||||
)
|
||||
val resolvedFusion = resolveBrightnessTarget(
|
||||
plan = globalPlan,
|
||||
fusionParameters = fusionParameters,
|
||||
brightnessTarget = brightnessTarget,
|
||||
)
|
||||
resolvedFusion.diagnostics?.let { resolutionDiagnostics?.invoke(it) }
|
||||
val cellPlans = DngHdrLtmSpatialModel.buildExposurePlans(
|
||||
cells = cells,
|
||||
grid = grid,
|
||||
global = spatialStats,
|
||||
globalPlan = resolvedFusion.plan,
|
||||
globalPlan = globalPlan,
|
||||
minimumExposureGain = inputScale,
|
||||
maxExposureGain = fusionParameters.maxExposureGain,
|
||||
preserveExposureSpan = resolvedFusion.preserveExposureSpan,
|
||||
preserveExposureSpan = false,
|
||||
)
|
||||
return buildMap(
|
||||
return HdrProfileGainTablePlan(
|
||||
grid = grid,
|
||||
pointCount = tablePointCount.coerceIn(MIN_TABLE_POINTS, MAX_TABLE_POINTS),
|
||||
inputScale = inputScale,
|
||||
cellPlans = cellPlans,
|
||||
diagnosticBand = diagnosticBand?.sanitized(),
|
||||
fusionParameters = resolvedFusion.parameters,
|
||||
protectedExposureGain = resolvedFusion.protectedExposureGain,
|
||||
fusionParameters = fusionParameters,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun mapFromGpuGains(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
gains: FloatArray,
|
||||
): DngProfileGainTableMap? {
|
||||
val expectedGainCount = plan.grid.mapPointsH * plan.grid.mapPointsV * plan.pointCount
|
||||
if (gains.size != expectedGainCount) {
|
||||
PLog.e(TAG, "GPU PGTM gain count=${gains.size}, expected=$expectedGainCount")
|
||||
return null
|
||||
}
|
||||
return createMap(plan, gains)
|
||||
}
|
||||
|
||||
data class DiagnosticBand(
|
||||
val start: Float,
|
||||
val end: Float,
|
||||
@@ -245,31 +198,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
BLOCK_ONLY,
|
||||
}
|
||||
|
||||
fun withDiagnosticBand(
|
||||
map: DngProfileGainTableMap,
|
||||
diagnosticBand: DiagnosticBand?,
|
||||
): DngProfileGainTableMap {
|
||||
val band = diagnosticBand?.sanitized() ?: return map
|
||||
if (!map.isValid) return map
|
||||
val gains = map.gains.copyOf()
|
||||
val pointCount = map.mapPointsN
|
||||
val cellCount = map.mapPointsH * map.mapPointsV
|
||||
val maxGain = gains.maxOrNull()
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
?.coerceAtLeast(MAX_LTM_GAIN)
|
||||
?: MAX_LTM_GAIN
|
||||
for (cell in 0 until cellCount) {
|
||||
applyDiagnosticBand(
|
||||
output = gains,
|
||||
outputOffset = cell * pointCount,
|
||||
pointCount = pointCount,
|
||||
band = band,
|
||||
maxGainValue = maxGain
|
||||
)
|
||||
}
|
||||
return map.copy(gains = gains)
|
||||
}
|
||||
|
||||
private fun packedStatsAt(
|
||||
stats: FloatArray,
|
||||
offset: Int,
|
||||
@@ -460,388 +388,25 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Solves the center of the synthetic exposure stack while preserving the span planned by the
|
||||
* current PGTM model. The well-exposed key, exposure spacing, and stack width therefore keep
|
||||
* defining one stable curve shape; scene brightness only translates that stack in EV.
|
||||
*/
|
||||
private fun resolveBrightnessTarget(
|
||||
plan: HdrLtmExposurePlan,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
brightnessTarget: HdrExposureFusionBrightnessTarget?,
|
||||
): ResolvedExposureFusion {
|
||||
val fallback = ResolvedExposureFusion(
|
||||
plan = plan,
|
||||
parameters = fusionParameters,
|
||||
preserveExposureSpan = false,
|
||||
protectedExposureGain = null,
|
||||
diagnostics = null,
|
||||
)
|
||||
val target = brightnessTarget ?: return fallback
|
||||
if (!target.sceneInput.isFinite() || target.sceneInput <= 0f ||
|
||||
!target.targetOutput.isFinite() || target.targetOutput <= 0f
|
||||
) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
val desiredOutput = target.targetOutput.coerceIn(0f, 1f)
|
||||
val darkestGain = plan.darkestExposureGain.coerceIn(
|
||||
MIN_TABLE_GAIN,
|
||||
fusionParameters.maxExposureGain,
|
||||
)
|
||||
val baseDarkestEv = log2(darkestGain)
|
||||
val baseBrightestEv = log2(
|
||||
plan.brightestExposureGain.coerceIn(darkestGain, fusionParameters.maxExposureGain)
|
||||
)
|
||||
val minimumExposureEv = baseDarkestEv
|
||||
val maximumExposureEv = log2(fusionParameters.maxExposureGain)
|
||||
val fullExposureSpanEv = (baseBrightestEv - baseDarkestEv).coerceIn(
|
||||
0f,
|
||||
maximumExposureEv - minimumExposureEv,
|
||||
)
|
||||
// Keep one exposure fixed at inputScale for highlight reconstruction. The other seven
|
||||
// retain exactly the span occupied by the brightest seven members of the original
|
||||
// equally-spaced eight-exposure stack.
|
||||
val exposureIntervalEv = fullExposureSpanEv / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
|
||||
val centeredExposureSpanEv = fullExposureSpanEv - exposureIntervalEv
|
||||
val halfSpanEv = centeredExposureSpanEv * 0.5f
|
||||
val minimumCenterEv = minimumExposureEv + halfSpanEv
|
||||
val maximumCenterEv = maximumExposureEv - halfSpanEv
|
||||
val referenceCenterEv = (
|
||||
baseDarkestEv + exposureIntervalEv + halfSpanEv
|
||||
).coerceIn(minimumCenterEv, maximumCenterEv)
|
||||
val protectedExposureGain = darkestGain
|
||||
|
||||
fun fusionOutput(centerEv: Float): Float {
|
||||
val resolvedCenterEv = centerEv.coerceIn(minimumCenterEv, maximumCenterEv)
|
||||
val resolvedDarkestEv = resolvedCenterEv - halfSpanEv
|
||||
val resolvedBrightestEv = resolvedCenterEv + halfSpanEv
|
||||
val resolvedDarkestGain = 2.0f.pow(resolvedDarkestEv)
|
||||
val resolvedBrightestGain = 2.0f.pow(resolvedBrightestEv)
|
||||
val exposureGains = syntheticExposureGains(
|
||||
resolvedBrightestGain,
|
||||
resolvedDarkestGain,
|
||||
protectedExposureGain = protectedExposureGain,
|
||||
)
|
||||
val exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
|
||||
log2(exposureGains[exposure])
|
||||
}
|
||||
return fuseSyntheticExposures(
|
||||
sceneInput = target.sceneInput,
|
||||
exposureGains = exposureGains,
|
||||
exposureGainEvs = exposureGainEvs,
|
||||
fusionParameters = fusionParameters,
|
||||
)
|
||||
}
|
||||
|
||||
fun evaluate(centerEv: Float): ExposureCenterEvaluation {
|
||||
val output = fusionOutput(centerEv)
|
||||
return ExposureCenterEvaluation(
|
||||
centerEv = centerEv.coerceIn(minimumCenterEv, maximumCenterEv),
|
||||
brightnessErrorEv = abs(
|
||||
log2(max(output, CURVE_EPS) / max(desiredOutput, CURVE_EPS))
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
var bestStep = 0
|
||||
var bestEvaluation = evaluate(minimumCenterEv)
|
||||
for (step in 0..BRIGHTNESS_PLAN_SEARCH_STEPS) {
|
||||
val amount = step.toFloat() / BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat()
|
||||
val candidateEv = lerp(minimumCenterEv, maximumCenterEv, amount)
|
||||
val candidateEvaluation = evaluate(candidateEv)
|
||||
if (candidateEvaluation.brightnessErrorEv < bestEvaluation.brightnessErrorEv) {
|
||||
bestEvaluation = candidateEvaluation
|
||||
bestStep = step
|
||||
}
|
||||
}
|
||||
var lowerEv = lerp(
|
||||
minimumCenterEv,
|
||||
maximumCenterEv,
|
||||
(bestStep - 1).coerceAtLeast(0).toFloat() / BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat(),
|
||||
)
|
||||
var upperEv = lerp(
|
||||
minimumCenterEv,
|
||||
maximumCenterEv,
|
||||
(bestStep + 1).coerceAtMost(BRIGHTNESS_PLAN_SEARCH_STEPS).toFloat() /
|
||||
BRIGHTNESS_PLAN_SEARCH_STEPS.toFloat(),
|
||||
)
|
||||
repeat(BRIGHTNESS_PLAN_REFINEMENT_ITERATIONS) {
|
||||
val firstEv = lerp(lowerEv, upperEv, 1f / 3f)
|
||||
val secondEv = lerp(lowerEv, upperEv, 2f / 3f)
|
||||
val firstEvaluation = evaluate(firstEv)
|
||||
val secondEvaluation = evaluate(secondEv)
|
||||
if (firstEvaluation.brightnessErrorEv < secondEvaluation.brightnessErrorEv) {
|
||||
upperEv = secondEv
|
||||
} else {
|
||||
lowerEv = firstEv
|
||||
}
|
||||
}
|
||||
val resolvedEvaluation = listOf(
|
||||
evaluate(lowerEv),
|
||||
evaluate((lowerEv + upperEv) * 0.5f),
|
||||
evaluate(upperEv),
|
||||
).reduce { best, candidate ->
|
||||
if (candidate.brightnessErrorEv < best.brightnessErrorEv) candidate else best
|
||||
}
|
||||
val resolvedCenterEv = resolvedEvaluation.centerEv
|
||||
return ResolvedExposureFusion(
|
||||
plan = HdrLtmExposurePlan(
|
||||
brightestExposureGain = 2.0f.pow(resolvedCenterEv + halfSpanEv),
|
||||
darkestExposureGain = 2.0f.pow(resolvedCenterEv - halfSpanEv),
|
||||
),
|
||||
parameters = fusionParameters,
|
||||
preserveExposureSpan = true,
|
||||
protectedExposureGain = protectedExposureGain,
|
||||
diagnostics = HdrExposureFusionResolutionDiagnostics(
|
||||
referenceCenterEv = referenceCenterEv,
|
||||
resolvedCenterEv = resolvedCenterEv,
|
||||
centeredExposureSpanEv = centeredExposureSpanEv,
|
||||
brightnessErrorEv = resolvedEvaluation.brightnessErrorEv,
|
||||
protectedExposureGain = protectedExposureGain,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildMap(
|
||||
grid: HdrPgtmGrid,
|
||||
pointCount: Int,
|
||||
inputScale: Float,
|
||||
cellPlans: Array<HdrLtmExposurePlan>,
|
||||
diagnosticBand: DiagnosticBand?,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
protectedExposureGain: Float?,
|
||||
private fun createMap(
|
||||
plan: HdrProfileGainTablePlan,
|
||||
gains: FloatArray,
|
||||
): DngProfileGainTableMap {
|
||||
val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * pointCount)
|
||||
// Local exposure plans vary smoothly. Quantizing both stack endpoints to 1/128 EV limits
|
||||
// the maximum planning error to 1/256 EV while allowing neighboring cells to share the
|
||||
// complete 257-point fused curve.
|
||||
val curveCache = HashMap<Long, FloatArray>()
|
||||
for (cell in cellPlans.indices) {
|
||||
val plan = cellPlans[cell]
|
||||
val brightestKey = (log2(plan.brightestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV)
|
||||
.roundToInt()
|
||||
val darkestKey = (log2(plan.darkestExposureGain) * EXPOSURE_PLAN_STEPS_PER_EV)
|
||||
.roundToInt()
|
||||
val planKey = (brightestKey.toLong() shl 32) xor
|
||||
(darkestKey.toLong() and 0xffffffffL)
|
||||
val curve = curveCache.getOrPut(planKey) {
|
||||
val quantizedBrightestGain = 2.0f.pow(
|
||||
brightestKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV
|
||||
).coerceIn(inputScale, fusionParameters.maxExposureGain)
|
||||
val quantizedDarkestGain = 2.0f.pow(
|
||||
darkestKey.toFloat() / EXPOSURE_PLAN_STEPS_PER_EV
|
||||
).coerceIn(inputScale, quantizedBrightestGain)
|
||||
FloatArray(pointCount).also { cachedCurve ->
|
||||
writeExposureFusionCurve(
|
||||
output = cachedCurve,
|
||||
outputOffset = 0,
|
||||
pointCount = pointCount,
|
||||
inputScale = inputScale,
|
||||
plan = HdrLtmExposurePlan(
|
||||
brightestExposureGain = quantizedBrightestGain,
|
||||
darkestExposureGain = quantizedDarkestGain,
|
||||
),
|
||||
fusionParameters = fusionParameters,
|
||||
protectedExposureGain = protectedExposureGain,
|
||||
)
|
||||
}
|
||||
}
|
||||
curve.copyInto(
|
||||
destination = gains,
|
||||
destinationOffset = cell * pointCount
|
||||
)
|
||||
diagnosticBand?.let { band ->
|
||||
applyDiagnosticBand(
|
||||
output = gains,
|
||||
outputOffset = cell * pointCount,
|
||||
pointCount = pointCount,
|
||||
band = band,
|
||||
maxGainValue = fusionParameters.maxExposureGain,
|
||||
)
|
||||
}
|
||||
}
|
||||
return DngProfileGainTableMap(
|
||||
mapPointsV = grid.mapPointsV,
|
||||
mapPointsH = grid.mapPointsH,
|
||||
mapSpacingV = grid.mapSpacingV,
|
||||
mapSpacingH = grid.mapSpacingH,
|
||||
mapPointsV = plan.grid.mapPointsV,
|
||||
mapPointsH = plan.grid.mapPointsH,
|
||||
mapSpacingV = plan.grid.mapSpacingV,
|
||||
mapSpacingH = plan.grid.mapSpacingH,
|
||||
mapOriginV = 0.0,
|
||||
mapOriginH = 0.0,
|
||||
mapPointsN = pointCount,
|
||||
mapInputWeights = ltmInputWeights(inputScale),
|
||||
mapPointsN = plan.pointCount,
|
||||
mapInputWeights = ltmInputWeights(plan.inputScale),
|
||||
gamma = 1f,
|
||||
gains = gains,
|
||||
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders eight exposure levels. The standard path spaces all eight equally in EV; an
|
||||
* adaptive centered stack spaces seven equally and reserves one inputScale exposure for
|
||||
* highlight reconstruction. Weights are computed from each rendered exposure's distance to
|
||||
* the well-exposed key. Monotonic enforcement only removes numerical or switching reversals.
|
||||
*/
|
||||
private fun writeExposureFusionCurve(
|
||||
output: FloatArray,
|
||||
outputOffset: Int,
|
||||
pointCount: Int,
|
||||
inputScale: Float,
|
||||
plan: HdrLtmExposurePlan,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
protectedExposureGain: Float?,
|
||||
) {
|
||||
val brightestGain = plan.brightestExposureGain.coerceIn(
|
||||
MIN_TABLE_GAIN,
|
||||
fusionParameters.maxExposureGain,
|
||||
)
|
||||
val darkestGain = plan.darkestExposureGain.coerceIn(MIN_TABLE_GAIN, brightestGain)
|
||||
val exposureGains = syntheticExposureGains(
|
||||
brightestGain,
|
||||
darkestGain,
|
||||
protectedExposureGain,
|
||||
)
|
||||
val exposureGainEvs = FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
|
||||
log2(exposureGains[exposure])
|
||||
}
|
||||
var previousOutput = 0f
|
||||
for (index in 0 until pointCount) {
|
||||
val tableInput = tableInputForIndex(index, pointCount)
|
||||
if (tableInput <= CURVE_EPS) {
|
||||
output[outputOffset + index] = brightestGain
|
||||
continue
|
||||
}
|
||||
val sceneInput = tableInput / inputScale
|
||||
val fusedOutput = fuseSyntheticExposures(
|
||||
sceneInput = sceneInput,
|
||||
exposureGains = exposureGains,
|
||||
exposureGainEvs = exposureGainEvs,
|
||||
fusionParameters = fusionParameters,
|
||||
)
|
||||
val monotonicOutput = max(previousOutput, fusedOutput)
|
||||
output[outputOffset + index] = (monotonicOutput / sceneInput)
|
||||
.coerceIn(MIN_TABLE_GAIN, fusionParameters.maxExposureGain)
|
||||
previousOutput = monotonicOutput
|
||||
}
|
||||
}
|
||||
|
||||
private fun syntheticExposureGains(
|
||||
brightestGain: Float,
|
||||
darkestGain: Float,
|
||||
protectedExposureGain: Float? = null,
|
||||
): FloatArray {
|
||||
val protectedGain = protectedExposureGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
?.coerceAtMost(darkestGain)
|
||||
?: return FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
|
||||
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 1).toFloat()
|
||||
2.0f.pow(lerp(log2(brightestGain), log2(darkestGain), amount))
|
||||
}
|
||||
return FloatArray(SYNTHETIC_EXPOSURE_COUNT) { exposure ->
|
||||
if (exposure == SYNTHETIC_EXPOSURE_COUNT - 1) {
|
||||
protectedGain
|
||||
} else {
|
||||
val amount = exposure.toFloat() / (SYNTHETIC_EXPOSURE_COUNT - 2).toFloat()
|
||||
2.0f.pow(lerp(log2(brightestGain), log2(darkestGain), amount))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun fuseSyntheticExposures(
|
||||
sceneInput: Float,
|
||||
exposureGains: FloatArray,
|
||||
exposureGainEvs: FloatArray,
|
||||
fusionParameters: HdrExposureFusionParameters,
|
||||
): Float {
|
||||
val sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / fusionParameters.wellExposedKey)
|
||||
val darkestExposureGain = exposureGains.lastOrNull() ?: return 0f
|
||||
val tableInput = sceneInput * darkestExposureGain
|
||||
val highlightFusionStrength = smoothStep(
|
||||
fusionParameters.highlightFusionStart,
|
||||
fusionParameters.highlightFusionEnd,
|
||||
tableInput
|
||||
)
|
||||
var weightSum = 0f
|
||||
var outputSum = 0f
|
||||
var nearestDistanceEv = Float.POSITIVE_INFINITY
|
||||
var nearestOutput = 0f
|
||||
for (exposure in exposureGains.indices) {
|
||||
val exposureGain = exposureGains[exposure]
|
||||
val exposed = max(sceneInput * exposureGain, CURVE_EPS)
|
||||
val distanceEv = sceneFromKeyEv + exposureGainEvs[exposure]
|
||||
val weight = lerp(
|
||||
wellExposedWeight(distanceEv, WELL_EXPOSED_WEIGHT_LUT),
|
||||
wellExposedWeight(distanceEv, HIGHLIGHT_WELL_EXPOSED_WEIGHT_LUT),
|
||||
highlightFusionStrength
|
||||
)
|
||||
weightSum += weight
|
||||
outputSum += weight * min(exposed, 1f)
|
||||
if (abs(distanceEv) < nearestDistanceEv) {
|
||||
nearestDistanceEv = abs(distanceEv)
|
||||
nearestOutput = min(exposed, 1f)
|
||||
}
|
||||
}
|
||||
if (weightSum <= 0f) return nearestOutput
|
||||
return (outputSum / weightSum).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun wellExposedWeight(distanceEv: Float, lut: FloatArray): Float {
|
||||
// Linear interpolation at 1/256 EV removes millions of exp() calls without changing the
|
||||
// exposure-fusion equation or its normalization.
|
||||
val scaled = abs(distanceEv) * WEIGHT_LUT_STEPS_PER_EV
|
||||
if (scaled >= lut.lastIndex.toFloat()) return 0f
|
||||
val index = scaled.toInt()
|
||||
val fraction = scaled - index
|
||||
return lerp(
|
||||
lut[index],
|
||||
lut[index + 1],
|
||||
fraction
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyDiagnosticBand(
|
||||
output: FloatArray,
|
||||
outputOffset: Int,
|
||||
pointCount: Int,
|
||||
band: DiagnosticBand,
|
||||
maxGainValue: Float = MAX_LTM_GAIN,
|
||||
) {
|
||||
var previousOutput = 0f
|
||||
val safeMaxGain = maxGainValue.takeIf { it.isFinite() && it > 0f }
|
||||
?.coerceAtLeast(1f)
|
||||
?: MAX_LTM_GAIN
|
||||
for (index in 0 until pointCount) {
|
||||
val input = tableInputForIndex(index, pointCount)
|
||||
val trueGain = output[outputOffset + index]
|
||||
val mask = diagnosticBandMask(input, band)
|
||||
val mixedGain = when (band.mode) {
|
||||
DiagnosticMode.PASS_ONLY -> lerp(1f, trueGain, mask)
|
||||
DiagnosticMode.BLOCK_ONLY -> lerp(trueGain, 1f, mask)
|
||||
}
|
||||
val monotonicOutput = max(previousOutput, input * mixedGain)
|
||||
output[outputOffset + index] = if (input <= CURVE_EPS) {
|
||||
mixedGain.coerceIn(MIN_TABLE_GAIN, safeMaxGain)
|
||||
} else {
|
||||
(monotonicOutput / input).coerceIn(MIN_TABLE_GAIN, safeMaxGain)
|
||||
}
|
||||
previousOutput = monotonicOutput
|
||||
}
|
||||
}
|
||||
|
||||
private fun diagnosticBandMask(input: Float, band: DiagnosticBand): Float {
|
||||
val enter = if (band.start <= 0f || band.feather <= 0f) {
|
||||
if (input >= band.start) 1f else 0f
|
||||
} else {
|
||||
smoothStep(band.start - band.feather, band.start + band.feather, input)
|
||||
}
|
||||
val exit = if (band.end >= 1f || band.feather <= 0f) {
|
||||
if (input <= band.end) 1f else 0f
|
||||
} else {
|
||||
1f - smoothStep(band.end - band.feather, band.end + band.feather, input)
|
||||
}
|
||||
return min(enter, exit).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun chooseLtmGrid(width: Int, height: Int): HdrPgtmGrid {
|
||||
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
|
||||
.coerceIn(GRID_MIN_H, GRID_MAX_H)
|
||||
@@ -866,20 +431,11 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
?: 1f / MAX_SCENE_WHITE
|
||||
}
|
||||
|
||||
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
|
||||
if (pointCount <= 1) return 0f
|
||||
return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat()
|
||||
}
|
||||
|
||||
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val t = ((value - edge0) / max(edge1 - edge0, CURVE_EPS)).coerceIn(0f, 1f)
|
||||
return t * t * (3f - 2f * t)
|
||||
}
|
||||
|
||||
private fun lerp(first: Float, second: Float, amount: Float): Float {
|
||||
return first + (second - first) * amount.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun log2(value: Float): Float {
|
||||
return (ln(max(value, CURVE_EPS).toDouble()) / ln(2.0)).toFloat()
|
||||
}
|
||||
@@ -896,32 +452,15 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
return values.firstOrNull { it.isFinite() && it > 0f } ?: 1f
|
||||
}
|
||||
|
||||
private data class ResolvedExposureFusion(
|
||||
val plan: HdrLtmExposurePlan,
|
||||
val parameters: HdrExposureFusionParameters,
|
||||
val preserveExposureSpan: Boolean,
|
||||
val protectedExposureGain: Float?,
|
||||
val diagnostics: HdrExposureFusionResolutionDiagnostics?,
|
||||
)
|
||||
|
||||
private data class ExposureCenterEvaluation(
|
||||
val centerEv: Float,
|
||||
val brightnessErrorEv: Float,
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
internal data class HdrExposureFusionBrightnessTarget(
|
||||
val sceneInput: Float,
|
||||
val targetOutput: Float,
|
||||
)
|
||||
|
||||
internal data class HdrExposureFusionResolutionDiagnostics(
|
||||
val referenceCenterEv: Float,
|
||||
val resolvedCenterEv: Float,
|
||||
val centeredExposureSpanEv: Float,
|
||||
val brightnessErrorEv: Float,
|
||||
val protectedExposureGain: Float,
|
||||
internal data class HdrProfileGainTablePlan(
|
||||
val grid: HdrPgtmGrid,
|
||||
val pointCount: Int,
|
||||
val inputScale: Float,
|
||||
val cellPlans: Array<HdrLtmExposurePlan>,
|
||||
val diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand?,
|
||||
val fusionParameters: HdrExposureFusionParameters,
|
||||
)
|
||||
|
||||
internal data class HdrExposureFusionParameters(
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** Compute shaders for capture-time DNG ProfileGainTableMap preparation. */
|
||||
internal object DngHdrProfileGainTableGpuShaders {
|
||||
val CELL_STATS = """
|
||||
#version 310 es
|
||||
|
||||
layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
|
||||
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
precision highp sampler3D;
|
||||
|
||||
uniform highp usampler2D uRawTexture;
|
||||
uniform sampler3D uHueSatMap;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
uniform ivec2 uGridSize;
|
||||
uniform int uSamplesPerPixel;
|
||||
uniform int uCfaPattern;
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
uniform float uBaselineGain;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform int uHueSatEnabled;
|
||||
uniform ivec3 uHueSatDivisions;
|
||||
uniform int uHueSatEncoding;
|
||||
|
||||
layout(std430, binding = 0) writeonly buffer CellStatsBuffer {
|
||||
float cellStats[];
|
||||
};
|
||||
|
||||
shared float inputSamples[256];
|
||||
|
||||
${DcpHueSatMapGl.SHADER_FUNCTIONS}
|
||||
|
||||
int expandedBlockSize(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return 4;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int baseBayerPattern(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return cfaPattern - 8;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return cfaPattern - 4;
|
||||
return clamp(cfaPattern, 0, 3);
|
||||
}
|
||||
|
||||
int bayerChannelIndex(int cfaPattern, int xParity, int yParity) {
|
||||
if (cfaPattern == 1) {
|
||||
if (yParity == 0 && xParity == 0) return 1;
|
||||
if (yParity == 0 && xParity == 1) return 0;
|
||||
if (yParity == 1 && xParity == 0) return 3;
|
||||
return 2;
|
||||
}
|
||||
if (cfaPattern == 2) {
|
||||
if (yParity == 0 && xParity == 0) return 2;
|
||||
if (yParity == 0 && xParity == 1) return 3;
|
||||
if (yParity == 1 && xParity == 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
if (cfaPattern == 3) {
|
||||
if (yParity == 0 && xParity == 0) return 3;
|
||||
if (yParity == 0 && xParity == 1) return 2;
|
||||
if (yParity == 1 && xParity == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
if (yParity == 0 && xParity == 0) return 0;
|
||||
if (yParity == 0 && xParity == 1) return 1;
|
||||
if (yParity == 1 && xParity == 0) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
int channelIndexForPixel(ivec2 coord) {
|
||||
int blockSize = expandedBlockSize(uCfaPattern);
|
||||
return bayerChannelIndex(
|
||||
baseBayerPattern(uCfaPattern),
|
||||
(coord.x / blockSize) & 1,
|
||||
(coord.y / blockSize) & 1
|
||||
);
|
||||
}
|
||||
|
||||
float normalizeRaw(uint raw, int channelIndex) {
|
||||
float black = uBlackLevel[clamp(channelIndex, 0, 3)];
|
||||
float range = max(uWhiteLevel - black, 1.0);
|
||||
return clamp((float(raw) - black) / range, 0.0, 1.0);
|
||||
}
|
||||
|
||||
float profileSceneInput(vec3 cameraRgb) {
|
||||
vec3 boundedCameraRgb = min(cameraRgb, uCameraWhite);
|
||||
vec3 profileRgb = clamp(uColorCorrectionMatrix * boundedCameraRgb, 0.0, 1.0);
|
||||
if (uHueSatEnabled != 0) {
|
||||
profileRgb = dngApplyHueSatMap(
|
||||
profileRgb,
|
||||
uHueSatMap,
|
||||
uHueSatDivisions,
|
||||
uHueSatEncoding,
|
||||
false
|
||||
);
|
||||
}
|
||||
profileRgb = clamp(profileRgb, 0.0, 1.0) * uBaselineGain;
|
||||
float rgbMin = min(profileRgb.r, min(profileRgb.g, profileRgb.b));
|
||||
float rgbMax = max(profileRgb.r, max(profileRgb.g, profileRgb.b));
|
||||
return max(
|
||||
0.1495 * profileRgb.r +
|
||||
0.2935 * profileRgb.g +
|
||||
0.0570 * profileRgb.b +
|
||||
0.1250 * rgbMin +
|
||||
0.3750 * rgbMax,
|
||||
0.0
|
||||
);
|
||||
}
|
||||
|
||||
float sampleSceneInput(ivec2 baseCoord) {
|
||||
if (uSamplesPerPixel >= 3) {
|
||||
ivec2 coord = clamp(baseCoord, ivec2(0), uImageSize - ivec2(1));
|
||||
uvec3 rawRgb = texelFetch(uRawTexture, coord, 0).rgb;
|
||||
return profileSceneInput(vec3(
|
||||
normalizeRaw(rawRgb.r, 0),
|
||||
normalizeRaw(rawRgb.g, 1),
|
||||
normalizeRaw(rawRgb.b, 2)
|
||||
));
|
||||
}
|
||||
|
||||
vec3 sums = vec3(0.0);
|
||||
vec3 counts = vec3(0.0);
|
||||
for (int dy = 0; dy < 2; ++dy) {
|
||||
for (int dx = 0; dx < 2; ++dx) {
|
||||
ivec2 coord = clamp(baseCoord + ivec2(dx, dy), ivec2(0), uImageSize - ivec2(1));
|
||||
int channel = channelIndexForPixel(coord);
|
||||
float value = normalizeRaw(texelFetch(uRawTexture, coord, 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 profileSceneInput(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
|
||||
));
|
||||
}
|
||||
|
||||
void sortSamples(uint localIndex) {
|
||||
for (uint sequenceSize = 2u; sequenceSize <= 256u; sequenceSize <<= 1u) {
|
||||
for (uint compareDistance = sequenceSize >> 1u;
|
||||
compareDistance > 0u;
|
||||
compareDistance >>= 1u
|
||||
) {
|
||||
uint partner = localIndex ^ compareDistance;
|
||||
if (partner > localIndex) {
|
||||
float first = inputSamples[localIndex];
|
||||
float second = inputSamples[partner];
|
||||
bool ascending = (localIndex & sequenceSize) == 0u;
|
||||
if ((first > second) == ascending) {
|
||||
inputSamples[localIndex] = second;
|
||||
inputSamples[partner] = first;
|
||||
}
|
||||
}
|
||||
barrier();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 cell = ivec2(gl_WorkGroupID.xy);
|
||||
uint localIndex = gl_LocalInvocationIndex;
|
||||
int cellIndex = cell.y * uGridSize.x + cell.x;
|
||||
int statsOffset = cellIndex * 8;
|
||||
int statsWidth = uStatsBounds.z - uStatsBounds.x;
|
||||
int statsHeight = uStatsBounds.w - uStatsBounds.y;
|
||||
|
||||
int startX = uStatsBounds.x + (cell.x * statsWidth) / uGridSize.x;
|
||||
int endX = uStatsBounds.x +
|
||||
(((cell.x + 1) * statsWidth + uGridSize.x - 1) / uGridSize.x);
|
||||
int startY = uStatsBounds.y + (cell.y * statsHeight) / uGridSize.y;
|
||||
int endY = uStatsBounds.y +
|
||||
(((cell.y + 1) * statsHeight + uGridSize.y - 1) / uGridSize.y);
|
||||
startX = (startX + 1) & ~1;
|
||||
startY = (startY + 1) & ~1;
|
||||
endX = min(endX & ~1, uStatsBounds.z);
|
||||
endY = min(endY & ~1, uStatsBounds.w);
|
||||
bool validCell = endX - startX >= 2 && endY - startY >= 2;
|
||||
|
||||
float inputValue = 0.0;
|
||||
if (validCell) {
|
||||
int localX = int(localIndex & 15u);
|
||||
int localY = int(localIndex >> 4u);
|
||||
int cellWidth = max(endX - startX, 2);
|
||||
int cellHeight = max(endY - startY, 2);
|
||||
int x = startX + ((localX * 2 + 1) * cellWidth) / 32;
|
||||
int y = startY + ((localY * 2 + 1) * cellHeight) / 32;
|
||||
x = clamp(x & ~1, startX, max(startX, endX - 2));
|
||||
y = clamp(y & ~1, startY, max(startY, endY - 2));
|
||||
inputValue = sampleSceneInput(ivec2(x, y));
|
||||
}
|
||||
inputSamples[localIndex] = inputValue;
|
||||
barrier();
|
||||
|
||||
sortSamples(localIndex);
|
||||
if (localIndex == 0u) {
|
||||
if (!validCell) {
|
||||
for (int component = 0; component < 8; ++component) {
|
||||
cellStats[statsOffset + component] = 0.0;
|
||||
}
|
||||
return;
|
||||
}
|
||||
int highlightCount = 0;
|
||||
for (int sampleIndex = 0; sampleIndex < 256; ++sampleIndex) {
|
||||
if (inputSamples[sampleIndex] >= 0.92) ++highlightCount;
|
||||
}
|
||||
cellStats[statsOffset] = inputSamples[25];
|
||||
cellStats[statsOffset + 1] = inputSamples[127];
|
||||
cellStats[statsOffset + 2] = inputSamples[230];
|
||||
cellStats[statsOffset + 3] = inputSamples[250];
|
||||
cellStats[statsOffset + 4] = float(highlightCount) / 256.0;
|
||||
cellStats[statsOffset + 5] = 256.0;
|
||||
cellStats[statsOffset + 6] = inputSamples[254];
|
||||
cellStats[statsOffset + 7] = inputSamples[255];
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val GAIN_CURVES = """
|
||||
#version 310 es
|
||||
|
||||
layout(local_size_x = 64, local_size_y = 1, local_size_z = 1) in;
|
||||
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer ExposurePlanBuffer {
|
||||
float exposurePlans[];
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer GainCurveBuffer {
|
||||
float gainCurves[];
|
||||
};
|
||||
layout(std430, binding = 2) readonly buffer WeightLutBuffer {
|
||||
float weightLut[];
|
||||
};
|
||||
|
||||
uniform int uCellCount;
|
||||
uniform int uPointCount;
|
||||
uniform float uInputScale;
|
||||
uniform float uWellExposedKey;
|
||||
uniform float uMaxExposureGain;
|
||||
uniform float uHighlightFusionStart;
|
||||
uniform float uHighlightFusionEnd;
|
||||
uniform int uDiagnosticMode;
|
||||
uniform float uDiagnosticStart;
|
||||
uniform float uDiagnosticEnd;
|
||||
uniform float uDiagnosticFeather;
|
||||
|
||||
const float MIN_TABLE_GAIN = 0.05;
|
||||
const float CURVE_EPS = 1e-6;
|
||||
const float EXPOSURE_STEPS_PER_EV = 128.0;
|
||||
const float WEIGHT_STEPS_PER_EV = 256.0;
|
||||
const float WEIGHT_MAX_DISTANCE_EV = 12.0;
|
||||
|
||||
float smoothUnit(float edge0, float edge1, float value) {
|
||||
float amount = clamp((value - edge0) / max(edge1 - edge0, CURVE_EPS), 0.0, 1.0);
|
||||
return amount * amount * (3.0 - 2.0 * amount);
|
||||
}
|
||||
|
||||
float quantizedExposureGain(float gain) {
|
||||
float key = floor(log2(max(gain, CURVE_EPS)) * EXPOSURE_STEPS_PER_EV + 0.5);
|
||||
return exp2(key / EXPOSURE_STEPS_PER_EV);
|
||||
}
|
||||
|
||||
float sampledWeight(float distanceEv, int component) {
|
||||
float scaled = abs(distanceEv) * WEIGHT_STEPS_PER_EV;
|
||||
if (scaled >= WEIGHT_MAX_DISTANCE_EV * WEIGHT_STEPS_PER_EV) return 0.0;
|
||||
int index = int(floor(scaled));
|
||||
float fraction = scaled - float(index);
|
||||
float first = weightLut[index * 2 + component];
|
||||
float second = weightLut[(index + 1) * 2 + component];
|
||||
return mix(first, second, fraction);
|
||||
}
|
||||
|
||||
float diagnosticMask(float inputValue) {
|
||||
float enter = uDiagnosticStart <= 0.0 || uDiagnosticFeather <= 0.0
|
||||
? (inputValue >= uDiagnosticStart ? 1.0 : 0.0)
|
||||
: smoothUnit(
|
||||
uDiagnosticStart - uDiagnosticFeather,
|
||||
uDiagnosticStart + uDiagnosticFeather,
|
||||
inputValue
|
||||
);
|
||||
float exit = uDiagnosticEnd >= 1.0 || uDiagnosticFeather <= 0.0
|
||||
? (inputValue <= uDiagnosticEnd ? 1.0 : 0.0)
|
||||
: 1.0 - smoothUnit(
|
||||
uDiagnosticEnd - uDiagnosticFeather,
|
||||
uDiagnosticEnd + uDiagnosticFeather,
|
||||
inputValue
|
||||
);
|
||||
return clamp(min(enter, exit), 0.0, 1.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
int cellIndex = int(gl_GlobalInvocationID.x);
|
||||
if (cellIndex >= uCellCount) return;
|
||||
|
||||
// Some GLES drivers preserve the SSBO member's readonly qualifier when it is used
|
||||
// directly as a function argument. Copy to ordinary locals before quantization.
|
||||
float brightestPlanGain = exposurePlans[cellIndex * 2];
|
||||
float darkestPlanGain = exposurePlans[cellIndex * 2 + 1];
|
||||
float brightestGain = clamp(
|
||||
quantizedExposureGain(brightestPlanGain),
|
||||
uInputScale,
|
||||
uMaxExposureGain
|
||||
);
|
||||
float darkestGain = clamp(
|
||||
quantizedExposureGain(darkestPlanGain),
|
||||
uInputScale,
|
||||
brightestGain
|
||||
);
|
||||
float exposureGains[8];
|
||||
float exposureGainEvs[8];
|
||||
for (int exposure = 0; exposure < 8; ++exposure) {
|
||||
float amount = float(exposure) / 7.0;
|
||||
exposureGains[exposure] = exp2(mix(
|
||||
log2(brightestGain),
|
||||
log2(darkestGain),
|
||||
amount
|
||||
));
|
||||
exposureGainEvs[exposure] = log2(exposureGains[exposure]);
|
||||
}
|
||||
|
||||
float previousTrueOutput = 0.0;
|
||||
float previousFinalOutput = 0.0;
|
||||
int outputOffset = cellIndex * uPointCount;
|
||||
for (int point = 0; point < uPointCount; ++point) {
|
||||
float tableInput = point == uPointCount - 1
|
||||
? 1.0
|
||||
: float(point) / float(uPointCount);
|
||||
float trueGain;
|
||||
if (tableInput <= CURVE_EPS) {
|
||||
trueGain = brightestGain;
|
||||
} else {
|
||||
float sceneInput = tableInput / uInputScale;
|
||||
float sceneFromKeyEv = log2(max(sceneInput, CURVE_EPS) / uWellExposedKey);
|
||||
float highlightStrength = smoothUnit(
|
||||
uHighlightFusionStart,
|
||||
uHighlightFusionEnd,
|
||||
sceneInput * exposureGains[7]
|
||||
);
|
||||
float weightSum = 0.0;
|
||||
float outputSum = 0.0;
|
||||
float nearestDistanceEv = 3.402823466e+38;
|
||||
float nearestOutput = 0.0;
|
||||
for (int exposure = 0; exposure < 8; ++exposure) {
|
||||
float exposed = max(sceneInput * exposureGains[exposure], CURVE_EPS);
|
||||
float distanceEv = sceneFromKeyEv + exposureGainEvs[exposure];
|
||||
float weight = mix(
|
||||
sampledWeight(distanceEv, 0),
|
||||
sampledWeight(distanceEv, 1),
|
||||
highlightStrength
|
||||
);
|
||||
float clippedOutput = min(exposed, 1.0);
|
||||
weightSum += weight;
|
||||
outputSum += weight * clippedOutput;
|
||||
if (abs(distanceEv) < nearestDistanceEv) {
|
||||
nearestDistanceEv = abs(distanceEv);
|
||||
nearestOutput = clippedOutput;
|
||||
}
|
||||
}
|
||||
float fusedOutput = weightSum <= 0.0
|
||||
? nearestOutput
|
||||
: clamp(outputSum / weightSum, 0.0, 1.0);
|
||||
float monotonicOutput = max(previousTrueOutput, fusedOutput);
|
||||
trueGain = clamp(
|
||||
monotonicOutput / sceneInput,
|
||||
MIN_TABLE_GAIN,
|
||||
uMaxExposureGain
|
||||
);
|
||||
previousTrueOutput = monotonicOutput;
|
||||
}
|
||||
|
||||
float finalGain = trueGain;
|
||||
if (uDiagnosticMode >= 0) {
|
||||
float mask = diagnosticMask(tableInput);
|
||||
float mixedGain = uDiagnosticMode == 0
|
||||
? mix(1.0, trueGain, mask)
|
||||
: mix(trueGain, 1.0, mask);
|
||||
float monotonicOutput = max(previousFinalOutput, tableInput * mixedGain);
|
||||
finalGain = tableInput <= CURVE_EPS
|
||||
? clamp(mixedGain, MIN_TABLE_GAIN, uMaxExposureGain)
|
||||
: clamp(
|
||||
monotonicOutput / tableInput,
|
||||
MIN_TABLE_GAIN,
|
||||
uMaxExposureGain
|
||||
);
|
||||
previousFinalOutput = monotonicOutput;
|
||||
}
|
||||
gainCurves[outputOffset + point] = finalGain;
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -37,15 +37,6 @@ internal object DngPgtmDiagnostic {
|
||||
return PGTM_VISUAL_OVERLAY_MODE
|
||||
}
|
||||
|
||||
fun applyToEmbeddedMap(
|
||||
map: DngProfileGainTableMap?,
|
||||
source: String,
|
||||
): DngProfileGainTableMap? {
|
||||
val embeddedMap = map ?: return null
|
||||
val band = activeBandForSource(source) ?: return embeddedMap
|
||||
return DngHdrProfileGainTableGenerator.withDiagnosticBand(embeddedMap, band)
|
||||
}
|
||||
|
||||
private fun activeBand(): DngHdrProfileGainTableGenerator.DiagnosticBand? {
|
||||
return when (PGTM_DIAGNOSTIC_BAND_INDEX) {
|
||||
1 -> band(0.000f, 0.005f, feather = 0.0010f)
|
||||
|
||||
@@ -1,381 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import java.util.Arrays
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Scene-wide PGTM statistics computed from one uniform sample population.
|
||||
*
|
||||
* These values must not be produced by averaging per-cell percentiles: doing
|
||||
* so removes the spatial contrast between bright and dark regions and makes a
|
||||
* high-dynamic-range scene appear artificially flat.
|
||||
*/
|
||||
internal data class DngPgtmGlobalStats(
|
||||
val p10: Float,
|
||||
val p50: Float,
|
||||
val p90: Float,
|
||||
val p98: Float,
|
||||
val p995: Float,
|
||||
val p999: Float,
|
||||
val maxInput: Float,
|
||||
val highlightFraction: Float,
|
||||
val linearMean: Float,
|
||||
val logAverage: Float,
|
||||
val shadowEdge: Float,
|
||||
val shadowFoot: Float,
|
||||
val sampleCount: Int,
|
||||
) {
|
||||
companion object {
|
||||
private const val HIGHLIGHT_THRESHOLD = 0.92f
|
||||
private const val LOG_HISTOGRAM_MIN_EV = -16f
|
||||
private const val LOG_HISTOGRAM_MAX_EV = 8f
|
||||
private const val LOG_HISTOGRAM_BIN_EV = 0.125f
|
||||
private const val LOG_HISTOGRAM_BIN_COUNT = 192
|
||||
private const val LOG_HISTOGRAM_SMOOTH_SIGMA_BINS = 2f
|
||||
private const val LOG_HISTOGRAM_SMOOTH_RADIUS = 8
|
||||
private const val SHADOW_SEARCH_MIN_QUANTILE = 0.01f
|
||||
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.
|
||||
*/
|
||||
fun fromMutableSamples(samples: FloatArray, sampleCount: Int): DngPgtmGlobalStats? {
|
||||
val requestedCount = sampleCount.coerceIn(0, samples.size)
|
||||
var validCount = 0
|
||||
var highlightCount = 0
|
||||
var linearSum = 0.0
|
||||
var logSum = 0.0
|
||||
for (index in 0 until requestedCount) {
|
||||
val value = samples[index]
|
||||
if (!value.isFinite() || value < 0f) continue
|
||||
samples[validCount] = value
|
||||
validCount += 1
|
||||
linearSum += value.toDouble()
|
||||
logSum += ln(value.coerceAtLeast(1e-6f).toDouble())
|
||||
if (value >= HIGHLIGHT_THRESHOLD) highlightCount += 1
|
||||
}
|
||||
if (validCount <= 0) return null
|
||||
|
||||
Arrays.sort(samples, 0, validCount)
|
||||
val shadowSlope = shadowSlopeFromSortedSamples(samples, validCount)
|
||||
return DngPgtmGlobalStats(
|
||||
p10 = percentileFromSorted(samples, validCount, 0.10f),
|
||||
p50 = percentileFromSorted(samples, validCount, 0.50f),
|
||||
p90 = percentileFromSorted(samples, validCount, 0.90f),
|
||||
p98 = percentileFromSorted(samples, validCount, 0.98f),
|
||||
p995 = percentileFromSorted(samples, validCount, 0.995f),
|
||||
p999 = percentileFromSorted(samples, validCount, 0.999f),
|
||||
maxInput = samples[validCount - 1],
|
||||
highlightFraction = highlightCount.toFloat() / validCount.toFloat(),
|
||||
linearMean = (linearSum / validCount.toDouble()).toFloat(),
|
||||
logAverage = exp(logSum / validCount.toDouble()).toFloat(),
|
||||
shadowEdge = shadowSlope.edge,
|
||||
shadowFoot = shadowSlope.foot,
|
||||
sampleCount = validCount
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Locates the main shadow-content onset in an EV histogram. The strongest
|
||||
* rising edge is searched only in the lower 40% of positive samples, then
|
||||
* its outer foot is taken where density reaches 15% of the following peak.
|
||||
* This keeps the black reference tied to image structure instead of to a
|
||||
* fixed population count such as p10.
|
||||
*/
|
||||
private fun shadowSlopeFromSortedSamples(
|
||||
sortedSamples: FloatArray,
|
||||
sampleCount: Int,
|
||||
): ShadowSlope {
|
||||
val histogram = FloatArray(LOG_HISTOGRAM_BIN_COUNT)
|
||||
var positiveCount = 0
|
||||
for (index in 0 until sampleCount) {
|
||||
val value = sortedSamples[index]
|
||||
if (value <= 0f) continue
|
||||
val ev = log2(value).coerceIn(
|
||||
LOG_HISTOGRAM_MIN_EV,
|
||||
LOG_HISTOGRAM_MAX_EV - LOG_HISTOGRAM_BIN_EV
|
||||
)
|
||||
val bin = floor(
|
||||
(ev - LOG_HISTOGRAM_MIN_EV) / LOG_HISTOGRAM_BIN_EV
|
||||
).toInt().coerceIn(0, histogram.lastIndex)
|
||||
histogram[bin] += 1f
|
||||
positiveCount += 1
|
||||
}
|
||||
if (positiveCount <= 0) {
|
||||
val minimum = 2.0f.pow(LOG_HISTOGRAM_MIN_EV)
|
||||
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,
|
||||
positiveCount,
|
||||
SHADOW_SEARCH_MIN_QUANTILE
|
||||
).coerceIn(1, histogram.lastIndex - 1)
|
||||
val searchEnd = percentileBin(
|
||||
histogram,
|
||||
positiveCount,
|
||||
SHADOW_SEARCH_MAX_QUANTILE
|
||||
).coerceIn(searchStart, histogram.lastIndex - 1)
|
||||
|
||||
var edgeBin = searchStart
|
||||
var strongestRise = Float.NEGATIVE_INFINITY
|
||||
for (bin in searchStart..searchEnd) {
|
||||
val rise = smoothed[(bin + 1).coerceAtMost(smoothed.lastIndex)] -
|
||||
smoothed[bin - 1]
|
||||
if (rise > strongestRise) {
|
||||
strongestRise = rise
|
||||
edgeBin = bin
|
||||
}
|
||||
}
|
||||
|
||||
var peakBin = edgeBin
|
||||
for (bin in edgeBin..searchEnd) {
|
||||
if (smoothed[bin] > smoothed[peakBin]) peakBin = bin
|
||||
}
|
||||
val footDensity = smoothed[peakBin] * SHADOW_FOOT_DENSITY_RATIO
|
||||
var footBin = edgeBin
|
||||
while (footBin > 0 && smoothed[footBin] > footDensity) {
|
||||
footBin -= 1
|
||||
}
|
||||
|
||||
val edgeEv = binCenterEv(edgeBin)
|
||||
val footEv = if (footBin < edgeBin) {
|
||||
val lowerDensity = smoothed[footBin]
|
||||
val upperDensity = smoothed[footBin + 1]
|
||||
val fraction = if (upperDensity > lowerDensity) {
|
||||
((footDensity - lowerDensity) / (upperDensity - lowerDensity))
|
||||
.coerceIn(0f, 1f)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
binCenterEv(footBin) + fraction * LOG_HISTOGRAM_BIN_EV
|
||||
} else {
|
||||
edgeEv
|
||||
}
|
||||
return ShadowSlope(
|
||||
edge = 2.0f.pow(edgeEv),
|
||||
foot = 2.0f.pow(footEv.coerceAtMost(edgeEv))
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
for (offset in -LOG_HISTOGRAM_SMOOTH_RADIUS..LOG_HISTOGRAM_SMOOTH_RADIUS) {
|
||||
val normalized = offset.toDouble() / LOG_HISTOGRAM_SMOOTH_SIGMA_BINS.toDouble()
|
||||
val weight = exp(-0.5 * normalized * normalized)
|
||||
kernel[offset + LOG_HISTOGRAM_SMOOTH_RADIUS] = weight.toFloat()
|
||||
kernelSum += weight
|
||||
}
|
||||
for (index in kernel.indices) {
|
||||
kernel[index] = (kernel[index] / kernelSum).toFloat()
|
||||
}
|
||||
|
||||
return FloatArray(histogram.size) { bin ->
|
||||
var value = 0f
|
||||
for (offset in -LOG_HISTOGRAM_SMOOTH_RADIUS..LOG_HISTOGRAM_SMOOTH_RADIUS) {
|
||||
val sourceBin = bin + offset
|
||||
if (sourceBin !in histogram.indices) continue
|
||||
value += histogram[sourceBin] *
|
||||
kernel[offset + LOG_HISTOGRAM_SMOOTH_RADIUS]
|
||||
}
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
private fun percentileBin(
|
||||
histogram: FloatArray,
|
||||
sampleCount: Int,
|
||||
percentile: Float,
|
||||
): Int {
|
||||
val target = ceil(sampleCount * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceAtLeast(1)
|
||||
var cumulative = 0
|
||||
for (bin in histogram.indices) {
|
||||
cumulative += histogram[bin].toInt()
|
||||
if (cumulative >= target) return bin
|
||||
}
|
||||
return histogram.lastIndex
|
||||
}
|
||||
|
||||
private fun binCenterEv(bin: Int): Float {
|
||||
return LOG_HISTOGRAM_MIN_EV + (bin.toFloat() + 0.5f) * LOG_HISTOGRAM_BIN_EV
|
||||
}
|
||||
|
||||
private fun log2(value: Float): Float {
|
||||
return (ln(value.toDouble()) / ln(2.0)).toFloat()
|
||||
}
|
||||
|
||||
private fun percentileFromSorted(
|
||||
sortedSamples: FloatArray,
|
||||
sampleCount: Int,
|
||||
percentile: Float,
|
||||
): Float {
|
||||
val index = ceil(sampleCount.toFloat() * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceIn(1, sampleCount) - 1
|
||||
return sortedSamples[index]
|
||||
}
|
||||
|
||||
private data class ShadowSlope(
|
||||
val edge: Float,
|
||||
val foot: Float,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/** Legacy GPU result kept until the obsolete render-time PGTM shader is removed. */
|
||||
internal data class DngProfileGainTableGeneration(
|
||||
val baselineExposureEv: Float,
|
||||
val profileGainTableMap: DngProfileGainTableMap,
|
||||
)
|
||||
@@ -1,163 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
|
||||
/** CPU reference for the DNG SDK Camera RGB -> RIMM steps that precede PGTM. */
|
||||
internal object DngSdkProfileRgbTransform {
|
||||
fun fromCameraRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
colorCorrectionMatrix: FloatArray?,
|
||||
cameraWhite: FloatArray? = null,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): FloatArray {
|
||||
val white = sanitizedCameraWhite(cameraWhite)
|
||||
val cameraRed = min(red, white[0])
|
||||
val cameraGreen = min(green, white[1])
|
||||
val cameraBlue = min(blue, white[2])
|
||||
val matrix = colorCorrectionMatrix?.takeIf { it.size >= 9 }
|
||||
val profileRgb = if (matrix != null) {
|
||||
floatArrayOf(
|
||||
matrix[0] * cameraRed + matrix[1] * cameraGreen + matrix[2] * cameraBlue,
|
||||
matrix[3] * cameraRed + matrix[4] * cameraGreen + matrix[5] * cameraBlue,
|
||||
matrix[6] * cameraRed + matrix[7] * cameraGreen + matrix[8] * cameraBlue,
|
||||
)
|
||||
} else {
|
||||
floatArrayOf(cameraRed, cameraGreen, cameraBlue)
|
||||
}
|
||||
for (index in profileRgb.indices) {
|
||||
profileRgb[index] = profileRgb[index].takeIf { it.isFinite() }
|
||||
?.coerceIn(0f, 1f)
|
||||
?: 0f
|
||||
}
|
||||
return applyHueSatMap(profileRgb, hueSatMap)
|
||||
}
|
||||
|
||||
fun clampProfileRgb(red: Float, green: Float, blue: Float): FloatArray = floatArrayOf(
|
||||
red.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
green.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
blue.takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: 0f,
|
||||
)
|
||||
|
||||
private fun sanitizedCameraWhite(cameraWhite: FloatArray?): FloatArray {
|
||||
if (cameraWhite == null || cameraWhite.size < 3) return floatArrayOf(1f, 1f, 1f)
|
||||
return FloatArray(3) { index ->
|
||||
cameraWhite[index].takeIf { it.isFinite() }?.coerceIn(0.001f, 1f) ?: 1f
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyHueSatMap(rgb: FloatArray, map: DcpHueSatMap?): FloatArray {
|
||||
val table = map?.takeIf { it.isValid } ?: return rgb
|
||||
val hsv = rgbToHsv(rgb)
|
||||
var encodedValue = hsv[2]
|
||||
var lookupValue = hsv[2]
|
||||
if (table.encoding == DcpHueSatMap.ENCODING_SRGB && table.valueDivisions > 1) {
|
||||
encodedValue = encodeScaledValue(hsv[2], table.encoding)
|
||||
lookupValue = encodeLookupValue(hsv[2], table.encoding)
|
||||
}
|
||||
val modify = sampleMap(
|
||||
table,
|
||||
hsv[0],
|
||||
hsv[1],
|
||||
lookupValue.coerceIn(0f, 1f),
|
||||
)
|
||||
hsv[0] = positiveModulo(hsv[0] + modify[0] * 6f / 360f, 6f)
|
||||
hsv[1] = (hsv[1] * modify[1]).coerceIn(0f, 1f)
|
||||
hsv[2] = decodeScaledValue((encodedValue * modify[2]).coerceIn(0f, 1f), table.encoding)
|
||||
return hsvToRgb(hsv)
|
||||
}
|
||||
|
||||
private fun sampleMap(map: DcpHueSatMap, hue: Float, saturation: Float, value: Float): FloatArray {
|
||||
val hScaled = hue * map.hueDivisions.toFloat() / 6f
|
||||
val sScaled = saturation * max(map.satDivisions - 1, 0).toFloat()
|
||||
val vScaled = value * max(map.valueDivisions - 1, 0).toFloat()
|
||||
var h0 = floor(hScaled).toInt()
|
||||
var h1 = h0 + 1
|
||||
if (h0 >= map.hueDivisions - 1) {
|
||||
h0 = map.hueDivisions - 1
|
||||
h1 = 0
|
||||
}
|
||||
val s0 = min(floor(sScaled).toInt(), max(map.satDivisions - 2, 0))
|
||||
val v0 = min(floor(vScaled).toInt(), max(map.valueDivisions - 2, 0))
|
||||
val s1 = min(s0 + 1, map.satDivisions - 1)
|
||||
val v1 = min(v0 + 1, map.valueDivisions - 1)
|
||||
val hf = hScaled - h0.toFloat()
|
||||
val sf = sScaled - s0.toFloat()
|
||||
val vf = vScaled - v0.toFloat()
|
||||
|
||||
fun entry(h: Int, s: Int, v: Int): FloatArray {
|
||||
val offset = ((v * map.hueDivisions + h) * map.satDivisions + s) * 3
|
||||
return floatArrayOf(map.values[offset], map.values[offset + 1], map.values[offset + 2])
|
||||
}
|
||||
|
||||
fun mix(first: FloatArray, second: FloatArray, amount: Float): FloatArray =
|
||||
FloatArray(3) { index -> first[index] + (second[index] - first[index]) * amount }
|
||||
|
||||
val p000 = mix(entry(h0, s0, v0), entry(h0, s0, v1), vf)
|
||||
val p001 = mix(entry(h1, s0, v0), entry(h1, s0, v1), vf)
|
||||
val p010 = mix(entry(h0, s1, v0), entry(h0, s1, v1), vf)
|
||||
val p011 = mix(entry(h1, s1, v0), entry(h1, s1, v1), vf)
|
||||
return mix(mix(p000, p001, hf), mix(p010, p011, hf), sf)
|
||||
}
|
||||
|
||||
private fun rgbToHsv(rgb: FloatArray): FloatArray {
|
||||
val maxValue = max(rgb[0], max(rgb[1], rgb[2]))
|
||||
val minValue = min(rgb[0], min(rgb[1], rgb[2]))
|
||||
val delta = maxValue - minValue
|
||||
val hue = if (delta <= 1e-6f) {
|
||||
0f
|
||||
} else when (maxValue) {
|
||||
rgb[0] -> positiveModulo((rgb[1] - rgb[2]) / delta, 6f)
|
||||
rgb[1] -> (rgb[2] - rgb[0]) / delta + 2f
|
||||
else -> (rgb[0] - rgb[1]) / delta + 4f
|
||||
}
|
||||
return floatArrayOf(hue, if (maxValue > 1e-6f) delta / maxValue else 0f, maxValue)
|
||||
}
|
||||
|
||||
private fun hsvToRgb(hsv: FloatArray): FloatArray {
|
||||
val hue = positiveModulo(hsv[0], 6f)
|
||||
val chroma = max(hsv[2], 0f) * max(hsv[1], 0f)
|
||||
val x = chroma * (1f - abs(positiveModulo(hue, 2f) - 1f))
|
||||
val base = when {
|
||||
hue < 1f -> floatArrayOf(chroma, x, 0f)
|
||||
hue < 2f -> floatArrayOf(x, chroma, 0f)
|
||||
hue < 3f -> floatArrayOf(0f, chroma, x)
|
||||
hue < 4f -> floatArrayOf(0f, x, chroma)
|
||||
hue < 5f -> floatArrayOf(x, 0f, chroma)
|
||||
else -> floatArrayOf(chroma, 0f, x)
|
||||
}
|
||||
val match = max(hsv[2], 0f) - chroma
|
||||
return FloatArray(3) { index -> base[index] + match }
|
||||
}
|
||||
|
||||
private fun encodeLookupValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) linearToSrgb(value.coerceIn(0f, 1f)) else value
|
||||
|
||||
private fun encodeScaledValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) linearToSrgb(max(value, 0f)) else max(value, 0f)
|
||||
|
||||
private fun decodeScaledValue(value: Float, encoding: Int): Float =
|
||||
if (encoding == DcpHueSatMap.ENCODING_SRGB) srgbToLinear(max(value, 0f)) else max(value, 0f)
|
||||
|
||||
private fun linearToSrgb(value: Float): Float = if (value <= 0.0031308f) {
|
||||
value * 12.92f
|
||||
} else {
|
||||
1.055f * value.toDouble().pow(1.0 / 2.4).toFloat() - 0.055f
|
||||
}
|
||||
|
||||
private fun srgbToLinear(value: Float): Float = if (value <= 0.04045f) {
|
||||
value / 12.92f
|
||||
} else {
|
||||
((value + 0.055f) / 1.055f).toDouble().pow(2.4).toFloat()
|
||||
}
|
||||
|
||||
private fun positiveModulo(value: Float, modulus: Float): Float {
|
||||
val result = value % modulus
|
||||
return if (result < 0f) result + modulus else result
|
||||
}
|
||||
}
|
||||
@@ -271,6 +271,9 @@ class RawDemosaicProcessor {
|
||||
private var quadChromaProgram = 0
|
||||
private var quadRefineProgram = 0
|
||||
private var quadWriteOutputProgram = 0
|
||||
private var pgtmCellStatsProgram = 0
|
||||
private var pgtmGainCurvesProgram = 0
|
||||
private var pgtmWeightLutBufferId = 0
|
||||
private var linearRcdProgram = 0
|
||||
private var warpRectilinearProgram = 0
|
||||
private var linearRawRgbProgram = 0
|
||||
@@ -338,6 +341,7 @@ class RawDemosaicProcessor {
|
||||
private var curveTextureId = 0
|
||||
private var dcpToneCurveTextureId = 0
|
||||
private var dcpHueSatTextureId = 0
|
||||
private var dcpHueSatTextureSource: DcpHueSatMap? = null
|
||||
private var dcpLookTableTextureId = 0
|
||||
private var spectralFilmTextureId = 0
|
||||
private var spectralFilmTextureKey: String? = null
|
||||
@@ -737,21 +741,23 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/** Renders default-curve preview samples requested by a capture-side exposure solver. */
|
||||
internal suspend fun renderExposurePreviewSamples(
|
||||
/** Solves optional viewfinder exposure and prepares the capture PGTM in the same GL pass. */
|
||||
internal suspend fun prepareCaptureProfile(
|
||||
context: Context,
|
||||
input: RawDngViewfinderMatchInput,
|
||||
input: RawDngCaptureProfileInput,
|
||||
aspectRatio: AspectRatio?,
|
||||
cropRegion: Rect?,
|
||||
rotation: Int,
|
||||
request: RawExposurePreviewRequest,
|
||||
request: RawExposurePreviewRequest?,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
statsBounds: Rect?,
|
||||
rawBlackPointCorrection: Float = 0f,
|
||||
rawWhitePointCorrection: Float = 0f,
|
||||
rawAutoWhiteBalanceEstimate: Boolean = false,
|
||||
applyLensShadingCorrection: Boolean = true,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
): Float? = withContext(glDispatcher) {
|
||||
var solvedExposureEv: Float? = null
|
||||
): RawDngCaptureProfileResult? = withContext(glDispatcher) {
|
||||
var preparedResult: RawDngCaptureProfileResult? = null
|
||||
try {
|
||||
processInternal(
|
||||
context = context,
|
||||
@@ -780,12 +786,14 @@ class RawDemosaicProcessor {
|
||||
),
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
exposurePreviewRequest = request,
|
||||
onExposurePreviewSolved = { solvedExposureEv = it },
|
||||
captureProfileToneMapMode = profileToneMapMode,
|
||||
captureProfileStatsBounds = statsBounds,
|
||||
onCaptureProfilePrepared = { preparedResult = it },
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to render RAW exposure preview samples", e)
|
||||
PLog.e(TAG, "Failed to prepare RAW capture profile", e)
|
||||
}
|
||||
solvedExposureEv
|
||||
preparedResult
|
||||
}
|
||||
|
||||
suspend fun renderLinearRcdFrame(
|
||||
@@ -1003,7 +1011,9 @@ class RawDemosaicProcessor {
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null,
|
||||
includeHdrReference: Boolean = false,
|
||||
exposurePreviewRequest: RawExposurePreviewRequest? = null,
|
||||
onExposurePreviewSolved: ((Float?) -> Unit)? = null,
|
||||
captureProfileToneMapMode: RawProfileToneMapMode? = null,
|
||||
captureProfileStatsBounds: Rect? = null,
|
||||
onCaptureProfilePrepared: ((RawDngCaptureProfileResult?) -> Unit)? = null,
|
||||
): RawHdrRenderResult? = withContext(glDispatcher) {
|
||||
var actualRawData = rawData
|
||||
var actualWidth = width
|
||||
@@ -1023,10 +1033,7 @@ class RawDemosaicProcessor {
|
||||
if (dngFile != null) {
|
||||
val hasClassicTiffHeader = DngProfileGainTableMap.hasClassicTiffHeader(dngFile)
|
||||
val profileGainTableMap = if (hasClassicTiffHeader) {
|
||||
DngPgtmDiagnostic.applyToEmbeddedMap(
|
||||
DngProfileGainTableMap.readFrom(dngFile),
|
||||
"DNG render"
|
||||
)
|
||||
DngProfileGainTableMap.readFrom(dngFile)
|
||||
} else {
|
||||
PLog.d(TAG, "Skipping DNG-only metadata for non-classic-TIFF RAW: ${dngFile.name}")
|
||||
null
|
||||
@@ -1184,6 +1191,38 @@ class RawDemosaicProcessor {
|
||||
"aspectRatio=$aspectRatio rotation=$actualRotation outputSourceBounds=$outputSourceBounds"
|
||||
)
|
||||
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
|
||||
try {
|
||||
if (!isInitialized && !initializeOnGlThread()) {
|
||||
PLog.e(TAG, "Failed to initialize processor")
|
||||
return@withContext null
|
||||
}
|
||||
if (actualWidth > maxTextureSize || actualHeight > maxTextureSize) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Input ${actualWidth}x$actualHeight exceeds GL_MAX_TEXTURE_SIZE=$maxTextureSize",
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
setupFullResFramebuffer(actualWidth, actualHeight)
|
||||
if (actualSamplesPerPixel in 3..4) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride,
|
||||
actualSamplesPerPixel,
|
||||
)
|
||||
} else {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride,
|
||||
)
|
||||
}
|
||||
// The RAW source is GPU-resident from this point onward.
|
||||
actualRawData = null
|
||||
|
||||
val embeddedDngProfileName = embeddedDngRenderPlan?.profileName
|
||||
val embeddedProfileToneCurveLut = embeddedDngRenderPlan?.toneCurveLut
|
||||
val embeddedProfileToneMapMode = when {
|
||||
@@ -1223,25 +1262,23 @@ class RawDemosaicProcessor {
|
||||
if (profileGainToneMapRequested &&
|
||||
(profileGainTableMap == null || profileToneMapMode != requestedProfileToneMapMode)
|
||||
) {
|
||||
val generated = RawProfileGainTableMapBuilder.prepareForDngWrite(
|
||||
rawData = actualRawData,
|
||||
val generated = generateProfileGainTableMapOnGpu(
|
||||
rawTextureId = rawTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
rowStride = actualRowStride,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
options = RawDngProfilePreparationOptions(
|
||||
profileToneMapMode = requestedProfileToneMapMode,
|
||||
statsBounds = outputSourceBounds,
|
||||
),
|
||||
statsBounds = outputSourceBounds,
|
||||
baselineExposureEv = DngBaselineExposure.sanitize(actualMetadata.baselineExposure),
|
||||
profileToneMapMode = requestedProfileToneMapMode,
|
||||
colorCorrectionMatrix = resolvedDcpRenderPlan?.colorCorrectionMatrix
|
||||
?: actualMetadata.colorCorrectionMatrix,
|
||||
cameraWhite = resolvedDcpRenderPlan?.cameraWhite ?: actualMetadata.cameraWhite,
|
||||
hueSatMap = resolvedDcpRenderPlan?.hueSatMap,
|
||||
)?.profileGainTableMap?.takeIf { it.isValid }
|
||||
)?.takeIf { it.isValid }
|
||||
if (generated != null) {
|
||||
profileGainTableMap = generated
|
||||
profileGainTableMapSource = "generated"
|
||||
profileGainTableMapSource = "generated-gpu"
|
||||
} else if (profileGainTableMap != null) {
|
||||
// PGTM maps are curve-independent. A valid embedded map remains usable when the
|
||||
// user switches between the Photon and Google profile curves.
|
||||
@@ -1385,63 +1422,24 @@ class RawDemosaicProcessor {
|
||||
"engineWorkingSpace=$engineWorkingColorSpace"
|
||||
)
|
||||
|
||||
try {
|
||||
if (!isInitialized) {
|
||||
if (!initializeOnGlThread()) {
|
||||
PLog.e(TAG, "Failed to initialize processor")
|
||||
return@withContext null
|
||||
}
|
||||
}
|
||||
|
||||
// Check GL_MAX_TEXTURE_SIZE. Oversized Bayer RCD inputs are rejected.
|
||||
if (actualWidth > maxTextureSize || actualHeight > maxTextureSize) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Input ${actualWidth}x${actualHeight} exceeds GL_MAX_TEXTURE_SIZE=$maxTextureSize"
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
val bounds = rawOutputBounds
|
||||
val finalWidth = bounds.width()
|
||||
val finalHeight = bounds.height()
|
||||
|
||||
// 4. 第一步:全分辨率处理 (Linear CCM / RCD Compute Shader Demosaic)
|
||||
setupFullResFramebuffer(actualWidth, actualHeight)
|
||||
if (actualSamplesPerPixel in 3..4) {
|
||||
uploadLinearRawRgbTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride,
|
||||
actualSamplesPerPixel,
|
||||
)
|
||||
actualRawData = null
|
||||
renderLinearRawRgbToFramebuffer(
|
||||
sourceTextureId = rawTextureId,
|
||||
targetFramebufferId = demosaicFramebufferId,
|
||||
width = actualWidth,
|
||||
height = actualHeight
|
||||
)
|
||||
if (rawTextureId != 0) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(rawTextureId), 0)
|
||||
rawTextureId = 0
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"LinearRaw input prepared on GPU: ${actualWidth}x${actualHeight} " +
|
||||
"samplesPerPixel=$actualSamplesPerPixel rowStride=$actualRowStride"
|
||||
)
|
||||
} else {
|
||||
uploadRawTextureFromBuffer(
|
||||
actualRawData,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
actualRowStride
|
||||
)
|
||||
// GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB)
|
||||
actualRawData = null
|
||||
|
||||
// darktable feeds Filmic after the raw highlight reconstruction module;
|
||||
// keep the raw-domain repair enabled before Filmic HR.
|
||||
val rawDomainHighlightReconstructionEnabled = true
|
||||
@@ -1751,33 +1749,73 @@ class RawDemosaicProcessor {
|
||||
PLog.d(TAG, "Applied $appliedWarpCount/${warps.size / 8} DNG WarpRectilinear opcode(s) before color conversion")
|
||||
}
|
||||
|
||||
if (exposurePreviewRequest != null) {
|
||||
val solvedExposureEv = renderExposurePreviewRequest(
|
||||
request = exposurePreviewRequest,
|
||||
metadata = actualMetadata,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
applyLinearDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
applyProfileDngBaselineExposure = applyProfileDngBaselineExposure,
|
||||
applyProfileGainTableMap = false,
|
||||
clampProfileRgb = clampProfileRgb,
|
||||
outputBounds = bounds,
|
||||
outputRotation = actualRotation,
|
||||
spectralFilmLut = spektrafilmLut,
|
||||
colorEngine = colorEngine,
|
||||
outputWorkingColorSpace = engineWorkingColorSpace,
|
||||
profileToEngineTransform = profileToEngineTransform,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
useProfileExposureRamp = useProfileExposureRamp,
|
||||
applyProfileDcpBaselineExposureOffset = applyDcpBaselineExposureOffset,
|
||||
supportProfileOverrange = supportProfileOverrange
|
||||
if (exposurePreviewRequest != null || captureProfileToneMapMode != null) {
|
||||
val solvedExposureEv = exposurePreviewRequest?.let { request ->
|
||||
renderExposurePreviewRequest(
|
||||
request = request,
|
||||
metadata = actualMetadata,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
applyLinearDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
applyProfileDngBaselineExposure = applyProfileDngBaselineExposure,
|
||||
applyProfileGainTableMap = false,
|
||||
clampProfileRgb = clampProfileRgb,
|
||||
outputBounds = bounds,
|
||||
outputRotation = actualRotation,
|
||||
spectralFilmLut = spektrafilmLut,
|
||||
colorEngine = colorEngine,
|
||||
outputWorkingColorSpace = engineWorkingColorSpace,
|
||||
profileToEngineTransform = profileToEngineTransform,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
useProfileExposureRamp = useProfileExposureRamp,
|
||||
applyProfileDcpBaselineExposureOffset = applyDcpBaselineExposureOffset,
|
||||
supportProfileOverrange = supportProfileOverrange,
|
||||
)
|
||||
}
|
||||
solvedExposureEv?.let { exposureEv ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_VIEWFINDER_BASELINE stage=METERING_COMPLETE curve=DEFAULT " +
|
||||
"pgtm=false sourceBaselineEv=${actualMetadata.baselineExposure} " +
|
||||
"meteredExposureOffsetEv=$exposureEv",
|
||||
)
|
||||
}
|
||||
val finalBaselineExposureEv = DngBaselineExposure.sanitize(
|
||||
actualMetadata.baselineExposure + (solvedExposureEv ?: 0f)
|
||||
)
|
||||
onExposurePreviewSolved?.invoke(solvedExposureEv)
|
||||
val captureProfileGainTableMap = when (captureProfileToneMapMode) {
|
||||
RawProfileToneMapMode.Photon,
|
||||
RawProfileToneMapMode.GooglePixel -> generateProfileGainTableMapOnGpu(
|
||||
rawTextureId = rawTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata,
|
||||
statsBounds = captureProfileStatsBounds,
|
||||
baselineExposureEv = finalBaselineExposureEv,
|
||||
profileToneMapMode = captureProfileToneMapMode,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
val profileRequired = captureProfileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
captureProfileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
val captureResult = if (profileRequired && captureProfileGainTableMap == null) {
|
||||
null
|
||||
} else {
|
||||
RawDngCaptureProfileResult(
|
||||
exposureOffsetEv = solvedExposureEv,
|
||||
profileGainTableMap = captureProfileGainTableMap,
|
||||
)
|
||||
}
|
||||
onCaptureProfilePrepared?.invoke(captureResult)
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
@@ -2066,6 +2104,355 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private fun generateProfileGainTableMapOnGpu(
|
||||
rawTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
samplesPerPixel: Int,
|
||||
metadata: RawMetadata,
|
||||
statsBounds: Rect?,
|
||||
baselineExposureEv: Float,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): DngProfileGainTableMap? {
|
||||
if (rawTextureId == 0 || width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW PGTM input invalid: texture=$rawTextureId size=${width}x$height " +
|
||||
"white=${metadata.whiteLevel}",
|
||||
)
|
||||
return null
|
||||
}
|
||||
if (pgtmCellStatsProgram == 0 ||
|
||||
pgtmGainCurvesProgram == 0 ||
|
||||
pgtmWeightLutBufferId == 0
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW PGTM programs unavailable: stats=$pgtmCellStatsProgram " +
|
||||
"curves=$pgtmGainCurvesProgram weights=$pgtmWeightLutBufferId",
|
||||
)
|
||||
return null
|
||||
}
|
||||
val fusionParameters = when (profileToneMapMode) {
|
||||
RawProfileToneMapMode.Photon -> DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS
|
||||
RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS
|
||||
else -> return null
|
||||
}
|
||||
val safeStatsBounds = sanitizePgtmStatsBounds(statsBounds, width, height) ?: run {
|
||||
PLog.e(TAG, "GPU RAW PGTM stats bounds invalid: source=${width}x$height bounds=$statsBounds")
|
||||
return null
|
||||
}
|
||||
val gridSize = DngHdrProfileGainTableGenerator.gridSizeFor(width, height)
|
||||
val gridWidth = gridSize.getOrElse(0) { 0 }
|
||||
val gridHeight = gridSize.getOrElse(1) { 0 }
|
||||
if (gridWidth <= 0 || gridHeight <= 0) return null
|
||||
|
||||
val cellCount = gridWidth * gridHeight
|
||||
val statsFloatCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
val bufferIds = IntArray(3)
|
||||
val totalStartNs = System.nanoTime()
|
||||
GLES31.glGenBuffers(bufferIds.size, bufferIds, 0)
|
||||
try {
|
||||
val statsBufferId = bufferIds[0]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, statsBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
statsFloatCount * Float.SIZE_BYTES,
|
||||
null,
|
||||
GLES31.GL_DYNAMIC_READ,
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, statsBufferId)
|
||||
|
||||
GLES31.glUseProgram(pgtmCellStatsProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uRawTexture"),
|
||||
RCD_RAW_TEXTURE_UNIT,
|
||||
)
|
||||
val activeHueSatMap = hueSatMap?.takeIf { it.isValid }
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
|
||||
val hueSatTextureId = activeHueSatMap?.let { map ->
|
||||
ensureDcpHueSatTexture(map)
|
||||
} ?: ensureDummyDcp3DTexture()
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, hueSatTextureId)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatMap"),
|
||||
LINEAR_DCP_HUE_SAT_TEXTURE_UNIT,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatEnabled"),
|
||||
if (activeHueSatMap != null) 1 else 0,
|
||||
)
|
||||
GLES31.glUniform3i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatDivisions"),
|
||||
activeHueSatMap?.hueDivisions ?: 1,
|
||||
activeHueSatMap?.satDivisions ?: 1,
|
||||
activeHueSatMap?.valueDivisions ?: 1,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uHueSatEncoding"),
|
||||
activeHueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uImageSize"),
|
||||
width,
|
||||
height,
|
||||
)
|
||||
GLES31.glUniform4i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uStatsBounds"),
|
||||
safeStatsBounds.left,
|
||||
safeStatsBounds.top,
|
||||
safeStatsBounds.right,
|
||||
safeStatsBounds.bottom,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uGridSize"),
|
||||
gridWidth,
|
||||
gridHeight,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uSamplesPerPixel"),
|
||||
samplesPerPixel.coerceAtLeast(1),
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uCfaPattern"),
|
||||
metadata.cfaPattern,
|
||||
)
|
||||
val blackLevel4 = FloatArray(4) { index ->
|
||||
metadata.blackLevel.getOrElse(index) {
|
||||
metadata.blackLevel.firstOrNull() ?: 0f
|
||||
}
|
||||
}
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uBlackLevel"),
|
||||
1,
|
||||
blackLevel4,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uWhiteLevel"),
|
||||
metadata.whiteLevel,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uBaselineGain"),
|
||||
DngBaselineExposure.exactGain(baselineExposureEv),
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uCameraWhite"),
|
||||
1,
|
||||
sanitizeCameraWhite(cameraWhite),
|
||||
0,
|
||||
)
|
||||
val safeColorCorrectionMatrix = colorCorrectionMatrix.takeIf { matrix ->
|
||||
matrix.size >= 9 && matrix.take(9).all { it.isFinite() }
|
||||
} ?: floatArrayOf(
|
||||
1f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 1f,
|
||||
)
|
||||
GLES31.glUniformMatrix3fv(
|
||||
GLES31.glGetUniformLocation(pgtmCellStatsProgram, "uColorCorrectionMatrix"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(safeColorCorrectionMatrix),
|
||||
0,
|
||||
)
|
||||
val statsGpuStartNs = System.nanoTime()
|
||||
GLES31.glDispatchCompute(gridWidth, gridHeight, 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
checkGlError("generateProfileGainTableMapOnGpu stats dispatch")
|
||||
val packedCellStats = readFloatStorageBuffer(
|
||||
bufferId = statsBufferId,
|
||||
floatCount = statsFloatCount,
|
||||
label = "PGTM cell stats",
|
||||
) ?: return null
|
||||
val statsGpuReadyNs = System.nanoTime()
|
||||
|
||||
val plan = DngHdrProfileGainTableGenerator.planForCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU capture"),
|
||||
fusionParameters = fusionParameters,
|
||||
) ?: return null
|
||||
val planReadyNs = System.nanoTime()
|
||||
if (plan.cellPlans.size != cellCount) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW PGTM plan count=${plan.cellPlans.size}, expected=$cellCount",
|
||||
)
|
||||
return null
|
||||
}
|
||||
|
||||
val exposurePlanBuffer = ByteBuffer.allocateDirect(cellCount * 2 * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer()
|
||||
plan.cellPlans.forEach { cellPlan ->
|
||||
exposurePlanBuffer.put(cellPlan.brightestExposureGain)
|
||||
exposurePlanBuffer.put(cellPlan.darkestExposureGain)
|
||||
}
|
||||
exposurePlanBuffer.position(0)
|
||||
val planBufferId = bufferIds[1]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, planBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
cellCount * 2 * Float.SIZE_BYTES,
|
||||
exposurePlanBuffer,
|
||||
GLES31.GL_STATIC_DRAW,
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, planBufferId)
|
||||
|
||||
val gainFloatCount = cellCount * plan.pointCount
|
||||
val gainBufferId = bufferIds[2]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, gainBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
gainFloatCount * Float.SIZE_BYTES,
|
||||
null,
|
||||
GLES31.GL_DYNAMIC_READ,
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, gainBufferId)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
2,
|
||||
pgtmWeightLutBufferId,
|
||||
)
|
||||
|
||||
GLES31.glUseProgram(pgtmGainCurvesProgram)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uCellCount"),
|
||||
cellCount,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uPointCount"),
|
||||
plan.pointCount,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uInputScale"),
|
||||
plan.inputScale,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uWellExposedKey"),
|
||||
plan.fusionParameters.wellExposedKey,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uMaxExposureGain"),
|
||||
plan.fusionParameters.maxExposureGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uHighlightFusionStart"),
|
||||
plan.fusionParameters.highlightFusionStart,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uHighlightFusionEnd"),
|
||||
plan.fusionParameters.highlightFusionEnd,
|
||||
)
|
||||
val diagnosticMode = when (plan.diagnosticBand?.mode) {
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
|
||||
DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
|
||||
null -> -1
|
||||
}
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticMode"),
|
||||
diagnosticMode,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticStart"),
|
||||
plan.diagnosticBand?.start ?: 0f,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticEnd"),
|
||||
plan.diagnosticBand?.end ?: 1f,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(pgtmGainCurvesProgram, "uDiagnosticFeather"),
|
||||
plan.diagnosticBand?.feather ?: 0f,
|
||||
)
|
||||
val curveGpuStartNs = System.nanoTime()
|
||||
GLES31.glDispatchCompute((cellCount + 63) / 64, 1, 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
checkGlError("generateProfileGainTableMapOnGpu curve dispatch")
|
||||
val gains = readFloatStorageBuffer(
|
||||
bufferId = gainBufferId,
|
||||
floatCount = gainFloatCount,
|
||||
label = "PGTM gain curves",
|
||||
) ?: return null
|
||||
val curvesGpuReadyNs = System.nanoTime()
|
||||
val map = DngHdrProfileGainTableGenerator.mapFromGpuGains(plan, gains) ?: return null
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU RAW PGTM prepared: mode=$profileToneMapMode size=${width}x$height " +
|
||||
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
|
||||
"statsGpuMs=${(statsGpuReadyNs - statsGpuStartNs) / 1_000_000.0} " +
|
||||
"planCpuMs=${(planReadyNs - statsGpuReadyNs) / 1_000_000.0} " +
|
||||
"curvesGpuMs=${(curvesGpuReadyNs - curveGpuStartNs) / 1_000_000.0} " +
|
||||
"totalMs=${(curvesGpuReadyNs - totalStartNs) / 1_000_000.0}",
|
||||
)
|
||||
return map
|
||||
} catch (error: Exception) {
|
||||
PLog.e(TAG, "GPU RAW PGTM preparation failed", error)
|
||||
return null
|
||||
} finally {
|
||||
GLES31.glUseProgram(0)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, 0)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, 0)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, 0)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, 0)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
|
||||
GLES31.glDeleteBuffers(bufferIds.size, bufferIds, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun readFloatStorageBuffer(
|
||||
bufferId: Int,
|
||||
floatCount: Int,
|
||||
label: String,
|
||||
): FloatArray? {
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId)
|
||||
val byteCount = floatCount * Float.SIZE_BYTES
|
||||
val mapped = GLES31.glMapBufferRange(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
0,
|
||||
byteCount,
|
||||
GLES31.GL_MAP_READ_BIT,
|
||||
) ?: run {
|
||||
PLog.e(TAG, "$label buffer map failed")
|
||||
return null
|
||||
}
|
||||
return try {
|
||||
val byteBuffer = mapped as? ByteBuffer ?: run {
|
||||
PLog.e(TAG, "$label mapped buffer is not a ByteBuffer")
|
||||
return null
|
||||
}
|
||||
FloatArray(floatCount).also { values ->
|
||||
byteBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer().get(values)
|
||||
}
|
||||
} finally {
|
||||
GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sanitizePgtmStatsBounds(bounds: Rect?, width: Int, height: Int): Rect? {
|
||||
val imageBounds = Rect(0, 0, width, height)
|
||||
if (bounds == null) return imageBounds
|
||||
if (bounds.isEmpty) return null
|
||||
return Rect(bounds).takeIf {
|
||||
it.intersect(imageBounds) && it.width() >= 2 && it.height() >= 2
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateOutputSourceBounds(
|
||||
width: Int,
|
||||
height: Int,
|
||||
@@ -2452,7 +2839,8 @@ class RawDemosaicProcessor {
|
||||
GLES30.glDeleteShader(vShader)
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Shader programs created: passthrough=$passthroughProgram"
|
||||
"Shader programs created: passthrough=$passthroughProgram " +
|
||||
"pgtmStats=$pgtmCellStatsProgram pgtmCurves=$pgtmGainCurvesProgram"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2985,6 +3373,17 @@ class RawDemosaicProcessor {
|
||||
quadChromaProgram = compileComputeProgram(QuadBayerShaders.CHROMA, "QUAD_CHROMA")
|
||||
quadRefineProgram = compileComputeProgram(QuadBayerShaders.REFINE, "QUAD_REFINE")
|
||||
quadWriteOutputProgram = compileComputeProgram(QuadBayerShaders.WRITE_OUTPUT, "QUAD_WRITE_OUTPUT")
|
||||
pgtmCellStatsProgram = compileComputeProgram(
|
||||
DngHdrProfileGainTableGpuShaders.CELL_STATS,
|
||||
"DNG_PGTM_CELL_STATS",
|
||||
)
|
||||
pgtmGainCurvesProgram = compileComputeProgram(
|
||||
DngHdrProfileGainTableGpuShaders.GAIN_CURVES,
|
||||
"DNG_PGTM_GAIN_CURVES",
|
||||
)
|
||||
if (pgtmCellStatsProgram != 0 && pgtmGainCurvesProgram != 0) {
|
||||
initPgtmWeightLutBuffer()
|
||||
}
|
||||
|
||||
val fShaderLinearRcd = compileShader(
|
||||
GLES30.GL_FRAGMENT_SHADER,
|
||||
@@ -3029,6 +3428,28 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
|
||||
private fun initPgtmWeightLutBuffer() {
|
||||
if (pgtmWeightLutBufferId != 0) return
|
||||
val weights = DngHdrProfileGainTableGenerator.interleavedWellExposedWeightLut()
|
||||
val buffer = ByteBuffer.allocateDirect(weights.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer()
|
||||
buffer.put(weights)
|
||||
buffer.position(0)
|
||||
val ids = IntArray(1)
|
||||
GLES31.glGenBuffers(1, ids, 0)
|
||||
pgtmWeightLutBufferId = ids[0]
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, pgtmWeightLutBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
weights.size * Float.SIZE_BYTES,
|
||||
buffer,
|
||||
GLES31.GL_STATIC_DRAW,
|
||||
)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
checkGlError("initPgtmWeightLutBuffer")
|
||||
}
|
||||
|
||||
private fun linkFragmentProgram(
|
||||
vShader: Int,
|
||||
fragmentSource: String,
|
||||
@@ -5732,6 +6153,19 @@ class RawDemosaicProcessor {
|
||||
return textureId
|
||||
}
|
||||
|
||||
private fun ensureDcpHueSatTexture(table: DcpHueSatMap): Int {
|
||||
if (dcpHueSatTextureId != 0 && dcpHueSatTextureSource === table) {
|
||||
return dcpHueSatTextureId
|
||||
}
|
||||
val textureId = uploadDcp3DTexture(
|
||||
textureIdProvider = { dcpHueSatTextureId },
|
||||
assignTextureId = { dcpHueSatTextureId = it },
|
||||
table = table,
|
||||
)
|
||||
dcpHueSatTextureSource = table
|
||||
return textureId
|
||||
}
|
||||
|
||||
private fun bindDcpCombinedResources(
|
||||
program: Int,
|
||||
dcpRenderPlan: DcpRenderPlan?,
|
||||
@@ -5753,8 +6187,7 @@ class RawDemosaicProcessor {
|
||||
|
||||
if (hueSatMap != null) {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE2)
|
||||
val textureId =
|
||||
uploadDcp3DTexture({ dcpHueSatTextureId }, { dcpHueSatTextureId = it }, hueSatMap)
|
||||
val textureId = ensureDcpHueSatTexture(hueSatMap)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
|
||||
GLES30.glUniform3i(
|
||||
GLES30.glGetUniformLocation(program, "uDcpHueSatDivisions"),
|
||||
@@ -7267,11 +7700,7 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + LINEAR_DCP_HUE_SAT_TEXTURE_UNIT)
|
||||
val textureId = activeMap?.let { map ->
|
||||
uploadDcp3DTexture(
|
||||
textureIdProvider = { dcpHueSatTextureId },
|
||||
assignTextureId = { dcpHueSatTextureId = it },
|
||||
table = map,
|
||||
)
|
||||
ensureDcpHueSatTexture(map)
|
||||
} ?: ensureDummyDcp3DTexture()
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
|
||||
GLES30.glUniform1i(
|
||||
@@ -8115,6 +8544,12 @@ class RawDemosaicProcessor {
|
||||
if (quadChromaProgram != 0) GLES31.glDeleteProgram(quadChromaProgram)
|
||||
if (quadRefineProgram != 0) GLES31.glDeleteProgram(quadRefineProgram)
|
||||
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
|
||||
if (pgtmCellStatsProgram != 0) GLES31.glDeleteProgram(pgtmCellStatsProgram)
|
||||
if (pgtmGainCurvesProgram != 0) GLES31.glDeleteProgram(pgtmGainCurvesProgram)
|
||||
if (pgtmWeightLutBufferId != 0) {
|
||||
GLES31.glDeleteBuffers(1, intArrayOf(pgtmWeightLutBufferId), 0)
|
||||
pgtmWeightLutBufferId = 0
|
||||
}
|
||||
if (linearRcdProgram != 0) GLES31.glDeleteProgram(linearRcdProgram)
|
||||
if (warpRectilinearProgram != 0) GLES31.glDeleteProgram(warpRectilinearProgram)
|
||||
if (linearRawRgbProgram != 0) GLES31.glDeleteProgram(linearRawRgbProgram)
|
||||
@@ -8222,6 +8657,7 @@ class RawDemosaicProcessor {
|
||||
0
|
||||
)
|
||||
if (dcpHueSatTextureId != 0) GLES30.glDeleteTextures(1, intArrayOf(dcpHueSatTextureId), 0)
|
||||
dcpHueSatTextureSource = null
|
||||
if (dcpLookTableTextureId != 0) GLES30.glDeleteTextures(
|
||||
1,
|
||||
intArrayOf(dcpLookTableTextureId),
|
||||
|
||||
@@ -7,14 +7,14 @@ import java.nio.ByteBuffer
|
||||
data class RawDngProfilePreparationOptions(
|
||||
val profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon,
|
||||
val statsBounds: Rect? = null,
|
||||
val viewfinderExposureMatcher: RawDngViewfinderExposureMatcher? = null,
|
||||
val captureProfilePreparer: RawDngCaptureProfilePreparer? = null,
|
||||
)
|
||||
|
||||
fun interface RawDngViewfinderExposureMatcher {
|
||||
suspend fun match(input: RawDngViewfinderMatchInput): Float?
|
||||
fun interface RawDngCaptureProfilePreparer {
|
||||
suspend fun prepare(input: RawDngCaptureProfileInput): RawDngCaptureProfileResult?
|
||||
}
|
||||
|
||||
data class RawDngViewfinderMatchInput(
|
||||
data class RawDngCaptureProfileInput(
|
||||
val rawData: ByteBuffer,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
@@ -23,6 +23,11 @@ data class RawDngViewfinderMatchInput(
|
||||
val metadata: RawMetadata,
|
||||
)
|
||||
|
||||
data class RawDngCaptureProfileResult(
|
||||
val exposureOffsetEv: Float?,
|
||||
val profileGainTableMap: DngProfileGainTableMap?,
|
||||
)
|
||||
|
||||
/** BaselineExposure and optional PGTM prepared before the DNG writer starts. */
|
||||
internal data class RawDngProfilePreparation(
|
||||
val baselineExposureEv: Float,
|
||||
|
||||
@@ -1,397 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.graphics.Rect
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.max
|
||||
|
||||
internal object RawProfileGainTableMapBuilder {
|
||||
private const val TAG = "RawProfileGainTableMapBuilder"
|
||||
private const val SAMPLE_GRID = 16
|
||||
|
||||
private data class BuiltPgtmStats(
|
||||
val packedCellStats: FloatArray,
|
||||
)
|
||||
|
||||
fun prepareForDngWrite(
|
||||
rawData: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
rowStride: Int,
|
||||
metadata: RawMetadata,
|
||||
samplesPerPixel: Int = 1,
|
||||
options: RawDngProfilePreparationOptions = RawDngProfilePreparationOptions(),
|
||||
colorCorrectionMatrix: FloatArray = metadata.colorCorrectionMatrix,
|
||||
cameraWhite: FloatArray = metadata.cameraWhite,
|
||||
hueSatMap: DcpHueSatMap? = null,
|
||||
): RawDngProfilePreparation? {
|
||||
val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure)
|
||||
val generatePgtm = options.profileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
options.profileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
if (!generatePgtm) {
|
||||
return RawDngProfilePreparation(
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
profileGainTableMap = null,
|
||||
)
|
||||
}
|
||||
|
||||
val statsMetadata = metadata.copy(baselineExposure = baselineExposureEv)
|
||||
val initialStats = buildPackedCellStats(
|
||||
rawData = rawData,
|
||||
width = width,
|
||||
height = height,
|
||||
rowStride = rowStride,
|
||||
metadata = statsMetadata,
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
statsBounds = options.statsBounds,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
) ?: return null
|
||||
return prepareFromStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
profileToneMapMode = options.profileToneMapMode,
|
||||
packedCellStats = initialStats.packedCellStats,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun prepareFromStats(
|
||||
width: Int,
|
||||
height: Int,
|
||||
baselineExposureEv: Float,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
packedCellStats: FloatArray,
|
||||
): RawDngProfilePreparation? {
|
||||
val generatePgtm = profileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
profileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG)
|
||||
val profileGainTableMap = if (generatePgtm) {
|
||||
DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = packedCellStats,
|
||||
diagnosticBand = diagnosticBand,
|
||||
fusionParameters = if (profileToneMapMode == RawProfileToneMapMode.Photon)
|
||||
DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS
|
||||
else DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS
|
||||
) ?: run {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"PGTM generation failed: mode=$profileToneMapMode " +
|
||||
"baselineExposureEv=$baselineExposureEv size=${width}x$height"
|
||||
)
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
return RawDngProfilePreparation(
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
profileGainTableMap = profileGainTableMap,
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildPackedCellStats(
|
||||
rawData: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
rowStride: Int,
|
||||
metadata: RawMetadata,
|
||||
samplesPerPixel: Int,
|
||||
statsBounds: Rect?,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): BuiltPgtmStats? {
|
||||
if (width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) return null
|
||||
val sampleCountPerPixel = samplesPerPixel.coerceAtLeast(1)
|
||||
val rowBytes = width * sampleCountPerPixel * 2
|
||||
val safeRowStride = rowStride.takeIf { it >= rowBytes } ?: rowBytes
|
||||
val source = rawData.duplicate().order(ByteOrder.nativeOrder())
|
||||
val requiredBytes = (height - 1).toLong() * safeRowStride.toLong() + rowBytes.toLong()
|
||||
if (requiredBytes > source.capacity().toLong()) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"RAW buffer too small for PGTM stats: required=$requiredBytes capacity=${source.capacity()} " +
|
||||
"size=${width}x$height rowStride=$safeRowStride"
|
||||
)
|
||||
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 safeStatsBounds = sanitizeStatsBounds(statsBounds, width, height) ?: return null
|
||||
if (!safeStatsBounds.isFullImage(width, height)) {
|
||||
PLog.d(TAG, "PGTM stats bounds: source=${width}x$height bounds=$safeStatsBounds")
|
||||
}
|
||||
|
||||
val baselineGain = DngBaselineExposure.exactGain(metadata.baselineExposure)
|
||||
val stats = FloatArray(gridWidth * gridHeight * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE)
|
||||
val inputSamples = FloatArray(SAMPLE_GRID * SAMPLE_GRID)
|
||||
val statsWidth = safeStatsBounds.width()
|
||||
val statsHeight = safeStatsBounds.height()
|
||||
for (cellY in 0 until gridHeight) {
|
||||
for (cellX in 0 until gridWidth) {
|
||||
var sampleCount = 0
|
||||
var highlightCount = 0
|
||||
var startX = safeStatsBounds.left + (cellX * statsWidth) / gridWidth
|
||||
var endX = safeStatsBounds.left + ((cellX + 1) * statsWidth + gridWidth - 1) / gridWidth
|
||||
var startY = safeStatsBounds.top + (cellY * statsHeight) / gridHeight
|
||||
var endY = safeStatsBounds.top + ((cellY + 1) * statsHeight + gridHeight - 1) / gridHeight
|
||||
startX = alignUpToEven(startX)
|
||||
startY = alignUpToEven(startY)
|
||||
endX = alignDownToEven(endX).coerceAtMost(safeStatsBounds.right)
|
||||
endY = alignDownToEven(endY).coerceAtMost(safeStatsBounds.bottom)
|
||||
|
||||
val offset = (cellY * gridWidth + cellX) *
|
||||
DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
if (endX - startX < 2 || endY - startY < 2) {
|
||||
stats[offset + 5] = 0f
|
||||
continue
|
||||
}
|
||||
|
||||
val cellWidth = max(endX - startX, 2)
|
||||
val cellHeight = max(endY - startY, 2)
|
||||
for (localY in 0 until SAMPLE_GRID) {
|
||||
for (localX in 0 until SAMPLE_GRID) {
|
||||
var x = startX + ((localX * 2 + 1) * cellWidth) / (SAMPLE_GRID * 2)
|
||||
var y = startY + ((localY * 2 + 1) * cellHeight) / (SAMPLE_GRID * 2)
|
||||
x = (x - (x and 1)).coerceIn(startX, max(startX, endX - 2))
|
||||
y = (y - (y and 1)).coerceIn(startY, max(startY, endY - 2))
|
||||
val inputValue = pgtmInputAt(
|
||||
rawData = source,
|
||||
rowStride = safeRowStride,
|
||||
metadata = metadata,
|
||||
width = width,
|
||||
height = height,
|
||||
baseX = x,
|
||||
baseY = y,
|
||||
baselineGain = baselineGain,
|
||||
samplesPerPixel = sampleCountPerPixel,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
inputSamples[sampleCount] = inputValue
|
||||
sampleCount += 1
|
||||
if (inputValue >= 0.92f) {
|
||||
highlightCount += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
java.util.Arrays.sort(inputSamples, 0, sampleCount)
|
||||
stats[offset] = percentileFromSortedSamples(inputSamples, sampleCount, 0.10f)
|
||||
stats[offset + 1] = percentileFromSortedSamples(inputSamples, sampleCount, 0.50f)
|
||||
stats[offset + 2] = percentileFromSortedSamples(inputSamples, sampleCount, 0.90f)
|
||||
stats[offset + 3] = percentileFromSortedSamples(inputSamples, sampleCount, 0.98f)
|
||||
stats[offset + 4] = if (sampleCount > 0) {
|
||||
highlightCount.toFloat() / sampleCount.toFloat()
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
stats[offset + 5] = sampleCount.toFloat()
|
||||
stats[offset + 6] = percentileFromSortedSamples(inputSamples, sampleCount, 0.995f)
|
||||
stats[offset + 7] = percentileFromSortedSamples(inputSamples, sampleCount, 0.999f)
|
||||
}
|
||||
}
|
||||
return BuiltPgtmStats(
|
||||
packedCellStats = stats,
|
||||
)
|
||||
}
|
||||
|
||||
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 alignUpToEven(value: Int): Int {
|
||||
return if ((value and 1) == 0) value else value + 1
|
||||
}
|
||||
|
||||
private fun alignDownToEven(value: Int): Int {
|
||||
return if ((value and 1) == 0) value else value - 1
|
||||
}
|
||||
|
||||
private fun Rect.isFullImage(width: Int, height: Int): Boolean {
|
||||
return left == 0 && top == 0 && right == width && bottom == height
|
||||
}
|
||||
|
||||
private fun pgtmInputAt(
|
||||
rawData: ByteBuffer,
|
||||
rowStride: Int,
|
||||
metadata: RawMetadata,
|
||||
width: Int,
|
||||
height: Int,
|
||||
baseX: Int,
|
||||
baseY: Int,
|
||||
baselineGain: Float,
|
||||
samplesPerPixel: Int,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
if (samplesPerPixel >= 3) {
|
||||
return linearRgbPgtmInputAt(
|
||||
rawData = rawData,
|
||||
rowStride = rowStride,
|
||||
metadata = metadata,
|
||||
width = width,
|
||||
height = height,
|
||||
x = baseX,
|
||||
y = baseY,
|
||||
baselineGain = baselineGain,
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
var r = 0f
|
||||
var g = 0f
|
||||
var b = 0f
|
||||
var rc = 0f
|
||||
var gc = 0f
|
||||
var bc = 0f
|
||||
for (dy in 0..1) {
|
||||
for (dx in 0..1) {
|
||||
val x = (baseX + dx).coerceIn(0, width - 1)
|
||||
val y = (baseY + dy).coerceIn(0, height - 1)
|
||||
val value = normalizedRawAt(rawData, rowStride, metadata, x, y)
|
||||
when (RawCfaCorrection.colorCodeForPixel(metadata.cfaPattern, x, y)) {
|
||||
0 -> {
|
||||
r += value
|
||||
rc += 1f
|
||||
}
|
||||
|
||||
2 -> {
|
||||
b += value
|
||||
bc += 1f
|
||||
}
|
||||
|
||||
else -> {
|
||||
g += value
|
||||
gc += 1f
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val fallback = (r + g + b) / max(rc + gc + bc, 1f)
|
||||
val red = if (rc > 0f) r / rc else fallback
|
||||
val green = if (gc > 0f) g / gc else fallback
|
||||
val blue = if (bc > 0f) b / bc else fallback
|
||||
return sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
private fun linearRgbPgtmInputAt(
|
||||
rawData: ByteBuffer,
|
||||
rowStride: Int,
|
||||
metadata: RawMetadata,
|
||||
width: Int,
|
||||
height: Int,
|
||||
x: Int,
|
||||
y: Int,
|
||||
baselineGain: Float,
|
||||
samplesPerPixel: Int,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
val clampedX = x.coerceIn(0, width - 1)
|
||||
val clampedY = y.coerceIn(0, height - 1)
|
||||
val pixelOffset = clampedY * rowStride + clampedX * samplesPerPixel * 2
|
||||
val red = normalizedLinearRgbAt(rawData, pixelOffset, metadata, 0)
|
||||
val green = normalizedLinearRgbAt(rawData, pixelOffset + 2, metadata, 1)
|
||||
val blue = normalizedLinearRgbAt(rawData, pixelOffset + 4, metadata, 2)
|
||||
return sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
private fun sceneInputFromLinearRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
colorCorrectionMatrix: FloatArray?,
|
||||
cameraWhite: FloatArray?,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
): Float {
|
||||
return DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
cameraWhite = cameraWhite,
|
||||
hueSatMap = hueSatMap,
|
||||
)
|
||||
}
|
||||
|
||||
private fun normalizedLinearRgbAt(
|
||||
rawData: ByteBuffer,
|
||||
offset: Int,
|
||||
metadata: RawMetadata,
|
||||
channelIndex: Int,
|
||||
): Float {
|
||||
val raw = rawData.getShort(offset).toInt() and 0xFFFF
|
||||
val black = metadata.blackLevel.getOrElse(channelIndex) {
|
||||
metadata.blackLevel.firstOrNull() ?: 0f
|
||||
}
|
||||
val range = max(metadata.whiteLevel - black, 1f)
|
||||
return ((raw.toFloat() - black) / range).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun normalizedRawAt(
|
||||
rawData: ByteBuffer,
|
||||
rowStride: Int,
|
||||
metadata: RawMetadata,
|
||||
x: Int,
|
||||
y: Int,
|
||||
): Float {
|
||||
val offset = y * rowStride + x * 2
|
||||
val raw = rawData.getShort(offset).toInt() and 0xFFFF
|
||||
val channelIndex = RawCfaCorrection.channelIndexForPixel(metadata.cfaPattern, x, y)
|
||||
val black = metadata.blackLevel.getOrElse(channelIndex) {
|
||||
metadata.blackLevel.firstOrNull() ?: 0f
|
||||
}
|
||||
val range = max(metadata.whiteLevel - black, 1f)
|
||||
return ((raw.toFloat() - black) / range).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun percentileFromSortedSamples(
|
||||
samples: FloatArray,
|
||||
sampleCount: Int,
|
||||
percentile: Float,
|
||||
): Float {
|
||||
if (sampleCount <= 0) return 0f
|
||||
val index = ceil(sampleCount.toFloat() * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceIn(1, sampleCount) - 1
|
||||
return samples[index].takeIf { it.isFinite() && it > 0f } ?: 0f
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,9 @@ internal data class RawExposurePreviewFrame(
|
||||
/**
|
||||
* Capture-side viewfinder matcher.
|
||||
*
|
||||
* The RAW renderer only supplies default-curve preview samples for requested EV values. All
|
||||
* thumbnail analysis, error calculation and iterative exposure solving live here, outside the
|
||||
* normal RAW rendering path.
|
||||
* Thumbnail analysis, error calculation and iterative exposure solving live here. The RAW
|
||||
* renderer supplies default-curve preview samples and prepares the GPU profile map in the same
|
||||
* capture-side GL pass.
|
||||
*/
|
||||
internal object RawViewfinderExposureMatcher {
|
||||
private const val TAG = "RawViewfinderExposureMatcher"
|
||||
@@ -31,49 +31,48 @@ internal object RawViewfinderExposureMatcher {
|
||||
private const val EV_TOLERANCE = 0.05f
|
||||
private const val MIN_STEP_EV = 0.025f
|
||||
|
||||
suspend fun match(
|
||||
suspend fun prepareCaptureProfile(
|
||||
renderer: RawDemosaicProcessor,
|
||||
context: Context,
|
||||
input: RawDngViewfinderMatchInput,
|
||||
input: RawDngCaptureProfileInput,
|
||||
aspectRatio: AspectRatio?,
|
||||
cropRegion: Rect?,
|
||||
rotation: Int,
|
||||
capturePreviewThumbnail: Bitmap,
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
profileToneMapMode: RawProfileToneMapMode,
|
||||
statsBounds: Rect?,
|
||||
rawBlackPointCorrection: Float = 0f,
|
||||
rawWhitePointCorrection: Float = 0f,
|
||||
rawAutoWhiteBalanceEstimate: Boolean = false,
|
||||
applyLensShadingCorrection: Boolean = true,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
): Float? {
|
||||
val reference = buildReference(capturePreviewThumbnail) ?: run {
|
||||
): RawDngCaptureProfileResult? {
|
||||
val reference = capturePreviewThumbnail?.let(::buildReference)
|
||||
if (capturePreviewThumbnail != null && reference == null) {
|
||||
PLog.w(TAG, "Viewfinder match skipped: capture preview is unavailable")
|
||||
return null
|
||||
}
|
||||
val request = RawExposurePreviewRequest(
|
||||
width = reference.width,
|
||||
height = reference.height,
|
||||
solve = { renderSample -> solve(reference, renderSample) },
|
||||
)
|
||||
return renderer.renderExposurePreviewSamples(
|
||||
val request = reference?.let {
|
||||
RawExposurePreviewRequest(
|
||||
width = it.width,
|
||||
height = it.height,
|
||||
solve = { renderSample -> solve(it, renderSample) },
|
||||
)
|
||||
}
|
||||
return renderer.prepareCaptureProfile(
|
||||
context = context,
|
||||
input = input,
|
||||
aspectRatio = aspectRatio,
|
||||
cropRegion = cropRegion,
|
||||
rotation = rotation,
|
||||
request = request,
|
||||
profileToneMapMode = profileToneMapMode,
|
||||
statsBounds = statsBounds,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
|
||||
applyLensShadingCorrection = applyLensShadingCorrection,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
).also { exposureEv ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_VIEWFINDER_BASELINE stage=METERING_COMPLETE curve=DEFAULT " +
|
||||
"pgtm=false sourceBaselineEv=${input.metadata.baselineExposure} " +
|
||||
"meteredExposureOffsetEv=$exposureEv"
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private data class Reference(
|
||||
|
||||
@@ -17,7 +17,6 @@ import com.hinnka.mycamera.raw.RawCfaCorrection
|
||||
import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawProfileGainTableMapBuilder
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
|
||||
import java.io.File
|
||||
@@ -406,8 +405,8 @@ object RawProcessor {
|
||||
baselineExposure = sourceBaselineExposureEv,
|
||||
defaultCrop = defaultCrop,
|
||||
)
|
||||
val exposureOffsetEv = options.viewfinderExposureMatcher?.match(
|
||||
com.hinnka.mycamera.raw.RawDngViewfinderMatchInput(
|
||||
val captureProfile = options.captureProfilePreparer?.prepare(
|
||||
com.hinnka.mycamera.raw.RawDngCaptureProfileInput(
|
||||
rawData = rawBuffer.duplicate().order(ByteOrder.nativeOrder()),
|
||||
width = width,
|
||||
height = height,
|
||||
@@ -415,7 +414,9 @@ object RawProcessor {
|
||||
samplesPerPixel = inputSamplesPerPixel,
|
||||
metadata = statsMetadata.copy(profileGainTableMap = null),
|
||||
)
|
||||
)?.takeIf { it.isFinite() }
|
||||
)
|
||||
val exposureOffsetEv = captureProfile?.exposureOffsetEv
|
||||
?.takeIf { it.isFinite() }
|
||||
?.coerceIn(
|
||||
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MIN_EV,
|
||||
com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MAX_EV,
|
||||
@@ -423,19 +424,24 @@ object RawProcessor {
|
||||
val finalBaselineExposureEv = DngBaselineExposure.sanitize(
|
||||
sourceBaselineExposureEv + (exposureOffsetEv ?: 0f)
|
||||
)
|
||||
val finalProfile = RawProfileGainTableMapBuilder.prepareForDngWrite(
|
||||
rawData = rawBuffer,
|
||||
width = width,
|
||||
height = height,
|
||||
rowStride = inputRowStrideBytes,
|
||||
metadata = statsMetadata.copy(baselineExposure = finalBaselineExposureEv),
|
||||
samplesPerPixel = inputSamplesPerPixel,
|
||||
options = options,
|
||||
) ?: return false
|
||||
val profileRequired = options.profileToneMapMode == RawProfileToneMapMode.Photon ||
|
||||
options.profileToneMapMode == RawProfileToneMapMode.GooglePixel
|
||||
if (profileRequired && captureProfile?.profileGainTableMap == null) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"GPU RAW profile preparation failed: mode=${options.profileToneMapMode} " +
|
||||
"size=${width}x$height samplesPerPixel=$inputSamplesPerPixel"
|
||||
)
|
||||
return false
|
||||
}
|
||||
val finalProfile = com.hinnka.mycamera.raw.RawDngProfilePreparation(
|
||||
baselineExposureEv = finalBaselineExposureEv,
|
||||
profileGainTableMap = captureProfile?.profileGainTableMap,
|
||||
)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_VIEWFINDER_BASELINE stage=DNG_WRITE_READY " +
|
||||
"enabled=${options.viewfinderExposureMatcher != null} " +
|
||||
"enabled=${options.captureProfilePreparer != null} " +
|
||||
"matched=${exposureOffsetEv != null} " +
|
||||
"sourceBaselineEv=$sourceBaselineExposureEv " +
|
||||
"sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " +
|
||||
@@ -444,7 +450,7 @@ object RawProcessor {
|
||||
"writtenBaselineEv=${finalProfile.baselineExposureEv} " +
|
||||
"writtenBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " +
|
||||
"pgtm=${finalProfile.profileGainTableMap != null} " +
|
||||
"mode=${options.profileToneMapMode} statsBounds=${options.statsBounds}"
|
||||
"pgtmSource=GPU mode=${options.profileToneMapMode} statsBounds=${options.statsBounds}"
|
||||
)
|
||||
finalProfile
|
||||
}
|
||||
|
||||
@@ -1,505 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.sqrt
|
||||
|
||||
class DngHdrProfileGainTableGeneratorTest {
|
||||
@Test
|
||||
fun bimodalPhotonCaptureKeepsAUsableBrightSyntheticExposure() {
|
||||
val fixture = loadFixture(BIMODAL_CAPTURE_RESOURCE)
|
||||
val map = generateMap(
|
||||
fixture = fixture,
|
||||
fusionParameters = DngHdrProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS,
|
||||
)
|
||||
val blackGains = actualAnchorGains(fixture, map, ToneAnchor.BLACK)
|
||||
val medianGains = actualAnchorGains(fixture, map, ToneAnchor.MEDIAN)
|
||||
val medianOutputs = FloatArray(fixture.cellCount) { cell ->
|
||||
val p50 = sceneSignalForAnchor(
|
||||
fixture = fixture,
|
||||
cell = cell,
|
||||
anchor = ToneAnchor.MEDIAN,
|
||||
inputScale = map.mapInputWeights.sum()
|
||||
)
|
||||
p50 * medianGains[cell]
|
||||
}
|
||||
val blackGainMedian = percentile(blackGains, 0.50f)
|
||||
val medianOutputMean = medianOutputs.average().toFloat()
|
||||
assertTrue(
|
||||
"inputScale=${map.mapInputWeights.sum()}",
|
||||
map.mapInputWeights.sum() in 0.095f..0.120f
|
||||
)
|
||||
assertTrue("blackGainMedian=$blackGainMedian", blackGainMedian > 1.0f)
|
||||
assertTrue(
|
||||
"medianOutputMean=$medianOutputMean blackGainMedian=$blackGainMedian",
|
||||
medianOutputMean > 0.18f
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skyykingFixturesCoverRealBlackMedianHighlightAndWhiteCases() {
|
||||
val fixtures = loadFixtures()
|
||||
assertEquals(12, fixtures.size)
|
||||
|
||||
val inputScales = fixtures.map { it.inputScale }
|
||||
val globalMedians = fixtures.map { fixture ->
|
||||
percentile(cellStats(fixture, STAT_P50), 0.50f)
|
||||
}
|
||||
val blackGains = fixtures.flatMap { fixture ->
|
||||
anchorGains(fixture.expectedGains, fixture.cellCount, ToneAnchor.BLACK).asIterable()
|
||||
}
|
||||
|
||||
assertTrue("inputScales=$inputScales", inputScales.min() < 0.07f)
|
||||
assertTrue("inputScales=$inputScales", inputScales.max() > 0.33f)
|
||||
assertTrue("globalMedians=$globalMedians", globalMedians.min() < 0.10f)
|
||||
assertTrue("globalMedians=$globalMedians", globalMedians.max() > 0.80f)
|
||||
assertTrue("blackGainMin=${blackGains.min()}", blackGains.min() < 0.30f)
|
||||
assertTrue("blackGainMax=${blackGains.max()}", blackGains.max() > 4.50f)
|
||||
|
||||
fixtures.forEach { fixture ->
|
||||
assertEquals(64, fixture.mapPointsH)
|
||||
assertEquals(48, fixture.mapPointsV)
|
||||
assertEquals(ToneAnchor.entries.size, fixture.anchorCount)
|
||||
assertEquals(fixture.cellCount * CELL_STATS_STRIDE, fixture.packedStats.size)
|
||||
assertEquals(fixture.cellCount * fixture.anchorCount, fixture.expectedGains.size)
|
||||
assertEquals(1f, fixture.gamma, 0f)
|
||||
assertOfficialInputWeights(fixture.inputWeights, fixture.sourceName)
|
||||
assertEmbeddedSemanticOutputsMonotonic(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun official184953TrustedHighlightTailStaysNearWhite() {
|
||||
val fixture = loadFixture(
|
||||
"/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture"
|
||||
)
|
||||
val map = generateMap(fixture)
|
||||
val expectedSpecular = anchorGains(
|
||||
source = fixture.expectedGains,
|
||||
cellCount = fixture.cellCount,
|
||||
anchor = ToneAnchor.SPECULAR
|
||||
)
|
||||
val actualSpecular = actualAnchorGains(fixture, map, ToneAnchor.SPECULAR)
|
||||
val trustedShoulderCells = actualSpecular.indices.filter { cell ->
|
||||
fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999] in 2f..3f
|
||||
}
|
||||
|
||||
assertTrue("Expected trusted shoulder cells", trustedShoulderCells.isNotEmpty())
|
||||
trustedShoulderCells.forEach { cell ->
|
||||
val p999 = fixture.packedStats[cell * CELL_STATS_STRIDE + STAT_P999]
|
||||
val expectedOutput = p999 * expectedSpecular[cell]
|
||||
val actualOutput = p999 * actualSpecular[cell]
|
||||
assertTrue(
|
||||
"cell=$cell p999=$p999 expectedOutput=$expectedOutput actualOutput=$actualOutput",
|
||||
actualOutput + 0.025f >= expectedOutput
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fixedFusionPreservesOfficialShouldersAcrossSkyykingSet() {
|
||||
val fixturesByName = loadFixtures().associateBy { it.sourceName }
|
||||
val results = denseShoulderCases().flatMap { case ->
|
||||
val fixture = fixturesByName[case.name] ?: error("Missing fixture ${case.name}")
|
||||
val map = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = fixture.width,
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = fixture.packedStats,
|
||||
fusionParameters = DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS,
|
||||
) ?: error("Expected Google PGTM for ${case.name}")
|
||||
listOf(0.25f, 0.50f, 0.75f).mapIndexed { index, tableInput ->
|
||||
val actual = percentile(
|
||||
FloatArray(fixture.cellCount) { cell -> sampleGain(map, tableInput, cell) },
|
||||
0.50f,
|
||||
)
|
||||
DenseShoulderResult(
|
||||
name = case.name,
|
||||
tableInput = tableInput,
|
||||
expectedGain = case.officialMedianGains[index],
|
||||
actualGain = actual,
|
||||
errorEv = abs(log2(actual / case.officialMedianGains[index])),
|
||||
)
|
||||
}
|
||||
}
|
||||
assertTrue(
|
||||
results.joinToString("\n") { result ->
|
||||
"${result.name} t=${result.tableInput} expected=${result.expectedGain} " +
|
||||
"actual=${result.actualGain} errorEv=${result.errorEv}"
|
||||
},
|
||||
results.all { it.errorEv <= 0.38f },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun generatedMapsMatchEmbeddedSemanticToneDistributions() {
|
||||
val failures = mutableListOf<String>()
|
||||
loadFixtures().forEach { fixture ->
|
||||
val map = generateMap(fixture)
|
||||
assertTrue("${fixture.sourceName} invalid map", map.isValid)
|
||||
assertMapOutputsMonotonic(map, fixture.sourceName)
|
||||
assertOfficialInputWeights(map.mapInputWeights, fixture.sourceName)
|
||||
|
||||
val scaleError = relativeError(map.mapInputWeights.sum(), fixture.inputScale)
|
||||
if (scaleError > MAX_INPUT_SCALE_RELATIVE_ERROR) {
|
||||
failures += "${fixture.sourceName} inputScale expected=${fixture.inputScale} " +
|
||||
"actual=${map.mapInputWeights.sum()} relativeError=$scaleError"
|
||||
}
|
||||
|
||||
ToneAnchor.entries.forEach { anchor ->
|
||||
val expected = anchorGains(
|
||||
source = fixture.expectedGains,
|
||||
cellCount = fixture.cellCount,
|
||||
anchor = anchor
|
||||
)
|
||||
val actual = actualAnchorGains(fixture, map, anchor)
|
||||
DISTRIBUTION_PERCENTILES.forEach { percentile ->
|
||||
val expectedGain = percentile(expected, percentile)
|
||||
val actualGain = percentile(actual, percentile)
|
||||
val errorEv = gainErrorEv(actualGain, expectedGain)
|
||||
val tolerance = when (percentile) {
|
||||
0.50f -> MAX_MEDIAN_GAIN_ERROR_EV
|
||||
else -> MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV
|
||||
}
|
||||
if (errorEv > tolerance) {
|
||||
failures += "${fixture.sourceName} ${anchor.label} " +
|
||||
"p${(percentile * 100).toInt()} expected=$expectedGain " +
|
||||
"actual=$actualGain errorEv=$errorEv toleranceEv=$tolerance"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun generatedMapsMatchEmbeddedPerCellToneShape() {
|
||||
val failures = mutableListOf<String>()
|
||||
loadFixtures().forEach { fixture ->
|
||||
val map = generateMap(fixture)
|
||||
ToneAnchor.entries
|
||||
.filterNot { it == ToneAnchor.ENDPOINT }
|
||||
.forEach { anchor ->
|
||||
val expected = anchorGains(
|
||||
source = fixture.expectedGains,
|
||||
cellCount = fixture.cellCount,
|
||||
anchor = anchor
|
||||
)
|
||||
val actual = actualAnchorGains(fixture, map, anchor)
|
||||
val rmseEv = logGainRmseEv(actual, expected)
|
||||
if (rmseEv > MAX_PER_CELL_GAIN_RMSE_EV) {
|
||||
failures += "${fixture.sourceName} ${anchor.label} " +
|
||||
"perCellRmseEv=$rmseEv toleranceEv=$MAX_PER_CELL_GAIN_RMSE_EV"
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(failures.joinToString(separator = "\n"), failures.isEmpty())
|
||||
}
|
||||
|
||||
private fun generateMap(
|
||||
fixture: PgtmFixture,
|
||||
fusionParameters: HdrExposureFusionParameters =
|
||||
DngHdrProfileGainTableGenerator.GOOGLE_FUSION_PARAMETERS,
|
||||
): DngProfileGainTableMap {
|
||||
return DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = fixture.width,
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = fixture.packedStats,
|
||||
fusionParameters = fusionParameters,
|
||||
) ?: error("Expected PGTM for ${fixture.sourceName}")
|
||||
}
|
||||
|
||||
private fun actualAnchorGains(
|
||||
fixture: PgtmFixture,
|
||||
map: DngProfileGainTableMap,
|
||||
anchor: ToneAnchor,
|
||||
): FloatArray {
|
||||
val inputScale = map.mapInputWeights.sum()
|
||||
return FloatArray(fixture.cellCount) { cell ->
|
||||
val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, inputScale)
|
||||
val tableInput = if (anchor == ToneAnchor.ENDPOINT) 1f else sceneSignal * inputScale
|
||||
sampleGain(map, tableInput, cell)
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertEmbeddedSemanticOutputsMonotonic(fixture: PgtmFixture) {
|
||||
for (cell in 0 until fixture.cellCount) {
|
||||
var previousOutput = 0f
|
||||
ToneAnchor.entries.forEach { anchor ->
|
||||
val sceneSignal = sceneSignalForAnchor(fixture, cell, anchor, fixture.inputScale)
|
||||
val gain = fixture.expectedGains[cell * fixture.anchorCount + anchor.ordinal]
|
||||
val tableInput = if (anchor == ToneAnchor.ENDPOINT) {
|
||||
1f
|
||||
} else {
|
||||
(sceneSignal * fixture.inputScale).coerceIn(0f, 1f)
|
||||
}
|
||||
val output = tableInput * gain
|
||||
assertTrue(
|
||||
"${fixture.sourceName} cell=$cell anchor=${anchor.label} output=$output previous=$previousOutput",
|
||||
output + OUTPUT_EPS >= previousOutput
|
||||
)
|
||||
previousOutput = max(previousOutput, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertMapOutputsMonotonic(map: DngProfileGainTableMap, sourceName: String) {
|
||||
for (cell in 0 until map.mapPointsH * map.mapPointsV) {
|
||||
var previousOutput = 0f
|
||||
for (index in 0 until map.mapPointsN) {
|
||||
val input = tableInputForIndex(index, map.mapPointsN)
|
||||
val output = input * map.gains[cell * map.mapPointsN + index]
|
||||
assertTrue(
|
||||
"$sourceName cell=$cell index=$index output=$output previous=$previousOutput",
|
||||
output + OUTPUT_EPS >= previousOutput
|
||||
)
|
||||
previousOutput = max(previousOutput, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sceneSignalForAnchor(
|
||||
fixture: PgtmFixture,
|
||||
cell: Int,
|
||||
anchor: ToneAnchor,
|
||||
inputScale: Float,
|
||||
): Float {
|
||||
val offset = cell * CELL_STATS_STRIDE
|
||||
val p10 = fixture.packedStats[offset + STAT_P10].coerceIn(0f, 1f)
|
||||
val p50 = max(p10, fixture.packedStats[offset + STAT_P50].coerceIn(0f, 1f))
|
||||
val p90 = max(p50, fixture.packedStats[offset + STAT_P90].coerceIn(0f, 1f))
|
||||
val p98 = max(p90, fixture.packedStats[offset + STAT_P98].coerceIn(0f, 1f))
|
||||
val p995 = max(p98, fixture.packedStats[offset + STAT_P995].takeIf { it > 0f } ?: p98)
|
||||
val p999 = max(p995, fixture.packedStats[offset + STAT_P999].takeIf { it > 0f } ?: p995)
|
||||
return when (anchor) {
|
||||
ToneAnchor.BLACK -> 0f
|
||||
ToneAnchor.SHADOW -> p10
|
||||
ToneAnchor.DARK -> 0.5f * (p10 + p50)
|
||||
ToneAnchor.MEDIAN -> p50
|
||||
ToneAnchor.BRIGHT -> p90
|
||||
ToneAnchor.HIGHLIGHT -> p98
|
||||
ToneAnchor.WHITE -> p995
|
||||
ToneAnchor.SPECULAR -> p999
|
||||
ToneAnchor.ENDPOINT -> 1f / inputScale.coerceAtLeast(1e-6f)
|
||||
}
|
||||
}
|
||||
|
||||
private fun anchorGains(
|
||||
source: FloatArray,
|
||||
cellCount: Int,
|
||||
anchor: ToneAnchor,
|
||||
): FloatArray {
|
||||
return FloatArray(cellCount) { cell ->
|
||||
source[cell * ToneAnchor.entries.size + anchor.ordinal]
|
||||
}
|
||||
}
|
||||
|
||||
private fun cellStats(fixture: PgtmFixture, stat: Int): FloatArray {
|
||||
return FloatArray(fixture.cellCount) { cell ->
|
||||
fixture.packedStats[cell * CELL_STATS_STRIDE + stat]
|
||||
}
|
||||
}
|
||||
|
||||
private fun sampleGain(map: DngProfileGainTableMap, input: Float, cell: Int): Float {
|
||||
val scaled = input.coerceIn(0f, 1f) * map.mapPointsN.coerceAtLeast(1)
|
||||
val index0 = scaled.toInt().coerceIn(0, map.mapPointsN - 1)
|
||||
val index1 = (index0 + 1).coerceIn(0, map.mapPointsN - 1)
|
||||
val fraction = scaled - index0
|
||||
val offset = cell.coerceIn(0, map.mapPointsH * map.mapPointsV - 1) * map.mapPointsN
|
||||
return map.gains[offset + index0] * (1f - fraction) +
|
||||
map.gains[offset + index1] * fraction
|
||||
}
|
||||
|
||||
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
|
||||
if (pointCount <= 1) return 0f
|
||||
return if (index == pointCount - 1) 1f else index.toFloat() / pointCount.toFloat()
|
||||
}
|
||||
|
||||
private fun assertOfficialInputWeights(weights: FloatArray, sourceName: String) {
|
||||
val sum = weights.sum()
|
||||
assertTrue("$sourceName invalid weight sum=$sum", sum.isFinite() && sum > 0f)
|
||||
OFFICIAL_INPUT_WEIGHTS.forEachIndexed { index, expected ->
|
||||
assertEquals("$sourceName weight[$index]", expected, weights[index] / sum, 0.0001f)
|
||||
}
|
||||
}
|
||||
|
||||
private fun percentile(values: FloatArray, percentile: Float): Float {
|
||||
if (values.isEmpty()) return 0f
|
||||
val sorted = values.copyOf().also { it.sort() }
|
||||
val rank = (sorted.size - 1).toFloat() * percentile.coerceIn(0f, 1f)
|
||||
val lower = floor(rank).toInt()
|
||||
val upper = ceil(rank).toInt()
|
||||
if (lower == upper) return sorted[lower]
|
||||
return sorted[lower] * (upper - rank) + sorted[upper] * (rank - lower)
|
||||
}
|
||||
|
||||
private fun relativeError(actual: Float, expected: Float): Float {
|
||||
return abs(actual - expected) / max(abs(expected), 1e-6f)
|
||||
}
|
||||
|
||||
private fun gainErrorEv(actual: Float, expected: Float): Float {
|
||||
return abs(log2(actual.coerceAtLeast(1e-6f) / expected.coerceAtLeast(1e-6f)))
|
||||
}
|
||||
|
||||
private fun logGainRmseEv(actual: FloatArray, expected: FloatArray): Float {
|
||||
require(actual.size == expected.size)
|
||||
val meanSquare = actual.indices.sumOf { index ->
|
||||
val error = log2(
|
||||
actual[index].coerceAtLeast(1e-6f) /
|
||||
expected[index].coerceAtLeast(1e-6f)
|
||||
)
|
||||
(error * error).toDouble()
|
||||
} / actual.size.coerceAtLeast(1).toDouble()
|
||||
return sqrt(meanSquare).toFloat()
|
||||
}
|
||||
|
||||
private fun log2(value: Float): Float {
|
||||
return (ln(value.coerceAtLeast(1e-6f).toDouble()) / ln(2.0)).toFloat()
|
||||
}
|
||||
|
||||
private fun denseShoulderCases(): List<DenseShoulderCase> = listOf(
|
||||
denseShoulderCase("Skyyking_20260711_184627.RAW-02.ORIGINAL", 0.331765622f, 0.205544580f, 0.152909992f),
|
||||
denseShoulderCase("Skyyking_20260711_184751.RAW-02.ORIGINAL", 0.462672237f, 0.337412789f, 0.272237092f),
|
||||
denseShoulderCase("Skyyking_20260711_184953.RAW-02.ORIGINAL", 0.915177912f, 0.544002324f, 0.395905923f),
|
||||
denseShoulderCase("Skyyking_20260711_185653.RAW-02.ORIGINAL", 0.213499438f, 0.181819726f, 0.162513237f),
|
||||
denseShoulderCase("Skyyking_20260711_185704.RAW-02.ORIGINAL", 0.163654307f, 0.101506390f, 0.075539880f),
|
||||
denseShoulderCase("Skyyking_20260711_185836.RAW-02.ORIGINAL", 0.522830814f, 0.433588199f, 0.374911249f),
|
||||
denseShoulderCase("Skyyking_20260712_105529.RAW-02.ORIGINAL", 0.332546350f, 0.203987684f, 0.150961947f),
|
||||
denseShoulderCase("Skyyking_20260713_232945.RAW-02.ORIGINAL", 0.504472025f, 0.425721936f, 0.372749154f),
|
||||
denseShoulderCase("Skyyking_20260714_083737.RAW-02.ORIGINAL", 0.735527232f, 0.438027993f, 0.319880389f),
|
||||
denseShoulderCase("Skyyking_20260714_092416.RAW-02.ORIGINAL", 0.243842043f, 0.142250773f, 0.102864855f),
|
||||
denseShoulderCase("Skyyking_20260714_123251.RAW-02.ORIGINAL", 0.259386316f, 0.154736947f, 0.113109255f),
|
||||
denseShoulderCase("Skyyking_20260714_151021.RAW-02.ORIGINAL", 0.411366213f, 0.272355564f, 0.209032677f),
|
||||
)
|
||||
|
||||
private fun denseShoulderCase(
|
||||
name: String,
|
||||
gain25: Float,
|
||||
gain50: Float,
|
||||
gain75: Float,
|
||||
) = DenseShoulderCase(name, floatArrayOf(gain25, gain50, gain75))
|
||||
|
||||
private fun loadFixtures(): List<PgtmFixture> = FIXTURE_RESOURCES.map(::loadFixture)
|
||||
|
||||
private fun loadFixture(resourceName: String): PgtmFixture {
|
||||
val bytes = requireNotNull(javaClass.getResourceAsStream(resourceName)) {
|
||||
"Missing PGTM fixture $resourceName"
|
||||
}.use { it.readBytes() }
|
||||
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
|
||||
val magic = ByteArray(FIXTURE_MAGIC.size).also(buffer::get)
|
||||
require(magic.contentEquals(FIXTURE_MAGIC)) { "Invalid PGTM fixture $resourceName" }
|
||||
val width = buffer.int
|
||||
val height = buffer.int
|
||||
val baselineExposureEv = buffer.float
|
||||
val mapPointsH = buffer.int
|
||||
val mapPointsV = buffer.int
|
||||
val anchorCount = buffer.int
|
||||
val statCount = buffer.int
|
||||
val gainCount = buffer.int
|
||||
val weights = FloatArray(5) { buffer.float }
|
||||
val gamma = buffer.float
|
||||
val packedStats = FloatArray(statCount) { buffer.float }
|
||||
val expectedGains = FloatArray(gainCount) { buffer.float }
|
||||
require(!buffer.hasRemaining()) { "Unexpected trailing data in $resourceName" }
|
||||
return PgtmFixture(
|
||||
sourceName = resourceName.substringAfterLast('/').substringBefore(".pgtfixture"),
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
mapPointsH = mapPointsH,
|
||||
mapPointsV = mapPointsV,
|
||||
anchorCount = anchorCount,
|
||||
inputWeights = weights,
|
||||
gamma = gamma,
|
||||
packedStats = packedStats,
|
||||
expectedGains = expectedGains
|
||||
)
|
||||
}
|
||||
|
||||
private enum class ToneAnchor(val label: String) {
|
||||
BLACK("black"),
|
||||
SHADOW("shadow-p10"),
|
||||
DARK("dark-p10-p50"),
|
||||
MEDIAN("median-p50"),
|
||||
BRIGHT("bright-p90"),
|
||||
HIGHLIGHT("highlight-p98"),
|
||||
WHITE("white-p995"),
|
||||
SPECULAR("specular-p999"),
|
||||
ENDPOINT("table-endpoint"),
|
||||
}
|
||||
|
||||
private data class PgtmFixture(
|
||||
val sourceName: String,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val baselineExposureEv: Float,
|
||||
val mapPointsH: Int,
|
||||
val mapPointsV: Int,
|
||||
val anchorCount: Int,
|
||||
val inputWeights: FloatArray,
|
||||
val gamma: Float,
|
||||
val packedStats: FloatArray,
|
||||
val expectedGains: FloatArray,
|
||||
) {
|
||||
val cellCount: Int get() = mapPointsH * mapPointsV
|
||||
val inputScale: Float get() = inputWeights.sum()
|
||||
}
|
||||
|
||||
private data class DenseShoulderCase(
|
||||
val name: String,
|
||||
val officialMedianGains: FloatArray,
|
||||
)
|
||||
|
||||
private data class DenseShoulderResult(
|
||||
val name: String,
|
||||
val tableInput: Float,
|
||||
val expectedGain: Float,
|
||||
val actualGain: Float,
|
||||
val errorEv: Float,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
private const val CELL_STATS_STRIDE = 8
|
||||
private const val STAT_P10 = 0
|
||||
private const val STAT_P50 = 1
|
||||
private const val STAT_P90 = 2
|
||||
private const val STAT_P98 = 3
|
||||
private const val STAT_P995 = 6
|
||||
private const val STAT_P999 = 7
|
||||
private const val OUTPUT_EPS = 0.0001f
|
||||
private const val MAX_INPUT_SCALE_RELATIVE_ERROR = 0.12f
|
||||
private const val MAX_MEDIAN_GAIN_ERROR_EV = 0.22f
|
||||
private const val MAX_SPATIAL_QUANTILE_GAIN_ERROR_EV = 0.38f
|
||||
private const val MAX_PER_CELL_GAIN_RMSE_EV = 0.48f
|
||||
private val FIXTURE_MAGIC = "PGTFIX2\u0000".toByteArray(Charsets.US_ASCII)
|
||||
private const val BIMODAL_CAPTURE_RESOURCE =
|
||||
"/pgtm/captures/PhotonCamera_20260715_173013.pgtfixture"
|
||||
private val DISTRIBUTION_PERCENTILES =
|
||||
floatArrayOf(0.10f, 0.25f, 0.50f, 0.75f, 0.90f, 0.98f)
|
||||
private val OFFICIAL_INPUT_WEIGHTS = floatArrayOf(0.1495f, 0.2935f, 0.0570f, 0.1250f, 0.3750f)
|
||||
private val FIXTURE_RESOURCES = listOf(
|
||||
"/pgtm/skyyking/Skyyking_20260711_184627.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260711_184751.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260711_184953.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260711_185653.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260711_185704.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260711_185836.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260712_105529.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260713_232945.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260714_083737.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260714_092416.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260714_123251.RAW-02.ORIGINAL.pgtfixture",
|
||||
"/pgtm/skyyking/Skyyking_20260714_151021.RAW-02.ORIGINAL.pgtfixture",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
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
|
||||
|
||||
class DngPgtmGlobalStatsTest {
|
||||
@Test
|
||||
fun computesPercentilesFromSingleSamplePopulation() {
|
||||
val samples = FloatArray(1_000) { index -> (index + 1).toFloat() / 1_000f }
|
||||
|
||||
val stats = DngPgtmGlobalStats.fromMutableSamples(samples, samples.size)
|
||||
|
||||
assertNotNull(stats)
|
||||
stats ?: return
|
||||
assertEquals(0.100f, stats.p10, 1e-6f)
|
||||
assertEquals(0.500f, stats.p50, 1e-6f)
|
||||
assertEquals(0.900f, stats.p90, 1e-6f)
|
||||
assertEquals(0.980f, stats.p98, 1e-6f)
|
||||
assertEquals(0.995f, stats.p995, 1e-6f)
|
||||
assertEquals(0.999f, stats.p999, 1e-6f)
|
||||
assertEquals(1.000f, stats.maxInput, 1e-6f)
|
||||
assertEquals(0.081f, stats.highlightFraction, 1e-6f)
|
||||
assertEquals(0.5005f, stats.linearMean, 1e-6f)
|
||||
val expectedLogAverage = exp(
|
||||
(1..1_000).sumOf { value -> ln(value.toDouble() / 1_000.0) } / 1_000.0
|
||||
).toFloat()
|
||||
assertEquals(expectedLogAverage, stats.logAverage, 1e-6f)
|
||||
assertTrue("shadowEdge=${stats.shadowEdge}", stats.shadowEdge > 0f)
|
||||
assertTrue(
|
||||
"shadowFoot=${stats.shadowFoot} shadowEdge=${stats.shadowEdge}",
|
||||
stats.shadowFoot in 0f..stats.shadowEdge
|
||||
)
|
||||
assertEquals(1_000, stats.sampleCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shadowSlopeFootIgnoresMovementInsideSparseDarkTail() {
|
||||
fun samples(tailStartEv: Float): FloatArray {
|
||||
return FloatArray(1_000) { index ->
|
||||
val ev = if (index < 150) {
|
||||
tailStartEv + 3f * index.toFloat() / 149f
|
||||
} else {
|
||||
-4f + 3f * (index - 150).toFloat() / 849f
|
||||
}
|
||||
2.0f.pow(ev)
|
||||
}
|
||||
}
|
||||
|
||||
val first = DngPgtmGlobalStats.fromMutableSamples(samples(-9f), 1_000)
|
||||
?: error("Expected first stats")
|
||||
val second = DngPgtmGlobalStats.fromMutableSamples(samples(-10f), 1_000)
|
||||
?: error("Expected second stats")
|
||||
val p10DeltaEv = kotlin.math.abs(log2(second.p10 / first.p10))
|
||||
val footDeltaEv = kotlin.math.abs(log2(second.shadowFoot / first.shadowFoot))
|
||||
|
||||
assertTrue("p10DeltaEv=$p10DeltaEv", p10DeltaEv > 0.8f)
|
||||
assertTrue(
|
||||
"firstFoot=${first.shadowFoot} secondFoot=${second.shadowFoot} " +
|
||||
"footDeltaEv=$footDeltaEv",
|
||||
footDeltaEv < 0.2f
|
||||
)
|
||||
}
|
||||
|
||||
@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 {
|
||||
// HDR stacker uses 1024 bins; the single-frame RAW path uses 2048.
|
||||
// Validate against the lower-resolution layout as the stricter case.
|
||||
private const val GPU_HISTOGRAM_BIN_COUNT = 1024
|
||||
private const val GPU_HISTOGRAM_MIN_EV = -16f
|
||||
private const val GPU_HISTOGRAM_MAX_EV = 8f
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class DngSdkProfileRgbTransformTest {
|
||||
@Test
|
||||
fun cameraWhiteAndRimmClampMatchBaselineAbcToRgbOrder() {
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.9f,
|
||||
green = 0.9f,
|
||||
blue = 0.9f,
|
||||
colorCorrectionMatrix = floatArrayOf(
|
||||
3f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 2f,
|
||||
),
|
||||
cameraWhite = floatArrayOf(0.5f, 1f, 0.75f),
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(1f, 0.9f, 1f), rgb, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun neutralOverrangeIsClampedBeforeCompressivePgtmGain() {
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 1f,
|
||||
green = 1f,
|
||||
blue = 1f,
|
||||
colorCorrectionMatrix = floatArrayOf(
|
||||
1.35f, 0f, 0f,
|
||||
0f, 0.96f, 0f,
|
||||
0f, 0f, 1.28f,
|
||||
),
|
||||
)
|
||||
val gain = 0.45f
|
||||
val output = FloatArray(3) { index -> rgb[index] * gain }
|
||||
|
||||
assertArrayEquals(floatArrayOf(0.45f, 0.432f, 0.45f), output, 1e-6f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun identityHueSatMapKeepsProfileRgbUnchanged() {
|
||||
val identityMap = DcpHueSatMap(
|
||||
hueDivisions = 1,
|
||||
satDivisions = 1,
|
||||
valueDivisions = 1,
|
||||
values = floatArrayOf(0f, 1f, 1f),
|
||||
)
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.72f,
|
||||
green = 0.41f,
|
||||
blue = 0.18f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
hueSatMap = identityMap,
|
||||
)
|
||||
|
||||
assertArrayEquals(floatArrayOf(0.72f, 0.41f, 0.18f), rgb, 1e-5f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun srgbEncodedTwoPointFiveDimensionalMapKeepsValueLinearUntilScale() {
|
||||
val map = DcpHueSatMap(
|
||||
hueDivisions = 1,
|
||||
satDivisions = 1,
|
||||
valueDivisions = 1,
|
||||
values = floatArrayOf(0f, 1f, 0.5f),
|
||||
encoding = DcpHueSatMap.ENCODING_SRGB,
|
||||
)
|
||||
val rgb = DngSdkProfileRgbTransform.fromCameraRgb(
|
||||
red = 0.8f,
|
||||
green = 0.4f,
|
||||
blue = 0.2f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
hueSatMap = map,
|
||||
)
|
||||
val sdkDecodedValue = srgbToLinear(0.4f)
|
||||
|
||||
assertArrayEquals(
|
||||
floatArrayOf(sdkDecodedValue, sdkDecodedValue * 0.5f, sdkDecodedValue * 0.25f),
|
||||
rgb,
|
||||
1e-5f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun baselineExposureScalesOnlyClampedFiveWeightInput() {
|
||||
val input = DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = 2f,
|
||||
green = 3f,
|
||||
blue = 4f,
|
||||
baselineGain = 2f,
|
||||
colorCorrectionMatrix = IDENTITY_MATRIX,
|
||||
)
|
||||
|
||||
assertEquals(2f, input, 1e-6f)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val IDENTITY_MATRIX = floatArrayOf(
|
||||
1f, 0f, 0f,
|
||||
0f, 1f, 0f,
|
||||
0f, 0f, 1f,
|
||||
)
|
||||
|
||||
fun srgbToLinear(value: Float): Float = if (value <= 0.04045f) {
|
||||
value / 12.92f
|
||||
} else {
|
||||
Math.pow(((value + 0.055f) / 1.055f).toDouble(), 2.4).toFloat()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user