feat: new opengl es yuv stacker

This commit is contained in:
Hinnka committed 2026-06-14 20:24:13 +08:00
1 parent bc2bde4baa
commit c61b426206
14 files changed
+1637 -3433

No files matched your search

+2 -7
View File
@@ -31,11 +31,6 @@ if(NOT GLSL_COMPILER)
endif()
set(SHADER_SOURCES
shaders/accumulate.comp
shaders/align_tiles.comp
shaders/build_pyramid.comp
shaders/normalize.comp
shaders/structure_tensor.comp
shaders/align_lk.comp
shaders/raw_structure_tensor.comp
shaders/robustness_raw.comp
@@ -46,7 +41,6 @@ set(SHADER_SOURCES
shaders/normalize_green_hr.comp
shaders/color_gather_raw.comp
shaders/normalize_color_hr.comp
shaders/yuv_to_rgba.comp
)
set(GENERATED_SHADER_HEADERS "")
@@ -93,7 +87,6 @@ add_library(my-native-lib SHARED
lut_processor.cpp
vulkan_manager.cpp
vulkan_utils.cpp
vulkan_stacker.cpp
vulkan_raw_stacker.cpp
dcp_parser.cpp
${LIBRAW_SOURCES}
@@ -128,6 +121,8 @@ target_link_libraries(
log
jnigraphics
android
EGL
GLESv3
vulkan
z
)
-99
View File
@@ -28,8 +28,6 @@
#include "math_utils.h"
#include "stacking_utils.h"
#include "vulkan_raw_stacker.h"
#include "vulkan_stacker.h"
#include <android/hardware_buffer_jni.h>
#ifndef LOG_TAG
#define LOG_TAG "native-lib"
@@ -1158,103 +1156,6 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_releaseStackerNative(
delete stacker;
}
/**
* Vulkan Stacking JNI Interface
*/
JNIEXPORT jlong JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_createVulkanStackerNative(
JNIEnv *env, jobject /* this */, jint width, jint height,
jboolean enableSuperRes) {
try {
auto *stacker = new VulkanImageStacker(width, height, enableSuperRes);
return reinterpret_cast<jlong>(stacker);
} catch (const std::exception &e) {
LOGE("createVulkanStackerNative failed: %s", e.what());
} catch (...) {
LOGE("createVulkanStackerNative failed with unknown error");
}
return 0;
}
JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_addVulkanFrameNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject hardwareBuffer) {
auto *stacker = reinterpret_cast<VulkanImageStacker *>(stackerPtr);
if (!stacker || !hardwareBuffer)
return JNI_FALSE;
AHardwareBuffer *buffer =
AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
if (!buffer)
return JNI_FALSE;
try {
bool success = stacker->addFrame(buffer);
return success ? JNI_TRUE : JNI_FALSE;
} catch (const std::exception &e) {
LOGE("addVulkanFrameNative failed: %s", e.what());
} catch (...) {
LOGE("addVulkanFrameNative failed with unknown error");
}
return JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processVulkanStackNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject outBitmap,
jint rotation) {
auto *stacker = reinterpret_cast<VulkanImageStacker *>(stackerPtr);
if (!stacker)
return JNI_FALSE;
AndroidBitmapInfo info;
void *bitmapPixels = nullptr;
if (outBitmap &&
(AndroidBitmap_getInfo(env, outBitmap, &info) < 0 ||
AndroidBitmap_lockPixels(env, outBitmap, &bitmapPixels) < 0)) {
return JNI_FALSE;
}
bool success = false;
try {
success =
stacker->processStack(static_cast<uint32_t *>(bitmapPixels), info.width,
info.height, info.stride, rotation);
} catch (const std::exception &e) {
LOGE("processVulkanStackNative failed: %s", e.what());
} catch (...) {
LOGE("processVulkanStackNative failed with unknown error");
}
if (outBitmap) {
AndroidBitmap_unlockPixels(env, outBitmap);
}
return success ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_releaseVulkanStackerNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
auto *stacker = reinterpret_cast<VulkanImageStacker *>(stackerPtr);
delete stacker;
}
JNIEXPORT jboolean JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_resetVulkanStackerNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
auto *stacker = reinterpret_cast<VulkanImageStacker *>(stackerPtr);
if (!stacker)
return JNI_FALSE;
try {
return stacker->resetForReuse() ? JNI_TRUE : JNI_FALSE;
} catch (const std::exception &e) {
LOGE("resetVulkanStackerNative failed: %s", e.what());
} catch (...) {
LOGE("resetVulkanStackerNative failed with unknown error");
}
return JNI_FALSE;
}
/**
* Raw Stacking JNI Interface
*/
-328
View File
@@ -1,328 +0,0 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform sampler2D rgbSampler;
layout(binding = 1, scalar) buffer Accumulator {
vec4 data[]; // vec4(Y*w, Cb*w, Cr*w, w)
} accumulator;
layout(binding = 2, scalar) buffer AlignmentGrid {
vec2 offsets[];
} alignmentGrid;
layout(binding = 3, scalar) readonly buffer KernelParams {
vec4 data[]; // (k1, k2, cos2theta, sin2theta)
} kernelParams;
layout(binding = 4, scalar) buffer MotionPrior {
float errors[];
} motionPrior;
layout(binding = 5, scalar) buffer LocalTileMask {
float weights[];
} localTileMask;
layout(binding = 6) uniform sampler2D referenceSampler;
layout(push_constant, scalar) uniform PushConstants {
float t0, t1, t2, t3, t4, t5;
float offsetX, offsetY;
float scale;
uint width; // Global width
uint height; // Global height
float baseNoise; // Unused legacy
uint isFirstFrame;
uint tileX; // Tile start X
uint tileY; // Tile start Y
uint tileW; // Tile width
uint tileH; // Tile height
uint gridW;
uint gridH;
uint bufferStride;
float noiseAlpha; // Sensor noise model slope
float noiseBeta; // Sensor noise model intercept
float frameWeight;
} pc;
vec3 sanitizeRgb(vec3 rgb) {
if (any(isnan(rgb)) || any(isinf(rgb))) {
return vec3(1.0);
}
return clamp(rgb, 0.0, 1.0);
}
vec4 sampleBicubic(sampler2D s, vec2 uv, vec2 size) {
// Redefined to use hardware-accelerated bilinear filtering (texture)
// to resolve the 500+ texelFetch software instruction bottleneck.
return vec4(sanitizeRgb(texture(s, uv).rgb), 1.0);
}
vec3 rgb2ycbcr(vec3 rgb) {
rgb = sanitizeRgb(rgb);
float Y = dot(rgb, vec3(0.2126, 0.7152, 0.0722));
float Cb = dot(rgb, vec3(-0.1146, -0.3854, 0.5)) + 0.5;
float Cr = dot(rgb, vec3(0.5, -0.4542, -0.0458)) + 0.5;
return vec3(Y, Cb, Cr);
}
float sampleLuma(sampler2D s, vec2 uv, vec2 size) {
return rgb2ycbcr(sampleBicubic(s, uv, size).rgb).x;
}
float yccDiffSq(vec3 a, vec3 b) {
vec3 d = (a - b) * vec3(1.0, 0.5, 0.5);
return dot(d, d);
}
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;
if (tx >= pc.tileW || ty >= pc.tileH) return;
uint x = pc.tileX + tx;
uint y = pc.tileY + ty;
uint outIndex = ty * pc.bufferStride + tx;
// 1b. Get Kernel Params (at native resolution)
uint nx = uint(float(x) / pc.scale);
uint ny = uint(float(y) / pc.scale);
uint nativeW = uint(float(pc.width) / pc.scale);
uint nativeH = uint(float(pc.height) / pc.scale);
nx = clamp(nx, 0, nativeW - 1);
ny = clamp(ny, 0, nativeH - 1);
uint kernelTileY = uint(pc.offsetY);
uint localNy = (ny > kernelTileY) ? (ny - kernelTileY) : 0u;
uint kpIndex = localNy * nativeW + nx;
vec4 kp = kernelParams.data[kpIndex];
// 1. Get transformations / coordinates
vec2 pixelSize = vec2(1.0) / vec2(pc.width, pc.height);
vec2 normalizedUV = (vec2(x, y) + 0.5) * pixelSize;
vec2 finalUV;
finalUV.x = normalizedUV.x * pc.t0 + normalizedUV.y * pc.t1 + pc.t2;
finalUV.y = normalizedUV.x * pc.t3 + normalizedUV.y * pc.t4 + pc.t5;
vec2 referenceUV = finalUV;
// 2. Alignment
vec2 nativeSize = vec2(float(pc.width) / pc.scale, float(pc.height) / pc.scale);
vec2 alignment = vec2(0.0);
float motionError = 0.0;
if (pc.isFirstFrame == 0) {
vec2 gCoord = finalUV * vec2(float(pc.gridW), float(pc.gridH)) - 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 = alignmentGrid.offsets[g0.y * pc.gridW + g0.x];
vec2 f10 = alignmentGrid.offsets[g0.y * pc.gridW + g1.x];
vec2 f01 = alignmentGrid.offsets[g1.y * pc.gridW + g0.x];
vec2 f11 = alignmentGrid.offsets[g1.y * pc.gridW + g1.x];
alignment = mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y);
alignment = clamp(alignment, vec2(-128.0), vec2(128.0));
float e00 = motionPrior.errors[g0.y * pc.gridW + g0.x];
float e10 = motionPrior.errors[g0.y * pc.gridW + g1.x];
float e01 = motionPrior.errors[g1.y * pc.gridW + g0.x];
float e11 = motionPrior.errors[g1.y * pc.gridW + g1.x];
motionError = mix(mix(e00, e10, gf.x), mix(e01, e11, gf.x), gf.y);
finalUV = referenceUV + alignment / nativeSize;
}
vec2 posInSource = finalUV * nativeSize;
vec2 centerSource = floor(posInSource - 0.5) + 0.5;
vec2 centerReference = floor(referenceUV * nativeSize - 0.5) + 0.5;
vec4 accumValue = accumulator.data[outIndex];
float currentW = accumValue.a;
float expectedSigma = 0.025;
float centerRobustness = 1.0;
vec3 centerColor = vec3(0.0);
vec3 centerYCC = vec3(0.0);
if (pc.isFirstFrame == 0) {
centerColor = sampleBicubic(rgbSampler, finalUV, nativeSize).rgb;
centerYCC = rgb2ycbcr(centerColor);
vec3 refYCC = rgb2ycbcr(sampleBicubic(referenceSampler, referenceUV, nativeSize).rgb);
float centerLuma = refYCC.x;
float sumY = 0.0;
float sumY2 = 0.0;
for (int sy = -1; sy <= 1; sy++) {
for (int sx = -1; sx <= 1; sx++) {
vec2 refSampleUV = (centerReference + vec2(float(sx), float(sy))) / nativeSize;
float yRef = sampleLuma(referenceSampler, refSampleUV, nativeSize);
sumY += yRef;
sumY2 += yRef * yRef;
}
}
float meanY = sumY / 9.0;
float sigma2Spatial = max(sumY2 / 9.0 - meanY * meanY, 0.0);
float sigma2Noise = max(pc.noiseAlpha * centerLuma + pc.noiseBeta, 1e-10);
float sigma2 = max(sigma2Spatial, sigma2Noise);
expectedSigma = sqrt(max(sigma2, 1e-10));
float gradX = 0.5 * (
sampleLuma(referenceSampler, (centerReference + vec2(1.0, 0.0)) / nativeSize, nativeSize) -
sampleLuma(referenceSampler, (centerReference + vec2(-1.0, 0.0)) / nativeSize, nativeSize));
float gradY = 0.5 * (
sampleLuma(referenceSampler, (centerReference + vec2(0.0, 1.0)) / nativeSize, nativeSize) -
sampleLuma(referenceSampler, (centerReference + vec2(0.0, -1.0)) / nativeSize, nativeSize));
float edgeStrength = sqrt(max((gradX * gradX + gradY * gradY) / max(sigma2, 1e-8), 0.0));
float edgeRelax = smoothstep(1.2, 5.0, edgeStrength);
float flowMag = length(alignment);
float flowPenalty = 1.0;
if (flowMag > 15.0) {
flowPenalty = exp(-0.1 * (flowMag - 15.0));
}
float errorPenalty = exp(-0.015 * max(motionError, 0.0));
float globalPenalty = flowPenalty * errorPenalty;
float minRobustness = 1.0;
float sumRobustness = 0.0;
float weightSum = 0.0;
float centerR = 1.0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
vec2 sampleOffset = vec2(float(dx), float(dy));
vec2 refSampleUV = (centerReference + sampleOffset) / nativeSize;
vec2 trgSampleUV = (centerReference + sampleOffset + alignment) / nativeSize;
vec3 localRefYCC = rgb2ycbcr(sampleBicubic(referenceSampler, refSampleUV, nativeSize).rgb);
vec3 localTrgYCC = rgb2ycbcr(sampleBicubic(rgbSampler, trgSampleUV, nativeSize).rgb);
float dSq = yccDiffSq(localRefYCC, localTrgYCC);
float noiseFloor = mix(4.5 * sigma2, sigma2Noise, edgeRelax);
float den = mix(sigma2, sigma2Noise, edgeRelax);
float residual = max(0.0, dSq - noiseFloor) / max(den, 1e-10);
float tau = 1.0 + 1.2 * edgeRelax;
float r = exp(-0.5 * pow(residual / tau, 8.0)) * 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) {
centerR = r;
}
}
}
float avgRobustness = (weightSum > 0.0) ? (sumRobustness / weightSum) : minRobustness;
float minMix = mix(0.35, 0.15, edgeRelax);
float centerMix = mix(0.35, 0.55, edgeRelax);
float avgMix = 1.0 - minMix - centerMix;
centerRobustness = clamp(minMix * minRobustness +
centerMix * centerR +
avgMix * avgRobustness,
0.0, 1.0);
if (isnan(centerRobustness) || isinf(centerRobustness)) centerRobustness = 0.0;
}
float localTileWeight = sampleLocalTileWeight(referenceUV);
float fusionMask = localTileWeight;
int supportRadius = 1;
if (pc.isFirstFrame == 0) {
supportRadius = 2;
float tilePenalty = 1.0 - smoothstep(0.10, 0.55, localTileWeight);
fusionMask *= mix(0.95, 0.65, tilePenalty);
}
float c_ = kp.z; float s_ = kp.w;
float cosT = sqrt(0.5 * (1.0 + c_));
float sinT = sqrt(0.5 * (1.0 - c_));
if (s_ < 0.0) sinT = -sinT;
float kernelScale = 0.25 * pc.scale * pc.scale;
float invVarU = kp.x * kernelScale;
float invVarV = kp.y * kernelScale;
float baseWeightScale = pc.frameWeight * fusionMask;
float robustnessFloor = 0.01 * localTileWeight;
for (int j = -2; j <= 2; ++j) {
for (int i = -2; i <= 2; ++i) {
if (abs(i) > supportRadius || abs(j) > supportRadius) {
continue;
}
vec2 d = (centerSource + vec2(float(i), float(j)) - posInSource);
float u = d.x * cosT + d.y * sinT;
float v = -d.x * sinT + d.y * cosT;
float w = exp(-0.5 * (u*u * invVarU + v*v * invVarV));
if (w <= 1e-4) {
continue;
}
float baseCombinedUpperBound = w * baseWeightScale;
if (pc.isFirstFrame == 0) {
baseCombinedUpperBound *= max(centerRobustness, robustnessFloor);
}
if (baseCombinedUpperBound <= 1e-6) {
continue;
}
vec2 samplePos = centerSource + vec2(float(i), float(j));
vec2 sampleUV = samplePos / nativeSize;
vec3 sampleColor;
if (i == 0 && j == 0) {
if (pc.isFirstFrame == 0) {
sampleColor = centerColor;
} else {
sampleColor = sampleBicubic(rgbSampler, sampleUV, nativeSize).rgb;
}
} else {
sampleColor = sanitizeRgb(texture(rgbSampler, sampleUV).rgb);
}
vec3 sampleYCC = rgb2ycbcr(sampleColor);
float robustness = centerRobustness;
if (pc.isFirstFrame == 0) {
vec2 refSampleUV = (samplePos - alignment) / nativeSize;
vec3 sampleRefYCC = rgb2ycbcr(sanitizeRgb(texture(referenceSampler, refSampleUV).rgb));
float sampleDiffSq = yccDiffSq(sampleYCC, sampleRefYCC);
float sampleResidual = max(0.0, sampleDiffSq - 4.5 * expectedSigma * expectedSigma) /
max(expectedSigma * expectedSigma, 1e-10);
float sampleRobustness = exp(-0.5 * pow(sampleResidual, 8.0));
robustness *= sampleRobustness;
robustness = max(robustness, robustnessFloor);
}
float combinedWeight = w * robustness * pc.frameWeight * fusionMask;
if (isnan(combinedWeight) || isinf(combinedWeight)) combinedWeight = 0.0;
if (combinedWeight <= 1e-6) continue;
vec4 increment = vec4(
sampleYCC.x * combinedWeight,
sampleYCC.y * combinedWeight,
sampleYCC.z * combinedWeight,
combinedWeight
);
if (!any(isnan(increment)) && !any(isinf(increment))) {
accumValue += increment;
}
}
}
accumulator.data[outIndex] = accumValue;
}
-63
View File
@@ -1,63 +0,0 @@
#version 450
layout(local_size_x = 8, local_size_y = 8) in;
layout(binding = 0, r8) uniform readonly image2D refImage;
layout(binding = 1, r8) uniform readonly image2D targetImage;
layout(binding = 2) buffer Result {
ivec2 offsets[];
} results;
layout(push_constant) uniform PushConstants {
ivec2 gridPos; // Top-left of the tile
int tileSize;
int searchRadius;
int gridW;
} pc;
shared float sadCache[17][17]; // Supporting search radius up to 8
void main() {
int dx = int(gl_LocalInvocationID.x) - pc.searchRadius;
int dy = int(gl_LocalInvocationID.y) - pc.searchRadius;
if (abs(dx) > pc.searchRadius || abs(dy) > pc.searchRadius) return;
float sad = 0.0;
int count = 0;
for (int y = 0; y < pc.tileSize; y += 2) {
for (int x = 0; x < pc.tileSize; x += 2) {
ivec2 rCoord = pc.gridPos + ivec2(x, y);
ivec2 tCoord = rCoord + ivec2(dx, dy);
float r = imageLoad(refImage, rCoord).r;
float t = imageLoad(targetImage, tCoord).r;
sad += abs(r - t);
count++;
}
}
sadCache[dy + pc.searchRadius][dx + pc.searchRadius] = sad / max(float(count), 1.0);
barrier();
// Only one thread per tile finds the minimum
if (gl_LocalInvocationID.x == 0 && gl_LocalInvocationID.y == 0) {
float minSad = 1e10;
ivec2 bestOffset = ivec2(0);
for (int sy = 0; sy <= pc.searchRadius * 2; sy++) {
for (int sx = 0; sx <= pc.searchRadius * 2; sx++) {
if (sadCache[sy][sx] < minSad) {
minSad = sadCache[sy][sx];
bestOffset = ivec2(sx - pc.searchRadius, sy - pc.searchRadius);
}
}
}
uint tileIdx = (pc.gridPos.y / pc.tileSize) * pc.gridW + (pc.gridPos.x / pc.tileSize);
results.offsets[tileIdx] = bestOffset;
}
}
@@ -1,22 +0,0 @@
#version 450
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0, r8) uniform readonly image2D inputImage;
layout(binding = 1, r8) uniform writeonly image2D outputImage;
void main() {
ivec2 outSize = imageSize(outputImage);
ivec2 outCoord = ivec2(gl_GlobalInvocationID.xy);
if (outCoord.x >= outSize.x || outCoord.y >= outSize.y) return;
ivec2 inCoord = outCoord * 2;
float sum = imageLoad(inputImage, inCoord).r;
sum += imageLoad(inputImage, inCoord + ivec2(1, 0)).r;
sum += imageLoad(inputImage, inCoord + ivec2(0, 1)).r;
sum += imageLoad(inputImage, inCoord + ivec2(1, 1)).r;
imageStore(outputImage, outCoord, vec4(sum * 0.25));
}
-266
View File
@@ -1,266 +0,0 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0, scalar) buffer OutputBuffer {
uint pixels[];
} outputBuffer;
layout(binding = 1, scalar) buffer Accumulator {
vec4 data[]; // vec4(Y*w, Cb*w, Cr*w, w)
} accumulator;
layout(push_constant, scalar) uniform PushConstants {
float t0, t1, t2, t3, t4, t5;
uint outWidth;
uint outHeight;
uint outOriginX;
uint outOriginY;
uint outBufferOriginY;
uint sensorWidth; // Global sensor width
uint sensorHeight; // Global sensor height
uint tileX;
uint tileY;
uint tileW;
uint tileH;
uint bufferStride;
} pc;
const float MIN_ACCUM_WEIGHT = 1e-4;
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)];
}
bool hasValidAccum(vec4 acc) {
return acc.a > MIN_ACCUM_WEIGHT &&
!any(isnan(acc)) && !any(isinf(acc));
}
vec3 normalizeYCC(vec4 acc) {
if (!hasValidAccum(acc)) {
return vec3(0.0, 0.5, 0.5);
}
float invW = 1.0 / acc.a;
float Y = acc.r * invW;
float Cb = acc.g * invW;
float Cr = acc.b * invW;
vec3 ycc = vec3(Y, Cb, Cr);
if (any(isnan(ycc)) || any(isinf(ycc))) {
return vec3(0.0, 0.5, 0.5);
}
return clamp(ycc, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));
}
void addValidSample(inout vec3 yccSum, inout float weightSum,
inout float accumWeightSum, vec4 acc, float sampleWeight) {
if (!hasValidAccum(acc) || sampleWeight <= 0.0) {
return;
}
yccSum += normalizeYCC(acc) * sampleWeight;
weightSum += sampleWeight;
accumWeightSum += acc.a * sampleWeight;
}
// YCbCr to Linear RGB (BT.709 inverse, matches accumulate.comp)
vec3 ycbcr2rgb(vec3 ycc) {
float Y = ycc.x;
float Cb = ycc.y - 0.5;
float Cr = ycc.z - 0.5;
float R = Y + 1.5748 * Cr;
float G = Y - 0.1873 * Cb - 0.4681 * Cr;
float B = Y + 1.8556 * Cb;
return vec3(R, G, B);
}
void main() {
uint X = gl_GlobalInvocationID.x + pc.outOriginX;
uint Y = gl_GlobalInvocationID.y + pc.outOriginY;
if (X >= pc.outWidth || Y >= pc.outHeight) return;
float fx = float(X) * pc.t0 + float(Y) * pc.t1 + pc.t2;
float fy = float(X) * pc.t3 + float(Y) * pc.t4 + pc.t5;
// Bilinear sampling from accumulator to preserve sub-pixel super-res detail.
// Nearest-neighbor (floor+0.5) would alias 2x SR data back to 1x.
float localFx = fx - float(pc.tileX);
float localFy = fy - float(pc.tileY);
// Check if the sampled point is within THIS tile (with 1px margin for bilinear)
if (localFx >= -0.5 && localFx < float(pc.tileW) - 0.5 &&
localFy >= -0.5 && localFy < float(pc.tileH) - 0.5) {
// Bilinear interpolation of accumulator
float bx = localFx - 0.5;
float by = localFy - 0.5;
int x0 = int(floor(bx));
int y0 = int(floor(by));
float fracX = bx - float(x0);
float fracY = by - float(y0);
vec4 a00 = readAccum(x0, y0);
vec4 a10 = readAccum(x0 + 1, y0);
vec4 a01 = readAccum(x0, y0 + 1);
vec4 a11 = readAccum(x0 + 1, y0 + 1);
float w00 = (1.0 - fracX) * (1.0 - fracY);
float w10 = fracX * (1.0 - fracY);
float w01 = (1.0 - fracX) * fracY;
float w11 = fracX * fracY;
vec3 yccSum = vec3(0.0);
float validWeightSum = 0.0;
float accumWeight = 0.0;
addValidSample(yccSum, validWeightSum, accumWeight, a00, w00);
addValidSample(yccSum, validWeightSum, accumWeight, a10, w10);
addValidSample(yccSum, validWeightSum, accumWeight, a01, w01);
addValidSample(yccSum, validWeightSum, accumWeight, a11, w11);
if (validWeightSum <= 0.0) {
return;
}
// Bilinear interpolation in YCbCr space, ignoring invalid accumulator
// texels so sparse zero-weight samples cannot turn into black dots.
vec3 ycc = yccSum / validWeightSum;
accumWeight /= validWeightSum;
if (any(isnan(ycc)) || any(isinf(ycc))) {
ycc = vec3(0.0, 0.5, 0.5);
}
// ── Y-guided spatial chroma denoising ──
// Chroma noise is LOW-FREQUENCY (large color blobs), so we must sample
// widely spaced pixels to break the spatial correlation.
// 5×5 guided window with large step scale.
{
int cx = int(floor(localFx));
int cy = int(floor(localFy));
float centerY = ycc.x;
vec2 centerCbCr = ycc.yz;
vec2 chromaSum = vec2(0.0);
float chromaWSum = 0.0;
// Step scale: sample every ~6 pixels in accumulator space.
// 5×5 window × step 6 = effective 30×30 pixel coverage,
// enough to average out low-frequency chroma blobs.
const int stepScale = 6;
// Spatial Gaussian sigma² (in grid units, not pixels)
const float spatialSigmaSq = 3.0;
// Luma range sigma²: tight to preserve edges (linear space)
const float lumaSigmaSq = 0.001;
// Chroma range sigma²: wide to aggressively merge similar chroma
const float chromaSigmaSq = 0.02;
for (int gy = -2; gy <= 2; ++gy) {
for (int gx = -2; gx <= 2; ++gx) {
int nx = cx + gx * stepScale;
int ny = cy + gy * stepScale;
vec4 nAcc = readAccum(nx, ny);
if (!hasValidAccum(nAcc)) {
continue;
}
vec3 nYCC = normalizeYCC(nAcc);
// Spatial weight
float wS = exp(-float(gx*gx + gy*gy) / (2.0 * spatialSigmaSq));
// Luma edge guide: tight tolerance prevents color bleeding across edges
float dL = nYCC.x - centerY;
float wL = exp(-(dL * dL) / (2.0 * lumaSigmaSq));
// Chroma self-similarity: wide tolerance merges noisy chroma variants
vec2 dC = nYCC.yz - centerCbCr;
float wC = exp(-dot(dC, dC) / (2.0 * chromaSigmaSq));
float w = wS * wL * wC;
// Ensure center pixel always contributes
if (gx == 0 && gy == 0) w = max(w, 0.1);
chromaSum += nYCC.yz * w;
chromaWSum += w;
}
}
if (chromaWSum > 0.001) {
ycc.yz = chromaSum / chromaWSum;
}
}
// ── Residual luma denoise ──
// Only active when accumWeight is low (few frames merged).
// 3×3 bilateral filter with very tight range sigma to preserve edges.
if (accumWeight < 3.0) {
int lx = int(floor(localFx));
int ly = int(floor(localFy));
// Use readAccum at integer position as reference, matching neighbor sources
float centerL = normalizeYCC(readAccum(lx, ly)).x;
float lumaSum = 0.0;
float lumaW = 0.0;
// Filtering strength fades out as more frames are accumulated
float strength = smoothstep(3.0, 0.5, accumWeight);
float rangeSigmaSq = 0.0005 * strength;
for (int gy = -1; gy <= 1; ++gy) {
for (int gx = -1; gx <= 1; ++gx) {
vec4 nAcc = readAccum(lx + gx, ly + gy);
if (!hasValidAccum(nAcc)) {
continue;
}
float nL = normalizeYCC(nAcc).x;
float wS = (gx == 0 && gy == 0) ? 1.0 : 0.5;
float dL = nL - centerL;
float wR = exp(-(dL * dL) / max(2.0 * rangeSigmaSq, 1e-8));
float w = wS * wR;
lumaSum += nL * w;
lumaW += w;
}
}
// Blend denoised luma with original bilinear value to keep sub-pixel detail
if (lumaW > 0.001) {
float denoisedL = lumaSum / lumaW;
ycc.x = mix(ycc.x, denoisedL, strength);
}
}
// ── Luma-only detail recovery ──
// Gated by confidence and local contrast.
if (accumWeight > 0.75) {
int lx = int(floor(localFx));
int ly = int(floor(localFy));
vec3 left = normalizeYCC(readAccum(lx - 1, ly));
vec3 right = normalizeYCC(readAccum(lx + 1, ly));
vec3 up = normalizeYCC(readAccum(lx, ly - 1));
vec3 down = normalizeYCC(readAccum(lx, ly + 1));
float centerY = ycc.x;
float neighborY = 0.25 * (left.x + right.x + up.x + down.x);
float detail = centerY - neighborY;
float localContrast =
abs(detail) / max(centerY + neighborY + 1e-4, 1e-4);
float confidenceBoost = smoothstep(1.0, 4.0, accumWeight);
float baseSharpen = mix(0.15, 0.35, confidenceBoost);
float sharpenAmount =
baseSharpen * smoothstep(0.015, 0.08, localContrast);
ycc.x = max(ycc.x + detail * sharpenAmount, 0.0);
}
// Convert YCbCr back to RGB after chroma denoising.
vec3 color = ycbcr2rgb(ycc);
color = clamp(color, 0.0, 1.0);
uint r = uint(clamp(color.r * 255.0, 0.0, 255.0));
uint g = uint(clamp(color.g * 255.0, 0.0, 255.0));
uint b = uint(clamp(color.b * 255.0, 0.0, 255.0));
uint a = 255;
uint outIndex = (Y - pc.outBufferOriginY) * pc.outWidth + X;
outputBuffer.pixels[outIndex] = (a << 24) | (b << 16) | (g << 8) | r;
}
}
@@ -1,150 +0,0 @@
#version 450
#extension GL_EXT_scalar_block_layout : require
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform sampler2D rgbSampler;
layout(binding = 1, scalar) writeonly buffer KernelParams {
vec4 data[]; // (k1, k2, cos2theta, sin2theta)
} kernelParams;
layout(push_constant, scalar) uniform PushConstants {
float t0, t1, t2, t3, t4, t5;
float offsetX, offsetY;
float scale;
uint width; // Global width
uint height; // Global height
float baseNoise; // Unused legacy
uint isFirstFrame;
uint tileX; // Tile start X
uint tileY; // Tile start Y
uint tileW; // Tile width
uint tileH; // Tile height
uint gridW;
uint gridH;
uint bufferStride;
float noiseAlpha; // Sensor noise model slope
float noiseBeta; // Sensor noise model intercept
} pc;
float rgb2gray(vec3 rgb) {
if (any(isnan(rgb)) || any(isinf(rgb))) {
rgb = vec3(1.0);
}
rgb = clamp(rgb, 0.0, 1.0);
return dot(rgb, vec3(0.299, 0.587, 0.114));
}
void main() {
uint tx = gl_GlobalInvocationID.x;
uint ty = gl_GlobalInvocationID.y;
if (tx >= pc.tileW || ty >= pc.tileH) return;
uint x = pc.tileX + tx;
uint y = pc.tileY + ty;
// Safety check for global bounds
if (x >= pc.width || y >= pc.height) return;
// Convert output coordinate to UV
vec2 pixelSize = vec2(1.0) / vec2(pc.width, pc.height);
vec2 uv = (vec2(x, y) + 0.5) * pixelSize;
// Calculate Gradients and Smooth J (Structure Tensor Elements) using a 5x5 window
// Larger window is MUCH more robust against high-ISO noise
float sIxIx = 0.0;
float sIyIy = 0.0;
float sIxIy = 0.0;
for (int dy = -2; dy <= 2; dy++) {
for (int dx = -2; dx <= 2; dx++) {
vec2 offset = vec2(float(dx), float(dy)) * pixelSize;
vec2 sampleUV = uv + offset;
float cxp = rgb2gray(texture(rgbSampler, sampleUV + vec2(pixelSize.x, 0.0)).rgb);
float cxm = rgb2gray(texture(rgbSampler, sampleUV - vec2(pixelSize.x, 0.0)).rgb);
float cyp = rgb2gray(texture(rgbSampler, sampleUV + vec2(0.0, pixelSize.y)).rgb);
float cym = rgb2gray(texture(rgbSampler, sampleUV - vec2(0.0, pixelSize.y)).rgb);
float Ix_ = (cxp - cxm) * 0.5;
float Iy_ = (cyp - cym) * 0.5;
sIxIx += Ix_ * Ix_;
sIyIy += Iy_ * Iy_;
sIxIy += Ix_ * Iy_;
}
}
// Normalize gradients to [0, 1] range to match noise model scale properly
// The previous 255.0 multipliers artificially distorted the tensor energy.
// We now keep it strictly in Unorm space.
float varIxIx = sIxIx / 25.0;
float varIyIy = sIyIy / 25.0;
float varIxIy = sIxIy / 25.0;
// Eigen Analysis of J
float trace = varIxIx + varIyIy;
float diff_tr = varIxIx - varIyIy;
float sqrt_term = sqrt(diff_tr * diff_tr + 4.0 * varIxIy * varIxIy);
float lambda1 = 0.5 * (trace + sqrt_term);
float lambda2 = 0.5 * (trace - sqrt_term);
// --- Exact Google MFSR Python Reconstruction ---
// Noise estimation (Mid-tone Unorm noise variance)
float noiseVar = pc.noiseAlpha * 0.5 + max(pc.noiseBeta, 1e-10);
float noiseGradEnergy = 2.0 * noiseVar * 9.0; // Assume 3x3 equivalent smoothing
float SNR = lambda1 / max(noiseGradEnergy, 1e-12);
// Parameters derived from reference code (Relaxed for YUV fp domain scale)
float k_detail = 0.30;
// In super-res mode (scale > 1), a large denoise kernel averages away the
// sub-pixel differences needed for resolution recovery. With the accumulate
// shader's kernelScale = 0.25 * scale², the kernel sigma is already normalized
// to output space. Use a tighter sigma to resolve 2x detail.
float k_denoise = 1.0;
float k_shrink = 3.0;
float k_stretch = 5.0;
// D is the "flatness" metric
float D = 1.0 - smoothstep(0.35, 4.0, SNR);
// Anisotropy factor A
float A_py = 1.0 + sqrt(max(lambda1 - lambda2, 0.0) / max(lambda1 + lambda2, 1e-7));
float k1_base = 1.0;
float k2_base = 1.0;
if (A_py > 1.6) {
k1_base = 1.0 / k_shrink;
k2_base = k_stretch;
}
float pre_k1 = k_detail * mix(k1_base, k_denoise, D);
float pre_k2 = k_detail * mix(k2_base, k_denoise, D);
// Passed as INVERSE variance to the accumulator
float k1 = 1.0 / max(pre_k1 * pre_k1, 1e-7);
float k2 = 1.0 / max(pre_k2 * pre_k2, 1e-7);
// 2*theta logic for orientation
float diff = varIxIx - varIyIy;
float length = sqrt(diff * diff + 4.0 * varIxIy * varIxIy);
float cos2t, sin2t;
if (length < 1e-9 || isnan(length)) {
cos2t = 1.0;
sin2t = 0.0;
} else {
cos2t = diff / length;
sin2t = 2.0 * varIxIy / length;
}
vec4 result = vec4(k1, k2, cos2t, sin2t);
if (any(isnan(result)) || any(isinf(result))) {
result = vec4(1.0, 1.0, 1.0, 0.0); // Safe fallback (Identity kernel)
}
uint kernelTileY = uint(pc.offsetY);
uint localY = (y > kernelTileY) ? (y - kernelTileY) : 0u;
kernelParams.data[localY * pc.width + x] = result;
}
-34
View File
@@ -1,34 +0,0 @@
#version 450
layout(local_size_x = 16, local_size_y = 16) in;
layout(binding = 0) uniform sampler2D yuvSampler;
layout(binding = 1, rgba16f) uniform writeonly image2D rgbaOutput;
layout(push_constant) uniform PushConstants {
uint width;
uint height;
} pc;
vec3 sanitizeRgb(vec3 rgb) {
if (any(isnan(rgb)) || any(isinf(rgb))) {
return vec3(1.0);
}
return clamp(rgb, 0.0, 1.0);
}
void main() {
uint x = gl_GlobalInvocationID.x;
uint y = gl_GlobalInvocationID.y;
if (x >= pc.width || y >= pc.height) return;
vec2 uv = (vec2(float(x), float(y)) + 0.5) / vec2(float(pc.width), float(pc.height));
vec4 color = texture(yuvSampler, uv);
vec3 rgb = sanitizeRgb(color.rgb);
// Explicitly set alpha to 1.0 as some YUV samplers might return 0
// and storing 0 alpha could cause issues in subsequent blending/weighting.
imageStore(rgbaOutput, ivec2(x, y), vec4(rgb, 1.0));
}
+1 -2
View File
@@ -10,8 +10,7 @@
* VulkanRawStacker - GPU-accelerated RAW image stacking using Vulkan
*
* This class processes RAW sensor data (Bayer pattern) using Vulkan compute
* shaders. It follows the same design pattern as VulkanImageStacker but
* optimized for 16-bit RAW data.
* shaders and is optimized for 16-bit RAW data.
*/
class VulkanRawStacker {
public:
File diff suppressed because it is too large. Load diff
-144
View File
@@ -1,144 +0,0 @@
#pragma once
#include "stacking_utils.h"
#include "vulkan_manager.h"
#include "vulkan_utils.h"
#include <vector>
struct YuvStackPerfStats {
double totalMs = 0.0;
double scoreCalculationMs = 0.0;
double allFramesProcessingMs = 0.0;
double normalizationDispatchMs = 0.0;
double outputCopyMs = 0.0;
size_t totalFrames = 0;
size_t keptFrames = 0;
size_t skippedFrames = 0;
double totalEffectiveFrames = 0.0;
void logSummary(uint32_t outputW, uint32_t outputH, float scale) const;
};
class VulkanImageStacker {
public:
VulkanImageStacker(uint32_t width, uint32_t height, bool enableSuperRes);
~VulkanImageStacker();
bool addFrame(AHardwareBuffer *buffer);
bool processStack(uint32_t *outBitmap, uint32_t outWidth, uint32_t outHeight,
uint32_t stride, int rotation);
bool resetForReuse();
private:
uint32_t width, height;
bool enableSuperRes;
bool isFirstFrame = true;
VulkanImage accumulator;
// Dynamic Tiling
int numTilesX = 1;
int numTilesY = 1;
// Alignment grid info
uint32_t gridW = 0;
uint32_t gridH = 0;
VkBuffer alignmentBuffer = VK_NULL_HANDLE;
VkDeviceMemory alignmentMemory = VK_NULL_HANDLE;
VkBuffer alignmentUploadBuffer = VK_NULL_HANDLE;
VkDeviceMemory alignmentUploadMemory = VK_NULL_HANDLE;
std::vector<VkBuffer> accumBuffers;
std::vector<VkDeviceMemory> accumMemories;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> accumSets;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkPipeline accumulatePipeline = VK_NULL_HANDLE;
// Pre-conversion resources
VulkanImage rgbFrame;
VulkanImage referenceRgbFrame;
VkDescriptorSetLayout yuvToRgbaLayout = VK_NULL_HANDLE;
VkDescriptorSet yuvToRgbaSet = VK_NULL_HANDLE;
VkPipelineLayout yuvToRgbaPipelineLayout = VK_NULL_HANDLE;
VkPipeline yuvToRgbaPipeline = VK_NULL_HANDLE;
VkSampler immutableSampler = VK_NULL_HANDLE;
VkSamplerYcbcrConversion ycbcrConversion = VK_NULL_HANDLE;
VkDescriptorSetLayout normalizeSetLayout = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> normalizeSets;
VkPipelineLayout normalizePipelineLayout = VK_NULL_HANDLE;
VkPipeline normalizePipeline = VK_NULL_HANDLE;
VkQueryPool gpuTimingQueryPool = VK_NULL_HANDLE;
float gpuTimestampPeriodNs = 0.0f;
bool gpuTimestampSupported = false;
// Staging buffer for result copy
VkBuffer stagingBuffer = VK_NULL_HANDLE;
VkDeviceMemory stagingMemory = VK_NULL_HANDLE;
// Reference for alignment
std::vector<GrayImage> referencePyramid;
struct PushConstants {
// Transform matrix as individual floats (avoids array padding issues)
float t0, t1, t2, t3, t4, t5;
float offsetX, offsetY;
float scale;
uint32_t width;
uint32_t height;
float baseNoise;
uint32_t isFirstFrame;
// Tile info
uint32_t tileX;
uint32_t tileY;
uint32_t tileW;
uint32_t tileH;
// Grid info
uint32_t gridW;
uint32_t gridH;
uint32_t bufferStride;
// Phase 2/3: Noise Model
float noiseAlpha;
float noiseBeta;
float frameWeight;
};
struct FrameData {
AHardwareBuffer *buffer;
float score = 0.0f;
GrayImage grayY; // cached grayscale from score calculation
};
std::vector<FrameData> pendingFrames;
// Phase 2: Structure Tensor Resources
VkBuffer kernelParamsBuffer = VK_NULL_HANDLE;
VkDeviceMemory kernelParamsMemory = VK_NULL_HANDLE;
VkDescriptorSetLayout tensorSetLayout = VK_NULL_HANDLE;
VkPipelineLayout tensorPipelineLayout = VK_NULL_HANDLE;
VkPipeline tensorPipeline = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> tensorSets;
// Phase 3: Motion Prior Buffer (Grid Resolution)
VkBuffer motionPriorBuffer = VK_NULL_HANDLE;
VkDeviceMemory motionPriorMemory = VK_NULL_HANDLE;
VkBuffer motionPriorUploadBuffer = VK_NULL_HANDLE;
VkDeviceMemory motionPriorUploadMemory = VK_NULL_HANDLE;
VkBuffer localTileMaskBuffer = VK_NULL_HANDLE;
VkDeviceMemory localTileMaskMemory = VK_NULL_HANDLE;
VkBuffer localTileMaskUploadBuffer = VK_NULL_HANDLE;
VkDeviceMemory localTileMaskUploadMemory = VK_NULL_HANDLE;
float referenceFrameScore = 0.0f;
void initVulkanResources();
void releaseVulkanResources();
void createPipelines(VkSampler immutableSampler);
bool processFrame(AHardwareBuffer *buffer, float frameScore,
GrayImage &cachedGray, YuvStackPerfStats &perf);
void resetDescriptorHandles();
void releasePendingFrames();
};
@@ -29,7 +29,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.hinnka.mycamera.livephoto.LivePhotoRecorder
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.MultiFrameStacker
import com.hinnka.mycamera.utils.DeviceUtil
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.video.CaptureMode
@@ -44,9 +43,6 @@ import com.hinnka.mycamera.video.VideoRecorder
import com.hinnka.mycamera.video.VideoResolutionPreset
import com.hinnka.mycamera.video.VideoRecordingState
import com.hinnka.mycamera.video.VideoStabilizationMode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean
@@ -1020,21 +1016,6 @@ class Camera2Controller(private val context: Context) {
}, cameraHandler)
}
if ((state.value.useMFNR || state.value.useMFSR) &&
captureFormat != ImageFormat.RAW_SENSOR
) {
CoroutineScope(Dispatchers.IO).launch {
val prewarmOk = MultiFrameStacker.prewarmVulkanStacker(
width = captureSize.width,
height = captureSize.height,
enableSuperResolution = state.value.useMFSR,
)
PLog.i(
TAG,
"Vulkan stacker prewarm after ImageReader creation: size=${captureSize.width}x${captureSize.height}, SR=${state.value.useMFSR}, ok=$prewarmOk"
)
}
}
} else {
safeCloseImageReader(imageReader)
imageReader = null
File diff suppressed because it is too large. Load diff
@@ -31,13 +31,6 @@ data class RawStackResult(
object MultiFrameStacker {
private const val TAG = "MultiFrameStacker"
private data class CachedVulkanStacker(
val ptr: Long,
val width: Int,
val height: Int,
val enableSuperResolution: Boolean,
)
private data class CachedVulkanRawStacker(
val ptr: Long,
val width: Int,
@@ -79,7 +72,6 @@ object MultiFrameStacker {
}
}
private var cachedVulkanStacker: CachedVulkanStacker? = null
private var cachedVulkanRawStacker: CachedVulkanRawStacker? = null
init {
@@ -117,49 +109,38 @@ object MultiFrameStacker {
val targetW = dimensions.width() * scale
val targetH = dimensions.height() * scale
val inputFormat = images[0].format
if (useVulkan) {
if (enableSuperResolution) {
PLog.w(TAG, "GLES streaming stacker does not support SR yet; Vulkan/legacy fallback disabled")
images.forEach { it.close() }
return null
}
if (!GlesYuvStacker.supportsImageFormat(inputFormat)) {
PLog.w(TAG, "GLES streaming stacker does not support image format=$inputFormat; Vulkan/legacy fallback disabled")
images.forEach { it.close() }
return null
}
PLog.i(
TAG,
"Starting Vulkan stacking process for ${images.size} frames ($width x $height). SR=$enableSuperResolution"
"Starting GLES streaming stacking process for ${images.size} frames ($width x $height)"
)
val stackerPtr = obtainVulkanStacker(width, height, enableSuperResolution, resetForUse = true)
if (stackerPtr != 0L) {
try {
for (image in images) {
image.use {
val hardwareBuffer = it.image.hardwareBuffer
if (hardwareBuffer != null) {
addVulkanFrameNative(stackerPtr, hardwareBuffer)
} else {
PLog.w(TAG, "Image has no hardware buffer, skipping")
}
}
}
PLog.d(TAG, "Stack frames processed")
val previewBitmap = try {
createBitmap(targetW, targetH, colorSpace = colorSpace)
} catch (e: OutOfMemoryError) {
PLog.e(TAG, "OOM creating Vulkan stack bitmap ($targetW x $targetH)", e)
return null
}
val processOk = processVulkanStackNative(stackerPtr, previewBitmap, rotation)
if (!processOk) {
PLog.w(TAG, "Vulkan stack processing failed, invalidating cached stacker")
previewBitmap.recycle()
invalidateCachedVulkanStacker(stackerPtr)
return null
} else {
PLog.i(TAG, "Vulkan stacking completed in ${System.currentTimeMillis() - startTime}ms")
return previewBitmap
}
} catch (e: Exception) {
PLog.e(TAG, "Error during Vulkan stacking", e)
invalidateCachedVulkanStacker(stackerPtr)
return null
}
val glesBitmap = GlesYuvStacker(
width = width,
height = height,
outputWidth = targetW,
outputHeight = targetH,
rotation = rotation,
colorSpace = colorSpace,
inputFormat = inputFormat,
).process(images)
if (glesBitmap != null) {
images.forEach { it.close() }
return glesBitmap
}
PLog.w(TAG, "GLES streaming stacker failed; Vulkan/legacy fallback disabled")
images.forEach { it.close() }
return null
}
// Fallback or legacy path
@@ -214,32 +195,7 @@ object MultiFrameStacker {
}
@Synchronized
fun prewarmVulkanStacker(
width: Int,
height: Int,
enableSuperResolution: Boolean = false,
): Boolean {
val stackerPtr = obtainVulkanStacker(width, height, enableSuperResolution, resetForUse = false)
val success = stackerPtr != 0L
if (success) {
PLog.i(
TAG,
"Prewarmed Vulkan stacker for ${width}x$height SR=$enableSuperResolution"
)
}
return success
}
@Synchronized
fun releaseCachedVulkanStacker() {
cachedVulkanStacker?.let {
releaseVulkanStackerNative(it.ptr)
PLog.i(
TAG,
"Released cached Vulkan stacker for ${it.width}x${it.height} SR=${it.enableSuperResolution}"
)
}
cachedVulkanStacker = null
fun releaseCachedVulkanRawStacker() {
cachedVulkanRawStacker?.let {
releaseVulkanRawStackerNative(it.ptr)
PLog.i(
@@ -250,49 +206,6 @@ object MultiFrameStacker {
cachedVulkanRawStacker = null
}
private fun obtainVulkanStacker(
width: Int,
height: Int,
enableSuperResolution: Boolean,
resetForUse: Boolean,
): Long {
val cached = cachedVulkanStacker
if (cached != null &&
cached.width == width &&
cached.height == height &&
cached.enableSuperResolution == enableSuperResolution
) {
if (!resetForUse || resetVulkanStackerNative(cached.ptr)) {
return cached.ptr
}
PLog.w(TAG, "Failed to reset cached Vulkan stacker, recreating")
releaseVulkanStackerNative(cached.ptr)
cachedVulkanStacker = null
} else if (cached != null) {
releaseVulkanStackerNative(cached.ptr)
cachedVulkanStacker = null
}
val stackerPtr = createVulkanStackerNative(width, height, enableSuperResolution)
if (stackerPtr != 0L) {
cachedVulkanStacker = CachedVulkanStacker(
ptr = stackerPtr,
width = width,
height = height,
enableSuperResolution = enableSuperResolution,
)
}
return stackerPtr
}
private fun invalidateCachedVulkanStacker(stackerPtr: Long) {
val cached = cachedVulkanStacker
if (cached != null && cached.ptr == stackerPtr) {
releaseVulkanStackerNative(stackerPtr)
cachedVulkanStacker = null
}
}
private fun obtainVulkanRawStacker(
width: Int,
height: Int,
@@ -535,16 +448,6 @@ object MultiFrameStacker {
private external fun releaseStackerNative(stackerPtr: Long)
private external fun createVulkanStackerNative(width: Int, height: Int, enableSuperRes: Boolean): Long
private external fun addVulkanFrameNative(
stackerPtr: Long,
hardwareBuffer: android.hardware.HardwareBuffer
): Boolean
private external fun processVulkanStackNative(stackerPtr: Long, outBitmap: Bitmap?, rotation: Int): Boolean
private external fun releaseVulkanStackerNative(stackerPtr: Long)
private external fun resetVulkanStackerNative(stackerPtr: Long): Boolean
private external fun createRawStackerNative(width: Int, height: Int, enableSuperRes: Boolean): Long
private external fun stageRawFrameNative(stackerPtr: Long, rawData: ByteBuffer, rowStride: Int, cfaPattern: Int)
private external fun processRawFrameNative(stackerPtr: Long, index: Int)