fix: image close

This commit is contained in:
Hinnka committed 2026-02-03 23:32:28 +08:00
1 parent 989229386a
commit af9cff7313
13 files changed
+805 -730

No files matched your search

+1
View File
@@ -102,6 +102,7 @@ dependencies {
// DataStore for user preferences
implementation("androidx.datastore:datastore-preferences:1.0.0")
implementation(libs.androidx.animation.core)
// Bugly for china flavor
"chinaImplementation"("com.tencent.bugly:crashreport:latest.release")
+62
View File
@@ -65,6 +65,39 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_addToStackNative(
}
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_stageFrameNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject yBuffer,
jobject uBuffer, jobject vBuffer, jint yRowStride, jint uvRowStride,
jint uvPixelStride, jint format) {
auto *stacker = reinterpret_cast<ImageStacker *>(stackerPtr);
if (!stacker)
return;
auto *yData = static_cast<uint8_t *>(env->GetDirectBufferAddress(yBuffer));
auto *uData = static_cast<uint8_t *>(env->GetDirectBufferAddress(uBuffer));
auto *vData = static_cast<uint8_t *>(env->GetDirectBufferAddress(vBuffer));
if (yData && uData && vData) {
stacker->stageFrame(yData, uData, vData, yRowStride, uvRowStride,
uvPixelStride, format);
}
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processFrameNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jint index) {
auto *stacker = reinterpret_cast<ImageStacker *>(stackerPtr);
if (stacker)
stacker->processFrame(index);
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_clearStagedFramesNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
auto *stacker = reinterpret_cast<ImageStacker *>(stackerPtr);
if (stacker)
stacker->clearStagedFrames();
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processStackNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject outBitmap,
@@ -142,6 +175,35 @@ Java_com_hinnka_mycamera_processor_MultiFrameStacker_addToRawStackNative(
}
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_stageRawFrameNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject rawData,
jint rowStride, jint cfaPattern) {
auto *stacker = reinterpret_cast<RawStacker *>(stackerPtr);
if (!stacker)
return;
auto *data = static_cast<uint16_t *>(env->GetDirectBufferAddress(rawData));
if (data) {
stacker->stageFrame(data, rowStride, cfaPattern);
}
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processRawFrameNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jint index) {
auto *stacker = reinterpret_cast<RawStacker *>(stackerPtr);
if (stacker)
stacker->processFrame(index);
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_clearStagedRawFramesNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
auto *stacker = reinterpret_cast<RawStacker *>(stackerPtr);
if (stacker)
stacker->clearStagedFrames();
}
JNIEXPORT void JNICALL
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processRawStackWithBufferNative(
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject outputBuffer) {
+115 -187
View File
@@ -445,65 +445,88 @@ inline int calculateWeight(int diff, float variance) {
void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
const uint8_t *vData, int yRowStride,
int uvRowStride, int uvPixelStride, int format) {
stageFrame(yData, uData, vData, yRowStride, uvRowStride, uvPixelStride,
format);
processFrame((int)stagedFrames.size() - 1);
}
void ImageStacker::stageFrame(const uint8_t *yData, const uint8_t *uData,
const uint8_t *vData, int yRowStride,
int uvRowStride, int uvPixelStride, int format) {
frameCount++;
if (!yData || !uData || !vData) {
LOGE("ImageStacker::addFrame: Received NULL buffer(s)");
LOGE("ImageStacker::stageFrame: Received NULL buffer(s)");
return;
}
StagedYuvFrame frame;
frame.format = format;
bool isP010 = (format == 0x36);
int yPixelStride = isP010 ? 2 : 1;
// Convert current frame to internal 16-bit and 8-bit for alignment
std::vector<uint16_t> currentY(width * height);
GrayImage image8bit;
image8bit.width = width;
image8bit.height = height;
image8bit.data.resize(width * height);
frame.y.resize(width * height);
frame.y8.width = width;
frame.y8.height = height;
frame.y8.data.resize(width * height);
#pragma omp parallel for num_threads(4)
for (int r = 0; r < height; ++r) {
const uint8_t *yRowPtr = yData + r * yRowStride;
for (int c = 0; c < width; ++c) {
uint16_t val;
if (isP010) {
val = readValue<uint16_t>(yData + r * yRowStride + c * yPixelStride,
false);
val = readValue<uint16_t>(yRowPtr + c * yPixelStride, false);
} else {
val = static_cast<uint16_t>(yData[r * yRowStride + c]) << 8;
val = static_cast<uint16_t>(yRowPtr[c]) << 8;
}
currentY[r * width + c] = val;
image8bit.data[r * width + c] = static_cast<uint8_t>(val >> 8);
frame.y[r * width + c] = val;
frame.y8.data[r * width + c] = static_cast<uint8_t>(val >> 8);
}
}
if (isFirstFrame) {
referenceY = currentY;
// Store U, V for reference as well
int uvRefWidth = width / 2;
int uvRefHeight = height / 2;
// Convert UV frames to internal 16-bit
int uvW = width / 2;
int uvH = height / 2;
frame.u.resize(uvW * uvH);
frame.v.resize(uvW * uvH);
// Store reference UV same as before
for (int r = 0; r < uvRefHeight; ++r) {
for (int c = 0; c < uvRefWidth; ++c) {
if (isP010) {
referenceU[r * uvRefWidth + c] = readValue<uint16_t>(
uData + r * uvRowStride + c * uvPixelStride, false);
referenceV[r * uvRefWidth + c] = readValue<uint16_t>(
vData + r * uvRowStride + c * uvPixelStride, false);
} else {
referenceU[r * uvRefWidth + c] =
static_cast<uint16_t>(uData[r * uvRowStride + c * uvPixelStride])
<< 8;
referenceV[r * uvRefWidth + c] =
static_cast<uint16_t>(vData[r * uvRowStride + c * uvPixelStride])
<< 8;
}
#pragma omp parallel for num_threads(4)
for (int r = 0; r < uvH; ++r) {
const uint8_t *uRowPtr = uData + r * uvRowStride;
const uint8_t *vRowPtr = vData + r * uvRowStride;
for (int c = 0; c < uvW; ++c) {
uint16_t uVal, vVal;
if (isP010) {
uVal = readValue<uint16_t>(uRowPtr + c * uvPixelStride, false);
vVal = readValue<uint16_t>(vRowPtr + c * uvPixelStride, false);
} else {
uVal = static_cast<uint16_t>(uRowPtr[c * uvPixelStride]) << 8;
vVal = static_cast<uint16_t>(vRowPtr[c * uvPixelStride]) << 8;
}
frame.u[r * uvW + c] = uVal;
frame.v[r * uvW + c] = vVal;
}
}
stagedFrames.push_back(std::move(frame));
}
referencePyramid = buildPyramid(image8bit.data.data(), width, height, 4);
void ImageStacker::processFrame(int index) {
if (index < 0 || index >= (int)stagedFrames.size()) {
LOGE("ImageStacker::processFrame: Invalid index %d", index);
return;
}
const auto &staged = stagedFrames[index];
bool isP010 = (staged.format == 0x36);
if (isFirstFrame) {
referenceY = staged.y;
referenceU = staged.u;
referenceV = staged.v;
referencePyramid = buildPyramid(staged.y8.data.data(), width, height, 4);
// Initialize accumulators by upscaling the first frame
int scaledW = width * scale;
@@ -512,14 +535,13 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
#pragma omp parallel for collapse(2) num_threads(4)
for (int y = 0; y < scaledH; ++y) {
for (int x = 0; x < scaledW; ++x) {
// Map scaled coordinates back to input coordinates
float srcX = (float)x / scale;
float srcY = (float)y / scale;
// Initial frame: strict bicubic upscale
uint16_t val =
(uint16_t)sampleBicubic(currentY, width, height, srcX, srcY);
(uint16_t)sampleBicubic(staged.y, width, height, srcX, srcY);
accumY[y * scaledW + x] = (int32_t)val * 256;
weightY[y * scaledW + x] = 256;
}
@@ -528,24 +550,18 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
// UV
int scaledUVWidth = scaledW / 2;
int scaledUVHeight = scaledH / 2;
int uvRefWidth = width / 2;
int uvRefHeight = height / 2;
#pragma omp parallel for collapse(2) num_threads(4)
for (int y = 0; y < scaledUVHeight; ++y) {
for (int x = 0; x < scaledUVWidth; ++x) {
// Need to sample original UV.
// Original UV size is (width/2) x (height/2).
// Current scaled UV index (x, y) corresponds to (x/scale, y/scale) in
// original UV grid.
float srcX = (float)x / scale;
float srcY = (float)y / scale;
// We need a helper to sample UV from raw pointer again, or use
// referenceU/V since it's first frame Actually, referenceU/V are
// already populated above. using basic bilinear/bicubic on them.
uint16_t uVal = (uint16_t)sampleBicubic(referenceU, uvRefWidth,
uint16_t uVal = (uint16_t)sampleBicubic(staged.u, uvRefWidth,
uvRefHeight, srcX, srcY);
uint16_t vVal = (uint16_t)sampleBicubic(referenceV, uvRefWidth,
uint16_t vVal = (uint16_t)sampleBicubic(staged.v, uvRefWidth,
uvRefHeight, srcX, srcY);
accumU[y * scaledUVWidth + x] = (int32_t)uVal * 256;
@@ -562,7 +578,7 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
// Align current frame against reference (Always at 1x scale)
std::vector<GrayImage> currentPyramid =
buildPyramid(image8bit.data.data(), width, height, 4);
buildPyramid(staged.y8.data.data(), width, height, 4);
TileAlignment alignment =
computeTileAlignment(referencePyramid, currentPyramid, 64);
@@ -574,33 +590,19 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
#pragma omp parallel for collapse(2) num_threads(4)
for (int y = 0; y < scaledH; ++y) {
for (int x = 0; x < scaledW; ++x) {
// 1. Map output pixel to input reference space
// (x, y) in scaled grid -> (x/s, y/s) in 1x reference grid
float refX = (float)x / scale;
float refY = (float)y / scale;
// 2. Get alignment offset at this location (from 1x grid)
Point offset = alignment.getOffset((int)refX, (int)refY);
// 3. Apply offset to find sampling point in CURRENT frame
float tx = refX + offset.x;
float ty = refY + offset.y;
int destIdx = y * scaledW + x;
if (tx >= 0 && tx < (float)width && ty >= 0 && ty < (float)height) {
// Sample from current frame (1x) at aligned position
uint16_t targetVal =
(uint16_t)sampleBicubic(currentY, width, height, tx, ty);
// Look up accumulated value for comparison (De-ghosting)
// We compare against the current accumulated average
(uint16_t)sampleBicubic(staged.y, width, height, tx, ty);
uint16_t refVal = (uint16_t)(accumY[destIdx] / weightY[destIdx]);
// Compute local variance on REFERENCE frame (1x)
// We use nearest neighbor or bilinear mapping to finding variance at
// refX, refY
float variance = computeLocalVariance(referenceY, width, height,
(int)refX, (int)refY);
@@ -610,13 +612,6 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
accumY[destIdx] += (int32_t)targetVal * weight;
weightY[destIdx] += weight;
// Progressive reference update (recursive filter)
// Update 1x reference mainly using values that map to integer
// coordinates? Or just don't update reference for now in SuperRes mode
// to simplify. Actually, updating reference is good for long bursts.
// But referenceY is 1x. We only have 2x data here.
// Simple strategy: Update reference only if we are at a "center" pixel
// (modulo scale == 0)
if (x % scale == 0 && y % scale == 0 && weight > 128) {
int refIdx = (y / scale) * width + (x / scale);
referenceY[refIdx] =
@@ -645,61 +640,27 @@ void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
#pragma omp parallel for collapse(2) num_threads(4)
for (int y = 0; y < scaledUVHeight; ++y) {
for (int x = 0; x < scaledUVWidth; ++x) {
// Map to 1x UV grid
float refUVX = (float)x / scale;
float refUVY = (float)y / scale;
// Get offset. Note: alignment offset matches Y plane (full res 1x).
// UV is half res 1x. So need to scale coordinates to Y plane for offset
// lookup. Y-coord = refUVX * 2.
Point offset = alignment.getOffset(refUVX * 2, refUVY * 2);
// Target in current frame UV
float tx = refUVX + offset.x / 2.0f;
float ty = refUVY + offset.y / 2.0f;
int destIdx = y * scaledUVWidth + x;
if (tx >= 0 && tx < (float)uvRefWidth && ty >= 0 &&
ty < (float)uvRefHeight) {
auto sampleRawUV = [&](const uint8_t *data, float sx, float sy) {
int x0 = (int)std::floor(sx);
int y0 = (int)std::floor(sy);
int x1 = std::min(x0 + 1, uvRefWidth - 1);
int y1 = std::min(y0 + 1, uvRefHeight - 1);
float dx = sx - (float)x0;
float dy = sy - (float)y0;
auto getRawVal = [&](int ix, int iy) {
if (isP010) {
return (float)readValue<uint16_t>(
data + iy * uvRowStride + ix * uvPixelStride, false);
} else {
return (float)data[iy * uvRowStride + ix * uvPixelStride] *
256.0f;
}
};
float v00 = getRawVal(x0, y0);
float v10 = getRawVal(x1, y0);
float v01 = getRawVal(x0, y1);
float v11 = getRawVal(x1, y1);
return (1.0f - dx) * (1.0f - dy) * v00 + dx * (1.0f - dy) * v10 +
(1.0f - dx) * dy * v01 + dx * dy * v11;
};
uint16_t targetU = (uint16_t)sampleRawUV(uData, tx, ty);
uint16_t targetV = (uint16_t)sampleRawUV(vData, tx, ty);
if (tx >= 2.0f && tx < (float)uvRefWidth - 3.0f && ty >= 2.0f &&
ty < (float)uvRefHeight - 3.0f) {
// Use Bicubic for UV as well since we now have Dense 16-bit staging
uint16_t targetU =
(uint16_t)sampleBicubic(staged.u, uvRefWidth, uvRefHeight, tx, ty);
uint16_t targetV =
(uint16_t)sampleBicubic(staged.v, uvRefWidth, uvRefHeight, tx, ty);
uint16_t refU = (uint16_t)(accumU[destIdx] / weightU[destIdx]);
uint16_t refV = (uint16_t)(accumV[destIdx] / weightV[destIdx]);
int diffU = std::abs((int)targetU - (int)refU);
int diffV = std::abs((int)targetV - (int)refV);
int weight = calculateWeight(std::max(diffU, diffV),
40000.0f); // Higher base for UV
int weight = calculateWeight(std::max(diffU, diffV), 40000.0f);
accumU[destIdx] += (int32_t)targetU * weight;
weightU[destIdx] += weight;
@@ -938,55 +899,36 @@ void smoothImage(GrayImage &img) {
void RawStacker::addFrame(const uint16_t *rawData, int rowStride,
int cfaPattern) {
stageFrame(rawData, rowStride, cfaPattern);
processFrame((int)stagedFrames.size() - 1);
}
void RawStacker::stageFrame(const uint16_t *rawData, int rowStride,
int cfaPattern) {
frameCount++;
const uint8_t *rawBytes = (const uint8_t *)rawData;
// 1. 自动曝光计算
// (每帧独立计算或只算第一帧,这里为了安全每帧检查,第一帧锁定)
if (isFirstFrame) {
byteScale = computeRawScaleSafe(rawBytes, width, height, rowStride);
// 限制缩放倍数,防止纯黑图片导致数值爆炸
if (byteScale > 100.0f)
byteScale = 100.0f;
LOGD("RawStacker: Scale factor: %f", byteScale);
}
// 2. 准备 Proxy 和 Planes
StagedRawFrame frame;
frame.cfaPattern = cfaPattern;
int proxyW = width / 2;
int proxyH = height / 2;
GrayImage proxy;
proxy.width = proxyW;
proxy.height = proxyH;
proxy.data.resize(proxyW * proxyH);
frame.proxy.width = proxyW;
frame.proxy.height = proxyH;
frame.proxy.data.resize(proxyW * proxyH);
// 初始化 Planes
std::vector<uint16_t> planes[4];
for (int i = 0; i < 4; ++i)
planes[i].resize(proxyW * proxyH);
frame.planes[i].resize(proxyW * proxyH);
// CFA 偏移量逻辑 (保持之前的修正)
int g1_dx = 0, g1_dy = 0;
int g2_dx = 0, g2_dy = 0;
// RGGB(0), BGGR(3) -> G at (1,0), (0,1) relative to 2x2 block
// GRBG(1), GBRG(2) -> G at (0,0), (1,1) relative to 2x2 block
if (cfaPattern == 1 || cfaPattern == 2) {
g1_dx = 0;
g1_dy = 0;
g2_dx = 1;
g2_dy = 1;
} else {
g1_dx = 1;
g1_dy = 0;
g2_dx = 0;
g2_dy = 1;
}
// 3. 提取数据 (使用 Byte Stride 指针运算)
#pragma omp parallel for num_threads(4)
for (int y = 0; y < proxyH; ++y) {
// 预先计算当前行的指针,减少循环内乘法
const uint8_t *row0 = rawBytes + (y * 2) * rowStride;
const uint8_t *row1 = rawBytes + (y * 2 + 1) * rowStride;
const uint16_t *pRow0 = (const uint16_t *)row0;
@@ -994,65 +936,67 @@ void RawStacker::addFrame(const uint16_t *rawData, int rowStride,
for (int x = 0; x < proxyW; ++x) {
int ox = x * 2;
// 读取 2x2 块
uint16_t p00 = pRow0[ox];
uint16_t p10 = pRow0[ox + 1];
uint16_t p01 = pRow1[ox];
uint16_t p11 = pRow1[ox + 1];
// 提取绿色通道用于 Proxy
// 根据 CFA 模式选择哪两个像素是绿色
uint16_t g1, g2;
// 简化逻辑:利用预读的像素值,避免重复指针计算
if (cfaPattern == 1 || cfaPattern == 2) {
// G at (0,0) and (1,1)
g1 = p00;
g2 = p11;
} else {
// G at (1,0) and (0,1)
g1 = p10;
g2 = p01;
}
// 生成对齐用 Proxy 像素 (均值 + 缩放)
float avgG = (float)(g1 + g2) * 0.5f;
proxy.data[y * proxyW + x] =
frame.proxy.data[y * proxyW + x] =
(uint8_t)std::max(0.0f, std::min(255.0f, avgG * byteScale));
// 分发到 Planes
planes[getPlaneIndex(ox, 0, cfaPattern)][y * proxyW + x] = p00;
planes[getPlaneIndex(ox + 1, 0, cfaPattern)][y * proxyW + x] = p10;
planes[getPlaneIndex(ox, 1, cfaPattern)][y * proxyW + x] = p01;
planes[getPlaneIndex(ox + 1, 1, cfaPattern)][y * proxyW + x] = p11;
frame.planes[getPlaneIndex(ox, 0, cfaPattern)][y * proxyW + x] = p00;
frame.planes[getPlaneIndex(ox + 1, 0, cfaPattern)][y * proxyW + x] = p10;
frame.planes[getPlaneIndex(ox, 1, cfaPattern)][y * proxyW + x] = p01;
frame.planes[getPlaneIndex(ox + 1, 1, cfaPattern)][y * proxyW + x] = p11;
}
}
// --- 关键修正 2: Proxy 降噪 ---
// RAW 的单像素噪声极强,会导致 SAD 误判。对齐前进行轻微模糊是必须的。
if (!isFirstFrame) {
smoothImage(proxy);
smoothImage(frame.proxy);
} else {
smoothImage(frame.proxy);
}
stagedFrames.push_back(std::move(frame));
}
void RawStacker::processFrame(int index) {
if (index < 0 || index >= (int)stagedFrames.size()) {
LOGE("RawStacker::processFrame: Invalid index %d", index);
return;
}
const auto &staged = stagedFrames[index];
int proxyW = width / 2;
int proxyH = height / 2;
if (isFirstFrame) {
mCfaPattern = cfaPattern;
// 第一帧也要平滑,作为干净的参考基准
smoothImage(proxy);
referencePyramid = buildPyramid(proxy.data.data(), proxyW, proxyH, 4);
mCfaPattern = staged.cfaPattern;
referencePyramid =
buildPyramid(staged.proxy.data.data(), proxyW, proxyH, 4);
int scaledW = proxyW * scale;
int scaledH = proxyH * scale;
for (int i = 0; i < 4; ++i) {
referencePlanes[i] = planes[i];
referencePlanes[i] = staged.planes[i];
#pragma omp parallel for collapse(2) num_threads(4)
for (int sy = 0; sy < scaledH; sy++) {
for (int sx = 0; sx < scaledW; sx++) {
float refX = (float)sx / scale;
float refY = (float)sy / scale;
float val = sampleBicubicPlane(planes[i], proxyW, proxyH, refX, refY);
float val =
sampleBicubicPlane(staged.planes[i], proxyW, proxyH, refX, refY);
int destIdx = sy * scaledW + sx;
accum[i][destIdx] = (int32_t)val * 256;
weight[i][destIdx] = 256;
@@ -1063,25 +1007,20 @@ void RawStacker::addFrame(const uint16_t *rawData, int rowStride,
return;
}
// 4. 对齐 (Alignment)
std::vector<GrayImage> currentPyramid =
buildPyramid(proxy.data.data(), proxyW, proxyH, 4);
// 搜索范围:48 (对应 RAW 像素 96)
buildPyramid(staged.proxy.data.data(), proxyW, proxyH, 4);
TileAlignment alignment =
computeTileAlignment(referencePyramid, currentPyramid, 48);
// 5. 堆栈融合 (Accumulate)
int scaledW = proxyW * scale;
int scaledH = proxyH * scale;
for (int i = 0; i < 4; ++i) {
const auto &srcPlane = planes[i];
const auto &srcPlane = staged.planes[i];
#pragma omp parallel for collapse(2) num_threads(4)
for (int y = 0; y < scaledH; ++y) {
for (int x = 0; x < scaledW; ++x) {
float refX = (float)x / scale;
float refY = (float)y / scale;
@@ -1091,27 +1030,17 @@ void RawStacker::addFrame(const uint16_t *rawData, int rowStride,
int destIdx = y * scaledW + x;
// 边界保护
if (tx >= 2.0f && tx < (float)proxyW - 3.0f && ty >= 2.0f &&
ty < (float)proxyH - 3.0f) {
// --- 核心升级 1: 调用 Bicubic 采样 ---
float val = sampleBicubicPlane(srcPlane, proxyW, proxyH, tx, ty);
int32_t sampleVal = (int32_t)val;
// De-ghosting with adaptive threshold based on variance
int32_t currentAvg = accum[i][destIdx] / weight[i][destIdx];
int diff = std::abs(sampleVal - currentAvg);
// Compute local variance on reference plane to detect high frequency
// regions
float variance = computeLocalVariance(referencePlanes[i], proxyW,
proxyH, (int)refX, (int)refY);
float noiseModel = 32.0f + std::sqrt((float)currentAvg) * 2.5f;
float thresholdLow = noiseModel * 1.5f;
// Relax thresholdHigh in high variance areas to preserve details
float factorHigh = 4.0f + std::min(8.0f, variance / 5000.0f);
float thresholdHigh = noiseModel * factorHigh;
@@ -1121,8 +1050,7 @@ void RawStacker::addFrame(const uint16_t *rawData, int rowStride,
} else if (diff > thresholdLow) {
float t =
((float)diff - thresholdLow) / (thresholdHigh - thresholdLow);
float factor =
1.0f - (t * t * (3.0f - 2.0f * t)); // smoothstep flip
float factor = 1.0f - (t * t * (3.0f - 2.0f * t));
w = (int)(256.0f * factor);
}
+39 -5
View File
@@ -5,12 +5,26 @@
#include <cstdint>
#include <vector>
// Represents a 2D point or offset
// Represents a 2D point or offset
struct Point {
float x;
float y;
};
// Represents a grayscale image buffer for processing
struct GrayImage {
std::vector<uint8_t> data;
int width;
int height;
};
struct StagedYuvFrame {
std::vector<uint16_t> y, u, v;
GrayImage y8;
int format;
};
// Represents a 2D vector field for tile-based alignment
struct TileAlignment {
int tileWidth;
@@ -57,11 +71,7 @@ struct TileAlignment {
};
// Represents a grayscale image buffer for processing
struct GrayImage {
std::vector<uint8_t> data;
int width;
int height;
};
// (Already moved above Point)
// Build a Gaussian pyramid (downsampled images)
std::vector<GrayImage> buildPyramid(const uint8_t *src, int width, int height,
@@ -82,6 +92,13 @@ public:
const uint8_t *vData, int yRowStride, int uvRowStride,
int uvPixelStride, int format);
// New methods for faster image closing
void stageFrame(const uint8_t *yData, const uint8_t *uData,
const uint8_t *vData, int yRowStride, int uvRowStride,
int uvPixelStride, int format);
void processFrame(int index);
void clearStagedFrames() { stagedFrames.clear(); }
// Write the result to an ARGB8888 bitmap buffer with rotation and cropping
void writeResult(uint32_t *outBitmap, int outWidth, int outHeight,
int rotation, int targetWR, int targetHR,
@@ -98,6 +115,9 @@ private:
bool isFirstFrame;
int frameCount = 0;
// Staged frame data (for fast closing of image)
std::vector<StagedYuvFrame> stagedFrames;
// Reference frame data for de-ghosting and alignment
// Reference is always kept at original resolution (scale=1)
std::vector<GrayImage> referencePyramid;
@@ -117,6 +137,12 @@ private:
std::vector<int32_t> weightV;
};
struct StagedRawFrame {
std::vector<uint16_t> planes[4];
GrayImage proxy;
int cfaPattern;
};
class RawStacker {
public:
RawStacker(int width, int height, bool enableSuperRes = false);
@@ -127,6 +153,11 @@ public:
// cfaPattern: 0=RGGB, 1=GRBG, 2=GBRG, 3=BGGR
void addFrame(const uint16_t *rawData, int rowStride, int cfaPattern);
// New methods for faster image closing
void stageFrame(const uint16_t *rawData, int rowStride, int cfaPattern);
void processFrame(int index);
void clearStagedFrames() { stagedFrames.clear(); }
// Process and return the stacked raw image
// Returns a vector containing the stacked 16-bit Bayer data
std::vector<uint16_t> process();
@@ -141,6 +172,9 @@ private:
int frameCount = 0;
float byteScale = 1.0f;
// Staged data
std::vector<StagedRawFrame> stagedFrames;
// Reference pyramid for alignment (built from a downscaled grayscale version
// of the raw data)
std::vector<GrayImage> referencePyramid;
@@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.hinnka.mycamera.livephoto.LivePhotoRecorder
import com.hinnka.mycamera.model.SafeImage
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
@@ -115,7 +116,7 @@ class Camera2Controller(private val context: Context) {
// 缓存 CaptureResult 和 Image 用于配对 (timestamp -> Data)
private val pendingResults = ConcurrentHashMap<Long, TotalCaptureResult>()
private val pendingImages = ConcurrentHashMap<Long, Image>()
private val pendingImages = ConcurrentHashMap<Long, SafeImage>()
private val pendingCloseReaders = mutableListOf<ImageReader>()
private val openImagesCount = AtomicInteger(0)
@@ -124,13 +125,13 @@ class Camera2Controller(private val context: Context) {
private var lastCaptureResult: TotalCaptureResult? = null
// 图片拍摄回调(携带 CaptureInfo, CameraCharacteristics 和 CaptureResult 用于 RAW 处理)
var onImageCaptured: ((Image, CaptureInfo, CameraCharacteristics?, CaptureResult?) -> Unit)? = null
var onImageCaptured: ((SafeImage, CaptureInfo, CameraCharacteristics?, CaptureResult?) -> Unit)? = null
private fun trackImage(image: Image?): Image? {
private fun trackImage(image: Image?): SafeImage? {
if (image != null) {
openImagesCount.getAndIncrement()
}
return image
return image?.let { SafeImage(it, this) }
}
// 快门音效播放回调
@@ -144,9 +145,9 @@ class Camera2Controller(private val context: Context) {
// canRetry: 是否可以重试打开相机
var onCameraError: ((errorCode: Int, message: String, canRetry: Boolean) -> Unit)? = null
fun releaseImage(image: Image) {
image.close()
fun onImageRelease() {
if (openImagesCount.decrementAndGet() == 0) {
_state.value = _state.value.copy(isCapturing = false)
checkAndClosePendingReaders()
}
}
@@ -515,6 +516,10 @@ class Camera2Controller(private val context: Context) {
try {
PLog.d(TAG, "ImageReader onImageAvailableListener triggered")
// 关键修复:使用 acquireNextImage() 而不是 acquireLatestImage()
if (openImagesCount.get() >= maxImages) {
PLog.w(TAG, "Too many open images ($openImagesCount), skipping acquire")
return@setOnImageAvailableListener
}
val image = trackImage(reader.acquireNextImage())
if (image != null) {
if (state.value.useRaw && isRawSupported) {
@@ -530,7 +535,7 @@ class Camera2Controller(private val context: Context) {
if (pendingImages.size > 5) {
val oldestKey = pendingImages.keys.minOrNull()
if (oldestKey != null) {
pendingImages.remove(oldestKey)?.let { releaseImage(it) }
pendingImages.remove(oldestKey)?.close()
}
}
}
@@ -1894,7 +1899,6 @@ class Camera2Controller(private val context: Context) {
) {
super.onCaptureSequenceCompleted(session, sequenceId, frameNumber)
PLog.d(TAG, "Burst sequence completed")
_state.value = _state.value.copy(isCapturing = false)
resetPreviewAfterCapture()
}
@@ -1926,7 +1930,6 @@ class Camera2Controller(private val context: Context) {
request: CaptureRequest,
result: TotalCaptureResult
) {
_state.value = _state.value.copy(isCapturing = false)
val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
if (timestamp != null && state.value.useRaw && isRawSupported) {
val pendingImage = pendingImages.remove(timestamp)
@@ -2157,7 +2160,7 @@ class Camera2Controller(private val context: Context) {
}
}
private fun processAndTriggerCapture(image: Image, result: TotalCaptureResult?) {
private fun processAndTriggerCapture(image: SafeImage, result: TotalCaptureResult?) {
try {
val width = image.width
val height = image.height
@@ -2171,11 +2174,11 @@ class Camera2Controller(private val context: Context) {
if (callback != null) {
callback.invoke(image, captureInfo, cachedCharacteristics, result)
} else {
releaseImage(image)
image.close()
}
} catch (e: Exception) {
PLog.e(TAG, "Error processing joined capture data", e)
releaseImage(image)
image.close()
}
}
@@ -2217,12 +2220,4 @@ class Camera2Controller(private val context: Context) {
onLivePhotoVideoCaptured?.invoke(file, timestamp)
}
}
/**
* 兼容性方法:执行 Live Photo 快照并立即开始后台录制
*/
fun captureLivePhoto() {
snapshotLivePhoto()
recordLivePhotoVideo()
}
}
@@ -6,17 +6,18 @@ import android.content.Context
import android.graphics.*
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureResult
import android.media.Image
import android.media.ThumbnailUtils
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.core.graphics.createBitmap
import androidx.exifinterface.media.ExifInterface
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.data.RawEngine
import com.hinnka.mycamera.livephoto.MotionPhotoWriter
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.processor.MultiFrameStacker
import com.hinnka.mycamera.raw.RawDemosaicProcessor
import com.hinnka.mycamera.utils.BitmapUtils
@@ -30,6 +31,7 @@ import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.text.SimpleDateFormat
import java.util.*
import kotlin.use
/**
* 照片管理器
@@ -274,6 +276,211 @@ object PhotoManager {
}
}
suspend fun preparePhoto(
context: Context,
metadata: PhotoMetadata,
captureResult: CaptureResult?,
thumbnail: Bitmap?,
useLivePhoto: Boolean,
useSuperResolution: Boolean
) = withContext(Dispatchers.IO) {
try {
val photoId = UUID.randomUUID().toString()
val photoDir = getPhotoDir(context, photoId)
val photoFile = File(photoDir, PHOTO_FILE)
val videoFile = File(photoDir, VIDEO_FILE)
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
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)
}
val dimensions =
BitmapUtils.calculateProcessedRect(metadata.width, metadata.height, metadata.ratio, cropRegion, metadata.rotation)
val finalWidth = dimensions.width()
val finalHeight = dimensions.height()
// 保存元数据
val metadataWithInfo = metadata.copy(
width = finalWidth,
height = finalHeight,
cropRegion = cropRegion,
)
metadataFile.writeText(metadataWithInfo.toJson())
if (thumbnail != null && !thumbnail.isRecycled) {
generateThumbnail(thumbnail, thumbnailFile)
} else {
PLog.d(TAG, "Thumbnail unavailable: $thumbnail")
}
photoFile.createNewFile()
if (useLivePhoto) {
videoFile.createNewFile()
}
photoId
} catch (e: Exception) {
PLog.e(TAG, "Failed to prepare photo", e)
null
}
}
suspend fun saveVideo(context: Context, photoId: String, livePhotoVideoDeferred: Deferred<Pair<File, Long>?>? = null) {
val photoDir = getPhotoDir(context, photoId)
val videoFile = File(photoDir, VIDEO_FILE)
val livePhotoResult = livePhotoVideoDeferred?.await()
livePhotoResult?.first?.let { cacheVideoFile ->
if (cacheVideoFile.exists()) {
try {
cacheVideoFile.copyTo(videoFile, overwrite = true)
cacheVideoFile.delete()
// 更新元数据以包含时间戳
val currentMeta = loadMetadata(context, photoId) ?: return
saveMetadata(context, photoId, currentMeta.copy(presentationTimestampUs = livePhotoResult.second))
} catch (e: Exception) {
PLog.e(TAG, "Failed to move video file", e)
}
PLog.d(TAG, "Motion Photo synthesized for $photoId with TS: ${livePhotoResult.second}")
}
}
}
suspend fun saveYuvPhoto(
context: Context,
photoId: String,
image: SafeImage,
rotation: Int,
aspectRatio: AspectRatio,
shouldAutoSave: Boolean = true,
photoProcessor: PhotoProcessor,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95
) = withContext(Dispatchers.IO) {
try {
val photoDir = getPhotoDir(context, photoId)
// 预先准备所有文件路径
val photoFile = File(photoDir, PHOTO_FILE)
val tempFile = File(photoDir, "temp.jpg")
val yuvFile = File(photoDir, YUV_FILE)
val metadata = loadMetadata(context, photoId) ?: return@withContext
// 创建预览用的 Bitmap
val previewBitmap = createBitmap(metadata.width, metadata.height)
PLog.d(TAG, "saveYuvPhoto: ${metadata.width} ${metadata.height}")
// YUV 格式:使用 native 处理(包含旋转和裁切)并直接保存为 FP16 JXL
val success = image.use {
YuvProcessor.processAndSave(
image, aspectRatio, rotation,
yuvFile.absolutePath, previewBitmap
)
}
if (success) {
FileOutputStream(tempFile).use { outputStream ->
previewBitmap.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
}
}
suspend fun saveRawPhoto(
context: Context,
photoId: String,
image: SafeImage,
rotation: Int,
aspectRatio: AspectRatio,
characteristics: CameraCharacteristics,
captureResult: CaptureResult?,
shouldAutoSave: Boolean = true,
photoProcessor: PhotoProcessor,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95
) = withContext(Dispatchers.IO) {
try {
val photoDir = getPhotoDir(context, photoId)
// 预先准备所有文件路径
val photoFile = File(photoDir, PHOTO_FILE)
val tempFile = File(photoDir, "temp.jpg")
val dngFile = File(photoDir, DNG_FILE)
val metadata = loadMetadata(context, photoId) ?: return@withContext
captureResult ?: return@withContext
val dngDataBytes = ByteArrayOutputStream().use { dngData ->
image.use {
RawProcessor.saveToDng(image, characteristics, captureResult, dngData, rotation)
}
dngData.toByteArray()
}
FileOutputStream(dngFile).use { outputStream ->
outputStream.write(dngDataBytes)
}
val bitmap = if (metadata.rawEngine == RawEngine.SELF_DEVELOPED) {
RawDemosaicProcessor.getInstance().process(
dngFile.absolutePath,
aspectRatio,
metadata.cropRegion,
rotation
)
} else {
RawProcessor.processAndToBitmap(
dngDataBytes,
aspectRatio,
metadata.cropRegion,
rotation
)
} ?: return@withContext
FileOutputStream(tempFile).use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
bitmap.recycle()
if (shouldAutoSave) {
exportDng(
context,
dngDataBytes,
metadata,
)
exportPhoto(
context,
photoId,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
}
}
/**
* 保存新拍摄的照片
@@ -284,9 +491,8 @@ object PhotoManager {
*/
suspend fun savePhoto(
context: Context,
image: Image,
thumbnail: Bitmap?,
metadata: PhotoMetadata,
photoId: String,
image: SafeImage,
rotation: Int,
aspectRatio: AspectRatio,
characteristics: CameraCharacteristics,
@@ -296,225 +502,107 @@ object PhotoManager {
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95
) {
// 根据图像格式处理
when (val format = image.format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
saveYuvPhoto(
context,
photoId,
image,
rotation,
aspectRatio,
shouldAutoSave,
photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
ImageFormat.RAW_SENSOR, ImageFormat.RAW10, ImageFormat.RAW12 -> {
saveRawPhoto(
context,
photoId,
image,
rotation,
aspectRatio,
characteristics,
captureResult,
shouldAutoSave,
photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
else -> {
PLog.e(TAG, "Unsupported image format: $format")
}
}
}
suspend fun saveYuvStackedPhoto(
context: Context,
photoId: String,
images: List<SafeImage>,
rotation: Int,
aspectRatio: AspectRatio,
shouldAutoSave: Boolean = true,
photoProcessor: PhotoProcessor,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95,
livePhotoVideoDeferred: Deferred<Pair<File, Long>?>? = null,
onProcessingComplete: (() -> Unit)? = null
): String? = withContext(Dispatchers.IO) {
useSuperResolution: Boolean = false,
) = withContext(Dispatchers.IO) {
try {
val photoId = UUID.randomUUID().toString()
val photoDir = getPhotoDir(context, photoId)
// 预先准备所有文件路径
val photoFile = File(photoDir, PHOTO_FILE)
val videoFile = File(photoDir, VIDEO_FILE)
val tempFile = File(photoDir, "temp.jpg")
val yuvFile = File(photoDir, YUV_FILE)
val dngFile = File(photoDir, DNG_FILE)
val metadataFile = File(photoDir, METADATA_FILE)
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
val format = image.format
if (thumbnail != null && !thumbnail.isRecycled) {
generateThumbnail(thumbnail, thumbnailFile)
} else {
PLog.d(TAG, "Thumbnail unavailable: $thumbnail")
val result = MultiFrameStacker.processBurst(
images,
rotation,
aspectRatio,
yuvFile.absolutePath,
useSuperResolution
) ?: return@withContext
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
result.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
val cropRegion = captureResult?.get(CaptureResult.SCALER_CROP_REGION)
// 根据图像格式处理
when (format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
val dimensions =
BitmapUtils.calculateProcessedRect(image.width, image.height, aspectRatio, null, rotation)
val finalWidth = dimensions.width()
val finalHeight = dimensions.height()
// 保存元数据
val metadataWithInfo = metadata.copy(
width = finalWidth,
height = finalHeight,
ratio = aspectRatio,
)
metadataFile.writeText(metadataWithInfo.toJson())
photoFile.createNewFile()
if (livePhotoVideoDeferred != null) {
videoFile.createNewFile()
}
processingScope.launch(Dispatchers.IO) {
try {
// 创建预览用的 Bitmap
val previewBitmap = createBitmap(finalWidth, finalHeight)
val livePhotoResult = livePhotoVideoDeferred?.await()
livePhotoResult?.first?.let { cacheVideoFile ->
if (cacheVideoFile.exists()) {
try {
cacheVideoFile.copyTo(videoFile, overwrite = true)
cacheVideoFile.delete()
// 更新元数据以包含时间戳
val currentMeta = loadMetadata(context, photoId) ?: metadataWithInfo
saveMetadata(context, photoId, currentMeta.copy(presentationTimestampUs = livePhotoResult.second))
} catch (e: Exception) {
PLog.e(TAG, "Failed to move video file", e)
}
PLog.d(TAG, "Motion Photo synthesized for $photoId with TS: ${livePhotoResult.second}")
}
}
// YUV 格式:使用 native 处理(包含旋转和裁切)并直接保存为 FP16 JXL
val success = YuvProcessor.processAndSave(
image, aspectRatio, rotation,
yuvFile.absolutePath, previewBitmap
)
if (success) {
if (thumbnail == null) {
generateThumbnail(previewBitmap, thumbnailFile)
}
FileOutputStream(tempFile).use { outputStream ->
previewBitmap.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
photoProcessor,
metadataWithInfo,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
onProcessingComplete?.invoke()
}
}
}
ImageFormat.RAW_SENSOR, ImageFormat.RAW10, ImageFormat.RAW12 -> {
val dimensions =
BitmapUtils.calculateProcessedRect(image.width, image.height, aspectRatio, cropRegion, rotation)
// 保存元数据
val metadataWithInfo = metadata.copy(
width = dimensions.width(),
height = dimensions.height(),
ratio = aspectRatio,
cropRegion = cropRegion,
rotation = rotation,
sharpening = if (sharpeningValue == 0f) 0.4f else sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = if (chromaNoiseReductionValue == 0f) 0.25f else chromaNoiseReductionValue,
)
metadataFile.writeText(metadataWithInfo.toJson())
photoFile.createNewFile()
if (livePhotoVideoDeferred != null) {
videoFile.createNewFile()
}
processingScope.launch(Dispatchers.IO) {
try {
captureResult ?: return@launch
val livePhotoResult = livePhotoVideoDeferred?.await()
livePhotoResult?.first?.let { cacheVideoFile ->
if (cacheVideoFile.exists()) {
try {
cacheVideoFile.copyTo(videoFile, overwrite = true)
cacheVideoFile.delete()
// 更新元数据以包含时间戳
val currentMeta = loadMetadata(context, photoId) ?: metadataWithInfo
saveMetadata(context, photoId, currentMeta.copy(presentationTimestampUs = livePhotoResult.second))
} catch (e: Exception) {
PLog.e(TAG, "Failed to move video file", e)
}
PLog.d(TAG, "Motion Photo synthesized for $photoId with TS: ${livePhotoResult.second}")
}
}
val dngDataBytes = ByteArrayOutputStream().use { dngData ->
RawProcessor.saveToDng(image, characteristics, captureResult, dngData, rotation)
dngData.toByteArray()
}
FileOutputStream(dngFile).use { outputStream ->
outputStream.write(dngDataBytes)
}
val bitmap = if (metadataWithInfo.rawEngine == RawEngine.SELF_DEVELOPED) {
RawDemosaicProcessor.getInstance().process(
dngFile.absolutePath,
aspectRatio,
cropRegion,
rotation
)
} else {
RawProcessor.processAndToBitmap(
dngDataBytes,
aspectRatio,
cropRegion,
rotation
)
} ?: return@launch
if (thumbnail == null) {
generateThumbnail(bitmap, thumbnailFile)
}
FileOutputStream(tempFile).use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
bitmap.recycle()
if (shouldAutoSave) {
exportDng(
context,
dngDataBytes,
metadataWithInfo,
)
exportPhoto(
context,
photoId,
photoProcessor,
metadataWithInfo,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
onProcessingComplete?.invoke()
}
}
}
else -> {
PLog.e(TAG, "Unsupported image format: $format")
onProcessingComplete?.invoke()
}
tempFile.renameTo(photoFile)
result.recycle()
// Auto Save
if (shouldAutoSave) {
val metadata = loadMetadata(context, photoId) ?: return@withContext
exportPhoto(
context,
photoId,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
photoId
} catch (e: Exception) {
PLog.e(TAG, "Failed to save photo", e)
onProcessingComplete?.invoke()
null
PLog.e(TAG, "Failed to savePhoto", e)
}
}
/**
* 保存堆栈合成后的照片
*/
suspend fun saveStackedPhoto(
suspend fun saveRawStackedPhoto(
context: Context,
images: List<Image>,
thumbnail: Bitmap?,
metadata: PhotoMetadata,
photoId: String,
images: List<SafeImage>,
rotation: Int,
aspectRatio: AspectRatio,
characteristics: CameraCharacteristics?,
@@ -526,240 +614,146 @@ object PhotoManager {
chromaNoiseReductionValue: Float,
photoQuality: Int = 95,
useSuperResolution: Boolean = false,
livePhotoVideoDeferred: Deferred<Pair<File, Long>?>? = null,
onProcessingComplete: (() -> Unit)? = null
): String? = withContext(Dispatchers.IO) {
) = withContext(Dispatchers.IO) {
try {
val photoId = UUID.randomUUID().toString()
val photoDir = getPhotoDir(context, photoId)
// 预先准备所有文件路径
val photoFile = File(photoDir, PHOTO_FILE)
val videoFile = File(photoDir, VIDEO_FILE)
val tempFile = File(photoDir, "temp.jpg")
val yuvFile = File(photoDir, YUV_FILE)
val dngFile = File(photoDir, DNG_FILE)
val metadataFile = File(photoDir, METADATA_FILE)
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
if (thumbnail != null && !thumbnail.isRecycled) {
generateThumbnail(thumbnail, thumbnailFile)
} else {
PLog.d(TAG, "Thumbnail unavailable: $thumbnail")
val metadata = loadMetadata(context, photoId) ?: return@withContext
characteristics ?: return@withContext
captureResult ?: return@withContext
val firstImageData = images[0].planes[0].buffer
val firstImageWidth = images[0].width
val firstImageHeight = images[0].height
val byteBuffer = MultiFrameStacker.processBurstRaw(
images, characteristics,
useSuperResolution
)
byteBuffer ?: return@withContext
val byteOutstream = ByteArrayOutputStream()
byteOutstream.use { outputStream ->
try {
val scale = if (useSuperResolution) 2 else 1
RawProcessor.saveToDng(
byteBuffer.asReadOnlyBuffer(), characteristics,
captureResult, outputStream, firstImageWidth * scale, firstImageHeight * scale, rotation
)
} catch (e: Throwable) {
// Fallback: If scaled DNG is not supported by hardware,
// save the first original frame to maintain DNG availability.
PLog.e(TAG, "SR DNG dimensions not supported, falling back to original frame DNG", e)
RawProcessor.saveToDng(firstImageData, characteristics, captureResult, outputStream,
firstImageWidth, firstImageHeight, rotation)
}
}
val array = byteOutstream.toByteArray()
FileOutputStream(dngFile).use {
it.write(array)
}
if (shouldAutoSave) {
exportDng(context, array, metadata)
}
val dimensions =
BitmapUtils.calculateProcessedRect(
images[0].width,
images[0].height,
val result = if (metadata.rawEngine == RawEngine.SELF_DEVELOPED) {
RawDemosaicProcessor.getInstance().process(
dngFile.absolutePath,
aspectRatio,
null,
metadata.cropRegion,
rotation
)
val finalWidth = dimensions.width()
val finalHeight = dimensions.height()
val format = images[0].format
when (format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
// 保存元数据
val metadataWithInfo = metadata.copy(
width = finalWidth * if (useSuperResolution) 2 else 1,
height = finalHeight * if (useSuperResolution) 2 else 1,
ratio = aspectRatio,
sharpening = if (sharpeningValue == 0f) (if (useSuperResolution) 0.8f else 0.4f) else sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
)
metadataFile.writeText(metadataWithInfo.toJson())
photoFile.createNewFile()
if (livePhotoVideoDeferred != null) {
videoFile.createNewFile()
}
processingScope.launch(Dispatchers.IO) {
val livePhotoResult = livePhotoVideoDeferred?.await()
livePhotoResult?.first?.let { cacheVideoFile ->
if (cacheVideoFile.exists()) {
try {
cacheVideoFile.copyTo(videoFile, overwrite = true)
cacheVideoFile.delete()
// 更新元数据以包含时间戳
val currentMeta = loadMetadata(context, photoId) ?: metadataWithInfo
saveMetadata(context, photoId, currentMeta.copy(presentationTimestampUs = livePhotoResult.second))
} catch (e: Exception) {
PLog.e(TAG, "Failed to move video file", e)
}
PLog.d(TAG, "Motion Photo synthesized for $photoId with TS: ${livePhotoResult.second}")
}
}
try {
val result = MultiFrameStacker.processBurst(
images,
rotation,
aspectRatio,
yuvFile.absolutePath,
useSuperResolution
) ?: return@launch
// Generate Thumbnail
if (thumbnail == null) {
generateThumbnail(result, thumbnailFile)
}
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
result.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
result.recycle()
// Auto Save
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
photoProcessor,
metadataWithInfo,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
onProcessingComplete?.invoke()
}
}
}
ImageFormat.RAW_SENSOR, ImageFormat.RAW10, ImageFormat.RAW12 -> {
photoFile.createNewFile()
if (livePhotoVideoDeferred != null) {
videoFile.createNewFile()
}
val scale = if (useSuperResolution) 2 else 1
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)
}
// 保存元数据
val metadataWithInfo = metadata.copy(
width = finalWidth * scale,
height = finalHeight * scale,
ratio = aspectRatio,
cropRegion = cropRegion,
rotation = rotation,
sharpening = if (sharpeningValue == 0f) 0.8f else sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = if (chromaNoiseReductionValue == 0f) 0.25f else chromaNoiseReductionValue,
)
metadataFile.writeText(metadataWithInfo.toJson())
processingScope.launch(Dispatchers.IO) {
try {
characteristics ?: return@launch
captureResult ?: return@launch
val livePhotoResult = livePhotoVideoDeferred?.await()
livePhotoResult?.first?.let { cacheVideoFile ->
if (cacheVideoFile.exists()) {
try {
cacheVideoFile.copyTo(videoFile, overwrite = true)
cacheVideoFile.delete()
// 更新元数据以包含时间戳
val currentMeta = loadMetadata(context, photoId) ?: metadataWithInfo
saveMetadata(context, photoId, currentMeta.copy(presentationTimestampUs = livePhotoResult.second))
} catch (e: Exception) {
PLog.e(TAG, "Failed to move video file", e)
}
PLog.d(TAG, "Motion Photo synthesized for $photoId with TS: ${livePhotoResult.second}")
}
}
val byteBuffer = MultiFrameStacker.processBurstRaw(
images, characteristics,
useSuperResolution
)
byteBuffer ?: return@launch
val byteOutstream = ByteArrayOutputStream()
byteOutstream.use { outputStream ->
try {
val scaledWidth = images[0].width * scale
val scaledHeight = images[0].height * scale
RawProcessor.saveToDng(
byteBuffer.asReadOnlyBuffer(), characteristics,
captureResult, outputStream, scaledWidth, scaledHeight, rotation
)
} catch (e: Throwable) {
// Fallback: If scaled DNG is not supported by hardware,
// save the first original frame to maintain DNG availability.
PLog.i(TAG, "SR DNG dimensions not supported, falling back to original frame DNG")
RawProcessor.saveToDng(images[0], characteristics, captureResult, outputStream, rotation)
}
}
val array = byteOutstream.toByteArray()
FileOutputStream(dngFile).use {
it.write(array)
}
if (shouldAutoSave) {
exportDng(context, array, metadataWithInfo)
}
val result = if (metadataWithInfo.rawEngine == RawEngine.SELF_DEVELOPED) {
RawDemosaicProcessor.getInstance().process(
dngFile.absolutePath,
aspectRatio,
cropRegion,
rotation
)
} else {
RawProcessor.processAndToBitmap(dngFile, aspectRatio, cropRegion, rotation)
} ?: return@launch
// Generate Thumbnail
if (thumbnail == null) {
generateThumbnail(result, thumbnailFile)
}
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
result.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
// Auto Save
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
photoProcessor,
metadataWithInfo,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to savePhoto", e)
} finally {
onProcessingComplete?.invoke()
}
}
}
else -> {
PLog.e(TAG, "Unsupported image format: $format")
onProcessingComplete?.invoke()
return@withContext null
}
} else {
RawProcessor.processAndToBitmap(dngFile, aspectRatio, metadata.cropRegion, rotation)
} ?: return@withContext
// Save Original (Stacked Result)
FileOutputStream(tempFile).use { outputStream ->
result.compress(Bitmap.CompressFormat.JPEG, photoQuality, outputStream)
}
tempFile.renameTo(photoFile)
// Auto Save
if (shouldAutoSave) {
exportPhoto(
context,
photoId,
photoProcessor,
metadata,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality
)
}
photoId
} catch (e: Exception) {
PLog.e(TAG, "Failed to save stacked photo", e)
onProcessingComplete?.invoke()
null
PLog.e(TAG, "Failed to savePhoto", e)
}
}
/**
* 保存堆栈合成后的照片
*/
suspend fun saveStackedPhoto(
context: Context,
photoId: String,
images: List<SafeImage>,
rotation: Int,
aspectRatio: AspectRatio,
characteristics: CameraCharacteristics?,
captureResult: CaptureResult?,
shouldAutoSave: Boolean = true,
photoProcessor: PhotoProcessor,
sharpeningValue: Float,
noiseReductionValue: Float,
chromaNoiseReductionValue: Float,
photoQuality: Int = 95,
useSuperResolution: Boolean = false,
) = withContext(Dispatchers.IO) {
when (val format = images[0].format) {
ImageFormat.YUV_420_888, ImageFormat.YCBCR_P010, ImageFormat.NV21 -> {
saveYuvStackedPhoto(
context,
photoId,
images,
rotation,
aspectRatio,
shouldAutoSave,
photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality,
useSuperResolution
)
}
ImageFormat.RAW_SENSOR, ImageFormat.RAW10, ImageFormat.RAW12 -> {
saveRawStackedPhoto(
context,
photoId,
images,
rotation,
aspectRatio,
characteristics,
captureResult,
shouldAutoSave,
photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQuality,
useSuperResolution
)
}
else -> {
PLog.e(TAG, "Unsupported image format: $format")
return@withContext null
}
}
}
@@ -0,0 +1,23 @@
package com.hinnka.mycamera.model
import android.media.Image
import com.hinnka.mycamera.camera.Camera2Controller
class SafeImage(val image: Image, private val camera2Controller: Camera2Controller) : AutoCloseable {
val width: Int
get() = image.width
val height: Int
get() = image.height
val format: Int
get() = image.format
val planes: Array<Image.Plane>
get() = image.planes
val timestamp: Long
get() = image.timestamp
override fun close() {
image.close()
camera2Controller.onImageRelease()
}
}
@@ -7,6 +7,7 @@ import com.hinnka.mycamera.utils.PLog
import java.nio.ByteBuffer
import androidx.core.graphics.createBitmap
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.utils.BitmapUtils
import java.nio.ByteOrder
@@ -34,7 +35,7 @@ object MultiFrameStacker {
* @return Stacked Bitmap (ARGB_8888), or null if failed.
*/
fun processBurst(
images: List<Image>,
images: List<SafeImage>,
rotation: Int,
aspectRatio: AspectRatio?,
outputPath: String? = null,
@@ -58,30 +59,41 @@ object MultiFrameStacker {
}
try {
val stagedIndices = mutableListOf<Int>()
for ((index, image) in images.withIndex()) {
// Validate dimensions
if (image.width != width || image.height != height) {
PLog.w(TAG, "Skipping frame $index due to dimension mismatch")
continue
image.use {
// Validate dimensions
if (image.width != width || image.height != height) {
PLog.w(TAG, "Skipping frame $index due to dimension mismatch")
return@use
}
val planes = image.planes
val yBuffer = planes[0].buffer
val uBuffer = planes[1].buffer
val vBuffer = planes[2].buffer
val yRowStride = planes[0].rowStride
val uvRowStride = planes[1].rowStride
val uvPixelStride = planes[1].pixelStride
stageFrameNative(
stackerPtr,
yBuffer, uBuffer, vBuffer,
yRowStride, uvRowStride, uvPixelStride,
image.format
)
stagedIndices.add(stagedIndices.size)
}
val planes = image.planes
val yBuffer = planes[0].buffer
val uBuffer = planes[1].buffer
val vBuffer = planes[2].buffer
val yRowStride = planes[0].rowStride
val uvRowStride = planes[1].rowStride
val uvPixelStride = planes[1].pixelStride
addToStackNative(
stackerPtr,
yBuffer, uBuffer, vBuffer,
yRowStride, uvRowStride, uvPixelStride,
image.format
)
}
// High-latency processing happens here, after all Images are closed
for (idx in stagedIndices) {
processFrameNative(stackerPtr, idx)
}
// Optional: clear native memory when done
clearStagedFramesNative(stackerPtr)
val dimensions = BitmapUtils.calculateProcessedRect(width, height, aspectRatio, null, rotation)
// Apply scale to output dimensions
@@ -111,7 +123,7 @@ object MultiFrameStacker {
}
fun processBurstRaw(
images: List<Image>,
images: List<SafeImage>,
characteristics: CameraCharacteristics,
enableSuperResolution: Boolean = false
): ByteBuffer? {
@@ -132,13 +144,20 @@ object MultiFrameStacker {
return null
}
// 2. Add frames
val stagedIndices = mutableListOf<Int>()
for (image in images) {
if (image.width != width || image.height != height) continue
val buffer = image.planes[0].buffer
val rowStride = image.planes[0].rowStride
addToRawStackNative(stackerPtr, buffer, rowStride, sensorCfa)
image.use {
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)
stagedIndices.add(stagedIndices.size)
}
}
for (idx in stagedIndices) {
processRawFrameNative(stackerPtr, idx)
}
clearStagedRawFramesNative(stackerPtr)
// 3. Process Stack
val scale = getRawStackerScaleNative(stackerPtr)
@@ -154,13 +173,16 @@ object MultiFrameStacker {
private external fun createStackerNative(width: Int, height: Int, enableSuperRes: Boolean): Long
private external fun addToStackNative(
private external fun stageFrameNative(
stackerPtr: Long,
yBuffer: ByteBuffer, uBuffer: ByteBuffer, vBuffer: ByteBuffer,
yRowStride: Int, uvRowStride: Int, uvPixelStride: Int,
format: Int
)
private external fun processFrameNative(stackerPtr: Long, index: Int)
private external fun clearStagedFramesNative(stackerPtr: Long)
private external fun processStackNative(
stackerPtr: Long,
outBitmap: Bitmap?,
@@ -174,7 +196,9 @@ object MultiFrameStacker {
private external fun createRawStackerNative(width: Int, height: Int, useSuperRes: Boolean): Long
private external fun getRawStackerScaleNative(stackerPtr: Long): Int
private external fun addToRawStackNative(stackerPtr: Long, rawData: ByteBuffer, rowStride: Int, cfaPattern: Int)
private external fun stageRawFrameNative(stackerPtr: Long, rawData: ByteBuffer, rowStride: Int, cfaPattern: Int)
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 releaseRawStackerNative(stackerPtr: Long)
}
@@ -1,6 +1,9 @@
package com.hinnka.mycamera.ui.camera
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
@@ -27,6 +30,8 @@ import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathOperation
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.layout
@@ -509,7 +514,6 @@ fun Controls(
// 拍照按钮 (Center)
CaptureButton(
isCapturing = state.isCapturing,
isCapturingLivePhoto = state.isCapturingLivePhoto,
onClick = { viewModel.capture() }
)
@@ -539,19 +543,22 @@ fun Controls(
@Composable
fun CaptureButton(
isCapturing: Boolean,
isCapturingLivePhoto: Boolean = false,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val infiniteTransition = rememberInfiniteTransition(label = "infinite transition")
val scale by animateFloatAsState(
targetValue = if (isCapturing) 0.9f else 1f,
animationSpec = spring(dampingRatio = 0.5f),
label = "captureScale"
)
val rotation by animateFloatAsState(
targetValue = if (isCapturingLivePhoto) 360f else 0f,
animationSpec = if (isCapturingLivePhoto) tween(1500) else tween(0),
val rotation by infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(tween(1500)),
label = "livePhotoRotation"
)
@@ -559,7 +566,7 @@ fun CaptureButton(
modifier = modifier
.size(72.dp)
.scale(scale)
.clickable(enabled = !isCapturing && !isCapturingLivePhoto) { onClick() },
.clickable(enabled = !isCapturing) { onClick() },
contentAlignment = Alignment.Center
) {
// Inner Yellow Ring
@@ -570,7 +577,7 @@ fun CaptureButton(
)
// Live Photo Indicator (Spinning dash)
if (isCapturingLivePhoto) {
if (isCapturing) {
Canvas(modifier = Modifier.fillMaxSize()) {
val strokeWidth = 3.dp.toPx()
drawArc(
@@ -578,24 +585,22 @@ fun CaptureButton(
startAngle = rotation - 90f,
sweepAngle = 90f,
useCenter = false,
style = androidx.compose.ui.graphics.drawscope.Stroke(
style = Stroke(
width = strokeWidth,
cap = androidx.compose.ui.graphics.StrokeCap.Round
cap = StrokeCap.Round
)
)
}
}
// Center Solid Button (When not capturing)
if (!isCapturing) {
Box(
modifier = Modifier
.padding(4.dp)
.fillMaxSize()
.clip(CircleShape)
.background(Color.White)
)
}
// Center Solid Button
Box(
modifier = Modifier
.padding(4.dp)
.fillMaxSize()
.clip(CircleShape)
.background(Color.White)
)
}
}
@@ -9,6 +9,7 @@ import android.media.Image
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.RawDemosaicProcessor
import java.io.File
import java.io.FileInputStream
@@ -29,7 +30,7 @@ object RawProcessor {
/**
* 检查图像是否为 RAW 格式
*/
fun isRawImage(image: Image): Boolean {
fun isRawImage(image: SafeImage): Boolean {
return image.format == ImageFormat.RAW_SENSOR ||
image.format == ImageFormat.RAW_PRIVATE ||
image.format == ImageFormat.RAW10 ||
@@ -120,7 +121,7 @@ object RawProcessor {
* @param rotation 旋转角度 (0, 90, 180, 270)
*/
fun saveToDng(
image: Image,
image: SafeImage,
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
outputStream: java.io.OutputStream,
@@ -139,7 +140,7 @@ object RawProcessor {
else -> ExifInterface.ORIENTATION_NORMAL
}
dngCreator.setOrientation(orientation)
dngCreator.writeImage(outputStream, image)
dngCreator.writeImage(outputStream, image.image)
} catch (e: Exception) {
PLog.e(TAG, "Failed to save DNG", e)
} finally {
@@ -6,6 +6,7 @@ import com.hinnka.mycamera.camera.AspectRatio
import java.nio.ByteBuffer
import androidx.core.graphics.createBitmap
import android.util.Half
import com.hinnka.mycamera.model.SafeImage
/**
* YUV 图像处理器
@@ -65,7 +66,7 @@ object YuvProcessor {
* 处理 YUV 图像并直接保存为高精度 JXL 文件 (FP16),同时生成预览图
*/
fun processAndSave(
image: Image,
image: SafeImage,
aspectRatio: AspectRatio,
rotation: Int,
outputPath: String,
@@ -26,6 +26,7 @@ import com.hinnka.mycamera.gallery.PhotoProcessor
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.lut.LutInfo
import com.hinnka.mycamera.model.ColorRecipeParams
import com.hinnka.mycamera.model.SafeImage
import com.hinnka.mycamera.ui.camera.CameraGLSurfaceView
import com.hinnka.mycamera.utils.OrientationObserver
import com.hinnka.mycamera.utils.PLog
@@ -181,7 +182,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// Burst State
private var isBursting = false
private val burstImages = mutableListOf<Image>()
private val burstImages = mutableListOf<SafeImage>()
init {
cameraController.initialize()
@@ -215,10 +216,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
PLog.d(TAG, "onCameraError: code=$code, message=$message, canRetry=$canRetry")
isBursting = false
burstImages.forEach {
try {
cameraController.releaseImage(it)
} catch (e: Exception) {
}
it.close()
}
burstImages.clear()
}
@@ -1284,7 +1282,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
* 保存图片
*/
private suspend fun saveImage(
image: Image,
image: SafeImage,
captureInfo: CaptureInfo,
characteristics: CameraCharacteristics?,
captureResult: CaptureResult?
@@ -1328,9 +1326,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
sharpening = sharpeningValue,
sharpening = if (useRaw.value && sharpeningValue == 0f) 0.4f else sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
chromaNoiseReduction = if (useRaw.value && chromaNoiseReductionValue == 0f) 0.25f else chromaNoiseReductionValue,
width = image.width,
height = image.height,
ratio = aspectRatio,
rotation = rotation,
deviceModel = captureInfo.model,
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
dateTaken = captureInfo.captureTime,
@@ -1350,39 +1352,39 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
deferred
} else null
val photoId = characteristics?.let {
characteristics ?: return
val photoId = PhotoManager.preparePhoto(context, metadata, captureResult, previewThumbnail, useLivePhoto.value, false)
if (photoId == null) {
PLog.e(TAG, "Failed to save image")
return
}
viewModelScope.launch(Dispatchers.IO) {
PhotoManager.saveVideo(context, photoId, livePhotoVideoDeferred)
PhotoManager.savePhoto(
context,
photoId,
image,
previewThumbnail,
metadata,
rotation,
aspectRatio,
it,
characteristics,
captureResult,
shouldAutoSave,
photoProcessor,
sharpeningValue,
noiseReductionValue,
chromaNoiseReductionValue,
photoQualityValue,
livePhotoVideoDeferred = livePhotoVideoDeferred,
onProcessingComplete = { cameraController.releaseImage(image) }
photoQualityValue
)
}
if (photoId != null) {
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
_imageSavedEvent.emit(Unit)
} else {
PLog.e(TAG, "Failed to save image via PhotoManager")
}
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
_imageSavedEvent.emit(Unit)
} catch (e: Exception) {
PLog.e(TAG, "Failed to save image", e)
}
}
private suspend fun processBurst(
images: List<Image>,
images: List<SafeImage>,
captureInfo: CaptureInfo,
characteristics: CameraCharacteristics?,
captureResult: CaptureResult?
@@ -1426,9 +1428,13 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
lutId = lutIdToSave,
frameId = frameIdToSave,
colorRecipeParams = currentRecipeParams.value,
sharpening = sharpeningValue,
sharpening = if (sharpeningValue == 0f) (if (useSuperResolution.value) 0.8f else 0.4f) else sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
chromaNoiseReduction = if (useRaw.value && chromaNoiseReductionValue == 0f) 0.25f else chromaNoiseReductionValue,
width = images[0].width * (if (useSuperResolution.value) 2 else 1),
height = images[0].height * (if (useSuperResolution.value) 2 else 1),
ratio = aspectRatio,
rotation = rotation,
deviceModel = captureInfo.model,
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
dateTaken = captureInfo.captureTime,
@@ -1450,15 +1456,23 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
deferred
} else null
val photoId = characteristics?.let {
characteristics ?: return
val photoId = PhotoManager.preparePhoto(context, metadata, captureResult, previewThumbnail,
useLivePhoto.value, useSuperResolution.value)
if (photoId == null) {
PLog.e(TAG, "Failed to save burst image")
return
}
viewModelScope.launch(Dispatchers.IO) {
PhotoManager.saveVideo(context, photoId, livePhotoVideoDeferred)
PhotoManager.saveStackedPhoto(
context,
photoId,
images,
previewThumbnail,
metadata,
rotation,
aspectRatio,
it,
characteristics,
captureResult,
shouldAutoSave,
photoProcessor,
@@ -1467,16 +1481,10 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
chromaNoiseReductionValue,
photoQualityValue,
useSuperResolution = useSuperResolution.value,
livePhotoVideoDeferred = livePhotoVideoDeferred,
onProcessingComplete = { images.forEach { cameraController.releaseImage(it) } }
)
}
if (photoId != null) {
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
_imageSavedEvent.emit(Unit)
} else {
PLog.e(TAG, "Failed to save image via PhotoManager")
}
PLog.d(TAG, "Image saved: $photoId, LUT: $lutIdToSave, Frame: $frameIdToSave")
_imageSavedEvent.emit(Unit)
} catch (e: Exception) {
PLog.e(TAG, "Failed to save image", e)
}
@@ -1549,10 +1557,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
// 清理未处理的连拍图片
burstImages.forEach {
try {
cameraController.releaseImage(it)
} catch (e: Exception) {
}
it.close()
}
burstImages.clear()
}
+2
View File
@@ -16,6 +16,7 @@ exifinterface = "1.4.2"
billing = "8.3.0"
fragment = "1.8.9"
media3 = "1.5.1"
animationCore = "1.10.2"
[libraries]
media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" }
@@ -43,6 +44,7 @@ coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coi
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }
androidx-fragment-ktx = { group = "androidx.fragment", name = "fragment-ktx", version.ref = "fragment" }
androidx-animation-core = { group = "androidx.compose.animation", name = "animation-core", version.ref = "animationCore" }
[plugins]