From e8cfc9dfb0a7ca8692dbc75385b0d6d39cf340ca Mon Sep 17 00:00:00 2001 From: Hinnka Date: Sun, 19 Jul 2026 16:24:29 +0800 Subject: [PATCH] feat: radiance (1) --- .../processor/GlesRawStackerShaderTest.kt | 79 +- .../mycamera/camera/Camera2Controller.kt | 67 +- .../com/hinnka/mycamera/camera/CameraState.kt | 2 +- .../mycamera/camera/MultiFrameConfig.kt | 4 + .../processor/GlesRadianceReconstruction.kt | 482 +++ .../hinnka/mycamera/processor/GlesRawHdr.kt | 49 - .../processor/GlesRawRadianceFusion.kt | 765 ++++- .../hinnka/mycamera/processor/GlesRawRcd.kt | 59 + .../mycamera/processor/GlesRawStacker.kt | 3007 +++++++++++++---- .../mycamera/processor/RadianceTilePlanner.kt | 156 + .../mycamera/processor/RawNoiseModel.kt | 77 +- .../mycamera/processor/RawStackDebugConfig.kt | 17 +- .../processor/RawStackTuningProfile.kt | 7 +- .../RawSuperResolutionStripePlanner.kt | 7 +- .../com/hinnka/mycamera/raw/RcdShaders.kt | 62 +- .../mycamera/camera/MultiFrameConfigTest.kt | 18 + .../GlesRadianceReconstructionTest.kt | 88 + .../GlesRawRadianceFusionShadersTest.kt | 188 ++ .../processor/RadianceTilePlannerTest.kt | 80 + .../mycamera/processor/RawNoiseModelTest.kt | 64 +- .../RawSuperResolutionStripePlannerTest.kt | 1 + .../com/hinnka/mycamera/raw/RcdShadersTest.kt | 10 +- docs/gles-driver-compatibility.md | 88 +- ...raw-stack-mfnr-mfsr-implementation-plan.md | 4 +- 24 files changed, 4386 insertions(+), 995 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/GlesRadianceReconstruction.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/GlesRawRcd.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/RadianceTilePlanner.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/camera/MultiFrameConfigTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/GlesRadianceReconstructionTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/GlesRawRadianceFusionShadersTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/processor/RadianceTilePlannerTest.kt diff --git a/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt b/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt index cb3b8e94..5811c79e 100644 --- a/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt +++ b/app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt @@ -2,6 +2,7 @@ package com.hinnka.mycamera.processor import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @@ -57,7 +58,10 @@ class GlesRawStackerShaderTest { mode = RawStackMode.MFSR, superResolution = RawStackSuperResolutionTuning(outputScale = 1.5f), ), - debugConfig = RawStackDebugConfig.Disabled, + debugConfig = RawStackDebugConfig( + visualizeRadianceFusionRejections = true, + visualizeRadianceSrDetail = true, + ), fusionPipeline = RawFusionPipeline.RADIANCE_RGB, ) try { @@ -66,34 +70,73 @@ class GlesRawStackerShaderTest { invokePrivate(stacker, "initPrograms") invokePrivate(stacker, "initResources") invokePrivate(stacker, "applyRawRenderState") - invokePrivate(stacker, "ensureRadianceRcdStripeResources", 64) - invokePrivate(stacker, "runRcdStripe", 0, 64, "instrumentation Radiance", true) + assertTrue( + "Radiance must initialize its VGN reference adapter", + readPrivateInt(stacker, "radianceVgnFinalProgram") != 0, + ) + assertTrue( + "Radiance must initialize its non-reference semantic resolver", + readPrivateInt(stacker, "radianceSemanticResolveProgram") != 0, + ) + // Exercise the Radiance RGBA16F tile-confidence target, not just shader linking. + // RG are independent NR/detail confidence; BA carry NR rejection reason/severity. + invokePrivate(stacker, "computeTileMask") + val sourceRegion = RadianceTileRect(0, 0, 64, 64) + val outputRegion = RadianceTileRect(0, 0, 96, 96) + val tile = RadianceTile( + index = 0, + rawCore = sourceRegion, + outputCore = outputRegion, + outputWorking = outputRegion, + ) + invokePrivate(stacker, "ensureRadianceTileResources", 64, 64) invokePrivate( stacker, - "storeRcdRgbStripe", - readPrivateInt(stacker, "radianceRgbStripeTexture"), - 64, - "instrumentation Radiance RGB store", - 1f, - false, + "runRadianceReferenceVgn", + sourceRegion, + "instrumentation Radiance reference", ) invokePrivate(stacker, "clearSuperResolutionAccumulator") invokePrivate( stacker, "accumulateRadianceFusionFrame", true, - 0, - 64, + sourceRegion, + outputRegion, readPrivateInt(stacker, "flowTexture"), readPrivateInt(stacker, "robustnessTexture"), readPrivateInt(stacker, "tileMaskTexture"), 1f, 1f, 0, - 64, + 0, + outputRegion, + false, ) - invokePrivate(stacker, "captureRadianceReferenceBase", 64) - invokePrivate(stacker, "normalizeSuperResolutionStripe", 0, 64, 0) + invokePrivate(stacker, "captureRadianceReferenceBase", 96, 96) + invokePrivate( + stacker, + "runRadianceSemanticProxy", + sourceRegion, + "instrumentation Radiance non-reference", + ) + invokePrivate( + stacker, + "accumulateRadianceFusionFrame", + false, + sourceRegion, + outputRegion, + readPrivateInt(stacker, "flowTexture"), + readPrivateInt(stacker, "robustnessTexture"), + readPrivateInt(stacker, "tileMaskTexture"), + 1f, + 1f, + 0, + 1, + outputRegion, + true, + ) + invokePrivate(stacker, "normalizeRadianceTile", tile, 1, 1) } finally { invokePrivate(stacker, "release") } @@ -120,6 +163,7 @@ class GlesRawStackerShaderTest { invokePrivate(stacker, "initHdrPrograms") invokePrivate(stacker, "initResources") invokePrivate(stacker, "applyRawRenderState") + assertUnifiedRcdPpgInitialized(stacker, "HDR") val refRaw = readPrivateInt(stacker, "refRaw") invokePrivate(stacker, "clearAccumulator") @@ -214,4 +258,11 @@ class GlesRawStackerShaderTest { } } + private fun assertUnifiedRcdPpgInitialized(stacker: GlesRawStacker, mode: String) { + assertTrue( + "$mode must initialize the shared RCD photo-border PPG program", + readPrivateInt(stacker, "rcdRegionBorderPpgProgram") != 0, + ) + } + } diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index c61efb5f..b431a39e 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -438,10 +438,7 @@ class Camera2Controller(private val context: Context) { private fun resolveImageReaderMaxImages(): Int { val currentState = _state.value - val multiFrameCount = currentState.multiFrameCount.coerceIn( - MultiFrameConfig.MIN_FRAME_COUNT, - MultiFrameConfig.MAX_FRAME_COUNT - ) + val multiFrameCount = MultiFrameConfig.normalizeFrameCount(currentState.multiFrameCount) val requestedImages = when { currentState.useHdrComposition && currentState.useMFNR -> maxOf( @@ -465,10 +462,8 @@ class Camera2Controller(private val context: Context) { currentState.burstCapturing -> BURST_CAPTURE_BATCH_SIZE currentState.hdrBracketCapturing -> currentState.hdrBracketFrameCount .coerceAtLeast(HDR_BRACKET_BASE_CAPTURE_COUNT) - currentState.useMFNR || currentState.useMFSR -> currentState.multiFrameCount.coerceIn( - MultiFrameConfig.MIN_FRAME_COUNT, - MultiFrameConfig.MAX_FRAME_COUNT - ) + currentState.useMFNR || currentState.useMFSR -> + MultiFrameConfig.normalizeFrameCount(currentState.multiFrameCount) else -> 1 } @@ -5008,7 +5003,15 @@ class Camera2Controller(private val context: Context) { } fun setUseMFNR(useMultiFrame: Boolean) { - _state.value = _state.value.copy(useMFNR = useMultiFrame) + val currentState = _state.value + _state.value = currentState.copy( + useMFNR = useMultiFrame, + multiFrameCount = if (useMultiFrame) { + MultiFrameConfig.normalizeFrameCount(currentState.multiFrameCount) + } else { + currentState.multiFrameCount + }, + ) } fun setUseHdrComposition(useHdrComposition: Boolean) { @@ -5016,7 +5019,15 @@ class Camera2Controller(private val context: Context) { } fun setUseMFSR(useSuperResolution: Boolean) { - _state.value = _state.value.copy(useMFSR = useSuperResolution) + val currentState = _state.value + _state.value = currentState.copy( + useMFSR = useSuperResolution, + multiFrameCount = if (useSuperResolution) { + MultiFrameConfig.normalizeFrameCount(currentState.multiFrameCount) + } else { + currentState.multiFrameCount + }, + ) } fun setUseMultipleExposure(useMultipleExposure: Boolean) { @@ -5032,10 +5043,7 @@ class Camera2Controller(private val context: Context) { fun setMultiFrameCount(multiFrameCount: Int) { _state.value = _state.value.copy( - multiFrameCount = multiFrameCount.coerceIn( - MultiFrameConfig.MIN_FRAME_COUNT, - MultiFrameConfig.MAX_FRAME_COUNT - ) + multiFrameCount = MultiFrameConfig.normalizeFrameCount(multiFrameCount), ) } @@ -5518,10 +5526,7 @@ class Camera2Controller(private val context: Context) { private fun resolveHdrBracketZeroEvFrameCount(state: CameraState): Int { return if (state.useMFNR || state.useMFSR) { - state.multiFrameCount.coerceIn( - MultiFrameConfig.MIN_FRAME_COUNT, - MultiFrameConfig.MAX_FRAME_COUNT - ) + MultiFrameConfig.normalizeFrameCount(state.multiFrameCount) } else { 0 } @@ -5553,6 +5558,8 @@ class Camera2Controller(private val context: Context) { ) return } + val session = captureSession + ?: throw IllegalStateException("Capture session unavailable") val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply { addTarget(reader.surface) @@ -5616,19 +5623,25 @@ class Camera2Controller(private val context: Context) { PLog.d( TAG, - "Capture request built and ready to send. ISO: ${_state.value.iso}, shutter: ${_state.value.shutterSpeed}, AE: ${_state.value.isAutoExposure}" + "Capture request built and ready to send. ISO: ${currentState.iso}, " + + "shutter: ${currentState.shutterSpeed}, AE: ${currentState.isAutoExposure}" ) } - if (state.value.useMFNR || _state.value.useMFSR) { + if (currentState.useMFNR || currentState.useMFSR) { // Burst Mode - val requests = ArrayList() - val request = captureBuilder.build() - for (i in 0 until state.value.multiFrameCount) { - requests.add(request) + val requestedFrameCount = currentState.multiFrameCount + val frameCount = MultiFrameConfig.normalizeFrameCount(requestedFrameCount) + if (frameCount != requestedFrameCount) { + PLog.w( + TAG, + "Normalized invalid multi-frame count $requestedFrameCount to $frameCount", + ) } + val request = captureBuilder.build() + val requests = List(frameCount) { request } - captureSession?.captureBurst(requests, object : CameraCaptureSession.CaptureCallback() { + session.captureBurst(requests, object : CameraCaptureSession.CaptureCallback() { override fun onCaptureStarted( session: CameraCaptureSession, request: CaptureRequest, @@ -5687,7 +5700,7 @@ class Camera2Controller(private val context: Context) { } else { // Single Capture Mode - captureSession?.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() { + session.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() { override fun onCaptureStarted( session: CameraCaptureSession, request: CaptureRequest, @@ -5737,6 +5750,8 @@ class Camera2Controller(private val context: Context) { } catch (e: Exception) { PLog.e(TAG, "Failed to perform capture", e) _state.value = _state.value.copy(isCapturing = false) + burstGyroRecorder.stop() + resetPreviewAfterCapture() } } diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index 84e88bb1..4efae9d8 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -345,7 +345,7 @@ data class CameraState( val isRawSupported: Boolean = false, val useMFNR: Boolean = false, val useHdrComposition: Boolean = false, - val multiFrameCount: Int = 0, + val multiFrameCount: Int = MultiFrameConfig.DEFAULT_FRAME_COUNT, val useMFSR: Boolean = false, val useRaw: Boolean = false, val useMultipleExposure: Boolean = false, diff --git a/app/src/main/java/com/hinnka/mycamera/camera/MultiFrameConfig.kt b/app/src/main/java/com/hinnka/mycamera/camera/MultiFrameConfig.kt index 457b73d5..95f40fa7 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/MultiFrameConfig.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/MultiFrameConfig.kt @@ -4,4 +4,8 @@ object MultiFrameConfig { const val MIN_FRAME_COUNT = 2 const val MAX_FRAME_COUNT = 20 const val DEFAULT_FRAME_COUNT = 6 + + fun normalizeFrameCount(frameCount: Int): Int { + return frameCount.coerceIn(MIN_FRAME_COUNT, MAX_FRAME_COUNT) + } } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRadianceReconstruction.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRadianceReconstruction.kt new file mode 100644 index 00000000..9e875691 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRadianceReconstruction.kt @@ -0,0 +1,482 @@ +package com.hinnka.mycamera.processor + +/** Geometry of the canonical RGGB work surface used by the packed VGN shaders. */ +internal data class RadianceVgnGeometry( + val regionWidth: Int, + val regionHeight: Int, + val roiLeft: Int, + val roiTop: Int, + val roiRight: Int, + val roiBottom: Int, + val packedWidth: Int, + val workWidth: Int, + val workHeight: Int, + val halfHeight: Int, +) { + companion object { + const val WORK_HALO_PX = 20 + + fun forRegion(regionWidth: Int, regionHeight: Int, cfaPattern: Int): RadianceVgnGeometry { + require(regionWidth > 0 && regionHeight > 0) + require(cfaPattern in 0..3) { "Radiance VGN requires a standard Bayer CFA" } + val phaseX = if (cfaPattern == 1 || cfaPattern == 3) 1 else 0 + val phaseY = if (cfaPattern == 2 || cfaPattern == 3) 1 else 0 + val roiLeft = WORK_HALO_PX + phaseX + val roiTop = WORK_HALO_PX + phaseY + val roiRight = roiLeft + regionWidth + val roiBottom = roiTop + regionHeight + val packedWidth = (roiRight + WORK_HALO_PX + 3) / 4 + val workWidth = packedWidth * 4 + val workHeight = ((roiBottom + WORK_HALO_PX + 1) / 2) * 2 + return RadianceVgnGeometry( + regionWidth = regionWidth, + regionHeight = regionHeight, + roiLeft = roiLeft, + roiTop = roiTop, + roiRight = roiRight, + roiBottom = roiBottom, + packedWidth = packedWidth, + workWidth = workWidth, + workHeight = workHeight, + halfHeight = workHeight / 2, + ) + } + } +} + +/** + * Radiance-only reconstruction adapters. + * + * The reference path adapts a RAW tile to the canonical VGN work domain and converts Pass 3 + * YCCD directly to un-white-balanced camera RGB. The non-reference path never interpolates CFA + * samples across phases: it first creates dense G plus native R-G/B-G samples, then resolves + * each opponent plane exclusively on its own global two-pixel lattice. + */ +internal object GlesRadianceReconstructionShaders { + val vgnPrepareRegion: String = """ + #version 310 es + precision highp float; + precision highp int; + precision highp image2D; + + layout(local_size_x = 16, local_size_y = 16) in; + layout(binding = 0) uniform highp usampler2D uRawRegion; + layout(binding = 1) uniform highp sampler2D uLensShadingMap; + layout(rgba16f, binding = 0) writeonly uniform image2D uPackedRaw; + + uniform ivec2 uRegionSize; + uniform ivec2 uFullImageSize; + uniform ivec2 uGlobalOrigin; + uniform ivec2 uPackedSize; + uniform ivec2 uSourceOffset; + uniform int uCfaPattern; + uniform vec4 uBlackLevel; + uniform float uWhiteLevel; + uniform vec4 uCalculationGains; + uniform int uReconstructHighlights; + + int bayerIndexAt(int pattern, ivec2 p) { + int phase = (p.x & 1) + ((p.y & 1) << 1); + 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 colorAt(ivec2 global) { + int channel = bayerIndexAt(uCfaPattern, global); + return channel == 0 ? 0 : (channel == 3 ? 2 : 1); + } + + int lensChannelAt(ivec2 global) { + int channel = bayerIndexAt(uCfaPattern, global); + if (channel == 0 || channel == 3) return channel; + return (global.y & 1) == 0 ? 1 : 2; + } + + int mirrorIndex(int value, int size) { + if (size <= 1) return 0; + int period = 2 * (size - 1); + int wrapped = value % period; + if (wrapped < 0) wrapped += period; + return wrapped < size ? wrapped : period - wrapped; + } + + ivec2 clampLocal(ivec2 local) { + return ivec2( + mirrorIndex(local.x, uRegionSize.x), + mirrorIndex(local.y, uRegionSize.y) + ); + } + + float sensorAt(ivec2 local) { + local = clampLocal(local); + ivec2 global = local + uGlobalOrigin; + int channel = bayerIndexAt(uCfaPattern, global); + float raw = float(texelFetch(uRawRegion, local, 0).r); + return max(raw - uBlackLevel[channel], 0.0) / + max(uWhiteLevel - uBlackLevel[channel], 1.0); + } + + float calculationAt(ivec2 local) { + local = clampLocal(local); + ivec2 global = local + uGlobalOrigin; + int channel = bayerIndexAt(uCfaPattern, global); + vec2 uv = (vec2(global) + vec2(0.5)) / vec2(uFullImageSize); + vec4 lsc = texture(uLensShadingMap, clamp(uv, vec2(0.0), vec2(1.0))); + return clamp( + sensorAt(local) * max(lsc[lensChannelAt(global)], 0.0) * + max(uCalculationGains[channel], 1e-6), + 0.0, + 8.0 + ); + } + + float opposedEstimate(ivec2 local, int ownColor, float fallback) { + vec3 sum = vec3(0.0); + vec3 count = vec3(0.0); + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + ivec2 q = clampLocal(local + ivec2(x, y)); + int color = colorAt(q + uGlobalOrigin); + sum[color] += calculationAt(q); + count[color] += 1.0; + } + } + const float power = 3.0; + vec3 roots = pow(max(sum / max(count, vec3(1.0)), vec3(0.0)), + vec3(1.0 / power)); + float opposed = ownColor == 0 ? 0.5 * (roots.g + roots.b) : + (ownColor == 1 ? 0.5 * (roots.r + roots.b) : + 0.5 * (roots.r + roots.g)); + return max(pow(max(opposed, 0.0), power), fallback); + } + + float preparedSample(ivec2 workPosition) { + ivec2 local = clampLocal(workPosition - uSourceOffset); + float sensor = sensorAt(local); + float value = calculationAt(local); + if (uReconstructHighlights != 0) { + float clipMask = smoothstep(0.985, 1.0, sensor); + if (clipMask > 0.0) { + int ownColor = colorAt(local + uGlobalOrigin); + value = min(mix(value, opposedEstimate(local, ownColor, value), clipMask), 8.0); + } + } + return value; + } + + void main() { + ivec2 packed = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(packed, uPackedSize))) return; + int x = packed.x * 4; + imageStore(uPackedRaw, packed, vec4( + preparedSample(ivec2(x + 0, packed.y)), + preparedSample(ivec2(x + 1, packed.y)), + preparedSample(ivec2(x + 2, packed.y)), + preparedSample(ivec2(x + 3, packed.y)) + )); + } + """.trimIndent() + + val vgnYccdToCameraRgb: String = """ + #version 310 es + precision highp float; + precision highp int; + precision highp uimage2D; + precision highp image2D; + + layout(local_size_x = 16, local_size_y = 16) in; + layout(rgba16ui, binding = 0) readonly uniform uimage2D uYccd; + layout(rgba16f, binding = 1) writeonly uniform image2D uCameraRgb; + uniform ivec2 uOutputSize; + uniform ivec2 uRoiOrigin; + uniform vec3 uCalculationGains; + + int signed16(int value) { + return (value & (1 << 15)) != 0 ? value | ~((1 << 16) - 1) : value; + } + + vec3 yccdToRgb(uvec3 yccd) { + float y = clamp(float(yccd.r), 0.0, 65534.0); + float rg = float(signed16(int(yccd.g))); + float bg = float(signed16(int(yccd.b))); + float r = clamp(y * 3.0 * rg / 32768.0 - y * bg / 32768.0 + y, + 0.0, 65535.0); + float b = clamp(y * 3.0 * bg / 32768.0 - y * rg / 32768.0 + y, + 0.0, 65535.0); + float g = clamp((4.0 * y - r - b) * 0.5, 0.0, 65535.0); + return vec3(r, g, b) / 65535.0; + } + + void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(p, uOutputSize))) return; + vec3 calculationRgb = yccdToRgb(imageLoad(uYccd, p + uRoiOrigin).rgb); + vec3 cameraRgb = calculationRgb / max(uCalculationGains, vec3(1e-6)); + imageStore(uCameraRgb, p, vec4(max(cameraRgb, vec3(0.0)), 1.0)); + } + """.trimIndent() + + val semanticSeed: String = """ + #version 310 es + precision highp float; + precision highp int; + precision highp image2D; + + layout(local_size_x = 16, local_size_y = 16) in; + layout(binding = 0) uniform highp usampler2D uRawRegion; + layout(binding = 1) uniform highp sampler2D uLensShadingMap; + layout(rgba16f, binding = 0) writeonly uniform image2D uSemanticSeed; + uniform ivec2 uRegionSize; + uniform ivec2 uFullImageSize; + uniform ivec2 uGlobalOrigin; + uniform int uCfaPattern; + uniform vec4 uBlackLevel; + uniform float uWhiteLevel; + + int bayerIndexAt(int pattern, ivec2 p) { + int phase = (p.x & 1) + ((p.y & 1) << 1); + 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 lensChannelAt(ivec2 global) { + int channel = bayerIndexAt(uCfaPattern, global); + if (channel == 0 || channel == 3) return channel; + return (global.y & 1) == 0 ? 1 : 2; + } + + int mirrorIndex(int value, int size) { + if (size <= 1) return 0; + int period = 2 * (size - 1); + int wrapped = value % period; + if (wrapped < 0) wrapped += period; + return wrapped < size ? wrapped : period - wrapped; + } + + ivec2 clampLocal(ivec2 p) { + return ivec2( + mirrorIndex(p.x, uRegionSize.x), + mirrorIndex(p.y, uRegionSize.y) + ); + } + + float cameraAt(ivec2 local) { + local = clampLocal(local); + ivec2 global = local + uGlobalOrigin; + int channel = bayerIndexAt(uCfaPattern, global); + float raw = float(texelFetch(uRawRegion, local, 0).r); + float sensor = max(raw - uBlackLevel[channel], 0.0) / + max(uWhiteLevel - uBlackLevel[channel], 1.0); + vec2 uv = (vec2(global) + vec2(0.5)) / vec2(uFullImageSize); + vec4 lsc = texture(uLensShadingMap, clamp(uv, vec2(0.0), vec2(1.0))); + return max(sensor * max(lsc[lensChannelAt(global)], 0.0), 0.0); + } + + float denseGreenAt(ivec2 p) { + p = clampLocal(p); + ivec2 global = p + uGlobalOrigin; + int channel = bayerIndexAt(uCfaPattern, global); + float center = cameraAt(p); + if (channel == 1 || channel == 2) return center; + + float gL = cameraAt(p + ivec2(-1, 0)); + float gR = cameraAt(p + ivec2(1, 0)); + float gU = cameraAt(p + ivec2(0, -1)); + float gD = cameraAt(p + ivec2(0, 1)); + float cL2 = cameraAt(p + ivec2(-2, 0)); + float cR2 = cameraAt(p + ivec2(2, 0)); + float cU2 = cameraAt(p + ivec2(0, -2)); + float cD2 = cameraAt(p + ivec2(0, 2)); + float horizontalLinear = 0.5 * (gL + gR); + float verticalLinear = 0.5 * (gU + gD); + float horizontalCorrection = 0.25 * (2.0 * center - cL2 - cR2); + float verticalCorrection = 0.25 * (2.0 * center - cU2 - cD2); + // The second-derivative correction is useful for detail, but an unrestricted value + // can overshoot on defocused/high-contrast chromatic edges and create a false green + // extremum. A missing G sample on a monotonic edge must stay between its two native + // G neighbors along the chosen direction. + float horizontalLimit = 0.5 * abs(gL - gR); + float verticalLimit = 0.5 * abs(gU - gD); + float horizontal = horizontalLinear + clamp( + horizontalCorrection, + -horizontalLimit, + horizontalLimit + ); + float vertical = verticalLinear + clamp( + verticalCorrection, + -verticalLimit, + verticalLimit + ); + float gradientH = abs(gL - gR) + abs(2.0 * center - cL2 - cR2); + float gradientV = abs(gU - gD) + abs(2.0 * center - cU2 - cD2); + float blendH = gradientV / max(gradientH + gradientV, 1e-7); + float green = mix(vertical, horizontal, blendH); + float nativeGreenMin = min(min(gL, gR), min(gU, gD)); + float nativeGreenMax = max(max(gL, gR), max(gU, gD)); + return clamp(green, max(nativeGreenMin, 0.0), max(nativeGreenMax, 0.0)); + } + + void main() { + ivec2 local = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(local, uRegionSize))) return; + ivec2 global = local + uGlobalOrigin; + int channel = bayerIndexAt(uCfaPattern, global); + float green = denseGreenAt(local); + float native = cameraAt(local); + float redGreen = channel == 0 ? native - green : 0.0; + float blueGreen = channel == 3 ? native - green : 0.0; + imageStore(uSemanticSeed, local, vec4(green, redGreen, blueGreen, 1.0)); + } + """.trimIndent() + + val semanticResolve: String = """ + #version 310 es + precision highp float; + precision highp int; + precision highp image2D; + + layout(local_size_x = 16, local_size_y = 16) in; + layout(rgba16f, binding = 0) readonly uniform image2D uSemanticSeed; + layout(rgba16f, binding = 1) writeonly uniform image2D uSemanticOutput; + uniform ivec2 uRegionSize; + uniform ivec2 uFullImageSize; + uniform ivec2 uGlobalOrigin; + uniform int uCfaPattern; + + ivec2 channelPhase(int channel) { + if (uCfaPattern == 0) return channel == 0 ? ivec2(0, 0) : ivec2(1, 1); + if (uCfaPattern == 1) return channel == 0 ? ivec2(1, 0) : ivec2(0, 1); + if (uCfaPattern == 2) return channel == 0 ? ivec2(0, 1) : ivec2(1, 0); + return channel == 0 ? ivec2(1, 1) : ivec2(0, 0); + } + + int clampToPhase(int value, int phase, int fullSize, int regionStart, int regionSize) { + int globalFirst = phase; + int globalLast = phase + 2 * max((fullSize - 1 - phase) / 2, 0); + int regionEnd = regionStart + regionSize - 1; + int first = globalFirst + 2 * max((regionStart - globalFirst + 1) / 2, 0); + int last = globalLast - 2 * max((globalLast - regionEnd + 1) / 2, 0); + return clamp(value, first, max(first, last)); + } + + vec4 semanticAt(ivec2 global) { + ivec2 local = global - uGlobalOrigin; + return imageLoad(uSemanticSeed, local); + } + + float opponentGuideWeight( + float candidateGreen, + float targetGreen, + float guideSigma, + float edgeStrength + ) { + float normalized = (candidateGreen - targetGreen) / max(guideSigma, 1e-5); + float similarity = max(exp(-0.5 * normalized * normalized), 0.02); + // In flat/noisy regions retain ordinary bilinear interpolation. The range guide is + // activated only where a real luminance edge is strong enough to locate chroma. + return mix(1.0, similarity, edgeStrength); + } + + float resolveOpponent( + ivec2 global, + int channel, + int component, + float targetGreen + ) { + ivec2 phase = channelPhase(channel); + ivec2 lower = ivec2( + global.x - ((global.x - phase.x) & 1), + global.y - ((global.y - phase.y) & 1) + ); + ivec2 upper = lower + ivec2(2); + float tx = clamp(float(global.x - lower.x) * 0.5, 0.0, 1.0); + float ty = clamp(float(global.y - lower.y) * 0.5, 0.0, 1.0); + lower.x = clampToPhase(lower.x, phase.x, uFullImageSize.x, + uGlobalOrigin.x, uRegionSize.x); + lower.y = clampToPhase(lower.y, phase.y, uFullImageSize.y, + uGlobalOrigin.y, uRegionSize.y); + upper.x = clampToPhase(upper.x, phase.x, uFullImageSize.x, + uGlobalOrigin.x, uRegionSize.x); + upper.y = clampToPhase(upper.y, phase.y, uFullImageSize.y, + uGlobalOrigin.y, uRegionSize.y); + ivec2 p00 = ivec2(lower.x, lower.y); + ivec2 p10 = ivec2(upper.x, lower.y); + ivec2 p01 = ivec2(lower.x, upper.y); + ivec2 p11 = ivec2(upper.x, upper.y); + // Fetch each lattice site once; the same RGBA16F texel carries G and opponent. + vec4 s00 = semanticAt(p00); + vec4 s10 = semanticAt(p10); + vec4 s01 = semanticAt(p01); + vec4 s11 = semanticAt(p11); + float o00 = s00[component]; + float o10 = s10[component]; + float o01 = s01[component]; + float o11 = s11[component]; + float g00 = s00.r; + float g10 = s10.r; + float g01 = s01.r; + float g11 = s11.r; + float guideMin = min(min(g00, g10), min(g01, g11)); + float guideMax = max(max(g00, g10), max(g01, g11)); + float guideRange = guideMax - guideMin; + float edgeStrength = smoothstep(0.01, 0.08, guideRange); + float guideSigma = max(0.15 * guideRange, 0.004); + + vec4 spatialWeight = vec4( + (1.0 - tx) * (1.0 - ty), + tx * (1.0 - ty), + (1.0 - tx) * ty, + tx * ty + ); + vec4 guideWeight = vec4( + opponentGuideWeight(g00, targetGreen, guideSigma, edgeStrength), + opponentGuideWeight(g10, targetGreen, guideSigma, edgeStrength), + opponentGuideWeight(g01, targetGreen, guideSigma, edgeStrength), + opponentGuideWeight(g11, targetGreen, guideSigma, edgeStrength) + ); + vec4 weight = spatialWeight * guideWeight; + return dot(weight, vec4(o00, o10, o01, o11)) / + max(dot(weight, vec4(1.0)), 1e-7); + } + + void main() { + ivec2 local = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(local, uRegionSize))) return; + ivec2 global = local + uGlobalOrigin; + float green = imageLoad(uSemanticSeed, local).r; + float redGreen = resolveOpponent(global, 0, 1, green); + float blueGreen = resolveOpponent(global, 3, 2, green); + imageStore(uSemanticOutput, local, vec4(green, redGreen, blueGreen, 1.0)); + } + """.trimIndent() +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawHdr.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawHdr.kt index 536ca822..783e0543 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawHdr.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawHdr.kt @@ -76,55 +76,6 @@ internal object GlesRawHdrShaders { } """.trimIndent() - /** RCD 完成后的 HDR 曝光域转换;解马赛克与边界处理不在这里实现。 */ - val workingRgbStore: String = """ - #version 310 es - precision highp float; - precision highp int; - layout(local_size_x = 16, local_size_y = 16) in; - layout(std430, binding = 1) readonly buffer RcdRgb0_Buf { float rcdRgb0[]; }; - layout(std430, binding = 2) readonly buffer RcdRgb1_Buf { float rcdRgb1[]; }; - layout(std430, binding = 3) readonly buffer RcdRgb2_Buf { float rcdRgb2[]; }; - layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput; - uniform ivec2 uSourceSize; - uniform vec3 uCalculationGains; - uniform float uExposureScale; - uniform int uDesaturateBeforeExposureScale; - - vec3 desaturateHighlightPreservingLuma(vec3 rgb) { - rgb = max(rgb, vec3(0.0)); - const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722); - float luma = dot(rgb, LUMA); - float ceiling = max(1.0, luma); - vec3 chroma = rgb - vec3(luma); - float chromaScale = 1.0; - if (chroma.r > 0.0) { - chromaScale = min(chromaScale, (ceiling - luma) / chroma.r); - } - if (chroma.g > 0.0) { - chromaScale = min(chromaScale, (ceiling - luma) / chroma.g); - } - if (chroma.b > 0.0) { - chromaScale = min(chromaScale, (ceiling - luma) / chroma.b); - } - return vec3(luma) + chroma * clamp(chromaScale, 0.0, 1.0); - } - - void main() { - ivec2 p = ivec2(gl_GlobalInvocationID.xy); - if (p.x >= uSourceSize.x || p.y >= uSourceSize.y) return; - int index = p.y * uSourceSize.x + p.x; - vec3 workingRgb = vec3(rcdRgb0[index], rcdRgb1[index], rcdRgb2[index]); - if (uDesaturateBeforeExposureScale != 0) { - workingRgb = desaturateHighlightPreservingLuma(workingRgb); - } - workingRgb *= uExposureScale; - vec3 rgb = workingRgb / - max(uCalculationGains, vec3(1e-6)); - imageStore(uOutput, p, vec4(max(rgb, vec3(0.0)), 1.0)); - } - """.trimIndent() - fun rgbFusion(): String = """ #version 300 es precision highp float; diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRadianceFusion.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRadianceFusion.kt index de767163..63efc2bd 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRadianceFusion.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRadianceFusion.kt @@ -9,7 +9,9 @@ import kotlin.math.ln * * 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. [outputScale] only selects the output sampling grid. + * sensor-linear RGB domain. Standard Bayer references use the full VGN demosaic core while + * non-reference frames use phase-safe dense-G/R-G/B-G semantic reconstruction. Non-standard + * CFAs retain the region RCD backend. [outputScale] only selects the output sampling grid. */ class GlesRawRadianceFusion( private val width: Int, @@ -103,6 +105,7 @@ enum class RawFusionPipeline { * change denoise radius, detail radius, or confidence behavior. */ data class RawRadianceFusionTuning( + val tileCoreSizeRawPx: Int = 1024, val denoiseSigmaRawPx: Float = 1.10f, val denoiseSteeringStrength: Float = 0.48f, val robustnessSpatialMix: Float = 0.68f, @@ -113,18 +116,50 @@ data class RawRadianceFusionTuning( val referenceDetailFloor: Float = 0.18f, val bilateralNoiseScale: Float = 8.0f, val detailChromaStrength: Float = 0.0f, + val chromaConsistencySigmaStart: Float = 3.0f, + val chromaConsistencySigmaFull: Float = 6.0f, ) +/** Returns a sensor-linear RGB value that becomes neutral after the capture WB is applied. */ +internal fun radianceDebugNeutralRgb(calculationWbGains: FloatArray): FloatArray { + require(calculationWbGains.size >= 4) { "Radiance debug WB gains must contain RGGB channels" } + val rgbGains = floatArrayOf( + calculationWbGains[0], + 1f, + calculationWbGains[3], + ) + require(rgbGains.all { it.isFinite() && it > 0f }) { + "Radiance debug WB gains must be finite and positive" + } + val neutral = FloatArray(3) { index -> 1f / rgbGains[index] } + val peak = neutral.maxOrNull()?.coerceAtLeast(1e-6f) ?: 1f + return FloatArray(3) { index -> neutral[index] / peak } +} + internal object GlesRawRadianceFusionShaders { - val clearAccumulator: String = """ + fun clearAccumulator(trackRejections: Boolean): String { + val rejectionDeclaration = if (trackRejections) { + "layout(rgba16f, binding = 6) writeonly uniform highp image2D uFusionRejections;" + } else { + "" + } + val rejectionClear = if (trackRejections) { + "imageStore(uFusionRejections, p, vec4(0.0));" + } else { + "" + } + return """ #version 310 es precision highp float; precision highp int; layout(local_size_x = 16, local_size_y = 16) in; layout(r32ui, binding = 0) writeonly uniform highp uimage2D uNrSumRg; layout(r32ui, binding = 1) writeonly uniform highp uimage2D uNrSumBw; - layout(r32ui, binding = 2) writeonly uniform highp uimage2D uDetailSumRg; - layout(r32ui, binding = 3) writeonly uniform highp uimage2D uDetailSumBw; + layout(r32ui, binding = 2) writeonly uniform highp uimage2D uNrWeightRg; + layout(r32ui, binding = 3) writeonly uniform highp uimage2D uDetailSumRg; + layout(r32ui, binding = 4) writeonly uniform highp uimage2D uDetailSumBw; + layout(r32ui, binding = 5) writeonly uniform highp uimage2D uDetailWeightRg; + $rejectionDeclaration uniform ivec2 uImageSize; void main() { @@ -132,46 +167,262 @@ internal object GlesRawRadianceFusionShaders { if (p.x >= uImageSize.x || p.y >= uImageSize.y) return; imageStore(uNrSumRg, p, uvec4(0u)); imageStore(uNrSumBw, p, uvec4(0u)); + imageStore(uNrWeightRg, p, uvec4(0u)); imageStore(uDetailSumRg, p, uvec4(0u)); imageStore(uDetailSumBw, p, uvec4(0u)); + imageStore(uDetailWeightRg, p, uvec4(0u)); + $rejectionClear } - """.trimIndent() + """.trimIndent() + } - fun accumulate(rawCommon: String): String = """ + fun accumulate( + rawCommon: String, + trackRejections: Boolean = false, + trackParticipation: Boolean = false, + ): String { + val rejectionDeclaration = if (trackRejections) { + """ + uniform highp sampler2D uPreviousFusionRejections; + layout(rgba16f, binding = 6) writeonly uniform highp image2D uNextFusionRejections; + uniform int uRecordFusionRejections; + """.trimIndent() + } else { + "" + } + val rejectionHelper = if (trackRejections) { + """ + const float MATERIAL_REJECTION_THRESHOLD = 0.5; + + bool shouldReplaceFusionRejection(vec3 previous, vec3 candidate) { + if (candidate.x <= 0.0 || candidate.z <= 0.0) return false; + if (previous.x <= 0.0 || previous.z <= 0.0) return true; + bool previousMaterial = previous.z >= MATERIAL_REJECTION_THRESHOLD; + bool candidateMaterial = candidate.z >= MATERIAL_REJECTION_THRESHOLD; + if (candidateMaterial != previousMaterial) return candidateMaterial; + if (candidateMaterial && candidate.y != previous.y) { + return candidate.y > previous.y; + } + return candidate.z > previous.z; + } + + float fusionRejectionPriority(float reasonId) { + if (reasonId < 1.5) return 110.0; + if (reasonId < 5.5) return 70.0; + if (reasonId < 6.5) return 60.0; + if (reasonId < 7.5) return 50.0; + return 0.0; + } + + void considerFusionRejection( + inout vec3 selected, + float reasonId, + float priority, + float rejectionStrength + ) { + vec3 candidate = vec3( + reasonId, + priority, + clamp(rejectionStrength, 0.0, 1.0) + ); + if (shouldReplaceFusionRejection(selected, candidate)) { + selected = candidate; + } + } + + void storeFusionRejection(ivec2 p, vec3 rejection) { + vec4 previousSample = texelFetch( + uPreviousFusionRejections, + p, + 0 + ); + if (uRecordFusionRejections == 0) { + imageStore(uNextFusionRejections, p, previousSample); + return; + } + vec3 selected = previousSample.rgb; + if (shouldReplaceFusionRejection(selected, rejection)) { + selected = rejection; + } + imageStore( + uNextFusionRejections, + p, + vec4(selected, previousSample.a + (rejection.x > 0.0 ? 1.0 : 0.0)) + ); + } + """.trimIndent() + } else { + "" + } + val participationDeclaration = if (trackParticipation) { + """ + layout(std430, binding = 0) buffer RadianceFusionParticipationStats { + uint uFusionParticipationStats[]; + }; + uniform int uFusionStatsIndex; + uniform int uFusionStatsSampleStep; + uniform ivec2 uFusionStatsCoreOrigin; + uniform ivec2 uFusionStatsCoreSize; + """.trimIndent() + } else { + "" + } + val participationHelper = if (trackParticipation) { + """ + const int FUSION_STATS_STRIDE = 5; + const float FUSION_WEIGHT_QUANTIZATION = 63.0; + + bool shouldSampleFusionParticipation(ivec2 outputP) { + ivec2 coreEnd = uFusionStatsCoreOrigin + uFusionStatsCoreSize; + bool insideCore = all(greaterThanEqual(outputP, uFusionStatsCoreOrigin)) && + all(lessThan(outputP, coreEnd)); + int step = max(uFusionStatsSampleStep, 1); + return insideCore && (outputP.x % step) == 0 && (outputP.y % step) == 0; + } + + void recordFusionParticipation( + ivec2 outputP, + vec3 nrWeight, + vec3 detailWeight + ) { + if (!shouldSampleFusionParticipation(outputP)) return; + int offset = uFusionStatsIndex * FUSION_STATS_STRIDE; + float meanNrWeight = dot(nrWeight, vec3(0.3333333)); + float meanDetailWeight = dot(detailWeight, vec3(0.3333333)); + atomicAdd(uFusionParticipationStats[offset + 0], 1u); + if (meanNrWeight > 1e-7) { + atomicAdd(uFusionParticipationStats[offset + 1], 1u); + } + atomicAdd( + uFusionParticipationStats[offset + 2], + uint(floor(clamp(meanNrWeight, 0.0, 1.0) * FUSION_WEIGHT_QUANTIZATION + 0.5)) + ); + if (meanDetailWeight > 1e-7) { + atomicAdd(uFusionParticipationStats[offset + 3], 1u); + } + atomicAdd( + uFusionParticipationStats[offset + 4], + uint(floor(clamp(meanDetailWeight, 0.0, 1.0) * FUSION_WEIGHT_QUANTIZATION + 0.5)) + ); + } + """.trimIndent() + } else { + "" + } + val outOfBoundsHandling = buildString { + if (trackRejections) { + // reason 9: the warped RAW sample is outside the source frame. + appendLine("storeFusionRejection(accumulatorP, vec3(9.0, 120.0, 1.0));") + } + if (trackParticipation) { + append("recordFusionParticipation(outputP, vec3(0.0), vec3(0.0));") + } + } + val rejectionVariable = if (trackRejections) { + "vec3 fusionRejection = vec3(0.0);" + } else { + "" + } + val rejectionAssignment = if (trackRejections) { + """ + // BA contains the NR rejection reason and severity selected while the + // reference/current proxy pair is still available. Patch evidence lives only in + // the detail-confidence channel and therefore cannot reject NR. + fusionRejection = vec3( + tileConfidence.b, + fusionRejectionPriority(tileConfidence.b), + tileConfidence.a + ); + // reason 8: the accepted frame has been reduced to zero by frame registration quality. + considerFusionRejection( + fusionRejection, + 8.0, + 40.0, + 1.0 - clamp(uRegistrationNrWeight, 0.0, 1.0) + ); + // reason 10: relative per-channel sensor precision reduced the sample. + considerFusionRejection( + fusionRejection, + 10.0, + 30.0, + 1.0 - min(min( + clamp(channelPrecision.r, 0.0, 1.0), + clamp(channelPrecision.g, 0.0, 1.0) + ), clamp(channelPrecision.b, 0.0, 1.0)) + ); + // reason 11: highlight protection eliminated the sample. + considerFusionRejection( + fusionRejection, + 11.0, + 20.0, + 1.0 - min(min(highlight.r, highlight.g), highlight.b) + ); + // reason 12: noise-normalized R-G or B-G consistency reduced its channel. + considerFusionRejection( + fusionRejection, + 12.0, + 65.0, + 1.0 - min(channelConsistency.r, channelConsistency.b) + ); + """.trimIndent() + } else { + "" + } + val rejectionStore = if (trackRejections) { + """ + storeFusionRejection( + accumulatorP, + uIsReference == 0 && fusionRejection.z >= MATERIAL_REJECTION_THRESHOLD ? + fusionRejection : vec3(0.0) + ); + """.trimIndent() + } else { + "" + } + val participationStore = if (trackParticipation) { + "recordFusionParticipation(outputP, nrWeight, detailWeight);" + } else { + "" + } + return """ #version 310 es $rawCommon layout(local_size_x = 16, local_size_y = 16) in; - uniform sampler2D uRcdRgbStripe; + uniform sampler2D uRcdRgbTile; uniform sampler2D uFlowGrid; uniform sampler2D uRobustness; uniform sampler2D uTileMask; uniform sampler2D uKernel; uniform sampler2D uLensShadingMap; + uniform sampler2D uReferenceBase; layout(r32ui, binding = 0) uniform highp uimage2D uNrSumRg; layout(r32ui, binding = 1) uniform highp uimage2D uNrSumBw; - layout(r32ui, binding = 2) uniform highp uimage2D uDetailSumRg; - layout(r32ui, binding = 3) uniform highp uimage2D uDetailSumBw; + layout(r32ui, binding = 2) uniform highp uimage2D uNrWeightRg; + layout(r32ui, binding = 3) uniform highp uimage2D uDetailSumRg; + layout(r32ui, binding = 4) uniform highp uimage2D uDetailSumBw; + layout(r32ui, binding = 5) uniform highp uimage2D uDetailWeightRg; + $rejectionDeclaration + $participationDeclaration uniform ivec2 uImageSize; uniform ivec2 uSourceSize; - uniform int uSourceRowOffset; + uniform ivec2 uSourceOrigin; uniform ivec2 uOutputSize; uniform ivec2 uPlaneSize; uniform ivec2 uGridSize; uniform int uTileSize; uniform int uIsReference; + uniform int uSemanticEncoding; uniform int uCfaPattern; uniform float uBlackLevel[4]; uniform float uWhiteLevel; uniform float uNoiseAlphaByChannel[4]; uniform float uNoiseBetaByChannel[4]; - uniform float uOutputScale; uniform float uFrameWeight; uniform float uRegistrationNrWeight; uniform float uRegistrationDetailWeight; uniform float uDenoiseSigmaRawPx; uniform float uDenoiseSteeringStrength; uniform float uRobustnessSpatialMix; - uniform float uRobustnessFloorFactor; uniform float uPrecisionReferenceSignal; uniform float uLscNoiseGainMax; uniform float uDenoiseSignalLow; @@ -181,13 +432,17 @@ internal object GlesRawRadianceFusionShaders { uniform float uDenoiseStaticTileStart; uniform float uDenoiseStaticTileEnd; uniform float uDenoiseNonReferenceWeightBoost; - uniform float uDenoiseNonReferenceWeightFloor; uniform float uDenoiseReferenceDarkWeightScale; uniform float uHighlightSuppressionStrength; uniform float uHighlightSuppressionStart; uniform float uHighlightSuppressionEnd; - uniform int uOutputRowOffset; - uniform int uOutputRowCount; + uniform float uChromaConsistencySigmaStart; + uniform float uChromaConsistencySigmaFull; + uniform ivec2 uAccumulatorOrigin; + uniform ivec2 uAccumulatorSize; + + $rejectionHelper + $participationHelper struct DualRgb { vec3 detail; @@ -195,7 +450,8 @@ internal object GlesRawRadianceFusionShaders { }; vec2 referenceRawPos(ivec2 outputPos) { - return (vec2(outputPos) + vec2(0.5)) / max(uOutputScale, 1.0) - vec2(0.5); + return (vec2(outputPos) + vec2(0.5)) * vec2(uImageSize) / + vec2(uOutputSize) - vec2(0.5); } vec2 flowAt(vec2 planePos) { @@ -210,10 +466,19 @@ internal object GlesRawRadianceFusionShaders { return texture(tex, uv).r; } - float tileMaskAt(vec2 planePos) { + vec4 tileConfidenceAt(vec2 planePos) { vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); - return texture(uTileMask, clamp(uv, vec2(0.0), vec2(1.0))).r; + vec2 confidence = texture( + uTileMask, + clamp(uv, vec2(0.0), vec2(1.0)) + ).rg; + ivec2 reasonTile = clamp( + ivec2(round(grid)), + ivec2(0), + uGridSize - ivec2(1) + ); + return vec4(confidence, texelFetch(uTileMask, reasonTile, 0).ba); } float spatiallySmoothedRobustness(vec2 planePos) { @@ -239,13 +504,20 @@ internal object GlesRawRadianceFusionShaders { return texture(uLensShadingMap, clamp(uv, vec2(0.0), vec2(1.0))); } - vec3 rcdRgbAt(vec2 globalRawPos) { - vec2 localPos = globalRawPos - vec2(0.0, float(uSourceRowOffset)); + vec3 reconstructedRgbAt(vec2 globalRawPos) { + vec2 localPos = globalRawPos - vec2(uSourceOrigin); vec2 maxPos = vec2(max(uSourceSize - ivec2(1), ivec2(0))); - vec2 storageSize = vec2(textureSize(uRcdRgbStripe, 0)); + vec2 storageSize = vec2(textureSize(uRcdRgbTile, 0)); vec2 uv = (clamp(localPos, vec2(0.0), maxPos) + vec2(0.5)) / storageSize; - return clamp(texture(uRcdRgbStripe, uv).rgb, 0.0, 1.0); + vec3 encoded = texture(uRcdRgbTile, uv).rgb; + if (uIsReference != 0 || uSemanticEncoding == 0) { + return clamp(encoded, 0.0, 1.0); + } + // Non-reference tiles encode (G, R-G, B-G). Decoding only after the semantic + // planes have been warped/interpolated keeps CFA phase out of the fusion domain. + return clamp(vec3(encoded.r + encoded.g, encoded.r, encoded.r + encoded.b), + 0.0, 1.0); } vec3 kernelMatrix(vec4 params) { @@ -266,7 +538,7 @@ internal object GlesRawRadianceFusionShaders { } DualRgb reconstructRgb(vec2 rawPos, vec4 steeringKernel) { - vec3 detail = rcdRgbAt(rawPos); + vec3 detail = reconstructedRgbAt(rawPos); float sigma = max(uDenoiseSigmaRawPx, 0.5); vec2 offsets[5] = vec2[5]( vec2(0.0), @@ -288,7 +560,7 @@ internal object GlesRawRadianceFusionShaders { float weight = exp( -0.5 * dot(offset, offset) / (sigma * sigma) ) * steering; - vec3 sampleRgb = i == 0 ? detail : rcdRgbAt(rawPos + offset); + vec3 sampleRgb = i == 0 ? detail : reconstructedRgbAt(rawPos + offset); denoiseSum += sampleRgb * weight; denoiseWeightSum += weight; } @@ -303,13 +575,43 @@ internal object GlesRawRadianceFusionShaders { return max(alpha * clamp(signal, 0.0, 1.0) * gain + beta * gain * gain, 1e-10); } - float precisionWeight(float signal, int bayerIndex, float lscGainForNoise) { - float alpha = uNoiseAlphaByChannel[bayerIndex]; - float beta = uNoiseBetaByChannel[bayerIndex]; - if (alpha <= 0.0 && beta <= 0.0) return 1.0; - float variance = noiseVariance(signal, bayerIndex, lscGainForNoise); - float referenceVariance = noiseVariance(uPrecisionReferenceSignal, bayerIndex, 1.0); - return clamp(referenceVariance / variance, 0.05, 4.0); + vec3 cameraNoiseVariance(vec3 signal, vec4 lsc) { + return vec3( + noiseVariance(signal.r, 0, lsc.r), + 0.5 * ( + noiseVariance(signal.g, 1, lsc.g) + + noiseVariance(signal.g, 2, lsc.b) + ), + noiseVariance(signal.b, 3, lsc.a) + ); + } + + vec2 opponentChromaConfidence( + vec3 referenceRgb, + vec3 currentRgb, + vec3 differenceVariance + ) { + vec2 referenceChroma = referenceRgb.rb - referenceRgb.gg; + vec2 currentChroma = currentRgb.rb - currentRgb.gg; + vec2 chromaDelta = currentChroma - referenceChroma; + // R-G and B-G are differences of independent sensor channels, therefore their + // variances add. Keeping the two opponent axes separate prevents red noise from + // reducing blue/green fusion weight and vice versa. + vec2 opponentVariance = max( + vec2( + differenceVariance.r + differenceVariance.g, + differenceVariance.b + differenceVariance.g + ), + vec2(1e-10) + ); + vec2 normalizedSquaredResidual = chromaDelta * chromaDelta / opponentVariance; + float sigmaStart = max(uChromaConsistencySigmaStart, 0.0); + float sigmaFull = max(uChromaConsistencySigmaFull, sigmaStart + 1e-3); + return vec2(1.0) - smoothstep( + vec2(sigmaStart * sigmaStart), + vec2(sigmaFull * sigmaFull), + normalizedSquaredResidual + ); } float denoiseNeed(float signal) { @@ -336,26 +638,27 @@ internal object GlesRawRadianceFusionShaders { void main() { ivec2 accumulatorP = ivec2(gl_GlobalInvocationID.xy); - ivec2 outputP = accumulatorP + ivec2(0, uOutputRowOffset); - if (accumulatorP.x >= uOutputSize.x || - accumulatorP.y >= uOutputRowCount || - outputP.y >= uOutputSize.y) { + ivec2 outputP = accumulatorP + uAccumulatorOrigin; + if (accumulatorP.x >= uAccumulatorSize.x || + accumulatorP.y >= uAccumulatorSize.y || + outputP.x >= uOutputSize.x || outputP.y >= uOutputSize.y) { return; } vec2 refRaw = referenceRawPos(outputP); vec2 planePos = refRaw * 0.5; vec2 sourceRaw = refRaw; - float tile = 1.0; + vec4 tileConfidence = vec4(1.0, 1.0, 0.0, 0.0); float robust = 1.0; if (uIsReference == 0) { sourceRaw += flowAt(planePos) * 2.0; if (sourceRaw.x < -0.5 || sourceRaw.y < -0.5 || sourceRaw.x > float(uImageSize.x) - 0.5 || sourceRaw.y > float(uImageSize.y) - 0.5) { + $outOfBoundsHandling return; } - tile = tileMaskAt(planePos); + tileConfidence = tileConfidenceAt(planePos); robust = spatiallySmoothedRobustness(planePos); } @@ -366,52 +669,84 @@ internal object GlesRawRadianceFusionShaders { float signal = dot(rgb.denoise, vec3(0.2126, 0.7152, 0.0722)); ivec2 nearestSource = clamp(ivec2(round(sourceRaw)), ivec2(0), uImageSize - ivec2(1)); vec4 lsc = lscAt(nearestSource); - float redPrecision = precisionWeight(rgb.denoise.r, 0, lsc.r); - float greenPrecision = 0.5 * ( - precisionWeight(rgb.denoise.g, 1, lsc.g) + - precisionWeight(rgb.denoise.g, 2, lsc.b) - ); - float bluePrecision = precisionWeight(rgb.denoise.b, 3, lsc.a); - float sensorPrecision = (redPrecision + greenPrecision + bluePrecision) / 3.0; float shadow = denoiseNeed(signal); - float highlight = 1.0 - uHighlightSuppressionStrength * + vec3 highlight = vec3(1.0) - uHighlightSuppressionStrength * smoothstep(uHighlightSuppressionStart, uHighlightSuppressionEnd, - max(max(rgb.denoise.r, rgb.denoise.g), rgb.denoise.b)); + rgb.denoise); - float nrWeight; - float detailWeight; + vec3 channelPrecision = vec3(1.0); + vec3 channelConsistency = vec3(1.0); + vec3 nrWeight; + vec3 detailWeight; + $rejectionVariable if (uIsReference != 0) { - nrWeight = 1.0; - detailWeight = 1.0; + nrWeight = vec3(1.0); + detailWeight = vec3(1.0); } else { - float robustFloor = max(robust, uRobustnessFloorFactor * tile); - float strictCoverage = clamp(tile * robustFloor, 0.0, 1.0); - float relaxedRobust = smoothstep( - 0.25 * min(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), - min(uDenoiseStaticRobustStart, uDenoiseStaticRobustEnd), - robust + vec3 referenceRgb = clamp( + texelFetch(uReferenceBase, accumulatorP, 0).rgb, + 0.0, + 1.0 ); - float relaxedCoverage = shadow * relaxedRobust * - max(uDenoiseNonReferenceWeightFloor, 0.0); - float nrCoverage = max( - strictCoverage, - relaxedCoverage - ) * clamp(uRegistrationNrWeight, 0.0, 1.0); - float staticConfidence = denoiseStaticConfidence(tile, robust); - nrWeight = uFrameWeight * sensorPrecision * nrCoverage * highlight * mix( + ivec2 nearestReference = clamp( + ivec2(round(refRaw)), + ivec2(0), + uImageSize - ivec2(1) + ); + vec4 referenceLsc = lscAt(nearestReference); + vec3 referenceVariance = cameraNoiseVariance(referenceRgb, referenceLsc); + // Both estimates use the reference signal so shot-noise weighting cannot be + // biased by the current frame's random positive/negative noise excursion. + vec3 currentExpectedVariance = cameraNoiseVariance(referenceRgb, lsc); + channelPrecision = clamp( + referenceVariance / max(currentExpectedVariance, vec3(1e-10)), + vec3(0.25), + vec3(4.0) + ); + vec2 chromaConfidence = opponentChromaConfidence( + referenceRgb, + rgb.denoise, + referenceVariance + currentExpectedVariance + ); + channelConsistency = vec3(chromaConfidence.x, 1.0, chromaConfidence.y); + // Keep the noise model channel-specific, but couple the final color support. + // Independent RGB weights let G keep accumulating while R/B fall back to the + // reference at chromatic or slightly misregistered edges. That combines channels + // from different effective frame sets and creates green/magenta fringes. The + // conservative shared support preserves the reconstructed RGB triplet as a unit. + float sharedPrecision = min( + min(channelPrecision.r, channelPrecision.g), + channelPrecision.b + ); + float sharedConsistency = min(chromaConfidence.x, chromaConfidence.y); + float sharedHighlight = min(min(highlight.r, highlight.g), highlight.b); + float nrCoverage = clamp(tileConfidence.r * robust, 0.0, 1.0) * + clamp(uRegistrationNrWeight, 0.0, 1.0); + float detailCoverage = clamp(tileConfidence.g * robust, 0.0, 1.0); + $rejectionAssignment + float staticConfidence = denoiseStaticConfidence(tileConfidence.r, robust); + float sharedNrWeight = uFrameWeight * sharedPrecision * sharedConsistency * + nrCoverage * sharedHighlight * mix( 1.0, max(uDenoiseNonReferenceWeightBoost, 1.0), shadow * staticConfidence ); - detailWeight = uFrameWeight * sensorPrecision * strictCoverage * highlight * + float sharedDetailWeight = uFrameWeight * sharedPrecision * sharedConsistency * + detailCoverage * sharedHighlight * clamp(uRegistrationDetailWeight, 0.0, 1.0); + nrWeight = vec3(sharedNrWeight); + detailWeight = vec3(sharedDetailWeight); } + $rejectionStore + $participationStore - if (nrWeight > 1e-7) { + if (any(greaterThan(nrWeight, vec3(1e-7)))) { vec2 nrRg = unpackHalf2x16(imageLoad(uNrSumRg, accumulatorP).r); vec2 nrBw = unpackHalf2x16(imageLoad(uNrSumBw, accumulatorP).r); - nrRg += rgb.denoise.rg * nrWeight; - nrBw += vec2(rgb.denoise.b, 1.0) * nrWeight; + vec2 nrWeightRg = unpackHalf2x16(imageLoad(uNrWeightRg, accumulatorP).r); + nrRg += rgb.denoise.rg * nrWeight.rg; + nrBw += vec2(rgb.denoise.b * nrWeight.b, nrWeight.b); + nrWeightRg += nrWeight.rg; imageStore( uNrSumRg, accumulatorP, @@ -422,12 +757,21 @@ internal object GlesRawRadianceFusionShaders { accumulatorP, uvec4(packHalf2x16(nrBw), 0u, 0u, 0u) ); + imageStore( + uNrWeightRg, + accumulatorP, + uvec4(packHalf2x16(nrWeightRg), 0u, 0u, 0u) + ); } - if (detailWeight > 1e-7) { + if (any(greaterThan(detailWeight, vec3(1e-7)))) { vec2 detailRg = unpackHalf2x16(imageLoad(uDetailSumRg, accumulatorP).r); vec2 detailBw = unpackHalf2x16(imageLoad(uDetailSumBw, accumulatorP).r); - detailRg += rgb.detail.rg * detailWeight; - detailBw += vec2(rgb.detail.b, 1.0) * detailWeight; + vec2 detailWeightRg = unpackHalf2x16( + imageLoad(uDetailWeightRg, accumulatorP).r + ); + detailRg += rgb.detail.rg * detailWeight.rg; + detailBw += vec2(rgb.detail.b * detailWeight.b, detailWeight.b); + detailWeightRg += detailWeight.rg; imageStore( uDetailSumRg, accumulatorP, @@ -438,9 +782,15 @@ internal object GlesRawRadianceFusionShaders { accumulatorP, uvec4(packHalf2x16(detailBw), 0u, 0u, 0u) ); + imageStore( + uDetailWeightRg, + accumulatorP, + uvec4(packHalf2x16(detailWeightRg), 0u, 0u, 0u) + ); } } - """.trimIndent() + """.trimIndent() + } val captureReferenceBase: String = """ #version 310 es @@ -450,6 +800,7 @@ internal object GlesRawRadianceFusionShaders { layout(local_size_x = 16, local_size_y = 16) in; uniform highp usampler2D uNrSumRg; uniform highp usampler2D uNrSumBw; + uniform highp usampler2D uNrWeightRg; layout(rgba16f, binding = 0) writeonly uniform highp image2D uReferenceBase; uniform ivec2 uImageSize; @@ -458,16 +809,104 @@ internal object GlesRawRadianceFusionShaders { if (p.x >= uImageSize.x || p.y >= uImageSize.y) return; vec2 rg = unpackHalf2x16(texelFetch(uNrSumRg, p, 0).r); vec2 bw = unpackHalf2x16(texelFetch(uNrSumBw, p, 0).r); - float weight = max(bw.y, 1e-6); + vec2 weightRg = max( + unpackHalf2x16(texelFetch(uNrWeightRg, p, 0).r), + vec2(1e-6) + ); + float weightB = max(bw.y, 1e-6); imageStore( uReferenceBase, p, - vec4(clamp(vec3(rg / weight, bw.x / weight), 0.0, 1.0), 1.0) + vec4(clamp(vec3(rg / weightRg, bw.x / weightB), 0.0, 1.0), 1.0) ); } """.trimIndent() - val normalize: String = """ + fun normalize( + showRejections: Boolean, + showSrDetail: Boolean = false, + ): String { + val rejectionUniforms = if (showRejections) { + """ + uniform highp sampler2D uFusionRejections; + uniform float uGlobalAlignmentRejectCount; + uniform float uAcceptedFusionFrameCount; + """.trimIndent() + } else { + "" + } + val debugColorUniform = if (showRejections || showSrDetail) { + "uniform vec3 uDebugNeutralRgb;" + } else { + "" + } + val rejectionOverlay = if (showRejections) { + """ + { + vec4 rejection = texelFetch(uFusionRejections, p, 0); + float reasonId = rejection.x; + float displayStrength = 0.0; + if (reasonId > 0.0 && rejection.a > 0.0) { + float rejectedFrameFraction = clamp( + rejection.a / max(uAcceptedFusionFrameCount, 1.0), + 0.0, + 1.0 + ); + displayStrength = sqrt(rejectedFrameFraction); + } else if (center.lumaConfidence <= 1e-6 && + uGlobalAlignmentRejectCount > 0.0) { + reasonId = 8.0; + displayStrength = 1.0; + } + vec3 displayColor = vec3(0.5); + if (reasonId < 1.5) { + displayColor = vec3(1.0, 1.0, 0.0); // proxy validity: yellow + } else if (reasonId < 2.5) { + displayColor = vec3(1.0, 0.35, 0.0); // patch peak: orange + } else if (reasonId < 3.5) { + displayColor = vec3(1.0, 0.0, 1.0); // patch score: magenta + } else if (reasonId < 4.5) { + displayColor = vec3(0.0, 1.0, 1.0); // absolute flow: cyan + } else if (reasonId < 5.5) { + displayColor = vec3(0.0, 0.0, 1.0); // local flow range: blue + } else if (reasonId < 6.5) { + displayColor = vec3(1.0, 0.0, 0.0); // photometric residual: red + } else if (reasonId < 7.5) { + displayColor = vec3(0.0, 1.0, 0.0); // tile aggregation: green + } else if (reasonId < 8.5) { + displayColor = vec3(0.45, 0.0, 1.0); // frame gate: violet + } else if (reasonId < 9.5) { + displayColor = vec3(0.0, 1.0, 0.35); // out of bounds: turquoise + } else if (reasonId < 10.5) { + displayColor = vec3(1.0, 0.20, 0.45); // sensor precision: pink + } else if (reasonId < 11.5) { + displayColor = vec3(0.45, 1.0, 0.0); // highlight suppression: lime + } else if (reasonId < 12.5) { + displayColor = vec3(1.0, 0.0, 1.0); // opponent chroma: magenta + } + if (reasonId > 0.0 && displayStrength > 0.0) { + rgb = mix( + rgb, + displayColor * uDebugNeutralRgb, + displayStrength + ); + } + } + """.trimIndent() + } else { + "" + } + val srDetailOverlay = if (showSrDetail) { + """ + if (srDetailConfidence > 1e-6) { + vec3 srDetailColor = vec3(0.0, 1.0, 1.0) * uDebugNeutralRgb; + rgb = mix(rgb, srDetailColor, srDetailConfidence); + } + """.trimIndent() + } else { + "" + } + return """ #version 300 es precision highp float; precision highp int; @@ -476,9 +915,13 @@ internal object GlesRawRadianceFusionShaders { layout(location = 0) out highp uvec4 fragColor; uniform highp usampler2D uNrSumRg; uniform highp usampler2D uNrSumBw; + uniform highp usampler2D uNrWeightRg; uniform highp usampler2D uDetailSumRg; uniform highp usampler2D uDetailSumBw; + uniform highp usampler2D uDetailWeightRg; uniform sampler2D uReferenceBase; + $rejectionUniforms + $debugColorUniform uniform float uNoiseAlphaByChannel[4]; uniform float uNoiseBetaByChannel[4]; uniform float uNrConfidenceStart; @@ -493,21 +936,29 @@ internal object GlesRawRadianceFusionShaders { uniform float uLowLightSignalHigh; uniform float uLowLightSmoothBoost; uniform float uMaxSmoothStrength; - uniform int uAccumulatorRowOffset; - uniform int uOutputRowOffset; + uniform vec3 uCalculationGains; + uniform ivec2 uAccumulatorOrigin; + uniform ivec2 uAccumulatorSize; + uniform ivec2 uOutputOrigin; struct NrState { vec3 base; vec3 nr; vec3 noise; - float confidence; - float consistency; - float effectiveSupport; - float weight; + vec3 confidence; + vec3 consistency; + vec3 effectiveSupport; + vec3 weight; + float lumaConfidence; + }; + + struct WeightedRgb { + vec3 value; + vec3 weight; }; ivec2 clampAccumulatorPos(ivec2 p) { - return clamp(p, ivec2(0), textureSize(uNrSumRg, 0) - ivec2(1)); + return clamp(p, ivec2(0), uAccumulatorSize - ivec2(1)); } vec3 sensorNoise(vec3 rgb) { @@ -522,57 +973,86 @@ internal object GlesRawRadianceFusionShaders { ), vec3(1e-10)); } - vec4 packedRgbWeightAt( + WeightedRgb packedRgbWeightAt( highp usampler2D rgTexture, highp usampler2D bwTexture, + highp usampler2D weightRgTexture, ivec2 p ) { p = clampAccumulatorPos(p); vec2 rg = unpackHalf2x16(texelFetch(rgTexture, p, 0).r); vec2 bw = unpackHalf2x16(texelFetch(bwTexture, p, 0).r); - float weight = max(bw.y, 0.0); - return vec4( - weight > 1e-7 ? clamp(vec3(rg / weight, bw.x / weight), 0.0, 1.0) : - vec3(0.0), - weight + vec2 weightRg = max( + unpackHalf2x16(texelFetch(weightRgTexture, p, 0).r), + vec2(0.0) ); + vec3 weight = vec3(weightRg, max(bw.y, 0.0)); + vec3 value = vec3( + weight.r > 1e-7 ? rg.r / weight.r : 0.0, + weight.g > 1e-7 ? rg.g / weight.g : 0.0, + weight.b > 1e-7 ? bw.x / weight.b : 0.0 + ); + return WeightedRgb(clamp(value, 0.0, 1.0), weight); } NrState nrStateAt(ivec2 p) { p = clampAccumulatorPos(p); vec3 base = clamp(texelFetch(uReferenceBase, p, 0).rgb, 0.0, 1.0); - vec4 sampleValue = packedRgbWeightAt(uNrSumRg, uNrSumBw, p); - float weight = sampleValue.a; - vec3 nr = weight > 1e-7 ? sampleValue.rgb : base; + WeightedRgb sampleValue = packedRgbWeightAt( + uNrSumRg, + uNrSumBw, + uNrWeightRg, + p + ); + vec3 weight = sampleValue.weight; + vec3 nr = vec3( + weight.r > 1e-7 ? sampleValue.value.r : base.r, + weight.g > 1e-7 ? sampleValue.value.g : base.g, + weight.b > 1e-7 ? sampleValue.value.b : base.b + ); vec3 noise = sensorNoise(nr); - float noiseStd = sqrt(max(dot(noise, vec3(0.3333333)), 1e-10)); - float residual = abs(dot(nr - base, vec3(0.2126, 0.7152, 0.0722))); - float consistency = 1.0 - smoothstep( - 3.0 * noiseStd + 0.002, - 10.0 * noiseStd + 0.015, + vec3 noiseStd = sqrt(max(noise + sensorNoise(base), vec3(1e-10))); + vec3 residual = abs(nr - base); + vec3 channelConsistency = vec3(1.0) - smoothstep( + 3.0 * noiseStd + vec3(0.002), + 10.0 * noiseStd + vec3(0.015), residual ); - float additionalWeight = max(weight - 1.0, 0.0); - float support = smoothstep( - min(uNrConfidenceStart, uNrConfidenceFull), - max(uNrConfidenceStart, uNrConfidenceFull), + vec3 additionalWeight = max(weight - vec3(1.0), vec3(0.0)); + vec3 channelSupport = smoothstep( + vec3(min(uNrConfidenceStart, uNrConfidenceFull)), + vec3(max(uNrConfidenceStart, uNrConfidenceFull)), additionalWeight ); - float confidence = support * mix(0.35, 1.0, consistency); + // Accumulation uses one shared color weight. Keep reference fallback coupled as + // well; per-channel fallback would recreate the same effective-frame mismatch here. + float sharedConsistency = min( + min(channelConsistency.r, channelConsistency.g), + channelConsistency.b + ); + float sharedSupport = min(min(channelSupport.r, channelSupport.g), channelSupport.b); + float sharedConfidence = clamp( + sharedSupport * mix(0.35, 1.0, sharedConsistency), + 0.0, + 1.0 + ); + vec3 consistency = vec3(sharedConsistency); + vec3 confidence = vec3(sharedConfidence); return NrState( base, nr, noise, clamp(confidence, 0.0, 1.0), clamp(consistency, 0.0, 1.0), - max(weight, 1.0), - weight + max(weight, vec3(1.0)), + weight, + sharedConfidence ); } void main() { - ivec2 outputP = ivec2(gl_FragCoord.xy) + ivec2(0, uOutputRowOffset); - ivec2 p = outputP - ivec2(0, uAccumulatorRowOffset); + ivec2 outputP = ivec2(gl_FragCoord.xy) + uOutputOrigin; + ivec2 p = outputP - uAccumulatorOrigin; NrState center = nrStateAt(p); vec3 safeCenter = mix(center.base, center.nr, center.confidence); float rangeVariance = max( @@ -631,25 +1111,44 @@ internal object GlesRawRadianceFusionShaders { float spatialSmooth = uFinalSmoothStrength * (0.35 + uLowLightSmoothBoost * shadow) * (1.0 - 0.82 * structure) * - (1.0 + 0.35 * (1.0 - center.confidence)); + (1.0 + 0.35 * (1.0 - center.lumaConfidence)); spatialSmooth = clamp(spatialSmooth, 0.0, uMaxSmoothStrength); vec3 nrSpatial = mix(safeCenter, bilateral, spatialSmooth); - vec4 detailSample = packedRgbWeightAt(uDetailSumRg, uDetailSumBw, p); - vec3 detail = detailSample.a > 1e-7 ? detailSample.rgb : center.base; - float additionalDetailWeight = max(detailSample.a - 1.0, 0.0); - float detailSupport = smoothstep( - min(uDetailConfidenceStart, uDetailConfidenceFull), - max(uDetailConfidenceStart, uDetailConfidenceFull), + WeightedRgb detailSample = packedRgbWeightAt( + uDetailSumRg, + uDetailSumBw, + uDetailWeightRg, + p + ); + vec3 detail = vec3( + detailSample.weight.r > 1e-7 ? detailSample.value.r : center.base.r, + detailSample.weight.g > 1e-7 ? detailSample.value.g : center.base.g, + detailSample.weight.b > 1e-7 ? detailSample.value.b : center.base.b + ); + vec3 additionalDetailWeight = max( + detailSample.weight - vec3(1.0), + vec3(0.0) + ); + vec3 detailSupport = smoothstep( + vec3(min(uDetailConfidenceStart, uDetailConfidenceFull)), + vec3(max(uDetailConfidenceStart, uDetailConfidenceFull)), additionalDetailWeight ); + vec3 lumaWeights = vec3(0.2126, 0.7152, 0.0722); + float detailLumaSupport = dot(detailSupport, lumaWeights); + float centerLumaConsistency = dot(center.consistency, lumaWeights); + float srDetailConfidence = detailLumaSupport * centerLumaConsistency; float referenceFloor = clamp(uReferenceDetailFloor, 0.0, 1.0) * structure; float detailConfidence = max( referenceFloor, - detailSupport * center.consistency + detailLumaSupport * centerLumaConsistency ); + vec3 calculationGains = max(uCalculationGains, vec3(1e-6)); + vec3 nrCalculation = nrSpatial * calculationGains; + vec3 detailCalculation = detail * calculationGains; float detailLumaDelta = abs(dot( - detail - nrSpatial, + detailCalculation - nrCalculation, vec3(0.2126, 0.7152, 0.0722) )); float flatStability = 1.0 - smoothstep( @@ -657,32 +1156,52 @@ internal object GlesRawRadianceFusionShaders { 10.0 * finalNoiseStd + 0.020, detailLumaDelta ); - detailConfidence *= mix(flatStability, 1.0, structure); + float detailStability = mix(flatStability, 1.0, structure); + detailConfidence *= detailStability; + srDetailConfidence = clamp(srDetailConfidence * detailStability, 0.0, 1.0); detailConfidence = clamp(detailConfidence, 0.0, 1.0); - vec3 lumaWeights = vec3(0.2126, 0.7152, 0.0722); - float signedLumaDetail = dot(detail - nrSpatial, lumaWeights) * + // Radiance is stored as un-white-balanced camera RGB. Equal RGB deltas are not + // achromatic in that domain: after capture WB they turn into complementary + // magenta/green edge ringing. Extract, limit and inject luma detail in the + // calculation-WB domain, then return to the camera-RGB output contract. + float signedLumaDetail = dot( + detailCalculation - nrCalculation, + lumaWeights + ) * detailConfidence; - float lowerHeadroom = min(min(nrSpatial.r, nrSpatial.g), nrSpatial.b); - float upperHeadroom = 1.0 - - max(max(nrSpatial.r, nrSpatial.g), nrSpatial.b); + float lowerHeadroom = min( + min(nrCalculation.r, nrCalculation.g), + nrCalculation.b + ); + vec3 calculationCeiling = calculationGains; + vec3 availableHeadroom = max(calculationCeiling - nrCalculation, vec3(0.0)); + float upperHeadroom = min( + min(availableHeadroom.r, availableHeadroom.g), + availableHeadroom.b + ); signedLumaDetail = clamp( signedLumaDetail, -lowerHeadroom, upperHeadroom ); - vec3 lumaDetail = nrSpatial + vec3(signedLumaDetail); + vec3 lumaDetail = + (nrCalculation + vec3(signedLumaDetail)) / calculationGains; vec3 fullRgbDetail = nrSpatial + detailConfidence * (detail - nrSpatial); float chromaConfidence = clamp(uDetailChromaStrength, 0.0, 1.0) * - detailSupport * center.consistency; + min(min(detailSupport.r, detailSupport.g), detailSupport.b) * + min(min(center.consistency.r, center.consistency.g), center.consistency.b); vec3 rgb = clamp( mix(lumaDetail, fullRgbDetail, chromaConfidence), 0.0, 1.0 ); + $srDetailOverlay + $rejectionOverlay fragColor = uvec4( uvec3(floor(rgb * 65535.0 + vec3(0.5))), 65535u ); } - """.trimIndent() + """.trimIndent() + } } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRcd.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRcd.kt new file mode 100644 index 00000000..5af25bfa --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawRcd.kt @@ -0,0 +1,59 @@ +package com.hinnka.mycamera.processor + +/** + * Shared output adapters for the region-based RCD pipeline. + * + * The demosaic itself is owned by [com.hinnka.mycamera.raw.RcdShaders]. Its RCD interior and + * PPG photo-border completion are dispatched together by [GlesRawStacker] before this adapter + * reads the RGB working buffers. Keeping this shader mode-agnostic prevents HDR and Radiance + * from growing separate post-demosaic paths. + */ +internal object GlesRawRcdShaders { + val workingRgbStore: String = """ + #version 310 es + precision highp float; + precision highp int; + layout(local_size_x = 16, local_size_y = 16) in; + layout(std430, binding = 1) readonly buffer RcdRgb0_Buf { float rcdRgb0[]; }; + layout(std430, binding = 2) readonly buffer RcdRgb1_Buf { float rcdRgb1[]; }; + layout(std430, binding = 3) readonly buffer RcdRgb2_Buf { float rcdRgb2[]; }; + layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput; + uniform ivec2 uSourceSize; + uniform vec3 uCalculationGains; + uniform float uExposureScale; + uniform int uDesaturateBeforeExposureScale; + + vec3 desaturateHighlightPreservingLuma(vec3 rgb) { + rgb = max(rgb, vec3(0.0)); + const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722); + float luma = dot(rgb, LUMA); + float ceiling = max(1.0, luma); + vec3 chroma = rgb - vec3(luma); + float chromaScale = 1.0; + if (chroma.r > 0.0) { + chromaScale = min(chromaScale, (ceiling - luma) / chroma.r); + } + if (chroma.g > 0.0) { + chromaScale = min(chromaScale, (ceiling - luma) / chroma.g); + } + if (chroma.b > 0.0) { + chromaScale = min(chromaScale, (ceiling - luma) / chroma.b); + } + return vec3(luma) + chroma * clamp(chromaScale, 0.0, 1.0); + } + + void main() { + ivec2 p = ivec2(gl_GlobalInvocationID.xy); + if (p.x >= uSourceSize.x || p.y >= uSourceSize.y) return; + int index = p.y * uSourceSize.x + p.x; + vec3 workingRgb = vec3(rcdRgb0[index], rcdRgb1[index], rcdRgb2[index]); + if (uDesaturateBeforeExposureScale != 0) { + workingRgb = desaturateHighlightPreservingLuma(workingRgb); + } + workingRgb *= uExposureScale; + vec3 rgb = workingRgb / + max(uCalculationGains, vec3(1e-6)); + imageStore(uOutput, p, vec4(max(rgb, vec3(0.0)), 1.0)); + } + """.trimIndent() +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt index 8eca2f3c..365f7245 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt @@ -11,6 +11,7 @@ import android.opengl.GLES31 import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.raw.RawProfileToneMapMode import com.hinnka.mycamera.raw.RcdShaders +import com.hinnka.mycamera.raw.VgnShaders import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog import java.nio.ByteBuffer @@ -55,6 +56,8 @@ class GlesRawStacker( val flowTexture: Int, val robustnessTexture: Int, val tileMaskTexture: Int, + val minFlowXPlanePx: Float, + val maxFlowXPlanePx: Float, val minFlowYPlanePx: Float, val maxFlowYPlanePx: Float, ) @@ -65,6 +68,12 @@ class GlesRawStacker( val allocMs: Long, val mode: String, ) + private data class RadianceVgnImageBinding( + val unit: Int, + val texture: Int, + val access: Int, + val format: Int, + ) private data class RegistrationAcceptance( val accepted: Boolean, val transform: RawStackPerspectiveTransform, @@ -158,10 +167,15 @@ class GlesRawStacker( relative(safeGain(3, greenBase)), ) } - private val normalizedNoiseAlphaByChannel = rawNoiseModel.normalizedShotNoiseForShader() - private val normalizedNoiseBetaByChannel = rawNoiseModel.normalizedReadNoiseForShader() - private val noiseAlpha = rawNoiseModel.greenShotNoise.coerceAtLeast(0f) / 65535.0f - private val noiseBeta = rawNoiseModel.greenReadNoise.coerceAtLeast(0f) / (65535.0f * 65535.0f) + private val radianceDebugNeutralColor = radianceDebugNeutralRgb(demosaicCalculationWbGains) + private val normalizedNoiseAlphaByChannel = rawNoiseModel.normalizedShotNoiseForShader(cfaPattern) + private val normalizedNoiseBetaByChannel = rawNoiseModel.normalizedReadNoiseForShader(cfaPattern) + private val noiseAlpha = 0.5f * ( + normalizedNoiseAlphaByChannel[1] + normalizedNoiseAlphaByChannel[2] + ) + private val noiseBeta = 0.5f * ( + normalizedNoiseBetaByChannel[1] + normalizedNoiseBetaByChannel[2] + ) private val hwmfPrefilter = tuning.prefilter private val hwmfBlend = tuning.blend private val hwmfPostfilter = tuning.postfilter @@ -170,6 +184,14 @@ class GlesRawStacker( private val registrationSetup = RawStackRegistrationResolver.resolve(width, height) private val registrationSummary = registrationSetup.toSummary() private val radianceFusionEnabled = fusionPipeline == RawFusionPipeline.RADIANCE_RGB + private val radianceUsesVgnSemanticBackend = radianceFusionEnabled && cfaPattern in 0..3 + private val visualizeRadianceFusionRejections = + radianceFusionEnabled && hwmfDebug.visualizeRadianceFusionRejections + private val visualizeRadianceSrDetail = + radianceFusionEnabled && hwmfDebug.visualizeRadianceSrDetail + private val logRadianceFusionParticipation = + radianceFusionEnabled && hwmfDebug.logRadianceFusionParticipation + private val dualTileConfidence = radianceFusionEnabled private val superResolutionEnabled = tuning.mode == RawStackMode.MFSR || radianceFusionEnabled private val superResolutionScale = if (superResolutionEnabled) { hwmfSr.outputScale.coerceIn(1.0f, hwmfSr.internalScale.coerceIn(1.0f, 2.0f)) @@ -178,15 +200,44 @@ class GlesRawStacker( } private val outputWidth = scaledRawDimension(width, superResolutionScale) private val outputHeight = scaledRawDimension(height, superResolutionScale) - private val superResolutionAccumulatorHeight = minOf( - outputHeight, - SUPER_RESOLUTION_STRIPE_ROWS + 2 * SUPER_RESOLUTION_SPATIAL_RADIUS, - ) private val rawCfaPeriod = when { cfaPattern >= 8 -> 8 cfaPattern >= 4 -> 4 else -> 2 } + private val radianceTiles = if (radianceFusionEnabled) { + RadianceTilePlanner.plan( + rawWidth = width, + rawHeight = height, + outputWidth = outputWidth, + outputHeight = outputHeight, + coreSizeRawPx = radianceFusionTuning.tileCoreSizeRawPx, + outputSpatialRadiusPx = SUPER_RESOLUTION_SPATIAL_RADIUS, + cfaPeriod = rawCfaPeriod, + ) + } else { + emptyList() + } + private val superResolutionAccumulatorWidth = if (radianceFusionEnabled) { + radianceTiles.maxOf { it.outputWorking.width } + } else { + outputWidth + } + private val superResolutionAccumulatorHeight = if (radianceFusionEnabled) { + radianceTiles.maxOf { it.outputWorking.height } + } else { + minOf(outputHeight, SUPER_RESOLUTION_STRIPE_ROWS + 2 * SUPER_RESOLUTION_SPATIAL_RADIUS) + } + private val radianceOutputTileWidth = if (radianceFusionEnabled) { + radianceTiles.maxOf { it.outputCore.width } + } else { + outputWidth + } + private val radianceOutputTileHeight = if (radianceFusionEnabled) { + radianceTiles.maxOf { it.outputCore.height } + } else { + outputHeight + } private val superResolutionPhaseTracker = RawStackSuperResolutionPhaseTracker( cfaPeriod = rawCfaPeriod, outputScale = superResolutionScale, @@ -216,6 +267,7 @@ class GlesRawStacker( private var lkRefineProgram = 0 private var smoothFlowProgram = 0 private var copyScalarProgram = 0 + private var copyRgbaProgram = 0 private var structureProgram = 0 private var robustnessProgram = 0 private var tileMaskProgram = 0 @@ -227,15 +279,19 @@ class GlesRawStacker( private var accumulateSuperResolutionProgram = 0 private var normalizeSuperResolutionProgram = 0 private var radianceReferenceBaseProgram = 0 - private var rcdStripePopulateProgram = 0 - private var rcdStripeStep1Program = 0 - private var rcdStripeStep2Program = 0 - private var rcdStripeStep3Program = 0 - private var rcdStripeStep40Program = 0 - private var rcdStripeStep41Program = 0 - private var rcdStripeStep42Program = 0 - private var rcdStripeStep43Program = 0 - private var rcdStripeBorderPpgProgram = 0 + private val radianceVgnPrograms = IntArray(VgnShaders.PROGRAM_3 + 1) + private var radianceVgnFinalProgram = 0 + private var radianceSemanticSeedProgram = 0 + private var radianceSemanticResolveProgram = 0 + private var rcdRegionPopulateProgram = 0 + private var rcdRegionStep1Program = 0 + private var rcdRegionStep2Program = 0 + private var rcdRegionStep3Program = 0 + private var rcdRegionStep40Program = 0 + private var rcdRegionStep41Program = 0 + private var rcdRegionStep42Program = 0 + private var rcdRegionStep43Program = 0 + private var rcdRegionBorderPpgProgram = 0 private var hdrShortGlobalAlignProgram = 0 private var hdrNormalCfaInputProgram = 0 private var rcdStoreRgbProgram = 0 @@ -268,13 +324,29 @@ class GlesRawStacker( private var accumulatorStatisticsTexture = 0 private var superResolutionAccumulatorTexture = 0 private var superResolutionAccumulatorBwTexture = 0 + private var radianceNrWeightRgTexture = 0 private var superResolutionAccumulatorBTexture = 0 private var radianceDetailBwTexture = 0 + private var radianceDetailWeightRgTexture = 0 private var radianceReferenceBaseTexture = 0 - private var radianceRgbStripeTexture = 0 - private var rcdStripeRawTexture = 0 - private var rcdStripeCapacityRows = 0 - private val rcdStripeBuffers = IntArray(9) + private var radianceFusionRejectionTexture = 0 + private var radianceFusionRejectionScratchTexture = 0 + private var radianceRgbTileTexture = 0 + private var radianceSemanticSeedTexture = 0 + private var radianceVgnPackedFloatTexture = 0 + private var radianceVgnPackedBayerTexture = 0 + private var radianceVgnPackedSmoothTexture = 0 + private var radianceVgnScaleTexture = 0 + private var radianceVgnMedianTexture = 0 + private var radianceVgnEdgeTexture = 0 + private var radianceVgnFull0Texture = 0 + private var radianceVgnFull1Texture = 0 + private var radianceVgnUbo = 0 + private var radianceVgnCapacityGeometry: RadianceVgnGeometry? = null + private var rcdRawRegionTexture = 0 + private var rcdRegionCapacityWidth = 0 + private var rcdRegionCapacityHeight = 0 + private val rcdRegionBuffers = IntArray(9) private var outputTexture = 0 private var hdrLinearOutputTexture = 0 private var lensShadingTexture = 0 @@ -423,8 +495,8 @@ class GlesRawStacker( superResolutionPhaseTracker.reset() resetSuperResolutionDecisionStats() val acceptedSuperResolutionFrames = ArrayList() - // Stripe reconstruction owns both MFSR and Radiance output. The CFA accumulator is - // only needed for MFNR output and optional diagnostic statistics. + // Deferred reconstruction owns MFSR stripes and Radiance tiles. The CFA accumulator + // is only needed for MFNR output and optional diagnostic statistics. val needsBaseAccumulator = !superResolutionEnabled || hwmfDebug.collectMetrics if (needsBaseAccumulator) { clearAccumulator() @@ -509,18 +581,24 @@ class GlesRawStacker( } else { SuperResolutionOutputDecision.Disabled } - val stripeReadTiming = if (superResolutionEnabled) { - reconstructSuperResolutionStripes( + val reconstructionReadTiming = when { + radianceFusionEnabled -> reconstructRadianceTiles( referenceImage = images[0], acceptedFrames = acceptedSuperResolutionFrames, - radianceOutputBuffer = if (radianceFusionEnabled) outputBuffer else null, + candidateFrameCount = (images.size - 1).coerceAtLeast(0), + outputBuffer = outputBuffer, ) - } else { - normalizeOutput() - null + superResolutionEnabled -> reconstructSuperResolutionStripes( + referenceImage = images[0], + acceptedFrames = acceptedSuperResolutionFrames, + ) + else -> { + normalizeOutput() + null + } } GlesGpuScheduler.yieldToUiRenderer() - val readTiming = stripeReadTiming ?: readOutput(outputBuffer) + val readTiming = reconstructionReadTiming ?: readOutput(outputBuffer) outputBuffer.rewind() val diagnostics = if (hwmfDebug.collectMetrics) { collectFinalDiagnostics( @@ -801,7 +879,18 @@ class GlesRawStacker( smoothFlowProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, SMOOTH_FLOW_FRAGMENT_SHADER, "raw_smooth_flow") structureProgram = linkComputeProgram(STRUCTURE_COMPUTE_SHADER, "raw_structure") robustnessProgram = linkComputeProgram(ROBUSTNESS_COMPUTE_SHADER, "raw_robustness") - tileMaskProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, TILE_MASK_FRAGMENT_SHADER, "raw_tile_mask") + tileMaskProgram = linkGraphicsProgram( + FULLSCREEN_VERTEX_SHADER, + tileMaskFragmentShader( + dualConfidence = dualTileConfidence, + trackRejectionReasons = visualizeRadianceFusionRejections, + ), + if (visualizeRadianceFusionRejections) { + "raw_tile_mask_with_rejection_reasons" + } else { + "raw_tile_mask" + }, + ) registrationSampleProgram = linkComputeProgram( REGISTRATION_SAMPLE_COMPUTE_SHADER, "raw_registration_samples", @@ -819,14 +908,35 @@ class GlesRawStacker( COPY_SCALAR_FRAGMENT_SHADER, "raw_copy_scalar", ) + if (dualTileConfidence) { + copyRgbaProgram = linkGraphicsProgram( + FULLSCREEN_VERTEX_SHADER, + COPY_RGBA_FRAGMENT_SHADER, + "raw_copy_rgba", + ) + } if (radianceFusionEnabled) { clearSuperResolutionAccumulatorProgram = linkComputeProgram( - GlesRawRadianceFusionShaders.clearAccumulator, - "raw_radiance_clear_r32ui_writeonly", + GlesRawRadianceFusionShaders.clearAccumulator( + visualizeRadianceFusionRejections, + ), + if (visualizeRadianceFusionRejections) { + "raw_radiance_clear_r32ui_rgba16f_writeonly" + } else { + "raw_radiance_clear_r32ui_writeonly" + }, ) accumulateSuperResolutionProgram = linkComputeProgram( - GlesRawRadianceFusionShaders.accumulate(RAW_COMMON), - "raw_radiance_accumulate_r32ui_read_write", + GlesRawRadianceFusionShaders.accumulate( + RAW_COMMON, + trackRejections = visualizeRadianceFusionRejections, + trackParticipation = logRadianceFusionParticipation, + ), + if (visualizeRadianceFusionRejections) { + "raw_radiance_accumulate_r32ui_read_write_rgba16f_ping_pong_writeonly" + } else { + "raw_radiance_accumulate_r32ui_read_write" + }, ) radianceReferenceBaseProgram = linkComputeProgram( GlesRawRadianceFusionShaders.captureReferenceBase, @@ -834,11 +944,20 @@ class GlesRawStacker( ) normalizeSuperResolutionProgram = linkGraphicsProgram( FULLSCREEN_VERTEX_SHADER, - GlesRawRadianceFusionShaders.normalize, + GlesRawRadianceFusionShaders.normalize( + showRejections = visualizeRadianceFusionRejections, + showSrDetail = visualizeRadianceSrDetail, + ), "raw_radiance_normalize_r32ui_usampler", ) - initRcdStripePrograms("raw_radiance") - initRcdStoreRgbProgram() + if (radianceUsesVgnSemanticBackend) { + initRadianceReconstructionPrograms() + } else { + // VGN is defined only for the four standard 2x2 Bayer layouts. Preserve + // Quad/Nona CFA support through the phase-aware region RCD backend. + initRcdRegionPrograms("raw_radiance_fallback") + initRcdStoreRgbProgram() + } } else { clearSuperResolutionAccumulatorProgram = linkComputeProgram( CLEAR_SUPER_RESOLUTION_ACCUMULATOR_COMPUTE_SHADER, @@ -853,35 +972,34 @@ class GlesRawStacker( SUPER_RESOLUTION_NORMALIZE_RCD_FRAGMENT_SHADER, "raw_sr_normalize", ) - initRcdStripePrograms("raw_sr") + initRcdRegionPrograms("raw_sr") } } initDiagnosticPrograms() } - private fun initRcdStripePrograms(labelPrefix: String) { - if (rcdStripePopulateProgram != 0) return - rcdStripePopulateProgram = linkComputeProgram( - RcdShaders.stripePopulate(RAW_COMMON), + private fun initRcdRegionPrograms(labelPrefix: String) { + if (rcdRegionPopulateProgram != 0) return + rcdRegionPopulateProgram = linkComputeProgram( + RcdShaders.regionPopulate(RAW_COMMON), "${labelPrefix}_rcd_populate", ) - rcdStripeStep1Program = linkComputeProgram(RcdShaders.STEP_1, "${labelPrefix}_rcd_step1") - rcdStripeStep2Program = linkComputeProgram(RcdShaders.STEP_2, "${labelPrefix}_rcd_step2") - rcdStripeStep3Program = linkComputeProgram(RcdShaders.STEP_3, "${labelPrefix}_rcd_step3") - rcdStripeStep40Program = linkComputeProgram(RcdShaders.STEP_4_0, "${labelPrefix}_rcd_step40") - rcdStripeStep41Program = linkComputeProgram(RcdShaders.STEP_4_1, "${labelPrefix}_rcd_step41") - rcdStripeStep42Program = linkComputeProgram(RcdShaders.STEP_4_2, "${labelPrefix}_rcd_step42") - rcdStripeStep43Program = linkComputeProgram(RcdShaders.STEP_4_3, "${labelPrefix}_rcd_step43") - rcdStripeBorderPpgProgram = linkComputeProgram( - RcdShaders.STRIPE_BORDER_PPG, + rcdRegionStep1Program = linkComputeProgram(RcdShaders.STEP_1, "${labelPrefix}_rcd_step1") + rcdRegionStep2Program = linkComputeProgram(RcdShaders.STEP_2, "${labelPrefix}_rcd_step2") + rcdRegionStep3Program = linkComputeProgram(RcdShaders.STEP_3, "${labelPrefix}_rcd_step3") + rcdRegionStep40Program = linkComputeProgram(RcdShaders.STEP_4_0, "${labelPrefix}_rcd_step40") + rcdRegionStep41Program = linkComputeProgram(RcdShaders.STEP_4_1, "${labelPrefix}_rcd_step41") + rcdRegionStep42Program = linkComputeProgram(RcdShaders.STEP_4_2, "${labelPrefix}_rcd_step42") + rcdRegionStep43Program = linkComputeProgram(RcdShaders.STEP_4_3, "${labelPrefix}_rcd_step43") + rcdRegionBorderPpgProgram = linkComputeProgram( + RcdShaders.REGION_BORDER_PPG, "${labelPrefix}_rcd_border_ppg", ) } - private fun initRcdStoreRgbProgram() { if (rcdStoreRgbProgram != 0) return rcdStoreRgbProgram = linkComputeProgram( - GlesRawHdrShaders.workingRgbStore, + GlesRawRcdShaders.workingRgbStore, "raw_rcd_store_rgb", ) } @@ -903,7 +1021,35 @@ class GlesRawStacker( GlesRawHdrShaders.rgbFusion(), "raw_hdr_rgb_fusion", ) - initRcdStripePrograms("raw_hdr") + initRcdRegionPrograms("raw_hdr") + } + + private fun initRadianceReconstructionPrograms() { + check(radianceUsesVgnSemanticBackend) + if (radianceVgnPrograms[0] != 0) return + radianceVgnPrograms[VgnShaders.PROGRAM_PREPARE] = linkComputeProgram( + GlesRadianceReconstructionShaders.vgnPrepareRegion, + "raw_radiance_vgn_prepare_region", + ) + for (index in VgnShaders.PROGRAM_NEUTRAL..VgnShaders.PROGRAM_3) { + val (name, source) = VgnShaders.PROGRAM_SOURCES[index] + radianceVgnPrograms[index] = linkComputeProgram( + source, + "raw_radiance_vgn_$name", + ) + } + radianceVgnFinalProgram = linkComputeProgram( + GlesRadianceReconstructionShaders.vgnYccdToCameraRgb, + "raw_radiance_vgn_yccd_to_camera_rgb", + ) + radianceSemanticSeedProgram = linkComputeProgram( + GlesRadianceReconstructionShaders.semanticSeed, + "raw_radiance_semantic_seed", + ) + radianceSemanticResolveProgram = linkComputeProgram( + GlesRadianceReconstructionShaders.semanticResolve, + "raw_radiance_semantic_resolve", + ) } private fun createHdrWeightMap(): GlesRawHdrWeightMap { @@ -958,18 +1104,29 @@ class GlesRawStacker( val maxTextureSize = IntArray(1) GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0) val maxSize = maxTextureSize[0].coerceAtLeast(1) - if (outputWidth > maxSize || outputHeight > maxSize) { + val requiredTextureWidth = if (radianceFusionEnabled) { + maxOf(width, radianceOutputTileWidth, superResolutionAccumulatorWidth) + } else { + maxOf(width, outputWidth) + } + val requiredTextureHeight = if (radianceFusionEnabled) { + maxOf(height, radianceOutputTileHeight, superResolutionAccumulatorHeight) + } else { + maxOf(height, outputHeight) + } + if (requiredTextureWidth > maxSize || requiredTextureHeight > maxSize) { throw IllegalStateException( - "RAW ${tuning.mode} output ${outputWidth}x$outputHeight exceeds GL_MAX_TEXTURE_SIZE=$maxSize", + "RAW ${tuning.mode} texture ${requiredTextureWidth}x$requiredTextureHeight " + + "exceeds GL_MAX_TEXTURE_SIZE=$maxSize", ) } if (superResolutionEnabled && RawStackRuntimeDebug.enabled) { val accumulatorBytesPerPixel = if (radianceFusionEnabled) { - 4L * 4L + 8L + 4L * 4L + 8L + if (visualizeRadianceFusionRejections) 16L else 0L } else { 4L * 3L } - val accumulatorBytes = outputWidth.toLong() * + val accumulatorBytes = superResolutionAccumulatorWidth.toLong() * superResolutionAccumulatorHeight.toLong() * accumulatorBytesPerPixel val baseAccumulatorBytes = if (!radianceFusionEnabled || hwmfDebug.collectMetrics) { @@ -982,7 +1139,8 @@ class GlesRawStacker( if (radianceFusionEnabled) 6L else 2L RawStackRuntimeDebug.d(TAG) { "HWMF $fusionPipeline resources out=${outputWidth}x$outputHeight maxTex=$maxSize " + - "srAccumulatorStripe=${accumulatorBytes.mibString()} " + + "srAccumulatorWindow=${superResolutionAccumulatorWidth}x" + + "$superResolutionAccumulatorHeight/${accumulatorBytes.mibString()} " + "baseAccumulator=${baseAccumulatorBytes.mibString()} " + "baseOutput=${baseOutputBytes.mibString()} output=${outputBytes.mibString()}" } @@ -1020,49 +1178,80 @@ class GlesRawStacker( flowScratchTexture = 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(gridWidth, gridHeight, GLES30.GL_R16F, GLES30.GL_LINEAR) + tileMaskTexture = createTexture2D( + gridWidth, + gridHeight, + if (dualTileConfidence) GLES30.GL_RGBA16F else GLES30.GL_R16F, + GLES30.GL_LINEAR, + ) if (!radianceFusionEnabled || hwmfDebug.collectMetrics) { accumulatorValueWeightTexture = createTexture2D(width, height, GLES30.GL_R32UI, GLES30.GL_NEAREST) accumulatorStatisticsTexture = createTexture2D(width, height, GLES30.GL_R32UI, GLES30.GL_NEAREST) } if (superResolutionEnabled) { superResolutionAccumulatorTexture = createTexture2D( - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, GLES30.GL_R32UI, GLES30.GL_NEAREST, ) superResolutionAccumulatorBwTexture = createTexture2D( - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, GLES30.GL_R32UI, GLES30.GL_NEAREST, ) superResolutionAccumulatorBTexture = createTexture2D( - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, GLES30.GL_R32UI, GLES30.GL_NEAREST, ) if (radianceFusionEnabled) { + radianceNrWeightRgTexture = createTexture2D( + superResolutionAccumulatorWidth, + superResolutionAccumulatorHeight, + GLES30.GL_R32UI, + GLES30.GL_NEAREST, + ) radianceDetailBwTexture = createTexture2D( - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, GLES30.GL_R32UI, GLES30.GL_NEAREST, ) radianceReferenceBaseTexture = createTexture2D( - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST, ) + radianceDetailWeightRgTexture = createTexture2D( + superResolutionAccumulatorWidth, + superResolutionAccumulatorHeight, + GLES30.GL_R32UI, + GLES30.GL_NEAREST, + ) + if (visualizeRadianceFusionRejections) { + radianceFusionRejectionTexture = createTexture2D( + superResolutionAccumulatorWidth, + superResolutionAccumulatorHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + radianceFusionRejectionScratchTexture = createTexture2D( + superResolutionAccumulatorWidth, + superResolutionAccumulatorHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + } } } outputTexture = createTexture2D( - outputWidth, + if (radianceFusionEnabled) radianceOutputTileWidth else outputWidth, if (radianceFusionEnabled) { - minOf(outputHeight, SUPER_RESOLUTION_STRIPE_ROWS) + radianceOutputTileHeight } else { outputHeight }, @@ -1173,30 +1362,37 @@ class GlesRawStacker( checkGlError("uploadRawTexture $label") } - private fun ensureRawStripeResource(capacityRows: Int) { - if (rcdStripeRawTexture != 0) { - require(capacityRows <= rcdStripeCapacityRows) { - "RAW stripe capacity $rcdStripeCapacityRows is smaller than required $capacityRows" + private fun ensureRawRegionTexture(capacityWidth: Int, capacityHeight: Int) { + val requestedWidth = capacityWidth.coerceIn(1, width) + val requestedHeight = capacityHeight.coerceIn(1, height) + if (rcdRawRegionTexture != 0) { + require( + requestedWidth <= rcdRegionCapacityWidth && + requestedHeight <= rcdRegionCapacityHeight, + ) { + "RCD region capacity ${rcdRegionCapacityWidth}x$rcdRegionCapacityHeight is " + + "smaller than required ${requestedWidth}x$requestedHeight" } return } - rcdStripeCapacityRows = capacityRows.coerceIn(1, height) - rcdStripeRawTexture = createTexture2D( - width, - rcdStripeCapacityRows, + rcdRegionCapacityWidth = requestedWidth + rcdRegionCapacityHeight = requestedHeight + rcdRawRegionTexture = createTexture2D( + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, GLES30.GL_R16UI, GLES30.GL_NEAREST, ) } - private fun ensureRcdStripeResources(capacityRows: Int) { - ensureRawStripeResource(capacityRows) - if (rcdStripeBuffers.firstOrNull() != 0) return - GLES31.glGenBuffers(rcdStripeBuffers.size, rcdStripeBuffers, 0) - val byteCount = width.toLong() * rcdStripeCapacityRows.toLong() * 4L - require(byteCount <= Int.MAX_VALUE) { "RCD stripe buffer exceeds GLES allocation range: $byteCount" } - rcdStripeBuffers.forEach { buffer -> - require(buffer != 0) { "Failed to allocate RCD stripe SSBO" } + private fun ensureRcdRegionResources(capacityWidth: Int, capacityHeight: Int) { + ensureRawRegionTexture(capacityWidth, capacityHeight) + if (rcdRegionBuffers[0] != 0) return + GLES31.glGenBuffers(rcdRegionBuffers.size, rcdRegionBuffers, 0) + val byteCount = rcdRegionCapacityWidth.toLong() * rcdRegionCapacityHeight.toLong() * 4L + require(byteCount <= Int.MAX_VALUE) { "RCD region buffer exceeds GLES allocation range: $byteCount" } + rcdRegionBuffers.forEach { buffer -> + require(buffer != 0) { "Failed to allocate RCD region SSBO" } buffers += buffer GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer) GLES31.glBufferData( @@ -1208,53 +1404,145 @@ class GlesRawStacker( } GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) RawStackRuntimeDebug.i(TAG) { - "MFSR RCD stripe=${width}x$rcdStripeCapacityRows ssbo=${(byteCount * 9L).mibString()}" + "RCD region=${rcdRegionCapacityWidth}x$rcdRegionCapacityHeight " + + "ssbo=${(byteCount * 9L).mibString()}" } } - private fun ensureRadianceRcdStripeResources(capacityRows: Int) { - ensureRcdStripeResources(capacityRows) - if (radianceRgbStripeTexture != 0) return - radianceRgbStripeTexture = createTexture2D( - width, - rcdStripeCapacityRows, + private fun ensureRcdStripeResources(capacityRows: Int) { + ensureRcdRegionResources(width, capacityRows) + } + + private fun ensureRadianceTileResources(capacityWidth: Int, capacityHeight: Int) { + if (!radianceUsesVgnSemanticBackend) { + ensureRcdRegionResources(capacityWidth, capacityHeight) + if (radianceRgbTileTexture == 0) { + radianceRgbTileTexture = createTexture2D( + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, + GLES30.GL_RGBA16F, + GLES30.GL_LINEAR, + ) + } + return + } + ensureRawRegionTexture(capacityWidth, capacityHeight) + if (radianceRgbTileTexture != 0) return + radianceRgbTileTexture = createTexture2D( + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR, ) + radianceSemanticSeedTexture = createTexture2D( + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + val geometry = RadianceVgnGeometry.forRegion( + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, + cfaPattern, + ) + radianceVgnCapacityGeometry = geometry + radianceVgnPackedFloatTexture = createTexture2D( + geometry.packedWidth, + geometry.workHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + radianceVgnPackedBayerTexture = createTexture2D( + geometry.packedWidth, + geometry.workHeight, + GLES30.GL_RGBA16UI, + GLES30.GL_NEAREST, + ) + radianceVgnPackedSmoothTexture = createTexture2D( + geometry.packedWidth, + geometry.workHeight, + GLES30.GL_RGBA16UI, + GLES30.GL_NEAREST, + ) + radianceVgnScaleTexture = createTexture2D( + geometry.workWidth, + geometry.halfHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + radianceVgnMedianTexture = createTexture2D( + geometry.packedWidth, + geometry.halfHeight, + GLES30.GL_RGBA16F, + GLES30.GL_NEAREST, + ) + radianceVgnEdgeTexture = createTexture2D( + geometry.packedWidth, + geometry.workHeight, + GLES30.GL_RGBA16I, + GLES30.GL_NEAREST, + ) + radianceVgnFull0Texture = createTexture2D( + geometry.workWidth, + geometry.workHeight, + GLES30.GL_RGBA16UI, + GLES30.GL_NEAREST, + ) + radianceVgnFull1Texture = createTexture2D( + geometry.workWidth, + geometry.workHeight, + GLES30.GL_RGBA16UI, + GLES30.GL_NEAREST, + ) + val ids = IntArray(1) + GLES31.glGenBuffers(1, ids, 0) + check(ids[0] != 0) { "Failed to allocate Radiance VGN UBO" } + radianceVgnUbo = ids[0] + buffers += radianceVgnUbo + RawStackRuntimeDebug.i(TAG) { + "Radiance reconstruction=VGN-reference/semantic-nonreference " + + "region=${rcdRegionCapacityWidth}x$rcdRegionCapacityHeight " + + "vgnWork=${geometry.workWidth}x${geometry.workHeight} " + + "colorDenoise=false iir=false" + } } private fun ensureHdrRcdStripeResources(capacityRows: Int) { ensureRcdStripeResources(capacityRows) if (hdrNormalRgbStripeTexture != 0) return hdrNormalRgbStripeTexture = createTexture2D( - width, - rcdStripeCapacityRows, + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR, ) hdrReferenceRgbStripeTexture = createTexture2D( - width, - rcdStripeCapacityRows, + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR, ) hdrShortRgbStripeTexture = createTexture2D( - width, - rcdStripeCapacityRows, + rcdRegionCapacityWidth, + rcdRegionCapacityHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR, ) } - private fun uploadRcdRawStripe(image: SafeImage, firstRow: Int, rowCount: Int, label: String) { - require(rcdStripeRawTexture != 0 && rowCount <= rcdStripeCapacityRows) + private fun uploadRcdRawRegion(image: SafeImage, region: RadianceTileRect, label: String) { + require( + rcdRawRegionTexture != 0 && + region.width <= rcdRegionCapacityWidth && + region.height <= rcdRegionCapacityHeight, + ) val plane = image.planes.firstOrNull() ?: throw IllegalArgumentException("$label has no RAW plane") require(plane.pixelStride == 2 && plane.rowStride >= width * 2 && plane.rowStride % 2 == 0) - require(firstRow >= 0 && rowCount > 0 && firstRow + rowCount <= height) + require(region.right <= width && region.bottom <= height) val uploadBuffer = plane.buffer.duplicate().order(ByteOrder.nativeOrder()).apply { - position(firstRow * plane.rowStride) + position(region.top * plane.rowStride + region.left * plane.pixelStride) } - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rcdStripeRawTexture) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rcdRawRegionTexture) GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, plane.rowStride / 2) GLES30.glTexSubImage2D( @@ -1262,111 +1550,147 @@ class GlesRawStacker( 0, 0, 0, - width, - rowCount, + region.width, + region.height, GLES30.GL_RED_INTEGER, GLES30.GL_UNSIGNED_SHORT, uploadBuffer, ) GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) - checkGlError("uploadRcdRawStripe $label") + checkGlError("uploadRcdRawRegion $label") } - private fun bindRcdStripeBuffers() { + private fun uploadRcdRawStripe(image: SafeImage, firstRow: Int, rowCount: Int, label: String) { + uploadRcdRawRegion(image, RadianceTileRect(0, firstRow, width, firstRow + rowCount), label) + } + + private fun bindRcdRegionBuffers() { for (index in 0..7) { - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, index, rcdStripeBuffers[index]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, index, rcdRegionBuffers[index]) } } + private fun runRcdRegion( + region: RadianceTileRect, + label: String, + reconstructHighlights: Boolean = true, + ) { + require(region.left % rawCfaPeriod == 0 && region.top % rawCfaPeriod == 0) { + "RCD region must preserve CFA phase: $region period=$rawCfaPeriod" + } + bindRcdRegionBuffers() + GLES31.glUseProgram(rcdRegionPopulateProgram) + bindTexture(rcdRegionPopulateProgram, "uRawRegion", 0, rcdRawRegionTexture) + bindTexture(rcdRegionPopulateProgram, "uLensShadingMap", 1, lensShadingTexture) + GLES31.glUniform2i( + uniformLocation(rcdRegionPopulateProgram, "uRegionSize"), + region.width, + region.height, + ) + GLES31.glUniform2i(uniformLocation(rcdRegionPopulateProgram, "uFullImageSize"), width, height) + GLES31.glUniform2i( + uniformLocation(rcdRegionPopulateProgram, "uGlobalOrigin"), + region.left, + region.top, + ) + GLES31.glUniform1i(uniformLocation(rcdRegionPopulateProgram, "uCfaPattern"), cfaPattern) + GLES31.glUniform4fv( + uniformLocation(rcdRegionPopulateProgram, "uBlackLevel"), + 1, + normalizedBlackLevel, + 0, + ) + GLES31.glUniform1f( + uniformLocation(rcdRegionPopulateProgram, "uWhiteLevel"), + normalizedWhiteLevel, + ) + GLES31.glUniform1i( + uniformLocation(rcdRegionPopulateProgram, "uReconstructHighlights"), + if (reconstructHighlights) 1 else 0, + ) + GLES31.glUniform4fv( + uniformLocation(rcdRegionPopulateProgram, "uCalculationWbGains"), + 1, + demosaicCalculationWbGains, + 0, + ) + GLES31.glDispatchCompute(groupCount(region.width), groupCount(region.height), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) + + completeRcdRegionWithPpgBorder(region, label) + } + private fun runRcdStripe( firstRow: Int, rowCount: Int, label: String, reconstructHighlights: Boolean = true, ) { - require(firstRow % 2 == 0) { "RCD stripe must preserve CFA row parity: $firstRow" } - bindRcdStripeBuffers() - GLES31.glUseProgram(rcdStripePopulateProgram) - bindTexture(rcdStripePopulateProgram, "uRawStripe", 0, rcdStripeRawTexture) - bindTexture(rcdStripePopulateProgram, "uLensShadingMap", 1, lensShadingTexture) - GLES31.glUniform2i(uniformLocation(rcdStripePopulateProgram, "uStripeSize"), width, rowCount) - GLES31.glUniform2i(uniformLocation(rcdStripePopulateProgram, "uFullImageSize"), width, height) - GLES31.glUniform1i(uniformLocation(rcdStripePopulateProgram, "uGlobalRowOffset"), firstRow) - GLES31.glUniform1i(uniformLocation(rcdStripePopulateProgram, "uCfaPattern"), cfaPattern) - GLES31.glUniform4fv( - uniformLocation(rcdStripePopulateProgram, "uBlackLevel"), - 1, - normalizedBlackLevel, - 0, + runRcdRegion( + RadianceTileRect(0, firstRow, width, firstRow + rowCount), + label, + reconstructHighlights, ) - GLES31.glUniform1f( - uniformLocation(rcdStripePopulateProgram, "uWhiteLevel"), - normalizedWhiteLevel, - ) - GLES31.glUniform1i( - uniformLocation(rcdStripePopulateProgram, "uReconstructHighlights"), - if (reconstructHighlights) 1 else 0, - ) - GLES31.glUniform4fv( - uniformLocation(rcdStripePopulateProgram, "uCalculationWbGains"), - 1, - demosaicCalculationWbGains, - 0, - ) - GLES31.glDispatchCompute(groupCount(width), groupCount(rowCount), 1) - GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) - - runRcdSteps(firstRow, rowCount, label) } - private fun runRcdSteps(firstRow: Int, rowCount: Int, label: String) { - require(firstRow % 2 == 0) { "RCD stripe must preserve CFA row parity: $firstRow" } - bindRcdStripeBuffers() + /** + * Completes one shared demosaic operation. RCD owns the reliable interior and PPG owns the + * physical photo border; callers cannot dispatch one without the other. + */ + private fun completeRcdRegionWithPpgBorder(region: RadianceTileRect, label: String) { + require(region.left % rawCfaPeriod == 0 && region.top % rawCfaPeriod == 0) + check(rcdRegionBorderPpgProgram != 0) { "RCD region PPG border program is not initialized" } + bindRcdRegionBuffers() fun dispatch(program: Int, halfWidth: Boolean, step: String) { GLES31.glUseProgram(program) - GLES31.glUniform2i(uniformLocation(program, "uImageSize"), width, rowCount) + GLES31.glUniform2i(uniformLocation(program, "uImageSize"), region.width, region.height) val cfaLocation = uniformLocation(program, "uCfaPattern") if (cfaLocation >= 0) GLES31.glUniform1i(cfaLocation, cfaPattern) - GLES31.glDispatchCompute(groupCount(if (halfWidth) (width + 1) / 2 else width), groupCount(rowCount), 1) + GLES31.glDispatchCompute( + groupCount(if (halfWidth) (region.width + 1) / 2 else region.width), + groupCount(region.height), + 1, + ) GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) - checkGlError("RCD stripe $step $label") + checkGlError("RCD region $step $label") } - dispatch(rcdStripeStep1Program, false, "step1") - dispatch(rcdStripeStep2Program, true, "step2") - dispatch(rcdStripeStep3Program, true, "step3") - dispatch(rcdStripeStep40Program, true, "step40") - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 5, rcdStripeBuffers[8]) - dispatch(rcdStripeStep41Program, true, "step41") - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdStripeBuffers[8]) - dispatch(rcdStripeStep42Program, true, "step42") - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdStripeBuffers[4]) - dispatch(rcdStripeStep43Program, true, "step43") + dispatch(rcdRegionStep1Program, false, "step1") + dispatch(rcdRegionStep2Program, true, "step2") + dispatch(rcdRegionStep3Program, true, "step3") + dispatch(rcdRegionStep40Program, true, "step40") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 5, rcdRegionBuffers[8]) + dispatch(rcdRegionStep41Program, true, "step41") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdRegionBuffers[8]) + dispatch(rcdRegionStep42Program, true, "step42") + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 4, rcdRegionBuffers[4]) + dispatch(rcdRegionStep43Program, true, "step43") - GLES31.glUseProgram(rcdStripeBorderPpgProgram) + GLES31.glUseProgram(rcdRegionBorderPpgProgram) GLES31.glUniform2i( - uniformLocation(rcdStripeBorderPpgProgram, "uStripeSize"), - width, - rowCount, + uniformLocation(rcdRegionBorderPpgProgram, "uRegionSize"), + region.width, + region.height, ) GLES31.glUniform2i( - uniformLocation(rcdStripeBorderPpgProgram, "uFullImageSize"), + uniformLocation(rcdRegionBorderPpgProgram, "uFullImageSize"), width, height, ) - GLES31.glUniform1i( - uniformLocation(rcdStripeBorderPpgProgram, "uGlobalRowOffset"), - firstRow, + GLES31.glUniform2i( + uniformLocation(rcdRegionBorderPpgProgram, "uGlobalOrigin"), + region.left, + region.top, ) GLES31.glUniform1i( - uniformLocation(rcdStripeBorderPpgProgram, "uCfaPattern"), + uniformLocation(rcdRegionBorderPpgProgram, "uCfaPattern"), cfaPattern, ) - GLES31.glDispatchCompute(groupCount(width), groupCount(rowCount), 1) + GLES31.glDispatchCompute(groupCount(region.width), groupCount(region.height), 1) GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) - checkGlError("RCD stripe border PPG $label") + checkGlError("RCD region border PPG $label") } private fun validExposureProduct(exposureProduct: Double): Double { @@ -2009,6 +2333,27 @@ class GlesRawStacker( finishFramebufferPass(label) } + private fun copyRgbaTexture( + input: Int, + output: Int, + copyWidth: Int, + copyHeight: Int, + label: String, + ) { + check(copyRgbaProgram != 0) { "RGBA copy program is unavailable for $label" } + bindFramebufferOutput(output, label) + GLES30.glViewport(0, 0, copyWidth, copyHeight) + GLES30.glUseProgram(copyRgbaProgram) + bindTexture(copyRgbaProgram, "uInput", 0, input) + GLES31.glUniform2i( + GLES31.glGetUniformLocation(copyRgbaProgram, "uImageSize"), + copyWidth, + copyHeight, + ) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass(label) + } + private fun cacheAcceptedSuperResolutionFrame( frameIndex: Int, image: SafeImage, @@ -2024,13 +2369,19 @@ class GlesRawStacker( if (radianceFusionEnabled) GLES30.GL_R16F else GLES30.GL_R8, GLES30.GL_NEAREST, ) - val cachedTileMask = createTexture2D(gridWidth, gridHeight, GLES30.GL_R16F, GLES30.GL_LINEAR) + val cachedTileMaskBytesPerPixel = if (dualTileConfidence) 8L else 2L + val cachedTileMask = createTexture2D( + gridWidth, + gridHeight, + if (dualTileConfidence) GLES30.GL_RGBA16F else GLES30.GL_R16F, + GLES30.GL_LINEAR, + ) RawStackRuntimeDebug.d(TAG) { val cacheBytes = planeWidth.toLong() * planeHeight * cachedRobustnessBytesPerPixel + - gridWidth.toLong() * gridHeight * (8L + 2L) + gridWidth.toLong() * gridHeight * (8L + cachedTileMaskBytesPerPixel) "Cache $fusionPipeline frame=$frameIndex alignment=${cacheBytes.mibString()} " + "robustness=${if (radianceFusionEnabled) "R16F" else "R8"} " + - "flow=RGBA16F tile=R16F" + "flow=RGBA16F tile=${if (dualTileConfidence) "RGBA16F" else "R16F"}" } copyFlow(flowTexture, cachedFlow, "cache $fusionPipeline flow frame $frameIndex") copyScalarTexture( @@ -2040,24 +2391,41 @@ class GlesRawStacker( planeHeight, "cache $fusionPipeline robustness frame $frameIndex", ) - copyScalarTexture( - tileMaskTexture, - cachedTileMask, - gridWidth, - gridHeight, - "cache $fusionPipeline tile mask frame $frameIndex", - ) + if (dualTileConfidence) { + copyRgbaTexture( + tileMaskTexture, + cachedTileMask, + gridWidth, + gridHeight, + "cache $fusionPipeline dual tile confidence frame $frameIndex", + ) + } else { + copyScalarTexture( + tileMaskTexture, + cachedTileMask, + gridWidth, + gridHeight, + "cache $fusionPipeline tile mask frame $frameIndex", + ) + } val flowValues = readFlowTexture( texture = cachedFlow, textureWidth = gridWidth, textureHeight = gridHeight, label = "cache $fusionPipeline flow bounds frame $frameIndex", ) + var minFlowX = 0f + var maxFlowX = 0f var minFlowY = 0f var maxFlowY = 0f - var index = 1 + var index = 0 while (index < flowValues.size) { - val flowY = flowValues[index] + val flowX = flowValues[index] + val flowY = flowValues[index + 1] + if (flowX.isFinite()) { + minFlowX = minOf(minFlowX, flowX) + maxFlowX = maxOf(maxFlowX, flowX) + } if (flowY.isFinite()) { minFlowY = minOf(minFlowY, flowY) maxFlowY = maxOf(maxFlowY, flowY) @@ -2073,6 +2441,8 @@ class GlesRawStacker( flowTexture = cachedFlow, robustnessTexture = cachedRobustness, tileMaskTexture = cachedTileMask, + minFlowXPlanePx = minFlowX, + maxFlowXPlanePx = maxFlowX, minFlowYPlanePx = minFlowY, maxFlowYPlanePx = maxFlowY, ) @@ -2088,7 +2458,7 @@ class GlesRawStacker( GLES31.glUniform2i(GLES31.glGetUniformLocation(robustnessProgram, "uPlaneSize"), planeWidth, planeHeight) GLES31.glUniform2i(GLES31.glGetUniformLocation(robustnessProgram, "uGridSize"), gridWidth, gridHeight) GLES31.glUniform1i(GLES31.glGetUniformLocation(robustnessProgram, "uTileSize"), flowGridSpacing) - setBlendRobustnessUniforms(robustnessProgram) + setNrRobustnessUniforms(robustnessProgram) GLES31.glDispatchCompute(groupCount(planeWidth), groupCount(planeHeight), 1) GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("computeRobustness") @@ -2100,6 +2470,13 @@ class GlesRawStacker( GLES30.glUseProgram(tileMaskProgram) bindTexture(tileMaskProgram, "uReference", 0, refProxy) bindTexture(tileMaskProgram, "uRobustness", 1, robustnessTexture) + if (dualTileConfidence) { + bindTexture(tileMaskProgram, "uFlowGrid", 3, flowTexture) + setDetailConfidenceUniforms(tileMaskProgram) + } + if (visualizeRadianceFusionRejections) { + bindTexture(tileMaskProgram, "uCurrent", 2, curProxy) + } GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uPlaneSize"), planeWidth, planeHeight) GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uGridSize"), gridWidth, gridHeight) GLES31.glUniform1i(GLES31.glGetUniformLocation(tileMaskProgram, "uTileSize"), flowGridSpacing) @@ -2211,47 +2588,82 @@ class GlesRawStacker( dy = summary.medianDyPlanePx * 2f, ) currentTemporalFlowPhase = phase - val accepted = summary.validTileFraction >= hwmfPrefilter.temporalGraphFrameMinCoverage && + val detailAccepted = summary.validTileFraction >= hwmfPrefilter.temporalGraphFrameMinCoverage && summary.meanConfidence >= hwmfPrefilter.temporalGraphFrameMinMeanConfidence && summary.coveredQuadrants >= hwmfPrefilter.temporalGraphFrameMinQuadrants.coerceIn(1, 4) && summary.residualP90PlanePx <= hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx - val coverageWeight = smoothStep( + val detailCoverageWeight = smoothStep( hwmfPrefilter.temporalGraphFrameMinCoverage, max(hwmfPrefilter.temporalGraphFrameMinCoverage * 3f, 0.35f), summary.validTileFraction, ) - val confidenceWeight = smoothStep( + val detailConfidenceWeight = smoothStep( hwmfPrefilter.temporalGraphFrameMinMeanConfidence, max(hwmfPrefilter.temporalGraphFrameMinMeanConfidence * 3f, 0.20f), summary.meanConfidence, ) - val residualWeight = 1f - smoothStep( + val detailResidualWeight = 1f - smoothStep( hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx * 0.5f, hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx, summary.residualP90PlanePx, ) val spatialWeight = summary.coveredQuadrants / 4f - val frameWeight = minOf( - coverageWeight, - confidenceWeight, - residualWeight, + val detailFrameWeight = minOf( + detailCoverageWeight, + detailConfidenceWeight, + detailResidualWeight, spatialWeight, ).coerceIn(0f, 1f) - val phaseNovelty = if (accepted) { + val nrUsable = summary.validTileCount > 0 && + summary.totalTileCount > 0 && + summary.coveredQuadrants > 0 && + summary.validTileFraction.isFinite() && + summary.meanConfidence.isFinite() && + summary.residualP90PlanePx.isFinite() + val nrCoverageWeight = smoothStep( + 0f, + max(hwmfPrefilter.temporalGraphFrameMinCoverage * 3f, 0.35f), + summary.validTileFraction, + ) + val nrConfidenceWeight = smoothStep( + 0f, + max(hwmfPrefilter.temporalGraphFrameMinMeanConfidence * 3f, 0.20f), + summary.meanConfidence, + ) + val nrResidualWeight = 1f - smoothStep( + hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx, + hwmfPrefilter.temporalGraphFrameMaxResidualP90PlanePx * 2f, + summary.residualP90PlanePx, + ) + val nrFrameWeight = minOf( + nrCoverageWeight, + nrConfidenceWeight, + nrResidualWeight, + spatialWeight, + ).coerceIn(0f, 1f) + val nrAccepted = nrUsable && nrFrameWeight > 0f + val accepted = if (radianceFusionEnabled) nrAccepted else detailAccepted + val phaseNovelty = if (detailAccepted) { superResolutionPhaseTracker.noveltyWeight(phase.dx, phase.dy) } else { 0f } - currentRegistrationSrWeight = if (accepted) frameWeight else 0f - currentRegistrationNrWeight = if (accepted) frameWeight else 0f + currentRegistrationSrWeight = if (detailAccepted) detailFrameWeight else 0f + currentRegistrationNrWeight = if (radianceFusionEnabled) { + if (nrAccepted) nrFrameWeight else 0f + } else { + if (detailAccepted) detailFrameWeight else 0f + } currentRegistrationSrDetailWeight = currentRegistrationSrWeight * phaseNovelty RawStackRuntimeDebug.d(TAG) { - "Temporal frame=$frameIndex accepted=$accepted tiles=${summary.validTileCount}/" + + "Temporal frame=$frameIndex nrAccepted=$nrAccepted detailAccepted=$detailAccepted " + + "tiles=${summary.validTileCount}/" + "${summary.totalTileCount} quadrants=${summary.coveredQuadrants} " + "confidence=${summary.meanConfidence.formatWeight()} " + "resP90=${summary.residualP90PlanePx.formatPx()} " + "phase=[${phase.dx.formatPx()} ${phase.dy.formatPx()}] " + - "srWeight=${currentRegistrationSrWeight.formatWeight()}" + "nrWeight=${currentRegistrationNrWeight.formatWeight()} " + + "detailWeight=${currentRegistrationSrWeight.formatWeight()}" } return accepted } @@ -2942,6 +3354,10 @@ class GlesRawStacker( GLES31.glUniform2i(uniformLocation(registrationSampleProgram, "uPlaneSize"), planeWidth, planeHeight) GLES31.glUniform2i(uniformLocation(registrationSampleProgram, "uGridSize"), gridWidth, gridHeight) GLES31.glUniform1i(uniformLocation(registrationSampleProgram, "uTileSize"), flowGridSpacing) + GLES31.glUniform1i( + uniformLocation(registrationSampleProgram, "uUseDetailTileConfidence"), + if (dualTileConfidence) 1 else 0, + ) GLES31.glDispatchCompute(groupCount(gridWidth), groupCount(gridHeight), 1) GLES31.glMemoryBarrier( GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT @@ -3070,8 +3486,18 @@ class GlesRawStacker( if (radianceFusionEnabled) { bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) bindImage(1, superResolutionAccumulatorBwTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) - bindImage(2, superResolutionAccumulatorBTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) - bindImage(3, radianceDetailBwTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(2, radianceNrWeightRgTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(3, superResolutionAccumulatorBTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(4, radianceDetailBwTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + bindImage(5, radianceDetailWeightRgTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) + if (visualizeRadianceFusionRejections) { + bindImage( + 6, + radianceFusionRejectionTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ) + } } else { bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) bindImage(1, superResolutionAccumulatorBwTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_R32UI) @@ -3079,10 +3505,14 @@ class GlesRawStacker( } GLES31.glUniform2i( uniformLocation(clearSuperResolutionAccumulatorProgram, "uImageSize"), - outputWidth, + superResolutionAccumulatorWidth, superResolutionAccumulatorHeight, ) - GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(superResolutionAccumulatorHeight), 1) + GLES31.glDispatchCompute( + groupCount(superResolutionAccumulatorWidth), + groupCount(superResolutionAccumulatorHeight), + 1, + ) GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) checkGlError("clearSuperResolutionAccumulator") } @@ -3239,21 +3669,6 @@ class GlesRawStacker( outputRowOffset: Int = 0, outputRowCount: Int = superResolutionAccumulatorHeight, ) { - if (radianceFusionEnabled) { - accumulateRadianceFusionFrame( - isReference = isReference, - sourceRowOffset = sourceRowOffset, - sourceRowCount = sourceRowCount, - frameFlowTexture = frameFlowTexture, - frameRobustnessTexture = frameRobustnessTexture, - frameTileMaskTexture = frameTileMaskTexture, - registrationWeight = registrationWeight, - detailWeight = detailWeight, - outputRowOffset = outputRowOffset, - outputRowCount = outputRowCount, - ) - return - } GLES31.glUseProgram(accumulateSuperResolutionProgram) bindTexture(accumulateSuperResolutionProgram, "uFlowGrid", 1, frameFlowTexture) bindTexture(accumulateSuperResolutionProgram, "uRobustness", 2, frameRobustnessTexture) @@ -3263,9 +3678,9 @@ class GlesRawStacker( bindImage(0, superResolutionAccumulatorTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) bindImage(1, superResolutionAccumulatorBwTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) bindImage(2, superResolutionAccumulatorBTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, rcdStripeBuffers[1]) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, rcdStripeBuffers[2]) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 3, rcdStripeBuffers[3]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, rcdRegionBuffers[1]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, rcdRegionBuffers[2]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 3, rcdRegionBuffers[3]) setCommonUniforms(accumulateSuperResolutionProgram) GLES31.glUniform2i( uniformLocation(accumulateSuperResolutionProgram, "uImageSize"), @@ -3357,23 +3772,31 @@ class GlesRawStacker( private fun accumulateRadianceFusionFrame( isReference: Boolean, - sourceRowOffset: Int, - sourceRowCount: Int, + sourceRegion: RadianceTileRect, + accumulatorRegion: RadianceTileRect, frameFlowTexture: Int, frameRobustnessTexture: Int, frameTileMaskTexture: Int, registrationWeight: Float, detailWeight: Float, - outputRowOffset: Int, - outputRowCount: Int, + fusionStatsBuffer: Int, + fusionStatsIndex: Int, + fusionStatsCoreRegion: RadianceTileRect, + recordFusionRejections: Boolean, ) { GLES31.glUseProgram(accumulateSuperResolutionProgram) - bindTexture(accumulateSuperResolutionProgram, "uRcdRgbStripe", 0, radianceRgbStripeTexture) + bindTexture(accumulateSuperResolutionProgram, "uRcdRgbTile", 0, radianceRgbTileTexture) bindTexture(accumulateSuperResolutionProgram, "uFlowGrid", 1, frameFlowTexture) bindTexture(accumulateSuperResolutionProgram, "uRobustness", 2, frameRobustnessTexture) bindTexture(accumulateSuperResolutionProgram, "uTileMask", 3, frameTileMaskTexture) bindTexture(accumulateSuperResolutionProgram, "uKernel", 4, kernelTexture) bindTexture(accumulateSuperResolutionProgram, "uLensShadingMap", 5, lensShadingTexture) + bindTexture( + accumulateSuperResolutionProgram, + "uReferenceBase", + 6, + radianceReferenceBaseTexture, + ) bindImage( 0, superResolutionAccumulatorTexture, @@ -3388,16 +3811,72 @@ class GlesRawStacker( ) bindImage( 2, - superResolutionAccumulatorBTexture, + radianceNrWeightRgTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI, ) bindImage( 3, + superResolutionAccumulatorBTexture, + GLES31.GL_READ_WRITE, + GLES30.GL_R32UI, + ) + bindImage( + 4, radianceDetailBwTexture, GLES31.GL_READ_WRITE, GLES30.GL_R32UI, ) + bindImage( + 5, + radianceDetailWeightRgTexture, + GLES31.GL_READ_WRITE, + GLES30.GL_R32UI, + ) + if (visualizeRadianceFusionRejections) { + bindTexture( + accumulateSuperResolutionProgram, + "uPreviousFusionRejections", + 7, + radianceFusionRejectionTexture, + ) + bindImage( + 6, + radianceFusionRejectionScratchTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glUniform1i( + uniformLocation(accumulateSuperResolutionProgram, "uRecordFusionRejections"), + if (recordFusionRejections) 1 else 0, + ) + } + if (logRadianceFusionParticipation) { + check(fusionStatsBuffer != 0) { "Radiance fusion stats buffer is unavailable" } + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + RADIANCE_FUSION_STATS_BUFFER_BINDING, + fusionStatsBuffer, + ) + GLES31.glUniform1i( + uniformLocation(accumulateSuperResolutionProgram, "uFusionStatsIndex"), + fusionStatsIndex, + ) + GLES31.glUniform1i( + uniformLocation(accumulateSuperResolutionProgram, "uFusionStatsSampleStep"), + hwmfDebug.radianceFusionStatsSampleStep, + ) + GLES31.glUniform2i( + uniformLocation(accumulateSuperResolutionProgram, "uFusionStatsCoreOrigin"), + fusionStatsCoreRegion.left, + fusionStatsCoreRegion.top, + ) + GLES31.glUniform2i( + uniformLocation(accumulateSuperResolutionProgram, "uFusionStatsCoreSize"), + fusionStatsCoreRegion.width, + fusionStatsCoreRegion.height, + ) + } setCommonUniforms(accumulateSuperResolutionProgram) GLES31.glUniform2i( uniformLocation(accumulateSuperResolutionProgram, "uImageSize"), @@ -3406,12 +3885,13 @@ class GlesRawStacker( ) GLES31.glUniform2i( uniformLocation(accumulateSuperResolutionProgram, "uSourceSize"), - width, - sourceRowCount, + sourceRegion.width, + sourceRegion.height, ) - GLES31.glUniform1i( - uniformLocation(accumulateSuperResolutionProgram, "uSourceRowOffset"), - sourceRowOffset, + GLES31.glUniform2i( + uniformLocation(accumulateSuperResolutionProgram, "uSourceOrigin"), + sourceRegion.left, + sourceRegion.top, ) GLES31.glUniform2i( uniformLocation(accumulateSuperResolutionProgram, "uOutputSize"), @@ -3436,9 +3916,9 @@ class GlesRawStacker( uniformLocation(accumulateSuperResolutionProgram, "uIsReference"), if (isReference) 1 else 0, ) - GLES31.glUniform1f( - uniformLocation(accumulateSuperResolutionProgram, "uOutputScale"), - superResolutionScale, + GLES31.glUniform1i( + uniformLocation(accumulateSuperResolutionProgram, "uSemanticEncoding"), + if (radianceUsesVgnSemanticBackend) 1 else 0, ) GLES31.glUniform1f( uniformLocation(accumulateSuperResolutionProgram, "uFrameWeight"), @@ -3464,25 +3944,55 @@ class GlesRawStacker( uniformLocation(accumulateSuperResolutionProgram, "uRobustnessSpatialMix"), radianceFusionTuning.robustnessSpatialMix.coerceIn(0f, 1f), ) + val chromaSigmaStart = radianceFusionTuning.chromaConsistencySigmaStart.coerceAtLeast(0f) + GLES31.glUniform1f( + uniformLocation(accumulateSuperResolutionProgram, "uChromaConsistencySigmaStart"), + chromaSigmaStart, + ) + GLES31.glUniform1f( + uniformLocation(accumulateSuperResolutionProgram, "uChromaConsistencySigmaFull"), + radianceFusionTuning.chromaConsistencySigmaFull.coerceAtLeast(chromaSigmaStart + 1e-3f), + ) setBlendAccumulatorUniforms(accumulateSuperResolutionProgram) - val safeRowCount = outputRowCount.coerceIn(1, superResolutionAccumulatorHeight) - GLES31.glUniform1i( - uniformLocation(accumulateSuperResolutionProgram, "uOutputRowOffset"), - outputRowOffset, + GLES31.glUniform2i( + uniformLocation(accumulateSuperResolutionProgram, "uAccumulatorOrigin"), + accumulatorRegion.left, + accumulatorRegion.top, ) - GLES31.glUniform1i( - uniformLocation(accumulateSuperResolutionProgram, "uOutputRowCount"), - safeRowCount, + GLES31.glUniform2i( + uniformLocation(accumulateSuperResolutionProgram, "uAccumulatorSize"), + accumulatorRegion.width, + accumulatorRegion.height, + ) + GLES31.glDispatchCompute( + groupCount(accumulatorRegion.width), + groupCount(accumulatorRegion.height), + 1, ) - GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(safeRowCount), 1) GLES31.glMemoryBarrier( GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or - GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, + GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or + (if (logRadianceFusionParticipation) { + GLES31.GL_SHADER_STORAGE_BARRIER_BIT + } else { + 0 + }), ) - checkGlError("accumulateRadianceFusionFrame") + checkGlError( + if (visualizeRadianceFusionRejections) { + "accumulateRadianceFusionFrame RGBA16F ping-pong write-only" + } else { + "accumulateRadianceFusionFrame" + }, + ) + if (visualizeRadianceFusionRejections) { + val previousRejections = radianceFusionRejectionTexture + radianceFusionRejectionTexture = radianceFusionRejectionScratchTexture + radianceFusionRejectionScratchTexture = previousRejections + } } - private fun captureRadianceReferenceBase(rowCount: Int) { + private fun captureRadianceReferenceBase(regionWidth: Int, regionHeight: Int) { GLES31.glUseProgram(radianceReferenceBaseProgram) bindTexture( radianceReferenceBaseProgram, @@ -3496,6 +4006,12 @@ class GlesRawStacker( 1, superResolutionAccumulatorBwTexture, ) + bindTexture( + radianceReferenceBaseProgram, + "uNrWeightRg", + 2, + radianceNrWeightRgTexture, + ) bindImage( 0, radianceReferenceBaseTexture, @@ -3504,10 +4020,10 @@ class GlesRawStacker( ) GLES31.glUniform2i( uniformLocation(radianceReferenceBaseProgram, "uImageSize"), - outputWidth, - rowCount, + regionWidth, + regionHeight, ) - GLES31.glDispatchCompute(groupCount(outputWidth), groupCount(rowCount), 1) + GLES31.glDispatchCompute(groupCount(regionWidth), groupCount(regionHeight), 1) GLES31.glMemoryBarrier( GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, @@ -3585,7 +4101,7 @@ class GlesRawStacker( sourceRowCount: Int, referenceExposureScale: Float, ) { - bindRcdStripeBuffers() + bindRcdRegionBuffers() GLES31.glUseProgram(hdrNormalCfaInputProgram) bindTexture(hdrNormalCfaInputProgram, "uAccumulatorValueWeight", 0, accumulatorValueWeightTexture) bindTexture(hdrNormalCfaInputProgram, "uReferenceRaw", 1, refRaw) @@ -3612,19 +4128,24 @@ class GlesRawStacker( checkGlError("HDR normal RCD populate") } - private fun storeRcdRgbStripe( + private fun storeRcdRgbRegion( targetTexture: Int, - rowCount: Int, + regionWidth: Int, + regionHeight: Int, label: String, exposureScale: Float = 1f, desaturateBeforeExposureScale: Boolean = false, ) { GLES31.glUseProgram(rcdStoreRgbProgram) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, rcdStripeBuffers[1]) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, rcdStripeBuffers[2]) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 3, rcdStripeBuffers[3]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, rcdRegionBuffers[1]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 2, rcdRegionBuffers[2]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 3, rcdRegionBuffers[3]) bindImage(0, targetTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) - GLES31.glUniform2i(uniformLocation(rcdStoreRgbProgram, "uSourceSize"), width, rowCount) + GLES31.glUniform2i( + uniformLocation(rcdStoreRgbProgram, "uSourceSize"), + regionWidth, + regionHeight, + ) GLES31.glUniform1f( uniformLocation(rcdStoreRgbProgram, "uExposureScale"), exposureScale, @@ -3639,13 +4160,30 @@ class GlesRawStacker( 1f, demosaicCalculationWbGains[3], ) - GLES31.glDispatchCompute(groupCount(width), groupCount(rowCount), 1) + GLES31.glDispatchCompute(groupCount(regionWidth), groupCount(regionHeight), 1) GLES31.glMemoryBarrier( GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, ) checkGlError(label) } + private fun storeRcdRgbStripe( + targetTexture: Int, + rowCount: Int, + label: String, + exposureScale: Float = 1f, + desaturateBeforeExposureScale: Boolean = false, + ) { + storeRcdRgbRegion( + targetTexture = targetTexture, + regionWidth = width, + regionHeight = rowCount, + label = label, + exposureScale = exposureScale, + desaturateBeforeExposureScale = desaturateBeforeExposureScale, + ) + } + private fun reconstructHdrRgbStripes( shortImage: SafeImage, referenceImage: SafeImage, @@ -3711,7 +4249,10 @@ class GlesRawStacker( sourceRowCount = normalBand.rowCount, referenceExposureScale = referenceExposureScale, ) - runRcdSteps(normalBand.firstRow, normalBand.rowCount, "HDR normal") + completeRcdRegionWithPpgBorder( + RadianceTileRect(0, normalBand.firstRow, width, normalBand.endExclusive), + "HDR normal", + ) storeRcdRgbStripe(hdrNormalRgbStripeTexture, normalBand.rowCount, "HDR normal RGB store") uploadRcdRawStripe(referenceImage, normalBand.firstRow, normalBand.rowCount, "HDR reference") @@ -3828,11 +4369,981 @@ class GlesRawStacker( finishFramebufferPass(label) } + private fun createRadianceFusionStatsBuffer(frameCount: Int): Int { + require(frameCount > 0) { "Radiance fusion stats require at least one frame" } + val byteCount = frameCount * RADIANCE_FUSION_STATS_STRIDE * Int.SIZE_BYTES + val zero = ByteBuffer.allocateDirect(byteCount).order(ByteOrder.nativeOrder()) + val ids = IntArray(1) + GLES31.glGenBuffers(1, ids, 0) + val buffer = ids[0] + check(buffer != 0) { "Failed to allocate Radiance fusion stats buffer" } + buffers += buffer + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer) + GLES31.glBufferData( + GLES31.GL_SHADER_STORAGE_BUFFER, + byteCount, + zero, + GLES31.GL_DYNAMIC_READ, + ) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + checkGlError("createRadianceFusionStatsBuffer") + return buffer + } + + private fun logRadianceFusionStats( + buffer: Int, + frameIndices: IntArray, + candidateFrameCount: Int, + ) { + if (buffer == 0 || frameIndices.isEmpty()) return + val uintCount = frameIndices.size * RADIANCE_FUSION_STATS_STRIDE + val byteCount = uintCount * Int.SIZE_BYTES + val stats = try { + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, buffer) + val mapped = GLES31.glMapBufferRange( + GLES31.GL_SHADER_STORAGE_BUFFER, + 0, + byteCount, + GLES31.GL_MAP_READ_BIT, + ) ?: throw IllegalStateException("Radiance fusion stats buffer map failed") + try { + val byteBuffer = mapped as? ByteBuffer + ?: throw IllegalStateException("Radiance fusion stats mapping is not ByteBuffer") + IntArray(uintCount).also { values -> + byteBuffer.order(ByteOrder.nativeOrder()).asIntBuffer().get(values) + } + } finally { + GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) + } + } finally { + GLES31.glBindBufferBase( + GLES31.GL_SHADER_STORAGE_BUFFER, + RADIANCE_FUSION_STATS_BUFFER_BINDING, + 0, + ) + GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) + } + + var nonReferenceSamples = 0L + var nonReferenceNrAccepted = 0L + var nonReferenceNrWeight = 0L + var nonReferenceDetailAccepted = 0L + var nonReferenceDetailWeight = 0L + frameIndices.forEachIndexed { statsIndex, frameIndex -> + val offset = statsIndex * RADIANCE_FUSION_STATS_STRIDE + val samples = uintStat(stats, offset) + val nrAccepted = uintStat(stats, offset + 1) + val nrWeight = uintStat(stats, offset + 2) + val detailAccepted = uintStat(stats, offset + 3) + val detailWeight = uintStat(stats, offset + 4) + val nrParticipation = ratioStat(nrAccepted, samples) + val detailParticipation = ratioStat(detailAccepted, samples) + val nrMergeFactor = if (samples > 0L) { + nrWeight.toFloat() / (samples * RADIANCE_FUSION_WEIGHT_QUANTIZATION) + } else { + Float.NaN + } + val detailMergeFactor = if (samples > 0L) { + detailWeight.toFloat() / (samples * RADIANCE_FUSION_WEIGHT_QUANTIZATION) + } else { + Float.NaN + } + PLog.i( + TAG, + "Radiance merge frame=$frameIndex statsIndex=$statsIndex samples=$samples " + + "nrParticipation=${nrParticipation.percentString()} " + + "nrRejected=${(1f - nrParticipation).percentString()} " + + "nrMergeFactor=${nrMergeFactor.formatWeight()} " + + "srDetailParticipation=${detailParticipation.percentString()} " + + "srDetailFactor=${detailMergeFactor.formatWeight()}", + ) + if (statsIndex > 0) { + nonReferenceSamples += samples + nonReferenceNrAccepted += nrAccepted + nonReferenceNrWeight += nrWeight + nonReferenceDetailAccepted += detailAccepted + nonReferenceDetailWeight += detailWeight + } + } + + val acceptedNonReferenceFrames = (frameIndices.size - 1).coerceAtLeast(0) + val frameAdmission = if (candidateFrameCount > 0) { + acceptedNonReferenceFrames.toFloat() / candidateFrameCount + } else { + Float.NaN + } + val overallNrParticipation = ratioStat(nonReferenceNrAccepted, nonReferenceSamples) + val overallDetailParticipation = ratioStat( + nonReferenceDetailAccepted, + nonReferenceSamples, + ) + val averageMergeFactor = if (nonReferenceSamples > 0L) { + nonReferenceNrWeight.toFloat() / + (nonReferenceSamples * RADIANCE_FUSION_WEIGHT_QUANTIZATION) + } else { + Float.NaN + } + val averageDetailFactor = if (nonReferenceSamples > 0L) { + nonReferenceDetailWeight.toFloat() / + (nonReferenceSamples * RADIANCE_FUSION_WEIGHT_QUANTIZATION) + } else { + Float.NaN + } + PLog.i( + TAG, + "Radiance merge summary mergeFrameCount=${frameIndices.size} " + + "candidateNonReferenceFrames=$candidateFrameCount " + + "acceptedNonReferenceFrames=$acceptedNonReferenceFrames " + + "globalRejectedFrames=${(candidateFrameCount - acceptedNonReferenceFrames).coerceAtLeast(0)} " + + "frameAdmission=${frameAdmission.percentString()} " + + "nrParticipation=${overallNrParticipation.percentString()} " + + "nrRejected=${(1f - overallNrParticipation).percentString()} " + + "averageMergeFactor=${averageMergeFactor.formatWeight()} " + + "srDetailParticipation=${overallDetailParticipation.percentString()} " + + "averageSrDetailFactor=${averageDetailFactor.formatWeight()} " + + "sampleStep=${hwmfDebug.radianceFusionStatsSampleStep}", + ) + } + + private fun reconstructRadianceTiles( + referenceImage: SafeImage, + acceptedFrames: List, + candidateFrameCount: Int, + outputBuffer: ByteBuffer, + ): ReadOutputTiming { + check(radianceFusionEnabled) + check(radianceTiles.isNotEmpty()) + var requiredRcdWidth = 1 + var requiredRcdHeight = 1 + radianceTiles.forEach { tile -> + val referenceRegion = radianceSourceRegion(tile, RadianceFlowBounds.Zero) + requiredRcdWidth = max(requiredRcdWidth, referenceRegion.width) + requiredRcdHeight = max(requiredRcdHeight, referenceRegion.height) + acceptedFrames.forEach { frame -> + val frameRegion = radianceSourceRegion(tile, frame.flowBounds()) + requiredRcdWidth = max(requiredRcdWidth, frameRegion.width) + requiredRcdHeight = max(requiredRcdHeight, frameRegion.height) + } + } + ensureRadianceTileResources(requiredRcdWidth, requiredRcdHeight) + val readbackAllocStart = System.currentTimeMillis() + val scratchBytes = radianceOutputTileWidth.toLong() * radianceOutputTileHeight.toLong() * 8L + val readbackScratch = LargeDirectBuffer.allocate(scratchBytes, "Radiance RGBA16 tile readback") + ?.order(ByteOrder.nativeOrder()) + ?: throw IllegalStateException("Failed to allocate Radiance tile readback") + val readbackAllocMs = System.currentTimeMillis() - readbackAllocStart + val output = outputBuffer.apply { clear() }.order(ByteOrder.nativeOrder()).asShortBuffer() + val fusionStatsFrameIndices = IntArray(acceptedFrames.size + 1).also { indices -> + indices[0] = 0 + acceptedFrames.forEachIndexed { index, frame -> + indices[index + 1] = frame.frameIndex + } + } + val fusionStatsBuffer = if (logRadianceFusionParticipation) { + createRadianceFusionStatsBuffer(fusionStatsFrameIndices.size) + } else { + 0 + } + val rejectionFrameOrdinal = hwmfDebug.radianceFusionRejectionFrameOrdinal + val rejectionFrame = acceptedFrames.getOrNull(rejectionFrameOrdinal) + if (visualizeRadianceFusionRejections) { + PLog.i( + TAG, + "Radiance rejection overlay target acceptedOrdinal=$rejectionFrameOrdinal " + + "frame=${rejectionFrame?.frameIndex ?: "unavailable"}", + ) + } + var totalGlReadMs = 0L + var totalCopyMs = 0L + RawStackRuntimeDebug.i(TAG) { + "Radiance tiled reconstruction tiles=${radianceTiles.size} " + + "backend=${if (radianceUsesVgnSemanticBackend) "vgn-semantic" else "rcd-fallback"} " + + "coreRaw=${radianceFusionTuning.tileCoreSizeRawPx} " + + "maxOutput=${radianceOutputTileWidth}x$radianceOutputTileHeight " + + "maxSource=${requiredRcdWidth}x$requiredRcdHeight " + + "rejectionOverlay=$visualizeRadianceFusionRejections " + + "srDetailOverlay=$visualizeRadianceSrDetail " + + "candidates=$candidateFrameCount accepted=${acceptedFrames.size}" + } + try { + radianceTiles.forEach { tile -> + RawStackRuntimeDebug.d(TAG) { + "Radiance tile ${tile.index + 1}/${radianceTiles.size} " + + "rawCore=${tile.rawCore} outputCore=${tile.outputCore} " + + "working=${tile.outputWorking}" + } + clearSuperResolutionAccumulator() + val referenceRegion = radianceSourceRegion(tile, RadianceFlowBounds.Zero) + reconstructRadianceReferenceTile( + image = referenceImage, + sourceRegion = referenceRegion, + label = "Radiance reference tile ${tile.index}", + ) + accumulateRadianceFusionFrame( + isReference = true, + sourceRegion = referenceRegion, + accumulatorRegion = tile.outputWorking, + frameFlowTexture = flowTexture, + frameRobustnessTexture = robustnessTexture, + frameTileMaskTexture = tileMaskTexture, + registrationWeight = 1f, + detailWeight = 1f, + fusionStatsBuffer = fusionStatsBuffer, + fusionStatsIndex = 0, + fusionStatsCoreRegion = tile.outputCore, + recordFusionRejections = false, + ) + captureRadianceReferenceBase(tile.outputWorking.width, tile.outputWorking.height) + + acceptedFrames.forEachIndexed { statsFrameIndex, frame -> + val sourceRegion = radianceSourceRegion(tile, frame.flowBounds()) + reconstructRadianceNonReferenceTile( + image = frame.image, + sourceRegion = sourceRegion, + label = "Radiance frame ${frame.frameIndex} tile ${tile.index}", + ) + accumulateRadianceFusionFrame( + isReference = false, + sourceRegion = sourceRegion, + accumulatorRegion = tile.outputWorking, + frameFlowTexture = frame.flowTexture, + frameRobustnessTexture = frame.robustnessTexture, + frameTileMaskTexture = frame.tileMaskTexture, + registrationWeight = frame.registrationWeight, + detailWeight = frame.detailWeight, + fusionStatsBuffer = fusionStatsBuffer, + fusionStatsIndex = statsFrameIndex + 1, + fusionStatsCoreRegion = tile.outputCore, + recordFusionRejections = statsFrameIndex == rejectionFrameOrdinal, + ) + } + + normalizeRadianceTile( + tile, + globalAlignmentRejectCount = 0, + acceptedFusionFrameCount = if (rejectionFrame != null) 1 else 0, + ) + val timing = readRadianceOutputTile(readbackScratch, output, tile.outputCore) + totalGlReadMs += timing.glReadMs + totalCopyMs += timing.copyMs + GlesGpuScheduler.yieldToUiRenderer() + } + if (logRadianceFusionParticipation) { + logRadianceFusionStats( + buffer = fusionStatsBuffer, + frameIndices = fusionStatsFrameIndices, + candidateFrameCount = candidateFrameCount, + ) + } + } finally { + LargeDirectBuffer.free(readbackScratch) + } + outputBuffer.rewind() + return ReadOutputTiming( + elapsedMs = readbackAllocMs + totalGlReadMs + totalCopyMs, + glReadMs = totalGlReadMs, + copyMs = totalCopyMs, + allocMs = readbackAllocMs, + mode = if (radianceUsesVgnSemanticBackend) { + "radiance-vgn-semantic-rgb16-tiled" + } else { + "radiance-rcd-fallback-rgb16-tiled" + }, + ) + } + + private fun AcceptedSuperResolutionFrame.flowBounds(): RadianceFlowBounds { + return RadianceFlowBounds( + minXPlanePx = minFlowXPlanePx, + maxXPlanePx = maxFlowXPlanePx, + minYPlanePx = minFlowYPlanePx, + maxYPlanePx = maxFlowYPlanePx, + ) + } + + private fun radianceSourceRegion( + tile: RadianceTile, + flowBounds: RadianceFlowBounds, + ): RadianceTileRect { + return RadianceTilePlanner.sourceRegion( + tile = tile, + rawWidth = width, + rawHeight = height, + outputWidth = outputWidth, + outputHeight = outputHeight, + flowBounds = flowBounds, + cfaPeriod = rawCfaPeriod, + reconstructionHaloRawPx = if (radianceUsesVgnSemanticBackend) { + RadianceVgnGeometry.WORK_HALO_PX + } else { + RcdShaders.REGION_HALO_PX + }, + radianceSampleRadiusRawPx = RADIANCE_RECONSTRUCTION_RADIUS_RAW_PX, + ) + } + + private fun reconstructRadianceReferenceTile( + image: SafeImage, + sourceRegion: RadianceTileRect, + label: String, + ) { + uploadRcdRawRegion(image, sourceRegion, label) + if (radianceUsesVgnSemanticBackend) { + runRadianceReferenceVgn(sourceRegion, label) + } else { + runRcdRegion(sourceRegion, label) + storeRcdRgbRegion( + targetTexture = radianceRgbTileTexture, + regionWidth = sourceRegion.width, + regionHeight = sourceRegion.height, + label = "$label RGB store", + ) + } + } + + private fun reconstructRadianceNonReferenceTile( + image: SafeImage, + sourceRegion: RadianceTileRect, + label: String, + ) { + uploadRcdRawRegion(image, sourceRegion, label) + if (radianceUsesVgnSemanticBackend) { + runRadianceSemanticProxy(sourceRegion, label) + } else { + runRcdRegion(sourceRegion, label) + storeRcdRgbRegion( + targetTexture = radianceRgbTileTexture, + regionWidth = sourceRegion.width, + regionHeight = sourceRegion.height, + label = "$label RGB store", + ) + } + } + + private fun radianceVgnUbo(capacity: Int, writer: ByteBuffer.() -> Unit): ByteBuffer { + return ByteBuffer.allocateDirect(capacity).order(ByteOrder.nativeOrder()).apply { + writer() + limit(position()) + position(0) + } + } + + private fun radianceVgnBoundsUbo( + left: Int, + top: Int, + right: Int, + bottom: Int, + ): ByteBuffer = radianceVgnUbo(16) { + putInt(left) + putInt(top) + putInt(right) + putInt(bottom) + } + + private fun radianceVgnThresholdBoundsUbo( + left: Int, + top: Int, + right: Int, + bottom: Int, + edgeThreshold: Int, + vngThreshold: Int, + ): ByteBuffer = radianceVgnUbo(32) { + putInt(left) + putInt(top) + putInt(right) + putInt(bottom) + putInt(edgeThreshold) + putInt(vngThreshold) + putInt(0) + putInt(0) + } + + private fun dispatchRadianceVgnPass( + program: Int, + groupCountX: Int, + groupCountY: Int, + label: String, + uboBinding: Int? = null, + ubo: ByteBuffer? = null, + vararg images: RadianceVgnImageBinding, + ) { + check(program != 0) { "Radiance VGN program unavailable: $label" } + GLES31.glUseProgram(program) + images.forEach { image -> + GLES31.glBindImageTexture( + image.unit, + image.texture, + 0, + false, + 0, + image.access, + image.format, + ) + } + if (uboBinding != null && ubo != null) { + check(radianceVgnUbo != 0) { "Radiance VGN UBO is unavailable" } + GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, radianceVgnUbo) + GLES31.glBufferData( + GLES31.GL_UNIFORM_BUFFER, + ubo.remaining(), + ubo, + GLES31.GL_DYNAMIC_DRAW, + ) + GLES31.glBindBufferBase(GLES31.GL_UNIFORM_BUFFER, uboBinding, radianceVgnUbo) + GLES31.glBindBuffer(GLES31.GL_UNIFORM_BUFFER, 0) + } + GLES31.glDispatchCompute(groupCountX.coerceAtLeast(1), groupCountY.coerceAtLeast(1), 1) + // Every following VGN stage consumes an image written by the preceding stage. A GPU + // memory barrier is sufficient; unlike the single-frame path, tiled Radiance must not + // insert a CPU-visible fence after each pass. + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) + checkGlError("Radiance VGN $label") + } + + private fun runRadianceReferenceVgn(sourceRegion: RadianceTileRect, label: String) { + val geometry = RadianceVgnGeometry.forRegion( + sourceRegion.width, + sourceRegion.height, + cfaPattern, + ) + val capacity = checkNotNull(radianceVgnCapacityGeometry) + require( + geometry.packedWidth <= capacity.packedWidth && + geometry.workWidth <= capacity.workWidth && + geometry.workHeight <= capacity.workHeight, + ) { "Radiance VGN work surface exceeds allocated capacity" } + val groupsPackedX = groupCount(geometry.packedWidth) + val groupsWorkX = groupCount(geometry.workWidth) + val groupsWorkY = groupCount(geometry.workHeight) + val groupsHalfHeight = groupCount(geometry.halfHeight) + val standardDeviation = kotlin.math.sqrt( + (0.5f * (normalizedNoiseBetaByChannel[1] + normalizedNoiseBetaByChannel[2])) + .coerceAtLeast(1e-10f), + ).times(65535f).coerceIn(1f, 100f) + val edgeThreshold = 50 + val vngThreshold = 400 + + val prepare = radianceVgnPrograms[VgnShaders.PROGRAM_PREPARE] + GLES31.glUseProgram(prepare) + bindTexture(prepare, "uRawRegion", 0, rcdRawRegionTexture) + bindTexture(prepare, "uLensShadingMap", 1, lensShadingTexture) + GLES31.glUniform2i( + uniformLocation(prepare, "uRegionSize"), + sourceRegion.width, + sourceRegion.height, + ) + GLES31.glUniform2i(uniformLocation(prepare, "uFullImageSize"), width, height) + GLES31.glUniform2i( + uniformLocation(prepare, "uGlobalOrigin"), + sourceRegion.left, + sourceRegion.top, + ) + GLES31.glUniform2i( + uniformLocation(prepare, "uPackedSize"), + geometry.packedWidth, + geometry.workHeight, + ) + GLES31.glUniform2i( + uniformLocation(prepare, "uSourceOffset"), + geometry.roiLeft, + geometry.roiTop, + ) + GLES31.glUniform1i(uniformLocation(prepare, "uCfaPattern"), cfaPattern) + GLES31.glUniform4fv(uniformLocation(prepare, "uBlackLevel"), 1, normalizedBlackLevel, 0) + GLES31.glUniform1f(uniformLocation(prepare, "uWhiteLevel"), normalizedWhiteLevel) + GLES31.glUniform4fv( + uniformLocation(prepare, "uCalculationGains"), + 1, + demosaicCalculationWbGains, + 0, + ) + GLES31.glUniform1i(uniformLocation(prepare, "uReconstructHighlights"), 1) + bindImage(0, radianceVgnPackedFloatTexture, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F) + GLES31.glDispatchCompute(groupsPackedX, groupsWorkY, 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) + checkGlError("$label VGN prepare") + + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_NEUTRAL], + groupsPackedX, + groupsWorkY, + "$label neutral", + 2, + radianceVgnUbo(48) { + putInt(0); putInt(0); putInt(geometry.packedWidth); putInt(geometry.workHeight) + putInt(4096); putInt(4096); putInt(4096); putInt(0) + putInt(12); putInt(0); putInt(0); putInt(0) + }, + RadianceVgnImageBinding( + 0, + radianceVgnPackedFloatTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ), + RadianceVgnImageBinding( + 1, + radianceVgnPackedBayerTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16UI, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_0A1], + groupsPackedX, + groupsWorkY, + "$label pass 0A1", + 2, + radianceVgnBoundsUbo(0, 1, geometry.packedWidth - 1, geometry.workHeight - 1), + RadianceVgnImageBinding( + 0, + radianceVgnPackedBayerTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnPackedSmoothTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16UI, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_0A2], + groupsWorkX, + groupsHalfHeight, + "$label pass 0A2", + 2, + radianceVgnUbo(32) { + putInt(0); putInt(1); putInt(geometry.packedWidth - 1) + putInt((geometry.workHeight - 2) / 2) + putFloat(standardDeviation); putFloat(0f); putFloat(0f); putFloat(0f) + }, + RadianceVgnImageBinding( + 0, + radianceVgnPackedBayerTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnScaleTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_0B], + groupsPackedX, + groupsHalfHeight, + "$label pass 0B", + 2, + radianceVgnBoundsUbo(1, 0, geometry.packedWidth - 1, geometry.workHeight - 4), + RadianceVgnImageBinding( + 0, + radianceVgnScaleTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ), + RadianceVgnImageBinding( + 1, + radianceVgnMedianTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_0C], + groupsPackedX, + groupsWorkY, + "$label pass 0C", + 2, + radianceVgnBoundsUbo(0, 1, geometry.packedWidth - 1, geometry.workHeight - 1), + RadianceVgnImageBinding( + 0, + radianceVgnPackedSmoothTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnEdgeTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16I, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_1], + groupsWorkX, + groupsWorkY, + "$label pass 1", + 5, + radianceVgnThresholdBoundsUbo( + 12, + 12, + geometry.workWidth - 12, + geometry.workHeight - 12, + edgeThreshold, + vngThreshold, + ), + RadianceVgnImageBinding( + 0, + radianceVgnPackedBayerTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnEdgeTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16I, + ), + RadianceVgnImageBinding( + 2, + radianceVgnScaleTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ), + RadianceVgnImageBinding( + 3, + radianceVgnMedianTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ), + RadianceVgnImageBinding( + 4, + radianceVgnFull0Texture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16UI, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_2], + groupsWorkX, + groupsWorkY, + "$label pass 2", + 2, + radianceVgnBoundsUbo( + 13, + 13, + geometry.workWidth - 13, + geometry.workHeight - 13, + ), + RadianceVgnImageBinding( + 0, + radianceVgnFull0Texture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnFull1Texture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16UI, + ), + ) + dispatchRadianceVgnPass( + radianceVgnPrograms[VgnShaders.PROGRAM_3], + groupsWorkX, + groupsWorkY, + "$label pass 3", + 4, + radianceVgnThresholdBoundsUbo( + 16, + 16, + geometry.workWidth - 16, + geometry.workHeight - 16, + edgeThreshold, + vngThreshold, + ), + RadianceVgnImageBinding( + 0, + radianceVgnFull1Texture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 1, + radianceVgnPackedBayerTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ), + RadianceVgnImageBinding( + 2, + radianceVgnEdgeTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16I, + ), + RadianceVgnImageBinding( + 3, + radianceVgnFull0Texture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16UI, + ), + ) + + GLES31.glUseProgram(radianceVgnFinalProgram) + GLES31.glUniform2i( + uniformLocation(radianceVgnFinalProgram, "uOutputSize"), + sourceRegion.width, + sourceRegion.height, + ) + GLES31.glUniform2i( + uniformLocation(radianceVgnFinalProgram, "uRoiOrigin"), + geometry.roiLeft, + geometry.roiTop, + ) + GLES31.glUniform3f( + uniformLocation(radianceVgnFinalProgram, "uCalculationGains"), + demosaicCalculationWbGains[0], + 1f, + demosaicCalculationWbGains[3], + ) + bindImage( + 0, + radianceVgnFull0Texture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16UI, + ) + bindImage( + 1, + radianceRgbTileTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1) + GLES31.glMemoryBarrier( + GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, + ) + checkGlError("$label VGN camera RGB") + } + + private fun runRadianceSemanticProxy(sourceRegion: RadianceTileRect, label: String) { + val seed = radianceSemanticSeedProgram + GLES31.glUseProgram(seed) + bindTexture(seed, "uRawRegion", 0, rcdRawRegionTexture) + bindTexture(seed, "uLensShadingMap", 1, lensShadingTexture) + GLES31.glUniform2i( + uniformLocation(seed, "uRegionSize"), + sourceRegion.width, + sourceRegion.height, + ) + GLES31.glUniform2i(uniformLocation(seed, "uFullImageSize"), width, height) + GLES31.glUniform2i( + uniformLocation(seed, "uGlobalOrigin"), + sourceRegion.left, + sourceRegion.top, + ) + GLES31.glUniform1i(uniformLocation(seed, "uCfaPattern"), cfaPattern) + GLES31.glUniform4fv(uniformLocation(seed, "uBlackLevel"), 1, normalizedBlackLevel, 0) + GLES31.glUniform1f(uniformLocation(seed, "uWhiteLevel"), normalizedWhiteLevel) + bindImage( + 0, + radianceSemanticSeedTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1) + GLES31.glMemoryBarrier(GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) + checkGlError("$label semantic seed") + + val resolve = radianceSemanticResolveProgram + GLES31.glUseProgram(resolve) + GLES31.glUniform2i( + uniformLocation(resolve, "uRegionSize"), + sourceRegion.width, + sourceRegion.height, + ) + GLES31.glUniform2i(uniformLocation(resolve, "uFullImageSize"), width, height) + GLES31.glUniform2i( + uniformLocation(resolve, "uGlobalOrigin"), + sourceRegion.left, + sourceRegion.top, + ) + GLES31.glUniform1i(uniformLocation(resolve, "uCfaPattern"), cfaPattern) + bindImage( + 0, + radianceSemanticSeedTexture, + GLES31.GL_READ_ONLY, + GLES30.GL_RGBA16F, + ) + bindImage( + 1, + radianceRgbTileTexture, + GLES31.GL_WRITE_ONLY, + GLES30.GL_RGBA16F, + ) + GLES31.glDispatchCompute(groupCount(sourceRegion.width), groupCount(sourceRegion.height), 1) + GLES31.glMemoryBarrier( + GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT, + ) + checkGlError("$label semantic resolve") + } + + private fun normalizeRadianceTile( + tile: RadianceTile, + globalAlignmentRejectCount: Int, + acceptedFusionFrameCount: Int, + ) { + 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) + if (visualizeRadianceFusionRejections) { + bindTexture( + normalizeSuperResolutionProgram, + "uFusionRejections", + 7, + radianceFusionRejectionTexture, + ) + } + setCommonUniforms(normalizeSuperResolutionProgram) + GLES31.glUniform2i( + uniformLocation(normalizeSuperResolutionProgram, "uAccumulatorOrigin"), + tile.outputWorking.left, + tile.outputWorking.top, + ) + GLES31.glUniform2i( + uniformLocation(normalizeSuperResolutionProgram, "uAccumulatorSize"), + tile.outputWorking.width, + tile.outputWorking.height, + ) + GLES31.glUniform2i( + uniformLocation(normalizeSuperResolutionProgram, "uOutputOrigin"), + tile.outputCore.left, + tile.outputCore.top, + ) + if (visualizeRadianceFusionRejections || visualizeRadianceSrDetail) { + if (visualizeRadianceFusionRejections) { + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uGlobalAlignmentRejectCount"), + globalAlignmentRejectCount.coerceAtLeast(0).toFloat(), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uAcceptedFusionFrameCount"), + acceptedFusionFrameCount.coerceAtLeast(0).toFloat(), + ) + } + GLES31.glUniform3fv( + uniformLocation(normalizeSuperResolutionProgram, "uDebugNeutralRgb"), + 1, + radianceDebugNeutralColor, + 0, + ) + } + setRadianceNormalizeUniforms() + setPostfilterUniforms(normalizeSuperResolutionProgram) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("normalizeRadianceTile ${tile.index}") + } + + private fun setRadianceNormalizeUniforms() { + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceStart"), + radianceFusionTuning.nrConfidenceStart.coerceAtLeast(0f), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceFull"), + radianceFusionTuning.nrConfidenceFull.coerceAtLeast(radianceFusionTuning.nrConfidenceStart), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceStart"), + radianceFusionTuning.detailConfidenceStart.coerceAtLeast(0f), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceFull"), + radianceFusionTuning.detailConfidenceFull.coerceAtLeast(radianceFusionTuning.detailConfidenceStart), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uReferenceDetailFloor"), + radianceFusionTuning.referenceDetailFloor.coerceIn(0f, 1f), + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uDetailChromaStrength"), + radianceFusionTuning.detailChromaStrength.coerceIn(0f, 1f), + ) + GLES31.glUniform3f( + uniformLocation(normalizeSuperResolutionProgram, "uCalculationGains"), + demosaicCalculationWbGains[0], + 1f, + demosaicCalculationWbGains[3], + ) + GLES31.glUniform1f( + uniformLocation(normalizeSuperResolutionProgram, "uBilateralNoiseScale"), + radianceFusionTuning.bilateralNoiseScale.coerceAtLeast(1f), + ) + } + + private fun readRadianceOutputTile( + scratch: ByteBuffer, + output: ShortBuffer, + outputCore: RadianceTileRect, + ): ReadOutputTiming { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readbackFbo) + return try { + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, + outputTexture, + 0, + ) + GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0) + checkFramebuffer("readRadianceOutputTile") + GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8) + scratch.clear() + val readStart = System.currentTimeMillis() + GLES30.glReadPixels( + 0, + 0, + outputCore.width, + outputCore.height, + GLES30.GL_RGBA_INTEGER, + GLES30.GL_UNSIGNED_SHORT, + scratch, + ) + val readMs = System.currentTimeMillis() - readStart + checkGlError("readRadianceOutputTile core=$outputCore") + + val copyStart = System.currentTimeMillis() + val rgba = scratch.order(ByteOrder.nativeOrder()).asShortBuffer() + for (localY in 0 until outputCore.height) { + for (localX in 0 until outputCore.width) { + val source = (localY * outputCore.width + localX) * 4 + val target = ( + (outputCore.top + localY) * outputWidth + outputCore.left + localX + ) * 3 + output.put(target, rgba.get(source)) + output.put(target + 1, rgba.get(source + 1)) + output.put(target + 2, rgba.get(source + 2)) + } + } + val copyMs = System.currentTimeMillis() - copyStart + ReadOutputTiming( + elapsedMs = readMs + copyMs, + glReadMs = readMs, + copyMs = copyMs, + allocMs = 0L, + mode = "radiance-rgb16-tile", + ) + } finally { + GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + } + } + private fun reconstructSuperResolutionStripes( referenceImage: SafeImage, acceptedFrames: List, - radianceOutputBuffer: ByteBuffer? = null, ): ReadOutputTiming? { + check(!radianceFusionEnabled) { + "Radiance reconstruction must use the two-dimensional tile path" + } var requiredRcdRows = 1 var planRow = 0 while (planRow < outputHeight) { @@ -3862,164 +5373,86 @@ class GlesRawStacker( } planRow += coreCount } - if (radianceFusionEnabled) { - ensureRadianceRcdStripeResources(requiredRcdRows) - } else { - ensureRcdStripeResources(requiredRcdRows) - } - val readbackAllocStart = System.currentTimeMillis() - val radianceReadbackScratch = if (radianceFusionEnabled) { - val stripeRows = minOf(outputHeight, SUPER_RESOLUTION_STRIPE_ROWS) - val stripeBytes = outputWidth.toLong() * stripeRows.toLong() * 8L - LargeDirectBuffer.allocate(stripeBytes, "Radiance RGBA16 stripe readback") - ?.order(ByteOrder.nativeOrder()) - ?: throw IllegalStateException("Failed to allocate Radiance stripe readback") - } else { - null - } - val readbackAllocMs = System.currentTimeMillis() - readbackAllocStart - val radianceOutputShorts = if (radianceFusionEnabled) { - requireNotNull(radianceOutputBuffer) { - "Radiance reconstruction requires a linear RGB output buffer" - }.apply { clear() }.order(ByteOrder.nativeOrder()).asShortBuffer() - } else { - null - } - var totalGlReadMs = 0L - var totalCopyMs = 0L - try { - var outputRowOffset = 0 - while (outputRowOffset < outputHeight) { - val outputRowCount = minOf( - SUPER_RESOLUTION_STRIPE_ROWS, - outputHeight - outputRowOffset, - ) - val accumulationRowOffset = max( - 0, - outputRowOffset - SUPER_RESOLUTION_SPATIAL_RADIUS, - ) - val accumulationEnd = minOf( - outputHeight, - outputRowOffset + outputRowCount + SUPER_RESOLUTION_SPATIAL_RADIUS, - ) - val accumulationRowCount = accumulationEnd - accumulationRowOffset - clearSuperResolutionAccumulator() - val referenceBand = RawSuperResolutionStripePlanner.sourceRowBand( - accumulationRowOffset, - accumulationRowCount, - superResolutionScale, - 0f, - 0f, - rawCfaPeriod, - height, + ensureRcdStripeResources(requiredRcdRows) + var outputRowOffset = 0 + while (outputRowOffset < outputHeight) { + val outputRowCount = minOf( + SUPER_RESOLUTION_STRIPE_ROWS, + outputHeight - outputRowOffset, + ) + val accumulationRowOffset = max( + 0, + outputRowOffset - SUPER_RESOLUTION_SPATIAL_RADIUS, + ) + val accumulationEnd = minOf( + outputHeight, + outputRowOffset + outputRowCount + SUPER_RESOLUTION_SPATIAL_RADIUS, + ) + val accumulationRowCount = accumulationEnd - accumulationRowOffset + clearSuperResolutionAccumulator() + val referenceBand = RawSuperResolutionStripePlanner.sourceRowBand( + accumulationRowOffset, + accumulationRowCount, + superResolutionScale, + 0f, + 0f, + rawCfaPeriod, + height, + ) + uploadRcdRawStripe( + referenceImage, + referenceBand.firstRow, + referenceBand.rowCount, + "reference", + ) + runRcdStripe(referenceBand.firstRow, referenceBand.rowCount, "reference") + accumulateSuperResolutionFrame( + isReference = true, + sourceRowOffset = referenceBand.firstRow, + sourceRowCount = referenceBand.rowCount, + outputRowOffset = accumulationRowOffset, + outputRowCount = accumulationRowCount, + ) + acceptedFrames.forEach { frame -> + val sourceBand = RawSuperResolutionStripePlanner.sourceRowBand( + outputRowOffset = accumulationRowOffset, + outputRowCount = accumulationRowCount, + outputScale = superResolutionScale, + minFlowYPlanePx = frame.minFlowYPlanePx, + maxFlowYPlanePx = frame.maxFlowYPlanePx, + cfaPeriod = rawCfaPeriod, + rawHeight = height, ) uploadRcdRawStripe( - referenceImage, - referenceBand.firstRow, - referenceBand.rowCount, - "reference", + image = frame.image, + firstRow = sourceBand.firstRow, + rowCount = sourceBand.rowCount, + label = "MFSR stripe frame ${frame.frameIndex}", ) - if (radianceFusionEnabled) { - runRcdStripe(referenceBand.firstRow, referenceBand.rowCount, "Radiance reference") - storeRcdRgbStripe( - radianceRgbStripeTexture, - referenceBand.rowCount, - "Radiance reference RGB store", - ) - } else { - runRcdStripe(referenceBand.firstRow, referenceBand.rowCount, "reference") - } + runRcdStripe(sourceBand.firstRow, sourceBand.rowCount, "frame ${frame.frameIndex}") accumulateSuperResolutionFrame( - isReference = true, - sourceRowOffset = referenceBand.firstRow, - sourceRowCount = referenceBand.rowCount, + isReference = false, + sourceRowOffset = sourceBand.firstRow, + sourceRowCount = sourceBand.rowCount, + exposureScale = frame.exposureScale, + frameFlowTexture = frame.flowTexture, + frameRobustnessTexture = frame.robustnessTexture, + frameTileMaskTexture = frame.tileMaskTexture, + registrationWeight = frame.registrationWeight, + detailWeight = frame.detailWeight, outputRowOffset = accumulationRowOffset, outputRowCount = accumulationRowCount, ) - if (radianceFusionEnabled) { - captureRadianceReferenceBase(accumulationRowCount) - } - acceptedFrames.forEach { frame -> - val sourceBand = RawSuperResolutionStripePlanner.sourceRowBand( - outputRowOffset = accumulationRowOffset, - outputRowCount = accumulationRowCount, - outputScale = superResolutionScale, - minFlowYPlanePx = frame.minFlowYPlanePx, - maxFlowYPlanePx = frame.maxFlowYPlanePx, - cfaPeriod = rawCfaPeriod, - rawHeight = height, - ) - uploadRcdRawStripe( - image = frame.image, - firstRow = sourceBand.firstRow, - rowCount = sourceBand.rowCount, - label = if (radianceFusionEnabled) { - "Radiance stripe frame ${frame.frameIndex}" - } else { - "MFSR stripe frame ${frame.frameIndex}" - }, - ) - if (radianceFusionEnabled) { - runRcdStripe( - sourceBand.firstRow, - sourceBand.rowCount, - "Radiance frame ${frame.frameIndex}", - ) - storeRcdRgbStripe( - radianceRgbStripeTexture, - sourceBand.rowCount, - "Radiance frame ${frame.frameIndex} RGB store", - ) - } else { - runRcdStripe(sourceBand.firstRow, sourceBand.rowCount, "frame ${frame.frameIndex}") - } - accumulateSuperResolutionFrame( - isReference = false, - sourceRowOffset = sourceBand.firstRow, - sourceRowCount = sourceBand.rowCount, - exposureScale = frame.exposureScale, - frameFlowTexture = frame.flowTexture, - frameRobustnessTexture = frame.robustnessTexture, - frameTileMaskTexture = frame.tileMaskTexture, - registrationWeight = frame.registrationWeight, - detailWeight = frame.detailWeight, - outputRowOffset = accumulationRowOffset, - outputRowCount = accumulationRowCount, - ) - } - normalizeSuperResolutionStripe( - outputRowOffset = outputRowOffset, - outputRowCount = outputRowCount, - accumulatorRowOffset = accumulationRowOffset, - ) - if (radianceFusionEnabled) { - val stripeTiming = readRadianceOutputStripe( - scratch = requireNotNull(radianceReadbackScratch), - output = requireNotNull(radianceOutputShorts), - outputRowOffset = outputRowOffset, - outputRowCount = outputRowCount, - ) - totalGlReadMs += stripeTiming.glReadMs - totalCopyMs += stripeTiming.copyMs - } - outputRowOffset += outputRowCount - GlesGpuScheduler.yieldToUiRenderer() } - } finally { - LargeDirectBuffer.free(radianceReadbackScratch) - } - radianceOutputBuffer?.rewind() - return if (radianceFusionEnabled) { - ReadOutputTiming( - elapsedMs = readbackAllocMs + totalGlReadMs + totalCopyMs, - glReadMs = totalGlReadMs, - copyMs = totalCopyMs, - allocMs = readbackAllocMs, - mode = "radiance-rgb16-striped", + normalizeSuperResolutionStripe( + outputRowOffset = outputRowOffset, + outputRowCount = outputRowCount, + accumulatorRowOffset = accumulationRowOffset, ) - } else { - null + outputRowOffset += outputRowCount + GlesGpuScheduler.yieldToUiRenderer() } + return null } private fun normalizeSuperResolutionStripe( @@ -4028,155 +5461,21 @@ class GlesRawStacker( accumulatorRowOffset: Int, ) { bindFramebufferOutput(outputTexture, "normalizeSuperResolutionStripe") - GLES30.glViewport( - 0, - if (radianceFusionEnabled) 0 else outputRowOffset, - outputWidth, - outputRowCount, - ) + GLES30.glViewport(0, outputRowOffset, outputWidth, outputRowCount) GLES30.glUseProgram(normalizeSuperResolutionProgram) - if (radianceFusionEnabled) { - bindTexture( - normalizeSuperResolutionProgram, - "uNrSumRg", - 0, - superResolutionAccumulatorTexture, - ) - bindTexture( - normalizeSuperResolutionProgram, - "uNrSumBw", - 1, - superResolutionAccumulatorBwTexture, - ) - bindTexture( - normalizeSuperResolutionProgram, - "uDetailSumRg", - 2, - superResolutionAccumulatorBTexture, - ) - bindTexture( - normalizeSuperResolutionProgram, - "uDetailSumBw", - 3, - radianceDetailBwTexture, - ) - bindTexture( - normalizeSuperResolutionProgram, - "uReferenceBase", - 4, - radianceReferenceBaseTexture, - ) - } else { - bindTexture(normalizeSuperResolutionProgram, "uSrAccumulator", 0, superResolutionAccumulatorTexture) - bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorBw", 1, superResolutionAccumulatorBwTexture) - bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorB", 2, superResolutionAccumulatorBTexture) - } + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulator", 0, superResolutionAccumulatorTexture) + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorBw", 1, superResolutionAccumulatorBwTexture) + bindTexture(normalizeSuperResolutionProgram, "uSrAccumulatorB", 2, superResolutionAccumulatorBTexture) setCommonUniforms(normalizeSuperResolutionProgram) GLES31.glUniform1i( GLES31.glGetUniformLocation(normalizeSuperResolutionProgram, "uAccumulatorRowOffset"), accumulatorRowOffset, ) - if (radianceFusionEnabled) { - GLES31.glUniform1i( - uniformLocation(normalizeSuperResolutionProgram, "uOutputRowOffset"), - outputRowOffset, - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceStart"), - radianceFusionTuning.nrConfidenceStart.coerceAtLeast(0f), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uNrConfidenceFull"), - radianceFusionTuning.nrConfidenceFull - .coerceAtLeast(radianceFusionTuning.nrConfidenceStart), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceStart"), - radianceFusionTuning.detailConfidenceStart.coerceAtLeast(0f), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uDetailConfidenceFull"), - radianceFusionTuning.detailConfidenceFull - .coerceAtLeast(radianceFusionTuning.detailConfidenceStart), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uReferenceDetailFloor"), - radianceFusionTuning.referenceDetailFloor.coerceIn(0f, 1f), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uDetailChromaStrength"), - radianceFusionTuning.detailChromaStrength.coerceIn(0f, 1f), - ) - GLES31.glUniform1f( - uniformLocation(normalizeSuperResolutionProgram, "uBilateralNoiseScale"), - radianceFusionTuning.bilateralNoiseScale.coerceAtLeast(1f), - ) - } setPostfilterUniforms(normalizeSuperResolutionProgram) GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) finishFramebufferPass("normalizeSuperResolutionStripe") } - private fun readRadianceOutputStripe( - scratch: ByteBuffer, - output: ShortBuffer, - outputRowOffset: Int, - outputRowCount: Int, - ): ReadOutputTiming { - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readbackFbo) - return try { - GLES30.glFramebufferTexture2D( - GLES30.GL_FRAMEBUFFER, - GLES30.GL_COLOR_ATTACHMENT0, - GLES30.GL_TEXTURE_2D, - outputTexture, - 0, - ) - GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0) - checkFramebuffer("readRadianceOutputStripe") - GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8) - scratch.clear() - val readStart = System.currentTimeMillis() - GLES30.glReadPixels( - 0, - 0, - outputWidth, - outputRowCount, - GLES30.GL_RGBA_INTEGER, - GLES30.GL_UNSIGNED_SHORT, - scratch, - ) - val readMs = System.currentTimeMillis() - readStart - checkGlError( - "readRadianceOutputStripe rows=$outputRowOffset.." + - "${outputRowOffset + outputRowCount}", - ) - - val copyStart = System.currentTimeMillis() - val rgba = scratch.order(ByteOrder.nativeOrder()).asShortBuffer() - val pixelCount = outputWidth * outputRowCount - val outputPixelOffset = outputRowOffset * outputWidth - for (index in 0 until pixelCount) { - val source = index * 4 - val target = (outputPixelOffset + index) * 3 - output.put(target, rgba.get(source)) - output.put(target + 1, rgba.get(source + 1)) - output.put(target + 2, rgba.get(source + 2)) - } - val copyMs = System.currentTimeMillis() - copyStart - ReadOutputTiming( - elapsedMs = readMs + copyMs, - glReadMs = readMs, - copyMs = copyMs, - allocMs = 0L, - mode = "radiance-rgb16-stripe", - ) - } finally { - GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - } - private fun recordAlignmentDiagnostics() { runDiagnosticStep("alignment") { GLES31.glUseProgram(diagnosticAlignmentProgram) @@ -5019,7 +6318,7 @@ class GlesRawStacker( ) } - private fun setBlendRobustnessUniforms(program: Int) { + private fun setNrRobustnessUniforms(program: Int) { GLES31.glUniform1f( GLES31.glGetUniformLocation(program, "uRobustNoiseFloorSpatialScale"), hwmfBlend.robustnessNoiseFloorSpatialScale @@ -5031,15 +6330,36 @@ class GlesRawStacker( GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustTauBase"), hwmfBlend.robustnessTauBase) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustTauEdge"), hwmfBlend.robustnessTauEdge) GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustResidualPower"), hwmfBlend.robustnessResidualPower) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustFlowPenaltyStartPx"), hwmfBlend.flowPenaltyStartPx) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustFlowPenaltyDecay"), hwmfBlend.flowPenaltyDecay) GLES31.glUniform1f( GLES31.glGetUniformLocation(program, "uRobustFlowRangePenaltyStartPx"), hwmfBlend.flowRangePenaltyStartPx ) GLES31.glUniform1f( - GLES31.glGetUniformLocation(program, "uRobustFlowRangePenaltyDecay"), - hwmfBlend.flowRangePenaltyDecay + GLES31.glGetUniformLocation(program, "uRobustFlowRangeRejectPx"), + hwmfBlend.flowRangeRejectPx + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchPeakConfidenceStart"), + hwmfBlend.patchPeakConfidenceStart, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uPatchPeakConfidenceFull"), + hwmfBlend.patchPeakConfidenceFull, + ) + GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixFlat"), hwmfBlend.robustMinMixFlat) + GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixEdge"), hwmfBlend.robustMinMixEdge) + GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustCenterMixFlat"), hwmfBlend.robustCenterMixFlat) + GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustCenterMixEdge"), hwmfBlend.robustCenterMixEdge) + } + + private fun setDetailConfidenceUniforms(program: Int) { + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uRobustFlowRangePenaltyStartPx"), + hwmfBlend.flowRangePenaltyStartPx, + ) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(program, "uRobustFlowRangeRejectPx"), + hwmfBlend.flowRangeRejectPx, ) GLES31.glUniform1f( GLES31.glGetUniformLocation(program, "uPatchScoreFullConfidence"), @@ -5057,14 +6377,6 @@ class GlesRawStacker( GLES31.glGetUniformLocation(program, "uPatchPeakConfidenceFull"), hwmfBlend.patchPeakConfidenceFull, ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(program, "uPatchConfidenceFloor"), - hwmfBlend.patchConfidenceFloor.coerceIn(0f, 1f), - ) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixFlat"), hwmfBlend.robustMinMixFlat) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustMinMixEdge"), hwmfBlend.robustMinMixEdge) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustCenterMixFlat"), hwmfBlend.robustCenterMixFlat) - GLES31.glUniform1f(GLES31.glGetUniformLocation(program, "uRobustCenterMixEdge"), hwmfBlend.robustCenterMixEdge) } private fun setTileMaskUniforms(program: Int) { @@ -5512,11 +6824,15 @@ class GlesRawStacker( private const val BASE_ACCUMULATOR_DISPATCH_ROWS = 256 private const val SUPER_RESOLUTION_STRIPE_ROWS = 256 private const val SUPER_RESOLUTION_SPATIAL_RADIUS = 2 + private const val RADIANCE_RECONSTRUCTION_RADIUS_RAW_PX = 1 private const val READBACK_STRIPE_ROWS = 128 private const val DIAGNOSTIC_BUFFER_BINDING = 9 private const val REGISTRATION_SAMPLE_BUFFER_BINDING = 10 private const val REGISTRATION_GLOBAL_SCORE_BUFFER_BINDING = 11 private const val FLOW_READBACK_BUFFER_BINDING = 12 + private const val RADIANCE_FUSION_STATS_BUFFER_BINDING = 0 + private const val RADIANCE_FUSION_STATS_STRIDE = 5 + private const val RADIANCE_FUSION_WEIGHT_QUANTIZATION = 63f private const val REGISTRATION_GLOBAL_SCORE_STRIDE = 4 private const val REGISTRATION_SAMPLE_FLOAT_STRIDE = 8 private const val DIAGNOSTIC_HIST_BINS = 64 @@ -5691,6 +7007,8 @@ class GlesRawStacker( uniform int uCfaPattern; uniform float uBlackLevel[4]; uniform float uWhiteLevel; + uniform float uNoiseAlphaByChannel[4]; + uniform float uNoiseBetaByChannel[4]; uniform float uExposureScale; float rawNormAt(ivec2 p) { @@ -5701,25 +7019,44 @@ class GlesRawStacker( return clamp((raw - uBlackLevel[b]) / range, 0.0, 1.0); } - float greenBlock(ivec2 planeCoord) { + float noiseVariance(float signal, int bayerIndex) { + return max( + uNoiseAlphaByChannel[bayerIndex] * clamp(signal, 0.0, 1.0) + + uNoiseBetaByChannel[bayerIndex], + 0.0 + ); + } + + vec2 rawSignalAndVariance(ivec2 p) { + int bayerIndex = bayerIndexAt(uCfaPattern, p); + float signal = rawNormAt(p); + return vec2(signal, noiseVariance(signal, bayerIndex)); + } + + vec2 greenBlockStats(ivec2 planeCoord) { ivec2 s = clamp(planeCoord * 2, ivec2(0), uProxySize * 2 - ivec2(2)); if (uCfaPattern >= 4) { - float p00 = rawNormAt(s); - float p10 = rawNormAt(s + ivec2(1, 0)); - float p01 = rawNormAt(s + ivec2(0, 1)); - float p11 = rawNormAt(s + ivec2(1, 1)); - return 0.25 * (p00 + p10 + p01 + p11); + vec2 sum = vec2(0.0); + for (int y = 0; y <= 1; ++y) { + for (int x = 0; x <= 1; ++x) { + sum += rawSignalAndVariance(s + ivec2(x, y)); + } + } + // A four-sample mean combines independent variances with squared weights. + return vec2(0.25 * sum.x, 0.0625 * sum.y); } - float g1; - float g2; + ivec2 g1Pos; + ivec2 g2Pos; if (uCfaPattern == 0 || uCfaPattern == 3) { - g1 = rawNormAt(s + ivec2(1, 0)); - g2 = rawNormAt(s + ivec2(0, 1)); + g1Pos = s + ivec2(1, 0); + g2Pos = s + ivec2(0, 1); } else { - g1 = rawNormAt(s); - g2 = rawNormAt(s + ivec2(1, 1)); + g1Pos = s; + g2Pos = s + ivec2(1, 1); } - return 0.5 * (g1 + g2); + vec2 g1 = rawSignalAndVariance(g1Pos); + vec2 g2 = rawSignalAndVariance(g2Pos); + return vec2(0.5 * (g1.x + g2.x), 0.25 * (g1.y + g2.y)); } float tileMaxRaw(ivec2 planeCoord) { @@ -5736,20 +7073,51 @@ class GlesRawStacker( void main() { ivec2 p = ivec2(gl_GlobalInvocationID.xy); if (p.x >= uProxySize.x || p.y >= uProxySize.y) return; - float centerRaw = greenBlock(p); + vec2 centerStats = greenBlockStats(p); + float centerRaw = centerStats.x; float center = clamp(centerRaw * uExposureScale, 0.0, 1.0); float sum = 0.0; + float varianceSum = 0.0; for (int y = -1; y <= 1; ++y) { for (int x = -1; x <= 1; ++x) { ivec2 q = clamp(p + ivec2(x, y), ivec2(0), uProxySize - ivec2(1)); - sum += clamp(greenBlock(q) * uExposureScale, 0.0, 1.0); + vec2 stats = greenBlockStats(q); + sum += clamp(stats.x * uExposureScale, 0.0, 1.0); + varianceSum += stats.y; } } float mean = sum / 9.0; - float shadowValid = smoothstep(0.004, 0.035, centerRaw); + const float sharpen = 0.35; + float centerCoefficient = 1.0 + sharpen * (8.0 / 9.0); + float neighborCoefficient = sharpen / 9.0; + float proxyVariance = uExposureScale * uExposureScale * ( + centerCoefficient * centerCoefficient * centerStats.y + + neighborCoefficient * neighborCoefficient * + max(varianceSum - centerStats.y, 0.0) + ); + float detailVariance = uExposureScale * uExposureScale * ( + (64.0 / 81.0) * centerStats.y + + (1.0 / 81.0) * max(varianceSum - centerStats.y, 0.0) + ); + // G is physical sample validity. A dark RAW sample is noisy, but it is still a + // valid NR observation. B is alignment observability and may fall to zero when + // the patch does not carry enough signal to estimate a new local displacement. + float detailSnr = abs(center - mean) / sqrt(max(detailVariance, 1e-10)); + float alignmentObservability = centerStats.y > 1e-9 ? + smoothstep(1.5, 4.0, detailSnr) : + smoothstep(0.004, 0.035, centerRaw); float clipValid = 1.0 - smoothstep(0.90, 0.995, tileMaxRaw(p)); - float validity = clamp(shadowValid * clipValid, 0.0, 1.0); - imageStore(uProxy, p, vec4(clamp(center + 0.35 * (center - mean), 0.0, 1.0), validity, 0.0, 1.0)); + float sampleValidity = clamp(clipValid, 0.0, 1.0); + imageStore( + uProxy, + p, + vec4( + clamp(center + sharpen * (center - mean), 0.0, 1.0), + sampleValidity, + alignmentObservability, + max(proxyVariance, 1e-10) + ) + ); } """.trimIndent() @@ -5817,10 +7185,14 @@ class GlesRawStacker( } signal *= 0.25; float normalized = clamp(signal * uExposureScale, 0.0, 1.0); - float shadowValid = smoothstep(0.004, 0.035, signal); + float alignmentObservability = smoothstep(0.004, 0.035, signal); float clipValid = 1.0 - smoothstep(0.90, 0.995, tileMax); - float validity = clamp(shadowValid * clipValid, 0.0, 1.0); - imageStore(uTrackingProxy, p, vec4(normalized, validity, 0.0, 1.0)); + float sampleValidity = clamp(clipValid, 0.0, 1.0); + imageStore( + uTrackingProxy, + p, + vec4(normalized, sampleValidity, alignmentObservability, 1.0) + ); } """.trimIndent() @@ -5834,14 +7206,14 @@ class GlesRawStacker( void main() { ivec2 p = ivec2(gl_FragCoord.xy); ivec2 src = p * 2; - vec2 sum = vec2(0.0); + vec3 sum = vec3(0.0); for (int y = 0; y < 2; ++y) { for (int x = 0; x < 2; ++x) { ivec2 q = clamp(src + ivec2(x, y), ivec2(0), uInputSize - ivec2(1)); - sum += texelFetch(uInput, q, 0).rg; + sum += texelFetch(uInput, q, 0).rgb; } } - fragColor = vec4(sum * 0.25, 0.0, 1.0); + fragColor = vec4(sum * 0.25, 1.0); } """.trimIndent() @@ -5870,9 +7242,9 @@ class GlesRawStacker( uniform int uGraphRefineSearchRadius; out vec4 fragColor; - vec2 readProxy(sampler2D tex, ivec2 p) { + vec3 readProxy(sampler2D tex, ivec2 p) { p = clamp(p, ivec2(0), uLevelSize - ivec2(1)); - return texelFetch(tex, p, 0).rg; + return texelFetch(tex, p, 0).rgb; } vec4 graphSeedAt(vec2 planePos) { @@ -5924,9 +7296,11 @@ class GlesRawStacker( for (int sy = 1; sy < levelTile - 1; sy += uSampleStep) { for (int sx = 1; sx < levelTile - 1; sx += uSampleStep) { ivec2 rp = levelStart + ivec2(sx, sy); - vec2 rv = readProxy(uReference, rp); - vec2 cv = readProxy(uCurrent, rp + initialShift + ivec2(dx, dy)); - float w = min(rv.g, cv.g); + vec3 rv = readProxy(uReference, rp); + vec3 cv = readProxy(uCurrent, rp + initialShift + ivec2(dx, dy)); + float sampleValidity = min(rv.g, cv.g); + float observability = min(rv.b, cv.b); + float w = sampleValidity * observability; sad += abs(rv.r - cv.r) * w; count += w; sampleCount += 1.0; @@ -6005,14 +7379,14 @@ class GlesRawStacker( shared float validityParts[LOCAL_COUNT]; shared float sampleParts[LOCAL_COUNT]; - vec2 readProxy(sampler2D tex, ivec2 p) { + vec3 readProxy(sampler2D tex, ivec2 p) { p = clamp(p, ivec2(0), uLevelSize - ivec2(1)); - return texelFetch(tex, p, 0).rg; + return texelFetch(tex, p, 0).rgb; } - vec2 sampleProxy(sampler2D tex, vec2 p) { + vec3 sampleProxy(sampler2D tex, vec2 p) { vec2 uv = (clamp(p, vec2(0.0), vec2(uLevelSize - ivec2(1))) + vec2(0.5)) / vec2(uLevelSize); - return texture(tex, uv).rg; + return texture(tex, uv).rgb; } bool insideLevel(vec2 p) { @@ -6062,10 +7436,12 @@ class GlesRawStacker( continue; } - vec2 rv = readProxy(uReference, rp); - vec2 cv = sampleProxy(uCurrent, cp); - float valid = min(rv.g, cv.g); - float detail = clamp(detailAt(rp) * 18.0, 0.08, 1.0); + vec3 rv = readProxy(uReference, rp); + vec3 cv = sampleProxy(uCurrent, cp); + float sampleValidity = min(rv.g, cv.g); + float observability = min(rv.b, cv.b); + float valid = sampleValidity * observability; + float detail = clamp(detailAt(rp) * 18.0, 0.0, 1.0); float w = valid * detail; sad += abs(rv.r - cv.r) * w; weight += w; @@ -6120,9 +7496,9 @@ class GlesRawStacker( uniform ivec2 uGridSize; uniform int uTileSize; - vec2 sampleProxy(sampler2D tex, vec2 p) { + vec3 sampleProxy(sampler2D tex, vec2 p) { vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); - return texture(tex, uv).rg; + return texture(tex, uv).rgb; } void main() { @@ -6146,23 +7522,27 @@ class GlesRawStacker( basePoint.y > float(uPlaneSize.y - 2)) { continue; } - vec2 tSample = sampleProxy(uReference, basePoint); - vec2 iSample = sampleProxy(uCurrent, basePoint + flow); - vec2 txPos = sampleProxy(uReference, basePoint + vec2(1.0, 0.0)); - vec2 txNeg = sampleProxy(uReference, basePoint - vec2(1.0, 0.0)); - vec2 tyPos = sampleProxy(uReference, basePoint + vec2(0.0, 1.0)); - vec2 tyNeg = sampleProxy(uReference, basePoint - vec2(0.0, 1.0)); + vec3 tSample = sampleProxy(uReference, basePoint); + vec3 iSample = sampleProxy(uCurrent, basePoint + flow); + vec3 txPos = sampleProxy(uReference, basePoint + vec2(1.0, 0.0)); + vec3 txNeg = sampleProxy(uReference, basePoint - vec2(1.0, 0.0)); + vec3 tyPos = sampleProxy(uReference, basePoint + vec2(0.0, 1.0)); + vec3 tyNeg = sampleProxy(uReference, basePoint - vec2(0.0, 1.0)); float t = tSample.r; float i = iSample.r; float tx = 0.5 * (txPos.r - txNeg.r); float ty = 0.5 * (tyPos.r - tyNeg.r); - float validity = min( + float sampleValidity = min( min(tSample.g, iSample.g), min(min(txPos.g, txNeg.g), min(tyPos.g, tyNeg.g)) ); - float detailGate = clamp(max(abs(tx), abs(ty)) * 18.0, 0.08, 1.0); + float observability = min( + min(tSample.b, iSample.b), + min(min(txPos.b, txNeg.b), min(tyPos.b, tyNeg.b)) + ); + float detailGate = clamp(max(abs(tx), abs(ty)) * 18.0, 0.0, 1.0); float spatialW = exp(-0.5 * float(ox * ox + oy * oy) / sigma2); - float w = spatialW * detailGate * validity; + float w = spatialW * detailGate * sampleValidity * observability; float it = i - t; sIxIx += w * tx * tx; sIyIy += w * ty * ty; @@ -6248,6 +7628,20 @@ class GlesRawStacker( } """.trimIndent() + private val COPY_RGBA_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + precision highp int; + uniform sampler2D uInput; + uniform ivec2 uImageSize; + out vec4 fragColor; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uImageSize - ivec2(1)); + fragColor = texelFetch(uInput, p, 0); + } + """.trimIndent() + private val STRUCTURE_COMPUTE_SHADER = """ #version 310 es precision highp float; @@ -6338,22 +7732,15 @@ class GlesRawStacker( uniform ivec2 uPlaneSize; uniform ivec2 uGridSize; uniform int uTileSize; - uniform float uNoiseAlpha; - uniform float uNoiseBeta; uniform float uRobustNoiseFloorSpatialScale; uniform float uRobustNoiseFloorEdgeScale; uniform float uRobustTauBase; uniform float uRobustTauEdge; uniform float uRobustResidualPower; - uniform float uRobustFlowPenaltyStartPx; - uniform float uRobustFlowPenaltyDecay; uniform float uRobustFlowRangePenaltyStartPx; - uniform float uRobustFlowRangePenaltyDecay; - uniform float uPatchScoreFullConfidence; - uniform float uPatchScoreReject; + uniform float uRobustFlowRangeRejectPx; uniform float uPatchPeakConfidenceStart; uniform float uPatchPeakConfidenceFull; - uniform float uPatchConfidenceFloor; uniform float uRobustMinMixFlat; uniform float uRobustMinMixEdge; uniform float uRobustCenterMixFlat; @@ -6369,6 +7756,11 @@ class GlesRawStacker( return texelFetch(uReference, p, 0).g; } + float refNoiseVariance(ivec2 p) { + p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); + return max(texelFetch(uReference, p, 0).a, 1e-10); + } + float curProxy(vec2 p) { vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); return texture(uCurrent, uv).r; @@ -6379,16 +7771,21 @@ class GlesRawStacker( return texture(uCurrent, uv).g; } + float curNoiseVariance(vec2 p) { + vec2 uv = (clamp(p, vec2(0.0), vec2(uPlaneSize - ivec2(1))) + vec2(0.5)) / vec2(uPlaneSize); + return max(texture(uCurrent, uv).a, 1e-10); + } + vec2 flowAt(vec2 planePos) { vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; } - vec2 patchEvidenceAt(vec2 planePos) { + float patchPeakEvidenceAt(vec2 planePos) { vec2 grid = planePos / float(uTileSize) - vec2(0.5); vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); - return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).ba; + return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).a; } $LOCAL_FLOW_WARP_GLSL @@ -6405,7 +7802,6 @@ class GlesRawStacker( return; } - float greenCenter = refProxy(p); float sumG = 0.0; float sumG2 = 0.0; for (int y = -1; y <= 1; ++y) { @@ -6417,8 +7813,7 @@ class GlesRawStacker( } float meanG = sumG / 9.0; float sigma2Spatial = max(sumG2 / 9.0 - meanG * meanG, 0.0); - float sigma2Noise = max(uNoiseAlpha * greenCenter + uNoiseBeta, 1e-10); - float sigma2 = max(sigma2Spatial, sigma2Noise); + float sigma2 = max(sigma2Spatial, refNoiseVariance(p)); float gradX = 0.5 * (refProxy(p + ivec2(1, 0)) - refProxy(p - ivec2(1, 0))); float gradY = 0.5 * (refProxy(p + ivec2(0, 1)) - refProxy(p - ivec2(0, 1))); float edgeStrength = sqrt(max((gradX * gradX + gradY * gradY) / max(sigma2, 1e-8), 0.0)); @@ -6436,26 +7831,22 @@ class GlesRawStacker( fMax = max(fMax, f); } } - float flowMag = length(flow); - float flowPenalty = flowMag > uRobustFlowPenaltyStartPx ? - exp(-uRobustFlowPenaltyDecay * (flowMag - uRobustFlowPenaltyStartPx)) : 1.0; float flowRange = length(fMax - fMin); - float consistencyPenalty = flowRange > uRobustFlowRangePenaltyStartPx ? - exp(-uRobustFlowRangePenaltyDecay * (flowRange - uRobustFlowRangePenaltyStartPx)) : 1.0; - vec2 patchEvidence = patchEvidenceAt(vec2(p)); - float patchScoreConfidence = 1.0 - smoothstep( - uPatchScoreFullConfidence, - uPatchScoreReject, - patchEvidence.x + float rawConsistencyPenalty = 1.0 - smoothstep( + min(uRobustFlowRangePenaltyStartPx, uRobustFlowRangeRejectPx), + max(uRobustFlowRangePenaltyStartPx, uRobustFlowRangeRejectPx), + flowRange ); float patchPeakConfidence = smoothstep( uPatchPeakConfidenceStart, uPatchPeakConfidenceFull, - patchEvidence.y + patchPeakEvidenceAt(vec2(p)) ); - float patchConfidence = patchScoreConfidence * patchPeakConfidence; - float globalPenalty = flowPenalty * consistencyPenalty * - mix(uPatchConfidenceFloor, 1.0, patchConfidence); + // A flow discontinuity is meaningful motion evidence only where alignment is + // observable. Noise-normalized edges cover moving boundaries; patch peak covers + // textured interiors. Flat dark regions keep the inherited flow without penalty. + float motionEvidence = max(edgeRelax, patchPeakConfidence); + float consistencyPenalty = mix(1.0, rawConsistencyPenalty, motionEvidence); float minR = 1.0; float sumR = 0.0; @@ -6469,16 +7860,24 @@ class GlesRawStacker( float validity = min(refValidity(rp), curValidity(vec2(rp) + flow)); float diff = r - c; float d2 = diff * diff; + float differenceNoiseVariance = max( + refNoiseVariance(rp) + curNoiseVariance(vec2(rp) + flow), + 1e-10 + ); + float localSpatialVariance = max(sigma2Spatial, refNoiseVariance(rp)); float noiseFloor = mix( - uRobustNoiseFloorSpatialScale * sigma2, - uRobustNoiseFloorEdgeScale * sigma2Noise, + uRobustNoiseFloorSpatialScale * localSpatialVariance, + uRobustNoiseFloorEdgeScale * differenceNoiseVariance, edgeRelax ); - float den = mix(sigma2, sigma2Noise, edgeRelax); + float den = mix(localSpatialVariance, differenceNoiseVariance, edgeRelax); float residual = max(0.0, d2 - noiseFloor) / max(den, 1e-10); float tau = uRobustTauBase + uRobustTauEdge * edgeRelax; + // NR certainty describes whether this warped sample is physically usable + // and photometrically consistent. Patch sharpness and absolute motion are + // alignment observability/detail evidence, not NR rejection reasons. float robust = exp(-0.5 * pow(residual / tau, uRobustResidualPower)) * - globalPenalty * validity; + consistencyPenalty * validity; float w = (x == 0 && y == 0) ? 2.0 : 1.0; sumR += robust * w; weightSum += w; @@ -6494,72 +7893,290 @@ class GlesRawStacker( } """.trimIndent() - private val TILE_MASK_FRAGMENT_SHADER = """ - #version 300 es - precision highp float; - uniform sampler2D uReference; - uniform sampler2D uRobustness; - uniform ivec2 uPlaneSize; - uniform ivec2 uGridSize; - uniform int uTileSize; - uniform float uTileRobustCenter; - uniform float uTileRobustWidth; - uniform float uTileWeakThreshold; - uniform float uTileWeakStart; - uniform float uTileWeakRange; - uniform float uTileDetailMid; - uniform float uTileDetailHigh; - uniform float uTileDetailBoostLow; - uniform float uTileDetailBoostMid; - uniform float uTileDetailBoostHigh; - uniform float uTileMaskMinMidDetail; - uniform float uTileMaskMinHighDetail; - out float fragColor; - - float readRef(ivec2 p) { - p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); - return texelFetch(uReference, p, 0).r; + private fun tileMaskFragmentShader( + dualConfidence: Boolean, + trackRejectionReasons: Boolean, + ): String { + val flowUniforms = if (dualConfidence) { + """ + uniform sampler2D uFlowGrid; + uniform float uRobustFlowRangePenaltyStartPx; + uniform float uRobustFlowRangeRejectPx; + uniform float uPatchScoreFullConfidence; + uniform float uPatchScoreReject; + uniform float uPatchPeakConfidenceStart; + uniform float uPatchPeakConfidenceFull; + """.trimIndent() + } else { + "" } + val reasonUniforms = if (trackRejectionReasons) { + "uniform sampler2D uCurrent;" + } else { + "" + } + val outputDeclaration = if (dualConfidence) { + "out vec4 fragColor;" + } else { + "out float fragColor;" + } + val flowHelpers = if (dualConfidence) { + """ + vec4 flowEvidenceAt(vec2 planePos) { + vec2 grid = planePos / float(uTileSize) - vec2(0.5); + vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); + return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))); + } + """.trimIndent() + } else { + "" + } + val reasonHelpers = if (trackRejectionReasons) { + """ + const float MATERIAL_REJECTION_THRESHOLD = 0.5; - void main() { - ivec2 tile = ivec2(gl_FragCoord.xy); - ivec2 start = tile * uTileSize; - float robustSum = 0.0; - float weakCount = 0.0; - float detailSum = 0.0; - float count = 0.0; - for (int y = 0; y < uTileSize; y += 4) { - for (int x = 0; x < uTileSize; x += 4) { - ivec2 p = start + ivec2(x, y); - if (p.x >= uPlaneSize.x || p.y >= uPlaneSize.y) continue; - float r = texelFetch(uRobustness, p, 0).r; - float c = readRef(p); - float detail = abs(readRef(p + ivec2(1, 0)) - readRef(p - ivec2(1, 0))) + - abs(readRef(p + ivec2(0, 1)) - readRef(p - ivec2(0, 1))) + - 0.5 * abs(4.0 * c - readRef(p + ivec2(1, 0)) - readRef(p - ivec2(1, 0)) - - readRef(p + ivec2(0, 1)) - readRef(p - ivec2(0, 1))); - robustSum += r; - weakCount += r < uTileWeakThreshold ? 1.0 : 0.0; - detailSum += detail; - count += 1.0; + float currentValidityAt(vec2 planePos) { + if (planePos.x < 0.0 || planePos.y < 0.0 || + planePos.x > float(uPlaneSize.x - 1) || + planePos.y > float(uPlaneSize.y - 1)) { + return 0.0; + } + vec2 uv = (planePos + vec2(0.5)) / vec2(uPlaneSize); + return texture(uCurrent, uv).g; + } + + bool shouldReplaceRejectionCause(vec3 previous, vec3 candidate) { + if (candidate.x <= 0.0 || candidate.z <= 0.0) return false; + if (previous.x <= 0.0 || previous.z <= 0.0) return true; + bool previousMaterial = previous.z >= MATERIAL_REJECTION_THRESHOLD; + bool candidateMaterial = candidate.z >= MATERIAL_REJECTION_THRESHOLD; + if (candidateMaterial != previousMaterial) return candidateMaterial; + if (candidateMaterial && candidate.y != previous.y) { + return candidate.y > previous.y; + } + return candidate.z > previous.z; + } + + void considerRejectionCause( + inout vec3 selected, + float reasonId, + float priority, + float rejectionStrength + ) { + vec3 candidate = vec3( + reasonId, + priority, + clamp(rejectionStrength, 0.0, 1.0) + ); + if (shouldReplaceRejectionCause(selected, candidate)) { + selected = candidate; } } - float meanR = robustSum / max(count, 1.0); - float weak = weakCount / max(count, 1.0); - float detail = detailSum / max(count, 1.0); - float robustNorm = clamp((meanR - uTileRobustCenter) / uTileRobustWidth, 0.0, 1.0); - float weakPenalty = clamp(1.0 - max(0.0, weak - uTileWeakStart) / uTileWeakRange, 0.0, 1.0); - float detailBoost = detail > uTileDetailHigh ? - uTileDetailBoostHigh : (detail > uTileDetailMid ? uTileDetailBoostMid : uTileDetailBoostLow); - float mask = clamp((0.60 * robustNorm + 0.40 * weakPenalty) * (0.55 + 0.45 * detailBoost), 0.0, 1.0); - if (detail > uTileDetailHigh) { - mask = max(mask, uTileMaskMinHighDetail * robustNorm); - } else if (detail > uTileDetailMid) { - mask = max(mask, uTileMaskMinMidDetail * robustNorm); - } - fragColor = mask; + """.trimIndent() + } else { + "" } - """.trimIndent() + val flowSetup = if (dualConfidence) { + """ + vec2 tileCenter = vec2(start) + vec2(0.5 * float(uTileSize)); + vec4 centerFlowEvidence = flowEvidenceAt(tileCenter); + vec2 flowMin = centerFlowEvidence.rg; + vec2 flowMax = centerFlowEvidence.rg; + for (int gy = -1; gy <= 1; ++gy) { + for (int gx = -1; gx <= 1; ++gx) { + ivec2 neighborTile = clamp( + tile + ivec2(gx, gy), + ivec2(0), + uGridSize - ivec2(1) + ); + vec2 neighborFlow = texelFetch(uFlowGrid, neighborTile, 0).rg; + flowMin = min(flowMin, neighborFlow); + flowMax = max(flowMax, neighborFlow); + } + } + float flowRange = length(flowMax - flowMin); + float flowRangeConfidence = 1.0 - smoothstep( + min(uRobustFlowRangePenaltyStartPx, uRobustFlowRangeRejectPx), + max(uRobustFlowRangePenaltyStartPx, uRobustFlowRangeRejectPx), + flowRange + ); + float patchScoreConfidence = 1.0 - smoothstep( + uPatchScoreFullConfidence, + uPatchScoreReject, + centerFlowEvidence.b + ); + float patchPeakConfidence = smoothstep( + uPatchPeakConfidenceStart, + uPatchPeakConfidenceFull, + centerFlowEvidence.a + ); + float detailAlignmentConfidence = clamp( + flowRangeConfidence * patchScoreConfidence * patchPeakConfidence, + 0.0, + 1.0 + ); + """.trimIndent() + } else { + "" + } + val reasonSetup = if (trackRejectionReasons) { + """ + float validityConfidenceSum = 0.0; + """.trimIndent() + } else { + "" + } + val reasonSample = if (trackRejectionReasons) { + """ + vec2 sampleFlow = flowEvidenceAt(vec2(p)).rg; + float validityConfidence = min( + texelFetch(uReference, p, 0).g, + currentValidityAt(vec2(p) + sampleFlow) + ); + validityConfidenceSum += validityConfidence; + """.trimIndent() + } else { + "" + } + val output = when { + trackRejectionReasons -> { + """ + float validityConfidence = validityConfidenceSum / max(count, 1.0); + float textureMotionEvidence = smoothstep( + 0.5 * min(uTileDetailMid, uTileDetailHigh), + max(uTileDetailMid, uTileDetailHigh), + detail + ); + float motionEvidence = max(patchPeakConfidence, textureMotionEvidence); + float motionConfidence = mix(1.0, flowRangeConfidence, motionEvidence); + float explainedConfidence = motionConfidence * validityConfidence; + float photometricConfidence = explainedConfidence > 1e-5 ? + clamp(meanR / explainedConfidence, 0.0, 1.0) : 1.0; + float tileAggregationConfidence = meanR > 1e-4 ? + clamp(nrMask / meanR, 0.0, 1.0) : 1.0; + vec3 rejectionCause = vec3(0.0); + // Only causes that can suppress NR belong in the NR rejection overlay. + // Patch peak/texture only activate motion evidence; neither can reject NR by itself. + considerRejectionCause(rejectionCause, 1.0, 110.0, 1.0 - validityConfidence); + considerRejectionCause(rejectionCause, 5.0, 70.0, 1.0 - motionConfidence); + considerRejectionCause(rejectionCause, 6.0, 60.0, 1.0 - photometricConfidence); + considerRejectionCause(rejectionCause, 7.0, 50.0, 1.0 - tileAggregationConfidence); + fragColor = vec4( + nrMask, + detailMask, + rejectionCause.x, + rejectionCause.z + ); + """.trimIndent() + } + + dualConfidence -> "fragColor = vec4(nrMask, detailMask, 0.0, 0.0);" + else -> "fragColor = legacyMask;" + } + return """ + #version 300 es + precision highp float; + uniform sampler2D uReference; + uniform sampler2D uRobustness; + $flowUniforms + $reasonUniforms + uniform ivec2 uPlaneSize; + uniform ivec2 uGridSize; + uniform int uTileSize; + uniform float uTileRobustCenter; + uniform float uTileRobustWidth; + uniform float uTileWeakThreshold; + uniform float uTileWeakStart; + uniform float uTileWeakRange; + uniform float uTileDetailMid; + uniform float uTileDetailHigh; + uniform float uTileDetailBoostLow; + uniform float uTileDetailBoostMid; + uniform float uTileDetailBoostHigh; + uniform float uTileMaskMinMidDetail; + uniform float uTileMaskMinHighDetail; + $outputDeclaration + + float readRef(ivec2 p) { + p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); + return texelFetch(uReference, p, 0).r; + } + + float readRefNoiseVariance(ivec2 p) { + p = clamp(p, ivec2(0), uPlaneSize - ivec2(1)); + return max(texelFetch(uReference, p, 0).a, 0.0); + } + + float structureBeyondNoise(float magnitude, float variance) { + return max(magnitude - 2.0 * sqrt(max(variance, 0.0)), 0.0); + } + + $flowHelpers + $reasonHelpers + + void main() { + ivec2 tile = ivec2(gl_FragCoord.xy); + ivec2 start = tile * uTileSize; + float robustSum = 0.0; + float weakCount = 0.0; + float detailSum = 0.0; + float count = 0.0; + $flowSetup + $reasonSetup + for (int y = 0; y < uTileSize; y += 4) { + for (int x = 0; x < uTileSize; x += 4) { + ivec2 p = start + ivec2(x, y); + if (p.x >= uPlaneSize.x || p.y >= uPlaneSize.y) continue; + float r = texelFetch(uRobustness, p, 0).r; + float c = readRef(p); + ivec2 px = p + ivec2(1, 0); + ivec2 nx = p - ivec2(1, 0); + ivec2 py = p + ivec2(0, 1); + ivec2 ny = p - ivec2(0, 1); + float centerVariance = readRefNoiseVariance(p); + float pxVariance = readRefNoiseVariance(px); + float nxVariance = readRefNoiseVariance(nx); + float pyVariance = readRefNoiseVariance(py); + float nyVariance = readRefNoiseVariance(ny); + float detail = structureBeyondNoise( + abs(readRef(px) - readRef(nx)), + pxVariance + nxVariance + ) + structureBeyondNoise( + abs(readRef(py) - readRef(ny)), + pyVariance + nyVariance + ) + 0.5 * structureBeyondNoise( + abs(4.0 * c - readRef(px) - readRef(nx) - readRef(py) - readRef(ny)), + 16.0 * centerVariance + pxVariance + nxVariance + pyVariance + nyVariance + ); + robustSum += r; + weakCount += r < uTileWeakThreshold ? 1.0 : 0.0; + detailSum += detail; + count += 1.0; + $reasonSample + } + } + float meanR = robustSum / max(count, 1.0); + float weak = weakCount / max(count, 1.0); + float detail = detailSum / max(count, 1.0); + float robustNorm = clamp((meanR - uTileRobustCenter) / uTileRobustWidth, 0.0, 1.0); + float weakPenalty = clamp(1.0 - max(0.0, weak - uTileWeakStart) / uTileWeakRange, 0.0, 1.0); + float detailBoost = detail > uTileDetailHigh ? + uTileDetailBoostHigh : (detail > uTileDetailMid ? uTileDetailBoostMid : uTileDetailBoostLow); + float legacyMask = clamp((0.60 * robustNorm + 0.40 * weakPenalty) * + (0.55 + 0.45 * detailBoost), 0.0, 1.0); + if (detail > uTileDetailHigh) { + legacyMask = max(legacyMask, uTileMaskMinHighDetail * robustNorm); + } else if (detail > uTileDetailMid) { + legacyMask = max(legacyMask, uTileMaskMinMidDetail * robustNorm); + } + // NR is a spatial confidence filter over already noise-normalized per-pixel + // robustness. It deliberately has no texture or patch-peak requirement. + float nrMask = clamp(0.75 * meanR + 0.25 * weakPenalty, 0.0, 1.0); + ${if (dualConfidence) "float detailMask = legacyMask * detailAlignmentConfidence;" else ""} + $output + } + """.trimIndent() + } private val REGISTRATION_SAMPLE_COMPUTE_SHADER = """ #version 310 es @@ -6575,6 +8192,7 @@ class GlesRawStacker( uniform ivec2 uPlaneSize; uniform ivec2 uGridSize; uniform int uTileSize; + uniform int uUseDetailTileConfidence; layout(std430, binding = $REGISTRATION_SAMPLE_BUFFER_BINDING) buffer RegistrationSamples { float samples[]; }; @@ -6648,7 +8266,12 @@ class GlesRawStacker( return; } float robustness = clamp(mapAt(uRobustness, planePos), 0.0, 1.0); - float tileMask = clamp(texelFetch(uTileMask, tile, 0).r, 0.0, 1.0); + vec4 tileConfidence = texelFetch(uTileMask, tile, 0); + float tileMask = clamp( + uUseDetailTileConfidence != 0 ? tileConfidence.g : tileConfidence.r, + 0.0, + 1.0 + ); float residual = abs(refAt(planeCoord) - curAt(targetPlane)); float detail = detailAt(planeCoord); writeSample(tile, referenceRaw, targetRaw, robustness, tileMask, residual, detail); diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RadianceTilePlanner.kt b/app/src/main/java/com/hinnka/mycamera/processor/RadianceTilePlanner.kt new file mode 100644 index 00000000..61f20bb3 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/RadianceTilePlanner.kt @@ -0,0 +1,156 @@ +package com.hinnka.mycamera.processor + +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.roundToInt + +internal data class RadianceTileRect( + val left: Int, + val top: Int, + val right: Int, + val bottom: Int, +) { + init { + require(left >= 0 && top >= 0) + require(right > left && bottom > top) + } + + val width: Int get() = right - left + val height: Int get() = bottom - top +} + +internal data class RadianceFlowBounds( + val minXPlanePx: Float, + val maxXPlanePx: Float, + val minYPlanePx: Float, + val maxYPlanePx: Float, +) { + companion object { + val Zero = RadianceFlowBounds(0f, 0f, 0f, 0f) + } +} + +internal data class RadianceTile( + val index: Int, + val rawCore: RadianceTileRect, + val outputCore: RadianceTileRect, + val outputWorking: RadianceTileRect, +) + +/** + * Plans non-overlapping output cores plus dependency-complete working/source regions. + * + * Overlap is computational halo only: callers write [RadianceTile.outputCore] and discard the + * rest. Source regions include global flow displacement, the selected reconstruction backend's + * reliable-output halo, the Radiance sampling radius and an interpolation guard. Their origins + * preserve global CFA phase. + */ +internal object RadianceTilePlanner { + private const val INTERPOLATION_GUARD_RAW_PX = 2 + + fun plan( + rawWidth: Int, + rawHeight: Int, + outputWidth: Int, + outputHeight: Int, + coreSizeRawPx: Int, + outputSpatialRadiusPx: Int, + cfaPeriod: Int, + ): List { + require(rawWidth > 0 && rawHeight > 0) + require(outputWidth > 0 && outputHeight > 0) + val phase = cfaPeriod.coerceAtLeast(2) + val requestedCore = coreSizeRawPx.coerceAtLeast(phase) + val coreSize = (requestedCore / phase * phase).coerceAtLeast(phase) + val spatialRadius = outputSpatialRadiusPx.coerceAtLeast(0) + val result = ArrayList() + var rawTop = 0 + var index = 0 + while (rawTop < rawHeight) { + val rawBottom = minOf(rawHeight, rawTop + coreSize) + var rawLeft = 0 + while (rawLeft < rawWidth) { + val rawRight = minOf(rawWidth, rawLeft + coreSize) + val outputCore = RadianceTileRect( + left = mapBoundary(rawLeft, rawWidth, outputWidth), + top = mapBoundary(rawTop, rawHeight, outputHeight), + right = mapBoundary(rawRight, rawWidth, outputWidth), + bottom = mapBoundary(rawBottom, rawHeight, outputHeight), + ) + val workingLeft = maxOf(0, outputCore.left - spatialRadius) + val workingTop = maxOf(0, outputCore.top - spatialRadius) + val workingRight = minOf(outputWidth, outputCore.right + spatialRadius) + val workingBottom = minOf(outputHeight, outputCore.bottom + spatialRadius) + result += RadianceTile( + index = index++, + rawCore = RadianceTileRect(rawLeft, rawTop, rawRight, rawBottom), + outputCore = outputCore, + outputWorking = RadianceTileRect( + workingLeft, + workingTop, + workingRight, + workingBottom, + ), + ) + rawLeft = rawRight + } + rawTop = rawBottom + } + return result + } + + fun sourceRegion( + tile: RadianceTile, + rawWidth: Int, + rawHeight: Int, + outputWidth: Int, + outputHeight: Int, + flowBounds: RadianceFlowBounds, + cfaPeriod: Int, + reconstructionHaloRawPx: Int, + radianceSampleRadiusRawPx: Int, + ): RadianceTileRect { + require(rawWidth > 0 && rawHeight > 0) + require(outputWidth > 0 && outputHeight > 0) + val scaleX = outputWidth.toDouble() / rawWidth.toDouble() + val scaleY = outputHeight.toDouble() / rawHeight.toDouble() + val firstRawX = (tile.outputWorking.left + 0.5) / scaleX - 0.5 + val lastRawX = (tile.outputWorking.right - 0.5) / scaleX - 0.5 + val firstRawY = (tile.outputWorking.top + 0.5) / scaleY - 0.5 + val lastRawY = (tile.outputWorking.bottom - 0.5) / scaleY - 0.5 + val gatherMargin = reconstructionHaloRawPx.coerceAtLeast(0) + + radianceSampleRadiusRawPx.coerceAtLeast(0) + + INTERPOLATION_GUARD_RAW_PX + val minFlowXRaw = finiteOrZero(minOf(flowBounds.minXPlanePx, flowBounds.maxXPlanePx)) * 2f + val maxFlowXRaw = finiteOrZero(maxOf(flowBounds.minXPlanePx, flowBounds.maxXPlanePx)) * 2f + val minFlowYRaw = finiteOrZero(minOf(flowBounds.minYPlanePx, flowBounds.maxYPlanePx)) * 2f + val maxFlowYRaw = finiteOrZero(maxOf(flowBounds.minYPlanePx, flowBounds.maxYPlanePx)) * 2f + val phase = cfaPeriod.coerceAtLeast(2) + + var left = floor(firstRawX + minFlowXRaw - gatherMargin).toInt().coerceIn(0, rawWidth - 1) + var top = floor(firstRawY + minFlowYRaw - gatherMargin).toInt().coerceIn(0, rawHeight - 1) + left -= left % phase + top -= top % phase + val unalignedRight = ceil(lastRawX + maxFlowXRaw + gatherMargin + 1.0) + .toInt() + .coerceIn(left + 1, rawWidth) + val unalignedBottom = ceil(lastRawY + maxFlowYRaw + gatherMargin + 1.0) + .toInt() + .coerceIn(top + 1, rawHeight) + val right = minOf(rawWidth, alignUp(unalignedRight, phase)) + val bottom = minOf(rawHeight, alignUp(unalignedBottom, phase)) + return RadianceTileRect(left, top, right, bottom) + } + + private fun mapBoundary(value: Int, sourceSize: Int, targetSize: Int): Int { + return (value.toDouble() * targetSize.toDouble() / sourceSize.toDouble()) + .roundToInt() + .coerceIn(0, targetSize) + } + + private fun alignUp(value: Int, alignment: Int): Int { + return (value + alignment - 1) / alignment * alignment + } + + private fun finiteOrZero(value: Float): Float = value.takeIf { it.isFinite() } ?: 0f +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawNoiseModel.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawNoiseModel.kt index d3bfa683..b7adf672 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawNoiseModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawNoiseModel.kt @@ -4,6 +4,7 @@ class RawNoiseModel private constructor( shotNoise: FloatArray, readNoise: FloatArray, val hasValidCamera2Profile: Boolean, + private val cfaPhaseOrdered: Boolean, ) { val shotNoise: FloatArray = normalizeChannels(shotNoise) val readNoise: FloatArray = normalizeChannels(readNoise) @@ -13,27 +14,40 @@ class RawNoiseModel private constructor( val greenShotNoise: Float = 0.5f * (this.shotNoise[1] + this.shotNoise[2]) val greenReadNoise: Float = 0.5f * (this.readNoise[1] + this.readNoise[2]) - fun normalizedShotNoiseForShader(): FloatArray { - return FloatArray(CHANNEL_COUNT) { index -> - shotNoise[index].coerceAtLeast(0f) / SENSOR_NORMALIZATION_SCALE - } - } + /** + * Camera2/DNG noise-profile coefficients already describe variance in normalized sensor + * space: variance = S * signal + O. The shader also works in that space, so applying an + * additional 16-bit normalization here would underestimate noise by several orders of + * magnitude. + */ + fun normalizedShotNoiseForShader(cfaPattern: Int = 0): FloatArray = + canonicalChannels(shotNoise, cfaPattern) - fun normalizedReadNoiseForShader(): FloatArray { - return FloatArray(CHANNEL_COUNT) { index -> - readNoise[index].coerceAtLeast(0f) / SENSOR_VARIANCE_NORMALIZATION_SCALE + fun normalizedReadNoiseForShader(cfaPattern: Int = 0): FloatArray = + canonicalChannels(readNoise, cfaPattern) + + private fun canonicalChannels(values: FloatArray, cfaPattern: Int): FloatArray { + if (!cfaPhaseOrdered) return values.copyOf() + val phaseToCanonical = when (cfaPattern.mod(4)) { + 1 -> intArrayOf(1, 0, 3, 2) + 2 -> intArrayOf(2, 3, 0, 1) + 3 -> intArrayOf(3, 2, 1, 0) + else -> intArrayOf(0, 1, 2, 3) + } + return FloatArray(CHANNEL_COUNT).also { canonical -> + phaseToCanonical.forEachIndexed { phase, channel -> + canonical[channel] = values[phase] + } } } companion object { private const val CHANNEL_COUNT = 4 - private const val SENSOR_NORMALIZATION_SCALE = 65535.0f - private const val SENSOR_VARIANCE_NORMALIZATION_SCALE = SENSOR_NORMALIZATION_SCALE * SENSOR_NORMALIZATION_SCALE - val EMPTY = RawNoiseModel( shotNoise = FloatArray(CHANNEL_COUNT), readNoise = FloatArray(CHANNEL_COUNT), hasValidCamera2Profile = false, + cfaPhaseOrdered = false, ) fun fromLegacyNoiseModel(noiseModel: FloatArray): RawNoiseModel { @@ -44,6 +58,7 @@ class RawNoiseModel private constructor( shotNoise = FloatArray(CHANNEL_COUNT) { s }, readNoise = FloatArray(CHANNEL_COUNT) { o }, hasValidCamera2Profile = false, + cfaPhaseOrdered = false, ) } @@ -51,18 +66,44 @@ class RawNoiseModel private constructor( if (channelPairs.size < 2) return EMPTY if (channelPairs.size == 2) return fromLegacyNoiseModel(channelPairs) - val pairCount = (channelPairs.size / 2).coerceAtLeast(1) - val shotNoise = FloatArray(CHANNEL_COUNT) - val readNoise = FloatArray(CHANNEL_COUNT) - for (index in 0 until CHANNEL_COUNT) { - val source = index.coerceAtMost(pairCount - 1) - shotNoise[index] = sanitizeCoefficient(channelPairs[source * 2]) - readNoise[index] = sanitizeCoefficient(channelPairs[source * 2 + 1]) + val pairCount = channelPairs.size / 2 + fun coefficient(pair: Int, component: Int): Float = + sanitizeCoefficient(channelPairs.getOrElse(pair * 2 + component) { 0f }) + + // Camera2 supplies four CFA-position pairs. A DNG normally supplies canonical + // R/G/B pairs and native parsing may append an empty fourth pair. + val hasFourthPair = pairCount >= CHANNEL_COUNT && + (coefficient(3, 0) > 0f || coefficient(3, 1) > 0f) + val cfaPhaseOrdered = hasFourthPair + val shotNoise = if (hasFourthPair) { + FloatArray(CHANNEL_COUNT) { coefficient(it, 0) } + } else if (pairCount >= 3) { + floatArrayOf( + coefficient(0, 0), + coefficient(1, 0), + coefficient(1, 0), + coefficient(2, 0), + ) + } else { + FloatArray(CHANNEL_COUNT) { coefficient(it.coerceAtMost(pairCount - 1), 0) } + } + val readNoise = if (hasFourthPair) { + FloatArray(CHANNEL_COUNT) { coefficient(it, 1) } + } else if (pairCount >= 3) { + floatArrayOf( + coefficient(0, 1), + coefficient(1, 1), + coefficient(1, 1), + coefficient(2, 1), + ) + } else { + FloatArray(CHANNEL_COUNT) { coefficient(it.coerceAtMost(pairCount - 1), 1) } } return RawNoiseModel( shotNoise = shotNoise, readNoise = readNoise, hasValidCamera2Profile = shotNoise.any { it > 0f } || readNoise.any { it > 0f }, + cfaPhaseOrdered = cfaPhaseOrdered, ) } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt index 93769d08..dbb1e63f 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawStackDebugConfig.kt @@ -5,6 +5,11 @@ import com.hinnka.mycamera.BuildConfig data class RawStackDebugConfig( val collectMetrics: Boolean = false, val logCompactSummary: Boolean = false, + val visualizeRadianceFusionRejections: Boolean = false, + val radianceFusionRejectionFrameOrdinal: Int = 0, + val visualizeRadianceSrDetail: Boolean = false, + val logRadianceFusionParticipation: Boolean = false, + val radianceFusionStatsSampleStep: Int = 8, val sampleStep: Int = 16, val tileRejectThreshold: Float = 0.10f, val lensShadingEdgeFraction: Float = 0.125f, @@ -22,6 +27,8 @@ data class RawStackDebugConfig( if (!BuildConfig.DEBUG) return Disabled return copy( collectMetrics = needsMetrics, + radianceFusionRejectionFrameOrdinal = radianceFusionRejectionFrameOrdinal.coerceAtLeast(0), + radianceFusionStatsSampleStep = radianceFusionStatsSampleStep.coerceIn(4, 64), sampleStep = sampleStep.coerceAtLeast(1), tileRejectThreshold = tileRejectThreshold.coerceIn(0f, 1f), lensShadingEdgeFraction = lensShadingEdgeFraction.coerceIn(0.02f, 0.45f), @@ -44,7 +51,15 @@ data class RawStackDebugConfig( fun forCurrentBuild(): RawStackDebugConfig { // Diagnostic shaders and SSBO readback are opt-in. A normal debug photo must exercise // the same production pass graph instead of paying for metrics that do not affect output. - return Disabled + return RawStackDebugConfig( + visualizeRadianceFusionRejections = ENABLE_RADIANCE_FUSION_REJECTION_OVERLAY, + visualizeRadianceSrDetail = ENABLE_RADIANCE_SR_DETAIL_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_FUSION_PARTICIPATION_LOG = true } } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt index a0bd97d7..546c11ba 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawStackTuningProfile.kt @@ -53,15 +53,12 @@ data class RawStackBlendTuning( val robustnessTauBase: Float = 1.0f, val robustnessTauEdge: Float = 0.75f, val robustnessResidualPower: Float = 8.0f, - val flowPenaltyStartPx: Float = 15.0f, - val flowPenaltyDecay: Float = 0.1f, - val flowRangePenaltyStartPx: Float = 8.0f, - val flowRangePenaltyDecay: Float = 0.1f, + val flowRangePenaltyStartPx: Float = 1.5f, + val flowRangeRejectPx: Float = 4.0f, val patchScoreFullConfidence: Float = 0.035f, val patchScoreReject: Float = 0.18f, val patchPeakConfidenceStart: Float = 0.005f, val patchPeakConfidenceFull: Float = 0.08f, - val patchConfidenceFloor: Float = 0.05f, val robustMinMixFlat: Float = 0.35f, val robustMinMixEdge: Float = 0.15f, val robustCenterMixFlat: Float = 0.35f, diff --git a/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt b/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt index a0d3089c..63feefa2 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlanner.kt @@ -37,10 +37,11 @@ internal object RawSuperResolutionStripePlanner { val safeMaxFlow = maxFlowYPlanePx.takeIf { it.isFinite() } ?: 0f val minFlow = min(safeMinFlow, safeMaxFlow) * 2f val maxFlow = max(safeMinFlow, safeMaxFlow) * 2f - val gatherMargin = cfaPeriod.coerceAtLeast(2) + RcdShaders.STRIPE_HALO_ROWS + val gatherMargin = cfaPeriod.coerceAtLeast(2) + RcdShaders.REGION_HALO_PX + val phase = cfaPeriod.coerceAtLeast(2) var first = floor(firstReferenceRaw + minFlow - gatherMargin).toInt().coerceIn(0, rawHeight - 1) - // RCD shaders evaluate CFA parity in stripe-local coordinates. Preserve the global phase. - if ((first and 1) != 0) first = (first - 1).coerceAtLeast(0) + // RCD shaders evaluate CFA phase in region-local coordinates. Preserve the global phase. + first -= first % phase val endExclusive = ceil(lastReferenceRaw + maxFlow + gatherMargin + 1f) .toInt() .coerceIn(first + 1, rawHeight) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RcdShaders.kt b/app/src/main/java/com/hinnka/mycamera/raw/RcdShaders.kt index 9b8845bc..b007eaf5 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RcdShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RcdShaders.kt @@ -15,8 +15,8 @@ object RcdShaders { /** PPG 最深的递归邻域半径,用于验证条带是否包含完整输入。 */ const val PPG_RADIUS = 4 - /** 条带调用方在输出采样范围之外至少保留的 RCD 输入行数。 */ - const val STRIPE_HALO_ROWS = OUTPUT_MARGIN + 1 + /** 区域调用方在输出采样范围之外至少保留的 RCD 输入像素数。 */ + const val REGION_HALO_PX = OUTPUT_MARGIN + 1 const val HIGHLIGHT_RECONSTRUCTION_THRESHOLD = 0.985f const val HIGHLIGHT_RECONSTRUCTION_CEILING = 8.0f @@ -933,12 +933,12 @@ object RcdShaders { """.trimIndent() /** - * HDR/MFSR 条带 RCD 的统一照片边界收尾。 + * HDR/MFSR 条带与 Radiance 二维分片共用的照片边界收尾。 * - * 仅覆盖照片的真实外圈,不把条带边界当作照片边界。位于内部条带 halo 外缘、邻域尚未 - * 上传完整的行会跳过;它们不属于该条带的有效采样域,并会在相邻条带拥有完整邻域时处理。 + * 仅覆盖照片的真实外圈,不把工作区域边界当作照片边界。位于内部 halo 外缘、邻域尚未 + * 上传完整的像素会跳过;它们不属于该区域的有效采样域,并会在相邻区域拥有完整邻域时处理。 */ - val STRIPE_BORDER_PPG = """ + val REGION_BORDER_PPG = """ #version 310 es precision highp float; precision highp int; @@ -949,9 +949,9 @@ object RcdShaders { layout(std430, binding = 2) buffer RGB1_Buf { float rgb1[]; }; layout(std430, binding = 3) buffer RGB2_Buf { float rgb2[]; }; - uniform ivec2 uStripeSize; + uniform ivec2 uRegionSize; uniform ivec2 uFullImageSize; - uniform int uGlobalRowOffset; + uniform ivec2 uGlobalOrigin; uniform int uCfaPattern; #define RED 0 @@ -994,8 +994,8 @@ object RcdShaders { int indexAt(ivec2 coord) { ivec2 safe = mirrorCoord(coord); - int localY = safe.y - uGlobalRowOffset; - return localY * uStripeSize.x + safe.x; + ivec2 local = safe - uGlobalOrigin; + return local.y * uRegionSize.x + local.x; } int colorAt(ivec2 coord) { @@ -1011,8 +1011,8 @@ object RcdShaders { void main() { ivec2 local = ivec2(gl_GlobalInvocationID.xy); - if (local.x >= uStripeSize.x || local.y >= uStripeSize.y) return; - ivec2 global = ivec2(local.x, local.y + uGlobalRowOffset); + if (local.x >= uRegionSize.x || local.y >= uRegionSize.y) return; + ivec2 global = local + uGlobalOrigin; bool horizontalBorder = global.x < RCD_OUTPUT_MARGIN || global.x >= uFullImageSize.x - RCD_OUTPUT_MARGIN; @@ -1020,34 +1020,40 @@ object RcdShaders { global.y >= uFullImageSize.y - RCD_OUTPUT_MARGIN; if (!horizontalBorder && !verticalBorder) return; + int minRequiredX = uFullImageSize.x - 1; + int maxRequiredX = 0; int minRequiredY = uFullImageSize.y - 1; int maxRequiredY = 0; - for (int dy = -PPG_RADIUS; dy <= PPG_RADIUS; ++dy) { - int sampleY = mirrorIndex(global.y + dy, uFullImageSize.y); + for (int delta = -PPG_RADIUS; delta <= PPG_RADIUS; ++delta) { + int sampleX = mirrorIndex(global.x + delta, uFullImageSize.x); + int sampleY = mirrorIndex(global.y + delta, uFullImageSize.y); + minRequiredX = min(minRequiredX, sampleX); + maxRequiredX = max(maxRequiredX, sampleX); minRequiredY = min(minRequiredY, sampleY); maxRequiredY = max(maxRequiredY, sampleY); } - int stripeEnd = uGlobalRowOffset + uStripeSize.y; - if (minRequiredY < uGlobalRowOffset || maxRequiredY >= stripeEnd) return; + ivec2 regionEnd = uGlobalOrigin + uRegionSize; + if (minRequiredX < uGlobalOrigin.x || maxRequiredX >= regionEnd.x || + minRequiredY < uGlobalOrigin.y || maxRequiredY >= regionEnd.y) return; vec3 color = ppgColorAt(global); - int index = local.y * uStripeSize.x + local.x; + int index = local.y * uRegionSize.x + local.x; rgb0[index] = color.r; rgb1[index] = color.g; rgb2[index] = color.b; } """.trimIndent() - /** 原始 RAW 条带到 RCD CFA/RGB 工作缓冲的统一适配 shader。 */ - fun stripePopulate(rawCommon: String): String = """ + /** 原始 RAW 条带/分片到 RCD CFA/RGB 工作缓冲的统一适配 shader。 */ + fun regionPopulate(rawCommon: String): String = """ #version 310 es $rawCommon layout(local_size_x = 16, local_size_y = 16) in; - uniform highp usampler2D uRawStripe; + uniform highp usampler2D uRawRegion; uniform sampler2D uLensShadingMap; - uniform ivec2 uStripeSize; + uniform ivec2 uRegionSize; uniform ivec2 uFullImageSize; - uniform int uGlobalRowOffset; + uniform ivec2 uGlobalOrigin; uniform int uCfaPattern; uniform vec4 uBlackLevel; uniform float uWhiteLevel; @@ -1062,19 +1068,19 @@ object RcdShaders { const float HIGHLIGHT_CEILING = $HIGHLIGHT_RECONSTRUCTION_CEILING; ivec2 clampLocal(ivec2 p) { - return clamp(p, ivec2(0), uStripeSize - ivec2(1)); + return clamp(p, ivec2(0), uRegionSize - ivec2(1)); } ivec2 globalAt(ivec2 local) { local = clampLocal(local); - return ivec2(local.x, local.y + uGlobalRowOffset); + return local + uGlobalOrigin; } float sensorNormalizedAt(ivec2 local) { local = clampLocal(local); ivec2 global = globalAt(local); int channel = bayerIndexAt(uCfaPattern, global); - float raw = float(texelFetch(uRawStripe, local, 0).r); + float raw = float(texelFetch(uRawRegion, local, 0).r); float range = max(uWhiteLevel - uBlackLevel[channel], 1.0); return max(raw - uBlackLevel[channel], 0.0) / range; } @@ -1119,8 +1125,8 @@ object RcdShaders { void main() { ivec2 local = ivec2(gl_GlobalInvocationID.xy); - if (local.x >= uStripeSize.x || local.y >= uStripeSize.y) return; - ivec2 global = ivec2(local.x, local.y + uGlobalRowOffset); + if (local.x >= uRegionSize.x || local.y >= uRegionSize.y) return; + ivec2 global = local + uGlobalOrigin; int channel = bayerIndexAt(uCfaPattern, global); float sensor = sensorNormalizedAt(local); float value = calculationSampleAt(local); @@ -1129,7 +1135,7 @@ object RcdShaders { float reconstructed = estimateOpposedLinear(local, colorAt(local), value); value = min(mix(value, reconstructed, clipMask), HIGHLIGHT_CEILING); } - int index = local.y * uStripeSize.x + local.x; + int index = local.y * uRegionSize.x + local.x; cfa[index] = value; rgb0[index] = channel == 0 ? value : 0.0; rgb1[index] = (channel == 1 || channel == 2) ? value : 0.0; diff --git a/app/src/test/java/com/hinnka/mycamera/camera/MultiFrameConfigTest.kt b/app/src/test/java/com/hinnka/mycamera/camera/MultiFrameConfigTest.kt new file mode 100644 index 00000000..7dd5e8e7 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/camera/MultiFrameConfigTest.kt @@ -0,0 +1,18 @@ +package com.hinnka.mycamera.camera + +import org.junit.Assert.assertEquals +import org.junit.Test + +class MultiFrameConfigTest { + @Test + fun cameraStateStartsWithValidMultiFrameCount() { + assertEquals(MultiFrameConfig.DEFAULT_FRAME_COUNT, CameraState().multiFrameCount) + } + + @Test + fun normalizeFrameCountNeverAllowsEmptyBurst() { + assertEquals(MultiFrameConfig.MIN_FRAME_COUNT, MultiFrameConfig.normalizeFrameCount(0)) + assertEquals(MultiFrameConfig.DEFAULT_FRAME_COUNT, MultiFrameConfig.normalizeFrameCount(6)) + assertEquals(MultiFrameConfig.MAX_FRAME_COUNT, MultiFrameConfig.normalizeFrameCount(100)) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/GlesRadianceReconstructionTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/GlesRadianceReconstructionTest.kt new file mode 100644 index 00000000..b6bf21c0 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/GlesRadianceReconstructionTest.kt @@ -0,0 +1,88 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class GlesRadianceReconstructionTest { + @Test + fun everyStandardBayerPatternMapsItsRedSiteToCanonicalVgnRedPhase() { + val redPhases = arrayOf( + intArrayOf(0, 0), + intArrayOf(1, 0), + intArrayOf(0, 1), + intArrayOf(1, 1), + ) + + redPhases.forEachIndexed { pattern, redPhase -> + val geometry = RadianceVgnGeometry.forRegion(1068, 1064, pattern) + + assertEquals(0, (geometry.roiLeft + redPhase[0]) and 1) + assertEquals(0, (geometry.roiTop + redPhase[1]) and 1) + assertTrue(geometry.roiLeft >= RadianceVgnGeometry.WORK_HALO_PX) + assertTrue(geometry.roiTop >= RadianceVgnGeometry.WORK_HALO_PX) + assertEquals(0, geometry.workWidth % 4) + assertEquals(0, geometry.workHeight % 2) + assertEquals(geometry.workHeight / 2, geometry.halfHeight) + } + } + + @Test + fun semanticProxyUsesGlobalCfaAndSameColorOpponentLattices() { + val seed = GlesRadianceReconstructionShaders.semanticSeed + val resolve = GlesRadianceReconstructionShaders.semanticResolve + + assertTrue(seed.contains("ivec2 global = local + uGlobalOrigin")) + assertTrue(seed.contains("int mirrorIndex(int value, int size)")) + assertTrue(seed.contains("float redGreen = channel == 0 ? native - green : 0.0")) + assertTrue(seed.contains("float blueGreen = channel == 3 ? native - green : 0.0")) + assertTrue(resolve.contains("ivec2 channelPhase(int channel)")) + assertTrue(resolve.contains("resolveOpponent(global, 0, 1, green)")) + assertTrue(resolve.contains("resolveOpponent(global, 3, 2, green)")) + assertTrue(resolve.contains("global.x - ((global.x - phase.x) & 1)")) + assertFalse(resolve.contains("bayerIndexAt(uCfaPattern, local)")) + } + + @Test + fun semanticDenseGreenCannotCreateAnExtremumOutsideNativeGreenNeighbors() { + val seed = GlesRadianceReconstructionShaders.semanticSeed + + assertTrue(seed.contains("float horizontalLimit = 0.5 * abs(gL - gR)")) + assertTrue(seed.contains("float verticalLimit = 0.5 * abs(gU - gD)")) + assertTrue(seed.contains("float horizontalCorrection")) + assertTrue(seed.contains("-horizontalLimit")) + assertTrue(seed.contains("float verticalCorrection")) + assertTrue(seed.contains("-verticalLimit")) + assertTrue(seed.contains("float nativeGreenMin")) + assertTrue(seed.contains("float nativeGreenMax")) + assertTrue(seed.contains("return clamp(green")) + assertFalse(seed.contains("return max(mix(vertical, horizontal, blendH), 0.0)")) + } + + @Test + fun opponentChromaInterpolationUsesDenseGreenAsAnEdgeGuide() { + val resolve = GlesRadianceReconstructionShaders.semanticResolve + + assertTrue(resolve.contains("float opponentGuideWeight")) + assertTrue(resolve.contains("vec4 s00 = semanticAt(p00)")) + assertTrue(resolve.contains("float g00 = s00.r")) + assertTrue(resolve.contains("float edgeStrength = smoothstep")) + assertTrue(resolve.contains("vec4 spatialWeight")) + assertTrue(resolve.contains("vec4 guideWeight")) + assertTrue(resolve.contains("vec4 weight = spatialWeight * guideWeight")) + assertFalse(resolve.contains("return mix(a, b, ty)")) + } + + @Test + fun vgnReferenceReturnsToCameraRgbWithoutColorNoiseOrIirStages() { + val prepare = GlesRadianceReconstructionShaders.vgnPrepareRegion + val finish = GlesRadianceReconstructionShaders.vgnYccdToCameraRgb + + assertTrue(prepare.contains("uGlobalOrigin")) + assertTrue(prepare.contains("uSourceOffset")) + assertTrue(finish.contains("calculationRgb / max(uCalculationGains")) + assertFalse(prepare.contains("COLOR_NOISE")) + assertFalse(finish.contains("IIR")) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/GlesRawRadianceFusionShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/GlesRawRadianceFusionShadersTest.kt new file mode 100644 index 00000000..c0be1dab --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/GlesRawRadianceFusionShadersTest.kt @@ -0,0 +1,188 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class GlesRawRadianceFusionShadersTest { + @Test + fun debugNeutralIsInverseWbNormalizedToSensorCeiling() { + val neutral = radianceDebugNeutralRgb(floatArrayOf(2f, 1f, 1f, 4f)) + + assertArrayEquals(floatArrayOf(0.5f, 1f, 0.25f), neutral, 1e-6f) + assertArrayEquals( + floatArrayOf(1f, 1f, 1f), + floatArrayOf(neutral[0] * 2f, neutral[1], neutral[2] * 4f), + 1e-6f, + ) + } + + @Test + fun rejectionDiagnosticsPreserveSpecificCauseByInvestigationPriority() { + val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = true) + + assertTrue(shader.contains("vec4 tileConfidence = vec4(1.0, 1.0, 0.0, 0.0)")) + assertTrue(shader.contains("fusionRejectionPriority(tileConfidence.b)")) + assertTrue(shader.contains("return vec4(confidence, texelFetch(uTileMask, reasonTile, 0).ba)")) + assertTrue(shader.contains("const float MATERIAL_REJECTION_THRESHOLD = 0.5")) + assertTrue(shader.contains("considerFusionRejection")) + assertTrue(shader.contains("8.0,")) + assertTrue(shader.contains("10.0,")) + assertTrue(shader.contains("11.0,")) + assertTrue(shader.contains("12.0,")) + assertTrue(shader.contains("uniform highp sampler2D uPreviousFusionRejections;")) + assertTrue(shader.contains("writeonly uniform highp image2D uNextFusionRejections;")) + assertTrue(shader.contains("uniform int uRecordFusionRejections;")) + assertTrue(shader.contains("if (uRecordFusionRejections == 0)")) + assertTrue(shader.contains("texelFetch(")) + assertTrue(shader.contains("storeFusionRejection(accumulatorP, vec3(9.0, 120.0, 1.0));")) + assertTrue(shader.contains("fusionRejection.z >= MATERIAL_REJECTION_THRESHOLD")) + assertFalse(shader.contains("imageLoad(uFusionRejections")) + } + + @Test + fun nrAndDetailUseIndependentConfidenceChains() { + val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false) + + assertTrue(shader.contains("tileConfidence.r * robust")) + assertTrue(shader.contains("tileConfidence.g * robust")) + assertTrue(shader.contains("float nrCoverage")) + assertTrue(shader.contains("float detailCoverage")) + assertFalse(shader.contains("float robustFloor")) + assertFalse(shader.contains("float relaxedCoverage")) + assertFalse(shader.contains("uDenoiseNonReferenceWeightFloor")) + assertFalse(shader.contains("uRobustnessFloorFactor")) + } + + @Test + fun participationLogCountsFinalNrAndDetailWeightsInsideOutputCore() { + val shader = GlesRawRadianceFusionShaders.accumulate( + rawCommon = "", + trackParticipation = true, + ) + + assertTrue(shader.contains("buffer RadianceFusionParticipationStats")) + assertTrue(shader.contains("uniform ivec2 uFusionStatsCoreOrigin")) + assertTrue(shader.contains("shouldSampleFusionParticipation")) + assertTrue(shader.contains("recordFusionParticipation(outputP, nrWeight, detailWeight)")) + assertTrue(shader.contains("recordFusionParticipation(outputP, vec3(0.0), vec3(0.0))")) + assertTrue(shader.contains("float meanNrWeight = dot(nrWeight, vec3(0.3333333))")) + assertTrue(shader.contains("atomicAdd(uFusionParticipationStats[offset + 1], 1u)")) + assertTrue(shader.contains("atomicAdd(uFusionParticipationStats[offset + 3], 1u)")) + } + + @Test + fun chromaConsistencyUsesIndependentOpponentChannelNoise() { + val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false) + + assertTrue(shader.contains("vec2 referenceChroma = referenceRgb.rb - referenceRgb.gg")) + assertTrue(shader.contains("differenceVariance.r + differenceVariance.g")) + assertTrue(shader.contains("differenceVariance.b + differenceVariance.g")) + assertTrue(shader.contains("normalizedSquaredResidual")) + assertTrue(shader.contains("channelConsistency = vec3(chromaConfidence.x, 1.0, chromaConfidence.y)")) + assertTrue(shader.contains("float sharedConsistency = min(chromaConfidence.x, chromaConfidence.y)")) + assertFalse(shader.contains("float sensorPrecision")) + } + + @Test + fun nonReferenceSemanticPlanesDecodeOnlyAfterCfaIndependentReconstruction() { + val shader = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false) + + assertTrue(shader.contains("uniform int uSemanticEncoding")) + assertTrue(shader.contains("uIsReference != 0 || uSemanticEncoding == 0")) + assertTrue( + shader.contains( + "vec3(encoded.r + encoded.g, encoded.r, encoded.r + encoded.b)", + ), + ) + assertFalse(shader.contains("bayerIndexAt(uCfaPattern, outputP)")) + } + + @Test + fun radianceAccumulatorsUseOneSharedColorSupportThroughNormalization() { + val clear = GlesRawRadianceFusionShaders.clearAccumulator(trackRejections = false) + val accumulate = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false) + val reference = GlesRawRadianceFusionShaders.captureReferenceBase + val normalize = GlesRawRadianceFusionShaders.normalize(showRejections = false) + + assertTrue(clear.contains("uNrWeightRg")) + assertTrue(clear.contains("uDetailWeightRg")) + assertTrue(accumulate.contains("vec3 nrWeight")) + assertTrue(accumulate.contains("nrWeight = vec3(sharedNrWeight)")) + assertTrue(accumulate.contains("detailWeight = vec3(sharedDetailWeight)")) + assertTrue(accumulate.contains("rgb.denoise.rg * nrWeight.rg")) + assertTrue(accumulate.contains("rgb.denoise.b * nrWeight.b")) + assertTrue(reference.contains("rg / weightRg")) + assertTrue(reference.contains("bw.x / weightB")) + assertTrue(normalize.contains("uniform highp usampler2D uNrWeightRg")) + assertTrue(normalize.contains("uniform highp usampler2D uDetailWeightRg")) + assertTrue(normalize.contains("vec3 weight = vec3(weightRg, max(bw.y, 0.0))")) + assertTrue(normalize.contains("vec3 confidence = vec3(sharedConfidence)")) + } + + @Test + fun rejectionOverlayColorsMaterialPerFrameRejectionsByFrequency() { + val shader = GlesRawRadianceFusionShaders.normalize(showRejections = true) + + assertTrue(shader.contains("uniform float uAcceptedFusionFrameCount")) + assertTrue(shader.contains("rejection.a / max(uAcceptedFusionFrameCount, 1.0)")) + assertTrue(shader.contains("displayStrength = sqrt(rejectedFrameFraction)")) + assertTrue(shader.contains("displayColor = vec3(1.0, 1.0, 0.0)")) + assertTrue(shader.contains("displayColor = vec3(1.0, 0.35, 0.0)")) + assertTrue(shader.contains("displayColor = vec3(1.0, 0.0, 1.0)")) + assertTrue(shader.contains("displayColor = vec3(0.0, 1.0, 1.0)")) + assertTrue(shader.contains("displayColor = vec3(0.0, 0.0, 1.0)")) + assertTrue(shader.contains("displayColor = vec3(1.0, 0.0, 0.0)")) + assertTrue(shader.contains("displayColor = vec3(0.0, 1.0, 0.0)")) + assertTrue(shader.contains("displayColor = vec3(1.0, 0.0, 1.0)")) + assertTrue(shader.contains("displayColor * uDebugNeutralRgb")) + assertTrue(shader.contains("displayStrength")) + assertTrue(shader.contains("uniform vec3 uDebugNeutralRgb;")) + assertFalse(shader.contains("mix(rgb, uDebugNeutralRgb")) + } + + @Test + fun srDetailOverlayUsesFinalNonReferenceDetailConfidence() { + val shader = GlesRawRadianceFusionShaders.normalize( + showRejections = false, + showSrDetail = true, + ) + + assertTrue(shader.contains("float srDetailConfidence = detailLumaSupport * centerLumaConsistency")) + assertTrue(shader.contains("srDetailConfidence * detailStability")) + assertTrue(shader.contains("vec3 srDetailColor = vec3(0.0, 1.0, 1.0)")) + assertTrue(shader.contains("mix(rgb, srDetailColor, srDetailConfidence)")) + assertTrue(shader.contains("uniform vec3 uDebugNeutralRgb;")) + assertFalse(shader.contains("uFusionRejections")) + } + + @Test + fun lumaDetailIsInjectedOnTheWhiteBalancedNeutralAxis() { + val shader = GlesRawRadianceFusionShaders.normalize(showRejections = false) + + assertTrue(shader.contains("uniform vec3 uCalculationGains")) + assertTrue(shader.contains("vec3 nrCalculation = nrSpatial * calculationGains")) + assertTrue(shader.contains("vec3 detailCalculation = detail * calculationGains")) + assertTrue(shader.contains("detailCalculation - nrCalculation")) + assertTrue( + shader.contains( + "(nrCalculation + vec3(signedLumaDetail)) / calculationGains", + ), + ) + assertFalse(shader.contains("nrSpatial + vec3(signedLumaDetail)")) + } + + @Test + fun productionShadersExcludeRejectionResources() { + val clear = GlesRawRadianceFusionShaders.clearAccumulator(trackRejections = false) + val accumulate = GlesRawRadianceFusionShaders.accumulate("", trackRejections = false) + val normalize = GlesRawRadianceFusionShaders.normalize(showRejections = false) + + assertFalse(clear.contains("uFusionRejections")) + assertFalse(accumulate.contains("uFusionRejections")) + assertFalse(accumulate.contains("uFusionParticipationStats")) + assertFalse(normalize.contains("uFusionRejections")) + assertFalse(normalize.contains("uDebugNeutralRgb")) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RadianceTilePlannerTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RadianceTilePlannerTest.kt new file mode 100644 index 00000000..8ac44589 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/processor/RadianceTilePlannerTest.kt @@ -0,0 +1,80 @@ +package com.hinnka.mycamera.processor + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RadianceTilePlannerTest { + @Test + fun twelveMegapixelFrameUsesTwelveNonOverlappingCores() { + val tiles = RadianceTilePlanner.plan( + rawWidth = 4096, + rawHeight = 3072, + outputWidth = 6144, + outputHeight = 4608, + coreSizeRawPx = 1024, + outputSpatialRadiusPx = 2, + cfaPeriod = 2, + ) + + assertEquals(12, tiles.size) + assertEquals(RadianceTileRect(0, 0, 1024, 1024), tiles.first().rawCore) + assertEquals(RadianceTileRect(0, 0, 1536, 1536), tiles.first().outputCore) + assertEquals(RadianceTileRect(3072, 2048, 4096, 3072), tiles.last().rawCore) + assertEquals(RadianceTileRect(4608, 3072, 6144, 4608), tiles.last().outputCore) + assertEquals(4096L * 3072L, tiles.sumOf { it.rawCore.width.toLong() * it.rawCore.height }) + assertEquals(6144L * 4608L, tiles.sumOf { it.outputCore.width.toLong() * it.outputCore.height }) + } + + @Test + fun edgeTilesCoverNonPowerOfTwoSensorWithoutGaps() { + val tiles = RadianceTilePlanner.plan( + rawWidth = 4032, + rawHeight = 3024, + outputWidth = 6048, + outputHeight = 4536, + coreSizeRawPx = 1024, + outputSpatialRadiusPx = 2, + cfaPeriod = 2, + ) + + assertEquals(12, tiles.size) + assertEquals(960, tiles[3].rawCore.width) + assertEquals(976, tiles[8].rawCore.height) + assertEquals(4032L * 3024L, tiles.sumOf { it.rawCore.width.toLong() * it.rawCore.height }) + assertEquals(6048L * 4536L, tiles.sumOf { it.outputCore.width.toLong() * it.outputCore.height }) + } + + @Test + fun sourceRegionPreservesCfaPhaseAndContainsFlowHalo() { + val tile = RadianceTilePlanner.plan( + rawWidth = 4096, + rawHeight = 3072, + outputWidth = 6144, + outputHeight = 4608, + coreSizeRawPx = 1024, + outputSpatialRadiusPx = 2, + cfaPeriod = 4, + )[5] + val source = RadianceTilePlanner.sourceRegion( + tile = tile, + rawWidth = 4096, + rawHeight = 3072, + outputWidth = 6144, + outputHeight = 4608, + flowBounds = RadianceFlowBounds(-12f, 9f, -7f, 11f), + cfaPeriod = 4, + reconstructionHaloRawPx = 20, + radianceSampleRadiusRawPx = 1, + ) + + assertEquals(0, source.left % 4) + assertEquals(0, source.top % 4) + assertEquals(0, source.right % 4) + assertEquals(0, source.bottom % 4) + assertTrue(source.left < tile.rawCore.left - 20) + assertTrue(source.top < tile.rawCore.top - 10) + assertTrue(source.right > tile.rawCore.right + 15) + assertTrue(source.bottom > tile.rawCore.bottom + 20) + } +} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawNoiseModelTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawNoiseModelTest.kt index 7f34b0ad..9d0af181 100644 --- a/app/src/test/java/com/hinnka/mycamera/processor/RawNoiseModelTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawNoiseModelTest.kt @@ -39,26 +39,66 @@ class RawNoiseModelTest { } @Test - fun noiseModelNormalizesSensorCoefficientsForShaderDomain() { - val varianceScale = SENSOR_SCALE * SENSOR_SCALE + fun noiseModelKeepsAlreadyNormalizedSensorCoefficientsInShaderDomain() { val model = RawNoiseModel.fromCamera2NoiseProfile( floatArrayOf( - SENSOR_SCALE, varianceScale, - SENSOR_SCALE * 0.5f, varianceScale * 0.25f, - 0f, 0f, - SENSOR_SCALE * 0.1f, varianceScale * 0.1f, + 0.001f, 0.00001f, + 0.002f, 0.00002f, + 0.003f, 0.00003f, + 0.004f, 0.00004f, ), ) assertArrayEquals( - floatArrayOf(1f, 0.5f, 0f, 0.1f), + floatArrayOf(0.001f, 0.002f, 0.003f, 0.004f), model.normalizedShotNoiseForShader(), - 0.000001f, + 0f, ) assertArrayEquals( - floatArrayOf(1f, 0.25f, 0f, 0.1f), + floatArrayOf(0.00001f, 0.00002f, 0.00003f, 0.00004f), model.normalizedReadNoiseForShader(), - 0.000001f, + 0f, + ) + } + + @Test + fun camera2PhaseNoiseIsReorderedToCanonicalBayerChannels() { + val model = RawNoiseModel.fromCamera2NoiseProfile( + floatArrayOf( + 1f, 10f, + 2f, 20f, + 3f, 30f, + 4f, 40f, + ), + ) + + assertArrayEquals( + floatArrayOf(2f, 1f, 4f, 3f), + model.normalizedShotNoiseForShader(cfaPattern = 1), + 0f, + ) + assertArrayEquals( + floatArrayOf(30f, 40f, 10f, 20f), + model.normalizedReadNoiseForShader(cfaPattern = 2), + 0f, + ) + } + + @Test + fun threePlaneDngNoiseExpandsGreenWithoutCfaReordering() { + val model = RawNoiseModel.fromCamera2NoiseProfile( + floatArrayOf( + 1f, 10f, + 2f, 20f, + 3f, 30f, + 0f, 0f, + ), + ) + + assertArrayEquals( + floatArrayOf(1f, 2f, 2f, 3f), + model.normalizedShotNoiseForShader(cfaPattern = 3), + 0f, ) } @@ -80,8 +120,4 @@ class RawNoiseModelTest { assertArrayEquals(FloatArray(4), negative.shotNoise, 0f) assertArrayEquals(FloatArray(4), negative.readNoise, 0f) } - - private companion object { - const val SENSOR_SCALE = 65535.0f - } } diff --git a/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt index 340acaf3..940d22ad 100644 --- a/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/processor/RawSuperResolutionStripePlannerTest.kt @@ -37,6 +37,7 @@ class RawSuperResolutionStripePlannerTest { val last = RawSuperResolutionStripePlanner.sourceRowBand(1792, 208, 2f, -2f, 10f, 8, 1000) assertEquals(0, first.firstRow) + assertEquals(0, last.firstRow % 8) assertEquals(1000, last.endExclusive) } } diff --git a/app/src/test/java/com/hinnka/mycamera/raw/RcdShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/RcdShadersTest.kt index f6ef2dc5..c6645eb2 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/RcdShadersTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/RcdShadersTest.kt @@ -18,9 +18,9 @@ class RcdShadersTest { } @Test - fun stripeRcdUsesTheSamePpgKernelOnTheRealPhotoBorder() { + fun regionRcdUsesTheSamePpgKernelOnTheRealPhotoBorder() { val fullImageShader = RcdShaders.WRITE_OUTPUT - val stripeShader = RcdShaders.STRIPE_BORDER_PPG + val regionShader = RcdShaders.REGION_BORDER_PPG val sharedKernelLines = listOf( "float ppgGreenAt(ivec2 coord)", "vec3 ppgColorAt(ivec2 coord)", @@ -30,9 +30,9 @@ class RcdShadersTest { sharedKernelLines.forEach { line -> assertTrue(fullImageShader.contains(line)) - assertTrue(stripeShader.contains(line)) + assertTrue(regionShader.contains(line)) } - assertTrue(stripeShader.contains("vec3 color = ppgColorAt(global);")) - assertTrue(stripeShader.contains("mirrorIndex(global.y + dy, uFullImageSize.y)")) + assertTrue(regionShader.contains("vec3 color = ppgColorAt(global);")) + assertTrue(regionShader.contains("mirrorIndex(global.y + delta, uFullImageSize.y)")) } } diff --git a/docs/gles-driver-compatibility.md b/docs/gles-driver-compatibility.md index 6f803d5a..fa0ae1ad 100644 --- a/docs/gles-driver-compatibility.md +++ b/docs/gles-driver-compatibility.md @@ -53,28 +53,76 @@ MFSR accumulator 只保存 `weightedValue + weight`,使用一张 `R32UI`,为 ### Radiance RGB accumulator `GlesRawRadianceFusion` 同样遵循上述限制,不使用 `RGBA32F/RGBA16F` read/write image。 -每个输出像素使用四张 `R32UI`: +每个输出像素使用六张 `R32UI`,NR 与 Detail 各自保存完整的逐通道和值/权重: 1. NR `sumR + sumG` -2. NR `sumB + weight` -3. Detail `sumR + sumG` -4. Detail `sumB + weight` +2. NR `sumB + weightB` +3. NR `weightR + weightG` +4. Detail `sumR + sumG` +5. Detail `sumB + weightB` +6. Detail `weightR + weightG` -四张纹理均通过 `packHalf2x16` 原位累积。参考帧连续 RGB 底图在参考帧累积完成后,由 +六张纹理均通过 `packHalf2x16` 原位累积。参考帧连续 RGB 底图在参考帧累积完成后,由 `usampler2D` 读取 NR accumulator,再写入单独的 `RGBA16F writeonly image2D`。最终 -normalize 只能通过四个 `usampler2D` 和一个普通 `sampler2D` 读取这些资源。 +normalize 只能通过六个 `usampler2D` 和一个普通 `sampler2D` 读取这些资源。 -这样 compute pass 同时最多绑定四个 read/write image,且所有 read/write image 都是已经 -在 PMA110 验证过的 `R32UI`。 +这样 compute pass 同时最多绑定六个 read/write image,低于 GLES 3.1 保证的八个 compute +image unit 下限;所有 read/write image 仍是已经在 PMA110 验证过的 `R32UI` 格式。新增绑定 +数量仍须在代表设备上执行 shader compile、bind、dispatch 和 normalize 采样验证。 -Radiance 每帧先通过项目既有的 RCD pass 得到条带式 `RGBA16F` 连续 RGB。RCD 结果通过 -`writeonly image2D` 写入、在 accumulator pass 中只作为普通线性过滤 `sampler2D` 读取, -不作为 read/write image。这样避免分别插值 R/G/B CFA 平面造成的绿色 zipper 和孤立伪色, -同时把 accumulator pass 的 RAW/LSC 邻域读取缩减为少量 RGB texture sample。 +Radiance 的公共对齐/光度置信度来自绿色结构引导。连续 RGB 域的色度一致性必须分别使用 +`R-G` 和 `B-G` 对手轴,差值方差分别为 `Var(R)+Var(G)` 与 `Var(B)+Var(G)`;不得把 R/G/B +噪声精度先平均为一个标量。R、G、B 的 NR/Detail 权重须独立累计和归一化,R 或 B 的色度 +噪声只能降低对应通道,不能连带降低绿色或另一个色度通道。 + +Radiance 拒绝原因调试图需要跨帧保留分类原因、排查优先级、拒绝强度和命中次数时,使用 +两张 `RGBA16F` 纹理 ping-pong:上一张仅作为普通 `sampler2D` 读取,下一张仅以 +`layout(rgba16f) writeonly image2D` 写入。每次 dispatch 后交换纹理角色。禁止把其中任何一张 +绑定为 `GL_READ_WRITE`,也禁止在同一个 shader 中对同一张 `RGBA16F` 同时调用 +`imageLoad` 和 `imageStore`。 + +Radiance 的 tile confidence 固定使用 `RGBA16F`,不能把 NR 与 Detail 压回同一个标量: +R 是 NR confidence,G 是 Detail confidence,B/A 是仅供调试使用的 NR 拒绝原因编号和强度。 +拒绝优先级由原因编号在 accumulator shader 中恢复,不占用纹理通道。跨帧累计只记录实际 +达到 material rejection 阈值的逐帧原因;A 通道累计被拒帧数。最终颜色强度按被拒帧比例的 +平方根显示,因此局部运动即使仍有其他帧成功融合也能看见,而弱惩罚不会被误画成拒绝。 + +RAW proxy 的通道语义也必须保持分离:R 是跟踪信号,G 是物理采样有效性(主要排除削波), +B 是对齐可观测性。暗部和低纹理可以令 B 接近零,使局部对齐保持继承流场,但不能令 G 清零。 +NR confidence 只由采样有效性、噪声归一化光度一致性和局部流场连续性决定;patch score、 +patch peak 和纹理强度只能限制 Detail/SR,不能拒绝暗部降噪融合。 +局部流场范围从 `flowRangePenaltyStartPx` 开始连续降权,并在 `flowRangeRejectPx` 归零;该惩罚 +必须由 patch peak 或噪声归一化边缘证据激活,避免低纹理暗部因流场不可观测而再次被误拒绝。 + +SR Detail 调试覆盖必须在最终 normalize pass 中根据 `additionalDetailWeight` 生成,不能直接 +显示上游 G 通道候选 mask。最终覆盖强度还要乘 NR 一致性和 detail stability,确保青色只表示 +真正进入最终细节分支的非参考帧支持;零支持区域保持原图。若同时开启拒绝图,实际拒绝颜色 +最后写入并覆盖 SR Detail 青色。 + +融合参与度日志同样必须统计最终 accumulator weight,而不是上游 mask。Radiance accumulate +在每个输出 core 内按固定步长采样,使用 SSBO 原子计数分别记录尝试数、NR 非零权重数、NR +Q6 平均 RGB 权重和、Detail 非零权重数、Detail Q6 平均 RGB 权重和;working halo 不计数, +避免分片重叠造成重复。 +日志要把整帧准入率、局部 NR 参与率、平均 merge factor 和 Detail 参与率分开输出,才能与 +GCam 的 merge frame count、block rejection percentage 和 average merge factor 对照。 + +Radiance 对标准 2x2 Bayer 使用非对称重建:参考帧在每个分片内运行完整 VGN 基础解马赛克 +(Prepare 到 Pass 3),随后直接从 YCCD 转回未白平衡 camera RGB;不调度 VGN 色度降噪和 +IIR。非参考帧只生成 Dense G、原生 R-G 和原生 B-G,再分别沿全局 R/B 相位格点补全两个 +色差平面。warp 和融合阶段不再读取或判断 CFA 相位,因而不会把跨相位位移解释成绿色像素。 +Quad/Nona 等非标准 CFA 继续使用区域 RCD 兼容后端。 + +重建结果通过 `writeonly image2D` 写入、在 accumulator pass 中只作为普通线性过滤 +`sampler2D` 读取,不作为 read/write image。参考帧纹理编码为 camera RGB;非参考帧纹理 +编码为 `(G, R-G, B-G)`,仅在采样后解码为 RGB。分片原点必须按 CFA 周期对齐,VGN 工作域 +必须从全局 CFA 相位映射到规范 RGGB,相位选择不得依赖输出坐标或输出倍率。 窄核 Detail accumulator 默认只向宽核 NR 结果注入亮度高频;色度由宽核分支持有。只有在 多帧细节支持度和一致性都足够高时,才允许通过 `detailChromaStrength` 恢复一部分窄核色度。 这样可避免对齐残差重新被放大成彩色 zipper。 +由于 Radiance 缓冲保持未白平衡 camera RGB,亮度高频的提取、headroom 限制与中性轴注入 +必须先进入 calculation/WB RGB,完成后再除以 WB gain 返回 camera RGB。不能直接在 camera +RGB 中增加 `vec3(detail)`,否则后续 WB 会把边缘的正负高频变成互补的紫色/黄绿色彩边。 ### 验收要求 @@ -86,7 +134,21 @@ Radiance 每帧先通过项目既有的 RCD pass 得到条带式 `RGBA16F` 连 - `R32UI` imageLoad/imageStore - `usampler2D` normalize - MFNR 与 MFSR 两种模式 -- Radiance clear、accumulate、reference-base capture 与 normalize 四个 pass +- Radiance VGN reference、semantic seed/resolve、clear、accumulate、reference-base capture 与 + normalize pass + +Radiance 的噪声与色差一致性必须继续按传感器通道以及 `R-G`、`B-G` 两条色差轴分别 +估算,但最终帧采纳权重和参考帧回退置信度必须对完整 RGB 三元组共用同一个保守值。 +不得让 G 与 R/B 使用不同的有效帧集合,否则即使非参考帧已经完成 CFA 无关重建,细边缘 +仍会因为通道来源不一致产生绿/品红色边。 + +非参考帧 semantic proxy 的 Dense-G 二阶校正必须限制在所选方向的相邻原生 G 范围内, +最终估计也不得超出四个相邻原生 G 的包络。无界 Hamilton–Adams 校正在少数虚焦或高反差 +彩色边缘上会制造不存在的 G 极值,这种错误会在进入融合前就表现为局部绿色边缘。 + +`R-G` 与 `B-G` 从同色 2×2 格点恢复到全分辨率时,不能在强边缘上无条件双线性插值。 +平坦区使用双线性权重,高反差区还需按目标 Dense-G 与各同色格点 G 的相似度引导权重, +使亮度与色差边缘保持同一位置;否则合法但更宽的色差过渡仍会形成局部绿/品红色边。 桌面静态检查和 Kotlin 编译不能替代真机验证。新增格式前应优先扩展 `app/src/androidTest/java/com/hinnka/mycamera/processor/GlesRawStackerShaderTest.kt`,让测试实际 diff --git a/docs/raw-stack-mfnr-mfsr-implementation-plan.md b/docs/raw-stack-mfnr-mfsr-implementation-plan.md index 31aa5f97..c6adfb71 100644 --- a/docs/raw-stack-mfnr-mfsr-implementation-plan.md +++ b/docs/raw-stack-mfnr-mfsr-implementation-plan.md @@ -247,10 +247,8 @@ data class RawStackTuningProfile( - `residualTauBase` - `residualTauEdge` - `residualPower` - - `flowPenaltyStartPx` - - `flowPenaltyDecay` - `flowRangePenaltyStartPx` - - `flowRangePenaltyDecay` + - `flowRangeRejectPx` - `centerMixFlat` - `centerMixEdge` - `minMixFlat`