feat: radiance (1)

This commit is contained in:
Hinnka committed 2026-07-19 21:01:58 +08:00
1 parent c2a8a73b09
commit e8cfc9dfb0
24 files changed
+4386 -995

No files matched your search

@@ -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,
)
}
}
@@ -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<CaptureRequest>()
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()
}
}
@@ -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,
@@ -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)
}
}
@@ -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()
}
@@ -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;
File diff suppressed because it is too large. Load diff
@@ -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()
}
File diff suppressed because it is too large. Load diff
@@ -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<RadianceTile> {
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<RadianceTile>()
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
}
@@ -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,
)
}
@@ -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
}
}
@@ -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,
@@ -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)
@@ -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;
@@ -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))
}
}
@@ -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"))
}
}
@@ -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"))
}
}
@@ -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)
}
}
@@ -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
}
}
@@ -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)
}
}
@@ -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)"))
}
}