fix: bokeh

This commit is contained in:
zhoubinjia committed 2026-07-22 15:01:13 +08:00
1 parent bb6c3b288b
commit 16e1207e8f
8 files changed
+588 -108

No files matched your search

@@ -0,0 +1,73 @@
package com.hinnka.mycamera.processor
import android.graphics.Bitmap
import android.graphics.Color
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class OglBokehProcessorShaderTest {
@Test
fun productionBokehShadersCompileAndLinkOnDevice() {
val processor = OglBokehProcessor()
try {
assertEquals(1922 to 2560, invokePrivate(processor, "resolveBokehRenderSize", 4098, 5458))
invokePrivate(processor, "initEGL", 32, 32)
invokePrivate(processor, "initGL")
assertTrue(readPrivateInt(processor, "bokehProgramId") != 0)
assertTrue(readPrivateInt(processor, "bokehCompositeProgramId") != 0)
assertTrue(readPrivateInt(processor, "jbuUpsampleProgramId") != 0)
assertTrue(readPrivateInt(processor, "depthSharpenProgramId") != 0)
} finally {
invokePrivate(processor, "releaseGL")
}
}
@Test
fun productionBokehPipelineRendersThroughFullResolutionComposite() {
val input = Bitmap.createBitmap(64, 48, Bitmap.Config.ARGB_8888).apply {
eraseColor(Color.rgb(96, 128, 160))
}
val depth = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888).apply {
eraseColor(Color.rgb(128, 128, 128))
}
val result = try {
OglBokehProcessor().applyBokeh(
originalImage = input,
lowResDepthMap = depth,
focusX = 0.5f,
focusY = 0.5f,
aperture = 1.4f,
)
} finally {
input.recycle()
depth.recycle()
}
assertNotNull(result)
assertEquals(64, result?.width)
assertEquals(48, result?.height)
result?.recycle()
}
private fun invokePrivate(target: Any, methodName: String, vararg args: Any): Any? {
return target.javaClass.declaredMethods.first {
it.name == methodName && it.parameterCount == args.size
}.run {
isAccessible = true
invoke(target, *args)
}
}
private fun readPrivateInt(target: Any, fieldName: String): Int {
return target.javaClass.getDeclaredField(fieldName).run {
isAccessible = true
getInt(target)
}
}
}
@@ -932,6 +932,7 @@ object GalleryManager {
preparedUltraHdrSource: GainmapSourceSet? = null,
preparedGainmapResult: GainmapResult? = null,
preferHeicExport: Boolean? = null,
bitmapComputationalBokehApplied: Boolean = false,
): Boolean {
return withContext(Dispatchers.IO) {
val tempExportFile = File(context.cacheDir, "temp_export_${System.nanoTime()}.jpg")
@@ -1009,9 +1010,14 @@ object GalleryManager {
)
} else bitmap?.let {
photoProcessor.processBitmap(
context, id, bitmap, bitmapPostMetadata,
bitmapSharpeningValue, bitmapNoiseReductionValue, bitmapChromaNoiseReductionValue,
true
context = context,
photoId = id,
input = bitmap,
metadata = bitmapPostMetadata,
sharpening = bitmapSharpeningValue,
noiseReduction = bitmapNoiseReductionValue,
chromaNoiseReduction = bitmapChromaNoiseReductionValue,
useComputationalAperture = !bitmapComputationalBokehApplied,
)
} ?: photoProcessor.process(
context, id, metadata,
@@ -1685,11 +1691,16 @@ object GalleryManager {
}
}
suspend fun generateBokehPhoto(context: Context, photoId: String, metadata: MediaMetadata, bitmap: Bitmap) {
private suspend fun renderAndSaveBokehPhoto(
context: Context,
photoId: String,
metadata: MediaMetadata,
bitmap: Bitmap,
): Bitmap {
val aperture = metadata.computationalAperture ?: 0f
if (aperture <= 0f) {
getBokehFile(context, photoId).takeIf { it.exists() }?.delete()
return
return bitmap
}
val focusPointX = metadata.focusPointX
val focusPointY = metadata.focusPointY
@@ -1702,6 +1713,14 @@ object GalleryManager {
aperture
)
saveBokehPhoto(context, photoId, bokeh)
return bokeh
}
suspend fun generateBokehPhoto(context: Context, photoId: String, metadata: MediaMetadata, bitmap: Bitmap) {
val bokeh = renderAndSaveBokehPhoto(context, photoId, metadata, bitmap)
if (bokeh !== bitmap && !bokeh.isRecycled) {
bokeh.recycle()
}
}
suspend fun saveYuvPhoto(
@@ -1718,6 +1737,9 @@ object GalleryManager {
photoQuality: Int = 95
) = withContext(Dispatchers.IO) {
beginHdrWork(photoId)
var previewBitmap: Bitmap? = null
var bokehBitmap: Bitmap? = null
var preparedUltraHdrSource: GainmapSourceSet? = null
try {
val photoDir = getPhotoDir(context, photoId, true)
@@ -1735,47 +1757,94 @@ object GalleryManager {
}
PLog.d(TAG, "saveYuvPhoto processAndToBitmap took ${nativeProcessElapsed}ms, success=${processedPreview != null}")
var previewBitmap = processedPreview ?: return@withContext
previewBitmap = processedPreview ?: return@withContext
if (metadata.isMirrored) {
previewBitmap = BitmapUtils.flipHorizontal(previewBitmap)
val sourcePreview = checkNotNull(previewBitmap)
val mirroredPreview = BitmapUtils.flipHorizontal(sourcePreview)
if (mirroredPreview !== sourcePreview && !sourcePreview.isRecycled) {
sourcePreview.recycle()
}
previewBitmap = mirroredPreview
}
if (metadata.usesNaturalLightToneMap()) {
val toneMappedPreview = photoProcessor.processCapturePreviewToneMap(previewBitmap, metadata)
if (toneMappedPreview !== previewBitmap && !previewBitmap.isRecycled) {
previewBitmap.recycle()
val sourcePreview = checkNotNull(previewBitmap)
val toneMappedPreview = photoProcessor.processCapturePreviewToneMap(sourcePreview, metadata)
if (toneMappedPreview !== sourcePreview && !sourcePreview.isRecycled) {
sourcePreview.recycle()
}
previewBitmap = toneMappedPreview
}
val originalFile = writeInternalOriginalPhoto(photoDir, previewBitmap, photoQuality) ?: return@withContext
val originalFile = writeInternalOriginalPhoto(photoDir, checkNotNull(previewBitmap), photoQuality)
?: return@withContext
PLog.d(TAG, "saveYuvPhoto internal original saved=${originalFile.name}")
generateBokehPhoto(context, photoId, metadata, previewBitmap)
queueDetailHdrCacheBuild(
bokehBitmap = renderAndSaveBokehPhoto(context, photoId, metadata, checkNotNull(previewBitmap))
preparedUltraHdrSource = photoProcessor.prepareUltraHdrSourceFromProcessedSdr(
context = context,
photoId = photoId,
processedSdr = checkNotNull(bokehBitmap),
metadata = metadata,
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue
chromaNoiseReduction = chromaNoiseReductionValue,
)
val preparedGainmapResult = preparedUltraHdrSource?.let { source ->
gainmapProducer.build(source, HdrGainmapStrength.coerce(metadata.hdrEffectStrength))
}
if (preparedUltraHdrSource != null) {
PLog.d(TAG, "saveYuvPhoto reusing one in-memory bokeh/HDR source: $photoId")
buildDetailHdrCache(
context = context,
photoId = photoId,
metadata = metadata,
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
preparedUltraHdrSource = preparedUltraHdrSource,
preparedGainmapResult = preparedGainmapResult,
)
} else {
deleteDetailHdrFile(context, photoId)
}
// updateThumbnail(context, photoId, photoProcessor, metadata)
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
null,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
context = context,
id = photoId,
bitmap = bokehBitmap,
photoProcessor = photoProcessor,
metadata = metadata,
sharpeningValue = sharpeningValue,
noiseReductionValue = noiseReductionValue,
chromaNoiseReductionValue = chromaNoiseReductionValue,
photoQuality = photoQuality,
preparedUltraHdrSource = preparedUltraHdrSource,
preparedGainmapResult = preparedGainmapResult,
bitmapComputationalBokehApplied = true,
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
preparedUltraHdrSource?.hdrReference?.bitmap?.let { bitmap ->
if (!bitmap.isRecycled) bitmap.recycle()
}
preparedUltraHdrSource?.lutLuminanceGainMap?.bitmap?.let { bitmap ->
if (!bitmap.isRecycled) bitmap.recycle()
}
preparedUltraHdrSource?.sdrBase?.let { bitmap ->
if (bitmap !== bokehBitmap && bitmap !== previewBitmap && !bitmap.isRecycled) {
bitmap.recycle()
}
}
bokehBitmap?.let { bitmap ->
if (bitmap !== previewBitmap && !bitmap.isRecycled) bitmap.recycle()
}
previewBitmap?.let { bitmap ->
if (!bitmap.isRecycled) bitmap.recycle()
}
endHdrWork(photoId)
}
}
@@ -1938,7 +2007,7 @@ object GalleryManager {
}
tempFile.renameTo(photoFile)
saveMetadata(context, photoId, updatedMetadata)
generateBokehPhoto(context, photoId, updatedMetadata, bitmap)
val bokehBitmap = renderAndSaveBokehPhoto(context, photoId, updatedMetadata, bitmap)
val preparedUltraHdrSource = if (updatedMetadata.manualHdrEffectEnabled) {
photoProcessor.prepareUltraHdrSourceFromRawResult(
context = context,
@@ -1948,7 +2017,8 @@ object GalleryManager {
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
applyMirror = true
applyMirror = true,
preparedSdrBitmap = bokehBitmap,
)
} else {
null
@@ -2001,10 +2071,13 @@ object GalleryManager {
}
}
preparedUltraHdrSource?.sdrBase?.let {
if (it !== bitmap && !it.isRecycled) {
if (it !== bitmap && it !== bokehBitmap && !it.isRecycled) {
it.recycle()
}
}
if (bokehBitmap !== bitmap && !bokehBitmap.isRecycled) {
bokehBitmap.recycle()
}
if (!bitmap.isRecycled) {
bitmap.recycle()
}
@@ -2986,7 +3059,7 @@ object GalleryManager {
}
tempFile.renameTo(photoFile)
saveMetadata(context, photoId, updatedMetadata)
generateBokehPhoto(context, photoId, updatedMetadata, bitmap)
val bokehBitmap = renderAndSaveBokehPhoto(context, photoId, updatedMetadata, bitmap)
val preparedUltraHdrSource = if (updatedMetadata.manualHdrEffectEnabled) {
photoProcessor.prepareUltraHdrSourceFromRawResult(
@@ -2997,7 +3070,8 @@ object GalleryManager {
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
applyMirror = true
applyMirror = true,
preparedSdrBitmap = bokehBitmap,
)
} else {
null
@@ -3052,10 +3126,13 @@ object GalleryManager {
}
}
preparedUltraHdrSource?.sdrBase?.let {
if (it !== bitmap && !it.isRecycled) {
if (it !== bitmap && it !== bokehBitmap && !it.isRecycled) {
it.recycle()
}
}
if (bokehBitmap !== bitmap && !bokehBitmap.isRecycled) {
bokehBitmap.recycle()
}
if (!bitmap.isRecycled) {
bitmap.recycle()
}
@@ -3166,7 +3243,7 @@ object GalleryManager {
}
tempFile.renameTo(photoFile)
saveMetadata(context, photoId, updatedMetadata)
generateBokehPhoto(context, photoId, updatedMetadata, bitmap)
val bokehBitmap = renderAndSaveBokehPhoto(context, photoId, updatedMetadata, bitmap)
val preparedUltraHdrSource = if (updatedMetadata.manualHdrEffectEnabled) {
photoProcessor.prepareUltraHdrSourceFromRawResult(
@@ -3177,7 +3254,8 @@ object GalleryManager {
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
applyMirror = true
applyMirror = true,
preparedSdrBitmap = bokehBitmap,
)
} else {
null
@@ -3231,10 +3309,13 @@ object GalleryManager {
}
}
preparedUltraHdrSource?.sdrBase?.let {
if (it !== bitmap && !it.isRecycled) {
if (it !== bitmap && it !== bokehBitmap && !it.isRecycled) {
it.recycle()
}
}
if (bokehBitmap !== bitmap && !bokehBitmap.isRecycled) {
bokehBitmap.recycle()
}
if (!bitmap.isRecycled) {
bitmap.recycle()
}
@@ -222,6 +222,42 @@ class PhotoProcessor(
return null
}
/**
* Builds the SDR-backed HDR source from an in-memory capture result that has
* already received computational bokeh. This keeps detail-HDR generation and
* export on the same pixels without running the full-resolution bokeh pass again.
*/
suspend fun prepareUltraHdrSourceFromProcessedSdr(
context: Context,
photoId: String,
processedSdr: Bitmap,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
): GainmapSourceSet? {
if (!metadata.manualHdrEffectEnabled) return null
val sdrBase = processBitmap(
context = context,
photoId = photoId,
input = processedSdr,
metadata = metadata,
sharpening = sharpening,
noiseReduction = noiseReduction,
chromaNoiseReduction = chromaNoiseReduction,
useComputationalAperture = false,
applyFrameWatermark = false,
)
return GainmapSourceSet(
sdrBase = sdrBase,
hdrReference = null,
sourceKind = SourceKind.SDR_BITMAP,
confidence = 0.35f,
displayHdrSdrRatio = readDisplayHdrSdrRatio(),
)
}
private fun readDisplayHdrSdrRatio(): Float = GalleryManager.hdrSdrRatio
suspend fun prepareUltraHdrSourceFromRawResult(
@@ -233,6 +269,7 @@ class PhotoProcessor(
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
applyMirror: Boolean = false,
preparedSdrBitmap: Bitmap? = null,
): GainmapSourceSet? = withContext(Dispatchers.IO) {
val displayHdrSdrRatio = readDisplayHdrSdrRatio()
@@ -241,27 +278,32 @@ class PhotoProcessor(
fallbackTarget = BaselineColorCorrectionTarget.RAW
)
var sdrBitmap = rawResult.sdrBitmap
var sdrBitmap = preparedSdrBitmap ?: rawResult.sdrBitmap
var hdrReferenceBitmap = normalizeRawHdrReferenceForGainmap(
rawResult = rawResult,
sdrBitmap = sdrBitmap,
sdrBitmap = rawResult.sdrBitmap,
hdrReferenceBitmap = rawResult.hdrReferenceBitmap
)
if (applyMirror && metadata.isMirrored) {
sdrBitmap = BitmapUtils.flipHorizontal(sdrBitmap)
if (preparedSdrBitmap == null) {
sdrBitmap = BitmapUtils.flipHorizontal(sdrBitmap)
}
hdrReferenceBitmap = hdrReferenceBitmap?.let { BitmapUtils.flipHorizontal(it) }
}
metadata.computationalAperture?.let { aperture ->
sdrBitmap = depthBokehProcessor.applyHighQualityBokeh(
context,
photoId,
sdrBitmap,
metadata.focusPointX,
metadata.focusPointY,
aperture
)
if (preparedSdrBitmap == null) {
sdrBitmap = depthBokehProcessor.applyHighQualityBokeh(
context,
photoId,
sdrBitmap,
metadata.focusPointX,
metadata.focusPointY,
aperture
)
photoId?.let { id -> GalleryManager.saveBokehPhoto(context, id, sdrBitmap) }
}
hdrReferenceBitmap = hdrReferenceBitmap?.let {
depthBokehProcessor.applyHighQualityBokeh(
context,
@@ -272,7 +314,6 @@ class PhotoProcessor(
aperture
)
}
photoId?.let { id -> GalleryManager.saveBokehPhoto(context, id, sdrBitmap) }
}
val lutStackResult = lutImageProcessor.applyLutStackWithLuminanceGain(
@@ -719,6 +719,7 @@ object Shaders {
uniform float uAperture;
uniform float uFocusDepth;
uniform vec2 uTexelSize;
uniform int uLinearInput;
const float PI = 3.14159265359;
const float GOLDEN_ANGLE = 2.39996323;
@@ -844,4 +845,48 @@ object Shaders {
fragColor = vec4(finalColor, centerColor.a);
}
""".trimIndent()
/**
* Full-resolution resolve for the reduced-resolution PSF result. Focused pixels
* come directly from the original texture; only defocused regions consume the
* filtered bokeh texture.
*/
val BOKEH_COMPOSITE_FRAGMENT_SHADER = """
#version 300 es
precision highp float;
in vec2 vTexCoord;
out vec4 fragColor;
uniform sampler2D uOriginalTexture;
uniform sampler2D uBokehTexture;
uniform sampler2D uDepthTexture;
uniform mat4 uDepthMatrix;
uniform float uMaxBlurRadius;
uniform float uAperture;
uniform float uFocusDepth;
float computeCoc(float depth) {
float gap = max(abs(uFocusDepth - depth) - 0.015, 0.0);
float defocus = pow(gap, 1.1);
return clamp(
defocus * uMaxBlurRadius * (1.0 / max(uAperture, 0.45)),
0.0,
uMaxBlurRadius
);
}
void main() {
vec4 originalColor = texture(uOriginalTexture, vTexCoord);
vec3 bokehColor = texture(uBokehTexture, vTexCoord).rgb;
vec2 depthUV = clamp(
(uDepthMatrix * vec4(vTexCoord, 0.0, 1.0)).xy,
0.0,
1.0
);
float coc = computeCoc(texture(uDepthTexture, depthUV).r);
float bokehMix = smoothstep(0.2, 1.2, coc);
fragColor = vec4(mix(originalColor.rgb, bokehColor, bokehMix), originalColor.a);
}
""".trimIndent()
}
@@ -2,6 +2,9 @@ package com.hinnka.mycamera.ml
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import com.hinnka.mycamera.utils.LargeDirectBuffer
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.StartupTrace
@@ -150,6 +153,7 @@ class DepthEstimator(
return null
}
var modelInputBitmap: Bitmap? = null
try {
// 1. Get input/output metadata
val inputTensor = interpreter!!.getInputTensor(0)
@@ -158,13 +162,15 @@ class DepthEstimator(
val outputDataType = outputTensor.dataType()
// 2. Preprocess the input image
val preparedInput = prepareModelInputBitmap(inputBitmap)
modelInputBitmap = preparedInput
val inputUsesLargeDirectAllocator = modelAssetName == MODEL_DEPTH_ANYTHING
val inputBuffer = if (inputUsesLargeDirectAllocator) {
createDepthAnythingInputBuffer(inputBitmap, inputDataType)
createDepthAnythingInputBuffer(preparedInput, inputDataType)
} else {
val imageProcessor = buildImageProcessor()
var tensorImage = TensorImage(inputDataType)
tensorImage.load(inputBitmap)
tensorImage.load(preparedInput)
tensorImage = imageProcessor.process(tensorImage)
tensorImage.buffer
}
@@ -206,6 +212,36 @@ class DepthEstimator(
} catch (e: Exception) {
PLog.e(TAG, "Error during depth estimation: $modelAssetName", e)
return null
} finally {
modelInputBitmap?.let { bitmap ->
if (bitmap !== inputBitmap && !bitmap.isRecycled) {
bitmap.recycle()
}
}
}
}
/**
* Depth models consume a small, display-referred RGB guide. Convert and resize
* in one Canvas draw so RGBA_F16 captures never create a full-resolution
* ARGB_8888 intermediate bitmap.
*/
private fun prepareModelInputBitmap(inputBitmap: Bitmap): Bitmap {
if (
inputBitmap.config == Bitmap.Config.ARGB_8888 &&
inputBitmap.width == inputWidth &&
inputBitmap.height == inputHeight
) {
return inputBitmap
}
return Bitmap.createBitmap(inputWidth, inputHeight, Bitmap.Config.ARGB_8888).also { output ->
Canvas(output).drawBitmap(
inputBitmap,
null,
Rect(0, 0, inputWidth, inputHeight),
Paint(Paint.FILTER_BITMAP_FLAG),
)
}
}
@@ -315,7 +351,7 @@ class DepthEstimator(
val range = max - min
val finalRange = if (range <= 0f) 1f else range // avoid division by zero
PLog.d(TAG, "Depth output range: asset=$modelAssetName min=$min max=$max range=$range valid=$validCount")
// PLog.d(TAG, "Depth output range: asset=$modelAssetName min=$min max=$max range=$range valid=$validCount")
val pixels = IntArray(width * height)
val limit = minOf(outputArray.size, pixels.size)
@@ -53,14 +53,7 @@ class DepthBokehProcessor(context: Context) {
}
if (depthMap == null) {
val depthGuide = ensureArgb8888(originalImage)
depthMap = try {
SharedDepthEstimator.estimateDepth(appContext, depthGuide)
} finally {
if (depthGuide !== originalImage && !depthGuide.isRecycled) {
depthGuide.recycle()
}
}
depthMap = SharedDepthEstimator.estimateDepth(appContext, originalImage)
if (depthMap != null && depthFile != null) {
try {
@@ -97,17 +90,5 @@ class DepthBokehProcessor(context: Context) {
return result ?: originalImage
}
/**
* The depth estimator consumes an 8-bit display-referred guide. The bokeh
* renderer itself receives the original bitmap so a linear RGBA_F16 HDR
* reference keeps both its encoding and values above 1.0.
*/
private fun ensureArgb8888(bitmap: Bitmap): Bitmap {
if (bitmap.config == Bitmap.Config.ARGB_8888) return bitmap
PLog.d(TAG, "Converting bitmap from ${bitmap.config} to ARGB_8888 for bokeh processing (${bitmap.width}x${bitmap.height})")
val converted = bitmap.copy(Bitmap.Config.ARGB_8888, false)
return converted ?: bitmap
}
fun close() = Unit
}
@@ -5,6 +5,7 @@ import android.graphics.ColorSpace
import android.opengl.EGL14
import android.opengl.GLES30
import android.opengl.GLUtils
import android.os.SystemClock
import com.hinnka.mycamera.lut.GlUtils
import com.hinnka.mycamera.lut.Shaders
import com.hinnka.mycamera.utils.LargeDirectBuffer
@@ -13,10 +14,12 @@ import com.hinnka.mycamera.utils.PLog
class OglBokehProcessor {
companion object {
private const val TAG = "OglBokehProcessor"
private const val MAX_BOKEH_RENDER_EDGE = 2560
}
private var uDepthMatrixLoc: Int = 0
private var bokehProgramId = 0
private var bokehCompositeProgramId = 0
private var jbuUpsampleProgramId = 0
private var depthSharpenProgramId = 0
private var vertexBufferId = 0
@@ -34,32 +37,43 @@ class OglBokehProcessor {
focusY: Float,
aperture: Float
): Bitmap? {
val startedAtMs = SystemClock.elapsedRealtime()
try {
val halfFloatOutput = originalImage.config == Bitmap.Config.RGBA_F16
val linearInput = originalImage.colorSpace?.id ==
ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB).id
val (bokehWidth, bokehHeight) = resolveBokehRenderSize(
originalImage.width,
originalImage.height,
)
PLog.d(
TAG,
"Bokeh working resolution: ${bokehWidth}x${bokehHeight}, output=${originalImage.width}x${originalImage.height}"
)
initEGL(originalImage.width, originalImage.height)
initGL()
val inputTex = createTexture(originalImage, mipmap = true)
val lowResDepthTex = createTexture(lowResDepthMap, filterNearest = false, mipmap = false)
val renderStartedAtMs = SystemClock.elapsedRealtime()
val fbo = IntArray(1)
GLES30.glGenFramebuffers(1, fbo, 0)
var highResDepthTex = IntArray(1)
var refinedDepthTex = IntArray(1)
val highResDepthTex = IntArray(1)
val refinedDepthTex = IntArray(1)
// Step 1: JBU Upsample (Generate High-Res Refined Depth)
GLES30.glGenTextures(1, highResDepthTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highResDepthTex[0])
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R8, originalImage.width, originalImage.height, 0, GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, null)
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R8, bokehWidth, bokehHeight, 0, GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, null)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0])
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, highResDepthTex[0], 0)
GLES30.glViewport(0, 0, originalImage.width, originalImage.height)
requireFramebufferComplete("depth upsample")
GLES30.glViewport(0, 0, bokehWidth, bokehHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(jbuUpsampleProgramId)
@@ -78,24 +92,76 @@ class OglBokehProcessor {
// Step 2: Depth Edge Sharpening
GLES30.glGenTextures(1, refinedDepthTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, refinedDepthTex[0])
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R8, originalImage.width, originalImage.height, 0, GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, null)
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R8, bokehWidth, bokehHeight, 0, GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, null)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, refinedDepthTex[0], 0)
requireFramebufferComplete("depth sharpen")
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(depthSharpenProgramId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highResDepthTex[0])
GLES30.glUniform1i(GLES30.glGetUniformLocation(depthSharpenProgramId, "uDepthTexture"), 0)
GLES30.glUniform2f(GLES30.glGetUniformLocation(depthSharpenProgramId, "uTexelSize"), 1.0f / originalImage.width, 1.0f / originalImage.height)
GLES30.glUniform2f(GLES30.glGetUniformLocation(depthSharpenProgramId, "uTexelSize"), 1.0f / bokehWidth, 1.0f / bokehHeight)
drawQuad(depthSharpenProgramId)
val finalDepthTex = refinedDepthTex[0]
// Step 3: Apply Bokeh
// Step 3: Render the expensive PSF at a bounded working resolution.
val bokehTex = IntArray(1)
GLES30.glGenTextures(1, bokehTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bokehTex[0])
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D,
0,
if (halfFloatOutput) GLES30.GL_RGBA16F else GLES30.GL_RGBA8,
bokehWidth,
bokehHeight,
0,
GLES30.GL_RGBA,
if (halfFloatOutput) GLES30.GL_HALF_FLOAT else GLES30.GL_UNSIGNED_BYTE,
null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, bokehTex[0], 0)
requireFramebufferComplete("PSF bokeh")
GLES30.glViewport(0, 0, bokehWidth, bokehHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(bokehProgramId)
val focusDepth = sampleDepth(lowResDepthMap, focusX, focusY)
val maxBlurRadius = originalImage.width.toFloat() / 45.0f
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius"), maxBlurRadius)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uAperture"), aperture)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uFocusDepth"), focusDepth)
GLES30.glUniform2f(GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize"), 1.0f / originalImage.width, 1.0f / originalImage.height)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bokehProgramId, "uLinearInput"),
if (linearInput) 1 else 0
)
val identity = FloatArray(16)
android.opengl.Matrix.setIdentityM(identity, 0)
GLES30.glUniformMatrix4fv(GLES30.glGetUniformLocation(bokehProgramId, "uDepthMatrix"), 1, false, identity, 0)
drawQuad(bokehProgramId)
// Step 4: Resolve at full resolution. In-focus detail is sampled directly
// from the original image, while defocused regions use the PSF texture.
val outputTex = IntArray(1)
GLES30.glGenTextures(1, outputTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, outputTex[0])
@@ -112,36 +178,44 @@ class OglBokehProcessor {
)
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.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, outputTex[0], 0)
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER,
GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D,
outputTex[0],
0
)
requireFramebufferComplete("full-resolution bokeh composite")
GLES30.glViewport(0, 0, originalImage.width, originalImage.height)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(bokehProgramId)
val focusDepth = sampleDepth(lowResDepthMap, focusX, focusY)
GLES30.glUseProgram(bokehCompositeProgramId)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uInputTexture"), 0)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uOriginalTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bokehTex[0])
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uBokehTexture"), 1)
GLES30.glActiveTexture(GLES30.GL_TEXTURE2)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius"), originalImage.width.toFloat() / 45.0f)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uAperture"), aperture)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uFocusDepth"), focusDepth)
GLES30.glUniform2f(GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize"), 1.0f / originalImage.width, 1.0f / originalImage.height)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(bokehProgramId, "uLinearInput"),
if (linearInput) 1 else 0
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uDepthTexture"), 2)
GLES30.glUniformMatrix4fv(
GLES30.glGetUniformLocation(bokehCompositeProgramId, "uDepthMatrix"),
1,
false,
identity,
0
)
GLES30.glUniform1f(
GLES30.glGetUniformLocation(bokehCompositeProgramId, "uMaxBlurRadius"),
maxBlurRadius
)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uAperture"), aperture)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehCompositeProgramId, "uFocusDepth"), focusDepth)
val identity = FloatArray(16)
android.opengl.Matrix.setIdentityM(identity, 0)
GLES30.glUniformMatrix4fv(GLES30.glGetUniformLocation(bokehProgramId, "uDepthMatrix"), 1, false, identity, 0)
drawQuad(bokehProgramId)
drawQuad(bokehCompositeProgramId)
GLES30.glFinish()
val renderFinishedAtMs = SystemClock.elapsedRealtime()
// Read back to Bitmap
val resultBitmap = Bitmap.createBitmap(originalImage.width, originalImage.height,
@@ -165,15 +239,25 @@ class OglBokehProcessor {
} finally {
LargeDirectBuffer.free(buffer)
}
val readbackFinishedAtMs = SystemClock.elapsedRealtime()
// Clean up
GLES30.glDeleteTextures(1, intArrayOf(inputTex), 0)
GLES30.glDeleteTextures(1, intArrayOf(lowResDepthTex), 0)
GLES30.glDeleteTextures(1, highResDepthTex, 0)
GLES30.glDeleteTextures(1, refinedDepthTex, 0)
GLES30.glDeleteTextures(1, bokehTex, 0)
GLES30.glDeleteTextures(1, outputTex, 0)
GLES30.glDeleteFramebuffers(1, fbo, 0)
PLog.d(
TAG,
"Bokeh completed: total=${readbackFinishedAtMs - startedAtMs}ms, " +
"setupUpload=${renderStartedAtMs - startedAtMs}ms, " +
"render=${renderFinishedAtMs - renderStartedAtMs}ms, " +
"readback=${readbackFinishedAtMs - renderFinishedAtMs}ms, " +
"working=${bokehWidth}x${bokehHeight}, output=${originalImage.width}x${originalImage.height}"
)
return resultBitmap
} catch (e: Exception) {
PLog.e(TAG, "Error applying OGL Bokeh: ${e.message}")
@@ -205,6 +289,25 @@ class OglBokehProcessor {
return samples[samples.size / 2]
}
private fun resolveBokehRenderSize(width: Int, height: Int): Pair<Int, Int> {
val maxEdge = maxOf(width, height)
if (maxEdge <= MAX_BOKEH_RENDER_EDGE) return width to height
return if (width >= height) {
MAX_BOKEH_RENDER_EDGE to
(height.toLong() * MAX_BOKEH_RENDER_EDGE / width).toInt().coerceAtLeast(1)
} else {
(width.toLong() * MAX_BOKEH_RENDER_EDGE / height).toInt().coerceAtLeast(1) to
MAX_BOKEH_RENDER_EDGE
}
}
private fun requireFramebufferComplete(label: String) {
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
check(status == GLES30.GL_FRAMEBUFFER_COMPLETE) {
"$label framebuffer incomplete: 0x${status.toString(16)}"
}
}
private fun createTexture(bitmap: Bitmap, filterNearest: Boolean = false, mipmap: Boolean = false): Int {
val tex = IntArray(1)
GLES30.glGenTextures(1, tex, 0)
@@ -280,19 +383,19 @@ class OglBokehProcessor {
private fun initGL() {
val vs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER)
val fs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.PSF_SPLAT_FRAGMENT_SHADER)
bokehProgramId = GlUtils.linkProgram(vs, fs)
val jbuFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.JBU_UPSAMPLE_FRAGMENT_SHADER)
jbuUpsampleProgramId = GlUtils.linkProgram(vs, jbuFs)
val sharpenFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.DEPTH_SHARPEN_FRAGMENT_SHADER)
depthSharpenProgramId = GlUtils.linkProgram(vs, sharpenFs)
GLES30.glDeleteShader(vs)
GLES30.glDeleteShader(fs)
GLES30.glDeleteShader(jbuFs)
GLES30.glDeleteShader(sharpenFs)
check(vs != 0) { "Bokeh vertex shader compilation failed" }
try {
bokehProgramId = createProgram(vs, Shaders.PSF_SPLAT_FRAGMENT_SHADER, "PSF bokeh")
bokehCompositeProgramId = createProgram(
vs,
Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER,
"bokeh composite",
)
jbuUpsampleProgramId = createProgram(vs, Shaders.JBU_UPSAMPLE_FRAGMENT_SHADER, "depth upsample")
depthSharpenProgramId = createProgram(vs, Shaders.DEPTH_SHARPEN_FRAGMENT_SHADER, "depth sharpen")
} finally {
GLES30.glDeleteShader(vs)
}
vertexBufferId = GlUtils.createBuffer(Shaders.FULL_QUAD_VERTICES)
texCoordBufferId = GlUtils.createBuffer(Shaders.TEXTURE_COORDS)
@@ -310,6 +413,18 @@ class OglBokehProcessor {
GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0)
}
private fun createProgram(vertexShader: Int, fragmentSource: String, label: String): Int {
val fragmentShader = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource)
check(fragmentShader != 0) { "$label fragment shader compilation failed" }
return try {
GlUtils.linkProgram(vertexShader, fragmentShader).also { program ->
check(program != 0) { "$label program linking failed" }
}
} finally {
GLES30.glDeleteShader(fragmentShader)
}
}
private fun drawQuad(program: Int) {
GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId)
val posLoc = GLES30.glGetAttribLocation(program, "aPosition")
@@ -330,6 +445,7 @@ class OglBokehProcessor {
private fun releaseGL() {
if (bokehProgramId != 0) GLES30.glDeleteProgram(bokehProgramId)
if (bokehCompositeProgramId != 0) GLES30.glDeleteProgram(bokehCompositeProgramId)
if (jbuUpsampleProgramId != 0) GLES30.glDeleteProgram(jbuUpsampleProgramId)
if (depthSharpenProgramId != 0) GLES30.glDeleteProgram(depthSharpenProgramId)
if (vertexBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(vertexBufferId), 0)
@@ -345,5 +461,12 @@ class OglBokehProcessor {
eglDisplay = EGL14.EGL_NO_DISPLAY
eglContext = EGL14.EGL_NO_CONTEXT
eglSurface = EGL14.EGL_NO_SURFACE
bokehProgramId = 0
bokehCompositeProgramId = 0
jbuUpsampleProgramId = 0
depthSharpenProgramId = 0
vertexBufferId = 0
texCoordBufferId = 0
indexBufferId = 0
}
}
@@ -0,0 +1,100 @@
package com.hinnka.mycamera.lut
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
class BokehShadersTest {
@Test
fun offlineBokehDeclaresEveryUniformRequiredByItsRenderer() {
val shader = Shaders.PSF_SPLAT_FRAGMENT_SHADER
val expectedUniforms = listOf(
"uInputTexture",
"uDepthTexture",
"uDepthMatrix",
"uMaxBlurRadius",
"uAperture",
"uFocusDepth",
"uTexelSize",
"uLinearInput",
)
expectedUniforms.forEach { uniform ->
assertTrue(
"$uniform must be declared by the offline bokeh shader",
Regex("""uniform\s+\w+\s+$uniform\s*;""").containsMatchIn(shader),
)
}
}
@Test
fun bokehCompositeDeclaresEveryUniformRequiredByItsRenderer() {
val shader = Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER
val expectedUniforms = listOf(
"uOriginalTexture",
"uBokehTexture",
"uDepthTexture",
"uDepthMatrix",
"uMaxBlurRadius",
"uAperture",
"uFocusDepth",
)
expectedUniforms.forEach { uniform ->
assertTrue(
"$uniform must be declared by the bokeh composite shader",
Regex("""uniform\s+\w+\s+$uniform\s*;""").containsMatchIn(shader),
)
}
}
@Test
fun offlineBokehPassesAvailableNdkShaderValidator() {
val sdkRoot = System.getenv("ANDROID_SDK_ROOT") ?: System.getenv("ANDROID_HOME")
val validator = sdkRoot?.let(::File)
?.resolve("ndk")
?.listFiles()
?.sortedByDescending { it.name }
?.asSequence()
?.mapNotNull { ndk ->
ndk.resolve("shader-tools")
.walkTopDown()
.firstOrNull { it.name == "glslc" && it.canExecute() }
}
?.firstOrNull()
assumeTrue("Android NDK glslc is unavailable", validator != null)
val shaders = listOf(
Shaders.PSF_SPLAT_FRAGMENT_SHADER,
Shaders.BOKEH_COMPOSITE_FRAGMENT_SHADER,
)
shaders.forEachIndexed { index, shader ->
val sourceFile = File.createTempFile("offline-bokeh-$index-", ".frag")
val outputFile = File.createTempFile("offline-bokeh-$index-", ".spv")
try {
// glslc emits SPIR-V and therefore requires GLSL ES 3.10 or newer.
// Only the validator copy needs the higher version; the production
// shader remains GLSL ES 3.00 for the app's OpenGL ES 3.0 renderer.
sourceFile.writeText(shader.replaceFirst("#version 300 es", "#version 310 es"))
val process = ProcessBuilder(
checkNotNull(validator).absolutePath,
"--target-env=opengl",
"-fauto-map-locations",
"-fauto-bind-uniforms",
"-fshader-stage=frag",
sourceFile.absolutePath,
"-o",
outputFile.absolutePath,
).redirectErrorStream(true).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
assertEquals("shader $index: $output", 0, process.waitFor())
} finally {
sourceFile.delete()
outputFile.delete()
}
}
}
}