Revert "feat: local laplacian shadows and highlights tone mapping"
This reverts commit aa9d8a26e7.
This commit is contained in:
1 parent
8ef38ff7bd
commit
f2c67b2bdb
12 files changed
+255
-1527
No files matched your search
@@ -57,10 +57,6 @@ 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 uPreviewBlurLocation: Int,
|
||||
val uPreviewClarityLocation: Int,
|
||||
val uPreviewSoftLightLocation: Int,
|
||||
@@ -69,7 +65,6 @@ internal data class ColorPassLocations(
|
||||
val aPositionLocation: Int,
|
||||
val aTexCoordLocation: Int,
|
||||
val previewBlur: Boolean,
|
||||
val liteShadowsHighlights: Boolean,
|
||||
)
|
||||
|
||||
internal class PreviewColorProgramCache {
|
||||
@@ -178,10 +173,6 @@ 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"),
|
||||
uPreviewBlurLocation = GLES30.glGetUniformLocation(program, "uPreviewBlur"),
|
||||
uPreviewClarityLocation = GLES30.glGetUniformLocation(program, "uPreviewClarity"),
|
||||
uPreviewSoftLightLocation = GLES30.glGetUniformLocation(program, "uPreviewSoftLight"),
|
||||
@@ -189,8 +180,7 @@ internal class PreviewColorProgramCache {
|
||||
uPreviewRedHalationLocation = GLES30.glGetUniformLocation(program, "uPreviewRedHalation"),
|
||||
aPositionLocation = GLES30.glGetAttribLocation(program, "aPosition"),
|
||||
aTexCoordLocation = GLES30.glGetAttribLocation(program, "aTexCoord"),
|
||||
previewBlur = variant.includePreviewBlur && !variant.toneMapSource,
|
||||
liteShadowsHighlights = variant.includeLiteShadowsHighlights && !variant.toneMapSource,
|
||||
previewBlur = variant.includePreviewBlur,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -101,7 +101,6 @@ 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
|
||||
@@ -808,19 +807,6 @@ 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)
|
||||
|
||||
@@ -833,17 +819,6 @@ 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)
|
||||
@@ -879,11 +854,7 @@ 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,
|
||||
if (shadowsHighlightsApplied) highlights else 0f,
|
||||
if (shadowsHighlightsApplied) shadows else 0f,
|
||||
)
|
||||
ShadowsHighlightsShader.bindUniforms(program, highlights, shadows)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uVignette"), vignette)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uFlash"), flash)
|
||||
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uBleachBypass"), bleachBypass)
|
||||
@@ -2289,7 +2260,6 @@ 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)
|
||||
@@ -2441,10 +2411,6 @@ 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;
|
||||
@@ -2463,11 +2429,33 @@ class LutImageProcessor(context: Context? = null) {
|
||||
${PreviewColorShaderModules.SANITIZE}
|
||||
${BasicToneLutShader.GLSL}
|
||||
|
||||
vec3 shToLinear(vec3 rgb) {
|
||||
return srgbToLinear(rgb);
|
||||
vec3 prepareToneSample(vec3 sampleColor) {
|
||||
vec3 prepared = sampleColor;
|
||||
if (abs(uExposure) > 0.001) {
|
||||
prepared = applyExposureInLinearSpace(prepared, uExposure);
|
||||
}
|
||||
return sanitizeColor(prepared);
|
||||
}
|
||||
|
||||
vec3 shFromLinear(vec3 linearRgb) {
|
||||
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;
|
||||
return linearToSrgb(linearRgb);
|
||||
}
|
||||
|
||||
|
||||
@@ -69,9 +69,6 @@ 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)
|
||||
@@ -586,8 +583,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
*/
|
||||
private fun resetGlResourceState() {
|
||||
colorProgramCache.reset()
|
||||
shadowsHighlightsPreview.reset()
|
||||
shadowsHighlightsStackPreview.reset()
|
||||
previewLiteEffects.reset()
|
||||
enginePreview.reset()
|
||||
mgcEisHardwareBufferRenderer.resetAfterContextLoss()
|
||||
@@ -795,7 +790,6 @@ 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,
|
||||
@@ -805,19 +799,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
videoLogEnabled = enableVideoLog && videoLogProfile.isEnabled,
|
||||
previewLite = previewLiteEffectsEnabled,
|
||||
)
|
||||
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 (previewLiteEffectsEnabled) return null
|
||||
if (params.isDefault() || !ShadowsHighlightsShader.isActive(params.highlights, params.shadows)) return null
|
||||
return locations()
|
||||
return colorProgramCache.get(variant.copy(includeEnginePreview = includeEnginePreview))
|
||||
}
|
||||
|
||||
private fun drawColorPass(
|
||||
@@ -838,37 +820,7 @@ 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
|
||||
}
|
||||
val previewBlurTextureId = if (locations.previewBlur) {
|
||||
val oesSource = sourceTextureTarget == GLES11Ext.GL_TEXTURE_EXTERNAL_OES
|
||||
previewLiteEffects.render(
|
||||
@@ -894,7 +846,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
GLES30.glUniform1f(locations.uPreviewBloomLocation, params.bloom)
|
||||
GLES30.glUniform1f(locations.uPreviewRedHalationLocation, params.redHalation)
|
||||
}
|
||||
(shadowsHighlights ?: shadowsHighlightsPreview).bind(locations, shadowsHighlightsResult)
|
||||
colorProgramCache.bindLogInput(locations)
|
||||
enginePreview.bind(locations.uEnginePreviewLutLocation)
|
||||
|
||||
@@ -941,12 +892,11 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
GLES30.glUniform1f(locations.uTintLocation, params.tint)
|
||||
GLES30.glUniform1f(locations.uFadeLocation, params.fade)
|
||||
GLES30.glUniform1f(locations.uVibranceLocation, params.color)
|
||||
val shadowsHighlightsApplied = shadowsHighlightsResult != null || locations.liteShadowsHighlights
|
||||
ShadowsHighlightsShader.bindUniformLocations(
|
||||
highlightsLocation = locations.uHighlightsLocation,
|
||||
shadowsLocation = locations.uShadowsLocation,
|
||||
highlights = if (shadowsHighlightsApplied) params.highlights else 0f,
|
||||
shadows = if (shadowsHighlightsApplied) params.shadows else 0f,
|
||||
highlights = params.highlights,
|
||||
shadows = params.shadows,
|
||||
)
|
||||
GLES30.glUniform1f(locations.uSharpeningLocation, params.sharpness.coerceIn(-1f, 1f))
|
||||
GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain)
|
||||
@@ -1208,17 +1158,6 @@ 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
|
||||
}
|
||||
@@ -1528,18 +1467,6 @@ 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,
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
// 测光和直方图(按需)
|
||||
@@ -3271,8 +3198,6 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
|
||||
clarityDownsampleProgram = 0
|
||||
clarityCompositeProgram = 0
|
||||
releaseClarityPreviewFramebuffers()
|
||||
shadowsHighlightsPreview.release()
|
||||
shadowsHighlightsStackPreview.release()
|
||||
previewLiteEffects.release()
|
||||
filmGrainGl.release()
|
||||
highlightDiffusionGl.release()
|
||||
|
||||
@@ -131,23 +131,6 @@ internal object PreviewColorShader {
|
||||
return dot(color, W);
|
||||
}
|
||||
|
||||
${if (variant.includeShadowsHighlights && !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 ""}
|
||||
${if (variant.includeOklchDensity) PreviewColorShaderModules.OKLCH_DENSITY else PreviewColorShaderModules.OKLCH_DENSITY_STUB}
|
||||
@@ -214,13 +197,7 @@ internal object PreviewColorShader {
|
||||
}
|
||||
""")}
|
||||
|
||||
${if (variant.toneMapSource) """
|
||||
fragColor = vec4(color.rgb, 1.0);
|
||||
return;
|
||||
""" else if (variant.includeShadowsHighlights) """
|
||||
color.rgb = applyShadowsHighlights(color.rgb, vOutputCoord);
|
||||
color.rgb = sanitizeColor(color.rgb);
|
||||
""" else if (variant.includeLiteShadowsHighlights) """
|
||||
${if (variant.includeLiteShadowsHighlights) """
|
||||
color.rgb = applyPreviewShadowsHighlights(color.rgb, uvCoord);
|
||||
color.rgb = sanitizeColor(color.rgb);
|
||||
""" else ""}
|
||||
|
||||
@@ -23,13 +23,9 @@ internal data class PreviewColorShaderVariant(
|
||||
val includeEnginePreview: Boolean = false,
|
||||
val includeChromaticAberration: Boolean = false,
|
||||
val includeColorRecipe: Boolean = true,
|
||||
/**
|
||||
* Compiles the highlights / shadows tone map only while it acts: its arrays, loops and
|
||||
* samplers raise register pressure for the whole shader even when the uniform branch skips it.
|
||||
*/
|
||||
val includeShadowsHighlights: Boolean = false,
|
||||
/** Preview-only single-pass stand-ins for the multi-pass effects, see [PreviewLiteEffectsGl]. */
|
||||
/** Highlights / shadows through [PreviewLiteEffectsGl], the only preview implementation. */
|
||||
val includeLiteShadowsHighlights: Boolean = false,
|
||||
/** Preview-only single-pass stand-ins for the multi-pass effects, see [PreviewLiteEffectsGl]. */
|
||||
val includeLiteClarity: Boolean = false,
|
||||
val includeLiteSoftLight: Boolean = false,
|
||||
val includeLiteBloom: Boolean = false,
|
||||
@@ -41,11 +37,6 @@ internal data class PreviewColorShaderVariant(
|
||||
* single slider costs one step rather than the whole recipe chain.
|
||||
*/
|
||||
val recipeOps: Int = RecipeOps.ALL,
|
||||
/**
|
||||
* 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,
|
||||
) {
|
||||
val includePreviewBlur: Boolean
|
||||
get() = includeLiteShadowsHighlights || includeLiteClarity || includeLiteSoftLight ||
|
||||
@@ -62,7 +53,9 @@ internal data class PreviewColorShaderVariant(
|
||||
): PreviewColorShaderVariant {
|
||||
val lutCurve = lutConfig?.curve ?: TransferCurve.SRGB
|
||||
val recipe = !params.isDefault()
|
||||
val shadowsHighlights = recipe && ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
|
||||
val shadowsHighlights = recipe &&
|
||||
(abs(params.highlights) >= SHADOWS_HIGHLIGHTS_ACTIVE_THRESHOLD ||
|
||||
abs(params.shadows) >= SHADOWS_HIGHLIGHTS_ACTIVE_THRESHOLD)
|
||||
val preLogFilmGrain = videoLogEnabled && !lutEnabled && params.filmGrain > EPSILON
|
||||
val lite = previewLite && recipe
|
||||
return PreviewColorShaderVariant(
|
||||
@@ -78,7 +71,6 @@ internal data class PreviewColorShaderVariant(
|
||||
includeSharpening = abs(params.sharpness) > 0.0001f,
|
||||
includeChromaticAberration = params.chromaticAberration > 0.001f,
|
||||
includeColorRecipe = recipe,
|
||||
includeShadowsHighlights = shadowsHighlights && !previewLite,
|
||||
includeLiteShadowsHighlights = shadowsHighlights && previewLite,
|
||||
includeLiteClarity = lite && abs(params.clarity) > EPSILON,
|
||||
includeLiteSoftLight = lite && params.softLight > EPSILON,
|
||||
@@ -91,6 +83,9 @@ internal data class PreviewColorShaderVariant(
|
||||
|
||||
private val SIMPLE_LUT_CURVES = setOf(TransferCurve.SRGB.shaderId, TransferCurve.LINEAR.shaderId)
|
||||
private const val EPSILON = 0.001f
|
||||
|
||||
/** Matches the early-out of `applyShadowsHighlights`, which doubles the slider value first. */
|
||||
private const val SHADOWS_HIGHLIGHTS_ACTIVE_THRESHOLD = 0.0005f
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ import kotlin.math.max
|
||||
* its mip chain stands in for every blur: clarity, soft light, bloom, red halation and the local
|
||||
* adaptation of highlights / shadows sample it at fixed levels inside the colour pass. The blur
|
||||
* is taken before the recipe, so glows and detail bands live in camera colour rather than in the
|
||||
* graded output; capture and video keep the full implementations.
|
||||
* graded output; capture keeps the full implementations, and for highlights / shadows this is the
|
||||
* only implementation.
|
||||
*/
|
||||
internal class PreviewLiteEffectsGl(private val tag: String) {
|
||||
private var oesProgram = 0
|
||||
@@ -188,8 +189,8 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
|
||||
uniform float uPreviewBloom;
|
||||
uniform float uPreviewRedHalation;
|
||||
|
||||
// Global-plus-local tone curve standing in for the local Laplacian tone map: the coarse
|
||||
// blur supplies the adaptation level, highlights / shadows act as gains on linear RGB.
|
||||
// Global-plus-local tone curve: the coarse blur supplies the adaptation level, highlights /
|
||||
// shadows act as gains on linear RGB.
|
||||
vec3 applyPreviewShadowsHighlights(vec3 color, vec2 uv) {
|
||||
float fill = clamp(uShadows, -1.0, 1.0);
|
||||
float highlight = clamp(uHighlights, -1.0, 1.0);
|
||||
|
||||
@@ -107,14 +107,6 @@ 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) {
|
||||
@@ -290,7 +282,6 @@ class RealtimeVideoRenderer(
|
||||
mvpMatrix = firstPassMvpMatrix,
|
||||
enableVideoLog = videoLogProfile.isEnabled,
|
||||
presentationTimeNs = timestampNs,
|
||||
shadowsHighlights = shadowsHighlightsSlot(0),
|
||||
)
|
||||
|
||||
if (layers.size > 1) {
|
||||
@@ -311,7 +302,6 @@ class RealtimeVideoRenderer(
|
||||
mvpMatrix = identityMatrix,
|
||||
enableVideoLog = false,
|
||||
presentationTimeNs = timestampNs,
|
||||
shadowsHighlights = shadowsHighlightsSlot(index + 1),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -449,10 +439,6 @@ 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(
|
||||
@@ -462,42 +448,15 @@ class RealtimeVideoRenderer(
|
||||
lutEnabled = lutEnabled,
|
||||
videoLogEnabled = enableVideoLog,
|
||||
)
|
||||
val locations = colorProgramCache.get(variant.copy(toneMapSource = toneMapSource))
|
||||
val locations = colorProgramCache.get(variant)
|
||||
?: 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, width, height)
|
||||
GLES30.glViewport(0, 0, encoderOutputSize.width, encoderOutputSize.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)
|
||||
@@ -552,7 +511,6 @@ class RealtimeVideoRenderer(
|
||||
locations = locations,
|
||||
params = layer.params,
|
||||
presentationTimeNs = presentationTimeNs,
|
||||
shadowsHighlightsActive = shadowsHighlightsResult != null,
|
||||
)
|
||||
|
||||
val curveEnabled = layer.curveTextureId != 0
|
||||
@@ -574,8 +532,8 @@ class RealtimeVideoRenderer(
|
||||
|
||||
GLES30.glUniform2f(
|
||||
locations.uTexelSizeLocation,
|
||||
1f / max(1, width).toFloat(),
|
||||
1f / max(1, height).toFloat(),
|
||||
1f / max(1, encoderOutputSize.width).toFloat(),
|
||||
1f / max(1, encoderOutputSize.height).toFloat(),
|
||||
)
|
||||
|
||||
val positions = vertexBuffer ?: return
|
||||
@@ -609,7 +567,6 @@ class RealtimeVideoRenderer(
|
||||
locations: ColorPassLocations,
|
||||
params: ColorRecipeParams,
|
||||
presentationTimeNs: Long,
|
||||
shadowsHighlightsActive: Boolean,
|
||||
) {
|
||||
val enabled = !params.isDefault()
|
||||
GLES30.glUniform1i(locations.uColorRecipeEnabledLocation, if (enabled) 1 else 0)
|
||||
@@ -630,12 +587,6 @@ class RealtimeVideoRenderer(
|
||||
GLES30.glUniform1f(locations.uTintLocation, params.tint)
|
||||
GLES30.glUniform1f(locations.uFadeLocation, params.fade)
|
||||
GLES30.glUniform1f(locations.uVibranceLocation, params.color)
|
||||
ShadowsHighlightsShader.bindUniformLocations(
|
||||
highlightsLocation = locations.uHighlightsLocation,
|
||||
shadowsLocation = locations.uShadowsLocation,
|
||||
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)
|
||||
GLES30.glUniform1f(
|
||||
@@ -1023,8 +974,6 @@ class RealtimeVideoRenderer(
|
||||
mgcEisHardwareBufferRenderer.release()
|
||||
mgcEisYuvRenderer.release()
|
||||
colorProgramCache.release()
|
||||
shadowsHighlightsSlots.forEach { it.release() }
|
||||
shadowsHighlightsSlots.clear()
|
||||
basicToneTextures.release()
|
||||
|
||||
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
|
||||
|
||||
@@ -1,800 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
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,16 +2,6 @@ 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(
|
||||
@@ -32,363 +22,176 @@ object ShadowsHighlightsShader {
|
||||
GLES30.glUniform1f(shadowsLocation, shadows)
|
||||
}
|
||||
|
||||
/** 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
|
||||
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;
|
||||
|
||||
/** 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));
|
||||
float shSanitizeFloat(float value) {
|
||||
if (value != value) return 0.0;
|
||||
return value;
|
||||
}
|
||||
|
||||
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;
|
||||
vec3 shSanitizeColor(vec3 color) {
|
||||
return vec3(
|
||||
shSanitizeFloat(color.r),
|
||||
shSanitizeFloat(color.g),
|
||||
shSanitizeFloat(color.b)
|
||||
);
|
||||
}
|
||||
|
||||
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 shSign(float value) {
|
||||
return value < 0.0 ? -1.0 : 1.0;
|
||||
}
|
||||
|
||||
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 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;
|
||||
}
|
||||
|
||||
// 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));
|
||||
float shColorCorrection(float adjustment, float signSource) {
|
||||
return (clamp(adjustment, 0.0, 1.0) - 0.5) * shSign(signSource) + 0.5;
|
||||
}
|
||||
|
||||
vec3 shRenderProPhoto(sampler2D curve, vec3 scene) {
|
||||
return vec3(shCurve(curve, scene.r, 1), shCurve(curve, scene.g, 1), shCurve(curve, scene.b, 1));
|
||||
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));
|
||||
}
|
||||
|
||||
float shLinearToLog2(float y) {
|
||||
float flare = $FLARE_GLSL;
|
||||
return y >= 0.0 ? log2(flare + y) : 2.0 * log2(flare) - log2(flare - y);
|
||||
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 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 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 shSrgbDecode(float v) {
|
||||
return v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4);
|
||||
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 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()
|
||||
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
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);
|
||||
vec3 shRgbToLabScaled(vec3 color) {
|
||||
vec3 lab = shXyzToLab(shRgbToXyz(color));
|
||||
return lab / vec3(100.0, 128.0, 128.0);
|
||||
}
|
||||
|
||||
// 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;
|
||||
vec3 shLabScaledToRgb(vec3 labScaled) {
|
||||
vec3 lab = labScaled * vec3(100.0, 128.0, 128.0);
|
||||
return shXyzToRgb(shLabToXyz(lab));
|
||||
}
|
||||
|
||||
// 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);
|
||||
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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
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;
|
||||
}
|
||||
|
||||
// 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);
|
||||
vec2 shPixelOffset(float x, float y) {
|
||||
return vec2(x * uTexelSize.x, y * uTexelSize.y);
|
||||
}
|
||||
|
||||
// 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
|
||||
void shAddBaseSamplePair(
|
||||
vec2 uv,
|
||||
vec2 offset,
|
||||
float centerL,
|
||||
float spatialWeight,
|
||||
inout float sum,
|
||||
inout float weightSum
|
||||
) {
|
||||
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));
|
||||
}
|
||||
shAddBaseSample(uv + offset, centerL, spatialWeight, sum, weightSum);
|
||||
shAddBaseSample(uv - offset, centerL, spatialWeight, sum, weightSum);
|
||||
}
|
||||
|
||||
// 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;
|
||||
float shSampleBaseL(vec2 uv, vec3 centerLab) {
|
||||
float centerL = centerLab.x;
|
||||
float sum = centerL * 0.48;
|
||||
float weightSum = 0.48;
|
||||
|
||||
vec2 shAmountDomain(vec4 statsIn) {
|
||||
return vec2(statsIn.x - 1.0, max(statsIn.y, 0.0) + 1.0);
|
||||
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);
|
||||
}
|
||||
""".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;
|
||||
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 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));
|
||||
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);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
vec3 applyShadowsHighlights(vec3 inputColor, vec2 uv) {
|
||||
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) {
|
||||
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) {
|
||||
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);
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
// 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 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);
|
||||
|
||||
// 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);
|
||||
}
|
||||
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);
|
||||
|
||||
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));
|
||||
return shSanitizeColor(shLabScaledToRgb(lab));
|
||||
}
|
||||
""".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,7 +28,6 @@ internal class RawAdjustmentPass(
|
||||
)
|
||||
|
||||
private var program = 0
|
||||
private val shadowsHighlightsMask = ShadowsHighlightsMaskGl(TAG)
|
||||
private var loggedUniformLocations = false
|
||||
|
||||
fun render(input: Input): Output? {
|
||||
@@ -45,22 +44,6 @@ 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)
|
||||
@@ -71,16 +54,10 @@ internal class RawAdjustmentPass(
|
||||
GLES30.glGetUniformLocation(activeProgram, "uInputTexture"),
|
||||
0,
|
||||
)
|
||||
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"),
|
||||
GLES30.glUniform2f(
|
||||
GLES30.glGetUniformLocation(activeProgram, "uTexelSize"),
|
||||
1f / max(1, input.width),
|
||||
1f / max(1, input.height),
|
||||
)
|
||||
|
||||
val highlightsLocation = GLES30.glGetUniformLocation(activeProgram, "uHighlights")
|
||||
@@ -114,7 +91,6 @@ internal class RawAdjustmentPass(
|
||||
}
|
||||
|
||||
fun release() {
|
||||
shadowsHighlightsMask.release()
|
||||
if (program != 0) {
|
||||
GLES30.glDeleteProgram(program)
|
||||
program = 0
|
||||
@@ -140,21 +116,30 @@ internal class RawAdjustmentPass(
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform highp sampler2D uShadowsHighlightsMask;
|
||||
uniform highp sampler2D uShadowsHighlightsStats;
|
||||
uniform highp sampler2D uShadowsHighlightsCurve;
|
||||
uniform highp sampler2D uShadowsHighlightsAmounts;
|
||||
uniform vec2 uTexelSize;
|
||||
uniform float uHighlights;
|
||||
uniform float uShadows;
|
||||
uniform float uBlacks;
|
||||
uniform float uWhites;
|
||||
|
||||
vec3 shToLinear(vec3 rgb) {
|
||||
return rgb;
|
||||
vec3 sampleToneSource(vec2 uv) {
|
||||
return texture(uInputTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb;
|
||||
}
|
||||
|
||||
vec3 shFromLinear(vec3 linearRgb) {
|
||||
return linearRgb;
|
||||
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}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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(
|
||||
@@ -158,7 +159,7 @@ internal class RawEngineTonePass(
|
||||
}
|
||||
|
||||
internal fun fragmentShader(shaderDefinition: RawEngineToneShaderDefinition): String {
|
||||
val source = combinedFragmentShader(shaderDefinition)
|
||||
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
|
||||
val cutoff = source.indexOf("const vec3 BW_LUMA")
|
||||
.takeIf { it >= 0 }
|
||||
?: source.indexOf("void main()").takeIf { it >= 0 }
|
||||
@@ -182,7 +183,7 @@ internal class RawEngineTonePass(
|
||||
internal fun hdrReferenceFragmentShader(
|
||||
shaderDefinition: RawEngineToneShaderDefinition,
|
||||
): String {
|
||||
val source = combinedFragmentShader(shaderDefinition)
|
||||
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
|
||||
val cutoff = source.indexOf("const vec3 BW_LUMA")
|
||||
.takeIf { it >= 0 }
|
||||
?: source.indexOf("void main()").takeIf { it >= 0 }
|
||||
@@ -305,7 +306,7 @@ internal class RawEngineTonePass(
|
||||
shaderDefinition: RawEngineToneShaderDefinition,
|
||||
isHncs: Boolean,
|
||||
): String {
|
||||
val source = combinedFragmentShader(shaderDefinition)
|
||||
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
|
||||
val cutoff = source.indexOf("const vec3 BW_LUMA")
|
||||
.takeIf { it >= 0 }
|
||||
?: source.indexOf("void main()").takeIf { it >= 0 }
|
||||
@@ -338,6 +339,16 @@ 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 {
|
||||
@@ -357,7 +368,50 @@ 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) {
|
||||
@@ -402,6 +456,7 @@ internal class RawEngineTonePass(
|
||||
uniform sampler2D uInputTexture;
|
||||
uniform float uBlacks;
|
||||
uniform float uWhites;
|
||||
$shadowsHighlightsUniforms
|
||||
uniform mat3 uProfileToEngineTransform;
|
||||
|
||||
${shaderDefinition.engineUniforms}
|
||||
@@ -424,6 +479,8 @@ internal class RawEngineTonePass(
|
||||
|
||||
$prepareEngineInputFunction
|
||||
|
||||
$shadowsHighlightsFunctions
|
||||
|
||||
const vec3 BW_LUMA = vec3(0.2126, 0.7152, 0.0722);
|
||||
const float BW_EPSILON = 0.000001;
|
||||
|
||||
@@ -464,6 +521,7 @@ 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
|
||||
|
||||
Reference in new issue
Block a user