feat: MFNR/MFSR optimize & hdr fusion fix

This commit is contained in:
Hinnka committed 2026-07-11 19:40:13 +08:00
1 parent ec5815e2df
commit f7d265b44a
32 files changed
+6075 -1281

No files matched your search

@@ -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<Any>(),
)
}
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))
}
}
}
+1
View File
@@ -14,6 +14,7 @@
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.HIGH_SAMPLING_RATE_SENSORS" />
<uses-feature
android:name="android.hardware.camera"
@@ -0,0 +1,92 @@
package com.hinnka.mycamera.camera
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import com.hinnka.mycamera.utils.PLog
import java.util.ArrayDeque
class BurstGyroRecorder(context: Context) {
private val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
private val sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED)
?: sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE)
private val samples = ArrayDeque<GyroSample>(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
}
}
@@ -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<String, CameraCharacteristics>()
private var cachedCharacteristics: CameraCharacteristics? = null
@@ -278,6 +279,7 @@ class Camera2Controller(private val context: Context) {
// 缓存 CaptureResult 和 Image 用于配对 (timestamp -> Data)
private val pendingResults = ConcurrentHashMap<Long, TotalCaptureResult>()
private val pendingImages = ConcurrentHashMap<Long, SafeImage>()
private val pendingFrameMetadata = ConcurrentHashMap<Long, CapturedFrameMetadata>()
private val pendingCaptureStartedTimestamps = ConcurrentHashMap<Long, Long>()
private val pendingCloseReaders = mutableListOf<ImageReader>()
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()
@@ -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?,
)
@@ -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<GyroSample>,
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<GyroSample>()
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<GyroSample>, 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
}
@@ -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<Double?> = emptyList(),
frameFocusDistances: List<Float?> = emptyList(),
rawStackFrames: List<RawStackFrame> = 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<Double?> = emptyList(),
frameFocusDistances: List<Float?> = emptyList(),
rawStackFrames: List<RawStackFrame> = 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,
)
}
File diff suppressed because it is too large. Load diff
@@ -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<SafeImage>,
frames: List<RawStackFrame>,
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<Double?> = emptyList(),
frameFocusDistances: List<Float?> = 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,
@@ -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<Pair<Int, Int>> {
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)
}
@@ -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<Float, Float> {
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,
)
@@ -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<RawStackFrame>): RawBurstGyroSelection {
return selectMetadata(
frames.map {
RawBurstGyroFrameSample(
sensorTimestampNs = it.sensorTimestampNs,
exposureTimeNs = it.exposureTimeNs,
gyroWindow = it.gyroWindow,
)
}
)
}
fun selectMetadata(frames: List<RawBurstGyroFrameSample>): 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<RawBurstGyroFrameSample>,
accepted: List<Int>,
risks: FloatArray,
reference: Int,
): IntArray {
val remainder = accepted
.asSequence()
.filter { it != reference }
.sortedWith(
compareBy<Int> { 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>): 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]
}
}
}
@@ -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<RawGlobalAlignment?>,
val preAlignmentsToReference: List<RawFramePreAlignment?>,
val referenceCost: Float,
)
object RawBurstReferencePlanner {
fun plan(
frames: List<RawStackFrame>,
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<RawAlignmentProxy?>,
gyroRisks: FloatArray = FloatArray(proxies.size) { Float.NaN },
sensorTimestampsNs: List<Long> = 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<RawGlobalAlignment?> = 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<RawGlobalAlignment?>(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<Int> { 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<RawAlignmentProxy?>,
gyroRisks: FloatArray,
valid: List<Int>,
): List<Int> {
val candidates = LinkedHashSet<Int>()
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<RawAlignmentProxy?>,
sensorTimestampsNs: List<Long>,
referenceIndex: Int,
directAlignments: List<RawGlobalAlignment?>,
directPreAlignments: List<RawFramePreAlignment?>,
): List<RawFramePreAlignment?>? {
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
}
@@ -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<Candidate>()
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
}
@@ -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
}
}
}
@@ -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,
)
@@ -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
}
@@ -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<RawTemporalAlignmentEdge>,
)
object RawTemporalAlignmentGraphBuilder {
fun build(
frames: List<RawStackFrame>,
referenceFrameIndex: Int = 0,
includeSkipOne: Boolean = true,
): RawTemporalAlignmentGraph = build(
sensorTimestampsNs = frames.map { it.sensorTimestampNs },
referenceFrameIndex = referenceFrameIndex,
includeSkipOne = includeSkipOne,
)
internal fun build(
sensorTimestampsNs: List<Long>,
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<Int> { sensorTimestampsNs[it] }.thenBy { it },
)
val edges = ArrayList<RawTemporalAlignmentEdge>()
val pairs = HashSet<EdgeKey>()
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<RawTemporalAlignmentEdge>,
pairs: MutableSet<EdgeKey>,
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
}
@@ -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<RawTemporalFramePosition>,
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<RawTemporalEdgeObservation>,
): 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<RawTemporalEdgeObservation>,
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<RawTemporalEdgeObservation>,
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<RawTemporalEdgeObservation>,
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<RawTemporalEdgeObservation>,
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<DoubleArray>, 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<RawTemporalEdgeObservation>,
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
}
@@ -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<RawTemporalEdgeFlowField>,
fallbackFlowByFrame: List<FloatArray>,
scoreFullConfidence: Float,
scoreReject: Float,
minimumObservationConfidence: Float = 0.02f,
): List<RawTemporalFrameFlowField>? {
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<RawTemporalEdgeObservation>(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<Float>()
val dy = ArrayList<Float>()
val residuals = ArrayList<Float>()
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<Float>, 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
}
@@ -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
@@ -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<SafeImage>()
private val stackingCaptureResults = mutableListOf<CaptureResult?>()
private val pendingRawStackFrames = mutableListOf<PendingRawStackFrame>()
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<SafeImage>,
frames: List<RawStackFrame>,
captureInfo: CaptureInfo,
characteristics: CameraCharacteristics?,
captureResult: CaptureResult?,
frameExposureProducts: List<Double?>,
frameFocusDistances: List<Float?>,
) {
try {
val images = frames.map { it.image }
PLog.d(TAG, "processStacking started - image size ${images.size}")
val context = getApplication<Application>()
@@ -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()
}
@@ -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 })
}
}
@@ -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,
)
},
)
}
}
@@ -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)
}
}
@@ -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
}
}
@@ -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<Float, Float>,
period: Int,
): List<SamplePosition> {
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)
}
@@ -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)
}
}
@@ -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)
}
}
@@ -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)
}
}