diff --git a/app/src/main/assets/face_det_lite.tflite b/app/src/main/assets/face_det_lite.tflite new file mode 100644 index 00000000..da469bda Binary files /dev/null and b/app/src/main/assets/face_det_lite.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 a51c6223..07b06197 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -371,7 +371,7 @@ class Camera2Controller(private val context: Context) { if (refProduct > 0) { val ratio = if (curProduct > refProduct) curProduct / refProduct else refProduct / curProduct if (ratio > SCENE_CHANGE_EXPOSURE_RATIO) { - PLog.d(TAG, "scene change: exposure ratio=$ratio") +// PLog.d(TAG, "scene change: exposure ratio=$ratio") sceneChanged = true } } @@ -382,7 +382,7 @@ class Camera2Controller(private val context: Context) { if (focusLockedReferenceDistance > 0f && currentFocusDistance > 0f) { val delta = abs(currentFocusDistance - focusLockedReferenceDistance) if (delta > SCENE_CHANGE_FOCUS_DISTANCE_DELTA) { - PLog.d(TAG, "scene change: focusDistance delta=$delta (ref=$focusLockedReferenceDistance, cur=$currentFocusDistance)") +// PLog.d(TAG, "scene change: focusDistance delta=$delta (ref=$focusLockedReferenceDistance, cur=$currentFocusDistance)") sceneChanged = true } } @@ -669,6 +669,7 @@ class Camera2Controller(private val context: Context) { fun openCamera(surfaceTexture: SurfaceTexture, preserveVideoRecording: Boolean = false) { // 先关闭旧的相机和资源,防止资源泄漏 closeCamera(preserveVideoRecording = preserveVideoRecording) + previewAiFocusProcessor.resetForPreviewRestart() val openGeneration = ++cameraOpenGeneration // 确保在权限已授予后才发现相机(延迟初始化) @@ -3523,6 +3524,7 @@ class Camera2Controller(private val context: Context) { fun closeCamera(preserveVideoRecording: Boolean = false) { try { cameraOpenGeneration++ + previewAiFocusProcessor.resetForPreviewRestart() val keepVideoRecording = preserveVideoRecording && _state.value.videoRecordingState.isRecording if (keepVideoRecording) { PLog.d(TAG, "Closing camera while keeping active video recording") diff --git a/app/src/main/java/com/hinnka/mycamera/ml/FaceDetLiteFocusDetector.kt b/app/src/main/java/com/hinnka/mycamera/ml/FaceDetLiteFocusDetector.kt new file mode 100644 index 00000000..1492ed87 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ml/FaceDetLiteFocusDetector.kt @@ -0,0 +1,284 @@ +package com.hinnka.mycamera.ml + +import android.content.Context +import android.graphics.Bitmap +import com.hinnka.mycamera.utils.PLog +import com.hinnka.mycamera.utils.StartupTrace +import org.tensorflow.lite.Interpreter +import org.tensorflow.lite.gpu.CompatibilityList +import org.tensorflow.lite.gpu.GpuDelegate +import org.tensorflow.lite.nnapi.NnApiDelegate +import org.tensorflow.lite.support.common.FileUtil +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.MappedByteBuffer +import kotlin.math.exp +import kotlin.math.max +import kotlin.math.min + +class FaceDetLiteFocusDetector(context: Context) { + data class FaceFocus( + val x: Float, + val y: Float, + val label: String, + val score: Float, + val priority: Int, + ) + + private var state: InterpreterState? = null + private var isInitialized = false + private val inputBuffer = ByteBuffer.allocateDirect(INPUT_WIDTH * INPUT_HEIGHT).order(ByteOrder.nativeOrder()) + private val heatmapBuffer = ByteBuffer.allocateDirect(HEATMAP_HEIGHT * HEATMAP_WIDTH).order(ByteOrder.nativeOrder()) + private val bboxBuffer = ByteBuffer.allocateDirect(HEATMAP_HEIGHT * HEATMAP_WIDTH * BBOX_SIZE).order(ByteOrder.nativeOrder()) + private val landmarkBuffer = ByteBuffer.allocateDirect(HEATMAP_HEIGHT * HEATMAP_WIDTH * LANDMARK_SIZE).order(ByteOrder.nativeOrder()) + private val pixels = IntArray(INPUT_WIDTH * INPUT_HEIGHT) + private val outputs = mapOf(0 to heatmapBuffer, 1 to bboxBuffer, 2 to landmarkBuffer) + + init { + try { + val modelFile = StartupTrace.measure("FaceDetLiteFocusDetector.loadModel") { + FileUtil.loadMappedFile(context, MODEL_ASSET) + } + val compatList = StartupTrace.measure("FaceDetLiteFocusDetector.CompatibilityList") { + CompatibilityList() + } + state = createInterpreterState(modelFile, compatList) + isInitialized = true + } catch (e: Exception) { + PLog.e(TAG, "Failed to initialize FaceDetLite focus detector", e) + } + } + + fun detect(inputBitmap: Bitmap, minScore: Float): FaceFocus? { + val activeState = state + if (!isInitialized || activeState == null) return null + +// val startTimeMs = System.currentTimeMillis() + return try { + val input = createInputBuffer(inputBitmap) + heatmapBuffer.rewind() + bboxBuffer.rewind() + landmarkBuffer.rewind() + + activeState.interpreter.runForMultipleInputsOutputs(arrayOf(input), outputs) + heatmapBuffer.rewind() + bboxBuffer.rewind() + + val face = decodeBestFace(heatmapBuffer, bboxBuffer, minScore.coerceIn(0.05f, 0.95f)) +// val elapsedMs = System.currentTimeMillis() - startTimeMs +// if (face != null) { +// PLog.d( +// TAG, +// "FaceDetLite focus: backend=${activeState.backend} face=${elapsedMs}ms score=${face.score} x=${face.x} y=${face.y} box=[${face.left},${face.top},${face.right},${face.bottom}]" +// ) +// } else { +// logRejectedBestCandidate(heatmap, bbox, activeState.backend, elapsedMs, minScore) +// } + face?.toFaceFocus() + } catch (e: Exception) { + PLog.e(TAG, "Failed during FaceDetLite detection", e) + null + } + } + + fun close() { + state?.close() + state = null + isInitialized = false + } + + private fun decodeBestFace(heatmap: ByteBuffer, bbox: ByteBuffer, minScore: Float): FaceCandidate? { + var best: FaceCandidate? = null + repeat(HEATMAP_HEIGHT) { row -> + repeat(HEATMAP_WIDTH) { col -> + val index = row * HEATMAP_WIDTH + col + val score = heatmapScore(heatmap.get(index)) + if (score < minScore) return@repeat + + val boxOffset = index * BBOX_SIZE + val leftDistance = bboxDistance(bbox.get(boxOffset)) + val topDistance = bboxDistance(bbox.get(boxOffset + 1)) + val rightDistance = bboxDistance(bbox.get(boxOffset + 2)) + val bottomDistance = bboxDistance(bbox.get(boxOffset + 3)) + if (leftDistance + rightDistance < MIN_FACE_SIZE_PX || + topDistance + bottomDistance < MIN_FACE_SIZE_PX + ) { + return@repeat + } + + val centerX = (col + 0.5f) * STRIDE + val centerY = (row + 0.5f) * STRIDE + val left = ((centerX - leftDistance) / INPUT_WIDTH).coerceIn(0f, 1f) + val top = ((centerY - topDistance) / INPUT_HEIGHT).coerceIn(0f, 1f) + val right = ((centerX + rightDistance) / INPUT_WIDTH).coerceIn(0f, 1f) + val bottom = ((centerY + bottomDistance) / INPUT_HEIGHT).coerceIn(0f, 1f) + if (right <= left || bottom <= top) return@repeat + + val candidate = FaceCandidate(left, top, right, bottom, score) + val currentBest = best + if (currentBest == null || candidate.score > currentBest.score) { + best = candidate + } + } + } + return best + } + + private fun logRejectedBestCandidate( + heatmap: ByteBuffer, + bbox: ByteBuffer, + backend: String, + elapsedMs: Long, + minScore: Float, + ) { + var bestIndex = 0 + var bestScore = -1f + repeat(HEATMAP_HEIGHT * HEATMAP_WIDTH) { index -> + val score = heatmapScore(heatmap.get(index)) + if (score > bestScore) { + bestScore = score + bestIndex = index + } + } + val row = bestIndex / HEATMAP_WIDTH + val col = bestIndex % HEATMAP_WIDTH + val boxOffset = bestIndex * BBOX_SIZE + val leftDistance = bboxDistance(bbox.get(boxOffset)) + val topDistance = bboxDistance(bbox.get(boxOffset + 1)) + val rightDistance = bboxDistance(bbox.get(boxOffset + 2)) + val bottomDistance = bboxDistance(bbox.get(boxOffset + 3)) + PLog.d( + TAG, + "FaceDetLite no face: backend=$backend face=${elapsedMs}ms topScore=$bestScore threshold=$minScore cell=($col,$row) size=${leftDistance + rightDistance}x${topDistance + bottomDistance} distances=[$leftDistance,$topDistance,$rightDistance,$bottomDistance]" + ) + } + + private fun createInputBuffer(inputBitmap: Bitmap): ByteBuffer { + val scaled = Bitmap.createScaledBitmap(inputBitmap, INPUT_WIDTH, INPUT_HEIGHT, true) + scaled.getPixels(pixels, 0, INPUT_WIDTH, 0, 0, INPUT_WIDTH, INPUT_HEIGHT) + inputBuffer.rewind() + pixels.forEach { pixel -> + val r = (pixel shr 16) and 0xFF + val g = (pixel shr 8) and 0xFF + val b = pixel and 0xFF + val gray = (0.299f * r + 0.587f * g + 0.114f * b).toInt().coerceIn(0, 255) + inputBuffer.put(gray.toByte()) + } + inputBuffer.rewind() + return inputBuffer + } + + private fun createInterpreterState( + modelFile: MappedByteBuffer, + compatList: CompatibilityList, + ): InterpreterState { + var gpuDelegate: GpuDelegate? = null + try { + val options = Interpreter.Options() + gpuDelegate = StartupTrace.measure("FaceDetLiteFocusDetector.GpuDelegate") { + if (compatList.isDelegateSupportedOnThisDevice) { + GpuDelegate(compatList.bestOptionsForThisDevice) + } else { + GpuDelegate() + } + } + options.addDelegate(gpuDelegate) + val interpreter = StartupTrace.measure("FaceDetLiteFocusDetector.Interpreter.GPU") { + Interpreter(modelFile, options) + } + PLog.d(TAG, "Using GPU delegate for FaceDetLite focus detector") + return InterpreterState(interpreter, gpuDelegate, null, "GPU") + } catch (e: Exception) { + PLog.w(TAG, "Failed to initialize FaceDetLite with GPU, falling back to NNAPI", e) + gpuDelegate?.close() + } + + var nnApiDelegate: NnApiDelegate? = null + try { + val options = Interpreter.Options().apply { setNumThreads(2) } + nnApiDelegate = StartupTrace.measure("FaceDetLiteFocusDetector.NnApiDelegate") { + NnApiDelegate() + } + options.addDelegate(nnApiDelegate) + val interpreter = StartupTrace.measure("FaceDetLiteFocusDetector.Interpreter.NNAPI") { + Interpreter(modelFile, options) + } + PLog.d(TAG, "Using NNAPI for FaceDetLite focus detector") + return InterpreterState(interpreter, null, nnApiDelegate, "NNAPI") + } catch (e: Exception) { + PLog.w(TAG, "Failed to initialize FaceDetLite with NNAPI, falling back to CPU", e) + nnApiDelegate?.close() + } + + val interpreter = Interpreter(modelFile, Interpreter.Options().apply { setNumThreads(2) }) + PLog.d(TAG, "Using CPU for FaceDetLite focus detector") + return InterpreterState(interpreter, null, null, "CPU") + } + + private data class FaceCandidate( + val left: Float, + val top: Float, + val right: Float, + val bottom: Float, + val score: Float, + ) { + val x: Float get() = ((left + right) * 0.5f).coerceIn(0f, 1f) + val y: Float get() = (top + (bottom - top) * 0.36f).coerceIn(0f, 1f) + + fun toFaceFocus(): FaceFocus = FaceFocus( + x = x, + y = y, + label = "face", + score = score, + priority = PRIORITY_FACE, + ) + } + + private data class InterpreterState( + val interpreter: Interpreter, + val gpuDelegate: GpuDelegate?, + val nnApiDelegate: NnApiDelegate?, + val backend: String, + ) { + fun close() { + interpreter.close() + gpuDelegate?.close() + nnApiDelegate?.close() + } + } + + private fun dequantize(value: Byte, scale: Float, zeroPoint: Int): Float { + return ((value.toInt() and 0xFF) - zeroPoint) * scale + } + + private fun heatmapScore(value: Byte): Float { + val dequantized = dequantize(value, HEATMAP_SCALE, HEATMAP_ZERO_POINT) + return if (dequantized in 0f..1f) dequantized else sigmoid(dequantized) + } + + private fun bboxDistance(value: Byte): Float { + return (dequantize(value, BBOX_SCALE, BBOX_ZERO_POINT) * STRIDE).coerceAtLeast(0f) + } + + private fun sigmoid(value: Float): Float { + return (1f / (1f + exp(-value))).coerceIn(0f, 1f) + } + + companion object { + private const val TAG = "FaceDetLiteFocusDetector" + private const val MODEL_ASSET = "face_det_lite.tflite" + private const val INPUT_WIDTH = 640 + private const val INPUT_HEIGHT = 480 + private const val HEATMAP_WIDTH = 80 + private const val HEATMAP_HEIGHT = 60 + private const val STRIDE = 8f + private const val BBOX_SIZE = 4 + private const val LANDMARK_SIZE = 10 + private const val PRIORITY_FACE = 4 + private const val MIN_FACE_SIZE_PX = 18f + private const val HEATMAP_SCALE = 0.026649248f + private const val HEATMAP_ZERO_POINT = 191 + private const val BBOX_SCALE = 0.27092865f + private const val BBOX_ZERO_POINT = 10 + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ml/SharedFaceDetLiteFocusDetector.kt b/app/src/main/java/com/hinnka/mycamera/ml/SharedFaceDetLiteFocusDetector.kt new file mode 100644 index 00000000..1b8ba77b --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/ml/SharedFaceDetLiteFocusDetector.kt @@ -0,0 +1,48 @@ +package com.hinnka.mycamera.ml + +import android.content.Context +import android.graphics.Bitmap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +object SharedFaceDetLiteFocusDetector { + private val mutex = Mutex() + private var detector: FaceDetLiteFocusDetector? = null + + suspend fun prewarm(context: Context) { + withDetector(context) { + Unit + } + } + + suspend fun detect( + context: Context, + bitmap: Bitmap, + minScore: Float, + ): FaceDetLiteFocusDetector.FaceFocus? = withDetector(context) { detector -> + detector.detect(bitmap, minScore) + } + + suspend fun release() { + withContext(Dispatchers.Default) { + mutex.withLock { + detector?.close() + detector = null + } + } + } + + private suspend fun withDetector( + context: Context, + block: (FaceDetLiteFocusDetector) -> T, + ): T = withContext(Dispatchers.Default) { + mutex.withLock { + val activeDetector = detector ?: FaceDetLiteFocusDetector(context.applicationContext).also { + detector = it + } + block(activeDetector) + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ml/YoloXObjectDetector.kt b/app/src/main/java/com/hinnka/mycamera/ml/YoloXObjectDetector.kt index 651a218c..7735de30 100644 --- a/app/src/main/java/com/hinnka/mycamera/ml/YoloXObjectDetector.kt +++ b/app/src/main/java/com/hinnka/mycamera/ml/YoloXObjectDetector.kt @@ -44,6 +44,12 @@ class YoloXObjectDetector(context: Context) { private var isInitialized = false private var activeBackend = "NONE" private val labels: List + private val inputBuffer = ByteBuffer.allocateDirect(INPUT_SIZE * INPUT_SIZE * 3).order(ByteOrder.nativeOrder()) + private val boxesBuffer = ByteBuffer.allocateDirect(DETECTION_COUNT * 4).order(ByteOrder.nativeOrder()) + private val scoresBuffer = ByteBuffer.allocateDirect(DETECTION_COUNT).order(ByteOrder.nativeOrder()) + private val classIdxBuffer = ByteBuffer.allocateDirect(DETECTION_COUNT).order(ByteOrder.nativeOrder()) + private val pixels = IntArray(INPUT_SIZE * INPUT_SIZE) + private val outputs = mapOf(0 to boxesBuffer, 1 to scoresBuffer, 2 to classIdxBuffer) @Volatile var targetMode: AiFocusTargetMode = AiFocusTargetMode.PERSON @@ -131,13 +137,12 @@ class YoloXObjectDetector(context: Context) { return try { val input = createInputBuffer(inputBitmap) - val boxes = ByteBuffer.allocateDirect(DETECTION_COUNT * 4).order(ByteOrder.nativeOrder()) - val scores = ByteBuffer.allocateDirect(DETECTION_COUNT).order(ByteOrder.nativeOrder()) - val classIdx = ByteBuffer.allocateDirect(DETECTION_COUNT).order(ByteOrder.nativeOrder()) - val outputs = mapOf(0 to boxes, 1 to scores, 2 to classIdx) + boxesBuffer.rewind() + scoresBuffer.rewind() + classIdxBuffer.rewind() activeInterpreter.runForMultipleInputsOutputs(arrayOf(input), outputs) - val detections = parseDetections(boxes, scores, classIdx) + val detections = parseDetections(boxesBuffer, scoresBuffer, classIdxBuffer) detections } catch (e: Exception) { PLog.e(TAG, "Error during YOLOX inference", e) @@ -162,16 +167,15 @@ class YoloXObjectDetector(context: Context) { } else { Bitmap.createScaledBitmap(inputBitmap, INPUT_SIZE, INPUT_SIZE, true) } - val pixels = IntArray(INPUT_SIZE * INPUT_SIZE) scaled.getPixels(pixels, 0, INPUT_SIZE, 0, 0, INPUT_SIZE, INPUT_SIZE) - val buffer = ByteBuffer.allocateDirect(INPUT_SIZE * INPUT_SIZE * 3).order(ByteOrder.nativeOrder()) + inputBuffer.rewind() for (pixel in pixels) { - buffer.put(((pixel shr 16) and 0xFF).toByte()) - buffer.put(((pixel shr 8) and 0xFF).toByte()) - buffer.put((pixel and 0xFF).toByte()) + inputBuffer.put(((pixel shr 16) and 0xFF).toByte()) + inputBuffer.put(((pixel shr 8) and 0xFF).toByte()) + inputBuffer.put((pixel and 0xFF).toByte()) } - buffer.rewind() - return buffer + inputBuffer.rewind() + return inputBuffer } private fun parseDetections( diff --git a/app/src/main/java/com/hinnka/mycamera/preview/PreviewAiFocusProcessor.kt b/app/src/main/java/com/hinnka/mycamera/preview/PreviewAiFocusProcessor.kt index 19509c7e..e0026951 100644 --- a/app/src/main/java/com/hinnka/mycamera/preview/PreviewAiFocusProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/preview/PreviewAiFocusProcessor.kt @@ -3,6 +3,8 @@ package com.hinnka.mycamera.preview import android.content.Context import android.graphics.Bitmap import com.hinnka.mycamera.data.AiFocusTargetMode +import com.hinnka.mycamera.ml.FaceDetLiteFocusDetector +import com.hinnka.mycamera.ml.SharedFaceDetLiteFocusDetector import com.hinnka.mycamera.ml.SharedYoloXObjectDetector import com.hinnka.mycamera.ml.YoloXObjectDetector import com.hinnka.mycamera.utils.PLog @@ -19,7 +21,13 @@ class PreviewAiFocusProcessor(private val context: Context) { private const val MIN_FOCUS_INTERVAL_MS = 60L private const val MIN_TARGET_MOVE = 0.025f private const val TRACK_KEEP_DISTANCE = 0.22f - private const val TARGET_LOST_CONFIRM_FRAMES = 5 + private const val TARGET_LOST_CONFIRM_FRAMES = 3 + private const val FACE_PERSON_BOX_PADDING = 0.12f + private const val PERSON_PRIORITY = 3 + private const val FACE_REFINEMENT_PRIORITY = 4 + private const val FACE_REFINEMENT_SMOOTHING = 0.65f + private const val FACE_HOLD_MS = 700L + private const val PROCESSING_STALE_MS = 2_000L } data class FocusTarget( @@ -30,6 +38,15 @@ class PreviewAiFocusProcessor(private val context: Context) { val priority: Int, ) + private data class FocusCandidate( + val label: String, + val score: Float, + val focusX: Float, + val focusY: Float, + val priority: Int, + val area: Float, + ) + private val scope = CoroutineScope(Dispatchers.Default + Job()) @Volatile private var isPrewarming = false @@ -38,6 +55,8 @@ class PreviewAiFocusProcessor(private val context: Context) { @Volatile private var isProcessing = false @Volatile + private var processingStartTimeMs = 0L + @Volatile var targetMode: AiFocusTargetMode = AiFocusTargetMode.PERSON @Volatile var scoreThreshold: Float = 0.5f @@ -46,6 +65,11 @@ class PreviewAiFocusProcessor(private val context: Context) { private var lastFocusY = -1f private var targetMissingFrames = 0 private var lastDetectionLogTimeMs = 0L + private var lastRefinedFaceX = -1f + private var lastRefinedFaceY = -1f + private var lastRefinedFaceLabel = "" + private var heldFaceCandidate: FocusCandidate? = null + private var heldFaceTimeMs = 0L var onFocusTarget: ((FocusTarget) -> Unit)? = null var onTargetSeen: ((FocusTarget) -> Unit)? = null var onTargetLost: (() -> Unit)? = null @@ -57,6 +81,9 @@ class PreviewAiFocusProcessor(private val context: Context) { try { StartupTrace.mark("PreviewAiFocusProcessor.prewarm start") SharedYoloXObjectDetector.prewarm(context) + if (shouldDetectFaceFocus()) { + SharedFaceDetLiteFocusDetector.prewarm(context) + } isPrewarmed = true StartupTrace.mark("PreviewAiFocusProcessor.prewarm end") } catch (e: Exception) { @@ -72,13 +99,20 @@ class PreviewAiFocusProcessor(private val context: Context) { handleMissingTarget() return } - if (isProcessing) return + if (isProcessing) { + val processingElapsedMs = System.currentTimeMillis() - processingStartTimeMs + if (processingElapsedMs < PROCESSING_STALE_MS) return + PLog.w(TAG, "AI focus processing stale, resetting: elapsed=${processingElapsedMs}ms") + isProcessing = false + processingStartTimeMs = 0L + } if (!isPrewarmed) { prewarm() return } isProcessing = true + processingStartTimeMs = System.currentTimeMillis() scope.launch { val startTimeMs = System.currentTimeMillis() try { @@ -88,7 +122,8 @@ class PreviewAiFocusProcessor(private val context: Context) { targetMode = targetMode, scoreThreshold = scoreThreshold ) - val target = selectFocusTarget(detections) + val candidates = buildFocusCandidates(bitmap, detections) + val target = selectFocusTarget(candidates) if (target == null) { handleMissingTarget() return@launch @@ -102,62 +137,113 @@ class PreviewAiFocusProcessor(private val context: Context) { priority = target.priority, ) onTargetSeen?.invoke(seenTarget) - logTargetSeen(target, startTimeMs, System.currentTimeMillis() - startTimeMs) +// logTargetSeen(target, startTimeMs, System.currentTimeMillis() - startTimeMs) if (!shouldRefocus(target)) return@launch lastFocusTimeMs = System.currentTimeMillis() lastFocusX = target.focusX lastFocusY = target.focusY - PLog.d( - TAG, - "AI focus target: label=${target.label} score=${target.score} x=${target.focusX} y=${target.focusY}" - ) +// PLog.d( +// TAG, +// "AI focus target: label=${target.label} score=${target.score} x=${target.focusX} y=${target.focusY}" +// ) onFocusTarget?.invoke(seenTarget) } catch (e: Exception) { PLog.e(TAG, "Error processing preview bitmap for AI focus", e) } finally { isProcessing = false + processingStartTimeMs = 0L } } } fun release() { + resetForPreviewRestart() + scope.launch { + SharedYoloXObjectDetector.release() + SharedFaceDetLiteFocusDetector.release() + } + } + + fun resetForPreviewRestart() { + PLog.d(TAG, "Reset AI focus processor for preview restart") + isProcessing = false + processingStartTimeMs = 0L + isPrewarming = false isPrewarmed = false + targetMissingFrames = 0 + lastFocusX = -1f + lastFocusY = -1f + lastFocusTimeMs = 0L + resetFaceRefinementSmoothing() + } + + private suspend fun buildFocusCandidates( + bitmap: Bitmap, + detections: List, + ): List { + val candidates = detections.map { it.toFocusCandidate() }.toMutableList() + val personDetections = detections.filter { it.priority == PERSON_PRIORITY } + if (shouldDetectFaceFocus() && personDetections.isNotEmpty()) { + val faceFocus = SharedFaceDetLiteFocusDetector.detect(context, bitmap, scoreThreshold) + if (faceFocus != null && faceFocus.isAttachedToPerson(personDetections)) { + val faceCandidate = faceFocus.toFocusCandidate().smoothedFaceRefinement() + rememberHeldFaceCandidate(faceCandidate) + candidates += faceCandidate + }/* else if (faceFocus != null) { + PLog.d( + TAG, + "AI face focus rejected: label=${faceFocus.label} score=${faceFocus.score} x=${faceFocus.x} y=${faceFocus.y}" + ) + } else { + PLog.d(TAG, "AI face focus missing: persons=${personDetections.size} threshold=$scoreThreshold") + }*/ + if (faceFocus == null || !faceFocus.isAttachedToPerson(personDetections)) { + getHeldFaceCandidate(personDetections)?.let { candidates += it } + } + } else { + clearHeldFaceCandidate() + } + return candidates + } + + private fun shouldDetectFaceFocus(): Boolean { + return targetMode == AiFocusTargetMode.PERSON || targetMode == AiFocusTargetMode.AUTO } private fun selectFocusTarget( - detections: List, - ): YoloXObjectDetector.Detection? { - if (detections.isEmpty()) return null + candidates: List, + ): FocusCandidate? { + if (candidates.isEmpty()) return null val hasTrackedTarget = lastFocusX >= 0f && lastFocusY >= 0f if (hasTrackedTarget) { - val trackedPriority = detections.maxOf { it.priority } - val trackedCandidates = detections + val trackedPriority = candidates.maxOf { it.priority } + val trackedCandidates = candidates .filter { it.priority == trackedPriority } - .map { detection -> - val distance = hypot(detection.focusX - lastFocusX, detection.focusY - lastFocusY) - detection to distance + .map { candidate -> + val distance = hypot(candidate.focusX - lastFocusX, candidate.focusY - lastFocusY) + candidate to distance } .filter { (_, distance) -> distance <= TRACK_KEEP_DISTANCE } if (trackedCandidates.isNotEmpty()) { return trackedCandidates.maxWithOrNull( - compareBy> { -it.second } + compareBy> { -it.second } .thenBy { it.first.score } .thenBy { it.first.area } )?.first } } - return detections.maxWithOrNull( - compareBy { it.priority } + return candidates.maxWithOrNull( + compareBy { it.priority } .thenBy { it.score } .thenBy { it.area } ) } - private fun shouldRefocus(target: YoloXObjectDetector.Detection): Boolean { + private fun shouldRefocus(target: FocusCandidate): Boolean { val now = System.currentTimeMillis() if (now - lastFocusTimeMs < MIN_FOCUS_INTERVAL_MS) return false if (lastFocusX < 0f || lastFocusY < 0f) return true @@ -174,10 +260,11 @@ class PreviewAiFocusProcessor(private val context: Context) { lastFocusX = -1f lastFocusY = -1f lastFocusTimeMs = 0L + resetFaceRefinementSmoothing() onTargetLost?.invoke() } - private fun logTargetSeen(target: YoloXObjectDetector.Detection, startTimeMs: Long, elapsedMs: Long) { + private fun logTargetSeen(target: FocusCandidate, startTimeMs: Long, elapsedMs: Long) { val intervalMs = if (lastDetectionLogTimeMs > 0L) startTimeMs - lastDetectionLogTimeMs else 0L lastDetectionLogTimeMs = startTimeMs PLog.d( @@ -185,4 +272,92 @@ class PreviewAiFocusProcessor(private val context: Context) { "AI target seen: label=${target.label} score=${target.score} x=${target.focusX} y=${target.focusY} interval=${intervalMs}ms inference=${elapsedMs}ms" ) } + + private fun YoloXObjectDetector.Detection.toFocusCandidate(): FocusCandidate { + return FocusCandidate( + label = label, + score = score, + focusX = focusX, + focusY = focusY, + priority = priority, + area = area, + ) + } + + private fun FaceDetLiteFocusDetector.FaceFocus.toFocusCandidate(): FocusCandidate { + return FocusCandidate( + label = label, + score = score, + focusX = x, + focusY = y, + priority = priority, + area = 0f, + ) + } + + private fun FaceDetLiteFocusDetector.FaceFocus.isAttachedToPerson( + personDetections: List, + ): Boolean { + return personDetections.any { person -> + x >= (person.left - FACE_PERSON_BOX_PADDING).coerceAtLeast(0f) && + x <= (person.right + FACE_PERSON_BOX_PADDING).coerceAtMost(1f) && + y >= (person.top - FACE_PERSON_BOX_PADDING).coerceAtLeast(0f) && + y <= (person.bottom + FACE_PERSON_BOX_PADDING).coerceAtMost(1f) + } + } + + private fun FocusCandidate.smoothedFaceRefinement(): FocusCandidate { + if (priority < FACE_REFINEMENT_PRIORITY) return this + if (lastRefinedFaceX < 0f || lastRefinedFaceY < 0f || lastRefinedFaceLabel != label) { + lastRefinedFaceX = focusX + lastRefinedFaceY = focusY + lastRefinedFaceLabel = label + return this + } + + val smoothedX = lastRefinedFaceX * FACE_REFINEMENT_SMOOTHING + focusX * (1f - FACE_REFINEMENT_SMOOTHING) + val smoothedY = lastRefinedFaceY * FACE_REFINEMENT_SMOOTHING + focusY * (1f - FACE_REFINEMENT_SMOOTHING) + lastRefinedFaceX = smoothedX + lastRefinedFaceY = smoothedY + return copy(focusX = smoothedX, focusY = smoothedY) + } + + private fun resetFaceRefinementSmoothing() { + lastRefinedFaceX = -1f + lastRefinedFaceY = -1f + lastRefinedFaceLabel = "" + clearHeldFaceCandidate() + } + + private fun rememberHeldFaceCandidate(candidate: FocusCandidate) { + heldFaceCandidate = candidate + heldFaceTimeMs = System.currentTimeMillis() + } + + private fun getHeldFaceCandidate( + personDetections: List, + ): FocusCandidate? { + val candidate = heldFaceCandidate ?: return null + if (System.currentTimeMillis() - heldFaceTimeMs > FACE_HOLD_MS) { + clearHeldFaceCandidate() + return null + } + return if (candidate.isAttachedToPerson(personDetections)) candidate else null + } + + private fun FocusCandidate.isAttachedToPerson( + personDetections: List, + ): Boolean { + return personDetections.any { person -> + focusX >= (person.left - FACE_PERSON_BOX_PADDING).coerceAtLeast(0f) && + focusX <= (person.right + FACE_PERSON_BOX_PADDING).coerceAtMost(1f) && + focusY >= (person.top - FACE_PERSON_BOX_PADDING).coerceAtLeast(0f) && + focusY <= (person.bottom + FACE_PERSON_BOX_PADDING).coerceAtMost(1f) + } + } + + private fun clearHeldFaceCandidate() { + heldFaceCandidate = null + heldFaceTimeMs = 0L + } } 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 1b0274c4..39afa5de 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 @@ -24,6 +24,7 @@ import com.hinnka.mycamera.lut.LutConfig import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.ui.components.FocusIndicator import com.hinnka.mycamera.utils.OrientationObserver +import com.hinnka.mycamera.video.CaptureMode import com.hinnka.mycamera.video.VideoLogProfile import com.hinnka.mycamera.video.VideoRecorder @@ -36,6 +37,7 @@ import com.hinnka.mycamera.video.VideoRecorder fun CameraPreviewGL( aspectRatio: Float, previewSize: Size, + captureMode: CaptureMode, sensorOrientation: Int, lensFacing: Int, calibrationOffset: Int, @@ -69,6 +71,7 @@ fun CameraPreviewGL( val rotationDegrees = OrientationObserver.rotationDegrees val lifecycleOwner = LocalLifecycleOwner.current var glSurfaceViewRef by remember { mutableStateOf(null) } + var resumeGeneration by remember { mutableIntStateOf(0) } DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> @@ -77,6 +80,7 @@ fun CameraPreviewGL( Lifecycle.Event.ON_RESUME -> { glSurfaceViewRef?.onResume() glSurfaceViewRef?.restoreRenderStateAfterResume() + resumeGeneration++ } else -> Unit } @@ -120,6 +124,7 @@ fun CameraPreviewGL( // 标记是否已经通知过 SurfaceTexture var surfaceTextureNotified by remember { mutableStateOf(false) } var notifiedPreviewSize by remember { mutableStateOf(null) } + var notifiedResumeGeneration by remember { mutableIntStateOf(-1) } // 标记 Surface 是否已经准备好 var surfaceAvailable by remember { mutableStateOf(false) } @@ -139,7 +144,7 @@ fun CameraPreviewGL( } ) { // GLSurfaceView 用于相机预览 - key(previewSize.width, previewSize.height) { + key(previewSize.width, previewSize.height, captureMode) { AndroidView( factory = { ctx -> CameraGLSurfaceView(ctx).apply { @@ -160,10 +165,13 @@ fun CameraPreviewGL( } glSurfaceView.onSurfaceDestroyed = { - surfaceAvailable = false - surfaceTextureNotified = false - notifiedPreviewSize = null - onSurfaceDestroyed() + if (glSurfaceViewRef === glSurfaceView) { + surfaceAvailable = false + surfaceTextureNotified = false + notifiedPreviewSize = null + notifiedResumeGeneration = -1 + onSurfaceDestroyed() + } } glSurfaceView.onHistogramUpdated = { onHistogramUpdated?.invoke(it) } @@ -187,10 +195,13 @@ fun CameraPreviewGL( glSurfaceView.getSurfaceTexture()?.let { surfaceTexture -> glSurfaceView.setPreviewSize(previewSize.width, previewSize.height) val shouldNotifySurfaceTexture = - !surfaceTextureNotified || notifiedPreviewSize != previewSize + !surfaceTextureNotified || + notifiedPreviewSize != previewSize || + notifiedResumeGeneration != resumeGeneration if (shouldNotifySurfaceTexture) { surfaceTextureNotified = true notifiedPreviewSize = previewSize + notifiedResumeGeneration = resumeGeneration onSurfaceTextureReady(surfaceTexture) } } 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 162e3ce1..85f025dd 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 @@ -194,9 +194,7 @@ fun CameraScreen( // 从后台返回时检查并恢复相机,刷新最新照片 LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { - if (cameraOpened) { - viewModel.checkAndRecoverCamera() - } + viewModel.checkAndRecoverCamera() galleryViewModel.refreshLatestPhoto() // Handle automated ghost mode permission sequence @@ -726,6 +724,7 @@ fun CameraScreen( CameraPreviewGL( aspectRatio = previewAspectRatio, previewSize = previewSize, + captureMode = state.captureMode, sensorOrientation = state.getCurrentCameraInfo()?.sensorOrientation ?: 0, lensFacing = if (state.getCurrentCameraInfo()?.lensFacing == android.hardware.camera2.CameraCharacteristics.LENS_FACING_FRONT) 0 else 1, calibrationOffset = calibrationOffset, diff --git a/app/src/main/java/com/hinnka/mycamera/ui/components/FocusIndicator.kt b/app/src/main/java/com/hinnka/mycamera/ui/components/FocusIndicator.kt index 4065bd1c..f6db387b 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/components/FocusIndicator.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/components/FocusIndicator.kt @@ -69,10 +69,10 @@ fun FocusIndicator( val x = position.first * size.width val y = position.second * size.height val isAiFocus = source == FocusPointSource.AI - val boxSize = (if (isAiFocus) 38.dp else 60.dp).toPx() * scale + val boxSize = (if (isAiFocus) 20.dp else 60.dp).toPx() * scale val halfSize = boxSize / 2 - val cornerLength = (if (isAiFocus) 9.dp else 15.dp).toPx() - val strokeWidth = (if (isAiFocus) 1.5.dp else 2.dp).toPx() + val cornerLength = (if (isAiFocus) 5.dp else 15.dp).toPx() + val strokeWidth = (if (isAiFocus) 1.dp else 2.dp).toPx() val drawColor = color.copy(alpha = alpha) 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 c5be9506..af3f8bc5 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -838,6 +838,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) * 关闭相机 */ fun closeCamera() { + currentSurfaceTexture = null cameraController.closeCamera() } @@ -1468,7 +1469,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val shouldDisableVideoLog = mode == CaptureMode.PHOTO && state.value.videoConfig.logProfile != VideoLogProfile.OFF cameraController.setCaptureMode(mode) - reopenCamera() + cameraController.previewAiFocusProcessor.resetForPreviewRestart() + currentSurfaceTexture = null + cameraController.closeCamera() viewModelScope.launch { userPreferencesRepository.saveCaptureMode(mode) if (shouldDisableVideoLog) {