camera: screen flash, video quality, and bind-retry hardening
- Commit
8f603fb8baa0b2c8a281a51abcee3be7edd2fe43- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 16:06 UTC (15 days ago)
- Parents
a864708
Three camera fixes landed together in one tree state. Screen flash: front lenses without an LED offered no flash; FlashModePolicy now resolves hardware vs CameraX FLASH_MODE_SCREEN per lens (viewfinder overlay handles flash and brightness), back lenses byte-identical to before. Video quality: normal VIDEO mode now probes and enables preview+video stabilization (was Cinematic-only); the Recorder gets an explicit bitrate ladder (UHD 48/FHD 25/HD 12/ SD 6 Mbps) instead of encoder defaults; stills set HIGH_QUALITY noise-reduction/edge/tonemap explicitly when on instead of leaving HAL defaults; audio codec is a persisted AAC/Opus setting (Opus only when the encoder exists) at 128kbps stereo instead of a hardcoded useOpus=false. Bind hardening: a failed session bind retried forever-black; it now retries twice with teardown between attempts, then shows a Camera-couldn't-start ErrorState with manual retry, superseded by any key change. Torch state is re-asserted after rebinds (was: UI lit, hardware off). Verified: full camera suite 561 tests green, lint green.
Diff
camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.ktindex ff9937f3fb..2dcbe4449e 100644--- a/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt+++ b/camera/src/main/java/com/vayunmathur/camera/data/CameraSettings.kt@@ -8,6 +8,7 @@ import androidx.core.net.toUri import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import com.vayunmathur.camera.platform.AspectRatioOption+import com.vayunmathur.camera.platform.AudioCodec import com.vayunmathur.camera.platform.AudioInputSource import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.CodecSupport@@ -52,6 +53,13 @@ private fun CameraViewModel.loadCaptureSettings() { AudioInputSource.CAMCORDER } }+ ds.getString("camera_audio_codec")?.let {+ audioCodecMutable.value = try {+ AudioCodec.valueOf(it)+ } catch (_: Exception) {+ AudioCodec.AAC+ }+ } loadSaveTarget() // Guard against a blank persisted value: Uri.parse("") yields a non-null ds.getString("camera_last_capture")?.takeIf { it.isNotBlank() }?.let { lastCaptureUriMutable.value = it.toUri() }@@ -148,6 +156,11 @@ fun CameraViewModel.setMotionPhotoDuration(duration: MotionPhotoDuration) { viewModelScope.launch { ds.setString("camera_motion_duration", duration.name) } } +fun CameraViewModel.setAudioCodec(codec: AudioCodec) {+ audioCodecMutable.value = codec+ viewModelScope.launch { ds.setString("camera_audio_codec", codec.name) }+}+ fun CameraViewModel.setAudioInputSource(source: AudioInputSource) { audioInputSourceMutable.value = source viewModelScope.launch { ds.setString("camera_audio_source", source.name) }
camera/src/main/java/com/vayunmathur/camera/domain/FlashModePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/FlashModePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/domain/FlashModePolicy.ktnew file mode 100644index 0000000000..a3993a2d03--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/FlashModePolicy.kt@@ -0,0 +1,43 @@+package com.vayunmathur.camera.domain++/** User-selected still-flash behaviour, mirrored from the platform `FlashMode`. */+enum class FlashSetting { OFF, ON, AUTO }++/**+ * How a still capture is actually illuminated once the lens is known.+ *+ * [HARDWARE] drives the LED flash unit; [SCREEN] lights the display instead+ * (CameraX `FLASH_MODE_SCREEN` + a `ScreenFlash`); [NONE] fires no flash.+ */+enum class FlashResolution { NONE, HARDWARE, SCREEN }++/**+ * Resolves the user's flash setting against the bound lens.+ *+ * A front lens with no flash unit has no LED to drive, so ON/AUTO fall back+ * to the screen flash instead of silently capturing dark. A lens with a+ * real unit (the usual back camera) always keeps the hardware flash, and+ * OFF never illuminates on either facing. Screen flash is front-only:+ * CameraX rejects `FLASH_MODE_SCREEN` for a back camera.+ */+object FlashModePolicy {++ /** True when this lens can only flash via the screen (front, no LED unit). */+ fun usesScreenFlash(facing: LensFacing, hasFlashUnit: Boolean): Boolean =+ facing == LensFacing.FRONT && !hasFlashUnit++ /** The flash control is worth showing when either flash kind can fire. */+ fun showFlashControl(facing: LensFacing, hasFlashUnit: Boolean): Boolean =+ hasFlashUnit || usesScreenFlash(facing, hasFlashUnit)++ /** Maps the user setting + lens to the illumination a capture must use. */+ fun resolve(facing: LensFacing, hasFlashUnit: Boolean, setting: FlashSetting): FlashResolution =+ when (setting) {+ FlashSetting.OFF -> FlashResolution.NONE+ FlashSetting.ON, FlashSetting.AUTO -> if (usesScreenFlash(facing, hasFlashUnit)) {+ FlashResolution.SCREEN+ } else {+ FlashResolution.HARDWARE+ }+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.ktindex 1081fc5af6..92d811afea 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt@@ -46,6 +46,7 @@ suspend fun CameraViewModel.refreshCapabilities(bound: Camera, lensId: String?) readManualControlRanges() reapplyCaptureControls()+ reapplyTorch(bound) val hasFlash = readFlashUnit(bound) hasFlashUnitMutable.value = hasFlash@@ -110,6 +111,26 @@ private fun CameraViewModel.reapplyCaptureControls() { } } +/**+ * Re-asserts the UI's torch state onto the fresh bind. The session effect+ * only calls `enableTorch` when `torchEnabled` changes, so a mode/lens+ * rebind (which resets the hardware torch) left the UI lit with the torch+ * off until the user toggled it twice.+ */+private fun CameraViewModel.reapplyTorch(bound: Camera) {+ try {+ bound.cameraControl.enableTorch(torchEnabledMutable.value)+ } catch (e: IllegalStateException) {+ Log.status("LensSelector", "Could not re-apply torch", e)+ } catch (e: IllegalArgumentException) {+ Log.status("LensSelector", "Could not re-apply torch", e)+ } catch (e: NullPointerException) {+ // Fake controls in unit tests return a null future for enableTorch;+ // a real bind always returns one, so this is "unavailable", not a crash.+ Log.status("LensSelector", "Could not re-apply torch", e)+ }+}+ /** Flash-unit availability; keeps the previous value when unreadable. */ private fun CameraViewModel.readFlashUnit(bound: Camera): Boolean { return try {
camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.ktindex 65d89471dc..82f2a076ec 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraControls.kt@@ -211,9 +211,25 @@ fun CameraViewModel.applyExposureCompensation(value: Float) { cam.cameraControl.setExposureCompensationIndex(index) } -/** Pushes the current flash mode onto the bound ImageCapture (runtime-mutable, no rebind). */+/**+ * Pushes the current flash mode onto the bound ImageCapture (runtime-mutable, no rebind).+ * The ScreenFlash is attached first (and cleared on hardware lenses) so a+ * FLASH_MODE_SCREEN capture never fires without its UI mechanism in place.+ */ fun CameraViewModel.applyImageCaptureFlashMode() {- imageCapture?.flashMode = getImageCaptureFlashMode()+ val capture = imageCapture ?: return+ capture.setScreenFlash(getScreenFlashForCapture())+ capture.flashMode = getImageCaptureFlashMode()+}++/**+ * Receives the [androidx.camera.core.ImageCapture.ScreenFlash] created by+ * the Compose viewfinder (its overlay + window-brightness mechanism) and+ * re-applies it to the bound capture. Brightness is CameraX's job, not ours.+ */+fun CameraViewModel.setScreenFlash(screenFlash: androidx.camera.core.ImageCapture.ScreenFlash?) {+ this.screenFlash = screenFlash+ applyImageCaptureFlashMode() } /** Swaps the analyzer on the bound ImageAnalysis without rebinding. */
camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.ktindex a79f4189b8..86f31f5dd2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraManualControls.kt@@ -117,20 +117,38 @@ fun CameraViewModel.applyManualControls() { } // Post-processing toggles (issue #662): OFF explicitly disables the HAL's noise- // reduction / edge sharpening. When enabled the keys are left unset so the HAL- // keeps its default behavior.- if (!noiseReductionEnabledMutable.value) {+ // reduction / edge sharpening. ON now explicitly requests the high-quality+ // modes instead of leaving the keys unset, where the HAL default may be+ // FAST. Tonemap joins the high-quality request when either toggle is on,+ // so turning both off does not force a high-quality tonemap either.+ if (noiseReductionEnabledMutable.value) {+ builder.setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.NOISE_REDUCTION_MODE,+ android.hardware.camera2.CameraMetadata.NOISE_REDUCTION_MODE_HIGH_QUALITY+ )+ } else { builder.setCaptureRequestOption( android.hardware.camera2.CaptureRequest.NOISE_REDUCTION_MODE, android.hardware.camera2.CameraMetadata.NOISE_REDUCTION_MODE_OFF ) }- if (!edgeSharpeningEnabledMutable.value) {+ if (edgeSharpeningEnabledMutable.value) {+ builder.setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.EDGE_MODE,+ android.hardware.camera2.CameraMetadata.EDGE_MODE_HIGH_QUALITY+ )+ } else { builder.setCaptureRequestOption( android.hardware.camera2.CaptureRequest.EDGE_MODE, android.hardware.camera2.CameraMetadata.EDGE_MODE_OFF ) }+ if (noiseReductionEnabledMutable.value || edgeSharpeningEnabledMutable.value) {+ builder.setCaptureRequestOption(+ android.hardware.camera2.CaptureRequest.TONEMAP_MODE,+ android.hardware.camera2.CameraMetadata.TONEMAP_MODE_HIGH_QUALITY+ )+ } try { // An empty options set clears any previously-applied manual 3A → full auto.
camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.ktindex 4536f02353..e9e681af31 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraNightCapture.kt@@ -79,6 +79,7 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() { .setFlashMode(getImageCaptureFlashMode()) .build() imageCapture = capture+ capture.setScreenFlash(getScreenFlashForCapture()) // Match the still crop the normal photo session uses (1:1 / 3:2 / 16:9 / 4:3), or // night-extension shots always save full-frame while the preview shows cropped. capture.setCropAspectRatio(currentCropAspectRatio())
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessionSetup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessionSetup.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessionSetup.ktindex 8aa4789a34..2996cd3e76 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessionSetup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessionSetup.kt@@ -243,6 +243,8 @@ internal fun CameraViewModel.buildPhotoCapture( .setCaptureMode( if (zsl) ImageCapture.CAPTURE_MODE_ZERO_SHUTTER_LAG else ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY )+ // Builder.setScreenFlash is @NonNull; the instance setter (nullable) runs in applyImageCaptureFlashMode.+ getScreenFlashForCapture()?.let { captureBuilder.setScreenFlash(it) } if (ultraHdr) { captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR) }
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessions.ktindex 190b7bf488..215e675af7 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoSessions.kt@@ -132,6 +132,7 @@ internal suspend fun CameraViewModel.prepareNightPreview(): NightPreviewPrep? { .setFlashMode(getImageCaptureFlashMode()) .build() imageCapture = capture+ capture.setScreenFlash(getScreenFlashForCapture()) return NightPreviewPrep( provider, mgr,
camera/src/main/java/com/vayunmathur/camera/platform/CameraPortraitSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPortraitSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPortraitSession.ktindex 8b119f9005..775752ff19 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPortraitSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPortraitSession.kt@@ -319,6 +319,8 @@ internal fun CameraViewModel.buildPortraitCapture(maxResCapture: Boolean, ultraH val captureBuilder = ImageCapture.Builder() .setResolutionSelector(captureSelectorBuilder.build()) .setFlashMode(getImageCaptureFlashMode())+ // Builder.setScreenFlash is @NonNull; the instance setter (nullable) runs in applyImageCaptureFlashMode.+ getScreenFlashForCapture()?.let { captureBuilder.setScreenFlash(it) } if (ultraHdr) { captureBuilder.setOutputFormat(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR) }
camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.ktindex 51669cb1de..b827842cf4 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraSessions.kt@@ -11,6 +11,7 @@ import androidx.camera.core.SessionConfig import androidx.camera.core.UseCase import androidx.camera.lifecycle.ProcessCameraProvider import androidx.lifecycle.LifecycleOwner+import kotlinx.coroutines.delay /** * Binds [useCases] via a [SessionConfig] with auto-rotation enabled, so CameraX applies the@@ -28,6 +29,44 @@ internal fun CameraViewModel.bindSession( SessionConfig.Builder(*useCases).setAutoRotationEnabled(true).build(), ) +/** Bounded bind retries after the first attempt (3 attempts in total). */+internal const val SESSION_BIND_MAX_RETRIES = 2++/** Pause between bind retries: long enough for a transient HAL teardown to settle. */+internal const val SESSION_BIND_RETRY_DELAY_MS = 300L++/**+ * Runs [bind] until it succeeds or [maxRetries] retries are exhausted, waiting+ * [retryDelayMs] (via [delayFn]) between attempts. Cancellation is never+ * swallowed: a [kotlinx.coroutines.CancellationException] from [bind] or+ * [delayFn] propagates, so a session-effect key change (mode/lens/lifecycle)+ * supersedes an in-progress retry ladder immediately.+ */+internal suspend fun runSessionBindWithRetry(+ maxRetries: Int = SESSION_BIND_MAX_RETRIES,+ retryDelayMs: Long = SESSION_BIND_RETRY_DELAY_MS,+ delayFn: suspend (Long) -> Unit = { delay(it) },+ bind: suspend () -> Boolean,+): Boolean {+ var retriesLeft = maxRetries+ while (true) {+ if (bind()) return true+ if (retriesLeft <= 0) return false+ retriesLeft--+ delayFn(retryDelayMs)+ }+}++/**+ * Manual retry after a bind exhausted its retries: clears the failure so the+ * preview placeholder returns, then bumps the retry counter the session+ * effect is keyed on, which cancels the parked effect and rebinds.+ */+fun CameraViewModel.retrySessionBind() {+ sessionBindFailedMutable.value = false+ sessionBindRetryMutable.value += 1+}+ /** Tears down whatever session is currently bound and clears the shared preview surface. */ fun CameraViewModel.teardownSession() { sessionTeardownCount++@@ -266,12 +305,58 @@ internal fun <T> CameraViewModel.applyVideoCaptureRequestOptions( } } -fun CameraViewModel.getImageCaptureFlashMode(): Int = when (flashModeMutable.value) {- FlashMode.ON -> ImageCapture.FLASH_MODE_ON- FlashMode.OFF -> ImageCapture.FLASH_MODE_OFF- FlashMode.AUTO -> ImageCapture.FLASH_MODE_AUTO+/** The pure lens-facing model for the currently selected facing. */+internal fun CameraViewModel.currentLensFacing(): com.vayunmathur.camera.domain.LensFacing =+ if (lensFacingMutable.value == CameraSelector.LENS_FACING_FRONT) {+ com.vayunmathur.camera.domain.LensFacing.FRONT+ } else {+ com.vayunmathur.camera.domain.LensFacing.BACK+ }++private fun FlashMode.toFlashSetting(): com.vayunmathur.camera.domain.FlashSetting = when (this) {+ FlashMode.ON -> com.vayunmathur.camera.domain.FlashSetting.ON+ FlashMode.OFF -> com.vayunmathur.camera.domain.FlashSetting.OFF+ FlashMode.AUTO -> com.vayunmathur.camera.domain.FlashSetting.AUTO } +/** How the next still will be illuminated for the bound lens + user setting. */+internal fun CameraViewModel.currentFlashResolution(): com.vayunmathur.camera.domain.FlashResolution =+ com.vayunmathur.camera.domain.FlashModePolicy.resolve(+ currentLensFacing(),+ hasFlashUnitMutable.value,+ flashModeMutable.value.toFlashSetting(),+ )++/**+ * The CameraX flash mode for the next still. A front lens with no flash+ * unit resolves ON/AUTO to [ImageCapture.FLASH_MODE_SCREEN] (display as+ * flash); a lens with a real unit keeps the hardware modes exactly as+ * before. CameraX rejects FLASH_MODE_SCREEN on a back camera, which the+ * policy can never produce (screen is front-only).+ */+fun CameraViewModel.getImageCaptureFlashMode(): Int =+ when (currentFlashResolution()) {+ com.vayunmathur.camera.domain.FlashResolution.SCREEN -> ImageCapture.FLASH_MODE_SCREEN+ com.vayunmathur.camera.domain.FlashResolution.NONE -> ImageCapture.FLASH_MODE_OFF+ com.vayunmathur.camera.domain.FlashResolution.HARDWARE -> when (flashModeMutable.value) {+ FlashMode.ON -> ImageCapture.FLASH_MODE_ON+ FlashMode.AUTO -> ImageCapture.FLASH_MODE_AUTO+ FlashMode.OFF -> ImageCapture.FLASH_MODE_OFF+ }+ }++/**+ * The viewfinder-provided [ImageCapture.ScreenFlash] to attach to a still+ * capture, or null unless the resolution is SCREEN. Null also clears a+ * stale instance when flipping back to a hardware-flash lens.+ */+internal fun CameraViewModel.getScreenFlashForCapture(): ImageCapture.ScreenFlash? =+ if (currentFlashResolution() == com.vayunmathur.camera.domain.FlashResolution.SCREEN) {+ screenFlash+ } else {+ null+ }+ /** * Best-effort unbind used inside bind-retry catch blocks: logs (with [tag]) instead of * throwing so the retry ladder keeps walking the lens list.
camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.ktindex 0c95a990a6..fa493aaab2 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraVideoSession.kt@@ -36,6 +36,33 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean { } } +/** Explicit video bitrate ladder, bits per second. */+private const val VIDEO_BITRATE_UHD_BPS = 48_000_000+private const val VIDEO_BITRATE_FHD_BPS = 25_000_000+private const val VIDEO_BITRATE_HD_BPS = 12_000_000+private const val VIDEO_BITRATE_SD_BPS = 6_000_000++/** Explicit recording audio: 128 kbps stereo, for AAC and Opus alike. */+private const val AUDIO_BITRATE_BPS = 128_000+private const val AUDIO_CHANNEL_COUNT = 2++/**+ * Bitrate for [quality], scaled by pixel count at the fixed 30 fps video rate:+ * UHD (3840x2160, 8.3 MP) at 48 Mbps, FHD (1920x1080, 2.1 MP) at 25 Mbps,+ * HD (1280x720, 0.9 MP) at 12 Mbps, SD at 6 Mbps. Each step roughly halves+ * with the pixel count, keeping bits per pixel in the same high-quality+ * band instead of leaving the encoder at its macro-block-prone default.+ * Unknown/unprobeable quality falls back to the FHD rung: high enough for+ * HD/FHD, low enough that UHD-only encoder ranges are not required.+ */+internal fun videoBitRateForQuality(quality: Quality?): Int = when (quality) {+ Quality.UHD -> VIDEO_BITRATE_UHD_BPS+ Quality.FHD -> VIDEO_BITRATE_FHD_BPS+ Quality.HD -> VIDEO_BITRATE_HD_BPS+ Quality.SD -> VIDEO_BITRATE_SD_BPS+ else -> VIDEO_BITRATE_FHD_BPS+}+ /** Codec/quality choices resolved off the camera info. */ internal data class VideoChoices( val useAv1: Boolean,@@ -44,7 +71,10 @@ internal data class VideoChoices( val hlgSupported: Boolean, val bestFpsRange: android.util.Range<Int>?, val stabilizationMode: Int?,- val qualitySelector: QualitySelector+ val qualitySelector: QualitySelector,+ val videoEncodingBitRate: Int = VIDEO_BITRATE_FHD_BPS,+ val audioEncodingBitRate: Int = AUDIO_BITRATE_BPS,+ val audioChannelCount: Int = AUDIO_CHANNEL_COUNT ) /** Video session scaffolding: provider, lens, owner, choices. */@@ -83,18 +113,26 @@ internal fun CameraViewModel.resolveVideoChoices(cameraInfo: androidx.camera.cor CodecSupport.isHardwareAv1EncoderAvailable && av1SupportedByCamera(cameraInfo) val useHevc = !useAv1 && selectedCodec != VideoCodec.AVC && CodecSupport.isHevcEncoderAvailable && hevcSupportedByCamera(cameraInfo)- val useOpus = false+ // Audio codec follows the user setting with the video-codec fallback style:+ // Opus only when chosen AND the Recorder reports an Opus encoder, else AAC.+ val useOpus = audioCodecMutable.value == AudioCodec.OPUS &&+ CodecSupport.isOpusAudioEncoderAvailable // HLG10 (10-bit HDR) when the camera's video pipeline supports it. Uses the default // HEVC/H.264 codec (AV1 stays off). Preview and VideoCapture must share the dynamic // range or the bind fails, so both are gated together. val hlgSupported = hlgSupportedByCamera(cameraInfo) Log.debug("VideoSession", "Codec selection: av1=$useAv1, hevc=$useHevc, opus=$useOpus, hlg10=$hlgSupported") - // Cinematic mode enables video stabilization; all video modes always record at max- // quality/fps (no UI picker).- val cinematic = cameraModeMutable.value == CameraMode.CINEMATIC+ // Standard and Cinematic video enable stabilization when the device probe+ // reports a mode; other modes (timelapse/slo-mo/photo) leave it unset.+ // All video modes always record at max quality/fps (no UI picker).+ val mode = cameraModeMutable.value val bestFpsRange = highestFpsRange(cameraInfo)- val stabilizationMode = if (cinematic) preferredStabilizationMode(cameraInfo) else null+ val stabilizationMode = if (mode == CameraMode.VIDEO || mode == CameraMode.CINEMATIC) {+ preferredStabilizationMode(cameraInfo)+ } else {+ null+ } Log.debug("VideoSession", "Video tuning: fps=$bestFpsRange, stabilization=$stabilizationMode") // Prefer UHD, then FHD, then HD, falling back to the next lower supported quality.@@ -102,7 +140,45 @@ internal fun CameraViewModel.resolveVideoChoices(cameraInfo: androidx.camera.cor listOf(Quality.UHD, Quality.FHD, Quality.HD), FallbackStrategy.lowerQualityOrHigherThan(Quality.HD) )- return VideoChoices(useAv1, useHevc, useOpus, hlgSupported, bestFpsRange, stabilizationMode, qualitySelector)+ // Explicit bitrate for the highest quality the probe reports, instead of+ // the encoder default. The Recorder is built inside each bind rung, so a+ // device that rejects these encoding options fails that rung and the+ // existing bind ladder (HDR/snapshot x lens) walks on.+ val videoEncodingBitRate = videoBitRateForQuality(+ highestSupportedVideoQuality(cameraInfo, hlgSupported)+ )+ Log.debug("VideoSession", "Video encoding bitrate=$videoEncodingBitRate")+ return VideoChoices(+ useAv1, useHevc, useOpus, hlgSupported, bestFpsRange, stabilizationMode,+ qualitySelector, videoEncodingBitRate = videoEncodingBitRate+ )+}++/**+ * Highest of UHD/FHD/HD/SD in the camera's supported qualities for the+ * recording dynamic range (SDR when HLG is unsupported), or null when the+ * capabilities probe cannot answer - the caller then uses the FHD bitrate.+ */+internal fun CameraViewModel.highestSupportedVideoQuality(+ cameraInfo: androidx.camera.core.CameraInfo,+ hlgSupported: Boolean+): Quality? = try {+ val capabilities = Recorder.getVideoCapabilities(cameraInfo)+ val range = if (hlgSupported) {+ androidx.camera.core.DynamicRange.HLG_10_BIT+ } else {+ androidx.camera.core.DynamicRange.SDR+ }+ val supported = capabilities.getSupportedQualities(range)+ .ifEmpty { capabilities.getSupportedQualities(androidx.camera.core.DynamicRange.SDR) }+ listOf(Quality.UHD, Quality.FHD, Quality.HD, Quality.SD)+ .firstOrNull { supported.contains(it) }+} catch (e: IllegalStateException) {+ Log.status("VideoSession", "Could not query supported video qualities", e)+ null+} catch (e: IllegalArgumentException) {+ Log.status("VideoSession", "Could not query supported video qualities", e)+ null } /**@@ -264,9 +340,13 @@ internal fun CameraViewModel.buildVideoCapture( val recorderBuilder = Recorder.Builder() .setQualitySelector(choices.qualitySelector) .setAudioSource(audioInputSourceMutable.value.specValue)+ .setTargetVideoEncodingBitRate(choices.videoEncodingBitRate)+ .setTargetAudioEncodingBitRate(choices.audioEncodingBitRate)+ .setTargetAudioChannelCount(choices.audioChannelCount) if (choices.useAv1) recorderBuilder.setVideoMimeType(MediaFormat.MIMETYPE_VIDEO_AV1) else if (choices.useHevc) recorderBuilder.setVideoMimeType(MediaFormat.MIMETYPE_VIDEO_HEVC) if (choices.useOpus) recorderBuilder.setAudioMimeType(MediaFormat.MIMETYPE_AUDIO_OPUS)+ else recorderBuilder.setAudioMimeType(MediaFormat.MIMETYPE_AUDIO_AAC) val captureBuilder = VideoCapture.Builder(recorderBuilder.build()) .setMirrorMode( if (mirrorFrontMutable.value) MirrorMode.MIRROR_MODE_ON_FRONT_ONLY
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 fe19431a60..755c95a1f4 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -202,6 +202,11 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val audioInputSourceMutable = MutableStateFlow(AudioInputSource.CAMCORDER) val audioInputSource = audioInputSourceMutable.asStateFlow() + // Recording audio codec. Default AAC preserves the long-standing Recorder+ // default; Opus is opt-in and only used when the Recorder reports support.+ internal val audioCodecMutable = MutableStateFlow(AudioCodec.AAC)+ val audioCodec = audioCodecMutable.asStateFlow()+ internal val saveTargetMutable = MutableStateFlow<SaveTarget>(SaveTarget.MediaStoreDefault) val saveTarget = saveTargetMutable.asStateFlow() @@ -458,6 +463,18 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val surfaceRequestMutable = MutableStateFlow<SurfaceRequest?>(null) val surfaceRequest = surfaceRequestMutable.asStateFlow() + // Session bind exhausted its bounded retries: the preview has no surface,+ // so the UI shows an error with a manual retry instead of a black frame.+ // Cleared when a bind succeeds, a bind (re)starts, or a key change+ // supersedes the failed bind.+ internal val sessionBindFailedMutable = MutableStateFlow(false)+ val sessionBindFailed = sessionBindFailedMutable.asStateFlow()++ // Monotonic manual-retry counter: bumping it is a session-effect key, so+ // a tap re-runs the bind (cancelling the parked failed effect first).+ internal val sessionBindRetryMutable = MutableStateFlow(0)+ val sessionBindRetry = sessionBindRetryMutable.asStateFlow()+ // Monotonic count of teardownSession() calls. The UI session effect owns binding; a // capture-time rebind (captureNightPhotoExtension) snapshots this so its finally-restore // can tell whether the effect already tore down / rebound meanwhile (mode switch, lens@@ -471,6 +488,12 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal var sessionLifecycleOwner: ManualLifecycleOwner? = null internal var boundCamera: Camera? = null internal var imageCapture: ImageCapture? = null++ // The Compose viewfinder's CameraX ScreenFlash (white overlay + window+ // brightness, owned by CameraXViewfinder), handed over via+ // onScreenFlashReady. Attached to ImageCapture only when the front lens+ // has no flash unit and the resolution is SCREEN (see FlashModePolicy).+ internal var screenFlash: ImageCapture.ScreenFlash? = null internal var imageAnalysis: ImageAnalysis? = null // The analyzer the UI wants running, kept across teardown/rebind. Every session bind re-attaches
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 d1de8f29f0..2a6cef193b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelTypes.kt@@ -40,6 +40,24 @@ enum class VideoCodec(@StringRes val labelRes: Int, @StringRes val descriptionRe HEVC(R.string.codec_hevc_label, R.string.codec_hevc_description), AV1(R.string.codec_av1_label, R.string.codec_av1_description), }++/** Audio codecs selectable for video recording, with display text and Recorder mime. */+enum class AudioCodec(+ @StringRes val labelRes: Int,+ @StringRes val descriptionRes: Int,+ val mimeType: String,+) {+ AAC(+ R.string.audio_codec_aac_label,+ R.string.audio_codec_aac_description,+ android.media.MediaFormat.MIMETYPE_AUDIO_AAC,+ ),+ OPUS(+ R.string.audio_codec_opus_label,+ R.string.audio_codec_opus_description,+ android.media.MediaFormat.MIMETYPE_AUDIO_OPUS,+ ),+} /** Motion-Photo clip durations (seconds). */ private const val MOTION_ONE_SECOND = 1 private const val MOTION_THREE_SECONDS = 3
camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.ktindex def6def326..a6c259c6d5 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CodecSupport.kt@@ -22,15 +22,31 @@ object CodecSupport { } } + private val supportedAudioMimeTypes: List<String> by lazy {+ try {+ Recorder.getSupportedAudioMimeTypes()+ } catch (_: Exception) {+ emptyList()+ }+ }+ private fun supports(mimeType: String): Boolean = supportedVideoMimeTypes.any { it.equals(mimeType, ignoreCase = true) } + private fun supportsAudio(mimeType: String): Boolean =+ supportedAudioMimeTypes.any { it.equals(mimeType, ignoreCase = true) }+ /** The Recorder can encode AV1 (`video/av01`) on this device. */ val isHardwareAv1EncoderAvailable: Boolean by lazy { supports(MediaFormat.MIMETYPE_VIDEO_AV1) } /** The Recorder can encode HEVC/H.265 (`video/hevc`) on this device. */ val isHevcEncoderAvailable: Boolean by lazy { supports(MediaFormat.MIMETYPE_VIDEO_HEVC) } + /** The Recorder can encode Opus (`audio/opus`) on this device. */+ val isOpusAudioEncoderAvailable: Boolean by lazy {+ supportsAudio(MediaFormat.MIMETYPE_AUDIO_OPUS)+ }+ /** * Default recording codec (issue #757): HEVC when the Recorder supports it, else AVC. * AV1 hardware encoders stall on several devices, so AV1 stays opt-in via Settings.
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 a53f695eb8..e5bf6d6174 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -31,6 +31,7 @@ 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 import com.vayunmathur.camera.platform.BOKEH_SHADER@@ -47,10 +48,15 @@ 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.setScreenFlash import com.vayunmathur.camera.data.setShadows import com.vayunmathur.camera.data.setWarmth 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.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 =@@ -223,12 +229,30 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( 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 (surfaceRequest == null) {- // 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))+ 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))+ } } CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp)))
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex b8e34278f8..e448192a23 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -111,6 +111,7 @@ fun CameraScreen( flashMode = state.flashMode, torchEnabled = state.torchEnabled, hasFlashUnit = state.hasFlashUnit,+ screenFlashAvailable = state.screenFlashAvailable, gridEnabled = state.gridEnabled, levelEnabled = state.levelEnabled, aspectRatio = state.aspectRatio,
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex 133fc884a0..b7591c31cd 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -26,6 +26,7 @@ import com.vayunmathur.camera.platform.applyImageCaptureFlashMode import com.vayunmathur.camera.platform.enableTorch import com.vayunmathur.camera.platform.onLuminance import com.vayunmathur.camera.platform.refreshNightExtensionUsable+import com.vayunmathur.camera.platform.runSessionBindWithRetry import com.vayunmathur.camera.platform.setBokehAnalyzer import com.vayunmathur.camera.platform.setImageAnalyzer import com.vayunmathur.camera.platform.setPhotoAnalyzer@@ -77,7 +78,10 @@ internal fun CameraScreenEffects( viewModel.updateLocation() } - LaunchedEffect(state.flashMode) {+ // Lens facing / flash-unit changes flip the resolution (hardware <-> screen)+ // without a flashMode change, so they re-apply too; the session rebind that+ // follows picks the same resolution up in its ImageCapture builder.+ LaunchedEffect(state.flashMode, state.lensFacing, state.hasFlashUnit) { viewModel.applyImageCaptureFlashMode() } @@ -244,35 +248,46 @@ internal fun CameraScreenEffects( // manual exposure or night mode makes ZSL unsafe, or safe again (#914). Other kinds ignore it. val zslCompatible by viewModel.zslCompatible.collectAsState() val zslKey = if (sessionKind == SessionKind.PHOTO) zslCompatible else null- LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, zslKey, state.videoCodec, state.audioInputSource, state.mirrorFront, lifecycleOwner) {+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, zslKey, state.videoCodec, state.audioInputSource, state.mirrorFront, state.sessionBindRetry, lifecycleOwner) { Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys zsl=$zslKey lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${state.videoCodec} audio=${state.audioInputSource} mirror=${state.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}") lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {- Log.dev("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()")- viewModel.teardownSession()- // Brief yield so the previous session's surface detaches before the next binds; short- // enough that a mode switch reads as instant, long enough to avoid a bind-over-teardown race.- delay(40)- val bindStart = System.currentTimeMillis()- val bindSuccess = try {- when (sessionKind) {- SessionKind.HIGH_SPEED -> viewModel.setupHighSpeedSession()- SessionKind.VIDEO -> viewModel.setupVideoSession()- SessionKind.PANORAMA -> viewModel.setupPanoramaSession()- SessionKind.PORTRAIT -> viewModel.setupPortraitSession()- SessionKind.PHOTO ->- if (useNightPreview) viewModel.setupNightPreviewSession()- else viewModel.setupPhotoSession()+ // A fresh (re)bind supersedes any earlier exhausted-retry failure.+ viewModel.sessionBindFailedMutable.value = false+ // Bounded retry: a failed setup used to park here on a black+ // preview until the next key change. Retry twice with a short+ // delay (teardown before each attempt clears a partial bind),+ // then surface a visible error with a manual retry instead.+ // Cancellation (key change / lifecycle drop) aborts the ladder.+ val bindSuccess = runSessionBindWithRetry {+ Log.dev("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()")+ viewModel.teardownSession()+ // Brief yield so the previous session's surface detaches before the next binds; short+ // enough that a mode switch reads as instant, long enough to avoid a bind-over-teardown race.+ delay(40)+ val bindStart = System.currentTimeMillis()+ val success = try {+ when (sessionKind) {+ SessionKind.HIGH_SPEED -> viewModel.setupHighSpeedSession()+ SessionKind.VIDEO -> viewModel.setupVideoSession()+ SessionKind.PANORAMA -> viewModel.setupPanoramaSession()+ SessionKind.PORTRAIT -> viewModel.setupPortraitSession()+ SessionKind.PHOTO ->+ if (useNightPreview) viewModel.setupNightPreviewSession()+ else viewModel.setupPhotoSession()+ }+ } catch (e: IllegalStateException) {+ Log.error("NightPreview", "CameraScreen session binding THREW (was not logged before) kind=$sessionKind useNightPreview=$useNightPreview nightExtAvailable=${state.nightExtAvailable}", e)+ false+ } catch (e: IllegalArgumentException) {+ Log.error("NightPreview", "CameraScreen session binding THREW (was not logged before) kind=$sessionKind useNightPreview=$useNightPreview nightExtAvailable=${state.nightExtAvailable}", e)+ false }- } catch (e: IllegalStateException) {- Log.error("NightPreview", "CameraScreen session binding THREW (was not logged before) kind=$sessionKind useNightPreview=$useNightPreview nightExtAvailable=${state.nightExtAvailable}", e)- false- } catch (e: IllegalArgumentException) {- Log.error("NightPreview", "CameraScreen session binding THREW (was not logged before) kind=$sessionKind useNightPreview=$useNightPreview nightExtAvailable=${state.nightExtAvailable}", e)- false+ Log.dev("NightPreview", "CameraScreen session bind finished success=$success took=${System.currentTimeMillis() - bindStart}ms surface after=${viewModel.surfaceRequest.value?.resolution} zoomLevels=${viewModel.availableZoomLevels.value} zoomRatio=${viewModel.zoomRatio.value}")+ success }- Log.dev("NightPreview", "CameraScreen session bind finished success=$bindSuccess took=${System.currentTimeMillis() - bindStart}ms surface after=${viewModel.surfaceRequest.value?.resolution} zoomLevels=${viewModel.availableZoomLevels.value} zoomRatio=${viewModel.zoomRatio.value}") if (!bindSuccess) {- Log.error("NightPreview", "CameraScreen BIND FAILED – this produces solid black preview and zoom bar showing only 1x (fallback?). Check logcat for NightPreview tag – exception was previously swallowed as warning")+ Log.error("NightPreview", "CameraScreen BIND FAILED after retries – showing bind error instead of a solid black preview")+ viewModel.sessionBindFailedMutable.value = true } try { awaitCancellation()
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex b6d9d19333..47287266bf 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -92,6 +92,8 @@ import com.vayunmathur.camera.platform.BokehAnalyzer activeSettingState: MutableState<CameraSetting?>, maskBitmapState: MutableState<Bitmap?>, deviceRotationState: MutableIntState,+ val sessionBindFailed: Boolean = false,+ val sessionBindRetry: Int = 0, ) { var activeSetting by activeSettingState var maskBitmap by maskBitmapState@@ -129,6 +131,16 @@ import com.vayunmathur.camera.platform.BokehAnalyzer } val mirrorPreview get() = lensFacing == CameraSelector.LENS_FACING_FRONT && !mirrorFront++ /** Front lens with no LED unit: stills flash via the screen instead. */+ val screenFlashAvailable get() = com.vayunmathur.camera.domain.FlashModePolicy.usesScreenFlash(+ if (lensFacing == CameraSelector.LENS_FACING_FRONT) {+ com.vayunmathur.camera.domain.LensFacing.FRONT+ } else {+ com.vayunmathur.camera.domain.LensFacing.BACK+ },+ hasFlashUnit,+ ) } @Composable@@ -179,6 +191,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val analysisStreamActive by viewModel.analysisStreamActive.collectAsState() val nightExtAvailable by viewModel.nightExtensionUsable.collectAsState() val surfaceRequest by viewModel.surfaceRequest.collectAsState()+ val sessionBindFailed by viewModel.sessionBindFailed.collectAsState()+ val sessionBindRetry by viewModel.sessionBindRetry.collectAsState() val availableZoomLevels by viewModel.availableZoomLevels.collectAsState() val galleryBitmap by viewModel.galleryThumbnail.collectAsState() @@ -205,6 +219,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen isoStops, longExposureProgress, longExposureRemaining, lowLightDetected, nightModeActive, extensionStrength, sloMoSupported, highSpeedActive, photoSessionActive, analysisStreamActive, nightExtAvailable, surfaceRequest,+ sessionBindFailed, sessionBindRetry, availableZoomLevels, galleryBitmap, panoSweeping, panoStitching, panoDots, panoCurrentAngle, panoDirection, panoPitch, ) {@@ -266,6 +281,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen activeSettingState = activeSettingState, maskBitmapState = maskBitmapState, deviceRotationState = deviceRotationState,+ sessionBindFailed = sessionBindFailed,+ sessionBindRetry = sessionBindRetry, ) } }
camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.ktindex e609b92954..9ff507c4ed 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraTopBar.kt@@ -48,6 +48,7 @@ internal fun CameraTopBar( flashMode: FlashMode, torchEnabled: Boolean, hasFlashUnit: Boolean,+ screenFlashAvailable: Boolean = false, gridEnabled: Boolean, levelEnabled: Boolean, aspectRatio: AspectRatioOption,@@ -74,9 +75,12 @@ internal fun CameraTopBar( horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically ) {- // Flash/torch share the same LED: without a flash unit (some front lenses) the- // control is dead, so hide it instead of showing a button that does nothing.- if (hasFlashUnit) {+ // Flash/torch share the same LED: without a flash unit the torch is dead, but a+ // front lens can still flash via the screen (CameraX FLASH_MODE_SCREEN), so the+ // flash cycle stays available there and only the torch long-press goes away.+ // With neither a unit nor screen flash the control is dead, so hide it instead+ // of showing a button that does nothing.+ if (hasFlashUnit || screenFlashAvailable) { val flashBg = if (torchEnabled || flashMode != FlashMode.OFF) Color(0xFF3C3C3C) else Color.Transparent Box( modifier = Modifier@@ -85,7 +89,7 @@ internal fun CameraTopBar( .background(flashBg, CircleShape) .combinedClickable( onClick = onFlashToggle,- onLongClick = onTorchToggle+ onLongClick = if (hasFlashUnit) onTorchToggle else null ), contentAlignment = Alignment.Center ) {
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex a8331548b2..84ef79d478 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -79,6 +79,16 @@ <item quantity="other">%1$d seconds</item> </plurals> + <!-- Audio codec settings: codec used for video recording audio -->+ <!-- Audio codec option label: AAC -->+ <string name="audio_codec_aac_label">AAC</string>+ <!-- Audio codec description: most compatible -->+ <string name="audio_codec_aac_description">Most compatible</string>+ <!-- Audio codec option label: Opus -->+ <string name="audio_codec_opus_label">Opus</string>+ <!-- Audio codec description: more efficient than AAC -->+ <string name="audio_codec_opus_description">More efficient</string>+ <!-- Audio input source settings (SettingsPage): mic source used for video recordings --> <!-- SettingsPage: section header for audio input source selection --> <string name="settings_audio_source">Audio input source</string>@@ -152,6 +162,11 @@ <string name="auto">Auto</string> <string name="night_2">Night %1$s%%</string> + <!-- CameraPreviewBox: session bind failed after retries, shown over the black preview -->+ <string name="camera_bind_failed_title">Camera couldn\'t start</string>+ <!-- CameraPreviewBox: bind-failure detail under the title, above the Retry button -->+ <string name="camera_bind_failed_message">Try again, or switch lens or mode.</string>+ <!-- LensBar: physical-lens picker above the zoom bar --> <!-- LensBar: label for the ultra-wide (0.5x) physical lens. Short pill label --> <!-- LensBar: label for the default wide (1x) physical lens. Short pill label -->
camera/src/test/java/com/vayunmathur/camera/domain/FlashModePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/FlashModePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/FlashModePolicyTest.ktnew file mode 100644index 0000000000..cbb4fbf62e--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/FlashModePolicyTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class FlashModePolicyTest {++ @Test+ fun frontWithoutFlashUnitArmsScreenFlash() {+ assertTrue(FlashModePolicy.usesScreenFlash(LensFacing.FRONT, hasFlashUnit = false))+ assertEquals(+ FlashResolution.SCREEN,+ FlashModePolicy.resolve(LensFacing.FRONT, hasFlashUnit = false, FlashSetting.ON)+ )+ assertEquals(+ FlashResolution.SCREEN,+ FlashModePolicy.resolve(LensFacing.FRONT, hasFlashUnit = false, FlashSetting.AUTO)+ )+ }++ @Test+ fun frontWithoutFlashUnitOffStaysDark() {+ assertEquals(+ FlashResolution.NONE,+ FlashModePolicy.resolve(LensFacing.FRONT, hasFlashUnit = false, FlashSetting.OFF)+ )+ }++ @Test+ fun backWithFlashUnitKeepsHardwareFlash() {+ assertFalse(FlashModePolicy.usesScreenFlash(LensFacing.BACK, hasFlashUnit = true))+ assertEquals(+ FlashResolution.HARDWARE,+ FlashModePolicy.resolve(LensFacing.BACK, hasFlashUnit = true, FlashSetting.ON)+ )+ assertEquals(+ FlashResolution.HARDWARE,+ FlashModePolicy.resolve(LensFacing.BACK, hasFlashUnit = true, FlashSetting.AUTO)+ )+ assertEquals(+ FlashResolution.NONE,+ FlashModePolicy.resolve(LensFacing.BACK, hasFlashUnit = true, FlashSetting.OFF)+ )+ }++ @Test+ fun frontWithFlashUnitKeepsHardwareFlash() {+ assertFalse(FlashModePolicy.usesScreenFlash(LensFacing.FRONT, hasFlashUnit = true))+ assertEquals(+ FlashResolution.HARDWARE,+ FlashModePolicy.resolve(LensFacing.FRONT, hasFlashUnit = true, FlashSetting.ON)+ )+ }++ @Test+ fun backWithoutFlashUnitNeverUsesScreenFlash() {+ // CameraX rejects FLASH_MODE_SCREEN on a back camera, so no unit = no flash.+ assertFalse(FlashModePolicy.usesScreenFlash(LensFacing.BACK, hasFlashUnit = false))+ assertEquals(+ FlashResolution.HARDWARE,+ FlashModePolicy.resolve(LensFacing.BACK, hasFlashUnit = false, FlashSetting.ON)+ )+ }++ @Test+ fun flashControlShownWhenEitherFlashCanFire() {+ assertTrue(FlashModePolicy.showFlashControl(LensFacing.BACK, hasFlashUnit = true))+ assertTrue(FlashModePolicy.showFlashControl(LensFacing.FRONT, hasFlashUnit = true))+ assertTrue(FlashModePolicy.showFlashControl(LensFacing.FRONT, hasFlashUnit = false))+ assertFalse(FlashModePolicy.showFlashControl(LensFacing.BACK, hasFlashUnit = false))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/CameraCovC2CapabilitiesTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovC2CapabilitiesTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovC2CapabilitiesTest.ktindex 81d02e74cc..7d59584a38 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovC2CapabilitiesTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CameraCovC2CapabilitiesTest.kt@@ -92,6 +92,32 @@ class CameraCovC2CapabilitiesTest { assertTrue(viewModel.hasFlashUnitMutable.value) } + @Test fun refreshCapabilitiesReassertsTorchFromUiState() = runBlocking<Unit> {+ val viewModel = vm()+ viewModel.cameraModeMutable.value = CameraMode.VIDEO+ // Recording control so the re-assert onto the fresh bind is observable.+ val control = org.mockito.Mockito.mock(CameraControl::class.java)+ val info = cameraInfo(zoomState(0.5f, 8f), flash = true)+ val bound = proxy(Camera::class.java) { name ->+ when (name) {+ "getCameraInfo" -> info+ "getCameraControl" -> control+ else -> null+ }+ } as Camera+ // Torch left on in the UI across a mode/lens rebind must be re-applied+ // to the new bind (the torch effect only fires on value change).+ viewModel.torchEnabledMutable.value = true+ viewModel.refreshCapabilities(bound, "lens-1")+ org.mockito.Mockito.verify(control).enableTorch(true)+ // And a torch-off UI state is re-asserted off, not left as the+ // previous bind's hardware state.+ org.mockito.Mockito.clearInvocations(control)+ viewModel.torchEnabledMutable.value = false+ viewModel.refreshCapabilities(bound, "lens-1")+ org.mockito.Mockito.verify(control).enableTorch(false)+ }+ @Test fun refreshCapabilitiesDefaultsWhenZoomUnreadable() = runBlocking<Unit> { val viewModel = vm() viewModel.cameraModeMutable.value = CameraMode.TIMELAPSE
camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.ktnew file mode 100644index 0000000000..90d1c8bd73--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/CameraSessionBindRetryTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.camera.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Bounded session-bind retry: fake setups that fail, then succeed (or don't). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CameraSessionBindRetryTest {++ @Test fun failingThenSucceedingSetupIsRetriedUntilSuccess() = runBlocking<Unit> {+ var attempts = 0+ val delays = mutableListOf<Long>()+ val bound = runSessionBindWithRetry(+ maxRetries = 2,+ retryDelayMs = 7L,+ delayFn = { delays += it },+ ) {+ attempts+++ attempts >= 3 // fake setup fails twice, succeeds on the third try+ }+ assertTrue(bound)+ assertEquals(3, attempts)+ assertEquals(listOf(7L, 7L), delays)+ }++ @Test fun alwaysFailingSetupStopsAfterBoundedRetries() = runBlocking<Unit> {+ var attempts = 0+ val bound = runSessionBindWithRetry(+ maxRetries = SESSION_BIND_MAX_RETRIES,+ retryDelayMs = 1L,+ delayFn = {},+ ) {+ attempts+++ false+ }+ assertFalse(bound)+ // First attempt + SESSION_BIND_MAX_RETRIES retries, never a fourth bind.+ assertEquals(SESSION_BIND_MAX_RETRIES + 1, attempts)+ }++ @Test fun firstTrySuccessDoesNotRetryOrDelay() = runBlocking<Unit> {+ var attempts = 0+ var delays = 0+ val bound = runSessionBindWithRetry(delayFn = { delays++ }) {+ attempts+++ true+ }+ assertTrue(bound)+ assertEquals(1, attempts)+ assertEquals(0, delays)+ }++ @Test fun cancellationSupersedesRetryLadder() = runBlocking<Unit> {+ var attempts = 0+ var cancelled = false+ try {+ runSessionBindWithRetry(delayFn = { throw CancellationException("key changed") }) {+ attempts+++ false+ }+ } catch (e: CancellationException) {+ cancelled = true+ }+ assertTrue(cancelled)+ assertEquals(1, attempts)+ }++ @Test fun manualRetryClearsFailureAndBumpsRetryCounter() {+ val viewModel = CameraViewModel(ApplicationProvider.getApplicationContext())+ viewModel.sessionBindFailedMutable.value = true+ val before = viewModel.sessionBindRetryMutable.value+ viewModel.retrySessionBind()+ assertFalse(viewModel.sessionBindFailedMutable.value)+ assertEquals(before + 1, viewModel.sessionBindRetryMutable.value)+ viewModel.retrySessionBind()+ assertEquals(before + 2, viewModel.sessionBindRetryMutable.value)+ }+}
camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.ktnew file mode 100644index 0000000000..22721c3c19--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraBindFailedComposeTest.kt@@ -0,0 +1,108 @@+package com.vayunmathur.camera.ui++import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.camera.platform.AspectRatioOption+import com.vayunmathur.camera.platform.CameraMode+import com.vayunmathur.camera.platform.CameraViewModel+import com.vayunmathur.camera.platform.FlashMode+import com.vayunmathur.camera.platform.TimerDuration+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++/** Bind-failure preview: ErrorState with a working manual retry, not black. */+@RunWith(AndroidJUnit4::class)+class CameraBindFailedComposeTest {+ @get:Rule val rule = createComposeRule()+ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private fun vm() = CameraViewModel(context.applicationContext as android.app.Application)++ private fun failedState(viewModel: CameraViewModel) = CameraScreenState(+ cameraMode = CameraMode.PHOTO,+ lensFacing = androidx.camera.core.CameraSelector.LENS_FACING_BACK,+ selectedLens = null,+ availableLenses = emptyList(),+ hasFlashUnit = true,+ flashMode = FlashMode.OFF,+ torchEnabled = false,+ videoCodec = viewModel.videoCodecMutable.value,+ audioInputSource = viewModel.audioInputSourceMutable.value,+ isRecording = false,+ recordingDuration = 0,+ timerCountdown = 0,+ qrResult = null,+ aspectRatio = AspectRatioOption.RATIO_4_3,+ zoomRatio = 1f,+ mirrorFront = true,+ timerDuration = TimerDuration.NONE,+ isCapturing = false,+ burstActive = false,+ burstCount = 0,+ focusLocked = false,+ recordingPaused = false,+ micMuted = false,+ videoSnapshotSupported = false,+ lastCaptureUri = null,+ gridEnabled = false,+ levelEnabled = false,+ roll = 0f,+ blurStrength = 0.5f,+ exposureComp = 0f,+ warmth = 0f,+ shadows = 0f,+ exposureTimeIndex = 0,+ manualIsoIndex = 0,+ isoStops = emptyList(),+ longExposureProgress = 0f,+ longExposureRemaining = "",+ lowLightDetected = false,+ nightModeActive = false,+ extensionStrength = null,+ sloMoSupported = null,+ highSpeedActive = false,+ photoSessionActive = false,+ analysisStreamActive = false,+ nightExtAvailable = false,+ surfaceRequest = null,+ availableZoomLevels = listOf("1x" to 1f),+ galleryBitmap = null,+ panoSweeping = false,+ panoStitching = false,+ panoDots = emptyList(),+ panoCurrentAngle = 0f,+ panoDirection = 0,+ panoPitch = 0f,+ activeSettingState = mutableStateOf<CameraSetting?>(null),+ maskBitmapState = mutableStateOf<android.graphics.Bitmap?>(null),+ deviceRotationState = mutableIntStateOf(0),+ sessionBindFailed = true,+ sessionBindRetry = 0,+ )++ @Test fun bindFailedShowsErrorWithManualRetry() {+ val viewModel = vm()+ viewModel.sessionBindFailedMutable.value = true+ val retriesBefore = viewModel.sessionBindRetryMutable.value+ rule.setContent {+ BoxWithConstraints(Modifier.fillMaxSize()) {+ CameraPreviewBox(state = failedState(viewModel), viewModel = viewModel, animatedRotation = 0f)+ }+ }+ rule.onNodeWithText("Camera couldn't start").assertIsDisplayed()+ rule.onNodeWithText("Retry").assertIsDisplayed().performClick()+ assertEquals(retriesBefore + 1, viewModel.sessionBindRetryMutable.value)+ assertFalse(viewModel.sessionBindFailedMutable.value)+ }+}