feat: local laplacian shadows and highlights tone mapping

This commit is contained in:
zhoubinjia committed 2026-11-02 15:05:42 +08:00
1 parent 2c7191082d
commit aa9d8a26e7
12 files changed
+1518 -289

No files matched your search

@@ -57,6 +57,10 @@ internal data class ColorPassLocations(
val uTexelSizeLocation: Int,
val uCurveTextureLocation: Int,
val uCurveEnabledLocation: Int,
val uShadowsHighlightsMaskLocation: Int,
val uShadowsHighlightsStatsLocation: Int,
val uShadowsHighlightsCurveLocation: Int,
val uShadowsHighlightsAmountsLocation: Int,
val aPositionLocation: Int,
val aTexCoordLocation: Int,
)
@@ -167,6 +171,10 @@ internal class PreviewColorProgramCache {
uTexelSizeLocation = GLES30.glGetUniformLocation(program, "uTexelSize"),
uCurveTextureLocation = GLES30.glGetUniformLocation(program, "uCurveTexture"),
uCurveEnabledLocation = GLES30.glGetUniformLocation(program, "uCurveEnabled"),
uShadowsHighlightsMaskLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsMask"),
uShadowsHighlightsStatsLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsStats"),
uShadowsHighlightsCurveLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsCurve"),
uShadowsHighlightsAmountsLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsAmounts"),
aPositionLocation = GLES30.glGetAttribLocation(program, "aPosition"),
aTexCoordLocation = GLES30.glGetAttribLocation(program, "aTexCoord"),
)
@@ -101,6 +101,7 @@ class LutImageProcessor(context: Context? = null) {
private var lutSharpenHeight = 0
private val filmGrainGl = FilmGrainGl(TAG)
private val highlightDiffusionGl = HighlightDiffusionGl(TAG)
private val shadowsHighlightsMask = ShadowsHighlightsMaskGl(TAG)
// HDF (Highlight Diffusion) 光晕效果资源
private var hdfExtractBlurHProgram = 0
@@ -798,6 +799,19 @@ class LutImageProcessor(context: Context? = null) {
val lchAdjustments = ColorRecipeGl.lchAdjustments(colorRecipeParams)
val primaryCalibrationMatrix = CameraRawCalibrationMatrix.build(colorRecipeParams)
val program = shaderProgram
val shadowsHighlightsMaskResult = if (colorRecipeEnabled && ShadowsHighlightsShader.isActive(highlights, shadows)) {
shadowsHighlightsMask.render(
sourceTextureId = inputTextureId,
sourceWidth = width,
sourceHeight = height,
encoding = ShadowsHighlightsMaskGl.SourceEncoding.DisplaySrgb,
exposureEv = if (kotlin.math.abs(exposure) > 0.001f) exposure else 0f,
)?.takeIf { shadowsHighlightsMask.renderAmounts(highlights, shadows) }
.also { if (it == null) PLog.e(TAG, "Shadows/highlights mask unavailable, adjustment skipped") }
} else {
null
}
val shadowsHighlightsApplied = shadowsHighlightsMaskResult != null
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glViewport(0, 0, width, height)
@@ -810,6 +824,17 @@ class LutImageProcessor(context: Context? = null) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTextureId)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uImageTexture"), 0)
shadowsHighlightsMask.bind(
result = shadowsHighlightsMaskResult,
maskUnit = 4,
maskLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsMask"),
statsUnit = 8,
statsLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsStats"),
curveUnit = 9,
curveLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsCurve"),
amountsUnit = 10,
amountsLocation = GLES30.glGetUniformLocation(program, "uShadowsHighlightsAmounts"),
)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, lutTextureId)
@@ -845,7 +870,11 @@ class LutImageProcessor(context: Context? = null) {
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uTint"), tint)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uFade"), fade)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uVibrance"), vibrance)
ShadowsHighlightsShader.bindUniforms(program, highlights, shadows)
ShadowsHighlightsShader.bindUniforms(
program,
if (shadowsHighlightsApplied) highlights else 0f,
if (shadowsHighlightsApplied) shadows else 0f,
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uVignette"), vignette)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uFlash"), flash)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uBleachBypass"), bleachBypass)
@@ -2251,6 +2280,7 @@ class LutImageProcessor(context: Context? = null) {
if (clarityCompositeProgram != 0) GLES30.glDeleteProgram(clarityCompositeProgram)
releaseClarityFramebuffers()
filmGrainGl.release()
shadowsHighlightsMask.release()
highlightDiffusionGl.release()
for (i in 0..1) {
if (hdfTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(hdfTexId[i]), 0)
@@ -2402,6 +2432,10 @@ class LutImageProcessor(context: Context? = null) {
// 色散效果
uniform float uChromaticAberration; // 0.0 ~ 1.0 (色散强度)
uniform vec2 uTexelSize;
uniform highp sampler2D uShadowsHighlightsMask;
uniform highp sampler2D uShadowsHighlightsStats;
uniform highp sampler2D uShadowsHighlightsCurve;
uniform highp sampler2D uShadowsHighlightsAmounts;
// 辅助函数:亮度计算
const float PI = 3.14159265359;
@@ -2420,33 +2454,11 @@ class LutImageProcessor(context: Context? = null) {
${PreviewColorShaderModules.SANITIZE}
${BasicToneLutShader.GLSL}
vec3 prepareToneSample(vec3 sampleColor) {
vec3 prepared = sampleColor;
if (abs(uExposure) > 0.001) {
prepared = applyExposureInLinearSpace(prepared, uExposure);
}
return sanitizeColor(prepared);
vec3 shToLinear(vec3 rgb) {
return srgbToLinear(rgb);
}
vec3 sampleToneSource(vec2 uv) {
return prepareToneSample(sampleImage(clamp(uv, vec2(0.0), vec2(1.0))).rgb);
}
vec3 shRgbToXyz(vec3 rgb) {
vec3 linearRgb = srgbToLinear(rgb);
return mat3(
0.4360747, 0.2225045, 0.0139322,
0.3850649, 0.7168786, 0.0971045,
0.1430804, 0.0606169, 0.7141733
) * linearRgb;
}
vec3 shXyzToRgb(vec3 xyz) {
vec3 linearRgb = mat3(
3.1338561, -0.9787684, 0.0719453,
-1.6168667, 1.9161415, -0.2289914,
-0.4906146, 0.0334540, 1.4052427
) * xyz;
vec3 shFromLinear(vec3 linearRgb) {
return linearToSrgb(linearRgb);
}
@@ -69,6 +69,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
private val colorProgramCache = PreviewColorProgramCache()
private val shadowsHighlightsPreview = ShadowsHighlightsPreviewGl(TAG)
private val shadowsHighlightsStackPreview = ShadowsHighlightsPreviewGl(TAG)
private val shadowsHighlightsSourceMvp = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
private val enginePreview = RawEnginePreviewGl()
private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG)
private val mgcEisYuvRenderer = MgcEisYuvRenderer(TAG)
@@ -574,6 +577,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
*/
private fun resetGlResourceState() {
colorProgramCache.reset()
shadowsHighlightsPreview.reset()
shadowsHighlightsStackPreview.reset()
enginePreview.reset()
mgcEisHardwareBufferRenderer.resetAfterContextLoss()
mgcEisYuvRenderer.resetAfterContextLoss()
@@ -780,6 +785,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
params: com.hinnka.mycamera.model.ColorRecipeParams,
enableVideoLog: Boolean,
includeEnginePreview: Boolean = false,
toneMapSource: Boolean = false,
): ColorPassLocations? {
val variant = PreviewColorShaderVariant.forPass(
textureSource = textureSource,
@@ -788,7 +794,18 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
lutEnabled = lutEnabled && lutConfig != null,
videoLogEnabled = enableVideoLog && videoLogProfile.isEnabled,
)
return colorProgramCache.get(variant.copy(includeEnginePreview = includeEnginePreview))
return colorProgramCache.get(
variant.copy(includeEnginePreview = includeEnginePreview, toneMapSource = toneMapSource)
)
}
/** The tone-map source program, compiled only while highlights / shadows are active. */
private inline fun toneMapSourceLocationsFor(
params: com.hinnka.mycamera.model.ColorRecipeParams,
locations: () -> ColorPassLocations?,
): ColorPassLocations? {
if (params.isDefault() || !ShadowsHighlightsShader.isActive(params.highlights, params.shadows)) return null
return locations()
}
private fun drawColorPass(
@@ -809,11 +826,42 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveTextureId: Int,
curveEnabled: Boolean,
enableVideoLog: Boolean,
shadowsHighlights: ShadowsHighlightsPreviewGl? = null,
toneMapSourceLocations: ColorPassLocations? = null,
) {
// Highlights / shadows: render the tone-map source with the same inputs, then build the mask.
val shadowsHighlightsResult = if (shadowsHighlights != null && toneMapSourceLocations != null &&
!params.isDefault()
) {
shadowsHighlights.prepare(width, height, params.highlights, params.shadows) { framebuffer, w, h ->
drawColorPass(
locations = toneMapSourceLocations,
targetFboId = framebuffer,
width = w,
height = h,
sourceTextureTarget = sourceTextureTarget,
sourceTextureId = sourceTextureId,
sourceStMatrix = sourceStMatrix,
sourceCropRect = sourceCropRect,
targetMvpMatrix = shadowsHighlightsSourceMvp,
lutConfig = lutConfig,
lutTextureId = lutTextureId,
lutSize = lutSize,
lutEnabled = lutEnabled,
params = params,
curveTextureId = curveTextureId,
curveEnabled = curveEnabled,
enableVideoLog = enableVideoLog,
)
}
} else {
null
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, width, height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(locations.programId)
(shadowsHighlights ?: shadowsHighlightsPreview).bind(locations, shadowsHighlightsResult)
colorProgramCache.bindLogInput(locations)
enginePreview.bind(locations.uEnginePreviewLutLocation)
@@ -863,8 +911,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
ShadowsHighlightsShader.bindUniformLocations(
highlightsLocation = locations.uHighlightsLocation,
shadowsLocation = locations.uShadowsLocation,
highlights = params.highlights,
shadows = params.shadows
highlights = if (shadowsHighlightsResult != null) params.highlights else 0f,
shadows = if (shadowsHighlightsResult != null) params.shadows else 0f,
)
GLES30.glUniform1f(locations.uSharpeningLocation, params.sharpness.coerceIn(-1f, 1f))
GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain)
@@ -1124,6 +1172,17 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveTextureId = curveTextureId,
curveEnabled = curveEnabled && curveTextureId != 0,
enableVideoLog = false,
shadowsHighlights = shadowsHighlightsStackPreview,
toneMapSourceLocations = toneMapSourceLocationsFor(creativeParams) {
getColorPassLocations(
textureSource = PreviewColorTextureSource.TEXTURE_2D,
lutConfig = currentLutConfig,
lutEnabled = lutEnabled && currentLutConfig != null,
params = creativeParams,
enableVideoLog = false,
toneMapSource = true,
)
},
)
currentTexId = stackTextureId
}
@@ -1433,6 +1492,18 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveTextureId = layerCurveTextureId,
curveEnabled = layerCurveEnabled,
enableVideoLog = enableVideoLog,
shadowsHighlights = shadowsHighlightsPreview,
toneMapSourceLocations = toneMapSourceLocationsFor(layerParams) {
getColorPassLocations(
textureSource = currentCameraTextureSource,
lutConfig = layerLutConfig,
lutEnabled = layerLutEnabled,
params = layerParams,
enableVideoLog = enableVideoLog,
includeEnginePreview = plan != null,
toneMapSource = true,
)
},
)
// 测光和直方图(按需)
@@ -3164,6 +3235,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
clarityDownsampleProgram = 0
clarityCompositeProgram = 0
releaseClarityPreviewFramebuffers()
shadowsHighlightsPreview.release()
shadowsHighlightsStackPreview.release()
filmGrainGl.release()
highlightDiffusionGl.release()
releaseFilmGrainSourceFramebuffer()
@@ -130,7 +130,22 @@ internal object PreviewColorShader {
return dot(color, W);
}
${PreviewShadowsHighlightsShader.GLSL}
${if (variant.includeColorRecipe && !variant.toneMapSource) """
uniform highp sampler2D uShadowsHighlightsMask;
uniform highp sampler2D uShadowsHighlightsStats;
uniform highp sampler2D uShadowsHighlightsCurve;
uniform highp sampler2D uShadowsHighlightsAmounts;
vec3 shToLinear(vec3 color) {
return srgbToLinear(color);
}
vec3 shFromLinear(vec3 color) {
return linearToSrgb(color);
}
${ShadowsHighlightsShader.GLSL}
""" else ""}
${if (needsOklab) PreviewColorShaderModules.OKLAB else ""}
${if (needsClassifiers) PreviewColorShaderModules.LCH_CLASSIFIERS else ""}
@@ -193,8 +208,13 @@ internal object PreviewColorShader {
color.rgb = sanitizeColor(color.rgb);
}
color.rgb = applyPreviewShadowsHighlights(color.rgb);
${if (variant.toneMapSource) """
fragColor = vec4(color.rgb, 1.0);
return;
""" else if (variant.includeColorRecipe) """
color.rgb = applyShadowsHighlights(color.rgb, vOutputCoord);
color.rgb = sanitizeColor(color.rgb);
""" else ""}
float luma = getLuma(color.rgb);
@@ -23,6 +23,11 @@ internal data class PreviewColorShaderVariant(
val includeEnginePreview: Boolean = false,
val includeChromaticAberration: Boolean = false,
val includeColorRecipe: Boolean = true,
/**
* Writes the colour as it enters highlights / shadows and stops there: the source of the
* tone-map mask, so that mask and colour pass share one input chain.
*/
val toneMapSource: Boolean = false,
) {
companion object {
fun forPass(
@@ -1,31 +0,0 @@
package com.hinnka.mycamera.lut
object PreviewShadowsHighlightsShader {
val GLSL = """
vec3 applyPreviewShadowsHighlights(vec3 inputColor) {
vec3 color = inputColor;
float luma = getLuma(color);
float highlights = clamp(uHighlights, -1.0, 1.0);
float shadows = clamp(uShadows, -1.0, 1.0);
if (abs(highlights) > 0.001 || abs(shadows) > 0.001) {
float highlightMask = smoothstep(0.5, 1.0, luma);
float shadowMask = 1.0 - smoothstep(0.0, 0.5, luma);
if (abs(highlights) > 0.001) {
float highlightFactor = 1.0 + highlights * (highlights > 0.0 ? 0.7 : 0.3);
color = mix(color, color * highlightFactor, highlightMask);
}
if (abs(shadows) > 0.001) {
vec3 shadowTarget = (shadows > 0.0)
? (mix(color, vec3(luma), shadows * 0.2) + color * shadows * 0.5)
: (color * (1.0 + shadows * 0.5));
color = mix(color, shadowTarget, shadowMask);
}
}
return sanitizeColor(color);
}
""".trimIndent()
}
@@ -107,6 +107,14 @@ class RealtimeVideoRenderer(
return layers.lastOrNull { select(it.params) > 0.001f }?.params?.let(select) ?: 0f
}
private val identityMatrix = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
/** One highlights / shadows state per colour layer, indexed like `layers`. */
private val shadowsHighlightsSlots = mutableListOf<ShadowsHighlightsPreviewGl>()
private fun shadowsHighlightsSlot(index: Int): ShadowsHighlightsPreviewGl {
while (shadowsHighlightsSlots.size <= index) shadowsHighlightsSlots += ShadowsHighlightsPreviewGl(TAG)
return shadowsHighlightsSlots[index]
}
private val firstPassMvpMatrix = FloatArray(16).also {
Matrix.setIdentityM(it, 0)
if (mirrorHorizontally || mirrorVertically) {
@@ -282,6 +290,7 @@ class RealtimeVideoRenderer(
mvpMatrix = firstPassMvpMatrix,
enableVideoLog = videoLogProfile.isEnabled,
presentationTimeNs = timestampNs,
shadowsHighlights = shadowsHighlightsSlot(0),
)
if (layers.size > 1) {
@@ -302,6 +311,7 @@ class RealtimeVideoRenderer(
mvpMatrix = identityMatrix,
enableVideoLog = false,
presentationTimeNs = timestampNs,
shadowsHighlights = shadowsHighlightsSlot(index + 1),
)
}
}
@@ -439,6 +449,10 @@ class RealtimeVideoRenderer(
mvpMatrix: FloatArray,
enableVideoLog: Boolean,
presentationTimeNs: Long,
width: Int = encoderOutputSize.width,
height: Int = encoderOutputSize.height,
toneMapSource: Boolean = false,
shadowsHighlights: ShadowsHighlightsPreviewGl? = null,
) {
val lutEnabled = layer.lutConfig != null && layer.lutTextureId != 0
val variant = PreviewColorShaderVariant.forPass(
@@ -448,15 +462,42 @@ class RealtimeVideoRenderer(
lutEnabled = lutEnabled,
videoLogEnabled = enableVideoLog,
)
val locations = colorProgramCache.get(variant)
val locations = colorProgramCache.get(variant.copy(toneMapSource = toneMapSource))
?: throw IllegalStateException("Cannot create realtime video color shader: $variant")
// Highlights / shadows: render the tone-map source with the same inputs, then build the mask.
val params = layer.params
val shadowsHighlightsResult = if (shadowsHighlights != null && !params.isDefault() &&
ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
) {
shadowsHighlights.prepare(width, height, params.highlights, params.shadows) { framebuffer, w, h ->
drawLayer(
layer = layer,
targetFboId = framebuffer,
textureSource = textureSource,
textureTarget = textureTarget,
textureId = textureId,
sourceStMatrix = sourceStMatrix,
cropRect = cropRect,
mvpMatrix = identityMatrix,
enableVideoLog = enableVideoLog,
presentationTimeNs = presentationTimeNs,
width = w,
height = h,
toneMapSource = true,
)
}
} else {
null
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, encoderOutputSize.width, encoderOutputSize.height)
GLES30.glViewport(0, 0, width, height)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(locations.programId)
colorProgramCache.bindLogInput(locations)
(shadowsHighlights ?: shadowsHighlightsSlot(0)).bind(locations, shadowsHighlightsResult)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(textureTarget, textureId)
@@ -511,6 +552,7 @@ class RealtimeVideoRenderer(
locations = locations,
params = layer.params,
presentationTimeNs = presentationTimeNs,
shadowsHighlightsActive = shadowsHighlightsResult != null,
)
val curveEnabled = layer.curveTextureId != 0
@@ -532,8 +574,8 @@ class RealtimeVideoRenderer(
GLES30.glUniform2f(
locations.uTexelSizeLocation,
1f / max(1, encoderOutputSize.width).toFloat(),
1f / max(1, encoderOutputSize.height).toFloat(),
1f / max(1, width).toFloat(),
1f / max(1, height).toFloat(),
)
val positions = vertexBuffer ?: return
@@ -567,6 +609,7 @@ class RealtimeVideoRenderer(
locations: ColorPassLocations,
params: ColorRecipeParams,
presentationTimeNs: Long,
shadowsHighlightsActive: Boolean,
) {
val enabled = !params.isDefault()
GLES30.glUniform1i(locations.uColorRecipeEnabledLocation, if (enabled) 1 else 0)
@@ -590,8 +633,8 @@ class RealtimeVideoRenderer(
ShadowsHighlightsShader.bindUniformLocations(
highlightsLocation = locations.uHighlightsLocation,
shadowsLocation = locations.uShadowsLocation,
highlights = params.highlights,
shadows = params.shadows,
highlights = if (shadowsHighlightsActive) params.highlights else 0f,
shadows = if (shadowsHighlightsActive) params.shadows else 0f,
)
GLES30.glUniform1f(locations.uSharpeningLocation, params.sharpness.coerceIn(-1f, 1f))
GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain)
@@ -980,6 +1023,8 @@ class RealtimeVideoRenderer(
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
colorProgramCache.release()
shadowsHighlightsSlots.forEach { it.release() }
shadowsHighlightsSlots.clear()
basicToneTextures.release()
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
@@ -0,0 +1,800 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.raw.ACR3Curve
import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Builds Camera Raw's PV2012 tone-map mask (see docs/lrmobile-highlights-shadows-evidence.md and
* docs/lrmobile-tone-map-llf-evidence.md) at a reduced resolution:
*
* 1. `L = log2(flare + gray)` of the area-averaged RIMM gray of ProPhoto linear RGB with the ACR3
* render curve undone (MakeGrayLogImage for a non-raw negative, see [ShadowsHighlightsShader]).
* 2. Gaussian pyramid of L (DNG Gaussian resampling kernel `exp(-2x^2)`, extent 2, widened by the scale).
* 3. Input statistics on the last pyramid level whose long side exceeds 127 px.
* 4. Fast local Laplacian filter with alpha = 1, beta = 0: each intensity sample g_k is remapped as
* `clamp(L, g_k - sigma, g_k + sigma)`, its Laplacian is taken per level and the output Laplacian
* is tent-interpolated between samples by the Gaussian value; the top residual is the Gaussian top.
* 5. Output statistics on the same level, then `delta = min(Y - L + keyIn - keyOut, 4)`.
*
* Outputs: [Result.maskTextureId] RG16F (delta, L) at mask resolution, and [Result.statsTextureId]
* RGBA16F 3x1: (low, high, mean in gamma) of the input (x = 0) and of the filtered output (x = 1),
* and the recover threshold / white floor (x = 2, see `shRecoverThreshold`); [Result.curveTextureId]
* R32F 4096x2 with the inverse ACR3 curve (row 0) and the ACR3 curve (row 1); [Result.amountsTextureId]
* RGBA16F with the fill (row 0) and recover (row 1) level amounts over the image's log range for the
* sliders last passed to [renderAmounts]. The mask itself does not depend on the sliders, so it can
* be kept across frames while only the amount table follows slider changes.
*/
class ShadowsHighlightsMaskGl(private val tag: String) {
enum class SourceEncoding(val id: Int) {
/** sRGB transfer-encoded values (display-referred bitmaps). */
DisplaySrgb(0),
/** Linear RGB with sRGB primaries. */
Linear(1),
}
data class Result(
val maskTextureId: Int,
val statsTextureId: Int,
val curveTextureId: Int,
val amountsTextureId: Int,
)
private class Level(val width: Int, val height: Int) {
var gaussian = 0
val samples = IntArray(SAMPLE_TEXTURES)
var laplacian = 0
var output = 0
}
private var luminanceProgram = 0
private var resampleProgram = 0
private var statsProgram = 0
private var remapProgram = 0
private var laplacianProgram = 0
private var collapseProgram = 0
private var deltaProgram = 0
private var constantsProgram = 0
private var amountsProgram = 0
private var vertexArray = 0
private var framebuffer = 0
private var levels: List<Level> = emptyList()
private val statsChain = mutableListOf<Triple<Int, Int, Int>>()
private var statsTexture = 0
private var rangeTexture = 0
private var curveTexture = 0
private var amountsTexture = 0
private var exportedStatsTexture = 0
private var maskTexture = 0
private var maskWidth = 0
private var maskHeight = 0
private var statsLevel = 0
/**
* Renders the mask for [sourceTextureId], or returns null on failure.
*
* Leaves the framebuffer, viewport, program and texture bindings changed; callers bind their own
* state afterwards.
*/
fun render(
sourceTextureId: Int,
sourceWidth: Int,
sourceHeight: Int,
encoding: SourceEncoding,
exposureEv: Float,
): Result? {
if (!ensurePrograms()) return null
val longSide = max(sourceWidth, sourceHeight)
val scale = minOf(1f, MASK_LONG_SIDE.toFloat() / longSide)
val width = max(1, (sourceWidth * scale).roundToInt())
val height = max(1, (sourceHeight * scale).roundToInt())
if (!ensureTargets(width, height)) return null
GLES30.glBindVertexArray(vertexArray)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
val base = levels[0]
draw(luminanceProgram, base.gaussian, base.width, base.height) {
bindTexture(luminanceProgram, "uSource", 0, sourceTextureId)
bindTexture(luminanceProgram, "uCurve", 1, curveTexture)
GLES30.glUniform2i(uniform(luminanceProgram, "uSourceSize"), sourceWidth, sourceHeight)
GLES30.glUniform2i(uniform(luminanceProgram, "uMaskSize"), base.width, base.height)
GLES30.glUniform1i(uniform(luminanceProgram, "uSourceEncoding"), encoding.id)
GLES30.glUniform1f(uniform(luminanceProgram, "uExposure"), exposureEv)
}
for (l in 1 until levels.size) {
resample(levels[l - 1].gaussian, levels[l].gaussian, levels[l])
}
renderStats(levels[statsLevel].gaussian, column = 0)
for (group in 0 until SAMPLE_TEXTURES) {
draw(remapProgram, base.samples[group], base.width, base.height) {
bindTexture(remapProgram, "uLightness", 0, base.gaussian)
bindTexture(remapProgram, "uStats", 1, statsTexture)
GLES30.glUniform1i(uniform(remapProgram, "uSampleGroup"), group)
}
}
for (l in 0 until levels.size - 1) {
val fine = levels[l]
val coarse = levels[l + 1]
for (group in 0 until SAMPLE_TEXTURES) {
resample(fine.samples[group], coarse.samples[group], coarse)
}
draw(laplacianProgram, fine.laplacian, fine.width, fine.height) {
for (group in 0 until SAMPLE_TEXTURES) {
bindTexture(laplacianProgram, "uFine$group", group, fine.samples[group])
bindTexture(laplacianProgram, "uCoarse$group", SAMPLE_TEXTURES + group, coarse.samples[group])
}
bindTexture(laplacianProgram, "uGaussian", 2 * SAMPLE_TEXTURES, fine.gaussian)
bindTexture(laplacianProgram, "uStats", 2 * SAMPLE_TEXTURES + 1, statsTexture)
}
}
for (l in levels.size - 2 downTo 0) {
val fine = levels[l]
draw(collapseProgram, fine.output, fine.width, fine.height) {
bindTexture(collapseProgram, "uCoarse", 0, levels[l + 1].output)
bindTexture(collapseProgram, "uLaplacian", 1, fine.laplacian)
}
}
renderStats(levels[statsLevel].output, column = 1)
draw(deltaProgram, maskTexture, base.width, base.height) {
bindTexture(deltaProgram, "uOutput", 0, base.output)
bindTexture(deltaProgram, "uLightness", 1, base.gaussian)
bindTexture(deltaProgram, "uStats", 2, statsTexture)
}
draw(constantsProgram, exportedStatsTexture, 3, 1) {
bindTexture(constantsProgram, "uStats", 0, statsTexture)
}
GLES30.glBindVertexArray(0)
for (unit in 0..2 * SAMPLE_TEXTURES + 1) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GlUtils.checkGlError("$tag.ShadowsHighlightsMask")
return Result(maskTexture, exportedStatsTexture, curveTexture, amountsTexture)
}
/** Fills the level amount table of the last [render] for the given sliders. */
fun renderAmounts(highlights: Float, shadows: Float): Boolean {
if (amountsTexture == 0 || amountsProgram == 0) return false
GLES30.glBindVertexArray(vertexArray)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
draw(amountsProgram, amountsTexture, ShadowsHighlightsShader.AMOUNT_TABLE_SIZE, 2) {
bindTexture(amountsProgram, "uStats", 0, exportedStatsTexture)
GLES30.glUniform1f(uniform(amountsProgram, "uFill"), shadows.coerceIn(-1f, 1f))
GLES30.glUniform1f(uniform(amountsProgram, "uRecover"), -highlights.coerceIn(-1f, 1f))
}
GLES30.glBindVertexArray(0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GlUtils.checkGlError("$tag.ShadowsHighlightsAmounts")
return true
}
/** Binds [result] (null when the adjustment is inactive) to the four given units. */
fun bind(
result: Result?,
maskUnit: Int,
maskLocation: Int,
statsUnit: Int,
statsLocation: Int,
curveUnit: Int,
curveLocation: Int,
amountsUnit: Int,
amountsLocation: Int,
) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + maskUnit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, result?.maskTextureId ?: 0)
GLES30.glUniform1i(maskLocation, maskUnit)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + statsUnit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, result?.statsTextureId ?: 0)
GLES30.glUniform1i(statsLocation, statsUnit)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + curveUnit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, result?.curveTextureId ?: 0)
GLES30.glUniform1i(curveLocation, curveUnit)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + amountsUnit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, result?.amountsTextureId ?: 0)
GLES30.glUniform1i(amountsLocation, amountsUnit)
}
/** Forget handles after the owning EGL context has been lost. */
fun reset() {
levels = emptyList()
statsChain.clear()
statsTexture = 0
rangeTexture = 0
curveTexture = 0
amountsTexture = 0
exportedStatsTexture = 0
maskTexture = 0
maskWidth = 0
maskHeight = 0
statsLevel = 0
luminanceProgram = 0
resampleProgram = 0
statsProgram = 0
remapProgram = 0
laplacianProgram = 0
collapseProgram = 0
deltaProgram = 0
constantsProgram = 0
amountsProgram = 0
vertexArray = 0
framebuffer = 0
}
fun release() {
releaseTargets()
for (program in intArrayOf(
luminanceProgram, resampleProgram, statsProgram, remapProgram,
laplacianProgram, collapseProgram, deltaProgram, constantsProgram, amountsProgram,
)) {
if (program != 0) GLES30.glDeleteProgram(program)
}
luminanceProgram = 0
resampleProgram = 0
statsProgram = 0
remapProgram = 0
laplacianProgram = 0
collapseProgram = 0
deltaProgram = 0
constantsProgram = 0
amountsProgram = 0
if (vertexArray != 0) GLES30.glDeleteVertexArrays(1, intArrayOf(vertexArray), 0)
if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
vertexArray = 0
framebuffer = 0
}
private fun resample(source: Int, target: Int, targetLevel: Level) {
draw(resampleProgram, target, targetLevel.width, targetLevel.height) {
bindTexture(resampleProgram, "uSource", 0, source)
GLES30.glUniform2i(uniform(resampleProgram, "uTargetSize"), targetLevel.width, targetLevel.height)
}
}
/**
* Two 4x4 reduction chains into column [column]: the log2 range first (into the range texture),
* then the mean of the sRGB-encoded position inside that range (into the stats texture).
*/
private fun renderStats(sourceTexture: Int, column: Int) {
for (pass in 0..1) {
var input = sourceTexture
var seed = 1
for ((index, entry) in statsChain.withIndex()) {
val (texture, width, height) = entry
val last = index == statsChain.lastIndex
val target = when {
!last -> texture
pass == 0 -> rangeTexture
else -> statsTexture
}
draw(statsProgram, target, width, height, column.takeIf { last }) {
bindTexture(statsProgram, "uSource", 0, input)
bindTexture(statsProgram, "uRange", 1, rangeTexture)
GLES30.glUniform1i(uniform(statsProgram, "uSeed"), seed)
GLES30.glUniform1i(uniform(statsProgram, "uPass"), pass)
GLES30.glUniform1i(uniform(statsProgram, "uRangeColumn"), column)
GLES30.glUniform1i(uniform(statsProgram, "uColumn"), if (last) column else 0)
}
input = texture
seed = 0
}
}
}
private inline fun draw(
program: Int,
target: Int,
width: Int,
height: Int,
column: Int? = null,
setup: () -> Unit,
) {
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, target, 0,
)
if (column != null) GLES30.glViewport(column, 0, 1, 1) else GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(program)
setup()
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
}
private fun bindTexture(program: Int, name: String, unit: Int, texture: Int) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glUniform1i(uniform(program, name), unit)
}
private fun uniform(program: Int, name: String): Int = GLES30.glGetUniformLocation(program, name)
private fun ensurePrograms(): Boolean {
if (luminanceProgram == 0) luminanceProgram = createProgram(LUMINANCE_SHADER, "luminance")
if (resampleProgram == 0) resampleProgram = createProgram(RESAMPLE_SHADER, "resample")
if (statsProgram == 0) statsProgram = createProgram(STATS_SHADER, "stats")
if (remapProgram == 0) remapProgram = createProgram(REMAP_SHADER, "remap")
if (laplacianProgram == 0) laplacianProgram = createProgram(LAPLACIAN_SHADER, "laplacian")
if (collapseProgram == 0) collapseProgram = createProgram(COLLAPSE_SHADER, "collapse")
if (deltaProgram == 0) deltaProgram = createProgram(DELTA_SHADER, "delta")
if (constantsProgram == 0) constantsProgram = createProgram(CONSTANTS_SHADER, "constants")
if (amountsProgram == 0) amountsProgram = createProgram(AMOUNTS_SHADER, "amounts")
if (vertexArray == 0) {
val ids = IntArray(1)
GLES30.glGenVertexArrays(1, ids, 0)
vertexArray = ids[0]
}
if (framebuffer == 0) {
val ids = IntArray(1)
GLES30.glGenFramebuffers(1, ids, 0)
framebuffer = ids[0]
}
return luminanceProgram != 0 && resampleProgram != 0 && statsProgram != 0 && remapProgram != 0 &&
laplacianProgram != 0 && collapseProgram != 0 && deltaProgram != 0 && constantsProgram != 0 && amountsProgram != 0 &&
vertexArray != 0 && framebuffer != 0
}
private fun createProgram(fragmentSource: String, name: String): Int {
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource)
val program = if (vertexShader != 0 && fragmentShader != 0) {
GlUtils.linkProgram(vertexShader, fragmentShader)
} else {
0
}
if (vertexShader != 0) GLES30.glDeleteShader(vertexShader)
if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader)
if (program == 0) PLog.e(tag, "Failed to create shadows/highlights mask $name program")
return program
}
private fun ensureTargets(width: Int, height: Int): Boolean {
if (maskTexture != 0 && width == maskWidth && height == maskHeight) return true
releaseTargets()
val built = mutableListOf<Level>()
var w = width
var h = height
while (true) {
built += Level(w, h)
if ((w == 1 && h == 1) || built.size == MAX_LEVELS) break
w = ceil(w / 2.0).toInt()
h = ceil(h / 2.0).toInt()
}
for (level in built) {
level.gaussian = createTexture(GLES30.GL_R16F, level.width, level.height)
level.laplacian = createTexture(GLES30.GL_R16F, level.width, level.height)
// The collapse never writes the top level: its output is the Gaussian top.
level.output = if (level === built.last()) level.gaussian else
createTexture(GLES30.GL_R16F, level.width, level.height)
for (group in 0 until SAMPLE_TEXTURES) {
level.samples[group] = createTexture(GLES30.GL_RGBA16F, level.width, level.height)
}
}
levels = built
statsLevel = built.indexOfLast { max(it.width, it.height) > 127 }.coerceAtLeast(0)
var sw = built[statsLevel].width
var sh = built[statsLevel].height
do {
sw = ceil(sw / 4.0).toInt()
sh = ceil(sh / 4.0).toInt()
statsChain += Triple(createTexture(GLES30.GL_RGBA16F, sw, sh), sw, sh)
} while (sw > 1 || sh > 1)
statsTexture = createTexture(GLES30.GL_RGBA16F, 2, 1)
rangeTexture = createTexture(GLES30.GL_RGBA16F, 2, 1)
curveTexture = createCurveTexture()
amountsTexture = createTexture(GLES30.GL_RGBA16F, ShadowsHighlightsShader.AMOUNT_TABLE_SIZE, 2)
exportedStatsTexture = createTexture(GLES30.GL_RGBA16F, 3, 1)
maskTexture = createTexture(GLES30.GL_RG16F, width, height)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer)
for (texture in intArrayOf(maskTexture, built[0].samples[0], built[0].gaussian)) {
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, texture, 0,
)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(tag, "Shadows/highlights mask framebuffer incomplete: 0x${Integer.toHexString(status)}")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
releaseTargets()
return false
}
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
maskWidth = width
maskHeight = height
return true
}
private fun createTexture(format: Int, width: Int, height: Int): Int {
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, ids[0])
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, format, width, height)
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.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return ids[0]
}
private fun createCurveTexture(): Int {
val samples = ByteBuffer.allocateDirect(2 * CURVE_SIZE * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
for (index in 0 until CURVE_SIZE) samples.put(ACR3Curve.inputForOutput(index.toFloat() / (CURVE_SIZE - 1)))
for (index in 0 until CURVE_SIZE) samples.put(ACR3Curve.outputForInput(index.toFloat() / (CURVE_SIZE - 1)))
samples.flip()
val texture = createTexture(GLES30.GL_R32F, CURVE_SIZE, 2)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture)
GLES30.glTexSubImage2D(GLES30.GL_TEXTURE_2D, 0, 0, 0, CURVE_SIZE, 2, GLES30.GL_RED, GLES30.GL_FLOAT, samples)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
return texture
}
private fun releaseTargets() {
val textures = mutableListOf<Int>()
for ((index, level) in levels.withIndex()) {
textures += level.gaussian
textures += level.laplacian
if (index != levels.lastIndex) textures += level.output
textures += level.samples.toList()
}
statsChain.forEach { textures += it.first }
textures += statsTexture
textures += rangeTexture
textures += curveTexture
textures += amountsTexture
textures += exportedStatsTexture
textures += maskTexture
val live = textures.filter { it != 0 }.toIntArray()
if (live.isNotEmpty()) GLES30.glDeleteTextures(live.size, live, 0)
levels = emptyList()
statsChain.clear()
statsTexture = 0
rangeTexture = 0
curveTexture = 0
amountsTexture = 0
exportedStatsTexture = 0
maskTexture = 0
maskWidth = 0
maskHeight = 0
statsLevel = 0
}
companion object {
/**
* Long side of the mask; Camera Raw filters a reduced negative level. The local Laplacian
* result depends on it, so preview and capture must use the same value.
*/
internal const val MASK_LONG_SIDE = 768
/** Pyramid depth limit of cr_gaussian_pyramid. */
private const val MAX_LEVELS = 16
/** Remap samples are packed four per RGBA texture. */
private const val SAMPLE_TEXTURES = 4
private const val SAMPLE_COUNT = SAMPLE_TEXTURES * 4
/** Samples per ACR3 table row (R32F, interpolated in the shader). */
private const val CURVE_SIZE = 4096
/** Upper bound of source taps per mask texel and axis during the luminance reduction. */
private const val REDUCE_MAX_TAPS = 8
private val VERTEX_SHADER = """
#version 300 es
void main() {
vec2 position = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0);
}
""".trimIndent()
private val HEADER = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
""".trimIndent()
/** Gaussian resampling of `source` at destination texel `dst` (DNG `exp(-2x^2)`, extent 2). */
private val RESAMPLE_GLSL = """
vec4 shResample(sampler2D source, ivec2 dst, ivec2 dstSize) {
ivec2 srcSize = textureSize(source, 0);
vec2 scale = vec2(srcSize) / vec2(dstSize);
vec2 width = max(scale, vec2(1.0));
vec2 center = (vec2(dst) + 0.5) * scale;
ivec2 first = ivec2(floor(center - 2.0 * width));
vec4 sum = vec4(0.0);
float weightSum = 0.0;
for (int j = 0; j < 10; j++) {
int y = first.y + j;
float dy = (float(y) + 0.5 - center.y) / width.y;
if (dy > 2.0) break;
if (dy < -2.0) continue;
float wy = exp(-2.0 * dy * dy);
for (int i = 0; i < 10; i++) {
int x = first.x + i;
float dx = (float(x) + 0.5 - center.x) / width.x;
if (dx > 2.0) break;
if (dx < -2.0) continue;
float w = wy * exp(-2.0 * dx * dx);
sum += w * texelFetch(source, clamp(ivec2(x, y), ivec2(0), srcSize - 1), 0);
weightSum += w;
}
}
return sum / max(weightSum, 1e-6);
}
""".trimIndent()
/** LLF sample placement and sigma from the input statistics (texel 0 of uStats). */
private val SAMPLING_GLSL = """
const int SH_SAMPLE_COUNT = $SAMPLE_COUNT;
// Returns (lo, step, sigma).
vec3 shLlfSampling(sampler2D stats) {
vec4 s = texelFetch(stats, ivec2(0, 0), 0);
float lo = s.x;
float hi = max(s.y, s.x + 1e-3);
float range = hi - lo;
// Camera Raw piecewise-linear sigma table over the input dynamic range (stops).
float knotX[6] = float[6](2.0, 3.5, 5.0, 6.5, 12.0, 14.0);
float knotY[6] = float[6](1.4, 1.6, 2.3, 2.5, 2.5, 2.0);
float spread = knotY[0];
if (range >= knotX[5]) {
spread = knotY[5];
} else {
for (int i = 0; i < 5; i++) {
if (range >= knotX[i] && range < knotX[i + 1]) {
spread = mix(knotY[i], knotY[i + 1], (range - knotX[i]) / (knotX[i + 1] - knotX[i]));
}
}
}
float sigma = log2(${ShadowsHighlightsShader.FLARE_GLSL} + spread);
return vec3(lo, range / float(SH_SAMPLE_COUNT - 1), sigma);
}
""".trimIndent()
private val LUMINANCE_SHADER = """
$HEADER
uniform sampler2D uSource;
uniform sampler2D uCurve;
uniform ivec2 uSourceSize;
uniform int uSourceEncoding;
uniform float uExposure;
uniform ivec2 uMaskSize;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
vec3 maskSrgbToLinear(vec3 value) {
vec3 v = max(value, vec3(0.0));
vec3 low = v / 12.92;
vec3 high = pow((v + 0.055) / 1.055, vec3(2.4));
return mix(low, high, step(vec3(0.04045), v));
}
void main() {
ivec2 dst = ivec2(gl_FragCoord.xy);
vec2 scale = vec2(uSourceSize) / vec2(uMaskSize);
ivec2 start = min(ivec2(floor(vec2(dst) * scale)), uSourceSize - 1);
ivec2 end = clamp(ivec2(floor(vec2(dst + 1) * scale)), start + 1, uSourceSize);
ivec2 stride = max((end - start + ($REDUCE_MAX_TAPS - 1)) / $REDUCE_MAX_TAPS, ivec2(1));
float sum = 0.0;
float count = 0.0;
for (int y = 0; y < $REDUCE_MAX_TAPS; y++) {
int py = start.y + y * stride.y;
if (py >= end.y) break;
for (int x = 0; x < $REDUCE_MAX_TAPS; x++) {
int px = start.x + x * stride.x;
if (px >= end.x) break;
vec3 color = texelFetch(uSource, ivec2(px, py), 0).rgb;
if (color != color) color = vec3(0.0);
vec3 linearColor = uSourceEncoding == 0 ? maskSrgbToLinear(color) : color;
sum += shGray(shToSceneProPhoto(uCurve, linearColor * exp2(uExposure)));
count += 1.0;
}
}
fragColor = vec4(shLinearToLog2(sum / max(count, 1.0)), 0.0, 0.0, 1.0);
}
""".trimStart()
private val RESAMPLE_SHADER = """
$HEADER
uniform sampler2D uSource;
uniform ivec2 uTargetSize;
out vec4 fragColor;
$RESAMPLE_GLSL
void main() {
fragColor = shResample(uSource, ivec2(gl_FragCoord.xy), uTargetSize);
}
""".trimStart()
private val STATS_SHADER = """
$HEADER
uniform sampler2D uSource;
uniform sampler2D uRange;
uniform int uSeed;
uniform int uPass;
uniform int uRangeColumn;
uniform int uColumn;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
${ShadowsHighlightsShader.STATS_GLSL}
// Pass 0: (min L, max L). Pass 1: (low, high, mean of the sRGB-encoded linear position
// inside [low, high]). Seeds read L from .r.
void main() {
ivec2 size = textureSize(uSource, 0);
ivec2 origin = (ivec2(gl_FragCoord.xy) - ivec2(uColumn, 0)) * 4;
vec4 range = texelFetch(uRange, ivec2(uRangeColumn, 0), 0);
float lo = shLog2ToLinear(range.x);
float hi = shLog2ToLinear(range.y);
vec4 result = uPass == 0 ? vec4(1e4, -1e4, 0.0, 1.0) : vec4(range.x, range.y, 0.0, 1.0);
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 4; i++) {
vec4 v = texelFetch(uSource, min(origin + ivec2(i, j), size - 1), 0);
if (uPass == 0) {
if (uSeed != 0) v = vec4(v.r, v.r, 0.0, 1.0);
result.x = min(result.x, v.x);
result.y = max(result.y, v.y);
} else {
if (uSeed != 0) {
float t = (shLog2ToLinear(v.r) - lo) / max(hi - lo, 1e-20);
v.z = shSrgbEncode(clamp(t, 0.0, 1.0));
}
result.z += v.z / 16.0;
}
}
}
fragColor = result;
}
""".trimStart()
private val REMAP_SHADER = """
$HEADER
uniform sampler2D uLightness;
uniform sampler2D uStats;
uniform int uSampleGroup;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
$SAMPLING_GLSL
void main() {
vec3 sampling = shLlfSampling(uStats);
float l = texelFetch(uLightness, ivec2(gl_FragCoord.xy), 0).r;
vec4 g = sampling.x + sampling.y * (vec4(0.0, 1.0, 2.0, 3.0) + float(uSampleGroup * 4));
fragColor = clamp(vec4(l), g - sampling.z, g + sampling.z);
}
""".trimStart()
private val LAPLACIAN_SHADER = """
$HEADER
uniform sampler2D uFine0;
uniform sampler2D uFine1;
uniform sampler2D uFine2;
uniform sampler2D uFine3;
uniform sampler2D uCoarse0;
uniform sampler2D uCoarse1;
uniform sampler2D uCoarse2;
uniform sampler2D uCoarse3;
uniform sampler2D uGaussian;
uniform sampler2D uStats;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
$RESAMPLE_GLSL
$SAMPLING_GLSL
float pick(vec4 v, int c) {
return c == 0 ? v.x : (c == 1 ? v.y : (c == 2 ? v.z : v.w));
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 size = textureSize(uFine0, 0);
vec4 lap[4];
lap[0] = texelFetch(uFine0, p, 0) - shResample(uCoarse0, p, size);
lap[1] = texelFetch(uFine1, p, 0) - shResample(uCoarse1, p, size);
lap[2] = texelFetch(uFine2, p, 0) - shResample(uCoarse2, p, size);
lap[3] = texelFetch(uFine3, p, 0) - shResample(uCoarse3, p, size);
vec3 sampling = shLlfSampling(uStats);
float g = texelFetch(uGaussian, p, 0).r;
float t = clamp((g - sampling.x) / sampling.y, 0.0, float(SH_SAMPLE_COUNT - 1));
int k0 = min(int(floor(t)), SH_SAMPLE_COUNT - 2);
float f = t - float(k0);
int k1 = k0 + 1;
float a = pick(lap[k0 / 4], k0 - (k0 / 4) * 4);
float b = pick(lap[k1 / 4], k1 - (k1 / 4) * 4);
fragColor = vec4(mix(a, b, f), 0.0, 0.0, 1.0);
}
""".trimStart()
private val COLLAPSE_SHADER = """
$HEADER
uniform sampler2D uCoarse;
uniform sampler2D uLaplacian;
out vec4 fragColor;
$RESAMPLE_GLSL
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 size = textureSize(uLaplacian, 0);
float value = shResample(uCoarse, p, size).r + texelFetch(uLaplacian, p, 0).r;
fragColor = vec4(value, 0.0, 0.0, 1.0);
}
""".trimStart()
private val DELTA_SHADER = """
$HEADER
uniform sampler2D uOutput;
uniform sampler2D uLightness;
uniform sampler2D uStats;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
${ShadowsHighlightsShader.STATS_GLSL}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
float l = texelFetch(uLightness, p, 0).r;
float y = texelFetch(uOutput, p, 0).r;
float keyIn = shStatsKey(texelFetch(uStats, ivec2(0, 0), 0));
float keyOut = shStatsKey(texelFetch(uStats, ivec2(1, 0), 0));
fragColor = vec4(min(y - l + keyIn - keyOut, 4.0), l, 0.0, 1.0);
}
""".trimStart()
private val CONSTANTS_SHADER = """
$HEADER
uniform sampler2D uStats;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
${ShadowsHighlightsShader.STATS_GLSL}
${ShadowsHighlightsShader.TONE_MAP_GLSL}
void main() {
int column = int(gl_FragCoord.x);
vec4 statsIn = texelFetch(uStats, ivec2(0, 0), 0);
vec4 statsOut = texelFetch(uStats, ivec2(1, 0), 0);
if (column == 0) {
fragColor = statsIn;
} else if (column == 1) {
fragColor = statsOut;
} else {
fragColor = vec4(shRecoverThreshold(statsIn, statsOut), 0.0, 1.0);
}
}
""".trimStart()
private val AMOUNTS_SHADER = """
$HEADER
uniform sampler2D uStats;
uniform float uFill;
uniform float uRecover;
out vec4 fragColor;
${ShadowsHighlightsShader.LOG_GLSL}
${ShadowsHighlightsShader.STATS_GLSL}
${ShadowsHighlightsShader.TONE_MAP_GLSL}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec4 statsIn = texelFetch(uStats, ivec2(0, 0), 0);
vec4 statsOut = texelFetch(uStats, ivec2(1, 0), 0);
vec2 recoverCurve = texelFetch(uStats, ivec2(2, 0), 0).xy;
vec2 domain = shAmountDomain(statsIn);
float x = mix(domain.x, domain.y, float(p.x) / float(SH_AMOUNT_TABLE_SIZE - 1));
vec4 fillLevels;
vec4 recoverLevels;
shLevelAmountsAt(x, shToneMapTargets(statsIn, statsOut), statsIn, recoverCurve,
uFill, uRecover, fillLevels, recoverLevels);
fragColor = p.y == 0 ? fillLevels : recoverLevels;
}
""".trimStart()
}
}
@@ -0,0 +1,143 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.utils.PLog
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Highlights / shadows for one realtime colour pass.
*
* The caller renders the colour as it enters the tone map (the `toneMapSource` variant of the
* same colour pass) into [prepare]'s source target; the mask is rebuilt from it every
* [MASK_REFRESH_FRAMES] frames, while the slider-dependent level table follows every frame. The
* source is rendered at twice the mask size so the mask's luminance reduction box-filters it, as the
* capture path does from the full image.
*/
internal class ShadowsHighlightsPreviewGl(private val tag: String) {
private val mask = ShadowsHighlightsMaskGl(tag)
private var sourceTexture = 0
private var sourceFramebuffer = 0
private var sourceWidth = 0
private var sourceHeight = 0
private var result: ShadowsHighlightsMaskGl.Result? = null
private var framesSinceBuild = 0
/**
* Returns the mask for this frame, or null when the adjustment is inactive or unavailable.
* [drawSource] renders the tone-map source into the given framebuffer at the given size.
*/
fun prepare(
outputWidth: Int,
outputHeight: Int,
highlights: Float,
shadows: Float,
drawSource: (framebuffer: Int, width: Int, height: Int) -> Unit,
): ShadowsHighlightsMaskGl.Result? {
if (!ShadowsHighlightsShader.isActive(highlights, shadows)) {
result = null
return null
}
val scale = minOf(1f, ShadowsHighlightsMaskGl.MASK_LONG_SIDE.toFloat() / max(outputWidth, outputHeight))
val width = max(1, (outputWidth * scale).roundToInt()) * SOURCE_OVERSAMPLE
val height = max(1, (outputHeight * scale).roundToInt()) * SOURCE_OVERSAMPLE
if (!ensureSource(width, height)) return null
if (result == null || ++framesSinceBuild >= MASK_REFRESH_FRAMES) {
drawSource(sourceFramebuffer, width, height)
result = mask.render(
sourceTextureId = sourceTexture,
sourceWidth = width,
sourceHeight = height,
encoding = ShadowsHighlightsMaskGl.SourceEncoding.DisplaySrgb,
exposureEv = 0f,
)
framesSinceBuild = 0
}
if (result != null && !mask.renderAmounts(highlights, shadows)) result = null
if (result == null) PLog.e(tag, "Realtime shadows/highlights mask unavailable")
return result
}
fun bind(locations: ColorPassLocations, result: ShadowsHighlightsMaskGl.Result?) {
mask.bind(
result = result,
maskUnit = MASK_UNIT,
maskLocation = locations.uShadowsHighlightsMaskLocation,
statsUnit = MASK_UNIT + 1,
statsLocation = locations.uShadowsHighlightsStatsLocation,
curveUnit = MASK_UNIT + 2,
curveLocation = locations.uShadowsHighlightsCurveLocation,
amountsUnit = MASK_UNIT + 3,
amountsLocation = locations.uShadowsHighlightsAmountsLocation,
)
}
fun release() {
mask.release()
releaseSource()
result = null
}
/** Forget handles after the owning EGL context has been lost. */
fun reset() {
sourceTexture = 0
sourceFramebuffer = 0
sourceWidth = 0
sourceHeight = 0
result = null
mask.reset()
}
private fun ensureSource(width: Int, height: Int): Boolean {
if (sourceTexture != 0 && width == sourceWidth && height == sourceHeight) return true
releaseSource()
result = null
val ids = IntArray(1)
GLES30.glGenTextures(1, ids, 0)
sourceTexture = ids[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTexture)
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height)
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.glGenFramebuffers(1, ids, 0)
sourceFramebuffer = ids[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, sourceFramebuffer)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, sourceTexture, 0,
)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
PLog.e(tag, "Shadows/highlights source framebuffer incomplete: 0x${Integer.toHexString(status)}")
releaseSource()
return false
}
sourceWidth = width
sourceHeight = height
return true
}
private fun releaseSource() {
if (sourceTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(sourceTexture), 0)
if (sourceFramebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(sourceFramebuffer), 0)
sourceTexture = 0
sourceFramebuffer = 0
sourceWidth = 0
sourceHeight = 0
}
companion object {
/** Frames between mask rebuilds; the slider-dependent level table follows every frame. */
private const val MASK_REFRESH_FRAMES = 2
/** The source is rendered at this multiple of the mask size and box-filtered by the mask. */
private const val SOURCE_OVERSAMPLE = 2
/** First of four consecutive texture units; the colour pass uses units 0..5. */
const val MASK_UNIT = 8
}
}
@@ -2,6 +2,16 @@ package com.hinnka.mycamera.lut
import android.opengl.GLES30
/**
* Highlights / shadows after Camera Raw's PV2012 tone map (`cr_tone_map_info`), see
* docs/lrmobile-highlights-shadows-evidence.md and tools/lrmobile/tone_map_reference.py.
*
* Works on `x = log2(flare + Y)`: the mask from [ShadowsHighlightsMaskGl] gives the local
* compression `delta` (local Laplacian output minus input), and four levels pull x towards
* targets derived from `x + delta` and from image statistics. Highlights ("recover") only act
* where the target lies below x, shadows ("fill") only where it lies above. The new luminance is
* applied as a gain on linear RGB.
*/
object ShadowsHighlightsShader {
fun bindUniforms(program: Int, highlights: Float, shadows: Float) {
bindUniformLocations(
@@ -22,176 +32,363 @@ object ShadowsHighlightsShader {
GLES30.glUniform1f(shadowsLocation, shadows)
}
val GLSL = """
const float SH_LAB_EPSILON = 216.0 / 24389.0;
const float SH_LAB_KAPPA = 24389.0 / 27.0;
const float SH_LOW_APPROX = 0.000001;
const float SH_COMPRESS = 0.5;
const float SH_HIGHLIGHTS_COLOR_ADJUSTMENT = 0.6;
const float SH_SHADOWS_COLOR_ADJUSTMENT = 1.0;
const float SH_RANGE_SIGMA = 0.105;
const float SH_RANGE_SIGMA2 = SH_RANGE_SIGMA * SH_RANGE_SIGMA;
/** Matches the early-out in `applyShadowsHighlights`. */
fun isActive(highlights: Float, shadows: Float): Boolean =
kotlin.math.abs(highlights) >= 0.0005f || kotlin.math.abs(shadows) >= 0.0005f
float shSanitizeFloat(float value) {
if (value != value) return 0.0;
return value;
/** Samples of the per-image fill / recover level table (see `shLevelAmountsAt`). */
const val AMOUNT_TABLE_SIZE = 256
/** Camera Raw's default log flare (2^-12). */
const val FLARE_GLSL = "(1.0 / 4096.0)"
/**
* LinearToLog2 with flare (odd-symmetric below zero), the gray it is applied to, and Camera
* Raw's working domain for bitmaps: a non-raw negative renders through the default ACR3 curve
* (`cr_negative::RenderCurve`, `neg+0x170 == 1`), so the tone map runs on ProPhoto linear RGB
* with that curve undone per channel (`AppendStage_UndoRenderCurve`) and the curve is applied
* again afterwards. `curve` rows: 0 = inverse ACR3, 1 = ACR3 (see [ShadowsHighlightsMaskGl]).
*/
val LOG_GLSL = """
// cr_stage_RGBToGray on ProPhoto linear RGB.
float shGray(vec3 prophoto) {
return dot(prophoto, vec3(0.30, 0.59, 0.11));
}
vec3 shSanitizeColor(vec3 color) {
return vec3(
shSanitizeFloat(color.r),
shSanitizeFloat(color.g),
shSanitizeFloat(color.b)
);
vec3 shSrgbToProPhoto(vec3 linearSrgb) {
return mat3(
0.5293459, 0.0983744, 0.0168832,
0.3300728, 0.8734611, 0.1176725,
0.1405813, 0.0281647, 0.8654443
) * linearSrgb;
}
float shSign(float value) {
return value < 0.0 ? -1.0 : 1.0;
vec3 shProPhotoToSrgb(vec3 prophoto) {
return mat3(
2.0340762, -0.2288134, -0.0085698,
-0.7273343, 1.2317302, -0.1532866,
-0.3067417, -0.0029169, 1.1618564
) * prophoto;
}
float shSignedInv(float value, float signSource) {
float inv = abs(value) > SH_LOW_APPROX ? 1.0 / abs(value) : 1.0 / SH_LOW_APPROX;
return signSource < 0.0 ? -inv : inv;
float shCurve(sampler2D curve, float value, int row) {
highp int lastIndex = textureSize(curve, 0).x - 1;
float position = clamp(value, 0.0, 1.0) * float(lastIndex);
highp int lowerIndex = int(floor(position));
highp int upperIndex = min(lowerIndex + 1, lastIndex);
float lower = texelFetch(curve, ivec2(lowerIndex, row), 0).r;
float upper = texelFetch(curve, ivec2(upperIndex, row), 0).r;
return mix(lower, upper, position - float(lowerIndex));
}
float shColorCorrection(float adjustment, float signSource) {
return (clamp(adjustment, 0.0, 1.0) - 0.5) * shSign(signSource) + 0.5;
// Linear sRGB -> ProPhoto linear with the ACR3 render curve undone.
vec3 shToSceneProPhoto(sampler2D curve, vec3 linearSrgb) {
vec3 prophoto = clamp(shSrgbToProPhoto(linearSrgb), 0.0, 1.0);
return vec3(shCurve(curve, prophoto.r, 0), shCurve(curve, prophoto.g, 0), shCurve(curve, prophoto.b, 0));
}
vec3 shLabF(vec3 value) {
vec3 linearPart = (SH_LAB_KAPPA * value + vec3(16.0)) / 116.0;
vec3 cubePart = pow(max(value, vec3(0.0)), vec3(1.0 / 3.0));
return mix(linearPart, cubePart, step(vec3(SH_LAB_EPSILON), value));
vec3 shRenderProPhoto(sampler2D curve, vec3 scene) {
return vec3(shCurve(curve, scene.r, 1), shCurve(curve, scene.g, 1), shCurve(curve, scene.b, 1));
}
vec3 shLabFInv(vec3 value) {
vec3 cubePart = value * value * value;
vec3 linearPart = (116.0 * value - vec3(16.0)) / SH_LAB_KAPPA;
return mix(linearPart, cubePart, step(vec3(0.20689655172413796), value));
float shLinearToLog2(float y) {
float flare = $FLARE_GLSL;
return y >= 0.0 ? log2(flare + y) : 2.0 * log2(flare) - log2(flare - y);
}
vec3 shXyzToLab(vec3 xyz) {
vec3 f = shLabF(xyz / vec3(0.9642, 1.0, 0.8249));
return vec3(116.0 * f.y - 16.0, 500.0 * (f.x - f.y), 200.0 * (f.y - f.z));
float shLog2ToLinear(float l) {
float flare = $FLARE_GLSL;
float lf = log2(flare);
return l >= lf ? exp2(l) - flare : flare - exp2(2.0 * lf - l);
}
""".trimIndent()
/**
* Stats texture layout: texel (0, 0) input, (1, 0) filtered output, each (low, high, mean of
* sRGB-encoded window position) in log2. `shStatsKey` gives the `cr_image_stats` key (+0x10):
* linear values inside the 0.01%..99.99% window are normalised to it, averaged after sRGB
* encoding, decoded and mapped back (needs [LOG_GLSL]).
*/
val STATS_GLSL = """
float shSrgbEncode(float v) {
return v <= 0.0031308 ? 12.92 * v : 1.055 * pow(v, 1.0 / 2.4) - 0.055;
}
vec3 shLabToXyz(vec3 lab) {
float fy = (lab.x + 16.0) / 116.0;
vec3 f = vec3(lab.y / 500.0 + fy, fy, fy - lab.z / 200.0);
return vec3(0.9642, 1.0, 0.8249) * shLabFInv(f);
float shSrgbDecode(float v) {
return v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4);
}
vec3 shRgbToLabScaled(vec3 color) {
vec3 lab = shXyzToLab(shRgbToXyz(color));
return lab / vec3(100.0, 128.0, 128.0);
float shStatsKey(vec4 stats) {
float lo = shLog2ToLinear(stats.x);
float hi = shLog2ToLinear(stats.y);
return shLinearToLog2(lo + (hi - lo) * shSrgbDecode(clamp(stats.z, 0.0, 1.0)));
}
""".trimIndent()
vec3 shLabScaledToRgb(vec3 labScaled) {
vec3 lab = labScaled * vec3(100.0, 128.0, 128.0);
return shXyzToRgb(shLabToXyz(lab));
}
float shTonalRangeWeight(float sampleL, float centerL) {
float delta = sampleL - centerL;
float bilateral = exp(-(delta * delta) / max(2.0 * SH_RANGE_SIGMA2, SH_LOW_APPROX));
float edgeStop = 1.0 - smoothstep(0.12, 0.24, abs(delta));
return bilateral * edgeStop;
}
void shAddBaseSample(vec2 uv, float centerL, float spatialWeight, inout float sum, inout float weightSum) {
float sampleL = shRgbToLabScaled(sampleToneSource(clamp(uv, vec2(0.0), vec2(1.0)))).x;
float weight = spatialWeight * shTonalRangeWeight(sampleL, centerL);
sum += sampleL * weight;
weightSum += weight;
}
vec2 shPixelOffset(float x, float y) {
return vec2(x * uTexelSize.x, y * uTexelSize.y);
}
void shAddBaseSamplePair(
vec2 uv,
vec2 offset,
float centerL,
float spatialWeight,
inout float sum,
inout float weightSum
) {
shAddBaseSample(uv + offset, centerL, spatialWeight, sum, weightSum);
shAddBaseSample(uv - offset, centerL, spatialWeight, sum, weightSum);
}
float shSampleBaseL(vec2 uv, vec3 centerLab) {
float centerL = centerLab.x;
float sum = centerL * 0.48;
float weightSum = 0.48;
shAddBaseSamplePair(uv, shPixelOffset(2.5, 1.5), centerL, 0.11, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-1.5, 3.5), centerL, 0.11, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(4.5, -2.5), centerL, 0.10, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-4.5, -3.5), centerL, 0.10, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(7.5, 4.5), centerL, 0.065, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-6.5, 8.5), centerL, 0.06, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(10.5, -7.5), centerL, 0.055, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(15.5, 11.5), centerL, 0.035, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-18.5, 5.5), centerL, 0.03, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(22.5, -13.5), centerL, 0.026, sum, weightSum);
return sum / max(weightSum, 0.0001);
}
vec3 shOverlay(vec3 a, vec3 b, float opacity, float transform, float ccorrect) {
float remainingOpacity = min(opacity * opacity, 4.0);
float tonalWeight = clamp(transform, 0.0, 1.0);
// Split strong adjustments into convex blends instead of extrapolating past
// the overlay result. The local base is a mask, not a luminance bound:
// clipping to it creates a jump whenever the base crosses the source L.
for (int i = 0; i < 4; i++) {
float optrans = min(remainingOpacity, 1.0) * tonalWeight;
if (optrans <= 0.0) break;
remainingOpacity = max(remainingOpacity - 1.0, 0.0);
float la = a.x;
float lb = (b.x - 0.5) * shSign(opacity) * shSign(1.0 - la) + 0.5;
lb = clamp(lb, 0.0, 1.0);
float lref = shSignedInv(la, la);
float href = shSignedInv(1.0 - la, 1.0 - la);
float overL = la > 0.5
? 1.0 - (1.0 - 2.0 * (la - 0.5)) * (1.0 - lb)
: 2.0 * la * lb;
a.x = mix(la, overL, optrans);
float chromaFactor = a.x * lref * ccorrect + (1.0 - a.x) * href * (1.0 - ccorrect);
a.y = mix(a.y, (a.y + b.y) * chromaFactor, optrans);
a.z = mix(a.z, (a.z + b.z) * chromaFactor, optrans);
/**
* Initialize pieces shared by the apply pass and the mask constants pass (needs [LOG_GLSL] and
* [STATS_GLSL]).
*/
val TONE_MAP_GLSL = """
// cr_amount_curve::Evaluate: dng_spline_solver (unit-spaced knots 0..4) evaluated at the
// amount, mapped back through the piecewise-linear knots.
float shAmountTotal(float knots[5], float amount) {
float s[5];
float b = knots[1] - knots[0];
s[0] = b;
for (int j = 2; j < 5; j++) {
float d = knots[j] - knots[j - 1];
s[j - 1] = 0.5 * (b + d);
b = d;
}
return a;
s[4] = 2.0 * b - s[3];
s[0] = 2.0 * s[0] - s[1];
float e[5] = float[5](0.25, 0.25, 0.25, 0.25, 0.5);
float fv[5] = float[5](0.5, 0.25, 0.25, 0.25, 0.25);
float g[5];
g[0] = 0.75 * (s[0] + s[1]);
for (int j = 1; j < 4; j++) g[j] = 1.5 * s[j];
g[4] = 0.75 * (s[3] + s[4]);
for (int j = 1; j < 5; j++) {
float a = 1.0 - fv[j - 1] * e[j];
if (j != 4) fv[j] /= a;
g[j] = (g[j] - g[j - 1] * e[j]) / a;
}
for (int j = 3; j >= 0; j--) g[j] -= fv[j] * g[j + 1];
float t = clamp(amount, 0.0, 4.0);
int seg = min(int(floor(t)), 3);
float u = t - float(seg);
float u2 = u * u;
float u3 = u2 * u;
float v = (2.0 * u3 - 3.0 * u2 + 1.0) * knots[seg] + (u3 - 2.0 * u2 + u) * g[seg]
+ (-2.0 * u3 + 3.0 * u2) * knots[seg + 1] + (u3 - u2) * g[seg + 1];
int j = clamp(int(ceil(amount)) - 1, 0, 3);
return (v - knots[j]) / (knots[j + 1] - knots[j]) + float(j);
}
// The cr_amount_curve total split into four unit levels.
vec4 shLevelAmounts(float knots[5], float amount) {
float total = shAmountTotal(knots, amount);
vec4 levels;
levels.x = min(total, 1.0); total -= levels.x;
levels.y = min(total, 1.0); total -= levels.y;
levels.z = min(total, 1.0); total -= levels.z;
levels.w = total;
return levels;
}
// Highlight side of cr_tone_map_info::Initialize: key M, A = max(p99.99, M + 1/8) of the
// input, and the level targets from the filtered output.
void shHighTargets(vec4 statsIn, vec4 statsOut, out float m, out float highA, out float tHigh[4]) {
m = shStatsKey(statsIn);
float outShift = m - shStatsKey(statsOut);
highA = max(statsIn.y, m + 0.125);
float highB = max(statsOut.y + outShift, m + 0.125);
tHigh[0] = max(highB - 0.25, m + 0.1 * (highB - m));
for (int k = 1; k < 4; k++) tHigh[k] = 0.5 * (tHigh[k - 1] + m);
}
// cr_recover_curve::Evaluate: where the 99.99% point lands for amount 2t through the
// first two global levels.
float shRecoverHighPoint(float t, float m, float highA, float tHigh[4], float highP) {
float knots[5] = float[5](highA, tHigh[0], tHigh[1], tHigh[2], tHigh[3]);
float total = shAmountTotal(knots, 2.0 * t);
float first = min(total, 1.0);
float r0 = (tHigh[0] - m) / (highA - m);
float r1 = (tHigh[1] - m) / (highA - m);
float after0 = highP + first * (m + r0 * (highP - m) - highP);
return after0 + (total - first) * (m + r1 * (highP - m) - after0);
}
// Recover threshold and white floor (Initialize 0x3478e94..0x3478f54): (1000, 1) unless the
// white clip W lies above the first targets; then the amount mapping the 99.99% point
// onto W (dng_1d_function::EvaluateInverse, secant on [0, 1]) and its relative position.
vec2 shRecoverThreshold(vec4 statsIn, vec4 statsOut) {
float m;
float highA;
float tHigh[4];
shHighTargets(statsIn, statsOut, m, highA, tHigh);
float white = shLinearToLog2(1.0);
if (!(white > tHigh[0] || white > tHigh[1])) return vec2(1000.0, 1.0);
float highP = statsIn.y;
float floorValue = clamp((highP - white) / max(m - white, exp2(-16.0)), 0.0, 1.0);
float x0 = 0.0;
float y0 = shRecoverHighPoint(0.0, m, highA, tHigh, highP);
float x1 = 1.0;
float y1 = shRecoverHighPoint(1.0, m, highA, tHigh, highP);
for (int i = 0; i < 30; i++) {
if (abs(y1 - y0) < 1e-10) break;
float x2 = clamp(x1 + (white - y1) * (x1 - x0) / (y1 - y0), 0.0, 1.0);
x0 = x1;
y0 = y1;
x1 = x2;
y1 = shRecoverHighPoint(x2, m, highA, tHigh, highP);
}
return vec2(max(2.0 * x1, 0.0), floorValue);
}
// cr_tone_map_info::Initialize targets: key M, A / B anchors and the level targets.
struct ShToneMapTargets {
float m;
float lowA;
float highA;
float tLow[4];
float tHigh[4];
float negativeBoost;
};
ShToneMapTargets shToneMapTargets(vec4 statsIn, vec4 statsOut) {
ShToneMapTargets t;
shHighTargets(statsIn, statsOut, t.m, t.highA, t.tHigh);
// The output stats share the delta's key alignment (keyIn - keyOut).
float outShift = t.m - shStatsKey(statsOut);
t.lowA = min(statsIn.x, t.m - 0.125);
float lowB = min(statsOut.x + outShift, t.m - 0.125);
t.tLow[0] = min(lowB + 0.25, t.m + 0.1 * (lowB - t.m));
for (int k = 1; k < 4; k++) t.tLow[k] = 0.5 * (t.tLow[k - 1] + t.m);
float spanLow = t.lowA - 2.0 * (t.tLow[0] - t.lowA);
float spanHigh = t.highA - 2.0 * (t.tHigh[0] - t.highA);
float span = spanHigh - spanLow;
t.negativeBoost = span < 12.0 ? 12.0 / max(span, exp2(-15.0)) : 1.0;
return t;
}
// CalcFillAmounts / CalcRecoverAmounts at log luminance x.
void shLevelAmountsAt(
float x, ShToneMapTargets t, vec4 statsIn, vec2 recoverCurve, float fill, float recover,
out vec4 fillLevels, out vec4 recoverLevels
) {
float m = t.m;
fillLevels = vec4(0.0);
float fillAmount = 2.0 * fill;
if (fillAmount > 0.0) {
float floorSlope = statsIn.x != m ? 0.85 / (m - statsIn.x) : 0.0;
float floorGain = clamp(0.15 + (x - statsIn.x) * floorSlope, 0.15, 1.0);
float knots[5] = float[5](t.lowA, t.tLow[0], t.tLow[1], t.tLow[2], t.tLow[3]);
fillLevels = shLevelAmounts(knots, fillAmount * 1.2 * pow(floorGain, 0.454545));
} else if (fillAmount < 0.0) {
fillLevels.x = fillAmount * (1.0 + clamp(-0.5 * fillAmount, 0.0, 1.0) * (t.negativeBoost - 1.0));
}
recoverLevels = vec4(0.0);
float recoverAmount = 2.0 * recover;
if (recoverAmount > 0.0) {
float threshold = recoverCurve.x;
if (threshold < recoverAmount) {
// Attenuate the amount beyond the threshold towards white (cr_div_map).
float p = 0.3 + 0.35 * min(0.5 * recoverAmount, 1.0);
float k = 0.8 * p / ((1.0 - p) * 0.2);
float q = recoverCurve.y;
float slope = m != statsIn.y ? (1.0 - q) / (m - statsIn.y) : 0.0;
float u = clamp(1.0 + slope * (x - m), q, 1.0);
recoverAmount = threshold + (recoverAmount - threshold) * (k * u / (k * u + 1.0 - u));
}
float knots[5] = float[5](t.highA, t.tHigh[0], t.tHigh[1], t.tHigh[2], t.tHigh[3]);
recoverLevels = shLevelAmounts(knots, recoverAmount);
} else if (recoverAmount < 0.0) {
// Initialize: knee = max(-exposure[0x98], M + 1); no exposure offset here.
float knee = max(0.0, m + 1.0);
float slope = knee != m ? 0.9 / (m - knee) : 0.0;
float a0 = pow(clamp(1.0 + slope * (x - m), 0.0, 1.0), 0.714285) * recoverAmount;
recoverLevels.x = a0 * (1.0 + clamp(-0.5 * a0, 0.0, 1.0) * (t.negativeBoost - 1.0));
}
}
// Log-luminance span covered by the amount table; amounts are constant outside the
// image range except through the clamps above, so one stop of margin suffices.
const int SH_AMOUNT_TABLE_SIZE = $AMOUNT_TABLE_SIZE;
vec2 shAmountDomain(vec4 statsIn) {
return vec2(statsIn.x - 1.0, max(statsIn.y, 0.0) + 1.0);
}
""".trimIndent()
/**
* Requires the host to declare `uHighlights`, `uShadows`, `highp sampler2D uShadowsHighlightsMask`,
* `highp sampler2D uShadowsHighlightsStats` (3x1: input stats, output stats, recover threshold),
* `highp sampler2D uShadowsHighlightsCurve` (ACR3 tables), `highp sampler2D uShadowsHighlightsAmounts`
* (level amounts for the current sliders; all four from [ShadowsHighlightsMaskGl], built from the
* same source and exposure) and `shToLinear` / `shFromLinear` for its RGB encoding.
*/
val GLSL = LOG_GLSL + "\n" + STATS_GLSL + "\n" + TONE_MAP_GLSL + "\n" + """
// Joint-bilateral upsample of (delta, L) guided by the full-resolution log luminance.
const float SH_UPSAMPLE_RANGE = 0.5;
float shSampleDelta(vec2 uv, float x) {
ivec2 size = textureSize(uShadowsHighlightsMask, 0);
vec2 position = clamp(uv, vec2(0.0), vec2(1.0)) * vec2(size) - 0.5;
vec2 cell = floor(position);
vec2 f = position - cell;
ivec2 i0 = clamp(ivec2(cell), ivec2(0), size - 1);
ivec2 i1 = clamp(ivec2(cell) + 1, ivec2(0), size - 1);
vec2 m00 = texelFetch(uShadowsHighlightsMask, i0, 0).rg;
vec2 m10 = texelFetch(uShadowsHighlightsMask, ivec2(i1.x, i0.y), 0).rg;
vec2 m01 = texelFetch(uShadowsHighlightsMask, ivec2(i0.x, i1.y), 0).rg;
vec2 m11 = texelFetch(uShadowsHighlightsMask, i1, 0).rg;
vec4 delta = vec4(m00.x, m10.x, m01.x, m11.x);
vec4 dl = (vec4(m00.y, m10.y, m01.y, m11.y) - x) / SH_UPSAMPLE_RANGE;
vec4 bilinear = vec4((1.0 - f.x) * (1.0 - f.y), f.x * (1.0 - f.y), (1.0 - f.x) * f.y, f.x * f.y);
vec4 weight = bilinear * (exp(-0.5 * dl * dl) + 0.001);
return dot(weight, delta) / dot(weight, vec4(1.0));
}
vec3 applyShadowsHighlights(vec3 inputColor, vec2 uv) {
float highlights = 2.0 * clamp(uHighlights, -1.0, 1.0);
float shadows = 2.0 * clamp(uShadows, -1.0, 1.0);
if (abs(highlights) < 0.001 && abs(shadows) < 0.001) {
float fill = clamp(uShadows, -1.0, 1.0);
float recover = -clamp(uHighlights, -1.0, 1.0);
if (abs(fill) < 0.0005 && abs(recover) < 0.0005) {
return inputColor;
}
vec3 linearColor = shToLinear(inputColor);
vec3 scene = shToSceneProPhoto(uShadowsHighlightsCurve, linearColor);
float luminance = shGray(scene);
if (!(luminance > 0.0)) {
return inputColor;
}
float x = shLinearToLog2(luminance);
vec3 lab = shRgbToLabScaled(inputColor);
float baseL = clamp(shSampleBaseL(uv, lab), 0.0, 1.0);
vec3 maskLab = vec3(1.0 - baseL, 0.0, 0.0);
float compressDenom = max(1.0 - SH_COMPRESS, 0.0001);
vec4 statsIn = texelFetch(uShadowsHighlightsStats, ivec2(0, 0), 0);
vec4 statsOut = texelFetch(uShadowsHighlightsStats, ivec2(1, 0), 0);
ShToneMapTargets t = shToneMapTargets(statsIn, statsOut);
float m = t.m;
float falloffSigma = clamp((statsIn.y - statsIn.x - 2.0) * 0.03125 + 0.125, 0.125, 0.25);
float falloffK = 1.0 / (falloffSigma * falloffSigma);
float falloffC = clamp(1.25 - abs(fill - recover), 0.0, 1.0);
float highlightsXform = clamp(1.0 - maskLab.x / compressDenom, 0.0, 1.0);
float highlightsCcorrect = shColorCorrection(SH_HIGHLIGHTS_COLOR_ADJUSTMENT, -highlights);
lab = shOverlay(lab, maskLab, -highlights, highlightsXform, 1.0 - highlightsCcorrect);
// Level amounts from the per-image table (row 0 fill, row 1 recover).
vec2 domain = shAmountDomain(statsIn);
float position = clamp((x - domain.x) / (domain.y - domain.x), 0.0, 1.0) * float(SH_AMOUNT_TABLE_SIZE - 1);
int i0 = int(floor(position));
int i1 = min(i0 + 1, SH_AMOUNT_TABLE_SIZE - 1);
float f = position - float(i0);
vec4 fillLevels = mix(
texelFetch(uShadowsHighlightsAmounts, ivec2(i0, 0), 0),
texelFetch(uShadowsHighlightsAmounts, ivec2(i1, 0), 0), f);
vec4 recoverLevels = mix(
texelFetch(uShadowsHighlightsAmounts, ivec2(i0, 1), 0),
texelFetch(uShadowsHighlightsAmounts, ivec2(i1, 1), 0), f);
float shadowsXform = clamp(maskLab.x / compressDenom - SH_COMPRESS / compressDenom, 0.0, 1.0);
float shadowsCcorrect = shColorCorrection(SH_SHADOWS_COLOR_ADJUSTMENT, shadows);
lab = shOverlay(lab, maskLab, shadows, shadowsXform, shadowsCcorrect);
// cr_tone_map_info::Process
bool below = x < m;
float y = x;
float delta = shSampleDelta(uv, x);
float r0 = below ? (t.tLow[0] - m) / (t.lowA - m) : (t.tHigh[0] - m) / (t.highA - m);
float detailOffset = x + delta - (m + r0 * (x - m));
for (int k = 0; k < 4; k++) {
float rk = below ? (t.tLow[k] - m) / (t.lowA - m) : (t.tHigh[k] - m) / (t.highA - m);
float target = m + rk * (x - m) + detailOffset;
float amount = target < y ? recoverLevels[k] : fillLevels[k];
float e = y - target;
float falloff = falloffC + (1.0 - falloffC) * (1.0 - exp(-falloffK * e * e));
y += falloff * amount * (target - y);
}
return shSanitizeColor(shLabScaledToRgb(lab));
float gain = shLog2ToLinear(y) / luminance;
// Re-render through ACR3 and apply the change to the original colour, so that a unit
// gain is exact and colours outside the ProPhoto [0, 1] range keep their excess.
vec3 rendered = shRenderProPhoto(uShadowsHighlightsCurve, scene * gain);
vec3 original = shRenderProPhoto(uShadowsHighlightsCurve, scene);
return shFromLinear(linearColor + shProPhotoToSrgb(rendered - original));
}
""".trimIndent()
}
@@ -1,9 +1,9 @@
package com.hinnka.mycamera.raw
import android.opengl.GLES30
import com.hinnka.mycamera.lut.ShadowsHighlightsMaskGl
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
import com.hinnka.mycamera.utils.PLog
import kotlin.math.max
/** Applies the optional linear-domain shadows/highlights and black/white adjustments. */
internal class RawAdjustmentPass(
@@ -28,6 +28,7 @@ internal class RawAdjustmentPass(
)
private var program = 0
private val shadowsHighlightsMask = ShadowsHighlightsMaskGl(TAG)
private var loggedUniformLocations = false
fun render(input: Input): Output? {
@@ -44,6 +45,22 @@ internal class RawAdjustmentPass(
"source=${input.textureId} target=${input.targetTextureId} " +
"size=${input.width}x${input.height}",
)
val maskResult = if (ShadowsHighlightsShader.isActive(input.highlights, input.shadows)) {
shadowsHighlightsMask.render(
sourceTextureId = input.textureId,
sourceWidth = input.width,
sourceHeight = input.height,
encoding = ShadowsHighlightsMaskGl.SourceEncoding.Linear,
exposureEv = 0f,
)?.takeIf { shadowsHighlightsMask.renderAmounts(input.highlights, input.shadows) }.also {
if (it == null) {
PLog.e(TAG, "Unable to build RAW shadows/highlights mask")
return null
}
}
} else {
null
}
GLES30.glUseProgram(activeProgram)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, input.targetFramebufferId)
GLES30.glViewport(0, 0, input.width, input.height)
@@ -54,10 +71,16 @@ internal class RawAdjustmentPass(
GLES30.glGetUniformLocation(activeProgram, "uInputTexture"),
0,
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(activeProgram, "uTexelSize"),
1f / max(1, input.width),
1f / max(1, input.height),
shadowsHighlightsMask.bind(
result = maskResult,
maskUnit = 1,
maskLocation = GLES30.glGetUniformLocation(activeProgram, "uShadowsHighlightsMask"),
statsUnit = 2,
statsLocation = GLES30.glGetUniformLocation(activeProgram, "uShadowsHighlightsStats"),
curveUnit = 3,
curveLocation = GLES30.glGetUniformLocation(activeProgram, "uShadowsHighlightsCurve"),
amountsUnit = 4,
amountsLocation = GLES30.glGetUniformLocation(activeProgram, "uShadowsHighlightsAmounts"),
)
val highlightsLocation = GLES30.glGetUniformLocation(activeProgram, "uHighlights")
@@ -91,6 +114,7 @@ internal class RawAdjustmentPass(
}
fun release() {
shadowsHighlightsMask.release()
if (program != 0) {
GLES30.glDeleteProgram(program)
program = 0
@@ -116,30 +140,21 @@ internal class RawAdjustmentPass(
out vec4 fragColor;
uniform sampler2D uInputTexture;
uniform vec2 uTexelSize;
uniform highp sampler2D uShadowsHighlightsMask;
uniform highp sampler2D uShadowsHighlightsStats;
uniform highp sampler2D uShadowsHighlightsCurve;
uniform highp sampler2D uShadowsHighlightsAmounts;
uniform float uHighlights;
uniform float uShadows;
uniform float uBlacks;
uniform float uWhites;
vec3 sampleToneSource(vec2 uv) {
return texture(uInputTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb;
vec3 shToLinear(vec3 rgb) {
return rgb;
}
vec3 shRgbToXyz(vec3 rgb) {
return mat3(
0.4360747, 0.2225045, 0.0139322,
0.3850649, 0.7168786, 0.0971045,
0.1430804, 0.0606169, 0.7141733
) * rgb;
}
vec3 shXyzToRgb(vec3 xyz) {
return mat3(
3.1338561, -0.9787684, 0.0719453,
-1.6168667, 1.9161415, -0.2289914,
-0.4906146, 0.0334540, 1.4052427
) * xyz;
vec3 shFromLinear(vec3 linearRgb) {
return linearRgb;
}
${ShadowsHighlightsShader.GLSL}
@@ -1,6 +1,5 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
/** Selects a rendering engine and composes its shader with the shared tone pipeline. */
internal class RawEngineTonePass(
@@ -159,7 +158,7 @@ internal class RawEngineTonePass(
}
internal fun fragmentShader(shaderDefinition: RawEngineToneShaderDefinition): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -183,7 +182,7 @@ internal class RawEngineTonePass(
internal fun hdrReferenceFragmentShader(
shaderDefinition: RawEngineToneShaderDefinition,
): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -306,7 +305,7 @@ internal class RawEngineTonePass(
shaderDefinition: RawEngineToneShaderDefinition,
isHncs: Boolean,
): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -339,16 +338,6 @@ internal class RawEngineTonePass(
""".trimIndent()
}
fun combinedFragmentShaderFor(
colorEngine: RawRenderingEngine,
includeShadowsHighlights: Boolean = true,
): String {
return combinedFragmentShader(
shaderDefinition = shaderDefinitionFor(colorEngine),
includeShadowsHighlights = includeShadowsHighlights,
)
}
internal fun shaderDefinitionFor(
colorEngine: RawRenderingEngine,
): RawEngineToneShaderDefinition {
@@ -368,50 +357,7 @@ internal class RawEngineTonePass(
private fun combinedFragmentShader(
shaderDefinition: RawEngineToneShaderDefinition,
includeShadowsHighlights: Boolean,
): String {
val shadowsHighlightsUniforms = if (includeShadowsHighlights) {
"""
uniform vec2 uTexelSize;
uniform float uHighlights;
uniform float uShadows;
""".trimIndent()
} else {
""
}
val shadowsHighlightsFunctions = if (includeShadowsHighlights) {
"""
vec3 sampleToneSource(vec2 uv) {
vec3 sampleColor = texture(uInputTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb;
return applyEngineTone(prepareEngineInput(sampleColor));
}
vec3 shRgbToXyz(vec3 rgb) {
return mat3(
0.4360747, 0.2225045, 0.0139322,
0.3850649, 0.7168786, 0.0971045,
0.1430804, 0.0606169, 0.7141733
) * rgb;
}
vec3 shXyzToRgb(vec3 xyz) {
return mat3(
3.1338561, -0.9787684, 0.0719453,
-1.6168667, 1.9161415, -0.2289914,
-0.4906146, 0.0334540, 1.4052427
) * xyz;
}
${ShadowsHighlightsShader.GLSL}
""".trimIndent()
} else {
""
}
val shadowsHighlightsApply = if (includeShadowsHighlights) {
"color = applyShadowsHighlights(color, vTexCoord);"
} else {
""
}
val prepareEngineInputFunction = if (shaderDefinition.includeAdobeProfilePipeline) {
"""
vec3 prepareProfileGainInput(vec3 color) {
@@ -456,7 +402,6 @@ internal class RawEngineTonePass(
uniform sampler2D uInputTexture;
uniform float uBlacks;
uniform float uWhites;
$shadowsHighlightsUniforms
uniform mat3 uProfileToEngineTransform;
${shaderDefinition.engineUniforms}
@@ -479,8 +424,6 @@ internal class RawEngineTonePass(
$prepareEngineInputFunction
$shadowsHighlightsFunctions
const vec3 BW_LUMA = vec3(0.2126, 0.7152, 0.0722);
const float BW_EPSILON = 0.000001;
@@ -521,7 +464,6 @@ internal class RawEngineTonePass(
vec3 color = texture(uInputTexture, vTexCoord).rgb;
color = prepareEngineInput(color);
color = applyEngineTone(color);
$shadowsHighlightsApply
color = applyBlackWhiteLevels(color);
// Engine tone and adjustment passes have a linear-RGB output contract.
// RawSrgbPass performs the single display encoding after all