fix: mfsr

This commit is contained in:
zhoubinjia committed 2026-03-16 19:50:54 +08:00
1 parent a80415e3b3
commit 52bf3cb86e
16 files changed
+2334 -286

No files matched your search

+4
View File
@@ -37,6 +37,10 @@ set(SHADER_SOURCES
shaders/align_lk.comp
shaders/raw_structure_tensor.comp
shaders/robustness_raw.comp
shaders/green_scatter_raw.comp
shaders/normalize_green_hr.comp
shaders/color_scatter_raw.comp
shaders/normalize_color_hr.comp
shaders/yuv_to_rgba.comp
)
+51 -27
View File
@@ -20,6 +20,10 @@ layout(binding = 4, scalar) buffer MotionPrior {
float errors[];
} motionPrior;
layout(binding = 5, scalar) buffer LocalTileMask {
float weights[];
} localTileMask;
layout(push_constant, scalar) uniform PushConstants {
float t0, t1, t2, t3, t4, t5;
float offsetX, offsetY;
@@ -37,30 +41,41 @@ layout(push_constant, scalar) uniform PushConstants {
uint bufferStride;
float noiseAlpha; // Sensor noise model slope
float noiseBeta; // Sensor noise model intercept
float frameWeight;
} pc;
vec4 sampleBicubic(sampler2D s, vec2 uv, vec2 size) {
// Standard bicubic sampling
// We rely on high quality sampling for the input value
// But for the weight calculation we use analytic Gaussian
vec2 f = fract(uv * size - 0.5);
vec2 invSize = 1.0 / size;
vec2 center = (floor(uv * size - 0.5) + 0.5) * invSize;
vec2 texelPos = uv * size - 0.5;
ivec2 base = ivec2(floor(texelPos));
vec2 f = texelPos - vec2(base);
// Catmull-Rom weights
// Optimized implementation could go here, but for clarity:
// This is just a placeholder if we need strict bicubic value fetch
// Actually, texture() with linear filtering is often "good enough" for the value
// *if* we have many frames. But for super-res, we want to avoid blurring the input.
// Let's use the hardware linear filter to save cost,
// as the main quality comes from the Merge Kernel, not the Input Resampler.
// BUT paper says "Bicubic interpolation".
// Let's stick to a simple 4-tap or decent hardware linear for now to save cycles
// unless we see quality issues. The previous code had a manual bicubic.
// Let's revert to Texture Linear for performance in this heavy shader,
// unless user complains about sharpness.
return texture(s, uv);
float wx[4];
float wy[4];
float fx = f.x;
float fy = f.y;
wx[0] = -0.5 * fx + fx * fx - 0.5 * fx * fx * fx;
wx[1] = 1.0 - 2.5 * fx * fx + 1.5 * fx * fx * fx;
wx[2] = 0.5 * fx + 2.0 * fx * fx - 1.5 * fx * fx * fx;
wx[3] = -0.5 * fx * fx + 0.5 * fx * fx * fx;
wy[0] = -0.5 * fy + fy * fy - 0.5 * fy * fy * fy;
wy[1] = 1.0 - 2.5 * fy * fy + 1.5 * fy * fy * fy;
wy[2] = 0.5 * fy + 2.0 * fy * fy - 1.5 * fy * fy * fy;
wy[3] = -0.5 * fy * fy + 0.5 * fy * fy * fy;
vec4 accum = vec4(0.0);
float weightSum = 0.0;
for (int j = 0; j < 4; ++j) {
for (int i = 0; i < 4; ++i) {
ivec2 p = base + ivec2(i - 1, j - 1);
p = clamp(p, ivec2(0), ivec2(size) - ivec2(1));
float w = wx[i] * wy[j];
accum += texelFetch(s, p, 0) * w;
weightSum += w;
}
}
return (abs(weightSum) > 1e-6) ? (accum / weightSum) : accum;
}
// Compute Anisotropic Gaussian Weight
@@ -111,6 +126,13 @@ float computeKernelWeight(vec2 diffVec, vec4 kp) {
return w;
}
float sampleLocalTileWeight(vec2 uv) {
vec2 gridPos = uv * vec2(float(pc.gridW), float(pc.gridH));
ivec2 g = ivec2(floor(gridPos));
g = clamp(g, ivec2(0), ivec2(int(pc.gridW) - 1, int(pc.gridH) - 1));
return clamp(localTileMask.weights[g.y * int(pc.gridW) + g.x], 0.0, 1.0);
}
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
@@ -171,10 +193,6 @@ void main() {
finalUV += alignment / nativeSize;
}
// 3. Sample Input Frame (Target)
// Using hardware linear for speed, replace with Bicubic function if needed
vec4 targetVal = texture(rgbSampler, finalUV);
// 4. Kernel Regression Elements
vec2 posInSource = finalUV * nativeSize;
vec2 centerSource = floor(posInSource - 0.5) + 0.5;
@@ -187,7 +205,7 @@ void main() {
float centerRobustness = 1.0;
if (pc.isFirstFrame == 0 && currentW > 0.001) {
vec3 refRGB = accumulator.data[outIndex].rgb / currentW;
vec3 centerColor = texture(rgbSampler, finalUV).rgb;
vec3 centerColor = sampleBicubic(rgbSampler, finalUV, nativeSize).rgb;
vec3 diffVec = abs(centerColor - refRGB);
float diff = max(diffVec.r, max(diffVec.g, diffVec.b));
float luma = refRGB.g;
@@ -210,14 +228,20 @@ void main() {
centerRobustness *= (1.0 / (1.0 + motionError * 0.005));
if (isnan(centerRobustness)) centerRobustness = 0.0;
}
float localTileWeight = sampleLocalTileWeight(finalUV);
float detailStrength = smoothstep(6.0, 28.0, max(kp.x, kp.y));
int supportRadius = (detailStrength > 0.45) ? 1 : 2;
// Accumulate neighbors
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
if (abs(i) > supportRadius || abs(j) > supportRadius) {
continue;
}
vec2 samplePos = centerSource + vec2(float(i), float(j));
vec2 sampleUV = samplePos / nativeSize;
vec3 sampleColor = texture(rgbSampler, sampleUV).rgb;
vec3 sampleColor = sampleBicubic(rgbSampler, sampleUV, nativeSize).rgb;
vec2 d = (samplePos - posInSource);
// Per-sample robustness
@@ -237,7 +261,7 @@ void main() {
// We multiply the inverse variances by 0.25 to normalize the spatial spread.
float w = exp(-0.5 * (u*u * kp.x * 0.25 + v*v * kp.y * 0.25));
float combinedWeight = w * robustness;
float combinedWeight = w * robustness * pc.frameWeight * localTileWeight;
if (isnan(combinedWeight) || isinf(combinedWeight)) combinedWeight = 0.0;
vec4 increment = vec4(sampleColor * combinedWeight, combinedWeight);
+155 -87
View File
@@ -35,6 +35,7 @@ layout(push_constant, scalar) uniform PushConstants {
float noiseAlpha;
float noiseBeta;
float baseNoise;
float frameWeight;
} pc;
// Bindings
@@ -61,6 +62,75 @@ layout(set = 0, binding = 4, scalar) buffer RobustnessBuffer {
} outRobustness;
layout(set = 0, binding = 5) uniform sampler2D uLensShadingMap;
layout(set = 0, binding = 6, scalar) buffer LocalTileMask {
float data[];
} localTileMask;
float cubicWeight(float x) {
x = abs(x);
if (x >= 2.0) return 0.0;
if (x < 1.0) {
return 1.0 - 2.5 * x * x + 1.5 * x * x * x;
}
return 2.0 - 4.0 * x + 2.5 * x * x - 0.5 * x * x * x;
}
int getSampleColor(int cfaPattern, ivec2 samplePos, out int lscIdx) {
int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1);
int sampleColor = -1;
lscIdx = -1;
if (cfaPattern == 0) { // RGGB
if (samplePhase == 0) { sampleColor = 0; lscIdx = 0; }
else if (samplePhase == 1) { sampleColor = 1; lscIdx = 1; }
else if (samplePhase == 2) { sampleColor = 1; lscIdx = 2; }
else { sampleColor = 2; lscIdx = 3; }
} else if (cfaPattern == 1) { // GRBG
if (samplePhase == 0) { sampleColor = 1; lscIdx = 1; }
else if (samplePhase == 1) { sampleColor = 0; lscIdx = 0; }
else if (samplePhase == 2) { sampleColor = 2; lscIdx = 3; }
else { sampleColor = 1; lscIdx = 2; }
} else if (cfaPattern == 2) { // GBRG
if (samplePhase == 0) { sampleColor = 1; lscIdx = 2; }
else if (samplePhase == 1) { sampleColor = 2; lscIdx = 3; }
else if (samplePhase == 2) { sampleColor = 0; lscIdx = 0; }
else { sampleColor = 1; lscIdx = 1; }
} else { // BGGR
if (samplePhase == 0) { sampleColor = 2; lscIdx = 3; }
else if (samplePhase == 1) { sampleColor = 1; lscIdx = 2; }
else if (samplePhase == 2) { sampleColor = 1; lscIdx = 1; }
else { sampleColor = 0; lscIdx = 0; }
}
return sampleColor;
}
ivec2 getLatticeParity(int cfaPattern, int targetCFA, int familyIndex) {
if (cfaPattern == 0) { // RGGB
if (targetCFA == 0) return ivec2(0, 0);
if (targetCFA == 2) return ivec2(1, 1);
return (familyIndex == 0) ? ivec2(1, 0) : ivec2(0, 1);
} else if (cfaPattern == 1) { // GRBG
if (targetCFA == 0) return ivec2(1, 0);
if (targetCFA == 2) return ivec2(0, 1);
return (familyIndex == 0) ? ivec2(0, 0) : ivec2(1, 1);
} else if (cfaPattern == 2) { // GBRG
if (targetCFA == 0) return ivec2(0, 1);
if (targetCFA == 2) return ivec2(1, 0);
return (familyIndex == 0) ? ivec2(0, 0) : ivec2(1, 1);
} else { // BGGR
if (targetCFA == 0) return ivec2(1, 1);
if (targetCFA == 2) return ivec2(0, 0);
return (familyIndex == 0) ? ivec2(1, 0) : ivec2(0, 1);
}
}
float nearestFamilyDistanceSq(vec2 centerPos, ivec2 parity) {
vec2 lattice = 0.5 * (centerPos - vec2(parity));
vec2 nearest = floor(lattice + 0.5);
vec2 samplePos = nearest * 2.0 + vec2(parity);
vec2 d = samplePos - centerPos;
return dot(d, d);
}
// Helper to get inverse kernel matrix from parameters
// Params: k1, k2, cos2t, sin2t
@@ -81,6 +151,15 @@ vec3 getKernelMatrix(vec4 params) {
return vec3(a, b, c_val);
}
float sampleLocalTileWeight(vec2 rawPos) {
vec2 planePos = rawPos * 0.5;
uint tilesX = (pc.planeWidth + 15u) / 16u;
uint tilesY = (pc.planeHeight + 15u) / 16u;
uint tileX = min(uint(clamp(floor(planePos.x / 16.0), 0.0, float(max(tilesX, 1u) - 1u))), max(tilesX, 1u) - 1u);
uint tileY = min(uint(clamp(floor(planePos.y / 16.0), 0.0, float(max(tilesY, 1u) - 1u))), max(tilesY, 1u) - 1u);
return clamp(localTileMask.data[tileY * tilesX + tileX], 0.0, 1.0);
}
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
@@ -132,109 +211,98 @@ void main() {
vec2 f11 = alignBuffer.offsets[g1.y * pc.gridW + g1.x];
flow = mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y);
}
vec2 flowRaw = flow * 2.0; // In raw pixels
// Projected Center in Input Frame
vec2 centerPos = vec2(float(outX) / pc.scale, float(outY) / pc.scale) + flowRaw;
float localTileWeight = sampleLocalTileWeight(centerPos);
// Window search in Current Frame (Bayer)
// 3×3 nearest neighbors (Paper §5.4: "每个输出像素独立处理 9 个最近邻")
// For Bayer, we need slightly larger to find same-color samples,
// but 5×5 is sufficient (guarantees ≥4 same-color in any CFA pattern).
ivec2 iCenter = ivec2(round(centerPos));
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
ivec2 samplePos = iCenter + ivec2(dx, dy);
// Reconstruct on the Bayer color lattice instead of averaging over a dense
// square neighborhood. This preserves sub-pixel sample placement better.
int familyCount = (targetCFA == 1) ? 2 : 1;
int dominantFamily = 0;
if (targetCFA == 1 && pc.scale > 1.5) {
float bestDist = 1e10;
for (int family = 0; family < 2; ++family) {
ivec2 parity = getLatticeParity(int(pc.cfaPattern), targetCFA, family);
float distSq = nearestFamilyDistanceSq(centerPos, parity);
if (distSq < bestDist) {
bestDist = distSq;
dominantFamily = family;
}
}
}
for (int family = 0; family < familyCount; ++family) {
ivec2 parity = getLatticeParity(int(pc.cfaPattern), targetCFA, family);
vec2 latticeCenter = 0.5 * (centerPos - vec2(parity));
ivec2 latticeBase = ivec2(floor(latticeCenter));
float familyWeight = 1.0;
if (targetCFA == 1 && pc.scale > 1.5) {
familyWeight = (family == dominantFamily) ? 1.0 : 0.12;
}
for (int ly = -1; ly <= 1; ++ly) {
for (int lx = -1; lx <= 1; ++lx) {
ivec2 latticeCoord = latticeBase + ivec2(lx, ly);
ivec2 samplePos = latticeCoord * 2 + parity;
if (samplePos.x < 0 || samplePos.y < 0 ||
samplePos.x >= int(pc.sensorWidth) ||
samplePos.y >= int(pc.sensorHeight)) {
continue;
}
int lscIdx = -1;
int sampleColor = getSampleColor(int(pc.cfaPattern), samplePos, lscIdx);
if (sampleColor != targetCFA) continue;
// Check Bounds
if (samplePos.x < 0 || samplePos.y < 0 ||
samplePos.x >= int(pc.sensorWidth) || samplePos.y >= int(pc.sensorHeight)) continue;
// --- Strict Weight Calculation ---
// Check Color Channel of Sample
// Bayer Pattern Logic
int samplePhase = (samplePos.y % 2) * 2 + (samplePos.x % 2);
// Spatial Distance d = samplePos - centerPos (in raw sensor pixels)
vec2 d_raw = vec2(samplePos) - centerPos;
vec2 d = d_raw * 0.5;
int sampleColor = -1;
int lscIdx = -1; // 0=R, 1=Gr, 2=Gb, 3=B
float mahalanobis = OmegaInv.x * d.x * d.x +
(OmegaInv.y * d.x * d.y) * 2.0 +
OmegaInv.z * d.y * d.y;
if (pc.cfaPattern == 0) { // RGGB
if (samplePhase == 0) { sampleColor = 0; lscIdx = 0; }
else if (samplePhase == 1) { sampleColor = 1; lscIdx = 1; }
else if (samplePhase == 2) { sampleColor = 1; lscIdx = 2; }
else { sampleColor = 2; lscIdx = 3; }
} else if (pc.cfaPattern == 1) { // GRBG
if (samplePhase == 0) { sampleColor = 1; lscIdx = 1; }
else if (samplePhase == 1) { sampleColor = 0; lscIdx = 0; }
else if (samplePhase == 2) { sampleColor = 2; lscIdx = 3; }
else { sampleColor = 1; lscIdx = 2; }
} else if (pc.cfaPattern == 2) { // GBRG
if (samplePhase == 0) { sampleColor = 1; lscIdx = 2; }
else if (samplePhase == 1) { sampleColor = 2; lscIdx = 3; }
else if (samplePhase == 2) { sampleColor = 0; lscIdx = 0; }
else { sampleColor = 1; lscIdx = 1; }
} else { // BGGR
if (samplePhase == 0) { sampleColor = 2; lscIdx = 3; }
else if (samplePhase == 1) { sampleColor = 1; lscIdx = 2; }
else if (samplePhase == 2) { sampleColor = 1; lscIdx = 1; }
else { sampleColor = 0; lscIdx = 0; }
}
float raw = texelFetch(inputRawSampler, samplePos, 0).r;
if (sampleColor != targetCFA) continue;
int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1);
float black = pc.blackLevel[samplePhase];
float val = max(0.0, raw * 65535.0 - black);
// --- Strict Weight Calculation ---
vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight);
vec4 lscGains = texture(uLensShadingMap, lscUV);
float lscGain = 1.0;
if (lscIdx == 0) lscGain = lscGains.r;
else if (lscIdx == 1) lscGain = lscGains.g;
else if (lscIdx == 2) lscGain = lscGains.b;
else if (lscIdx == 3) lscGain = lscGains.a;
// Spatial Distance d = samplePos - centerPos (in raw sensor pixels)
vec2 d_raw = vec2(samplePos) - centerPos;
// Convert to plane pixels (half-res) to match kernel parameter coordinate space
// k1, k2 were computed at plane resolution in raw_structure_tensor.comp
vec2 d = d_raw * 0.5;
val *= lscGain;
val /= 65535.0;
// Kernel Weight: exp( -0.5 * d^T * Omega^-1 * d )
// OmegaInv packed as vec3(a, b, c) -> [a b; b c]
float mahalanobis = OmegaInv.x * d.x * d.x +
(OmegaInv.y * d.x * d.y) * 2.0 +
OmegaInv.z * d.y * d.y;
int rX = clamp(samplePos.x / 2, 0, int(pc.planeWidth)-1);
int rY = clamp(samplePos.y / 2, 0, int(pc.planeHeight)-1);
// Fetch Value
float raw = texelFetch(inputRawSampler, samplePos, 0).r;
float R = 1.0;
if (pc.isFirstFrame == 0) {
R = outRobustness.data[rY * pc.planeWidth + rX];
}
// --- Scientific Correction ---
// 1. Black Level Subtraction
float black = pc.blackLevel[samplePhase];
float val = max(0.0, raw * 65535.0 - black);
vec2 d_hr = d_raw * pc.scale;
float reconWeight = cubicWeight(d_hr.x) * cubicWeight(d_hr.y);
if (reconWeight <= 0.0) continue;
float w = exp(-0.5 * max(mahalanobis, 0.0)) *
reconWeight * R * pc.frameWeight * familyWeight *
localTileWeight;
// 2. Lens Shading Correction
// Android LensShadingMap order: [R, Gr, Gb, B]
// Bayer phase (RGGB): 0=R, 1=Gr, 2=Gb, 3=B
vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight);
vec4 lscGains = texture(uLensShadingMap, lscUV);
float lscGain = 1.0;
if (lscIdx == 0) lscGain = lscGains.r;
else if (lscIdx == 1) lscGain = lscGains.g;
else if (lscIdx == 2) lscGain = lscGains.b;
else if (lscIdx == 3) lscGain = lscGains.a;
val *= lscGain;
val /= 65535.0; // Normalize back to [0, 1] for accumulator
// Fetch Robustness R
// Robustness is at Half-Res (Plane)
int rX = clamp(samplePos.x / 2, 0, int(pc.planeWidth)-1);
int rY = clamp(samplePos.y / 2, 0, int(pc.planeHeight)-1);
float R = 1.0;
if (pc.isFirstFrame == 0) {
// Fetch precomputed and min-filtered robustness
R = outRobustness.data[rY * pc.planeWidth + rX];
}
// Final Weight
float w = exp(-0.5 * max(mahalanobis, 0.0)) * R;
// Accumulate (Value * Weight, Weight)
accumVal += vec2(val * w, w);
accumVal += vec2(val * w, w);
}
}
}
+40 -21
View File
@@ -45,16 +45,36 @@ layout(binding = 2, scalar) buffer AlignmentBuffer {
vec2 offsets[]; // Alignment (u,v) per tile
} alignBuffer;
// Helper: Sample half-resolution luminance at plane coordinate (px, py)
// Uses textureGather to fetch 2×2 Bayer quad and averages for CFA-aware luminance.
// This avoids hardware bilinear which mixes Bayer colors at boundaries.
float getLuma(sampler2D tex, vec2 planeUV) {
// Convert plane UV to sensor UV, targeting center of the 2×2 Bayer block
vec2 sensorUV = planeUV;
// textureGather fetches 4 texels from a 2×2 block around the UV
vec4 quad = textureGather(tex, sensorUV, 0);
// Average all 4 Bayer values → approximate luminance
return dot(quad, vec4(0.25));
float getGreenBlock(sampler2D tex, ivec2 planeCoord) {
int sx = clamp(planeCoord.x * 2, 0, int(pc.sensorWidth) - 2);
int sy = clamp(planeCoord.y * 2, 0, int(pc.sensorHeight) - 2);
float g1 = 0.0;
float g2 = 0.0;
if (pc.cfaPattern == 0u || pc.cfaPattern == 3u) {
g1 = texelFetch(tex, ivec2(sx + 1, sy), 0).r;
g2 = texelFetch(tex, ivec2(sx, sy + 1), 0).r;
} else {
g1 = texelFetch(tex, ivec2(sx, sy), 0).r;
g2 = texelFetch(tex, ivec2(sx + 1, sy + 1), 0).r;
}
return 0.5 * (g1 + g2);
}
float sampleGreenProxy(sampler2D tex, vec2 planePos) {
vec2 clampedPos = clamp(
planePos,
vec2(0.0),
vec2(float(pc.planeWidth - 1u), float(pc.planeHeight - 1u)));
ivec2 p0 = ivec2(floor(clampedPos));
ivec2 p1 = min(p0 + ivec2(1), ivec2(int(pc.planeWidth) - 1, int(pc.planeHeight) - 1));
vec2 f = clampedPos - vec2(p0);
float g00 = getGreenBlock(tex, p0);
float g10 = getGreenBlock(tex, ivec2(p1.x, p0.y));
float g01 = getGreenBlock(tex, ivec2(p0.x, p1.y));
float g11 = getGreenBlock(tex, p1);
return mix(mix(g00, g10, f.x), mix(g01, g11, f.x), f.y);
}
void main() {
@@ -93,7 +113,6 @@ void main() {
uint startY = gy * tileH;
vec2 planeDims = vec2(pc.planeWidth, pc.planeHeight);
vec2 pixelSize = 1.0 / vec2(pc.sensorWidth, pc.sensorHeight); // Raw Pixel Size
// Iterate over the tile
// Note: LK usually runs largely on gradients of the WARPED image I?
@@ -113,22 +132,22 @@ void main() {
uint py = startY + y;
if (px >= pc.planeWidth || py >= pc.planeHeight) continue;
vec2 baseUV = (vec2(px, py) + 0.5) / planeDims;
vec2 basePoint = vec2(px, py);
// 1. Sample Base Frame T(x) — Bayer-averaged luminance
float T = getLuma(refImg, baseUV);
// 1. Sample Base Frame T(x) — green proxy keeps more text edge energy
float T = sampleGreenProxy(refImg, basePoint);
// 2. Sample Current Frame I(x + p) — Bayer-averaged luminance
vec2 currentValPoint = baseUV + (currentFlow / planeDims);
float I = getLuma(trgImg, currentValPoint);
// 2. Sample Current Frame I(x + p) in plane coordinates
vec2 currentValPoint = basePoint + currentFlow;
float I = sampleGreenProxy(trgImg, currentValPoint);
// 3. Compute Gradient of I at (x + p) using plane-pixel steps
// One plane pixel = one 2×2 Bayer block
vec2 dX = vec2(1.0 / planeDims.x, 0.0);
vec2 dY = vec2(0.0, 1.0 / planeDims.y);
vec2 dX = vec2(1.0, 0.0);
vec2 dY = vec2(0.0, 1.0);
float I_x = (getLuma(trgImg, currentValPoint + dX) - getLuma(trgImg, currentValPoint - dX)) * 0.5;
float I_y = (getLuma(trgImg, currentValPoint + dY) - getLuma(trgImg, currentValPoint - dY)) * 0.5;
float I_x = (sampleGreenProxy(trgImg, currentValPoint + dX) - sampleGreenProxy(trgImg, currentValPoint - dX)) * 0.5;
float I_y = (sampleGreenProxy(trgImg, currentValPoint + dY) - sampleGreenProxy(trgImg, currentValPoint - dY)) * 0.5;
// 4. Temporal Derivative / Error
// It = I(x+p) - T(x)
@@ -0,0 +1,150 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(push_constant, scalar) uniform PushConstants {
uint width;
uint height;
uint planeWidth;
uint planeHeight;
uint sensorWidth;
uint sensorHeight;
float scale;
float blackLevel[4];
float whiteLevel;
float wbGains[4];
uint isFirstFrame;
uint outputChannel;
uint cfaPattern;
uint planeIndex;
uint tileX;
uint tileY;
uint tileW;
uint tileH;
uint bufferStride;
uint gridW;
uint gridH;
uint tileSize;
float noiseAlpha;
float noiseBeta;
float baseNoise;
float frameWeight;
} pc;
layout(set = 0, binding = 0) uniform sampler2D inputRawSampler;
layout(set = 0, binding = 1, scalar) buffer AlignBuffer { vec2 offsets[]; } alignBuffer;
layout(set = 0, binding = 2, scalar) buffer KernelParams { vec4 data[]; } kernelParams;
layout(set = 0, binding = 3, scalar) buffer RobustnessBuffer { float data[]; } outRobustness;
layout(set = 0, binding = 4, scalar) buffer ColorAccum { uvec2 data[]; } colorAccum;
layout(set = 0, binding = 5) uniform sampler2D uLensShadingMap;
const float kAccumScale = 2048.0;
float cubicWeight(float x) {
x = abs(x);
if (x >= 2.0) return 0.0;
if (x < 1.0) return 1.0 - 2.5 * x * x + 1.5 * x * x * x;
return 2.0 - 4.0 * x + 2.5 * x * x - 0.5 * x * x * x;
}
vec3 getKernelMatrix(vec4 params) {
float k1 = params.x;
float k2 = params.y;
float c2 = params.z;
float s2 = params.w;
float k_sum = k1 + k2;
float k_diff = k1 - k2;
return vec3(0.5 * (k_sum + k_diff * c2),
0.5 * k_diff * s2,
0.5 * (k_sum - k_diff * c2));
}
vec2 sampleFlow(vec2 planeCoord) {
vec2 gCoord = planeCoord / float(pc.tileSize) - 0.5;
ivec2 g0 = ivec2(floor(gCoord));
vec2 gf = gCoord - vec2(g0);
ivec2 g1 = g0 + 1;
g0 = clamp(g0, ivec2(0), ivec2(int(pc.gridW) - 1, int(pc.gridH) - 1));
g1 = clamp(g1, ivec2(0), ivec2(int(pc.gridW) - 1, int(pc.gridH) - 1));
vec2 f00 = alignBuffer.offsets[g0.y * pc.gridW + g0.x];
vec2 f10 = alignBuffer.offsets[g0.y * pc.gridW + g1.x];
vec2 f01 = alignBuffer.offsets[g1.y * pc.gridW + g0.x];
vec2 f11 = alignBuffer.offsets[g1.y * pc.gridW + g1.x];
return mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y);
}
bool sampleMatchesTarget(ivec2 pos, out int lscIdx) {
int phase = (pos.y & 1) * 2 + (pos.x & 1);
lscIdx = -1;
if (pc.cfaPattern == 0u) {
if (pc.outputChannel == 0u && phase == 0) { lscIdx = 0; return true; }
if (pc.outputChannel == 2u && phase == 3) { lscIdx = 3; return true; }
} else if (pc.cfaPattern == 1u) {
if (pc.outputChannel == 0u && phase == 1) { lscIdx = 0; return true; }
if (pc.outputChannel == 2u && phase == 2) { lscIdx = 3; return true; }
} else if (pc.cfaPattern == 2u) {
if (pc.outputChannel == 0u && phase == 2) { lscIdx = 0; return true; }
if (pc.outputChannel == 2u && phase == 1) { lscIdx = 3; return true; }
} else {
if (pc.outputChannel == 0u && phase == 3) { lscIdx = 0; return true; }
if (pc.outputChannel == 2u && phase == 0) { lscIdx = 3; return true; }
}
return false;
}
void main() {
uint x = gl_GlobalInvocationID.x;
uint y = gl_GlobalInvocationID.y;
if (x >= pc.sensorWidth || y >= pc.sensorHeight) return;
ivec2 samplePos = ivec2(x, y);
int lscIdx = -1;
if (!sampleMatchesTarget(samplePos, lscIdx)) return;
vec2 planePos = vec2(samplePos) * 0.5;
vec2 flow = (pc.isFirstFrame == 0u) ? sampleFlow(planePos) : vec2(0.0);
vec2 refPos = vec2(samplePos) - flow * 2.0;
vec2 outCenter = refPos * pc.scale;
ivec2 base = ivec2(floor(outCenter));
float raw = texelFetch(inputRawSampler, samplePos, 0).r;
int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1);
float val = max(0.0, raw * 65535.0 - pc.blackLevel[samplePhase]);
vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight);
vec4 lscGains = texture(uLensShadingMap, lscUV);
float lscGain = (lscIdx == 0) ? lscGains.r : lscGains.a;
val = (val * lscGain) / 65535.0;
int rX = clamp(samplePos.x / 2, 0, int(pc.planeWidth) - 1);
int rY = clamp(samplePos.y / 2, 0, int(pc.planeHeight) - 1);
float robustness = (pc.isFirstFrame == 0u) ? outRobustness.data[rY * int(pc.planeWidth) + rX] : 1.0;
vec2 planeRef = clamp(refPos * 0.5, vec2(0.0), vec2(float(pc.planeWidth - 1u), float(pc.planeHeight - 1u)));
ivec2 planeIdx = ivec2(round(planeRef));
vec3 OmegaInv = getKernelMatrix(kernelParams.data[planeIdx.y * int(pc.planeWidth) + planeIdx.x]);
for (int oy = -1; oy <= 2; ++oy) {
for (int ox = -1; ox <= 2; ++ox) {
ivec2 outPos = base + ivec2(ox, oy);
if (outPos.x < int(pc.tileX) || outPos.y < int(pc.tileY) ||
outPos.x >= int(pc.tileX + pc.tileW) || outPos.y >= int(pc.tileY + pc.tileH) ||
outPos.x < 0 || outPos.y < 0 || outPos.x >= int(pc.width) || outPos.y >= int(pc.height)) continue;
vec2 d_hr = vec2(outPos) - outCenter;
float reconWeight = cubicWeight(d_hr.x) * cubicWeight(d_hr.y);
if (reconWeight <= 0.0) continue;
vec2 d_raw = (vec2(outPos) / pc.scale) - refPos;
vec2 d = d_raw * 0.5;
float mahalanobis = OmegaInv.x * d.x * d.x + 2.0 * OmegaInv.y * d.x * d.y + OmegaInv.z * d.y * d.y;
float w = exp(-0.5 * max(mahalanobis, 0.0)) * reconWeight * robustness * pc.frameWeight;
if (w <= 0.0) continue;
uint weightFixed = uint(clamp(w * kAccumScale, 0.0, 4294967040.0));
uint sumFixed = uint(clamp(val * w * 65535.0 * kAccumScale, 0.0, 4294967040.0));
uint idx = uint(outPos.y - int(pc.tileY)) * pc.bufferStride + uint(outPos.x - int(pc.tileX));
atomicAdd(colorAccum.data[idx].x, sumFixed);
atomicAdd(colorAccum.data[idx].y, weightFixed);
}
}
}
@@ -0,0 +1,202 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(push_constant, scalar) uniform PushConstants {
uint width;
uint height;
uint planeWidth;
uint planeHeight;
uint sensorWidth;
uint sensorHeight;
float scale;
float blackLevel[4];
float whiteLevel;
float wbGains[4];
uint isFirstFrame;
uint outputChannel;
uint cfaPattern;
uint planeIndex;
uint tileX;
uint tileY;
uint tileW;
uint tileH;
uint bufferStride;
uint gridW;
uint gridH;
uint tileSize;
float noiseAlpha;
float noiseBeta;
float baseNoise;
float frameWeight;
} pc;
layout(set = 0, binding = 0) uniform sampler2D inputRawSampler;
layout(set = 0, binding = 1, scalar) buffer AlignBuffer { vec2 offsets[]; } alignBuffer;
layout(set = 0, binding = 2, scalar) buffer KernelParams { vec4 data[]; } kernelParams;
layout(set = 0, binding = 3, scalar) buffer RobustnessBuffer { float data[]; } outRobustness;
layout(set = 0, binding = 4, scalar) buffer GreenPhase0 { uvec2 data[]; } greenPhase0;
layout(set = 0, binding = 5, scalar) buffer GreenPhase1 { uvec2 data[]; } greenPhase1;
layout(set = 0, binding = 6) uniform sampler2D uLensShadingMap;
layout(set = 0, binding = 7, scalar) buffer LocalTileMask { float data[]; } localTileMask;
const float kAccumScale = 2048.0;
float cubicWeight(float x) {
x = abs(x);
if (x >= 2.0) return 0.0;
if (x < 1.0) {
return 1.0 - 2.5 * x * x + 1.5 * x * x * x;
}
return 2.0 - 4.0 * x + 2.5 * x * x - 0.5 * x * x * x;
}
vec3 getKernelMatrix(vec4 params) {
float k1 = params.x;
float k2 = params.y;
float c2 = params.z;
float s2 = params.w;
float k_sum = k1 + k2;
float k_diff = k1 - k2;
float a = 0.5 * (k_sum + k_diff * c2);
float c_val = 0.5 * (k_sum - k_diff * c2);
float b = 0.5 * k_diff * s2;
return vec3(a, b, c_val);
}
vec2 sampleFlow(vec2 planeCoord) {
vec2 gCoord = planeCoord / float(pc.tileSize) - 0.5;
ivec2 g0 = ivec2(floor(gCoord));
vec2 gf = gCoord - vec2(g0);
ivec2 g1 = g0 + 1;
g0 = clamp(g0, ivec2(0), ivec2(int(pc.gridW) - 1, int(pc.gridH) - 1));
g1 = clamp(g1, ivec2(0), ivec2(int(pc.gridW) - 1, int(pc.gridH) - 1));
vec2 f00 = alignBuffer.offsets[g0.y * pc.gridW + g0.x];
vec2 f10 = alignBuffer.offsets[g0.y * pc.gridW + g1.x];
vec2 f01 = alignBuffer.offsets[g1.y * pc.gridW + g0.x];
vec2 f11 = alignBuffer.offsets[g1.y * pc.gridW + g1.x];
return mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y);
}
float sampleLocalTileWeight(vec2 refPos) {
vec2 planeRef = refPos * 0.5;
uint tilesX = (pc.planeWidth + 15u) / 16u;
uint tileX = min(uint(clamp(floor(planeRef.x / 16.0), 0.0, float(max(tilesX, 1u) - 1u))), max(tilesX, 1u) - 1u);
uint tilesY = (pc.planeHeight + 15u) / 16u;
uint tileY = min(uint(clamp(floor(planeRef.y / 16.0), 0.0, float(max(tilesY, 1u) - 1u))), max(tilesY, 1u) - 1u);
return clamp(localTileMask.data[tileY * tilesX + tileX], 0.0, 1.0);
}
int getGreenFamily(int cfaPattern, ivec2 samplePos, out int lscIdx) {
int phase = (samplePos.y & 1) * 2 + (samplePos.x & 1);
lscIdx = -1;
if (cfaPattern == 0) { // RGGB
if (phase == 1) { lscIdx = 1; return 0; }
if (phase == 2) { lscIdx = 2; return 1; }
} else if (cfaPattern == 1) { // GRBG
if (phase == 0) { lscIdx = 1; return 0; }
if (phase == 3) { lscIdx = 2; return 1; }
} else if (cfaPattern == 2) { // GBRG
if (phase == 3) { lscIdx = 1; return 0; }
if (phase == 0) { lscIdx = 2; return 1; }
} else { // BGGR
if (phase == 2) { lscIdx = 1; return 0; }
if (phase == 1) { lscIdx = 2; return 1; }
}
return -1;
}
void splatSample(int phaseIndex, vec2 outCenter, vec2 refPos, float val, float robustness) {
vec2 kernelPlanePos = clamp(refPos * 0.5, vec2(0.0), vec2(float(pc.planeWidth - 1u), float(pc.planeHeight - 1u)));
ivec2 planeIdx = ivec2(round(kernelPlanePos));
vec4 kParams = kernelParams.data[planeIdx.y * int(pc.planeWidth) + planeIdx.x];
vec3 OmegaInv = getKernelMatrix(kParams);
ivec2 base = ivec2(floor(outCenter));
for (int oy = -1; oy <= 2; ++oy) {
for (int ox = -1; ox <= 2; ++ox) {
ivec2 outPos = base + ivec2(ox, oy);
if (outPos.x < int(pc.tileX) || outPos.y < int(pc.tileY) ||
outPos.x >= int(pc.tileX + pc.tileW) ||
outPos.y >= int(pc.tileY + pc.tileH) ||
outPos.x < 0 || outPos.y < 0 ||
outPos.x >= int(pc.width) || outPos.y >= int(pc.height)) {
continue;
}
vec2 d_hr = vec2(outPos) - outCenter;
float reconWeight = cubicWeight(d_hr.x) * cubicWeight(d_hr.y);
if (reconWeight <= 0.0) continue;
vec2 d_raw = (vec2(outPos) / pc.scale) - refPos;
vec2 d = d_raw * 0.5;
float mahalanobis = OmegaInv.x * d.x * d.x +
(OmegaInv.y * d.x * d.y) * 2.0 +
OmegaInv.z * d.y * d.y;
float w = exp(-0.5 * max(mahalanobis, 0.0)) * reconWeight *
robustness * pc.frameWeight;
if (w <= 0.0) continue;
uint weightFixed = uint(clamp(w * kAccumScale, 0.0, 4294967040.0));
uint sumFixed = uint(clamp(val * w * 65535.0 * kAccumScale, 0.0, 4294967040.0));
uint localX = uint(outPos.x - int(pc.tileX));
uint localY = uint(outPos.y - int(pc.tileY));
uint idx = localY * pc.bufferStride + localX;
if (phaseIndex == 0) {
atomicAdd(greenPhase0.data[idx].x, sumFixed);
atomicAdd(greenPhase0.data[idx].y, weightFixed);
} else {
atomicAdd(greenPhase1.data[idx].x, sumFixed);
atomicAdd(greenPhase1.data[idx].y, weightFixed);
}
}
}
}
void main() {
uint x = gl_GlobalInvocationID.x;
uint y = gl_GlobalInvocationID.y;
if (x >= pc.sensorWidth || y >= pc.sensorHeight) return;
ivec2 samplePos = ivec2(x, y);
int lscIdx = -1;
int family = getGreenFamily(int(pc.cfaPattern), samplePos, lscIdx);
if (family < 0) return;
vec2 planePos = vec2(samplePos) * 0.5;
vec2 flow = vec2(0.0);
if (pc.isFirstFrame == 0u) {
flow = sampleFlow(planePos);
}
vec2 refPos = vec2(samplePos) - flow * 2.0;
vec2 outCenter = refPos * pc.scale;
float raw = texelFetch(inputRawSampler, samplePos, 0).r;
int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1);
float val = max(0.0, raw * 65535.0 - pc.blackLevel[samplePhase]);
vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight);
vec4 lscGains = texture(uLensShadingMap, lscUV);
float lscGain = (lscIdx == 1) ? lscGains.g : lscGains.b;
val = (val * lscGain) / 65535.0;
int rX = clamp(samplePos.x / 2, 0, int(pc.planeWidth) - 1);
int rY = clamp(samplePos.y / 2, 0, int(pc.planeHeight) - 1);
float robustness = 1.0;
if (pc.isFirstFrame == 0u) {
robustness = outRobustness.data[rY * int(pc.planeWidth) + rX];
}
robustness *= sampleLocalTileWeight(refPos);
splatSample(family, outCenter, refPos, val, robustness);
}
+33
View File
@@ -24,6 +24,16 @@ layout(push_constant, scalar) uniform PushConstants {
uint bufferStride;
} pc;
vec4 readAccum(int x, int y) {
x = clamp(x, 0, int(pc.tileW) - 1);
y = clamp(y, 0, int(pc.tileH) - 1);
return accumulator.data[uint(y) * pc.bufferStride + uint(x)];
}
float luminance(vec3 color) {
return dot(color, vec3(0.299, 0.587, 0.114));
}
void main() {
uint X = gl_GlobalInvocationID.x;
uint Y = gl_GlobalInvocationID.y;
@@ -49,6 +59,29 @@ void main() {
if (any(isnan(color)) || any(isinf(color))) {
color = vec3(0.0);
}
// Gentle luma-only detail recovery, gated by confidence and local contrast.
if (accum.a > 0.75) {
vec3 left = readAccum(int(localX) - 1, int(localY)).rgb /
max(readAccum(int(localX) - 1, int(localY)).a, 0.001);
vec3 right = readAccum(int(localX) + 1, int(localY)).rgb /
max(readAccum(int(localX) + 1, int(localY)).a, 0.001);
vec3 up = readAccum(int(localX), int(localY) - 1).rgb /
max(readAccum(int(localX), int(localY) - 1).a, 0.001);
vec3 down = readAccum(int(localX), int(localY) + 1).rgb /
max(readAccum(int(localX), int(localY) + 1).a, 0.001);
float centerY = luminance(color);
float neighborY = 0.25 * (luminance(left) + luminance(right) +
luminance(up) + luminance(down));
float detail = centerY - neighborY;
float localContrast =
abs(detail) / max(centerY + neighborY + 1e-4, 1e-4);
float sharpenAmount =
0.10 * smoothstep(0.02, 0.10, localContrast);
color = max(color + detail * sharpenAmount, vec3(0.0));
}
color = clamp(color, 0.0, 1.0);
uint r = uint(clamp(color.r * 255.0, 0.0, 255.0));
@@ -0,0 +1,59 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
#extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0, scalar) buffer OutputBuffer { uint16_t data[]; } outputBuffer;
layout(binding = 1, scalar) buffer ColorAccum { uvec2 data[]; } colorAccum;
layout(push_constant, scalar) uniform PushConstants {
uint width;
uint height;
uint planeWidth;
uint planeHeight;
uint sensorWidth;
uint sensorHeight;
float scale;
float blackLevel[4];
float whiteLevel;
float wbGains[4];
uint isFirstFrame;
uint outputChannel;
uint cfaPattern;
uint planeIndex;
uint tileX;
uint tileY;
uint tileW;
uint tileH;
uint bufferStride;
uint gridW;
uint gridH;
uint tileSize;
float noiseAlpha;
float noiseBeta;
float baseNoise;
float frameWeight;
} pc;
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
uint outX = pc.tileX + tx;
uint outY = pc.tileY + ty;
if (tx >= pc.tileW || ty >= pc.tileH) return;
if (outX >= pc.width || outY >= pc.height) return;
uvec2 accum = colorAccum.data[ty * pc.bufferStride + tx];
float resLinear = 0.0;
if (accum.y > 0u) {
float val = float(accum.x) / max(float(accum.y), 1.0) / 65535.0;
float gain = (pc.planeIndex == 0u) ? pc.wbGains[0] : pc.wbGains[3];
float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25;
resLinear = (val * 65535.0) / (pc.whiteLevel - bl_avg) * gain;
}
uint outIndex = (outY * pc.width + outX) * 3 + pc.planeIndex;
outputBuffer.data[outIndex] = uint16_t(clamp(resLinear * 65535.0, 0.0, 65535.0));
}
@@ -0,0 +1,110 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
#extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0, scalar) buffer OutputBuffer {
uint16_t data[];
} outputBuffer;
layout(binding = 1, scalar) buffer GreenPhase0 {
uvec2 data[];
} greenPhase0;
layout(binding = 2, scalar) buffer GreenPhase1 {
uvec2 data[];
} greenPhase1;
layout(push_constant, scalar) uniform PushConstants {
uint width;
uint height;
uint planeWidth;
uint planeHeight;
uint sensorWidth;
uint sensorHeight;
float scale;
float blackLevel[4];
float whiteLevel;
float wbGains[4];
uint isFirstFrame;
uint outputChannel;
uint cfaPattern;
uint planeIndex;
uint tileX;
uint tileY;
uint tileW;
uint tileH;
uint bufferStride;
uint gridW;
uint gridH;
uint tileSize;
float noiseAlpha;
float noiseBeta;
float baseNoise;
float frameWeight;
} pc;
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
uint outX = pc.tileX + tx;
uint outY = pc.tileY + ty;
if (tx >= pc.tileW || ty >= pc.tileH) return;
if (outX >= pc.width || outY >= pc.height) return;
uint idx = ty * pc.bufferStride + tx;
uvec2 p0 = greenPhase0.data[idx];
uvec2 p1 = greenPhase1.data[idx];
float weight0 = float(p0.y);
float weight1 = float(p1.y);
float resLinear = 0.0;
if (weight0 + weight1 > 0.0) {
bool has0 = weight0 > 0.0;
bool has1 = weight1 > 0.0;
float g0 = has0 ? (float(p0.x) / max(weight0, 1e-6) / 65535.0) : 0.0;
float g1 = has1 ? (float(p1.x) / max(weight1, 1e-6) / 65535.0) : 0.0;
float blend0 = weight0;
float blend1 = weight1;
float val = 0.0;
if (has0 && has1) {
float diff = abs(g0 - g1);
float consistency = 1.0 - smoothstep(0.010, 0.050, diff);
float dominant0 = step(blend1, blend0);
float dominant1 = 1.0 - dominant0;
float avgVal = (g0 * blend0 + g1 * blend1) / max(blend0 + blend1, 1e-6);
float dominantVal = g0 * dominant0 + g1 * dominant1;
val = mix(dominantVal, avgVal, consistency);
float inconsistency = 1.0 - consistency;
uint baseIndex = (outY * pc.width + outX) * 3;
float rLinear = float(outputBuffer.data[baseIndex + 0]) / 65535.0;
float bLinear = float(outputBuffer.data[baseIndex + 2]) / 65535.0;
float rbMean = 0.5 * (rLinear + bLinear);
float rbMax = max(rLinear, bLinear);
float greenCeiling = max(rbMean * 1.35 + 0.015, rbMax * 1.18 + 0.010);
val = mix(val, min(val, greenCeiling), smoothstep(0.20, 0.75, inconsistency));
} else if (has0) {
val = g0;
} else {
val = g1;
}
float gain = (pc.wbGains[1] + pc.wbGains[2]) * 0.5;
float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25;
resLinear = (val * 65535.0) / (pc.whiteLevel - bl_avg) * gain;
}
uint outIndex = (outY * pc.width + outX) * 3 + 1;
outputBuffer.data[outIndex] = uint16_t(clamp(resLinear * 65535.0, 0.0, 65535.0));
}
+28 -8
View File
@@ -48,6 +48,19 @@ layout(push_constant, scalar) uniform PushConstants {
float baseNoise;
} pc;
vec2 readAccum(int x, int y) {
x = clamp(x, 0, int(pc.tileW) - 1);
y = clamp(y, 0, int(pc.tileH) - 1);
uint idx = uint(y) * pc.bufferStride + uint(x);
return accumulator.data[idx];
}
float accumToLinear(vec2 accum, float gain, float whiteRangeInv) {
if (accum.y <= 0.0) return 0.0;
float val = accum.x / accum.y;
return (val * 65535.0) * whiteRangeInv * gain;
}
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
@@ -78,14 +91,21 @@ void main() {
gain = pc.wbGains[3];
}
float resLinear = 0.0;
if (accum.y > 0) {
float val = accum.x / accum.y; // Already [0, 1] net signal per sample
// Scale and apply WB gain
// Net signal range is [0, (white - black)]
// We want to map it back to [0, 1.0] for the processor
float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25;
resLinear = (val * 65535.0) / (pc.whiteLevel - bl_avg) * gain;
float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25;
float whiteRangeInv = 1.0 / max(pc.whiteLevel - bl_avg, 1.0);
float resLinear = accumToLinear(accum, gain, whiteRangeInv);
// Conservative detail recovery on green only, gated by accumulated confidence.
if (pc.planeIndex == 1u && accum.y > 0.65) {
float left = accumToLinear(readAccum(int(tx) - 1, int(ty)), gain, whiteRangeInv);
float right = accumToLinear(readAccum(int(tx) + 1, int(ty)), gain, whiteRangeInv);
float up = accumToLinear(readAccum(int(tx), int(ty) - 1), gain, whiteRangeInv);
float down = accumToLinear(readAccum(int(tx), int(ty) + 1), gain, whiteRangeInv);
float neighborAvg = 0.25 * (left + right + up + down);
float detail = resLinear - neighborAvg;
float localContrast = abs(detail) / max(resLinear + neighborAvg + 1e-4, 1e-4);
float sharpenAmount = 0.18 * smoothstep(0.02, 0.12, localContrast);
resLinear = max(resLinear + detail * sharpenAmount, 0.0);
}
// Write Interleaved RGB (R, G, B, R, G, B...)
@@ -46,21 +46,37 @@ layout(push_constant, scalar) uniform PushConstants {
float baseNoise;
} pc;
ivec2 getPlaneOffsets(uint planeIdx, uint cfa) {
const int offsets[4][4][2] = int[4][4][2](
int[4][2](int[2](0,0), int[2](1,0), int[2](0,1), int[2](1,1)), // RGGB
int[4][2](int[2](1,0), int[2](0,0), int[2](1,1), int[2](0,1)), // GRBG
int[4][2](int[2](0,1), int[2](1,1), int[2](0,0), int[2](1,0)), // GBRG
int[4][2](int[2](1,1), int[2](0,1), int[2](1,0), int[2](0,0)) // BGGR
);
return ivec2(offsets[cfa][planeIdx][0], offsets[cfa][planeIdx][1]);
float getGreenBlock(ivec2 planeCoord) {
int sx = clamp(planeCoord.x * 2, 0, int(pc.sensorWidth) - 2);
int sy = clamp(planeCoord.y * 2, 0, int(pc.sensorHeight) - 2);
float g1 = 0.0;
float g2 = 0.0;
if (pc.cfaPattern == 0u || pc.cfaPattern == 3u) {
g1 = texelFetch(inputRawSampler, ivec2(sx + 1, sy), 0).r;
g2 = texelFetch(inputRawSampler, ivec2(sx, sy + 1), 0).r;
} else {
g1 = texelFetch(inputRawSampler, ivec2(sx, sy), 0).r;
g2 = texelFetch(inputRawSampler, ivec2(sx + 1, sy + 1), 0).r;
}
return 0.5 * (g1 + g2);
}
// Convert Bayer to Grayscale (Luma approximation)
// We use a simple average of the 2x2 block for the half-res structure tensor
// This runs on half-res (plane resolution), so one thread per 2x2 Bayer block output?
// No, the paper says "compute structure tensor on half-resolution luminance".
// Let's assume this shader runs on the plane resolution (W/2 x H/2).
float sampleGreenProxy(vec2 planePos) {
vec2 clampedPos = clamp(
planePos,
vec2(0.0),
vec2(float(pc.planeWidth - 1u), float(pc.planeHeight - 1u)));
ivec2 p0 = ivec2(floor(clampedPos));
ivec2 p1 = min(p0 + ivec2(1), ivec2(int(pc.planeWidth) - 1, int(pc.planeHeight) - 1));
vec2 f = clampedPos - vec2(p0);
float g00 = getGreenBlock(p0);
float g10 = getGreenBlock(ivec2(p1.x, p0.y));
float g01 = getGreenBlock(ivec2(p0.x, p1.y));
float g11 = getGreenBlock(p1);
return mix(mix(g00, g10, f.x), mix(g01, g11, f.x), f.y);
}
void main() {
uint tx = gl_GlobalInvocationID.x;
@@ -73,11 +89,8 @@ void main() {
if (planeX >= pc.planeWidth || planeY >= pc.planeHeight) return;
vec2 pixelSize = vec2(1.0) / vec2(pc.sensorWidth, pc.sensorHeight);
// 1. Compute Gradients Ix, Iy on Half-Resolution Luma
// Luma is defined as average of the 2x2 Bayer block (simplification for robustness).
// Gradient is computed via Central Difference on this Luma field.
// 1. Compute Gradients on the green proxy rather than averaging the full
// Bayer quad. This keeps more line/text energy for anisotropic kernels.
float sIxIx = 0.0;
float sIyIy = 0.0;
@@ -89,18 +102,10 @@ void main() {
int nx = clamp(int(planeX) + dx, 0, int(pc.planeWidth) - 1);
int ny = clamp(int(planeY) + dy, 0, int(pc.planeHeight) - 1);
// Compute Luma and Gradient at (nx, ny) on the fly
// Ideally this should be a separate pass, but we do it here to save BW.
// Helper to fetch Luma at (cx, cy)
#define FETCH_LUMA(cx, cy) \
dot(textureGather(inputRawSampler, (vec2(cx, cy) * 2.0 + 1.0) * pixelSize, 0), vec4(0.25))
// Gradient at (nx, ny)
float xp = FETCH_LUMA(clamp(nx + 1, 0, int(pc.planeWidth)-1), ny);
float xm = FETCH_LUMA(clamp(nx - 1, 0, int(pc.planeWidth)-1), ny);
float yp = FETCH_LUMA(nx, clamp(ny + 1, 0, int(pc.planeHeight)-1));
float ym = FETCH_LUMA(nx, clamp(ny - 1, 0, int(pc.planeHeight)-1));
float xp = sampleGreenProxy(vec2(clamp(nx + 1, 0, int(pc.planeWidth)-1), ny));
float xm = sampleGreenProxy(vec2(clamp(nx - 1, 0, int(pc.planeWidth)-1), ny));
float yp = sampleGreenProxy(vec2(nx, clamp(ny + 1, 0, int(pc.planeHeight)-1)));
float ym = sampleGreenProxy(vec2(nx, clamp(ny - 1, 0, int(pc.planeHeight)-1)));
float Ix = (xp - xm) * 0.5;
float Iy = (yp - ym) * 0.5;
+48 -29
View File
@@ -70,6 +70,22 @@ float getGreen(sampler2D tex, int px, int py) {
return (g1 + g2) * 0.5;
}
float sampleTargetGreen(vec2 planePos) {
vec2 clampedPos = clamp(
planePos,
vec2(0.0),
vec2(float(pc.planeWidth - 1u), float(pc.planeHeight - 1u)));
ivec2 p0 = ivec2(floor(clampedPos));
ivec2 p1 = min(p0 + ivec2(1), ivec2(int(pc.planeWidth) - 1, int(pc.planeHeight) - 1));
vec2 f = clampedPos - vec2(p0);
float g00 = getGreen(trgImg, p0.x, p0.y);
float g10 = getGreen(trgImg, p1.x, p0.y);
float g01 = getGreen(trgImg, p0.x, p1.y);
float g11 = getGreen(trgImg, p1.x, p1.y);
return mix(mix(g00, g10, f.x), mix(g01, g11, f.x), f.y);
}
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
@@ -149,7 +165,18 @@ void main() {
// Final sigma² = max(measured, noise_model) — lower-bound truncation (Paper §6.4)
float sigma2 = max(sigma2_spatial, sigma2_noise);
float gradX = 0.5 * (getGreen(refImg, int(planeX) + 1, int(planeY)) -
getGreen(refImg, int(planeX) - 1, int(planeY)));
float gradY = 0.5 * (getGreen(refImg, int(planeX), int(planeY) + 1) -
getGreen(refImg, int(planeX), int(planeY) - 1));
float gradEnergy = gradX * gradX + gradY * gradY;
float edgeStrength = sqrt(max(gradEnergy / max(sigma2, 1e-8), 0.0));
float edgeRelax = smoothstep(1.2, 5.0, edgeStrength);
float minRobustness = 1.0;
float sumRobustness = 0.0;
float centerRobustness = 1.0;
float weightSum = 0.0;
// Morphological Min Filter (Radius 1 = 3×3 — less aggressive than 5×5)
for (int dy = -1; dy <= 1; dy++) {
@@ -160,26 +187,8 @@ void main() {
// Use green channel for comparison
float greenRef = getGreen(refImg, nx, ny);
// Target: use manual bilinear sampling of Green pixels.
// Our flow vector 'flow' is in the half-res "plane" scale.
// So trgPlane is in half-res coordinates (0 to planeWidth-1).
vec2 trgPlane = vec2(nx, ny) + flow;
// Bilinear weights for half-res sampling
vec2 trgPlaneFloor = floor(trgPlane);
vec2 trgPlaneFrac = trgPlane - trgPlaneFloor;
int txi = int(trgPlaneFloor.x);
int tyi = int(trgPlaneFloor.y);
// Sample 4 surrounding Green pixels using our helper function (which acts on plane coords)
float g00 = getGreen(trgImg, txi, tyi);
float g10 = getGreen(trgImg, txi + 1, tyi);
float g01 = getGreen(trgImg, txi, tyi + 1);
float g11 = getGreen(trgImg, txi + 1, tyi + 1);
float greenTrg = mix(mix(g00, g10, trgPlaneFrac.x),
mix(g01, g11, trgPlaneFrac.x),
trgPlaneFrac.y);
float greenTrg = sampleTargetGreen(trgPlane);
// Squared difference
float diff = greenRef - greenTrg;
@@ -188,30 +197,40 @@ void main() {
float d_ms_sq = diff * diff;
// Wiener shrinkage noise correction (Paper §6.4 & Python Reference)
float d_noise_sq = 2.0 * sigma2;
float sigma2_adapted = sigma2 * mix(1.0, 2.4, edgeRelax);
float d_noise_sq = 2.0 * sigma2_adapted;
float shrink = d_ms_sq / max(d_ms_sq + d_noise_sq, 1e-10);
float d_corrected_sq = d_ms_sq * shrink * shrink; // Multiplied twice per paper
// Python Reference Parameter mapped S and t
// S2 = 12.0 (Relaxed) is used when flow is smooth and reliable (flowRange <= 0.8).
// This relaxation is VITAL: it allows sub-pixel shifted frames to pass the temporal mask
// and accumulate, physically filling in the missing Bayer colors on thin text!
// S1 = 2.0 (Strict) is used when flow is chaotic (flowRange > 0.8) to prevent ghosting.
float S_param = (flowRange > 0.8) ? 2.0 : 12.0;
float t_param = 0.12;
float baseRelax = (flowRange > 0.8) ? 0.0 : 1.0;
float S_param = mix(2.0, 12.0, max(baseRelax, edgeRelax));
float t_param = mix(0.12, 0.04, edgeRelax);
// Robustness calculation: R = S * exp(-d / sigma^2) - t
float exponential = exp(-d_corrected_sq / max(sigma2, 1e-10));
float exponential = exp(-d_corrected_sq / max(sigma2_adapted, 1e-10));
float R = clamp(S_param * exponential - t_param, 0.0, 1.0);
// Apply pre-computed penalties
R *= globalPenalty;
float spatialWeight = (dx == 0 && dy == 0) ? 2.0 : 1.0;
sumRobustness += R * spatialWeight;
weightSum += spatialWeight;
minRobustness = min(minRobustness, R);
if (dx == 0 && dy == 0) {
centerRobustness = R;
}
}
}
// Output
uint outIdx = planeY * pc.planeWidth + planeX;
outRobustness.data[outIdx] = minRobustness;
float avgRobustness = (weightSum > 0.0) ? (sumRobustness / weightSum) : minRobustness;
float minMix = mix(0.22, 0.08, edgeRelax);
float centerMix = mix(0.43, 0.56, edgeRelax);
float avgMix = 1.0 - minMix - centerMix;
float robustness = minMix * minRobustness +
centerMix * centerRobustness +
avgMix * avgRobustness;
outRobustness.data[outIdx] = clamp(robustness, 0.0, 1.0);
}
File diff suppressed because it is too large. Load diff
+35 -1
View File
@@ -63,6 +63,27 @@ private:
VkDescriptorSetLayout robustnessSetLayout = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> robustnessSets; // Per-frame sets
// Green HR scatter/splat path
VkPipelineLayout greenScatterPipelineLayout = VK_NULL_HANDLE;
VkPipeline greenScatterPipeline = VK_NULL_HANDLE;
VkDescriptorSetLayout greenScatterSetLayout = VK_NULL_HANDLE;
VkDescriptorSet greenScatterSet = VK_NULL_HANDLE;
VkPipelineLayout colorScatterPipelineLayout = VK_NULL_HANDLE;
VkPipeline colorScatterPipeline = VK_NULL_HANDLE;
VkDescriptorSetLayout colorScatterSetLayout = VK_NULL_HANDLE;
VkDescriptorSet colorScatterSets[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkDescriptorSetLayout greenNormalizeSetLayout = VK_NULL_HANDLE;
VkPipelineLayout greenNormalizePipelineLayout = VK_NULL_HANDLE;
VkPipeline greenNormalizePipeline = VK_NULL_HANDLE;
VkDescriptorSet greenNormalizeSet = VK_NULL_HANDLE;
VkDescriptorSetLayout colorNormalizeSetLayout = VK_NULL_HANDLE;
VkPipelineLayout colorNormalizePipelineLayout = VK_NULL_HANDLE;
VkPipeline colorNormalizePipeline = VK_NULL_HANDLE;
VkDescriptorSet colorNormalizeSets[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
// Normalization
VkDescriptorSetLayout normalizeSetLayout = VK_NULL_HANDLE;
VkPipelineLayout normalizePipelineLayout = VK_NULL_HANDLE;
@@ -79,6 +100,14 @@ private:
VkBuffer robustnessBuffer = VK_NULL_HANDLE; // Robustness Mask Output
VkDeviceMemory robustnessMemory = VK_NULL_HANDLE;
VkBuffer localTileMaskBuffer = VK_NULL_HANDLE;
VkDeviceMemory localTileMaskMemory = VK_NULL_HANDLE;
VkBuffer greenPhaseAccumBuffers[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkDeviceMemory greenPhaseAccumMemories[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkBuffer rbScatterAccumBuffers[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkDeviceMemory rbScatterAccumMemories[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE};
VkBuffer stagingBuffer = VK_NULL_HANDLE;
VkDeviceMemory stagingMemory = VK_NULL_HANDLE;
@@ -135,7 +164,8 @@ private:
float noiseAlpha; // 112
float noiseBeta; // 116
float baseNoise; // 120
}; // Total size: 124 bytes
float frameWeight; // 124
}; // Total size: 128 bytes
// Metadata storage
float mBlackLevel[4] = {0, 0, 0, 0};
@@ -150,6 +180,10 @@ private:
};
std::vector<FrameData> pendingFrames;
GrayImage buildAlignmentProxy(const FrameData &frame) const;
float calculateFrameScore(const FrameData &frame) const;
void selectReferenceFrame();
void initVulkanResources();
void releaseVulkanResources();
void createPipelines();
+226 -8
View File
@@ -5,6 +5,8 @@
#include "structure_tensor.comp.h"
#include "yuv_to_rgba.comp.h"
#include <android/log.h>
#include <algorithm>
#include <cmath>
#include <sys/resource.h>
#include <unistd.h>
#include <vector>
@@ -17,6 +19,144 @@
} \
} while (0)
namespace {
struct ScalarStats {
float minValue = 0.0f;
float maxValue = 0.0f;
float p50 = 0.0f;
float p90 = 0.0f;
};
struct LocalReliabilityMap {
std::vector<float> tileWeights;
float edgeGoodFraction = 0.0f;
float textGoodFraction = 0.0f;
};
inline float clamp01(float v) { return std::clamp(v, 0.0f, 1.0f); }
inline ScalarStats computeScalarStats(const std::vector<float> &values) {
ScalarStats stats;
if (values.empty())
return stats;
std::vector<float> sorted = values;
std::sort(sorted.begin(), sorted.end());
auto percentile = [&](float q) -> float {
size_t idx =
std::min(sorted.size() - 1, (size_t)std::floor(q * (sorted.size() - 1)));
return sorted[idx];
};
stats.minValue = sorted.front();
stats.maxValue = sorted.back();
stats.p50 = percentile(0.50f);
stats.p90 = percentile(0.90f);
return stats;
}
LocalReliabilityMap buildLocalReliabilityMap(const GrayImage &reference,
const std::vector<float> &errorMap,
uint32_t gridW, uint32_t gridH) {
LocalReliabilityMap result;
if (reference.data.empty() || errorMap.empty() || gridW == 0 || gridH == 0)
return result;
result.tileWeights.resize((size_t)gridW * gridH, 1.0f);
std::vector<float> detailScores;
detailScores.reserve((size_t)gridW * gridH);
uint32_t tileW = (reference.width + gridW - 1) / gridW;
uint32_t tileH = (reference.height + gridH - 1) / gridH;
for (uint32_t gy = 0; gy < gridH; ++gy) {
for (uint32_t gx = 0; gx < gridW; ++gx) {
uint32_t x0 = gx * tileW;
uint32_t y0 = gy * tileH;
uint32_t x1 = std::min<uint32_t>(x0 + tileW, reference.width);
uint32_t y1 = std::min<uint32_t>(y0 + tileH, reference.height);
double detailSum = 0.0;
size_t count = 0;
for (uint32_t y = y0; y < y1; ++y) {
for (uint32_t x = x0; x < x1; ++x) {
size_t idx = (size_t)y * reference.width + x;
float center = (float)reference.data[idx];
float xp = (float)reference
.data[(size_t)y * reference.width +
std::min<uint32_t>(x + 1, reference.width - 1)];
float xm = (float)reference
.data[(size_t)y * reference.width + (x > 0 ? x - 1 : 0)];
float yp = (float)reference.data[(size_t)std::min<uint32_t>(
y + 1, reference.height - 1) *
reference.width +
x];
float ym = (float)reference
.data[(size_t)(y > 0 ? y - 1 : 0) * reference.width + x];
detailSum += std::abs(xp - xm) + std::abs(yp - ym) +
0.5 * std::abs(4.0f * center - xp - xm - yp - ym);
++count;
}
}
float detail = (count > 0) ? (float)(detailSum / (double)count) : 0.0f;
detailScores.push_back(detail);
}
}
ScalarStats detailStats = computeScalarStats(detailScores);
float edgeThreshold = std::max(detailStats.p50, detailStats.p90 * 0.65f);
float textThreshold = std::max(detailStats.p90, detailStats.maxValue * 0.70f);
size_t edgeCount = 0;
size_t edgeGood = 0;
size_t textCount = 0;
size_t textGood = 0;
for (size_t idx = 0; idx < errorMap.size() && idx < detailScores.size(); ++idx) {
float detail = detailScores[idx];
float err = errorMap[idx];
bool isEdge = detail >= edgeThreshold;
bool isText = detail >= textThreshold;
float errorWeight = clamp01(1.0f - std::max(0.0f, err - 10.0f) / 28.0f);
float detailBoost = isText ? 1.0f : (isEdge ? 0.72f : 0.38f);
float tileWeight = clamp01(errorWeight * (0.55f + 0.45f * detailBoost));
if (isText) {
tileWeight = std::max(tileWeight, 0.35f);
++textCount;
if (err < 16.0f)
++textGood;
} else if (isEdge) {
tileWeight = std::max(tileWeight, 0.20f);
++edgeCount;
if (err < 18.0f)
++edgeGood;
}
result.tileWeights[idx] = tileWeight;
}
result.edgeGoodFraction =
(edgeCount > 0) ? (float)edgeGood / (float)edgeCount : 0.0f;
result.textGoodFraction =
(textCount > 0) ? (float)textGood / (float)textCount
: result.edgeGoodFraction;
return result;
}
float computeFrameFusionWeight(const std::vector<float> &errorMap,
float sharpnessRatio,
const LocalReliabilityMap &localMap) {
if (errorMap.empty())
return clamp01(0.35f + 0.65f * sharpnessRatio);
ScalarStats errStats = computeScalarStats(errorMap);
float errorWeight =
clamp01(1.0f - std::max(0.0f, errStats.p90 - 14.0f) / 18.0f);
float sharpnessWeight = clamp01(0.35f + 0.65f * sharpnessRatio);
float localWeight =
clamp01(0.55f * localMap.edgeGoodFraction + 0.45f * localMap.textGoodFraction);
float rescueFloor = 0.18f * localWeight;
return std::max(errorWeight * sharpnessWeight * (0.72f + 0.28f * localWeight),
rescueFloor);
}
} // namespace
VulkanImageStacker::VulkanImageStacker(uint32_t w, uint32_t h, bool sr)
: width(w), height(h), enableSuperRes(sr) {
@@ -230,6 +370,25 @@ void VulkanImageStacker::initVulkanResources() {
VK_CHECK(vkAllocateMemory(device, &mpAlloc, nullptr, &motionPriorMemory));
vkBindBufferMemory(device, motionPriorBuffer, motionPriorMemory, 0);
VkBufferCreateInfo lmInfo{};
lmInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
lmInfo.size = mpSize;
lmInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
lmInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(vkCreateBuffer(device, &lmInfo, nullptr, &localTileMaskBuffer));
VkMemoryRequirements lmReqs;
vkGetBufferMemoryRequirements(device, localTileMaskBuffer, &lmReqs);
VkMemoryAllocateInfo lmAlloc{};
lmAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
lmAlloc.allocationSize = lmReqs.size;
lmAlloc.memoryTypeIndex = vm.findMemoryType(
lmReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
VK_CHECK(vkAllocateMemory(device, &lmAlloc, nullptr, &localTileMaskMemory));
vkBindBufferMemory(device, localTileMaskBuffer, localTileMaskMemory, 0);
// Initialize RGB Intermediate Image
rgbFrame.width = width;
rgbFrame.height = height;
@@ -322,16 +481,23 @@ void VulkanImageStacker::createPipelines(VkSampler sampler) {
motionPriorBinding.descriptorCount = 1;
motionPriorBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding bindingsFinal[5];
VkDescriptorSetLayoutBinding localMaskBinding{};
localMaskBinding.binding = 5;
localMaskBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
localMaskBinding.descriptorCount = 1;
localMaskBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
VkDescriptorSetLayoutBinding bindingsFinal[6];
bindingsFinal[0] = bindings[0];
bindingsFinal[1] = bindings[1];
bindingsFinal[2] = bindings[2];
bindingsFinal[3] = bindings[3];
bindingsFinal[4] = motionPriorBinding;
bindingsFinal[5] = localMaskBinding;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 5;
layoutInfo.bindingCount = 6;
layoutInfo.pBindings = bindingsFinal;
vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr,
&descriptorSetLayout);
@@ -525,7 +691,7 @@ bool VulkanImageStacker::addFrame(AHardwareBuffer *buffer) {
return true;
}
bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore) {
VulkanImage input;
// Use existing conversion if available (from first frame) to compatible with
// immutable sampler
@@ -589,8 +755,9 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
VkDescriptorBufferInfo alignBufferInfo{alignmentBuffer, 0, VK_WHOLE_SIZE};
VkDescriptorBufferInfo kpBufferInfo{kernelParamsBuffer, 0, VK_WHOLE_SIZE};
VkDescriptorBufferInfo mpBufferInfo{motionPriorBuffer, 0, VK_WHOLE_SIZE};
VkDescriptorBufferInfo lmBufferInfo{localTileMaskBuffer, 0, VK_WHOLE_SIZE};
VkWriteDescriptorSet descriptorWrites[5] = {};
VkWriteDescriptorSet descriptorWrites[6] = {};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = accumSets[i];
descriptorWrites[0].dstBinding = 0;
@@ -627,7 +794,14 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
descriptorWrites[4].descriptorCount = 1;
descriptorWrites[4].pBufferInfo = &mpBufferInfo;
vkUpdateDescriptorSets(device, 5, descriptorWrites, 0, nullptr);
descriptorWrites[5].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[5].dstSet = accumSets[i];
descriptorWrites[5].dstBinding = 5;
descriptorWrites[5].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
descriptorWrites[5].descriptorCount = 1;
descriptorWrites[5].pBufferInfo = &lmBufferInfo;
vkUpdateDescriptorSets(device, 6, descriptorWrites, 0, nullptr);
}
if (tensorSets[i] == VK_NULL_HANDLE) {
@@ -669,7 +843,9 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
float offsetX = 0.0f, offsetY = 0.0f;
std::vector<Point> alignmentOffsets;
std::vector<float> alignmentErrorMap;
std::vector<float> localTileMask;
size_t copyCount = 0;
float frameWeight = 1.0f;
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
@@ -703,6 +879,7 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
auto currentPyramid = buildPyramid(currentY.data.data(), width, height, 4);
if (currentIsFirstFrame) {
referencePyramid = std::move(currentPyramid);
localTileMask.assign((size_t)gridW * gridH, 1.0f);
} else {
TileAlignment alignment =
computeTileAlignment(referencePyramid, currentPyramid, 64);
@@ -728,6 +905,15 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
offsetX = sumX / alignmentOffsets.size();
offsetY = sumY / alignmentOffsets.size();
}
LocalReliabilityMap localMap = buildLocalReliabilityMap(
referencePyramid.front(), alignmentErrorMap, gridW, gridH);
localTileMask = std::move(localMap.tileWeights);
float sharpnessRatio = (referenceFrameScore > 0.0f)
? std::min(frameScore / referenceFrameScore, 1.0f)
: 1.0f;
frameWeight = computeFrameFusionWeight(alignmentErrorMap, sharpnessRatio,
localMap);
}
}
TIME_END(cpuAlignment);
@@ -753,9 +939,13 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
pc.gridH = gridH;
pc.noiseAlpha = 0.005f;
pc.noiseBeta = 0.001f;
pc.frameWeight = frameWeight;
LOGI("processFrame: Dispatching. Alpha=%f, Beta=%f, Scale=%f, Grid=%dx%d",
pc.noiseAlpha, pc.noiseBeta, pc.scale, gridW, gridH);
if (!currentIsFirstFrame && pc.frameWeight < 0.12f) {
input.release(device);
isFirstFrame = false;
return true;
}
// --- START PIPELINING SYNC POINT ---
// Wait for the PREVIOUS frame's GPU task to finish before we start recording
@@ -779,6 +969,19 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
memcpy(mpMapPtr, alignmentErrorMap.data(), copyCount * sizeof(float));
vkUnmapMemory(device, motionPriorMemory);
}
}
if (localTileMask.empty()) {
localTileMask.assign((size_t)gridW * gridH, 1.0f);
}
void *lmMapPtr = nullptr;
VkResult resLM =
vkMapMemory(device, localTileMaskMemory, 0, VK_WHOLE_SIZE, 0, &lmMapPtr);
if (resLM == VK_SUCCESS && lmMapPtr != nullptr && !localTileMask.empty()) {
memcpy(lmMapPtr, localTileMask.data(),
localTileMask.size() * sizeof(float));
vkUnmapMemory(device, localTileMaskMemory);
}
// Update yuvToRgbaSet with current input
@@ -905,6 +1108,16 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
&memBarrier, 0, nullptr, 0, nullptr);
}
VkBufferMemoryBarrier localMaskBarrier{};
localMaskBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
localMaskBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
localMaskBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
localMaskBarrier.buffer = localTileMaskBuffer;
localMaskBarrier.size = VK_WHOLE_SIZE;
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
&localMaskBarrier, 0, nullptr);
// Phase 2: Compute Structure Tensor (Pass 1)
// Phase 2: Compute Structure Tensor (Pass 1)
@@ -1076,6 +1289,7 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
std::sort(
pendingFrames.begin(), pendingFrames.end(),
[](const FrameData &a, const FrameData &b) { return a.score > b.score; });
referenceFrameScore = pendingFrames.empty() ? 0.0f : pendingFrames.front().score;
// LOGI("processStack: Processing %zu frames", pendingFrames.size());
@@ -1091,7 +1305,7 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
for (auto &frame : pendingFrames) {
// LOGI("processStack: Processing frame %d, score %f", frameIdx,
// frame.score);
if (!processFrame(frame.buffer)) {
if (!processFrame(frame.buffer, frame.score)) {
LOGE("processStack: Failed to process frame %d", frameIdx);
} else {
// LOGI("processStack: Successfully processed frame %d", frameIdx);
@@ -1343,6 +1557,10 @@ void VulkanImageStacker::releaseVulkanResources() {
vkDestroyBuffer(device, motionPriorBuffer, nullptr);
if (motionPriorMemory != VK_NULL_HANDLE)
vkFreeMemory(device, motionPriorMemory, nullptr);
if (localTileMaskBuffer != VK_NULL_HANDLE)
vkDestroyBuffer(device, localTileMaskBuffer, nullptr);
if (localTileMaskMemory != VK_NULL_HANDLE)
vkFreeMemory(device, localTileMaskMemory, nullptr);
if (tensorSetLayout != VK_NULL_HANDLE)
vkDestroyDescriptorSetLayout(device, tensorSetLayout, nullptr);
+5 -1
View File
@@ -82,6 +82,7 @@ private:
// Phase 2/3: Noise Model
float noiseAlpha;
float noiseBeta;
float frameWeight;
};
struct FrameData {
@@ -102,9 +103,12 @@ private:
// Phase 3: Motion Prior Buffer (Grid Resolution)
VkBuffer motionPriorBuffer = VK_NULL_HANDLE;
VkDeviceMemory motionPriorMemory = VK_NULL_HANDLE;
VkBuffer localTileMaskBuffer = VK_NULL_HANDLE;
VkDeviceMemory localTileMaskMemory = VK_NULL_HANDLE;
float referenceFrameScore = 0.0f;
void initVulkanResources();
void releaseVulkanResources();
void createPipelines(VkSampler immutableSampler);
bool processFrame(AHardwareBuffer *buffer);
bool processFrame(AHardwareBuffer *buffer, float frameScore);
};