camera: split three over-limit files for release lint
- Commit
26c42da98e9bb17f89be78010d188ec23c187ca0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 14:39 UTC (14 days ago)
- Parents
fe8508d
The Camera2 enablement grew CameraViewModel to 933, Camera2Session to 849 and CameraPreviewBox to 370 (limits 800/800/350), blocking lintVitalRelease. Verbatim splits: ViewModel gate and mode/lens actions into extension files, constant tables into CameraViewModelTables (companion names unchanged), session still-delivery into its own file, the preview surface into CameraPreviewSurface.kt. No behavior change, no lint config touched. Verified: lintVitalRelease + compileDevKotlin green; 45 targeted unit tests + SVM classes pass.
Diff
camera/src/main/java/com/vayunmathur/camera/MainActivity.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt b/camera/src/main/java/com/vayunmathur/camera/MainActivity.ktindex c3823ad902..3c6f267bb0 100644--- a/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt+++ b/camera/src/main/java/com/vayunmathur/camera/MainActivity.kt@@ -14,6 +14,7 @@ import androidx.core.content.IntentCompat import com.vayunmathur.camera.ui.CameraScreen import com.vayunmathur.camera.ui.SettingsPage import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.triggerShutter import com.vayunmathur.library.ui.AppPermissionsGate import com.vayunmathur.library.ui.AppPermissionsSpec import com.vayunmathur.library.ui.MaActivity
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 b22f1d798f..cd35e12900 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -24,7 +24,6 @@ import androidx.camera.extensions.ExtensionsManager import androidx.camera.video.Recorder import androidx.camera.video.Recording import androidx.camera.video.VideoCapture-import androidx.exifinterface.media.ExifInterface import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.library.util.DataStoreUtils@@ -98,65 +97,20 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { // 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),- ExposureTimeStop("1/2000s", 500_000L),- ExposureTimeStop("1/1000s", 1_000_000L),- ExposureTimeStop("1/500s", 2_000_000L),- ExposureTimeStop("1/250s", 4_000_000L),- ExposureTimeStop("1/125s", 8_000_000L),- ExposureTimeStop("1/60s", 16_666_667L),- ExposureTimeStop("1/30s", 33_333_333L),- ExposureTimeStop("1/15s", 66_666_667L),- ExposureTimeStop("1/8s", 125_000_000L),- ExposureTimeStop("1/4s", 250_000_000L),- ExposureTimeStop("1/2s", 500_000_000L),- ExposureTimeStop("1s", 1_000_000_000L),- ExposureTimeStop("2s", 2_000_000_000L),- ExposureTimeStop("4s", 4_000_000_000L),- )+ val EXPOSURE_TIME_STOPS: List<ExposureTimeStop> = EXPOSURE_TIME_STOPS_TABLE /** * EXIF tags copied from the original frame onto an adjusted capture. Orientation and GPS * are set separately (see writeCaptureExif); dimension tags are omitted so they aren't * left inconsistent with the re-encoded JPEG. */- val EXIF_TAGS_TO_COPY = listOf(- ExifInterface.TAG_DATETIME,- ExifInterface.TAG_DATETIME_ORIGINAL,- ExifInterface.TAG_DATETIME_DIGITIZED,- ExifInterface.TAG_OFFSET_TIME,- ExifInterface.TAG_OFFSET_TIME_ORIGINAL,- ExifInterface.TAG_OFFSET_TIME_DIGITIZED,- ExifInterface.TAG_SUBSEC_TIME,- ExifInterface.TAG_SUBSEC_TIME_ORIGINAL,- ExifInterface.TAG_SUBSEC_TIME_DIGITIZED,- ExifInterface.TAG_MAKE,- ExifInterface.TAG_MODEL,- ExifInterface.TAG_SOFTWARE,- ExifInterface.TAG_F_NUMBER,- ExifInterface.TAG_EXPOSURE_TIME,- ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY,- ExifInterface.TAG_FOCAL_LENGTH,- ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM,- ExifInterface.TAG_APERTURE_VALUE,- ExifInterface.TAG_SHUTTER_SPEED_VALUE,- ExifInterface.TAG_EXPOSURE_BIAS_VALUE,- ExifInterface.TAG_MAX_APERTURE_VALUE,- ExifInterface.TAG_METERING_MODE,- ExifInterface.TAG_EXPOSURE_PROGRAM,- ExifInterface.TAG_EXPOSURE_MODE,- ExifInterface.TAG_WHITE_BALANCE,- ExifInterface.TAG_LIGHT_SOURCE,- ExifInterface.TAG_FLASH,- ExifInterface.TAG_SCENE_CAPTURE_TYPE,- ExifInterface.TAG_DIGITAL_ZOOM_RATIO,- )+ val EXIF_TAGS_TO_COPY: List<String> = EXIF_TAGS_TO_COPY_TABLE } internal val ds = DataStoreUtils.getInstance(app) + // Camera2 gate setters/fallback live in CameraViewModelCamera2Gates.kt as extensions.+ /** * Gate for the Camera2 preview engine. Default ON — Camera2 is the * live path and CameraX is the opt-out / fallback. Persisted as@@ -171,32 +125,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2FallbackBindKeyMutable = MutableStateFlow<String?>(null) val camera2FallbackBindKey = camera2FallbackBindKeyMutable.asStateFlow() - /**- * Records a Camera2 preview configure/bind failure. First failure for- * this bind key latches (returns true) and the UI switches that- * session to CameraX; repeat failures for the same key are ignored.- */- fun onCamera2PreviewFailed(cameraId: String): Boolean {- val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch- .bindKey(cameraId, cameraModeMutable.value)- if (!camera2FallbackLatch.recordFailure(key)) return false- camera2FallbackBindKeyMutable.value = key- Log.status("Camera2Preview", "Camera2 bind failed for $key; falling back to CameraX for this session")- return true- }-- /** Clears the fallback latch (manual retry / gate re-enable / new bind). */- fun clearCamera2Fallback() {- camera2FallbackLatch.reset()- camera2FallbackBindKeyMutable.value = null- }-- /** Turns the Camera2 engine on/off (PHOTO only; see PreviewEnginePolicy). */- fun setCamera2PreviewEnabled(enabled: Boolean) {- camera2PreviewEnabledMutable.value = enabled- if (enabled) clearCamera2Fallback()- viewModelScope.launch { ds.setString("camera_camera2_engine", enabled.toString()) }- } /** * Gate for the Camera2 slo-mo path. Default ON — the Camera2 decision@@ -207,11 +135,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2SloMoEnabledMutable = MutableStateFlow(true) val camera2SloMoEnabled = camera2SloMoEnabledMutable.asStateFlow() - /** Turns the Camera2 slo-mo gate on/off (SLOW_MO only; see SloMoEnginePolicy). */- fun setCamera2SloMoEnabled(enabled: Boolean) {- camera2SloMoEnabledMutable.value = enabled- viewModelScope.launch { ds.setString("camera_camera2_slomo", enabled.toString()) }- } /** * Gate for the Camera2 NIGHT path. Default ON — the Camera2 decision@@ -222,11 +145,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2NightEnabledMutable = MutableStateFlow(true) val camera2NightEnabled = camera2NightEnabledMutable.asStateFlow() - /** Turns the Camera2 night gate on/off (PHOTO only; see ExtensionsEnginePolicy). */- fun setCamera2NightEnabled(enabled: Boolean) {- camera2NightEnabledMutable.value = enabled- viewModelScope.launch { ds.setString("camera_camera2_night", enabled.toString()) }- } /** * RAW-night selection on the Camera2 dual ring. Default ON as the@@ -238,11 +156,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2RawNightEnabledMutable = MutableStateFlow(true) val camera2RawNightEnabled = camera2RawNightEnabledMutable.asStateFlow() - /** Turns the RAW-night Camera2 route on/off (see RawNightPolicy). */- fun setCamera2RawNightEnabled(enabled: Boolean) {- camera2RawNightEnabledMutable.value = enabled- viewModelScope.launch { ds.setString("camera_camera2_raw_night", enabled.toString()) }- } /** * The live Camera2 NIGHT extension session while one is bound@@ -691,9 +604,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val shutterEventsMutable = kotlinx.coroutines.flow.MutableSharedFlow<Unit>(extraBufferCapacity = 1) val shutterEvents = shutterEventsMutable.asSharedFlow() - fun triggerShutter() {- shutterEventsMutable.tryEmit(Unit)- } // Burst mode (press-and-hold shutter): fires single-frame captures back-to-back with only one // in flight at a time, up to BURST_MAX, until the user releases (stopBurst).@@ -761,9 +671,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { /** True while a record press is rebinding the video session for a new bitrate. */ internal var adaptiveBitrateRebindInFlight: Boolean = false - fun setSloMoFps(fps: Int) {- sloMoFps = fps- } // (cancelTimerCountdown lives in CameraViewModelActions.kt as an extension.) @@ -794,11 +701,9 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { // Capture settings live in CameraSettings.kt as extensions. - // --- Mode, lens, capture-intent, shutter, timer and sensor members stay here: ---- // they are called from other packages (ui, root), which this task may not edit,- // and Kotlin extensions would need new imports at those call sites.- // Same-package-only helpers (crop ratio, level sensor, mirror flag, debug logging)- // live in CameraViewModelActions.kt as extensions.+ // --- Mode/lens actions live in CameraViewModelModeLens.kt as extensions;+ // shutter/timer/sensor helpers live in CameraViewModelActions.kt as extensions.+ // Capture-intent, timer and sensor members stay here. // Bitmap/EXIF processing helpers live in CameraCaptureProcessing.kt as extensions. // (long-exposure countdown lives in CameraNightCapture.kt.)@@ -808,70 +713,6 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { // Night luminance/override handling lives in CameraNightMode.kt as extensions. // Last-capture persistence lives in CameraSettings.kt as an extension. - fun switchCameraMode(newMode: CameraMode) {- // Mid-recording mode switches rebind the session, whose teardown stops the- // active recording. Unlike the persisted bind-time settings they cannot be- // deferred (a mode jump on stop would surprise), so the switch is gated- // while recording; the UI explains why. Same-mode taps stay harmless.- if (isRecordingMutable.value && newMode != cameraModeMutable.value) return- // A pending shutter timer belongs to the old mode: firing capturePhoto() into the- // new session would capture unprompted (and with the wrong use cases bound).- if (newMode != cameraModeMutable.value) {- cancelTimerCountdown()- resetNightModeDetection()- }- // Slo-Mo is back-camera only; enforce it when entering Slo-Mo.- if (newMode == CameraMode.SLOW_MO) {- if (lensFacingMutable.value != CameraSelector.LENS_FACING_BACK) {- lensFacingMutable.value = CameraSelector.LENS_FACING_BACK- resetNightModeDetection()- }- }- cameraModeMutable.value = newMode- }-- fun flipCamera() {- // Disallow flipping while in Slo-Mo — it's back-camera only, true HFR.- if (cameraModeMutable.value == CameraMode.SLOW_MO) return- // A flip rebinds the session and teardown would stop an active recording- // (the shutter row already hides flip while recording; this is the backstop).- if (isRecordingMutable.value) return- lensFacingMutable.value = if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)- CameraSelector.LENS_FACING_FRONT else CameraSelector.LENS_FACING_BACK- // Preserve the lens family across the flip: e.g. UW back -> front lens,- // tele back -> front lens (front has a single family, anchored at its default).- val facing = if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)- com.vayunmathur.camera.domain.LensFacing.BACK- else com.vayunmathur.camera.domain.LensFacing.FRONT- selectedLensMutable.value =- com.vayunmathur.camera.domain.LensSelectionLogic.filterByFacing(- availableLensesMutable.value, facing- ).minByOrNull { it.fallbackPriority }- resetNightModeDetection()- }-- /**- * Selects a physical lens within the current facing family. The session- * rebind effect is keyed on [selectedLens], so this triggers a rebind with- * the filtered selector plus a capability refresh. Unknown lenses are- * ignored so a stale UI entry can never crash a bind.- */- fun selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) {- // A lens switch rebinds the session and teardown would stop an active- // recording; gated while recording (the lens bar explains why in the UI).- if (isRecordingMutable.value) return- if (lens.facing != (- if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)- com.vayunmathur.camera.domain.LensFacing.BACK- else com.vayunmathur.camera.domain.LensFacing.FRONT- )- ) {- return- }- if (lens !in availableLensesMutable.value) return- selectedLensMutable.value = lens- resetNightModeDetection()- } // (night reset helper lives in CameraNightMode.kt.) // (mirrorCaptures lives in CameraViewModelActions.kt as an extension.)@@ -925,8 +766,3 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { } // (ManualLifecycleOwner lives in CameraViewModelTypes.kt.) -/** One [CameraViewModel.zslCompatible] input sample: wanted value plus whether a shot is in flight. */-internal class ZslGate(val compatible: Boolean, val capturing: Boolean)--/** One [CameraViewModel.bindTimeSettings] input sample: desired settings plus recording state. */-internal class BindSettingsGate(val settings: BindTimeSettings, val recording: Boolean)
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelActions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelActions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelActions.ktindex 26e5d9d8ee..d94764d672 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelActions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelActions.kt@@ -99,3 +99,13 @@ internal fun CameraViewModel.startDebugLogging() { } } }++/** Fires a hardware-shutter event for the UI to run as a capture. */+fun CameraViewModel.triggerShutter() {+ shutterEventsMutable.tryEmit(Unit)+}++/** Records the requested slo-mo frame rate for the next session bind. */+fun CameraViewModel.setSloMoFps(fps: Int) {+ sloMoFps = fps+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.ktnew file mode 100644index 0000000000..826917adf5--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -0,0 +1,58 @@+package com.vayunmathur.camera.platform++import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.launch++/**+ * Camera2 engine gate actions for [CameraViewModel]: preview fallback+ * handling and the persisted on/off setters for the preview, slo-mo,+ * night and RAW-night Camera2 routes. The gate state flows themselves+ * stay on the ViewModel; these extensions only mutate them, exactly as+ * the former member functions did.+ */++/**+ * Records a Camera2 preview configure/bind failure. First failure for+ * this bind key latches (returns true) and the UI switches that+ * session to CameraX; repeat failures for the same key are ignored.+ */+fun CameraViewModel.onCamera2PreviewFailed(cameraId: String): Boolean {+ val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(cameraId, cameraModeMutable.value)+ if (!camera2FallbackLatch.recordFailure(key)) return false+ camera2FallbackBindKeyMutable.value = key+ Log.status("Camera2Preview", "Camera2 bind failed for $key; falling back to CameraX for this session")+ return true+}++/** Clears the fallback latch (manual retry / gate re-enable / new bind). */+fun CameraViewModel.clearCamera2Fallback() {+ camera2FallbackLatch.reset()+ camera2FallbackBindKeyMutable.value = null+}++/** Turns the Camera2 engine on/off (PHOTO only; see PreviewEnginePolicy). */+fun CameraViewModel.setCamera2PreviewEnabled(enabled: Boolean) {+ camera2PreviewEnabledMutable.value = enabled+ if (enabled) clearCamera2Fallback()+ viewModelScope.launch { ds.setString("camera_camera2_engine", enabled.toString()) }+}++/** Turns the Camera2 slo-mo gate on/off (SLOW_MO only; see SloMoEnginePolicy). */+fun CameraViewModel.setCamera2SloMoEnabled(enabled: Boolean) {+ camera2SloMoEnabledMutable.value = enabled+ viewModelScope.launch { ds.setString("camera_camera2_slomo", enabled.toString()) }+}++/** Turns the Camera2 night gate on/off (PHOTO only; see ExtensionsEnginePolicy). */+fun CameraViewModel.setCamera2NightEnabled(enabled: Boolean) {+ camera2NightEnabledMutable.value = enabled+ viewModelScope.launch { ds.setString("camera_camera2_night", enabled.toString()) }+}++/** Turns the RAW-night Camera2 route on/off (see RawNightPolicy). */+fun CameraViewModel.setCamera2RawNightEnabled(enabled: Boolean) {+ camera2RawNightEnabledMutable.value = enabled+ viewModelScope.launch { ds.setString("camera_camera2_raw_night", enabled.toString()) }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.ktnew file mode 100644index 0000000000..b5f3dde4f5--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelModeLens.kt@@ -0,0 +1,76 @@+package com.vayunmathur.camera.platform++import androidx.camera.core.CameraSelector++/**+ * Mode and lens actions for [CameraViewModel]: mode switches, lens flip+ * and physical-lens selection. All three rebind the session, so all three+ * are gated while a recording is in flight (the UI explains why). Moved+ * verbatim from the ViewModel as extensions; signatures and behaviour+ * are unchanged.+ */++fun CameraViewModel.switchCameraMode(newMode: CameraMode) {+ // Mid-recording mode switches rebind the session, whose teardown stops the+ // active recording. Unlike the persisted bind-time settings they cannot be+ // deferred (a mode jump on stop would surprise), so the switch is gated+ // while recording; the UI explains why. Same-mode taps stay harmless.+ if (isRecordingMutable.value && newMode != cameraModeMutable.value) return+ // A pending shutter timer belongs to the old mode: firing capturePhoto() into the+ // new session would capture unprompted (and with the wrong use cases bound).+ if (newMode != cameraModeMutable.value) {+ cancelTimerCountdown()+ resetNightModeDetection()+ }+ // Slo-Mo is back-camera only; enforce it when entering Slo-Mo.+ if (newMode == CameraMode.SLOW_MO) {+ if (lensFacingMutable.value != CameraSelector.LENS_FACING_BACK) {+ lensFacingMutable.value = CameraSelector.LENS_FACING_BACK+ resetNightModeDetection()+ }+ }+ cameraModeMutable.value = newMode+}++fun CameraViewModel.flipCamera() {+ // Disallow flipping while in Slo-Mo — it's back-camera only, true HFR.+ if (cameraModeMutable.value == CameraMode.SLOW_MO) return+ // A flip rebinds the session and teardown would stop an active recording+ // (the shutter row already hides flip while recording; this is the backstop).+ if (isRecordingMutable.value) return+ lensFacingMutable.value = if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)+ CameraSelector.LENS_FACING_FRONT else CameraSelector.LENS_FACING_BACK+ // Preserve the lens family across the flip: e.g. UW back -> front lens,+ // tele back -> front lens (front has a single family, anchored at its default).+ val facing = if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)+ com.vayunmathur.camera.domain.LensFacing.BACK+ else com.vayunmathur.camera.domain.LensFacing.FRONT+ selectedLensMutable.value =+ com.vayunmathur.camera.domain.LensSelectionLogic.filterByFacing(+ availableLensesMutable.value, facing+ ).minByOrNull { it.fallbackPriority }+ resetNightModeDetection()+}++/**+ * Selects a physical lens within the current facing family. The session+ * rebind effect is keyed on [selectedLens], so this triggers a rebind with+ * the filtered selector plus a capability refresh. Unknown lenses are+ * ignored so a stale UI entry can never crash a bind.+ */+fun CameraViewModel.selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) {+ // A lens switch rebinds the session and teardown would stop an active+ // recording; gated while recording (the lens bar explains why in the UI).+ if (isRecordingMutable.value) return+ if (lens.facing != (+ if (lensFacingMutable.value == CameraSelector.LENS_FACING_BACK)+ com.vayunmathur.camera.domain.LensFacing.BACK+ else com.vayunmathur.camera.domain.LensFacing.FRONT+ )+ ) {+ return+ }+ if (lens !in availableLensesMutable.value) return+ selectedLensMutable.value = lens+ resetNightModeDetection()+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTables.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTables.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTables.ktnew file mode 100644index 0000000000..8759cb2a07--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTables.kt@@ -0,0 +1,56 @@+package com.vayunmathur.camera.platform++import androidx.exifinterface.media.ExifInterface++/** Lookup tables backing [CameraViewModel]'s companion constants. */++internal val EXPOSURE_TIME_STOPS_TABLE = listOf(+ ExposureTimeStop("Auto", null),+ ExposureTimeStop("1/4000s", 250_000L),+ ExposureTimeStop("1/2000s", 500_000L),+ ExposureTimeStop("1/1000s", 1_000_000L),+ ExposureTimeStop("1/500s", 2_000_000L),+ ExposureTimeStop("1/250s", 4_000_000L),+ ExposureTimeStop("1/125s", 8_000_000L),+ ExposureTimeStop("1/60s", 16_666_667L),+ ExposureTimeStop("1/30s", 33_333_333L),+ ExposureTimeStop("1/15s", 66_666_667L),+ ExposureTimeStop("1/8s", 125_000_000L),+ ExposureTimeStop("1/4s", 250_000_000L),+ ExposureTimeStop("1/2s", 500_000_000L),+ ExposureTimeStop("1s", 1_000_000_000L),+ ExposureTimeStop("2s", 2_000_000_000L),+ ExposureTimeStop("4s", 4_000_000_000L),+)++internal val EXIF_TAGS_TO_COPY_TABLE = listOf(+ ExifInterface.TAG_DATETIME,+ ExifInterface.TAG_DATETIME_ORIGINAL,+ ExifInterface.TAG_DATETIME_DIGITIZED,+ ExifInterface.TAG_OFFSET_TIME,+ ExifInterface.TAG_OFFSET_TIME_ORIGINAL,+ ExifInterface.TAG_OFFSET_TIME_DIGITIZED,+ ExifInterface.TAG_SUBSEC_TIME,+ ExifInterface.TAG_SUBSEC_TIME_ORIGINAL,+ ExifInterface.TAG_SUBSEC_TIME_DIGITIZED,+ ExifInterface.TAG_MAKE,+ ExifInterface.TAG_MODEL,+ ExifInterface.TAG_SOFTWARE,+ ExifInterface.TAG_F_NUMBER,+ ExifInterface.TAG_EXPOSURE_TIME,+ ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY,+ ExifInterface.TAG_FOCAL_LENGTH,+ ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM,+ ExifInterface.TAG_APERTURE_VALUE,+ ExifInterface.TAG_SHUTTER_SPEED_VALUE,+ ExifInterface.TAG_EXPOSURE_BIAS_VALUE,+ ExifInterface.TAG_MAX_APERTURE_VALUE,+ ExifInterface.TAG_METERING_MODE,+ ExifInterface.TAG_EXPOSURE_PROGRAM,+ ExifInterface.TAG_EXPOSURE_MODE,+ ExifInterface.TAG_WHITE_BALANCE,+ ExifInterface.TAG_LIGHT_SOURCE,+ ExifInterface.TAG_FLASH,+ ExifInterface.TAG_SCENE_CAPTURE_TYPE,+ ExifInterface.TAG_DIGITAL_ZOOM_RATIO,+)
camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.ktindex 17e75537c6..8660f07f68 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -165,3 +165,9 @@ internal class ManualLifecycleOwner : LifecycleOwner { registry.currentState = Lifecycle.State.DESTROYED } }++/** One [CameraViewModel.zslCompatible] input sample: wanted value plus whether a shot is in flight. */+internal class ZslGate(val compatible: Boolean, val capturing: Boolean)++/** One [CameraViewModel.bindTimeSettings] input sample: desired settings plus recording state. */+internal class BindSettingsGate(val settings: BindTimeSettings, val recording: Boolean)
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 7d229b2cca..3a77eae3dc 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@@ -35,7 +35,7 @@ import android.view.Surface */ class Camera2Session( private val driver: Camera2Driver,- private val executor: Camera2Executor,+ internal val executor: Camera2Executor, private val snapshot: LensCharacteristicsSnapshot, private val stateMachine: SessionStateMachine = SessionStateMachine(), private val listener: Listener? = null,@@ -88,12 +88,12 @@ class Camera2Session( private val rawRing = ReprocessRing<RawHeldFrame>(rawRingConfig.capacity) private var latestPreviewTimestampNs: Long? = null private val previewMetas = LinkedHashMap<Long, RawStillMetadata>()- private var pendingStill: PendingStill? = null+ internal 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(+ internal class PendingStill( val params: ResolvedStillParams, val callback: StillCallback, val tag: StillOutputTag = StillOutputTag.JPEG,@@ -490,6 +490,8 @@ class Camera2Session( }.onFailure { failPending(pending, "captureStill failed: ${it.message}") } } + // Still byte/result pairing + delivery lives in Camera2SessionStillDelivery.kt.+ private fun onRingFrame(frame: RingHeldFrame) { try { executor.execute {@@ -536,71 +538,6 @@ class Camera2Session( rawRing.attachMetadata(timestamp, raw.exposureTimeNs, raw.frameNumber, raw.aeState, raw.iso) } - 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) {- onStillBytesAvailable(bytes, width, height, StillOutputTag.JPEG)- }-- private fun onUltraHdrJpegAvailable(bytes: ByteArray, width: Int, height: Int) {- onStillBytesAvailable(bytes, width, height, StillOutputTag.ULTRA_HDR_JPEG_R)- }-- private fun onStillBytesAvailable(bytes: ByteArray, width: Int, height: Int, tag: StillOutputTag) {- try {- executor.execute {- val pending = pendingStill ?: return@execute- // Bytes from the output the pending capture did not target- // are not this still (both readers share the session).- if (pending.tag != tag) 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,- ),- tag = pending.tag,- ),- )- }-- 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
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionStillDelivery.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionStillDelivery.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionStillDelivery.ktnew file mode 100644index 0000000000..e412a3cda3--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2SessionStillDelivery.kt@@ -0,0 +1,80 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Still-delivery plumbing for [Camera2Session]: pairing the JPEG bytes+ * and the capture-result metadata of an in-flight still (they arrive+ * independently, by output tag) and delivering or failing the pending+ * capture exactly once. Moved verbatim from the session as extensions;+ * all state is touched only on the session executor, as before.+ */++internal fun Camera2Session.onStillResult(pending: Camera2Session.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.+ }+}++internal fun Camera2Session.onJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+ onStillBytesAvailable(bytes, width, height, StillOutputTag.JPEG)+}++internal fun Camera2Session.onUltraHdrJpegAvailable(bytes: ByteArray, width: Int, height: Int) {+ onStillBytesAvailable(bytes, width, height, StillOutputTag.ULTRA_HDR_JPEG_R)+}++internal fun Camera2Session.onStillBytesAvailable(+ bytes: ByteArray,+ width: Int,+ height: Int,+ tag: StillOutputTag,+) {+ try {+ executor.execute {+ val pending = pendingStill ?: return@execute+ // Bytes from the output the pending capture did not target+ // are not this still (both readers share the session).+ if (pending.tag != tag) return@execute+ pending.jpegBytes = bytes+ pending.jpegWidth = width+ pending.jpegHeight = height+ deliverPendingIfReady(pending)+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ }+}++internal fun Camera2Session.deliverPendingIfReady(pending: Camera2Session.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,+ ),+ tag = pending.tag,+ ),+ )+}++internal fun Camera2Session.failPending(pending: Camera2Session.PendingStill, message: String) {+ try {+ executor.execute {+ if (pendingStill !== pending) return@execute+ pendingStill = null+ pending.callback.onStillFailed(message)+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.ktindex 1c96557c10..05902cee74 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraBottomControls.kt@@ -11,6 +11,8 @@ import androidx.compose.ui.platform.LocalContext import com.vayunmathur.camera.Route import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.flipCamera+import com.vayunmathur.camera.platform.switchCameraMode import com.vayunmathur.camera.platform.captureVideoSnapshot import com.vayunmathur.camera.platform.startBurst import com.vayunmathur.camera.platform.stopBurst
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 c80b7bf4de..5fd53055c1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -7,12 +7,7 @@ import android.graphics.RenderEffect import android.graphics.RuntimeShader import android.graphics.Shader import android.os.Build-import androidx.camera.core.DynamicRange-import androidx.camera.compose.CameraXViewfinder import androidx.camera.viewfinder.compose.MutableCoordinateTransformer-import androidx.camera.viewfinder.core.ImplementationMode-import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.BoxWithConstraintsScope import androidx.compose.foundation.layout.aspectRatio@@ -20,17 +15,13 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable-import androidx.compose.runtime.DisposableEffect-import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds-import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposeRenderEffect import androidx.compose.ui.graphics.graphicsLayer-import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.log.Log@@ -48,17 +39,13 @@ 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+import com.vayunmathur.camera.platform.selectLens import com.vayunmathur.camera.platform.setZoomRatio-import com.vayunmathur.camera.platform.retrySessionBind import com.vayunmathur.camera.platform.toggleNightModeOverride import com.vayunmathur.camera.R-import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.rememberMessenger-import com.vayunmathur.library.ui.R as UiR /** Maps the CameraX selector facing int to the pure lens-facing model. */ private fun currentLensFacing(selectorInt: Int): com.vayunmathur.camera.domain.LensFacing =@@ -199,103 +186,13 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( } ) - if (useCamera2Preview) {- // Camera2 preview behind gate (CameraScreenState.useCamera2Preview, PHOTO only).- // TextureView-backed, same overlay tree / RenderEffects below.- // Guard: never compose with empty cameraId — fall back to CameraX black/error branch below.- val camera2Id = state.selectedLens?.logicalCameraId.orEmpty()- if (camera2Id.isNotEmpty()) {- Camera2Preview(- cameraId = camera2Id,- 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)- },- onError = { viewModel.onCamera2PreviewFailed(camera2Id) },- modifier = previewModifier,- )- } else {- Box(modifier = previewModifier.background(Color.Black))- }- }- if (!useCamera2Preview) {- surfaceRequest?.let { request ->- LaunchedEffect(request) {- Log.dev("NightPreview", "CameraXViewfinder COMPOSED with request res=${request.resolution} dynamicRange=${request.dynamicRange} useNightPreview=${state.useNightPreview} sessionKind=${state.sessionKind} zoomRatio=${state.zoomRatio} levels=${state.availableZoomLevels} thread=${Thread.currentThread().name}")- }- DisposableEffect(request) {- Log.dev("NightPreview", "CameraXViewfinder DisposableEffect ATTACH request res=${request.resolution} useNightPreview=${state.useNightPreview}")- onDispose {- Log.dev("NightPreview", "CameraXViewfinder DisposableEffect DETACH request res=${request.resolution} useNightPreview=${state.useNightPreview} – surface will be invalidated, if next request fails to emit we go black")- }- }- CameraXViewfinder(- surfaceRequest = request,- modifier = previewModifier,- // HDR (HLG 10-bit) video previews must render through a SurfaceView- // (EXTERNAL): the EMBEDDED/TextureView path doesn't tone-map the BT.2020- // HLG buffer, which shows up as a reddish/pink cast in video mode. SDR- // (photo) stays EMBEDDED so graphicsLayer RenderEffects (warmth, bokeh)- // still composite onto the preview.- implementationMode = if (- request.dynamicRange.bitDepth != DynamicRange.BIT_DEPTH_8_BIT- ) {- ImplementationMode.EXTERNAL- } else {- ImplementationMode.EMBEDDED- },- coordinateTransformer = coordinateTransformer,- alignment = Alignment.Center,- // Crop (fill) so the camera feed fills the ratio-shaped box for the- // selected aspect ratio (1:1 / 3:2 / 16:9 / 4:3). Fit letterboxed the native- // 4:3 frame inside the box, making the preview shrink instead of reshape.- contentScale = ContentScale.Crop,- // Pinch-to-zoom stays built-in (1.7.0-alpha02); we just sync the- // displayed zoom ratio so the zoom bar stays in step. Tap-to-focus- // is DISABLED here — it is handled by the tapToFocus modifier on- // previewModifier above, which shows the focus ring and observes- // (and falls back from) the metering result. Leaving both enabled- // double-metered every tap and let the built-in detector swallow- // taps the app never saw.- isTapToFocusEnabled = false,- isPinchToZoomEnabled = true,- onZoomRatioChanged = { ratio -> viewModel.onViewfinderZoomRatio(ratio) },- // CameraX owns the screen-flash UI (white overlay + window brightness):- // hand its ScreenFlash to the ViewModel so ImageCapture can invoke it- // for front captures on lenses with no flash unit. Never hand-roll- // brightness here.- onScreenFlashReady = { screenFlash -> viewModel.setScreenFlash(screenFlash) },- )- }- if (!useCamera2Preview && surfaceRequest == null) {- if (state.sessionBindFailed) {- // Bind exhausted its retries: a visible, retryable error instead- // of parking on a black preview until the next mode/lens change.- Box(modifier = previewModifier.background(Color.Black), contentAlignment = Alignment.Center) {- ErrorState(- title = stringResource(R.string.camera_bind_failed_title),- message = stringResource(R.string.camera_bind_failed_message),- retryLabel = stringResource(UiR.string.retry),- onRetry = { viewModel.retrySessionBind() },- )- }- } else {- // Brief gap between a mode's teardown and the next session's first frame.- // Show a plain black fill (no debug text) so the switch reads as instant.- Box(modifier = previewModifier.background(Color.Black))- }- }- }+ CameraPreviewSurface(+ state = state,+ viewModel = viewModel,+ previewModifier = previewModifier,+ coordinateTransformer = coordinateTransformer,+ )+ CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp))) CameraPreviewOverlays(
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.ktnew file mode 100644index 0000000000..33bad619ef--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -0,0 +1,141 @@+package com.vayunmathur.camera.ui++import androidx.camera.core.DynamicRange+import androidx.camera.compose.CameraXViewfinder+import androidx.camera.viewfinder.compose.MutableCoordinateTransformer+import androidx.camera.viewfinder.core.ImplementationMode+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import com.vayunmathur.camera.R+import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.onCamera2PreviewFailed+import com.vayunmathur.camera.platform.onViewfinderZoomRatio+import com.vayunmathur.camera.platform.retrySessionBind+import com.vayunmathur.camera.platform.registerCamera2Session+import com.vayunmathur.camera.platform.setScreenFlash+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.R as UiR++/**+ * The viewfinder surface itself: the gated Camera2 preview when the+ * Camera2 engine serves, otherwise the CameraX viewfinder (or the+ * bind-failed / black fallback box). Extracted verbatim from+ * [CameraPreviewBox]; overlays, effects and gestures stay with the caller.+ */+@Composable+internal fun CameraPreviewSurface(+ state: CameraScreenState,+ viewModel: CameraViewModel,+ previewModifier: Modifier,+ coordinateTransformer: MutableCoordinateTransformer,+) {+ val useCamera2Preview = state.useCamera2Preview+ val surfaceRequest = state.surfaceRequest++ if (useCamera2Preview) {+ // Camera2 preview behind gate (CameraScreenState.useCamera2Preview, PHOTO only).+ // TextureView-backed, same overlay tree / RenderEffects below.+ // Guard: never compose with empty cameraId — fall back to CameraX black/error branch below.+ val camera2Id = state.selectedLens?.logicalCameraId.orEmpty()+ if (camera2Id.isNotEmpty()) {+ Camera2Preview(+ cameraId = camera2Id,+ 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)+ },+ onError = { viewModel.onCamera2PreviewFailed(camera2Id) },+ modifier = previewModifier,+ )+ } else {+ Box(modifier = previewModifier.background(Color.Black))+ }+ }+ if (!useCamera2Preview) {+ surfaceRequest?.let { request ->+ LaunchedEffect(request) {+ Log.dev("NightPreview", "CameraXViewfinder COMPOSED with request res=${request.resolution} dynamicRange=${request.dynamicRange} useNightPreview=${state.useNightPreview} sessionKind=${state.sessionKind} zoomRatio=${state.zoomRatio} levels=${state.availableZoomLevels} thread=${Thread.currentThread().name}")+ }+ DisposableEffect(request) {+ Log.dev("NightPreview", "CameraXViewfinder DisposableEffect ATTACH request res=${request.resolution} useNightPreview=${state.useNightPreview}")+ onDispose {+ Log.dev("NightPreview", "CameraXViewfinder DisposableEffect DETACH request res=${request.resolution} useNightPreview=${state.useNightPreview} – surface will be invalidated, if next request fails to emit we go black")+ }+ }+ CameraXViewfinder(+ surfaceRequest = request,+ modifier = previewModifier,+ // HDR (HLG 10-bit) video previews must render through a SurfaceView+ // (EXTERNAL): the EMBEDDED/TextureView path doesn't tone-map the BT.2020+ // HLG buffer, which shows up as a reddish/pink cast in video mode. SDR+ // (photo) stays EMBEDDED so graphicsLayer RenderEffects (warmth, bokeh)+ // still composite onto the preview.+ implementationMode = if (+ request.dynamicRange.bitDepth != DynamicRange.BIT_DEPTH_8_BIT+ ) {+ ImplementationMode.EXTERNAL+ } else {+ ImplementationMode.EMBEDDED+ },+ coordinateTransformer = coordinateTransformer,+ alignment = Alignment.Center,+ // Crop (fill) so the camera feed fills the ratio-shaped box for the+ // selected aspect ratio (1:1 / 3:2 / 16:9 / 4:3). Fit letterboxed the native+ // 4:3 frame inside the box, making the preview shrink instead of reshape.+ contentScale = ContentScale.Crop,+ // Pinch-to-zoom stays built-in (1.7.0-alpha02); we just sync the+ // displayed zoom ratio so the zoom bar stays in step. Tap-to-focus+ // is DISABLED here — it is handled by the tapToFocus modifier on+ // previewModifier above, which shows the focus ring and observes+ // (and falls back from) the metering result. Leaving both enabled+ // double-metered every tap and let the built-in detector swallow+ // taps the app never saw.+ isTapToFocusEnabled = false,+ isPinchToZoomEnabled = true,+ onZoomRatioChanged = { ratio -> viewModel.onViewfinderZoomRatio(ratio) },+ // CameraX owns the screen-flash UI (white overlay + window brightness):+ // hand its ScreenFlash to the ViewModel so ImageCapture can invoke it+ // for front captures on lenses with no flash unit. Never hand-roll+ // brightness here.+ onScreenFlashReady = { screenFlash -> viewModel.setScreenFlash(screenFlash) },+ )+ }+ if (!useCamera2Preview && surfaceRequest == null) {+ if (state.sessionBindFailed) {+ // Bind exhausted its retries: a visible, retryable error instead+ // of parking on a black preview until the next mode/lens change.+ Box(modifier = previewModifier.background(Color.Black), contentAlignment = Alignment.Center) {+ ErrorState(+ title = stringResource(R.string.camera_bind_failed_title),+ message = stringResource(R.string.camera_bind_failed_message),+ retryLabel = stringResource(UiR.string.retry),+ onRetry = { viewModel.retrySessionBind() },+ )+ }+ } else {+ // Brief gap between a mode's teardown and the next session's first frame.+ // Show a plain black fill (no debug text) so the switch reads as instant.+ Box(modifier = previewModifier.background(Color.Black))+ }+ }+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex c458ee3222..68b97a9221 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -31,6 +31,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.camera.R import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.setCamera2PreviewEnabled import com.vayunmathur.camera.platform.MotionPhotoDuration import com.vayunmathur.camera.data.SafDocuments import com.vayunmathur.camera.data.SaveTarget
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.ktindex 231fcbd276..df783e23fb 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2GateDefaultsTest.kt@@ -7,6 +7,9 @@ import com.vayunmathur.camera.domain.RecordingPathInput import com.vayunmathur.camera.domain.RecordingPathPolicy import com.vayunmathur.camera.platform.CameraMode import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.clearCamera2Fallback+import com.vayunmathur.camera.platform.onCamera2PreviewFailed+import com.vayunmathur.camera.platform.setCamera2PreviewEnabled import com.vayunmathur.camera.platform.CustomRecordingGate import kotlin.test.assertEquals import kotlin.test.assertFalse