feat: new local Laplacian highlights and shadows

This commit is contained in:
zhoubinjia committed 2026-11-04 11:40:03 +08:00
1 parent f2c67b2bdb
commit e5a2c1826f
12 files changed
+730 -330

No files matched your search

@@ -30,6 +30,7 @@ internal data class ColorPassLocations(
val uVibranceLocation: Int,
val uHighlightsLocation: Int,
val uShadowsLocation: Int,
val uToneBaseOnlyLocation: Int,
val uSharpeningLocation: Int,
val uFilmGrainLocation: Int,
val uFilmGrainSeedLocation: Int,
@@ -143,6 +144,7 @@ internal class PreviewColorProgramCache {
uVibranceLocation = GLES30.glGetUniformLocation(program, "uVibrance"),
uHighlightsLocation = GLES30.glGetUniformLocation(program, "uHighlights"),
uShadowsLocation = GLES30.glGetUniformLocation(program, "uShadows"),
uToneBaseOnlyLocation = GLES30.glGetUniformLocation(program, "uToneBaseOnly"),
uSharpeningLocation = GLES30.glGetUniformLocation(program, "uSharpening"),
uFilmGrainLocation = GLES30.glGetUniformLocation(program, "uFilmGrain"),
uFilmGrainSeedLocation = GLES30.glGetUniformLocation(program, "uFilmGrainSeed"),
@@ -101,6 +101,7 @@ class LutImageProcessor(context: Context? = null) {
private var lutSharpenHeight = 0
private val filmGrainGl = FilmGrainGl(TAG)
private val highlightDiffusionGl = HighlightDiffusionGl(TAG)
private val toneBase = ToneBaseGl(TAG)
// HDF (Highlight Diffusion) 光晕效果资源
private var hdfExtractBlurHProgram = 0
@@ -780,6 +781,7 @@ class LutImageProcessor(context: Context? = null) {
colorRecipeParams: ColorRecipeParams?,
sharpening: Float,
lutMaskType: Int,
toneBaseOnly: Boolean = false,
): Bitmap {
val colorRecipeEnabled = colorRecipeParams != null && !colorRecipeParams.isDefault()
val exposure = colorRecipeParams?.exposure ?: 0f
@@ -807,12 +809,37 @@ class LutImageProcessor(context: Context? = null) {
val lchAdjustments = ColorRecipeGl.lchAdjustments(colorRecipeParams)
val primaryCalibrationMatrix = CameraRawCalibrationMatrix.build(colorRecipeParams)
val program = shaderProgram
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glViewport(0, 0, width, height)
// 绘制
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
val shadowsHighlightsActive = ShadowsHighlightsShader.isActive(highlights, shadows)
if (!toneBaseOnly && shadowsHighlightsActive &&
toneBase.prepare(width, height) && toneBase.bindLevel0()
) {
performRender(
width = width,
height = height,
inputTextureId = inputTextureId,
inputColorSpace = inputColorSpace,
lutConfig = lutConfig,
colorRecipeParams = colorRecipeParams,
sharpening = sharpening,
lutMaskType = lutMaskType,
toneBaseOnly = true,
)
toneBase.buildLevels(::drawQuad)
}
if (!toneBaseOnly) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glViewport(0, 0, width, height)
// 绘制
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
}
GLES30.glUseProgram(program)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(program, "uToneBaseOnly"),
if (toneBaseOnly) 1 else 0,
)
if (shadowsHighlightsActive && !toneBaseOnly) {
toneBase.bind(program)
}
logInput.bind(GLES30.glGetUniformLocation(program, "uInverseAcr3Texture"), textureUnit = 7)
// 设置纹理 uniform
@@ -974,6 +1001,12 @@ class LutImageProcessor(context: Context? = null) {
if (positionHandle >= 0) GLES30.glDisableVertexAttribArray(positionHandle)
if (texCoordHandle >= 0) GLES30.glDisableVertexAttribArray(texCoordHandle)
if (toneBaseOnly) {
// Recursive call from the tone-base prepass: the base pyramid already holds the
// pre-adjustment log luminance, so post-processing and readback are not run.
return Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
}
val clarityApplied = kotlin.math.abs(clarity) > 0.001f &&
renderClarity(outputTextureId, width, height, clarity)
val postClarityTextureId = if (clarityApplied) clarityOutputTextureId else outputTextureId
@@ -2261,6 +2294,7 @@ class LutImageProcessor(context: Context? = null) {
releaseClarityFramebuffers()
filmGrainGl.release()
highlightDiffusionGl.release()
toneBase.release()
for (i in 0..1) {
if (hdfTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(hdfTexId[i]), 0)
if (hdfFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(hdfFboId[i]), 0)
@@ -2383,6 +2417,7 @@ class LutImageProcessor(context: Context? = null) {
uniform float uVibrance; // 0.0 ~ 2.0 (蓝色增强)
uniform float uHighlights; // -1.0 ~ +1.0 (高光调整)
uniform float uShadows; // -1.0 ~ +1.0 (阴影调整)
uniform int uToneBaseOnly;
uniform float uVignette; // -1.0 ~ +1.0 (晕影)
uniform float uFlash; // 0.0 ~ 1.0 (镜头轴向直闪模拟)
uniform float uBleachBypass; // 0.0 ~ 1.0 (留银冲洗强度)
@@ -2429,36 +2464,6 @@ class LutImageProcessor(context: Context? = null) {
${PreviewColorShaderModules.SANITIZE}
${BasicToneLutShader.GLSL}
vec3 prepareToneSample(vec3 sampleColor) {
vec3 prepared = sampleColor;
if (abs(uExposure) > 0.001) {
prepared = applyExposureInLinearSpace(prepared, uExposure);
}
return sanitizeColor(prepared);
}
vec3 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);
}
${ShadowsHighlightsShader.GLSL}
${PreviewColorShaderModules.OKLAB}
@@ -2534,8 +2539,20 @@ class LutImageProcessor(context: Context? = null) {
color.rgb = sanitizeColor(color.rgb);
}
// 2. 高光/阴影调整:RT 风格 tonal width + 局部 base mask,避免线性乘法洗白全图
color.rgb = applyShadowsHighlights(color.rgb, uvCoord);
// 2. 高光/阴影调整:Local Laplacian 三带局部色调映射
if (uToneBaseOnly != 0) {
fragColor = vec4(
shLogLuminance(srgbToLinear(max(color.rgb, 0.0))),
0.0,
0.0,
1.0
);
return;
}
color.rgb = linearToSrgb(applyShadowsHighlightsLinear(
srgbToLinear(max(color.rgb, 0.0)),
vTexCoord
));
color.rgb = sanitizeColor(color.rgb);
// 3. 对比度(固定 0.5 中点的 S 曲线)
@@ -194,6 +194,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private val filmGrainGl = FilmGrainGl(TAG)
private val highlightDiffusionGl = HighlightDiffusionGl(TAG)
private val previewLiteEffects = PreviewLiteEffectsGl(TAG)
private val toneBase = ToneBaseGl(TAG)
private var filmGrainSourceTextureId: Int = 0
private var filmGrainSourceFboId: Int = 0
private var filmGrainSourceWidth: Int = 0
@@ -584,6 +585,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
private fun resetGlResourceState() {
colorProgramCache.reset()
previewLiteEffects.reset()
toneBase.reset()
enginePreview.reset()
mgcEisHardwareBufferRenderer.resetAfterContextLoss()
mgcEisYuvRenderer.resetAfterContextLoss()
@@ -820,8 +822,36 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
curveTextureId: Int,
curveEnabled: Boolean,
enableVideoLog: Boolean,
toneBaseOnly: Boolean = false,
) {
val previewBlurTextureId = if (locations.previewBlur) {
val shadowsHighlightsActive =
ShadowsHighlightsShader.isActive(params.highlights, params.shadows)
if (!toneBaseOnly && shadowsHighlightsActive &&
toneBase.prepare(width, height) && toneBase.bindLevel0()
) {
drawColorPass(
locations = locations,
targetFboId = targetFboId,
width = width,
height = height,
sourceTextureTarget = sourceTextureTarget,
sourceTextureId = sourceTextureId,
sourceStMatrix = sourceStMatrix,
sourceCropRect = sourceCropRect,
targetMvpMatrix = targetMvpMatrix,
lutConfig = lutConfig,
lutTextureId = lutTextureId,
lutSize = lutSize,
lutEnabled = lutEnabled,
params = params,
curveTextureId = curveTextureId,
curveEnabled = curveEnabled,
enableVideoLog = enableVideoLog,
toneBaseOnly = true,
)
toneBase.buildLevels(::drawSimpleQuad)
}
val previewBlurTextureId = if (locations.previewBlur && !toneBaseOnly) {
val oesSource = sourceTextureTarget == GLES11Ext.GL_TEXTURE_EXTERNAL_OES
previewLiteEffects.render(
sourceTarget = sourceTextureTarget,
@@ -833,10 +863,13 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
} else {
0
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, width, height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
if (!toneBaseOnly) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, width, height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
}
GLES30.glUseProgram(locations.programId)
GLES30.glUniform1i(locations.uToneBaseOnlyLocation, if (toneBaseOnly) 1 else 0)
if (locations.previewBlur) {
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + PreviewLiteEffectsGl.TEXTURE_UNIT)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, previewBlurTextureId)
@@ -848,6 +881,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
}
colorProgramCache.bindLogInput(locations)
enginePreview.bind(locations.uEnginePreviewLutLocation)
if (shadowsHighlightsActive && !toneBaseOnly) {
toneBase.bind(locations.programId)
}
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(sourceTextureTarget, sourceTextureId)
@@ -3199,6 +3235,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
clarityCompositeProgram = 0
releaseClarityPreviewFramebuffers()
previewLiteEffects.release()
toneBase.release()
filmGrainGl.release()
highlightDiffusionGl.release()
releaseFilmGrainSourceFramebuffer()
@@ -54,6 +54,7 @@ internal object PreviewColorShader {
uniform float uVibrance;
uniform float uHighlights;
uniform float uShadows;
uniform int uToneBaseOnly;
${if (variant.includeSharpening) "uniform float uSharpening;" else ""}
${if (variant.includePreLogFilmGrain || variant.includeFinalFilmGrain) """
uniform float uFilmGrain;
@@ -137,6 +138,8 @@ internal object PreviewColorShader {
${if (variant.includeLchMixer) PreviewColorShaderModules.LCH_MIXER else PreviewColorShaderModules.LCH_MIXER_STUB}
${if (variant.includeLutMask) PreviewColorShaderModules.LUT_MASK else PreviewColorShaderModules.LUT_MASK_STUB}
${if (variant.includeExtendedLutCurves) PreviewColorShaderModules.EXTENDED_LUT_CURVES else PreviewColorShaderModules.SIMPLE_LUT_CURVES}
${ShadowsHighlightsShader.GLSL}
${if (variant.includePreLogFilmGrain) FilmGrainShaders.FUNCTIONS else ""}
${if (variant.includeFinalFilmGrain) PreviewLiteEffectsGl.GRAIN_GLSL else ""}
${if (variant.includePreviewBlur) PreviewLiteEffectsGl.GLSL else ""}
@@ -197,8 +200,20 @@ internal object PreviewColorShader {
}
""")}
${if (variant.includeLiteShadowsHighlights) """
color.rgb = applyPreviewShadowsHighlights(color.rgb, uvCoord);
${if (variant.includeShadowsHighlights) """
if (uToneBaseOnly != 0) {
fragColor = vec4(
shLogLuminance(srgbToLinear(max(color.rgb, 0.0))),
0.0,
0.0,
1.0
);
return;
}
color.rgb = linearToSrgb(applyShadowsHighlightsLinear(
srgbToLinear(max(color.rgb, 0.0)),
vOutputCoord
));
color.rgb = sanitizeColor(color.rgb);
""" else ""}
@@ -23,8 +23,8 @@ internal data class PreviewColorShaderVariant(
val includeEnginePreview: Boolean = false,
val includeChromaticAberration: Boolean = false,
val includeColorRecipe: Boolean = true,
/** Highlights / shadows through [PreviewLiteEffectsGl], the only preview implementation. */
val includeLiteShadowsHighlights: Boolean = false,
/** Local Laplacian highlights / shadows from [ShadowsHighlightsShader]. */
val includeShadowsHighlights: Boolean = false,
/** Preview-only single-pass stand-ins for the multi-pass effects, see [PreviewLiteEffectsGl]. */
val includeLiteClarity: Boolean = false,
val includeLiteSoftLight: Boolean = false,
@@ -39,7 +39,7 @@ internal data class PreviewColorShaderVariant(
val recipeOps: Int = RecipeOps.ALL,
) {
val includePreviewBlur: Boolean
get() = includeLiteShadowsHighlights || includeLiteClarity || includeLiteSoftLight ||
get() = includeLiteClarity || includeLiteSoftLight ||
includeLiteBloom || includeLiteRedHalation
companion object {
@@ -71,7 +71,7 @@ internal data class PreviewColorShaderVariant(
includeSharpening = abs(params.sharpness) > 0.0001f,
includeChromaticAberration = params.chromaticAberration > 0.001f,
includeColorRecipe = recipe,
includeLiteShadowsHighlights = shadowsHighlights && previewLite,
includeShadowsHighlights = shadowsHighlights,
includeLiteClarity = lite && abs(params.clarity) > EPSILON,
includeLiteSoftLight = lite && params.softLight > EPSILON,
includeLiteBloom = lite && params.bloom > EPSILON,
@@ -9,11 +9,11 @@ import kotlin.math.max
* Single-pass approximations of the multi-pass spatial effects for realtime preview.
*
* One quarter-resolution downsample of the colour pass source (rgb, highlight mask in alpha) plus
* 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 keeps the full implementations, and for highlights / shadows this is the
* only implementation.
* its mip chain stands in for every blur: clarity, soft light, bloom and red halation 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 keeps the full
* implementations. Highlights / shadows are not part of this class: they use the shared
* [ShadowsHighlightsShader] operator with the [ToneBaseGl] pyramid in every host.
*/
internal class PreviewLiteEffectsGl(private val tag: String) {
private var oesProgram = 0
@@ -179,8 +179,8 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
"""
/**
* Colour pass functions. The host declares `uHighlights`, `uShadows`, `uExposure`, `W` and the
* sRGB transfer helpers; [uvCoord] is the source coordinate the blur was rendered in.
* Colour pass functions. The host declares `uExposure`, `W` and the sRGB transfer helpers;
* [uv] is the output coordinate the blur was rendered in.
*/
const val GLSL = """
uniform sampler2D uPreviewBlur;
@@ -189,23 +189,6 @@ internal class PreviewLiteEffectsGl(private val tag: String) {
uniform float uPreviewBloom;
uniform float uPreviewRedHalation;
// 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);
if (abs(fill) < 0.0005 && abs(highlight) < 0.0005) return color;
vec3 linearColor = srgbToLinear(max(color, vec3(0.0)));
float y = dot(linearColor, W);
float local = dot(srgbToLinear(textureLod(uPreviewBlur, uv, 3.0).rgb), W) * exp2(uExposure);
float level = sqrt(clamp(mix(y, local, 0.65), 0.0, 1.0));
float shadowWeight = 1.0 - smoothstep(0.0, 0.6, level);
float highlightWeight = smoothstep(0.4, 1.0, level);
float ev = fill * 1.6 * shadowWeight * shadowWeight +
highlight * 1.2 * highlightWeight * highlightWeight;
return linearToSrgb(linearColor * exp2(ev));
}
// Detail bands from the source-domain blur, applied as a luminance ratio like the
// pyramid composite.
vec3 applyPreviewClarity(vec3 color, float sourceLuma, vec2 uv) {
@@ -81,6 +81,7 @@ class RealtimeVideoRenderer(
}
}
private val colorProgramCache = PreviewColorProgramCache()
private val toneBase = ToneBaseGl(TAG)
private val basicToneTextures = BasicToneGlTextures()
private val filmGrainGl = FilmGrainGl(TAG)
private val mgcEisHardwareBufferRenderer = MgcEisHardwareBufferRenderer(TAG)
@@ -439,6 +440,7 @@ class RealtimeVideoRenderer(
mvpMatrix: FloatArray,
enableVideoLog: Boolean,
presentationTimeNs: Long,
toneBaseOnly: Boolean = false,
) {
val lutEnabled = layer.lutConfig != null && layer.lutTextureId != 0
val variant = PreviewColorShaderVariant.forPass(
@@ -451,12 +453,40 @@ class RealtimeVideoRenderer(
val locations = colorProgramCache.get(variant)
?: throw IllegalStateException("Cannot create realtime video color shader: $variant")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
GLES30.glViewport(0, 0, encoderOutputSize.width, encoderOutputSize.height)
GLES30.glClearColor(0f, 0f, 0f, 1f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
val shadowsHighlightsActive =
ShadowsHighlightsShader.isActive(layer.params.highlights, layer.params.shadows)
if (!toneBaseOnly && shadowsHighlightsActive &&
toneBase.prepare(encoderOutputSize.width, encoderOutputSize.height) &&
toneBase.bindLevel0()
) {
drawLayer(
layer = layer,
targetFboId = targetFboId,
textureSource = textureSource,
textureTarget = textureTarget,
textureId = textureId,
sourceStMatrix = sourceStMatrix,
cropRect = cropRect,
mvpMatrix = mvpMatrix,
enableVideoLog = enableVideoLog,
presentationTimeNs = presentationTimeNs,
toneBaseOnly = true,
)
toneBase.buildLevels(::drawSimpleQuad)
}
if (!toneBaseOnly) {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId)
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)
GLES30.glUniform1i(locations.uToneBaseOnlyLocation, if (toneBaseOnly) 1 else 0)
colorProgramCache.bindLogInput(locations)
if (shadowsHighlightsActive && !toneBaseOnly) {
toneBase.bind(locations.programId)
}
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(textureTarget, textureId)
@@ -974,6 +1004,7 @@ class RealtimeVideoRenderer(
mgcEisHardwareBufferRenderer.release()
mgcEisYuvRenderer.release()
colorProgramCache.release()
toneBase.release()
basicToneTextures.release()
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
@@ -1,8 +1,43 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import kotlin.math.abs
/**
* Local Laplacian highlights / shadows.
*
* The operator works on the Laplacian decomposition of the log2 luminance instead of a tone curve
* on the pixel value:
*
* ```
* level = log2(flare + Y) // Y = luminance of the linear pixel
* base1 = neighbourhood mean at 1/8 of the output
* base2 = neighbourhood mean at 1/16
* base3 = neighbourhood mean at 1/32
* detail = level - base1 // finer than 1/8: never touched
* band1 = base1 - base2
* band2 = base2 - base3
* ```
*
* Amounts are functions of the pixel's own level; the blurred levels only shape the fill band and
* the black/fill gates. Taking an amount from a blurred field makes the gain ramp over that
* field's blur radius, so across a strong edge the adjustment steps from the subject's value to
* the neighbour's within ~1/32 of the frame: the "half pale / half grey" split along a silhouette.
* Pixel-level amounts are monotone pointwise maps, so no amount can introduce an edge, and the
* only spatial term is the dark-side fill, which is gated to pixels that are themselves dark.
*
* The luminance change is applied as a gain on linear RGB, so hue and saturation are preserved.
* [ToneBaseGl] renders and filters the three base levels; hosts only need to bind them and set
* `uToneBaseOnly` while rendering the pyramid's first level.
*/
object ShadowsHighlightsShader {
/** Texture units used by [ToneBaseGl.bind] for the three log2-luminance base levels. */
val TONE_BASE_TEXTURE_UNITS = intArrayOf(9, 10, 11)
/** True when [applyShadowsHighlightsLinear] does any work. */
fun isActive(highlights: Float, shadows: Float): Boolean =
abs(highlights) >= ACTIVE_THRESHOLD || abs(shadows) >= ACTIVE_THRESHOLD
fun bindUniforms(program: Int, highlights: Float, shadows: Float) {
bindUniformLocations(
highlightsLocation = GLES30.glGetUniformLocation(program, "uHighlights"),
@@ -22,176 +57,155 @@ object ShadowsHighlightsShader {
GLES30.glUniform1f(shadowsLocation, shadows)
}
/** Matches `isActive`. */
private const val ACTIVE_THRESHOLD = 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;
uniform sampler2D uToneBase1;
uniform sampler2D uToneBase2;
uniform sampler2D uToneBase3;
uniform sampler2D uToneStats;
float shSanitizeFloat(float value) {
if (value != value) return 0.0;
return value;
const float SH_FLARE = 1.0 / 4096.0;
const float SH_SHADOW_BAND_SIGMA_1 = 0.4;
const float SH_SHADOW_BAND_SIGMA_2 = 0.7;
const float SH_SHADOW_KNEE = -2.8;
const float SH_SHADOW_WIDTH = 1.9;
const float SH_HIGHLIGHT_KNEE = -1.6;
const float SH_HIGHLIGHT_WIDTH = 1.2;
// The knee width sets how far the lift reaches, the scale sets its maximum slope. Both
// stay below 1.0 so the composed map keeps headroom for the band terms and never inverts.
const float SH_SHADOW_SCALE = 0.9;
const float SH_HIGHLIGHT_SCALE = 0.95;
const float SH_BLACK_LEVEL = -8.0;
const float SH_BLACK_FADE = 2.0;
// Band fill only runs where the pixel itself is dark; a coarse mean cannot separate a
// dark subject from a bright neighbour, and letting the fill follow it draws a halo.
const float SH_FILL_GATE_LOW = -6.0;
const float SH_FILL_GATE_HIGH = -3.5;
// The thresholds above are tuned for a frame whose /16-base maximum (a robust p99.99)
// sits here. [ToneBaseGl]'s statistics shift them down for darker frames, so a low-key
// image still has a working highlight range; the black point comes from the frame's own
// dark end instead of a fixed -8.
const float SH_REFERENCE_HIGH = -0.42;
const float SH_BLACK_FLOOR = -4.0;
const float SH_MIN_GAIN = 0.0625;
const float SH_MAX_GAIN = 16.0;
float shLuminance(vec3 linearColor) {
return dot(max(linearColor, vec3(0.0)), vec3(0.2126, 0.7152, 0.0722));
}
vec3 shSanitizeColor(vec3 color) {
return vec3(
shSanitizeFloat(color.r),
shSanitizeFloat(color.g),
shSanitizeFloat(color.b)
float shLogLuminance(vec3 linearColor) {
return log2(SH_FLARE + shLuminance(linearColor));
}
float shKnee(float distance, float width) {
return width * (1.0 - exp(-max(distance, 0.0) / width));
}
// Local Laplacian band remap for the fill side: only deviations darker than the coarser
// level are filled, and the excess over sigma follows the slider. The rational form is
// smooth at sigma (no threshold contour) and its slope stays inside [0, |amount|], so the
// composed map can never invert. Highlights deliberately have no band term: compressing
// the /8../32 structure of a lit subject flattens skin shading into visible patches
// ("dirty" colour), while a gain on the smooth local base keeps the shading intact.
float shShadowBand(float band, float amount, float sigma) {
float magnitude = max(-band, 0.0);
return amount * magnitude * magnitude / (magnitude + sigma);
}
// 4-tap joint-bilateral upsample of a base level, guided by the pixel's own log
// luminance. A plain bilinear fetch mixes both sides of a strong edge, so the base - and
// every band derived from it - carries the neighbour's value for the width of the coarse
// texel. The range weight keeps only the texels on the pixel's own side. Range 0.5 stop
// and the +0.001 floor follow the reference mask implementation.
const float SH_UPSAMPLE_RANGE = 0.5;
float shSampleBase(sampler2D base, vec2 uv, float level) {
ivec2 size = textureSize(base, 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);
vec4 b = vec4(
texelFetch(base, i0, 0).r,
texelFetch(base, ivec2(i1.x, i0.y), 0).r,
texelFetch(base, ivec2(i0.x, i1.y), 0).r,
texelFetch(base, i1, 0).r
);
vec4 d = (b - level) / 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 * d * d) + 0.001);
return dot(weight, b) / dot(weight, vec4(1.0));
}
float shSign(float value) {
return value < 0.0 ? -1.0 : 1.0;
}
float shSignedInv(float value, float signSource) {
float inv = abs(value) > SH_LOW_APPROX ? 1.0 / abs(value) : 1.0 / SH_LOW_APPROX;
return signSource < 0.0 ? -inv : inv;
}
float shColorCorrection(float adjustment, float signSource) {
return (clamp(adjustment, 0.0, 1.0) - 0.5) * shSign(signSource) + 0.5;
}
vec3 shLabF(vec3 value) {
vec3 linearPart = (SH_LAB_KAPPA * value + vec3(16.0)) / 116.0;
vec3 cubePart = pow(max(value, vec3(0.0)), vec3(1.0 / 3.0));
return mix(linearPart, cubePart, step(vec3(SH_LAB_EPSILON), value));
}
vec3 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));
}
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));
}
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);
}
vec3 shRgbToLabScaled(vec3 color) {
vec3 lab = shXyzToLab(shRgbToXyz(color));
return lab / vec3(100.0, 128.0, 128.0);
}
vec3 shLabScaledToRgb(vec3 labScaled) {
vec3 lab = labScaled * vec3(100.0, 128.0, 128.0);
return shXyzToRgb(shLabToXyz(lab));
}
float shTonalRangeWeight(float sampleL, float centerL) {
float delta = sampleL - centerL;
float bilateral = exp(-(delta * delta) / max(2.0 * SH_RANGE_SIGMA2, SH_LOW_APPROX));
float edgeStop = 1.0 - smoothstep(0.12, 0.24, abs(delta));
return bilateral * edgeStop;
}
void shAddBaseSample(vec2 uv, float centerL, float spatialWeight, inout float sum, inout float weightSum) {
float sampleL = shRgbToLabScaled(sampleToneSource(clamp(uv, vec2(0.0), vec2(1.0)))).x;
float weight = spatialWeight * shTonalRangeWeight(sampleL, centerL);
sum += sampleL * weight;
weightSum += weight;
}
vec2 shPixelOffset(float x, float y) {
return vec2(x * uTexelSize.x, y * uTexelSize.y);
}
void shAddBaseSamplePair(
vec2 uv,
vec2 offset,
float centerL,
float spatialWeight,
inout float sum,
inout float weightSum
) {
shAddBaseSample(uv + offset, centerL, spatialWeight, sum, weightSum);
shAddBaseSample(uv - offset, centerL, spatialWeight, sum, weightSum);
}
float shSampleBaseL(vec2 uv, vec3 centerLab) {
float centerL = centerLab.x;
float sum = centerL * 0.48;
float weightSum = 0.48;
shAddBaseSamplePair(uv, shPixelOffset(2.5, 1.5), centerL, 0.11, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-1.5, 3.5), centerL, 0.11, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(4.5, -2.5), centerL, 0.10, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-4.5, -3.5), centerL, 0.10, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(7.5, 4.5), centerL, 0.065, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-6.5, 8.5), centerL, 0.06, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(10.5, -7.5), centerL, 0.055, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(15.5, 11.5), centerL, 0.035, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(-18.5, 5.5), centerL, 0.03, sum, weightSum);
shAddBaseSamplePair(uv, shPixelOffset(22.5, -13.5), centerL, 0.026, sum, weightSum);
return sum / max(weightSum, 0.0001);
}
vec3 shOverlay(vec3 a, vec3 b, float opacity, float transform, float ccorrect) {
float remainingOpacity = min(opacity * opacity, 4.0);
float tonalWeight = clamp(transform, 0.0, 1.0);
// Split strong adjustments into convex blends instead of extrapolating past
// the overlay result. The local base is a mask, not a luminance bound:
// clipping to it creates a jump whenever the base crosses the source L.
for (int i = 0; i < 4; i++) {
float optrans = min(remainingOpacity, 1.0) * tonalWeight;
if (optrans <= 0.0) break;
remainingOpacity = max(remainingOpacity - 1.0, 0.0);
float la = a.x;
float lb = (b.x - 0.5) * shSign(opacity) * shSign(1.0 - la) + 0.5;
lb = clamp(lb, 0.0, 1.0);
float lref = shSignedInv(la, la);
float href = shSignedInv(1.0 - la, 1.0 - la);
float overL = la > 0.5
? 1.0 - (1.0 - 2.0 * (la - 0.5)) * (1.0 - lb)
: 2.0 * la * lb;
a.x = mix(la, overL, optrans);
float chromaFactor = a.x * lref * ccorrect + (1.0 - a.x) * href * (1.0 - ccorrect);
a.y = mix(a.y, (a.y + b.y) * chromaFactor, optrans);
a.z = mix(a.z, (a.z + b.z) * chromaFactor, optrans);
}
return a;
}
vec3 applyShadowsHighlights(vec3 inputColor, vec2 uv) {
float highlights = 2.0 * clamp(uHighlights, -1.0, 1.0);
float shadows = 2.0 * clamp(uShadows, -1.0, 1.0);
if (abs(highlights) < 0.001 && abs(shadows) < 0.001) {
return inputColor;
/**
* Adjusts [linearColor]. [uv] is the output-space coordinate of the pixel, which is the
* parameterisation of the [ToneBaseGl] pyramid.
*/
vec3 applyShadowsHighlightsLinear(vec3 linearColor, vec2 uv) {
float highlights = clamp(uHighlights, -1.0, 1.0);
float shadows = clamp(uShadows, -1.0, 1.0);
if (abs(highlights) < 0.0005 && abs(shadows) < 0.0005) {
return linearColor;
}
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);
float luminance = shLuminance(linearColor);
float level = log2(SH_FLARE + luminance);
float base1 = shSampleBase(uToneBase1, uv, level);
float base2 = shSampleBase(uToneBase2, uv, level);
float base3 = shSampleBase(uToneBase3, uv, level);
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);
// Image-relative calibration: a 1x1 reduction of the /16 base gives the log-luminance
// low, high and mean. Everything below is then placed relative to that mean instead of
// at fixed stops, and the black point starts at the image's own dark end.
vec3 stats = texelFetch(uToneStats, ivec2(0), 0).rgb;
bool statsValid = stats.y > stats.x && stats.y > -11.0;
// Only darker-than-reference frames shift the knees; a brighter frame keeps the
// tuned positions so ordinary images render exactly as before.
float shift = statsValid ? min(stats.y - SH_REFERENCE_HIGH, 0.0) : 0.0;
float highlightKnee = SH_HIGHLIGHT_KNEE + shift;
float shadowKnee = SH_SHADOW_KNEE + shift;
float blackLevel = statsValid
? clamp(stats.x, SH_BLACK_LEVEL, SH_BLACK_FLOOR)
: SH_BLACK_LEVEL;
float fillLow = SH_FILL_GATE_LOW + shift;
float fillHigh = SH_FILL_GATE_HIGH + shift;
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);
// Every amount below is a function of the pixel's own level only. A blurred field
// cannot be used for an amount: it ramps over its own blur radius, so across a strong
// edge the gain steps from the subject's value to the neighbour's over ~1/32 of the
// frame, which is exactly the "half pale, half grey" split along a silhouette. The
// measured halo of a /32 base at a 3.5 stop step edge is +47% of the adjustment; with
// pixel-level amounts it is 0 by construction.
//
// Black protection: the fill fades out where the pixel is near black, so shadow lift
// cannot raise the black level. Darkening shadows is not gated: it can only lower the
// black level, and gating it would invert the slope where the gate rises faster than
// the band.
float blackGate = smoothstep(blackLevel, blackLevel + SH_BLACK_FADE, level);
float shadowGate = shadows > 0.0 ? blackGate : 1.0;
float fillGate = smoothstep(fillLow, fillHigh, level);
return shSanitizeColor(shLabScaledToRgb(lab));
float local = shShadowBand(base1 - base2, shadows * fillGate, SH_SHADOW_BAND_SIGMA_1)
+ shShadowBand(base2 - base3, shadows * fillGate, SH_SHADOW_BAND_SIGMA_2);
float tonal =
SH_HIGHLIGHT_SCALE * highlights * shKnee(level - highlightKnee, SH_HIGHLIGHT_WIDTH)
+ SH_SHADOW_SCALE * shadows * shadowGate * shKnee(shadowKnee - level, SH_SHADOW_WIDTH);
if (luminance <= 0.0) {
return linearColor;
}
float adjusted = exp2(level + tonal + local) - SH_FLARE;
float gain = clamp(adjusted / luminance, SH_MIN_GAIN, SH_MAX_GAIN);
return linearColor * gain;
}
""".trimIndent()
}
@@ -0,0 +1,359 @@
package com.hinnka.mycamera.lut
import android.opengl.GLES30
import com.hinnka.mycamera.utils.PLog
import kotlin.math.max
/**
* Log2-luminance pyramid for [ShadowsHighlightsShader].
*
* Level 0 is rendered by the host's colour pass in `uToneBaseOnly` mode and holds
* `log2(flare + Y)` at 1/4 of the output, so the base is exposure- and pipeline-consistent with
* the pixels it will adjust. Levels 1 and 2 are 1/8 and 1/16 of the output and are produced here
* by 2x2 box reductions. There is deliberately no 1/32 level: a 2x2 joint-bilateral upsample can
* recover the base across an edge while each coarse texel still has a same-side neighbour, which
* holds up to 1/16 but not at 1/32 (measured on a 3.5 stop step edge).
*
* The three low levels are separate textures rather than one mip chain: rendering level `i` while
* sampling level `i - 1` never samples the texture bound to the draw framebuffer, which would be a
* feedback loop on some drivers.
*/
internal class ToneBaseGl(private val tag: String) {
private class Level {
var texture = 0
var framebuffer = 0
var width = 0
var height = 0
}
private val levels = Array(LEVEL_COUNT) { Level() }
private var program = 0
private var programFailed = false
private var statsProgram = 0
private var statsFailed = false
private var statsTexture = 0
private var statsFramebuffer = 0
private val uniformLocations = mutableMapOf<Int, Int>()
/** Size of level 0. Returns false when the target cannot be allocated. */
fun prepare(width: Int, height: Int): Boolean {
val levelWidth = max(1, width / BASE_DIVISOR)
val levelHeight = max(1, height / BASE_DIVISOR)
if (levels[0].texture != 0 &&
levels[0].width == levelWidth &&
levels[0].height == levelHeight
) {
return true
}
release()
for (index in 0 until LEVEL_COUNT) {
val targetWidth = max(1, levelWidth shr index)
val targetHeight = max(1, levelHeight shr index)
if (!createLevel(levels[index], targetWidth, targetHeight)) {
release()
return false
}
}
return true
}
/** Binds the level-0 framebuffer and returns false when the pyramid is not allocated. */
fun bindLevel0(): Boolean {
val level = levels[0]
if (level.texture == 0 || level.framebuffer == 0) return false
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, level.framebuffer)
GLES30.glViewport(0, 0, level.width, level.height)
return true
}
/** Reduces level 0 into the three base levels. Draws with [drawQuad]'s fullscreen geometry. */
fun buildLevels(drawQuad: (Int) -> Unit) {
val activeProgram = ensureProgram() ?: return
for (index in 1 until LEVEL_COUNT) {
val source = levels[index - 1]
val target = levels[index]
if (source.texture == 0 || target.framebuffer == 0) continue
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer)
GLES30.glViewport(0, 0, target.width, target.height)
GLES30.glUseProgram(activeProgram)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, source.texture)
GLES30.glUniform1i(location(activeProgram, "uToneBaseSource"), 0)
GLES30.glUniform2f(
location(activeProgram, "uToneBaseSourceTexel"),
1f / source.width.toFloat(),
1f / source.height.toFloat()
)
drawQuad(activeProgram)
}
renderStats(drawQuad)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glUseProgram(0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
}
/** Binds the 1x1 statistics texture as `uToneStats` (unit 12). */
private fun bindStats(program: Int) {
if (statsTexture == 0) return
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + STATS_TEXTURE_UNIT)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, statsTexture)
GLES30.glUniform1i(location(program, "uToneStats"), STATS_TEXTURE_UNIT)
}
/** Binds levels 0..2 as `uToneBase1..3` on the units declared by the shader object. */
fun bind(program: Int) {
val units = ShadowsHighlightsShader.TONE_BASE_TEXTURE_UNITS
for (index in 0 until LEVEL_COUNT) {
val level = levels[index]
val unit = units[index]
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, level.texture)
GLES30.glUniform1i(location(program, "uToneBase${index + 1}"), unit)
}
bindStats(program)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
}
fun release() {
for (level in levels) {
if (level.texture != 0) GLES30.glDeleteTextures(1, intArrayOf(level.texture), 0)
if (level.framebuffer != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(level.framebuffer), 0)
}
level.texture = 0
level.framebuffer = 0
level.width = 0
level.height = 0
}
releaseStatsTarget()
if (program != 0) {
GLES30.glDeleteProgram(program)
program = 0
}
if (statsProgram != 0) {
GLES30.glDeleteProgram(statsProgram)
statsProgram = 0
}
uniformLocations.clear()
programFailed = false
}
/** Drops GL objects that belong to a destroyed context. */
fun reset() {
for (level in levels) {
level.texture = 0
level.framebuffer = 0
level.width = 0
level.height = 0
}
program = 0
statsProgram = 0
statsTexture = 0
statsFramebuffer = 0
uniformLocations.clear()
programFailed = false
statsFailed = false
}
private fun location(program: Int, name: String): Int {
uniformLocations[name.hashCode() * 31 + program]?.let { return it }
val location = GLES30.glGetUniformLocation(program, name)
uniformLocations[name.hashCode() * 31 + program] = location
return location
}
/**
* Reduces level 2 into a 1x1 (low, high, mean) texture of the log2 luminance distribution.
* The shader uses it to place its thresholds relative to the image instead of absolute
* stops, so a low-key frame still gets a working highlight range and a dark frame keeps its
* black point. 32x32 evenly spaced bilinear taps are enough: the source is a /16 base.
*/
private fun renderStats(drawQuad: (Int) -> Unit) {
if (!ensureStatsTarget()) return
val activeProgram = ensureStatsProgram() ?: return
if (levels[LEVEL_COUNT - 1].texture == 0) return
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, statsFramebuffer)
GLES30.glViewport(0, 0, 1, 1)
GLES30.glUseProgram(activeProgram)
GLES30.glDisable(GLES30.GL_BLEND)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, levels[LEVEL_COUNT - 1].texture)
GLES30.glUniform1i(location(activeProgram, "uToneStatsSource"), 0)
drawQuad(activeProgram)
}
private fun ensureStatsTarget(): Boolean {
if (statsTexture != 0 && statsFramebuffer != 0) return true
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
statsTexture = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, statsTexture)
GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, 1, 1)
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)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
statsFramebuffer = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, statsFramebuffer)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
statsTexture,
0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (!complete) {
PLog.e(tag, "Tone base stats target is incomplete")
releaseStatsTarget()
return false
}
return true
}
private fun ensureStatsProgram(): Int? {
if (statsProgram != 0) return statsProgram
if (statsFailed) return null
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, STATS_SHADER)
if (vertexShader == 0 || fragmentShader == 0) {
if (vertexShader != 0) GLES30.glDeleteShader(vertexShader)
if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader)
PLog.e(tag, "Unable to compile tone base stats shader")
statsFailed = true
return null
}
val linked = GlUtils.linkProgram(vertexShader, fragmentShader)
GLES30.glDeleteShader(vertexShader)
GLES30.glDeleteShader(fragmentShader)
if (linked == 0) {
PLog.e(tag, "Unable to link tone base stats program")
statsFailed = true
return null
}
statsProgram = linked
return statsProgram
}
private fun releaseStatsTarget() {
if (statsTexture != 0) GLES30.glDeleteTextures(1, intArrayOf(statsTexture), 0)
if (statsFramebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(statsFramebuffer), 0)
statsTexture = 0
statsFramebuffer = 0
}
private fun ensureProgram(): Int? {
if (program != 0) return program
if (programFailed) return null
val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER)
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, DOWNSAMPLE_SHADER)
if (vertexShader == 0 || fragmentShader == 0) {
if (vertexShader != 0) GLES30.glDeleteShader(vertexShader)
if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader)
PLog.e(tag, "Unable to compile tone base downsample shader")
programFailed = true
return null
}
val linked = GlUtils.linkProgram(vertexShader, fragmentShader)
GLES30.glDeleteShader(vertexShader)
GLES30.glDeleteShader(fragmentShader)
if (linked == 0) {
PLog.e(tag, "Unable to link tone base downsample program")
programFailed = true
return null
}
program = linked
return program
}
private fun createLevel(level: Level, width: Int, height: Int): Boolean {
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
level.texture = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, level.texture)
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_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
val framebuffers = IntArray(1)
GLES30.glGenFramebuffers(1, framebuffers, 0)
level.framebuffer = framebuffers[0]
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, level.framebuffer)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
level.texture,
0,
)
val complete = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
GLES30.GL_FRAMEBUFFER_COMPLETE
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
if (!complete) {
PLog.e(tag, "Tone base target ${width}x$height is incomplete")
return false
}
level.width = width
level.height = height
return true
}
private companion object {
const val LEVEL_COUNT = 3
const val BASE_DIVISOR = 4
const val STATS_TEXTURE_UNIT = 12
const val STATS_SAMPLE_GRID = 32
val STATS_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uToneStatsSource;
void main() {
float low = 1.0e9;
float high = -1.0e9;
float sum = 0.0;
for (int y = 0; y < $STATS_SAMPLE_GRID; ++y) {
for (int x = 0; x < $STATS_SAMPLE_GRID; ++x) {
vec2 uv = (vec2(float(x), float(y)) + 0.5) / float($STATS_SAMPLE_GRID);
float value = texture(uToneStatsSource, uv).r;
low = min(low, value);
high = max(high, value);
sum += value;
}
}
float count = float($STATS_SAMPLE_GRID * $STATS_SAMPLE_GRID);
fragColor = vec4(low, high, sum / count, 1.0);
}
""".trimIndent()
// 2x2 box through four bilinear taps at the corners of the source texel footprint.
val DOWNSAMPLE_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uToneBaseSource;
uniform vec2 uToneBaseSourceTexel;
void main() {
vec2 offset = uToneBaseSourceTexel * 0.5;
float sum = texture(uToneBaseSource, vTexCoord + vec2(-offset.x, -offset.y)).r;
sum += texture(uToneBaseSource, vTexCoord + vec2(offset.x, -offset.y)).r;
sum += texture(uToneBaseSource, vTexCoord + vec2(-offset.x, offset.y)).r;
sum += texture(uToneBaseSource, vTexCoord + vec2(offset.x, offset.y)).r;
fragColor = vec4(sum * 0.25, 0.0, 0.0, 1.0);
}
""".trimIndent()
}
}
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.raw
import android.opengl.GLES30
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
import com.hinnka.mycamera.lut.ToneBaseGl
import com.hinnka.mycamera.utils.PLog
import kotlin.math.max
@@ -29,6 +30,7 @@ internal class RawAdjustmentPass(
private var program = 0
private var loggedUniformLocations = false
private val toneBase = ToneBaseGl(TAG)
fun render(input: Input): Output? {
val activeProgram = getOrCreateProgram()
@@ -44,10 +46,32 @@ internal class RawAdjustmentPass(
"source=${input.textureId} target=${input.targetTextureId} " +
"size=${input.width}x${input.height}",
)
GLES30.glUseProgram(activeProgram)
val shadowsHighlightsActive =
ShadowsHighlightsShader.isActive(input.highlights, input.shadows)
if (shadowsHighlightsActive &&
toneBase.prepare(input.width, input.height) &&
toneBase.bindLevel0()
) {
draw(input, activeProgram, toneBaseOnly = true)
toneBase.buildLevels { quad.draw(it) }
}
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, input.targetFramebufferId)
GLES30.glViewport(0, 0, input.width, input.height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
draw(input, activeProgram, toneBaseOnly = false)
RawGlesProgram.logErrors("RawAdjustmentPass.render")
return Output(input.targetTextureId, input.width, input.height)
}
private fun draw(input: Input, activeProgram: Int, toneBaseOnly: Boolean) {
GLES30.glUseProgram(activeProgram)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(activeProgram, "uToneBaseOnly"),
if (toneBaseOnly) 1 else 0,
)
if (!toneBaseOnly) {
toneBase.bind(activeProgram)
}
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, input.textureId)
GLES30.glUniform1i(
@@ -86,8 +110,6 @@ internal class RawAdjustmentPass(
)
quad.bindIdentityTextureMatrix(activeProgram)
quad.draw(activeProgram)
RawGlesProgram.logErrors("RawAdjustmentPass.render")
return Output(input.targetTextureId, input.width, input.height)
}
fun release() {
@@ -95,6 +117,7 @@ internal class RawAdjustmentPass(
GLES30.glDeleteProgram(program)
program = 0
}
toneBase.release()
}
private fun getOrCreateProgram(): Int {
@@ -121,26 +144,7 @@ internal class RawAdjustmentPass(
uniform float uShadows;
uniform float uBlacks;
uniform float uWhites;
vec3 sampleToneSource(vec2 uv) {
return texture(uInputTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb;
}
vec3 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;
}
uniform int uToneBaseOnly;
${ShadowsHighlightsShader.GLSL}
@@ -177,7 +181,11 @@ internal class RawAdjustmentPass(
void main() {
vec3 color = texture(uInputTexture, vTexCoord).rgb;
color = applyShadowsHighlights(color, vTexCoord);
if (uToneBaseOnly != 0) {
fragColor = vec4(shLogLuminance(color), 0.0, 0.0, 1.0);
return;
}
color = applyShadowsHighlightsLinear(color, vTexCoord);
color = applyBlackWhiteLevels(color);
fragColor = vec4(color, 1.0);
}
@@ -1,7 +1,5 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.lut.ShadowsHighlightsShader
/** Selects a rendering engine and composes its shader with the shared tone pipeline. */
internal class RawEngineTonePass(
private val quad: RawFullscreenQuad,
@@ -159,7 +157,7 @@ internal class RawEngineTonePass(
}
internal fun fragmentShader(shaderDefinition: RawEngineToneShaderDefinition): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -183,7 +181,7 @@ internal class RawEngineTonePass(
internal fun hdrReferenceFragmentShader(
shaderDefinition: RawEngineToneShaderDefinition,
): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -306,7 +304,7 @@ internal class RawEngineTonePass(
shaderDefinition: RawEngineToneShaderDefinition,
isHncs: Boolean,
): String {
val source = combinedFragmentShader(shaderDefinition, includeShadowsHighlights = false)
val source = combinedFragmentShader(shaderDefinition)
val cutoff = source.indexOf("const vec3 BW_LUMA")
.takeIf { it >= 0 }
?: source.indexOf("void main()").takeIf { it >= 0 }
@@ -339,14 +337,8 @@ internal class RawEngineTonePass(
""".trimIndent()
}
fun combinedFragmentShaderFor(
colorEngine: RawRenderingEngine,
includeShadowsHighlights: Boolean = true,
): String {
return combinedFragmentShader(
shaderDefinition = shaderDefinitionFor(colorEngine),
includeShadowsHighlights = includeShadowsHighlights,
)
fun combinedFragmentShaderFor(colorEngine: RawRenderingEngine): String {
return combinedFragmentShader(shaderDefinition = shaderDefinitionFor(colorEngine))
}
internal fun shaderDefinitionFor(
@@ -368,50 +360,7 @@ internal class RawEngineTonePass(
private fun combinedFragmentShader(
shaderDefinition: RawEngineToneShaderDefinition,
includeShadowsHighlights: Boolean,
): String {
val shadowsHighlightsUniforms = if (includeShadowsHighlights) {
"""
uniform vec2 uTexelSize;
uniform float uHighlights;
uniform float uShadows;
""".trimIndent()
} else {
""
}
val shadowsHighlightsFunctions = if (includeShadowsHighlights) {
"""
vec3 sampleToneSource(vec2 uv) {
vec3 sampleColor = texture(uInputTexture, clamp(uv, vec2(0.0), vec2(1.0))).rgb;
return applyEngineTone(prepareEngineInput(sampleColor));
}
vec3 shRgbToXyz(vec3 rgb) {
return mat3(
0.4360747, 0.2225045, 0.0139322,
0.3850649, 0.7168786, 0.0971045,
0.1430804, 0.0606169, 0.7141733
) * rgb;
}
vec3 shXyzToRgb(vec3 xyz) {
return mat3(
3.1338561, -0.9787684, 0.0719453,
-1.6168667, 1.9161415, -0.2289914,
-0.4906146, 0.0334540, 1.4052427
) * xyz;
}
${ShadowsHighlightsShader.GLSL}
""".trimIndent()
} else {
""
}
val shadowsHighlightsApply = if (includeShadowsHighlights) {
"color = applyShadowsHighlights(color, vTexCoord);"
} else {
""
}
val prepareEngineInputFunction = if (shaderDefinition.includeAdobeProfilePipeline) {
"""
vec3 prepareProfileGainInput(vec3 color) {
@@ -456,7 +405,6 @@ internal class RawEngineTonePass(
uniform sampler2D uInputTexture;
uniform float uBlacks;
uniform float uWhites;
$shadowsHighlightsUniforms
uniform mat3 uProfileToEngineTransform;
${shaderDefinition.engineUniforms}
@@ -479,8 +427,6 @@ internal class RawEngineTonePass(
$prepareEngineInputFunction
$shadowsHighlightsFunctions
const vec3 BW_LUMA = vec3(0.2126, 0.7152, 0.0722);
const float BW_EPSILON = 0.000001;
@@ -521,7 +467,6 @@ internal class RawEngineTonePass(
vec3 color = texture(uInputTexture, vTexCoord).rgb;
color = prepareEngineInput(color);
color = applyEngineTone(color);
$shadowsHighlightsApply
color = applyBlackWhiteLevels(color);
// Engine tone and adjustment passes have a linear-RGB output contract.
// RawSrgbPass performs the single display encoding after all
@@ -30,10 +30,7 @@ class RawHncsShadersTest {
@Test
fun hncsShaderKeepsFilmCurveBeforeGammaAndOmitsHighlightStrength() {
val shader = RawEngineTonePass.combinedFragmentShaderFor(
colorEngine = RawRenderingEngine.Hncs,
includeShadowsHighlights = false,
)
val shader = RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.Hncs)
val filmCurve = shader.indexOf("color = hncsApplyFilmCurve(color);")
val gamma = shader.indexOf("color = hncsGammaEncode(color);")
@@ -65,18 +62,10 @@ class RawHncsShadersTest {
RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.AdobeCurve),
RawEngineTonePass.hdrReferenceFragmentShaderFor(RawRenderingEngine.AdobeCurve),
RawEngineTonePass.hdrBaseCurveFragmentShaderFor(RawRenderingEngine.AdobeCurve),
RawEngineTonePass.combinedFragmentShaderFor(
colorEngine = RawRenderingEngine.Hncs,
includeShadowsHighlights = false,
),
RawEngineTonePass.combinedFragmentShaderFor(
colorEngine = RawRenderingEngine.Hncs,
includeShadowsHighlights = true,
),
RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.Hncs),
RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.Lumix),
RawEngineTonePass.fragmentShaderFor(RawRenderingEngine.Canon),
RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.Canon),
RawEngineTonePass.combinedFragmentShaderFor(RawRenderingEngine.Canon, false),
RawEngineTonePass.hdrReferenceFragmentShaderFor(RawRenderingEngine.Canon),
RawEngineTonePass.hdrBaseCurveFragmentShaderFor(RawRenderingEngine.Canon),
RawEngineTonePass.hdrReferenceFragmentShaderFor(RawRenderingEngine.Hncs),