diff --git a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt index ae62ccd2..06b84ced 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/ColorPassProgram.kt @@ -61,8 +61,15 @@ internal data class ColorPassLocations( val uShadowsHighlightsStatsLocation: Int, val uShadowsHighlightsCurveLocation: Int, val uShadowsHighlightsAmountsLocation: Int, + val uPreviewBlurLocation: Int, + val uPreviewClarityLocation: Int, + val uPreviewSoftLightLocation: Int, + val uPreviewBloomLocation: Int, + val uPreviewRedHalationLocation: Int, val aPositionLocation: Int, val aTexCoordLocation: Int, + val previewBlur: Boolean, + val liteShadowsHighlights: Boolean, ) internal class PreviewColorProgramCache { @@ -175,8 +182,15 @@ internal class PreviewColorProgramCache { 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"), + uPreviewBloomLocation = GLES30.glGetUniformLocation(program, "uPreviewBloom"), + 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, ) } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index d02599bf..40b66187 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -196,6 +196,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { private var clarityOutputHeight: Int = 0 private val filmGrainGl = FilmGrainGl(TAG) private val highlightDiffusionGl = HighlightDiffusionGl(TAG) + private val previewLiteEffects = PreviewLiteEffectsGl(TAG) private var filmGrainSourceTextureId: Int = 0 private var filmGrainSourceFboId: Int = 0 private var filmGrainSourceWidth: Int = 0 @@ -359,6 +360,14 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { @Volatile var colorRecipeEnabled: Boolean = false + /** + * Replaces the multi-pass preview effects (highlights / shadows tone map, clarity pyramid, + * soft light, bloom, red halation, film grain pass) with single-pass approximations inside the + * colour pass. Capture and video keep the full implementations. + */ + @Volatile + var previewLiteEffectsEnabled: Boolean = true + @Volatile var baselineColorRecipeEnabled: Boolean = false @@ -579,6 +588,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { colorProgramCache.reset() shadowsHighlightsPreview.reset() shadowsHighlightsStackPreview.reset() + previewLiteEffects.reset() enginePreview.reset() mgcEisHardwareBufferRenderer.resetAfterContextLoss() mgcEisYuvRenderer.resetAfterContextLoss() @@ -793,6 +803,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { lutConfig = lutConfig, lutEnabled = lutEnabled && lutConfig != null, videoLogEnabled = enableVideoLog && videoLogProfile.isEnabled, + previewLite = previewLiteEffectsEnabled, ) return colorProgramCache.get( variant.copy(includeEnginePreview = includeEnginePreview, toneMapSource = toneMapSource) @@ -804,6 +815,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { 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() } @@ -857,10 +869,31 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } else { null } + val previewBlurTextureId = if (locations.previewBlur) { + val oesSource = sourceTextureTarget == GLES11Ext.GL_TEXTURE_EXTERNAL_OES + previewLiteEffects.render( + sourceTarget = sourceTextureTarget, + sourceTextureId = sourceTextureId, + sourceWidth = if (oesSource) previewWidth else width, + sourceHeight = if (oesSource) previewHeight else height, + drawQuad = ::drawSimpleQuad, + ) + } else { + 0 + } GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId) GLES30.glViewport(0, 0, width, height) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(locations.programId) + if (locations.previewBlur) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + PreviewLiteEffectsGl.TEXTURE_UNIT) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, previewBlurTextureId) + GLES30.glUniform1i(locations.uPreviewBlurLocation, PreviewLiteEffectsGl.TEXTURE_UNIT) + GLES30.glUniform1f(locations.uPreviewClarityLocation, params.clarity.coerceIn(-1f, 1f)) + GLES30.glUniform1f(locations.uPreviewSoftLightLocation, params.softLight) + GLES30.glUniform1f(locations.uPreviewBloomLocation, params.bloom) + GLES30.glUniform1f(locations.uPreviewRedHalationLocation, params.redHalation) + } (shadowsHighlights ?: shadowsHighlightsPreview).bind(locations, shadowsHighlightsResult) colorProgramCache.bindLogInput(locations) enginePreview.bind(locations.uEnginePreviewLutLocation) @@ -908,11 +941,12 @@ 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 (shadowsHighlightsResult != null) params.highlights else 0f, - shadows = if (shadowsHighlightsResult != null) params.shadows else 0f, + highlights = if (shadowsHighlightsApplied) params.highlights else 0f, + shadows = if (shadowsHighlightsApplied) params.shadows else 0f, ) GLES30.glUniform1f(locations.uSharpeningLocation, params.sharpness.coerceIn(-1f, 1f)) GLES30.glUniform1f(locations.uFilmGrainLocation, params.filmGrain) @@ -1098,15 +1132,17 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } val liveRecorder = livePhotoRecorder - val hdfEnabled = halation > 0.001f - val halationEnabled = redHalation > 0.001f - val bloomEnabled = bloom > 0.001f - val softLightEnabled = softLight > 0.001f - val clarityEnabled = abs(clarity) > 0.001f + // Lite mode renders these inside the colour pass instead of as separate passes. + val fullPostProcess = !previewLiteEffectsEnabled + val hdfEnabled = fullPostProcess && halation > 0.001f + val halationEnabled = fullPostProcess && redHalation > 0.001f + val bloomEnabled = fullPostProcess && bloom > 0.001f + val softLightEnabled = fullPostProcess && softLight > 0.001f + val clarityEnabled = fullPostProcess && abs(clarity) > 0.001f val preLogFilmGrainEnabled = filmGrain > 0.001f && videoLogProfile.isEnabled && !(lutEnabled && currentLutConfig != null) - val filmGrainEnabled = filmGrain > 0.001f && !preLogFilmGrainEnabled + val filmGrainEnabled = fullPostProcess && filmGrain > 0.001f && !preLogFilmGrainEnabled val postProcessEffectEnabled = hdfEnabled || halationEnabled || bloomEnabled || softLightEnabled val eyeFocusSamplingNeeded = onEyeFocusInputAvailable != null && !isEyeFocusBusy val suppressBaselineLayerForVideoLog = videoLogProfile.isEnabled @@ -3237,6 +3273,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { releaseClarityPreviewFramebuffers() shadowsHighlightsPreview.release() shadowsHighlightsStackPreview.release() + previewLiteEffects.release() filmGrainGl.release() highlightDiffusionGl.release() releaseFilmGrainSourceFramebuffer() diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt index e3d6b28f..287131f2 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShader.kt @@ -16,6 +16,7 @@ internal object PreviewColorShader { val needsClassifiers = variant.includeLchMixer || variant.includeLutMask val needsLogInput = variant.includeVideoLog || variant.includeExtendedLutCurves + fun op(bit: Int, code: String) = if (variant.recipeOps and bit != 0) code else "" return """ #version 300 es ${extension} @@ -54,7 +55,7 @@ internal object PreviewColorShader { uniform float uHighlights; uniform float uShadows; ${if (variant.includeSharpening) "uniform float uSharpening;" else ""} - ${if (variant.includePreLogFilmGrain) """ + ${if (variant.includePreLogFilmGrain || variant.includeFinalFilmGrain) """ uniform float uFilmGrain; uniform float uFilmGrainSeed; uniform float uFilmGrainPixelScale; @@ -130,7 +131,7 @@ internal object PreviewColorShader { return dot(color, W); } - ${if (variant.includeColorRecipe && !variant.toneMapSource) """ + ${if (variant.includeShadowsHighlights && !variant.toneMapSource) """ uniform highp sampler2D uShadowsHighlightsMask; uniform highp sampler2D uShadowsHighlightsStats; uniform highp sampler2D uShadowsHighlightsCurve; @@ -154,6 +155,8 @@ internal object PreviewColorShader { ${if (variant.includeLutMask) PreviewColorShaderModules.LUT_MASK else PreviewColorShaderModules.LUT_MASK_STUB} ${if (variant.includeExtendedLutCurves) PreviewColorShaderModules.EXTENDED_LUT_CURVES else PreviewColorShaderModules.SIMPLE_LUT_CURVES} ${if (variant.includePreLogFilmGrain) FilmGrainShaders.FUNCTIONS else ""} + ${if (variant.includeFinalFilmGrain) PreviewLiteEffectsGl.GRAIN_GLSL else ""} + ${if (variant.includePreviewBlur) PreviewLiteEffectsGl.GLSL else ""} ${PreviewColorShaderModules.PRIMARY_CALIBRATION} ${PreviewColorShaderModules.LUT_COLOR_SPACE} @@ -170,7 +173,7 @@ internal object PreviewColorShader { // The vertex stage already applies crop and the SurfaceTexture transform. // Only effects that change raw coordinates need a fragment-stage transform. vec2 uvCoord = vTexCoord; - if (uLowRes > 0.005) { + if (${if (variant.recipeOps and RecipeOps.LOW_RES != 0) "uLowRes > 0.005" else "false"}) { float blocksX = mix(512.0, 32.0, uLowRes); vec2 gridSize = vec2(1.0 / blocksX, 1.0 / (blocksX / uAspectRatio)); vec2 gridRC = floor(rcCoord / gridSize) * gridSize + gridSize * 0.5; @@ -201,35 +204,47 @@ internal object PreviewColorShader { color.rgb = applyJpegInputToneCurve(color.rgb); color.rgb = sanitizeColor(color.rgb); """ else ""} + ${if (variant.includeLiteClarity) "float previewSourceLuma = getLuma(color.rgb);" else ""} if (${if (variant.includeColorRecipe) "uColorRecipeEnabled" else "false"}) { + ${op(RecipeOps.EXPOSURE, """ if (abs(uExposure) > 0.001) { color.rgb = applyExposureInLinearSpace(color.rgb, uExposure); color.rgb = sanitizeColor(color.rgb); } + """)} ${if (variant.toneMapSource) """ fragColor = vec4(color.rgb, 1.0); return; - """ else if (variant.includeColorRecipe) """ + """ else if (variant.includeShadowsHighlights) """ color.rgb = applyShadowsHighlights(color.rgb, vOutputCoord); color.rgb = sanitizeColor(color.rgb); + """ else if (variant.includeLiteShadowsHighlights) """ + color.rgb = applyPreviewShadowsHighlights(color.rgb, uvCoord); + color.rgb = sanitizeColor(color.rgb); """ else ""} float luma = getLuma(color.rgb); + ${op(RecipeOps.CONTRAST, """ color.rgb = applyContrastSCurve(color.rgb, uContrast); color.rgb = sanitizeColor(color.rgb); + """)} + ${op(RecipeOps.BASIC_TONE, """ color.rgb = applyBasicToneLut(color.rgb); color.rgb = sanitizeColor(color.rgb); + """)} + ${op(RecipeOps.WHITE_BALANCE, """ color.r += uTemperature * 0.1; color.b -= uTemperature * 0.1; color.g -= uTint * 0.05; color.rgb = sanitizeColor(color.rgb); + """)} - if (abs(uSaturation - 1.0) > 0.001) { + if (${if (variant.recipeOps and RecipeOps.SATURATION != 0) "abs(uSaturation - 1.0) > 0.001" else "false"}) { luma = dot(color.rgb, W); color.rgb = mix(vec3(luma), color.rgb, uSaturation); color.rgb = sanitizeColor(color.rgb); @@ -240,12 +255,17 @@ internal object PreviewColorShader { color.rgb = sanitizeColor(color.rgb); } + ${op(RecipeOps.PRIMARY_CALIBRATION, """ color.rgb = applyPrimaryCalibration(color.rgb); color.rgb = sanitizeColor(color.rgb); + """)} + ${if (variant.includeLchMixer) """ color.rgb = applyLchColorMixer(color.rgb); color.rgb = sanitizeColor(color.rgb); + """ else ""} + ${op(RecipeOps.GRADING, """ color.rgb = applyThreeWayColorGrading( color.rgb, uGradingHues, @@ -256,13 +276,17 @@ internal object PreviewColorShader { W ); color.rgb = sanitizeColor(color.rgb); + """)} + ${op(RecipeOps.FADE, """ if (uFade > 0.001) { float fadeAmount = uFade * 0.3; color.rgb = mix(color.rgb, vec3(0.5), fadeAmount) + fadeAmount * 0.1; color.rgb = sanitizeColor(color.rgb); } + """)} + ${op(RecipeOps.BLEACH_BYPASS, """ if (uBleachBypass > 0.001) { luma = dot(color.rgb, W); vec3 desaturated = mix(color.rgb, vec3(luma), 0.6); @@ -273,12 +297,16 @@ internal object PreviewColorShader { color.rgb = mix(color.rgb, desaturated, uBleachBypass); color.rgb = sanitizeColor(color.rgb); } + """)} + ${op(RecipeOps.FLASH, """ if (uFlash > 0.001) { color.rgb = applyDirectFlash(color.rgb, vTexCoord, uAspectRatio, uFlash); color.rgb = sanitizeColor(color.rgb); } + """)} + ${op(RecipeOps.VIGNETTE, """ if (abs(uVignette) > 0.001) { float dist = distance(vTexCoord, vec2(0.5)); float vignetteMask = smoothstep(0.8, 0.3, dist); @@ -289,7 +317,9 @@ internal object PreviewColorShader { } color.rgb = sanitizeColor(color.rgb); } + """)} + ${op(RecipeOps.NOISE, """ if (uNoise > 0.001) { vec2 seedOffset = vec2(fract(uNoiseSeed * 1.234), fract(uNoiseSeed * 3.456)); vec2 noiseCoord = uvCoord * 800.0 + seedOffset * 100.0; @@ -305,6 +335,7 @@ internal object PreviewColorShader { color.rgb += finalNoise * uNoise * max(0.0, noiseMask); color.rgb = sanitizeColor(color.rgb); } + """)} color.rgb = sanitizeColor(color.rgb); } @@ -403,6 +434,31 @@ internal object PreviewColorShader { } """ else ""} + // Preview-only stand-ins, in the order of the full post-process chain. + ${if (variant.includeLiteClarity) """ + color.rgb = sanitizeColor(applyPreviewClarity(color.rgb, previewSourceLuma, uvCoord)); + """ else ""} + ${if (variant.includeLiteSoftLight) """ + color.rgb = sanitizeColor(applyPreviewSoftLight(clamp(color.rgb, 0.0, 1.0), uvCoord)); + """ else ""} + ${if (variant.includeLiteBloom) """ + color.rgb = sanitizeColor(applyPreviewBloom(clamp(color.rgb, 0.0, 1.0), uvCoord)); + """ else ""} + ${if (variant.includeLiteRedHalation) """ + color.rgb = sanitizeColor(applyPreviewRedHalation(clamp(color.rgb, 0.0, 1.0), uvCoord)); + """ else ""} + ${if (variant.includeFinalFilmGrain) """ + if (uFilmGrain > 0.001) { + color.rgb = applyPreviewFilmGrain( + clamp(color.rgb, 0.0, 1.0), + gl_FragCoord.xy, + uFilmGrain, + uFilmGrainSeed, + uFilmGrainPixelScale + ); + } + """ else ""} + fragColor = vec4(clamp(sanitizeColor(color.rgb), 0.0, 1.0), color.a); } """.trimIndent().trimStart() diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt index a98b7e75..89141291 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewColorShaderVariant.kt @@ -23,12 +23,34 @@ 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]. */ + val includeLiteShadowsHighlights: Boolean = false, + val includeLiteClarity: Boolean = false, + val includeLiteSoftLight: Boolean = false, + val includeLiteBloom: Boolean = false, + val includeLiteRedHalation: Boolean = false, + /** Cheap film grain after the LUT, in place of the separate grain pass. */ + val includeFinalFilmGrain: Boolean = false, + /** + * [RecipeOps] bits of the recipe steps that are not identity. Only these are emitted, so a + * 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 || + includeLiteBloom || includeLiteRedHalation + companion object { fun forPass( textureSource: PreviewColorTextureSource, @@ -36,8 +58,13 @@ internal data class PreviewColorShaderVariant( lutConfig: LutConfig?, lutEnabled: Boolean, videoLogEnabled: Boolean, + previewLite: Boolean = false, ): PreviewColorShaderVariant { val lutCurve = lutConfig?.curve ?: TransferCurve.SRGB + val recipe = !params.isDefault() + val shadowsHighlights = recipe && ShadowsHighlightsShader.isActive(params.highlights, params.shadows) + val preLogFilmGrain = videoLogEnabled && !lutEnabled && params.filmGrain > EPSILON + val lite = previewLite && recipe return PreviewColorShaderVariant( textureSource = textureSource, includeExtendedLutCurves = videoLogEnabled || @@ -45,14 +72,20 @@ internal data class PreviewColorShaderVariant( includeOklchDensity = abs(params.color) > EPSILON, includeLchMixer = params.hasLchAdjustments(), // A custom Log recording has no display LUT, so bake grain before encoding. - includePreLogFilmGrain = videoLogEnabled && - !lutEnabled && - params.filmGrain > EPSILON, + includePreLogFilmGrain = preLogFilmGrain, includeVideoLog = videoLogEnabled, // Match the shader's activation threshold, including negative (softening) values. includeSharpening = abs(params.sharpness) > 0.0001f, includeChromaticAberration = params.chromaticAberration > 0.001f, - includeColorRecipe = !params.isDefault(), + includeColorRecipe = recipe, + includeShadowsHighlights = shadowsHighlights && !previewLite, + includeLiteShadowsHighlights = shadowsHighlights && previewLite, + includeLiteClarity = lite && abs(params.clarity) > EPSILON, + includeLiteSoftLight = lite && params.softLight > EPSILON, + includeLiteBloom = lite && params.bloom > EPSILON, + includeLiteRedHalation = lite && params.redHalation > EPSILON, + includeFinalFilmGrain = lite && !preLogFilmGrain && params.filmGrain > EPSILON, + recipeOps = if (recipe) RecipeOps.of(params) else 0, ) } @@ -90,3 +123,47 @@ private fun ColorRecipeParams.hasLchAdjustments(): Boolean { abs(magentaChroma) > 0.001f || abs(magentaLightness) > 0.001f } + +/** Recipe steps of the colour pass; each bit set means the step changes the image. */ +internal object RecipeOps { + const val EXPOSURE = 1 shl 0 + const val CONTRAST = 1 shl 1 + const val BASIC_TONE = 1 shl 2 + const val WHITE_BALANCE = 1 shl 3 + const val SATURATION = 1 shl 4 + const val PRIMARY_CALIBRATION = 1 shl 5 + const val GRADING = 1 shl 6 + const val FADE = 1 shl 7 + const val BLEACH_BYPASS = 1 shl 8 + const val FLASH = 1 shl 9 + const val VIGNETTE = 1 shl 10 + const val NOISE = 1 shl 11 + const val LOW_RES = 1 shl 12 + const val ALL = (1 shl 13) - 1 + + // Thresholds match the shader's own early-outs. + fun of(params: ColorRecipeParams): Int { + var ops = 0 + if (abs(params.exposure) > 0.001f) ops = ops or EXPOSURE + if (abs(params.contrast.coerceIn(0.5f, 1.5f) - 1f) > 0f) ops = ops or CONTRAST + if (abs(params.tonality) >= 0.001f) ops = ops or BASIC_TONE + if (params.temperature != 0f || params.tint != 0f) ops = ops or WHITE_BALANCE + if (abs(params.saturation - 1f) > 0.001f) ops = ops or SATURATION + if (params.primaryRedHue != 0f || params.primaryRedSaturation != 0f || + params.primaryGreenHue != 0f || params.primaryGreenSaturation != 0f || + params.primaryBlueHue != 0f || params.primaryBlueSaturation != 0f + ) { + ops = ops or PRIMARY_CALIBRATION + } + if (maxOf(params.gradingShadowAmount, params.gradingMidtoneAmount, params.gradingHighlightAmount) > 0.0001f) { + ops = ops or GRADING + } + if (params.fade > 0.001f) ops = ops or FADE + if (params.bleachBypass > 0.001f) ops = ops or BLEACH_BYPASS + if (params.flash > 0.001f) ops = ops or FLASH + if (abs(params.vignette) > 0.001f) ops = ops or VIGNETTE + if (params.noise > 0.001f) ops = ops or NOISE + if (params.lowRes > 0.005f) ops = ops or LOW_RES + return ops + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt b/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt new file mode 100644 index 00000000..10f29338 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/PreviewLiteEffectsGl.kt @@ -0,0 +1,258 @@ +package com.hinnka.mycamera.lut + +import android.opengl.GLES11Ext +import android.opengl.GLES30 +import com.hinnka.mycamera.utils.PLog +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 and video keep the full implementations. + */ +internal class PreviewLiteEffectsGl(private val tag: String) { + private var oesProgram = 0 + private var texture2dProgram = 0 + private var texture = 0 + private var framebuffer = 0 + private var width = 0 + private var height = 0 + + /** Renders the blur pyramid of [sourceTextureId] and returns its texture, or 0 when unavailable. */ + fun render( + sourceTarget: Int, + sourceTextureId: Int, + sourceWidth: Int, + sourceHeight: Int, + drawQuad: (Int) -> Unit, + ): Int { + val program = ensureProgram(sourceTarget) + if (program == 0) return 0 + if (!ensureTarget(max(1, sourceWidth / DOWNSAMPLE), max(1, sourceHeight / DOWNSAMPLE))) return 0 + + GLES30.glDisable(GLES30.GL_BLEND) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer) + GLES30.glViewport(0, 0, width, height) + GLES30.glUseProgram(program) + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(sourceTarget, sourceTextureId) + GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSource"), 0) + GLES30.glUniform2f( + GLES30.glGetUniformLocation(program, "uSourceTexel"), + 1f / max(1, sourceWidth), + 1f / max(1, sourceHeight), + ) + drawQuad(program) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + return texture + } + + fun reset() { + oesProgram = 0 + texture2dProgram = 0 + texture = 0 + framebuffer = 0 + width = 0 + height = 0 + } + + fun release() { + GlUtils.deleteProgram(oesProgram) + GlUtils.deleteProgram(texture2dProgram) + releaseTarget() + reset() + } + + private fun ensureProgram(sourceTarget: Int): Int { + val oes = sourceTarget == GLES11Ext.GL_TEXTURE_EXTERNAL_OES + if (oes && oesProgram != 0) return oesProgram + if (!oes && texture2dProgram != 0) return texture2dProgram + val vertexShader = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER) + val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, downsampleShader(oes)) + if (vertexShader == 0 || fragmentShader == 0) { + if (vertexShader != 0) GLES30.glDeleteShader(vertexShader) + if (fragmentShader != 0) GLES30.glDeleteShader(fragmentShader) + PLog.e(tag, "Failed to compile preview lite downsample (oes=$oes)") + return 0 + } + val program = GlUtils.linkProgram(vertexShader, fragmentShader) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) + if (oes) oesProgram = program else texture2dProgram = program + return program + } + + private fun ensureTarget(targetWidth: Int, targetHeight: Int): Boolean { + if (texture != 0 && framebuffer != 0 && width == targetWidth && height == targetHeight) return true + releaseTarget() + val levels = 32 - Integer.numberOfLeadingZeros(max(targetWidth, targetHeight)) + texture = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0] + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, levels, GLES30.GL_RGBA8, targetWidth, targetHeight) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR_MIPMAP_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) + framebuffer = IntArray(1).also { GLES30.glGenFramebuffers(1, it, 0) }[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffer) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, 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, "Preview lite blur target ${targetWidth}x$targetHeight incomplete") + releaseTarget() + return false + } + width = targetWidth + height = targetHeight + return true + } + + private fun releaseTarget() { + if (texture != 0) GLES30.glDeleteTextures(1, intArrayOf(texture), 0) + if (framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0) + texture = 0 + framebuffer = 0 + width = 0 + height = 0 + } + + companion object { + const val TEXTURE_UNIT = 6 + private const val DOWNSAMPLE = 4 + + // Four bilinear taps cover the 4x4 source footprint of each quarter-resolution texel. + private fun downsampleShader(oes: Boolean): String = """ + #version 300 es + ${if (oes) "#extension GL_OES_EGL_image_external_essl3 : require" else ""} + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + uniform ${if (oes) "samplerExternalOES" else "sampler2D"} uSource; + uniform vec2 uSourceTexel; + void main() { + vec2 d = uSourceTexel; + vec3 color = texture(uSource, vTexCoord + vec2(-d.x, -d.y)).rgb; + color += texture(uSource, vTexCoord + vec2(d.x, -d.y)).rgb; + color += texture(uSource, vTexCoord + vec2(-d.x, d.y)).rgb; + color += texture(uSource, vTexCoord + vec2(d.x, d.y)).rgb; + color = clamp(color * 0.25, 0.0, 1.0); + float y = dot(color, vec3(0.299, 0.587, 0.114)); + fragColor = vec4(color, clamp((y - $BLOOM_THRESHOLD) / (1.0 - $BLOOM_THRESHOLD), 0.0, 1.0)); + } + """.trimIndent() + + private const val BLOOM_THRESHOLD = "0.598" + + /** + * Hash grain in place of the density / simplex model: one cell per grain, triangular + * noise, strongest in the midtones and thinned in highlights like the full model. + */ + const val GRAIN_GLSL = """ + float previewGrainHash(vec2 p) { + vec3 p3 = fract(vec3(p.xyx) * 0.1031); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.x + p3.y) * p3.z); + } + + vec3 applyPreviewFilmGrain(vec3 color, vec2 pixel, float amount, float seed, float pixelScale) { + float normalizedAmount = clamp(amount, 0.0, 1.0); + float grainSize = max(pixelScale, 0.25) * mix(0.5, 1.0, smoothstep(0.0, 0.5, normalizedAmount)); + vec2 cell = floor(pixel / max(grainSize, 0.5)) + + floor(fract(seed * vec2(0.754877666, 0.569840296)) * 1024.0); + float noise = previewGrainHash(cell) + previewGrainHash(cell + 17.0) - 1.0; + float luma = dot(color, W); + float tonal = mix(0.35, 1.0, 4.0 * luma * (1.0 - luma)) * + mix(1.0, 0.32, smoothstep(0.75, 0.97, luma)); + return color + vec3(noise * pow(normalizedAmount, 0.58) * 0.09 * tonal); + } + """ + + /** + * 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. + */ + const val GLSL = """ + uniform sampler2D uPreviewBlur; + uniform float uPreviewClarity; + uniform float uPreviewSoftLight; + 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. + 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) { + float referenceLuma = dot(max(color, vec3(0.0)), W); + float l0 = dot(textureLod(uPreviewBlur, uv, 0.0).rgb, W); + float l1 = dot(textureLod(uPreviewBlur, uv, 1.0).rgb, W); + float l2 = dot(textureLod(uPreviewBlur, uv, 2.0).rgb, W); + float detail = (sourceLuma - l0) * 0.2 + (l0 - l1) * 0.5 + (l1 - l2) * 0.32; + float tonalWeight = smoothstep(0.02, 0.18, l2) * (1.0 - smoothstep(0.72, 0.98, l2)); + float gain = uPreviewClarity * (uPreviewClarity >= 0.0 ? 1.8 : 1.1); + float processedLuma = max(referenceLuma + detail * gain * tonalWeight, 0.0); + const float epsilon = 1.0 / 65535.0; + float factor = referenceLuma > 0.00002 + ? clamp((processedLuma + epsilon) / (referenceLuma + epsilon), 0.25, 4.0) + : 1.0; + return color * factor; + } + + vec3 applyPreviewSoftLight(vec3 color, vec2 uv) { + vec3 softBlur = textureLod(uPreviewBlur, uv, 1.5).rgb; + vec3 screen = vec3(1.0) - (vec3(1.0) - color) * (vec3(1.0) - softBlur); + vec3 softGlow = mix(color, screen, 0.42); + color = mix(color, softGlow, uPreviewSoftLight * 0.75); + color += vec3(dot(softBlur, W)) * (uPreviewSoftLight * 0.025); + return (color - 0.5) * (1.0 - uPreviewSoftLight * 0.05) + 0.5; + } + + vec3 applyPreviewBloom(vec3 color, vec2 uv) { + vec4 blurred = textureLod(uPreviewBlur, uv, 2.5); + vec3 linearColor = pow(max(color, vec3(0.0)), vec3(2.2)); + vec3 linearBloom = pow(clamp(blurred.rgb * blurred.a * 1.5, 0.0, 1.0), vec3(2.2)); + if (uPreviewBloom <= 0.5) { + vec3 full = pow(clamp(linearColor + linearBloom, 0.0, 1.0), vec3(1.0 / 2.2)); + return mix(color, full, uPreviewBloom * 2.0); + } + return pow(linearColor + linearBloom * (uPreviewBloom * 2.0), vec3(1.0 / 2.2)); + } + + vec3 applyPreviewRedHalation(vec3 color, vec2 uv) { + float mask = textureLod(uPreviewBlur, uv, 2.0).a; + float x = min(mask * 1.5, 1.0); + float amount = x < 0.4 ? 0.4 * pow(x / 0.4, 1.25) : 0.4 + 0.6 * pow((x - 0.4) / 0.6, 0.8); + float y = dot(color, vec3(0.299, 0.587, 0.114)); + float destination = 1.0 / (1.0 + exp(-50.0 * (1.0 - y))); + vec3 glow = amount * vec3(1.0, 0.05, 0.05) * uPreviewRedHalation * destination; + vec3 linearColor = pow(max(color, vec3(0.0)), vec3(2.2)); + return pow(clamp(linearColor + glow, 0.0, 1.0), vec3(1.0 / 2.2)); + } + """ + } +}