feat: frame stack
This commit is contained in:
1 parent
bb31f4176e
commit
b2db84ebd0
18 files changed
+1803
-532
No files matched your search
@@ -50,14 +50,3 @@
|
||||
|
||||
* Pixel 7 Android 16 - 拍照后预览黑屏
|
||||
* Pixel 7 Android 16 - 切换摄像头闪退
|
||||
|
||||
|
||||
if (warmMask > 0.0) {
|
||||
// 6.2.1 "去脏":只在一定范围内应用,避免把鲜艳的红色变黑
|
||||
color.b = mix(color.b, color.b * 0.85, warmMask * strength);
|
||||
// 6.2.2 密度调整
|
||||
color.g = mix(color.g, color.g * 0.95, warmMask * strength);
|
||||
// 6.2.3 胶片感增强:使用非线性缩放而不是简单的乘法,保护亮度
|
||||
vec3 sCurve = color * color * (3.0 - 2.0 * color);
|
||||
color = mix(color, sCurve, warmMask * strength * 0.2);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ add_library(my-native-lib SHARED
|
||||
dng_parser.cpp
|
||||
yuv_utils.cpp
|
||||
jxl_utils.cpp
|
||||
stacking_utils.cpp
|
||||
)
|
||||
|
||||
# 启用优化
|
||||
|
||||
@@ -15,10 +15,81 @@
|
||||
#include "dng_parser.h"
|
||||
#include "jxl_utils.h"
|
||||
#include "math_utils.h"
|
||||
#include "stacking_utils.h"
|
||||
#include "yuv_utils.h"
|
||||
|
||||
extern "C" {
|
||||
|
||||
/**
|
||||
* Multi-Frame Stacking JNI Interface
|
||||
*/
|
||||
JNIEXPORT jlong JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MultiFrameStacker_createStackerNative(
|
||||
JNIEnv *env, jobject /* this */, jint width, jint height) {
|
||||
auto *stacker = new ImageStacker(width, height);
|
||||
return reinterpret_cast<jlong>(stacker);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MultiFrameStacker_addToStackNative(
|
||||
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->addFrame(yData, uData, vData, yRowStride, uvRowStride,
|
||||
uvPixelStride, format);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MultiFrameStacker_processStackNative(
|
||||
JNIEnv *env, jobject /* this */, jlong stackerPtr, jobject outBitmap,
|
||||
jint rotation, jint targetWR, jint targetHR, jstring outputPath) {
|
||||
|
||||
auto *stacker = reinterpret_cast<ImageStacker *>(stackerPtr);
|
||||
if (!stacker)
|
||||
return;
|
||||
|
||||
const char *path = nullptr;
|
||||
if (outputPath) {
|
||||
path = env->GetStringUTFChars(outputPath, nullptr);
|
||||
}
|
||||
|
||||
void *bitmapPixels = nullptr;
|
||||
if (outBitmap &&
|
||||
AndroidBitmap_lockPixels(env, outBitmap, &bitmapPixels) < 0) {
|
||||
if (path)
|
||||
env->ReleaseStringUTFChars(outputPath, path);
|
||||
return;
|
||||
}
|
||||
|
||||
stacker->writeResult(static_cast<uint32_t *>(bitmapPixels), rotation,
|
||||
targetWR, targetHR, path);
|
||||
|
||||
if (outBitmap) {
|
||||
AndroidBitmap_unlockPixels(env, outBitmap);
|
||||
}
|
||||
if (path) {
|
||||
env->ReleaseStringUTFChars(outputPath, path);
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_hinnka_mycamera_processor_MultiFrameStacker_releaseStackerNative(
|
||||
JNIEnv *env, jobject /* this */, jlong stackerPtr) {
|
||||
auto *stacker = reinterpret_cast<ImageStacker *>(stackerPtr);
|
||||
delete stacker;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 YUV_420_888 或 P010 图像:旋转、裁切、转换为 RGBA16
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
#include "stacking_utils.h"
|
||||
#include "common.h" // For LOG macros
|
||||
#include "math_utils.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
|
||||
// Helper to access pixel with boundary check (clamp)
|
||||
inline uint8_t getPixel(const GrayImage &img, int x, int y) {
|
||||
x = std::max(0, std::min(x, img.width - 1));
|
||||
y = std::max(0, std::min(y, img.height - 1));
|
||||
return img.data[y * img.width + x];
|
||||
}
|
||||
|
||||
std::vector<GrayImage> buildPyramid(const uint8_t *src, int width, int height,
|
||||
int levels) {
|
||||
std::vector<GrayImage> pyramid;
|
||||
|
||||
// Level 0 is the original image (or copy of it)
|
||||
GrayImage level0;
|
||||
level0.width = width;
|
||||
level0.height = height;
|
||||
level0.data.assign(src, src + width * height);
|
||||
pyramid.push_back(std::move(level0));
|
||||
|
||||
for (int i = 1; i < levels; ++i) {
|
||||
const GrayImage &prev = pyramid.back();
|
||||
GrayImage next;
|
||||
next.width = prev.width / 2;
|
||||
next.height = prev.height / 2;
|
||||
next.data.resize(next.width * next.height);
|
||||
|
||||
for (int y = 0; y < next.height; ++y) {
|
||||
for (int x = 0; x < next.width; ++x) {
|
||||
// Simple 2x2 average (Box filter)
|
||||
int sum = prev.data[(2 * y) * prev.width + (2 * x)] +
|
||||
prev.data[(2 * y) * prev.width + (2 * x + 1)] +
|
||||
prev.data[(2 * y + 1) * prev.width + (2 * x)] +
|
||||
prev.data[(2 * y + 1) * prev.width + (2 * x + 1)];
|
||||
next.data[y * next.width + x] = static_cast<uint8_t>(sum / 4);
|
||||
}
|
||||
}
|
||||
pyramid.push_back(std::move(next));
|
||||
}
|
||||
return pyramid;
|
||||
}
|
||||
|
||||
// Compute Sum of Absolute Differences (SAD)
|
||||
long long computeSAD(const GrayImage &ref, const GrayImage &target, int dx,
|
||||
int dy) {
|
||||
long long sad = 0;
|
||||
int margin = 2;
|
||||
int startX = std::max(margin, -dx + margin);
|
||||
int startY = std::max(margin, -dy + margin);
|
||||
int endX = std::min(ref.width - margin, target.width - dx - margin);
|
||||
int endY = std::min(ref.height - margin, target.height - dy - margin);
|
||||
|
||||
if (startX >= endX || startY >= endY)
|
||||
return std::numeric_limits<long long>::max();
|
||||
|
||||
int samples = 0;
|
||||
for (int y = startY; y < endY; ++y) {
|
||||
const uint8_t *pRef = &ref.data[y * ref.width + startX];
|
||||
const uint8_t *pTgt = &target.data[(y + dy) * target.width + (startX + dx)];
|
||||
for (int x = startX; x < endX; ++x) {
|
||||
sad += std::abs((int)(*pRef) - (int)(*pTgt));
|
||||
pRef++;
|
||||
pTgt++;
|
||||
}
|
||||
samples += (endX - startX);
|
||||
}
|
||||
|
||||
return samples > 0 ? (sad * 1000) / samples
|
||||
: std::numeric_limits<long long>::max();
|
||||
}
|
||||
|
||||
// Compute Sum of Absolute Differences (SAD) for a block
|
||||
long long computeBlockSAD(const GrayImage &ref, const GrayImage &target,
|
||||
int refX, int refY, int w, int h, int dx, int dy) {
|
||||
long long sad = 0;
|
||||
int count = 0;
|
||||
for (int y = 0; y < h; ++y) {
|
||||
int rY = refY + y;
|
||||
int tY = rY + dy;
|
||||
if (rY < 0 || rY >= ref.height || tY < 0 || tY >= target.height)
|
||||
continue;
|
||||
|
||||
const uint8_t *pRef = &ref.data[rY * ref.width + refX];
|
||||
const uint8_t *pTgt = &target.data[tY * target.width + refX + dx];
|
||||
|
||||
for (int x = 0; x < w; ++x) {
|
||||
int rX = refX + x;
|
||||
int tX = rX + dx;
|
||||
if (rX < 0 || rX >= ref.width || tX < 0 || tX >= target.width)
|
||||
continue;
|
||||
sad += std::abs((int)pRef[x] - (int)pTgt[x]);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count > 0 ? (sad * 256) / count
|
||||
: std::numeric_limits<long long>::max();
|
||||
}
|
||||
|
||||
TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
const std::vector<GrayImage> &targetPyramid,
|
||||
int maxShift) {
|
||||
const int tileSize = 32; // Use 32x32 tiles
|
||||
int width = refPyramid[0].width;
|
||||
int height = refPyramid[0].height;
|
||||
int gridW = (width + tileSize - 1) / tileSize;
|
||||
int gridH = (height + tileSize - 1) / tileSize;
|
||||
|
||||
TileAlignment alignment;
|
||||
alignment.tileWidth = tileSize;
|
||||
alignment.tileHeight = tileSize;
|
||||
alignment.gridW = gridW;
|
||||
alignment.gridH = gridH;
|
||||
alignment.offsets.resize(gridW * gridH, {0, 0});
|
||||
|
||||
// 1. Compute a global offset first as a base
|
||||
Point globalOffset = {0, 0};
|
||||
int currentDx = 0;
|
||||
int currentDy = 0;
|
||||
|
||||
for (int i = refPyramid.size() - 1; i >= 0; --i) {
|
||||
currentDx *= 2;
|
||||
currentDy *= 2;
|
||||
const GrayImage &ref = refPyramid[i];
|
||||
const GrayImage &tgt = targetPyramid[i];
|
||||
int searchRadius = (i == (int)refPyramid.size() - 1) ? (maxShift >> i) : 2;
|
||||
|
||||
long long bestSAD = std::numeric_limits<long long>::max();
|
||||
for (int dy = -searchRadius; dy <= searchRadius; ++dy) {
|
||||
for (int dx = -searchRadius; dx <= searchRadius; ++dx) {
|
||||
long long sad = computeSAD(ref, tgt, currentDx + dx, currentDy + dy);
|
||||
if (sad < bestSAD) {
|
||||
bestSAD = sad;
|
||||
globalOffset = {currentDx + dx, currentDy + dy};
|
||||
}
|
||||
}
|
||||
}
|
||||
currentDx = globalOffset.x;
|
||||
currentDy = globalOffset.y;
|
||||
}
|
||||
LOGD("Frame global alignment: %d, %d", globalOffset.x, globalOffset.y);
|
||||
|
||||
// 2. Refine per tile using the global offset as a starting point
|
||||
// We refine at level 1 (1/2 size) for better speed/robustness balance
|
||||
const GrayImage &refL1 = refPyramid[1];
|
||||
const GrayImage &tgtL1 = targetPyramid[1];
|
||||
int tSizeL1 = tileSize / 2;
|
||||
int gDxL1 = globalOffset.x / 2;
|
||||
int gDyL1 = globalOffset.y / 2;
|
||||
|
||||
for (int ty = 0; ty < gridH; ++ty) {
|
||||
for (int tx = 0; tx < gridW; ++tx) {
|
||||
int refX = tx * tSizeL1;
|
||||
int refY = ty * tSizeL1;
|
||||
|
||||
long long bestSAD = std::numeric_limits<long long>::max();
|
||||
Point bestOffset = {globalOffset.x, globalOffset.y};
|
||||
|
||||
// Search range around global offset at level 1
|
||||
for (int dy = -2; dy <= 2; ++dy) {
|
||||
for (int dx = -2; dx <= 2; ++dx) {
|
||||
long long sad = computeBlockSAD(refL1, tgtL1, refX, refY, tSizeL1,
|
||||
tSizeL1, gDxL1 + dx, gDyL1 + dy);
|
||||
if (sad < bestSAD) {
|
||||
bestSAD = sad;
|
||||
bestOffset = {(gDxL1 + dx) * 2, (gDyL1 + dy) * 2};
|
||||
}
|
||||
}
|
||||
}
|
||||
alignment.offsets[ty * gridW + tx] = bestOffset;
|
||||
}
|
||||
}
|
||||
|
||||
return alignment;
|
||||
}
|
||||
|
||||
// --- ImageStacker Implementation ---
|
||||
|
||||
ImageStacker::ImageStacker(int width, int height)
|
||||
: width(width), height(height), isFirstFrame(true) {
|
||||
int size = width * height;
|
||||
int uvWidth = width / 2;
|
||||
int uvHeight = height / 2;
|
||||
int uvSize = uvWidth * uvHeight;
|
||||
|
||||
accumY.assign(size, 0);
|
||||
accumU.assign(uvSize, 0);
|
||||
accumV.assign(uvSize, 0);
|
||||
|
||||
weightY.assign(size, 0);
|
||||
weightU.assign(uvSize, 0);
|
||||
weightV.assign(uvSize, 0);
|
||||
|
||||
referenceY.resize(size);
|
||||
referenceU.resize(uvSize);
|
||||
referenceV.resize(uvSize);
|
||||
}
|
||||
|
||||
inline int calculateWeight(int diff) {
|
||||
// Simple de-ghosting weight logic
|
||||
// If diff is small (noise), weight is high.
|
||||
// if diff is large (motion), weight is small.
|
||||
// Using a threshold-based ramp.
|
||||
const int threshold1 = 2000; // ~8 in 0-255 scale
|
||||
const int threshold2 = 8000; // ~31 in 0-255 scale
|
||||
if (diff < threshold1)
|
||||
return 256;
|
||||
if (diff > threshold2)
|
||||
return 0;
|
||||
return 256 * (threshold2 - diff) / (threshold2 - threshold1);
|
||||
}
|
||||
|
||||
void ImageStacker::addFrame(const uint8_t *yData, const uint8_t *uData,
|
||||
const uint8_t *vData, int yRowStride,
|
||||
int uvRowStride, int uvPixelStride, int format) {
|
||||
frameCount++;
|
||||
LOGD("ImageStacker::addFrame #%d starting (w=%d, h=%d, isP010=%d)",
|
||||
frameCount, width, height, (format == 0x36));
|
||||
|
||||
if (!yData || !uData || !vData) {
|
||||
LOGE("ImageStacker::addFrame: Received NULL buffer(s)");
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
for (int r = 0; r < height; ++r) {
|
||||
for (int c = 0; c < width; ++c) {
|
||||
uint16_t val;
|
||||
if (isP010) {
|
||||
val = readValue<uint16_t>(yData + r * yRowStride + c * yPixelStride,
|
||||
false);
|
||||
} else {
|
||||
val = static_cast<uint16_t>(yData[r * yRowStride + c]) << 8;
|
||||
}
|
||||
currentY[r * width + c] = val;
|
||||
image8bit.data[r * width + c] = static_cast<uint8_t>(val >> 8);
|
||||
}
|
||||
}
|
||||
|
||||
if (isFirstFrame) {
|
||||
referenceY = currentY;
|
||||
// Store U, V for reference as well
|
||||
int uvWidth = width / 2;
|
||||
int uvHeight = height / 2;
|
||||
referenceU.resize(uvWidth * uvHeight);
|
||||
referenceV.resize(uvWidth * uvHeight);
|
||||
|
||||
for (int r = 0; r < uvHeight; ++r) {
|
||||
for (int c = 0; c < uvWidth; ++c) {
|
||||
if (isP010) {
|
||||
referenceU[r * uvWidth + c] = readValue<uint16_t>(
|
||||
uData + r * uvRowStride + c * uvPixelStride, false);
|
||||
referenceV[r * uvWidth + c] = readValue<uint16_t>(
|
||||
vData + r * uvRowStride + c * uvPixelStride, false);
|
||||
} else {
|
||||
referenceU[r * uvWidth + c] =
|
||||
static_cast<uint16_t>(uData[r * uvRowStride + c * uvPixelStride])
|
||||
<< 8;
|
||||
referenceV[r * uvWidth + c] =
|
||||
static_cast<uint16_t>(vData[r * uvRowStride + c * uvPixelStride])
|
||||
<< 8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
referencePyramid = buildPyramid(image8bit.data.data(), width, height, 4);
|
||||
|
||||
// First frame has full weight (exactly copying to accum/weight)
|
||||
for (int i = 0; i < (int)accumY.size(); ++i) {
|
||||
accumY[i] = (int32_t)referenceY[i] * 256;
|
||||
weightY[i] = 256;
|
||||
}
|
||||
for (int i = 0; i < (int)accumU.size(); ++i) {
|
||||
accumU[i] = (int32_t)referenceU[i] * 256;
|
||||
weightU[i] = 256;
|
||||
accumV[i] = (int32_t)referenceV[i] * 256;
|
||||
weightV[i] = 256;
|
||||
}
|
||||
isFirstFrame = false;
|
||||
LOGD("ImageStacker::addFrame: First frame initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
// Align current frame against reference
|
||||
std::vector<GrayImage> currentPyramid =
|
||||
buildPyramid(image8bit.data.data(), width, height, 4);
|
||||
TileAlignment alignment =
|
||||
computeTileAlignment(referencePyramid, currentPyramid, 64);
|
||||
LOGD("ImageStacker::addFrame: Alignment completed, merging planes");
|
||||
|
||||
// Merge with Robust Weighting
|
||||
// Y Plane
|
||||
for (int y = 0; y < height; ++y) {
|
||||
for (int x = 0; x < width; ++x) {
|
||||
Point offset = alignment.getOffset(x, y);
|
||||
int tx = x + offset.x;
|
||||
int ty = y + offset.y;
|
||||
|
||||
int destIdx = y * width + x;
|
||||
if (tx >= 0 && tx < width && ty >= 0 && ty < height &&
|
||||
destIdx < (int)accumY.size()) {
|
||||
uint16_t targetVal = currentY[ty * width + tx];
|
||||
uint16_t refVal = referenceY[destIdx];
|
||||
int diff = std::abs((int)targetVal - (int)refVal);
|
||||
int weight = calculateWeight(diff);
|
||||
|
||||
accumY[destIdx] += (int32_t)targetVal * weight;
|
||||
weightY[destIdx] += weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UV Planes (subsampled)
|
||||
int uvWidth = width / 2;
|
||||
int uvHeight = height / 2;
|
||||
int uvSize = uvWidth * uvHeight;
|
||||
|
||||
for (int y = 0; y < uvHeight; ++y) {
|
||||
for (int x = 0; x < uvWidth; ++x) {
|
||||
Point offset = alignment.getOffset(x * 2, y * 2);
|
||||
int tx = x + offset.x / 2;
|
||||
int ty = y + offset.y / 2;
|
||||
|
||||
int destIdx = y * uvWidth + x;
|
||||
if (tx >= 0 && tx < uvWidth && ty >= 0 && ty < uvHeight &&
|
||||
destIdx < uvSize) {
|
||||
uint16_t targetU, targetV;
|
||||
if (isP010) {
|
||||
targetU = readValue<uint16_t>(
|
||||
uData + ty * uvRowStride + tx * uvPixelStride, false);
|
||||
targetV = readValue<uint16_t>(
|
||||
vData + ty * uvRowStride + tx * uvPixelStride, false);
|
||||
} else {
|
||||
targetU = static_cast<uint16_t>(
|
||||
uData[ty * uvRowStride + tx * uvPixelStride])
|
||||
<< 8;
|
||||
targetV = static_cast<uint16_t>(
|
||||
vData[ty * uvRowStride + tx * uvPixelStride])
|
||||
<< 8;
|
||||
}
|
||||
|
||||
uint16_t refU = referenceU[y * uvWidth + x];
|
||||
uint16_t refV = referenceV[y * uvWidth + x];
|
||||
|
||||
// Use Y weight or compute independent weight?
|
||||
// For simplicity, let's use a weight based on UV difference or just
|
||||
// reuse Y weight from nearby. Actually, UV de-ghosting is often linked
|
||||
// to Y. Let's compute a simple UV weight.
|
||||
int diffU = std::abs((int)targetU - (int)refU);
|
||||
int diffV = std::abs((int)targetV - (int)refV);
|
||||
int weight = calculateWeight(std::max(diffU, diffV));
|
||||
|
||||
// Note: we could also use the weight from the corresponding Y pixel to
|
||||
// be more robust.
|
||||
|
||||
accumU[y * uvWidth + x] += (int32_t)targetU * weight;
|
||||
weightU[y * uvWidth + x] += weight;
|
||||
accumV[y * uvWidth + x] += (int32_t)targetV * weight;
|
||||
weightV[y * uvWidth + x] += weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#include "yuv_utils.h"
|
||||
|
||||
#include "jxl_utils.h"
|
||||
|
||||
void ImageStacker::writeResult(uint32_t *outBitmap, int rotation, int targetWR,
|
||||
int targetHR, const char *outputPath,
|
||||
int *outFinalW, int *outFinalH) {
|
||||
int ySize = width * height;
|
||||
int uvWidth = width / 2;
|
||||
int uvHeight = height / 2;
|
||||
int uvSize = uvWidth * uvHeight;
|
||||
|
||||
// 1. Calculate averaged unrotated 16-bit YUV
|
||||
std::vector<uint16_t> iY(ySize);
|
||||
std::vector<uint16_t> iU(uvSize);
|
||||
std::vector<uint16_t> iV(uvSize);
|
||||
|
||||
for (int i = 0; i < ySize; ++i) {
|
||||
iY[i] =
|
||||
(weightY[i] > 0) ? static_cast<uint16_t>(accumY[i] / weightY[i]) : 0;
|
||||
}
|
||||
for (int i = 0; i < uvSize; ++i) {
|
||||
iU[i] = (weightU[i] > 0) ? static_cast<uint16_t>(accumU[i] / weightU[i])
|
||||
: 32768;
|
||||
iV[i] = (weightV[i] > 0) ? static_cast<uint16_t>(accumV[i] / weightV[i])
|
||||
: 32768;
|
||||
}
|
||||
|
||||
// 2. Rotate
|
||||
int rotatedWidth = (rotation == 90 || rotation == 270) ? height : width;
|
||||
int rotatedHeight = (rotation == 90 || rotation == 270) ? width : height;
|
||||
int rotatedUvWidth = rotatedWidth / 2;
|
||||
int rotatedUvHeight = rotatedHeight / 2;
|
||||
|
||||
std::vector<uint16_t> rY(rotatedWidth * rotatedHeight);
|
||||
std::vector<uint16_t> rU(rotatedUvWidth * rotatedUvHeight);
|
||||
std::vector<uint16_t> rV(rotatedUvWidth * rotatedUvHeight);
|
||||
|
||||
RotatePlane16(iY.data(), rY.data(), width, height, rotation);
|
||||
RotatePlane16(iU.data(), rU.data(), uvWidth, uvHeight, rotation);
|
||||
RotatePlane16(iV.data(), rV.data(), uvWidth, uvHeight, rotation);
|
||||
|
||||
// 3. Cropping Calculation (same as processAndSaveYuv)
|
||||
bool currentIsLandscape = (rotatedWidth >= rotatedHeight);
|
||||
int tw, th;
|
||||
if (currentIsLandscape) {
|
||||
tw = (targetWR >= targetHR) ? targetWR : targetHR;
|
||||
th = (targetWR >= targetHR) ? targetHR : targetWR;
|
||||
} else {
|
||||
tw = (targetWR >= targetHR) ? targetHR : targetWR;
|
||||
th = (targetWR >= targetHR) ? targetWR : targetHR;
|
||||
}
|
||||
|
||||
int finalWidth, finalHeight;
|
||||
if ((long long)rotatedWidth * th > (long long)tw * rotatedHeight) {
|
||||
finalHeight = (rotatedHeight / 2) * 2;
|
||||
finalWidth = (int)(((long long)finalHeight * tw / th) / 2) * 2;
|
||||
} else {
|
||||
finalWidth = (rotatedWidth / 2) * 2;
|
||||
finalHeight = (int)(((long long)finalWidth * th / tw) / 2) * 2;
|
||||
}
|
||||
|
||||
if (finalWidth > rotatedWidth)
|
||||
finalWidth = (rotatedWidth / 2) * 2;
|
||||
if (finalHeight > rotatedHeight)
|
||||
finalHeight = (rotatedHeight / 2) * 2;
|
||||
|
||||
if (outFinalW)
|
||||
*outFinalW = finalWidth;
|
||||
if (outFinalH)
|
||||
*outFinalH = finalHeight;
|
||||
|
||||
int cropX = ((rotatedWidth - finalWidth) / 4) * 2;
|
||||
int cropY = ((rotatedHeight - finalHeight) / 4) * 2;
|
||||
|
||||
// 4. Convert and write to outBitmap and optionally to JXL (FP16)
|
||||
std::vector<uint16_t> fp16Pixels;
|
||||
if (outputPath) {
|
||||
fp16Pixels.resize(finalWidth * finalHeight * 4);
|
||||
}
|
||||
|
||||
for (int y = 0; y < finalHeight; y++) {
|
||||
for (int x = 0; x < finalWidth; x++) {
|
||||
int srcY = (cropY + y) * rotatedWidth + (cropX + x);
|
||||
int srcUV = ((cropY + y) / 2) * (rotatedWidth / 2) + ((cropX + x) / 2);
|
||||
|
||||
float Y_val = (float)rY[srcY] / 65535.0f;
|
||||
float U_val = (static_cast<float>(rU[srcUV]) - 32768.0f) / 65535.0f;
|
||||
float V_val = (static_cast<float>(rV[srcUV]) - 32768.0f) / 65535.0f;
|
||||
|
||||
// YUV to RGB (Rec. 601)
|
||||
float R = Y_val + 1.402f * V_val;
|
||||
float G = Y_val - 0.344136f * U_val - 0.714136f * V_val;
|
||||
float B = Y_val + 1.772f * U_val;
|
||||
|
||||
// --- Preview: 8-bit ---
|
||||
if (outBitmap) {
|
||||
uint32_t r8 =
|
||||
static_cast<uint32_t>(std::max(0.0f, std::min(1.0f, R)) * 255.0f);
|
||||
uint32_t g8 =
|
||||
static_cast<uint32_t>(std::max(0.0f, std::min(1.0f, G)) * 255.0f);
|
||||
uint32_t b8 =
|
||||
static_cast<uint32_t>(std::max(0.0f, std::min(1.0f, B)) * 255.0f);
|
||||
outBitmap[y * finalWidth + x] =
|
||||
(0xFF << 24) | (b8 << 16) | (g8 << 8) | r8;
|
||||
}
|
||||
|
||||
// --- Storage: 16-bit JXL ---
|
||||
if (outputPath) {
|
||||
int idx16 = (y * finalWidth + x) * 4;
|
||||
fp16Pixels[idx16 + 0] =
|
||||
static_cast<uint16_t>(std::max(0.0f, std::min(1.0f, R)) * 65535.0f);
|
||||
fp16Pixels[idx16 + 1] =
|
||||
static_cast<uint16_t>(std::max(0.0f, std::min(1.0f, G)) * 65535.0f);
|
||||
fp16Pixels[idx16 + 2] =
|
||||
static_cast<uint16_t>(std::max(0.0f, std::min(1.0f, B)) * 65535.0f);
|
||||
fp16Pixels[idx16 + 3] = 65535; // Alpha
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (outputPath) {
|
||||
saveJxl(fp16Pixels.data(), finalWidth, finalHeight, JXL_TYPE_UINT16,
|
||||
outputPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#ifndef STACKING_UTILS_H
|
||||
#define STACKING_UTILS_H
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
// Represents a 2D point or offset
|
||||
struct Point {
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
|
||||
// Represents a 2D vector field for tile-based alignment
|
||||
struct TileAlignment {
|
||||
int tileWidth;
|
||||
int tileHeight;
|
||||
int gridW;
|
||||
int gridH;
|
||||
std::vector<Point> offsets;
|
||||
|
||||
Point getOffset(int x, int y) const {
|
||||
if (tileWidth <= 0 || tileHeight <= 0 || offsets.empty())
|
||||
return {0, 0};
|
||||
int tx = std::max(0, std::min(x / tileWidth, gridW - 1));
|
||||
int ty = std::max(0, std::min(y / tileHeight, gridH - 1));
|
||||
return offsets[ty * gridW + tx];
|
||||
}
|
||||
};
|
||||
|
||||
// Represents a grayscale image buffer for processing
|
||||
struct GrayImage {
|
||||
std::vector<uint8_t> data;
|
||||
int width;
|
||||
int height;
|
||||
};
|
||||
|
||||
// Build a Gaussian pyramid (downsampled images)
|
||||
std::vector<GrayImage> buildPyramid(const uint8_t *src, int width, int height,
|
||||
int levels);
|
||||
|
||||
// Compute tile-based alignment
|
||||
TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
const std::vector<GrayImage> &targetPyramid,
|
||||
int maxShift);
|
||||
|
||||
class ImageStacker {
|
||||
public:
|
||||
ImageStacker(int width, int height);
|
||||
~ImageStacker() = default;
|
||||
|
||||
// Add a frame to the stack. The first frame becomes the reference.
|
||||
void addFrame(const uint8_t *yData, const uint8_t *uData,
|
||||
const uint8_t *vData, int yRowStride, int uvRowStride,
|
||||
int uvPixelStride, int format);
|
||||
|
||||
// Write the result to an ARGB8888 bitmap buffer with rotation and cropping
|
||||
void writeResult(uint32_t *outBitmap, int rotation, int targetWR,
|
||||
int targetHR, const char *outputPath = nullptr,
|
||||
int *outFinalW = nullptr, int *outFinalH = nullptr);
|
||||
|
||||
private:
|
||||
int width;
|
||||
int height;
|
||||
bool isFirstFrame;
|
||||
int frameCount = 0;
|
||||
|
||||
// Reference frame data for de-ghosting and alignment
|
||||
std::vector<GrayImage> referencePyramid;
|
||||
std::vector<uint16_t> referenceY; // Store in 16-bit to match accum logic
|
||||
std::vector<uint16_t> referenceU;
|
||||
std::vector<uint16_t> referenceV;
|
||||
|
||||
// Accumulation buffers (32-bit for sum)
|
||||
std::vector<int32_t> accumY;
|
||||
std::vector<int32_t> accumU;
|
||||
std::vector<int32_t> accumV;
|
||||
|
||||
// Weight buffers (instead of simple counts)
|
||||
// We'll use 8-bit or 16-bit weights. Let's use 32-bit for accumulated weights
|
||||
// to avoid overflow.
|
||||
std::vector<int32_t> weightY;
|
||||
std::vector<int32_t> weightU;
|
||||
std::vector<int32_t> weightV;
|
||||
};
|
||||
|
||||
#endif // STACKING_UTILS_H
|
||||
@@ -11,9 +11,9 @@ import android.hardware.camera2.params.RggbChannelVector
|
||||
import android.hardware.camera2.params.SessionConfiguration
|
||||
import android.media.Image
|
||||
import android.media.ImageReader
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
@@ -53,6 +53,7 @@ class Camera2Controller(private val context: Context) {
|
||||
|
||||
// 拍照状态机常量
|
||||
private const val STATE_PREVIEW = 0 // Showing camera preview.
|
||||
private const val STATE_WAITING_LOCK = 1 // Waiting for the focus to be locked.
|
||||
private const val STATE_WAITING_PRECAPTURE = 2 // Waiting for the exposure to be precapture state.
|
||||
private const val STATE_WAITING_NON_PRECAPTURE =
|
||||
3 // Waiting for the exposure state to be something other than precapture.
|
||||
@@ -88,7 +89,6 @@ class Camera2Controller(private val context: Context) {
|
||||
|
||||
// 锐化等级 (0=Off, 1=Fast, 2=High Quality, 3=Zero Shutter Lag/Real-time)
|
||||
private var edgeLevel = 1
|
||||
private var useRaw = false
|
||||
|
||||
private var cameraThread: HandlerThread? = null
|
||||
private var cameraHandler: Handler? = null
|
||||
@@ -122,7 +122,7 @@ 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: ((Image, CaptureInfo, CameraCharacteristics?, CaptureResult?) -> Unit)? = null
|
||||
|
||||
// 快门音效播放回调
|
||||
var onPlayShutterSound: (() -> Unit)? = null
|
||||
@@ -147,7 +147,7 @@ class Camera2Controller(private val context: Context) {
|
||||
super.onCaptureCompleted(session, request, result)
|
||||
|
||||
val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
|
||||
if (timestamp != null) {
|
||||
if (timestamp != null && state.value.useRaw && isRawSupported) {
|
||||
val pendingImage = pendingImages.remove(timestamp)
|
||||
if (pendingImage != null) {
|
||||
// 找到了匹配的图像,触发回调
|
||||
@@ -213,19 +213,44 @@ class Camera2Controller(private val context: Context) {
|
||||
* 处理拍照状态机的核心逻辑
|
||||
*/
|
||||
private fun processCaptureState(result: CaptureResult) {
|
||||
val afState = result.get(CaptureResult.CONTROL_AF_STATE) ?: return
|
||||
val aeState = result.get(CaptureResult.CONTROL_AE_STATE) ?: return
|
||||
|
||||
if (aeState != lastAeState) {
|
||||
//Log.d(TAG, "processCaptureState: aeState = $aeState")
|
||||
lastAeState = aeState
|
||||
}
|
||||
|
||||
when (internalCaptureState) {
|
||||
STATE_PREVIEW -> {
|
||||
// 正常预览状态,不做处理
|
||||
}
|
||||
|
||||
STATE_WAITING_LOCK -> {
|
||||
// 等待对焦锁定
|
||||
if (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED ||
|
||||
afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED ||
|
||||
afState == CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED ||
|
||||
afState == CaptureResult.CONTROL_AF_STATE_PASSIVE_UNFOCUSED ||
|
||||
// 部分设备可能不返回 Locked 状态,如果 AF 模式是 OFF,也可以认为对焦完成
|
||||
_state.value.currentAfMode == CaptureRequest.CONTROL_AF_MODE_OFF
|
||||
) {
|
||||
// 对焦完成(成功或失败),尝试预闪或拍照
|
||||
// CONTROL_AE_STATE can be null on some devices
|
||||
if (aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
|
||||
internalCaptureState = STATE_PICTURE_TAKEN
|
||||
runCaptureSequence()
|
||||
} else {
|
||||
runPrecaptureSequence()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
STATE_WAITING_PRECAPTURE -> {
|
||||
// 等待 AE 预取(预闪)完成
|
||||
if (aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
|
||||
if (aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
|
||||
aeState == CaptureResult.CONTROL_AE_STATE_FLASH_REQUIRED
|
||||
) {
|
||||
internalCaptureState = STATE_WAITING_NON_PRECAPTURE
|
||||
}
|
||||
}
|
||||
@@ -240,6 +265,39 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 锁定对焦
|
||||
*/
|
||||
private fun lockFocus() {
|
||||
try {
|
||||
previewRequestBuilder?.let { builder ->
|
||||
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START)
|
||||
internalCaptureState = STATE_WAITING_LOCK
|
||||
captureSession?.capture(builder.build(), previewCallback, cameraHandler)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to lock focus", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解锁对焦
|
||||
*/
|
||||
private fun unlockFocus() {
|
||||
try {
|
||||
previewRequestBuilder?.let { builder ->
|
||||
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL)
|
||||
captureSession?.capture(builder.build(), previewCallback, cameraHandler)
|
||||
|
||||
internalCaptureState = STATE_PREVIEW
|
||||
builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE)
|
||||
captureSession?.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to unlock focus", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行最终的拍照序列
|
||||
*/
|
||||
@@ -254,6 +312,11 @@ class Camera2Controller(private val context: Context) {
|
||||
pendingCaptureReader = null
|
||||
}
|
||||
|
||||
fun captureBurst() {
|
||||
capture()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 运行预取序列(预闪)
|
||||
*/
|
||||
@@ -411,8 +474,12 @@ class Camera2Controller(private val context: Context) {
|
||||
cachedCharacteristics?.get(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION)
|
||||
?: intArrayOf()
|
||||
isRawSupported = capabilities.contains(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)
|
||||
val outputFormats = cachedCharacteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)?.outputFormats ?: intArrayOf()
|
||||
isP010Supported = outputFormats.contains(ImageFormat.YCBCR_P010)
|
||||
val outputFormats =
|
||||
cachedCharacteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)?.outputFormats
|
||||
?: intArrayOf()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
isP010Supported = outputFormats.contains(ImageFormat.YCBCR_P010)
|
||||
}
|
||||
|
||||
PLog.i(
|
||||
TAG, "Camera characteristics cached - ID: $cameraId, Level: $hardwareLevelName, " +
|
||||
@@ -438,7 +505,7 @@ class Camera2Controller(private val context: Context) {
|
||||
|
||||
// 创建 ImageReader 用于拍照
|
||||
// 开启 RAW 开关且设备支持时,优先使用 RAW 格式(更高质量),否则使用 YUV
|
||||
val effectivelyUseRaw = useRaw && isRawSupported
|
||||
val effectivelyUseRaw = state.value.useRaw && isRawSupported
|
||||
val captureSize = if (effectivelyUseRaw) {
|
||||
CameraUtils.getRawCaptureSize(context, cameraId) ?: CameraUtils.getBestCaptureSize(
|
||||
context,
|
||||
@@ -450,7 +517,7 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
val captureFormat = if (effectivelyUseRaw && CameraUtils.getRawCaptureSize(context, cameraId) != null) {
|
||||
ImageFormat.RAW_SENSOR
|
||||
} else if (isP010Supported) {
|
||||
} else if (isP010Supported && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
ImageFormat.YCBCR_P010
|
||||
} else {
|
||||
ImageFormat.YUV_420_888
|
||||
@@ -465,11 +532,12 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
}"
|
||||
)
|
||||
val maxImages = if (state.value.useMultiFrame) state.value.multiFrameCount else 2
|
||||
imageReader = ImageReader.newInstance(
|
||||
captureSize.width,
|
||||
captureSize.height,
|
||||
captureFormat,
|
||||
2
|
||||
maxImages
|
||||
).apply {
|
||||
setOnImageAvailableListener({ reader ->
|
||||
try {
|
||||
@@ -477,22 +545,25 @@ class Camera2Controller(private val context: Context) {
|
||||
// 关键修复:使用 acquireNextImage() 而不是 acquireLatestImage()
|
||||
val image = reader.acquireNextImage()
|
||||
if (image != null) {
|
||||
val timestamp = image.timestamp
|
||||
val pendingResult = pendingResults.remove(timestamp)
|
||||
|
||||
if (pendingResult != null) {
|
||||
// 找到了匹配的结果,触发回调
|
||||
processAndTriggerCapture(image, pendingResult)
|
||||
} else {
|
||||
// 还没找到结果,存入缓存
|
||||
pendingImages[timestamp] = image
|
||||
// 限制缓存大小(防御性,防止内存泄漏)
|
||||
if (pendingImages.size > 5) {
|
||||
val oldestKey = pendingImages.keys.minOrNull()
|
||||
if (oldestKey != null) {
|
||||
pendingImages.remove(oldestKey)?.close()
|
||||
if (state.value.useRaw && isRawSupported) {
|
||||
val timestamp = image.timestamp
|
||||
val pendingResult = pendingResults.remove(timestamp)
|
||||
if (pendingResult != null) {
|
||||
// 找到了匹配的结果,触发回调
|
||||
processAndTriggerCapture(image, pendingResult)
|
||||
} else {
|
||||
// 还没找到结果,存入缓存
|
||||
pendingImages[timestamp] = image
|
||||
// 限制缓存大小(防御性,防止内存泄漏)
|
||||
if (pendingImages.size > 5) {
|
||||
val oldestKey = pendingImages.keys.minOrNull()
|
||||
if (oldestKey != null) {
|
||||
pendingImages.remove(oldestKey)?.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
processAndTriggerCapture(image, null)
|
||||
}
|
||||
} else {
|
||||
PLog.w(TAG, "acquireNextImage() returned null, resetting capture state")
|
||||
@@ -878,7 +949,10 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
|
||||
// 设置连续自动对焦
|
||||
set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
|
||||
val initialAfMode = CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE
|
||||
set(CaptureRequest.CONTROL_AF_MODE, initialAfMode)
|
||||
// 更新 State 中的 AF 模式
|
||||
_state.value = _state.value.copy(currentAfMode = initialAfMode)
|
||||
|
||||
// 应用所有相机参数(曝光、白平衡、闪光灯、变焦、色调映射)
|
||||
applyBaseCameraSettings(this, isCapture = false)
|
||||
@@ -945,6 +1019,9 @@ class Camera2Controller(private val context: Context) {
|
||||
private fun applyBaseCameraSettings(builder: CaptureRequest.Builder, isCapture: Boolean = false) {
|
||||
val currentState = _state.value
|
||||
|
||||
builder.set(CaptureRequest.CONTROL_ENABLE_ZSL, currentState.useMultiFrame)
|
||||
builder.set(CaptureRequest.CONTROL_CAPTURE_INTENT, CaptureRequest.CONTROL_CAPTURE_INTENT_STILL_CAPTURE)
|
||||
|
||||
// 1. 曝光设置
|
||||
applyExposureSettings(builder, currentState, isCapture)
|
||||
|
||||
@@ -982,6 +1059,7 @@ class Camera2Controller(private val context: Context) {
|
||||
if (isCapture) CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH
|
||||
else CaptureRequest.CONTROL_AE_MODE_ON
|
||||
}
|
||||
|
||||
CameraMetadata.FLASH_MODE_TORCH -> CaptureRequest.CONTROL_AE_MODE_ON
|
||||
else -> CaptureRequest.CONTROL_AE_MODE_ON
|
||||
}
|
||||
@@ -1070,9 +1148,11 @@ class Camera2Controller(private val context: Context) {
|
||||
builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF)
|
||||
}
|
||||
}
|
||||
|
||||
CameraMetadata.FLASH_MODE_TORCH -> {
|
||||
builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH)
|
||||
}
|
||||
|
||||
else -> {
|
||||
builder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF)
|
||||
}
|
||||
@@ -1120,7 +1200,6 @@ class Camera2Controller(private val context: Context) {
|
||||
CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE,
|
||||
CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON
|
||||
)
|
||||
PLog.d(TAG, "Enabled Optical Image Stabilization (OIS)")
|
||||
}
|
||||
|
||||
// 2. 处理 EIS (视频/数字防抖)
|
||||
@@ -1211,7 +1290,7 @@ class Camera2Controller(private val context: Context) {
|
||||
* 设置是否使用 RAW 格式拍照
|
||||
*/
|
||||
fun setUseRaw(enabled: Boolean) {
|
||||
useRaw = enabled
|
||||
_state.value = _state.value.copy(useRaw = enabled)
|
||||
PLog.d(TAG, "RAW 格式拍照: $enabled")
|
||||
}
|
||||
|
||||
@@ -1799,8 +1878,10 @@ class Camera2Controller(private val context: Context) {
|
||||
if (maxAeRegions > 0) {
|
||||
set(CaptureRequest.CONTROL_AE_REGIONS, arrayOf(meteringRectangle))
|
||||
}
|
||||
set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO)
|
||||
val afMode = CaptureRequest.CONTROL_AF_MODE_AUTO
|
||||
set(CaptureRequest.CONTROL_AF_MODE, afMode)
|
||||
set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START)
|
||||
_state.value = _state.value.copy(currentAfMode = afMode)
|
||||
updatePreview()
|
||||
}
|
||||
|
||||
@@ -1808,7 +1889,9 @@ class Camera2Controller(private val context: Context) {
|
||||
cameraHandler?.postDelayed({
|
||||
previewRequestBuilder?.apply {
|
||||
set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE)
|
||||
set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
|
||||
val afMode = CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE
|
||||
set(CaptureRequest.CONTROL_AF_MODE, afMode)
|
||||
_state.value = _state.value.copy(currentAfMode = afMode)
|
||||
updatePreview()
|
||||
}
|
||||
_state.value = _state.value.copy(isFocusing = false, focusSuccess = null)
|
||||
@@ -1870,6 +1953,11 @@ 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)
|
||||
}
|
||||
|
||||
|
||||
// ==================== 拍照 ====================
|
||||
|
||||
/**
|
||||
@@ -1925,7 +2013,12 @@ class Camera2Controller(private val context: Context) {
|
||||
*/
|
||||
private fun performCapture(device: CameraDevice, reader: ImageReader) {
|
||||
try {
|
||||
val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply {
|
||||
val template = if (state.value.useMultiFrame) {
|
||||
CameraDevice.TEMPLATE_ZERO_SHUTTER_LAG
|
||||
} else {
|
||||
CameraDevice.TEMPLATE_STILL_CAPTURE
|
||||
}
|
||||
val captureBuilder = device.createCaptureRequest(template).apply {
|
||||
addTarget(reader.surface)
|
||||
|
||||
previewSurface?.let { addTarget(it) }
|
||||
@@ -1956,54 +2049,98 @@ class Camera2Controller(private val context: Context) {
|
||||
)
|
||||
}
|
||||
|
||||
capturePreviewFrame()
|
||||
captureSession?.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() {
|
||||
override fun onCaptureStarted(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
timestamp: Long,
|
||||
frameNumber: Long
|
||||
) {
|
||||
// 关键修复:在 onCaptureStarted 中预先获取 request 中的参数作为 fallback
|
||||
// 这样即使 onCaptureCompleted 晚于 ImageReader 回调,也能提供基本的 EXIF 信息
|
||||
// 注意:这里不能获取到实际的 result,只能从 request 获取设置的参数
|
||||
PLog.d(TAG, "Capture started at frame $frameNumber")
|
||||
if (state.value.useMultiFrame) {
|
||||
// Burst Mode
|
||||
val requests = ArrayList<CaptureRequest>()
|
||||
val request = captureBuilder.build()
|
||||
for (i in 0 until state.value.multiFrameCount) {
|
||||
requests.add(request)
|
||||
}
|
||||
|
||||
override fun onCaptureCompleted(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
result: TotalCaptureResult
|
||||
) {
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
val timestamp = result.get(CaptureResult.SENSOR_TIMESTAMP)
|
||||
if (timestamp != null) {
|
||||
val pendingImage = pendingImages.remove(timestamp)
|
||||
if (pendingImage != null) {
|
||||
processAndTriggerCapture(pendingImage, result)
|
||||
} else {
|
||||
pendingResults[timestamp] = result
|
||||
}
|
||||
captureSession?.captureBurst(requests, object : CameraCaptureSession.CaptureCallback() {
|
||||
override fun onCaptureStarted(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
timestamp: Long,
|
||||
frameNumber: Long
|
||||
) {
|
||||
PLog.d(TAG, "Burst capture started at frame $frameNumber")
|
||||
}
|
||||
lastCaptureResult = result
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Capture completed, result saved"
|
||||
)
|
||||
}
|
||||
|
||||
override fun onCaptureFailed(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
failure: CaptureFailure
|
||||
) {
|
||||
PLog.e(TAG, "Capture failed: ${failure.reason}")
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
override fun onCaptureCompleted(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
result: TotalCaptureResult
|
||||
) {}
|
||||
|
||||
// 拍照失败时重置预览
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
}, cameraHandler)
|
||||
override fun onCaptureSequenceCompleted(
|
||||
session: CameraCaptureSession,
|
||||
sequenceId: Int,
|
||||
frameNumber: Long
|
||||
) {
|
||||
super.onCaptureSequenceCompleted(session, sequenceId, frameNumber)
|
||||
PLog.d(TAG, "Burst sequence completed")
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
|
||||
override fun onCaptureFailed(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
failure: CaptureFailure
|
||||
) {
|
||||
PLog.e(TAG, "Burst Capture failed: ${failure.reason}")
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
}, cameraHandler)
|
||||
|
||||
} else {
|
||||
// Single Capture Mode
|
||||
captureSession?.capture(captureBuilder.build(), object : CameraCaptureSession.CaptureCallback() {
|
||||
override fun onCaptureStarted(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
timestamp: Long,
|
||||
frameNumber: Long
|
||||
) {
|
||||
PLog.d(TAG, "Capture started at frame $frameNumber")
|
||||
}
|
||||
|
||||
override fun onCaptureCompleted(
|
||||
session: CameraCaptureSession,
|
||||
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)
|
||||
if (pendingImage != null) {
|
||||
processAndTriggerCapture(pendingImage, result)
|
||||
} else {
|
||||
pendingResults[timestamp] = result
|
||||
}
|
||||
}
|
||||
lastCaptureResult = result
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Capture completed, result buffered (timestamp: $timestamp). Pending images: ${pendingImages.size}, Pending results: ${pendingResults.size}"
|
||||
)
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
|
||||
override fun onCaptureFailed(
|
||||
session: CameraCaptureSession,
|
||||
request: CaptureRequest,
|
||||
failure: CaptureFailure
|
||||
) {
|
||||
PLog.e(TAG, "Capture failed: ${failure.reason}")
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
}, cameraHandler)
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to perform capture", e)
|
||||
@@ -2040,8 +2177,6 @@ class Camera2Controller(private val context: Context) {
|
||||
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE
|
||||
)
|
||||
session.setRepeatingRequest(builder.build(), previewCallback, cameraHandler)
|
||||
|
||||
PLog.d(TAG, "Preview reset completed (CANCEL -> IDLE)")
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to reset preview", e)
|
||||
}
|
||||
@@ -2093,7 +2228,6 @@ class Camera2Controller(private val context: Context) {
|
||||
// 如果有实时的光圈/焦距,使用实时值
|
||||
result?.get(CaptureResult.LENS_APERTURE)?.let { aperture = it }
|
||||
result?.get(CaptureResult.LENS_FOCAL_LENGTH)?.let {
|
||||
PLog.d(TAG, "buildCaptureInfo: $zoomRatio")
|
||||
focalLength = it * zoomRatio
|
||||
// 重新计算35mm等效焦距
|
||||
try {
|
||||
@@ -2187,8 +2321,7 @@ class Camera2Controller(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun processAndTriggerCapture(image: Image, result: TotalCaptureResult) {
|
||||
val processStartTime = System.currentTimeMillis()
|
||||
private fun processAndTriggerCapture(image: Image, result: TotalCaptureResult?) {
|
||||
try {
|
||||
_state.value = _state.value.copy(isCapturing = false)
|
||||
val width = image.width
|
||||
@@ -2204,10 +2337,6 @@ class Camera2Controller(private val context: Context) {
|
||||
PLog.e(TAG, "Error processing joined capture data", e)
|
||||
image.close()
|
||||
} finally {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Capture data pairing and callback took: ${System.currentTimeMillis() - processStartTime}ms"
|
||||
)
|
||||
resetPreviewAfterCapture()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,6 +131,7 @@ data class CameraState(
|
||||
val focusPoint: Pair<Float, Float>? = null, // normalized coordinates (0-1)
|
||||
val isFocusing: Boolean = false,
|
||||
val focusSuccess: Boolean? = null,
|
||||
val currentAfMode: Int? = null, // 当前的 AF 模式
|
||||
|
||||
//闪光灯
|
||||
val flashMode: Int = 0, // 0: off, 1: auto, 2: torch
|
||||
@@ -170,6 +171,9 @@ data class CameraState(
|
||||
val availableNrModes: IntArray = intArrayOf(),
|
||||
|
||||
val isRawSupported: Boolean = false,
|
||||
val useMultiFrame: Boolean = false,
|
||||
val multiFrameCount: Int = 0,
|
||||
val useRaw: Boolean = false,
|
||||
) {
|
||||
/**
|
||||
* 是否全自动曝光
|
||||
|
||||
@@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.floatPreferencesKey
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -49,7 +50,9 @@ data class UserPreferences(
|
||||
val filterOrder: List<String> = emptyList(), // 滤镜排序(ID列表)
|
||||
val frameOrder: List<String> = emptyList(), // 边框排序(ID列表)
|
||||
val categoryOrder: List<String> = emptyList(), // 分类排序
|
||||
val defaultFocalLength: Float = 0f // 默认焦段 (mm),0表示不设置
|
||||
val defaultFocalLength: Float = 0f, // 默认焦段 (mm),0表示不设置
|
||||
val useMultiFrame: Boolean = false, // 是否使用多帧合成
|
||||
val multiFrameCount: Int = 8 // 多帧合成帧数
|
||||
)
|
||||
|
||||
/**
|
||||
@@ -70,8 +73,8 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
private val VIBRATION_ENABLED = booleanPreferencesKey("vibration_enabled")
|
||||
private val VOLUME_KEY_ACTION = stringPreferencesKey("volume_key_action")
|
||||
private val AUTO_SAVE_AFTER_CAPTURE = booleanPreferencesKey("auto_save_after_capture")
|
||||
private val NR_LEVEL = androidx.datastore.preferences.core.intPreferencesKey("nr_level")
|
||||
private val EDGE_LEVEL = androidx.datastore.preferences.core.intPreferencesKey("edge_level")
|
||||
private val NR_LEVEL = intPreferencesKey("nr_level")
|
||||
private val EDGE_LEVEL = intPreferencesKey("edge_level")
|
||||
private val USE_RAW = booleanPreferencesKey("use_raw")
|
||||
|
||||
// 软件处理参数 Keys
|
||||
@@ -89,6 +92,10 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
|
||||
// 默认焦段 Key
|
||||
private val DEFAULT_FOCAL_LENGTH = floatPreferencesKey("default_focal_length")
|
||||
|
||||
// 多帧合成 Key
|
||||
private val USE_MULTI_FRAME = booleanPreferencesKey("use_multi_frame")
|
||||
private val MULTI_FRAME_COUNT = intPreferencesKey("multi_frame_count")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -122,7 +129,9 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
filterOrder = preferences[FILTER_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList(),
|
||||
frameOrder = preferences[FRAME_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList(),
|
||||
categoryOrder = preferences[CATEGORY_ORDER]?.split(",")?.filter { it.isNotEmpty() } ?: emptyList(),
|
||||
defaultFocalLength = preferences[DEFAULT_FOCAL_LENGTH] ?: 0f
|
||||
defaultFocalLength = preferences[DEFAULT_FOCAL_LENGTH] ?: 0f,
|
||||
useMultiFrame = preferences[USE_MULTI_FRAME] ?: false,
|
||||
multiFrameCount = preferences[MULTI_FRAME_COUNT] ?: 8
|
||||
)
|
||||
}
|
||||
|
||||
@@ -375,4 +384,22 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
preferences[DEFAULT_FOCAL_LENGTH] = focalLength
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存是否使用多帧合成
|
||||
*/
|
||||
suspend fun saveUseMultiFrame(enabled: Boolean) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[USE_MULTI_FRAME] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存多帧合成帧数
|
||||
*/
|
||||
suspend fun saveMultiFrameCount(count: Int) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[MULTI_FRAME_COUNT] = count
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import android.provider.MediaStore
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.processor.MultiFrameStacker
|
||||
import com.hinnka.mycamera.utils.BitmapUtils
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.RawProcessor
|
||||
@@ -28,7 +29,6 @@ import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* 照片管理器
|
||||
@@ -212,7 +212,7 @@ object PhotoManager {
|
||||
rotation: Int,
|
||||
aspectRatio: AspectRatio,
|
||||
characteristics: CameraCharacteristics,
|
||||
captureResult: CaptureResult,
|
||||
captureResult: CaptureResult?,
|
||||
shouldAutoSave: Boolean = true,
|
||||
photoProcessor: PhotoProcessor,
|
||||
sharpeningValue: Float,
|
||||
@@ -232,11 +232,13 @@ object PhotoManager {
|
||||
|
||||
val format = image.format
|
||||
|
||||
if (thumbnail != null) {
|
||||
if (thumbnail != null && !thumbnail.isRecycled) {
|
||||
generateThumbnail(thumbnail, thumbnailFile)
|
||||
} else {
|
||||
PLog.d(TAG, "Thumbnail unavailable: $thumbnail")
|
||||
}
|
||||
|
||||
val cropRegion = captureResult.get(CaptureResult.SCALER_CROP_REGION)
|
||||
val cropRegion = captureResult?.get(CaptureResult.SCALER_CROP_REGION)
|
||||
|
||||
// 根据图像格式处理
|
||||
when (format) {
|
||||
@@ -288,6 +290,7 @@ object PhotoManager {
|
||||
}
|
||||
|
||||
ImageFormat.RAW_SENSOR, ImageFormat.RAW10, ImageFormat.RAW12 -> {
|
||||
captureResult ?: return null
|
||||
val dimensions =
|
||||
BitmapUtils.calculateProcessedRect(image.width, image.height, aspectRatio, cropRegion, rotation)
|
||||
processingScope.launch(Dispatchers.IO) {
|
||||
@@ -358,431 +361,520 @@ object PhotoManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 512x512 缩略图
|
||||
*/
|
||||
private suspend fun generateThumbnail(bitmap: Bitmap, targetFile: File) {
|
||||
withContext(Dispatchers.IO) {
|
||||
|
||||
/**
|
||||
* 保存堆栈合成后的照片
|
||||
*/
|
||||
suspend fun saveStackedPhoto(
|
||||
context: Context,
|
||||
images: List<Image>,
|
||||
thumbnail: Bitmap?,
|
||||
metadata: PhotoMetadata,
|
||||
rotation: Int,
|
||||
aspectRatio: AspectRatio,
|
||||
shouldAutoSave: Boolean = true,
|
||||
photoProcessor: PhotoProcessor,
|
||||
sharpeningValue: Float,
|
||||
noiseReductionValue: Float,
|
||||
chromaNoiseReductionValue: Float,
|
||||
): String? {
|
||||
return try {
|
||||
val photoId = UUID.randomUUID().toString()
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
|
||||
// 预先准备所有文件路径
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val yuvFile = File(photoDir, YUV_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")
|
||||
}
|
||||
|
||||
processingScope.launch(Dispatchers.IO) {
|
||||
try {
|
||||
// 生成 512x512 缩略图
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, 512, 512)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
photoFile.createNewFile()
|
||||
val dimensions =
|
||||
BitmapUtils.calculateProcessedRect(images[0].width, images[0].height, aspectRatio, null, rotation)
|
||||
val finalWidth = dimensions.width()
|
||||
val finalHeight = dimensions.height()
|
||||
|
||||
val result = MultiFrameStacker.processBurst(
|
||||
images,
|
||||
rotation,
|
||||
aspectRatio,
|
||||
yuvFile.absolutePath
|
||||
)
|
||||
|
||||
result ?: return@launch
|
||||
|
||||
// 保存元数据
|
||||
val metadataWithInfo = metadata.copy(
|
||||
width = finalWidth,
|
||||
height = finalHeight,
|
||||
ratio = aspectRatio,
|
||||
)
|
||||
metadataFile.writeText(metadataWithInfo.toJson())
|
||||
// Generate Thumbnail
|
||||
if (thumbnail == null) {
|
||||
generateThumbnail(result, thumbnailFile)
|
||||
}
|
||||
thumbnail.recycle()
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to generate thumbnail", e)
|
||||
// Save Original (Stacked Result)
|
||||
FileOutputStream(photoFile).use { outputStream ->
|
||||
result.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)
|
||||
}
|
||||
result.recycle()
|
||||
// Auto Save
|
||||
/*if (shouldAutoSave) {
|
||||
exportPhoto(
|
||||
context,
|
||||
photoId,
|
||||
photoProcessor,
|
||||
metadataWithInfo,
|
||||
sharpeningValue,
|
||||
noiseReductionValue,
|
||||
chromaNoiseReductionValue
|
||||
)
|
||||
}*/
|
||||
} finally {
|
||||
images.forEach { it.close() }
|
||||
}
|
||||
}
|
||||
photoId
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save stacked photo", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成缩略图
|
||||
*/
|
||||
private fun generateThumbnail(sourceFile: File, targetFile: File) {
|
||||
/**
|
||||
* 生成 512x512 缩略图
|
||||
*/
|
||||
private suspend fun generateThumbnail(bitmap: Bitmap, targetFile: File) {
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeFile(sourceFile.absolutePath, options)
|
||||
|
||||
// 计算缩放比例,缩略图大小 512x512
|
||||
val targetSize = 512
|
||||
options.inSampleSize = calculateInSampleSize(options, targetSize, targetSize)
|
||||
options.inJustDecodeBounds = false
|
||||
|
||||
val bitmap = BitmapFactory.decodeFile(sourceFile.absolutePath, options)
|
||||
|
||||
if (bitmap != null) {
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, targetSize, targetSize)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
}
|
||||
bitmap.recycle()
|
||||
thumbnail.recycle()
|
||||
// 生成 512x512 缩略图
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, 512, 512)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
}
|
||||
thumbnail.recycle()
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to generate thumbnail", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
|
||||
val (height: Int, width: Int) = options.outHeight to options.outWidth
|
||||
var inSampleSize = 1
|
||||
|
||||
if (height > reqHeight || width > reqWidth) {
|
||||
val halfHeight: Int = height / 2
|
||||
val halfWidth: Int = width / 2
|
||||
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
/**
|
||||
* 生成缩略图
|
||||
*/
|
||||
private fun generateThumbnail(sourceFile: File, targetFile: File) {
|
||||
try {
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
return inSampleSize
|
||||
}
|
||||
BitmapFactory.decodeFile(sourceFile.absolutePath, options)
|
||||
|
||||
/**
|
||||
* 获取所有照片 ID 列表(按时间降序)
|
||||
*/
|
||||
fun getPhotoIds(context: Context): List<String> {
|
||||
val baseDir = getPhotosBaseDir(context)
|
||||
return baseDir.listFiles()
|
||||
?.filter { it.isDirectory }
|
||||
?.sortedByDescending { it.lastModified() }
|
||||
?.map { it.name }
|
||||
?: emptyList()
|
||||
}
|
||||
// 计算缩放比例,缩略图大小 512x512
|
||||
val targetSize = 512
|
||||
options.inSampleSize = calculateInSampleSize(options, targetSize, targetSize)
|
||||
options.inJustDecodeBounds = false
|
||||
|
||||
/**
|
||||
* 创建删除系统相册照片的请求(弹出确认对话框)
|
||||
*
|
||||
* 仅适用于 Android 11+ (API 30+)
|
||||
* 返回 PendingIntent,需要在 Activity 中通过 startIntentSenderForResult 启动
|
||||
*/
|
||||
fun createDeleteRequest(context: Context, photoId: String): PendingIntent? {
|
||||
return try {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
PLog.w(TAG, "createDeleteRequest requires Android 11+")
|
||||
return null
|
||||
val bitmap = BitmapFactory.decodeFile(sourceFile.absolutePath, options)
|
||||
|
||||
if (bitmap != null) {
|
||||
val thumbnail = ThumbnailUtils.extractThumbnail(bitmap, targetSize, targetSize)
|
||||
FileOutputStream(targetFile).use { out ->
|
||||
thumbnail.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
}
|
||||
|
||||
// 加载元数据,获取导出的 URI 列表(使用 runBlocking 同步调用)
|
||||
val metadata = runBlocking {
|
||||
loadMetadata(context, photoId)
|
||||
}
|
||||
val exportedUris = metadata?.exportedUris ?: emptyList()
|
||||
|
||||
if (exportedUris.isEmpty()) {
|
||||
PLog.d(TAG, "No exported URIs to delete for photo: $photoId")
|
||||
return null
|
||||
}
|
||||
|
||||
// 将字符串 URI 转换为 Uri 对象列表
|
||||
val uriList = exportedUris.mapNotNull { uriString ->
|
||||
try {
|
||||
Uri.parse(uriString)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Invalid URI: $uriString", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (uriList.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 创建删除请求(会弹出系统确认对话框)
|
||||
MediaStore.createDeleteRequest(context.contentResolver, uriList)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to create delete request for photo: $photoId", e)
|
||||
null
|
||||
bitmap.recycle()
|
||||
thumbnail.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除照片及其所有相关文件
|
||||
*/
|
||||
suspend fun deletePhoto(
|
||||
context: Context,
|
||||
photoId: String
|
||||
): Boolean {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
if (photoDir.exists()) {
|
||||
photoDir.deleteRecursively()
|
||||
}
|
||||
|
||||
PLog.d(TAG, "Photo deleted: $photoId")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to delete photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅删除应用内部的照片,不删除系统相册中的导出照片
|
||||
*/
|
||||
suspend fun deletePhotoOnly(context: Context, photoId: String): Boolean {
|
||||
return deletePhoto(context, photoId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载元数据
|
||||
*/
|
||||
suspend fun loadMetadata(context: Context, photoId: String): PhotoMetadata? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val file = getMetadataFile(context, photoId)
|
||||
if (file.exists()) {
|
||||
PhotoMetadata.fromJson(file.readText())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to load metadata for photo: $photoId", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新元数据
|
||||
*/
|
||||
suspend fun saveMetadata(context: Context, photoId: String, metadata: PhotoMetadata): Boolean {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val file = getMetadataFile(context, photoId)
|
||||
file.writeText(metadata.toJson())
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save metadata for photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadYuvData(context: Context, photoId: String): ShortArray? {
|
||||
val yuvFile = getYuvFile(context, photoId)
|
||||
if (!yuvFile.exists()) {
|
||||
return null
|
||||
}
|
||||
val yuv = YuvProcessor.loadCompressedArgb(yuvFile.absolutePath)
|
||||
return yuv
|
||||
}
|
||||
|
||||
fun loadBitmap(context: Context, photoId: String): Bitmap? {
|
||||
val photoFile = getPhotoFile(context, photoId)
|
||||
if (!photoFile.exists()) {
|
||||
return null
|
||||
}
|
||||
return BitmapFactory.decodeFile(photoFile.absolutePath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 URI 获取文件名
|
||||
*/
|
||||
private fun getFileName(context: Context, uri: Uri): String? {
|
||||
return try {
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
cursor.moveToFirst()
|
||||
cursor.getString(nameIndex)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从系统相册导入照片
|
||||
*/
|
||||
suspend fun importPhoto(context: Context, uri: Uri): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoId = UUID.randomUUID().toString()
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val dngFile = File(photoDir, DNG_FILE)
|
||||
val metadataFile = File(photoDir, METADATA_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
|
||||
// 1. 检测是否为 RAW 文件
|
||||
val mimeType = context.contentResolver.getType(uri)
|
||||
val fileName = getFileName(context, uri) ?: ""
|
||||
val isRaw = mimeType?.contains("raw", ignoreCase = true) == true ||
|
||||
mimeType?.contains("dng", ignoreCase = true) == true ||
|
||||
fileName.endsWith(".dng", ignoreCase = true)
|
||||
|
||||
if (isRaw) {
|
||||
// --- RAW 处理逻辑 ---
|
||||
// 1. 复制 RAW 文件
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(dngFile).use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 读取元数据以获取旋转信息
|
||||
val metadata = PhotoMetadata.fromUri(context, uri)
|
||||
val exif = ExifInterface(dngFile.absolutePath)
|
||||
val orientation = exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
val rotation = when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> 90
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> 180
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> 270
|
||||
else -> 0
|
||||
}
|
||||
|
||||
// 3. 处理 RAW 以生成 JPEG 预览
|
||||
val processedBitmap = RawProcessor.process(
|
||||
dngFile.absolutePath,
|
||||
null,
|
||||
null,
|
||||
rotation
|
||||
)
|
||||
|
||||
if (processedBitmap != null) {
|
||||
// 保存为 original.jpg
|
||||
FileOutputStream(photoFile).use { out ->
|
||||
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
|
||||
}
|
||||
|
||||
// 生成缩略图
|
||||
generateThumbnail(processedBitmap, thumbnailFile)
|
||||
|
||||
// 更新元数据
|
||||
val updatedMetadata = metadata.copy(
|
||||
width = processedBitmap.width,
|
||||
height = processedBitmap.height,
|
||||
rotation = rotation,
|
||||
isImported = true
|
||||
)
|
||||
metadataFile.writeText(updatedMetadata.toJson())
|
||||
|
||||
processedBitmap.recycle()
|
||||
} else {
|
||||
// 降级:如果 RAW 处理失败,尝试直接解码(某些 DNG 包含内置预览图)
|
||||
tempImportJpeg(uri, context, photoFile, metadataFile, thumbnailFile)
|
||||
}
|
||||
} else {
|
||||
// --- 常规 JPEG 处理逻辑 ---
|
||||
tempImportJpeg(uri, context, photoFile, metadataFile, thumbnailFile)
|
||||
}
|
||||
|
||||
PLog.d(TAG, "Photo imported: $photoId (isRaw: $isRaw)")
|
||||
photoId
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to import photo", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun tempImportJpeg(
|
||||
uri: Uri,
|
||||
context: Context,
|
||||
photoFile: File,
|
||||
metadataFile: File,
|
||||
thumbnailFile: File
|
||||
) {
|
||||
val photoDir = photoFile.parentFile ?: return
|
||||
val tempFile = File(photoDir, "temp.jpg")
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(tempFile).use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
}
|
||||
|
||||
val exif = ExifInterface(tempFile)
|
||||
val orientation = exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
|
||||
if (orientation != ExifInterface.ORIENTATION_NORMAL &&
|
||||
orientation != ExifInterface.ORIENTATION_UNDEFINED
|
||||
) {
|
||||
val bitmap = BitmapFactory.decodeFile(tempFile.absolutePath)
|
||||
if (bitmap != null) {
|
||||
val rotatedBitmap = rotateImageIfRequired(bitmap, orientation)
|
||||
FileOutputStream(photoFile).use { out ->
|
||||
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
|
||||
}
|
||||
val newExif = ExifInterface(photoFile)
|
||||
newExif.setAttribute(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL.toString()
|
||||
)
|
||||
newExif.saveAttributes()
|
||||
|
||||
if (rotatedBitmap != bitmap) {
|
||||
rotatedBitmap.recycle()
|
||||
}
|
||||
bitmap.recycle()
|
||||
} else {
|
||||
tempFile.copyTo(photoFile, overwrite = true)
|
||||
}
|
||||
} else {
|
||||
tempFile.renameTo(photoFile)
|
||||
}
|
||||
|
||||
if (tempFile.exists()) {
|
||||
tempFile.delete()
|
||||
}
|
||||
|
||||
val metadata = PhotoMetadata.fromUri(context, uri)
|
||||
metadataFile.writeText(metadata.toJson())
|
||||
generateThumbnail(photoFile, thumbnailFile)
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 EXIF 方向信息旋转图片
|
||||
*/
|
||||
private fun rotateImageIfRequired(img: Bitmap, orientation: Int): Bitmap {
|
||||
return when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> {
|
||||
rotateImage(img, 90f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> {
|
||||
rotateImage(img, 180f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> {
|
||||
rotateImage(img, 270f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
|
||||
flipImage(img, horizontal = true, vertical = false)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
|
||||
flipImage(img, horizontal = false, vertical = true)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
||||
// 先水平翻转,再旋转 270 度
|
||||
val flipped = flipImage(img, horizontal = true, vertical = false)
|
||||
val rotated = rotateImage(flipped, 270f)
|
||||
if (flipped != img) flipped.recycle()
|
||||
rotated
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
||||
// 先垂直翻转,再旋转 270 度
|
||||
val flipped = flipImage(img, horizontal = false, vertical = true)
|
||||
val rotated = rotateImage(flipped, 270f)
|
||||
if (flipped != img) flipped.recycle()
|
||||
rotated
|
||||
}
|
||||
|
||||
else -> img
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 旋转图片
|
||||
*/
|
||||
private fun rotateImage(img: Bitmap, degree: Float): Bitmap {
|
||||
val matrix = Matrix()
|
||||
matrix.postRotate(degree)
|
||||
return Bitmap.createBitmap(img, 0, 0, img.width, img.height, matrix, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 翻转图片
|
||||
*/
|
||||
private fun flipImage(img: Bitmap, horizontal: Boolean, vertical: Boolean): Bitmap {
|
||||
val matrix = Matrix()
|
||||
matrix.postScale(
|
||||
if (horizontal) -1f else 1f,
|
||||
if (vertical) -1f else 1f
|
||||
)
|
||||
return Bitmap.createBitmap(img, 0, 0, img.width, img.height, matrix, true)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to generate thumbnail", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
|
||||
val (height: Int, width: Int) = options.outHeight to options.outWidth
|
||||
var inSampleSize = 1
|
||||
|
||||
if (height > reqHeight || width > reqWidth) {
|
||||
val halfHeight: Int = height / 2
|
||||
val halfWidth: Int = width / 2
|
||||
while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
return inSampleSize
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有照片 ID 列表(按时间降序)
|
||||
*/
|
||||
fun getPhotoIds(context: Context): List<String> {
|
||||
val baseDir = getPhotosBaseDir(context)
|
||||
return baseDir.listFiles()
|
||||
?.filter { it.isDirectory }
|
||||
?.sortedByDescending { it.lastModified() }
|
||||
?.map { it.name }
|
||||
?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建删除系统相册照片的请求(弹出确认对话框)
|
||||
*
|
||||
* 仅适用于 Android 11+ (API 30+)
|
||||
* 返回 PendingIntent,需要在 Activity 中通过 startIntentSenderForResult 启动
|
||||
*/
|
||||
fun createDeleteRequest(context: Context, photoId: String): PendingIntent? {
|
||||
return try {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||
PLog.w(TAG, "createDeleteRequest requires Android 11+")
|
||||
return null
|
||||
}
|
||||
|
||||
// 加载元数据,获取导出的 URI 列表(使用 runBlocking 同步调用)
|
||||
val metadata = runBlocking {
|
||||
loadMetadata(context, photoId)
|
||||
}
|
||||
val exportedUris = metadata?.exportedUris ?: emptyList()
|
||||
|
||||
if (exportedUris.isEmpty()) {
|
||||
PLog.d(TAG, "No exported URIs to delete for photo: $photoId")
|
||||
return null
|
||||
}
|
||||
|
||||
// 将字符串 URI 转换为 Uri 对象列表
|
||||
val uriList = exportedUris.mapNotNull { uriString ->
|
||||
try {
|
||||
Uri.parse(uriString)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Invalid URI: $uriString", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
if (uriList.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
|
||||
// 创建删除请求(会弹出系统确认对话框)
|
||||
MediaStore.createDeleteRequest(context.contentResolver, uriList)
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to create delete request for photo: $photoId", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除照片及其所有相关文件
|
||||
*/
|
||||
suspend fun deletePhoto(
|
||||
context: Context,
|
||||
photoId: String
|
||||
): Boolean {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
if (photoDir.exists()) {
|
||||
photoDir.deleteRecursively()
|
||||
}
|
||||
|
||||
PLog.d(TAG, "Photo deleted: $photoId")
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to delete photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅删除应用内部的照片,不删除系统相册中的导出照片
|
||||
*/
|
||||
suspend fun deletePhotoOnly(context: Context, photoId: String): Boolean {
|
||||
return deletePhoto(context, photoId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载元数据
|
||||
*/
|
||||
suspend fun loadMetadata(context: Context, photoId: String): PhotoMetadata? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val file = getMetadataFile(context, photoId)
|
||||
if (file.exists()) {
|
||||
PhotoMetadata.fromJson(file.readText())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to load metadata for photo: $photoId", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新元数据
|
||||
*/
|
||||
suspend fun saveMetadata(context: Context, photoId: String, metadata: PhotoMetadata): Boolean {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val file = getMetadataFile(context, photoId)
|
||||
file.writeText(metadata.toJson())
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save metadata for photo: $photoId", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun loadYuvData(context: Context, photoId: String): ShortArray? {
|
||||
val yuvFile = getYuvFile(context, photoId)
|
||||
if (!yuvFile.exists()) {
|
||||
return null
|
||||
}
|
||||
val yuv = YuvProcessor.loadCompressedArgb(yuvFile.absolutePath)
|
||||
return yuv
|
||||
}
|
||||
|
||||
fun loadBitmap(context: Context, photoId: String): Bitmap? {
|
||||
val photoFile = getPhotoFile(context, photoId)
|
||||
if (!photoFile.exists()) {
|
||||
return null
|
||||
}
|
||||
return BitmapFactory.decodeFile(photoFile.absolutePath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 URI 获取文件名
|
||||
*/
|
||||
private fun getFileName(context: Context, uri: Uri): String? {
|
||||
return try {
|
||||
context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
|
||||
val nameIndex = cursor.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
|
||||
cursor.moveToFirst()
|
||||
cursor.getString(nameIndex)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从系统相册导入照片
|
||||
*/
|
||||
suspend fun importPhoto(context: Context, uri: Uri): String? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val photoId = UUID.randomUUID().toString()
|
||||
val photoDir = getPhotoDir(context, photoId)
|
||||
val photoFile = File(photoDir, PHOTO_FILE)
|
||||
val dngFile = File(photoDir, DNG_FILE)
|
||||
val metadataFile = File(photoDir, METADATA_FILE)
|
||||
val thumbnailFile = File(photoDir, THUMBNAIL_FILE)
|
||||
|
||||
// 1. 检测是否为 RAW 文件
|
||||
val mimeType = context.contentResolver.getType(uri)
|
||||
val fileName = getFileName(context, uri) ?: ""
|
||||
val isRaw = mimeType?.contains("raw", ignoreCase = true) == true ||
|
||||
mimeType?.contains("dng", ignoreCase = true) == true ||
|
||||
fileName.endsWith(".dng", ignoreCase = true)
|
||||
|
||||
if (isRaw) {
|
||||
// --- RAW 处理逻辑 ---
|
||||
// 1. 复制 RAW 文件
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(dngFile).use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 读取元数据以获取旋转信息
|
||||
val metadata = PhotoMetadata.fromUri(context, uri)
|
||||
val exif = ExifInterface(dngFile.absolutePath)
|
||||
val orientation = exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
val rotation = when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> 90
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> 180
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> 270
|
||||
else -> 0
|
||||
}
|
||||
|
||||
// 3. 处理 RAW 以生成 JPEG 预览
|
||||
val processedBitmap = RawProcessor.process(
|
||||
dngFile.absolutePath,
|
||||
null,
|
||||
null,
|
||||
rotation
|
||||
)
|
||||
|
||||
if (processedBitmap != null) {
|
||||
// 保存为 original.jpg
|
||||
FileOutputStream(photoFile).use { out ->
|
||||
processedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
|
||||
}
|
||||
|
||||
// 生成缩略图
|
||||
generateThumbnail(processedBitmap, thumbnailFile)
|
||||
|
||||
// 更新元数据
|
||||
val updatedMetadata = metadata.copy(
|
||||
width = processedBitmap.width,
|
||||
height = processedBitmap.height,
|
||||
rotation = rotation,
|
||||
isImported = true
|
||||
)
|
||||
metadataFile.writeText(updatedMetadata.toJson())
|
||||
|
||||
processedBitmap.recycle()
|
||||
} else {
|
||||
// 降级:如果 RAW 处理失败,尝试直接解码(某些 DNG 包含内置预览图)
|
||||
tempImportJpeg(uri, context, photoFile, metadataFile, thumbnailFile)
|
||||
}
|
||||
} else {
|
||||
// --- 常规 JPEG 处理逻辑 ---
|
||||
tempImportJpeg(uri, context, photoFile, metadataFile, thumbnailFile)
|
||||
}
|
||||
|
||||
PLog.d(TAG, "Photo imported: $photoId (isRaw: $isRaw)")
|
||||
photoId
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to import photo", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun tempImportJpeg(
|
||||
uri: Uri,
|
||||
context: Context,
|
||||
photoFile: File,
|
||||
metadataFile: File,
|
||||
thumbnailFile: File
|
||||
) {
|
||||
val photoDir = photoFile.parentFile ?: return
|
||||
val tempFile = File(photoDir, "temp.jpg")
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
FileOutputStream(tempFile).use { output ->
|
||||
input.copyTo(output)
|
||||
}
|
||||
}
|
||||
|
||||
val exif = ExifInterface(tempFile)
|
||||
val orientation = exif.getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
)
|
||||
|
||||
if (orientation != ExifInterface.ORIENTATION_NORMAL &&
|
||||
orientation != ExifInterface.ORIENTATION_UNDEFINED
|
||||
) {
|
||||
val bitmap = BitmapFactory.decodeFile(tempFile.absolutePath)
|
||||
if (bitmap != null) {
|
||||
val rotatedBitmap = rotateImageIfRequired(bitmap, orientation)
|
||||
FileOutputStream(photoFile).use { out ->
|
||||
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
|
||||
}
|
||||
val newExif = ExifInterface(photoFile)
|
||||
newExif.setAttribute(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL.toString()
|
||||
)
|
||||
newExif.saveAttributes()
|
||||
|
||||
if (rotatedBitmap != bitmap) {
|
||||
rotatedBitmap.recycle()
|
||||
}
|
||||
bitmap.recycle()
|
||||
} else {
|
||||
tempFile.copyTo(photoFile, overwrite = true)
|
||||
}
|
||||
} else {
|
||||
tempFile.renameTo(photoFile)
|
||||
}
|
||||
|
||||
if (tempFile.exists()) {
|
||||
tempFile.delete()
|
||||
}
|
||||
|
||||
val metadata = PhotoMetadata.fromUri(context, uri)
|
||||
metadataFile.writeText(metadata.toJson())
|
||||
generateThumbnail(photoFile, thumbnailFile)
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 EXIF 方向信息旋转图片
|
||||
*/
|
||||
private fun rotateImageIfRequired(img: Bitmap, orientation: Int): Bitmap {
|
||||
return when (orientation) {
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> {
|
||||
rotateImage(img, 90f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> {
|
||||
rotateImage(img, 180f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> {
|
||||
rotateImage(img, 270f)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
|
||||
flipImage(img, horizontal = true, vertical = false)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
|
||||
flipImage(img, horizontal = false, vertical = true)
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
||||
// 先水平翻转,再旋转 270 度
|
||||
val flipped = flipImage(img, horizontal = true, vertical = false)
|
||||
val rotated = rotateImage(flipped, 270f)
|
||||
if (flipped != img) flipped.recycle()
|
||||
rotated
|
||||
}
|
||||
|
||||
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
||||
// 先垂直翻转,再旋转 270 度
|
||||
val flipped = flipImage(img, horizontal = false, vertical = true)
|
||||
val rotated = rotateImage(flipped, 270f)
|
||||
if (flipped != img) flipped.recycle()
|
||||
rotated
|
||||
}
|
||||
|
||||
else -> img
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 旋转图片
|
||||
*/
|
||||
private fun rotateImage(img: Bitmap, degree: Float): Bitmap {
|
||||
val matrix = Matrix()
|
||||
matrix.postRotate(degree)
|
||||
return Bitmap.createBitmap(img, 0, 0, img.width, img.height, matrix, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 翻转图片
|
||||
*/
|
||||
private fun flipImage(img: Bitmap, horizontal: Boolean, vertical: Boolean): Bitmap {
|
||||
val matrix = Matrix()
|
||||
matrix.postScale(
|
||||
if (horizontal) -1f else 1f,
|
||||
if (vertical) -1f else 1f
|
||||
)
|
||||
return Bitmap.createBitmap(img, 0, 0, img.width, img.height, matrix, true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.media.Image
|
||||
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.utils.BitmapUtils
|
||||
|
||||
/**
|
||||
* Multi-Frame Stacker
|
||||
*
|
||||
* Manages the native stacking process for burst captures.
|
||||
* Aligns and merges multiple frames to reduce noise and improve quality.
|
||||
*/
|
||||
object MultiFrameStacker {
|
||||
private const val TAG = "MultiFrameStacker"
|
||||
|
||||
init {
|
||||
try {
|
||||
System.loadLibrary("my-native-lib")
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
PLog.e(TAG, "Failed to load native library", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a burst of images and return a stacked Bitmap.
|
||||
*
|
||||
* @param images List of captured Images (YUV_420_888).
|
||||
* @return Stacked Bitmap (ARGB_8888), or null if failed.
|
||||
*/
|
||||
fun processBurst(
|
||||
images: List<Image>,
|
||||
rotation: Int,
|
||||
aspectRatio: AspectRatio?,
|
||||
outputPath: String? = null
|
||||
): Bitmap? {
|
||||
if (images.isEmpty()) return null
|
||||
|
||||
val width = images[0].width
|
||||
val height = images[0].height
|
||||
|
||||
PLog.i(TAG, "Starting stacking process for ${images.size} frames ($width x $height)")
|
||||
val startTime = System.currentTimeMillis()
|
||||
|
||||
val stackerPtr = createStackerNative(width, height)
|
||||
if (stackerPtr == 0L) {
|
||||
PLog.e(TAG, "Failed to create native stacker")
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
for ((index, image) in images.withIndex()) {
|
||||
image.use {
|
||||
// Validate dimensions
|
||||
if (image.width != width || image.height != height) {
|
||||
PLog.w(TAG, "Skipping frame $index due to dimension mismatch")
|
||||
continue
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val dimensions = BitmapUtils.calculateProcessedRect(width, height, aspectRatio, null, rotation)
|
||||
val previewBitmap = createBitmap(dimensions.width(), dimensions.height())
|
||||
|
||||
val tw = aspectRatio?.widthRatio ?: width
|
||||
val th = aspectRatio?.heightRatio ?: height
|
||||
|
||||
processStackNative(stackerPtr, previewBitmap, rotation, tw, th, outputPath)
|
||||
|
||||
PLog.i(TAG, "Stacking completed in ${System.currentTimeMillis() - startTime}ms")
|
||||
return previewBitmap
|
||||
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Error during stacking", e)
|
||||
return null
|
||||
} finally {
|
||||
releaseStackerNative(stackerPtr)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Native Methods ---
|
||||
|
||||
private external fun createStackerNative(width: Int, height: Int): Long
|
||||
|
||||
private external fun addToStackNative(
|
||||
stackerPtr: Long,
|
||||
yBuffer: ByteBuffer, uBuffer: ByteBuffer, vBuffer: ByteBuffer,
|
||||
yRowStride: Int, uvRowStride: Int, uvPixelStride: Int,
|
||||
format: Int
|
||||
)
|
||||
|
||||
private external fun processStackNative(
|
||||
stackerPtr: Long,
|
||||
outBitmap: Bitmap?,
|
||||
rotation: Int,
|
||||
targetWR: Int,
|
||||
targetHR: Int,
|
||||
outputPath: String?
|
||||
)
|
||||
|
||||
private external fun releaseStackerNative(stackerPtr: Long)
|
||||
}
|
||||
@@ -78,6 +78,7 @@ 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 backgroundColor = Color(0xFF434A5D)
|
||||
|
||||
@@ -91,7 +92,7 @@ fun CameraScreen(
|
||||
// 当打开滤镜面板时,生成预览图
|
||||
LaunchedEffect(activePanel) {
|
||||
if (activePanel == ActivePanel.FILTERS) {
|
||||
viewModel.captureAndGenerateLutPreviews()
|
||||
viewModel.generateThumbnail()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,7 +401,9 @@ fun CameraScreen(
|
||||
onMoreSettingsClick = {
|
||||
activePanel = ActivePanel.NONE
|
||||
onSettingsClick()
|
||||
}
|
||||
},
|
||||
useMultiFrame = useMultiFrame,
|
||||
onMultiFrameToggle = { viewModel.setUseMultiFrame(it) }
|
||||
)
|
||||
|
||||
// LutControlPanel 显示在遮罩层之上,确保能接收点击事件
|
||||
|
||||
@@ -38,6 +38,8 @@ fun CameraTopSheet(
|
||||
onNRLevelChange: (Int) -> Unit,
|
||||
onFilterManageClick: () -> Unit,
|
||||
onMoreSettingsClick: () -> Unit,
|
||||
useMultiFrame: Boolean,
|
||||
onMultiFrameToggle: (Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
@@ -120,6 +122,14 @@ fun CameraTopSheet(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
// Multi-Frame Stacking Toggle
|
||||
QuickSettingToggle(
|
||||
title = stringResource(R.string.settings_use_multi_frame),
|
||||
checked = useMultiFrame,
|
||||
onCheckedChange = onMultiFrameToggle,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
|
||||
// NR Level Cycle
|
||||
val nrLevelNames = availableNrLevels.map {
|
||||
when (it) {
|
||||
@@ -141,7 +151,14 @@ fun CameraTopSheet(
|
||||
},
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
// Filter Management Button
|
||||
QuickSettingButton(
|
||||
title = stringResource(R.string.settings_filter_management),
|
||||
@@ -149,6 +166,7 @@ fun CameraTopSheet(
|
||||
onClick = onFilterManageClick,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
@@ -67,7 +67,7 @@ fun ZoomControlBar(
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp)
|
||||
.padding(8.dp)
|
||||
.height(32.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
|
||||
@@ -36,7 +36,6 @@ import androidx.compose.ui.res.stringResource
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.frame.FrameInfo
|
||||
import com.hinnka.mycamera.ui.camera.autoRotate
|
||||
import com.hinnka.mycamera.ui.components.SliderSettingItem
|
||||
@@ -73,6 +72,8 @@ fun SettingsScreen(
|
||||
val noiseReduction by viewModel.noiseReduction.collectAsState(initial = 0f)
|
||||
val chromaNoiseReduction by viewModel.chromaNoiseReduction.collectAsState(initial = 0f)
|
||||
val defaultFocalLength by viewModel.defaultFocalLength.collectAsState(initial = 0f)
|
||||
val useMultiFrame by viewModel.useMultiFrame.collectAsState()
|
||||
val multiFrameCount by viewModel.multiFrameCount.collectAsState()
|
||||
val isPurchased by viewModel.isPurchased.collectAsState()
|
||||
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
@@ -215,10 +216,10 @@ fun SettingsScreen(
|
||||
description = stringResource(R.string.settings_nr_level_description),
|
||||
levels = listOf(
|
||||
0 to stringResource(R.string.settings_nr_level_off),
|
||||
4 to stringResource(R.string.settings_nr_level_minimal),
|
||||
1 to stringResource(R.string.settings_nr_level_fast),
|
||||
2 to stringResource(R.string.settings_nr_level_high_quality),
|
||||
3 to stringResource(R.string.settings_nr_level_zsl)
|
||||
3 to stringResource(R.string.settings_nr_level_minimal),
|
||||
4 to stringResource(R.string.settings_nr_level_zsl)
|
||||
),
|
||||
currentLevel = nrLevel,
|
||||
onLevelSelected = { viewModel.setNRLevel(it) }
|
||||
@@ -332,6 +333,37 @@ fun SettingsScreen(
|
||||
modifier = Modifier.padding(vertical = 8.dp)
|
||||
)
|
||||
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.settings_use_multi_frame),
|
||||
description = stringResource(R.string.settings_use_multi_frame_description),
|
||||
checked = useMultiFrame,
|
||||
onCheckedChange = { viewModel.setUseMultiFrame(it) }
|
||||
)
|
||||
|
||||
if (useMultiFrame) {
|
||||
HorizontalDivider(
|
||||
color = Color.White.copy(alpha = 0.1f),
|
||||
modifier = Modifier.padding(vertical = 12.dp)
|
||||
)
|
||||
|
||||
QualityLevelSetting(
|
||||
title = stringResource(R.string.settings_multi_frame_count),
|
||||
description = stringResource(R.string.settings_multi_frame_count_description),
|
||||
levels = listOf(
|
||||
4 to "4",
|
||||
8 to "8",
|
||||
12 to "12",
|
||||
),
|
||||
currentLevel = multiFrameCount,
|
||||
onLevelSelected = { viewModel.setMultiFrameCount(it) }
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider(
|
||||
color = Color.White.copy(alpha = 0.1f),
|
||||
modifier = Modifier.padding(vertical = 8.dp)
|
||||
)
|
||||
|
||||
DefaultFocalLengthSetting(
|
||||
viewModel = viewModel,
|
||||
currentFocalLength = defaultFocalLength,
|
||||
@@ -1015,7 +1047,8 @@ fun DefaultFocalLengthSetting(
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
options.forEach { (fl, label) ->
|
||||
val isSelected = if (fl == 0f) currentFocalLength == 0f else kotlin.math.abs(currentFocalLength - fl) < 0.5f
|
||||
val isSelected =
|
||||
if (fl == 0f) currentFocalLength == 0f else kotlin.math.abs(currentFocalLength - fl) < 0.5f
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(64.dp)
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.graphics.SurfaceTexture
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CaptureResult
|
||||
import android.media.Image
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -136,6 +137,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 1)
|
||||
|
||||
val defaultFocalLength: Flow<Float> = userPreferencesRepository.userPreferences.map { it.defaultFocalLength }
|
||||
val useMultiFrame: StateFlow<Boolean> = userPreferencesRepository.userPreferences
|
||||
.map { it.useMultiFrame }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
|
||||
val multiFrameCount: StateFlow<Int> = userPreferencesRepository.userPreferences
|
||||
.map { it.multiFrameCount }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 8)
|
||||
|
||||
// 软件处理参数 Flow
|
||||
val sharpening: StateFlow<Float> = userPreferencesRepository.userPreferences
|
||||
@@ -160,15 +167,32 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
private var hasAppliedDefaultFocalLength = false
|
||||
|
||||
// Burst State
|
||||
private var isBursting = false
|
||||
private val burstImages = mutableListOf<Image>()
|
||||
|
||||
init {
|
||||
cameraController.initialize()
|
||||
cameraController.onImageCaptured = { image, captureInfo, characteristics, captureResult ->
|
||||
PLog.d(
|
||||
TAG,
|
||||
"onImageCaptured callback triggered - image: ${image.width}x${image.height}, format: ${image.format}"
|
||||
)
|
||||
viewModelScope.launch {
|
||||
saveImage(image, captureInfo, characteristics, captureResult)
|
||||
if (isBursting) {
|
||||
val count = multiFrameCount.value
|
||||
PLog.d(TAG, "Burst frame received: ${burstImages.size + 1}/$count")
|
||||
burstImages.add(image)
|
||||
if (burstImages.size >= count) {
|
||||
viewModelScope.launch {
|
||||
processBurst(burstImages.toList(), captureInfo, characteristics)
|
||||
burstImages.clear()
|
||||
}
|
||||
isBursting = false
|
||||
}
|
||||
} else {
|
||||
PLog.d(
|
||||
TAG,
|
||||
"onImageCaptured callback triggered - image: ${image.width}x${image.height}, format: ${image.format}"
|
||||
)
|
||||
viewModelScope.launch {
|
||||
saveImage(image, captureInfo, characteristics, captureResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +201,14 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
// 相机恢复应该由 CameraScreen 的 ON_RESUME 生命周期事件处理
|
||||
// 这样可以避免在相机被其他应用占用时的无限重试循环
|
||||
PLog.d(TAG, "onCameraError: code=$code, message=$message, canRetry=$canRetry")
|
||||
isBursting = false
|
||||
burstImages.forEach {
|
||||
try {
|
||||
it.close()
|
||||
} catch (e: Exception) {
|
||||
}
|
||||
}
|
||||
burstImages.clear()
|
||||
}
|
||||
|
||||
// 监听快门声音、震动和软件处理设置
|
||||
@@ -220,6 +252,12 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
}
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
multiFrameCount.collect {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
contentRepository.availableFrames.combine(
|
||||
userPreferencesRepository.userPreferences.map { it.frameOrder }
|
||||
@@ -266,6 +304,8 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
// 应用保存的网格线设置
|
||||
cameraController.setShowGrid(prefs.showGrid)
|
||||
|
||||
cameraController.setUseMultiFrame(prefs.useMultiFrame, prefs.multiFrameCount)
|
||||
} else {
|
||||
// 如果没有任何偏好设置,使用配置文件中的默认 LUT(第一个)
|
||||
val defaultLut = availableLutList.firstOrNull { it.isDefault }
|
||||
@@ -337,13 +377,24 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
cameraController.setCountdownValue(i)
|
||||
delay(1000)
|
||||
}
|
||||
generateThumbnail()
|
||||
// 倒计时结束,拍照
|
||||
cameraController.setCountdownValue(0)
|
||||
cameraController.capture()
|
||||
}
|
||||
} else {
|
||||
// 普通拍摄:直接拍照
|
||||
cameraController.capture()
|
||||
generateThumbnail()
|
||||
// Check if we should use burst/stacking
|
||||
// Skip raw (stacking raw not supported yet)
|
||||
burstImages.clear()
|
||||
if (useMultiFrame.value && !useRaw.value) {
|
||||
isBursting = true
|
||||
cameraController.capture()
|
||||
} else {
|
||||
isBursting = false
|
||||
// 普通拍摄:直接拍照
|
||||
cameraController.capture()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -640,7 +691,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
/**
|
||||
* 从相机捕获预览帧并生成所有 LUT 的预览图
|
||||
*/
|
||||
fun captureAndGenerateLutPreviews() {
|
||||
fun generateThumbnail() {
|
||||
if (isGeneratingPreviews) {
|
||||
PLog.d(TAG, "Already generating previews, skipping")
|
||||
return
|
||||
@@ -749,6 +800,34 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
// ==================== 延时拍摄和网格线相关方法 ====================
|
||||
|
||||
/**
|
||||
* 设置是否使用多帧合成
|
||||
*/
|
||||
fun setUseMultiFrame(enabled: Boolean) {
|
||||
if (enabled) {
|
||||
cameraController.setUseRaw(false)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseRaw(false)
|
||||
}
|
||||
}
|
||||
cameraController.setUseMultiFrame(enabled, multiFrameCount.value)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseMultiFrame(enabled)
|
||||
}
|
||||
reopenCamera()
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置多帧合成帧数
|
||||
*/
|
||||
fun setMultiFrameCount(count: Int) {
|
||||
cameraController.setUseMultiFrame(state.value.useMultiFrame, count)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveMultiFrameCount(count)
|
||||
//reopenCamera()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换延时拍摄档位(0s → 3s → 5s → 10s → 0s)
|
||||
*/
|
||||
@@ -781,12 +860,21 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
*/
|
||||
fun toggleRaw() {
|
||||
val nextValue = !useRaw.value
|
||||
cameraController.setUseRaw(nextValue)
|
||||
reopenCamera()
|
||||
setUseRaw(nextValue)
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseRaw(nextValue)
|
||||
fun setUseRaw(useRaw: Boolean) {
|
||||
if (useRaw) {
|
||||
cameraController.setUseMultiFrame(false, multiFrameCount.value)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseMultiFrame(false)
|
||||
}
|
||||
}
|
||||
cameraController.setUseRaw(useRaw)
|
||||
viewModelScope.launch {
|
||||
userPreferencesRepository.saveUseRaw(useRaw)
|
||||
}
|
||||
reopenCamera()
|
||||
}
|
||||
|
||||
// ==================== 新增设置项方法 ====================
|
||||
@@ -1117,7 +1205,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
image: Image,
|
||||
captureInfo: CaptureInfo,
|
||||
characteristics: CameraCharacteristics?,
|
||||
captureResult: CaptureResult
|
||||
captureResult: CaptureResult?
|
||||
) {
|
||||
try {
|
||||
PLog.d(TAG, "saveImage started - dimensions: ${image.width}x${image.height}, format: ${image.format}")
|
||||
@@ -1172,8 +1260,101 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
|
||||
val photoId = characteristics?.let {
|
||||
PhotoManager.savePhoto(
|
||||
context, image, cameraController.rawPreviewFrame, metadata, rotation, aspectRatio, it, captureResult, shouldAutoSave,
|
||||
photoProcessor, sharpening.value, noiseReduction.value, chromaNoiseReduction.value
|
||||
context,
|
||||
image,
|
||||
cameraController.rawPreviewFrame,
|
||||
metadata,
|
||||
rotation,
|
||||
aspectRatio,
|
||||
it,
|
||||
captureResult,
|
||||
shouldAutoSave,
|
||||
photoProcessor,
|
||||
sharpening.value,
|
||||
noiseReduction.value,
|
||||
chromaNoiseReduction.value
|
||||
)
|
||||
}
|
||||
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")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to save image", e)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun processBurst(
|
||||
images: List<Image>,
|
||||
captureInfo: CaptureInfo,
|
||||
characteristics: CameraCharacteristics?
|
||||
) {
|
||||
try {
|
||||
PLog.d(TAG, "processBurst started - image size ${images.size}")
|
||||
val context = getApplication<Application>()
|
||||
|
||||
// 保存当前配置信息
|
||||
val lutIdToSave = currentLutId.value
|
||||
val aspectRatio = state.value.aspectRatio
|
||||
val frameIdToSave = currentFrameId
|
||||
val shouldAutoSave = autoSaveAfterCapture.firstOrNull() ?: false
|
||||
val sharpeningValue = sharpening.value
|
||||
val noiseReductionValue = noiseReduction.value
|
||||
val chromaNoiseReductionValue = chromaNoiseReduction.value
|
||||
val currentCameraId = cameraController.getCurrentCameraId()
|
||||
|
||||
// 计算旋转角度
|
||||
val sensorOrientation = cameraController.getSensorOrientation()
|
||||
val lensFacing = cameraController.getLensFacing()
|
||||
val deviceRotation = OrientationObserver.rotationDegrees.toInt()
|
||||
|
||||
// 基础旋转角度计算
|
||||
val baseRotation = if (lensFacing == CameraCharacteristics.LENS_FACING_FRONT) {
|
||||
(sensorOrientation - deviceRotation + 360) % 360
|
||||
} else {
|
||||
(sensorOrientation + deviceRotation) % 360
|
||||
}
|
||||
|
||||
// 获取用户配置的摄像头方向偏移
|
||||
val userPrefs = userPreferencesRepository.userPreferences.firstOrNull()
|
||||
val orientationOffset = userPrefs?.cameraOrientationOffsets?.get(currentCameraId) ?: 0
|
||||
|
||||
// 应用方向偏移
|
||||
val rotation = (baseRotation + orientationOffset) % 360
|
||||
|
||||
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
|
||||
val metadata = PhotoMetadata(
|
||||
lutId = lutIdToSave,
|
||||
frameId = frameIdToSave,
|
||||
colorRecipeParams = currentRecipeParams.value,
|
||||
sharpening = sharpeningValue,
|
||||
noiseReduction = noiseReductionValue,
|
||||
chromaNoiseReduction = chromaNoiseReductionValue,
|
||||
deviceModel = captureInfo.model,
|
||||
brand = captureInfo.make.replaceFirstChar { it.uppercase() },
|
||||
dateTaken = captureInfo.captureTime,
|
||||
iso = captureInfo.iso,
|
||||
shutterSpeed = captureInfo.formatExposureTime(),
|
||||
focalLength = captureInfo.formatFocalLength(),
|
||||
focalLength35mm = captureInfo.formatFocalLength35mm(),
|
||||
aperture = captureInfo.formatAperture(),
|
||||
)
|
||||
|
||||
val photoId = characteristics?.let {
|
||||
PhotoManager.saveStackedPhoto(
|
||||
context,
|
||||
images,
|
||||
cameraController.rawPreviewFrame,
|
||||
metadata,
|
||||
rotation,
|
||||
aspectRatio,
|
||||
shouldAutoSave,
|
||||
photoProcessor,
|
||||
sharpening.value,
|
||||
noiseReduction.value,
|
||||
chromaNoiseReduction.value
|
||||
)
|
||||
}
|
||||
if (photoId != null) {
|
||||
|
||||
@@ -86,4 +86,8 @@
|
||||
<string name="import_failed">导入失败: %d 个项目</string>
|
||||
<string name="sort_categories">分类排序</string>
|
||||
<string name="drag_to_reorder_categories">按住右侧手柄拖动排序</string>
|
||||
<string name="settings_use_multi_frame">多帧合成</string>
|
||||
<string name="settings_use_multi_frame_description">拍摄多张照片并合成,以获得更好的画质和更低的噪点。</string>
|
||||
<string name="settings_multi_frame_count">多帧合成帧数</string>
|
||||
<string name="settings_multi_frame_count_description">多帧合成所使用的帧数(帧数越多效果越好,但合成也越慢)。</string>
|
||||
</resources>
|
||||
@@ -100,6 +100,10 @@
|
||||
<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_multi_frame_count">多帧合成帧数</string>
|
||||
<string name="settings_multi_frame_count_description">多帧合成所使用的帧数(帧数越多效果越好,但合成也越慢)。</string>
|
||||
<string name="settings_section_frame">边框水印</string>
|
||||
<string name="settings_frame_style">边框样式</string>
|
||||
<string name="settings_frame_description">为拍摄的照片添加装饰性边框和水印</string>
|
||||
|
||||
@@ -101,6 +101,10 @@
|
||||
<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_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_section_frame">Frame Watermark</string>
|
||||
<string name="settings_frame_style">Frame Style</string>
|
||||
<string name="settings_frame_description">Add decorative frame and watermark to photos</string>
|
||||
|
||||
Reference in new issue
Block a user