camera: fix capture lifecycle, sessions, save paths and UI honesty
- Commit
05e6db310b95947c3d5d41a679892ac80ba0ce7b- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-23 04:31 UTC (2 months ago)
- Parents
2573071
Diff
camera/src/main/java/com/vayunmathur/camera/MainActivity.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt b/camera/src/main/java/com/vayunmathur/camera/MainActivity.ktindex 2f97c9a741..c6c8827ae0 100644--- a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt+++ b/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt@@ -108,9 +108,12 @@ class MainActivity : ComponentActivity() { // button (the CameraScreen collects shutterEvents and picks the right action for the mode). // Desktop keyboards cannot send volume keys, so Esc/space-preview also triggers the shutter // without disturbing phones (phones rarely carry a hardware keyboard; onKeyDown still wins).+ // Gated on the camera route being foreground so keys pressed in Settings don't take a+ // photo behind your back (and volume keeps adjusting volume there). override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {- return if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||- keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ESCAPE+ return if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||+ keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ESCAPE) &&+ viewModel.foregroundRoute == "camera" ) { viewModel.triggerShutter() true@@ -119,9 +122,10 @@ class MainActivity : ComponentActivity() { } } - // Consume the matching key-up so the system volume UI doesn't appear.+ // Consume the matching key-up so the system volume UI doesn't appear (camera route only). override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {- return if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {+ return if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) &&+ viewModel.foregroundRoute == "camera") { true } else { super.onKeyUp(keyCode, event)
camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.ktindex 9554fb1d92..42e02e92b3 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt@@ -5,6 +5,8 @@ import androidx.camera.camera2.interop.ExperimentalCamera2Interop import androidx.camera.core.Camera import com.vayunmathur.camera.domain.LensSelectionLogic import com.vayunmathur.camera.util.CameraViewModel+import com.vayunmathur.camera.util.applyExposureCompensation+import com.vayunmathur.camera.util.applyManualControls import com.vayunmathur.camera.util.readManualControlRanges import com.vayunmathur.camera.util.refreshNightExtensionUsable import com.vayunmathur.camera.util.restoreZoom@@ -53,6 +55,20 @@ suspend fun CameraViewModel.refreshCapabilities(bound: Camera, lensId: String?) readManualControlRanges() + // Re-assert manual shutter/ISO and exposure compensation onto the fresh bind: the+ // session effect only pushes them on value change, so without this a rebind silently+ // drops them (video mode never applied them at all).+ try {+ applyManualControls()+ } catch (e: Exception) {+ Log.w("LensSelector", "Could not re-apply manual controls", e)+ }+ try {+ applyExposureCompensation(_exposureCompensation.value)+ } catch (e: Exception) {+ Log.w("LensSelector", "Could not re-apply exposure compensation", e)+ }+ val hasFlash = try { bound.cameraInfo.hasFlashUnit() } catch (e: Exception) {
camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.ktindex 747a8d04e0..f477c06e1a 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt@@ -111,10 +111,12 @@ internal fun CameraBottomControls( cameraMode = cameraMode, isPhotoType = state.isPhotoType, sloMoSupported = state.sloMoSupported,+ captureForResult = onCaptureResult != null, onModeSelected = { viewModel.switchCameraMode(it) }, iconRotation = animatedRotation, onPickerChanged = onPickerChanged, onSettingsClick = { backStack.add(Route.Settings) },+ videoPickerEnabled = onCaptureResult == null, ) }, sideBySide = expandedSide,
camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.ktindex 1bc08c5eab..2e1908600d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModeBars.kt@@ -23,6 +23,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import androidx.compose.ui.res.stringResource+import com.vayunmathur.camera.R import com.vayunmathur.camera.util.CameraMode @Composable@@ -30,6 +32,7 @@ internal fun ModeSelector( cameraMode: CameraMode, isPhotoType: Boolean, sloMoSupported: Boolean?,+ captureForResult: Boolean, onModeSelected: (CameraMode) -> Unit ) { Row(@@ -37,22 +40,27 @@ internal fun ModeSelector( horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) {+ // IMAGE_CAPTURE callers wait on a still: lock out video/slo-mo/pano/sphere so the+ // user can't wander into a mode whose shutter never resolves the caller's intent. val modes = if (isPhotoType) {- listOf(- CameraMode.PORTRAIT to "Portrait",- CameraMode.PHOTO to "Photo",- CameraMode.PANORAMA to "Pano",- CameraMode.PHOTOSPHERE to "Sphere"+ val photoModes = listOf(+ CameraMode.PORTRAIT to stringResource(R.string.mode_portrait),+ CameraMode.PHOTO to stringResource(R.string.mode_photo),+ )+ if (captureForResult) photoModes+ else photoModes + listOf(+ CameraMode.PANORAMA to stringResource(R.string.mode_panorama),+ CameraMode.PHOTOSPHERE to stringResource(R.string.mode_photosphere), ) } else { // Only include Slo-Mo when the device's back camera actually supports true HFR. buildList { if (sloMoSupported != false) {- add(CameraMode.SLOW_MO to "Slo-Mo")+ add(CameraMode.SLOW_MO to stringResource(R.string.mode_slo_mo)) }- add(CameraMode.VIDEO to "Video")- add(CameraMode.CINEMATIC to "Cinematic")- add(CameraMode.TIMELAPSE to "Timelapse")+ add(CameraMode.VIDEO to stringResource(R.string.mode_video))+ add(CameraMode.CINEMATIC to stringResource(R.string.mode_cinematic))+ add(CameraMode.TIMELAPSE to stringResource(R.string.mode_timelapse)) } } modes.forEach { (mode, label) ->@@ -77,7 +85,8 @@ internal fun BottomBar( isPhotoType: Boolean, iconRotation: Float, onPickerChanged: (Boolean) -> Unit,- onSettingsClick: () -> Unit+ onSettingsClick: () -> Unit,+ videoPickerEnabled: Boolean = true, ) { Row( modifier = Modifier@@ -118,10 +127,12 @@ internal fun BottomBar( modifier = Modifier .size(36.dp) .selectedPill(!isPhotoType, CircleShape, Color(0xFF5C5C5C))- .clickable { if (isPhotoType) onPickerChanged(false) },+ // IMAGE_CAPTURE callers wait on a still: the video picker stays disabled so+ // the user can't enter a mode whose shutter never resolves the intent.+ .clickable(enabled = videoPickerEnabled) { if (isPhotoType) onPickerChanged(false) }, contentAlignment = Alignment.Center ) {- IconVideoCamera(Modifier.size(20.dp).rotate(iconRotation), Color.White)+ IconVideoCamera(Modifier.size(20.dp).rotate(iconRotation), if (videoPickerEnabled) Color.White else Color(0xFF777777)) } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraModesPane.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModesPane.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModesPane.ktindex 7bf9aa4586..b3d60ec962 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraModesPane.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraModesPane.kt@@ -8,6 +8,8 @@ internal fun CameraModesPane( cameraMode: CameraMode, isPhotoType: Boolean, sloMoSupported: Boolean?,+ captureForResult: Boolean,+ videoPickerEnabled: Boolean = true, onModeSelected: (CameraMode) -> Unit, iconRotation: Float, onPickerChanged: (Boolean) -> Unit,@@ -17,6 +19,7 @@ internal fun CameraModesPane( cameraMode = cameraMode, isPhotoType = isPhotoType, sloMoSupported = sloMoSupported,+ captureForResult = captureForResult, onModeSelected = onModeSelected ) @@ -25,6 +28,7 @@ internal fun CameraModesPane( isPhotoType = isPhotoType, iconRotation = iconRotation, onPickerChanged = onPickerChanged,- onSettingsClick = onSettingsClick+ onSettingsClick = onSettingsClick,+ videoPickerEnabled = videoPickerEnabled, ) }
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex 5955824d7c..85eeefca72 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -98,7 +98,10 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( .clip(RoundedCornerShape(12.dp)) .then( run {- val hasColorAdj = state.warmth != 0f || state.shadows != 0f+ // Warmth/shadows only render where the capture path bakes them (PHOTO/PORTRAIT):+ // elsewhere the capture drops them, so showing the grade in the viewfinder is a lie.+ val bakesStills = cameraMode == CameraMode.PHOTO || cameraMode == CameraMode.PORTRAIT+ val hasColorAdj = bakesStills && (state.warmth != 0f || state.shadows != 0f) // Snapshot mask bitmap at this composition point – don't !! inside graphicsLayer // or a race with DisposableEffect onDispose (null + recycle) causes NPE at 567. val currentMask = maskBitmap?.takeIf {
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex a0798b16d9..157ec32331 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -54,7 +54,12 @@ fun CameraScreen( // The shutter action, shared by the on-screen button and the volume-key (hardware) shutter. val performCapture: () -> Unit = {- view.performHapticFeedback(android.view.HapticFeedbackConstants.CLOCK_TICK)+ // Post to the view's message queue: the hardware-shutter path collects shutterEvents+ // off the composition thread, and performHapticFeedback must run on the UI thread+ // (ThreadConstraint lint). post{} is a no-op hop when already on the UI thread.+ view.post {+ view.performHapticFeedback(android.view.HapticFeedbackConstants.CLOCK_TICK)+ } if (state.longExposureProgress <= 0f) when { state.cameraMode == CameraMode.PHOTOSPHERE -> { if (state.panoSweeping) viewModel.stopPhotosphere() else viewModel.startPhotosphere()@@ -104,9 +109,11 @@ fun CameraScreen( CameraTopBar( flashMode = state.flashMode, torchEnabled = state.torchEnabled,+ hasFlashUnit = state.hasFlashUnit, gridEnabled = state.gridEnabled, levelEnabled = state.levelEnabled, aspectRatio = state.aspectRatio,+ stillCropEnabled = state.cameraMode == CameraMode.PHOTO || state.cameraMode == CameraMode.PORTRAIT, isPhotoType = state.isPhotoType, isVideoType = state.isVideoType, micMuted = state.micMuted,
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex f095b71f6c..6247d83223 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -143,7 +143,13 @@ internal fun CameraScreenEffects( state.maskBitmap = null viewModel.setImageAnalyzer( ImageAnalysis.Analyzer { imageProxy ->- viewModel.panoramaEngine.latestFrame = imageProxy.toBitmap()+ // Atomic publish; captureFrame() takes ownership exactly once, and+ // offerFrame() recycles any undelivered previous bitmap (no leak,+ // no use-after-free across the analyzer/sensor threads).+ viewModel.panoramaEngine.offerFrame(+ imageProxy.toBitmap(),+ imageProxy.imageInfo.rotationDegrees+ ) imageProxy.close() } )@@ -227,8 +233,11 @@ internal fun CameraScreenEffects( // backgrounded and rebound on resume. Without this the ManualLifecycleOwner stays RESUMED, // the OS reclaims the camera while we're away, and the preview comes back frozen. val lifecycleOwner = LocalLifecycleOwner.current- LaunchedEffect(lensFacing, selectedLens, sessionKind, useNightPreview, lifecycleOwner) {- Log.d("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")+ // Codec/audio/mirror are fixed at bind time (Recorder mime, AudioSource, MirrorMode), so+ // they join the effect keys: changing them in Settings rebinds instead of silently waiting+ // for the next mode switch. Aspect ratio is applied live (setCropAspectRatio) — no rebind.+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, state.videoCodec, state.audioInputSource, state.mirrorFront, lifecycleOwner) {+ Log.d("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${state.videoCodec} audio=${state.audioInputSource} mirror=${state.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}") lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { Log.d("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()") viewModel.teardownSession()@@ -267,6 +276,11 @@ internal fun CameraScreenEffects( // Hardware volume-key shutter. val currentCapture = rememberUpdatedState(onCapture) LaunchedEffect(Unit) {- viewModel.shutterEvents.collect { currentCapture.value() }+ viewModel.foregroundRoute = "camera"+ try {+ viewModel.shutterEvents.collect { currentCapture.value() }+ } finally {+ viewModel.foregroundRoute = null+ } } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex cb10f97e35..c499536c44 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -12,10 +12,12 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import com.vayunmathur.camera.util.AspectRatioOption+import com.vayunmathur.camera.util.AudioInputSource import com.vayunmathur.camera.util.CameraMode import com.vayunmathur.camera.util.CameraViewModel import com.vayunmathur.camera.util.FlashMode import com.vayunmathur.camera.util.TimerDuration+import com.vayunmathur.camera.util.VideoCodec /** * All UI state read by [CameraScreen], collected from [CameraViewModel] flows in one@@ -25,7 +27,7 @@ import com.vayunmathur.camera.util.TimerDuration * Collection happens in [rememberCameraScreenState] (a @Composable context); this class is a * plain snapshot holder so the screen stays a thin layout. */-internal class CameraScreenState(+ internal class CameraScreenState( val cameraMode: CameraMode, val lensFacing: Int, val selectedLens: com.vayunmathur.camera.domain.PhysicalLens?,@@ -33,6 +35,8 @@ internal class CameraScreenState( val hasFlashUnit: Boolean, val flashMode: FlashMode, val torchEnabled: Boolean,+ val videoCodec: VideoCodec,+ val audioInputSource: AudioInputSource, val isRecording: Boolean, val recordingDuration: Long, val timerCountdown: Int,@@ -110,10 +114,16 @@ internal class CameraScreenState( val useNightPreview get() = sessionKind == SessionKind.PHOTO && cameraMode == CameraMode.PHOTO && nightModeActive && nightExtAvailable - val previewAspectRatio get() = when (aspectRatio) {- AspectRatioOption.RATIO_16_9 -> 9f / 16f- AspectRatioOption.RATIO_4_3 -> 3f / 4f- AspectRatioOption.RATIO_1_1 -> 1f+ val previewAspectRatio get() = when {+ // The still crop only exists on the photo sessions (PHOTO/PORTRAIT ImageCapture).+ // Video/HFR/pano never crop to it, so letterboxing their preview to it lies about+ // the framing — they show their native 4:3 frame instead.+ cameraMode == CameraMode.PHOTO || cameraMode == CameraMode.PORTRAIT -> when (aspectRatio) {+ AspectRatioOption.RATIO_16_9 -> 9f / 16f+ AspectRatioOption.RATIO_4_3 -> 3f / 4f+ AspectRatioOption.RATIO_1_1 -> 1f+ }+ else -> 3f / 4f } val mirrorPreview get() = lensFacing == CameraSelector.LENS_FACING_FRONT && !mirrorFront@@ -128,6 +138,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val hasFlashUnit by viewModel.hasFlashUnit.collectAsState() val flashMode by viewModel.flashMode.collectAsState() val torchEnabled by viewModel.torchEnabled.collectAsState()+ val videoCodec by viewModel.videoCodec.collectAsState()+ val audioInputSource by viewModel.audioInputSource.collectAsState() val isRecording by viewModel.isRecording.collectAsState() val recordingDuration by viewModel.recordingDurationSec.collectAsState() val timerCountdown by viewModel.timerCountdown.collectAsState()@@ -183,8 +195,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val deviceRotationState = remember { mutableIntStateOf(0) } return remember(- cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, isRecording, recordingDuration,- timerCountdown, qrResult, aspectRatio, zoomRatio, mirrorFront, timerDuration,+ cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, videoCodec, audioInputSource, mirrorFront, isRecording, recordingDuration,+ timerCountdown, qrResult, aspectRatio, zoomRatio, timerDuration, isCapturing, burstActive, burstCount, focusLocked, recordingPaused, micMuted, videoSnapshotSupported, lastCaptureUri, gridEnabled, levelEnabled, roll, blurStrength, exposureComp, warmth, shadows, exposureTimeIndex, manualIsoIndex,@@ -202,6 +214,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen hasFlashUnit = hasFlashUnit, flashMode = flashMode, torchEnabled = torchEnabled,+ videoCodec = videoCodec,+ audioInputSource = audioInputSource, isRecording = isRecording, recordingDuration = recordingDuration, timerCountdown = timerCountdown,
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.ktindex 543eb2300b..7ee9ed4773 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsBars.kt@@ -103,12 +103,18 @@ internal fun SettingsButtonRow( horizontalArrangement = Arrangement.spacedBy(2.dp), verticalAlignment = Alignment.CenterVertically ) {+ // The sliders below bake into saved stills (PHOTO/PORTRAIT) or drive the live+ // preview's 3A (PHOTO only). Offer them only where they do something: elsewhere+ // they'd silently move a preview effect that the capture path drops.+ val bakesStills = cameraMode == CameraMode.PHOTO || cameraMode == CameraMode.PORTRAIT val settings = buildList<Pair<CameraSetting, @Composable (Modifier, Color) -> Unit>> {- add(CameraSetting.BRIGHTNESS to { m, c -> IconSunny(m, c) })- add(CameraSetting.SHADOWS to { m, c -> IconContrast(m, c) })- add(CameraSetting.WARMTH to { m, c -> IconLightbulb(m, c) })- add(CameraSetting.EXPOSURE_TIME to { m, c -> IconTimer(m, c) })+ if (bakesStills) {+ add(CameraSetting.BRIGHTNESS to { m, c -> IconSunny(m, c) })+ add(CameraSetting.SHADOWS to { m, c -> IconContrast(m, c) })+ add(CameraSetting.WARMTH to { m, c -> IconLightbulb(m, c) })+ } if (cameraMode == CameraMode.PHOTO) {+ add(CameraSetting.EXPOSURE_TIME to { m, c -> IconTimer(m, c) }) add(CameraSetting.ISO to { m, c -> IconIso(m, c) }) } if (cameraMode == CameraMode.PORTRAIT) {
camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.ktindex 15b677d893..2dd3a05eaf 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt@@ -47,9 +47,11 @@ import com.vayunmathur.library.ui.Text internal fun CameraTopBar( flashMode: FlashMode, torchEnabled: Boolean,+ hasFlashUnit: Boolean, gridEnabled: Boolean, levelEnabled: Boolean, aspectRatio: AspectRatioOption,+ stillCropEnabled: Boolean, isPhotoType: Boolean, isVideoType: Boolean, micMuted: Boolean,@@ -72,26 +74,30 @@ internal fun CameraTopBar( horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically ) {- val flashBg = if (torchEnabled || flashMode != FlashMode.OFF) Color(0xFF3C3C3C) else Color.Transparent- Box(- modifier = Modifier- .size(40.dp)- .clip(CircleShape)- .background(flashBg, CircleShape)- .combinedClickable(- onClick = onFlashToggle,- onLongClick = onTorchToggle- ),- contentAlignment = Alignment.Center- ) {- val flashIconModifier = Modifier.size(22.dp).rotate(iconRotation)- if (torchEnabled) {- IconFlashlight(flashIconModifier, Color.White)- } else {- when (flashMode) {- FlashMode.ON -> IconFlashOn(flashIconModifier, Color.White)- FlashMode.OFF -> IconFlashOff(flashIconModifier, Color.White)- FlashMode.AUTO -> IconFlashAuto(flashIconModifier, Color.White)+ // Flash/torch share the same LED: without a flash unit (some front lenses) the+ // control is dead, so hide it instead of showing a button that does nothing.+ if (hasFlashUnit) {+ val flashBg = if (torchEnabled || flashMode != FlashMode.OFF) Color(0xFF3C3C3C) else Color.Transparent+ Box(+ modifier = Modifier+ .size(40.dp)+ .clip(CircleShape)+ .background(flashBg, CircleShape)+ .combinedClickable(+ onClick = onFlashToggle,+ onLongClick = onTorchToggle+ ),+ contentAlignment = Alignment.Center+ ) {+ val flashIconModifier = Modifier.size(22.dp).rotate(iconRotation)+ if (torchEnabled) {+ IconFlashlight(flashIconModifier, Color.White)+ } else {+ when (flashMode) {+ FlashMode.ON -> IconFlashOn(flashIconModifier, Color.White)+ FlashMode.OFF -> IconFlashOff(flashIconModifier, Color.White)+ FlashMode.AUTO -> IconFlashAuto(flashIconModifier, Color.White)+ } } } }@@ -106,22 +112,24 @@ internal fun CameraTopBar( IconGrid(Modifier.size(22.dp).rotate(iconRotation), Color.White) } - // The ratio as text: an icon of three nested rectangles does not tell you which one is- // active, and the enum already carries "16:9" / "4:3" / "1:1".- val aspectLabel = stringResource(R.string.settings_aspect_ratio)- IconButton(- onClick = onAspectCycle,- modifier = Modifier.height(40.dp).widthIn(min = 40.dp)- ) {- Text(- aspectRatio.label,- color = Color.White,- fontSize = 13.sp,- fontWeight = FontWeight.Bold,- modifier = Modifier- .rotate(iconRotation)- .semantics { contentDescription = aspectLabel },- )+ // The still crop only binds on the photo sessions (PHOTO/PORTRAIT ImageCapture):+ // hide the picker elsewhere so it can't promise a 1:1 video or pano it won't deliver.+ if (stillCropEnabled) {+ val aspectLabel = stringResource(R.string.settings_aspect_ratio)+ IconButton(+ onClick = onAspectCycle,+ modifier = Modifier.height(40.dp).widthIn(min = 40.dp)+ ) {+ Text(+ aspectRatio.label,+ color = Color.White,+ fontSize = 13.sp,+ fontWeight = FontWeight.Bold,+ modifier = Modifier+ .rotate(iconRotation)+ .semantics { contentDescription = aspectLabel },+ )+ } } if (isPhotoType) {
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex ee3abe5a5d..43b456ee11 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -76,6 +76,14 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM if (granted) viewModel.updateLocation() } + // Publish the foreground route so MainActivity's hardware shutter only fires on camera.+ // onDispose restores "camera" (not null): popping Settings always returns to Camera, and+ // CameraScreen's entry effect won't re-run if NavDisplay kept it composed underneath.+ androidx.compose.runtime.DisposableEffect(Unit) {+ viewModel.foregroundRoute = "settings"+ onDispose { viewModel.foregroundRoute = "camera" }+ }+ // ACTION_OPEN_DOCUMENT_TREE via a hand-built intent: the stock // OpenDocumentTree contract doesn't set FLAG_GRANT_PERSISTABLE_URI_PERMISSION, // which we need to keep the folder across restarts.
camera/src/main/java/com/vayunmathur/camera/util/CameraCaptureProcessing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraCaptureProcessing.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraCaptureProcessing.ktindex 3a58df1753..f7fdc29907 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraCaptureProcessing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraCaptureProcessing.kt@@ -54,13 +54,16 @@ internal fun downscaledThumbnail(image: ImageProxy, mirror: Boolean): Bitmap { if (mirror) postScale(-1f, 1f) } val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)+ if (upright !== raw) raw.recycle() val maxSide = 512 val scale = maxSide.toFloat() / maxOf(upright.width, upright.height) if (scale >= 1f) return upright return upright.scale( (upright.width * scale).roundToInt(), (upright.height * scale).roundToInt()- )+ ).also {+ if (it !== upright) upright.recycle()+ } } /**@@ -130,14 +133,18 @@ internal fun CameraViewModel.writeCaptureExif(uri: Uri, sourceJpeg: ByteArray?, * kept it (issue #731). * * Stamping happens BEFORE any Motion Photo trailer is appended so ExifInterface only ever- * rewrites a pure JPEG. When there is no location to stamp the bytes are returned untouched- * (bit-for-bit, Ultra HDR gain map included).+ * rewrites a pure JPEG. When location is off only orientation is stamped (no GPS rewrite);+ * the Ultra HDR gain map survives either way since ExifInterface preserves it. * Must be called off the main thread (file I/O). */-internal fun CameraViewModel.stampStillBytes(jpeg: ByteArray, rotationDegrees: Int): ByteArray {+internal fun CameraViewModel.stampStillBytes(jpeg: ByteArray, rotationDegrees: Int, mirrored: Boolean = false): ByteArray { updateLocation() val loc = if (_locationEnabled.value) lastLocation else null- ?: return jpeg+ // In-memory captures carry no ImageCapture.Metadata, so orientation must ALWAYS be+ // stamped — not just when GPS is on — or motion shots save sideways with location off.+ // Mirrored front shots need the inverted rotation (FLIP∘ROTATE(θ)∘FLIP = ROTATE(−θ)),+ // matching writeCaptureExif().+ val effectiveDegrees = if (mirrored) (360 - rotationDegrees) % 360 else rotationDegrees var tmp: java.io.File? = null return try { tmp = java.io.File.createTempFile("stamp_", ".jpg", app.cacheDir)@@ -145,14 +152,16 @@ internal fun CameraViewModel.stampStillBytes(jpeg: ByteArray, rotationDegrees: I val exif = ExifInterface(tmp.absolutePath) exif.setAttribute( ExifInterface.TAG_ORIENTATION,- when ((rotationDegrees % 360 + 360) % 360) {+ when ((effectiveDegrees % 360 + 360) % 360) { 90 -> ExifInterface.ORIENTATION_ROTATE_90 180 -> ExifInterface.ORIENTATION_ROTATE_180 270 -> ExifInterface.ORIENTATION_ROTATE_270 else -> ExifInterface.ORIENTATION_NORMAL }.toString() )- exif.setGpsInfo(loc)+ // GPS only when the user opted in; orientation is always stamped above. Skipping+ // setGpsInfo with no location keeps the bytes bit-for-bit (Ultra HDR gain map intact).+ if (loc != null) exif.setGpsInfo(loc) exif.saveAttributes() tmp.readBytes() } catch (e: Exception) {
camera/src/main/java/com/vayunmathur/camera/util/CameraControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraControls.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraControls.ktindex 95ce078365..5389de2e2f 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraControls.kt@@ -166,11 +166,3 @@ internal fun CameraViewModel.stopRecordingTimer() { recordingTimerJob?.cancel() _recordingDurationSec.value = 0 }--fun CameraViewModel.triggerShutter() {- _shutterEvents.tryEmit(Unit)-}--fun CameraViewModel.setSloMoFps(fps: Int) {- sloMoFps = fps-}
camera/src/main/java/com/vayunmathur/camera/util/CameraManualControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraManualControls.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraManualControls.ktindex af9ec2d57f..accc5227ec 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraManualControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraManualControls.kt@@ -70,11 +70,6 @@ fun CameraViewModel.applyManualControls() { } } -internal fun CameraViewModel.resetManualControls() {- _manualIsoIndex.value = 0- _exposureTimeIndex.value = 0-}- /** Reads the bound sensor's ISO range → stop list for the manual ISO control. */ @OptIn(ExperimentalCamera2Interop::class) internal fun CameraViewModel.readManualControlRanges() {@@ -99,6 +94,9 @@ internal fun CameraViewModel.readManualControlRanges() { Log.w("NightPreview", "readManualControlRanges() isoRange null, emitting emptyList -> ISO bar notAvailable") emptyList() }+ // The stop list is per-lens: a new lens can be shorter, so re-clamp the persisted+ // index instead of pointing past the end (ISO bar read getOrNull → blank label).+ _manualIsoIndex.value = _manualIsoIndex.value.coerceIn(0, _isoStops.value.size) } catch (e: Exception) { Log.e("NightPreview", "readManualControlRanges() FAILED (was Warn, hidden) – could affect ISO bar + manual controls", e) }
camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.ktindex 11d573e5df..45ef0e8993 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt@@ -2,6 +2,7 @@ package com.vayunmathur.camera.util import android.graphics.Bitmap import android.graphics.Matrix+import android.graphics.Rect import android.net.Uri import android.util.Log import androidx.camera.camera2.interop.ExperimentalCamera2Interop@@ -62,6 +63,9 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() { .setFlashMode(getImageCaptureFlashMode()) .build() imageCapture = capture+ // Match the still crop the normal photo session uses (1:1 / 16:9 / 4:3), or+ // night-extension shots always save full-frame while the preview shows cropped.+ capture.setCropAspectRatio(currentCropAspectRatio()) boundCamera = bindSession(provider, owner, nightSelector, preview, capture) val pending = prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg")@@ -212,8 +216,11 @@ internal fun CameraViewModel.captureNightBurst(exposure: NightExposure, onDone: object : ImageCapture.OnImageCapturedCallback() { override fun onCaptureSuccess(image: ImageProxy) { try {- // toBitmap() is provided by CameraX (used also in BokehAnalyzer)- val raw = image.toBitmap()+ // toBitmap() is provided by CameraX (used also in BokehAnalyzer).+ // Apply the session's cropRect (setCropAspectRatio): the raw frame is+ // always full-frame, so without this the burst ignores the 1:1/16:9 crop.+ val cropRect = android.graphics.Rect(image.cropRect)+ val raw = cropToRect(image.toBitmap(), cropRect) val matrix = Matrix().apply { postRotate(image.imageInfo.rotationDegrees.toFloat()) if (mirror) postScale(-1f, 1f)
camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.ktindex b12abfec78..12976aed9d 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt@@ -14,14 +14,21 @@ import kotlinx.coroutines.withContext import kotlin.math.roundToInt fun CameraViewModel.takePhoto() {+ // Second tap cancels an armed timer, mirroring toggleRecording().+ if (_timerCountdown.value > 0) {+ cancelTimerCountdown()+ return+ }+ if (_isCapturing.value || _burstActive.value) return val timer = _timerDuration.value if (timer.seconds > 0) {- viewModelScope.launch {+ timerCountdownJob = viewModelScope.launch { for (i in timer.seconds downTo 1) { _timerCountdown.value = i kotlinx.coroutines.delay(1000) } _timerCountdown.value = 0+ timerCountdownJob = null capturePhoto() } } else {@@ -30,7 +37,10 @@ fun CameraViewModel.takePhoto() { } internal fun CameraViewModel.capturePhoto() {- if (imageCapture == null) return+ if (imageCapture == null || _isCapturing.value || _burstActive.value) return+ // Claim in-flight synchronously so a second shutter tap (or a stacked timer firing)+ // can't start a concurrent capture; every path below clears it on completion.+ _isCapturing.value = true when { // Night Sight mode (or auto-engaged night): the preview is bound with the vendor NIGHT // extension, so a plain single capture through that ImageCapture lets the vendor pipeline@@ -55,19 +65,32 @@ internal fun CameraViewModel.capturePhoto() { * is reached. Uses the plain capture path (no night/manual special-casing). */ fun CameraViewModel.startBurst() {- if (_burstActive.value) return+ if (_burstActive.value || _isCapturing.value) return+ // A burst is immediate: an armed shutter timer no longer applies.+ cancelTimerCountdown() val capture = imageCapture ?: return+ // Mark both in-flight: a single capture must not start mid-burst and a burst must not+ // start mid-capture. Releasing the shutter always goes through finishBurst().+ _isCapturing.value = true _burstActive.value = true _burstCount.value = 0 val ts = MediaStoreSaver.timestamp() + fun finishBurst() {+ _burstActive.value = false+ _isCapturing.value = false+ }+ fun shootNext(n: Int) { if (!_burstActive.value || n > CameraViewModel.BURST_MAX) {- _burstActive.value = false+ finishBurst() return }+ // prepareStillSave falls back to MediaStore, so null is unexpected — but a null+ // here must terminate, never retry (the old `?: run { shootNext(n + 1) }` looped+ // forever when the save target was unusable). val pending = prepareStillSave("IMG_${ts}_BURST${n}.jpg") ?: run {- shootNext(n + 1)+ finishBurst() return } val outputOptions = pending.outputOptions@@ -94,6 +117,9 @@ fun CameraViewModel.startBurst() { } fun CameraViewModel.stopBurst() {+ // Release path for the press-and-hold gesture: only clears the loop flag. The in-flight+ // frame's save callback finishes the sequence (finishBurst) so a release between frames+ // still lands the shot already exposing. _burstActive.value = false } @@ -171,7 +197,7 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto( // In-memory captures carry no ImageCapture.Metadata, so stamp GPS/orientation into the // still bytes here (issue #731). Must happen BEFORE the MP4 trailer is appended — // ExifInterface only understands a pure JPEG.- val stillBytes = stampStillBytes(jpegBytes, degrees)+ val stillBytes = stampStillBytes(jpegBytes, degrees, mirrorCaptures) // Only frames matching the newest frame's dimensions are encoded (a rebind can change size). val sized = frames.takeIf { it.isNotEmpty() }?.let { list -> val w = list.last().bitmap.width
camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.ktindex 9430c4e9f4..9d6803d39a 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt@@ -566,7 +566,6 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean { val zsPor = boundCamera?.cameraInfo?.zoomState?.value Log.d("NightPreview", "setupPortraitSession() final zoom min=${zsPor?.minZoomRatio} max=${zsPor?.maxZoomRatio} ratio=${zsPor?.zoomRatio} – if max=1, zoom bar will show only 1x")- _sloMoSupported.value = true applyManualControls() boundCamera?.let { refreshCapabilities(it, portraitBoundLensId) } onSessionBound()
camera/src/main/java/com/vayunmathur/camera/util/CameraSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraSessions.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraSessions.ktindex f706fe0b01..8dc29c3a4d 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSessions.kt@@ -39,6 +39,22 @@ fun CameraViewModel.teardownSession() { currentRecording = null highSpeedRecording?.stop() highSpeedRecording = null+ // Reset recording/timer state: the session they belonged to is gone (e.g. app+ // backgrounded mid-recording via repeatOnLifecycle). Without this the timer keeps+ // ticking with _isRecording=true while nothing records (phantom indicator), and a+ // pending shutter timer would fire capturePhoto() into the next session unprompted.+ // _isCapturing is also reset: a capture in flight across teardown never completes+ // (its session is gone), and a stuck true would deaden the shutter on resume.+ recordingTimerJob?.cancel()+ recordingTimerJob = null+ timerCountdownJob?.cancel()+ timerCountdownJob = null+ _isRecording.value = false+ _recordingPaused.value = false+ _recordingDurationSec.value = 0+ _timerCountdown.value = 0+ _isCapturing.value = false+ stopLongExposureCountdown() try { imageAnalysis?.clearAnalyzer() Log.d("NightPreview", "teardownSession() cleared analyzer previous=${desiredAnalyzer?.javaClass?.simpleName}")@@ -72,7 +88,12 @@ fun CameraViewModel.teardownSession() { // runs on every night<->normal preview rebind, and resetting would clear // nightModeActive mid-swap and thrash the session. Explicit resets live in // switchCameraMode / flipCamera instead.- resetManualControls()+ //+ // Manual shutter/ISO are likewise NOT reset: they are no longer a transient preview+ // tweak — applyManualControls() pushes them onto the session, and+ // refreshCapabilities() re-asserts them after this teardown's rebind. Resetting+ // silently wiped the user's pro settings on every mode switch. The ISO stop list is+ // per-lens, so readManualControlRanges() re-probes it; the index is re-clamped there. clearMotionFrames() }
camera/src/main/java/com/vayunmathur/camera/util/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraSettings.ktindex 544b246edb..22c0243462 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSettings.kt@@ -9,9 +9,15 @@ import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch internal fun CameraViewModel.loadSettings() {- ds.getString("camera_flash")?.let { _flashMode.value = FlashMode.valueOf(it) }- ds.getString("camera_timer")?.let { _timerDuration.value = TimerDuration.valueOf(it) }- ds.getString("camera_aspect_ratio")?.let { _aspectRatio.value = AspectRatioOption.valueOf(it) }+ ds.getString("camera_flash")?.let {+ runCatching { _flashMode.value = FlashMode.valueOf(it) }+ }+ ds.getString("camera_timer")?.let {+ runCatching { _timerDuration.value = TimerDuration.valueOf(it) }+ }+ ds.getString("camera_aspect_ratio")?.let {+ runCatching { _aspectRatio.value = AspectRatioOption.valueOf(it) }+ } ds.getString("camera_video_codec")?.let { _videoCodec.value = try { VideoCodec.valueOf(it) } catch (_: Exception) { when {
camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.ktindex b3670b6224..4a9ce150b3 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt@@ -91,21 +91,22 @@ internal fun CameraViewModel.captureSinglePhoto() { } viewModelScope.launch { val uri = withContext(Dispatchers.IO) {- val decoded = cropToRect(- BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size),- cropRect- )- // The bokeh renderer folds the colour matrix and the mirror in- // as it composites; it leaves `decoded` alone if it can't run,- // so fall back to the plain colour pass.- val adjusted = (if (bokeh) {- stillBokeh.render(decoded, degrees, strength, warmth, shadows, mirror)- } else null)- ?: applyColorAdjustments(decoded, warmth, shadows, mirror)- val name = "IMG_${MediaStoreSaver.timestamp()}.jpg"- saveStillBitmap(name, adjusted)- ?.also { writeCaptureExif(it, sourceJpeg, degrees, mirrored = mirror) }- .also { adjusted.recycle() }+ runCatching {+ val decodedRaw = BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size)+ ?: error("Could not decode captured frame")+ val decoded = cropToRect(decodedRaw, cropRect)+ // The bokeh renderer folds the colour matrix and the mirror in+ // as it composites; it leaves `decoded` alone if it can't run,+ // so fall back to the plain colour pass.+ val adjusted = (if (bokeh) {+ stillBokeh.render(decoded, degrees, strength, warmth, shadows, mirror)+ } else null)+ ?: applyColorAdjustments(decoded, warmth, shadows, mirror)+ val name = "IMG_${MediaStoreSaver.timestamp()}.jpg"+ saveStillBitmap(name, adjusted)+ ?.also { writeCaptureExif(it, sourceJpeg, degrees, mirrored = mirror) }+ .also { adjusted.recycle() }+ }.getOrNull() } finishCapture(uri) }@@ -169,6 +170,7 @@ internal fun CameraViewModel.captureSinglePhoto() { */ fun CameraViewModel.capturePhotoForResult(onSaved: (Bitmap?) -> Unit, onError: () -> Unit) { val capture = imageCapture ?: return onError()+ if (_isCapturing.value) return _isCapturing.value = true val executor = ContextCompat.getMainExecutor(app) val outputUri = resultOutputUri
camera/src/main/java/com/vayunmathur/camera/util/CameraVideoRecording.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoRecording.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoRecording.ktindex 8f1f9dc430..feeb4000a0 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoRecording.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoRecording.kt@@ -47,6 +47,7 @@ fun CameraViewModel.toggleHighSpeedRecording() { @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startHighSpeedRecording() {+ if (_isRecording.value) return val videoCapture = highSpeedVideoCapture ?: return val timestamp = MediaStoreSaver.timestamp()@@ -120,6 +121,7 @@ fun CameraViewModel.toggleRecording() { @android.annotation.SuppressLint("MissingPermission") internal fun CameraViewModel.startRecording() {+ if (_isRecording.value) return val capture = videoCapture ?: return val timestamp = MediaStoreSaver.timestamp()@@ -212,6 +214,7 @@ fun CameraViewModel.toggleMicMuted() { * video session. No-op if the device couldn't bind the extra ImageCapture use case. */ fun CameraViewModel.captureVideoSnapshot() {+ if (_isCapturing.value) return val capture = imageCapture ?: return val pending = prepareStillSave("IMG_${MediaStoreSaver.timestamp()}.jpg") ?: return val outputOptions = pending.outputOptions@@ -231,11 +234,17 @@ fun CameraViewModel.captureVideoSnapshot() { ) } -fun CameraViewModel.startPanorama() = panoramaEngine.startSweep()+fun CameraViewModel.startPanorama() {+ if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || _isCapturing.value) return+ panoramaEngine.startSweep()+} fun CameraViewModel.stopPanorama() = finishPanoramaSweep() -fun CameraViewModel.startPhotosphere() = panoramaEngine.startSweep(fullSphere = true)+fun CameraViewModel.startPhotosphere() {+ if (panoramaEngine.isSweeping.value || panoramaEngine.isStitching.value || _isCapturing.value) return+ panoramaEngine.startSweep(fullSphere = true)+} fun CameraViewModel.stopPhotosphere() = finishPanoramaSweep()
camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.ktindex f6f8ef71ab..5e1e08b9cf 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt@@ -96,10 +96,13 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean { recordingWithHevc = hevc return if (snapshot) { // Extra ImageCapture use case enables taking a still while recording (SDR JPEG).+ // Crop matches the still aspect ratio like the photo session, or snapshots+ // always save full-frame while the preview shows cropped. val still = ImageCapture.Builder() .setFlashMode(ImageCapture.FLASH_MODE_OFF) .build() imageCapture = still+ still.setCropAspectRatio(currentCropAspectRatio()) bindSession(provider, owner, lensSelector, preview, capture, still) } else { imageCapture = null
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex e067003cac..273945e061 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -574,6 +574,21 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { sloMoFps = fps } + /** Cancels an armed photo/video shutter timer (second tap dismisses it). */+ fun cancelTimerCountdown() {+ timerCountdownJob?.cancel()+ timerCountdownJob = null+ _timerCountdown.value = 0+ }++ /**+ * Which camera route is in the foreground ("camera" vs "settings"), or null before first+ * composition. Set by CameraScreenEffects/SettingsPage; MainActivity gates the hardware+ * shutter on it so volume/space keys pressed in Settings don't queue a surprise capture+ * (and volume keys keep adjusting volume there).+ */+ @Volatile var foregroundRoute: String? = null+ init { loadSettings() panoramaEngine.onSweepComplete = { finishPanoramaSweep() }@@ -661,9 +676,12 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { // Last-capture persistence lives in CameraSettings.kt as an extension. fun switchCameraMode(newMode: CameraMode) {- // A new mode starts with a clean night-detection slate (teardown no longer- // resets it, since it also runs on night<->normal preview rebinds).- if (newMode != _cameraMode.value) resetNightModeDetection()+ // A pending shutter timer belongs to the old mode: firing capturePhoto() into the+ // new session would capture unprompted (and with the wrong use cases bound).+ if (newMode != _cameraMode.value) {+ cancelTimerCountdown()+ resetNightModeDetection()+ } // Slo-Mo is back-camera only; enforce it when entering Slo-Mo. if (newMode == CameraMode.SLOW_MO) { if (_lensFacing.value != CameraSelector.LENS_FACING_BACK) {
camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt b/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.ktindex e718d22bea..cf73678df2 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/MediaStoreSaver.kt@@ -23,8 +23,12 @@ object MediaStoreSaver { year(); monthNumber(); day(); char('_'); hour(); minute(); second() } - fun timestamp(): String =- Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).format(FileStamp)+ // Millisecond suffix: two singles in the same second otherwise share IMG_<ts>.jpg+ // (burst adds its own suffix, singles don't), producing confusing duplicates.+ fun timestamp(): String {+ val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())+ return now.format(FileStamp) + "_%03d".format(now.nanosecond / 1_000_000)+ } fun imageValues(displayName: String): ContentValues = contentValues(displayName, "image/jpeg") @@ -43,8 +47,18 @@ object MediaStoreSaver { quality: Int = 95, ): Uri? { val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null- resolver.openOutputStream(uri)?.use { os ->- bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os)+ val ok = try {+ resolver.openOutputStream(uri)?.use { os ->+ bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os)+ } ?: false+ } catch (e: Exception) {+ android.util.Log.w("MediaStoreSaver", "saveBitmap write failed for $uri", e)+ false+ }+ // A failed write must not leave a 0-byte ghost row that becomes the gallery thumbnail.+ if (!ok) {+ try { resolver.delete(uri, null, null) } catch (_: Exception) {}+ return null } return uri }@@ -56,8 +70,18 @@ object MediaStoreSaver { bytes: ByteArray, ): Uri? { val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return null- resolver.openOutputStream(uri)?.use { os ->- os.write(bytes)+ val ok = try {+ resolver.openOutputStream(uri)?.use { os ->+ os.write(bytes)+ }+ true+ } catch (e: Exception) {+ android.util.Log.w("MediaStoreSaver", "saveJpegBytes write failed for $uri", e)+ false+ }+ if (!ok) {+ try { resolver.delete(uri, null, null) } catch (_: Exception) {}+ return null } return uri }@@ -106,8 +130,18 @@ object MediaStoreSaver { fun saveVideoFile(resolver: ContentResolver, values: ContentValues, file: File): Uri? { val uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values) ?: return null- resolver.openOutputStream(uri)?.use { os ->- file.inputStream().use { input -> input.copyTo(os) }+ val ok = try {+ resolver.openOutputStream(uri)?.use { os ->+ file.inputStream().use { input -> input.copyTo(os) }+ }+ true+ } catch (e: Exception) {+ android.util.Log.w("MediaStoreSaver", "saveVideoFile write failed for $uri", e)+ false+ }+ if (!ok) {+ try { resolver.delete(uri, null, null) } catch (_: Exception) {}+ return null } return uri }
camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.ktindex 2f3589b4d0..f09c2418b4 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PanoramaEngine.kt@@ -91,8 +91,47 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { private var sphereMode = false - @Volatile- var latestFrame: Bitmap? = null+ /**+ * Latest analysis frame for panorama capture, with the sensor rotation (degrees) needed+ * to upright it. Delivered every frame by the analyzer; only the newest is kept — the+ * setter recycles any undelivered previous bitmap so a sweep doesn't leak one per frame.+ * All access is under [frameLock]: the analyzer writes on the main executor while+ * captureFrame() reads on the sensor thread, so an unsynchronized recycle would+ * use-after-free the bitmap mid-compress.+ */+ private val frameLock = Any()+ private var _latestFrame: Bitmap? = null+ private var _latestFrameRotation: Int = 0+ var latestFrame: Bitmap?+ get() = synchronized(frameLock) { _latestFrame }+ set(value) = synchronized(frameLock) {+ val old = _latestFrame+ _latestFrame = value+ if (old !== value && old != null && !old.isRecycled) {+ try { old.recycle() } catch (_: Exception) {}+ }+ }+ var latestFrameRotation: Int+ get() = synchronized(frameLock) { _latestFrameRotation }+ set(value) = synchronized(frameLock) { _latestFrameRotation = value }++ /** Atomically publishes one analyzer frame plus its rotation. */+ fun offerFrame(frame: Bitmap?, rotation: Int) = synchronized(frameLock) {+ val old = _latestFrame+ _latestFrame = frame+ _latestFrameRotation = rotation+ if (old !== frame && old != null && !old.isRecycled) {+ try { old.recycle() } catch (_: Exception) {}+ }+ }++ /** Atomically takes ownership of the pending frame (clearing the slot); caller must recycle. */+ fun takeFrame(): Pair<Bitmap?, Int> = synchronized(frameLock) {+ val f = _latestFrame+ val r = _latestFrameRotation+ _latestFrame = null+ f to r+ } /** * Invoked once when a sweep auto-completes (all guide dots captured, or a flat@@ -157,8 +196,13 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { nativeHandle = if (StitchNative.isAvailable) StitchNative.newSession(fullSphere) else 0L capturedFrames.clear() - captureFrame() // seed with the starting frame- updateDotState(0, GuideDotState.CAPTURED)+ // Seed with the starting frame, but only mark dot 0 captured if a frame was actually+ // available: the analyzer may not have delivered one yet, and marking it captured with+ // zero frames produced an empty sweep that could never complete.+ captureFrame()+ if (_frameCount.value > 0) {+ updateDotState(0, GuideDotState.CAPTURED)+ } _isSweeping.value = true gyroscope?.let {@@ -172,23 +216,51 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { } private fun captureFrame() {- val frame = latestFrame ?: return- val handle = nativeHandle- if (handle == 0L) return- // Rotate to upright and JPEG-compress. Storing frames compressed keeps- // memory bounded across a long, high-resolution sweep (they're decoded on- // demand by the native stitcher, one at a time).- val rotMatrix = Matrix().apply { postRotate(90f) }- val rotated = Bitmap.createBitmap(frame, 0, 0, frame.width, frame.height, rotMatrix, true)- val baos = ByteArrayOutputStream()- rotated.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, baos)- rotated.recycle()- val jpeg = baos.toByteArray()- // Keep the same JPEG bytes the native registrar receives, so the GPU- // compositor can decode kept frames into textures by capture index.- capturedFrames.add(jpeg)- StitchNative.addFrame(handle, jpeg, accumulatedAngle, accumulatedPitch, accumulatedRoll)- _frameCount.value = _frameCount.value + 1+ // Takes ownership of the pending analyzer frame (clearing the slot); the source bitmap+ // is always consumed here — either compressed to JPEG bytes or recycled on failure.+ val (frame, rotation) = takeFrame()+ if (frame == null) return+ try {+ if (frame.isRecycled || frame.width <= 0 || frame.height <= 0) return+ val handle = nativeHandle+ if (handle == 0L) return+ // Upright the sensor-oriented frame with the rotation the analyzer reported for it+ // (instead of the old hardcoded 90° that sideways-stitched landscape sensors), then+ // JPEG-compress for storage: frames are decoded on demand by the native stitcher,+ // one at a time, so a long high-resolution sweep stays memory-bounded.+ val normalized = ((rotation % 360) + 360) % 360+ val rotated = if (normalized == 0) {+ frame+ } else {+ val rotMatrix = Matrix().apply { postRotate(normalized.toFloat()) }+ try {+ Bitmap.createBitmap(frame, 0, 0, frame.width, frame.height, rotMatrix, true)+ } catch (_: Exception) {+ return+ }+ }+ val baos = ByteArrayOutputStream()+ val ok = try {+ rotated.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, baos)+ } catch (_: Exception) {+ false+ }+ if (rotated !== frame) {+ try { rotated.recycle() } catch (_: Exception) {}+ }+ if (!ok) return+ val jpeg = baos.toByteArray()+ if (jpeg.isEmpty()) return+ // Keep the same JPEG bytes the native registrar receives, so the GPU+ // compositor can decode kept frames into textures by capture index.+ capturedFrames.add(jpeg)+ StitchNative.addFrame(handle, jpeg, accumulatedAngle, accumulatedPitch, accumulatedRoll)+ _frameCount.value = _frameCount.value + 1+ } finally {+ // The analyzer hands off ownership; either the rotated copy above survives as JPEG+ // bytes or nothing does — the source bitmap is always consumed here.+ try { frame.recycle() } catch (_: Exception) {}+ } } override fun onSensorChanged(event: SensorEvent) {@@ -430,6 +502,10 @@ class PanoramaEngine(private val context: Context) : SensorEventListener { accumulatedPitch = 0f accumulatedRoll = 0f pitchVelocity = 0f- latestFrame = null+ // takeFrame() takes ownership; recycle whatever the analyzer left pending.+ val (pending, _) = takeFrame()+ if (pending != null && !pending.isRecycled) {+ try { pending.recycle() } catch (_: Exception) {}+ } } }
camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt b/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.ktindex c1f5cbc62b..84ebb4c68c 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/VideoProcessor.kt@@ -14,57 +14,69 @@ object VideoProcessor { val rotation = try { retriever.setDataSource(inputFile.path) retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull() ?: 0- } catch (_: Exception) { 0 } finally { retriever.release() }+ } catch (_: Exception) { 0 } finally {+ try { retriever.release() } catch (_: Exception) {}+ } val extractor = MediaExtractor()- extractor.setDataSource(inputFile.path)+ var muxer: MediaMuxer? = null+ try {+ extractor.setDataSource(inputFile.path) - val muxer = MediaMuxer(outputFile.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)- muxer.setOrientationHint(rotation)+ muxer = MediaMuxer(outputFile.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4)+ muxer.setOrientationHint(rotation) - var videoTrackIndex = -1- var muxerTrackIndex = -1- for (i in 0 until extractor.trackCount) {- val format = extractor.getTrackFormat(i)- val mime = format.getString(MediaFormat.KEY_MIME) ?: ""- if (mime.startsWith("video/")) {- videoTrackIndex = i- muxerTrackIndex = muxer.addTrack(format)- break+ var videoTrackIndex = -1+ var muxerTrackIndex = -1+ for (i in 0 until extractor.trackCount) {+ val format = extractor.getTrackFormat(i)+ val mime = format.getString(MediaFormat.KEY_MIME) ?: ""+ if (mime.startsWith("video/")) {+ videoTrackIndex = i+ muxerTrackIndex = muxer.addTrack(format)+ break+ } }- } - if (videoTrackIndex < 0) {- extractor.release()- muxer.release()- return- }+ // No video track (audio-only input): clean up the half-created muxer and the empty+ // output so the caller falls back to the raw recording instead of a 0-byte file.+ if (videoTrackIndex < 0) {+ try { extractor.release() } catch (_: Exception) {}+ try { muxer.release() } catch (_: Exception) {}+ muxer = null+ try { outputFile.delete() } catch (_: Exception) {}+ return+ } - extractor.selectTrack(videoTrackIndex)- muxer.start()+ extractor.selectTrack(videoTrackIndex)+ muxer.start() - val buffer = ByteBuffer.allocate(2 * 1024 * 1024)- val info = MediaCodec.BufferInfo()+ val buffer = ByteBuffer.allocate(2 * 1024 * 1024)+ val info = MediaCodec.BufferInfo() - // newPts = (pts / totalDuration) * (totalDuration / speedFactor) == pts / speedFactor,- // so timestamps can be remapped per-sample without buffering the whole stream.- while (true) {- val size = extractor.readSampleData(buffer, 0)- if (size < 0) break- info.offset = 0- info.size = size- info.flags = if (extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0) {- MediaCodec.BUFFER_FLAG_KEY_FRAME- } else {- 0+ // newPts = (pts / totalDuration) * (totalDuration / speedFactor) == pts / speedFactor,+ // so timestamps can be remapped per-sample without buffering the whole stream.+ while (true) {+ val size = extractor.readSampleData(buffer, 0)+ if (size < 0) break+ info.offset = 0+ info.size = size+ info.flags = if (extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0) {+ MediaCodec.BUFFER_FLAG_KEY_FRAME+ } else {+ 0+ }+ info.presentationTimeUs = (extractor.sampleTime.toDouble() / speedFactor).toLong()+ muxer.writeSampleData(muxerTrackIndex, buffer, info)+ extractor.advance() }- info.presentationTimeUs = (extractor.sampleTime.toDouble() / speedFactor).toLong()- muxer.writeSampleData(muxerTrackIndex, buffer, info)- extractor.advance()- } - muxer.stop()- muxer.release()- extractor.release()+ try { muxer.stop() } catch (_: Exception) {}+ } finally {+ if (muxer != null) {+ try { muxer.release() } catch (_: Exception) {}+ }+ try { extractor.release() } catch (_: Exception) {}+ } } }
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 36ebc6ecb7..f9a29f0165 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -3,6 +3,14 @@ <string name="app_name">Camera</string> <!-- Main camera: mode selector at bottom (Photo / Video / Portrait etc) -->+ <string name="mode_photo">Photo</string>+ <string name="mode_portrait">Portrait</string>+ <string name="mode_panorama">Pano</string>+ <string name="mode_photosphere">Sphere</string>+ <string name="mode_video">Video</string>+ <string name="mode_slo_mo">Slo-Mo</string>+ <string name="mode_cinematic">Cinematic</string>+ <string name="mode_timelapse">Timelapse</string> <!-- TopBar / Auto night: night mode button shown in low light --> <string name="night">Night</string>