camera: Camera2 preview+control session behind a gate (Phase 2)
- Commit
1997090cf7ebae29e187939f76e821c755e68cc8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 17:44 UTC (14 days ago)
- Parents
eb1dbe4
A Camera2 session core now exists: driver seam over CameraDevice/CaptureSession, deterministic stream selection validated against the characteristics snapshot before opening (no trial binds), controls resolved purely onto raw request keys (zoom ratio with crop-region fallback, torch, EV steps, AF/AE regions behind the region-count gates), and the viewfinder->sensor metering transform as pure math. Every async callback is generation-checked against the Phase-0 state machine. Wired for PHOTO preview only behind a policy gate that defaults to CameraX - gate on, the effects skip the CameraX session and the same overlay/effects tree renders over a TextureView preview; still capture stays CameraX until the stills phase, so gate-on mode is preview-only by design and needs a device pass before defaulting anywhere. Verified: full camera suite 677 tests green incl. 29 new camera2 tests (session sequencing, stale-generation drops, stream rejection, metering math, gate policy).
Diff
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 8cc5aca740..9a96c83658 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -157,6 +157,19 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { internal val ds = DataStoreUtils.getInstance(app) + /**+ * Gate for the Camera2 preview engine (Phase 2). Default OFF — CameraX+ * stays the live path and `Camera2Preview` is never composed. In-memory+ * only for now; `PreviewEnginePolicy` further restricts it to PHOTO.+ */+ internal val camera2PreviewEnabledMutable = MutableStateFlow(false)+ val camera2PreviewEnabled = camera2PreviewEnabledMutable.asStateFlow()++ /** Turns the Camera2 preview gate on/off (PHOTO only; see PreviewEnginePolicy). */+ fun setCamera2PreviewEnabled(enabled: Boolean) {+ camera2PreviewEnabledMutable.value = enabled+ }+ internal val cameraModeMutable = MutableStateFlow(CameraMode.PHOTO) val cameraMode = cameraModeMutable.asStateFlow()
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.ktnew file mode 100644index 0000000000..b11ce400bf--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Controls.kt@@ -0,0 +1,121 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata+import kotlin.math.roundToInt++/**+ * Camera2 migration Phase 2: preview controls as raw `CaptureRequest` fields.+ *+ * The UI-facing state ([Camera2ControlState]) is what the screen already+ * holds (zoom ratio, torch, EV, tap point). [resolve] turns it into the+ * exact request parameters for one lens, using only the facade snapshot —+ * clamping and fallbacks happen here, purely, so the driver only writes+ * fields. Re-resolving on every change and re-issuing the repeating request+ * is the session's job.+ */++/** What the user asked for. EV is in stops (e.g. +1.0), zoom is a ratio ≥ min. */+data class Camera2ControlState(+ val zoomRatio: Float = 1f,+ val torchOn: Boolean = false,+ val exposureCompEv: Float = 0f,+ val afRegion: MeteringRegion? = null,+ val aeRegion: MeteringRegion? = null,+) {+ companion object {+ val DEFAULT = Camera2ControlState()+ }+}++/**+ * Resolved `CaptureRequest` fields for one preview request. Null fields are+ * left unset on the builder (HAL default applies).+ */+data class ResolvedRequestParams(+ /** `CONTROL_ZOOM_RATIO`; null when the crop-region fallback is used. */+ val zoomRatio: Float?,+ /** `SCALER_CROP_REGION`; null when [zoomRatio] carries the zoom. */+ val cropRegion: SensorRect?,+ /** `FLASH_MODE` (`CameraMetadata.FLASH_MODE_*`). */+ val flashMode: Int,+ /** `CONTROL_AE_EXPOSURE_COMPENSATION`, in HAL steps (not EV). */+ val aeExposureCompensationSteps: Int,+ /** `CONTROL_AF_REGIONS`; empty when the lens takes no AF regions. */+ val afRegions: List<MeteringRegion>,+ /** `CONTROL_AE_REGIONS`; empty when the lens takes no AE regions. */+ val aeRegions: List<MeteringRegion>,+ /** True when a tap point is being metered (AF/AE triggered at a point). */+ val meteringActive: Boolean,+)++object Camera2Controls {++ /**+ * Resolves [state] against [snapshot]. Never throws: every value is+ * clamped to what the lens advertises, and unsupported features degrade+ * to their no-op field values (torch off without a flash unit, no+ * metering regions when the HAL reports zero region slots).+ */+ fun resolve(+ state: Camera2ControlState,+ snapshot: LensCharacteristicsSnapshot,+ ): ResolvedRequestParams {+ val zoom = state.zoomRatio.coerceIn(snapshot.minZoomRatio, snapshot.maxZoomRatio)+ val supportsZoomRatio = snapshot.supportsZoomRatioKey+ val activeArray = SensorRect.ofSize(snapshot.activeArrayWidth, snapshot.activeArrayHeight)+ val crop = if (supportsZoomRatio) {+ null+ } else {+ MeteringTransform.cropRegionForZoom(activeArray, zoom)+ }+ val flashMode = if (state.torchOn && snapshot.hasFlashUnit) {+ CameraMetadata.FLASH_MODE_TORCH+ } else {+ CameraMetadata.FLASH_MODE_OFF+ }+ return ResolvedRequestParams(+ zoomRatio = if (supportsZoomRatio) zoom else null,+ cropRegion = crop,+ flashMode = flashMode,+ aeExposureCompensationSteps = evToSteps(state.exposureCompEv, snapshot),+ afRegions = if (snapshot.maxAfRegions > 0) {+ listOfNotNull(state.afRegion)+ } else {+ emptyList()+ },+ aeRegions = if (snapshot.maxAeRegions > 0) {+ listOfNotNull(state.aeRegion)+ } else {+ emptyList()+ },+ meteringActive = state.afRegion != null || state.aeRegion != null,+ )+ }++ /**+ * Converts an EV value to `CONTROL_AE_EXPOSURE_COMPENSATION` steps using+ * the lens's step size, clamped to the advertised EV range. A lens with+ * no readable step/range takes 0 (HAL default).+ */+ fun evToSteps(ev: Float, snapshot: LensCharacteristicsSnapshot): Int {+ val step = snapshot.exposureCompensationStepEv ?: return 0+ val range = snapshot.exposureCompensationEvRange ?: return 0+ if (step <= 0f) return 0+ val clampedEv = ev.coerceIn(range.lower, range.upper)+ return (clampedEv / step).roundToInt()+ }++ /** The active array as a [SensorRect], or an empty rect when unreadable. */+ fun activeArrayOf(snapshot: LensCharacteristicsSnapshot): SensorRect =+ SensorRect.ofSize(snapshot.activeArrayWidth, snapshot.activeArrayHeight)++ /** The crop window the current zoom implies (for metering transforms). */+ fun currentCropRegion(+ state: Camera2ControlState,+ snapshot: LensCharacteristicsSnapshot,+ ): SensorRect {+ val activeArray = activeArrayOf(snapshot)+ val zoom = state.zoomRatio.coerceIn(snapshot.minZoomRatio, snapshot.maxZoomRatio)+ return MeteringTransform.cropRegionForZoom(activeArray, zoom)+ }+}
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.ktnew file mode 100644index 0000000000..528b92aa01--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -0,0 +1,202 @@+package com.vayunmathur.camera.platform.camera2++import android.annotation.SuppressLint+import android.content.Context+import android.graphics.Rect+import android.hardware.camera2.CameraCaptureSession+import android.hardware.camera2.CameraDevice+import android.hardware.camera2.CameraManager+import android.hardware.camera2.CaptureRequest+import android.hardware.camera2.params.MeteringRectangle+import android.hardware.camera2.params.OutputConfiguration+import android.hardware.camera2.params.SessionConfiguration+import android.os.Build+import android.os.Handler+import android.view.Surface++/**+ * Camera2 migration Phase 2: the driver seam between [Camera2Session] and the+ * `android.hardware.camera2` API. Robolectric's Camera2 shadows cannot drive+ * a real session, so the session logic (state machine, stream validation,+ * control resolution) is written against these interfaces and unit-tested+ * with a fake driver; [AndroidCamera2Driver] is the only implementation that+ * touches `CameraDevice`/`CameraCaptureSession`.+ *+ * All callbacks fire on the session's [Camera2Executor] thread (the driver is+ * constructed with its [Handler]); implementations must not call back from+ * any other thread, and the session generation-checks every callback anyway.+ */++fun interface SessionErrorListener {+ fun onError(message: String)+}++/** Callbacks for one [Camera2Driver.openCamera] call. */+interface DeviceCallback {+ fun onOpened(device: DeviceHandle)+ fun onClosed()+ fun onDisconnected()+ fun onError(errorCode: Int)+}++/** Callbacks for one [DeviceHandle.createCaptureSession] call. */+interface CaptureSessionCallback {+ fun onConfigured(session: CaptureSessionHandle)+ fun onConfigureFailed()+ fun onClosed()+}++/** Testable handle over a `CameraDevice`. */+interface DeviceHandle {+ val cameraId: String+ fun createCaptureSession(surfaces: List<Surface>, callback: CaptureSessionCallback)+ fun close()+}++/** Testable handle over a `CameraCaptureSession`. */+interface CaptureSessionHandle {+ /** Issues [params] as the TEMPLATE_PREVIEW repeating request on [target]. */+ fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface)+ fun close()+}++/** Opens cameras; the session owns the returned handles' lifecycle. */+interface Camera2Driver {+ fun openCamera(cameraId: String, callback: DeviceCallback)+}++/** Converts a pure [SensorRect] into the HAL's `Rect`. */+internal fun SensorRect.toRect(): Rect = Rect(left, top, right, bottom)++internal fun MeteringRegion.toMeteringRectangle(): MeteringRectangle =+ MeteringRectangle(rect.toRect(), weight)++/** Applies resolved preview controls onto a TEMPLATE_PREVIEW builder. */+internal fun CaptureRequest.Builder.applyPreviewParams(+ params: ResolvedRequestParams,+ target: Surface,+) {+ addTarget(target)+ set(CaptureRequest.CONTROL_MODE, CaptureRequest.CONTROL_MODE_AUTO)+ set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)+ set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)+ if (params.zoomRatio != null) {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ set(CaptureRequest.CONTROL_ZOOM_RATIO, params.zoomRatio)+ } else if (params.cropRegion != null) {+ set(CaptureRequest.SCALER_CROP_REGION, params.cropRegion.toRect())+ }+ } else if (params.cropRegion != null) {+ set(CaptureRequest.SCALER_CROP_REGION, params.cropRegion.toRect())+ }+ set(CaptureRequest.FLASH_MODE, params.flashMode)+ set(+ CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION,+ params.aeExposureCompensationSteps,+ )+ if (params.afRegions.isNotEmpty()) {+ set(+ CaptureRequest.CONTROL_AF_REGIONS,+ params.afRegions.map { it.toMeteringRectangle() }.toTypedArray(),+ )+ set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START)+ }+ if (params.aeRegions.isNotEmpty()) {+ set(+ CaptureRequest.CONTROL_AE_REGIONS,+ params.aeRegions.map { it.toMeteringRectangle() }.toTypedArray(),+ )+ set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START)+ }+}++/**+ * Real driver over [CameraManager]. Constructed with the session executor's+ * handler so every HAL callback lands on the camera thread.+ */+class AndroidCamera2Driver(+ private val manager: CameraManager,+ private val handler: Handler,+) : Camera2Driver {++ constructor(context: Context, handler: Handler) : this(+ context.getSystemService(CameraManager::class.java),+ handler,+ )++ @SuppressLint("MissingPermission")+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ manager.openCamera(+ cameraId,+ object : CameraDevice.StateCallback() {+ override fun onOpened(camera: CameraDevice) =+ callback.onOpened(AndroidDeviceHandle(camera, handler))++ override fun onClosed(camera: CameraDevice) = callback.onClosed()++ override fun onDisconnected(camera: CameraDevice) {+ camera.close()+ callback.onDisconnected()+ }++ override fun onError(camera: CameraDevice, error: Int) {+ camera.close()+ callback.onError(error)+ }+ },+ handler,+ )+ }+}++private class AndroidDeviceHandle(+ private val device: CameraDevice,+ private val handler: Handler,+) : DeviceHandle {++ override val cameraId: String get() = device.id++ override fun createCaptureSession(+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ val stateCallback = object : CameraCaptureSession.StateCallback() {+ override fun onConfigured(session: CameraCaptureSession) =+ callback.onConfigured(AndroidCaptureSessionHandle(device, session))++ override fun onConfigureFailed(session: CameraCaptureSession) =+ callback.onConfigureFailed()++ override fun onClosed(session: CameraCaptureSession) = callback.onClosed()+ }+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {+ val outputs = surfaces.map { OutputConfiguration(it) }+ val config = SessionConfiguration(+ SessionConfiguration.SESSION_REGULAR,+ outputs,+ { command -> handler.post(command) },+ stateCallback,+ )+ device.createCaptureSession(config)+ } else {+ @Suppress("DEPRECATION")+ device.createCaptureSession(surfaces, stateCallback, handler)+ }+ }++ override fun close() = device.close()+}++private class AndroidCaptureSessionHandle(+ private val device: CameraDevice,+ private val session: CameraCaptureSession,+) : CaptureSessionHandle {++ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {+ val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)+ builder.applyPreviewParams(params, target)+ session.setRepeatingRequest(builder.build(), null, null)+ }++ override fun close() = session.close()+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktnew file mode 100644index 0000000000..3ac4da380a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -0,0 +1,265 @@+package com.vayunmathur.camera.platform.camera2++import android.view.Surface++/**+ * Camera2 migration Phase 2: preview session core. Opens a `CameraDevice` on+ * the Phase-0 [Camera2Executor], configures a capture session whose only+ * output is the [PreviewSurfaceBridge] surface, and streams a+ * TEMPLATE_PREVIEW repeating request carrying the resolved controls.+ *+ * 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+ * from a torn-down generation is dropped rather than resurrecting a closed+ * device.+ *+ * Stream selection is validated against the [CharacteristicsFacade] snapshot+ * before the device is opened (see [StreamSelection]): an unsupported+ * preview size fails fast here and never reaches a trial bind.+ *+ * Ownership: whoever constructs this owns it and must call [close] (e.g.+ * from a `DisposableEffect`). [close] is idempotent and terminal.+ */+class Camera2Session(+ private val driver: Camera2Driver,+ private val executor: Camera2Executor,+ private val snapshot: LensCharacteristicsSnapshot,+ private val stateMachine: SessionStateMachine = SessionStateMachine(),+ private val listener: Listener? = null,+) {++ /** Session lifecycle notifications; all fire on the executor thread. */+ interface Listener {+ fun onStateChanged(state: SessionState) {}+ fun onError(message: String) {}+ fun onStreaming(previewSize: FrameSize) {}+ }++ val state: SessionState get() = stateMachine.state+ val generation: Long get() = stateMachine.generation++ private var device: DeviceHandle? = null+ private var captureSession: CaptureSessionHandle? = null+ private var previewSurface: Surface? = null+ private var previewSize: FrameSize? = null+ private var controls: Camera2ControlState = Camera2ControlState.DEFAULT++ /** Current control state (user intent, unresolved). */+ val controlState: Camera2ControlState get() = controls++ /**+ * Opens [cameraId] and starts preview on [surface]. [requestedSize] is+ * validated against the snapshot first; a rejected size reports+ * [Listener.onError] and never opens the device. No-op unless CLOSED.+ */+ fun open(cameraId: String, surface: Surface, requestedSize: FrameSize) {+ executor.execute {+ if (stateMachine.state != SessionState.CLOSED) return@execute+ val supported = StreamSelection.supportedPreviewSizes(snapshot)+ val selected = StreamSelection.selectPreviewSize(requestedSize, supported)+ if (selected == null) {+ reportError(+ "no supported preview sizes for camera $cameraId " ++ "(requested ${requestedSize.width}x${requestedSize.height})",+ )+ return@execute+ }+ previewSurface = surface+ previewSize = selected+ if (transition(SessionEvent.OPEN_REQUESTED) !is TransitionResult.Applied) {+ return@execute+ }+ val gen = stateMachine.generation+ runCatching {+ driver.openCamera(cameraId, DeviceCallbackImpl(gen))+ }.onFailure {+ dispatch(gen, SessionEvent.ERROR_OCCURRED)+ reportError("openCamera failed for $cameraId: ${it.message}")+ }+ }+ }++ /** Replaces the whole control state and re-issues the repeating request. */+ fun updateControls(next: Camera2ControlState) {+ executor.execute {+ controls = next+ issueRepeatingRequest()+ }+ }++ /** Applies a zoom ratio (control-bar / pinch), keeping other controls. */+ fun setZoomRatio(ratio: Float) = updateControls(controls.copy(zoomRatio = ratio))++ /** Applies torch on/off, keeping other controls. */+ fun setTorch(on: Boolean) = updateControls(controls.copy(torchOn = on))++ /** Applies exposure compensation in EV stops, keeping other controls. */+ fun setExposureCompEv(ev: Float) = updateControls(controls.copy(exposureCompEv = ev))++ /**+ * Tap-to-focus: transforms a normalised viewfinder tap into AF + AE+ * metering regions (see [MeteringTransform]) and re-issues the request.+ * [displayRotationDegrees] is the display rotation (0/90/180/270);+ * [mirrored] is true for a mirrored front preview.+ */+ fun tapToFocus(+ tapX: Float,+ tapY: Float,+ displayRotationDegrees: Int = 0,+ mirrored: Boolean = false,+ ) {+ executor.execute {+ val activeArray = Camera2Controls.activeArrayOf(snapshot)+ if (activeArray.width <= 0 || activeArray.height <= 0) return@execute+ val crop = Camera2Controls.currentCropRegion(controls, snapshot)+ val region = MeteringTransform.meteringRegionForTap(+ tapX = tapX,+ tapY = tapY,+ activeArray = activeArray,+ cropRegion = crop,+ sensorOrientationDegrees = snapshot.sensorOrientationDegrees,+ displayRotationDegrees = displayRotationDegrees,+ mirrored = mirrored,+ )+ controls = controls.copy(afRegion = region, aeRegion = region)+ issueRepeatingRequest()+ }+ }++ /** Clears tap metering, returning AF/AE to continuous full-frame. */+ fun clearMetering() = updateControls(controls.copy(afRegion = null, aeRegion = null))++ /** The preview size chosen at [open], or null before a successful open. */+ fun currentPreviewSize(): FrameSize? = previewSize++ /**+ * Tears the session down: bumps the generation first (so callbacks+ * already in flight go stale), then closes the capture session and the+ * device. Idempotent.+ */+ fun close() {+ executor.execute {+ if (stateMachine.state == SessionState.CLOSED) return@execute+ val gen = stateMachine.beginTeardown()+ runCatching { captureSession?.close() }+ captureSession = null+ runCatching { device?.close() }+ device = null+ previewSurface = null+ dispatch(gen, SessionEvent.DEVICE_CLOSED)+ if (stateMachine.state == SessionState.CLOSING) {+ stateMachine.completeTeardown()+ }+ notifyState()+ }+ }++ // -- internals (executor thread only) ------------------------------------++ private fun issueRepeatingRequest() {+ val session = captureSession ?: return+ val surface = previewSurface ?: return+ if (stateMachine.state != SessionState.STREAMING) return+ val params = Camera2Controls.resolve(controls, snapshot)+ runCatching { session.setRepeatingPreview(params, surface) }+ .onFailure { reportError("setRepeatingPreview failed: ${it.message}") }+ }++ private fun configureSession(opened: DeviceHandle, gen: Long) {+ val surface = previewSurface ?: return+ if (transition(SessionEvent.CONFIGURE_REQUESTED) !is TransitionResult.Applied) return+ runCatching {+ opened.createCaptureSession(+ listOf(surface),+ SessionCallbackImpl(gen),+ )+ }.onFailure {+ dispatch(gen, SessionEvent.CONFIGURE_FAILED)+ reportError("createCaptureSession failed: ${it.message}")+ }+ }++ private fun transition(event: SessionEvent): TransitionResult {+ val result = stateMachine.transition(event)+ if (result is TransitionResult.Applied) notifyState()+ return result+ }++ private fun dispatch(gen: Long, event: SessionEvent): TransitionResult {+ val result = stateMachine.dispatch(gen, event)+ if (result is TransitionResult.Applied) notifyState()+ return result+ }++ private fun notifyState() {+ listener?.onStateChanged(stateMachine.state)+ }++ private fun reportError(message: String) {+ listener?.onError(message)+ }++ private inner class DeviceCallbackImpl(+ private val gen: Long,+ ) : DeviceCallback {+ override fun onOpened(device: DeviceHandle) {+ if (!stateMachine.isCurrent(gen)) {+ // Stale open completing after teardown: drop the handle.+ runCatching { device.close() }+ return+ }+ if (dispatch(gen, SessionEvent.DEVICE_OPENED) !is TransitionResult.Applied) {+ runCatching { device.close() }+ return+ }+ [email protected] = device+ configureSession(device, gen)+ }++ override fun onClosed() {+ dispatch(gen, SessionEvent.DEVICE_CLOSED)+ }++ override fun onDisconnected() {+ if (!stateMachine.isCurrent(gen)) return+ dispatch(gen, SessionEvent.ERROR_OCCURRED)+ reportError("camera disconnected")+ }++ override fun onError(errorCode: Int) {+ if (!stateMachine.isCurrent(gen)) return+ dispatch(gen, SessionEvent.ERROR_OCCURRED)+ reportError("camera open error $errorCode")+ }+ }++ private inner class SessionCallbackImpl(+ private val gen: Long,+ ) : CaptureSessionCallback {+ override fun onConfigured(session: CaptureSessionHandle) {+ if (!stateMachine.isCurrent(gen)) {+ runCatching { session.close() }+ return+ }+ if (dispatch(gen, SessionEvent.SESSION_CONFIGURED) !is TransitionResult.Applied) {+ runCatching { session.close() }+ return+ }+ captureSession = session+ issueRepeatingRequest()+ previewSize?.let { listener?.onStreaming(it) }+ }++ override fun onConfigureFailed() {+ if (!stateMachine.isCurrent(gen)) return+ dispatch(gen, SessionEvent.CONFIGURE_FAILED)+ reportError("capture session configure failed")+ }++ override fun onClosed() {+ // Session close is a consequence of device teardown; the device+ // callback drives the machine to CLOSED.+ }+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.ktindex 7629cdc0b9..a0b166188d 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/CharacteristicsFacade.kt@@ -35,6 +35,12 @@ data class FormatSummary( /** Pure-data summary of a stream configuration map (never holds the map itself). */ data class StreamConfigSummary( val formats: Map<Int, FormatSummary>,+ /**+ * Sizes legal for a `SurfaceTexture` (TextureView) preview output, from+ * `getOutputSizes(SurfaceTexture::class.java)`. Empty when built from plain+ * sizes (tests) — preview selection then falls back to the format lists.+ */+ val surfaceTextureSizes: List<Size> = emptyList(), ) { fun sizesFor(format: Int): List<Size> = formats[format]?.sizes.orEmpty() fun maxSizeFor(format: Int): Size? = formats[format]?.maxSize@@ -44,15 +50,23 @@ data class StreamConfigSummary( val EMPTY = StreamConfigSummary(emptyMap()) /** Builds a summary from plain sizes — the fake-map entry point for tests. */- fun fromSizes(sizesByFormat: Map<Int, List<Size>>): StreamConfigSummary =- StreamConfigSummary(sizesByFormat.mapValues { (format, sizes) -> FormatSummary(format, sizes) })+ fun fromSizes(+ sizesByFormat: Map<Int, List<Size>>,+ surfaceTextureSizes: List<Size> = emptyList(),+ ): StreamConfigSummary = StreamConfigSummary(+ sizesByFormat.mapValues { (format, sizes) -> FormatSummary(format, sizes) },+ surfaceTextureSizes,+ ) fun fromMap(map: StreamConfigurationMap?): StreamConfigSummary { if (map == null) return EMPTY val byFormat = map.outputFormats.associateWith { format -> runCatching { map.getOutputSizes(format)?.toList().orEmpty() }.getOrDefault(emptyList()) }- return fromSizes(byFormat)+ val textureSizes = runCatching {+ map.getOutputSizes(android.graphics.SurfaceTexture::class.java)?.toList().orEmpty()+ }.getOrDefault(emptyList())+ return fromSizes(byFormat, textureSizes) } } }@@ -80,6 +94,31 @@ data class LensCharacteristicsSnapshot( val availableExtensionModes: List<Int>, val focalLengthsMm: List<Float>, val colorFilterArrangement: Int?,+ /** `SENSOR_INFO_ACTIVE_ARRAY_SIZE` width in pixels; 0 when unreadable. */+ val activeArrayWidth: Int = 0,+ /** `SENSOR_INFO_ACTIVE_ARRAY_SIZE` height in pixels; 0 when unreadable. */+ val activeArrayHeight: Int = 0,+ /** `SENSOR_ORIENTATION` in degrees (0/90/180/270); 0 when unreadable. */+ val sensorOrientationDegrees: Int = 0,+ /**+ * `CONTROL_AE_COMPENSATION_STEP` as a float (EV per compensation step,+ * e.g. 1/6); null when unreadable. Converts an EV value to the integer+ * step count `CONTROL_AE_EXPOSURE_COMPENSATION` takes.+ */+ val exposureCompensationStepEv: Float? = null,+ /**+ * `CONTROL_MAX_REGIONS_AF` / `CONTROL_MAX_REGIONS_AE`; 0 when unreadable.+ * A zero means tap metering regions are not honoured by the HAL.+ */+ val maxAfRegions: Int = 0,+ val maxAeRegions: Int = 0,+ /**+ * True when `CONTROL_ZOOM_RATIO_RANGE` itself was reported, i.e. the+ * request key `CONTROL_ZOOM_RATIO` is honoured. False when [zoomRatioRange]+ * was synthesised from `SCALER_AVAILABLE_MAX_DIGITAL_ZOOM` — zoom then+ * goes through `SCALER_CROP_REGION` instead.+ */+ val supportsZoomRatioKey: Boolean = false, ) { val lensFacing: LensFacing? = when (lensFacingRaw) { CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK@@ -134,6 +173,14 @@ class CharacteristicsFacade private constructor( availableExtensionModes: List<Int> = emptyList(), focalLengthsMm: List<Float> = emptyList(), colorFilterArrangement: Int? = null,+ activeArrayWidth: Int = 0,+ activeArrayHeight: Int = 0,+ sensorOrientationDegrees: Int = 0,+ exposureCompensationStepEv: Float? = null,+ maxAfRegions: Int = 0,+ maxAeRegions: Int = 0,+ supportsZoomRatioKey: Boolean = zoomRatioRange != null,+ surfaceTextureSizes: List<Size> = emptyList(), ): CharacteristicsFacade = fromSnapshot( LensCharacteristicsSnapshot( cameraId = cameraId,@@ -149,12 +196,19 @@ class CharacteristicsFacade private constructor( videoStabilizationModes = videoStabilizationModes, opticalStabilizationModes = opticalStabilizationModes, aeTargetFpsRanges = aeTargetFpsRanges,- streamConfig = StreamConfigSummary.fromSizes(sizesByFormat),+ streamConfig = StreamConfigSummary.fromSizes(sizesByFormat, surfaceTextureSizes), hardwareLevel = hardwareLevel, availableCapabilities = availableCapabilities, availableExtensionModes = availableExtensionModes, focalLengthsMm = focalLengthsMm, colorFilterArrangement = colorFilterArrangement,+ activeArrayWidth = activeArrayWidth,+ activeArrayHeight = activeArrayHeight,+ sensorOrientationDegrees = sensorOrientationDegrees,+ exposureCompensationStepEv = exposureCompensationStepEv,+ maxAfRegions = maxAfRegions,+ maxAeRegions = maxAeRegions,+ supportsZoomRatioKey = supportsZoomRatioKey, ), ) @@ -169,12 +223,14 @@ class CharacteristicsFacade private constructor( val capabilities = get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES) ?.toSet().orEmpty()- val zoomRange = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val zoomRatioRange = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { get(CameraCharacteristics.CONTROL_ZOOM_RATIO_RANGE) } else { null- } ?: get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)- ?.let { max -> Range(1f, max) }+ }+ val zoomRange = zoomRatioRange+ ?: get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM)+ ?.let { max -> Range(1f, max) } val compensationRange = get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE) val compensationStep = get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP) val evRange = if (compensationRange != null && compensationStep != null) {@@ -215,6 +271,15 @@ class CharacteristicsFacade private constructor( focalLengthsMm = get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)?.toList().orEmpty(), colorFilterArrangement = get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT),+ activeArrayWidth =+ get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)?.width() ?: 0,+ activeArrayHeight =+ get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)?.height() ?: 0,+ sensorOrientationDegrees = get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0,+ exposureCompensationStepEv = compensationStep?.toFloat(),+ maxAfRegions = get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF) ?: 0,+ maxAeRegions = get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE) ?: 0,+ supportsZoomRatioKey = zoomRatioRange != null, ), ) }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/MeteringTransform.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/MeteringTransform.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/MeteringTransform.ktnew file mode 100644index 0000000000..b059168f97--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/MeteringTransform.kt@@ -0,0 +1,150 @@+package com.vayunmathur.camera.platform.camera2++import kotlin.math.roundToInt++/**+ * Camera2 migration Phase 2: the viewfinder → sensor coordinate transform for+ * tap metering (`CONTROL_AF_REGIONS` / `CONTROL_AE_REGIONS`). Pure integer /+ * float math — no `Rect`, no `CameraCharacteristics` — so the geometry is+ * unit-tested directly; the driver converts [SensorRect] to+ * `android.graphics.Rect` / `MeteringRectangle` at the HAL boundary.+ *+ * Coordinate spaces:+ * - Viewfinder: normalised 0..1 over the *displayed* (centre-cropped) preview+ * content. The caller divides the tap by the view size; letterboxing outside+ * the content never reaches here.+ * - Sensor: pixel coordinates in `SENSOR_INFO_ACTIVE_ARRAY_SIZE`, the space+ * metering rectangles and `SCALER_CROP_REGION` live in.+ *+ * The transform accounts for: the relative rotation between sensor and+ * display, front-camera mirroring, and the current crop region (digital+ * zoom): a point in the cropped preview maps into the crop window, not the+ * full active array.+ */++/** Axis-aligned rectangle in sensor pixel coordinates (right/bottom exclusive). */+data class SensorRect(val left: Int, val top: Int, val right: Int, val bottom: Int) {+ val width: Int get() = right - left+ val height: Int get() = bottom - top+ val centerX: Float get() = (left + right) / 2f+ val centerY: Float get() = (top + bottom) / 2f++ fun clampWithin(bounds: SensorRect): SensorRect {+ val w = minOf(width, bounds.width).coerceAtLeast(1)+ val h = minOf(height, bounds.height).coerceAtLeast(1)+ val l = left.coerceIn(bounds.left, bounds.right - w)+ val t = top.coerceIn(bounds.top, bounds.bottom - h)+ return SensorRect(l, t, l + w, t + h)+ }++ companion object {+ fun ofSize(width: Int, height: Int): SensorRect = SensorRect(0, 0, width, height)+ }+}++/** One metering region: a sensor-space rectangle plus its HAL weight. */+data class MeteringRegion(val rect: SensorRect, val weight: Int = DEFAULT_WEIGHT) {+ companion object {+ /** `MeteringRectangle.METERING_WEIGHT_MAX`-style centre weight. */+ const val DEFAULT_WEIGHT = 1000+ }+}++object MeteringTransform {++ /** Default metering window edge, as a fraction of the crop-region edge. */+ const val DEFAULT_REGION_FRACTION = 0.12f++ /**+ * Centred crop region for [zoomRatio] over the active array — the+ * `SCALER_CROP_REGION` fallback when `CONTROL_ZOOM_RATIO` is unavailable.+ * A ratio ≤ 1 (or a degenerate array) yields the full array.+ */+ fun cropRegionForZoom(activeArray: SensorRect, zoomRatio: Float): SensorRect {+ if (activeArray.width <= 0 || activeArray.height <= 0) return activeArray+ val ratio = zoomRatio.coerceAtLeast(1f)+ if (ratio <= 1f) return activeArray+ val cropW = (activeArray.width / ratio).roundToInt().coerceIn(1, activeArray.width)+ val cropH = (activeArray.height / ratio).roundToInt().coerceIn(1, activeArray.height)+ val left = activeArray.left + (activeArray.width - cropW) / 2+ val top = activeArray.top + (activeArray.height - cropH) / 2+ return SensorRect(left, top, left + cropW, top + cropH)+ }++ /**+ * Rotates a normalised viewfinder point into sensor orientation.+ * [relativeRotationDegrees] is `(sensorOrientation - displayRotation)`+ * normalised to 0/90/180/270: how far sensor space is rotated clockwise+ * from what the user sees. Front lenses mirror the preview, so the+ * x-axis flips before rotation when [mirrored].+ */+ fun rotateViewfinderPoint(+ x: Float,+ y: Float,+ relativeRotationDegrees: Int,+ mirrored: Boolean,+ ): Pair<Float, Float> {+ val mx = if (mirrored) 1f - x else x+ return when (((relativeRotationDegrees % 360) + 360) % 360) {+ 90 -> (1f - y) to mx+ 180 -> (1f - mx) to (1f - y)+ 270 -> y to (1f - mx)+ else -> mx to y+ }+ }++ /**+ * Maps a normalised viewfinder tap to a sensor-space point inside+ * [cropRegion]. Out-of-range taps are clamped to the crop edges; a+ * degenerate crop yields the active-array centre.+ */+ fun viewfinderToSensorPoint(+ tapX: Float,+ tapY: Float,+ cropRegion: SensorRect,+ sensorOrientationDegrees: Int,+ displayRotationDegrees: Int,+ mirrored: Boolean,+ ): Pair<Float, Float> {+ if (cropRegion.width <= 0 || cropRegion.height <= 0) return 0f to 0f+ val relative = sensorOrientationDegrees - displayRotationDegrees+ val (rx, ry) = rotateViewfinderPoint(+ tapX.coerceIn(0f, 1f), tapY.coerceIn(0f, 1f), relative, mirrored,+ )+ val px = cropRegion.left + rx * cropRegion.width+ val py = cropRegion.top + ry * cropRegion.height+ return px.coerceIn(+ cropRegion.left.toFloat(), (cropRegion.right - 1).toFloat(),+ ) to py.coerceIn(cropRegion.top.toFloat(), (cropRegion.bottom - 1).toFloat())+ }++ /**+ * Full tap → metering region: centres a window of [regionFraction] of the+ * crop edge on the transformed tap point, clamped inside the active array.+ */+ fun meteringRegionForTap(+ tapX: Float,+ tapY: Float,+ activeArray: SensorRect,+ cropRegion: SensorRect,+ sensorOrientationDegrees: Int,+ displayRotationDegrees: Int,+ mirrored: Boolean,+ regionFraction: Float = DEFAULT_REGION_FRACTION,+ weight: Int = MeteringRegion.DEFAULT_WEIGHT,+ ): MeteringRegion {+ val (px, py) = viewfinderToSensorPoint(+ tapX, tapY, cropRegion, sensorOrientationDegrees, displayRotationDegrees, mirrored,+ )+ val fraction = regionFraction.coerceIn(0.01f, 1f)+ val regionW = (cropRegion.width * fraction).roundToInt().coerceAtLeast(1)+ val regionH = (cropRegion.height * fraction).roundToInt().coerceAtLeast(1)+ val rect = SensorRect(+ (px - regionW / 2f).roundToInt(),+ (py - regionH / 2f).roundToInt(),+ (px + regionW / 2f).roundToInt(),+ (py + regionH / 2f).roundToInt(),+ ).clampWithin(activeArray)+ return MeteringRegion(rect, weight)+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.ktnew file mode 100644index 0000000000..14097d6548--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicy.kt@@ -0,0 +1,42 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode++/** Which engine renders the viewfinder preview. */+enum class PreviewEngine { CAMERAX, CAMERA2 }++/**+ * Inputs to the preview-engine selection rule.+ *+ * @property camera2Enabled the per-mode Camera2 preview gate. Default OFF:+ * CameraX remains the live path and the Camera2 engine is never built.+ * @property mode the camera mode the preview is for (PHOTO first).+ */+data class PreviewEngineInput(+ val camera2Enabled: Boolean,+ val mode: CameraMode,+)++/**+ * Explicit selection rule for the two preview engines, mirroring+ * `RecordingPathPolicy` for recording: the Camera2 path is selected only+ * when the gate is explicitly on *and* the mode is one the Camera2 session+ * honestly supports. Phase 2 supports PHOTO only (preview + controls, no+ * still capture yet), so every other mode stays on CameraX even with the+ * gate on.+ */+object PreviewEnginePolicy {++ /** Modes the Camera2 preview engine supports today (PHOTO first). */+ val supportedModes: Set<CameraMode> = setOf(CameraMode.PHOTO)++ fun select(input: PreviewEngineInput): PreviewEngine = when {+ !input.camera2Enabled -> PreviewEngine.CAMERAX+ input.mode !in supportedModes -> PreviewEngine.CAMERAX+ else -> PreviewEngine.CAMERA2+ }++ /** True when [mode] should render through the Camera2 preview engine. */+ fun usesCamera2(enabled: Boolean, mode: CameraMode): Boolean =+ select(PreviewEngineInput(enabled, mode)) == PreviewEngine.CAMERA2+}
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.ktnew file mode 100644index 0000000000..d7c4acdbcd--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -0,0 +1,125 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.util.Size+import kotlin.math.abs++/**+ * Camera2 migration Phase 2: deterministic preview stream selection from the+ * [CharacteristicsFacade] snapshot. The requested preview size is validated+ * against the `StreamConfigurationMap` summary *before* any device is opened —+ * an unsupported size fails fast with a typed reason instead of surfacing as+ * a HAL configure failure after a trial bind.+ *+ * Selection is a pure function of the supported list: same input, same output+ * on every device and in every test. No HAL iteration order leaks in — ties+ * break on width, then height.+ */++/** Plain width/height pair so selection math needs no Android types. */+data class FrameSize(val width: Int, val height: Int) {+ val area: Int get() = width * height+ /** width / height as a float; 0 for a degenerate height. */+ val aspect: Float get() = if (height == 0) 0f else width.toFloat() / height++ fun toSize(): Size = Size(width, height)++ companion object {+ fun from(size: Size): FrameSize = FrameSize(size.width, size.height)+ }+}++/** Why a preview-size request cannot be honoured. */+sealed interface PreviewSizeRejection {+ /** The HAL reported no preview-capable sizes at all. */+ data object NoSupportedSizes : PreviewSizeRejection++ /** [requested] is not in the supported list and no close substitute exists. */+ data class Unsupported(val requested: FrameSize) : PreviewSizeRejection+}++object StreamSelection {++ /** Aspect ratios within this absolute tolerance count as the same shape. */+ const val ASPECT_TOLERANCE = 0.02f++ /**+ * Supported preview sizes for a TextureView surface, in facade order:+ * the explicit `SurfaceTexture` list when the HAL reported one, else the+ * PRIVATE list (what a preview surface consumes), else YUV.+ */+ fun supportedPreviewSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> {+ val config = snapshot.streamConfig+ val sizes = when {+ config.surfaceTextureSizes.isNotEmpty() -> config.surfaceTextureSizes+ config.sizesFor(ImageFormat.PRIVATE).isNotEmpty() -> config.sizesFor(ImageFormat.PRIVATE)+ else -> config.sizesFor(ImageFormat.YUV_420_888)+ }+ return sizes.map { FrameSize.from(it) }.distinct()+ }++ /** True only when [requested] is exactly one of the supported sizes. */+ fun isSupported(requested: FrameSize, supported: List<FrameSize>): Boolean =+ requested in supported++ /**+ * Picks the preview size for [requested]:+ * 1. An exact match wins.+ * 2. Else, among sizes sharing the requested aspect (within+ * [ASPECT_TOLERANCE]), the smallest that still covers the request,+ * or the largest available when none covers it.+ * 3. Else (no same-aspect size), the closest aspect, then closest area.+ *+ * Returns null only when [supported] is empty — the caller must not open+ * the device in that case.+ */+ fun selectPreviewSize(requested: FrameSize, supported: List<FrameSize>): FrameSize? {+ if (supported.isEmpty()) return null+ if (requested in supported) return requested+ val sameAspect = supported.filter { abs(it.aspect - requested.aspect) <= ASPECT_TOLERANCE }+ if (sameAspect.isNotEmpty()) {+ val covering = sameAspect.filter { it.area >= requested.area }+ return (if (covering.isNotEmpty()) {+ covering.minWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ } else {+ sameAspect.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ })+ }+ return supported.minWithOrNull(+ compareBy(+ { abs(it.aspect - requested.aspect) },+ { abs(it.area - requested.area) },+ { it.width },+ { it.height },+ ),+ )+ }++ /**+ * Validates [requested] up front: [Result.success] carries the size to+ * configure (the request itself or its deterministic substitute); failure+ * carries the typed rejection so the session can refuse before opening.+ */+ fun validatePreviewSize(+ requested: FrameSize,+ supported: List<FrameSize>,+ ): Result<FrameSize> {+ if (supported.isEmpty()) {+ return Result.failure(IllegalStateException("no supported preview sizes"))+ }+ val selected = selectPreviewSize(requested, supported)+ ?: return Result.failure(IllegalStateException("no supported preview sizes"))+ return Result.success(selected)+ }++ /** The rejection for [requested], or null when a size can be selected. */+ fun rejectionFor(+ requested: FrameSize,+ supported: List<FrameSize>,+ ): PreviewSizeRejection? = when {+ supported.isEmpty() -> PreviewSizeRejection.NoSupportedSizes+ selectPreviewSize(requested, supported) == null ->+ PreviewSizeRejection.Unsupported(requested)+ else -> null+ }+}
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.ktnew file mode 100644index 0000000000..d80f7677a4--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -0,0 +1,123 @@+package com.vayunmathur.camera.ui++import android.content.Context+import android.hardware.camera2.CameraManager+import android.view.TextureView+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.input.pointer.pointerInput+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.Camera2Session+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 (Phase 2) viewfinder: a TextureView whose surface feeds a+ * [Camera2Session]. Rendered only when the preview-engine gate selects+ * Camera2 (PHOTO + gate on — see `PreviewEnginePolicy`); the CameraX+ * viewfinder path is untouched otherwise.+ *+ * The [modifier] carries the same graphicsLayer RenderEffects / clipping as+ * the CameraX preview, so warmth/bokeh grading composites identically over+ * this TextureView (EMBEDDED-style texture rendering under the overlay tree).+ *+ * Ownership: this composition owns the executor and the session; both are+ * torn down when it leaves composition (mode switch, lens flip, gate off).+ */+@Composable+internal fun Camera2Preview(+ cameraId: String,+ zoomRatio: Float,+ torchOn: Boolean,+ exposureCompEv: Float,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val sessionHolder = remember(cameraId) { Camera2PreviewSession(context, cameraId) }++ DisposableEffect(sessionHolder) {+ onDispose { sessionHolder.close() }+ }+ LaunchedEffect(sessionHolder, zoomRatio) { sessionHolder.session.setZoomRatio(zoomRatio) }+ LaunchedEffect(sessionHolder, torchOn) { sessionHolder.session.setTorch(torchOn) }+ LaunchedEffect(sessionHolder, exposureCompEv) {+ sessionHolder.session.setExposureCompEv(exposureCompEv)+ }++ AndroidView(+ factory = { ctx ->+ TextureView(ctx).also { view -> sessionHolder.bridge.attachTo(view) }+ },+ modifier = modifier.pointerInput(sessionHolder) {+ detectTapGestures { offset ->+ if (size.width > 0 && size.height > 0) {+ sessionHolder.session.tapToFocus(+ tapX = offset.x / size.width,+ tapY = offset.y / size.height,+ )+ }+ }+ },+ )+}++/** Executor + bridge + session for one camera id; built once, closed once. */+private class Camera2PreviewSession(context: Context, private val cameraId: String) {+ val executor = Camera2Executor("Camera2Preview-$cameraId")+ val session: Camera2Session+ 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 = Camera2Session(+ driver = driver,+ executor = executor,+ snapshot = facade.snapshot,+ listener = object : Camera2Session.Listener {+ override fun onError(message: String) {+ Log.status("Camera2Preview", 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 -> {+ // No resize API on the Phase-2 session: reopen at the new+ // size so the stream is re-validated up front.+ 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/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 84e290fd4f..9a3160a1fe 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -112,6 +112,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( } val coordinateTransformer = remember { MutableCoordinateTransformer() } val tapToFocusState = remember { TapToFocusState() }+ val useCamera2Preview = state.useCamera2Preview val previewModifier = previewSize // CameraX mirrors the front-camera preview by default; counter it when the // user turns selfie mirroring off so the preview matches the saved image (#632).@@ -179,7 +180,13 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( ) // Tap-to-focus (gesture, metering, indicator) is owned by // TapToFocus.kt; pinch-to-zoom stays built-in below.- .tapToFocus(+ // Camera2 preview owns its taps (see Camera2Preview); do not attach+ // CameraX tapToFocus there (it self-gates on CameraX FocusMetering).+ .then(+ if (useCamera2Preview) {+ Modifier+ } else {+ Modifier.tapToFocus( state = tapToFocusState, surfaceRequest = surfaceRequest, mirrorPreview = state.mirrorPreview,@@ -187,8 +194,28 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( onFocus = { viewModel.startFocusAndMetering(it) }, onLockFocus = { viewModel.lockFocusAndMetering(it) }, onFallback = { viewModel.fallbackToDefaultMetering() },+ )+ } ) + if (useCamera2Preview) {+ // Camera2 preview behind gate (CameraScreenState.useCamera2Preview, PHOTO only).+ // TextureView-backed, same overlay tree / RenderEffects below.+ // Guard: never compose with empty cameraId — fall back to CameraX black/error branch below.+ val camera2Id = state.selectedLens?.logicalCameraId.orEmpty()+ if (camera2Id.isNotEmpty()) {+ Camera2Preview(+ cameraId = camera2Id,+ zoomRatio = state.zoomRatio,+ torchOn = state.torchEnabled,+ exposureCompEv = state.exposureComp,+ modifier = previewModifier,+ )+ } else {+ Box(modifier = previewModifier.background(Color.Black))+ }+ }+ if (!useCamera2Preview) { surfaceRequest?.let { request -> LaunchedEffect(request) { Log.dev("NightPreview", "CameraXViewfinder COMPOSED with request res=${request.resolution} dynamicRange=${request.dynamicRange} useNightPreview=${state.useNightPreview} sessionKind=${state.sessionKind} zoomRatio=${state.zoomRatio} levels=${state.availableZoomLevels} thread=${Thread.currentThread().name}")@@ -237,7 +264,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( onScreenFlashReady = { screenFlash -> viewModel.setScreenFlash(screenFlash) }, ) }- if (surfaceRequest == null) {+ if (!useCamera2Preview && surfaceRequest == null) { if (state.sessionBindFailed) { // Bind exhausted its retries: a visible, retryable error instead // of parking on a black preview until the next mode/lens change.@@ -255,6 +282,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox( Box(modifier = previewModifier.background(Color.Black)) } }+ } CaptureFlashOverlay(viewModel.shutterFeedback, previewSize.clip(RoundedCornerShape(12.dp))) CameraPreviewOverlays(
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 0a50da923b..c40ad9c097 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -60,6 +60,7 @@ internal fun CameraScreenEffects( val selectedLens = state.selectedLens val sessionKind = state.sessionKind val useNightPreview = state.useNightPreview+ val useCamera2Preview = state.useCamera2Preview // Tracks physical orientation purely to rotate the on-screen control icons. Capture output // rotation is handled by CameraX via SessionConfig.setAutoRotationEnabled(true).@@ -253,7 +254,21 @@ 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, zslKey, bindSettings, state.sessionBindRetry, lifecycleOwner) {+ LaunchedEffect(cameraMode, lensFacing, selectedLens, sessionKind, useNightPreview, useCamera2Preview, 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) {+ lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {+ viewModel.sessionBindFailedMutable.value = false+ viewModel.teardownSession()+ try { awaitCancellation() } finally { viewModel.teardownSession() }+ }+ Log.dev("NightPreview", "CameraScreen repeatOnLifecycle block EXIT – lifecycle dropped below STARTED")+ return@LaunchedEffect+ } Log.dev("NightPreview", "CameraScreen session LaunchedEffect START keys zsl=$zslKey lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview codec=${bindSettings.videoCodec} audioCodec=${bindSettings.audioCodec} audio=${bindSettings.audioInputSource} mirror=${bindSettings.mirrorFront} lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}") lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { // A fresh (re)bind supersedes any earlier exhausted-retry failure.
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 fcfe66f078..ff4bd3b49b 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -96,6 +96,8 @@ import com.vayunmathur.camera.platform.BokehAnalyzer deviceRotationState: MutableIntState, val sessionBindFailed: Boolean = false, val sessionBindRetry: Int = 0,+ /** Camera2 preview gate (default OFF); policy-gated to PHOTO in the getter below. */+ val camera2PreviewEnabled: Boolean = false, ) { var activeSetting by activeSettingState var maskBitmap by maskBitmapState@@ -119,6 +121,16 @@ import com.vayunmathur.camera.platform.BokehAnalyzer val useNightPreview get() = sessionKind == SessionKind.PHOTO && cameraMode == CameraMode.PHOTO && nightModeActive && nightExtAvailable + /**+ * True when the Camera2 preview engine owns the viewfinder (gate on ++ * PHOTO). CameraX is not bound in this state; capture still uses the+ * CameraX still path — Phase 2 is preview + controls only.+ */+ val useCamera2Preview: Boolean+ get() = com.vayunmathur.camera.platform.camera2.PreviewEnginePolicy.usesCamera2(+ camera2PreviewEnabled, cameraMode,+ )+ val previewAspectRatio get() = when { // The still crop only exists on the photo sessions (PHOTO/PORTRAIT ImageCapture). // Video/HFR/pano never crop to it, so letterboxing their preview to it lies about@@ -194,6 +206,7 @@ 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 camera2PreviewEnabled by viewModel.camera2PreviewEnabled.collectAsState() val sessionBindFailed by viewModel.sessionBindFailed.collectAsState() val sessionBindRetry by viewModel.sessionBindRetry.collectAsState() val availableZoomLevels by viewModel.availableZoomLevels.collectAsState()@@ -222,6 +235,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen isoStops, longExposureProgress, longExposureRemaining, lowLightDetected, nightModeActive, extensionStrength, sloMoSupported, highSpeedActive, photoSessionActive, analysisStreamActive, nightExtAvailable, surfaceRequest,+ camera2PreviewEnabled, sessionBindFailed, sessionBindRetry, availableZoomLevels, galleryBitmap, panoSweeping, panoStitching, panoDots, panoCurrentAngle, panoDirection, panoPitch,@@ -287,6 +301,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen deviceRotationState = deviceRotationState, sessionBindFailed = sessionBindFailed, sessionBindRetry = sessionBindRetry,+ camera2PreviewEnabled = camera2PreviewEnabled, ) } }
camera/src/test/java/com/vayunmathur/camera/domain/AnalysisPlaneMathTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisPlaneMathTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisPlaneMathTest.ktnew file mode 100644index 0000000000..c981933351--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisPlaneMathTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.camera.domain++import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class AnalysisPlaneMathTest {++ /** Builds a plane with poisoned (0xEE) padding; pixel (x,y) = (x*7 + y*13) % 251. */+ private fun paddedPlane(w: Int, h: Int, rowStride: Int, pixelStride: Int = 1): PlaneView {+ val bytes = ByteArray(rowStride * h) { 0xEE.toByte() }+ for (y in 0 until h) {+ for (x in 0 until w) {+ bytes[y * rowStride + x * pixelStride] = ((x * 7 + y * 13) % 251).toByte()+ }+ }+ return PlaneView(ByteBuffer.wrap(bytes), rowStride, pixelStride, w, h)+ }++ @Test fun flatPlaneMeanAndGrid() {+ val plane = PlaneView(ByteBuffer.wrap(ByteArray(64 * 48) { 100 }), 64, 1, 64, 48)+ val stats = LumaPlaneMath.stats(plane)!!+ assertEquals(100.0, stats.mean)+ assertEquals(64, stats.gridWidth)+ assertEquals(48, stats.gridHeight)+ assertTrue(stats.grid.all { it == 100f })+ }++ @Test fun paddedStridesAreNotReadAsPixels() {+ val plane = paddedPlane(37, 23, 48)+ var sum = 0L+ var count = 0L+ var n = 0+ while (n < 37 * 23) {+ sum += ((n % 37 * 7 + n / 37 * 13) % 251)+ count+++ n += LumaPlaneMath.LUMA_SAMPLE_STEP+ }+ assertEquals(sum.toDouble() / count, LumaPlaneMath.mean(plane))+ val (grid, gridWidth) = LumaPlaneMath.grid(plane)!!+ assertEquals(37, gridWidth)+ assertEquals(0f, grid[0])+ assertEquals(((36 * 7 + 22 * 13) % 251).toFloat(), grid.last())+ }++ @Test fun pixelStrideIsHonoured() {+ val plane = paddedPlane(16, 16, 64, pixelStride = 2)+ val stats = LumaPlaneMath.stats(plane)!!+ assertEquals(16, stats.gridWidth)+ assertEquals(((15 * 7 + 15 * 13) % 251).toFloat(), stats.grid.last())+ }++ @Test fun gridDownsamplesLargePlanes() {+ val plane = paddedPlane(640, 480, 640)+ val (grid, gridWidth) = LumaPlaneMath.grid(plane)!!+ // stride 6 x 5 -> 107 x 96 samples, both sides capped at ~96+.+ assertEquals((640 + 5) / 6, gridWidth)+ assertEquals(gridWidth * 96, grid.size)+ }++ @Test fun unreadablePlanesReturnNull() {+ assertNull(LumaPlaneMath.stats(PlaneView(ByteBuffer.wrap(ByteArray(4)), 0, 1, 64, 48)))+ assertNull(LumaPlaneMath.stats(PlaneView(ByteBuffer.wrap(ByteArray(4)), 64, 1, 0, 48)))+ assertNull(LumaPlaneMath.grid(ByteBuffer.wrap(ByteArray(10)), 64, 1, 64, 48))+ }++ @Test fun bufferPositionIsUntouched() {+ val buffer = ByteBuffer.wrap(ByteArray(64 * 48) { 7 })+ buffer.position(11)+ LumaPlaneMath.stats(PlaneView(buffer, 64, 1, 64, 48))+ assertEquals(11, buffer.position())+ }+}
camera/src/test/java/com/vayunmathur/camera/domain/AnalysisSourcePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisSourcePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisSourcePolicyTest.ktnew file mode 100644index 0000000000..096bff1445--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/AnalysisSourcePolicyTest.kt@@ -0,0 +1,45 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse++class AnalysisSourcePolicyTest {++ private fun input(+ enabled: Boolean = true,+ qr: Boolean = false,+ bitmap: Boolean = false,+ cheapOnly: Boolean = true,+ ) = AnalysisSourceInput(+ camera2Enabled = enabled, needsQr = qr, needsBitmapFrame = bitmap,+ cheapPlaneConsumersOnly = cheapOnly,+ )++ @Test fun defaultFlagIsCameraX() {+ assertFalse(AnalysisSourcePolicy.CAMERA2_ENABLED)+ val defaulted = AnalysisSourceInput(needsQr = false, needsBitmapFrame = false, cheapPlaneConsumersOnly = true)+ assertEquals(AnalysisSource.CAMERAX, AnalysisSourcePolicy.select(defaulted))+ }++ @Test fun cheapPlaneSessionMayUseImageReaderWhenEnabled() {+ assertEquals(AnalysisSource.CAMERA2_IMAGE_READER, AnalysisSourcePolicy.select(input()))+ }++ @Test fun qrStaysOnCameraX() {+ assertEquals(AnalysisSource.CAMERAX, AnalysisSourcePolicy.select(input(qr = true)))+ }++ @Test fun bitmapConsumersStayOnCameraX() {+ // Bokeh/Pano/Motion-Photo: segmenters and PanoramaEngine take Bitmaps.+ assertEquals(AnalysisSource.CAMERAX, AnalysisSourcePolicy.select(input(bitmap = true)))+ }++ @Test fun mixedConsumersStayOnCameraX() {+ assertEquals(AnalysisSource.CAMERAX, AnalysisSourcePolicy.select(input(cheapOnly = false)))+ }++ @Test fun disabledFlagAlwaysCameraX() {+ assertEquals(AnalysisSource.CAMERAX, AnalysisSourcePolicy.select(input(enabled = false)))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/LumaStatsNativeTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/LumaStatsNativeTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/LumaStatsNativeTest.ktnew file mode 100644index 0000000000..06f1523d50--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/LumaStatsNativeTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.domain.LumaPlaneMath+import com.vayunmathur.camera.domain.PlaneView+import java.nio.ByteBuffer+import kotlin.math.abs+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Kotlin vs native luma-stats parity on synthetic Y planes (the+ * StillEncoderNativeTest pattern: real JNI bridge against the host .so,+ * skipped when the host library is not built in this environment).+ */+class LumaStatsNativeTest {++ /** Direct plane, padding poisoned with 0xEE; pixel (x,y) = (x*7 + y*13) % 251. */+ private fun directPlane(w: Int, h: Int, rowStride: Int, pixelStride: Int = 1): PlaneView {+ val buffer = ByteBuffer.allocateDirect(rowStride * h)+ for (i in 0 until rowStride * h) buffer.put(i, 0xEE.toByte())+ for (y in 0 until h) {+ for (x in 0 until w) {+ buffer.put(y * rowStride + x * pixelStride, ((x * 7 + y * 13) % 251).toByte())+ }+ }+ return PlaneView(buffer, rowStride, pixelStride, w, h)+ }++ private fun assertParity(plane: PlaneView) {+ val kotlin = LumaPlaneMath.stats(plane)+ assertNotNull(kotlin)+ // The unified entry point must agree whichever half computed it.+ val unified = StitchNative.lumaStats(plane)+ assertNotNull(unified)+ assertEquals(kotlin.gridWidth, unified.gridWidth)+ assertEquals(kotlin.gridHeight, unified.gridHeight)+ assertTrue(kotlin.grid.contentEquals(unified.grid), "grid values differ")+ assertTrue(abs(kotlin.mean - unified.mean) < 0.01, "mean ${kotlin.mean} vs ${unified.mean}")++ if (!StitchNative.isAvailable || !plane.buffer.isDirect) return+ val native = StitchNative.lumaStatsFromYPlane(+ plane.buffer, plane.width, plane.height, plane.rowStride, plane.pixelStride,+ )+ assertNotNull(native, "native returned null for a direct plane")+ val decoded = decodeLumaStats(native)+ assertNotNull(decoded)+ assertEquals(kotlin.gridWidth, decoded.gridWidth)+ assertEquals(kotlin.gridHeight, decoded.gridHeight)+ assertTrue(kotlin.grid.contentEquals(decoded.grid), "native grid differs from Kotlin")+ // Mean travels as float32 in the native encoding.+ assertTrue(abs(kotlin.mean - decoded.mean) < 0.01, "native mean ${decoded.mean} vs ${kotlin.mean}")+ }++ @Test fun parityOnPaddedDirectPlane() {+ assertParity(directPlane(37, 23, 48))+ }++ @Test fun parityOnTightlyPackedPlane() {+ assertParity(directPlane(64, 48, 64))+ }++ @Test fun parityWithPixelStride() {+ assertParity(directPlane(16, 16, 64, pixelStride = 2))+ }++ @Test fun parityOnGridDownsampledPlane() {+ assertParity(directPlane(640, 480, 640))+ }++ @Test fun heapBufferUsesKotlinFallbackWithSameResult() {+ val bytes = ByteArray(64 * 48) { (it % 251).toByte() }+ val heap = PlaneView(ByteBuffer.wrap(bytes), 64, 1, 64, 48)+ val viaUnified = StitchNative.lumaStats(heap)+ val viaKotlin = LumaPlaneMath.stats(heap)+ assertNotNull(viaUnified)+ assertEquals(viaKotlin, viaUnified)+ if (StitchNative.isAvailable) {+ // A heap buffer has no direct address: native must refuse, not crash.+ assertNull(+ StitchNative.lumaStatsFromYPlane(heap.buffer, 64, 48, 64, 1),+ )+ }+ }++ @Test fun decodeRejectsMalformedEncodings() {+ assertNull(decodeLumaStats(null))+ assertNull(decodeLumaStats(floatArrayOf(1f, 2f)))+ assertNull(decodeLumaStats(floatArrayOf(1f, 0f, 2f)))+ assertNull(decodeLumaStats(floatArrayOf(1f, 2f, 2f, 9f)))+ assertNotNull(decodeLumaStats(floatArrayOf(5f, 2f, 2f, 1f, 2f, 3f, 4f)))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/PlaneConsumersTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/PlaneConsumersTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/PlaneConsumersTest.ktnew file mode 100644index 0000000000..746daa34c2--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/PlaneConsumersTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.camera.platform++import com.vayunmathur.camera.domain.FrameDiffSample+import com.vayunmathur.camera.domain.PlaneView+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowSystemClock++/** Plane entry points of the two cheap consumers, fed Camera2-style views. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PlaneConsumersTest {++ private fun plane(w: Int, h: Int, fill: (Int, Int) -> Int): PlaneView {+ val bytes = ByteArray(w * h)+ for (y in 0 until h) for (x in 0 until w) bytes[y * w + x] = fill(x, y).toByte()+ return PlaneView(ByteBuffer.wrap(bytes), w, 1, w, h)+ }++ @Test fun photoAnalyzerPlaneEntryReportsStridedMean() {+ var luminance: Float? = null+ val analyzer = PhotoAnalyzer(onLuminance = { luminance = it }, onQrDetected = {})+ analyzer.onYPlane(plane(32, 32) { _, _ -> 120 })+ assertEquals(120f, luminance)++ analyzer.onYPlane(plane(32, 32) { x, _ -> x * 4 })+ // Raster step-16 samples of a horizontal ramp: not the naive row mean.+ assertTrue(luminance != null && luminance!! in 0f..255f)+ }++ @Test fun videoMotionPlaneEntryDiffsSuccessiveGrids() {+ val samples = mutableListOf<FrameDiffSample>()+ val analyzer = VideoMotionAnalyzer { samples += it }++ ShadowSystemClock.advanceBy(java.time.Duration.ofMillis(1_000))+ analyzer.onYPlane(plane(32, 24) { _, _ -> 50 }) // first grid: no diff yet+ assertTrue(samples.isEmpty())++ ShadowSystemClock.advanceBy(java.time.Duration.ofMillis(VIDEO_MOTION_SAMPLE_INTERVAL_MS + 50))+ analyzer.onYPlane(plane(32, 24) { _, _ -> 90 })+ assertEquals(1, samples.size)+ assertEquals(40.0, samples[0].meanAbsDiff)+ assertEquals(0.0, samples[0].meanGradient)+ }++ @Test fun videoMotionPlaneEntryHonoursCadence() {+ val samples = mutableListOf<FrameDiffSample>()+ val analyzer = VideoMotionAnalyzer { samples += it }+ ShadowSystemClock.advanceBy(java.time.Duration.ofMillis(1_000))+ analyzer.onYPlane(plane(32, 24) { _, _ -> 50 })+ // No clock advance: the second frame is inside the sample interval.+ analyzer.onYPlane(plane(32, 24) { _, _ -> 90 })+ assertTrue(samples.isEmpty())+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.ktnew file mode 100644index 0000000000..dd482459f1--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/AnalysisImageSourceTest.kt@@ -0,0 +1,110 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.domain.PlaneView+import java.nio.ByteBuffer+import java.util.concurrent.CountDownLatch+import java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AnalysisImageSourceTest {++ private class FakeFrame : AnalysisFrame {+ val closed = AtomicInteger(0)+ override val width = 4+ override val height = 3+ override val timestampNs = 42L+ override val yPlane = PlaneView(ByteBuffer.wrap(ByteArray(12) { 9 }), 4, 1, 4, 3)+ override val planes = listOf(yPlane)+ override fun close() {+ closed.incrementAndGet()+ }+ }++ @Test fun gateAdmitsOneInFlightAndCountsDrops() {+ val gate = FrameDropGate()+ assertTrue(gate.tryBeginDelivery())+ assertFalse(gate.tryBeginDelivery())+ assertFalse(gate.tryBeginDelivery())+ assertEquals(2, gate.droppedFrames)+ assertEquals(1, gate.deliveredFrames)+ gate.endDelivery()+ assertTrue(gate.tryBeginDelivery())+ }++ @Test fun dispatchDeliversAndClosesFrame() {+ val seen = AtomicInteger(0)+ val dispatcher = AnalysisFrameDispatcher(+ consumer = { frame ->+ assertEquals(42L, frame.timestampNs)+ seen.incrementAndGet()+ },+ executor = { it.run() },+ )+ val frame = FakeFrame()+ assertTrue(dispatcher.dispatch(frame))+ assertEquals(1, seen.get())+ assertEquals(1, frame.closed.get())+ assertFalse(dispatcher.gate.isBusy)+ }++ @Test fun busyConsumerDropsNewFramesAndClosesThem() {+ val executor = Executors.newSingleThreadExecutor()+ try {+ val entered = CountDownLatch(1)+ val release = CountDownLatch(1)+ val dispatcher = AnalysisFrameDispatcher(+ consumer = {+ entered.countDown()+ release.await(5, TimeUnit.SECONDS)+ },+ executor = executor,+ )+ val first = FakeFrame()+ assertTrue(dispatcher.dispatch(first))+ assertTrue(entered.await(5, TimeUnit.SECONDS))++ // Consumer busy on the executor: both of these must drop.+ val droppedA = FakeFrame()+ val droppedB = FakeFrame()+ assertFalse(dispatcher.dispatch(droppedA))+ assertFalse(dispatcher.dispatch(droppedB))+ assertEquals(2, dispatcher.gate.droppedFrames)+ assertEquals(1, droppedA.closed.get())+ assertEquals(1, droppedB.closed.get())++ release.countDown()+ executor.submit { }.get(5, TimeUnit.SECONDS)+ assertEquals(1, first.closed.get())+ assertFalse(dispatcher.gate.isBusy)++ val after = FakeFrame()+ assertTrue(dispatcher.dispatch(after))+ executor.submit { }.get(5, TimeUnit.SECONDS)+ assertEquals(1, after.closed.get())+ } finally {+ executor.shutdownNow()+ }+ }++ @Test fun throwingConsumerStillClosesAndFreesGate() {+ val dispatcher = AnalysisFrameDispatcher(+ consumer = { throw IllegalStateException("consumer gone") },+ executor = { it.run() },+ )+ val frame = FakeFrame()+ assertTrue(dispatcher.dispatch(frame))+ assertEquals(1, frame.closed.get())+ assertFalse(dispatcher.gate.isBusy)+ assertTrue(dispatcher.dispatch(FakeFrame()))+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ControlsTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ControlsTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ControlsTest.ktnew file mode 100644index 0000000000..0026cdaf09--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2ControlsTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata+import android.util.Range+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2ControlsTest {++ /** Snapshot with zoom-ratio support, flash, ±4 EV in 1/6 steps, regions. */+ private fun snapshot(+ zoomRatioRange: Range<Float>? = Range(1f, 10f),+ hasFlashUnit: Boolean = true,+ maxAfRegions: Int = 1,+ maxAeRegions: Int = 1,+ supportsZoomRatioKey: Boolean = true,+ ): LensCharacteristicsSnapshot {+ val facade = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ zoomRatioRange = zoomRatioRange,+ hasFlashUnit = hasFlashUnit,+ supportsZoomRatioKey = supportsZoomRatioKey,+ exposureCompensationEvRange = Range(-4f, 4f),+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = maxAfRegions,+ maxAeRegions = maxAeRegions,+ )+ return facade.snapshot+ }++ @Test fun zoomRatioPathWhenSupported() {+ val params = Camera2Controls.resolve(+ Camera2ControlState(zoomRatio = 3f), snapshot(),+ )+ assertEquals(3f, params.zoomRatio)+ assertNull(params.cropRegion)+ }++ @Test fun zoomClampsToLensRange() {+ val params = Camera2Controls.resolve(+ Camera2ControlState(zoomRatio = 99f), snapshot(),+ )+ assertEquals(10f, params.zoomRatio)+ val low = Camera2Controls.resolve(+ Camera2ControlState(zoomRatio = 0.1f), snapshot(),+ )+ assertEquals(1f, low.zoomRatio)+ }++ @Test fun cropRegionFallbackWhenZoomRatioUnsupported() {+ // Range known (from SCALER_AVAILABLE_MAX_DIGITAL_ZOOM) but the+ // CONTROL_ZOOM_RATIO key is not honoured: crop region carries zoom.+ val params = Camera2Controls.resolve(+ Camera2ControlState(zoomRatio = 2f),+ snapshot(zoomRatioRange = Range(1f, 8f), supportsZoomRatioKey = false),+ )+ assertNull(params.zoomRatio)+ assertEquals(SensorRect(1000, 750, 3000, 2250), params.cropRegion)+ }++ @Test fun torchRequiresFlashUnit() {+ val on = Camera2Controls.resolve(+ Camera2ControlState(torchOn = true), snapshot(),+ )+ assertEquals(CameraMetadata.FLASH_MODE_TORCH, on.flashMode)+ val noUnit = Camera2Controls.resolve(+ Camera2ControlState(torchOn = true), snapshot(hasFlashUnit = false),+ )+ assertEquals(CameraMetadata.FLASH_MODE_OFF, noUnit.flashMode)+ val off = Camera2Controls.resolve(Camera2ControlState.DEFAULT, snapshot())+ assertEquals(CameraMetadata.FLASH_MODE_OFF, off.flashMode)+ }++ @Test fun evConvertsToStepsAndClamps() {+ // 1/6 EV steps: +1 EV = 6 steps, -2 EV = -12 steps.+ assertEquals(6, Camera2Controls.evToSteps(1f, snapshot()))+ assertEquals(-12, Camera2Controls.evToSteps(-2f, snapshot()))+ assertEquals(0, Camera2Controls.evToSteps(0f, snapshot()))+ // Clamped to the ±4 EV range.+ assertEquals(24, Camera2Controls.evToSteps(9f, snapshot()))+ assertEquals(-24, Camera2Controls.evToSteps(-9f, snapshot()))+ // Resolved params carry the same conversion.+ val params = Camera2Controls.resolve(+ Camera2ControlState(exposureCompEv = 0.5f), snapshot(),+ )+ assertEquals(3, params.aeExposureCompensationSteps)+ }++ @Test fun meteringRegionsGatedOnHalRegionCounts() {+ val region = MeteringRegion(SensorRect(100, 100, 300, 300))+ val withRegions = Camera2Controls.resolve(+ Camera2ControlState(afRegion = region, aeRegion = region), snapshot(),+ )+ assertEquals(listOf(region), withRegions.afRegions)+ assertEquals(listOf(region), withRegions.aeRegions)+ assertTrue(withRegions.meteringActive)++ val noRegions = Camera2Controls.resolve(+ Camera2ControlState(afRegion = region, aeRegion = region),+ snapshot(maxAfRegions = 0, maxAeRegions = 0),+ )+ assertTrue(noRegions.afRegions.isEmpty())+ assertTrue(noRegions.aeRegions.isEmpty())++ val defaults = Camera2Controls.resolve(Camera2ControlState.DEFAULT, snapshot())+ assertTrue(defaults.afRegions.isEmpty())+ assertTrue(!defaults.meteringActive)+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.ktnew file mode 100644index 0000000000..a3f476ab1f--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/Camera2SessionTest.kt@@ -0,0 +1,268 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraMetadata+import android.util.Range+import android.util.Size+import android.view.Surface+import 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++/**+ * Session-logic tests over a fake driver: Robolectric's Camera2 shadows+ * cannot drive a real session, so the open/configure/stream sequence, the+ * generation-token drop of stale callbacks, and up-front stream validation+ * are verified here against recorded fake calls.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class Camera2SessionTest {++ private class FakeSessionHandle : CaptureSessionHandle {+ val repeating = mutableListOf<ResolvedRequestParams>()+ var closed = false+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {+ repeating += params+ }+ override fun close() { closed = true }+ }++ private class FakeDeviceHandle(+ override val cameraId: String = "0",+ private val sessionHandle: FakeSessionHandle = FakeSessionHandle(),+ private val failConfigure: Boolean = false,+ ) : DeviceHandle {+ var sessionCallback: CaptureSessionCallback? = null+ var closed = false+ val sessionHandleRef: FakeSessionHandle get() = sessionHandle+ override fun createCaptureSession(+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ sessionCallback = callback+ if (failConfigure) callback.onConfigureFailed()+ else callback.onConfigured(sessionHandle)+ }+ override fun close() { closed = true }+ }++ private class FakeDriver(+ val device: FakeDeviceHandle = FakeDeviceHandle(),+ private val failConfigure: Boolean = false,+ ) : Camera2Driver {+ var openedCameraId: String? = null+ var deviceCallback: DeviceCallback? = null+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ openedCameraId = cameraId+ deviceCallback = callback+ callback.onOpened(+ if (failConfigure) FakeDeviceHandle(cameraId, failConfigure = true) else device,+ )+ }+ }++ private fun snapshot(+ previewSizes: List<Size> = listOf(Size(1920, 1080), Size(1280, 720)),+ zoomRatioRange: Range<Float>? = Range(1f, 10f),+ ): LensCharacteristicsSnapshot = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ zoomRatioRange = zoomRatioRange,+ hasFlashUnit = true,+ exposureCompensationEvRange = Range(-4f, 4f),+ sizesByFormat = mapOf(ImageFormat.PRIVATE to previewSizes),+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = 1,+ maxAeRegions = 1,+ ).snapshot++ private class RecordingListener : Camera2Session.Listener {+ val states = mutableListOf<SessionState>()+ val errors = mutableListOf<String>()+ val streamingSizes = mutableListOf<FrameSize>()+ override fun onStateChanged(state: SessionState) { states += state }+ override fun onError(message: String) { errors += message }+ override fun onStreaming(previewSize: FrameSize) { streamingSizes += previewSize }+ }++ /** Runs [block] after posting a barrier behind the session's queued work. */+ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+ }++ private fun newSession(+ driver: Camera2Driver,+ executor: Camera2Executor,+ listener: RecordingListener = RecordingListener(),+ snap: LensCharacteristicsSnapshot = snapshot(),+ ): Camera2Session = Camera2Session(driver, executor, snap, listener = listener)++ @Test fun openConfigureStreamSequence() {+ val executor = Camera2Executor("Camera2SessionTest-seq")+ try {+ val driver = FakeDriver()+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ val surface = mock(Surface::class.java)++ session.open("0", surface, FrameSize(1280, 720))+ executor.drain()++ assertEquals("0", driver.openedCameraId)+ assertEquals(SessionState.STREAMING, session.state)+ assertEquals(listOf(FrameSize(1280, 720)), listener.streamingSizes)+ // Initial repeating request carries the default controls.+ val handle = driver.device.sessionHandleRef+ assertEquals(1, handle.repeating.size)+ val params = handle.repeating.single()+ assertEquals(1f, params.zoomRatio)+ assertEquals(CameraMetadata.FLASH_MODE_OFF, params.flashMode)+ assertEquals(0, params.aeExposureCompensationSteps)++ // Control changes re-issue the repeating request resolved.+ session.setZoomRatio(2f)+ session.setTorch(true)+ executor.drain()+ assertTrue(handle.repeating.size >= 3)+ val zoomed = handle.repeating[1]+ assertEquals(2f, zoomed.zoomRatio)+ val torched = handle.repeating.last()+ assertEquals(CameraMetadata.FLASH_MODE_TORCH, torched.flashMode)++ // Tap metering resolves to regions in the last repeating request.+ session.tapToFocus(0.5f, 0.5f)+ executor.drain()+ val metered = handle.repeating.last()+ assertTrue(metered.meteringActive)+ assertEquals(1, metered.afRegions.size)+ assertEquals(1, metered.aeRegions.size)++ session.close()+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)+ assertTrue(handle.closed)+ assertTrue(driver.device.closed)+ } finally {+ executor.shutdown()+ }+ }++ @Test fun unsupportedStreamFailsBeforeOpeningDevice() {+ val executor = Camera2Executor("Camera2SessionTest-nostream")+ try {+ val driver = FakeDriver()+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener, snapshot(previewSizes = emptyList()))+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()++ // Validation happens up front: the HAL was never opened.+ assertEquals(null, driver.openedCameraId)+ assertEquals(SessionState.CLOSED, session.state)+ assertEquals(1, listener.errors.size)+ assertTrue(listener.errors.single().contains("no supported preview sizes"))+ } finally {+ executor.shutdown()+ }+ }++ @Test fun unlistedSizeSubstitutesDeterministically() {+ val executor = Camera2Executor("Camera2SessionTest-substitute")+ try {+ val driver = FakeDriver()+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1600, 900))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ assertEquals(listOf(FrameSize(1920, 1080)), listener.streamingSizes)+ assertEquals(FrameSize(1920, 1080), session.currentPreviewSize())+ } finally {+ executor.shutdown()+ }+ }++ @Test fun configureFailureFallsBackToOpenWithError() {+ val executor = Camera2Executor("Camera2SessionTest-cfgfail")+ try {+ val driver = FakeDriver(failConfigure = true)+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()++ assertEquals(SessionState.OPEN, session.state)+ assertTrue(listener.errors.any { it.contains("configure failed") })+ assertTrue(listener.streamingSizes.isEmpty())+ } finally {+ executor.shutdown()+ }+ }++ @Test fun staleGenerationCallbacksAreDropped() {+ val executor = Camera2Executor("Camera2SessionTest-stale")+ try {+ // Driver that captures the callback without firing it, so the+ // test can deliver the open completion after teardown began.+ var pendingCallback: DeviceCallback? = null+ val driver = object : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) {+ pendingCallback = callback+ }+ }+ val listener = RecordingListener()+ val session = newSession(driver, executor, listener)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.OPENING, session.state)++ session.close()+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)++ // The stale onOpened arrives late: its device must be closed and+ // the machine must stay CLOSED (no resurrection).+ val lateDevice = FakeDeviceHandle()+ pendingCallback!!.onOpened(lateDevice)+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)+ assertTrue(lateDevice.closed, "stale device handle must be closed")+ assertFalse(lateDevice.sessionHandleRef.repeating.isNotEmpty())+ } finally {+ executor.shutdown()+ }+ }++ @Test fun closeIsIdempotent() {+ val executor = Camera2Executor("Camera2SessionTest-close")+ try {+ val driver = FakeDriver()+ val session = newSession(driver, executor)+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ session.close()+ session.close()+ executor.drain()+ assertEquals(SessionState.CLOSED, session.state)+ // Reopening after close stays closed (terminal ownership).+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ // A closed session may be re-opened only from CLOSED — which is+ // exactly its state — so a fresh open is legal and streams again.+ assertEquals(SessionState.STREAMING, session.state)+ } finally {+ executor.shutdown()+ }+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/MeteringTransformTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/MeteringTransformTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/MeteringTransformTest.ktnew file mode 100644index 0000000000..e356fcaff9--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/MeteringTransformTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.camera.platform.camera2++import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Test++class MeteringTransformTest {++ private val active = SensorRect(0, 0, 4000, 3000)++ @Test fun cropRegionForZoomCentersAndScales() {+ // 2x zoom: halved edges, centred in the active array.+ assertEquals(SensorRect(1000, 750, 3000, 2250),+ MeteringTransform.cropRegionForZoom(active, 2f))+ // 1x and below: the full array.+ assertEquals(active, MeteringTransform.cropRegionForZoom(active, 1f))+ assertEquals(active, MeteringTransform.cropRegionForZoom(active, 0.5f))+ // 4x zoom.+ assertEquals(SensorRect(1500, 1125, 2500, 1875),+ MeteringTransform.cropRegionForZoom(active, 4f))+ }++ @Test fun rotateViewfinderPointHandlesQuarterTurns() {+ // No rotation: identity (unmirrored).+ assertEquals(0.25f to 0.75f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 0, mirrored = false))+ // 180: both axes flip.+ assertEquals(0.75f to 0.25f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 180, mirrored = false))+ // 90 clockwise: (x,y) -> (1-y, x).+ assertEquals(0.25f to 0.25f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 90, mirrored = false))+ // 270 clockwise: (x,y) -> (y, 1-x).+ assertEquals(0.75f to 0.75f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 270, mirrored = false))+ // Non-quarter / negative inputs normalise instead of throwing.+ assertEquals(0.75f to 0.25f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, -180, mirrored = false))+ }++ @Test fun mirroredFrontFlipsXBeforeRotation() {+ // Mirror only: x flips.+ assertEquals(0.75f to 0.75f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 0, mirrored = true))+ // Mirror + 180 ends up as a y-flip only.+ assertEquals(0.25f to 0.25f,+ MeteringTransform.rotateViewfinderPoint(0.25f, 0.75f, 180, mirrored = true))+ }++ @Test fun centreTapMapsToCropCentreAtAnyRotation() {+ val crop = MeteringTransform.cropRegionForZoom(active, 2f)+ for (rotation in listOf(0, 90, 180, 270)) {+ val (x, y) = MeteringTransform.viewfinderToSensorPoint(+ 0.5f, 0.5f, crop,+ sensorOrientationDegrees = rotation, displayRotationDegrees = 0,+ mirrored = false,+ )+ assertEquals(crop.centerX, x, 0.6f, "rotation $rotation x")+ assertEquals(crop.centerY, y, 0.6f, "rotation $rotation y")+ }+ }++ @Test fun cornerTapsLandOnCropCorners() {+ val crop = MeteringTransform.cropRegionForZoom(active, 2f)+ // Back lens, sensor 90 / display 0: viewfinder top-left is the crop's+ // (right-1, top) corner in sensor space.+ val (x, y) = MeteringTransform.viewfinderToSensorPoint(+ 0f, 0f, crop,+ sensorOrientationDegrees = 90, displayRotationDegrees = 0, mirrored = false,+ )+ assertEquals((crop.right - 1).toFloat(), x, 0.6f)+ assertEquals(crop.top.toFloat(), y, 0.6f)+ }++ @Test fun meteringRegionStaysInsideActiveArrayAtEdges() {+ val full = active+ for ((tx, ty) in listOf(0f to 0f, 1f to 0f, 0f to 1f, 1f to 1f, 0.5f to 0f)) {+ val region = MeteringTransform.meteringRegionForTap(+ tx, ty, active, full,+ sensorOrientationDegrees = 90, displayRotationDegrees = 0, mirrored = false,+ )+ assertTrue(region.rect.left >= active.left, "left for $tx,$ty: ${region.rect}")+ assertTrue(region.rect.top >= active.top, "top for $tx,$ty: ${region.rect}")+ assertTrue(region.rect.right <= active.right, "right for $tx,$ty: ${region.rect}")+ assertTrue(region.rect.bottom <= active.bottom, "bottom for $tx,$ty: ${region.rect}")+ assertTrue(region.rect.width > 0 && region.rect.height > 0)+ assertEquals(MeteringRegion.DEFAULT_WEIGHT, region.weight)+ }+ // Centre tap: region centres on the (rotated) centre — same centre.+ val centre = MeteringTransform.meteringRegionForTap(+ 0.5f, 0.5f, active, full,+ sensorOrientationDegrees = 0, displayRotationDegrees = 0, mirrored = false,+ )+ assertEquals(active.centerX, centre.rect.centerX, 1.5f)+ assertEquals(active.centerY, centre.rect.centerY, 1.5f)+ }++ @Test fun zoomedTapMapsIntoCropNotFullArray() {+ val crop = MeteringTransform.cropRegionForZoom(active, 2f)+ // A corner tap under 2x zoom centres on the crop corner (the region+ // may extend past the crop into the array — it is clamped to the+ // array, not the crop), never near the array's opposite corner.+ val corner = MeteringTransform.meteringRegionForTap(+ 0f, 0f, active, crop,+ sensorOrientationDegrees = 0, displayRotationDegrees = 0, mirrored = false,+ )+ assertTrue(corner.rect.left >= active.left)+ assertEquals(crop.left.toFloat(), corner.rect.centerX, crop.width * 0.13f)+ assertEquals(crop.top.toFloat(), corner.rect.centerY, crop.height * 0.13f)+ assertTrue(corner.rect.centerX < active.centerX)+ }++ @Test fun displayRotationCancelsSensorOrientation() {+ // Sensor 90 with the display also rotated 90: relative rotation 0,+ // so the tap maps like an unrotated sensor.+ val (x, y) = MeteringTransform.viewfinderToSensorPoint(+ 0.25f, 0.5f, active,+ sensorOrientationDegrees = 90, displayRotationDegrees = 90, mirrored = false,+ )+ assertEquals(1000f, x, 0.6f)+ assertEquals(1500f, y, 0.6f)+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.ktnew file mode 100644index 0000000000..7e1ec5701c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/PreviewEnginePolicyTest.kt@@ -0,0 +1,40 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.Test++class PreviewEnginePolicyTest {++ @Test fun gateOffAlwaysCameraX() {+ for (mode in CameraMode.entries) {+ assertEquals(+ PreviewEngine.CAMERAX,+ PreviewEnginePolicy.select(PreviewEngineInput(false, mode)),+ "gate off must stay on CameraX for $mode",+ )+ }+ }++ @Test fun gateOnSelectsCamera2ForPhotoOnly() {+ assertEquals(+ PreviewEngine.CAMERA2,+ PreviewEnginePolicy.select(PreviewEngineInput(true, CameraMode.PHOTO)),+ )+ assertTrue(PreviewEnginePolicy.usesCamera2(true, CameraMode.PHOTO))+ for (mode in CameraMode.entries - CameraMode.PHOTO) {+ assertEquals(+ PreviewEngine.CAMERAX,+ PreviewEnginePolicy.select(PreviewEngineInput(true, mode)),+ "Phase 2 supports PHOTO only; $mode must stay on CameraX",+ )+ assertFalse(PreviewEnginePolicy.usesCamera2(true, mode))+ }+ }++ @Test fun supportedModesIsPhotoOnlyInPhase2() {+ assertEquals(setOf(CameraMode.PHOTO), PreviewEnginePolicy.supportedModes)+ }+}
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.ktnew file mode 100644index 0000000000..21ab74c90c--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/StreamSelectionTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.util.Size+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class StreamSelectionTest {++ private val supported = listOf(+ FrameSize(1920, 1080),+ FrameSize(1440, 1080),+ FrameSize(1280, 720),+ FrameSize(640, 480),+ )++ @Test fun exactMatchWins() {+ assertEquals(FrameSize(1280, 720),+ StreamSelection.selectPreviewSize(FrameSize(1280, 720), supported))+ assertTrue(StreamSelection.isSupported(FrameSize(1280, 720), supported))+ assertFalse(StreamSelection.isSupported(FrameSize(1280, 721), supported))+ }++ @Test fun sameAspectPicksSmallestCoveringThenLargest() {+ // 1600x900 is 16:9 like 1920x1080 and 1280x720: smallest covering is 1920x1080.+ assertEquals(FrameSize(1920, 1080),+ StreamSelection.selectPreviewSize(FrameSize(1600, 900), supported))+ // 2560x1440 (16:9) is covered by nothing: largest 16:9 wins.+ assertEquals(FrameSize(1920, 1080),+ StreamSelection.selectPreviewSize(FrameSize(2560, 1440), supported))+ // 960x720 is 4:3 like 1440x1080 and 640x480: smallest covering is 1440x1080.+ assertEquals(FrameSize(1440, 1080),+ StreamSelection.selectPreviewSize(FrameSize(960, 720), supported))+ }++ @Test fun noSameAspectFallsBackToClosestShapeDeterministically() {+ // Square request: 1440x1080 and 640x480 are both 4:3 (aspect 1.333,+ // distance 0.333); 1280x720 is 16:9 (distance 0.778) — a 4:3 size wins,+ // and between the two the closer area (1440x1080) wins.+ assertEquals(FrameSize(1440, 1080),+ StreamSelection.selectPreviewSize(FrameSize(1000, 1000), supported))+ // Selection is order-independent.+ assertEquals(+ StreamSelection.selectPreviewSize(FrameSize(1000, 1000), supported),+ StreamSelection.selectPreviewSize(FrameSize(1000, 1000), supported.reversed()),+ )+ }++ @Test fun emptySupportedSelectsNothing() {+ assertNull(StreamSelection.selectPreviewSize(FrameSize(1280, 720), emptyList()))+ assertEquals(PreviewSizeRejection.NoSupportedSizes,+ StreamSelection.rejectionFor(FrameSize(1280, 720), emptyList()))+ assertTrue(StreamSelection.validatePreviewSize(FrameSize(1280, 720), emptyList()).isFailure)+ }++ @Test fun validateReturnsSelectedSize() {+ val result = StreamSelection.validatePreviewSize(FrameSize(1600, 900), supported)+ assertTrue(result.isSuccess)+ assertEquals(FrameSize(1920, 1080), result.getOrThrow())+ assertNull(StreamSelection.rejectionFor(FrameSize(1600, 900), supported))+ }++ @Test fun supportedSizesPreferSurfaceTextureThenPrivate() {+ val withTexture = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = mapOf(ImageFormat.PRIVATE to listOf(Size(640, 480))),+ surfaceTextureSizes = listOf(Size(1920, 1080), Size(1280, 720)),+ )+ assertEquals(+ listOf(FrameSize(1920, 1080), FrameSize(1280, 720)),+ StreamSelection.supportedPreviewSizes(withTexture.snapshot),+ )+ val privateOnly = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = mapOf(ImageFormat.PRIVATE to listOf(Size(640, 480))),+ )+ assertEquals(+ listOf(FrameSize(640, 480)),+ StreamSelection.supportedPreviewSizes(privateOnly.snapshot),+ )+ }+}