feat: lens switch preview transition

This commit is contained in:
zhoubinjia committed 2026-09-28 13:48:55 +08:00
1 parent 34fc64a454
commit 436bf1a883
8 files changed
+85 -78

No files matched your search

@@ -1090,6 +1090,12 @@ class Camera2Controller(private val context: Context) {
) {
super.onCaptureCompleted(session, request, result)
if (session === captureSession && _state.value.previewFirstFrameTimestampNs == null) {
result.get(CaptureResult.SENSOR_TIMESTAMP)?.let { timestamp ->
_state.update { it.copy(previewFirstFrameTimestampNs = timestamp) }
}
}
realtimeStabilizationCoordinator.submitCaptureResult(
result = result,
request = request,
@@ -2068,7 +2074,14 @@ class Camera2Controller(private val context: Context) {
pendingFrameMetadata.clear()
pendingCaptureStartedTimestamps.clear()
photoCaptureByTimestamp.clear()
_state.update { it.copy(isCapturing = false, hdrBracketCapturing = false, hdrBracketFrameCount = 0) }
_state.update {
it.copy(
isCapturing = false,
hdrBracketCapturing = false,
hdrBracketFrameCount = 0,
previewFirstFrameTimestampNs = null,
)
}
previewSessionGeneration++
previewUpdateScheduled.set(false)
livePhotoVideoStartTimestampUs = null
@@ -3691,6 +3704,7 @@ class Camera2Controller(private val context: Context) {
return
}
captureSession = session
_state.update { it.copy(previewFirstFrameTimestampNs = null) }
try {
// 根据测光模式设置默认 AE 区域
@@ -338,6 +338,8 @@ data class CameraState(
// 是否处于预览状态
val isPreviewActive: Boolean = false,
// 当前预览会话首个 CaptureResult 的传感器时间戳,用于等待对应画面真正渲染。
val previewFirstFrameTimestampNs: Long? = null,
// 是否正在拍照
val isCapturing: Boolean = false,
@@ -7,8 +7,7 @@ import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import androidx.core.graphics.createBitmap
import kotlin.math.ceil
import kotlin.math.exp
import com.hinnka.mycamera.utils.GaussianBlur
import kotlin.math.roundToInt
/** Photo materials shared by preview and export, including Android 11 bitmap canvases. */
@@ -51,74 +50,11 @@ internal object FrameBackgroundRenderer {
)
if (sigma > 0f) {
blur(background, sigma * workingWidth / width, sigma * workingHeight / height)
GaussianBlur.blur(background, sigma * workingWidth / width, sigma * workingHeight / height)
}
canvas.drawBitmap(background, null, RectF(0f, 0f, width.toFloat(), height.toFloat()), paint)
} finally {
background.recycle()
}
}
private fun kernel(sigma: Float): FloatArray {
require(sigma > 0f && sigma.isFinite())
val radius = ceil(3f * sigma).toInt()
val weights = FloatArray(radius * 2 + 1) { index ->
val distance = (index - radius).toFloat()
exp(-distance * distance / (2f * sigma * sigma))
}
val total = weights.sum()
weights.indices.forEach { weights[it] /= total }
return weights
}
private fun blur(bitmap: Bitmap, sigmaX: Float, sigmaY: Float) {
val width = bitmap.width
val height = bitmap.height
val pixels = IntArray(width * height)
bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
// Retain fractional channel values between the two separable passes.
val horizontal = FloatArray(pixels.size * 3)
val weightsX = kernel(sigmaX)
val radiusX = weightsX.size / 2
for (y in 0 until height) {
for (x in 0 until width) {
var red = 0f
var green = 0f
var blue = 0f
for (tap in weightsX.indices) {
val color = pixels[y * width + (x + tap - radiusX).coerceIn(0, width - 1)]
val weight = weightsX[tap]
red += ((color ushr 16) and 255) * weight
green += ((color ushr 8) and 255) * weight
blue += (color and 255) * weight
}
val offset = (y * width + x) * 3
horizontal[offset] = red
horizontal[offset + 1] = green
horizontal[offset + 2] = blue
}
}
val weightsY = kernel(sigmaY)
val radiusY = weightsY.size / 2
for (y in 0 until height) {
for (x in 0 until width) {
var red = 0f
var green = 0f
var blue = 0f
for (tap in weightsY.indices) {
val offset = ((y + tap - radiusY).coerceIn(0, height - 1) * width + x) * 3
val weight = weightsY[tap]
red += horizontal[offset] * weight
green += horizontal[offset + 1] * weight
blue += horizontal[offset + 2] * weight
}
pixels[y * width + x] = Color.rgb(
red.roundToInt().coerceIn(0, 255),
green.roundToInt().coerceIn(0, 255),
blue.roundToInt().coerceIn(0, 255)
)
}
}
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
}
}
@@ -492,6 +492,8 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
var onMeteringUpdated: ((Double, Double) -> Unit)? = null
var onHighlightPointUpdated: ((Float, Float) -> Unit)? = null
var onFirstFrameRendered: (() -> Unit)? = null
// 仅在有等待者时安装;时间戳属于已经完成所有预览 pass 的画面。
var onPreviewFrameRendered: ((Long) -> Unit)? = null
// Live Photo 录制器
var livePhotoRecorder: LivePhotoRecorder? = null
@@ -1271,6 +1273,9 @@ class LutRenderer(context: Context) : GLSurfaceView.Renderer {
firstFrameRendered = true
onFirstFrameRendered?.invoke()
}
if (currentFrameTimestampNs > 0L) {
onPreviewFrameRendered?.invoke(currentFrameTimestampNs)
}
}
private fun useCurrentOesFrame() {
@@ -24,6 +24,8 @@ import com.hinnka.mycamera.stabilization.normalizeStabilizationLookahead
import com.hinnka.mycamera.stabilization.normalizeStabilizationStrength
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.video.VideoLogProfile
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
/**
* 相机预览 GLSurfaceView
@@ -360,6 +362,37 @@ class CameraGLSurfaceView @JvmOverloads constructor(
}
}
/** 等待新会话的画面完成渲染,不能用 session configured 代替画面就绪。 */
suspend fun awaitPreviewFrame(minimumTimestampNs: Long) {
var listener: ((Long) -> Unit)? = null
try {
suspendCancellableCoroutine<Unit> { continuation ->
val callback: (Long) -> Unit = { timestamp ->
if (timestamp >= minimumTimestampNs) {
renderer.onPreviewFrameRendered = null
post {
if (continuation.isActive) continuation.resume(Unit)
}
}
}
listener = callback
queueEvent {
if (continuation.isActive) {
renderer.onPreviewFrameRendered = callback
requestRender()
}
}
}
} finally {
val installedListener = listener
queueEvent {
if (renderer.onPreviewFrameRendered === installedListener) {
renderer.onPreviewFrameRendered = null
}
}
}
}
fun captureOriginalPreviewFrame(callback: (Bitmap?) -> Unit) {
capturePreviewFrameInternal(
maxLongEdge = null,
@@ -288,6 +288,14 @@ fun CameraScreen(
var hasPlayedInitialPreviewTransition by remember { mutableStateOf(false) }
var rawCaptureTapLocked by remember { mutableStateOf(false) }
var zoomStopAnimationJob by remember { mutableStateOf<Job?>(null) }
val lensSwitchTransition = remember(viewModel, scope) { LensSwitchTransitionState(scope, viewModel) }
DisposableEffect(lensSwitchTransition) {
onDispose { lensSwitchTransition.cancel() }
}
LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) {
lensSwitchTransition.cancel()
}
fun discardTransientLookEdits() {
previewRecipeParamsOverride = null
@@ -527,6 +535,7 @@ fun CameraScreen(
fun runPreviewTransition(onSwitch: () -> Unit) {
cancelZoomStopAnimation()
lensSwitchTransition.cancel()
previewTransitionActive = true
previewTransitionRevealing = false
previewTransitionToken += 1
@@ -539,19 +548,22 @@ fun CameraScreen(
}
fun switchToLensWithPreviewTransition(cameraId: String) {
lensSwitchTransition.cancelPendingSwitch()
if (cameraId == state.getCurrentCameraInfo()?.cameraId) return
val targetCamera = state.availableCameras.firstOrNull { it.cameraId == cameraId } ?: return
val targetZoom = targetCamera.displayIntrinsicZoomRatio.takeIf { it > 0f }
?: targetCamera.intrinsicZoomRatio.takeIf { it > 0f }
?: 1f
if (viewModel.isVideoLensLocked()) {
val targetCamera = state.availableCameras.firstOrNull { it.cameraId == cameraId }
val targetZoom = targetCamera?.displayIntrinsicZoomRatio
?.takeIf { it > 0f }
?: targetCamera?.intrinsicZoomRatio?.takeIf { it > 0f }
targetZoom?.let(::animateCurrentLensToZoomStop)
animateCurrentLensToZoomStop(targetZoom)
return
}
runPreviewTransition { viewModel.switchToLens(cameraId) }
cancelZoomStopAnimation()
lensSwitchTransition.switchLens(cameraId, targetZoom) { viewModel.switchToLens(cameraId) }
}
fun setZoomWithPreviewTransition(targetZoom: Float) {
lensSwitchTransition.cancelPendingSwitch()
cancelZoomStopAnimation()
if (viewModel.isVideoLensLocked()) {
viewModel.setZoomRatio(targetZoom)
@@ -569,7 +581,7 @@ fun CameraScreen(
currentCameraId
)
if (camera != null && camera.cameraId != currentCamera?.cameraId) {
runPreviewTransition {
lensSwitchTransition.switchLens(camera.cameraId, targetZoom) {
viewModel.switchToLensAndSetZoomRatio(camera.cameraId, targetZoom)
}
} else {
@@ -578,6 +590,8 @@ fun CameraScreen(
}
fun animateZoomStopWithPreviewTransition(targetZoom: Float) {
lensSwitchTransition.cancelPendingSwitch()
cancelZoomStopAnimation()
if (viewModel.isVideoLensLocked() ||
viewModel.isCurrentLensCustomZoomRatioStop(targetZoom)
) {
@@ -592,7 +606,7 @@ fun CameraScreen(
currentCameraId
)
if (camera != null && camera.cameraId != currentCamera?.cameraId) {
runPreviewTransition {
lensSwitchTransition.switchLens(camera.cameraId, targetZoom) {
viewModel.switchToLensAndSetZoomRatio(camera.cameraId, targetZoom)
}
} else {
@@ -1293,6 +1307,8 @@ fun CameraScreen(
)
}
LensSwitchTransitionOverlay(lensSwitchTransition, Modifier.fillMaxSize())
val showLivePhotoIndicator =
state.captureMode == CaptureMode.PHOTO && useLivePhoto
val showVirtualApertureIndicator =
@@ -1514,7 +1530,7 @@ fun CameraScreen(
},
onSwitchCameraClick = ::switchCameraWithPreviewTransition,
onCaptureModeSelected = ::setShootingModeWithPreviewTransition,
modeSwitchEnabled = !previewTransitionActive,
modeSwitchEnabled = !previewTransitionActive && !lensSwitchTransition.isActive,
onCaptureTap = {
val shouldDebounceRawCapture =
state.useRaw && state.captureMode == CaptureMode.PHOTO
@@ -1879,7 +1879,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
private var isShutterSoundEnabled = true
private var isVibrationEnabled = true
var glSurfaceView: CameraGLSurfaceView? = null
var glSurfaceView by mutableStateOf<CameraGLSurfaceView?>(null)
var isEyeFocusBusy by mutableStateOf(false)
private set
var isEyeFocusRuntimeAvailable by mutableStateOf(true)