camera: own ZSL ring - shutter returns an already-exposed frame
- Commit
284f2ff1945b666e1d256d8504aff0c7f9567178- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 20:32 UTC (14 days ago)
- Parents
58f35ad
A YUV ring buffer (8 frames, acquireLatest drop policy) fills while the Camera2 session streams; on shutter it selects the frame nearest the press whose exposure had completed (from CaptureResult metadata) and either reprocesses it on reprocessable sessions (ImageWriter + createReprocessCaptureRequest) or encodes it directly, falling back to a regular still on a ring miss - the shutter is never lost. The latency model is the point: no AE convergence wait and no fresh exposure. Policy admits only plain single PHOTO with YUV reprocess support; RAW rings slot into the same generic structure later (scoped out, listed in the change). Gate defaults off. Verified: 118 camera2 tests pass incl. eviction/selection/ fallback/pairing tests; full suite deferred while the health suite occupies the box.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.ktindex 5446011a2e..b1e3902cdf 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2StillCapture.kt@@ -12,6 +12,7 @@ import com.vayunmathur.camera.domain.StillFormat import com.vayunmathur.camera.platform.camera2.Camera2Session import com.vayunmathur.camera.platform.camera2.CapturedStill import com.vayunmathur.camera.platform.camera2.StillEngineInput+import com.vayunmathur.camera.platform.camera2.ReprocessRingGate import com.vayunmathur.camera.platform.camera2.StillEnginePolicy import com.vayunmathur.library.log.Log import kotlinx.coroutines.Dispatchers@@ -73,16 +74,20 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { captureForResult = captureForResult, burst = burstActiveMutable.value, )- if (!StillEnginePolicy.usesCamera2(input)) return false+ // Depth-phase ring inputs: gate + facade reprocess + live ring output.+ val ringInput = input.copy(+ ringEnabled = ReprocessRingGate.ENABLED && camera2PreviewEnabledMutable.value,+ reprocessSupported = session.reprocessSupported,+ hasRingOutput = session.hasRingOutput,+ )+ if (!StillEnginePolicy.usesCamera2(ringInput)) return false // Flash setting is the one control the preview effects do not push; // zoom/torch/EV/metering already live on the session. session.setFlashSetting(flashModeMutable.value.toFlashSetting()) val mirrored = mirrorCaptures emitShutterFeedback()- session.capture(- mirrored = mirrored,- callback = object : Camera2Session.StillCallback {+ val stillCallback = object : Camera2Session.StillCallback { override fun onStillCaptured(still: CapturedStill) { viewModelScope.launch { val uri = withContext(Dispatchers.IO) {@@ -99,8 +104,15 @@ internal fun CameraViewModel.tryCaptureCamera2Still(): Boolean { Log.status("Camera2Still", "capture failed: $message") isCapturingMutable.value = false }- },- )+ }+ // Ring first when the policy selects it; its runtime fallback to a+ // regular still lives inside captureFromRing. Night captures never+ // reach here (policy excludes the night route, Phase 6 is separate).+ if (StillEnginePolicy.usesRing(ringInput)) {+ session.captureFromRing(callback = stillCallback, mirrored = mirrored)+ } else {+ session.capture(mirrored = mirrored, callback = stillCallback)+ } return true }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.ktindex bd94367b01..2aa869cf9c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Driver.kt@@ -44,6 +44,14 @@ interface DeviceCallback { fun onError(errorCode: Int) } +/** Callbacks for preview `CaptureResult`s (ring metadata pairing). */+fun interface PreviewResultCallback {+ fun onPreviewResult(metadata: RawStillMetadata)+}++/** Input stream config for a reprocessable session (the ring format). */+data class ReprocessInputConfig(val width: Int, val height: Int, val format: Int)+ /** Callbacks for one [DeviceHandle.createCaptureSession] call. */ interface CaptureSessionCallback { fun onConfigured(session: CaptureSessionHandle)@@ -84,6 +92,19 @@ interface DeviceHandle { callback.onConfigureFailed() } + /**+ * Creates a reprocessable session whose input is [input] (the ring+ * reader). The default fails the configure: silently substituting a+ * regular session would let a "reprocess" request consume nothing.+ */+ fun createReprocessableCaptureSession(+ input: ReprocessInputConfig,+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ callback.onConfigureFailed()+ }+ fun close() } @@ -106,6 +127,35 @@ interface CaptureSessionHandle { */ fun captureStill(params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback) + /**+ * Streaming request over [targets] (preview first, ring second when+ * present) with per-frame results for ring metadata pairing. The+ * default keeps the single-target behaviour and drops results.+ */+ fun setRepeatingStreaming(+ params: ResolvedRequestParams,+ targets: List<Surface>,+ callback: PreviewResultCallback?,+ ) {+ if (targets.isNotEmpty()) setRepeatingPreview(params, targets.first())+ }++ /** True when this session was created as reprocessable. */+ val isReprocessable: Boolean get() = false++ /**+ * Reprocesses [frame] (a held ring image) into [stillTarget] with a+ * TEMPLATE_STILL_CAPTURE reprocess request via `ImageWriter`.+ * Returns false when this session cannot reprocess — the caller+ * then falls back to direct encode of the same frame.+ */+ fun captureReprocess(+ params: ResolvedStillParams,+ stillTarget: Surface,+ frame: RingHeldFrame,+ callback: StillResultCallback,+ ): Boolean = false+ /** * Issues [params] as the TEMPLATE_RECORD repeating burst on [targets] * (encoder surface first, preview second) of a constrained high-speed@@ -126,6 +176,9 @@ interface Camera2Driver { /** Creates the JPEG still output for [size], or null when unavailable. */ fun createStillOutput(size: FrameSize): StillOutput?++ /** Creates the YUV ring output for [size]; null when unavailable. */+ fun createRingOutput(size: FrameSize): RingOutput? = null } /** Converts a pure [SensorRect] into the HAL's `Rect`. */@@ -254,6 +307,9 @@ class AndroidCamera2Driver( override fun createStillOutput(size: FrameSize): StillOutput? = runCatching { JpegStillOutput(size.width, size.height, handler = handler) }.getOrNull() + override fun createRingOutput(size: FrameSize): RingOutput? =+ runCatching { YuvRingOutput(size.width, size.height, handler = handler) }.getOrNull()+ @SuppressLint("MissingPermission") override fun openCamera(cameraId: String, callback: DeviceCallback) { manager.openCamera(@@ -314,6 +370,52 @@ private class AndroidDeviceHandle( } } + override fun createReprocessableCaptureSession(+ input: ReprocessInputConfig,+ surfaces: List<Surface>,+ callback: CaptureSessionCallback,+ ) {+ val stateCallback = object : CameraCaptureSession.StateCallback() {+ override fun onConfigured(session: CameraCaptureSession) =+ callback.onConfigured(+ AndroidCaptureSessionHandle(+ device, session, handler,+ inputSurface = runCatching { session.inputSurface }.getOrNull(),+ ),+ )++ 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,+ )+ config.inputConfiguration =+ android.hardware.camera2.params.InputConfiguration(+ input.width, input.height, input.format,+ )+ runCatching { device.createCaptureSession(config) }+ .onFailure { callback.onConfigureFailed() }+ } else {+ @Suppress("DEPRECATION")+ runCatching {+ device.createReprocessableCaptureSession(+ android.hardware.camera2.params.InputConfiguration(+ input.width, input.height, input.format,+ ),+ surfaces, stateCallback, handler,+ )+ }.onFailure { callback.onConfigureFailed() }+ }+ }+ override fun createConstrainedHighSpeedCaptureSession( surfaces: List<Surface>, callback: CaptureSessionCallback,@@ -429,12 +531,95 @@ private class AndroidCaptureSessionHandle( private val device: CameraDevice, private val session: CameraCaptureSession, private val handler: Handler,+ private val inputSurface: Surface? = null, ) : CaptureSessionHandle { + private var imageWriter: android.media.ImageWriter? = null++ // Reprocess requests are built from a frame's TotalCaptureResult+ // (createReprocessCaptureRequest), so preview results are retained+ // by sensor timestamp until their ring image is consumed/evicted.+ private val previewResults = LinkedHashMap<Long, TotalCaptureResult>()++ override val isReprocessable: Boolean get() = inputSurface != null+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {+ setRepeatingStreaming(params, listOf(target), null)+ }++ override fun setRepeatingStreaming(+ params: ResolvedRequestParams,+ targets: List<Surface>,+ callback: PreviewResultCallback?,+ ) { val builder = device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)- builder.applyPreviewParams(params, target)- session.setRepeatingRequest(builder.build(), null, handler)+ builder.applyPreviewParams(params, targets.first())+ targets.drop(1).forEach { builder.addTarget(it) }+ val captureCallback = if (callback == null) {+ null+ } else {+ object : CameraCaptureSession.CaptureCallback() {+ override fun onCaptureCompleted(+ session: CameraCaptureSession,+ request: CaptureRequest,+ result: TotalCaptureResult,+ ) {+ result.get(CaptureResult.SENSOR_TIMESTAMP)?.let { ts ->+ previewResults[ts] = result+ while (previewResults.size > 16) {+ previewResults.remove(previewResults.keys.first())+ }+ }+ callback.onPreviewResult(result.toRawStillMetadata())+ }+ }+ }+ session.setRepeatingRequest(builder.build(), captureCallback, handler)+ }++ override fun captureReprocess(+ params: ResolvedStillParams,+ stillTarget: Surface,+ frame: RingHeldFrame,+ callback: StillResultCallback,+ ): Boolean {+ val input = inputSurface ?: return false+ val image = frame.nativeImageForReprocess as? android.media.Image ?: return false+ // queueInputImage transfers ownership of the ring image to the+ // writer; the session must not close it afterwards.+ val writer = imageWriter ?: android.media.ImageWriter.newInstance(input, 2).also {+ imageWriter = it+ }+ // No retained result for this frame (evicted before use): the+ // caller falls back to direct encode of the same image.+ val inputResult = previewResults.remove(frame.meta.sensorTimestampNs) ?: return false+ return runCatching {+ val builder = device.createReprocessCaptureRequest(inputResult)+ builder.applyStillParams(params, stillTarget)+ writer.queueInputImage(image)+ session.capture(+ builder.build(),+ object : CameraCaptureSession.CaptureCallback() {+ override fun onCaptureCompleted(+ session: CameraCaptureSession,+ request: CaptureRequest,+ result: TotalCaptureResult,+ ) {+ callback.onCompleted(result.toRawStillMetadata())+ }++ override fun onCaptureFailed(+ session: CameraCaptureSession,+ request: CaptureRequest,+ failure: android.hardware.camera2.CaptureFailure,+ ) {+ callback.onFailed("reprocess capture failed (reason ${failure.reason})")+ }+ },+ handler,+ )+ true+ }.getOrDefault(false) } override fun setRepeatingHighSpeed(params: ResolvedHighSpeedParams, targets: List<Surface>) {@@ -478,5 +663,9 @@ private class AndroidCaptureSessionHandle( ) } - override fun close() = session.close()+ override fun close() {+ runCatching { imageWriter?.close() }+ imageWriter = null+ session.close()+ } }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex 582f3b6eab..0f11166208 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt@@ -1,5 +1,6 @@ package com.vayunmathur.camera.platform.camera2 +import android.graphics.ImageFormat import android.view.Surface /**@@ -12,6 +13,13 @@ import android.view.Surface * reports JPEG sizes) and [capture] for plain single stills; see * [StillCapturePlanner] and [StillEnginePolicy]. *+ * The depth phase adds an optional YUV reprocess ring (third output,+ * [ReprocessRingConfig]): while streaming the ring holds the newest+ * already-exposed frames; [captureFromRing] serves a shutter from one+ * of them — reprocessed through `ImageWriter` on a reprocessable+ * session when the facade reports YUV reprocessing, direct-encoded+ * otherwise — with no AE-convergence wait or fresh exposure.+ * * 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@@ -31,6 +39,7 @@ class Camera2Session( private val snapshot: LensCharacteristicsSnapshot, private val stateMachine: SessionStateMachine = SessionStateMachine(), private val listener: Listener? = null,+ private val ringConfig: ReprocessRingConfig = ReprocessRingConfig.DISABLED, ) { /** Session lifecycle notifications; all fire on the executor thread. */@@ -55,6 +64,11 @@ class Camera2Session( private var previewSize: FrameSize? = null private var stillOutput: StillOutput? = null private var stillSize: FrameSize? = null+ private var ringOutput: RingOutput? = null+ private var ringSize: FrameSize? = null+ private val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity)+ private var latestPreviewTimestampNs: Long? = null+ private val previewMetas = LinkedHashMap<Long, RawStillMetadata>() private var pendingStill: PendingStill? = null private var displayRotationDegrees: Int = 0 private var controls: Camera2ControlState = Camera2ControlState.DEFAULT@@ -195,6 +209,120 @@ class Camera2Session( /** True when a JPEG output exists (see [StillEnginePolicy]). */ val hasJpegOutput: Boolean get() = stillOutput != null + /** True when the YUV ring output is configured (see [StillEnginePolicy]). */+ val hasRingOutput: Boolean get() = ringOutput != null++ /** The ring size configured at [open], or null when unavailable. */+ fun currentRingSize(): FrameSize? = ringSize++ /** Frames currently held in the ring. */+ val ringFrameCount: Int get() = ring.size++ /** Ring frames evicted (oldest dropped) since [open]. */+ val ringEvictedFrames: Long get() = ring.evictedFrames++ /** Facade-reported YUV reprocess support for this lens. */+ val reprocessSupported: Boolean get() = snapshot.supportsYuvRingReprocess++ /**+ * Takes one still from the ring: picks the exposure-complete frame+ * nearest [shutterTimestampNs] (or the latest preview timestamp when+ * null), then either reprocesses it on the reprocessable session or+ * direct-encodes it, delivering through the same [StillCallback]+ * shape as [capture]. A ring miss (empty / nothing fully exposed)+ * and a runtime reprocess refusal both fall back to the regular+ * still capture — the shutter is never lost to the ring.+ */+ fun captureFromRing(+ callback: StillCallback,+ shutterTimestampNs: Long? = null,+ displayRotationDegrees: Int? = null,+ mirrored: Boolean = false,+ ) {+ executor.execute {+ val session = captureSession+ when {+ stateMachine.state != SessionState.STREAMING || session == null ->+ callback.onStillFailed("ring capture requires a streaming session")+ ringOutput == null ->+ callback.onStillFailed("no YUV ring output on this session")+ pendingStill != null ->+ callback.onStillFailed("a still capture is already in flight")+ else -> {+ val shutter = shutterTimestampNs+ ?: latestPreviewTimestampNs+ ?: ring.metas().maxOfOrNull { it.sensorTimestampNs }+ val selection = shutter?.let { ring.select(it) }+ if (selection !is RingSelection.Hit) {+ // No already-exposed frame: take a fresh still.+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ val held = ring.remove(selection.meta.sensorTimestampNs)+ if (held == null) {+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ val params = StillCapturePlanner.resolve(+ state = controls,+ snapshot = snapshot,+ displayRotationDegrees = displayRotationDegrees+ ?: [email protected],+ mirrored = mirrored,+ )+ val output = stillOutput+ val reprocessed = output != null && snapshot.supportsYuvRingReprocess &&+ runCatching {+ val pending = PendingStill(params, callback)+ pendingStill = pending+ val started = session.captureReprocess(+ params, output.surface, held,+ object : StillResultCallback {+ override fun onCompleted(metadata: RawStillMetadata) =+ onStillResult(pending, metadata)++ override fun onFailed(message: String) =+ failPending(pending, message)+ },+ )+ if (!started && pendingStill === pending) pendingStill = null+ started+ }.getOrDefault(false)+ if (reprocessed) {+ // ImageWriter owns the held image from here.+ return@execute+ }+ // Direct fallback: encode the already-exposed frame.+ val jpeg = held.encodeJpeg()+ // The ring's copy carries preview-result patches;+ // the held frame's own meta may predate them.+ val meta = selection.meta+ held.close()+ if (jpeg == null) {+ startStillCapture(callback, displayRotationDegrees, mirrored)+ return@execute+ }+ callback.onStillCaptured(+ CapturedStill(+ jpegBytes = jpeg,+ jpegWidth = meta.width,+ jpegHeight = meta.height,+ metadata = StillMetadataMapper.map(+ RawStillMetadata(+ sensorTimestampNs = meta.sensorTimestampNs,+ exposureTimeNs = meta.exposureTimeNs,+ iso = meta.iso,+ frameNumber = meta.frameNumber,+ ),+ params.jpegOrientationDegrees, params.mirrored,+ ),+ ),+ )+ }+ }+ }+ }+ /** * Takes one plain still: issues `TEMPLATE_STILL_CAPTURE` carrying the * session's current control state plus flash resolution, and delivers@@ -218,32 +346,79 @@ class Camera2Session( callback.onStillFailed("no JPEG output on this session") pendingStill != null -> callback.onStillFailed("a still capture is already in flight")- else -> {- val params = StillCapturePlanner.resolve(- state = controls,- snapshot = snapshot,- displayRotationDegrees = displayRotationDegrees- ?: [email protected],- mirrored = mirrored,+ else -> startStillCapture(callback, displayRotationDegrees, mirrored)+ }+ }+ }++ /** Regular TEMPLATE_STILL_CAPTURE path (capture + ring-miss fallback). */+ private fun startStillCapture(+ callback: StillCallback,+ displayRotationDegrees: Int?,+ mirrored: Boolean,+ ) {+ val session = captureSession ?: run {+ callback.onStillFailed("still capture requires a streaming session")+ return+ }+ val output = stillOutput ?: run {+ callback.onStillFailed("no JPEG output on this session")+ return+ }+ if (pendingStill != null) {+ callback.onStillFailed("a still capture is already in flight")+ return+ }+ val params = StillCapturePlanner.resolve(+ state = controls,+ snapshot = snapshot,+ displayRotationDegrees = displayRotationDegrees+ ?: [email protected],+ mirrored = mirrored,+ )+ val pending = PendingStill(params, callback)+ pendingStill = pending+ runCatching {+ session.captureStill(params, output.surface, object : StillResultCallback {+ override fun onCompleted(metadata: RawStillMetadata) {+ onStillResult(pending, metadata)+ }++ override fun onFailed(message: String) {+ failPending(pending, message)+ }+ })+ }.onFailure { failPending(pending, "captureStill failed: ${it.message}") }+ }++ private fun onRingFrame(frame: RingHeldFrame) {+ try {+ executor.execute {+ val evicted = ring.offer(frame.meta, frame)+ evicted?.close()+ // The preview result may have arrived before this image.+ previewMetas[frame.meta.sensorTimestampNs]?.let { raw ->+ ring.attachMetadata(+ frame.meta.sensorTimestampNs, raw.exposureTimeNs,+ raw.frameNumber, raw.aeState, raw.iso, )- val pending = PendingStill(params, callback)- pendingStill = pending- runCatching {- session.captureStill(params, output.surface, object : StillResultCallback {- override fun onCompleted(metadata: RawStillMetadata) {- onStillResult(pending, metadata)- }-- override fun onFailed(message: String) {- failPending(pending, message)- }- })- }.onFailure { failPending(pending, "captureStill failed: ${it.message}") } } }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ frame.close() } } + private fun onPreviewResult(raw: RawStillMetadata) {+ val timestamp = raw.sensorTimestampNs ?: return+ latestPreviewTimestampNs = timestamp+ previewMetas[timestamp] = raw+ while (previewMetas.size > PREVIEW_META_CAP) {+ previewMetas.remove(previewMetas.keys.first())+ }+ ring.attachMetadata(timestamp, raw.exposureTimeNs, raw.frameNumber, raw.aeState, raw.iso)+ }+ private fun onStillResult(pending: PendingStill, metadata: RawStillMetadata) { // Real driver callbacks already land on the executor; fakes may // call synchronously. State is only touched on the executor.@@ -319,6 +494,11 @@ class Camera2Session( runCatching { stillOutput?.close() } stillOutput = null stillSize = null+ runCatching { ringOutput?.close() }+ ringOutput = null+ ringSize = null+ ring.drainAll().forEach { runCatching { it.close() } }+ previewMetas.clear() runCatching { device?.close() } device = null previewSurface = null@@ -337,8 +517,16 @@ class Camera2Session( 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}") }+ val targets = listOfNotNull(surface, ringOutput?.surface)+ runCatching {+ session.setRepeatingStreaming(params, targets, PreviewResultCallback { raw ->+ try {+ executor.execute { onPreviewResult(raw) }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ // Session is gone; preview metadata no longer matters.+ }+ })+ }.onFailure { reportError("setRepeatingPreview failed: ${it.message}") } } private fun configureSession(opened: DeviceHandle, gen: Long) {@@ -357,12 +545,36 @@ class Camera2Session( } stillOutput = output stillSize = if (output != null) jpegSize else null- val surfaces = listOfNotNull(surface, output?.surface)+ // Third output: the YUV ring, only when this session was built+ // with the ring enabled. Failure degrades to no-ring (the+ // policy then excludes the ring path, capture stays Phase 4a).+ val selectedRingSize = if (ringConfig.enabled) {+ StreamSelection.selectRingSize(snapshot)+ } else {+ null+ }+ val createdRing = selectedRingSize?.let { size ->+ runCatching { driver.createRingOutput(size) }.getOrNull()?.also { created ->+ created.setListener(RingFrameListener { frame -> onRingFrame(frame) })+ }+ }+ ringOutput = createdRing+ ringSize = if (createdRing != null) selectedRingSize else null+ val surfaces = listOfNotNull(surface, output?.surface, createdRing?.surface)+ val callback = SessionCallbackImpl(gen) runCatching {- opened.createCaptureSession(- surfaces,- SessionCallbackImpl(gen),- )+ if (createdRing != null && snapshot.supportsYuvRingReprocess) {+ opened.createReprocessableCaptureSession(+ ReprocessInputConfig(+ selectedRingSize.width, selectedRingSize.height,+ ImageFormat.YUV_420_888,+ ),+ surfaces,+ callback,+ )+ } else {+ opened.createCaptureSession(surfaces, callback)+ } }.onFailure { dispatch(gen, SessionEvent.CONFIGURE_FAILED) reportError("createCaptureSession failed: ${it.message}")@@ -389,6 +601,10 @@ class Camera2Session( listener?.onError(message) } + private companion object {+ const val PREVIEW_META_CAP: Int = 16+ }+ private inner class DeviceCallbackImpl( private val gen: Long, ) : DeviceCallback {
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 461e10fd5a..aae7fc1d92 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@@ -159,6 +159,12 @@ data class LensCharacteristicsSnapshot( * goes through `SCALER_CROP_REGION` instead. */ val supportsZoomRatioKey: Boolean = false,+ /**+ * Input sizes for reprocessing (`StreamConfigurationMap.getInputSizes`),+ * keyed by input format. Empty when never read (fake snapshots may+ * omit it — reprocess support then falls back to the capability bit).+ */+ val reprocessInputSizesByFormat: Map<Int, List<Size>> = emptyMap(), ) { val lensFacing: LensFacing? = when (lensFacingRaw) { CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK@@ -170,8 +176,39 @@ data class LensCharacteristicsSnapshot( val supportsRaw: Boolean get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW in availableCapabilities val supportsReprocess: Boolean- get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING in availableCapabilities ||- CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING in availableCapabilities+ get() = supportsYuvReprocessing || supportsPrivateReprocessing+ /** `YUV_REPROCESSING` capability: a YUV ring frame can be reprocessed. */+ val supportsYuvReprocessing: Boolean+ get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING in+ availableCapabilities+ /** `PRIVATE_REPROCESSING` capability (PRIVATE input, not our YUV ring). */+ val supportsPrivateReprocessing: Boolean+ get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING in+ availableCapabilities+ /**+ * The reprocess input format for this lens, or null when unsupported.+ * YUV is preferred (it is the ring format); PRIVATE is reported so a+ * future PRIVATE ring can use it, but the YUV ring cannot queue to it.+ */+ val reprocessInputFormat: Int?+ get() = when {+ supportsYuvReprocessing &&+ (reprocessInputSizesByFormat.isEmpty() ||+ ImageFormat.YUV_420_888 in reprocessInputSizesByFormat) ->+ ImageFormat.YUV_420_888+ supportsPrivateReprocessing &&+ (reprocessInputSizesByFormat.isEmpty() ||+ ImageFormat.PRIVATE in reprocessInputSizesByFormat) ->+ ImageFormat.PRIVATE+ else -> null+ }+ /** Advertised input sizes for [reprocessInputFormat] (empty if unread). */+ val reprocessInputSizes: List<Size>+ get() = reprocessInputFormat?.let { reprocessInputSizesByFormat[it].orEmpty() }+ .orEmpty()+ /** True when the YUV ring can honestly reprocess on this lens. */+ val supportsYuvRingReprocess: Boolean+ get() = reprocessInputFormat == ImageFormat.YUV_420_888 val supportsManualSensor: Boolean get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR in availableCapabilities /** True when the HAL offers `CONSTRAINED_HIGH_SPEED_VIDEO` (Phase 5). */@@ -231,6 +268,7 @@ class CharacteristicsFacade private constructor( highSpeedVideoSizes: List<Size> = emptyList(), highSpeedFpsRangesBySize: Map<Size, List<Range<Int>>> = emptyMap(), extensionSupport: Map<Int, ExtensionModeSupport> = emptyMap(),+ reprocessInputSizesByFormat: Map<Int, List<Size>> = emptyMap(), ): CharacteristicsFacade = fromSnapshot( LensCharacteristicsSnapshot( cameraId = cameraId,@@ -262,6 +300,7 @@ class CharacteristicsFacade private constructor( highSpeedVideoSizes = highSpeedVideoSizes, highSpeedFpsRangesBySize = highSpeedFpsRangesBySize, extensionSupport = extensionSupport,+ reprocessInputSizesByFormat = reprocessInputSizesByFormat, ), ) @@ -304,6 +343,12 @@ class CharacteristicsFacade private constructor( val highSpeedSizes = runCatching { streamMap?.highSpeedVideoSizes?.toList().orEmpty() }.getOrDefault(emptyList())+ val reprocessInputSizes = runCatching {+ streamMap?.inputFormats?.associateWith { format ->+ runCatching { streamMap.getInputSizes(format)?.toList().orEmpty() }+ .getOrDefault(emptyList())+ }.orEmpty()+ }.getOrDefault(emptyMap()) val highSpeedRanges = highSpeedSizes.associateWith { size -> runCatching { streamMap?.getHighSpeedVideoFpsRangesFor(size)?.toList().orEmpty()@@ -348,6 +393,7 @@ class CharacteristicsFacade private constructor( highSpeedVideoSizes = highSpeedSizes, highSpeedFpsRangesBySize = highSpeedRanges, extensionSupport = extensionSupport,+ reprocessInputSizesByFormat = reprocessInputSizes, ), ) }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.ktnew file mode 100644index 0000000000..ea54a6a111--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.kt@@ -0,0 +1,277 @@+package com.vayunmathur.camera.platform.camera2++import android.hardware.camera2.CameraMetadata++/**+ * Camera2 depth phase: own reprocess ZSL ring — pure core.+ *+ * A YUV `ImageReader` ring (N=[DEFAULT_CAPACITY]) is continuously filled+ * while the Camera2 session streams. On `capture()` the ring hands back an+ * already-exposed frame, so the shutter does not wait for AE convergence+ * or a fresh exposure (see [StillLatencyModel]). This file is the pure+ * half: frame descriptors, eviction/selection math and the latency model.+ * The Android holder (`YuvRingSource.kt`) and the session glue+ * (`Camera2Session.captureFromRing`) own the `Image` lifetimes.+ *+ * RAW is out of this phase: [RingFormat] and the generic payload type are+ * the slot a future RAW10/YUV dual ring uses — one `ReprocessRing` per+ * format, selected by a future RAW policy, with no change here.+ */++/** Gate for the ring path. Default OFF, mirroring [NightCamera2Gate]. */+object ReprocessRingGate {+ const val ENABLED: Boolean = false+}++/** Pixel format of one ring. RAW entries exist only as the future slot. */+enum class RingFormat {+ YUV_420_888,+ PRIVATE,+ RAW10,+ RAW_SENSOR,+}++/** What one ring instance holds. [format] picks the future dual-ring slot. */+data class ReprocessRingConfig(+ val enabled: Boolean = false,+ val capacity: Int = DEFAULT_CAPACITY,+ val format: RingFormat = RingFormat.YUV_420_888,+) {+ init {+ require(capacity > 0) { "ring capacity must be positive" }+ }++ companion object {+ const val DEFAULT_CAPACITY: Int = 8+ val DISABLED = ReprocessRingConfig(enabled = false)+ }+}++/**+ * Metadata of one ring frame, as far as `CaptureResult` reported it.+ * [sensorTimestampNs] is the frame's SENSOR_TIMESTAMP (start of exposure+ * on current HALs); [exposureTimeNs] is SENSOR_EXPOSURE_TIME when read.+ */+data class RingFrameMeta(+ val sensorTimestampNs: Long,+ val exposureTimeNs: Long? = null,+ val frameNumber: Long? = null,+ val aeState: Int? = null,+ val iso: Int? = null,+ val width: Int = 0,+ val height: Int = 0,+ val format: RingFormat = RingFormat.YUV_420_888,+) {+ /** End of exposure, or null when the exposure time is unknown. */+ val exposureEndNs: Long? get() = exposureTimeNs?.let { sensorTimestampNs + it }++ /**+ * True when this frame was fully exposed at [atNs]. With a known+ * exposure time that is `timestamp + exposure <= at`; without one the+ * frame can only be proven incomplete when it starts after [atNs],+ * so a started frame counts as complete (unknown is not a veto).+ */+ fun isExposureComplete(atNs: Long): Boolean {+ val end = exposureEndNs ?: return sensorTimestampNs <= atNs+ return end <= atNs+ }++ /** AE had converged/locked for this frame, when AE state was reported. */+ val aeConverged: Boolean+ get() = aeState == null ||+ aeState == CameraMetadata.CONTROL_AE_STATE_CONVERGED ||+ aeState == CameraMetadata.CONTROL_AE_STATE_LOCKED+}++/** Why a ring selection came back empty. */+enum class RingMissReason { EMPTY, NO_EXPOSURE_COMPLETE_FRAME }++/** Outcome of [ReprocessRing.select]. */+sealed interface RingSelection<out T> {+ data class Hit<T>(val frame: T, val meta: RingFrameMeta, val ageAtShutterNs: Long) :+ RingSelection<T>++ data class Miss(val reason: RingMissReason) : RingSelection<Nothing>+}++/**+ * Bounded ring of the newest [capacity] frames, newest last.+ *+ * Drop policy mirrors Phase 3 (`AnalysisImageSource`): the producer uses+ * acquireLatest semantics, frames are never queued for later — offering+ * into a full ring evicts (and returns, so the owner can close) the+ * oldest frame and counts it in [evictedFrames]. Selection does not+ * remove the frame; the caller removes/closes it once consumed.+ *+ * Not thread-safe by itself: the session feeds and drains it on the+ * Camera2 executor thread only.+ */+class ReprocessRing<T>(+ val capacity: Int = ReprocessRingConfig.DEFAULT_CAPACITY,+) {+ init {+ require(capacity > 0) { "ring capacity must be positive" }+ }++ private class Entry<T>(val payload: T, var meta: RingFrameMeta, val seq: Long)++ private val entries = ArrayDeque<Entry<T>>()+ private var nextSeq: Long = 0++ var evictedFrames: Long = 0+ private set+ var offeredFrames: Long = 0+ private set++ val size: Int get() = entries.size+ fun isEmpty(): Boolean = entries.isEmpty()++ /** Metas currently held, oldest first. */+ fun metas(): List<RingFrameMeta> = entries.map { it.meta }++ /** Payload for an exact sensor timestamp, or null. */+ fun payloadFor(timestampNs: Long): T? =+ entries.firstOrNull { it.meta.sensorTimestampNs == timestampNs }?.payload++ /**+ * Adds [payload]; returns the evicted oldest payload (owner must+ * close it) or null. Out-of-order timestamps are kept in arrival+ * order — selection is by timestamp, not position.+ */+ fun offer(meta: RingFrameMeta, payload: T): T? {+ offeredFrames+++ entries.addLast(Entry(payload, meta, nextSeq++))+ if (entries.size <= capacity) return null+ evictedFrames+++ return entries.removeFirst().payload+ }++ /** Patches CaptureResult fields onto a frame that arrived first. */+ fun attachMetadata(+ sensorTimestampNs: Long,+ exposureTimeNs: Long? = null,+ frameNumber: Long? = null,+ aeState: Int? = null,+ iso: Int? = null,+ ): Boolean {+ val entry = entries.firstOrNull { it.meta.sensorTimestampNs == sensorTimestampNs }+ ?: return false+ entry.meta = entry.meta.copy(+ exposureTimeNs = exposureTimeNs ?: entry.meta.exposureTimeNs,+ frameNumber = frameNumber ?: entry.meta.frameNumber,+ aeState = aeState ?: entry.meta.aeState,+ iso = iso ?: entry.meta.iso,+ )+ return true+ }++ /**+ * Picks the frame for a shutter at [shutterTimestampNs]: among+ * exposure-complete frames (see [RingFrameMeta.isExposureComplete])+ * the one whose sensor timestamp is nearest the shutter; ties go to+ * the later frame. Incomplete frames are never picked while a+ * complete one exists, and with no complete frame this is a [Miss]+ * (the caller falls back to a normal capture, never a half-exposed+ * frame). AE state does not veto — a converged frame is preferred+ * only as a tie-break via the timestamp rule in practice; ZSL rings+ * upstream only hold converged frames, here the exposure check is+ * the honest gate we can prove from metadata.+ */+ fun select(shutterTimestampNs: Long): RingSelection<T> {+ if (entries.isEmpty()) return RingSelection.Miss(RingMissReason.EMPTY)+ val complete = entries.filter { it.meta.isExposureComplete(shutterTimestampNs) }+ if (complete.isEmpty()) {+ return RingSelection.Miss(RingMissReason.NO_EXPOSURE_COMPLETE_FRAME)+ }+ val best = complete.minWithOrNull(+ compareBy<Entry<T>>(+ { kotlin.math.abs(it.meta.sensorTimestampNs - shutterTimestampNs) },+ // Later timestamp, then later arrival: ties go to the newest.+ { -it.meta.sensorTimestampNs },+ { -it.seq },+ ),+ ) ?: return RingSelection.Miss(RingMissReason.EMPTY)+ return RingSelection.Hit(+ frame = best.payload,+ meta = best.meta,+ ageAtShutterNs = shutterTimestampNs - best.meta.sensorTimestampNs,+ )+ }++ /** Latest fully-exposed frame at [atNs], or null (the select fallback). */+ fun latestComplete(atNs: Long): Pair<T, RingFrameMeta>? =+ entries.filter { it.meta.isExposureComplete(atNs) }+ .maxByOrNull { it.meta.sensorTimestampNs }+ ?.let { it.payload to it.meta }++ /** Removes and returns one frame by timestamp (owner closes it). */+ fun remove(timestampNs: Long): T? {+ val index = entries.indexOfFirst { it.meta.sensorTimestampNs == timestampNs }+ if (index < 0) return null+ return entries.removeAt(index).payload+ }++ /** Drains every payload, oldest first (owner closes each). */+ fun drainAll(): List<T> {+ val all = entries.map { it.payload }+ entries.clear()+ return all+ }++ fun clear() {+ entries.clear()+ }+}++/** Latency split for one still, in milliseconds. Pure accounting. */+data class StillLatencyBreakdown(+ val aeConvergenceWaitMs: Long,+ val freshExposureMs: Long,+ val readoutEncodeMs: Long,+ val reprocessMs: Long,+) {+ val totalMs: Long get() = aeConvergenceWaitMs + freshExposureMs + readoutEncodeMs + reprocessMs+}++/**+ * Shutter-to-still latency model. The conventional Camera2/CameraX still+ * pays AE convergence plus a fresh exposure after the press; a ring+ * capture pays neither — the frame was already exposed while streaming —+ * only readout/encode (direct fallback) or reprocess+encode. This is+ * the win the ring exists for, stated as arithmetic tests can assert.+ */+object StillLatencyModel {++ fun conventional(+ aeConvergenceWaitMs: Long,+ exposureMs: Long,+ readoutEncodeMs: Long,+ ): StillLatencyBreakdown = StillLatencyBreakdown(+ aeConvergenceWaitMs = aeConvergenceWaitMs.coerceAtLeast(0),+ freshExposureMs = exposureMs.coerceAtLeast(0),+ readoutEncodeMs = readoutEncodeMs.coerceAtLeast(0),+ reprocessMs = 0,+ )++ /** Ring + HAL reprocess: no AE wait, no fresh exposure. */+ fun ringReprocess(reprocessMs: Long, readoutEncodeMs: Long): StillLatencyBreakdown =+ StillLatencyBreakdown(+ aeConvergenceWaitMs = 0,+ freshExposureMs = 0,+ readoutEncodeMs = readoutEncodeMs.coerceAtLeast(0),+ reprocessMs = reprocessMs.coerceAtLeast(0),+ )++ /** Ring + direct encode fallback: no AE wait, no fresh exposure. */+ fun ringDirectEncode(readoutEncodeMs: Long): StillLatencyBreakdown =+ StillLatencyBreakdown(+ aeConvergenceWaitMs = 0,+ freshExposureMs = 0,+ readoutEncodeMs = readoutEncodeMs.coerceAtLeast(0),+ reprocessMs = 0,+ )++ /** Milliseconds the ring path saves over [conventional]. */+ fun savedMs(conventional: StillLatencyBreakdown, ring: StillLatencyBreakdown): Long =+ conventional.totalMs - ring.totalMs+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.ktindex 4ed3040e8d..711eee2783 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillEnginePolicy.kt@@ -3,7 +3,13 @@ package com.vayunmathur.camera.platform.camera2 import com.vayunmathur.camera.platform.CameraMode /** Which engine takes a still. */-enum class StillEngine { CAMERAX, CAMERA2 }+enum class StillEngine {+ CAMERAX,+ CAMERA2,++ /** Camera2 ZSL ring: an already-exposed YUV frame, reprocessed or direct-encoded. */+ CAMERA2_RING,+} /** * Inputs to the still-engine selection rule. Every flag that describes a@@ -25,6 +31,12 @@ data class StillEngineInput( val captureForResult: Boolean = false, /** Press-and-hold burst (a sequence, not a plain single capture). */ val burst: Boolean = false,+ /** Depth-phase ring gate (compile-time [ReprocessRingGate] AND runtime). */+ val ringEnabled: Boolean = false,+ /** Facade snapshot reports YUV reprocessing for this lens. */+ val reprocessSupported: Boolean = false,+ /** A YUV ring output is configured and holding frames on the session. */+ val hasRingOutput: Boolean = false, ) /**@@ -38,16 +50,50 @@ data class StillEngineInput( * - processed captures (warmth/shadows bake, portrait bokeh) — Phase 4a * does not re-encode through those pipelines from Camera2 bytes * - Motion Photo, burst, and capture-for-result- * - RAW, reprocess/ZSL-ring captures: no such output is configured on the- * Camera2 session in this phase at all+ * - RAW captures: no RAW output is configured in this phase (the ring is+ * structured so a RAW10 ring could slot in beside the YUV one later)+ *+ * Ring extension (depth phase): [StillEngine.CAMERA2_RING] is selected+ * only when [StillEngineInput.ringEnabled] is on, the facade reports YUV+ * reprocessing, a ring output exists, and every plain-single-photo rule+ * above already passes. Everything else stays exactly as today. The+ * direct-encode fallback in `Camera2Session.captureFromRing` covers a+ * runtime reprocess failure after this policy has passed (facade said+ * supported, the writer/session refused) — it is not a second route in. */ object StillEnginePolicy { - fun select(input: StillEngineInput): StillEngine =- if (exclusionReason(input) == null) StillEngine.CAMERA2 else StillEngine.CAMERAX+ fun select(input: StillEngineInput): StillEngine = when {+ ringExclusionReason(input) == null -> StillEngine.CAMERA2_RING+ exclusionReason(input) == null -> StillEngine.CAMERA2+ else -> StillEngine.CAMERAX+ }++ /** True when this shot should be taken on the Camera2 session (any path). */+ fun usesCamera2(input: StillEngineInput): Boolean = select(input) != StillEngine.CAMERAX++ /** True when this shot should be served from the reprocess ZSL ring. */+ fun usesRing(input: StillEngineInput): Boolean = select(input) == StillEngine.CAMERA2_RING++ /** Why [input] cannot use the ring, or null when it can. */+ fun ringExclusionReason(input: StillEngineInput): String? = when {+ !input.ringEnabled -> "reprocess ring gate off"+ !input.reprocessSupported -> "YUV reprocessing not supported for this lens"+ !input.hasRingOutput -> "no YUV ring output on the Camera2 session"+ exclusionReason(input) != null -> exclusionReason(input)+ else -> null+ }++ /** Why HAL reprocessing cannot run for [input], or null when it can. */+ fun reprocessExclusionReason(input: StillEngineInput): String? = when {+ ringExclusionReason(input) != null -> ringExclusionReason(input)+ !input.reprocessSupported -> "YUV reprocessing not supported for this lens"+ else -> null+ } - /** True when this shot should be taken on the Camera2 session. */- fun usesCamera2(input: StillEngineInput): Boolean = select(input) == StillEngine.CAMERA2+ /** True when the ring frame should go through ImageWriter reprocessing. */+ fun usesReprocess(input: StillEngineInput): Boolean =+ reprocessExclusionReason(input) == null /** Why [input] cannot use Camera2, or null when it can. */ fun exclusionReason(input: StillEngineInput): String? = when {
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.ktindex 3d734cfbf9..45a593e010 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StreamSelection.kt@@ -127,6 +127,26 @@ object StreamSelection { supportedJpegSizes(snapshot) .maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height })) + /** Supported YUV_420_888 sizes in facade order (empty = no ring). */+ fun supportedYuvSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> =+ snapshot.streamConfig.sizesFor(ImageFormat.YUV_420_888)+ .map { FrameSize.from(it) }.distinct()++ /**+ * The ring size: the largest advertised reprocess-input size that is+ * also a YUV output (the only size a reprocess request can honestly+ * consume), else the largest YUV output. Null when the lens reports+ * no YUV sizes — no ring output is configured then.+ */+ fun selectRingSize(snapshot: LensCharacteristicsSnapshot): FrameSize? {+ val yuv = supportedYuvSizes(snapshot)+ if (yuv.isEmpty()) return null+ val inputSizes = snapshot.reprocessInputSizes.map { FrameSize.from(it) }+ val reprocessable = yuv.filter { it in inputSizes }+ val pool = if (reprocessable.isNotEmpty()) reprocessable else yuv+ return pool.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ }+ /** The rejection for [requested], or null when a size can be selected. */ fun rejectionFor( requested: FrameSize,
camera/src/main/java/com/vayunmathur/camera/platform/camera2/YuvRingSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/YuvRingSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/YuvRingSource.ktnew file mode 100644index 0000000000..2e9e8f84ec--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/YuvRingSource.kt@@ -0,0 +1,194 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.graphics.Rect+import android.graphics.YuvImage+import android.media.Image+import android.media.ImageReader+import android.os.Handler+import android.view.Surface+import com.vayunmathur.camera.domain.PlaneView+import com.vayunmathur.library.log.Log+import java.io.ByteArrayOutputStream++/** Delivers one held ring frame; fires on the reader handler thread. */+fun interface RingFrameListener {+ fun onRingFrame(frame: RingHeldFrame)+}++/**+ * One frame held by the [ReprocessRing]. The owner must [close] it:+ * an unclosed image exhausts the reader pool and stalls the stream.+ * [encodeJpeg] is the direct-conversion fallback used when HAL+ * reprocessing is unavailable; it is valid until [close].+ */+interface RingHeldFrame : AutoCloseable {+ val meta: RingFrameMeta++ /** The underlying `Image` for the reprocess writer, or null in fakes. */+ val nativeImageForReprocess: Any? get() = null++ /** JPEG bytes from this frame's YUV planes, or null on failure. */+ fun encodeJpeg(quality: Int = DEFAULT_JPEG_QUALITY): ByteArray?++ override fun close()++ companion object {+ const val DEFAULT_JPEG_QUALITY: Int = 95+ }+}++/** Testable handle over the ring's YUV `ImageReader` (real driver below). */+interface RingOutput : AutoCloseable {+ val surface: Surface+ fun setListener(listener: RingFrameListener?)+ override fun close()+}++/** Pure YUV_420_888 -> NV21 assembly (the layout `YuvImage` consumes). */+object Yuv420ToNv21 {++ /** [planes] are Y, U, V in format order, any row/pixel stride. */+ fun convert(planes: List<PlaneView>, width: Int, height: Int): ByteArray? {+ if (planes.size < 3 || width <= 0 || height <= 0) return null+ val out = ByteArray(width * height + 2 * ((width + 1) / 2) * ((height + 1) / 2))+ val yPlane = planes[0]+ var offset = 0+ for (row in 0 until height) {+ for (col in 0 until width) {+ out[offset++] = sample(yPlane, col, row)+ }+ }+ val chromaWidth = (width + 1) / 2+ val chromaHeight = (height + 1) / 2+ val uPlane = planes[1]+ val vPlane = planes[2]+ for (row in 0 until chromaHeight) {+ for (col in 0 until chromaWidth) {+ // NV21 is interleaved V,U.+ out[offset++] = sample(vPlane, col, row)+ out[offset++] = sample(uPlane, col, row)+ }+ }+ return out+ }++ private fun sample(plane: PlaneView, x: Int, y: Int): Byte {+ val buffer = plane.buffer.duplicate()+ val index = y * plane.rowStride + x * plane.pixelStride+ if (index < 0 || index >= buffer.limit()) return 0+ return buffer.get(index)+ }+}++/** [RingHeldFrame] over a real Camera2 [Image]. */+class ImageRingHeldFrame(private val image: Image) : RingHeldFrame {+ override val meta: RingFrameMeta = RingFrameMeta(+ sensorTimestampNs = image.timestamp,+ width = image.width,+ height = image.height,+ format = RingFormat.YUV_420_888,+ )++ override val nativeImageForReprocess: Any get() = image++ @Volatile+ private var closed = false++ override fun encodeJpeg(quality: Int): ByteArray? {+ if (closed) return null+ return try {+ val planes = image.planes.map { plane ->+ PlaneView(+ buffer = plane.buffer.duplicate(),+ rowStride = plane.rowStride,+ pixelStride = plane.pixelStride,+ width = image.width,+ height = image.height,+ )+ }+ val nv21 = Yuv420ToNv21.convert(planes, image.width, image.height) ?: return null+ val yuv = YuvImage(nv21, ImageFormat.NV21, image.width, image.height, null)+ ByteArrayOutputStream().use { out ->+ if (!yuv.compressToJpeg(Rect(0, 0, image.width, image.height), quality, out)) {+ null+ } else {+ out.toByteArray()+ }+ }+ } catch (e: IllegalStateException) {+ Log.error("YuvRingSource", "ring frame JPEG encode failed", e)+ null+ } catch (e: IllegalArgumentException) {+ Log.error("YuvRingSource", "ring frame JPEG encode failed", e)+ null+ }+ }++ override fun close() {+ if (closed) return+ closed = true+ try {+ image.close()+ } catch (e: IllegalStateException) {+ Log.error("YuvRingSource", "ring image close threw", e)+ }+ }+}++/**+ * YUV `ImageReader` ring source. Uses `acquireLatestImage()` (Phase-3+ * semantics): when the HAL outruns the session, intermediate images are+ * discarded by the reader itself; every acquired image becomes a+ * [RingHeldFrame] the session's [ReprocessRing] evicts/closes.+ *+ * Ownership: whoever constructs this owns it and must call [close].+ */+class YuvRingOutput(+ width: Int,+ height: Int,+ maxImages: Int = ReprocessRingConfig.DEFAULT_CAPACITY,+ private val handler: Handler,+) : RingOutput {++ private val reader: ImageReader =+ ImageReader.newInstance(width, height, ImageFormat.YUV_420_888, maxImages)++ override val surface: Surface get() = reader.surface++ @Volatile+ private var listener: RingFrameListener? = null++ init {+ reader.setOnImageAvailableListener({ onImageAvailable() }, handler)+ }++ override fun setListener(listener: RingFrameListener?) {+ this.listener = listener+ }++ private fun onImageAvailable() {+ val image = try {+ reader.acquireLatestImage()+ } catch (e: IllegalStateException) {+ Log.error("YuvRingSource", "acquireLatestImage threw", e)+ null+ } ?: return+ val frame = ImageRingHeldFrame(image)+ val current = listener+ if (current == null) {+ frame.close()+ return+ }+ current.onRingFrame(frame)+ }++ override fun close() {+ try {+ reader.setOnImageAvailableListener(null, null)+ } catch (e: IllegalStateException) {+ Log.error("YuvRingSource", "clearing listener threw", e)+ }+ reader.close()+ }+}
camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.ktindex d3b70f0174..2955d41f94 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/Camera2Preview.kt@@ -18,6 +18,8 @@ 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.ReprocessRingConfig+import com.vayunmathur.camera.platform.camera2.ReprocessRingGate import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent import com.vayunmathur.library.log.Log @@ -103,6 +105,7 @@ private class Camera2PreviewSession(context: Context, private val cameraId: Stri driver = driver, executor = executor, snapshot = facade.snapshot,+ ringConfig = ReprocessRingConfig(enabled = ReprocessRingGate.ENABLED), listener = object : Camera2Session.Listener { override fun onError(message: String) { Log.status("Camera2Preview", message)
camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingSessionTest.ktnew file mode 100644index 0000000000..95be9f92b3--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingSessionTest.kt@@ -0,0 +1,349 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraMetadata+import android.util.Range+import android.util.Size+import android.view.Surface+import com.vayunmathur.camera.platform.CameraMode+import java.util.concurrent.CountDownLatch+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.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.mockito.Mockito.mock+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ReprocessRingSessionTest {++ // -- fakes ----------------------------------------------------------------++ private class FakeRingFrame(+ ts: Long,+ exposureNs: Long? = 10L,+ private val jpeg: ByteArray? = byteArrayOf(7, 7, 7),+ ) : RingHeldFrame {+ override val meta = RingFrameMeta(+ sensorTimestampNs = ts, exposureTimeNs = exposureNs,+ width = 1920, height = 1080,+ )+ val closes = AtomicInteger(0)+ val encodes = AtomicInteger(0)+ override fun encodeJpeg(quality: Int): ByteArray? {+ encodes.incrementAndGet()+ return jpeg+ }+ override fun close() { closes.incrementAndGet() }+ }++ private class FakeRingOutput : RingOutput {+ override val surface: Surface = mock(Surface::class.java)+ var ringListener: RingFrameListener? = null+ var closed = false+ override fun setListener(listener: RingFrameListener?) { ringListener = listener }+ override fun close() { closed = true }+ fun emit(frame: RingHeldFrame) = ringListener?.onRingFrame(frame)+ }++ private class FakeStillOutput : StillOutput {+ override val surface: Surface = mock(Surface::class.java)+ var jpegListener: JpegImageListener? = null+ var closed = false+ override fun setListener(listener: JpegImageListener?) { jpegListener = listener }+ override fun close() { closed = true }+ fun emit(bytes: ByteArray) = jpegListener?.onJpeg(bytes, 4000, 3000, 99L)+ }++ private class FakeHandle(+ var reprocessResult: Boolean = false,+ ) : CaptureSessionHandle {+ val stillRequests = mutableListOf<ResolvedStillParams>()+ var stillCallback: StillResultCallback? = null+ val reprocessFrames = mutableListOf<RingHeldFrame>()+ var reprocessCallback: StillResultCallback? = null+ var streamingTargets: List<Surface> = emptyList()+ var previewCallback: PreviewResultCallback? = null+ var closed = false+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+ override fun setRepeatingStreaming(+ params: ResolvedRequestParams, targets: List<Surface>, callback: PreviewResultCallback?,+ ) {+ streamingTargets = targets+ previewCallback = callback+ }+ override fun captureStill(+ params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback,+ ) {+ stillRequests += params+ stillCallback = callback+ }+ override fun captureReprocess(+ params: ResolvedStillParams, stillTarget: Surface,+ frame: RingHeldFrame, callback: StillResultCallback,+ ): Boolean {+ reprocessFrames += frame+ reprocessCallback = callback+ return reprocessResult+ }+ override fun close() { closed = true }+ }++ private class FakeDevice(private val handle: FakeHandle) : DeviceHandle {+ override val cameraId: String = "0"+ var surfaces: List<Surface>? = null+ var reprocessInput: ReprocessInputConfig? = null+ override fun createCaptureSession(surfaces: List<Surface>, callback: CaptureSessionCallback) {+ this.surfaces = surfaces+ callback.onConfigured(handle)+ }+ override fun createReprocessableCaptureSession(+ input: ReprocessInputConfig, surfaces: List<Surface>, callback: CaptureSessionCallback,+ ) {+ this.surfaces = surfaces+ reprocessInput = input+ callback.onConfigured(handle)+ }+ override fun close() {}+ }++ private class FakeDriver(+ private val device: FakeDevice,+ private val still: FakeStillOutput?,+ private val ring: FakeRingOutput?,+ ) : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) =+ callback.onOpened(device)+ override fun createStillOutput(size: FrameSize): StillOutput? = still+ override fun createRingOutput(size: FrameSize): RingOutput? = ring+ }++ private class RecordingCallback : Camera2Session.StillCallback {+ val captured = mutableListOf<CapturedStill>()+ val failures = mutableListOf<String>()+ override fun onStillCaptured(still: CapturedStill) { captured += still }+ override fun onStillFailed(message: String) { failures += message }+ }++ private fun snapshot(reprocess: Boolean): LensCharacteristicsSnapshot =+ CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+ zoomRatioRange = Range(1f, 10f),+ hasFlashUnit = true,+ exposureCompensationEvRange = Range(-4f, 4f),+ sizesByFormat = mapOf(+ ImageFormat.PRIVATE to listOf(Size(1280, 720)),+ ImageFormat.JPEG to listOf(Size(4000, 3000)),+ ImageFormat.YUV_420_888 to listOf(Size(1920, 1080)),+ ),+ availableCapabilities = if (reprocess) {+ setOf(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING)+ } else {+ emptySet()+ },+ activeArrayWidth = 4000,+ activeArrayHeight = 3000,+ sensorOrientationDegrees = 90,+ exposureCompensationStepEv = 1f / 6f,+ maxAfRegions = 1,+ maxAeRegions = 1,+ reprocessInputSizesByFormat = if (reprocess) {+ mapOf(ImageFormat.YUV_420_888 to listOf(Size(1920, 1080)))+ } else {+ emptyMap()+ },+ ).snapshot++ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS), "executor did not drain")+ }++ private fun streaming(+ executor: Camera2Executor,+ handle: FakeHandle,+ reprocess: Boolean,+ ring: FakeRingOutput? = FakeRingOutput(),+ ): Triple<Camera2Session, FakeStillOutput, FakeDevice> {+ val still = FakeStillOutput()+ val device = FakeDevice(handle)+ val session = Camera2Session(+ FakeDriver(device, still, ring), executor, snapshot(reprocess),+ ringConfig = ReprocessRingConfig(enabled = true),+ )+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ return Triple(session, still, device)+ }++ // -- policy ---------------------------------------------------------------++ @Test fun ringPolicyNeedsGateReprocessRingOutputAndPlainPhoto() {+ val plain = StillEngineInput(+ camera2Enabled = true, mode = CameraMode.PHOTO, hasJpegOutput = true,+ ringEnabled = true, reprocessSupported = true, hasRingOutput = true,+ )+ assertEquals(StillEngine.CAMERA2_RING, StillEnginePolicy.select(plain))+ assertTrue(StillEnginePolicy.usesRing(plain))+ assertTrue(StillEnginePolicy.usesReprocess(plain))+ // Each requirement removed drops back to the Phase-4a plain path.+ assertEquals(StillEngine.CAMERA2, StillEnginePolicy.select(plain.copy(ringEnabled = false)))+ assertEquals(StillEngine.CAMERA2, StillEnginePolicy.select(plain.copy(reprocessSupported = false)))+ assertEquals(StillEngine.CAMERA2, StillEnginePolicy.select(plain.copy(hasRingOutput = false)))+ // Non-plain shots stay CameraX even with every ring flag on.+ assertEquals(StillEngine.CAMERAX, StillEnginePolicy.select(plain.copy(nightRoute = true)))+ assertEquals(StillEngine.CAMERAX, StillEnginePolicy.select(plain.copy(burst = true)))+ assertEquals(StillEngine.CAMERAX, StillEnginePolicy.select(plain.copy(mode = CameraMode.PORTRAIT)))+ assertTrue(StillEnginePolicy.ringExclusionReason(plain.copy(nightRoute = true)).orEmpty().contains("night"))+ }++ @Test fun facadeReportsYuvReprocessOnlyForYuvCapability() {+ assertTrue(snapshot(true).supportsYuvRingReprocess)+ assertEquals(ImageFormat.YUV_420_888, snapshot(true).reprocessInputFormat)+ assertFalse(snapshot(false).supportsYuvRingReprocess)+ assertNull(snapshot(false).reprocessInputFormat)+ val privateOnly = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ availableCapabilities = setOf(+ CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING,+ ),+ ).snapshot+ assertEquals(ImageFormat.PRIVATE, privateOnly.reprocessInputFormat)+ assertFalse(privateOnly.supportsYuvRingReprocess) // YUV ring cannot queue to PRIVATE+ }++ // -- session --------------------------------------------------------------++ @Test fun ringConfiguresReprocessableSessionWithRingTarget() {+ val executor = Camera2Executor("RingSessionTest-config")+ try {+ val handle = FakeHandle()+ val ring = FakeRingOutput()+ val (session, _, device) = streaming(executor, handle, reprocess = true, ring = ring)+ assertTrue(session.hasRingOutput)+ assertTrue(session.reprocessSupported)+ assertEquals(FrameSize(1920, 1080), session.currentRingSize())+ assertEquals(+ ReprocessInputConfig(1920, 1080, ImageFormat.YUV_420_888), device.reprocessInput,+ )+ assertEquals(3, device.surfaces!!.size) // preview + JPEG + ring+ assertEquals(2, handle.streamingTargets.size) // preview + ring+ session.close(); executor.drain()+ assertTrue(ring.closed)+ } finally { executor.shutdown() }+ }++ @Test fun directFallbackEncodesAlreadyExposedFrameWithoutStillRequest() {+ val executor = Camera2Executor("RingSessionTest-direct")+ try {+ val handle = FakeHandle()+ val ring = FakeRingOutput()+ val (session, _, _) = streaming(executor, handle, reprocess = false, ring = ring)+ val older = FakeRingFrame(100)+ val nearer = FakeRingFrame(200)+ ring.emit(older); ring.emit(nearer); executor.drain()+ assertEquals(2, session.ringFrameCount)++ val callback = RecordingCallback()+ session.captureFromRing(callback, shutterTimestampNs = 215)+ executor.drain()+ assertEquals(1, callback.captured.size)+ assertTrue(callback.captured.single().jpegBytes.contentEquals(byteArrayOf(7, 7, 7)))+ assertEquals(200L, callback.captured.single().metadata.sensorTimestampNs)+ assertEquals(0, handle.stillRequests.size) // no fresh exposure was requested+ assertEquals(1, nearer.encodes.get())+ assertEquals(1, nearer.closes.get())+ assertEquals(0, older.encodes.get())+ session.close(); executor.drain()+ } finally { executor.shutdown() }+ }++ @Test fun reprocessPathQueuesRingFrameAndPairsJpeg() {+ val executor = Camera2Executor("RingSessionTest-reprocess")+ try {+ val handle = FakeHandle(reprocessResult = true)+ val ring = FakeRingOutput()+ val (session, still, _) = streaming(executor, handle, reprocess = true, ring = ring)+ val frame = FakeRingFrame(200)+ ring.emit(frame); executor.drain()+ val callback = RecordingCallback()+ session.captureFromRing(callback, shutterTimestampNs = 210)+ executor.drain()+ assertEquals(1, handle.reprocessFrames.size)+ assertEquals(0, frame.encodes.get()) // HAL reprocess, not direct encode+ // JPEG arrives through the still output, result through the callback.+ still.emit(byteArrayOf(1, 2))+ handle.reprocessCallback!!.onCompleted(RawStillMetadata(sensorTimestampNs = 200, iso = 100))+ executor.drain()+ assertEquals(1, callback.captured.size)+ assertEquals(100, callback.captured.single().metadata.iso)+ session.close(); executor.drain()+ } finally { executor.shutdown() }+ }++ @Test fun reprocessRuntimeRefusalFallsBackToDirectEncode() {+ val executor = Camera2Executor("RingSessionTest-refusal")+ try {+ val handle = FakeHandle(reprocessResult = false)+ val ring = FakeRingOutput()+ val (session, _, _) = streaming(executor, handle, reprocess = true, ring = ring)+ ring.emit(FakeRingFrame(200)); executor.drain()+ val callback = RecordingCallback()+ session.captureFromRing(callback, shutterTimestampNs = 210)+ executor.drain()+ assertEquals(1, handle.reprocessFrames.size)+ assertEquals(1, callback.captured.size) // same frame, direct-encoded+ assertEquals(0, handle.stillRequests.size)+ session.close(); executor.drain()+ } finally { executor.shutdown() }+ }++ @Test fun ringMissFallsBackToRegularStillCapture() {+ val executor = Camera2Executor("RingSessionTest-miss")+ try {+ val handle = FakeHandle()+ val ring = FakeRingOutput()+ val (session, _, _) = streaming(executor, handle, reprocess = true, ring = ring)+ // Only a still-exposing frame: ends 350, shutter at 260.+ ring.emit(FakeRingFrame(250, exposureNs = 100)); executor.drain()+ val callback = RecordingCallback()+ session.captureFromRing(callback, shutterTimestampNs = 260)+ executor.drain()+ assertEquals(1, handle.stillRequests.size) // fresh still, shutter not lost+ assertTrue(callback.captured.isEmpty())+ session.close(); executor.drain()+ assertEquals(1, callback.failures.size) // close fails the pending fresh still+ } finally { executor.shutdown() }+ }++ @Test fun previewResultsPatchRingFrameExposure() {+ val executor = Camera2Executor("RingSessionTest-meta")+ try {+ val handle = FakeHandle()+ val ring = FakeRingOutput()+ val (session, _, _) = streaming(executor, handle, reprocess = false, ring = ring)+ ring.emit(FakeRingFrame(200, exposureNs = null)); executor.drain()+ // Preview result for the same sensor timestamp arrives after.+ handle.previewCallback!!.onPreviewResult(+ RawStillMetadata(sensorTimestampNs = 200, exposureTimeNs = 10, iso = 320),+ )+ executor.drain()+ val callback = RecordingCallback()+ session.captureFromRing(callback, shutterTimestampNs = 215)+ executor.drain()+ assertEquals(1, callback.captured.size)+ assertEquals(320, callback.captured.single().metadata.iso)+ assertEquals(10L, callback.captured.single().metadata.exposureTimeNs)+ session.close(); executor.drain()+ } finally { executor.shutdown() }+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingTest.ktnew file mode 100644index 0000000000..3dd33ee827--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/ReprocessRingTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.domain.PlaneView+import java.nio.ByteBuffer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+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 ReprocessRingTest {++ private fun meta(ts: Long, exposureNs: Long? = 10L, format: RingFormat = RingFormat.YUV_420_888) =+ RingFrameMeta(sensorTimestampNs = ts, exposureTimeNs = exposureNs, format = format)++ // -- eviction -------------------------------------------------------------++ @Test fun offerEvictsOldestAndCounts() {+ val ring = ReprocessRing<String>(capacity = 3)+ assertNull(ring.offer(meta(1), "a"))+ assertNull(ring.offer(meta(2), "b"))+ assertNull(ring.offer(meta(3), "c"))+ assertEquals("a", ring.offer(meta(4), "d"))+ assertEquals(3, ring.size)+ assertEquals(1, ring.evictedFrames)+ assertEquals(4, ring.offeredFrames)+ assertEquals(listOf(2L, 3L, 4L), ring.metas().map { it.sensorTimestampNs })+ }++ @Test fun defaultCapacityIsEight() {+ val ring = ReprocessRing<Int>()+ repeat(8) { assertNull(ring.offer(meta(it.toLong()), it)) }+ assertEquals(0, ring.evictedFrames)+ assertEquals(0, ring.offer(meta(8), 8))+ assertEquals(8, ring.size)+ }++ @Test fun drainAndRemoveReturnPayloads() {+ val ring = ReprocessRing<String>(capacity = 4)+ ring.offer(meta(1), "a"); ring.offer(meta(2), "b"); ring.offer(meta(3), "c")+ assertEquals("b", ring.remove(2))+ assertNull(ring.remove(99))+ assertEquals(listOf("a", "c"), ring.drainAll())+ assertTrue(ring.isEmpty())+ }++ // -- selection ------------------------------------------------------------++ @Test fun selectPicksNearestExposureCompleteFrame() {+ val ring = ReprocessRing<String>(capacity = 8)+ ring.offer(meta(100), "a"); ring.offer(meta(200), "b"); ring.offer(meta(300), "c")+ // The 300 frame ends at 310 (still exposing at 260); nearest+ // exposure-complete frame is 200.+ val hit = ring.select(260) as RingSelection.Hit+ assertEquals("b", hit.frame)+ }++ @Test fun selectSkipsFrameStillExposingAtShutter() {+ val ring = ReprocessRing<String>(capacity = 8)+ ring.offer(meta(100, exposureNs = 10), "done-long-ago")+ ring.offer(meta(200, exposureNs = 10), "done")+ ring.offer(meta(250, exposureNs = 100), "still-exposing") // ends 350 > 260+ val hit = ring.select(260) as RingSelection.Hit+ assertEquals("done", hit.frame)+ assertEquals(60, hit.ageAtShutterNs)+ }++ @Test fun selectTieGoesToLaterFrame() {+ // Only a duplicate timestamp can tie (a frame starting after the+ // shutter is never exposure-complete at it); later arrival wins.+ val ring = ReprocessRing<String>(capacity = 8)+ ring.offer(meta(200, exposureNs = 10), "earlier")+ ring.offer(meta(200, exposureNs = 10), "later")+ val hit = ring.select(250) as RingSelection.Hit+ assertEquals("later", hit.frame)+ }++ @Test fun selectMissesWhenNothingFullyExposed() {+ val ring = ReprocessRing<String>(capacity = 8)+ ring.offer(meta(250, exposureNs = 100), "exposing")+ val miss = ring.select(260) as RingSelection.Miss+ assertEquals(RingMissReason.NO_EXPOSURE_COMPLETE_FRAME, miss.reason)+ val empty = ReprocessRing<String>().select(1) as RingSelection.Miss+ assertEquals(RingMissReason.EMPTY, empty.reason)+ }++ @Test fun unknownExposureCountsStartedFrameCompleteOnly() {+ val frame = RingFrameMeta(sensorTimestampNs = 100, exposureTimeNs = null)+ assertTrue(frame.isExposureComplete(100))+ assertFalse(frame.isExposureComplete(99))+ assertEquals(110L, RingFrameMeta(100, 10).exposureEndNs)+ assertNull(RingFrameMeta(100, null).exposureEndNs)+ }++ @Test fun latestCompleteAndMetadataPatch() {+ val ring = ReprocessRing<String>(capacity = 8)+ ring.offer(RingFrameMeta(sensorTimestampNs = 100), "a")+ ring.offer(RingFrameMeta(sensorTimestampNs = 200), "b")+ assertTrue(ring.attachMetadata(200, exposureTimeNs = 5, aeState = 2, iso = 400))+ assertFalse(ring.attachMetadata(999, exposureTimeNs = 5))+ assertEquals("b", ring.latestComplete(205)?.first)+ assertEquals(400, ring.latestComplete(205)?.second?.iso)+ // At 204 b is not yet fully exposed; a (unknown exposure, started) is.+ assertEquals("a", ring.latestComplete(204)?.first)+ }++ @Test fun rawFormatSlotHoldsAlongsideYuvShape() {+ // RAW is out of phase, but a second ring of RAW10 metas uses the+ // same eviction/selection math without changes to this class.+ val rawRing = ReprocessRing<String>(capacity = 2)+ rawRing.offer(meta(1, format = RingFormat.RAW10), "r1")+ rawRing.offer(meta(2, format = RingFormat.RAW10), "r2")+ assertEquals(RingFormat.RAW10, rawRing.metas().first().format)+ assertEquals("r2", (rawRing.select(12) as RingSelection.Hit).frame)+ }++ // -- latency model --------------------------------------------------------++ @Test fun ringLatencyHasNoAeWaitOrFreshExposure() {+ val conventional = StillLatencyModel.conventional(+ aeConvergenceWaitMs = 120, exposureMs = 33, readoutEncodeMs = 45,+ )+ assertEquals(198, conventional.totalMs)+ val reprocess = StillLatencyModel.ringReprocess(reprocessMs = 20, readoutEncodeMs = 45)+ assertEquals(0, reprocess.aeConvergenceWaitMs)+ assertEquals(0, reprocess.freshExposureMs)+ assertEquals(65, reprocess.totalMs)+ assertEquals(133, StillLatencyModel.savedMs(conventional, reprocess))+ val direct = StillLatencyModel.ringDirectEncode(readoutEncodeMs = 45)+ assertEquals(45, direct.totalMs)+ assertTrue(StillLatencyModel.savedMs(conventional, direct) > 0)+ }++ // -- NV21 conversion ------------------------------------------------------++ @Test fun nv21ConversionHonoursStridesAndInterleavesVu() {+ // 2x2: Y plane rowStride 3 (1 pad), chroma 1x1 pixelStride 1.+ val y = PlaneView(ByteBuffer.wrap(byteArrayOf(10, 20, 0, 30, 40, 0)), 3, 1, 2, 2)+ val u = PlaneView(ByteBuffer.wrap(byteArrayOf(100)), 1, 1, 1, 1)+ val v = PlaneView(ByteBuffer.wrap(byteArrayOf(110)), 1, 1, 1, 1)+ val nv21 = Yuv420ToNv21.convert(listOf(y, u, v), 2, 2)!!+ assertTrue(nv21.contentEquals(byteArrayOf(10, 20, 30, 40, 110, 100)))+ assertNull(Yuv420ToNv21.convert(listOf(y), 2, 2))+ }+}