camera: release shutter on capture, save Motion Photos in background (#914)
- Commit
32bf57042a4668815fbf940dbb57e3e4871dde86- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-12 05:05 UTC (24 days ago)
- Parents
c158abe
Symptom (#914): a noticeable delay between pressing the shutter and getting the picture. After a press the shutter stayed pressed in, the gallery thumbnail did not change, and a second press was ignored until the photo was fully saved. Root cause: the default shot (Photo mode, 4:3, flash off) is a Motion Photo, and captureMotionPhoto() cleared isCapturing only after the whole clip was built: draining up to 24 frames, converting and encoding them to H.264, appending the trailer and writing it to MediaStore. isCapturing drives the pressed-in shutter, gates the next press (capturePhoto() returns early), and the thumbnail only updates from the saved Uri, so every one of those steps was on the shutter path. Changes: - The in-flight state is released in onCaptureSuccess, as soon as the still's JPEG bytes are copied out, not after the save. The clip is built and saved by onMotionStillCaptured() in motionSaveScope on Dispatchers.IO (blocking MediaCodec/file work). The scope is a SupervisorJob with a logging exception handler and is deliberately not cancelled in onCleared, so a save in progress still lands when the user leaves the screen. Saves run one at a time in shot order under a fair Mutex; the thumbnail updates as each lands. - Bounded queue: domain/MotionSaveQueue (capacity MAX_PENDING_MOTION_SAVES = 2: one encoding, one waiting). Each pending save holds its drained frames (up to 24 ~5 MB bitmaps) until encoded, so this caps that memory. The router reserves a slot before capturing; if none is free the press takes a plain still instead of blocking. Slots are released when the save finishes or fails, or when the capture errors. Frames are recycled after their save, not before. - Capture-time snapshot: file name, mirroring and rotation are fixed at the press (MotionSaveRequest), so a camera flip or later shots while a save waits can't change how it is saved, and queued shots keep their own timestamps. - capturePhoto()'s routing is now routeStillCapture() returning a StillRoute (same night/single/Motion Photo rules as before, plus the queue check), so the decision is testable. - Shutter feedback at the real moment of capture: CameraX onCaptureStarted (falling back to onCaptureSuccess) emits shutterFeedback, and a new CaptureFlashOverlay briefly dims the viewfinder, like the stock camera. Wired for the Motion Photo, plain single and processed (portrait/warmth) single paths; bursts and night shots keep their existing indicators. Uses the library/ui animatedFloat helper, no raw animation APIs; nothing else in the layout changes, so the hand-committed screenshots are unaffected. - Lint/detekt cleanup in touched files: KDoc for CameraViewModel, its companion and MotionFrame; @OptIn(ExperimentalCamera2Interop) on the single-capture helpers that use Camera2 interop; a night-extension comment reworded that lint misread as commented-out code. Alternatives considered: - Keeping the shutter held but making the encode faster (previous commit) still leaves encode + MediaStore I/O on the shutter path. - An unbounded queue or one save coroutine per shot would let rapid shooting hold many 24-frame buffers at once. - viewModelScope for saves: cancelled when the screen is closed, losing the last shot. - Showing the thumbnail from the in-memory JPEG before the save lands: tapping it would still open the previous photo, so the thumbnail keeps updating from the saved Uri. User-visible effect: the shutter springs back as soon as the frame is captured, with a brief viewfinder dim as the "got it" cue; the next shot can be taken right away while earlier Motion Photos finish saving; the thumbnail updates a moment later when each save lands. A third rapid shot while two are still saving is saved as a plain photo (no motion clip) rather than waiting. Portrait/warmth (processed) captures and night shots still hold the shutter until saved. Verification: :camera:compileDevKotlin, :camera:testDevUnitTest (new MotionSaveQueueTest; new Robolectric MotionPhotoCaptureStateTest: default shot routes to Motion Photo and reserves a slot; in-flight is released on capture while the save is still blocked, and the Uri, slot and frame recycling happen only when the save completes; a second shot is allowed mid-save; a full queue falls back to a plain still and recovers after a save; saves land in shot order even when the first is slower; a failing save still frees its slot and frames; non-Motion modes don't touch the queue), :camera:lint and :camera:detekt clean for the touched files. Not timed on a device.
Diff
camera/AGENTS.md
diff --git a/camera/AGENTS.md b/camera/AGENTS.mdindex f73bc19ce8..dab42fe2b7 100644--- a/camera/AGENTS.md+++ b/camera/AGENTS.md@@ -33,6 +33,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/domain/LensModel.kt - com/vayunmathur/camera/domain/LensSelectionLogic.kt - com/vayunmathur/camera/domain/ArgbToI420Converter.kt — bulk ARGB→YUV 4:2:0 for the Motion Photo clip+- com/vayunmathur/camera/domain/MotionSaveQueue.kt — bound on Motion Photos still saving after the shutter ### platform/ — capability queries - com/vayunmathur/camera/platform/CameraCapabilities.kt - com/vayunmathur/camera/platform/LensSelector.kt@@ -43,6 +44,7 @@ _Install: ./install camera (dev by default)._ - com/vayunmathur/camera/ui/CameraScreenEffects.kt - com/vayunmathur/camera/ui/CameraPreviewBox.kt - com/vayunmathur/camera/ui/CameraPreviewOverlays.kt+- com/vayunmathur/camera/ui/CaptureFlashOverlay.kt - com/vayunmathur/camera/ui/CameraOverlays.kt - com/vayunmathur/camera/ui/CameraPanoramaOverlay.kt - com/vayunmathur/camera/ui/CameraTopBar.kt
camera/src/main/java/com/vayunmathur/camera/domain/MotionSaveQueue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/MotionSaveQueue.kt b/camera/src/main/java/com/vayunmathur/camera/domain/MotionSaveQueue.ktnew file mode 100644index 0000000000..3d3433280e--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/MotionSaveQueue.kt@@ -0,0 +1,38 @@+package com.vayunmathur.camera.domain++import java.util.concurrent.atomic.AtomicInteger++/**+ * Admission control for Motion Photos still being built after their shutter was released.+ *+ * Each pending save holds its drained ring-buffer frames (up to 24 analysis bitmaps, ~5 MB each)+ * until the clip is encoded, so the number in flight must stay small. A shot reserves a slot+ * before it is captured and releases it once its save finishes (or fails); when no slot is free+ * the caller takes a plain still instead of blocking the shutter. Thread-safe: reserved on the+ * main thread, released from the save worker.+ */+class MotionSaveQueue(val capacity: Int) {++ init {+ require(capacity > 0) { "capacity must be positive, was $capacity" }+ }++ private val inFlight = AtomicInteger(0)++ /** Saves currently reserved (captured or capturing, not yet saved). */+ val pending: Int get() = inFlight.get()++ /** Claims a slot; false (and nothing claimed) when [capacity] saves are already pending. */+ fun tryReserve(): Boolean {+ while (true) {+ val current = inFlight.get()+ if (current >= capacity) return false+ if (inFlight.compareAndSet(current, current + 1)) return true+ }+ }++ /** Returns a slot claimed by [tryReserve]. Never drops below zero. */+ fun release() {+ inFlight.updateAndGet { (it - 1).coerceAtLeast(0) }+ }+}
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 9675f8de00..3d8518c694 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -238,6 +238,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( // Show a plain black fill (no debug text) so the switch reads as instant. Box(modifier = previewModifier.background(Color.Black)) }+ CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp))) CameraPreviewOverlays( gridEnabled = state.gridEnabled,
camera/src/main/java/com/vayunmathur/camera/ui/CaptureFlashOverlay.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CaptureFlashOverlay.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CaptureFlashOverlay.ktnew file mode 100644index 0000000000..ffa6b7c028--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CaptureFlashOverlay.kt@@ -0,0 +1,44 @@+package com.vayunmathur.camera.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayer+import com.vayunmathur.library.ui.animatedFloat+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.collectLatest++/** How long the viewfinder stays dimmed after the sensor starts exposing a still. */+private const val FLASH_HOLD_MS = 60L++/** Peak opacity of the black capture dim over the viewfinder. */+private const val FLASH_ALPHA = 0.6f++/**+ * Briefly dims the viewfinder each time [captureEvents] fires (CameraX onCaptureStarted), the+ * stock-camera cue that the picture was taken at that moment. The shutter no longer stays+ * pressed until the Motion Photo clip is saved (#914), so this is the "got it" signal.+ */+@Composable+internal fun CaptureFlashOverlay(captureEvents: Flow<Unit>, modifier: Modifier = Modifier) {+ var dimmed by remember { mutableStateOf(false) }+ LaunchedEffect(captureEvents) {+ captureEvents.collectLatest {+ dimmed = true+ delay(FLASH_HOLD_MS)+ dimmed = false+ }+ }+ val alpha = animatedFloat(if (dimmed) FLASH_ALPHA else 0f)+ if (alpha > 0f) {+ Box(modifier.graphicsLayer { this.alpha = alpha }.background(Color.Black))+ }+}
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 91ebfd91b3..d36d7fcb18 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoCapture.kt@@ -8,9 +8,9 @@ import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope-import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext+import kotlinx.coroutines.sync.withLock import kotlin.math.roundToInt /** Shutter-timer countdown tick (1s). */@@ -42,30 +42,59 @@ fun CameraViewModel.takePhoto() { internal fun CameraViewModel.capturePhoto() { if (imageCapture == null || isCapturingMutable.value || burstActiveMutable.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.+ // can't start a concurrent capture. Every path clears it once its frame is captured+ // (Motion Photo) or saved (the other paths) — never later. isCapturingMutable.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- // produce the multi-frame night image.- nightPreviewActiveMutable.value -> captureSinglePhoto()- // Multi-frame night capture only when night mode is active, exposure is fully auto,- // and flash is off: the night paths lock AE off (CONTROL_AE_MODE_OFF) with a forced- // long exposure, which breaks flash metering/timing and double-exposes (issue #721).- // With flash on, fall through to the plain single capture so the shot is an instant- // flash photo with no long-exposure countdown overlay.- nightModeActive.value && isExposureAuto() && flashModeMutable.value == FlashMode.OFF -> captureNightPhoto()- // Motion Photo for plain PHOTO captures (no warmth/shadows bake, not capturing for a- // caller). Only at the native 4:3 ratio: the motion still is saved as raw JPEG bytes- // (to preserve the Ultra HDR gain map + motion trailer), which can't carry CameraX's- // crop. For other ratios fall through to the single-shot path, which saves a cropped JPEG.- cameraModeMutable.value == CameraMode.PHOTO && !captureForResult &&- warmthMutable.value == 0f && shadowsMutable.value == 0f &&- aspectRatioMutable.value == AspectRatioOption.RATIO_4_3 -> captureMotionPhoto()- else -> captureSinglePhoto()+ when (routeStillCapture()) {+ StillRoute.NIGHT -> captureNightPhoto()+ StillRoute.MOTION_PHOTO -> captureMotionPhoto()+ StillRoute.SINGLE -> captureSinglePhoto() } } +/** Which capture path a shutter press takes; chosen by [routeStillCapture]. */+internal enum class StillRoute { SINGLE, NIGHT, MOTION_PHOTO }++/**+ * Picks the capture path for a shutter press. Choosing [StillRoute.MOTION_PHOTO] reserves a+ * [CameraViewModel.motionSaveQueue] slot, which the Motion Photo path releases once its save+ * lands; with every slot taken by earlier shots still encoding, the press takes a plain still+ * instead of waiting (#914).+ */+internal fun CameraViewModel.routeStillCapture(): StillRoute = 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+ // produce the multi-frame night image.+ nightPreviewActiveMutable.value -> StillRoute.SINGLE+ // Multi-frame night capture only when night mode is active, exposure is fully auto,+ // and flash is off: the night paths lock AE off (CONTROL_AE_MODE_OFF) with a forced+ // long exposure, which breaks flash metering/timing and double-exposes (issue #721).+ // With flash on, fall through to the plain single capture so the shot is an instant+ // flash photo with no long-exposure countdown overlay.+ nightModeActive.value && isExposureAuto() && flashModeMutable.value == FlashMode.OFF -> StillRoute.NIGHT+ !motionPhotoEligible() -> StillRoute.SINGLE+ motionSaveQueue.tryReserve() -> StillRoute.MOTION_PHOTO+ else -> {+ Log.status(+ "CameraViewModel",+ "${motionSaveQueue.pending} Motion Photos still saving; taking a plain still instead"+ )+ StillRoute.SINGLE+ }+}++/**+ * Motion Photo for plain PHOTO captures (no warmth/shadows bake, not capturing for a caller).+ * Only at the native 4:3 ratio: the motion still is saved as raw JPEG bytes (to preserve the+ * Ultra HDR gain map + motion trailer), which can't carry CameraX's crop. For other ratios the+ * single-shot path saves a cropped JPEG.+ */+private fun CameraViewModel.motionPhotoEligible(): Boolean {+ val plainPhoto = cameraModeMutable.value == CameraMode.PHOTO && !captureForResult+ val noBake = warmthMutable.value == 0f && shadowsMutable.value == 0f+ return plainPhoto && noBake && aspectRatioMutable.value == AspectRatioOption.RATIO_4_3+}+ /** * Starts a press-and-hold burst: standard single-frame captures fired back-to-back (one in * flight at a time) with `IMG_<ts>_BURSTn` names, until [stopBurst] or [CameraViewModel.BURST_MAX]@@ -159,19 +188,52 @@ internal fun CameraViewModel.clearMotionFrames() = synchronized(motionLock) { motionFrames.clear() } +/**+ * A captured Motion Photo still waiting for its clip: the JPEG bytes, the ring-buffer frames+ * drained at capture time (owned by the request and recycled once the save finishes), and the+ * capture-time orientation, mirroring and file name, so a camera flip or a later shot while+ * this one waits in the queue can't change how it is saved.+ */+internal class MotionSaveRequest(+ val jpegBytes: ByteArray,+ val frames: List<CameraViewModel.MotionFrame>,+ val rotationDegrees: Int,+ val mirrored: Boolean,+ val displayName: String+)+ /** * Captures a Motion Photo: the still (captured in-memory so its bytes can carry the trailer) plus * the buffered ring-buffer frames encoded to a short MP4 and appended as a Google Motion Photo * trailer. Falls back to saving the plain still if no frames are buffered or encoding fails. * The still may be Ultra HDR (gain map preserved); the appended clip is SDR at analysis resolution.+ *+ * The caller ([routeStillCapture]) has already reserved a [CameraViewModel.motionSaveQueue] slot.+ * The shutter is released as soon as the still is in memory; the clip is built and saved in the+ * background by [onMotionStillCaptured] (#914). */ internal fun CameraViewModel.captureMotionPhoto() {- val capture = imageCapture ?: return+ val capture = imageCapture ?: run {+ motionSaveQueue.release()+ isCapturingMutable.value = false+ return+ } isCapturingMutable.value = true+ // Name, mirroring and orientation are fixed at the shutter press, not when the save runs.+ val displayName = "IMG_${MediaStoreSaver.timestamp()}.jpg"+ val mirrored = mirrorCaptures capture.takePicture( ContextCompat.getMainExecutor(app), object : ImageCapture.OnImageCapturedCallback() {+ private var feedbackSent = false++ override fun onCaptureStarted() {+ feedbackSent = true+ emitShutterFeedback()+ }+ override fun onCaptureSuccess(image: ImageProxy) {+ if (!feedbackSent) emitShutterFeedback() val degrees = image.imageInfo.rotationDegrees val jpegBytes = try { image.planes[0].buffer.let { buf ->@@ -180,18 +242,14 @@ internal fun CameraViewModel.captureMotionPhoto() { } finally { image.close() }- val frames = drainMotionFrames()- viewModelScope.launch {- val uri = withContext(Dispatchers.Default) {- assembleAndSaveMotionPhoto(jpegBytes, frames, degrees)- }- frames.forEach { it.bitmap.recycle() }- isCapturingMutable.value = false- if (uri != null) setLastCaptureUri(uri)- }+ onMotionStillCaptured(+ MotionSaveRequest(jpegBytes, drainMotionFrames(), degrees, mirrored, displayName)+ ) }+ override fun onError(exception: ImageCaptureException) { Log.error("CameraViewModel", "Motion Photo capture failed; falling back to still", exception)+ motionSaveQueue.release() isCapturingMutable.value = false captureSinglePhoto() }@@ -199,16 +257,37 @@ internal fun CameraViewModel.captureMotionPhoto() { ) } -internal fun CameraViewModel.assembleAndSaveMotionPhoto(- jpegBytes: ByteArray,- frames: List<CameraViewModel.MotionFrame>,- degrees: Int-): Uri? {- val name = "IMG_${MediaStoreSaver.timestamp()}.jpg"+/**+ * The Motion Photo still is in memory: release the shutter now and finish the clip in the+ * background. Saves run on [CameraViewModel.motionSaveDispatcher] one at a time, in shot order+ * (the mutex is fair), inside [CameraViewModel.motionSaveScope], which outlives the screen so+ * a shot taken just before leaving still lands. The thumbnail updates when each save lands.+ */+internal fun CameraViewModel.onMotionStillCaptured(request: MotionSaveRequest): Job {+ isCapturingMutable.value = false+ return motionSaveScope.launch(motionSaveDispatcher) {+ val uri = try {+ motionSaveMutex.withLock { motionPhotoSaver(request) }+ } finally {+ request.frames.forEach { it.bitmap.recycle() }+ motionSaveQueue.release()+ }+ if (uri != null) setLastCaptureUri(uri)+ }+}++/** Signals the UI that the sensor started (or finished) exposing a still. */+internal fun CameraViewModel.emitShutterFeedback() {+ shutterFeedbackMutable.tryEmit(Unit)+}++/** Builds the clip for [request], appends it to the still and saves it. Blocking: call off main. */+internal fun CameraViewModel.assembleAndSaveMotionPhoto(request: MotionSaveRequest): Uri? {+ val frames = request.frames // 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, mirrorCaptures)+ val stillBytes = stampStillBytes(request.jpegBytes, request.rotationDegrees, request.mirrored) // 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@@ -234,7 +313,7 @@ internal fun CameraViewModel.assembleAndSaveMotionPhoto( } else { stillBytes }- return saveStillBytes(name, bytes)+ return saveStillBytes(request.displayName, bytes) } /**
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 601fd7b832..251d0fe6dc 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSingleCapture.kt@@ -4,7 +4,9 @@ import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Rect import android.net.Uri+import androidx.annotation.OptIn import com.vayunmathur.library.log.Log+import androidx.camera.camera2.interop.ExperimentalCamera2Interop import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy@@ -35,6 +37,7 @@ internal fun CameraViewModel.captureSinglePhoto() { /** Everything doCapture/runSingleCapture needs, resolved up front. */ @Suppress("DEPRECATION")+@OptIn(ExperimentalCamera2Interop::class) private data class SingleCapturePlan( val capture: ImageCapture, val pending: PendingStill,@@ -55,6 +58,7 @@ private data class SingleCapturePlan( * Null when there is no save target (caller clears the in-flight flag). */ @Suppress("DEPRECATION")+@OptIn(ExperimentalCamera2Interop::class) private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): SingleCapturePlan? { val capture = imageCapture ?: return null val outputOptions = pending.outputOptions@@ -103,6 +107,7 @@ private fun CameraViewModel.buildSingleCapturePlan(pending: PendingStill): Singl /** Applies the transient night exposure, then runs the capture (or the capture directly). */ @Suppress("DEPRECATION")+@OptIn(ExperimentalCamera2Interop::class) private fun CameraViewModel.applyNightExposureThen(plan: SingleCapturePlan, doCapture: (SingleCapturePlan) -> Unit) { try { val options = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()@@ -159,6 +164,9 @@ private fun CameraViewModel.runSingleCapture(plan: SingleCapturePlan) { plan.outputOptions, ContextCompat.getMainExecutor(app), object : ImageCapture.OnImageSavedCallback {+ override fun onCaptureStarted() {+ emitShutterFeedback()+ } override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { finishCapture(plan.pending.resolveUri(outputFileResults)) }@@ -185,6 +193,9 @@ private fun CameraViewModel.captureProcessedSingle( plan.capture.takePicture( ContextCompat.getMainExecutor(app), object : ImageCapture.OnImageCapturedCallback() {+ override fun onCaptureStarted() {+ emitShutterFeedback()+ } override fun onCaptureSuccess(image: ImageProxy) { val degrees = image.imageInfo.rotationDegrees // cropRect reflects setCropAspectRatio; apply it to the decoded bitmap
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 a846de10b0..91607a0cfd 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -11,6 +11,7 @@ import android.location.Location import android.net.Uri import com.vayunmathur.library.log.Log import androidx.camera.core.CameraSelector+import com.vayunmathur.camera.domain.MotionSaveQueue import androidx.camera.core.Camera import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageCapture@@ -27,6 +28,12 @@ import androidx.exifinterface.media.ExifInterface import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.CoroutineExceptionHandler+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow@@ -34,9 +41,15 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex import kotlin.math.atan2 +/**+ * State and session owner for the single camera screen: the bound CameraX session, every+ * capture setting, and the capture paths (implemented as extensions in the sibling files).+ */ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {+ /** Tuning constants and lookup tables shared by the extension files. */ companion object { // Companions are public so same-module extension files resolve these constants. @@ -77,6 +90,11 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { const val MOTION_FRAMES_PER_SECOND = 8 const val MOTION_MAX_FRAMES_HARD_CAP = 24 + // Motion Photos still building after their shutter was released (#914). Each holds its+ // drained frames (up to MOTION_MAX_FRAMES_HARD_CAP bitmaps) until encoded, so keep this+ // small: one encoding plus one waiting. A press beyond it takes a plain still.+ const val MAX_PENDING_MOTION_SAVES = 2+ val EXPOSURE_TIME_STOPS = listOf( ExposureTimeStop("Auto", null), ExposureTimeStop("1/4000s", 250_000L),@@ -220,6 +238,24 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val isCapturingMutable = MutableStateFlow(false) val isCapturing = isCapturingMutable.asStateFlow() + // Fires when the sensor starts exposing a still (CameraX onCaptureStarted), so the viewfinder+ // can flash at the real moment of capture instead of when the file lands (#914).+ internal val shutterFeedbackMutable = MutableSharedFlow<Unit>(extraBufferCapacity = 1)+ val shutterFeedback = shutterFeedbackMutable.asSharedFlow()++ // Background Motion Photo saves (#914): the clip is built after the shutter is released.+ // The scope is deliberately not cancelled in onCleared, so a save in progress still lands;+ // the dispatcher and saver are vars only so tests can drive the state machine.+ internal val motionSaveQueue = MotionSaveQueue(MAX_PENDING_MOTION_SAVES)+ internal val motionSaveMutex = Mutex()+ internal val motionSaveScope = CoroutineScope(+ SupervisorJob() + CoroutineExceptionHandler { _, e ->+ Log.error("CameraViewModel", "Background Motion Photo save failed", e)+ }+ )+ internal var motionSaveDispatcher: CoroutineDispatcher = Dispatchers.IO+ internal var motionPhotoSaver: suspend (MotionSaveRequest) -> Uri? = { assembleAndSaveMotionPhoto(it) }+ internal val locationEnabledMutable = MutableStateFlow(false) val locationEnabled = locationEnabledMutable.asStateFlow() @@ -316,9 +352,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { val nightModeActive = combine(lowLightDetectedMutable, nightModeOverriddenOffMutable) { low, off -> low && !off } .stateIn(viewModelScope, SharingStarted.Eagerly, false) - // Whether to offer the vendor NIGHT extension. We optimistically probe with- // isSessionConfigSupported(), but the authoritative signal is the actual bind: if- // setupNightPreviewSession() ever fails on this device, we remember that (persisted, with a+ // Whether to offer the vendor NIGHT extension. We optimistically probe with the+ // isSessionConfigSupported check, but the authoritative signal is the actual bind: if+ // the night preview session ever fails to bind on this device, we remember that (persisted, with a // ~1-week TTL) and stop offering night for a week — so a broken extender (GrapheneOS/Pixel) // makes at most one failed attempt per week instead of engaging/failing in a loop. internal val nightExtensionUsableMutable = MutableStateFlow(false)@@ -469,8 +505,11 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val burstCountMutable = MutableStateFlow(0) val burstCount = burstCountMutable.asStateFlow() - // Motion-Photo ring buffer: the last ~MOTION_WINDOW of analysis frames (RGB copies), fed by the- // PhotoAnalyzer off the shared analysis stream and drained when a Motion Photo is captured.+ /**+ * One Motion-Photo ring-buffer entry: the last ~MOTION_WINDOW of analysis frames (RGB copies),+ * fed by the PhotoAnalyzer off the shared analysis stream and drained when a Motion Photo is+ * captured.+ */ class MotionFrame(val bitmap: Bitmap, val timestampNanos: Long, val rotationDegrees: Int) internal val motionFrames = ArrayDeque<MotionFrame>() internal val motionLock = Any()
camera/src/test/java/com/vayunmathur/camera/domain/MotionSaveQueueTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/MotionSaveQueueTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/MotionSaveQueueTest.ktnew file mode 100644index 0000000000..0d831f7584--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/MotionSaveQueueTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class MotionSaveQueueTest {++ @Test+ fun reservesUpToCapacityThenRefuses() {+ val q = MotionSaveQueue(2)+ assertTrue(q.tryReserve())+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ assertEquals(2, q.pending)+ }++ @Test+ fun releaseFreesASlot() {+ val q = MotionSaveQueue(1)+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ q.release()+ assertEquals(0, q.pending)+ assertTrue(q.tryReserve())+ }++ @Test+ fun extraReleaseNeverGoesNegative() {+ val q = MotionSaveQueue(1)+ q.release()+ assertEquals(0, q.pending)+ assertTrue(q.tryReserve())+ assertFalse(q.tryReserve())+ }++ @Test+ fun concurrentReservationsNeverExceedCapacity() {+ val q = MotionSaveQueue(3)+ val granted = java.util.concurrent.atomic.AtomicInteger()+ val threads = List(16) {+ Thread { repeat(100) { if (q.tryReserve()) granted.incrementAndGet() } }+ }+ threads.forEach { it.start() }+ threads.forEach { it.join() }+ assertEquals(3, granted.get())+ assertEquals(3, q.pending)+ }++ @Test+ fun rejectsNonPositiveCapacity() {+ assertFailsWith<IllegalArgumentException> { MotionSaveQueue(0) }+ }+}
camera/src/test/java/com/vayunmathur/camera/util/MotionPhotoCaptureStateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/util/MotionPhotoCaptureStateTest.kt b/camera/src/test/java/com/vayunmathur/camera/util/MotionPhotoCaptureStateTest.ktnew file mode 100644index 0000000000..f2b6409021--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/util/MotionPhotoCaptureStateTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.camera.util++import android.graphics.Bitmap+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.TestCoroutineScheduler+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Capture state machine for background Motion Photo saves (#914): the shutter is released when+ * the still is captured, not when its clip is saved; saves run in shot order; frames are freed+ * only after their save; and with the save queue full a press falls back to a plain still.+ * No CameraX binding: the capture callback's hand-off ([onMotionStillCaptured]) and the router+ * ([routeStillCapture]) are driven directly.+ */+@RunWith(AndroidJUnit4::class)+class MotionPhotoCaptureStateTest {++ private val scheduler = TestCoroutineScheduler()++ private fun vm() = CameraViewModel(ApplicationProvider.getApplicationContext()).apply {+ motionSaveDispatcher = StandardTestDispatcher(scheduler)+ }++ private fun request(name: String, frameCount: Int = 2) = MotionSaveRequest(+ jpegBytes = byteArrayOf(1, 2, 3),+ frames = List(frameCount) { i ->+ CameraViewModel.MotionFrame(Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888), i * 1_000L, 90)+ },+ rotationDegrees = 90,+ mirrored = false,+ displayName = name+ )++ private fun uri(name: String): Uri = Uri.parse("content://media/external/images/media/$name")++ @Test+ fun defaultPhotoShotRoutesToMotionPhotoAndReservesASlot() {+ val v = vm()+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ assertEquals(1, v.motionSaveQueue.pending)+ }++ @Test+ fun inFlightReleasedOnCaptureNotOnSave() {+ val v = vm()+ val gate = CompletableDeferred<Uri?>()+ v.motionPhotoSaver = { gate.await() }+ v.isCapturingMutable.value = true+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ val req = request("a")++ v.onMotionStillCaptured(req)++ // Captured: the shutter is free immediately, while the save hasn't even started.+ assertFalse(v.isCapturing.value)+ scheduler.advanceUntilIdle()+ // Saving (blocked on the gate): still free, slot still held, frames still alive.+ assertFalse(v.isCapturing.value)+ assertEquals(1, v.motionSaveQueue.pending)+ assertNull(v.lastCaptureUri.value)+ assertFalse(req.frames.any { it.bitmap.isRecycled })++ gate.complete(uri("a"))+ scheduler.advanceUntilIdle()+ // Saved: thumbnail source updated, slot returned, frames freed.+ assertEquals(uri("a"), v.lastCaptureUri.value)+ assertEquals(0, v.motionSaveQueue.pending)+ assertTrue(req.frames.all { it.bitmap.isRecycled })+ }++ @Test+ fun nextShotAllowedWhileEarlierSaveRuns() {+ val v = vm()+ val gate = CompletableDeferred<Uri?>()+ v.motionPhotoSaver = { gate.await() }+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ v.onMotionStillCaptured(request("a"))+ scheduler.advanceUntilIdle()++ // Second press while the first clip is still encoding: another Motion Photo.+ assertFalse(v.isCapturing.value)+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ assertEquals(2, v.motionSaveQueue.pending)+ }++ @Test+ fun queueFullFallsBackToPlainStill() {+ val v = vm()+ repeat(CameraViewModel.MAX_PENDING_MOTION_SAVES) {+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ }+ // Every slot is held by a shot still saving: this press must not block or queue more+ // frames, it takes a plain still and leaves the queue as it was.+ assertEquals(StillRoute.SINGLE, v.routeStillCapture())+ assertEquals(CameraViewModel.MAX_PENDING_MOTION_SAVES, v.motionSaveQueue.pending)++ // Once a save lands, the next press is a Motion Photo again.+ v.motionPhotoSaver = { uri("x") }+ v.onMotionStillCaptured(request("x"))+ scheduler.advanceUntilIdle()+ assertEquals(StillRoute.MOTION_PHOTO, v.routeStillCapture())+ }++ @Test+ fun savesLandInShotOrderEvenWhenTheFirstIsSlower() {+ val v = vm()+ val firstGate = CompletableDeferred<Unit>()+ val finished = mutableListOf<String>()+ v.motionPhotoSaver = { req ->+ if (req.displayName == "first") firstGate.await()+ finished += req.displayName+ uri(req.displayName)+ }+ repeat(2) { v.routeStillCapture() }+ v.onMotionStillCaptured(request("first"))+ v.onMotionStillCaptured(request("second"))+ scheduler.advanceUntilIdle()+ assertTrue(finished.isEmpty(), "second must wait for first, got $finished")+ assertNull(v.lastCaptureUri.value)++ firstGate.complete(Unit)+ scheduler.advanceUntilIdle()+ assertEquals(listOf("first", "second"), finished)+ assertEquals(uri("second"), v.lastCaptureUri.value)+ assertEquals(0, v.motionSaveQueue.pending)+ }++ @Test+ fun failedSaveStillReleasesSlotAndFrames() {+ val v = vm()+ v.motionPhotoSaver = { error("encoder blew up") }+ v.routeStillCapture()+ val req = request("boom")+ v.onMotionStillCaptured(req)+ scheduler.advanceUntilIdle()+ assertEquals(0, v.motionSaveQueue.pending)+ assertTrue(req.frames.all { it.bitmap.isRecycled })+ assertNull(v.lastCaptureUri.value)+ assertFalse(v.isCapturing.value)+ }++ @Test+ fun nonMotionModesDoNotTouchTheQueue() {+ val v = vm()+ v.aspectRatioMutable.value = AspectRatioOption.RATIO_16_9+ assertEquals(StillRoute.SINGLE, v.routeStillCapture())+ v.aspectRatioMutable.value = AspectRatioOption.RATIO_4_3+ v.warmthMutable.value = 0.5f+ assertEquals(StillRoute.SINGLE, v.routeStillCapture())+ assertEquals(0, v.motionSaveQueue.pending)+ }+}