diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 8e0364a1..3261c460 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -32,13 +32,13 @@ set(SHADER_SOURCES shaders/align_tiles.comp shaders/build_pyramid.comp shaders/normalize.comp - shaders/accumulate_raw.comp - shaders/normalize_raw.comp shaders/structure_tensor.comp shaders/align_lk.comp shaders/raw_structure_tensor.comp shaders/robustness_raw.comp shaders/green_scatter_raw.comp + shaders/reference_preprocess_raw.comp + shaders/reference_prior_raw.comp shaders/normalize_green_hr.comp shaders/color_scatter_raw.comp shaders/normalize_color_hr.comp diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index eae0077b..f8e6f54c 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -367,6 +367,57 @@ static inline float hlgToLinear(float value) { return linear * kHdrReferenceScale; } +static void copyJavaFloatArray(JNIEnv *env, jfloatArray src, float *dst, + size_t count, float defaultValue) { + for (size_t i = 0; i < count; ++i) { + dst[i] = defaultValue; + } + + if (!src) { + return; + } + + const jsize length = std::min(env->GetArrayLength(src), + static_cast(count)); + if (length <= 0) { + return; + } + + jfloat *elements = env->GetFloatArrayElements(src, nullptr); + if (!elements) { + return; + } + + std::memcpy(dst, elements, static_cast(length) * sizeof(float)); + env->ReleaseFloatArrayElements(src, elements, JNI_ABORT); +} + +static unsigned char mapCfaPatternToLibRaw(int cfaPattern) { + switch (cfaPattern) { + case 0: + return LIBRAW_OPENBAYER_RGGB; + case 1: + return LIBRAW_OPENBAYER_GRBG; + case 2: + return LIBRAW_OPENBAYER_GBRG; + case 3: + return LIBRAW_OPENBAYER_BGGR; + default: + return 0; + } +} + +static void mapProjectRggbToLibRawRgbg(const float src[4], float dst[4]) { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[3]; + dst[3] = src[2]; +} + +static int roundNonNegative(float value) { + return static_cast(std::lround(std::max(0.0f, value))); +} + extern "C" { /** @@ -629,12 +680,151 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_processRawStackWithBufferNa } } +JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_processor_MultiFrameStacker_demosaicStackedRawWithLibRawNative( + JNIEnv *env, jobject /* this */, jobject fusedBayerBuffer, jint width, + jint height, jint cfaPattern, jfloatArray blackLevelArray, jint whiteLevel, + jfloatArray wbGainsArray, jobject outputBuffer) { + if (!fusedBayerBuffer || !outputBuffer || width <= 0 || height <= 0) { + LOGE("demosaicStackedRawWithLibRawNative: invalid arguments"); + return JNI_FALSE; + } + + auto *fusedBayerData = static_cast( + env->GetDirectBufferAddress(fusedBayerBuffer)); + auto *outputData = + static_cast(env->GetDirectBufferAddress(outputBuffer)); + if (!fusedBayerData || !outputData) { + LOGE("demosaicStackedRawWithLibRawNative: failed to get buffer address"); + return JNI_FALSE; + } + + const size_t inputBytes = + static_cast(width) * static_cast(height) * + sizeof(uint16_t); + const size_t outputBytes = + static_cast(width) * static_cast(height) * 3 * + sizeof(uint16_t); + const jlong inputCapacity = env->GetDirectBufferCapacity(fusedBayerBuffer); + const jlong outputCapacity = env->GetDirectBufferCapacity(outputBuffer); + if (inputCapacity < static_cast(inputBytes) || + outputCapacity < static_cast(outputBytes)) { + LOGE("demosaicStackedRawWithLibRawNative: buffer too small in=%ld/%ld out=%ld/%ld", + static_cast(inputCapacity), static_cast(inputBytes), + static_cast(outputCapacity), static_cast(outputBytes)); + return JNI_FALSE; + } + + const unsigned char libRawPattern = mapCfaPatternToLibRaw(cfaPattern); + if (libRawPattern == 0) { + LOGE("demosaicStackedRawWithLibRawNative: unsupported CFA pattern %d", + cfaPattern); + return JNI_FALSE; + } + + float projectBlackLevel[4]; + float projectWbGains[4]; + float libRawWbGains[4]; + int libRawBlackLevels[4]; + int libRawBlackResiduals[4]; + copyJavaFloatArray(env, blackLevelArray, projectBlackLevel, 4, 0.0f); + copyJavaFloatArray(env, wbGainsArray, projectWbGains, 4, 1.0f); + mapProjectRggbToLibRawRgbg(projectWbGains, libRawWbGains); + for (int i = 0; i < 4; ++i) { + if (libRawWbGains[i] <= 0.0f) { + libRawWbGains[i] = 1.0f; + } + } + + float projectBlackLevelOrdered[4]; + mapProjectRggbToLibRawRgbg(projectBlackLevel, projectBlackLevelOrdered); + for (int i = 0; i < 4; ++i) { + libRawBlackLevels[i] = roundNonNegative(projectBlackLevelOrdered[i]); + } + + const int commonBlack = + *std::min_element(std::begin(libRawBlackLevels), std::end(libRawBlackLevels)); + for (int i = 0; i < 4; ++i) { + libRawBlackResiduals[i] = libRawBlackLevels[i] - commonBlack; + } + + const int effectiveWhiteLevel = + whiteLevel > commonBlack ? whiteLevel : 65535; + + LibRaw rawProcessor; + int ret = rawProcessor.open_bayer( + fusedBayerData, static_cast(inputBytes), + static_cast(width), static_cast(height), 0, 0, 0, 0, 0, + libRawPattern, 0, 0, static_cast(commonBlack)); + if (ret != LIBRAW_SUCCESS) { + LOGE("demosaicStackedRawWithLibRawNative: open_bayer failed ret=%d err=%s", + ret, libraw_strerror(ret)); + return JNI_FALSE; + } + + rawProcessor.imgdata.params.output_bps = 16; + rawProcessor.imgdata.params.gamm[0] = 1.0; + rawProcessor.imgdata.params.gamm[1] = 1.0; + rawProcessor.imgdata.params.no_auto_bright = 1; + rawProcessor.imgdata.params.use_camera_wb = 0; + rawProcessor.imgdata.params.use_auto_wb = 0; + rawProcessor.imgdata.params.output_color = 0; + rawProcessor.imgdata.params.user_qual = 14; + rawProcessor.imgdata.params.fbdd_noiserd = 0; + rawProcessor.imgdata.params.threshold = 0; + rawProcessor.imgdata.params.med_passes = 0; + rawProcessor.imgdata.params.user_black = commonBlack; + rawProcessor.imgdata.params.user_sat = effectiveWhiteLevel; + for (int i = 0; i < 4; ++i) { + rawProcessor.imgdata.params.user_mul[i] = libRawWbGains[i]; + rawProcessor.imgdata.params.user_cblack[i] = libRawBlackResiduals[i]; + } + + ret = rawProcessor.unpack(); + if (ret != LIBRAW_SUCCESS) { + LOGE("demosaicStackedRawWithLibRawNative: unpack failed ret=%d err=%s", ret, + libraw_strerror(ret)); + return JNI_FALSE; + } + + ret = rawProcessor.dcraw_process(); + if (ret != LIBRAW_SUCCESS) { + LOGE("demosaicStackedRawWithLibRawNative: dcraw_process failed ret=%d err=%s", + ret, libraw_strerror(ret)); + return JNI_FALSE; + } + + libraw_processed_image_t *image = rawProcessor.dcraw_make_mem_image(&ret); + if (!image || ret != LIBRAW_SUCCESS) { + LOGE("demosaicStackedRawWithLibRawNative: dcraw_make_mem_image failed ret=%d err=%s", + ret, libraw_strerror(ret)); + return JNI_FALSE; + } + + const bool validImage = image->type == LIBRAW_IMAGE_BITMAP && + image->colors == 3 && image->bits == 16 && + image->width == width && image->height == height && + image->data_size >= outputBytes; + if (!validImage) { + LOGE("demosaicStackedRawWithLibRawNative: unexpected image type=%d colors=%d bits=%d size=%u %dx%d", + image->type, image->colors, image->bits, image->data_size, + image->width, image->height); + LibRaw::dcraw_clear_mem(image); + return JNI_FALSE; + } + + std::memcpy(outputData, image->data, outputBytes); + LibRaw::dcraw_clear_mem(image); + return JNI_TRUE; +} + /** * Vulkan Raw Stacking JNI Interface */ JNIEXPORT jlong JNICALL Java_com_hinnka_mycamera_processor_MultiFrameStacker_createVulkanRawStackerNative( JNIEnv *env, jobject, jint width, jint height, jboolean enableSuperRes, + jfloat superResScale, jfloatArray blackLevel, jint whiteLevel, jfloatArray wbGains, jfloatArray noiseModel, jfloatArray lensShadingMap, jint lscWidth, jint lscHeight) { @@ -665,7 +855,8 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_createVulkanRawStackerNativ lsc = env->GetFloatArrayElements(lensShadingMap, nullptr); } - auto *stacker = new VulkanRawStacker(width, height, enableSuperRes, bl, + auto *stacker = new VulkanRawStacker(width, height, enableSuperRes, + superResScale, bl, (float)whiteLevel, wb, noise, lsc, (uint32_t)lscWidth, (uint32_t)lscHeight); diff --git a/app/src/main/cpp/shaders/accumulate_raw.comp b/app/src/main/cpp/shaders/accumulate_raw.comp deleted file mode 100644 index a9a79c14..00000000 --- a/app/src/main/cpp/shaders/accumulate_raw.comp +++ /dev/null @@ -1,314 +0,0 @@ -#version 450 -#extension GL_EXT_scalar_block_layout : require - -layout(local_size_x = 16, local_size_y = 16) in; - -// Push Constants -layout(push_constant, scalar) uniform PushConstants { - uint width; - uint height; - uint planeWidth; - uint planeHeight; - uint sensorWidth; - uint sensorHeight; - - float scale; - - float blackLevel[4]; - float whiteLevel; - float wbGains[4]; - - uint isFirstFrame; - uint outputChannel; - uint cfaPattern; - uint planeIndex; - - uint tileX; - uint tileY; - uint tileW; - uint tileH; - uint bufferStride; - uint gridW; - uint gridH; - uint tileSize; - - float noiseAlpha; - float noiseBeta; - float baseNoise; - float frameWeight; -} pc; - -// Bindings -layout(set = 0, binding = 0) uniform sampler2D inputRawSampler; // The current frame RAW - -// Accumulator: Stores (val * weight, weight) -layout(set = 0, binding = 1, scalar) buffer Accumulator { - vec2 data[]; -} accumulator; - -// Alignment: Offsets per tile (Plane Resolution) -layout(set = 0, binding = 2, scalar) buffer AlignBuffer { - vec2 offsets[]; -} alignBuffer; - -// Kernel: k1, k2, cos2t, sin2t (Plane Resolution) -layout(set = 0, binding = 3, scalar) buffer KernelParams { - vec4 data[]; -} kernelParams; - -// Robustness: R value (Plane Resolution) -layout(set = 0, binding = 4, scalar) buffer RobustnessBuffer { - float data[]; -} outRobustness; - -layout(set = 0, binding = 5, scalar) buffer FlowVarianceBuffer { - float data[]; -} flowVarianceBuffer; - -layout(set = 0, binding = 6) uniform sampler2D uLensShadingMap; - -float cubicWeight(float x) { - x = abs(x); - if (x >= 2.0) return 0.0; - if (x < 1.0) { - return 1.0 - 2.5 * x * x + 1.5 * x * x * x; - } - return 2.0 - 4.0 * x + 2.5 * x * x - 0.5 * x * x * x; -} - -int getSampleColor(int cfaPattern, ivec2 samplePos, out int lscIdx) { - int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1); - int sampleColor = -1; - lscIdx = -1; - - if (cfaPattern == 0) { // RGGB - if (samplePhase == 0) { sampleColor = 0; lscIdx = 0; } - else if (samplePhase == 1) { sampleColor = 1; lscIdx = 1; } - else if (samplePhase == 2) { sampleColor = 1; lscIdx = 2; } - else { sampleColor = 2; lscIdx = 3; } - } else if (cfaPattern == 1) { // GRBG - if (samplePhase == 0) { sampleColor = 1; lscIdx = 1; } - else if (samplePhase == 1) { sampleColor = 0; lscIdx = 0; } - else if (samplePhase == 2) { sampleColor = 2; lscIdx = 3; } - else { sampleColor = 1; lscIdx = 2; } - } else if (cfaPattern == 2) { // GBRG - if (samplePhase == 0) { sampleColor = 1; lscIdx = 2; } - else if (samplePhase == 1) { sampleColor = 2; lscIdx = 3; } - else if (samplePhase == 2) { sampleColor = 0; lscIdx = 0; } - else { sampleColor = 1; lscIdx = 1; } - } else { // BGGR - if (samplePhase == 0) { sampleColor = 2; lscIdx = 3; } - else if (samplePhase == 1) { sampleColor = 1; lscIdx = 2; } - else if (samplePhase == 2) { sampleColor = 1; lscIdx = 1; } - else { sampleColor = 0; lscIdx = 0; } - } - return sampleColor; -} - -ivec2 getLatticeParity(int cfaPattern, int targetCFA, int familyIndex) { - if (cfaPattern == 0) { // RGGB - if (targetCFA == 0) return ivec2(0, 0); - if (targetCFA == 2) return ivec2(1, 1); - return (familyIndex == 0) ? ivec2(1, 0) : ivec2(0, 1); - } else if (cfaPattern == 1) { // GRBG - if (targetCFA == 0) return ivec2(1, 0); - if (targetCFA == 2) return ivec2(0, 1); - return (familyIndex == 0) ? ivec2(0, 0) : ivec2(1, 1); - } else if (cfaPattern == 2) { // GBRG - if (targetCFA == 0) return ivec2(0, 1); - if (targetCFA == 2) return ivec2(1, 0); - return (familyIndex == 0) ? ivec2(0, 0) : ivec2(1, 1); - } else { // BGGR - if (targetCFA == 0) return ivec2(1, 1); - if (targetCFA == 2) return ivec2(0, 0); - return (familyIndex == 0) ? ivec2(1, 0) : ivec2(0, 1); - } -} - -float nearestFamilyDistanceSq(vec2 centerPos, ivec2 parity) { - vec2 lattice = 0.5 * (centerPos - vec2(parity)); - vec2 nearest = floor(lattice + 0.5); - vec2 samplePos = nearest * 2.0 + vec2(parity); - vec2 d = samplePos - centerPos; - return dot(d, d); -} - -// Helper to get inverse kernel matrix from parameters -// Params: k1, k2, cos2t, sin2t -// Output: Inverse Covariance Matrix components (a, b, c) -> [a b; b c] -vec3 getKernelMatrix(vec4 params) { - float k1 = params.x; - float k2 = params.y; - float c2 = params.z; // cos(2theta) - float s2 = params.w; // sin(2theta) - - float k_sum = k1 + k2; - float k_diff = k1 - k2; - - float a = 0.5 * (k_sum + k_diff * c2); - float c_val = 0.5 * (k_sum - k_diff * c2); - float b = 0.5 * k_diff * s2; - - return vec3(a, b, c_val); -} - -void main() { - uint tx = gl_GlobalInvocationID.x; - uint ty = gl_GlobalInvocationID.y; - - if (tx >= pc.tileW || ty >= pc.tileH) return; - - // Output Coordinate (RGB Pixel) - uint outX = pc.tileX + tx; - uint outY = pc.tileY + ty; - - if (outX >= pc.width || outY >= pc.height) return; - - // 1. Fetch Kernel Parameters from Base Frame (Structure Tensor) - // Structure Tensor is computed at Half-Res (Plane Resolution) of Input - uint nativeX = uint(float(outX) / pc.scale); - uint nativeY = uint(float(outY) / pc.scale); - uint planeX = nativeX / 2; - uint planeY = nativeY / 2; - planeX = clamp(planeX, 0, pc.planeWidth - 1); - planeY = clamp(planeY, 0, pc.planeHeight - 1); - - // Fetch Kernel Params from Buffer - uint kIdx = planeY * pc.planeWidth + planeX; - vec4 kParams = kernelParams.data[kIdx]; - - // Compute Inverse Covariance Matrix - vec3 OmegaInv = getKernelMatrix(kParams); - - // 2. Accumulate Contributions - vec2 accumVal = vec2(0.0); - - // This shader processes a specific Output Channel (pc.outputChannel). - int targetCFA = int(pc.outputChannel); // 0=R, 1=G, 2=B - - // Get Alignment Flow (from map) with bilinear interpolation - vec2 flow = vec2(0.0); - if (pc.isFirstFrame == 0) { - // Bilinear interpolation of flow field for smooth sub-tile alignment - vec2 gCoord = vec2(float(planeX), float(planeY)) / float(pc.tileSize) - 0.5; - ivec2 g0 = ivec2(floor(gCoord)); - vec2 gf = gCoord - vec2(g0); - ivec2 g1 = g0 + 1; - g0 = clamp(g0, ivec2(0), ivec2(int(pc.gridW)-1, int(pc.gridH)-1)); - g1 = clamp(g1, ivec2(0), ivec2(int(pc.gridW)-1, int(pc.gridH)-1)); - - vec2 f00 = alignBuffer.offsets[g0.y * pc.gridW + g0.x]; - vec2 f10 = alignBuffer.offsets[g0.y * pc.gridW + g1.x]; - vec2 f01 = alignBuffer.offsets[g1.y * pc.gridW + g0.x]; - vec2 f11 = alignBuffer.offsets[g1.y * pc.gridW + g1.x]; - flow = mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y); - } - - vec2 flowRaw = flow * 2.0; // In raw pixels - - // Projected Center in Input Frame - vec2 centerPos = vec2(float(outX) / pc.scale, float(outY) / pc.scale) + flowRaw; - - // Reconstruct on the Bayer color lattice instead of averaging over a dense - // square neighborhood. This preserves sub-pixel sample placement better. - int familyCount = (targetCFA == 1) ? 2 : 1; - int dominantFamily = 0; - if (targetCFA == 1 && pc.scale > 1.5) { - float bestDist = 1e10; - for (int family = 0; family < 2; ++family) { - ivec2 parity = getLatticeParity(int(pc.cfaPattern), targetCFA, family); - float distSq = nearestFamilyDistanceSq(centerPos, parity); - if (distSq < bestDist) { - bestDist = distSq; - dominantFamily = family; - } - } - } - - for (int family = 0; family < familyCount; ++family) { - ivec2 parity = getLatticeParity(int(pc.cfaPattern), targetCFA, family); - vec2 latticeCenter = 0.5 * (centerPos - vec2(parity)); - ivec2 latticeBase = ivec2(floor(latticeCenter)); - float familyWeight = 1.0; - if (targetCFA == 1 && pc.scale > 1.5) { - familyWeight = (family == dominantFamily) ? 1.0 : 0.12; - } - - for (int ly = -1; ly <= 1; ++ly) { - for (int lx = -1; lx <= 1; ++lx) { - ivec2 latticeCoord = latticeBase + ivec2(lx, ly); - ivec2 samplePos = latticeCoord * 2 + parity; - - if (samplePos.x < 0 || samplePos.y < 0 || - samplePos.x >= int(pc.sensorWidth) || - samplePos.y >= int(pc.sensorHeight)) { - continue; - } - - int lscIdx = -1; - int sampleColor = getSampleColor(int(pc.cfaPattern), samplePos, lscIdx); - if (sampleColor != targetCFA) continue; - - // --- Strict Weight Calculation --- - - // Spatial Distance d = samplePos - centerPos (in raw sensor pixels) - vec2 d_raw = vec2(samplePos) - centerPos; - vec2 d = d_raw * 0.5; - - float mahalanobis = OmegaInv.x * d.x * d.x + - (OmegaInv.y * d.x * d.y) * 2.0 + - OmegaInv.z * d.y * d.y; - - float raw = texelFetch(inputRawSampler, samplePos, 0).r; - - int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1); - float black = pc.blackLevel[samplePhase]; - float val = max(0.0, raw * 65535.0 - black); - - vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight); - vec4 lscGains = texture(uLensShadingMap, lscUV); - float lscGain = 1.0; - if (lscIdx == 0) lscGain = lscGains.r; - else if (lscIdx == 1) lscGain = lscGains.g; - else if (lscIdx == 2) lscGain = lscGains.b; - else if (lscIdx == 3) lscGain = lscGains.a; - - val *= lscGain; - val /= 65535.0; - - int rX = clamp(samplePos.x / 2, 0, int(pc.planeWidth)-1); - int rY = clamp(samplePos.y / 2, 0, int(pc.planeHeight)-1); - - float pInlier = 1.0; - float flowVar = 0.03; - if (pc.isFirstFrame == 0) { - uint confidenceIdx = rY * pc.planeWidth + rX; - pInlier = outRobustness.data[confidenceIdx]; - flowVar = flowVarianceBuffer.data[confidenceIdx]; - } - - vec2 d_hr = d_raw * pc.scale; - float reconWeight = cubicWeight(d_hr.x) * cubicWeight(d_hr.y); - if (reconWeight <= 0.0) continue; - - float effectiveSigma2 = 1.0 + 4.0 * flowVar; - float inlierWeight = 0.18 + 0.82 * pInlier; - float w = inlierWeight * - exp(-0.5 * max(mahalanobis, 0.0) / effectiveSigma2) * - reconWeight * (0.45 + 0.55 * pc.frameWeight) * - familyWeight; - - accumVal += vec2(val * w, w); - } - } - } - - // Write to Accumulator - uint accIdx = ty * pc.bufferStride + tx; - - // We add to existing value (atomic/race managed by careful dispatch or just atomic add? - // Here we are single-threaded per output pixel. No race if we just add.) - // But buffer is "coherent". - // We strictly accumulate. - accumulator.data[accIdx] += accumVal; -} diff --git a/app/src/main/cpp/shaders/color_scatter_raw.comp b/app/src/main/cpp/shaders/color_scatter_raw.comp index db8f4953..0439dacc 100644 --- a/app/src/main/cpp/shaders/color_scatter_raw.comp +++ b/app/src/main/cpp/shaders/color_scatter_raw.comp @@ -75,6 +75,22 @@ vec2 sampleFlow(vec2 planeCoord) { return mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y); } +int getBayerIndex(int cfaPattern, ivec2 samplePos) { + int phase = (samplePos.y & 1) * 2 + (samplePos.x & 1); + if (cfaPattern == 0) { + return phase; // RGGB -> R, Gr, Gb, B + } else if (cfaPattern == 1) { + const int map[4] = int[4](1, 0, 3, 2); + return map[phase]; + } else if (cfaPattern == 2) { + const int map[4] = int[4](2, 3, 0, 1); + return map[phase]; + } else { + const int map[4] = int[4](3, 2, 1, 0); + return map[phase]; + } +} + bool sampleMatchesTarget(ivec2 pos, out int lscIdx) { int phase = (pos.y & 1) * 2 + (pos.x & 1); lscIdx = -1; @@ -110,8 +126,8 @@ void main() { ivec2 base = ivec2(floor(outCenter)); float raw = texelFetch(inputRawSampler, samplePos, 0).r; - int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1); - float val = max(0.0, raw * 65535.0 - pc.blackLevel[samplePhase]); + int bayerIndex = getBayerIndex(int(pc.cfaPattern), samplePos); + float val = max(0.0, raw * 65535.0 - pc.blackLevel[bayerIndex]); vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight); vec4 lscGains = texture(uLensShadingMap, lscUV); float lscGain = (lscIdx == 0) ? lscGains.r : lscGains.a; diff --git a/app/src/main/cpp/shaders/green_scatter_raw.comp b/app/src/main/cpp/shaders/green_scatter_raw.comp index 498d12a3..bf216f8b 100644 --- a/app/src/main/cpp/shaders/green_scatter_raw.comp +++ b/app/src/main/cpp/shaders/green_scatter_raw.comp @@ -87,6 +87,22 @@ vec2 sampleFlow(vec2 planeCoord) { return mix(mix(f00, f10, gf.x), mix(f01, f11, gf.x), gf.y); } +int getBayerIndex(int cfaPattern, ivec2 samplePos) { + int phase = (samplePos.y & 1) * 2 + (samplePos.x & 1); + if (cfaPattern == 0) { + return phase; // RGGB -> R, Gr, Gb, B + } else if (cfaPattern == 1) { + const int map[4] = int[4](1, 0, 3, 2); + return map[phase]; + } else if (cfaPattern == 2) { + const int map[4] = int[4](2, 3, 0, 1); + return map[phase]; + } else { + const int map[4] = int[4](3, 2, 1, 0); + return map[phase]; + } +} + int getGreenFamily(int cfaPattern, ivec2 samplePos, out int lscIdx) { int phase = (samplePos.y & 1) * 2 + (samplePos.x & 1); lscIdx = -1; @@ -177,8 +193,8 @@ void main() { vec2 outCenter = refPos * pc.scale; float raw = texelFetch(inputRawSampler, samplePos, 0).r; - int samplePhase = (samplePos.y & 1) * 2 + (samplePos.x & 1); - float val = max(0.0, raw * 65535.0 - pc.blackLevel[samplePhase]); + int bayerIndex = getBayerIndex(int(pc.cfaPattern), samplePos); + float val = max(0.0, raw * 65535.0 - pc.blackLevel[bayerIndex]); vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight); vec4 lscGains = texture(uLensShadingMap, lscUV); diff --git a/app/src/main/cpp/shaders/normalize_color_hr.comp b/app/src/main/cpp/shaders/normalize_color_hr.comp index 5ed354d5..8f6db2db 100644 --- a/app/src/main/cpp/shaders/normalize_color_hr.comp +++ b/app/src/main/cpp/shaders/normalize_color_hr.comp @@ -7,6 +7,8 @@ layout(local_size_x = 16, local_size_y = 16) in; layout(binding = 0, scalar) buffer OutputBuffer { uint16_t data[]; } outputBuffer; layout(binding = 1, scalar) buffer ColorAccum { uvec2 data[]; } colorAccum; +layout(binding = 2, scalar) buffer PriorBuffer { uint16_t data[]; } priorBuffer; +layout(binding = 3, scalar) buffer PriorWeightBuffer { uint16_t data[]; } priorWeightBuffer; layout(push_constant, scalar) uniform PushConstants { uint width; @@ -48,44 +50,111 @@ float accumMean(uvec2 accum) { return float(accum.x) / max(float(accum.y), 1.0) / 65535.0; } +void gatherNeighborhoodEstimate(int centerX, int centerY, + out float meanVal, out float support) { + float sum = 0.0; + float weight = 0.0; + for (int oy = -2; oy <= 2; ++oy) { + for (int ox = -2; ox <= 2; ++ox) { + if (ox == 0 && oy == 0) continue; + uvec2 neighAccum = readAccum(centerX + ox, centerY + oy); + if (neighAccum.y == 0u) continue; + + float spatialWeight = 1.0 / (1.0 + float(ox * ox + oy * oy)); + float sampleSupport = clamp(float(neighAccum.y) / 256.0, 0.15, 1.0); + float w = spatialWeight * sampleSupport; + sum += accumMean(neighAccum) * w; + weight += w; + } + } + + if (weight > 0.0) { + meanVal = sum / weight; + support = clamp(weight / 3.0, 0.0, 1.0); + } else { + meanVal = 0.0; + support = 0.0; + } +} + +int getBayerIndex(uint cfaPattern, uvec2 pos) { + uint phase = ((pos.y & 1u) << 1u) | (pos.x & 1u); + if (cfaPattern == 0u) { + return int(phase); // RGGB -> R,Gr,Gb,B + } else if (cfaPattern == 1u) { + const int map[4] = int[4](1, 0, 3, 2); + return map[phase]; + } else if (cfaPattern == 2u) { + const int map[4] = int[4](2, 3, 0, 1); + return map[phase]; + } else { + const int map[4] = int[4](3, 2, 1, 0); + return map[phase]; + } +} + +bool matchesTargetColor(int bayerIndex, uint planeIndex) { + if (planeIndex == 0u) return bayerIndex == 0; + if (planeIndex == 2u) return bayerIndex == 3; + return false; +} + void main() { uint tx = gl_GlobalInvocationID.x; uint ty = gl_GlobalInvocationID.y; - uint outX = pc.tileX + tx; - uint outY = pc.tileY + ty; + uint globalX = pc.tileX + tx; + uint globalY = pc.tileY + ty; if (tx >= pc.tileW || ty >= pc.tileH) return; - if (outX >= pc.width || outY >= pc.height) return; + if (globalX >= pc.width || globalY >= pc.height) return; + + int bayerIndex = getBayerIndex(pc.cfaPattern, uvec2(globalX, globalY)); + if (!matchesTargetColor(bayerIndex, pc.planeIndex)) return; uvec2 accum = colorAccum.data[ty * pc.bufferStride + tx]; - float resLinear = 0.0; - if (accum.y > 0u) { - float val = accumMean(accum); - float confidence = clamp(float(accum.y) / 768.0, 0.0, 1.0); - if (confidence < 0.999) { - float neighSum = 0.0; - float neighWeight = 0.0; - for (int oy = -1; oy <= 1; ++oy) { - for (int ox = -1; ox <= 1; ++ox) { - if (ox == 0 && oy == 0) continue; - uvec2 neighAccum = readAccum(int(tx) + ox, int(ty) + oy); - if (neighAccum.y == 0u) continue; - float w = (ox == 0 || oy == 0) ? 1.0 : 0.7; - neighSum += accumMean(neighAccum) * w; - neighWeight += w; - } - } - if (neighWeight > 0.0) { - float neighVal = neighSum / neighWeight; - float highlightBlend = smoothstep(0.70, 0.96, max(val, neighVal)); - val = mix(neighVal, val, confidence * (1.0 - 0.55 * highlightBlend)); - } - } + float neighborVal = 0.0; + float neighborSupport = 0.0; + gatherNeighborhoodEstimate(int(tx), int(ty), neighborVal, neighborSupport); - float gain = (pc.planeIndex == 0u) ? pc.wbGains[0] : pc.wbGains[3]; - float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25; - resLinear = (val * 65535.0) / (pc.whiteLevel - bl_avg) * gain; + uint outIndex = ty * pc.width + globalX; + float priorNorm = float(priorBuffer.data[outIndex]) / 65535.0; + float priorSupport = float(priorWeightBuffer.data[outIndex]) / 65535.0; + + float observationNorm = 0.0; + float observationSupport = 0.0; + float val = 0.0; + bool hasEstimate = false; + if (accum.y > 0u) { + val = accumMean(accum); + float confidence = clamp(float(accum.y) / 768.0, 0.0, 1.0); + observationSupport = confidence; + if (neighborSupport > 0.0 && confidence < 0.999) { + float highlightBlend = smoothstep(0.70, 0.96, max(val, neighborVal)); + float preserveCenter = confidence * (1.0 - 0.55 * highlightBlend); + val = mix(neighborVal, val, preserveCenter); + observationSupport = max(observationSupport, 0.30 * neighborSupport); + } + hasEstimate = true; + } else if (neighborSupport > 0.0) { + val = neighborVal; + observationSupport = 0.24 * neighborSupport; + hasEstimate = true; } - uint outIndex = (outY * pc.width + outX) * 3 + pc.planeIndex; - outputBuffer.data[outIndex] = uint16_t(clamp(resLinear * 65535.0, 0.0, 65535.0)); + float normalizedRaw = 0.0; + if (hasEstimate) { + float whiteRange = max(pc.whiteLevel - pc.blackLevel[bayerIndex], 1.0); + observationNorm = (val * 65535.0) / whiteRange; + } + + if (hasEstimate && priorSupport > 0.0) { + float obsBlend = observationSupport / + max(observationSupport + priorSupport, 1e-5); + normalizedRaw = mix(priorNorm, observationNorm, obsBlend); + } else if (hasEstimate) { + normalizedRaw = observationNorm; + } else if (priorSupport > 0.0) { + normalizedRaw = priorNorm; + } + + outputBuffer.data[outIndex] = uint16_t(clamp(normalizedRaw * 65535.0, 0.0, 65535.0)); } diff --git a/app/src/main/cpp/shaders/normalize_green_hr.comp b/app/src/main/cpp/shaders/normalize_green_hr.comp index a1828970..974e955a 100644 --- a/app/src/main/cpp/shaders/normalize_green_hr.comp +++ b/app/src/main/cpp/shaders/normalize_green_hr.comp @@ -17,6 +17,14 @@ layout(binding = 2, scalar) buffer GreenPhase1 { uvec2 data[]; } greenPhase1; +layout(binding = 3, scalar) buffer PriorBuffer { + uint16_t data[]; +} priorBuffer; + +layout(binding = 4, scalar) buffer PriorWeightBuffer { + uint16_t data[]; +} priorWeightBuffer; + layout(push_constant, scalar) uniform PushConstants { uint width; uint height; @@ -51,76 +59,155 @@ layout(push_constant, scalar) uniform PushConstants { float frameWeight; } pc; +float accumMean(uvec2 accum) { + if (accum.y == 0u) return 0.0; + return float(accum.x) / max(float(accum.y), 1.0) / 65535.0; +} + +uvec2 readGreenAccum(int familyIndex, int x, int y) { + x = clamp(x, 0, int(pc.tileW) - 1); + y = clamp(y, 0, int(pc.tileH) - 1); + uint idx = uint(y) * pc.bufferStride + uint(x); + return (familyIndex == 0) ? greenPhase0.data[idx] : greenPhase1.data[idx]; +} + +void gatherGreenNeighborhood(int familyIndex, int centerX, int centerY, + out float meanVal, out float support) { + float sum = 0.0; + float weight = 0.0; + for (int oy = -2; oy <= 2; ++oy) { + for (int ox = -2; ox <= 2; ++ox) { + if (ox == 0 && oy == 0) continue; + uvec2 neighAccum = readGreenAccum(familyIndex, centerX + ox, centerY + oy); + if (neighAccum.y == 0u) continue; + + float spatialWeight = 1.0 / (1.0 + float(ox * ox + oy * oy)); + float sampleSupport = clamp(float(neighAccum.y) / 256.0, 0.15, 1.0); + float w = spatialWeight * sampleSupport; + sum += accumMean(neighAccum) * w; + weight += w; + } + } + + if (weight > 0.0) { + meanVal = sum / weight; + support = clamp(weight / 3.0, 0.0, 1.0); + } else { + meanVal = 0.0; + support = 0.0; + } +} + +bool getGreenSite(uint cfaPattern, uvec2 pos, out int familyIndex, out int bayerIndex) { + uint phase = ((pos.y & 1u) << 1u) | (pos.x & 1u); + familyIndex = -1; + bayerIndex = -1; + + if (cfaPattern == 0u) { // RGGB + if (phase == 1u) { familyIndex = 0; bayerIndex = 1; return true; } + if (phase == 2u) { familyIndex = 1; bayerIndex = 2; return true; } + } else if (cfaPattern == 1u) { // GRBG + if (phase == 0u) { familyIndex = 0; bayerIndex = 1; return true; } + if (phase == 3u) { familyIndex = 1; bayerIndex = 2; return true; } + } else if (cfaPattern == 2u) { // GBRG + if (phase == 3u) { familyIndex = 0; bayerIndex = 1; return true; } + if (phase == 0u) { familyIndex = 1; bayerIndex = 2; return true; } + } else { // BGGR + if (phase == 2u) { familyIndex = 0; bayerIndex = 1; return true; } + if (phase == 1u) { familyIndex = 1; bayerIndex = 2; return true; } + } + + return false; +} + void main() { uint tx = gl_GlobalInvocationID.x; uint ty = gl_GlobalInvocationID.y; - uint outX = pc.tileX + tx; - uint outY = pc.tileY + ty; + uint globalX = pc.tileX + tx; + uint globalY = pc.tileY + ty; if (tx >= pc.tileW || ty >= pc.tileH) return; - if (outX >= pc.width || outY >= pc.height) return; + if (globalX >= pc.width || globalY >= pc.height) return; - uint idx = ty * pc.bufferStride + tx; - uvec2 p0 = greenPhase0.data[idx]; - uvec2 p1 = greenPhase1.data[idx]; - - float weight0 = float(p0.y); - float weight1 = float(p1.y); - float resLinear = 0.0; - if (weight0 + weight1 > 0.0) { - bool has0 = weight0 > 0.0; - bool has1 = weight1 > 0.0; - float g0 = has0 ? (float(p0.x) / max(weight0, 1e-6) / 65535.0) : 0.0; - float g1 = has1 ? (float(p1.x) / max(weight1, 1e-6) / 65535.0) : 0.0; - float blend0 = weight0; - float blend1 = weight1; - - float val = 0.0; - - if (has0 && has1) { - float diff = abs(g0 - g1); - float consistency = 1.0 - smoothstep(0.010, 0.050, diff); - float dominant0 = step(blend1, blend0); - float dominant1 = 1.0 - dominant0; - float avgVal = (g0 * blend0 + g1 * blend1) / max(blend0 + blend1, 1e-6); - float dominantVal = g0 * dominant0 + g1 * dominant1; - val = mix(dominantVal, avgVal, consistency); - - float inconsistency = 1.0 - consistency; - uint baseIndex = (outY * pc.width + outX) * 3; - float rLinear = float(outputBuffer.data[baseIndex + 0]) / 65535.0; - float bLinear = float(outputBuffer.data[baseIndex + 2]) / 65535.0; - float rbMean = 0.5 * (rLinear + bLinear); - float rbMax = max(rLinear, bLinear); - float highlight = smoothstep(0.68, 0.95, max(max(g0, g1), rbMax)); - val = mix(val, avgVal, 0.35 * highlight); - float greenCeiling = mix(max(rbMean * 1.35 + 0.015, rbMax * 1.18 + 0.010), - max(rbMean * 1.08 + 0.003, rbMax * 1.04 + 0.002), - highlight); - val = mix(val, min(val, greenCeiling), - smoothstep(0.20, 0.75, inconsistency) + 0.55 * highlight); - } else if (has0) { - val = g0; - } else { - val = g1; - } - - uint baseIndex = (outY * pc.width + outX) * 3; - float rLinear = float(outputBuffer.data[baseIndex + 0]) / 65535.0; - float bLinear = float(outputBuffer.data[baseIndex + 2]) / 65535.0; - float rbMean = 0.5 * (rLinear + bLinear); - float rbMax = max(rLinear, bLinear); - float highlight = smoothstep(0.72, 0.97, max(val, rbMax)); - float singlePhasePenalty = (has0 ^^ has1) ? 1.0 : 0.0; - float strictCeiling = max(rbMean * 1.06 + 0.002, rbMax * 1.03 + 0.002); - float strictBlend = clamp(0.65 * highlight + 0.35 * singlePhasePenalty, 0.0, 1.0); - val = mix(val, min(val, strictCeiling), strictBlend); - - float gain = (pc.wbGains[1] + pc.wbGains[2]) * 0.5; - float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25; - resLinear = (val * 65535.0) / (pc.whiteLevel - bl_avg) * gain; + int familyIndex = -1; + int bayerIndex = -1; + if (!getGreenSite(pc.cfaPattern, uvec2(globalX, globalY), familyIndex, bayerIndex)) { + return; } - uint outIndex = (outY * pc.width + outX) * 3 + 1; - outputBuffer.data[outIndex] = uint16_t(clamp(resLinear * 65535.0, 0.0, 65535.0)); + uint idx = ty * pc.bufferStride + tx; + uvec2 primary = (familyIndex == 0) ? greenPhase0.data[idx] : greenPhase1.data[idx]; + uvec2 secondary = (familyIndex == 0) ? greenPhase1.data[idx] : greenPhase0.data[idx]; + float primaryNeighborVal = 0.0; + float primaryNeighborSupport = 0.0; + float secondaryNeighborVal = 0.0; + float secondaryNeighborSupport = 0.0; + gatherGreenNeighborhood(familyIndex, int(tx), int(ty), + primaryNeighborVal, primaryNeighborSupport); + gatherGreenNeighborhood(1 - familyIndex, int(tx), int(ty), + secondaryNeighborVal, secondaryNeighborSupport); + + uint outIndex = ty * pc.width + globalX; + float priorNorm = float(priorBuffer.data[outIndex]) / 65535.0; + float priorSupport = float(priorWeightBuffer.data[outIndex]) / 65535.0; + + float observationNorm = 0.0; + float observationSupport = 0.0; + float normalizedRaw = 0.0; + if (primary.y > 0u || secondary.y > 0u || + primaryNeighborSupport > 0.0 || secondaryNeighborSupport > 0.0) { + float primaryVal = accumMean(primary); + float secondaryVal = accumMean(secondary); + float primaryConfidence = clamp(float(primary.y) / 768.0, 0.0, 1.0); + float secondaryConfidence = clamp(float(secondary.y) / 768.0, 0.0, 1.0); + observationSupport = max(primaryConfidence, 0.70 * secondaryConfidence); + observationSupport = max(observationSupport, 0.28 * primaryNeighborSupport); + observationSupport = max(observationSupport, 0.20 * secondaryNeighborSupport); + float val = (primary.y > 0u) ? primaryVal : + (secondary.y > 0u ? secondaryVal : + (primaryNeighborSupport >= secondaryNeighborSupport + ? primaryNeighborVal + : secondaryNeighborVal)); + + if (primary.y > 0u && secondary.y > 0u) { + float phaseDiff = abs(primaryVal - secondaryVal); + float crossPhaseBlend = 1.0 - smoothstep(0.020, 0.080, phaseDiff); + val = mix(secondaryVal, primaryVal, max(primaryConfidence, 0.25)); + val = mix(val, 0.5 * (primaryVal + secondaryVal), 0.25 * crossPhaseBlend); + } else if (primary.y == 0u && secondary.y == 0u) { + if (primaryNeighborSupport > 0.0 && secondaryNeighborSupport > 0.0) { + float blend = primaryNeighborSupport / + max(primaryNeighborSupport + secondaryNeighborSupport, 1e-5); + val = mix(secondaryNeighborVal, primaryNeighborVal, blend); + } else if (primaryNeighborSupport > 0.0) { + val = primaryNeighborVal; + } else { + val = secondaryNeighborVal; + } + observationSupport = max(0.22 * primaryNeighborSupport, + 0.18 * secondaryNeighborSupport); + } + + if (primaryNeighborSupport > 0.0 && primaryConfidence < 0.999) { + val = mix(primaryNeighborVal, val, primaryConfidence); + } + if (primary.y == 0u && secondaryNeighborSupport > 0.0 && secondaryConfidence < 0.999) { + val = mix(secondaryNeighborVal, val, max(secondaryConfidence, 0.35)); + } + + float whiteRange = max(pc.whiteLevel - pc.blackLevel[bayerIndex], 1.0); + observationNorm = (val * 65535.0) / whiteRange; + } + + if (observationSupport > 0.0 && priorSupport > 0.0) { + float obsBlend = observationSupport / + max(observationSupport + priorSupport, 1e-5); + normalizedRaw = mix(priorNorm, observationNorm, obsBlend); + } else if (observationSupport > 0.0) { + normalizedRaw = observationNorm; + } else if (priorSupport > 0.0) { + normalizedRaw = priorNorm; + } + + outputBuffer.data[outIndex] = uint16_t(clamp(normalizedRaw * 65535.0, 0.0, 65535.0)); } diff --git a/app/src/main/cpp/shaders/normalize_raw.comp b/app/src/main/cpp/shaders/normalize_raw.comp deleted file mode 100644 index 6004174b..00000000 --- a/app/src/main/cpp/shaders/normalize_raw.comp +++ /dev/null @@ -1,117 +0,0 @@ -#version 450 -#extension GL_EXT_scalar_block_layout : require -#extension GL_EXT_shader_16bit_storage : require -#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require - -layout(local_size_x = 16, local_size_y = 16) in; - -// Output buffer: RAW16 data in Bayer pattern (full resolution) -layout(binding = 0, scalar) buffer OutputBuffer { - uint16_t data[]; -} outputBuffer; - -// Input: Accumulator for ONE plane -layout(binding = 1, scalar) buffer Accumulator { - vec2 data[]; // (sum, weight) -} accumulator; - -layout(push_constant, scalar) uniform PushConstants { - uint width; - uint height; - uint planeWidth; - uint planeHeight; - uint sensorWidth; - uint sensorHeight; - - float scale; - - float blackLevel[4]; - float whiteLevel; - float wbGains[4]; - - uint isFirstFrame; - uint outputChannel; - uint cfaPattern; - uint planeIndex; - - uint tileX; - uint tileY; - uint tileW; - uint tileH; - uint bufferStride; - uint gridW; - uint gridH; - uint tileSize; - - float noiseAlpha; - float noiseBeta; - float baseNoise; -} pc; - -vec2 readAccum(int x, int y) { - x = clamp(x, 0, int(pc.tileW) - 1); - y = clamp(y, 0, int(pc.tileH) - 1); - uint idx = uint(y) * pc.bufferStride + uint(x); - return accumulator.data[idx]; -} - -float accumToLinear(vec2 accum, float gain, float whiteRangeInv) { - if (accum.y <= 0.0) return 0.0; - float val = accum.x / accum.y; - return (val * 65535.0) * whiteRangeInv * gain; -} - -void main() { - uint tx = gl_GlobalInvocationID.x; - uint ty = gl_GlobalInvocationID.y; - - // Global output coordinates - uint outX = pc.tileX + tx; - uint outY = pc.tileY + ty; - - // Bounds check within this tile - if (tx >= pc.tileW || ty >= pc.tileH) return; - - // Ensure we don't go out of bounds of the full image - if (outX >= pc.width || outY >= pc.height) return; - - // Read Accumulator - uint accIndex = ty * pc.bufferStride + tx; - vec2 accum = accumulator.data[accIndex]; - - float gain = 1.0; - - // Map planeIndex (R=0, G=1, B=2) to Bayer offsets for black level and WB gains - // RGGB/Metadata/mWbGains: 0=R, 1=Gr, 2=Gb, 3=B - if (pc.planeIndex == 0) { // Red - gain = pc.wbGains[0]; - } else if (pc.planeIndex == 1) { // Green (Average of Gr/Gb) - gain = (pc.wbGains[1] + pc.wbGains[2]) * 0.5; - } else { // Blue (planeIndex == 2) - gain = pc.wbGains[3]; - } - - float bl_avg = (pc.blackLevel[0] + pc.blackLevel[1] + pc.blackLevel[2] + pc.blackLevel[3]) * 0.25; - float whiteRangeInv = 1.0 / max(pc.whiteLevel - bl_avg, 1.0); - float resLinear = accumToLinear(accum, gain, whiteRangeInv); - - // Conservative detail recovery on green only, gated by accumulated confidence. - if (pc.planeIndex == 1u && accum.y > 0.65) { - float left = accumToLinear(readAccum(int(tx) - 1, int(ty)), gain, whiteRangeInv); - float right = accumToLinear(readAccum(int(tx) + 1, int(ty)), gain, whiteRangeInv); - float up = accumToLinear(readAccum(int(tx), int(ty) - 1), gain, whiteRangeInv); - float down = accumToLinear(readAccum(int(tx), int(ty) + 1), gain, whiteRangeInv); - float neighborAvg = 0.25 * (left + right + up + down); - float detail = resLinear - neighborAvg; - float localContrast = abs(detail) / max(resLinear + neighborAvg + 1e-4, 1e-4); - float sharpenAmount = 0.18 * smoothstep(0.02, 0.12, localContrast); - resLinear = max(resLinear + detail * sharpenAmount, 0.0); - } - - // Write Interleaved RGB (R, G, B, R, G, B...) - uint outIndex = (outY * pc.width + outX) * 3 + pc.planeIndex; - - // Scale to full uint16 range for the Linear RGB processor in Kotlin - uint16_t outVal = uint16_t(clamp(resLinear * 65535.0, 0.0, 65535.0)); - outputBuffer.data[outIndex] = outVal; -} diff --git a/app/src/main/cpp/shaders/reference_preprocess_raw.comp b/app/src/main/cpp/shaders/reference_preprocess_raw.comp new file mode 100644 index 00000000..69184842 --- /dev/null +++ b/app/src/main/cpp/shaders/reference_preprocess_raw.comp @@ -0,0 +1,84 @@ +#version 450 +#extension GL_EXT_scalar_block_layout : require +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require + +layout(local_size_x = 16, local_size_y = 16) in; + +layout(binding = 0) uniform sampler2D inputRawSampler; +layout(binding = 1, scalar) buffer NormalizedReferenceBuffer { + uint16_t data[]; +} normalizedReferenceBuffer; +layout(binding = 2) uniform sampler2D uLensShadingMap; + +layout(push_constant, scalar) uniform PushConstants { + uint width; + uint height; + uint planeWidth; + uint planeHeight; + uint sensorWidth; + uint sensorHeight; + float scale; + float blackLevel[4]; + float whiteLevel; + float wbGains[4]; + uint isFirstFrame; + uint outputChannel; + uint cfaPattern; + uint planeIndex; + uint tileX; + uint tileY; + uint tileW; + uint tileH; + uint bufferStride; + uint gridW; + uint gridH; + uint tileSize; + float noiseAlpha; + float noiseBeta; + float baseNoise; + float frameWeight; +} pc; + +int getBayerIndex(uint cfaPattern, uvec2 pos) { + uint phase = ((pos.y & 1u) << 1u) | (pos.x & 1u); + if (cfaPattern == 0u) { + return int(phase); + } else if (cfaPattern == 1u) { + const int map[4] = int[4](1, 0, 3, 2); + return map[phase]; + } else if (cfaPattern == 2u) { + const int map[4] = int[4](2, 3, 0, 1); + return map[phase]; + } else { + const int map[4] = int[4](3, 2, 1, 0); + return map[phase]; + } +} + +float getLscGain(int bayerIndex, ivec2 samplePos) { + vec2 lscUV = (vec2(samplePos) + 0.5) / vec2(pc.sensorWidth, pc.sensorHeight); + vec4 lscGains = texture(uLensShadingMap, lscUV); + if (bayerIndex == 0) return lscGains.r; + if (bayerIndex == 1) return lscGains.g; + if (bayerIndex == 2) return lscGains.b; + return lscGains.a; +} + +void main() { + uint x = gl_GlobalInvocationID.x; + uint y = gl_GlobalInvocationID.y; + if (x >= pc.sensorWidth || y >= pc.sensorHeight) return; + + ivec2 samplePos = ivec2(x, y); + int bayerIndex = getBayerIndex(pc.cfaPattern, uvec2(x, y)); + + float raw = texelFetch(inputRawSampler, samplePos, 0).r; + float val = max(0.0, raw * 65535.0 - pc.blackLevel[bayerIndex]); + val = (val * getLscGain(bayerIndex, samplePos)) / 65535.0; + float whiteRange = max(pc.whiteLevel - pc.blackLevel[bayerIndex], 1.0); + float normalized = clamp((val * 65535.0) / whiteRange, 0.0, 1.0); + + normalizedReferenceBuffer.data[y * pc.sensorWidth + x] = + uint16_t(clamp(normalized * 65535.0, 0.0, 65535.0)); +} diff --git a/app/src/main/cpp/shaders/reference_prior_raw.comp b/app/src/main/cpp/shaders/reference_prior_raw.comp new file mode 100644 index 00000000..51fbece6 --- /dev/null +++ b/app/src/main/cpp/shaders/reference_prior_raw.comp @@ -0,0 +1,127 @@ +#version 450 +#extension GL_EXT_scalar_block_layout : require +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require + +layout(local_size_x = 16, local_size_y = 16) in; + +layout(binding = 0, scalar) buffer NormalizedReferenceBuffer { + uint16_t data[]; +} normalizedReferenceBuffer; +layout(binding = 1, scalar) buffer PriorBuffer { uint16_t data[]; } priorBuffer; +layout(binding = 2, scalar) buffer PriorWeightBuffer { uint16_t data[]; } priorWeightBuffer; + +layout(push_constant, scalar) uniform PushConstants { + uint width; + uint height; + uint planeWidth; + uint planeHeight; + uint sensorWidth; + uint sensorHeight; + float scale; + float blackLevel[4]; + float whiteLevel; + float wbGains[4]; + uint isFirstFrame; + uint outputChannel; + uint cfaPattern; + uint planeIndex; + uint tileX; + uint tileY; + uint tileW; + uint tileH; + uint bufferStride; + uint gridW; + uint gridH; + uint tileSize; + float noiseAlpha; + float noiseBeta; + float baseNoise; + float frameWeight; +} pc; + +int getBayerIndex(uint cfaPattern, uvec2 pos) { + uint phase = ((pos.y & 1u) << 1u) | (pos.x & 1u); + if (cfaPattern == 0u) { + return int(phase); // RGGB -> R, Gr, Gb, B + } else if (cfaPattern == 1u) { + const int map[4] = int[4](1, 0, 3, 2); + return map[phase]; + } else if (cfaPattern == 2u) { + const int map[4] = int[4](2, 3, 0, 1); + return map[phase]; + } else { + const int map[4] = int[4](3, 2, 1, 0); + return map[phase]; + } +} + +ivec2 getBayerOffset(uint cfaPattern, int bayerIndex) { + if (cfaPattern == 0u) { + const ivec2 map[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); + return map[bayerIndex]; + } else if (cfaPattern == 1u) { + const ivec2 map[4] = ivec2[4](ivec2(1, 0), ivec2(0, 0), ivec2(1, 1), ivec2(0, 1)); + return map[bayerIndex]; + } else if (cfaPattern == 2u) { + const ivec2 map[4] = ivec2[4](ivec2(0, 1), ivec2(1, 1), ivec2(0, 0), ivec2(1, 0)); + return map[bayerIndex]; + } else { + const ivec2 map[4] = ivec2[4](ivec2(1, 1), ivec2(0, 1), ivec2(1, 0), ivec2(0, 0)); + return map[bayerIndex]; + } +} + +float fetchNormalizedRaw(int bayerIndex, ivec2 samplePos) { + samplePos.x = clamp(samplePos.x, 0, int(pc.sensorWidth) - 1); + samplePos.y = clamp(samplePos.y, 0, int(pc.sensorHeight) - 1); + uint idx = uint(samplePos.y) * pc.sensorWidth + uint(samplePos.x); + return float(normalizedReferenceBuffer.data[idx]) / 65535.0; +} + +void samplePrior(int bayerIndex, vec2 sourcePos, + out float normalizedRaw, out float support) { + ivec2 offset = getBayerOffset(pc.cfaPattern, bayerIndex); + vec2 latticePos = 0.5 * (sourcePos - vec2(offset)); + ivec2 base = ivec2(floor(latticePos)); + vec2 frac = latticePos - vec2(base); + + ivec2 p00 = offset + 2 * base; + ivec2 p10 = p00 + ivec2(2, 0); + ivec2 p01 = p00 + ivec2(0, 2); + ivec2 p11 = p00 + ivec2(2, 2); + + float v00 = fetchNormalizedRaw(bayerIndex, p00); + float v10 = fetchNormalizedRaw(bayerIndex, p10); + float v01 = fetchNormalizedRaw(bayerIndex, p01); + float v11 = fetchNormalizedRaw(bayerIndex, p11); + + float vx0 = mix(v00, v10, frac.x); + float vx1 = mix(v01, v11, frac.x); + normalizedRaw = mix(vx0, vx1, frac.y); + + float sampleMin = min(min(v00, v10), min(v01, v11)); + float sampleMax = max(max(v00, v10), max(v01, v11)); + float coherence = 1.0 - smoothstep(0.04, 0.18, sampleMax - sampleMin); + float interpolationPenalty = + 0.5 * (4.0 * frac.x * (1.0 - frac.x) + 4.0 * frac.y * (1.0 - frac.y)); + float exactness = 1.0 - interpolationPenalty; + support = clamp(0.18 + 0.22 * coherence + 0.20 * exactness, 0.18, 0.60); +} + +void main() { + uint x = gl_GlobalInvocationID.x; + uint y = gl_GlobalInvocationID.y; + if (x >= pc.width || y >= pc.height) return; + + uint outIndex = y * pc.width + x; + int bayerIndex = getBayerIndex(pc.cfaPattern, uvec2(x, y)); + + vec2 sourcePos = vec2(x, y) / max(pc.scale, 1e-5); + float normalizedRaw = 0.0; + float support = 0.0; + samplePrior(bayerIndex, sourcePos, normalizedRaw, support); + + priorBuffer.data[outIndex] = uint16_t(clamp(normalizedRaw * 65535.0, 0.0, 65535.0)); + priorWeightBuffer.data[outIndex] = uint16_t(clamp(support * 65535.0, 0.0, 65535.0)); +} diff --git a/app/src/main/cpp/vulkan_raw_stacker.cpp b/app/src/main/cpp/vulkan_raw_stacker.cpp index 97ea34af..8e45db19 100644 --- a/app/src/main/cpp/vulkan_raw_stacker.cpp +++ b/app/src/main/cpp/vulkan_raw_stacker.cpp @@ -1,12 +1,12 @@ #include "vulkan_raw_stacker.h" -#include "accumulate_raw.comp.h" #include "align_lk.comp.h" #include "common.h" #include "color_scatter_raw.comp.h" #include "green_scatter_raw.comp.h" #include "normalize_color_hr.comp.h" -#include "normalize_raw.comp.h" #include "normalize_green_hr.comp.h" +#include "reference_preprocess_raw.comp.h" +#include "reference_prior_raw.comp.h" #include "raw_structure_tensor.comp.h" #include "robustness_raw.comp.h" #include @@ -27,14 +27,158 @@ constexpr uint32_t kDenseAlignmentGridSpacing = 8; constexpr int kAlignmentRegularizationPasses = 2; constexpr float kAlignmentOutlierThreshold = 0.65f; +constexpr bool kEnableRawSuperResPerfLogs = false; + +using PerfClock = std::chrono::steady_clock; + +inline double elapsedMillis(PerfClock::time_point start, + PerfClock::time_point end) { + return std::chrono::duration(end - start).count(); +} + +inline double elapsedMillis(PerfClock::time_point start) { + return elapsedMillis(start, PerfClock::now()); +} + +inline double averageMillis(double totalMs, size_t count) { + return count > 0 ? totalMs / static_cast(count) : 0.0; +} + +inline void logRawSuperResStage(const char *stage, double elapsedMs) { + if (!kEnableRawSuperResPerfLogs) + return; + LOGI("RawSuperResPerf[%s]: %.3f ms", stage, elapsedMs); +} + +#undef TIME_START +#undef TIME_END +#define TIME_START(name) const auto start_##name = PerfClock::now() +#define TIME_END(name) \ + const double elapsed_##name = elapsedMillis(start_##name); \ + logRawSuperResStage(#name, elapsed_##name) + +struct RawSuperResPerfStats { + double totalMs = 0.0; + double scoreCalculationMs = 0.0; + double descriptorSetupMs = 0.0; + + double phase1UploadAndPyramidMs = 0.0; + double proxyBuildMs = 0.0; + double pyramidBuildMs = 0.0; + double gpuUploadMs = 0.0; + + double referencePriorMs = 0.0; + double structureTensorMs = 0.0; + + double coarseAlignmentMs = 0.0; + double coarseAlignmentComputeMs = 0.0; + + double globalReliabilityMs = 0.0; + double globalReliabilitySeedMs = 0.0; + double globalReliabilityLkStage1Ms = 0.0; + double globalReliabilityRegularize1Ms = 0.0; + double globalReliabilityRobustness1Ms = 0.0; + double globalReliabilityLkStage2Ms = 0.0; + double globalReliabilityRobustness1AndLkStage2Ms = 0.0; + double globalReliabilityRegularize2Ms = 0.0; + double globalReliabilityRobustness2Ms = 0.0; + double globalReliabilityReadbackMs = 0.0; + + double tileProcessingMs = 0.0; + double outputClearMs = 0.0; + double tileClearMs = 0.0; + double localMaskUploadMs = 0.0; + double tileRefinedStateUploadMs = 0.0; + double tileAlignmentSeedMs = 0.0; + double tileAlignmentLkStage1Ms = 0.0; + double tileAlignmentRegularize1Ms = 0.0; + double tileRobustness1Ms = 0.0; + double tileAlignmentLkStage2Ms = 0.0; + double tileAlignmentRegularize2Ms = 0.0; + double tileRobustness2Ms = 0.0; + double scatterMs = 0.0; + double normalizeMs = 0.0; + + double outputReadbackMs = 0.0; + double cleanupMs = 0.0; + + size_t totalFrames = 0; + size_t keptFrames = 0; + size_t skippedFrames = 0; + size_t tilesProcessed = 0; + size_t coarseAlignedFrames = 0; + size_t globalReliabilityFrames = 0; + size_t tileAlignedFrameInstances = 0; + size_t tileScatterFrameInstances = 0; + + void logSummary(uint32_t outputW, uint32_t outputH, float scale) const { + if (!kEnableRawSuperResPerfLogs) + return; + LOGI( + "RawSuperResPerf summary: total=%.3f ms output=%ux%u scale=%.2f " + "frames=%zu kept=%zu skipped=%zu tiles=%zu", + totalMs, outputW, outputH, scale, totalFrames, keptFrames, + skippedFrames, tilesProcessed); + LOGI( + "RawSuperResPerf phases: score=%.3f setup=%.3f upload=%.3f prior=%.3f " + "tensor=%.3f coarse=%.3f reliability=%.3f tile=%.3f readback=%.3f " + "cleanup=%.3f", + scoreCalculationMs, descriptorSetupMs, phase1UploadAndPyramidMs, + referencePriorMs, structureTensorMs, coarseAlignmentMs, + globalReliabilityMs, tileProcessingMs, outputReadbackMs, cleanupMs); + LOGI( + "RawSuperResPerf upload-detail: proxy=%.3f pyramid=%.3f gpuUpload=%.3f " + "avgFrame=%.3f", + proxyBuildMs, pyramidBuildMs, gpuUploadMs, + averageMillis(phase1UploadAndPyramidMs, totalFrames)); + if (coarseAlignedFrames > 0 || globalReliabilityFrames > 0) { + LOGI( + "RawSuperResPerf align-detail: coarse=%.3f avgCoarse=%.3f " + "seed=%.3f lk1=%.3f reg1=%.3f rb1=%.3f lk2=%.3f rb1+lk2=%.3f " + "reg2=%.3f rb2=%.3f summary=%.3f avgReliabilityFrame=%.3f", + coarseAlignmentComputeMs, + averageMillis(coarseAlignmentComputeMs, coarseAlignedFrames), + globalReliabilitySeedMs, globalReliabilityLkStage1Ms, + globalReliabilityRegularize1Ms, globalReliabilityRobustness1Ms, + globalReliabilityLkStage2Ms, + globalReliabilityRobustness1AndLkStage2Ms, + globalReliabilityRegularize2Ms, globalReliabilityRobustness2Ms, + globalReliabilityReadbackMs, + averageMillis(globalReliabilityMs, globalReliabilityFrames)); + } + if (tilesProcessed > 0) { + LOGI( + "RawSuperResPerf tile-detail: clearOut=%.3f clearTile=%.3f " + "maskUpload=%.3f refinedUpload=%.3f alignSeed=%.3f lk1=%.3f reg1=%.3f rb1=%.3f " + "lk2=%.3f reg2=%.3f rb2=%.3f scatter=%.3f normalize=%.3f " + "avgTile=%.3f avgScatterFrame=%.3f avgNonRefFramePrep=%.3f", + outputClearMs, tileClearMs, localMaskUploadMs, + tileRefinedStateUploadMs, tileAlignmentSeedMs, + tileAlignmentLkStage1Ms, tileAlignmentRegularize1Ms, + tileRobustness1Ms, tileAlignmentLkStage2Ms, + tileAlignmentRegularize2Ms, tileRobustness2Ms, scatterMs, + normalizeMs, averageMillis(tileProcessingMs, tilesProcessed), + averageMillis(scatterMs, tileScatterFrameInstances), + averageMillis(tileRefinedStateUploadMs + tileAlignmentSeedMs + + tileAlignmentLkStage1Ms + + tileAlignmentRegularize1Ms + tileRobustness1Ms + + tileAlignmentLkStage2Ms + + tileAlignmentRegularize2Ms + tileRobustness2Ms, + tileAlignedFrameInstances)); + } + } +}; VulkanRawStacker::VulkanRawStacker(uint32_t w, uint32_t h, bool enableSuperRes, + float superResScale, const float *blackLevel, float whiteLevel, const float *wbGains, const float *noiseModel, const float *lensShadingMap, uint32_t lscWidth, uint32_t lscHeight) : width(w), height(h), mEnableSuperRes(enableSuperRes), + mSuperResScale(enableSuperRes ? std::clamp(superResScale, 1.0f, 2.0f) + : 1.0f), mWhiteLevel(whiteLevel), mLscWidth(lscWidth), mLscHeight(lscHeight) { if (blackLevel) @@ -49,9 +193,8 @@ VulkanRawStacker::VulkanRawStacker(uint32_t w, uint32_t h, bool enableSuperRes, } if (mEnableSuperRes) { - uint32_t scale = 2; - uint32_t outW = width * scale; - uint32_t outH = height * scale; + uint32_t outW = (uint32_t)std::lround(width * mSuperResScale); + uint32_t outH = (uint32_t)std::lround(height * mSuperResScale); const uint32_t MAX_TILE_SIZE = 4096; numTilesX = (outW + MAX_TILE_SIZE - 1) / MAX_TILE_SIZE; numTilesY = (outH + MAX_TILE_SIZE - 1) / MAX_TILE_SIZE; @@ -73,9 +216,9 @@ void VulkanRawStacker::initVulkanResources() { VulkanManager &vm = VulkanManager::getInstance(); VkDevice device = vm.getDevice(); - uint32_t scale = mEnableSuperRes ? 2 : 1; - uint32_t outW = width * scale; - uint32_t outH = height * scale; + float scale = mEnableSuperRes ? mSuperResScale : 1.0f; + uint32_t outW = (uint32_t)std::lround(width * scale); + uint32_t outH = (uint32_t)std::lround(height * scale); uint32_t planeW = outW; uint32_t planeH = outH; @@ -90,56 +233,24 @@ void VulkanRawStacker::initVulkanResources() { VkDeviceSize accumBufferSize = (VkDeviceSize)stride * (tileH + 16) * sizeof(float) * 2; - // Sequential tile processing: only allocate 3 accum buffers (R/G/B). - // Tiles are processed one at a time, reusing the same 3 buffers. - // This drastically reduces VRAM usage from ~2GB to ~25MB. + alignLkSets.resize(1); + robustnessSets.resize(1); - int totalBuffers = 3; // Only R, G, B channels - accumBuffers.resize(totalBuffers); - accumMemories.resize(totalBuffers); - accumSets.resize(totalBuffers); - normalizeSets.resize(totalBuffers); - alignLkSets.resize(totalBuffers); - robustnessSets.resize(totalBuffers); - - for (int i = 0; i < totalBuffers; ++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); - } - - // Staging Buffer for Planar RGB (3 channels * 16-bit) - VkDeviceSize stagingSize = - (VkDeviceSize)width * height * scale * scale * 3 * sizeof(uint16_t); + // Host-visible fused Bayer output buffer. + VkDeviceSize fusedBayerSize = + (VkDeviceSize)outW * outH * sizeof(uint16_t); VkBufferCreateInfo stagingInfo{}; stagingInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - stagingInfo.size = stagingSize; + stagingInfo.size = fusedBayerSize; stagingInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; stagingInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - VK_CHECK(vkCreateBuffer(device, &stagingInfo, nullptr, &stagingBuffer)); + VK_CHECK(vkCreateBuffer(device, &stagingInfo, nullptr, &fusedBayerBuffer)); VkMemoryRequirements stagingReqs; - vkGetBufferMemoryRequirements(device, stagingBuffer, &stagingReqs); + vkGetBufferMemoryRequirements(device, fusedBayerBuffer, &stagingReqs); VkMemoryAllocateInfo stagingAlloc{}; stagingAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; @@ -148,8 +259,8 @@ void VulkanRawStacker::initVulkanResources() { 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); + VK_CHECK(vkAllocateMemory(device, &stagingAlloc, nullptr, &fusedBayerMemory)); + vkBindBufferMemory(device, fusedBayerBuffer, fusedBayerMemory, 0); // Descriptor Pool — sized for 3 channels, not all tiles VkDescriptorPoolSize poolSizes[2] = {}; @@ -311,21 +422,55 @@ void VulkanRawStacker::initVulkanResources() { rbScatterAccumMemories[c], 0); } - // Clear Accumulator Buffers (only 3 now) + VkDeviceSize priorBufferSize = + (VkDeviceSize)outW * outH * sizeof(uint16_t); + VkBufferCreateInfo priorInfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + priorInfo.size = priorBufferSize; + priorInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + priorInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + VK_CHECK(vkCreateBuffer(device, &priorInfo, nullptr, &priorBayerBuffer)); + VK_CHECK(vkCreateBuffer(device, &priorInfo, nullptr, &priorWeightBuffer)); + + VkMemoryRequirements priorReqs; + vkGetBufferMemoryRequirements(device, priorBayerBuffer, &priorReqs); + VkMemoryAllocateInfo priorAlloc{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + priorAlloc.allocationSize = priorReqs.size; + priorAlloc.memoryTypeIndex = vm.findMemoryType( + priorReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VK_CHECK(vkAllocateMemory(device, &priorAlloc, nullptr, &priorBayerMemory)); + vkBindBufferMemory(device, priorBayerBuffer, priorBayerMemory, 0); + + vkGetBufferMemoryRequirements(device, priorWeightBuffer, &priorReqs); + priorAlloc.allocationSize = priorReqs.size; + priorAlloc.memoryTypeIndex = vm.findMemoryType( + priorReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VK_CHECK(vkAllocateMemory(device, &priorAlloc, nullptr, &priorWeightMemory)); + vkBindBufferMemory(device, priorWeightBuffer, priorWeightMemory, 0); + + VkDeviceSize normalizedReferenceSize = + (VkDeviceSize)width * height * sizeof(uint16_t); + VkBufferCreateInfo normalizedReferenceInfo{ + VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + normalizedReferenceInfo.size = normalizedReferenceSize; + normalizedReferenceInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + normalizedReferenceInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; + VK_CHECK(vkCreateBuffer(device, &normalizedReferenceInfo, nullptr, + &normalizedReferenceBuffer)); + + VkMemoryRequirements normalizedReferenceReqs; + vkGetBufferMemoryRequirements(device, normalizedReferenceBuffer, + &normalizedReferenceReqs); + VkMemoryAllocateInfo normalizedReferenceAlloc{ + VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + normalizedReferenceAlloc.allocationSize = normalizedReferenceReqs.size; + normalizedReferenceAlloc.memoryTypeIndex = vm.findMemoryType( + normalizedReferenceReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VK_CHECK(vkAllocateMemory(device, &normalizedReferenceAlloc, nullptr, + &normalizedReferenceMemory)); + vkBindBufferMemory(device, normalizedReferenceBuffer, + normalizedReferenceMemory, 0); + VkCommandBuffer cb = vm.beginSingleTimeCommands(); - for (int i = 0; i < 3; ++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); - } for (int phase = 0; phase < 2; ++phase) { vkCmdFillBuffer(cb, greenPhaseAccumBuffers[phase], 0, greenAccumSize, 0); VkBufferMemoryBarrier barrier{}; @@ -352,6 +497,17 @@ void VulkanRawStacker::initVulkanResources() { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr); } + vkCmdFillBuffer(cb, fusedBayerBuffer, 0, fusedBayerSize, 0); + VkBufferMemoryBarrier fusedBarrier{}; + fusedBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + fusedBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + fusedBarrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + fusedBarrier.buffer = fusedBayerBuffer; + fusedBarrier.size = fusedBayerSize; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, + &fusedBarrier, 0, nullptr); // Initial Clear for Alignment Buffer void *ptr; @@ -681,58 +837,81 @@ void VulkanRawStacker::createPipelines() { device, colorScatterPipelineLayout, color_scatter_raw_comp_spv, color_scatter_raw_comp_spv_size); - // --- 6. Accumulate Pipeline --- - // Updated with 7 bindings: 0=Input, 1=Accum, 2=Align, 3=Kernel, - // 4=Robustness, 5=LSC, 6=Local tile mask - VkDescriptorSetLayoutBinding bindings[8] = {}; - bindings[0] = {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[3] = {3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[4] = {4, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[5] = {5, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[6] = {6, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - bindings[7] = {7, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, - VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + // --- 6. Reference Normalize Pipeline --- + VkDescriptorSetLayoutBinding rnBindings[3] = {}; + rnBindings[0] = {0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + rnBindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + rnBindings[2] = {2, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; - VkDescriptorSetLayoutCreateInfo layoutInfo{}; - layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; - layoutInfo.bindingCount = 8; - layoutInfo.pBindings = bindings; - vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, - &descriptorSetLayout); + VkDescriptorSetLayoutCreateInfo rnLayoutInfo{ + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + rnLayoutInfo.bindingCount = 3; + rnLayoutInfo.pBindings = rnBindings; + vkCreateDescriptorSetLayout(device, &rnLayoutInfo, nullptr, + &referenceNormalizeSetLayout); - 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); + VkPipelineLayoutCreateInfo rnPLInfo{ + VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + rnPLInfo.setLayoutCount = 1; + rnPLInfo.pSetLayouts = &referenceNormalizeSetLayout; + rnPLInfo.pushConstantRangeCount = 1; + rnPLInfo.pPushConstantRanges = &pushConstantRange; + vkCreatePipelineLayout(device, &rnPLInfo, nullptr, + &referenceNormalizePipelineLayout); - accumulatePipeline = - createComputePipeline(device, pipelineLayout, accumulate_raw_comp_spv, - accumulate_raw_comp_spv_size); + referenceNormalizePipeline = createComputePipeline( + device, referenceNormalizePipelineLayout, + reference_preprocess_raw_comp_spv, + reference_preprocess_raw_comp_spv_size); - // --- 7. Green Normalize Pipeline --- - VkDescriptorSetLayoutBinding gnBindings[3] = {}; + // --- 7. Reference Prior Pipeline --- + VkDescriptorSetLayoutBinding rpBindings[3] = {}; + rpBindings[0] = {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + rpBindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + rpBindings[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + + VkDescriptorSetLayoutCreateInfo rpLayoutInfo{ + VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; + rpLayoutInfo.bindingCount = 3; + rpLayoutInfo.pBindings = rpBindings; + vkCreateDescriptorSetLayout(device, &rpLayoutInfo, nullptr, + &referencePriorSetLayout); + + VkPipelineLayoutCreateInfo rpPLInfo{ + VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + rpPLInfo.setLayoutCount = 1; + rpPLInfo.pSetLayouts = &referencePriorSetLayout; + rpPLInfo.pushConstantRangeCount = 1; + rpPLInfo.pPushConstantRanges = &pushConstantRange; + vkCreatePipelineLayout(device, &rpPLInfo, nullptr, + &referencePriorPipelineLayout); + + referencePriorPipeline = createComputePipeline( + device, referencePriorPipelineLayout, reference_prior_raw_comp_spv, + reference_prior_raw_comp_spv_size); + + // --- 8. Green Normalize Pipeline --- + VkDescriptorSetLayoutBinding gnBindings[5] = {}; gnBindings[0] = {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; // Output gnBindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; // Phase 0 gnBindings[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; // Phase 1 + gnBindings[3] = {3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; // Prior value + gnBindings[4] = {4, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; // Prior weight VkDescriptorSetLayoutCreateInfo gnLayoutInfo{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - gnLayoutInfo.bindingCount = 3; + gnLayoutInfo.bindingCount = 5; gnLayoutInfo.pBindings = gnBindings; vkCreateDescriptorSetLayout(device, &gnLayoutInfo, nullptr, &greenNormalizeSetLayout); @@ -750,16 +929,20 @@ void VulkanRawStacker::createPipelines() { device, greenNormalizePipelineLayout, normalize_green_hr_comp_spv, normalize_green_hr_comp_spv_size); - // --- 8. Color Normalize Pipeline --- - VkDescriptorSetLayoutBinding cnBindings[2] = {}; + // --- 9. Color Normalize Pipeline --- + VkDescriptorSetLayoutBinding cnBindings[4] = {}; cnBindings[0] = {0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; cnBindings[1] = {1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + cnBindings[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; + cnBindings[3] = {3, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, + VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo cnLayoutInfo{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - cnLayoutInfo.bindingCount = 2; + cnLayoutInfo.bindingCount = 4; cnLayoutInfo.pBindings = cnBindings; vkCreateDescriptorSetLayout(device, &cnLayoutInfo, nullptr, &colorNormalizeSetLayout); @@ -777,41 +960,6 @@ void VulkanRawStacker::createPipelines() { device, colorNormalizePipelineLayout, normalize_color_hr_comp_spv, normalize_color_hr_comp_spv_size); - // --- 9. 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; - vkCreatePipelineLayout(device, &normalizePipelineLayoutInfo, nullptr, - &normalizePipelineLayout); - - normalizePipeline = createComputePipeline(device, normalizePipelineLayout, - normalize_raw_comp_spv, - normalize_raw_comp_spv_size); - LOGD("Pipelines created"); } @@ -946,6 +1094,13 @@ struct LocalReliabilityMap { LocalReliabilitySummary summary; }; +struct RefinedFrameCache { + std::vector alignment; + std::vector robustness; + std::vector flowVariance; + bool valid = false; +}; + struct GreenPhaseSummary { ScalarStats phase0Mean; ScalarStats phase1Mean; @@ -1064,6 +1219,28 @@ inline RobustnessSummary readRobustnessSummary(VkDevice device, return summary; } +inline RobustnessSummary readRobustnessSummary(const std::vector &robustness, + uint32_t planeW, + uint32_t planeH) { + RobustnessSummary summary; + if (planeW == 0 || planeH == 0 || robustness.empty()) + return summary; + + size_t count = std::min((size_t)planeW * planeH, robustness.size()); + summary.values = computeScalarStats(robustness.data(), count); + size_t weak015 = 0; + size_t weak05 = 0; + for (size_t i = 0; i < count; ++i) { + if (robustness[i] < 0.15f) + ++weak015; + if (robustness[i] < 0.5f) + ++weak05; + } + summary.weak015Fraction = (float)weak015 / (float)count; + summary.weak05Fraction = (float)weak05 / (float)count; + return summary; +} + inline bool uploadAlignmentField(VkDevice device, VkDeviceMemory alignMem, const std::vector &field) { if (field.empty()) @@ -1081,6 +1258,23 @@ inline bool uploadAlignmentField(VkDevice device, VkDeviceMemory alignMem, return true; } +inline bool uploadFloatBuffer(VkDevice device, VkDeviceMemory memory, + const std::vector &values) { + if (values.empty()) + return false; + + void *mapPtr = nullptr; + VkResult res = vkMapMemory(device, memory, 0, + (VkDeviceSize)values.size() * sizeof(float), 0, + &mapPtr); + if (res != VK_SUCCESS || mapPtr == nullptr) + return false; + + std::memcpy(mapPtr, values.data(), values.size() * sizeof(float)); + vkUnmapMemory(device, memory); + return true; +} + inline bool fillFloatBuffer(VkDevice device, VkDeviceMemory memory, size_t count, float value) { if (count == 0) @@ -1116,6 +1310,24 @@ inline bool downloadAlignmentField(VkDevice device, VkDeviceMemory alignMem, return true; } +inline bool downloadFloatBuffer(VkDevice device, VkDeviceMemory memory, + size_t count, std::vector &values) { + if (count == 0) + return false; + + void *mapPtr = nullptr; + VkResult res = + vkMapMemory(device, memory, 0, (VkDeviceSize)count * sizeof(float), 0, + &mapPtr); + if (res != VK_SUCCESS || mapPtr == nullptr) + return false; + + values.resize(count); + std::memcpy(values.data(), mapPtr, count * sizeof(float)); + vkUnmapMemory(device, memory); + return true; +} + inline std::vector buildDenseAlignmentSeed(const TileAlignment &coarseAlign, uint32_t gridW, uint32_t gridH, uint32_t tileSize) { @@ -1388,6 +1600,142 @@ inline LocalReliabilityMap readLocalReliabilityMap(VkDevice device, return result; } +inline LocalReliabilityMap +readLocalReliabilityMap(const std::vector &robustness, uint32_t planeW, + uint32_t planeH, const GrayImage &referenceProxy) { + LocalReliabilityMap result; + if (planeW == 0 || planeH == 0 || referenceProxy.data.empty() || + robustness.empty()) + return result; + + const uint32_t localTileSize = 16; + const uint32_t tilesX = (planeW + localTileSize - 1) / localTileSize; + const uint32_t tilesY = (planeH + localTileSize - 1) / localTileSize; + result.tilesX = tilesX; + result.tilesY = tilesY; + result.tileWeights.resize((size_t)tilesX * tilesY, 1.0f); + auto saturate = [](float v) { return std::clamp(v, 0.0f, 1.0f); }; + + struct TileMetric { + float detailScore = 0.0f; + float meanRobustness = 0.0f; + float weakFraction = 0.0f; + }; + + std::vector tileMetrics; + tileMetrics.reserve((size_t)tilesX * tilesY); + std::vector tileDetails; + std::vector tileRobustnessMeans; + tileDetails.reserve((size_t)tilesX * tilesY); + tileRobustnessMeans.reserve((size_t)tilesX * tilesY); + + for (uint32_t ty = 0; ty < tilesY; ++ty) { + for (uint32_t tx = 0; tx < tilesX; ++tx) { + uint32_t x0 = tx * localTileSize; + uint32_t y0 = ty * localTileSize; + uint32_t x1 = std::min(x0 + localTileSize, planeW); + uint32_t y1 = std::min(y0 + localTileSize, planeH); + + double detailSum = 0.0; + double robustSum = 0.0; + size_t weakCount = 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 * planeW + x; + float center = (float)referenceProxy.data[idx]; + float xp = (float)referenceProxy + .data[(size_t)y * planeW + std::min(x + 1, planeW - 1)]; + float xm = (float)referenceProxy + .data[(size_t)y * planeW + (x > 0 ? x - 1 : 0)]; + float yp = (float)referenceProxy.data[(size_t)std::min(y + 1, planeH - 1) * + planeW + + x]; + float ym = (float)referenceProxy + .data[(size_t)(y > 0 ? y - 1 : 0) * planeW + x]; + float gx = std::abs(xp - xm); + float gy = std::abs(yp - ym); + float lap = std::abs(4.0f * center - xp - xm - yp - ym); + detailSum += gx + gy + 0.5 * lap; + + float r = robustness[idx]; + robustSum += r; + if (r < 0.5f) + ++weakCount; + ++count; + } + } + + TileMetric metric; + if (count > 0) { + metric.detailScore = (float)(detailSum / (double)count); + metric.meanRobustness = (float)(robustSum / (double)count); + metric.weakFraction = (float)weakCount / (float)count; + } + tileMetrics.push_back(metric); + tileDetails.push_back(metric.detailScore); + tileRobustnessMeans.push_back(metric.meanRobustness); + } + } + + result.summary.tileRobustness = + computeScalarStats(tileRobustnessMeans.data(), tileRobustnessMeans.size()); + ScalarStats detailStats = + computeScalarStats(tileDetails.data(), tileDetails.size()); + float edgeThreshold = std::max(detailStats.p50, detailStats.p90 * 0.65f); + float textThreshold = std::max(detailStats.p90, detailStats.p99 * 0.75f); + + size_t edgeTiles = 0; + size_t edgeGoodTiles = 0; + size_t textTiles = 0; + size_t textGoodTiles = 0; + for (size_t idx = 0; idx < tileMetrics.size(); ++idx) { + const TileMetric &metric = tileMetrics[idx]; + bool isEdgeTile = metric.detailScore >= edgeThreshold; + bool isTextTile = metric.detailScore >= textThreshold; + float robustNorm = saturate((metric.meanRobustness - 0.58f) / 0.24f); + float weakPenalty = + saturate(1.0f - std::max(0.0f, metric.weakFraction - 0.10f) / 0.30f); + float detailBoost = isTextTile ? 1.0f : (isEdgeTile ? 0.70f : 0.35f); + float tileWeight = saturate((0.55f * robustNorm + 0.45f * weakPenalty) * + (0.55f + 0.45f * detailBoost)); + if (isTextTile) { + tileWeight = std::max(tileWeight, 0.35f); + } else if (isEdgeTile) { + tileWeight = std::max(tileWeight, 0.20f); + } + result.tileWeights[idx] = tileWeight; + if (isEdgeTile) { + ++edgeTiles; + if (metric.meanRobustness >= 0.70f && metric.weakFraction <= 0.22f) { + ++edgeGoodTiles; + } + } + if (isTextTile) { + ++textTiles; + if (metric.meanRobustness >= 0.74f && metric.weakFraction <= 0.16f) { + ++textGoodTiles; + } + } + } + + size_t totalTiles = tileMetrics.size(); + if (totalTiles > 0) { + result.summary.edgeTileFraction = (float)edgeTiles / (float)totalTiles; + } + if (edgeTiles > 0) { + result.summary.edgeGoodFraction = (float)edgeGoodTiles / (float)edgeTiles; + } + if (textTiles > 0) { + result.summary.textGoodFraction = (float)textGoodTiles / (float)textTiles; + } else { + result.summary.textGoodFraction = result.summary.edgeGoodFraction; + } + + return result; +} + inline float clamp01(float v) { return std::clamp(v, 0.0f, 1.0f); } inline float computeFusionFrameWeight(const TileAlignment &alignment, @@ -1597,21 +1945,26 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { if (pendingFrames.empty()) return false; + RawSuperResPerfStats perf; + perf.totalFrames = pendingFrames.size(); + const auto processStackStart = PerfClock::now(); + // 1. Calculate scores and sort (Highest score first = Reference) TIME_START(scoreCalculation); selectReferenceFrame(); TIME_END(scoreCalculation); + perf.scoreCalculationMs = elapsed_scoreCalculation; VulkanManager &vm = VulkanManager::getInstance(); VkDevice device = vm.getDevice(); - if (accumulatePipeline == VK_NULL_HANDLE) { + if (structureTensorPipeline == VK_NULL_HANDLE) { createPipelines(); } - uint32_t scale = mEnableSuperRes ? 2 : 1; - uint32_t outputW = width * scale; - uint32_t outputH = height * scale; + float scale = mEnableSuperRes ? mSuperResScale : 1.0f; + uint32_t outputW = (uint32_t)std::lround(width * scale); + uint32_t outputH = (uint32_t)std::lround(height * scale); uint32_t inputW = width / 2; uint32_t inputH = height / 2; uint32_t localTilesX = (inputW + 15) / 16; @@ -1622,6 +1975,8 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { uint32_t tileW = (outputW + numTilesX - 1) / numTilesX; uint32_t tileH = (outputH + numTilesY - 1) / numTilesY; + TIME_START(descriptorSetup); + // Global Sampler VkSampler sampler; VkSamplerCreateInfo samplerInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; @@ -1657,6 +2012,12 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &colorScatterSets[c])); } + allocInfo.pSetLayouts = &referenceNormalizeSetLayout; + VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &referenceNormalizeSet)); + + allocInfo.pSetLayouts = &referencePriorSetLayout; + VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &referencePriorSet)); + allocInfo.pSetLayouts = &greenNormalizeSetLayout; VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &greenNormalizeSet)); @@ -1666,34 +2027,6 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { vkAllocateDescriptorSets(device, &allocInfo, &colorNormalizeSets[c])); } - // Allocate descriptor sets for 3 channels (R/G/B) - allocInfo.pSetLayouts = &descriptorSetLayout; - for (int c = 0; c < 3; ++c) { - if (accumSets[c] == VK_NULL_HANDLE) { - VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &accumSets[c])); - } - updateBufferDescriptorSet(device, accumSets[c], accumBuffers[c], - VK_WHOLE_SIZE, 1); - updateBufferDescriptorSet(device, accumSets[c], alignmentBuffer, - VK_WHOLE_SIZE, 2); - updateBufferDescriptorSet(device, accumSets[c], kernelBuffer, VK_WHOLE_SIZE, - 3); - updateBufferDescriptorSet(device, accumSets[c], robustnessBuffer, - VK_WHOLE_SIZE, 4); - updateBufferDescriptorSet(device, accumSets[c], flowVarianceBuffer, - VK_WHOLE_SIZE, 5); - updateImageDescriptorSet(device, accumSets[c], lscView, lscSampler, 6); - updateBufferDescriptorSet(device, accumSets[c], localTileMaskBuffer, - VK_WHOLE_SIZE, 7); - } - - allocInfo.pSetLayouts = &normalizeSetLayout; - for (int c = 0; c < 3; ++c) { - if (normalizeSets[c] == VK_NULL_HANDLE) { - VK_CHECK(vkAllocateDescriptorSets(device, &allocInfo, &normalizeSets[c])); - } - } - // Pre-update constant bindings for other pipelines updateBufferDescriptorSet(device, structureTensorSet, kernelBuffer, VK_WHOLE_SIZE, 1); @@ -1736,6 +2069,18 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { updateImageDescriptorSet(device, colorScatterSets[c], lscView, lscSampler, 6); } + updateBufferDescriptorSet(device, referenceNormalizeSet, + normalizedReferenceBuffer, VK_WHOLE_SIZE, 1); + updateImageDescriptorSet(device, referenceNormalizeSet, lscView, lscSampler, + 2); + updateBufferDescriptorSet(device, referencePriorSet, + normalizedReferenceBuffer, VK_WHOLE_SIZE, 0); + updateBufferDescriptorSet(device, referencePriorSet, priorBayerBuffer, + VK_WHOLE_SIZE, 1); + updateBufferDescriptorSet(device, referencePriorSet, priorWeightBuffer, + VK_WHOLE_SIZE, 2); + TIME_END(descriptorSetup); + perf.descriptorSetupMs = elapsed_descriptorSetup; // ===================================================================== // Phase 1: Upload all frames to GPU and build proxies/pyramids @@ -1755,13 +2100,19 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { // Build grayscale proxy { + const auto proxyBuildStart = PerfClock::now(); uploadedFrames[i].proxy = buildAlignmentProxy(frame); + perf.proxyBuildMs += elapsedMillis(proxyBuildStart); } // Build pyramid - uploadedFrames[i].pyramid = buildPyramid( - uploadedFrames[i].proxy.data.data(), uploadedFrames[i].proxy.width, - uploadedFrames[i].proxy.height, 4); + { + const auto pyramidBuildStart = PerfClock::now(); + uploadedFrames[i].pyramid = buildPyramid( + uploadedFrames[i].proxy.data.data(), uploadedFrames[i].proxy.width, + uploadedFrames[i].proxy.height, 4); + perf.pyramidBuildMs += elapsedMillis(pyramidBuildStart); + } if (i == 0) { referencePyramid = uploadedFrames[i].pyramid; @@ -1769,6 +2120,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { // Upload frame to GPU { + const auto gpuUploadStart = PerfClock::now(); VkImageCreateInfo imgInfo{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; imgInfo.imageType = VK_IMAGE_TYPE_2D; imgInfo.format = VK_FORMAT_R16_UNORM; @@ -1798,9 +2150,9 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VkDeviceSize size = width * height * 2; void *map; - vkMapMemory(device, stagingMemory, 0, size, 0, &map); + vkMapMemory(device, fusedBayerMemory, 0, size, 0, &map); memcpy(map, frame.rawData.data(), size); - vkUnmapMemory(device, stagingMemory); + vkUnmapMemory(device, fusedBayerMemory); VkCommandBuffer cb = vm.beginSingleTimeCommands(); VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; @@ -1816,7 +2168,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VkBufferImageCopy copyReg{}; copyReg.imageExtent = {width, height, 1}; copyReg.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; - vkCmdCopyBufferToImage(cb, stagingBuffer, uploadedFrames[i].image, + vkCmdCopyBufferToImage(cb, fusedBayerBuffer, uploadedFrames[i].image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©Reg); barrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; @@ -1828,9 +2180,93 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { 0, nullptr, 1, &barrier); vm.endSingleTimeCommands(cb); + perf.gpuUploadMs += elapsedMillis(gpuUploadStart); } } TIME_END(phase1_UploadAndPyramid); + perf.phase1UploadAndPyramidMs = elapsed_phase1_UploadAndPyramid; + + // ===================================================================== + // Phase 1B: Build dense HR Bayer prior from the reference frame + // ===================================================================== + { + TIME_START(phase1b_ReferencePrior); + VkCommandBuffer cb = vm.beginSingleTimeCommands(); + + updateImageDescriptorSet(device, referenceNormalizeSet, uploadedFrames[0].view, + sampler, 0); + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + referenceNormalizePipeline); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + referenceNormalizePipelineLayout, 0, 1, + &referenceNormalizeSet, 0, nullptr); + + PushConstants normalizePc{}; + normalizePc.width = outputW; + normalizePc.height = outputH; + normalizePc.planeWidth = outputW; + normalizePc.planeHeight = outputH; + normalizePc.sensorWidth = width; + normalizePc.sensorHeight = height; + normalizePc.scale = scale; + normalizePc.cfaPattern = (uint32_t)mCfaPattern; + normalizePc.whiteLevel = mWhiteLevel; + memcpy(normalizePc.blackLevel, mBlackLevel, 4 * sizeof(float)); + memcpy(normalizePc.wbGains, mWbGains, 4 * sizeof(float)); + vkCmdPushConstants(cb, referenceNormalizePipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(normalizePc), + &normalizePc); + vkCmdDispatch(cb, (width + 15) / 16, (height + 15) / 16, 1); + + VkBufferMemoryBarrier normalizedReferenceBarrier{ + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + normalizedReferenceBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + normalizedReferenceBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + normalizedReferenceBarrier.buffer = normalizedReferenceBuffer; + normalizedReferenceBarrier.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, + 1, &normalizedReferenceBarrier, 0, nullptr); + + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + referencePriorPipeline); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + referencePriorPipelineLayout, 0, 1, + &referencePriorSet, 0, nullptr); + + PushConstants priorPc{}; + priorPc.width = outputW; + priorPc.height = outputH; + priorPc.planeWidth = outputW; + priorPc.planeHeight = outputH; + priorPc.sensorWidth = width; + priorPc.sensorHeight = height; + priorPc.scale = scale; + priorPc.cfaPattern = (uint32_t)mCfaPattern; + priorPc.whiteLevel = mWhiteLevel; + memcpy(priorPc.blackLevel, mBlackLevel, 4 * sizeof(float)); + memcpy(priorPc.wbGains, mWbGains, 4 * sizeof(float)); + vkCmdPushConstants(cb, referencePriorPipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(priorPc), + &priorPc); + vkCmdDispatch(cb, (outputW + 15) / 16, (outputH + 15) / 16, 1); + + VkBufferMemoryBarrier priorBarriers[2]{}; + for (int i = 0; i < 2; ++i) { + priorBarriers[i].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + priorBarriers[i].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + priorBarriers[i].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + priorBarriers[i].buffer = (i == 0) ? priorBayerBuffer : priorWeightBuffer; + priorBarriers[i].size = VK_WHOLE_SIZE; + } + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, + 2, priorBarriers, 0, nullptr); + + vm.endSingleTimeCommands(cb); + TIME_END(phase1b_ReferencePrior); + perf.referencePriorMs = elapsed_phase1b_ReferencePrior; + } // Phase 2: Structure tensor pass on reference frame (global, once) // ===================================================================== @@ -1885,6 +2321,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { vm.endSingleTimeCommands(cb); } TIME_END(phase2_StructureTensor); + perf.structureTensorMs = elapsed_phase2_StructureTensor; // ===================================================================== // Phase 3: Pre-compute alignment for each non-reference frame @@ -1899,10 +2336,14 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { std::vector skipFusionFrame(pendingFrames.size(), false); std::vector frameLocalSummaries(pendingFrames.size()); std::vector frameLocalMaps(pendingFrames.size()); + std::vector frameRefinedCaches(pendingFrames.size()); const float referenceScore = std::max(pendingFrames.front().score, 1.0f); for (size_t i = 1; i < pendingFrames.size(); ++i) { + const auto coarseAlignStart = PerfClock::now(); frameAlignments[i].coarseAlign = computeTileAlignment(referencePyramid, uploadedFrames[i].pyramid, 64); + perf.coarseAlignmentComputeMs += elapsedMillis(coarseAlignStart); + ++perf.coarseAlignedFrames; logAlignmentDiagnostics("coarse", i, frameAlignments[i].coarseAlign); float sharpnessRatio = pendingFrames[i].score / referenceScore; float frameWeight = computeFusionFrameWeight(frameAlignments[i].coarseAlign, @@ -1911,6 +2352,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { skipFusionFrame[i] = frameWeight < 0.12f; } TIME_END(phase3_CoarseAlignment); + perf.coarseAlignmentMs = elapsed_phase3_CoarseAlignment; // ===================================================================== // Phase 3B: Global reliability pre-pass using actual refined flow + @@ -1921,6 +2363,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { if (skipFusionFrame[i]) { continue; } + ++perf.globalReliabilityFrames; PushConstants pc{}; pc.width = outputW; @@ -1948,12 +2391,15 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { pc.bufferStride = tileW + 16; const auto &coarseAlign = frameAlignments[i].coarseAlign; + const auto reliabilitySeedStart = PerfClock::now(); std::vector seededFlow = buildDenseAlignmentSeed(coarseAlign, (uint32_t)gridW, (uint32_t)gridH, (uint32_t)tileSize); uploadAlignmentField(device, alignmentMemory, seededFlow); fillFloatBuffer(device, robustnessMemory, (size_t)inputW * inputH, 1.0f); + perf.globalReliabilitySeedMs += elapsedMillis(reliabilitySeedStart); + const auto reliabilityLkStage1Start = PerfClock::now(); VkCommandBuffer cb = vm.beginSingleTimeCommands(); VkBufferMemoryBarrier hostBarriers[2]{}; @@ -1998,14 +2444,20 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { } vm.endSingleTimeCommands(cb); + perf.globalReliabilityLkStage1Ms += + elapsedMillis(reliabilityLkStage1Start); + const auto reliabilityRegularize1Start = PerfClock::now(); if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, (uint32_t)gridH, seededFlow)) { regularizeAlignmentField(seededFlow, (uint32_t)gridW, (uint32_t)gridH, (uint32_t)tileSize, uploadedFrames[0].proxy); uploadAlignmentField(device, alignmentMemory, seededFlow); } + perf.globalReliabilityRegularize1Ms += + elapsedMillis(reliabilityRegularize1Start); + const auto reliabilityRobustness1AndLkStage2Start = PerfClock::now(); cb = vm.beginSingleTimeCommands(); VkBufferMemoryBarrier refinedHostBarrier{ VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -2044,9 +2496,6 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 2, rbBarriers, 0, nullptr); - vm.endSingleTimeCommands(cb); - - cb = vm.beginSingleTimeCommands(); vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, alignLkPipeline); updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, sampler, 0); @@ -2070,15 +2519,22 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &lkBarrier, 0, nullptr); } - vm.endSingleTimeCommands(cb); + vm.endSingleTimeCommands(cb); + perf.globalReliabilityRobustness1AndLkStage2Ms += + elapsedMillis(reliabilityRobustness1AndLkStage2Start); + + const auto reliabilityRegularize2Start = PerfClock::now(); if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, (uint32_t)gridH, seededFlow)) { regularizeAlignmentField(seededFlow, (uint32_t)gridW, (uint32_t)gridH, (uint32_t)tileSize, uploadedFrames[0].proxy); uploadAlignmentField(device, alignmentMemory, seededFlow); } + perf.globalReliabilityRegularize2Ms += + elapsedMillis(reliabilityRegularize2Start); + const auto reliabilityRobustness2Start = PerfClock::now(); cb = vm.beginSingleTimeCommands(); VkBufferMemoryBarrier finalAlignBarrier{ VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -2118,14 +2574,51 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { finalRbBarriers, 0, nullptr); vm.endSingleTimeCommands(cb); + perf.globalReliabilityRobustness2Ms += + elapsedMillis(reliabilityRobustness2Start); - FlowSummary refinedFlow = - readFlowSummary(device, alignmentMemory, gridW, gridH); + const auto reliabilityReadbackStart = PerfClock::now(); + RefinedFrameCache &refinedCache = frameRefinedCaches[i]; + refinedCache.alignment = seededFlow; + refinedCache.valid = downloadFloatBuffer(device, robustnessMemory, + (size_t)inputW * inputH, + refinedCache.robustness) && + downloadFloatBuffer(device, flowVarianceMemory, + (size_t)inputW * inputH, + refinedCache.flowVariance); + if (!refinedCache.valid) { + if (kEnableRawSuperResPerfLogs) { + LOGW("RawSuperResPerf: failed to cache refined state for frame %zu", + i); + } + } + + FlowSummary refinedFlow; + if (!refinedCache.alignment.empty()) { + std::vector magnitudes; + magnitudes.reserve(refinedCache.alignment.size()); + double sumX = 0.0; + double sumY = 0.0; + for (const Point &point : refinedCache.alignment) { + sumX += point.x; + sumY += point.y; + magnitudes.push_back(std::sqrt(point.x * point.x + point.y * point.y)); + } + refinedFlow.magnitude = + computeScalarStats(magnitudes.data(), magnitudes.size()); + refinedFlow.meanX = (float)(sumX / (double)magnitudes.size()); + refinedFlow.meanY = (float)(sumY / (double)magnitudes.size()); + } RobustnessSummary robustSummary = - readRobustnessSummary(device, robustnessMemory, inputW, inputH); + refinedCache.valid + ? readRobustnessSummary(refinedCache.robustness, inputW, inputH) + : readRobustnessSummary(device, robustnessMemory, inputW, inputH); LocalReliabilityMap localMap = - readLocalReliabilityMap(device, robustnessMemory, inputW, inputH, - uploadedFrames[0].proxy); + refinedCache.valid + ? readLocalReliabilityMap(refinedCache.robustness, inputW, inputH, + uploadedFrames[0].proxy) + : readLocalReliabilityMap(device, robustnessMemory, inputW, inputH, + uploadedFrames[0].proxy); LocalReliabilitySummary localSummary = localMap.summary; frameLocalMaps[i] = std::move(localMap); frameLocalSummaries[i] = localSummary; @@ -2139,6 +2632,8 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { frameRetentionScores[i] = retentionScore; float keepThreshold = (localPriority > 0.58f) ? 0.16f : 0.20f; skipFusionFrame[i] = frameFusionWeights[i] < keepThreshold; + perf.globalReliabilityReadbackMs += + elapsedMillis(reliabilityReadbackStart); } @@ -2175,27 +2670,58 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { } } TIME_END(phase3b_GlobalReliability); + perf.globalReliabilityMs = elapsed_phase3b_GlobalReliability; + + perf.keptFrames = pendingFrames.empty() ? 0 : 1; + for (size_t i = 1; i < pendingFrames.size(); ++i) { + if (skipFusionFrame[i]) { + ++perf.skippedFrames; + std::vector().swap(frameRefinedCaches[i].alignment); + std::vector().swap(frameRefinedCaches[i].robustness); + std::vector().swap(frameRefinedCaches[i].flowVariance); + frameRefinedCaches[i].valid = false; + } else { + ++perf.keptFrames; + } + } // Phase 4: Sequential tile processing // For each tile: clear accum → accumulate all frames → normalize // ===================================================================== TIME_START(phase4_TileProcessing); - VkDeviceSize accumBufferSize = - (VkDeviceSize)(tileW + 16) * (tileH + 16) * sizeof(float) * 2; VkDeviceSize greenAccumBufferSize = (VkDeviceSize)(tileW + 16) * (tileH + 16) * sizeof(uint32_t) * 2; + VkDeviceSize fusedBayerSize = + (VkDeviceSize)outputW * outputH * sizeof(uint16_t); + + { + const auto outputClearStart = PerfClock::now(); + VkCommandBuffer cb = vm.beginSingleTimeCommands(); + vkCmdFillBuffer(cb, fusedBayerBuffer, 0, fusedBayerSize, 0); + VkBufferMemoryBarrier outBarrier{ + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + outBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + outBarrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + outBarrier.buffer = fusedBayerBuffer; + outBarrier.size = fusedBayerSize; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, + 1, &outBarrier, 0, nullptr); + vm.endSingleTimeCommands(cb); + perf.outputClearMs += elapsedMillis(outputClearStart); + } for (int ty = 0; ty < numTilesY; ++ty) { for (int tx = 0; tx < numTilesX; ++tx) { + ++perf.tilesProcessed; uint32_t currentTileW = std::min(tileW, outputW - tx * tileW); uint32_t currentTileH = std::min(tileH, outputH - ty * tileH); // Clear accumulators for this tile { + const auto tileClearStart = PerfClock::now(); VkCommandBuffer cb = vm.beginSingleTimeCommands(); - for (int c = 0; c < 3; ++c) { - vkCmdFillBuffer(cb, accumBuffers[c], 0, accumBufferSize, 0); - } for (int phase = 0; phase < 2; ++phase) { vkCmdFillBuffer(cb, greenPhaseAccumBuffers[phase], 0, greenAccumBufferSize, 0); @@ -2212,6 +2738,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &memBarrier, 0, nullptr, 0, nullptr); vm.endSingleTimeCommands(cb); + perf.tileClearMs += elapsedMillis(tileClearStart); } // Process all frames for this tile @@ -2222,6 +2749,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { if (!isRef && skipFusionFrame[i]) { continue; } + ++perf.tileScatterFrameInstances; PushConstants pc{}; pc.width = outputW; @@ -2247,6 +2775,7 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { (!isRef && !frameLocalMaps[i].tileWeights.empty()) ? frameLocalMaps[i].tileWeights : defaultLocalTileMask; + const auto localMaskUploadStart = PerfClock::now(); void *localMaskPtr = nullptr; VkResult localMaskRes = vkMapMemory(device, localTileMaskMemory, 0, VK_WHOLE_SIZE, 0, @@ -2256,212 +2785,284 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { localTileMask.size() * sizeof(float)); vkUnmapMemory(device, localTileMaskMemory); } + perf.localMaskUploadMs += elapsedMillis(localMaskUploadStart); + const RefinedFrameCache *refinedCache = + (!isRef && frameRefinedCaches[i].valid) ? &frameRefinedCaches[i] + : nullptr; if (!isRef) { - // Upload coarse alignment for this frame - const auto &coarseAlign = frameAlignments[i].coarseAlign; - std::vector seededFlow = buildDenseAlignmentSeed( - coarseAlign, (uint32_t)gridW, (uint32_t)gridH, - (uint32_t)tileSize); - uploadAlignmentField(device, alignmentMemory, seededFlow); - fillFloatBuffer(device, robustnessMemory, (size_t)inputW * inputH, - 1.0f); + ++perf.tileAlignedFrameInstances; + if (refinedCache != nullptr) { + const auto tileRefinedStateUploadStart = PerfClock::now(); + uploadAlignmentField(device, alignmentMemory, refinedCache->alignment); + uploadFloatBuffer(device, robustnessMemory, refinedCache->robustness); + uploadFloatBuffer(device, flowVarianceMemory, + refinedCache->flowVariance); + perf.tileRefinedStateUploadMs += + elapsedMillis(tileRefinedStateUploadStart); + } else { + const auto tileAlignmentSeedStart = PerfClock::now(); + // Upload coarse alignment for this frame + const auto &coarseAlign = frameAlignments[i].coarseAlign; + std::vector seededFlow = buildDenseAlignmentSeed( + coarseAlign, (uint32_t)gridW, (uint32_t)gridH, + (uint32_t)tileSize); + uploadAlignmentField(device, alignmentMemory, seededFlow); + fillFloatBuffer(device, robustnessMemory, (size_t)inputW * inputH, + 1.0f); + perf.tileAlignmentSeedMs += elapsedMillis(tileAlignmentSeedStart); - // LK alignment + Robustness - VkCommandBuffer cb = vm.beginSingleTimeCommands(); + // LK alignment + Robustness + const auto tileLkStage1Start = PerfClock::now(); + VkCommandBuffer cb = vm.beginSingleTimeCommands(); - // HOST_WRITE -> SHADER barrier - VkBufferMemoryBarrier hostBarriers[2]{}; - hostBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - hostBarriers[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - hostBarriers[0].dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - hostBarriers[0].buffer = alignmentBuffer; - hostBarriers[0].size = VK_WHOLE_SIZE; - hostBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - hostBarriers[1].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - hostBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - hostBarriers[1].buffer = robustnessBuffer; - hostBarriers[1].size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 2, hostBarriers, 0, nullptr); - - // Set pre-processing tile range (plane resolution) - pc.tileX = 0; - pc.tileY = 0; - pc.tileW = inputW; - pc.tileH = inputH; - pc.bufferStride = tileW + 16; - - // LK Alignment - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - alignLkPipeline); - updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, - sampler, 0); - updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, - sampler, 1); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - alignLkPipelineLayout, 0, 1, &alignSet, 0, - nullptr); - vkCmdPushConstants(cb, alignLkPipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - - for (int iter = 0; iter < 5; ++iter) { - vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1); - VkBufferMemoryBarrier lkBarrier{ - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - lkBarrier.dstAccessMask = + // HOST_WRITE -> SHADER barrier + VkBufferMemoryBarrier hostBarriers[2]{}; + hostBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + hostBarriers[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + hostBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - lkBarrier.buffer = alignmentBuffer; - lkBarrier.size = VK_WHOLE_SIZE; + hostBarriers[0].buffer = alignmentBuffer; + hostBarriers[0].size = VK_WHOLE_SIZE; + hostBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + hostBarriers[1].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + hostBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + hostBarriers[1].buffer = robustnessBuffer; + hostBarriers[1].size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 2, hostBarriers, 0, nullptr); + + // Set pre-processing tile range (plane resolution) + pc.tileX = 0; + pc.tileY = 0; + pc.tileW = inputW; + pc.tileH = inputH; + pc.bufferStride = tileW + 16; + + // LK Alignment + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + alignLkPipeline); + updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, + sampler, 0); + updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, + sampler, 1); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + alignLkPipelineLayout, 0, 1, &alignSet, 0, + nullptr); + vkCmdPushConstants(cb, alignLkPipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + + for (int iter = 0; iter < 5; ++iter) { + vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1); + VkBufferMemoryBarrier lkBarrier{ + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + lkBarrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + lkBarrier.buffer = alignmentBuffer; + lkBarrier.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 1, &lkBarrier, 0, nullptr); + } + + vm.endSingleTimeCommands(cb); + perf.tileAlignmentLkStage1Ms += elapsedMillis(tileLkStage1Start); + + const auto tileRegularize1Start = PerfClock::now(); + if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, + (uint32_t)gridH, seededFlow)) { + regularizeAlignmentField(seededFlow, (uint32_t)gridW, + (uint32_t)gridH, (uint32_t)tileSize, + uploadedFrames[0].proxy); + uploadAlignmentField(device, alignmentMemory, seededFlow); + } + perf.tileAlignmentRegularize1Ms += + elapsedMillis(tileRegularize1Start); + + const auto tileRobustness1Start = PerfClock::now(); + cb = vm.beginSingleTimeCommands(); + VkBufferMemoryBarrier refinedHostBarrier{ + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + refinedHostBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + refinedHostBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + refinedHostBarrier.buffer = alignmentBuffer; + refinedHostBarrier.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 1, &refinedHostBarrier, 0, nullptr); + + // Robustness + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + robustnessPipeline); + updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, + sampler, 0); + updateImageDescriptorSet(device, robustSet, uploadedFrames[i].view, + sampler, 1); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + robustnessPipelineLayout, 0, 1, &robustSet, + 0, nullptr); + vkCmdPushConstants(cb, robustnessPipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + vkCmdDispatch(cb, (inputW + 15) / 16, (inputH + 15) / 16, 1); + + VkBufferMemoryBarrier rbBarriers[2]{}; + rbBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + rbBarriers[0].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + rbBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + rbBarriers[0].buffer = robustnessBuffer; + rbBarriers[0].size = VK_WHOLE_SIZE; + rbBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + rbBarriers[1].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + rbBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + rbBarriers[1].buffer = flowVarianceBuffer; + rbBarriers[1].size = VK_WHOLE_SIZE; vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 1, &lkBarrier, 0, nullptr); - } + nullptr, 2, rbBarriers, 0, nullptr); - vm.endSingleTimeCommands(cb); + vm.endSingleTimeCommands(cb); + perf.tileRobustness1Ms += elapsedMillis(tileRobustness1Start); - if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, - (uint32_t)gridH, seededFlow)) { - regularizeAlignmentField(seededFlow, (uint32_t)gridW, - (uint32_t)gridH, (uint32_t)tileSize, - uploadedFrames[0].proxy); - uploadAlignmentField(device, alignmentMemory, seededFlow); - } + const auto tileLkStage2Start = PerfClock::now(); + cb = vm.beginSingleTimeCommands(); + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + alignLkPipeline); + updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, + sampler, 0); + updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, + sampler, 1); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + alignLkPipelineLayout, 0, 1, &alignSet, 0, + nullptr); + vkCmdPushConstants(cb, alignLkPipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + for (int iter = 0; iter < 2; ++iter) { + vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1); + VkBufferMemoryBarrier lkBarrier{ + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; + lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + lkBarrier.dstAccessMask = + VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; + lkBarrier.buffer = alignmentBuffer; + lkBarrier.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 1, &lkBarrier, 0, nullptr); + } + vm.endSingleTimeCommands(cb); + perf.tileAlignmentLkStage2Ms += elapsedMillis(tileLkStage2Start); - cb = vm.beginSingleTimeCommands(); - VkBufferMemoryBarrier refinedHostBarrier{ - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - refinedHostBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - refinedHostBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - refinedHostBarrier.buffer = alignmentBuffer; - refinedHostBarrier.size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 1, &refinedHostBarrier, 0, nullptr); + const auto tileRegularize2Start = PerfClock::now(); + if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, + (uint32_t)gridH, seededFlow)) { + regularizeAlignmentField(seededFlow, (uint32_t)gridW, + (uint32_t)gridH, (uint32_t)tileSize, + uploadedFrames[0].proxy); + uploadAlignmentField(device, alignmentMemory, seededFlow); + } + perf.tileAlignmentRegularize2Ms += + elapsedMillis(tileRegularize2Start); - // Robustness - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - robustnessPipeline); - updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, - sampler, 0); - updateImageDescriptorSet(device, robustSet, uploadedFrames[i].view, - sampler, 1); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - robustnessPipelineLayout, 0, 1, &robustSet, 0, - nullptr); - vkCmdPushConstants(cb, robustnessPipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - vkCmdDispatch(cb, (inputW + 15) / 16, (inputH + 15) / 16, 1); - - VkBufferMemoryBarrier rbBarriers[2]{}; - rbBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - rbBarriers[0].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - rbBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - rbBarriers[0].buffer = robustnessBuffer; - rbBarriers[0].size = VK_WHOLE_SIZE; - rbBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - rbBarriers[1].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - rbBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - rbBarriers[1].buffer = flowVarianceBuffer; - rbBarriers[1].size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 2, rbBarriers, 0, nullptr); - - vm.endSingleTimeCommands(cb); - - cb = vm.beginSingleTimeCommands(); - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - alignLkPipeline); - updateImageDescriptorSet(device, alignSet, uploadedFrames[0].view, - sampler, 0); - updateImageDescriptorSet(device, alignSet, uploadedFrames[i].view, - sampler, 1); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - alignLkPipelineLayout, 0, 1, &alignSet, 0, - nullptr); - vkCmdPushConstants(cb, alignLkPipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - for (int iter = 0; iter < 2; ++iter) { - vkCmdDispatch(cb, (gridW + 15) / 16, (gridH + 15) / 16, 1); - VkBufferMemoryBarrier lkBarrier{ + const auto tileRobustness2Start = PerfClock::now(); + cb = vm.beginSingleTimeCommands(); + VkBufferMemoryBarrier finalAlignBarrier{ VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - lkBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - lkBarrier.dstAccessMask = - VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT; - lkBarrier.buffer = alignmentBuffer; - lkBarrier.size = VK_WHOLE_SIZE; + finalAlignBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; + finalAlignBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + finalAlignBarrier.buffer = alignmentBuffer; + finalAlignBarrier.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, + nullptr, 1, &finalAlignBarrier, 0, nullptr); + + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + robustnessPipeline); + updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, + sampler, 0); + updateImageDescriptorSet(device, robustSet, uploadedFrames[i].view, + sampler, 1); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, + robustnessPipelineLayout, 0, 1, &robustSet, + 0, nullptr); + vkCmdPushConstants(cb, robustnessPipelineLayout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); + vkCmdDispatch(cb, (inputW + 15) / 16, (inputH + 15) / 16, 1); + + VkBufferMemoryBarrier finalRbBarriers[2]{}; + finalRbBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + finalRbBarriers[0].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + finalRbBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + finalRbBarriers[0].buffer = robustnessBuffer; + finalRbBarriers[0].size = VK_WHOLE_SIZE; + finalRbBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + finalRbBarriers[1].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; + finalRbBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + finalRbBarriers[1].buffer = flowVarianceBuffer; + finalRbBarriers[1].size = VK_WHOLE_SIZE; vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 1, &lkBarrier, 0, nullptr); + nullptr, 2, finalRbBarriers, 0, nullptr); + + vm.endSingleTimeCommands(cb); + perf.tileRobustness2Ms += elapsedMillis(tileRobustness2Start); } - vm.endSingleTimeCommands(cb); - - if (downloadAlignmentField(device, alignmentMemory, (uint32_t)gridW, - (uint32_t)gridH, seededFlow)) { - regularizeAlignmentField(seededFlow, (uint32_t)gridW, - (uint32_t)gridH, (uint32_t)tileSize, - uploadedFrames[0].proxy); - uploadAlignmentField(device, alignmentMemory, seededFlow); - } - - cb = vm.beginSingleTimeCommands(); - VkBufferMemoryBarrier finalAlignBarrier{ - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - finalAlignBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - finalAlignBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - finalAlignBarrier.buffer = alignmentBuffer; - finalAlignBarrier.size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 1, &finalAlignBarrier, 0, nullptr); - - vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - robustnessPipeline); - updateImageDescriptorSet(device, robustSet, uploadedFrames[0].view, - sampler, 0); - updateImageDescriptorSet(device, robustSet, uploadedFrames[i].view, - sampler, 1); - vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, - robustnessPipelineLayout, 0, 1, &robustSet, 0, - nullptr); - vkCmdPushConstants(cb, robustnessPipelineLayout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc); - vkCmdDispatch(cb, (inputW + 15) / 16, (inputH + 15) / 16, 1); - - VkBufferMemoryBarrier finalRbBarriers[2]{}; - finalRbBarriers[0].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - finalRbBarriers[0].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - finalRbBarriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - finalRbBarriers[0].buffer = robustnessBuffer; - finalRbBarriers[0].size = VK_WHOLE_SIZE; - finalRbBarriers[1].sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; - finalRbBarriers[1].srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - finalRbBarriers[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - finalRbBarriers[1].buffer = flowVarianceBuffer; - finalRbBarriers[1].size = VK_WHOLE_SIZE; - vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 2, finalRbBarriers, 0, nullptr); - - vm.endSingleTimeCommands(cb); } // Accumulate this frame's contribution for this tile's 3 channels { + const auto scatterStart = PerfClock::now(); VkCommandBuffer cb = vm.beginSingleTimeCommands(); - VkBufferMemoryBarrier localMaskBarrier{ - VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; - localMaskBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; - localMaskBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - localMaskBarrier.buffer = localTileMaskBuffer; - localMaskBarrier.size = VK_WHOLE_SIZE; + VkBufferMemoryBarrier preScatterBarriers[4]{}; + uint32_t preScatterBarrierCount = 0; + + preScatterBarriers[preScatterBarrierCount].sType = + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + preScatterBarriers[preScatterBarrierCount].srcAccessMask = + VK_ACCESS_HOST_WRITE_BIT; + preScatterBarriers[preScatterBarrierCount].dstAccessMask = + VK_ACCESS_SHADER_READ_BIT; + preScatterBarriers[preScatterBarrierCount].buffer = localTileMaskBuffer; + preScatterBarriers[preScatterBarrierCount].size = VK_WHOLE_SIZE; + ++preScatterBarrierCount; + + if (refinedCache != nullptr) { + preScatterBarriers[preScatterBarrierCount].sType = + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + preScatterBarriers[preScatterBarrierCount].srcAccessMask = + VK_ACCESS_HOST_WRITE_BIT; + preScatterBarriers[preScatterBarrierCount].dstAccessMask = + VK_ACCESS_SHADER_READ_BIT; + preScatterBarriers[preScatterBarrierCount].buffer = alignmentBuffer; + preScatterBarriers[preScatterBarrierCount].size = VK_WHOLE_SIZE; + ++preScatterBarrierCount; + + preScatterBarriers[preScatterBarrierCount].sType = + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + preScatterBarriers[preScatterBarrierCount].srcAccessMask = + VK_ACCESS_HOST_WRITE_BIT; + preScatterBarriers[preScatterBarrierCount].dstAccessMask = + VK_ACCESS_SHADER_READ_BIT; + preScatterBarriers[preScatterBarrierCount].buffer = robustnessBuffer; + preScatterBarriers[preScatterBarrierCount].size = VK_WHOLE_SIZE; + ++preScatterBarrierCount; + + preScatterBarriers[preScatterBarrierCount].sType = + VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + preScatterBarriers[preScatterBarrierCount].srcAccessMask = + VK_ACCESS_HOST_WRITE_BIT; + preScatterBarriers[preScatterBarrierCount].dstAccessMask = + VK_ACCESS_SHADER_READ_BIT; + preScatterBarriers[preScatterBarrierCount].buffer = + flowVarianceBuffer; + preScatterBarriers[preScatterBarrierCount].size = VK_WHOLE_SIZE; + ++preScatterBarrierCount; + } vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, - nullptr, 1, &localMaskBarrier, 0, nullptr); + nullptr, preScatterBarrierCount, + preScatterBarriers, 0, nullptr); updateImageDescriptorSet(device, greenScatterSet, uploadedFrames[i].view, sampler, 0); @@ -2533,35 +3134,40 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { nullptr, 2, colorBarriers, 0, nullptr); vm.endSingleTimeCommands(cb); - + perf.scatterMs += elapsedMillis(scatterStart); } } // end for each frame - // Normalize this tile and write to staging buffer + // Normalize this tile and write to the fused Bayer output buffer. // NOTE: Bind staging buffer with a row offset to stay within - // maxStorageBufferRange. The shader uses outIndex = (outY * width + outX) - // * 3 + planeIndex, so we offset the binding to the start of this tile's - // first row (tileY * outputW * 3 * 2). We then shift the shader's tileY - // to 0 and height to currentTileH, so outY ranges [0, currentTileH) - // relative to the buffer binding. + // maxStorageBufferRange. The normalize shaders write local row indices + // into the bound row band, but still use global output coordinates for + // CFA parity. { + const auto normalizeStart = PerfClock::now(); VkCommandBuffer cb = vm.beginSingleTimeCommands(); // Compute the byte offset into staging buffer for this tile's row band VkDeviceSize rowBandOffset = - (VkDeviceSize)(ty * tileH) * outputW * 3 * sizeof(uint16_t); + (VkDeviceSize)(ty * tileH) * outputW * sizeof(uint16_t); // Range covers from this row band to the end of the buffer VkDeviceSize stagingTotalSize = - (VkDeviceSize)outputW * outputH * 3 * sizeof(uint16_t); + (VkDeviceSize)outputW * outputH * sizeof(uint16_t); VkDeviceSize rowBandRange = stagingTotalSize - rowBandOffset; for (int colorIdx = 0; colorIdx < 2; ++colorIdx) { updateBufferDescriptorSet(device, colorNormalizeSets[colorIdx], - stagingBuffer, rowBandRange, 0, + fusedBayerBuffer, rowBandRange, 0, rowBandOffset); updateBufferDescriptorSet(device, colorNormalizeSets[colorIdx], rbScatterAccumBuffers[colorIdx], VK_WHOLE_SIZE, 1); + updateBufferDescriptorSet(device, colorNormalizeSets[colorIdx], + priorBayerBuffer, rowBandRange, 2, + rowBandOffset); + updateBufferDescriptorSet(device, colorNormalizeSets[colorIdx], + priorWeightBuffer, rowBandRange, 3, + rowBandOffset); vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, colorNormalizePipeline); vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, @@ -2570,12 +3176,13 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { PushConstants colorPc{}; colorPc.width = outputW; - colorPc.height = outputH - ty * tileH; + colorPc.height = outputH; + colorPc.scale = (float)scale; colorPc.planeWidth = outputW; colorPc.planeHeight = outputH; colorPc.bufferStride = tileW + 16; colorPc.tileX = tx * tileW; - colorPc.tileY = 0; + colorPc.tileY = ty * tileH; colorPc.tileW = currentTileW; colorPc.tileH = currentTileH; colorPc.planeIndex = (colorIdx == 0) ? 0u : 2u; @@ -2591,20 +3198,16 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { (currentTileH + 15) / 16, 1); } - VkMemoryBarrier rbReadyBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - rbReadyBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; - rbReadyBarrier.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, - &rbReadyBarrier, 0, nullptr, 0, nullptr); - - updateBufferDescriptorSet(device, greenNormalizeSet, stagingBuffer, + updateBufferDescriptorSet(device, greenNormalizeSet, fusedBayerBuffer, rowBandRange, 0, rowBandOffset); updateBufferDescriptorSet(device, greenNormalizeSet, greenPhaseAccumBuffers[0], VK_WHOLE_SIZE, 1); updateBufferDescriptorSet(device, greenNormalizeSet, greenPhaseAccumBuffers[1], VK_WHOLE_SIZE, 2); + updateBufferDescriptorSet(device, greenNormalizeSet, priorBayerBuffer, + rowBandRange, 3, rowBandOffset); + updateBufferDescriptorSet(device, greenNormalizeSet, priorWeightBuffer, + rowBandRange, 4, rowBandOffset); vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, greenNormalizePipeline); vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, @@ -2613,12 +3216,13 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { PushConstants greenPc{}; greenPc.width = outputW; - greenPc.height = outputH - ty * tileH; + greenPc.height = outputH; + greenPc.scale = (float)scale; greenPc.planeWidth = outputW; greenPc.planeHeight = outputH; greenPc.bufferStride = tileW + 16; greenPc.tileX = tx * tileW; - greenPc.tileY = 0; + greenPc.tileY = ty * tileH; greenPc.tileW = currentTileW; greenPc.tileH = currentTileH; greenPc.planeIndex = 1; @@ -2634,11 +3238,13 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { (currentTileH + 15) / 16, 1); vm.endSingleTimeCommands(cb); + perf.normalizeMs += elapsedMillis(normalizeStart); } } // end for tx } // end for ty TIME_END(phase4_TileProcessing); + perf.tileProcessingMs = elapsed_phase4_TileProcessing; // ===================================================================== // Phase 5: Read back result from staging buffer @@ -2646,20 +3252,23 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { { TIME_START(phase5_OutputReadback); void *mapData; - VK_CHECK(vkMapMemory(device, stagingMemory, 0, VK_WHOLE_SIZE, 0, &mapData)); - size_t reqSize = (size_t)outputW * outputH * 3 * sizeof(uint16_t); + VK_CHECK( + vkMapMemory(device, fusedBayerMemory, 0, VK_WHOLE_SIZE, 0, &mapData)); + size_t reqSize = (size_t)outputW * outputH * sizeof(uint16_t); if (bufferSize >= reqSize) { memcpy(outBuffer, mapData, reqSize); } else { LOGE("Buffer too small! Req: %zu, Has: %zu", reqSize, bufferSize); } - vkUnmapMemory(device, stagingMemory); + vkUnmapMemory(device, fusedBayerMemory); TIME_END(phase5_OutputReadback); + perf.outputReadbackMs = elapsed_phase5_OutputReadback; } // ===================================================================== // Cleanup // ===================================================================== + const auto cleanupStart = PerfClock::now(); for (auto &uf : uploadedFrames) { if (uf.view) vkDestroyImageView(device, uf.view, nullptr); @@ -2670,6 +3279,9 @@ bool VulkanRawStacker::processStack(uint16_t *outBuffer, size_t bufferSize) { } vkDestroySampler(device, sampler, nullptr); + perf.cleanupMs = elapsedMillis(cleanupStart); + perf.totalMs = elapsedMillis(processStackStart); + perf.logSummary(outputW, outputH, scale); return true; } @@ -2680,20 +3292,6 @@ void VulkanRawStacker::releaseVulkanResources() { 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); - // New Pipelines if (structureTensorSetLayout) vkDestroyDescriptorSetLayout(device, structureTensorSetLayout, nullptr); @@ -2730,6 +3328,20 @@ void VulkanRawStacker::releaseVulkanResources() { if (colorScatterPipeline) vkDestroyPipeline(device, colorScatterPipeline, nullptr); + if (referenceNormalizeSetLayout) + vkDestroyDescriptorSetLayout(device, referenceNormalizeSetLayout, nullptr); + if (referenceNormalizePipelineLayout) + vkDestroyPipelineLayout(device, referenceNormalizePipelineLayout, nullptr); + if (referenceNormalizePipeline) + vkDestroyPipeline(device, referenceNormalizePipeline, nullptr); + + if (referencePriorSetLayout) + vkDestroyDescriptorSetLayout(device, referencePriorSetLayout, nullptr); + if (referencePriorPipelineLayout) + vkDestroyPipelineLayout(device, referencePriorPipelineLayout, nullptr); + if (referencePriorPipeline) + vkDestroyPipeline(device, referencePriorPipeline, nullptr); + if (greenNormalizeSetLayout) vkDestroyDescriptorSetLayout(device, greenNormalizeSetLayout, nullptr); if (greenNormalizePipelineLayout) @@ -2744,17 +3356,10 @@ void VulkanRawStacker::releaseVulkanResources() { if (colorNormalizePipeline) vkDestroyPipeline(device, colorNormalizePipeline, 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 (fusedBayerBuffer != VK_NULL_HANDLE) + vkDestroyBuffer(device, fusedBayerBuffer, nullptr); + if (fusedBayerMemory != VK_NULL_HANDLE) + vkFreeMemory(device, fusedBayerMemory, nullptr); if (alignmentBuffer != VK_NULL_HANDLE) vkDestroyBuffer(device, alignmentBuffer, nullptr); @@ -2791,6 +3396,18 @@ void VulkanRawStacker::releaseVulkanResources() { if (rbScatterAccumMemories[c]) vkFreeMemory(device, rbScatterAccumMemories[c], nullptr); } + if (priorBayerBuffer) + vkDestroyBuffer(device, priorBayerBuffer, nullptr); + if (priorBayerMemory) + vkFreeMemory(device, priorBayerMemory, nullptr); + if (priorWeightBuffer) + vkDestroyBuffer(device, priorWeightBuffer, nullptr); + if (priorWeightMemory) + vkFreeMemory(device, priorWeightMemory, nullptr); + if (normalizedReferenceBuffer) + vkDestroyBuffer(device, normalizedReferenceBuffer, nullptr); + if (normalizedReferenceMemory) + vkFreeMemory(device, normalizedReferenceMemory, nullptr); if (lscView) vkDestroyImageView(device, lscView, nullptr); diff --git a/app/src/main/cpp/vulkan_raw_stacker.h b/app/src/main/cpp/vulkan_raw_stacker.h index ebfb6ec9..e593e801 100644 --- a/app/src/main/cpp/vulkan_raw_stacker.h +++ b/app/src/main/cpp/vulkan_raw_stacker.h @@ -16,6 +16,7 @@ class VulkanRawStacker { public: VulkanRawStacker(uint32_t width, uint32_t height, bool enableSuperRes, + float superResScale, const float *blackLevel, float whiteLevel, const float *wbGains, const float *noiseModel, const float *lensShadingMap = nullptr, uint32_t lscWidth = 0, @@ -31,6 +32,7 @@ public: private: uint32_t width, height; bool mEnableSuperRes = false; + float mSuperResScale = 1.0f; bool isFirstFrame = true; int mCfaPattern = 0; // 0=RGGB, 1=GRBG, 2=GBRG, 3=BGGR @@ -38,14 +40,7 @@ private: int numTilesX = 1; int numTilesY = 1; - 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; // New Pipelines for Handheld Super-Res VkPipelineLayout alignLkPipelineLayout = VK_NULL_HANDLE; @@ -74,6 +69,16 @@ private: VkDescriptorSetLayout colorScatterSetLayout = VK_NULL_HANDLE; VkDescriptorSet colorScatterSets[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE}; + VkDescriptorSetLayout referenceNormalizeSetLayout = VK_NULL_HANDLE; + VkPipelineLayout referenceNormalizePipelineLayout = VK_NULL_HANDLE; + VkPipeline referenceNormalizePipeline = VK_NULL_HANDLE; + VkDescriptorSet referenceNormalizeSet = VK_NULL_HANDLE; + + VkDescriptorSetLayout referencePriorSetLayout = VK_NULL_HANDLE; + VkPipelineLayout referencePriorPipelineLayout = VK_NULL_HANDLE; + VkPipeline referencePriorPipeline = VK_NULL_HANDLE; + VkDescriptorSet referencePriorSet = VK_NULL_HANDLE; + VkDescriptorSetLayout greenNormalizeSetLayout = VK_NULL_HANDLE; VkPipelineLayout greenNormalizePipelineLayout = VK_NULL_HANDLE; VkPipeline greenNormalizePipeline = VK_NULL_HANDLE; @@ -84,12 +89,6 @@ private: VkPipeline colorNormalizePipeline = VK_NULL_HANDLE; VkDescriptorSet colorNormalizeSets[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE}; - // Normalization - VkDescriptorSetLayout normalizeSetLayout = VK_NULL_HANDLE; - VkPipelineLayout normalizePipelineLayout = VK_NULL_HANDLE; - VkPipeline normalizePipeline = VK_NULL_HANDLE; - std::vector normalizeSets; - // Intermediate Buffers VkBuffer kernelBuffer = VK_NULL_HANDLE; // Structure Tensor Output VkDeviceMemory kernelMemory = VK_NULL_HANDLE; @@ -111,8 +110,15 @@ private: VkBuffer rbScatterAccumBuffers[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE}; VkDeviceMemory rbScatterAccumMemories[2] = {VK_NULL_HANDLE, VK_NULL_HANDLE}; - VkBuffer stagingBuffer = VK_NULL_HANDLE; - VkDeviceMemory stagingMemory = VK_NULL_HANDLE; + VkBuffer priorBayerBuffer = VK_NULL_HANDLE; + VkDeviceMemory priorBayerMemory = VK_NULL_HANDLE; + VkBuffer priorWeightBuffer = VK_NULL_HANDLE; + VkDeviceMemory priorWeightMemory = VK_NULL_HANDLE; + VkBuffer normalizedReferenceBuffer = VK_NULL_HANDLE; + VkDeviceMemory normalizedReferenceMemory = VK_NULL_HANDLE; + + VkBuffer fusedBayerBuffer = VK_NULL_HANDLE; + VkDeviceMemory fusedBayerMemory = VK_NULL_HANDLE; // Lens Shading Map VkImage lscImage = VK_NULL_HANDLE; @@ -130,11 +136,6 @@ private: // Reference pyramid for CPU-side coarse alignment (plane resolution proxy) std::vector referencePyramid; - // Accumulated RGB buffers (3 planes: R, G, B) instead of Bayer - // We reuse accumBuffers but maybe need to change count/size logic? - // Current logic: numTilesX * numTilesY * 4. - // We will likely use indices 0, 1, 2 for R, G, B. - struct PushConstants { uint32_t width; // 0 uint32_t height; // 4 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 3a16a05f..ee8ef784 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -552,7 +552,8 @@ class Camera2Controller(private val context: Context) { } val rawImage = when { state.value.burstCapturing -> reader.acquireNextImage() - state.value.useMultiFrame -> reader.acquireNextImage() + state.value.useMFNR -> reader.acquireNextImage() + state.value.useMFSR -> reader.acquireNextImage() else -> reader.acquireLatestImage() } val image = trackImage(rawImage) @@ -1101,7 +1102,7 @@ class Camera2Controller(private val context: Context) { */ private fun applyImageQualitySettings(builder: CaptureRequest.Builder, isCapture: Boolean) { try { - val isBurst = _state.value.useMultiFrame + val isBurst = _state.value.useMFNR || _state.value.useMFSR val effectiveEdgeLevel = if (isBurst && edgeLevel == 2) 1 else edgeLevel val edgeMode = when (effectiveEdgeLevel) { 0 -> CaptureRequest.EDGE_MODE_OFF @@ -1909,12 +1910,16 @@ class Camera2Controller(private val context: Context) { _state.value = _state.value.copy(showGrid = show) } - fun setUseMultiFrame(useMultiFrame: Boolean, multiFrameCount: Int) { - _state.value = _state.value.copy(useMultiFrame = useMultiFrame, multiFrameCount = multiFrameCount) + fun setUseMFNR(useMultiFrame: Boolean) { + _state.value = _state.value.copy(useMFNR = useMultiFrame) } - fun setUseSuperResolution(useSuperResolution: Boolean) { - _state.value = _state.value.copy(useSuperResolution = useSuperResolution) + fun setUseMFSR(useSuperResolution: Boolean) { + _state.value = _state.value.copy(useMFSR = useSuperResolution) + } + + fun setMultiFrameCount(multiFrameCount: Int) { + _state.value = _state.value.copy(multiFrameCount = multiFrameCount) } @@ -2009,15 +2014,13 @@ class Camera2Controller(private val context: Context) { } } - applyUltraHDR(this) - PLog.d( TAG, "Capture request built and ready to send. ISO: ${_state.value.iso}, shutter: ${_state.value.shutterSpeed}, AE: ${_state.value.isAutoExposure}" ) } - if (state.value.useMultiFrame) { + if (state.value.useMFNR || _state.value.useMFSR) { // Burst Mode val requests = ArrayList() val request = captureBuilder.build() @@ -2163,110 +2166,6 @@ class Camera2Controller(private val context: Context) { } } - // RAW + MultiFrame 曝光控制策略(手动曝光自适应版本) - // 原理:多帧堆叠提升 SNR √N 倍,理论上可缩减 0.5*log2(N) EV 的曝光来换取高光余量。 - fun applyUltraHDR(builder: CaptureRequest.Builder) { - if (!_state.value.applyUltraHDR) return - if (!_state.value.useRaw) return - if (!_state.value.useMultiFrame) return - if (!_state.value.isIsoAuto) return - if (!_state.value.isShutterSpeedAuto) return - if (!isManualSensorSupported) return - val characteristics = cachedCharacteristics ?: return - try { - // 计算光照等级 (LV) - val aperture = _state.value.physicalAperture.toDouble() - val shutterSpeed = _state.value.shutterSpeed.toDouble() / 1_000_000_000.0 - val iso = _state.value.iso.toDouble() - val ev = ln(aperture * aperture / shutterSpeed) / ln(2.0) - val lv = ev - ln(iso / 100.0) / ln(2.0) - - // 只有在光照等级足够时才触发 Ultra HDR 曝光压制策略 - // 阈值设为 7.0 (办公室内典型照明),低于此数值通常认为是暗光,不应压低曝光以保护信噪比。 - if (lv < 7.0) { - PLog.d(TAG, "applyUltraHDR: Light level too low (LV=${String.format("%.2f", lv)}), skip HDR reduction") - return - } - - val count = _state.value.multiFrameCount.toDouble() - // 理论最大降幅: 0.5 * log2(N) - val maxReductionEv = ln(count.pow(0.5)) / ln(2.0) - - // 基于当前预览直方图的亮点(满井像素)比例,动态决定要压多少曝光(scaleFactor)来保护高光 - // 亮点越多,压得越狠;如果不满井,则不压曝光,保持原始亮度以保护暗部。 - val histogram = _state.value.histogram ?: intArrayOf() - val scaleFactor = if (histogram.size >= 256) { - val totalPixels = histogram.sum().toDouble().coerceAtLeast(1.0) - // 满井像素在直方图最后一格 (255) - val saturatedPixels = histogram[255].toDouble() - val saturatedRatio = saturatedPixels / totalPixels - - // 定义自适应阈值: - // - 当满井比例 ≤ 0.2% (lowRatio): 认为是琐碎亮点或可接受裁切,不压曝光 (scaleFactor = 0.0) - // - 当满井比例 ≥ 2.0% (highRatio): 认为存在大面积高光过曝,全力压低曝光 (scaleFactor = 1.0) - // - 中间区域:线性过渡 - val lowRatio = 0.002 - val highRatio = 0.02 - if (saturatedRatio <= lowRatio) 0.0 - else if (saturatedRatio >= highRatio) 1.0 - else (saturatedRatio - lowRatio) / (highRatio - lowRatio) - } else { - // 直方图数据缺失时,默认不进行额外的降曝光压制 - 0.0 - } - - val currentIso = _state.value.iso - val currentShutter = _state.value.shutterSpeed - - val actualReductionEv = maxReductionEv * scaleFactor - val reductionFactor = 2.0.pow(actualReductionEv) - - // 优先调整快门以避免感光度不足(低 ISO)在暗部产生的噪点碎片或色差。 - // 在 RAW 流程中,较高的 ISO(在合理范围内)往往比过低的 ISO 配合后期提亮有更好的底噪表现。 - var targetShutter = (currentShutter / reductionFactor).toLong() - var targetIso = currentIso - - // 约束调整:如果快门已经达到硬件极限,则补偿 ISO - val shutterRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_EXPOSURE_TIME_RANGE) - val isoRange = characteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE) - - if (shutterRange != null && isoRange != null) { - if (targetShutter < shutterRange.lower) { - val remainingFactor = shutterRange.lower.toDouble() / targetShutter.toDouble() - targetShutter = shutterRange.lower - targetIso = (targetIso / remainingFactor).toInt().coerceIn(isoRange.lower, isoRange.upper) - } - } - - // 应用手动曝光设置,覆盖 applyBaseCameraSettings - builder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF) - builder.set(CaptureRequest.SENSOR_SENSITIVITY, targetIso) - builder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, targetShutter) - - PLog.d( - TAG, "RAW MultiFrame Histogram-Adaptive Manual Capture (LV=${String.format("%.2f", lv)}): " + - "saturated=${ - String.format( - "%.2f", - (histogram.getOrElse(255) { 0 }.toDouble() / histogram.sum().toDouble() - .coerceAtLeast(1.0)) * 100 - ) - }%, " + - "scale=${String.format("%.2f", scaleFactor)}, " + - "target: ISO=$targetIso (from $currentIso), " + - "Shutter=${String.format("%.2f", targetShutter / 1_000_000.0)}ms (from ${ - String.format( - "%.2f", - currentShutter / 1_000_000.0 - ) - }ms), " + - "reduction=${String.format("%.2f", actualReductionEv)}EV" - ) - } catch (e: Exception) { - PLog.e(TAG, "Failed to apply adaptive manual exposure", e) - } - } - /** * 构建 CaptureInfo diff --git a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt index ca8653b4..210dd484 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/CameraState.kt @@ -1,7 +1,6 @@ package com.hinnka.mycamera.camera import android.graphics.Rect -import android.hardware.camera2.CameraMetadata import android.util.Range /** @@ -177,9 +176,9 @@ data class CameraState( val availableNrModes: IntArray = intArrayOf(), val isRawSupported: Boolean = false, - val useMultiFrame: Boolean = false, + val useMFNR: Boolean = false, val multiFrameCount: Int = 0, - val useSuperResolution: Boolean = false, + val useMFSR: Boolean = false, val useRaw: Boolean = false, val useLivePhoto: Boolean = false, // 是否正在拍摄 Live Photo (用于 UI 动画) diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index db968ee8..a3a695df 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -61,11 +61,12 @@ data class UserPreferences( val frameOrder: List = emptyList(), // 边框排序(ID列表) val categoryOrder: List = emptyList(), // 分类排序 val defaultFocalLength: Float = 0f, // 默认焦段 (mm),0表示不设置 - val useMultiFrame: Boolean = false, // 是否使用多帧合成 - val multiFrameCount: Int = 8, // 多帧合成帧数 + val useMFNR: Boolean = false, // 是否使用多帧降噪 + val multiFrameCount: Int = 8, // 多帧降噪帧数 val useMultipleExposure: Boolean = false, // 是否启用多重曝光 val multipleExposureCount: Int = 2, // 多重曝光张数 - val useSuperResolution: Boolean = false, // 是否使用超分辨率 + val useMFSR: Boolean = false, // 是否启用 RAW 多帧超分 + val rawSuperResolutionScale: Float = 1f, // RAW 多帧超分倍率 val photoQuality: Int = 95, // 照片质量: 90, 95, 100 val useLivePhoto: Boolean = false, // 是否启用 Live Photo (Motion Photo) val enableDevelopAnimation: Boolean = true, // 是否启用拍摄后的显影动画 @@ -138,6 +139,7 @@ class UserPreferencesRepository(private val context: Context) { private val USE_MULTIPLE_EXPOSURE = booleanPreferencesKey("use_multiple_exposure") private val MULTIPLE_EXPOSURE_COUNT = intPreferencesKey("multiple_exposure_count") private val USE_SUPER_RESOLUTION = booleanPreferencesKey("use_super_resolution") + private val RAW_SUPER_RESOLUTION_SCALE = floatPreferencesKey("raw_super_resolution_scale") private val PHOTO_QUALITY = intPreferencesKey("photo_quality") private val USE_LIVE_PHOTO = booleanPreferencesKey("use_live_photo") private val ENABLE_DEVELOP_ANIMATION = booleanPreferencesKey("enable_develop_animation") @@ -197,11 +199,12 @@ class UserPreferencesRepository(private val context: Context) { frameOrder = preferences[FRAME_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList(), categoryOrder = preferences[CATEGORY_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList(), defaultFocalLength = preferences[DEFAULT_FOCAL_LENGTH] ?: 0f, - useMultiFrame = preferences[USE_MULTI_FRAME] ?: false, + useMFNR = preferences[USE_MULTI_FRAME] ?: false, multiFrameCount = preferences[MULTI_FRAME_COUNT] ?: 8, useMultipleExposure = preferences[USE_MULTIPLE_EXPOSURE] ?: false, multipleExposureCount = preferences[MULTIPLE_EXPOSURE_COUNT] ?: 2, - useSuperResolution = preferences[USE_SUPER_RESOLUTION] ?: false, + useMFSR = preferences[USE_SUPER_RESOLUTION] ?: false, + rawSuperResolutionScale = preferences[RAW_SUPER_RESOLUTION_SCALE] ?: 1.5f, photoQuality = preferences[PHOTO_QUALITY] ?: 95, useLivePhoto = preferences[USE_LIVE_PHOTO] ?: false, enableDevelopAnimation = preferences[ENABLE_DEVELOP_ANIMATION] ?: true, @@ -498,7 +501,7 @@ class UserPreferencesRepository(private val context: Context) { /** * 保存是否使用多帧合成 */ - suspend fun saveUseMultiFrame(enabled: Boolean) { + suspend fun setUseMFNR(enabled: Boolean) { context.dataStore.edit { preferences -> preferences[USE_MULTI_FRAME] = enabled } @@ -534,12 +537,18 @@ class UserPreferencesRepository(private val context: Context) { /** * 保存是否使用超分辨率 */ - suspend fun saveUseSuperResolution(enabled: Boolean) { + suspend fun saveUseMFSR(enabled: Boolean) { context.dataStore.edit { preferences -> preferences[USE_SUPER_RESOLUTION] = enabled } } + suspend fun saveRawSuperResolutionScale(scale: Float) { + context.dataStore.edit { preferences -> + preferences[RAW_SUPER_RESOLUTION_SCALE] = scale.coerceIn(1.0f, 2.0f) + } + } + /** * 保存照片质量 */ diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt index 156e84ac..e38c0279 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoManager.kt @@ -15,8 +15,8 @@ import androidx.core.graphics.createBitmap import androidx.exifinterface.media.ExifInterface import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.data.ContentRepository -import com.hinnka.mycamera.hdr.GainmapSourceSet import com.hinnka.mycamera.hdr.GainmapResult +import com.hinnka.mycamera.hdr.GainmapSourceSet import com.hinnka.mycamera.hdr.UltraHdrWriter import com.hinnka.mycamera.hdr.UnifiedGainmapProducer import com.hinnka.mycamera.livephoto.MotionPhotoWriter @@ -43,8 +43,17 @@ import java.nio.IntBuffer import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ConcurrentHashMap -import kotlin.use +import kotlin.io.copyTo +import kotlin.io.deleteRecursively +import kotlin.io.extension +import kotlin.io.inputStream +import kotlin.io.readBytes +import kotlin.io.readText +import kotlin.io.walkBottomUp +import kotlin.io.writeText +import kotlin.math.roundToInt import kotlin.system.measureTimeMillis +import kotlin.use /** * 照片管理器 @@ -188,16 +197,16 @@ object PhotoManager { private fun canReuseEmbeddedGainmap(metadata: PhotoMetadata): Boolean { return metadata.manualHdrEffectEnabled && - metadata.hasEmbeddedGainmap && - metadata.lutId == null && - metadata.colorRecipeParams == null && - metadata.sharpening == null && - metadata.noiseReduction == null && - metadata.chromaNoiseReduction == null && - metadata.frameId == null && - metadata.cropRegion == null && - metadata.postCropRegion == null && - metadata.computationalAperture == null + metadata.hasEmbeddedGainmap && + metadata.lutId == null && + metadata.colorRecipeParams == null && + metadata.sharpening == null && + metadata.noiseReduction == null && + metadata.chromaNoiseReduction == null && + metadata.frameId == null && + metadata.cropRegion == null && + metadata.postCropRegion == null && + metadata.computationalAperture == null } private fun writeFinalJpeg( @@ -282,7 +291,10 @@ object PhotoManager { tempFile.renameTo(detailFile) stableTimestamp?.let { photoDir.setLastModified(it) } _detailHdrReadyEvents.tryEmit(photoId) - PLog.d(TAG, "buildDetailHdrCache success: $photoId, source=${ultraHdrSource.sourceKind}, gainmap=${gainmapResult != null}") + PLog.d( + TAG, + "buildDetailHdrCache success: $photoId, source=${ultraHdrSource.sourceKind}, gainmap=${gainmapResult != null}" + ) true } catch (e: Exception) { PLog.e(TAG, "Failed to build detail HDR cache for $photoId", e) @@ -623,13 +635,58 @@ object PhotoManager { } } + suspend fun exportDng(context: Context, photoId: String, sourceFile: File, metadata: PhotoMetadata) = + withContext(Dispatchers.IO) { + try { + if (!sourceFile.exists() || sourceFile.length() <= 0L) { + PLog.w(TAG, "Skipping DNG export because source file is missing or empty: ${sourceFile.absolutePath}") + return@withContext + } + + val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US) + .format(Date()) + val dngFilename = "PhotonCamera_${timestamp}.dng" + val dngContentValues = ContentValues().apply { + put(MediaStore.MediaColumns.DISPLAY_NAME, dngFilename) + put(MediaStore.MediaColumns.MIME_TYPE, "image/x-adobe-dng") + put( + MediaStore.MediaColumns.RELATIVE_PATH, + Environment.DIRECTORY_DCIM + "/PhotonCamera" + ) + } + + val dngUri = context.contentResolver.insert( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + dngContentValues + ) + + dngUri?.let { uri -> + context.contentResolver.openOutputStream(uri)?.use { outputStream -> + sourceFile.inputStream().use { inputStream -> + inputStream.copyTo(outputStream) + } + } + PLog.d(TAG, "DNG exported from file: $uri") + + val currentMetadata = loadMetadata(context, photoId) ?: metadata + val updatedMetadata = currentMetadata.copy( + exportedUris = currentMetadata.exportedUris + uri.toString() + ) + saveMetadata(context, photoId, updatedMetadata) + PLog.d(TAG, "Exported URI saved: $uri") + } + } catch (e: Exception) { + PLog.e(TAG, "Failed to export DNG", e) + } + } + suspend fun preparePhoto( context: Context, metadata: PhotoMetadata, captureResult: CaptureResult?, thumbnail: Bitmap?, useLivePhoto: Boolean, - useSuperResolution: Boolean, + superResolutionScale: Float, photoId: String? = null, ) = withContext(Dispatchers.IO) { try { @@ -641,9 +698,13 @@ object PhotoManager { val metadataFile = File(photoDir, METADATA_FILE) var cropRegion = captureResult?.get(CaptureResult.SCALER_CROP_REGION) - if (useSuperResolution && cropRegion != null) { - cropRegion = - Rect(cropRegion.left * 2, cropRegion.top * 2, cropRegion.right * 2, cropRegion.bottom * 2) + if (superResolutionScale > 1.0f && cropRegion != null) { + cropRegion = Rect( + (cropRegion.left * superResolutionScale).roundToInt(), + (cropRegion.top * superResolutionScale).roundToInt(), + (cropRegion.right * superResolutionScale).roundToInt(), + (cropRegion.bottom * superResolutionScale).roundToInt() + ) } val dimensions = @@ -836,14 +897,15 @@ object PhotoManager { // 预先准备所有文件路径 val photoFile = File(photoDir, PHOTO_FILE) val dngFile = File(photoDir, DNG_FILE) + val tempDngFile = File(photoDir, "temp.dng") val tempFile = File(photoDir, "temp.jpg") val metadata = loadMetadata(context, photoId) ?: return@withContext captureResult ?: return@withContext - val byteOutstream = ByteArrayOutputStream() - byteOutstream.use { outputStream -> + var dngSaveAttempted = false + FileOutputStream(tempDngFile).use { outputStream -> image.use { try { RawProcessor.saveToDng( @@ -854,17 +916,26 @@ object PhotoManager { rotation, thumbnail ) + dngSaveAttempted = true } catch (e: Throwable) { PLog.e(TAG, "DNG save failed", e) } } } - val array = byteOutstream.toByteArray() - FileOutputStream(dngFile).use { - it.write(array) + val dngWritten = dngSaveAttempted && tempDngFile.exists() && tempDngFile.length() > 0L + if (!dngWritten) { + tempDngFile.delete() + return@withContext + } + if (dngFile.exists()) { + dngFile.delete() + } + if (!tempDngFile.renameTo(dngFile)) { + tempDngFile.copyTo(dngFile, overwrite = true) + tempDngFile.delete() } if (shouldAutoSave) { - exportDng(context, photoId, array, metadata) + exportDng(context, photoId, dngFile, metadata) } val rawResult = RawDemosaicProcessor.getInstance().processForHdrSources( @@ -1099,7 +1170,12 @@ object PhotoManager { fun getMultipleExposureFrameFiles(context: Context, sessionId: String): List { val dir = getMultipleExposureSessionDir(context, sessionId) - return dir.listFiles { file -> file.isFile && file.name.startsWith("frame_") && file.extension.equals("jpg", ignoreCase = true) } + return dir.listFiles { file -> + file.isFile && file.name.startsWith("frame_") && file.extension.equals( + "jpg", + ignoreCase = true + ) + } ?.sortedBy { it.name } ?: emptyList() } @@ -1240,6 +1316,7 @@ object PhotoManager { chromaNoiseReductionValue: Float, photoQuality: Int = 95, useSuperResolution: Boolean = false, + superResolutionScale: Float = 1.0f, useGpuAcceleration: Boolean = true, ) = withContext(Dispatchers.IO) { try { @@ -1323,6 +1400,7 @@ object PhotoManager { chromaNoiseReductionValue: Float, photoQuality: Int = 95, useSuperResolution: Boolean = false, + superResolutionScale: Float = 1.0f, useGpuAcceleration: Boolean = true, exposureBias: Float? = null, droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF @@ -1332,6 +1410,7 @@ object PhotoManager { // 预先准备所有文件路径 val photoFile = File(photoDir, PHOTO_FILE) + val dngFile = File(photoDir, DNG_FILE) val tempFile = File(photoDir, "temp.jpg") val yuvFile = File(photoDir, YUV_FILE) @@ -1353,9 +1432,10 @@ object PhotoManager { ) var currentUseSuperResolution = useSuperResolution - var byteBuffer = MultiFrameStacker.processBurstRaw( - images, characteristics, + var rawStackResult = MultiFrameStacker.processBurstRaw( + images, rawMetadata.cfaPattern, currentUseSuperResolution, + superResolutionScale, useGpuAcceleration, masterBlackLevel = rawMetadata.blackLevel, whiteLevel = rawMetadata.whiteLevel.toInt(), @@ -1367,12 +1447,13 @@ object PhotoManager { lensShadingHeight = 0, ) - if (byteBuffer == null && currentUseSuperResolution) { + if (rawStackResult == null && currentUseSuperResolution) { PLog.w(TAG, "processBurstRaw failed with SR, retrying without SR") currentUseSuperResolution = false - byteBuffer = MultiFrameStacker.processBurstRaw( - images, characteristics, + rawStackResult = MultiFrameStacker.processBurstRaw( + images, rawMetadata.cfaPattern, currentUseSuperResolution, + 1.0f, useGpuAcceleration, masterBlackLevel = rawMetadata.blackLevel, whiteLevel = rawMetadata.whiteLevel.toInt(), @@ -1384,14 +1465,15 @@ object PhotoManager { ) } - val finalByteBuffer = byteBuffer ?: return@withContext + val finalStackResult = rawStackResult ?: return@withContext val result: Bitmap = run { // Construct metadata for Linear RGB - val finalScale = if (currentUseSuperResolution) 2 else 1 + val finalWidth = finalStackResult.width + val finalHeight = finalStackResult.height val linearMetadata = rawMetadata.copy( - width = firstImageWidth * finalScale, - height = firstImageHeight * finalScale, + width = finalWidth, + height = finalHeight, cfaPattern = RawMetadata.CFA_LINEAR_RGB, blackLevel = floatArrayOf(0f, 0f, 0f, 0f), whiteLevel = 65535f, @@ -1401,15 +1483,17 @@ object PhotoManager { ) var bitmap = RawDemosaicProcessor.getInstance().process( context, - finalByteBuffer, - firstImageWidth * finalScale, - firstImageHeight * finalScale, - firstImageWidth * finalScale * 6, // 3 channels * 2 bytes + finalStackResult.stackedRgbBuffer, + finalWidth, + finalHeight, + finalWidth * 6, // 3 channels * 2 bytes linearMetadata, aspectRatio, metadata.cropRegion, rotation, - sharpeningValue = 0.4f + sharpeningValue = 0.4f, + denoiseValue = 0f, + chromaDenoiseValue = 0.2f ) if (metadata.isMirrored && bitmap != null) { @@ -1424,6 +1508,26 @@ object PhotoManager { bitmap } ?: return@withContext + + processingScope.launch { + trySaveStackedRawDng( + context = context, + photoId = photoId, + dngFile = dngFile, + fusedBayerBuffer = finalStackResult.fusedBayerBuffer, + width = finalStackResult.width, + height = finalStackResult.height, + rawMetadata = rawMetadata, + isNormalizedSensorData = finalStackResult.isNormalizedSensorData, + characteristics = characteristics, + captureResult = captureResult, + rotation = rotation, + thumbnail = result, + metadata = metadata, + shouldAutoSave = shouldAutoSave + ) + } + // Save Original (Stacked Result) FileOutputStream(tempFile).use { outputStream -> writeFinalJpeg(result, outputStream, photoQuality) @@ -1448,6 +1552,76 @@ object PhotoManager { } } + private suspend fun trySaveStackedRawDng( + context: Context, + photoId: String, + dngFile: File, + fusedBayerBuffer: ByteBuffer, + width: Int, + height: Int, + rawMetadata: RawMetadata, + isNormalizedSensorData: Boolean, + characteristics: CameraCharacteristics, + captureResult: CaptureResult, + rotation: Int, + thumbnail: Bitmap?, + metadata: PhotoMetadata, + shouldAutoSave: Boolean, + ) { + val tempDngFile = File(dngFile.parentFile, "temp_stacked.dng") + val dngWritten = try { + FileOutputStream(tempDngFile).use { outputStream -> + RawProcessor.saveRawBufferToDng( + rawBuffer = fusedBayerBuffer, + width = width, + height = height, + characteristics = characteristics, + captureResult = captureResult, + outputStream = outputStream, + rotation = rotation, + thumbnail = thumbnail, + cfaPattern = rawMetadata.cfaPattern, + blackLevel = rawMetadata.blackLevel, + whiteLevel = rawMetadata.whiteLevel.toInt(), + valueDomain = if (isNormalizedSensorData) { + RawProcessor.RawBufferValueDomain.NORMALIZED_SENSOR_RANGE + } else { + RawProcessor.RawBufferValueDomain.SENSOR + } + ) + } + } catch (e: Throwable) { + PLog.w(TAG, "Failed to build stacked RAW DNG, ignoring", e) + false + } + + if (!dngWritten || !tempDngFile.exists() || tempDngFile.length() <= 0L) { + tempDngFile.delete() + return + } + + try { + if (dngFile.exists()) { + dngFile.delete() + } + if (!tempDngFile.renameTo(dngFile)) { + tempDngFile.copyTo(dngFile, overwrite = true) + tempDngFile.delete() + } + } catch (e: Exception) { + tempDngFile.delete() + if (dngFile.exists()) { + dngFile.delete() + } + PLog.w(TAG, "Failed to persist stacked RAW DNG, ignoring", e) + return + } + + if (shouldAutoSave) { + exportDng(context, photoId, dngFile, metadata) + } + } + /** * 保存堆栈合成后的照片 @@ -1467,6 +1641,7 @@ object PhotoManager { chromaNoiseReductionValue: Float, photoQuality: Int = 95, useSuperResolution: Boolean = false, + superResolutionScale: Float = 1.0f, useGpuAcceleration: Boolean = true, exposureBias: Float? = null, droMode: RawProcessingPreferences.DROMode = RawProcessingPreferences.DROMode.OFF @@ -1486,6 +1661,7 @@ object PhotoManager { chromaNoiseReductionValue, photoQuality, useSuperResolution, + superResolutionScale, useGpuAcceleration ) } @@ -1506,6 +1682,7 @@ object PhotoManager { chromaNoiseReductionValue, photoQuality, useSuperResolution, + superResolutionScale, useGpuAcceleration, exposureBias, droMode @@ -1877,7 +2054,12 @@ object PhotoManager { return loadBitmap(context, Uri.fromFile(photoFile), maxEdge, preserveHdr) } - fun loadOriginalBitmap(context: Context, photoId: String, maxEdge: Int? = null, preserveHdr: Boolean = false): Bitmap? { + fun loadOriginalBitmap( + context: Context, + photoId: String, + maxEdge: Int? = null, + preserveHdr: Boolean = false + ): Bitmap? { val photoFile = getPhotoFile(context, photoId) if (!photoFile.exists()) { return null @@ -2011,7 +2193,8 @@ object PhotoManager { // 1. 检测是否为 RAW 文件 val mimeType = context.contentResolver.getType(uri) val fileName = getFileName(context, uri) ?: "" - val userPrefs = ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull() + val userPrefs = + ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull() val isRaw = mimeType?.contains("raw", ignoreCase = true) == true || mimeType?.contains("dng", ignoreCase = true) == true || fileName.endsWith(".dng", ignoreCase = true) || @@ -2030,14 +2213,14 @@ object PhotoManager { // 3. 处理 RAW 以生成 JPEG 预览 var updatedMetadata = metadata - val processedBitmap = RawDemosaicProcessor.getInstance().process( - context, - dngFile.absolutePath, null, null, 0, - sharpeningValue = 0.4f, - denoiseValue = updatedMetadata.rawDenoiseValue, - onMetadata = { raw -> - updatedMetadata = updatedMetadata.merge(raw) - } + val processedBitmap = RawDemosaicProcessor.getInstance().process( + context, + dngFile.absolutePath, null, null, 0, + sharpeningValue = 0.4f, + denoiseValue = updatedMetadata.rawDenoiseValue, + onMetadata = { raw -> + updatedMetadata = updatedMetadata.merge(raw) + } ) if (processedBitmap != null) { @@ -2121,7 +2304,11 @@ object PhotoManager { } } - suspend fun refreshRawPreview(context: Context, photoId: String, droMode: RawProcessingPreferences.DROMode): Bitmap? { + suspend fun refreshRawPreview( + context: Context, + photoId: String, + droMode: RawProcessingPreferences.DROMode + ): Bitmap? { return withContext(Dispatchers.IO) { try { val photoDir = getPhotoDir(context, photoId, true) 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 06572504..8446b6b6 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/MultiFrameStacker.kt @@ -2,7 +2,6 @@ package com.hinnka.mycamera.processor import android.graphics.Bitmap import android.graphics.ColorSpace -import android.hardware.camera2.CameraCharacteristics import android.media.Image import android.util.Log import com.hinnka.mycamera.utils.PLog @@ -12,6 +11,15 @@ import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.utils.BitmapUtils import java.nio.ByteOrder +import kotlin.math.roundToInt + +data class RawStackResult( + val stackedRgbBuffer: ByteBuffer, + val fusedBayerBuffer: ByteBuffer, + val width: Int, + val height: Int, + val isNormalizedSensorData: Boolean, +) /** * Multi-Frame Stacker @@ -151,8 +159,9 @@ object MultiFrameStacker { fun processBurstRaw( images: List, - characteristics: CameraCharacteristics, + cfaPattern: Int, enableSuperResolution: Boolean = false, + superResolutionScale: Float = 1.5f, useVulkan: Boolean = true, masterBlackLevel: FloatArray = floatArrayOf(0f, 0f, 0f, 0f), whiteLevel: Int = 1023, @@ -161,49 +170,78 @@ object MultiFrameStacker { lensShading: FloatArray? = null, lensShadingWidth: Int = 0, lensShadingHeight: Int = 0, - ): ByteBuffer? { + ): RawStackResult? { val width = images[0].width val height = images[0].height - val sensorCfa = characteristics.get(CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT) ?: 0 PLog.d( TAG, - "Starting RAW stacking for ${images.size} frames. Pattern=$sensorCfa SR=$enableSuperResolution Vulkan=$useVulkan WL=$whiteLevel" + "Starting RAW stacking for ${images.size} frames. Pattern=$cfaPattern SR=$enableSuperResolution scale=$superResolutionScale Vulkan=$useVulkan WL=$whiteLevel" ) + val outputScale = if (enableSuperResolution) superResolutionScale.coerceIn(1.0f, 2.0f) else 1.0f + val useNativeSuperResolution = outputScale > 1.0f - // Try Vulkan path if (useVulkan) { val vulkanStackerPtr = createVulkanRawStackerNative( - width, height, enableSuperResolution, + width, height, enableSuperResolution, outputScale, masterBlackLevel, whiteLevel, whiteBalanceGains, noiseModel, lensShading, lensShadingWidth, lensShadingHeight ) if (vulkanStackerPtr != 0L) { - PLog.i(TAG, "Using Vulkan RAW stacker") + PLog.i(TAG, "Using Vulkan RAW stacker + native LibRaw demosaic") try { for (image in images) { image.use { if (image.width != width || image.height != height) return@use val buffer = image.planes[0].buffer val rowStride = image.planes[0].rowStride - addVulkanRawFrameNative(vulkanStackerPtr, buffer, rowStride, sensorCfa) + addVulkanRawFrameNative(vulkanStackerPtr, buffer, rowStride, cfaPattern) } } - // RGB output (3 channels * 16-bit = 6 bytes per pixel) - val scale = if (enableSuperResolution) 2 else 1 - val stackedBuffer = try { - ByteBuffer.allocateDirect(width * scale * height * scale * 6) + val outWidth = (width * outputScale).roundToInt() + val outHeight = (height * outputScale).roundToInt() + val fusedBayerBuffer = try { + ByteBuffer.allocateDirect(outWidth * outHeight * 2) .order(ByteOrder.nativeOrder()) } catch (e: OutOfMemoryError) { - PLog.e(TAG, "OOM allocating Vulkan RAW buffer (SR=$enableSuperResolution)", e) + PLog.e(TAG, "OOM allocating Vulkan fused Bayer buffer", e) return null } - val success = processVulkanRawStackNative(vulkanStackerPtr, stackedBuffer) - if (success) { - PLog.i(TAG, "Vulkan RAW stacking completed successfully") - return stackedBuffer + val stackedBuffer = try { + ByteBuffer.allocateDirect(outWidth * outHeight * 6) + .order(ByteOrder.nativeOrder()) + } catch (e: OutOfMemoryError) { + PLog.e(TAG, "OOM allocating Vulkan stacked RGB buffer", e) + return null + } + + val fusedOk = processVulkanRawStackNative(vulkanStackerPtr, fusedBayerBuffer) + if (fusedOk) { + val demosaicOk = demosaicStackedRawWithLibRawNative( + fusedBayerBuffer, + outWidth, + outHeight, + cfaPattern, + floatArrayOf(0f, 0f, 0f, 0f), + 65535, + whiteBalanceGains, + stackedBuffer + ) + if (demosaicOk) { + fusedBayerBuffer.rewind() + stackedBuffer.rewind() + PLog.i(TAG, "Vulkan RAW stacking and native LibRaw demosaic completed successfully") + return RawStackResult( + stackedRgbBuffer = stackedBuffer, + fusedBayerBuffer = fusedBayerBuffer, + width = outWidth, + height = outHeight, + isNormalizedSensorData = true + ) + } + PLog.w(TAG, "Vulkan fused Bayer demosaic failed, falling back to CPU") } else { PLog.w(TAG, "Vulkan RAW stacking failed, falling back to CPU") } @@ -217,9 +255,8 @@ object MultiFrameStacker { } } - // CPU fallback - PLog.i(TAG, "Using CPU RAW stacker") - var stackerPtr = createRawStackerNative(width, height, enableSuperResolution) + PLog.i(TAG, "Using CPU RAW stacker + native LibRaw demosaic") + val stackerPtr = createRawStackerNative(width, height, useNativeSuperResolution) if (stackerPtr == 0L) { PLog.e(TAG, "Failed to create CPU raw stacker") return null @@ -232,7 +269,7 @@ object MultiFrameStacker { if (image.width != width || image.height != height) return@use val buffer = image.planes[0].buffer val rowStride = image.planes[0].rowStride - stageRawFrameNative(stackerPtr, buffer, rowStride, sensorCfa) + stageRawFrameNative(stackerPtr, buffer, rowStride, cfaPattern) stagedIndices.add(stagedIndices.size) } } @@ -241,18 +278,51 @@ object MultiFrameStacker { } clearStagedRawFramesNative(stackerPtr) - val scale = if (enableSuperResolution) 2 else 1 - val stackedBuffer = try { - ByteBuffer.allocateDirect(width * scale * height * scale * 2) + val stackedWidth = if (useNativeSuperResolution) width * 2 else width + val stackedHeight = if (useNativeSuperResolution) height * 2 else height + val fusedBayerBuffer = try { + ByteBuffer.allocateDirect(stackedWidth * stackedHeight * 2) .order(ByteOrder.nativeOrder()) } catch (e: OutOfMemoryError) { - PLog.e(TAG, "OOM allocating CPU RAW buffer (SR=$enableSuperResolution)", e) + PLog.e(TAG, "OOM allocating fused Bayer buffer", e) return null } - processRawStackWithBufferNative(stackerPtr, stackedBuffer) + processRawStackWithBufferNative(stackerPtr, fusedBayerBuffer) + + val stackedRgbBuffer = try { + ByteBuffer.allocateDirect(stackedWidth * stackedHeight * 6) + .order(ByteOrder.nativeOrder()) + } catch (e: OutOfMemoryError) { + PLog.e(TAG, "OOM allocating stacked RGB buffer", e) + return null + } + + val success = demosaicStackedRawWithLibRawNative( + fusedBayerBuffer, + stackedWidth, + stackedHeight, + cfaPattern, + masterBlackLevel, + whiteLevel, + whiteBalanceGains, + stackedRgbBuffer + ) + if (!success) { + PLog.e(TAG, "Native LibRaw demosaic failed") + return null + } + + fusedBayerBuffer.rewind() + stackedRgbBuffer.rewind() + PLog.i(TAG, "CPU RAW stacking and native LibRaw demosaic completed successfully") + return RawStackResult( + stackedRgbBuffer = stackedRgbBuffer, + fusedBayerBuffer = fusedBayerBuffer, + width = stackedWidth, + height = stackedHeight, + isNormalizedSensorData = false + ) - PLog.i(TAG, "CPU RAW stacking completed successfully") - return stackedBuffer } finally { releaseRawStackerNative(stackerPtr) } @@ -297,11 +367,21 @@ object MultiFrameStacker { private external fun processRawFrameNative(stackerPtr: Long, index: Int) private external fun clearStagedRawFramesNative(stackerPtr: Long) private external fun processRawStackWithBufferNative(stackerPtr: Long, outputBuffer: ByteBuffer) + private external fun demosaicStackedRawWithLibRawNative( + fusedBayerBuffer: ByteBuffer, + width: Int, + height: Int, + cfaPattern: Int, + blackLevel: FloatArray, + whiteLevel: Int, + wbGains: FloatArray, + outputBuffer: ByteBuffer + ): Boolean private external fun releaseRawStackerNative(stackerPtr: Long) // Vulkan RAW Stacker private external fun createVulkanRawStackerNative( - width: Int, height: Int, enableSuperRes: Boolean, + width: Int, height: Int, enableSuperRes: Boolean, superResScale: Float, blackLevel: FloatArray, whiteLevel: Int, wbGains: FloatArray, noiseModel: FloatArray, lensShadingMap: FloatArray?, shadingMapWidth: Int, shadingMapHeight: Int ): Long diff --git a/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt b/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt index 71d51eb6..0fceffb8 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/HistogramMatching.kt @@ -37,6 +37,12 @@ object HistogramMatching { referenceBitmap: Bitmap? ): FloatArray { val baseCurve = buildAcr3BaseCurve(logCurve) + + if (logCurve != LogCurve.SRGB) { + PLog.d(TAG, "using ACR3 base curve for log curve") + return stabilizeCurve(baseCurve, baseCurve, logCurve) + } + if (referenceBitmap == null) { PLog.d(TAG, "No embedded preview found, using ACR3 base curve") return stabilizeCurve(baseCurve, baseCurve, logCurve) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/NLMShaders.kt b/app/src/main/java/com/hinnka/mycamera/raw/NLMShaders.kt index 34c33323..95a70706 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/NLMShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/NLMShaders.kt @@ -101,6 +101,10 @@ object NLMShaders { void main() { vec3 centerVal = texture(uInputTexture, vTexCoord).rgb; + if (uH <= 0.00001) { + fragColor = vec4(centerVal, 1.0); + return; + } float h2 = max(uH * uH, 1e-5); float patchArea = float((2 * PATCH_RADIUS + 1) * (2 * PATCH_RADIUS + 1)); @@ -173,6 +177,10 @@ object NLMShaders { void main() { vec3 centerValBlur = texture(uBlurTexture, vTexCoord).rgb; + if (uH <= 0.00001) { + fragColor = vec4(centerValBlur, 1.0); + return; + } float h2 = max(uH * uH, 1e-5); float patchArea = float((2 * PATCH_RADIUS + 1) * (2 * PATCH_RADIUS + 1)); diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 3fbb0952..2bb78b34 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -356,6 +356,7 @@ class RawDemosaicProcessor { rotation: Int, sharpeningValue: Float = 0f, denoiseValue: Float? = null, + chromaDenoiseValue: Float? = null, ): Bitmap? = withContext(glDispatcher) { try { if (!isInitialized) { @@ -377,6 +378,7 @@ class RawDemosaicProcessor { rotation = rotation, sharpeningValue = sharpeningValue, denoiseValue = denoiseValue, + chromaDenoiseValue = chromaDenoiseValue )?.sdrBitmap } catch (e: Exception) { PLog.e(TAG, "Failed to process RAW buffer", e) @@ -436,6 +438,7 @@ class RawDemosaicProcessor { exposureBias: Float = 0f, sharpeningValue: Float = 0f, denoiseValue: Float? = null, + chromaDenoiseValue: Float? = null, dngFile: File? = null, onMetadata: ((RawMetadata) -> Unit)? = null, includeHdrReference: Boolean = false @@ -577,14 +580,16 @@ class RawDemosaicProcessor { val workingColorSpace = resolveWorkingColorSpace() val denoiseValue = denoiseValue ?: 0.2f - val outputTexture = if (denoiseValue > 0f) { + val chromaDenoiseValue = chromaDenoiseValue ?: 0.2f + val outputTexture = if (denoiseValue > 0f || chromaDenoiseValue > 0f) { // NLM 降噪 renderNLMPass( sourceTextureId = demosaicTextureId, width = actualWidth, height = actualHeight, metadata = actualMetadata, - denoiseValue = denoiseValue + denoiseValue = denoiseValue, + chromaDenoiseValue = chromaDenoiseValue, ) gfTexId[1] } else { @@ -1066,7 +1071,8 @@ class RawDemosaicProcessor { width: Int, height: Int, metadata: RawMetadata, - denoiseValue: Float + denoiseValue: Float, + chromaDenoiseValue: Float, ) { setupNLMFramebuffers(width, height) @@ -1096,15 +1102,16 @@ class RawDemosaicProcessor { // 1. noiseBase 直接决定主体强度 // 2. totalGain 同时以 sqrt 与线性两部分参与,提升高增益场景下的去噪力度 val gainSqrt = sqrt(totalGain.toDouble()).toFloat() - val gainNoise = denoiseValue * (0.0035f * gainSqrt + 0.0006f * totalGain) + val gainNoise = 0.0035f * gainSqrt + 0.0006f * totalGain val baseNoise = if (noiseBase > 0f) { - noiseBase * denoiseValue * 0.8f + noiseBase * 0.8f } else { - denoiseValue * 0.010f * gainSqrt + 0.010f * gainSqrt } val noise = baseNoise + gainNoise - val h = noise.coerceIn(0.001f, 0.1f) + val h = (noise * denoiseValue).coerceIn(0.0f, 0.1f) + val ch = (noise * chromaDenoiseValue).coerceIn(0.0f, 0.1f) PLog.d( TAG, "Dynamic NLM: totalGain=${"%.2f".format(totalGain)} (ISO=$isoGain, Boost=$digitalGain, Post=$postGain), noiseBase=$noiseBase, baseNoise=$baseNoise, gainNoise=$gainNoise, h=$h" @@ -1126,7 +1133,7 @@ class RawDemosaicProcessor { GLES30.glGetUniformLocation(gfPass0Program, "uTexMatrix"), 1, false, identityMatrix, 0 ) - GLES30.glUniform1f(GLES30.glGetUniformLocation(gfPass0Program, "uH"), h) + GLES30.glUniform1f(GLES30.glGetUniformLocation(gfPass0Program, "uH"), ch) drawQuad(gfPass0Program) // ===== NLM Pass 1: Horizontal (gfChromaTexId -> gfFboId[0]) ===== diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt index a61a7e1e..14c92df8 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraScreen.kt @@ -12,10 +12,8 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.* -import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut -import androidx.compose.animation.shrinkVertically import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.Canvas @@ -33,8 +31,6 @@ import androidx.compose.material.icons.automirrored.outlined.Undo import androidx.compose.material.icons.filled.Cameraswitch import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Layers -import androidx.compose.material.icons.filled.Undo -import androidx.compose.material.icons.outlined.Undo import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment @@ -60,7 +56,6 @@ import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Constraints @@ -108,9 +103,9 @@ fun CameraScreen( val currentRecipeParams by viewModel.currentRecipeParams.collectAsState() val categoryOrder by viewModel.categoryOrder.collectAsState(emptyList()) val useRaw by viewModel.useRaw.collectAsState() - val useMultiFrame by viewModel.useMultiFrame.collectAsState() + val useMFNR by viewModel.useMFNR.collectAsState() val useMultipleExposure by viewModel.useMultipleExposure.collectAsState() - val useSuperResolution by viewModel.useSuperResolution.collectAsState() + val useMFSR by viewModel.useMFSR.collectAsState() val useLivePhoto by viewModel.useLivePhoto.collectAsState() val enableDevelopAnimation by viewModel.enableDevelopAnimation.collectAsState() val phantomMode by viewModel.phantomMode.collectAsState() @@ -774,21 +769,15 @@ fun CameraScreen( activePanel = ActivePanel.NONE onSettingsClick() }, - useMultiFrame = useMultiFrame, - onMultiFrameToggle = { - if (!it) { - viewModel.setUseSuperResolution(false) - } - viewModel.setUseMultiFrame(it) + useMFNR = useMFNR, + onMFNRToggle = { + viewModel.setUseMFNR(it) }, useMultipleExposure = useMultipleExposure, onMultipleExposureToggle = { viewModel.setUseMultipleExposure(it) }, - useSuperResolution = useSuperResolution, - onSuperResolutionToggle = { - if (it) { - viewModel.setUseMultiFrame(true) - } - viewModel.setUseSuperResolution(it) + useMFSR = useMFSR, + onMFSRToggle = { + viewModel.setUseMFSR(it) } ) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt index 9208156e..b1505825 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/camera/CameraTopSheet.kt @@ -41,12 +41,12 @@ fun CameraTopSheet( phantomMode: Boolean, onPhantomModeToggle: (Boolean) -> Unit, onMoreSettingsClick: () -> Unit, - useMultiFrame: Boolean, - onMultiFrameToggle: (Boolean) -> Unit, + useMFNR: Boolean, + onMFNRToggle: (Boolean) -> Unit, useMultipleExposure: Boolean, onMultipleExposureToggle: (Boolean) -> Unit, - useSuperResolution: Boolean, - onSuperResolutionToggle: (Boolean) -> Unit, + useMFSR: Boolean, + onMFSRToggle: (Boolean) -> Unit, modifier: Modifier = Modifier ) { AnimatedVisibility( @@ -94,28 +94,29 @@ fun CameraTopSheet( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp) ) { - QuickSettingToggle( title = stringResource(R.string.settings_use_multi_frame), - checked = useMultiFrame, - onCheckedChange = onMultiFrameToggle, - modifier = Modifier.weight(1f) - ) - - QuickSettingToggle( - title = stringResource(R.string.settings_use_super_resolution), - checked = useSuperResolution, - onCheckedChange = onSuperResolutionToggle, + checked = useMFNR, + onCheckedChange = onMFNRToggle, modifier = Modifier.weight(1f) ) if (isRawSupported) { + QuickSettingToggle( + title = stringResource(R.string.settings_use_super_resolution), + checked = useMFSR, + onCheckedChange = onMFSRToggle, + modifier = Modifier.weight(1f) + ) + QuickSettingToggle( title = stringResource(R.string.settings_use_raw), checked = useRaw, onCheckedChange = onRawToggle, modifier = Modifier.weight(1f) ) + } else { + Spacer(modifier = Modifier.weight(1f)) } } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index 06e94e13..309dda25 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -126,6 +126,8 @@ fun SettingsScreen( val nrLevel by viewModel.nrLevel.collectAsState(initial = 1) val edgeLevel by viewModel.edgeLevel.collectAsState(initial = 1) val useRaw by viewModel.useRaw.collectAsState(initial = false) + val useSuperResolution by viewModel.useMFSR.collectAsState(initial = false) + val rawSuperResolutionScale by viewModel.rawSuperResolutionScale.collectAsState(initial = 1f) // 软件处理参数 val sharpening by viewModel.sharpening.collectAsState(initial = 0f) val noiseReduction by viewModel.noiseReduction.collectAsState(initial = 0f) @@ -720,6 +722,25 @@ fun SettingsScreen( modifier = Modifier.padding(vertical = 12.dp) ) + QualityLevelSetting( + title = stringResource(R.string.settings_super_resolution_scale), + description = stringResource(R.string.settings_super_resolution_scale_description), + levels = listOf( + 1f to "1x", + 1.25f to "1.25x", + 1.5f to "1.5x", + 1.75f to "1.75x", + 2.0f to "2.0x" + ), + currentLevel = rawSuperResolutionScale, + onLevelSelected = { viewModel.setRawSuperResolutionScale(it) } + ) + + HorizontalDivider( + color = Color.White.copy(alpha = 0.1f), + modifier = Modifier.padding(vertical = 12.dp) + ) + SwitchSettingItem( title = stringResource(R.string.settings_use_multiple_exposure), description = stringResource(R.string.settings_use_multiple_exposure_description), diff --git a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt index f8a781bd..a0effb9b 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -10,6 +10,7 @@ import android.util.Log import android.util.Size import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.model.SafeImage +import com.hinnka.mycamera.raw.RawMetadata import com.hinnka.mycamera.raw.RawDemosaicProcessor import java.io.File import java.io.FileInputStream @@ -27,6 +28,11 @@ object RawProcessor { private const val TAG = "RawProcessor" + enum class RawBufferValueDomain { + SENSOR, + NORMALIZED_SENSOR_RANGE, + } + /** * 检查图像是否为 RAW 格式 */ @@ -134,6 +140,116 @@ object RawProcessor { } } + fun saveRawBufferToDng( + rawBuffer: ByteBuffer, + width: Int, + height: Int, + characteristics: CameraCharacteristics, + captureResult: CaptureResult, + outputStream: java.io.OutputStream, + rotation: Int = 0, + thumbnail: Bitmap? = null, + cfaPattern: Int = RawMetadata.CFA_RGGB, + blackLevel: FloatArray = floatArrayOf(0f, 0f, 0f, 0f), + whiteLevel: Int = 65535, + valueDomain: RawBufferValueDomain = RawBufferValueDomain.SENSOR, + ): Boolean { + val dngCreator = DngCreator(characteristics, captureResult) + return try { + val orientation = when (rotation) { + 90 -> ExifInterface.ORIENTATION_ROTATE_90 + 180 -> ExifInterface.ORIENTATION_ROTATE_180 + 270 -> ExifInterface.ORIENTATION_ROTATE_270 + else -> ExifInterface.ORIENTATION_NORMAL + } + dngCreator.setOrientation(orientation) + buildDngThumbnail(thumbnail)?.let { + dngCreator.setThumbnail(it) + PLog.d(TAG, "Embedded stacked DNG thumbnail written: ${it.width}x${it.height}") + } + + val dngInputBuffer = rawBuffer.duplicate().order(ByteOrder.nativeOrder()) + if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) { + denormalizeNormalizedRawBufferInPlace( + rawBuffer = dngInputBuffer, + width = width, + height = height, + cfaPattern = cfaPattern, + blackLevel = blackLevel, + whiteLevel = whiteLevel + ) + } + dngInputBuffer.rewind() + dngCreator.writeByteBuffer(outputStream, Size(width, height), dngInputBuffer, 0) + true + } catch (e: Exception) { + PLog.w(TAG, "Failed to save stacked RAW buffer as DNG, ignoring", e) + false + } finally { + dngCreator.close() + } + } + + private fun denormalizeNormalizedRawBufferInPlace( + rawBuffer: ByteBuffer, + width: Int, + height: Int, + cfaPattern: Int, + blackLevel: FloatArray, + whiteLevel: Int, + ) { + val output = rawBuffer.order(ByteOrder.nativeOrder()).asShortBuffer() + var index = 0 + for (y in 0 until height) { + val rowParity = y and 1 + for (x in 0 until width) { + val channelIndex = getRggbChannelIndex(x and 1, rowParity, cfaPattern) + val encoded = output.get(index).toInt() and 0xFFFF + val channelBlackLevel = blackLevel.getOrElse(channelIndex) { 0f } + val channelWhiteLevel = whiteLevel.coerceAtLeast(channelBlackLevel.toInt() + 1) + val sensorValue = ((encoded / 65535f) * (channelWhiteLevel - channelBlackLevel) + channelBlackLevel) + .toInt() + .coerceIn(0, channelWhiteLevel) + output.put(index, sensorValue.toShort()) + index++ + } + } + } + + private fun getRggbChannelIndex(xParity: Int, yParity: Int, cfaPattern: Int): Int { + return when (cfaPattern) { + RawMetadata.CFA_RGGB -> when { + yParity == 0 && xParity == 0 -> 0 + yParity == 0 && xParity == 1 -> 1 + yParity == 1 && xParity == 0 -> 2 + else -> 3 + } + + RawMetadata.CFA_GRBG -> when { + yParity == 0 && xParity == 0 -> 1 + yParity == 0 && xParity == 1 -> 0 + yParity == 1 && xParity == 0 -> 3 + else -> 2 + } + + RawMetadata.CFA_GBRG -> when { + yParity == 0 && xParity == 0 -> 2 + yParity == 0 && xParity == 1 -> 3 + yParity == 1 && xParity == 0 -> 0 + else -> 1 + } + + RawMetadata.CFA_BGGR -> when { + yParity == 0 && xParity == 0 -> 3 + yParity == 0 && xParity == 1 -> 2 + yParity == 1 && xParity == 0 -> 1 + else -> 0 + } + + else -> 0 + } + } + private fun buildDngThumbnail(source: Bitmap?): Bitmap? { if (source == null || source.isRecycled) { return null diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index b6e00f58..0f4a4cb1 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -1,11 +1,8 @@ package com.hinnka.mycamera.viewmodel import android.app.Application -import android.app.PendingIntent import android.content.Context import android.content.Intent -import android.content.pm.ShortcutInfo -import android.content.pm.ShortcutManager import android.graphics.Bitmap import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCharacteristics @@ -38,6 +35,7 @@ import com.hinnka.mycamera.raw.rawFolder import com.hinnka.mycamera.ui.camera.CameraGLSurfaceView import com.hinnka.mycamera.utils.* import kotlinx.coroutines.* +import kotlin.math.roundToInt import kotlinx.coroutines.flow.* import java.io.File import java.util.UUID @@ -165,8 +163,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val defaultFocalLength: Flow = userPreferencesRepository.userPreferences.map { it.defaultFocalLength } val userPreferences: StateFlow = userPreferencesRepository.userPreferences .stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.data.UserPreferences()) - val useMultiFrame: StateFlow = userPreferencesRepository.userPreferences - .map { it.useMultiFrame } + val useMFNR: StateFlow = userPreferencesRepository.userPreferences + .map { it.useMFNR } .stateIn(viewModelScope, SharingStarted.Eagerly, false) val useMultipleExposure: StateFlow = userPreferencesRepository.userPreferences .map { it.useMultipleExposure } @@ -177,9 +175,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val multiFrameCount: StateFlow = userPreferencesRepository.userPreferences .map { it.multiFrameCount } .stateIn(viewModelScope, SharingStarted.Eagerly, 8) - val useSuperResolution: StateFlow = userPreferencesRepository.userPreferences - .map { it.useSuperResolution } + val useMFSR: StateFlow = userPreferencesRepository.userPreferences + .map { it.useMFSR } .stateIn(viewModelScope, SharingStarted.Eagerly, false) + val rawSuperResolutionScale: StateFlow = userPreferencesRepository.userPreferences + .map { it.rawSuperResolutionScale } + .stateIn(viewModelScope, SharingStarted.Eagerly, 1f) val useLivePhoto: StateFlow = userPreferencesRepository.userPreferences .map { it.useLivePhoto } .stateIn(viewModelScope, SharingStarted.Eagerly, false) @@ -315,7 +316,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch { handleMultipleExposureFrameCaptured(image, captureInfo) } - } else if (state.value.useMultiFrame) { + } else if (state.value.useMFNR || state.value.useMFSR) { val count = state.value.multiFrameCount PLog.d(TAG, "Burst frame received: ${stackingImages.size + 1}/$count") stackingImages.add(image) @@ -462,8 +463,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) // 应用保存的网格线设置 cameraController.setShowGrid(prefs.showGrid) - cameraController.setUseMultiFrame(prefs.useMultiFrame, prefs.multiFrameCount) - cameraController.setUseSuperResolution(prefs.useSuperResolution) + cameraController.setUseMFNR(prefs.useMFNR) + cameraController.setUseMFSR(prefs.useMFSR) + cameraController.setMultiFrameCount(prefs.multiFrameCount) cameraController.setUseLivePhoto(prefs.useLivePhoto) // 应用保存的虚拟光圈 @@ -645,8 +647,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) } if (enabled) { - cameraController.setUseMultiFrame(false, multiFrameCount.value) - cameraController.setUseSuperResolution(false) + cameraController.setUseMFNR(false) + cameraController.setUseMFSR(false) cameraController.setUseLivePhoto(false) cameraController.setUseRaw(false) } @@ -654,8 +656,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) viewModelScope.launch { userPreferencesRepository.saveUseMultipleExposure(enabled) if (enabled) { - userPreferencesRepository.saveUseMultiFrame(false) - userPreferencesRepository.saveUseSuperResolution(false) + userPreferencesRepository.setUseMFNR(false) + userPreferencesRepository.saveUseMFSR(false) userPreferencesRepository.saveUseLivePhoto(false) userPreferencesRepository.saveUseRaw(false) } @@ -712,7 +714,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) null, previewThumbnail, false, - false + 1.0f ) ?: run { composedBitmap.recycle() multipleExposureState = multipleExposureState.copy(isProcessing = false) @@ -1413,21 +1415,17 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) // ==================== 延时拍摄和网格线相关方法 ==================== /** - * 设置是否使用多帧合成 + * 设置是否使用多帧降噪 */ - fun setUseMultiFrame(enabled: Boolean) { + fun setUseMFNR(enabled: Boolean) { if (enabled) { setUseMultipleExposure(false) + setUseRaw(false) + cameraController.setUseMFSR(false) } - /*if (enabled) { - cameraController.setUseRaw(false) - viewModelScope.launch { - userPreferencesRepository.saveUseRaw(false) - } - }*/ - cameraController.setUseMultiFrame(enabled, multiFrameCount.value) + cameraController.setUseMFNR(enabled) viewModelScope.launch { - userPreferencesRepository.saveUseMultiFrame(enabled) + userPreferencesRepository.setUseMFNR(enabled) } reopenCamera() } @@ -1436,7 +1434,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) * 设置多帧合成帧数 */ fun setMultiFrameCount(count: Int) { - cameraController.setUseMultiFrame(state.value.useMultiFrame, count) + cameraController.setMultiFrameCount(count) viewModelScope.launch { userPreferencesRepository.saveMultiFrameCount(count) //reopenCamera() @@ -1454,17 +1452,25 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) /** * 设置是否使用超分辨率 */ - fun setUseSuperResolution(enabled: Boolean) { + fun setUseMFSR(enabled: Boolean) { if (enabled) { setUseMultipleExposure(false) + setUseRaw(true) + setUseMFNR(false) } - cameraController.setUseSuperResolution(enabled) + cameraController.setUseMFSR(enabled) viewModelScope.launch { - userPreferencesRepository.saveUseSuperResolution(enabled) + userPreferencesRepository.saveUseMFSR(enabled) } reopenCamera() } + fun setRawSuperResolutionScale(scale: Float) { + viewModelScope.launch { + userPreferencesRepository.saveRawSuperResolutionScale(scale) + } + } + /** * 设置是否启用 Live Photo */ @@ -1526,14 +1532,11 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) fun setUseRaw(useRaw: Boolean) { if (useRaw) { + setUseMFNR(false) setUseMultipleExposure(false) + } else { + setUseMFSR(false) } - /*if (useRaw) { - cameraController.setUseMultiFrame(false, multiFrameCount.value) - viewModelScope.launch { - userPreferencesRepository.saveUseMultiFrame(false) - } - }*/ cameraController.setUseRaw(useRaw) viewModelScope.launch { userPreferencesRepository.saveUseRaw(useRaw) @@ -2009,7 +2012,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) characteristics ?: return val photoId = - PhotoManager.preparePhoto(context, metadata, captureResult, previewThumbnail, useLivePhoto.value, false) + PhotoManager.preparePhoto(context, metadata, captureResult, previewThumbnail, useLivePhoto.value, 1.0f) if (photoId == null) { PLog.e(TAG, "Failed to save image") return @@ -2092,7 +2095,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) // 应用方向偏移 val rotation = (baseRotation + orientationOffset) % 360 - val useSuperRes = useSuperResolution.value + val useSuperRes = useMFSR.value + val rawSuperResScale = + if (useSuperRes && useRaw.value) rawSuperResolutionScale.value else 1.0f val aperture = if (state.value.isVirtualApertureEnabled) state.value.virtualAperture else null val defaultHdrEffectEnabled = defaultHdrEffectEnabled( @@ -2112,8 +2117,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) sharpening = sharpeningValue, noiseReduction = noiseReductionValue, chromaNoiseReduction = chromaNoiseReductionValue, - width = images[0].width * (if (useSuperRes) 2 else 1), - height = images[0].height * (if (useSuperRes) 2 else 1), + width = (images[0].width.toFloat() * rawSuperResScale).roundToInt(), + height = (images[0].height.toFloat() * rawSuperResScale).roundToInt(), ratio = aspectRatio, rotation = rotation, deviceModel = captureInfo.model, @@ -2151,7 +2156,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) characteristics ?: return val photoId = PhotoManager.preparePhoto( context, metadata, captureResult, previewThumbnail, - useLivePhoto.value, useSuperRes + useLivePhoto.value, rawSuperResScale ) if (photoId == null) { PLog.e(TAG, "Failed to save burst image") @@ -2176,6 +2181,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) chromaNoiseReductionValue, photoQualityValue, useSuperResolution = useSuperRes, + superResolutionScale = rawSuperResScale, useGpuAcceleration = useGpuAcceleration.value, exposureBias = state.value.exposureBias, droMode = droModeForProcessing @@ -2262,7 +2268,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) PhotoManager.preparePhoto( context, metadata, null, previewThumbnail, - false, false, photoId + false, 1.0f, photoId ) } diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 6105eb5d..83b4ac90 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -114,8 +114,8 @@ 在拍摄时显示水平仪,帮助保持画面水平 网格线显示 在拍摄时显示网格线,辅助构图 - 多帧合成 - 拍摄多张照片并合成,以获得更好的画质和更低的噪点。 + 多帧降噪 + 在 YUV 路径拍摄多张照片并融合,主要用于降低噪点。 多重曝光 通过多次快门逐步叠加一张作品,并提供幽灵预览辅助构图。 多曝 @@ -127,10 +127,12 @@ 已就绪,等待下一次曝光 多重曝光张数 最终合成所使用的曝光张数。默认 2 张,更接近经典双重曝光工作流。 - 多帧合成帧数 - 多帧合成所使用的帧数(帧数越多效果越好,但合成也越慢)。 - 超分辨率 - 使用 2x 多帧超分辨率以获得更多细节。(需要开启多帧合成) + 多帧降噪帧数 + YUV 多帧降噪使用的帧数(帧数越多降噪越明显,但处理也越慢)。 + 多帧超分 + 启用 RAW 多帧超分,仅作用于 RAW 多帧拍摄。 + 超分倍率 + 设置 RAW 多帧超分倍率,默认 1x。 RAW 处理引擎 选择用于处理 RAW 数据的引擎 原生 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2d0da85b..f179570c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -116,8 +116,8 @@ Show horizontal level indicator while shooting Grid Lines Show grid lines for composition - Multi-Frame Stacking - Capture multiple frames and stack them for better quality and less noise. + Multi-Frame Denoise + Capture multiple frames on the YUV path and merge them mainly for noise reduction. Multiple Exposure Build one image across multiple shutter presses with ghost preview guidance. ME @@ -129,10 +129,12 @@ Ready for next exposure Multiple Exposure Count How many exposures to combine for one final image. Default is 2 for a classic double exposure workflow. - Multi-frame Count - Number of frames for multi-frame stacking (more frames = better quality but slower). - Super Resolution - Use 2x multi-frame super resolution for more detail. (Requires Multi-Frame Stacking) + Multi-Frame Denoise Count + Number of frames used for YUV multi-frame denoise (more frames reduce noise more, but take longer). + Multi-Frame Super Resolution + Enable RAW multi-frame super resolution. This toggle only affects RAW multi-frame capture. + Super Resolution Scale + Set the RAW multi-frame super resolution scale. Default is 1x. RAW Processing Engine Choose the engine for RAW data processing Native