camera: fix bokeh
- Commit
50b03547de6ee2ed84cd7ecb7a2d76596d4e4c65- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-25 05:24 UTC (4 months ago)
- Parents
11e207b
Diff
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 2ebea87863..337726620c 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -210,7 +210,7 @@ private enum class CameraSetting { } /** Which camera pipeline drives the preview for the current mode. */-private enum class SessionKind { PHOTO, PANORAMA, HIGH_SPEED, VIDEO }+private enum class SessionKind { PHOTO, PORTRAIT, PANORAMA, HIGH_SPEED, VIDEO } private fun Modifier.selectedPill( selected: Boolean,@@ -268,10 +268,12 @@ fun CameraScreen( val isSloMo = cameraMode == CameraMode.SLOW_MO val isVideoType = cameraMode == CameraMode.VIDEO || cameraMode == CameraMode.TIMELAPSE || cameraMode == CameraMode.CINEMATIC val isPanoType = cameraMode == CameraMode.PANORAMA || cameraMode == CameraMode.PHOTOSPHERE+ val isPortrait = cameraMode == CameraMode.PORTRAIT val sessionKind = when { isSloMo -> SessionKind.HIGH_SPEED isVideoType -> SessionKind.VIDEO isPanoType -> SessionKind.PANORAMA+ isPortrait -> SessionKind.PORTRAIT else -> SessionKind.PHOTO } val highSpeedActive by viewModel.highSpeedActive.collectAsState()@@ -404,22 +406,43 @@ fun CameraScreen( // Owns the PORTRAIT bokeh segmenter so it is closed (and its mask recycled) on mode change. // Keyed on photoSessionActive (re-attach after a rebind) and lensFacing (front/back changes // the frame orientation/mirroring the analyzer must apply).+ // Runs on dedicated bokeh executor so main thread stays free for preview rendering.+ // Final capture ImageCapture is still max-res – only analysis is capped.+ // Mask callback comes from bokeh thread; post recycle+set to main to avoid racing with+ // the RenderEffect reading the previous Bitmap on the UI thread.+ val mainHandler = remember { android.os.Handler(android.os.Looper.getMainLooper()) } DisposableEffect(cameraMode, photoSessionActive, lensFacing) { val analyzer = if (cameraMode == CameraMode.PORTRAIT) { BokehAnalyzer( context, isFrontFacing = lensFacing == CameraSelector.LENS_FACING_FRONT ) { mask ->- maskBitmap?.recycle()- maskBitmap = mask+ if (mask.isRecycled) return@BokehAnalyzer+ mainHandler.post {+ // If mask was recycled while message queued, drop it+ if (mask.isRecycled) return@post+ val prev = maskBitmap+ if (prev != null && prev !== mask && !prev.isRecycled) {+ try { prev.recycle() } catch (_: Exception) {}+ }+ maskBitmap = mask+ } }.also {- viewModel.setImageAnalyzer(it)+ viewModel.setBokehAnalyzer(it) } } else null onDispose {+ viewModel.setImageAnalyzer(null) analyzer?.close()- maskBitmap?.recycle()- maskBitmap = null+ // Post recycle to avoid racing with graphicsLayer reading maskBitmap+ mainHandler.post {+ maskBitmap?.let { bmp ->+ if (!bmp.isRecycled) {+ try { bmp.recycle() } catch (_: Exception) {}+ }+ }+ maskBitmap = null+ } } } @@ -435,6 +458,7 @@ fun CameraScreen( SessionKind.HIGH_SPEED -> viewModel.setupHighSpeedSession() SessionKind.VIDEO -> viewModel.setupVideoSession() SessionKind.PANORAMA -> viewModel.setupPanoramaSession()+ SessionKind.PORTRAIT -> viewModel.setupPortraitSession() SessionKind.PHOTO -> if (useNightPreview) viewModel.setupNightPreviewSession() else viewModel.setupPhotoSession()@@ -547,43 +571,54 @@ fun CameraScreen( .then( run { val hasColorAdj = warmth != 0f || shadows != 0f- val hasBokeh = cameraMode == CameraMode.PORTRAIT && maskBitmap != null+ // Snapshot mask bitmap at this composition point – don't !! inside graphicsLayer+ // or a race with DisposableEffect onDispose (null + recycle) causes NPE at 567.+ val currentMask = maskBitmap?.takeIf {+ !it.isRecycled && it.width > 0 && it.height > 0+ }+ val hasBokeh = cameraMode == CameraMode.PORTRAIT && currentMask != null if (hasBokeh || hasColorAdj) { Modifier.graphicsLayer { var effect: RenderEffect? = null if (hasBokeh) {- val mask = maskBitmap!!- val shader = bokehShader.value- val maskShader = BitmapShader(mask, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)- val matrix = Matrix()- matrix.setScale(size.width / mask.width, size.height / mask.height)- maskShader.setLocalMatrix(matrix)- shader.setInputShader("alphaMask", maskShader)- shader.setFloatUniform("blurScale", 0.4f + blurStrength * 1.4f)- effect = RenderEffect.createRuntimeShaderEffect(shader, "cameraInput")+ val localMask = currentMask+ if (localMask != null && !localMask.isRecycled && size.width > 0 && size.height > 0) {+ try {+ val shader = bokehShader.value+ val maskShader = BitmapShader(localMask, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)+ val matrix = Matrix()+ matrix.setScale(size.width / localMask.width, size.height / localMask.height)+ maskShader.setLocalMatrix(matrix)+ shader.setInputShader("alphaMask", maskShader)+ shader.setFloatUniform("blurScale", 0.4f + blurStrength * 1.4f)+ effect = RenderEffect.createRuntimeShaderEffect(shader, "cameraInput")+ } catch (_: Exception) {+ // Mask may be recycled between snapshot and render – skip bokeh this frame+ } }+ } - if (hasColorAdj) {- val colorEffect = RenderEffect.createColorFilterEffect(- ColorMatrixColorFilter(- buildColorAdjustmentMatrix(warmth, shadows)- )+ if (hasColorAdj) {+ val colorEffect = RenderEffect.createColorFilterEffect(+ ColorMatrixColorFilter(+ buildColorAdjustmentMatrix(warmth, shadows) )- effect = if (effect != null) {- RenderEffect.createChainEffect(colorEffect, effect)- } else {- colorEffect- }+ )+ effect = if (effect != null) {+ RenderEffect.createChainEffect(colorEffect, effect)+ } else {+ colorEffect }-- renderEffect = effect?.asComposeRenderEffect() }- } else {- Modifier.graphicsLayer { renderEffect = null }++ renderEffect = effect?.asComposeRenderEffect() }+ } else {+ Modifier.graphicsLayer { renderEffect = null } }- )+ }+ ) .pointerInput(activeSetting) { fun meteringPoint(tapOffset: Offset) = surfaceRequest?.let { request -> val transformed = with(coordinateTransformer) { tapOffset.transform() }
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex 23005825f2..14c5724f90 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -4,12 +4,19 @@ import android.content.Context import android.graphics.Bitmap import android.graphics.Color import android.graphics.Matrix+import android.os.SystemClock import android.util.Log import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.vayunmathur.ncnn.PortraitSegmenter private const val TEMPORAL_WEIGHT = 0.35f+// Throttle segmentation to avoid running more than ~15 fps even if analysis+// delivers faster. KEEP_ONLY_LATEST already drops, but this skips the JNI work early.+private const val MIN_SEGMENT_INTERVAL_MS = 66L+// Preview analysis is now capped to 1024x768, but we still downscale to <=512 max side+// before feeding the 256x256 model to cut toBitmap -> orient allocations.+private const val MAX_PREVIEW_SIDE = 512 class BokehAnalyzer( context: Context,@@ -18,42 +25,93 @@ class BokehAnalyzer( ) : ImageAnalysis.Analyzer { private var prevMask: FloatArray? = null+ private var blurTemp: FloatArray? = null+ private var blurDst: FloatArray? = null+ private var pixelBuffer: IntArray? = null+ private var lastSegmentMs: Long = 0L+ @Volatile private var closed = false private val segmenter = PortraitSegmenter(context) @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class) override fun analyze(imageProxy: ImageProxy) { try {- // toBitmap() returns the raw sensor-oriented buffer; the preview is- // shown in display orientation (and mirrored for the front camera).- // Rotate/mirror the frame to match so the mask lines up instead of- // coming out rotated 90°.- val raw = imageProxy.toBitmap()- val bitmap = orientToDisplay(raw, imageProxy.imageInfo.rotationDegrees)-- // Synchronous forward pass; the analyzer runs on a background executor- // with KEEP_ONLY_LATEST backpressure so blocking here is fine.- val result = segmenter.segment(bitmap)- if (bitmap !== raw) bitmap.recycle()- raw.recycle()+ if (closed) return+ val now = SystemClock.elapsedRealtime()+ if (now - lastSegmentMs < MIN_SEGMENT_INTERVAL_MS) {+ return+ }+ lastSegmentMs = now++ // Raw sensor-oriented buffer; capped to 1024x768 in portrait session,+ // so this is ~0.8MP not 12MP. Full-res final image kept in ImageCapture.+ var frame = imageProxy.toBitmap()+ if (closed) {+ frame.recycle()+ return+ }+ // Immediate downscale to <=512 max side, filter=false to avoid bilinear cost.+ var downscaled = downscaleIfNeeded(frame, MAX_PREVIEW_SIDE)+ if (downscaled !== frame) {+ frame.recycle()+ }+ frame = downscaled++ // Orient to display + mirror for front camera, filter=false (was true = bilinear).+ var oriented = orientToDisplay(frame, imageProxy.imageInfo.rotationDegrees)+ if (oriented !== frame) {+ frame.recycle()+ }+ frame = oriented+ if (closed) {+ frame.recycle()+ return+ }++ // Synchronous forward pass; runs on dedicated bokehExecutor with KEEP_ONLY_LATEST.+ val result = try {+ segmenter.segment(frame)+ } catch (e: IllegalStateException) {+ // PortraitSegmenter is closed – analyzer disposed while frame in-flight+ Log.w("BokehAnalyzer", "segmenter closed mid-frame", e)+ frame.recycle()+ return+ }+ frame.recycle()+ if (closed) return+ val w = result.width val h = result.height- val current = result.mask // foreground probability in [0,1], row-major+ val current = result.mask // foreground prob [0,1], row-major - // Temporal smoothing: blend with previous frame.+ // Temporal smoothing: in-place blend into current array when possible to avoid alloc. val prev = prevMask val smoothed = if (prev != null && prev.size == current.size) {- FloatArray(current.size) { i ->- current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT+ for (i in current.indices) {+ current[i] = current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT }- } else current+ current+ } else {+ current+ } prevMask = smoothed - // Gaussian blur the mask for soft edges.+ // Blur for soft edges – reuses temp/dst buffers. val blurred = blurMask(smoothed, w, h) - val pixels = IntArray(w * h)- for (i in pixels.indices) {- val alpha = (blurred[i].coerceIn(0f, 1f) * 255).toInt()+ // Reuse pixel buffer.+ var pixels = pixelBuffer+ if (pixels == null || pixels.size != w * h) {+ pixels = IntArray(w * h)+ pixelBuffer = pixels+ }+ for (i in 0 until w * h) {+ val v = blurred[i]+ val clamped = when {+ v < 0f -> 0f+ v > 1f -> 1f+ else -> v+ }+ val alpha = (clamped * 255f).toInt() pixels[i] = Color.argb(alpha, 255, 255, 255) } val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)@@ -66,45 +124,116 @@ class BokehAnalyzer( } fun close() {- segmenter.close()+ closed = true+ try { segmenter.close() } catch (_: Exception) {}+ prevMask = null+ blurTemp = null+ blurDst = null+ pixelBuffer = null+ }++ private fun downscaleIfNeeded(src: Bitmap, maxSide: Int): Bitmap {+ val max = maxOf(src.width, src.height)+ if (max <= maxSide) return src+ val scale = maxSide.toFloat() / max+ val newW = (src.width * scale).toInt().coerceAtLeast(1)+ val newH = (src.height * scale).toInt().coerceAtLeast(1)+ // filter=false – nearest/cheap, avoids bilinear alloc cost+ return Bitmap.createScaledBitmap(src, newW, newH, false) } /** * Rotate the sensor-oriented frame into display orientation (and mirror it * horizontally for the front camera) so the produced mask aligns with the * preview, which CameraX renders with that same transform.+ * filter=false to avoid second full-res bilinear alloc. */ private fun orientToDisplay(src: Bitmap, rotationDegrees: Int): Bitmap { if (rotationDegrees == 0 && !isFrontFacing) return src val matrix = Matrix() matrix.postRotate(rotationDegrees.toFloat()) if (isFrontFacing) matrix.postScale(-1f, 1f) // preview mirrors the front lens- return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)+ return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, false) } private fun blurMask(src: FloatArray, w: Int, h: Int): FloatArray { // Two-pass separable Gaussian blur (radius 3, sigma ~1.5)- val kernel = floatArrayOf(0.06f, 0.12f, 0.18f, 0.28f, 0.18f, 0.12f, 0.06f)- val r = 3- val temp = FloatArray(w * h)- // Horizontal pass- for (y in 0 until h) for (x in 0 until w) {- var sum = 0f- for (k in -r..r) {- val sx = (x + k).coerceIn(0, w - 1)- sum += src[y * w + sx] * kernel[k + r]+ // Reuse buffers to avoid per-frame allocs that caused GC pressure.+ val wh = w * h+ var temp = blurTemp+ if (temp == null || temp.size != wh) {+ temp = FloatArray(wh)+ blurTemp = temp+ }+ var dst = blurDst+ if (dst == null || dst.size != wh) {+ dst = FloatArray(wh)+ blurDst = dst+ }++ // Horizontal pass – manual clamp instead of coerceIn in inner loop+ for (y in 0 until h) {+ val row = y * w+ for (x in 0 until w) {+ var sum = 0f+ var sx: Int+ // k = -3+ sx = x - 3+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.06f+ // k = -2+ sx = x - 2+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.12f+ // k = -1+ sx = x - 1+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.18f+ // k = 0+ sum += src[row + x] * 0.28f+ // k = 1+ sx = x + 1+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.18f+ // k = 2+ sx = x + 2+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.12f+ // k = 3+ sx = x + 3+ if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+ sum += src[row + sx] * 0.06f++ temp[row + x] = sum }- temp[y * w + x] = sum } // Vertical pass- val dst = FloatArray(w * h)- for (y in 0 until h) for (x in 0 until w) {- var sum = 0f- for (k in -r..r) {- val sy = (y + k).coerceIn(0, h - 1)- sum += temp[sy * w + x] * kernel[k + r]+ for (x in 0 until w) {+ for (y in 0 until h) {+ var sum = 0f+ var sy: Int+ sy = y - 3+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.06f+ sy = y - 2+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.12f+ sy = y - 1+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.18f+ sum += temp[y * w + x] * 0.28f+ sy = y + 1+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.18f+ sy = y + 2+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.12f+ sy = y + 3+ if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+ sum += temp[sy * w + x] * 0.06f++ dst[y * w + x] = sum }- dst[y * w + x] = sum } return dst }
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 6cb4c7348c..e1290094c5 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -36,6 +36,9 @@ import androidx.camera.core.SurfaceRequest import androidx.camera.core.resolutionselector.ResolutionSelector import androidx.camera.core.resolutionselector.ResolutionStrategy import androidx.camera.lifecycle.ProcessCameraProvider+import java.util.concurrent.Executor+import java.util.concurrent.ExecutorService+import java.util.concurrent.Executors import androidx.camera.extensions.ExtensionMode import androidx.camera.extensions.ExtensionsManager import androidx.camera.video.FileOutputOptions@@ -262,6 +265,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { val roll = _roll.asStateFlow() private val sensorManager by lazy { app.getSystemService(Context.SENSOR_SERVICE) as SensorManager }+ // Dedicated single thread for portrait segmentation so main thread stays free for preview rendering.+ private val bokehExecutor: ExecutorService = Executors.newSingleThreadExecutor() private val levelListener = object : SensorEventListener { override fun onSensorChanged(event: SensorEvent) { val x = event.values[0]@@ -1236,6 +1241,151 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { } } + /**+ * Portrait session: full-resolution ImageCapture (final image stays max-res) but capped+ * ImageAnalysis (~0.8 MP, 1024x768) for smooth preview segmentation. This fixes the+ * "No supported surface combination" bind failures that happened when portrait reused+ * the max-res 3-stream photo path (Preview + max ImageCapture + max ImageAnalysis) for a+ * model that only needs 256x256.+ *+ * Fallback ladder prioritizes keeping max-res capture:+ * capped+max+UHD → capped+max+JPEG → capped+default+UHD → capped+default+JPEG → default+default+ */+ suspend fun setupPortraitSession(): Boolean {+ return try {+ val provider = ProcessCameraProvider.awaitInstance(app)+ cameraProvider = provider+ provider.unbindAll()++ val selector = CameraSelector.Builder()+ .requireLensFacing(_lensFacing.value)+ .build()++ val previewBuilder = Preview.Builder()+ try {+ androidx.camera.camera2.interop.Camera2Interop.Extender(previewBuilder)+ .setSessionCaptureCallback(aeSnapshotCallback)+ } catch (e: Exception) {+ Log.w("PortraitSession", "Could not attach AE snapshot callback", e)+ }+ val preview = previewBuilder.build()+ preview.setSurfaceProvider { request -> _surfaceRequest.value = request }++ val owner = ManualLifecycleOwner()+ owner.start()+ sessionLifecycleOwner = owner++ val ultraHdrSupported = try {+ val cameraInfo = provider.getCameraInfo(selector)+ ImageCapture.getImageCaptureCapabilities(cameraInfo)+ .supportedOutputFormats+ .contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ } catch (e: Exception) {+ Log.w("PortraitSession", "Could not query Ultra HDR support", e)+ false+ }++ fun bind(+ cappedAnalysis: Boolean,+ maxResCapture: Boolean,+ ultraHdr: Boolean+ ): Camera {+ // Capture: always try max-res first to keep final image full-res.+ val captureSelectorBuilder = ResolutionSelector.Builder()+ .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)+ if (maxResCapture) {+ captureSelectorBuilder.setAllowedResolutionMode(+ ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE+ )+ }+ val captureBuilder = ImageCapture.Builder()+ .setResolutionSelector(captureSelectorBuilder.build())+ .setFlashMode(getImageCaptureFlashMode())+ .setTargetRotation(targetRotation)+ if (ultraHdr) {+ captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)+ }+ val capture = captureBuilder.build()+ imageCapture = capture++ val analysisBuilder = ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ if (cappedAnalysis) {+ analysisBuilder.setResolutionSelector(+ ResolutionSelector.Builder()+ .setResolutionStrategy(+ ResolutionStrategy(+ Size(1024, 768), // ~0.8MP sweet spot > 256 model input+ ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER+ )+ )+ .build()+ )+ } else if (maxResCapture) {+ analysisBuilder.setResolutionSelector(+ ResolutionSelector.Builder()+ .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY)+ .build()+ )+ }+ val analysis = analysisBuilder.build()+ imageAnalysis = analysis+ return provider.bindToLifecycle(owner, selector, preview, capture, analysis)+ }++ // Build attempt ladder; keep max-res capture attempts first per user request.+ data class Attempt(val capped: Boolean, val maxRes: Boolean, val ultra: Boolean)+ val attempts = mutableListOf<Attempt>()+ if (ultraHdrSupported) {+ attempts.add(Attempt(true, true, true))+ attempts.add(Attempt(true, true, false))+ attempts.add(Attempt(true, false, true))+ attempts.add(Attempt(true, false, false))+ attempts.add(Attempt(false, false, true))+ attempts.add(Attempt(false, false, false))+ } else {+ attempts.add(Attempt(true, true, false))+ attempts.add(Attempt(true, false, false))+ attempts.add(Attempt(false, false, false))+ }++ var bound: Camera? = null+ var lastError: Exception? = null+ for ((capped, maxRes, ultra) in attempts) {+ try {+ if (bound != null) provider.unbindAll()+ bound = bind(capped, maxRes, ultra)+ Log.d(+ "PortraitSession",+ "Portrait bind succeeded: capped=$capped maxRes=$maxRes ultra=$ultra"+ )+ break+ } catch (e: Exception) {+ lastError = e+ Log.w(+ "PortraitSession",+ "Portrait bind failed (capped=$capped maxRes=$maxRes ultra=$ultra); trying next",+ e+ )+ provider.unbindAll()+ }+ }+ boundCamera = bound ?: throw (lastError ?: IllegalStateException("Portrait session bind failed"))++ boundCamera?.cameraInfo?.zoomState?.value?.let {+ updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)+ _zoomRatio.value = it.zoomRatio+ }+ readManualControlRanges()+ applyManualControls()+ _photoSessionActive.value = true+ true+ } catch (e: Exception) {+ Log.e("PortraitSession", "Failed to set up portrait session", e)+ false+ }+ }+ /** Reads the bound sensor's ISO range → stop list for the manual ISO control. */ private fun readManualControlRanges() { val cam = boundCamera ?: return@@ -1574,6 +1724,18 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { else analysis.setAnalyzer(ContextCompat.getMainExecutor(app), analyzer) } + fun setImageAnalyzer(analyzer: ImageAnalysis.Analyzer?, executor: Executor) {+ val analysis = imageAnalysis ?: return+ currentAnalyzer = analyzer+ if (analyzer == null) analysis.clearAnalyzer()+ else analysis.setAnalyzer(executor, analyzer)+ }++ /** Convenience for portrait bokeh – always runs off the dedicated bokeh thread. */+ fun setBokehAnalyzer(analyzer: ImageAnalysis.Analyzer?) {+ setImageAnalyzer(analyzer, bokehExecutor)+ }+ private fun startRecordingTimer() { _isRecording.value = true _recordingPaused.value = false@@ -2651,6 +2813,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) { override fun onCleared() { unregisterLevelSensor()+ try { bokehExecutor.shutdown() } catch (_: Exception) {} super.onCleared() } }