From f7d265b44ac2c1844ee86cce5e0176ebb0099b5a Mon Sep 17 00:00:00 2001 From: Hinnka Date: Sat, 11 Jul 2026 17:47:36 +0800 Subject: [PATCH] feat: MFNR/MFSR optimize & hdr fusion fix --- .../processor/GlesRawStackerShaderTest.kt | 146 + app/src/main/AndroidManifest.xml | 1 + .../mycamera/camera/BurstGyroRecorder.kt | 92 + .../mycamera/camera/Camera2Controller.kt | 100 +- .../mycamera/camera/CapturedFrameMetadata.kt | 13 + .../mycamera/camera/GyroExposureWindow.kt | 153 + .../hinnka/mycamera/gallery/GalleryManager.kt | 32 +- .../mycamera/processor/GlesRawStacker.kt | 3592 +++++++++++------ .../mycamera/processor/MultiFrameStacker.kt | 28 +- .../mycamera/processor/RawAlignmentProxy.kt | 155 + .../mycamera/processor/RawBurstFrame.kt | 65 + .../processor/RawBurstGyroSelector.kt | 130 + .../processor/RawBurstReferencePlanner.kt | 249 ++ .../mycamera/processor/RawGlobalPreAligner.kt | 164 + .../mycamera/processor/RawStackDebugConfig.kt | 4 +- .../processor/RawStackTuningProfile.kt | 30 +- .../RawSuperResolutionStripePlanner.kt | 50 + .../processor/RawTemporalAlignmentGraph.kt | 106 + .../processor/RawTemporalAlignmentSolver.kt | 283 ++ .../processor/RawTemporalFlowFieldSolver.kt | 177 + .../mycamera/raw/DngProfileToneCurve.kt | 2 +- .../mycamera/viewmodel/CameraViewModel.kt | 204 +- .../GyroExposureWindowIntegratorTest.kt | 60 + .../processor/RawBurstGyroSelectorTest.kt | 76 + .../processor/RawFramePreAlignmentTest.kt | 26 + .../processor/RawGlobalPreAlignerTest.kt | 94 + .../processor/RawStackCfaPhaseGatherTest.kt | 77 + .../RawSuperResolutionStripePlannerTest.kt | 42 + .../RawTemporalAlignmentSolverTest.kt | 53 + .../RawTemporalFlowFieldSolverTest.kt | 54 + docs/gles-driver-compatibility.md | 74 + ...ignator-gles-raw-stacker-rearchitecture.md | 1024 +++++ 32 files changed, 6075 insertions(+), 1281 deletions(-) create mode 100644 app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/camera/BurstGyroRecorder.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/camera/CapturedFrameMetadata.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/camera/GyroExposureWindow.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawAlignmentProxy.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawBurstFrame.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawBurstGyroSelector.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawBurstReferencePlanner.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawGlobalPreAligner.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentGraph.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolver.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolver.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/camera/GyroExposureWindowIntegratorTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawBurstGyroSelectorTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawFramePreAlignmentTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawGlobalPreAlignerTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawStackCfaPhaseGatherTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolverTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolverTest.kt create mode 100644 docs/gles-driver-compatibility.md create mode 100644 docs/image-stack-alignator-gles-raw-stacker-rearchitecture.md diff --git a/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt b/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt new file mode 100644 index 00000000..1c6acc30 --- /dev/null +++ b/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt @@ -0,0 +1,146 @@ +package com.hinnka.mycamera.processor + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class GlesRawStackerShaderTest { + @Test + fun productionShadersCompileAndLinkOnDevice() { + validateMode(RawStackMode.MFNR) + validateMode(RawStackMode.MFSR) + validateHdrMode() + } + + private fun validateHdrMode() { + val stacker = GlesRawStacker( + width = 64, + height = 64, + cfaPattern = 0, + blackLevel = floatArrayOf(64f, 64f, 64f, 64f), + whiteLevel = 4095, + noiseModel = floatArrayOf(0.001f, 0.00001f), + lensShading = null, + lensShadingWidth = 0, + lensShadingHeight = 0, + tuning = RawStackTuningProfile(mode = RawStackMode.HDR_MFNR), + debugConfig = RawStackDebugConfig.Disabled, + ) + try { + invokePrivate(stacker, "initEgl") + invokePrivate(stacker, "ensureGles31") + invokePrivate(stacker, "initPrograms") + invokePrivate(stacker, "initHdrPrograms") + invokePrivate(stacker, "initResources") + invokePrivate(stacker, "applyRawRenderState") + + val refRaw = readPrivateInt(stacker, "refRaw") + invokePrivate(stacker, "clearAccumulator") + invokePrivate(stacker, "accumulateFrame", refRaw, true, 1f, true) + invokePrivate(stacker, "computeHdrRecoveryMask", 1f, true) + invokePrivate( + stacker, + "normalizeOutput", + true, + 1f, + 1f, + readPrivateInt(stacker, "outputTexture"), + 64, + 64, + "instrumentation HDR normalize", + ) + } finally { + invokePrivate(stacker, "release") + } + } + + private fun validateMode(mode: RawStackMode) { + val stacker = GlesRawStacker( + width = 64, + height = 64, + cfaPattern = 0, + blackLevel = floatArrayOf(64f, 64f, 64f, 64f), + whiteLevel = 4095, + noiseModel = floatArrayOf(0.001f, 0.00001f), + lensShading = null, + lensShadingWidth = 0, + lensShadingHeight = 0, + tuning = RawStackTuningProfile(mode = mode), + debugConfig = RawStackDebugConfig.Disabled, + ) + try { + invokePrivate(stacker, "initEgl") + invokePrivate(stacker, "ensureGles31") + invokePrivate(stacker, "initPrograms") + invokePrivate(stacker, "initResources") + invokePrivate(stacker, "applyRawRenderState") + + val refRaw = readPrivateInt(stacker, "refRaw") + val refProxy = readPrivateInt(stacker, "refProxy") + invokePrivate(stacker, "clearAccumulator") + invokePrivate(stacker, "accumulateFrame", refRaw, true, 1f, false) + if (mode == RawStackMode.MFSR) { + invokePrivate( + stacker, + "reconstructSuperResolutionStripes", + createSuperResolutionDecision(), + emptyList(), + ) + } + invokePrivate( + stacker, + "buildTrackingProxy", + refRaw, + refProxy, + 32, + 32, + 1, + 1f, + "instrumentation smoke", + ) + + val gridWidth = readPrivateInt(stacker, "gridWidth") + val gridHeight = readPrivateInt(stacker, "gridHeight") + val flowTexture = readPrivateInt(stacker, "flowTexture") + val flowValues = invokePrivate( + stacker, + "readFlowTexture", + flowTexture, + gridWidth, + gridHeight, + "instrumentation smoke", + ) as FloatArray + assertEquals(gridWidth * gridHeight * 4, flowValues.size) + } finally { + invokePrivate(stacker, "release") + } + } + + private fun invokePrivate(target: Any, methodName: String, vararg args: Any): Any? { + return target.javaClass.declaredMethods.first { + it.name == methodName && it.parameterCount == args.size + }.run { + isAccessible = true + invoke(target, *args) + } + } + + private fun readPrivateInt(target: Any, fieldName: String): Int { + return target.javaClass.getDeclaredField(fieldName).run { + isAccessible = true + getInt(target) + } + } + + private fun createSuperResolutionDecision(): Any { + val decisionClass = GlesRawStacker::class.java.declaredClasses.first { + it.simpleName == "SuperResolutionOutputDecision" + } + return decisionClass.declaredConstructors.first { it.parameterCount == 7 }.run { + isAccessible = true + newInstance("SUPER_RESOLUTION", null, 1, 1f, 1, 4, listOf(1, 0, 0, 0)) + } + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f4061671..a473a2b8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -14,6 +14,7 @@ android:maxSdkVersion="32" /> + (MAX_SAMPLES) + private val lock = Any() + + @Volatile + private var recording = false + + private val listener = object : SensorEventListener { + override fun onSensorChanged(event: SensorEvent) { + if (!recording || event.values.size < 3) return + val hasBias = event.sensor.type == Sensor.TYPE_GYROSCOPE_UNCALIBRATED && event.values.size >= 6 + val sample = GyroSample( + timestampNs = event.timestamp, + x = event.values[0] - if (hasBias) event.values[3] else 0f, + y = event.values[1] - if (hasBias) event.values[4] else 0f, + z = event.values[2] - if (hasBias) event.values[5] else 0f, + ) + synchronized(lock) { + while (samples.size >= MAX_SAMPLES) samples.removeFirst() + samples.addLast(sample) + } + } + + override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit + } + + fun start(handler: Handler?): Boolean { + if (recording) return true + val gyro = sensor ?: run { + PLog.w(TAG, "Burst Gyro unavailable") + return false + } + synchronized(lock) { samples.clear() } + recording = sensorManager.registerListener( + listener, + gyro, + SensorManager.SENSOR_DELAY_FASTEST, + handler, + ) + if (!recording) PLog.w(TAG, "Failed to register burst Gyro listener") + return recording + } + + fun stop() { + if (!recording) return + recording = false + sensorManager.unregisterListener(listener) + } + + fun exposureWindow(startTimestampNs: Long, exposureTimeNs: Long): GyroExposureWindow { + val safeExposureNs = exposureTimeNs.coerceAtLeast(0L) + val endTimestampNs = startTimestampNs.saturatingAdd(safeExposureNs) + if (safeExposureNs == 0L) { + return GyroExposureWindow.unavailable(startTimestampNs, endTimestampNs) + } + val guardStart = (startTimestampNs - WINDOW_GUARD_NS).coerceAtLeast(0L) + val guardEnd = endTimestampNs.saturatingAdd(WINDOW_GUARD_NS) + val snapshot = synchronized(lock) { + samples.filter { it.timestampNs in guardStart..guardEnd } + } + return GyroExposureWindowIntegrator.integrate(snapshot, startTimestampNs, endTimestampNs) + } + + fun release() { + stop() + synchronized(lock) { samples.clear() } + } + + private fun Long.saturatingAdd(value: Long): Long { + return if (value > 0L && this > Long.MAX_VALUE - value) Long.MAX_VALUE else this + value + } + + private companion object { + const val TAG = "BurstGyroRecorder" + const val MAX_SAMPLES = 8_192 + const val WINDOW_GUARD_NS = 2_000_000L + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index 02f59900..730106fc 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -200,6 +200,7 @@ class Camera2Controller(private val context: Context) { private var cameraThread: HandlerThread? = null private var cameraHandler: Handler? = null + private val burstGyroRecorder = BurstGyroRecorder(context) private val cameraCharacteristicsCache = ConcurrentHashMap() private var cachedCharacteristics: CameraCharacteristics? = null @@ -278,6 +279,7 @@ class Camera2Controller(private val context: Context) { // 缓存 CaptureResult 和 Image 用于配对 (timestamp -> Data) private val pendingResults = ConcurrentHashMap() private val pendingImages = ConcurrentHashMap() + private val pendingFrameMetadata = ConcurrentHashMap() private val pendingCaptureStartedTimestamps = ConcurrentHashMap() private val pendingCloseReaders = mutableListOf() private val openImagesCount = AtomicInteger(0) @@ -314,7 +316,7 @@ class Camera2Controller(private val context: Context) { private var lastSentHighlightPointY: Float = -1f // 图片拍摄回调(携带 CaptureInfo, CameraCharacteristics 和 CaptureResult 用于 RAW 处理) - var onImageCaptured: ((SafeImage, CaptureInfo, CameraCharacteristics?, CaptureResult?) -> Unit)? = null + var onImageCaptured: ((SafeImage, CaptureInfo, CameraCharacteristics?, CaptureResult?, CapturedFrameMetadata?) -> Unit)? = null var onHdrBracketCaptureFailed: (() -> Unit)? = null private fun trackImage(image: Image?): SafeImage? { @@ -351,6 +353,7 @@ class Camera2Controller(private val context: Context) { PLog.w(TAG, "Capture result missing timestamp, frame=${result.frameNumber}") return } + captureFrameMetadata(result, timestamp)?.let { pendingFrameMetadata[timestamp] = it } val pendingImage = pendingImages.remove(timestamp) if (pendingImage != null) { @@ -371,6 +374,31 @@ class Camera2Controller(private val context: Context) { if (pendingResults.size <= maxSize) return val oldestKey = pendingResults.keys.minOrNull() ?: return pendingResults.remove(oldestKey) + pendingFrameMetadata.remove(oldestKey) + } + + private fun captureFrameMetadata( + result: TotalCaptureResult, + sensorTimestampNs: Long, + ): CapturedFrameMetadata? { + val exposureTimeNs = result.get(CaptureResult.SENSOR_EXPOSURE_TIME) ?: return null + val sensitivityIso = result.get(CaptureResult.SENSOR_SENSITIVITY) ?: return null + val postRawBoost = result + .get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST) + ?.coerceAtLeast(1) + ?: 100 + return CapturedFrameMetadata( + sensorTimestampNs = sensorTimestampNs, + frameNumber = result.frameNumber, + exposureTimeNs = exposureTimeNs, + sensitivityIso = sensitivityIso, + exposureProduct = exposureTimeNs.toDouble() * sensitivityIso.toDouble() * + (postRawBoost.toDouble() / 100.0), + focusDistanceDiopters = result.get(CaptureResult.LENS_FOCUS_DISTANCE) ?: Float.NaN, + lensState = result.get(CaptureResult.LENS_STATE), + rollingShutterSkewNs = result.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW), + gyroWindow = burstGyroRecorder.exposureWindow(sensorTimestampNs, exposureTimeNs), + ) } // 快门音效播放回调 @@ -4972,6 +5000,9 @@ class Camera2Controller(private val context: Context) { // 只有在【自动曝光 + 单次闪光】时才使用预闪流程 // 手动曝光模式下,AE_PRECAPTURE_TRIGGER 不生效(因为 AE_MODE=OFF),直接拍照 val currentState = _state.value + if (currentState.useMFNR || currentState.useMFSR) { + burstGyroRecorder.start(cameraHandler) + } val needsPrecapture = currentState.flashMode == CameraMetadata.FLASH_MODE_SINGLE && currentState.isIsoAuto && currentState.isShutterSpeedAuto @@ -4994,6 +5025,7 @@ class Camera2Controller(private val context: Context) { PLog.e(TAG, "Failed to capture", e) PLog.e(TAG, "拍照失败", e) _state.value = _state.value.copy(isCapturing = false) + burstGyroRecorder.stop() } } @@ -5018,6 +5050,9 @@ class Camera2Controller(private val context: Context) { } val baseExposureResult = lastCaptureResult lastCaptureResult = null + if (_state.value.useMFNR || _state.value.useMFSR) { + burstGyroRecorder.start(cameraHandler) + } performHdrBracketCapture( device = device, reader = reader, @@ -5114,6 +5149,14 @@ class Camera2Controller(private val context: Context) { ) { super.onCaptureSequenceCompleted(session, sequenceId, frameNumber) PLog.d(TAG, "HDR bracket sequence completed") + burstGyroRecorder.stop() + resetPreviewAfterCapture() + } + + override fun onCaptureSequenceAborted(session: CameraCaptureSession, sequenceId: Int) { + burstGyroRecorder.stop() + PLog.w(TAG, "HDR bracket sequence aborted") + onHdrBracketCaptureFailed?.invoke() resetPreviewAfterCapture() } @@ -5128,6 +5171,7 @@ class Camera2Controller(private val context: Context) { hdrBracketCapturing = false, hdrBracketFrameCount = 0 ) + burstGyroRecorder.stop() onHdrBracketCaptureFailed?.invoke() resetPreviewAfterCapture() } @@ -5139,6 +5183,7 @@ class Camera2Controller(private val context: Context) { hdrBracketCapturing = false, hdrBracketFrameCount = 0 ) + burstGyroRecorder.stop() onHdrBracketCaptureFailed?.invoke() resetPreviewAfterCapture() } @@ -5516,15 +5561,9 @@ class Camera2Controller(private val context: Context) { request: CaptureRequest, result: TotalCaptureResult ) { - val timestamp = getCaptureTimestamp(result) - if (timestamp != null && isRawCapture) { - val pendingImage = pendingImages.remove(timestamp) - if (pendingImage != null) { - processAndTriggerCapture(pendingImage, result) - } else { - pendingResults[timestamp] = result - } - } + val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP) + ?: pendingCaptureStartedTimestamps[result.frameNumber] + if (isRawCapture) processOrBufferCaptureResult(result) lastCaptureResult = result PLog.d( TAG, @@ -5539,6 +5578,13 @@ class Camera2Controller(private val context: Context) { ) { super.onCaptureSequenceCompleted(session, sequenceId, frameNumber) PLog.d(TAG, "Burst sequence completed") + burstGyroRecorder.stop() + resetPreviewAfterCapture() + } + + override fun onCaptureSequenceAborted(session: CameraCaptureSession, sequenceId: Int) { + burstGyroRecorder.stop() + PLog.w(TAG, "Burst capture sequence aborted") resetPreviewAfterCapture() } @@ -5549,6 +5595,7 @@ class Camera2Controller(private val context: Context) { ) { PLog.e(TAG, "Burst Capture failed: ${failure.reason}") _state.value = _state.value.copy(isCapturing = false) + burstGyroRecorder.stop() resetPreviewAfterCapture() } }, cameraHandler) @@ -5805,6 +5852,8 @@ class Camera2Controller(private val context: Context) { return } try { + burstGyroRecorder.stop() + pendingFrameMetadata.clear() cameraOpenGeneration++ val keepVideoRecording = preserveVideoRecording && _state.value.videoRecordingState.isRecording if (keepVideoRecording) { @@ -5930,11 +5979,39 @@ class Camera2Controller(private val context: Context) { longitude = _state.value.longitude, effectiveCharacteristics = effectiveCharacteristics ) + val frameResult = effectiveResult ?: result + val sensorTimestampNs = frameResult?.get(CaptureResult.SENSOR_TIMESTAMP) ?: image.timestamp + val exposureTimeNs = frameResult?.get(CaptureResult.SENSOR_EXPOSURE_TIME) ?: 0L + val sensitivityIso = frameResult?.get(CaptureResult.SENSOR_SENSITIVITY) ?: 0 + val postRawBoost = frameResult + ?.get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST) + ?.coerceAtLeast(1) + ?: 100 + val frozenMetadata = pendingFrameMetadata.remove(image.timestamp) + val frameMetadata = if (image.format == ImageFormat.RAW_SENSOR && frameResult != null) { + CapturedFrameMetadata( + sensorTimestampNs = sensorTimestampNs, + frameNumber = frozenMetadata?.frameNumber ?: result?.frameNumber ?: -1L, + exposureTimeNs = exposureTimeNs, + sensitivityIso = sensitivityIso, + exposureProduct = exposureTimeNs.toDouble() * sensitivityIso.toDouble() * + (postRawBoost.toDouble() / 100.0), + focusDistanceDiopters = frameResult + .get(CaptureResult.LENS_FOCUS_DISTANCE) + ?: Float.NaN, + lensState = frameResult.get(CaptureResult.LENS_STATE), + rollingShutterSkewNs = frameResult.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW), + gyroWindow = frozenMetadata?.gyroWindow + ?: burstGyroRecorder.exposureWindow(sensorTimestampNs, exposureTimeNs), + ) + } else { + null + } // 传递完整的 Image 对象、CaptureInfo、CameraCharacteristics 和 CaptureResult val callback = onImageCaptured if (callback != null) { - callback.invoke(image, captureInfo, effectiveCharacteristics, effectiveResult ?: result) + callback.invoke(image, captureInfo, effectiveCharacteristics, frameResult, frameMetadata) } else { image.close() } @@ -5968,6 +6045,7 @@ class Camera2Controller(private val context: Context) { } previewDepthProcessor.release() previewAiFocusProcessor.release() + burstGyroRecorder.release() videoRecorder.release() stopBackgroundThread() cameraDiscovery.clearCache() diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CapturedFrameMetadata.kt b/app/src/main/java/com/hinnka/mycamera/camera/CapturedFrameMetadata.kt new file mode 100644 index 00000000..7ac73d4f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/CapturedFrameMetadata.kt @@ -0,0 +1,13 @@ +package com.hinnka.mycamera.camera + +data class CapturedFrameMetadata( + val sensorTimestampNs: Long, + val frameNumber: Long, + val exposureTimeNs: Long, + val sensitivityIso: Int, + val exposureProduct: Double, + val focusDistanceDiopters: Float, + val lensState: Int?, + val rollingShutterSkewNs: Long?, + val gyroWindow: GyroExposureWindow?, +) diff --git a/app/src/main/java/com/hinnka/mycamera/camera/GyroExposureWindow.kt b/app/src/main/java/com/hinnka/mycamera/camera/GyroExposureWindow.kt new file mode 100644 index 00000000..601bf6d9 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/camera/GyroExposureWindow.kt @@ -0,0 +1,153 @@ +package com.hinnka.mycamera.camera + +import kotlin.math.max +import kotlin.math.min +import kotlin.math.sqrt + +data class GyroExposureWindow( + val startTimestampNs: Long, + val endTimestampNs: Long, + val sampleCount: Int, + val integratedRotationRad: FloatArray, + val angularEnergy: Float, + val peakAngularVelocity: Float, + val jerkEnergy: Float, + val coverageRatio: Float, +) { + companion object { + fun unavailable(startTimestampNs: Long, endTimestampNs: Long) = GyroExposureWindow( + startTimestampNs = startTimestampNs, + endTimestampNs = endTimestampNs, + sampleCount = 0, + integratedRotationRad = FloatArray(3), + angularEnergy = 0f, + peakAngularVelocity = 0f, + jerkEnergy = 0f, + coverageRatio = 0f, + ) + } +} + +internal data class GyroSample( + val timestampNs: Long, + val x: Float, + val y: Float, + val z: Float, +) + +internal object GyroExposureWindowIntegrator { + fun integrate( + samples: List, + startTimestampNs: Long, + endTimestampNs: Long, + ): GyroExposureWindow { + if (endTimestampNs <= startTimestampNs || samples.size < 2) { + return GyroExposureWindow.unavailable(startTimestampNs, endTimestampNs) + } + + val ordered = samples + .asSequence() + .filter { it.timestampNs >= 0L } + .sortedBy { it.timestampNs } + .distinctBy { it.timestampNs } + .toList() + if (ordered.size < 2) { + return GyroExposureWindow.unavailable(startTimestampNs, endTimestampNs) + } + + val coveredStart = max(startTimestampNs, ordered.first().timestampNs) + val coveredEnd = min(endTimestampNs, ordered.last().timestampNs) + val requestedDurationNs = endTimestampNs - startTimestampNs + val coveredDurationNs = (coveredEnd - coveredStart).coerceAtLeast(0L) + val coverage = (coveredDurationNs.toDouble() / requestedDurationNs.toDouble()) + .coerceIn(0.0, 1.0) + .toFloat() + if (coveredDurationNs <= 0L) { + return GyroExposureWindow.unavailable(startTimestampNs, endTimestampNs) + } + + val clipped = ArrayList() + interpolateAt(ordered, coveredStart)?.let(clipped::add) + ordered.forEach { sample -> + if (sample.timestampNs > coveredStart && sample.timestampNs < coveredEnd) { + clipped.add(sample) + } + } + interpolateAt(ordered, coveredEnd)?.let { sample -> + if (clipped.lastOrNull()?.timestampNs != sample.timestampNs) clipped.add(sample) + } + if (clipped.size < 2) { + return GyroExposureWindow.unavailable(startTimestampNs, endTimestampNs).copy( + coverageRatio = coverage, + ) + } + + val rotation = DoubleArray(3) + var energyIntegral = 0.0 + var jerkIntegral = 0.0 + var peakVelocity = 0.0 + for (index in 0 until clipped.lastIndex) { + val a = clipped[index] + val b = clipped[index + 1] + val dtSeconds = (b.timestampNs - a.timestampNs).toDouble() * NS_TO_SECONDS + if (dtSeconds <= 0.0) continue + + rotation[0] += 0.5 * (a.x + b.x) * dtSeconds + rotation[1] += 0.5 * (a.y + b.y) * dtSeconds + rotation[2] += 0.5 * (a.z + b.z) * dtSeconds + + val magnitudeA2 = magnitudeSquared(a) + val magnitudeB2 = magnitudeSquared(b) + energyIntegral += 0.5 * (magnitudeA2 + magnitudeB2) * dtSeconds + peakVelocity = max(peakVelocity, sqrt(max(magnitudeA2, magnitudeB2))) + + val dx = (b.x - a.x).toDouble() / dtSeconds + val dy = (b.y - a.y).toDouble() / dtSeconds + val dz = (b.z - a.z).toDouble() / dtSeconds + jerkIntegral += (dx * dx + dy * dy + dz * dz) * dtSeconds + } + + val durationSeconds = coveredDurationNs.toDouble() * NS_TO_SECONDS + return GyroExposureWindow( + startTimestampNs = startTimestampNs, + endTimestampNs = endTimestampNs, + sampleCount = clipped.size, + integratedRotationRad = FloatArray(3) { rotation[it].toFloat() }, + angularEnergy = (energyIntegral / durationSeconds).toFloat(), + peakAngularVelocity = peakVelocity.toFloat(), + jerkEnergy = (jerkIntegral / durationSeconds).toFloat(), + coverageRatio = coverage, + ) + } + + private fun interpolateAt(samples: List, timestampNs: Long): GyroSample? { + if (timestampNs < samples.first().timestampNs || timestampNs > samples.last().timestampNs) return null + val exact = samples.binarySearchBy(timestampNs) { it.timestampNs } + if (exact >= 0) return samples[exact] + val insertionPoint = -exact - 1 + if (insertionPoint <= 0 || insertionPoint >= samples.size) return null + val before = samples[insertionPoint - 1] + val after = samples[insertionPoint] + val span = after.timestampNs - before.timestampNs + if (span <= 0L) return before.copy(timestampNs = timestampNs) + val fraction = (timestampNs - before.timestampNs).toDouble() / span.toDouble() + return GyroSample( + timestampNs = timestampNs, + x = lerp(before.x, after.x, fraction), + y = lerp(before.y, after.y, fraction), + z = lerp(before.z, after.z, fraction), + ) + } + + private fun magnitudeSquared(sample: GyroSample): Double { + return sample.x.toDouble() * sample.x + + sample.y.toDouble() * sample.y + + sample.z.toDouble() * sample.z + } + + private fun lerp(a: Float, b: Float, fraction: Double): Float { + return (a + (b - a) * fraction).toFloat() + } + + private const val NS_TO_SECONDS = 1.0e-9 +} diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index aaf5f950..403eee38 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -34,6 +34,7 @@ import com.hinnka.mycamera.processor.MultiFrameStacker import com.hinnka.mycamera.processor.RawHdrStackFrame import com.hinnka.mycamera.processor.RawNoiseModel import com.hinnka.mycamera.processor.RawStackResult +import com.hinnka.mycamera.processor.RawStackFrame import com.hinnka.mycamera.processor.YuvHdrStackFrame import com.hinnka.mycamera.processor.YuvHdrStackFrameRole import com.hinnka.mycamera.raw.DngEmbeddedProfile @@ -2621,6 +2622,7 @@ object GalleryManager { capturePreviewThumbnail: Bitmap? = null, frameExposureProducts: List = emptyList(), frameFocusDistances: List = emptyList(), + rawStackFrames: List = emptyList(), ) = withContext(Dispatchers.IO) { try { val photoDir = getPhotoDir(context, photoId, true) @@ -2678,11 +2680,29 @@ object GalleryManager { var currentUseSuperResolution = useSuperResolution val applyRawLensShading = resolveRawLensShadingCorrectionEnabled(context, metadata) + val effectiveRawStackFrames = if (rawStackFrames.size == images.size && + rawStackFrames.indices.all { rawStackFrames[it].image === images[it] } + ) { + rawStackFrames + } else { + images.mapIndexed { index, image -> + RawStackFrame( + image = image, + exposureProduct = frameExposureProducts.getOrNull(index) + ?.takeIf { it.isFinite() && it > 0.0 } + ?: 1.0, + focusDistanceDiopters = frameFocusDistances.getOrNull(index) + ?.takeIf { it.isFinite() } + ?: Float.NaN, + ) + } + } var rawStackResult = MultiFrameStacker.processBurstRaw( - images, stackCfaPattern, - currentUseSuperResolution, - superResolutionScale, - useGpuAcceleration, + frames = effectiveRawStackFrames, + cfaPattern = stackCfaPattern, + enableSuperResolution = currentUseSuperResolution, + superResolutionScale = superResolutionScale, + useGpuAcceleration = useGpuAcceleration, masterBlackLevel = stackBlackLevel, whiteLevel = stackWhiteLevel, whiteBalanceGains = rawMetadata.whiteBalanceGains, @@ -2692,8 +2712,6 @@ object GalleryManager { lensShadingWidth = rawMetadata.lensShadingMapWidth, lensShadingHeight = rawMetadata.lensShadingMapHeight, applyLensShadingCorrection = applyRawLensShading, - frameExposureProducts = frameExposureProducts, - frameFocusDistances = frameFocusDistances, ) val finalStackResult = rawStackResult ?: return@withContext @@ -3471,6 +3489,7 @@ object GalleryManager { capturePreviewThumbnail: Bitmap? = null, frameExposureProducts: List = emptyList(), frameFocusDistances: List = emptyList(), + rawStackFrames: List = emptyList(), ) = withContext(Dispatchers.IO) { when (val format = images[0].format) { ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> { @@ -3515,6 +3534,7 @@ object GalleryManager { capturePreviewThumbnail, frameExposureProducts, frameFocusDistances, + rawStackFrames, ) } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt index a2ced749..2a14e996 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt @@ -14,6 +14,7 @@ import com.hinnka.mycamera.raw.DngHdrProfileGainTableGenerator import com.hinnka.mycamera.raw.DngPhotonProfileGainTableGenerator import com.hinnka.mycamera.raw.DngPgtmDiagnostic import com.hinnka.mycamera.raw.RawProfileToneMapMode +import com.hinnka.mycamera.raw.RcdShaders import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog import java.nio.ByteBuffer @@ -42,6 +43,25 @@ class GlesRawStacker( debugConfig: RawStackDebugConfig = RawStackDebugConfig.Disabled, ) { private data class TextureLevel(val texture: Int, val width: Int, val height: Int) + private data class TemporalGraphSeedResources( + val texturesByFrame: IntArray, + val summariesByFrame: List, + val gridWidth: Int, + val gridHeight: Int, + val tileSpacing: Int, + ) + private data class AcceptedSuperResolutionFrame( + val frameIndex: Int, + val image: SafeImage, + val exposureScale: Float, + val registrationWeight: Float, + val detailWeight: Float, + val flowTexture: Int, + val robustnessTexture: Int, + val tileMaskTexture: Int, + val minFlowYPlanePx: Float, + val maxFlowYPlanePx: Float, + ) private data class ReadOutputTiming( val elapsedMs: Long, val glReadMs: Long, @@ -81,9 +101,6 @@ class GlesRawStacker( val phaseBinTotal: Int, val phaseBinSamples: List, ) { - val forceBaseUpscale: Boolean - get() = mode == "BASE_UPSCALE" - companion object { val Disabled = SuperResolutionOutputDecision( mode = "n/a", @@ -142,19 +159,22 @@ class GlesRawStacker( private val hwmfPrefilter = tuning.prefilter private val hwmfBlend = tuning.blend private val hwmfPostfilter = tuning.postfilter - private val hwmfHdr = tuning.hdr private val hwmfSr = tuning.superResolution private val hwmfDebug = debugConfig.normalized() private val registrationSetup = RawStackRegistrationResolver.resolve(width, height) private val registrationSummary = registrationSetup.toSummary() private val superResolutionEnabled = tuning.mode == RawStackMode.MFSR private val superResolutionScale = if (superResolutionEnabled) { - hwmfSr.internalScale.coerceIn(1.0f, 2.0f) + hwmfSr.outputScale.coerceIn(1.0f, hwmfSr.internalScale.coerceIn(1.0f, 2.0f)) } else { 1.0f } private val outputWidth = scaledRawDimension(width, superResolutionScale) private val outputHeight = scaledRawDimension(height, superResolutionScale) + private val superResolutionAccumulatorHeight = minOf( + outputHeight, + SUPER_RESOLUTION_STRIPE_ROWS + 2 * SUPER_RESOLUTION_SPATIAL_RADIUS, + ) private val rawCfaPeriod = when { cfaPattern >= 8 -> 8 cfaPattern >= 4 -> 4 @@ -181,12 +201,14 @@ class GlesRawStacker( private var gridHeight = 0 private var proxyProgram = 0 + private var trackingProxyProgram = 0 private var downsampleProgram = 0 private var alignProgram = 0 - private var hdrShortGlobalAlignProgram = 0 + private var flowReadbackProgram = 0 private var registrationGlobalAlignProgram = 0 private var lkRefineProgram = 0 private var smoothFlowProgram = 0 + private var copyScalarProgram = 0 private var structureProgram = 0 private var robustnessProgram = 0 private var tileMaskProgram = 0 @@ -196,11 +218,18 @@ class GlesRawStacker( private var normalizeProgram = 0 private var clearSuperResolutionAccumulatorProgram = 0 private var accumulateSuperResolutionProgram = 0 - private var computeSuperResolutionChannelRatioProgram = 0 private var normalizeSuperResolutionProgram = 0 + private var rcdStripePopulateProgram = 0 + private var rcdStripeStep1Program = 0 + private var rcdStripeStep2Program = 0 + private var rcdStripeStep3Program = 0 + private var rcdStripeStep40Program = 0 + private var rcdStripeStep41Program = 0 + private var rcdStripeStep42Program = 0 + private var rcdStripeStep43Program = 0 + private var hdrShortGlobalAlignProgram = 0 private var hdrRecoveryMaskProgram = 0 - private var hdrRecoveryDilateProgram = 0 - private var hdrRecoveryFeatherProgram = 0 + private var hdrRecoveryCoverageProgram = 0 private var pgtmStatsProgram = 0 private var diagnosticAlignmentProgram = 0 private var diagnosticFinalProgram = 0 @@ -222,22 +251,23 @@ class GlesRawStacker( private var robustnessTexture = 0 private var tileMaskTexture = 0 private var hdrRecoveryOrigMaskTexture = 0 - private var hdrRecoveryMaskTexture = 0 - private var hdrRecoveryScratchTexture = 0 - private var accumulatorTexture = 0 - private var accumulatorScratchTexture = 0 - private var currentAccumulatorTexture = 0 + private var hdrRecoveryCoverageTexture = 0 + private var accumulatorValueWeightTexture = 0 + private var accumulatorStatisticsTexture = 0 private var superResolutionAccumulatorTexture = 0 - private var superResolutionAccumulatorScratchTexture = 0 - private var currentSuperResolutionAccumulatorTexture = 0 - private var superResolutionBaseTexture = 0 - private var superResolutionChannelRatioTexture = 0 + private var superResolutionAccumulatorBwTexture = 0 + private var superResolutionAccumulatorBTexture = 0 + private var rcdStripeRawTexture = 0 + private var rcdStripeCapacityRows = 0 + private val rcdStripeBuffers = IntArray(9) private var outputTexture = 0 private var lensShadingTexture = 0 private var currentRegistrationTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) private var currentRegistrationSrTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) private var currentRegistrationSrWeight = 1.0f + private var currentRegistrationNrWeight = 1.0f private var currentRegistrationSrDetailWeight = 1.0f + private var currentTemporalFlowPhase: RegistrationTranslation? = null private var registrationEstimateCount = 0 private var registrationConfidenceSum = 0f private var registrationConfidenceMin = Int.MAX_VALUE @@ -305,39 +335,71 @@ class GlesRawStacker( "scaleMin=${frameExposureScales.minOrNull()?.formatScale()} " + "scaleMax=${frameExposureScales.maxOrNull()?.formatScale()}" } - images[0].use { - uploadRawTexture(it, refRaw, "reference") + var referenceTrackingTexture = 0 + uploadRawTexture(images[0], refRaw, "reference") + RawStackRuntimeDebug.i(TAG) { + "HWMF reference listIndex=0 frameNumber=${frames[0].frameNumber} " + + "sensorTimestampNs=${frames[0].sensorTimestampNs} " + + "imageTimestampNs=${images[0].timestamp} exposure=${frames[0].exposureProduct}" + } + if (frames.size >= MIN_TEMPORAL_GRAPH_FRAME_COUNT) { + val trackingScale = temporalTrackingLevelScale(frames.size) + val trackingWidth = scaledTrackingDimension(planeWidth, trackingScale) + val trackingHeight = scaledTrackingDimension(planeHeight, trackingScale) + referenceTrackingTexture = createTexture2D( + trackingWidth, + trackingHeight, + GLES30.GL_RGBA16F, + GLES30.GL_LINEAR, + ) + buildTrackingProxy( + rawTexture = refRaw, + outputTexture = referenceTrackingTexture, + outputWidth = trackingWidth, + outputHeight = trackingHeight, + levelScale = trackingScale, + exposureScale = 1f, + label = "reference", + ) } buildProxy(refRaw, refProxy, "reference") val refPyramid = createPyramid(refProxy) val curPyramid = createPyramid(curProxy) buildPyramid(refPyramid) + val temporalGraphSeeds = if (referenceTrackingTexture != 0) { + runCatching { + buildTemporalGraphSeeds( + frames = frames, + images = images, + frameExposureScales = frameExposureScales, + referenceTrackingTexture = referenceTrackingTexture, + ) + }.onFailure { error -> + PLog.w(TAG, "Temporal flow graph disabled after setup failure", error) + }.getOrNull() + } else { + null + } computeStructureTensor() currentRegistrationTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) currentRegistrationSrTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) currentRegistrationSrWeight = 1.0f + currentRegistrationNrWeight = 1.0f currentRegistrationSrDetailWeight = 1.0f + currentTemporalFlowPhase = RegistrationTranslation(0f, 0f) acceptedRegistrationTranslations.clear() acceptedSrRegistrationTranslations.clear() superResolutionPhaseTracker.reset() resetSuperResolutionDecisionStats() + val acceptedSuperResolutionFrames = ArrayList() clearAccumulator() - if (superResolutionEnabled) { - clearSuperResolutionAccumulator() - accumulateFrame(refRaw, isReference = true) - accumulateSuperResolutionFrame(refRaw, isReference = true) - } else { - accumulateFrame(refRaw, isReference = true) - } + accumulateFrame(refRaw, isReference = true) GlesGpuScheduler.yieldToUiRenderer() var alignedFrameCount = 0 for (index in 1 until images.size) { val frameFocusDistance = frames[index].focusDistanceDiopters - if (referenceFocusDistance.isFinite() && frameFocusDistance.isFinite() && - kotlin.math.abs(frameFocusDistance - referenceFocusDistance) > - hwmfBlend.focusDistanceRejectDeltaDiopters.coerceAtLeast(0f) - ) { + if (!isFocusCompatibleWithReference(frames.first(), frames[index])) { PLog.w( TAG, "Rejecting RAW stack frame $index due to focus breathing " + @@ -346,18 +408,26 @@ class GlesRawStacker( images[index].close() continue } - images[index].use { - uploadRawTexture(it, curRaw, "frame $index") - } + uploadRawTexture(images[index], curRaw, "frame $index") val exposureScale = frameExposureScales[index] buildProxy(curRaw, curProxy, "frame $index", exposureScale = exposureScale) buildPyramid(curPyramid) - alignCurrentToReference(refPyramid, curPyramid) + alignCurrentToReference( + reference = refPyramid, + current = curPyramid, + preAlignment = frames[index].preAlignmentToReference, + temporalGraphSeeds = temporalGraphSeeds, + frameIndex = index, + ) refineFlow() smoothFlow() computeRobustness() computeTileMask() - val registrationAccepted = estimateCurrentRegistration(refPyramid, curPyramid, frameIndex = index) + val registrationAccepted = if (temporalGraphSeeds != null) { + applyTemporalGraphFrameQuality(temporalGraphSeeds, frameIndex = index) + } else { + estimateCurrentRegistration(refPyramid, curPyramid, frameIndex = index) + } if (!registrationAccepted) { GlesGpuScheduler.yieldToUiRenderer() continue @@ -365,11 +435,18 @@ class GlesRawStacker( if (superResolutionEnabled) { accumulateFrame(curRaw, isReference = false, exposureScale = exposureScale) if (shouldAccumulateSuperResolutionFrame()) { - recordSuperResolutionDetailFrame(currentRegistrationSrDetailWeight) - accumulateSuperResolutionFrame( - rawTexture = curRaw, - isReference = false, + // Phase novelty is a ranking signal, not an admission gate. Temporal graph + // summaries may legitimately quantize the global phase to zero while the + // refined local flow still contains useful sub-pixel observations. + recordSuperResolutionDetailFrame( + max(currentRegistrationSrDetailWeight, currentRegistrationSrWeight * 0.35f), + ) + acceptedSuperResolutionFrames += cacheAcceptedSuperResolutionFrame( + frameIndex = index, + image = images[index], exposureScale = exposureScale, + registrationWeight = currentRegistrationNrWeight, + detailWeight = currentRegistrationSrDetailWeight, ) recordAccumulatedSuperResolutionPhase() } @@ -389,7 +466,10 @@ class GlesRawStacker( SuperResolutionOutputDecision.Disabled } if (superResolutionEnabled) { - normalizeSuperResolutionOutput(superResolutionDecision) + reconstructSuperResolutionStripes( + referenceImage = images[0], + acceptedFrames = acceptedSuperResolutionFrames, + ) } else { normalizeOutput() } @@ -488,13 +568,8 @@ class GlesRawStacker( val outputScales = normalFrames.map { hdrExposureScale(shortExposureProduct, validExposureProduct(it.exposureProduct)) } - - shortFrame.image.use { - uploadRawTexture(it, hdrShortRaw, "short highlight recovery") - } - normalFrames.first().image.use { - uploadRawTexture(it, refRaw, "normal reference") - } + uploadRawTexture(shortFrame.image, hdrShortRaw, "short highlight recovery") + uploadRawTexture(normalFrames.first().image, refRaw, "HDR normal reference") buildProxy(refRaw, refProxy, "normal reference", exposureScale = 1.0f) val refPyramid = createPyramid(refProxy) val curPyramid = createPyramid(curProxy) @@ -516,29 +591,27 @@ class GlesRawStacker( exposureScale = referenceOutputScale, hdrMode = true, ) - GlesGpuScheduler.waitForGpuCheckpoint(TAG, "hdr reference accumulation") + GlesGpuScheduler.waitForGpuCheckpoint(TAG, "hdr normal reference accumulation") - var alignedFrameCount = 0 - normalFrames.drop(1).forEachIndexed { index, frame -> - val frameIndex = index + 1 + var alignedFrameCount = 1 + normalFrames.drop(1).forEachIndexed { relativeIndex, frame -> + val frameIndex = relativeIndex + 1 val alignmentScale = alignmentScales[frameIndex] val outputScale = outputScales[frameIndex] - frame.image.use { - uploadRawTexture(it, curRaw, "normal frame $frameIndex") - } + uploadRawTexture(frame.image, curRaw, "normal frame $frameIndex") buildProxy(curRaw, curProxy, "normal frame $frameIndex", exposureScale = alignmentScale) buildPyramid(curPyramid) - alignCurrentToReference(refPyramid, curPyramid) + alignCurrentToReference( + reference = refPyramid, + current = curPyramid, + preAlignment = null, + frameIndex = frameIndex, + ) GlesGpuScheduler.waitForGpuCheckpoint(TAG, "hdr normal frame $frameIndex alignment") refineFlow() smoothFlow() computeRobustness() computeTileMask() - val registrationAccepted = estimateCurrentRegistration(refPyramid, curPyramid, frameIndex = frameIndex) - if (!registrationAccepted) { - GlesGpuScheduler.waitForGpuCheckpoint(TAG, "hdr normal frame $frameIndex registration rejected") - return@forEachIndexed - } accumulateFrame( rawTexture = curRaw, isReference = false, @@ -551,8 +624,7 @@ class GlesRawStacker( alignedFrameCount += 1 GlesGpuScheduler.waitForGpuCheckpoint(TAG, "hdr normal frame $frameIndex accumulation") } - - computeHdrRecoveryMask(shortToReferenceExposureScale = shortAlignmentScale) + computeHdrRecoveryMask() GlesGpuScheduler.yieldToUiRenderer() normalizeOutput( hdrMode = true, @@ -575,6 +647,7 @@ class GlesRawStacker( returned = true RawStackRuntimeDebug.i(TAG) { "GLES RAW HDR stacking completed in ${System.currentTimeMillis() - startTime}ms " + + "normalAligned=$alignedFrameCount/${normalFrames.size} " + "readback=${readTiming.elapsedMs}ms glRead=${readTiming.glReadMs}ms " + "copy=${readTiming.copyMs}ms alloc=${readTiming.allocMs}ms mode=${readTiming.mode}" } @@ -665,8 +738,10 @@ class GlesRawStacker( private fun initPrograms() { proxyProgram = linkComputeProgram(RAW_PROXY_COMPUTE_SHADER, "raw_proxy") + trackingProxyProgram = linkComputeProgram(RAW_TRACKING_PROXY_COMPUTE_SHADER, "raw_tracking_proxy") downsampleProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, DOWNSAMPLE_FRAGMENT_SHADER, "raw_downsample") alignProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, ALIGN_FRAGMENT_SHADER, "raw_align") + flowReadbackProgram = linkComputeProgram(FLOW_READBACK_COMPUTE_SHADER, "raw_flow_readback") lkRefineProgram = linkComputeProgram(LK_REFINE_COMPUTE_SHADER, "raw_lk_refine") smoothFlowProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, SMOOTH_FLOW_FRAGMENT_SHADER, "raw_smooth_flow") structureProgram = linkComputeProgram(STRUCTURE_COMPUTE_SHADER, "raw_structure") @@ -684,23 +759,32 @@ class GlesRawStacker( accumulateProgram = linkComputeProgram(ACCUMULATE_COMPUTE_SHADER, "raw_accumulate") normalizeProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, NORMALIZE_FRAGMENT_SHADER, "raw_normalize") if (superResolutionEnabled) { + copyScalarProgram = linkGraphicsProgram( + FULLSCREEN_VERTEX_SHADER, + COPY_SCALAR_FRAGMENT_SHADER, + "raw_copy_scalar", + ) clearSuperResolutionAccumulatorProgram = linkComputeProgram( - CLEAR_ACCUMULATOR_COMPUTE_SHADER, + CLEAR_SUPER_RESOLUTION_ACCUMULATOR_COMPUTE_SHADER, "raw_sr_clear_accumulator", ) accumulateSuperResolutionProgram = linkComputeProgram( - SUPER_RESOLUTION_ACCUMULATE_COMPUTE_SHADER, + SUPER_RESOLUTION_RCD_ACCUMULATE_COMPUTE_SHADER, "raw_sr_accumulate", ) - computeSuperResolutionChannelRatioProgram = linkComputeProgram( - SUPER_RESOLUTION_CHANNEL_RATIO_COMPUTE_SHADER, - "raw_sr_channel_ratio", - ) normalizeSuperResolutionProgram = linkGraphicsProgram( FULLSCREEN_VERTEX_SHADER, - SUPER_RESOLUTION_NORMALIZE_FRAGMENT_SHADER, + SUPER_RESOLUTION_NORMALIZE_RCD_FRAGMENT_SHADER, "raw_sr_normalize", ) + rcdStripePopulateProgram = linkComputeProgram(RCD_STRIPE_POPULATE_COMPUTE_SHADER, "raw_sr_rcd_populate") + rcdStripeStep1Program = linkComputeProgram(RcdShaders.STEP_1, "raw_sr_rcd_step1") + rcdStripeStep2Program = linkComputeProgram(RcdShaders.STEP_2, "raw_sr_rcd_step2") + rcdStripeStep3Program = linkComputeProgram(RcdShaders.STEP_3, "raw_sr_rcd_step3") + rcdStripeStep40Program = linkComputeProgram(RcdShaders.STEP_4_0, "raw_sr_rcd_step40") + rcdStripeStep41Program = linkComputeProgram(RcdShaders.STEP_4_1, "raw_sr_rcd_step41") + rcdStripeStep42Program = linkComputeProgram(RcdShaders.STEP_4_2, "raw_sr_rcd_step42") + rcdStripeStep43Program = linkComputeProgram(RcdShaders.STEP_4_3, "raw_sr_rcd_step43") } initDiagnosticPrograms() } @@ -716,15 +800,10 @@ class GlesRawStacker( HDR_RECOVERY_MASK_FRAGMENT_SHADER, "raw_hdr_recovery_mask", ) - hdrRecoveryDilateProgram = linkGraphicsProgram( + hdrRecoveryCoverageProgram = linkGraphicsProgram( FULLSCREEN_VERTEX_SHADER, - HDR_RECOVERY_DILATE_FRAGMENT_SHADER, - "raw_hdr_recovery_dilate", - ) - hdrRecoveryFeatherProgram = linkGraphicsProgram( - FULLSCREEN_VERTEX_SHADER, - HDR_RECOVERY_FEATHER_FRAGMENT_SHADER, - "raw_hdr_recovery_feather", + HDR_RECOVERY_COVERAGE_FRAGMENT_SHADER, + "raw_hdr_recovery_coverage", ) pgtmStatsProgram = linkComputeProgram(PGTM_STATS_COMPUTE_SHADER, "raw_hdr_pgtm_stats") } @@ -739,18 +818,14 @@ class GlesRawStacker( ) } if (superResolutionEnabled && RawStackRuntimeDebug.enabled) { - val accumulatorBytes = outputWidth.toLong() * outputHeight.toLong() * 8L - val accumulatorTotalBytes = accumulatorBytes * 2L + val accumulatorBytes = outputWidth.toLong() * superResolutionAccumulatorHeight.toLong() * 4L val baseAccumulatorBytes = width.toLong() * height.toLong() * 8L - val baseAccumulatorTotalBytes = baseAccumulatorBytes * 2L val baseOutputBytes = width.toLong() * height.toLong() * 2L val outputBytes = outputWidth.toLong() * outputHeight.toLong() * 2L RawStackRuntimeDebug.d(TAG) { "HWMF MFSR resources out=${outputWidth}x$outputHeight maxTex=$maxSize " + - "srAccumulator=${accumulatorBytes.mibString()}x2 " + - "srAccumulatorTotal=${accumulatorTotalBytes.mibString()} " + - "baseAccumulator=${baseAccumulatorBytes.mibString()}x2 " + - "baseAccumulatorTotal=${baseAccumulatorTotalBytes.mibString()} " + + "srAccumulatorStripe=${accumulatorBytes.mibString()} " + + "baseAccumulator=${baseAccumulatorBytes.mibString()} " + "baseOutput=${baseOutputBytes.mibString()} output=${outputBytes.mibString()}" } } @@ -791,31 +866,27 @@ class GlesRawStacker( robustnessTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_R32F, GLES30.GL_NEAREST) tileMaskTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_R16F, GLES30.GL_LINEAR) hdrRecoveryOrigMaskTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) - hdrRecoveryMaskTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_R16F, GLES30.GL_NEAREST) - hdrRecoveryScratchTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_R16F, GLES30.GL_NEAREST) - accumulatorTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) - accumulatorScratchTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) - currentAccumulatorTexture = accumulatorTexture + hdrRecoveryCoverageTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) + accumulatorValueWeightTexture = createTexture2D(width, height, GLES30.GL_R32UI, GLES30.GL_NEAREST) + accumulatorStatisticsTexture = createTexture2D(width, height, GLES30.GL_R32UI, GLES30.GL_NEAREST) if (superResolutionEnabled) { superResolutionAccumulatorTexture = createTexture2D( outputWidth, - outputHeight, - GLES30.GL_RGBA16F, + superResolutionAccumulatorHeight, + GLES30.GL_R32UI, GLES30.GL_NEAREST, ) - superResolutionAccumulatorScratchTexture = createTexture2D( + superResolutionAccumulatorBwTexture = createTexture2D( outputWidth, - outputHeight, - GLES30.GL_RGBA16F, + superResolutionAccumulatorHeight, + GLES30.GL_R32UI, GLES30.GL_NEAREST, ) - currentSuperResolutionAccumulatorTexture = superResolutionAccumulatorTexture - superResolutionBaseTexture = createTexture2D(width, height, GLES30.GL_RG8, GLES30.GL_NEAREST) - superResolutionChannelRatioTexture = createTexture2D( - planeWidth, - planeHeight, - GLES30.GL_RGBA16F, - GLES30.GL_LINEAR, + superResolutionAccumulatorBTexture = createTexture2D( + outputWidth, + superResolutionAccumulatorHeight, + GLES30.GL_R32UI, + GLES30.GL_NEAREST, ) } outputTexture = createTexture2D(outputWidth, outputHeight, GLES30.GL_RG8, GLES30.GL_NEAREST) @@ -874,31 +945,156 @@ class GlesRawStacker( } private fun uploadRawTexture(image: SafeImage, texture: Int, label: String) { + uploadRawTextureRows(image, texture, firstRow = 0, rowCount = height, label = label) + } + + private fun uploadRawTextureRows( + image: SafeImage, + texture: Int, + firstRow: Int, + rowCount: Int, + label: String, + ) { val plane = image.planes.firstOrNull() ?: throw IllegalArgumentException("$label has no RAW plane") + require(plane.pixelStride == 2) { + "$label RAW pixel stride ${plane.pixelStride} is not 16-bit unpackable" + } require(plane.rowStride >= width * 2) { "$label RAW row stride ${plane.rowStride} is smaller than width $width" } require(plane.rowStride % 2 == 0) { "$label RAW row stride must be 16-bit aligned: ${plane.rowStride}" } - val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply { position(0) } + require(firstRow in 0 until height && rowCount > 0 && firstRow + rowCount <= height) { + "$label RAW row band $firstRow+${rowCount} exceeds height $height" + } + val byteOffset = firstRow * plane.rowStride + val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply { position(byteOffset) } GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride / 2) + GLES30.glTexSubImage2D( + GLES30.GL_TEXTURE_2D, + 0, + 0, + firstRow, + width, + rowCount, + GLES30.GL_RED_INTEGER, + GLES30.GL_UNSIGNED_SHORT, + uploadBuffer, + ) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + checkGlError("uploadRawTexture $label") + } + + private fun ensureRcdStripeResources(capacityRows: Int) { + if (rcdStripeRawTexture != 0) return + rcdStripeCapacityRows = capacityRows.coerceIn(1, height) + rcdStripeRawTexture = createTexture2D( + width, + rcdStripeCapacityRows, + GLES30.GL_R16UI, + GLES30.GL_NEAREST, + ) + GLES31.glGenBuffers(rcdStripeBuffers.size, rcdStripeBuffers, 0) + val byteCount = width.toLong() * rcdStripeCapacityRows.toLong() * 4L + require(byteCount <= Int.MAX_VALUE) { "RCD stripe buffer exceeds GLES allocation range: $byteCount" } + rcdStripeBuffers.forEach { buffer -> + require(buffer != 0) { "Failed to allocate RCD stripe SSBO" } + buffers += buffer + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer) + GLES31.glBufferData( + GLES31.GL_SHADER_STORAGE_BUFFER, + byteCount.toInt(), + null, + GLES31.GL_DYNAMIC_DRAW, + ) + } + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + RawStackRuntimeDebug.i(TAG) { + "MFSR RCD stripe=${width}x$rcdStripeCapacityRows ssbo=${(byteCount * 9L).mibString()}" + } + } + + private fun uploadRcdRawStripe(image: SafeImage, firstRow: Int, rowCount: Int, label: String) { + require(rcdStripeRawTexture != 0 && rowCount <= rcdStripeCapacityRows) + val plane = image.planes.firstOrNull() ?: throw IllegalArgumentException("$label has no RAW plane") + require(plane.pixelStride == 2 && plane.rowStride >= width * 2 && plane.rowStride % 2 == 0) + require(firstRow >= 0 && rowCount > 0 && firstRow + rowCount <= height) + val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply { + position(firstRow * plane.rowStride) + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rcdStripeRawTexture) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride / 2) GLES30.glTexSubImage2D( GLES30.GL_TEXTURE_2D, 0, 0, 0, width, - height, + rowCount, GLES30.GL_RED_INTEGER, GLES30.GL_UNSIGNED_SHORT, uploadBuffer, ) GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - checkGlError("uploadRawTexture $label") + checkGlError("uploadRcdRawStripe $label") + } + + private fun bindRcdStripeBuffers() { + for (index in 0..7) { + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, index, rcdStripeBuffers[index]) + } + } + + private fun runRcdStripe(firstRow: Int, rowCount: Int, label: String) { + require(firstRow % 2 == 0) { "RCD stripe must preserve CFA row parity: $firstRow" } + bindRcdStripeBuffers() + GLES31.glUseProgram(rcdStripePopulateProgram) + bindTexture(rcdStripePopulateProgram, "uRawStripe", 0, rcdStripeRawTexture) + bindTexture(rcdStripePopulateProgram, "uLensShadingMap", 1, lensShadingTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uStripeSize"), width, rowCount) + GLES31.glUniform2i(GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uFullImageSize"), width, height) + GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uGlobalRowOffset"), firstRow) + GLES31.glUniform1i(GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uCfaPattern"), cfaPattern) + GLES31.glUniform4fv( + GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uBlackLevel"), + 1, + normalizedBlackLevel, + 0, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(rcdStripePopulateProgram, "uWhiteLevel"), + normalizedWhiteLevel, + ) + GLES31.glDispatchCompute(groupCount(width), groupCount(rowCount), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) + + fun dispatch(program: Int, halfWidth: Boolean, step: String) { + GLES31.glUseProgram(program) + GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, rowCount) + val cfaLocation = GLES31.glGetUniformLocation(program, "uCfaPattern") + if (cfaLocation >= 0) GLES31.glUniform1i(cfaLocation, cfaPattern) + GLES31.glDispatchCompute(groupCount(if (halfWidth) (width + 1) / 2 else width), groupCount(rowCount), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) + checkGlError("RCD stripe $step $label") + } + + dispatch(rcdStripeStep1Program, false, "step1") + dispatch(rcdStripeStep2Program, true, "step2") + dispatch(rcdStripeStep3Program, true, "step3") + dispatch(rcdStripeStep40Program, true, "step40") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 5, rcdStripeBuffers[8]) + dispatch(rcdStripeStep41Program, true, "step41") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdStripeBuffers[8]) + dispatch(rcdStripeStep42Program, true, "step42") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdStripeBuffers[4]) + dispatch(rcdStripeStep43Program, true, "step43") + GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) } private fun validExposureProduct(exposureProduct: Double): Double { @@ -1086,6 +1282,367 @@ class GlesRawStacker( GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) } + private fun buildTrackingProxy( + rawTexture: Int, + outputTexture: Int, + outputWidth: Int, + outputHeight: Int, + levelScale: Int, + exposureScale: Float, + label: String, + ) { + GLES31.glUseProgram(trackingProxyProgram) + bindTexture(trackingProxyProgram, "uRaw", 0, rawTexture) + bindImage(1, outputTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + setCommonUniforms(trackingProxyProgram) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(trackingProxyProgram, "uPlaneSize"), + planeWidth, + planeHeight, + ) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(trackingProxyProgram, "uTrackingSize"), + outputWidth, + outputHeight, + ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(trackingProxyProgram, "uLevelScale"), + levelScale, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(trackingProxyProgram, "uExposureScale"), + exposureScale, + ) + GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(outputHeight), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) + checkGlError("buildTrackingProxy $label") + } + + private fun buildTemporalGraphSeeds( + frames: List, + images: List, + frameExposureScales: List, + referenceTrackingTexture: Int, + ): TemporalGraphSeedResources? { + if (frames.size < MIN_TEMPORAL_GRAPH_FRAME_COUNT || images.size != frames.size) return null + val eligibleFrameIndices = frames.indices.filter { frameIndex -> + frameIndex == 0 || isFocusCompatibleWithReference(frames[0], frames[frameIndex]) + } + if (eligibleFrameIndices.size < MIN_TEMPORAL_GRAPH_FRAME_COUNT) { + deleteTexture(referenceTrackingTexture) + return null + } + val eligibleFrames = eligibleFrameIndices.map(frames::get) + val trackingScale = temporalTrackingLevelScale(frames.size) + val trackingWidth = scaledTrackingDimension(planeWidth, trackingScale) + val trackingHeight = scaledTrackingDimension(planeHeight, trackingScale) + val trackingTextures = IntArray(frames.size) + trackingTextures[0] = referenceTrackingTexture + var edgeOutputTexture = 0 + try { + eligibleFrameIndices.drop(1).forEach { index -> + val texture = createTexture2D( + trackingWidth, + trackingHeight, + GLES30.GL_RGBA16F, + GLES30.GL_LINEAR, + ) + trackingTextures[index] = texture + uploadRawTexture(images[index], curRaw, "temporal tracking frame $index") + buildTrackingProxy( + rawTexture = curRaw, + outputTexture = texture, + outputWidth = trackingWidth, + outputHeight = trackingHeight, + levelScale = trackingScale, + exposureScale = frameExposureScales[index], + label = "frame $index", + ) + GlesGpuScheduler.yieldToUiRenderer() + } + + val graph = RawTemporalAlignmentGraphBuilder.build( + frames = eligibleFrames, + referenceFrameIndex = 0, + includeSkipOne = eligibleFrames.size <= MAX_TEMPORAL_GRAPH_SKIP_FRAME_COUNT, + ) + val configuredGraphSpacing = max( + hwmfPrefilter.temporalGraphTileSpacing, + flowGridSpacing * MIN_TEMPORAL_GRAPH_SPACING_MULTIPLIER, + ) + val budgetSpacing = kotlin.math.ceil( + kotlin.math.sqrt( + planeWidth.toDouble() * planeHeight.toDouble() / MAX_TEMPORAL_GRAPH_TILES, + ), + ).toInt() + val graphTileSpacing = roundUpToMultiple( + max(configuredGraphSpacing, budgetSpacing), + flowGridSpacing, + ) + val graphGridWidth = (planeWidth + graphTileSpacing - 1) / graphTileSpacing + val graphGridHeight = (planeHeight + graphTileSpacing - 1) / graphTileSpacing + edgeOutputTexture = createTexture2D( + graphGridWidth, + graphGridHeight, + GLES30.GL_RGBA16F, + GLES30.GL_LINEAR, + ) + val edgeFields = ArrayList(graph.edges.size) + graph.edges.forEachIndexed { edgeIndex, edge -> + val fromFrameIndex = eligibleFrameIndices[edge.fromFrameIndex] + val toFrameIndex = eligibleFrameIndices[edge.toFrameIndex] + drawAlignment( + reference = TextureLevel( + trackingTextures[fromFrameIndex], + trackingWidth, + trackingHeight, + ), + current = TextureLevel( + trackingTextures[toFrameIndex], + trackingWidth, + trackingHeight, + ), + levelScale = trackingScale, + outputTexture = edgeOutputTexture, + outputGridWidth = graphGridWidth, + outputGridHeight = graphGridHeight, + outputTileSpacing = graphTileSpacing, + preAlignment = relativePreAlignment( + frames = frames, + fromFrameIndex = fromFrameIndex, + toFrameIndex = toFrameIndex, + ), + alignWindowSize = max( + hwmfPrefilter.alignWindowSize, + trackingScale * MIN_TEMPORAL_WINDOW_LEVEL_PIXELS, + ), + label = "temporal edge $edgeIndex", + ) + edgeFields += RawTemporalEdgeFlowField( + edge = edge, + width = graphGridWidth, + height = graphGridHeight, + values = readFlowTexture( + texture = edgeOutputTexture, + textureWidth = graphGridWidth, + textureHeight = graphGridHeight, + label = "temporal edge $edgeIndex", + ), + ) + GlesGpuScheduler.yieldToUiRenderer() + } + + val fallbackFlow = buildTemporalFallbackFlow( + frames = eligibleFrames, + gridWidth = graphGridWidth, + gridHeight = graphGridHeight, + tileSpacing = graphTileSpacing, + ) + val solved = RawTemporalFlowFieldSolver.solve( + graph = graph, + edgeFields = edgeFields, + fallbackFlowByFrame = fallbackFlow, + scoreFullConfidence = hwmfBlend.patchScoreFullConfidence, + scoreReject = hwmfBlend.patchScoreReject, + minimumObservationConfidence = hwmfPrefilter.temporalGraphMinimumSeedConfidence, + ) ?: return null + val seedTextures = IntArray(frames.size) + val summaries = MutableList(frames.size) { null } + for (localIndex in 1 until eligibleFrames.size) { + val originalIndex = eligibleFrameIndices[localIndex] + summaries[originalIndex] = RawTemporalFlowFieldSolver.summarize( + field = solved[localIndex].copy(frameIndex = originalIndex), + minimumConfidence = hwmfPrefilter.temporalGraphMinimumSeedConfidence, + ) + seedTextures[originalIndex] = uploadTemporalSeedTexture( + solved[localIndex].copy(frameIndex = originalIndex), + ) + } + RawStackRuntimeDebug.d(TAG) { + "Temporal flow graph frames=${eligibleFrames.size}/${frames.size} edges=${graph.edges.size} " + + "grid=${graphGridWidth}x$graphGridHeight spacing=$graphTileSpacing" + } + return TemporalGraphSeedResources( + texturesByFrame = seedTextures, + summariesByFrame = summaries, + gridWidth = graphGridWidth, + gridHeight = graphGridHeight, + tileSpacing = graphTileSpacing, + ) + } finally { + trackingTextures.filter { it != 0 }.forEach(::deleteTexture) + if (edgeOutputTexture != 0) deleteTexture(edgeOutputTexture) + } + } + + private fun relativePreAlignment( + frames: List, + fromFrameIndex: Int, + toFrameIndex: Int, + ): RawFramePreAlignment? { + val from = if (fromFrameIndex == 0) { + RawFramePreAlignment.Identity + } else { + frames[fromFrameIndex].preAlignmentToReference + } ?: return null + val to = if (toFrameIndex == 0) { + RawFramePreAlignment.Identity + } else { + frames[toFrameIndex].preAlignmentToReference + } ?: return null + return RawFramePreAlignment( + translationXPlanePx = to.translationXPlanePx - from.translationXPlanePx, + translationYPlanePx = to.translationYPlanePx - from.translationYPlanePx, + rotationDegrees = to.rotationDegrees - from.rotationDegrees, + confidence = minOf(from.confidence, to.confidence), + ) + } + + private fun isFocusCompatibleWithReference( + reference: RawStackFrame, + current: RawStackFrame, + ): Boolean { + val referenceFocus = reference.focusDistanceDiopters + val currentFocus = current.focusDistanceDiopters + return !referenceFocus.isFinite() || !currentFocus.isFinite() || + kotlin.math.abs(currentFocus - referenceFocus) <= + hwmfBlend.focusDistanceRejectDeltaDiopters.coerceAtLeast(0f) + } + + private fun buildTemporalFallbackFlow( + frames: List, + gridWidth: Int, + gridHeight: Int, + tileSpacing: Int, + ): List = List(frames.size) { frameIndex -> + val values = FloatArray(gridWidth * gridHeight * 4) + val preAlignment = if (frameIndex == 0) { + RawFramePreAlignment.Identity + } else { + frames[frameIndex].preAlignmentToReference + } + for (y in 0 until gridHeight) { + for (x in 0 until gridWidth) { + val planeX = minOf(planeWidth - 1, x * tileSpacing + tileSpacing / 2).toFloat() + val planeY = minOf(planeHeight - 1, y * tileSpacing + tileSpacing / 2).toFloat() + val flow = preAlignment?.flowAtPlanePosition( + planeX, + planeY, + planeWidth, + planeHeight, + ) ?: (0f to 0f) + val offset = (y * gridWidth + x) * 4 + values[offset] = flow.first + values[offset + 1] = flow.second + } + } + values + } + + private fun readFlowTexture( + texture: Int, + textureWidth: Int, + textureHeight: Int, + label: String, + ): FloatArray { + val floatCount = textureWidth * textureHeight * 4 + val byteCount = floatCount * 4 + val ids = IntArray(1) + GLES31.glGenBuffers(1, ids, 0) + val bufferId = ids[0] + if (bufferId == 0) throw IllegalStateException("Failed to allocate flow readback buffer") + try { + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId) + GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, byteCount, null, GLES31.GL_DYNAMIC_READ) + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + FLOW_READBACK_BUFFER_BINDING, + bufferId, + ) + GLES31.glUseProgram(flowReadbackProgram) + bindTexture(flowReadbackProgram, "uFlow", 0, texture) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(flowReadbackProgram, "uGridSize"), + textureWidth, + textureHeight, + ) + GLES31.glDispatchCompute(groupCount(textureWidth), groupCount(textureHeight), 1) + GLES31.glMemoryBarrier( + GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT, + ) + checkGlError("readFlowTexture dispatch $label") + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId) + val mapped = GLES31.glMapBufferRange( + GLES31.GL_SHADER_STORAGE_BUFFER, + 0, + byteCount, + GLES31.GL_MAP_READ_BIT, + ) as? ByteBuffer ?: throw IllegalStateException("Flow readback map failed for $label") + return try { + FloatArray(floatCount).also { values -> + mapped.order(ByteOrder.nativeOrder()).asFloatBuffer().get(values) + } + } finally { + GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) + } + } finally { + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, FLOW_READBACK_BUFFER_BINDING, 0) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + GLES31.glDeleteBuffers(1, intArrayOf(bufferId), 0) + } + } + + private fun uploadTemporalSeedTexture(field: RawTemporalFrameFlowField): Int { + val texture = createTexture2D( + field.width, + field.height, + GLES30.GL_RGBA16F, + GLES30.GL_LINEAR, + ) + val buffer = ByteBuffer.allocateDirect(field.values.size * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + .apply { + put(field.values) + position(0) + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glTexSubImage2D( + GLES30.GL_TEXTURE_2D, + 0, + 0, + 0, + field.width, + field.height, + GLES30.GL_RGBA, + GLES30.GL_FLOAT, + buffer, + ) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + checkGlError("uploadTemporalSeedTexture frame ${field.frameIndex}") + return texture + } + + private fun temporalTrackingLevelScale(frameCount: Int): Int { + var scale = 1 shl max(alignLevel, MIN_TEMPORAL_TRACKING_LEVEL) + while (scale < MAX_TEMPORAL_TRACKING_SCALE) { + val trackingPixels = scaledTrackingDimension(planeWidth, scale).toLong() * + scaledTrackingDimension(planeHeight, scale) + val totalBytes = trackingPixels * frameCount.coerceAtLeast(1) * TRACKING_TEXTURE_BYTES_PER_PIXEL + if (totalBytes <= MAX_TEMPORAL_TRACKING_BYTES) break + scale *= 2 + } + return scale + } + + private fun scaledTrackingDimension(dimension: Int, scale: Int): Int = + max(1, (dimension + scale - 1) / scale) + + private fun roundUpToMultiple(value: Int, multiple: Int): Int { + val safeMultiple = multiple.coerceAtLeast(1) + return ((value.coerceAtLeast(1) + safeMultiple - 1) / safeMultiple) * safeMultiple + } + private fun computeStructureTensor() { GLES31.glUseProgram(structureProgram) bindTexture(structureProgram, "uProxy", 0, refProxy) @@ -1098,141 +1655,115 @@ class GlesRawStacker( checkGlError("computeStructureTensor") } - private fun alignCurrentToReference(reference: List, current: List) { + private fun alignCurrentToReference( + reference: List, + current: List, + preAlignment: RawFramePreAlignment? = null, + temporalGraphSeeds: TemporalGraphSeedResources? = null, + frameIndex: Int = -1, + ) { val levelIndex = alignLevel.coerceAtMost(reference.lastIndex).coerceAtMost(current.lastIndex) val ref = reference[levelIndex] val cur = current[levelIndex] - bindFramebufferOutput(flowTexture, "alignCurrentToReference") - GLES30.glViewport(0, 0, gridWidth, gridHeight) + val graphSeedTexture = temporalGraphSeeds + ?.texturesByFrame + ?.getOrNull(frameIndex) + ?.takeIf { it != 0 } + drawAlignment( + reference = ref, + current = cur, + levelScale = 1 shl levelIndex, + outputTexture = flowTexture, + outputGridWidth = gridWidth, + outputGridHeight = gridHeight, + outputTileSpacing = flowGridSpacing, + preAlignment = preAlignment, + graphSeedTexture = graphSeedTexture, + graphSeedGridWidth = temporalGraphSeeds?.gridWidth ?: 1, + graphSeedGridHeight = temporalGraphSeeds?.gridHeight ?: 1, + graphSeedTileSpacing = temporalGraphSeeds?.tileSpacing ?: 1, + label = "alignCurrentToReference", + ) + } + + private fun drawAlignment( + reference: TextureLevel, + current: TextureLevel, + levelScale: Int, + outputTexture: Int, + outputGridWidth: Int, + outputGridHeight: Int, + outputTileSpacing: Int, + preAlignment: RawFramePreAlignment?, + graphSeedTexture: Int? = null, + graphSeedGridWidth: Int = 1, + graphSeedGridHeight: Int = 1, + graphSeedTileSpacing: Int = 1, + alignWindowSize: Int = hwmfPrefilter.alignWindowSize, + label: String, + ) { + bindFramebufferOutput(outputTexture, label) + GLES30.glViewport(0, 0, outputGridWidth, outputGridHeight) GLES30.glUseProgram(alignProgram) - bindTexture(alignProgram, "uReference", 0, ref.texture) - bindTexture(alignProgram, "uCurrent", 1, cur.texture) - GLES31.glUniform2i(GLES31.glGetUniformLocation(alignProgram, "uLevelSize"), ref.width, ref.height) - GLES31.glUniform2i(GLES31.glGetUniformLocation(alignProgram, "uGridSize"), gridWidth, gridHeight) - GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uTileSize"), flowGridSpacing) - GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uAlignWindowSize"), hwmfPrefilter.alignWindowSize) - GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uLevelScale"), 1 shl levelIndex) + bindTexture(alignProgram, "uReference", 0, reference.texture) + bindTexture(alignProgram, "uCurrent", 1, current.texture) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(alignProgram, "uLevelSize"), + reference.width, + reference.height, + ) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(alignProgram, "uGridSize"), + outputGridWidth, + outputGridHeight, + ) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uTileSize"), outputTileSpacing) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uAlignWindowSize"), alignWindowSize) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uLevelScale"), levelScale) GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uSearchRadius"), hwmfPrefilter.alignSearchRadiusLevel) GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uSampleStep"), hwmfPrefilter.alignSampleStep) GLES31.glUniform1f(GLES31.glGetUniformLocation(alignProgram, "uCoveragePenalty"), hwmfPrefilter.alignCoveragePenalty) GLES31.glUniform1f(GLES31.glGetUniformLocation(alignProgram, "uShiftPenalty"), hwmfPrefilter.alignShiftPenalty) - GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) - finishFramebufferPass("alignCurrentToReference") - } - - private fun alignHdrShortToReference(reference: List, shortFrame: List) { - val levelIndex = alignLevel.coerceAtMost(reference.lastIndex).coerceAtMost(shortFrame.lastIndex) - val ref = reference[levelIndex] - val cur = shortFrame[levelIndex] - val minLevelSide = minOf(ref.width, ref.height) - val searchRadius = minOf(hwmfHdr.shortGlobalSearchRadiusLevel, max(1, minLevelSide / 6)) - val sampleBorder = minOf(hwmfHdr.shortGlobalSampleBorder, max(1, minLevelSide / 5)) - val scoreSide = searchRadius * 2 + 1 - val scoreCount = scoreSide * scoreSide - val floatCount = scoreCount * HDR_SHORT_ALIGNMENT_SCORE_STRIDE - val byteCount = floatCount * 4 - val buffers = IntArray(1) - GLES31.glGenBuffers(1, buffers, 0) - val scoreBufferId = buffers[0] - if (scoreBufferId == 0) { - writeHdrShortAlignmentTexture(0f, 0f) - return - } - try { - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, scoreBufferId) - GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, byteCount, null, GLES31.GL_DYNAMIC_READ) - GLES31.glBindBufferBase( - GLES31.GL_SHADER_STORAGE_BUFFER, - HDR_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING, - scoreBufferId, - ) - GLES31.glUseProgram(hdrShortGlobalAlignProgram) - bindTexture(hdrShortGlobalAlignProgram, "uReference", 0, ref.texture) - bindTexture(hdrShortGlobalAlignProgram, "uCurrent", 1, cur.texture) - GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uLevelSize"), ref.width, ref.height) - GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uLevelScale"), 1 shl levelIndex) - GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSearchRadius"), searchRadius) - GLES31.glUniform1i( - GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSampleStep"), - hwmfHdr.shortGlobalSampleStep, - ) - GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSampleBorder"), sampleBorder) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uCoveragePenalty"), - hwmfHdr.shortGlobalCoveragePenalty, - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uShiftPenalty"), - hwmfHdr.shortGlobalShiftPenalty, - ) - GLES31.glDispatchCompute(scoreSide, scoreSide, 1) - GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT) - checkGlError("alignHdrShortToReference dispatch") - - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, scoreBufferId) - val mapped = GLES31.glMapBufferRange( - GLES31.GL_SHADER_STORAGE_BUFFER, - 0, - byteCount, - GLES31.GL_MAP_READ_BIT - ) ?: throw IllegalStateException("HDR short alignment score buffer map failed") - val scores = try { - FloatArray(floatCount).also { values -> - val byteBuffer = mapped as? ByteBuffer - ?: throw IllegalStateException("HDR short alignment score buffer is not ByteBuffer") - byteBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer().get(values) - } - } finally { - GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) - } - var bestScore = Float.POSITIVE_INFINITY - var bestDx = 0f - var bestDy = 0f - for (index in 0 until scoreCount) { - val offset = index * HDR_SHORT_ALIGNMENT_SCORE_STRIDE - val score = scores[offset + 2] - if (score.isFinite() && score < bestScore) { - bestScore = score - bestDx = scores[offset] - bestDy = scores[offset + 1] - } - } - writeHdrShortAlignmentTexture(bestDx, bestDy) - } catch (e: Exception) { - PLog.w(TAG, "Failed to compute HDR short global alignment", e) - writeHdrShortAlignmentTexture(0f, 0f) - } finally { - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, HDR_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING, 0) - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) - GLES31.glDeleteBuffers(1, intArrayOf(scoreBufferId), 0) - } - } - - private fun writeHdrShortAlignmentTexture(dx: Float, dy: Float) { - val buffer = ByteBuffer.allocateDirect(4 * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer() - .apply { - put(dx) - put(dy) - put(0f) - put(0f) - position(0) - } - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdrShortAlignmentTexture) - GLES30.glTexSubImage2D( - GLES30.GL_TEXTURE_2D, - 0, - 0, - 0, - 1, - 1, - GLES30.GL_RGBA, - GLES30.GL_FLOAT, - buffer + val seed = preAlignment?.takeIf { it.isUsable } + GLES31.glUniform2f( + GLES31.glGetUniformLocation(alignProgram, "uInitialTranslation"), + seed?.translationXPlanePx ?: 0f, + seed?.translationYPlanePx ?: 0f, ) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - checkGlError("writeHdrShortAlignmentTexture") + GLES31.glUniform1f( + GLES31.glGetUniformLocation(alignProgram, "uInitialRotationRadians"), + Math.toRadians((seed?.rotationDegrees ?: 0f).toDouble()).toFloat(), + ) + GLES31.glUniform2f( + GLES31.glGetUniformLocation(alignProgram, "uPlaneCenter"), + (planeWidth - 1) * 0.5f, + (planeHeight - 1) * 0.5f, + ) + val useGraphSeed = graphSeedTexture != null + graphSeedTexture?.let { texture -> bindTexture(alignProgram, "uGraphSeed", 2, texture) } + GLES31.glUniform1i( + GLES31.glGetUniformLocation(alignProgram, "uUseGraphSeed"), + if (useGraphSeed) 1 else 0, + ) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(alignProgram, "uGraphGridSize"), + graphSeedGridWidth, + graphSeedGridHeight, + ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(alignProgram, "uGraphTileSize"), + graphSeedTileSpacing, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(alignProgram, "uGraphSeedConfidenceMin"), + hwmfPrefilter.temporalGraphMinimumSeedConfidence, + ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(alignProgram, "uGraphRefineSearchRadius"), + hwmfPrefilter.temporalGraphRefineSearchRadiusLevel.coerceAtLeast(0), + ) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass(label) } private fun refineFlow() { @@ -1284,6 +1815,88 @@ class GlesRawStacker( finishFramebufferPass(label) } + private fun copyScalarTexture( + input: Int, + output: Int, + copyWidth: Int, + copyHeight: Int, + label: String, + ) { + bindFramebufferOutput(output, label) + GLES30.glViewport(0, 0, copyWidth, copyHeight) + GLES30.glUseProgram(copyScalarProgram) + bindTexture(copyScalarProgram, "uInput", 0, input) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(copyScalarProgram, "uImageSize"), + copyWidth, + copyHeight, + ) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass(label) + } + + private fun cacheAcceptedSuperResolutionFrame( + frameIndex: Int, + image: SafeImage, + exposureScale: Float, + registrationWeight: Float, + detailWeight: Float, + ): AcceptedSuperResolutionFrame { + val cachedFlow = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR) + val cachedRobustness = createTexture2D(planeWidth, planeHeight, GLES30.GL_R8, GLES30.GL_NEAREST) + val cachedTileMask = createTexture2D(gridWidth, gridHeight, GLES30.GL_R16F, GLES30.GL_LINEAR) + RawStackRuntimeDebug.d(TAG) { + val cacheBytes = planeWidth.toLong() * planeHeight + + gridWidth.toLong() * gridHeight * (8L + 2L) + "Cache MFSR frame=$frameIndex alignment=${cacheBytes.mibString()} " + + "robustness=R8 flow=RGBA16F tile=R16F" + } + copyFlow(flowTexture, cachedFlow, "cache MFSR flow frame $frameIndex") + copyScalarTexture( + robustnessTexture, + cachedRobustness, + planeWidth, + planeHeight, + "cache MFSR robustness frame $frameIndex", + ) + copyScalarTexture( + tileMaskTexture, + cachedTileMask, + gridWidth, + gridHeight, + "cache MFSR tile mask frame $frameIndex", + ) + val flowValues = readFlowTexture( + texture = cachedFlow, + textureWidth = gridWidth, + textureHeight = gridHeight, + label = "cache MFSR flow bounds frame $frameIndex", + ) + var minFlowY = 0f + var maxFlowY = 0f + var index = 1 + while (index < flowValues.size) { + val flowY = flowValues[index] + if (flowY.isFinite()) { + minFlowY = minOf(minFlowY, flowY) + maxFlowY = maxOf(maxFlowY, flowY) + } + index += 4 + } + return AcceptedSuperResolutionFrame( + frameIndex = frameIndex, + image = image, + exposureScale = exposureScale, + registrationWeight = registrationWeight.coerceIn(0f, 1f), + detailWeight = detailWeight.coerceIn(0f, 1f), + flowTexture = cachedFlow, + robustnessTexture = cachedRobustness, + tileMaskTexture = cachedTileMask, + minFlowYPlanePx = minFlowY, + maxFlowYPlanePx = maxFlowY, + ) + } + private fun computeRobustness() { GLES31.glUseProgram(robustnessProgram) bindTexture(robustnessProgram, "uReference", 0, refProxy) @@ -1351,6 +1964,7 @@ class GlesRawStacker( currentRegistrationTransform = acceptance.transform currentRegistrationSrTransform = acceptance.srTransform val srTranslation = registrationTranslation(currentRegistrationSrTransform) + currentTemporalFlowPhase = srTranslation val srPhaseNovelty = if (acceptance.srWeight > 0f && srTranslation != null) { superResolutionPhaseTracker.noveltyWeight(srTranslation.dx, srTranslation.dy) } else { @@ -1363,6 +1977,7 @@ class GlesRawStacker( recordRegistrationEstimate(estimate, currentRegistrationTransform) } val accepted = acceptance.accepted + currentRegistrationNrWeight = if (accepted) 1.0f else 0.0f if (hwmfDebug.logCompactSummary) { val candidateTranslation = registrationTranslation(estimate.candidateTransform) PLog.d( @@ -1396,6 +2011,70 @@ class GlesRawStacker( return accepted } + private fun applyTemporalGraphFrameQuality( + resources: TemporalGraphSeedResources, + frameIndex: Int, + ): Boolean { + val summary = resources.summariesByFrame.getOrNull(frameIndex) + currentRegistrationTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) + currentRegistrationSrTransform = registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) + if (summary == null) { + currentRegistrationSrWeight = 0f + currentRegistrationNrWeight = 0f + currentRegistrationSrDetailWeight = 0f + currentTemporalFlowPhase = null + return false + } + val phase = RegistrationTranslation( + dx = summary.medianDxPlanePx * 2f, + dy = summary.medianDyPlanePx * 2f, + ) + currentTemporalFlowPhase = phase + val accepted = summary.validTileFraction >= hwmfPrefilter.temporalGraphFrameMinCoverage && + summary.meanConfidence >= hwmfPrefilter.temporalGraphFrameMinMeanConfidence && + summary.coveredQuadrants >= hwmfPrefilter.temporalGraphFrameMinQuadrants.coerceIn(1, 4) && + summary.residualP90PlanePx <= hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx + val coverageWeight = smoothStep( + hwmfPrefilter.temporalGraphFrameMinCoverage, + max(hwmfPrefilter.temporalGraphFrameMinCoverage * 3f, 0.35f), + summary.validTileFraction, + ) + val confidenceWeight = smoothStep( + hwmfPrefilter.temporalGraphFrameMinMeanConfidence, + max(hwmfPrefilter.temporalGraphFrameMinMeanConfidence * 3f, 0.20f), + summary.meanConfidence, + ) + val residualWeight = 1f - smoothStep( + hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx * 0.5f, + hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx, + summary.residualP90PlanePx, + ) + val spatialWeight = summary.coveredQuadrants / 4f + val frameWeight = minOf( + coverageWeight, + confidenceWeight, + residualWeight, + spatialWeight, + ).coerceIn(0f, 1f) + val phaseNovelty = if (accepted) { + superResolutionPhaseTracker.noveltyWeight(phase.dx, phase.dy) + } else { + 0f + } + currentRegistrationSrWeight = if (accepted) frameWeight else 0f + currentRegistrationNrWeight = if (accepted) frameWeight else 0f + currentRegistrationSrDetailWeight = currentRegistrationSrWeight * phaseNovelty + RawStackRuntimeDebug.d(TAG) { + "Temporal frame=$frameIndex accepted=$accepted tiles=${summary.validTileCount}/" + + "${summary.totalTileCount} quadrants=${summary.coveredQuadrants} " + + "confidence=${summary.meanConfidence.formatWeight()} " + + "resP90=${summary.residualP90PlanePx.formatPx()} " + + "phase=[${phase.dx.formatPx()} ${phase.dy.formatPx()}] " + + "srWeight=${currentRegistrationSrWeight.formatWeight()}" + } + return accepted + } + private fun resolveRegistrationAcceptance( estimate: RawStackRegistrationEstimate, seedTranslation: RegistrationTranslation?, @@ -1757,14 +2436,14 @@ class GlesRawStacker( } private fun shouldAccumulateSuperResolutionFrame(): Boolean { - if (currentRegistrationSrWeight <= 0f) return false - val translation = registrationTranslation(currentRegistrationSrTransform) ?: return false - return superResolutionPhaseTracker.isUnoccupiedBin(translation.dx, translation.dy) || - currentRegistrationSrDetailWeight >= hwmfSr.accumulationMinPhaseWeight.coerceIn(0f, 1f) + // Registration/robustness decide whether a frame is safe. Phase novelty only modulates + // its SR contribution; using it as a hard gate makes a zero-quantized temporal graph reject + // every otherwise valid frame (all frames land in the reference phase bin). + return currentRegistrationNrWeight > 0f } private fun recordAccumulatedSuperResolutionPhase() { - val translation = registrationTranslation(currentRegistrationSrTransform) ?: return + val translation = currentTemporalFlowPhase ?: return superResolutionPhaseTracker.record(translation.dx, translation.dy) } @@ -1920,22 +2599,29 @@ class GlesRawStacker( referencePyramid: List, currentPyramid: List, seedShiftPlane: FloatArray, + searchRadiusOverride: Int? = null, + sampleStepOverride: Int? = null, + sampleBorderOverride: Int? = null, + coveragePenaltyOverride: Float? = null, + shiftPenaltyOverride: Float? = null, ): List? { val levelIndex = 0.coerceAtMost(referencePyramid.lastIndex).coerceAtMost(currentPyramid.lastIndex) val reference = referencePyramid[levelIndex] val current = currentPyramid[levelIndex] val minLevelSide = minOf(reference.width, reference.height) val searchRadius = minOf( - max(3, hwmfPrefilter.alignSearchRadiusLevel.coerceAtLeast(1)), + searchRadiusOverride?.coerceAtLeast(1) + ?: max(3, hwmfPrefilter.alignSearchRadiusLevel.coerceAtLeast(1)), max(1, minLevelSide / 6), ) val scoreSide = searchRadius * 2 + 1 val scoreCount = scoreSide * scoreSide if (scoreCount <= 0 || registrationGlobalAlignProgram == 0) return null - val sampleStep = max(2, hwmfPrefilter.alignSampleStep * 4) + val sampleStep = sampleStepOverride?.coerceAtLeast(1) + ?: max(2, hwmfPrefilter.alignSampleStep * 4) val sampleBorder = minOf( - max(8, hwmfPrefilter.alignWindowSize), + sampleBorderOverride?.coerceAtLeast(1) ?: max(8, hwmfPrefilter.alignWindowSize), max(1, minLevelSide / 5), ) val floatCount = scoreCount * REGISTRATION_GLOBAL_SCORE_STRIDE @@ -1986,11 +2672,11 @@ class GlesRawStacker( ) GLES31.glUniform1f( GLES31.glGetUniformLocation(registrationGlobalAlignProgram, "uCoveragePenalty"), - hwmfPrefilter.alignCoveragePenalty, + coveragePenaltyOverride ?: hwmfPrefilter.alignCoveragePenalty, ) GLES31.glUniform1f( GLES31.glGetUniformLocation(registrationGlobalAlignProgram, "uShiftPenalty"), - hwmfPrefilter.alignShiftPenalty, + shiftPenaltyOverride ?: hwmfPrefilter.alignShiftPenalty, ) GLES31.glDispatchCompute(scoreSide, scoreSide, 1) GLES31.glMemoryBarrier( @@ -2208,26 +2894,27 @@ class GlesRawStacker( private fun clearAccumulator() { GLES31.glUseProgram(clearAccumulatorProgram) - bindImage(0, accumulatorTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + bindImage(0, accumulatorValueWeightTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(1, accumulatorStatisticsTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) GLES31.glUniform2i(GLES31.glGetUniformLocation(clearAccumulatorProgram, "uImageSize"), width, height) GLES31.glDispatchCompute(groupCount(width), groupCount(height), 1) GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("clearAccumulator") - currentAccumulatorTexture = accumulatorTexture } private fun clearSuperResolutionAccumulator() { GLES31.glUseProgram(clearSuperResolutionAccumulatorProgram) - bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(1, superResolutionAccumulatorBwTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(2, superResolutionAccumulatorBTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) GLES31.glUniform2i( GLES31.glGetUniformLocation(clearSuperResolutionAccumulatorProgram, "uImageSize"), outputWidth, - outputHeight, + superResolutionAccumulatorHeight, ) - GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(outputHeight), 1) + GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(superResolutionAccumulatorHeight), 1) GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("clearSuperResolutionAccumulator") - currentSuperResolutionAccumulatorTexture = superResolutionAccumulatorTexture } private fun accumulateFrame( @@ -2236,11 +2923,6 @@ class GlesRawStacker( exposureScale: Float = 1.0f, hdrMode: Boolean = false, ) { - val outputAccumulator = if (currentAccumulatorTexture == accumulatorTexture) { - accumulatorScratchTexture - } else { - accumulatorTexture - } GLES31.glUseProgram(accumulateProgram) bindTexture(accumulateProgram, "uInputRaw", 0, rawTexture) bindTexture(accumulateProgram, "uFlowGrid", 1, flowTexture) @@ -2248,8 +2930,8 @@ class GlesRawStacker( bindTexture(accumulateProgram, "uTileMask", 3, tileMaskTexture) bindTexture(accumulateProgram, "uKernel", 4, kernelTexture) bindTexture(accumulateProgram, "uLensShadingMap", 5, lensShadingTexture) - bindTexture(accumulateProgram, "uAccumulatorInput", 6, currentAccumulatorTexture) - bindImage(0, outputAccumulator, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + bindImage(0, accumulatorValueWeightTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) + bindImage(1, accumulatorStatisticsTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) setCommonUniforms(accumulateProgram) GLES31.glUniform2i(GLES31.glGetUniformLocation(accumulateProgram, "uImageSize"), width, height) GLES31.glUniform2i(GLES31.glGetUniformLocation(accumulateProgram, "uPlaneSize"), planeWidth, planeHeight) @@ -2280,28 +2962,140 @@ class GlesRawStacker( } GLES31.glMemoryBarrier(GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("accumulateFrame") - currentAccumulatorTexture = outputAccumulator + } + + private fun alignHdrShortToReference(reference: List, shortFrame: List) { + val levelIndex = HDR_123_ALIGN_LEVEL.coerceAtMost(reference.lastIndex).coerceAtMost(shortFrame.lastIndex) + val ref = reference[levelIndex] + val cur = shortFrame[levelIndex] + val minLevelSide = minOf(ref.width, ref.height) + val searchRadius = minOf(HDR_123_SHORT_GLOBAL_SEARCH_RADIUS_LEVEL, max(1, minLevelSide / 6)) + val sampleBorder = minOf(HDR_123_SHORT_GLOBAL_SAMPLE_BORDER, max(1, minLevelSide / 5)) + val scoreSide = searchRadius * 2 + 1 + val scoreCount = scoreSide * scoreSide + val floatCount = scoreCount * HDR_123_SHORT_ALIGNMENT_SCORE_STRIDE + val byteCount = floatCount * 4 + val ids = IntArray(1) + GLES31.glGenBuffers(1, ids, 0) + val scoreBufferId = ids[0] + if (scoreBufferId == 0) { + writeHdrShortAlignmentTexture(0f, 0f) + return + } + try { + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, scoreBufferId) + GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, byteCount, null, GLES31.GL_DYNAMIC_READ) + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + HDR_123_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING, + scoreBufferId, + ) + GLES31.glUseProgram(hdrShortGlobalAlignProgram) + bindTexture(hdrShortGlobalAlignProgram, "uReference", 0, ref.texture) + bindTexture(hdrShortGlobalAlignProgram, "uCurrent", 1, cur.texture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uLevelSize"), ref.width, ref.height) + GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uLevelScale"), 1 shl levelIndex) + GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSearchRadius"), searchRadius) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSampleStep"), + HDR_123_SHORT_GLOBAL_SAMPLE_STEP, + ) + GLES31.glUniform1i(GLES31.glGetUniformLocation(hdrShortGlobalAlignProgram, "uSampleBorder"), sampleBorder) + GLES31.glDispatchCompute(scoreSide, scoreSide, 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT) + checkGlError("alignHdrShortToReference dispatch") + + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, scoreBufferId) + val mapped = GLES31.glMapBufferRange( + GLES31.GL_SHADER_STORAGE_BUFFER, + 0, + byteCount, + GLES31.GL_MAP_READ_BIT, + ) ?: throw IllegalStateException("HDR short alignment score buffer map failed") + val scores = try { + FloatArray(floatCount).also { values -> + val byteBuffer = mapped as? ByteBuffer + ?: throw IllegalStateException("HDR short alignment score buffer is not ByteBuffer") + byteBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer().get(values) + } + } finally { + GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) + } + var bestScore = Float.POSITIVE_INFINITY + var bestDx = 0f + var bestDy = 0f + for (index in 0 until scoreCount) { + val offset = index * HDR_123_SHORT_ALIGNMENT_SCORE_STRIDE + val score = scores[offset + 2] + if (score.isFinite() && score < bestScore) { + bestScore = score + bestDx = scores[offset] + bestDy = scores[offset + 1] + } + } + writeHdrShortAlignmentTexture(bestDx, bestDy) + } catch (e: Exception) { + PLog.w(TAG, "Failed to compute HDR short global alignment", e) + writeHdrShortAlignmentTexture(0f, 0f) + } finally { + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, HDR_123_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING, 0) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + GLES31.glDeleteBuffers(1, intArrayOf(scoreBufferId), 0) + } + } + + private fun writeHdrShortAlignmentTexture(dx: Float, dy: Float) { + val buffer = ByteBuffer.allocateDirect(4 * 4) + .order(ByteOrder.nativeOrder()) + .asFloatBuffer() + .apply { + put(dx) + put(dy) + put(0f) + put(0f) + position(0) + } + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, hdrShortAlignmentTexture) + GLES30.glTexSubImage2D( + GLES30.GL_TEXTURE_2D, + 0, + 0, + 0, + 1, + 1, + GLES30.GL_RGBA, + GLES30.GL_FLOAT, + buffer, + ) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + checkGlError("writeHdrShortAlignmentTexture") } private fun accumulateSuperResolutionFrame( - rawTexture: Int, isReference: Boolean, + sourceRowOffset: Int, + sourceRowCount: Int, exposureScale: Float = 1.0f, + frameFlowTexture: Int = flowTexture, + frameRobustnessTexture: Int = robustnessTexture, + frameTileMaskTexture: Int = tileMaskTexture, + registrationWeight: Float = currentRegistrationSrWeight, + detailWeight: Float = currentRegistrationSrDetailWeight, + outputRowOffset: Int = 0, + outputRowCount: Int = superResolutionAccumulatorHeight, ) { - val outputAccumulator = if (currentSuperResolutionAccumulatorTexture == superResolutionAccumulatorTexture) { - superResolutionAccumulatorScratchTexture - } else { - superResolutionAccumulatorTexture - } GLES31.glUseProgram(accumulateSuperResolutionProgram) - bindTexture(accumulateSuperResolutionProgram, "uInputRaw", 0, rawTexture) - bindTexture(accumulateSuperResolutionProgram, "uFlowGrid", 1, flowTexture) - bindTexture(accumulateSuperResolutionProgram, "uRobustness", 2, robustnessTexture) - bindTexture(accumulateSuperResolutionProgram, "uTileMask", 3, tileMaskTexture) + bindTexture(accumulateSuperResolutionProgram, "uFlowGrid", 1, frameFlowTexture) + bindTexture(accumulateSuperResolutionProgram, "uRobustness", 2, frameRobustnessTexture) + bindTexture(accumulateSuperResolutionProgram, "uTileMask", 3, frameTileMaskTexture) bindTexture(accumulateSuperResolutionProgram, "uKernel", 4, kernelTexture) bindTexture(accumulateSuperResolutionProgram, "uLensShadingMap", 5, lensShadingTexture) - bindTexture(accumulateSuperResolutionProgram, "uAccumulatorInput", 6, currentSuperResolutionAccumulatorTexture) - bindImage(0, outputAccumulator, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) + bindImage(1, superResolutionAccumulatorBwTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) + bindImage(2, superResolutionAccumulatorBTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, rcdStripeBuffers[1]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, rcdStripeBuffers[2]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 3, rcdStripeBuffers[3]) setCommonUniforms(accumulateSuperResolutionProgram) GLES31.glUniform2i( GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uImageSize"), @@ -2331,6 +3125,15 @@ class GlesRawStacker( GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uIsReference"), if (isReference) 1 else 0, ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uSourceRowOffset"), + sourceRowOffset, + ) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uSourceSize"), + width, + sourceRowCount, + ) GLES31.glUniform1f( GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uOutputScale"), superResolutionScale, @@ -2349,89 +3152,30 @@ class GlesRawStacker( ) GLES31.glUniform1f( GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uSrSplatRadius"), - hwmfSr.greenFootprintSigmaRawPx.coerceAtLeast(0.25f), + hwmfSr.cfaFootprintSigmaRawPx.coerceAtLeast(0.25f), ) GLES31.glUniform1f( GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uRegistrationSrWeight"), - if (isReference) 1.0f else currentRegistrationSrWeight.coerceIn(0.0f, 1.0f), - ) - setRegistrationUniforms( - program = accumulateSuperResolutionProgram, - transform = if (isReference) { - registrationSetup.identityTransform(RawStackRegistrationStage.BLEND) - } else { - currentRegistrationSrTransform - }, - ) - setLocalFlowResidualUniforms( - program = accumulateSuperResolutionProgram, - strength = hwmfSr.localFlowResidualStrength, - maxResidualPx = hwmfSr.localFlowResidualMaxPx, + if (isReference) 1.0f else registrationWeight.coerceIn(0.0f, 1.0f), ) setBlendAccumulatorUniforms(accumulateSuperResolutionProgram) - var outputRow = 0 - while (outputRow < outputHeight) { - val rowCount = minOf(SUPER_RESOLUTION_DISPATCH_ROWS, outputHeight - outputRow) - GLES31.glUniform1i( - GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uOutputRowOffset"), - outputRow, - ) - GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(rowCount), 1) - GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) - GlesGpuScheduler.waitForGpuCheckpoint( - TAG, - "MFSR rows=$outputRow..${outputRow + rowCount}", - ) - outputRow += rowCount - } + val safeRowCount = outputRowCount.coerceIn(1, superResolutionAccumulatorHeight) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uOutputRowOffset"), + outputRowOffset, + ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(accumulateSuperResolutionProgram, "uOutputRowCount"), + safeRowCount, + ) + GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(safeRowCount), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) + GlesGpuScheduler.waitForGpuCheckpoint( + TAG, + "MFSR rows=$outputRowOffset..${outputRowOffset + safeRowCount}", + ) GLES31.glMemoryBarrier(GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("accumulateSuperResolutionFrame") - currentSuperResolutionAccumulatorTexture = outputAccumulator - } - - private fun computeHdrRecoveryMask(shortToReferenceExposureScale: Float) { - computeInitialHdrRecoveryMask(shortToReferenceExposureScale) - filterHdrRecoveryMask( - program = hdrRecoveryDilateProgram, - input = hdrRecoveryOrigMaskTexture, - output = hdrRecoveryScratchTexture, - label = "computeHdrRecoveryMask dilate", - ) - filterHdrRecoveryMask( - program = hdrRecoveryFeatherProgram, - input = hdrRecoveryScratchTexture, - output = hdrRecoveryMaskTexture, - label = "computeHdrRecoveryMask feather", - ) - } - - private fun computeInitialHdrRecoveryMask(shortToReferenceExposureScale: Float) { - bindFramebufferOutput(hdrRecoveryOrigMaskTexture, "computeHdrRecoveryMask initial") - GLES30.glViewport(0, 0, planeWidth, planeHeight) - GLES30.glUseProgram(hdrRecoveryMaskProgram) - bindTexture(hdrRecoveryMaskProgram, "uAccumulator", 0, currentAccumulatorTexture) - bindTexture(hdrRecoveryMaskProgram, "uReferenceRaw", 1, refRaw) - bindTexture(hdrRecoveryMaskProgram, "uShortRaw", 2, hdrShortRaw) - bindTexture(hdrRecoveryMaskProgram, "uShortGlobalAlignment", 3, hdrShortAlignmentTexture) - setCommonUniforms(hdrRecoveryMaskProgram) - GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrRecoveryMaskProgram, "uImageSize"), width, height) - GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrRecoveryMaskProgram, "uPlaneSize"), planeWidth, planeHeight) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(hdrRecoveryMaskProgram, "uShortToReferenceExposureScale"), - shortToReferenceExposureScale, - ) - GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) - finishFramebufferPass("computeHdrRecoveryMask initial") - } - - private fun filterHdrRecoveryMask(program: Int, input: Int, output: Int, label: String) { - bindFramebufferOutput(output, label) - GLES30.glViewport(0, 0, planeWidth, planeHeight) - GLES30.glUseProgram(program) - bindTexture(program, "uMask", 0, input) - GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uPlaneSize"), planeWidth, planeHeight) - GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) - finishFramebufferPass(label) } private fun resetSuperResolutionDecisionStats() { @@ -2469,7 +3213,7 @@ class GlesRawStacker( val qualityReason = reasons.takeIf { it.isNotEmpty() }?.joinToString("+") val hasAnySrSupport = superResolutionDetailFrameCount > 0 && superResolutionDetailWeightSum > 0f val mode = when { - !hasAnySrSupport || detailCoverageLow || phaseCoverageLow -> "BASE_UPSCALE" + !hasAnySrSupport -> "SUPER_RESOLUTION_REFERENCE_ONLY" qualityReason != null -> "SUPER_RESOLUTION_PARTIAL" else -> "SUPER_RESOLUTION" } @@ -2499,6 +3243,43 @@ class GlesRawStacker( ) } + private fun computeHdrRecoveryMask() { + computeInitialHdrRecoveryMask() + expandHdrRecoveryCoverage() + } + + private fun computeInitialHdrRecoveryMask() { + bindFramebufferOutput(hdrRecoveryOrigMaskTexture, "computeHdrRecoveryMask initial") + GLES30.glViewport(0, 0, planeWidth, planeHeight) + GLES30.glUseProgram(hdrRecoveryMaskProgram) + bindTexture(hdrRecoveryMaskProgram, "uAccumulatorValueWeight", 0, accumulatorValueWeightTexture) + bindTexture(hdrRecoveryMaskProgram, "uAccumulatorStatistics", 1, accumulatorStatisticsTexture) + bindTexture(hdrRecoveryMaskProgram, "uReferenceRaw", 2, refRaw) + setCommonUniforms(hdrRecoveryMaskProgram) + GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrRecoveryMaskProgram, "uImageSize"), width, height) + GLES31.glUniform2i(GLES31.glGetUniformLocation(hdrRecoveryMaskProgram, "uPlaneSize"), planeWidth, planeHeight) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("computeHdrRecoveryMask initial") + } + + private fun expandHdrRecoveryCoverage() { + bindFramebufferOutput(hdrRecoveryCoverageTexture, "computeHdrRecoveryMask coverage") + GLES30.glViewport(0, 0, planeWidth, planeHeight) + GLES30.glUseProgram(hdrRecoveryCoverageProgram) + bindTexture(hdrRecoveryCoverageProgram, "uInitialMask", 0, hdrRecoveryOrigMaskTexture) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(hdrRecoveryCoverageProgram, "uPlaneSize"), + planeWidth, + planeHeight, + ) + GLES31.glUniform1i( + GLES31.glGetUniformLocation(hdrRecoveryCoverageProgram, "uBlockRadius"), + (rawCfaPeriod / 2).coerceIn(1, 4), + ) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("computeHdrRecoveryMask coverage") + } + private fun normalizeOutput( hdrMode: Boolean = false, referenceExposureScale: Float = 1.0f, @@ -2511,137 +3292,149 @@ class GlesRawStacker( bindFramebufferOutput(targetTexture, label) GLES30.glViewport(0, 0, targetWidth, targetHeight) GLES30.glUseProgram(normalizeProgram) - bindTexture(normalizeProgram, "uAccumulator", 0, currentAccumulatorTexture) - bindTexture(normalizeProgram, "uReferenceRaw", 1, refRaw) - bindTexture(normalizeProgram, "uShortRaw", 2, hdrShortRaw) + bindTexture(normalizeProgram, "uAccumulatorValueWeight", 0, accumulatorValueWeightTexture) + bindTexture(normalizeProgram, "uAccumulatorStatistics", 1, accumulatorStatisticsTexture) + bindTexture(normalizeProgram, "uReferenceRaw", 2, refRaw) bindTexture(normalizeProgram, "uLensShadingMap", 3, lensShadingTexture) - bindTexture(normalizeProgram, "uShortGlobalAlignment", 4, hdrShortAlignmentTexture) - bindTexture(normalizeProgram, "uHdrRecoveryMask", 5, hdrRecoveryMaskTexture) - bindTexture(normalizeProgram, "uHdrRecoveryOrigMask", 6, hdrRecoveryOrigMaskTexture) + bindTexture(normalizeProgram, "uShortRaw", 4, hdrShortRaw) + bindTexture(normalizeProgram, "uShortGlobalAlignment", 5, hdrShortAlignmentTexture) + bindTexture(normalizeProgram, "uHdrRecoveryOrigMask", 6, hdrRecoveryCoverageTexture) setCommonUniforms(normalizeProgram) GLES31.glUniform2i(GLES31.glGetUniformLocation(normalizeProgram, "uImageSize"), width, height) - GLES31.glUniform2i(GLES31.glGetUniformLocation(normalizeProgram, "uPlaneSize"), planeWidth, planeHeight) GLES31.glUniform1i(GLES31.glGetUniformLocation(normalizeProgram, "uHdrMode"), if (hdrMode) 1 else 0) GLES31.glUniform1f( GLES31.glGetUniformLocation(normalizeProgram, "uReferenceExposureScale"), referenceExposureScale, ) GLES31.glUniform1f(GLES31.glGetUniformLocation(normalizeProgram, "uShortExposureScale"), shortExposureScale) + GLES31.glUniform2i(GLES31.glGetUniformLocation(normalizeProgram, "uPlaneSize"), planeWidth, planeHeight) setPostfilterUniforms(normalizeProgram) GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) finishFramebufferPass(label) } - private fun normalizeSuperResolutionOutput(decision: SuperResolutionOutputDecision) { - normalizeOutput( - targetTexture = superResolutionBaseTexture, - targetWidth = width, - targetHeight = height, - label = "normalizeSuperResolutionBase", - ) - if (!decision.forceBaseUpscale) { - computeSuperResolutionChannelRatios() + private fun reconstructSuperResolutionStripes( + referenceImage: SafeImage, + acceptedFrames: List, + ) { + var requiredRcdRows = 1 + var planRow = 0 + while (planRow < outputHeight) { + val coreCount = minOf(SUPER_RESOLUTION_STRIPE_ROWS, outputHeight - planRow) + val planStart = max(0, planRow - SUPER_RESOLUTION_SPATIAL_RADIUS) + val planEnd = minOf(outputHeight, planRow + coreCount + SUPER_RESOLUTION_SPATIAL_RADIUS) + val planCount = planEnd - planStart + requiredRcdRows = max( + requiredRcdRows, + RawSuperResolutionStripePlanner.sourceRowBand( + planStart, planCount, superResolutionScale, 0f, 0f, rawCfaPeriod, height, + ).rowCount, + ) + acceptedFrames.forEach { frame -> + requiredRcdRows = max( + requiredRcdRows, + RawSuperResolutionStripePlanner.sourceRowBand( + planStart, + planCount, + superResolutionScale, + frame.minFlowYPlanePx, + frame.maxFlowYPlanePx, + rawCfaPeriod, + height, + ).rowCount, + ) + } + planRow += coreCount } - bindFramebufferOutput(outputTexture, "normalizeSuperResolutionOutput") - GLES30.glViewport(0, 0, outputWidth, outputHeight) + ensureRcdStripeResources(requiredRcdRows) + var outputRowOffset = 0 + while (outputRowOffset < outputHeight) { + val outputRowCount = minOf(SUPER_RESOLUTION_STRIPE_ROWS, outputHeight - outputRowOffset) + val accumulationRowOffset = max(0, outputRowOffset - SUPER_RESOLUTION_SPATIAL_RADIUS) + val accumulationEnd = minOf( + outputHeight, + outputRowOffset + outputRowCount + SUPER_RESOLUTION_SPATIAL_RADIUS, + ) + val accumulationRowCount = accumulationEnd - accumulationRowOffset + clearSuperResolutionAccumulator() + val referenceBand = RawSuperResolutionStripePlanner.sourceRowBand( + accumulationRowOffset, + accumulationRowCount, + superResolutionScale, + 0f, + 0f, + rawCfaPeriod, + height, + ) + uploadRcdRawStripe(referenceImage, referenceBand.firstRow, referenceBand.rowCount, "reference") + runRcdStripe(referenceBand.firstRow, referenceBand.rowCount, "reference") + accumulateSuperResolutionFrame( + isReference = true, + sourceRowOffset = referenceBand.firstRow, + sourceRowCount = referenceBand.rowCount, + outputRowOffset = accumulationRowOffset, + outputRowCount = accumulationRowCount, + ) + acceptedFrames.forEach { frame -> + val sourceBand = RawSuperResolutionStripePlanner.sourceRowBand( + outputRowOffset = accumulationRowOffset, + outputRowCount = accumulationRowCount, + outputScale = superResolutionScale, + minFlowYPlanePx = frame.minFlowYPlanePx, + maxFlowYPlanePx = frame.maxFlowYPlanePx, + cfaPeriod = rawCfaPeriod, + rawHeight = height, + ) + uploadRcdRawStripe( + image = frame.image, + firstRow = sourceBand.firstRow, + rowCount = sourceBand.rowCount, + label = "MFSR stripe frame ${frame.frameIndex}", + ) + runRcdStripe(sourceBand.firstRow, sourceBand.rowCount, "frame ${frame.frameIndex}") + accumulateSuperResolutionFrame( + isReference = false, + sourceRowOffset = sourceBand.firstRow, + sourceRowCount = sourceBand.rowCount, + exposureScale = frame.exposureScale, + frameFlowTexture = frame.flowTexture, + frameRobustnessTexture = frame.robustnessTexture, + frameTileMaskTexture = frame.tileMaskTexture, + registrationWeight = frame.registrationWeight, + detailWeight = frame.detailWeight, + outputRowOffset = accumulationRowOffset, + outputRowCount = accumulationRowCount, + ) + } + normalizeSuperResolutionStripe( + outputRowOffset = outputRowOffset, + outputRowCount = outputRowCount, + accumulatorRowOffset = accumulationRowOffset, + ) + outputRowOffset += outputRowCount + GlesGpuScheduler.yieldToUiRenderer() + } + } + + private fun normalizeSuperResolutionStripe( + outputRowOffset: Int, + outputRowCount: Int, + accumulatorRowOffset: Int, + ) { + bindFramebufferOutput(outputTexture, "normalizeSuperResolutionStripe") + GLES30.glViewport(0, outputRowOffset, outputWidth, outputRowCount) GLES30.glUseProgram(normalizeSuperResolutionProgram) - bindTexture(normalizeSuperResolutionProgram, "uSrAccumulator", 0, currentSuperResolutionAccumulatorTexture) - bindTexture(normalizeSuperResolutionProgram, "uBasePackedRaw", 1, superResolutionBaseTexture) - bindTexture(normalizeSuperResolutionProgram, "uLensShadingMap", 2, lensShadingTexture) - bindTexture( - normalizeSuperResolutionProgram, - "uChannelRatio", - 3, - superResolutionChannelRatioTexture, - ) + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulator", 0, superResolutionAccumulatorTexture) + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorBw", 1, superResolutionAccumulatorBwTexture) + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorB", 2, superResolutionAccumulatorBTexture) setCommonUniforms(normalizeSuperResolutionProgram) - GLES31.glUniform2i( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uImageSize"), - width, - height, - ) - GLES31.glUniform2i( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uOutputSize"), - outputWidth, - outputHeight, - ) - GLES31.glUniform2i( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uRatioSize"), - planeWidth, - planeHeight, - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uOutputScale"), - superResolutionScale, - ) GLES31.glUniform1i( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uForceBaseUpscale"), - if (decision.forceBaseUpscale) 1 else 0, - ) - val detailConfidenceStart = hwmfSr.minEffectiveWeight.coerceAtLeast(0f) * - hwmfSr.detailConfidenceStartScale.coerceAtLeast(0f) - val detailConfidenceFull = hwmfSr.minEffectiveWeight.coerceAtLeast(0f) * - hwmfSr.detailConfidenceFullScale.coerceAtLeast(hwmfSr.detailConfidenceStartScale) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceStart"), - detailConfidenceStart, - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceFull"), - detailConfidenceFull, - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation( - normalizeSuperResolutionProgram, - "uGreenReconstructionLowLightSuppression", - ), - hwmfSr.greenReconstructionLowLightSuppression.coerceIn(0f, 1f), - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation( - normalizeSuperResolutionProgram, - "uGreenReconstructionLscSuppression", - ), - hwmfSr.greenReconstructionLscSuppression.coerceIn(0f, 1f), + GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uAccumulatorRowOffset"), + accumulatorRowOffset, ) setPostfilterUniforms(normalizeSuperResolutionProgram) GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) - finishFramebufferPass("normalizeSuperResolutionOutput") - } - - private fun computeSuperResolutionChannelRatios() { - GLES31.glUseProgram(computeSuperResolutionChannelRatioProgram) - bindTexture( - computeSuperResolutionChannelRatioProgram, - "uBasePackedRaw", - 0, - superResolutionBaseTexture, - ) - bindImage( - 0, - superResolutionChannelRatioTexture, - GLES31.GL_WRITE_ONLY, - GLES30.GL_RGBA16F, - ) - GLES31.glUniform2i( - GLES31.glGetUniformLocation(computeSuperResolutionChannelRatioProgram, "uImageSize"), - width, - height, - ) - GLES31.glUniform2i( - GLES31.glGetUniformLocation(computeSuperResolutionChannelRatioProgram, "uRatioSize"), - planeWidth, - planeHeight, - ) - GLES31.glUniform1i( - GLES31.glGetUniformLocation(computeSuperResolutionChannelRatioProgram, "uCfaPattern"), - cfaPattern, - ) - GLES31.glDispatchCompute(groupCount(planeWidth), groupCount(planeHeight), 1) - GLES31.glMemoryBarrier( - GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, - ) - checkGlError("computeSuperResolutionChannelRatios") + finishFramebufferPass("normalizeSuperResolutionStripe") } private fun recordAlignmentDiagnostics() { @@ -2728,19 +3521,17 @@ class GlesRawStacker( superResolutionDecision: SuperResolutionOutputDecision = SuperResolutionOutputDecision.Disabled, ): RawStackDiagnostics? { if (!hwmfDebug.collectMetrics) return null - val diagnosticAccumulatorTexture = if (superResolutionEnabled) { - currentSuperResolutionAccumulatorTexture - } else { - currentAccumulatorTexture - } - val diagnosticAccumulatorWidth = if (superResolutionEnabled) outputWidth else width - val diagnosticAccumulatorHeight = if (superResolutionEnabled) outputHeight else height - val diagnosticOutputScale = if (superResolutionEnabled) superResolutionScale else 1.0f + // The compact MFSR accumulator intentionally retains only value/weight detail data. + // Final diagnostics sample the full base accumulator instead of allocating or decoding + // a separate diagnostic representation for a production-disabled code path. + val diagnosticAccumulatorWidth = width + val diagnosticAccumulatorHeight = height + val diagnosticOutputScale = 1.0f val finalRecorded = runDiagnosticStep("final") { GLES31.glUseProgram(diagnosticFinalProgram) - bindTexture(diagnosticFinalProgram, "uAccumulator", 0, diagnosticAccumulatorTexture) - bindTexture(diagnosticFinalProgram, "uLensShadingMap", 1, lensShadingTexture) - bindTexture(diagnosticFinalProgram, "uPostfilterAccumulator", 2, currentAccumulatorTexture) + bindTexture(diagnosticFinalProgram, "uAccumulatorValueWeight", 0, accumulatorValueWeightTexture) + bindTexture(diagnosticFinalProgram, "uAccumulatorStatistics", 1, accumulatorStatisticsTexture) + bindTexture(diagnosticFinalProgram, "uLensShadingMap", 2, lensShadingTexture) setCommonUniforms(diagnosticFinalProgram) setPostfilterUniforms(diagnosticFinalProgram) GLES31.glBindBufferBase( @@ -2761,7 +3552,7 @@ class GlesRawStacker( GLES31.glUniform1i(GLES31.glGetUniformLocation(diagnosticFinalProgram, "uCfaPattern"), cfaPattern) GLES31.glUniform1i( GLES31.glGetUniformLocation(diagnosticFinalProgram, "uSuperResolutionEnabled"), - if (superResolutionEnabled) 1 else 0, + 0, ) GLES31.glUniform1f( GLES31.glGetUniformLocation(diagnosticFinalProgram, "uWeightHistogramRange"), @@ -3402,6 +4193,26 @@ class GlesRawStacker( GLES31.glGetUniformLocation(program, "uRobustFlowRangePenaltyDecay"), hwmfBlend.flowRangePenaltyDecay ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchScoreFullConfidence"), + hwmfBlend.patchScoreFullConfidence, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchScoreReject"), + hwmfBlend.patchScoreReject, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchPeakConfidenceStart"), + hwmfBlend.patchPeakConfidenceStart, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchPeakConfidenceFull"), + hwmfBlend.patchPeakConfidenceFull, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchConfidenceFloor"), + hwmfBlend.patchConfidenceFloor.coerceIn(0f, 1f), + ) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixFlat"), hwmfBlend.robustMinMixFlat) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixEdge"), hwmfBlend.robustMinMixEdge) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustCenterMixFlat"), hwmfBlend.robustCenterMixFlat) @@ -3501,21 +4312,6 @@ class GlesRawStacker( ) } - private fun setLocalFlowResidualUniforms( - program: Int, - strength: Float, - maxResidualPx: Float, - ) { - GLES31.glUniform1f( - GLES31.glGetUniformLocation(program, "uLocalFlowResidualStrength"), - strength.coerceIn(0f, 1f), - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(program, "uLocalFlowResidualMaxPx"), - maxResidualPx.coerceAtLeast(0f), - ) - } - private fun setPostfilterUniforms(program: Int) { GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uFinalSmoothStrength"), hwmfPostfilter.finalSmoothStrength) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uFlatVarianceStart"), hwmfPostfilter.flatVarianceStart) @@ -3601,10 +4397,6 @@ class GlesRawStacker( GLES31.glGetUniformLocation(program, "uMaxSmoothStrength"), hwmfPostfilter.maxSmoothStrength.coerceIn(0f, 1f) ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(program, "uHdrRecoverySmoothSuppression"), - hwmfPostfilter.hdrRecoverySmoothSuppression - ) } private fun createTexture2D(textureWidth: Int, textureHeight: Int, internalFormat: Int, filter: Int): Int { @@ -3623,6 +4415,12 @@ class GlesRawStacker( return texture } + private fun deleteTexture(texture: Int) { + if (texture == 0) return + GLES30.glDeleteTextures(1, intArrayOf(texture), 0) + textures.removeAll { it == texture } + } + private fun createLensShadingTexture(): Int { val hasValidLensShading = lensShading != null && lensShadingWidth > 0 && @@ -3809,14 +4607,29 @@ class GlesRawStacker( private const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040 private const val LOCAL_SIZE = 16 + private const val MIN_TEMPORAL_GRAPH_FRAME_COUNT = 3 + private const val MIN_TEMPORAL_TRACKING_LEVEL = 2 + private const val MIN_TEMPORAL_WINDOW_LEVEL_PIXELS = 8 + private const val MIN_TEMPORAL_GRAPH_SPACING_MULTIPLIER = 4 + private const val MAX_TEMPORAL_GRAPH_SKIP_FRAME_COUNT = 8 + private const val MAX_TEMPORAL_GRAPH_TILES = 2048.0 + private const val MAX_TEMPORAL_TRACKING_SCALE = 16 + private const val TRACKING_TEXTURE_BYTES_PER_PIXEL = 8L + private const val MAX_TEMPORAL_TRACKING_BYTES = 32L * 1024L * 1024L private const val BASE_ACCUMULATOR_DISPATCH_ROWS = 256 - private const val SUPER_RESOLUTION_DISPATCH_ROWS = 256 + private const val SUPER_RESOLUTION_STRIPE_ROWS = 256 + private const val SUPER_RESOLUTION_SPATIAL_RADIUS = 2 private const val PGTM_STATS_BUFFER_BINDING = 7 - private const val HDR_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING = 8 + private const val HDR_123_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING = 8 + private const val HDR_123_SHORT_ALIGNMENT_SCORE_STRIDE = 4 + private const val HDR_123_ALIGN_LEVEL = 2 + private const val HDR_123_SHORT_GLOBAL_SEARCH_RADIUS_LEVEL = 8 + private const val HDR_123_SHORT_GLOBAL_SAMPLE_STEP = 6 + private const val HDR_123_SHORT_GLOBAL_SAMPLE_BORDER = 8 private const val DIAGNOSTIC_BUFFER_BINDING = 9 private const val REGISTRATION_SAMPLE_BUFFER_BINDING = 10 private const val REGISTRATION_GLOBAL_SCORE_BUFFER_BINDING = 11 - private const val HDR_SHORT_ALIGNMENT_SCORE_STRIDE = 4 + private const val FLOW_READBACK_BUFFER_BINDING = 12 private const val REGISTRATION_GLOBAL_SCORE_STRIDE = 4 private const val REGISTRATION_SAMPLE_FLOAT_STRIDE = 8 private const val DIAGNOSTIC_HIST_BINS = 64 @@ -4053,6 +4866,77 @@ class GlesRawStacker( } """.trimIndent() + private val RAW_TRACKING_PROXY_COMPUTE_SHADER = """ + #version 310 es + $RAW_COMMON + layout(local_size_x = 16, local_size_y = 16) in; + uniform highp usampler2D uRaw; + layout(rgba16f, binding = 1) writeonly uniform highp image2D uTrackingProxy; + uniform ivec2 uPlaneSize; + uniform ivec2 uTrackingSize; + uniform int uLevelScale; + uniform int uCfaPattern; + uniform float uBlackLevel[4]; + uniform float uWhiteLevel; + uniform float uNoiseAlphaByChannel[4]; + uniform float uNoiseBetaByChannel[4]; + uniform float uExposureScale; + + float rawNormAt(ivec2 p) { + p = clamp(p, ivec2(0), uPlaneSize * 2 - ivec2(1)); + int b = bayerIndexAt(uCfaPattern, p); + float raw = float(texelFetch(uRaw, p, 0).r); + float range = max(uWhiteLevel - uBlackLevel[b], 1.0); + return clamp((raw - uBlackLevel[b]) / range, 0.0, 1.0); + } + + vec2 greenAndMax(ivec2 planeCoord) { + ivec2 s = clamp(planeCoord * 2, ivec2(0), uPlaneSize * 2 - ivec2(2)); + float p00 = rawNormAt(s); + float p10 = rawNormAt(s + ivec2(1, 0)); + float p01 = rawNormAt(s + ivec2(0, 1)); + float p11 = rawNormAt(s + ivec2(1, 1)); + float green; + if (uCfaPattern >= 4) { + green = 0.25 * (p00 + p10 + p01 + p11); + } else if (uCfaPattern == 0 || uCfaPattern == 3) { + green = 0.5 * (p10 + p01); + } else { + green = 0.5 * (p00 + p11); + } + return vec2(green, max(max(p00, p10), max(p01, p11))); + } + + void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= uTrackingSize.x || p.y >= uTrackingSize.y) return; + ivec2 base = p * uLevelScale; + int quarter = max(1, uLevelScale / 4); + int threeQuarter = max(1, (3 * uLevelScale) / 4); + ivec2 offsets[4] = ivec2[4]( + ivec2(quarter, quarter), + ivec2(threeQuarter, quarter), + ivec2(quarter, threeQuarter), + ivec2(threeQuarter, threeQuarter) + ); + float signal = 0.0; + float tileMax = 0.0; + for (int index = 0; index < 4; ++index) { + vec2 sampleValue = greenAndMax( + clamp(base + offsets[index], ivec2(0), uPlaneSize - ivec2(1)) + ); + signal += sampleValue.x; + tileMax = max(tileMax, sampleValue.y); + } + signal *= 0.25; + float normalized = clamp(signal * uExposureScale, 0.0, 1.0); + float shadowValid = smoothstep(0.004, 0.035, signal); + float clipValid = 1.0 - smoothstep(0.90, 0.995, tileMax); + float validity = clamp(shadowValid * clipValid, 0.0, 1.0); + imageStore(uTrackingProxy, p, vec4(normalized, validity, 0.0, 1.0)); + } + """.trimIndent() + private val DOWNSAMPLE_FRAGMENT_SHADER = """ #version 300 es precision highp float; @@ -4088,6 +4972,15 @@ class GlesRawStacker( uniform int uSampleStep; uniform float uCoveragePenalty; uniform float uShiftPenalty; + uniform vec2 uInitialTranslation; + uniform float uInitialRotationRadians; + uniform vec2 uPlaneCenter; + uniform sampler2D uGraphSeed; + uniform int uUseGraphSeed; + uniform ivec2 uGraphGridSize; + uniform int uGraphTileSize; + uniform float uGraphSeedConfidenceMin; + uniform int uGraphRefineSearchRadius; out vec4 fragColor; vec2 readProxy(sampler2D tex, ivec2 p) { @@ -4095,17 +4988,49 @@ class GlesRawStacker( return texelFetch(tex, p, 0).rg; } + vec4 graphSeedAt(vec2 planePos) { + vec2 grid = planePos / float(uGraphTileSize) - vec2(0.5); + vec2 uv = (grid + vec2(0.5)) / vec2(uGraphGridSize); + return texture(uGraphSeed, clamp(uv, vec2(0.0), vec2(1.0))); + } + void main() { ivec2 tile = ivec2(gl_FragCoord.xy); - ivec2 fullCenter = tile * uTileSize; + ivec2 planeMax = ivec2(round(uPlaneCenter * 2.0)); + ivec2 fullCenter = min( + tile * uTileSize + ivec2(uTileSize / 2), + planeMax + ); ivec2 levelCenter = fullCenter / uLevelScale; int levelTile = max(4, uAlignWindowSize / uLevelScale); ivec2 levelStart = levelCenter - ivec2(levelTile / 2); + float cosTheta = cos(uInitialRotationRadians); + float sinTheta = sin(uInitialRotationRadians); + vec2 centered = vec2(fullCenter) - uPlaneCenter; + vec2 rotated = vec2( + cosTheta * centered.x - sinTheta * centered.y, + sinTheta * centered.x + cosTheta * centered.y + ); + vec2 initialFlowFull = rotated - centered + uInitialTranslation; + bool hasGraphSeed = false; + if (uUseGraphSeed != 0) { + vec4 graphSeed = graphSeedAt(vec2(fullCenter)); + if (graphSeed.a >= uGraphSeedConfidenceMin) { + initialFlowFull = graphSeed.rg; + hasGraphSeed = true; + } + } + ivec2 initialShift = ivec2(round(initialFlowFull / float(uLevelScale))); + int activeSearchRadius = hasGraphSeed ? + min(uSearchRadius, uGraphRefineSearchRadius) : uSearchRadius; float bestSad = 1e20; + float secondBestSad = 1e20; + float bestCoverage = 0.0; ivec2 bestShift = ivec2(0); for (int dy = -uSearchRadius; dy <= uSearchRadius; ++dy) { for (int dx = -uSearchRadius; dx <= uSearchRadius; ++dx) { + if (abs(dx) > activeSearchRadius || abs(dy) > activeSearchRadius) continue; float sad = 0.0; float count = 0.0; float sampleCount = 0.0; @@ -4113,7 +5038,7 @@ class GlesRawStacker( for (int sx = 1; sx < levelTile - 1; sx += uSampleStep) { ivec2 rp = levelStart + ivec2(sx, sy); vec2 rv = readProxy(uReference, rp); - vec2 cv = readProxy(uCurrent, rp + ivec2(dx, dy)); + vec2 cv = readProxy(uCurrent, rp + initialShift + ivec2(dx, dy)); float w = min(rv.g, cv.g); sad += abs(rv.r - cv.r) * w; count += w; @@ -4125,125 +5050,44 @@ class GlesRawStacker( uCoveragePenalty * (1.0 - clamp(coverage, 0.0, 1.0)) + uShiftPenalty * float(dx * dx + dy * dy); if (sad < bestSad) { + secondBestSad = bestSad; bestSad = sad; bestShift = ivec2(dx, dy); + bestCoverage = coverage; + } else if (sad < secondBestSad) { + secondBestSad = sad; } } } - fragColor = vec4(vec2(bestShift) * float(uLevelScale), bestSad, 1.0); + float relativeMargin = clamp( + (secondBestSad - bestSad) / max(abs(bestSad), 1e-4), + 0.0, + 1.0 + ); + float patchConfidence = clamp(bestCoverage, 0.0, 1.0) * relativeMargin; + fragColor = vec4( + vec2(initialShift + bestShift) * float(uLevelScale), + bestSad, + patchConfidence + ); } """.trimIndent() - private val HDR_SHORT_GLOBAL_ALIGN_COMPUTE_SHADER = """ + private val FLOW_READBACK_COMPUTE_SHADER = """ #version 310 es precision highp float; precision highp int; - layout(local_size_x = 8, local_size_y = 8) in; - uniform sampler2D uReference; - uniform sampler2D uCurrent; - uniform ivec2 uLevelSize; - uniform int uLevelScale; - uniform int uSearchRadius; - uniform int uSampleStep; - uniform int uSampleBorder; - uniform float uCoveragePenalty; - uniform float uShiftPenalty; - layout(std430, binding = $HDR_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING) buffer HdrShortAlignmentScores { - float scores[]; + layout(local_size_x = 16, local_size_y = 16) in; + uniform sampler2D uFlow; + uniform ivec2 uGridSize; + layout(std430, binding = $FLOW_READBACK_BUFFER_BINDING) buffer FlowReadback { + vec4 samples[]; }; - const int LOCAL_COUNT = 64; - const int SCORE_STRIDE = $HDR_SHORT_ALIGNMENT_SCORE_STRIDE; - shared float sadParts[LOCAL_COUNT]; - shared float weightParts[LOCAL_COUNT]; - shared float sampleParts[LOCAL_COUNT]; - - vec2 readProxy(sampler2D tex, ivec2 p) { - p = clamp(p, ivec2(0), uLevelSize - ivec2(1)); - return texelFetch(tex, p, 0).rg; - } - - bool insideLevel(ivec2 p) { - return p.x >= 0 && p.y >= 0 && p.x < uLevelSize.x && p.y < uLevelSize.y; - } - - float detailAt(ivec2 p) { - float c = readProxy(uReference, p).r; - float gx = abs(readProxy(uReference, p + ivec2(1, 0)).r - readProxy(uReference, p - ivec2(1, 0)).r); - float gy = abs(readProxy(uReference, p + ivec2(0, 1)).r - readProxy(uReference, p - ivec2(0, 1)).r); - float lap = abs(4.0 * c - - readProxy(uReference, p + ivec2(1, 0)).r - - readProxy(uReference, p - ivec2(1, 0)).r - - readProxy(uReference, p + ivec2(0, 1)).r - - readProxy(uReference, p - ivec2(0, 1)).r); - return gx + gy + 0.5 * lap; - } - void main() { - ivec2 candidate = ivec2(gl_WorkGroupID.xy); - int scoreSide = uSearchRadius * 2 + 1; - if (candidate.x >= scoreSide || candidate.y >= scoreSide) return; - - ivec2 localId = ivec2(gl_LocalInvocationID.xy); - int localIndex = localId.y * 8 + localId.x; - ivec2 shift = candidate - ivec2(uSearchRadius); - int sampleWidth = max(0, (uLevelSize.x - 2 * uSampleBorder + uSampleStep - 1) / uSampleStep); - int sampleHeight = max(0, (uLevelSize.y - 2 * uSampleBorder + uSampleStep - 1) / uSampleStep); - int totalSamples = sampleWidth * sampleHeight; - - float sad = 0.0; - float weight = 0.0; - float sampleCount = 0.0; - for (int sampleIndex = localIndex; sampleIndex < totalSamples; sampleIndex += LOCAL_COUNT) { - int sx = sampleIndex - (sampleIndex / sampleWidth) * sampleWidth; - int sy = sampleIndex / sampleWidth; - ivec2 rp = ivec2( - uSampleBorder + sx * uSampleStep, - uSampleBorder + sy * uSampleStep - ); - ivec2 cp = rp + shift; - sampleCount += 1.0; - if (!insideLevel(cp)) { - continue; - } - - vec2 rv = readProxy(uReference, rp); - vec2 cv = readProxy(uCurrent, cp); - float detail = clamp(detailAt(rp) * 18.0, 0.08, 1.0); - float w = min(rv.g, cv.g) * detail; - sad += abs(rv.r - cv.r) * w; - weight += w; - } - - sadParts[localIndex] = sad; - weightParts[localIndex] = weight; - sampleParts[localIndex] = sampleCount; - memoryBarrierShared(); - barrier(); - - if (localIndex != 0) { - return; - } - - float totalSad = 0.0; - float totalWeight = 0.0; - float totalSampleCount = 0.0; - for (int i = 0; i < LOCAL_COUNT; ++i) { - totalSad += sadParts[i]; - totalWeight += weightParts[i]; - totalSampleCount += sampleParts[i]; - } - float coverage = totalWeight / max(totalSampleCount, 1.0); - float shiftPenalty = uShiftPenalty * float(shift.x * shift.x + shift.y * shift.y); - float score = totalSad / max(totalWeight, 1e-4) + - uCoveragePenalty * (1.0 - clamp(coverage, 0.0, 1.0)) + - shiftPenalty; - int scoreIndex = candidate.y * scoreSide + candidate.x; - int offset = scoreIndex * SCORE_STRIDE; - scores[offset + 0] = float(shift.x * uLevelScale); - scores[offset + 1] = float(shift.y * uLevelScale); - scores[offset + 2] = score; - scores[offset + 3] = coverage; + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= uGridSize.x || p.y >= uGridSize.y) return; + samples[p.y * uGridSize.x + p.x] = texelFetch(uFlow, p, 0); } """.trimIndent() @@ -4388,15 +5232,16 @@ class GlesRawStacker( uniform ivec2 uGridSize; uniform int uTileSize; - float sampleProxy(sampler2D tex, vec2 p) { + vec2 sampleProxy(sampler2D tex, vec2 p) { vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); - return texture(tex, uv).r; + return texture(tex, uv).rg; } void main() { ivec2 tile = ivec2(gl_GlobalInvocationID.xy); if (tile.x >= uGridSize.x || tile.y >= uGridSize.y) return; - vec2 flow = texelFetch(uInputFlow, tile, 0).rg; + vec4 flowSample = texelFetch(uInputFlow, tile, 0); + vec2 flow = flowSample.rg; vec2 tileCenter = vec2(tile * uTileSize + ivec2(uTileSize / 2)); float sIxIx = 0.0; float sIyIy = 0.0; @@ -4413,15 +5258,23 @@ class GlesRawStacker( basePoint.y > float(uPlaneSize.y - 2)) { continue; } - float t = sampleProxy(uReference, basePoint); - float i = sampleProxy(uCurrent, basePoint + flow); - float tx = 0.5 * (sampleProxy(uReference, basePoint + vec2(1.0, 0.0)) - - sampleProxy(uReference, basePoint - vec2(1.0, 0.0))); - float ty = 0.5 * (sampleProxy(uReference, basePoint + vec2(0.0, 1.0)) - - sampleProxy(uReference, basePoint - vec2(0.0, 1.0))); + vec2 tSample = sampleProxy(uReference, basePoint); + vec2 iSample = sampleProxy(uCurrent, basePoint + flow); + vec2 txPos = sampleProxy(uReference, basePoint + vec2(1.0, 0.0)); + vec2 txNeg = sampleProxy(uReference, basePoint - vec2(1.0, 0.0)); + vec2 tyPos = sampleProxy(uReference, basePoint + vec2(0.0, 1.0)); + vec2 tyNeg = sampleProxy(uReference, basePoint - vec2(0.0, 1.0)); + float t = tSample.r; + float i = iSample.r; + float tx = 0.5 * (txPos.r - txNeg.r); + float ty = 0.5 * (tyPos.r - tyNeg.r); + float validity = min( + min(tSample.g, iSample.g), + min(min(txPos.g, txNeg.g), min(tyPos.g, tyNeg.g)) + ); float detailGate = clamp(max(abs(tx), abs(ty)) * 18.0, 0.08, 1.0); float spatialW = exp(-0.5 * float(ox * ox + oy * oy) / sigma2); - float w = spatialW * detailGate; + float w = spatialW * detailGate * validity; float it = i - t; sIxIx += w * tx * tx; sIyIy += w * ty * ty; @@ -4451,7 +5304,7 @@ class GlesRawStacker( if (isnan(updated.x) || isnan(updated.y) || isinf(updated.x) || isinf(updated.y)) { updated = flow; } - imageStore(uOutputFlow, tile, vec4(updated, 0.0, 1.0)); + imageStore(uOutputFlow, tile, vec4(updated, flowSample.ba)); } """.trimIndent() @@ -4464,27 +5317,46 @@ class GlesRawStacker( uniform float uOutlierWeight; out vec4 fragColor; - vec2 readFlow(ivec2 p) { + vec4 readFlowSample(ivec2 p) { p = clamp(p, ivec2(0), uGridSize - ivec2(1)); - return texelFetch(uInputFlow, p, 0).rg; + return texelFetch(uInputFlow, p, 0); } void main() { ivec2 p = ivec2(gl_FragCoord.xy); - vec2 center = readFlow(p); - vec2 sum = center * 4.0; - float weight = 4.0; + vec4 centerSample = readFlowSample(p); + vec2 center = centerSample.rg; + float centerWeight = mix(0.5, 4.0, clamp(centerSample.a, 0.0, 1.0)); + vec2 sum = center * centerWeight; + float weight = centerWeight; for (int y = -1; y <= 1; ++y) { for (int x = -1; x <= 1; ++x) { if (x == 0 && y == 0) continue; - vec2 f = readFlow(p + ivec2(x, y)); + vec4 neighbor = readFlowSample(p + ivec2(x, y)); + vec2 f = neighbor.rg; float d = length(f - center); - float w = d > uOutlierThreshold ? uOutlierWeight : 1.0; + float consistency = d > uOutlierThreshold ? uOutlierWeight : 1.0; + float evidence = mix(0.05, 1.0, clamp(neighbor.a, 0.0, 1.0)); + float w = consistency * evidence; sum += f * w; weight += w; } } - fragColor = vec4(sum / weight, 0.0, 1.0); + fragColor = vec4(sum / weight, centerSample.ba); + } + """.trimIndent() + + private val COPY_SCALAR_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + precision highp int; + uniform sampler2D uInput; + uniform ivec2 uImageSize; + out float fragColor; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uImageSize - ivec2(1)); + fragColor = texelFetch(uInput, p, 0).r; } """.trimIndent() @@ -4589,6 +5461,11 @@ class GlesRawStacker( uniform float uRobustFlowPenaltyDecay; uniform float uRobustFlowRangePenaltyStartPx; uniform float uRobustFlowRangePenaltyDecay; + uniform float uPatchScoreFullConfidence; + uniform float uPatchScoreReject; + uniform float uPatchPeakConfidenceStart; + uniform float uPatchPeakConfidenceFull; + uniform float uPatchConfidenceFloor; uniform float uRobustMinMixFlat; uniform float uRobustMinMixEdge; uniform float uRobustCenterMixFlat; @@ -4599,17 +5476,33 @@ class GlesRawStacker( return texelFetch(uReference, p, 0).r; } + float refValidity(ivec2 p) { + p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); + return texelFetch(uReference, p, 0).g; + } + float curProxy(vec2 p) { vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); return texture(uCurrent, uv).r; } + float curValidity(vec2 p) { + vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); + return texture(uCurrent, uv).g; + } + vec2 flowAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; } + vec2 patchEvidenceAt(vec2 planePos) { + vec2 grid = planePos / float(uTileSize) - vec2(0.5); + vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); + return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).ba; + } + $LOCAL_FLOW_WARP_GLSL void main() { @@ -4661,7 +5554,20 @@ class GlesRawStacker( float flowRange = length(fMax - fMin); float consistencyPenalty = flowRange > uRobustFlowRangePenaltyStartPx ? exp(-uRobustFlowRangePenaltyDecay * (flowRange - uRobustFlowRangePenaltyStartPx)) : 1.0; - float globalPenalty = flowPenalty * consistencyPenalty; + vec2 patchEvidence = patchEvidenceAt(vec2(p)); + float patchScoreConfidence = 1.0 - smoothstep( + uPatchScoreFullConfidence, + uPatchScoreReject, + patchEvidence.x + ); + float patchPeakConfidence = smoothstep( + uPatchPeakConfidenceStart, + uPatchPeakConfidenceFull, + patchEvidence.y + ); + float patchConfidence = patchScoreConfidence * patchPeakConfidence; + float globalPenalty = flowPenalty * consistencyPenalty * + mix(uPatchConfidenceFloor, 1.0, patchConfidence); float minR = 1.0; float sumR = 0.0; @@ -4672,6 +5578,7 @@ class GlesRawStacker( ivec2 rp = p + ivec2(x, y); float r = refProxy(rp); float c = curProxy(vec2(rp) + flow); + float validity = min(refValidity(rp), curValidity(vec2(rp) + flow)); float diff = r - c; float d2 = diff * diff; float noiseFloor = mix( @@ -4682,7 +5589,8 @@ class GlesRawStacker( float den = mix(sigma2, sigma2Noise, edgeRelax); float residual = max(0.0, d2 - noiseFloor) / max(den, 1e-10); float tau = uRobustTauBase + uRobustTauEdge * edgeRelax; - float robust = exp(-0.5 * pow(residual / tau, uRobustResidualPower)) * globalPenalty; + float robust = exp(-0.5 * pow(residual / tau, uRobustResidualPower)) * + globalPenalty * validity; float w = (x == 0 && y == 0) ? 2.0 : 1.0; sumR += robust * w; weightSum += w; @@ -4864,13 +5772,34 @@ class GlesRawStacker( precision highp float; precision highp int; layout(local_size_x = 16, local_size_y = 16) in; - layout(rgba16f, binding = 0) writeonly uniform highp image2D uAccumulator; + layout(r32ui, binding = 0) writeonly uniform highp uimage2D uAccumulatorValueWeight; + layout(r32ui, binding = 1) writeonly uniform highp uimage2D uAccumulatorStatistics; uniform ivec2 uImageSize; void main() { ivec2 p = ivec2(gl_GlobalInvocationID.xy); if (p.x >= uImageSize.x || p.y >= uImageSize.y) return; - imageStore(uAccumulator, p, vec4(0.0)); + imageStore(uAccumulatorValueWeight, p, uvec4(0u)); + imageStore(uAccumulatorStatistics, p, uvec4(0u)); + } + """.trimIndent() + + private val CLEAR_SUPER_RESOLUTION_ACCUMULATOR_COMPUTE_SHADER = """ + #version 310 es + precision highp float; + precision highp int; + layout(local_size_x = 16, local_size_y = 16) in; + layout(r32ui, binding = 0) writeonly uniform highp uimage2D uAccumulatorRw; + layout(r32ui, binding = 1) writeonly uniform highp uimage2D uAccumulatorGw; + layout(r32ui, binding = 2) writeonly uniform highp uimage2D uAccumulatorBw; + uniform ivec2 uImageSize; + + void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= uImageSize.x || p.y >= uImageSize.y) return; + imageStore(uAccumulatorRw, p, uvec4(0u)); + imageStore(uAccumulatorGw, p, uvec4(0u)); + imageStore(uAccumulatorBw, p, uvec4(0u)); } """.trimIndent() @@ -4884,8 +5813,8 @@ class GlesRawStacker( uniform sampler2D uTileMask; uniform sampler2D uKernel; uniform sampler2D uLensShadingMap; - uniform sampler2D uAccumulatorInput; - layout(rgba16f, binding = 0) writeonly uniform highp image2D uAccumulatorOutput; + layout(r32ui, binding = 0) uniform highp uimage2D uAccumulatorValueWeight; + layout(r32ui, binding = 1) uniform highp uimage2D uAccumulatorStatistics; uniform ivec2 uImageSize; uniform ivec2 uPlaneSize; uniform ivec2 uGridSize; @@ -4923,7 +5852,7 @@ class GlesRawStacker( uniform float uHighlightSuppressionEnd; vec2 flowAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; } @@ -4936,7 +5865,7 @@ class GlesRawStacker( } float tileMaskAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uTileMask, clamp(uv, vec2(0.0), vec2(1.0))).r; } @@ -4959,7 +5888,9 @@ class GlesRawStacker( samplePos = clamp(samplePos, ivec2(0), uImageSize - ivec2(1)); float raw = float(texelFetch(uInputRaw, samplePos, 0).r); float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); - return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(samplePos) / range, 0.0, 1.0); + // Keep HDR headroom until the sample has been mapped to the short-exposure + // output domain. Clamping here destroys channel ratios before uExposureScale. + return max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(samplePos) / range; } float rawSensorNormAt(ivec2 samplePos) { @@ -4998,7 +5929,7 @@ class GlesRawStacker( float tileMean = tileSensorMean(samplePos); float pixelClip = smoothstep(0.90, 0.985, pixel); float tileMeanGate = smoothstep(0.68, 0.88, tileMean); - float edgeProtect = smoothstep(0.30, 0.10, tile - pixel); + float edgeProtect = 1.0 - smoothstep(0.10, 0.30, tile - pixel); float tileClip = smoothstep(0.91, 0.995, tile) * tileMeanGate * edgeProtect; return clamp(max(pixelClip, 0.62 * tileClip), 0.0, 1.0); } @@ -5052,6 +5983,29 @@ class GlesRawStacker( return phaseOffset + lattice * period; } + float kernelSupportHighlightInfluence(vec2 rawPos, ivec2 phaseOffset, int period) { + ivec2 maxLattice = maxLatticeForPhase(phaseOffset, period); + vec2 phase = vec2(float(phaseOffset.x), float(phaseOffset.y)); + vec2 latticePos = clamp( + (rawPos - phase) / float(period), + vec2(0.0), + vec2(float(maxLattice.x), float(maxLattice.y)) + ); + ivec2 latticeBase = ivec2(floor(latticePos)); + float maxSensorSignal = 0.0; + // The 3x3 reconstruction taps each use bilinear same-phase sampling. Their union + // is the 4x4 lattice footprint [base-1, base+2]. Record the complete support so + // every destination block modified by a highlight can preserve short-frame chroma. + for (int y = -1; y <= 2; ++y) { + for (int x = -1; x <= 2; ++x) { + ivec2 lattice = clamp(latticeBase + ivec2(x, y), ivec2(0), maxLattice); + ivec2 samplePos = phaseOffset + lattice * period; + maxSensorSignal = max(maxSensorSignal, rawSensorNormAt(samplePos)); + } + } + return step(0.90, maxSensorSignal); + } + vec3 kernelMatrix(vec4 params) { float k1 = params.x; float k2 = params.y; @@ -5117,13 +6071,32 @@ class GlesRawStacker( return clamp(tileConfidence * robustConfidence, 0.0, 1.0); } + vec4 loadAccumulator(ivec2 p) { + vec2 valueWeight = unpackHalf2x16(imageLoad(uAccumulatorValueWeight, p).r); + vec2 statistics = unpackHalf2x16(imageLoad(uAccumulatorStatistics, p).r); + return vec4(valueWeight, statistics); + } + + void storeAccumulator(ivec2 p, vec4 value) { + imageStore( + uAccumulatorValueWeight, + p, + uvec4(packHalf2x16(value.rg), 0u, 0u, 0u) + ); + imageStore( + uAccumulatorStatistics, + p, + uvec4(packHalf2x16(value.ba), 0u, 0u, 0u) + ); + } + void main() { ivec2 p = ivec2( int(gl_GlobalInvocationID.x), int(gl_GlobalInvocationID.y) + uImageRowOffset ); if (p.x >= uImageSize.x || p.y >= uImageSize.y) return; - vec4 prev = texelFetch(uAccumulatorInput, p, 0); + vec4 prev = loadAccumulator(p); int bayerIndex = bayerIndexAt(uCfaPattern, p); int period = cfaPeriod(uCfaPattern); ivec2 phaseOffset = cfaPhaseOffset(uCfaPattern, p); @@ -5131,7 +6104,7 @@ class GlesRawStacker( if (planePos.x < -0.001 || planePos.y < -0.001 || planePos.x > float(uPlaneSize.x - 1) + 0.001 || planePos.y > float(uPlaneSize.y - 1) + 0.001) { - imageStore(uAccumulatorOutput, p, prev); + storeAccumulator(p, prev); return; } @@ -5140,12 +6113,14 @@ class GlesRawStacker( float local = 1.0; float alignmentRobust = 1.0; float clipAlpha = 0.0; + float highlightInfluence = 0.0; float sourceLscNoiseGain = 1.0; if (uIsReference != 0) { value = rawNormAt(p, bayerIndex); sourceLscNoiseGain = lscNoiseGain(p); if (uHdrMode != 0) { clipAlpha = highlightClipAlpha(p); + highlightInfluence = step(0.90, rawSensorNormAt(p)); } } else { // Robustness and tile acceptance are evaluated with this exact local-flow warp. @@ -5155,7 +6130,7 @@ class GlesRawStacker( if (sourcePlane.x < 0.0 || sourcePlane.y < 0.0 || sourcePlane.x > float(uPlaneSize.x - 1) || sourcePlane.y > float(uPlaneSize.y - 1)) { - imageStore(uAccumulatorOutput, p, prev); + storeAccumulator(p, prev); return; } alignmentRobust = mapAt(uRobustness, planePos); @@ -5163,22 +6138,47 @@ class GlesRawStacker( local = tileMaskAt(planePos); float base = local * max(robust, uRobustnessFloorFactor * local); if (base <= uMinBlendBaseWeight) { - imageStore(uAccumulatorOutput, p, prev); + storeAccumulator(p, prev); return; } vec2 sourceRaw = vec2(p) + (sourcePlane - planePos) * 2.0; - value = sampleSamePhase(sourceRaw, phaseOffset, period, bayerIndex); + if (uHdrMode != 0) { + highlightInfluence = kernelSupportHighlightInfluence(sourceRaw, phaseOffset, period); + ivec2 kernelCoord = clamp(ivec2(round(planePos)), ivec2(0), uPlaneSize - ivec2(1)); + vec4 kernel = texelFetch(uKernel, kernelCoord, 0); + float sumValue = 0.0; + float sumWeight = 0.0; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + vec2 tap = vec2(float(x), float(y)); + float tapWeight = kernelWeight(tap, kernel); + sumValue += sampleSamePhase( + sourceRaw + tap * float(period), + phaseOffset, + period, + bayerIndex + ) * tapWeight; + sumWeight += tapWeight; + } + } + value = sumValue / max(sumWeight, 1e-5); + } else { + value = sampleSamePhase(sourceRaw, phaseOffset, period, bayerIndex); + } ivec2 sourceSample = nearestSamePhase(sourceRaw, phaseOffset, period); sourceLscNoiseGain = lscNoiseGain(sourceSample); if (uHdrMode != 0) { clipAlpha = highlightClipAlpha(sourceSample); + float highlightSuppression = 1.0 - 0.62 * smoothstep(0.78, 0.98, value); + highlightSuppression *= 1.0 - clipAlpha; + robust = base * highlightSuppression; } else { clipAlpha = nonReferenceOverexposureAlpha(sourceSample, value); + float highlightSuppression = 1.0 - uHighlightSuppressionStrength * + smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, value); + highlightSuppression *= 1.0 - clipAlpha; + robust = base * highlightSuppression; } - float highlightSuppression = 1.0 - uHighlightSuppressionStrength * - smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, value); - highlightSuppression *= 1.0 - clipAlpha; - robust = base * highlightSuppression; } float sourceValue = value; @@ -5190,7 +6190,8 @@ class GlesRawStacker( float weight = precisionWeight * (uWienerBaseWeight + wiener); float denoiseAmount = denoiseNeed(sourceValue, sourceLscNoiseGain); if (uIsReference == 0) { - float staticConfidence = denoiseStaticConfidence(local, alignmentRobust) * (1.0 - clipAlpha); + float staticConfidence = denoiseStaticConfidence(local, alignmentRobust); + if (uHdrMode == 0) staticConfidence *= 1.0 - clipAlpha; float denoiseBoost = denoiseAmount * staticConfidence; weight *= uFrameWeight * robust; weight *= mix(1.0, max(uDenoiseNonReferenceWeightBoost, 1.0), denoiseBoost); @@ -5203,15 +6204,16 @@ class GlesRawStacker( weight *= mix(1.0, clamp(uDenoiseReferenceDarkWeightScale, 0.05, 1.0), denoiseAmount); } if (uHdrMode != 0) { - weight *= 1.0 - 0.90 * clipAlpha; + weight *= 1.0 - clipAlpha; } - if (weight <= 0.0 && (uHdrMode == 0 || clipAlpha <= 0.0)) { - imageStore(uAccumulatorOutput, p, prev); + if (weight <= 0.0 && + (uHdrMode == 0 || (clipAlpha <= 0.0 && highlightInfluence <= 0.0))) { + storeAccumulator(p, prev); return; } float clipMass = uHdrMode != 0 ? - precisionWeight * uFrameWeight * clipAlpha : + precisionWeight * uFrameWeight * max(clipAlpha, highlightInfluence) : weight * clamp(robust, 0.0, 1.0); vec4 next = prev + vec4( outputValue * weight, @@ -5219,7 +6221,7 @@ class GlesRawStacker( outputValue * outputValue * weight, clipMass ); - imageStore(uAccumulatorOutput, p, next); + storeAccumulator(p, next); } """.trimIndent() @@ -5227,15 +6229,21 @@ class GlesRawStacker( #version 310 es $RAW_COMMON layout(local_size_x = 16, local_size_y = 16) in; - uniform highp usampler2D uInputRaw; + uniform highp usampler2D uInputRaw; // Removed with the remaining legacy CFA helpers. uniform sampler2D uFlowGrid; uniform sampler2D uRobustness; uniform sampler2D uTileMask; uniform sampler2D uKernel; uniform sampler2D uLensShadingMap; - uniform sampler2D uAccumulatorInput; - layout(rgba16f, binding = 0) writeonly uniform highp image2D uAccumulatorOutput; + layout(r32ui, binding = 0) uniform highp uimage2D uAccumulatorRw; + layout(r32ui, binding = 1) uniform highp uimage2D uAccumulatorGw; + layout(r32ui, binding = 2) uniform highp uimage2D uAccumulatorBw; + layout(std430, binding = 1) readonly buffer RcdRgb0_Buf { float rcdRgb0[]; }; + layout(std430, binding = 2) readonly buffer RcdRgb1_Buf { float rcdRgb1[]; }; + layout(std430, binding = 3) readonly buffer RcdRgb2_Buf { float rcdRgb2[]; }; uniform ivec2 uImageSize; + uniform ivec2 uSourceSize; + uniform int uSourceRowOffset; uniform ivec2 uOutputSize; uniform ivec2 uPlaneSize; uniform ivec2 uGridSize; @@ -5262,40 +6270,21 @@ class GlesRawStacker( uniform float uHighlightSuppressionStrength; uniform float uHighlightSuppressionStart; uniform float uHighlightSuppressionEnd; - uniform mat3 uRegistrationTransform; - uniform int uRegistrationForceIdentity; - uniform float uLocalFlowResidualStrength; - uniform float uLocalFlowResidualMaxPx; uniform int uOutputRowOffset; + uniform int uOutputRowCount; vec2 referenceRawPos(ivec2 outputPos) { return (vec2(outputPos) + vec2(0.5)) / max(uOutputScale, 1.0) - vec2(0.5); } vec2 flowAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; } - vec2 registrationSourceRaw(vec2 rawPos) { - if (uRegistrationForceIdentity != 0) { - return rawPos; - } - vec3 mapped = uRegistrationTransform * vec3(rawPos, 1.0); - float z = abs(mapped.z) > 1e-6 ? mapped.z : 1.0; - vec2 source = mapped.xy / z; - if (any(isnan(source)) || any(isinf(source))) { - return rawPos; - } - vec2 flowSource = rawPos + flowAt(rawPos * 0.5) * 2.0; - vec2 residual = flowSource - source; - float residualLength = length(residual); - if (residualLength > max(uLocalFlowResidualMaxPx, 0.0) && residualLength > 1e-6) { - residual *= max(uLocalFlowResidualMaxPx, 0.0) / residualLength; - } - source += residual * clamp(uLocalFlowResidualStrength, 0.0, 1.0); - return source; + vec2 localFlowSourceRaw(vec2 rawPos) { + return rawPos + flowAt(rawPos * 0.5) * 2.0; } float mapAt(sampler2D tex, vec2 planePos) { @@ -5304,7 +6293,7 @@ class GlesRawStacker( } float tileMaskAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uTileMask, clamp(uv, vec2(0.0), vec2(1.0))).r; } @@ -5369,10 +6358,6 @@ class GlesRawStacker( return clamp(max(pixelClip, 0.75 * tileClip), 0.0, 1.0); } - bool isGreenSample(int bayerIndex) { - return bayerIndex == 1 || bayerIndex == 2; - } - vec3 kernelMatrix(vec4 params) { float k1 = params.x; float k2 = params.y; @@ -5410,192 +6395,310 @@ class GlesRawStacker( return clamp(referenceVariance / variance, 0.05, 4.0); } - void main() { - ivec2 p = ivec2( - int(gl_GlobalInvocationID.x), - int(gl_GlobalInvocationID.y) + uOutputRowOffset - ); - if (p.x >= uOutputSize.x || p.y >= uOutputSize.y) return; + ivec2 phaseForBayerIndex(int bayerIndex) { + int period = cfaPeriod(uCfaPattern); + for (int y = 0; y < 8; ++y) { + for (int x = 0; x < 8; ++x) { + if (x < period && y < period && + bayerIndexAt(uCfaPattern, ivec2(x, y)) == bayerIndex) { + return ivec2(x, y); + } + } + } + return ivec2(0); + } - vec4 prev = texelFetch(uAccumulatorInput, p, 0); + vec2 channelObservation(vec2 rawPos, int bayerIndex, vec4 steeringKernel) { + int period = cfaPeriod(uCfaPattern); + ivec2 phaseOffset = phaseForBayerIndex(bayerIndex); + ivec2 maxLattice = max( + (uImageSize - ivec2(1) - phaseOffset) / ivec2(period), + ivec2(0) + ); + vec2 lattice = clamp( + (rawPos - vec2(phaseOffset)) / float(period), + vec2(0.0), + vec2(maxLattice) + ); + ivec2 p0 = ivec2(floor(lattice)); + ivec2 p1 = min(p0 + ivec2(1), maxLattice); + float sigma = max(uSrSplatRadius, 0.25); + float valueSum = 0.0; + float weightSum = 0.0; + for (int y = 0; y <= 1; ++y) { + for (int x = 0; x <= 1; ++x) { + ivec2 q = ivec2(x == 0 ? p0.x : p1.x, y == 0 ? p0.y : p1.y); + ivec2 samplePos = phaseOffset + q * period; + vec2 delta = vec2(samplePos) - rawPos; + ivec2 qxm = max(q - ivec2(1, 0), ivec2(0)); + ivec2 qxp = min(q + ivec2(1, 0), maxLattice); + ivec2 qym = max(q - ivec2(0, 1), ivec2(0)); + ivec2 qyp = min(q + ivec2(0, 1), maxLattice); + float center = rawNormAt(samplePos, bayerIndex); + float xm = rawNormAt(phaseOffset + qxm * period, bayerIndex); + float xp = rawNormAt(phaseOffset + qxp * period, bayerIndex); + float ym = rawNormAt(phaseOffset + qym * period, bayerIndex); + float yp = rawNormAt(phaseOffset + qyp * period, bayerIndex); + float spanX = max(float(qxp.x - qxm.x) * float(period), 1.0); + float spanY = max(float(qyp.y - qym.y) * float(period), 1.0); + vec2 gradient = vec2((xp - xm) / spanX, (yp - ym) / spanY); + // First-order local polynomial regression evaluated at the target point. + // Clamp to the observed same-color neighborhood to prevent ringing at + // clipped edges and isolated hot pixels. + float projected = center - dot(gradient, delta); + float localMin = min(center, min(min(xm, xp), min(ym, yp))); + float localMax = max(center, max(max(xm, xp), max(ym, yp))); + float value = clamp(projected, localMin, localMax); + value = clamp(value * uExposureScale, 0.0, 1.0); + float spatialWeight = exp(-0.5 * dot(delta, delta) / (sigma * sigma)); + spatialWeight *= kernelWeight(delta * 0.5, steeringKernel); + valueSum += value * spatialWeight; + weightSum += spatialWeight; + } + } + return vec2(valueSum, weightSum); + } + + float cubicWeight(float x) { + x = abs(x); + if (x < 1.0) return 1.5 * x * x * x - 2.5 * x * x + 1.0; + if (x < 2.0) return -0.5 * x * x * x + 2.5 * x * x - 4.0 * x + 2.0; + return 0.0; + } + + vec3 rcdRgbAt(ivec2 p) { + p = clamp(p, ivec2(0), uSourceSize - ivec2(1)); + int index = p.y * uSourceSize.x + p.x; + return vec3(rcdRgb0[index], rcdRgb1[index], rcdRgb2[index]); + } + + vec3 sampleRcdRgb(vec2 globalRawPos) { + vec2 localPos = globalRawPos - vec2(0.0, float(uSourceRowOffset)); + ivec2 origin = ivec2(floor(localPos)); + vec3 sum = vec3(0.0); + float weightSum = 0.0; + for (int y = -1; y <= 2; ++y) { + for (int x = -1; x <= 2; ++x) { + ivec2 q = origin + ivec2(x, y); + float weight = cubicWeight(localPos.x - float(q.x)) * + cubicWeight(localPos.y - float(q.y)); + sum += rcdRgbAt(q) * weight; + weightSum += weight; + } + } + return clamp(sum / max(weightSum, 1e-6), 0.0, 1.0); + } + + void main() { + ivec2 accumulatorP = ivec2(gl_GlobalInvocationID.xy); + ivec2 p = accumulatorP + ivec2(0, uOutputRowOffset); + if (accumulatorP.x >= uOutputSize.x || accumulatorP.y >= uOutputRowCount || + p.y >= uOutputSize.y) return; + + vec2 prevRw = unpackHalf2x16(imageLoad(uAccumulatorRw, accumulatorP).r); + vec2 prevGw = unpackHalf2x16(imageLoad(uAccumulatorGw, accumulatorP).r); + vec2 prevBw = unpackHalf2x16(imageLoad(uAccumulatorBw, accumulatorP).r); vec2 refRaw = referenceRawPos(p); vec2 planePos = refRaw * 0.5; - float robust = 1.0; - float base = 1.0; vec2 sourceRaw = refRaw; + float base = 1.0; if (uIsReference == 0) { - if (uRegistrationSrWeight <= 0.0) { - imageStore(uAccumulatorOutput, p, prev); - return; - } - sourceRaw = registrationSourceRaw(refRaw); + if (uRegistrationSrWeight <= 0.0) return; + sourceRaw = localFlowSourceRaw(refRaw); if (sourceRaw.x < -0.5 || sourceRaw.y < -0.5 || sourceRaw.x > float(uImageSize.x) - 0.5 || sourceRaw.y > float(uImageSize.y) - 0.5) { - imageStore(uAccumulatorOutput, p, prev); return; } float local = tileMaskAt(planePos); - robust = mapAt(uRobustness, planePos); + float robust = mapAt(uRobustness, planePos); base = local * max(robust, uRobustnessFloorFactor * local); - if (base <= max(uMinBlendBaseWeight, uSrMinEffectiveWeight * 0.25)) { - imageStore(uAccumulatorOutput, p, prev); - return; - } + if (base <= max(uMinBlendBaseWeight, uSrMinEffectiveWeight * 0.25)) return; } - ivec2 kernelCoord = clamp(ivec2(round(planePos)), ivec2(0), uPlaneSize - ivec2(1)); - vec4 kernel = texelFetch(uKernel, kernelCoord, 0); - float sigma = max(uSrSplatRadius, 0.25); - float greenLatticeOffset = isGreenSample(bayerIndexAt(uCfaPattern, ivec2(0))) ? 0.0 : 0.5; - vec2 sourceGreenUv = vec2( - 0.5 * (sourceRaw.x + sourceRaw.y), - 0.5 * (sourceRaw.x - sourceRaw.y) - ); - vec2 greenLatticeOrigin = floor(sourceGreenUv - vec2(greenLatticeOffset)) + - vec2(greenLatticeOffset); - vec2 greenLatticeFraction = sourceGreenUv - greenLatticeOrigin; - float valueSum = 0.0; - float weightSum = 0.0; - float squareSum = 0.0; - for (int latticeY = 0; latticeY <= 1; ++latticeY) { - for (int latticeX = 0; latticeX <= 1; ++latticeX) { - vec2 sampleUv = greenLatticeOrigin + vec2(latticeX, latticeY); - ivec2 sourceSample = ivec2(round(vec2( - sampleUv.x + sampleUv.y, - sampleUv.x - sampleUv.y - ))); - if (sourceSample.x < 0 || sourceSample.y < 0 || - sourceSample.x >= uImageSize.x || sourceSample.y >= uImageSize.y) { - continue; - } - int bayerIndex = bayerIndexAt(uCfaPattern, sourceSample); - if (!isGreenSample(bayerIndex)) continue; - - vec2 deltaRaw = vec2(sourceSample) - sourceRaw; - float distance2 = dot(deltaRaw, deltaRaw); - float latticeWeightX = latticeX == 0 ? - 1.0 - greenLatticeFraction.x : greenLatticeFraction.x; - float latticeWeightY = latticeY == 0 ? - 1.0 - greenLatticeFraction.y : greenLatticeFraction.y; - float footprint = latticeWeightX * latticeWeightY; - footprint *= exp(-0.5 * distance2 / (sigma * sigma)); - footprint *= kernelWeight(deltaRaw * 0.5, kernel); - if (footprint <= 1e-5) continue; - - float value = rawNormAt(sourceSample, bayerIndex); - float outputValue = clamp(value * uExposureScale, 0.0, 1.0); - float sourceLscNoiseGain = lscNoiseGain(sourceSample); - float variance = noiseVarianceForChannel(value, bayerIndex, sourceLscNoiseGain); - float outputVariance = variance * uExposureScale * uExposureScale; - float wiener = (outputValue * outputValue) / - (outputValue * outputValue + outputVariance + 1e-6); - float precisionWeight = sensorPrecisionWeight(value, bayerIndex, sourceLscNoiseGain); - float weight = precisionWeight * (uWienerBaseWeight + wiener) * footprint; - if (uIsReference == 0) { - float clipAlpha = highlightClipAlpha(sourceSample); - float highlightSuppression = 1.0 - uHighlightSuppressionStrength * - smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, outputValue); - weight *= uFrameWeight * base * highlightSuppression * (1.0 - clipAlpha) * - clamp(uRegistrationSrWeight, 0.0, 1.0); - } - valueSum += outputValue * weight; - weightSum += weight; - squareSum += outputValue * outputValue * weight; - } - } - if (weightSum <= 0.0) { - imageStore(uAccumulatorOutput, p, prev); - return; + vec3 rgb = sampleRcdRgb(sourceRaw) * uExposureScale; + float signal = max(max(rgb.r, rgb.g), rgb.b); + float temporalWeight = 1.0; + if (uIsReference == 0) { + float highlightSuppression = 1.0 - uHighlightSuppressionStrength * + smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, signal); + temporalWeight = uFrameWeight * base * highlightSuppression * + clamp(uRegistrationSrWeight, 0.0, 1.0); } + if (temporalWeight <= 1e-5) return; - vec4 next = prev + vec4( - valueSum, - weightSum, - squareSum, - uIsReference != 0 ? 0.0 : weightSum - ); - imageStore(uAccumulatorOutput, p, next); + vec2 nextRw = prevRw + vec2(rgb.r * temporalWeight, temporalWeight); + vec2 nextGw = prevGw + vec2(rgb.g * temporalWeight, temporalWeight); + vec2 nextBw = prevBw + vec2(rgb.b * temporalWeight, temporalWeight); + imageStore(uAccumulatorRw, accumulatorP, uvec4(packHalf2x16(nextRw), 0u, 0u, 0u)); + imageStore(uAccumulatorGw, accumulatorP, uvec4(packHalf2x16(nextGw), 0u, 0u, 0u)); + imageStore(uAccumulatorBw, accumulatorP, uvec4(packHalf2x16(nextBw), 0u, 0u, 0u)); } """.trimIndent() - private val SUPER_RESOLUTION_CHANNEL_RATIO_COMPUTE_SHADER = """ + private val SUPER_RESOLUTION_RCD_ACCUMULATE_COMPUTE_SHADER = """ #version 310 es $RAW_COMMON layout(local_size_x = 16, local_size_y = 16) in; - uniform sampler2D uBasePackedRaw; - layout(rgba16f, binding = 0) writeonly uniform highp image2D uChannelRatio; + uniform sampler2D uFlowGrid; + uniform sampler2D uRobustness; + uniform sampler2D uTileMask; + layout(r32ui, binding = 0) uniform highp uimage2D uAccumulatorRw; + layout(r32ui, binding = 1) uniform highp uimage2D uAccumulatorGw; + layout(r32ui, binding = 2) uniform highp uimage2D uAccumulatorBw; + layout(std430, binding = 1) readonly buffer RcdRgb0_Buf { float rcdRgb0[]; }; + layout(std430, binding = 2) readonly buffer RcdRgb1_Buf { float rcdRgb1[]; }; + layout(std430, binding = 3) readonly buffer RcdRgb2_Buf { float rcdRgb2[]; }; uniform ivec2 uImageSize; - uniform ivec2 uRatioSize; - uniform int uCfaPattern; + uniform ivec2 uOutputSize; + uniform ivec2 uPlaneSize; + uniform ivec2 uGridSize; + uniform ivec2 uSourceSize; + uniform int uSourceRowOffset; + uniform int uTileSize; + uniform int uIsReference; + uniform float uFrameWeight; + uniform float uExposureScale; + uniform float uOutputScale; + uniform float uRegistrationSrWeight; + uniform float uSrMinEffectiveWeight; + uniform float uMinBlendBaseWeight; + uniform float uRobustnessFloorFactor; + uniform float uHighlightSuppressionStrength; + uniform float uHighlightSuppressionStart; + uniform float uHighlightSuppressionEnd; + uniform float uDenoiseSignalLow; + uniform float uDenoiseSignalHigh; + uniform float uDenoiseStaticRobustStart; + uniform float uDenoiseStaticRobustEnd; + uniform float uDenoiseStaticTileStart; + uniform float uDenoiseStaticTileEnd; + uniform float uDenoiseNonReferenceWeightBoost; + uniform float uDenoiseNonReferenceWeightFloor; + uniform float uDenoiseReferenceDarkWeightScale; + uniform int uOutputRowOffset; + uniform int uOutputRowCount; - float basePackedNormAt(ivec2 samplePos) { - samplePos = clamp(samplePos, ivec2(0), uImageSize - ivec2(1)); - vec2 rg = texelFetch(uBasePackedRaw, samplePos, 0).rg; - float lo = floor(rg.r * 255.0 + 0.5); - float hi = floor(rg.g * 255.0 + 0.5); - return clamp((lo + hi * 256.0) / 65535.0, 0.0, 1.0); + vec2 referenceRawPos(ivec2 outputPos) { + return (vec2(outputPos) + vec2(0.5)) / max(uOutputScale, 1.0) - vec2(0.5); } - - vec3 cellSignals(ivec2 cell) { - cell = clamp(cell, ivec2(0), uRatioSize - ivec2(1)); - ivec2 origin = cell * 2; - float red = 0.0; - float green = 0.0; - float blue = 0.0; - float redCount = 0.0; - float greenCount = 0.0; - float blueCount = 0.0; - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - ivec2 samplePos = min(origin + ivec2(x, y), uImageSize - ivec2(1)); - int bayerIndex = bayerIndexAt(uCfaPattern, samplePos); - float value = basePackedNormAt(samplePos); - if (bayerIndex == 0) { - red += value; - redCount += 1.0; - } else if (bayerIndex == 3) { - blue += value; - blueCount += 1.0; - } else { - green += value; - greenCount += 1.0; - } - } - } - green /= max(greenCount, 1.0); - red = redCount > 0.0 ? red / redCount : green; - blue = blueCount > 0.0 ? blue / blueCount : green; - return vec3(red, green, blue); + vec2 flowAt(vec2 planePos) { + vec2 grid = planePos / float(uTileSize) - vec2(0.5); + return texture(uFlowGrid, clamp((grid + vec2(0.5)) / vec2(uGridSize), vec2(0.0), vec2(1.0))).rg; } - - void main() { - ivec2 p = ivec2(gl_GlobalInvocationID.xy); - if (p.x >= uRatioSize.x || p.y >= uRatioSize.y) return; - - vec3 center = cellSignals(p); - vec3 signalSum = vec3(0.0); - float weightSum = 0.0; - const float spatialSigma = 1.25; - for (int y = -2; y <= 2; ++y) { - for (int x = -2; x <= 2; ++x) { - vec3 signal = cellSignals(p + ivec2(x, y)); - float distance2 = float(x * x + y * y); - float spatialWeight = exp(-0.5 * distance2 / (spatialSigma * spatialSigma)); - float rangeWeight = exp(-abs(signal.g - center.g) * 12.0); - float weight = spatialWeight * rangeWeight; - signalSum += signal * weight; - weightSum += weight; - } + float mapAt(sampler2D tex, vec2 planePos) { + vec2 uv = (clamp(planePos, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); + return texture(tex, uv).r; + } + float tileMaskAt(vec2 planePos) { + vec2 grid = planePos / float(uTileSize) - vec2(0.5); + return texture(uTileMask, clamp((grid + vec2(0.5)) / vec2(uGridSize), vec2(0.0), vec2(1.0))).r; + } + float cubicWeight(float x) { + x = abs(x); + if (x < 1.0) return 1.5*x*x*x - 2.5*x*x + 1.0; + if (x < 2.0) return -0.5*x*x*x + 2.5*x*x - 4.0*x + 2.0; + return 0.0; + } + vec3 rcdRgbAt(ivec2 p) { + p = clamp(p, ivec2(0), uSourceSize - ivec2(1)); + int i = p.y * uSourceSize.x + p.x; + return vec3(rcdRgb0[i], rcdRgb1[i], rcdRgb2[i]); + } + vec3 sampleRcdRgb(vec2 globalRawPos) { + vec2 pos = globalRawPos - vec2(0.0, float(uSourceRowOffset)); + ivec2 origin = ivec2(floor(pos)); + vec3 sum = vec3(0.0); + float weight = 0.0; + for (int y = -1; y <= 2; ++y) for (int x = -1; x <= 2; ++x) { + ivec2 q = origin + ivec2(x, y); + float w = cubicWeight(pos.x - float(q.x)) * cubicWeight(pos.y - float(q.y)); + sum += rcdRgbAt(q) * w; + weight += w; } - vec3 low = signalSum / max(weightSum, 1e-6); - const float shadowRegularizer = 0.002; - vec2 ratio = vec2( - (low.r + shadowRegularizer) / (low.g + shadowRegularizer), - (low.b + shadowRegularizer) / (low.g + shadowRegularizer) + return clamp(sum / max(weight, 1e-6), 0.0, 1.0); + } + float denoiseNeed(float signal) { + return 1.0 - smoothstep( + min(uDenoiseSignalLow, uDenoiseSignalHigh), + max(uDenoiseSignalLow, uDenoiseSignalHigh), + signal ); - imageStore(uChannelRatio, p, vec4(clamp(ratio, vec2(0.0625), vec2(8.0)), 0.0, 1.0)); + } + float denoiseStaticConfidence(float local, float robust) { + float tileConfidence = smoothstep( + min(uDenoiseStaticTileStart, uDenoiseStaticTileEnd), + max(uDenoiseStaticTileStart, uDenoiseStaticTileEnd), + local + ); + float robustConfidence = smoothstep( + min(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), + max(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), + robust + ); + return clamp(tileConfidence * robustConfidence, 0.0, 1.0); + } + void main() { + ivec2 ap = ivec2(gl_GlobalInvocationID.xy); + ivec2 p = ap + ivec2(0, uOutputRowOffset); + if (ap.x >= uOutputSize.x || ap.y >= uOutputRowCount || p.y >= uOutputSize.y) return; + vec2 refRawPos = referenceRawPos(p); + vec2 planePos = refRawPos * 0.5; + vec2 sourceRaw = refRawPos; + float temporalWeight = 1.0; + float local = 1.0; + float robust = 1.0; + float srCoverage = 1.0; + if (uIsReference == 0) { + if (uRegistrationSrWeight <= 0.0) return; + sourceRaw += flowAt(planePos) * 2.0; + if (sourceRaw.x < 0.0 || sourceRaw.y < 0.0 || + sourceRaw.x > float(uImageSize.x - 1) || sourceRaw.y > float(uImageSize.y - 1)) return; + local = tileMaskAt(planePos); + robust = mapAt(uRobustness, planePos); + srCoverage = local * max(robust, uRobustnessFloorFactor * local); + // Registration already admitted this frame. Keep robustness continuous; + // the old CFA-SR hard threshold rejected nearly every RCD RGB observation. + temporalWeight = uFrameWeight * clamp(uRegistrationSrWeight, 0.0, 1.0); + } + vec3 rgb = clamp(sampleRcdRgb(sourceRaw) * uExposureScale, 0.0, 1.0); + float denoiseAmount = denoiseNeed(dot(rgb, vec3(0.2126, 0.7152, 0.0722))); + if (uIsReference == 0) { + float staticConfidence = denoiseStaticConfidence(local, robust); + float relaxedRobust = smoothstep( + 0.25 * min(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), + min(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), + robust + ); + // NR coverage is deliberately wider than SR detail coverage. Reliable flow in + // dark/flat regions still contributes temporal denoising even when the strict + // detail tile mask is low. + float nrCoverage = denoiseAmount * relaxedRobust * + max(uDenoiseNonReferenceWeightFloor, 0.0); + float fusionCoverage = max(srCoverage, nrCoverage); + temporalWeight *= fusionCoverage * mix( + 1.0, + max(uDenoiseNonReferenceWeightBoost, 1.0), + denoiseAmount * staticConfidence + ); + float signal = max(max(rgb.r, rgb.g), rgb.b); + temporalWeight *= 1.0 - uHighlightSuppressionStrength * + smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, signal); + } else { + temporalWeight *= mix( + 1.0, + clamp(uDenoiseReferenceDarkWeightScale, 0.05, 1.0), + denoiseAmount + ); + } + if (temporalWeight <= 1e-6) return; + vec2 rw = unpackHalf2x16(imageLoad(uAccumulatorRw, ap).r) + vec2(rgb.r, 1.0) * temporalWeight; + vec2 gw = unpackHalf2x16(imageLoad(uAccumulatorGw, ap).r) + vec2(rgb.g, 1.0) * temporalWeight; + vec2 bw = unpackHalf2x16(imageLoad(uAccumulatorBw, ap).r) + vec2(rgb.b, 1.0) * temporalWeight; + imageStore(uAccumulatorRw, ap, uvec4(packHalf2x16(rw), 0u, 0u, 0u)); + imageStore(uAccumulatorGw, ap, uvec4(packHalf2x16(gw), 0u, 0u, 0u)); + imageStore(uAccumulatorBw, ap, uvec4(packHalf2x16(bw), 0u, 0u, 0u)); } """.trimIndent() @@ -5604,13 +6707,12 @@ class GlesRawStacker( $RAW_COMMON in vec2 vTexCoord; out vec4 fragColor; - uniform sampler2D uSrAccumulator; + uniform highp usampler2D uSrAccumulator; + uniform highp usampler2D uSrAccumulatorBw; + uniform highp usampler2D uSrAccumulatorB; uniform sampler2D uBasePackedRaw; uniform sampler2D uLensShadingMap; - uniform sampler2D uChannelRatio; uniform ivec2 uImageSize; - uniform ivec2 uOutputSize; - uniform ivec2 uRatioSize; uniform int uCfaPattern; uniform float uOutputScale; uniform int uForceBaseUpscale; @@ -5621,17 +6723,26 @@ class GlesRawStacker( uniform float uLowLightSignalHigh; uniform float uLscSmoothGainStart; uniform float uLscSmoothGainEnd; - uniform float uGreenReconstructionLowLightSuppression; - uniform float uGreenReconstructionLscSuppression; + uniform float uReconstructionLowLightSuppression; + uniform float uReconstructionLscSuppression; + uniform int uOutputRowOffset; vec2 referenceRawPos(ivec2 outputPos) { return (vec2(outputPos) + vec2(0.5)) / max(uOutputScale, 1.0) - vec2(0.5); } - float greenLscNoiseGain(vec2 rawPos) { + float channelLscNoiseGain(vec2 rawPos) { vec2 uv = (rawPos + vec2(0.5)) / vec2(uImageSize); vec4 gains = texture(uLensShadingMap, uv); - return clamp(0.5 * (gains.g + gains.b), 1e-3, max(uLscNoiseGainMax, 1.0)); + ivec2 samplePos = clamp( + ivec2(round(rawPos)), + ivec2(0), + uImageSize - ivec2(1) + ); + int channel = lensShadingChannelAt(uCfaPattern, samplePos); + float gain = channel == 0 ? gains.r : + (channel == 1 ? gains.g : (channel == 2 ? gains.b : gains.a)); + return clamp(gain, 1e-3, max(uLscNoiseGainMax, 1.0)); } float basePackedNormAt(ivec2 samplePos) { @@ -5673,6 +6784,37 @@ class GlesRawStacker( return sampleBaseSamePhase(referenceRawPos(outputPos), phaseOffset, period); } + ivec2 phaseForBayerIndex(int bayerIndex) { + int period = cfaPeriod(uCfaPattern); + for (int y = 0; y < 8; ++y) { + for (int x = 0; x < 8; ++x) { + if (x < period && y < period && + bayerIndexAt(uCfaPattern, ivec2(x, y)) == bayerIndex) { + return ivec2(x, y); + } + } + } + return ivec2(0); + } + + vec3 baseLinearRgb(vec2 rawPos) { + int period = cfaPeriod(uCfaPattern); + float red = sampleBaseSamePhase(rawPos, phaseForBayerIndex(0), period); + float green = 0.5 * ( + sampleBaseSamePhase(rawPos, phaseForBayerIndex(1), period) + + sampleBaseSamePhase(rawPos, phaseForBayerIndex(2), period) + ); + float blue = sampleBaseSamePhase(rawPos, phaseForBayerIndex(3), period); + return vec3(red, green, blue); + } + + float mosaicValue(vec3 rgb, ivec2 outputPos) { + int channel = bayerIndexAt(uCfaPattern, outputPos); + if (channel == 0) return rgb.r; + if (channel == 3) return rgb.b; + return rgb.g; + } + float lowLightAmount(float signal) { return 1.0 - smoothstep( min(uLowLightSignalLow, uLowLightSignalHigh), @@ -5689,68 +6831,18 @@ class GlesRawStacker( ); } - float accumulatorSupportAt(ivec2 p) { - p = clamp(p, ivec2(0), uOutputSize - ivec2(1)); - return max(texelFetch(uSrAccumulator, p, 0).a, 0.0); - } - - bool isGreenSample(int bayerIndex) { - return bayerIndex == 1 || bayerIndex == 2; - } - - float channelRatioAt(vec2 rawPos, int bayerIndex) { - if (isGreenSample(bayerIndex)) return 1.0; - vec2 ratioSize = vec2(uRatioSize); - vec2 uv = (rawPos * 0.5 + vec2(0.25)) / ratioSize; - vec2 halfTexel = vec2(0.5) / ratioSize; - vec2 ratio = texture(uChannelRatio, clamp(uv, halfTexel, vec2(1.0) - halfTexel)).rg; - return bayerIndex == 0 ? ratio.r : ratio.g; - } - - float greenCellSupport(ivec2 p) { - ivec2 cellOrigin = p - ivec2(p.x & 1, p.y & 1); - cellOrigin = clamp(cellOrigin, ivec2(0), max(uOutputSize - ivec2(2), ivec2(0))); - float support = accumulatorSupportAt(cellOrigin); - support = min(support, accumulatorSupportAt(cellOrigin + ivec2(1, 0))); - support = min(support, accumulatorSupportAt(cellOrigin + ivec2(0, 1))); - support = min(support, accumulatorSupportAt(cellOrigin + ivec2(1, 1))); - return support; - } - void main() { ivec2 p = ivec2(gl_FragCoord.xy); - int bayerIndex = bayerIndexAt(uCfaPattern, p); - int period = cfaPeriod(uCfaPattern); - ivec2 phaseOffset = ivec2(p.x % period, p.y % period); - vec4 a = texelFetch(uSrAccumulator, p, 0); - float baseCfa = baseOutputNorm(p, period, phaseOffset); - if (uForceBaseUpscale != 0) { - uint raw = uint(floor(clamp(baseCfa, 0.0, 1.0) * 65535.0 + 0.5)); - uint lo = raw & 255u; - uint hi = (raw >> 8) & 255u; - fragColor = vec4(float(lo) / 255.0, float(hi) / 255.0, 0.0, 1.0); - return; - } - float srGreen = a.g > 1e-5 ? clamp(a.r / max(a.g, 1e-5), 0.0, 1.0) : baseCfa; - float detailSupport = greenCellSupport(p); - float confidence = smoothstep( - max(uDetailConfidenceStart, 0.02), - max(uDetailConfidenceFull, max(uDetailConfidenceStart, 0.02) + 1e-4), - detailSupport - ); - vec2 rawPos = referenceRawPos(p); - float lowLight = lowLightAmount(max(baseCfa, srGreen)); - float lsc = lscSmoothAmount(greenLscNoiseGain(rawPos)); - float reconstructionReliability = 1.0 - clamp( - uGreenReconstructionLowLightSuppression * lowLight + - uGreenReconstructionLscSuppression * lsc, - 0.0, - 0.95 - ); - float reconstructionWeight = confidence * reconstructionReliability; - float channelRatio = channelRatioAt(rawPos, bayerIndex); - float reconstructedCfa = clamp(srGreen * channelRatio, 0.0, 1.0); - float fused = mix(baseCfa, reconstructedCfa, reconstructionWeight); + ivec2 accumulatorP = p - ivec2(0, uOutputRowOffset); + vec2 accumulatedRw = unpackHalf2x16(texelFetch(uSrAccumulator, accumulatorP, 0).r); + vec2 accumulatedGw = unpackHalf2x16(texelFetch(uSrAccumulatorBw, accumulatorP, 0).r); + vec2 accumulatedBw = unpackHalf2x16(texelFetch(uSrAccumulatorB, accumulatorP, 0).r); + vec3 reconstructedRgb = clamp(vec3( + accumulatedRw.x / max(accumulatedRw.y, 1e-5), + accumulatedGw.x / max(accumulatedGw.y, 1e-5), + accumulatedBw.x / max(accumulatedBw.y, 1e-5) + ), 0.0, 1.0); + float fused = mosaicValue(reconstructedRgb, p); uint raw = uint(floor(fused * 65535.0 + 0.5)); uint lo = raw & 255u; @@ -5759,232 +6851,348 @@ class GlesRawStacker( } """.trimIndent() + /** Pure RCD-MFSR normalization; intentionally contains no base or fallback input. */ + private val SUPER_RESOLUTION_NORMALIZE_RCD_FRAGMENT_SHADER = """ + #version 300 es + $RAW_COMMON + in vec2 vTexCoord; + out vec4 fragColor; + uniform highp usampler2D uSrAccumulator; + uniform highp usampler2D uSrAccumulatorBw; + uniform highp usampler2D uSrAccumulatorB; + uniform int uCfaPattern; + uniform int uAccumulatorRowOffset; + uniform float uNoiseAlphaByChannel[4]; + uniform float uNoiseBetaByChannel[4]; + uniform float uFinalSmoothStrength; + uniform float uFlatVarianceStart; + uniform float uFlatVarianceEnd; + uniform float uDetailKeepNoiseLowScale; + uniform float uDetailKeepNoiseHighScale; + uniform float uDetailKeepOffsetLow; + uniform float uDetailKeepOffsetHigh; + uniform float uDetailKeepSuppression; + uniform float uPostfilterNoiseFloor; + uniform float uLowLightSignalLow; + uniform float uLowLightSignalHigh; + uniform float uLowLightSmoothBoost; + uniform float uMaxSmoothStrength; + + vec4 rgbWeightAt(ivec2 p) { + ivec2 size = textureSize(uSrAccumulator, 0); + p = clamp(p, ivec2(0), size - ivec2(1)); + vec2 rw = unpackHalf2x16(texelFetch(uSrAccumulator, p, 0).r); + vec2 gw = unpackHalf2x16(texelFetch(uSrAccumulatorBw, p, 0).r); + vec2 bw = unpackHalf2x16(texelFetch(uSrAccumulatorB, p, 0).r); + return vec4( + rw.x / max(rw.y, 1e-6), + gw.x / max(gw.y, 1e-6), + bw.x / max(bw.y, 1e-6), + min(rw.y, min(gw.y, bw.y)) + ); + } + + void main() { + ivec2 outputPos = ivec2(gl_FragCoord.xy); + ivec2 stripePos = outputPos - ivec2(0, uAccumulatorRowOffset); + vec4 centerSample = rgbWeightAt(stripePos); + vec3 rgb = clamp(centerSample.rgb, 0.0, 1.0); + vec3 mean = vec3(0.0); + vec3 mean2 = vec3(0.0); + float count = 0.0; + for (int y = -2; y <= 2; ++y) { + for (int x = -2; x <= 2; ++x) { + vec3 value = rgbWeightAt(stripePos + ivec2(x, y)).rgb; + mean += value; + mean2 += value * value; + count += 1.0; + } + } + mean /= count; + mean2 /= count; + vec3 variance = max(mean2 - mean * mean, vec3(0.0)); + vec3 alpha = vec3( + uNoiseAlphaByChannel[0], + 0.5 * (uNoiseAlphaByChannel[1] + uNoiseAlphaByChannel[2]), + uNoiseAlphaByChannel[3] + ); + vec3 beta = vec3( + uNoiseBetaByChannel[0], + 0.5 * (uNoiseBetaByChannel[1] + uNoiseBetaByChannel[2]), + uNoiseBetaByChannel[3] + ); + vec3 noise = max( + alpha * rgb + beta, + vec3(max(uPostfilterNoiseFloor, 0.0)) + ) / max(centerSample.a, 1.0); + vec3 structure = max(variance - noise, vec3(0.0)); + vec3 wienerGain = structure / max(variance, vec3(1e-6)); + vec3 denoised = mean + wienerGain * (rgb - mean); + vec3 noiseStd = sqrt(max(noise, vec3(1e-10))); + vec3 detail = abs(rgb - mean); + vec3 detailKeep = smoothstep( + uDetailKeepNoiseLowScale * noiseStd + vec3(uDetailKeepOffsetLow), + uDetailKeepNoiseHighScale * noiseStd + vec3(uDetailKeepOffsetHigh), + detail + ); + vec3 flatness = vec3(1.0) - smoothstep( + vec3(uFlatVarianceStart), vec3(uFlatVarianceEnd), structure + ); + float luma = dot(rgb, vec3(0.2126, 0.7152, 0.0722)); + float shadow = 1.0 - smoothstep( + min(uLowLightSignalLow, uLowLightSignalHigh), + max(uLowLightSignalLow, uLowLightSignalHigh), + luma + ); + vec3 smoothAmount = uFinalSmoothStrength * flatness * + (vec3(1.0) - uDetailKeepSuppression * detailKeep) * + (1.0 + uLowLightSmoothBoost * shadow); + smoothAmount = clamp(smoothAmount, vec3(0.0), vec3(uMaxSmoothStrength)); + rgb = clamp(mix(rgb, denoised, smoothAmount), 0.0, 1.0); + int channel = bayerIndexAt(uCfaPattern, outputPos); + float value = channel == 0 ? rgb.r : (channel == 3 ? rgb.b : rgb.g); + uint raw = uint(floor(value * 65535.0 + 0.5)); + fragColor = vec4( + float(raw & 255u) / 255.0, + float((raw >> 8) & 255u) / 255.0, + 0.0, + 1.0 + ); + } + """.trimIndent() + + private val HDR_SHORT_GLOBAL_ALIGN_COMPUTE_SHADER = """ + #version 310 es + precision highp float; + precision highp int; + layout(local_size_x = 8, local_size_y = 8) in; + uniform sampler2D uReference; + uniform sampler2D uCurrent; + uniform ivec2 uLevelSize; + uniform int uLevelScale; + uniform int uSearchRadius; + uniform int uSampleStep; + uniform int uSampleBorder; + layout(std430, binding = $HDR_123_SHORT_ALIGNMENT_SCORE_BUFFER_BINDING) buffer HdrShortAlignmentScores { + float scores[]; + }; + + const int LOCAL_COUNT = 64; + const int SCORE_STRIDE = $HDR_123_SHORT_ALIGNMENT_SCORE_STRIDE; + shared float sadParts[LOCAL_COUNT]; + shared float weightParts[LOCAL_COUNT]; + shared float sampleParts[LOCAL_COUNT]; + + vec2 readProxy(sampler2D tex, ivec2 p) { + p = clamp(p, ivec2(0), uLevelSize - ivec2(1)); + return texelFetch(tex, p, 0).rg; + } + + bool insideLevel(ivec2 p) { + return p.x >= 0 && p.y >= 0 && p.x < uLevelSize.x && p.y < uLevelSize.y; + } + + float detailAt(ivec2 p) { + float c = readProxy(uReference, p).r; + float gx = abs(readProxy(uReference, p + ivec2(1, 0)).r - readProxy(uReference, p - ivec2(1, 0)).r); + float gy = abs(readProxy(uReference, p + ivec2(0, 1)).r - readProxy(uReference, p - ivec2(0, 1)).r); + float lap = abs(4.0 * c - + readProxy(uReference, p + ivec2(1, 0)).r - + readProxy(uReference, p - ivec2(1, 0)).r - + readProxy(uReference, p + ivec2(0, 1)).r - + readProxy(uReference, p - ivec2(0, 1)).r); + return gx + gy + 0.5 * lap; + } + + void main() { + ivec2 candidate = ivec2(gl_WorkGroupID.xy); + int scoreSide = uSearchRadius * 2 + 1; + if (candidate.x >= scoreSide || candidate.y >= scoreSide) return; + ivec2 localId = ivec2(gl_LocalInvocationID.xy); + int localIndex = localId.y * 8 + localId.x; + ivec2 shift = candidate - ivec2(uSearchRadius); + int sampleWidth = max(0, (uLevelSize.x - 2 * uSampleBorder + uSampleStep - 1) / uSampleStep); + int sampleHeight = max(0, (uLevelSize.y - 2 * uSampleBorder + uSampleStep - 1) / uSampleStep); + int totalSamples = sampleWidth * sampleHeight; + float sad = 0.0; + float weight = 0.0; + float sampleCount = 0.0; + for (int sampleIndex = localIndex; sampleIndex < totalSamples; sampleIndex += LOCAL_COUNT) { + int sx = sampleIndex - (sampleIndex / sampleWidth) * sampleWidth; + int sy = sampleIndex / sampleWidth; + ivec2 rp = ivec2(uSampleBorder + sx * uSampleStep, uSampleBorder + sy * uSampleStep); + ivec2 cp = rp + shift; + sampleCount += 1.0; + if (!insideLevel(cp)) continue; + vec2 rv = readProxy(uReference, rp); + vec2 cv = readProxy(uCurrent, cp); + float detail = clamp(detailAt(rp) * 18.0, 0.08, 1.0); + float w = min(rv.g, cv.g) * detail; + sad += abs(rv.r - cv.r) * w; + weight += w; + } + sadParts[localIndex] = sad; + weightParts[localIndex] = weight; + sampleParts[localIndex] = sampleCount; + memoryBarrierShared(); + barrier(); + if (localIndex != 0) return; + float totalSad = 0.0; + float totalWeight = 0.0; + float totalSampleCount = 0.0; + for (int i = 0; i < LOCAL_COUNT; ++i) { + totalSad += sadParts[i]; + totalWeight += weightParts[i]; + totalSampleCount += sampleParts[i]; + } + float coverage = totalWeight / max(totalSampleCount, 1.0); + float shiftPenalty = 0.0008 * float(shift.x * shift.x + shift.y * shift.y); + float score = totalSad / max(totalWeight, 1e-4) + + 0.12 * (1.0 - clamp(coverage, 0.0, 1.0)) + shiftPenalty; + int offset = (candidate.y * scoreSide + candidate.x) * SCORE_STRIDE; + scores[offset + 0] = float(shift.x * uLevelScale); + scores[offset + 1] = float(shift.y * uLevelScale); + scores[offset + 2] = score; + scores[offset + 3] = coverage; + } + """.trimIndent() + private val HDR_RECOVERY_MASK_FRAGMENT_SHADER = """ #version 300 es $RAW_COMMON in vec2 vTexCoord; out vec4 fragColor; - uniform sampler2D uAccumulator; + uniform highp usampler2D uAccumulatorValueWeight; + uniform highp usampler2D uAccumulatorStatistics; uniform highp usampler2D uReferenceRaw; - uniform highp usampler2D uShortRaw; - uniform sampler2D uShortGlobalAlignment; uniform ivec2 uImageSize; uniform ivec2 uPlaneSize; uniform int uCfaPattern; uniform float uBlackLevel[4]; uniform float uWhiteLevel; - uniform float uShortToReferenceExposureScale; + uniform float uNoiseAlphaByChannel[4]; + uniform float uNoiseBetaByChannel[4]; ivec2 clampRaw(ivec2 p) { return clamp(p, ivec2(0), uImageSize - ivec2(1)); } - float sensorNorm(usampler2D tex, ivec2 p) { + float sensorNorm(ivec2 p) { p = clampRaw(p); int bayerIndex = bayerIndexAt(uCfaPattern, p); - float raw = float(texelFetch(tex, p, 0).r); + float raw = float(texelFetch(uReferenceRaw, p, 0).r); float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) / range, 0.0, 1.0); } - vec2 shortAlignedRawPos(ivec2 p) { - vec2 rawOffset = texelFetch(uShortGlobalAlignment, ivec2(0), 0).rg * 2.0; - vec2 rawPos = vec2(float(p.x), float(p.y)) + rawOffset; - vec2 maxRawPos = vec2(float(uImageSize.x - 1), float(uImageSize.y - 1)); - return clamp(rawPos, vec2(0.0), maxRawPos); - } - - ivec2 cfaPhaseOffset(int cfaPattern, ivec2 p) { - int period = cfaPeriod(cfaPattern); - return ivec2(p.x % period, p.y % period); - } - - ivec2 maxLatticeForPhase(ivec2 phaseOffset, int period) { - return max((uImageSize - ivec2(1) - phaseOffset) / ivec2(period), ivec2(0)); - } - - float shortRawNormAt(ivec2 samplePos, int bayerIndex) { - samplePos = clampRaw(samplePos); - float raw = float(texelFetch(uShortRaw, samplePos, 0).r); - float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); - return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) / range, 0.0, 1.0); - } - - float fetchShortSamePhase(ivec2 lattice, ivec2 phaseOffset, int period, int bayerIndex) { - lattice = clamp(lattice, ivec2(0), maxLatticeForPhase(phaseOffset, period)); - return shortRawNormAt(phaseOffset + lattice * period, bayerIndex); - } - - float sampleShortSamePhase(vec2 rawPos, ivec2 phaseOffset, int period, int bayerIndex) { - ivec2 maxLattice = maxLatticeForPhase(phaseOffset, period); - vec2 phase = vec2(float(phaseOffset.x), float(phaseOffset.y)); - vec2 pos = clamp( - (rawPos - phase) / float(period), - vec2(0.0), - vec2(float(maxLattice.x), float(maxLattice.y)) - ); - ivec2 p0 = ivec2(floor(pos)); - ivec2 p1 = min(p0 + ivec2(1), maxLattice); - vec2 f = pos - vec2(p0); - float v00 = fetchShortSamePhase(p0, phaseOffset, period, bayerIndex); - float v10 = fetchShortSamePhase(ivec2(p1.x, p0.y), phaseOffset, period, bayerIndex); - float v01 = fetchShortSamePhase(ivec2(p0.x, p1.y), phaseOffset, period, bayerIndex); - float v11 = fetchShortSamePhase(p1, phaseOffset, period, bayerIndex); - return mix(mix(v00, v10, f.x), mix(v01, v11, f.x), f.y); - } - - float shortSensorNorm(ivec2 p) { + bool highlightAtRisk(ivec2 p) { p = clampRaw(p); - int bayerIndex = bayerIndexAt(uCfaPattern, p); - int period = cfaPeriod(uCfaPattern); - return sampleShortSamePhase( - shortAlignedRawPos(p), - cfaPhaseOffset(uCfaPattern, p), - period, - bayerIndex - ); + float signal = sensorNorm(p); + return signal >= 0.90; } - float shortReferenceNorm(ivec2 p) { - return clamp(shortSensorNorm(p) * uShortToReferenceExposureScale, 0.0, 1.0); + vec4 readAccumulator(ivec2 p) { + vec2 valueWeight = unpackHalf2x16(texelFetch(uAccumulatorValueWeight, p, 0).r); + vec2 statistics = unpackHalf2x16(texelFetch(uAccumulatorStatistics, p, 0).r); + return vec4(valueWeight, statistics); } - float referenceBlockMax(ivec2 base) { - float m = 0.0; - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - m = max(m, sensorNorm(uReferenceRaw, base + ivec2(x, y))); - } - } - return m; - } - - float shortReferenceBlockMax(ivec2 base) { - float m = 0.0; - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - m = max(m, shortReferenceNorm(base + ivec2(x, y))); - } - } - return m; - } - - float shortReferenceBlockMean(ivec2 base) { - float sum = 0.0; - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - sum += shortReferenceNorm(base + ivec2(x, y)); - } - } - return sum * 0.25; - } - - float blockClipRatioMax(ivec2 base) { - float m = 0.0; - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - ivec2 p = clampRaw(base + ivec2(x, y)); - vec4 a = texelFetch(uAccumulator, p, 0); - m = max(m, a.a / max(a.a + a.g, 1e-5)); - } - } - return m; - } - - float shortReferenceConsistency(ivec2 base) { - float residualSum = 0.0; - float count = 0.0; - for (int y = -1; y <= 2; ++y) { - for (int x = -1; x <= 2; ++x) { - ivec2 p = base + ivec2(x, y); - float reference = sensorNorm(uReferenceRaw, p); - if (reference <= 0.035 || reference >= 0.860) { - continue; - } - float shortReference = shortReferenceNorm(p); - float residual = abs(shortReference - reference) / max(max(shortReference, reference), 0.08); - residualSum += residual; - count += 1.0; - } - } - float support = smoothstep(2.0, 8.0, count); - float averageResidual = residualSum / max(count, 1.0); - float consistency = 1.0 - smoothstep(0.26, 0.58, averageResidual); - return mix(1.0, consistency, support); + bool phaseAffected(ivec2 p) { + p = clampRaw(p); + vec4 accumulator = readAccumulator(p); + return highlightAtRisk(p) || accumulator.a > 0.0001; } void main() { ivec2 block = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uPlaneSize - ivec2(1)); ivec2 base = block * 2; - float refMax = referenceBlockMax(base); - float clipRatio = blockClipRatioMax(base); - float shortMax = shortReferenceBlockMax(base); - float shortMean = shortReferenceBlockMean(base); - float consistency = shortReferenceConsistency(base); - - float saturatedCore = smoothstep(0.970, 0.995, refMax); - float accumulatedClip = smoothstep(0.35, 0.65, clipRatio) * smoothstep(0.880, 0.960, refMax); - float sourceMask = max(saturatedCore, accumulatedClip); - - float shortPeakConfidence = smoothstep(0.46, 0.78, shortMax); - float shortMeanConfidence = smoothstep(0.16, 0.42, shortMean); - float shortSignalConfidence = shortPeakConfidence * (0.45 + 0.55 * shortMeanConfidence); - float recoveryConfidence = clamp(shortSignalConfidence * consistency, 0.0, 1.0); - - sourceMask = clamp(sourceMask * recoveryConfidence, 0.0, 1.0); - float saturationPush = smoothstep(0.990, 0.999, refMax) * recoveryConfidence; - fragColor = vec4(sourceMask, saturationPush, 0.0, 1.0); - } - """.trimIndent() - - private val HDR_RECOVERY_DILATE_FRAGMENT_SHADER = """ - #version 300 es - precision highp float; - precision highp int; - uniform sampler2D uMask; - uniform ivec2 uPlaneSize; - out float fragColor; - - float maskAt(ivec2 p) { - p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); - return texelFetch(uMask, p, 0).r; - } - - void main() { - ivec2 p = ivec2(gl_FragCoord.xy); - float m = 0.0; - for (int y = -1; y <= 1; ++y) { - for (int x = -1; x <= 1; ++x) { - m = max(m, maskAt(p + ivec2(x, y))); + int riskCount = 0; + for (int y = 0; y <= 1; ++y) { + for (int x = 0; x <= 1; ++x) { + if (phaseAffected(base + ivec2(x, y))) riskCount += 1; } } - fragColor = clamp(m, 0.0, 1.0); + bool sourceMask = riskCount > 0; + bool fullySaturated = riskCount == 4; + bool partiallySaturated = sourceMask && !fullySaturated; + fragColor = vec4( + sourceMask ? 1.0 : 0.0, + partiallySaturated ? 1.0 : 0.0, + fullySaturated ? 1.0 : 0.0, + 1.0 + ); } """.trimIndent() - private val HDR_RECOVERY_FEATHER_FRAGMENT_SHADER = """ + private val RCD_STRIPE_POPULATE_COMPUTE_SHADER = """ + #version 310 es + $RAW_COMMON + layout(local_size_x = 16, local_size_y = 16) in; + uniform highp usampler2D uRawStripe; + uniform sampler2D uLensShadingMap; + uniform ivec2 uStripeSize; + uniform ivec2 uFullImageSize; + uniform int uGlobalRowOffset; + uniform int uCfaPattern; + uniform vec4 uBlackLevel; + uniform float uWhiteLevel; + layout(std430, binding = 0) buffer CFA_Buf { float cfa[]; }; + layout(std430, binding = 1) buffer RGB0_Buf { float rgb0[]; }; + layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; + layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; + + void main() { + ivec2 local = ivec2(gl_GlobalInvocationID.xy); + if (local.x >= uStripeSize.x || local.y >= uStripeSize.y) return; + ivec2 global = ivec2(local.x, local.y + uGlobalRowOffset); + int channel = bayerIndexAt(uCfaPattern, global); + float raw = float(texelFetch(uRawStripe, local, 0).r); + float range = max(uWhiteLevel - uBlackLevel[channel], 1.0); + vec2 uv = (vec2(global) + vec2(0.5)) / vec2(uFullImageSize); + vec4 gains = texture(uLensShadingMap, clamp(uv, vec2(0.0), vec2(1.0))); + int lscChannel = lensShadingChannelAt(uCfaPattern, global); + float value = clamp(max(raw - uBlackLevel[channel], 0.0) * gains[lscChannel] / range, 0.0, 1.0); + int index = local.y * uStripeSize.x + local.x; + cfa[index] = value; + rgb0[index] = channel == 0 ? value : 0.0; + rgb1[index] = (channel == 1 || channel == 2) ? value : 0.0; + rgb2[index] = channel == 3 ? value : 0.0; + } + """.trimIndent() + + private val HDR_RECOVERY_COVERAGE_FRAGMENT_SHADER = """ #version 300 es precision highp float; precision highp int; - uniform sampler2D uMask; + uniform sampler2D uInitialMask; uniform ivec2 uPlaneSize; - out float fragColor; + uniform int uBlockRadius; + out vec4 fragColor; - float maskAt(ivec2 p) { + vec3 maskAt(ivec2 p) { p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); - return texelFetch(uMask, p, 0).r; + return clamp(texelFetch(uInitialMask, p, 0).rgb, vec3(0.0), vec3(1.0)); } void main() { - ivec2 p = ivec2(gl_FragCoord.xy); - float center = maskAt(p); - float sum = center * 4.0; - sum += (maskAt(p + ivec2(1, 0)) + maskAt(p + ivec2(-1, 0)) + - maskAt(p + ivec2(0, 1)) + maskAt(p + ivec2(0, -1))) * 2.0; - sum += maskAt(p + ivec2(1, 1)) + maskAt(p + ivec2(-1, 1)) + - maskAt(p + ivec2(1, -1)) + maskAt(p + ivec2(-1, -1)); - float feather = sum / 16.0; - fragColor = clamp(feather, 0.0, 1.0); + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uPlaneSize - ivec2(1)); + vec3 center = maskAt(p); + if (center.r > 0.5) { + fragColor = vec4(center, 1.0); + return; + } + bool filterSupportAffected = false; + for (int y = -4; y <= 4; ++y) { + for (int x = -4; x <= 4; ++x) { + if (abs(x) <= uBlockRadius && abs(y) <= uBlockRadius && + maskAt(p + ivec2(x, y)).r > 0.5) { + filterSupportAffected = true; + } + } + } + fragColor = filterSupportAffected ? + vec4(1.0, 1.0, 0.0, 1.0) : + vec4(0.0, 0.0, 0.0, 1.0); } """.trimIndent() @@ -6266,7 +7474,7 @@ class GlesRawStacker( } vec2 flowAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; } @@ -6297,7 +7505,7 @@ class GlesRawStacker( } float tileMaskAt(vec2 planePos) { - vec2 grid = planePos / float(uTileSize); + vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uTileMask, clamp(uv, vec2(0.0), vec2(1.0))).r; } @@ -6423,8 +7631,8 @@ class GlesRawStacker( #version 310 es $RAW_COMMON layout(local_size_x = 16, local_size_y = 16) in; - uniform sampler2D uAccumulator; - uniform sampler2D uPostfilterAccumulator; + uniform highp usampler2D uAccumulatorValueWeight; + uniform highp usampler2D uAccumulatorStatistics; uniform sampler2D uLensShadingMap; uniform ivec2 uImageSize; uniform ivec2 uAccumulatorSize; @@ -6541,6 +7749,12 @@ class GlesRawStacker( return clamp(ivec2(round(mapped)), ivec2(0), uAccumulatorSize - ivec2(1)); } + vec4 readAccumulator(ivec2 p) { + vec2 valueWeight = unpackHalf2x16(texelFetch(uAccumulatorValueWeight, p, 0).r); + vec2 statistics = unpackHalf2x16(texelFetch(uAccumulatorStatistics, p, 0).r); + return vec4(valueWeight, statistics); + } + float lscNoiseGain(ivec2 samplePos) { return clamp(lscGain(samplePos), 1e-3, max(uLscNoiseGainMax, 1.0)); } @@ -6559,7 +7773,7 @@ class GlesRawStacker( float postFusedAt(ivec2 p, float fallback) { p = clamp(p, ivec2(0), uImageSize - ivec2(1)); - vec4 a = texelFetch(uPostfilterAccumulator, p, 0); + vec4 a = readAccumulator(p); if (a.g <= 1e-5) return fallback; return clamp(a.r / max(a.g, 1e-5), 0.0, 1.0); } @@ -6641,7 +7855,7 @@ class GlesRawStacker( ivec2 raw = min(sampleIndex * uSampleStep, uImageSize - ivec2(1)); ivec2 mappedAccumulatorCoord = accumulatorCoord(raw); - vec4 accumulator = texelFetch(uAccumulator, mappedAccumulatorCoord, 0); + vec4 accumulator = readAccumulator(mappedAccumulatorCoord); float weight = max(accumulator.g, 0.0); atomicAdd(stats[WEIGHT_COUNT_INDEX], 1u); atomicAdd(stats[WEIGHT_SUM_INDEX], quant(weight, WEIGHT_Q)); @@ -6654,10 +7868,10 @@ class GlesRawStacker( mappedAccumulatorCoord.y & 1 ); cellOrigin = clamp(cellOrigin, ivec2(0), max(uAccumulatorSize - ivec2(2), ivec2(0))); - float srSupport = max(texelFetch(uAccumulator, cellOrigin, 0).a, 0.0); - srSupport = min(srSupport, max(texelFetch(uAccumulator, cellOrigin + ivec2(1, 0), 0).a, 0.0)); - srSupport = min(srSupport, max(texelFetch(uAccumulator, cellOrigin + ivec2(0, 1), 0).a, 0.0)); - srSupport = min(srSupport, max(texelFetch(uAccumulator, cellOrigin + ivec2(1, 1), 0).a, 0.0)); + float srSupport = max(readAccumulator(cellOrigin).a, 0.0); + srSupport = min(srSupport, max(readAccumulator(cellOrigin + ivec2(1, 0)).a, 0.0)); + srSupport = min(srSupport, max(readAccumulator(cellOrigin + ivec2(0, 1)).a, 0.0)); + srSupport = min(srSupport, max(readAccumulator(cellOrigin + ivec2(1, 1)).a, 0.0)); atomicAdd(stats[SR_SUPPORT_COUNT_INDEX], 1u); atomicAdd(stats[SR_SUPPORT_SUM_INDEX], quant(srSupport, WEIGHT_Q)); atomicMax(stats[SR_SUPPORT_MAX_INDEX], quant(srSupport, WEIGHT_Q)); @@ -6676,7 +7890,7 @@ class GlesRawStacker( atomicAdd(stats[LSC_EDGE_SUM_INDEX], quant(gain, LSC_Q)); } - vec4 post = texelFetch(uPostfilterAccumulator, raw, 0); + vec4 post = readAccumulator(raw); if (post.g <= 1e-5) return; float fused = clamp(post.r / max(post.g, 1e-5), 0.0, 1.0); @@ -6771,12 +7985,12 @@ class GlesRawStacker( $RAW_COMMON in vec2 vTexCoord; out vec4 fragColor; - uniform sampler2D uAccumulator; + uniform highp usampler2D uAccumulatorValueWeight; + uniform highp usampler2D uAccumulatorStatistics; uniform highp usampler2D uReferenceRaw; uniform highp usampler2D uShortRaw; uniform sampler2D uLensShadingMap; uniform sampler2D uShortGlobalAlignment; - uniform sampler2D uHdrRecoveryMask; uniform sampler2D uHdrRecoveryOrigMask; uniform ivec2 uImageSize; uniform ivec2 uPlaneSize; @@ -6814,8 +8028,6 @@ class GlesRawStacker( uniform float uResidualNoiseHighScale; uniform float uResidualSmoothBoost; uniform float uMaxSmoothStrength; - uniform float uHdrRecoverySmoothSuppression; - float lscGain(ivec2 samplePos) { vec2 uv = (vec2(samplePos) + vec2(0.5)) / vec2(uImageSize); vec4 gains = texture(uLensShadingMap, uv); @@ -6846,7 +8058,7 @@ class GlesRawStacker( p = clamp(p, ivec2(0), uImageSize - ivec2(1)); float raw = float(texelFetch(uReferenceRaw, p, 0).r); float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); - return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(p) / range, 0.0, 1.0); + return max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(p) / range; } float referenceOutputNorm(ivec2 p, int bayerIndex) { @@ -6861,77 +8073,102 @@ class GlesRawStacker( return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) / range, 0.0, 1.0); } - vec2 shortAlignedRawPos(ivec2 p) { - vec2 rawOffset = texelFetch(uShortGlobalAlignment, ivec2(0), 0).rg * 2.0; - vec2 rawPos = vec2(float(p.x), float(p.y)) + rawOffset; - vec2 maxRawPos = vec2(float(uImageSize.x - 1), float(uImageSize.y - 1)); - return clamp(rawPos, vec2(0.0), maxRawPos); + bool referenceHighlightAtRisk(ivec2 p) { + p = clamp(p, ivec2(0), uImageSize - ivec2(1)); + float signal = referenceSensorNorm(p); + return signal >= 0.90; } - ivec2 cfaPhaseOffset(int cfaPattern, ivec2 p) { - int period = cfaPeriod(cfaPattern); - return ivec2(p.x % period, p.y % period); - } - - ivec2 maxLatticeForPhase(ivec2 phaseOffset, int period) { - return max((uImageSize - ivec2(1) - phaseOffset) / ivec2(period), ivec2(0)); - } - - float shortRawNormAt(ivec2 samplePos, int bayerIndex) { - samplePos = clamp(samplePos, ivec2(0), uImageSize - ivec2(1)); - float raw = float(texelFetch(uShortRaw, samplePos, 0).r); - float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); - return clamp(max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(samplePos) / range, 0.0, 1.0); - } - - float fetchShortSamePhase(ivec2 lattice, ivec2 phaseOffset, int period, int bayerIndex) { - lattice = clamp(lattice, ivec2(0), maxLatticeForPhase(phaseOffset, period)); - return shortRawNormAt(phaseOffset + lattice * period, bayerIndex); - } - - float sampleShortSamePhase(vec2 rawPos, ivec2 phaseOffset, int period, int bayerIndex) { - ivec2 maxLattice = maxLatticeForPhase(phaseOffset, period); - vec2 phase = vec2(float(phaseOffset.x), float(phaseOffset.y)); - vec2 pos = clamp( - (rawPos - phase) / float(period), - vec2(0.0), - vec2(float(maxLattice.x), float(maxLattice.y)) - ); - ivec2 p0 = ivec2(floor(pos)); - ivec2 p1 = min(p0 + ivec2(1), maxLattice); - vec2 f = pos - vec2(p0); - float v00 = fetchShortSamePhase(p0, phaseOffset, period, bayerIndex); - float v10 = fetchShortSamePhase(ivec2(p1.x, p0.y), phaseOffset, period, bayerIndex); - float v01 = fetchShortSamePhase(ivec2(p0.x, p1.y), phaseOffset, period, bayerIndex); - float v11 = fetchShortSamePhase(p1, phaseOffset, period, bayerIndex); - return mix(mix(v00, v10, f.x), mix(v01, v11, f.x), f.y); + ivec2 shortAlignedPos(ivec2 p) { + ivec2 rawOffset = ivec2(round(texelFetch(uShortGlobalAlignment, ivec2(0), 0).rg)) * 2; + return clamp(p + rawOffset, ivec2(0), uImageSize - ivec2(1)); } float shortRecoveryNorm(ivec2 p, int bayerIndex) { - p = clamp(p, ivec2(0), uImageSize - ivec2(1)); - int period = cfaPeriod(uCfaPattern); - float norm = sampleShortSamePhase( - shortAlignedRawPos(p), - cfaPhaseOffset(uCfaPattern, p), - period, - bayerIndex - ); + p = shortAlignedPos(p); + float raw = float(texelFetch(uShortRaw, p, 0).r); + float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0); + float norm = max(raw - uBlackLevel[bayerIndex], 0.0) * lscGain(p) / range; return clamp(norm * uShortExposureScale, 0.0, 1.0); } - float hdrRecoveryMaskAt(ivec2 p) { - ivec2 block = clamp(p / 2, ivec2(0), uPlaneSize - ivec2(1)); - return clamp(texelFetch(uHdrRecoveryMask, block, 0).r, 0.0, 1.0); - } - - vec2 hdrRecoveryOrigMaskAt(ivec2 p) { - ivec2 block = clamp(p / 2, ivec2(0), uPlaneSize - ivec2(1)); - return clamp(texelFetch(uHdrRecoveryOrigMask, block, 0).rg, vec2(0.0), vec2(1.0)); - } - vec4 readAccum(ivec2 p) { p = clamp(p, ivec2(0), uImageSize - ivec2(1)); - return texelFetch(uAccumulator, p, 0); + vec2 valueWeight = unpackHalf2x16(texelFetch(uAccumulatorValueWeight, p, 0).r); + vec2 statistics = unpackHalf2x16(texelFetch(uAccumulatorStatistics, p, 0).r); + return vec4(valueWeight, statistics); + } + + vec3 hdrRecoveryOrigMaskAt(ivec2 p) { + ivec2 block = clamp(p / 2, ivec2(0), uPlaneSize - ivec2(1)); + return clamp(texelFetch(uHdrRecoveryOrigMask, block, 0).rgb, vec3(0.0), vec3(1.0)); + } + + float partialHighlightShortScale(ivec2 p) { + ivec2 base = p - ivec2(p.x & 1, p.y & 1); + float ratios[4]; + int count = 0; + for (int y = 0; y <= 1; ++y) { + for (int x = 0; x <= 1; ++x) { + ivec2 q = clamp(base + ivec2(x, y), ivec2(0), uImageSize - ivec2(1)); + int qBayerIndex = bayerIndexAt(uCfaPattern, q); + vec4 qAccumulator = readAccum(q); + float qShort = shortRecoveryNorm(q, qBayerIndex); + if (!referenceHighlightAtRisk(q) && qAccumulator.a <= 0.0001 && + qAccumulator.g > 0.02 && qShort > 0.005) { + float qNormal = clamp(qAccumulator.r / qAccumulator.g, 0.0, 1.0); + ratios[count] = clamp(qNormal / qShort, 0.5, 2.0); + count += 1; + } + } + } + if (count == 0) return 1.0; + for (int i = 0; i < 4; ++i) { + for (int j = i + 1; j < 4; ++j) { + if (i < count && j < count && ratios[j] < ratios[i]) { + float temporary = ratios[i]; + ratios[i] = ratios[j]; + ratios[j] = temporary; + } + } + } + if (count == 1) return ratios[0]; + if (count == 2) return 0.5 * (ratios[0] + ratios[1]); + if (count == 3) return ratios[1]; + return 0.5 * (ratios[1] + ratios[2]); + } + + float normalReferenceChromaScale(ivec2 p) { + ivec2 base = p - ivec2(p.x & 1, p.y & 1); + float ratios[4]; + int count = 0; + for (int y = 0; y <= 1; ++y) { + for (int x = 0; x <= 1; ++x) { + ivec2 q = clamp(base + ivec2(x, y), ivec2(0), uImageSize - ivec2(1)); + int qBayerIndex = bayerIndexAt(uCfaPattern, q); + vec4 qAccumulator = readAccum(q); + float qReference = referenceOutputNorm(q, qBayerIndex); + if (qAccumulator.g > 0.02 && qReference > 0.005) { + float qNormal = clamp(qAccumulator.r / qAccumulator.g, 0.0, 1.0); + ratios[count] = clamp(qNormal / qReference, 0.5, 2.0); + count += 1; + } + } + } + if (count == 0) return 1.0; + for (int i = 0; i < 4; ++i) { + for (int j = i + 1; j < 4; ++j) { + if (i < count && j < count && ratios[j] < ratios[i]) { + float temporary = ratios[i]; + ratios[i] = ratios[j]; + ratios[j] = temporary; + } + } + } + if (count == 1) return ratios[0]; + if (count == 2) return 0.5 * (ratios[0] + ratios[1]); + if (count == 3) return ratios[1]; + return 0.5 * (ratios[1] + ratios[2]); } float meanAt(ivec2 p) { @@ -6941,6 +8178,13 @@ class GlesRawStacker( return clamp(a.r / max(a.g, 1e-5), 0.0, 1.0); } + void writePackedRaw(float value) { + uint raw = uint(floor(clamp(value, 0.0, 1.0) * 65535.0 + 0.5)); + uint lo = raw & 255u; + uint hi = (raw >> 8) & 255u; + fragColor = vec4(float(lo) / 255.0, float(hi) / 255.0, 0.0, 1.0); + } + float lowLightAmount(float signal) { return 1.0 - smoothstep( min(uLowLightSignalLow, uLowLightSignalHigh), @@ -6999,8 +8243,6 @@ class GlesRawStacker( detailDeviation ); float base = uFinalSmoothStrength * flatness * (1.0 - uDetailKeepSuppression * detailKeep); - if (uHdrMode != 0) return base; - float lowLight = lowLightAmount(signal); float lsc = lscSmoothAmount(lscGainForNoise); float lowWeight = lowWeightAmount(accumulatorWeight); @@ -7020,28 +8262,20 @@ class GlesRawStacker( vec4 a = readAccum(p); float reference = referenceOutputNorm(p, bayerIndex); float fused = a.g > 1e-5 ? clamp(a.r / max(a.g, 1e-5), 0.0, 1.0) : reference; - float recoveryMix = 0.0; if (uHdrMode != 0) { - float normalConfidence = smoothstep(0.04, 0.35, a.g); - recoveryMix = hdrRecoveryMaskAt(p); - vec2 origRecovery = hdrRecoveryOrigMaskAt(p); - if (origRecovery.r > 0.5) { - recoveryMix += (1.0 - recoveryMix) * origRecovery.g; - } - recoveryMix = clamp(recoveryMix, 0.0, 1.0); - fused = mix(reference, fused, normalConfidence); - if (recoveryMix > 0.0001) { - float shortValue = shortRecoveryNorm(p, bayerIndex); - float shortPresenceFloor = max(0.012, reference * 0.25); - float shortPresenceWidth = max(0.035, reference * 0.45); - float shortPresence = smoothstep( - shortPresenceFloor, - shortPresenceFloor + shortPresenceWidth, - shortValue - ); - recoveryMix *= shortPresence; - fused = mix(fused, shortValue, recoveryMix); + vec3 recoveryClass = hdrRecoveryOrigMaskAt(p); + if (recoveryClass.r > 0.5) { + float recovered = shortRecoveryNorm(p, bayerIndex); + if (recoveryClass.b < 0.5) { + recovered *= partialHighlightShortScale(p); + } + writePackedRaw(recovered); + return; } + float normalChroma = referenceOutputNorm(p, bayerIndex) * + normalReferenceChromaScale(p); + writePackedRaw(normalChroma); + return; } float mean = 0.0; @@ -7098,16 +8332,10 @@ class GlesRawStacker( a.g, residualAmount ); - if (uHdrMode != 0) { - smoothAmount *= 1.0 - uHdrRecoverySmoothSuppression * recoveryMix; - } fused = mix(fused, mean + wienerGain * (fused - mean), smoothAmount); fused = clamp(fused, 0.0, 1.0); - uint raw = uint(floor(fused * 65535.0 + 0.5)); - uint lo = raw & 255u; - uint hi = (raw >> 8) & 255u; - fragColor = vec4(float(lo) / 255.0, float(hi) / 255.0, 0.0, 1.0); + writePackedRaw(fused); } """.trimIndent() } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt index cec2102b..a572d15d 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt @@ -30,12 +30,6 @@ data class RawHdrStackFrame( val exposureProduct: Double, ) -data class RawStackFrame( - val image: SafeImage, - val exposureProduct: Double = 1.0, - val focusDistanceDiopters: Float = Float.NaN, -) - enum class YuvHdrStackFrameRole { ZERO_EV, HIGH_EV, @@ -291,7 +285,7 @@ object MultiFrameStacker { @Synchronized fun processBurstRaw( - images: List, + frames: List, cfaPattern: Int, enableSuperResolution: Boolean = false, superResolutionScale: Float = 1.5f, @@ -305,9 +299,9 @@ object MultiFrameStacker { lensShadingWidth: Int = 0, lensShadingHeight: Int = 0, applyLensShadingCorrection: Boolean = true, - frameExposureProducts: List = emptyList(), - frameFocusDistances: List = emptyList(), ): RawStackResult? { + if (frames.isEmpty()) return null + val images = frames.map { it.image } val width = images[0].width val height = images[0].height @@ -333,22 +327,6 @@ object MultiFrameStacker { frameCount = images.size, superResolutionScale = outputScale, ) - val fallbackExposureProduct = frameExposureProducts - .firstOrNull { it != null && it.isFinite() && it > 0.0 } - ?: 1.0 - val frames = images.mapIndexed { index, image -> - RawStackFrame( - image = image, - exposureProduct = frameExposureProducts - .getOrNull(index) - ?.takeIf { it.isFinite() && it > 0.0 } - ?: fallbackExposureProduct, - focusDistanceDiopters = frameFocusDistances - .getOrNull(index) - ?.takeIf { it.isFinite() } - ?: Float.NaN, - ) - } return GlesRawStacker( width = width, height = height, diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawAlignmentProxy.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawAlignmentProxy.kt new file mode 100644 index 00000000..79c30a51 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawAlignmentProxy.kt @@ -0,0 +1,155 @@ +package com.hinnka.mycamera.processor + +import android.graphics.ImageFormat +import com.hinnka.mycamera.model.SafeImage +import java.nio.ByteOrder +import kotlin.math.abs +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min + +data class RawAlignmentProxyConfig( + val cfaArrangement: Int, + val blackLevelByPosition: FloatArray, + val whiteLevel: Float, + val maxLongEdge: Int = 128, +) + +data class RawAlignmentProxy( + val width: Int, + val height: Int, + val lowPass: FloatArray, + val bandPass: FloatArray, + val sharpness: Float, + val sourcePlaneWidth: Int = width, + val sourcePlaneHeight: Int = height, +) + +object RawAlignmentProxyBuilder { + fun build(image: SafeImage, config: RawAlignmentProxyConfig): RawAlignmentProxy? { + if (image.format != ImageFormat.RAW_SENSOR || image.width < 4 || image.height < 4) return null + val plane = image.planes.firstOrNull() ?: return null + if (plane.pixelStride < 2 || plane.rowStride <= 0) return null + val sourceCellWidth = image.width / 2 + val sourceCellHeight = image.height / 2 + if (sourceCellWidth < 2 || sourceCellHeight < 2) return null + val scale = max( + 1.0, + max(sourceCellWidth, sourceCellHeight).toDouble() / config.maxLongEdge.coerceAtLeast(32), + ) + val width = max(2, (sourceCellWidth / scale).toInt()) + val height = max(2, (sourceCellHeight / scale).toInt()) + val buffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()) + val positionBlack = FloatArray(4) { index -> + config.blackLevelByPosition.getOrElse(index) { + config.blackLevelByPosition.firstOrNull() ?: 0f + } + } + val greenOffsets = greenOffsets(config.cfaArrangement) + val linear = FloatArray(width * height) + for (y in 0 until height) { + val sourceCellY = min(sourceCellHeight - 1, ((y + 0.5) * sourceCellHeight / height).toInt()) + val rawY = sourceCellY * 2 + for (x in 0 until width) { + val sourceCellX = min(sourceCellWidth - 1, ((x + 0.5) * sourceCellWidth / width).toInt()) + val rawX = sourceCellX * 2 + var sum = 0f + for (offset in greenOffsets) { + val px = rawX + offset.first + val py = rawY + offset.second + val positionIndex = offset.second * 2 + offset.first + val byteOffset = py * plane.rowStride + px * plane.pixelStride + if (byteOffset < 0 || byteOffset + 1 >= buffer.limit()) continue + val raw = buffer.getShort(byteOffset).toInt() and 0xffff + val black = positionBlack[positionIndex] + val range = max(config.whiteLevel - black, 1f) + sum += ((raw - black) / range).coerceIn(0f, 1f) + } + val value = sum * 0.5f + linear[y * width + x] = (ln(1.0 + LOG_COMPRESSION * value) / LOG_COMPRESSION_DENOMINATOR).toFloat() + } + } + + val lowPass = gaussian5(linear, width, height) + val wide = gaussian5(gaussian5(lowPass, width, height), width, height) + val bandPass = FloatArray(linear.size) { lowPass[it] - wide[it] } + normalizeZeroMeanUnitVariance(lowPass) + normalizeZeroMeanUnitVariance(bandPass) + val sharpness = laplacianSharpness(lowPass, width, height) + return RawAlignmentProxy( + width = width, + height = height, + lowPass = lowPass, + bandPass = bandPass, + sharpness = sharpness, + sourcePlaneWidth = sourceCellWidth, + sourcePlaneHeight = sourceCellHeight, + ) + } + + private fun greenOffsets(cfaArrangement: Int): Array> { + return when (cfaArrangement) { + 1, 2 -> arrayOf(0 to 0, 1 to 1) // GRBG / GBRG + else -> arrayOf(1 to 0, 0 to 1) // RGGB / BGGR and safe fallback + } + } + + private fun gaussian5(input: FloatArray, width: Int, height: Int): FloatArray { + val temporary = FloatArray(input.size) + val output = FloatArray(input.size) + for (y in 0 until height) { + for (x in 0 until width) { + var sum = 0f + for (k in -2..2) { + val sx = (x + k).coerceIn(0, width - 1) + sum += input[y * width + sx] * GAUSSIAN_5[k + 2] + } + temporary[y * width + x] = sum * GAUSSIAN_5_NORMALIZER + } + } + for (y in 0 until height) { + for (x in 0 until width) { + var sum = 0f + for (k in -2..2) { + val sy = (y + k).coerceIn(0, height - 1) + sum += temporary[sy * width + x] * GAUSSIAN_5[k + 2] + } + output[y * width + x] = sum * GAUSSIAN_5_NORMALIZER + } + } + return output + } + + private fun normalizeZeroMeanUnitVariance(values: FloatArray) { + if (values.isEmpty()) return + val mean = values.sum().toDouble() / values.size + var variance = 0.0 + values.forEach { value -> + val delta = value - mean + variance += delta * delta + } + val scale = 1.0 / kotlin.math.sqrt(max(variance / values.size, 1.0e-8)) + for (index in values.indices) values[index] = ((values[index] - mean) * scale).toFloat() + } + + private fun laplacianSharpness(values: FloatArray, width: Int, height: Int): Float { + if (width < 3 || height < 3) return 0f + var sum = 0.0 + var count = 0 + for (y in 1 until height - 1) { + for (x in 1 until width - 1) { + val center = values[y * width + x] + val laplacian = values[y * width + x - 1] + values[y * width + x + 1] + + values[(y - 1) * width + x] + values[(y + 1) * width + x] - 4f * center + sum += abs(laplacian) + count++ + } + } + return if (count > 0) (sum / count).toFloat() else 0f + } + + private val GAUSSIAN_5 = floatArrayOf(1f, 4f, 6f, 4f, 1f) + private const val GAUSSIAN_5_NORMALIZER = 1f / 16f + private const val LOG_COMPRESSION = 8.0 + private val LOG_COMPRESSION_DENOMINATOR = ln(1.0 + LOG_COMPRESSION) +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawBurstFrame.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstFrame.kt new file mode 100644 index 00000000..c70c3e10 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstFrame.kt @@ -0,0 +1,65 @@ +package com.hinnka.mycamera.processor + +import com.hinnka.mycamera.camera.GyroExposureWindow +import com.hinnka.mycamera.model.SafeImage + +enum class RawBurstFrameRole { + NORMAL, + HDR_SHORT, + HDR_LONG, +} + +/** + * Global reference-to-frame transform used only as the starting point for local optical flow. + * Translation is expressed in the half-resolution Bayer plane used by [GlesRawStacker]. + */ +data class RawFramePreAlignment( + val translationXPlanePx: Float, + val translationYPlanePx: Float, + val rotationDegrees: Float, + val confidence: Float, +) { + val isUsable: Boolean + get() = translationXPlanePx.isFinite() && translationYPlanePx.isFinite() && + rotationDegrees.isFinite() && confidence.isFinite() && confidence >= MIN_USABLE_CONFIDENCE + + fun flowAtPlanePosition( + xPlanePx: Float, + yPlanePx: Float, + planeWidth: Int, + planeHeight: Int, + ): Pair { + if (!isUsable) return 0f to 0f + val centerX = (planeWidth - 1) * 0.5f + val centerY = (planeHeight - 1) * 0.5f + val centeredX = xPlanePx - centerX + val centeredY = yPlanePx - centerY + val radians = Math.toRadians(rotationDegrees.toDouble()) + val cosTheta = kotlin.math.cos(radians).toFloat() + val sinTheta = kotlin.math.sin(radians).toFloat() + val rotatedX = cosTheta * centeredX - sinTheta * centeredY + val rotatedY = sinTheta * centeredX + cosTheta * centeredY + return (rotatedX - centeredX + translationXPlanePx) to + (rotatedY - centeredY + translationYPlanePx) + } + + companion object { + val Identity = RawFramePreAlignment(0f, 0f, 0f, 1f) + const val MIN_USABLE_CONFIDENCE = 0.08f + } +} + +data class RawStackFrame( + val image: SafeImage, + val sensorTimestampNs: Long = image.timestamp, + val frameNumber: Long = -1L, + val exposureTimeNs: Long = 0L, + val sensitivityIso: Int = 0, + val exposureProduct: Double = 1.0, + val focusDistanceDiopters: Float = Float.NaN, + val lensState: Int? = null, + val rollingShutterSkewNs: Long? = null, + val gyroWindow: GyroExposureWindow? = null, + val role: RawBurstFrameRole = RawBurstFrameRole.NORMAL, + val preAlignmentToReference: RawFramePreAlignment? = null, +) diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawBurstGyroSelector.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstGyroSelector.kt new file mode 100644 index 00000000..6bb4ee1f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstGyroSelector.kt @@ -0,0 +1,130 @@ +package com.hinnka.mycamera.processor + +import com.hinnka.mycamera.camera.GyroExposureWindow +import kotlin.math.ceil +import kotlin.math.max +import kotlin.math.sqrt + +data class RawBurstGyroSelection( + val orderedAcceptedIndices: IntArray, + val rejectedIndices: IntArray, + val blurRiskByIndex: FloatArray, + val referenceOriginalIndex: Int, +) + +data class RawBurstGyroFrameSample( + val sensorTimestampNs: Long, + val exposureTimeNs: Long, + val gyroWindow: GyroExposureWindow?, +) + +object RawBurstGyroSelector { + private const val MIN_GYRO_COVERAGE = 0.80f + private const val MIN_RETAINED_FRAMES = 3 + private const val MAX_REJECTION_FRACTION = 0.25f + private const val ABSOLUTE_OUTLIER_FLOOR_RAD = 0.0015f + + fun select(frames: List): RawBurstGyroSelection { + return selectMetadata( + frames.map { + RawBurstGyroFrameSample( + sensorTimestampNs = it.sensorTimestampNs, + exposureTimeNs = it.exposureTimeNs, + gyroWindow = it.gyroWindow, + ) + } + ) + } + + fun selectMetadata(frames: List): RawBurstGyroSelection { + if (frames.isEmpty()) { + return RawBurstGyroSelection(IntArray(0), IntArray(0), FloatArray(0), -1) + } + + val risks = FloatArray(frames.size) { index -> blurRisk(frames[index]) } + val reliableIndices = frames.indices.filter { risks[it].isFinite() } + if (reliableIndices.size < 2 || frames.size <= MIN_RETAINED_FRAMES) { + val reference = reliableIndices.minByOrNull { risks[it] } ?: 0 + return RawBurstGyroSelection( + orderedAcceptedIndices = orderAccepted(frames, frames.indices.toList(), risks, reference), + rejectedIndices = IntArray(0), + blurRiskByIndex = risks, + referenceOriginalIndex = reference, + ) + } + + val reliableRisks = reliableIndices.map { risks[it] }.sorted() + val median = median(reliableRisks) + val deviations = reliableRisks.map { kotlin.math.abs(it - median) }.sorted() + val mad = median(deviations) + val threshold = max( + ABSOLUTE_OUTLIER_FLOOR_RAD, + max(median * 2.5f, median + 3.0f * 1.4826f * mad), + ) + val maxRejected = minOf( + frames.size - MIN_RETAINED_FRAMES, + ceil(frames.size * MAX_REJECTION_FRACTION).toInt(), + ).coerceAtLeast(0) + val rejected = reliableIndices + .asSequence() + .filter { risks[it] > threshold } + .sortedByDescending { risks[it] } + .take(maxRejected) + .toSet() + val accepted = frames.indices.filterNot(rejected::contains) + val reference = accepted + .asSequence() + .filter { risks[it].isFinite() } + .minByOrNull { risks[it] } + ?: accepted.first() + + return RawBurstGyroSelection( + orderedAcceptedIndices = orderAccepted(frames, accepted, risks, reference), + rejectedIndices = rejected.sorted().toIntArray(), + blurRiskByIndex = risks, + referenceOriginalIndex = reference, + ) + } + + private fun blurRisk(frame: RawBurstGyroFrameSample): Float { + val window = frame.gyroWindow ?: return Float.NaN + if (window.coverageRatio < MIN_GYRO_COVERAGE || window.sampleCount < 2) return Float.NaN + val rotation = window.integratedRotationRad + if (rotation.size < 3) return Float.NaN + val integratedMagnitude = sqrt( + rotation[0] * rotation[0] + rotation[1] * rotation[1] + rotation[2] * rotation[2] + ) + val exposureSeconds = frame.exposureTimeNs.coerceAtLeast(0L) * 1.0e-9f + val energyEquivalent = sqrt(window.angularEnergy.coerceAtLeast(0f)) * exposureSeconds + val peakEquivalent = window.peakAngularVelocity.coerceAtLeast(0f) * exposureSeconds + return integratedMagnitude + 0.20f * energyEquivalent + 0.10f * peakEquivalent + } + + private fun orderAccepted( + frames: List, + accepted: List, + risks: FloatArray, + reference: Int, + ): IntArray { + val remainder = accepted + .asSequence() + .filter { it != reference } + .sortedWith( + compareBy { if (risks[it].isFinite()) 0 else 1 } + .thenBy { if (risks[it].isFinite()) risks[it] else Float.POSITIVE_INFINITY } + .thenBy { frames[it].sensorTimestampNs } + ) + .toList() + return intArrayOf(reference, *remainder.toIntArray()) + } + + private fun median(values: List): Float { + if (values.isEmpty()) return 0f + val middle = values.size / 2 + return if (values.size % 2 == 0) { + (values[middle - 1] + values[middle]) * 0.5f + } else { + values[middle] + } + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawBurstReferencePlanner.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstReferencePlanner.kt new file mode 100644 index 00000000..6c68b1e4 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawBurstReferencePlanner.kt @@ -0,0 +1,249 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.abs +import kotlin.math.hypot +import kotlin.math.max + +data class RawBurstReferencePlan( + val referenceOriginalIndex: Int, + val orderedIndices: IntArray, + val alignmentsToReference: List, + val preAlignmentsToReference: List, + val referenceCost: Float, +) + +object RawBurstReferencePlanner { + fun plan( + frames: List, + proxyConfig: RawAlignmentProxyConfig, + ): RawBurstReferencePlan { + val proxies = frames.map { RawAlignmentProxyBuilder.build(it.image, proxyConfig) } + val gyroRisks = RawBurstGyroSelector.select(frames).blurRiskByIndex + return planProxies(proxies, gyroRisks, frames.map { it.sensorTimestampNs }) + } + + internal fun planProxies( + proxies: List, + gyroRisks: FloatArray = FloatArray(proxies.size) { Float.NaN }, + sensorTimestampsNs: List = proxies.indices.map(Int::toLong), + ): RawBurstReferencePlan { + if (proxies.isEmpty()) { + return RawBurstReferencePlan(-1, IntArray(0), emptyList(), emptyList(), Float.POSITIVE_INFINITY) + } + val valid = proxies.indices.filter { proxies[it] != null } + if (valid.size < 2) return fallback(proxies.size, valid.firstOrNull() ?: 0) + + val candidates = referenceCandidates(proxies, gyroRisks, valid) + var bestReference = candidates.first() + var bestCost = Float.POSITIVE_INFINITY + var bestAlignments: List = List(proxies.size) { null } + val maxSharpness = valid.maxOf { proxies[it]!!.sharpness }.coerceAtLeast(1.0e-6f) + val medianGyro = gyroRisks + .filter(Float::isFinite) + .sorted() + .let { values -> + if (values.isEmpty()) Float.NaN else values[values.size / 2].coerceAtLeast(1.0e-6f) + } + + for (candidate in candidates) { + val reference = proxies[candidate] ?: continue + val alignments = MutableList(proxies.size) { null } + alignments[candidate] = RawGlobalAlignment(0f, 0f, 0f, 0f, 1f, 1f) + var geometryCost = 0f + var failed = 0 + for (index in valid) { + if (index == candidate) continue + val alignment = RawGlobalPreAligner.align(reference, proxies[index]!!) + alignments[index] = alignment + if (alignment == null) { + failed++ + geometryCost += FAILED_ALIGNMENT_COST + continue + } + geometryCost += GEOMETRY_TRANSLATION_WEIGHT * hypot( + alignment.dxProxyPx / reference.width, + alignment.dyProxyPx / reference.height, + ) + geometryCost += GEOMETRY_ROTATION_WEIGHT * abs(alignment.rotationDegrees) + geometryCost += ALIGNMENT_SCORE_WEIGHT * alignment.score + geometryCost += COVERAGE_WEIGHT * (1f - alignment.coverage) + geometryCost += MARGIN_WEIGHT / max(alignment.margin, MIN_MARGIN) + } + val sharpnessPenalty = SHARPNESS_WEIGHT * + (1f - reference.sharpness / maxSharpness).coerceIn(0f, 1f) + val gyroPenalty = if (medianGyro.isFinite() && gyroRisks.getOrNull(candidate)?.isFinite() == true) { + GYRO_WEIGHT * (gyroRisks[candidate] / medianGyro).coerceIn(0f, 4f) + } else { + UNKNOWN_GYRO_PENALTY + } + val cost = geometryCost / max(1, valid.size - 1) + sharpnessPenalty + gyroPenalty + + failed * FAILED_REFERENCE_PENALTY + if (cost < bestCost) { + bestCost = cost + bestReference = candidate + bestAlignments = alignments + } + } + + val remainder = proxies.indices + .asSequence() + .filter { it != bestReference } + .sortedWith( + compareBy { bestAlignments[it] == null } + .thenBy { index -> + bestAlignments[index]?.let { hypot(it.dxProxyPx, it.dyProxyPx) } + ?: Float.POSITIVE_INFINITY + } + .thenBy { it } + ) + .toList() + val directPreAlignments = bestAlignments.mapIndexed { index, alignment -> + val proxy = proxies[index] + if (index == bestReference) { + RawFramePreAlignment.Identity + } else if (alignment != null && proxy != null) { + alignment.toFramePreAlignment(proxy) + } else { + null + } + } + val graphPreAlignments = solveGlobalTemporalGraph( + proxies = proxies, + sensorTimestampsNs = sensorTimestampsNs, + referenceIndex = bestReference, + directAlignments = bestAlignments, + directPreAlignments = directPreAlignments, + ) + return RawBurstReferencePlan( + referenceOriginalIndex = bestReference, + orderedIndices = intArrayOf(bestReference, *remainder.toIntArray()), + alignmentsToReference = bestAlignments, + preAlignmentsToReference = graphPreAlignments ?: directPreAlignments, + referenceCost = bestCost, + ) + } + + private fun referenceCandidates( + proxies: List, + gyroRisks: FloatArray, + valid: List, + ): List { + val candidates = LinkedHashSet() + candidates += valid[valid.size / 2] + valid.sortedByDescending { proxies[it]!!.sharpness }.take(2).forEach(candidates::add) + valid.asSequence() + .filter { gyroRisks.getOrNull(it)?.isFinite() == true } + .sortedBy { gyroRisks[it] } + .take(2) + .forEach(candidates::add) + if (candidates.size < MAX_REFERENCE_CANDIDATES) { + candidates += valid.first() + candidates += valid.last() + } + return candidates.take(MAX_REFERENCE_CANDIDATES) + } + + private fun fallback(frameCount: Int, reference: Int): RawBurstReferencePlan { + val remainder = (0 until frameCount).filter { it != reference } + return RawBurstReferencePlan( + referenceOriginalIndex = reference, + orderedIndices = intArrayOf(reference, *remainder.toIntArray()), + alignmentsToReference = List(frameCount) { null }, + preAlignmentsToReference = List(frameCount) { index -> + if (index == reference) RawFramePreAlignment.Identity else null + }, + referenceCost = Float.POSITIVE_INFINITY, + ) + } + + private fun RawGlobalAlignment.toFramePreAlignment(proxy: RawAlignmentProxy): RawFramePreAlignment { + return RawFramePreAlignment( + translationXPlanePx = dxProxyPx * proxy.sourcePlaneWidth / proxy.width.coerceAtLeast(1), + translationYPlanePx = dyProxyPx * proxy.sourcePlaneHeight / proxy.height.coerceAtLeast(1), + rotationDegrees = rotationDegrees, + confidence = confidence(), + ) + } + + private fun RawGlobalAlignment.confidence(): Float { + val scoreConfidence = (1f - score / MAX_CONFIDENT_SCORE).coerceIn(0f, 1f) + val marginConfidence = (margin / FULL_CONFIDENCE_MARGIN).coerceIn(0f, 1f) + return coverage.coerceIn(0f, 1f) * scoreConfidence * marginConfidence + } + + private fun solveGlobalTemporalGraph( + proxies: List, + sensorTimestampsNs: List, + referenceIndex: Int, + directAlignments: List, + directPreAlignments: List, + ): List? { + if (sensorTimestampsNs.size != proxies.size || proxies.size < 3) return null + val graph = RawTemporalAlignmentGraphBuilder.build( + sensorTimestampsNs = sensorTimestampsNs, + referenceFrameIndex = referenceIndex, + includeSkipOne = proxies.size <= MAX_SKIP_ONE_FRAME_COUNT, + ) + val observations = graph.edges.mapNotNull { edge -> + val fromProxy = proxies[edge.fromFrameIndex] ?: return@mapNotNull null + val toProxy = proxies[edge.toFrameIndex] ?: return@mapNotNull null + val alignment = if ( + edge.type == RawTemporalEdgeType.REFERENCE && edge.fromFrameIndex == referenceIndex + ) { + directAlignments[edge.toFrameIndex] + } else { + RawGlobalPreAligner.align(fromProxy, toProxy) + } ?: return@mapNotNull null + val preAlignment = alignment.toFramePreAlignment(fromProxy) + if (preAlignment.confidence < MIN_GRAPH_EDGE_CONFIDENCE) return@mapNotNull null + RawTemporalEdgeObservation( + edge = edge, + dxPlanePx = preAlignment.translationXPlanePx, + dyPlanePx = preAlignment.translationYPlanePx, + confidence = preAlignment.confidence, + ) + } + val solution = RawTemporalAlignmentSolver.solve(graph, observations) ?: return null + if (solution.acceptedObservationIndices.size < proxies.size - 1) return null + val accepted = solution.acceptedObservationIndices.toSet() + return List(proxies.size) { frameIndex -> + if (frameIndex == referenceIndex) return@List RawFramePreAlignment.Identity + val incidentConfidence = observations.indices.asSequence() + .filter { it in accepted } + .map { observations[it] } + .filter { observation -> + observation.edge.fromFrameIndex == frameIndex || observation.edge.toFrameIndex == frameIndex + } + .map { it.confidence } + .toList() + .average() + .takeIf(Double::isFinite) + ?.toFloat() + ?: return@List directPreAlignments[frameIndex] + val position = solution.positions[frameIndex] + RawFramePreAlignment( + translationXPlanePx = position.xPlanePx, + translationYPlanePx = position.yPlanePx, + rotationDegrees = directPreAlignments[frameIndex]?.rotationDegrees ?: 0f, + confidence = incidentConfidence, + ) + } + } + + private const val MAX_REFERENCE_CANDIDATES = 4 + private const val GEOMETRY_TRANSLATION_WEIGHT = 8f + private const val GEOMETRY_ROTATION_WEIGHT = 0.08f + private const val ALIGNMENT_SCORE_WEIGHT = 0.7f + private const val COVERAGE_WEIGHT = 0.3f + private const val MARGIN_WEIGHT = 0.0005f + private const val MIN_MARGIN = 0.002f + private const val SHARPNESS_WEIGHT = 0.4f + private const val GYRO_WEIGHT = 0.15f + private const val UNKNOWN_GYRO_PENALTY = 0.08f + private const val FAILED_ALIGNMENT_COST = 2f + private const val FAILED_REFERENCE_PENALTY = 0.5f + private const val MAX_CONFIDENT_SCORE = 0.8f + private const val FULL_CONFIDENCE_MARGIN = 0.02f + private const val MIN_GRAPH_EDGE_CONFIDENCE = 0.02f + private const val MAX_SKIP_ONE_FRAME_COUNT = 8 +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawGlobalPreAligner.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawGlobalPreAligner.kt new file mode 100644 index 00000000..bbdeb685 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawGlobalPreAligner.kt @@ -0,0 +1,164 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.abs +import kotlin.math.cos +import kotlin.math.max +import kotlin.math.sin +import kotlin.math.sqrt + +data class RawGlobalAlignment( + val dxProxyPx: Float, + val dyProxyPx: Float, + val rotationDegrees: Float, + val score: Float, + val margin: Float, + val coverage: Float, +) + +object RawGlobalPreAligner { + fun align(reference: RawAlignmentProxy, current: RawAlignmentProxy): RawGlobalAlignment? { + if (reference.width != current.width || reference.height != current.height) return null + if (reference.width < 32 || reference.height < 32) return null + + var best = Candidate.INVALID + var second = Candidate.INVALID + for (rotation in COARSE_ROTATIONS) { + var dy = -COARSE_RADIUS + while (dy <= COARSE_RADIUS) { + var dx = -COARSE_RADIUS + while (dx <= COARSE_RADIUS) { + val candidate = score(reference, current, dx.toFloat(), dy.toFloat(), rotation, COARSE_SAMPLE_STEP) + if (candidate.score < best.score) { + second = best + best = candidate + } else if (candidate.score < second.score) { + second = candidate + } + dx += COARSE_SHIFT_STEP + } + dy += COARSE_SHIFT_STEP + } + } + if (!best.score.isFinite()) return null + + val refinedCandidates = ArrayList() + for (rotationOffset in FINE_ROTATION_OFFSETS) { + for (dyOffset in -FINE_RADIUS..FINE_RADIUS) { + for (dxOffset in -FINE_RADIUS..FINE_RADIUS) { + refinedCandidates += score( + reference, + current, + best.dx + dxOffset, + best.dy + dyOffset, + best.rotationDegrees + rotationOffset, + FINE_SAMPLE_STEP, + ) + } + } + } + val sorted = refinedCandidates.filter { it.score.isFinite() }.sortedBy { it.score } + if (sorted.isEmpty()) return null + best = sorted.first() + second = sorted.firstOrNull { candidate -> + abs(candidate.dx - best.dx) >= 1f || abs(candidate.dy - best.dy) >= 1f || + abs(candidate.rotationDegrees - best.rotationDegrees) >= 0.25f + } ?: second + return RawGlobalAlignment( + dxProxyPx = best.dx, + dyProxyPx = best.dy, + rotationDegrees = best.rotationDegrees, + score = best.score, + margin = (second.score - best.score).coerceAtLeast(0f), + coverage = best.coverage, + ) + } + + private fun score( + reference: RawAlignmentProxy, + current: RawAlignmentProxy, + dx: Float, + dy: Float, + rotationDegrees: Float, + sampleStep: Int, + ): Candidate { + val width = reference.width + val height = reference.height + val radians = Math.toRadians(rotationDegrees.toDouble()) + val cosTheta = cos(radians).toFloat() + val sinTheta = sin(radians).toFloat() + val centerX = (width - 1) * 0.5f + val centerY = (height - 1) * 0.5f + val border = max(4, minOf(width, height) / 12) + var sumReference2 = 0.0 + var sumCurrent2 = 0.0 + var sumCross = 0.0 + var count = 0 + var possible = 0 + var y = border + while (y < height - border) { + var x = border + while (x < width - border) { + possible++ + val centeredX = x - centerX + val centeredY = y - centerY + val sourceX = cosTheta * centeredX - sinTheta * centeredY + centerX + dx + val sourceY = sinTheta * centeredX + cosTheta * centeredY + centerY + dy + if (sourceX >= 1f && sourceY >= 1f && sourceX < width - 2f && sourceY < height - 2f) { + val refLow = reference.lowPass[y * width + x] + val curLow = bilinear(current.lowPass, width, height, sourceX, sourceY) + val refBand = reference.bandPass[y * width + x] + val curBand = bilinear(current.bandPass, width, height, sourceX, sourceY) + val ref = refLow + BAND_WEIGHT * refBand + val cur = curLow + BAND_WEIGHT * curBand + sumReference2 += ref * ref + sumCurrent2 += cur * cur + sumCross += ref * cur + count++ + } + x += sampleStep + } + y += sampleStep + } + if (count < MIN_SAMPLES || possible == 0) return Candidate.INVALID + val denominator = sqrt(max(sumReference2 * sumCurrent2, 1.0e-12)) + val correlation = (sumCross / denominator).coerceIn(-1.0, 1.0) + val coverage = count.toFloat() / possible + val cost = (1.0 - correlation).toFloat() + COVERAGE_PENALTY * (1f - coverage) + return Candidate(dx, dy, rotationDegrees, cost, coverage) + } + + private fun bilinear(values: FloatArray, width: Int, height: Int, x: Float, y: Float): Float { + val x0 = x.toInt().coerceIn(0, width - 1) + val y0 = y.toInt().coerceIn(0, height - 1) + val x1 = (x0 + 1).coerceAtMost(width - 1) + val y1 = (y0 + 1).coerceAtMost(height - 1) + val fx = x - x0 + val fy = y - y0 + val a = values[y0 * width + x0] * (1f - fx) + values[y0 * width + x1] * fx + val b = values[y1 * width + x0] * (1f - fx) + values[y1 * width + x1] * fx + return a * (1f - fy) + b * fy + } + + private data class Candidate( + val dx: Float, + val dy: Float, + val rotationDegrees: Float, + val score: Float, + val coverage: Float, + ) { + companion object { + val INVALID = Candidate(0f, 0f, 0f, Float.POSITIVE_INFINITY, 0f) + } + } + + private val COARSE_ROTATIONS = floatArrayOf(-1.0f, -0.5f, 0f, 0.5f, 1.0f) + private val FINE_ROTATION_OFFSETS = floatArrayOf(-0.25f, 0f, 0.25f) + private const val COARSE_RADIUS = 10 + private const val COARSE_SHIFT_STEP = 2 + private const val FINE_RADIUS = 2 + private const val COARSE_SAMPLE_STEP = 4 + private const val FINE_SAMPLE_STEP = 3 + private const val BAND_WEIGHT = 0.75f + private const val COVERAGE_PENALTY = 0.15f + private const val MIN_SAMPLES = 256 +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt index 8b1b8ba4..93769d08 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt @@ -42,7 +42,9 @@ data class RawStackDebugConfig( ) fun forCurrentBuild(): RawStackDebugConfig { - return if (BuildConfig.DEBUG) CompactSummary else Disabled + // Diagnostic shaders and SSBO readback are opt-in. A normal debug photo must exercise + // the same production pass graph instead of paying for metrics that do not affect output. + return Disabled } } } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt index 2b151818..a0bd97d7 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt @@ -13,7 +13,6 @@ data class RawStackTuningProfile( val prefilter: RawStackPrefilterTuning = RawStackPrefilterTuning(), val blend: RawStackBlendTuning = RawStackBlendTuning(), val postfilter: RawStackPostfilterTuning = RawStackPostfilterTuning(), - val hdr: RawStackHdrTuning = RawStackHdrTuning(), val superResolution: RawStackSuperResolutionTuning = RawStackSuperResolutionTuning(), ) @@ -26,6 +25,13 @@ data class RawStackPrefilterTuning( val alignSampleStep: Int = 2, val alignCoveragePenalty: Float = 0.08f, val alignShiftPenalty: Float = 0.0006f, + val temporalGraphTileSpacing: Int = 64, + val temporalGraphMinimumSeedConfidence: Float = 0.02f, + val temporalGraphRefineSearchRadiusLevel: Int = 2, + val temporalGraphFrameMinCoverage: Float = 0.08f, + val temporalGraphFrameMinMeanConfidence: Float = 0.03f, + val temporalGraphFrameMinQuadrants: Int = 2, + val temporalGraphFrameMaxResidualP90PlanePx: Float = 1.5f, val structureFlatnessSnrLow: Float = 0.35f, val structureFlatnessSnrHigh: Float = 4.0f, val structureKernelDetail: Float = 0.26f, @@ -51,6 +57,11 @@ data class RawStackBlendTuning( val flowPenaltyDecay: Float = 0.1f, val flowRangePenaltyStartPx: Float = 8.0f, val flowRangePenaltyDecay: Float = 0.1f, + val patchScoreFullConfidence: Float = 0.035f, + val patchScoreReject: Float = 0.18f, + val patchPeakConfidenceStart: Float = 0.005f, + val patchPeakConfidenceFull: Float = 0.08f, + val patchConfidenceFloor: Float = 0.05f, val robustMinMixFlat: Float = 0.35f, val robustMinMixEdge: Float = 0.15f, val robustCenterMixFlat: Float = 0.35f, @@ -134,29 +145,18 @@ data class RawStackPostfilterTuning( val residualNoiseHighScale: Float = 6.0f, val residualSmoothBoost: Float = 1.10f, val maxSmoothStrength: Float = 0.92f, - val hdrRecoverySmoothSuppression: Float = 0.65f, -) - -data class RawStackHdrTuning( - val shortGlobalSearchRadiusLevel: Int = 8, - val shortGlobalSampleStep: Int = 6, - val shortGlobalSampleBorder: Int = 8, - val shortGlobalCoveragePenalty: Float = 0.12f, - val shortGlobalShiftPenalty: Float = 0.0008f, ) data class RawStackSuperResolutionTuning( val internalScale: Float = 2.0f, val outputScale: Float = 1.5f, - val greenFootprintSigmaRawPx: Float = 0.65f, + val cfaFootprintSigmaRawPx: Float = 0.65f, val phaseNoveltyStartPx: Float = 0.10f, val phaseNoveltyFullPx: Float = 0.45f, val accumulationMinPhaseWeight: Float = 0.10f, val minEffectiveWeight: Float = 0.35f, val detailConfidenceStartScale: Float = 0.25f, val detailConfidenceFullScale: Float = 1.50f, - val localFlowResidualStrength: Float = 0.65f, - val localFlowResidualMaxPx: Float = 0.75f, val fallbackMinAlignedFrames: Int = 3, val fallbackMinDetailFrames: Int = 3, val fallbackMinDetailWeightSum: Float = 2.25f, @@ -176,6 +176,6 @@ data class RawStackSuperResolutionTuning( val registrationSeedDistanceEndPx: Float = 1.50f, val registrationConsistencyDistanceStartPx: Float = 1.25f, val registrationConsistencyDistanceEndPx: Float = 2.50f, - val greenReconstructionLowLightSuppression: Float = 0.45f, - val greenReconstructionLscSuppression: Float = 0.35f, + val reconstructionLowLightSuppression: Float = 0.45f, + val reconstructionLscSuppression: Float = 0.35f, ) diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt new file mode 100644 index 00000000..ab5fa42e --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt @@ -0,0 +1,50 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min + +internal data class RawSourceRowBand( + val firstRow: Int, + val rowCount: Int, +) { + val endExclusive: Int + get() = firstRow + rowCount +} + +internal object RawSuperResolutionStripePlanner { + fun sourceRowBand( + outputRowOffset: Int, + outputRowCount: Int, + outputScale: Float, + minFlowYPlanePx: Float, + maxFlowYPlanePx: Float, + cfaPeriod: Int, + rawHeight: Int, + ): RawSourceRowBand { + require(outputRowOffset >= 0) + require(outputRowCount > 0) + require(outputScale.isFinite() && outputScale >= 1f) + require(rawHeight > 0) + + val firstOutputCenter = outputRowOffset + 0.5f + val lastOutputCenter = outputRowOffset + outputRowCount - 0.5f + val firstReferenceRaw = firstOutputCenter / outputScale - 0.5f + val lastReferenceRaw = lastOutputCenter / outputScale - 0.5f + val safeMinFlow = minFlowYPlanePx.takeIf { it.isFinite() } ?: 0f + val safeMaxFlow = maxFlowYPlanePx.takeIf { it.isFinite() } ?: 0f + val minFlow = min(safeMinFlow, safeMaxFlow) * 2f + val maxFlow = max(safeMinFlow, safeMaxFlow) * 2f + val gatherMargin = cfaPeriod.coerceAtLeast(2) + RCD_HALO_ROWS + var first = floor(firstReferenceRaw + minFlow - gatherMargin).toInt().coerceIn(0, rawHeight - 1) + // RCD shaders evaluate CFA parity in stripe-local coordinates. Preserve the global phase. + if ((first and 1) != 0) first = (first - 1).coerceAtLeast(0) + val endExclusive = ceil(lastReferenceRaw + maxFlow + gatherMargin + 1f) + .toInt() + .coerceIn(first + 1, rawHeight) + return RawSourceRowBand(firstRow = first, rowCount = endExclusive - first) + } + + private const val RCD_HALO_ROWS = 10 +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentGraph.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentGraph.kt new file mode 100644 index 00000000..6278c257 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentGraph.kt @@ -0,0 +1,106 @@ +package com.hinnka.mycamera.processor + +enum class RawTemporalEdgeType { + ADJACENT, + REFERENCE, + SKIP_ONE, +} + +/** + * A sparse temporal alignment graph. Edge transforms use the convention + * position[to] - position[from], matching the reference-to-current GLES flow convention. + */ +data class RawTemporalAlignmentEdge( + val fromFrameIndex: Int, + val toFrameIndex: Int, + val type: RawTemporalEdgeType, +) + +data class RawTemporalAlignmentGraph( + val frameCount: Int, + val referenceFrameIndex: Int, + val edges: List, +) + +object RawTemporalAlignmentGraphBuilder { + fun build( + frames: List, + referenceFrameIndex: Int = 0, + includeSkipOne: Boolean = true, + ): RawTemporalAlignmentGraph = build( + sensorTimestampsNs = frames.map { it.sensorTimestampNs }, + referenceFrameIndex = referenceFrameIndex, + includeSkipOne = includeSkipOne, + ) + + internal fun build( + sensorTimestampsNs: List, + referenceFrameIndex: Int = 0, + includeSkipOne: Boolean = true, + ): RawTemporalAlignmentGraph { + val frameCount = sensorTimestampsNs.size + if (frameCount == 0) return RawTemporalAlignmentGraph(0, -1, emptyList()) + require(referenceFrameIndex in 0 until frameCount) + val chronological = sensorTimestampsNs.indices.sortedWith( + compareBy { sensorTimestampsNs[it] }.thenBy { it }, + ) + val edges = ArrayList() + val pairs = HashSet() + val maxEdges = (frameCount * MAX_EDGES_PER_FRAME).coerceAtLeast(frameCount - 1) + + // The adjacent chain is a low-baseline initializer and must stay complete. + chronological.zipWithNext().forEach { (from, to) -> + addUnique(edges, pairs, from, to, RawTemporalEdgeType.ADJACENT) + } + + // Reference edges constrain chain drift. Adjacent reference pairs are already represented. + chronological.forEach { frameIndex -> + if (frameIndex != referenceFrameIndex && edges.size < maxEdges) { + addUnique( + edges, + pairs, + referenceFrameIndex, + frameIndex, + RawTemporalEdgeType.REFERENCE, + ) + } + } + + // Skip-one edges close short cycles while keeping graph size linear on mobile. + if (includeSkipOne) { + for (index in 0 until chronological.size - 2) { + if (edges.size >= maxEdges) break + addUnique( + edges, + pairs, + chronological[index], + chronological[index + 2], + RawTemporalEdgeType.SKIP_ONE, + ) + } + } + return RawTemporalAlignmentGraph(frameCount, referenceFrameIndex, edges) + } + + private fun addUnique( + edges: MutableList, + pairs: MutableSet, + from: Int, + to: Int, + type: RawTemporalEdgeType, + ) { + if (from == to) return + val low = minOf(from, to) + val high = maxOf(from, to) + val key = EdgeKey(low, high, type) + if (pairs.add(key)) edges += RawTemporalAlignmentEdge(from, to, type) + } + + private data class EdgeKey( + val lowFrameIndex: Int, + val highFrameIndex: Int, + val type: RawTemporalEdgeType, + ) + + private const val MAX_EDGES_PER_FRAME = 3 +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolver.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolver.kt new file mode 100644 index 00000000..df6638b5 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolver.kt @@ -0,0 +1,283 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.abs +import kotlin.math.hypot +import kotlin.math.max + +data class RawTemporalEdgeObservation( + val edge: RawTemporalAlignmentEdge, + val dxPlanePx: Float, + val dyPlanePx: Float, + val confidence: Float = 1f, +) + +data class RawTemporalFramePosition( + val xPlanePx: Float, + val yPlanePx: Float, +) + +data class RawTemporalAlignmentSolution( + val positions: List, + val residualByObservation: FloatArray, + val acceptedObservationIndices: IntArray, +) + +/** Small dense IRLS solver intended to run once per flow tile, not once per pixel. */ +object RawTemporalAlignmentSolver { + fun solve( + graph: RawTemporalAlignmentGraph, + observations: List, + ): RawTemporalAlignmentSolution? { + if (graph.frameCount <= 0 || graph.referenceFrameIndex !in 0 until graph.frameCount) return null + val valid = observations.withIndex().filter { (_, observation) -> + observation.edge.fromFrameIndex in 0 until graph.frameCount && + observation.edge.toFrameIndex in 0 until graph.frameCount && + observation.edge.fromFrameIndex != observation.edge.toFrameIndex && + observation.dxPlanePx.isFinite() && observation.dyPlanePx.isFinite() && + observation.confidence.isFinite() && observation.confidence > 0f + } + if (graph.frameCount > 1 && valid.isEmpty()) return null + + val validObservations = valid.map { it.value } + val candidates = listOf(RawTemporalEdgeType.ADJACENT, RawTemporalEdgeType.REFERENCE) + .mapNotNull { initializerType -> + optimize( + graph = graph, + observations = validObservations, + initialX = initialFromEdgeType(graph, validObservations, initializerType, useX = true), + initialY = initialFromEdgeType(graph, validObservations, initializerType, useX = false), + ) + } + val best = candidates.minByOrNull { candidate -> + truncatedConsistencyCost(validObservations, candidate.x, candidate.y) + } ?: return null + var x = best.x + var y = best.y + + val validResiduals = residuals(validObservations, x, y) + val rejectThreshold = max(MIN_REJECT_THRESHOLD_PX, robustOutlierThreshold(validResiduals)) + val acceptedValidIndices = validResiduals.indices.filter { validResiduals[it] <= rejectThreshold } + if (acceptedValidIndices.size >= graph.frameCount - 1 && acceptedValidIndices.size < valid.size) { + val acceptedObservations = acceptedValidIndices.map { valid[it].value } + val weights = DoubleArray(acceptedObservations.size) { index -> + acceptedObservations[index].confidence.toDouble() * edgePrior(acceptedObservations[index].edge.type) + } + solveAxis(graph, acceptedObservations, weights, useX = true)?.let { x = it } + solveAxis(graph, acceptedObservations, weights, useX = false)?.let { y = it } + } + + val allResiduals = FloatArray(observations.size) { Float.POSITIVE_INFINITY } + valid.forEach { indexed -> + val observation = indexed.value + allResiduals[indexed.index] = hypot( + (x[observation.edge.toFrameIndex] - x[observation.edge.fromFrameIndex] - observation.dxPlanePx).toFloat(), + (y[observation.edge.toFrameIndex] - y[observation.edge.fromFrameIndex] - observation.dyPlanePx).toFloat(), + ) + } + val accepted = valid.mapNotNull { indexed -> + indexed.index.takeIf { allResiduals[it] <= rejectThreshold } + }.toIntArray() + val positions = List(graph.frameCount) { index -> + RawTemporalFramePosition(x[index].toFloat(), y[index].toFloat()) + } + return RawTemporalAlignmentSolution(positions, allResiduals, accepted) + } + + private fun optimize( + graph: RawTemporalAlignmentGraph, + observations: List, + initialX: DoubleArray, + initialY: DoubleArray, + ): Candidate? { + var x = initialX + var y = initialY + repeat(IRLS_ITERATIONS) { + val residuals = residuals(observations, x, y) + val robustScale = robustScale(residuals) + val weights = DoubleArray(observations.size) { index -> + val observation = observations[index] + val residual = residuals[index] + val huber = if (residual <= robustScale) 1.0 else robustScale / residual.coerceAtLeast(1.0e-6f) + observation.confidence.toDouble() * edgePrior(observation.edge.type) * huber + } + x = solveAxis(graph, observations, weights, useX = true) ?: return null + y = solveAxis(graph, observations, weights, useX = false) ?: return null + } + return Candidate(x, y) + } + + private fun initialFromEdgeType( + graph: RawTemporalAlignmentGraph, + observations: List, + edgeType: RawTemporalEdgeType, + useX: Boolean, + ): DoubleArray { + val positions = DoubleArray(graph.frameCount) + val known = BooleanArray(graph.frameCount) + known[graph.referenceFrameIndex] = true + repeat(graph.frameCount) { + var changed = false + observations.asSequence() + .filter { it.edge.type == edgeType } + .forEach { observation -> + val from = observation.edge.fromFrameIndex + val to = observation.edge.toFrameIndex + val delta = if (useX) observation.dxPlanePx else observation.dyPlanePx + when { + known[from] && !known[to] -> { + positions[to] = positions[from] + delta + known[to] = true + changed = true + } + known[to] && !known[from] -> { + positions[from] = positions[to] - delta + known[from] = true + changed = true + } + } + } + if (!changed) return@repeat + } + return positions + } + + private fun truncatedConsistencyCost( + observations: List, + x: DoubleArray, + y: DoubleArray, + ): Double { + val residuals = residuals(observations, x, y) + var weightedCost = 0.0 + var weightSum = 0.0 + observations.forEachIndexed { index, observation -> + val weight = observation.confidence.toDouble() * edgePrior(observation.edge.type) + val residual = residuals[index].toDouble() + weightedCost += weight * minOf(residual * residual, CONSENSUS_TRUNCATION_PX_SQUARED) + weightSum += weight + } + return weightedCost / weightSum.coerceAtLeast(1.0e-8) + } + + private fun solveAxis( + graph: RawTemporalAlignmentGraph, + observations: List, + weights: DoubleArray, + useX: Boolean, + ): DoubleArray? { + if (graph.frameCount == 1) return DoubleArray(1) + val variableByFrame = IntArray(graph.frameCount) { -1 } + var variableCount = 0 + for (frame in 0 until graph.frameCount) { + if (frame != graph.referenceFrameIndex) variableByFrame[frame] = variableCount++ + } + val normal = Array(variableCount) { DoubleArray(variableCount) } + val rhs = DoubleArray(variableCount) + observations.forEachIndexed { index, observation -> + val weight = weights[index] + if (!weight.isFinite() || weight <= 0.0) return@forEachIndexed + val fromVariable = variableByFrame[observation.edge.fromFrameIndex] + val toVariable = variableByFrame[observation.edge.toFrameIndex] + val delta = (if (useX) observation.dxPlanePx else observation.dyPlanePx).toDouble() + if (fromVariable >= 0) { + normal[fromVariable][fromVariable] += weight + rhs[fromVariable] -= weight * delta + } + if (toVariable >= 0) { + normal[toVariable][toVariable] += weight + rhs[toVariable] += weight * delta + } + if (fromVariable >= 0 && toVariable >= 0) { + normal[fromVariable][toVariable] -= weight + normal[toVariable][fromVariable] -= weight + } + } + for (index in 0 until variableCount) normal[index][index] += RIDGE + val variables = gaussianElimination(normal, rhs) ?: return null + return DoubleArray(graph.frameCount) { frame -> + variableByFrame[frame].takeIf { it >= 0 }?.let { variables[it] } ?: 0.0 + } + } + + private fun gaussianElimination(matrix: Array, rhs: DoubleArray): DoubleArray? { + val size = rhs.size + for (column in 0 until size) { + var pivot = column + for (row in column + 1 until size) { + if (abs(matrix[row][column]) > abs(matrix[pivot][column])) pivot = row + } + if (abs(matrix[pivot][column]) < MIN_PIVOT) return null + if (pivot != column) { + val row = matrix[column] + matrix[column] = matrix[pivot] + matrix[pivot] = row + val value = rhs[column] + rhs[column] = rhs[pivot] + rhs[pivot] = value + } + val divisor = matrix[column][column] + for (entry in column until size) matrix[column][entry] /= divisor + rhs[column] /= divisor + for (row in 0 until size) { + if (row == column) continue + val factor = matrix[row][column] + if (abs(factor) < MIN_PIVOT) continue + for (entry in column until size) matrix[row][entry] -= factor * matrix[column][entry] + rhs[row] -= factor * rhs[column] + } + } + return rhs + } + + private fun residuals( + observations: List, + x: DoubleArray, + y: DoubleArray, + ): FloatArray = FloatArray(observations.size) { index -> + val observation = observations[index] + hypot( + (x[observation.edge.toFrameIndex] - x[observation.edge.fromFrameIndex] - observation.dxPlanePx).toFloat(), + (y[observation.edge.toFrameIndex] - y[observation.edge.fromFrameIndex] - observation.dyPlanePx).toFloat(), + ) + } + + private fun robustScale(residuals: FloatArray): Double { + if (residuals.isEmpty()) return HUBER_MIN_PX + val median = median(residuals) + val deviations = FloatArray(residuals.size) { abs(residuals[it] - median) } + return max(HUBER_MIN_PX, (median + MAD_SCALE * median(deviations)).toDouble()) + } + + private fun robustOutlierThreshold(residuals: FloatArray): Float { + if (residuals.isEmpty()) return MIN_REJECT_THRESHOLD_PX + val median = median(residuals) + val deviations = FloatArray(residuals.size) { abs(residuals[it] - median) } + return median + OUTLIER_MAD_MULTIPLIER * MAD_SCALE * median(deviations) + } + + private fun median(values: FloatArray): Float { + val sorted = values.filter(Float::isFinite).sorted() + if (sorted.isEmpty()) return 0f + val middle = sorted.size / 2 + return if ((sorted.size and 1) == 0) (sorted[middle - 1] + sorted[middle]) * 0.5f else sorted[middle] + } + + private fun edgePrior(type: RawTemporalEdgeType): Double = when (type) { + RawTemporalEdgeType.ADJACENT -> 1.0 + RawTemporalEdgeType.SKIP_ONE -> 0.85 + RawTemporalEdgeType.REFERENCE -> 0.7 + } + + private data class Candidate( + val x: DoubleArray, + val y: DoubleArray, + ) + + private const val IRLS_ITERATIONS = 4 + private const val HUBER_MIN_PX = 0.5 + private const val MIN_REJECT_THRESHOLD_PX = 1.25f + private const val MAD_SCALE = 1.4826f + private const val OUTLIER_MAD_MULTIPLIER = 3.5f + private const val RIDGE = 1.0e-8 + private const val MIN_PIVOT = 1.0e-12 + private const val CONSENSUS_TRUNCATION_PX_SQUARED = 4.0 +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolver.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolver.kt new file mode 100644 index 00000000..41ff7bc5 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolver.kt @@ -0,0 +1,177 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.abs + +/** RGBA per tile: dx, dy, patch score, peak/coverage confidence. */ +data class RawTemporalEdgeFlowField( + val edge: RawTemporalAlignmentEdge, + val width: Int, + val height: Int, + val values: FloatArray, +) { + init { + require(width > 0 && height > 0) + require(values.size == width * height * CHANNEL_COUNT) + } + + companion object { + const val CHANNEL_COUNT = 4 + } +} + +/** RGBA per tile: graph-consistent dx, dy, mean incident residual, confidence. */ +data class RawTemporalFrameFlowField( + val frameIndex: Int, + val width: Int, + val height: Int, + val values: FloatArray, +) + +data class RawTemporalFrameFlowSummary( + val frameIndex: Int, + val validTileCount: Int, + val totalTileCount: Int, + val coveredQuadrants: Int, + val meanConfidence: Float, + val residualP90PlanePx: Float, + val medianDxPlanePx: Float, + val medianDyPlanePx: Float, +) { + val validTileFraction: Float + get() = validTileCount.toFloat() / totalTileCount.coerceAtLeast(1) +} + +object RawTemporalFlowFieldSolver { + fun solve( + graph: RawTemporalAlignmentGraph, + edgeFields: List, + fallbackFlowByFrame: List, + scoreFullConfidence: Float, + scoreReject: Float, + minimumObservationConfidence: Float = 0.02f, + ): List? { + if (graph.frameCount <= 0 || edgeFields.isEmpty()) return null + val width = edgeFields.first().width + val height = edgeFields.first().height + val valueCount = width * height * RawTemporalEdgeFlowField.CHANNEL_COUNT + if (edgeFields.any { it.width != width || it.height != height }) return null + if (fallbackFlowByFrame.size != graph.frameCount || + fallbackFlowByFrame.any { it.size != valueCount } + ) return null + + val outputs = List(graph.frameCount) { frameIndex -> + fallbackFlowByFrame[frameIndex].copyOf().also { values -> + for (tile in 0 until width * height) { + values[tile * 4 + 2] = MAX_STORED_RESIDUAL + values[tile * 4 + 3] = if (frameIndex == graph.referenceFrameIndex) 1f else 0f + } + } + } + for (tile in 0 until width * height) { + val observations = ArrayList(edgeFields.size) + edgeFields.forEach { field -> + val offset = tile * 4 + val dx = field.values[offset] + val dy = field.values[offset + 1] + val score = field.values[offset + 2] + val peakConfidence = field.values[offset + 3] + val scoreConfidence = 1f - smoothStep(scoreFullConfidence, scoreReject, score) + val confidence = peakConfidence.coerceIn(0f, 1f) * scoreConfidence + if (dx.isFinite() && dy.isFinite() && confidence >= minimumObservationConfidence) { + observations += RawTemporalEdgeObservation(field.edge, dx, dy, confidence) + } + } + val solution = RawTemporalAlignmentSolver.solve(graph, observations) ?: continue + val accepted = solution.acceptedObservationIndices.toSet() + for (frameIndex in 0 until graph.frameCount) { + if (frameIndex == graph.referenceFrameIndex) continue + var confidenceSum = 0f + var residualSum = 0f + var incidentCount = 0 + observations.forEachIndexed { observationIndex, observation -> + if (observationIndex !in accepted) return@forEachIndexed + if (observation.edge.fromFrameIndex != frameIndex && + observation.edge.toFrameIndex != frameIndex + ) return@forEachIndexed + confidenceSum += observation.confidence + residualSum += solution.residualByObservation[observationIndex] + incidentCount++ + } + if (incidentCount == 0) continue + val offset = tile * 4 + val meanResidual = (residualSum / incidentCount).coerceIn(0f, MAX_STORED_RESIDUAL) + val residualConfidence = 1f - smoothStep( + FULL_CONFIDENCE_RESIDUAL_PX, + REJECT_CONFIDENCE_RESIDUAL_PX, + meanResidual, + ) + outputs[frameIndex][offset] = solution.positions[frameIndex].xPlanePx + outputs[frameIndex][offset + 1] = solution.positions[frameIndex].yPlanePx + outputs[frameIndex][offset + 2] = meanResidual + outputs[frameIndex][offset + 3] = + ((confidenceSum / incidentCount).coerceIn(0f, 1f) * residualConfidence) + } + } + return outputs.mapIndexed { frameIndex, values -> + RawTemporalFrameFlowField(frameIndex, width, height, values) + } + } + + fun summarize( + field: RawTemporalFrameFlowField, + minimumConfidence: Float = 0.02f, + ): RawTemporalFrameFlowSummary { + val dx = ArrayList() + val dy = ArrayList() + val residuals = ArrayList() + var confidenceSum = 0f + var quadrantMask = 0 + for (y in 0 until field.height) { + for (x in 0 until field.width) { + val offset = (y * field.width + x) * 4 + val tileDx = field.values[offset] + val tileDy = field.values[offset + 1] + val residual = field.values[offset + 2] + val confidence = field.values[offset + 3] + if (!tileDx.isFinite() || !tileDy.isFinite() || !residual.isFinite() || + !confidence.isFinite() || confidence < minimumConfidence + ) continue + dx += tileDx + dy += tileDy + residuals += residual + confidenceSum += confidence + val quadrantX = if (x * 2 < field.width) 0 else 1 + val quadrantY = if (y * 2 < field.height) 0 else 1 + quadrantMask = quadrantMask or (1 shl (quadrantY * 2 + quadrantX)) + } + } + return RawTemporalFrameFlowSummary( + frameIndex = field.frameIndex, + validTileCount = dx.size, + totalTileCount = field.width * field.height, + coveredQuadrants = Integer.bitCount(quadrantMask), + meanConfidence = if (dx.isEmpty()) 0f else confidenceSum / dx.size, + residualP90PlanePx = percentile(residuals, 0.90f), + medianDxPlanePx = percentile(dx, 0.50f), + medianDyPlanePx = percentile(dy, 0.50f), + ) + } + + private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float { + if (!value.isFinite()) return 0f + if (abs(edge1 - edge0) < 1.0e-6f) return if (value >= edge1) 1f else 0f + val t = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f) + return t * t * (3f - 2f * t) + } + + private fun percentile(values: List, percentile: Float): Float { + if (values.isEmpty()) return Float.POSITIVE_INFINITY + val sorted = values.sorted() + val index = ((sorted.lastIndex) * percentile.coerceIn(0f, 1f)).toInt() + return sorted[index] + } + + private const val MAX_STORED_RESIDUAL = 65504f + private const val FULL_CONFIDENCE_RESIDUAL_PX = 0.35f + private const val REJECT_CONFIDENCE_RESIDUAL_PX = 1.5f +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt index 8ae4e45b..29a77269 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt @@ -2,7 +2,7 @@ package com.hinnka.mycamera.raw internal object DngProfileToneCurve { const val GOOGLE_HDR_PROFILE_NAME = "Google Pixel HDR Tone Map" - const val PHOTON_PGTM_PROFILE_NAME = "Photon PGTM" + const val PHOTON_PGTM_PROFILE_NAME = "Photon HDR" private const val POINT_TOLERANCE = 2e-4f private const val LUT_TOLERANCE = 2e-3f diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index fd990425..3a06d530 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -44,6 +44,10 @@ import com.hinnka.mycamera.model.ColorRecipeParams import com.hinnka.mycamera.model.LutSelectorMode import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.phantom.PhantomWidgetProvider +import com.hinnka.mycamera.processor.RawAlignmentProxyConfig +import com.hinnka.mycamera.processor.RawBurstGyroSelector +import com.hinnka.mycamera.processor.RawBurstReferencePlanner +import com.hinnka.mycamera.processor.RawStackFrame import com.hinnka.mycamera.raw.ColorSpace import com.hinnka.mycamera.raw.DcpProfileParser import com.hinnka.mycamera.raw.DcpInfo @@ -88,6 +92,11 @@ data class MultipleExposureFrame( val file: File ) +private data class PendingRawStackFrame( + val frame: RawStackFrame, + val captureResult: CaptureResult?, +) + data class MultipleExposureSessionState( val enabled: Boolean = false, val sessionId: String? = null, @@ -1368,8 +1377,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) private var hasAppliedDefaultFocalLength = false - private val stackingImages = mutableListOf() - private val stackingCaptureResults = mutableListOf() + private val pendingRawStackFrames = mutableListOf() private var multipleExposureMetadata: MediaMetadata? = null var multipleExposureState by mutableStateOf(MultipleExposureSessionState()) private set @@ -1402,7 +1410,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } } - cameraController.onImageCaptured = { image, captureInfo, characteristics, captureResult -> + cameraController.onImageCaptured = { image, captureInfo, characteristics, captureResult, frameMetadata -> if (hdrBracketImages.isNotEmpty() || state.value.hdrBracketCapturing) { handleHdrBracketFrameCaptured(image, captureInfo, characteristics, captureResult) } else if (state.value.burstCapturing) { @@ -1416,31 +1424,70 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } else if (state.value.useMFNR || state.value.useMFSR) { val count = state.value.multiFrameCount - PLog.d(TAG, "Burst frame received: ${stackingImages.size + 1}/$count") - stackingImages.add(image) - stackingCaptureResults.add(captureResult) - if (stackingImages.size >= count) { - val orderedFrames = stackingImages.indices - .map { index -> stackingImages[index] to stackingCaptureResults.getOrNull(index) } - .sortedBy { (frameImage, _) -> frameImage.timestamp } - val imagesToProcess = orderedFrames.map { it.first } - val exposureProducts = orderedFrames.map { (_, result) -> - result?.let(::captureExposureProduct) - } - val focusDistances = orderedFrames.map { (_, result) -> - result?.get(CaptureResult.LENS_FOCUS_DISTANCE) - } - val referenceCaptureResult = orderedFrames.firstOrNull()?.second ?: captureResult - stackingImages.clear() - stackingCaptureResults.clear() + PLog.d(TAG, "Burst frame received: ${pendingRawStackFrames.size + 1}/$count") + pendingRawStackFrames.add( + PendingRawStackFrame( + frame = rawStackFrame(image, captureResult, frameMetadata), + captureResult = captureResult, + ) + ) + if (pendingRawStackFrames.size >= count) { + val chronologicalFrames = pendingRawStackFrames + .sortedBy { it.frame.sensorTimestampNs } + pendingRawStackFrames.clear() viewModelScope.launch { + val gyroSelection = withContext(Dispatchers.Default) { + RawBurstGyroSelector.select(chronologicalFrames.map { it.frame }) + } + gyroSelection.rejectedIndices.forEach { rejectedIndex -> + chronologicalFrames[rejectedIndex].frame.image.close() + } + val gyroOrderedFrames = gyroSelection.orderedAcceptedIndices.map { index -> + chronologicalFrames[index] + } + val proxyConfig = rawAlignmentProxyConfig( + characteristics = characteristics, + captureResult = gyroOrderedFrames.firstOrNull()?.captureResult ?: captureResult, + ) + val referencePlan = if (proxyConfig != null && gyroOrderedFrames.size >= 2) { + runCatching { + withContext(Dispatchers.Default) { + RawBurstReferencePlanner.plan( + frames = gyroOrderedFrames.map { it.frame }, + proxyConfig = proxyConfig, + ) + } + }.onFailure { error -> + PLog.w(TAG, "RAW reference planning failed; keeping Gyro order", error) + }.getOrNull() + } else { + null + } + val orderedFrames = referencePlan?.orderedIndices?.map { index -> + val pending = gyroOrderedFrames[index] + pending.copy( + frame = pending.frame.copy( + preAlignmentToReference = referencePlan.preAlignmentsToReference[index], + ), + ) + } ?: gyroOrderedFrames + if (gyroSelection.rejectedIndices.isNotEmpty() || referencePlan != null) { + PLog.i( + TAG, + "RAW burst plan: gyroReference=${gyroSelection.referenceOriginalIndex}, " + + "reference=${referencePlan?.referenceOriginalIndex ?: 0}, " + + "accepted=${orderedFrames.size}, " + + "rejected=${gyroSelection.rejectedIndices.joinToString()}, " + + "cost=${referencePlan?.referenceCost}", + ) + } + val framesToProcess = orderedFrames.map { it.frame } + val referenceCaptureResult = orderedFrames.firstOrNull()?.captureResult ?: captureResult processStacking( - images = imagesToProcess, + frames = framesToProcess, captureInfo = captureInfo, characteristics = characteristics, captureResult = referenceCaptureResult, - frameExposureProducts = exposureProducts, - frameFocusDistances = focusDistances, ) } } @@ -1473,11 +1520,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) cameraOpenInFlight = false scheduleCameraListRefreshAfterError(code) resetExposureCompensationForCameraRestart() - stackingImages.forEach { - it.close() - } - stackingImages.clear() - stackingCaptureResults.clear() + pendingRawStackFrames.forEach { it.frame.image.close() } + pendingRawStackFrames.clear() burstImages.forEach { it.close() } @@ -2543,8 +2587,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } else { generateThumbnail() - stackingImages.clear() - stackingCaptureResults.clear() + pendingRawStackFrames.forEach { it.frame.image.close() } + pendingRawStackFrames.clear() if (useLivePhoto.value) { cameraController.setCapturingLivePhoto(true) @@ -5019,15 +5063,99 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } } + private fun rawStackFrame( + image: SafeImage, + captureResult: CaptureResult?, + metadata: CapturedFrameMetadata?, + ): RawStackFrame { + return RawStackFrame( + image = image, + sensorTimestampNs = metadata?.sensorTimestampNs ?: image.timestamp, + frameNumber = metadata?.frameNumber ?: -1L, + exposureTimeNs = metadata?.exposureTimeNs + ?: captureResult?.get(CaptureResult.SENSOR_EXPOSURE_TIME) + ?: 0L, + sensitivityIso = metadata?.sensitivityIso + ?: captureResult?.get(CaptureResult.SENSOR_SENSITIVITY) + ?: 0, + exposureProduct = metadata?.exposureProduct + ?: captureResult?.let(::captureExposureProduct) + ?: 1.0, + focusDistanceDiopters = metadata?.focusDistanceDiopters + ?: captureResult?.get(CaptureResult.LENS_FOCUS_DISTANCE) + ?: Float.NaN, + lensState = metadata?.lensState ?: captureResult?.get(CaptureResult.LENS_STATE), + rollingShutterSkewNs = metadata?.rollingShutterSkewNs + ?: captureResult?.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW), + gyroWindow = metadata?.gyroWindow, + ) + } + + private fun rawAlignmentProxyConfig( + characteristics: CameraCharacteristics?, + captureResult: CaptureResult?, + ): RawAlignmentProxyConfig? { + characteristics ?: return null + var cfa = characteristics.get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT) + ?: CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB + val activeArray = characteristics.get( + CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE + ) + if (((activeArray?.left ?: 0) and 1) != 0) { + cfa = when (cfa) { + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG + else -> cfa + } + } + if (((activeArray?.top ?: 0) and 1) != 0) { + cfa = when (cfa) { + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GBRG -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_BGGR -> + CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_GRBG + else -> cfa + } + } + val dynamicBlack = captureResult?.get(CaptureResult.SENSOR_DYNAMIC_BLACK_LEVEL) + val staticBlack = characteristics.get(CameraCharacteristics.SENSOR_BLACK_LEVEL_PATTERN) + val blackByPosition = when { + dynamicBlack != null && dynamicBlack.size >= 4 -> dynamicBlack.copyOf(4) + staticBlack != null -> floatArrayOf( + staticBlack.getOffsetForIndex(0, 0).toFloat(), + staticBlack.getOffsetForIndex(1, 0).toFloat(), + staticBlack.getOffsetForIndex(0, 1).toFloat(), + staticBlack.getOffsetForIndex(1, 1).toFloat(), + ) + else -> FloatArray(4) + } + return RawAlignmentProxyConfig( + cfaArrangement = cfa, + blackLevelByPosition = blackByPosition, + whiteLevel = characteristics.get(CameraCharacteristics.SENSOR_INFO_WHITE_LEVEL) + ?.toFloat() + ?: 1023f, + ) + } + private suspend fun processStacking( - images: List, + frames: List, captureInfo: CaptureInfo, characteristics: CameraCharacteristics?, captureResult: CaptureResult?, - frameExposureProducts: List, - frameFocusDistances: List, ) { try { + val images = frames.map { it.image } PLog.d(TAG, "processStacking started - image size ${images.size}") val context = getApplication() @@ -5210,8 +5338,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) exposureBias = state.value.exposureBias, exportDngWithRawExport = exportDngWithRawExport.value, capturePreviewThumbnail = previewThumbnail, - frameExposureProducts = frameExposureProducts, - frameFocusDistances = frameFocusDistances, + rawStackFrames = frames, ) } PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave") @@ -5853,11 +5980,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) videoAudioInputManager.release() // 清理未处理的连拍图片 - stackingImages.forEach { - it.close() - } - stackingImages.clear() - stackingCaptureResults.clear() + pendingRawStackFrames.forEach { it.frame.image.close() } + pendingRawStackFrames.clear() burstImages.forEach { it.close() } diff --git a/app/src/test/java/com/hinnka/mycamera/camera/GyroExposureWindowIntegratorTest.kt b/app/src/test/java/com/hinnka/mycamera/camera/GyroExposureWindowIntegratorTest.kt new file mode 100644 index 00000000..28005f72 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/camera/GyroExposureWindowIntegratorTest.kt @@ -0,0 +1,60 @@ +package com.hinnka.mycamera.camera + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class GyroExposureWindowIntegratorTest { + @Test + fun constantAngularVelocityIntegratesAcrossInterpolatedBoundaries() { + val samples = listOf( + GyroSample(0L, 1f, 2f, -1f), + GyroSample(5_000_000L, 1f, 2f, -1f), + GyroSample(10_000_000L, 1f, 2f, -1f), + ) + + val window = GyroExposureWindowIntegrator.integrate( + samples = samples, + startTimestampNs = 2_000_000L, + endTimestampNs = 8_000_000L, + ) + + assertEquals(1f, window.coverageRatio, 1e-6f) + assertEquals(0.006f, window.integratedRotationRad[0], 1e-6f) + assertEquals(0.012f, window.integratedRotationRad[1], 1e-6f) + assertEquals(-0.006f, window.integratedRotationRad[2], 1e-6f) + assertEquals(6f, window.angularEnergy, 1e-5f) + assertEquals(0f, window.jerkEnergy, 1e-5f) + assertTrue(window.sampleCount >= 3) + } + + @Test + fun partialSampleCoverageIsReportedWithoutBorrowingData() { + val samples = listOf( + GyroSample(4_000_000L, 1f, 0f, 0f), + GyroSample(8_000_000L, 1f, 0f, 0f), + ) + + val window = GyroExposureWindowIntegrator.integrate( + samples = samples, + startTimestampNs = 0L, + endTimestampNs = 10_000_000L, + ) + + assertEquals(0.4f, window.coverageRatio, 1e-6f) + assertEquals(0.004f, window.integratedRotationRad[0], 1e-6f) + } + + @Test + fun missingSamplesProduceUnavailableWindow() { + val window = GyroExposureWindowIntegrator.integrate( + samples = emptyList(), + startTimestampNs = 100L, + endTimestampNs = 200L, + ) + + assertEquals(0, window.sampleCount) + assertEquals(0f, window.coverageRatio, 0f) + assertTrue(window.integratedRotationRad.all { it == 0f }) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawBurstGyroSelectorTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawBurstGyroSelectorTest.kt new file mode 100644 index 00000000..fe5758ed --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawBurstGyroSelectorTest.kt @@ -0,0 +1,76 @@ +package com.hinnka.mycamera.processor + +import com.hinnka.mycamera.camera.GyroExposureWindow +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Test + +class RawBurstGyroSelectorTest { + @Test + fun lowestRiskFrameBecomesReferenceAndLargeOutlierIsRejected() { + val frames = listOf( + frame(0L, 0.003f), + frame(1L, 0.001f), + frame(2L, 0.002f), + frame(3L, 0.030f), + frame(4L, 0.004f), + ) + + val selection = RawBurstGyroSelector.selectMetadata(frames) + + assertEquals(1, selection.referenceOriginalIndex) + assertEquals(1, selection.orderedAcceptedIndices.first()) + assertArrayEquals(intArrayOf(3), selection.rejectedIndices) + } + + @Test + fun missingGyroIsKeptAndNeverPreferredOverReliableReference() { + val frames = listOf( + frame(0L, null), + frame(1L, 0.002f), + frame(2L, 0.001f), + frame(3L, null), + ) + + val selection = RawBurstGyroSelector.selectMetadata(frames) + + assertEquals(2, selection.referenceOriginalIndex) + assertEquals(0, selection.rejectedIndices.size) + assertEquals(setOf(0, 1, 2, 3), selection.orderedAcceptedIndices.toSet()) + } + + @Test + fun selectorNeverDropsBelowThreeFrames() { + val frames = listOf( + frame(0L, 0.001f), + frame(1L, 0.0012f), + frame(2L, 0.0013f), + frame(3L, 0.050f), + ) + + val selection = RawBurstGyroSelector.selectMetadata(frames) + + assertEquals(3, selection.orderedAcceptedIndices.size) + assertEquals(1, selection.rejectedIndices.size) + } + + private fun frame(timestamp: Long, rotationRadians: Float?): RawBurstGyroFrameSample { + val exposureNs = 10_000_000L + return RawBurstGyroFrameSample( + sensorTimestampNs = timestamp, + exposureTimeNs = exposureNs, + gyroWindow = rotationRadians?.let { + GyroExposureWindow( + startTimestampNs = timestamp, + endTimestampNs = timestamp + exposureNs, + sampleCount = 5, + integratedRotationRad = floatArrayOf(it, 0f, 0f), + angularEnergy = 0f, + peakAngularVelocity = 0f, + jerkEnergy = 0f, + coverageRatio = 1f, + ) + }, + ) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawFramePreAlignmentTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawFramePreAlignmentTest.kt new file mode 100644 index 00000000..b4e201a0 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawFramePreAlignmentTest.kt @@ -0,0 +1,26 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Test + +class RawFramePreAlignmentTest { + @Test + fun expandsRotationAroundBayerPlaneCenter() { + val alignment = RawFramePreAlignment( + translationXPlanePx = 3f, + translationYPlanePx = -2f, + rotationDegrees = 90f, + confidence = 1f, + ) + + val flow = alignment.flowAtPlanePosition( + xPlanePx = 6f, + yPlanePx = 5f, + planeWidth = 11, + planeHeight = 11, + ) + + assertEquals(2f, flow.first, 1.0e-4f) + assertEquals(-1f, flow.second, 1.0e-4f) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawGlobalPreAlignerTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawGlobalPreAlignerTest.kt new file mode 100644 index 00000000..cf666237 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawGlobalPreAlignerTest.kt @@ -0,0 +1,94 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import kotlin.math.abs +import kotlin.math.sin + +class RawGlobalPreAlignerTest { + @Test + fun recoversIntegerTranslation() { + val reference = proxy(pattern(WIDTH, HEIGHT), WIDTH, HEIGHT) + val current = proxy(shift(reference.lowPass, WIDTH, HEIGHT, 4, -2), WIDTH, HEIGHT) + + val alignment = RawGlobalPreAligner.align(reference, current) + + assertNotNull(alignment) + alignment!! + assertEquals(4f, alignment.dxProxyPx, 1f) + assertEquals(-2f, alignment.dyProxyPx, 1f) + assertTrue(alignment.score < 0.2f) + assertTrue(alignment.coverage > 0.75f) + } + + @Test + fun geometryCenterFrameIsSelectedAsReference() { + val base = pattern(WIDTH, HEIGHT) + val proxies = listOf( + proxy(shift(base, WIDTH, HEIGHT, -5, 0), WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2), + proxy(base, WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2), + proxy(shift(base, WIDTH, HEIGHT, 5, 0), WIDTH, HEIGHT).copy(sourcePlaneWidth = WIDTH * 2), + ) + + val plan = RawBurstReferencePlanner.planProxies( + proxies = proxies, + gyroRisks = floatArrayOf(0.001f, 0.001f, 0.001f), + ) + + assertEquals(1, plan.referenceOriginalIndex) + assertEquals(1, plan.orderedIndices.first()) + assertEquals(-10f, plan.preAlignmentsToReference[0]!!.translationXPlanePx, 2f) + assertEquals(10f, plan.preAlignmentsToReference[2]!!.translationXPlanePx, 2f) + } + + private fun proxy(values: FloatArray, width: Int, height: Int): RawAlignmentProxy { + val band = FloatArray(values.size) + for (y in 1 until height - 1) { + for (x in 1 until width - 1) { + val index = y * width + x + band[index] = values[index] - 0.25f * ( + values[index - 1] + values[index + 1] + + values[index - width] + values[index + width] + ) + } + } + return RawAlignmentProxy(width, height, values, band, sharpness = 1f) + } + + private fun pattern(width: Int, height: Int): FloatArray { + return FloatArray(width * height) { index -> + val x = index % width + val y = index / width + val checker = if ((((x / 7) + (y / 5)) and 1) == 0) 0.7f else -0.5f + checker + 0.25f * sin(x * 0.19f) + 0.2f * sin(y * 0.13f) + + if (abs(x - 31) < 3 && abs(y - 57) < 5) 1.2f else 0f + } + } + + private fun shift( + input: FloatArray, + width: Int, + height: Int, + dx: Int, + dy: Int, + ): FloatArray { + val output = FloatArray(input.size) + for (y in 0 until height) { + for (x in 0 until width) { + val sourceX = x - dx + val sourceY = y - dy + if (sourceX in 0 until width && sourceY in 0 until height) { + output[y * width + x] = input[sourceY * width + sourceX] + } + } + } + return output + } + + private companion object { + const val WIDTH = 96 + const val HEIGHT = 96 + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawStackCfaPhaseGatherTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawStackCfaPhaseGatherTest.kt new file mode 100644 index 00000000..adc41af3 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawStackCfaPhaseGatherTest.kt @@ -0,0 +1,77 @@ +package com.hinnka.mycamera.processor + +import com.hinnka.mycamera.raw.RawCfaCorrection +import com.hinnka.mycamera.raw.RawMetadata +import kotlin.math.floor +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Test + +class RawStackCfaPhaseGatherTest { + @Test + fun fourTapGatherPreservesExactCfaPhaseForEverySupportedPattern() { + val patterns = RawMetadata.CFA_RGGB..RawMetadata.CFA_QUAD_8X8_BGGR + val output = SamplePosition(13, 11) + val sourceRaw = 9.35f to 7.80f + + patterns.forEach { cfaPattern -> + val period = RawCfaCorrection.repeatPatternDim(cfaPattern)[0] + val targetChannel = RawCfaCorrection.channelIndexForPixel( + cfaPattern, + output.x, + output.y, + ) + val samples = samePhaseFourTapGather(output, sourceRaw, period) + + assertEquals(4, samples.size) + samples.forEach { sample -> + assertEquals(Math.floorMod(output.x, period), Math.floorMod(sample.x, period)) + assertEquals(Math.floorMod(output.y, period), Math.floorMod(sample.y, period)) + assertEquals( + targetChannel, + RawCfaCorrection.channelIndexForPixel(cfaPattern, sample.x, sample.y), + ) + } + } + } + + @Test + fun motionMovesGatherFootprintWithoutChangingOutputPhase() { + val output = SamplePosition(8, 5) + val period = 2 + val first = samePhaseFourTapGather(output, 6.1f to 4.2f, period) + val shifted = samePhaseFourTapGather(output, 8.2f to 2.1f, period) + + assertNotEquals(first, shifted) + (first + shifted).forEach { sample -> + assertEquals(Math.floorMod(output.x, period), Math.floorMod(sample.x, period)) + assertEquals(Math.floorMod(output.y, period), Math.floorMod(sample.y, period)) + } + } + + /** Mirrors the integer lattice construction in SUPER_RESOLUTION_ACCUMULATE_COMPUTE_SHADER. */ + private fun samePhaseFourTapGather( + output: SamplePosition, + sourceRaw: Pair, + period: Int, + ): List { + val phaseX = Math.floorMod(output.x, period) + val phaseY = Math.floorMod(output.y, period) + val originX = floor((sourceRaw.first - phaseX) / period).toInt() + val originY = floor((sourceRaw.second - phaseY) / period).toInt() + return buildList(4) { + for (latticeY in 0..1) { + for (latticeX in 0..1) { + add( + SamplePosition( + x = phaseX + (originX + latticeX) * period, + y = phaseY + (originY + latticeY) * period, + ), + ) + } + } + } + } + + private data class SamplePosition(val x: Int, val y: Int) +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt new file mode 100644 index 00000000..30fa3cac --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt @@ -0,0 +1,42 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RawSuperResolutionStripePlannerTest { + @Test + fun stationaryTwoXStripeUploadsOnlyCorrespondingRawBand() { + val band = RawSuperResolutionStripePlanner.sourceRowBand( + outputRowOffset = 512, + outputRowCount = 256, + outputScale = 2f, + minFlowYPlanePx = 0f, + maxFlowYPlanePx = 0f, + cfaPeriod = 2, + rawHeight = 3000, + ) + + assertTrue(band.firstRow <= 255) + assertTrue(band.endExclusive >= 384) + assertTrue(band.rowCount < 150) + } + + @Test + fun flowExtremaExpandBandInBothDirections() { + val stationary = RawSuperResolutionStripePlanner.sourceRowBand(512, 256, 2f, 0f, 0f, 2, 3000) + val moving = RawSuperResolutionStripePlanner.sourceRowBand(512, 256, 2f, -6f, 8f, 2, 3000) + + assertTrue(moving.firstRow < stationary.firstRow) + assertTrue(moving.endExclusive > stationary.endExclusive) + } + + @Test + fun firstAndLastStripeClampToSensorBounds() { + val first = RawSuperResolutionStripePlanner.sourceRowBand(0, 256, 2f, -10f, 2f, 8, 1000) + val last = RawSuperResolutionStripePlanner.sourceRowBand(1792, 208, 2f, -2f, 10f, 8, 1000) + + assertEquals(0, first.firstRow) + assertEquals(1000, last.endExclusive) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolverTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolverTest.kt new file mode 100644 index 00000000..f339e213 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalAlignmentSolverTest.kt @@ -0,0 +1,53 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class RawTemporalAlignmentSolverTest { + @Test + fun graphContainsCompleteAdjacentChainAndSparseCycleEdges() { + val graph = RawTemporalAlignmentGraphBuilder.build( + sensorTimestampsNs = listOf(40L, 10L, 30L, 20L, 50L), + referenceFrameIndex = 2, + ) + + val adjacent = graph.edges.filter { it.type == RawTemporalEdgeType.ADJACENT } + assertEquals(4, adjacent.size) + assertTrue(graph.edges.size <= 15) + assertEquals( + setOf(1 to 3, 3 to 2, 2 to 0, 0 to 4), + adjacent.map { it.fromFrameIndex to it.toFrameIndex }.toSet(), + ) + } + + @Test + fun rejectsCorruptReferenceEdgeAndKeepsTemporalConsensus() { + val graph = RawTemporalAlignmentGraphBuilder.build( + sensorTimestampsNs = listOf(0L, 1L, 2L, 3L, 4L), + referenceFrameIndex = 0, + ) + val observations = graph.edges.map { edge -> + val expected = edge.toFrameIndex - edge.fromFrameIndex.toFloat() + val corrupt = edge.type == RawTemporalEdgeType.REFERENCE && edge.toFrameIndex == 4 + RawTemporalEdgeObservation( + edge = edge, + dxPlanePx = if (corrupt) 18f else expected, + dyPlanePx = 0f, + ) + } + + val solution = RawTemporalAlignmentSolver.solve(graph, observations)!! + + solution.positions.forEachIndexed { index, position -> + assertEquals(index.toFloat(), position.xPlanePx, 0.35f) + assertEquals(0f, position.yPlanePx, 0.01f) + } + val corruptIndex = observations.indexOfFirst { + it.edge.type == RawTemporalEdgeType.REFERENCE && it.edge.toFrameIndex == 4 + } + assertFalse(solution.acceptedObservationIndices.contains(corruptIndex)) + assertTrue(solution.residualByObservation[corruptIndex] > 5f) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolverTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolverTest.kt new file mode 100644 index 00000000..48db4878 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawTemporalFlowFieldSolverTest.kt @@ -0,0 +1,54 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RawTemporalFlowFieldSolverTest { + @Test + fun solvesEachTileAndRejectsDifferentBadEdges() { + val graph = RawTemporalAlignmentGraphBuilder.build( + sensorTimestampsNs = listOf(0L, 1L, 2L, 3L), + referenceFrameIndex = 0, + ) + val edgeFields = graph.edges.map { edge -> + val values = FloatArray(2 * 4) + for (tile in 0..1) { + val offset = tile * 4 + val expected = (edge.toFrameIndex - edge.fromFrameIndex).toFloat() + val badAnchor = tile == 0 && edge.type == RawTemporalEdgeType.REFERENCE && + edge.toFrameIndex == 3 + val badAdjacent = tile == 1 && edge.type == RawTemporalEdgeType.ADJACENT && + edge.fromFrameIndex == 1 && edge.toFrameIndex == 2 + values[offset] = if (badAnchor || badAdjacent) expected + 12f else expected + values[offset + 1] = 0f + values[offset + 2] = 0.01f + values[offset + 3] = 1f + } + RawTemporalEdgeFlowField(edge, width = 2, height = 1, values = values) + } + val fallback = List(4) { FloatArray(2 * 4) } + + val result = RawTemporalFlowFieldSolver.solve( + graph = graph, + edgeFields = edgeFields, + fallbackFlowByFrame = fallback, + scoreFullConfidence = 0.035f, + scoreReject = 0.18f, + )!! + + for (frameIndex in 1..3) { + for (tile in 0..1) { + val offset = tile * 4 + assertEquals(frameIndex.toFloat(), result[frameIndex].values[offset], 0.35f) + assertTrue(result[frameIndex].values[offset + 3] > 0.5f) + } + } + val summary = RawTemporalFlowFieldSolver.summarize(result[3]) + assertEquals(2, summary.validTileCount) + assertEquals(2, summary.coveredQuadrants) + assertEquals(1f, summary.validTileFraction, 1.0e-6f) + assertEquals(3f, summary.medianDxPlanePx, 0.35f) + assertTrue(summary.residualP90PlanePx < 0.35f) + } +} diff --git a/docs/gles-driver-compatibility.md b/docs/gles-driver-compatibility.md new file mode 100644 index 00000000..547a21ba --- /dev/null +++ b/docs/gles-driver-compatibility.md @@ -0,0 +1,74 @@ +# GLES 驱动兼容性记录 + +本文记录项目在真实 Android 设备上确认过的 GLES 驱动限制。修改 compute shader、image +load/store、纹理格式或 accumulator 架构前必须复查本文,并在目标设备上运行 +`GlesRawStackerShaderTest`。不能仅凭 GLES 版本号或桌面 GLSL 编译结果判断移动端可用性。 + +## PMA110 + +### `RGBA16F` image 的访问限制 + +PMA110 的 GLES 驱动可以编译和运行以下组合: + +- `layout(rgba16f) writeonly image2D` +- `glBindImageTexture(..., GL_WRITE_ONLY, GL_RGBA16F)` + +但不能编译以下组合: + +- `layout(rgba16f) image2D`,即 read/write image +- 对该 image 同时使用 `imageLoad` 与 `imageStore` +- `glBindImageTexture(..., GL_READ_WRITE, GL_RGBA16F)` + +驱动编译错误为: + +```text +Shader raw_accumulate compute compilation failed: +unsupported format on read/write image +``` + +因此不得使用单张 `RGBA16F` texture 原位完成 accumulator 的读取和写入。即使同一个 +compute invocation 只访问唯一像素、没有跨 invocation 竞争,该格式仍会在 shader 编译阶段 +被驱动拒绝。 + +### 当前兼容策略 + +需要原位 read/write 的 half-float accumulator 使用规范支持的整数 image: + +- `R32UI` +- `layout(r32ui) uimage2D` +- `GL_READ_WRITE + GL_R32UI` +- 使用 `packHalf2x16` / `unpackHalf2x16` 在一个 texel 中保存两个 half + +RAW base accumulator 使用两张 `R32UI`: + +1. `weightedValue + weight` +2. `squareSum + clipMass` + +总显存仍为 8 B/像素,与单张 `RGBA16F` 相同,但不需要两张 `RGBA16F` ping-pong。 +MFSR accumulator 只保存 `weightedValue + weight`,使用一张 `R32UI`,为 4 B/输出像素。 + +所有读取 accumulator 的 fragment/compute shader 必须使用 `usampler2D`,取出 `uint` 后再 +调用 `unpackHalf2x16`。禁止把 `R32UI` texture 绑定给普通 `sampler2D`。 + +### 验收要求 + +相关修改至少验证以下路径: + +- shader compile/link +- `GL_R32UI` clear dispatch +- `GL_READ_WRITE` accumulator dispatch +- `R32UI` imageLoad/imageStore +- `usampler2D` normalize +- MFNR 与 MFSR 两种模式 + +桌面静态检查和 Kotlin 编译不能替代真机验证。新增格式前应优先扩展 +`app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt`,让测试实际 +dispatch 对应 pass,而不只编译 program。 + +## 通用规则 + +- 不根据 `GL_MAX_TEXTURE_SIZE` 推断 image load/store 格式支持。 +- 不根据 write-only image 可用推断同格式 read/write image 也可用。 +- 不以增加补偿 pass 掩盖驱动格式错误;应选择驱动明确支持的存储格式和访问模型。 +- 每个新增 image format 都需要在代表设备上验证 compile、bind、dispatch 和后续采样。 +- 运行时错误日志必须保留 shader 名称、访问模式、internal format 和驱动错误文本。 diff --git a/docs/image-stack-alignator-gles-raw-stacker-rearchitecture.md b/docs/image-stack-alignator-gles-raw-stacker-rearchitecture.md new file mode 100644 index 00000000..74514087 --- /dev/null +++ b/docs/image-stack-alignator-gles-raw-stacker-rearchitecture.md @@ -0,0 +1,1024 @@ +# GlesRawStacker 重构方案:ImageStackAlignator 移动端等价实现 + +## 1. 方案目标 + +本方案重构 Photon 的 RAW 多帧拍摄与合成链路,算法目标以 ImageStackAlignator 对 Google HWMF/MFSR 的实现为基准,同时满足 Android Camera2、GLES 3.1、移动端显存、功耗和拍摄延迟约束。 + +目标不是继续在现有 `GlesRawStacker` 上叠加阈值,而是重新闭合以下逻辑链: + +1. 拍摄端为每帧建立可靠的 Camera2 与 Gyro 时间同步元数据。 +2. 在进入 GPU 合成前完成帧质量筛选、参考帧选择和处理顺序规划。 +3. 使用全局预对齐扩大局部搜索的收敛范围。 +4. 使用局部多尺度 patch tracking 生成位移场。 +5. 使用有限时间图和鲁棒最小二乘约束多帧位移的一致性。 +6. 使用 Lucas–Kanade 完成亚像素精修。 +7. 使用噪声模型、光度残差和 flow 不连续度生成可解释的 certainty mask。 +8. 使用参考帧结构张量生成各向异性重建核。 +9. 在 RAW/CFA 域完成 MFNR 或 MFSR 重建,不从绿色通道推导红蓝细节。 +10. 只输出生产决策必需的质量和降级原因,后续 RAW renderer 依据有效融合结果决定去噪强度。 + +## 2. 基本原则 + +### 2.1 复刻算法语义,不复刻桌面实现代价 + +ImageStackAlignator 的优秀设计应尽可能保留其算法语义: + +- 全局平移和旋转预对齐。 +- 根据整组位移选择几何中心参考帧。 +- 多尺度归一化相关 patch tracking。 +- 不只测量 `frame -> reference`,还利用帧间依赖和闭环一致性。 +- 对异常位移观测进行剔除后重新求解。 +- Lucas–Kanade 亚像素精修。 +- 参考帧全分辨率结构张量与各向异性重建核。 +- 噪声模型驱动的 robustness/certainty。 +- RAW 样本直接参与每个 CFA 通道的重建。 + +以下桌面实现方式不直接复制: + +- 所有帧对的 `O(N²)` FFT tracking。 +- 全分辨率、多帧 GPU 常驻。 +- 暴力扫描大范围旋转角。 +- 每个 patch 分配独立 FFT 工作区。 +- C# 端大量 GPU/CPU 往返和人工调参流程。 + +### 2.2 Gyro 负责质量和初值,视觉配准负责最终几何 + +Gyro 不直接替代图像对齐。其职责限定为: + +- 曝光期间运动模糊风险评分。 +- 粗略全局旋转和平移搜索中心估计。 +- 帧筛除和参考帧质量评分。 +- 视觉配准失败时的诊断证据。 + +最终 RAW 采样坐标必须来自视觉配准得到的局部位移场。原因是 Gyro 无法覆盖 OIS 位移、平移、景深视差、主体运动、rolling shutter 和 Camera/IMU 外参误差。 + +### 2.3 画质决策必须可解释,但不为诊断增加生产算法 + +每个帧、tile 和输出像素的拒绝必须能够归因于以下明确证据: + +- Gyro 模糊风险。 +- focus distance 不一致。 +- patch 相关峰不明确。 +- 时间图闭环残差过大。 +- LK 结构矩阵退化。 +- flow 局部不连续。 +- 光度残差超过噪声模型可解释范围。 +- 高光或暗部没有有效样本。 + +不再用层层叠加、互相补偿的经验 gate 掩盖上游错误。 + +可解释性不等于保留一套重型诊断流水线。生产路径遵循: + +- 只记录算法本来就会计算的 score、weight、residual 和 reject reason。 +- 不为统计额外执行全图 compute pass。 +- 不为日志额外拟合第二套 global/affine 模型。 +- 不在生产路径 readback flow、certainty、accumulator 或直方图全图。 +- 不使用 `glFinish` 获取精确计时。 +- Debug 构建可按需启用单次 map 导出,但相关 program、SSBO 和纹理不在默认路径创建。 + +## 3. 目标数据模型 + +### 3.1 `RawBurstFrame` + +替换当前只包含 image、exposure product 和 focus distance 的 `RawStackFrame`: + +```kotlin +data class RawBurstFrame( + val image: SafeImage, + val sensorTimestampNs: Long, + val frameNumber: Long, + val exposureTimeNs: Long, + val sensitivityIso: Int, + val exposureProduct: Double, + val focusDistanceDiopters: Float, + val lensState: Int?, + val rollingShutterSkewNs: Long?, + val gyroWindow: GyroExposureWindow?, + val role: RawBurstFrameRole, +) +``` + +`RawBurstFrameRole` 至少包含: + +- `NORMAL` +- `HDR_SHORT` +- `HDR_LONG` + +帧对象必须按 `sensorTimestampNs` 排序,但参考帧选择与 GPU 处理顺序由后续 plan 决定,不能再把时间排序后的第一帧隐式当作 reference。 + +### 3.2 `GyroExposureWindow` + +```kotlin +data class GyroExposureWindow( + val startTimestampNs: Long, + val endTimestampNs: Long, + val sampleCount: Int, + val integratedRotationRad: FloatArray, + val angularEnergy: Float, + val peakAngularVelocity: Float, + val jerkEnergy: Float, + val coverageRatio: Float, +) +``` + +### 3.3 `RawBurstPlan` + +```kotlin +data class RawBurstPlan( + val acceptedFrames: List, + val rejectedFrames: List, + val referenceFrameIndex: Int, + val processingOrder: IntArray, + val temporalGraph: RawTemporalGraph, + val mode: RawStackMode, + val performanceTier: RawStackPerformanceTier, +) +``` + +`RawBurstPlan` 是拍摄与算法之间的唯一边界。`GlesRawStacker` 不再自行假设第一帧、帧顺序、角色或可用帧数。 + +## 4. 拍摄端:Gyro 采集、筛帧和排序 + +### 4.1 时间同步 + +新增 `BurstGyroRecorder`,使用 `TYPE_GYROSCOPE_UNCALIBRATED` 优先、`TYPE_GYROSCOPE` 回退,并以传感器支持的最高稳定频率记录环形缓冲。 + +要求: + +1. 使用 `SensorEvent.timestamp`。 +2. 每帧使用 `CaptureResult.SENSOR_TIMESTAMP` 和 `SENSOR_EXPOSURE_TIME` 定义曝光窗口。 +3. 曝光窗口为 `[sensorTimestamp, sensorTimestamp + exposureTime]`;设备验证必须确认其 timestamp 语义,若设备报告曝光结束时间,则通过日志校准后调整。 +4. 为窗口前后保留约 2 ms guard samples,插值到窗口边界。 +5. 记录覆盖率;覆盖率不足不能循环复用其他帧 Gyro 数据。 +6. Camera2 timestamp 和 Sensor timestamp 的时间基准必须通过设备启动时与实拍日志验证;发现稳定偏移时只允许设备级校准,不允许逐帧猜测。 + +### 4.2 Gyro 模糊风险评分 + +参考 eszdmanPhoton 的 `shakiness` 思路,但避免只使用单一积分平方: + +```text +gyroBlurScore = + w1 * projectedIntegratedRotationPx + + w2 * projectedAngularEnergyPx + + w3 * projectedPeakVelocityPx + + w4 * jerkPenalty + + w5 * coveragePenalty +``` + +角运动通过当前焦距、sensor active array 和视场角投影到像素域。没有可靠内参时使用归一化角运动,不伪造像素值。 + +Gyro 评分只反映相机运动,不反映主体运动和纯平移,因此不能作为唯一帧质量指标。 + +### 4.3 低成本图像质量评分 + +ImageReader 收齐帧后,在 GPU 主合成前为每张 RAW 生成小尺寸绿色代理图。参考帧规划使用最大长边 128 的直接抽样代理;后续局部 tracking 可独立生成更高分辨率 proxy: + +- CFA-aware 绿色采样。 +- 黑白电平归一化。 +- 曝光归一化。 +- 计算 Laplacian/Tenengrad 清晰度。 +- 计算高光饱和率、暗部无信息率和坏点异常率。 + +```text +frameQuality = + sharpnessReward + - gyroBlurPenalty + - saturationPenalty + - shadowFailurePenalty + - focusMismatchPenalty +``` + +### 4.4 初始筛帧规则 + +筛帧按曝光角色分别执行: + +- 非 HDR:至少保留 3 帧;只有 2 帧可用时允许 MFNR,但禁用 MFSR。 +- HDR:至少保留 1 张短曝和 2 张 normal;短曝不可因与 normal 曝光不同而被质量比较直接淘汰。 +- Gyro 数据缺失只降低置信度,不能自动删除唯一有效曝光角色。 +- focus distance 超阈值变化直接拒绝,除非该帧是唯一 HDR 短曝,此时保留但只允许参与受限高光恢复。 +- 清晰度显著低于中位数且 Gyro 同时异常的帧拒绝。 +- 单一指标异常时保守降权,两个独立指标同时异常才整帧拒绝。 + +### 4.5 参考帧选择 + +参考帧不在拍摄端立即固定。流程为: + +1. 从质量排名前若干帧中选择候选。 +2. 对候选执行低分辨率全局预对齐。 +3. 为候选计算: + +```text +referenceCost = + sum(globalTranslationDistanceToAllFrames) + + maxTranslationPenalty + + rotationPenalty + + gyroBlurPenalty + + sharpnessPenalty + + edgeCropLossPenalty + + exposureRolePenalty +``` + +4. 选择 cost 最低的 normal 帧作为 reference。 + +这同时吸收 ImageStackAlignator 的几何中心参考帧和 eszdmanPhoton 的稳定帧优先策略。 + +### 4.6 处理顺序 + +融合顺序以参考帧为中心向时间两侧扩展,并优先处理: + +- 与 reference 全局位移较小的帧。 +- Gyro 风险较低的帧。 +- 时间图中能为后续帧提供稳定相邻边的帧。 + +Accumulator 使用加权和,因此处理顺序原则上不应改变最终数学结果;顺序仅用于尽早获得稳定的图约束和在 GPU 超时/热降级时保留最佳子集。 + +## 5. GlesRawStacker 目标流水线 + +```mermaid +flowchart TD + A["RawBurstPlan"] --> B["CFA-aware proxy"] + B --> C["Low-pass + high-pass proxy pyramid"] + C --> D["Global translation/rotation pre-alignment"] + D --> E["Reference selection finalized"] + E --> F["Temporal graph edge tracking"] + F --> G["Robust graph solve per tile"] + G --> H["LK subpixel refinement"] + H --> I["Flow consistency + photometric certainty"] + E --> J["Reference structure tensor"] + J --> K["Anisotropic reconstruction kernel"] + I --> L["CFA-domain MFNR/MFSR accumulation"] + K --> L + L --> M["Normalize + coverage fallback"] + M --> N["RawStackResult + decision summary"] +``` + +## 6. Proxy 与预滤波 + +### 6.1 Proxy 格式 + +统一使用半分辨率或四分之一分辨率 `R16F` 绿色亮度代理,不再用 RGBA 纹理保存单通道数据。 + +每个 proxy 像素来自一个 CFA block: + +- Bayer:两颗绿色平均。 +- Quad Bayer / 特殊 CFA:按实际 CFA 周期生成绿色或亮度代理。 +- 先减黑电平、除有效白电平,再应用曝光尺度。 + +为避免不同曝光和高光截断破坏相关性,proxy 使用单调压缩: + +```text +proxy = log(1 + k * linearSignal) / log(1 + k) +``` + +不得在 RAW 主合成数据上应用该压缩。 + +### 6.2 双带代理 + +参考 ImageStackAlignator 的高通经验,同时输出: + +- `proxyLow`: Gaussian 低通后用于噪声稳定的 patch matching。 +- `proxyBand`: `proxyLow - widerGaussian(proxyLow)`,抑制低频固定图样和渐晕残差。 + +相关代价同时包含亮度带与高通带: + +```text +cost = normalizedL2(proxyLow) + hpWeight * normalizedL2(proxyBand) +``` + +不在 GLES 中实现通用 FFT 高通;DoG 是移动端等价实现,内存和执行时间可控。 + +## 7. 全局预对齐 + +### 7.1 几何模型 + +全局预对齐只求: + +- 平移 `dx, dy` +- 小角度旋转 `theta` + +不在此阶段拟合 projective homography。手机 burst 的大透视变化通常意味着场景或拍摄已经不适合稳定 MFSR;过早引入高自由度模型容易吸收局部运动并制造错误几何。 + +### 7.2 移动端搜索方式 + +不实现全图 cuFFT。采用 DS16/DS32 proxy 上的 coarse-to-fine compute search: + +1. Gyro integrated roll 给出 `theta` 搜索中心。 +2. 在小角度集合上评估全局 normalized L2/correlation。 +3. 每个角度在低分辨率搜索平移。 +4. 保留最优与次优 score,输出 margin 和 coverage。 +5. 在更高一层围绕最优解精修。 + +默认旋转范围由 Gyro 置信度决定;Gyro 缺失时扩大范围,但受严格性能预算限制。 + +输出: + +```kotlin +data class GlobalPreAlignment( + val dxRawPx: Float, + val dyRawPx: Float, + val rotationRad: Float, + val score: Float, + val margin: Float, + val coverage: Float, +) +``` + +该结果只作为 patch tracking 的初值和参考帧选择依据,不直接成为最终 MFNR/MFSR 主 warp。 + +## 8. 时间图 Patch Tracking + +### 8.1 图结构 + +ImageStackAlignator 的 `Full` 策略质量高但为 `O(N²)`。移动端采用有界稀疏图: + +- reference 到所有 accepted frame 的 anchor edge。 +- 时间相邻边 `(i, i+1)`。 +- 隔一帧边 `(i, i+2)`,仅在帧数和性能预算允许时启用。 +- 对 anchor edge 质量差的帧,增加到最近高质量帧的 recovery edge。 + +8 帧典型边数约 18~22,而全图为 28。12 帧典型边数约 30~34,而全图为 66。 + +### 8.2 多尺度局部匹配 + +每条边执行粗到细 patch tracking: + +1. 全局预对齐提供初值。 +2. 低层使用较大 tile 和搜索半径。 +3. 上采样 flow 到高层。 +4. 高层使用较小搜索范围修正。 +5. 所有层使用 normalized L2/correlation,不混用语义不一致的代价。 +6. 保存 best score、second-best score、coverage 和局部结构强度。 + +无纹理 tile 不生成“看似有效”的零 flow,而是输出: + +- `increment = 0` +- `measurementValid = false` +- 继承上层或全局初值 + +### 8.3 图一致性求解 + +对于每个 tile,测量边满足: + +```text +observedShift(i -> j) ~= position[j] - position[i] +``` + +以 reference position 为零,求所有帧的 tile position: + +```text +min Σ edgeWeight * robustLoss( + position[j] - position[i] - observedShift[i,j] +) +``` + +实现约束: + +- 帧数通常不超过 12,方程规模很小。 +- GPU 只负责生成 edge observation。 +- 将低分辨率 tile observation 成批 readback 到 CPU。 +- CPU 使用预计算图矩阵和 2~3 次 IRLS 解 X/Y 两个小型系统。 +- Huber/Tukey 权重剔除闭环残差异常边。 +- 解算结果上传为每帧 flow seed texture。 + +CPU 求解避免在 GLES 中实现复杂稀疏线性代数,readback 数据量仅为 tile 数 × edge 数 × 少量 float,远小于 RAW readback。 + +### 8.4 为什么替换当前 registration gate + +当前实现对单帧 flow 再拟合 global translation/affine,并叠加大量 confidence、seed、consistency 和 SR gate。该结构存在两个问题: + +1. 先把局部运动压缩为全局模型,再允许有限 local residual,可能损失真实的局部视差与 rolling-shutter 形变。 +2. 多个 gate 对同一批证据重复判断,难以确认画质问题来自 flow、模型选择还是阈值组合。 + +改造后: + +- global transform 只作预对齐种子。 +- 图优化后的局部 flow 是最终 RAW 采样主几何。 +- 整帧拒绝直接使用图求解已经产生的有效边比例和残差,不额外拟合 registration summary。 +- MFSR 不再依赖单一 affine transform 生成所有亚像素采样坐标。 + +## 9. Lucas–Kanade 亚像素精修 + +图求解得到每帧每 tile 的一致 flow 后,在 reference/current proxy 上执行 LK: + +- 使用图 flow 作为初值。 +- 2~3 次 inverse compositional LK。 +- 计算结构矩阵最小特征值或 determinant。 +- 单次增量设物理上限;超限意味着初值或局部模型失败,不允许强行截断后继续当作高置信结果。 +- 低纹理区域保留图 flow,LK confidence 置低。 +- 输出 refined flow、LK confidence 和 residual。 + +现有 `flowSmoothPasses` 改为 edge-aware consistency filter: + +- 只用邻近高置信 flow 修复无效 tile。 +- 不对有效 motion boundary 做普通均值平滑。 +- flow discontinuity 保留给 certainty mask 判定遮挡边界。 + +## 10. Certainty / Robustness 模型 + +重写现有 `computeRobustness` 与 `computeTileMask`,合并为一套证据明确的 certainty pipeline。 + +### 10.1 Tile registration confidence + +```text +registrationConfidence = + peakMarginConfidence + * coverageConfidence + * graphResidualConfidence + * lkConditionConfidence + * lkResidualConfidence +``` + +### 10.2 像素光度 confidence + +对齐后比较 reference 与 current 的同 CFA/代理亮度邻域: + +```text +sigmaDiff² = variance(reference) + exposureScale² * variance(current) +photometricConfidence = exp( + -robustDistance² / (k * sigmaDiff²) +) +``` + +噪声模型使用现有 per-channel `RawNoiseModel`,并保留 lens-shading gain 对 shot/read noise 的影响。 + +### 10.3 Flow discontinuity 与遮挡 + +计算局部 flow 最大最小范围、相邻 divergence 和 forward/backward consistency。高不连续区域: + +- certainty 降低或清零。 +- 对 mask 做与结构方向相关的 1~2 像素扩张。 +- 禁止普通大半径 erosion 吞掉细小静态纹理。 + +### 10.4 最终权重 + +```text +certainty = + frameQualityWeight + * registrationConfidence + * photometricConfidence + * occlusionConfidence + * clippingConfidence +``` + +不保留固定 `nonReferenceFrameWeight = 0.92`。非参考帧权重必须由真实质量和传感器 precision 决定。 + +## 11. 结构张量与重建核 + +保留当前 `computeStructureTensor` 的总体方向,但按 ImageStackAlignator 语义整理: + +1. 只从最终 reference 生成结构张量。 +2. 使用轻微低通后的全分辨率或半分辨率亮度梯度。 +3. Gaussian 平滑 `Ix²`、`IxIy`、`Iy²`。 +4. 使用特征值、coherence 和主方向生成椭圆 Gaussian kernel。 +5. 平坦区域扩大核;边缘沿切线伸长、法线收缩;角点/点细节收缩核。 +6. 噪声水平只控制核宽度范围,不改变边缘方向。 + +结构核参数减少为可解释集合: + +- `gradientSigma` +- `tensorSigma` +- `detailThresholdLow/High` +- `kernelSigmaFlat` +- `kernelSigmaEdgeTangent` +- `kernelSigmaEdgeNormal` +- `kernelSigmaPoint` + +移除当前大量互相重叠的 structure、detail 和 denoise 补偿参数。 + +## 12. RAW MFNR 重建 + +### 12.1 采样模型 + +每个输出 Bayer 像素: + +1. 通过最终局部 flow 映射到当前帧 source coordinate。 +2. 在相同 CFA 通道样本中搜索 5×5 reconstruction footprint。 +3. 使用结构张量核计算空间权重。 +4. 使用 certainty、noise precision、曝光和 clipping 权重累计。 +5. 分别累计 `sum`、`weight`、`squareSum`、`nonReferenceWeight`。 + +```text +w = kernelWeight + * certainty + * inverseNoiseVariance + * exposureValidity + * cfaPhaseValidity +``` + +Reference 也通过同一重建核进入 accumulator,但 certainty 固定为 1。这样平坦区域可以利用 reference 邻域降噪,边缘区域由结构核保护,而不是把 reference 作为一个特殊的硬回退层。 + +### 12.2 Accumulator 内存 + +当前 ping-pong 全尺寸 `RGBA16F` accumulator 占用过高。因为每个 compute invocation 只读写唯一输出像素,可改为单 accumulator texture: + +- 每帧 dispatch 前后插入 image memory barrier。 +- 同一个 dispatch 内不跨像素读写 accumulator。 +- MFNR 使用两张原位更新的 `R32UI`,以 `packHalf2x16` 分别保存 + `value/weight` 与 `squareSum/clipMass`,不再分配 scratch ping-pong。 +- 不使用 `RGBA16F` read/write image;PMA110 驱动只接受该格式的 write-only image。 +- square sum 精度不足的设备改用可选 `R32F` 辅助纹理,不默认双倍全尺寸 ping-pong。 + +### 12.3 Normalize + +输出优先取 `sum / weight`。只有 weight 不足时才按 certainty 缓慢过渡到 reference reconstruction,禁止硬切 reference。 + +移除当前 normalize pass 中默认启用的大范围同 CFA 5×5 最终平滑。重建核和多帧 precision accumulation 已经承担主要降噪;额外 post smooth 容易制造塑料纹理并掩盖上游错误。 + +允许保留一个受严格约束的 residual Wiener: + +- 仅在有效帧权重不足且局部结构为平坦区域时工作。 +- 强度由实际 temporal variance 与 noise model 偏差驱动。 +- 默认最大混合量显著低于当前 `maxSmoothStrength`。 +- Debug 构建可抽样记录其使用量;生产路径不为此增加统计 pass。 + +## 13. RAW MFSR 重建 + +### 13.1 移除 green-only SR + +当前 MFSR 主要重建绿色 lattice,再使用 channel ratio 推导红蓝通道。这会把 demosaic/颜色相关假设带入 RAW super-resolution,并可能产生: + +- 红蓝细节缺失。 +- 彩色边缘错位。 +- 高频区域通道比例泄漏。 +- 输出 DNG 的 CFA 语义不纯。 + +重构后必须对 R、G1、G2、B 的真实 RAW 样本分别重建: + +- 每个输出 CFA phase 只收集输入中相同物理颜色/相位的样本。 +- 两个绿色可以共享噪声模型,但保留几何采样位置。 +- 不再生成 `superResolutionChannelRatioTexture`。 +- 不再用 base RGB/channel ratio 补造高分辨率红蓝细节。 + +### 13.2 Gather 重建 + +使用 gather 而非原子 splat: + +1. 每个高分辨率输出 Bayer 像素映射到 reference raw coordinate。 +2. 对每帧使用局部 flow 得到 source coordinate。 +3. 枚举相同 CFA phase 的邻近真实样本。 +4. 依据亚像素距离、结构核、certainty 和 noise precision 累加。 + +MFSR accumulator 只保留 normalize 真正消费的 `weightedValue` 与 `weight`,使用 +`R32UI + packHalf2x16` 原位更新。Reference 仍经过同一 CFA gather 核,但写入固定单位权重; +因此 `weight - 1` 精确表示非 reference detail support,不需要额外 coverage 通道或第二张 +accumulator。二阶矩继续由 native-resolution MFNR accumulator 负责,不在 2x lattice 重复保存。 + +### 13.3 Coverage 与降级 + +保留 MFSR 输出决策必需的 coverage,并重新定义为每个 CFA 通道的真实采样覆盖: + +- `effectiveWeight` +- `independentFrameCount` +- `subpixelPhaseSpread` +- `registrationConfidence` + +不使用单一 phase-bin 数量决定整帧参与与否。phase novelty 进入连续权重,不做过早 hard gate。 + +输出降级: + +- 高 coverage:使用 MFSR reconstruction。 +- 中 coverage:MFSR 与结构核控制的 native reconstruction 混合。 +- 低 coverage/运动区域:回退 reference/MFNR 的 CFA-aware upscale。 + +### 13.4 输出倍率 + +- 内部 lattice 使用 2x,保持亚像素定义清晰。 +- 用户 1.5x 输出在重建后按 CFA-aware resize 或 DNG/renderer 约定处理。 +- 2x 仅在原始分辨率、显存和 GPU tier 满足时启用。 +- 大像素 RAW 必须采用 output tiling,不能分配完整 2x accumulator。 + +当前实现使用 256 行 output stripe 和 accepted-frame 压缩缓存:每个参与 MFSR 的帧缓存 +`RGBA16F flow + R8 robustness + R16F tile mask`,不缓存完整 RAW GPU texture。重建每个 stripe +时根据最终 flow 的 Y 极值、输出倍率、CFA period 和 filter margin 计算 source row band,直接从 +仍持有的 Camera2 RAW plane buffer 上传该行段。所有 stripe 合计约上传一遍 RAW 加少量 halo, +不会为每个 stripe 重传整帧,也不会重跑对齐。 + +MFSR accumulator 固定为 `outputWidth × min(outputHeight, 256)` 的单张 `R32UI`,完成一个 stripe +后立即 normalize 到最终 `RG8` 输出 texture。全尺寸 1.5x/2x accumulator 已不再分配。 + +## 14. HDR 处理边界 + +HDR 的 normal 合成与短帧配准按 `1.23.1` 回退,并通过当前 packed accumulator 格式做等价适配; +高光覆盖与色度恢复按实际采样足迹闭合: + +1. 第一张 normal 是原生输出参考,其余 normal 使用局部 flow 对齐后累加。 +2. 短帧使用曝光归一化 proxy 和旧版整数全局平移搜索,不参与 normal accumulator。 +3. normal accumulator 除 clipping alpha 外,独立记录每个目标像素的 highlight influence;该 influence + 来自 3×3 重建核与双线性采样合并后的完整 4×4 同相位采样足迹,而不是只检查中心采样点。 +4. 初始 recovery mask 对 2×2 block 的四个 CFA 相位分别检查 reference 饱和风险与 accumulator + influence;任一相位受影响即要求色度恢复,四相位全部受影响才归为完全覆盖。 +5. 初始 mask 再按 HDR same-CFA 后滤波的真实 block 半径执行一次硬覆盖扩展;扩展 block 归为部分影响, + 不执行 feather 或连续权重混合。 +6. normal 的 LSC 校正值在映射到短帧输出曝光域之前不得 clamp;必须先乘目标曝光尺度,最后统一截断, + 避免未到 sensor white level 的相位提前丢失高光比例。 +7. 高光可靠上限固定保留 10% sensor headroom;任一相位达到 0.90 即切换到短帧色度来源。 +8. 每个 HDR 2×2 block 都强制满足共同亮度倍率的色度后置条件:安全 block 使用 normal reference + 四相位比例,受影响 block 使用短帧四相位比例。公共倍率来自 normal accumulator,短帧只负责色度来源。 +9. DNG `BaselineExposure` 和 PGTM 路径保持当前工程接口。 + +## 15. 应删除或替换的当前逻辑 + +### 15.1 删除 + +- 固定 `frames.first()` 为 reference。 +- 固定非参考帧权重。 +- 以 single global/affine registration transform 作为 RAW 主 warp。 +- 对 global transform 叠加被强行截断的 local residual 作为主要几何。 +- green-only MFSR accumulator。 +- `superResolutionChannelRatioTexture` 及其红蓝通道比例重建。 +- 默认强 final same-CFA smooth。 +- Gyro 数据不足时循环复用其他帧数据的任何方案。 +- 配准失败后以 identity 当作正常成功帧参与融合。 +- 仅用于统计的 `diagnosticAlignmentProgram`、`diagnosticFinalProgram`、全图 diagnostic SSBO 和对应 readback。 +- 仅用于 compact log、但重复执行 registration/global estimation 的路径。 +- 生产构建中的 flow/robustness/tile-mask 分布直方图和 debug-map 输出。 + +### 15.2 替换 + +- `computeRobustness + computeTileMask` 替换为统一 certainty pipeline。 +- registration 多层 gate 替换为 patch peak、graph residual、LK condition 和 photometric residual 的证据链。 +- 普通 flow averaging 替换为 edge-aware invalid-flow repair。 +- 单帧 `frame -> reference` 配准替换为稀疏时间图约束。 +- HDR short 独立 global-only 对齐替换为共享 global/local tracking。 + +### 15.3 保留 + +- Camera2 per-channel noise model。 +- lens shading 对噪声与 precision 的影响。 +- CFA-aware RAW normalization。 +- GPU 分行 dispatch 与 UI renderer 调度让步。 +- GL/内存完整释放和失败路径。 +- 算法内生的轻量 decision summary;不保留独立 diagnostics GPU 流水线。 +- MFSR coverage fallback,改为连续、逐通道证据。 +- PGTM/DNG 输出语义,适配新的 stack metadata。 + +## 16. 移动端性能与内存设计 + +### 16.1 不让所有 RAW 帧常驻 GPU + +仅保留: + +- reference RAW texture。 +- current RAW texture。 +- reference/current proxy pyramid。 +- 当前 edge 的 flow/certainty 工作纹理。 +- 每帧最终 flow seed/压缩 flow,按需上传或存 CPU。 +- accumulator 和输出 tile。 + +所有非 reference 帧按流式顺序 upload、处理、释放。 + +### 16.2 纹理格式 + +建议: + +| 数据 | 格式 | +| --- | --- | +| RAW input | `R16UI` | +| proxy | `R16F` | +| proxy pyramid | `R16F` | +| tile flow | `RG16F`,超大位移设备使用 `RG32F` | +| confidence/certainty | `R16F` | +| structure kernel | `RGBA16F` 或两个 `RG16F` | +| MFNR accumulator | 两张原位 `R32UI`,四个 half 保存完整统计量 | +| MFSR accumulator | 单张原位 `R32UI`,两个 half 保存 value/weight | +| global score | SSBO,小规模 | +| graph observations | SSBO/readback,小规模 | + +### 16.3 输出分块 + +MFNR 在高分辨率设备、MFSR 在所有设备上支持 output tile: + +- tile 推荐 512~1024 输出像素。 +- halo 至少覆盖最大 structure kernel、flow interpolation 和 CFA period。 +- 每个 tile 流式遍历 accepted frames。 +- tile 完成后直接写入最终 direct buffer。 +- tile 边界使用相同 reference coordinate,重叠区只保留中心有效区域,不做后期拼接补偿。 + +这使 MFSR accumulator 内存由整张 2x 图降低为一个 output tile。 + +### 16.4 性能档位 + +`RawStackPerformanceTier` 根据像素数、帧数、`ActivityManager.memoryClass`、GL 限制和基准测试选择: + +| 档位 | 典型策略 | +| --- | --- | +| HIGH | reference+adjacent+skip temporal graph,3 层 tracking,LK 3 次,允许 2x tiled MFSR | +| MEDIUM | reference+adjacent graph,3 层 tracking,LK 2 次,1.5x tiled MFSR | +| LOW | reference+adjacent graph,2 层 tracking,LK 1~2 次,只允许 MFNR | + +降级必须减少计算规模,不能改变正确性定义: + +- 减少 temporal graph 边。 +- 减少 pyramid 层和 LK 次数。 +- 降低 SR 输出倍率或关闭 SR。 +- 减少 accepted frame 数,但保留最高质量和时间覆盖。 + +禁止通过放宽配准/ghost 阈值换取速度。 + +### 16.5 热与时延预算 + +建议目标,以 12 MP、6~8 帧为基准: + +- 帧质量 proxy:100 ms 内。 +- 全局预对齐与 reference selection:150 ms 内。 +- 时间图 patch tracking:400 ms 内。 +- graph solve + LK:250 ms 内。 +- MFNR accumulate + normalize:700 ms 内。 +- 总 GPU stack:1.5~2.0 s 级,具体以设备 tier 校准。 + +每个长 compute pass 继续使用 row/tile dispatch 和 fence checkpoint,避免 GPU watchdog、UI 卡死和长时间独占。 + +### 16.6 生产可观测性预算 + +生产路径只保留以下标量,且全部复用算法中已经存在的数据: + +- accepted/rejected frame count 与逐帧 reject reason。 +- 参考帧索引和 reference cost。 +- temporal graph 有效边数、拒绝边数和最大 IRLS residual。 +- 每帧有效 tile 比例;在 graph observation CPU 数组上顺便累计。 +- MFNR/MFSR 最终有效权重是否达到输出门槛。 +- MFSR 是否降级及单一 fallback reason。 +- 每个主要 stage 的 CPU wall time;GPU 时间只在已有 fence 边界近似计算。 +- GL error、allocation failure 和性能 tier。 + +生产路径删除: + +- GPU 原子直方图。 +- 全图 percentile 统计。 +- 为统计创建的 accumulator/flow/certainty 镜像纹理。 +- 为诊断增加的 shader dispatch。 +- 常态化 PBO/SSBO 全图 readback。 +- 每帧输出 matrix、flow sample 或长 compact summary。 + +Debug 构建通过单一 `RawStackDebugCapture` 开关支持一次只抓取一种中间图。抓取时明确接受性能下降,不允许该代码改变生产 pass 顺序、uniform 或资源生命周期。 + +## 17. 文件与模块改造 + +### 17.1 新增 + +- `camera/BurstGyroRecorder.kt` +- `camera/GyroExposureWindow.kt` +- `processor/RawBurstFrame.kt` +- `processor/RawBurstPlanner.kt` +- `processor/RawFrameQualityAnalyzer.kt` +- `processor/RawGlobalPreAligner.kt` +- `processor/RawTemporalGraph.kt` +- `processor/RawTemporalGraphSolver.kt` +- `processor/RawStackPerformanceTier.kt` +- `processor/RawStackCertaintyModel.kt` + +### 17.2 重构 + +- `Camera2Controller.kt` + - burst 开始前启动 Gyro ring buffer。 + - 保存每帧完整 CaptureResult 元数据。 + - burst 完成后闭合每帧曝光窗口。 +- `CameraViewModel.kt` + - 不再只维护两个平行 ArrayList。 + - 组装 `RawBurstFrame`,调用 `RawBurstPlanner`。 +- `MultiFrameStacker.kt` + - 接收 `RawBurstPlan`。 + - 删除重新猜测 exposure/focus fallback 的逻辑。 +- `GlesRawStacker.kt` + - 拆分 orchestration 与 shader source。 + - 接收显式 reference、temporal graph 和 performance tier。 + - 按本方案重建 pass。 +- `RawStackTuningProfile.kt` + - 删除为补偿当前 gate 形成的重叠参数。 + - 参数按 proxy、global、patch、graph、LK、certainty、kernel、reconstruction 分组。 +- `RawStackDiagnostics.kt` + - 缩减为 `RawStackDecisionSummary`,只保存处理过程中已产生的标量结果和拒绝原因。 + +### 17.3 Shader 拆文件 + +当前 `GlesRawStacker.kt` 同时包含 Kotlin orchestration 和数千行 shader 字符串,难以验证 pass 边界。将 shader 移至 assets: + +- `assets/shaders/rawstack/proxy.comp` +- `assets/shaders/rawstack/downsample.comp` +- `assets/shaders/rawstack/global_search.comp` +- `assets/shaders/rawstack/patch_match.comp` +- `assets/shaders/rawstack/lk_refine.comp` +- `assets/shaders/rawstack/flow_consistency.comp` +- `assets/shaders/rawstack/certainty.comp` +- `assets/shaders/rawstack/structure_tensor.comp` +- `assets/shaders/rawstack/reconstruction_kernel.comp` +- `assets/shaders/rawstack/mfnr_accumulate.comp` +- `assets/shaders/rawstack/mfsr_accumulate.comp` +- `assets/shaders/rawstack/normalize.comp` + +公共 CFA、noise、LSC、warp 函数通过构建时 include/preprocess 组合,不复制多份略有差异的坐标逻辑。 + +## 18. 实施里程碑 + +### 里程碑 A:拍摄元数据与 Gyro 闭环 + +- 完成 `BurstGyroRecorder`。 +- `RawBurstFrame` 替换平行 images/results 列表。 +- 完成 timestamp、曝光窗口和 coverage 日志。 +- 完成 Gyro + RAW 低成本质量评分。 +- 暂不改变现有 stack 输出,只记录新 plan。 + +验收: + +- 每帧 Camera2/Gyro 对应关系可追踪。 +- 不出现 Gyro 窗口串帧和循环复用。 +- 静止、轻抖和明显抖动的评分排序符合实拍。 + +### 里程碑 B:全局预对齐与参考帧选择 + +- 实现小尺寸 proxy 和 DoG band。 +- 实现平移/旋转 coarse-to-fine search。 +- `RawBurstPlanner` 输出 reference 与处理顺序。 +- 现有 stack 可先使用新 reference 验证收益。 + +验收: + +- 参考帧不再固定第一张。 +- 参考帧选择降低整组最大位移和边缘裁切。 +- 明显模糊帧不被选为 reference。 + +### 里程碑 C:稀疏时间图与一致 flow + +- 实现 anchor、adjacent、skip edges。 +- patch matcher 输出 score/margin/coverage。 +- CPU IRLS graph solver。 +- graph residual 驱动 outlier rejection。 + +验收: + +- 闭环位移残差显著小于独立 reference tracking。 +- 远离 reference 的帧可通过相邻链路稳定求解。 +- 错误 edge 被拒绝而不是污染整帧 flow。 + +### 里程碑 D:LK 与 certainty 重写 + +- graph flow seed 进入 LK。 +- edge-aware invalid flow repair。 +- 合并 robustness/tile mask。 +- Debug 构建按需抓取 registration、photometric 或 occlusion certainty;生产构建不生成额外可视化资源。 + +验收: + +- 运动边缘无明显重影。 +- 平坦区域不会因无纹理产生随机 flow。 +- 整帧/整 tile 拒绝可由算法内生 reason code 定位,不依赖额外诊断 pass。 + +### 里程碑 E:MFNR 重建核与 accumulator + +- 结构张量参数语义整理。 +- 局部 flow 成为 RAW 主 warp。 +- 单 accumulator 或 tiled accumulator。 +- 移除固定 frame weight 和默认强 post smooth。 + +验收: + +- 静态区域达到理论帧数对应的噪声下降趋势。 +- 低 ISO 高频纹理不塑料化。 +- reference 与非 reference 坐标验证完全一致。 + +### 里程碑 F:全 CFA MFSR + +- 删除 green-only/channel-ratio 路径。 +- 对 R/G1/G2/B 分别 gather reconstruction。 +- CFA-channel coverage 和连续 fallback。 +- tiled 1.5x/2x 输出。 + +验收: + +- 彩色边缘不依赖绿色比例生成。 +- 高频彩色测试卡无通道错位和棋盘伪细节。 +- 低 coverage 区域平滑回退,无硬边界。 + +### 里程碑 G:HDR 共用对齐基础设施 + +- short frame 使用 global/local flow。 +- recovery certainty 与主 stack certainty 对齐。 +- HDR 失败与 normal MFNR 解耦。 + +验收: + +- 高光边缘无 global-only 对齐造成的局部错位。 +- short frame 不污染中暗部。 +- PGTM/DNG 语义保持正确。 + +### 里程碑 H:清理旧逻辑与调参收敛 + +- 删除废弃 shader、texture、gate 和 tuning 参数。 +- 更新轻量 decision summary、metadata 与 renderer denoise policy。 +- 完成多设备性能 tier。 +- 在删除旧路径前使用固定 RAW burst corpus 做 A/B。 + +验收: + +- 不存在新旧两套 warp/certainty 同时影响输出。 +- 代码中的每个 tuning 参数都对应明确公式或物理意义。 +- 输出差异优先通过算法内生标量解释;只有离线调试才抓取单项 debug map。 + +## 19. 验证体系 + +### 19.1 算法单元测试 + +- Gyro 窗口切片和积分。 +- timestamp 边界插值。 +- 参考帧 cost 选择。 +- temporal graph 矩阵构建。 +- 合成位移数据的 IRLS 求解和异常边剔除。 +- CFA phase 映射。 +- per-channel noise variance。 +- MFSR phase/coverage。 + +### 19.2 GPU 合成测试 + +建立固定 RAW burst corpus,至少包含: + +- 纯平移。 +- 小角度旋转。 +- affine/轻微透视。 +- rolling-shutter 摆动。 +- 前景运动和背景静止。 +- 遮挡出现/消失。 +- 低纹理墙面。 +- 高频织物与文字。 +- 单帧人为运动模糊。 +- hot pixel/暗场。 +- HDR 短曝高光。 + +为已知几何的合成数据记录: + +- global transform error。 +- tile flow endpoint error。 +- graph loop residual。 +- LK residual。 +- certainty AUC/错误接受率。 +- MFNR temporal noise reduction。 +- MFSR slanted-edge MTF 和假频能量。 + +### 19.3 实拍验收 + +每台代表设备覆盖: + +- ISO 100/400/1600/3200。 +- 1/1000、1/100、1/15、1/4 秒。 +- OIS 开/关可控时分别测试。 +- 静物手持、人物轻动、行走主体、树叶、水面。 +- 中心和边角高频纹理。 +- 点光源和高反差窗口。 +- 4/8/12 帧。 + +必须与以下输出盲测: + +- 最佳单帧。 +- 当前 GlesRawStacker。 +- 新 MFNR。 +- 新 MFSR。 + +### 19.4 性能指标 + +- 每个 pass GPU 时间。 +- 峰值 Java/native/GPU 内存估算。 +- GL allocation failure。 +- GPU fence 超时。 +- UI frame drop。 +- 设备温度与连续三次拍摄时延退化。 +- 降级原因和最终 tier。 + +## 20. 完成定义 + +重构完成必须同时满足: + +1. 拍摄端每帧拥有完整 Camera2 与 Gyro 曝光窗口元数据。 +2. Gyro 与图像质量共同参与筛帧,Gyro 不直接替代视觉对齐。 +3. Reference 由整组几何与质量 cost 选择,不固定第一张。 +4. Global translation/rotation 只作为局部 tracking 初值。 +5. 最终 RAW warp 来自时间图约束并经 LK 精修的局部 flow。 +6. 稀疏时间图能够检测并剔除错误 patch observation。 +7. Certainty 由明确的 registration、noise、photometric 和 occlusion 证据组成。 +8. MFNR 使用结构张量重建核,不依赖默认强 post smooth 获得干净观感。 +9. MFSR 对全部 CFA 通道使用真实 RAW 样本重建。 +10. HDR short frame 复用统一的全局/局部对齐基础设施。 +11. 12/24/48 MP 均有明确内存策略和性能降级,不以放宽质量阈值降级。 +12. 旧 global-primary warp、green-only SR、channel-ratio SR 和重叠 gate 被删除。 +13. 所有质量参数具有明确公式、单位或物理含义。 +14. 固定 corpus、单元测试、GPU 测试和真实设备测试全部通过。 +15. `./gradlew compileDefaultDebugKotlin` 与 `./gradlew buildCMakeDebug` 通过。 + +## 21. 推荐实施顺序 + +严格按以下依赖顺序实施: + +```text +帧元数据/Gyro +→ 质量评分 +→ 全局预对齐 +→ 参考帧选择 +→ 时间图 patch tracking +→ graph solve +→ LK +→ certainty +→ MFNR reconstruction +→ MFSR reconstruction +→ HDR +→ 旧路径清理 +``` + +不得先改最终平滑或继续增加融合阈值来补偿 reference、flow 或 certainty 的错误。每个里程碑先用固定 corpus、算法内生标量和按需离线抓图证明上游输出正确,再接入下一阶段。