feat: radiance (2)

This commit is contained in:
zhoubinjia committed 2026-07-20 12:18:26 +08:00
1 parent 238ca30228
commit 50e2453b31
14 files changed
+1579 -91

No files matched your search

@@ -373,13 +373,17 @@ class Camera2Controller(private val context: Context) {
}
}
private fun trimPendingImages(maxSize: Int = 20) {
private fun trimPendingImages(
maxSize: Int = MultiFrameConfig.MAX_FRAME_COUNT,
) {
if (pendingImages.size <= maxSize) return
val oldestKey = pendingImages.keys.minOrNull() ?: return
pendingImages.remove(oldestKey)?.close()
}
private fun trimPendingResults(maxSize: Int = 20) {
private fun trimPendingResults(
maxSize: Int = MultiFrameConfig.MAX_FRAME_COUNT,
) {
if (pendingResults.size <= maxSize) return
val oldestKey = pendingResults.keys.minOrNull() ?: return
pendingResults.remove(oldestKey)
@@ -407,6 +411,7 @@ class Camera2Controller(private val context: Context) {
lensState = result.get(CaptureResult.LENS_STATE),
rollingShutterSkewNs = result.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW),
gyroWindow = burstGyroRecorder.exposureWindow(sensorTimestampNs, exposureTimeNs),
multiFrameCaptureRole = result.request.tag as? MultiFrameCaptureRole,
)
}
@@ -449,7 +454,8 @@ class Camera2Controller(private val context: Context) {
currentState.useHdrComposition && currentState.useMFSR ->
multiFrameCount + HDR_BRACKET_SIDE_FRAME_COUNT
currentState.useMFNR || currentState.useMFSR -> multiFrameCount
currentState.useMFNR || currentState.useMFSR ->
MultiFrameConfig.captureFrameCount(multiFrameCount)
else -> BURST_CAPTURE_BATCH_SIZE
}
@@ -463,7 +469,7 @@ class Camera2Controller(private val context: Context) {
currentState.hdrBracketCapturing -> currentState.hdrBracketFrameCount
.coerceAtLeast(HDR_BRACKET_BASE_CAPTURE_COUNT)
currentState.useMFNR || currentState.useMFSR ->
MultiFrameConfig.normalizeFrameCount(currentState.multiFrameCount)
MultiFrameConfig.captureFrameCount(currentState.multiFrameCount)
else -> 1
}
@@ -5514,6 +5520,110 @@ class Camera2Controller(private val context: Context) {
)
}
private fun buildMultiFrameShortCaptureRequest(
device: CameraDevice,
reader: ImageReader,
state: CameraState,
baseResult: CaptureResult?,
baseRequest: CaptureRequest,
isRawCapture: Boolean,
): CaptureRequest {
return device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply {
addTarget(reader.surface)
applyBaseCameraSettings(this, isCapture = true, isRawCapture = isRawCapture)
set(
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE,
)
set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF)
copyStillFocusSettingsFromPreview(this)
applyMultiFrameCaptureConsistency(
builder = this,
state = state,
baseResult = baseResult,
lockExposure = true,
isRawCapture = isRawCapture,
)
applyMultiFrameShortExposure(
builder = this,
state = state,
baseResult = baseResult,
baseRequest = baseRequest,
)
setTag(MultiFrameCaptureRole.SHORT)
}.build()
}
private fun applyMultiFrameShortExposure(
builder: CaptureRequest.Builder,
state: CameraState,
baseResult: CaptureResult?,
baseRequest: CaptureRequest,
) {
val baseIso = baseRequest.get(CaptureRequest.SENSOR_SENSITIVITY)
?: baseResult?.get(CaptureResult.SENSOR_SENSITIVITY)
val baseShutter = baseRequest.get(CaptureRequest.SENSOR_EXPOSURE_TIME)
?: baseResult?.get(CaptureResult.SENSOR_EXPOSURE_TIME)
val canUseManualExposure = isManualSensorSupported &&
availableAeModes.contains(CaptureRequest.CONTROL_AE_MODE_OFF) &&
baseIso != null && baseIso > 0 &&
baseShutter != null && baseShutter > 0L
if (canUseManualExposure) {
val manualBaseIso = checkNotNull(baseIso)
val manualBaseShutter = checkNotNull(baseShutter)
val (shortIso, shortShutter) = calculateMultiFrameShortExposure(
baseIso = manualBaseIso,
baseShutter = manualBaseShutter,
state = state,
)
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF)
builder.set(CaptureRequest.CONTROL_AE_LOCK, false)
builder.set(CaptureRequest.SENSOR_SENSITIVITY, shortIso)
builder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, shortShutter)
val achievedRatio = shortIso.toDouble() * shortShutter.toDouble() /
(manualBaseIso.toDouble() * manualBaseShutter.toDouble())
PLog.i(
TAG,
"Multi-frame short request: base=ISO$manualBaseIso/${manualBaseShutter}ns " +
"short=ISO$shortIso/${shortShutter}ns exposureRatio=$achievedRatio",
)
return
}
val shortEv = -ln(MultiFrameConfig.SHORT_FRAME_EXPOSURE_DIVISOR) / ln(2.0)
val compensation = calculateHdrBracketExposureCompensation(state, shortEv.toFloat())
builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
builder.set(CaptureRequest.CONTROL_AE_LOCK, false)
builder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, compensation)
PLog.w(
TAG,
"Manual sensor exposure unavailable for multi-frame short request; " +
"using AE compensation=$compensation for ${shortEv}EV",
)
}
private fun calculateMultiFrameShortExposure(
baseIso: Int,
baseShutter: Long,
state: CameraState,
): Pair<Int, Long> {
val isoRange = state.getIsoRange()
val shutterRange = state.getShutterSpeedRange()
val targetProduct = baseIso.toDouble() * baseShutter.toDouble() /
MultiFrameConfig.SHORT_FRAME_EXPOSURE_DIVISOR
val initialShutter = (baseShutter.toDouble() /
MultiFrameConfig.SHORT_FRAME_EXPOSURE_DIVISOR)
.roundToLong()
.coerceIn(shutterRange.lower, shutterRange.upper)
val shortIso = (targetProduct / initialShutter.toDouble())
.roundToInt()
.coerceIn(isoRange.lower, isoRange.upper)
val shortShutter = (targetProduct / shortIso.toDouble())
.roundToLong()
.coerceIn(shutterRange.lower, shutterRange.upper)
return shortIso to shortShutter
}
private fun shouldUseDefaultHdrBracketCapture(state: CameraState, isRawCapture: Boolean): Boolean {
return state.captureMode == CaptureMode.PHOTO &&
state.useHdrComposition &&
@@ -5632,14 +5742,34 @@ class Camera2Controller(private val context: Context) {
// Burst Mode
val requestedFrameCount = currentState.multiFrameCount
val frameCount = MultiFrameConfig.normalizeFrameCount(requestedFrameCount)
val normalFrameCount = MultiFrameConfig.normalFrameCount(frameCount)
if (frameCount != requestedFrameCount) {
PLog.w(
TAG,
"Normalized invalid multi-frame count $requestedFrameCount to $frameCount",
)
}
val request = captureBuilder.build()
val requests = List(frameCount) { request }
captureBuilder.setTag(MultiFrameCaptureRole.BASE)
val baseRequest = captureBuilder.build()
val shortRequest = buildMultiFrameShortCaptureRequest(
device = device,
reader = reader,
state = currentState,
baseResult = baseExposureResult,
baseRequest = baseRequest,
isRawCapture = isRawCapture,
)
val requests = buildList(MultiFrameConfig.captureFrameCount(frameCount)) {
repeat(normalFrameCount) {
add(baseRequest)
}
add(shortRequest)
}
PLog.i(
TAG,
"Multi-frame burst plan: normalFrames=$normalFrameCount shortFrames=" +
"${MultiFrameConfig.SHORT_FRAME_COUNT} total=${requests.size}",
)
session.captureBurst(requests, object : CameraCaptureSession.CaptureCallback() {
override fun onCaptureStarted(
@@ -5662,10 +5792,17 @@ class Camera2Controller(private val context: Context) {
val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
?: pendingCaptureStartedTimestamps[result.frameNumber]
if (isRawCapture) processOrBufferCaptureResult(result)
lastCaptureResult = result
val role = request.tag as? MultiFrameCaptureRole ?: MultiFrameCaptureRole.BASE
if (role == MultiFrameCaptureRole.BASE) {
lastCaptureResult = result
}
val actualIso = result.get(CaptureResult.SENSOR_SENSITIVITY)
val actualShutter = result.get(CaptureResult.SENSOR_EXPOSURE_TIME)
PLog.d(
TAG,
"Capture completed, result buffered (timestamp: $timestamp). Pending images: ${pendingImages.size}, Pending results: ${pendingResults.size}"
"Capture completed role=$role ISO=$actualIso shutter=$actualShutter, " +
"result buffered (timestamp: $timestamp). " +
"Pending images: ${pendingImages.size}, Pending results: ${pendingResults.size}"
)
}
@@ -6103,6 +6240,8 @@ class Camera2Controller(private val context: Context) {
rollingShutterSkewNs = frameResult.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW),
gyroWindow = frozenMetadata?.gyroWindow
?: burstGyroRecorder.exposureWindow(sensorTimestampNs, exposureTimeNs),
multiFrameCaptureRole = frozenMetadata?.multiFrameCaptureRole
?: (frameResult.request.tag as? MultiFrameCaptureRole),
)
} else {
null
@@ -1,5 +1,10 @@
package com.hinnka.mycamera.camera
enum class MultiFrameCaptureRole {
BASE,
SHORT,
}
data class CapturedFrameMetadata(
val sensorTimestampNs: Long,
val frameNumber: Long,
@@ -10,4 +15,5 @@ data class CapturedFrameMetadata(
val lensState: Int?,
val rollingShutterSkewNs: Long?,
val gyroWindow: GyroExposureWindow?,
val multiFrameCaptureRole: MultiFrameCaptureRole? = null,
)
@@ -4,8 +4,18 @@ object MultiFrameConfig {
const val MIN_FRAME_COUNT = 2
const val MAX_FRAME_COUNT = 20
const val DEFAULT_FRAME_COUNT = 6
const val SHORT_FRAME_COUNT = 1
const val SHORT_FRAME_EXPOSURE_DIVISOR = 3.0
fun normalizeFrameCount(frameCount: Int): Int {
return frameCount.coerceIn(MIN_FRAME_COUNT, MAX_FRAME_COUNT)
}
fun normalFrameCount(totalFrameCount: Int): Int {
return normalizeFrameCount(totalFrameCount) - SHORT_FRAME_COUNT
}
fun captureFrameCount(totalFrameCount: Int): Int {
return normalFrameCount(totalFrameCount) + SHORT_FRAME_COUNT
}
}
@@ -2782,6 +2782,7 @@ object GalleryManager {
compression = finalStackResult.bufferLayout.toDngCompression(),
inputRowStepSamples = finalStackResult.inputRowStepSamples,
inputColStepSamples = finalStackResult.inputColStepSamples,
baselineExposureEv = finalStackResult.baselineExposureEv,
)
} finally {
finalStackResult.fusedBayerBuffer = null
@@ -1,12 +1,120 @@
package com.hinnka.mycamera.processor
import com.hinnka.mycamera.camera.MultiFrameConfig
import com.hinnka.mycamera.utils.PLog
import kotlin.math.abs
import kotlin.math.ln
internal data class RawRadianceExposurePlan(
val baseExposureProduct: Double?,
val normalIndices: IntArray,
val shortIndex: Int?,
val excludedIndices: IntArray,
) {
val acceptedIndices: IntArray
get() = if (shortIndex != null) {
intArrayOf(*normalIndices, shortIndex)
} else {
normalIndices
}
}
internal object RawRadianceExposurePlanner {
private val LN_2 = ln(2.0)
private const val NORMAL_EXPOSURE_TOLERANCE_EV = 0.12
private const val SHORT_EXPOSURE_TOLERANCE_EV = 0.35
fun plan(
exposureProducts: List<Double>,
frameRoles: List<RawBurstFrameRole> = List(exposureProducts.size) {
RawBurstFrameRole.NORMAL
},
): RawRadianceExposurePlan {
require(frameRoles.size == exposureProducts.size) {
"Exposure products and frame roles must have the same size"
}
if (exposureProducts.isEmpty()) {
return RawRadianceExposurePlan(null, IntArray(0), null, IntArray(0))
}
val taggedShortIndices = frameRoles.indices.filter { index ->
frameRoles[index] == RawBurstFrameRole.HIGHLIGHT_SHORT
}
val taggedShortIndex = taggedShortIndices.firstOrNull()
val validIndices = exposureProducts.indices.filter { index ->
index !in taggedShortIndices &&
exposureProducts[index].isFinite() && exposureProducts[index] > 0.0
}
if (validIndices.isEmpty()) {
val normalIndices = exposureProducts.indices.filterNot(taggedShortIndices::contains)
return RawRadianceExposurePlan(
baseExposureProduct = null,
normalIndices = normalIndices.toIntArray(),
shortIndex = taggedShortIndex,
excludedIndices = taggedShortIndices.drop(1).toIntArray(),
)
}
val sortedExposures = validIndices.map(exposureProducts::get).sorted()
val baseExposure = sortedExposures[sortedExposures.size / 2]
val normalIndices = exposureProducts.indices.filter { index ->
if (index in taggedShortIndices) return@filter false
val exposure = exposureProducts[index]
!exposure.isFinite() || exposure <= 0.0 ||
exposureDeltaEv(exposure, baseExposure) <= NORMAL_EXPOSURE_TOLERANCE_EV
}
val targetShortEv = -ln(MultiFrameConfig.SHORT_FRAME_EXPOSURE_DIVISOR) / LN_2
val shortIndex = taggedShortIndex ?: validIndices
.asSequence()
.filterNot(normalIndices::contains)
.map { index ->
index to abs(signedExposureDeltaEv(exposureProducts[index], baseExposure) - targetShortEv)
}
.filter { (_, targetDeltaEv) -> targetDeltaEv <= SHORT_EXPOSURE_TOLERANCE_EV }
.minByOrNull { (_, targetDeltaEv) -> targetDeltaEv }
?.first
val excludedIndices = exposureProducts.indices.filter { index ->
index !in normalIndices && index != shortIndex
}
return RawRadianceExposurePlan(
baseExposureProduct = baseExposure,
normalIndices = normalIndices.toIntArray(),
shortIndex = shortIndex,
excludedIndices = excludedIndices.toIntArray(),
)
}
private fun exposureDeltaEv(exposure: Double, reference: Double): Double {
return abs(signedExposureDeltaEv(exposure, reference))
}
private fun signedExposureDeltaEv(exposure: Double, reference: Double): Double {
return ln(exposure / reference) / LN_2
}
}
internal data class RawRadianceHighlightFrame(
val shortFrame: RawStackFrame,
val anchorFrameIndex: Int,
val exposureRatio: Float,
val baselineExposureEv: Float,
)
internal fun hasRadianceHighlightAlignmentSupport(
validTileCount: Int,
coveredQuadrants: Int,
minimumValidTiles: Int,
minimumQuadrants: Int,
): Boolean {
return validTileCount >= minimumValidTiles.coerceAtLeast(1) &&
coveredQuadrants >= minimumQuadrants.coerceIn(1, 4)
}
/**
* Unified same-exposure RAW fusion.
*
* One optional one-third-exposure frame is identified and reserved for the dedicated
* highlight-reconstruction stage. It must not participate in normal MFNR/MFSR accumulation.
*
* The reconstruction algorithm is independent of output scale: every accepted RAW frame
* contributes a wide-kernel denoise estimate and a narrow-kernel detail estimate in the
* sensor-linear RGB domain. Standard Bayer references use the full VGN demosaic core while
@@ -33,18 +141,58 @@ class GlesRawRadianceFusion(
fun processFrames(frames: List<RawStackFrame>): RawStackResult? {
if (frames.isEmpty()) return null
val sameExposureFrames = selectSameExposureFrames(frames)
if (sameExposureFrames.size != frames.size) {
val exposurePlan = RawRadianceExposurePlanner.plan(
exposureProducts = frames.map { it.exposureProduct },
frameRoles = frames.map { it.role },
)
exposurePlan.excludedIndices.forEach { index ->
frames[index].image.close()
}
val fusionFrames = exposurePlan.normalIndices.map { index ->
frames[index].copy(role = RawBurstFrameRole.NORMAL)
}
val shortFrame = exposurePlan.shortIndex?.let(frames::get)
if (fusionFrames.isEmpty()) {
shortFrame?.image?.close()
return null
}
if (exposurePlan.excludedIndices.isNotEmpty()) {
PLog.w(
TAG,
"Radiance fusion excluded ${frames.size - sameExposureFrames.size} exposure-mismatched " +
"frames; reference exposure=${frames.first().exposureProduct}",
"Radiance fusion excluded ${exposurePlan.excludedIndices.size} unsupported-exposure " +
"frames; baseExposure=${exposurePlan.baseExposureProduct}",
)
}
val highlightFrame = shortFrame?.let { short ->
createHighlightFrame(
normalFrames = fusionFrames,
shortFrame = short,
baseExposureProduct = exposurePlan.baseExposureProduct,
)
}
if (highlightFrame != null) {
PLog.i(
TAG,
"Radiance highlight frame index=${exposurePlan.shortIndex} " +
"exposure=${highlightFrame.shortFrame.exposureProduct} " +
"base=${exposurePlan.baseExposureProduct} " +
"ratio=${highlightFrame.exposureRatio} " +
"anchor=${highlightFrame.anchorFrameIndex} " +
"normalFrames=${exposurePlan.normalIndices.size}; normal fusion excluded",
)
} else if (shortFrame != null) {
PLog.w(
TAG,
"Radiance short frame has no usable exposure ratio; highlight reconstruction disabled",
)
shortFrame.image.close()
} else {
PLog.w(TAG, "Radiance fusion received no valid one-third short frame")
}
val tuning = RawStackTuningResolver.resolve(
mode = RawStackMode.MFSR,
frameCount = sameExposureFrames.size,
frameCount = exposurePlan.normalIndices.size,
superResolutionScale = outputScale,
)
return GlesRawStacker(
@@ -63,35 +211,45 @@ class GlesRawRadianceFusion(
debugConfig = debugConfig,
fusionPipeline = RawFusionPipeline.RADIANCE_RGB,
radianceFusionTuning = fusionTuning,
).processFrames(sameExposureFrames)
).processFrames(fusionFrames, highlightFrame)
}
private fun selectSameExposureFrames(frames: List<RawStackFrame>): List<RawStackFrame> {
val reference = frames.first().exposureProduct
private fun createHighlightFrame(
normalFrames: List<RawStackFrame>,
shortFrame: RawStackFrame,
baseExposureProduct: Double?,
): RawRadianceHighlightFrame? {
if (normalFrames.isEmpty()) return null
val normalExposure = baseExposureProduct
?.takeIf { it.isFinite() && it > 0.0 }
?: return null
val shortExposure = shortFrame.exposureProduct
.takeIf { it.isFinite() && it > 0.0 }
?: return frames
val accepted = ArrayList<RawStackFrame>(frames.size)
accepted += frames.first()
for (frame in frames.drop(1)) {
val exposure = frame.exposureProduct.takeIf { it.isFinite() && it > 0.0 }
if (exposure == null) {
accepted += frame
continue
}
val deltaEv = abs(ln(exposure / reference) / LN_2).toFloat()
if (deltaEv <= SAME_EXPOSURE_TOLERANCE_EV) {
accepted += frame
} else {
frame.image.close()
}
?: return null
val ratio = (normalExposure / shortExposure).toFloat()
if (!ratio.isFinite() || ratio < fusionTuning.highlightMinExposureRatio ||
ratio > fusionTuning.highlightMaxExposureRatio
) {
return null
}
return accepted
val anchorIndex = normalFrames.indices.minByOrNull { index ->
timestampDistance(normalFrames[index].sensorTimestampNs, shortFrame.sensorTimestampNs)
} ?: return null
return RawRadianceHighlightFrame(
shortFrame = shortFrame.copy(role = RawBurstFrameRole.HIGHLIGHT_SHORT),
anchorFrameIndex = anchorIndex,
exposureRatio = ratio,
baselineExposureEv = (ln(ratio.toDouble()) / ln(2.0)).toFloat(),
)
}
private fun timestampDistance(first: Long, second: Long): Long {
if (first <= 0L || second <= 0L) return Long.MAX_VALUE
return if (first >= second) first - second else second - first
}
companion object {
private const val TAG = "GlesRawRadianceFusion"
private const val SAME_EXPOSURE_TOLERANCE_EV = 0.08f
private val LN_2 = ln(2.0)
}
}
@@ -118,6 +276,24 @@ data class RawRadianceFusionTuning(
val detailChromaStrength: Float = 0.0f,
val chromaConsistencySigmaStart: Float = 3.0f,
val chromaConsistencySigmaFull: Float = 6.0f,
val highlightMinExposureRatio: Float = 1.2f,
val highlightMaxExposureRatio: Float = 8.0f,
val highlightNormalClipStart: Float = 0.90f,
val highlightNormalClipFull: Float = 0.985f,
val highlightShortClipStart: Float = 0.94f,
val highlightShortClipFull: Float = 0.99f,
val highlightShortSignalStart: Float = 0.01f,
val highlightShortSignalFull: Float = 0.04f,
val highlightFlowFbConsistencyStartPx: Float = 0.75f,
val highlightFlowFbConsistencyFullPx: Float = 2.0f,
val highlightFlowPropagationPasses: Int = 48,
val highlightFlowPropagationDecay: Float = 0.96f,
val highlightFlowGuideEdgeSigma: Float = 0.08f,
val highlightFlowSeedConfidence: Float = 0.05f,
val highlightFlowMinimumConfidence: Float = 0.005f,
val highlightFlowFullConfidence: Float = 0.05f,
val highlightFlowMinimumValidTiles: Int = 16,
val highlightFlowMinimumQuadrants: Int = 2,
)
/** Returns a sensor-linear RGB value that becomes neutral after the capture WB is applied. */
@@ -137,6 +313,213 @@ internal fun radianceDebugNeutralRgb(calculationWbGains: FloatArray): FloatArray
}
internal object GlesRawRadianceFusionShaders {
val validateHighlightFlow: String = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uForwardFlow;
uniform sampler2D uReverseFlow;
uniform ivec2 uGridSize;
uniform ivec2 uPlaneSize;
uniform int uTileSize;
uniform float uFbConsistencyStart;
uniform float uFbConsistencyFull;
out vec4 fragColor;
vec4 flowAt(sampler2D flowTexture, vec2 planePosition) {
vec2 grid = planePosition / float(uTileSize) - vec2(0.5);
vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize);
return texture(flowTexture, clamp(uv, vec2(0.0), vec2(1.0)));
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
vec2 referencePosition = min(
vec2(tile * uTileSize + ivec2(uTileSize / 2)),
vec2(uPlaneSize - ivec2(1))
);
vec4 forward = texelFetch(uForwardFlow, tile, 0);
vec2 currentPosition = referencePosition + forward.rg;
bool inside = currentPosition.x >= 0.0 && currentPosition.y >= 0.0 &&
currentPosition.x <= float(uPlaneSize.x - 1) &&
currentPosition.y <= float(uPlaneSize.y - 1);
vec4 reverse = inside ? flowAt(uReverseFlow, currentPosition) : vec4(0.0);
float error = length(forward.rg + reverse.rg);
float consistency = 1.0 - smoothstep(
min(uFbConsistencyStart, uFbConsistencyFull),
max(uFbConsistencyStart, uFbConsistencyFull),
error
);
float confidence = min(forward.a, reverse.a) * consistency * (inside ? 1.0 : 0.0);
fragColor = vec4(forward.rg, max(forward.b, error), clamp(confidence, 0.0, 1.0));
}
""".trimIndent()
val propagateHighlightFlow: String = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uInputFlow;
uniform sampler2D uGuideProxy;
uniform ivec2 uGridSize;
uniform ivec2 uPlaneSize;
uniform int uTileSize;
uniform float uConfidenceDecay;
uniform float uDirectConfidence;
uniform float uMinimumConfidence;
uniform float uFlowConsistencySigma;
uniform float uGuideEdgeSigma;
out vec4 fragColor;
vec4 readFlow(ivec2 position) {
return texelFetch(
uInputFlow,
clamp(position, ivec2(0), uGridSize - ivec2(1)),
0
);
}
vec4 guideAt(ivec2 tilePosition) {
ivec2 planePosition = min(
tilePosition * uTileSize + ivec2(uTileSize / 2),
uPlaneSize - ivec2(1)
);
return texelFetch(
uGuideProxy,
clamp(planePosition, ivec2(0), uPlaneSize - ivec2(1)),
0
);
}
void main() {
ivec2 position = ivec2(gl_FragCoord.xy);
vec4 center = readFlow(position);
vec4 centerGuide = guideAt(position);
float minimumConfidence = clamp(uMinimumConfidence, 0.0, 1.0);
float directConfidence = max(
clamp(uDirectConfidence, 0.0, 1.0),
minimumConfidence + 1e-4
);
if (center.a >= directConfidence) {
fragColor = center;
return;
}
vec2 flowSum = vec2(0.0);
float residualSum = 0.0;
float weightSum = 0.0;
float maxConfidence = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
if (x == 0 && y == 0) continue;
vec4 sampleValue = readFlow(position + ivec2(x, y));
vec4 neighborGuide = guideAt(
clamp(position + ivec2(x, y), ivec2(0), uGridSize - ivec2(1))
);
float spatial = (x == 0 || y == 0) ? 1.0 : 0.70710678;
float guideDelta = neighborGuide.r - centerGuide.r;
float edgeSigma = max(uGuideEdgeSigma, 1e-3);
float edgeWeight = min(centerGuide.g, neighborGuide.g) < 0.5 ?
1.0 : exp(-(guideDelta * guideDelta) / (edgeSigma * edgeSigma));
float support = smoothstep(
minimumConfidence,
directConfidence,
sampleValue.a
);
float weight = sampleValue.a * support * spatial * edgeWeight;
flowSum += sampleValue.rg * weight;
residualSum += sampleValue.b * weight;
weightSum += weight;
maxConfidence = max(maxConfidence, sampleValue.a);
}
}
if (weightSum <= 1e-6) {
fragColor = vec4(center.rgb, 0.0);
return;
}
vec2 propagatedFlow = flowSum / weightSum;
float variance = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
if (x == 0 && y == 0) continue;
vec4 sampleValue = readFlow(position + ivec2(x, y));
vec4 neighborGuide = guideAt(
clamp(position + ivec2(x, y), ivec2(0), uGridSize - ivec2(1))
);
float spatial = (x == 0 || y == 0) ? 1.0 : 0.70710678;
float guideDelta = neighborGuide.r - centerGuide.r;
float edgeSigma = max(uGuideEdgeSigma, 1e-3);
float edgeWeight = min(centerGuide.g, neighborGuide.g) < 0.5 ?
1.0 : exp(-(guideDelta * guideDelta) / (edgeSigma * edgeSigma));
float support = smoothstep(
minimumConfidence,
directConfidence,
sampleValue.a
);
float weight = sampleValue.a * support * spatial * edgeWeight;
vec2 delta = sampleValue.rg - propagatedFlow;
variance += dot(delta, delta) * weight;
}
}
variance /= weightSum;
float sigma = max(uFlowConsistencySigma, 0.25);
float consistency = exp(-variance / (sigma * sigma));
float propagatedConfidence = maxConfidence *
clamp(uConfidenceDecay, 0.0, 1.0) * consistency;
fragColor = vec4(
propagatedFlow,
residualSum / weightSum,
clamp(propagatedConfidence, 0.0, 1.0)
);
}
""".trimIndent()
val composeHighlightFlow: String = """
#version 300 es
precision highp float;
precision highp int;
uniform sampler2D uReferenceToAnchorFlow;
uniform sampler2D uAnchorToShortFlow;
uniform ivec2 uGridSize;
uniform ivec2 uPlaneSize;
uniform int uTileSize;
uniform int uAnchorIsReference;
out vec4 fragColor;
vec4 flowAt(sampler2D flowTexture, vec2 planePosition) {
vec2 grid = planePosition / float(uTileSize) - vec2(0.5);
vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize);
return texture(flowTexture, clamp(uv, vec2(0.0), vec2(1.0)));
}
void main() {
ivec2 tile = ivec2(gl_FragCoord.xy);
vec2 referencePosition = min(
vec2(tile * uTileSize + ivec2(uTileSize / 2)),
vec2(uPlaneSize - ivec2(1))
);
vec4 referenceToAnchorFlow = uAnchorIsReference != 0 ?
vec4(0.0, 0.0, 0.0, 1.0) :
texelFetch(uReferenceToAnchorFlow, tile, 0);
vec2 anchorPosition = referencePosition + referenceToAnchorFlow.rg;
bool inside = anchorPosition.x >= 0.0 && anchorPosition.y >= 0.0 &&
anchorPosition.x <= float(uPlaneSize.x - 1) &&
anchorPosition.y <= float(uPlaneSize.y - 1);
vec4 anchorToShortFlow = inside ?
flowAt(uAnchorToShortFlow, anchorPosition) : vec4(0.0);
fragColor = vec4(
referenceToAnchorFlow.rg + anchorToShortFlow.rg,
max(referenceToAnchorFlow.b, anchorToShortFlow.b),
clamp(
referenceToAnchorFlow.a * anchorToShortFlow.a * (inside ? 1.0 : 0.0),
0.0,
1.0
)
);
}
""".trimIndent()
fun clearAccumulator(trackRejections: Boolean): String {
val rejectionDeclaration = if (trackRejections) {
"layout(rgba16f, binding = 6) writeonly uniform highp image2D uFusionRejections;"
@@ -825,6 +1208,8 @@ internal object GlesRawRadianceFusionShaders {
fun normalize(
showRejections: Boolean,
showSrDetail: Boolean = false,
reconstructHighlights: Boolean = false,
showHighlightReconstruction: Boolean = false,
): String {
val rejectionUniforms = if (showRejections) {
"""
@@ -840,6 +1225,207 @@ internal object GlesRawRadianceFusionShaders {
} else {
""
}
val highlightDeclarations = if (reconstructHighlights) {
"""
uniform sampler2D uHighlightRgb;
uniform highp usampler2D uHighlightRaw;
uniform highp usampler2D uReferenceRaw;
uniform sampler2D uHighlightFlow;
uniform ivec2 uHighlightSourceOrigin;
uniform ivec2 uHighlightSourceSize;
uniform ivec2 uHighlightFlowGridSize;
uniform ivec2 uInputSize;
uniform ivec2 uOutputSize;
uniform int uHighlightFlowTileSize;
uniform int uCfaPattern;
uniform float uBlackLevel[4];
uniform float uWhiteLevel;
uniform float uHighlightExposureRatio;
uniform float uHighlightNormalClipStart;
uniform float uHighlightNormalClipFull;
uniform float uHighlightShortClipStart;
uniform float uHighlightShortClipFull;
uniform float uHighlightShortSignalStart;
uniform float uHighlightShortSignalFull;
uniform float uHighlightFlowMinimumConfidence;
uniform float uHighlightFlowFullConfidence;
""".trimIndent()
} else {
""
}
val highlightHelpers = if (reconstructHighlights) {
"""
int highlightBaseCfaPattern() {
if (uCfaPattern >= 8) return uCfaPattern - 8;
if (uCfaPattern >= 4) return uCfaPattern - 4;
return uCfaPattern;
}
int highlightCfaBlockSize() {
if (uCfaPattern >= 8) return 4;
if (uCfaPattern >= 4) return 2;
return 1;
}
int highlightBayerIndexForPhase(int pattern, int phase) {
if (pattern == 0) return phase;
if (pattern == 1) {
if (phase == 0) return 1;
if (phase == 1) return 0;
if (phase == 2) return 3;
return 2;
}
if (pattern == 2) {
if (phase == 0) return 2;
if (phase == 1) return 3;
if (phase == 2) return 0;
return 1;
}
if (phase == 0) return 3;
if (phase == 1) return 2;
if (phase == 2) return 1;
return 0;
}
int highlightBayerIndexAt(ivec2 p) {
int blockSize = highlightCfaBlockSize();
int phase = ((p.y / blockSize) & 1) * 2 + ((p.x / blockSize) & 1);
return highlightBayerIndexForPhase(highlightBaseCfaPattern(), phase);
}
vec4 highlightFlowAt(vec2 planePosition) {
vec2 grid = planePosition / float(uHighlightFlowTileSize) - vec2(0.5);
vec2 uv = (grid + vec2(0.5)) / vec2(uHighlightFlowGridSize);
return texture(uHighlightFlow, clamp(uv, vec2(0.0), vec2(1.0)));
}
vec3 highlightRgbAt(vec2 localRawPosition) {
vec2 maximum = vec2(max(uHighlightSourceSize - ivec2(1), ivec2(0)));
vec2 storageSize = vec2(textureSize(uHighlightRgb, 0));
vec2 uv = (clamp(localRawPosition, vec2(0.0), maximum) + vec2(0.5)) /
storageSize;
return clamp(texture(uHighlightRgb, uv).rgb, 0.0, 1.0);
}
float highlightRawNormAt(ivec2 localPosition) {
localPosition = clamp(
localPosition,
ivec2(0),
uHighlightSourceSize - ivec2(1)
);
ivec2 globalPosition = localPosition + uHighlightSourceOrigin;
int bayerIndex = highlightBayerIndexAt(globalPosition);
float raw = float(texelFetch(uHighlightRaw, localPosition, 0).r);
float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0);
return clamp((raw - uBlackLevel[bayerIndex]) / range, 0.0, 1.0);
}
float referenceRawNormAt(ivec2 globalPosition) {
globalPosition = clamp(globalPosition, ivec2(0), uInputSize - ivec2(1));
int bayerIndex = highlightBayerIndexAt(globalPosition);
float raw = float(texelFetch(uReferenceRaw, globalPosition, 0).r);
float range = max(uWhiteLevel - uBlackLevel[bayerIndex], 1.0);
return clamp((raw - uBlackLevel[bayerIndex]) / range, 0.0, 1.0);
}
vec2 highlightRawSignalAndPeak(vec2 localRawPosition) {
ivec2 center = ivec2(round(localRawPosition));
ivec2 block = (center / 2) * 2;
float signal = 0.0;
float peak = 0.0;
for (int y = 0; y <= 1; ++y) {
for (int x = 0; x <= 1; ++x) {
float sampleValue = highlightRawNormAt(block + ivec2(x, y));
signal += sampleValue;
peak = max(peak, sampleValue);
}
}
return vec2(signal * 0.25, peak);
}
float referenceRawPeak(vec2 globalRawPosition) {
ivec2 center = ivec2(round(globalRawPosition));
ivec2 block = (center / 2) * 2;
float peak = 0.0;
for (int y = 0; y <= 1; ++y) {
for (int x = 0; x <= 1; ++x) {
peak = max(peak, referenceRawNormAt(block + ivec2(x, y)));
}
}
return peak;
}
""".trimIndent()
} else {
""
}
val highlightComposition = if (reconstructHighlights) {
val highlightDebugOverlay = if (showHighlightReconstruction) {
"""
if (highlightWeight > 1e-4) {
rgb = vec3(0.0, 1.0, 0.0);
}
""".trimIndent()
} else {
""
}
"""
vec2 referenceRawPosition = (vec2(outputP) + vec2(0.5)) *
vec2(uInputSize) / vec2(uOutputSize) - vec2(0.5);
vec4 highlightFlow = highlightFlowAt(referenceRawPosition * 0.5);
vec2 highlightGlobalPosition = referenceRawPosition + 2.0 * highlightFlow.rg;
vec2 highlightLocalPosition = highlightGlobalPosition - vec2(uHighlightSourceOrigin);
float highlightInside = highlightLocalPosition.x >= 0.0 &&
highlightLocalPosition.y >= 0.0 &&
highlightLocalPosition.x <= float(uHighlightSourceSize.x - 1) &&
highlightLocalPosition.y <= float(uHighlightSourceSize.y - 1) ? 1.0 : 0.0;
vec3 highlightRgb = highlightRgbAt(highlightLocalPosition);
vec2 highlightRawStats = highlightRawSignalAndPeak(highlightLocalPosition);
float normalPeak = referenceRawPeak(referenceRawPosition);
float normalClipped = smoothstep(
min(uHighlightNormalClipStart, uHighlightNormalClipFull),
max(uHighlightNormalClipStart, uHighlightNormalClipFull),
normalPeak
);
float shortNotClipped = 1.0 - smoothstep(
min(uHighlightShortClipStart, uHighlightShortClipFull),
max(uHighlightShortClipStart, uHighlightShortClipFull),
highlightRawStats.y
);
float shortHasSignal = smoothstep(
min(uHighlightShortSignalStart, uHighlightShortSignalFull),
max(uHighlightShortSignalStart, uHighlightShortSignalFull),
highlightRawStats.x
);
float highlightFlowConfidence = smoothstep(
uHighlightFlowMinimumConfidence,
max(
uHighlightFlowMinimumConfidence + 1e-4,
uHighlightFlowFullConfidence
),
highlightFlow.a
);
float shortReliability = clamp(
shortNotClipped * shortHasSignal * highlightFlowConfidence * highlightInside,
0.0,
1.0
);
// A confirmed RAW-clipped normal sample contains no radiance information. In that
// core region choose one source: a sufficiently reliable short sample replaces it
// completely; otherwise retain the normal fallback. Never average the two, because
// the clipped normal value biases recovered highlights toward dirty gray.
float saturatedCore = step(uHighlightNormalClipFull, normalPeak);
float coreShortSelection = saturatedCore * step(0.5, shortReliability);
// The soft shoulder lies below confirmed sensor clipping, where the normal sample is
// still physically meaningful and can safely hide exposure-boundary seams.
float shoulderBlend = (1.0 - saturatedCore) * normalClipped * shortReliability;
float highlightWeight = max(coreShortSelection, shoulderBlend);
vec3 normalInShortDomain = rgb / max(uHighlightExposureRatio, 1.0);
rgb = clamp(mix(normalInShortDomain, highlightRgb, highlightWeight), 0.0, 1.0);
$highlightDebugOverlay
""".trimIndent()
} else {
""
}
val rejectionOverlay = if (showRejections) {
"""
{
@@ -922,6 +1508,7 @@ internal object GlesRawRadianceFusionShaders {
uniform sampler2D uReferenceBase;
$rejectionUniforms
$debugColorUniform
$highlightDeclarations
uniform float uNoiseAlphaByChannel[4];
uniform float uNoiseBetaByChannel[4];
uniform float uNrConfidenceStart;
@@ -941,6 +1528,8 @@ internal object GlesRawRadianceFusionShaders {
uniform ivec2 uAccumulatorSize;
uniform ivec2 uOutputOrigin;
$highlightHelpers
struct NrState {
vec3 base;
vec3 nr;
@@ -1195,6 +1784,7 @@ internal object GlesRawRadianceFusionShaders {
0.0,
1.0
);
$highlightComposition
$srDetailOverlay
$rejectionOverlay
fragColor = uvec4(
@@ -61,6 +61,23 @@ class GlesRawStacker(
val minFlowYPlanePx: Float,
val maxFlowYPlanePx: Float,
)
private data class RadianceHighlightAlignment(
val frame: RawRadianceHighlightFrame,
val flowTexture: Int,
val minFlowXPlanePx: Float,
val maxFlowXPlanePx: Float,
val minFlowYPlanePx: Float,
val maxFlowYPlanePx: Float,
val validTileFraction: Float,
val coveredQuadrants: Int,
) {
fun flowBounds(): RadianceFlowBounds = RadianceFlowBounds(
minXPlanePx = minFlowXPlanePx,
maxXPlanePx = maxFlowXPlanePx,
minYPlanePx = minFlowYPlanePx,
maxYPlanePx = maxFlowYPlanePx,
)
}
private data class ReadOutputTiming(
val elapsedMs: Long,
val glReadMs: Long,
@@ -189,6 +206,8 @@ class GlesRawStacker(
radianceFusionEnabled && hwmfDebug.visualizeRadianceFusionRejections
private val visualizeRadianceSrDetail =
radianceFusionEnabled && hwmfDebug.visualizeRadianceSrDetail
private val visualizeRadianceHighlightReconstruction =
radianceFusionEnabled && hwmfDebug.visualizeRadianceHighlightReconstruction
private val logRadianceFusionParticipation =
radianceFusionEnabled && hwmfDebug.logRadianceFusionParticipation
private val dualTileConfidence = radianceFusionEnabled
@@ -278,6 +297,10 @@ class GlesRawStacker(
private var clearSuperResolutionAccumulatorProgram = 0
private var accumulateSuperResolutionProgram = 0
private var normalizeSuperResolutionProgram = 0
private var radianceHighlightNormalizeProgram = 0
private var radianceHighlightValidateFlowProgram = 0
private var radianceHighlightPropagateFlowProgram = 0
private var radianceHighlightComposeFlowProgram = 0
private var radianceReferenceBaseProgram = 0
private val radianceVgnPrograms = IntArray(VgnShaders.PROGRAM_3 + 1)
private var radianceVgnFinalProgram = 0
@@ -314,6 +337,9 @@ class GlesRawStacker(
private var curProxy = 0
private var flowTexture = 0
private var flowScratchTexture = 0
private var radianceHighlightReverseFlowTexture = 0
private var radianceHighlightAnchorFlowTexture = 0
private var radianceHighlightComposedFlowTexture = 0
private var kernelTexture = 0
private var robustnessTexture = 0
private var tileMaskTexture = 0
@@ -374,22 +400,34 @@ class GlesRawStacker(
private var hdrShortRawOffsetX = 0f
private var hdrShortRawOffsetY = 0f
private var hdrWeightMap: GlesRawHdrWeightMap? = null
private var activeRadianceHighlightFrame: RawRadianceHighlightFrame? = null
fun process(images: List<SafeImage>): RawStackResult? {
return processFrames(images.map { RawStackFrame(it) })
}
fun processFrames(frames: List<RawStackFrame>): RawStackResult? {
internal fun processFrames(
frames: List<RawStackFrame>,
highlightFrame: RawRadianceHighlightFrame? = null,
): RawStackResult? {
val images = frames.map { it.image }
if (images.isEmpty() || width <= 0 || height <= 0) return null
if (images.any { it.width != width || it.height != height }) {
PLog.w(TAG, "GLES RAW stack got mixed frame sizes")
images.forEach { it.close() }
activeRadianceHighlightFrame = highlightFrame?.takeIf { radianceFusionEnabled }
val ownedImages = buildList {
addAll(images)
activeRadianceHighlightFrame?.shortFrame?.image?.let(::add)
}
if (images.isEmpty() || width <= 0 || height <= 0) {
ownedImages.forEach { it.close() }
return null
}
if (images.any { it.format != ImageFormat.RAW_SENSOR }) {
if (images.any { it.width != width || it.height != height }) {
PLog.w(TAG, "GLES RAW stack got mixed frame sizes")
ownedImages.forEach { it.close() }
return null
}
if (ownedImages.any { it.format != ImageFormat.RAW_SENSOR }) {
PLog.w(TAG, "GLES RAW stack only supports RAW_SENSOR input")
images.forEach { it.close() }
ownedImages.forEach { it.close() }
return null
}
@@ -576,6 +614,15 @@ class GlesRawStacker(
GlesGpuScheduler.yieldToUiRenderer()
}
val highlightAlignment = activeRadianceHighlightFrame?.let { highlight ->
prepareRadianceHighlightAlignment(
highlight = highlight,
frames = frames,
acceptedFrames = acceptedSuperResolutionFrames,
referencePyramid = refPyramid,
currentPyramid = curPyramid,
)
}
val superResolutionDecision = if (superResolutionEnabled) {
decideSuperResolutionOutput(alignedFrameCount)
} else {
@@ -587,6 +634,7 @@ class GlesRawStacker(
acceptedFrames = acceptedSuperResolutionFrames,
candidateFrameCount = (images.size - 1).coerceAtLeast(0),
outputBuffer = outputBuffer,
highlightAlignment = highlightAlignment,
)
superResolutionEnabled -> reconstructSuperResolutionStripes(
referenceImage = images[0],
@@ -631,12 +679,13 @@ class GlesRawStacker(
},
inputRowStepSamples = if (radianceFusionEnabled) outputWidth * 3 else null,
inputColStepSamples = if (radianceFusionEnabled) 3 else null,
baselineExposureEv = highlightAlignment?.frame?.baselineExposureEv,
)
} catch (e: Exception) {
PLog.e(TAG, "GLES RAW stacking failed", e)
null
} finally {
images.forEach { it.close() }
ownedImages.forEach { it.close() }
release()
GlesGpuScheduler.restoreCurrentThreadPriority(originalThreadPriority, TAG)
if (!returned) {
@@ -950,6 +999,34 @@ class GlesRawStacker(
),
"raw_radiance_normalize_r32ui_usampler",
)
if (activeRadianceHighlightFrame != null) {
radianceHighlightNormalizeProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.normalize(
showRejections = visualizeRadianceFusionRejections,
showSrDetail = visualizeRadianceSrDetail,
reconstructHighlights = true,
showHighlightReconstruction =
visualizeRadianceHighlightReconstruction,
),
"raw_radiance_highlight_normalize_r32ui_usampler",
)
radianceHighlightValidateFlowProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.validateHighlightFlow,
"raw_radiance_highlight_validate_flow",
)
radianceHighlightPropagateFlowProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.propagateHighlightFlow,
"raw_radiance_highlight_propagate_flow",
)
radianceHighlightComposeFlowProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesRawRadianceFusionShaders.composeHighlightFlow,
"raw_radiance_highlight_compose_flow",
)
}
if (radianceUsesVgnSemanticBackend) {
initRadianceReconstructionPrograms()
} else {
@@ -1176,6 +1253,26 @@ class GlesRawStacker(
curProxy = createTexture2D(planeWidth, planeHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
flowTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
flowScratchTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
if (radianceFusionEnabled && activeRadianceHighlightFrame != null) {
radianceHighlightReverseFlowTexture = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
radianceHighlightAnchorFlowTexture = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
radianceHighlightComposedFlowTexture = createTexture2D(
gridWidth,
gridHeight,
GLES30.GL_RGBA16F,
GLES30.GL_LINEAR,
)
}
kernelTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
robustnessTexture = createTexture2D(planeWidth, planeHeight, GLES30.GL_R32F, GLES30.GL_NEAREST)
tileMaskTexture = createTexture2D(
@@ -2264,13 +2361,18 @@ class GlesRawStacker(
finishFramebufferPass(label)
}
private fun refineFlow() {
private fun refineFlow(
referenceProxyTexture: Int = refProxy,
currentProxyTexture: Int = curProxy,
targetFlowTexture: Int = flowTexture,
scratchFlowTexture: Int = flowScratchTexture,
) {
repeat(lkRefinePasses) { pass ->
val input = if (pass % 2 == 0) flowTexture else flowScratchTexture
val output = if (pass % 2 == 0) flowScratchTexture else flowTexture
val input = if (pass % 2 == 0) targetFlowTexture else scratchFlowTexture
val output = if (pass % 2 == 0) scratchFlowTexture else targetFlowTexture
GLES31.glUseProgram(lkRefineProgram)
bindTexture(lkRefineProgram, "uReference", 0, refProxy)
bindTexture(lkRefineProgram, "uCurrent", 1, curProxy)
bindTexture(lkRefineProgram, "uReference", 0, referenceProxyTexture)
bindTexture(lkRefineProgram, "uCurrent", 1, currentProxyTexture)
bindTexture(lkRefineProgram, "uInputFlow", 2, input)
bindImage(3, output, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glUniform2i(GLES31.glGetUniformLocation(lkRefineProgram, "uPlaneSize"), planeWidth, planeHeight)
@@ -2281,14 +2383,17 @@ class GlesRawStacker(
checkGlError("refineFlow pass $pass")
}
if (lkRefinePasses % 2 != 0) {
copyFlow(flowScratchTexture, flowTexture, "refineFlow copy")
copyFlowResult(scratchFlowTexture, targetFlowTexture, "refineFlow copy")
}
}
private fun smoothFlow() {
private fun smoothFlow(
targetFlowTexture: Int = flowTexture,
scratchFlowTexture: Int = flowScratchTexture,
) {
repeat(flowSmoothPasses) { pass ->
val input = if (pass % 2 == 0) flowTexture else flowScratchTexture
val output = if (pass % 2 == 0) flowScratchTexture else flowTexture
val input = if (pass % 2 == 0) targetFlowTexture else scratchFlowTexture
val output = if (pass % 2 == 0) scratchFlowTexture else targetFlowTexture
bindFramebufferOutput(output, "smoothFlow pass $pass")
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(smoothFlowProgram)
@@ -2299,6 +2404,17 @@ class GlesRawStacker(
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("smoothFlow pass $pass")
}
if (flowSmoothPasses % 2 != 0) {
copyFlowResult(scratchFlowTexture, targetFlowTexture, "smoothFlow copy")
}
}
private fun copyFlowResult(input: Int, output: Int, label: String) {
if (copyRgbaProgram != 0) {
copyRgbaTexture(input, output, gridWidth, gridHeight, label)
} else {
copyFlow(input, output, label)
}
}
private fun copyFlow(input: Int, output: Int, label: String) {
@@ -2448,6 +2564,298 @@ class GlesRawStacker(
)
}
private fun prepareRadianceHighlightAlignment(
highlight: RawRadianceHighlightFrame,
frames: List<RawStackFrame>,
acceptedFrames: List<AcceptedSuperResolutionFrame>,
referencePyramid: List<TextureLevel>,
currentPyramid: List<TextureLevel>,
): RadianceHighlightAlignment? {
if (!radianceFusionEnabled || highlight.anchorFrameIndex !in frames.indices) return null
val anchorIsReference = highlight.anchorFrameIndex == 0
val anchorAlignment = if (anchorIsReference) {
null
} else {
acceptedFrames.firstOrNull { it.frameIndex == highlight.anchorFrameIndex }
?: run {
PLog.w(
TAG,
"Radiance highlight disabled: adjacent normal anchor " +
"${highlight.anchorFrameIndex} was rejected",
)
return null
}
}
return runCatching {
val anchor = frames[highlight.anchorFrameIndex]
uploadRawTexture(anchor.image, curRaw, "Radiance highlight anchor")
buildProxy(curRaw, refProxy, "Radiance highlight anchor")
buildPyramid(referencePyramid)
uploadRawTexture(highlight.shortFrame.image, curRaw, "Radiance highlight short")
buildProxy(
curRaw,
curProxy,
"Radiance highlight short exposure-normalized",
exposureScale = highlight.exposureRatio,
)
buildPyramid(currentPyramid)
drawAlignment(
reference = referencePyramid[alignLevel.coerceAtMost(referencePyramid.lastIndex)],
current = currentPyramid[alignLevel.coerceAtMost(currentPyramid.lastIndex)],
levelScale = 1 shl alignLevel.coerceAtMost(referencePyramid.lastIndex),
outputTexture = flowTexture,
outputGridWidth = gridWidth,
outputGridHeight = gridHeight,
outputTileSpacing = flowGridSpacing,
preAlignment = null,
label = "Radiance highlight anchor-to-short",
)
refineFlow(
referenceProxyTexture = refProxy,
currentProxyTexture = curProxy,
targetFlowTexture = flowTexture,
scratchFlowTexture = flowScratchTexture,
)
smoothFlow(flowTexture, flowScratchTexture)
drawAlignment(
reference = currentPyramid[alignLevel.coerceAtMost(currentPyramid.lastIndex)],
current = referencePyramid[alignLevel.coerceAtMost(referencePyramid.lastIndex)],
levelScale = 1 shl alignLevel.coerceAtMost(currentPyramid.lastIndex),
outputTexture = radianceHighlightReverseFlowTexture,
outputGridWidth = gridWidth,
outputGridHeight = gridHeight,
outputTileSpacing = flowGridSpacing,
preAlignment = null,
label = "Radiance highlight short-to-anchor",
)
refineFlow(
referenceProxyTexture = curProxy,
currentProxyTexture = refProxy,
targetFlowTexture = radianceHighlightReverseFlowTexture,
scratchFlowTexture = flowScratchTexture,
)
smoothFlow(radianceHighlightReverseFlowTexture, flowScratchTexture)
validateRadianceHighlightFlow()
propagateRadianceHighlightFlow(
targetTexture = flowTexture,
guideProxyTexture = refProxy,
label = "anchor-to-short",
)
if (!anchorIsReference) {
copyRgbaTexture(
checkNotNull(anchorAlignment).flowTexture,
radianceHighlightAnchorFlowTexture,
gridWidth,
gridHeight,
"Radiance highlight anchor flow copy",
)
uploadRawTexture(frames.first().image, curRaw, "Radiance highlight reference guide")
buildProxy(curRaw, refProxy, "Radiance highlight reference guide")
propagateRadianceHighlightFlow(
targetTexture = radianceHighlightAnchorFlowTexture,
guideProxyTexture = refProxy,
label = "reference-to-anchor",
)
}
composeRadianceHighlightFlow(anchorIsReference)
summarizeRadianceHighlightAlignment(highlight)
}.onFailure { error ->
PLog.w(TAG, "Radiance highlight alignment failed; preserving normal fusion", error)
}.getOrNull()
}
private fun validateRadianceHighlightFlow() {
val program = radianceHighlightValidateFlowProgram
check(program != 0)
bindFramebufferOutput(flowScratchTexture, "Radiance highlight FB validation")
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(program)
bindTexture(program, "uForwardFlow", 0, flowTexture)
bindTexture(program, "uReverseFlow", 1, radianceHighlightReverseFlowTexture)
GLES31.glUniform2i(uniformLocation(program, "uGridSize"), gridWidth, gridHeight)
GLES31.glUniform2i(uniformLocation(program, "uPlaneSize"), planeWidth, planeHeight)
GLES31.glUniform1i(uniformLocation(program, "uTileSize"), flowGridSpacing)
GLES31.glUniform1f(
uniformLocation(program, "uFbConsistencyStart"),
radianceFusionTuning.highlightFlowFbConsistencyStartPx.coerceAtLeast(0f),
)
GLES31.glUniform1f(
uniformLocation(program, "uFbConsistencyFull"),
radianceFusionTuning.highlightFlowFbConsistencyFullPx.coerceAtLeast(
radianceFusionTuning.highlightFlowFbConsistencyStartPx + 1e-3f,
),
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("Radiance highlight FB validation")
copyRgbaTexture(
flowScratchTexture,
flowTexture,
gridWidth,
gridHeight,
"Radiance highlight validated flow copy",
)
}
private fun propagateRadianceHighlightFlow(
targetTexture: Int,
guideProxyTexture: Int,
label: String,
) {
val passes = radianceFusionTuning.highlightFlowPropagationPasses.coerceIn(0, 64)
if (passes == 0) return
val program = radianceHighlightPropagateFlowProgram
check(program != 0)
repeat(passes) { pass ->
val input = if ((pass and 1) == 0) targetTexture else flowScratchTexture
val output = if ((pass and 1) == 0) flowScratchTexture else targetTexture
bindFramebufferOutput(output, "Radiance highlight propagate $label pass $pass")
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(program)
bindTexture(program, "uInputFlow", 0, input)
bindTexture(program, "uGuideProxy", 1, guideProxyTexture)
GLES31.glUniform2i(uniformLocation(program, "uGridSize"), gridWidth, gridHeight)
GLES31.glUniform2i(uniformLocation(program, "uPlaneSize"), planeWidth, planeHeight)
GLES31.glUniform1i(uniformLocation(program, "uTileSize"), flowGridSpacing)
GLES31.glUniform1f(
uniformLocation(program, "uConfidenceDecay"),
radianceFusionTuning.highlightFlowPropagationDecay.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uDirectConfidence"),
radianceFusionTuning.highlightFlowSeedConfidence.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uMinimumConfidence"),
radianceFusionTuning.highlightFlowMinimumConfidence.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uFlowConsistencySigma"),
radianceFusionTuning.highlightFlowFbConsistencyFullPx.coerceAtLeast(0.25f),
)
GLES31.glUniform1f(
uniformLocation(program, "uGuideEdgeSigma"),
radianceFusionTuning.highlightFlowGuideEdgeSigma.coerceAtLeast(1e-3f),
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("Radiance highlight propagate $label pass $pass")
}
if ((passes and 1) != 0) {
copyRgbaTexture(
flowScratchTexture,
targetTexture,
gridWidth,
gridHeight,
"Radiance highlight propagated $label copy",
)
}
}
private fun composeRadianceHighlightFlow(anchorIsReference: Boolean) {
val program = radianceHighlightComposeFlowProgram
check(program != 0)
bindFramebufferOutput(
radianceHighlightComposedFlowTexture,
"Radiance highlight compose flow",
)
GLES30.glViewport(0, 0, gridWidth, gridHeight)
GLES30.glUseProgram(program)
bindTexture(program, "uReferenceToAnchorFlow", 0, radianceHighlightAnchorFlowTexture)
bindTexture(program, "uAnchorToShortFlow", 1, flowTexture)
GLES31.glUniform2i(uniformLocation(program, "uGridSize"), gridWidth, gridHeight)
GLES31.glUniform2i(uniformLocation(program, "uPlaneSize"), planeWidth, planeHeight)
GLES31.glUniform1i(uniformLocation(program, "uTileSize"), flowGridSpacing)
GLES31.glUniform1i(
uniformLocation(program, "uAnchorIsReference"),
if (anchorIsReference) 1 else 0,
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("Radiance highlight compose flow")
}
private fun summarizeRadianceHighlightAlignment(
highlight: RawRadianceHighlightFrame,
): RadianceHighlightAlignment? {
val values = readFlowTexture(
texture = radianceHighlightComposedFlowTexture,
textureWidth = gridWidth,
textureHeight = gridHeight,
label = "Radiance highlight composed flow",
)
val confidenceThreshold = radianceFusionTuning.highlightFlowMinimumConfidence
.coerceIn(0f, 1f)
var validTiles = 0
var minX = 0f
var maxX = 0f
var minY = 0f
var maxY = 0f
val quadrants = BooleanArray(4)
var offset = 0
while (offset + 3 < values.size) {
val tileIndex = offset / 4
val flowX = values[offset]
val flowY = values[offset + 1]
val confidence = values[offset + 3]
if (flowX.isFinite() && flowY.isFinite() && confidence.isFinite() &&
confidence >= confidenceThreshold
) {
minX = minOf(minX, flowX)
maxX = maxOf(maxX, flowX)
minY = minOf(minY, flowY)
maxY = maxOf(maxY, flowY)
validTiles++
val tileX = tileIndex % gridWidth
val tileY = tileIndex / gridWidth
val quadrant = (if (tileY >= gridHeight / 2) 2 else 0) +
if (tileX >= gridWidth / 2) 1 else 0
quadrants[quadrant] = true
}
offset += 4
}
val totalTiles = (gridWidth * gridHeight).coerceAtLeast(1)
val validFraction = validTiles.toFloat() / totalTiles
val coveredQuadrants = quadrants.count { it }
val minimumValidTiles = radianceFusionTuning.highlightFlowMinimumValidTiles
.coerceAtLeast(1)
val minimumQuadrants = radianceFusionTuning.highlightFlowMinimumQuadrants
.coerceIn(1, 4)
if (!hasRadianceHighlightAlignmentSupport(
validTileCount = validTiles,
coveredQuadrants = coveredQuadrants,
minimumValidTiles = minimumValidTiles,
minimumQuadrants = minimumQuadrants,
)
) {
PLog.w(
TAG,
"Radiance highlight alignment rejected coverage=$validFraction " +
"validTiles=$validTiles/$totalTiles requiredTiles=$minimumValidTiles " +
"quadrants=$coveredQuadrants/$minimumQuadrants",
)
return null
}
PLog.i(
TAG,
"Radiance highlight alignment accepted coverage=$validFraction " +
"validTiles=$validTiles/$totalTiles quadrants=$coveredQuadrants " +
"flow=[$minX,$maxX]x[$minY,$maxY] " +
"ratio=${highlight.exposureRatio} baseline=${highlight.baselineExposureEv}EV",
)
return RadianceHighlightAlignment(
frame = highlight,
flowTexture = radianceHighlightComposedFlowTexture,
minFlowXPlanePx = minX,
maxFlowXPlanePx = maxX,
minFlowYPlanePx = minY,
maxFlowYPlanePx = maxY,
validTileFraction = validFraction,
coveredQuadrants = coveredQuadrants,
)
}
private fun computeRobustness() {
GLES31.glUseProgram(robustnessProgram)
bindTexture(robustnessProgram, "uReference", 0, refProxy)
@@ -4510,6 +4918,7 @@ class GlesRawStacker(
acceptedFrames: List<AcceptedSuperResolutionFrame>,
candidateFrameCount: Int,
outputBuffer: ByteBuffer,
highlightAlignment: RadianceHighlightAlignment?,
): ReadOutputTiming {
check(radianceFusionEnabled)
check(radianceTiles.isNotEmpty())
@@ -4524,6 +4933,11 @@ class GlesRawStacker(
requiredRcdWidth = max(requiredRcdWidth, frameRegion.width)
requiredRcdHeight = max(requiredRcdHeight, frameRegion.height)
}
highlightAlignment?.let { highlight ->
val highlightRegion = radianceSourceRegion(tile, highlight.flowBounds())
requiredRcdWidth = max(requiredRcdWidth, highlightRegion.width)
requiredRcdHeight = max(requiredRcdHeight, highlightRegion.height)
}
}
ensureRadianceTileResources(requiredRcdWidth, requiredRcdHeight)
val readbackAllocStart = System.currentTimeMillis()
@@ -4563,6 +4977,7 @@ class GlesRawStacker(
"maxSource=${requiredRcdWidth}x$requiredRcdHeight " +
"rejectionOverlay=$visualizeRadianceFusionRejections " +
"srDetailOverlay=$visualizeRadianceSrDetail " +
"highlightOverlay=$visualizeRadianceHighlightReconstruction " +
"candidates=$candidateFrameCount accepted=${acceptedFrames.size}"
}
try {
@@ -4618,10 +5033,22 @@ class GlesRawStacker(
)
}
val highlightSourceRegion = highlightAlignment?.let { highlight ->
radianceSourceRegion(tile, highlight.flowBounds()).also { sourceRegion ->
reconstructRadianceReferenceTile(
image = highlight.frame.shortFrame.image,
sourceRegion = sourceRegion,
label = "Radiance highlight tile ${tile.index}",
)
}
}
normalizeRadianceTile(
tile,
globalAlignmentRejectCount = 0,
acceptedFusionFrameCount = if (rejectionFrame != null) 1 else 0,
highlightAlignment = highlightAlignment,
highlightSourceRegion = highlightSourceRegion,
)
val timing = readRadianceOutputTile(readbackScratch, output, tile.outputCore)
totalGlReadMs += timing.glReadMs
@@ -4645,9 +5072,17 @@ class GlesRawStacker(
copyMs = totalCopyMs,
allocMs = readbackAllocMs,
mode = if (radianceUsesVgnSemanticBackend) {
"radiance-vgn-semantic-rgb16-tiled"
if (highlightAlignment != null) {
"radiance-vgn-semantic-highlight-rgb16-tiled"
} else {
"radiance-vgn-semantic-rgb16-tiled"
}
} else {
"radiance-rcd-fallback-rgb16-tiled"
if (highlightAlignment != null) {
"radiance-rcd-fallback-highlight-rgb16-tiled"
} else {
"radiance-rcd-fallback-rgb16-tiled"
}
},
)
}
@@ -5183,102 +5618,181 @@ class GlesRawStacker(
tile: RadianceTile,
globalAlignmentRejectCount: Int,
acceptedFusionFrameCount: Int,
highlightAlignment: RadianceHighlightAlignment?,
highlightSourceRegion: RadianceTileRect?,
) {
require((highlightAlignment == null) == (highlightSourceRegion == null))
val program = if (highlightAlignment != null) {
check(radianceHighlightNormalizeProgram != 0)
radianceHighlightNormalizeProgram
} else {
normalizeSuperResolutionProgram
}
bindFramebufferOutput(outputTexture, "normalizeRadianceTile")
GLES30.glViewport(0, 0, tile.outputCore.width, tile.outputCore.height)
GLES30.glUseProgram(normalizeSuperResolutionProgram)
bindTexture(normalizeSuperResolutionProgram, "uNrSumRg", 0, superResolutionAccumulatorTexture)
bindTexture(normalizeSuperResolutionProgram, "uNrSumBw", 1, superResolutionAccumulatorBwTexture)
bindTexture(normalizeSuperResolutionProgram, "uNrWeightRg", 2, radianceNrWeightRgTexture)
bindTexture(normalizeSuperResolutionProgram, "uDetailSumRg", 3, superResolutionAccumulatorBTexture)
bindTexture(normalizeSuperResolutionProgram, "uDetailSumBw", 4, radianceDetailBwTexture)
bindTexture(normalizeSuperResolutionProgram, "uDetailWeightRg", 5, radianceDetailWeightRgTexture)
bindTexture(normalizeSuperResolutionProgram, "uReferenceBase", 6, radianceReferenceBaseTexture)
GLES30.glUseProgram(program)
bindTexture(program, "uNrSumRg", 0, superResolutionAccumulatorTexture)
bindTexture(program, "uNrSumBw", 1, superResolutionAccumulatorBwTexture)
bindTexture(program, "uNrWeightRg", 2, radianceNrWeightRgTexture)
bindTexture(program, "uDetailSumRg", 3, superResolutionAccumulatorBTexture)
bindTexture(program, "uDetailSumBw", 4, radianceDetailBwTexture)
bindTexture(program, "uDetailWeightRg", 5, radianceDetailWeightRgTexture)
bindTexture(program, "uReferenceBase", 6, radianceReferenceBaseTexture)
if (visualizeRadianceFusionRejections) {
bindTexture(
normalizeSuperResolutionProgram,
program,
"uFusionRejections",
7,
radianceFusionRejectionTexture,
)
}
setCommonUniforms(normalizeSuperResolutionProgram)
setCommonUniforms(program)
GLES31.glUniform2i(
uniformLocation(normalizeSuperResolutionProgram, "uAccumulatorOrigin"),
uniformLocation(program, "uAccumulatorOrigin"),
tile.outputWorking.left,
tile.outputWorking.top,
)
GLES31.glUniform2i(
uniformLocation(normalizeSuperResolutionProgram, "uAccumulatorSize"),
uniformLocation(program, "uAccumulatorSize"),
tile.outputWorking.width,
tile.outputWorking.height,
)
GLES31.glUniform2i(
uniformLocation(normalizeSuperResolutionProgram, "uOutputOrigin"),
uniformLocation(program, "uOutputOrigin"),
tile.outputCore.left,
tile.outputCore.top,
)
if (visualizeRadianceFusionRejections || visualizeRadianceSrDetail) {
if (visualizeRadianceFusionRejections) {
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uGlobalAlignmentRejectCount"),
uniformLocation(program, "uGlobalAlignmentRejectCount"),
globalAlignmentRejectCount.coerceAtLeast(0).toFloat(),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uAcceptedFusionFrameCount"),
uniformLocation(program, "uAcceptedFusionFrameCount"),
acceptedFusionFrameCount.coerceAtLeast(0).toFloat(),
)
}
GLES31.glUniform3fv(
uniformLocation(normalizeSuperResolutionProgram, "uDebugNeutralRgb"),
uniformLocation(program, "uDebugNeutralRgb"),
1,
radianceDebugNeutralColor,
0,
)
}
setRadianceNormalizeUniforms()
setPostfilterUniforms(normalizeSuperResolutionProgram)
if (highlightAlignment != null && highlightSourceRegion != null) {
bindTexture(program, "uHighlightRgb", 8, radianceRgbTileTexture)
bindTexture(program, "uHighlightRaw", 9, rcdRawRegionTexture)
bindTexture(program, "uHighlightFlow", 10, highlightAlignment.flowTexture)
bindTexture(program, "uReferenceRaw", 11, refRaw)
GLES31.glUniform2i(
uniformLocation(program, "uHighlightSourceOrigin"),
highlightSourceRegion.left,
highlightSourceRegion.top,
)
GLES31.glUniform2i(
uniformLocation(program, "uHighlightSourceSize"),
highlightSourceRegion.width,
highlightSourceRegion.height,
)
GLES31.glUniform2i(
uniformLocation(program, "uHighlightFlowGridSize"),
gridWidth,
gridHeight,
)
GLES31.glUniform2i(uniformLocation(program, "uInputSize"), width, height)
GLES31.glUniform2i(uniformLocation(program, "uOutputSize"), outputWidth, outputHeight)
GLES31.glUniform1i(
uniformLocation(program, "uHighlightFlowTileSize"),
flowGridSpacing,
)
setRadianceHighlightUniforms(program, highlightAlignment.frame.exposureRatio)
}
setRadianceNormalizeUniforms(program)
setPostfilterUniforms(program)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("normalizeRadianceTile ${tile.index}")
}
private fun setRadianceNormalizeUniforms() {
private fun setRadianceNormalizeUniforms(program: Int = normalizeSuperResolutionProgram) {
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceStart"),
uniformLocation(program, "uNrConfidenceStart"),
radianceFusionTuning.nrConfidenceStart.coerceAtLeast(0f),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceFull"),
uniformLocation(program, "uNrConfidenceFull"),
radianceFusionTuning.nrConfidenceFull.coerceAtLeast(radianceFusionTuning.nrConfidenceStart),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceStart"),
uniformLocation(program, "uDetailConfidenceStart"),
radianceFusionTuning.detailConfidenceStart.coerceAtLeast(0f),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceFull"),
uniformLocation(program, "uDetailConfidenceFull"),
radianceFusionTuning.detailConfidenceFull.coerceAtLeast(radianceFusionTuning.detailConfidenceStart),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uReferenceDetailFloor"),
uniformLocation(program, "uReferenceDetailFloor"),
radianceFusionTuning.referenceDetailFloor.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uDetailChromaStrength"),
uniformLocation(program, "uDetailChromaStrength"),
radianceFusionTuning.detailChromaStrength.coerceIn(0f, 1f),
)
GLES31.glUniform3f(
uniformLocation(normalizeSuperResolutionProgram, "uCalculationGains"),
uniformLocation(program, "uCalculationGains"),
demosaicCalculationWbGains[0],
1f,
demosaicCalculationWbGains[3],
)
GLES31.glUniform1f(
uniformLocation(normalizeSuperResolutionProgram, "uBilateralNoiseScale"),
uniformLocation(program, "uBilateralNoiseScale"),
radianceFusionTuning.bilateralNoiseScale.coerceAtLeast(1f),
)
}
private fun setRadianceHighlightUniforms(program: Int, exposureRatio: Float) {
GLES31.glUniform1f(
uniformLocation(program, "uHighlightExposureRatio"),
exposureRatio.coerceAtLeast(1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightNormalClipStart"),
radianceFusionTuning.highlightNormalClipStart.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightNormalClipFull"),
radianceFusionTuning.highlightNormalClipFull.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightShortClipStart"),
radianceFusionTuning.highlightShortClipStart.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightShortClipFull"),
radianceFusionTuning.highlightShortClipFull.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightShortSignalStart"),
radianceFusionTuning.highlightShortSignalStart.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightShortSignalFull"),
radianceFusionTuning.highlightShortSignalFull.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightFlowMinimumConfidence"),
radianceFusionTuning.highlightFlowMinimumConfidence.coerceIn(0f, 1f),
)
GLES31.glUniform1f(
uniformLocation(program, "uHighlightFlowFullConfidence"),
radianceFusionTuning.highlightFlowFullConfidence.coerceIn(
radianceFusionTuning.highlightFlowMinimumConfidence.coerceIn(0f, 1f),
1f,
),
)
}
private fun readRadianceOutputTile(
scratch: ByteBuffer,
output: ShortBuffer,
@@ -6446,15 +6960,23 @@ class GlesRawStacker(
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(program, "uHighlightSuppressionStrength"),
hwmfBlend.highlightSuppressionStrength
if (radianceFusionEnabled) 1f else hwmfBlend.highlightSuppressionStrength
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(program, "uHighlightSuppressionStart"),
hwmfBlend.highlightSuppressionStart
if (radianceFusionEnabled) {
radianceFusionTuning.highlightNormalClipStart
} else {
hwmfBlend.highlightSuppressionStart
}
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(program, "uHighlightSuppressionEnd"),
hwmfBlend.highlightSuppressionEnd
if (radianceFusionEnabled) {
radianceFusionTuning.highlightNormalClipFull
} else {
hwmfBlend.highlightSuppressionEnd
}
)
}
@@ -30,6 +30,7 @@ data class RawStackResult(
val bufferLayout: RawStackBufferLayout = RawStackBufferLayout.CFA,
val inputRowStepSamples: Int? = null,
val inputColStepSamples: Int? = null,
val baselineExposureEv: Float? = null,
)
data class RawHdrStackFrame(
@@ -5,6 +5,7 @@ import com.hinnka.mycamera.model.SafeImage
enum class RawBurstFrameRole {
NORMAL,
HIGHLIGHT_SHORT,
HDR_SHORT,
HDR_LONG,
}
@@ -8,6 +8,7 @@ data class RawStackDebugConfig(
val visualizeRadianceFusionRejections: Boolean = false,
val radianceFusionRejectionFrameOrdinal: Int = 0,
val visualizeRadianceSrDetail: Boolean = false,
val visualizeRadianceHighlightReconstruction: Boolean = false,
val logRadianceFusionParticipation: Boolean = false,
val radianceFusionStatsSampleStep: Int = 8,
val sampleStep: Int = 16,
@@ -54,12 +55,15 @@ data class RawStackDebugConfig(
return RawStackDebugConfig(
visualizeRadianceFusionRejections = ENABLE_RADIANCE_FUSION_REJECTION_OVERLAY,
visualizeRadianceSrDetail = ENABLE_RADIANCE_SR_DETAIL_OVERLAY,
visualizeRadianceHighlightReconstruction =
ENABLE_RADIANCE_HIGHLIGHT_RECONSTRUCTION_OVERLAY,
logRadianceFusionParticipation = ENABLE_RADIANCE_FUSION_PARTICIPATION_LOG,
)
}
private const val ENABLE_RADIANCE_FUSION_REJECTION_OVERLAY = false
private const val ENABLE_RADIANCE_SR_DETAIL_OVERLAY = false
private const val ENABLE_RADIANCE_HIGHLIGHT_RECONSTRUCTION_OVERLAY = false
private const val ENABLE_RADIANCE_FUSION_PARTICIPATION_LOG = true
}
}
@@ -45,8 +45,10 @@ 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.RawBurstFrameRole
import com.hinnka.mycamera.processor.RawBurstGyroSelector
import com.hinnka.mycamera.processor.RawBurstReferencePlanner
import com.hinnka.mycamera.processor.RawRadianceExposurePlanner
import com.hinnka.mycamera.processor.RawStackFrame
import com.hinnka.mycamera.raw.ColorSpace
import com.hinnka.mycamera.raw.DcpProfileParser
@@ -95,6 +97,7 @@ data class MultipleExposureFrame(
private data class PendingRawStackFrame(
val frame: RawStackFrame,
val captureInfo: CaptureInfo,
val captureResult: CaptureResult?,
)
@@ -1424,11 +1427,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
handleMultipleExposureFrameCaptured(image, captureInfo)
}
} else if (state.value.useMFNR || state.value.useMFSR) {
val count = state.value.multiFrameCount
val count = MultiFrameConfig.captureFrameCount(state.value.multiFrameCount)
PLog.d(TAG, "Burst frame received: ${pendingRawStackFrames.size + 1}/$count")
pendingRawStackFrames.add(
PendingRawStackFrame(
frame = rawStackFrame(image, captureResult, frameMetadata),
captureInfo = captureInfo,
captureResult = captureResult,
)
)
@@ -1437,14 +1441,22 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
.sortedBy { it.frame.sensorTimestampNs }
pendingRawStackFrames.clear()
viewModelScope.launch {
val exposurePlan = RawRadianceExposurePlanner.plan(
exposureProducts = chronologicalFrames.map { it.frame.exposureProduct },
frameRoles = chronologicalFrames.map { it.frame.role },
)
val normalFrames = exposurePlan.normalIndices.map(chronologicalFrames::get)
val auxiliaryFrames = chronologicalFrames.indices
.filterNot(exposurePlan.normalIndices.toSet()::contains)
.map(chronologicalFrames::get)
val gyroSelection = withContext(Dispatchers.Default) {
RawBurstGyroSelector.select(chronologicalFrames.map { it.frame })
RawBurstGyroSelector.select(normalFrames.map { it.frame })
}
gyroSelection.rejectedIndices.forEach { rejectedIndex ->
chronologicalFrames[rejectedIndex].frame.image.close()
normalFrames[rejectedIndex].frame.image.close()
}
val gyroOrderedFrames = gyroSelection.orderedAcceptedIndices.map { index ->
chronologicalFrames[index]
normalFrames[index]
}
val proxyConfig = rawAlignmentProxyConfig(
characteristics = characteristics,
@@ -1464,7 +1476,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
} else {
null
}
val orderedFrames = referencePlan?.orderedIndices?.map { index ->
val orderedNormalFrames = referencePlan?.orderedIndices?.map { index ->
val pending = gyroOrderedFrames[index]
pending.copy(
frame = pending.frame.copy(
@@ -1472,21 +1484,42 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
),
)
} ?: gyroOrderedFrames
val orderedFrames = orderedNormalFrames + auxiliaryFrames
if (gyroSelection.rejectedIndices.isNotEmpty() || referencePlan != null) {
PLog.i(
TAG,
"RAW burst plan: gyroReference=${gyroSelection.referenceOriginalIndex}, " +
"reference=${referencePlan?.referenceOriginalIndex ?: 0}, " +
"accepted=${orderedFrames.size}, " +
"normal=${orderedNormalFrames.size}, " +
"short=${if (exposurePlan.shortIndex != null) 1 else 0}, " +
"rejected=${gyroSelection.rejectedIndices.joinToString()}, " +
"cost=${referencePlan?.referenceCost}",
)
}
val framesToProcess = orderedFrames.map { it.frame }
val referenceCaptureResult = orderedFrames.firstOrNull()?.captureResult ?: captureResult
val isRawStack = orderedNormalFrames.firstOrNull()?.frame?.image?.format
?.let(::isRawCaptureFormat) == true
val processingFrames = if (isRawStack) {
orderedFrames
} else {
auxiliaryFrames.forEach { it.frame.image.close() }
if (auxiliaryFrames.isNotEmpty()) {
PLog.i(
TAG,
"Excluded ${auxiliaryFrames.size} short/auxiliary frames from " +
"non-RAW MFNR/MFSR accumulation",
)
}
orderedNormalFrames
}
val framesToProcess = processingFrames.map { it.frame }
val referenceCaptureInfo = orderedNormalFrames.firstOrNull()?.captureInfo
?: captureInfo
val referenceCaptureResult = orderedNormalFrames.firstOrNull()?.captureResult
?: captureResult
processStacking(
frames = framesToProcess,
captureInfo = captureInfo,
captureInfo = referenceCaptureInfo,
characteristics = characteristics,
captureResult = referenceCaptureResult,
)
@@ -5094,6 +5127,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rollingShutterSkewNs = metadata?.rollingShutterSkewNs
?: captureResult?.get(CaptureResult.SENSOR_ROLLING_SHUTTER_SKEW),
gyroWindow = metadata?.gyroWindow,
role = when (
metadata?.multiFrameCaptureRole
?: (captureResult?.request?.tag as? MultiFrameCaptureRole)
) {
MultiFrameCaptureRole.SHORT -> RawBurstFrameRole.HIGHLIGHT_SHORT
else -> RawBurstFrameRole.NORMAL
},
)
}
@@ -15,4 +15,20 @@ class MultiFrameConfigTest {
assertEquals(MultiFrameConfig.DEFAULT_FRAME_COUNT, MultiFrameConfig.normalizeFrameCount(6))
assertEquals(MultiFrameConfig.MAX_FRAME_COUNT, MultiFrameConfig.normalizeFrameCount(100))
}
@Test
fun configuredFrameCountIncludesOneShortFrame() {
assertEquals(
MultiFrameConfig.DEFAULT_FRAME_COUNT - 1,
MultiFrameConfig.normalFrameCount(MultiFrameConfig.DEFAULT_FRAME_COUNT),
)
assertEquals(
MultiFrameConfig.DEFAULT_FRAME_COUNT,
MultiFrameConfig.captureFrameCount(MultiFrameConfig.DEFAULT_FRAME_COUNT),
)
assertEquals(
MultiFrameConfig.MAX_FRAME_COUNT,
MultiFrameConfig.captureFrameCount(Int.MAX_VALUE),
)
}
}
@@ -6,6 +6,64 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class GlesRawRadianceFusionShadersTest {
@Test
fun highlightFlowRejectsForwardBackwardInconsistencyBeforePropagation() {
val validation = GlesRawRadianceFusionShaders.validateHighlightFlow
val propagation = GlesRawRadianceFusionShaders.propagateHighlightFlow
val composition = GlesRawRadianceFusionShaders.composeHighlightFlow
assertTrue(validation.contains("forward.rg + reverse.rg"))
assertTrue(validation.contains("min(forward.a, reverse.a) * consistency"))
assertTrue(propagation.contains("uConfidenceDecay"))
assertTrue(propagation.contains("uMinimumConfidence"))
assertTrue(propagation.contains("smoothstep("))
assertTrue(propagation.contains("sampleValue.a * support"))
assertTrue(propagation.contains("variance"))
assertTrue(propagation.contains("uGuideProxy"))
assertTrue(propagation.contains("min(centerGuide.g, neighborGuide.g) < 0.5"))
assertTrue(
composition.contains("referenceToAnchorFlow.rg + anchorToShortFlow.rg"),
)
assertTrue(
composition.contains("referenceToAnchorFlow.a * anchorToShortFlow.a"),
)
}
@Test
fun highlightCompositionUsesOneSharedMaskAndShortExposureOutputDomain() {
val shader = GlesRawRadianceFusionShaders.normalize(
showRejections = false,
reconstructHighlights = true,
)
assertTrue(shader.contains("shortNotClipped * shortHasSignal * highlightFlowConfidence"))
assertTrue(shader.contains("uniform highp usampler2D uReferenceRaw"))
assertTrue(shader.contains("float normalPeak = referenceRawPeak(referenceRawPosition)"))
assertTrue(shader.contains("float coreShortSelection = saturatedCore * step(0.5, shortReliability)"))
assertTrue(shader.contains("float shoulderBlend = (1.0 - saturatedCore)"))
assertTrue(shader.contains("uHighlightFlowFullConfidence"))
assertTrue(shader.contains("vec3 normalInShortDomain = rgb /"))
assertTrue(shader.contains("mix(normalInShortDomain, highlightRgb, highlightWeight)"))
assertFalse(shader.contains("vec3 highlightWeight"))
}
@Test
fun highlightReconstructionDebugColorsOnlyParticipatingPixelsGreen() {
val debugShader = GlesRawRadianceFusionShaders.normalize(
showRejections = false,
reconstructHighlights = true,
showHighlightReconstruction = true,
)
val productionShader = GlesRawRadianceFusionShaders.normalize(
showRejections = false,
reconstructHighlights = true,
)
assertTrue(debugShader.contains("if (highlightWeight > 1e-4)"))
assertTrue(debugShader.contains("rgb = vec3(0.0, 1.0, 0.0)"))
assertFalse(productionShader.contains("rgb = vec3(0.0, 1.0, 0.0)"))
}
@Test
fun debugNeutralIsInverseWbNormalizedToSensorCeiling() {
val neutral = radianceDebugNeutralRgb(floatArrayOf(2f, 1f, 1f, 4f))
@@ -0,0 +1,57 @@
package com.hinnka.mycamera.processor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class RawRadianceExposurePlannerTest {
@Test
fun taggedShortFrameIsExcludedEvenWhenExposureMetadataMatchesNormalFrames() {
val plan = RawRadianceExposurePlanner.plan(
exposureProducts = listOf(300.0, 300.0, 300.0),
frameRoles = listOf(
RawBurstFrameRole.NORMAL,
RawBurstFrameRole.NORMAL,
RawBurstFrameRole.HIGHLIGHT_SHORT,
),
)
assertArrayEquals(intArrayOf(0, 1), plan.normalIndices)
assertEquals(2, plan.shortIndex)
assertArrayEquals(IntArray(0), plan.excludedIndices)
}
@Test
fun acceptsOneThirdExposureAfterNormalFrameCluster() {
val plan = RawRadianceExposurePlanner.plan(
listOf(100.0, 101.0, 99.0, 100.5, 33.333, 100.0),
)
assertEquals(100.0, plan.baseExposureProduct!!, 1e-6)
assertArrayEquals(intArrayOf(0, 1, 2, 3, 5), plan.normalIndices)
assertEquals(4, plan.shortIndex)
assertArrayEquals(IntArray(0), plan.excludedIndices)
assertArrayEquals(intArrayOf(0, 1, 2, 3, 5, 4), plan.acceptedIndices)
}
@Test
fun rejectsExposureOutliersThatAreNotThePlannedShortFrame() {
val plan = RawRadianceExposurePlanner.plan(
listOf(100.0, 100.0, 33.0, 250.0, 100.0),
)
assertArrayEquals(intArrayOf(0, 1, 4), plan.normalIndices)
assertEquals(2, plan.shortIndex)
assertArrayEquals(intArrayOf(3), plan.excludedIndices)
}
@Test
fun preservesSameExposureBurstsWithoutInventingShortFrame() {
val plan = RawRadianceExposurePlanner.plan(listOf(100.0, 101.0, 99.0))
assertArrayEquals(intArrayOf(0, 1, 2), plan.normalIndices)
assertNull(plan.shortIndex)
assertArrayEquals(IntArray(0), plan.excludedIndices)
}
}
@@ -0,0 +1,43 @@
package com.hinnka.mycamera.processor
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RawRadianceHighlightAlignmentSupportTest {
@Test
fun acceptsSparseButSpatiallyDistributedValidatedFlow() {
assertTrue(
hasRadianceHighlightAlignmentSupport(
validTileCount = 166,
coveredQuadrants = 3,
minimumValidTiles = 16,
minimumQuadrants = 2,
),
)
}
@Test
fun rejectsTooFewValidatedCorrespondences() {
assertFalse(
hasRadianceHighlightAlignmentSupport(
validTileCount = 15,
coveredQuadrants = 4,
minimumValidTiles = 16,
minimumQuadrants = 2,
),
)
}
@Test
fun rejectsSpatiallyConcentratedCorrespondences() {
assertFalse(
hasRadianceHighlightAlignmentSupport(
validTileCount = 166,
coveredQuadrants = 1,
minimumValidTiles = 16,
minimumQuadrants = 2,
),
)
}
}