fix: camera state

This commit is contained in:
Hinnka committed 2026-07-23 00:19:28 +08:00
1 parent a23454ebb5
commit a0e071537f
6 files changed
+123 -14

No files matched your search

@@ -1224,7 +1224,17 @@ class Camera2Controller(private val context: Context) {
// 确保在权限已授予后才发现相机(延迟初始化)
if (_state.value.availableCameras.isEmpty()) {
PLog.i(TAG, "首次打开相机,开始发现可用摄像头")
discoverCameras()
try {
discoverCameras()
} catch (error: Exception) {
handleCameraOpenFailure(
cameraId = "",
errorCode = ERROR_CAMERA_CHARACTERISTICS_UNAVAILABLE,
message = "摄像头列表加载失败",
error = error
)
return
}
}
val cameraId = _state.value.currentCameraId
@@ -1233,7 +1243,12 @@ class Camera2Controller(private val context: Context) {
val targetZoomRatioByMain = getTargetZoomRatioByMain(_state.value, selectedCamera)
val captureMode = _state.value.captureMode
if (cameraId.isEmpty()) {
PLog.e(TAG, "No camera ID set")
handleCameraOpenFailure(
cameraId = cameraId,
errorCode = ERROR_CAMERA_CHARACTERISTICS_UNAVAILABLE,
message = "未发现可用摄像头",
error = IllegalStateException("Camera discovery returned no available camera")
)
return
}
@@ -1577,6 +1592,9 @@ class Camera2Controller(private val context: Context) {
}
PLog.d(TAG, "Camera opened: ${camera.id}")
cameraDevice = camera
if (restartCameraForRawCaptureOutputMismatch("camera opened")) {
return
}
createPreviewSession(openGeneration = openGeneration)
}
@@ -2284,6 +2302,42 @@ class Camera2Controller(private val context: Context) {
return reader?.imageFormat == ImageFormat.RAW_SENSOR
}
/**
* RAW is an ImageReader/session-level choice. If the desired state changes after an
* ImageReader has already been created, changing [CameraState.useRaw] alone leaves the
* active capture output in the old format.
*
* This check also runs from CameraDevice.onOpened so a preference restored while the
* initial camera open is in flight is applied before the first preview session starts.
*/
private fun restartCameraForRawCaptureOutputMismatch(reason: String): Boolean {
val currentState = _state.value
if (currentState.captureMode != CaptureMode.PHOTO) return false
val currentReader = imageReader ?: return false
val expectsRawOutput = currentState.useRaw && isRawSupported
val hasRawOutput = isRawCaptureReader(currentReader)
if (expectsRawOutput == hasRawOutput) return false
val surfaceTexture = previewSurfaceTexture ?: return false
if (cameraDevice == null) {
PLog.d(
TAG,
"RAW capture output update is waiting for camera open: " +
"reason=$reason, expectedRaw=$expectsRawOutput, actualRaw=$hasRawOutput"
)
return false
}
PLog.i(
TAG,
"Restarting camera for RAW capture output update: " +
"reason=$reason, expectedRaw=$expectsRawOutput, actualRaw=$hasRawOutput"
)
openCamera(surfaceTexture)
return true
}
// ==================== 统一参数配置 ====================
/**
@@ -3533,9 +3587,23 @@ class Camera2Controller(private val context: Context) {
/**
* 设置是否使用 RAW 格式拍照
*/
fun setUseRaw(enabled: Boolean) {
fun setUseRaw(
enabled: Boolean,
reconfigureCaptureOutputIfNeeded: Boolean = true
) {
_state.value = _state.value.copy(useRaw = enabled)
PLog.d(TAG, "RAW 格式拍照: $enabled")
if (!reconfigureCaptureOutputIfNeeded) return
val handler = cameraHandler
if (handler != null && Looper.myLooper() != handler.looper) {
handler.post {
restartCameraForRawCaptureOutputMismatch("RAW setting changed")
}
return
}
restartCameraForRawCaptureOutputMismatch("RAW setting changed")
}
fun setRawMinShutterSpeedNs(value: Long) {
@@ -1683,7 +1683,7 @@ class LutRenderer : GLSurfaceView.Renderer {
)
// 测光和直方图(按需)
if (meteringEnabled && videoRecorder?.isRecording() != true) {
if (fboId == 0 && meteringEnabled && videoRecorder?.isRecording() != true) {
runMeteringInternal()
}
@@ -2939,6 +2939,10 @@ class LutRenderer : GLSurfaceView.Renderer {
}
// 2. 读取像素
// drawInternal 中的附加 pass 可能改变 framebuffer;读回必须以本次请求的
// capture FBO 为唯一来源,不能依赖调用链遗留的 GL 绑定状态。
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, captureFboId)
GLES30.glViewport(0, 0, targetWidth, targetHeight)
val pixelSize = targetWidth * targetHeight * 4
if (pboId == 0) {
val pbos = IntArray(1)
@@ -5,6 +5,7 @@ import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.SurfaceTexture
import android.os.Environment
import android.provider.Settings
import android.view.WindowManager
@@ -203,6 +204,7 @@ fun CameraScreen(
val context = LocalContext.current
val scope = rememberCoroutineScope()
val state by viewModel.state.collectAsState()
val isCameraInitialized by viewModel.isInitialized.collectAsState()
val latestPhoto by galleryViewModel.latestPhoto.collectAsState()
val showLevelIndicator by viewModel.showLevelIndicator.collectAsState(initial = false)
val focusPeakingEnabled by viewModel.focusPeakingEnabled.collectAsState(initial = true)
@@ -316,8 +318,19 @@ fun CameraScreen(
}
}
// 标记相机是否已打开
var cameraOpened by remember { mutableStateOf(false) }
// Surface may become ready while persisted camera settings are still being restored.
// Retain the exact instance and open only after initialization has completed.
var previewSurfaceTexture by remember { mutableStateOf<SurfaceTexture?>(null) }
LaunchedEffect(
isCameraInitialized,
previewSurfaceTexture,
state.availableCameras.isNotEmpty()
) {
val surfaceTexture = previewSurfaceTexture ?: return@LaunchedEffect
if (!isCameraInitialized) return@LaunchedEffect
viewModel.openCamera(surfaceTexture)
}
// UI State
var activePanel by remember { mutableStateOf(ActivePanel.NONE) }
@@ -1011,12 +1024,13 @@ fun CameraScreen(
focusSuccess = state.focusSuccess,
meteringMode = state.meteringMode,
onSurfaceTextureReady = { surfaceTexture ->
viewModel.openCamera(surfaceTexture)
cameraOpened = true
previewSurfaceTexture = surfaceTexture
},
onSurfaceDestroyed = { surfaceTexture ->
if (previewSurfaceTexture === surfaceTexture) {
previewSurfaceTexture = null
}
viewModel.closeCamera(surfaceTexture)
cameraOpened = false
},
onTap = { x, y, w, h ->
if (state.isFocusLocked) {
@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
@@ -77,6 +78,7 @@ fun ZoomControlBar(
val currentCameraIdState by rememberUpdatedState(currentCameraId)
val currentCamera = availableCameras.find { it.cameraId == currentCameraId }
val isCameraReady = currentCamera != null
// 获取当前相机信息
val mainCamera =
@@ -167,7 +169,8 @@ fun ZoomControlBar(
.fillMaxWidth()
.padding(8.dp)
.height(32.dp)
.pointerInput(minZoom, maxZoom, zoomStops) {
.pointerInput(isCameraReady, minZoom, maxZoom, zoomStops) {
if (!isCameraReady) return@pointerInput
var dragAccumulated = 0f
detectHorizontalDragGestures(
onDragStart = {
@@ -271,7 +274,13 @@ fun ZoomControlBar(
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
if (isContinuousZooming) {
if (!isCameraReady) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = Color(0xFFFFD700),
strokeWidth = 2.dp
)
} else if (isContinuousZooming) {
ZoomContinuousRuler(
zoomRatio = internalZoomRatio,
minZoom = minZoom,
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
@@ -58,6 +59,7 @@ fun ZoomControlBarVerticel(
val currentCameraIdState by rememberUpdatedState(currentCameraId)
val currentCamera = availableCameras.find { it.cameraId == currentCameraId }
val isCameraReady = currentCamera != null
// 获取当前相机信息
val mainCamera =
@@ -146,7 +148,8 @@ fun ZoomControlBarVerticel(
modifier = modifier
.padding(8.dp)
.width(32.dp)
.pointerInput(minZoom, maxZoom, zoomStops) {
.pointerInput(isCameraReady, minZoom, maxZoom, zoomStops) {
if (!isCameraReady) return@pointerInput
var dragAccumulated = 0f
detectVerticalDragGestures(
onDragStart = {
@@ -249,7 +252,13 @@ fun ZoomControlBarVerticel(
.padding(vertical = if (isContinuousZooming) 0.dp else 40.dp),
contentAlignment = Alignment.Center
) {
if (isContinuousZooming) {
if (!isCameraReady) {
CircularProgressIndicator(
modifier = Modifier.size(20.dp),
color = Color(0xFFFFD700),
strokeWidth = 2.dp
)
} else if (isContinuousZooming) {
ZoomContinuousRulerVertical(
zoomRatio = internalZoomRatio,
minZoom = minZoom,
@@ -648,7 +648,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
}
if (update.useRaw != null || desiredUseRaw != prefs.useRaw) {
cameraController.setUseRaw(desiredUseRaw)
cameraController.setUseRaw(
enabled = desiredUseRaw,
// This transaction already performs the required reopen below. Avoid a
// duplicate restart, but still let same-value calls repair a stale output.
reconfigureCaptureOutputIfNeeded = !needsCameraReopen
)
}
if (update.useJpgMax != null || update.useRawMax != null ||
desiredMultiFrameOutputScale != currentState.multiFrameOutputScale