camera: RAW burst merged in linear space for night (device-gated)
- Commit
0b79135a45a498ebeadaa16aedefa467290c8694- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 20:56 UTC (14 days ago)
- Parents
4bed66f
The night P2 core: a second RAW ring fills beside the YUV ring on the Camera2 session, and RAW bursts merge in Rust in linear space - black-level subtract/white-normalise (never crushed below black), white-balance gains, demosaic, green-channel registration, exposure-normalised trimmed merge with linear deghost, then the existing tone pipeline. This beats merging HAL-processed JPEGs, which bakes in per-frame NR/AWB. Glue hooks after the extension path with fallback to the existing night paths on any failure, and policy demands an explicit (default-off) opt-in. DNG sidecars deliberately NOT written: the metadata fields assemble from characteristics, but DngCreator needs live TotalCaptureResults the ring discards for testability - writing one anyway would ship corrupt DNGs. The gap is documented with the fix (retain live results in the driver). Two pre-existing FileLength lint errors (CameraViewModel, CameraPreviewBox) predate this change and are noted. Verified: cargo 160 pass incl. synthetic-Bayer noise- reduction tests; camera2 tests green. All device-blocked stream combos remain gate-off.
Diff
camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.ktnew file mode 100644index 0000000000..1a5849c96f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/Camera2RawNightGlue.kt@@ -0,0 +1,104 @@+package com.vayunmathur.camera.platform++import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.data.saveProcessedStill+import com.vayunmathur.camera.data.setLastCaptureUri+import com.vayunmathur.camera.platform.camera2.Camera2Session+import com.vayunmathur.camera.platform.camera2.DngMetadataAssembler+import com.vayunmathur.camera.platform.camera2.RawNightInput+import com.vayunmathur.camera.platform.camera2.RawNightMerger+import com.vayunmathur.camera.platform.camera2.RawNightPolicy+import com.vayunmathur.camera.platform.camera2.RawRingGate+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Camera2 depth Phase 2: RAW night glue between the gated dual-ring+ * [Camera2Session] and the existing night routing.+ *+ * Decision (see [RawNightPolicy]): RAW takes the night shutter only when+ * the gate is on, RAW night was explicitly selected, the facade proves+ * RAW, and the RAW ring is live. Else this returns false and the existing+ * routing (vendor extension, then YUV burst) runs exactly as before.+ *+ * On a RAW burst, frames go through the Rust linear merge and the result+ * lands via `saveProcessedStill` — the same `StillEncoder` landing as+ * every other night shot. No DNG sidecar is written: metadata assembly+ * is validated by [DngMetadataAssembler] and logged, but `DngCreator`+ * needs live characteristics/results the ring does not retain (see+ * `DngMetadata.kt`), so claiming a DNG here would be dishonest.+ */+internal fun CameraViewModel.tryCaptureCamera2RawNight(): Boolean {+ val session = activeCamera2Session ?: return false+ val snapshot = session.characteristics+ val input = RawNightInput(+ rawGateOn = RawRingGate.ENABLED && camera2RawNightEnabledMutable.value,+ explicitRawSelected = camera2RawNightEnabledMutable.value,+ mode = cameraModeMutable.value,+ nightRoute = true,+ rawSupported = session.rawSupported,+ hasRawRingOutput = session.hasRawRingOutput,+ dngMetadataComplete = DngMetadataAssembler.assemble(snapshot) != null,+ )+ if (!RawNightPolicy.usesRawNight(input)) {+ Log.debug(+ "Camera2RawNight",+ "RAW night skipped: ${RawNightPolicy.exclusionReason(input)}; " ++ "dngMissing=${DngMetadataAssembler.missingRequirements(snapshot)}",+ )+ return false+ }+ emitShutterFeedback()+ session.captureRawBurst(+ count = RawNightMerger.RAW_BURST_COUNT,+ callback = object : Camera2Session.RawBurstCallback {+ override fun onRawBurst(+ frames: List<com.vayunmathur.camera.platform.camera2.RawHeldFrame>,+ metas: List<com.vayunmathur.camera.platform.camera2.RingFrameMeta>,+ ) {+ viewModelScope.launch {+ val uri = withContext(Dispatchers.Default) {+ try {+ val merged = RawNightMerger.merge(+ frames, snapshot,+ previewMetadataFor = { session.previewMetadataFor(it) },+ )+ if (merged == null) {+ null+ } else {+ try {+ withContext(Dispatchers.IO) {+ saveProcessedStill(merged, 0)?.uri+ }+ } finally {+ merged.recycle()+ }+ }+ } finally {+ frames.forEach { runCatching { it.close() } }+ }+ }+ isCapturingMutable.value = false+ if (uri != null) {+ setLastCaptureUri(uri)+ stopLongExposureCountdown()+ } else {+ // RAW merge failed after claiming the shutter:+ // hand the shot back to the existing night paths.+ Log.status("Camera2RawNight", "RAW merge failed; falling back to YUV night")+ captureNightPhotoCustom()+ }+ }+ }++ override fun onRawBurstFailed(message: String) {+ Log.status("Camera2RawNight", "RAW burst failed: $message; falling back")+ isCapturingMutable.value = false+ captureNightPhotoCustom()+ }+ },+ )+ return true+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.ktindex 64faba781a..e18ab78eba 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraPhotoCapture.kt@@ -469,6 +469,10 @@ internal fun CameraViewModel.captureNightPhoto() { // the shot first (ExtensionsEnginePolicy). With the gate off (default) // this is one null/policy check and routing below is unchanged. if (tryCaptureCamera2NightExtension()) return+ // Depth Phase 2: explicitly-selected RAW night on the dual ring.+ // Gate-default-off; a policy miss returns false and routing below+ // (extension, then YUV burst) runs exactly as before.+ if (tryCaptureCamera2RawNight()) return viewModelScope.launch { if (nightExtensionUsableMutable.value) { captureNightPhotoExtension()
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 61feb08424..eebe37c3ab 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraViewModel.kt@@ -200,6 +200,20 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) { camera2NightEnabledMutable.value = enabled } + /**+ * Explicit RAW-night selection (depth Phase 2). Default OFF — this is+ * the user explicitly choosing the RAW burst; it is never inferred+ * from darkness. In-memory only; [com.vayunmathur.camera.platform.camera2.RawNightPolicy]+ * additionally requires the RAW gate, RAW support and a live RAW ring.+ */+ internal val camera2RawNightEnabledMutable = MutableStateFlow(false)+ val camera2RawNightEnabled = camera2RawNightEnabledMutable.asStateFlow()++ /** Turns the explicit RAW-night selection on/off (see RawNightPolicy). */+ fun setCamera2RawNightEnabled(enabled: Boolean) {+ camera2RawNightEnabledMutable.value = enabled+ }+ /** * The live Camera2 NIGHT extension session while one is bound * (Phase 6), registered by its owner; null otherwise. The night glue
camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.ktindex d01c9ea2f6..7204c8b023 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/NightCaptureEngine.kt@@ -132,6 +132,31 @@ object NightCaptureEngine { } } + /**+ * Applies the night brightening curve to an already-merged bitmap+ * (the RAW linear merge's tone-mapped output). Returns a new bitmap;+ * the caller owns both. This is the existing tone pipeline the RAW+ * path hands off to before `StillEncoder`.+ */+ fun applyNightTone(source: Bitmap): Bitmap {+ val w = source.width+ val h = source.height+ val px = IntArray(w * h)+ source.getPixels(px, 0, w, 0, 0, w, h)+ for (i in px.indices) {+ val p = px[i]+ val a = (p ushr ALPHA_SHIFT) and CHANNEL_MASK+ val r = (p shr RED_SHIFT) and CHANNEL_MASK+ val g = (p shr GREEN_SHIFT) and CHANNEL_MASK+ val b = p and CHANNEL_MASK+ px[i] = (a shl ALPHA_SHIFT) or+ (brightenChannel(r.toFloat()) shl RED_SHIFT) or+ (brightenChannel(g.toFloat()) shl GREEN_SHIFT) or+ brightenChannel(b.toFloat())+ }+ return createBitmap(w, h).apply { setPixels(px, 0, w, 0, 0, w, h) }+ }+ /** Lossless RGBA path -> Rust (no double JPEG), fallback to old JPEG path. */ private fun alignAndMergeNative(burst: List<Bitmap>): Bitmap? { if (!StitchNative.isAvailable) return null
camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.ktindex ccfe3b5867..6abd92024c 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/StitchNative.kt@@ -53,6 +53,28 @@ object StitchNative { /** Releases a night session (also cleans pano registry if mixed). */ external fun freeNight(handle: Long) + // --- RAW night path: packed Bayer frames, linear-light merge ---++ /** Opens a RAW night session holding packed Bayer frames. */+ external fun newRawNightSession(): Long++ /**+ * Adds one packed RAW frame. [format] is 10 for RAW10 (4 photosites per+ * 5 bytes) or 16 for RAW_SENSOR little-endian u16 samples. [cfa] mirrors+ * `SENSOR_INFO_COLOR_FILTER_ARRANGEMENT` (RGGB=0, GRBG=1, GBRG=2, BGGR=3).+ */+ external fun addRawFrame(+ handle: Long, bytes: ByteArray, width: Int, height: Int, format: Int,+ blackLevel: Float, whiteLevel: Float, cfa: Int,+ rGain: Float, gGain: Float, bGain: Float, exposureScale: Float,+ )++ /** Linear-merges the RAW session and returns tone-mapped JPEG bytes, or null. Consumes the session. */+ external fun mergeRawNight(handle: Long, exposureGain: Float): ByteArray?++ /** Releases a RAW night session. */+ external fun freeRawNight(handle: Long)+ /** * Encodes one RGBA frame (len = width*height*4) to AVIF bytes, or null on * failure. [quality] is 1..100, [speed] is rav1e's 1..10 (10 = fastest).
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 2aa869cf9c..30c413c907 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@@ -179,6 +179,9 @@ interface Camera2Driver { /** Creates the YUV ring output for [size]; null when unavailable. */ fun createRingOutput(size: FrameSize): RingOutput? = null++ /** Creates the RAW ring output for [size]/[format]; null when unavailable. */+ fun createRawRingOutput(size: FrameSize, format: RingFormat): RawRingOutput? = null } /** Converts a pure [SensorRect] into the HAL's `Rect`. */@@ -288,6 +291,11 @@ internal fun TotalCaptureResult.toRawStillMetadata(): RawStillMetadata = RawStil aeState = get(CaptureResult.CONTROL_AE_STATE), afState = get(CaptureResult.CONTROL_AF_STATE), flashState = get(CaptureResult.FLASH_STATE),+ colorCorrectionGains = runCatching {+ get(CaptureResult.COLOR_CORRECTION_GAINS)?.let { gains ->+ listOf(gains.red, gains.greenEven, gains.greenOdd, gains.blue)+ }+ }.getOrNull(), ) /**@@ -310,6 +318,11 @@ class AndroidCamera2Driver( override fun createRingOutput(size: FrameSize): RingOutput? = runCatching { YuvRingOutput(size.width, size.height, handler = handler) }.getOrNull() + override fun createRawRingOutput(size: FrameSize, format: RingFormat): RawRingOutput? =+ runCatching {+ RawImageReaderOutput(size.width, size.height, format, handler = handler)+ }.getOrNull()+ @SuppressLint("MissingPermission") override fun openCamera(cameraId: String, callback: DeviceCallback) { manager.openCamera(
camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/Camera2Session.ktindex 0f11166208..3ad0d9f3a5 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@@ -40,6 +40,7 @@ class Camera2Session( private val stateMachine: SessionStateMachine = SessionStateMachine(), private val listener: Listener? = null, private val ringConfig: ReprocessRingConfig = ReprocessRingConfig.DISABLED,+ private val rawRingConfig: RawRingConfig = RawRingConfig.DISABLED, ) { /** Session lifecycle notifications; all fire on the executor thread. */@@ -55,9 +56,21 @@ class Camera2Session( fun onStillFailed(message: String) } + /** RAW burst outcome; fires on the executor thread. Caller closes frames. */+ interface RawBurstCallback {+ fun onRawBurst(frames: List<RawHeldFrame>, metas: List<RingFrameMeta>)+ fun onRawBurstFailed(message: String)+ }+ val state: SessionState get() = stateMachine.state val generation: Long get() = stateMachine.generation + /** The facade snapshot this session was built with (RAW metadata source). */+ val characteristics: LensCharacteristicsSnapshot get() = snapshot++ /** Retained preview `CaptureResult` metadata for [timestampNs], or null. */+ fun previewMetadataFor(timestampNs: Long): RawStillMetadata? = previewMetas[timestampNs]+ private var device: DeviceHandle? = null private var captureSession: CaptureSessionHandle? = null private var previewSurface: Surface? = null@@ -67,6 +80,10 @@ class Camera2Session( private var ringOutput: RingOutput? = null private var ringSize: FrameSize? = null private val ring = ReprocessRing<RingHeldFrame>(ringConfig.capacity)+ private var rawRingOutput: RawRingOutput? = null+ private var rawRingSize: FrameSize? = null+ private var rawRingFormat: RingFormat? = null+ private val rawRing = ReprocessRing<RawHeldFrame>(rawRingConfig.capacity) private var latestPreviewTimestampNs: Long? = null private val previewMetas = LinkedHashMap<Long, RawStillMetadata>() private var pendingStill: PendingStill? = null@@ -224,6 +241,21 @@ class Camera2Session( /** Facade-reported YUV reprocess support for this lens. */ val reprocessSupported: Boolean get() = snapshot.supportsYuvRingReprocess + /** True when the RAW ring output is configured (see [RawNightPolicy]). */+ val hasRawRingOutput: Boolean get() = rawRingOutput != null++ /** The RAW ring size configured at [open], or null when unavailable. */+ fun currentRawRingSize(): FrameSize? = rawRingSize++ /** The RAW ring format configured at [open], or null when unavailable. */+ fun currentRawRingFormat(): RingFormat? = rawRingFormat++ /** Frames currently held in the RAW ring. */+ val rawRingFrameCount: Int get() = rawRing.size++ /** Facade-reported RAW ring support for this lens. */+ val rawSupported: Boolean get() = snapshot.supportsRawRing+ /** * Takes one still from the ring: picks the exposure-complete frame * nearest [shutterTimestampNs] (or the latest preview timestamp when@@ -323,6 +355,50 @@ class Camera2Session( } } + /**+ * Hands the newest [count] exposure-complete RAW ring frames (oldest+ * first, so frame 0 is the merge reference) to [callback]. The frames+ * are removed from the ring; the caller owns closing them. Fewer than+ * two frames is a failure — a one-frame "merge" would silently be a+ * single RAW shot, and the caller falls back to the YUV night path.+ */+ fun captureRawBurst(+ count: Int,+ callback: RawBurstCallback,+ shutterTimestampNs: Long? = null,+ ) {+ executor.execute {+ when {+ stateMachine.state != SessionState.STREAMING ->+ callback.onRawBurstFailed("RAW burst requires a streaming session")+ rawRingOutput == null ->+ callback.onRawBurstFailed("no RAW ring output on this session")+ else -> {+ val shutter = shutterTimestampNs+ ?: latestPreviewTimestampNs+ ?: rawRing.metas().maxOfOrNull { it.sensorTimestampNs }+ val burst = shutter?.let { rawRing.latestCompleteBurst(count, it) }+ .orEmpty()+ if (burst.size < 2) {+ callback.onRawBurstFailed(+ "RAW ring holds ${burst.size} complete frames, need 2+",+ )+ return@execute+ }+ val frames = burst.mapNotNull { (frame, meta) ->+ rawRing.remove(meta.sensorTimestampNs)?.let { frame }+ }+ if (frames.size < 2) {+ frames.forEach { runCatching { it.close() } }+ callback.onRawBurstFailed("RAW ring frames vanished during burst selection")+ return@execute+ }+ callback.onRawBurst(frames, burst.map { it.second })+ }+ }+ }+ }+ /** * Takes one plain still: issues `TEMPLATE_STILL_CAPTURE` carrying the * session's current control state plus flash resolution, and delivers@@ -409,6 +485,23 @@ class Camera2Session( } } + private fun onRawRingFrame(frame: RawHeldFrame) {+ try {+ executor.execute {+ val evicted = rawRing.offer(frame.meta, frame)+ evicted?.close()+ previewMetas[frame.meta.sensorTimestampNs]?.let { raw ->+ rawRing.attachMetadata(+ frame.meta.sensorTimestampNs, raw.exposureTimeNs,+ raw.frameNumber, raw.aeState, raw.iso,+ )+ }+ }+ } catch (e: java.util.concurrent.RejectedExecutionException) {+ frame.close()+ }+ }+ private fun onPreviewResult(raw: RawStillMetadata) { val timestamp = raw.sensorTimestampNs ?: return latestPreviewTimestampNs = timestamp@@ -417,6 +510,7 @@ class Camera2Session( previewMetas.remove(previewMetas.keys.first()) } ring.attachMetadata(timestamp, raw.exposureTimeNs, raw.frameNumber, raw.aeState, raw.iso)+ rawRing.attachMetadata(timestamp, raw.exposureTimeNs, raw.frameNumber, raw.aeState, raw.iso) } private fun onStillResult(pending: PendingStill, metadata: RawStillMetadata) {@@ -498,6 +592,11 @@ class Camera2Session( ringOutput = null ringSize = null ring.drainAll().forEach { runCatching { it.close() } }+ runCatching { rawRingOutput?.close() }+ rawRingOutput = null+ rawRingSize = null+ rawRingFormat = null+ rawRing.drainAll().forEach { runCatching { it.close() } } previewMetas.clear() runCatching { device?.close() } device = null@@ -517,7 +616,7 @@ class Camera2Session( val surface = previewSurface ?: return if (stateMachine.state != SessionState.STREAMING) return val params = Camera2Controls.resolve(controls, snapshot)- val targets = listOfNotNull(surface, ringOutput?.surface)+ val targets = listOfNotNull(surface, ringOutput?.surface, rawRingOutput?.surface) runCatching { session.setRepeatingStreaming(params, targets, PreviewResultCallback { raw -> try {@@ -560,7 +659,30 @@ class Camera2Session( } ringOutput = createdRing ringSize = if (createdRing != null) selectedRingSize else null- val surfaces = listOfNotNull(surface, output?.surface, createdRing?.surface)+ // Fourth output: the RAW ring, only when built with it enabled and+ // the facade proves RAW. RAW stream combos vary wildly per HAL, so+ // failure degrades to no RAW ring (policy excludes the RAW path).+ val selectedRawSize = if (rawRingConfig.enabled) {+ StreamSelection.selectRawRingSize(snapshot)+ } else {+ null+ }+ val selectedRawFormat = snapshot.rawRingFormat+ val createdRawRing = if (selectedRawSize != null && selectedRawFormat != null) {+ runCatching {+ driver.createRawRingOutput(selectedRawSize, selectedRawFormat)+ }.getOrNull()?.also { created ->+ created.setListener(RawRingFrameListener { frame -> onRawRingFrame(frame) })+ }+ } else {+ null+ }+ rawRingOutput = createdRawRing+ rawRingSize = if (createdRawRing != null) selectedRawSize else null+ rawRingFormat = if (createdRawRing != null) selectedRawFormat else null+ val surfaces = listOfNotNull(+ surface, output?.surface, createdRing?.surface, createdRawRing?.surface,+ ) val callback = SessionCallbackImpl(gen) runCatching { if (createdRing != null && snapshot.supportsYuvRingReprocess) {
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 aae7fc1d92..29361be42b 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@@ -165,6 +165,22 @@ data class LensCharacteristicsSnapshot( * omit it — reprocess support then falls back to the capability bit). */ val reprocessInputSizesByFormat: Map<Int, List<Size>> = emptyMap(),+ /** `SENSOR_BLACK_LEVEL_PATTERN` (4 values, 2x2 cell order); empty when unread. */+ val rawBlackLevelPattern: List<Int> = emptyList(),+ /** `SENSOR_INFO_WHITE_LEVEL`; null when unread (RAW linearisation impossible). */+ val rawWhiteLevel: Int? = null,+ /** `SENSOR_COLOR_TRANSFORM1/2` as row-major 3x3 floats; empty when unread. */+ val rawColorTransform1: List<Float> = emptyList(),+ val rawColorTransform2: List<Float> = emptyList(),+ /** `SENSOR_CALIBRATION_TRANSFORM1/2` as row-major 3x3 floats. */+ val rawCalibrationTransform1: List<Float> = emptyList(),+ val rawCalibrationTransform2: List<Float> = emptyList(),+ /** `SENSOR_FORWARD_MATRIX1/2` as row-major 3x3 floats. */+ val rawForwardMatrix1: List<Float> = emptyList(),+ val rawForwardMatrix2: List<Float> = emptyList(),+ /** `SENSOR_REFERENCE_ILLUMINANT1/2` (`CameraMetadata` illuminant codes). */+ val rawReferenceIlluminant1: Int? = null,+ val rawReferenceIlluminant2: Int? = null, ) { val lensFacing: LensFacing? = when (lensFacingRaw) { CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK@@ -209,6 +225,20 @@ data class LensCharacteristicsSnapshot( /** True when the YUV ring can honestly reprocess on this lens. */ val supportsYuvRingReprocess: Boolean get() = reprocessInputFormat == ImageFormat.YUV_420_888+ /**+ * The RAW stream format this lens can feed a RAW ring with, or null:+ * RAW_SENSOR (unpacked u16) is preferred over RAW10 (packed) because+ * its layout is stride-trivial; both require the RAW capability —+ * a stream size alone never proves RAW support.+ */+ val rawRingFormat: RingFormat?+ get() = when {+ !supportsRaw -> null+ streamConfig.sizesFor(ImageFormat.RAW_SENSOR).isNotEmpty() -> RingFormat.RAW_SENSOR+ streamConfig.sizesFor(ImageFormat.RAW10).isNotEmpty() -> RingFormat.RAW10+ else -> null+ }+ val supportsRawRing: Boolean get() = rawRingFormat != null val supportsManualSensor: Boolean get() = CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR in availableCapabilities /** True when the HAL offers `CONSTRAINED_HIGH_SPEED_VIDEO` (Phase 5). */@@ -269,6 +299,16 @@ class CharacteristicsFacade private constructor( highSpeedFpsRangesBySize: Map<Size, List<Range<Int>>> = emptyMap(), extensionSupport: Map<Int, ExtensionModeSupport> = emptyMap(), reprocessInputSizesByFormat: Map<Int, List<Size>> = emptyMap(),+ rawBlackLevelPattern: List<Int> = emptyList(),+ rawWhiteLevel: Int? = null,+ rawColorTransform1: List<Float> = emptyList(),+ rawColorTransform2: List<Float> = emptyList(),+ rawCalibrationTransform1: List<Float> = emptyList(),+ rawCalibrationTransform2: List<Float> = emptyList(),+ rawForwardMatrix1: List<Float> = emptyList(),+ rawForwardMatrix2: List<Float> = emptyList(),+ rawReferenceIlluminant1: Int? = null,+ rawReferenceIlluminant2: Int? = null, ): CharacteristicsFacade = fromSnapshot( LensCharacteristicsSnapshot( cameraId = cameraId,@@ -301,6 +341,16 @@ class CharacteristicsFacade private constructor( highSpeedFpsRangesBySize = highSpeedFpsRangesBySize, extensionSupport = extensionSupport, reprocessInputSizesByFormat = reprocessInputSizesByFormat,+ rawBlackLevelPattern = rawBlackLevelPattern,+ rawWhiteLevel = rawWhiteLevel,+ rawColorTransform1 = rawColorTransform1,+ rawColorTransform2 = rawColorTransform2,+ rawCalibrationTransform1 = rawCalibrationTransform1,+ rawCalibrationTransform2 = rawCalibrationTransform2,+ rawForwardMatrix1 = rawForwardMatrix1,+ rawForwardMatrix2 = rawForwardMatrix2,+ rawReferenceIlluminant1 = rawReferenceIlluminant1,+ rawReferenceIlluminant2 = rawReferenceIlluminant2, ), ) @@ -394,10 +444,44 @@ class CharacteristicsFacade private constructor( highSpeedFpsRangesBySize = highSpeedRanges, extensionSupport = extensionSupport, reprocessInputSizesByFormat = reprocessInputSizes,+ rawBlackLevelPattern =+ get(CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN)?.let { pattern ->+ runCatching {+ IntArray(4).also { pattern.copyTo(it, 0) }.toList()+ }.getOrDefault(emptyList())+ }.orEmpty(),+ rawWhiteLevel = get(CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL),+ rawColorTransform1 =+ get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1).toFloatList(),+ rawColorTransform2 =+ get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM2).toFloatList(),+ rawCalibrationTransform1 =+ get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM1).toFloatList(),+ rawCalibrationTransform2 =+ get(CameraCharacteristics.SENSOR_CALIBRATION_TRANSFORM2).toFloatList(),+ rawForwardMatrix1 =+ get(CameraCharacteristics.SENSOR_FORWARD_MATRIX1).toFloatList(),+ rawForwardMatrix2 =+ get(CameraCharacteristics.SENSOR_FORWARD_MATRIX2).toFloatList(),+ rawReferenceIlluminant1 =+ get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1)?.let { it.toInt() },+ rawReferenceIlluminant2 =+ get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)?.let { it.toInt() }, ), ) } + /** Row-major 3x3 floats from a `ColorSpaceTransform`, empty when unread. */+ private fun android.hardware.camera2.params.ColorSpaceTransform?.toFloatList():+ List<Float> {+ val transform = this ?: return emptyList()+ return runCatching {+ (0 until 3).flatMap { row ->+ (0 until 3).map { col -> transform.getElement(col, row).toFloat() }+ }+ }.getOrDefault(emptyList())+ }+ /** * Full entry point: characteristics + extension availability for [cameraId]. * Extension probing (`getCameraExtensionCharacteristics`, API 31+) degrades
camera/src/main/java/com/vayunmathur/camera/platform/camera2/DngMetadata.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/DngMetadata.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/DngMetadata.ktnew file mode 100644index 0000000000..c1828cb79a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/DngMetadata.kt@@ -0,0 +1,84 @@+package com.vayunmathur.camera.platform.camera2++/**+ * Camera2 depth Phase 2: DNG sidecar metadata assembly — the pure half.+ *+ * A DNG is only honest when every sensor field `DngCreator` would embed+ * is actually known: black-level pattern, white level, CFA arrangement,+ * both colour/calibration/forward matrix pairs and their illuminants,+ * plus a RAW stream to write. [DngMetadataAssembler] assembles exactly+ * that from the facade snapshot and names every missing piece; the night+ * RAW path never writes a DNG when this returns null.+ *+ * Deliberate gap (reported, not papered over): even a complete+ * [DngSensorMetadata] is not a DNG. `android.hardware.camera2.DngCreator`+ * additionally requires the live `CameraCharacteristics` and the frame's+ * live `TotalCaptureResult` objects. The ring deliberately retains only+ * pure data ([RingFrameMeta] / [RawStillMetadata]) so sessions stay+ * fakeable in tests, so no DNG writer is wired in this phase and no+ * RAW photo-format setting is offered. Wiring one means retaining live+ * results beside RAW ring frames in the driver — a Phase-3 decision.+ */+data class DngSensorMetadata(+ val blackLevelPattern: List<Int>,+ val whiteLevel: Int,+ val colorFilterArrangement: Int,+ val colorTransform1: List<Float>,+ val colorTransform2: List<Float>,+ val calibrationTransform1: List<Float>,+ val calibrationTransform2: List<Float>,+ val forwardMatrix1: List<Float>,+ val forwardMatrix2: List<Float>,+ val referenceIlluminant1: Int,+ val referenceIlluminant2: Int?,+ val activeArrayWidth: Int,+ val activeArrayHeight: Int,+)++object DngMetadataAssembler {++ /** Why a DNG cannot be written for [snapshot], empty when it can (metadata-wise). */+ fun missingRequirements(snapshot: LensCharacteristicsSnapshot): List<String> = buildList {+ if (!snapshot.supportsRaw) add("RAW capability not reported")+ if (snapshot.rawRingFormat == null) add("no RAW_SENSOR/RAW10 stream size")+ if (snapshot.rawBlackLevelPattern.size != 4) add("SENSOR_BLACK_LEVEL_PATTERN missing or not 4 values")+ val white = snapshot.rawWhiteLevel+ if (white == null || white <= 0) add("SENSOR_INFO_WHITE_LEVEL missing")+ if (snapshot.colorFilterArrangement == null) add("SENSOR_INFO_COLOR_FILTER_ARRANGEMENT missing")+ if (snapshot.rawColorTransform1.size != 9) add("SENSOR_COLOR_TRANSFORM1 missing")+ if (snapshot.rawColorTransform2.size != 9) add("SENSOR_COLOR_TRANSFORM2 missing")+ if (snapshot.rawCalibrationTransform1.size != 9) add("SENSOR_CALIBRATION_TRANSFORM1 missing")+ if (snapshot.rawCalibrationTransform2.size != 9) add("SENSOR_CALIBRATION_TRANSFORM2 missing")+ if (snapshot.rawForwardMatrix1.size != 9) add("SENSOR_FORWARD_MATRIX1 missing")+ if (snapshot.rawForwardMatrix2.size != 9) add("SENSOR_FORWARD_MATRIX2 missing")+ if (snapshot.rawReferenceIlluminant1 == null) add("SENSOR_REFERENCE_ILLUMINANT1 missing")+ if (snapshot.activeArrayWidth <= 0 || snapshot.activeArrayHeight <= 0) {+ add("SENSOR_INFO_ACTIVE_ARRAY_SIZE missing")+ }+ // Illuminant 2 / second matrices are only meaningful as a pair:+ // a present transform2 with no illuminant2 is a half-known DNG.+ if (snapshot.rawColorTransform2.size == 9 && snapshot.rawReferenceIlluminant2 == null) {+ add("SENSOR_REFERENCE_ILLUMINANT2 missing for second colour transform")+ }+ }++ /** Assembled metadata, or null when [missingRequirements] is non-empty. */+ fun assemble(snapshot: LensCharacteristicsSnapshot): DngSensorMetadata? {+ if (missingRequirements(snapshot).isNotEmpty()) return null+ return DngSensorMetadata(+ blackLevelPattern = snapshot.rawBlackLevelPattern,+ whiteLevel = snapshot.rawWhiteLevel!!,+ colorFilterArrangement = snapshot.colorFilterArrangement!!,+ colorTransform1 = snapshot.rawColorTransform1,+ colorTransform2 = snapshot.rawColorTransform2,+ calibrationTransform1 = snapshot.rawCalibrationTransform1,+ calibrationTransform2 = snapshot.rawCalibrationTransform2,+ forwardMatrix1 = snapshot.rawForwardMatrix1,+ forwardMatrix2 = snapshot.rawForwardMatrix2,+ referenceIlluminant1 = snapshot.rawReferenceIlluminant1!!,+ referenceIlluminant2 = snapshot.rawReferenceIlluminant2,+ activeArrayWidth = snapshot.activeArrayWidth,+ activeArrayHeight = snapshot.activeArrayHeight,+ )+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/NightRawPolicy.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/NightRawPolicy.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/NightRawPolicy.ktnew file mode 100644index 0000000000..f89db31040--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/NightRawPolicy.kt@@ -0,0 +1,47 @@+package com.vayunmathur.camera.platform.camera2++import com.vayunmathur.camera.platform.CameraMode++/** Inputs to the RAW-night selection rule. */+data class RawNightInput(+ /** Compile-time [RawRingGate] AND the runtime explicit RAW selection. */+ val rawGateOn: Boolean,+ /** The user explicitly selected RAW night (never inferred from "it's dark"). */+ val explicitRawSelected: Boolean,+ val mode: CameraMode,+ /** This shutter is the night route (auto night / night mode), not plain PHOTO. */+ val nightRoute: Boolean,+ /** Facade reports the RAW capability plus a RAW stream size. */+ val rawSupported: Boolean,+ /** A RAW ring output is configured and holding frames on the session. */+ val hasRawRingOutput: Boolean,+ /** DNG metadata assembled completely (see [DngMetadataAssembler]). */+ val dngMetadataComplete: Boolean = false,+)++/**+ * Explicit selection rule for the RAW night merge (depth Phase 2).+ *+ * RAW is never the silent default: it takes a night shutter only when the+ * gate is on, the user explicitly selected RAW night, the facade proves+ * RAW support, and a RAW ring is live. Everything else stays on the+ * existing night routing (vendor extension, then the YUV burst) exactly+ * as before. [RawNightInput.dngMetadataComplete] gates nothing here —+ * it is carried so the report/UI can state whether a DNG sidecar could+ * even be assembled; this phase writes none (see `DngMetadata.kt`).+ */+object RawNightPolicy {++ fun usesRawNight(input: RawNightInput): Boolean = exclusionReason(input) == null++ /** Why [input] cannot use the RAW night merge, or null when it can. */+ fun exclusionReason(input: RawNightInput): String? = when {+ !input.rawGateOn -> "raw ring gate off"+ !input.explicitRawSelected -> "RAW night not explicitly selected"+ !input.nightRoute -> "not a night capture"+ input.mode != CameraMode.PHOTO -> "mode ${input.mode} is not PHOTO"+ !input.rawSupported -> "RAW not supported for this lens"+ !input.hasRawRingOutput -> "no RAW ring output on the Camera2 session"+ else -> null+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawNightMerger.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawNightMerger.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawNightMerger.ktnew file mode 100644index 0000000000..2c423bf95a--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawNightMerger.kt@@ -0,0 +1,114 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import com.vayunmathur.camera.platform.NightCaptureEngine+import com.vayunmathur.camera.platform.StitchNative+import com.vayunmathur.library.log.Log++/**+ * Camera2 depth Phase 2: Kotlin side of the RAW night merge. Copies each+ * held RAW frame's plane (tightening row stride first — Rust unpackers+ * assume tight rows), feeds the packed bytes plus the facade's black /+ * white level, CFA and the frame's white-balance gains to the Rust+ * linear merge, then hands the tone-mapped JPEG through the existing+ * night tone curve. Returns null on any gap so the caller falls back to+ * the YUV night path — a RAW failure never loses the shutter.+ */+object RawNightMerger {++ /** RAW frames in one night burst (matches the YUV burst count). */+ const val RAW_BURST_COUNT: Int = 6++ fun merge(+ frames: List<RawHeldFrame>,+ snapshot: LensCharacteristicsSnapshot,+ previewMetadataFor: (Long) -> RawStillMetadata?,+ ): Bitmap? {+ if (!StitchNative.isAvailable || frames.size < 2) return null+ val white = snapshot.rawWhiteLevel?.toFloat() ?: run {+ Log.status("RawNight", "no white level; RAW merge unavailable")+ return null+ }+ val black = snapshot.rawBlackLevelPattern+ .takeIf { it.size == 4 }?.average()?.toFloat() ?: run {+ Log.status("RawNight", "no black level pattern; RAW merge unavailable")+ return null+ }+ val cfa = snapshot.colorFilterArrangement ?: run {+ Log.status("RawNight", "no CFA arrangement; RAW merge unavailable")+ return null+ }+ val refMeta = frames.first().meta+ val refExposure = exposureProduct(refMeta, previewMetadataFor(refMeta.sensorTimestampNs))+ val handle = StitchNative.newRawNightSession()+ if (handle == 0L) return null+ try {+ for (frame in frames) {+ val rawMeta = previewMetadataFor(frame.meta.sensorTimestampNs)+ val gains = rawMeta?.colorCorrectionGains+ val exposure = exposureProduct(frame.meta, rawMeta)+ val bytes = tightRows(frame) ?: continue+ StitchNative.addRawFrame(+ handle, bytes, frame.meta.width, frame.meta.height,+ frame.format.rawBitDepth(),+ black, white, cfa,+ gains?.getOrNull(0) ?: 1f,+ gains?.let {+ val g0 = it.getOrNull(1) ?: 1f+ val g1 = it.getOrNull(2) ?: g0+ (g0 + g1) * 0.5f+ } ?: 1f,+ gains?.getOrNull(3) ?: 1f,+ if (refExposure > 0 && exposure > 0) {+ (exposure / refExposure).toFloat()+ } else {+ 1f+ },+ )+ }+ val jpeg = StitchNative.mergeRawNight(handle, 1.0f) ?: return null+ val bitmap = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size) ?: return null+ val toned = NightCaptureEngine.applyNightTone(bitmap)+ if (toned !== bitmap) bitmap.recycle()+ return toned+ } catch (e: UnsatisfiedLinkError) {+ Log.status("RawNight", "native RAW merge unavailable; falling back", e)+ return null+ } finally {+ try {+ StitchNative.freeRawNight(handle)+ } catch (e: UnsatisfiedLinkError) {+ Log.status("RawNight", "freeRawNight failed", e)+ }+ }+ }++ private fun exposureProduct(meta: RingFrameMeta, raw: RawStillMetadata?): Double {+ val exposureNs = meta.exposureTimeNs ?: raw?.exposureTimeNs ?: return 0.0+ val iso = meta.iso ?: raw?.iso ?: return 0.0+ return exposureNs.toDouble() * iso.toDouble()+ }++ /** Strips row-stride padding so Rust sees tight RAW rows. */+ private fun tightRows(frame: RawHeldFrame): ByteArray? {+ val bytes = frame.copyRawBytes() ?: return null+ val width = frame.meta.width+ val height = frame.meta.height+ if (width <= 0 || height <= 0) return null+ val tightRow = when (frame.format) {+ RingFormat.RAW10 -> width / 4 * 5+ else -> width * 2+ }+ val stride = frame.rowStrideBytes+ if (stride <= tightRow || stride == 0) {+ return if (bytes.size >= tightRow * height) bytes.copyOf(tightRow * height) else null+ }+ if (bytes.size < stride * height) return null+ val out = ByteArray(tightRow * height)+ for (row in 0 until height) {+ bytes.copyInto(out, row * tightRow, row * stride, row * stride + tightRow)+ }+ return out+ }+}
camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawRingSource.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawRingSource.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawRingSource.ktnew file mode 100644index 0000000000..713bdb7cb2--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/RawRingSource.kt@@ -0,0 +1,180 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.media.Image+import android.media.ImageReader+import android.os.Handler+import android.view.Surface+import com.vayunmathur.library.log.Log++/** Delivers one held RAW ring frame; fires on the reader handler thread. */+fun interface RawRingFrameListener {+ fun onRawRingFrame(frame: RawHeldFrame)+}++/** Maps a ring format to its `ImageFormat` stream format. */+fun RingFormat.toImageFormat(): Int = when (this) {+ RingFormat.YUV_420_888 -> ImageFormat.YUV_420_888+ RingFormat.PRIVATE -> ImageFormat.PRIVATE+ RingFormat.RAW10 -> ImageFormat.RAW10+ RingFormat.RAW_SENSOR -> ImageFormat.RAW_SENSOR+}++/** Bit depth a [RawHeldFrame.copyRawBytes] payload carries to Rust. */+fun RingFormat.rawBitDepth(): Int = when (this) {+ RingFormat.RAW10 -> 10+ else -> 16+}++/**+ * One RAW frame held by the RAW [ReprocessRing]. The owner must [close]+ * it: an unclosed image exhausts the reader pool and stalls the stream.+ * [copyRawBytes] copies the single plane out (RAW is one plane) and is+ * valid until [close]; the copy, not the image, crosses into Rust.+ */+interface RawHeldFrame : AutoCloseable {+ val meta: RingFrameMeta+ val format: RingFormat++ /** Packed plane bytes (RAW10 packed, or RAW_SENSOR u16 LE rows incl. row-stride padding), or null. */+ fun copyRawBytes(): ByteArray?++ /** Row stride of the copied plane in bytes (Rust unpack assumes tight rows; see glue). */+ val rowStrideBytes: Int get() = 0++ override fun close()+}++/** Testable handle over the ring's RAW `ImageReader` (real driver below). */+interface RawRingOutput : AutoCloseable {+ val surface: Surface+ fun setListener(listener: RawRingFrameListener?)+ override fun close()+}++/** [RawHeldFrame] over a real Camera2 RAW [Image]. */+class ImageRawHeldFrame(+ private val image: Image,+ override val format: RingFormat,+) : RawHeldFrame {+ override val meta: RingFrameMeta = RingFrameMeta(+ sensorTimestampNs = image.timestamp,+ width = image.width,+ height = image.height,+ format = format,+ )++ override val rowStrideBytes: Int+ get() = try {+ image.planes.firstOrNull()?.rowStride ?: 0+ } catch (e: IllegalStateException) {+ 0+ }++ @Volatile+ private var closed = false++ override fun copyRawBytes(): ByteArray? {+ if (closed) return null+ return try {+ val plane = image.planes.firstOrNull() ?: return null+ val buffer = plane.buffer.duplicate()+ ByteArray(buffer.remaining()).also { buffer.get(it) }+ } catch (e: IllegalStateException) {+ Log.error("RawRingSource", "RAW plane copy failed", e)+ null+ } catch (e: IllegalArgumentException) {+ Log.error("RawRingSource", "RAW plane copy failed", e)+ null+ }+ }++ override fun close() {+ if (closed) return+ closed = true+ try {+ image.close()+ } catch (e: IllegalStateException) {+ Log.error("RawRingSource", "RAW image close threw", e)+ }+ }+}++/**+ * RAW `ImageReader` ring source. Mirrors [YuvRingOutput]: `acquireLatest`+ * semantics, every acquired image becomes a [RawHeldFrame] the session's+ * RAW [ReprocessRing] evicts/closes. RAW stream combinations vary wildly+ * per HAL, so construction failure is expected on many devices and the+ * driver degrades to no RAW ring (policy then excludes the RAW path).+ *+ * Ownership: whoever constructs this owns it and must call [close].+ */+class RawImageReaderOutput(+ width: Int,+ height: Int,+ private val format: RingFormat,+ maxImages: Int = RawRingConfig.DEFAULT_CAPACITY,+ private val handler: Handler,+) : RawRingOutput {++ private val reader: ImageReader =+ ImageReader.newInstance(width, height, format.toImageFormat(), maxImages)++ override val surface: Surface get() = reader.surface++ @Volatile+ private var listener: RawRingFrameListener? = null++ init {+ reader.setOnImageAvailableListener({ onImageAvailable() }, handler)+ }++ override fun setListener(listener: RawRingFrameListener?) {+ this.listener = listener+ }++ private fun onImageAvailable() {+ val image = try {+ reader.acquireLatestImage()+ } catch (e: IllegalStateException) {+ Log.error("RawRingSource", "acquireLatestImage threw", e)+ null+ } ?: return+ val frame = ImageRawHeldFrame(image, format)+ val current = listener+ if (current == null) {+ frame.close()+ return+ }+ current.onRawRingFrame(frame)+ }++ override fun close() {+ try {+ reader.setOnImageAvailableListener(null, null)+ } catch (e: IllegalStateException) {+ Log.error("RawRingSource", "clearing listener threw", e)+ }+ reader.close()+ }+}++/** Gate for the RAW night path. Default OFF, mirroring [ReprocessRingGate]. */+object RawRingGate {+ const val ENABLED: Boolean = false+}++/** What the RAW half of the dual ring holds. */+data class RawRingConfig(+ val enabled: Boolean = false,+ val capacity: Int = DEFAULT_CAPACITY,+) {+ init {+ require(capacity > 0) { "raw ring capacity must be positive" }+ }++ companion object {+ const val DEFAULT_CAPACITY: Int = 6+ val DISABLED = RawRingConfig(enabled = false)+ }+}
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.ktindex ea54a6a111..150e1c9d4f 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/ReprocessRing.kt@@ -13,9 +13,9 @@ import android.hardware.camera2.CameraMetadata * 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.+ * A second [ReprocessRing] of RAW frames (depth Phase 2, `RawRingSource.kt`)+ * now sits beside this one: the rings share this eviction/selection math+ * unchanged, one instance per format, selected by `RawNightPolicy`. */ /** Gate for the ring path. Default OFF, mirroring [NightCamera2Gate]. */@@ -198,6 +198,20 @@ class ReprocessRing<T>( ) } + /**+ * The newest [count] exposure-complete frames ending at or before+ * [atNs], oldest first (burst order for the RAW night merge, whose+ * first frame is the alignment reference). Fewer than [count] when+ * the ring holds fewer complete frames; never a still-exposing one.+ */+ fun latestCompleteBurst(count: Int, atNs: Long): List<Pair<T, RingFrameMeta>> {+ if (count <= 0) return emptyList()+ return entries.filter { it.meta.isExposureComplete(atNs) }+ .sortedBy { it.meta.sensorTimestampNs }+ .takeLast(count)+ .map { it.payload to it.meta }+ }+ /** Latest fully-exposed frame at [atNs], or null (the select fallback). */ fun latestComplete(atNs: Long): Pair<T, RingFrameMeta>? = entries.filter { it.meta.isExposureComplete(atNs) }
camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.ktindex 73f7146e61..8c853c9255 100644--- a/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/platform/camera2/StillCapture.kt@@ -31,6 +31,8 @@ data class RawStillMetadata( val aeState: Int? = null, val afState: Int? = null, val flashState: Int? = null,+ /** `COLOR_CORRECTION_GAINS` (R, G-even, G-odd, B) for RAW linearisation. */+ val colorCorrectionGains: List<Float>? = null, ) /**
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 45a593e010..99b686f422 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@@ -43,6 +43,9 @@ object StreamSelection { /** Aspect ratios within this absolute tolerance count as the same shape. */ const val ASPECT_TOLERANCE = 0.02f + /** Pixel cap for the RAW ring stream (see [selectRawRingSize]). */+ const val MAX_RAW_RING_PIXELS: Long = 12_000_000L+ /** * Supported preview sizes for a TextureView surface, in facade order: * the explicit `SurfaceTexture` list when the HAL reported one, else the@@ -147,6 +150,30 @@ object StreamSelection { return pool.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height })) } + /** Supported RAW sizes for the facade's RAW ring format (empty = no RAW ring). */+ fun supportedRawSizes(snapshot: LensCharacteristicsSnapshot): List<FrameSize> {+ val format = snapshot.rawRingFormat?.toImageFormat() ?: return emptyList()+ return snapshot.streamConfig.sizesFor(format).map { FrameSize.from(it) }.distinct()+ }++ /**+ * The RAW ring size: the largest advertised RAW size, capped at+ * [MAX_RAW_RING_PIXELS] — a full-sensor RAW ring at 8+ frames is a+ * memory and HAL-bandwidth liability the night burst does not need,+ * so the largest size at or under the cap wins, else the smallest+ * over it. Null when the lens reports no RAW sizes.+ */+ fun selectRawRingSize(snapshot: LensCharacteristicsSnapshot): FrameSize? {+ val raw = supportedRawSizes(snapshot)+ if (raw.isEmpty()) return null+ val underCap = raw.filter { it.area.toLong() <= MAX_RAW_RING_PIXELS }+ return if (underCap.isNotEmpty()) {+ underCap.maxWithOrNull(compareBy({ it.area }, { it.width }, { it.height }))+ } else {+ raw.minWithOrNull(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/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 2955d41f94..30d5b8bf8b 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.RawRingConfig+import com.vayunmathur.camera.platform.camera2.RawRingGate import com.vayunmathur.camera.platform.camera2.ReprocessRingConfig import com.vayunmathur.camera.platform.camera2.ReprocessRingGate import com.vayunmathur.camera.platform.camera2.PreviewSurfaceEvent@@ -106,6 +108,7 @@ private class Camera2PreviewSession(context: Context, private val cameraId: Stri executor = executor, snapshot = facade.snapshot, ringConfig = ReprocessRingConfig(enabled = ReprocessRingGate.ENABLED),+ rawRingConfig = RawRingConfig(enabled = RawRingGate.ENABLED), listener = object : Camera2Session.Listener { override fun onError(message: String) { Log.status("Camera2Preview", message)
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex 206e54f857..0b1313a7e0 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -19,6 +19,9 @@ mod seam; mod blend; mod stitch; mod night;+mod raw_night;+#[allow(dead_code)]+mod raw_jni; mod avif; mod luma; @@ -43,6 +46,11 @@ fn night_registry() -> &'static Mutex<HashMap<i64, Vec<Rgba>>> { NREG.get_or_init(|| Mutex::new(HashMap::new())) } +fn raw_night_registry() -> &'static Mutex<HashMap<i64, Vec<raw_night::RawFrame>>> {+ static RREG: OnceLock<Mutex<HashMap<i64, Vec<raw_night::RawFrame>>>> = OnceLock::new();+ RREG.get_or_init(|| Mutex::new(HashMap::new()))+}+ fn next_handle() -> i64 { static CTR: OnceLock<Mutex<i64>> = OnceLock::new(); let m = CTR.get_or_init(|| Mutex::new(1));
camera/src/main/rust/src/raw_jni.rs
diff --git a/camera/src/main/rust/src/raw_jni.rs b/camera/src/main/rust/src/raw_jni.rsnew file mode 100644index 0000000000..62d67ee9ec--- /dev/null+++ b/camera/src/main/rust/src/raw_jni.rs@@ -0,0 +1,108 @@+//! JNI bindings for the RAW night session (split from `lib.rs` for the+//! 500-line Rust file cap). Symbols are `#[no_mangle]` and named for+//! `StitchNative` exactly as the other night bindings in `lib.rs`.++use crate::{encode_jpeg, next_handle, raw_night, raw_night_registry};+use jni::objects::{JByteArray, JClass};+use jni::sys::{jbyteArray, jfloat, jint, jlong};+use jni::EnvUnowned;++// --- RAW night path: packed Bayer frames, linear merge ---++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_newRawNightSession<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jlong {+ let h = next_handle();+ raw_night_registry().lock().unwrap().insert(h, Vec::new());+ h+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_addRawFrame<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+ bytes: JByteArray<'l>,+ width: jint,+ height: jint,+ format: jint,+ black_level: jfloat,+ white_level: jfloat,+ cfa: jint,+ r_gain: jfloat,+ g_gain: jfloat,+ b_gain: jfloat,+ exposure_scale: jfloat,+) {+ env.with_env(|env| -> jni::errors::Result<()> {+ let (w, h) = (width as usize, height as usize);+ if w == 0 || h == 0 || w > 20000 || h > 20000 {+ return Ok(());+ }+ let data = match env.convert_byte_array(&bytes) {+ Ok(b) => b,+ Err(_) => return Ok(()),+ };+ let samples = match format {+ 10 => raw_night::unpack_raw10(&data, w, h),+ _ => raw_night::unpack_raw16(&data, w, h),+ };+ let (Some(samples), Some(cfa)) = (samples, raw_night::Cfa::from_code(cfa)) else {+ return Ok(());+ };+ let frame = raw_night::RawFrame {+ w,+ h,+ samples,+ meta: raw_night::RawMeta {+ black_levels: [black_level; 4],+ white_level,+ cfa,+ gains: [r_gain, g_gain, b_gain],+ exposure_scale,+ },+ };+ if let Some(v) = raw_night_registry().lock().unwrap().get_mut(&handle) {+ v.push(frame);+ }+ Ok(())+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_mergeRawNight<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+ exposure_gain: jfloat,+) -> jbyteArray {+ env.with_env(|env| -> jni::errors::Result<jbyteArray> {+ let null = std::ptr::null_mut();+ let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let frames = raw_night_registry().lock().unwrap().remove(&handle)?;+ raw_night::merge_raw_burst(&frames, exposure_gain)+ .and_then(|img| encode_jpeg(&img, 95))+ }))+ .unwrap_or(None);+ match bytes {+ Some(b) => match env.byte_array_from_slice(&b) {+ Ok(arr) => Ok(arr.into_raw()),+ Err(_) => Ok(null),+ },+ None => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_camera_platform_StitchNative_freeRawNight<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ raw_night_registry().lock().unwrap().remove(&handle);+}
camera/src/main/rust/src/raw_night.rs
diff --git a/camera/src/main/rust/src/raw_night.rs b/camera/src/main/rust/src/raw_night.rsnew file mode 100644index 0000000000..15dcad9146--- /dev/null+++ b/camera/src/main/rust/src/raw_night.rs@@ -0,0 +1,378 @@+//! RAW night merge (depth Phase 2): linear-light burst merge.+//!+//! Each frame is unpacked Bayer, black-level subtracted and white-level+//! normalised to linear f32, white-balance gained per channel, demosaiced+//! (bilinear), aligned on the green channel with the same ORB+RANSAC+//! homography estimation the YUV night path uses, and robustly merged+//! (trimmed mean with a linear-light deghost gate). The output is linear+//! RGB; `merge_raw_burst` tone-maps it to the 8-bit RGBA the existing+//! Kotlin tone/encode pipeline consumes. No gamma-space averaging ever+//! happens, which is the point: averaging gamma YUV bakes noise and+//! black-level crush into the result.++use crate::features::{detect_and_describe, match_features};+use crate::geometry::{find_homography_ransac, Pt};+use crate::imgbuf::{Gray, Rgba};+use crate::linalg::Matrix3;++const MAX_FEATURES: usize = 2000;+const FAST_THRESHOLD: i32 = 12;+const RATIO: f32 = 0.78;+const RANSAC_ITERS: usize = 500;+const RANSAC_THRESH: f32 = 3.0;+const MIN_INLIERS: usize = 12;+const REG_MAX_MP: f64 = 0.8;+/// Summed linear RGB difference above which a warped sample is a ghost.+const LINEAR_GHOST_THRESH: f32 = 0.35;++/// Bayer colour-filter arrangement (mirrors `SENSOR_INFO_COLOR_FILTER_ARRANGEMENT`).+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Cfa {+ Rggb,+ Bggr,+ Grbg,+ Gbrg,+ Mono,+}++impl Cfa {+ pub fn from_code(code: i32) -> Option<Self> {+ Some(match code {+ 0 => Cfa::Rggb,+ 1 => Cfa::Grbg,+ 2 => Cfa::Gbrg,+ 3 => Cfa::Bggr,+ 4 => Cfa::Mono,+ _ => return None,+ })+ }+ /// Channel index (0=R,1=G,2=B) sampled at pixel (x,y); Mono is 1.+ fn channel_at(&self, x: usize, y: usize) -> usize {+ let (even_row, even_col) = (y % 2 == 0, x % 2 == 0);+ match self {+ Cfa::Mono => 1,+ Cfa::Rggb => match (even_row, even_col) {+ (true, true) => 0,+ (false, false) => 2,+ _ => 1,+ },+ Cfa::Bggr => match (even_row, even_col) {+ (true, true) => 2,+ (false, false) => 0,+ _ => 1,+ },+ Cfa::Grbg => match (even_row, even_col) {+ (true, false) => 0,+ (false, true) => 2,+ _ => 1,+ },+ Cfa::Gbrg => match (even_row, even_col) {+ (true, false) => 2,+ (false, true) => 0,+ _ => 1,+ },+ }+ }+}++/// Per-frame sensor metadata needed to linearise honestly.+#[derive(Clone, Copy, Debug)]+pub struct RawMeta {+ /// Black level per 2x2 pattern cell, indexed `(y%2)*2 + (x%2)`.+ pub black_levels: [f32; 4],+ pub white_level: f32,+ pub cfa: Cfa,+ /// White-balance gains (R,G,B); G is normally 1.+ pub gains: [f32; 3],+ /// Exposure x ISO product relative to the reference (1 = same).+ pub exposure_scale: f32,+}++impl RawMeta {+ /// Uniform-black convenience constructor (tests and scalar-black sensors).+ #[allow(dead_code)]+ pub fn scalar(black: f32, white: f32, cfa: Cfa) -> Self {+ RawMeta { black_levels: [black; 4], white_level: white, cfa, gains: [1.0, 1.0, 1.0], exposure_scale: 1.0 }+ }+}++/// One unpacked RAW frame (one u16 sample per photosite).+pub struct RawFrame {+ pub w: usize,+ pub h: usize,+ pub samples: Vec<u16>,+ pub meta: RawMeta,+}++/// Linear RGB image, one `[R,G,B]` f32 triplet per pixel (nominally 0..1,+/// may exceed 1 before tone mapping).+pub struct LinearRgb {+ pub w: usize,+ pub h: usize,+ pub px: Vec<[f32; 3]>,+}++/// Unpacks RAW10 (4 photosites in 5 bytes, low 2 bits packed in byte 4).+pub fn unpack_raw10(bytes: &[u8], w: usize, h: usize) -> Option<Vec<u16>> {+ if w == 0 || h == 0 || w % 4 != 0 {+ return None;+ }+ let row_bytes = w / 4 * 5;+ if bytes.len() < row_bytes * h {+ return None;+ }+ let mut out = vec![0u16; w * h];+ for y in 0..h {+ for g in 0..w / 4 {+ let b = &bytes[y * row_bytes + g * 5..y * row_bytes + g * 5 + 5];+ let lo = b[4];+ for k in 0..4 {+ out[y * w + g * 4 + k] = ((b[k] as u16) << 2) | ((lo >> (k * 2)) & 3) as u16;+ }+ }+ }+ Some(out)+}++/// Unpacks little-endian RAW_SENSOR / RAW16 samples (tight rows).+pub fn unpack_raw16(bytes: &[u8], w: usize, h: usize) -> Option<Vec<u16>> {+ if w == 0 || h == 0 || bytes.len() < w * h * 2 {+ return None;+ }+ Some((0..w * h).map(|i| u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]])).collect())+}++/// Black-subtract + white-normalise one photosite. Values at or below+/// black map to exactly 0 (never negative, so shadows are not crushed+/// below the noise floor they carry); above white clamps to 1.+#[inline]+fn linearise(sample: u16, black: f32, white: f32) -> f32 {+ let range = (white - black).max(1.0);+ ((sample as f32 - black) / range).clamp(0.0, 1.0)+}++fn sample_linear(frame: &RawFrame, x: usize, y: usize) -> f32 {+ let cell = (y % 2) * 2 + (x % 2);+ linearise(frame.samples[y * frame.w + x], frame.meta.black_levels[cell], frame.meta.white_level)+}++/// Bilinear demosaic to linear RGB: the sampled channel is exact, green+/// at R/B sites averages the cross neighbours, R/B at green sites average+/// the axis neighbours of that colour, and R at B (and vice versa) average+/// the diagonals. Border neighbours clamp to the edge.+pub fn demosaic(frame: &RawFrame) -> LinearRgb {+ let (w, h) = (frame.w, frame.h);+ let mut px = vec![[0f32; 3]; w * h];+ let at = |x: i32, y: i32| -> (f32, usize) {+ let cx = x.clamp(0, w as i32 - 1) as usize;+ let cy = y.clamp(0, h as i32 - 1) as usize;+ (sample_linear(frame, cx, cy), frame.meta.cfa.channel_at(cx, cy))+ };+ for y in 0..h as i32 {+ for x in 0..w as i32 {+ let (v, ch) = at(x, y);+ let mut rgb = [0f32; 3];+ rgb[ch] = v;+ if frame.meta.cfa == Cfa::Mono {+ rgb = [v, v, v];+ } else if ch == 1 {+ let horiz = [at(x - 1, y).0, at(x + 1, y).0];+ let vert = [at(x, y - 1).0, at(x, y + 1).0];+ let (hc, vc) = (at(x - 1, y).1, at(x, y - 1).1);+ rgb[hc] = (horiz[0] + horiz[1]) * 0.5;+ rgb[vc] = (vert[0] + vert[1]) * 0.5;+ } else {+ rgb[1] = (at(x - 1, y).0 + at(x + 1, y).0 + at(x, y - 1).0 + at(x, y + 1).0) * 0.25;+ let other = 2 - ch;+ rgb[other] = (at(x - 1, y - 1).0 + at(x + 1, y - 1).0 + at(x - 1, y + 1).0 + at(x + 1, y + 1).0) * 0.25;+ }+ for c in 0..3 {+ rgb[c] *= frame.meta.gains[c];+ }+ px[y as usize * w + x as usize] = rgb;+ }+ }+ LinearRgb { w, h, px }+}++/// Green channel as an 8-bit registration image (the sharpest, densest+/// channel: half of all photosites, and the homography's best signal).+fn green_gray(img: &LinearRgb, scale: f64) -> Gray {+ let (w, h) = (img.w, img.h);+ let (rw, rh) = if scale < 0.999 {+ (((w as f64 * scale).round() as usize).max(1), ((h as f64 * scale).round() as usize).max(1))+ } else {+ (w, h)+ };+ let mut g = Gray::new(rw, rh);+ for y in 0..rh {+ for x in 0..rw {+ let sx = ((x as f64 + 0.5) / scale - 0.5).max(0.0) as usize;+ let sy = ((y as f64 + 0.5) / scale - 0.5).max(0.0) as usize;+ let v = img.px[sy.min(h - 1) * w + sx.min(w - 1)][1];+ g.px[y * rw + x] = (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ }+ g+}++fn scale_homography(h: &Matrix3<f64>, s: f64) -> Matrix3<f64> {+ if (s - 1.0).abs() < 1e-6 {+ return *h;+ }+ Matrix3::new(h[(0, 0)], h[(0, 1)], h[(0, 2)] / s, h[(1, 0)], h[(1, 1)], h[(1, 2)] / s, h[(2, 0)] * s, h[(2, 1)] * s, h[(2, 2)])+}++/// Estimates, per frame, the warp from reference coordinates into that+/// frame (the inverse homography), by registering green channels at+/// reduced resolution exactly as the YUV night path registers luma.+/// Frame 0 is the reference; callers order the burst accordingly.+fn estimate_warps(frames: &[LinearRgb]) -> Vec<Option<Matrix3<f64>>> {+ let n = frames.len();+ let mut warps: Vec<Option<Matrix3<f64>>> = vec![None; n];+ if n < 2 || frames[0].w == 0 || frames[0].h == 0 {+ return warps;+ }+ let area = frames[0].w as f64 * frames[0].h as f64;+ let reg_scale = (REG_MAX_MP * 1e6 / area).sqrt().min(1.0);+ let grays: Vec<Gray> = frames.iter().map(|f| green_gray(f, reg_scale)).collect();+ let ref_feat = detect_and_describe(&grays[0], MAX_FEATURES, FAST_THRESHOLD);+ for i in 1..n {+ let feat = detect_and_describe(&grays[i], MAX_FEATURES, FAST_THRESHOLD);+ let matches = match_features(&feat, &ref_feat, RATIO);+ if matches.len() < MIN_INLIERS {+ continue;+ }+ let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();+ let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();+ if let Some((h_small, inl)) = find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) {+ if inl < MIN_INLIERS {+ continue;+ }+ let s = if frames[i].w > 0 { grays[i].w as f64 / frames[i].w as f64 } else { 1.0 };+ if let Some(inv) = scale_homography(&h_small, s).try_inverse() {+ warps[i] = Some(inv);+ }+ }+ }+ warps+}++#[inline]+fn apply_h(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) {+ let v = h * crate::linalg::Vector3::new(x, y, 1.0);+ if v.z.abs() < 1e-12 { (v.x, v.y) } else { (v.x / v.z, v.y / v.z) }+}++#[inline]+fn sample_linear_rgb(img: &LinearRgb, fx: f32, fy: f32) -> Option<[f32; 3]> {+ if fx < 0.0 || fy < 0.0 || fx > (img.w - 1) as f32 || fy > (img.h - 1) as f32 {+ return None;+ }+ let x0 = fx.floor() as usize;+ let y0 = fy.floor() as usize;+ let x1 = (x0 + 1).min(img.w - 1);+ let y1 = (y0 + 1).min(img.h - 1);+ let (ax, ay) = (fx - x0 as f32, fy - y0 as f32);+ let mut out = [0f32; 3];+ for c in 0..3 {+ let top = img.px[y0 * img.w + x0][c] * (1.0 - ax) + img.px[y0 * img.w + x1][c] * ax;+ let bot = img.px[y1 * img.w + x0][c] * (1.0 - ax) + img.px[y1 * img.w + x1][c] * ax;+ out[c] = top * (1.0 - ay) + bot * ay;+ }+ Some(out)+}++fn trimmed_mean(sum: f32, min: f32, max: f32, count: usize) -> f32 {+ match count {+ 0 => 0.0,+ 1 => sum,+ 2 => sum * 0.5,+ 3 => sum - min - max,+ _ => (sum - min - max) / (count - 2) as f32,+ }+}++/// Aligns and robustly merges a RAW burst in linear light. Frames are+/// exposure-normalised to the reference (`meta.exposure_scale`), warped+/// by the green-channel homographies, deghosted against the reference,+/// and combined with the night path's trimmed mean. Frames whose+/// registration failed contribute nothing (never an unwarped smear).+pub fn merge_raw_linear(frames: &[RawFrame]) -> Option<LinearRgb> {+ if frames.is_empty() || frames[0].w == 0 || frames[0].h == 0 {+ return None;+ }+ let (w, h) = (frames[0].w, frames[0].h);+ if frames.iter().any(|f| f.w != w || f.h != h || f.samples.len() != w * h) {+ return None;+ }+ let linear: Vec<LinearRgb> = frames.iter().map(demosaic).collect();+ if linear.len() == 1 {+ return Some(linear.into_iter().next().unwrap());+ }+ let warps = estimate_warps(&linear);+ let reff = &linear[0];+ let ref_scale = frames[0].meta.exposure_scale.max(1e-6);+ let mut out = LinearRgb { w, h, px: vec![[0f32; 3]; w * h] };+ for y in 0..h {+ for x in 0..w {+ let rp = reff.px[y * w + x];+ let mut sum = rp;+ let mut min = rp;+ let mut max = rp;+ let mut count = 1usize;+ for (i, f) in linear.iter().enumerate().skip(1) {+ let Some(warp) = warps[i] else { continue };+ let (sx, sy) = apply_h(&warp, x as f64, y as f64);+ let Some(mut c) = sample_linear_rgb(f, sx as f32, sy as f32) else { continue };+ let norm = ref_scale / frames[i].meta.exposure_scale.max(1e-6);+ for ch in 0..3 { c[ch] *= norm; }+ let diff = (c[0] - rp[0]).abs() + (c[1] - rp[1]).abs() + (c[2] - rp[2]).abs();+ if diff > LINEAR_GHOST_THRESH {+ continue;+ }+ for ch in 0..3 {+ sum[ch] += c[ch];+ min[ch] = min[ch].min(c[ch]);+ max[ch] = max[ch].max(c[ch]);+ }+ count += 1;+ }+ let mut px = [0f32; 3];+ for ch in 0..3 {+ px[ch] = trimmed_mean(sum[ch], min[ch], max[ch], count).max(0.0);+ }+ out.px[y * w + x] = px;+ }+ }+ Some(out)+}++/// Tone-maps linear RGB to 8-bit RGBA: exposure gain, a soft highlight+/// knee, then sRGB gamma. Hand-off to the existing Kotlin tone/encode+/// pipeline, which applies its highlight-preserving brighten before encoding.+pub fn tone_map(img: &LinearRgb, exposure_gain: f32) -> Rgba {+ let mut out = Rgba::new(img.w, img.h);+ for i in 0..img.w * img.h {+ let mut px = [0u8; 4];+ for c in 0..3 {+ let mut v = (img.px[i][c] * exposure_gain).max(0.0);+ if v > 0.8 {+ v = 0.8 + (v - 0.8) / (1.0 + (v - 0.8));+ }+ px[c] = (v.powf(1.0 / 2.2).clamp(0.0, 1.0) * 255.0).round() as u8;+ }+ px[3] = 255;+ out.px[i * 4..i * 4 + 4].copy_from_slice(&px);+ }+ out+}++/// Full RAW night merge: linear merge, then tone map for the encoder.+pub fn merge_raw_burst(frames: &[RawFrame], exposure_gain: f32) -> Option<Rgba> {+ Some(tone_map(&merge_raw_linear(frames)?, exposure_gain))+}++#[cfg(test)]+#[path = "raw_night_tests.rs"]+mod raw_night_tests;
camera/src/main/rust/src/raw_night_tests.rs
diff --git a/camera/src/main/rust/src/raw_night_tests.rs b/camera/src/main/rust/src/raw_night_tests.rsnew file mode 100644index 0000000000..2275666f18--- /dev/null+++ b/camera/src/main/rust/src/raw_night_tests.rs@@ -0,0 +1,164 @@+//! Synthetic RAW tests: Bayer gradients, black-level handling, and a+//! measurable noise-variance reduction from the linear merge.++use super::*;++/// Deterministic pseudo-noise in [-amp, amp] from a cheap LCG.+fn noise(i: usize, seed: u32, amp: i32) -> i32 {+ let mut s = seed.wrapping_add((i as u32).wrapping_mul(2654435761));+ s ^= s << 13;+ s ^= s >> 17;+ s ^= s << 5;+ (s % (2 * amp as u32 + 1)) as i32 - amp+}++/// Builds an RGGB frame whose underlying scene is a smooth gradient in+/// linear light, rendered per-photosite, plus per-sample noise.+fn synthetic(w: usize, h: usize, seed: u32, noise_amp: i32, black: u16, white: u16) -> RawFrame {+ let meta = RawMeta::scalar(black as f32, white as f32, Cfa::Rggb);+ let mut samples = vec![0u16; w * h];+ for y in 0..h {+ for x in 0..w {+ let ch = meta.cfa.channel_at(x, y);+ // Scene: R rises with x, G with (x+y)/2, B falls with x.+ let scene = match ch {+ 0 => 0.15 + 0.5 * x as f32 / w as f32,+ 2 => 0.65 - 0.5 * x as f32 / w as f32,+ _ => 0.15 + 0.5 * (x + y) as f32 / (w + h) as f32,+ };+ // Block texture so green-channel ORB registration has corners+ // to lock onto (a pure gradient is featureless by design).+ let block = ((x / 16) * 31 + (y / 16) * 17 + ((x / 16) * (y / 16)) * 7) % 5;+ // Fine scene texture, identical across the burst (only the+ // per-frame `noise` differs), so registration has signal.+ let cell = ((x / 3) * 73856093) ^ ((y / 3) * 19349663);+ let fine = ((cell % 13) as f32 - 6.0) * 0.012;+ let texture = (block as f32 - 2.0) * 0.05 + fine;+ let v = black as i32+ + ((scene + texture).clamp(0.02, 0.95) * (white - black) as f32).round() as i32+ + noise(y * w + x, seed, noise_amp);+ samples[y * w + x] = v.clamp(0, 65535) as u16;+ }+ }+ RawFrame { w, h, samples, meta }+}++/// Noise power: mean squared deviation of the green channel from the+/// noiseless ground-truth frame (scene gradient/texture cancels out).+fn green_noise_power(img: &LinearRgb, clean: &LinearRgb, x0: usize, y0: usize, side: usize) -> f64 {+ let mut acc = 0.0f64;+ let mut n = 0usize;+ for y in y0..y0 + side {+ for x in x0..x0 + side {+ let d = img.px[y * img.w + x][1] as f64 - clean.px[y * clean.w + x][1] as f64;+ acc += d * d;+ n += 1;+ }+ }+ acc / n as f64+}++#[test]+fn raw10_unpack_roundtrip() {+ // Samples 0, 341, 682, 1023 packed as RAW10.+ let samples = [0u16, 341, 682, 1023];+ let mut bytes = vec![0u8; 5];+ for k in 0..4 {+ bytes[k] = (samples[k] >> 2) as u8;+ bytes[4] |= ((samples[k] & 3) as u8) << (k * 2);+ }+ let out = unpack_raw10(&bytes.repeat(4), 4, 1).expect("unpack");+ assert_eq!(out[0..4], samples[..]);+ assert!(unpack_raw10(&bytes, 3, 1).is_none(), "width must be multiple of 4");+}++#[test]+fn raw16_unpack_little_endian() {+ let out = unpack_raw16(&[0x34, 0x12, 0x00, 0x01], 2, 1).expect("unpack");+ assert_eq!(out, vec![0x1234, 0x0100]);+}++#[test]+fn black_level_is_subtracted_not_crushed() {+ // A frame sitting exactly at black level linearises to 0, and a+ // frame 10% above black (in sensor counts) stays ~10% of range:+ // black subtraction must not push shadow signal negative or clip it.+ let black = 64u16;+ let white = 1023u16;+ let mut frame = synthetic(16, 16, 1, 0, black, white);+ for s in frame.samples.iter_mut() {+ *s = black;+ }+ let lin = demosaic(&frame);+ assert!(lin.px.iter().all(|p| p.iter().all(|&v| v == 0.0)), "at black -> 0");++ for s in frame.samples.iter_mut() {+ *s = black + (white - black) / 10;+ }+ let lin = demosaic(&frame);+ let v = lin.px[8 * 16 + 8][1];+ assert!((v - 0.1).abs() < 0.02, "10% above black stays ~0.1, got {v}");+}++#[test]+fn demosaic_recovers_bayer_gradient_channels() {+ let frame = synthetic(32, 24, 7, 0, 64, 1023);+ let lin = demosaic(&frame);+ // Left edge is R-dark/B-bright, right edge the reverse.+ let left = lin.px[12 * 32 + 2];+ let right = lin.px[12 * 32 + 29];+ assert!(left[2] > left[0] + 0.2, "left should be blue-dominant: {left:?}");+ assert!(right[0] > right[2] + 0.2, "right should be red-dominant: {right:?}");+ assert!(lin.px.iter().all(|p| p.iter().all(|&v| (0.0..=1.05).contains(&v))));+}++#[test]+fn merge_reduces_noise_variance_measurably() {+ // Large enough for the ORB pyramid's 31px edge threshold to leave an+ // interior (registration needs >~72px per side to see any keypoints).+ let (w, h) = (160, 120);+ let frames: Vec<RawFrame> = (0..6).map(|i| synthetic(w, h, 100 + i * 17, 28, 64, 1023)).collect();+ let single = demosaic(&frames[0]);+ let clean = demosaic(&synthetic(w, h, 999, 0, 64, 1023));+ let merged = merge_raw_linear(&frames).expect("merge");+ assert_eq!((merged.w, merged.h), (w, h));+ // Interior patch (avoid demosaic borders): merging 6 frames should+ // cut noise power by well over 2x even after demosaic correlation.+ let v_single = green_noise_power(&single, &clean, 60, 45, 32);+ let v_merged = green_noise_power(&merged, &clean, 60, 45, 32);+ assert!(v_single > 0.0, "synthetic noise must be present");+ assert!(+ v_merged < v_single * 0.45,+ "merge should at least halve variance: single {v_single:.6} merged {v_merged:.6}"+ );+ // And the merged mean stays on the scene, not dragged toward black.+ let mean: f64 = merged.px.iter().map(|p| p[1] as f64).sum::<f64>() / merged.px.len() as f64;+ assert!((0.25..0.55).contains(&mean), "merged green mean on scene: {mean}");+}++#[test]+fn merge_rejects_mismatched_and_empty_bursts() {+ assert!(merge_raw_linear(&[]).is_none());+ let a = synthetic(16, 16, 1, 0, 64, 1023);+ let b = synthetic(8, 16, 1, 0, 64, 1023);+ assert!(merge_raw_linear(&[a, b]).is_none(), "size mismatch refuses, never guesses");+}++#[test]+fn tone_map_is_monotonic_and_opaque() {+ let frame = synthetic(16, 16, 3, 0, 64, 1023);+ let rgba = merge_raw_burst(&[frame], 1.0).expect("burst");+ assert!(rgba.px.chunks_exact(4).all(|p| p[3] == 255));+ let dark = tone_map(&LinearRgb { w: 1, h: 1, px: vec![[0.05, 0.05, 0.05]] }, 1.0);+ let bright = tone_map(&LinearRgb { w: 1, h: 1, px: vec![[0.5, 0.5, 0.5]] }, 1.0);+ assert!(bright.px[0] > dark.px[0], "tone map preserves order");+}++#[test]+fn cfa_codes_match_android_constants() {+ // CameraMetadata: RGGB=0, GRBG=1, GBRG=2, BGGR=3, MONO=4 (API 31+ values+ // for MONO differ by platform level; the first four are stable).+ assert_eq!(Cfa::from_code(0), Some(Cfa::Rggb));+ assert_eq!(Cfa::from_code(3), Some(Cfa::Bggr));+ assert_eq!(Cfa::from_code(99), None);+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawNightPolicyTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawNightPolicyTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawNightPolicyTest.ktnew file mode 100644index 0000000000..2a3de3ae61--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawNightPolicyTest.kt@@ -0,0 +1,134 @@+package com.vayunmathur.camera.platform.camera2++import android.graphics.ImageFormat+import android.hardware.camera2.CameraMetadata+import android.util.Size+import com.vayunmathur.camera.platform.CameraMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+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 RawNightPolicyTest {++ private fun rawInput(+ gate: Boolean = true,+ explicit: Boolean = true,+ night: Boolean = true,+ mode: CameraMode = CameraMode.PHOTO,+ supported: Boolean = true,+ ring: Boolean = true,+ ) = RawNightInput(+ rawGateOn = gate, explicitRawSelected = explicit, mode = mode,+ nightRoute = night, rawSupported = supported, hasRawRingOutput = ring,+ )++ @Test fun rawNightNeedsGateExplicitNightRawAndRing() {+ assertTrue(RawNightPolicy.usesRawNight(rawInput()))+ // Every requirement removed individually disables RAW.+ assertFalse(RawNightPolicy.usesRawNight(rawInput(gate = false)))+ assertFalse(RawNightPolicy.usesRawNight(rawInput(explicit = false)))+ assertFalse(RawNightPolicy.usesRawNight(rawInput(night = false)))+ assertFalse(RawNightPolicy.usesRawNight(rawInput(supported = false)))+ assertFalse(RawNightPolicy.usesRawNight(rawInput(ring = false)))+ assertFalse(RawNightPolicy.usesRawNight(rawInput(mode = CameraMode.PORTRAIT)))+ assertTrue(+ RawNightPolicy.exclusionReason(rawInput(explicit = false))+ .orEmpty().contains("explicitly"),+ )+ }++ private fun rawSnapshot(+ capabilities: Set<Int> = setOf(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW),+ sizes: Map<Int, List<Size>> = mapOf(+ ImageFormat.RAW_SENSOR to listOf(Size(4032, 3024), Size(1920, 1440)),+ ImageFormat.RAW10 to listOf(Size(4032, 3024)),+ ),+ black: List<Int> = listOf(64, 64, 64, 64),+ white: Int? = 1023,+ cfa: Int? = CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB,+ matrices: List<Float> = List(9) { 0.5f },+ illuminant2: Int? = 0x15, // STANDARD_A-ish, any non-null code+ ) = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ sizesByFormat = sizes,+ availableCapabilities = capabilities,+ colorFilterArrangement = cfa,+ activeArrayWidth = 4032,+ activeArrayHeight = 3024,+ rawBlackLevelPattern = black,+ rawWhiteLevel = white,+ rawColorTransform1 = matrices,+ rawColorTransform2 = matrices,+ rawCalibrationTransform1 = matrices,+ rawCalibrationTransform2 = matrices,+ rawForwardMatrix1 = matrices,+ rawForwardMatrix2 = matrices,+ rawReferenceIlluminant1 = 0x15,+ rawReferenceIlluminant2 = illuminant2,+ ).snapshot++ @Test fun facadePrefersRawSensorAndSelectsCappedSize() {+ val snap = rawSnapshot()+ assertTrue(snap.supportsRaw)+ assertEquals(RingFormat.RAW_SENSOR, snap.rawRingFormat)+ assertTrue(snap.supportsRawRing)+ assertEquals(FrameSize(1920, 1440), StreamSelection.selectRawRingSize(snap))+ // No RAW capability: a RAW stream size alone never proves support.+ val noCap = rawSnapshot(capabilities = emptySet())+ assertNull(noCap.rawRingFormat)+ assertFalse(noCap.supportsRawRing)+ // RAW10-only lens falls back to the packed format.+ val raw10Only = rawSnapshot(+ sizes = mapOf(ImageFormat.RAW10 to listOf(Size(1920, 1440))),+ )+ assertEquals(RingFormat.RAW10, raw10Only.rawRingFormat)+ assertEquals(10, RingFormat.RAW10.rawBitDepth())+ assertEquals(ImageFormat.RAW10, RingFormat.RAW10.toImageFormat())+ }++ @Test fun dngAssemblyRequiresEverySensorField() {+ val complete = rawSnapshot()+ assertTrue(DngMetadataAssembler.missingRequirements(complete).isEmpty())+ val assembled = assertNotNull(DngMetadataAssembler.assemble(complete))+ assertEquals(listOf(64, 64, 64, 64), assembled.blackLevelPattern)+ assertEquals(1023, assembled.whiteLevel)+ assertEquals(9, assembled.colorTransform1.size)++ val noWhite = rawSnapshot(white = null)+ assertNull(DngMetadataAssembler.assemble(noWhite))+ assertTrue(+ DngMetadataAssembler.missingRequirements(noWhite)+ .any { it.contains("WHITE_LEVEL") },+ )+ val shortBlack = rawSnapshot(black = listOf(64, 64))+ assertNull(DngMetadataAssembler.assemble(shortBlack))+ val noCfa = rawSnapshot(cfa = null)+ assertNull(DngMetadataAssembler.assemble(noCfa))+ val halfSecondIlluminant = rawSnapshot(illuminant2 = null)+ assertNull(DngMetadataAssembler.assemble(halfSecondIlluminant))+ }++ @Test fun latestCompleteBurstReturnsOldestFirstCompleteFrames() {+ val ring = ReprocessRing<String>(capacity = 8)+ fun meta(ts: Long, exp: Long?) = RingFrameMeta(+ sensorTimestampNs = ts, exposureTimeNs = exp, format = RingFormat.RAW_SENSOR,+ )+ ring.offer(meta(100, 10), "a")+ ring.offer(meta(200, 10), "b")+ ring.offer(meta(300, 10), "c")+ ring.offer(meta(400, 500), "still-exposing") // ends 900+ val burst = ring.latestCompleteBurst(2, atNs = 350)+ assertEquals(listOf("b", "c"), burst.map { it.first })+ assertEquals(listOf(200L, 300L), burst.map { it.second.sensorTimestampNs })+ assertEquals(3, ring.latestCompleteBurst(6, atNs = 350).size)+ assertTrue(ring.latestCompleteBurst(0, atNs = 350).isEmpty())+ }+}
camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.ktnew file mode 100644index 0000000000..e5a89dcacb--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/platform/camera2/RawRingSessionTest.kt@@ -0,0 +1,158 @@+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 java.util.concurrent.atomic.AtomicInteger+import kotlin.test.Test+import kotlin.test.assertEquals+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 RawRingSessionTest {++ private class FakeRawFrame(ts: Long) : RawHeldFrame {+ override val meta = RingFrameMeta(+ sensorTimestampNs = ts, exposureTimeNs = 10,+ width = 1920, height = 1440, format = RingFormat.RAW_SENSOR,+ )+ override val format: RingFormat = RingFormat.RAW_SENSOR+ val closes = AtomicInteger(0)+ override fun copyRawBytes(): ByteArray = ByteArray(4)+ override fun close() { closes.incrementAndGet() }+ }++ private class FakeRawOutput : RawRingOutput {+ override val surface: Surface = mock(Surface::class.java)+ var ringListener: RawRingFrameListener? = null+ var closed = false+ override fun setListener(listener: RawRingFrameListener?) { ringListener = listener }+ override fun close() { closed = true }+ fun emit(frame: RawHeldFrame) = ringListener?.onRawRingFrame(frame)+ }++ private class FakeHandle : CaptureSessionHandle {+ var streamingTargets: List<Surface> = emptyList()+ override fun setRepeatingPreview(params: ResolvedRequestParams, target: Surface) {}+ override fun setRepeatingStreaming(+ params: ResolvedRequestParams, targets: List<Surface>, callback: PreviewResultCallback?,+ ) { streamingTargets = targets }+ override fun captureStill(+ params: ResolvedStillParams, stillTarget: Surface, callback: StillResultCallback,+ ) {}+ override fun close() {}+ }++ private class FakeDevice(private val handle: FakeHandle) : DeviceHandle {+ override val cameraId: String = "0"+ var surfaces: List<Surface>? = null+ override fun createCaptureSession(surfaces: List<Surface>, callback: CaptureSessionCallback) {+ this.surfaces = surfaces+ callback.onConfigured(handle)+ }+ override fun close() {}+ }++ private class FakeDriver(+ private val device: FakeDevice,+ private val raw: FakeRawOutput?,+ ) : Camera2Driver {+ override fun openCamera(cameraId: String, callback: DeviceCallback) =+ callback.onOpened(device)+ override fun createStillOutput(size: FrameSize): StillOutput? = null+ override fun createRingOutput(size: FrameSize): RingOutput? = null+ override fun createRawRingOutput(size: FrameSize, format: RingFormat): RawRingOutput? = raw+ }++ private fun snapshot() = CharacteristicsFacade.fromFakeMap(+ cameraId = "0",+ lensFacingRaw = CameraMetadata.LENS_FACING_BACK,+ zoomRatioRange = Range(1f, 10f),+ sizesByFormat = mapOf(+ ImageFormat.PRIVATE to listOf(Size(1280, 720)),+ ImageFormat.RAW_SENSOR to listOf(Size(1920, 1440)),+ ),+ availableCapabilities = setOf(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW),+ activeArrayWidth = 1920,+ activeArrayHeight = 1440,+ sensorOrientationDegrees = 90,+ exposureCompensationStepEv = 1f / 6f,+ ).snapshot++ private fun Camera2Executor.drain() {+ val latch = CountDownLatch(1)+ execute { latch.countDown() }+ assertTrue(latch.await(5, TimeUnit.SECONDS))+ }++ @Test fun dualRingConfiguresRawOutputAndServesBurst() {+ val executor = Camera2Executor("RawRingSessionTest")+ try {+ val handle = FakeHandle()+ val raw = FakeRawOutput()+ val device = FakeDevice(handle)+ val session = Camera2Session(+ FakeDriver(device, raw), executor, snapshot(),+ rawRingConfig = RawRingConfig(enabled = true),+ )+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ assertEquals(SessionState.STREAMING, session.state)+ assertTrue(session.hasRawRingOutput)+ assertTrue(session.rawSupported)+ assertEquals(FrameSize(1920, 1440), session.currentRawRingSize())+ assertEquals(RingFormat.RAW_SENSOR, session.currentRawRingFormat())++ raw.emit(FakeRawFrame(100)); raw.emit(FakeRawFrame(200)); raw.emit(FakeRawFrame(300))+ executor.drain()+ assertEquals(3, session.rawRingFrameCount)++ var burst: List<RawHeldFrame>? = null+ var failure: String? = null+ session.captureRawBurst(2, object : Camera2Session.RawBurstCallback {+ override fun onRawBurst(frames: List<RawHeldFrame>, metas: List<RingFrameMeta>) {+ burst = frames+ }+ override fun onRawBurstFailed(message: String) { failure = message }+ }, shutterTimestampNs = 320)+ executor.drain()+ assertEquals(null, failure)+ assertEquals(listOf(200L, 300L), burst!!.map { it.meta.sensorTimestampNs })+ assertEquals(1, session.rawRingFrameCount) // oldest remains held+ burst!!.forEach { it.close() }+ session.close(); executor.drain()+ assertTrue(raw.closed)+ } finally { executor.shutdown() }+ }++ @Test fun rawBurstFailsWithFewerThanTwoCompleteFrames() {+ val executor = Camera2Executor("RawRingSessionTest-short")+ try {+ val raw = FakeRawOutput()+ val session = Camera2Session(+ FakeDriver(FakeDevice(FakeHandle()), raw), executor, snapshot(),+ rawRingConfig = RawRingConfig(enabled = true),+ )+ session.open("0", mock(Surface::class.java), FrameSize(1280, 720))+ executor.drain()+ raw.emit(FakeRawFrame(100)); executor.drain()+ var failure: String? = null+ session.captureRawBurst(6, object : Camera2Session.RawBurstCallback {+ override fun onRawBurst(frames: List<RawHeldFrame>, metas: List<RingFrameMeta>) {}+ override fun onRawBurstFailed(message: String) { failure = message }+ }, shutterTimestampNs = 200)+ executor.drain()+ assertTrue(failure.orEmpty().contains("need 2+"), "got: $failure")+ session.close(); executor.drain()+ } finally { executor.shutdown() }+ }+}