diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 25f0a701..7e3d7010 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -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 ) diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index c9528394..d44ded3d 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -28,8 +28,6 @@ #include "math_utils.h" #include "stacking_utils.h" #include "vulkan_raw_stacker.h" -#include "vulkan_stacker.h" -#include #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(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(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(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(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(stackerPtr); - delete stacker; -} - -JNIEXPORT jboolean JNICALL -Java_com_hinnka_mycamera_processor_MultiFrameStacker_resetVulkanStackerNative( - JNIEnv *env, jobject /* this */, jlong stackerPtr) { - auto *stacker = reinterpret_cast(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 */ diff --git a/app/src/main/cpp/shaders/accumulate.comp b/app/src/main/cpp/shaders/accumulate.comp deleted file mode 100644 index aa11c359..00000000 --- a/app/src/main/cpp/shaders/accumulate.comp +++ /dev/null @@ -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; -} diff --git a/app/src/main/cpp/shaders/align_tiles.comp b/app/src/main/cpp/shaders/align_tiles.comp deleted file mode 100644 index f7f7aec1..00000000 --- a/app/src/main/cpp/shaders/align_tiles.comp +++ /dev/null @@ -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; - } -} diff --git a/app/src/main/cpp/shaders/build_pyramid.comp b/app/src/main/cpp/shaders/build_pyramid.comp deleted file mode 100644 index d336f446..00000000 --- a/app/src/main/cpp/shaders/build_pyramid.comp +++ /dev/null @@ -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)); -} diff --git a/app/src/main/cpp/shaders/normalize.comp b/app/src/main/cpp/shaders/normalize.comp deleted file mode 100644 index 5f16f980..00000000 --- a/app/src/main/cpp/shaders/normalize.comp +++ /dev/null @@ -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; - } -} diff --git a/app/src/main/cpp/shaders/structure_tensor.comp b/app/src/main/cpp/shaders/structure_tensor.comp deleted file mode 100644 index 475d7b23..00000000 --- a/app/src/main/cpp/shaders/structure_tensor.comp +++ /dev/null @@ -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; -} diff --git a/app/src/main/cpp/shaders/yuv_to_rgba.comp b/app/src/main/cpp/shaders/yuv_to_rgba.comp deleted file mode 100644 index f889445f..00000000 --- a/app/src/main/cpp/shaders/yuv_to_rgba.comp +++ /dev/null @@ -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)); -} diff --git a/app/src/main/cpp/vulkan_raw_stacker.h b/app/src/main/cpp/vulkan_raw_stacker.h index b6a35617..f865ca16 100644 --- a/app/src/main/cpp/vulkan_raw_stacker.h +++ b/app/src/main/cpp/vulkan_raw_stacker.h @@ -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: diff --git a/app/src/main/cpp/vulkan_stacker.cpp b/app/src/main/cpp/vulkan_stacker.cpp deleted file mode 100644 index 8035e3a5..00000000 --- a/app/src/main/cpp/vulkan_stacker.cpp +++ /dev/null @@ -1,2174 +0,0 @@ -#include "vulkan_stacker.h" -#include "accumulate.comp.h" -#include "common.h" -#include "normalize.comp.h" -#include "structure_tensor.comp.h" -#include "yuv_to_rgba.comp.h" -#include -#include -#include -#include -#include -#include -#include - -#define VK_CHECK(x) \ - do { \ - VkResult err = x; \ - if (err) { \ - LOGE("Detected Vulkan error: %d at %s:%d", err, __FILE__, __LINE__); \ - throw std::runtime_error("Vulkan call failed"); \ - } \ - } 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 tileWeights; - float flatGoodFraction = 0.0f; - float flatAreaFraction = 0.0f; - float detailAreaFraction = 0.0f; -}; - -constexpr bool kEnableYuvStackPerfLogs = false; - -inline void logYuvStackStage(const char *stage, double elapsedMs) { - if (!kEnableYuvStackPerfLogs) - return; - LOGI("YuvStackPerf[%s]: %.3f ms", stage, elapsedMs); -} - -#undef TIME_START -#undef TIME_END -#define TIME_START(name) const auto start_##name = std::chrono::steady_clock::now() -#define TIME_END(name) \ - const double elapsed_##name = std::chrono::duration( \ - std::chrono::steady_clock::now() - \ - start_##name) \ - .count(); \ - logYuvStackStage(#name, elapsed_##name) - -inline float clamp01(float v) { return std::clamp(v, 0.0f, 1.0f); } - -inline float smoothstepf(float edge0, float edge1, float x) { - float width = std::max(edge1 - edge0, 1e-6f); - float t = clamp01((x - edge0) / width); - return t * t * (3.0f - 2.0f * t); -} - -inline VkDeviceSize yuvAccumTileBytes(uint32_t fullW, uint32_t fullH, - int tilesX, int tilesY) { - uint32_t tileW = (fullW + tilesX - 1) / tilesX; - uint32_t tileH = (fullH + tilesY - 1) / tilesY; - return (VkDeviceSize)(tileW + 16) * (tileH + 16) * sizeof(float) * 4; -} - -inline VkDeviceSize yuvKernelTileRangeBytes(uint32_t width, uint32_t height, - int tilesY) { - uint32_t tileH = (height + tilesY - 1) / tilesY; - return (VkDeviceSize)width * tileH * sizeof(float) * 4; -} - -void constrainYuvTileGridForStorageRange(uint32_t width, uint32_t height, - uint32_t scale, - VkDeviceSize maxStorageBufferRange, - int &tilesX, int &tilesY) { - if (maxStorageBufferRange == 0) - return; - - const uint32_t fullW = width * scale; - const uint32_t fullH = height * scale; - while (yuvAccumTileBytes(fullW, fullH, tilesX, tilesY) > - maxStorageBufferRange || - yuvKernelTileRangeBytes(width, height, tilesY) > - maxStorageBufferRange) { - if (yuvKernelTileRangeBytes(width, height, tilesY) > - maxStorageBufferRange) { - ++tilesY; - } else { - uint32_t tileW = (fullW + tilesX - 1) / tilesX; - uint32_t tileH = (fullH + tilesY - 1) / tilesY; - if (tileW >= tileH) { - ++tilesX; - } else { - ++tilesY; - } - } - - if (tilesX > 16 || tilesY > 16) { - throw std::runtime_error("Unable to tile Vulkan stacker buffers"); - } - } -} - -inline ScalarStats computeScalarStats(const std::vector &values) { - ScalarStats stats; - if (values.empty()) - return stats; - std::vector 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 &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 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(x0 + tileW, reference.width); - uint32_t y1 = std::min(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(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( - 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 flatThreshold = detailStats.minValue + - (detailStats.p50 - detailStats.minValue) * 0.70f; - float detailThreshold = std::max( - detailStats.p50, detailStats.minValue + - (detailStats.p90 - detailStats.minValue) * 0.55f); - size_t flatCount = 0; - size_t flatGood = 0; - size_t detailCount = 0; - - for (size_t idx = 0; idx < errorMap.size() && idx < detailScores.size(); ++idx) { - float detail = detailScores[idx]; - float err = errorMap[idx]; - float errRms = std::sqrt(std::max(err, 0.0f)); - float detailPenalty = smoothstepf(flatThreshold, detailThreshold, detail); - float errorWeight = clamp01(1.0f - std::max(0.0f, errRms - 2.0f) / 4.5f); - float tileWeight = clamp01(errorWeight); - - if (detailPenalty > 0.60f) { - ++detailCount; - } else { - ++flatCount; - if (errRms < 4.0f) - ++flatGood; - } - - if (errRms > 5.5f) { - tileWeight *= 0.60f; - } - - if (detailPenalty > 0.78f && errRms > 7.5f) { - tileWeight = 0.0f; - } - - result.tileWeights[idx] = clamp01(tileWeight); - } - - float tileCount = static_cast(detailScores.size()); - result.flatGoodFraction = - (flatCount > 0) ? (float)flatGood / (float)flatCount : 0.0f; - result.flatAreaFraction = (tileCount > 0.0f) ? (float)flatCount / tileCount : 0.0f; - result.detailAreaFraction = - (tileCount > 0.0f) ? (float)detailCount / tileCount : 0.0f; - return result; -} - -float computeFrameFusionWeight(const std::vector &errorMap, - float sharpnessRatio, - const LocalReliabilityMap &localMap) { - if (errorMap.empty()) - return clamp01(0.70f + 0.25f * sharpnessRatio); - - ScalarStats errStats = computeScalarStats(errorMap); - float errP90Rms = std::sqrt(std::max(errStats.p90, 0.0f)); - float errorWeight = - clamp01(1.0f - std::max(0.0f, errP90Rms - 2.5f) / 5.0f); - float sharpnessGuard = clamp01(0.88f + 0.12f * sharpnessRatio); - float flatCoverage = clamp01(0.75f + 0.25f * localMap.flatAreaFraction); - float flatReliability = clamp01(0.44f + 0.55f * localMap.flatGoodFraction); - float detailPenalty = clamp01(1.0f - 0.15f * localMap.detailAreaFraction); - float baseWeight = - 0.6f + 0.40f * errorWeight * flatCoverage * flatReliability * detailPenalty; - return clamp01(baseWeight * sharpnessGuard); -} - -} // namespace - -void YuvStackPerfStats::logSummary(uint32_t outputW, uint32_t outputH, - float scale) const { - if (!kEnableYuvStackPerfLogs) - return; - LOGI("YuvStackPerf summary: total=%.3f ms output=%ux%u scale=%.2f frames=%zu " - "kept=%zu skipped=%zu effFrames=%.2f", - totalMs, outputW, outputH, scale, totalFrames, keptFrames, skippedFrames, - totalEffectiveFrames); - LOGI("YuvStackPerf phases: score=%.3f process=%.3f norm=%.3f copy=%.3f", - scoreCalculationMs, allFramesProcessingMs, normalizationDispatchMs, - outputCopyMs); -} - -VulkanImageStacker::VulkanImageStacker(uint32_t w, uint32_t h, bool sr) - : width(w), height(h), enableSuperRes(sr) { - - if (enableSuperRes) { - numTilesX = 2; - numTilesY = 2; - } else { - numTilesX = 1; - numTilesY = 1; - } - - if (width == 0 || height == 0) { - throw std::runtime_error("Invalid Vulkan stacker dimensions"); - } - if (!VulkanManager::getInstance().init()) { - throw std::runtime_error("Failed to initialize VulkanManager"); - } - try { - initVulkanResources(); - } catch (...) { - releaseVulkanResources(); - throw; - } -} - -VulkanImageStacker::~VulkanImageStacker() { - releasePendingFrames(); - releaseVulkanResources(); -} - -void VulkanImageStacker::initVulkanResources() { - VulkanManager &vm = VulkanManager::getInstance(); - VkDevice device = vm.getDevice(); - VkPhysicalDevice physicalDevice = vm.getPhysicalDevice(); - if (device == VK_NULL_HANDLE || physicalDevice == VK_NULL_HANDLE) { - throw std::runtime_error("VulkanManager is not ready"); - } - - VkPhysicalDeviceProperties deviceProperties{}; - vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties); - LOGI("initVulkanResources: device=%s vendor=0x%x device=0x%x api=%u.%u.%u " - "maxStorageBufferRange=%u", - deviceProperties.deviceName, deviceProperties.vendorID, - deviceProperties.deviceID, VK_VERSION_MAJOR(deviceProperties.apiVersion), - VK_VERSION_MINOR(deviceProperties.apiVersion), - VK_VERSION_PATCH(deviceProperties.apiVersion), - deviceProperties.limits.maxStorageBufferRange); - - // Create Accumulator Tiles - uint32_t scale = enableSuperRes ? 2 : 1; - uint32_t fullW = width * scale; - uint32_t fullH = height * scale; - VkDeviceSize maxStorageBufferRange = - deviceProperties.limits.maxStorageBufferRange; - - constrainYuvTileGridForStorageRange(width, height, scale, - maxStorageBufferRange, numTilesX, - numTilesY); - - // Each tile is roughly fullW / numTilesX ... - uint32_t tileW = (fullW + numTilesX - 1) / numTilesX; - uint32_t tileH = (fullH + numTilesY - 1) / numTilesY; - - // Pad tile size slightly for safety - VkDeviceSize accumBufferSize = - (VkDeviceSize)(tileW + 16) * (tileH + 16) * sizeof(float) * 4; - VkDeviceSize stagingSize = (VkDeviceSize)fullW * fullH * 4; - VkDeviceSize kpSize = - (VkDeviceSize)width * height * sizeof(float) * 4; // vec4 - VkDeviceSize kpTileRangeSize = yuvKernelTileRangeBytes(width, height, numTilesY); - if (maxStorageBufferRange > 0 && - (accumBufferSize > maxStorageBufferRange || - kpTileRangeSize > maxStorageBufferRange)) { - LOGE("Vulkan stacker buffers exceed device storage buffer range. " - "accum=%llu kernelRange=%llu limit=%llu size=%ux%u SR=%d tiles=%dx%d", - (unsigned long long)accumBufferSize, - (unsigned long long)kpTileRangeSize, - (unsigned long long)maxStorageBufferRange, width, height, - enableSuperRes ? 1 : 0, numTilesX, numTilesY); - throw std::runtime_error("Vulkan storage buffer range is too small"); - } - - int numTiles = numTilesX * numTilesY; - LOGI("initVulkanResources: Tiles: %d (%dx%d) accum=%llu staging=%llu " - "kernel=%llu kernelRange=%llu", - numTiles, numTilesX, numTilesY, (unsigned long long)accumBufferSize, - (unsigned long long)stagingSize, (unsigned long long)kpSize, - (unsigned long long)kpTileRangeSize); - - accumBuffers.resize(numTiles); - accumMemories.resize(numTiles); - accumSets.resize(numTiles); - normalizeSets.resize(numTiles); - - for (int i = 0; i < numTiles; ++i) { - VkBufferCreateInfo bufferInfo{}; - bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - bufferInfo.size = accumBufferSize; - bufferInfo.usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - VK_CHECK(vkCreateBuffer(device, &bufferInfo, nullptr, &accumBuffers[i])); - - VkMemoryRequirements memReqs; - vkGetBufferMemoryRequirements(device, accumBuffers[i], &memReqs); - - VkMemoryAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - allocInfo.allocationSize = memReqs.size; - allocInfo.memoryTypeIndex = vm.findMemoryType( - memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - - VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &accumMemories[i])); - vkBindBufferMemory(device, accumBuffers[i], accumMemories[i], 0); - } - - // Initialize Alignment Grid Buffer early - // Use finer grid (16px tiles) for super-res to capture sub-pixel variation - uint32_t alignTileSize = enableSuperRes ? 16 : 32; - gridW = (width + alignTileSize - 1) / alignTileSize; - gridH = (height + alignTileSize - 1) / alignTileSize; - VkDeviceSize alignBufferSize = gridW * gridH * sizeof(Point); - VkBufferCreateInfo alignInfo{}; - alignInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - alignInfo.size = alignBufferSize; - alignInfo.usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - alignInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &alignInfo, nullptr, &alignmentBuffer)); - - VkMemoryRequirements alignMemReqs; - vkGetBufferMemoryRequirements(device, alignmentBuffer, &alignMemReqs); - VkMemoryAllocateInfo alignAlloc{}; - alignAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alignAlloc.allocationSize = alignMemReqs.size; - alignAlloc.memoryTypeIndex = vm.findMemoryType( - alignMemReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VK_CHECK(vkAllocateMemory(device, &alignAlloc, nullptr, &alignmentMemory)); - vkBindBufferMemory(device, alignmentBuffer, alignmentMemory, 0); - - VkBufferCreateInfo alignUploadInfo{}; - alignUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - alignUploadInfo.size = alignBufferSize; - alignUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - alignUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK( - vkCreateBuffer(device, &alignUploadInfo, nullptr, &alignmentUploadBuffer)); - - VkMemoryRequirements alignUploadReqs; - vkGetBufferMemoryRequirements(device, alignmentUploadBuffer, - &alignUploadReqs); - VkMemoryAllocateInfo alignUploadAlloc{}; - alignUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - alignUploadAlloc.allocationSize = alignUploadReqs.size; - alignUploadAlloc.memoryTypeIndex = vm.findMemoryType( - alignUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VK_CHECK(vkAllocateMemory(device, &alignUploadAlloc, nullptr, - &alignmentUploadMemory)); - vkBindBufferMemory(device, alignmentUploadBuffer, alignmentUploadMemory, 0); - - // Initial Clear for Alignment Buffer - void *ptr; - vkMapMemory(device, alignmentUploadMemory, 0, alignBufferSize, 0, &ptr); - memset(ptr, 0, (size_t)alignBufferSize); - vkUnmapMemory(device, alignmentUploadMemory); - - // Staging Buffer - VkBufferCreateInfo stagingInfo{}; - stagingInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - stagingInfo.size = stagingSize; - stagingInfo.usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - stagingInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - VK_CHECK(vkCreateBuffer(device, &stagingInfo, nullptr, &stagingBuffer)); - - VkMemoryRequirements stagingReqs; - vkGetBufferMemoryRequirements(device, stagingBuffer, &stagingReqs); - - VkMemoryAllocateInfo stagingAlloc{}; - stagingAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - stagingAlloc.allocationSize = stagingReqs.size; - stagingAlloc.memoryTypeIndex = vm.findMemoryType( - stagingReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - - VK_CHECK(vkAllocateMemory(device, &stagingAlloc, nullptr, &stagingMemory)); - vkBindBufferMemory(device, stagingBuffer, stagingMemory, 0); - - // Descriptor Pool - VkDescriptorPoolSize poolSizes[3] = {}; - poolSizes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - poolSizes[0].descriptorCount = (uint32_t)numTiles * 64; - poolSizes[1].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - poolSizes[1].descriptorCount = (uint32_t)numTiles * 64; - poolSizes[2].type = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - poolSizes[2].descriptorCount = (uint32_t)numTiles * 64; - - VkDescriptorPoolCreateInfo poolInfo{}; - poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; - poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; - poolInfo.maxSets = (uint32_t)numTiles * 64; - poolInfo.poolSizeCount = 3; - poolInfo.pPoolSizes = poolSizes; - VK_CHECK(vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool)); - - gpuTimestampPeriodNs = deviceProperties.limits.timestampPeriod; - gpuTimestampSupported = - (deviceProperties.limits.timestampComputeAndGraphics == VK_TRUE); - if (gpuTimestampSupported) { - VkQueryPoolCreateInfo queryPoolInfo{}; - queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; - queryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; - queryPoolInfo.queryCount = 8; - VK_CHECK(vkCreateQueryPool(device, &queryPoolInfo, nullptr, - &gpuTimingQueryPool)); - } - - // Initial Clear - VkCommandBuffer cb = vm.beginSingleTimeCommands(); - for (int i = 0; i < numTiles; ++i) { - vkCmdFillBuffer(cb, accumBuffers[i], 0, accumBufferSize, 0); - VkBufferMemoryBarrier barrier{}; - barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - barrier.buffer = accumBuffers[i]; - barrier.size = accumBufferSize; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, - &barrier, 0, nullptr); - } - vm.endSingleTimeCommands(cb); - - // Phase 2: Kernel Params Buffer (Native Resolution - much safer for VRAM) - VkBufferCreateInfo kpInfo{}; - kpInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - kpInfo.size = kpSize; - kpInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; - kpInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &kpInfo, nullptr, &kernelParamsBuffer)); - - VkMemoryRequirements kpReqs; - vkGetBufferMemoryRequirements(device, kernelParamsBuffer, &kpReqs); - - VkMemoryAllocateInfo kpAlloc{}; - kpAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - kpAlloc.allocationSize = kpReqs.size; - kpAlloc.memoryTypeIndex = vm.findMemoryType( - kpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VK_CHECK(vkAllocateMemory(device, &kpAlloc, nullptr, &kernelParamsMemory)); - vkBindBufferMemory(device, kernelParamsBuffer, kernelParamsMemory, 0); - - // Allocate Descriptor Sets for Structure Tensor (One per tile? No, global - // pass or tile based?) For simplicity, let's make Structure Tensor a global - // pass or tile based. The shader uses inputSampler and kernelParams. Let's - // use 1 descriptor set for the whole image if possible, or per tile. Since we - // run ST on full image (or tiles), let's allocate 'numTiles' sets for it too - // to be consistent with dispatch pattern. - tensorSets.resize(numTiles); - - // Phase 3: Motion Prior Buffer (Grid resolution, float) - // Grid size: max (width+31)/32 * (height+31)/32 - // We reuse the 'gridW * gridH' logic, but max possible grid size is - // alignedW/32 * alignedH/32 - VkDeviceSize mpSize = (VkDeviceSize)gridW * gridH * sizeof(float); - - VkBufferCreateInfo mpInfo{}; - mpInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - mpInfo.size = mpSize; - mpInfo.usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - mpInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &mpInfo, nullptr, &motionPriorBuffer)); - - VkMemoryRequirements mpReqs; - vkGetBufferMemoryRequirements(device, motionPriorBuffer, &mpReqs); - - VkMemoryAllocateInfo mpAlloc{}; - mpAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mpAlloc.allocationSize = mpReqs.size; - mpAlloc.memoryTypeIndex = vm.findMemoryType( - mpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - VK_CHECK(vkAllocateMemory(device, &mpAlloc, nullptr, &motionPriorMemory)); - vkBindBufferMemory(device, motionPriorBuffer, motionPriorMemory, 0); - - VkBufferCreateInfo mpUploadInfo{}; - mpUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - mpUploadInfo.size = mpSize; - mpUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - mpUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &mpUploadInfo, nullptr, - &motionPriorUploadBuffer)); - - VkMemoryRequirements mpUploadReqs; - vkGetBufferMemoryRequirements(device, motionPriorUploadBuffer, - &mpUploadReqs); - VkMemoryAllocateInfo mpUploadAlloc{}; - mpUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - mpUploadAlloc.allocationSize = mpUploadReqs.size; - mpUploadAlloc.memoryTypeIndex = vm.findMemoryType( - mpUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VK_CHECK(vkAllocateMemory(device, &mpUploadAlloc, nullptr, - &motionPriorUploadMemory)); - vkBindBufferMemory(device, motionPriorUploadBuffer, motionPriorUploadMemory, - 0); - - VkBufferCreateInfo lmInfo{}; - lmInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - lmInfo.size = mpSize; - lmInfo.usage = - VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_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_DEVICE_LOCAL_BIT); - VK_CHECK(vkAllocateMemory(device, &lmAlloc, nullptr, &localTileMaskMemory)); - vkBindBufferMemory(device, localTileMaskBuffer, localTileMaskMemory, 0); - - VkBufferCreateInfo lmUploadInfo{}; - lmUploadInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - lmUploadInfo.size = mpSize; - lmUploadInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - lmUploadInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &lmUploadInfo, nullptr, - &localTileMaskUploadBuffer)); - - VkMemoryRequirements lmUploadReqs; - vkGetBufferMemoryRequirements(device, localTileMaskUploadBuffer, - &lmUploadReqs); - VkMemoryAllocateInfo lmUploadAlloc{}; - lmUploadAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - lmUploadAlloc.allocationSize = lmUploadReqs.size; - lmUploadAlloc.memoryTypeIndex = vm.findMemoryType( - lmUploadReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | - VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); - VK_CHECK(vkAllocateMemory(device, &lmUploadAlloc, nullptr, - &localTileMaskUploadMemory)); - vkBindBufferMemory(device, localTileMaskUploadBuffer, - localTileMaskUploadMemory, 0); - - // Initialize RGB Intermediate Image - rgbFrame.width = width; - rgbFrame.height = height; - rgbFrame.format = VK_FORMAT_R16G16B16A16_SFLOAT; - - VkImageCreateInfo imageInfo{}; - imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; - imageInfo.imageType = VK_IMAGE_TYPE_2D; - imageInfo.format = rgbFrame.format; - imageInfo.extent = {width, height, 1}; - imageInfo.mipLevels = 1; - imageInfo.arrayLayers = 1; - imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; - imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - imageInfo.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; - imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - - VK_CHECK(vkCreateImage(device, &imageInfo, nullptr, &rgbFrame.image)); - - VkMemoryRequirements memReqs; - vkGetImageMemoryRequirements(device, rgbFrame.image, &memReqs); - - VkMemoryAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; - allocInfo.allocationSize = memReqs.size; - allocInfo.memoryTypeIndex = vm.findMemoryType( - memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); - - VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &rgbFrame.memory)); - vkBindImageMemory(device, rgbFrame.image, rgbFrame.memory, 0); - - VkImageViewCreateInfo viewInfo{}; - viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; - viewInfo.image = rgbFrame.image; - viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; - viewInfo.format = rgbFrame.format; - viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - viewInfo.subresourceRange.baseMipLevel = 0; - viewInfo.subresourceRange.levelCount = 1; - viewInfo.subresourceRange.baseArrayLayer = 0; - viewInfo.subresourceRange.layerCount = 1; - - VK_CHECK(vkCreateImageView(device, &viewInfo, nullptr, &rgbFrame.viewY)); - - // Initialize Reference RGB Image - referenceRgbFrame.width = width; - referenceRgbFrame.height = height; - referenceRgbFrame.format = VK_FORMAT_R16G16B16A16_SFLOAT; - - imageInfo.format = referenceRgbFrame.format; - VK_CHECK(vkCreateImage(device, &imageInfo, nullptr, &referenceRgbFrame.image)); - - vkGetImageMemoryRequirements(device, referenceRgbFrame.image, &memReqs); - allocInfo.allocationSize = memReqs.size; - VK_CHECK(vkAllocateMemory(device, &allocInfo, nullptr, &referenceRgbFrame.memory)); - vkBindImageMemory(device, referenceRgbFrame.image, referenceRgbFrame.memory, 0); - - viewInfo.image = referenceRgbFrame.image; - viewInfo.format = referenceRgbFrame.format; - VK_CHECK(vkCreateImageView(device, &viewInfo, nullptr, &referenceRgbFrame.viewY)); - - VkSamplerCreateInfo samplerInfo{}; - samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; - samplerInfo.magFilter = VK_FILTER_LINEAR; - samplerInfo.minFilter = VK_FILTER_LINEAR; - samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; - samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - - VK_CHECK(vkCreateSampler(device, &samplerInfo, nullptr, &rgbFrame.sampler)); - VK_CHECK(vkCreateSampler(device, &samplerInfo, nullptr, &referenceRgbFrame.sampler)); -} - -void VulkanImageStacker::createPipelines(VkSampler sampler) { - VulkanManager &vm = VulkanManager::getInstance(); - VkDevice device = vm.getDevice(); - - // 1. Descriptor Set Layout with Immutable Sampler - VkSampler samplers[1] = {sampler}; - VkDescriptorSetLayoutBinding bindings[4] = {}; // Increased to 4 - bindings[0].binding = 0; - bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - bindings[0].descriptorCount = 1; - bindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - bindings[0].pImmutableSamplers = - nullptr; // Regular RGB image, no immutable sampler needed - - bindings[1].binding = 1; - bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - bindings[1].descriptorCount = 1; - bindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - bindings[2].binding = 2; - bindings[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - bindings[2].descriptorCount = 1; - bindings[2].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - bindings[3].binding = 3; // KernelParams (Read Only) - bindings[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - bindings[3].descriptorCount = 1; - bindings[3].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutBinding motionPriorBinding{}; - motionPriorBinding.binding = 4; // Motion Prior - motionPriorBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - motionPriorBinding.descriptorCount = 1; - motionPriorBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutBinding localMaskBinding{}; - localMaskBinding.binding = 5; - localMaskBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - localMaskBinding.descriptorCount = 1; - localMaskBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutBinding referenceBinding{}; - referenceBinding.binding = 6; - referenceBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - referenceBinding.descriptorCount = 1; - referenceBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutBinding bindingsFinal[7]; - bindingsFinal[0] = bindings[0]; - bindingsFinal[1] = bindings[1]; - bindingsFinal[2] = bindings[2]; - bindingsFinal[3] = bindings[3]; - bindingsFinal[4] = motionPriorBinding; - bindingsFinal[5] = localMaskBinding; - bindingsFinal[6] = referenceBinding; - - VkDescriptorSetLayoutCreateInfo layoutInfo{}; - layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - layoutInfo.bindingCount = 7; - layoutInfo.pBindings = bindingsFinal; - vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, - &descriptorSetLayout); - - // 2. Pipeline Layout with Push Constants - VkPushConstantRange pushConstantRange{}; - pushConstantRange.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - pushConstantRange.offset = 0; - pushConstantRange.size = sizeof(PushConstants); - - VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; - pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - pipelineLayoutInfo.setLayoutCount = 1; - pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; - pipelineLayoutInfo.pushConstantRangeCount = 1; - pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange; - vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout); - - // 3. Create Compute Pipeline - // Direct use of generated uint32_t array - std::vector shaderCode(accumulate_comp_spv, - accumulate_comp_spv + - (accumulate_comp_spv_size / 4)); - - VkShaderModule shaderModule = vm.createShaderModule(shaderCode); - - VkComputePipelineCreateInfo pipelineInfo{}; - pipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; - pipelineInfo.layout = pipelineLayout; - pipelineInfo.stage.sType = - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - pipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - pipelineInfo.stage.module = shaderModule; - pipelineInfo.stage.pName = "main"; - - vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, - &accumulatePipeline); - - vkDestroyShaderModule(device, shaderModule, nullptr); - - // 4. Create Normalization Pipeline - VkDescriptorSetLayoutBinding normalizeBindings[2] = {}; - normalizeBindings[0].binding = 0; // Output Buffer - normalizeBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - normalizeBindings[0].descriptorCount = 1; - normalizeBindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - normalizeBindings[1].binding = 1; // Accumulator Buffer - normalizeBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - normalizeBindings[1].descriptorCount = 1; - normalizeBindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutCreateInfo normalizeLayoutInfo{}; - normalizeLayoutInfo.sType = - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - normalizeLayoutInfo.bindingCount = 2; - normalizeLayoutInfo.pBindings = normalizeBindings; - vkCreateDescriptorSetLayout(device, &normalizeLayoutInfo, nullptr, - &normalizeSetLayout); - - VkPipelineLayoutCreateInfo normalizePipelineLayoutInfo{}; - normalizePipelineLayoutInfo.sType = - VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - normalizePipelineLayoutInfo.setLayoutCount = 1; - normalizePipelineLayoutInfo.pSetLayouts = &normalizeSetLayout; - normalizePipelineLayoutInfo.pushConstantRangeCount = 1; - normalizePipelineLayoutInfo.pPushConstantRanges = - &pushConstantRange; // Reuse push constant range - vkCreatePipelineLayout(device, &normalizePipelineLayoutInfo, nullptr, - &normalizePipelineLayout); - - std::vector normShaderCode( - normalize_comp_spv, normalize_comp_spv + (normalize_comp_spv_size / 4)); - VkShaderModule normShaderModule = vm.createShaderModule(normShaderCode); - - VkComputePipelineCreateInfo normPipelineInfo{}; - normPipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; - normPipelineInfo.layout = normalizePipelineLayout; - normPipelineInfo.stage.sType = - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - normPipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - normPipelineInfo.stage.module = normShaderModule; - normPipelineInfo.stage.pName = "main"; - - vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &normPipelineInfo, - nullptr, &normalizePipeline); - vkDestroyShaderModule(device, normShaderModule, nullptr); - - // 5. Create Structure Tensor Pipeline - // Layout: Binding 0 (Sampler), Binding 1 (KernelParams Out) - VkDescriptorSetLayoutBinding tensorBindings[2] = {}; - tensorBindings[0].binding = 0; - tensorBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - tensorBindings[0].descriptorCount = 1; - tensorBindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - tensorBindings[0].pImmutableSamplers = nullptr; // Regular RGB image - - tensorBindings[1].binding = 1; - tensorBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - tensorBindings[1].descriptorCount = 1; - tensorBindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutCreateInfo tensorLayoutInfo{}; - tensorLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - tensorLayoutInfo.bindingCount = 2; - tensorLayoutInfo.pBindings = tensorBindings; - vkCreateDescriptorSetLayout(device, &tensorLayoutInfo, nullptr, - &tensorSetLayout); - - VkPipelineLayoutCreateInfo tensorPLInfo{}; - tensorPLInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - tensorPLInfo.setLayoutCount = 1; - tensorPLInfo.pSetLayouts = &tensorSetLayout; - tensorPLInfo.pushConstantRangeCount = 1; - tensorPLInfo.pPushConstantRanges = &pushConstantRange; - vkCreatePipelineLayout(device, &tensorPLInfo, nullptr, &tensorPipelineLayout); - - std::vector stCode(structure_tensor_comp_spv, - structure_tensor_comp_spv + - (structure_tensor_comp_spv_size / 4)); - VkShaderModule stModule = vm.createShaderModule(stCode); - - VkComputePipelineCreateInfo stPipelineInfo{}; - stPipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; - stPipelineInfo.layout = tensorPipelineLayout; - stPipelineInfo.stage.sType = - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - stPipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - stPipelineInfo.stage.module = stModule; - stPipelineInfo.stage.pName = "main"; - - vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &stPipelineInfo, nullptr, - &tensorPipeline); - vkDestroyShaderModule(device, stModule, nullptr); - - // 6. Create YUV to RGBA Pipeline - VkDescriptorSetLayoutBinding yuvToRgbaBindings[2] = {}; - yuvToRgbaBindings[0].binding = 0; // Input YUV Sampler - yuvToRgbaBindings[0].descriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - yuvToRgbaBindings[0].descriptorCount = 1; - yuvToRgbaBindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - yuvToRgbaBindings[0].pImmutableSamplers = samplers; - - yuvToRgbaBindings[1].binding = 1; // Output RGBA Image - yuvToRgbaBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - yuvToRgbaBindings[1].descriptorCount = 1; - yuvToRgbaBindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; - - VkDescriptorSetLayoutCreateInfo yuvToRgbaLayoutInfo{}; - yuvToRgbaLayoutInfo.sType = - VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - yuvToRgbaLayoutInfo.bindingCount = 2; - yuvToRgbaLayoutInfo.pBindings = yuvToRgbaBindings; - vkCreateDescriptorSetLayout(device, &yuvToRgbaLayoutInfo, nullptr, - &yuvToRgbaLayout); - - VkPipelineLayoutCreateInfo yuvToRgbaPLInfo{}; - yuvToRgbaPLInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; - yuvToRgbaPLInfo.setLayoutCount = 1; - yuvToRgbaPLInfo.pSetLayouts = &yuvToRgbaLayout; - yuvToRgbaPLInfo.pushConstantRangeCount = 1; - yuvToRgbaPLInfo.pPushConstantRanges = &pushConstantRange; - vkCreatePipelineLayout(device, &yuvToRgbaPLInfo, nullptr, - &yuvToRgbaPipelineLayout); - - std::vector yuvToRgbaCode(yuv_to_rgba_comp_spv, - yuv_to_rgba_comp_spv + - (yuv_to_rgba_comp_spv_size / 4)); - VkShaderModule yuvToRgbaModule = vm.createShaderModule(yuvToRgbaCode); - - VkComputePipelineCreateInfo yuvToRgbaPipelineInfo{}; - yuvToRgbaPipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; - yuvToRgbaPipelineInfo.layout = yuvToRgbaPipelineLayout; - yuvToRgbaPipelineInfo.stage.sType = - VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; - yuvToRgbaPipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; - yuvToRgbaPipelineInfo.stage.module = yuvToRgbaModule; - yuvToRgbaPipelineInfo.stage.pName = "main"; - - vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &yuvToRgbaPipelineInfo, - nullptr, &yuvToRgbaPipeline); - vkDestroyShaderModule(device, yuvToRgbaModule, nullptr); -} - -bool VulkanImageStacker::addFrame(AHardwareBuffer *buffer) { - if (buffer == nullptr) - return false; - AHardwareBuffer_acquire(buffer); - pendingFrames.push_back({buffer, 0.0f}); - return true; -} - -bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer, float frameScore, - GrayImage &cachedGray, YuvStackPerfStats &perf) { - using PerfClock = std::chrono::steady_clock; - auto elapsedMs = [](const PerfClock::time_point &start, - const PerfClock::time_point &end) { - return std::chrono::duration(end - start).count(); - }; - VulkanImage input; - perf.totalFrames++; - - // Use existing conversion if available (from first frame) to compatible with - // immutable sampler - TIME_START(importBuffer); - if (!VulkanBufferImporter::importHardwareBuffer(buffer, input, - this->ycbcrConversion)) { - LOGE("processFrame: Failed to import hardware buffer"); - return false; - } - TIME_END(importBuffer); - - bool currentIsFirstFrame = isFirstFrame; - // LOGI("processFrame: Start. isFirstFrame=%d", currentIsFirstFrame); - - VulkanManager &vm = VulkanManager::getInstance(); - VkDevice device = vm.getDevice(); - - if (immutableSampler == VK_NULL_HANDLE) { - // Steal the first frame's sampler and conversion for long-lived pipelines - this->immutableSampler = input.sampler; - this->ycbcrConversion = input.ycbcrConversion; - input.sampler = VK_NULL_HANDLE; - input.ycbcrConversion = VK_NULL_HANDLE; // Steal ownership - - createPipelines(this->immutableSampler); - } else { - // If not first frame, we reused the conversion. - // We must NOT let input.release() destroy it, because - // 'this->ycbcrConversion' owns it now. - input.ycbcrConversion = VK_NULL_HANDLE; - } - - // 1. Reuse or Allocate Descriptor Sets for each tile - int numTiles = numTilesX * numTilesY; - - if (yuvToRgbaSet == VK_NULL_HANDLE) { - VkDescriptorSetAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - allocInfo.descriptorPool = descriptorPool; - allocInfo.descriptorSetCount = 1; - allocInfo.pSetLayouts = &yuvToRgbaLayout; - VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &yuvToRgbaSet)); - } - - // Descriptions for accum/tensor sets are constant for the life of the stacker - for (int i = 0; i < numTiles; ++i) { - if (accumSets[i] == VK_NULL_HANDLE) { - VkDescriptorSetAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - allocInfo.descriptorPool = descriptorPool; - allocInfo.descriptorSetCount = 1; - allocInfo.pSetLayouts = &descriptorSetLayout; - VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &accumSets[i])); - - VkDescriptorImageInfo imageInfo{}; - imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - imageInfo.imageView = rgbFrame.viewY; - imageInfo.sampler = rgbFrame.sampler; - - VkDescriptorImageInfo refImageInfo{}; - refImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - refImageInfo.imageView = referenceRgbFrame.viewY; - refImageInfo.sampler = referenceRgbFrame.sampler; - - uint32_t scale = enableSuperRes ? 2 : 1; - uint32_t fullH = height * scale; - uint32_t fullTileH = (fullH + numTilesY - 1) / numTilesY; - uint32_t tileRow = i / numTilesX; - uint32_t fullTileY = tileRow * fullTileH; - uint32_t fullActualTileH = std::min(fullTileH, fullH - fullTileY); - uint32_t nativeTileY = fullTileY / scale; - uint32_t nativeTileEndY = - (fullTileY + fullActualTileH + scale - 1) / scale; - VkDeviceSize kernelRowBytes = (VkDeviceSize)width * sizeof(float) * 4; - VkDescriptorBufferInfo accumBufferInfo{accumBuffers[i], 0, - VK_WHOLE_SIZE}; - VkDescriptorBufferInfo alignBufferInfo{alignmentBuffer, 0, VK_WHOLE_SIZE}; - VkDescriptorBufferInfo kpBufferInfo{ - kernelParamsBuffer, nativeTileY * kernelRowBytes, - (nativeTileEndY - nativeTileY) * kernelRowBytes}; - VkDescriptorBufferInfo mpBufferInfo{motionPriorBuffer, 0, VK_WHOLE_SIZE}; - VkDescriptorBufferInfo lmBufferInfo{localTileMaskBuffer, 0, VK_WHOLE_SIZE}; - - VkWriteDescriptorSet descriptorWrites[7] = {}; - descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[0].dstSet = accumSets[i]; - descriptorWrites[0].dstBinding = 0; - descriptorWrites[0].descriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - descriptorWrites[0].descriptorCount = 1; - descriptorWrites[0].pImageInfo = &imageInfo; - - descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[1].dstSet = accumSets[i]; - descriptorWrites[1].dstBinding = 1; - descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - descriptorWrites[1].descriptorCount = 1; - descriptorWrites[1].pBufferInfo = &accumBufferInfo; - - descriptorWrites[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[2].dstSet = accumSets[i]; - descriptorWrites[2].dstBinding = 2; - descriptorWrites[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - descriptorWrites[2].descriptorCount = 1; - descriptorWrites[2].pBufferInfo = &alignBufferInfo; - - descriptorWrites[3].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[3].dstSet = accumSets[i]; - descriptorWrites[3].dstBinding = 3; - descriptorWrites[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - descriptorWrites[3].descriptorCount = 1; - descriptorWrites[3].pBufferInfo = &kpBufferInfo; - - descriptorWrites[4].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[4].dstSet = accumSets[i]; - descriptorWrites[4].dstBinding = 4; - descriptorWrites[4].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - descriptorWrites[4].descriptorCount = 1; - descriptorWrites[4].pBufferInfo = &mpBufferInfo; - - 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; - - descriptorWrites[6].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - descriptorWrites[6].dstSet = accumSets[i]; - descriptorWrites[6].dstBinding = 6; - descriptorWrites[6].descriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - descriptorWrites[6].descriptorCount = 1; - descriptorWrites[6].pImageInfo = &refImageInfo; - - vkUpdateDescriptorSets(device, 7, descriptorWrites, 0, nullptr); - } - - if (tensorSets[i] == VK_NULL_HANDLE) { - VkDescriptorSetAllocateInfo tensorAlloc{}; - tensorAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - tensorAlloc.descriptorPool = descriptorPool; - tensorAlloc.descriptorSetCount = 1; - tensorAlloc.pSetLayouts = &tensorSetLayout; - VK_CHECK(vkAllocateDescriptorSets(device, &tensorAlloc, &tensorSets[i])); - - VkDescriptorImageInfo imageInfo{}; - imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - imageInfo.imageView = rgbFrame.viewY; - imageInfo.sampler = rgbFrame.sampler; - - uint32_t stTileH = (height + numTilesY - 1) / numTilesY; - uint32_t tileRow = i / numTilesX; - uint32_t stTileY = tileRow * stTileH; - uint32_t stActualTileH = std::min(stTileH, height - stTileY); - VkDeviceSize kernelRowBytes = (VkDeviceSize)width * sizeof(float) * 4; - VkDescriptorBufferInfo kpBufferInfo{ - kernelParamsBuffer, stTileY * kernelRowBytes, - stActualTileH * kernelRowBytes}; - - VkWriteDescriptorSet tensorWrites[2] = {}; - tensorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - tensorWrites[0].dstSet = tensorSets[i]; - tensorWrites[0].dstBinding = 0; - tensorWrites[0].descriptorType = - VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - tensorWrites[0].descriptorCount = 1; - tensorWrites[0].pImageInfo = &imageInfo; - - tensorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - tensorWrites[1].dstSet = tensorSets[i]; - tensorWrites[1].dstBinding = 1; - tensorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - tensorWrites[1].descriptorCount = 1; - tensorWrites[1].pBufferInfo = &kpBufferInfo; - - vkUpdateDescriptorSets(device, 2, tensorWrites, 0, nullptr); - } - } - - // 2. Alignment logic on CPU (to get offsets) - float offsetX = 0.0f, offsetY = 0.0f; - std::vector alignmentOffsets; - std::vector alignmentErrorMap; - std::vector localTileMask; - size_t copyCount = 0; - float frameWeight = 1.0f; - - TIME_START(cpuAlignment); - { - // Use cached grayscale from score calculation (no second HardwareBuffer lock) - auto currentPyramid = - buildPyramid(cachedGray.data.data(), width, height, 4); - if (currentIsFirstFrame) { - referencePyramid = std::move(currentPyramid); - localTileMask.assign((size_t)gridW * gridH, 1.0f); - } else { - int alignTileSize = enableSuperRes ? 16 : 32; - TileAlignment alignment = - computeTileAlignment(referencePyramid, currentPyramid, 64, alignTileSize); - - gridW = alignment.gridW; - gridH = alignment.gridH; - - uint32_t allocatedGridW = (width + alignTileSize - 1) / alignTileSize; - uint32_t allocatedGridH = (height + alignTileSize - 1) / alignTileSize; - uint32_t maxAllocatedPoints = allocatedGridW * allocatedGridH; - - copyCount = - std::min(alignment.offsets.size(), (size_t)maxAllocatedPoints); - alignmentOffsets = std::move(alignment.offsets); - alignmentErrorMap = std::move(alignment.errorMap); - - float sumX = 0, sumY = 0; - for (const auto &p : alignmentOffsets) { - sumX += p.x; - sumY += p.y; - } - if (!alignmentOffsets.empty()) { - 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); - float p90Err = computeScalarStats(alignmentErrorMap).p90; - LOGI("YUV fusion: frame=%zu sharpnessRatio=%.3f frameWeight=%.3f flatGood=%.3f flatArea=%.3f detailArea=%.3f p90Err=%.3f p90ErrRms=%.3f", - perf.totalFrames - 1, sharpnessRatio, frameWeight, localMap.flatGoodFraction, - localMap.flatAreaFraction, localMap.detailAreaFraction, - p90Err, std::sqrt(std::max(p90Err, 0.0f))); - } - } - TIME_END(cpuAlignment); // closes cpuAlignment + the cached-gray block - - // 3. Prepare Push Constants - float transform[6] = {1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; - PushConstants pc{}; - pc.t0 = transform[0]; - pc.t1 = transform[1]; - pc.t2 = transform[2]; - pc.t3 = transform[3]; - pc.t4 = transform[4]; - pc.t5 = transform[5]; - pc.offsetX = offsetX; - pc.offsetY = offsetY; - uint32_t scale = enableSuperRes ? 2 : 1; - pc.scale = static_cast(scale); - pc.width = width * scale; - pc.height = height * scale; - pc.baseNoise = 0.001f; - pc.isFirstFrame = currentIsFirstFrame ? 1 : 0; - pc.gridW = gridW; - pc.gridH = gridH; - pc.noiseAlpha = 0.005f; - pc.noiseBeta = 0.001f; - pc.frameWeight = frameWeight; - - if (!currentIsFirstFrame && pc.frameWeight < 0.12f) { - input.release(device); - isFirstFrame = false; - perf.skippedFrames++; - return false; - } - perf.keptFrames++; - perf.totalEffectiveFrames += pc.frameWeight; - - double yuvToRgbaGpuMs = -1.0; - double tensorGpuMs = -1.0; - double accumulateGpuMs = -1.0; - - // --- START PIPELINING SYNC POINT --- - // Wait for the PREVIOUS frame's GPU task to finish before we start recording - // new commands or mapping shared buffers. - vkQueueWaitIdle(vm.getComputeQueue()); - - // Safe to map alignment buffers and update frame-varying descriptors now - if (!currentIsFirstFrame && copyCount > 0) { - void *mapPtr = nullptr; - VkResult res = - vkMapMemory(device, alignmentUploadMemory, 0, VK_WHOLE_SIZE, 0, &mapPtr); - if (res == VK_SUCCESS && mapPtr != nullptr) { - memcpy(mapPtr, alignmentOffsets.data(), copyCount * sizeof(Point)); - vkUnmapMemory(device, alignmentUploadMemory); - } - - void *mpMapPtr = nullptr; - VkResult resMP = - vkMapMemory(device, motionPriorUploadMemory, 0, VK_WHOLE_SIZE, 0, - &mpMapPtr); - if (resMP == VK_SUCCESS && mpMapPtr != nullptr) { - memcpy(mpMapPtr, alignmentErrorMap.data(), copyCount * sizeof(float)); - vkUnmapMemory(device, motionPriorUploadMemory); - } - } - - if (localTileMask.empty()) { - localTileMask.assign((size_t)gridW * gridH, 1.0f); - } - void *lmMapPtr = nullptr; - VkResult resLM = - vkMapMemory(device, localTileMaskUploadMemory, 0, VK_WHOLE_SIZE, 0, - &lmMapPtr); - if (resLM == VK_SUCCESS && lmMapPtr != nullptr && !localTileMask.empty()) { - memcpy(lmMapPtr, localTileMask.data(), - localTileMask.size() * sizeof(float)); - vkUnmapMemory(device, localTileMaskUploadMemory); - } - - // Update yuvToRgbaSet with current input - { - VkDescriptorImageInfo imageInfo{input.sampler, input.viewY, - VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; - VkDescriptorImageInfo outInfo{VK_NULL_HANDLE, rgbFrame.viewY, - VK_IMAGE_LAYOUT_GENERAL}; - - VkWriteDescriptorSet writes[2] = {}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = yuvToRgbaSet; - writes[0].dstBinding = 0; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - writes[0].descriptorCount = 1; - writes[0].pImageInfo = &imageInfo; - - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = yuvToRgbaSet; - writes[1].dstBinding = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; - writes[1].descriptorCount = 1; - writes[1].pImageInfo = &outInfo; - - vkUpdateDescriptorSets(device, 2, writes, 0, nullptr); - } - - TIME_START(gpuDispatch); - // 3. Command Buffer Recording - VkCommandBuffer cb = vm.beginSingleTimeCommands(); - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdResetQueryPool(cb, gpuTimingQueryPool, 0, 8); - } - - // Transition Input Image Layout - VkImageMemoryBarrier imageBarrier{}; - imageBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - imageBarrier.image = input.image; - imageBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - imageBarrier.subresourceRange.baseMipLevel = 0; - imageBarrier.subresourceRange.levelCount = 1; - imageBarrier.subresourceRange.baseArrayLayer = 0; - imageBarrier.subresourceRange.layerCount = 1; - imageBarrier.srcAccessMask = 0; - imageBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &imageBarrier); - - // Transition RGB frame to GENERAL for writing - VkImageMemoryBarrier rgbWriteBarrier{}; - rgbWriteBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - rgbWriteBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - rgbWriteBarrier.newLayout = VK_IMAGE_LAYOUT_GENERAL; - rgbWriteBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - rgbWriteBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - rgbWriteBarrier.image = rgbFrame.image; - rgbWriteBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - rgbWriteBarrier.subresourceRange.baseMipLevel = 0; - rgbWriteBarrier.subresourceRange.levelCount = 1; - rgbWriteBarrier.subresourceRange.baseArrayLayer = 0; - rgbWriteBarrier.subresourceRange.layerCount = 1; - rgbWriteBarrier.srcAccessMask = 0; - rgbWriteBarrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &rgbWriteBarrier); - - // Dispatch YUV to RGBA Conversion - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 0); - } - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, yuvToRgbaPipeline); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - yuvToRgbaPipelineLayout, 0, 1, &yuvToRgbaSet, 0, - nullptr); - - struct { - uint32_t w; - uint32_t h; - } convPc = {width, height}; - vkCmdPushConstants(cb, yuvToRgbaPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, - 0, sizeof(convPc), &convPc); - vkCmdDispatch(cb, (width + 15) / 16, (height + 15) / 16, 1); - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 1); - } - - // Transition RGB frame to SHADER_READ_ONLY_OPTIMAL for sampling - VkImageMemoryBarrier rgbReadBarrier{}; - rgbReadBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - rgbReadBarrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; - rgbReadBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - rgbReadBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - rgbReadBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - rgbReadBarrier.image = rgbFrame.image; - rgbReadBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - rgbReadBarrier.subresourceRange.baseMipLevel = 0; - rgbReadBarrier.subresourceRange.levelCount = 1; - rgbReadBarrier.subresourceRange.baseArrayLayer = 0; - rgbReadBarrier.subresourceRange.layerCount = 1; - rgbReadBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - rgbReadBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 1, &rgbReadBarrier); - - // Copy RGB frame to referenceRgbFrame if first frame - if (pc.isFirstFrame) { - VkImageMemoryBarrier copyBarriers[2] = {}; - copyBarriers[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - copyBarriers[0].oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - copyBarriers[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - copyBarriers[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; - copyBarriers[0].dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - copyBarriers[0].image = rgbFrame.image; - copyBarriers[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyBarriers[0].subresourceRange.levelCount = 1; - copyBarriers[0].subresourceRange.layerCount = 1; - - copyBarriers[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - copyBarriers[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - copyBarriers[1].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - copyBarriers[1].srcAccessMask = 0; - copyBarriers[1].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - copyBarriers[1].image = referenceRgbFrame.image; - copyBarriers[1].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyBarriers[1].subresourceRange.levelCount = 1; - copyBarriers[1].subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, - nullptr, 2, copyBarriers); - - VkImageCopy copyRegion{}; - copyRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyRegion.srcSubresource.layerCount = 1; - copyRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - copyRegion.dstSubresource.layerCount = 1; - copyRegion.extent = {width, height, 1}; - - vkCmdCopyImage(cb, rgbFrame.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - referenceRgbFrame.image, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Region); - - VkImageMemoryBarrier postCopyBarriers[2] = {}; - postCopyBarriers[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - postCopyBarriers[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - postCopyBarriers[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - postCopyBarriers[0].srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - postCopyBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - postCopyBarriers[0].image = rgbFrame.image; - postCopyBarriers[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - postCopyBarriers[0].subresourceRange.levelCount = 1; - postCopyBarriers[0].subresourceRange.layerCount = 1; - - postCopyBarriers[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; - postCopyBarriers[1].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - postCopyBarriers[1].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - postCopyBarriers[1].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - postCopyBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - postCopyBarriers[1].image = referenceRgbFrame.image; - postCopyBarriers[1].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - postCopyBarriers[1].subresourceRange.levelCount = 1; - postCopyBarriers[1].subresourceRange.layerCount = 1; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, - nullptr, 2, postCopyBarriers); - } - - // Clear Accumulators if first frame - if (pc.isFirstFrame) { - for (int i = 0; i < numTiles; ++i) { - vkCmdFillBuffer(cb, accumBuffers[i], 0, VK_WHOLE_SIZE, 0); - } - // Barrier to ensure clear is done before usage? - // SingleTimeCommands end with a queue submission which has implicit - // ordering if we record linearly? No, we need a barrier if we use it in the - // SAME command buffer as Dispatch. Yes, we are in the same CB. - - VkMemoryBarrier memBarrier = {}; - memBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - memBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - memBarrier.dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, - &memBarrier, 0, nullptr, 0, nullptr); - } - - bool needAlignmentUpload = (!currentIsFirstFrame && copyCount > 0); - VkBufferMemoryBarrier uploadSrcBarriers[3] = {}; - uint32_t uploadSrcBarrierCount = 0; - auto appendUploadSrcBarrier = [&](VkBuffer buffer) { - VkBufferMemoryBarrier &barrier = uploadSrcBarriers[uploadSrcBarrierCount++]; - barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - barrier.buffer = buffer; - barrier.offset = 0; - barrier.size = VK_WHOLE_SIZE; - }; - if (needAlignmentUpload) { - appendUploadSrcBarrier(alignmentUploadBuffer); - appendUploadSrcBarrier(motionPriorUploadBuffer); - } - appendUploadSrcBarrier(localTileMaskUploadBuffer); - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, - uploadSrcBarrierCount, uploadSrcBarriers, 0, nullptr); - - if (needAlignmentUpload) { - VkBufferCopy alignCopy{}; - alignCopy.size = copyCount * sizeof(Point); - vkCmdCopyBuffer(cb, alignmentUploadBuffer, alignmentBuffer, 1, &alignCopy); - - VkBufferCopy motionCopy{}; - motionCopy.size = copyCount * sizeof(float); - vkCmdCopyBuffer(cb, motionPriorUploadBuffer, motionPriorBuffer, 1, - &motionCopy); - } - if (!localTileMask.empty()) { - VkBufferCopy localMaskCopy{}; - localMaskCopy.size = localTileMask.size() * sizeof(float); - vkCmdCopyBuffer(cb, localTileMaskUploadBuffer, localTileMaskBuffer, 1, - &localMaskCopy); - } - - VkBufferMemoryBarrier uploadDstBarriers[3] = {}; - uint32_t uploadDstBarrierCount = 0; - auto appendUploadDstBarrier = [&](VkBuffer buffer) { - VkBufferMemoryBarrier &barrier = uploadDstBarriers[uploadDstBarrierCount++]; - barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - barrier.buffer = buffer; - barrier.offset = 0; - barrier.size = VK_WHOLE_SIZE; - }; - if (needAlignmentUpload) { - appendUploadDstBarrier(alignmentBuffer); - appendUploadDstBarrier(motionPriorBuffer); - } - if (!localTileMask.empty()) { - appendUploadDstBarrier(localTileMaskBuffer); - } - if (uploadDstBarrierCount > 0) { - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, - uploadDstBarrierCount, uploadDstBarriers, 0, nullptr); - } - - // Phase 2: Compute Structure Tensor (only on first/reference frame) - // The kernel shape is driven by the reference frame's local structure. - // Subsequent frames reuse it — avoids (N-1) expensive GPU dispatches. - if (currentIsFirstFrame) { - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 2); - } - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, tensorPipeline); - - for (int y = 0; y < numTilesY; ++y) { - for (int x = 0; x < numTilesX; ++x) { - int i = y * numTilesX + x; - - uint32_t stFullW = width; - uint32_t stFullH = height; - uint32_t stTileW = (stFullW + numTilesX - 1) / numTilesX; - uint32_t stTileH = (stFullH + numTilesY - 1) / numTilesY; - - PushConstants stPC = pc; - stPC.tileX = x * stTileW; - stPC.tileY = y * stTileH; - stPC.tileW = std::min(stTileW, stFullW - stPC.tileX); - stPC.tileH = std::min(stTileH, stFullH - stPC.tileY); - stPC.width = stFullW; - stPC.height = stFullH; - stPC.offsetY = static_cast(stPC.tileY); - - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - tensorPipelineLayout, 0, 1, &tensorSets[i], 0, - nullptr); - vkCmdPushConstants(cb, tensorPipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(stPC), &stPC); - vkCmdDispatch(cb, (stPC.tileW + 15) / 16, (stPC.tileH + 15) / 16, 1); - } - } - - // Barrier: ST writes must finish before Accumulate reads kernelParams - VkBufferMemoryBarrier stBarrier{}; - stBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - stBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - stBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - stBarrier.buffer = kernelParamsBuffer; - stBarrier.size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, - &stBarrier, 0, nullptr); - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 3); - } - } - - // The previous frame is already fully retired by vkQueueWaitIdle() above. - // Avoid issuing redundant per-tile carry-over barriers here. - - // Pass 2: Accumulate - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 4); - } - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, accumulatePipeline); - - uint32_t fullW = pc.width; - uint32_t fullH = pc.height; - uint32_t tileW = (fullW + numTilesX - 1) / numTilesX; - uint32_t tileH = (fullH + numTilesY - 1) / numTilesY; - - for (int y = 0; y < numTilesY; ++y) { - for (int x = 0; x < numTilesX; ++x) { - int i = y * numTilesX + x; - pc.tileX = x * tileW; - pc.tileY = y * tileH; - pc.tileW = std::min(tileW, fullW - pc.tileX); - pc.tileH = std::min(tileH, fullH - pc.tileY); - pc.bufferStride = tileW + 16; // The allocated stride - pc.offsetY = static_cast(pc.tileY / (enableSuperRes ? 2 : 1)); - - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - pipelineLayout, 0, 1, &accumSets[i], 0, nullptr); - vkCmdPushConstants(cb, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, - sizeof(pc), &pc); - vkCmdDispatch(cb, (pc.tileW + 15) / 16, (pc.tileH + 15) / 16, 1); - } - } - - // Global barrier between frames to ensure ALL accumulator tiles are finished - // writing before the next frame begins reading or before normalization - VkMemoryBarrier postBarrier{}; - postBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER; - postBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - postBarrier.dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &postBarrier, - 0, nullptr, 0, nullptr); - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - gpuTimingQueryPool, 5); - } - - vm.endSingleTimeCommands(cb); - if (gpuTimestampSupported && gpuTimingQueryPool != VK_NULL_HANDLE) { - auto ticksToMs = [&](uint64_t begin, uint64_t end) { - return (double)(end - begin) * (double)gpuTimestampPeriodNs / 1.0e6; - }; - - uint64_t yuvTimestamps[2] = {}; - VkResult yuvResult = vkGetQueryPoolResults( - device, gpuTimingQueryPool, 0, 2, sizeof(yuvTimestamps), yuvTimestamps, - sizeof(uint64_t), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - if (yuvResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) { - yuvToRgbaGpuMs = ticksToMs(yuvTimestamps[0], yuvTimestamps[1]); - } - - if (currentIsFirstFrame) { - uint64_t tensorTimestamps[2] = {}; - VkResult tensorResult = vkGetQueryPoolResults( - device, gpuTimingQueryPool, 2, 2, sizeof(tensorTimestamps), - tensorTimestamps, sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - if (tensorResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) { - tensorGpuMs = ticksToMs(tensorTimestamps[0], tensorTimestamps[1]); - } - } - - uint64_t accumulateTimestamps[2] = {}; - VkResult accumulateResult = vkGetQueryPoolResults( - device, gpuTimingQueryPool, 4, 2, sizeof(accumulateTimestamps), - accumulateTimestamps, sizeof(uint64_t), - VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); - if (accumulateResult == VK_SUCCESS && gpuTimestampPeriodNs > 0.0f) { - accumulateGpuMs = - ticksToMs(accumulateTimestamps[0], accumulateTimestamps[1]); - } - } - TIME_END(gpuDispatch); - - isFirstFrame = false; - input.release(device); - return true; -} - -bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth, - uint32_t outHeight, uint32_t stride, - int rotation) { - // Lower CPU priority for this thread during heavy processing - setpriority(PRIO_PROCESS, 0, 10); - - YuvStackPerfStats perf; - const auto startTotal = std::chrono::steady_clock::now(); - - // Process all queued frames first - isFirstFrame = true; - if (pendingFrames.empty()) { - return false; - } - - // 1. Calculate scores and extract grayscale in a single lock per frame - TIME_START(scoreCalculation); - for (auto &frame : pendingFrames) { - AHardwareBuffer_Desc desc; - AHardwareBuffer_describe(frame.buffer, &desc); - void *lockedData = nullptr; - if (AHardwareBuffer_lock(frame.buffer, AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN, - -1, nullptr, &lockedData) == 0) { - uint8_t *srcY = (uint8_t *)lockedData; - int stride = desc.stride; - bool is10bit = (desc.format == 0x36); - - // Extract grayscale - frame.grayY.width = width; - frame.grayY.height = height; - frame.grayY.data.resize((size_t)width * height); - for (uint32_t y = 0; y < height; ++y) { - if (is10bit) { - uint16_t *rowPtr = (uint16_t *)(srcY + y * stride * 2); - for (uint32_t x = 0; x < width; ++x) { - frame.grayY.data[y * width + x] = (uint8_t)(rowPtr[x] >> 8); - } - } else { - memcpy(frame.grayY.data.data() + y * width, srcY + y * stride, width); - } - } - - // Calculate score from the same locked data - long long score = 0; - int step = 8; - for (uint32_t y = step; y < height - step; y += step) { - for (uint32_t x = step; x < width - step; x += step) { - int val = frame.grayY.data[y * width + x]; - int valR = frame.grayY.data[y * width + x + 1]; - int valB = frame.grayY.data[(y + 1) * width + x]; - score += std::abs(val - valR); - score += std::abs(val - valB); - } - } - frame.score = (float)score; - - AHardwareBuffer_unlock(frame.buffer, nullptr); - } - } - TIME_END(scoreCalculation); - perf.scoreCalculationMs = elapsed_scoreCalculation; - - // 2. Sort pendingFrames by score descending - 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()); - - VulkanManager &vm = VulkanManager::getInstance(); - VkDevice device = vm.getDevice(); - if (device == VK_NULL_HANDLE) { - LOGE("processStack: Vulkan device is NULL or NOT INITIALIZED"); - return false; - } - - VkDeviceSize rowBytes = (VkDeviceSize)outWidth * 4; - VkDeviceSize outSize = rowBytes * (VkDeviceSize)outHeight; - VkPhysicalDeviceProperties deviceProperties{}; - vkGetPhysicalDeviceProperties(vm.getPhysicalDevice(), &deviceProperties); - VkDeviceSize maxStorageBufferRange = - deviceProperties.limits.maxStorageBufferRange; - if (maxStorageBufferRange > 0 && rowBytes > maxStorageBufferRange) { - LOGE("processStack: one output row exceeds storage buffer range. row=%llu " - "limit=%llu output=%ux%u", - (unsigned long long)rowBytes, - (unsigned long long)maxStorageBufferRange, outWidth, outHeight); - return false; - } - uint32_t maxStripeRows = outHeight; - if (maxStorageBufferRange > 0 && outSize > maxStorageBufferRange) { - maxStripeRows = std::max( - 1, std::min( - outHeight, - static_cast(maxStorageBufferRange / rowBytes))); - LOGI("processStack: output storage buffer range requires striped output. " - "out=%llu limit=%llu output=%ux%u stripeRows=%u", - (unsigned long long)outSize, - (unsigned long long)maxStorageBufferRange, outWidth, outHeight, - maxStripeRows); - } - - TIME_START(allFramesProcessing); - int frameIdx = 0; - for (auto &frame : pendingFrames) { - // LOGI("processStack: Processing frame %d, score %f", frameIdx, - // frame.score); - if (!processFrame(frame.buffer, frame.score, frame.grayY, perf)) { - // LOGW("processStack: Skipped or failed frame %d", frameIdx); - } - // Release grayscale cache to free memory as soon as it's consumed - frame.grayY.data.clear(); - frame.grayY.data.shrink_to_fit(); - AHardwareBuffer_release(frame.buffer); - frameIdx++; - } - pendingFrames.clear(); - vkQueueWaitIdle(vm.getComputeQueue()); - vkResetDescriptorPool(device, descriptorPool, 0); - resetDescriptorHandles(); - - TIME_END(allFramesProcessing); - perf.allFramesProcessingMs = elapsed_allFramesProcessing; - - if (!outBitmap || isFirstFrame) // Check again after processing - return false; - - uint32_t scale = enableSuperRes ? 2 : 1; - uint32_t sensorW = width * scale; - uint32_t sensorH = height * scale; - - // Calculate the crop and rotation matrix - float transform[6] = {1, 0, 0, 0, 1, 0}; - - // Logic from RotatePlane + Cropping in legacy code: - // 1. Determine rotated dimensions of sensor - int rotW = (rotation == 90 || rotation == 270) ? sensorH : sensorW; - int rotH = (rotation == 90 || rotation == 270) ? sensorW : sensorH; - - float cropX = (rotW - (float)outWidth) / 2.0f; - float cropY = (rotH - (float)outHeight) / 2.0f; - - float sW = (float)sensorW; - float sH = (float)sensorH; - - switch (rotation) { - case 0: - transform[0] = 1.0f; - transform[1] = 0.0f; - transform[2] = cropX; - transform[3] = 0.0f; - transform[4] = 1.0f; - transform[5] = cropY; - break; - case 90: - // Inverse of 90 deg clockwise: (x,y) -> (y, H-1-x) - transform[0] = 0.0f; - transform[1] = 1.0f; - transform[2] = cropY; - transform[3] = -1.0f; - transform[4] = 0.0f; - transform[5] = sH - 1.0f - cropX; - break; - case 180: - // Inverse of 180 deg: (x,y) -> (W-1-x, H-1-y) - transform[0] = -1.0f; - transform[1] = 0.0f; - transform[2] = sW - 1.0f - cropX; - transform[3] = 0.0f; - transform[4] = -1.0f; - transform[5] = sH - 1.0f - cropY; - break; - case 270: - // Inverse of 270 deg clockwise: (x,y) -> (W-1-y, x) - transform[0] = 0.0f; - transform[1] = -1.0f; - transform[2] = sW - 1.0f - cropY; - transform[3] = 1.0f; - transform[4] = 0.0f; - transform[5] = cropX; - break; - } - - uint32_t fullW = sensorW; - uint32_t fullH = sensorH; - uint32_t tileW = (fullW + numTilesX - 1) / numTilesX; - uint32_t tileH = (fullH + numTilesY - 1) / numTilesY; - - int numTiles = numTilesX * numTilesY; - - TIME_START(normalizationDispatch); - TIME_START(outputCopy); - for (uint32_t stripeY = 0; stripeY < outHeight; stripeY += maxStripeRows) { - const uint32_t stripeRows = std::min(maxStripeRows, outHeight - stripeY); - const VkDeviceSize stripeSize = rowBytes * (VkDeviceSize)stripeRows; - - VkCommandBuffer cb = vm.beginSingleTimeCommands(); - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, normalizePipeline); - - std::vector stripeSets; - stripeSets.reserve(numTiles); - - for (int i = 0; i < numTiles; ++i) { - struct { - float t0, t1, t2, t3, t4, t5; - uint32_t outWidth; - uint32_t outHeight; - uint32_t outOriginX; - uint32_t outOriginY; - uint32_t outBufferOriginY; - uint32_t sensorWidth; - uint32_t sensorHeight; - uint32_t tileX; - uint32_t tileY; - uint32_t tileW; - uint32_t tileH; - uint32_t bufferStride; - } npc; - memcpy(&npc, transform, 6 * sizeof(float)); - npc.outWidth = outWidth; - npc.outHeight = outHeight; - npc.outBufferOriginY = stripeY; - int tx = i % numTilesX; - int ty = i / numTilesX; - npc.tileX = tx * tileW; - npc.tileY = ty * tileH; - npc.tileW = std::min(tileW, fullW - npc.tileX); - npc.tileH = std::min(tileH, fullH - npc.tileY); - npc.bufferStride = tileW + 16; - npc.sensorWidth = fullW; - npc.sensorHeight = fullH; - - const int tileStartX = static_cast(npc.tileX); - const int tileStartY = static_cast(npc.tileY); - const int tileEndX = tileStartX + static_cast(npc.tileW); - const int tileEndY = tileStartY + static_cast(npc.tileH); - int dispatchMinX = 0; - int dispatchMinY = static_cast(stripeY); - int dispatchMaxX = static_cast(outWidth); - int dispatchMaxY = static_cast(stripeY + stripeRows); - - switch (rotation) { - case 0: - dispatchMinX = - std::max(0, static_cast(std::floor(tileStartX - cropX)) - 1); - dispatchMaxX = std::min(static_cast(outWidth), - static_cast(std::ceil(tileEndX - cropX)) + 1); - dispatchMinY = std::max(dispatchMinY, - static_cast(std::floor(tileStartY - cropY)) - 1); - dispatchMaxY = std::min(dispatchMaxY, - static_cast(std::ceil(tileEndY - cropY)) + 1); - break; - case 90: - dispatchMinX = - std::max(0, static_cast(std::floor(sH - cropX - tileEndY)) - 1); - dispatchMaxX = - std::min(static_cast(outWidth), - static_cast(std::ceil(sH - cropX - tileStartY)) + 1); - dispatchMinY = - std::max(dispatchMinY, - static_cast(std::floor(tileStartX - cropY)) - 1); - dispatchMaxY = std::min(dispatchMaxY, - static_cast(std::ceil(tileEndX - cropY)) + 1); - break; - case 180: - dispatchMinX = - std::max(0, static_cast(std::floor(sW - cropX - tileEndX)) - 1); - dispatchMaxX = - std::min(static_cast(outWidth), - static_cast(std::ceil(sW - cropX - tileStartX)) + 1); - dispatchMinY = - std::max(dispatchMinY, - static_cast(std::floor(sH - cropY - tileEndY)) - 1); - dispatchMaxY = - std::min(dispatchMaxY, - static_cast(std::ceil(sH - cropY - tileStartY)) + 1); - break; - case 270: - dispatchMinX = - std::max(0, static_cast(std::floor(tileStartY - cropX)) - 1); - dispatchMaxX = std::min(static_cast(outWidth), - static_cast(std::ceil(tileEndY - cropX)) + 1); - dispatchMinY = - std::max(dispatchMinY, - static_cast(std::floor(sW - cropY - tileEndX)) - 1); - dispatchMaxY = - std::min(dispatchMaxY, - static_cast(std::ceil(sW - cropY - tileStartX)) + 1); - break; - default: - break; - } - - if (dispatchMinX >= dispatchMaxX || dispatchMinY >= dispatchMaxY) - continue; - - VkDescriptorSet normalizeSet = VK_NULL_HANDLE; - VkDescriptorSetAllocateInfo allocInfo{}; - allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; - allocInfo.descriptorPool = descriptorPool; - allocInfo.descriptorSetCount = 1; - allocInfo.pSetLayouts = &normalizeSetLayout; - VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &normalizeSet)); - stripeSets.push_back(normalizeSet); - - VkDescriptorBufferInfo outBufferInfo{stagingBuffer, 0, stripeSize}; - VkDescriptorBufferInfo accumBufferInfo{accumBuffers[i], 0, VK_WHOLE_SIZE}; - - VkWriteDescriptorSet writes[2] = {}; - writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[0].dstSet = normalizeSet; - writes[0].dstBinding = 0; - writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[0].descriptorCount = 1; - writes[0].pBufferInfo = &outBufferInfo; - - writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; - writes[1].dstSet = normalizeSet; - writes[1].dstBinding = 1; - writes[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; - writes[1].descriptorCount = 1; - writes[1].pBufferInfo = &accumBufferInfo; - - vkUpdateDescriptorSets(device, 2, writes, 0, nullptr); - - const uint32_t dispatchW = - static_cast(dispatchMaxX - dispatchMinX); - const uint32_t dispatchH = - static_cast(dispatchMaxY - dispatchMinY); - npc.outOriginX = static_cast(dispatchMinX); - npc.outOriginY = static_cast(dispatchMinY); - - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - normalizePipelineLayout, 0, 1, &normalizeSet, 0, - nullptr); - - vkCmdPushConstants(cb, normalizePipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(npc), &npc); - - vkCmdDispatch(cb, (dispatchW + 15) / 16, (dispatchH + 15) / 16, 1); - } - - VkBufferMemoryBarrier hostBarrier{}; - hostBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - hostBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - hostBarrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; - hostBarrier.buffer = stagingBuffer; - hostBarrier.size = stripeSize; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, 1, - &hostBarrier, 0, nullptr); - - vm.endSingleTimeCommands(cb); - vkQueueWaitIdle(vm.getComputeQueue()); - - void *hostData; - vkMapMemory(device, stagingMemory, 0, stripeSize, 0, &hostData); - for (uint32_t y = 0; y < stripeRows; ++y) { - memcpy((uint8_t *)outBitmap + (stripeY + y) * stride, - (uint8_t *)hostData + y * rowBytes, (size_t)rowBytes); - } - vkUnmapMemory(device, stagingMemory); - - if (!stripeSets.empty()) { - vkFreeDescriptorSets(device, descriptorPool, - static_cast(stripeSets.size()), - stripeSets.data()); - } - } - TIME_END(outputCopy); - TIME_END(normalizationDispatch); - perf.normalizationDispatchMs = elapsed_normalizationDispatch; - perf.outputCopyMs = elapsed_outputCopy; - - perf.totalMs = std::chrono::duration( - std::chrono::steady_clock::now() - startTotal) - .count(); - perf.logSummary(outWidth, outHeight, scale); - - return true; -} - -bool VulkanImageStacker::resetForReuse() { - VulkanManager &vm = VulkanManager::getInstance(); - VkDevice device = vm.getDevice(); - if (device == VK_NULL_HANDLE) { - LOGE("resetForReuse: Vulkan device is NULL"); - return false; - } - - vkQueueWaitIdle(vm.getComputeQueue()); - releasePendingFrames(); - referencePyramid.clear(); - referenceFrameScore = 0.0f; - isFirstFrame = true; - - if (descriptorPool != VK_NULL_HANDLE) { - vkResetDescriptorPool(device, descriptorPool, 0); - } - resetDescriptorHandles(); - return true; -} - -void VulkanImageStacker::resetDescriptorHandles() { - yuvToRgbaSet = VK_NULL_HANDLE; - std::fill(accumSets.begin(), accumSets.end(), (VkDescriptorSet)VK_NULL_HANDLE); - std::fill(tensorSets.begin(), tensorSets.end(), (VkDescriptorSet)VK_NULL_HANDLE); - std::fill(normalizeSets.begin(), normalizeSets.end(), - (VkDescriptorSet)VK_NULL_HANDLE); -} - -void VulkanImageStacker::releasePendingFrames() { - for (auto &frame : pendingFrames) { - frame.grayY.data.clear(); - if (frame.buffer != nullptr) { - AHardwareBuffer_release(frame.buffer); - } - } - pendingFrames.clear(); -} - -void VulkanImageStacker::releaseVulkanResources() { - VkDevice device = VulkanManager::getInstance().getDevice(); - if (device == VK_NULL_HANDLE) - return; - if (descriptorPool != VK_NULL_HANDLE) - vkDestroyDescriptorPool(device, descriptorPool, nullptr); - if (descriptorSetLayout != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); - if (pipelineLayout != VK_NULL_HANDLE) - vkDestroyPipelineLayout(device, pipelineLayout, nullptr); - if (accumulatePipeline != VK_NULL_HANDLE) - vkDestroyPipeline(device, accumulatePipeline, nullptr); - - if (normalizeSetLayout != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(device, normalizeSetLayout, nullptr); - if (normalizePipelineLayout != VK_NULL_HANDLE) - vkDestroyPipelineLayout(device, normalizePipelineLayout, nullptr); - if (normalizePipeline != VK_NULL_HANDLE) - vkDestroyPipeline(device, normalizePipeline, nullptr); - if (gpuTimingQueryPool != VK_NULL_HANDLE) - vkDestroyQueryPool(device, gpuTimingQueryPool, nullptr); - - if (immutableSampler != VK_NULL_HANDLE) - vkDestroySampler(device, immutableSampler, nullptr); - - if (ycbcrConversion != VK_NULL_HANDLE) { - auto pfnDestroy = (PFN_vkDestroySamplerYcbcrConversion)vkGetDeviceProcAddr( - device, "vkDestroySamplerYcbcrConversion"); - if (pfnDestroy) - pfnDestroy(device, ycbcrConversion, nullptr); - } - - for (size_t i = 0; i < accumBuffers.size(); ++i) { - if (accumBuffers[i] != VK_NULL_HANDLE) - vkDestroyBuffer(device, accumBuffers[i], nullptr); - if (accumMemories[i] != VK_NULL_HANDLE) - vkFreeMemory(device, accumMemories[i], nullptr); - } - - if (stagingBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, stagingBuffer, nullptr); - if (stagingMemory != VK_NULL_HANDLE) - vkFreeMemory(device, stagingMemory, nullptr); - - if (alignmentUploadBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, alignmentUploadBuffer, nullptr); - if (alignmentUploadMemory != VK_NULL_HANDLE) - vkFreeMemory(device, alignmentUploadMemory, nullptr); - if (alignmentBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, alignmentBuffer, nullptr); - if (alignmentMemory != VK_NULL_HANDLE) - vkFreeMemory(device, alignmentMemory, nullptr); - - if (kernelParamsBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, kernelParamsBuffer, nullptr); - if (kernelParamsMemory != VK_NULL_HANDLE) - vkFreeMemory(device, kernelParamsMemory, nullptr); - - if (motionPriorBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, motionPriorBuffer, nullptr); - if (motionPriorMemory != VK_NULL_HANDLE) - vkFreeMemory(device, motionPriorMemory, nullptr); - if (motionPriorUploadBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, motionPriorUploadBuffer, nullptr); - if (motionPriorUploadMemory != VK_NULL_HANDLE) - vkFreeMemory(device, motionPriorUploadMemory, nullptr); - if (localTileMaskBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, localTileMaskBuffer, nullptr); - if (localTileMaskMemory != VK_NULL_HANDLE) - vkFreeMemory(device, localTileMaskMemory, nullptr); - if (localTileMaskUploadBuffer != VK_NULL_HANDLE) - vkDestroyBuffer(device, localTileMaskUploadBuffer, nullptr); - if (localTileMaskUploadMemory != VK_NULL_HANDLE) - vkFreeMemory(device, localTileMaskUploadMemory, nullptr); - - if (tensorSetLayout != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(device, tensorSetLayout, nullptr); - if (tensorPipelineLayout != VK_NULL_HANDLE) - vkDestroyPipelineLayout(device, tensorPipelineLayout, nullptr); - if (tensorPipeline != VK_NULL_HANDLE) - vkDestroyPipeline(device, tensorPipeline, nullptr); - - if (yuvToRgbaLayout != VK_NULL_HANDLE) - vkDestroyDescriptorSetLayout(device, yuvToRgbaLayout, nullptr); - if (yuvToRgbaPipelineLayout != VK_NULL_HANDLE) - vkDestroyPipelineLayout(device, yuvToRgbaPipelineLayout, nullptr); - if (yuvToRgbaPipeline != VK_NULL_HANDLE) - vkDestroyPipeline(device, yuvToRgbaPipeline, nullptr); - - rgbFrame.release(device); - referenceRgbFrame.release(device); -} diff --git a/app/src/main/cpp/vulkan_stacker.h b/app/src/main/cpp/vulkan_stacker.h deleted file mode 100644 index 722f2618..00000000 --- a/app/src/main/cpp/vulkan_stacker.h +++ /dev/null @@ -1,144 +0,0 @@ -#pragma once - -#include "stacking_utils.h" -#include "vulkan_manager.h" -#include "vulkan_utils.h" -#include - -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 accumBuffers; - std::vector accumMemories; - - VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE; - VkDescriptorPool descriptorPool = VK_NULL_HANDLE; - std::vector 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 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 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 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 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(); -}; diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index ff436ed6..0ab3a92a 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -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 diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt new file mode 100644 index 00000000..ccb31b92 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt @@ -0,0 +1,1606 @@ +package com.hinnka.mycamera.processor + +import android.graphics.Bitmap +import android.graphics.ColorSpace +import android.graphics.ImageFormat +import android.opengl.EGL14 +import android.opengl.EGLConfig +import android.opengl.EGLContext +import android.opengl.EGLDisplay +import android.opengl.EGLSurface +import android.opengl.GLES30 +import android.opengl.GLES31 +import androidx.core.graphics.createBitmap +import com.hinnka.mycamera.model.SafeImage +import com.hinnka.mycamera.utils.LargeDirectBuffer +import com.hinnka.mycamera.utils.PLog +import java.nio.ByteBuffer +import kotlin.math.max + +class GlesYuvStacker( + private val width: Int, + private val height: Int, + private val outputWidth: Int, + private val outputHeight: Int, + private val rotation: Int, + private val colorSpace: ColorSpace, + private val inputFormat: Int, +) { + private data class TextureLevel(val texture: Int, val width: Int, val height: Int) + + private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY + private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT + private var eglSurface: EGLSurface = EGL14.EGL_NO_SURFACE + + private val textures = ArrayList() + private val programs = ArrayList() + private val framebuffers = ArrayList() + + private var downsampleProgram = 0 + private var structureProgram = 0 + private var alignProgram = 0 + private var smoothFlowProgram = 0 + private var robustnessProgram = 0 + private var tileMaskProgram = 0 + private var accumulateProgram = 0 + private var normalizeProgram = 0 + private var p010LumaProgram = 0 + private var p010ChromaProgram = 0 + private var planarChroma8Program = 0 + private var planarChroma16Program = 0 + + private var renderFbo = 0 + private var readbackFbo = 0 + + private var refY = 0 + private var refCbCr = 0 + private var curY = 0 + private var curCbCr = 0 + private var refYStaging = 0 + private var refCbCrStaging = 0 + private var curYStaging = 0 + private var curCbCrStaging = 0 + private var planarUStaging = 0 + private var planarVStaging = 0 + private var kernelTexture = 0 + private var flowTexture = 0 + private var flowScratchTexture = 0 + private var robustnessTexture = 0 + private var tileMaskTexture = 0 + private var accumulatorTexture = 0 + private var accumulatorScratchTexture = 0 + private var currentAccumulatorTexture = 0 + private var outputTexture = 0 + + private var gridWidth = 0 + private var gridHeight = 0 + private val renderOutputWidth = outputWidth + private val renderOutputHeight = outputHeight + private val normalizedRotation = normalizeRotation(rotation) + private val cpuRotateReadback = normalizedRotation == 90 || normalizedRotation == 270 + private val gpuOutputWidth = if (cpuRotateReadback) renderOutputHeight else renderOutputWidth + private val gpuOutputHeight = if (cpuRotateReadback) renderOutputWidth else renderOutputHeight + private val highPrecisionInput = inputFormat == ImageFormat.YCBCR_P010 + private val lumaInternalFormat = if (highPrecisionInput) GLES30.GL_R16F else GLES30.GL_R8 + private val chromaInternalFormat = if (highPrecisionInput) GLES30.GL_RG16F else GLES30.GL_RG8 + private val chromaWidth = (width + 1) / 2 + private val chromaHeight = (height + 1) / 2 + + fun process(images: List): Bitmap? { + if (images.isEmpty() || width <= 0 || height <= 0 || outputWidth <= 0 || outputHeight <= 0) { + return null + } + if (!supportsImageFormat(inputFormat)) { + PLog.w(TAG, "Unsupported GLES YUV stack format: $inputFormat") + return null + } + if (images.any { it.format != inputFormat }) { + PLog.w(TAG, "Mixed YUV formats in one stack are not supported") + return null + } + + val startTime = System.currentTimeMillis() + try { + initEgl() + ensureGles31() + initPrograms() + initResources() + PLog.d( + TAG, + "GLES stack format=${formatName(inputFormat)} internal=${if (highPrecisionInput) "R16F/RG16F" else "R8/RG8"} flowGrid=${FLOW_GRID_SPACING}px grid=${gridWidth}x${gridHeight}" + ) + + if (!uploadImagePlanes(images.first(), refY, refCbCr, refYStaging, refCbCrStaging, "reference")) { + return null + } + + val refPyramid = createPyramid(refY) + val curPyramid = createPyramid(curY) + buildPyramid(refPyramid) + computeStructureTensor(refY) + clearAccumulator() + accumulateFrame(refY, refCbCr, isReference = true) + + for (index in 1 until images.size) { + if (!uploadImagePlanes(images[index], curY, curCbCr, curYStaging, curCbCrStaging, "frame $index")) { + PLog.w(TAG, "Failed to upload frame $index YUV planes") + return null + } + buildPyramid(curPyramid) + alignCurrentToReference(refPyramid, curPyramid) + smoothFlow() + computeRobustness() + computeTileMask() + accumulateFrame(curY, curCbCr, isReference = false) + } + + normalizeOutput() + val bitmap = readOutputBitmap() ?: return null + PLog.i(TAG, "GLES YUV stacking completed in ${System.currentTimeMillis() - startTime}ms") + return bitmap + } catch (e: Exception) { + PLog.e(TAG, "GLES YUV stacking failed", e) + return null + } finally { + release() + } + } + + private fun initEgl() { + eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) + if (eglDisplay == EGL14.EGL_NO_DISPLAY) { + throw IllegalStateException("eglGetDisplay failed") + } + + val version = IntArray(2) + if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) { + throw IllegalStateException("eglInitialize failed: ${EGL14.eglGetError()}") + } + + val config = chooseConfig(EGL_OPENGL_ES3_BIT_KHR) ?: chooseConfig(EGL14.EGL_OPENGL_ES2_BIT) + ?: throw IllegalStateException("No EGL config for GLES") + + val contextAttribs31 = intArrayOf( + EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, + EGL_CONTEXT_MINOR_VERSION_KHR, 1, + EGL14.EGL_NONE, + ) + eglContext = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, contextAttribs31, 0) + if (eglContext == EGL14.EGL_NO_CONTEXT) { + val contextAttribs3 = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE) + eglContext = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, contextAttribs3, 0) + } + if (eglContext == EGL14.EGL_NO_CONTEXT) { + throw IllegalStateException("eglCreateContext failed: ${EGL14.eglGetError()}") + } + + val surfaceAttribs = intArrayOf( + EGL14.EGL_WIDTH, max(1, gpuOutputWidth), + EGL14.EGL_HEIGHT, max(1, gpuOutputHeight), + EGL14.EGL_NONE, + ) + eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, config, surfaceAttribs, 0) + if (eglSurface == EGL14.EGL_NO_SURFACE) { + throw IllegalStateException("eglCreatePbufferSurface failed: ${EGL14.eglGetError()}") + } + + if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) { + throw IllegalStateException("eglMakeCurrent failed: ${EGL14.eglGetError()}") + } + } + + private fun chooseConfig(renderableType: Int): EGLConfig? { + val attribs = intArrayOf( + EGL14.EGL_RED_SIZE, 8, + EGL14.EGL_GREEN_SIZE, 8, + EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_ALPHA_SIZE, 8, + EGL14.EGL_RENDERABLE_TYPE, renderableType, + EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT, + EGL14.EGL_NONE, + ) + val configs = arrayOfNulls(1) + val count = IntArray(1) + return if (EGL14.eglChooseConfig(eglDisplay, attribs, 0, configs, 0, configs.size, count, 0) && + count[0] > 0 + ) { + configs[0] + } else { + null + } + } + + private fun ensureGles31() { + val version = GLES30.glGetString(GLES30.GL_VERSION).orEmpty() + if (!version.contains("OpenGL ES 3.1") && !version.contains("OpenGL ES 3.2")) { + throw IllegalStateException("GLES compute requires OpenGL ES 3.1+, got: $version") + } + } + + private fun initPrograms() { + downsampleProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, DOWNSAMPLE_FRAGMENT_SHADER, "downsample") + structureProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, STRUCTURE_FRAGMENT_SHADER, "structure") + alignProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, ALIGN_FRAGMENT_SHADER, "align_tiles") + smoothFlowProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, SMOOTH_FLOW_FRAGMENT_SHADER, "smooth_flow") + robustnessProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, ROBUSTNESS_FRAGMENT_SHADER, "robustness") + tileMaskProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, TILE_MASK_FRAGMENT_SHADER, "tile_mask") + accumulateProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, ACCUMULATE_FRAGMENT_SHADER, "accumulate") + normalizeProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, NORMALIZE_FRAGMENT_SHADER, "normalize") + p010LumaProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, P010_LUMA_FRAGMENT_SHADER, "p010_luma") + p010ChromaProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, P010_CHROMA_FRAGMENT_SHADER, "p010_chroma") + planarChroma8Program = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, PLANAR_CHROMA_8_FRAGMENT_SHADER, "planar_chroma_8") + planarChroma16Program = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, PLANAR_CHROMA_16_FRAGMENT_SHADER, "planar_chroma_16") + } + + private fun initResources() { + gridWidth = (width + FLOW_GRID_SPACING - 1) / FLOW_GRID_SPACING + gridHeight = (height + FLOW_GRID_SPACING - 1) / FLOW_GRID_SPACING + + refY = createTexture2D(width, height, lumaInternalFormat, GLES30.GL_LINEAR) + refCbCr = createTexture2D(chromaWidth, chromaHeight, chromaInternalFormat, GLES30.GL_LINEAR) + curY = createTexture2D(width, height, lumaInternalFormat, GLES30.GL_LINEAR) + curCbCr = createTexture2D(chromaWidth, chromaHeight, chromaInternalFormat, GLES30.GL_LINEAR) + if (highPrecisionInput) { + refYStaging = createTexture2D(width, height, GLES30.GL_R16UI, GLES30.GL_NEAREST) + refCbCrStaging = createTexture2D(chromaWidth, chromaHeight, GLES30.GL_RG16UI, GLES30.GL_NEAREST) + curYStaging = createTexture2D(width, height, GLES30.GL_R16UI, GLES30.GL_NEAREST) + curCbCrStaging = createTexture2D(chromaWidth, chromaHeight, GLES30.GL_RG16UI, GLES30.GL_NEAREST) + } + + kernelTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) + flowTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR) + flowScratchTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR) + robustnessTexture = createTexture2D(width, height, GLES30.GL_RGBA8, GLES30.GL_LINEAR) + tileMaskTexture = createTexture2D(gridWidth, gridHeight, GLES30.GL_RGBA8, GLES30.GL_LINEAR) + accumulatorTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) + accumulatorScratchTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST) + currentAccumulatorTexture = accumulatorTexture + outputTexture = createTexture2D(gpuOutputWidth, gpuOutputHeight, GLES30.GL_RGBA8, GLES30.GL_NEAREST) + + renderFbo = createFramebuffer() + readbackFbo = createFramebuffer() + } + + private fun createPyramid(baseTexture: Int): List { + val levels = ArrayList(PYRAMID_LEVELS) + levels += TextureLevel(baseTexture, width, height) + var levelWidth = width + var levelHeight = height + repeat(PYRAMID_LEVELS - 1) { + levelWidth = max(1, (levelWidth + 1) / 2) + levelHeight = max(1, (levelHeight + 1) / 2) + val texture = createTexture2D( + levelWidth, + levelHeight, + GLES30.GL_RGBA8, + GLES30.GL_LINEAR, + ) + levels += TextureLevel(texture, levelWidth, levelHeight) + } + return levels + } + + private fun uploadImagePlanes( + image: SafeImage, + yTexture: Int, + cbCrTexture: Int, + yStagingTexture: Int, + cbCrStagingTexture: Int, + label: String, + ): Boolean { + val planes = image.planes + if (planes.size < 3) { + PLog.w(TAG, "$label has ${planes.size} planes") + return false + } + if (label == "reference") { + PLog.d( + TAG, + "GLES plane upload yRow=${planes[0].rowStride} cbRow=${planes[1].rowStride} cbPixel=${planes[1].pixelStride} chroma=${chromaWidth}x${chromaHeight}" + ) + } + + return if (highPrecisionInput) { + uploadP010Planes(image, yTexture, cbCrTexture, yStagingTexture, cbCrStagingTexture, label) + } else { + uploadYuv420Planes(image, yTexture, cbCrTexture, label) + } + } + + private fun uploadYuv420Planes( + image: SafeImage, + yTexture: Int, + cbCrTexture: Int, + label: String, + ): Boolean { + val planes = image.planes + val yPlane = planes[0] + val cbPlane = planes[1] + val crPlane = planes[2] + + uploadTextureData( + texture = yTexture, + width = width, + height = height, + format = GLES30.GL_RED, + type = GLES30.GL_UNSIGNED_BYTE, + rowLength = yPlane.rowStride, + buffer = yPlane.buffer, + label = "$label Y", + ) + + return when (cbPlane.pixelStride) { + 2 -> { + uploadTextureData( + texture = cbCrTexture, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RG, + type = GLES30.GL_UNSIGNED_BYTE, + rowLength = max(1, cbPlane.rowStride / 2), + buffer = cbPlane.buffer, + label = "$label CbCr", + ) + true + } + 1 -> { + ensurePlanarStaging(GLES30.GL_R8) + uploadTextureData( + texture = planarUStaging, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RED, + type = GLES30.GL_UNSIGNED_BYTE, + rowLength = cbPlane.rowStride, + buffer = cbPlane.buffer, + label = "$label Cb", + ) + uploadTextureData( + texture = planarVStaging, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RED, + type = GLES30.GL_UNSIGNED_BYTE, + rowLength = crPlane.rowStride, + buffer = crPlane.buffer, + label = "$label Cr", + ) + convertPlanarChroma8(cbCrTexture, label) + true + } + else -> { + PLog.w(TAG, "$label unsupported YUV_420_888 chroma pixelStride=${cbPlane.pixelStride}") + false + } + } + } + + private fun uploadP010Planes( + image: SafeImage, + yTexture: Int, + cbCrTexture: Int, + yStagingTexture: Int, + cbCrStagingTexture: Int, + label: String, + ): Boolean { + val planes = image.planes + val yPlane = planes[0] + val cbPlane = planes[1] + val crPlane = planes[2] + + if (yStagingTexture == 0 || cbCrStagingTexture == 0) { + PLog.w(TAG, "$label missing P010 staging textures") + return false + } + + uploadTextureData( + texture = yStagingTexture, + width = width, + height = height, + format = GLES30.GL_RED_INTEGER, + type = GLES30.GL_UNSIGNED_SHORT, + rowLength = max(1, yPlane.rowStride / 2), + buffer = yPlane.buffer, + label = "$label P010 Y", + ) + convertP010Luma(yStagingTexture, yTexture, label) + + return when (cbPlane.pixelStride) { + 4 -> { + uploadTextureData( + texture = cbCrStagingTexture, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RG_INTEGER, + type = GLES30.GL_UNSIGNED_SHORT, + rowLength = max(1, cbPlane.rowStride / 4), + buffer = cbPlane.buffer, + label = "$label P010 CbCr", + ) + convertP010Chroma(cbCrStagingTexture, cbCrTexture, label) + true + } + 2 -> { + ensurePlanarStaging(GLES30.GL_R16UI) + uploadTextureData( + texture = planarUStaging, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RED_INTEGER, + type = GLES30.GL_UNSIGNED_SHORT, + rowLength = max(1, cbPlane.rowStride / 2), + buffer = cbPlane.buffer, + label = "$label P010 Cb", + ) + uploadTextureData( + texture = planarVStaging, + width = chromaWidth, + height = chromaHeight, + format = GLES30.GL_RED_INTEGER, + type = GLES30.GL_UNSIGNED_SHORT, + rowLength = max(1, crPlane.rowStride / 2), + buffer = crPlane.buffer, + label = "$label P010 Cr", + ) + convertPlanarChroma16(cbCrTexture, label) + true + } + else -> { + PLog.w(TAG, "$label unsupported P010 chroma pixelStride=${cbPlane.pixelStride}") + false + } + } + } + + private fun uploadTextureData( + texture: Int, + width: Int, + height: Int, + format: Int, + type: Int, + rowLength: Int, + buffer: ByteBuffer, + label: String, + ) { + val uploadBuffer = buffer.duplicate() + uploadBuffer.position(0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 1) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, rowLength) + GLES30.glTexSubImage2D( + GLES30.GL_TEXTURE_2D, + 0, + 0, + 0, + width, + height, + format, + type, + uploadBuffer, + ) + GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + checkGlError("uploadTextureData $label") + } + + private fun ensurePlanarStaging(internalFormat: Int) { + if (planarUStaging != 0 && planarVStaging != 0) { + return + } + planarUStaging = createTexture2D(chromaWidth, chromaHeight, internalFormat, GLES30.GL_NEAREST) + planarVStaging = createTexture2D(chromaWidth, chromaHeight, internalFormat, GLES30.GL_NEAREST) + } + + private fun convertP010Luma(inputTexture: Int, outputTexture: Int, label: String) { + bindFramebufferOutput(outputTexture, "convertP010Luma $label") + GLES30.glViewport(0, 0, width, height) + GLES30.glUseProgram(p010LumaProgram) + bindTexture(p010LumaProgram, "uInput", 0, inputTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(p010LumaProgram, "uSize"), width, height) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("convertP010Luma $label") + } + + private fun convertP010Chroma(inputTexture: Int, outputTexture: Int, label: String) { + bindFramebufferOutput(outputTexture, "convertP010Chroma $label") + GLES30.glViewport(0, 0, chromaWidth, chromaHeight) + GLES30.glUseProgram(p010ChromaProgram) + bindTexture(p010ChromaProgram, "uInput", 0, inputTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(p010ChromaProgram, "uSize"), chromaWidth, chromaHeight) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("convertP010Chroma $label") + } + + private fun convertPlanarChroma8(outputTexture: Int, label: String) { + bindFramebufferOutput(outputTexture, "convertPlanarChroma8 $label") + GLES30.glViewport(0, 0, chromaWidth, chromaHeight) + GLES30.glUseProgram(planarChroma8Program) + bindTexture(planarChroma8Program, "uCb", 0, planarUStaging) + bindTexture(planarChroma8Program, "uCr", 1, planarVStaging) + GLES31.glUniform2i(GLES31.glGetUniformLocation(planarChroma8Program, "uSize"), chromaWidth, chromaHeight) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("convertPlanarChroma8 $label") + } + + private fun convertPlanarChroma16(outputTexture: Int, label: String) { + bindFramebufferOutput(outputTexture, "convertPlanarChroma16 $label") + GLES30.glViewport(0, 0, chromaWidth, chromaHeight) + GLES30.glUseProgram(planarChroma16Program) + bindTexture(planarChroma16Program, "uCb", 0, planarUStaging) + bindTexture(planarChroma16Program, "uCr", 1, planarVStaging) + GLES31.glUniform2i(GLES31.glGetUniformLocation(planarChroma16Program, "uSize"), chromaWidth, chromaHeight) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("convertPlanarChroma16 $label") + } + + private fun buildPyramid(levels: List) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, renderFbo) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT1, GLES30.GL_TEXTURE_2D, 0, 0) + val drawBuffers = intArrayOf(GLES30.GL_COLOR_ATTACHMENT0) + GLES30.glDrawBuffers(drawBuffers.size, drawBuffers, 0) + GLES30.glDisable(GLES30.GL_BLEND) + GLES30.glUseProgram(downsampleProgram) + for (index in 1 until levels.size) { + val input = levels[index - 1] + val output = levels[index] + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, output.texture, 0) + checkFramebuffer("buildPyramid level $index") + GLES30.glViewport(0, 0, output.width, output.height) + bindTexture(downsampleProgram, "uInput", 0, input.texture) + GLES30.glUniform2i(GLES30.glGetUniformLocation(downsampleProgram, "uInputSize"), input.width, input.height) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) + checkGlError("buildPyramid level $index") + } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + } + + private fun bindFramebufferOutput(texture: Int, label: String) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, renderFbo) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT0, + GLES30.GL_TEXTURE_2D, + texture, + 0, + ) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, + GLES30.GL_COLOR_ATTACHMENT1, + GLES30.GL_TEXTURE_2D, + 0, + 0, + ) + val drawBuffers = intArrayOf(GLES30.GL_COLOR_ATTACHMENT0) + GLES30.glDrawBuffers(drawBuffers.size, drawBuffers, 0) + GLES30.glDisable(GLES30.GL_BLEND) + checkFramebuffer(label) + } + + private fun finishFramebufferPass(label: String) { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT) + checkGlError(label) + } + + private fun computeStructureTensor(referenceY: Int) { + bindFramebufferOutput(kernelTexture, "computeStructureTensor") + GLES30.glViewport(0, 0, width, height) + GLES30.glUseProgram(structureProgram) + bindTexture(structureProgram, "uLuma", 0, referenceY) + GLES31.glUniform2i(GLES31.glGetUniformLocation(structureProgram, "uImageSize"), width, height) + GLES31.glUniform1f(GLES31.glGetUniformLocation(structureProgram, "uNoiseAlpha"), NOISE_ALPHA) + GLES31.glUniform1f(GLES31.glGetUniformLocation(structureProgram, "uNoiseBeta"), NOISE_BETA) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("computeStructureTensor") + } + + private fun clearAccumulator() { + bindFramebufferOutput(accumulatorTexture, "clearAccumulator") + GLES30.glViewport(0, 0, width, height) + GLES30.glClearColor(0f, 0f, 0f, 0f) + GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) + finishFramebufferPass("clearAccumulator") + currentAccumulatorTexture = accumulatorTexture + } + + private fun alignCurrentToReference(reference: List, current: List) { + val levelIndex = ALIGN_LEVEL.coerceAtMost(reference.lastIndex).coerceAtMost(current.lastIndex) + val ref = reference[levelIndex] + val cur = current[levelIndex] + + bindFramebufferOutput(flowTexture, "alignCurrentToReference") + GLES30.glViewport(0, 0, gridWidth, gridHeight) + GLES30.glUseProgram(alignProgram) + bindTexture(alignProgram, "uReference", 0, ref.texture) + bindTexture(alignProgram, "uCurrent", 1, cur.texture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(alignProgram, "uLevelSize"), ref.width, ref.height) + GLES31.glUniform2i(GLES31.glGetUniformLocation(alignProgram, "uGridSize"), gridWidth, gridHeight) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uTileSize"), FLOW_GRID_SPACING) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uAlignWindowSize"), ALIGN_WINDOW_SIZE) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uLevelScale"), 1 shl levelIndex) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uSearchRadius"), SEARCH_RADIUS_LEVEL) + GLES31.glUniform1i(GLES31.glGetUniformLocation(alignProgram, "uSampleStep"), ALIGN_SAMPLE_STEP) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("alignCurrentToReference") + } + + private fun smoothFlow() { + repeat(FLOW_SMOOTH_PASSES) { pass -> + val input = if (pass % 2 == 0) flowTexture else flowScratchTexture + val output = if (pass % 2 == 0) flowScratchTexture else flowTexture + bindFramebufferOutput(output, "smoothFlow pass $pass") + GLES30.glViewport(0, 0, gridWidth, gridHeight) + GLES30.glUseProgram(smoothFlowProgram) + bindTexture(smoothFlowProgram, "uInputFlow", 0, input) + GLES31.glUniform2i(GLES31.glGetUniformLocation(smoothFlowProgram, "uGridSize"), gridWidth, gridHeight) + GLES31.glUniform1f(GLES31.glGetUniformLocation(smoothFlowProgram, "uOutlierThreshold"), FLOW_OUTLIER_THRESHOLD_PX) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("smoothFlow pass $pass") + } + } + + private fun computeRobustness() { + bindFramebufferOutput(robustnessTexture, "computeRobustness") + GLES30.glViewport(0, 0, width, height) + GLES30.glUseProgram(robustnessProgram) + bindTexture(robustnessProgram, "uReferenceY", 0, refY) + bindTexture(robustnessProgram, "uReferenceCbCr", 1, refCbCr) + bindTexture(robustnessProgram, "uCurrentY", 2, curY) + bindTexture(robustnessProgram, "uCurrentCbCr", 3, curCbCr) + bindTexture(robustnessProgram, "uFlowGrid", 4, flowTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(robustnessProgram, "uImageSize"), width, height) + GLES31.glUniform2i(GLES31.glGetUniformLocation(robustnessProgram, "uGridSize"), gridWidth, gridHeight) + GLES31.glUniform1i(GLES31.glGetUniformLocation(robustnessProgram, "uTileSize"), FLOW_GRID_SPACING) + GLES31.glUniform1f(GLES31.glGetUniformLocation(robustnessProgram, "uNoiseAlpha"), NOISE_ALPHA) + GLES31.glUniform1f(GLES31.glGetUniformLocation(robustnessProgram, "uNoiseBeta"), NOISE_BETA) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("computeRobustness") + } + + private fun computeTileMask() { + bindFramebufferOutput(tileMaskTexture, "computeTileMask") + GLES30.glViewport(0, 0, gridWidth, gridHeight) + GLES30.glUseProgram(tileMaskProgram) + bindTexture(tileMaskProgram, "uReferenceY", 0, refY) + bindTexture(tileMaskProgram, "uRobustness", 1, robustnessTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uImageSize"), width, height) + GLES31.glUniform2i(GLES31.glGetUniformLocation(tileMaskProgram, "uGridSize"), gridWidth, gridHeight) + GLES31.glUniform1i(GLES31.glGetUniformLocation(tileMaskProgram, "uTileSize"), FLOW_GRID_SPACING) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("computeTileMask") + } + + private fun accumulateFrame(yTexture: Int, cbCrTexture: Int, isReference: Boolean) { + val outputAccumulator = if (currentAccumulatorTexture == accumulatorTexture) { + accumulatorScratchTexture + } else { + accumulatorTexture + } + bindFramebufferOutput(outputAccumulator, "accumulateFrame") + GLES30.glViewport(0, 0, width, height) + GLES30.glUseProgram(accumulateProgram) + bindTexture(accumulateProgram, "uCurrentY", 0, yTexture) + bindTexture(accumulateProgram, "uCurrentCbCr", 1, cbCrTexture) + bindTexture(accumulateProgram, "uFlowGrid", 2, flowTexture) + bindTexture(accumulateProgram, "uRobustness", 3, robustnessTexture) + bindTexture(accumulateProgram, "uTileMask", 4, tileMaskTexture) + bindTexture(accumulateProgram, "uKernel", 5, kernelTexture) + bindTexture(accumulateProgram, "uAccumulatorInput", 6, currentAccumulatorTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(accumulateProgram, "uImageSize"), width, height) + GLES31.glUniform2i(GLES31.glGetUniformLocation(accumulateProgram, "uGridSize"), gridWidth, gridHeight) + GLES31.glUniform1i(GLES31.glGetUniformLocation(accumulateProgram, "uTileSize"), FLOW_GRID_SPACING) + GLES31.glUniform1i(GLES31.glGetUniformLocation(accumulateProgram, "uIsReference"), if (isReference) 1 else 0) + GLES31.glUniform1f(GLES31.glGetUniformLocation(accumulateProgram, "uFrameWeight"), if (isReference) 1.0f else NON_REFERENCE_FRAME_WEIGHT) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("accumulateFrame") + currentAccumulatorTexture = outputAccumulator + } + + private fun normalizeOutput() { + bindFramebufferOutput(outputTexture, "normalizeOutput") + GLES30.glViewport(0, 0, gpuOutputWidth, gpuOutputHeight) + GLES30.glUseProgram(normalizeProgram) + bindTexture(normalizeProgram, "uAccumulator", 0, currentAccumulatorTexture) + GLES31.glUniform2i(GLES31.glGetUniformLocation(normalizeProgram, "uInputSize"), width, height) + val transform = computeRenderTransform() + GLES31.glUniform3f( + GLES31.glGetUniformLocation(normalizeProgram, "uTransformX"), + transform[0], + transform[1], + transform[2], + ) + GLES31.glUniform3f( + GLES31.glGetUniformLocation(normalizeProgram, "uTransformY"), + transform[3], + transform[4], + transform[5], + ) + GLES31.glUniform1f(GLES31.glGetUniformLocation(normalizeProgram, "uNoiseBeta"), NOISE_BETA) + GLES31.glUniform1i(GLES31.glGetUniformLocation(normalizeProgram, "uIsP010"), if (highPrecisionInput) 1 else 0) + val directOffset = computeDirectSourceOffset() + GLES31.glUniform1i(GLES31.glGetUniformLocation(normalizeProgram, "uDirectSource"), if (cpuRotateReadback) 1 else 0) + GLES31.glUniform2i(GLES31.glGetUniformLocation(normalizeProgram, "uDirectOffset"), directOffset[0], directOffset[1]) + GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) + finishFramebufferPass("normalizeOutput") + } + + private fun readOutputBitmap(): Bitmap? { + val bitmap = try { + createBitmap(renderOutputWidth, renderOutputHeight, colorSpace = colorSpace) + } catch (e: OutOfMemoryError) { + PLog.e(TAG, "OOM creating GLES stack bitmap ($renderOutputWidth x $renderOutputHeight)", e) + return null + } + + val bufferByteCount = gpuOutputWidth.toLong() * gpuOutputHeight.toLong() * 4L + val buffer = LargeDirectBuffer.allocate(bufferByteCount, "GLES YUV stack readback") ?: return null + try { + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, readbackFbo) + GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, outputTexture, 0) + GLES30.glReadBuffer(GLES30.GL_COLOR_ATTACHMENT0) + checkFramebuffer("readOutputBitmap") + GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1) + GLES30.glViewport(0, 0, gpuOutputWidth, gpuOutputHeight) + GLES30.glReadPixels(0, 0, gpuOutputWidth, gpuOutputHeight, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, buffer) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + buffer.position(0) + if (cpuRotateReadback) { + copyRotatedReadbackToBitmap(buffer, bitmap) + } else { + bitmap.copyPixelsFromBuffer(buffer) + } + checkGlError("readOutputBitmap") + } finally { + LargeDirectBuffer.free(buffer) + } + return bitmap + } + + private fun copyRotatedReadbackToBitmap(buffer: ByteBuffer, bitmap: Bitmap) { + val rotatedByteCount = renderOutputWidth.toLong() * renderOutputHeight.toLong() * 4L + val rotated = LargeDirectBuffer.allocate(rotatedByteCount, "GLES YUV rotated readback") ?: return + try { + for (y in 0 until renderOutputHeight) { + for (x in 0 until renderOutputWidth) { + val sourceX: Int + val sourceY: Int + if (normalizedRotation == 90) { + sourceX = y + sourceY = gpuOutputHeight - 1 - x + } else { + sourceX = gpuOutputWidth - 1 - y + sourceY = x + } + val sourceOffset = (sourceY * gpuOutputWidth + sourceX) * 4 + val destOffset = (y * renderOutputWidth + x) * 4 + rotated.put(destOffset, buffer.get(sourceOffset)) + rotated.put(destOffset + 1, buffer.get(sourceOffset + 1)) + rotated.put(destOffset + 2, buffer.get(sourceOffset + 2)) + rotated.put(destOffset + 3, buffer.get(sourceOffset + 3)) + } + } + rotated.position(0) + bitmap.copyPixelsFromBuffer(rotated) + } finally { + LargeDirectBuffer.free(rotated) + } + } + + private fun createTexture2D( + textureWidth: Int, + textureHeight: Int, + internalFormat: Int, + filter: Int, + ): Int { + val ids = IntArray(1) + GLES30.glGenTextures(1, ids, 0) + val texture = ids[0] + textures += texture + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, filter) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, filter) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, internalFormat, textureWidth, textureHeight) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + return texture + } + + private fun createFramebuffer(): Int { + val ids = IntArray(1) + GLES30.glGenFramebuffers(1, ids, 0) + framebuffers += ids[0] + return ids[0] + } + + private fun bindTexture(program: Int, name: String, unit: Int, texture: Int) { + GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit) + GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, texture) + GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit) + } + + private fun linkGraphicsProgram(vertexSource: String, fragmentSource: String, name: String): Int { + val vertexShader = compileShader(GLES30.GL_VERTEX_SHADER, vertexSource, "$name vertex") + val fragmentShader = compileShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource, "$name fragment") + val program = GLES30.glCreateProgram() + GLES30.glAttachShader(program, vertexShader) + GLES30.glAttachShader(program, fragmentShader) + GLES30.glLinkProgram(program) + val linked = IntArray(1) + GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linked, 0) + GLES30.glDeleteShader(vertexShader) + GLES30.glDeleteShader(fragmentShader) + if (linked[0] == 0) { + val log = GLES30.glGetProgramInfoLog(program) + GLES30.glDeleteProgram(program) + throw IllegalStateException("Program $name linking failed: $log") + } + programs += program + return program + } + + private fun compileShader(type: Int, source: String, name: String): Int { + val shader = GLES30.glCreateShader(type) + GLES30.glShaderSource(shader, source) + GLES30.glCompileShader(shader) + val compiled = IntArray(1) + GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compiled, 0) + if (compiled[0] == 0) { + val log = GLES30.glGetShaderInfoLog(shader) + GLES30.glDeleteShader(shader) + throw IllegalStateException("Shader $name compilation failed: $log") + } + return shader + } + + private fun checkFramebuffer(label: String) { + val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) + if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { + throw IllegalStateException("$label framebuffer incomplete: 0x${status.toString(16)}") + } + } + + private fun checkGlError(label: String) { + var error = GLES30.glGetError() + if (error != GLES30.GL_NO_ERROR) { + val first = error + while (error != GLES30.GL_NO_ERROR) { + error = GLES30.glGetError() + } + throw IllegalStateException("$label GL error: 0x${first.toString(16)}") + } + } + + private fun release() { + if (eglDisplay != EGL14.EGL_NO_DISPLAY) { + if (programs.isNotEmpty()) { + for (program in programs) { + GLES30.glDeleteProgram(program) + } + } + if (textures.isNotEmpty()) { + GLES30.glDeleteTextures(textures.size, textures.toIntArray(), 0) + } + if (framebuffers.isNotEmpty()) { + GLES30.glDeleteFramebuffers(framebuffers.size, framebuffers.toIntArray(), 0) + } + EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) + if (eglSurface != EGL14.EGL_NO_SURFACE) { + EGL14.eglDestroySurface(eglDisplay, eglSurface) + } + if (eglContext != EGL14.EGL_NO_CONTEXT) { + EGL14.eglDestroyContext(eglDisplay, eglContext) + } + EGL14.eglTerminate(eglDisplay) + } + eglDisplay = EGL14.EGL_NO_DISPLAY + eglContext = EGL14.EGL_NO_CONTEXT + eglSurface = EGL14.EGL_NO_SURFACE + } + + private fun normalizeRotation(degrees: Int): Int { + val normalized = ((degrees % 360) + 360) % 360 + return when (normalized) { + 90, 180, 270 -> normalized + else -> 0 + } + } + + private fun computeNormalizeTransform(): FloatArray { + val sensorWidth = width.toFloat() + val sensorHeight = height.toFloat() + val rotatedWidth = if (normalizedRotation == 90 || normalizedRotation == 270) height else width + val rotatedHeight = if (normalizedRotation == 90 || normalizedRotation == 270) width else height + val cropX = (((rotatedWidth - outputWidth).coerceAtLeast(0)) / 4 * 2).toFloat() + val cropY = (((rotatedHeight - outputHeight).coerceAtLeast(0)) / 4 * 2).toFloat() + return when (normalizedRotation) { + 90 -> floatArrayOf( + 0.0f, 1.0f, cropY, + -1.0f, 0.0f, sensorHeight - 1.0f - cropX, + ) + 180 -> floatArrayOf( + -1.0f, 0.0f, sensorWidth - 1.0f - cropX, + 0.0f, -1.0f, sensorHeight - 1.0f - cropY, + ) + 270 -> floatArrayOf( + 0.0f, -1.0f, sensorWidth - 1.0f - cropY, + 1.0f, 0.0f, cropX, + ) + else -> floatArrayOf( + 1.0f, 0.0f, cropX, + 0.0f, 1.0f, cropY, + ) + } + } + + private fun computeRenderTransform(): FloatArray { + if (!cpuRotateReadback) { + return computeNormalizeTransform() + } + val offset = computeDirectSourceOffset() + val offsetX = offset[0].toFloat() + val offsetY = offset[1].toFloat() + return floatArrayOf( + 1.0f, 0.0f, offsetX, + 0.0f, 1.0f, offsetY, + ) + } + + private fun computeDirectSourceOffset(): IntArray { + if (!cpuRotateReadback) { + return intArrayOf(0, 0) + } + val rotatedWidth = if (normalizedRotation == 90 || normalizedRotation == 270) height else width + val rotatedHeight = if (normalizedRotation == 90 || normalizedRotation == 270) width else height + val cropX = ((rotatedWidth - outputWidth).coerceAtLeast(0) / 4) * 2 + val cropY = ((rotatedHeight - outputHeight).coerceAtLeast(0) / 4) * 2 + return when (normalizedRotation) { + 90 -> intArrayOf( + cropY, + height - cropX - gpuOutputHeight, + ) + 270 -> intArrayOf( + width - cropY - gpuOutputWidth, + cropX, + ) + else -> intArrayOf(0, 0) + } + } + + companion object { + private const val TAG = "GlesYuvStacker" + + private const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040 + private const val EGL_CONTEXT_MINOR_VERSION_KHR = 0x30FB + + private const val PYRAMID_LEVELS = 4 + private const val ALIGN_LEVEL = 2 + private const val FLOW_GRID_SPACING = 8 + private const val ALIGN_WINDOW_SIZE = 32 + private const val SEARCH_RADIUS_LEVEL = 6 + private const val ALIGN_SAMPLE_STEP = 2 + private const val FLOW_SMOOTH_PASSES = 2 + private const val FLOW_OUTLIER_THRESHOLD_PX = 24.0f + private const val NON_REFERENCE_FRAME_WEIGHT = 0.92f + private const val NOISE_ALPHA = 0.005f + private const val NOISE_BETA = 0.001f + + fun supportsImageFormat(format: Int): Boolean { + return format == ImageFormat.YUV_420_888 || format == ImageFormat.YCBCR_P010 + } + + private fun formatName(format: Int): String { + return when (format) { + ImageFormat.YUV_420_888 -> "YUV_420_888" + ImageFormat.YCBCR_P010 -> "YCBCR_P010" + else -> format.toString() + } + } + + private val FULLSCREEN_VERTEX_SHADER = """ + #version 300 es + precision highp float; + out vec2 vTexCoord; + void main() { + vec2 positions[3] = vec2[3]( + vec2(-1.0, -1.0), + vec2( 3.0, -1.0), + vec2(-1.0, 3.0) + ); + vec2 texCoords[3] = vec2[3]( + vec2(0.0, 0.0), + vec2(2.0, 0.0), + vec2(0.0, 2.0) + ); + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + vTexCoord = texCoords[gl_VertexID]; + } + """.trimIndent() + + private val P010_LUMA_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + precision highp usampler2D; + uniform usampler2D uInput; + uniform ivec2 uSize; + out float outY; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uSize - ivec2(1)); + outY = float(texelFetch(uInput, p, 0).r) * (1.0 / 65535.0); + } + """.trimIndent() + + private val P010_CHROMA_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + precision highp usampler2D; + uniform usampler2D uInput; + uniform ivec2 uSize; + out vec2 outCbCr; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uSize - ivec2(1)); + uvec2 cbcr = texelFetch(uInput, p, 0).rg; + outCbCr = vec2(float(cbcr.r), float(cbcr.g)) * (1.0 / 65535.0); + } + """.trimIndent() + + private val PLANAR_CHROMA_8_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uCb; + uniform sampler2D uCr; + uniform ivec2 uSize; + out vec2 outCbCr; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uSize - ivec2(1)); + outCbCr = vec2(texelFetch(uCb, p, 0).r, texelFetch(uCr, p, 0).r); + } + """.trimIndent() + + private val PLANAR_CHROMA_16_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + precision highp usampler2D; + uniform usampler2D uCb; + uniform usampler2D uCr; + uniform ivec2 uSize; + out vec2 outCbCr; + + void main() { + ivec2 p = clamp(ivec2(gl_FragCoord.xy), ivec2(0), uSize - ivec2(1)); + outCbCr = vec2( + float(texelFetch(uCb, p, 0).r), + float(texelFetch(uCr, p, 0).r) + ) * (1.0 / 65535.0); + } + """.trimIndent() + + private val DOWNSAMPLE_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uInput; + uniform ivec2 uInputSize; + out vec4 fragColor; + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + ivec2 src = p * 2; + float sum = 0.0; + for (int y = 0; y < 2; ++y) { + for (int x = 0; x < 2; ++x) { + ivec2 q = clamp(src + ivec2(x, y), ivec2(0), uInputSize - ivec2(1)); + sum += texelFetch(uInput, q, 0).r; + } + } + float v = sum * 0.25; + fragColor = vec4(v, 0.0, 0.0, 1.0); + } + """.trimIndent() + + private val STRUCTURE_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uLuma; + uniform ivec2 uImageSize; + uniform float uNoiseAlpha; + uniform float uNoiseBeta; + out vec4 fragColor; + + float readY(ivec2 p) { + p = clamp(p, ivec2(0), uImageSize - ivec2(1)); + return texelFetch(uLuma, p, 0).r; + } + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + float sIxIx = 0.0; + float sIyIy = 0.0; + float sIxIy = 0.0; + for (int y = -2; y <= 2; ++y) { + for (int x = -2; x <= 2; ++x) { + ivec2 q = p + ivec2(x, y); + float ix = 0.5 * (readY(q + ivec2(1, 0)) - readY(q - ivec2(1, 0))); + float iy = 0.5 * (readY(q + ivec2(0, 1)) - readY(q - ivec2(0, 1))); + sIxIx += ix * ix; + sIyIy += iy * iy; + sIxIy += ix * iy; + } + } + + float jxx = sIxIx / 25.0; + float jyy = sIyIy / 25.0; + float jxy = sIxIy / 25.0; + float trace = jxx + jyy; + float diff = jxx - jyy; + float root = sqrt(max(diff * diff + 4.0 * jxy * jxy, 0.0)); + float lambda1 = 0.5 * (trace + root); + float lambda2 = 0.5 * (trace - root); + + float noiseVar = uNoiseAlpha * 0.5 + max(uNoiseBeta, 1e-10); + float snr = lambda1 / max(2.0 * noiseVar * 9.0, 1e-12); + float flatness = 1.0 - smoothstep(0.35, 4.0, snr); + float anisotropy = 1.0 + sqrt(max(lambda1 - lambda2, 0.0) / max(lambda1 + lambda2, 1e-7)); + + float kDetail = 0.30; + float kDenoise = 1.0; + float kShrink = 3.0; + float kStretch = 5.0; + float k1Base = anisotropy > 1.6 ? 1.0 / kShrink : 1.0; + float k2Base = anisotropy > 1.6 ? kStretch : 1.0; + float preK1 = kDetail * mix(k1Base, kDenoise, flatness); + float preK2 = kDetail * mix(k2Base, kDenoise, flatness); + float k1 = 1.0 / max(preK1 * preK1, 1e-7); + float k2 = 1.0 / max(preK2 * preK2, 1e-7); + + float len = sqrt(max(diff * diff + 4.0 * jxy * jxy, 0.0)); + float cos2t = len < 1e-9 ? 1.0 : diff / len; + float sin2t = len < 1e-9 ? 0.0 : 2.0 * jxy / len; + fragColor = vec4(k1, k2, cos2t, sin2t); + } + """.trimIndent() + + private val ALIGN_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uReference; + uniform sampler2D uCurrent; + uniform ivec2 uLevelSize; + uniform ivec2 uGridSize; + uniform int uTileSize; + uniform int uAlignWindowSize; + uniform int uLevelScale; + uniform int uSearchRadius; + uniform int uSampleStep; + out vec4 fragColor; + + float readTex(sampler2D tex, ivec2 p) { + p = clamp(p, ivec2(0), uLevelSize - ivec2(1)); + return texelFetch(tex, p, 0).r; + } + + void main() { + ivec2 tile = ivec2(gl_FragCoord.xy); + ivec2 fullCenter = tile * uTileSize; + ivec2 levelCenter = fullCenter / uLevelScale; + int levelTile = max(4, uAlignWindowSize / uLevelScale); + ivec2 levelStart = levelCenter - ivec2(levelTile / 2); + float bestSad = 1e20; + ivec2 bestShift = ivec2(0); + + for (int dy = -uSearchRadius; dy <= uSearchRadius; ++dy) { + for (int dx = -uSearchRadius; dx <= uSearchRadius; ++dx) { + float sad = 0.0; + float count = 0.0; + for (int sy = 1; sy < levelTile - 1; sy += uSampleStep) { + for (int sx = 1; sx < levelTile - 1; sx += uSampleStep) { + ivec2 rp = levelStart + ivec2(sx, sy); + ivec2 cp = rp + ivec2(dx, dy); + float rv = readTex(uReference, rp); + float cv = readTex(uCurrent, cp); + sad += abs(rv - cv); + count += 1.0; + } + } + sad /= max(count, 1.0); + float shiftPenalty = 0.0006 * float(dx * dx + dy * dy); + sad += shiftPenalty; + if (sad < bestSad) { + bestSad = sad; + bestShift = ivec2(dx, dy); + } + } + } + + vec2 flow = vec2(bestShift) * float(uLevelScale); + fragColor = vec4(flow, 0.0, 1.0); + } + """.trimIndent() + + private val SMOOTH_FLOW_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uInputFlow; + uniform ivec2 uGridSize; + uniform float uOutlierThreshold; + out vec4 fragColor; + + vec2 readFlow(ivec2 p) { + p = clamp(p, ivec2(0), uGridSize - ivec2(1)); + return texelFetch(uInputFlow, p, 0).rg; + } + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + vec2 center = readFlow(p); + vec2 sum = center * 4.0; + float weight = 4.0; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + if (x == 0 && y == 0) { + continue; + } + vec2 f = readFlow(p + ivec2(x, y)); + float d = length(f - center); + float w = d > uOutlierThreshold ? 0.15 : 1.0; + sum += f * w; + weight += w; + } + } + fragColor = vec4(sum / weight, 0.0, 1.0); + } + """.trimIndent() + + private val ROBUSTNESS_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uReferenceY; + uniform sampler2D uReferenceCbCr; + uniform sampler2D uCurrentY; + uniform sampler2D uCurrentCbCr; + uniform sampler2D uFlowGrid; + uniform ivec2 uImageSize; + uniform ivec2 uGridSize; + uniform int uTileSize; + uniform float uNoiseAlpha; + uniform float uNoiseBeta; + out vec4 fragColor; + + vec2 flowAt(vec2 pixel) { + vec2 grid = pixel / float(uTileSize); + vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); + return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; + } + + float refY(ivec2 p) { + p = clamp(p, ivec2(0), uImageSize - ivec2(1)); + return texelFetch(uReferenceY, p, 0).r; + } + + float curY(vec2 pixel) { + vec2 uv = (pixel + vec2(0.5)) / vec2(uImageSize); + return texture(uCurrentY, clamp(uv, vec2(0.0), vec2(1.0))).r; + } + + vec2 chromaUv(vec2 pixel) { + ivec2 chromaSize = (uImageSize + ivec2(1)) / 2; + vec2 chromaPixel = floor(pixel * 0.5); + return clamp((chromaPixel + vec2(0.5)) / vec2(chromaSize), vec2(0.0), vec2(1.0)); + } + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + vec2 flow = flowAt(vec2(p)); + vec2 curPixel = vec2(p) + flow; + if (curPixel.x < 1.0 || curPixel.y < 1.0 || + curPixel.x > float(uImageSize.x - 2) || curPixel.y > float(uImageSize.y - 2)) { + fragColor = vec4(0.0); + return; + } + + float center = refY(p); + float gx = refY(p + ivec2(1, 0)) - refY(p - ivec2(1, 0)); + float gy = refY(p + ivec2(0, 1)) - refY(p - ivec2(0, 1)); + float localVar = 0.0; + float minR = 1.0; + float sumR = 0.0; + + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + ivec2 rp = p + ivec2(x, y); + float ry = refY(rp); + float cy = curY(curPixel + vec2(x, y)); + float d = ry - cy; + float sigmaNoise = max(uNoiseAlpha * max(ry, 0.05) + uNoiseBeta, 1e-10); + float sigma = max(sigmaNoise, 0.0004); + float residual = max(0.0, d * d - 2.0 * sigmaNoise) / sigma; + float r = exp(-0.5 * pow(residual, 4.0)); + minR = min(minR, r); + sumR += r; + float dc = ry - center; + localVar += dc * dc; + } + } + + localVar /= 9.0; + float edgeStrength = sqrt((gx * gx + gy * gy) / max(localVar + uNoiseBeta, 1e-6)); + float edgeRelax = smoothstep(1.2, 5.0, edgeStrength); + + vec2 refC = texture(uReferenceCbCr, chromaUv(vec2(p))).rg; + vec2 curC = texture(uCurrentCbCr, chromaUv(curPixel)).rg; + float chromaResidual = dot(refC - curC, refC - curC); + float chromaPenalty = exp(-chromaResidual / 0.018); + + float flowPenalty = length(flow) > 15.0 ? exp(-0.1 * (length(flow) - 15.0)) : 1.0; + float avgR = sumR / 9.0; + float centerMix = mix(0.35, 0.55, edgeRelax); + float minMix = mix(0.35, 0.15, edgeRelax); + float robust = (minR * minMix + avgR * (1.0 - minMix)) * chromaPenalty * flowPenalty; + robust = mix(robust, avgR * chromaPenalty * flowPenalty, centerMix * 0.25); + float outR = clamp(robust, 0.0, 1.0); + fragColor = vec4(outR, outR, outR, 1.0); + } + """.trimIndent() + + private val TILE_MASK_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uReferenceY; + uniform sampler2D uRobustness; + uniform ivec2 uImageSize; + uniform ivec2 uGridSize; + uniform int uTileSize; + out vec4 fragColor; + + float readY(ivec2 p) { + p = clamp(p, ivec2(0), uImageSize - ivec2(1)); + return texelFetch(uReferenceY, p, 0).r; + } + + void main() { + ivec2 tile = ivec2(gl_FragCoord.xy); + ivec2 start = tile * uTileSize; + float robustSum = 0.0; + float weakCount = 0.0; + float detailSum = 0.0; + float count = 0.0; + + for (int y = 0; y < uTileSize; y += 4) { + for (int x = 0; x < uTileSize; x += 4) { + ivec2 p = start + ivec2(x, y); + if (p.x >= uImageSize.x || p.y >= uImageSize.y) { + continue; + } + float r = texelFetch(uRobustness, p, 0).r; + float c = readY(p); + float detail = abs(readY(p + ivec2(1, 0)) - readY(p - ivec2(1, 0))) + + abs(readY(p + ivec2(0, 1)) - readY(p - ivec2(0, 1))) + + 0.5 * abs(4.0 * c - readY(p + ivec2(1, 0)) - readY(p - ivec2(1, 0)) - + readY(p + ivec2(0, 1)) - readY(p - ivec2(0, 1))); + robustSum += r; + weakCount += r < 0.5 ? 1.0 : 0.0; + detailSum += detail; + count += 1.0; + } + } + + float meanR = robustSum / max(count, 1.0); + float weak = weakCount / max(count, 1.0); + float detail = detailSum / max(count, 1.0); + float robustNorm = clamp((meanR - 0.58) / 0.24, 0.0, 1.0); + float weakPenalty = clamp(1.0 - max(0.0, weak - 0.10) / 0.30, 0.0, 1.0); + float detailBoost = detail > 0.055 ? 1.0 : (detail > 0.025 ? 0.70 : 0.35); + float mask = clamp((0.55 * robustNorm + 0.45 * weakPenalty) * (0.55 + 0.45 * detailBoost), 0.0, 1.0); + if (detail > 0.055) { + mask = max(mask, 0.35); + } else if (detail > 0.025) { + mask = max(mask, 0.20); + } + fragColor = vec4(mask, mask, mask, 1.0); + } + """.trimIndent() + + private val ACCUMULATE_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uCurrentY; + uniform sampler2D uCurrentCbCr; + uniform sampler2D uFlowGrid; + uniform sampler2D uRobustness; + uniform sampler2D uTileMask; + uniform sampler2D uKernel; + uniform sampler2D uAccumulatorInput; + uniform ivec2 uImageSize; + uniform ivec2 uGridSize; + uniform int uTileSize; + uniform int uIsReference; + uniform float uFrameWeight; + out vec4 fragColor; + + vec2 flowAt(vec2 pixel) { + vec2 grid = pixel / float(uTileSize); + vec2 uv = (grid + vec2(0.5)) / vec2(uGridSize); + return texture(uFlowGrid, clamp(uv, vec2(0.0), vec2(1.0))).rg; + } + + vec2 gridUv(vec2 pixel) { + return clamp((pixel / float(uTileSize) + vec2(0.5)) / vec2(uGridSize), vec2(0.0), vec2(1.0)); + } + + float kernelWeight(vec2 tap, vec4 kp) { + float cosT = sqrt(max(0.0, 0.5 * (1.0 + kp.z))); + float sinT = sign(kp.w) * sqrt(max(0.0, 0.5 * (1.0 - kp.z))); + float u = cosT * tap.x + sinT * tap.y; + float v = -sinT * tap.x + cosT * tap.y; + float e = 0.25 * (kp.x * u * u + kp.y * v * v); + return exp(-0.5 * e); + } + + vec3 sampleYcc(vec2 pixel) { + vec2 uv = (pixel + vec2(0.5)) / vec2(uImageSize); + uv = clamp(uv, vec2(0.0), vec2(1.0)); + float y = texture(uCurrentY, uv).r; + ivec2 chromaSize = (uImageSize + ivec2(1)) / 2; + vec2 chromaPixel = floor(pixel * 0.5); + vec2 chromaUv = clamp((chromaPixel + vec2(0.5)) / vec2(chromaSize), vec2(0.0), vec2(1.0)); + vec2 cbcr = texture(uCurrentCbCr, chromaUv).rg; + return vec3(y, cbcr); + } + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + vec4 prev = texelFetch(uAccumulatorInput, p, 0); + if (uIsReference != 0) { + vec3 ycc = sampleYcc(vec2(p)); + fragColor = prev + vec4(ycc, 1.0); + return; + } + + vec2 flow = flowAt(vec2(p)); + vec2 source = vec2(p) + flow; + if (source.x < 1.0 || source.y < 1.0 || + source.x > float(uImageSize.x - 2) || source.y > float(uImageSize.y - 2)) { + fragColor = prev; + return; + } + + vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uImageSize); + float robust = texture(uRobustness, uv).r; + float local = texture(uTileMask, gridUv(vec2(p))).r; + float baseWeight = uFrameWeight * local * max(robust, 0.01 * local); + if (baseWeight <= 0.001) { + fragColor = prev; + return; + } + + vec4 kp = texelFetch(uKernel, p, 0); + vec3 sum = vec3(0.0); + float weight = 0.0; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + vec2 tap = vec2(x, y); + float kw = kernelWeight(tap, kp); + float w = baseWeight * kw; + sum += sampleYcc(source + tap) * w; + weight += w; + } + } + + if (weight > 1e-5) { + fragColor = prev + vec4(sum, weight); + } else { + fragColor = prev; + } + } + """.trimIndent() + + private val NORMALIZE_FRAGMENT_SHADER = """ + #version 300 es + precision highp float; + uniform sampler2D uAccumulator; + uniform ivec2 uInputSize; + uniform vec3 uTransformX; + uniform vec3 uTransformY; + uniform float uNoiseBeta; + uniform int uIsP010; + uniform int uDirectSource; + uniform ivec2 uDirectOffset; + out vec4 fragColor; + + bool valid(vec2 p) { + return p.x >= 0.0 && p.y >= 0.0 && + p.x <= float(uInputSize.x - 1) && + p.y <= float(uInputSize.y - 1); + } + + vec4 readAccumulator(ivec2 p) { + p = clamp(p, ivec2(0), uInputSize - ivec2(1)); + return texelFetch(uAccumulator, p, 0); + } + + ivec2 sourceTexel(vec2 pixel) { + return clamp(ivec2(floor(pixel + vec2(0.5))), ivec2(0), uInputSize - ivec2(1)); + } + + bool validTexel(ivec2 p) { + return p.x >= 0 && p.y >= 0 && p.x < uInputSize.x && p.y < uInputSize.y; + } + + vec3 readYcc(ivec2 p) { + vec4 a = readAccumulator(p); + if (a.a <= 1e-4) { + return vec3(0.0, 0.5, 0.5); + } + return clamp(a.rgb / a.a, vec3(0.0), vec3(1.0)); + } + + float readWeight(ivec2 p) { + return readAccumulator(p).a; + } + + vec3 yccToRgb(vec3 ycc) { + float y = ycc.x; + float cb = ycc.y - 0.5; + float cr = ycc.z - 0.5; + if (uIsP010 != 0) { + return vec3( + y + 1.4746 * cr, + y - 0.16455 * cb - 0.57135 * cr, + y + 1.8814 * cb + ); + } + return vec3( + y + 1.402 * cr, + y - 0.344136 * cb - 0.714136 * cr, + y + 1.772 * cb + ); + } + + void main() { + ivec2 outP = ivec2(gl_FragCoord.xy); + ivec2 srcP; + if (uDirectSource != 0) { + srcP = clamp(outP + uDirectOffset, ivec2(0), uInputSize - ivec2(1)); + } else { + vec2 src = vec2( + float(outP.x) * uTransformX.x + float(outP.y) * uTransformX.y + uTransformX.z, + float(outP.x) * uTransformY.x + float(outP.y) * uTransformY.y + uTransformY.z + ); + srcP = sourceTexel(src); + } + vec3 ycc = readYcc(srcP); + float accumWeight = readWeight(srcP); + + float mean = 0.0; + float mean2 = 0.0; + float count = 0.0; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + ivec2 q = srcP + ivec2(x, y); + if (!validTexel(q)) { + continue; + } + float yy = readYcc(q).x; + mean += yy; + mean2 += yy * yy; + count += 1.0; + } + } + mean /= max(count, 1.0); + mean2 /= max(count, 1.0); + float variance = max(mean2 - mean * mean, 0.0); + float noise = uNoiseBeta / max(accumWeight, 1.0); + float wienerGain = max(variance - noise, 0.0) / max(variance, 1e-6); + float flatness = 1.0 - smoothstep(0.0004, 0.006, variance); + ycc.x = mix(ycc.x, mean + wienerGain * (ycc.x - mean), 0.55 * flatness); + + vec3 rgb = clamp(yccToRgb(ycc), vec3(0.0), vec3(1.0)); + fragColor = vec4(rgb, 1.0); + } + """.trimIndent() + + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt index 8945593d..9d731165 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt @@ -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)