fix: mfnr & mfsr
This commit is contained in:
1 parent
b82e8ed2de
commit
4bfbca669a
12 files changed
+1121
-263
No files matched your search
@@ -5076,6 +5076,12 @@ class Camera2Controller(private val context: Context) {
|
||||
set(CaptureRequest.CONTROL_AWB_LOCK, true)
|
||||
}
|
||||
copyStillFocusSettingsFromPreview(this)
|
||||
applyMultiFrameCaptureConsistency(
|
||||
builder = this,
|
||||
state = currentState,
|
||||
baseResult = baseExposureResult,
|
||||
lockExposure = false,
|
||||
)
|
||||
PLog.d(TAG, "HDR bracket request[$index]: ev=$evOffset, manual=${manualBaseExposure != null}")
|
||||
}.build()
|
||||
}
|
||||
@@ -5301,6 +5307,76 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyMultiFrameCaptureConsistency(
|
||||
builder: CaptureRequest.Builder,
|
||||
state: CameraState,
|
||||
baseResult: CaptureResult?,
|
||||
lockExposure: Boolean,
|
||||
) {
|
||||
if (!state.useMFNR && !state.useMFSR) return
|
||||
|
||||
if (lockExposure) {
|
||||
builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF)
|
||||
val requestUsesManualExposure =
|
||||
builder.get(CaptureRequest.CONTROL_AE_MODE) == CaptureRequest.CONTROL_AE_MODE_OFF
|
||||
val requestIso = builder.get(CaptureRequest.SENSOR_SENSITIVITY)
|
||||
.takeIf { requestUsesManualExposure }
|
||||
val requestExposure = builder.get(CaptureRequest.SENSOR_EXPOSURE_TIME)
|
||||
.takeIf { requestUsesManualExposure }
|
||||
val lockedIso = requestIso ?: baseResult?.get(CaptureResult.SENSOR_SENSITIVITY)
|
||||
val lockedExposure = requestExposure ?: baseResult?.get(CaptureResult.SENSOR_EXPOSURE_TIME)
|
||||
val canUseManualExposure = isManualSensorSupported &&
|
||||
availableAeModes.contains(CaptureRequest.CONTROL_AE_MODE_OFF) &&
|
||||
lockedIso != null && lockedIso > 0 &&
|
||||
lockedExposure != null && lockedExposure > 0L
|
||||
if (canUseManualExposure) {
|
||||
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF)
|
||||
builder.set(CaptureRequest.SENSOR_SENSITIVITY, lockedIso)
|
||||
builder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, lockedExposure)
|
||||
} else {
|
||||
val aeLockAvailable = getActiveOpenCameraCharacteristics()
|
||||
?.get(CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE) == true
|
||||
if (availableAeModes.contains(CaptureRequest.CONTROL_AE_MODE_ON)) {
|
||||
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
|
||||
}
|
||||
if (aeLockAvailable) {
|
||||
builder.set(CaptureRequest.CONTROL_AE_LOCK, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val awbLockAvailable = getActiveOpenCameraCharacteristics()
|
||||
?.get(CameraCharacteristics.CONTROL_AWB_LOCK_AVAILABLE) == true
|
||||
if (state.awbMode != CameraMetadata.CONTROL_AWB_MODE_OFF && awbLockAvailable) {
|
||||
builder.set(CaptureRequest.CONTROL_AWB_LOCK, true)
|
||||
}
|
||||
|
||||
val lockedFocusDistance = baseResult?.get(CaptureResult.LENS_FOCUS_DISTANCE)
|
||||
?: builder.get(CaptureRequest.LENS_FOCUS_DISTANCE)
|
||||
when {
|
||||
availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_OFF) && lockedFocusDistance != null -> {
|
||||
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE)
|
||||
builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF)
|
||||
builder.set(CaptureRequest.LENS_FOCUS_DISTANCE, lockedFocusDistance)
|
||||
}
|
||||
|
||||
availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_AUTO) -> {
|
||||
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE)
|
||||
builder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO)
|
||||
}
|
||||
}
|
||||
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Multi-frame capture locked exposure=$lockExposure " +
|
||||
"ae=${builder.get(CaptureRequest.CONTROL_AE_MODE)} " +
|
||||
"iso=${builder.get(CaptureRequest.SENSOR_SENSITIVITY)} " +
|
||||
"shutter=${builder.get(CaptureRequest.SENSOR_EXPOSURE_TIME)} " +
|
||||
"af=${builder.get(CaptureRequest.CONTROL_AF_MODE)} " +
|
||||
"focus=${builder.get(CaptureRequest.LENS_FOCUS_DISTANCE)}"
|
||||
)
|
||||
}
|
||||
|
||||
private fun shouldUseDefaultHdrBracketCapture(state: CameraState, isRawCapture: Boolean): Boolean {
|
||||
return state.captureMode == CaptureMode.PHOTO &&
|
||||
state.useHdrComposition &&
|
||||
@@ -5401,6 +5477,13 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
applyMultiFrameCaptureConsistency(
|
||||
builder = this,
|
||||
state = currentState,
|
||||
baseResult = baseExposureResult,
|
||||
lockExposure = true,
|
||||
)
|
||||
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Capture request built and ready to send. ISO: ${_state.value.iso}, shutter: ${_state.value.shutterSpeed}, AE: ${_state.value.isAutoExposure}"
|
||||
|
||||
@@ -2618,7 +2618,9 @@ object GalleryManager {
|
||||
useGpuAcceleration: Boolean = true,
|
||||
exposureBias: Float? = null,
|
||||
exportDngWithRawExport: Boolean = false,
|
||||
capturePreviewThumbnail: Bitmap? = null
|
||||
capturePreviewThumbnail: Bitmap? = null,
|
||||
frameExposureProducts: List<Double?> = emptyList(),
|
||||
frameFocusDistances: List<Float?> = emptyList(),
|
||||
) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoDir = getPhotoDir(context, photoId, true)
|
||||
@@ -2690,6 +2692,8 @@ object GalleryManager {
|
||||
lensShadingWidth = rawMetadata.lensShadingMapWidth,
|
||||
lensShadingHeight = rawMetadata.lensShadingMapHeight,
|
||||
applyLensShadingCorrection = applyRawLensShading,
|
||||
frameExposureProducts = frameExposureProducts,
|
||||
frameFocusDistances = frameFocusDistances,
|
||||
)
|
||||
|
||||
val finalStackResult = rawStackResult ?: return@withContext
|
||||
@@ -2889,7 +2893,7 @@ object GalleryManager {
|
||||
useGpuAcceleration: Boolean = true,
|
||||
exposureBias: Float? = null,
|
||||
exportDngWithRawExport: Boolean = false,
|
||||
capturePreviewThumbnail: Bitmap? = null
|
||||
capturePreviewThumbnail: Bitmap? = null,
|
||||
): Boolean = withContext(Dispatchers.IO) {
|
||||
var rawHdrStackResult: RawStackResult? = null
|
||||
val imagesToClose = images.toMutableSet()
|
||||
@@ -3464,7 +3468,9 @@ object GalleryManager {
|
||||
useGpuAcceleration: Boolean = true,
|
||||
exposureBias: Float? = null,
|
||||
exportDngWithRawExport: Boolean = false,
|
||||
capturePreviewThumbnail: Bitmap? = null
|
||||
capturePreviewThumbnail: Bitmap? = null,
|
||||
frameExposureProducts: List<Double?> = emptyList(),
|
||||
frameFocusDistances: List<Float?> = emptyList(),
|
||||
) = withContext(Dispatchers.IO) {
|
||||
when (val format = images[0].format) {
|
||||
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
|
||||
@@ -3506,7 +3512,9 @@ object GalleryManager {
|
||||
useGpuAcceleration,
|
||||
exposureBias,
|
||||
exportDngWithRawExport,
|
||||
capturePreviewThumbnail
|
||||
capturePreviewThumbnail,
|
||||
frameExposureProducts,
|
||||
frameFocusDistances,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ object GlesGpuScheduler {
|
||||
private const val EGL_IMG_CONTEXT_PRIORITY = "EGL_IMG_context_priority"
|
||||
private const val GPU_CHECKPOINT_WAIT_NS = 1_000_000L
|
||||
private const val GPU_CHECKPOINT_SLEEP_MS = 1L
|
||||
private const val GPU_UI_BREATHING_ROOM_MS = 2L
|
||||
|
||||
fun createBackgroundContext(display: EGLDisplay, config: EGLConfig, tag: String): EGLContext {
|
||||
if (supportsLowPriorityContext(display)) {
|
||||
@@ -123,7 +124,11 @@ object GlesGpuScheduler {
|
||||
PLog.w(tag, "Failed to wait for GLES background checkpoint $label", e)
|
||||
} finally {
|
||||
GLES30.glDeleteSync(sync)
|
||||
Thread.yield()
|
||||
try {
|
||||
Thread.sleep(GPU_UI_BREATHING_ROOM_MS)
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -30,6 +30,12 @@ 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,
|
||||
@@ -299,6 +305,8 @@ object MultiFrameStacker {
|
||||
lensShadingWidth: Int = 0,
|
||||
lensShadingHeight: Int = 0,
|
||||
applyLensShadingCorrection: Boolean = true,
|
||||
frameExposureProducts: List<Double?> = emptyList(),
|
||||
frameFocusDistances: List<Float?> = emptyList(),
|
||||
): RawStackResult? {
|
||||
val width = images[0].width
|
||||
val height = images[0].height
|
||||
@@ -325,6 +333,22 @@ 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,
|
||||
@@ -338,7 +362,7 @@ object MultiFrameStacker {
|
||||
lensShadingHeight = if (stackLensShading != null) lensShadingHeight else 0,
|
||||
tuning = tuning,
|
||||
debugConfig = RawStackRuntimeDebug.debugConfig,
|
||||
).process(images)
|
||||
).processFrames(frames)
|
||||
}
|
||||
|
||||
RawStackRuntimeDebug.i(TAG) { "Using CPU RAW stacker" }
|
||||
|
||||
@@ -38,6 +38,9 @@ data class RawStackDiagnostics(
|
||||
val superResolutionFallbackReason: String? = null,
|
||||
val superResolutionDetailFrameCount: Int = 0,
|
||||
val superResolutionDetailWeightSum: Float = Float.NaN,
|
||||
val superResolutionPhaseBinCount: Int = 0,
|
||||
val superResolutionPhaseBinTotal: Int = 0,
|
||||
val superResolutionPhaseBinSamples: List<Int> = emptyList(),
|
||||
val flowMagnitudePx: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val alignmentResidual: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val noiseNormalizedResidual: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
@@ -45,6 +48,7 @@ data class RawStackDiagnostics(
|
||||
val robustness: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val tileMask: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val accumulatorWeight: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val superResolutionSupport: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val postfilterResidual: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val postfilterSmooth: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
val postfilterEffectiveSmooth: RawStackMetricDistribution = RawStackMetricDistribution.Empty,
|
||||
@@ -65,7 +69,9 @@ data class RawStackDiagnostics(
|
||||
val registrationQualitySummary = registrationQuality?.compactSummary()?.let { "$it " }.orEmpty()
|
||||
val superResolutionSummary = superResolutionOutputMode?.let { mode ->
|
||||
"srOut=$mode srReason=${superResolutionFallbackReason ?: "ok"} " +
|
||||
"srFrames=$superResolutionDetailFrameCount srWeight=${superResolutionDetailWeightSum.fmt()} "
|
||||
"srFrames=$superResolutionDetailFrameCount srWeight=${superResolutionDetailWeightSum.fmt()} " +
|
||||
"srPhase=$superResolutionPhaseBinCount/$superResolutionPhaseBinTotal " +
|
||||
"srPhaseDist=${superResolutionPhaseBinSamples.joinToString(prefix = "[", postfix = "]")} "
|
||||
}.orEmpty()
|
||||
return "HWMF diag mode=$mode frames=$frameCount aligned=$alignedFrameCount " +
|
||||
"size=${width}x$height step=$sampleStep " +
|
||||
@@ -81,6 +87,9 @@ data class RawStackDiagnostics(
|
||||
"hiConf=${highConfidenceTileRatio.percent()} srAlign=${srAlignmentReadyRatio.percent()} " +
|
||||
"srDetail=${srDetailReadyRatio.percent()} " +
|
||||
"weightMean=${accumulatorWeight.mean.fmt()} weightP10=${accumulatorWeight.p10.fmt()} " +
|
||||
"srSupportP10=${superResolutionSupport.p10.fmt()} " +
|
||||
"srSupportP50=${superResolutionSupport.p50.fmt()} " +
|
||||
"srSupportP90=${superResolutionSupport.p90.fmt()} " +
|
||||
"postResP50=${postfilterResidual.p50.fmt()} postResP90=${postfilterResidual.p90.fmt()} " +
|
||||
"postSmoothMean=${postfilterSmooth.mean.fmt()} postSmoothP90=${postfilterSmooth.p90.fmt()} " +
|
||||
"postEffMean=${postfilterEffectiveSmooth.mean.fmt()} postEffP90=${postfilterEffectiveSmooth.p90.fmt()} " +
|
||||
|
||||
+117
-3
@@ -49,6 +49,9 @@ data class RawStackRegistrationEstimate(
|
||||
val globalSecondScore: Float = Float.NaN,
|
||||
val globalScoreMargin: Float = Float.NaN,
|
||||
val globalCoverage: Float = Float.NaN,
|
||||
val globalDiscreteDxRaw: Float = Float.NaN,
|
||||
val globalDiscreteDyRaw: Float = Float.NaN,
|
||||
val globalSubpixelRefined: Boolean = false,
|
||||
) {
|
||||
val confidence: Int
|
||||
get() = transform.confidence
|
||||
@@ -58,6 +61,12 @@ data class RawStackRegistrationEstimate(
|
||||
}
|
||||
|
||||
object RawStackFrameRegistrationEstimator {
|
||||
private data class RefinedGlobalTranslation(
|
||||
val dxRaw: Float,
|
||||
val dyRaw: Float,
|
||||
val refined: Boolean,
|
||||
)
|
||||
|
||||
fun estimateGlobalTranslation(
|
||||
setup: RawStackRegistrationSetup,
|
||||
candidates: List<RawStackGlobalRegistrationCandidate>,
|
||||
@@ -82,7 +91,7 @@ object RawStackFrameRegistrationEstimator {
|
||||
}
|
||||
|
||||
val best = sortedCandidates.first()
|
||||
val second = sortedCandidates.drop(1).firstOrNull()
|
||||
val second = secondDistinctGlobalBasin(best, sortedCandidates)
|
||||
val secondScore = second?.score ?: Float.NaN
|
||||
val margin = if (secondScore.isFinite()) {
|
||||
((secondScore - best.score) / max(best.score, GLOBAL_SCORE_EPSILON)).coerceAtLeast(0f)
|
||||
@@ -95,6 +104,7 @@ object RawStackFrameRegistrationEstimator {
|
||||
scoreMargin = margin,
|
||||
coverage = best.coverage,
|
||||
)
|
||||
val refinedTranslation = refineGlobalTranslation(best, sortedCandidates)
|
||||
val fittedTransform = RawStackPerspectiveTransform.fromSingleMatrix(
|
||||
stage = stage,
|
||||
transformDefinedOnWidth = setup.sourceWidth,
|
||||
@@ -102,8 +112,8 @@ object RawStackFrameRegistrationEstimator {
|
||||
geometryColumns = setup.cvpPerspectiveGeometryColumns,
|
||||
geometryRows = setup.cvpPerspectiveGeometryRows,
|
||||
rowMajorMatrix = floatArrayOf(
|
||||
1f, 0f, best.dxRaw,
|
||||
0f, 1f, best.dyRaw,
|
||||
1f, 0f, refinedTranslation.dxRaw,
|
||||
0f, 1f, refinedTranslation.dyRaw,
|
||||
0f, 0f, 1f,
|
||||
),
|
||||
rawConfidence = rawConfidence,
|
||||
@@ -136,9 +146,109 @@ object RawStackFrameRegistrationEstimator {
|
||||
globalSecondScore = secondScore,
|
||||
globalScoreMargin = margin,
|
||||
globalCoverage = best.coverage,
|
||||
globalDiscreteDxRaw = best.dxRaw,
|
||||
globalDiscreteDyRaw = best.dyRaw,
|
||||
globalSubpixelRefined = refinedTranslation.refined,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Refines the discrete minimum with the gradient and Hessian of the local
|
||||
* 3x3 score surface. The full 2D fit retains the xy term, which matters for
|
||||
* diagonal structure and avoids independently biasing the two axes.
|
||||
*/
|
||||
private fun refineGlobalTranslation(
|
||||
best: RawStackGlobalRegistrationCandidate,
|
||||
candidates: List<RawStackGlobalRegistrationCandidate>,
|
||||
): RefinedGlobalTranslation {
|
||||
val stepX = minimumPositiveStep(candidates.map { it.dxRaw })
|
||||
?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val stepY = minimumPositiveStep(candidates.map { it.dyRaw })
|
||||
?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val toleranceX = max(stepX * 0.05f, GLOBAL_COORDINATE_EPSILON)
|
||||
val toleranceY = max(stepY * 0.05f, GLOBAL_COORDINATE_EPSILON)
|
||||
|
||||
fun scoreAt(x: Int, y: Int): Float? {
|
||||
val targetX = best.dxRaw + x * stepX
|
||||
val targetY = best.dyRaw + y * stepY
|
||||
return candidates.firstOrNull {
|
||||
kotlin.math.abs(it.dxRaw - targetX) <= toleranceX &&
|
||||
kotlin.math.abs(it.dyRaw - targetY) <= toleranceY
|
||||
}?.score
|
||||
}
|
||||
|
||||
val left = scoreAt(-1, 0) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val right = scoreAt(1, 0) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val up = scoreAt(0, -1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val down = scoreAt(0, 1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val upLeft = scoreAt(-1, -1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val upRight = scoreAt(1, -1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val downLeft = scoreAt(-1, 1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
val downRight = scoreAt(1, 1) ?: return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
|
||||
val gradientX = 0.5f * (right - left)
|
||||
val gradientY = 0.5f * (down - up)
|
||||
val hessianXX = left - 2f * best.score + right
|
||||
val hessianYY = up - 2f * best.score + down
|
||||
val hessianXY = 0.25f * (downRight - downLeft - upRight + upLeft)
|
||||
val determinant = hessianXX * hessianYY - hessianXY * hessianXY
|
||||
if (!determinant.isFinite() ||
|
||||
hessianXX <= GLOBAL_CURVATURE_EPSILON ||
|
||||
hessianYY <= GLOBAL_CURVATURE_EPSILON ||
|
||||
determinant <= GLOBAL_CURVATURE_EPSILON
|
||||
) {
|
||||
return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
}
|
||||
|
||||
val offsetX = (-hessianYY * gradientX + hessianXY * gradientY) / determinant
|
||||
val offsetY = (hessianXY * gradientX - hessianXX * gradientY) / determinant
|
||||
if (!offsetX.isFinite() || !offsetY.isFinite() ||
|
||||
kotlin.math.abs(offsetX) > GLOBAL_SUBPIXEL_OFFSET_LIMIT ||
|
||||
kotlin.math.abs(offsetY) > GLOBAL_SUBPIXEL_OFFSET_LIMIT
|
||||
) {
|
||||
return RefinedGlobalTranslation(best.dxRaw, best.dyRaw, false)
|
||||
}
|
||||
return RefinedGlobalTranslation(
|
||||
dxRaw = best.dxRaw + offsetX * stepX,
|
||||
dyRaw = best.dyRaw + offsetY * stepY,
|
||||
refined = true,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjacent scores belong to the same quadratic peak and naturally become
|
||||
* nearly equal when the true minimum lies between grid points. Ambiguity
|
||||
* must therefore be measured against the next basin, not the next sample
|
||||
* in the same 3x3 neighborhood.
|
||||
*/
|
||||
private fun secondDistinctGlobalBasin(
|
||||
best: RawStackGlobalRegistrationCandidate,
|
||||
candidates: List<RawStackGlobalRegistrationCandidate>,
|
||||
): RawStackGlobalRegistrationCandidate? {
|
||||
val stepX = minimumPositiveStep(candidates.map { it.dxRaw })
|
||||
?: return candidates.firstOrNull { it !== best }
|
||||
val stepY = minimumPositiveStep(candidates.map { it.dyRaw })
|
||||
?: return candidates.firstOrNull { it !== best }
|
||||
val localRadiusX = stepX * GLOBAL_LOCAL_BASIN_RADIUS
|
||||
val localRadiusY = stepY * GLOBAL_LOCAL_BASIN_RADIUS
|
||||
return candidates.firstOrNull { candidate ->
|
||||
candidate !== best && (
|
||||
kotlin.math.abs(candidate.dxRaw - best.dxRaw) > localRadiusX ||
|
||||
kotlin.math.abs(candidate.dyRaw - best.dyRaw) > localRadiusY
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun minimumPositiveStep(values: List<Float>): Float? {
|
||||
val sorted = values.filter { it.isFinite() }.distinct().sorted()
|
||||
var minimum = Float.POSITIVE_INFINITY
|
||||
for (index in 1 until sorted.size) {
|
||||
val delta = sorted[index] - sorted[index - 1]
|
||||
if (delta > GLOBAL_COORDINATE_EPSILON) minimum = minOf(minimum, delta)
|
||||
}
|
||||
return minimum.takeIf { it.isFinite() }
|
||||
}
|
||||
|
||||
fun estimate(
|
||||
setup: RawStackRegistrationSetup,
|
||||
samples: List<RawStackRegistrationSample>,
|
||||
@@ -415,4 +525,8 @@ object RawStackFrameRegistrationEstimator {
|
||||
private const val GLOBAL_SCORE_QUALITY_SCALE = 0.035f
|
||||
private const val GLOBAL_MARGIN_FULL_CONFIDENCE = 0.05f
|
||||
private const val GLOBAL_MARGIN_FLOOR = 0.70f
|
||||
private const val GLOBAL_COORDINATE_EPSILON = 1e-4f
|
||||
private const val GLOBAL_CURVATURE_EPSILON = 1e-7f
|
||||
private const val GLOBAL_SUBPIXEL_OFFSET_LIMIT = 0.75f
|
||||
private const val GLOBAL_LOCAL_BASIN_RADIUS = 1.05f
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.sqrt
|
||||
|
||||
/**
|
||||
* Tracks whether accepted frames add distinct sampling phases on the same-color
|
||||
* CFA lattice. Registration quality alone cannot tell whether a frame contributes
|
||||
* new samples to a 2x reconstruction.
|
||||
*/
|
||||
internal class RawStackSuperResolutionPhaseTracker(
|
||||
cfaPeriod: Int,
|
||||
outputScale: Float,
|
||||
private val noveltyStartPx: Float,
|
||||
private val noveltyFullPx: Float,
|
||||
) {
|
||||
private data class Phase(val x: Float, val y: Float)
|
||||
|
||||
private val period = cfaPeriod.coerceAtLeast(1).toFloat()
|
||||
private val binsPerAxis = outputScale.toInt().coerceAtLeast(1)
|
||||
private val binSpacing = period / binsPerAxis.toFloat()
|
||||
private val phases = ArrayList<Phase>()
|
||||
private val binCounts = IntArray(binsPerAxis * binsPerAxis)
|
||||
|
||||
init {
|
||||
reset()
|
||||
}
|
||||
|
||||
fun reset() {
|
||||
phases.clear()
|
||||
binCounts.fill(0)
|
||||
record(0f, 0f)
|
||||
}
|
||||
|
||||
fun noveltyWeight(dx: Float, dy: Float): Float {
|
||||
if (!dx.isFinite() || !dy.isFinite()) return 0f
|
||||
val phase = Phase(wrap(dx), wrap(dy))
|
||||
val nearestDistance = phases.minOfOrNull { existing -> phaseDistance(phase, existing) }
|
||||
?: Float.POSITIVE_INFINITY
|
||||
return smoothStep(noveltyStartPx, noveltyFullPx, nearestDistance)
|
||||
}
|
||||
|
||||
fun record(dx: Float, dy: Float) {
|
||||
if (!dx.isFinite() || !dy.isFinite()) return
|
||||
val phase = Phase(wrap(dx), wrap(dy))
|
||||
phases += phase
|
||||
binCounts[binIndex(phase)] += 1
|
||||
}
|
||||
|
||||
fun isUnoccupiedBin(dx: Float, dy: Float): Boolean {
|
||||
if (!dx.isFinite() || !dy.isFinite()) return false
|
||||
val phase = Phase(wrap(dx), wrap(dy))
|
||||
return binCounts[binIndex(phase)] == 0
|
||||
}
|
||||
|
||||
val occupiedBinCount: Int
|
||||
get() = binCounts.count { it > 0 }
|
||||
|
||||
val totalBinCount: Int
|
||||
get() = binCounts.size
|
||||
|
||||
val phaseBinCounts: List<Int>
|
||||
get() = binCounts.toList()
|
||||
|
||||
val coverage: Float
|
||||
get() = occupiedBinCount.toFloat() / totalBinCount.coerceAtLeast(1).toFloat()
|
||||
|
||||
private fun binIndex(phase: Phase): Int {
|
||||
val x = (floor(phase.x / binSpacing + 0.5f).toInt() % binsPerAxis + binsPerAxis) % binsPerAxis
|
||||
val y = (floor(phase.y / binSpacing + 0.5f).toInt() % binsPerAxis + binsPerAxis) % binsPerAxis
|
||||
return y * binsPerAxis + x
|
||||
}
|
||||
|
||||
private fun phaseDistance(a: Phase, b: Phase): Float {
|
||||
val dx = toroidalDistance(a.x, b.x)
|
||||
val dy = toroidalDistance(a.y, b.y)
|
||||
return sqrt(dx * dx + dy * dy)
|
||||
}
|
||||
|
||||
private fun toroidalDistance(a: Float, b: Float): Float {
|
||||
val direct = kotlin.math.abs(a - b)
|
||||
return minOf(direct, period - direct)
|
||||
}
|
||||
|
||||
private fun wrap(value: Float): Float {
|
||||
val remainder = value % period
|
||||
return if (remainder < 0f) remainder + period else remainder
|
||||
}
|
||||
|
||||
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
|
||||
val lo = minOf(edge0, edge1).coerceAtLeast(0f)
|
||||
val hi = maxOf(edge0, edge1).coerceAtLeast(lo)
|
||||
if (hi <= lo) return if (value >= hi) 1f else 0f
|
||||
val t = ((value - lo) / (hi - lo)).coerceIn(0f, 1f)
|
||||
return t * t * (3f - 2f * t)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -38,6 +38,7 @@ data class RawStackPrefilterTuning(
|
||||
data class RawStackBlendTuning(
|
||||
val lkRefinePasses: Int = 2,
|
||||
val flowSmoothPasses: Int = 2,
|
||||
val focusDistanceRejectDeltaDiopters: Float = 0.12f,
|
||||
val flowOutlierThresholdPx: Float = 12.0f,
|
||||
val flowOutlierWeight: Float = 0.15f,
|
||||
val nonReferenceFrameWeight: Float = 0.92f,
|
||||
@@ -147,13 +148,19 @@ data class RawStackHdrTuning(
|
||||
data class RawStackSuperResolutionTuning(
|
||||
val internalScale: Float = 2.0f,
|
||||
val outputScale: Float = 1.5f,
|
||||
val splatRadius: Float = 0.65f,
|
||||
val greenFootprintSigmaRawPx: Float = 0.65f,
|
||||
val phaseNoveltyStartPx: Float = 0.10f,
|
||||
val phaseNoveltyFullPx: Float = 0.45f,
|
||||
val accumulationMinPhaseWeight: Float = 0.10f,
|
||||
val minEffectiveWeight: Float = 0.35f,
|
||||
val holeFillPasses: Int = 2,
|
||||
val detailRestoreStrength: Float = 0.90f,
|
||||
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,
|
||||
val fallbackMinPhaseBins: Int = 3,
|
||||
val registrationConfidenceStart: Int = 100,
|
||||
val registrationConfidenceFull: Int = 170,
|
||||
val registrationMarginStart: Float = 0.012f,
|
||||
@@ -169,6 +176,6 @@ data class RawStackSuperResolutionTuning(
|
||||
val registrationSeedDistanceEndPx: Float = 1.50f,
|
||||
val registrationConsistencyDistanceStartPx: Float = 1.25f,
|
||||
val registrationConsistencyDistanceEndPx: Float = 2.50f,
|
||||
val detailLowLightSuppression: Float = 0.45f,
|
||||
val detailLscSuppression: Float = 0.35f,
|
||||
val greenReconstructionLowLightSuppression: Float = 0.45f,
|
||||
val greenReconstructionLscSuppression: Float = 0.35f,
|
||||
)
|
||||
@@ -1369,6 +1369,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
private var hasAppliedDefaultFocalLength = false
|
||||
|
||||
private val stackingImages = mutableListOf<SafeImage>()
|
||||
private val stackingCaptureResults = mutableListOf<CaptureResult?>()
|
||||
private var multipleExposureMetadata: MediaMetadata? = null
|
||||
var multipleExposureState by mutableStateOf(MultipleExposureSessionState())
|
||||
private set
|
||||
@@ -1417,11 +1418,30 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
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 imagesToProcess = stackingImages.toList()
|
||||
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()
|
||||
viewModelScope.launch {
|
||||
processStacking(imagesToProcess, captureInfo, characteristics, captureResult)
|
||||
processStacking(
|
||||
images = imagesToProcess,
|
||||
captureInfo = captureInfo,
|
||||
characteristics = characteristics,
|
||||
captureResult = referenceCaptureResult,
|
||||
frameExposureProducts = exposureProducts,
|
||||
frameFocusDistances = focusDistances,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -1457,6 +1477,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
it.close()
|
||||
}
|
||||
stackingImages.clear()
|
||||
stackingCaptureResults.clear()
|
||||
burstImages.forEach {
|
||||
it.close()
|
||||
}
|
||||
@@ -2523,6 +2544,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
} else {
|
||||
generateThumbnail()
|
||||
stackingImages.clear()
|
||||
stackingCaptureResults.clear()
|
||||
|
||||
if (useLivePhoto.value) {
|
||||
cameraController.setCapturingLivePhoto(true)
|
||||
@@ -4995,7 +5017,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
images: List<SafeImage>,
|
||||
captureInfo: CaptureInfo,
|
||||
characteristics: CameraCharacteristics?,
|
||||
captureResult: CaptureResult?
|
||||
captureResult: CaptureResult?,
|
||||
frameExposureProducts: List<Double?>,
|
||||
frameFocusDistances: List<Float?>,
|
||||
) {
|
||||
try {
|
||||
PLog.d(TAG, "processStacking started - image size ${images.size}")
|
||||
@@ -5179,7 +5203,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
useGpuAcceleration = useGpuAcceleration.value,
|
||||
exposureBias = state.value.exposureBias,
|
||||
exportDngWithRawExport = exportDngWithRawExport.value,
|
||||
capturePreviewThumbnail = previewThumbnail
|
||||
capturePreviewThumbnail = previewThumbnail,
|
||||
frameExposureProducts = frameExposureProducts,
|
||||
frameFocusDistances = frameFocusDistances,
|
||||
)
|
||||
}
|
||||
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
|
||||
@@ -5825,6 +5851,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
it.close()
|
||||
}
|
||||
stackingImages.clear()
|
||||
stackingCaptureResults.clear()
|
||||
burstImages.forEach {
|
||||
it.close()
|
||||
}
|
||||
|
||||
+45
@@ -6,6 +6,51 @@ import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RawStackFrameRegistrationEstimatorTest {
|
||||
@Test
|
||||
fun refinesGlobalTranslationFromTwoDimensionalScoreSurface() {
|
||||
val setup = RawStackRegistrationResolver.resolve(4096, 3072)
|
||||
val centerX = 8f
|
||||
val centerY = -4f
|
||||
val expectedOffsetX = 0.30f
|
||||
val expectedOffsetY = -0.25f
|
||||
val candidates = buildList {
|
||||
for (gridY in -1..1) {
|
||||
for (gridX in -1..1) {
|
||||
val x = gridX - expectedOffsetX
|
||||
val y = gridY - expectedOffsetY
|
||||
val score = 0.010f + 0.030f * (x * x + 1.2f * y * y + 0.2f * x * y)
|
||||
add(
|
||||
RawStackGlobalRegistrationCandidate(
|
||||
dxRaw = centerX + gridX * 2f,
|
||||
dyRaw = centerY + gridY * 2f,
|
||||
score = score,
|
||||
coverage = 0.92f,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
add(
|
||||
RawStackGlobalRegistrationCandidate(
|
||||
dxRaw = centerX + 6f,
|
||||
dyRaw = centerY,
|
||||
score = 0.040f,
|
||||
coverage = 0.92f,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
val estimate = RawStackFrameRegistrationEstimator.estimateGlobalTranslation(setup, candidates)
|
||||
val matrix = estimate.candidateTransform.matrixAt(0)
|
||||
|
||||
assertTrue(estimate.globalSubpixelRefined)
|
||||
assertEquals(centerX + expectedOffsetX * 2f, matrix[2], 0.001f)
|
||||
assertEquals(centerY + expectedOffsetY * 2f, matrix[5], 0.001f)
|
||||
assertEquals(centerX, estimate.globalDiscreteDxRaw, 0.001f)
|
||||
assertEquals(centerY, estimate.globalDiscreteDyRaw, 0.001f)
|
||||
assertEquals(0.040f, estimate.globalSecondScore, 0.001f)
|
||||
assertTrue(estimate.globalScoreMargin > 1f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun estimatesGlobalImageTranslationInRawCoordinates() {
|
||||
val setup = RawStackRegistrationResolver.resolve(4096, 3072)
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RawStackSuperResolutionPhaseTrackerTest {
|
||||
@Test
|
||||
fun identicalPhaseHasNoNovelty() {
|
||||
val tracker = tracker()
|
||||
|
||||
assertEquals(0f, tracker.noveltyWeight(2f, -2f), 1e-5f)
|
||||
assertEquals(1, tracker.occupiedBinCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun complementaryBayerPhasesFillFourBins() {
|
||||
val tracker = tracker()
|
||||
val phases = listOf(1f to 0f, 0f to 1f, 1f to 1f)
|
||||
|
||||
phases.forEach { (x, y) ->
|
||||
assertTrue(tracker.noveltyWeight(x, y) > 0.99f)
|
||||
tracker.record(x, y)
|
||||
}
|
||||
|
||||
assertEquals(4, tracker.occupiedBinCount)
|
||||
assertEquals(1f, tracker.coverage, 1e-5f)
|
||||
assertEquals(listOf(1, 1, 1, 1), tracker.phaseBinCounts)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wrappingUsesSameCfaPhase() {
|
||||
val tracker = tracker()
|
||||
tracker.record(1f, 0f)
|
||||
|
||||
assertEquals(0f, tracker.noveltyWeight(-1f, 2f), 1e-5f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reportsOnlyBinsThatHaveActuallyBeenAccumulated() {
|
||||
val tracker = tracker()
|
||||
|
||||
assertTrue(tracker.isUnoccupiedBin(1f, 0f))
|
||||
tracker.record(1f, 0f)
|
||||
assertTrue(!tracker.isUnoccupiedBin(1f, 0f))
|
||||
assertEquals(2, tracker.occupiedBinCount)
|
||||
}
|
||||
|
||||
private fun tracker() = RawStackSuperResolutionPhaseTracker(
|
||||
cfaPeriod = 2,
|
||||
outputScale = 2f,
|
||||
noveltyStartPx = 0.1f,
|
||||
noveltyFullPx = 0.45f,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user