camera: wire Camera2 analysis + night extension; document slo-mo gap
- Commit
56a2254cbeb58a8dd3a59fc44691709f5e748f56- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-22 17:08 UTC (13 days ago)
- Parents
2e9c873
Three deferred Camera2 pieces resolved or bounded. Analysis: the Camera2 session gains a YUV analysis stream feeding the same luma/plane consumer seam (combo failure degrades to no-analysis, preview intact); QR/portrait/ pano/Motion-Photo sessions stay on CameraX ImageAnalysis because they need bitmaps, per policy. Night extension: the built-but-unbound Camera2 extension session now has a production preview (Camera2NightPreview) registered for its lifetime, selected by night mode + gate + lens with a session-scoped fallback latch; the CameraX night extension and own burst remain fallbacks in order. Slo-mo recording: honestly NOT enabled. The coupling is not mechanical - seven missing pieces now documented in SloMoEnginePolicy in dependency order (encoder-surface handoff, session ownership, lifecycle, preview surface, audio/muxer contract, timestamp stretch, save/fallback glue). recordingEngineReady stays false; CameraX high-speed remains the recording path. CameraX holdouts now: bitmap-needing modes (QR, portrait, pano, Motion Photo), slo-mo recording, non-PHOTO preview. Verified: camera compile + targeted session/policy/UI tests green. Device verification still owed for the new night-preview stream combo.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.ktnew file mode 100644index 0000000000..25ce256deb--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2AnalysisGlue.kt@@ -0,0 +1,46 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.domain.AnalysisSource+import com.vayunmathur.camera.domain.AnalysisSourceInput+import com.vayunmathur.camera.domain.AnalysisSourcePolicy+import com.vayunmathur.camera.platform.camera2.AnalysisConsumer++/**+ * Camera2 analysis wiring: the plane consumer for a Camera2 session's YUV+ * analysis stream.+ *+ * The consumer is luma-only by construction: it feeds each frame's Y plane+ * to [PhotoAnalyzer.onYPlane] (luma stats via the Rust plane-stats work in+ * `StitchNative.lumaStats`, Kotlin fallback identical), which drives the+ * night hysteresis through [onLuminance]. QR decode and bitmap frame+ * copies deliberately have no plane entry point (see+ * [AnalysisSourcePolicy]): sessions needing them — QR, PORTRAIT,+ * PANORAMA/PHOTOSPHERE, Motion-Photo frame copies — stay on the CameraX+ * ImageAnalysis path, exactly as before. Those session types never compose+ * the Camera2 preview, so they never reach this glue.+ */+internal fun CameraViewModel.camera2AnalysisConsumer(): AnalysisConsumer {+ val analyzer = PhotoAnalyzer(+ onLuminance = { onLuminance(it) },+ onQrDetected = {},+ )+ return AnalysisConsumer { frame -> analyzer.onYPlane(frame.yPlane) }+}++/**+ * True when this session's analysis stream may serve from Camera2: the+ * persisted Camera2 preview toggle (the session only exists when that+ * gate selected Camera2) AND the [AnalysisSourcePolicy] master flag, for a+ * cheap-plane-only consumer. Excluded (QR/bitmap) sessions are not+ * classified here — they never compose a Camera2 session.+ */+internal fun CameraViewModel.camera2AnalysisServes(): Boolean =+ AnalysisSourcePolicy.select(+ AnalysisSourceInput(+ camera2Enabled = AnalysisSourcePolicy.CAMERA2_ENABLED &&+ camera2PreviewEnabledMutable.value,+ needsQr = false,+ needsBitmapFrame = false,+ cheapPlaneConsumersOnly = true,+ ),+ ) == AnalysisSource.CAMERA2_IMAGE_READER
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 cd35e12900..233ef5f265 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -170,6 +170,18 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val camera2NightSessionActiveMutable = MutableStateFlow(false) val camera2NightSessionActive = camera2NightSessionActiveMutable.asStateFlow() + /**+ * Bind key latched after a Camera2 NIGHT extension preview failed to+ * configure/open for this lens+mode; the UI then falls back to the+ * regular preview (Camera2 or CameraX) for that bind instead of+ * retry-looping the extension session. Session-scoped (not the 7-day+ * persisted failure cache): a probe miss on one lens must not suppress+ * the CameraX extension — capture-time failures still record into+ * that cache via `recordNightExtensionFailure`.+ */+ internal val camera2NightFallbackBindKeyMutable = MutableStateFlow<String?>(null)+ val camera2NightFallbackBindKey = camera2NightFallbackBindKeyMutable.asStateFlow()+ /** * The live Camera2 session while the gated preview is composed * (Phase 4a stills), registered by `Camera2Preview`; null otherwise.
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.ktindex 826917adf5..eb5b43594d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModelCamera2Gates.kt@@ -45,9 +45,31 @@ fun CameraViewModel.setCamera2SloMoEnabled(enabled: Boolean) { viewModelScope.launch { ds.setString("camera_camera2_slomo", enabled.toString()) } } +/**+ * Records a Camera2 NIGHT extension preview configure/open failure for+ * [cameraId]: latches this bind key so the UI stops composing the+ * extension preview and falls back to the regular preview path. Does+ * NOT write the persisted 7-day failure cache — a probe/configure miss+ * here must not suppress the CameraX extension at capture time; only a+ * real capture failure does that (see `tryCaptureCamera2NightExtension`).+ */+fun CameraViewModel.onCamera2NightPreviewFailed(cameraId: String) {+ val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(cameraId, cameraModeMutable.value)+ if (camera2NightFallbackBindKeyMutable.value == key) return+ camera2NightFallbackBindKeyMutable.value = key+ Log.status("Camera2Night", "Camera2 extension preview failed for $key; falling back for this session")+}++/** Clears the Camera2 night fallback latch (new lens/mode/gate re-enable). */+fun CameraViewModel.clearCamera2NightFallback() {+ camera2NightFallbackBindKeyMutable.value = null+}+ /** Turns the Camera2 night gate on/off (PHOTO only; see ExtensionsEnginePolicy). */ fun CameraViewModel.setCamera2NightEnabled(enabled: Boolean) { camera2NightEnabledMutable.value = enabled+ if (enabled) clearCamera2NightFallback() viewModelScope.launch { ds.setString("camera_camera2_night", enabled.toString()) } }
camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.ktindex 7b6c7ccdb5..b83808ad1b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/PhotoAnalyzer.kt@@ -75,7 +75,9 @@ class PhotoAnalyzer( * phase (see AnalysisSourcePolicy) and stay on the CameraX path. */ fun onYPlane(plane: PlaneView) {- val avg = LumaPlaneMath.mean(plane) ?: return+ // Luma via the Rust plane-stats work (StitchNative.lumaStats, with+ // the identical Kotlin fallback for non-direct/unavailable cases).+ val avg = StitchNative.lumaStats(plane)?.mean ?: return try { onLuminance(avg.toFloat()) } catch (e: IllegalStateException) {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.ktindex e70bbea02f..29f74a4571 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSource.kt@@ -35,6 +35,17 @@ fun interface AnalysisConsumer { fun onFrame(frame: AnalysisFrame) } +/**+ * Testable handle over a YUV analysis output (an `ImageReader` in the real+ * driver). The session adds [surface] as a capture-session output alongside+ * preview/still and includes it in the repeating request targets; frames+ * arrive through the consumer given at creation. Mirrors [RingOutput].+ */+interface AnalysisOutput : AutoCloseable {+ val surface: Surface+ override fun close()+}+ /** * The drop policy, isolated from Android so it is unit-testable: at most one * frame is in flight to the consumer. A frame that arrives while the consumer@@ -162,13 +173,13 @@ class AnalysisImageSource( handler: Handler, executor: Executor, consumer: AnalysisConsumer,-) : AutoCloseable {+) : AnalysisOutput { private val reader: ImageReader = ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, maxImages) private val dispatcher = AnalysisFrameDispatcher(consumer, executor) - val surface: Surface get() = reader.surface+ override val surface: Surface get() = reader.surface /** Frames dropped because the consumer was busy (see [FrameDropGate]). */ val droppedFrames: Long get() = dispatcher.gate.droppedFrames
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex 02a0fb8ba4..a7430a7c5b 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -190,6 +190,13 @@ interface Camera2Driver { /** Creates the RAW ring output for [size]/[format]; null when unavailable. */ fun createRawRingOutput(size: FrameSize, format: RingFormat): RawRingOutput? = null++ /**+ * Creates the YUV analysis output for [size] feeding [consumer]; null+ * when unavailable. The default is null: a fake/driver without analysis+ * degrades to no analysis stream, never to a failed preview.+ */+ fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? = null } /** Converts a pure [SensorRect] into the HAL's `Rect`. */@@ -342,6 +349,15 @@ class AndroidCamera2Driver( RawImageReaderOutput(size.width, size.height, format, handler = handler) }.getOrNull() + override fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? =+ runCatching {+ AnalysisImageSource(+ size.width, size.height, handler = handler,+ executor = java.util.concurrent.Executor { command -> handler.post(command) },+ consumer = consumer,+ )+ }.getOrNull()+ @SuppressLint("MissingPermission") override fun openCamera(cameraId: String, callback: DeviceCallback) { manager.openCamera(
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 3a77eae3dc..3147c9ab6b 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@@ -20,6 +20,15 @@ import android.view.Surface * session when the facade reports YUV reprocessing, direct-encoded * otherwise — with no AE-convergence wait or fresh exposure. *+ * The analysis phase adds an optional YUV analysis stream (another+ * output, [analysisConsumer]): when a consumer is supplied, a capped+ * YUV `ImageReader` feeds it plane views (see [AnalysisImageSource])+ * alongside preview/still. This stream is strictly best-effort: if its+ * output cannot be created, or the stream combination fails to+ * configure with it, the session drops the analysis output and+ * (re)configures preview+still without it — analysis never costs the+ * preview (the fallback-latch philosophy, applied per-stream).+ * * Threading: every public method posts onto the executor; every driver * callback arrives on the executor and is generation-checked through * [SessionStateMachine] before it may touch session state, so a callback@@ -41,6 +50,8 @@ class Camera2Session( private val listener: Listener? = null, private val ringConfig: ReprocessRingConfig = ReprocessRingConfig.DISABLED, private val rawRingConfig: RawRingConfig = RawRingConfig.DISABLED,+ /** Plane consumer for the analysis stream; null = no analysis output. */+ private val analysisConsumer: AnalysisConsumer? = null, ) { /** Session lifecycle notifications; all fire on the executor thread. */@@ -82,6 +93,10 @@ class Camera2Session( private var ringOutput: RingOutput? = null private var ringSize: FrameSize? = null private val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity)+ private var analysisOutput: AnalysisOutput? = null+ private var analysisSize: FrameSize? = null+ /** Set once a configure failure has dropped analysis: never re-add it. */+ private var analysisComboDropped: Boolean = false private var rawRingOutput: RawRingOutput? = null private var rawRingSize: FrameSize? = null private var rawRingFormat: RingFormat? = null@@ -238,6 +253,12 @@ class Camera2Session( /** The JPEG_R still size configured at [open], or null when unavailable. */ fun currentUltraHdrSize(): FrameSize? = ultraHdrSize + /** True when the YUV analysis output is configured (see AnalysisSourcePolicy). */+ val hasAnalysisOutput: Boolean get() = analysisOutput != null++ /** The analysis size configured at [open], or null when unavailable/dropped. */+ fun currentAnalysisSize(): FrameSize? = analysisSize+ /** True when the YUV ring output is configured (see [StillEnginePolicy]). */ val hasRingOutput: Boolean get() = ringOutput != null @@ -567,6 +588,9 @@ class Camera2Session( ringOutput = null ringSize = null ring.drainAll().forEach { runCatching { it.close() } }+ runCatching { analysisOutput?.close() }+ analysisOutput = null+ analysisSize = null runCatching { rawRingOutput?.close() } rawRingOutput = null rawRingSize = null@@ -591,7 +615,9 @@ class Camera2Session( val surface = previewSurface ?: return if (stateMachine.state != SessionState.STREAMING) return val params = Camera2Controls.resolve(controls, snapshot)- val targets = listOfNotNull(surface, ringOutput?.surface, rawRingOutput?.surface)+ val targets = listOfNotNull(+ surface, ringOutput?.surface, rawRingOutput?.surface, analysisOutput?.surface,+ ) runCatching { session.setRepeatingStreaming(params, targets, PreviewResultCallback { raw -> try {@@ -603,9 +629,15 @@ class Camera2Session( }.onFailure { reportError("setRepeatingPreview failed: ${it.message}") } } - private fun configureSession(opened: DeviceHandle, gen: Long) {+ private fun configureSession(opened: DeviceHandle, gen: Long, reuseOutputs: Boolean = false) { val surface = previewSurface ?: return if (transition(SessionEvent.CONFIGURE_REQUESTED) !is TransitionResult.Applied) return+ if (reuseOutputs) {+ // Retry after a stream-combo failure dropped analysis: every+ // other output already exists; only the capture session is new.+ createCaptureSessionWithAnalysisFallback(opened, gen)+ return+ } // Second output: the JPEG still reader, when the lens reports JPEG // sizes and the driver can create it. Failure degrades to // preview-only (capture() then fails cleanly, policy excludes it).@@ -672,30 +704,68 @@ class Camera2Session( rawRingOutput = createdRawRing rawRingSize = if (createdRawRing != null) selectedRawSize else null rawRingFormat = if (createdRawRing != null) selectedRawFormat else null- val surfaces = listOfNotNull(- surface, output?.surface, createdUltraHdr?.surface,- createdRing?.surface, createdRawRing?.surface,- )+ // Optional analysis output: only when a consumer was supplied.+ // Failure degrades to no analysis (preview/still unaffected).+ val consumer = analysisConsumer+ val selectedAnalysisSize = if (consumer != null && !analysisComboDropped) {+ StreamSelection.selectAnalysisSize(snapshot)+ } else {+ null+ }+ val createdAnalysis = if (selectedAnalysisSize != null && consumer != null) {+ runCatching { driver.createAnalysisOutput(selectedAnalysisSize, consumer) }.getOrNull()+ } else {+ null+ }+ analysisOutput = createdAnalysis+ analysisSize = if (createdAnalysis != null) selectedAnalysisSize else null+ createCaptureSessionWithAnalysisFallback(opened, gen)+ }++ /** Surfaces for one configure attempt: preview + every live output. */+ private fun configuredSurfaces(): List<Surface> = listOfNotNull(+ previewSurface, stillOutput?.surface, ultraHdrOutput?.surface,+ ringOutput?.surface, rawRingOutput?.surface, analysisOutput?.surface,+ )++ /**+ * Creates the capture session over [configuredSurfaces]. A synchronous+ * create failure with analysis present drops analysis and retries once+ * without it; an asynchronous configure failure takes the same path in+ * [SessionCallbackImpl.onConfigureFailed]. Analysis never costs preview.+ */+ private fun createCaptureSessionWithAnalysisFallback(opened: DeviceHandle, gen: Long) { val callback = SessionCallbackImpl(gen)+ val ringSize = ringSize runCatching {- if (createdRing != null && snapshot.supportsYuvRingReprocess) {+ if (ringOutput != null && ringSize != null && snapshot.supportsYuvRingReprocess) { opened.createReprocessableCaptureSession(- ReprocessInputConfig(- selectedRingSize.width, selectedRingSize.height,- ImageFormat.YUV_420_888,- ),- surfaces,+ ReprocessInputConfig(ringSize.width, ringSize.height, ImageFormat.YUV_420_888),+ configuredSurfaces(), callback, ) } else {- opened.createCaptureSession(surfaces, callback)+ opened.createCaptureSession(configuredSurfaces(), callback) } }.onFailure {- dispatch(gen, SessionEvent.CONFIGURE_FAILED)- reportError("createCaptureSession failed: ${it.message}")+ if (analysisOutput != null && !analysisComboDropped) {+ dropAnalysisOutput()+ createCaptureSessionWithAnalysisFallback(opened, gen)+ } else {+ dispatch(gen, SessionEvent.CONFIGURE_FAILED)+ reportError("createCaptureSession failed: ${it.message}")+ } } } + /** Drops the analysis output (combo degrade); preview/still keep serving. */+ private fun dropAnalysisOutput() {+ analysisComboDropped = true+ runCatching { analysisOutput?.close() }+ analysisOutput = null+ analysisSize = null+ }+ private fun transition(event: SessionEvent): TransitionResult { val result = stateMachine.transition(event) if (result is TransitionResult.Applied) notifyState()@@ -773,6 +843,17 @@ class Camera2Session( override fun onConfigureFailed() { if (!stateMachine.isCurrent(gen)) return+ // Stream-combo degrade: a combination that included the YUV+ // analysis surface failed — drop analysis and reconfigure+ // preview+still once. Only a failure without analysis (or a+ // second failure) is a real configure failure.+ val opened = device+ if (analysisOutput != null && !analysisComboDropped && opened != null) {+ dispatch(gen, SessionEvent.CONFIGURE_FAILED)+ dropAnalysisOutput()+ configureSession(opened, gen, reuseOutputs = true)+ return+ } dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("capture session configure failed") }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.ktindex b69a458374..c94044ac65 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/SloMoEnginePolicy.kt@@ -36,11 +36,56 @@ data class SloMoEngineInput( val encoderSupportsCaptureRate: Boolean = false, /** * The constrained session is coupled to a recording engine (codec +- * muxer) end to end. False today: `Camera2HighSpeedSession` can stream- * to an encoder surface, but the Phase-1 engine still opens its own- * device, so no live recording may be routed here yet. Device- * verification (encoder honouring `KEY_CAPTURE_RATE`, ffprobe of the- * output) is also outstanding — see the Phase-5 report.+ * muxer) end to end. False today — assessed 2026-11-22: coupling+ * `Camera2HighSpeedSession` to `Camera2VideoRecordingEngine` is NOT+ * mechanical. The exact missing pieces, in dependency order:+ *+ * 1. Encoder-surface handoff. The engine creates its codec input+ * surface internally in `openCamera()` (`videoCodec.createInputSurface()`+ * after `setupEncoders`) and never exposes it before the camera is+ * opened. The high-speed session needs that surface *before* open,+ * as a configure-time session target. Missing: a codec-first split+ * of the engine (configure codec -> expose input surface -> start+ * drain/muxer separately from camera open).+ * 2. Device/session ownership. Both classes open the same cameraId:+ * the engine owns a private `CameraDevice`/`HandlerThread` and a+ * *regular* capture session; the high-speed session owns the device+ * through the driver seam and a *constrained* session+ * (`SESSION_HIGH_SPEED` + `createHighSpeedRequestList`). The+ * engine's regular `TEMPLATE_RECORD` request with a pinned FPS+ * range cannot deliver 120/240 fps and must not be substituted.+ * Missing: an engine variant that accepts an externally-owned+ * session (or extracts the codec/muxer/drain core both can share).+ * 3. Recording lifecycle. `Camera2HighSpeedSession` has open/close+ * only — no start/stop-recording boundary, no EOS/drain+ * coordination with a codec. The engine's `stop()` assumes it owns+ * session+device+codec. Missing: start/stop semantics on the+ * high-speed session that signal EOS to the external codec and+ * only then close, without closing caller-owned surfaces.+ * 4. Preview surface in SLOW_MO. `PreviewEnginePolicy` serves PHOTO+ * only; SLOW_MO preview is a CameraX `surfaceRequest`. There is no+ * Camera2 slo-mo preview composable/bridge to supply the+ * high-speed session's preview target (mirroring `Camera2Preview`).+ * 5. Audio/muxer contract. CameraX slo-mo records *no* audio; the+ * engine always starts `AudioRecord`+AAC and its muxer only starts+ * once *both* tracks appear. Missing: a no-audio mode (muxer starts+ * on the video track alone) for the slo-mo configuration.+ * 6. Timestamp verification. The muxer writes encoder `BufferInfo`+ * PTS as-is; the pure `HighSpeedSelection.stretchedPtsUs` fallback+ * is not wired into the drain path, and `validateOutput` does not+ * check frame rate / stretched duration. Missing: either proof a+ * device encoder honours `KEY_CAPTURE_RATE`, or muxer-side PTS+ * stretching, plus read-back checks (and external ffprobe) that+ * the output is slow, not realtime HFR.+ * 7. Save-path glue + fallback. `setupHighSpeedSession` /+ * recording start-stop plumbing expects an engine that opens the+ * camera itself (`VideoRecordingEngine.start`). Missing: glue that+ * tears CameraX down, builds engine+high-speed session together,+ * routes the file through `saveVideoStaged`, and on any failure+ * rebinds the CameraX HFR ladder (fallback-latch philosophy) —+ * plus the device verification in (6) before this flag may flip.+ *+ * Until (1)-(7) land, no live recording may be routed here. */ val recordingEngineReady: Boolean = false, )
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex d8b0af7323..1e140ef944 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -165,6 +165,26 @@ object StreamSelection { return pool.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height })) } + /** Pixel cap for the analysis stream: the CameraX analysis cap (~1.2 MP, 1280x960). */+ const val MAX_ANALYSIS_PIXELS: Long = 1280L * 960L++ /**+ * The analysis size: the largest YUV size at or under+ * [MAX_ANALYSIS_PIXELS] (luma/motion consumers gain nothing from sensor+ * resolution), else the smallest YUV size over the cap. Null when the+ * lens reports no YUV sizes — no analysis output is configured then.+ */+ fun selectAnalysisSize(snapshot: LensCharacteristicsSnapshot): FrameSize? {+ val yuv = supportedYuvSizes(snapshot)+ if (yuv.isEmpty()) return null+ val underCap = yuv.filter { it.area.toLong() <= MAX_ANALYSIS_PIXELS }+ return if (underCap.isNotEmpty()) {+ underCap.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ } else {+ yuv.minWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ }+ }+ /** Supported RAW sizes for the facade's RAW ring format (empty = no RAW ring). */ fun supportedRawSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> { val format = snapshot.rawRingFormat?.toImageFormat() ?: return emptyList()
camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.ktnew file mode 100644index 0000000000..c79be01836--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2NightPreview.kt@@ -0,0 +1,126 @@+package com.vayunmathur.camera.ui++import android.content.Context+import android.hardware.camera2.CameraManager+import android.view.TextureView+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.viewinterop.AndroidView+import com.vayunmathur.camera.platform.camera2.AndroidCamera2Driver+import com.vayunmathur.camera.platform.camera2.Camera2Executor+import com.vayunmathur.camera.platform.camera2.Camera2ExtensionSession+import com.vayunmathur.camera.platform.camera2.CharacteristicsFacade+import com.vayunmathur.camera.platform.camera2.FrameSize+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceBridge+import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent+import com.vayunmathur.library.log.Log++/**+ * Camera2 NIGHT-extension viewfinder: a TextureView whose surface feeds a+ * [Camera2ExtensionSession]. Composed only when+ * `CameraScreenState.useCamera2NightPreview` selects the Camera2 extension+ * (PHOTO + night engaged + persisted night gate on, no latched failure);+ * the regular Camera2/CameraX preview is composed otherwise.+ *+ * Registration is the point of this composable: the session is handed to+ * the ViewModel via [onSessionChanged] (which calls+ * `registerCamera2ExtensionSession`) for its whole composition lifetime,+ * so `tryCaptureCamera2NightExtension` finds a live, probed session at+ * shutter time. On dispose it unregisters first, then closes.+ *+ * The session re-probes at open: an unusable lens never opens the device+ * and reports through [onError], which latches the bind in the ViewModel+ * so this composable is not recomposed in a retry loop — the regular+ * preview serves instead (capture order CameraX-extension → own-burst+ * intact).+ *+ * Ownership: this composition owns the executor and the session; both are+ * torn down when it leaves composition.+ */+@Composable+internal fun Camera2NightPreview(+ cameraId: String,+ onSessionChanged: (Camera2ExtensionSession?) -> Unit = {},+ onError: (String) -> Unit = {},+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val sessionHolder = remember(cameraId) { Camera2NightPreviewSession(context, cameraId, onError) }++ DisposableEffect(sessionHolder) {+ onSessionChanged(sessionHolder.session)+ onDispose {+ onSessionChanged(null)+ sessionHolder.close()+ }+ }++ AndroidView(+ factory = { ctx ->+ TextureView(ctx).also { view ->+ sessionHolder.session.setDisplayRotationDegrees(+ (view.display?.rotation ?: 0) * 90,+ )+ sessionHolder.bridge.attachTo(view)+ }+ },+ modifier = modifier,+ )+}++/** Executor + bridge + extension session for one camera id; built once, closed once. */+private class Camera2NightPreviewSession(+ context: Context,+ private val cameraId: String,+ private val onError: (String) -> Unit = {},+) {+ val executor = Camera2Executor("Camera2NightPreview-$cameraId")+ val session: Camera2ExtensionSession+ val bridge: PreviewSurfaceBridge++ init {+ val manager = context.getSystemService(CameraManager::class.java)+ val facade = CharacteristicsFacade.fromCameraManager(manager, cameraId)+ val driver = AndroidCamera2Driver(+ manager,+ android.os.Handler(executor.looper),+ )+ session = Camera2ExtensionSession(+ driver = driver,+ executor = executor,+ snapshot = facade.snapshot,+ listener = object : Camera2ExtensionSession.Listener {+ override fun onError(message: String) {+ Log.status("Camera2NightPreview", message)+ onError(message)+ }+ },+ )+ bridge = PreviewSurfaceBridge { event ->+ when (event) {+ is PreviewSurfaceEvent.Available -> session.open(+ cameraId = cameraId,+ surface = event.surface,+ requestedSize = FrameSize(event.width, event.height),+ )+ is PreviewSurfaceEvent.SizeChanged -> {+ session.close()+ session.open(+ cameraId = cameraId,+ surface = event.surface,+ requestedSize = FrameSize(event.width, event.height),+ )+ }+ is PreviewSurfaceEvent.Destroyed -> session.close()+ }+ }+ }++ fun close() {+ session.close()+ executor.shutdown()+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.ktindex 6e8a021616..f5e722fa91 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -48,10 +48,14 @@ internal fun Camera2Preview( com.vayunmathur.camera.domain.FlashSetting.OFF, onSessionChanged: (Camera2Session?) -> Unit = {}, onError: (String) -> Unit = {},+ /** Plane consumer for the analysis stream; null = no analysis output. */+ analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null, modifier: Modifier = Modifier, ) { val context = LocalContext.current- val sessionHolder = remember(cameraId) { Camera2PreviewSession(context, cameraId, onError) }+ val sessionHolder = remember(cameraId) {+ Camera2PreviewSession(context, cameraId, onError, analysisConsumer)+ } DisposableEffect(sessionHolder) { onSessionChanged(sessionHolder.session)@@ -96,6 +100,7 @@ private class Camera2PreviewSession( context: Context, private val cameraId: String, private val onError: (String) -> Unit = {},+ analysisConsumer: com.vayunmathur.camera.platform.camera2.AnalysisConsumer? = null, ) { val executor = Camera2Executor("Camera2Preview-$cameraId") val session: Camera2Session@@ -114,6 +119,7 @@ private class Camera2PreviewSession( snapshot = facade.snapshot, ringConfig = ReprocessRingConfig(enabled = ReprocessRingGate.ENABLED), rawRingConfig = RawRingConfig(enabled = RawRingGate.ENABLED),+ analysisConsumer = analysisConsumer, listener = object : Camera2Session.Listener { override fun onError(message: String) { Log.status("Camera2Preview", message)
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.ktindex 33bad619ef..175ec99365 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewSurface.kt@@ -16,9 +16,13 @@ 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.onCamera2NightPreviewFailed import com.vayunmathur.camera.platform.onCamera2PreviewFailed+import com.vayunmathur.camera.platform.registerCamera2ExtensionSession import com.vayunmathur.camera.platform.onViewfinderZoomRatio import com.vayunmathur.camera.platform.retrySessionBind+import com.vayunmathur.camera.platform.camera2AnalysisConsumer+import com.vayunmathur.camera.platform.camera2AnalysisServes import com.vayunmathur.camera.platform.registerCamera2Session import com.vayunmathur.camera.platform.setScreenFlash import com.vayunmathur.library.log.Log@@ -39,9 +43,29 @@ internal fun CameraPreviewSurface( coordinateTransformer: MutableCoordinateTransformer, ) { val useCamera2Preview = state.useCamera2Preview+ val useCamera2NightPreview = state.useCamera2NightPreview val surfaceRequest = state.surfaceRequest - if (useCamera2Preview) {+ if (useCamera2NightPreview) {+ // Camera2 NIGHT extension preview: registers the live extension+ // session so the night shutter can serve from Camera2. Takes+ // precedence over both regular previews; a probe/configure+ // failure latches the bind and the branch below serves instead.+ val nightCamera2Id = state.selectedLens?.logicalCameraId.orEmpty()+ if (nightCamera2Id.isNotEmpty()) {+ Camera2NightPreview(+ cameraId = nightCamera2Id,+ onSessionChanged = { session ->+ viewModel.registerCamera2ExtensionSession(session)+ },+ onError = { viewModel.onCamera2NightPreviewFailed(nightCamera2Id) },+ modifier = previewModifier,+ )+ } else {+ Box(modifier = previewModifier.background(Color.Black))+ }+ }+ if (useCamera2Preview && !useCamera2NightPreview) { // 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.@@ -63,6 +87,14 @@ internal fun CameraPreviewSurface( onSessionChanged = { session -> viewModel.registerCamera2Session(session) },+ // Analysis wiring: luma-only plane consumer when policy+ // selects Camera2; QR/bitmap sessions stay CameraX (they+ // never compose this preview).+ analysisConsumer = if (viewModel.camera2AnalysisServes()) {+ viewModel.camera2AnalysisConsumer()+ } else {+ null+ }, onError = { viewModel.onCamera2PreviewFailed(camera2Id) }, modifier = previewModifier, )@@ -70,7 +102,7 @@ internal fun CameraPreviewSurface( Box(modifier = previewModifier.background(Color.Black)) } }- if (!useCamera2Preview) {+ if (!useCamera2Preview && !useCamera2NightPreview) { 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}")@@ -119,7 +151,7 @@ internal fun CameraPreviewSurface( onScreenFlashReady = { screenFlash -> viewModel.setScreenFlash(screenFlash) }, ) }- if (!useCamera2Preview && surfaceRequest == null) {+ if (!useCamera2Preview && !useCamera2NightPreview && 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.
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 c40ad9c097..cc15bb3fde 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -22,6 +22,7 @@ import com.vayunmathur.camera.platform.CameraViewModel import com.vayunmathur.camera.platform.PhotoAnalyzer import com.vayunmathur.camera.platform.addMotionFrame import com.vayunmathur.camera.platform.applyExposureCompensation+import com.vayunmathur.camera.platform.clearCamera2NightFallback import com.vayunmathur.camera.platform.applyImageCaptureFlashMode import com.vayunmathur.camera.platform.enableTorch import com.vayunmathur.camera.platform.onLuminance@@ -61,6 +62,7 @@ internal fun CameraScreenEffects( val sessionKind = state.sessionKind val useNightPreview = state.useNightPreview val useCamera2Preview = state.useCamera2Preview+ val useCamera2NightPreview = state.useCamera2NightPreview // Tracks physical orientation purely to rotate the on-screen control icons. Capture output // rotation is handled by CameraX via SessionConfig.setAutoRotationEnabled(true).@@ -118,6 +120,11 @@ internal fun CameraScreenEffects( LaunchedEffect(useNightPreview) { Log.dev("NightPreview", "CameraScreen useNightPreview recomputed=$useNightPreview sessionKind=$sessionKind cameraMode=$cameraMode nightModeActive=${state.nightModeActive} nightExtAvailable=${state.nightExtAvailable} lensFacing=$lensFacing") }+ // A new lens/mode is a fresh bind: clear the Camera2 extension-preview+ // failure latch so the next night engagement gets one honest attempt.+ LaunchedEffect(selectedLens, cameraMode) {+ viewModel.clearCamera2NightFallback()+ } val surfaceRequest = state.surfaceRequest LaunchedEffect(surfaceRequest) { Log.dev("NightPreview", "CameraScreen surfaceRequest changed res=${surfaceRequest?.resolution} frameType=${surfaceRequest?.javaClass?.simpleName} useNightPreview=$useNightPreview sessionKind=$sessionKind thread=${Thread.currentThread().name} lensFacing=${lensFacing}")@@ -254,13 +261,16 @@ internal fun CameraScreenEffects( val zslCompatible by viewModel.zslCompatible.collectAsState() val zslKey = if (sessionKind == SessionKind.PHOTO) zslCompatible else null val bindSettings by viewModel.bindTimeSettings.collectAsState()- LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, useCamera2Preview, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) {+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, useCamera2Preview, useCamera2NightPreview, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) { // Camera2 preview engine (Phase 2, PHOTO, no other outputs yet) owns a // camera via Camera2Session directly. SetupPhotoSession() would double-open // the same cameraId — Camera2 open fails ERROR_CAMERA_IN_USE. So keep full // CameraX teardown lifecycle, skip CameraX Preview/ImageCapture/ImageAnalysis // preview binding, and let Camera2Preview compose the surface.- if (useCamera2Preview) {+ // Same for the Camera2 NIGHT extension preview: its extension+ // session owns the camera, so CameraX (including its own night+ // extension session) must not bind alongside it.+ if (useCamera2Preview || useCamera2NightPreview) { lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.sessionBindFailedMutable.value = false viewModel.teardownSession()
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 05c5499d2e..8073f34d0e 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -102,6 +102,10 @@ import com.vayunmathur.camera.platform.BokehAnalyzer val camera2FallbackBindKey: String? = null, /** Phase 6: a Camera2 NIGHT extension session is live (strength hides). */ val camera2NightSessionActive: Boolean = false,+ /** Camera2 NIGHT gate (default ON, persisted); policy still decides. */+ val camera2NightEnabled: Boolean = true,+ /** Bind key latched after a Camera2 extension preview failure, or null. */+ val camera2NightFallbackBindKey: String? = null, ) { var activeSetting by activeSettingState var maskBitmap by maskBitmapState@@ -143,6 +147,29 @@ import com.vayunmathur.camera.platform.BokehAnalyzer ) } + /**+ * True when the Camera2 NIGHT extension preview owns the viewfinder:+ * PHOTO, night engaged (luma hysteresis / indicator via the existing+ * flows), the persisted Camera2 night gate on, and no extension-preview+ * failure latched for this bind. The extension session itself re-probes+ * the lens at open (`Camera2ExtensionProbe`); a probe/configure failure+ * latches `camera2NightFallbackBindKey` and the regular preview+ * (Camera2 or CameraX, with CameraX-extension → own-burst capture+ * order) serves instead. This intentionally does NOT require the+ * CameraX extension to be usable — policy order is Camera2 first.+ */+ val useCamera2NightPreview: Boolean+ get() {+ if (cameraMode != CameraMode.PHOTO || !nightModeActive) return false+ if (!camera2NightEnabled) return false+ if (!com.vayunmathur.camera.platform.camera2.NightCamera2Gate.ENABLED) return false+ val cameraId = selectedLens?.logicalCameraId+ if (cameraId.isNullOrEmpty()) return false+ val bindKey = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch+ .bindKey(cameraId, cameraMode)+ return camera2NightFallbackBindKey != bindKey+ }+ /** * Strength indicator value to show, or null to hide it. There is no * Camera2 strength flow, so on the Camera2 night path the indicator is@@ -245,6 +272,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen val camera2PreviewEnabled by viewModel.camera2PreviewEnabled.collectAsState() val camera2FallbackBindKey by viewModel.camera2FallbackBindKey.collectAsState() val camera2NightSessionActive by viewModel.camera2NightSessionActive.collectAsState()+ val camera2NightEnabled by viewModel.camera2NightEnabled.collectAsState()+ val camera2NightFallbackBindKey by viewModel.camera2NightFallbackBindKey.collectAsState() val sessionBindFailed by viewModel.sessionBindFailed.collectAsState() val sessionBindRetry by viewModel.sessionBindRetry.collectAsState() val availableZoomLevels by viewModel.availableZoomLevels.collectAsState()@@ -274,6 +303,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen nightModeActive, extensionStrength, sloMoSupported, highSpeedActive, photoSessionActive, analysisStreamActive, nightExtAvailable, surfaceRequest, camera2PreviewEnabled, camera2FallbackBindKey, camera2NightSessionActive,+ camera2NightEnabled, camera2NightFallbackBindKey, sessionBindFailed, sessionBindRetry, availableZoomLevels, galleryBitmap, panoSweeping, panoStitching, panoDots, panoCurrentAngle, panoDirection, panoPitch,@@ -342,6 +372,8 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen camera2PreviewEnabled = camera2PreviewEnabled, camera2FallbackBindKey = camera2FallbackBindKey, camera2NightSessionActive = camera2NightSessionActive,+ camera2NightEnabled = camera2NightEnabled,+ camera2NightFallbackBindKey = camera2NightFallbackBindKey, ) } }
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.ktnew file mode 100644index 0000000000..65c9a32786--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2AnalysisSessionTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.util.Range+import android.util.Size+import android.view.Surface+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.Mockito.mock+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Analysis-stream wiring on [Camera2Session]: the YUV analysis output joins+ * the session outputs + repeating targets when a consumer is supplied, and+ * a stream-combination configure failure drops analysis (only) and keeps+ * preview streaming.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2AnalysisSessionTest {++ private class FakeAnalysisOutput(override val surface: Surface) : AnalysisOutput {+ var closed = false+ override fun close() { closed = true }+ }++ private class FakeSessionHandle : CaptureSessionHandle {+ val streamingTargets = mutableListOf<List<Surface>>()+ var closed = false+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+ override fun setRepeatingStreaming(+ params: ResolvedRequestParams,+ targets: List<Surface>,+ callback: PreviewResultCallback?,+ ) {+ streamingTargets += targets+ }+ override fun captureStill(+ params: ResolvedStillParams,+ stillTarget: Surface,+ callback: StillResultCallback,+ ) {+ callback.onCompleted(RawStillMetadata())+ }+ override fun close() { closed = true }+ }++ private class FakeDeviceHandle(+ private val sessionHandle: FakeSessionHandle,+ private val analysisSurface: Surface?,+ private val failWhenAnalysisPresent: Boolean,+ ) : DeviceHandle {+ override val cameraId: String = "0"+ var configureAttempts = 0+ override fun createCaptureSession(+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ configureAttempts+++ if (failWhenAnalysisPresent && analysisSurface != null && analysisSurface in surfaces) {+ callback.onConfigureFailed()+ } else {+ callback.onConfigured(sessionHandle)+ }+ }+ override fun close() {}+ }++ private class FakeDriver(+ private val device: FakeDeviceHandle,+ private val analysisOutput: FakeAnalysisOutput?,+ ) : Camera2Driver {+ val analysisSizes = mutableListOf<FrameSize>()+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ callback.onOpened(device)+ }+ override fun createStillOutput(size: FrameSize): StillOutput? = null+ override fun createAnalysisOutput(size: FrameSize, consumer: AnalysisConsumer): AnalysisOutput? {+ analysisSizes += size+ return analysisOutput+ }+ }++ private fun snapshot(): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ zoomRatioRange = Range(1f, 10f),+ hasFlashUnit = true,+ exposureCompensationEvRange = Range(-4f, 4f),+ sizesByFormat = mapOf(+ ImageFormat.PRIVATE to listOf(Size(1920, 1080), Size(1280, 720)),+ ImageFormat.YUV_420_888 to listOf(Size(1920, 1080), Size(1280, 960), Size(640, 480)),+ ),+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = 1,+ maxAeRegions = 1,+ ).snapshot++ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+ }++ @Test fun analysisOutputStreamsAlongsidePreview() {+ val executor = Camera2Executor("Camera2AnalysisSessionTest-ok")+ try {+ val analysisSurface = mock(Surface::class.java)+ val analysisOutput = FakeAnalysisOutput(analysisSurface)+ val handle = FakeSessionHandle()+ val device = FakeDeviceHandle(handle, analysisSurface, failWhenAnalysisPresent = false)+ val driver = FakeDriver(device, analysisOutput)+ val session = Camera2Session(+ driver, executor, snapshot(),+ analysisConsumer = AnalysisConsumer { },+ )+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()++ assertEquals(SessionState.STREAMING, session.state)+ assertTrue(session.hasAnalysisOutput)+ // Capped at ~1.2 MP: largest YUV at/under the cap is 1280x960.+ assertEquals(listOf(FrameSize(1280, 960)), driver.analysisSizes)+ assertEquals(FrameSize(1280, 960), session.currentAnalysisSize())+ // The analysis surface is a repeating-request target.+ assertTrue(handle.streamingTargets.single().contains(analysisSurface))++ session.close()+ executor.drain()+ assertTrue(analysisOutput.closed)+ assertFalse(session.hasAnalysisOutput)+ } finally {+ executor.shutdown()+ }+ }++ @Test fun configureFailureDropsAnalysisAndKeepsPreview() {+ val executor = Camera2Executor("Camera2AnalysisSessionTest-degrade")+ try {+ val analysisSurface = mock(Surface::class.java)+ val analysisOutput = FakeAnalysisOutput(analysisSurface)+ val handle = FakeSessionHandle()+ val device = FakeDeviceHandle(handle, analysisSurface, failWhenAnalysisPresent = true)+ val driver = FakeDriver(device, analysisOutput)+ val errors = mutableListOf<String>()+ val session = Camera2Session(+ driver, executor, snapshot(),+ listener = object : Camera2Session.Listener {+ override fun onError(message: String) { errors += message }+ },+ analysisConsumer = AnalysisConsumer { },+ )+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()++ // Preview survived: streaming without analysis, no error latched.+ assertEquals(SessionState.STREAMING, session.state)+ assertFalse(session.hasAnalysisOutput)+ assertTrue(analysisOutput.closed)+ assertEquals(2, device.configureAttempts)+ assertTrue(errors.isEmpty(), "analysis degrade must not report an error: $errors")+ assertFalse(handle.streamingTargets.single().contains(analysisSurface))+ } finally {+ executor.shutdown()+ }+ }++ @Test fun noConsumerMeansNoAnalysisOutput() {+ val executor = Camera2Executor("Camera2AnalysisSessionTest-none")+ try {+ val handle = FakeSessionHandle()+ val device = FakeDeviceHandle(handle, null, failWhenAnalysisPresent = false)+ val driver = FakeDriver(device, null)+ val session = Camera2Session(driver, executor, snapshot())+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ assertFalse(session.hasAnalysisOutput)+ assertTrue(driver.analysisSizes.isEmpty())+ } finally {+ executor.shutdown()+ }+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.ktindex 21ab74c90c..06adaf0a32 100644--- a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt@@ -68,6 +68,34 @@ class StreamSelectionTest { assertNull(StreamSelection.rejectionFor(FrameSize(1600, 900), supported)) } + @Test fun analysisSizeCapsAtPhotoAnalysisPixels() {+ val snapshot = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = mapOf(+ ImageFormat.YUV_420_888 to listOf(+ Size(1920, 1080), Size(1280, 960), Size(1280, 720), Size(640, 480),+ ),+ ),+ ).snapshot+ // Largest at/under ~1.2 MP wins (1280x960), never sensor resolution.+ assertEquals(FrameSize(1280, 960), StreamSelection.selectAnalysisSize(snapshot))+ }++ @Test fun analysisSizeOverCapPicksSmallestAndEmptyPicksNull() {+ val overCap = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = mapOf(+ ImageFormat.YUV_420_888 to listOf(Size(4000, 3000), Size(1920, 1080)),+ ),+ ).snapshot+ assertEquals(FrameSize(1920, 1080), StreamSelection.selectAnalysisSize(overCap))+ val noYuv = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = mapOf(ImageFormat.PRIVATE to listOf(Size(640, 480))),+ ).snapshot+ assertNull(StreamSelection.selectAnalysisSize(noYuv))+ }+ @Test fun supportedSizesPreferSurfaceTextureThenPrivate() { val withTexture = CharacteristicsFacade.fromFakeMap( cameraId = "0",
camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt b/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.ktindex 382c1ac2f6..0b2b5d3f58 100644--- a/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt+++ b/camera/src/test/java/com/vayunmathur/camera/ui/CameraScreenStateTest.kt@@ -23,10 +23,13 @@ class CameraScreenStateTest { mirrorFront: Boolean = true, nightModeActive: Boolean = false, nightExtAvailable: Boolean = false,+ selectedLens: com.vayunmathur.camera.domain.PhysicalLens? = null,+ camera2NightEnabled: Boolean = true,+ camera2NightFallbackBindKey: String? = null, ) = CameraScreenState( cameraMode = mode, lensFacing = lensFacing,- selectedLens = null,+ selectedLens = selectedLens, availableLenses = emptyList(), hasFlashUnit = true, flashMode = FlashMode.OFF,@@ -81,6 +84,18 @@ class CameraScreenStateTest { activeSettingState = mutableStateOf(null), maskBitmapState = mutableStateOf(null), deviceRotationState = mutableIntStateOf(0),+ camera2NightEnabled = camera2NightEnabled,+ camera2NightFallbackBindKey = camera2NightFallbackBindKey,+ )++ private fun lens(id: String = "0") = com.vayunmathur.camera.domain.PhysicalLens(+ logicalCameraId = id,+ lensType = com.vayunmathur.camera.domain.LensType.WIDE,+ facing = com.vayunmathur.camera.domain.LensFacing.BACK,+ focalLengthMm35Eq = 24f,+ nominalZoomRatio = 1f,+ fallbackPriority = 0,+ labelKey = "wide", ) @Test fun modeFamilies() {@@ -111,6 +126,18 @@ class CameraScreenStateTest { assertFalse(state(nightModeActive = false, nightExtAvailable = true).useNightPreview) } + @Test fun camera2NightPreviewRequiresPhotoNightGateAndLens() {+ // Camera2-first: does NOT require the CameraX extension to be usable.+ assertTrue(state(nightModeActive = true, nightExtAvailable = false, selectedLens = lens()).useCamera2NightPreview)+ assertFalse(state(nightModeActive = false, selectedLens = lens()).useCamera2NightPreview)+ assertFalse(state(nightModeActive = true, selectedLens = lens(), camera2NightEnabled = false).useCamera2NightPreview)+ assertFalse(state(nightModeActive = true, selectedLens = null).useCamera2NightPreview)+ assertFalse(state(CameraMode.PORTRAIT, nightModeActive = true, selectedLens = lens()).useCamera2NightPreview)+ // Latched failure for this bind (cameraId:mode) suppresses retry.+ val key = com.vayunmathur.camera.platform.camera2.Camera2FallbackLatch.bindKey("0", CameraMode.PHOTO)+ assertFalse(state(nightModeActive = true, selectedLens = lens(), camera2NightFallbackBindKey = key).useCamera2NightPreview)+ }+ @Test fun previewAspectRatios() { assertEquals(9f / 16f, state(aspectRatio = AspectRatioOption.RATIO_16_9).previewAspectRatio) assertEquals(3f / 4f, state(aspectRatio = AspectRatioOption.RATIO_4_3).previewAspectRatio)