From b9cf5905659523a15e9b14fc7f502bbf655da069 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Tue, 13 Oct 2026 11:15:05 +0800 Subject: [PATCH] feat: independent point metering --- .../mycamera/camera/Camera2Controller.kt | 304 ++++++++++-------- .../com/hinnka/mycamera/camera/CameraState.kt | 9 + .../com/hinnka/mycamera/lut/LutRenderer.kt | 10 +- .../mycamera/ui/camera/CameraGLSurfaceView.kt | 4 +- .../mycamera/ui/camera/CameraPreviewGL.kt | 12 +- .../hinnka/mycamera/ui/camera/CameraScreen.kt | 21 +- .../mycamera/ui/components/FocusIndicator.kt | 146 +++++++++ .../mycamera/viewmodel/CameraViewModel.kt | 19 +- app/src/main/res/values-b+zh+Hant/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-in/strings.xml | 2 + app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values-ko/strings.xml | 2 + app/src/main/res/values-pt-rBR/strings.xml | 2 + app/src/main/res/values-th/strings.xml | 2 + app/src/main/res/values-zh-rCN/strings.xml | 2 + app/src/main/res/values-zh-rHK/strings.xml | 2 + app/src/main/res/values-zh-rTW/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + 20 files changed, 393 insertions(+), 156 deletions(-) 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 bbf6c7ef..e0d3ae83 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -304,6 +304,7 @@ class Camera2Controller(private val context: Context) { private var isFlashSupported = false private var maxAfRegions = 0 private var maxAeRegions = 0 + private var pointMeteringViewAspectRatio: Float? = null private var availableAfModes: IntArray = intArrayOf() private var availableEdgeModes: IntArray = intArrayOf() private var availableNoiseReductionModes: IntArray = intArrayOf() @@ -1191,8 +1192,9 @@ class Camera2Controller(private val context: Context) { } } - // 场景变化检测:对焦锁定后持续监测曝光变化和焦距跳变 - if (_state.value.isAutoFocus && isFocusLockedWaitingForSceneChange) { + // 独立测光会主动改变曝光,期间保留用户选定的 AF 点,直到重新点按或解锁。 + // 其余状态在对焦后持续监测曝光变化和焦距跳变。 + if (_state.value.isAutoFocus && isFocusLockedWaitingForSceneChange && _state.value.meteringPoint == null) { // 对焦锁定后前几帧镜头还在微调,跳过不检测 if (focusLockSettleFrames > 0) { focusLockSettleFrames-- @@ -2753,6 +2755,7 @@ class Camera2Controller(private val context: Context) { }, minimumFocusDistance = minimumFocusDistance, supportsPointAutoFocus = supportsPointAutoFocus, + supportsPointMetering = maxAeRegions > 0, ) } refreshHyperfocalFocusDistanceIfEnabled(updatePreview = false) @@ -2979,6 +2982,11 @@ class Camera2Controller(private val context: Context) { } fun calculateAutoMetering(totalWeight: Double, weightedSumLuminance: Double) { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { calculateAutoMetering(totalWeight, weightedSumLuminance) } + return + } val currentState = _state.value if (!currentState.isAutoExposure && (currentState.isIsoAuto || currentState.isShutterSpeedAuto)) { @@ -5872,7 +5880,12 @@ class Camera2Controller(private val context: Context) { * 设置测光模式 */ fun setMeteringMode(mode: MeteringMode) { - _state.value = _state.value.copy(meteringMode = mode) + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { setMeteringMode(mode) } + return + } + _state.value = _state.value.copy(meteringMode = mode, meteringPoint = null) if (mode == MeteringMode.HIGHLIGHT_PRIORITY) { highlightPointInitialized = false lastSentHighlightPointX = -1f @@ -5888,6 +5901,11 @@ class Camera2Controller(private val context: Context) { * 使用 EMA 平滑防止 AE 频繁跳动 */ fun updateHighlightPoint(x: Float, y: Float) { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { updateHighlightPoint(x, y) } + return + } highlightPointX = x highlightPointY = y if (!highlightPointInitialized) { @@ -5899,7 +5917,7 @@ class Camera2Controller(private val context: Context) { highlightPointSmoothedX = (alpha * x + (1 - alpha) * highlightPointSmoothedX).toFloat() highlightPointSmoothedY = (alpha * y + (1 - alpha) * highlightPointSmoothedY).toFloat() } - if (_state.value.meteringMode == MeteringMode.HIGHLIGHT_PRIORITY) { + if (_state.value.effectiveMeteringMode == MeteringMode.HIGHLIGHT_PRIORITY) { // 计算当前平滑点与上次发送点的位移距离 val dist = hypot( highlightPointSmoothedX.toDouble() - lastSentHighlightPointX, @@ -5927,81 +5945,113 @@ class Camera2Controller(private val context: Context) { */ private fun applyMeteringRegions() { val builder = previewRequestBuilder ?: return - val mode = _state.value.meteringMode - + val currentState = _state.value + val mode = currentState.effectiveMeteringMode if (mode == MeteringMode.SYSTEM_DEFAULT) { clearCustomAeRegions(builder) return } - if (maxAeRegions <= 0) return - val characteristics = getActiveOpenCameraCharacteristics() ?: return - val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) ?: return - - if (mode == MeteringMode.AVERAGE) { - val fullRegion = MeteringRectangle(activeRect, MeteringRectangle.METERING_WEIGHT_MAX) - builder.set(CaptureRequest.CONTROL_AE_REGIONS, arrayOf(fullRegion)) - return - } - try { - val sensorOrientation = getSensorOrientation() - val lensFacing = getLensFacing() - - // 选择测光坐标:高光优先使用最亮区域,其他模式使用对焦点或画面中心 - val normX: Float - val normY: Float - if (mode == MeteringMode.HIGHLIGHT_PRIORITY && highlightPointInitialized) { - normX = highlightPointSmoothedX - normY = highlightPointSmoothedY + val point = if (mode == MeteringMode.HIGHLIGHT_PRIORITY && highlightPointInitialized) { + highlightPointSmoothedX to highlightPointSmoothedY } else { - val focus = _state.value.focusPoint - normX = focus?.first ?: 0.5f - normY = focus?.second ?: 0.5f + currentState.meteringReferencePoint ?: (0.5f to 0.5f) } - - val (sensorX, sensorY) = when (sensorOrientation) { - 0 -> Pair(normX, normY) - 90 -> Pair(normY, 1 - normX) - 180 -> Pair(1 - normX, 1 - normY) - 270 -> Pair(1 - normY, normX) - else -> Pair(normX, normY) - } - val (finalX, finalY) = if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT) { - Pair(1 - sensorX, sensorY) + val mapping = mapPreviewMeteringPoint(point.first, point.second, pointMeteringViewAspectRatio) + ?: return + val rect = if (mode == MeteringMode.AVERAGE) { + mapping.visibleRegion } else { - Pair(sensorX, sensorY) + val fraction = when (mode) { + MeteringMode.SPOT -> SPOT_AE_REGION_FRACTION + MeteringMode.CENTER_WEIGHTED -> CENTER_WEIGHTED_AE_REGION_FRACTION + MeteringMode.HIGHLIGHT_PRIORITY -> HIGHLIGHT_AE_REGION_FRACTION + } + PreviewMeteringMapper.buildCenteredRegion(mapping, fraction) } - - val centerX = (finalX * activeRect.width()).toInt() - val centerY = (finalY * activeRect.height()).toInt() - val regionSizeFraction = when (mode) { - MeteringMode.SPOT -> 0.03f - MeteringMode.CENTER_WEIGHTED -> 0.2f - MeteringMode.HIGHLIGHT_PRIORITY -> 0.08f - MeteringMode.SYSTEM_DEFAULT, - MeteringMode.AVERAGE -> return - } - val regionSize = (activeRect.width() * regionSizeFraction).toInt() - - val rect = android.graphics.Rect( - (centerX - regionSize).coerceAtLeast(0), - (centerY - regionSize).coerceAtLeast(0), - (centerX + regionSize).coerceAtMost(activeRect.width()), - (centerY + regionSize).coerceAtMost(activeRect.height()) - ) builder.set( CaptureRequest.CONTROL_AE_REGIONS, - arrayOf(MeteringRectangle( - rect, - MeteringRectangle.METERING_WEIGHT_MAX - )) + arrayOf(MeteringRectangle(rect.toAndroidRect(), MeteringRectangle.METERING_WEIGHT_MAX)) ) } catch (e: Exception) { PLog.e(TAG, "Failed to apply metering regions", e) } } + // AF 和 AE 共享预览裁切、前摄镜像和变焦坐标映射。 + private fun mapPreviewMeteringPoint( + normX: Float, + normY: Float, + previewViewAspectRatio: Float?, + ): PreviewMeteringMapping? { + val builder = previewRequestBuilder ?: return null + val openCameraId = getActiveOpenCameraId().takeIf { it.isNotEmpty() } ?: return null + val characteristics = resolveZoomRequestCharacteristics(openCameraId) + val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) ?: return null + val zoomRatioRange = characteristics.readMetadataOrNull(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE) + val zoomMode = if (shouldUseControlZoomRatio(zoomRatioRange)) { + PreviewMeteringZoomMode.POST_ZOOM_ACTIVE_ARRAY + } else { + PreviewMeteringZoomMode.SCALER_CROP_REGION + } + val requestedScalerCrop = if (zoomMode == PreviewMeteringZoomMode.SCALER_CROP_REGION) { + builder.get(CaptureRequest.SCALER_CROP_REGION) + ?: buildCenteredCropRegion(activeRect, _state.value.zoomRatio) + } else { + null + } + return PreviewMeteringMapper.mapPoint( + normalizedX = normX, + normalizedY = normY, + activeArray = activeRect.toCameraCoordinateRect(), + scalerCropRegion = requestedScalerCrop?.toCameraCoordinateRect(), + zoomMode = zoomMode, + previewViewAspectRatio = previewViewAspectRatio?.takeIf { it.isFinite() && it > 0f } + ?: _state.value.getPreviewAspectRatio(), + sensorOrientationDegrees = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) + ?: getSensorOrientation(), + isFrontFacing = (characteristics.get(CameraCharacteristics.LENS_FACING) ?: getLensFacing()) == + CameraCharacteristics.LENS_FACING_FRONT, + ) + } + + /** 拖动测光圈仅更新 AE,保留原有 AF 区域与镜头位置。 */ + fun moveMeteringPoint(normX: Float, normY: Float, viewAspectRatio: Float) { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { moveMeteringPoint(normX, normY, viewAspectRatio) } + return + } + val currentState = _state.value + if (!normX.isFinite() || !normY.isFinite() || !viewAspectRatio.isFinite() || viewAspectRatio <= 0f) return + if (isCaptureFocusFrozen || currentState.isCapturing || !currentState.supportsPointMetering) return + if (previewRequestBuilder == null || currentState.focusPoint == null || + currentState.focusPointSource != FocusPointSource.MANUAL) return + val point = normX.coerceIn(0f, 1f) to normY.coerceIn(0f, 1f) + pointMeteringViewAspectRatio = viewAspectRatio + _state.value = currentState.copy(meteringPoint = point) + if (currentState.meteringPoint == null) { + PLog.d(TAG, "Separate metering point: focus=${currentState.focusPoint} metering=$point") + } + applyMeteringRegions() + updatePreview() + } + + fun mergeMeteringPoint() { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { mergeMeteringPoint() } + return + } + val currentState = _state.value + if (isCaptureFocusFrozen || currentState.isCapturing || currentState.meteringPoint == null) return + _state.value = currentState.copy(meteringPoint = null) + applyMeteringRegions() + updatePreview() + PLog.d(TAG, "Merge metering point into focus=${currentState.focusPoint}") + } + private fun clearCustomAeRegions(builder: CaptureRequest.Builder) { builder.set(CaptureRequest.CONTROL_AE_REGIONS, null) } @@ -6212,6 +6262,9 @@ class Camera2Controller(private val context: Context) { resetCropAtUnitZoom = true ) } + if (_state.value.meteringPoint != null) { + applyMeteringRegions() + } if (cameraDevice != null && captureSession != null) { updatePreview() } @@ -6518,6 +6571,7 @@ class Camera2Controller(private val context: Context) { } private fun clearPointFocusState() { + pointMeteringViewAspectRatio = null isFocusLockedWaitingForSceneChange = false sceneChangeFrameCount = 0 focusLockedReferenceIso = 0 @@ -6527,6 +6581,7 @@ class Camera2Controller(private val context: Context) { eyeTargetLastSeenElapsedMs = 0L _state.value = _state.value.copy( focusPoint = null, + meteringPoint = null, focusPointSource = FocusPointSource.MANUAL, isFocusLocked = false, isFocusing = false, @@ -6559,12 +6614,35 @@ class Camera2Controller(private val context: Context) { ) } + /** 拖动中更新 AF 区域,松手后扫描一次;整个过程保持独立 AE 区域。 */ + fun moveFocusPoint(normX: Float, normY: Float, viewAspectRatio: Float, finished: Boolean) { + val handler = cameraHandler + if (handler != null && Looper.myLooper() != handler.looper) { + handler.post { moveFocusPoint(normX, normY, viewAspectRatio, finished) } + return + } + val currentState = _state.value + if (currentState.meteringPoint == null || currentState.focusPointSource != FocusPointSource.MANUAL) return + if (!normX.isFinite() || !normY.isFinite() || !viewAspectRatio.isFinite() || viewAspectRatio <= 0f) return + focusOnNormalizedPoint( + normX = normX, + normY = normY, + source = FocusPointSource.MANUAL, + lockFocus = currentState.isFocusLocked, + previewViewAspectRatio = viewAspectRatio, + preserveMeteringPoint = true, + triggerFocus = finished, + ) + } + fun focusOnNormalizedPoint( normX: Float, normY: Float, source: FocusPointSource, lockFocus: Boolean = false, previewViewAspectRatio: Float? = null, + preserveMeteringPoint: Boolean = false, + triggerFocus: Boolean = true, ) { val handler = cameraHandler if (handler != null && Looper.myLooper() != handler.looper) { @@ -6575,6 +6653,8 @@ class Camera2Controller(private val context: Context) { source = source, lockFocus = lockFocus, previewViewAspectRatio = previewViewAspectRatio, + preserveMeteringPoint = preserveMeteringPoint, + triggerFocus = triggerFocus, ) } return @@ -6616,48 +6696,20 @@ class Camera2Controller(private val context: Context) { try { val builder = previewRequestBuilder ?: return - val currentState = _state.value - val characteristics = resolveZoomRequestCharacteristics(openCameraId) - val activeRect = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE) ?: return - val sensorOrientation = - characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: getSensorOrientation() - val lensFacing = - characteristics.get(CameraCharacteristics.LENS_FACING) ?: getLensFacing() - val zoomRatioRange = characteristics.readMetadataOrNull(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE) - val zoomMode = if (shouldUseControlZoomRatio(zoomRatioRange)) { - PreviewMeteringZoomMode.POST_ZOOM_ACTIVE_ARRAY - } else { - PreviewMeteringZoomMode.SCALER_CROP_REGION - } - val requestedScalerCrop = if (zoomMode == PreviewMeteringZoomMode.SCALER_CROP_REGION) { - builder.get(CaptureRequest.SCALER_CROP_REGION) - ?: buildCenteredCropRegion(activeRect, currentState.zoomRatio) - } else { - null - } - - // 计算归一化坐标(0-1) val normalizedX = normX.coerceIn(0f, 1f) val normalizedY = normY.coerceIn(0f, 1f) - val mapping = PreviewMeteringMapper.mapPoint( - normalizedX = normalizedX, - normalizedY = normalizedY, - activeArray = activeRect.toCameraCoordinateRect(), - scalerCropRegion = requestedScalerCrop?.toCameraCoordinateRect(), - zoomMode = zoomMode, - previewViewAspectRatio = previewViewAspectRatio - ?.takeIf { it.isFinite() && it > 0f } - ?: currentState.getPreviewAspectRatio(), - sensorOrientationDegrees = sensorOrientation, - isFrontFacing = lensFacing == CameraCharacteristics.LENS_FACING_FRONT, - ) ?: return + val mapping = mapPreviewMeteringPoint(normalizedX, normalizedY, previewViewAspectRatio) ?: return + if (source == FocusPointSource.MANUAL && !preserveMeteringPoint) { + pointMeteringViewAspectRatio = previewViewAspectRatio + } // 存储UI坐标用于显示对焦框 _state.value = _state.value.copy( focusPoint = Pair(normalizedX, normalizedY), + meteringPoint = if (preserveMeteringPoint) _state.value.meteringPoint else null, focusPointSource = source, isFocusLocked = lockFocus, - isFocusing = true, + isFocusing = triggerFocus, focusSuccess = null ) // AF 区域保持为可见画面的 10%,避免 SCALER_CROP_REGION 变焦后区域相对画面膨胀。 @@ -6668,61 +6720,31 @@ class Camera2Controller(private val context: Context) { ).toAndroidRect() val afRegion = MeteringRectangle(afRect, MeteringRectangle.METERING_WEIGHT_MAX) - // 2. AE 区域:根据测光模式决定;系统默认模式不随点按写入 AE 区域 - val meteringMode = _state.value.meteringMode - val aeRegion = when (meteringMode) { - MeteringMode.SYSTEM_DEFAULT -> null - MeteringMode.AVERAGE -> { - // 平均测光模式下,点击屏幕仅改变对焦点,测光区域强制保持全屏平均 - MeteringRectangle( - mapping.visibleRegion.toAndroidRect(), - MeteringRectangle.METERING_WEIGHT_MAX, - ) - } - MeteringMode.SPOT, - MeteringMode.CENTER_WEIGHTED, - MeteringMode.HIGHLIGHT_PRIORITY -> { - val aeRegionFraction = when (meteringMode) { - MeteringMode.SPOT -> SPOT_AE_REGION_FRACTION - MeteringMode.CENTER_WEIGHTED -> CENTER_WEIGHTED_AE_REGION_FRACTION - MeteringMode.HIGHLIGHT_PRIORITY -> HIGHLIGHT_AE_REGION_FRACTION - } - MeteringRectangle( - PreviewMeteringMapper.buildCenteredRegion( - mapping = mapping, - widthFraction = aeRegionFraction, - heightFraction = aeRegionFraction, - ).toAndroidRect(), - MeteringRectangle.METERING_WEIGHT_MAX, - ) - } + if (triggerFocus) { + PLog.d( + TAG, + "Focus mapping: ui=($normalizedX,$normalizedY) " + + "source=$source preserveMetering=$preserveMeteringPoint " + + "coordinateCamera=${activeOutputPhysicalCameraId ?: openCameraId} " + + "requestZoom=${builder.get(CaptureRequest.CONTROL_ZOOM_RATIO)} " + + "requestCrop=${builder.get(CaptureRequest.SCALER_CROP_REGION)} " + + "visible=${mapping.visibleRegion} center=(${mapping.centerX},${mapping.centerY}) " + + "af=$afRect metering=${_state.value.effectiveMeteringMode}" + ) } - PLog.d( - TAG, - "Focus mapping: ui=($normalizedX,$normalizedY) " + - "source=$source " + - "coordinateCamera=${activeOutputPhysicalCameraId ?: openCameraId} " + - "zoomMode=$zoomMode requestZoom=${builder.get(CaptureRequest.CONTROL_ZOOM_RATIO)} " + - "requestCrop=$requestedScalerCrop active=$activeRect " + - "visible=${mapping.visibleRegion} center=(${mapping.centerX},${mapping.centerY}) " + - "af=$afRect metering=$meteringMode" - ) - if (maxAfRegions > 0) { builder.set(CaptureRequest.CONTROL_AF_REGIONS, arrayOf(afRegion)) } // 人眼跟踪只接管 AF,不移动用户当前的测光区域。 - if (source == FocusPointSource.MANUAL) { - if (meteringMode == MeteringMode.SYSTEM_DEFAULT) { - clearCustomAeRegions(builder) - } else if (maxAeRegions > 0 && aeRegion != null) { - builder.set(CaptureRequest.CONTROL_AE_REGIONS, arrayOf(aeRegion)) - } + if (source == FocusPointSource.MANUAL && !preserveMeteringPoint) { + applyMeteringRegions() } val afMode = CaptureRequest.CONTROL_AF_MODE_AUTO _state.value = _state.value.copy(currentAfMode = afMode) - if (!submitOneShotAfTrigger(afMode, "point focus")) { + if (!triggerFocus) { + updatePreview() + } else if (!submitOneShotAfTrigger(afMode, "point focus")) { PLog.w(TAG, "Unable to submit point-focus AF trigger") _state.value = _state.value.copy(isFocusing = false, focusSuccess = false) } diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index dd023e6d..56de89f8 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -318,6 +318,9 @@ data class CameraState( val minimumFocusDistance: Float = 0f, // 最小对焦距离 val supportsPointAutoFocus: Boolean = false, val focusPoint: Pair? = null, // normalized coordinates (0-1) + // 非空表示用户拖出了独立测光点;为空时测光遵循所选模式和对焦点。 + val meteringPoint: Pair? = null, + val supportsPointMetering: Boolean = false, val focusPointSource: FocusPointSource = FocusPointSource.MANUAL, val isFocusLocked: Boolean = false, val isFocusing: Boolean = false, @@ -401,6 +404,12 @@ data class CameraState( val videoCapabilities: VideoCapabilities = VideoCapabilities(), val videoRecordingState: VideoRecordingState = VideoRecordingState(), ) { + val effectiveMeteringMode: MeteringMode + get() = if (meteringPoint != null) MeteringMode.SPOT else meteringMode + + val meteringReferencePoint: Pair? + get() = meteringPoint ?: focusPoint?.takeIf { focusPointSource == FocusPointSource.MANUAL } + companion object { const val MAX_PHOTO_PREVIEW_SHUTTER_SPEED_NS = 1_000_000_000L / 15 const val MAX_VIDEO_MANUAL_SHUTTER_SPEED_NS = 1_000_000_000L / 6 diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt index f6e44e29..7b6c85ec 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutRenderer.kt @@ -360,7 +360,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { var baselineColorRecipeEnabled: Boolean = false @Volatile - var focusPoint: PointF? = null + var meteringPoint: PointF? = null @Volatile var meteringMode: MeteringMode = MeteringMode.SYSTEM_DEFAULT @@ -2792,16 +2792,16 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { } else { null } - val currentFocus = focusPoint?.let { PointF(it.x, it.y) } + val currentMeteringPoint = meteringPoint?.let { PointF(it.x, it.y) } val currentMode = meteringMode val now = System.currentTimeMillis() if (now - lastRunMeteringTime < 100) { - dispatchMeteringCalculation(completedBytes, currentFocus, currentMode) + dispatchMeteringCalculation(completedBytes, currentMeteringPoint, currentMode) return } if (!isPixelPackBufferWritable(meteringPboFences, writeIndex)) { - dispatchMeteringCalculation(completedBytes, currentFocus, currentMode) + dispatchMeteringCalculation(completedBytes, currentMeteringPoint, currentMode) return } lastRunMeteringTime = now @@ -2844,7 +2844,7 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer { restorePixelReadbackState() } - dispatchMeteringCalculation(completedBytes, currentFocus, currentMode) + dispatchMeteringCalculation(completedBytes, currentMeteringPoint, currentMode) } private fun ensurePixelPackPbos(pboIds: IntArray, pixelSize: Int): Boolean { diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt index 7d16e2aa..03ef77c5 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraGLSurfaceView.kt @@ -203,8 +203,8 @@ class CameraGLSurfaceView @JvmOverloads constructor( } } - fun setFocusPoint(point: PointF?) { - renderer.focusPoint = point + fun setMeteringPoint(point: PointF?) { + renderer.meteringPoint = point } fun setMeteringMode(mode: MeteringMode) { 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 4d7aa324..22b26cb4 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 @@ -54,6 +54,11 @@ fun CameraPreviewGL( baselineColorRecipeParams: ColorRecipeParams, colorRecipeParams: ColorRecipeParams, focusPoint: Pair?, + meteringPoint: Pair? = null, + canMoveMeteringPoint: Boolean = false, + onMeteringPointMove: (Float, Float, Float) -> Unit = { _, _, _ -> }, + onFocusPointMove: (Float, Float, Float, Boolean) -> Unit = { _, _, _, _ -> }, + onMeteringPointMerge: () -> Unit = {}, focusPointSource: FocusPointSource = FocusPointSource.MANUAL, isFocusLocked: Boolean = false, isFocusing: Boolean, @@ -312,7 +317,7 @@ fun CameraPreviewGL( glSurfaceView.setBaselineParams(baselineColorRecipeParams) glSurfaceView.setParams(colorRecipeParams) - glSurfaceView.setFocusPoint(focusPoint?.takeIf { + glSurfaceView.setMeteringPoint((meteringPoint ?: focusPoint)?.takeIf { focusPointSource == FocusPointSource.MANUAL }?.let { android.graphics.PointF( @@ -334,6 +339,11 @@ fun CameraPreviewGL( // 对焦指示器 FocusIndicator( position = focusPoint, + meteringPosition = meteringPoint, + canMoveMeteringPoint = canMoveMeteringPoint, + onMeteringPointMove = onMeteringPointMove, + onFocusPointMove = onFocusPointMove, + onMeteringPointMerge = onMeteringPointMerge, source = focusPointSource, isFocusLocked = isFocusLocked, isFocusing = isFocusing, 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 311a20cf..3e08a304 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 @@ -1101,6 +1101,7 @@ fun CameraScreen( var totalDrag = 0f awaitEachGesture { var gestureStartedInPreviewControl: Boolean? = null + var childConsumedDrag = false while (true) { val event = awaitPointerEvent() if (gestureStartedInPreviewControl == null) { @@ -1127,6 +1128,8 @@ fun CameraScreen( } if (event.changes.size >= 2) { // Pinch to zoom + childConsumedDrag = true + totalDrag = 0f viewModel.isZooming = true val zoom = event.calculateZoom() if (zoom != 1f) { @@ -1141,13 +1144,17 @@ fun CameraScreen( } else if (event.changes.size == 1) { // Single finger -> horizontal drag for LUT switch val change = event.changes[0] - if (change.pressed) { + if (change.isConsumed && change.position != change.previousPosition) { + childConsumedDrag = true + totalDrag = 0f + } + if (change.pressed && !childConsumedDrag) { val dragAmount = change.position.x - change.previousPosition.x totalDrag += dragAmount - } else { + } else if (!change.pressed) { // onDragEnd logic - if (abs(totalDrag) > 100) { + if (!childConsumedDrag && abs(totalDrag) > 100) { val selectedLut = if (totalDrag > 0) { viewModel.switchToPreviousLut() } else { @@ -1200,11 +1207,17 @@ fun CameraScreen( baselineColorRecipeParams = currentBaselineRecipeParams, colorRecipeParams = previewRecipeParamsOverride ?: currentRecipeParams, focusPoint = state.focusPoint, + meteringPoint = state.meteringPoint, + canMoveMeteringPoint = state.supportsPointMetering && + !state.isCapturing && activePanel == ActivePanel.NONE, + onMeteringPointMove = viewModel::moveMeteringPoint, + onFocusPointMove = viewModel::moveFocusPoint, + onMeteringPointMerge = viewModel::mergeMeteringPoint, focusPointSource = state.focusPointSource, isFocusLocked = state.isFocusLocked, isFocusing = state.isFocusing, focusSuccess = state.focusSuccess, - meteringMode = state.meteringMode, + meteringMode = state.effectiveMeteringMode, onSurfaceTextureReady = { surfaceTexture -> previewSurfaceTexture = surfaceTexture }, 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 baa9db1d..cf08a0e5 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 @@ -5,6 +5,10 @@ import androidx.compose.animation.core.* import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.Canvas +import androidx.compose.foundation.gestures.awaitEachGesture +import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.awaitTouchSlopOrCancellation +import androidx.compose.foundation.gestures.drag import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Lock @@ -16,11 +20,21 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shadow +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.drawText +import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.hinnka.mycamera.R import com.hinnka.mycamera.camera.FocusPointSource import kotlinx.coroutines.delay +import kotlin.math.abs import kotlin.math.roundToInt /** @@ -29,6 +43,11 @@ import kotlin.math.roundToInt @Composable fun FocusIndicator( position: Pair?, + meteringPosition: Pair? = null, + canMoveMeteringPoint: Boolean = false, + onMeteringPointMove: (Float, Float, Float) -> Unit = { _, _, _ -> }, + onFocusPointMove: (Float, Float, Float, Boolean) -> Unit = { _, _, _, _ -> }, + onMeteringPointMerge: () -> Unit = {}, source: FocusPointSource = FocusPointSource.MANUAL, isFocusLocked: Boolean = false, isFocusing: Boolean, @@ -36,10 +55,26 @@ fun FocusIndicator( modifier: Modifier = Modifier ) { var visible by remember { mutableStateOf(position != null) } + val isSeparated = source == FocusPointSource.MANUAL && meteringPosition != null + val currentFocusPosition by rememberUpdatedState(position) + val currentIsSeparated by rememberUpdatedState(isSeparated) + val currentMeteringPosition by rememberUpdatedState(meteringPosition ?: position) + val currentOnMeteringPointMove by rememberUpdatedState(onMeteringPointMove) + val currentOnFocusPointMove by rememberUpdatedState(onFocusPointMove) + val currentOnMeteringPointMerge by rememberUpdatedState(onMeteringPointMerge) + val textMeasurer = rememberTextMeasurer() + val labelStyle = TextStyle( + color = Color.White, + fontSize = 12.sp, + shadow = Shadow(Color.Black, Offset(0f, 1f), 3f), + ) + val focusLabel = textMeasurer.measure(stringResource(R.string.camera_focus_point_label), labelStyle) + val meteringLabel = textMeasurer.measure(stringResource(R.string.camera_metering_point_label), labelStyle) // 透明度动画 val alpha by animateFloatAsState( targetValue = when { + isSeparated -> 1f isFocusing -> 1f source == FocusPointSource.EYE && position != null -> 0.9f isFocusLocked && focusSuccess != false -> 0.9f @@ -82,6 +117,86 @@ fun FocusIndicator( BoxWithConstraints(modifier = Modifier.fillMaxSize()) { Canvas( modifier = Modifier.fillMaxSize() + .pointerInput(canMoveMeteringPoint, source, position != null) { + if (!canMoveMeteringPoint || source != FocusPointSource.MANUAL || position == null) { + return@pointerInput + } + val hitRadius = 24.dp.toPx() + val circleRadius = 11.dp.toPx() + val focusHalfSize = 30.dp.toPx() + val focusHitHalfSize = 38.dp.toPx() + val mergeRadius = 16.dp.toPx() + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + val point = currentMeteringPosition ?: return@awaitEachGesture + val focus = currentFocusPosition ?: return@awaitEachGesture + val meteringCenter = Offset(point.first * size.width, point.second * size.height) + val focusCenter = Offset(focus.first * size.width, focus.second * size.height) + val meteringDistance = (down.position - meteringCenter).getDistance() + val focusDelta = down.position - focusCenter + val hitsMetering = meteringDistance <= hitRadius + val hitsFocus = currentIsSeparated && + abs(focusDelta.x) <= focusHitHalfSize && abs(focusDelta.y) <= focusHitHalfSize + if (!hitsMetering && !hitsFocus) return@awaitEachGesture + // 命中范围重叠时优先圈本身,其余选择较近的标记;一次手势只拖动一个目标。 + val draggingFocus = hitsFocus && (!hitsMetering || + (meteringDistance > circleRadius && focusDelta.getDistance() < meteringDistance)) + val center = if (draggingFocus) focusCenter else meteringCenter + // 只在越过拖动阈值后消费事件,保留原有点按与长按锁焦。 + val start = awaitTouchSlopOrCancellation(down.id) { change, _ -> + if (currentEvent.changes.count { it.pressed } == 1) change.consume() + } + ?: return@awaitEachGesture + val grabOffset = center - down.position + var separatedDuringDrag = currentIsSeparated + var mergedDuringDrag = false + var lastFocusTarget: Offset? = null + var lastFocusAspectRatio = 1f + fun move(pointer: Offset) { + if (mergedDuringDrag) return + val width = size.width.toFloat() + val height = size.height.toFloat() + if (width <= 0f || height <= 0f) return + val radius = if (draggingFocus) focusHalfSize else circleRadius + val insetX = radius.coerceAtMost(width / 2f) + val insetY = radius.coerceAtMost(height / 2f) + val target = pointer + grabOffset + val normalized = Offset( + target.x.coerceIn(insetX, width - insetX) / width, + target.y.coerceIn(insetY, height - insetY) / height, + ) + if (draggingFocus) { + lastFocusTarget = normalized + lastFocusAspectRatio = width / height + currentOnFocusPointMove(normalized.x, normalized.y, width / height, false) + } else { + val distanceToFocus = (target - focusCenter).getDistance() + if (separatedDuringDrag && distanceToFocus <= mergeRadius) { + mergedDuringDrag = true + currentOnMeteringPointMerge() + } else if (separatedDuringDrag || distanceToFocus > hitRadius) { + // 拉出距离大于吸附距离,防止中心附近反复分离、合并。 + separatedDuringDrag = true + currentOnMeteringPointMove(normalized.x, normalized.y, width / height) + } + } + } + try { + move(start.position) + drag(start.id) { change -> + if (currentEvent.changes.count { it.pressed } == 1) { + change.consume() + move(change.position) + } + } + } finally { + // 包括多指接管或手势取消,均以最后接受的位置结束,避免留下未完成的 AF 状态。 + lastFocusTarget?.let { target -> + currentOnFocusPointMove(target.x, target.y, lastFocusAspectRatio, true) + } + } + } + } ) { val x = displayPosition.first * size.width val y = displayPosition.second * size.height @@ -147,6 +262,37 @@ fun FocusIndicator( end = Offset(x + halfSize, y + halfSize - cornerLength), strokeWidth = strokeWidth ) + + if (source == FocusPointSource.MANUAL && (canMoveMeteringPoint || isSeparated)) { + val point = meteringPosition ?: displayPosition + val center = Offset(point.first * size.width, point.second * size.height) + val radius = 11.dp.toPx() + drawCircle( + color = Color.White.copy(alpha = alpha), + radius = radius, + center = center, + style = Stroke(width = 1.5.dp.toPx()), + ) + if (isSeparated) { + fun labelTopLeft(center: Offset, radius: Float, width: Int, height: Int): Offset { + val below = center.y + radius + 5.dp.toPx() + val top = if (below + height <= size.height) below + else center.y - radius - 5.dp.toPx() - height + return Offset( + (center.x - width / 2f).coerceIn(0f, (size.width - width).coerceAtLeast(0f)), + top.coerceIn(0f, (size.height - height).coerceAtLeast(0f)), + ) + } + drawText( + focusLabel, + topLeft = labelTopLeft(Offset(x, y), halfSize, focusLabel.size.width, focusLabel.size.height), + ) + drawText( + meteringLabel, + topLeft = labelTopLeft(center, radius, meteringLabel.size.width, meteringLabel.size.height), + ) + } + } } if (source == FocusPointSource.MANUAL && isFocusLocked && position != null) { 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 e17a671a..4acd618c 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -2562,9 +2562,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } glSurfaceView?.let { view -> view.setVideoLogProfile(currentState.videoConfig.logProfile) - currentState.focusPoint?.let { fp -> - view.setFocusPoint(android.graphics.PointF(fp.first, fp.second)) - } + view.setMeteringPoint(currentState.meteringReferencePoint?.let { point -> + android.graphics.PointF(point.first, point.second) + }) + view.setMeteringMode(currentState.effectiveMeteringMode) view.setAutoFocus(currentState.isAutoFocus) } } @@ -4141,6 +4142,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraController.focusOnPoint(x, y, viewWidth, viewHeight) } + fun moveMeteringPoint(x: Float, y: Float, viewAspectRatio: Float) { + cameraController.moveMeteringPoint(x, y, viewAspectRatio) + } + + fun moveFocusPoint(x: Float, y: Float, viewAspectRatio: Float, finished: Boolean) { + cameraController.moveFocusPoint(x, y, viewAspectRatio, finished) + } + + fun mergeMeteringPoint() { + cameraController.mergeMeteringPoint() + } + fun lockFocusOnPoint(x: Float, y: Float, viewWidth: Int, viewHeight: Int) { cameraController.lockFocusOnPoint(x, y, viewWidth, viewHeight) } diff --git a/app/src/main/res/values-b+zh+Hant/strings.xml b/app/src/main/res/values-b+zh+Hant/strings.xml index d2d1f90a..0a6fbbe5 100644 --- a/app/src/main/res/values-b+zh+Hant/strings.xml +++ b/app/src/main/res/values-b+zh+Hant/strings.xml @@ -1305,4 +1305,6 @@ 選擇使用拍攝裝置或 M9 的色彩矩陣校準 RAW 色彩。 預設 M9 + 對焦框 + 測光點 diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a32306e8..b78f2726 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -355,4 +355,6 @@ Wählen Sie zur RAW-Farbkalibrierung die Farbmatrix des Aufnahmegeräts oder der M9. Standard M9 + Fokus + Messpunkt diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index d0c9cac1..6707ae0b 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -355,4 +355,6 @@ Choisissez la matrice de couleur de votre appareil ou du M9 pour calibrer les couleurs RAW. Par défaut M9 + Mise au point + Mesure diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 6496b174..9a1ddda4 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -355,4 +355,6 @@ Pilih matriks warna perangkat pengambilan gambar atau M9 untuk kalibrasi warna RAW. Default M9 + Fokus + Pengukuran diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 623a8e2c..db4facb9 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1180,4 +1180,6 @@ RAW の色補正に撮影機器または M9 のカラーマトリクスを使用します。 デフォルト M9 + フォーカス + 測光点 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 11ecb4d5..0f40ba9e 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -356,4 +356,6 @@ RAW 색상 보정에 촬영 기기 또는 M9의 색상 행렬을 사용합니다. 기본값 M9 + 초점 + 측광점 diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 6f752a16..01f98665 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -356,4 +356,6 @@ Escolha a matriz de cores do dispositivo de captura ou da M9 para calibrar as cores RAW. Padrão M9 + Foco + Medição diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 1175713f..3a2c6d5b 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -978,4 +978,6 @@ เลือกเมทริกซ์สีของอุปกรณ์ที่ใช้ถ่ายภาพหรือ M9 เพื่อปรับเทียบสี RAW ค่าเริ่มต้น M9 + จุดโฟกัส + จุดวัดแสง diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index b9479dcf..b4cdfbf7 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1361,4 +1361,6 @@ 选择使用拍摄设备或 M9 的色彩矩阵校准 RAW 色彩。 默认 M9 + 对焦框 + 测光点 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 1569dd8f..41c99067 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1301,4 +1301,6 @@ 選擇使用拍攝裝置或 M9 的色彩矩陣校準 RAW 色彩。 預設 M9 + 對焦框 + 測光點 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index debcc98f..2f0fd7c2 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1305,4 +1305,6 @@ 選擇使用拍攝裝置或 M9 的色彩矩陣校準 RAW 色彩。 預設 M9 + 對焦框 + 測光點 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e46e4822..fb579ccc 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1385,4 +1385,6 @@ Choose the capture device or M9 color matrix for RAW color calibration. Default M9 + Focus + Metering