feat: implement AI smart focus using YOLOX object detection

This commit is contained in:
Hinnka committed 2026-05-15 23:42:35 +08:00
1 parent 1d14bf6842
commit 6e79c7afd8
17 files changed
+965 -31

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
person
bicycle
car
motorcycle
airplane
bus
train
truck
boat
traffic light
fire hydrant
stop sign
parking meter
bench
bird
cat
dog
horse
sheep
cow
elephant
bear
zebra
giraffe
backpack
umbrella
handbag
tie
suitcase
frisbee
skis
snowboard
sports ball
kite
baseball bat
baseball glove
skateboard
surfboard
tennis racket
bottle
wine glass
cup
fork
knife
spoon
bowl
banana
apple
sandwich
orange
broccoli
carrot
hot dog
pizza
donut
cake
chair
couch
potted plant
bed
dining table
toilet
tv
laptop
mouse
remote
keyboard
cell phone
microwave
oven
toaster
sink
refrigerator
book
clock
vase
scissors
teddy bear
hair drier
toothbrush
Binary file not shown.
@@ -92,6 +92,7 @@ class Camera2Controller(private val context: Context) {
private const val SCENE_CHANGE_FOCUS_DISTANCE_DELTA = 0.2f // 焦距跳变阈值(diopters),对焦锁定后逐帧跟踪
private const val FOCUS_LOCK_SETTLE_FRAMES = 5 // 对焦锁定后等待镜头稳定的帧数
private const val SCENE_CHANGE_CONFIRM_FRAMES = 3 // 连续 N 帧检测到变化才确认
private const val AI_SUBJECT_RECENT_MS = 1800L
}
private val cameraManager: CameraManager by lazy {
@@ -116,6 +117,7 @@ class Camera2Controller(private val context: Context) {
private var imageReader: ImageReader? = null
val previewDepthProcessor = com.hinnka.mycamera.preview.PreviewDepthProcessor(context)
val previewAiFocusProcessor = com.hinnka.mycamera.preview.PreviewAiFocusProcessor(context)
// 降噪等级 (0=Off, 1=Fast, 2=High Quality, 3=ZSL, 4=Minimal, 5=Auto)
@@ -210,6 +212,9 @@ class Camera2Controller(private val context: Context) {
private var focusLockedReferenceDistance: Float = 0f
private var focusLockSettleFrames = 0 // 对焦锁定后等待镜头稳定的帧数
private var sceneChangeFrameCount = 0
private var aiSubjectLastSeenElapsedMs: Long = 0L
private var aiSubjectLastSeenX: Float = -1f
private var aiSubjectLastSeenY: Float = -1f
// 高光优先测光:最亮区域坐标(归一化 0-1)及平滑状态
@Volatile
@@ -334,13 +339,13 @@ class Camera2Controller(private val context: Context) {
if (_state.value.isFocusing) {
when (afState) {
CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED -> {
_state.value = _state.value.copy(focusSuccess = true)
_state.value = _state.value.copy(isFocusing = false, focusSuccess = true)
// 只在首次锁定时记录一次,后续 AF 狩猎重新锁定不再覆盖
if (!isFocusLockedWaitingForSceneChange) recordFocusLockExposure(result)
}
CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED -> {
_state.value = _state.value.copy(focusSuccess = false)
_state.value = _state.value.copy(isFocusing = false, focusSuccess = false)
if (!isFocusLockedWaitingForSceneChange) recordFocusLockExposure(result)
}
}
@@ -383,9 +388,14 @@ class Camera2Controller(private val context: Context) {
}
if (sceneChanged) {
sceneChangeFrameCount++
if (sceneChangeFrameCount >= SCENE_CHANGE_CONFIRM_FRAMES) {
restoreContinuousAf()
if (isAiSubjectRecentlySeen()) {
updateFocusLockSceneReference(result)
sceneChangeFrameCount = 0
} else {
sceneChangeFrameCount++
if (sceneChangeFrameCount >= SCENE_CHANGE_CONFIRM_FRAMES) {
restoreContinuousAf()
}
}
} else {
sceneChangeFrameCount = 0
@@ -2702,16 +2712,29 @@ class Camera2Controller(private val context: Context) {
// ==================== 对焦控制 ====================
private fun recordFocusLockExposure(result: CaptureResult) {
val iso = result.get(CaptureResult.SENSOR_SENSITIVITY) ?: return
val exposure = result.get(CaptureResult.SENSOR_EXPOSURE_TIME) ?: return
focusLockedReferenceIso = iso
focusLockedReferenceExposureNs = exposure
focusLockedReferenceDistance = result.get(CaptureResult.LENS_FOCUS_DISTANCE) ?: 0f
updateFocusLockSceneReference(result)
isFocusLockedWaitingForSceneChange = true
focusLockSettleFrames = FOCUS_LOCK_SETTLE_FRAMES
sceneChangeFrameCount = 0
}
private fun updateFocusLockSceneReference(result: CaptureResult) {
focusLockedReferenceIso = result.get(CaptureResult.SENSOR_SENSITIVITY) ?: return
focusLockedReferenceExposureNs = result.get(CaptureResult.SENSOR_EXPOSURE_TIME) ?: return
focusLockedReferenceDistance = result.get(CaptureResult.LENS_FOCUS_DISTANCE) ?: 0f
}
private fun isAiSubjectRecentlySeen(): Boolean {
if (aiSubjectLastSeenElapsedMs <= 0L) return false
return SystemClock.elapsedRealtime() - aiSubjectLastSeenElapsedMs <= AI_SUBJECT_RECENT_MS
}
fun notifyAiSubjectSeen(x: Float, y: Float) {
aiSubjectLastSeenElapsedMs = SystemClock.elapsedRealtime()
aiSubjectLastSeenX = x
aiSubjectLastSeenY = y
}
private fun restoreContinuousAf() {
isFocusLockedWaitingForSceneChange = false
sceneChangeFrameCount = 0
@@ -2728,13 +2751,27 @@ class Camera2Controller(private val context: Context) {
applyMeteringRegions()
updatePreview()
}
_state.value = _state.value.copy(isFocusing = false, focusSuccess = null)
_state.value = _state.value.copy(focusPoint = null, isFocusing = false, focusSuccess = null)
}
fun cancelSubjectFocus(reason: String) {
PLog.d(TAG, "Cancel subject focus: $reason")
restoreContinuousAf()
}
/**
* 点击对焦
*/
fun focusOnPoint(x: Float, y: Float, viewWidth: Int, viewHeight: Int) {
if (viewWidth <= 0 || viewHeight <= 0) return
focusOnNormalizedPoint(x / viewWidth, y / viewHeight, FocusPointSource.MANUAL)
}
fun focusOnNormalizedPoint(
normX: Float,
normY: Float,
source: FocusPointSource = FocusPointSource.AI,
) {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return
@@ -2749,12 +2786,13 @@ class Camera2Controller(private val context: Context) {
val lensFacing = getLensFacing()
// 计算归一化坐标(0-1)
val normX = x / viewWidth
val normY = y / viewHeight
val normalizedX = normX.coerceIn(0f, 1f)
val normalizedY = normY.coerceIn(0f, 1f)
// 存储UI坐标用于显示对焦框
_state.value = _state.value.copy(
focusPoint = Pair(normX, normY),
focusPoint = Pair(normalizedX, normalizedY),
focusPointSource = source,
isFocusing = true,
focusSuccess = null
)
@@ -2762,11 +2800,11 @@ class Camera2Controller(private val context: Context) {
// 根据传感器方向转换坐标
// 传感器坐标系与UI坐标系可能不同,需要旋转
val (sensorX, sensorY) = when (sensorOrientation) {
0 -> Pair(normX, normY)
90 -> Pair(normY, 1 - normX) // 顺时针90度
180 -> Pair(1 - normX, 1 - normY) // 180度
270 -> Pair(1 - normY, normX) // 顺时针270度
else -> Pair(normX, normY)
0 -> Pair(normalizedX, normalizedY)
90 -> Pair(normalizedY, 1 - normalizedX) // 顺时针90度
180 -> Pair(1 - normalizedX, 1 - normalizedY) // 180度
270 -> Pair(1 - normalizedY, normalizedX) // 顺时针270度
else -> Pair(normalizedX, normalizedY)
}
// 如果是前置摄像头,需要水平翻转
@@ -2811,7 +2849,7 @@ class Camera2Controller(private val context: Context) {
MeteringRectangle(aeRect, MeteringRectangle.METERING_WEIGHT_MAX)
}
PLog.d(TAG, "Focus: UI($normX, $normY) -> Sensor($finalX, $finalY), mode=${_state.value.meteringMode}")
PLog.d(TAG, "Focus: UI($normalizedX, $normalizedY) -> Sensor($finalX, $finalY), mode=${_state.value.meteringMode}")
previewRequestBuilder?.apply {
if (maxAfRegions > 0) {
@@ -3628,6 +3666,8 @@ class Camera2Controller(private val context: Context) {
*/
fun release() {
closeCamera()
previewDepthProcessor.release()
previewAiFocusProcessor.release()
videoRecorder.release()
stopBackgroundThread()
cameraDiscovery.clearCache()
@@ -212,6 +212,11 @@ data class CameraInfo(
}
}
enum class FocusPointSource {
MANUAL,
AI
}
/**
* 相机状态数据类
*/
@@ -244,6 +249,7 @@ data class CameraState(
val focusDistance: Float = 0f, // 当前对焦距离 (0.0 - minimumFocusDistance)
val minimumFocusDistance: Float = 0f, // 最小对焦距离
val focusPoint: Pair<Float, Float>? = null, // normalized coordinates (0-1)
val focusPointSource: FocusPointSource = FocusPointSource.MANUAL,
val isFocusing: Boolean = false,
val focusSuccess: Boolean? = null,
val currentAfMode: Int? = null, // 当前的 AF 模式
@@ -46,6 +46,16 @@ enum class WidgetTheme {
DARK
}
enum class AiFocusTargetMode {
OFF,
AUTO,
PERSON,
ANIMAL,
BIRD,
VEHICLE,
AIRPLANE
}
/**
* 用户偏好设置数据类
*/
@@ -75,6 +85,8 @@ data class UserPreferences(
val showGrid: Boolean = false, // 网格线显示
val showLevelIndicator: Boolean = false, // 水平仪显示
val focusPeakingEnabled: Boolean = true, // 手动对焦峰值显示
val aiFocusTargetMode: AiFocusTargetMode = AiFocusTargetMode.PERSON,
val aiFocusScoreThreshold: Float = 0.5f,
val shutterSoundEnabled: Boolean = true, // 快门声音
val vibrationEnabled: Boolean = true, // 拍摄震动
val volumeKeyAction: VolumeKeyAction = VolumeKeyAction.CAPTURE, // 音量键操作
@@ -175,6 +187,8 @@ class UserPreferencesRepository(private val context: Context) {
private val SHOW_GRID = booleanPreferencesKey("show_grid")
private val SHOW_LEVEL_INDICATOR = booleanPreferencesKey("show_level_indicator")
private val FOCUS_PEAKING_ENABLED = booleanPreferencesKey("focus_peaking_enabled")
private val AI_FOCUS_TARGET_MODE = stringPreferencesKey("ai_focus_target_mode")
private val AI_FOCUS_SCORE_THRESHOLD = floatPreferencesKey("ai_focus_score_threshold")
private val SHUTTER_SOUND_ENABLED = booleanPreferencesKey("shutter_sound_enabled")
private val VIBRATION_ENABLED = booleanPreferencesKey("vibration_enabled")
private val VOLUME_KEY_ACTION = stringPreferencesKey("volume_key_action")
@@ -288,6 +302,10 @@ class UserPreferencesRepository(private val context: Context) {
showGrid = preferences[SHOW_GRID] ?: false,
showLevelIndicator = preferences[SHOW_LEVEL_INDICATOR] ?: false,
focusPeakingEnabled = preferences[FOCUS_PEAKING_ENABLED] ?: true,
aiFocusTargetMode = runCatching {
AiFocusTargetMode.valueOf(preferences[AI_FOCUS_TARGET_MODE] ?: AiFocusTargetMode.PERSON.name)
}.getOrDefault(AiFocusTargetMode.PERSON),
aiFocusScoreThreshold = (preferences[AI_FOCUS_SCORE_THRESHOLD] ?: 0.5f).coerceIn(0.05f, 0.95f),
shutterSoundEnabled = preferences[SHUTTER_SOUND_ENABLED] ?: true,
vibrationEnabled = preferences[VIBRATION_ENABLED] ?: true,
volumeKeyAction = VolumeKeyAction.valueOf(
@@ -692,6 +710,18 @@ class UserPreferencesRepository(private val context: Context) {
}
}
suspend fun saveAiFocusTargetMode(mode: AiFocusTargetMode) {
context.dataStore.edit { preferences ->
preferences[AI_FOCUS_TARGET_MODE] = mode.name
}
}
suspend fun saveAiFocusScoreThreshold(value: Float) {
context.dataStore.edit { preferences ->
preferences[AI_FOCUS_SCORE_THRESHOLD] = value.coerceIn(0.05f, 0.95f)
}
}
/**
* 保存是否启用快门声音
*/
@@ -133,6 +133,13 @@ class LutRenderer : GLSurfaceView.Renderer {
private val depthInputBuffer = ByteBuffer.allocateDirect(DEPTH_INPUT_SIZE * DEPTH_INPUT_SIZE * 4)
private var lastRunDepthInputTime: Long = 0
var onDepthInputAvailable: ((Bitmap) -> Unit)? = null
private var aiFocusInputFboId: Int = 0
private var aiFocusInputTextureId: Int = 0
private var aiFocusInputPboId: Int = 0
private val AI_FOCUS_INPUT_SIZE = 640
private val aiFocusInputBuffer = ByteBuffer.allocateDirect(AI_FOCUS_INPUT_SIZE * AI_FOCUS_INPUT_SIZE * 4)
private var lastRunAiFocusInputTime: Long = 0
var onAiFocusInputAvailable: ((Bitmap) -> Unit)? = null
// FBO 相关
private var fboId: Int = 0
@@ -574,6 +581,9 @@ class LutRenderer : GLSurfaceView.Renderer {
depthInputFboId = 0
depthInputTextureId = 0
depthInputPboId = 0
aiFocusInputFboId = 0
aiFocusInputTextureId = 0
aiFocusInputPboId = 0
fboId = 0
fboTextureId = 0
stackFboId = 0
@@ -626,6 +636,7 @@ class LutRenderer : GLSurfaceView.Renderer {
initFbo(width, height)
initMeteringFbo()
initDepthInputFbo()
initAiFocusInputFbo()
// 更新 MVP 矩阵以处理 center crop
updateMVPMatrix()
@@ -933,12 +944,13 @@ class LutRenderer : GLSurfaceView.Renderer {
val halationEnabled = redHalation > 0.001f
val postProcessEffectEnabled = hdfEnabled || halationEnabled
val bokehNeeded = aperture > 0f && depthMap != null
val aiFocusInputNeeded = onAiFocusInputAvailable != null && isAutoFocus
val suppressBaselineLayerForVideoLog = videoLogProfile.isEnabled
val hasBaselineLayer = hasBaselineLayer() && !suppressBaselineLayerForVideoLog
val hasCreativeLayer = hasCreativeLayer()
val hasDualLayer = hasBaselineLayer && hasCreativeLayer
uploadPendingCurveTextures()
val needsFbo = (liveRecorder != null || activeVideoRecorder != null || postProcessEffectEnabled || bokehNeeded || hasDualLayer || (!isAutoFocus && focusPeakingEnabled)) &&
val needsFbo = (liveRecorder != null || activeVideoRecorder != null || postProcessEffectEnabled || bokehNeeded || aiFocusInputNeeded || hasDualLayer || (!isAutoFocus && focusPeakingEnabled)) &&
fboId != 0 && fboTextureId != 0
if (needsFbo) {
@@ -990,6 +1002,9 @@ class LutRenderer : GLSurfaceView.Renderer {
if (aperture > 0f) {
runDepthInputCaptureInternal(currentTexId)
}
if (aiFocusInputNeeded) {
runAiFocusInputCaptureInternal(currentTexId)
}
// 2. Bokeh 处理
if (bokehNeeded) {
@@ -1705,6 +1720,34 @@ class LutRenderer : GLSurfaceView.Renderer {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
private fun initAiFocusInputFbo() {
if (aiFocusInputFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(aiFocusInputFboId), 0)
aiFocusInputFboId = 0
}
if (aiFocusInputTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(aiFocusInputTextureId), 0)
aiFocusInputTextureId = 0
}
val fbos = IntArray(1)
GLES30.glGenFramebuffers(1, fbos, 0)
aiFocusInputFboId = fbos[0]
val textures = IntArray(1)
GLES30.glGenTextures(1, textures, 0)
aiFocusInputTextureId = textures[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, aiFocusInputTextureId)
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, AI_FOCUS_INPUT_SIZE, AI_FOCUS_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, aiFocusInputFboId)
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, aiFocusInputTextureId, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
}
private fun initCaptureFbo() {
if (captureFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(captureFboId), 0)
@@ -2368,6 +2411,73 @@ class LutRenderer : GLSurfaceView.Renderer {
GLES30.glViewport(0, 0, viewportWidth, viewportHeight)
}
private fun runAiFocusInputCaptureInternal(sourceTextureId: Int) {
if (onAiFocusInputAvailable == null || sourceTextureId == 0) return
val now = System.currentTimeMillis()
if (now - lastRunAiFocusInputTime < 60) return
lastRunAiFocusInputTime = now
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, aiFocusInputFboId)
GLES30.glViewport(0, 0, AI_FOCUS_INPUT_SIZE, AI_FOCUS_INPUT_SIZE)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
GLES30.glUseProgram(copyProgramId)
val captureMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(captureMatrix, 0)
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.glUniform4f(uCopyCropRectLoc, 0f, 0f, 1f, 1f)
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 = AI_FOCUS_INPUT_SIZE * AI_FOCUS_INPUT_SIZE * 4
if (aiFocusInputPboId == 0) {
val pbos = IntArray(1)
GLES30.glGenBuffers(1, pbos, 0)
aiFocusInputPboId = pbos[0]
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, aiFocusInputPboId)
GLES30.glBufferData(GLES30.GL_PIXEL_PACK_BUFFER, pixelSize, null, GLES30.GL_STREAM_READ)
} else {
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, aiFocusInputPboId)
}
GLES30.glReadPixels(0, 0, AI_FOCUS_INPUT_SIZE, AI_FOCUS_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) {
aiFocusInputBuffer.rewind()
aiFocusInputBuffer.put(mappedBuffer)
GLES30.glUnmapBuffer(GLES30.GL_PIXEL_PACK_BUFFER)
val bitmap = Bitmap.createBitmap(AI_FOCUS_INPUT_SIZE, AI_FOCUS_INPUT_SIZE, Bitmap.Config.ARGB_8888)
aiFocusInputBuffer.rewind()
bitmap.copyPixelsFromBuffer(aiFocusInputBuffer)
onAiFocusInputAvailable?.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() {
@@ -2570,6 +2680,14 @@ class LutRenderer : GLSurfaceView.Renderer {
GLES30.glDeleteBuffers(1, intArrayOf(meteringPboId), 0)
meteringPboId = 0
}
if (depthInputPboId != 0) {
GLES30.glDeleteBuffers(1, intArrayOf(depthInputPboId), 0)
depthInputPboId = 0
}
if (aiFocusInputPboId != 0) {
GLES30.glDeleteBuffers(1, intArrayOf(aiFocusInputPboId), 0)
aiFocusInputPboId = 0
}
if (meteringFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(meteringFboId), 0)
@@ -2587,6 +2705,22 @@ class LutRenderer : GLSurfaceView.Renderer {
GLES30.glDeleteTextures(1, intArrayOf(captureTextureId), 0)
captureTextureId = 0
}
if (depthInputFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(depthInputFboId), 0)
depthInputFboId = 0
}
if (depthInputTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(depthInputTextureId), 0)
depthInputTextureId = 0
}
if (aiFocusInputFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(aiFocusInputFboId), 0)
aiFocusInputFboId = 0
}
if (aiFocusInputTextureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(aiFocusInputTextureId), 0)
aiFocusInputTextureId = 0
}
if (recordFboId != 0) {
GLES30.glDeleteFramebuffers(1, intArrayOf(recordFboId), 0)
recordFboId = 0
@@ -0,0 +1,51 @@
package com.hinnka.mycamera.ml
import android.content.Context
import com.hinnka.mycamera.data.AiFocusTargetMode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
object SharedYoloXObjectDetector {
private val mutex = Mutex()
private var detector: YoloXObjectDetector? = null
suspend fun prewarm(context: Context) {
withDetector(context) { }
}
suspend fun detect(
context: Context,
bitmap: android.graphics.Bitmap,
targetMode: AiFocusTargetMode,
scoreThreshold: Float,
): List<YoloXObjectDetector.Detection> {
return withDetector(context) { detector ->
detector.targetMode = targetMode
detector.scoreThreshold = scoreThreshold.coerceIn(0.05f, 0.95f)
detector.detect(bitmap)
}
}
suspend fun release() {
withContext(Dispatchers.Default) {
mutex.withLock {
detector?.close()
detector = null
}
}
}
private suspend fun <T> withDetector(
context: Context,
block: (YoloXObjectDetector) -> T,
): T = withContext(Dispatchers.Default) {
mutex.withLock {
val activeDetector = detector ?: YoloXObjectDetector(context.applicationContext).also {
detector = it
}
block(activeDetector)
}
}
}
@@ -0,0 +1,254 @@
package com.hinnka.mycamera.ml
import android.content.Context
import android.graphics.Bitmap
import com.hinnka.mycamera.data.AiFocusTargetMode
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 kotlin.math.max
class YoloXObjectDetector(context: Context) {
data class Detection(
val label: String,
val score: Float,
val left: Float,
val top: Float,
val right: Float,
val bottom: Float,
val priority: Int,
) {
val centerX: Float get() = ((left + right) * 0.5f).coerceIn(0f, 1f)
val centerY: Float get() = ((top + bottom) * 0.5f).coerceIn(0f, 1f)
val focusX: Float get() = centerX
val focusY: Float get() = (top + (bottom - top) * focusYOffset).coerceIn(0f, 1f)
val area: Float get() = max(0f, right - left) * max(0f, bottom - top)
private val focusYOffset: Float
get() = when (priority) {
3 -> 0.28f
2 -> 0.38f
else -> 0.5f
}
}
private var interpreter: Interpreter? = null
private var gpuDelegate: GpuDelegate? = null
private var nnApiDelegate: NnApiDelegate? = null
private var isInitialized = false
private var activeBackend = "NONE"
private val labels: List<String>
@Volatile
var targetMode: AiFocusTargetMode = AiFocusTargetMode.PERSON
@Volatile
var scoreThreshold: Float = 0.5f
init {
labels = runCatching {
context.assets.open(LABELS_ASSET).bufferedReader().use { it.readLines() }
}.getOrElse {
PLog.e(TAG, "Failed to load YOLOX labels", it)
emptyList()
}
try {
val modelFile = StartupTrace.measure("YoloXObjectDetector.loadMappedFile") {
FileUtil.loadMappedFile(context, MODEL_ASSET)
}
val compatList = StartupTrace.measure("YoloXObjectDetector.CompatibilityList") {
CompatibilityList()
}
try {
val gpuOptions = Interpreter.Options()
gpuDelegate = StartupTrace.measure("YoloXObjectDetector.GpuDelegate") {
if (compatList.isDelegateSupportedOnThisDevice) {
GpuDelegate(compatList.bestOptionsForThisDevice)
} else {
GpuDelegate()
}
}
gpuOptions.addDelegate(gpuDelegate)
interpreter = StartupTrace.measure("YoloXObjectDetector.Interpreter.GPU") {
Interpreter(modelFile, gpuOptions)
}
activeBackend = "GPU"
PLog.d(TAG, "Using GPU delegate for YOLOX object detector")
} catch (e: Exception) {
PLog.w(TAG, "Failed to initialize YOLOX with GPU, falling back to NNAPI", e)
gpuDelegate?.close()
gpuDelegate = null
}
if (interpreter == null) {
val nnApiOptions = Interpreter.Options().apply {
setNumThreads(2)
}
nnApiDelegate = StartupTrace.measure("YoloXObjectDetector.NnApiDelegate") {
NnApiDelegate()
}
nnApiOptions.addDelegate(nnApiDelegate)
try {
interpreter = StartupTrace.measure("YoloXObjectDetector.Interpreter.NNAPI") {
Interpreter(modelFile, nnApiOptions)
}
activeBackend = "NNAPI"
PLog.d(TAG, "Using NNAPI for YOLOX object detector")
} catch (e: Exception) {
PLog.w(TAG, "Failed to initialize YOLOX with NNAPI, falling back to CPU", e)
nnApiDelegate?.close()
nnApiDelegate = null
}
}
if (interpreter == null) {
interpreter = Interpreter(modelFile, Interpreter.Options().apply { setNumThreads(4) })
activeBackend = "CPU"
PLog.d(TAG, "Using CPU for YOLOX object detector")
}
isInitialized = true
} catch (e: Exception) {
PLog.e(TAG, "Error initializing YOLOX object detector", e)
}
}
fun detect(inputBitmap: Bitmap): List<Detection> {
val activeInterpreter = interpreter
if (!isInitialized || activeInterpreter == null) {
PLog.e(TAG, "YOLOX object detector is not initialized")
return emptyList()
}
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)
activeInterpreter.runForMultipleInputsOutputs(arrayOf(input), outputs)
val detections = parseDetections(boxes, scores, classIdx)
detections
} catch (e: Exception) {
PLog.e(TAG, "Error during YOLOX inference", e)
emptyList()
}
}
fun close() {
interpreter?.close()
interpreter = null
gpuDelegate?.close()
gpuDelegate = null
nnApiDelegate?.close()
nnApiDelegate = null
isInitialized = false
activeBackend = "NONE"
}
private fun createInputBuffer(inputBitmap: Bitmap): ByteBuffer {
val scaled = if (inputBitmap.width == INPUT_SIZE && inputBitmap.height == INPUT_SIZE) {
inputBitmap
} 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())
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())
}
buffer.rewind()
return buffer
}
private fun parseDetections(
boxes: ByteBuffer,
scores: ByteBuffer,
classIdx: ByteBuffer,
): List<Detection> {
boxes.rewind()
scores.rewind()
classIdx.rewind()
val detections = ArrayList<Detection>()
repeat(DETECTION_COUNT) { index ->
val score = dequantize(scores.get(index), SCORE_SCALE, SCORE_ZERO_POINT)
if (score < scoreThreshold) return@repeat
val labelIndex = classIdx.get(index).toInt() and 0xFF
val priority = priorityForClass(labelIndex, targetMode)
if (priority == 0) return@repeat
val boxOffset = index * 4
val left = dequantize(boxes.get(boxOffset), BOX_SCALE, BOX_ZERO_POINT) / INPUT_SIZE
val top = dequantize(boxes.get(boxOffset + 1), BOX_SCALE, BOX_ZERO_POINT) / INPUT_SIZE
val right = dequantize(boxes.get(boxOffset + 2), BOX_SCALE, BOX_ZERO_POINT) / INPUT_SIZE
val bottom = dequantize(boxes.get(boxOffset + 3), BOX_SCALE, BOX_ZERO_POINT) / INPUT_SIZE
if (right <= left || bottom <= top) return@repeat
detections += Detection(
label = labels.getOrElse(labelIndex) { labelIndex.toString() },
score = score,
left = left.coerceIn(0f, 1f),
top = top.coerceIn(0f, 1f),
right = right.coerceIn(0f, 1f),
bottom = bottom.coerceIn(0f, 1f),
priority = priority,
)
}
return detections
}
private fun dequantize(value: Byte, scale: Float, zeroPoint: Int): Float {
return ((value.toInt() and 0xFF) - zeroPoint) * scale
}
private fun priorityForClass(classIndex: Int, mode: AiFocusTargetMode): Int {
return when (mode) {
AiFocusTargetMode.OFF -> 0
AiFocusTargetMode.AUTO -> when (classIndex) {
PERSON_CLASS -> 3
BIRD_CLASS -> 2
in ANIMAL_CLASSES -> 2
in VEHICLE_CLASSES -> 1
else -> 0
}
AiFocusTargetMode.PERSON -> if (classIndex == PERSON_CLASS) 3 else 0
AiFocusTargetMode.ANIMAL -> if (classIndex in ANIMAL_CLASSES) 2 else 0
AiFocusTargetMode.BIRD -> if (classIndex == BIRD_CLASS) 2 else 0
AiFocusTargetMode.VEHICLE -> if (classIndex in GROUND_VEHICLE_CLASSES) 1 else 0
AiFocusTargetMode.AIRPLANE -> if (classIndex == AIRPLANE_CLASS) 1 else 0
}
}
companion object {
private const val TAG = "YoloXObjectDetector"
private const val MODEL_ASSET = "yolox.tflite"
private const val LABELS_ASSET = "labels.txt"
private const val INPUT_SIZE = 640
private const val DETECTION_COUNT = 8400
private const val BOX_SCALE = 4.4156656f
private const val BOX_ZERO_POINT = 51
private const val SCORE_SCALE = 0.0038128477f
private const val SCORE_ZERO_POINT = 0
private const val PERSON_CLASS = 0
private const val BIRD_CLASS = 14
private const val AIRPLANE_CLASS = 4
private val ANIMAL_CLASSES = setOf(15, 16, 17, 18, 19, 20, 21, 22, 23)
private val GROUND_VEHICLE_CLASSES = setOf(1, 2, 3, 5, 6, 7, 8)
private val VEHICLE_CLASSES = GROUND_VEHICLE_CLASSES + AIRPLANE_CLASS
}
}
@@ -0,0 +1,188 @@
package com.hinnka.mycamera.preview
import android.content.Context
import android.graphics.Bitmap
import com.hinnka.mycamera.data.AiFocusTargetMode
import com.hinnka.mycamera.ml.SharedYoloXObjectDetector
import com.hinnka.mycamera.ml.YoloXObjectDetector
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.StartupTrace
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.math.hypot
class PreviewAiFocusProcessor(private val context: Context) {
companion object {
private const val TAG = "PreviewAiFocusProcessor"
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
}
data class FocusTarget(
val x: Float,
val y: Float,
val label: String,
val score: Float,
val priority: Int,
)
private val scope = CoroutineScope(Dispatchers.Default + Job())
@Volatile
private var isPrewarming = false
@Volatile
private var isPrewarmed = false
@Volatile
private var isProcessing = false
@Volatile
var targetMode: AiFocusTargetMode = AiFocusTargetMode.PERSON
@Volatile
var scoreThreshold: Float = 0.5f
private var lastFocusTimeMs = 0L
private var lastFocusX = -1f
private var lastFocusY = -1f
private var targetMissingFrames = 0
private var lastDetectionLogTimeMs = 0L
var onFocusTarget: ((FocusTarget) -> Unit)? = null
var onTargetSeen: ((FocusTarget) -> Unit)? = null
var onTargetLost: (() -> Unit)? = null
fun prewarm() {
if (isPrewarmed || isPrewarming) return
isPrewarming = true
scope.launch {
try {
StartupTrace.mark("PreviewAiFocusProcessor.prewarm start")
SharedYoloXObjectDetector.prewarm(context)
isPrewarmed = true
StartupTrace.mark("PreviewAiFocusProcessor.prewarm end")
} catch (e: Exception) {
PLog.e(TAG, "Failed to prewarm YOLOX object detector", e)
} finally {
isPrewarming = false
}
}
}
fun processBitmap(bitmap: Bitmap) {
if (targetMode == AiFocusTargetMode.OFF) {
handleMissingTarget()
return
}
if (isProcessing) return
if (!isPrewarmed) {
prewarm()
return
}
isProcessing = true
scope.launch {
val startTimeMs = System.currentTimeMillis()
try {
val detections = SharedYoloXObjectDetector.detect(
context = context,
bitmap = bitmap,
targetMode = targetMode,
scoreThreshold = scoreThreshold
)
val target = selectFocusTarget(detections)
if (target == null) {
handleMissingTarget()
return@launch
}
targetMissingFrames = 0
val seenTarget = FocusTarget(
x = target.focusX,
y = target.focusY,
label = target.label,
score = target.score,
priority = target.priority,
)
onTargetSeen?.invoke(seenTarget)
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}"
)
onFocusTarget?.invoke(seenTarget)
} catch (e: Exception) {
PLog.e(TAG, "Error processing preview bitmap for AI focus", e)
} finally {
isProcessing = false
}
}
}
fun release() {
isPrewarmed = false
}
private fun selectFocusTarget(
detections: List<YoloXObjectDetector.Detection>,
): YoloXObjectDetector.Detection? {
if (detections.isEmpty()) return null
val hasTrackedTarget = lastFocusX >= 0f && lastFocusY >= 0f
if (hasTrackedTarget) {
val trackedPriority = detections.maxOf { it.priority }
val trackedCandidates = detections
.filter { it.priority == trackedPriority }
.map { detection ->
val distance = hypot(detection.focusX - lastFocusX, detection.focusY - lastFocusY)
detection to distance
}
.filter { (_, distance) -> distance <= TRACK_KEEP_DISTANCE }
if (trackedCandidates.isNotEmpty()) {
return trackedCandidates.maxWithOrNull(
compareBy<Pair<YoloXObjectDetector.Detection, Float>> { -it.second }
.thenBy { it.first.score }
.thenBy { it.first.area }
)?.first
}
}
return detections.maxWithOrNull(
compareBy<YoloXObjectDetector.Detection> { it.priority }
.thenBy { it.score }
.thenBy { it.area }
)
}
private fun shouldRefocus(target: YoloXObjectDetector.Detection): Boolean {
val now = System.currentTimeMillis()
if (now - lastFocusTimeMs < MIN_FOCUS_INTERVAL_MS) return false
if (lastFocusX < 0f || lastFocusY < 0f) return true
return hypot(target.focusX - lastFocusX, target.focusY - lastFocusY) >= MIN_TARGET_MOVE
}
private fun handleMissingTarget() {
if (lastFocusX < 0f || lastFocusY < 0f) return
targetMissingFrames++
if (targetMissingFrames < TARGET_LOST_CONFIRM_FRAMES) return
PLog.d(TAG, "AI focus target lost: frames=$targetMissingFrames")
targetMissingFrames = 0
lastFocusX = -1f
lastFocusY = -1f
lastFocusTimeMs = 0L
onTargetLost?.invoke()
}
private fun logTargetSeen(target: YoloXObjectDetector.Detection, startTimeMs: Long, elapsedMs: Long) {
val intervalMs = if (lastDetectionLogTimeMs > 0L) startTimeMs - lastDetectionLogTimeMs else 0L
lastDetectionLogTimeMs = startTimeMs
PLog.d(
TAG,
"AI target seen: label=${target.label} score=${target.score} x=${target.focusX} y=${target.focusY} interval=${intervalMs}ms inference=${elapsedMs}ms"
)
}
}
@@ -39,6 +39,7 @@ class CameraGLSurfaceView @JvmOverloads constructor(
var onMeteringUpdated: ((Double, Double) -> Unit)? = null
var onHighlightPointUpdated: ((Float, Float) -> Unit)? = null
var onDepthInputAvailable: ((Bitmap) -> Unit)? = null
var onAiFocusInputAvailable: ((Bitmap) -> Unit)? = null
var onSurfaceReady: ((Surface) -> Unit)? = null
var onSurfaceDestroyed: (() -> Unit)? = null
@@ -86,6 +87,9 @@ class CameraGLSurfaceView @JvmOverloads constructor(
renderer.onDepthInputAvailable = { bitmap ->
onDepthInputAvailable?.invoke(bitmap)
}
renderer.onAiFocusInputAvailable = { bitmap ->
onAiFocusInputAvailable?.invoke(bitmap)
}
// 保持 EGL 上下文
preserveEGLContextOnPause = true
@@ -18,6 +18,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.hinnka.mycamera.livephoto.LivePhotoRecorder
import com.hinnka.mycamera.camera.FocusPointSource
import com.hinnka.mycamera.camera.MeteringMode
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.model.ColorRecipeParams
@@ -43,6 +44,7 @@ fun CameraPreviewGL(
baselineColorRecipeParams: ColorRecipeParams,
colorRecipeParams: ColorRecipeParams,
focusPoint: Pair<Float, Float>?,
focusPointSource: FocusPointSource = FocusPointSource.MANUAL,
isFocusing: Boolean,
focusSuccess: Boolean?,
meteringMode: MeteringMode = MeteringMode.CENTER_WEIGHTED,
@@ -53,6 +55,7 @@ fun CameraPreviewGL(
onMeteringUpdated: ((Double, Double) -> Unit)? = null,
onHighlightPointUpdated: ((Float, Float) -> Unit)? = null,
onDepthInputAvailable: ((android.graphics.Bitmap) -> Unit)? = null,
onAiFocusInputAvailable: ((android.graphics.Bitmap) -> Unit)? = null,
livePhotoRecorder: LivePhotoRecorder? = null,
videoRecorder: VideoRecorder? = null,
videoLogProfile: VideoLogProfile = VideoLogProfile.OFF,
@@ -167,6 +170,7 @@ fun CameraPreviewGL(
glSurfaceView.onMeteringUpdated = { w, l -> onMeteringUpdated?.invoke(w, l) }
glSurfaceView.onHighlightPointUpdated = { hx, hy -> onHighlightPointUpdated?.invoke(hx, hy) }
glSurfaceView.onDepthInputAvailable = { onDepthInputAvailable?.invoke(it) }
glSurfaceView.onAiFocusInputAvailable = { onAiFocusInputAvailable?.invoke(it) }
viewWidth = glSurfaceView.width
viewHeight = glSurfaceView.height
@@ -206,8 +210,8 @@ fun CameraPreviewGL(
glSurfaceView.setFocusPoint(focusPoint?.let {
android.graphics.PointF(
it.first / viewWidth,
it.second / viewHeight
it.first,
it.second
)
})
glSurfaceView.setMeteringMode(meteringMode)
@@ -225,6 +229,7 @@ fun CameraPreviewGL(
// 对焦指示器
FocusIndicator(
position = focusPoint,
source = focusPointSource,
isFocusing = isFocusing,
focusSuccess = focusSuccess,
modifier = Modifier.fillMaxSize()
@@ -734,6 +734,7 @@ fun CameraScreen(
baselineColorRecipeParams = currentBaselineRecipeParams,
colorRecipeParams = previewRecipeParamsOverride ?: currentRecipeParams,
focusPoint = state.focusPoint,
focusPointSource = state.focusPointSource,
isFocusing = state.isFocusing,
focusSuccess = state.focusSuccess,
meteringMode = state.meteringMode,
@@ -758,6 +759,7 @@ fun CameraScreen(
onMeteringUpdated = { w, l -> viewModel.handleMeteringUpdate(w, l) },
onHighlightPointUpdated = { hx, hy -> viewModel.handleHighlightPointUpdate(hx, hy) },
onDepthInputAvailable = { viewModel.handleDepthMapUpdate(it) },
onAiFocusInputAvailable = { viewModel.handleAiFocusInputUpdate(it) },
onGLSurfaceViewReady = {
viewModel.glSurfaceView = it
},
@@ -9,6 +9,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.hinnka.mycamera.camera.FocusPointSource
import kotlinx.coroutines.delay
/**
@@ -17,6 +18,7 @@ import kotlinx.coroutines.delay
@Composable
fun FocusIndicator(
position: Pair<Float, Float>?,
source: FocusPointSource = FocusPointSource.MANUAL,
isFocusing: Boolean,
focusSuccess: Boolean?,
modifier: Modifier = Modifier
@@ -46,13 +48,14 @@ fun FocusIndicator(
val color = when (focusSuccess) {
true -> Color.Green
false -> Color.Red
else -> Color.White
else -> if (source == FocusPointSource.AI) Color(0xFF64D8FF) else Color.White
}
LaunchedEffect(position, isFocusing) {
visible = position != null
if (!isFocusing) {
delay(500)
LaunchedEffect(position) {
if (position != null) {
visible = true
} else {
delay(200)
visible = false
}
}
@@ -65,10 +68,11 @@ fun FocusIndicator(
) {
val x = position.first * size.width
val y = position.second * size.height
val boxSize = 60.dp.toPx() * scale
val isAiFocus = source == FocusPointSource.AI
val boxSize = (if (isAiFocus) 38.dp else 60.dp).toPx() * scale
val halfSize = boxSize / 2
val cornerLength = 15.dp.toPx()
val strokeWidth = 2.dp.toPx()
val cornerLength = (if (isAiFocus) 9.dp else 15.dp).toPx()
val strokeWidth = (if (isAiFocus) 1.5.dp else 2.dp).toPx()
val drawColor = color.copy(alpha = alpha)
@@ -127,6 +131,22 @@ fun FocusIndicator(
end = Offset(x + halfSize, y + halfSize - cornerLength),
strokeWidth = strokeWidth
)
if (isAiFocus) {
val centerTick = 3.dp.toPx()
drawLine(
color = drawColor,
start = Offset(x - centerTick, y),
end = Offset(x + centerTick, y),
strokeWidth = strokeWidth
)
drawLine(
color = drawColor,
start = Offset(x, y - centerTick),
end = Offset(x, y + centerTick),
strokeWidth = strokeWidth
)
}
}
}
}
@@ -99,6 +99,7 @@ import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.R
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.data.AiFocusTargetMode
import com.hinnka.mycamera.data.VolumeKeyAction
import com.hinnka.mycamera.frame.FrameInfo
import com.hinnka.mycamera.lut.BaselineColorCorrectionTarget
@@ -133,6 +134,19 @@ private fun openExternalUrl(context: Context, url: String) {
runCatching { context.startActivity(intent) }
}
@Composable
private fun AiFocusTargetMode.displayName(): String {
return when (this) {
AiFocusTargetMode.OFF -> stringResource(R.string.settings_ai_focus_target_off)
AiFocusTargetMode.AUTO -> stringResource(R.string.settings_ai_focus_target_auto)
AiFocusTargetMode.PERSON -> stringResource(R.string.settings_ai_focus_target_person)
AiFocusTargetMode.ANIMAL -> stringResource(R.string.settings_ai_focus_target_animal)
AiFocusTargetMode.BIRD -> stringResource(R.string.settings_ai_focus_target_bird)
AiFocusTargetMode.VEHICLE -> stringResource(R.string.settings_ai_focus_target_vehicle)
AiFocusTargetMode.AIRPLANE -> stringResource(R.string.settings_ai_focus_target_airplane)
}
}
/**
* 设置页面
*/
@@ -149,6 +163,8 @@ fun SettingsScreen(
val state by viewModel.state.collectAsState()
val showLevelIndicator by viewModel.showLevelIndicator.collectAsState(initial = false)
val focusPeakingEnabled by viewModel.focusPeakingEnabled.collectAsState(initial = true)
val aiFocusTargetMode by viewModel.aiFocusTargetMode.collectAsState()
val aiFocusScoreThreshold by viewModel.aiFocusScoreThreshold.collectAsState()
val showGrid = state.showGrid
val shutterSoundEnabled by viewModel.shutterSoundEnabled.collectAsState(initial = true)
val vibrationEnabled by viewModel.vibrationEnabled.collectAsState(initial = true)
@@ -218,6 +234,7 @@ fun SettingsScreen(
var rawExposureCompensationUi by remember { mutableStateOf(rawExposureCompensation) }
var rawBlackPointCorrectionUi by remember { mutableStateOf(rawBlackPointCorrection) }
var rawWhitePointCorrectionUi by remember { mutableStateOf(rawWhitePointCorrection) }
var aiFocusScoreThresholdUi by remember(aiFocusScoreThreshold) { mutableStateOf(aiFocusScoreThreshold) }
var showAspectRatioDialog by remember { mutableStateOf(false) }
LaunchedEffect(rawNlmNoiseFactor, rawExposureCompensation, rawBlackPointCorrection, rawWhitePointCorrection) {
@@ -724,6 +741,40 @@ fun SettingsScreen(
modifier = Modifier.padding(vertical = 8.dp)
)
val aiFocusModeOptions = AiFocusTargetMode.entries.map { it to it.displayName() }
val aiFocusModeLabels = aiFocusModeOptions.map { it.second }
DropdownSettingItem(
title = stringResource(R.string.settings_ai_focus_target),
description = stringResource(R.string.settings_ai_focus_target_description),
value = aiFocusTargetMode.displayName(),
options = aiFocusModeLabels,
isLoading = false,
onExpanded = {},
onOptionSelected = { label ->
aiFocusModeOptions.firstOrNull { it.second == label }?.first?.let {
viewModel.setAiFocusTargetMode(it)
}
}
)
SliderSettingItem(
title = stringResource(R.string.settings_ai_focus_sensitivity),
description = stringResource(R.string.settings_ai_focus_sensitivity_description),
value = aiFocusScoreThresholdUi,
valueRange = 0.05f..0.95f,
onValueChange = {
aiFocusScoreThresholdUi = it
viewModel.setAiFocusScoreThreshold(it)
},
valueTextFormatter = { String.format("%.2f", it) },
resetValue = 0.5f
)
HorizontalDivider(
color = Color.White.copy(alpha = 0.1f),
modifier = Modifier.padding(vertical = 8.dp)
)
SwitchSettingItem(
title = stringResource(R.string.settings_grid_lines),
description = stringResource(R.string.settings_grid_description),
@@ -19,6 +19,7 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.hinnka.mycamera.camera.*
import com.hinnka.mycamera.data.ContentRepository
import com.hinnka.mycamera.data.AiFocusTargetMode
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.data.VolumeKeyAction
import com.hinnka.mycamera.frame.FrameEditorDraft
@@ -203,6 +204,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 新增设置项 StateFlow
val showLevelIndicator: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.showLevelIndicator }
val focusPeakingEnabled: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.focusPeakingEnabled }
val aiFocusTargetMode: StateFlow<AiFocusTargetMode> =
userPreferencesRepository.userPreferences.map { it.aiFocusTargetMode }
.stateIn(viewModelScope, SharingStarted.Eagerly, AiFocusTargetMode.PERSON)
val aiFocusScoreThreshold: StateFlow<Float> =
userPreferencesRepository.userPreferences.map { it.aiFocusScoreThreshold }
.stateIn(viewModelScope, SharingStarted.Eagerly, 0.5f)
val shutterSoundEnabled: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.shutterSoundEnabled }
val vibrationEnabled: Flow<Boolean> = userPreferencesRepository.userPreferences.map { it.vibrationEnabled }
val volumeKeyAction: StateFlow<VolumeKeyAction> =
@@ -836,6 +843,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun prewarmDepthEstimator() {
cameraController.previewDepthProcessor.prewarm()
cameraController.previewAiFocusProcessor.prewarm()
viewModelScope.launch {
RawDemosaicProcessor.getInstance().prewarmDepthEstimator(getApplication<Application>())
}
@@ -2007,6 +2015,33 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
cameraController.previewDepthProcessor.processBitmap(bitmap)
}
fun handleAiFocusInputUpdate(bitmap: android.graphics.Bitmap) {
if (!state.value.isAutoFocus || state.value.isFocusing) return
cameraController.previewAiFocusProcessor.targetMode = aiFocusTargetMode.value
cameraController.previewAiFocusProcessor.scoreThreshold = aiFocusScoreThreshold.value
cameraController.previewAiFocusProcessor.onFocusTarget = { target ->
viewModelScope.launch(Dispatchers.Main) {
val currentState = state.value
if (currentState.focusPoint != null &&
currentState.focusPointSource == com.hinnka.mycamera.camera.FocusPointSource.MANUAL
) {
return@launch
}
if (!state.value.isAutoFocus || state.value.isFocusing) return@launch
cameraController.focusOnNormalizedPoint(target.x, target.y)
}
}
cameraController.previewAiFocusProcessor.onTargetSeen = { target ->
cameraController.notifyAiSubjectSeen(target.x, target.y)
}
cameraController.previewAiFocusProcessor.onTargetLost = {
viewModelScope.launch(Dispatchers.Main) {
cameraController.cancelSubjectFocus("ai_target_lost")
}
}
cameraController.previewAiFocusProcessor.processBitmap(bitmap)
}
// ==================== 边框相关方法 ====================
/**
@@ -2226,6 +2261,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
}
fun setAiFocusTargetMode(mode: AiFocusTargetMode) {
viewModelScope.launch {
userPreferencesRepository.saveAiFocusTargetMode(mode)
}
}
fun setAiFocusScoreThreshold(value: Float) {
viewModelScope.launch {
userPreferencesRepository.saveAiFocusScoreThreshold(value)
}
}
/**
* 设置是否启用快门声音
*/
@@ -182,6 +182,17 @@
<string name="settings_level_description">在拍摄时显示水平仪,帮助保持画面水平</string>
<string name="settings_focus_peaking">峰值对焦</string>
<string name="settings_focus_peaking_description">手动对焦时显示峰值对焦高亮</string>
<string name="settings_ai_focus_target">AI 智能对焦</string>
<string name="settings_ai_focus_target_description">选择 AI 对焦优先追踪的主体类型。</string>
<string name="settings_ai_focus_target_off">关闭</string>
<string name="settings_ai_focus_target_auto">自动</string>
<string name="settings_ai_focus_target_person">人</string>
<string name="settings_ai_focus_target_animal">动物</string>
<string name="settings_ai_focus_target_bird">鸟类</string>
<string name="settings_ai_focus_target_vehicle">车</string>
<string name="settings_ai_focus_target_airplane">飞机</string>
<string name="settings_ai_focus_sensitivity">AI 对焦灵敏度</string>
<string name="settings_ai_focus_sensitivity_description">触发 AI 对焦所需的最低检测置信度。</string>
<string name="settings_grid_lines">网格线显示</string>
<string name="settings_grid_description">在拍摄时显示网格线,辅助构图</string>
<string name="settings_use_multi_frame">多帧降噪</string>
+11
View File
@@ -184,6 +184,17 @@
<string name="settings_level_description">Show horizontal level indicator while shooting</string>
<string name="settings_focus_peaking">Focus Peaking</string>
<string name="settings_focus_peaking_description">Show focus peaking highlights during manual focus</string>
<string name="settings_ai_focus_target">AI Smart Focus</string>
<string name="settings_ai_focus_target_description">Choose which subject type AI focus should track.</string>
<string name="settings_ai_focus_target_off">Off</string>
<string name="settings_ai_focus_target_auto">Auto</string>
<string name="settings_ai_focus_target_person">Person</string>
<string name="settings_ai_focus_target_animal">Animal</string>
<string name="settings_ai_focus_target_bird">Bird</string>
<string name="settings_ai_focus_target_vehicle">Vehicle</string>
<string name="settings_ai_focus_target_airplane">Airplane</string>
<string name="settings_ai_focus_sensitivity">AI Focus Sensitivity</string>
<string name="settings_ai_focus_sensitivity_description">Minimum detection score required to trigger AI focus.</string>
<string name="settings_grid_lines">Grid Lines</string>
<string name="settings_grid_description">Show grid lines for composition</string>
<string name="settings_use_multi_frame">Multi-Frame Denoise</string>