Align PGTM generation with DNG RIMM semantics
This commit is contained in:
1 parent
ff054b7d7a
commit
467bcffe23
10 files changed
+1104
-1204
No files matched your search
@@ -34,7 +34,6 @@ import com.hinnka.mycamera.processor.YuvHdrStackFrame
|
||||
import com.hinnka.mycamera.processor.YuvHdrStackFrameRole
|
||||
import com.hinnka.mycamera.raw.DngEmbeddedProfile
|
||||
import com.hinnka.mycamera.raw.DngProfileGainTableMap
|
||||
import com.hinnka.mycamera.raw.DngProfileGainTableMapPatcher
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawHdrLinearFusionProcessor
|
||||
import com.hinnka.mycamera.raw.RawMetadata
|
||||
@@ -82,7 +81,6 @@ import kotlin.use
|
||||
*/
|
||||
object GalleryManager {
|
||||
private const val TAG = "PhotoManager"
|
||||
private const val DEBUG_REWRITE_RAW_PREVIEW_PGTM2 = true
|
||||
private val metadataMutex = Mutex()
|
||||
private const val THUMBNAIL_MAX_EDGE = 512
|
||||
private const val PHOTOS_DIR = "photos"
|
||||
@@ -4375,10 +4373,6 @@ object GalleryManager {
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
|
||||
if (!dngFile.exists()) return@withContext null
|
||||
if (BuildConfig.DEBUG && DEBUG_REWRITE_RAW_PREVIEW_PGTM2) {
|
||||
DngProfileGainTableMapPatcher.rewriteExistingPgtm2WithCurrentGenerator(dngFile)
|
||||
}
|
||||
|
||||
// 2. 读取元数据以获取旋转信息
|
||||
val metadata = loadMetadata(context, photoId)
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ 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.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
@@ -28,6 +29,7 @@ class GlesRawStacker(
|
||||
private val lensShading: FloatArray?,
|
||||
private val lensShadingWidth: Int,
|
||||
private val lensShadingHeight: Int,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
) {
|
||||
private data class TextureLevel(val texture: Int, val width: Int, val height: Int)
|
||||
private data class ReadOutputTiming(
|
||||
@@ -57,6 +59,12 @@ class GlesRawStacker(
|
||||
private val normalizedWhiteLevel = whiteLevel.coerceAtLeast(1).toFloat()
|
||||
private val noiseAlpha = noiseModel.getOrElse(0) { 0f }.coerceAtLeast(0f) / 65535.0f
|
||||
private val noiseBeta = noiseModel.getOrElse(1) { 0f }.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 planeWidth = max(1, width / 2)
|
||||
private val planeHeight = max(1, height / 2)
|
||||
@@ -548,6 +556,13 @@ class GlesRawStacker(
|
||||
GLES31.glGetUniformLocation(pgtmStatsProgram, "uBaselineExposureGain"),
|
||||
2.0f.pow(baselineExposureEv.coerceIn(0f, 8f))
|
||||
)
|
||||
GLES31.glUniformMatrix3fv(
|
||||
GLES31.glGetUniformLocation(pgtmStatsProgram, "uColorCorrectionMatrix"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(pgtmColorCorrectionMatrix),
|
||||
0
|
||||
)
|
||||
GLES31.glDispatchCompute(pgtmGridWidth, pgtmGridHeight, 1)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT
|
||||
@@ -574,7 +589,8 @@ class GlesRawStacker(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = stats
|
||||
packedCellStats = stats,
|
||||
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU stacker")
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to compute GPU HDR PGTM stats", e)
|
||||
@@ -1215,6 +1231,14 @@ class GlesRawStacker(
|
||||
|
||||
private fun groupCount(value: Int): Int = (value + LOCAL_SIZE - 1) / LOCAL_SIZE
|
||||
|
||||
private fun transposeMatrix3x3(matrix: FloatArray): FloatArray {
|
||||
return floatArrayOf(
|
||||
matrix.getOrElse(0) { 1f }, matrix.getOrElse(3) { 0f }, matrix.getOrElse(6) { 0f },
|
||||
matrix.getOrElse(1) { 0f }, matrix.getOrElse(4) { 1f }, matrix.getOrElse(7) { 0f },
|
||||
matrix.getOrElse(2) { 0f }, matrix.getOrElse(5) { 0f }, matrix.getOrElse(8) { 1f }
|
||||
)
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
if (programs.isNotEmpty()) {
|
||||
@@ -2351,6 +2375,7 @@ class GlesRawStacker(
|
||||
uniform ivec2 uGridSize;
|
||||
uniform int uCfaPattern;
|
||||
uniform float uBaselineExposureGain;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
layout(std430, binding = $PGTM_STATS_BUFFER_BINDING) buffer PgtmStats {
|
||||
float stats[];
|
||||
};
|
||||
@@ -2405,9 +2430,17 @@ class GlesRawStacker(
|
||||
|
||||
float pgtmInputAt(ivec2 base) {
|
||||
vec3 rgb = blockRgbAt(base);
|
||||
float luma = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
|
||||
float maxChannel = max(rgb.r, max(rgb.g, rgb.b));
|
||||
return max((0.5 * luma + 0.5 * maxChannel) * uBaselineExposureGain, 0.0);
|
||||
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() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
internal object DngHdrProfileGainTableGenerator {
|
||||
private const val TAG = "DngHdrProfileGainTableGenerator"
|
||||
@@ -28,13 +29,30 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
private const val MIN_EFFECTIVE_INPUT_HEADROOM = 0.28f
|
||||
private const val MAX_EFFECTIVE_INPUT_HEADROOM = 3.05f
|
||||
private const val MIN_SCENE_MAX = 1.02f
|
||||
private const val LOW_KEY_LOCAL_TAIL_SCENE_MAX_FACTOR = 2.75f
|
||||
private const val LOW_KEY_LOCAL_TAIL_HDR_STRENGTH = 0.58f
|
||||
private const val SCENE_TAIL_EXPANSION_FACTOR = 2.75f
|
||||
private const val SCENE_TAIL_HDR_STRENGTH = 0.58f
|
||||
private const val SCENE_TAIL_EXPANSION_STRENGTH_GAIN = 2.10f
|
||||
private const val MAX_GAIN_VALUE = 5.40f
|
||||
private const val MIN_CURVE_INPUT = 1e-6f
|
||||
private const val SCENE_ULTRA_BLACK_ANCHOR = 0.0025f
|
||||
private const val SCENE_BLACK_DETAIL_ANCHOR = 0.005f
|
||||
private const val SCENE_DARK_DETAIL_ANCHOR = 0.0075f
|
||||
private const val SCENE_DEEP_SHADOW_ANCHOR = 0.010f
|
||||
private const val SCENE_DEEP_SHADOW_DETAIL_ANCHOR = 0.015f
|
||||
private const val SCENE_SHADOW_ANCHOR = 0.02f
|
||||
private const val SCENE_SHADOW_DETAIL_ANCHOR = 0.0275f
|
||||
private const val SCENE_LOWER_SHADOW_ANCHOR = 0.035f
|
||||
private const val SCENE_LOWER_LOW_ANCHOR = 0.045f
|
||||
private const val SCENE_LOW_ANCHOR = 0.05f
|
||||
private const val SCENE_LOW_DETAIL_ANCHOR = 0.0575f
|
||||
private const val SCENE_UPPER_SHADOW_ANCHOR = 0.065f
|
||||
private const val SCENE_PRE_TOE_ANCHOR = 0.0725f
|
||||
private const val SCENE_TOE_ANCHOR = 0.08f
|
||||
private const val SCENE_UPPER_TOE_ANCHOR = 0.095f
|
||||
private const val SCENE_TOE_MID_JOIN_ANCHOR = 0.105f
|
||||
private const val SCENE_LOWER_MID_ANCHOR = 0.11f
|
||||
private const val SCENE_MID_ANCHOR = 0.18f
|
||||
private const val SCENE_UPPER_MID_ANCHOR = 0.25f
|
||||
private const val SCENE_HALF_ANCHOR = 0.50f
|
||||
private const val SCENE_WHITE_ANCHOR = 1.0f
|
||||
private const val SCENE_BRIGHT_ANCHOR = 1.5f
|
||||
@@ -42,18 +60,24 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
private const val SCENE_EXTREME_WHITE_ANCHOR = 3.0f
|
||||
private const val MIN_MID_GAIN = 1.40f
|
||||
private const val MAX_MID_GAIN = 2.75f
|
||||
private const val LOW_DETAIL_MID_GAIN_FACTOR = 1.56f
|
||||
private const val MIN_BLACK_GAIN = 1.65f
|
||||
private const val MAX_BLACK_GAIN = 5.40f
|
||||
private const val MIN_TOE_SLOPE = 0.58f
|
||||
private const val MAX_TOE_SLOPE = 0.88f
|
||||
private const val MIN_SHOULDER_POWER = 0.82f
|
||||
private const val MAX_SHOULDER_POWER = 1.28f
|
||||
internal const val BASE_INPUT_WEIGHT_RED = 0.1495f
|
||||
internal const val BASE_INPUT_WEIGHT_GREEN = 0.2935f
|
||||
internal const val BASE_INPUT_WEIGHT_BLUE = 0.0570f
|
||||
internal const val BASE_INPUT_WEIGHT_MIN = 0.1250f
|
||||
internal const val BASE_INPUT_WEIGHT_MAX = 0.3750f
|
||||
private val BASE_INPUT_WEIGHTS = floatArrayOf(
|
||||
0.1495f,
|
||||
0.2935f,
|
||||
0.0570f,
|
||||
0.1250f,
|
||||
0.3750f
|
||||
BASE_INPUT_WEIGHT_RED,
|
||||
BASE_INPUT_WEIGHT_GREEN,
|
||||
BASE_INPUT_WEIGHT_BLUE,
|
||||
BASE_INPUT_WEIGHT_MIN,
|
||||
BASE_INPUT_WEIGHT_MAX
|
||||
)
|
||||
|
||||
fun gridSizeFor(width: Int, height: Int): IntArray {
|
||||
@@ -61,12 +85,58 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
return intArrayOf(grid.mapPointsH, grid.mapPointsV)
|
||||
}
|
||||
|
||||
fun sceneInputFromLinearRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
colorCorrectionMatrix: FloatArray? = null,
|
||||
): Float {
|
||||
val profileRgb = if (colorCorrectionMatrix != null && colorCorrectionMatrix.size >= 9) {
|
||||
floatArrayOf(
|
||||
colorCorrectionMatrix[0] * red + colorCorrectionMatrix[1] * green + colorCorrectionMatrix[2] * blue,
|
||||
colorCorrectionMatrix[3] * red + colorCorrectionMatrix[4] * green + colorCorrectionMatrix[5] * blue,
|
||||
colorCorrectionMatrix[6] * red + colorCorrectionMatrix[7] * green + colorCorrectionMatrix[8] * blue
|
||||
)
|
||||
} else {
|
||||
floatArrayOf(red, green, blue)
|
||||
}
|
||||
return sceneInputFromProfileRgb(
|
||||
red = profileRgb[0],
|
||||
green = profileRgb[1],
|
||||
blue = profileRgb[2],
|
||||
baselineGain = baselineGain
|
||||
)
|
||||
}
|
||||
|
||||
fun sceneInputFromProfileRgb(
|
||||
red: Float,
|
||||
green: Float,
|
||||
blue: Float,
|
||||
baselineGain: Float,
|
||||
): Float {
|
||||
val r = red * baselineGain
|
||||
val g = green * baselineGain
|
||||
val b = blue * 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(
|
||||
width: Int,
|
||||
height: Int,
|
||||
baselineExposureEv: Float,
|
||||
packedCellStats: FloatArray,
|
||||
tablePointCount: Int = DEFAULT_TABLE_POINTS,
|
||||
diagnosticBand: DiagnosticBand? = null,
|
||||
): DngProfileGainTableMap? {
|
||||
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < MIN_BASELINE_EV) {
|
||||
return null
|
||||
@@ -94,31 +164,76 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
val globalStats = weightedGlobalStats(cells)
|
||||
val inputScale = hdrPgtmInputScaleForStats(globalStats, safeBaselineEv)
|
||||
val sceneMax = 1f / sanitizeInputScale(inputScale)
|
||||
val sceneHdrStrength = (max(
|
||||
sceneHdrStrength(inputScale),
|
||||
LOW_KEY_LOCAL_TAIL_HDR_STRENGTH * lowKeyLocalTailStrength(globalStats)
|
||||
) * GCAM_HDR_EFFECT_INTENSITY).coerceIn(0f, 1f)
|
||||
val curveParams = smoothHdrPgtmCurveParams(
|
||||
stats = Array(cellCount) { index ->
|
||||
buildHdrPgtmCurveParams(
|
||||
cell = cells[index] ?: globalStats,
|
||||
global = globalStats,
|
||||
baselineExposureEv = safeBaselineEv,
|
||||
sceneHdrStrength = sceneHdrStrength,
|
||||
sceneMax = sceneMax
|
||||
)
|
||||
},
|
||||
grid = grid
|
||||
val sceneHdrStrength = (sceneHdrStrength(globalStats, inputScale) * GCAM_HDR_EFFECT_INTENSITY)
|
||||
.coerceIn(0f, 1f)
|
||||
val globalCurveParams = buildHdrPgtmCurveParams(
|
||||
global = globalStats,
|
||||
baselineExposureEv = safeBaselineEv,
|
||||
sceneHdrStrength = sceneHdrStrength,
|
||||
sceneMax = sceneMax
|
||||
)
|
||||
val curveParams = Array(cellCount) { globalCurveParams }
|
||||
return buildMap(
|
||||
grid = grid,
|
||||
safeBaselineEv = safeBaselineEv,
|
||||
safePointCount = safePointCount,
|
||||
curveParams = curveParams,
|
||||
inputScale = inputScale
|
||||
inputScale = inputScale,
|
||||
diagnosticBand = diagnosticBand?.sanitized()
|
||||
)
|
||||
}
|
||||
|
||||
data class DiagnosticBand(
|
||||
val start: Float,
|
||||
val end: Float,
|
||||
val feather: Float = 0.02f,
|
||||
val mode: DiagnosticMode = DiagnosticMode.PASS_ONLY,
|
||||
) {
|
||||
internal fun sanitized(): DiagnosticBand? {
|
||||
if (!start.isFinite() || !end.isFinite() || !feather.isFinite()) return null
|
||||
val safeStart = start.coerceIn(0f, 1f)
|
||||
val safeEnd = end.coerceIn(0f, 1f)
|
||||
if (safeEnd <= safeStart) return null
|
||||
return DiagnosticBand(
|
||||
start = safeStart,
|
||||
end = safeEnd,
|
||||
feather = feather.coerceIn(0f, 0.12f),
|
||||
mode = mode
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum class DiagnosticMode {
|
||||
PASS_ONLY,
|
||||
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_GAIN_VALUE)
|
||||
?: MAX_GAIN_VALUE
|
||||
for (cellIndex in 0 until cellCount) {
|
||||
applyDiagnosticBand(
|
||||
output = gains,
|
||||
outputOffset = cellIndex * pointCount,
|
||||
pointCount = pointCount,
|
||||
band = band,
|
||||
maxGainValue = maxGain
|
||||
)
|
||||
}
|
||||
return map.copy(gains = gains)
|
||||
}
|
||||
|
||||
private fun packedStatsAt(stats: FloatArray, offset: Int, sampleWeight: Float): HdrPgtmCellStats {
|
||||
val p10 = safe01(stats[offset])
|
||||
val p50 = max(p10, safe01(stats[offset + 1]))
|
||||
@@ -237,6 +352,7 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
safePointCount: Int,
|
||||
curveParams: Array<HdrPgtmCurveParams>,
|
||||
inputScale: Float,
|
||||
diagnosticBand: DiagnosticBand?,
|
||||
): DngProfileGainTableMap {
|
||||
val safeInputScale = sanitizeInputScale(inputScale)
|
||||
val gains = FloatArray(grid.mapPointsH * grid.mapPointsV * safePointCount)
|
||||
@@ -250,6 +366,14 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
inputScale = safeInputScale,
|
||||
params = curveParams[cellIndex]
|
||||
)
|
||||
diagnosticBand?.let { band ->
|
||||
applyDiagnosticBand(
|
||||
output = gains,
|
||||
outputOffset = cellIndex * safePointCount,
|
||||
pointCount = safePointCount,
|
||||
band = band
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return DngProfileGainTableMap(
|
||||
@@ -267,6 +391,50 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
)
|
||||
}
|
||||
|
||||
private fun applyDiagnosticBand(
|
||||
output: FloatArray,
|
||||
outputOffset: Int,
|
||||
pointCount: Int,
|
||||
band: DiagnosticBand,
|
||||
maxGainValue: Float = MAX_GAIN_VALUE,
|
||||
) {
|
||||
var previousOutput = 0f
|
||||
val safeMaxGain = maxGainValue.takeIf { it.isFinite() && it > 0f }
|
||||
?.coerceAtLeast(1f)
|
||||
?: MAX_GAIN_VALUE
|
||||
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 mixedOutput = input * mixedGain
|
||||
val monotonicOutput = max(previousOutput, mixedOutput)
|
||||
output[outputOffset + index] = if (input <= MIN_CURVE_INPUT) {
|
||||
mixedGain.coerceIn(0.05f, safeMaxGain)
|
||||
} else {
|
||||
(monotonicOutput / input).coerceIn(0.05f, 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 chooseHdrPgtmGrid(width: Int, height: Int): HdrPgtmGrid {
|
||||
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
|
||||
.coerceIn(GRID_MIN_H, GRID_MAX_H)
|
||||
@@ -281,7 +449,6 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
private fun buildHdrPgtmCurveParams(
|
||||
cell: HdrPgtmCellStats,
|
||||
global: HdrPgtmCellStats,
|
||||
baselineExposureEv: Float,
|
||||
sceneHdrStrength: Float,
|
||||
@@ -294,25 +461,14 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
smoothStep(0.35f, 3.2f, baselineExposureEv),
|
||||
0.70f * sceneContrastStrength
|
||||
) * sceneHdrStrength).coerceIn(0f, 1f)
|
||||
val globalMedian = global.p50.coerceIn(0.025f, 0.85f)
|
||||
val cellMedian = cell.p50.coerceIn(0.002f, 1f)
|
||||
val medianEv = log2(cellMedian / globalMedian)
|
||||
val brightRegion = smoothStep(0.25f, 1.7f, medianEv)
|
||||
val darkRegion = smoothStep(0.25f, 2.4f, -medianEv)
|
||||
val highlightPressure = (
|
||||
0.45f * smoothStep(0.48f, 0.88f, cell.p90) +
|
||||
0.35f * smoothStep(0.70f, 0.985f, cell.p98) +
|
||||
0.20f * smoothStep(0.015f, 0.30f, cell.highlightFraction)
|
||||
0.45f * smoothStep(0.48f, 0.88f, global.p90) +
|
||||
0.35f * smoothStep(0.70f, 0.985f, global.p98) +
|
||||
0.20f * smoothStep(0.015f, 0.30f, global.highlightFraction)
|
||||
).coerceIn(0f, 1f) * hdrStrength
|
||||
val combinedPressure = max(
|
||||
highlightPressure,
|
||||
0.60f * brightRegion * hdrStrength
|
||||
).coerceIn(0f, 1f)
|
||||
val rangeCenterEv = hdrRangeCenterOffsetEv(
|
||||
cell = cell,
|
||||
darkRegion = darkRegion,
|
||||
brightRegion = brightRegion,
|
||||
highlightPressure = combinedPressure,
|
||||
global = global,
|
||||
highlightPressure = highlightPressure,
|
||||
hdrStrength = hdrStrength
|
||||
)
|
||||
val baseMidGain = hdrRangeMidGain(baselineExposureEv, sceneHdrStrength)
|
||||
@@ -321,70 +477,27 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
val effectiveUpperRangeEv = log2(sceneMax / SCENE_MID_ANCHOR)
|
||||
.coerceIn(0.01f, GCAM_HDR_UPPER_RANGE_EV - GCAM_HDR_LOWER_RANGE_EV)
|
||||
val shoulderPower = hdrRangeShoulderPower(
|
||||
global = global,
|
||||
effectiveUpperRangeEv = effectiveUpperRangeEv,
|
||||
highlightPressure = combinedPressure,
|
||||
highlightPressure = highlightPressure,
|
||||
hdrStrength = hdrStrength
|
||||
)
|
||||
val toeSlope = hdrRangeToeSlope(sceneHdrStrength, combinedPressure)
|
||||
val toeSlope = hdrRangeToeSlope(sceneHdrStrength, highlightPressure)
|
||||
val blackGain = hdrRangeBlackGain(
|
||||
midGain = midGain,
|
||||
sceneHdrStrength = sceneHdrStrength,
|
||||
rangeCenterEv = rangeCenterEv,
|
||||
highlightPressure = combinedPressure
|
||||
highlightPressure = highlightPressure
|
||||
)
|
||||
return HdrPgtmCurveParams(
|
||||
midOutput = SCENE_MID_ANCHOR * midGain,
|
||||
blackGain = blackGain,
|
||||
blackGain = blackGain.coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN),
|
||||
toeSlope = toeSlope,
|
||||
shoulderPower = shoulderPower,
|
||||
highlightPressure = combinedPressure
|
||||
highlightPressure = highlightPressure
|
||||
)
|
||||
}
|
||||
|
||||
private fun smoothHdrPgtmCurveParams(
|
||||
stats: Array<HdrPgtmCurveParams>,
|
||||
grid: HdrPgtmGrid,
|
||||
): Array<HdrPgtmCurveParams> {
|
||||
var current = stats
|
||||
repeat(2) {
|
||||
val next = Array(current.size) { current[it] }
|
||||
for (y in 0 until grid.mapPointsV) {
|
||||
for (x in 0 until grid.mapPointsH) {
|
||||
var weightSum = 0f
|
||||
var midOutput = 0f
|
||||
var blackGain = 0f
|
||||
var toeSlope = 0f
|
||||
var shoulderPower = 0f
|
||||
var highlightPressure = 0f
|
||||
for (dy in -1..1) {
|
||||
for (dx in -1..1) {
|
||||
val nx = (x + dx).coerceIn(0, grid.mapPointsH - 1)
|
||||
val ny = (y + dy).coerceIn(0, grid.mapPointsV - 1)
|
||||
val weight = if (dx == 0 && dy == 0) 4f else if (dx == 0 || dy == 0) 2f else 1f
|
||||
val value = current[ny * grid.mapPointsH + nx]
|
||||
weightSum += weight
|
||||
midOutput += value.midOutput * weight
|
||||
blackGain += value.blackGain * weight
|
||||
toeSlope += value.toeSlope * weight
|
||||
shoulderPower += value.shoulderPower * weight
|
||||
highlightPressure += value.highlightPressure * weight
|
||||
}
|
||||
}
|
||||
val index = y * grid.mapPointsH + x
|
||||
next[index] = HdrPgtmCurveParams(
|
||||
midOutput = midOutput / weightSum,
|
||||
blackGain = blackGain / weightSum,
|
||||
toeSlope = toeSlope / weightSum,
|
||||
shoulderPower = shoulderPower / weightSum,
|
||||
highlightPressure = highlightPressure / weightSum,
|
||||
)
|
||||
}
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
private fun writeHdrPgtmCurve(
|
||||
output: FloatArray,
|
||||
outputOffset: Int,
|
||||
@@ -394,88 +507,167 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
) {
|
||||
val safeInputScale = sanitizeInputScale(inputScale)
|
||||
val sceneMax = (1f / safeInputScale).coerceAtLeast(SCENE_WHITE_ANCHOR + 1e-3f)
|
||||
val anchors = buildSceneAnchors(params, sceneMax)
|
||||
val curve = buildSceneCurve(params, sceneMax)
|
||||
for (index in 0 until pointCount) {
|
||||
val input = tableInputForIndex(index, pointCount)
|
||||
if (input <= MIN_CURVE_INPUT) {
|
||||
output[outputOffset + index] = params.blackGain
|
||||
output[outputOffset + index] = lowDetailGain(params)
|
||||
continue
|
||||
}
|
||||
val sceneLinear = input / safeInputScale
|
||||
val outputLinear = sampleSceneCurve(anchors, sceneLinear)
|
||||
val outputLinear = sampleSceneCurve(curve, sceneLinear)
|
||||
output[outputOffset + index] = (outputLinear / max(sceneLinear, MIN_CURVE_INPUT))
|
||||
.coerceIn(0.05f, MAX_GAIN_VALUE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSceneCurve(params: HdrPgtmCurveParams, sceneMax: Float): SceneToneCurve {
|
||||
val anchors = buildSceneAnchors(params, sceneMax)
|
||||
val inputs = FloatArray(anchors.size) { anchors[it].first }
|
||||
val outputs = FloatArray(anchors.size) { anchors[it].second }
|
||||
return SceneToneCurve(
|
||||
inputs = inputs,
|
||||
outputs = outputs,
|
||||
tangents = monotoneTangents(inputs, outputs)
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildSceneAnchors(params: HdrPgtmCurveParams, sceneMax: Float): List<Pair<Float, Float>> {
|
||||
val anchors = ArrayList<Pair<Float, Float>>(10)
|
||||
val anchors = ArrayList<Pair<Float, Float>>(24)
|
||||
fun addAnchor(scene: Float, output: Float) {
|
||||
if (!scene.isFinite() || scene <= 0f || scene >= sceneMax) return
|
||||
val previous = anchors.lastOrNull()?.second ?: 0f
|
||||
anchors += scene to output.coerceAtLeast(previous + 1e-5f)
|
||||
anchors += scene to output
|
||||
.coerceAtLeast(previous + 1e-5f)
|
||||
.coerceAtMost(1f - 1e-5f)
|
||||
}
|
||||
anchors += 0f to 0f
|
||||
addAnchor(SCENE_SHADOW_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_SHADOW_ANCHOR))
|
||||
addAnchor(SCENE_LOW_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_LOW_ANCHOR))
|
||||
addAnchor(SCENE_MID_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_MID_ANCHOR))
|
||||
addAnchor(SCENE_HALF_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_HALF_ANCHOR))
|
||||
addAnchor(SCENE_WHITE_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_WHITE_ANCHOR))
|
||||
addAnchor(SCENE_BRIGHT_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_BRIGHT_ANCHOR))
|
||||
addAnchor(SCENE_SUPER_WHITE_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_SUPER_WHITE_ANCHOR))
|
||||
addAnchor(SCENE_EXTREME_WHITE_ANCHOR, sampleHdrRangeCompression(params, sceneMax, SCENE_EXTREME_WHITE_ANCHOR))
|
||||
addAnchor(SCENE_ULTRA_BLACK_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_ULTRA_BLACK_ANCHOR))
|
||||
addAnchor(SCENE_BLACK_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_BLACK_DETAIL_ANCHOR))
|
||||
addAnchor(SCENE_DARK_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DARK_DETAIL_ANCHOR))
|
||||
addAnchor(SCENE_DEEP_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DEEP_SHADOW_ANCHOR))
|
||||
addAnchor(SCENE_DEEP_SHADOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_DEEP_SHADOW_DETAIL_ANCHOR))
|
||||
addAnchor(SCENE_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SHADOW_ANCHOR))
|
||||
addAnchor(SCENE_SHADOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SHADOW_DETAIL_ANCHOR))
|
||||
addAnchor(SCENE_LOWER_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_SHADOW_ANCHOR))
|
||||
addAnchor(SCENE_LOWER_LOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_LOW_ANCHOR))
|
||||
addAnchor(SCENE_LOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOW_ANCHOR))
|
||||
addAnchor(SCENE_LOW_DETAIL_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOW_DETAIL_ANCHOR))
|
||||
addAnchor(SCENE_UPPER_SHADOW_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_SHADOW_ANCHOR))
|
||||
addAnchor(SCENE_PRE_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_PRE_TOE_ANCHOR))
|
||||
addAnchor(SCENE_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_TOE_ANCHOR))
|
||||
addAnchor(SCENE_UPPER_TOE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_TOE_ANCHOR))
|
||||
addAnchor(SCENE_TOE_MID_JOIN_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_TOE_MID_JOIN_ANCHOR))
|
||||
addAnchor(SCENE_LOWER_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_LOWER_MID_ANCHOR))
|
||||
addAnchor(SCENE_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_MID_ANCHOR))
|
||||
addAnchor(SCENE_UPPER_MID_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_UPPER_MID_ANCHOR))
|
||||
addAnchor(SCENE_HALF_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_HALF_ANCHOR))
|
||||
addAnchor(SCENE_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_WHITE_ANCHOR))
|
||||
addAnchor(SCENE_BRIGHT_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_BRIGHT_ANCHOR))
|
||||
addAnchor(SCENE_SUPER_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_SUPER_WHITE_ANCHOR))
|
||||
addAnchor(SCENE_EXTREME_WHITE_ANCHOR, sceneAnchorOutput(params, sceneMax, SCENE_EXTREME_WHITE_ANCHOR))
|
||||
anchors += sceneMax to max(1f, (anchors.lastOrNull()?.second ?: 0f) + 1e-5f)
|
||||
return anchors
|
||||
}
|
||||
|
||||
private fun sampleHdrRangeCompression(
|
||||
private fun sceneAnchorOutput(
|
||||
params: HdrPgtmCurveParams,
|
||||
sceneMax: Float,
|
||||
sceneLinear: Float,
|
||||
): Float {
|
||||
if (sceneLinear <= 0f) return 0f
|
||||
if (sceneLinear >= sceneMax) return 1f
|
||||
val safeScene = sceneLinear.coerceAtLeast(MIN_CURVE_INPUT)
|
||||
val safeScene = sceneLinear.coerceIn(MIN_CURVE_INPUT, sceneMax)
|
||||
val midOutput = params.midOutput
|
||||
.coerceIn(SCENE_MID_ANCHOR * MIN_MID_GAIN, SCENE_MID_ANCHOR * MAX_MID_GAIN)
|
||||
if (safeScene <= SCENE_MID_ANCHOR) {
|
||||
val directGainOutput = safeScene * params.blackGain.coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN)
|
||||
val sceneEv = log2(safeScene / SCENE_MID_ANCHOR)
|
||||
val midOutputEv = log2(midOutput / SCENE_MID_ANCHOR)
|
||||
val toeEvOutput = SCENE_MID_ANCHOR *
|
||||
2.0f.pow(midOutputEv + sceneEv * params.toeSlope.coerceIn(MIN_TOE_SLOPE, MAX_TOE_SLOPE))
|
||||
val t = smoothStep(SCENE_SHADOW_ANCHOR, SCENE_MID_ANCHOR, safeScene)
|
||||
return lerp(directGainOutput, toeEvOutput, t)
|
||||
.coerceIn(0f, midOutput)
|
||||
}
|
||||
val midOutputEv = log2(midOutput / SCENE_MID_ANCHOR)
|
||||
val lowGain = lowDetailGain(params)
|
||||
val lowerTargetGain = max(midOutput / SCENE_MID_ANCHOR, lowGain * 0.76f)
|
||||
val lowerGain = lerp(
|
||||
lowGain,
|
||||
lowerTargetGain,
|
||||
smoothStep(SCENE_DEEP_SHADOW_ANCHOR, SCENE_LOWER_MID_ANCHOR, safeScene)
|
||||
)
|
||||
val lowerOutput = safeScene * lowerGain
|
||||
val sourceUpperEv = log2(sceneMax / SCENE_MID_ANCHOR).coerceAtLeast(0.01f)
|
||||
val sourceEv = log2(safeScene / SCENE_MID_ANCHOR).coerceIn(0f, sourceUpperEv)
|
||||
val midOutputEv = log2(midOutput / SCENE_MID_ANCHOR)
|
||||
val displayUpperEv = log2(1f / SCENE_MID_ANCHOR)
|
||||
val compressedRangeEv = max(displayUpperEv - midOutputEv, 0.01f)
|
||||
val t = (sourceEv / sourceUpperEv).coerceIn(0f, 1f)
|
||||
val shoulderT = hdrRangeShoulder(t, params.shoulderPower, params.highlightPressure)
|
||||
return (SCENE_MID_ANCHOR * 2.0f.pow(midOutputEv + compressedRangeEv * shoulderT))
|
||||
.coerceIn(midOutput, 1f)
|
||||
val upperOutput = SCENE_MID_ANCHOR * 2.0f.pow(midOutputEv + compressedRangeEv * shoulderT)
|
||||
val midJoin = ((safeScene - SCENE_LOWER_MID_ANCHOR) /
|
||||
max(SCENE_MID_ANCHOR - SCENE_LOWER_MID_ANCHOR, 1e-6f))
|
||||
.coerceIn(0f, 1f)
|
||||
return lerp(lowerOutput, upperOutput, midJoin)
|
||||
.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun sampleSceneCurve(anchors: List<Pair<Float, Float>>, sceneLinear: Float): Float {
|
||||
if (sceneLinear <= 0f) return 0f
|
||||
for (index in 0 until anchors.lastIndex) {
|
||||
val start = anchors[index]
|
||||
val end = anchors[index + 1]
|
||||
if (sceneLinear <= end.first) {
|
||||
val rawT = ((sceneLinear - start.first) / max(end.first - start.first, 1e-6f))
|
||||
.coerceIn(0f, 1f)
|
||||
val t = if (end.first <= SCENE_MID_ANCHOR) {
|
||||
rawT
|
||||
} else {
|
||||
smoothStep(0f, 1f, rawT)
|
||||
}
|
||||
return lerp(start.second, end.second, t)
|
||||
private fun monotoneTangents(inputs: FloatArray, outputs: FloatArray): FloatArray {
|
||||
val count = inputs.size
|
||||
if (count <= 1) return FloatArray(count)
|
||||
val slopes = FloatArray(count - 1)
|
||||
for (index in 0 until count - 1) {
|
||||
slopes[index] = (outputs[index + 1] - outputs[index]) /
|
||||
max(inputs[index + 1] - inputs[index], 1e-6f)
|
||||
}
|
||||
val tangents = FloatArray(count)
|
||||
tangents[0] = slopes[0]
|
||||
tangents[count - 1] = slopes[count - 2]
|
||||
for (index in 1 until count - 1) {
|
||||
tangents[index] = 0.5f * (slopes[index - 1] + slopes[index])
|
||||
}
|
||||
for (index in 0 until count - 1) {
|
||||
val slope = slopes[index]
|
||||
if (slope <= 0f) {
|
||||
tangents[index] = 0f
|
||||
tangents[index + 1] = 0f
|
||||
continue
|
||||
}
|
||||
val a = tangents[index] / slope
|
||||
val b = tangents[index + 1] / slope
|
||||
val magnitude = sqrt(a * a + b * b)
|
||||
if (magnitude > 3f) {
|
||||
val scale = 3f / magnitude
|
||||
tangents[index] = scale * a * slope
|
||||
tangents[index + 1] = scale * b * slope
|
||||
}
|
||||
}
|
||||
return anchors.last().second
|
||||
return tangents
|
||||
}
|
||||
|
||||
private fun lowDetailGain(params: HdrPgtmCurveParams): Float {
|
||||
val midGain = params.midOutput / SCENE_MID_ANCHOR
|
||||
return max(
|
||||
params.blackGain,
|
||||
midGain * LOW_DETAIL_MID_GAIN_FACTOR
|
||||
).coerceIn(MIN_BLACK_GAIN, MAX_BLACK_GAIN)
|
||||
}
|
||||
|
||||
private fun sampleSceneCurve(curve: SceneToneCurve, sceneLinear: Float): Float {
|
||||
if (sceneLinear <= 0f) return 0f
|
||||
val inputs = curve.inputs
|
||||
val outputs = curve.outputs
|
||||
val tangents = curve.tangents
|
||||
for (index in 0 until inputs.lastIndex) {
|
||||
val startX = inputs[index]
|
||||
val endX = inputs[index + 1]
|
||||
if (sceneLinear <= endX) {
|
||||
val span = max(endX - startX, 1e-6f)
|
||||
val t = ((sceneLinear - startX) / span)
|
||||
.coerceIn(0f, 1f)
|
||||
val t2 = t * t
|
||||
val t3 = t2 * t
|
||||
val h00 = 2f * t3 - 3f * t2 + 1f
|
||||
val h10 = t3 - 2f * t2 + t
|
||||
val h01 = -2f * t3 + 3f * t2
|
||||
val h11 = t3 - t2
|
||||
return (h00 * outputs[index] +
|
||||
h10 * span * tangents[index] +
|
||||
h01 * outputs[index + 1] +
|
||||
h11 * span * tangents[index + 1])
|
||||
.coerceIn(outputs[index], outputs[index + 1])
|
||||
}
|
||||
}
|
||||
return outputs.last()
|
||||
}
|
||||
|
||||
private fun hdrPgtmInputWeights(inputScale: Float): FloatArray {
|
||||
@@ -487,26 +679,22 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
|
||||
private fun hdrRangeMidGain(baselineExposureEv: Float, sceneHdrStrength: Float): Float {
|
||||
val hdrGain = lerp(2.30f, 2.40f, smoothStep(0.8f, 2.2f, baselineExposureEv))
|
||||
return lerp(1.65f, hdrGain, sceneHdrStrength)
|
||||
return lerp(1.88f, hdrGain, sceneHdrStrength)
|
||||
.coerceIn(MIN_MID_GAIN, MAX_MID_GAIN)
|
||||
}
|
||||
|
||||
private fun hdrRangeCenterOffsetEv(
|
||||
cell: HdrPgtmCellStats,
|
||||
darkRegion: Float,
|
||||
brightRegion: Float,
|
||||
global: HdrPgtmCellStats,
|
||||
highlightPressure: Float,
|
||||
hdrStrength: Float,
|
||||
): Float {
|
||||
val lowRangePressure = 1f - smoothStep(0.020f, 0.115f, cell.p90)
|
||||
val highRangePressure = smoothStep(0.18f, 0.88f, cell.p90)
|
||||
val lowRangePressure = 1f - smoothStep(0.020f, 0.115f, global.p90)
|
||||
val highRangePressure = smoothStep(0.18f, 0.88f, global.p90)
|
||||
return (
|
||||
0.32f * lowRangePressure +
|
||||
0.20f * darkRegion -
|
||||
0.16f * brightRegion -
|
||||
0.20f * highlightPressure -
|
||||
0.08f * highRangePressure * hdrStrength
|
||||
).coerceIn(-0.24f, 0.42f)
|
||||
0.24f * lowRangePressure -
|
||||
0.16f * highlightPressure -
|
||||
0.10f * highRangePressure * hdrStrength
|
||||
).coerceIn(-0.18f, 0.32f)
|
||||
}
|
||||
|
||||
private fun hdrRangeBlackGain(
|
||||
@@ -527,16 +715,19 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
private fun hdrRangeShoulderPower(
|
||||
global: HdrPgtmCellStats,
|
||||
effectiveUpperRangeEv: Float,
|
||||
highlightPressure: Float,
|
||||
hdrStrength: Float,
|
||||
): Float {
|
||||
val gcamRangeEv = GCAM_HDR_UPPER_RANGE_EV - GCAM_HDR_LOWER_RANGE_EV
|
||||
val normalizedRange = (effectiveUpperRangeEv / gcamRangeEv).coerceIn(0f, 1f)
|
||||
val lowToneSlopeBoost = 1f - smoothStep(0.45f, 0.70f, global.p98)
|
||||
return (1.02f +
|
||||
0.50f * normalizedRange +
|
||||
0.08f * hdrStrength -
|
||||
0.34f * highlightPressure)
|
||||
0.34f * highlightPressure +
|
||||
0.10f * lowToneSlopeBoost)
|
||||
.coerceIn(MIN_SHOULDER_POWER, MAX_SHOULDER_POWER)
|
||||
}
|
||||
|
||||
@@ -548,10 +739,10 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
val kneeLift = 0.035f * safePressure *
|
||||
smoothStep(0.68f, 0.82f, safeT) *
|
||||
(1f - smoothStep(0.88f, 0.96f, safeT))
|
||||
val rolloff = 0.30f * safePressure *
|
||||
val rolloff = 0.265f * safePressure *
|
||||
smoothStep(0.72f, 0.98f, safeT) *
|
||||
safeT
|
||||
val terminalRolloff = 0.028f *
|
||||
val terminalRolloff = 0.045f *
|
||||
smoothStep(0.90f, 0.99f, safeT) *
|
||||
safeT
|
||||
return (base + kneeLift - rolloff - terminalRolloff).coerceIn(0f, 1f)
|
||||
@@ -570,24 +761,13 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
val tailP99 = max(tailP98, global.inputTailP99.takeIf { it.isFinite() && it > 0f } ?: tailP98)
|
||||
val maxInput = max(tailP99, global.maxInput.takeIf { it.isFinite() && it > 0f } ?: tailP99)
|
||||
val baseSceneMax = hdrPgtmSceneMaxFromTailStats(
|
||||
highlightFraction = global.highlightFraction,
|
||||
global = global,
|
||||
tailP95 = tailP95,
|
||||
tailP98 = tailP98,
|
||||
tailP99 = tailP99,
|
||||
maxInput = maxInput
|
||||
)
|
||||
val lowKeyTailStrength = lowKeyLocalTailStrength(global)
|
||||
val lowKeySceneMax = if (lowKeyTailStrength > 0f) {
|
||||
val localTailSceneMax = tailP99 * lerp(
|
||||
1.0f,
|
||||
LOW_KEY_LOCAL_TAIL_SCENE_MAX_FACTOR,
|
||||
lowKeyTailStrength
|
||||
)
|
||||
max(baseSceneMax, localTailSceneMax)
|
||||
} else {
|
||||
baseSceneMax
|
||||
}
|
||||
val sceneMax = lowKeySceneMax.coerceIn(
|
||||
val sceneMax = baseSceneMax.coerceIn(
|
||||
max(MIN_SCENE_MAX, baselineGain / MAX_EFFECTIVE_INPUT_HEADROOM),
|
||||
baselineGain / MIN_EFFECTIVE_INPUT_HEADROOM
|
||||
)
|
||||
@@ -595,53 +775,84 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
private fun hdrPgtmSceneMaxFromTailStats(
|
||||
highlightFraction: Float,
|
||||
global: HdrPgtmCellStats,
|
||||
tailP95: Float,
|
||||
tailP98: Float,
|
||||
tailP99: Float,
|
||||
maxInput: Float,
|
||||
): Float {
|
||||
val safeHighlightFraction = highlightFraction.coerceIn(0f, 1f)
|
||||
return when {
|
||||
safeHighlightFraction >= 0.20f -> {
|
||||
max(maxInput * 0.99f, tailP99 * 1.10f)
|
||||
}
|
||||
|
||||
safeHighlightFraction >= 0.10f -> {
|
||||
max(tailP95, tailP98 * 0.98f)
|
||||
}
|
||||
|
||||
safeHighlightFraction >= 0.03f -> {
|
||||
tailP99 * 1.06f
|
||||
}
|
||||
|
||||
else -> {
|
||||
val outlierGapEv = log2((tailP99 + 0.04f) / (tailP98 + 0.04f))
|
||||
if (outlierGapEv >= 0.72f) {
|
||||
tailP99
|
||||
} else {
|
||||
min(tailP95 * 1.08f, tailP98)
|
||||
}
|
||||
}
|
||||
}
|
||||
val highlightDensity = global.highlightFraction.coerceIn(0f, 1f)
|
||||
val outlierGapEv = log2((tailP99 + 0.04f) / (tailP98 + 0.04f))
|
||||
val sparseOutlierStrength = smoothStep(0.50f, 0.95f, outlierGapEv)
|
||||
val isolatedHighlightStrength = smoothStep(0.025f, 0.08f, highlightDensity) *
|
||||
(1f - smoothStep(0.10f, 0.18f, highlightDensity))
|
||||
val broadHighlightStrength = smoothStep(0.08f, 0.17f, highlightDensity)
|
||||
val denseHighlightStrength = smoothStep(0.17f, 0.22f, highlightDensity)
|
||||
val baseSceneMax = min(tailP95 * 1.08f, tailP98)
|
||||
val outlierSceneMax = lerp(baseSceneMax, tailP99, sparseOutlierStrength)
|
||||
val isolatedHighlightSceneMax = lerp(
|
||||
outlierSceneMax,
|
||||
max(outlierSceneMax, tailP99 * 1.06f),
|
||||
isolatedHighlightStrength
|
||||
)
|
||||
val broadHighlightSceneMax = lerp(
|
||||
isolatedHighlightSceneMax,
|
||||
max(isolatedHighlightSceneMax, max(tailP95, tailP98 * 0.98f)),
|
||||
broadHighlightStrength * (1f - denseHighlightStrength)
|
||||
)
|
||||
val denseHighlightSceneMax = lerp(
|
||||
broadHighlightSceneMax,
|
||||
denseHighlightSceneMaxTarget(global, tailP95, tailP99),
|
||||
denseHighlightStrength
|
||||
)
|
||||
val expandedTailSceneMax = max(denseHighlightSceneMax, tailP99 * SCENE_TAIL_EXPANSION_FACTOR)
|
||||
return lerp(
|
||||
denseHighlightSceneMax,
|
||||
expandedTailSceneMax,
|
||||
sceneTailExpansionStrength(global)
|
||||
)
|
||||
}
|
||||
|
||||
private fun sceneHdrStrength(inputScale: Float): Float {
|
||||
private fun denseHighlightSceneMaxTarget(
|
||||
global: HdrPgtmCellStats,
|
||||
tailP95: Float,
|
||||
tailP99: Float,
|
||||
): Float {
|
||||
val denseBrightness = smoothStep(0.55f, 0.62f, global.p98)
|
||||
val tailFactor = lerp(0.96f, 1.12f, denseBrightness)
|
||||
val upperBound = max(MIN_SCENE_MAX, max(tailP95, tailP99 * 1.02f))
|
||||
return (tailP95 * tailFactor)
|
||||
.coerceIn(MIN_SCENE_MAX, upperBound)
|
||||
}
|
||||
|
||||
private fun sceneHdrStrength(global: HdrPgtmCellStats, inputScale: Float): Float {
|
||||
val sceneMax = 1f / sanitizeInputScale(inputScale)
|
||||
return smoothStep(1.12f, 2.35f, sceneMax)
|
||||
val sceneMaxStrength = smoothStep(1.12f, 2.35f, sceneMax)
|
||||
val globalDynamicRangeEv = log2((global.p98 + 0.006f) / (global.p10 + 0.006f))
|
||||
.coerceIn(0f, 8f)
|
||||
val contrastStrength = smoothStep(1.8f, 5.5f, globalDynamicRangeEv)
|
||||
return (sceneMaxStrength +
|
||||
(1f - sceneMaxStrength) * SCENE_TAIL_HDR_STRENGTH * contrastStrength)
|
||||
.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun lowKeyLocalTailStrength(global: HdrPgtmCellStats): Float {
|
||||
private fun sceneTailExpansionStrength(global: HdrPgtmCellStats): Float {
|
||||
val tailInput = max(global.inputTailP99, global.p999Input)
|
||||
if (!tailInput.isFinite() || tailInput <= 0f) return 0f
|
||||
val localTailGapEv = log2((tailInput + 0.04f) / (global.p98 + 0.04f))
|
||||
val lowUpperToneStrength = 1f - smoothStep(0.26f, 0.58f, global.p90)
|
||||
val lowHighlightToneStrength = 1f - smoothStep(0.24f, 0.52f, global.p98)
|
||||
val localTailStrength = smoothStep(0.82f, 1.55f, localTailGapEv)
|
||||
return (lowUpperToneStrength * lowHighlightToneStrength * localTailStrength)
|
||||
val medianToneGate = midToneTailGate(global)
|
||||
val upperToneGate = 1f - smoothStep(0.26f, 0.58f, global.p90)
|
||||
val highlightToneGate = 1f - smoothStep(0.24f, 0.52f, global.p98)
|
||||
val tailGapStrength = smoothStep(0.82f, 1.55f, localTailGapEv)
|
||||
return (medianToneGate * upperToneGate * highlightToneGate * tailGapStrength *
|
||||
SCENE_TAIL_EXPANSION_STRENGTH_GAIN)
|
||||
.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun midToneTailGate(global: HdrPgtmCellStats): Float {
|
||||
return 1f - smoothStep(0.18f, 0.48f, global.p50)
|
||||
}
|
||||
|
||||
private fun sanitizeInputScale(inputScale: Float): Float {
|
||||
return inputScale.takeIf { it.isFinite() }
|
||||
?.coerceIn(1e-4f, 1.0f)
|
||||
@@ -707,4 +918,10 @@ internal object DngHdrProfileGainTableGenerator {
|
||||
val shoulderPower: Float,
|
||||
val highlightPressure: Float,
|
||||
)
|
||||
|
||||
private data class SceneToneCurve(
|
||||
val inputs: FloatArray,
|
||||
val outputs: FloatArray,
|
||||
val tangents: FloatArray,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
|
||||
internal object DngPgtmDiagnostic {
|
||||
private const val TAG = "DngPgtmDiagnostic"
|
||||
|
||||
// 0 disables gain mutation. For halo isolation, use BLOCK_ONLY and sweep 7..18.
|
||||
private const val PGTM_DIAGNOSTIC_BAND_INDEX = 0
|
||||
private val PGTM_DIAGNOSTIC_MODE = DngHdrProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY
|
||||
|
||||
// Draws tableInput 0.080..0.140 as 0.005-wide false-color bands in RAW preview.
|
||||
private const val PGTM_VISUAL_OVERLAY_MODE = 0
|
||||
|
||||
private var visualOverlayLogged = false
|
||||
|
||||
fun activeBandForSource(source: String): DngHdrProfileGainTableGenerator.DiagnosticBand? {
|
||||
val band = activeBand() ?: return null
|
||||
PLog.w(
|
||||
TAG,
|
||||
"PGTM diagnostic band active for $source: mode=${band.mode} " +
|
||||
"tableInput=${band.start}..${band.end} feather=${band.feather}"
|
||||
)
|
||||
return band
|
||||
}
|
||||
|
||||
fun visualOverlayModeForSource(source: String): Int {
|
||||
if (PGTM_VISUAL_OVERLAY_MODE == 0) return 0
|
||||
if (!visualOverlayLogged) {
|
||||
visualOverlayLogged = true
|
||||
PLog.w(
|
||||
TAG,
|
||||
"PGTM visual overlay active for $source: tableInput 0.080..0.140 " +
|
||||
"split by 0.005; outside range is dim grayscale"
|
||||
)
|
||||
}
|
||||
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)
|
||||
2 -> band(0.005f, 0.010f, feather = 0.0010f)
|
||||
3 -> band(0.010f, 0.020f, feather = 0.0020f)
|
||||
4 -> band(0.020f, 0.040f, feather = 0.0030f)
|
||||
5 -> band(0.040f, 0.060f, feather = 0.0030f)
|
||||
6 -> band(0.060f, 0.080f, feather = 0.0030f)
|
||||
7 -> band(0.080f, 0.085f)
|
||||
8 -> band(0.085f, 0.090f)
|
||||
9 -> band(0.090f, 0.095f)
|
||||
10 -> band(0.095f, 0.100f)
|
||||
11 -> band(0.100f, 0.105f)
|
||||
12 -> band(0.105f, 0.110f)
|
||||
13 -> band(0.110f, 0.115f)
|
||||
14 -> band(0.115f, 0.120f)
|
||||
15 -> band(0.120f, 0.125f)
|
||||
16 -> band(0.125f, 0.130f)
|
||||
17 -> band(0.130f, 0.135f)
|
||||
18 -> band(0.135f, 0.140f)
|
||||
19 -> band(0.140f, 0.160f, feather = 0.0040f)
|
||||
20 -> band(0.160f, 0.180f, feather = 0.0040f)
|
||||
21 -> band(0.180f, 0.250f, feather = 0.0080f)
|
||||
22 -> band(0.250f, 0.400f, feather = 0.0120f)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun band(
|
||||
start: Float,
|
||||
end: Float,
|
||||
feather: Float = 0.0010f,
|
||||
): DngHdrProfileGainTableGenerator.DiagnosticBand {
|
||||
return DngHdrProfileGainTableGenerator.DiagnosticBand(
|
||||
start = start,
|
||||
end = end,
|
||||
feather = feather,
|
||||
mode = PGTM_DIAGNOSTIC_MODE
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,862 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
|
||||
object DngProfileGainTableMapPatcher {
|
||||
private const val TAG = "DngProfileGainTableMapPatcher"
|
||||
|
||||
private const val TIFF_CLASSIC_MAGIC = 42
|
||||
private const val TIFF_TAG_IMAGE_WIDTH = 256
|
||||
private const val TIFF_TAG_IMAGE_LENGTH = 257
|
||||
private const val TIFF_TAG_BITS_PER_SAMPLE = 258
|
||||
private const val TIFF_TAG_COMPRESSION = 259
|
||||
private const val TIFF_TAG_PHOTOMETRIC_INTERPRETATION = 262
|
||||
private const val TIFF_TAG_STRIP_OFFSETS = 273
|
||||
private const val TIFF_TAG_SAMPLES_PER_PIXEL = 277
|
||||
private const val TIFF_TAG_ROWS_PER_STRIP = 278
|
||||
private const val TIFF_TAG_STRIP_BYTE_COUNTS = 279
|
||||
private const val TIFF_TAG_SUB_IFDS = 330
|
||||
private const val TIFF_TAG_CFA_REPEAT_PATTERN_DIM = 33421
|
||||
private const val TIFF_TAG_CFA_PATTERN = 33422
|
||||
private const val TIFF_TAG_BLACK_LEVEL_REPEAT_DIM = 50713
|
||||
private const val TIFF_TAG_BLACK_LEVEL = 50714
|
||||
private const val TIFF_TAG_WHITE_LEVEL = 50717
|
||||
private const val TIFF_TAG_BASELINE_EXPOSURE = 50730
|
||||
private const val PHOTOMETRIC_CFA = 32803
|
||||
private const val COMPRESSION_UNCOMPRESSED = 1
|
||||
private const val BITS_PER_SAMPLE_16 = 16
|
||||
private const val RAW_SAMPLE_GRID = 16
|
||||
private const val HIST_BINS = 256
|
||||
private const val MAX_RAW_PIXEL_COUNT_FOR_PATCH = 80_000_000L
|
||||
private const val TYPE_BYTE = 1
|
||||
private const val TYPE_ASCII = 2
|
||||
private const val TYPE_SHORT = 3
|
||||
private const val TYPE_LONG = 4
|
||||
private const val TYPE_RATIONAL = 5
|
||||
private const val TYPE_SBYTE = 6
|
||||
private const val TYPE_UNDEFINED = 7
|
||||
private const val TYPE_SSHORT = 8
|
||||
private const val TYPE_SLONG = 9
|
||||
private const val TYPE_SRATIONAL = 10
|
||||
private const val TYPE_FLOAT = 11
|
||||
private const val TYPE_DOUBLE = 12
|
||||
private const val MAX_IFD_VISITS = 64
|
||||
|
||||
fun rewriteExistingPgtm2WithCurrentGenerator(file: File): Boolean {
|
||||
if (!file.exists() || file.length() < 16L) return false
|
||||
|
||||
val existingMap = DngProfileGainTableMap.readFrom(file)
|
||||
?.takeIf { it.isValid && it.sourceTag == DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 }
|
||||
?: return false
|
||||
|
||||
return runCatching {
|
||||
RandomAccessFile(file, "rw").use { raf ->
|
||||
val header = ByteArray(8)
|
||||
raf.seek(0)
|
||||
raf.readFully(header)
|
||||
|
||||
val byteOrder = when {
|
||||
header[0] == 'I'.code.toByte() && header[1] == 'I'.code.toByte() -> ByteOrder.LITTLE_ENDIAN
|
||||
header[0] == 'M'.code.toByte() && header[1] == 'M'.code.toByte() -> ByteOrder.BIG_ENDIAN
|
||||
else -> return@use false
|
||||
}
|
||||
if (readUnsignedShort(header, 2, byteOrder) != TIFF_CLASSIC_MAGIC) {
|
||||
return@use false
|
||||
}
|
||||
|
||||
val firstIfdOffset = readUnsignedInt(header, 4, byteOrder)
|
||||
if (firstIfdOffset <= 0L || firstIfdOffset + 2L > raf.length()) {
|
||||
return@use false
|
||||
}
|
||||
|
||||
val scan = scanForPgtm2Entries(raf, firstIfdOffset, byteOrder)
|
||||
if (scan.pgtm2Entries.isEmpty()) {
|
||||
return@use false
|
||||
}
|
||||
|
||||
val baselineExposureEv = scan.baselineExposure ?: run {
|
||||
PLog.w(TAG, "Skip PGTM2 rewrite for ${file.name}: missing BaselineExposure")
|
||||
return@use false
|
||||
}
|
||||
val localStats = scan.rawImages.firstNotNullOfOrNull { rawImage ->
|
||||
buildLocalStatsFromRaw(
|
||||
raf = raf,
|
||||
rawImage = rawImage,
|
||||
baselineExposureEv = baselineExposureEv
|
||||
)?.let { stats -> rawImage to stats }
|
||||
} ?: run {
|
||||
PLog.w(TAG, "Skip PGTM2 rewrite for ${file.name}: no supported uncompressed CFA RAW IFD")
|
||||
return@use false
|
||||
}
|
||||
val rawImage = localStats.first
|
||||
val replacementMap = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = rawImage.width,
|
||||
height = rawImage.height,
|
||||
baselineExposureEv = baselineExposureEv,
|
||||
packedCellStats = localStats.second,
|
||||
tablePointCount = existingMap.mapPointsN
|
||||
)?.let { map ->
|
||||
if (map.mapPointsH == existingMap.mapPointsH && map.mapPointsV == existingMap.mapPointsV) {
|
||||
map.copy(
|
||||
mapOriginH = existingMap.mapOriginH,
|
||||
mapOriginV = existingMap.mapOriginV
|
||||
)
|
||||
} else {
|
||||
map
|
||||
}
|
||||
} ?: return@use false
|
||||
val replacementBytes = replacementMap.encodeProfileGainTableMap2(byteOrder)
|
||||
val reusableEntry = scan.pgtm2Entries.firstOrNull { entry ->
|
||||
entry.count >= replacementBytes.size.toLong() &&
|
||||
entry.valueOffset >= 0L &&
|
||||
entry.valueOffset + replacementBytes.size.toLong() <= raf.length()
|
||||
}
|
||||
val replacementOffset = reusableEntry?.valueOffset
|
||||
?: appendValue(raf, replacementBytes)
|
||||
?: return@use false
|
||||
raf.seek(replacementOffset)
|
||||
raf.write(replacementBytes)
|
||||
|
||||
scan.pgtm2Entries.forEach { entry ->
|
||||
writeUndefinedEntryPointer(
|
||||
raf = raf,
|
||||
entryOffset = entry.entryOffset,
|
||||
count = replacementBytes.size.toLong(),
|
||||
valueOffset = replacementOffset,
|
||||
byteOrder = byteOrder
|
||||
)
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Rewrote ${scan.pgtm2Entries.size} DNG PGTM2 entries in ${file.name}: " +
|
||||
"baselineExposureEv=$baselineExposureEv " +
|
||||
"grid=${replacementMap.mapPointsH}x${replacementMap.mapPointsV}x${replacementMap.mapPointsN} " +
|
||||
"raw=${rawImage.width}x${rawImage.height} " +
|
||||
"storage=${if (reusableEntry != null) "reused" else "appended"}"
|
||||
)
|
||||
true
|
||||
}
|
||||
}.onFailure {
|
||||
PLog.w(TAG, "Failed to rewrite DNG PGTM2 with current generator: ${file.absolutePath}", it)
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun scanForPgtm2Entries(
|
||||
raf: RandomAccessFile,
|
||||
firstIfdOffset: Long,
|
||||
byteOrder: ByteOrder,
|
||||
): Pgtm2ScanResult {
|
||||
val pendingIfds = mutableListOf(firstIfdOffset)
|
||||
val visitedIfds = mutableSetOf<Long>()
|
||||
val pgtm2Entries = mutableListOf<Pgtm2Entry>()
|
||||
val rawImages = mutableListOf<RawImageInfo>()
|
||||
var baselineExposure: Float? = null
|
||||
|
||||
while (pendingIfds.isNotEmpty() && visitedIfds.size < MAX_IFD_VISITS) {
|
||||
val ifdOffset = pendingIfds.removeAt(0)
|
||||
if (ifdOffset <= 0L || ifdOffset in visitedIfds) continue
|
||||
visitedIfds += ifdOffset
|
||||
|
||||
val scan = scanIfd(raf, ifdOffset, byteOrder) ?: continue
|
||||
pgtm2Entries += scan.pgtm2Entries
|
||||
scan.rawImage?.let { rawImages += it }
|
||||
if (baselineExposure == null) {
|
||||
baselineExposure = scan.baselineExposure
|
||||
}
|
||||
if (scan.nextIfdOffset > 0L) {
|
||||
pendingIfds += scan.nextIfdOffset
|
||||
}
|
||||
scan.subIfdOffsets.forEach { subIfdOffset ->
|
||||
if (subIfdOffset > 0L && subIfdOffset !in visitedIfds) {
|
||||
pendingIfds += subIfdOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Pgtm2ScanResult(
|
||||
pgtm2Entries = pgtm2Entries,
|
||||
baselineExposure = baselineExposure,
|
||||
rawImages = rawImages
|
||||
)
|
||||
}
|
||||
|
||||
private fun scanIfd(
|
||||
raf: RandomAccessFile,
|
||||
ifdOffset: Long,
|
||||
byteOrder: ByteOrder,
|
||||
): IfdScanResult? {
|
||||
if (ifdOffset <= 0L || ifdOffset + 2L > raf.length()) return null
|
||||
|
||||
raf.seek(ifdOffset)
|
||||
val entryCountBytes = ByteArray(2)
|
||||
raf.readFully(entryCountBytes)
|
||||
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
|
||||
val entriesStart = ifdOffset + 2L
|
||||
val nextIfdPointerOffset = entriesStart + entryCount * 12L
|
||||
if (nextIfdPointerOffset + 4L > raf.length()) return null
|
||||
|
||||
val pgtm2Entries = mutableListOf<Pgtm2Entry>()
|
||||
val subIfdOffsets = mutableListOf<Long>()
|
||||
val entries = mutableListOf<IfdEntryBytes>()
|
||||
var baselineExposure: Float? = null
|
||||
|
||||
for (entryIndex in 0 until entryCount) {
|
||||
val entryOffset = entriesStart + entryIndex * 12L
|
||||
val entry = ByteArray(12)
|
||||
raf.seek(entryOffset)
|
||||
raf.readFully(entry)
|
||||
val tag = readUnsignedShort(entry, 0, byteOrder)
|
||||
val type = readUnsignedShort(entry, 2, byteOrder)
|
||||
val count = readUnsignedInt(entry, 4, byteOrder)
|
||||
entries += IfdEntryBytes(
|
||||
tag = tag,
|
||||
type = type,
|
||||
count = count,
|
||||
entryOffset = entryOffset,
|
||||
entry = entry
|
||||
)
|
||||
when (tag) {
|
||||
DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 -> {
|
||||
if (type == TYPE_UNDEFINED) {
|
||||
val valueOffset = valueOffsetForEntry(entry, entryOffset, count, byteOrder)
|
||||
if (valueOffset >= 0L && valueOffset + count <= raf.length()) {
|
||||
pgtm2Entries += Pgtm2Entry(
|
||||
entryOffset = entryOffset,
|
||||
count = count,
|
||||
valueOffset = valueOffset
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TIFF_TAG_BASELINE_EXPOSURE -> {
|
||||
baselineExposure = baselineExposure
|
||||
?: readFirstRealValue(raf, entry, entryOffset, type, count, byteOrder)
|
||||
}
|
||||
|
||||
TIFF_TAG_SUB_IFDS -> {
|
||||
subIfdOffsets += readUnsignedValues(raf, entry, entryOffset, type, count, byteOrder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raf.seek(nextIfdPointerOffset)
|
||||
val nextIfdBytes = ByteArray(4)
|
||||
raf.readFully(nextIfdBytes)
|
||||
return IfdScanResult(
|
||||
pgtm2Entries = pgtm2Entries,
|
||||
baselineExposure = baselineExposure,
|
||||
rawImage = parseRawImageInfo(raf, entries, byteOrder),
|
||||
subIfdOffsets = subIfdOffsets,
|
||||
nextIfdOffset = readUnsignedInt(nextIfdBytes, 0, byteOrder)
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseRawImageInfo(
|
||||
raf: RandomAccessFile,
|
||||
entries: List<IfdEntryBytes>,
|
||||
byteOrder: ByteOrder,
|
||||
): RawImageInfo? {
|
||||
val byTag = entries.associateBy { it.tag }
|
||||
val width = readFirstUnsignedValue(raf, byTag[TIFF_TAG_IMAGE_WIDTH], byteOrder)
|
||||
?.takeIf { it in 1..Int.MAX_VALUE.toLong() }
|
||||
?.toInt()
|
||||
?: return null
|
||||
val height = readFirstUnsignedValue(raf, byTag[TIFF_TAG_IMAGE_LENGTH], byteOrder)
|
||||
?.takeIf { it in 1..Int.MAX_VALUE.toLong() }
|
||||
?.toInt()
|
||||
?: return null
|
||||
if (width.toLong() * height.toLong() > MAX_RAW_PIXEL_COUNT_FOR_PATCH) return null
|
||||
val bitsPerSample = readFirstUnsignedValue(raf, byTag[TIFF_TAG_BITS_PER_SAMPLE], byteOrder)
|
||||
?.toInt()
|
||||
?: return null
|
||||
val compression = readFirstUnsignedValue(raf, byTag[TIFF_TAG_COMPRESSION], byteOrder)
|
||||
?.toInt()
|
||||
?: COMPRESSION_UNCOMPRESSED
|
||||
val photometric = readFirstUnsignedValue(raf, byTag[TIFF_TAG_PHOTOMETRIC_INTERPRETATION], byteOrder)
|
||||
?.toInt()
|
||||
?: return null
|
||||
val samplesPerPixel = readFirstUnsignedValue(raf, byTag[TIFF_TAG_SAMPLES_PER_PIXEL], byteOrder)
|
||||
?.toInt()
|
||||
?: 1
|
||||
if (bitsPerSample != BITS_PER_SAMPLE_16 ||
|
||||
compression != COMPRESSION_UNCOMPRESSED ||
|
||||
photometric != PHOTOMETRIC_CFA ||
|
||||
samplesPerPixel != 1
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
val stripOffsets = readUnsignedValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_STRIP_OFFSETS],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = 4096
|
||||
).takeIf { it.isNotEmpty() } ?: return null
|
||||
val stripByteCounts = readUnsignedValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_STRIP_BYTE_COUNTS],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = stripOffsets.size.coerceAtLeast(1)
|
||||
).takeIf { it.size == stripOffsets.size } ?: return null
|
||||
val rowsPerStrip = readFirstUnsignedValue(raf, byTag[TIFF_TAG_ROWS_PER_STRIP], byteOrder)
|
||||
?.takeIf { it > 0L && it <= Int.MAX_VALUE.toLong() }
|
||||
?.toInt()
|
||||
?: height
|
||||
|
||||
val cfaDim = readUnsignedValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_CFA_REPEAT_PATTERN_DIM],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = 2
|
||||
)
|
||||
val cfaRows = cfaDim.getOrNull(0)?.toInt()?.coerceIn(1, 8) ?: 2
|
||||
val cfaCols = cfaDim.getOrNull(1)?.toInt()?.coerceIn(1, 8) ?: 2
|
||||
val cfaPattern = readEntryBytes(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_CFA_PATTERN],
|
||||
byteOrder = byteOrder,
|
||||
maxBytes = 64
|
||||
)?.takeIf { it.size >= cfaRows * cfaCols }
|
||||
?.take(cfaRows * cfaCols)
|
||||
?.map { it.toInt() and 0xFF }
|
||||
?.toIntArray()
|
||||
?: intArrayOf(0, 1, 1, 2)
|
||||
|
||||
val blackDim = readUnsignedValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_BLACK_LEVEL_REPEAT_DIM],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = 2
|
||||
)
|
||||
val blackRows = blackDim.getOrNull(0)?.toInt()?.coerceIn(1, 8) ?: cfaRows
|
||||
val blackCols = blackDim.getOrNull(1)?.toInt()?.coerceIn(1, 8) ?: cfaCols
|
||||
val blackCount = blackRows * blackCols
|
||||
val blackValues = readRealValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_BLACK_LEVEL],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = blackCount.coerceAtLeast(1)
|
||||
)
|
||||
val blackLevel = FloatArray(blackCount) { index ->
|
||||
blackValues.getOrNull(index)
|
||||
?: blackValues.firstOrNull()
|
||||
?: 0f
|
||||
}
|
||||
val whiteLevel = readRealValues(
|
||||
raf = raf,
|
||||
entry = byTag[TIFF_TAG_WHITE_LEVEL],
|
||||
byteOrder = byteOrder,
|
||||
maxCount = 1
|
||||
).firstOrNull() ?: 65535f
|
||||
|
||||
return RawImageInfo(
|
||||
width = width,
|
||||
height = height,
|
||||
rowsPerStrip = rowsPerStrip,
|
||||
stripOffsets = stripOffsets,
|
||||
stripByteCounts = stripByteCounts,
|
||||
cfaRows = cfaRows,
|
||||
cfaCols = cfaCols,
|
||||
cfaPattern = cfaPattern,
|
||||
blackRows = blackRows,
|
||||
blackCols = blackCols,
|
||||
blackLevel = blackLevel,
|
||||
whiteLevel = whiteLevel.coerceAtLeast(1f),
|
||||
byteOrder = byteOrder
|
||||
)
|
||||
}
|
||||
|
||||
private fun buildLocalStatsFromRaw(
|
||||
raf: RandomAccessFile,
|
||||
rawImage: RawImageInfo,
|
||||
baselineExposureEv: Float,
|
||||
): FloatArray? {
|
||||
val rawPlane = readRawPlane(raf, rawImage) ?: return null
|
||||
val grid = DngHdrProfileGainTableGenerator.gridSizeFor(rawImage.width, rawImage.height)
|
||||
val gridWidth = grid.getOrElse(0) { 0 }
|
||||
val gridHeight = grid.getOrElse(1) { 0 }
|
||||
if (gridWidth <= 0 || gridHeight <= 0) return null
|
||||
|
||||
val baselineGain = 2.0f.pow(baselineExposureEv.coerceIn(0f, 8f))
|
||||
val stats = FloatArray(gridWidth * gridHeight * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE)
|
||||
val hist = IntArray(HIST_BINS)
|
||||
val inputSamples = FloatArray(RAW_SAMPLE_GRID * RAW_SAMPLE_GRID)
|
||||
for (cellY in 0 until gridHeight) {
|
||||
for (cellX in 0 until gridWidth) {
|
||||
java.util.Arrays.fill(hist, 0)
|
||||
var sampleCount = 0
|
||||
var highlightCount = 0
|
||||
var startX = (cellX * rawImage.width) / gridWidth
|
||||
var endX = ((cellX + 1) * rawImage.width + gridWidth - 1) / gridWidth
|
||||
var startY = (cellY * rawImage.height) / gridHeight
|
||||
var endY = ((cellY + 1) * rawImage.height + gridHeight - 1) / gridHeight
|
||||
startX -= startX and 1
|
||||
startY -= startY and 1
|
||||
endX = min(rawImage.width, endX + (endX and 1))
|
||||
endY = min(rawImage.height, endY + (endY and 1))
|
||||
|
||||
val cellWidth = max(endX - startX, 2)
|
||||
val cellHeight = max(endY - startY, 2)
|
||||
for (localY in 0 until RAW_SAMPLE_GRID) {
|
||||
for (localX in 0 until RAW_SAMPLE_GRID) {
|
||||
var x = startX + ((localX * 2 + 1) * cellWidth) / (RAW_SAMPLE_GRID * 2)
|
||||
var y = startY + ((localY * 2 + 1) * cellHeight) / (RAW_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(rawPlane, rawImage, x, y, baselineGain)
|
||||
inputSamples[sampleCount] = inputValue
|
||||
val clampedInput = inputValue.coerceIn(0f, 1f)
|
||||
val bin = (clampedInput * (HIST_BINS - 1).toFloat() + 0.5f)
|
||||
.toInt()
|
||||
.coerceIn(0, HIST_BINS - 1)
|
||||
hist[bin] += 1
|
||||
sampleCount += 1
|
||||
if (inputValue >= 0.92f) {
|
||||
highlightCount += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
val offset = (cellY * gridWidth + cellX) * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE
|
||||
stats[offset] = percentileFromHist(hist, sampleCount, 0.10f)
|
||||
stats[offset + 1] = percentileFromHist(hist, sampleCount, 0.50f)
|
||||
stats[offset + 2] = percentileFromHist(hist, sampleCount, 0.90f)
|
||||
stats[offset + 3] = percentileFromHist(hist, sampleCount, 0.98f)
|
||||
stats[offset + 4] = if (sampleCount > 0) highlightCount.toFloat() / sampleCount.toFloat() else 0f
|
||||
stats[offset + 5] = sampleCount.toFloat()
|
||||
stats[offset + 6] = percentileFromSamples(inputSamples, sampleCount, 0.995f)
|
||||
stats[offset + 7] = percentileFromSamples(inputSamples, sampleCount, 0.999f)
|
||||
}
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
private fun readRawPlane(
|
||||
raf: RandomAccessFile,
|
||||
rawImage: RawImageInfo,
|
||||
): ShortArray? {
|
||||
val pixelCount = rawImage.width.toLong() * rawImage.height.toLong()
|
||||
if (pixelCount <= 0L || pixelCount > MAX_RAW_PIXEL_COUNT_FOR_PATCH) return null
|
||||
val output = ShortArray(pixelCount.toInt())
|
||||
rawImage.stripOffsets.forEachIndexed { stripIndex, stripOffset ->
|
||||
val startRow = stripIndex * rawImage.rowsPerStrip
|
||||
if (startRow >= rawImage.height) return@forEachIndexed
|
||||
val rows = min(rawImage.rowsPerStrip, rawImage.height - startRow)
|
||||
val expectedBytes = rows.toLong() * rawImage.width.toLong() * 2L
|
||||
val byteCount = rawImage.stripByteCounts.getOrNull(stripIndex) ?: return null
|
||||
if (stripOffset <= 0L || byteCount < expectedBytes || stripOffset + expectedBytes > raf.length()) {
|
||||
return null
|
||||
}
|
||||
if (expectedBytes > Int.MAX_VALUE.toLong()) return null
|
||||
val bytes = ByteArray(expectedBytes.toInt())
|
||||
raf.seek(stripOffset)
|
||||
raf.readFully(bytes)
|
||||
val rowStrideBytes = rawImage.width * 2
|
||||
for (row in 0 until rows) {
|
||||
var byteOffset = row * rowStrideBytes
|
||||
var outOffset = (startRow + row) * rawImage.width
|
||||
repeat(rawImage.width) {
|
||||
val value = if (rawImage.byteOrder == ByteOrder.LITTLE_ENDIAN) {
|
||||
(bytes[byteOffset].toInt() and 0xFF) or
|
||||
((bytes[byteOffset + 1].toInt() and 0xFF) shl 8)
|
||||
} else {
|
||||
((bytes[byteOffset].toInt() and 0xFF) shl 8) or
|
||||
(bytes[byteOffset + 1].toInt() and 0xFF)
|
||||
}
|
||||
output[outOffset++] = value.toShort()
|
||||
byteOffset += 2
|
||||
}
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun pgtmInputAt(
|
||||
rawPlane: ShortArray,
|
||||
rawImage: RawImageInfo,
|
||||
baseX: Int,
|
||||
baseY: Int,
|
||||
baselineGain: Float,
|
||||
): Float {
|
||||
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, rawImage.width - 1)
|
||||
val y = (baseY + dy).coerceIn(0, rawImage.height - 1)
|
||||
val value = normalizedRawAt(rawPlane, rawImage, x, y)
|
||||
when (cfaColorAt(rawImage, 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
|
||||
val luma = 0.2126f * red + 0.7152f * green + 0.0722f * blue
|
||||
val maxChannel = max(red, max(green, blue))
|
||||
return max((0.5f * luma + 0.5f * maxChannel) * baselineGain, 0f)
|
||||
}
|
||||
|
||||
private fun normalizedRawAt(
|
||||
rawPlane: ShortArray,
|
||||
rawImage: RawImageInfo,
|
||||
x: Int,
|
||||
y: Int,
|
||||
): Float {
|
||||
val raw = rawPlane[y * rawImage.width + x].toInt() and 0xFFFF
|
||||
val blackIndex = (y % rawImage.blackRows) * rawImage.blackCols + (x % rawImage.blackCols)
|
||||
val black = rawImage.blackLevel.getOrElse(blackIndex) { rawImage.blackLevel.firstOrNull() ?: 0f }
|
||||
val range = max(rawImage.whiteLevel - black, 1f)
|
||||
return ((raw.toFloat() - black) / range).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
private fun cfaColorAt(rawImage: RawImageInfo, x: Int, y: Int): Int {
|
||||
val index = (y % rawImage.cfaRows) * rawImage.cfaCols + (x % rawImage.cfaCols)
|
||||
return rawImage.cfaPattern.getOrElse(index) { 1 }
|
||||
}
|
||||
|
||||
private fun percentileFromHist(hist: IntArray, sampleCount: Int, percentile: Float): Float {
|
||||
if (sampleCount <= 0) return 0f
|
||||
val target = kotlin.math.ceil(sampleCount.toFloat() * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceAtLeast(1)
|
||||
var cumulative = 0
|
||||
hist.forEachIndexed { index, count ->
|
||||
cumulative += count
|
||||
if (cumulative >= target) {
|
||||
return index.toFloat() / (hist.size - 1).toFloat()
|
||||
}
|
||||
}
|
||||
return 1f
|
||||
}
|
||||
|
||||
private fun percentileFromSamples(samples: FloatArray, sampleCount: Int, percentile: Float): Float {
|
||||
if (sampleCount <= 0) return 0f
|
||||
java.util.Arrays.sort(samples, 0, sampleCount)
|
||||
val index = kotlin.math.ceil(sampleCount.toFloat() * percentile.coerceIn(0f, 1f)).toInt()
|
||||
.coerceIn(1, sampleCount) - 1
|
||||
return samples[index].takeIf { it.isFinite() && it > 0f } ?: 0f
|
||||
}
|
||||
|
||||
private fun readFirstUnsignedValue(
|
||||
raf: RandomAccessFile,
|
||||
entry: IfdEntryBytes?,
|
||||
byteOrder: ByteOrder,
|
||||
): Long? {
|
||||
return readUnsignedValues(raf, entry, byteOrder, maxCount = 1).firstOrNull()
|
||||
}
|
||||
|
||||
private fun readUnsignedValues(
|
||||
raf: RandomAccessFile,
|
||||
entry: IfdEntryBytes?,
|
||||
byteOrder: ByteOrder,
|
||||
maxCount: Int,
|
||||
): List<Long> {
|
||||
entry ?: return emptyList()
|
||||
if (entry.count <= 0L || entry.count > maxCount.toLong()) return emptyList()
|
||||
val valueBytes = valueByteCount(entry.type, entry.count) ?: return emptyList()
|
||||
val valueOffset = valueOffsetForEntry(entry.entry, entry.entryOffset, valueBytes, byteOrder)
|
||||
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) return emptyList()
|
||||
val typeSize = typeSize(entry.type) ?: return emptyList()
|
||||
raf.seek(valueOffset)
|
||||
return buildList {
|
||||
repeat(entry.count.toInt()) {
|
||||
when (entry.type) {
|
||||
TYPE_BYTE, TYPE_ASCII, TYPE_UNDEFINED -> add(raf.readUnsignedByte().toLong())
|
||||
TYPE_SHORT -> add(readUnsignedShort(raf.readBytes(2), 0, byteOrder).toLong())
|
||||
TYPE_LONG -> add(readUnsignedInt(raf.readBytes(4), 0, byteOrder))
|
||||
TYPE_SBYTE -> add(raf.readByte().toLong())
|
||||
TYPE_SSHORT -> add(readSignedShort(raf.readBytes(2), 0, byteOrder).toLong())
|
||||
TYPE_SLONG -> add(readSignedInt(raf.readBytes(4), 0, byteOrder).toLong())
|
||||
else -> {
|
||||
raf.skipBytes(typeSize.toInt())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readRealValues(
|
||||
raf: RandomAccessFile,
|
||||
entry: IfdEntryBytes?,
|
||||
byteOrder: ByteOrder,
|
||||
maxCount: Int,
|
||||
): List<Float> {
|
||||
entry ?: return emptyList()
|
||||
if (entry.count <= 0L || entry.count > maxCount.toLong()) return emptyList()
|
||||
val valueBytes = valueByteCount(entry.type, entry.count) ?: return emptyList()
|
||||
val valueOffset = valueOffsetForEntry(entry.entry, entry.entryOffset, valueBytes, byteOrder)
|
||||
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) return emptyList()
|
||||
val typeSize = typeSize(entry.type) ?: return emptyList()
|
||||
raf.seek(valueOffset)
|
||||
return buildList {
|
||||
repeat(entry.count.toInt()) {
|
||||
val value = when (entry.type) {
|
||||
TYPE_BYTE, TYPE_ASCII, TYPE_UNDEFINED -> raf.readUnsignedByte().toDouble()
|
||||
TYPE_SBYTE -> raf.readByte().toDouble()
|
||||
TYPE_SHORT -> readUnsignedShort(raf.readBytes(2), 0, byteOrder).toDouble()
|
||||
TYPE_SSHORT -> readSignedShort(raf.readBytes(2), 0, byteOrder).toDouble()
|
||||
TYPE_LONG -> readUnsignedInt(raf.readBytes(4), 0, byteOrder).toDouble()
|
||||
TYPE_SLONG -> readSignedInt(raf.readBytes(4), 0, byteOrder).toDouble()
|
||||
TYPE_RATIONAL -> {
|
||||
val bytes = raf.readBytes(8)
|
||||
val numerator = readUnsignedInt(bytes, 0, byteOrder).toDouble()
|
||||
val denominator = readUnsignedInt(bytes, 4, byteOrder).toDouble()
|
||||
if (denominator == 0.0) Double.NaN else numerator / denominator
|
||||
}
|
||||
|
||||
TYPE_SRATIONAL -> {
|
||||
val bytes = raf.readBytes(8)
|
||||
val numerator = readSignedInt(bytes, 0, byteOrder).toDouble()
|
||||
val denominator = readSignedInt(bytes, 4, byteOrder).toDouble()
|
||||
if (denominator == 0.0) Double.NaN else numerator / denominator
|
||||
}
|
||||
|
||||
TYPE_FLOAT -> ByteBuffer.wrap(raf.readBytes(4)).order(byteOrder).float.toDouble()
|
||||
TYPE_DOUBLE -> ByteBuffer.wrap(raf.readBytes(8)).order(byteOrder).double
|
||||
else -> {
|
||||
raf.skipBytes(typeSize.toInt())
|
||||
Double.NaN
|
||||
}
|
||||
}
|
||||
if (value.isFinite()) {
|
||||
add(value.toFloat())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readEntryBytes(
|
||||
raf: RandomAccessFile,
|
||||
entry: IfdEntryBytes?,
|
||||
byteOrder: ByteOrder,
|
||||
maxBytes: Int,
|
||||
): ByteArray? {
|
||||
entry ?: return null
|
||||
val valueBytes = valueByteCount(entry.type, entry.count) ?: return null
|
||||
if (valueBytes <= 0L || valueBytes > maxBytes.toLong()) return null
|
||||
val valueOffset = valueOffsetForEntry(entry.entry, entry.entryOffset, valueBytes, byteOrder)
|
||||
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) return null
|
||||
raf.seek(valueOffset)
|
||||
return raf.readBytes(valueBytes.toInt())
|
||||
}
|
||||
|
||||
private fun readUnsignedValues(
|
||||
raf: RandomAccessFile,
|
||||
entry: ByteArray,
|
||||
entryOffset: Long,
|
||||
type: Int,
|
||||
count: Long,
|
||||
byteOrder: ByteOrder,
|
||||
): List<Long> {
|
||||
if (count <= 0L || count > 64L) return emptyList()
|
||||
val valueBytes = valueByteCount(type, count) ?: return emptyList()
|
||||
val valueOffset = valueOffsetForEntry(entry, entryOffset, valueBytes, byteOrder)
|
||||
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) return emptyList()
|
||||
|
||||
return buildList {
|
||||
raf.seek(valueOffset)
|
||||
repeat(count.toInt()) {
|
||||
when (type) {
|
||||
TYPE_SHORT -> add(readUnsignedShort(raf.readBytes(2), 0, byteOrder).toLong())
|
||||
TYPE_LONG -> add(readUnsignedInt(raf.readBytes(4), 0, byteOrder))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun readFirstRealValue(
|
||||
raf: RandomAccessFile,
|
||||
entry: ByteArray,
|
||||
entryOffset: Long,
|
||||
type: Int,
|
||||
count: Long,
|
||||
byteOrder: ByteOrder,
|
||||
): Float? {
|
||||
if (count <= 0L) return null
|
||||
val typeSize = typeSize(type) ?: return null
|
||||
val valueBytes = valueByteCount(type, count) ?: return null
|
||||
val valueOffset = valueOffsetForEntry(entry, entryOffset, valueBytes, byteOrder)
|
||||
if (valueOffset < 0L || valueOffset + typeSize > raf.length()) return null
|
||||
|
||||
raf.seek(valueOffset)
|
||||
val value = when (type) {
|
||||
TYPE_BYTE, TYPE_ASCII, TYPE_UNDEFINED -> raf.readUnsignedByte().toDouble()
|
||||
TYPE_SBYTE -> raf.readByte().toDouble()
|
||||
TYPE_SHORT -> readUnsignedShort(raf.readBytes(2), 0, byteOrder).toDouble()
|
||||
TYPE_SSHORT -> readSignedShort(raf.readBytes(2), 0, byteOrder).toDouble()
|
||||
TYPE_LONG -> readUnsignedInt(raf.readBytes(4), 0, byteOrder).toDouble()
|
||||
TYPE_SLONG -> readSignedInt(raf.readBytes(4), 0, byteOrder).toDouble()
|
||||
TYPE_RATIONAL -> {
|
||||
val bytes = raf.readBytes(8)
|
||||
val numerator = readUnsignedInt(bytes, 0, byteOrder).toDouble()
|
||||
val denominator = readUnsignedInt(bytes, 4, byteOrder).toDouble()
|
||||
if (denominator == 0.0) return null else numerator / denominator
|
||||
}
|
||||
|
||||
TYPE_SRATIONAL -> {
|
||||
val bytes = raf.readBytes(8)
|
||||
val numerator = readSignedInt(bytes, 0, byteOrder).toDouble()
|
||||
val denominator = readSignedInt(bytes, 4, byteOrder).toDouble()
|
||||
if (denominator == 0.0) return null else numerator / denominator
|
||||
}
|
||||
|
||||
TYPE_FLOAT -> ByteBuffer.wrap(raf.readBytes(4)).order(byteOrder).float.toDouble()
|
||||
TYPE_DOUBLE -> ByteBuffer.wrap(raf.readBytes(8)).order(byteOrder).double
|
||||
else -> return null
|
||||
}.toFloat()
|
||||
return value.takeIf { it.isFinite() }
|
||||
}
|
||||
|
||||
private fun writeUndefinedEntryPointer(
|
||||
raf: RandomAccessFile,
|
||||
entryOffset: Long,
|
||||
count: Long,
|
||||
valueOffset: Long,
|
||||
byteOrder: ByteOrder,
|
||||
) {
|
||||
raf.seek(entryOffset + 2L)
|
||||
raf.write(shortBytes(TYPE_UNDEFINED, byteOrder))
|
||||
raf.write(intBytes(count, byteOrder))
|
||||
raf.write(intBytes(valueOffset, byteOrder))
|
||||
}
|
||||
|
||||
private fun appendValue(raf: RandomAccessFile, value: ByteArray): Long? {
|
||||
var offset = raf.length()
|
||||
if ((offset and 1L) != 0L) {
|
||||
raf.seek(offset)
|
||||
raf.write(0)
|
||||
offset += 1L
|
||||
}
|
||||
if (offset + value.size.toLong() > 0xFFFFFFFFL) return null
|
||||
raf.seek(offset)
|
||||
raf.write(value)
|
||||
return offset
|
||||
}
|
||||
|
||||
private fun valueOffsetForEntry(
|
||||
entry: ByteArray,
|
||||
entryOffset: Long,
|
||||
valueBytes: Long,
|
||||
byteOrder: ByteOrder,
|
||||
): Long {
|
||||
return if (valueBytes <= 4L) {
|
||||
entryOffset + 8L
|
||||
} else {
|
||||
readUnsignedInt(entry, 8, byteOrder)
|
||||
}
|
||||
}
|
||||
|
||||
private fun valueByteCount(type: Int, count: Long): Long? {
|
||||
if (count <= 0L || count > Int.MAX_VALUE.toLong()) return null
|
||||
val size = typeSize(type) ?: return null
|
||||
return size * count
|
||||
}
|
||||
|
||||
private fun typeSize(type: Int): Long? {
|
||||
return when (type) {
|
||||
TYPE_BYTE, TYPE_ASCII, TYPE_SBYTE, TYPE_UNDEFINED -> 1L
|
||||
TYPE_SHORT, TYPE_SSHORT -> 2L
|
||||
TYPE_LONG, TYPE_SLONG, TYPE_FLOAT -> 4L
|
||||
TYPE_RATIONAL, TYPE_SRATIONAL, TYPE_DOUBLE -> 8L
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun RandomAccessFile.readBytes(count: Int): ByteArray {
|
||||
val bytes = ByteArray(count)
|
||||
readFully(bytes)
|
||||
return bytes
|
||||
}
|
||||
|
||||
private fun readUnsignedShort(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Int {
|
||||
return ByteBuffer.wrap(bytes, offset, 2).order(byteOrder).short.toInt() and 0xFFFF
|
||||
}
|
||||
|
||||
private fun readSignedShort(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Short {
|
||||
return ByteBuffer.wrap(bytes, offset, 2).order(byteOrder).short
|
||||
}
|
||||
|
||||
private fun readUnsignedInt(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Long {
|
||||
return ByteBuffer.wrap(bytes, offset, 4).order(byteOrder).int.toLong() and 0xFFFFFFFFL
|
||||
}
|
||||
|
||||
private fun readSignedInt(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Int {
|
||||
return ByteBuffer.wrap(bytes, offset, 4).order(byteOrder).int
|
||||
}
|
||||
|
||||
private fun shortBytes(value: Int, byteOrder: ByteOrder): ByteArray =
|
||||
ByteBuffer.allocate(2).order(byteOrder).putShort((value and 0xFFFF).toShort()).array()
|
||||
|
||||
private fun intBytes(value: Long, byteOrder: ByteOrder): ByteArray =
|
||||
ByteBuffer.allocate(4).order(byteOrder).putInt((value and 0xFFFFFFFFL).toInt()).array()
|
||||
|
||||
private data class Pgtm2ScanResult(
|
||||
val pgtm2Entries: List<Pgtm2Entry>,
|
||||
val baselineExposure: Float?,
|
||||
val rawImages: List<RawImageInfo>,
|
||||
)
|
||||
|
||||
private data class IfdScanResult(
|
||||
val pgtm2Entries: List<Pgtm2Entry>,
|
||||
val baselineExposure: Float?,
|
||||
val rawImage: RawImageInfo?,
|
||||
val subIfdOffsets: List<Long>,
|
||||
val nextIfdOffset: Long,
|
||||
)
|
||||
|
||||
private data class IfdEntryBytes(
|
||||
val tag: Int,
|
||||
val type: Int,
|
||||
val count: Long,
|
||||
val entryOffset: Long,
|
||||
val entry: ByteArray,
|
||||
)
|
||||
|
||||
private data class RawImageInfo(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val rowsPerStrip: Int,
|
||||
val stripOffsets: List<Long>,
|
||||
val stripByteCounts: List<Long>,
|
||||
val cfaRows: Int,
|
||||
val cfaCols: Int,
|
||||
val cfaPattern: IntArray,
|
||||
val blackRows: Int,
|
||||
val blackCols: Int,
|
||||
val blackLevel: FloatArray,
|
||||
val whiteLevel: Float,
|
||||
val byteOrder: ByteOrder,
|
||||
)
|
||||
|
||||
private data class Pgtm2Entry(
|
||||
val entryOffset: Long,
|
||||
val count: Long,
|
||||
val valueOffset: Long,
|
||||
)
|
||||
}
|
||||
@@ -942,7 +942,10 @@ class RawDemosaicProcessor {
|
||||
var embeddedDngRenderPlan: DcpRenderPlan? = null
|
||||
|
||||
if (dngFile != null) {
|
||||
val profileGainTableMap = DngProfileGainTableMap.readFrom(dngFile)
|
||||
val profileGainTableMap = DngPgtmDiagnostic.applyToEmbeddedMap(
|
||||
DngProfileGainTableMap.readFrom(dngFile),
|
||||
"DNG render"
|
||||
)
|
||||
val dngRawData = processDngNative(
|
||||
dngFile.absolutePath,
|
||||
profileWorkingColorSpace.xr, profileWorkingColorSpace.yr,
|
||||
@@ -2323,6 +2326,7 @@ class RawDemosaicProcessor {
|
||||
uniform float uProfileGainWeightMax;
|
||||
uniform float uProfileGainGamma;
|
||||
uniform float uProfileGainBaselineGain;
|
||||
uniform int uProfileGainDebugOverlay;
|
||||
|
||||
float profileGainTableValue(int tableX, int tableY, float tableIndex) {
|
||||
int pointCount = max(uProfileGainTableSize.z, 1);
|
||||
@@ -2336,7 +2340,15 @@ class RawDemosaicProcessor {
|
||||
return mix(g0, g1, t);
|
||||
}
|
||||
|
||||
float profileGain(vec3 rgb) {
|
||||
float profileGainTableInput(vec3 rgb) {
|
||||
float rgbMin = min(rgb.r, min(rgb.g, rgb.b));
|
||||
float rgbMax = max(rgb.r, max(rgb.g, rgb.b));
|
||||
float weightedInput = dot(vec4(rgb, rgbMin), uProfileGainWeights0) +
|
||||
rgbMax * uProfileGainWeightMax;
|
||||
return pow(clamp(weightedInput, 0.0, 1.0), uProfileGainGamma);
|
||||
}
|
||||
|
||||
float profileGain(vec3 rgb, float tableInput) {
|
||||
if (uProfileGainEnabled == 0) {
|
||||
return 1.0;
|
||||
}
|
||||
@@ -2352,11 +2364,6 @@ class RawDemosaicProcessor {
|
||||
int y1 = min(y0 + 1, mapV - 1);
|
||||
float tx = mapPosition.x - float(x0);
|
||||
float ty = mapPosition.y - float(y0);
|
||||
float rgbMin = min(rgb.r, min(rgb.g, rgb.b));
|
||||
float rgbMax = max(rgb.r, max(rgb.g, rgb.b));
|
||||
float weightedInput = dot(vec4(rgb, rgbMin), uProfileGainWeights0) +
|
||||
rgbMax * uProfileGainWeightMax;
|
||||
float tableInput = pow(clamp(weightedInput, 0.0, 1.0), uProfileGainGamma);
|
||||
float tableIndex = tableInput * float(max(uProfileGainTableSize.z, 1));
|
||||
float g00 = profileGainTableValue(x0, y0, tableIndex);
|
||||
float g10 = profileGainTableValue(x1, y0, tableIndex);
|
||||
@@ -2364,6 +2371,23 @@ class RawDemosaicProcessor {
|
||||
float g11 = profileGainTableValue(x1, y1, tableIndex);
|
||||
return max(mix(mix(g00, g10, tx), mix(g01, g11, tx), ty), 0.0);
|
||||
}
|
||||
|
||||
vec3 profileGainDebugColor(float tableInput) {
|
||||
float bin = floor((tableInput - 0.080) * 200.0);
|
||||
if (bin < 0.0 || bin >= 12.0) return vec3(0.0);
|
||||
if (bin < 1.0) return vec3(1.0, 0.05, 0.02); // 0.080..0.085 red
|
||||
if (bin < 2.0) return vec3(1.0, 0.32, 0.00); // 0.085..0.090 orange
|
||||
if (bin < 3.0) return vec3(1.0, 0.82, 0.00); // 0.090..0.095 yellow
|
||||
if (bin < 4.0) return vec3(0.62, 1.0, 0.00); // 0.095..0.100 lime
|
||||
if (bin < 5.0) return vec3(0.05, 0.90, 0.10); // 0.100..0.105 green
|
||||
if (bin < 6.0) return vec3(0.00, 0.92, 0.55); // 0.105..0.110 teal
|
||||
if (bin < 7.0) return vec3(0.00, 0.92, 1.0); // 0.110..0.115 cyan
|
||||
if (bin < 8.0) return vec3(0.00, 0.45, 1.0); // 0.115..0.120 blue
|
||||
if (bin < 9.0) return vec3(0.32, 0.10, 1.0); // 0.120..0.125 violet
|
||||
if (bin < 10.0) return vec3(0.82, 0.00, 1.0); // 0.125..0.130 purple
|
||||
if (bin < 11.0) return vec3(1.0, 0.00, 0.68); // 0.130..0.135 magenta
|
||||
return vec3(1.0, 0.75, 0.92); // 0.135..0.140 pink
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 rgb = texture(uDemosaickedTexture, vTexCoord).rgb;
|
||||
@@ -2371,11 +2395,20 @@ class RawDemosaicProcessor {
|
||||
float whitePoint = max(uWhitePoint, blackPoint + 0.01);
|
||||
rgb = max((rgb - vec3(blackPoint)) / max(whitePoint - blackPoint, 1e-5), vec3(0.0));
|
||||
rgb = uColorCorrectionMatrix * rgb;
|
||||
vec3 profileInputRgb = rgb * uProfileGainBaselineGain;
|
||||
float tableInput = profileGainTableInput(profileInputRgb);
|
||||
rgb *= profileGain(profileInputRgb, tableInput);
|
||||
if (uClampProfileRgb != 0) {
|
||||
rgb = clamp(rgb, vec3(0.0), vec3(1.0));
|
||||
}
|
||||
rgb *= profileGain(rgb * uProfileGainBaselineGain);
|
||||
rgb *= uExposureGain;
|
||||
if (uProfileGainDebugOverlay != 0 && uProfileGainEnabled != 0) {
|
||||
vec3 debugColor = profileGainDebugColor(tableInput);
|
||||
float inDebugRange = step(0.080, tableInput) * (1.0 - step(0.140, tableInput));
|
||||
float luma = dot(clamp(rgb, vec3(0.0), vec3(1.0)), vec3(0.2126, 0.7152, 0.0722));
|
||||
rgb = mix(vec3(luma * 0.42), rgb, 0.18);
|
||||
rgb = mix(rgb, debugColor, 0.90 * inDebugRange);
|
||||
}
|
||||
fragColor = vec4(rgb, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
@@ -5895,12 +5928,14 @@ class RawDemosaicProcessor {
|
||||
val profileGainTableMap = metadata.profileGainTableMap?.takeIf { it.isValid }
|
||||
if (profileGainTableMap == null || !applyAfterDngBaselineExposure) {
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uProfileGainEnabled"), 0)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uProfileGainDebugOverlay"), 0)
|
||||
return
|
||||
}
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + PROFILE_GAIN_TABLE_TEXTURE_UNIT)
|
||||
val textureId = ensureProfileGainTableTexture(profileGainTableMap)
|
||||
if (textureId == 0) {
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uProfileGainEnabled"), 0)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uProfileGainDebugOverlay"), 0)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -5944,6 +5979,10 @@ class RawDemosaicProcessor {
|
||||
GLES30.glGetUniformLocation(program, "uProfileGainBaselineGain"),
|
||||
exactDngBaselineExposureGain(metadata)
|
||||
)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(program, "uProfileGainDebugOverlay"),
|
||||
DngPgtmDiagnostic.visualOverlayModeForSource(TAG)
|
||||
)
|
||||
}
|
||||
|
||||
private fun ensureProfileGainTableTexture(profileGainTableMap: DngProfileGainTableMap): Int {
|
||||
|
||||
@@ -112,6 +112,7 @@ object RawHdrLinearFusionProcessor {
|
||||
lensShading = metadata.lensShadingMap.takeIf { applyLensShadingCorrection },
|
||||
lensShadingWidth = if (applyLensShadingCorrection) metadata.lensShadingMapWidth else 0,
|
||||
lensShadingHeight = if (applyLensShadingCorrection) metadata.lensShadingMapHeight else 0,
|
||||
colorCorrectionMatrix = metadata.colorCorrectionMatrix,
|
||||
)
|
||||
val stackResult = stacker.process(normalFrames.map { it.image })
|
||||
?: throw IllegalStateException("Failed to stack RAW HDR normal frames")
|
||||
|
||||
@@ -28,11 +28,13 @@ internal object RawProfileGainTableMapBuilder {
|
||||
metadata = metadata,
|
||||
samplesPerPixel = samplesPerPixel
|
||||
) ?: return null
|
||||
val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG)
|
||||
return DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = width,
|
||||
height = height,
|
||||
baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure),
|
||||
packedCellStats = stats
|
||||
packedCellStats = stats,
|
||||
diagnosticBand = diagnosticBand
|
||||
)
|
||||
}
|
||||
|
||||
@@ -190,9 +192,13 @@ internal object RawProfileGainTableMapBuilder {
|
||||
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
|
||||
val luma = 0.2126f * red + 0.7152f * green + 0.0722f * blue
|
||||
val maxChannel = max(red, max(green, blue))
|
||||
return max((0.5f * luma + 0.5f * maxChannel) * baselineGain, 0f)
|
||||
return DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = metadata.colorCorrectionMatrix
|
||||
)
|
||||
}
|
||||
|
||||
private fun linearRgbPgtmInputAt(
|
||||
@@ -212,9 +218,13 @@ internal object RawProfileGainTableMapBuilder {
|
||||
val red = normalizedLinearRgbAt(rawData, pixelOffset, metadata, 0)
|
||||
val green = normalizedLinearRgbAt(rawData, pixelOffset + 2, metadata, 1)
|
||||
val blue = normalizedLinearRgbAt(rawData, pixelOffset + 4, metadata, 2)
|
||||
val luma = 0.2126f * red + 0.7152f * green + 0.0722f * blue
|
||||
val maxChannel = max(red, max(green, blue))
|
||||
return max((0.5f * luma + 0.5f * maxChannel) * baselineGain, 0f)
|
||||
return DngHdrProfileGainTableGenerator.sceneInputFromLinearRgb(
|
||||
red = red,
|
||||
green = green,
|
||||
blue = blue,
|
||||
baselineGain = baselineGain,
|
||||
colorCorrectionMatrix = metadata.colorCorrectionMatrix
|
||||
)
|
||||
}
|
||||
|
||||
private fun normalizedLinearRgbAt(
|
||||
|
||||
+273
-124
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.raw
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.pow
|
||||
|
||||
class DngHdrProfileGainTableGeneratorTest {
|
||||
@@ -97,7 +98,7 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
|
||||
assertTrue("midGray=$midGray", midGray in 0.40f..0.46f)
|
||||
assertTrue("toneMappedMidGray=$toneMappedMidGray", toneMappedMidGray in 0.36f..0.46f)
|
||||
assertTrue("white=$white", white in 0.73f..0.80f)
|
||||
assertTrue("white=$white", white in 0.72f..0.80f)
|
||||
assertTrue("toneMappedWhite=$toneMappedWhite", toneMappedWhite in 0.78f..0.88f)
|
||||
assertTrue("superWhite=$superWhite", superWhite in 0.88f..0.93f)
|
||||
assertTrue("farHighlight=$farHighlight superWhite=$superWhite", farHighlight in superWhite..1.02f)
|
||||
@@ -110,123 +111,106 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun cellStatsDeriveSceneAdaptiveInputHeadroomLikePixelSamples() {
|
||||
val lowHdr = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = 1.55f,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
p10 = 0.065f,
|
||||
p50 = 0.208f,
|
||||
p90 = 0.663f,
|
||||
p98 = 0.93f,
|
||||
highlightFraction = 0.010f,
|
||||
tailP95 = 0.952f,
|
||||
tailP98 = 1.127f,
|
||||
tailP99 = 1.465f,
|
||||
maxInput = 2.798f
|
||||
)
|
||||
) ?: error("Expected low HDR PGTM")
|
||||
val typicalDenseHdr = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 2048,
|
||||
height = 1536,
|
||||
baselineExposureEv = 0.99f,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 2048,
|
||||
height = 1536,
|
||||
p10 = 0.038f,
|
||||
p50 = 0.059f,
|
||||
p90 = 0.111f,
|
||||
p98 = 1f,
|
||||
highlightFraction = 0.226f,
|
||||
tailP95 = 1.656f,
|
||||
tailP98 = 1.722f,
|
||||
tailP99 = 1.745f,
|
||||
maxInput = 1.986f
|
||||
)
|
||||
) ?: error("Expected typical dense HDR PGTM")
|
||||
val smallHighlightHdr = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = 1.56f,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
p10 = 0.005f,
|
||||
p50 = 0.03f,
|
||||
p90 = 0.48f,
|
||||
p98 = 1f,
|
||||
highlightFraction = 0.049f,
|
||||
tailP95 = 2.751f,
|
||||
tailP98 = 2.825f,
|
||||
tailP99 = 2.949f,
|
||||
maxInput = 2.949f
|
||||
)
|
||||
) ?: error("Expected small highlight PGTM")
|
||||
val sparseOutlierHdr = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = 1.47f,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
p10 = 0.015f,
|
||||
p50 = 0.12f,
|
||||
p90 = 0.55f,
|
||||
p98 = 0.77f,
|
||||
highlightFraction = 0.006f,
|
||||
tailP95 = 0.699f,
|
||||
tailP98 = 0.908f,
|
||||
tailP99 = 1.808f,
|
||||
maxInput = 2.770f
|
||||
)
|
||||
) ?: error("Expected sparse outlier PGTM")
|
||||
val denseHighlightHdr = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = 1.47f,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
p10 = 0.12f,
|
||||
p50 = 0.45f,
|
||||
p90 = 0.95f,
|
||||
p98 = 1f,
|
||||
highlightFraction = 0.165f,
|
||||
tailP95 = 2.563f,
|
||||
tailP98 = 2.579f,
|
||||
tailP99 = 2.586f,
|
||||
maxInput = 2.694f
|
||||
)
|
||||
) ?: error("Expected dense highlight PGTM")
|
||||
fun dngDerivedSceneStatsMatchEmbeddedPixelPgtmSamples() {
|
||||
DNG_DERIVED_FIXTURES.forEach { fixture ->
|
||||
val map = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = fixture.width,
|
||||
height = fixture.height,
|
||||
baselineExposureEv = fixture.baselineExposureEv,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = fixture.width,
|
||||
height = fixture.height,
|
||||
p10 = fixture.rimmP10,
|
||||
p50 = fixture.rimmP50,
|
||||
p90 = fixture.rimmP90,
|
||||
p98 = fixture.rimmP98,
|
||||
highlightFraction = fixture.rimmHighlightFraction,
|
||||
tailP95 = fixture.rimmTailP95,
|
||||
tailP98 = fixture.rimmTailP98,
|
||||
tailP99 = fixture.rimmTailP99,
|
||||
maxInput = fixture.rimmMaxInput
|
||||
)
|
||||
) ?: error("Expected PGTM for ${fixture.sourceName}")
|
||||
|
||||
val normalizedWeights = lowHdr.mapInputWeights.map { it / lowHdr.mapInputWeights.sum() }
|
||||
assertEquals(0.1495f, normalizedWeights[0], 0.0001f)
|
||||
assertEquals(0.2935f, normalizedWeights[1], 0.0001f)
|
||||
assertEquals(0.0570f, normalizedWeights[2], 0.0001f)
|
||||
assertEquals(0.1250f, normalizedWeights[3], 0.0001f)
|
||||
assertEquals(0.3750f, normalizedWeights[4], 0.0001f)
|
||||
val lowHeadroom = effectiveInputHeadroom(lowHdr, 1.55f)
|
||||
val typicalHeadroom = effectiveInputHeadroom(typicalDenseHdr, 0.99f)
|
||||
val smallHighlightHeadroom = effectiveInputHeadroom(smallHighlightHdr, 1.56f)
|
||||
val sparseOutlierHeadroom = effectiveInputHeadroom(sparseOutlierHdr, 1.47f)
|
||||
val denseHighlightHeadroom = effectiveInputHeadroom(denseHighlightHdr, 1.47f)
|
||||
assertTrue("lowHeadroom=$lowHeadroom", lowHeadroom in 2.65f..3.05f)
|
||||
assertTrue("typicalHeadroom=$typicalHeadroom", typicalHeadroom in 0.95f..1.08f)
|
||||
assertTrue("smallHighlightHeadroom=$smallHighlightHeadroom", smallHighlightHeadroom in 0.82f..1.05f)
|
||||
assertTrue("sparseOutlierHeadroom=$sparseOutlierHeadroom", sparseOutlierHeadroom in 1.45f..1.95f)
|
||||
assertTrue("denseHighlightHeadroom=$denseHighlightHeadroom", denseHighlightHeadroom in 1.05f..1.30f)
|
||||
assertTrue(sampleGainAtIndex(lowHdr, 0) < sampleGainAtIndex(smallHighlightHdr, 0))
|
||||
assertTrue(
|
||||
"typicalShadow=${sampleGainAtIndex(typicalDenseHdr, 0)} lowShadow=${sampleGainAtIndex(lowHdr, 0)}",
|
||||
sampleGainAtIndex(typicalDenseHdr, 0) > sampleGainAtIndex(lowHdr, 0)
|
||||
assertTrue("${fixture.sourceName} invalid map", map.isValid)
|
||||
assertToneOutputMonotonic(map)
|
||||
assertOfficialPgtmInputWeights(map, fixture.sourceName)
|
||||
assertEquals(
|
||||
"${fixture.sourceName} embedded weight sum",
|
||||
fixture.embeddedWeightSum,
|
||||
map.mapInputWeights.sum(),
|
||||
fixture.weightTolerance
|
||||
)
|
||||
assertEquals(
|
||||
"${fixture.sourceName} embedded headroom",
|
||||
fixture.embeddedInputHeadroom,
|
||||
effectiveInputHeadroom(map, fixture.baselineExposureEv),
|
||||
fixture.headroomTolerance
|
||||
)
|
||||
assertTrue(
|
||||
"${fixture.sourceName} shadow gain=${sampleGainAtIndex(map, 0)}",
|
||||
sampleGainAtIndex(map, 0) in fixture.shadowGainRange
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun googleKeycapDngStatsMatchEmbeddedPgtmLowRangeCurve() {
|
||||
val map = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = GOOGLE_KEYCAP_BASELINE_EV,
|
||||
packedCellStats = packedStatsForTailProfile(
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
p10 = 0.272827f,
|
||||
p50 = 0.344414f,
|
||||
p90 = 0.406222f,
|
||||
p98 = 0.429191f,
|
||||
highlightFraction = 0.038032f,
|
||||
tailP95 = 0.998236f,
|
||||
tailP98 = 1.243947f,
|
||||
tailP99 = 1.443504f,
|
||||
maxInput = 2.448398f
|
||||
)
|
||||
) ?: error("Expected Google keycap DNG PGTM")
|
||||
|
||||
assertTrue(map.isValid)
|
||||
assertToneOutputMonotonic(map)
|
||||
assertEquals(GOOGLE_KEYCAP_PGTM_WEIGHT_SUM, map.mapInputWeights.sum(), 0.045f)
|
||||
assertGainNear(map, tableInput = 0.005f, expected = 2.95f, tolerance = 0.38f)
|
||||
assertGainNear(map, tableInput = 0.010f, expected = 2.95f, tolerance = 0.36f)
|
||||
assertGainNear(map, tableInput = 0.015f, expected = 2.95f, tolerance = 0.35f)
|
||||
assertGainNear(map, tableInput = 0.02f, expected = 2.95f, tolerance = 0.34f)
|
||||
assertGainNear(map, tableInput = 0.03f, expected = 2.86f, tolerance = 0.30f)
|
||||
assertGainNear(map, tableInput = 0.04f, expected = 2.73f, tolerance = 0.28f)
|
||||
assertGainNear(map, tableInput = 0.05f, expected = 2.61f, tolerance = 0.24f)
|
||||
assertGainNear(map, tableInput = 0.06f, expected = 2.50f, tolerance = 0.22f)
|
||||
assertGainNear(map, tableInput = 0.07f, expected = 2.41f, tolerance = 0.20f)
|
||||
assertGainNear(map, tableInput = 0.08f, expected = 2.32f, tolerance = 0.18f)
|
||||
assertGainNear(map, tableInput = 0.09f, expected = 2.24f, tolerance = 0.17f)
|
||||
assertGainNear(map, tableInput = 0.10f, expected = 2.16f, tolerance = 0.16f)
|
||||
assertGainNear(map, tableInput = 0.11f, expected = 2.09f, tolerance = 0.15f)
|
||||
assertGainNear(map, tableInput = 0.12f, expected = 2.03f, tolerance = 0.14f)
|
||||
assertGainNear(map, tableInput = 0.13f, expected = 1.97f, tolerance = 0.13f)
|
||||
assertGainNear(map, tableInput = 0.14f, expected = 1.92f, tolerance = 0.13f)
|
||||
assertGainNear(map, tableInput = 0.16f, expected = 1.82f, tolerance = 0.13f)
|
||||
assertGainNear(map, tableInput = 0.18f, expected = 1.73f, tolerance = 0.13f)
|
||||
assertGainNear(map, tableInput = 0.28f, expected = 1.41f, tolerance = 0.12f)
|
||||
assertGainNear(map, tableInput = 0.50f, expected = 1.03f, tolerance = 0.08f)
|
||||
assertGainNear(map, tableInput = 0.75f, expected = 0.80f, tolerance = 0.06f)
|
||||
assertGainNear(map, tableInput = 1.00f, expected = 0.666f, tolerance = 0.025f)
|
||||
assertGoogleKeycapLowRangeOutputProfile(map)
|
||||
assertTrue("darkOutput=${0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum())}",
|
||||
0.03f * sampleGain(map, 0.03f * map.mapInputWeights.sum()) > 0.075f
|
||||
)
|
||||
assertTrue("midOutput=${0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum())}",
|
||||
0.18f * sampleGain(map, 0.18f * map.mapInputWeights.sum()) in 0.33f..0.41f
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun localToneMappingDodgesDarkTilesAndBurnsBrightTiles() {
|
||||
fun sceneStatsProduceOrderedToneTargetsWithoutBrightnessReversal() {
|
||||
val dark = DngHdrProfileGainTableGenerator.forCellStats(
|
||||
width = 1024,
|
||||
height = 768,
|
||||
@@ -278,21 +262,28 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
sampleGainAtIndex(dark, 0) > sampleGainAtIndex(mid, 0)
|
||||
)
|
||||
assertTrue(sampleGainAtIndex(mid, 0) > sampleGainAtIndex(bright, 0))
|
||||
val darkMid = renderedOutputForPostBaselineSignal(dark, input = 0.18f)
|
||||
val midMid = renderedOutputForPostBaselineSignal(mid, input = 0.18f)
|
||||
val brightMid = renderedOutputForPostBaselineSignal(bright, input = 0.18f)
|
||||
val brightWhite = renderedOutputForPostBaselineSignal(bright, input = 1f)
|
||||
val midWhite = renderedOutputForPostBaselineSignal(mid, input = 1f)
|
||||
val darkUpper = renderedOutputForPostBaselineSignal(dark, input = 0.8f)
|
||||
val brightUpper = renderedOutputForPostBaselineSignal(bright, input = 0.8f)
|
||||
assertTrue(
|
||||
renderedOutputForPostBaselineSignal(dark, input = 0.18f) >
|
||||
renderedOutputForPostBaselineSignal(mid, input = 0.18f)
|
||||
"darkMid=$darkMid midMid=$midMid",
|
||||
darkMid + 0.002f >= midMid
|
||||
)
|
||||
assertTrue(
|
||||
renderedOutputForPostBaselineSignal(mid, input = 0.18f) >
|
||||
renderedOutputForPostBaselineSignal(bright, input = 0.18f)
|
||||
"midMid=$midMid brightMid=$brightMid",
|
||||
midMid > brightMid
|
||||
)
|
||||
assertTrue(
|
||||
renderedOutputForPostBaselineSignal(bright, input = 1f) <
|
||||
renderedOutputForPostBaselineSignal(mid, input = 1f)
|
||||
"brightWhite=$brightWhite midWhite=$midWhite",
|
||||
brightWhite < midWhite
|
||||
)
|
||||
assertTrue(
|
||||
renderedOutputForPostBaselineSignal(dark, input = 0.8f) >
|
||||
renderedOutputForPostBaselineSignal(bright, input = 0.8f)
|
||||
"darkUpper=$darkUpper brightUpper=$brightUpper",
|
||||
darkUpper > brightUpper
|
||||
)
|
||||
assertEquals(sampleGainAtIndex(dark, 256), sampleGainAtIndex(bright, 256), 0.002f)
|
||||
}
|
||||
@@ -422,9 +413,12 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
|
||||
private fun sampleGain(map: DngProfileGainTableMap, input: Float): Float {
|
||||
val index = (input.coerceIn(0f, 1f) * map.mapPointsN).toInt()
|
||||
.coerceIn(0, map.mapPointsN - 1)
|
||||
return map.gains[index]
|
||||
val clamped = input.coerceIn(0f, 1f)
|
||||
val scaled = clamped * map.mapPointsN.coerceAtLeast(1)
|
||||
val i0 = scaled.toInt().coerceIn(0, map.mapPointsN - 1)
|
||||
val i1 = (i0 + 1).coerceIn(0, map.mapPointsN - 1)
|
||||
val t = scaled - i0.toFloat()
|
||||
return map.gains[i0] * (1f - t) + map.gains[i1] * t
|
||||
}
|
||||
|
||||
private fun sampleGainAtIndex(map: DngProfileGainTableMap, index: Int): Float {
|
||||
@@ -463,6 +457,7 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
|
||||
private fun tableInputForIndex(index: Int, pointCount: Int): Float {
|
||||
if (pointCount <= 1) return 0f
|
||||
return if (index == pointCount - 1) {
|
||||
1f
|
||||
} else {
|
||||
@@ -470,7 +465,161 @@ class DngHdrProfileGainTableGeneratorTest {
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertGainNear(
|
||||
map: DngProfileGainTableMap,
|
||||
tableInput: Float,
|
||||
expected: Float,
|
||||
tolerance: Float,
|
||||
) {
|
||||
val actual = sampleGain(map, tableInput)
|
||||
assertEquals("tableInput=$tableInput actual=$actual expected=$expected", expected, actual, tolerance)
|
||||
}
|
||||
|
||||
private fun assertOfficialPgtmInputWeights(map: DngProfileGainTableMap, sourceName: String) {
|
||||
val normalizedWeights = map.mapInputWeights.map { it / map.mapInputWeights.sum() }
|
||||
assertEquals("$sourceName weight R", 0.1495f, normalizedWeights[0], 0.0001f)
|
||||
assertEquals("$sourceName weight G", 0.2935f, normalizedWeights[1], 0.0001f)
|
||||
assertEquals("$sourceName weight B", 0.0570f, normalizedWeights[2], 0.0001f)
|
||||
assertEquals("$sourceName weight min", 0.1250f, normalizedWeights[3], 0.0001f)
|
||||
assertEquals("$sourceName weight max", 0.3750f, normalizedWeights[4], 0.0001f)
|
||||
}
|
||||
|
||||
private fun assertGoogleKeycapLowRangeOutputProfile(map: DngProfileGainTableMap) {
|
||||
val samples = floatArrayOf(
|
||||
0.080f, 0.085f, 0.090f, 0.095f, 0.100f, 0.105f, 0.110f,
|
||||
0.115f, 0.120f, 0.125f, 0.130f, 0.135f, 0.140f
|
||||
)
|
||||
val expectedOutputs = floatArrayOf(
|
||||
0.185364f, 0.193387f, 0.201181f, 0.208760f, 0.216135f, 0.223304f, 0.230243f,
|
||||
0.237050f, 0.243581f, 0.249959f, 0.256297f, 0.262396f, 0.268389f
|
||||
)
|
||||
val expectedSlopes = floatArrayOf(
|
||||
1.604631f, 1.558854f, 1.515782f, 1.474917f, 1.433899f, 1.387858f,
|
||||
1.361360f, 1.306116f, 1.275739f, 1.267608f, 1.219756f, 1.198601f
|
||||
)
|
||||
val outputs = samples.map { input -> input * sampleGain(map, input) }
|
||||
outputs.forEachIndexed { index, output ->
|
||||
assertEquals(
|
||||
"lowRangeOutput tableInput=${samples[index]} actual=$output expected=${expectedOutputs[index]}",
|
||||
expectedOutputs[index],
|
||||
output,
|
||||
0.007f
|
||||
)
|
||||
}
|
||||
val slopes = outputs.zipWithNext().mapIndexed { index, (a, b) ->
|
||||
(b - a) / (samples[index + 1] - samples[index])
|
||||
}
|
||||
slopes.forEachIndexed { index, slope ->
|
||||
assertEquals(
|
||||
"lowRangeSlope tableInput=${samples[index]}..${samples[index + 1]} " +
|
||||
"actual=$slope expected=${expectedSlopes[index]}",
|
||||
expectedSlopes[index],
|
||||
slope,
|
||||
0.17f
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val HIGH_HDR_BASELINE_EV = 3.377331f
|
||||
private const val GOOGLE_KEYCAP_BASELINE_EV = 1.46f
|
||||
private const val GOOGLE_KEYCAP_PGTM_HEADROOM = 1.8273006f
|
||||
private const val GOOGLE_KEYCAP_PGTM_WEIGHT_SUM = 0.6642112f
|
||||
|
||||
private val DNG_DERIVED_FIXTURES = listOf(
|
||||
DngDerivedPgtmFixture(
|
||||
sourceName = "PXL_20260628_175619159.RAW-02.ORIGINAL..dng",
|
||||
width = 2048,
|
||||
height = 1536,
|
||||
baselineExposureEv = 0.99f,
|
||||
embeddedWeightSum = 0.5074623f,
|
||||
embeddedInputHeadroom = 1.0079140f,
|
||||
rimmP10 = 0.337668f,
|
||||
rimmP50 = 0.428147f,
|
||||
rimmP90 = 0.556421f,
|
||||
rimmP98 = 0.622064f,
|
||||
rimmHighlightFraction = 0.237918f,
|
||||
rimmTailP95 = 1.769715f,
|
||||
rimmTailP98 = 1.848588f,
|
||||
rimmTailP99 = 1.960254f,
|
||||
rimmMaxInput = 3.247468f,
|
||||
shadowGainRange = 2.6f..4.2f
|
||||
),
|
||||
DngDerivedPgtmFixture(
|
||||
sourceName = "PXL_20260630_100508552.RAW-02.ORIGINAL..dng",
|
||||
width = 2818,
|
||||
height = 2114,
|
||||
baselineExposureEv = 1.38f,
|
||||
embeddedWeightSum = 0.6550936f,
|
||||
embeddedInputHeadroom = 1.7050014f,
|
||||
rimmP10 = 0.322686f,
|
||||
rimmP50 = 0.387230f,
|
||||
rimmP90 = 0.493896f,
|
||||
rimmP98 = 0.552372f,
|
||||
rimmHighlightFraction = 0.213364f,
|
||||
rimmTailP95 = 1.592500f,
|
||||
rimmTailP98 = 1.797323f,
|
||||
rimmTailP99 = 1.881310f,
|
||||
rimmMaxInput = 1.991887f,
|
||||
shadowGainRange = 2.5f..3.8f
|
||||
),
|
||||
DngDerivedPgtmFixture(
|
||||
sourceName = "PXL_20260629_213614190.RAW-02.ORIGINAL..dng",
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = 1.40f,
|
||||
embeddedWeightSum = 0.7948943f,
|
||||
embeddedInputHeadroom = 2.0977387f,
|
||||
rimmP10 = 0.270184f,
|
||||
rimmP50 = 0.340886f,
|
||||
rimmP90 = 0.418926f,
|
||||
rimmP98 = 0.456479f,
|
||||
rimmHighlightFraction = 0.012236f,
|
||||
rimmTailP95 = 0.920819f,
|
||||
rimmTailP98 = 1.325456f,
|
||||
rimmTailP99 = 1.543746f,
|
||||
rimmMaxInput = 4.766730f,
|
||||
shadowGainRange = 2.0f..3.4f
|
||||
),
|
||||
DngDerivedPgtmFixture(
|
||||
sourceName = "PXL_20260702_144246096.RAW-02.ORIGINAL..dng",
|
||||
width = 4096,
|
||||
height = 3072,
|
||||
baselineExposureEv = GOOGLE_KEYCAP_BASELINE_EV,
|
||||
embeddedWeightSum = GOOGLE_KEYCAP_PGTM_WEIGHT_SUM,
|
||||
embeddedInputHeadroom = GOOGLE_KEYCAP_PGTM_HEADROOM,
|
||||
rimmP10 = 0.272827f,
|
||||
rimmP50 = 0.344414f,
|
||||
rimmP90 = 0.406222f,
|
||||
rimmP98 = 0.429191f,
|
||||
rimmHighlightFraction = 0.038032f,
|
||||
rimmTailP95 = 0.998236f,
|
||||
rimmTailP98 = 1.243947f,
|
||||
rimmTailP99 = 1.443504f,
|
||||
rimmMaxInput = 2.448398f,
|
||||
shadowGainRange = 2.3f..3.3f
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
private data class DngDerivedPgtmFixture(
|
||||
val sourceName: String,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
val baselineExposureEv: Float,
|
||||
val embeddedWeightSum: Float,
|
||||
val embeddedInputHeadroom: Float,
|
||||
val rimmP10: Float,
|
||||
val rimmP50: Float,
|
||||
val rimmP90: Float,
|
||||
val rimmP98: Float,
|
||||
val rimmHighlightFraction: Float,
|
||||
val rimmTailP95: Float,
|
||||
val rimmTailP98: Float,
|
||||
val rimmTailP99: Float,
|
||||
val rimmMaxInput: Float,
|
||||
val shadowGainRange: ClosedFloatingPointRange<Float>,
|
||||
val weightTolerance: Float = 0.035f,
|
||||
val headroomTolerance: Float = 0.10f,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
# PGTM Debug Handoff 2026-07-02
|
||||
|
||||
## Context
|
||||
|
||||
This branch captures the PGTM halo debugging work from 2026-07-02. The issue is visible in RAW rendering when the Google Pixel-style tone map is enabled: regions that look visually close in the pre-PGTM linear image split into different brightness bands after PGTM, producing halo around keycaps. The user confirmed:
|
||||
|
||||
- The halo is absent before PGTM in the linear image.
|
||||
- Baseline exposure is not the root cause.
|
||||
- A constant `0.25` PGTM darkens in the app and system gallery, but Lightroom ignores PGTM.
|
||||
- A constant `0.25` PGTM has no halo after lifting, so the artifact is caused by generated PGTM data, not tag application alone.
|
||||
- The visible halo region maps roughly to PGTM table input `0.08..0.14`.
|
||||
- The solution must follow the Adobe DNG SDK/DNG spec semantics, not an ad-hoc luminance estimate.
|
||||
|
||||
## Official DNG Semantics Used
|
||||
|
||||
Adobe DNG 1.7.1 / DNG SDK 1.7.1 documents ProfileGainTableMap and ProfileGainTableMap2 with these constraints:
|
||||
|
||||
- PGTM input is computed from `(R, G, B, min(R,G,B), max(R,G,B)) * MapInputWeights`.
|
||||
- For PGTM2, the input is clamped and raised by `Gamma`.
|
||||
- PGTM should be applied in Reference Input Medium Metric / profile linear color space.
|
||||
- BaselineExposure is applied before PGTM.
|
||||
- PGTM is applied before ProfileToneCurve.
|
||||
- Table lookup indexes use `tableInput * MapPointsN`, with final lookup clamped to valid table entries.
|
||||
|
||||
The official docs source used during debugging was Adobe's DNG page:
|
||||
|
||||
https://helpx.adobe.com/camera-raw/digital-negative.html
|
||||
|
||||
The DNG 1.7.1 PDF was also downloaded locally during debugging as `/private/tmp/DNG_Spec_1_7_1_0.pdf` and converted to `/private/tmp/dng_spec_1_7_1_0.txt`.
|
||||
|
||||
## Root Causes Found
|
||||
|
||||
1. CPU and GPU PGTM stats were previously based on a custom camera-space `0.5*luma + 0.5*maxChannel` input. That does not match DNG PGTM semantics.
|
||||
|
||||
2. PGTM generation was not consistently transforming stats samples into profile/RIMM linear RGB before computing the five-weight input.
|
||||
|
||||
3. Rendering previously clamped profile RGB before computing PGTM input. DNG PGTM input should be derived from the linear profile/RIMM value after BaselineExposure, before optional render-domain clamp.
|
||||
|
||||
4. The old test samples were partially derived from DNGs but were not recomputed after switching to the correct RIMM/profile input. They could pass while no longer proving the generator matched the original DNG metadata.
|
||||
|
||||
5. The offline `DngProfileGainTableMapPatcher` was a divergent path. It rewrote DNG files after save and could not strictly reconstruct full DNG profile/RIMM metadata. This conflicted with the UI switch path.
|
||||
|
||||
## Code Changes
|
||||
|
||||
### Generator
|
||||
|
||||
File:
|
||||
|
||||
- `app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- Added shared official PGTM input weights:
|
||||
- R `0.1495`
|
||||
- G `0.2935`
|
||||
- B `0.0570`
|
||||
- min `0.1250`
|
||||
- max `0.3750`
|
||||
- Added `sceneInputFromLinearRgb(...)` and `sceneInputFromProfileRgb(...)`.
|
||||
- Generator stats are now assumed to be post-BaselineExposure profile/RIMM five-weight scene inputs.
|
||||
- Table input indexing is back to the DNG convention: `index / pointCount`, except last entry maps to `1.0`.
|
||||
- Dense-highlight scene max fitting was changed so dense highlight cases do not blindly chase `maxInput` outliers. The target now depends on `p98` and tail percentile stats, which lets older Pixel DNG-derived samples and the keycap sample pass together.
|
||||
- Added diagnostic band support for temporary PGTM range isolation.
|
||||
|
||||
### CPU Stats Builder
|
||||
|
||||
File:
|
||||
|
||||
- `app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- Replaced the custom luma/max stat input with `sceneInputFromLinearRgb(...)`.
|
||||
- Passes `metadata.colorCorrectionMatrix` so the stats input is computed in profile/RIMM linear space.
|
||||
- Handles both CFA raw and LinearRaw RGB inputs through the same official five-weight input path.
|
||||
|
||||
### GPU HDR Stacker Stats
|
||||
|
||||
Files:
|
||||
|
||||
- `app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt`
|
||||
- `app/src/main/java/com/hinnka/mycamera/raw/RawHdrLinearFusionProcessor.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- `GlesRawStacker` now accepts `colorCorrectionMatrix`.
|
||||
- PGTM stats compute shader transforms sampled RGB by `uColorCorrectionMatrix`, multiplies BaselineExposure gain, then computes the official five-weight PGTM input.
|
||||
- `RawHdrLinearFusionProcessor` passes `metadata.colorCorrectionMatrix` to the GPU stacker.
|
||||
|
||||
### Render Path
|
||||
|
||||
File:
|
||||
|
||||
- `app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- PGTM input is computed after the color matrix into profile/RIMM linear space.
|
||||
- PGTM input is computed from `rgb * baselineGain`.
|
||||
- PGTM gain is applied before optional profile RGB clamp.
|
||||
- Table lookup uses `tableInput * MapPointsN`.
|
||||
- Embedded PGTM can be wrapped by `DngPgtmDiagnostic` for temporary debug bands.
|
||||
|
||||
### Diagnostics
|
||||
|
||||
File:
|
||||
|
||||
- `app/src/main/java/com/hinnka/mycamera/raw/DngPgtmDiagnostic.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- Centralized temporary PGTM diagnostic band configuration.
|
||||
- Default is disabled:
|
||||
- `PGTM_DIAGNOSTIC_BAND_INDEX = 0`
|
||||
- `PGTM_VISUAL_OVERLAY_MODE = 0`
|
||||
- Fine bands cover `0.080..0.140` in `0.005` increments.
|
||||
|
||||
### Removed Offline Patcher
|
||||
|
||||
Files:
|
||||
|
||||
- Deleted `app/src/main/java/com/hinnka/mycamera/raw/DngProfileGainTableMapPatcher.kt`
|
||||
- Updated `app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt`
|
||||
|
||||
Main changes:
|
||||
|
||||
- Removed debug rewrite of existing DNG PGTM during RAW preview refresh.
|
||||
- PGTM generation now stays in-memory and follows the same path as the UI `rawGooglePixelToneMap` switch.
|
||||
|
||||
## DNG Samples Recomputed
|
||||
|
||||
The old synthetic "Pixel samples" test was replaced with explicit DNG-derived fixtures in:
|
||||
|
||||
- `app/src/test/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGeneratorTest.kt`
|
||||
|
||||
Fixtures currently used:
|
||||
|
||||
- `PXL_20260628_175619159.RAW-02.ORIGINAL..dng`
|
||||
- baseline `0.99`
|
||||
- embedded PGTM weight sum `0.5074623`
|
||||
- embedded input headroom `1.0079140`
|
||||
- RIMM stats:
|
||||
- p10 `0.337668`
|
||||
- p50 `0.428147`
|
||||
- p90 `0.556421`
|
||||
- p98 `0.622064`
|
||||
- highlight `0.237918`
|
||||
- tailP95 `1.769715`
|
||||
- tailP98 `1.848588`
|
||||
- tailP99 `1.960254`
|
||||
- maxInput `3.247468`
|
||||
|
||||
- `PXL_20260630_100508552.RAW-02.ORIGINAL..dng`
|
||||
- baseline `1.38`
|
||||
- embedded PGTM weight sum `0.6550936`
|
||||
- embedded input headroom `1.7050014`
|
||||
- RIMM stats:
|
||||
- p10 `0.322686`
|
||||
- p50 `0.387230`
|
||||
- p90 `0.493896`
|
||||
- p98 `0.552372`
|
||||
- highlight `0.213364`
|
||||
- tailP95 `1.592500`
|
||||
- tailP98 `1.797323`
|
||||
- tailP99 `1.881310`
|
||||
- maxInput `1.991887`
|
||||
|
||||
- `PXL_20260629_213614190.RAW-02.ORIGINAL..dng`
|
||||
- baseline `1.40`
|
||||
- embedded PGTM weight sum `0.7948943`
|
||||
- embedded input headroom `2.0977387`
|
||||
- RIMM stats:
|
||||
- p10 `0.270184`
|
||||
- p50 `0.340886`
|
||||
- p90 `0.418926`
|
||||
- p98 `0.456479`
|
||||
- highlight `0.012236`
|
||||
- tailP95 `0.920819`
|
||||
- tailP98 `1.325456`
|
||||
- tailP99 `1.543746`
|
||||
- maxInput `4.766730`
|
||||
|
||||
- `PXL_20260702_144246096.RAW-02.ORIGINAL..dng`
|
||||
- baseline `1.46`
|
||||
- embedded PGTM weight sum `0.6642112`
|
||||
- embedded input headroom `1.8273006`
|
||||
- RIMM stats:
|
||||
- p10 `0.272827`
|
||||
- p50 `0.344414`
|
||||
- p90 `0.406222`
|
||||
- p98 `0.429191`
|
||||
- highlight `0.038032`
|
||||
- tailP95 `0.998236`
|
||||
- tailP98 `1.243947`
|
||||
- tailP99 `1.443504`
|
||||
- maxInput `2.448398`
|
||||
|
||||
The analysis script used locally during debugging was:
|
||||
|
||||
```bash
|
||||
uv run python /private/tmp/analyze_google_pgtm.py /Users/zhoubinjia/Downloads/PXL_20260702_144246096.RAW-02.ORIGINAL..dng
|
||||
```
|
||||
|
||||
The script was temporary and is not committed.
|
||||
|
||||
## Test Coverage
|
||||
|
||||
Commands run successfully on this branch:
|
||||
|
||||
```bash
|
||||
./gradlew testDefaultDebugUnitTest --tests com.hinnka.mycamera.raw.DngHdrProfileGainTableGeneratorTest
|
||||
./gradlew compileDefaultDebugKotlin
|
||||
./gradlew testDefaultDebugUnitTest
|
||||
```
|
||||
|
||||
The generator tests now include:
|
||||
|
||||
- DNG-derived RIMM fixture matching against embedded Pixel PGTM weight/headroom.
|
||||
- Keycap low-range output and slope checks around table input `0.080..0.140`.
|
||||
- Monotonic output checks.
|
||||
- Brightness reversal checks.
|
||||
- Highlight shoulder ordering checks.
|
||||
- Google HDR ProfileToneCurve samples.
|
||||
|
||||
## Notes For Continued Debugging
|
||||
|
||||
- If halo still appears visually, use `DngPgtmDiagnostic` to enable visual overlay or isolate one table-input band at a time. Keep diagnostic constants disabled before committing production changes.
|
||||
- The main live/UI path is now the source of truth. Avoid reintroducing file-level DNG rewrites unless full DNG color/profile metadata is parsed and it is proven to be byte-for-byte equivalent to the UI path.
|
||||
- Lightroom desktop/mobile was observed to ignore PGTM in the tested sentinel DNGs, while the app and system gallery applied it. Use the app/system gallery for PGTM render validation.
|
||||
- `app/build.gradle.kts` had an unrelated pre-existing version change in the worktree before this branch was created. It is intentionally not part of this PGTM commit.
|
||||
Reference in new issue
Block a user