fix: mfsr

This commit is contained in:
Hinnka committed 2026-03-22 17:03:11 +08:00
1 parent d332f4320c
commit 0351dcd57a
27 files changed
+2386 -1277

No files matched your search

+2 -2
View File
@@ -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
+192 -1
View File
@@ -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<jsize>(env->GetArrayLength(src),
static_cast<jsize>(count));
if (length <= 0) {
return;
}
jfloat *elements = env->GetFloatArrayElements(src, nullptr);
if (!elements) {
return;
}
std::memcpy(dst, elements, static_cast<size_t>(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<int>(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<unsigned char *>(
env->GetDirectBufferAddress(fusedBayerBuffer));
auto *outputData =
static_cast<unsigned char *>(env->GetDirectBufferAddress(outputBuffer));
if (!fusedBayerData || !outputData) {
LOGE("demosaicStackedRawWithLibRawNative: failed to get buffer address");
return JNI_FALSE;
}
const size_t inputBytes =
static_cast<size_t>(width) * static_cast<size_t>(height) *
sizeof(uint16_t);
const size_t outputBytes =
static_cast<size_t>(width) * static_cast<size_t>(height) * 3 *
sizeof(uint16_t);
const jlong inputCapacity = env->GetDirectBufferCapacity(fusedBayerBuffer);
const jlong outputCapacity = env->GetDirectBufferCapacity(outputBuffer);
if (inputCapacity < static_cast<jlong>(inputBytes) ||
outputCapacity < static_cast<jlong>(outputBytes)) {
LOGE("demosaicStackedRawWithLibRawNative: buffer too small in=%ld/%ld out=%ld/%ld",
static_cast<long>(inputCapacity), static_cast<long>(inputBytes),
static_cast<long>(outputCapacity), static_cast<long>(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<unsigned>(inputBytes),
static_cast<ushort>(width), static_cast<ushort>(height), 0, 0, 0, 0, 0,
libRawPattern, 0, 0, static_cast<unsigned>(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);
@@ -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;
}
@@ -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;
@@ -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);
+100 -31
View File
@@ -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));
}
+151 -64
View File
@@ -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));
}
-117
View File
@@ -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;
}
@@ -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));
}
@@ -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));
}
File diff suppressed because it is too large. Load diff
+21 -20
View File
@@ -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<VkBuffer> accumBuffers;
std::vector<VkDeviceMemory> accumMemories;
VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> accumSets;
VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
VkPipeline accumulatePipeline = VK_NULL_HANDLE;
// 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<VkDescriptorSet> 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<GrayImage> 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
@@ -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<CaptureRequest>()
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
@@ -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 动画)
@@ -61,11 +61,12 @@ data class UserPreferences(
val frameOrder: List<String> = emptyList(), // 边框排序(ID列表)
val categoryOrder: List<String> = 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)
}
}
/**
* 保存照片质量
*/
@@ -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<File> {
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)
@@ -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<SafeImage>,
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
@@ -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)
@@ -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));
@@ -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]) =====
@@ -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)
}
)
@@ -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))
}
}
@@ -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),
@@ -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
@@ -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<Float> = userPreferencesRepository.userPreferences.map { it.defaultFocalLength }
val userPreferences: StateFlow<com.hinnka.mycamera.data.UserPreferences> = userPreferencesRepository.userPreferences
.stateIn(viewModelScope, SharingStarted.Eagerly, com.hinnka.mycamera.data.UserPreferences())
val useMultiFrame: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useMultiFrame }
val useMFNR: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useMFNR }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
val useMultipleExposure: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useMultipleExposure }
@@ -177,9 +175,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val multiFrameCount: StateFlow<Int> = userPreferencesRepository.userPreferences
.map { it.multiFrameCount }
.stateIn(viewModelScope, SharingStarted.Eagerly, 8)
val useSuperResolution: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useSuperResolution }
val useMFSR: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.useMFSR }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
val rawSuperResolutionScale: StateFlow<Float> = userPreferencesRepository.userPreferences
.map { it.rawSuperResolutionScale }
.stateIn(viewModelScope, SharingStarted.Eagerly, 1f)
val useLivePhoto: StateFlow<Boolean> = 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
)
}
+8 -6
View File
@@ -114,8 +114,8 @@
<string name="settings_level_description">在拍摄时显示水平仪,帮助保持画面水平</string>
<string name="settings_grid_lines">网格线显示</string>
<string name="settings_grid_description">在拍摄时显示网格线,辅助构图</string>
<string name="settings_use_multi_frame">多帧合成</string>
<string name="settings_use_multi_frame_description">拍摄多张照片并合成,以获得更好的画质和更低的噪点。</string>
<string name="settings_use_multi_frame">多帧降噪</string>
<string name="settings_use_multi_frame_description">在 YUV 路径拍摄多张照片并融合,主要用于降低噪点。</string>
<string name="settings_use_multiple_exposure">多重曝光</string>
<string name="settings_use_multiple_exposure_description">通过多次快门逐步叠加一张作品,并提供幽灵预览辅助构图。</string>
<string name="multiple_exposure_short">多曝</string>
@@ -127,10 +127,12 @@
<string name="multiple_exposure_ready">已就绪,等待下一次曝光</string>
<string name="settings_multiple_exposure_count">多重曝光张数</string>
<string name="settings_multiple_exposure_count_description">最终合成所使用的曝光张数。默认 2 张,更接近经典双重曝光工作流。</string>
<string name="settings_multi_frame_count">多帧合成帧数</string>
<string name="settings_multi_frame_count_description">多帧合成所使用的帧数(帧数越多效果越好,但合成也越慢)。</string>
<string name="settings_use_super_resolution">超分辨率</string>
<string name="settings_use_super_resolution_description">使用 2x 多帧超分辨率以获得更多细节。(需要开启多帧合成)</string>
<string name="settings_multi_frame_count">多帧降噪帧数</string>
<string name="settings_multi_frame_count_description">YUV 多帧降噪使用的帧数(帧数越多降噪越明显,但处理也越慢)。</string>
<string name="settings_use_super_resolution">多帧超分</string>
<string name="settings_use_super_resolution_description">启用 RAW 多帧超分,仅作用于 RAW 多帧拍摄。</string>
<string name="settings_super_resolution_scale">超分倍率</string>
<string name="settings_super_resolution_scale_description">设置 RAW 多帧超分倍率,默认 1x。</string>
<string name="settings_raw_engine">RAW 处理引擎</string>
<string name="settings_raw_engine_description">选择用于处理 RAW 数据的引擎</string>
<string name="settings_raw_engine_native">原生</string>
+8 -6
View File
@@ -116,8 +116,8 @@
<string name="settings_level_description">Show horizontal level indicator while shooting</string>
<string name="settings_grid_lines">Grid Lines</string>
<string name="settings_grid_description">Show grid lines for composition</string>
<string name="settings_use_multi_frame">Multi-Frame Stacking</string>
<string name="settings_use_multi_frame_description">Capture multiple frames and stack them for better quality and less noise.</string>
<string name="settings_use_multi_frame">Multi-Frame Denoise</string>
<string name="settings_use_multi_frame_description">Capture multiple frames on the YUV path and merge them mainly for noise reduction.</string>
<string name="settings_use_multiple_exposure">Multiple Exposure</string>
<string name="settings_use_multiple_exposure_description">Build one image across multiple shutter presses with ghost preview guidance.</string>
<string name="multiple_exposure_short">ME</string>
@@ -129,10 +129,12 @@
<string name="multiple_exposure_ready">Ready for next exposure</string>
<string name="settings_multiple_exposure_count">Multiple Exposure Count</string>
<string name="settings_multiple_exposure_count_description">How many exposures to combine for one final image. Default is 2 for a classic double exposure workflow.</string>
<string name="settings_multi_frame_count">Multi-frame Count</string>
<string name="settings_multi_frame_count_description">Number of frames for multi-frame stacking (more frames = better quality but slower).</string>
<string name="settings_use_super_resolution">Super Resolution</string>
<string name="settings_use_super_resolution_description">Use 2x multi-frame super resolution for more detail. (Requires Multi-Frame Stacking)</string>
<string name="settings_multi_frame_count">Multi-Frame Denoise Count</string>
<string name="settings_multi_frame_count_description">Number of frames used for YUV multi-frame denoise (more frames reduce noise more, but take longer).</string>
<string name="settings_use_super_resolution">Multi-Frame Super Resolution</string>
<string name="settings_use_super_resolution_description">Enable RAW multi-frame super resolution. This toggle only affects RAW multi-frame capture.</string>
<string name="settings_super_resolution_scale">Super Resolution Scale</string>
<string name="settings_super_resolution_scale_description">Set the RAW multi-frame super resolution scale. Default is 1x.</string>
<string name="settings_raw_engine">RAW Processing Engine</string>
<string name="settings_raw_engine_description">Choose the engine for RAW data processing</string>
<string name="settings_raw_engine_native">Native</string>