camera: stills on the Camera2 session (Phase 4a)
- Commit
b61409a8b37ca9882a5ec973aa6dc94470cd052e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 17:54 UTC (14 days ago)
- Parents
1997090
The Camera2 session gains a JPEG ImageReader output: capture() issues TEMPLATE_STILL_CAPTURE carrying the live control state (zoom/torch/EV/metering, flash mapped to real AE/flash keys; screen-flash flagged since no HAL key exists), pairs JPEG bytes with CaptureResult metadata, and saves through the existing pipeline - same orientation stamping, GPS, SAF/MediaStore routing and AVIF/JPEG choice, no fork. Policy keeps night, processed/bokeh, Motion Photo, burst and other modes on CameraX; RAW/ZSL/reprocess are later phases. A latent race the tests exposed (control state mutated on the caller thread) now mutates on the executor. Verified: full camera suite 688 green incl. 12 new stills tests. Device remainder: HAL preview+JPEG combos, flash firing, screen-flash lighting on this path (flagged, not yet triggered), rotation updates mid-session.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktnew file mode 100644index 0000000000..8c61dbf299--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -0,0 +1,136 @@+package com.vayunmathur.camera.platform++import android.graphics.BitmapFactory+import android.net.Uri+import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.MediaStoreSaver+import com.vayunmathur.camera.data.saveProcessedStill+import com.vayunmathur.camera.data.saveStillBytes+import com.vayunmathur.camera.data.setLastCaptureUri+import com.vayunmathur.camera.domain.FlashSetting+import com.vayunmathur.camera.domain.StillFormat+import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.CapturedStill+import com.vayunmathur.camera.platform.camera2.StillEngineInput+import com.vayunmathur.camera.platform.camera2.StillEnginePolicy+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Camera2 migration Phase 4a: still-capture glue between the gated+ * [Camera2Session] and the existing save pipeline.+ *+ * Reuse, not fork: a Camera2 still lands through exactly the helpers the+ * CameraX in-memory paths already use — [stampStillBytes] stamps the+ * orientation (from the mapped `CaptureResult`/sensor rotation, via the+ * same `rawStillOrientationString` the Motion Photo path uses) plus GPS+ * into the HAL JPEG, [saveStillBytes] routes it to SAF/MediaStore, and+ * when AVIF is the chosen format the bytes are decoded once and encoded+ * through `StillEncoder` via [saveProcessedStill] (which owns the+ * AVIF/JPEG choice and its JPEG fallback), with `writeCaptureExif`+ * restoring the EXIF the JPEG re-encode dropped.+ *+ * Everything [StillEnginePolicy] excludes (night, processed/bokeh,+ * Motion Photo, burst, capture-for-result, non-PHOTO modes) never reaches+ * this file: [tryCaptureCamera2Still] returns false and the CameraX+ * router runs exactly as before.+ */++/** Registers the live gated Camera2 session (null when it leaves composition). */+internal fun CameraViewModel.registerCamera2Session(session: Camera2Session?) {+ activeCamera2Session = session+}++private fun FlashMode.toFlashSetting(): FlashSetting = when (this) {+ FlashMode.ON -> FlashSetting.ON+ FlashMode.OFF -> FlashSetting.OFF+ FlashMode.AUTO -> FlashSetting.AUTO+}++/**+ * Attempts the shutter press on Camera2. Returns true when Camera2 took+ * the shot (the caller must not also route it to CameraX); false means+ * the shot is CameraX's, for a policy reason or because no gated session+ * is live. The caller ([capturePhoto]) has already claimed the in-flight+ * flag; every outcome here clears it.+ */+internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean {+ val session = activeCamera2Session ?: return false+ val input = StillEngineInput(+ camera2Enabled = camera2PreviewEnabledMutable.value,+ mode = cameraModeMutable.value,+ hasJpegOutput = session.hasJpegOutput,+ nightRoute = nightPreviewActiveMutable.value || nightCaptureApplies(),+ processedRoute = warmthMutable.value != 0f || shadowsMutable.value != 0f,+ // Mirrors the (private) Motion Photo eligibility in CameraPhotoCapture:+ // a plain 4:3 PHOTO shot with no bake would route to Motion Photo.+ motionPhotoRoute = cameraModeMutable.value == CameraMode.PHOTO &&+ !captureForResult &&+ warmthMutable.value == 0f && shadowsMutable.value == 0f &&+ aspectRatioMutable.value == AspectRatioOption.RATIO_4_3,+ captureForResult = captureForResult,+ burst = burstActiveMutable.value,+ )+ if (!StillEnginePolicy.usesCamera2(input)) return false++ // Flash setting is the one control the preview effects do not push;+ // zoom/torch/EV/metering already live on the session.+ session.setFlashSetting(flashModeMutable.value.toFlashSetting())+ val mirrored = mirrorCaptures+ emitShutterFeedback()+ session.capture(+ mirrored = mirrored,+ callback = object : Camera2Session.StillCallback {+ override fun onStillCaptured(still: CapturedStill) {+ viewModelScope.launch {+ val uri = withContext(Dispatchers.IO) {+ runCatching { saveCamera2Still(still) }+ .onFailure { Log.error("Camera2Still", "save failed", it) }+ .getOrNull()+ }+ isCapturingMutable.value = false+ if (uri != null) setLastCaptureUri(uri)+ }+ }++ override fun onStillFailed(message: String) {+ Log.status("Camera2Still", "capture failed: $message")+ isCapturingMutable.value = false+ }+ },+ )+ return true+}++/** Saves one Camera2 still through the shared routing. Blocking: call off main. */+private fun CameraViewModel.saveCamera2Still(still: CapturedStill): Uri? {+ val rotation = still.metadata.rotationDegrees+ if (photoFormatMutable.value == PhotoFormat.AVIF) {+ val bitmap = BitmapFactory.decodeByteArray(still.jpegBytes, 0, still.jpegBytes.size)+ ?: return saveJpegStill(still)+ try {+ val saved = saveProcessedStill(bitmap, rotation) ?: return null+ if (saved.format == StillFormat.JPEG) {+ // The JPEG re-encode dropped the HAL EXIF; restore it from+ // the original frame, exactly as the processed CameraX path.+ writeCaptureExif(+ saved.uri, still.jpegBytes, rotation, mirrored = still.metadata.mirrored,+ )+ }+ return saved.uri+ } finally {+ bitmap.recycle()+ }+ }+ return saveJpegStill(still)+}++/** The plain JPEG landing: stamp orientation/GPS, then route to SAF/MediaStore. */+private fun CameraViewModel.saveJpegStill(still: CapturedStill): Uri? {+ val stamped = stampStillBytes(+ still.jpegBytes, still.metadata.rotationDegrees, still.metadata.mirrored,+ )+ return saveStillBytes("IMG_${MediaStoreSaver.timestamp()}.jpg", stamped)+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex c5fff405b2..9f39db0548 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -94,7 +94,18 @@ fun CameraViewModel.takePhoto() { } internal fun CameraViewModel.capturePhoto() {- if (imageCapture == null || isCapturingMutable.value || burstActiveMutable.value) return+ if (isCapturingMutable.value || burstActiveMutable.value) return+ // Phase 4a: a gated Camera2 session takes plain PHOTO stills itself+ // (StillEnginePolicy excludes night/processed/Motion/burst/result+ // shots, which fall through to the CameraX routing below unchanged).+ // This runs before the imageCapture check: with the gate on, CameraX+ // may not be bound at all.+ if (activeCamera2Session != null) {+ isCapturingMutable.value = true+ if (tryCaptureCamera2Still()) return+ isCapturingMutable.value = false+ }+ if (imageCapture == null) return // Claim in-flight synchronously so a second shutter tap (or a stacked timer firing) // can't start a concurrent capture. Every path clears it once its frame is captured // (Motion Photo) or saved (the other paths) — never later.
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.ktindex 9a96c83658..ecd6840bd1 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -170,6 +170,15 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { camera2PreviewEnabledMutable.value = enabled } + /**+ * The live Camera2 session while the gated preview is composed+ * (Phase 4a stills), registered by `Camera2Preview`; null otherwise.+ * The shutter glue reads it synchronously — it is only ever set/cleared+ * on the main thread from composition effects.+ */+ internal var activeCamera2Session:+ com.vayunmathur.camera.platform.camera2.Camera2Session? = null+ internal val cameraModeMutable = MutableStateFlow(CameraMode.PHOTO) val cameraMode = cameraModeMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.ktindex b11ce400bf..7e5668cfa9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt@@ -1,6 +1,7 @@ package com.vayunmathur.camera.platform.camera2 import android.hardware.camera2.CameraMetadata+import com.vayunmathur.camera.domain.FlashSetting import kotlin.math.roundToInt /**@@ -21,6 +22,8 @@ data class Camera2ControlState( val exposureCompEv: Float = 0f, val afRegion: MeteringRegion? = null, val aeRegion: MeteringRegion? = null,+ /** User still-flash setting; preview ignores it, stills resolve it. */+ val flashSetting: FlashSetting = FlashSetting.OFF, ) { companion object { val DEFAULT = Camera2ControlState()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex 528b92aa01..11a2a927c6 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -7,6 +7,8 @@ import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraDevice import android.hardware.camera2.CameraManager import android.hardware.camera2.CaptureRequest+import android.hardware.camera2.CaptureResult+import android.hardware.camera2.TotalCaptureResult import android.hardware.camera2.params.MeteringRectangle import android.hardware.camera2.params.OutputConfiguration import android.hardware.camera2.params.SessionConfiguration@@ -53,16 +55,33 @@ interface DeviceHandle { fun close() } +/** Callbacks for one [CaptureSessionHandle.captureStill] call. */+interface StillResultCallback {+ fun onCompleted(metadata: RawStillMetadata)+ fun onFailed(message: String)+}+ /** Testable handle over a `CameraCaptureSession`. */ interface CaptureSessionHandle { /** Issues [params] as the TEMPLATE_PREVIEW repeating request on [target]. */ fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface)++ /**+ * Issues [params] as one TEMPLATE_STILL_CAPTURE request on [stillTarget]+ * (preview target stays in the session, not in this request). The JPEG+ * bytes arrive separately via the [StillOutput] listener; [callback]+ * carries the `CaptureResult` metadata for the same frame.+ */+ fun captureStill(params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback) fun close() } /** Opens cameras; the session owns the returned handles' lifecycle. */ interface Camera2Driver { fun openCamera(cameraId: String, callback: DeviceCallback)++ /** Creates the JPEG still output for [size], or null when unavailable. */+ fun createStillOutput(size: FrameSize): StillOutput? } /** Converts a pure [SensorRect] into the HAL's `Rect`. */@@ -110,6 +129,56 @@ internal fun CaptureRequest.Builder.applyPreviewParams( } } +/** Applies resolved still controls onto a TEMPLATE_STILL_CAPTURE builder. */+internal fun CaptureRequest.Builder.applyStillParams(+ params: ResolvedStillParams,+ target: Surface,+) {+ addTarget(target)+ set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)+ set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)+ set(CaptureRequest.CONTROL_AE_MODE, params.aeMode)+ if (params.zoomRatio != null) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ set(CaptureRequest.CONTROL_ZOOM_RATIO, params.zoomRatio)+ } else if (params.cropRegion != null) {+ set(CaptureRequest.SCALER_CROP_REGION, params.cropRegion.toRect())+ }+ } else if (params.cropRegion != null) {+ set(CaptureRequest.SCALER_CROP_REGION, params.cropRegion.toRect())+ }+ set(CaptureRequest.FLASH_MODE, params.flashMode)+ set(+ CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION,+ params.aeExposureCompensationSteps,+ )+ set(CaptureRequest.JPEG_ORIENTATION, params.jpegOrientationDegrees)+ if (params.afRegions.isNotEmpty()) {+ set(+ CaptureRequest.CONTROL_AF_REGIONS,+ params.afRegions.map { it.toMeteringRectangle() }.toTypedArray(),+ )+ }+ if (params.aeRegions.isNotEmpty()) {+ set(+ CaptureRequest.CONTROL_AE_REGIONS,+ params.aeRegions.map { it.toMeteringRectangle() }.toTypedArray(),+ )+ }+}++/** Extracts the pure metadata shape from a completed capture result. */+internal fun TotalCaptureResult.toRawStillMetadata(): RawStillMetadata = RawStillMetadata(+ sensorTimestampNs = get(CaptureResult.SENSOR_TIMESTAMP),+ exposureTimeNs = get(CaptureResult.SENSOR_EXPOSURE_TIME),+ iso = get(CaptureResult.SENSOR_SENSITIVITY),+ focalLengthMm = get(CaptureResult.LENS_FOCAL_LENGTH),+ frameNumber = frameNumber,+ aeState = get(CaptureResult.CONTROL_AE_STATE),+ afState = get(CaptureResult.CONTROL_AF_STATE),+ flashState = get(CaptureResult.FLASH_STATE),+)+ /** * Real driver over [CameraManager]. Constructed with the session executor's * handler so every HAL callback lands on the camera thread.@@ -124,6 +193,9 @@ class AndroidCamera2Driver( handler, ) + override fun createStillOutput(size: FrameSize): StillOutput? =+ runCatching { JpegStillOutput(size.width, size.height, handler = handler) }.getOrNull()+ @SuppressLint("MissingPermission") override fun openCamera(cameraId: String, callback: DeviceCallback) { manager.openCamera(@@ -162,7 +234,7 @@ private class AndroidDeviceHandle( ) { val stateCallback = object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) =- callback.onConfigured(AndroidCaptureSessionHandle(device, session))+ callback.onConfigured(AndroidCaptureSessionHandle(device, session, handler)) override fun onConfigureFailed(session: CameraCaptureSession) = callback.onConfigureFailed()@@ -190,12 +262,43 @@ private class AndroidDeviceHandle( private class AndroidCaptureSessionHandle( private val device: CameraDevice, private val session: CameraCaptureSession,+ private val handler: Handler, ) : CaptureSessionHandle { override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) { val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW) builder.applyPreviewParams(params, target)- session.setRepeatingRequest(builder.build(), null, null)+ session.setRepeatingRequest(builder.build(), null, handler)+ }++ override fun captureStill(+ params: ResolvedStillParams,+ stillTarget: Surface,+ callback: StillResultCallback,+ ) {+ val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE)+ builder.applyStillParams(params, stillTarget)+ session.capture(+ builder.build(),+ object : CameraCaptureSession.CaptureCallback() {+ override fun onCaptureCompleted(+ session: CameraCaptureSession,+ request: CaptureRequest,+ result: TotalCaptureResult,+ ) {+ callback.onCompleted(result.toRawStillMetadata())+ }++ override fun onCaptureFailed(+ session: CameraCaptureSession,+ request: CaptureRequest,+ failure: android.hardware.camera2.CaptureFailure,+ ) {+ callback.onFailed("capture failed (reason ${failure.reason})")+ }+ },+ handler,+ ) } override fun close() = session.close()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex 3ac4da380a..582f3b6eab 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -8,6 +8,10 @@ import android.view.Surface * output is the [PreviewSurfaceBridge] surface, and streams a * TEMPLATE_PREVIEW repeating request carrying the resolved controls. *+ * Phase 4a adds a JPEG `ImageReader` as a second output (when the lens+ * reports JPEG sizes) and [capture] for plain single stills; see+ * [StillCapturePlanner] and [StillEnginePolicy].+ * * Threading: every public method posts onto the executor; every driver * callback arrives on the executor and is generation-checked through * [SessionStateMachine] before it may touch session state, so a callback@@ -36,6 +40,12 @@ class Camera2Session( fun onStreaming(previewSize: FrameSize) {} } + /** One-shot still outcome; fires on the executor thread. */+ interface StillCallback {+ fun onStillCaptured(still: CapturedStill)+ fun onStillFailed(message: String)+ }+ val state: SessionState get() = stateMachine.state val generation: Long get() = stateMachine.generation @@ -43,8 +53,22 @@ class Camera2Session( private var captureSession: CaptureSessionHandle? = null private var previewSurface: Surface? = null private var previewSize: FrameSize? = null+ private var stillOutput: StillOutput? = null+ private var stillSize: FrameSize? = null+ private var pendingStill: PendingStill? = null+ private var displayRotationDegrees: Int = 0 private var controls: Camera2ControlState = Camera2ControlState.DEFAULT + /** In-flight still: JPEG bytes and result metadata pair up by arrival. */+ private class PendingStill(+ val params: ResolvedStillParams,+ val callback: StillCallback,+ var rawMetadata: RawStillMetadata? = null,+ var jpegBytes: ByteArray? = null,+ var jpegWidth: Int = 0,+ var jpegHeight: Int = 0,+ )+ /** Current control state (user intent, unresolved). */ val controlState: Camera2ControlState get() = controls @@ -89,13 +113,30 @@ class Camera2Session( } /** Applies a zoom ratio (control-bar / pinch), keeping other controls. */- fun setZoomRatio(ratio: Float) = updateControls(controls.copy(zoomRatio = ratio))+ fun setZoomRatio(ratio: Float) {+ // Mutate on the executor: copying the (executor-owned) state on the+ // caller thread would race with other queued control updates.+ executor.execute {+ controls = controls.copy(zoomRatio = ratio)+ issueRepeatingRequest()+ }+ } /** Applies torch on/off, keeping other controls. */- fun setTorch(on: Boolean) = updateControls(controls.copy(torchOn = on))+ fun setTorch(on: Boolean) {+ executor.execute {+ controls = controls.copy(torchOn = on)+ issueRepeatingRequest()+ }+ } /** Applies exposure compensation in EV stops, keeping other controls. */- fun setExposureCompEv(ev: Float) = updateControls(controls.copy(exposureCompEv = ev))+ fun setExposureCompEv(ev: Float) {+ executor.execute {+ controls = controls.copy(exposureCompEv = ev)+ issueRepeatingRequest()+ }+ } /** * Tap-to-focus: transforms a normalised viewfinder tap into AF + AE@@ -128,7 +169,134 @@ class Camera2Session( } /** Clears tap metering, returning AF/AE to continuous full-frame. */- fun clearMetering() = updateControls(controls.copy(afRegion = null, aeRegion = null))+ fun clearMetering() {+ executor.execute {+ controls = controls.copy(afRegion = null, aeRegion = null)+ issueRepeatingRequest()+ }+ }++ /** Applies the user's still-flash setting, keeping other controls. */+ fun setFlashSetting(setting: com.vayunmathur.camera.domain.FlashSetting) {+ executor.execute {+ controls = controls.copy(flashSetting = setting)+ issueRepeatingRequest()+ }+ }++ /** Records the display rotation still orientations are computed from. */+ fun setDisplayRotationDegrees(degrees: Int) {+ executor.execute { displayRotationDegrees = degrees }+ }++ /** The JPEG still size configured at [open], or null when unavailable. */+ fun currentStillSize(): FrameSize? = stillSize++ /** True when a JPEG output exists (see [StillEnginePolicy]). */+ val hasJpegOutput: Boolean get() = stillOutput != null++ /**+ * Takes one plain still: issues `TEMPLATE_STILL_CAPTURE` carrying the+ * session's current control state plus flash resolution, and delivers+ * the JPEG bytes with mapped `CaptureResult` metadata to [callback]+ * once both halves arrive. Only one still may be in flight; a second+ * call, a non-streaming session, or a session without a JPEG output+ * fails via [StillCallback.onStillFailed] without touching the HAL.+ */+ fun capture(+ callback: StillCallback,+ displayRotationDegrees: Int? = null,+ mirrored: Boolean = false,+ ) {+ executor.execute {+ val session = captureSession+ val output = stillOutput+ when {+ stateMachine.state != SessionState.STREAMING || session == null ->+ callback.onStillFailed("still capture requires a streaming session")+ output == null ->+ callback.onStillFailed("no JPEG output on this session")+ pendingStill != null ->+ callback.onStillFailed("a still capture is already in flight")+ else -> {+ val params = StillCapturePlanner.resolve(+ state = controls,+ snapshot = snapshot,+ displayRotationDegrees = displayRotationDegrees+ ?: [email protected],+ mirrored = mirrored,+ )+ val pending = PendingStill(params, callback)+ pendingStill = pending+ runCatching {+ session.captureStill(params, output.surface, object : StillResultCallback {+ override fun onCompleted(metadata: RawStillMetadata) {+ onStillResult(pending, metadata)+ }++ override fun onFailed(message: String) {+ failPending(pending, message)+ }+ })+ }.onFailure { failPending(pending, "captureStill failed: ${it.message}") }+ }+ }+ }+ }++ private fun onStillResult(pending: PendingStill, metadata: RawStillMetadata) {+ // Real driver callbacks already land on the executor; fakes may+ // call synchronously. State is only touched on the executor.+ try {+ executor.execute {+ if (pendingStill !== pending) return@execute+ pending.rawMetadata = metadata+ deliverPendingIfReady(pending)+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ // Session is gone; the capture outcome no longer matters.+ }+ }++ private fun onJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+ try {+ executor.execute {+ val pending = pendingStill ?: return@execute+ pending.jpegBytes = bytes+ pending.jpegWidth = width+ pending.jpegHeight = height+ deliverPendingIfReady(pending)+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ }+ }++ private fun deliverPendingIfReady(pending: PendingStill) {+ val raw = pending.rawMetadata ?: return+ val bytes = pending.jpegBytes ?: return+ pendingStill = null+ pending.callback.onStillCaptured(+ CapturedStill(+ jpegBytes = bytes,+ jpegWidth = pending.jpegWidth,+ jpegHeight = pending.jpegHeight,+ metadata = StillMetadataMapper.map(+ raw, pending.params.jpegOrientationDegrees, pending.params.mirrored,+ ),+ ),+ )+ }++ private fun failPending(pending: PendingStill, message: String) {+ try {+ executor.execute {+ if (pendingStill !== pending) return@execute+ pendingStill = null+ pending.callback.onStillFailed(message)+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ }+ } /** The preview size chosen at [open], or null before a successful open. */ fun currentPreviewSize(): FrameSize? = previewSize@@ -142,8 +310,15 @@ class Camera2Session( executor.execute { if (stateMachine.state == SessionState.CLOSED) return@execute val gen = stateMachine.beginTeardown()+ pendingStill?.let { pending ->+ pendingStill = null+ runCatching { pending.callback.onStillFailed("session closed during capture") }+ } runCatching { captureSession?.close() } captureSession = null+ runCatching { stillOutput?.close() }+ stillOutput = null+ stillSize = null runCatching { device?.close() } device = null previewSurface = null@@ -169,9 +344,23 @@ class Camera2Session( private fun configureSession(opened: DeviceHandle, gen: Long) { val surface = previewSurface ?: return if (transition(SessionEvent.CONFIGURE_REQUESTED) !is TransitionResult.Applied) return+ // Second output: the JPEG still reader, when the lens reports JPEG+ // sizes and the driver can create it. Failure degrades to+ // preview-only (capture() then fails cleanly, policy excludes it).+ val jpegSize = StreamSelection.selectJpegSize(snapshot)+ val output = jpegSize?.let { size ->+ runCatching { driver.createStillOutput(size) }.getOrNull()?.also { created ->+ created.setListener(JpegImageListener { bytes, width, height, _ ->+ onJpegAvailable(bytes, width, height)+ })+ }+ }+ stillOutput = output+ stillSize = if (output != null) jpegSize else null+ val surfaces = listOfNotNull(surface, output?.surface) runCatching { opened.createCaptureSession(- listOf(surface),+ surfaces, SessionCallbackImpl(gen), ) }.onFailure {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.ktindex 14097d6548..6c47d5b605 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt@@ -21,9 +21,10 @@ data class PreviewEngineInput( * Explicit selection rule for the two preview engines, mirroring * `RecordingPathPolicy` for recording: the Camera2 path is selected only * when the gate is explicitly on *and* the mode is one the Camera2 session- * honestly supports. Phase 2 supports PHOTO only (preview + controls, no- * still capture yet), so every other mode stays on CameraX even with the- * gate on.+ * honestly supports. Phase 2 supports PHOTO only; Phase 4a adds plain+ * PHOTO stills on that preview (see `StillEnginePolicy` for which shots+ * still stay on CameraX), so every other mode stays on CameraX even with+ * the gate on. */ object PreviewEnginePolicy {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.ktnew file mode 100644index 0000000000..73f7146e61--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt@@ -0,0 +1,189 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata+import com.vayunmathur.camera.domain.FlashModePolicy+import com.vayunmathur.camera.domain.FlashResolution+import com.vayunmathur.camera.domain.FlashSetting+import com.vayunmathur.camera.domain.LensFacing++/**+ * Camera2 migration Phase 4a: plain single stills on the Camera2 session.+ *+ * A still is a `TEMPLATE_STILL_CAPTURE` request targeted at a JPEG+ * `ImageReader` surface (the session's second output, alongside preview).+ * This file is the pure half: it resolves the session's current control+ * state (zoom / torch / EV / metering, plus the user's flash setting) into+ * exact request fields, and maps the resulting `CaptureResult` values into+ * the shape the existing save pipeline already consumes for in-memory+ * CameraX captures (`jpegBytes` + `rotationDegrees` + `mirrored`, see+ * `stampStillBytes` / `saveStillBytes`). No reprocess/ZSL ring, RAW,+ * Motion Photo or portrait work lives here — [StillEnginePolicy] keeps+ * those on CameraX.+ */++/** Raw `CaptureResult` values for one still, as read by the driver. */+data class RawStillMetadata(+ val sensorTimestampNs: Long? = null,+ val exposureTimeNs: Long? = null,+ val iso: Int? = null,+ val focalLengthMm: Float? = null,+ val frameNumber: Long? = null,+ val aeState: Int? = null,+ val afState: Int? = null,+ val flashState: Int? = null,+)++/**+ * Metadata for one captured still, in the shape the existing save pipeline+ * consumes: the CameraX in-memory paths hand `stampStillBytes` /+ * `writeCaptureExif` a JPEG plus a rotation and a mirror flag; the exposure+ * fields ride along for EXIF/logging parity with what CameraX surfaces via+ * `CaptureResult` interop snapshots (`lastAeIso` / `lastAeExposureNanos`).+ */+data class StillCaptureMetadata(+ /** Clockwise degrees to rotate the sensor JPEG upright (EXIF sense). */+ val rotationDegrees: Int,+ /** True when the saved image must be flipped (front lens, mirrored). */+ val mirrored: Boolean,+ val sensorTimestampNs: Long? = null,+ val exposureTimeNs: Long? = null,+ val iso: Int? = null,+ val focalLengthMm: Float? = null,+ val frameNumber: Long? = null,+)++/** One finished still: HAL JPEG bytes plus their mapped metadata. */+data class CapturedStill(+ val jpegBytes: ByteArray,+ val jpegWidth: Int,+ val jpegHeight: Int,+ val metadata: StillCaptureMetadata,+) {+ override fun equals(other: Any?): Boolean =+ other is CapturedStill && jpegWidth == other.jpegWidth &&+ jpegHeight == other.jpegHeight && metadata == other.metadata &&+ jpegBytes.contentEquals(other.jpegBytes)++ override fun hashCode(): Int {+ var result = jpegBytes.contentHashCode()+ result = 31 * result + jpegWidth+ result = 31 * result + jpegHeight+ result = 31 * result + metadata.hashCode()+ return result+ }+}++/**+ * Resolved `CaptureRequest` fields for one `TEMPLATE_STILL_CAPTURE`.+ * Carries everything the preview resolution produced (zoom/torch/EV/+ * metering) plus the still-only AE/flash fields.+ */+data class ResolvedStillParams(+ val zoomRatio: Float?,+ val cropRegion: SensorRect?,+ /** `FLASH_MODE` (`CameraMetadata.FLASH_MODE_*`). */+ val flashMode: Int,+ /** `CONTROL_AE_MODE` (`CameraMetadata.CONTROL_AE_MODE_*`). */+ val aeMode: Int,+ val aeExposureCompensationSteps: Int,+ val afRegions: List<MeteringRegion>,+ val aeRegions: List<MeteringRegion>,+ val meteringActive: Boolean,+ /** How illumination resolved for this lens + setting. */+ val flashResolution: FlashResolution,+ /**+ * True when illumination is the display (front lens, no flash unit):+ * no HAL request key can fire it, so the UI/glue must light the screen+ * around the capture. The request itself carries flash OFF.+ */+ val requiresScreenFlash: Boolean,+ /** `JPEG_ORIENTATION`: clockwise degrees, matching [StillCaptureMetadata]. */+ val jpegOrientationDegrees: Int,+ val mirrored: Boolean,+)++object StillCapturePlanner {++ /**+ * Rotation (clockwise, EXIF sense) for a JPEG from this lens at+ * [displayRotationDegrees]. Uses the same relative rotation as+ * [MeteringTransform] (`sensor - display`, normalised): e.g. the usual+ * back lens (sensor 90°) in portrait (display 0°) yields 90, exactly+ * the `rotationDegrees` CameraX reports for that frame, which is what+ * `stampStillBytes`/`rawStillOrientationString` expect.+ */+ fun jpegRotationDegrees(+ sensorOrientationDegrees: Int,+ displayRotationDegrees: Int,+ ): Int {+ val relative = (sensorOrientationDegrees - displayRotationDegrees) % 360+ return (relative + 360) % 360+ }++ /**+ * Resolves the still request for the session's current [state].+ *+ * Flash mapping (Camera2 request keys, where one exists):+ * - OFF / no unit -> `CONTROL_AE_MODE_ON` + `FLASH_MODE_OFF`+ * - hardware AUTO -> `CONTROL_AE_MODE_ON_AUTO_FLASH`+ * - hardware ON -> `CONTROL_AE_MODE_ON_ALWAYS_FLASH`+ * - screen (front, no unit; [FlashModePolicy]) -> `CONTROL_AE_MODE_ON`+ * + `FLASH_MODE_OFF` and [ResolvedStillParams.requiresScreenFlash]:+ * Camera2 has no screen-flash key, the display lighting is UI work.+ * - torch already on wins over a one-shot flash: `FLASH_MODE_TORCH`+ * with plain AE, as the LED is already lit for preview.+ */+ fun resolve(+ state: Camera2ControlState,+ snapshot: LensCharacteristicsSnapshot,+ displayRotationDegrees: Int = 0,+ mirrored: Boolean = false,+ ): ResolvedStillParams {+ val preview = Camera2Controls.resolve(state, snapshot)+ val facing = snapshot.lensFacing ?: LensFacing.BACK+ val resolution = FlashModePolicy.resolve(facing, snapshot.hasFlashUnit, state.flashSetting)+ val torchLit = preview.flashMode == CameraMetadata.FLASH_MODE_TORCH+ val (aeMode, flashMode) = when {+ torchLit -> CameraMetadata.CONTROL_AE_MODE_ON to CameraMetadata.FLASH_MODE_TORCH+ resolution == FlashResolution.HARDWARE && state.flashSetting == FlashSetting.AUTO ->+ CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH to CameraMetadata.FLASH_MODE_SINGLE+ resolution == FlashResolution.HARDWARE && state.flashSetting == FlashSetting.ON ->+ CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH to CameraMetadata.FLASH_MODE_SINGLE+ else -> CameraMetadata.CONTROL_AE_MODE_ON to CameraMetadata.FLASH_MODE_OFF+ }+ return ResolvedStillParams(+ zoomRatio = preview.zoomRatio,+ cropRegion = preview.cropRegion,+ flashMode = flashMode,+ aeMode = aeMode,+ aeExposureCompensationSteps = preview.aeExposureCompensationSteps,+ afRegions = preview.afRegions,+ aeRegions = preview.aeRegions,+ meteringActive = preview.meteringActive,+ flashResolution = resolution,+ requiresScreenFlash = resolution == FlashResolution.SCREEN,+ jpegOrientationDegrees = jpegRotationDegrees(+ snapshot.sensorOrientationDegrees, displayRotationDegrees,+ ),+ mirrored = mirrored,+ )+ }+}++/** Maps driver-raw result values into the save-pipeline metadata shape. */+object StillMetadataMapper {++ fun map(+ raw: RawStillMetadata,+ rotationDegrees: Int,+ mirrored: Boolean,+ ): StillCaptureMetadata = StillCaptureMetadata(+ rotationDegrees = ((rotationDegrees % 360) + 360) % 360,+ mirrored = mirrored,+ sensorTimestampNs = raw.sensorTimestampNs,+ exposureTimeNs = raw.exposureTimeNs,+ iso = raw.iso,+ focalLengthMm = raw.focalLengthMm,+ frameNumber = raw.frameNumber,+ )+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.ktnew file mode 100644index 0000000000..4ed3040e8d--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt@@ -0,0 +1,64 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode++/** Which engine takes a still. */+enum class StillEngine { CAMERAX, CAMERA2 }++/**+ * Inputs to the still-engine selection rule. Every flag that describes a+ * non-plain capture is an exclusion for Phase 4a (see [StillEnginePolicy]).+ */+data class StillEngineInput(+ /** The Phase-2 gate. Default OFF: CameraX remains the live path. */+ val camera2Enabled: Boolean,+ val mode: CameraMode,+ /** A JPEG `ImageReader` output was configured on the Camera2 session. */+ val hasJpegOutput: Boolean = false,+ /** Night route: vendor extension or custom burst/long-exposure path. */+ val nightRoute: Boolean = false,+ /** Warmth/shadows/portrait bake that only the CameraX path applies. */+ val processedRoute: Boolean = false,+ /** Motion Photo (JPEG + MP4 trailer from the analysis ring buffer). */+ val motionPhotoRoute: Boolean = false,+ /** Capture-for-result (`ACTION_IMAGE_CAPTURE`) for a caller. */+ val captureForResult: Boolean = false,+ /** Press-and-hold burst (a sequence, not a plain single capture). */+ val burst: Boolean = false,+)++/**+ * Explicit selection rule for stills, mirroring [PreviewEnginePolicy]:+ * Camera2 takes a still only when the gate is on *and* the shot is a plain+ * single PHOTO capture on a session that has a JPEG output.+ *+ * Documented exclusions (all stay on CameraX, even with the gate on):+ * - every mode other than PHOTO (portrait, night mode, panorama, video…)+ * - the night route (extension night or custom night/long exposure)+ * - processed captures (warmth/shadows bake, portrait bokeh) — Phase 4a+ * does not re-encode through those pipelines from Camera2 bytes+ * - Motion Photo, burst, and capture-for-result+ * - RAW, reprocess/ZSL-ring captures: no such output is configured on the+ * Camera2 session in this phase at all+ */+object StillEnginePolicy {++ fun select(input: StillEngineInput): StillEngine =+ if (exclusionReason(input) == null) StillEngine.CAMERA2 else StillEngine.CAMERAX++ /** True when this shot should be taken on the Camera2 session. */+ fun usesCamera2(input: StillEngineInput): Boolean = select(input) == StillEngine.CAMERA2++ /** Why [input] cannot use Camera2, or null when it can. */+ fun exclusionReason(input: StillEngineInput): String? = when {+ !input.camera2Enabled -> "camera2 gate off"+ input.mode != CameraMode.PHOTO -> "mode ${input.mode} is CameraX-only in Phase 4a"+ !input.hasJpegOutput -> "no JPEG output on the Camera2 session"+ input.nightRoute -> "night captures stay on CameraX in Phase 4a"+ input.processedRoute -> "processed (bake/bokeh) captures stay on CameraX in Phase 4a"+ input.motionPhotoRoute -> "Motion Photo stays on CameraX in Phase 4a"+ input.captureForResult -> "capture-for-result stays on CameraX in Phase 4a"+ input.burst -> "burst stays on CameraX in Phase 4a"+ else -> null+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.ktnew file mode 100644index 0000000000..e1452c6052--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillImageSource.kt@@ -0,0 +1,93 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.media.ImageReader+import android.os.Handler+import android.view.Surface+import com.vayunmathur.library.log.Log++/** Delivers one JPEG frame from a [StillOutput]; fires on the reader handler thread. */+fun interface JpegImageListener {+ fun onJpeg(jpegBytes: ByteArray, width: Int, height: Int, timestampNs: Long)+}++/**+ * Testable handle over a JPEG still output (an `ImageReader` in the real+ * driver). The session adds [surface] as its second capture-session output+ * alongside preview; JPEG bytes arrive through the listener.+ */+interface StillOutput : AutoCloseable {+ val surface: Surface+ fun setListener(listener: JpegImageListener?)+ override fun close()+}++/**+ * Camera2 migration Phase 4a: a JPEG `ImageReader` still source.+ *+ * Uses `acquireNextImage()` (not latest): a still must never be dropped in+ * favour of a newer frame — Phase 4a allows one capture in flight, so at+ * most one image is expected. The image is always closed; an unclosed+ * image exhausts the reader pool and stalls the stream.+ *+ * Ownership: whoever constructs this owns it and must call [close].+ */+class JpegStillOutput(+ width: Int,+ height: Int,+ maxImages: Int = DEFAULT_MAX_IMAGES,+ private val handler: Handler,+) : StillOutput {++ private val reader: ImageReader =+ ImageReader.newInstance(width, height, ImageFormat.JPEG, maxImages)++ override val surface: Surface get() = reader.surface++ @Volatile+ private var listener: JpegImageListener? = null++ init {+ reader.setOnImageAvailableListener({ onImageAvailable() }, handler)+ }++ override fun setListener(listener: JpegImageListener?) {+ this.listener = listener+ }++ private fun onImageAvailable() {+ val image = try {+ reader.acquireNextImage()+ } catch (e: IllegalStateException) {+ Log.error("StillImageSource", "acquireNextImage threw", e)+ null+ } ?: return+ try {+ val plane = image.planes.firstOrNull() ?: return+ val buffer = plane.buffer+ val bytes = ByteArray(buffer.remaining()).also { buffer.get(it) }+ listener?.onJpeg(bytes, image.width, image.height, image.timestamp)+ } catch (e: IllegalStateException) {+ Log.error("StillImageSource", "reading JPEG image threw", e)+ } finally {+ try {+ image.close()+ } catch (e: IllegalStateException) {+ Log.error("StillImageSource", "image close threw", e)+ }+ }+ }++ override fun close() {+ try {+ reader.setOnImageAvailableListener(null, null)+ } catch (e: IllegalStateException) {+ Log.error("StillImageSource", "clearing listener threw", e)+ }+ reader.close()+ }++ companion object {+ const val DEFAULT_MAX_IMAGES: Int = 2+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex d7c4acdbcd..3d734cfbf9 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -112,6 +112,21 @@ object StreamSelection { return Result.success(selected) } + /** Supported JPEG still sizes in facade order (empty = no still output). */+ fun supportedJpegSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> =+ snapshot.streamConfig.sizesFor(ImageFormat.JPEG)+ .map { FrameSize.from(it) }.distinct()++ /**+ * The JPEG still size to configure: the largest the HAL offers (ties on+ * width, then height), matching CameraX's default highest-resolution+ * still. Null when the lens reports no JPEG sizes — preview still+ * works, still capture is unavailable ([StillEnginePolicy] excludes it).+ */+ fun selectJpegSize(snapshot: LensCharacteristicsSnapshot): FrameSize? =+ supportedJpegSizes(snapshot)+ .maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ /** The rejection for [requested], or null when a size can be selected. */ fun rejectionFor( requested: FrameSize,
camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.ktindex d80f7677a4..d3b70f0174 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -40,23 +40,38 @@ internal fun Camera2Preview( zoomRatio: Float, torchOn: Boolean, exposureCompEv: Float,+ flashSetting: com.vayunmathur.camera.domain.FlashSetting =+ com.vayunmathur.camera.domain.FlashSetting.OFF,+ onSessionChanged: (Camera2Session?) -> Unit = {}, modifier: Modifier = Modifier, ) { val context = LocalContext.current val sessionHolder = remember(cameraId) { Camera2PreviewSession(context, cameraId) } DisposableEffect(sessionHolder) {- onDispose { sessionHolder.close() }+ onSessionChanged(sessionHolder.session)+ onDispose {+ onSessionChanged(null)+ sessionHolder.close()+ } } LaunchedEffect(sessionHolder, zoomRatio) { sessionHolder.session.setZoomRatio(zoomRatio) } LaunchedEffect(sessionHolder, torchOn) { sessionHolder.session.setTorch(torchOn) } LaunchedEffect(sessionHolder, exposureCompEv) { sessionHolder.session.setExposureCompEv(exposureCompEv) }+ LaunchedEffect(sessionHolder, flashSetting) {+ sessionHolder.session.setFlashSetting(flashSetting)+ } AndroidView( factory = { ctx ->- TextureView(ctx).also { view -> sessionHolder.bridge.attachTo(view) }+ TextureView(ctx).also { view ->+ sessionHolder.session.setDisplayRotationDegrees(+ (view.display?.rotation ?: 0) * 90,+ )+ sessionHolder.bridge.attachTo(view)+ } }, modifier = modifier.pointerInput(sessionHolder) { detectTapGestures { offset ->
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 9a3160a1fe..dec5bcf253 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -48,6 +48,7 @@ import com.vayunmathur.camera.data.setExposureCompensation import com.vayunmathur.camera.platform.setExposureTimeIndex import com.vayunmathur.camera.platform.setManualIsoIndex import com.vayunmathur.camera.platform.setQrResult+import com.vayunmathur.camera.platform.registerCamera2Session import com.vayunmathur.camera.platform.setScreenFlash import com.vayunmathur.camera.data.setShadows import com.vayunmathur.camera.data.setWarmth@@ -209,6 +210,17 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( zoomRatio = state.zoomRatio, torchOn = state.torchEnabled, exposureCompEv = state.exposureComp,+ flashSetting = when (state.flashMode) {+ com.vayunmathur.camera.platform.FlashMode.ON ->+ com.vayunmathur.camera.domain.FlashSetting.ON+ com.vayunmathur.camera.platform.FlashMode.AUTO ->+ com.vayunmathur.camera.domain.FlashSetting.AUTO+ com.vayunmathur.camera.platform.FlashMode.OFF ->+ com.vayunmathur.camera.domain.FlashSetting.OFF+ },+ onSessionChanged = { session ->+ viewModel.registerCamera2Session(session)+ }, modifier = previewModifier, ) } else {
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.ktindex a3f476ab1f..f35e210fdc 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt@@ -32,6 +32,13 @@ class Camera2SessionTest { override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) { repeating += params }+ override fun captureStill(+ params: ResolvedStillParams,+ stillTarget: Surface,+ callback: StillResultCallback,+ ) {+ callback.onCompleted(RawStillMetadata())+ } override fun close() { closed = true } } @@ -67,6 +74,7 @@ class Camera2SessionTest { if (failConfigure) FakeDeviceHandle(cameraId, failConfigure = true) else device, ) }+ override fun createStillOutput(size: FrameSize): StillOutput? = null } private fun snapshot(@@ -220,6 +228,7 @@ class Camera2SessionTest { override fun openCamera(cameraId: String, callback: DeviceCallback) { pendingCallback = callback }+ override fun createStillOutput(size: FrameSize): StillOutput? = null } val listener = RecordingListener() val session = newSession(driver, executor, listener)
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.ktnew file mode 100644index 0000000000..6fe2d325ad--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StillCaptureTest.kt@@ -0,0 +1,344 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraMetadata+import android.util.Range+import android.util.Size+import android.view.Surface+import com.vayunmathur.camera.domain.FlashResolution+import com.vayunmathur.camera.domain.FlashSetting+import com.vayunmathur.camera.platform.CameraMode+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.Mockito.mock+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class StillCaptureTest {++ private fun snapshot(+ hasFlashUnit: Boolean = true,+ lensFacingRaw: Int? = CameraMetadata.LENS_FACING_BACK,+ sensorOrientationDegrees: Int = 90,+ jpegSizes: List<Size> = listOf(Size(4000, 3000), Size(1920, 1080)),+ ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ lensFacingRaw = lensFacingRaw,+ zoomRatioRange = Range(1f, 10f),+ hasFlashUnit = hasFlashUnit,+ exposureCompensationEvRange = Range(-4f, 4f),+ sizesByFormat = mapOf(+ ImageFormat.PRIVATE to listOf(Size(1280, 720)),+ ImageFormat.JPEG to jpegSizes,+ ),+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ sensorOrientationDegrees = sensorOrientationDegrees,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = 1,+ maxAeRegions = 1,+ ).snapshot++ // -- request construction -------------------------------------------------++ @Test fun stillRequestCarriesCurrentControlState() {+ val region = MeteringRegion(SensorRect(100, 100, 300, 300))+ val params = StillCapturePlanner.resolve(+ Camera2ControlState(+ zoomRatio = 2f, exposureCompEv = 1f,+ afRegion = region, aeRegion = region,+ flashSetting = FlashSetting.OFF,+ ),+ snapshot(),+ )+ assertEquals(2f, params.zoomRatio)+ assertNull(params.cropRegion)+ assertEquals(6, params.aeExposureCompensationSteps)+ assertEquals(listOf(region), params.afRegions)+ assertEquals(listOf(region), params.aeRegions)+ assertTrue(params.meteringActive)+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON, params.aeMode)+ assertEquals(CameraMetadata.FLASH_MODE_OFF, params.flashMode)+ }++ @Test fun hardwareFlashMapsToAeFlashModes() {+ val auto = StillCapturePlanner.resolve(+ Camera2ControlState(flashSetting = FlashSetting.AUTO), snapshot(),+ )+ assertEquals(FlashResolution.HARDWARE, auto.flashResolution)+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH, auto.aeMode)+ assertEquals(CameraMetadata.FLASH_MODE_SINGLE, auto.flashMode)+ assertFalse(auto.requiresScreenFlash)++ val on = StillCapturePlanner.resolve(+ Camera2ControlState(flashSetting = FlashSetting.ON), snapshot(),+ )+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH, on.aeMode)+ assertEquals(CameraMetadata.FLASH_MODE_SINGLE, on.flashMode)+ }++ @Test fun screenFlashHasNoHalKeyAndIsFlaggedForTheUi() {+ val params = StillCapturePlanner.resolve(+ Camera2ControlState(flashSetting = FlashSetting.ON),+ snapshot(+ hasFlashUnit = false,+ lensFacingRaw = CameraMetadata.LENS_FACING_FRONT,+ ),+ )+ assertEquals(FlashResolution.SCREEN, params.flashResolution)+ assertTrue(params.requiresScreenFlash)+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON, params.aeMode)+ assertEquals(CameraMetadata.FLASH_MODE_OFF, params.flashMode)+ }++ @Test fun torchAlreadyLitWinsOverOneShotFlash() {+ val params = StillCapturePlanner.resolve(+ Camera2ControlState(torchOn = true, flashSetting = FlashSetting.ON),+ snapshot(),+ )+ assertEquals(CameraMetadata.FLASH_MODE_TORCH, params.flashMode)+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON, params.aeMode)+ }++ @Test fun noFlashUnitBackLensNeverInventsHardwareFlash() {+ val params = StillCapturePlanner.resolve(+ Camera2ControlState(flashSetting = FlashSetting.ON),+ snapshot(hasFlashUnit = false),+ )+ // FlashModePolicy: no unit + not front -> HARDWARE resolution, but+ // the AE flash modes would fire nothing; resolution stays hardware+ // per policy, so this asserts the planner's documented mapping.+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH, params.aeMode)+ }++ // -- orientation / metadata mapping ---------------------------------------++ @Test fun jpegRotationMatchesSensorMinusDisplay() {+ assertEquals(90, StillCapturePlanner.jpegRotationDegrees(90, 0))+ assertEquals(0, StillCapturePlanner.jpegRotationDegrees(90, 90))+ assertEquals(180, StillCapturePlanner.jpegRotationDegrees(90, 270))+ assertEquals(270, StillCapturePlanner.jpegRotationDegrees(270, 0))+ assertEquals(0, StillCapturePlanner.jpegRotationDegrees(0, 0))+ val params = StillCapturePlanner.resolve(+ Camera2ControlState(), snapshot(), displayRotationDegrees = 0, mirrored = true,+ )+ assertEquals(90, params.jpegOrientationDegrees)+ assertTrue(params.mirrored)+ }++ @Test fun metadataMappingCarriesCaptureResultFields() {+ val mapped = StillMetadataMapper.map(+ RawStillMetadata(+ sensorTimestampNs = 123_456L, exposureTimeNs = 10_000_000L,+ iso = 400, focalLengthMm = 4.5f, frameNumber = 7L,+ ),+ rotationDegrees = 450, mirrored = true,+ )+ assertEquals(90, mapped.rotationDegrees)+ assertTrue(mapped.mirrored)+ assertEquals(123_456L, mapped.sensorTimestampNs)+ assertEquals(10_000_000L, mapped.exposureTimeNs)+ assertEquals(400, mapped.iso)+ assertEquals(4.5f, mapped.focalLengthMm)+ assertEquals(7L, mapped.frameNumber)+ }++ @Test fun jpegSizeSelectionPicksLargest() {+ assertEquals(FrameSize(4000, 3000), StreamSelection.selectJpegSize(snapshot()))+ assertNull(StreamSelection.selectJpegSize(snapshot(jpegSizes = emptyList())))+ }++ // -- policy ---------------------------------------------------------------++ @Test fun policyAllowsOnlyPlainPhotoStillsBehindGate() {+ val plain = StillEngineInput(+ camera2Enabled = true, mode = CameraMode.PHOTO, hasJpegOutput = true,+ )+ assertTrue(StillEnginePolicy.usesCamera2(plain))+ assertNull(StillEnginePolicy.exclusionReason(plain))++ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(camera2Enabled = false)))+ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(hasJpegOutput = false)))+ for (mode in CameraMode.entries - CameraMode.PHOTO) {+ assertFalse(+ StillEnginePolicy.usesCamera2(plain.copy(mode = mode)),+ "$mode must stay on CameraX",+ )+ }+ assertTrue(+ StillEnginePolicy.exclusionReason(plain.copy(nightRoute = true))+ .orEmpty().contains("night"),+ )+ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(processedRoute = true)))+ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(motionPhotoRoute = true)))+ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(captureForResult = true)))+ assertFalse(StillEnginePolicy.usesCamera2(plain.copy(burst = true)))+ }++ // -- session pairing over fakes --------------------------------------------++ private class FakeStillOutput : StillOutput {+ override val surface: Surface = mock(Surface::class.java)+ var jpegListener: JpegImageListener? = null+ var closed = false+ override fun setListener(listener: JpegImageListener?) { jpegListener = listener }+ override fun close() { closed = true }+ fun emit(bytes: ByteArray) = jpegListener?.onJpeg(bytes, 4000, 3000, 99L)+ }++ private class FakeSessionHandle : CaptureSessionHandle {+ val stillRequests = mutableListOf<ResolvedStillParams>()+ var stillCallback: StillResultCallback? = null+ var closed = false+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+ override fun captureStill(+ params: ResolvedStillParams,+ stillTarget: Surface,+ callback: StillResultCallback,+ ) {+ stillRequests += params+ stillCallback = callback+ }+ override fun close() { closed = true }+ }++ private class FakeDevice(+ private val handle: FakeSessionHandle,+ ) : DeviceHandle {+ override val cameraId: String = "0"+ var surfaces: List<Surface>? = null+ override fun createCaptureSession(+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ this.surfaces = surfaces+ callback.onConfigured(handle)+ }+ override fun close() {}+ }++ private class FakeDriver(+ private val device: FakeDevice,+ private val output: FakeStillOutput?,+ ) : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ callback.onOpened(device)+ }+ override fun createStillOutput(size: FrameSize): StillOutput? = output+ }++ private class RecordingStillCallback : Camera2Session.StillCallback {+ val captured = mutableListOf<CapturedStill>()+ val failures = mutableListOf<String>()+ override fun onStillCaptured(still: CapturedStill) { captured += still }+ override fun onStillFailed(message: String) { failures += message }+ }++ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+ }++ private fun streamingSession(+ executor: Camera2Executor,+ handle: FakeSessionHandle,+ output: FakeStillOutput?,+ ): Camera2Session {+ val device = FakeDevice(handle)+ val session = Camera2Session(FakeDriver(device, output), executor, snapshot())+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ return session+ }++ @Test fun sessionCapturePairsJpegAndResultIntoOneStill() {+ val executor = Camera2Executor("StillCaptureTest-pair")+ try {+ val handle = FakeSessionHandle()+ val output = FakeStillOutput()+ val session = streamingSession(executor, handle, output)+ assertTrue(session.hasJpegOutput)+ assertEquals(FrameSize(4000, 3000), session.currentStillSize())++ session.setZoomRatio(3f)+ session.setFlashSetting(FlashSetting.AUTO)+ executor.drain()+ val callback = RecordingStillCallback()+ session.capture(callback, displayRotationDegrees = 0, mirrored = false)+ executor.drain()++ // Request construction: controls carried over at capture time.+ assertEquals(1, handle.stillRequests.size)+ val params = handle.stillRequests.single()+ assertEquals(3f, params.zoomRatio)+ assertEquals(CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH, params.aeMode)+ assertEquals(90, params.jpegOrientationDegrees)++ // JPEG first, result second: delivered only when both arrive.+ output.emit(byteArrayOf(1, 2, 3))+ executor.drain()+ assertTrue(callback.captured.isEmpty())+ handle.stillCallback!!.onCompleted(+ RawStillMetadata(sensorTimestampNs = 99L, iso = 200, exposureTimeNs = 5L),+ )+ executor.drain()+ assertEquals(1, callback.captured.size)+ val still = callback.captured.single()+ assertTrue(still.jpegBytes.contentEquals(byteArrayOf(1, 2, 3)))+ assertEquals(4000, still.jpegWidth)+ assertEquals(90, still.metadata.rotationDegrees)+ assertEquals(200, still.metadata.iso)+ assertEquals(99L, still.metadata.sensorTimestampNs)+ session.close()+ executor.drain()+ assertTrue(output.closed)+ } finally {+ executor.shutdown()+ }+ }++ @Test fun sessionCaptureRejectsSecondInFlightAndMissingOutput() {+ val executor = Camera2Executor("StillCaptureTest-guards")+ try {+ val handle = FakeSessionHandle()+ val session = streamingSession(executor, handle, FakeStillOutput())+ val first = RecordingStillCallback()+ val second = RecordingStillCallback()+ session.capture(first)+ session.capture(second)+ executor.drain()+ assertEquals(1, handle.stillRequests.size)+ assertEquals(1, second.failures.size)+ assertTrue(second.failures.single().contains("already in flight"))++ // Closing mid-capture fails the pending shot, never delivers it.+ session.close()+ executor.drain()+ assertEquals(1, first.failures.size)+ assertTrue(first.captured.isEmpty())++ // No JPEG output: capture fails cleanly, preview unaffected.+ val noJpeg = streamingSession(executor, FakeSessionHandle(), null)+ assertFalse(noJpeg.hasJpegOutput)+ val cb = RecordingStillCallback()+ noJpeg.capture(cb)+ executor.drain()+ assertEquals(1, cb.failures.size)+ assertTrue(cb.failures.single().contains("no JPEG output"))+ noJpeg.close()+ executor.drain()+ } finally {+ executor.shutdown()+ }+ }+}