diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a6b8f626..95812ae9 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -140,4 +140,10 @@ dependencies { androidTestImplementation(libs.androidx.ui.test.junit4) debugImplementation(libs.androidx.ui.tooling) debugImplementation(libs.androidx.ui.test.manifest) + + // TensorFlow Lite for Depth Estimator + implementation("org.tensorflow:tensorflow-lite:2.16.1") + implementation("org.tensorflow:tensorflow-lite-gpu:2.16.1") + implementation("org.tensorflow:tensorflow-lite-gpu-api:2.16.1") + implementation("org.tensorflow:tensorflow-lite-support:0.4.4") } \ No newline at end of file diff --git a/app/src/androidTest/java/com/hinnka/mycamera/ml/DepthEstimatorTest.kt b/app/src/androidTest/java/com/hinnka/mycamera/ml/DepthEstimatorTest.kt new file mode 100644 index 00000000..756c2238 --- /dev/null +++ b/app/src/androidTest/java/com/hinnka/mycamera/ml/DepthEstimatorTest.kt @@ -0,0 +1,41 @@ +package com.hinnka.mycamera.ml + +import android.graphics.Bitmap +import android.graphics.Color +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class DepthEstimatorTest { + + @Test + fun testDepthEstimatorInitializationAndInference() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + + // This test requires the midas_v2_w8a8.tflite model to be present in the assets folder. + // If it's not present, the initialization should fail gracefully (catch block in init). + val estimator = DepthEstimator(context) + + // Generate a dummy 640x480 bitmap + val testBitmap = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888) + testBitmap.eraseColor(Color.GRAY) + + val depthMap = estimator.estimateDepth(testBitmap) + + // Since we don't have the model file in the automated environment, + // depthMap will likely be null. If the user places the model in assets/, + // this test should pass and return a 256x256 bitmap. + if (depthMap != null) { + assertEquals(256, depthMap.width) + assertEquals(256, depthMap.height) + assertNotNull(depthMap) + } else { + println("Model file not found. Please place midas_v2_w8a8.tflite in src/main/assets/ to fully run this test.") + } + + estimator.close() + } +} diff --git a/app/src/main/assets/midas.tflite b/app/src/main/assets/midas.tflite new file mode 100644 index 00000000..48acfd48 Binary files /dev/null and b/app/src/main/assets/midas.tflite differ diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index 58a95088..010ca0dd 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -82,6 +82,9 @@ class Camera2Controller(private val context: Context) { private var previewSurface: Surface? = null private var imageReader: ImageReader? = null + val previewDepthProcessor = com.hinnka.mycamera.preview.PreviewDepthProcessor(context) + + // 降噪等级 (0=Off, 1=Fast, 2=High Quality, 3=Real-time) private var nrLevel = 1 @@ -225,7 +228,7 @@ class Camera2Controller(private val context: Context) { shutterSpeed = if (isAutoExposure) actualExposureTimeNs ?: _state.value.shutterSpeed else _state.value.shutterSpeed, awbMode = awbMode, - aperture = aperture ?: _state.value.aperture, + physicalAperture = aperture ?: _state.value.physicalAperture, ) } } @@ -564,14 +567,16 @@ class Camera2Controller(private val context: Context) { } } else { PLog.w(TAG, "acquireNextImage() returned null, resetting capture state") - _state.value = _state.value.copy(isCapturing = false) - resetPreviewAfterCapture() - } - } catch (e: Exception) { - PLog.e(TAG, "Error in onImageAvailable", e) + _state.value = _state.value.copy(isCapturing = false) + resetPreviewAfterCapture() } - }, cameraHandler) - } + } catch (e: Exception) { + PLog.e(TAG, "Error in onImageAvailable", e) + } + }, cameraHandler) + } + + PLog.d(TAG, "Opening camera: $cameraId") @@ -752,9 +757,6 @@ class Camera2Controller(private val context: Context) { } } - /** - * 创建预览会话 - */ private fun createPreviewSession() { val device = cameraDevice ?: return val surface = previewSurface ?: return @@ -775,6 +777,7 @@ class Camera2Controller(private val context: Context) { val surfaces = mutableListOf(surface, reader.surface) + // Android 9+ 使用 SessionConfiguration val outputConfigs = surfaces.map { OutputConfiguration(it) } val sessionConfig = SessionConfiguration( @@ -1114,6 +1117,22 @@ class Camera2Controller(private val context: Context) { PLog.d(TAG, "RAW 格式拍照: $enabled") } + /** + * 设置虚化模拟光圈大小 + */ + fun setAperture(value: Float) { + _state.value = _state.value.copy(virtualAperture = value) + PLog.d(TAG, "设置虚拟光圈: $value") + } + + /** + * 启用/禁用虚拟光圈控制 + */ + fun setVirtualApertureEnabled(enabled: Boolean) { + _state.value = _state.value.copy(isVirtualApertureEnabled = enabled) + PLog.d(TAG, "虚拟光圈开关: $enabled") + } + /** * 获取当前摄像头 ID */ @@ -2100,7 +2119,7 @@ class Camera2Controller(private val context: Context) { val characteristics = cachedCharacteristics ?: return try { // 计算光照等级 (LV) - val aperture = _state.value.aperture.toDouble() + val aperture = _state.value.physicalAperture.toDouble() val shutterSpeed = _state.value.shutterSpeed.toDouble() / 1_000_000_000.0 val iso = _state.value.iso.toDouble() val ev = ln(aperture * aperture / shutterSpeed) / ln(2.0) diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index 7914f5c5..9de2db5c 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -129,8 +129,9 @@ data class CameraState( val awbMode: Int = 1, // 自动白平衡模式 val awbTemperature: Int = 5000, // 色温 (K) - val aperture: Float = 2.0f, // 光圈值 (f-number) - + val isVirtualApertureEnabled: Boolean = false, + val physicalAperture: Float = 2.0f, // 物理光圈值 + val virtualAperture: Float = 2.0f, // 虚拟光圈值 (f-number) // 对焦 val isAutoFocus: Boolean = true, val focusPoint: Pair? = null, // normalized coordinates (0-1) diff --git a/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt index fa799e83..2b90f3f3 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/ContentRepository.kt @@ -9,6 +9,7 @@ import com.hinnka.mycamera.gallery.PhotoProcessor import com.hinnka.mycamera.lut.LutImageProcessor import com.hinnka.mycamera.lut.LutInfo import com.hinnka.mycamera.lut.LutManager +import com.hinnka.mycamera.processor.DepthBokehProcessor import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -52,11 +53,14 @@ class ContentRepository private constructor(context: Context) { // 边框渲染器 val frameRenderer = FrameRenderer(appContext) + val depthBokehProcessor = DepthBokehProcessor(appContext) + val photoProcessor = PhotoProcessor( lutManager, imageProcessor, frameManager, - frameRenderer + frameRenderer, + depthBokehProcessor ) // 用户偏好设置仓库 diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt index f90f37d8..434e8e62 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt @@ -15,10 +15,7 @@ import androidx.core.graphics.createBitmap import androidx.exifinterface.media.ExifInterface import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.data.ContentRepository -import com.hinnka.mycamera.phantom.PhantomService -import com.hinnka.mycamera.livephoto.GoogleLivePhotoCreator import com.hinnka.mycamera.livephoto.MotionPhotoWriter -import com.hinnka.mycamera.livephoto.VivoLivePhotoCreator import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.processor.MultiFrameStacker import com.hinnka.mycamera.raw.MeteringSystem @@ -53,6 +50,7 @@ object PhotoManager { private const val DNG_FILE = "original.dng" private const val METADATA_FILE = "metadata.json" private const val THUMBNAIL_FILE = "thumbnail.jpg" + private const val BOKEH_FILE = "bokeh.jpg" val processingScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) @@ -84,10 +82,18 @@ object PhotoManager { return File(getPhotoDir(context, photoId), METADATA_FILE) } + fun getDepthFile(context: Context, photoId: String): File { + return File(getPhotoDir(context, photoId), "depthmap.png") + } + fun getThumbnailFile(context: Context, photoId: String): File { return File(getPhotoDir(context, photoId), THUMBNAIL_FILE) } + fun getBokehFile(context: Context, photoId: String): File { + return File(getPhotoDir(context, photoId), BOKEH_FILE) + } + fun getVideoFile(context: Context, photoId: String): File { return File(getPhotoDir(context, photoId), VIDEO_FILE) } @@ -110,7 +116,7 @@ object PhotoManager { // 读取照片 val processedBitmap = bitmap?.let { photoProcessor.processBitmap( - bitmap, metadata, + context, id, bitmap, metadata, sharpeningValue, noiseReductionValue, chromaNoiseReductionValue ) } ?: photoProcessor.process( @@ -374,6 +380,14 @@ object PhotoManager { } } + suspend fun saveBokehPhoto(context: Context, photoId: String, bitmap: Bitmap) = withContext(Dispatchers.IO) { + val photoDir = getPhotoDir(context, photoId, true) + val bokehFile = File(photoDir, BOKEH_FILE) + FileOutputStream(bokehFile).use { outputStream -> + bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream) + } + } + suspend fun saveYuvPhoto( context: Context, photoId: String, @@ -1216,6 +1230,18 @@ object PhotoManager { } fun loadBitmap(context: Context, photoId: String, maxEdge: Int? = null): Bitmap? { + val photoFile = getPhotoFile(context, photoId) + val bokehFile = getBokehFile(context, photoId) + if (!photoFile.exists()) { + return null + } + if (bokehFile.exists()) { + return loadBitmap(context, Uri.fromFile(bokehFile), maxEdge) + } + return loadBitmap(context, Uri.fromFile(photoFile), maxEdge) + } + + fun loadOriginalBitmap(context: Context, photoId: String, maxEdge: Int? = null): Bitmap? { val photoFile = getPhotoFile(context, photoId) if (!photoFile.exists()) { return null diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt index c1e7981b..0186bdec 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoMetadata.kt @@ -58,6 +58,10 @@ data class PhotoMetadata( val customProperties: Map = emptyMap(), // 导出到系统相册的 URI 列表 val exportedUris: List = emptyList(), + // 计算摄影光圈与焦点 + val computationalAperture: Float? = null, + val focusPointX: Float? = null, + val focusPointY: Float? = null, // Live Photo 演示时间戳 (us) val presentationTimestampUs: Long? = null, // DRO 模式 @@ -192,6 +196,12 @@ data class PhotoMetadata( put("customProperties", customPropsObj) // 导出的 URI 列表 put("exportedUris", org.json.JSONArray(exportedUris)) + + // 计算摄影光圈与焦点 + put("computationalAperture", computationalAperture?.toDouble() ?: JSONObject.NULL) + put("focusPointX", focusPointX?.toDouble() ?: JSONObject.NULL) + put("focusPointY", focusPointY?.toDouble() ?: JSONObject.NULL) + // Live Photo 时间戳 put("presentationTimestampUs", presentationTimestampUs ?: JSONObject.NULL) // DRO 模式 @@ -290,6 +300,9 @@ data class PhotoMetadata( } }, exportedUris = exportedUris, + computationalAperture = if (obj.isNull("computationalAperture")) null else obj.optDouble("computationalAperture").toFloat(), + focusPointX = if (obj.isNull("focusPointX")) null else obj.optDouble("focusPointX").toFloat(), + focusPointY = if (obj.isNull("focusPointY")) null else obj.optDouble("focusPointY").toFloat(), presentationTimestampUs = if (obj.isNull("presentationTimestampUs")) null else obj.optLong("presentationTimestampUs"), droMode = if (obj.isNull("droMode")) null else obj.optString("droMode"), software = if (obj.isNull("software")) null else obj.optString("software"), diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index 1a791f83..79e574c8 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -10,7 +10,9 @@ import com.hinnka.mycamera.frame.FrameManager import com.hinnka.mycamera.frame.FrameRenderer import com.hinnka.mycamera.lut.LutImageProcessor import com.hinnka.mycamera.lut.LutManager +import com.hinnka.mycamera.processor.DepthBokehProcessor import com.hinnka.mycamera.raw.RawDemosaicProcessor +import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.utils.YuvProcessor import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -25,7 +27,8 @@ class PhotoProcessor( private val lutManager: LutManager, private val lutImageProcessor: LutImageProcessor, private val frameManager: FrameManager, - private val frameRenderer: FrameRenderer + private val frameRenderer: FrameRenderer, + private val depthBokehProcessor: DepthBokehProcessor, ) { suspend fun process(context: Context, photoId: String, metadata: PhotoMetadata, @@ -39,6 +42,7 @@ class PhotoProcessor( if (dngFile.exists()) { return processDng( context, + photoId, dngFile.absolutePath, metadata, sharpening, @@ -48,6 +52,8 @@ class PhotoProcessor( } else if (yuvFile.exists()) { val data = PhotoManager.loadYuvData(context, photoId) ?: return null return processYuv( + context, + photoId, data, metadata, sharpening, @@ -57,6 +63,8 @@ class PhotoProcessor( } else if (photoFile.exists()) { val bitmap = BitmapFactory.decodeFile(photoFile.absolutePath) ?: return null return processBitmap( + context, + photoId, bitmap, metadata, sharpening, @@ -77,6 +85,7 @@ class PhotoProcessor( */ suspend fun processDng( context: Context, + photoId: String?, dngPath: String, metadata: PhotoMetadata, sharpening: Float = 0f, @@ -106,8 +115,16 @@ class PhotoProcessor( ) result = bitmap?.let { + var b = it + + metadata.computationalAperture?.let { aperture -> + b = depthBokehProcessor.applyHighQualityBokeh(context, photoId, b, + metadata.focusPointX, metadata.focusPointY, aperture) + photoId?.let { photoId -> PhotoManager.saveBokehPhoto(context, photoId, b) } + } + lutImageProcessor.applyLut( - bitmap, + b, lutConfig, colorRecipeParams, finalSharpening, @@ -132,13 +149,14 @@ class PhotoProcessor( * @return 处理后的 Bitmap */ suspend fun processYuv( + context: Context, + photoId: String?, input: ByteBuffer, metadata: PhotoMetadata, sharpening: Float = 0f, noiseReduction: Float = 0f, chromaNoiseReduction: Float = 0f ): Bitmap = withContext(Dispatchers.IO) { - var result: Bitmap? = null // 优先从元数据中获取软件处理参数 // 智能回退:如果是导入的照片且元数据中没存过,则默认值为 0,不应用额外处理 @@ -150,7 +168,7 @@ class PhotoProcessor( val colorRecipeParams = metadata.lutId?.let { lutManager.loadColorRecipeParams(it) } // 1. 应用 LUT - result = lutImageProcessor.applyLut( + var result = lutImageProcessor.applyLut( input.asShortBuffer(), metadata.width, metadata.height, @@ -163,6 +181,12 @@ class PhotoProcessor( ) YuvProcessor.free(input) + metadata.computationalAperture?.let { aperture -> + result = depthBokehProcessor.applyHighQualityBokeh(context, photoId, result, + metadata.focusPointX, metadata.focusPointY, aperture) + photoId?.let { photoId -> PhotoManager.saveBokehPhoto(context, photoId, result) } + } + result = applyFrame(result, metadata) result @@ -177,11 +201,14 @@ class PhotoProcessor( * @return 处理后的 Bitmap */ suspend fun processBitmap( + context: Context, + photoId: String?, input: Bitmap, metadata: PhotoMetadata, sharpening: Float = 0f, noiseReduction: Float = 0f, - chromaNoiseReduction: Float = 0f + chromaNoiseReduction: Float = 0f, + useComputationalAperture: Boolean = false, ): Bitmap = withContext(Dispatchers.IO) { var result = input @@ -204,6 +231,14 @@ class PhotoProcessor( finalChromaNoiseReduction ) + if (useComputationalAperture) { + metadata.computationalAperture?.let { aperture -> + result = depthBokehProcessor.applyHighQualityBokeh(context, photoId, result, + metadata.focusPointX, metadata.focusPointY, aperture) + photoId?.let { photoId -> PhotoManager.saveBokehPhoto(context, photoId, result) } + } + } + result = applyFrame(result, metadata) result 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 c4bbc2a1..2bc51f91 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -58,6 +58,15 @@ class LutRenderer : GLSurfaceView.Renderer { private var uPassCameraTextureLocation: Int = 0 private var aPassPositionLocation: Int = 0 private var aPassTexCoordLocation: Int = 0 + + // 深度估计输入采集 + private var depthInputFboId: Int = 0 + private var depthInputTextureId: Int = 0 + private var depthInputPboId: Int = 0 + private val DEPTH_INPUT_SIZE = 256 + private val depthInputBuffer = ByteBuffer.allocateDirect(DEPTH_INPUT_SIZE * DEPTH_INPUT_SIZE * 4) + private var lastRunDepthInputTime: Long = 0 + var onDepthInputAvailable: ((Bitmap) -> Unit)? = null // FBO 相关 private var fboId: Int = 0 @@ -102,6 +111,8 @@ class LutRenderer : GLSurfaceView.Renderer { private var uLowResLocation: Int = 0 private var uAspectRatioLocation: Int = 0 private var uSTMatrixFragLocation: Int = 0 + private var uApertureLocation: Int = 0 + private var uFocusPointLocation: Int = 0 // HDF 实时预览资源 private var hdfExtractBlurHProgram: Int = 0 @@ -111,6 +122,27 @@ class LutRenderer : GLSurfaceView.Renderer { private var hdfFboId = IntArray(2) private var hdfWidth: Int = 0 private var hdfHeight: Int = 0 + + // Bokeh 实时预览资源 + private var bokehProgramId: Int = 0 + private var uBokehInputTexLoc: Int = 0 + private var uBokehDepthTexLoc: Int = 0 + private var uBokehMaxBlurRadiusLoc: Int = 0 + private var uBokehApertureLoc: Int = 0 + private var uBokehFocusDepthLoc: Int = 0 + private var uBokehTexelSizeLoc: Int = 0 + private var aBokehPositionLoc: Int = 0 + private var aBokehTexCoordLoc: Int = 0 + + private var depthTextureId: Int = 0 + @Volatile + var depthMap: Bitmap? = null + private var lastDepthMap: Bitmap? = null + private var bokehFboId: Int = 0 + private var bokehTextureId: Int = 0 + private var bokehFboWidth: Int = 0 + private var bokehFboHeight: Int = 0 + private var bokehRenderScale: Float = 0.5f // 降采样比例,0.5 代表 1/4 像素量 // Attribute 位置 private var aPositionLocation: Int = 0 @@ -152,6 +184,9 @@ class LutRenderer : GLSurfaceView.Renderer { @Volatile var focusPoint: PointF? = null + @Volatile + var aperture: Float = 0f + @Volatile var meteringEnabled: Boolean = true @@ -299,8 +334,10 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glViewport(0, 0, width, height) - // 初始化 FBO initFbo(width, height) + initBokehFbo(width, height) + initMeteringFbo() + initDepthInputFbo() // 更新 MVP 矩阵以处理 center crop updateMVPMatrix() @@ -365,16 +402,28 @@ class LutRenderer : GLSurfaceView.Renderer { val recorder = livePhotoRecorder val hdfEnabled = halation > 0.001f - val needsFbo = (recorder != null || hdfEnabled) && fboId != 0 && fboTextureId != 0 + val bokehNeeded = aperture > 0f && depthMap != null + val needsFbo = (recorder != null || hdfEnabled || bokehNeeded) && fboId != 0 && fboTextureId != 0 if (needsFbo) { // 1. 渲染主着色器到 FBO (色彩配方 + LUT + CA) drawInternal(fboId, viewportWidth, viewportHeight) - // 2. HDF 多 Pass 处理 - var outputTexId = fboTextureId + // 深度采集(按需,从刚刚渲染好的 FBO 纹理读取) + if (aperture > 0f) { + runDepthInputCaptureInternal(fboTextureId) + } + + // 2. Bokeh 处理 + var currentTexId = fboTextureId + if (bokehNeeded) { + currentTexId = renderBokehPreview(fboTextureId, viewportWidth, viewportHeight) + } + + // 3. HDF 多 Pass 处理 + var outputTexId = currentTexId if (hdfEnabled) { - renderHdfPreviewBlur(fboTextureId, viewportWidth, viewportHeight) + renderHdfPreviewBlur(currentTexId, viewportWidth, viewportHeight) } // 确保 FBO 内容已刷入显存 @@ -408,9 +457,9 @@ class LutRenderer : GLSurfaceView.Renderer { // 4. 显示到屏幕 if (hdfEnabled) { - drawHdfComposite(0, viewportWidth, viewportHeight) + drawHdfComposite(0, viewportWidth, viewportHeight, currentTexId) } else { - drawFboToScreen(0, viewportWidth, viewportHeight) + drawFboToScreen(0, viewportWidth, viewportHeight, currentTexId) } } else { // 直接渲染到屏幕 @@ -421,7 +470,7 @@ class LutRenderer : GLSurfaceView.Renderer { /** * 将 FBO 纹理绘制到屏幕 (Copy Shader) */ - private fun drawFboToScreen(fboId: Int, width: Int, height: Int) { + private fun drawFboToScreen(fboId: Int, width: Int, height: Int, sourceTextureId: Int) { GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fboId) GLES30.glViewport(0, 0, width, height) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) @@ -429,7 +478,7 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glUseProgram(copyProgramId) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, fboTextureId) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) GLES30.glUniform1i(uCopyTextureLoc, 0) // FBO 纹理已经是正向的 (经过 stMatrix/MVP 处理后),所以这里可能不需要再变换 @@ -529,7 +578,10 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glUniform1f(uAspectRatioLocation, viewportWidth.toFloat() / Math.max(1, viewportHeight).toFloat()) } - // 色散效果独立于色彩配方,始终更新 + // 虚化预览和色散效果始终更新(如果启用) + GLES30.glUniform1f(uApertureLocation, aperture) + val fp = focusPoint ?: PointF(0.5f, 0.5f) + GLES30.glUniform2f(uFocusPointLocation, fp.x, 1.0f - fp.y) // Y-flip to match texture coords GLES30.glUniform1f(uChromaticAberrationLocation, chromaticAberration) // 绑定顶点缓冲 @@ -639,11 +691,30 @@ class LutRenderer : GLSurfaceView.Renderer { uLowResLocation = GLES30.glGetUniformLocation(programId, "uLowRes") uAspectRatioLocation = GLES30.glGetUniformLocation(programId, "uAspectRatio") uSTMatrixFragLocation = GLES30.glGetUniformLocation(programId, "uSTMatrix") + uApertureLocation = GLES30.glGetUniformLocation(programId, "uAperture") + uFocusPointLocation = GLES30.glGetUniformLocation(programId, "uFocusPoint") // Attribute 位置 aPositionLocation = GLES30.glGetAttribLocation(programId, "aPosition") aTexCoordLocation = GLES30.glGetAttribLocation(programId, "aTexCoord") + // === 初始化 Passthrough Shader (用于深度采集) === + if (passthroughProgramId == 0) { + val passVs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.VERTEX_SHADER) + val passFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FRAGMENT_SHADER_PASSTHROUGH) + passthroughProgramId = GlUtils.linkProgram(passVs, passFs) + GLES30.glDeleteShader(passVs) + GLES30.glDeleteShader(passFs) + + if (passthroughProgramId != 0) { + uPassMVPMatrixLocation = GLES30.glGetUniformLocation(passthroughProgramId, "uMVPMatrix") + uPassSTMatrixLocation = GLES30.glGetUniformLocation(passthroughProgramId, "uSTMatrix") + uPassCameraTextureLocation = GLES30.glGetUniformLocation(passthroughProgramId, "uCameraTexture") + aPassPositionLocation = GLES30.glGetAttribLocation(passthroughProgramId, "aPosition") + aPassTexCoordLocation = GLES30.glGetAttribLocation(passthroughProgramId, "aTexCoord") + } + } + // === 初始化 Copy Shader (用于 FBO 上屏) === val copyVs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.VERTEX_SHADER) val copyFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FRAGMENT_SHADER_COPY_2D) @@ -663,6 +734,9 @@ class LutRenderer : GLSurfaceView.Renderer { // PLog.d(TAG, "Shader program created: $programId") // === 初始化 HDF 实时预览着色器 === initHdfPrograms() + + // === 初始化 Bokeh 实时预览着色器 === + initBokehProgram() } private fun initHdfPrograms() { @@ -758,14 +832,14 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) } - private fun drawHdfComposite(targetFboId: Int, width: Int, height: Int) { + private fun drawHdfComposite(targetFboId: Int, width: Int, height: Int, sourceTextureId: Int) { if (hdfCompositeProgram == 0) return GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId) GLES30.glViewport(0, 0, width, height) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(hdfCompositeProgram) GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, fboTextureId) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(hdfCompositeProgram, "uOriginalTexture"), 0) GLES30.glActiveTexture(GLES30.GL_TEXTURE1) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdfTexId[1]) @@ -856,6 +930,34 @@ class LutRenderer : GLSurfaceView.Renderer { GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) } + private fun initDepthInputFbo() { + if (depthInputFboId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(depthInputFboId), 0) + depthInputFboId = 0 + } + if (depthInputTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(depthInputTextureId), 0) + depthInputTextureId = 0 + } + + val fbos = IntArray(1) + GLES30.glGenFramebuffers(1, fbos, 0) + depthInputFboId = fbos[0] + + val textures = IntArray(1) + GLES30.glGenTextures(1, textures, 0) + depthInputTextureId = textures[0] + + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthInputTextureId) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, DEPTH_INPUT_SIZE, DEPTH_INPUT_SIZE, 0, GLES30.GL_RGBA, 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, depthInputFboId) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, depthInputTextureId, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + } + private fun initCaptureFbo() { if (captureFboId != 0) { GLES30.glDeleteFramebuffers(1, intArrayOf(captureFboId), 0) @@ -1312,6 +1414,79 @@ class LutRenderer : GLSurfaceView.Renderer { calculateMeteringResults() } + private fun runDepthInputCaptureInternal(sourceTextureId: Int) { + if (onDepthInputAvailable == null || sourceTextureId == 0) return + val now = System.currentTimeMillis() + if (now - lastRunDepthInputTime < 50) return + lastRunDepthInputTime = now + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, depthInputFboId) + GLES30.glViewport(0, 0, DEPTH_INPUT_SIZE, DEPTH_INPUT_SIZE) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + + // 使用 Copy Shader 采集,源是已校正好的 FBO 纹理 + GLES30.glUseProgram(copyProgramId) + + // 计算居中裁剪矩阵 (Center Crop) + val captureMatrix = FloatArray(16) + android.opengl.Matrix.setIdentityM(captureMatrix, 0) + + // MVP 矩阵处理 glReadPixels 的 Y 轴翻转 + // 标准 Quad 是 [-1, 1],直接 Scale -1 即可垂直镜像,无需位移 + val flipMatrix = FloatArray(16) + android.opengl.Matrix.setIdentityM(flipMatrix, 0) + android.opengl.Matrix.scaleM(flipMatrix, 0, 1f, -1f, 1f) + + GLES30.glUniformMatrix4fv(uCopyMVPMatrixLoc, 1, false, flipMatrix, 0) + GLES30.glUniformMatrix4fv(uCopySTMatrixLoc, 1, false, captureMatrix, 0) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) + GLES30.glUniform1i(uCopyTextureLoc, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) + GLES30.glEnableVertexAttribArray(aCopyPositionLoc) + GLES30.glVertexAttribPointer(aCopyPositionLoc, POSITION_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + GLES30.glEnableVertexAttribArray(aCopyTexCoordLoc) + GLES30.glVertexAttribPointer(aCopyTexCoordLoc, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements(GLES30.GL_TRIANGLES, 6, GLES30.GL_UNSIGNED_SHORT, 0) + + // 确保渲染已完成 + GLES30.glFinish() + + val pixelSize = DEPTH_INPUT_SIZE * DEPTH_INPUT_SIZE * 4 + if (depthInputPboId == 0) { + val pbos = IntArray(1) + GLES30.glGenBuffers(1, pbos, 0) + depthInputPboId = pbos[0] + GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, depthInputPboId) + GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, pixelSize, null, GLES30.GL_STREAM_READ) + } else { + GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, depthInputPboId) + } + + GLES30.glReadPixels(0, 0, DEPTH_INPUT_SIZE, DEPTH_INPUT_SIZE, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, 0) + val mappedBuffer = GLES30.glMapBufferRange(GLES30.GL_PIXEL_PACK_BUFFER, 0, pixelSize, GLES30.GL_MAP_READ_BIT) as? ByteBuffer + if (mappedBuffer != null) { + depthInputBuffer.rewind() + depthInputBuffer.put(mappedBuffer) + GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER) + + val bitmap = Bitmap.createBitmap(DEPTH_INPUT_SIZE, DEPTH_INPUT_SIZE, Bitmap.Config.ARGB_8888) + depthInputBuffer.rewind() + bitmap.copyPixelsFromBuffer(depthInputBuffer) + onDepthInputAvailable?.invoke(bitmap) + } + + GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES30.glViewport(0, 0, viewportWidth, viewportHeight) + } + private val meteringBytes = ByteArray(METERING_SIZE * METERING_SIZE * 4) private fun calculateMeteringResults() { @@ -1466,4 +1641,185 @@ class LutRenderer : GLSurfaceView.Renderer { halation = halation ) } + + private fun initBokehProgram() { + val vs = GlUtils.compileShader(GLES30.GL_VERTEX_SHADER, Shaders.SIMPLE_VERTEX_SHADER) + val fs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.BOKEH_FRAGMENT_SHADER) + bokehProgramId = GlUtils.linkProgram(vs, fs) + GLES30.glDeleteShader(vs) + GLES30.glDeleteShader(fs) + + if (bokehProgramId != 0) { + uBokehInputTexLoc = GLES30.glGetUniformLocation(bokehProgramId, "uInputTexture") + uBokehDepthTexLoc = GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture") + uBokehDepthMatrixLoc = GLES30.glGetUniformLocation(bokehProgramId, "uDepthMatrix") + uBokehMaxBlurRadiusLoc = GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius") + uBokehApertureLoc = GLES30.glGetUniformLocation(bokehProgramId, "uAperture") + uBokehFocusDepthLoc = GLES30.glGetUniformLocation(bokehProgramId, "uFocusDepth") + uBokehTexelSizeLoc = GLES30.glGetUniformLocation(bokehProgramId, "uTexelSize") + aBokehPositionLoc = GLES30.glGetAttribLocation(bokehProgramId, "aPosition") + aBokehTexCoordLoc = GLES30.glGetAttribLocation(bokehProgramId, "aTexCoord") + } + } + + private var uBokehDepthMatrixLoc: Int = 0 + + private fun initBokehFbo(width: Int, height: Int) { + if (bokehFboId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(bokehFboId), 0) + GLES30.glDeleteTextures(1, intArrayOf(bokehTextureId), 0) + } + + val fbo = IntArray(1) + val tex = IntArray(1) + GLES30.glGenFramebuffers(1, fbo, 0) + GLES30.glGenTextures(1, tex, 0) + bokehFboId = fbo[0] + bokehTextureId = tex[0] + + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, bokehTextureId) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, width, height, 0, GLES30.GL_RGBA, 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.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bokehFboId) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, bokehTextureId, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + } + + private fun updateDepthTexture() { + val bitmap = depthMap + if (bitmap != null && bitmap != lastDepthMap) { + if (depthTextureId == 0) { + val tex = IntArray(1) + GLES30.glGenTextures(1, tex, 0) + depthTextureId = tex[0] + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthTextureId) + 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) + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthTextureId) + GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0) + lastDepthMap = bitmap + } + } + + private fun getFocusDepth(): Float { + val bitmap = depthMap ?: return 0.5f + val fp = focusPoint ?: PointF(0.5f, 0.5f) + val px = (fp.x * bitmap.width).toInt().coerceIn(0, bitmap.width - 1) + val py = (fp.y * bitmap.height).toInt().coerceIn(0, bitmap.height - 1) + val color = try { bitmap.getPixel(px, py) } catch (e: Exception) { 0 } + return (color shr 16 and 0xFF) / 255.0f + } + + private fun renderBokehPreview(inputTexId: Int, width: Int, height: Int): Int { + if (bokehProgramId == 0 || depthMap == null) { + return inputTexId + } + + // 降采样优化:虚化计算不需要全分辨率 + val renderWidth = (width * bokehRenderScale).toInt() + val renderHeight = (height * bokehRenderScale).toInt() + + if (renderWidth != bokehFboWidth || renderHeight != bokehFboHeight) { + initBokehFbo(renderWidth, renderHeight) + bokehFboWidth = renderWidth + bokehFboHeight = renderHeight + } + + updateDepthTexture() + if (depthTextureId == 0) return inputTexId + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bokehFboId) + GLES30.glViewport(0, 0, renderWidth, renderHeight) + + GLES30.glUseProgram(bokehProgramId) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTexId) + GLES30.glUniform1i(uBokehInputTexLoc, 0) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthTextureId) + GLES30.glUniform1i(uBokehDepthTexLoc, 1) + + val depthMatrix = FloatArray(16) + android.opengl.Matrix.setIdentityM(depthMatrix, 0) + // Y-flip: depth texture top is at Y=0 (GLUtils convention) + android.opengl.Matrix.translateM(depthMatrix, 0, 0f, 1f, 0f) + android.opengl.Matrix.scaleM(depthMatrix, 0, 1f, -1f, 1f) + GLES30.glUniformMatrix4fv(uBokehDepthMatrixLoc, 1, false, depthMatrix, 0) + + // 性能优化建议:对于高分辨率预览,在 1/2 或更低分辨率 FBO 进行虚化计算 + // 这里根据实验将模糊半径根据分辨率对齐 + GLES30.glUniform1f(uBokehMaxBlurRadiusLoc, renderWidth.toFloat() / 25.0f) + GLES30.glUniform1f(uBokehApertureLoc, aperture) + GLES30.glUniform1f(uBokehFocusDepthLoc, getFocusDepth()) + GLES30.glUniform2f(uBokehTexelSizeLoc, 1.0f / renderWidth, 1.0f / renderHeight) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) + GLES30.glEnableVertexAttribArray(aBokehPositionLoc) + GLES30.glVertexAttribPointer(aBokehPositionLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + GLES30.glEnableVertexAttribArray(aBokehTexCoordLoc) + GLES30.glVertexAttribPointer(aBokehTexCoordLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements(GLES30.GL_TRIANGLES, 6, GLES30.GL_UNSIGNED_SHORT, 0) + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + return bokehTextureId + } + + private fun renderDepthDebug(width: Int, height: Int) { + updateDepthTexture() + if (depthTextureId == 0) return + + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES30.glViewport(0, 0, width, height) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + + // 使用 Copy Shader 绘制深度纹理 + GLES30.glUseProgram(copyProgramId) + + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, depthTextureId) + GLES30.glUniform1i(uCopyTextureLoc, 0) + + // 调试预览也要应用 Center Crop,否则 256x256 的正方形强行拉伸到屏幕会长得很难看 + val captureMatrix = FloatArray(16) + android.opengl.Matrix.setIdentityM(captureMatrix, 0) + android.opengl.Matrix.translateM(captureMatrix, 0, 0.5f, 0.5f, 0f) + val aspect = width.toFloat() / height.toFloat() + if (aspect > 1f) { + android.opengl.Matrix.scaleM(captureMatrix, 0, 1f / aspect, 1f, 1f) + } else { + android.opengl.Matrix.scaleM(captureMatrix, 0, 1f, aspect, 1f) + } + android.opengl.Matrix.translateM(captureMatrix, 0, -0.5f, -0.5f, 0f) + + val flipMatrix = FloatArray(16) + android.opengl.Matrix.setIdentityM(flipMatrix, 0) + // 渲染到屏幕时,应用 Y 轴翻转,使调试图看起来是正的 + android.opengl.Matrix.scaleM(flipMatrix, 0, 1f, -1f, 1f) + + GLES30.glUniformMatrix4fv(uCopyMVPMatrixLoc, 1, false, flipMatrix, 0) + GLES30.glUniformMatrix4fv(uCopySTMatrixLoc, 1, false, captureMatrix, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) + GLES30.glEnableVertexAttribArray(aCopyPositionLoc) + GLES30.glVertexAttribPointer(aCopyPositionLoc, POSITION_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + GLES30.glEnableVertexAttribArray(aCopyTexCoordLoc) + GLES30.glVertexAttribPointer(aCopyTexCoordLoc, TEXTURE_COORD_COMPONENT_COUNT, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements(GLES30.GL_TRIANGLES, 6, GLES30.GL_UNSIGNED_SHORT, 0) + } } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutTransformation.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutTransformation.kt index 940077f5..960822c7 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutTransformation.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutTransformation.kt @@ -3,6 +3,7 @@ package com.hinnka.mycamera.lut import android.graphics.Bitmap import coil.size.Size import coil.transform.Transformation +import android.content.Context import com.hinnka.mycamera.gallery.PhotoMetadata import com.hinnka.mycamera.gallery.PhotoProcessor @@ -15,6 +16,7 @@ import com.hinnka.mycamera.gallery.PhotoProcessor * @param chromaNoiseReduction 减少杂色强度 */ class PhotoTransformation( + private val context: Context, private val metadata: PhotoMetadata, private val photoProcessor: PhotoProcessor, private val sharpening: Float = 0f, @@ -26,7 +28,7 @@ class PhotoTransformation( override suspend fun transform(input: Bitmap, size: Size): Bitmap { return photoProcessor.processBitmap( - input, metadata, sharpening, noiseReduction, chromaNoiseReduction + context, null, input, metadata, sharpening, noiseReduction, chromaNoiseReduction ) } } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt index af0f9a62..86dcb5e9 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/Shaders.kt @@ -7,31 +7,31 @@ object Shaders { /** * 顶点着色器 - * + * * 处理顶点位置和纹理坐标变换 */ /** * 顶点着色器 - * + * * 处理顶点位置和纹理坐标变换 */ val VERTEX_SHADER = """ #version 300 es - + // 顶点属性 in vec4 aPosition; in vec2 aTexCoord; - + // 输出到片元着色器 out vec2 vTexCoord; out vec2 vRawCoord; // 原始坐标用于色散计算 - + // MVP 变换矩阵(用于 center crop 缩放) uniform mat4 uMVPMatrix; - + // SurfaceTexture 变换矩阵 uniform mat4 uSTMatrix; - + void main() { // 应用 MVP 矩阵进行顶点变换(center crop) gl_Position = uMVPMatrix * aPosition; @@ -69,12 +69,12 @@ object Shaders { val FRAGMENT_SHADER_COPY_2D = """ #version 300 es precision mediump float; - + in vec2 vTexCoord; out vec4 fragColor; - + uniform sampler2D uCameraTexture; - + void main() { fragColor = texture(uCameraTexture, vTexCoord); } @@ -229,6 +229,8 @@ object Shaders { uniform float uNoiseSeed; // 用于每帧刷新噪点的随机种子 uniform float uLowRes; // 0.0 ~ 1.0 (低分辨率强度,0为无效果) uniform float uAspectRatio; // 图像长宽比 (Width/Height),用于确保低分像素块是正方形 + uniform float uAperture; // 计算光圈 (1.4 ~ 16.0) + uniform vec2 uFocusPoint; // 对焦点 (0.0 ~ 1.0) const vec3 W = vec3(0.2126, 0.7152, 0.0722); @@ -274,7 +276,7 @@ object Shaders { vec3 applyLutColorSpace(vec3 rgb, int colorSpace) { if (colorSpace == 0) return rgb; // sRGB - + // Matrices for Linear sRGB to target color space (aligned with ColorSpace.kt) if (colorSpace == 1) { // DCI-P3 (Bradford adapted) return mat3(0.875905, 0.035332, 0.016382, 0.122070, 0.964542, 0.063767, 0.002025, 0.000126, 0.919851) * rgb; @@ -305,13 +307,13 @@ object Shaders { if (uLowRes > 0.005) { // 算法改良:不再使用 floor() 产生的硬边缘,而是通过降采样+双线性插值模拟“糊”感 // 同时保留边缘的低分锯齿感 - float blocksX = mix(512.0, 32.0, uLowRes); + float blocksX = mix(512.0, 32.0, uLowRes); vec2 gridSize = vec2(1.0 / blocksX, 1.0 / (blocksX / uAspectRatio)); - + // 1. 计算当前像素所在的网格坐标 vec2 gridUV = floor(vTexCoord / gridSize) * gridSize + gridSize * 0.5; vec2 gridRC = floor(vRawCoord / gridSize) * gridSize + gridSize * 0.5; - + // 2. 混合原始坐标和网格坐标,实现“糊”且有锯齿的效果 // 边缘会有锯齿,但平整区域通过插值变得平滑,避免彩色碎块 uvCoord = mix(vTexCoord, gridUV, 0.95); @@ -326,11 +328,11 @@ object Shaders { vec2 dir = rcCoord - center; float dist = length(dir); float offset = pow(dist, 1.5) * uChromaticAberration * 0.08; - + // 关键:基于原始坐标偏移后,必须通过 uSTMatrix 转换回实际采样坐标 vec2 rCoord = (uSTMatrix * vec4(rcCoord + dir * offset, 0.0, 1.0)).xy; vec2 bCoord = (uSTMatrix * vec4(rcCoord - dir * offset, 0.0, 1.0)).xy; - + float r = texture(uCameraTexture, rCoord).r; float g = texture(uCameraTexture, uvCoord).g; float b = texture(uCameraTexture, bCoord).b; @@ -360,14 +362,14 @@ object Shaders { if (abs(uHighlights) > 0.001 || abs(uShadows) > 0.001) { float highlightMask = smoothstep(0.5, 1.0, luma); float shadowMask = 1.0 - smoothstep(0.0, 0.5, luma); - + if (abs(uHighlights) > 0.001) { float highlightFactor = 1.0 + uHighlights * (uHighlights > 0.0 ? 0.7 : 0.3); color.rgb = mix(color.rgb, color.rgb * highlightFactor, highlightMask); } - + if (abs(uShadows) > 0.001) { - vec3 shadowTarget = (uShadows > 0.0) + vec3 shadowTarget = (uShadows > 0.0) ? (mix(color.rgb, vec3(luma), uShadows * 0.2) + (color.rgb * uShadows * 0.5)) : (color.rgb * (1.0 + uShadows * 0.5)); color.rgb = mix(color.rgb, shadowTarget, shadowMask); @@ -458,11 +460,11 @@ object Shaders { // 将浮点精度控制在适合 fract 的范围,避免伪影 vec2 seedOffset = vec2(fract(uNoiseSeed * 1.234), fract(uNoiseSeed * 3.456)); vec2 noiseCoord = uvCoord * 800.0 + seedOffset * 100.0; - + // 亮度噪点 float lumNoise = fract(sin(dot(noiseCoord, vec2(12.9898, 78.233))) * 43758.5453); lumNoise = (lumNoise - 0.5) * 2.0; - + // 彩色噪点 (R, G, B 分别生成) float colorNoiseR = fract(sin(dot(noiseCoord + vec2(1.1, 2.2), vec2(39.346, 11.135))) * 43758.5453); float colorNoiseG = fract(sin(dot(noiseCoord + vec2(3.3, 4.4), vec2(73.156, 52.235))) * 43758.5453); @@ -472,10 +474,10 @@ object Shaders { luma = dot(color.rgb, W); // 蒙版强度:中灰区域稍强,极端高光/阴影保留 float noiseMask = mix(0.5, 1.0, 1.0 - abs(luma - 0.5) * 1.5); - + // 混合:结合亮度和彩色噪点,使彩色噪点不那么突兀但又可见 vec3 finalNoise = mix(vec3(lumNoise), mix(vec3(lumNoise), colorNoise, 0.7), 0.8); - + // 基准强度为 0.3,效果较明显 color.rgb += finalNoise * uNoise * max(0.0, noiseMask); } @@ -523,6 +525,17 @@ object Shaders { 1.0f, 1.0f // 右上 ) + /** + * 后处理专用纹理坐标(垂直翻转) + * 用于让 glReadPixels 直接读取到正向的图片 + */ + val POST_PROCESS_TEXTURE_COORDS = floatArrayOf( + 0.0f, 1.0f, // Top-left -> GL Bottom-left + 1.0f, 1.0f, // Top-right -> GL Bottom-right + 0.0f, 0.0f, // Bottom-left -> GL Top-left + 1.0f, 0.0f // Bottom-right -> GL Top-right + ) + /** * 绘制顺序索引 * 使用两个三角形绘制四边形 @@ -531,4 +544,297 @@ object Shaders { 0, 1, 2, // 第一个三角形 1, 3, 2 // 第二个三角形 ) + + /** + * 高质量 Bokeh 片元着色器 (OpenGL ES 3.0) + * 采用 Golden-Angle 螺旋采样实现圆盘虚化 + */ + val BOKEH_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uInputTexture; + uniform sampler2D uDepthTexture; + + uniform mat4 uDepthMatrix; // 用于对齐深度图坐标(处理 Y 翻转和 FOV 缩放) + uniform float uMaxBlurRadius; + uniform float uAperture; + uniform float uFocusDepth; + uniform vec2 uTexelSize; + + const float PI = 3.14159265359; + const float GOLDEN_ANGLE = 2.39996323; + const int SAMPLES = 64; // 实时预览:64 采样配合 Jitter 已足够顺滑且性能均衡 + + // Interleaved Gradient Noise (IGN) - 用于低采样下消除环状伪影 + float random(vec2 fragCoord) { + vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189); + return fract(magic.z * fract(dot(fragCoord, magic.xy))); + } + + void main() { + vec2 depthUV = (uDepthMatrix * vec4(vTexCoord, 0.0, 1.0)).xy; + vec4 centerColor = texture(uInputTexture, vTexCoord); + float centerDepth = texture(uDepthTexture, depthUV).r; + + float coc = abs(centerDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture); + coc = clamp(coc, 0.0, uMaxBlurRadius); + + if (coc < 0.5) { + fragColor = centerColor; + return; + } + + vec3 accColor = vec3(0.0); + float accWeight = 0.0; + + // 重要优化:利用 IGN 随机扰动旋转角度,消除固定采样模式带来的色带感 + // 相对于 brute-force 160 采样,这样能以更低功耗达到相同平滑度 + float jitter = random(gl_FragCoord.xy) * GOLDEN_ANGLE; + + for (int i = 0; i < SAMPLES; i++) { + // 面积均匀分布 + float r = sqrt(float(i) / float(SAMPLES)) * coc; + float theta = float(i) * GOLDEN_ANGLE + jitter; + + vec2 offset = vec2(cos(theta), sin(theta)) * r * uTexelSize; + vec2 sampleUV = clamp(vTexCoord + offset, 0.0, 1.0); + + // Mipmap LOD 计算,融合相邻片元,在不加入噪点的情况下自然抹平色带 + float sampleRadiusPixels = r * 1.5 / sqrt(float(SAMPLES)); + float lod = max(0.0, log2(sampleRadiusPixels)); + + vec3 sampleColor = texture(uInputTexture, sampleUV, lod).rgb; + vec2 sDepthUV = clamp((uDepthMatrix * vec4(sampleUV, 0.0, 1.0)).xy, 0.0, 1.0); + float sampleDepth = texture(uDepthTexture, sDepthUV).r; + + float sampleCoc = abs(sampleDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture); + sampleCoc = clamp(sampleCoc, 0.0, uMaxBlurRadius); + + // 软权重逻辑 + float w = smoothstep(r - 0.5, r + 1.0, sampleCoc); + + float depthDiff = sampleDepth - centerDepth; + float bgOcclusion = smoothstep(-0.10, -0.01, depthDiff); + float fgHalo = smoothstep(0.06, 0.01, depthDiff); + w *= bgOcclusion * fgHalo; + + accColor += sampleColor * w; + accWeight += w; + } + vec3 finalColor = accWeight > 0.001 ? (accColor / accWeight) : centerColor.rgb; + fragColor = vec4(finalColor, centerColor.a); + } + """.trimIndent() + + val FGF_COEFFS_FRAGMENT_SHADER = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uLowResDepth; + uniform sampler2D uLowResGuide; // 通常是对原图做过预降采样后的版本 + uniform vec2 uTexelSize; // 低分辨率下的像素步进 + + const vec3 W = vec3(0.2126, 0.7152, 0.0722); + const float eps = 0.01 * 0.01; // 减小 epsilon,使系数更灵敏地响应引导图边缘 + + void main() { + float mean_I = 0.0; + float mean_p = 0.0; + float mean_Ip = 0.0; + float mean_II = 0.0; + float sumW = 0.0; + + // 优化:采用更紧凑、密集的 5x5 窗口 (stride=1),提高边缘系数的精确度 + // 之前的 stride=4 太粗糙,导致跨越边缘时系数过度平滑 + for(int y = -2; y <= 2; y++) { + for(int x = -2; x <= 2; x++) { + vec2 offset = vec2(float(x), float(y)) * uTexelSize; + vec2 sampleUV = vTexCoord + offset; + + float p = texture(uLowResDepth, sampleUV).r; + float I = dot(texture(uLowResGuide, sampleUV).rgb, W); + + // 使用高斯权重,使中心像素贡献更高,进一步抑制边缘扩散 + float wS = exp(-float(x*x + y*y) / 2.0); + + mean_I += I * wS; + mean_p += p * wS; + mean_Ip += I * p * wS; + mean_II += I * I * wS; + sumW += wS; + } + } + + mean_I /= sumW; + mean_p /= sumW; + mean_Ip /= sumW; + mean_II /= sumW; + + float var_I = mean_II - mean_I * mean_I; + float cov_Ip = mean_Ip - mean_I * mean_p; + + float a = cov_Ip / (var_I + eps); + float b = mean_p - a * mean_I; + + // 输出 a, b 和 mean_I 到 RGB 通道 (支持 Guidance-Aware Upsampling) + fragColor = vec4(a, b, mean_I, 1.0); + } + """.trimIndent() + + val FGF_APPLY_FRAGMENT_SHADER = """#version 300 es + precision highp float; + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uHighResGuide; // 高清原图 + uniform sampler2D uLowResCoeffs; // FGF Pass 1 生成的 (a, b, mean_I) 纹理 + uniform vec2 uLowResTexelSize; // 低分辨率系数纹理的像素尺寸 + + const vec3 W = vec3(0.2126, 0.7152, 0.0722); + + void main() { + // 获取当前像素的高清亮度 I + vec3 guideRGB = texture(uHighResGuide, vTexCoord).rgb; + float I = dot(guideRGB, W); + + // 优化:Guidance-Aware Upsampling (系数级的联合双边上采样) + // 解决常规双线性插值在边缘导致 a, b 混叠的问题 + vec2 pos = vTexCoord / uLowResTexelSize - 0.5; + vec2 p0 = floor(pos); + vec2 f = pos - p0; + + // 采样相邻的 4 个低分系数块 + vec3 c00 = texture(uLowResCoeffs, (p0 + vec2(0.5, 0.5)) * uLowResTexelSize).rgb; + vec3 c10 = texture(uLowResCoeffs, (p0 + vec2(1.5, 0.5)) * uLowResTexelSize).rgb; + vec3 c01 = texture(uLowResCoeffs, (p0 + vec2(0.5, 1.5)) * uLowResTexelSize).rgb; + vec3 c11 = texture(uLowResCoeffs, (p0 + vec2(1.5, 1.5)) * uLowResTexelSize).rgb; + + // 计算亮度权重:只采纳那些平均亮度与当前高清像素亮度接近的低分块生成的系数 + // 这样当高清像素在主体内时,背景侧的 low-res 系数即便物理位置近,权重也会被压低 + float sigma = 0.12; + float w00 = (1.0 - f.x) * (1.0 - f.y) * exp(-abs(I - c00.z) / sigma); + float w10 = f.x * (1.0 - f.y) * exp(-abs(I - c10.z) / sigma); + float w01 = (1.0 - f.x) * f.y * exp(-abs(I - c01.z) / sigma); + float w11 = f.x * f.y * exp(-abs(I - c11.z) / sigma); + + float sumW = w00 + w10 + w01 + w11; + vec2 coeffs; + if (sumW > 0.01) { + coeffs = (c00.xy * w00 + c10.xy * w10 + c01.xy * w01 + c11.xy * w11) / sumW; + } else { + // 回退:如果亮度差异都太大,使用基础双线性插值 + coeffs = mix(mix(c00.xy, c10.xy, f.x), mix(c01.xy, c11.xy, f.x), f.y); + } + + float finalDepth = coeffs.x * I + coeffs.y; + finalDepth = clamp(finalDepth, 0.0, 1.0); + + fragColor = vec4(finalDepth, finalDepth, finalDepth, 1.0); + } + """.trimIndent() + + /** + * 后期处理专用:物理级的 PSF Splatting 模拟算法。 + * 采用大半径 Gather、逆向 HDR 提亮(点光源扩张)、能量守恒、球面像差(肥皂泡边缘)和口径蚀来高度还原真实的单反镜头虚化质感。 + */ + val PSF_SPLAT_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + + in vec2 vTexCoord; + out vec4 fragColor; + + uniform sampler2D uInputTexture; + uniform sampler2D uDepthTexture; + + uniform mat4 uDepthMatrix; + uniform float uMaxBlurRadius; + uniform float uAperture; + uniform float uFocusDepth; + uniform vec2 uTexelSize; + + const float PI = 3.14159265359; + const float GOLDEN_ANGLE = 2.39996323; + const int SAMPLES = 160; + + void main() { + vec2 depthUV = clamp((uDepthMatrix * vec4(vTexCoord, 0.0, 1.0)).xy, 0.0, 1.0); + vec4 centerColor = texture(uInputTexture, vTexCoord); + float centerDepth = texture(uDepthTexture, depthUV).r; + + float centerCoc = abs(centerDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture); + centerCoc = clamp(centerCoc, 0.0, uMaxBlurRadius); + + // 1. 强力保护机制:对于清晰主体,保持 100% 锐度 + if (centerCoc < 0.2) { + fragColor = centerColor; + return; + } + + // 2. 初始权重:赋予较高的权重以定性,防止背景渗色 + float centerWeight = 6.0 / (centerCoc * 0.4 + 1.0); + vec3 accColor = centerColor.rgb * centerWeight; + float accWeight = centerWeight; + + float softBase = max(3.0, uMaxBlurRadius * 0.1); + + for (int i = 0; i < SAMPLES; i++) { + float f = float(i + 1); + float r = sqrt(f / float(SAMPLES)) * uMaxBlurRadius; + float theta = f * GOLDEN_ANGLE; + + vec2 offset = vec2(cos(theta), sin(theta)) * r * uTexelSize; + vec2 sampleUV = clamp(vTexCoord + offset, 0.0, 1.0); + + float lod = log2(r * 0.3 + 1.5); + vec3 sColor = textureLod(uInputTexture, sampleUV, lod).rgb; + vec2 sDepthUV = clamp((uDepthMatrix * vec4(sampleUV, 0.0, 1.0)).xy, 0.0, 1.0); + float sDepth = texture(uDepthTexture, sDepthUV).r; + + // --- 颜色引导保护 (Edge Protection Logic) --- + // 如果采样点颜色与中心色非常接近,说明它可能是主体的一部分 + // 我们限制其散景半径,防止它作为一个模糊点去“泼溅”覆盖中心点 + float colorDist = distance(centerColor.rgb, sColor); + float colorSimilarity = smoothstep(0.15, 0.01, colorDist); + + float rawCoc = abs(sDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture); + // 关键:如果颜色相似度高,则强制将采样点的 CoC 压低,视为主体保护区 + float sCoc = mix(rawCoc, min(rawCoc, centerCoc), colorSimilarity); + sCoc = clamp(sCoc, 0.0, uMaxBlurRadius); + + // 4. 重构权重逻辑 + float fW = smoothstep(r - softBase, r + softBase * 0.5, sCoc); + float bW = smoothstep(r - softBase, r + softBase * 0.5, centerCoc); + + float depthDiff = sDepth - centerDepth; + float isNearer = smoothstep(-0.1, 0.1, depthDiff); + + // 引入相似度加成,让主体边缘的像素更倾向于互相保护而不是混入背景 + float weight = mix(bW * (1.1 - isNearer), fW, isNearer); + weight *= (1.0 + colorSimilarity * 0.8); + + if (weight > 0.0001) { + float luma = dot(sColor, vec3(0.2126, 0.7152, 0.0722)); + float hdrBoost = 1.0 + pow(max(0.0, luma - 0.75), 2.0) * 4.0 * smoothstep(1.0, 5.0, sCoc); + + float edge = smoothstep(0.7, 1.05, r / max(sCoc, 0.1)); + float ring = 1.0 + edge * 0.4 * smoothstep(1.5, 5.0, sCoc); + + float fw = weight * ring; + accColor += sColor * hdrBoost * fw; + accWeight += fw; + } + } + + vec3 finalColor = accWeight > 0.001 ? (accColor / accWeight) : centerColor.rgb; + finalColor = clamp(finalColor, 0.0, 1.0); + + fragColor = vec4(finalColor, centerColor.a); + } + """.trimIndent() } diff --git a/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt b/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt new file mode 100644 index 00000000..87ee09e3 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ml/DepthEstimator.kt @@ -0,0 +1,181 @@ +package com.hinnka.mycamera.ml + +import android.content.Context +import android.graphics.Bitmap +import com.hinnka.mycamera.utils.PLog +import org.tensorflow.lite.DataType +import org.tensorflow.lite.Interpreter +import org.tensorflow.lite.gpu.CompatibilityList +import org.tensorflow.lite.gpu.GpuDelegate +import org.tensorflow.lite.support.common.FileUtil +import org.tensorflow.lite.support.image.ImageProcessor +import org.tensorflow.lite.support.image.TensorImage +import org.tensorflow.lite.support.image.ops.ResizeOp +import org.tensorflow.lite.support.tensorbuffer.TensorBuffer +import org.tensorflow.lite.nnapi.NnApiDelegate + +class DepthEstimator(context: Context) { + private var interpreter: Interpreter? = null + private var gpuDelegate: GpuDelegate? = null + private var nnApiDelegate: NnApiDelegate? = null + private var isInitialized = false + + // Input shape for Midas-v2 is typically [1, 256, 256, 3] + private val inputSize = 256 + + // Output shape is [1, 256, 256, 1] for depth map + private val outputSize = 256 + + init { + try { + val modelFile = FileUtil.loadMappedFile(context, "midas.tflite") + + // Try GPU + val gpuOptions = Interpreter.Options() + val compatList = CompatibilityList() + gpuDelegate = if (compatList.isDelegateSupportedOnThisDevice) { + val delegateOptions = compatList.bestOptionsForThisDevice + GpuDelegate(delegateOptions) + } else { + GpuDelegate() + } + gpuOptions.addDelegate(gpuDelegate) + try { + interpreter = Interpreter(modelFile, gpuOptions) + isInitialized = true + PLog.d(TAG, "Using GPU Delegate for Depth Estimator") + } catch (e: Exception) { + PLog.w(TAG, "Failed to initialize GPU delegate, falling back to NNAPI", e) + gpuDelegate?.close() + gpuDelegate = null + } + + // Try NNAPI (NPU) if GPU failed or not supported + if (!isInitialized) { + val nnApiOptions = Interpreter.Options() + nnApiDelegate = NnApiDelegate() + nnApiOptions.addDelegate(nnApiDelegate) + try { + interpreter = Interpreter(modelFile, nnApiOptions) + isInitialized = true + PLog.d(TAG, "Using NNAPI (NPU) for Depth Estimator") + } catch (e: Exception) { + PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to CPU", e) + nnApiDelegate?.close() + nnApiDelegate = null + } + } + + // Fallback to CPU + if (!isInitialized) { + val cpuOptions = Interpreter.Options() + cpuOptions.setNumThreads(4) + interpreter = Interpreter(modelFile, cpuOptions) + isInitialized = true + PLog.d(TAG, "Using CPU for Depth Estimator") + } + } catch (e: Exception) { + PLog.e(TAG, "Error initializing DepthEstimator", e) + } + } + + /** + * Estimates depth for the given bitmap. + * @param inputBitmap Original image bitmap. + * @return Depth map bitmap of size 256x256, or null if failed. + */ + fun estimateDepth(inputBitmap: Bitmap): Bitmap? { + if (!isInitialized || interpreter == null) { + PLog.e(TAG, "DepthEstimator is not initialized.") + return null + } + + try { + // 1. Get input/output metadata + val inputTensor = interpreter!!.getInputTensor(0) + val outputTensor = interpreter!!.getOutputTensor(0) + val inputDataType = inputTensor.dataType() + val outputDataType = outputTensor.dataType() + + // 2. Preprocess the input image + val imageProcessor = ImageProcessor.Builder() + .add(ResizeOp(inputSize, inputSize, ResizeOp.ResizeMethod.BILINEAR)) + .build() + + var tensorImage = TensorImage(inputDataType) + tensorImage.load(inputBitmap) + tensorImage = imageProcessor.process(tensorImage) + + // 3. Prepare the output buffer + val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType) + + // 4. Run inference + interpreter?.run(tensorImage.buffer, outputBuffer.buffer) + + // 5. Post-process to Bitmap (Grayscale) + return if (outputDataType == DataType.FLOAT32) { + convertOutputToBitmap(outputBuffer.floatArray) + } else { + // If quantized output, convert to float first or handle UINT8 directly + val floatArray = FloatArray(outputBuffer.flatSize) + if (outputDataType == DataType.UINT8) { + val byteBuffer = outputBuffer.buffer + byteBuffer.rewind() + val bytes = ByteArray(outputBuffer.flatSize) + byteBuffer.get(bytes) + for (i in bytes.indices) { + floatArray[i] = (bytes[i].toInt() and 0xFF).toFloat() + } + } + convertOutputToBitmap(floatArray) + } + + } catch (e: Exception) { + PLog.e(TAG, "Error during depth estimation", e) + return null + } + } + + /** + * Converts a float array output [256*256] to a Grayscale Bitmap. + */ + private fun convertOutputToBitmap(outputArray: FloatArray): Bitmap { + // Find min and max for normalization + var min = Float.MAX_VALUE + var max = Float.MIN_VALUE + for (value in outputArray) { + if (value < min) min = value + if (value > max) max = value + } + + val range = max - min + val finalRange = if (range == 0f) 1f else range // avoid division by zero + + val pixels = IntArray(outputSize * outputSize) + val limit = minOf(outputArray.size, pixels.size) + for (i in 0 until limit) { + // Normalize to [0, 255] + val normalized = ((outputArray[i] - min) / finalRange * 255f).toInt().coerceIn(0, 255) + // Create a grayscale color (ARGB) + pixels[i] = (0xFF shl 24) or (normalized shl 16) or (normalized shl 8) or normalized + } + + val bitmap = Bitmap.createBitmap(outputSize, outputSize, Bitmap.Config.ARGB_8888) + bitmap.setPixels(pixels, 0, outputSize, 0, 0, outputSize, outputSize) + return bitmap + } + + fun close() { + interpreter?.close() + interpreter = null + gpuDelegate?.close() + gpuDelegate = null + nnApiDelegate?.close() + nnApiDelegate = null + isInitialized = false + } + + companion object { + private const val TAG = "DepthEstimator" + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/phantom/PhantomWidgetProvider.kt b/app/src/main/java/com/hinnka/mycamera/phantom/PhantomWidgetProvider.kt index f4186843..84b268c3 100644 --- a/app/src/main/java/com/hinnka/mycamera/phantom/PhantomWidgetProvider.kt +++ b/app/src/main/java/com/hinnka/mycamera/phantom/PhantomWidgetProvider.kt @@ -225,7 +225,10 @@ class PhantomWidgetProvider : AppWidgetProvider() { val input = android.graphics.BitmapFactory.decodeStream(inputStream) latestPhoto.metadata?.let { ContentRepository.getInstance(context).photoProcessor.processBitmap( - input, it, + context, + null, + input, + it, ) } } catch (e: Exception) { diff --git a/app/src/main/java/com/hinnka/mycamera/preview/PreviewDepthProcessor.kt b/app/src/main/java/com/hinnka/mycamera/preview/PreviewDepthProcessor.kt new file mode 100644 index 00000000..0c2ca4f0 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/preview/PreviewDepthProcessor.kt @@ -0,0 +1,79 @@ +package com.hinnka.mycamera.preview + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.ImageFormat +import android.graphics.Rect +import android.graphics.YuvImage +import android.media.Image +import android.media.ImageReader +import android.util.Log +import com.hinnka.mycamera.ml.DepthEstimator +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer + +/** + * Processor for intercepting the real-time preview stream, + * converting frames to Bitmaps, and feeding them to the DepthEstimator. + */ +class PreviewDepthProcessor(private val context: Context) { + private val scope = CoroutineScope(Dispatchers.Default + Job()) + private var depthEstimator: DepthEstimator? = null + + private var isProcessing = false + + // Expose the latest depth map as a StateFlow for the UI or GL pipeline + private val _latestDepthMap = MutableStateFlow(null) + val latestDepthMap = _latestDepthMap.asStateFlow() + + init { + // Initialize DepthEstimator + scope.launch { + depthEstimator = DepthEstimator(context) + } + } + + /** + * Process a bitmap from the GL preview stream. + * Drops frames if the previous frame is still processing. + */ + fun processBitmap(bitmap: Bitmap) { + if (isProcessing) { + return + } + + val estimator = depthEstimator + if (estimator == null) { + return + } + + isProcessing = true + + // Process on background thread + scope.launch { + try { + val depthMap = estimator.estimateDepth(bitmap) + _latestDepthMap.value = depthMap + } catch (e: Exception) { + Log.e(TAG, "Error processing preview bitmap for depth", e) + } finally { + isProcessing = false + } + } + } + + fun release() { + depthEstimator?.close() + depthEstimator = null + } + + companion object { + private const val TAG = "PreviewDepthProcessor" + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt b/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt new file mode 100644 index 00000000..d546bd58 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/DepthBokehProcessor.kt @@ -0,0 +1,85 @@ +package com.hinnka.mycamera.processor + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.PointF +import com.hinnka.mycamera.gallery.PhotoManager +import com.hinnka.mycamera.ml.DepthEstimator +import com.hinnka.mycamera.utils.PLog + +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Handles the post-processing of the Depth Map for high-quality optical bokeh. + * This class coordinates the Vulkan compute pipeline for edge refinement (Guided Filter) + * and realistic bokeh convolution. + */ +class DepthBokehProcessor(context: Context) { + private val processor = OglBokehProcessor() + private val depthEstimator = DepthEstimator(context) + private val mutex = Mutex() + + /** + * Applies optical-grade computational bokeh to the high-res image. + * + * @param originalImage The high resolution RGB image (e.g. 12MP). + * @param focusPoint The normalized coordinates (0.0 - 1.0) where the user focused. + * @param aperture The simulated aperture value (e.g., 1.4 for heavy blur, 16.0 for none). + * @return A new Bitmap with the bokeh applied. + */ + suspend fun applyHighQualityBokeh( + context: Context, + photoId: String?, + originalImage: Bitmap, + focusX: Float?, + focusY: Float?, + aperture: Float + ): Bitmap = mutex.withLock { + if (aperture > 16.0f || aperture <= 0f) { + return originalImage + } + + var depthMap: Bitmap? = null + var depthFile: java.io.File? = null + if (photoId != null) { + depthFile = PhotoManager.getDepthFile(context, photoId) + if (depthFile.exists()) { + depthMap = BitmapFactory.decodeFile(depthFile.absolutePath) + } + } + + if (depthMap == null) { + depthMap = depthEstimator.estimateDepth(originalImage) + + if (depthMap != null && depthFile != null) { + try { + java.io.FileOutputStream(depthFile).use { out -> + depthMap.compress(Bitmap.CompressFormat.PNG, 100, out) + } + } catch (e: Exception) { + e.printStackTrace() + } + } + } + + var result: Bitmap? = null + if (depthMap != null) { + result = processor.applyBokeh( + originalImage, + depthMap, + focusX ?: 0.5f, + focusY ?: 0.5f, + aperture + ) + } + + return result ?: originalImage + } + + fun close() { + depthEstimator.close() + } +} + diff --git a/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt b/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt new file mode 100644 index 00000000..06524142 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/OglBokehProcessor.kt @@ -0,0 +1,284 @@ +package com.hinnka.mycamera.processor + +import android.graphics.Bitmap +import android.graphics.ColorSpace +import android.opengl.EGL14 +import android.opengl.GLES30 +import android.opengl.GLUtils +import com.hinnka.mycamera.lut.GlUtils +import com.hinnka.mycamera.lut.Shaders +import com.hinnka.mycamera.utils.PLog + +class OglBokehProcessor { + companion object { + private const val TAG = "OglBokehProcessor" + } + + private var uDepthMatrixLoc: Int = 0 + private var bokehProgramId = 0 + private var fgfCoeffProgramId = 0 + private var fgfApplyProgramId = 0 + private var vertexBufferId = 0 + private var texCoordBufferId = 0 + private var indexBufferId = 0 + + private var eglDisplay = EGL14.EGL_NO_DISPLAY + private var eglContext = EGL14.EGL_NO_CONTEXT + private var eglSurface = EGL14.EGL_NO_SURFACE + + fun applyBokeh( + originalImage: Bitmap, + lowResDepthMap: Bitmap, + focusX: Float, + focusY: Float, + aperture: Float + ): Bitmap? { + try { + initEGL(originalImage.width, originalImage.height) + initGL() + + val inputTex = createTexture(originalImage, mipmap = true) + val lowResDepthTex = createTexture(lowResDepthMap) + + // Step 1: FGF Coefficients (Run at low resolution) + val lowResCoeffTex = IntArray(1) + GLES30.glGenTextures(1, lowResCoeffTex, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lowResCoeffTex[0]) + // Use RGB16F to store (a, b, mean_I) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGB16F, lowResDepthMap.width, lowResDepthMap.height, 0, GLES30.GL_RGB, GLES30.GL_HALF_FLOAT, 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) + + val fbo = IntArray(1) + GLES30.glGenFramebuffers(1, fbo, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0]) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, lowResCoeffTex[0], 0) + + GLES30.glViewport(0, 0, lowResDepthMap.width, lowResDepthMap.height) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(fgfCoeffProgramId) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lowResDepthTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(fgfCoeffProgramId, "uLowResDepth"), 0) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(fgfCoeffProgramId, "uLowResGuide"), 1) + + GLES30.glUniform2f(GLES30.glGetUniformLocation(fgfCoeffProgramId, "uTexelSize"), 1.0f / lowResDepthMap.width, 1.0f / lowResDepthMap.height) + + drawQuad(fgfCoeffProgramId) + + // Step 2: FGF Apply (Generate High-Res Refined Depth) + val highResDepthTex = IntArray(1) + 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.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, highResDepthTex[0], 0) + GLES30.glViewport(0, 0, originalImage.width, originalImage.height) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(fgfApplyProgramId) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, inputTex) + GLES30.glUniform1i(GLES30.glGetUniformLocation(fgfApplyProgramId, "uHighResGuide"), 0) + + GLES30.glActiveTexture(GLES30.GL_TEXTURE1) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lowResCoeffTex[0]) + GLES30.glUniform1i(GLES30.glGetUniformLocation(fgfApplyProgramId, "uLowResCoeffs"), 1) + + // Pass the texel size of the low-res coefficient texture for guidance-aware upsampling + GLES30.glUniform2f(GLES30.glGetUniformLocation(fgfApplyProgramId, "uLowResTexelSize"), 1.0f / lowResDepthMap.width, 1.0f / lowResDepthMap.height) + + drawQuad(fgfApplyProgramId) + + // Step 3: Apply Bokeh + val outputTex = IntArray(1) + GLES30.glGenTextures(1, outputTex, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, outputTex[0]) + GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, originalImage.width, originalImage.height, 0, GLES30.GL_RGBA, 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, outputTex[0], 0) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + GLES30.glUseProgram(bokehProgramId) + + val focusDepth = sampleDepth(lowResDepthMap, focusX, focusY) + + 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, highResDepthTex[0]) + GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1) + + GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius"), originalImage.width.toFloat() / 24.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) + + val identity = FloatArray(16) + android.opengl.Matrix.setIdentityM(identity, 0) + GLES30.glUniformMatrix4fv(GLES30.glGetUniformLocation(bokehProgramId, "uDepthMatrix"), 1, false, identity, 0) + + drawQuad(bokehProgramId) + GLES30.glFinish() + + // Read back to Bitmap + val resultBitmap = Bitmap.createBitmap(originalImage.width, originalImage.height, + Bitmap.Config.ARGB_8888, false, originalImage.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB)) + val buffer = java.nio.ByteBuffer.allocateDirect(originalImage.width * originalImage.height * 4) + GLES30.glReadPixels(0, 0, originalImage.width, originalImage.height, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, buffer) + resultBitmap.copyPixelsFromBuffer(buffer) + + // Clean up + GLES30.glDeleteTextures(1, intArrayOf(inputTex), 0) + GLES30.glDeleteTextures(1, intArrayOf(lowResDepthTex), 0) + GLES30.glDeleteTextures(1, lowResCoeffTex, 0) + GLES30.glDeleteTextures(1, highResDepthTex, 0) + GLES30.glDeleteTextures(1, outputTex, 0) + GLES30.glDeleteFramebuffers(1, fbo, 0) + + return resultBitmap + } catch (e: Exception) { + PLog.e(TAG, "Error applying OGL Bokeh: ${e.message}") + return null + } finally { + releaseGL() + } + } + + private fun sampleDepth(depthMap: Bitmap, x: Float, y: Float): Float { + val px = (x * depthMap.width).toInt().coerceIn(0, depthMap.width - 1) + val py = (y * depthMap.height).toInt().coerceIn(0, depthMap.height - 1) + val color = depthMap.getPixel(px, py) + // Assume depth is in R channel + return (color shr 16 and 0xFF) / 255.0f + } + + private fun createTexture(bitmap: Bitmap, filterNearest: Boolean = false, mipmap: Boolean = false): Int { + val tex = IntArray(1) + GLES30.glGenTextures(1, tex, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, tex[0]) + val minFilter = if (filterNearest) GLES30.GL_NEAREST else if (mipmap) GLES30.GL_LINEAR_MIPMAP_LINEAR else GLES30.GL_LINEAR + val magFilter = if (filterNearest) GLES30.GL_NEAREST else GLES30.GL_LINEAR + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, minFilter) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, magFilter) + 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) + GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0) + if (mipmap) { + GLES30.glGenerateMipmap(GLES30.GL_TEXTURE_2D) + } + return tex[0] + } + + private fun initEGL(width: Int, height: Int) { + eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) + val version = IntArray(2) + EGL14.eglInitialize(eglDisplay, version, 0, version, 1) + + val configAttribs = intArrayOf( + EGL14.EGL_RED_SIZE, 8, + EGL14.EGL_GREEN_SIZE, 8, + EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_ALPHA_SIZE, 8, + EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, + EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, + EGL14.EGL_NONE + ) + val configs = arrayOfNulls(1) + val numConfigs = IntArray(1) + EGL14.eglChooseConfig(eglDisplay, configAttribs, 0, configs, 0, 1, numConfigs, 0) + val config = configs[0] + + val contextAttribs = intArrayOf( + EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, + EGL14.EGL_NONE + ) + eglContext = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, contextAttribs, 0) + + val surfaceAttribs = intArrayOf( + EGL14.EGL_WIDTH, width, + EGL14.EGL_HEIGHT, height, + EGL14.EGL_NONE + ) + eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, config, surfaceAttribs, 0) + EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) + } + + 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 fgfCoeffFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FGF_COEFFS_FRAGMENT_SHADER) + fgfCoeffProgramId = GlUtils.linkProgram(vs, fgfCoeffFs) + + val fgfApplyFs = GlUtils.compileShader(GLES30.GL_FRAGMENT_SHADER, Shaders.FGF_APPLY_FRAGMENT_SHADER) + fgfApplyProgramId = GlUtils.linkProgram(vs, fgfApplyFs) + + GLES30.glDeleteShader(vs) + GLES30.glDeleteShader(fs) + GLES30.glDeleteShader(fgfCoeffFs) + GLES30.glDeleteShader(fgfApplyFs) + + vertexBufferId = GlUtils.createBuffer(Shaders.FULL_QUAD_VERTICES) + texCoordBufferId = GlUtils.createBuffer(Shaders.TEXTURE_COORDS) + + val indexBuffer = java.nio.ByteBuffer.allocateDirect(Shaders.DRAW_ORDER.size * 2) + .order(java.nio.ByteOrder.nativeOrder()) + .asShortBuffer() + indexBuffer.put(Shaders.DRAW_ORDER) + indexBuffer.position(0) + val ids = IntArray(1) + GLES30.glGenBuffers(1, ids, 0) + indexBufferId = ids[0] + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glBufferData(GLES30.GL_ELEMENT_ARRAY_BUFFER, Shaders.DRAW_ORDER.size * 2, indexBuffer, GLES30.GL_STATIC_DRAW) + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, 0) + } + + private fun drawQuad(program: Int) { + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, vertexBufferId) + val posLoc = GLES30.glGetAttribLocation(program, "aPosition") + GLES30.glEnableVertexAttribArray(posLoc) + GLES30.glVertexAttribPointer(posLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, texCoordBufferId) + val texLoc = GLES30.glGetAttribLocation(program, "aTexCoord") + GLES30.glEnableVertexAttribArray(texLoc) + GLES30.glVertexAttribPointer(texLoc, 2, GLES30.GL_FLOAT, false, 0, 0) + + GLES30.glBindBuffer(GLES30.GL_ELEMENT_ARRAY_BUFFER, indexBufferId) + GLES30.glDrawElements(GLES30.GL_TRIANGLES, 6, GLES30.GL_UNSIGNED_SHORT, 0) + + GLES30.glDisableVertexAttribArray(posLoc) + GLES30.glDisableVertexAttribArray(texLoc) + } + + private fun releaseGL() { + if (bokehProgramId != 0) GLES30.glDeleteProgram(bokehProgramId) + if (fgfCoeffProgramId != 0) GLES30.glDeleteProgram(fgfCoeffProgramId) + if (fgfApplyProgramId != 0) GLES30.glDeleteProgram(fgfApplyProgramId) + if (vertexBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(vertexBufferId), 0) + if (texCoordBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(texCoordBufferId), 0) + if (indexBufferId != 0) GLES30.glDeleteBuffers(1, intArrayOf(indexBufferId), 0) + + if (eglDisplay != EGL14.EGL_NO_DISPLAY) { + EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) + EGL14.eglDestroySurface(eglDisplay, eglSurface) + EGL14.eglDestroyContext(eglDisplay, eglContext) + EGL14.eglTerminate(eglDisplay) + } + eglDisplay = EGL14.EGL_NO_DISPLAY + eglContext = EGL14.EGL_NO_CONTEXT + eglSurface = EGL14.EGL_NO_SURFACE + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt index 361326cf..4ec17e63 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt @@ -6,7 +6,6 @@ import android.graphics.PointF import android.graphics.SurfaceTexture import android.opengl.GLSurfaceView import android.util.AttributeSet -import android.util.Log import android.view.Surface import com.hinnka.mycamera.livephoto.LivePhotoRecorder import com.hinnka.mycamera.lut.LutConfig @@ -32,6 +31,7 @@ class CameraGLSurfaceView @JvmOverloads constructor( var onHistogramUpdated: ((IntArray) -> Unit)? = null var onMeteringUpdated: ((Double, Double) -> Unit)? = null + var onDepthInputAvailable: ((Bitmap) -> Unit)? = null var onSurfaceReady: ((Surface) -> Unit)? = null var onSurfaceDestroyed: (() -> Unit)? = null @@ -72,6 +72,10 @@ class CameraGLSurfaceView @JvmOverloads constructor( onMeteringUpdated?.invoke(totalWeight, weightedSumLuminance) } + renderer.onDepthInputAvailable = { bitmap -> + onDepthInputAvailable?.invoke(bitmap) + } + // 保持 EGL 上下文 preserveEGLContextOnPause = true @@ -158,9 +162,9 @@ class CameraGLSurfaceView @JvmOverloads constructor( } /** - * 设置色彩配方参数 + * 设置参数 */ - fun setColorRecipeParams( + fun setParams( exposure: Float, contrast: Float, saturation: Float, @@ -178,6 +182,7 @@ class CameraGLSurfaceView @JvmOverloads constructor( lowRes: Float, halation: Float, lutIntensity: Float, + aperture: Float, ) { renderer.exposure = exposure renderer.contrast = contrast @@ -196,6 +201,7 @@ class CameraGLSurfaceView @JvmOverloads constructor( renderer.lowRes = lowRes renderer.halation = halation renderer.lutIntensity = lutIntensity + renderer.aperture = aperture requestRender() } @@ -235,6 +241,21 @@ class CameraGLSurfaceView @JvmOverloads constructor( renderer.livePhotoRecorder = recorder } + /** + * 设置实时景深图 + */ + fun setDepthMap(bitmap: Bitmap?) { + renderer.depthMap = bitmap + } + + /** + * 设置光圈 (虚化强度) + */ + fun setAperture(value: Float) { + renderer.aperture = value + requestRender() + } + override fun onPause() { super.onPause() PLog.d(TAG, "onPause") diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraParameterBar.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraParameterBar.kt index d44985f1..9910744a 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraParameterBar.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraParameterBar.kt @@ -59,10 +59,11 @@ fun CameraParameterBar( ) ParameterItem( label = "Av", - value = String.format("f/%.1f", state.aperture), + value = String.format("f/%.1f", if (state.isVirtualApertureEnabled) state.virtualAperture else state.physicalAperture), labelColor = yellow, + valueColor = if (state.isVirtualApertureEnabled) Color(0xFF00E5FF) else null, // 开启虚拟光圈时显示青色 isSelected = selectedParameter == CameraParameter.APERTURE, - isEnabled = false, // Usually fixed on mobile cameras + isEnabled = true, // Enabled for computational bokeh onClick = { onParameterClick(CameraParameter.APERTURE) } ) ParameterItem( diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt index 48c793b5..2b312005 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraPreviewGL.kt @@ -17,7 +17,6 @@ import androidx.compose.ui.viewinterop.AndroidView import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.livephoto.LivePhotoRecorder import com.hinnka.mycamera.lut.LutConfig -import com.hinnka.mycamera.lut.LutRenderer import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.ui.components.FocusIndicator import com.hinnka.mycamera.utils.OrientationObserver @@ -44,8 +43,10 @@ fun CameraPreviewGL( onTap: (Float, Float, Int, Int) -> Unit, onHistogramUpdated: ((IntArray) -> Unit)? = null, onMeteringUpdated: ((Double, Double) -> Unit)? = null, + onDepthInputAvailable: ((android.graphics.Bitmap) -> Unit)? = null, livePhotoRecorder: LivePhotoRecorder? = null, onGLSurfaceViewReady: ((CameraGLSurfaceView) -> Unit)? = null, + aperture: Float = 0f, modifier: Modifier = Modifier ) { val rotationDegrees = OrientationObserver.rotationDegrees @@ -126,6 +127,7 @@ fun CameraPreviewGL( glSurfaceView.onHistogramUpdated = { onHistogramUpdated?.invoke(it) } glSurfaceView.onMeteringUpdated = { w, l -> onMeteringUpdated?.invoke(w, l) } + glSurfaceView.onDepthInputAvailable = { onDepthInputAvailable?.invoke(it) } viewWidth = glSurfaceView.width viewHeight = glSurfaceView.height @@ -155,30 +157,32 @@ fun CameraPreviewGL( glSurfaceView.setLut(currentLut) glSurfaceView.setLutEnabled(true) glSurfaceView.setColorRecipeEnabled(colorRecipeEnabled) - glSurfaceView.setColorRecipeParams( - exposure = colorRecipeParams.exposure, - contrast = colorRecipeParams.contrast, - saturation = colorRecipeParams.saturation, - temperature = colorRecipeParams.temperature, - tint = colorRecipeParams.tint, - fade = colorRecipeParams.fade, - vibrance = colorRecipeParams.color, - highlights = colorRecipeParams.highlights, - shadows = colorRecipeParams.shadows, - filmGrain = colorRecipeParams.filmGrain, - vignette = colorRecipeParams.vignette, - bleachBypass = colorRecipeParams.bleachBypass, - chromaticAberration = colorRecipeParams.chromaticAberration, - noise = colorRecipeParams.noise, - lowRes = colorRecipeParams.lowRes, - halation = colorRecipeParams.halation, - lutIntensity = colorRecipeParams.lutIntensity, - ) } else { glSurfaceView.setLutEnabled(false) glSurfaceView.setColorRecipeEnabled(false) } + glSurfaceView.setParams( + exposure = colorRecipeParams.exposure, + contrast = colorRecipeParams.contrast, + saturation = colorRecipeParams.saturation, + temperature = colorRecipeParams.temperature, + tint = colorRecipeParams.tint, + fade = colorRecipeParams.fade, + vibrance = colorRecipeParams.color, + highlights = colorRecipeParams.highlights, + shadows = colorRecipeParams.shadows, + filmGrain = colorRecipeParams.filmGrain, + vignette = colorRecipeParams.vignette, + bleachBypass = colorRecipeParams.bleachBypass, + chromaticAberration = colorRecipeParams.chromaticAberration, + noise = colorRecipeParams.noise, + lowRes = colorRecipeParams.lowRes, + halation = colorRecipeParams.halation, + lutIntensity = colorRecipeParams.lutIntensity, + aperture = aperture, + ) + glSurfaceView.setFocusPoint(focusPoint?.let { android.graphics.PointF( it.first / viewWidth, diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt index 742e7d89..0f41c07d 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -348,10 +348,12 @@ fun CameraScreen( }, onHistogramUpdated = { viewModel.handleHistogramUpdate(it) }, onMeteringUpdated = { w, l -> viewModel.handleMeteringUpdate(w, l) }, + onDepthInputAvailable = { viewModel.handleDepthMapUpdate(it) }, onGLSurfaceViewReady = { viewModel.glSurfaceView = it }, livePhotoRecorder = viewModel.livePhotoRecorder, + aperture = if (state.isVirtualApertureEnabled) state.virtualAperture else 0f, modifier = Modifier.fillMaxSize() ) @@ -454,32 +456,32 @@ fun CameraScreen( CameraParameter.EXPOSURE_COMPENSATION -> state.exposureCompensation * state.getExposureCompensationStep() CameraParameter.SHUTTER_SPEED -> state.shutterSpeed.toFloat() CameraParameter.ISO -> state.iso.toFloat() - CameraParameter.APERTURE -> state.aperture + CameraParameter.APERTURE -> if (state.isVirtualApertureEnabled) state.virtualAperture else state.physicalAperture CameraParameter.WHITE_BALANCE -> state.awbTemperature.toFloat() }, minValue = when (selectedParameter) { CameraParameter.EXPOSURE_COMPENSATION -> state.getExposureCompensationRange().lower * state.getExposureCompensationStep() CameraParameter.SHUTTER_SPEED -> state.getShutterSpeedRange().lower.toFloat() CameraParameter.ISO -> state.getIsoRange().lower.toFloat() - CameraParameter.APERTURE -> state.aperture // Fixed + CameraParameter.APERTURE -> 1f // Min synthetic aperture CameraParameter.WHITE_BALANCE -> 2000f }, maxValue = when (selectedParameter) { CameraParameter.EXPOSURE_COMPENSATION -> state.getExposureCompensationRange().upper * state.getExposureCompensationStep() CameraParameter.SHUTTER_SPEED -> state.getShutterSpeedRange().upper.toFloat() CameraParameter.ISO -> state.getIsoRange().upper.toFloat() - CameraParameter.APERTURE -> state.aperture // Fixed + CameraParameter.APERTURE -> 16.0f // Max synthetic aperture CameraParameter.WHITE_BALANCE -> 10000f }, isAdjustable = when (selectedParameter) { CameraParameter.EXPOSURE_COMPENSATION -> state.isAutoExposure CameraParameter.SHUTTER_SPEED -> !state.isShutterSpeedAuto CameraParameter.ISO -> !state.isIsoAuto - CameraParameter.APERTURE -> false + CameraParameter.APERTURE -> state.isVirtualApertureEnabled CameraParameter.WHITE_BALANCE -> state.awbMode != android.hardware.camera2.CameraMetadata.CONTROL_AWB_MODE_AUTO }, showAutoButton = when (selectedParameter) { - CameraParameter.SHUTTER_SPEED, CameraParameter.ISO, CameraParameter.WHITE_BALANCE -> true + CameraParameter.SHUTTER_SPEED, CameraParameter.ISO, CameraParameter.WHITE_BALANCE, CameraParameter.APERTURE -> true else -> false }, onValueChange = { value -> @@ -487,7 +489,7 @@ fun CameraScreen( CameraParameter.EXPOSURE_COMPENSATION -> viewModel.setExposureCompensation((value / state.getExposureCompensationStep()).roundToInt()) CameraParameter.SHUTTER_SPEED -> viewModel.setShutterSpeed(value.toLong()) CameraParameter.ISO -> viewModel.setIso(value.toInt()) - CameraParameter.APERTURE -> {} // Not adjustable + CameraParameter.APERTURE -> viewModel.setAperture(value) CameraParameter.WHITE_BALANCE -> viewModel.setAwbTemperature(value.toInt()) } }, @@ -502,7 +504,7 @@ fun CameraScreen( viewModel.setAwbMode(android.hardware.camera2.CameraMetadata.CONTROL_AWB_MODE_AUTO) } } - + CameraParameter.APERTURE -> viewModel.setVirtualApertureAuto(!state.isVirtualApertureEnabled) else -> {} } }, diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/ParameterRuler.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/ParameterRuler.kt index 2f07bc53..a531535f 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/ParameterRuler.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/ParameterRuler.kt @@ -444,11 +444,34 @@ private fun getScaleValues(parameter: CameraParameter, minValue: Float, maxValue } CameraParameter.APERTURE -> { - // Aperture values (usually fixed on mobile) - val step = 0.5f - generateSequence(minValue) { it + step } - .takeWhile { it <= maxValue } - .toList() + listOf( + minValue, + 1f, + 1.4f, + 1.8f, + 2f, + 2.4f, + 2.8f, + 3.2f, + 3.5f, + 4f, + 4.5f, + 5f, + 5.6f, + 6.3f, + 7.1f, + 8f, + 9f, + 10f, + 11f, + 13f, + 14f, + 16f, + maxValue + ) + .toSet() + .map { it } + .filter { it in minValue..maxValue } } } } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/SliderSettingItem.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/SliderSettingItem.kt index 16ebfae2..90d6e3ce 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/components/SliderSettingItem.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/SliderSettingItem.kt @@ -1,10 +1,18 @@ package com.hinnka.mycamera.ui.components -import androidx.compose.foundation.layout.* -import androidx.compose.material3.Text +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp @@ -20,8 +28,11 @@ fun SliderSettingItem( value: Float, valueRange: ClosedFloatingPointRange, onValueChange: (Float) -> Unit, + toggleValue: Boolean? = null, + onToggleChange: (Boolean) -> Unit = {}, modifier: Modifier = Modifier ) { + val enabled = toggleValue ?: true Column( modifier = modifier .fillMaxWidth() @@ -29,7 +40,6 @@ fun SliderSettingItem( ) { Row( modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( @@ -38,12 +48,33 @@ fun SliderSettingItem( fontSize = 16.sp, fontWeight = FontWeight.Normal ) - Text( - text = String.format("%.2f", value), - color = Color.White.copy(alpha = 0.8f), - fontSize = 14.sp, - fontWeight = FontWeight.Medium - ) + + if (toggleValue != null) { + Spacer(modifier = Modifier.width(8.dp)) + Switch( + checked = toggleValue, + onCheckedChange = onToggleChange, + modifier = Modifier.scale(0.7f).size(40.dp, 24.dp), + colors = SwitchDefaults.colors( + checkedThumbColor = Color.White, + checkedTrackColor = Color(0xFFFF6B35), + uncheckedThumbColor = Color.Gray, + uncheckedTrackColor = Color.White.copy(alpha = 0.2f), + uncheckedBorderColor = Color.Transparent + ) + ) + } + + Spacer(modifier = Modifier.weight(1f)) + + if (enabled) { + Text( + text = String.format("%.2f", value), + color = Color.White.copy(alpha = 0.8f), + fontSize = 14.sp, + fontWeight = FontWeight.Medium + ) + } } description?.let { @@ -56,15 +87,17 @@ fun SliderSettingItem( ) } - Spacer(modifier = Modifier.height(8.dp)) + if (enabled) { + Spacer(modifier = Modifier.height(8.dp)) - CustomSliderThinThumb( - value = value, - onValueChange = onValueChange, - valueRange = valueRange, - thumbColor = Color.White, - activeTrackColor = Color(0xFFFF6B35), - inactiveTrackColor = Color.White.copy(alpha = 0.2f) - ) + CustomSliderThinThumb( + value = value, + onValueChange = onValueChange, + valueRange = valueRange, + thumbColor = Color.White, + activeTrackColor = Color(0xFFFF6B35), + inactiveTrackColor = Color.White.copy(alpha = 0.2f) + ) + } } } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/SwitchSettingItem.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/SwitchSettingItem.kt new file mode 100644 index 00000000..5eeae6bc --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/SwitchSettingItem.kt @@ -0,0 +1,66 @@ +package com.hinnka.mycamera.ui.components + +import androidx.compose.foundation.layout.* +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.hinnka.mycamera.ui.theme.AccentOrange + +/** + * 开关设置项 + */ +@Composable +fun SwitchSettingItem( + title: String, + description: String? = null, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + Column( + modifier = modifier + .fillMaxWidth() + .padding(vertical = 8.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + color = Color.White, + fontSize = 16.sp, + fontWeight = FontWeight.Normal + ) + description?.let { + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = it, + color = Color.White.copy(alpha = 0.6f), + fontSize = 13.sp, + lineHeight = 18.sp + ) + } + } + + Switch( + checked = checked, + onCheckedChange = onCheckedChange, + colors = SwitchDefaults.colors( + checkedThumbColor = Color.White, + checkedTrackColor = AccentOrange, + uncheckedThumbColor = Color.Gray, + uncheckedTrackColor = Color.White.copy(alpha = 0.2f), + uncheckedBorderColor = Color.Transparent + ) + ) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt index 5f901955..be9f761a 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt @@ -58,6 +58,7 @@ import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.viewmodel.CameraViewModel import com.hinnka.mycamera.viewmodel.GalleryViewModel import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -109,6 +110,10 @@ fun PhotoEditScreen( val editSharpening by viewModel.editSharpening.collectAsState() val editNoiseReduction by viewModel.editNoiseReduction.collectAsState() val editChromaNoiseReduction by viewModel.editChromaNoiseReduction.collectAsState() + + val editComputationalAperture by viewModel.editComputationalAperture.collectAsState() + val editFocusX by viewModel.editFocusPointX.collectAsState() + val editFocusY by viewModel.editFocusPointY.collectAsState() val droMode by cameraViewModel.droMode.collectAsState() val colorSpace by cameraViewModel.colorSpace.collectAsState() @@ -143,6 +148,9 @@ fun PhotoEditScreen( editSharpening, editNoiseReduction, editChromaNoiseReduction, + editComputationalAperture, + editFocusX, + editFocusY, showOrigin ) { if (currentPhoto == null) return@LaunchedEffect @@ -340,8 +348,36 @@ fun PhotoEditScreen( // 如果既没有多指操作也没有明显位移,才根据结果执行逻辑 if (!isMultiTouch && !isMoved) { if (upEvent != null) { - // 快速点击:切换控制区域显隐 - showControls = !showControls + // 快速点击:切换控制区域显隐,或者调整景深焦点 + if (editTab == 1 && viewModel.editComputationalAperture.value != null && previewBitmap != null) { + val tapPosition = upEvent.changes[0].position + val boxWidth = size.width.toFloat() + val boxHeight = size.height.toFloat() + val imageRatio = previewBitmap!!.width.toFloat() / previewBitmap!!.height.toFloat() + val boxRatio = boxWidth / boxHeight + + var imageDisplayWidth = boxWidth + var imageDisplayHeight = boxHeight + if (imageRatio > boxRatio) { + imageDisplayHeight = boxWidth / imageRatio + } else { + imageDisplayWidth = boxHeight * imageRatio + } + + val offsetX = (boxWidth - imageDisplayWidth) / 2f + val offsetY = (boxHeight - imageDisplayHeight) / 2f + + val relativeX = (tapPosition.x - offsetX) / imageDisplayWidth + val relativeY = (tapPosition.y - offsetY) / imageDisplayHeight + + if (relativeX in 0f..1f && relativeY in 0f..1f) { + viewModel.setFocusPoint(relativeX, relativeY) + } else { + showControls = !showControls + } + } else { + showControls = !showControls + } } else { // 确认为长按:显示原图 showOrigin = true @@ -559,6 +595,20 @@ fun PhotoEditScreen( } else if (editTab == 1) { Spacer(modifier = Modifier.height(16.dp)) // 细节处理调整 (锐化, 降噪, 杂色降噪) + SliderSettingItem( + title = stringResource(R.string.virtual_aperture), + value = editComputationalAperture ?: 2.8f, + valueRange = 1.0f..16.0f, + onValueChange = { viewModel.setComputationalAperture(it) }, + toggleValue = editComputationalAperture != null, + onToggleChange = { checked -> + if (checked) { + viewModel.setComputationalAperture(2.8f) + } else { + viewModel.setComputationalAperture(null) + } + } + ) SliderSettingItem( title = stringResource(R.string.settings_sharpening), value = editSharpening, @@ -874,6 +924,11 @@ private fun RawEditPanel( availableRawLuts = listOf("none") + viewModel.getAvailableRawLutList(context, editLogCurve) } + val droOff = stringResource(R.string.settings_dro_off) + val droLow = stringResource(R.string.settings_dro_low) + val droHigh = stringResource(R.string.settings_dro_high) + val none = stringResource(R.string.none) + Column( modifier = modifier .fillMaxWidth() @@ -883,14 +938,14 @@ private fun RawEditPanel( // DRO Mode SegmentedControl( title = stringResource(R.string.settings_dro_mode), - items = MeteringSystem.DROMode.values().toList(), + items = MeteringSystem.DROMode.entries, selectedItem = editDroMode, onItemSelected = { viewModel.setDroMode(it.name) }, itemLabel = { when (it) { - MeteringSystem.DROMode.OFF -> context.getString(R.string.settings_dro_off) - MeteringSystem.DROMode.LOW -> context.getString(R.string.settings_dro_low) - MeteringSystem.DROMode.HIGH -> context.getString(R.string.settings_dro_high) + MeteringSystem.DROMode.OFF -> droOff + MeteringSystem.DROMode.LOW -> droLow + MeteringSystem.DROMode.HIGH -> droHigh } } ) @@ -919,7 +974,7 @@ private fun RawEditPanel( items = availableRawLuts, selectedItem = editRawLut ?: "none", onItemSelected = { viewModel.setRawLut(editLogCurve, it) }, - itemLabel = { if (it == "none") context.getString(R.string.none) else it.substringBeforeLast(".") } + itemLabel = { if (it == "none") none else it.substringBeforeLast(".") } ) } } diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 1598c88f..44d941bc 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -405,9 +405,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } - // 监听相机状态,用于首次启动应用默认焦段 + // 监听相机状态,用于同步预览渲染参数 viewModelScope.launch { state.collect { currentState -> + // 同步焦段 val availableCameras = currentState.availableCameras if (availableCameras.isNotEmpty() && !hasAppliedDefaultFocalLength) { val prefs = userPreferencesRepository.userPreferences.firstOrNull() @@ -417,6 +418,25 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } hasAppliedDefaultFocalLength = true } + + // 同步虚化参数到渲染器 + glSurfaceView?.let { view -> + if (currentState.isVirtualApertureEnabled) { + view.setAperture(currentState.virtualAperture) + } else { + view.setAperture(0f) + } + currentState.focusPoint?.let { fp -> + view.setFocusPoint(android.graphics.PointF(fp.first, fp.second)) + } + } + } + } + + // 实时景深处理 + viewModelScope.launch { + cameraController.previewDepthProcessor.latestDepthMap.collect { depth -> + glSurfaceView?.setDepthMap(depth) } } } @@ -596,6 +616,20 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.setShutterSpeed(value) } + /** + * 设置计算光圈 (等效虚化) + */ + fun setAperture(value: Float) { + cameraController.setAperture(value) + } + + /** + * 设置是否开启虚拟光圈 (等效虚化控制) + */ + fun setVirtualApertureAuto(enabled: Boolean) { + cameraController.setVirtualApertureEnabled(enabled) + } + /** * 设置变焦倍数 */ @@ -958,6 +992,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.calculateAutoMetering(totalWeight, weightedSumLuminance) } + fun handleDepthMapUpdate(bitmap: android.graphics.Bitmap) { + cameraController.previewDepthProcessor.processBitmap(bitmap) + } + // ==================== 边框相关方法 ==================== /** @@ -1504,6 +1542,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val shouldMirror = lensFacing == CameraCharacteristics.LENS_FACING_FRONT && (userPreferencesRepository.userPreferences.firstOrNull()?.mirrorFrontCamera ?: true) + val aperture = if (state.value.isVirtualApertureEnabled) state.value.virtualAperture else null + // 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息 val metadata = PhotoMetadata( lutId = lutIdToSave, @@ -1530,7 +1570,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) exposureBias = state.value.exposureBias, droMode = droModeString, isMirrored = shouldMirror, - colorSpace = captureInfo.colorSpace + colorSpace = captureInfo.colorSpace, + computationalAperture = aperture, + focusPointX = state.value.focusPoint?.first, + focusPointY = state.value.focusPoint?.second ) val livePhotoVideoDeferred = if (useLivePhoto.value) { @@ -1627,6 +1670,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val useSuperRes = useSuperResolution.value + val aperture = if (state.value.isVirtualApertureEnabled) state.value.virtualAperture else null + // 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息 val metadata = PhotoMetadata( lutId = lutIdToSave, @@ -1653,7 +1698,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) exposureBias = state.value.exposureBias, droMode = droModeString, isMirrored = shouldMirror, - colorSpace = captureInfo.colorSpace + colorSpace = captureInfo.colorSpace, + computationalAperture = aperture, + focusPointX = state.value.focusPoint?.first, + focusPointY = state.value.focusPoint?.second ) val livePhotoVideoDeferred = if (useLivePhoto.value) { @@ -1738,6 +1786,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val shouldMirror = lensFacing == CameraCharacteristics.LENS_FACING_FRONT && (userPreferencesRepository.userPreferences.firstOrNull()?.mirrorFrontCamera ?: true) + val aperture = if (state.value.isVirtualApertureEnabled) state.value.virtualAperture else null + // 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息 val metadata = PhotoMetadata( lutId = lutIdToSave, @@ -1762,7 +1812,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) focalLength35mm = captureInfo.formatFocalLength35mm(), aperture = captureInfo.formatAperture(), isMirrored = shouldMirror, - colorSpace = captureInfo.colorSpace + colorSpace = captureInfo.colorSpace, + computationalAperture = aperture, + focusPointX = state.value.focusPoint?.first, + focusPointY = state.value.focusPoint?.second ) PhotoManager.preparePhoto( diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index e6b5fb71..e043c3a6 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -8,25 +8,20 @@ import android.graphics.BitmapFactory import android.net.Uri import android.os.Build import android.provider.MediaStore -import android.util.Log import android.util.LruCache -import androidx.collection.MutableIntFloatMap -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateListOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.* import androidx.compose.runtime.snapshots.SnapshotStateMap import androidx.core.content.FileProvider +import androidx.core.graphics.scale +import androidx.core.net.toUri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.hinnka.mycamera.data.ContentRepository -import com.hinnka.mycamera.data.UserPreferencesRepository import com.hinnka.mycamera.frame.FrameInfo -import com.hinnka.mycamera.frame.FrameRenderer -import com.hinnka.mycamera.gallery.* +import com.hinnka.mycamera.gallery.PhotoData +import com.hinnka.mycamera.gallery.PhotoManager +import com.hinnka.mycamera.gallery.PhotoMetadata import com.hinnka.mycamera.lut.LutConfig -import com.hinnka.mycamera.lut.LutImageProcessor import com.hinnka.mycamera.lut.LutInfo import com.hinnka.mycamera.lut.PhotoTransformation import com.hinnka.mycamera.model.ColorRecipeParams @@ -35,10 +30,7 @@ import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import java.io.File import java.io.FileOutputStream -import java.util.* import kotlin.math.max -import androidx.core.net.toUri -import androidx.core.graphics.scale /** * 相册 Tab @@ -230,6 +222,60 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) var editChromaNoiseReduction = MutableStateFlow(0f) private set + // Computational Bokeh editing state + var editComputationalAperture = MutableStateFlow(null) + private set + var editFocusPointX = MutableStateFlow(null) + private set + var editFocusPointY = MutableStateFlow(null) + private set + + private var bokehJob: Job? = null + + fun setComputationalAperture(value: Float?) { + editComputationalAperture.value = value + updateBokehPhoto() + } + + fun setFocusPoint(x: Float, y: Float) { + editFocusPointX.value = x + editFocusPointY.value = y + updateBokehPhoto() + } + + private fun updateBokehPhoto() { + bokehJob?.cancel() + bokehJob = viewModelScope.launch(Dispatchers.IO) { + val context = getApplication() + val aperture = editComputationalAperture.value + val focusPointX = editFocusPointX.value + val focusPointY = editFocusPointY.value + val photoData = getCurrentPhoto() ?: return@launch + val bitmap = PhotoManager.loadOriginalBitmap(context, photoData.id) ?: return@launch + if (!isActive) return@launch + val bokeh = aperture?.let { + contentRepository.depthBokehProcessor.applyHighQualityBokeh( + context, + photoData.id, + bitmap, + focusPointX, + focusPointY, + it + ) + } ?: bitmap + if (!isActive) return@launch + PhotoManager.saveBokehPhoto(context, photoData.id, bokeh) + photoRefreshKeys[photoData.id] = System.currentTimeMillis() + } + } + + fun hasDepthInfo(photo: PhotoData?): Boolean { + if (photo == null) return false + if (selectedTab == GalleryTab.SYSTEM) return false + val context = getApplication() + return PhotoManager.getDepthFile(context, photo.id).exists() + } + // 最新照片(用于相机界面显示入口) private val _latestPhoto = MutableStateFlow(null) val latestPhoto: StateFlow = _latestPhoto.asStateFlow() @@ -1107,6 +1153,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) editChromaNoiseReduction.value = metadata.chromaNoiseReduction ?: (if (metadata.isImported) 0f else chromaNoiseReduction.value) + + editComputationalAperture.value = metadata.computationalAperture + editFocusPointX.value = metadata.focusPointX + editFocusPointY.value = metadata.focusPointY } ?: run { editLutId.value = null editFrameId.value = null @@ -1114,6 +1164,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) editSharpening.value = sharpening.value editNoiseReduction.value = noiseReduction.value editChromaNoiseReduction.value = chromaNoiseReduction.value + + editComputationalAperture.value = null + editFocusPointX.value = null + editFocusPointY.value = null } // 加载当前编辑的 LUT 配置 @@ -1225,6 +1279,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) ?: (if (metadata.isImported) 0f else chromaNoiseReduction.value) return PhotoTransformation( + context = getApplication(), metadata = metadata, photoProcessor = contentRepository.photoProcessor, sharpening = photoSharpening, @@ -1236,8 +1291,15 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) /** * 生成预览缓存 key */ - private fun previewCacheKey(photoId: String, metadataHash: Int, refreshKey: Long): String { - return "${photoId}_${metadataHash}_${refreshKey}" + private fun previewCacheKey(photoData: PhotoData, metadata: PhotoMetadata, showOrigin: Boolean): String { + val photoId = photoData.id + val metadataHash = metadata.toJson().hashCode() + val refreshKey = photoRefreshKeys[photoId] ?: 0L + return if (showOrigin) { + "${photoId}_${refreshKey}" + } else { + "${photoId}_${metadataHash}_${refreshKey}" + } } /** @@ -1281,7 +1343,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) colorRecipeParams = editLutRecipeParams.value, sharpening = editSharpening.value, noiseReduction = editNoiseReduction.value, - chromaNoiseReduction = editChromaNoiseReduction.value + chromaNoiseReduction = editChromaNoiseReduction.value, + computationalAperture = editComputationalAperture.value, + focusPointX = editFocusPointX.value, + focusPointY = editFocusPointY.value ) finalS = editSharpening.value finalNR = editNoiseReduction.value @@ -1298,50 +1363,36 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } // 使用多级缓存优化性能 - val refreshKey = photoRefreshKeys[photo.id] ?: 0L - val metadataHash = metadata.toJson().hashCode() + val previewCacheKey = previewCacheKey(photo, finalMetadata, showOrigin) - // 1. 完全处理后的预览图缓存 (LUT + 边框已应用) - val previewCacheKey = if (!useGlobalEdit && !showOrigin && bitmap == null) { - previewCacheKey(photo.id, metadataHash, refreshKey) - } else null - - previewCacheKey?.let { - val cached = previewBitmapCache.get(it) - if (cached != null && !cached.isRecycled) { - return@withContext cached - } + val cached = previewBitmapCache.get(previewCacheKey) + if (cached != null && !cached.isRecycled) { + return@withContext cached } // 2. 原始底图缓存 (4096px 状态,用于快速重新应用编辑) - val sourceCacheKey = "${photo.id}_source_${refreshKey}" - val currentBitmap = bitmap ?: previewBitmapCache.get(sourceCacheKey) ?: run { - val loaded = if (selectedTab == GalleryTab.PHOTON) { - PhotoManager.loadBitmap(context, photo.id, 4096) - } else { - PhotoManager.loadBitmap(context, photo.uri, 4096) - } - if (loaded != null) { - previewBitmapCache.put(sourceCacheKey, loaded) - } - loaded + val currentBitmap = bitmap ?: if (selectedTab == GalleryTab.PHOTON) { + PhotoManager.loadBitmap(context, photo.id, 4096) + } else { + PhotoManager.loadBitmap(context, photo.uri, 4096) } ?: return@withContext null + previewBitmapCache.put(previewCacheKey(photo, finalMetadata, true), currentBitmap) + if (showOrigin) { currentBitmap } else { // 预览生成 val result = contentRepository.photoProcessor.processBitmap( - currentBitmap, finalMetadata, - finalS, finalNR, finalCNR + context, photo.id, currentBitmap, finalMetadata, + finalS, finalNR, finalCNR, + false ) // 估计平均亮度 currentBrightness[photo.id] = estimateAverageBrightness(result) // 存入缓存 - if (previewCacheKey != null) { - previewBitmapCache.put(previewCacheKey, result) - } + previewBitmapCache.put(previewCacheKey, result) result } @@ -1399,6 +1450,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) sharpening = editSharpening.value, noiseReduction = editNoiseReduction.value, chromaNoiseReduction = editChromaNoiseReduction.value, + computationalAperture = editComputationalAperture.value, + focusPointX = editFocusPointX.value, + focusPointY = editFocusPointY.value, ) ?: run { onComplete(false) return@launch diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index f870620f..e6e87a35 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -390,4 +390,6 @@ 影像 幻影 关于 + 光圈 + 虚拟光圈 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7e8cc286..939aba83 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -390,4 +390,6 @@ Imaging Phantom About + Aperture + Virtual Aperture