feat: new HDR gainmap
This commit is contained in:
1 parent
2dc800bcc2
commit
876153a1d7
26 files changed
+1255
-1175
No files matched your search
@@ -198,7 +198,7 @@ data class UserPreferences(
|
||||
val videoStabilizationMode: com.hinnka.mycamera.video.VideoStabilizationMode = com.hinnka.mycamera.video.VideoStabilizationMode.OIS,
|
||||
val videoTorchEnabled: Boolean = false,
|
||||
val videoCodec: com.hinnka.mycamera.video.VideoCodec = com.hinnka.mycamera.video.VideoCodec.H264,
|
||||
val autoEnableHdr: Boolean = false,
|
||||
val autoEnableHdr: Boolean = true,
|
||||
val phantomMode: Boolean = false,
|
||||
val phantomButtonHidden: Boolean = false,
|
||||
val launchCameraOnPhantomMode: Boolean = false,
|
||||
@@ -609,7 +609,7 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
videoCodec = com.hinnka.mycamera.video.VideoCodec.valueOf(
|
||||
preferences[VIDEO_CODEC] ?: com.hinnka.mycamera.video.VideoCodec.H264.name
|
||||
),
|
||||
autoEnableHdr = preferences[AUTO_ENABLE_HDR_FOR_HDR_CAPTURE] ?: false,
|
||||
autoEnableHdr = preferences[AUTO_ENABLE_HDR_FOR_HDR_CAPTURE] ?: true,
|
||||
phantomMode = preferences[PHANTOM_MODE] ?: false,
|
||||
phantomButtonHidden = preferences[PHANTOM_BUTTON_HIDDEN] ?: false,
|
||||
launchCameraOnPhantomMode = preferences[LAUNCH_CAMERA_ON_PHANTOM_MODE] ?: false,
|
||||
|
||||
@@ -2003,6 +2003,11 @@ object GalleryManager {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.lutLuminanceGainMap?.bitmap?.let {
|
||||
if (!it.isRecycled) {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.sdrBase?.let {
|
||||
if (it !== bitmap && !it.isRecycled) {
|
||||
it.recycle()
|
||||
@@ -2912,6 +2917,11 @@ object GalleryManager {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.lutLuminanceGainMap?.bitmap?.let {
|
||||
if (!it.isRecycled) {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.sdrBase?.let {
|
||||
if (it !== bitmap && !it.isRecycled) {
|
||||
it.recycle()
|
||||
@@ -3351,6 +3361,11 @@ object GalleryManager {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.lutLuminanceGainMap?.bitmap?.let {
|
||||
if (!it.isRecycled) {
|
||||
it.recycle()
|
||||
}
|
||||
}
|
||||
preparedUltraHdrSource?.sdrBase?.let {
|
||||
if (it !== bitmap && !it.isRecycled) {
|
||||
it.recycle()
|
||||
|
||||
@@ -14,8 +14,11 @@ import com.hinnka.mycamera.frame.FrameRenderer
|
||||
import com.hinnka.mycamera.frame.FrameTemplate
|
||||
import com.hinnka.mycamera.hdr.GainmapResult
|
||||
import com.hinnka.mycamera.hdr.GainmapSourceSet
|
||||
import com.hinnka.mycamera.hdr.HlgImageProcessor
|
||||
import com.hinnka.mycamera.hdr.HdrBuffer
|
||||
import com.hinnka.mycamera.hdr.HdrBufferEncoding
|
||||
import com.hinnka.mycamera.hdr.LuminanceGainMap
|
||||
import com.hinnka.mycamera.hdr.LuminanceGainMapEncoding
|
||||
import com.hinnka.mycamera.hdr.RawGainmapMath
|
||||
import com.hinnka.mycamera.hdr.SourceKind
|
||||
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
|
||||
import com.hinnka.mycamera.lut.ColorCorrectionPipelineResolver
|
||||
@@ -49,7 +52,6 @@ class PhotoProcessor(
|
||||
private val depthBokehProcessor: DepthBokehProcessor,
|
||||
private val userPreferencesRepository: UserPreferencesRepository,
|
||||
) {
|
||||
private val hlgImageProcessor = HlgImageProcessor()
|
||||
private val colorCorrectionPipelineResolver = ColorCorrectionPipelineResolver(lutManager)
|
||||
|
||||
data class HdrFrameOutput(
|
||||
@@ -149,6 +151,7 @@ class PhotoProcessor(
|
||||
val finalChromaNoiseReduction =
|
||||
metadata.chromaNoiseReduction ?: (if (metadata.isImported) 0f else chromaNoiseReduction)
|
||||
|
||||
var lutLuminanceGainBitmap: Bitmap? = null
|
||||
val sdrBitmap = processBitmap(
|
||||
context = context,
|
||||
photoId = photoId,
|
||||
@@ -158,10 +161,28 @@ class PhotoProcessor(
|
||||
noiseReduction = finalNoiseReduction,
|
||||
chromaNoiseReduction = finalChromaNoiseReduction,
|
||||
useComputationalAperture = true,
|
||||
applyFrameWatermark = false
|
||||
applyFrameWatermark = false,
|
||||
onLutLuminanceGainMap = { lutLuminanceGainBitmap = it },
|
||||
lutLuminanceGainDownsample = RawGainmapMath.DOWNSAMPLE,
|
||||
)
|
||||
source.sdrBase.recycle()
|
||||
source = source.copy(sdrBase = sdrBitmap)
|
||||
lutLuminanceGainBitmap = lutLuminanceGainBitmap?.let {
|
||||
applyCrop(it, metadata, "ai_lut_luminance_gain")
|
||||
}
|
||||
lutLuminanceGainBitmap = lutLuminanceGainBitmap?.let {
|
||||
alignLutLuminanceGainMapToSdr(sdrBitmap, it)
|
||||
}
|
||||
val previousSdrBase = source.sdrBase
|
||||
val previousLutLuminanceGainMap = source.lutLuminanceGainMap?.bitmap
|
||||
source = source.copy(
|
||||
sdrBase = sdrBitmap,
|
||||
lutLuminanceGainMap = lutLuminanceGainBitmap?.let {
|
||||
LuminanceGainMap(it, LuminanceGainMapEncoding.LINEAR_RATIO)
|
||||
},
|
||||
)
|
||||
if (previousLutLuminanceGainMap?.isRecycled == false) {
|
||||
previousLutLuminanceGainMap.recycle()
|
||||
}
|
||||
if (!previousSdrBase.isRecycled) previousSdrBase.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,10 +222,6 @@ class PhotoProcessor(
|
||||
return null
|
||||
}
|
||||
|
||||
fun hasDeferredHlgSource(metadata: MediaMetadata): Boolean {
|
||||
return hlgImageProcessor.isHlgCapture(metadata)
|
||||
}
|
||||
|
||||
private fun readDisplayHdrSdrRatio(): Float = GalleryManager.hdrSdrRatio
|
||||
|
||||
suspend fun prepareUltraHdrSourceFromRawResult(
|
||||
@@ -258,27 +275,40 @@ class PhotoProcessor(
|
||||
photoId?.let { id -> GalleryManager.saveBokehPhoto(context, id, sdrBitmap) }
|
||||
}
|
||||
|
||||
sdrBitmap = lutImageProcessor.applyLutStack(
|
||||
val lutStackResult = lutImageProcessor.applyLutStackWithLuminanceGain(
|
||||
sdrBitmap,
|
||||
isHlgInput = false,
|
||||
colorCorrection.baselineLayer,
|
||||
colorCorrection.creativeLayer,
|
||||
0f,
|
||||
noiseReductionValue = 0f,
|
||||
chromaNoiseReductionValue = 0f
|
||||
chromaNoiseReductionValue = 0f,
|
||||
luminanceGainDownsample = RawGainmapMath.DOWNSAMPLE,
|
||||
)
|
||||
sdrBitmap = lutStackResult.bitmap
|
||||
var lutLuminanceGainBitmap = lutStackResult.luminanceGainMap
|
||||
|
||||
hdrReferenceBitmap = hdrReferenceBitmap?.let { alignHdrReferenceSizeToSdr(sdrBitmap, it, "raw_pre_crop") }
|
||||
lutLuminanceGainBitmap = lutLuminanceGainBitmap?.let {
|
||||
applyCrop(it, metadata, "raw_lut_luminance_gain")
|
||||
}
|
||||
sdrBitmap = applyCrop(sdrBitmap, metadata, "raw_sdr")
|
||||
hdrReferenceBitmap = hdrReferenceBitmap?.let { applyCrop(it, metadata, "raw_hdr") }
|
||||
hdrReferenceBitmap = hdrReferenceBitmap?.let { alignHdrReferenceSizeToSdr(sdrBitmap, it, "raw_post_crop") }
|
||||
lutLuminanceGainBitmap = lutLuminanceGainBitmap?.let {
|
||||
alignLutLuminanceGainMapToSdr(sdrBitmap, it)
|
||||
}
|
||||
|
||||
GainmapSourceSet(
|
||||
sdrBase = sdrBitmap,
|
||||
lutLuminanceGainMap = lutLuminanceGainBitmap?.let {
|
||||
LuminanceGainMap(it, LuminanceGainMapEncoding.LINEAR_RATIO)
|
||||
},
|
||||
hdrReference = hdrReferenceBitmap?.let {
|
||||
HdrBuffer(
|
||||
bitmap = it,
|
||||
description = "raw_scene_normalized"
|
||||
encoding = HdrBufferEncoding.LINEAR_SRGB,
|
||||
description = "raw_linear_srgb_baseline_acr3_linear",
|
||||
)
|
||||
},
|
||||
sourceKind = SourceKind.RAW,
|
||||
@@ -376,6 +406,23 @@ class PhotoProcessor(
|
||||
return scaled
|
||||
}
|
||||
|
||||
private fun alignLutLuminanceGainMapToSdr(sdrBitmap: Bitmap, gainMap: Bitmap): Bitmap {
|
||||
val targetWidth = ((sdrBitmap.width + RawGainmapMath.DOWNSAMPLE - 1) /
|
||||
RawGainmapMath.DOWNSAMPLE).coerceAtLeast(1)
|
||||
val targetHeight = ((sdrBitmap.height + RawGainmapMath.DOWNSAMPLE - 1) /
|
||||
RawGainmapMath.DOWNSAMPLE).coerceAtLeast(1)
|
||||
if (gainMap.width == targetWidth && gainMap.height == targetHeight) return gainMap
|
||||
|
||||
PLog.d(
|
||||
"PhotoProcessor",
|
||||
"Align LUT luminance sidecar ${gainMap.width}x${gainMap.height} -> " +
|
||||
"${targetWidth}x$targetHeight"
|
||||
)
|
||||
val aligned = Bitmap.createScaledBitmap(gainMap, targetWidth, targetHeight, true)
|
||||
if (aligned !== gainMap && !gainMap.isRecycled) gainMap.recycle()
|
||||
return aligned
|
||||
}
|
||||
|
||||
private fun cropHdrReferenceToSdrAspect(
|
||||
sdrBitmap: Bitmap,
|
||||
hdrReferenceBitmap: Bitmap,
|
||||
@@ -670,6 +717,8 @@ class PhotoProcessor(
|
||||
chromaNoiseReduction: Float = 0f,
|
||||
useComputationalAperture: Boolean = false,
|
||||
applyFrameWatermark: Boolean = true,
|
||||
onLutLuminanceGainMap: ((Bitmap?) -> Unit)? = null,
|
||||
lutLuminanceGainDownsample: Int = 1,
|
||||
): Bitmap = withContext(Dispatchers.IO) {
|
||||
var result = input
|
||||
val finalSharpening = metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening)
|
||||
@@ -693,15 +742,30 @@ class PhotoProcessor(
|
||||
}
|
||||
|
||||
// 1. 应用 LUT
|
||||
result = lutImageProcessor.applyLutStack(
|
||||
result,
|
||||
isHlgInput = shouldDecodeHlgInput(metadata),
|
||||
colorCorrection.baselineLayer,
|
||||
colorCorrection.creativeLayer,
|
||||
finalSharpening,
|
||||
finalNoiseReduction,
|
||||
finalChromaNoiseReduction
|
||||
)
|
||||
if (onLutLuminanceGainMap != null) {
|
||||
val lutStackResult = lutImageProcessor.applyLutStackWithLuminanceGain(
|
||||
result,
|
||||
isHlgInput = shouldDecodeHlgInput(metadata),
|
||||
colorCorrection.baselineLayer,
|
||||
colorCorrection.creativeLayer,
|
||||
finalSharpening,
|
||||
finalNoiseReduction,
|
||||
finalChromaNoiseReduction,
|
||||
luminanceGainDownsample = lutLuminanceGainDownsample,
|
||||
)
|
||||
result = lutStackResult.bitmap
|
||||
onLutLuminanceGainMap(lutStackResult.luminanceGainMap)
|
||||
} else {
|
||||
result = lutImageProcessor.applyLutStack(
|
||||
result,
|
||||
isHlgInput = shouldDecodeHlgInput(metadata),
|
||||
colorCorrection.baselineLayer,
|
||||
colorCorrection.creativeLayer,
|
||||
finalSharpening,
|
||||
finalNoiseReduction,
|
||||
finalChromaNoiseReduction
|
||||
)
|
||||
}
|
||||
|
||||
result = applyCrop(result, metadata, "bitmap")
|
||||
if (applyFrameWatermark) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import kotlin.math.ln
|
||||
|
||||
object EstimatedSdrGainmapMath {
|
||||
fun encodedSrgbLuma(red: Float, green: Float, blue: Float): Float {
|
||||
return (LUMA_RED * red + LUMA_GREEN * green + LUMA_BLUE * blue).coerceIn(0.0f, 1.0f)
|
||||
}
|
||||
|
||||
fun estimateGainRatio(
|
||||
encodedSrgbLuma: Float,
|
||||
fullHdrRatio: Float,
|
||||
maxGainRatio: Float,
|
||||
): Float {
|
||||
val targetRatio = fullHdrRatio.coerceIn(MIN_GAIN_RATIO, maxGainRatio)
|
||||
val highlightWeight = smoothstep(
|
||||
GAIN_START_LUMA,
|
||||
GAIN_END_LUMA,
|
||||
encodedSrgbLuma,
|
||||
)
|
||||
return MIN_GAIN_RATIO + (targetRatio - MIN_GAIN_RATIO) * highlightWeight
|
||||
}
|
||||
|
||||
fun encodeRatio(ratio: Float, minGainRatio: Float, maxGainRatio: Float): Int {
|
||||
val logRatioSpan = ln(maxGainRatio / minGainRatio)
|
||||
return ((ln(ratio.coerceIn(minGainRatio, maxGainRatio) / minGainRatio) / logRatioSpan) * 255.0f)
|
||||
.toInt()
|
||||
.coerceIn(0, 255)
|
||||
}
|
||||
|
||||
private fun smoothstep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val t = ((value - edge0) / (edge1 - edge0)).coerceIn(0.0f, 1.0f)
|
||||
return t * t * (3.0f - 2.0f * t)
|
||||
}
|
||||
|
||||
const val GAIN_START_LUMA = 0.25f
|
||||
const val GAIN_END_LUMA = 1.0f
|
||||
|
||||
private const val MIN_GAIN_RATIO = 1.0f
|
||||
private const val LUMA_RED = 0.2126f
|
||||
private const val LUMA_GREEN = 0.7152f
|
||||
private const val LUMA_BLUE = 0.0722f
|
||||
}
|
||||
@@ -11,7 +11,8 @@ class EstimatedSdrGainmapProducer : GainmapProducer {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return null
|
||||
if (source.sourceKind != SourceKind.SDR_BITMAP) return null
|
||||
|
||||
val fullHdrRatio = source.displayHdrSdrRatio.takeIf { it > 1f } ?: DEFAULT_FULL_HDR_RATIO
|
||||
val fullHdrRatio = (source.displayHdrSdrRatio.takeIf { it > 1f } ?: DEFAULT_FULL_HDR_RATIO)
|
||||
.coerceIn(MIN_FULL_HDR_RATIO, MAX_GAIN_RATIO)
|
||||
val gainmapBitmap = createGainmapBitmap(source.sdrBase, fullHdrRatio, strength) ?: return null
|
||||
val gainmap = Gainmap(gainmapBitmap).apply {
|
||||
setRatioMin(MIN_GAIN_RATIO, MIN_GAIN_RATIO, MIN_GAIN_RATIO)
|
||||
@@ -43,21 +44,25 @@ class EstimatedSdrGainmapProducer : GainmapProducer {
|
||||
val srcY = ((y + 0.5f) * sdrBase.height / height).toInt().coerceIn(0, sdrBase.height - 1)
|
||||
for (x in 0 until width) {
|
||||
val srcX = ((x + 0.5f) * sdrBase.width / width).toInt().coerceIn(0, sdrBase.width - 1)
|
||||
val sample = ProgressiveGainmapMath.sampleSdr(sdrBase, srcX, srcY)
|
||||
val ratio = ProgressiveGainmapMath.progressiveToneRatio(
|
||||
sample = sample,
|
||||
val color = sdrBase.getColor(srcX, srcY)
|
||||
val encodedSrgbLuma = EstimatedSdrGainmapMath.encodedSrgbLuma(
|
||||
red = color.red(),
|
||||
green = color.green(),
|
||||
blue = color.blue(),
|
||||
)
|
||||
val ratio = EstimatedSdrGainmapMath.estimateGainRatio(
|
||||
encodedSrgbLuma = encodedSrgbLuma,
|
||||
fullHdrRatio = fullHdrRatio,
|
||||
maxGainRatio = MAX_GAIN_RATIO
|
||||
).let {
|
||||
HdrGainmapStrength.applyToRatio(it, MIN_GAIN_RATIO, MAX_GAIN_RATIO, strength)
|
||||
}
|
||||
val encoded = ProgressiveGainmapMath.encodeRatio(ratio, MIN_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
val encoded = EstimatedSdrGainmapMath.encodeRatio(ratio, MIN_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
pixels[index++] = encoded.toByte()
|
||||
}
|
||||
}
|
||||
|
||||
val blurred = ProgressiveGainmapMath.blurGainmap(pixels, width, height, BLUR_RADIUS)
|
||||
contents.copyPixelsFromBuffer(ByteBuffer.wrap(blurred))
|
||||
contents.copyPixelsFromBuffer(ByteBuffer.wrap(pixels))
|
||||
return contents
|
||||
}
|
||||
|
||||
@@ -66,7 +71,7 @@ class EstimatedSdrGainmapProducer : GainmapProducer {
|
||||
private const val MIN_GAIN_RATIO = 1.0f
|
||||
private const val MAX_GAIN_RATIO = 4.0f
|
||||
private const val EPSILON = 1e-4f
|
||||
private const val BLUR_RADIUS = 3
|
||||
private const val MIN_FULL_HDR_RATIO = 1.02f
|
||||
private const val DEFAULT_FULL_HDR_RATIO = 1.8f
|
||||
}
|
||||
}
|
||||
@@ -5,17 +5,32 @@ import android.graphics.Gainmap
|
||||
|
||||
enum class SourceKind {
|
||||
RAW,
|
||||
HLG_CAPTURE,
|
||||
SDR_BITMAP,
|
||||
}
|
||||
|
||||
enum class HdrBufferEncoding {
|
||||
LINEAR_SRGB,
|
||||
}
|
||||
|
||||
enum class LuminanceGainMapEncoding {
|
||||
LINEAR_RATIO,
|
||||
}
|
||||
|
||||
data class LuminanceGainMap(
|
||||
val bitmap: Bitmap,
|
||||
val encoding: LuminanceGainMapEncoding,
|
||||
)
|
||||
|
||||
data class HdrBuffer(
|
||||
val bitmap: Bitmap,
|
||||
val encoding: HdrBufferEncoding,
|
||||
val description: String? = null,
|
||||
)
|
||||
|
||||
data class GainmapSourceSet(
|
||||
val sdrBase: Bitmap,
|
||||
/** Pixel-aligned sidecar generated by the LUT stack from its before/after linear luminance. */
|
||||
val lutLuminanceGainMap: LuminanceGainMap? = null,
|
||||
val hdrReference: HdrBuffer? = null,
|
||||
val sourceKind: SourceKind,
|
||||
val confidence: Float = 1.0f,
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.hdr
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.ColorSpace
|
||||
import android.graphics.Gainmap
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLConfig
|
||||
@@ -21,7 +22,6 @@ import java.nio.ByteOrder
|
||||
import java.nio.FloatBuffer
|
||||
import java.nio.ShortBuffer
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.pow
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
@@ -32,9 +32,7 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
|
||||
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
|
||||
private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE
|
||||
private var computeProgram = 0
|
||||
private var blurHProgram = 0
|
||||
private var blurVProgram = 0
|
||||
private var rawLumaResidualProgram = 0
|
||||
private var vertexBuffer: FloatBuffer? = null
|
||||
private var texCoordBuffer: FloatBuffer? = null
|
||||
private var indexBuffer: ShortBuffer? = null
|
||||
@@ -42,13 +40,49 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
|
||||
override suspend fun build(source: GainmapSourceSet, strength: Float): GainmapResult? = withContext(dispatcher) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return@withContext null
|
||||
val config = configFor(source.sourceKind) ?: return@withContext null
|
||||
val hdrReference = source.hdrReference?.bitmap
|
||||
if (source.sourceKind != SourceKind.RAW) return@withContext null
|
||||
val config = RAW_CONFIG
|
||||
val hdrBuffer = source.hdrReference ?: return@withContext null
|
||||
val hdrReference = hdrBuffer.bitmap
|
||||
val sdrBase = source.sdrBase
|
||||
if (sdrBase.width <= 0 || sdrBase.height <= 0) {
|
||||
return@withContext null
|
||||
}
|
||||
if (config.requiresHdrReference && (hdrReference == null || hdrReference.width <= 0 || hdrReference.height <= 0)) {
|
||||
if (hdrReference.width <= 0 || hdrReference.height <= 0) {
|
||||
return@withContext null
|
||||
}
|
||||
if (hdrBuffer.encoding != HdrBufferEncoding.LINEAR_SRGB) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Rejecting RAW gainmap input: expected=${HdrBufferEncoding.LINEAR_SRGB}, actual=${hdrBuffer.encoding}"
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
val lutLuminanceGainMap = source.lutLuminanceGainMap
|
||||
val expectedColorSpace = ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB)
|
||||
val hdrColorSpace = hdrReference.colorSpace
|
||||
if (hdrReference.config != Bitmap.Config.RGBA_F16 || hdrColorSpace?.id != expectedColorSpace.id) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Rejecting RAW HDR reference bitmap: config=${hdrReference.config}, colorSpace=$hdrColorSpace"
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
if (sdrBase.colorSpace?.isSrgb != true) {
|
||||
PLog.e(TAG, "Rejecting RAW SDR base outside sRGB: colorSpace=${sdrBase.colorSpace}")
|
||||
return@withContext null
|
||||
}
|
||||
if (lutLuminanceGainMap?.encoding != LuminanceGainMapEncoding.LINEAR_RATIO ||
|
||||
lutLuminanceGainMap.bitmap.config != Bitmap.Config.RGBA_F16 ||
|
||||
lutLuminanceGainMap.bitmap.colorSpace?.id != expectedColorSpace.id
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Rejecting RAW LUT luminance sidecar: " +
|
||||
"encoding=${lutLuminanceGainMap?.encoding}, " +
|
||||
"config=${lutLuminanceGainMap?.bitmap?.config}, " +
|
||||
"colorSpace=${lutLuminanceGainMap?.bitmap?.colorSpace}"
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
if (!ensureInitialized()) return@withContext null
|
||||
@@ -56,7 +90,7 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
var result: GainmapResult? = null
|
||||
val elapsed = measureTimeMillis {
|
||||
result = runCatching {
|
||||
renderGainmap(source, sdrBase, hdrReference, config, strength)
|
||||
renderRawLumaResidualGainmap(source, sdrBase, hdrReference, config, strength)
|
||||
}.onFailure {
|
||||
PLog.e(TAG, "GPU gainmap failed for ${source.sourceKind}", it)
|
||||
}.getOrNull()
|
||||
@@ -65,67 +99,60 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
result
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the new linear-light RAW residual while keeping the LUT-rendered SDR RGB as the
|
||||
* playback color base. A single luminance gain is therefore encoded for all three channels.
|
||||
*/
|
||||
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
||||
private fun renderGainmap(
|
||||
private fun renderRawLumaResidualGainmap(
|
||||
source: GainmapSourceSet,
|
||||
sdrBase: Bitmap,
|
||||
hdrReference: Bitmap?,
|
||||
hdrReference: Bitmap,
|
||||
config: Config,
|
||||
strength: Float,
|
||||
): GainmapResult? {
|
||||
val width = downsampleDimension(sdrBase.width, config.downsample)
|
||||
val height = downsampleDimension(sdrBase.height, config.downsample)
|
||||
val maxGainRatio = resolveMaxGainRatio(source.sourceKind, hdrReference, config)
|
||||
val defaultFullHdrRatio = if (source.sourceKind == SourceKind.RAW) maxGainRatio else config.defaultFullHdrRatio
|
||||
val fullHdrRatio = (source.displayHdrSdrRatio.takeIf { it > 1f } ?: defaultFullHdrRatio)
|
||||
val fullHdrRatio = (source.displayHdrSdrRatio.takeIf { it > 1f } ?: config.defaultFullHdrRatio)
|
||||
.coerceAtLeast(config.minFullHdrRatio)
|
||||
.coerceAtMost(maxGainRatio)
|
||||
.coerceAtMost(config.maxGainRatio)
|
||||
|
||||
val sdrUpload = prepareUploadBitmap(sdrBase)
|
||||
if (hdrReference != null && (hdrReference.width != sdrBase.width || hdrReference.height != sdrBase.height)) {
|
||||
PLog.w(
|
||||
val lutLuminanceGainMap = source.lutLuminanceGainMap?.bitmap ?: return null
|
||||
if (hdrReference.width != sdrBase.width || hdrReference.height != sdrBase.height ||
|
||||
lutLuminanceGainMap.width != width || lutLuminanceGainMap.height != height
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"HDR reference size differs from SDR base: " +
|
||||
"source=${source.sourceKind}, sdr=${sdrBase.width}x${sdrBase.height}, " +
|
||||
"hdr=${hdrReference.width}x${hdrReference.height}; sampling will use normalized UV"
|
||||
"RAW residual inputs must be pixel-aligned: " +
|
||||
"lutGain=${lutLuminanceGainMap.width}x${lutLuminanceGainMap.height}, " +
|
||||
"gainmap=${width}x$height, " +
|
||||
"sdr=${sdrBase.width}x${sdrBase.height}, " +
|
||||
"hdr=${hdrReference.width}x${hdrReference.height}"
|
||||
)
|
||||
return null
|
||||
}
|
||||
val hdrUpload = hdrReference?.let { prepareUploadBitmap(it) }
|
||||
val sdrTexture = uploadBitmapTexture(sdrUpload.bitmap)
|
||||
val hdrTexture = hdrUpload?.let { uploadBitmapTexture(it.bitmap) } ?: sdrTexture
|
||||
val computeTarget = createRenderTarget(width, height)
|
||||
val blurTarget = createRenderTarget(width, height)
|
||||
val finalTarget = createRenderTarget(width, height)
|
||||
|
||||
val lutLuminanceGainUpload = prepareUploadBitmap(lutLuminanceGainMap)
|
||||
val sdrUpload = prepareUploadBitmap(sdrBase)
|
||||
val hdrUpload = prepareUploadBitmap(hdrReference)
|
||||
val lutLuminanceGainTexture = uploadBitmapTexture(lutLuminanceGainUpload.bitmap)
|
||||
val sdrTexture = uploadBitmapTexture(sdrUpload.bitmap)
|
||||
val hdrTexture = uploadBitmapTexture(hdrUpload.bitmap)
|
||||
val target = createRenderTarget(width, height)
|
||||
try {
|
||||
renderComputePass(
|
||||
target = computeTarget,
|
||||
renderRawLumaResidualPass(
|
||||
target = target,
|
||||
lutLuminanceGainTexture = lutLuminanceGainTexture,
|
||||
sdrTexture = sdrTexture,
|
||||
hdrTexture = hdrTexture,
|
||||
config = config,
|
||||
fullHdrRatio = fullHdrRatio,
|
||||
maxGainRatio = maxGainRatio,
|
||||
minGainRatio = config.minGainRatio,
|
||||
maxGainRatio = config.maxGainRatio,
|
||||
strength = strength,
|
||||
)
|
||||
renderBlurPass(
|
||||
program = blurHProgram,
|
||||
target = blurTarget,
|
||||
inputTexture = computeTarget.textureId,
|
||||
width = width,
|
||||
height = height,
|
||||
)
|
||||
renderBlurPass(
|
||||
program = blurVProgram,
|
||||
target = finalTarget,
|
||||
inputTexture = blurTarget.textureId,
|
||||
width = width,
|
||||
height = height,
|
||||
)
|
||||
|
||||
val gainmapBitmap = readAlphaBitmap(width, height) ?: return null
|
||||
val gainmap = Gainmap(gainmapBitmap).apply {
|
||||
setRatioMin(config.minGainRatio, config.minGainRatio, config.minGainRatio)
|
||||
setRatioMax(maxGainRatio, maxGainRatio, maxGainRatio)
|
||||
setRatioMax(config.maxGainRatio, config.maxGainRatio, config.maxGainRatio)
|
||||
setGamma(1.0f, 1.0f, 1.0f)
|
||||
setEpsilonSdr(EPSILON, EPSILON, EPSILON)
|
||||
setEpsilonHdr(EPSILON, EPSILON, EPSILON)
|
||||
@@ -134,108 +161,57 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
}
|
||||
return GainmapResult(gainmap, source.sourceKind, source.confidence)
|
||||
} finally {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(lutLuminanceGainTexture), 0)
|
||||
GLES30.glDeleteTextures(1, intArrayOf(sdrTexture), 0)
|
||||
if (hdrTexture != sdrTexture) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(hdrTexture), 0)
|
||||
}
|
||||
computeTarget.release()
|
||||
blurTarget.release()
|
||||
finalTarget.release()
|
||||
GLES30.glDeleteTextures(1, intArrayOf(hdrTexture), 0)
|
||||
target.release()
|
||||
lutLuminanceGainUpload.recycleIfTemporary()
|
||||
sdrUpload.recycleIfTemporary()
|
||||
hdrUpload?.recycleIfTemporary()
|
||||
hdrUpload.recycleIfTemporary()
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderRawLumaResidualPass(
|
||||
target: RenderTarget,
|
||||
lutLuminanceGainTexture: Int,
|
||||
sdrTexture: Int,
|
||||
hdrTexture: Int,
|
||||
minGainRatio: Float,
|
||||
maxGainRatio: Float,
|
||||
strength: Float,
|
||||
) {
|
||||
GLES30.glUseProgram(rawLumaResidualProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebufferId)
|
||||
GLES30.glViewport(0, 0, target.width, target.height)
|
||||
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lutLuminanceGainTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(rawLumaResidualProgram, "uLutLuminanceGainTexture"), 0)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sdrTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(rawLumaResidualProgram, "uSdrTexture"), 1)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE2)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdrTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(rawLumaResidualProgram, "uHdrTexture"), 2)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(rawLumaResidualProgram, "uMinGainRatio"),
|
||||
minGainRatio,
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(rawLumaResidualProgram, "uMaxGainRatio"),
|
||||
maxGainRatio,
|
||||
)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(rawLumaResidualProgram, "uOffset"), EPSILON)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(rawLumaResidualProgram, "uStrength"), strength)
|
||||
drawQuad(rawLumaResidualProgram)
|
||||
checkGlError("renderRawLumaResidualPass")
|
||||
}
|
||||
|
||||
private fun downsampleDimension(value: Int, downsample: Int): Int {
|
||||
val safeDownsample = downsample.coerceAtLeast(1)
|
||||
return ((value + safeDownsample - 1) / safeDownsample).coerceAtLeast(1)
|
||||
}
|
||||
|
||||
private fun renderComputePass(
|
||||
target: RenderTarget,
|
||||
sdrTexture: Int,
|
||||
hdrTexture: Int,
|
||||
config: Config,
|
||||
fullHdrRatio: Float,
|
||||
maxGainRatio: Float,
|
||||
strength: Float,
|
||||
) {
|
||||
GLES30.glUseProgram(computeProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebufferId)
|
||||
GLES30.glViewport(0, 0, target.width, target.height)
|
||||
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
|
||||
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sdrTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(computeProgram, "uSdrTexture"), 0)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdrTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(computeProgram, "uHdrTexture"), 1)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uFullHdrRatio"), fullHdrRatio)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uMinGainRatio"), config.minGainRatio)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uMaxGainRatio"), maxGainRatio)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uStrength"), strength)
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(computeProgram, "uLocalContrastTexelSize"),
|
||||
1f / target.width.toFloat(),
|
||||
1f / target.height.toFloat()
|
||||
)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(computeProgram, "uHasHdrReference"), if (config.requiresHdrReference) 1 else 0)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uBaseSceneLift"), config.baseSceneLift)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uGlobalSceneLift"), config.globalSceneLift)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uShoulderSceneLift"), config.shoulderSceneLift)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uGlobalStart"), config.globalStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uGlobalEnd"), config.globalEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uGlobalPower"), config.globalPower)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uDarkStart"), config.darkStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uDarkEnd"), config.darkEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uShoulderStart"), config.shoulderStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uShoulderEnd"), config.shoulderEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uShoulderPower"), config.shoulderPower)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uSaturationPenalty"), config.saturationPenalty)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceSceneStart"), config.referenceSceneStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceSceneEnd"), config.referenceSceneEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceScenePower"), config.referenceScenePower)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceSceneWeight"), config.referenceSceneWeight)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(computeProgram, "uReferenceSaturationPenalty"),
|
||||
config.referenceSaturationPenalty
|
||||
)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceTonalStart"), config.referenceTonalStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceTonalEnd"), config.referenceTonalEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceHdrStart"), config.referenceHdrStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceHdrEnd"), config.referenceHdrEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceDeltaStart"), config.referenceDeltaStart)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceDeltaEnd"), config.referenceDeltaEnd)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceHdrWeight"), config.referenceHdrWeight)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceDeltaWeight"), config.referenceDeltaWeight)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uReferenceExtraScale"), config.referenceExtraScale)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(computeProgram, "uReferenceDisplayMapWeight"),
|
||||
config.referenceDisplayMapWeight
|
||||
)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uNonBlackFloorLowEv"), config.nonBlackFloorLowEv)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uNonBlackFloorHighEv"), config.nonBlackFloorHighEv)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uMidtoneFeatureLift"), config.midtoneFeatureLift)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uDetailFeatureLift"), config.detailFeatureLift)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(computeProgram, "uBlueSkySuppression"), config.blueSkySuppression)
|
||||
drawQuad(computeProgram)
|
||||
checkGlError("renderComputePass")
|
||||
}
|
||||
|
||||
private fun renderBlurPass(program: Int, target: RenderTarget, inputTexture: Int, width: Int, height: Int) {
|
||||
GLES30.glUseProgram(program)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebufferId)
|
||||
GLES30.glViewport(0, 0, target.width, target.height)
|
||||
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTexture)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uInputTexture"), 0)
|
||||
GLES30.glUniform2f(GLES30.glGetUniformLocation(program, "uTexelSize"), 1f / width, 1f / height)
|
||||
drawQuad(program)
|
||||
checkGlError("renderBlurPass")
|
||||
}
|
||||
|
||||
private fun readAlphaBitmap(width: Int, height: Int): Bitmap? {
|
||||
val rgba = LargeDirectBuffer.allocate(width.toLong() * height.toLong() * 4L, "gainmap alpha readback")
|
||||
?: return null
|
||||
@@ -321,7 +297,7 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
0,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_RGBA8,
|
||||
width,
|
||||
height,
|
||||
0,
|
||||
@@ -386,11 +362,13 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
|
||||
initBuffers()
|
||||
val vertexShader = compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
|
||||
computeProgram = linkProgram(vertexShader, GAINMAP_FRAGMENT_SHADER, "gainmapCompute")
|
||||
blurHProgram = linkProgram(vertexShader, BLUR_H_FRAGMENT_SHADER, "gainmapBlurH")
|
||||
blurVProgram = linkProgram(vertexShader, BLUR_V_FRAGMENT_SHADER, "gainmapBlurV")
|
||||
rawLumaResidualProgram = linkProgram(
|
||||
vertexShader,
|
||||
RAW_LUMA_RESIDUAL_FRAGMENT_SHADER,
|
||||
"rawLumaResidual",
|
||||
)
|
||||
GLES30.glDeleteShader(vertexShader)
|
||||
isInitialized = computeProgram != 0 && blurHProgram != 0 && blurVProgram != 0
|
||||
isInitialized = rawLumaResidualProgram != 0
|
||||
return isInitialized
|
||||
}
|
||||
|
||||
@@ -469,164 +447,13 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
}
|
||||
}
|
||||
|
||||
private fun resolveMaxGainRatio(sourceKind: SourceKind, hdrReference: Bitmap?, config: Config): Float {
|
||||
if (sourceKind != SourceKind.RAW) return config.maxGainRatio
|
||||
return estimateRawMaxGainRatio(hdrReference, config.maxGainRatio)
|
||||
}
|
||||
|
||||
private fun estimateRawMaxGainRatio(hdrReference: Bitmap?, upperBound: Float): Float {
|
||||
val bitmap = hdrReference ?: return RAW_LOW_SCENE_MAX_GAIN_RATIO.coerceAtMost(upperBound)
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.isRecycled) {
|
||||
return RAW_LOW_SCENE_MAX_GAIN_RATIO.coerceAtMost(upperBound)
|
||||
}
|
||||
|
||||
val sampleColumns = RAW_CAPACITY_SAMPLE_GRID.coerceAtMost(bitmap.width)
|
||||
val sampleRows = RAW_CAPACITY_SAMPLE_GRID.coerceAtMost(bitmap.height)
|
||||
val signals = FloatArray(sampleColumns * sampleRows)
|
||||
var count = 0
|
||||
var overWhiteCount = 0
|
||||
|
||||
for (y in 0 until sampleRows) {
|
||||
val srcY = ((y + 0.5f) * bitmap.height / sampleRows).toInt().coerceIn(0, bitmap.height - 1)
|
||||
for (x in 0 until sampleColumns) {
|
||||
val srcX = ((x + 0.5f) * bitmap.width / sampleColumns).toInt().coerceIn(0, bitmap.width - 1)
|
||||
val color = bitmap.getColor(srcX, srcY)
|
||||
val r = color.red().coerceAtLeast(0f)
|
||||
val g = color.green().coerceAtLeast(0f)
|
||||
val b = color.blue().coerceAtLeast(0f)
|
||||
val luma = 0.2627f * r + 0.6780f * g + 0.0593f * b
|
||||
val signal = maxOf(luma, r, g, b)
|
||||
signals[count++] = signal
|
||||
if (signal > RAW_REFERENCE_WHITE) overWhiteCount++
|
||||
}
|
||||
}
|
||||
|
||||
if (count == 0) return RAW_LOW_SCENE_MAX_GAIN_RATIO.coerceAtMost(upperBound)
|
||||
java.util.Arrays.sort(signals, 0, count)
|
||||
val p90 = percentile(signals, count, 0.90f)
|
||||
val p995 = percentile(signals, count, 0.995f)
|
||||
val overWhiteFraction = overWhiteCount.toFloat() / count.toFloat()
|
||||
|
||||
val coverageWeight = gainmapSmoothstep(
|
||||
RAW_HIGH_COVERAGE_START,
|
||||
RAW_HIGH_COVERAGE_END,
|
||||
overWhiteFraction
|
||||
)
|
||||
val headroomWeight = gainmapSmoothstep(1.0f, RAW_HIGH_CAPACITY_P995, p995)
|
||||
val contrastWeight = gainmapSmoothstep(0.08f, 0.55f, p995 - p90)
|
||||
val highSceneWeight = (coverageWeight * maxOf(headroomWeight, contrastWeight * 0.35f))
|
||||
.coerceIn(0f, 1f)
|
||||
val capacityEv = RAW_LOW_SCENE_GAIN_EV +
|
||||
(RAW_HIGH_SCENE_GAIN_EV - RAW_LOW_SCENE_GAIN_EV) * highSceneWeight
|
||||
val ratio = 2.0.pow(capacityEv.toDouble()).toFloat()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"RAW gainmap capacity fit: overWhite=$overWhiteFraction, p90=$p90, p995=$p995, weight=$highSceneWeight, ratio=$ratio"
|
||||
)
|
||||
return ratio.coerceIn(RAW_LOW_SCENE_MAX_GAIN_RATIO, upperBound)
|
||||
}
|
||||
|
||||
private fun percentile(sortedValues: FloatArray, count: Int, percentile: Float): Float {
|
||||
if (count <= 0) return 0f
|
||||
val index = ((count - 1) * percentile).toInt().coerceIn(0, count - 1)
|
||||
return sortedValues[index]
|
||||
}
|
||||
|
||||
private fun gainmapSmoothstep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
if (edge0 == edge1) return if (value >= edge1) 1f else 0f
|
||||
val t = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
|
||||
return t * t * (3f - 2f * t)
|
||||
}
|
||||
|
||||
private fun configFor(sourceKind: SourceKind): Config? {
|
||||
return when (sourceKind) {
|
||||
SourceKind.RAW -> Config(
|
||||
maxGainRatio = RAW_HIGH_SCENE_MAX_GAIN_RATIO,
|
||||
defaultFullHdrRatio = RAW_LOW_SCENE_MAX_GAIN_RATIO,
|
||||
downsample = RAW_DOWNSAMPLE,
|
||||
requiresHdrReference = true,
|
||||
baseSceneLift = 0.035f,
|
||||
globalSceneLift = 0.16f,
|
||||
shoulderSceneLift = 0.09f,
|
||||
globalStart = 0.0f,
|
||||
globalEnd = 0.90f,
|
||||
darkStart = 0.0f,
|
||||
darkEnd = 0.08f,
|
||||
shoulderStart = 0.42f,
|
||||
shoulderEnd = 0.98f,
|
||||
shoulderPower = 1.55f,
|
||||
saturationPenalty = 0.12f,
|
||||
referenceSceneStart = 0.38f,
|
||||
referenceSceneEnd = 2.40f,
|
||||
referenceScenePower = 0.90f,
|
||||
referenceSceneWeight = 0.38f,
|
||||
referenceSaturationPenalty = 0.10f,
|
||||
referenceTonalStart = 0.05f,
|
||||
referenceTonalEnd = 0.90f,
|
||||
referenceHdrStart = 0.42f,
|
||||
referenceHdrEnd = 1.65f,
|
||||
referenceDeltaStart = 0.02f,
|
||||
referenceDeltaEnd = 0.55f,
|
||||
referenceHdrWeight = 0.35f,
|
||||
referenceDeltaWeight = 0.65f,
|
||||
referenceExtraScale = 0.76f,
|
||||
referenceDisplayMapWeight = 0.35f,
|
||||
nonBlackFloorLowEv = 0.22f,
|
||||
nonBlackFloorHighEv = 0.045f,
|
||||
midtoneFeatureLift = 0.18f,
|
||||
detailFeatureLift = 0.10f,
|
||||
blueSkySuppression = 0.50f,
|
||||
)
|
||||
SourceKind.HLG_CAPTURE -> Config(maxGainRatio = 3.5f, defaultFullHdrRatio = 1.45f, requiresHdrReference = true)
|
||||
SourceKind.SDR_BITMAP -> Config(
|
||||
maxGainRatio = 4.0f,
|
||||
defaultFullHdrRatio = 1.8f,
|
||||
minDisplayRatioForHdrTransition = 1.02f,
|
||||
requiresHdrReference = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private data class Config(
|
||||
val minGainRatio: Float = 1.0f,
|
||||
val minGainRatio: Float,
|
||||
val maxGainRatio: Float,
|
||||
val defaultFullHdrRatio: Float,
|
||||
val minFullHdrRatio: Float = 1.0f,
|
||||
val minDisplayRatioForHdrTransition: Float = 1.0f,
|
||||
val requiresHdrReference: Boolean,
|
||||
val downsample: Int = DOWNSAMPLE,
|
||||
val baseSceneLift: Float = 0.035f,
|
||||
val globalSceneLift: Float = 0.4f,
|
||||
val shoulderSceneLift: Float = 0.34f,
|
||||
val globalStart: Float = 0.02f,
|
||||
val globalEnd: Float = 0.96f,
|
||||
val globalPower: Float = 0.82f,
|
||||
val darkStart: Float = 0.0f,
|
||||
val darkEnd: Float = 0.02f,
|
||||
val shoulderStart: Float = 0.34f,
|
||||
val shoulderEnd: Float = 1.0f,
|
||||
val shoulderPower: Float = 1.35f,
|
||||
val saturationPenalty: Float = 0.10f,
|
||||
val referenceSceneStart: Float = 0.0f,
|
||||
val referenceSceneEnd: Float = 1.0f,
|
||||
val referenceScenePower: Float = 1.0f,
|
||||
val referenceSceneWeight: Float = 0.0f,
|
||||
val referenceSaturationPenalty: Float = 0.0f,
|
||||
val referenceTonalStart: Float = 0.05f,
|
||||
val referenceTonalEnd: Float = 0.98f,
|
||||
val referenceHdrStart: Float = 0.65f,
|
||||
val referenceHdrEnd: Float = 2.0f,
|
||||
val referenceDeltaStart: Float = 0.01f,
|
||||
val referenceDeltaEnd: Float = 0.28f,
|
||||
val referenceHdrWeight: Float = 0.35f,
|
||||
val referenceDeltaWeight: Float = 0.65f,
|
||||
val referenceExtraScale: Float = 0.82f,
|
||||
val referenceDisplayMapWeight: Float = 1.0f,
|
||||
val nonBlackFloorLowEv: Float = 0.0f,
|
||||
val nonBlackFloorHighEv: Float = 0.0f,
|
||||
val midtoneFeatureLift: Float = 0.0f,
|
||||
val detailFeatureLift: Float = 0.0f,
|
||||
val blueSkySuppression: Float = 0.0f,
|
||||
val downsample: Int,
|
||||
)
|
||||
|
||||
private data class RenderTarget(
|
||||
@@ -654,22 +481,17 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "GpuReferenceGainmapProducer"
|
||||
private const val DOWNSAMPLE = 4
|
||||
private const val RAW_DOWNSAMPLE = 2
|
||||
private const val RAW_CAPACITY_SAMPLE_GRID = 48
|
||||
private const val RAW_REFERENCE_WHITE = 1.0f
|
||||
// Fitted from inspected Google DNGs:
|
||||
// low scenes stay around 0.04%-0.11% over-white samples; the high-headroom scene is about 3.96%.
|
||||
private const val RAW_HIGH_COVERAGE_START = 0.002f
|
||||
private const val RAW_HIGH_COVERAGE_END = 0.035f
|
||||
private const val RAW_HIGH_CAPACITY_P995 = 1.10f
|
||||
// 2^0.681828 from low-headroom Google DNG preview gainmaps.
|
||||
private const val RAW_LOW_SCENE_GAIN_EV = 0.681828f
|
||||
private const val RAW_DOWNSAMPLE = RawGainmapMath.DOWNSAMPLE
|
||||
private const val RAW_MIN_GAIN_RATIO = RawGainmapMath.MIN_GAIN_RATIO
|
||||
private const val RAW_MAX_GAIN_RATIO = RawGainmapMath.MAX_GAIN_RATIO
|
||||
private const val RAW_LOW_SCENE_MAX_GAIN_RATIO = 1.6033f
|
||||
// 2^1.941732 from the high-headroom Google DNG preview gainmap.
|
||||
private const val RAW_HIGH_SCENE_GAIN_EV = 1.941732f
|
||||
private const val RAW_HIGH_SCENE_MAX_GAIN_RATIO = 3.8417f
|
||||
private const val EPSILON = 1e-4f
|
||||
private const val EPSILON = RawGainmapMath.OFFSET
|
||||
private val RAW_CONFIG = Config(
|
||||
minGainRatio = RAW_MIN_GAIN_RATIO,
|
||||
maxGainRatio = RAW_MAX_GAIN_RATIO,
|
||||
defaultFullHdrRatio = RAW_LOW_SCENE_MAX_GAIN_RATIO,
|
||||
downsample = RAW_DOWNSAMPLE,
|
||||
)
|
||||
private val VERTICES = floatArrayOf(-1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f)
|
||||
private val TEX_COORDS = floatArrayOf(0f, 1f, 1f, 1f, 0f, 0f, 1f, 0f)
|
||||
private val DRAW_ORDER = shortArrayOf(0, 1, 2, 1, 3, 2)
|
||||
@@ -685,54 +507,29 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val GAINMAP_FRAGMENT_SHADER = """
|
||||
/**
|
||||
* RAW path: consume the LUT stack's linear-light luminance sidecar, transfer it onto the
|
||||
* 0..1 base of the linear-sRGB HDR reference, preserve the >1 headroom, and encode one
|
||||
* shared gain. Playback retains both LUT color and LUT luminance rendering.
|
||||
*/
|
||||
private val RAW_LUMA_RESIDUAL_FRAGMENT_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uLutLuminanceGainTexture;
|
||||
uniform sampler2D uSdrTexture;
|
||||
uniform sampler2D uHdrTexture;
|
||||
uniform float uFullHdrRatio;
|
||||
uniform float uMinGainRatio;
|
||||
uniform float uMaxGainRatio;
|
||||
uniform float uOffset;
|
||||
uniform float uStrength;
|
||||
uniform vec2 uLocalContrastTexelSize;
|
||||
uniform int uHasHdrReference;
|
||||
uniform float uBaseSceneLift;
|
||||
uniform float uGlobalSceneLift;
|
||||
uniform float uShoulderSceneLift;
|
||||
uniform float uGlobalStart;
|
||||
uniform float uGlobalEnd;
|
||||
uniform float uGlobalPower;
|
||||
uniform float uDarkStart;
|
||||
uniform float uDarkEnd;
|
||||
uniform float uShoulderStart;
|
||||
uniform float uShoulderEnd;
|
||||
uniform float uShoulderPower;
|
||||
uniform float uSaturationPenalty;
|
||||
uniform float uReferenceSceneStart;
|
||||
uniform float uReferenceSceneEnd;
|
||||
uniform float uReferenceScenePower;
|
||||
uniform float uReferenceSceneWeight;
|
||||
uniform float uReferenceSaturationPenalty;
|
||||
uniform float uReferenceTonalStart;
|
||||
uniform float uReferenceTonalEnd;
|
||||
uniform float uReferenceHdrStart;
|
||||
uniform float uReferenceHdrEnd;
|
||||
uniform float uReferenceDeltaStart;
|
||||
uniform float uReferenceDeltaEnd;
|
||||
uniform float uReferenceHdrWeight;
|
||||
uniform float uReferenceDeltaWeight;
|
||||
uniform float uReferenceExtraScale;
|
||||
uniform float uReferenceDisplayMapWeight;
|
||||
uniform float uNonBlackFloorLowEv;
|
||||
uniform float uNonBlackFloorHighEv;
|
||||
uniform float uMidtoneFeatureLift;
|
||||
uniform float uDetailFeatureLift;
|
||||
uniform float uBlueSkySuppression;
|
||||
|
||||
float srgbToLinear(float value) {
|
||||
return value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4);
|
||||
float safeValue = max(value, 0.0);
|
||||
return safeValue <= 0.04045
|
||||
? safeValue / 12.92
|
||||
: pow((safeValue + 0.055) / 1.055, 2.4);
|
||||
}
|
||||
|
||||
vec3 srgbToLinear(vec3 value) {
|
||||
@@ -743,170 +540,42 @@ class GpuReferenceGainmapProducer : GainmapProducer {
|
||||
);
|
||||
}
|
||||
|
||||
float sdrLumaAt(vec2 uv) {
|
||||
vec3 linearRgb = srgbToLinear(texture(uSdrTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb);
|
||||
return max(dot(linearRgb, vec3(0.2126, 0.7152, 0.0722)), 0.0);
|
||||
}
|
||||
|
||||
float gainmapSmoothstep(float edge0, float edge1, float x) {
|
||||
float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
|
||||
return t * t * (3.0 - 2.0 * t);
|
||||
}
|
||||
|
||||
float localLumaContrast(vec2 uv, float centerLuma) {
|
||||
vec2 texel = max(uLocalContrastTexelSize, vec2(0.000001));
|
||||
float left = sdrLumaAt(uv - vec2(texel.x, 0.0));
|
||||
float right = sdrLumaAt(uv + vec2(texel.x, 0.0));
|
||||
float up = sdrLumaAt(uv - vec2(0.0, texel.y));
|
||||
float down = sdrLumaAt(uv + vec2(0.0, texel.y));
|
||||
float averageDelta = (
|
||||
abs(left - centerLuma) +
|
||||
abs(right - centerLuma) +
|
||||
abs(up - centerLuma) +
|
||||
abs(down - centerLuma)
|
||||
) * 0.25;
|
||||
return clamp(averageDelta / max(centerLuma + 0.05, 0.08), 0.0, 1.0);
|
||||
}
|
||||
|
||||
float displayLuma(float sceneLuma, float fullHdrRatio) {
|
||||
float effectiveHeadroom = clamp(fullHdrRatio, 1.15, 3.2);
|
||||
if (sceneLuma <= 1.0) return max(sceneLuma, 0.0);
|
||||
float systemGamma = clamp(1.03 + (effectiveHeadroom - 1.0) * 0.16, 1.0, 1.25);
|
||||
float normalized = pow(max(sceneLuma, 0.0), systemGamma);
|
||||
float aboveWhite = max(normalized - 1.0, 0.0);
|
||||
float compressedBoost = 1.0 - exp(-aboveWhite * 0.85);
|
||||
return 1.0 + (effectiveHeadroom - 1.0) * compressedBoost;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 sdrEncoded = texture(uSdrTexture, vTexCoord).rgb;
|
||||
vec3 sdr = srgbToLinear(sdrEncoded);
|
||||
float sdrLuma = max(dot(sdr, vec3(0.2126, 0.7152, 0.0722)), 0.0);
|
||||
float maxChannel = max(sdr.r, max(sdr.g, sdr.b));
|
||||
float minChannel = min(sdr.r, min(sdr.g, sdr.b));
|
||||
float saturation = maxChannel <= 0.0001 ? 0.0 : clamp((maxChannel - minChannel) / maxChannel, 0.0, 1.0);
|
||||
float localContrast = localLumaContrast(vTexCoord, sdrLuma);
|
||||
vec3 sdrLinear = srgbToLinear(texture(uSdrTexture, vTexCoord).rgb);
|
||||
vec3 hdrLinear = max(texture(uHdrTexture, vTexCoord).rgb, vec3(0.0));
|
||||
const vec3 LINEAR_SRGB_LUMA = vec3(0.2126, 0.7152, 0.0722);
|
||||
float sdrLuma = max(dot(sdrLinear, LINEAR_SRGB_LUMA), 0.0);
|
||||
float hdrLuma = max(dot(hdrLinear, LINEAR_SRGB_LUMA), 0.0);
|
||||
float lutLumaGain = max(
|
||||
texture(uLutLuminanceGainTexture, vTexCoord).r,
|
||||
0.0
|
||||
);
|
||||
float hdrBaseLuma = min(hdrLuma, 1.0);
|
||||
float hdrHeadroomLuma = max(hdrLuma - 1.0, 0.0);
|
||||
float lutAdjustedHdrBaseLuma = max(
|
||||
(hdrBaseLuma + uOffset) * lutLumaGain - uOffset,
|
||||
0.0
|
||||
);
|
||||
float targetHdrLuma = lutAdjustedHdrBaseLuma + hdrHeadroomLuma;
|
||||
float ratio = clamp(
|
||||
(targetHdrLuma + uOffset) / (sdrLuma + uOffset),
|
||||
uMinGainRatio,
|
||||
uMaxGainRatio
|
||||
);
|
||||
|
||||
float displayHeadroom = clamp(uFullHdrRatio, 1.1, uMaxGainRatio);
|
||||
float tonalPosition = max(sdrLuma * 0.72 + maxChannel * 0.28, 0.0);
|
||||
float globalRamp = pow(gainmapSmoothstep(uGlobalStart, uGlobalEnd, tonalPosition), uGlobalPower);
|
||||
float shoulderRamp = pow(gainmapSmoothstep(uShoulderStart, uShoulderEnd, maxChannel), uShoulderPower);
|
||||
float chromaPenalty = 1.0 - saturation * uSaturationPenalty;
|
||||
float darkGate = gainmapSmoothstep(uDarkStart, uDarkEnd, tonalPosition);
|
||||
float blueDominance = clamp((sdr.b - max(sdr.r, sdr.g)) / max(maxChannel, 0.0001), 0.0, 1.0);
|
||||
float lowContrastWeight = 1.0 - gainmapSmoothstep(0.025, 0.12, localContrast);
|
||||
float blueSkyMask = clamp(
|
||||
gainmapSmoothstep(0.32, 0.74, saturation) *
|
||||
gainmapSmoothstep(0.08, 0.30, blueDominance) *
|
||||
gainmapSmoothstep(0.12, 0.62, tonalPosition) *
|
||||
lowContrastWeight *
|
||||
(1.0 - gainmapSmoothstep(0.84, 1.0, minChannel)),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float neutralDetailMask = clamp(
|
||||
(1.0 - gainmapSmoothstep(0.28, 0.68, saturation)) *
|
||||
gainmapSmoothstep(0.20, 0.78, tonalPosition) *
|
||||
gainmapSmoothstep(0.025, 0.14, localContrast),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float midtoneLiftMask = clamp(
|
||||
gainmapSmoothstep(0.08, 0.30, tonalPosition) *
|
||||
(1.0 - gainmapSmoothstep(0.78, 0.96, maxChannel)) *
|
||||
(1.0 - gainmapSmoothstep(0.45, 0.82, saturation)) *
|
||||
(1.0 - blueSkyMask),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float featureLiftScale = 1.0 +
|
||||
uMidtoneFeatureLift * midtoneLiftMask +
|
||||
uDetailFeatureLift * neutralDetailMask;
|
||||
float skyProtection = 1.0 - clamp(uBlueSkySuppression, 0.0, 0.95) * blueSkyMask;
|
||||
float lift = (uBaseSceneLift + uGlobalSceneLift * globalRamp + uShoulderSceneLift * shoulderRamp) *
|
||||
chromaPenalty * darkGate * featureLiftScale * skyProtection;
|
||||
float toneRatio = clamp(1.0 + (displayHeadroom - 1.0) * lift, 1.0, uMaxGainRatio);
|
||||
float lowHeadroomWeight = 1.0 - gainmapSmoothstep(1.80, 3.20, displayHeadroom);
|
||||
float nonBlackFloorEv = mix(
|
||||
max(uNonBlackFloorHighEv, 0.0),
|
||||
max(uNonBlackFloorLowEv, 0.0),
|
||||
lowHeadroomWeight
|
||||
);
|
||||
float nonBlackGate = gainmapSmoothstep(0.004, 0.030, tonalPosition);
|
||||
float floorSkyProtection = mix(1.0, skyProtection, 0.60);
|
||||
float nonBlackFloorRatio = exp(log(2.0) * nonBlackFloorEv * nonBlackGate * floorSkyProtection);
|
||||
toneRatio = max(toneRatio, clamp(nonBlackFloorRatio, 1.0, uMaxGainRatio));
|
||||
|
||||
float targetRatio = toneRatio;
|
||||
if (uHasHdrReference == 1) {
|
||||
vec3 hdr = max(texture(uHdrTexture, vTexCoord).rgb, vec3(0.0));
|
||||
float hdrSceneLuma = max(dot(hdr, vec3(0.2627, 0.6780, 0.0593)), 0.0);
|
||||
float hdrMaxChannel = max(hdr.r, max(hdr.g, hdr.b));
|
||||
float hdrMinChannel = min(hdr.r, min(hdr.g, hdr.b));
|
||||
float hdrSaturation = hdrMaxChannel <= 0.0001 ? 0.0 : clamp((hdrMaxChannel - hdrMinChannel) / hdrMaxChannel, 0.0, 1.0);
|
||||
float hdrDisplayLuma = displayLuma(hdrSceneLuma, uFullHdrRatio);
|
||||
float hdrMappedLuma = mix(
|
||||
hdrSceneLuma,
|
||||
hdrDisplayLuma,
|
||||
clamp(uReferenceDisplayMapWeight, 0.0, 1.0)
|
||||
);
|
||||
float referenceRatio = clamp(hdrMappedLuma / max(sdrLuma, 0.0001), uMinGainRatio, uMaxGainRatio);
|
||||
float referenceWeight = clamp(
|
||||
gainmapSmoothstep(uReferenceTonalStart, uReferenceTonalEnd, sdrLuma * 0.70 + maxChannel * 0.30) *
|
||||
(
|
||||
uReferenceHdrWeight * gainmapSmoothstep(uReferenceHdrStart, uReferenceHdrEnd, hdrSceneLuma) +
|
||||
uReferenceDeltaWeight * gainmapSmoothstep(uReferenceDeltaStart, uReferenceDeltaEnd, hdrMappedLuma - sdrLuma)
|
||||
),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
referenceWeight = clamp(
|
||||
referenceWeight * skyProtection * (1.0 + uDetailFeatureLift * 0.5 * neutralDetailMask),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
targetRatio = toneRatio + max(referenceRatio - toneRatio, 0.0) * referenceWeight * uReferenceExtraScale;
|
||||
|
||||
float referenceSignal = max(hdrSceneLuma, hdrMaxChannel);
|
||||
float referenceSceneLevel = pow(
|
||||
gainmapSmoothstep(uReferenceSceneStart, uReferenceSceneEnd, referenceSignal),
|
||||
uReferenceScenePower
|
||||
);
|
||||
float referenceSceneChroma = clamp(1.0 - hdrSaturation * uReferenceSaturationPenalty, 0.0, 1.0);
|
||||
float referenceSceneEv = log(uMaxGainRatio / uMinGainRatio) *
|
||||
clamp(referenceSceneLevel * referenceSceneChroma * uReferenceSceneWeight * skyProtection, 0.0, 1.0);
|
||||
float referenceSceneRatio = uMinGainRatio * exp(referenceSceneEv);
|
||||
targetRatio = max(targetRatio, referenceSceneRatio);
|
||||
}
|
||||
targetRatio = clamp(targetRatio, uMinGainRatio, uMaxGainRatio);
|
||||
float normalizedStrength = clamp(uStrength, 0.25, 2.0);
|
||||
float strengthRatio = clamp((targetRatio - 1.0) * normalizedStrength + 1.0, uMinGainRatio, uMaxGainRatio);
|
||||
float encoded = log(strengthRatio / uMinGainRatio) / log(uMaxGainRatio / uMinGainRatio);
|
||||
fragColor = vec4(vec3(clamp(encoded, 0.0, 1.0)), 1.0);
|
||||
float strengthRatio = clamp(
|
||||
1.0 + (ratio - 1.0) * normalizedStrength,
|
||||
uMinGainRatio,
|
||||
uMaxGainRatio
|
||||
);
|
||||
float gainEv = log2(strengthRatio);
|
||||
float minGainEv = log2(uMinGainRatio);
|
||||
float maxGainEv = log2(uMaxGainRatio);
|
||||
float normalized = (gainEv - minGainEv) / (maxGainEv - minGainEv);
|
||||
fragColor = vec4(vec3(clamp(normalized, 0.0, 1.0)), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val BLUR_H_FRAGMENT_SHADER = blurShader(horizontal = true)
|
||||
private val BLUR_V_FRAGMENT_SHADER = blurShader(horizontal = false)
|
||||
|
||||
private fun blurShader(horizontal: Boolean): String {
|
||||
val offset = if (horizontal) "vec2(float(i) * uTexelSize.x, 0.0)" else "vec2(0.0, float(i) * uTexelSize.y)"
|
||||
return """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform vec2 uTexelSize;
|
||||
void main() {
|
||||
float sum = 0.0;
|
||||
for (int i = -3; i <= 3; i++) {
|
||||
sum += texture(uInputTexture, vTexCoord + $offset).r;
|
||||
}
|
||||
float value = sum / 7.0;
|
||||
fragColor = vec4(vec3(value), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.pow
|
||||
|
||||
/**
|
||||
* Approximates how an HLG signal gets turned into display-referred brightness.
|
||||
*
|
||||
* This is not a strict BT.2100 reference monitor model. The goal here is to generate
|
||||
* a gainmap that tracks perceptual highlight lift on consumer HDR displays more closely
|
||||
* than a raw scene-linear / SDR ratio.
|
||||
*/
|
||||
class HlgDisplayMapper(
|
||||
fullHdrRatio: Float,
|
||||
) {
|
||||
|
||||
private val effectiveHeadroom = fullHdrRatio.coerceIn(MIN_EFFECTIVE_HEADROOM, MAX_EFFECTIVE_HEADROOM)
|
||||
private val systemGamma = (BASE_SYSTEM_GAMMA + (effectiveHeadroom - 1f) * SYSTEM_GAMMA_SLOPE)
|
||||
.coerceIn(MIN_SYSTEM_GAMMA, MAX_SYSTEM_GAMMA)
|
||||
|
||||
fun mapSceneLinearToDisplayLuma(sceneLuma: Float): Float {
|
||||
val safeSceneLuma = sceneLuma.coerceAtLeast(0f)
|
||||
if (safeSceneLuma <= SDR_REFERENCE_WHITE) {
|
||||
return safeSceneLuma
|
||||
}
|
||||
|
||||
val normalized = (safeSceneLuma / SDR_REFERENCE_WHITE).pow(systemGamma)
|
||||
val aboveWhite = (normalized - 1f).coerceAtLeast(0f)
|
||||
val compressedBoost = 1f - exp(-aboveWhite * HIGHLIGHT_ROLLOFF)
|
||||
return SDR_REFERENCE_WHITE * (1f + (effectiveHeadroom - 1f) * compressedBoost)
|
||||
}
|
||||
|
||||
fun estimateDisplayRatioFromSdr(
|
||||
sdrLuma: Float,
|
||||
highlightWeight: Float,
|
||||
peakWeight: Float,
|
||||
clipSuppression: Float = 1f,
|
||||
): Float {
|
||||
val safeSdrLuma = sdrLuma.coerceAtLeast(0f)
|
||||
val sceneEstimate = safeSdrLuma * (
|
||||
1f +
|
||||
highlightWeight.coerceAtLeast(0f) * SDR_HIGHLIGHT_RECOVERY +
|
||||
peakWeight.coerceAtLeast(0f) * SDR_PEAK_RECOVERY
|
||||
) * clipSuppression.coerceIn(0f, 1f)
|
||||
val displayLuma = mapSceneLinearToDisplayLuma(sceneEstimate)
|
||||
return (displayLuma / safeSdrLuma.coerceAtLeast(SDR_EPSILON)).coerceAtLeast(1f)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val SDR_REFERENCE_WHITE = 1.0f
|
||||
private const val SDR_EPSILON = 1e-4f
|
||||
private const val HIGHLIGHT_ROLLOFF = 0.85f
|
||||
private const val BASE_SYSTEM_GAMMA = 1.03f
|
||||
private const val SYSTEM_GAMMA_SLOPE = 0.16f
|
||||
private const val MIN_SYSTEM_GAMMA = 1.0f
|
||||
private const val MAX_SYSTEM_GAMMA = 1.25f
|
||||
private const val MIN_EFFECTIVE_HEADROOM = 1.15f
|
||||
private const val MAX_EFFECTIVE_HEADROOM = 3.2f
|
||||
private const val SDR_HIGHLIGHT_RECOVERY = 0.55f
|
||||
private const val SDR_PEAK_RECOVERY = 1.65f
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Gainmap
|
||||
import android.os.Build
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
class HlgGainmapProducer : GainmapProducer {
|
||||
|
||||
override suspend fun build(source: GainmapSourceSet, strength: Float): GainmapResult? {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return null
|
||||
if (source.sourceKind != SourceKind.HLG_CAPTURE) return null
|
||||
|
||||
val hdrReference = source.hdrReference?.bitmap ?: return null
|
||||
val sdrBase = source.sdrBase
|
||||
if (sdrBase.width <= 0 || sdrBase.height <= 0) return null
|
||||
|
||||
val alignedHdr = if (hdrReference.width != sdrBase.width || hdrReference.height != sdrBase.height) {
|
||||
Bitmap.createScaledBitmap(hdrReference, sdrBase.width, sdrBase.height, true)
|
||||
} else {
|
||||
hdrReference
|
||||
}
|
||||
|
||||
val fullHdrRatio = source.displayHdrSdrRatio.takeIf { it > 1f } ?: DEFAULT_FULL_HDR_RATIO
|
||||
val gainmapBitmap = createGainmapBitmap(sdrBase, alignedHdr, fullHdrRatio, strength) ?: return null
|
||||
val gainmap = Gainmap(gainmapBitmap).apply {
|
||||
setRatioMin(MIN_GAIN_RATIO, MIN_GAIN_RATIO, MIN_GAIN_RATIO)
|
||||
setRatioMax(MAX_GAIN_RATIO, MAX_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
setGamma(1.0f, 1.0f, 1.0f)
|
||||
setEpsilonSdr(EPSILON, EPSILON, EPSILON)
|
||||
setEpsilonHdr(EPSILON, EPSILON, EPSILON)
|
||||
setMinDisplayRatioForHdrTransition(1.0f)
|
||||
setDisplayRatioForFullHdr(fullHdrRatio)
|
||||
}
|
||||
|
||||
return GainmapResult(
|
||||
gainmap = gainmap,
|
||||
sourceKind = source.sourceKind,
|
||||
confidence = source.confidence
|
||||
)
|
||||
}
|
||||
|
||||
private fun createGainmapBitmap(
|
||||
sdrBase: Bitmap,
|
||||
hdrReference: Bitmap,
|
||||
fullHdrRatio: Float,
|
||||
strength: Float
|
||||
): Bitmap? {
|
||||
val displayMapper = HlgDisplayMapper(fullHdrRatio)
|
||||
val width = (sdrBase.width / DOWNSAMPLE).coerceAtLeast(1)
|
||||
val height = (sdrBase.height / DOWNSAMPLE).coerceAtLeast(1)
|
||||
val contents = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8)
|
||||
val pixels = ByteArray(width * height)
|
||||
|
||||
var index = 0
|
||||
for (y in 0 until height) {
|
||||
val srcY = ((y + 0.5f) * sdrBase.height / height).toInt().coerceIn(0, sdrBase.height - 1)
|
||||
for (x in 0 until width) {
|
||||
val srcX = ((x + 0.5f) * sdrBase.width / width).toInt().coerceIn(0, sdrBase.width - 1)
|
||||
|
||||
val sdrSample = ProgressiveGainmapMath.sampleSdr(sdrBase, srcX, srcY)
|
||||
val hdrSceneLuma = sampleHdrLuma(hdrReference, srcX, srcY)
|
||||
val hdrDisplayLuma = displayMapper.mapSceneLinearToDisplayLuma(hdrSceneLuma)
|
||||
|
||||
val toneRatio = ProgressiveGainmapMath.progressiveToneRatio(
|
||||
sample = sdrSample,
|
||||
fullHdrRatio = fullHdrRatio,
|
||||
maxGainRatio = MAX_GAIN_RATIO
|
||||
)
|
||||
val referenceRatio = (hdrDisplayLuma / (sdrSample.luma + EPSILON))
|
||||
.coerceIn(MIN_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
val referenceWeight = ProgressiveGainmapMath.referenceBlendWeight(
|
||||
sample = sdrSample,
|
||||
hdrSceneLuma = hdrSceneLuma,
|
||||
hdrDisplayLuma = hdrDisplayLuma
|
||||
)
|
||||
val targetRatio = ProgressiveGainmapMath.mergeReferenceRatio(
|
||||
toneRatio = toneRatio,
|
||||
referenceRatio = referenceRatio,
|
||||
referenceWeight = referenceWeight
|
||||
)
|
||||
.coerceIn(MIN_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
.let {
|
||||
HdrGainmapStrength.applyToRatio(it, MIN_GAIN_RATIO, MAX_GAIN_RATIO, strength)
|
||||
}
|
||||
val encoded = ProgressiveGainmapMath.encodeRatio(targetRatio, MIN_GAIN_RATIO, MAX_GAIN_RATIO)
|
||||
|
||||
pixels[index++] = encoded.toByte()
|
||||
}
|
||||
}
|
||||
|
||||
val blurred = ProgressiveGainmapMath.blurGainmap(pixels, width, height, BLUR_RADIUS)
|
||||
contents.copyPixelsFromBuffer(ByteBuffer.wrap(blurred))
|
||||
return contents
|
||||
}
|
||||
|
||||
private fun sampleHdrLuma(bitmap: Bitmap, x: Int, y: Int): Float {
|
||||
val c = bitmap.getColor(x, y)
|
||||
return (0.2627f * c.red() + 0.6780f * c.green() + 0.0593f * c.blue()).coerceAtLeast(0f)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val DOWNSAMPLE = 4
|
||||
private const val MIN_GAIN_RATIO = 1.0f
|
||||
private const val MAX_GAIN_RATIO = 3.5f
|
||||
private const val EPSILON = 1e-4f
|
||||
private const val BLUR_RADIUS = 3
|
||||
private const val DEFAULT_FULL_HDR_RATIO = 1.45f
|
||||
}
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorSpace
|
||||
import android.util.Half
|
||||
import com.hinnka.mycamera.gallery.MediaMetadata
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.system.measureTimeMillis
|
||||
|
||||
class HlgImageProcessor {
|
||||
|
||||
fun isHlgCapture(metadata: MediaMetadata): Boolean {
|
||||
return metadata.dynamicRangeProfile == "HLG10"
|
||||
}
|
||||
|
||||
fun createSourceFromCompressedArgb(
|
||||
buffer: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
confidence: Float = 0.7f,
|
||||
): GainmapSourceSet {
|
||||
buffer.rewind()
|
||||
|
||||
val encodedBitmap = Bitmap.createBitmap(
|
||||
width,
|
||||
height,
|
||||
Bitmap.Config.RGBA_F16,
|
||||
true,
|
||||
ColorSpace.get(ColorSpace.Named.BT2020_HLG)
|
||||
)
|
||||
val copyElapsed = measureTimeMillis {
|
||||
encodedBitmap.copyPixelsFromBuffer(buffer)
|
||||
}
|
||||
|
||||
val hdrReference = Bitmap.createBitmap(
|
||||
width,
|
||||
height,
|
||||
Bitmap.Config.RGBA_F16,
|
||||
true,
|
||||
ColorSpace.get(ColorSpace.Named.BT2020)
|
||||
)
|
||||
val sdrBase = Bitmap.createBitmap(
|
||||
width,
|
||||
height,
|
||||
Bitmap.Config.ARGB_8888
|
||||
)
|
||||
|
||||
val pixels = IntArray(width * height)
|
||||
val hdrBuffer = LargeDirectBuffer.allocate(width.toLong() * height.toLong() * 8L, "HLG HDR reference")
|
||||
?: throw OutOfMemoryError("Failed to allocate HLG HDR reference buffer")
|
||||
try {
|
||||
val transformElapsed = measureTimeMillis {
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
val c = encodedBitmap.getColor(x, y)
|
||||
val linearBt2020 = floatArrayOf(
|
||||
hlgToLinear(c.red()),
|
||||
hlgToLinear(c.green()),
|
||||
hlgToLinear(c.blue())
|
||||
)
|
||||
hdrBuffer.putShort(Half.toHalf(linearBt2020[0].coerceAtLeast(0f)))
|
||||
hdrBuffer.putShort(Half.toHalf(linearBt2020[1].coerceAtLeast(0f)))
|
||||
hdrBuffer.putShort(Half.toHalf(linearBt2020[2].coerceAtLeast(0f)))
|
||||
hdrBuffer.putShort(Half.toHalf(1.0f))
|
||||
|
||||
val sdrSrgb = bt2020LinearToSdrSrgb(linearBt2020)
|
||||
pixels[y * width + x] = Color.argb(
|
||||
255,
|
||||
(sdrSrgb[0].coerceIn(0f, 1f) * 255.0f).toInt(),
|
||||
(sdrSrgb[1].coerceIn(0f, 1f) * 255.0f).toInt(),
|
||||
(sdrSrgb[2].coerceIn(0f, 1f) * 255.0f).toInt(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val outputElapsed = measureTimeMillis {
|
||||
sdrBase.setPixels(pixels, 0, width, 0, 0, width, height)
|
||||
hdrBuffer.rewind()
|
||||
hdrReference.copyPixelsFromBuffer(hdrBuffer)
|
||||
}
|
||||
|
||||
encodedBitmap.recycle()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"createSourceFromCompressedArgb took ${copyElapsed + transformElapsed + outputElapsed}ms " +
|
||||
"(copy=${copyElapsed}ms, transform=${transformElapsed}ms, output=${outputElapsed}ms, size=${width}x${height})"
|
||||
)
|
||||
|
||||
return GainmapSourceSet(
|
||||
sdrBase = sdrBase,
|
||||
hdrReference = HdrBuffer(
|
||||
bitmap = hdrReference,
|
||||
description = "hlg_bt2020_linear"
|
||||
),
|
||||
sourceKind = SourceKind.HLG_CAPTURE,
|
||||
confidence = confidence
|
||||
)
|
||||
} finally {
|
||||
LargeDirectBuffer.free(hdrBuffer)
|
||||
}
|
||||
}
|
||||
|
||||
fun createHdrReferenceFromRawSidecar(
|
||||
buffer: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
): Bitmap {
|
||||
buffer.rewind()
|
||||
return Bitmap.createBitmap(
|
||||
width,
|
||||
height,
|
||||
Bitmap.Config.RGBA_F16,
|
||||
true,
|
||||
ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB)
|
||||
).also {
|
||||
it.copyPixelsFromBuffer(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
private fun hlgToLinear(value: Float): Float {
|
||||
val v = value.coerceIn(0f, 1f)
|
||||
return if (v <= 0.5f) {
|
||||
(v * v) / 3.0f
|
||||
} else {
|
||||
((exp(((v - HLG_C) / HLG_A).toDouble()) + HLG_B) / 12.0).toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
private fun bt2020LinearToSdrSrgb(bt2020: FloatArray): FloatArray {
|
||||
val r = 1.6605f * bt2020[0] - 0.5876f * bt2020[1] - 0.0728f * bt2020[2]
|
||||
val g = -0.1246f * bt2020[0] + 1.1329f * bt2020[1] - 0.0083f * bt2020[2]
|
||||
val b = -0.0182f * bt2020[0] - 0.1006f * bt2020[1] + 1.1187f * bt2020[2]
|
||||
|
||||
val toneMapped = floatArrayOf(
|
||||
toneMap(max(0f, r)),
|
||||
toneMap(max(0f, g)),
|
||||
toneMap(max(0f, b))
|
||||
)
|
||||
return floatArrayOf(
|
||||
linearToSrgb(toneMapped[0]),
|
||||
linearToSrgb(toneMapped[1]),
|
||||
linearToSrgb(toneMapped[2]),
|
||||
)
|
||||
}
|
||||
|
||||
private fun toneMap(value: Float): Float {
|
||||
val exposureAdjusted = value * SDR_EXPOSURE_SCALE
|
||||
return exposureAdjusted / (1.0f + exposureAdjusted)
|
||||
}
|
||||
|
||||
private fun linearToSrgb(value: Float): Float {
|
||||
return if (value <= 0.0031308f) {
|
||||
value * 12.92f
|
||||
} else {
|
||||
1.055f * value.pow(1.0f / 2.4f) - 0.055f
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HlgImageProcessor"
|
||||
private const val HLG_A = 0.17883277f
|
||||
private const val HLG_B = 0.28466892f
|
||||
private const val HLG_C = 0.55991073f
|
||||
private const val SDR_EXPOSURE_SCALE = 1.65f
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
|
||||
object ProgressiveGainmapMath {
|
||||
data class SdrSample(
|
||||
val luma: Float,
|
||||
val maxChannel: Float,
|
||||
val saturation: Float
|
||||
)
|
||||
|
||||
fun sampleSdr(bitmap: Bitmap, x: Int, y: Int): SdrSample {
|
||||
val c = bitmap.getColor(x, y)
|
||||
val r = srgbToLinear(c.red())
|
||||
val g = srgbToLinear(c.green())
|
||||
val b = srgbToLinear(c.blue())
|
||||
val luma = (0.2126f * r + 0.7152f * g + 0.0722f * b).coerceAtLeast(0f)
|
||||
val maxChannel = max(r, max(g, b))
|
||||
val minChannel = min(r, min(g, b))
|
||||
val saturation = if (maxChannel <= EPSILON) {
|
||||
0f
|
||||
} else {
|
||||
((maxChannel - minChannel) / maxChannel).coerceIn(0f, 1f)
|
||||
}
|
||||
return SdrSample(luma, maxChannel, saturation)
|
||||
}
|
||||
|
||||
fun progressiveToneRatio(sample: SdrSample, fullHdrRatio: Float, maxGainRatio: Float): Float {
|
||||
val displayHeadroom = fullHdrRatio.coerceIn(1.1f, maxGainRatio)
|
||||
val tonalPosition = (sample.luma * 0.72f + sample.maxChannel * 0.28f).coerceAtLeast(0f)
|
||||
val globalRamp = smoothstep(0.02f, 0.96f, tonalPosition).pow(TONE_POWER)
|
||||
val shoulderRamp = smoothstep(0.34f, 1.0f, sample.maxChannel).pow(SHOULDER_POWER)
|
||||
val chromaPenalty = 1.0f - sample.saturation * SATURATION_PENALTY
|
||||
|
||||
val lift = (BASE_SCENE_LIFT + GLOBAL_SCENE_LIFT * globalRamp + SHOULDER_SCENE_LIFT * shoulderRamp) *
|
||||
chromaPenalty
|
||||
|
||||
return (1.0f + (displayHeadroom - 1.0f) * lift)
|
||||
.coerceIn(1.0f, maxGainRatio)
|
||||
}
|
||||
|
||||
fun referenceBlendWeight(sample: SdrSample, hdrSceneLuma: Float, hdrDisplayLuma: Float): Float {
|
||||
val tonalPosition = (sample.luma * 0.70f + sample.maxChannel * 0.30f).coerceAtLeast(0f)
|
||||
val tonalWeight = smoothstep(0.05f, 0.98f, tonalPosition)
|
||||
val hdrWeight = smoothstep(0.65f, 2.0f, hdrSceneLuma)
|
||||
val deltaWeight = smoothstep(0.01f, 0.28f, hdrDisplayLuma - sample.luma)
|
||||
return (tonalWeight * (0.35f * hdrWeight + 0.65f * deltaWeight)).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
fun mergeReferenceRatio(toneRatio: Float, referenceRatio: Float, referenceWeight: Float): Float {
|
||||
val extraRatio = (referenceRatio - toneRatio).coerceAtLeast(0f)
|
||||
return toneRatio + extraRatio * referenceWeight * REFERENCE_EXTRA_SCALE
|
||||
}
|
||||
|
||||
fun encodeRatio(ratio: Float, minGainRatio: Float, maxGainRatio: Float): Int {
|
||||
val logRatioSpan = ln(maxGainRatio / minGainRatio)
|
||||
return ((ln(ratio.coerceIn(minGainRatio, maxGainRatio) / minGainRatio) / logRatioSpan) * 255.0f)
|
||||
.toInt()
|
||||
.coerceIn(0, 255)
|
||||
}
|
||||
|
||||
fun blurGainmap(pixels: ByteArray, width: Int, height: Int, radius: Int): ByteArray {
|
||||
val temp = ByteArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
var sum = 0
|
||||
for (dx in -radius..radius) {
|
||||
sum += pixels[y * width + (x + dx).coerceIn(0, width - 1)].toInt() and 0xFF
|
||||
}
|
||||
temp[y * width + x] = (sum / (2 * radius + 1)).toByte()
|
||||
}
|
||||
}
|
||||
val result = ByteArray(width * height)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
var sum = 0
|
||||
for (dy in -radius..radius) {
|
||||
sum += temp[(y + dy).coerceIn(0, height - 1) * width + x].toInt() and 0xFF
|
||||
}
|
||||
result[y * width + x] = (sum / (2 * radius + 1)).toByte()
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun smoothstep(edge0: Float, edge1: Float, x: Float): Float {
|
||||
if (edge0 == edge1) return if (x >= edge1) 1.0f else 0.0f
|
||||
val t = ((x - edge0) / (edge1 - edge0)).coerceIn(0.0f, 1.0f)
|
||||
return t * t * (3.0f - 2.0f * t)
|
||||
}
|
||||
|
||||
fun srgbToLinear(value: Float): Float {
|
||||
return if (value <= 0.04045f) {
|
||||
value / 12.92f
|
||||
} else {
|
||||
((value + 0.055f) / 1.055f).pow(2.4f)
|
||||
}
|
||||
}
|
||||
|
||||
private const val EPSILON = 1e-4f
|
||||
private const val BASE_SCENE_LIFT = 0.035f
|
||||
private const val GLOBAL_SCENE_LIFT = 0.4f
|
||||
private const val SHOULDER_SCENE_LIFT = 0.34f
|
||||
private const val TONE_POWER = 0.82f
|
||||
private const val SHOULDER_POWER = 1.35f
|
||||
private const val REFERENCE_EXTRA_SCALE = 0.82f
|
||||
private const val SATURATION_PENALTY = 0.10f
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.abs
|
||||
|
||||
internal object RawGainmapMath {
|
||||
const val DOWNSAMPLE = 2
|
||||
const val MIN_GAIN_RATIO = 0.25f
|
||||
const val MAX_GAIN_RATIO = 4.0f
|
||||
const val OFFSET = 1e-4f
|
||||
|
||||
private const val LUMA_R = 0.2126f
|
||||
private const val LUMA_G = 0.7152f
|
||||
private const val LUMA_B = 0.0722f
|
||||
|
||||
fun srgbToLinear(value: Float): Float {
|
||||
val magnitude = abs(value)
|
||||
val linearMagnitude = if (magnitude <= 0.04045f) {
|
||||
magnitude / 12.92f
|
||||
} else {
|
||||
((magnitude + 0.055f) / 1.055f).pow(2.4f)
|
||||
}
|
||||
return if (value < 0f) -linearMagnitude else linearMagnitude
|
||||
}
|
||||
|
||||
fun encode(
|
||||
sdrEncoded: Float,
|
||||
hdrLinear: Float,
|
||||
strength: Float = HdrGainmapStrength.DEFAULT,
|
||||
minGainRatio: Float = MIN_GAIN_RATIO,
|
||||
maxGainRatio: Float = MAX_GAIN_RATIO,
|
||||
offset: Float = OFFSET,
|
||||
): Float {
|
||||
val sdrLinear = srgbToLinear(sdrEncoded)
|
||||
val ratio = ((hdrLinear.coerceAtLeast(0f) + offset) / (sdrLinear + offset))
|
||||
.coerceIn(minGainRatio, maxGainRatio)
|
||||
val strengthRatio = HdrGainmapStrength.applyToRatio(
|
||||
ratio = ratio,
|
||||
minGainRatio = minGainRatio,
|
||||
maxGainRatio = maxGainRatio,
|
||||
strength = strength,
|
||||
)
|
||||
return ((ln(strengthRatio) - ln(minGainRatio)) / (ln(maxGainRatio) - ln(minGainRatio)))
|
||||
.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
fun encodeLuminance(
|
||||
sdrEncodedRgb: FloatArray,
|
||||
hdrLinearRgb: FloatArray,
|
||||
lutLuminanceGain: Float? = null,
|
||||
strength: Float = HdrGainmapStrength.DEFAULT,
|
||||
minGainRatio: Float = MIN_GAIN_RATIO,
|
||||
maxGainRatio: Float = MAX_GAIN_RATIO,
|
||||
offset: Float = OFFSET,
|
||||
): Float {
|
||||
require(sdrEncodedRgb.size >= 3 && hdrLinearRgb.size >= 3) {
|
||||
"SDR and HDR RGB inputs must contain at least three channels"
|
||||
}
|
||||
val sdrLuma = linearLuma(
|
||||
srgbToLinear(sdrEncodedRgb[0]),
|
||||
srgbToLinear(sdrEncodedRgb[1]),
|
||||
srgbToLinear(sdrEncodedRgb[2]),
|
||||
)
|
||||
val hdrLuma = linearLuma(
|
||||
hdrLinearRgb[0].coerceAtLeast(0f),
|
||||
hdrLinearRgb[1].coerceAtLeast(0f),
|
||||
hdrLinearRgb[2].coerceAtLeast(0f),
|
||||
)
|
||||
val targetHdrLuma = lutLuminanceGain?.let { gain ->
|
||||
applyLutLuminanceGain(gain, hdrLuma, offset)
|
||||
} ?: hdrLuma
|
||||
val ratio = ((targetHdrLuma + offset) / (sdrLuma + offset))
|
||||
.coerceIn(minGainRatio, maxGainRatio)
|
||||
val strengthRatio = HdrGainmapStrength.applyToRatio(
|
||||
ratio = ratio,
|
||||
minGainRatio = minGainRatio,
|
||||
maxGainRatio = maxGainRatio,
|
||||
strength = strength,
|
||||
)
|
||||
return ((ln(strengthRatio) - ln(minGainRatio)) /
|
||||
(ln(maxGainRatio) - ln(minGainRatio))).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
fun linearLuma(r: Float, g: Float, b: Float): Float =
|
||||
LUMA_R * r + LUMA_G * g + LUMA_B * b
|
||||
|
||||
fun computeLutLuminanceGain(
|
||||
sdrBeforeLutLuma: Float,
|
||||
sdrAfterLutLuma: Float,
|
||||
offset: Float = OFFSET,
|
||||
): Float {
|
||||
val safeBeforeLut = sdrBeforeLutLuma.coerceAtLeast(0f)
|
||||
val safeAfterLut = sdrAfterLutLuma.coerceAtLeast(0f)
|
||||
return (safeAfterLut + offset) / (safeBeforeLut + offset)
|
||||
}
|
||||
|
||||
fun applyLutLuminanceGain(
|
||||
lutLuminanceGain: Float,
|
||||
hdrReferenceLuma: Float,
|
||||
offset: Float = OFFSET,
|
||||
): Float {
|
||||
val safeHdr = hdrReferenceLuma.coerceAtLeast(0f)
|
||||
val lutGain = lutLuminanceGain.coerceAtLeast(0f)
|
||||
val hdrBase = safeHdr.coerceAtMost(1f)
|
||||
val hdrHeadroom = (safeHdr - 1f).coerceAtLeast(0f)
|
||||
val adjustedBase = ((hdrBase + offset) * lutGain - offset).coerceAtLeast(0f)
|
||||
return adjustedBase + hdrHeadroom
|
||||
}
|
||||
|
||||
fun reconstructLinear(
|
||||
sdrEncoded: Float,
|
||||
encodedGain: Float,
|
||||
minGainRatio: Float = MIN_GAIN_RATIO,
|
||||
maxGainRatio: Float = MAX_GAIN_RATIO,
|
||||
offset: Float = OFFSET,
|
||||
): Float {
|
||||
val logGain = ln(minGainRatio) +
|
||||
(ln(maxGainRatio) - ln(minGainRatio)) * encodedGain.coerceIn(0f, 1f)
|
||||
return (srgbToLinear(sdrEncoded) + offset) * kotlin.math.exp(logGain) - offset
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ class UnifiedGainmapProducer(
|
||||
private val producers: List<GainmapProducer> = listOf(
|
||||
EmbeddedGainmapProducer(),
|
||||
GpuReferenceGainmapProducer(),
|
||||
HlgGainmapProducer(),
|
||||
EstimatedSdrGainmapProducer(),
|
||||
)
|
||||
) : GainmapProducer {
|
||||
|
||||
@@ -19,6 +19,7 @@ import com.hinnka.mycamera.raw.RawShaders
|
||||
import com.hinnka.mycamera.raw.RawToneMappingGl
|
||||
import com.hinnka.mycamera.raw.RawToneMappingParameters
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import kotlinx.coroutines.asCoroutineDispatcher
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
@@ -35,6 +36,12 @@ import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.sqrt
|
||||
|
||||
data class LutStackRenderResult(
|
||||
val bitmap: Bitmap,
|
||||
/** RGBA_F16 sidecar; R stores the unbounded linear-light luminance ratio. */
|
||||
val luminanceGainMap: Bitmap?,
|
||||
)
|
||||
|
||||
/**
|
||||
* LUT 图片处理器
|
||||
*
|
||||
@@ -92,6 +99,7 @@ class LutImageProcessor {
|
||||
private var bitmapChromaDenoiseGuideProgram = 0
|
||||
private var bitmapChromaDenoiseProgram = 0
|
||||
private var lutSharpenProgram = 0
|
||||
private var lutLuminanceGainProgram = 0
|
||||
|
||||
private val bitmapDenoiseTexId = IntArray(2)
|
||||
private val bitmapDenoiseFboId = IntArray(2)
|
||||
@@ -722,6 +730,192 @@ class LutImageProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the complete LUT stack and emits its pixel-aligned linear-light luminance ratio as
|
||||
* an RGBA_F16 sidecar. The sidecar is context-independent and can be consumed by the later HDR
|
||||
* gainmap EGL context without retaining the full pre-LUT SDR bitmap.
|
||||
*/
|
||||
suspend fun applyLutStackWithLuminanceGain(
|
||||
bitmap: Bitmap,
|
||||
isHlgInput: Boolean = false,
|
||||
baselineLayer: LutRenderLayer?,
|
||||
creativeLayer: LutRenderLayer?,
|
||||
sharpeningValue: Float = 0f,
|
||||
noiseReductionValue: Float = 0f,
|
||||
chromaNoiseReductionValue: Float = 0f,
|
||||
linearInputToneMap: Boolean = false,
|
||||
linearInputExposureEv: Float = 0f,
|
||||
naturalLightDefaultChromaDenoise: Boolean = false,
|
||||
rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
|
||||
rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
|
||||
luminanceGainDownsample: Int = 1,
|
||||
): LutStackRenderResult {
|
||||
val rendered = applyLutStack(
|
||||
bitmap = bitmap,
|
||||
isHlgInput = isHlgInput,
|
||||
baselineLayer = baselineLayer,
|
||||
creativeLayer = creativeLayer,
|
||||
sharpeningValue = sharpeningValue,
|
||||
noiseReductionValue = noiseReductionValue,
|
||||
chromaNoiseReductionValue = chromaNoiseReductionValue,
|
||||
linearInputToneMap = linearInputToneMap,
|
||||
linearInputExposureEv = linearInputExposureEv,
|
||||
naturalLightDefaultChromaDenoise = naturalLightDefaultChromaDenoise,
|
||||
rawRenderingEngine = rawRenderingEngine,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
)
|
||||
val luminanceGainMap = if (isHlgInput || !bitmap.colorSpace.isEncodedSrgbFamily() ||
|
||||
!rendered.colorSpace.isEncodedSrgbFamily()
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"LUT luminance sidecar requires encoded sRGB input/output: " +
|
||||
"isHlg=$isHlgInput, before=${bitmap.colorSpace}, after=${rendered.colorSpace}"
|
||||
)
|
||||
null
|
||||
} else withContext(glDispatcher) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (!isInitialized || lutLuminanceGainProgram == 0) {
|
||||
PLog.e(TAG, "Cannot create LUT luminance sidecar: GL program unavailable")
|
||||
null
|
||||
} else {
|
||||
createLutLuminanceGainMap(bitmap, rendered, luminanceGainDownsample)
|
||||
}
|
||||
}
|
||||
return LutStackRenderResult(rendered, luminanceGainMap)
|
||||
}
|
||||
|
||||
private fun ColorSpace?.isEncodedSrgbFamily(): Boolean {
|
||||
val colorSpaceId = this?.id ?: return false
|
||||
return colorSpaceId == ColorSpace.get(ColorSpace.Named.SRGB).id ||
|
||||
colorSpaceId == ColorSpace.get(ColorSpace.Named.EXTENDED_SRGB).id
|
||||
}
|
||||
|
||||
private fun createLutLuminanceGainMap(
|
||||
beforeLut: Bitmap,
|
||||
afterLut: Bitmap,
|
||||
downsample: Int,
|
||||
): Bitmap? {
|
||||
if (beforeLut.width != afterLut.width || beforeLut.height != afterLut.height ||
|
||||
beforeLut.width <= 0 || beforeLut.height <= 0
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"LUT luminance sidecar inputs are not aligned: " +
|
||||
"before=${beforeLut.width}x${beforeLut.height}, " +
|
||||
"after=${afterLut.width}x${afterLut.height}"
|
||||
)
|
||||
return null
|
||||
}
|
||||
EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)
|
||||
val safeDownsample = downsample.coerceAtLeast(1)
|
||||
val outputWidth = ((beforeLut.width + safeDownsample - 1) / safeDownsample).coerceAtLeast(1)
|
||||
val outputHeight = ((beforeLut.height + safeDownsample - 1) / safeDownsample).coerceAtLeast(1)
|
||||
|
||||
val textures = IntArray(3)
|
||||
val framebuffers = IntArray(1)
|
||||
GLES30.glGenTextures(3, textures, 0)
|
||||
GLES30.glGenFramebuffers(1, framebuffers, 0)
|
||||
try {
|
||||
uploadLuminanceSidecarInput(textures[0], beforeLut)
|
||||
uploadLuminanceSidecarInput(textures[1], afterLut)
|
||||
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[2])
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
0,
|
||||
GLES30.GL_RGBA16F,
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
0,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
null,
|
||||
)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[0])
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER,
|
||||
GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
textures[2],
|
||||
0,
|
||||
)
|
||||
val framebufferStatus = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
|
||||
if (framebufferStatus != GLES30.GL_FRAMEBUFFER_COMPLETE) {
|
||||
PLog.e(TAG, "LUT luminance sidecar framebuffer incomplete: $framebufferStatus")
|
||||
return null
|
||||
}
|
||||
|
||||
GLES30.glViewport(0, 0, outputWidth, outputHeight)
|
||||
GLES30.glUseProgram(lutLuminanceGainProgram)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[0])
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(lutLuminanceGainProgram, "uBeforeLutTexture"),
|
||||
0,
|
||||
)
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[1])
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(lutLuminanceGainProgram, "uAfterLutTexture"),
|
||||
1,
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(lutLuminanceGainProgram, "uOffset"),
|
||||
LUT_LUMINANCE_OFFSET,
|
||||
)
|
||||
drawQuad(lutLuminanceGainProgram)
|
||||
checkGlError("renderLutLuminanceGainMap")
|
||||
|
||||
val byteCount = outputWidth.toLong() * outputHeight.toLong() * 8L
|
||||
val readback = LargeDirectBuffer.allocate(byteCount, "LUT luminance gain RGBA16F")
|
||||
?: return null
|
||||
try {
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 4)
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
readback,
|
||||
)
|
||||
checkGlError("readLutLuminanceGainMap")
|
||||
readback.position(0)
|
||||
return Bitmap.createBitmap(
|
||||
outputWidth,
|
||||
outputHeight,
|
||||
Bitmap.Config.RGBA_F16,
|
||||
true,
|
||||
ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB),
|
||||
).also { it.copyPixelsFromBuffer(readback) }
|
||||
} finally {
|
||||
LargeDirectBuffer.free(readback)
|
||||
}
|
||||
} finally {
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glDeleteFramebuffers(1, framebuffers, 0)
|
||||
GLES30.glDeleteTextures(3, textures, 0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun uploadLuminanceSidecarInput(textureId: Int, bitmap: Bitmap) {
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
val uploadBitmap = bitmap.asGlUploadCompatibleBitmap()
|
||||
android.opengl.GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, uploadBitmap, 0)
|
||||
if (uploadBitmap !== bitmap) uploadBitmap.recycle()
|
||||
}
|
||||
|
||||
suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float = 0.1f): Bitmap = withContext(glDispatcher) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
if (!isInitialized) {
|
||||
@@ -1506,6 +1700,11 @@ class LutImageProcessor {
|
||||
uLchChromaAdjustmentsLoc = GLES30.glGetUniformLocation(shaderProgram, "uLchChromaAdjustments")
|
||||
uLchLightnessAdjustmentsLoc = GLES30.glGetUniformLocation(shaderProgram, "uLchLightnessAdjustments")
|
||||
uPrimaryCalibrationMatrixLoc = GLES30.glGetUniformLocation(shaderProgram, "uPrimaryCalibrationMatrix")
|
||||
lutLuminanceGainProgram = createFragmentProgram(
|
||||
Shaders.SIMPLE_VERTEX_SHADER,
|
||||
LUT_LUMINANCE_GAIN_SHADER,
|
||||
"LutLuminanceGain",
|
||||
)
|
||||
}
|
||||
|
||||
private fun initBitmapDenoiseProfilePrograms() {
|
||||
@@ -2823,6 +3022,10 @@ class LutImageProcessor {
|
||||
GLES30.glDeleteProgram(lutSharpenProgram)
|
||||
lutSharpenProgram = 0
|
||||
}
|
||||
if (lutLuminanceGainProgram != 0) {
|
||||
GLES30.glDeleteProgram(lutLuminanceGainProgram)
|
||||
lutLuminanceGainProgram = 0
|
||||
}
|
||||
for (i in 0..1) {
|
||||
if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0)
|
||||
if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0)
|
||||
@@ -2872,6 +3075,7 @@ class LutImageProcessor {
|
||||
private const val TAG = "LutImageProcessor"
|
||||
private const val BITMAP_DENOISE_A = 0.008f
|
||||
private const val BITMAP_DENOISE_B = 0.0005f
|
||||
private const val LUT_LUMINANCE_OFFSET = 1e-4f
|
||||
private const val EGL_CONTEXT_PRIORITY_LEVEL_IMG = 0x3100
|
||||
private const val EGL_CONTEXT_PRIORITY_LOW_IMG = 0x3103
|
||||
|
||||
@@ -2906,6 +3110,43 @@ class LutImageProcessor {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val LUT_LUMINANCE_GAIN_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uBeforeLutTexture;
|
||||
uniform sampler2D uAfterLutTexture;
|
||||
uniform float uOffset;
|
||||
|
||||
float srgbToLinear(float value) {
|
||||
float magnitude = abs(value);
|
||||
float linearMagnitude = magnitude <= 0.04045
|
||||
? magnitude / 12.92
|
||||
: pow((magnitude + 0.055) / 1.055, 2.4);
|
||||
return sign(value) * linearMagnitude;
|
||||
}
|
||||
|
||||
vec3 srgbToLinear(vec3 value) {
|
||||
return vec3(
|
||||
srgbToLinear(value.r),
|
||||
srgbToLinear(value.g),
|
||||
srgbToLinear(value.b)
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
const vec3 LINEAR_SRGB_LUMA = vec3(0.2126, 0.7152, 0.0722);
|
||||
vec3 beforeLinear = srgbToLinear(texture(uBeforeLutTexture, vTexCoord).rgb);
|
||||
vec3 afterLinear = srgbToLinear(texture(uAfterLutTexture, vTexCoord).rgb);
|
||||
float beforeLuma = max(dot(beforeLinear, LINEAR_SRGB_LUMA), 0.0);
|
||||
float afterLuma = max(dot(afterLinear, LINEAR_SRGB_LUMA), 0.0);
|
||||
float gain = (afterLuma + uOffset) / (beforeLuma + uOffset);
|
||||
fragColor = vec4(gain, 0.0, 0.0, 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val SRGB_TO_LINEAR_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
@@ -547,6 +547,7 @@ object Shaders {
|
||||
uniform float uAperture;
|
||||
uniform float uFocusDepth;
|
||||
uniform vec2 uTexelSize;
|
||||
uniform int uLinearInput;
|
||||
|
||||
const float PI = 3.14159265359;
|
||||
const float GOLDEN_ANGLE = 2.39996323;
|
||||
@@ -751,10 +752,12 @@ object Shaders {
|
||||
}
|
||||
|
||||
vec3 toLinear(vec3 color) {
|
||||
if (uLinearInput != 0) return max(color, vec3(0.0));
|
||||
return pow(clamp(color, 0.0, 1.0), vec3(LENS_GAMMA));
|
||||
}
|
||||
|
||||
vec3 toDisplay(vec3 color) {
|
||||
if (uLinearInput != 0) return max(color, vec3(0.0));
|
||||
return pow(max(color, vec3(0.0)), vec3(1.0 / LENS_GAMMA));
|
||||
}
|
||||
|
||||
@@ -820,7 +823,9 @@ object Shaders {
|
||||
|
||||
// 更加平滑的高光增强曲线
|
||||
float highlight = max(0.0, luma - 0.55);
|
||||
float hdrBoost = 1.0 + pow(highlight, 1.8) * 18.0 * smoothstep(1.5, 5.0, sCoc);
|
||||
float hdrBoost = uLinearInput != 0
|
||||
? 1.0
|
||||
: 1.0 + pow(highlight, 1.8) * 18.0 * smoothstep(1.5, 5.0, sCoc);
|
||||
|
||||
float edge = smoothstep(0.75, 1.03, r / max(sCoc, 0.1));
|
||||
float ring = 1.0 + edge * 0.3 * smoothstep(1.5, 5.0, sCoc);
|
||||
@@ -832,7 +837,9 @@ object Shaders {
|
||||
}
|
||||
|
||||
vec3 finalColor = accWeight > 0.001 ? toDisplay(accColor / accWeight) : centerColor.rgb;
|
||||
finalColor = clamp(finalColor, 0.0, 1.0);
|
||||
if (uLinearInput == 0) {
|
||||
finalColor = clamp(finalColor, 0.0, 1.0);
|
||||
}
|
||||
|
||||
fragColor = vec4(finalColor, centerColor.a);
|
||||
}
|
||||
|
||||
@@ -52,10 +52,15 @@ class DepthBokehProcessor(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
val inputForBokeh = ensureArgb8888(originalImage)
|
||||
|
||||
if (depthMap == null) {
|
||||
depthMap = SharedDepthEstimator.estimateDepth(appContext, inputForBokeh)
|
||||
val depthGuide = ensureArgb8888(originalImage)
|
||||
depthMap = try {
|
||||
SharedDepthEstimator.estimateDepth(appContext, depthGuide)
|
||||
} finally {
|
||||
if (depthGuide !== originalImage && !depthGuide.isRecycled) {
|
||||
depthGuide.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
if (depthMap != null && depthFile != null) {
|
||||
try {
|
||||
@@ -80,15 +85,12 @@ class DepthBokehProcessor(context: Context) {
|
||||
"Prepared bokeh depth: inverted=${preparedDepth.inverted} focusDepth=${preparedDepth.focusDepth} normalScore=${preparedDepth.normalScore} invertedScore=${preparedDepth.invertedScore}"
|
||||
)
|
||||
val bokehResult = processor.applyBokeh(
|
||||
inputForBokeh,
|
||||
originalImage,
|
||||
preparedDepth.depthMap,
|
||||
focusX ?: 0.5f,
|
||||
focusY ?: 0.5f,
|
||||
aperture
|
||||
)
|
||||
if (inputForBokeh !== originalImage && !inputForBokeh.isRecycled) {
|
||||
inputForBokeh.recycle()
|
||||
}
|
||||
result = bokehResult
|
||||
}
|
||||
|
||||
@@ -96,9 +98,9 @@ class DepthBokehProcessor(context: Context) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a bitmap to ARGB_8888 if it isn't already.
|
||||
* RGBA_F16 bitmaps (from RAW processing) are not compatible with
|
||||
* GLUtils.texImage2D used by OglBokehProcessor.
|
||||
* The depth estimator consumes an 8-bit display-referred guide. The bokeh
|
||||
* renderer itself receives the original bitmap so a linear RGBA_F16 HDR
|
||||
* reference keeps both its encoding and values above 1.0.
|
||||
*/
|
||||
private fun ensureArgb8888(bitmap: Bitmap): Bitmap {
|
||||
if (bitmap.config == Bitmap.Config.ARGB_8888) return bitmap
|
||||
|
||||
@@ -35,6 +35,9 @@ class OglBokehProcessor {
|
||||
aperture: Float
|
||||
): Bitmap? {
|
||||
try {
|
||||
val halfFloatOutput = originalImage.config == Bitmap.Config.RGBA_F16
|
||||
val linearInput = originalImage.colorSpace?.id ==
|
||||
ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB).id
|
||||
initEGL(originalImage.width, originalImage.height)
|
||||
initGL()
|
||||
|
||||
@@ -96,7 +99,17 @@ class OglBokehProcessor {
|
||||
val outputTex = IntArray(1)
|
||||
GLES30.glGenTextures(1, outputTex, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, outputTex[0])
|
||||
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, originalImage.width, originalImage.height, 0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null)
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
0,
|
||||
if (halfFloatOutput) GLES30.GL_RGBA16F else GLES30.GL_RGBA8,
|
||||
originalImage.width,
|
||||
originalImage.height,
|
||||
0,
|
||||
GLES30.GL_RGBA,
|
||||
if (halfFloatOutput) GLES30.GL_HALF_FLOAT else GLES30.GL_UNSIGNED_BYTE,
|
||||
null
|
||||
)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
|
||||
|
||||
@@ -118,6 +131,10 @@ class OglBokehProcessor {
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uAperture"), aperture)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uFocusDepth"), focusDepth)
|
||||
GLES30.glUniform2f(GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize"), 1.0f / originalImage.width, 1.0f / originalImage.height)
|
||||
GLES30.glUniform1i(
|
||||
GLES30.glGetUniformLocation(bokehProgramId, "uLinearInput"),
|
||||
if (linearInput) 1 else 0
|
||||
)
|
||||
|
||||
val identity = FloatArray(16)
|
||||
android.opengl.Matrix.setIdentityM(identity, 0)
|
||||
@@ -128,11 +145,22 @@ class OglBokehProcessor {
|
||||
|
||||
// Read back to Bitmap
|
||||
val resultBitmap = Bitmap.createBitmap(originalImage.width, originalImage.height,
|
||||
Bitmap.Config.ARGB_8888, false, originalImage.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB))
|
||||
val bufferByteCount = originalImage.width.toLong() * originalImage.height.toLong() * 4L
|
||||
if (halfFloatOutput) Bitmap.Config.RGBA_F16 else Bitmap.Config.ARGB_8888,
|
||||
false,
|
||||
originalImage.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB))
|
||||
val bytesPerPixel = if (halfFloatOutput) 8L else 4L
|
||||
val bufferByteCount = originalImage.width.toLong() * originalImage.height.toLong() * bytesPerPixel
|
||||
val buffer = LargeDirectBuffer.allocate(bufferByteCount, "OGL bokeh readback") ?: return null
|
||||
try {
|
||||
GLES30.glReadPixels(0, 0, originalImage.width, originalImage.height, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, buffer)
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
originalImage.width,
|
||||
originalImage.height,
|
||||
GLES30.GL_RGBA,
|
||||
if (halfFloatOutput) GLES30.GL_HALF_FLOAT else GLES30.GL_UNSIGNED_BYTE,
|
||||
buffer
|
||||
)
|
||||
resultBitmap.copyPixelsFromBuffer(buffer)
|
||||
} finally {
|
||||
LargeDirectBuffer.free(buffer)
|
||||
@@ -187,7 +215,29 @@ class OglBokehProcessor {
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, magFilter)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
|
||||
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0)
|
||||
if (bitmap.config == Bitmap.Config.RGBA_F16) {
|
||||
val buffer = LargeDirectBuffer.allocate(bitmap.byteCount.toLong(), "OGL bokeh RGBA_F16 upload")
|
||||
?: throw IllegalStateException("Unable to allocate RGBA_F16 upload buffer")
|
||||
try {
|
||||
bitmap.copyPixelsToBuffer(buffer)
|
||||
buffer.position(0)
|
||||
GLES30.glTexImage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
0,
|
||||
GLES30.GL_RGBA16F,
|
||||
bitmap.width,
|
||||
bitmap.height,
|
||||
0,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
buffer
|
||||
)
|
||||
} finally {
|
||||
LargeDirectBuffer.free(buffer)
|
||||
}
|
||||
} else {
|
||||
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0)
|
||||
}
|
||||
if (mipmap) {
|
||||
GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D)
|
||||
}
|
||||
|
||||
@@ -1407,6 +1407,10 @@ class RawDemosaicProcessor {
|
||||
profileWorkingColorSpace,
|
||||
engineWorkingColorSpace
|
||||
)
|
||||
val profileToLinearSrgbTransform = computeWorkingToOutputTransform(
|
||||
profileWorkingColorSpace,
|
||||
ColorSpace.SRGB,
|
||||
)
|
||||
val linearColorCorrectionMatrix = resolveLinearColorCorrectionMatrix(
|
||||
metadata = actualMetadata,
|
||||
dcpRenderPlan = activeDcpRenderPlan
|
||||
@@ -1874,6 +1878,41 @@ class RawDemosaicProcessor {
|
||||
"dcpBaselineExposureOffsetApplied=$applyDcpBaselineExposureOffset"
|
||||
)
|
||||
|
||||
// The HDR reference branches directly from undenoised, demosaicked camera RGB.
|
||||
// It intentionally excludes denoise, ProfileGainMap, edit exposure, rendering engines,
|
||||
// their additional tone mapping, and output sharpening. The complete ACR3 reference
|
||||
// curve is applied. Its output contract is linear extended sRGB.
|
||||
val hdrReferenceBitmap = if (includeHdrReference) {
|
||||
setupHdrReferenceFramebuffer(actualWidth, actualHeight)
|
||||
renderHdrReferencePass(
|
||||
metadata = actualMetadata,
|
||||
inputTextureId = demosaicTextureId,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
profileToLinearSrgb = profileToLinearSrgbTransform,
|
||||
)
|
||||
setupOutputFramebuffer(finalWidth, finalHeight)
|
||||
renderOutputPass(
|
||||
actualRotation,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
bounds,
|
||||
hdrReferenceTextureId,
|
||||
)
|
||||
val hdrPixels = readPixels(
|
||||
finalWidth,
|
||||
finalHeight,
|
||||
android.graphics.ColorSpace.get(
|
||||
android.graphics.ColorSpace.Named.LINEAR_EXTENDED_SRGB
|
||||
),
|
||||
)
|
||||
releaseHdrReferenceFramebuffer()
|
||||
hdrPixels
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// Chroma denoise runs first in the un-white-balanced camera RGB domain,
|
||||
// where the DNG/Camera2 R/B noise model is valid. It writes to the spare
|
||||
// full-resolution texture and preserves green while filtering R-G/B-G.
|
||||
@@ -1950,40 +1989,6 @@ class RawDemosaicProcessor {
|
||||
// demosaicFramebufferId = 0
|
||||
// }
|
||||
// demosaicWidth = 0; demosaicHeight = 0
|
||||
val hdrReferenceBitmap = if (includeHdrReference) {
|
||||
setupHdrReferenceFramebuffer(actualWidth, actualHeight)
|
||||
renderHdrReferencePass(
|
||||
metadata = actualMetadata,
|
||||
inputTextureId = outputTexture
|
||||
)
|
||||
setupOutputFramebuffer(finalWidth, finalHeight)
|
||||
renderOutputPass(
|
||||
actualRotation,
|
||||
actualWidth,
|
||||
actualHeight,
|
||||
bounds,
|
||||
hdrReferenceTextureId
|
||||
)
|
||||
val hdrPixels = readPixels(
|
||||
finalWidth,
|
||||
finalHeight,
|
||||
android.graphics.ColorSpace.get(android.graphics.ColorSpace.Named.EXTENDED_SRGB)
|
||||
)
|
||||
// hdrReferenceTextureId 已被 outputPass 消费
|
||||
if (hdrReferenceTextureId != 0) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(hdrReferenceTextureId), 0)
|
||||
hdrReferenceTextureId = 0
|
||||
}
|
||||
if (hdrReferenceFramebufferId != 0) {
|
||||
GLES30.glDeleteFramebuffers(1, intArrayOf(hdrReferenceFramebufferId), 0)
|
||||
hdrReferenceFramebufferId = 0
|
||||
}
|
||||
hdrReferenceWidth = 0; hdrReferenceHeight = 0
|
||||
hdrPixels
|
||||
} else {
|
||||
null
|
||||
}
|
||||
|
||||
// 5. 第二步:Combined Pass (HDR Linear -> LDR sRGB + LUT)
|
||||
val combinedInputTexture = if (colorEngine == RawRenderingEngine.DarktableFilmic) {
|
||||
val reconstructedTexture = renderDarktableFilmicHighlightReconstruction(
|
||||
@@ -2841,7 +2846,7 @@ class RawDemosaicProcessor {
|
||||
val fShaderHdrReference =
|
||||
compileShader(
|
||||
GLES30.GL_FRAGMENT_SHADER,
|
||||
RawShaders.HDR_REFERENCE_FRAGMENT_SHADER,
|
||||
RawHdrReferenceShaders.FRAGMENT_SHADER,
|
||||
"hdrReferenceFragment"
|
||||
)
|
||||
if (vShader != 0 && fShaderHdrReference != 0) {
|
||||
@@ -6182,6 +6187,19 @@ class RawDemosaicProcessor {
|
||||
checkGlError("setupHdrReferenceFramebuffer")
|
||||
}
|
||||
|
||||
private fun releaseHdrReferenceFramebuffer() {
|
||||
if (hdrReferenceTextureId != 0) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(hdrReferenceTextureId), 0)
|
||||
hdrReferenceTextureId = 0
|
||||
}
|
||||
if (hdrReferenceFramebufferId != 0) {
|
||||
GLES30.glDeleteFramebuffers(1, intArrayOf(hdrReferenceFramebufferId), 0)
|
||||
hdrReferenceFramebufferId = 0
|
||||
}
|
||||
hdrReferenceWidth = 0
|
||||
hdrReferenceHeight = 0
|
||||
}
|
||||
|
||||
private fun setupSharpenFramebuffer(width: Int, height: Int) {
|
||||
if (sharpenWidth == width && sharpenHeight == height && sharpenFramebufferId != 0) {
|
||||
return
|
||||
@@ -7610,7 +7628,11 @@ class RawDemosaicProcessor {
|
||||
|
||||
private fun renderHdrReferencePass(
|
||||
metadata: RawMetadata,
|
||||
inputTextureId: Int
|
||||
inputTextureId: Int,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
cameraWhite: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
profileToLinearSrgb: FloatArray,
|
||||
) {
|
||||
GLES30.glUseProgram(hdrReferenceProgram)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, hdrReferenceFramebufferId)
|
||||
@@ -7620,14 +7642,34 @@ class RawDemosaicProcessor {
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTextureId)
|
||||
GLES30.glUniform1i(GLES30.glGetUniformLocation(hdrReferenceProgram, "uInputTexture"), 0)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uHighlightStart"),
|
||||
RawHdrReferenceMath.HIGHLIGHT_START
|
||||
GLES30.glUniformMatrix3fv(
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uCameraToProfile"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(colorCorrectionMatrix),
|
||||
0,
|
||||
)
|
||||
GLES30.glUniformMatrix3fv(
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uProfileToLinearSrgb"),
|
||||
1,
|
||||
false,
|
||||
transposeMatrix3x3(profileToLinearSrgb),
|
||||
0,
|
||||
)
|
||||
val safeCameraWhite = sanitizeCameraWhite(cameraWhite)
|
||||
GLES30.glUniform3f(
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uCameraWhite"),
|
||||
safeCameraWhite[0],
|
||||
safeCameraWhite[1],
|
||||
safeCameraWhite[2],
|
||||
)
|
||||
GLES30.glUniform1f(
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uWhitePointSceneLuma"),
|
||||
RawHdrReferenceMath.WHITE_POINT_SCENE_LUMA
|
||||
GLES30.glGetUniformLocation(hdrReferenceProgram, "uExposureGain"),
|
||||
RawHdrReferenceMath.exposureGain(metadata.baselineExposure),
|
||||
)
|
||||
val acr3Curve = ACR3Curve.samples()
|
||||
bindCurveCombinedResource(hdrReferenceProgram, acr3Curve)
|
||||
bindLinearDcpHueSatMap(hdrReferenceProgram, hueSatMap)
|
||||
|
||||
val identityMatrix = FloatArray(16)
|
||||
GlMatrix.setIdentityM(identityMatrix, 0)
|
||||
|
||||
@@ -1,27 +1,39 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
object RawHdrReferenceMath {
|
||||
const val HIGHLIGHT_START = 0.50f
|
||||
const val WHITE_POINT_SCENE_LUMA = 2.4f
|
||||
const val ACR3_BLEND_START = 0.09f
|
||||
const val LINEAR_GAIN_START = 0.18f
|
||||
|
||||
fun expandedSceneLuma(
|
||||
luma: Float,
|
||||
highlightStart: Float = HIGHLIGHT_START,
|
||||
whitePointSceneLuma: Float = WHITE_POINT_SCENE_LUMA,
|
||||
): Float {
|
||||
if (!luma.isFinite()) return 0f
|
||||
val safeLuma = luma.coerceAtLeast(0f)
|
||||
val whitePoint = whitePointSceneLuma.coerceAtLeast(1f)
|
||||
val highlight = smoothstep(highlightStart, 1f, safeLuma)
|
||||
val lift = 1f + (whitePoint - 1f) * highlight
|
||||
return max(safeLuma, min(safeLuma * lift, whitePoint))
|
||||
fun exposureEv(baselineExposureEv: Float): Float =
|
||||
DngBaselineExposure.sanitize(baselineExposureEv)
|
||||
|
||||
fun exposureGain(baselineExposureEv: Float): Float =
|
||||
DngBaselineExposure.exactGain(baselineExposureEv)
|
||||
|
||||
fun toneValue(value: Float, curve: FloatArray = ACR3Curve.samples()): Float {
|
||||
val safeValue = value.coerceAtLeast(0f)
|
||||
val curveAtAnchor = sampleCurve(curve, LINEAR_GAIN_START)
|
||||
val linearGain = curveAtAnchor / LINEAR_GAIN_START
|
||||
val linearValue = safeValue * linearGain
|
||||
if (safeValue <= ACR3_BLEND_START) return sampleCurve(curve, safeValue)
|
||||
if (safeValue >= LINEAR_GAIN_START) return linearValue
|
||||
|
||||
val blend = smoothstep(ACR3_BLEND_START, LINEAR_GAIN_START, safeValue)
|
||||
val curveValue = sampleCurve(curve, safeValue)
|
||||
return curveValue + (linearValue - curveValue) * blend
|
||||
}
|
||||
|
||||
private fun sampleCurve(curve: FloatArray, value: Float): Float {
|
||||
require(curve.isNotEmpty()) { "Curve must not be empty" }
|
||||
if (curve.size == 1) return curve[0]
|
||||
|
||||
val position = value.coerceIn(0f, 1f) * (curve.size - 1)
|
||||
val lowerIndex = position.toInt().coerceAtMost(curve.lastIndex - 1)
|
||||
val fraction = position - lowerIndex
|
||||
return curve[lowerIndex] + (curve[lowerIndex + 1] - curve[lowerIndex]) * fraction
|
||||
}
|
||||
|
||||
private fun smoothstep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
if (edge0 == edge1) return if (value >= edge1) 1f else 0f
|
||||
val t = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
|
||||
return t * t * (3f - 2f * t)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
/**
|
||||
* Produces the engine-independent RAW HDR reference.
|
||||
*
|
||||
* Input is the undenoised, demosaicked camera RGB texture. The pass performs only the base
|
||||
* camera/profile color work, applies the DCP HueSatMap when present, applies the exact DNG
|
||||
* BaselineExposure, applies ACR3 completely through 0.09, blends to an unnormalized linear gain
|
||||
* through 0.18, and keeps that gain for midtones and extended highlights before converting to
|
||||
* linear sRGB.
|
||||
*/
|
||||
object RawHdrReferenceShaders {
|
||||
val FRAGMENT_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
precision highp sampler3D;
|
||||
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform sampler2D uCurveTexture;
|
||||
uniform sampler3D uLinearDcpHueSatMap;
|
||||
uniform mat3 uCameraToProfile;
|
||||
uniform mat3 uProfileToLinearSrgb;
|
||||
uniform vec3 uCameraWhite;
|
||||
uniform float uExposureGain;
|
||||
uniform float uCurveSize;
|
||||
uniform bool uCurveEnabled;
|
||||
uniform int uLinearDcpHueSatEnabled;
|
||||
uniform ivec3 uLinearDcpHueSatDivisions;
|
||||
uniform int uLinearDcpHueSatEncoding;
|
||||
|
||||
${DcpHueSatMapGl.SHADER_FUNCTIONS}
|
||||
|
||||
float sampleAcr3Curve(float value) {
|
||||
if (!uCurveEnabled || uCurveSize <= 1.0) {
|
||||
return value;
|
||||
}
|
||||
float clampedValue = clamp(value, 0.0, 1.0);
|
||||
float coordX = clampedValue * ((uCurveSize - 1.0) / uCurveSize) +
|
||||
(0.5 / uCurveSize);
|
||||
return texture(uCurveTexture, vec2(coordX, 0.5)).r;
|
||||
}
|
||||
|
||||
float applyAcr3LinearToneValue(float value) {
|
||||
const float ACR3_BLEND_START = 0.09;
|
||||
const float LINEAR_GAIN_START = 0.18;
|
||||
float safeValue = max(value, 0.0);
|
||||
float curveAtAnchor = sampleAcr3Curve(LINEAR_GAIN_START);
|
||||
float linearGain = curveAtAnchor / LINEAR_GAIN_START;
|
||||
float linearValue = safeValue * linearGain;
|
||||
if (safeValue <= ACR3_BLEND_START) {
|
||||
return sampleAcr3Curve(safeValue);
|
||||
}
|
||||
if (safeValue >= LINEAR_GAIN_START) {
|
||||
return linearValue;
|
||||
}
|
||||
float blend = smoothstep(ACR3_BLEND_START, LINEAR_GAIN_START, safeValue);
|
||||
return mix(sampleAcr3Curve(safeValue), linearValue, blend);
|
||||
}
|
||||
|
||||
void toneRgb(inout float maxValue, inout float midValue, inout float minValue) {
|
||||
float oldMax = maxValue;
|
||||
float oldMid = midValue;
|
||||
float oldMin = minValue;
|
||||
maxValue = applyAcr3LinearToneValue(oldMax);
|
||||
minValue = applyAcr3LinearToneValue(oldMin);
|
||||
if (abs(oldMax - oldMin) < 1e-6) {
|
||||
midValue = minValue;
|
||||
} else {
|
||||
midValue = minValue +
|
||||
(maxValue - minValue) * (oldMid - oldMin) / (oldMax - oldMin);
|
||||
}
|
||||
}
|
||||
|
||||
vec3 applyHdrReferenceCurve(vec3 color) {
|
||||
color = max(color, vec3(0.0));
|
||||
float r = color.r;
|
||||
float g = color.g;
|
||||
float b = color.b;
|
||||
|
||||
if (r >= g) {
|
||||
if (g > b) {
|
||||
toneRgb(r, g, b);
|
||||
} else if (b > r) {
|
||||
toneRgb(b, r, g);
|
||||
} else if (b > g) {
|
||||
toneRgb(r, b, g);
|
||||
} else {
|
||||
r = applyAcr3LinearToneValue(r);
|
||||
g = applyAcr3LinearToneValue(g);
|
||||
b = g;
|
||||
}
|
||||
} else {
|
||||
if (r >= b) {
|
||||
toneRgb(g, r, b);
|
||||
} else if (b > g) {
|
||||
toneRgb(b, g, r);
|
||||
} else {
|
||||
toneRgb(g, b, r);
|
||||
}
|
||||
}
|
||||
return vec3(r, g, b);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 cameraRgb = max(texture(uInputTexture, vTexCoord).rgb, vec3(0.0));
|
||||
cameraRgb = min(cameraRgb, max(uCameraWhite, vec3(0.001)));
|
||||
|
||||
vec3 profileRgb = uCameraToProfile * cameraRgb;
|
||||
if (uLinearDcpHueSatEnabled != 0) {
|
||||
profileRgb = dngApplyHueSatMap(
|
||||
profileRgb,
|
||||
uLinearDcpHueSatMap,
|
||||
uLinearDcpHueSatDivisions,
|
||||
uLinearDcpHueSatEncoding,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
profileRgb *= uExposureGain;
|
||||
profileRgb = applyHdrReferenceCurve(profileRgb);
|
||||
vec3 linearSrgb = uProfileToLinearSrgb * profileRgb;
|
||||
fragColor = vec4(max(linearSrgb, vec3(0.0)), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -1545,40 +1545,6 @@ object RawShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* HDR Reference Shader
|
||||
*
|
||||
* RAW 线性输入已经按传感器白点归一化,直接输出会让拍到白点的灯光仍然只有
|
||||
* SDR reference white (= 1.0),gainmap 没有高光余量可写。这里只按原始亮度比例
|
||||
* 从普通高光开始逐步扩展到 scene-linear HDR headroom,保留白云等扩散高光的局部层次。
|
||||
*/
|
||||
val HDR_REFERENCE_FRAGMENT_SHADER = """
|
||||
#version 300 es
|
||||
precision highp float;
|
||||
|
||||
in vec2 vTexCoord;
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform float uHighlightStart;
|
||||
uniform float uWhitePointSceneLuma;
|
||||
|
||||
float luminance(vec3 color) {
|
||||
return max(dot(color, vec3(0.2126, 0.7152, 0.0722)), 1e-5);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 color = max(texture(uInputTexture, vTexCoord).rgb, vec3(0.0));
|
||||
float luma = luminance(color);
|
||||
float highlight = smoothstep(uHighlightStart, 1.0, luma);
|
||||
float whitePoint = max(uWhitePointSceneLuma, 1.0);
|
||||
float lift = mix(1.0, whitePoint, highlight);
|
||||
float targetLuma = max(luma, min(luma * lift, whitePoint));
|
||||
color *= targetLuma / luma;
|
||||
fragColor = vec4(max(color, vec3(0.0)), 1.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
/**
|
||||
* 绘制顺序索引
|
||||
*/
|
||||
|
||||
@@ -1295,7 +1295,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
val autoEnableHdr: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.autoEnableHdr }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
||||
|
||||
val useHdrScreenMode: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.useHdrScreenMode }
|
||||
@@ -2355,7 +2355,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
): Boolean {
|
||||
if (hasEmbeddedGainmap) return true
|
||||
if (rawToneMappingParameters?.normalized()?.useGooglePixelToneMap == true) return true
|
||||
return userPrefs?.autoEnableHdr ?: false
|
||||
return userPrefs?.autoEnableHdr ?: true
|
||||
}
|
||||
|
||||
fun setUseMultipleExposure(enabled: Boolean) {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class EstimatedSdrGainmapMathTest {
|
||||
@Test
|
||||
fun keepsEncodedSrgbLumaThroughQuarterScaleAtUnityGain() {
|
||||
for (luma in listOf(0.0f, 0.1f, 0.249f, 0.25f)) {
|
||||
assertEquals(1.0f, ratioAt(luma), 0.000001f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addsGainSmoothlyAndMonotonicallyAboveQuarterScale() {
|
||||
val atStart = ratioAt(0.25f)
|
||||
val justAboveStart = ratioAt(0.251f)
|
||||
val atHalf = ratioAt(0.5f)
|
||||
val atThreeQuarters = ratioAt(0.75f)
|
||||
|
||||
assertTrue(justAboveStart > atStart)
|
||||
assertTrue(justAboveStart - atStart < 0.00001f)
|
||||
assertTrue(atHalf > justAboveStart)
|
||||
assertTrue(atThreeQuarters > atHalf)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reachesFullHdrRatioAtEncodedSrgbWhite() {
|
||||
assertEquals(FULL_HDR_RATIO, ratioAt(1.0f), 0.000001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clampsRequestedPeakToDeclaredGainmapRange() {
|
||||
assertEquals(
|
||||
MAX_GAIN_RATIO,
|
||||
EstimatedSdrGainmapMath.estimateGainRatio(1.0f, 8.0f, MAX_GAIN_RATIO),
|
||||
0.000001f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun computesLumaInEncodedSrgbDomain() {
|
||||
assertEquals(0.2126f, EstimatedSdrGainmapMath.encodedSrgbLuma(1.0f, 0.0f, 0.0f), 0.000001f)
|
||||
assertEquals(0.7152f, EstimatedSdrGainmapMath.encodedSrgbLuma(0.0f, 1.0f, 0.0f), 0.000001f)
|
||||
assertEquals(0.0722f, EstimatedSdrGainmapMath.encodedSrgbLuma(0.0f, 0.0f, 1.0f), 0.000001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun encodesUnityAndDeclaredMaximumAtGainmapEndpoints() {
|
||||
assertEquals(0, EstimatedSdrGainmapMath.encodeRatio(1.0f, 1.0f, MAX_GAIN_RATIO))
|
||||
assertEquals(255, EstimatedSdrGainmapMath.encodeRatio(MAX_GAIN_RATIO, 1.0f, MAX_GAIN_RATIO))
|
||||
}
|
||||
|
||||
private fun ratioAt(luma: Float): Float {
|
||||
return EstimatedSdrGainmapMath.estimateGainRatio(luma, FULL_HDR_RATIO, MAX_GAIN_RATIO)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val FULL_HDR_RATIO = 1.8f
|
||||
const val MAX_GAIN_RATIO = 4.0f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.hinnka.mycamera.hdr
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class RawGainmapMathTest {
|
||||
@Test
|
||||
fun decodesStandardSrgbTransferFunction() {
|
||||
assertEquals(0f, RawGainmapMath.srgbToLinear(0f), 0.000001f)
|
||||
assertEquals(1f, RawGainmapMath.srgbToLinear(1f), 0.000001f)
|
||||
assertEquals(0.214041f, RawGainmapMath.srgbToLinear(0.5f), 0.00001f)
|
||||
assertEquals(-0.214041f, RawGainmapMath.srgbToLinear(-0.5f), 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unityResidualEncodesAtZeroEvPosition() {
|
||||
val sdr = 0.5f
|
||||
val encoded = RawGainmapMath.encode(sdr, RawGainmapMath.srgbToLinear(sdr))
|
||||
|
||||
assertEquals(0.5f, encoded, 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reconstructsLinearHdrFromRgbLogResidual() {
|
||||
val sdr = 0.42f
|
||||
val hdr = 0.5f
|
||||
val encoded = RawGainmapMath.encode(sdr, hdr)
|
||||
|
||||
assertEquals(hdr, RawGainmapMath.reconstructLinear(sdr, encoded), 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clipsResidualAtDeclaredMetadataRange() {
|
||||
val sdr = 0.42f
|
||||
val encoded = RawGainmapMath.encode(sdr, 0.72f)
|
||||
val expected = (RawGainmapMath.srgbToLinear(sdr) + RawGainmapMath.OFFSET) *
|
||||
RawGainmapMath.MAX_GAIN_RATIO - RawGainmapMath.OFFSET
|
||||
|
||||
assertEquals(1f, encoded, 0.00001f)
|
||||
assertEquals(expected, RawGainmapMath.reconstructLinear(sdr, encoded), 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesNegativeGainResidual() {
|
||||
val sdr = 0.8f
|
||||
val hdr = RawGainmapMath.srgbToLinear(sdr) * 0.5f
|
||||
val encoded = RawGainmapMath.encode(sdr, hdr)
|
||||
|
||||
assertEquals(hdr, RawGainmapMath.reconstructLinear(sdr, encoded), 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun luminanceResidualKeepsLutRenderedSdrRgbAsColorBase() {
|
||||
val sdr = floatArrayOf(0.82f, 0.41f, 0.19f)
|
||||
val hdr = floatArrayOf(0.70f, 0.82f, 0.64f)
|
||||
val encoded = RawGainmapMath.encodeLuminance(sdr, hdr)
|
||||
val reconstructed = FloatArray(3) { channel ->
|
||||
RawGainmapMath.reconstructLinear(sdr[channel], encoded)
|
||||
}
|
||||
val appliedRatios = FloatArray(3) { channel ->
|
||||
(reconstructed[channel] + RawGainmapMath.OFFSET) /
|
||||
(RawGainmapMath.srgbToLinear(sdr[channel]) + RawGainmapMath.OFFSET)
|
||||
}
|
||||
|
||||
assertEquals(appliedRatios[0], appliedRatios[1], 0.00001f)
|
||||
assertEquals(appliedRatios[1], appliedRatios[2], 0.00001f)
|
||||
assertEquals(
|
||||
RawGainmapMath.linearLuma(hdr[0], hdr[1], hdr[2]),
|
||||
RawGainmapMath.linearLuma(reconstructed[0], reconstructed[1], reconstructed[2]),
|
||||
0.0001f,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun transfersLutLuminanceGainOntoHdrBaseRange() {
|
||||
val beforeLut = floatArrayOf(0.40f, 0.40f, 0.40f)
|
||||
val afterLut = floatArrayOf(0.52f, 0.52f, 0.52f)
|
||||
val hdr = floatArrayOf(0.50f, 0.50f, 0.50f)
|
||||
val encoded = RawGainmapMath.encodeLuminance(
|
||||
sdrEncodedRgb = afterLut,
|
||||
hdrLinearRgb = hdr,
|
||||
lutLuminanceGain = RawGainmapMath.computeLutLuminanceGain(
|
||||
RawGainmapMath.srgbToLinear(beforeLut[0]),
|
||||
RawGainmapMath.srgbToLinear(afterLut[0]),
|
||||
),
|
||||
)
|
||||
val reconstructed = RawGainmapMath.reconstructLinear(afterLut[0], encoded)
|
||||
val beforeLutLuma = RawGainmapMath.srgbToLinear(beforeLut[0])
|
||||
val afterLutLuma = RawGainmapMath.srgbToLinear(afterLut[0])
|
||||
val expected = RawGainmapMath.applyLutLuminanceGain(
|
||||
RawGainmapMath.computeLutLuminanceGain(
|
||||
beforeLutLuma,
|
||||
afterLutLuma,
|
||||
),
|
||||
hdr[0],
|
||||
)
|
||||
|
||||
assertEquals(expected, reconstructed, 0.00001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsExtendedHdrHeadroomLinearAfterLutAdjustedBase() {
|
||||
val lutGain = RawGainmapMath.computeLutLuminanceGain(0.5f, 0.35f)
|
||||
val adjustedWhite = RawGainmapMath.applyLutLuminanceGain(lutGain, 1.0f)
|
||||
val adjustedExtended = RawGainmapMath.applyLutLuminanceGain(lutGain, 2.25f)
|
||||
|
||||
assertEquals(1.25f, adjustedExtended - adjustedWhite, 0.00001f)
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.hinnka.mycamera.lut
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ChromaDenoiseDefaultsTest {
|
||||
@Test
|
||||
fun rawCaptureUsesAnExplicitDefaultWithoutScalingUserValues() {
|
||||
assertEquals(0.25f, ChromaDenoiseDefaults.forRawCapture(0f), 0f)
|
||||
assertEquals(0.25f, ChromaDenoiseDefaults.forRawCapture(0.1f), 0f)
|
||||
assertEquals(0.5f, ChromaDenoiseDefaults.forRawCapture(0.5f), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeNoiseBandwidthRespondsAcrossTheWholeSliderRange() {
|
||||
assertEquals(0f, ChromaDenoiseDefaults.noiseBandwidth(0f), 0f)
|
||||
assertEquals(5.25f, ChromaDenoiseDefaults.noiseBandwidth(0.25f), 1e-6f)
|
||||
assertEquals(9.5f, ChromaDenoiseDefaults.noiseBandwidth(0.5f), 1e-6f)
|
||||
assertEquals(18f, ChromaDenoiseDefaults.noiseBandwidth(1f), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun outputStrengthSmoothlyReachesFullAtOneQuarter() {
|
||||
assertEquals(0f, ChromaDenoiseDefaults.outputStrength(0f), 0f)
|
||||
assertEquals(0.5f, ChromaDenoiseDefaults.outputStrength(0.125f), 1e-6f)
|
||||
assertEquals(1f, ChromaDenoiseDefaults.outputStrength(0.25f), 0f)
|
||||
assertEquals(1f, ChromaDenoiseDefaults.outputStrength(1f), 0f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun edgeGuidanceOnlyRelaxesAboveHalfStrength() {
|
||||
assertEquals(0f, ChromaDenoiseDefaults.edgeGuidanceRelaxation(0f), 0f)
|
||||
assertEquals(0f, ChromaDenoiseDefaults.edgeGuidanceRelaxation(0.5f), 0f)
|
||||
assertEquals(0.5f, ChromaDenoiseDefaults.edgeGuidanceRelaxation(0.75f), 1e-6f)
|
||||
assertEquals(1f, ChromaDenoiseDefaults.edgeGuidanceRelaxation(1f), 0f)
|
||||
}
|
||||
}
|
||||
@@ -6,48 +6,69 @@ import org.junit.Test
|
||||
|
||||
class RawHdrReferenceMathTest {
|
||||
@Test
|
||||
fun leavesMidtonesUnchanged() {
|
||||
assertEquals(0.5f, RawHdrReferenceMath.expandedSceneLuma(0.5f), 0.0001f)
|
||||
fun usesOnlyBaselineExposure() {
|
||||
assertEquals(0f, RawHdrReferenceMath.exposureEv(0f), 0.0001f)
|
||||
assertEquals(-0.7f, RawHdrReferenceMath.exposureEv(-0.7f), 0.0001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givesOrdinaryHighlightsGentleLift() {
|
||||
val highlight = RawHdrReferenceMath.expandedSceneLuma(0.6f)
|
||||
|
||||
assertTrue(highlight > 0.66f)
|
||||
assertTrue(highlight < 0.72f)
|
||||
fun convertsBaselineExposureToExactLinearGain() {
|
||||
assertEquals(1f, RawHdrReferenceMath.exposureGain(0f), 0.0001f)
|
||||
assertEquals(Math.pow(2.0, -0.7).toFloat(), RawHdrReferenceMath.exposureGain(-0.7f), 0.0001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsNearWhiteHighlightSeparation() {
|
||||
val lower = RawHdrReferenceMath.expandedSceneLuma(0.98f)
|
||||
val white = RawHdrReferenceMath.expandedSceneLuma(1.0f)
|
||||
|
||||
assertTrue(white > lower)
|
||||
assertTrue(white - lower > 0.04f)
|
||||
fun sanitizesNonFiniteBaseline() {
|
||||
assertEquals(0f, RawHdrReferenceMath.exposureEv(Float.NaN), 0.0001f)
|
||||
assertEquals(0f, RawHdrReferenceMath.exposureEv(Float.POSITIVE_INFINITY), 0.0001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun broadHighlightsStillGetVisibleLift() {
|
||||
assertTrue(RawHdrReferenceMath.expandedSceneLuma(0.85f) > 1.35f)
|
||||
fun usesCompleteAcr3CurveThroughBlendStart() {
|
||||
val curve = ACR3Curve.samples()
|
||||
assertEquals(sampleCurve(curve, 0.08f), RawHdrReferenceMath.toneValue(0.08f), 0.000001f)
|
||||
assertEquals(sampleCurve(curve, 0.09f), RawHdrReferenceMath.toneValue(0.09f), 0.000001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsBrightCloudTonesOrdered() {
|
||||
val lower = RawHdrReferenceMath.expandedSceneLuma(0.72f)
|
||||
val middle = RawHdrReferenceMath.expandedSceneLuma(0.85f)
|
||||
val upper = RawHdrReferenceMath.expandedSceneLuma(0.98f)
|
||||
|
||||
assertTrue(middle > lower)
|
||||
assertTrue(upper > middle)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun capsDiffuseWhiteAtReferenceHeadroom() {
|
||||
assertEquals(
|
||||
RawHdrReferenceMath.WHITE_POINT_SCENE_LUMA,
|
||||
RawHdrReferenceMath.expandedSceneLuma(1.0f),
|
||||
0.0001f
|
||||
fun smoothlyBlendsFromAcr3ToAnchoredLinearGain() {
|
||||
val curve = ACR3Curve.samples()
|
||||
val value = 0.135f
|
||||
val linearGain = sampleCurve(curve, RawHdrReferenceMath.LINEAR_GAIN_START) /
|
||||
RawHdrReferenceMath.LINEAR_GAIN_START
|
||||
val t = smoothstep(
|
||||
RawHdrReferenceMath.ACR3_BLEND_START,
|
||||
RawHdrReferenceMath.LINEAR_GAIN_START,
|
||||
value,
|
||||
)
|
||||
val expected = sampleCurve(curve, value) +
|
||||
(value * linearGain - sampleCurve(curve, value)) * t
|
||||
|
||||
assertEquals(expected, RawHdrReferenceMath.toneValue(value), 0.000001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsMidtonesAndOverrangeOnTheSameUnnormalizedLinearGain() {
|
||||
val curve = ACR3Curve.samples()
|
||||
val linearGain = sampleCurve(curve, RawHdrReferenceMath.LINEAR_GAIN_START) /
|
||||
RawHdrReferenceMath.LINEAR_GAIN_START
|
||||
|
||||
assertTrue(linearGain > 1f)
|
||||
assertEquals(0.18f * linearGain, RawHdrReferenceMath.toneValue(0.18f), 0.000001f)
|
||||
assertEquals(0.75f * linearGain, RawHdrReferenceMath.toneValue(0.75f), 0.000001f)
|
||||
assertEquals(1.0f * linearGain, RawHdrReferenceMath.toneValue(1.0f), 0.000001f)
|
||||
assertEquals(2.5f * linearGain, RawHdrReferenceMath.toneValue(2.5f), 0.000001f)
|
||||
}
|
||||
|
||||
private fun sampleCurve(curve: FloatArray, value: Float): Float {
|
||||
val position = value.coerceIn(0f, 1f) * (curve.size - 1)
|
||||
val lowerIndex = position.toInt().coerceAtMost(curve.lastIndex - 1)
|
||||
val fraction = position - lowerIndex
|
||||
return curve[lowerIndex] + (curve[lowerIndex + 1] - curve[lowerIndex]) * fraction
|
||||
}
|
||||
|
||||
private fun smoothstep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val t = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f)
|
||||
return t * t * (3f - 2f * t)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user