feat: implement per-camera black level correction and DNG metadata patching

This commit is contained in:
Hinnka committed 2026-05-02 13:15:41 +08:00
1 parent d994fa4b20
commit 9e2a3d9bb5
13 files changed
+494 -293

No files matched your search

+29 -203
View File
@@ -431,180 +431,36 @@ static float sampleDngGainMapBilinear(const DngGainMap &gainMap, float x, float
return top + (bottom - top) * ty;
}
struct AutoBlackLevelChoice {
bool valid = false;
bool usesMetadata[4] = {true, true, true, true};
float estimated[4] = {};
float selected[4] = {};
};
static int percentileFromHistogram(const std::vector<int> &histogram, int count,
float percentile) {
if (count <= 0) {
return 0;
}
const int target = static_cast<int>((count - 1) * percentile);
int cumulative = 0;
for (int value = 0; value < static_cast<int>(histogram.size()); ++value) {
cumulative += histogram[value];
if (cumulative > target) {
return value;
static void computeEffectiveBlackLevels(LibRaw &rawProcessor, float out[4]) {
const float base = static_cast<float>(rawProcessor.imgdata.color.black);
const unsigned cols = rawProcessor.imgdata.color.cblack[4];
const unsigned rows = rawProcessor.imgdata.color.cblack[5];
for (int ch = 0; ch < 4; ++ch) {
float total = base + static_cast<float>(rawProcessor.imgdata.color.cblack[ch]);
// Add the repeat pattern contribution for this CFA channel.
if (cols > 0 && rows > 0) {
float sum = 0.0f;
int count = 0;
for (unsigned r = 0; r < rows; ++r) {
for (unsigned c = 0; c < cols; ++c) {
if (rawProcessor.FC(r, c) == ch) {
sum += static_cast<float>(
rawProcessor.imgdata.color.cblack[6 + r * cols + c]);
++count;
}
}
}
if (count > 0) {
total += sum / static_cast<float>(count);
}
}
out[ch] = total;
}
return static_cast<int>(histogram.size()) - 1;
}
static AutoBlackLevelChoice chooseAutoBlackLevelPreset(
LibRaw &rawProcessor, const float metadataBlackLevels[4]) {
AutoBlackLevelChoice choice;
if (!rawProcessor.imgdata.rawdata.raw_image ||
!rawProcessor.imgdata.idata.filters) {
return choice;
}
const int rawWidth = rawProcessor.imgdata.sizes.raw_width;
const int rawHeight = rawProcessor.imgdata.sizes.raw_height;
const int rawPitch = rawProcessor.imgdata.sizes.raw_pitch > 0
? rawProcessor.imgdata.sizes.raw_pitch /
static_cast<int>(sizeof(ushort))
: rawWidth;
const int left =
std::max(0, static_cast<int>(rawProcessor.imgdata.sizes.left_margin));
const int top =
std::max(0, static_cast<int>(rawProcessor.imgdata.sizes.top_margin));
const int activeWidth = static_cast<int>(rawProcessor.imgdata.sizes.width);
const int activeHeight = static_cast<int>(rawProcessor.imgdata.sizes.height);
const int right = std::min(rawWidth - 1, left + activeWidth - 1);
const int bottom = std::min(rawHeight - 1, top + activeHeight - 1);
if (right < left || bottom < top) {
return choice;
}
// Metadata-based black level calculation is now handled by computeEffectiveBlackLevels.
std::vector<int> histograms[4];
for (auto &histogram : histograms) {
histogram.assign(65536, 0);
}
int counts[4] = {};
auto *rawImage = rawProcessor.imgdata.rawdata.raw_image;
int left_margin = static_cast<int>(rawProcessor.imgdata.sizes.left_margin);
int top_margin = static_cast<int>(rawProcessor.imgdata.sizes.top_margin);
bool useMargins = (left_margin > 2 || top_margin > 2 || (rawWidth - left - activeWidth) > 2 || (rawHeight - top - activeHeight) > 2);
const float percentile = useMargins ? 0.5f : 0.001f;
for (int y = 0; y < rawHeight; ++y) {
if (useMargins && (y >= top && y <= bottom)) {
continue;
}
if (!useMargins && !(y >= top && y <= bottom)) {
continue;
}
for (int x = 0; x < rawWidth; ++x) {
if (useMargins && (x >= left && x <= right)) {
continue;
}
if (!useMargins && !(x >= left && x <= right)) {
continue;
}
const int channel = rawProcessor.FC(y, x);
if (channel < 0 || channel > 3) {
continue;
}
const int value = rawImage[y * rawPitch + x] & 0xFFFF;
histograms[channel][value]++;
counts[channel]++;
}
}
int validChannels = 0;
float estimated[4] = {};
for (int channel = 0; channel < 4; ++channel) {
if (counts[channel] <= 0) {
continue;
}
estimated[channel] = static_cast<float>(
percentileFromHistogram(histograms[channel], counts[channel], percentile));
++validChannels;
}
if (validChannels <= 0) {
return choice;
}
if (useMargins) {
LOGI("dng auto black level: using %d masked pixels",
counts[0] + counts[1] + counts[2] + counts[3]);
}
const float fixedPresets[] = {0.0f, 16.0f, 64.0f, 100.0f};
for (int channel = 0; channel < 4; ++channel) {
choice.estimated[channel] = estimated[channel];
choice.selected[channel] = metadataBlackLevels[channel];
choice.usesMetadata[channel] = true;
if (counts[channel] <= 0) {
continue;
}
float bestValue = fixedPresets[0];
float bestDistance = std::abs(estimated[channel] - fixedPresets[0]);
for (int i = 1; i < 4; ++i) {
const float distance = std::abs(estimated[channel] - fixedPresets[i]);
if (distance < bestDistance) {
bestDistance = distance;
bestValue = fixedPresets[i];
}
}
const float metadataDistance =
std::abs(estimated[channel] - metadataBlackLevels[channel]);
// Only override if the estimation is close to a known preset
// and it's closer to that preset than it is to the metadata.
if (bestDistance < 32.0f && bestDistance < metadataDistance) {
choice.selected[channel] = bestValue;
choice.usesMetadata[channel] = false;
} else {
choice.selected[channel] = metadataBlackLevels[channel];
choice.usesMetadata[channel] = true;
}
}
choice.valid = true;
LOGI("dng auto black level: estimated=%0.2f/%0.2f/%0.2f/%0.2f "
"selected=%s%0.2f/%s%0.2f/%s%0.2f/%s%0.2f metadata=%0.2f/%0.2f/%0.2f/%0.2f",
choice.estimated[0], choice.estimated[1], choice.estimated[2],
choice.estimated[3],
choice.usesMetadata[0] ? "metadata:" : "", choice.selected[0],
choice.usesMetadata[1] ? "metadata:" : "", choice.selected[1],
choice.usesMetadata[2] ? "metadata:" : "", choice.selected[2],
choice.usesMetadata[3] ? "metadata:" : "", choice.selected[3],
metadataBlackLevels[0], metadataBlackLevels[1], metadataBlackLevels[2],
metadataBlackLevels[3]);
return choice;
}
static void overrideLibRawBlackLevels(LibRaw &rawProcessor,
const float blackLevels[4]) {
rawProcessor.imgdata.params.user_black = 0;
rawProcessor.imgdata.color.black = 0;
rawProcessor.imgdata.color.dng_levels.dng_black = 0;
rawProcessor.imgdata.color.dng_levels.dng_fblack = 0.0f;
for (int i = 0; i < 4; ++i) {
const unsigned level =
static_cast<unsigned>(std::max(0.0f, blackLevels[i]) + 0.5f);
rawProcessor.imgdata.params.user_cblack[i] = static_cast<int>(level);
rawProcessor.imgdata.color.cblack[i] = level;
rawProcessor.imgdata.color.dng_levels.dng_cblack[i] = level;
rawProcessor.imgdata.color.dng_levels.dng_fcblack[i] =
static_cast<float>(level);
}
rawProcessor.imgdata.color.cblack[4] = 0;
rawProcessor.imgdata.color.cblack[5] = 0;
rawProcessor.imgdata.color.dng_levels.dng_cblack[4] = 0;
rawProcessor.imgdata.color.dng_levels.dng_cblack[5] = 0;
rawProcessor.imgdata.color.dng_levels.dng_fcblack[4] = 0.0f;
rawProcessor.imgdata.color.dng_levels.dng_fcblack[5] = 0.0f;
}
static bool applySupportedDngGainMaps(LibRaw &rawProcessor, const float blackLevels[4]) {
if (!rawProcessor.imgdata.rawdata.raw_image || !rawProcessor.imgdata.idata.filters) {
@@ -2024,8 +1880,7 @@ JNIEXPORT jobject JNICALL
Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
JNIEnv *env, jobject /* this */, jstring filePath, jfloat xr, jfloat yr,
jfloat xg, jfloat yg, jfloat xb, jfloat yb, jfloat xw, jfloat yw,
jboolean useRawAutoWhiteBalanceEstimate,
jboolean useRawAutoBlackLevelCorrection) {
jboolean useRawAutoWhiteBalanceEstimate) {
const char *path = env->GetStringUTFChars(filePath, nullptr);
if (path == nullptr) {
@@ -2084,40 +1939,11 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
libraw_strerror(ret));
}*/
// Read the TOTAL effective black level per channel.
// LibRaw stores it as: color.black + cblack[channel] + repeat_pattern[position].
float dngBlackLevels[4] = {};
for (int i = 0; i < 4; ++i) {
dngBlackLevels[i] = static_cast<float>(RawProcessor.imgdata.color.dng_levels.dng_cblack[6 + i]);
}
LOGI("dng black levels: %f %f %f %f", dngBlackLevels[0], dngBlackLevels[1], dngBlackLevels[2], dngBlackLevels[3]);
const float metadataBlackLevels[4] = {
dngBlackLevels[0], dngBlackLevels[1], dngBlackLevels[2], dngBlackLevels[3]};
if (useRawAutoBlackLevelCorrection == JNI_TRUE) {
const AutoBlackLevelChoice choice =
chooseAutoBlackLevelPreset(RawProcessor, metadataBlackLevels);
bool shouldOverrideBlackLevels = false;
if (choice.valid) {
for (int i = 0; i < 4; ++i) {
if (!choice.usesMetadata[i]) {
shouldOverrideBlackLevels = true;
break;
}
}
}
if (choice.valid && shouldOverrideBlackLevels) {
for (int i = 0; i < 4; ++i) {
dngBlackLevels[i] = choice.selected[i];
}
overrideLibRawBlackLevels(RawProcessor, dngBlackLevels);
LOGI("dng black levels auto override: %f %f %f %f", dngBlackLevels[0],
dngBlackLevels[1], dngBlackLevels[2], dngBlackLevels[3]);
} else if (choice.valid) {
LOGI("dng auto black level: using metadata black levels");
} else {
LOGI("dng auto black level: unavailable, using metadata black levels");
}
} else {
LOGI("dng auto black level: disabled, using metadata black levels");
}
computeEffectiveBlackLevels(RawProcessor, dngBlackLevels);
LOGI("dng black levels (metadata): %f %f %f %f", dngBlackLevels[0], dngBlackLevels[1], dngBlackLevels[2], dngBlackLevels[3]);
const bool appliedDngGainMap = applySupportedDngGainMaps(RawProcessor, dngBlackLevels);
LOGI("dng gain map: opcode2_len=%u applied=%d", RawProcessor.imgdata.color.dng_levels.rawopcodes[1].len,
appliedDngGainMap ? 1 : 0);
@@ -674,8 +674,16 @@ class Camera2Controller(private val context: Context) {
if (captureMode == CaptureMode.PHOTO) {
val aspectRatio = state.value.aspectRatio
val effectivelyUseRaw = state.value.useRaw && isRawSupported
val captureSize = if (effectivelyUseRaw) {
CameraUtils.getRawCaptureSize(context, cameraId) ?: CameraUtils.getBestCaptureSize(
val rawCaptureSize = if (effectivelyUseRaw) {
CameraUtils.getRawCaptureSize(context, cameraId)
} else {
null
}
val captureSize = if (rawCaptureSize != null) {
rawCaptureSize
} else if (effectivelyUseRaw) {
PLog.w(TAG, "RAW requested for camera $cameraId but no RAW_SENSOR output size was reported")
CameraUtils.getBestCaptureSize(
context,
cameraId,
aspectRatio
@@ -683,7 +691,7 @@ class Camera2Controller(private val context: Context) {
} else {
CameraUtils.getBestCaptureSize(context, cameraId, aspectRatio)
}
val captureFormat = if (effectivelyUseRaw && CameraUtils.getRawCaptureSize(context, cameraId) != null) {
val captureFormat = if (rawCaptureSize != null) {
ImageFormat.RAW_SENSOR
} else if (isP010Supported && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && state.value.useP010) {
ImageFormat.YCBCR_P010
@@ -729,7 +737,7 @@ class Camera2Controller(private val context: Context) {
}
val image = trackImage(rawImage)
if (image != null) {
if (effectivelyUseRaw) {
if (image.image.format == ImageFormat.RAW_SENSOR) {
val timestamp = image.timestamp
val pendingResult = pendingResults.remove(timestamp)
if (pendingResult != null) {
@@ -753,6 +761,8 @@ class Camera2Controller(private val context: Context) {
}
} catch (e: Exception) {
PLog.e(TAG, "Error in onImageAvailable", e)
_state.value = _state.value.copy(isCapturing = false)
resetPreviewAfterCapture()
}
}, cameraHandler)
}
@@ -1077,7 +1087,12 @@ class Camera2Controller(private val context: Context) {
"readerFormat=${imageFormatToString(readerFormat)}, " +
"sessionColorSpace=${if (shouldUseP3ColorSpace()) "DISPLAY_P3" else "DEFAULT"}"
)
if (useHlgCapture) {
if (readerFormat == ImageFormat.RAW_SENSOR) {
PLog.w(TAG, "Retrying photo preview session without RAW output for camera ${_state.value.currentCameraId}")
session.close()
rebuildPhotoReaderWithoutRaw()
createPreviewSession(forceStandardSession = true)
} else if (useHlgCapture) {
PLog.w(TAG, "Retrying preview session with STANDARD dynamic range fallback")
_state.value = _state.value.copy(currentDynamicRangeProfile = "STANDARD")
createPreviewSession(forceStandardSession = true)
@@ -1092,10 +1107,70 @@ class Camera2Controller(private val context: Context) {
}
device.createCaptureSession(sessionConfig)
} catch (e: Exception) {
PLog.e(TAG, "Failed to create preview session")
PLog.e(TAG, "Failed to create preview session", e)
if (reader?.imageFormat == ImageFormat.RAW_SENSOR) {
PLog.w(TAG, "Retrying photo preview session after RAW session exception")
rebuildPhotoReaderWithoutRaw()
createPreviewSession(forceStandardSession = true)
}
}
}
private fun rebuildPhotoReaderWithoutRaw() {
val cameraId = _state.value.currentCameraId
if (cameraId.isEmpty()) return
safeCloseImageReader(imageReader)
imageReader = null
val captureSize = CameraUtils.getBestCaptureSize(context, cameraId, _state.value.aspectRatio)
val fallbackFormat = if (isP010Supported && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && _state.value.useP010) {
ImageFormat.YCBCR_P010
} else {
ImageFormat.YUV_420_888
}
PLog.w(
TAG,
"RAW disabled for current session fallback: camera=$cameraId, " +
"size=${captureSize.width}x${captureSize.height}, format=${imageFormatToString(fallbackFormat)}"
)
imageReader = ImageReader.newInstance(
captureSize.width,
captureSize.height,
fallbackFormat,
MAX_IMAGES
).apply {
setOnImageAvailableListener({ reader ->
try {
if (openImagesCount.get() >= MAX_IMAGES) {
PLog.w(TAG, "Too many open images ($openImagesCount), skipping fallback acquire")
return@setOnImageAvailableListener
}
val image = trackImage(reader.acquireLatestImage())
if (image != null) {
processAndTriggerCapture(image, null)
} else {
PLog.w(TAG, "Fallback acquireLatestImage() returned null")
_state.value = _state.value.copy(isCapturing = false)
resetPreviewAfterCapture()
}
} catch (e: Exception) {
PLog.e(TAG, "Error in fallback onImageAvailable", e)
_state.value = _state.value.copy(isCapturing = false)
resetPreviewAfterCapture()
}
}, cameraHandler)
}
_state.value = _state.value.copy(
isRawSupported = false,
isP3Supported = false,
)
isRawSupported = false
}
private fun onSessionConfigured(session: CameraCaptureSession) {
captureSession = session
@@ -1128,6 +1203,10 @@ class Camera2Controller(private val context: Context) {
}
}
private fun isRawCaptureReader(reader: ImageReader?): Boolean {
return reader?.imageFormat == ImageFormat.RAW_SENSOR
}
// ==================== 统一参数配置 ====================
/**
@@ -2628,11 +2707,14 @@ class Camera2Controller(private val context: Context) {
*/
private fun performCapture(device: CameraDevice, reader: ImageReader) {
try {
val isRawCapture = isRawCaptureReader(reader)
val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply {
addTarget(reader.surface)
if (shouldMirrorStillCaptureToPreview()) {
if (!isRawCapture && shouldMirrorStillCaptureToPreview()) {
previewSurface?.let { addTarget(it) }
} else if (isRawCapture) {
PLog.d(TAG, "RAW capture uses RAW target only to avoid unstable RAW+preview still requests")
}
// 应用所有相机参数(曝光、白平衡、闪光灯、变焦、色调映射)
@@ -2676,7 +2758,7 @@ class Camera2Controller(private val context: Context) {
timestamp: Long,
frameNumber: Long
) {
if (state.value.useRaw && isRawSupported) {
if (isRawCapture) {
pendingCaptureStartedTimestamps[frameNumber] = timestamp
}
PLog.d(TAG, "Burst capture started at frame $frameNumber")
@@ -2688,7 +2770,7 @@ class Camera2Controller(private val context: Context) {
result: TotalCaptureResult
) {
val timestamp = getCaptureTimestamp(result)
if (timestamp != null && state.value.useRaw && isRawSupported) {
if (timestamp != null && isRawCapture) {
val pendingImage = pendingImages.remove(timestamp)
if (pendingImage != null) {
processAndTriggerCapture(pendingImage, result)
@@ -2733,7 +2815,7 @@ class Camera2Controller(private val context: Context) {
timestamp: Long,
frameNumber: Long
) {
if (state.value.useRaw && isRawSupported) {
if (isRawCapture) {
pendingCaptureStartedTimestamps[frameNumber] = timestamp
}
PLog.d(TAG, "Capture started at frame $frameNumber")
@@ -2745,7 +2827,7 @@ class Camera2Controller(private val context: Context) {
result: TotalCaptureResult
) {
val timestamp = getCaptureTimestamp(result)
if (timestamp != null && state.value.useRaw && isRawSupported) {
if (timestamp != null && isRawCapture) {
val pendingImage = pendingImages.remove(timestamp)
if (pendingImage != null) {
processAndTriggerCapture(pendingImage, result)
@@ -3110,10 +3192,13 @@ class Camera2Controller(private val context: Context) {
try {
// Apply capture intent
val isRawCapture = isRawCaptureReader(imageReader)
val captureBuilder = device.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE).apply {
imageReader?.surface?.let { addTarget(it) }
if (shouldMirrorStillCaptureToPreview()) {
if (!isRawCapture && shouldMirrorStillCaptureToPreview()) {
previewSurface?.let { addTarget(it) }
} else if (isRawCapture) {
PLog.d(TAG, "RAW burst capture uses RAW target only to avoid unstable RAW+preview still requests")
}
applyBaseCameraSettings(this, isCapture = true)
@@ -63,7 +63,8 @@ data class UserPreferences(
val rawBlackPointCorrection: Float = 0f,
val rawWhitePointCorrection: Float = 0f,
val rawAutoWhiteBalanceEstimate: Boolean = false,
val rawAutoBlackLevelCorrection: Boolean = true,
val rawBlackLevelModes: Map<String, String> = emptyMap(),
val rawCustomBlackLevels: Map<String, Float> = emptyMap(),
val exportDngWithRawExport: Boolean = false,
val frameId: String? = null,
val showHistogram: Boolean = true,
@@ -156,7 +157,8 @@ class UserPreferencesRepository(private val context: Context) {
private val RAW_BLACK_POINT_CORRECTION_KEY = floatPreferencesKey("raw_black_point_correction")
private val RAW_WHITE_POINT_CORRECTION_KEY = floatPreferencesKey("raw_white_point_correction")
private val RAW_AUTO_WHITE_BALANCE_ESTIMATE_KEY = booleanPreferencesKey("raw_auto_white_balance_estimate")
private val RAW_AUTO_BLACK_LEVEL_CORRECTION_KEY = booleanPreferencesKey("raw_auto_black_level_correction")
private val RAW_BLACK_LEVEL_MODES_KEY = stringPreferencesKey("raw_black_level_modes")
private val RAW_CUSTOM_BLACK_LEVELS_KEY = stringPreferencesKey("raw_custom_black_levels")
private val EXPORT_DNG_WITH_RAW_EXPORT_KEY = booleanPreferencesKey("export_dng_with_raw_export")
private val PHANTOM_BASELINE_LUT_ID_KEY = stringPreferencesKey("phantom_baseline_lut_id")
private val FRAME_ID_KEY = stringPreferencesKey("frame_id")
@@ -258,7 +260,8 @@ class UserPreferencesRepository(private val context: Context) {
rawBlackPointCorrection = preferences[RAW_BLACK_POINT_CORRECTION_KEY] ?: 0f,
rawWhitePointCorrection = preferences[RAW_WHITE_POINT_CORRECTION_KEY] ?: 0f,
rawAutoWhiteBalanceEstimate = preferences[RAW_AUTO_WHITE_BALANCE_ESTIMATE_KEY] ?: false,
rawAutoBlackLevelCorrection = preferences[RAW_AUTO_BLACK_LEVEL_CORRECTION_KEY] ?: true,
rawBlackLevelModes = parseMapString(preferences[RAW_BLACK_LEVEL_MODES_KEY]),
rawCustomBlackLevels = parseMapFloat(preferences[RAW_CUSTOM_BLACK_LEVELS_KEY]),
exportDngWithRawExport = preferences[EXPORT_DNG_WITH_RAW_EXPORT_KEY] ?: false,
phantomBaselineLutId = preferences[PHANTOM_BASELINE_LUT_ID_KEY],
frameId = preferences[FRAME_ID_KEY],
@@ -387,6 +390,41 @@ class UserPreferencesRepository(private val context: Context) {
.joinToString(",") { "${it.key}:${it.value}" }
}
private fun parseMapString(value: String?): Map<String, String> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val parts = entry.split(":")
if (parts.size == 2) {
parts[0] to parts[1]
} else null
}
.toMap()
}
private fun serializeMapString(map: Map<String, String>): String {
return map.entries.joinToString(",") { "${it.key}:${it.value}" }
}
private fun parseMapFloat(value: String?): Map<String, Float> {
if (value.isNullOrEmpty()) return emptyMap()
return value.split(",")
.mapNotNull { entry ->
val parts = entry.split(":")
if (parts.size == 2) {
val floatValue = parts[1].toFloatOrNull()
if (floatValue != null) {
parts[0] to floatValue
} else null
} else null
}
.toMap()
}
private fun serializeMapFloat(map: Map<String, Float>): String {
return map.entries.joinToString(",") { "${it.key}:${it.value}" }
}
private fun parseCustomLensIds(value: String?): List<String> {
if (value.isNullOrBlank()) return emptyList()
return value.split(",")
@@ -521,9 +559,21 @@ class UserPreferencesRepository(private val context: Context) {
}
}
suspend fun saveRawAutoBlackLevelCorrection(enabled: Boolean) {
suspend fun saveRawBlackLevelMode(cameraId: String, mode: String) {
context.dataStore.edit { preferences ->
preferences[RAW_AUTO_BLACK_LEVEL_CORRECTION_KEY] = enabled
val current = parseMapString(preferences[RAW_BLACK_LEVEL_MODES_KEY])
val updated = current.toMutableMap()
updated[cameraId] = mode
preferences[RAW_BLACK_LEVEL_MODES_KEY] = serializeMapString(updated)
}
}
suspend fun saveRawCustomBlackLevel(cameraId: String, value: Float) {
context.dataStore.edit { preferences ->
val current = parseMapFloat(preferences[RAW_CUSTOM_BLACK_LEVELS_KEY])
val updated = current.toMutableMap()
updated[cameraId] = value
preferences[RAW_CUSTOM_BLACK_LEVELS_KEY] = serializeMapFloat(updated)
}
}
@@ -27,6 +27,7 @@ import com.hinnka.mycamera.raw.RawDemosaicProcessor
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawProcessingPreferences
import com.hinnka.mycamera.utils.BitmapUtils
import com.hinnka.mycamera.utils.DngBlackLevelPatcher
import com.hinnka.mycamera.utils.PLog
import com.hinnka.mycamera.utils.RawProcessor
import com.hinnka.mycamera.utils.YuvProcessor
@@ -114,15 +115,6 @@ object GalleryManager {
private val _detailHdrReadyEvents = MutableSharedFlow<String>(extraBufferCapacity = 16)
val detailHdrReadyEvents: SharedFlow<String> = _detailHdrReadyEvents.asSharedFlow()
private suspend fun resolveRawAutoBlackLevelCorrection(
context: Context,
metadata: MediaMetadata?
): Boolean {
return metadata?.rawAutoBlackLevelCorrection
?: (ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull()
?.rawAutoBlackLevelCorrection ?: true)
}
private suspend fun resolveRawAutoWhiteBalanceEstimate(
context: Context,
metadata: MediaMetadata?
@@ -1163,6 +1155,7 @@ object GalleryManager {
tempDngFile.delete()
return@withContext
}
patchSavedDngBlackLevel(tempDngFile, metadata)
if (dngFile.exists()) {
dngFile.delete()
}
@@ -1187,7 +1180,6 @@ object GalleryManager {
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(context, metadata),
sharpeningValue = 0.4f,
rawDcpId = metadata.rawDcpId
) ?: return@withContext
@@ -1754,7 +1746,6 @@ object GalleryManager {
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, metadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(context, metadata),
sharpeningValue = 0.4f,
denoiseValue = 0.2f,
rawDcpId = metadata.rawDcpId
@@ -1839,6 +1830,7 @@ object GalleryManager {
tempDngFile.delete()
return false
}
patchSavedDngBlackLevel(tempDngFile, metadata)
try {
if (dngFile.exists()) {
@@ -1864,6 +1856,17 @@ object GalleryManager {
return true
}
private fun patchSavedDngBlackLevel(dngFile: File, metadata: MediaMetadata) {
val patched = DngBlackLevelPatcher.patchFromMode(
file = dngFile,
mode = metadata.rawBlackLevelMode,
customBlackLevel = metadata.rawCustomBlackLevel
)
if (patched) {
PLog.d(TAG, "Applied DNG BlackLevel correction (${metadata.rawBlackLevelMode}) to ${dngFile.name}")
}
}
/**
* 保存堆栈合成后的照片
@@ -2634,7 +2637,6 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(context, updatedMetadata),
sharpeningValue = 0.4f,
denoiseValue = updatedMetadata.rawDenoiseValue,
rawDcpId = updatedMetadata.rawDcpId,
@@ -2752,7 +2754,6 @@ object GalleryManager {
rawBlackPointCorrection = updatedMetadata?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = updatedMetadata?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(context, updatedMetadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(context, updatedMetadata),
sharpeningValue = 0.4f,
denoiseValue = (updatedMetadata ?: MediaMetadata()).rawDenoiseValue,
rawDcpId = updatedMetadata?.rawDcpId,
@@ -23,7 +23,7 @@ import kotlin.math.log2
* 保存 LUT、边框水印、编辑信息和拍摄参数,用于非破坏性编辑和边框水印渲染
*/
data class MediaMetadata(
val version: Int = 15, // Added RAW DCP support
val version: Int = 16,
val mediaType: MediaType = MediaType.IMAGE,
// 编辑配置
val lutId: String? = null,
@@ -43,7 +43,6 @@ data class MediaMetadata(
val rawBlackPointCorrection: Float? = null,
val rawWhitePointCorrection: Float? = null,
val rawAutoWhiteBalanceEstimate: Boolean? = null,
val rawAutoBlackLevelCorrection: Boolean? = null,
val rawDcpId: String? = null,
// 边框水印配置
val frameId: String? = null,
@@ -101,7 +100,10 @@ data class MediaMetadata(
val captureMode: String? = null,
val multipleExposureFrameCount: Int? = null,
val hasAiDenoisedBase: Boolean = false,
val aiDenoiseStrength: Float? = null
val aiDenoiseStrength: Float? = null,
val rawBlackLevelMode: String? = null,
val rawCustomBlackLevel: Float? = null,
val cameraId: String? = null,
) {
/**
* 将元数据转换为 CaptureInfo,用于写入 EXIF
@@ -187,8 +189,10 @@ data class MediaMetadata(
put("rawBlackPointCorrection", rawBlackPointCorrection?.toDouble() ?: JSONObject.NULL)
put("rawWhitePointCorrection", rawWhitePointCorrection?.toDouble() ?: JSONObject.NULL)
put("rawAutoWhiteBalanceEstimate", rawAutoWhiteBalanceEstimate ?: JSONObject.NULL)
put("rawAutoBlackLevelCorrection", rawAutoBlackLevelCorrection ?: JSONObject.NULL)
put("rawDcpId", rawDcpId ?: JSONObject.NULL)
put("rawBlackLevelMode", rawBlackLevelMode ?: JSONObject.NULL)
put("rawCustomBlackLevel", rawCustomBlackLevel?.toDouble() ?: JSONObject.NULL)
put("cameraId", cameraId ?: JSONObject.NULL)
put("frameId", frameId ?: JSONObject.NULL)
put("width", width)
@@ -362,8 +366,10 @@ data class MediaMetadata(
rawBlackPointCorrection = if (obj.isNull("rawBlackPointCorrection")) null else obj.optDouble("rawBlackPointCorrection").toFloat(),
rawWhitePointCorrection = if (obj.isNull("rawWhitePointCorrection")) null else obj.optDouble("rawWhitePointCorrection").toFloat(),
rawAutoWhiteBalanceEstimate = if (obj.isNull("rawAutoWhiteBalanceEstimate")) null else obj.optBoolean("rawAutoWhiteBalanceEstimate"),
rawAutoBlackLevelCorrection = if (obj.isNull("rawAutoBlackLevelCorrection")) null else obj.optBoolean("rawAutoBlackLevelCorrection"),
rawDcpId = if (obj.isNull("rawDcpId")) null else obj.optString("rawDcpId"),
rawBlackLevelMode = if (obj.isNull("rawBlackLevelMode")) null else obj.optString("rawBlackLevelMode"),
rawCustomBlackLevel = if (obj.isNull("rawCustomBlackLevel")) null else obj.optDouble("rawCustomBlackLevel").toFloat(),
cameraId = if (obj.isNull("cameraId")) null else obj.optString("cameraId"),
frameId = if (obj.isNull("frameId")) null else obj.optString("frameId"),
width = obj.optInt("width", 0),
height = obj.optInt("height", 0),
@@ -53,11 +53,6 @@ class PhotoProcessor(
return userPreferencesRepository.userPreferences.firstOrNull()?.hlgHardwareCompatibilityEnabled ?: true
}
private suspend fun resolveRawAutoBlackLevelCorrection(metadata: MediaMetadata): Boolean {
return metadata.rawAutoBlackLevelCorrection
?: (userPreferencesRepository.userPreferences.firstOrNull()?.rawAutoBlackLevelCorrection ?: true)
}
private suspend fun resolveRawAutoWhiteBalanceEstimate(metadata: MediaMetadata): Boolean {
return metadata.rawAutoWhiteBalanceEstimate
?: (userPreferencesRepository.userPreferences.firstOrNull()?.rawAutoWhiteBalanceEstimate ?: false)
@@ -439,7 +434,6 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(metadata),
sharpeningValue = 0.4f,
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
@@ -502,7 +496,6 @@ class PhotoProcessor(
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate(metadata),
rawAutoBlackLevelCorrection = resolveRawAutoBlackLevelCorrection(metadata),
denoiseValue = metadata.rawDenoiseValue,
rawDcpId = metadata.rawDcpId
)
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.raw
import com.hinnka.mycamera.color.TransferCurve
import java.nio.FloatBuffer
import kotlin.math.exp
import kotlin.math.pow
/**
@@ -92,16 +93,12 @@ object MeteringSystem {
val zoneAvg = zoneSum[i] / zonePixCount[i]
// 1. 基础权重:画面中心
// 1. 基础权重:从评价测光连续过渡到中央重点测光。
val distSqC = (pzx - 0.5f).let { it * it } + (pzy - 0.5f).let { it * it }
val normalizedCenterWeight = centerWeight.coerceIn(0f, 1f).toDouble()
val evaluativeWeight = 1.0
val centerSigma = 0.22 - 0.19 * normalizedCenterWeight
val centerBoost = 1.0 + 7.0 * normalizedCenterWeight
val centerWeightedWeight = kotlin.math.exp(-distSqC / centerSigma) * centerBoost
var weight = evaluativeWeight * (1.0 - normalizedCenterWeight) +
centerWeightedWeight * normalizedCenterWeight
val centerInfluence = normalizedCenterWeight * normalizedCenterWeight
var weight = calculateSpatialMeteringWeight(distSqC.toDouble(), centerInfluence)
// 2. 肤色密度补偿
val skinDensity = zoneSkinCount[i].toDouble() / zonePixCount[i]
@@ -110,23 +107,17 @@ object MeteringSystem {
}
// 3. 高光评价逻辑 (Sky/Highlight handling)
// 中心权重越高,越主动排除中心附近的亮天空/背景,避免逆光场景继续压黑主体。
val highlightThreshold = 0.75 - 0.5 * normalizedCenterWeight
if (zoneAvg > highlightThreshold) {
weight *= 0.15 / (1.0 + 2.0 * normalizedCenterWeight)
}
weight *= calculateHighlightSuppression(zoneAvg, centerInfluence)
// 4. 逆光补偿 (Backlight compensation)
// 如果对焦中心区域明显暗于全局平均,说明可能处于大面积强光背后的阴影中,大幅增加权重以拉亮主体
if (zoneAvg < globalAvgLog - 0.05) {
weight *= 3.0 + 9.0 * normalizedCenterWeight
}
weight *= calculateCenterBacklightBoost(zoneAvg, globalAvgLog, distSqC.toDouble(), centerInfluence)
// 5. 中央重点暗部优先
// 高中心权重时,暗的中心区域应主导测光;否则大面积天空会把平均值抬高,肉眼上仍然欠曝。
if (normalizedCenterWeight > 0.0 && distSqC < 0.12 && zoneAvg < TransferCurve.LINEAR.middleGray) {
if (centerInfluence > 0.0 && distSqC < 0.12 && zoneAvg < TransferCurve.LINEAR.middleGray) {
val darkness = 1.0 - (zoneAvg / TransferCurve.LINEAR.middleGray).coerceIn(0.0, 1.0)
weight *= 1.0 + darkness * 12.0 * normalizedCenterWeight
weight *= 1.0 + darkness * 8.0 * centerInfluence
}
weightedSumLog += zoneAvg * weight
@@ -151,4 +142,38 @@ object MeteringSystem {
return gain.coerceIn(0.25f, 16f)
}
private fun calculateSpatialMeteringWeight(distSqC: Double, centerInfluence: Double): Double {
if (centerInfluence <= 0.0) {
return 1.0
}
val centerSigma = 0.24 - 0.17 * centerInfluence
val centerBoost = 1.0 + 3.0 * centerInfluence
val centerWeightedWeight = exp(-distSqC / centerSigma) * centerBoost
return 1.0 * (1.0 - centerInfluence) + centerWeightedWeight * centerInfluence
}
private fun calculateHighlightSuppression(zoneAvg: Double, centerInfluence: Double): Double {
val highlightThreshold = 0.75 - 0.25 * centerInfluence
if (zoneAvg <= highlightThreshold) {
return 1.0
}
return 0.25 / (1.0 + centerInfluence)
}
private fun calculateCenterBacklightBoost(
zoneAvg: Double,
globalAvg: Double,
distSqC: Double,
centerInfluence: Double
): Double {
if (centerInfluence <= 0.0 || zoneAvg >= globalAvg - 0.05) {
return 1.0
}
val centerProximity = exp(-distSqC / 0.08)
return 1.0 + centerProximity * (3.0 + 6.0 * centerInfluence) * centerInfluence
}
}
@@ -120,8 +120,7 @@ class RawDemosaicProcessor {
xg: Float, yg: Float,
xb: Float, yb: Float,
xw: Float, yw: Float,
useRawAutoWhiteBalanceEstimate: Boolean,
useRawAutoBlackLevelCorrection: Boolean
useRawAutoWhiteBalanceEstimate: Boolean
): DngRawData?
companion object {
@@ -261,7 +260,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawAutoBlackLevelCorrection: Boolean = true,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -287,7 +285,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawAutoBlackLevelCorrection = rawAutoBlackLevelCorrection,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -320,7 +317,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawAutoBlackLevelCorrection: Boolean = true,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -351,7 +347,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawAutoBlackLevelCorrection = rawAutoBlackLevelCorrection,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
chromaDenoiseValue = chromaDenoiseValue,
@@ -377,7 +372,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawAutoBlackLevelCorrection: Boolean = true,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
rawDcpId: String? = null,
@@ -403,7 +397,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate,
rawAutoBlackLevelCorrection = rawAutoBlackLevelCorrection,
sharpeningValue = sharpeningValue,
denoiseValue = denoiseValue,
rawDcpId = rawDcpId,
@@ -438,7 +431,6 @@ class RawDemosaicProcessor {
rawBlackPointCorrection: Float = 0f,
rawWhitePointCorrection: Float = 0f,
rawAutoWhiteBalanceEstimate: Boolean = false,
rawAutoBlackLevelCorrection: Boolean = true,
sharpeningValue: Float = 0f,
denoiseValue: Float? = null,
chromaDenoiseValue: Float? = null,
@@ -463,8 +455,7 @@ class RawDemosaicProcessor {
ColorSpace.ProPhoto.xg, ColorSpace.ProPhoto.yg,
ColorSpace.ProPhoto.xb, ColorSpace.ProPhoto.yb,
ColorSpace.ProPhoto.xw, ColorSpace.ProPhoto.yw,
rawAutoWhiteBalanceEstimate,
rawAutoBlackLevelCorrection
rawAutoWhiteBalanceEstimate
)
if (dngRawData == null) {
return@withContext RawProcessor.processAndToBitmap(dngFile, aspectRatio, cropRegion, rotation)?.let {
@@ -199,7 +199,8 @@ fun SettingsScreen(
val rawBlackPointCorrection by viewModel.rawBlackPointCorrection.collectAsState()
val rawWhitePointCorrection by viewModel.rawWhitePointCorrection.collectAsState()
val rawAutoWhiteBalanceEstimate by viewModel.rawAutoWhiteBalanceEstimate.collectAsState()
val rawAutoBlackLevelCorrection by viewModel.rawAutoBlackLevelCorrection.collectAsState()
val rawBlackLevelMode by viewModel.rawBlackLevelMode.collectAsState()
val rawCustomBlackLevel by viewModel.rawCustomBlackLevel.collectAsState()
val availableDcps = viewModel.availableDcps
val availableLuts = viewModel.availableLutList
val previewThumbnail = viewModel.previewThumbnail
@@ -1165,11 +1166,44 @@ fun SettingsScreen(
color = Color.White.copy(alpha = 0.1f)
)
SwitchSettingItem(
title = stringResource(R.string.settings_raw_auto_black_level_correction),
description = stringResource(R.string.settings_raw_auto_black_level_correction_description),
checked = rawAutoBlackLevelCorrection,
onCheckedChange = { viewModel.setRawAutoBlackLevelCorrection(it) }
val rawBlackLevelCorrectionTitle = state.getCurrentCameraInfo()?.let { info ->
stringResource(
R.string.settings_raw_black_level_correction_with_lens,
info.cameraId,
info.focalLength35mmEquivalent.roundToInt()
)
} ?: stringResource(R.string.settings_raw_black_level_correction)
QualityLevelSetting(
title = rawBlackLevelCorrectionTitle,
description = stringResource(R.string.settings_raw_black_level_correction_description),
levels = listOf(
"Default" to stringResource(R.string.settings_black_level_default),
"0" to "0",
"16" to "16",
"64" to "64",
"256" to "256",
"512" to "512",
"Custom" to stringResource(R.string.settings_black_level_custom)
),
currentLevel = rawBlackLevelMode,
onLevelSelected = { viewModel.setRawBlackLevelMode(it) }
)
if (rawBlackLevelMode == "Custom") {
Spacer(modifier = Modifier.height(8.dp))
TextInputSettingItem(
title = stringResource(R.string.settings_black_level_custom),
description = null,
value = if (rawCustomBlackLevel == 0f) "" else rawCustomBlackLevel.toString(),
onValueChange = {
it.toFloatOrNull()?.let { value -> viewModel.setRawCustomBlackLevel(value) }
}
)
}
HorizontalDivider(
modifier = Modifier.padding(vertical = 8.dp),
color = Color.White.copy(alpha = 0.1f)
)
HorizontalDivider(
@@ -0,0 +1,157 @@
package com.hinnka.mycamera.utils
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import kotlin.math.roundToInt
object DngBlackLevelPatcher {
private const val TAG = "DngBlackLevelPatcher"
private const val TIFF_TAG_BLACK_LEVEL = 50714
fun patchFromMode(file: File, mode: String?, customBlackLevel: Float?): Boolean {
val level = resolveBlackLevel(mode, customBlackLevel) ?: return false
return patchUniformBlackLevel(file, level)
}
private fun resolveBlackLevel(mode: String?, customBlackLevel: Float?): Float? {
return when (mode) {
"0" -> 0f
"16" -> 16f
"64" -> 64f
"256" -> 256f
"512" -> 512f
"Custom" -> customBlackLevel ?: 0f
else -> null
}
}
private fun patchUniformBlackLevel(file: File, level: Float): Boolean {
if (!file.exists() || file.length() < 16L) {
return false
}
return runCatching {
RandomAccessFile(file, "rw").use { raf ->
val header = ByteArray(8)
raf.seek(0)
raf.readFully(header)
val byteOrder = when {
header[0] == 'I'.code.toByte() && header[1] == 'I'.code.toByte() -> ByteOrder.LITTLE_ENDIAN
header[0] == 'M'.code.toByte() && header[1] == 'M'.code.toByte() -> ByteOrder.BIG_ENDIAN
else -> return false
}
val magic = readUnsignedShort(header, 2, byteOrder)
if (magic != 42) {
return false
}
val firstIfdOffset = readUnsignedInt(header, 4, byteOrder)
if (firstIfdOffset <= 0L || firstIfdOffset + 2L > raf.length()) {
return false
}
raf.seek(firstIfdOffset)
val entryCountBytes = ByteArray(2)
raf.readFully(entryCountBytes)
val entryCount = readUnsignedShort(entryCountBytes, 0, byteOrder)
for (entryIndex in 0 until entryCount) {
val entryOffset = firstIfdOffset + 2L + entryIndex * 12L
if (entryOffset + 12L > raf.length()) {
break
}
val entry = ByteArray(12)
raf.seek(entryOffset)
raf.readFully(entry)
val tag = readUnsignedShort(entry, 0, byteOrder)
if (tag != TIFF_TAG_BLACK_LEVEL) {
continue
}
val type = readUnsignedShort(entry, 2, byteOrder)
val count = readUnsignedInt(entry, 4, byteOrder)
val valueBytes = valueByteCount(type, count) ?: return false
val valueOffset = if (valueBytes <= 4L) {
entryOffset + 8L
} else {
readUnsignedInt(entry, 8, byteOrder)
}
if (valueOffset < 0L || valueOffset + valueBytes > raf.length()) {
return false
}
writeBlackLevelValues(raf, valueOffset, type, count, byteOrder, level)
PLog.d(TAG, "Patched DNG BlackLevel to $level in ${file.name}")
return true
}
false
}
}.onFailure {
PLog.w(TAG, "Failed to patch DNG BlackLevel: ${file.absolutePath}", it)
}.getOrDefault(false)
}
private fun writeBlackLevelValues(
raf: RandomAccessFile,
valueOffset: Long,
type: Int,
count: Long,
byteOrder: ByteOrder,
level: Float
) {
raf.seek(valueOffset)
val rounded = level.roundToInt().coerceAtLeast(0)
repeat(count.coerceAtMost(4096L).toInt()) {
when (type) {
3 -> raf.write(shortBytes(rounded.coerceAtMost(0xFFFF), byteOrder))
4 -> raf.write(intBytes(rounded, byteOrder))
5 -> {
raf.write(intBytes(rounded, byteOrder))
raf.write(intBytes(1, byteOrder))
}
9 -> raf.write(intBytes(rounded, byteOrder))
10 -> {
raf.write(intBytes(rounded, byteOrder))
raf.write(intBytes(1, byteOrder))
}
11 -> raf.write(floatBytes(level, byteOrder))
12 -> raf.write(doubleBytes(level.toDouble(), byteOrder))
else -> return
}
}
}
private fun valueByteCount(type: Int, count: Long): Long? {
val typeSize = when (type) {
1, 2, 6, 7 -> 1L
3, 8 -> 2L
4, 9, 11 -> 4L
5, 10, 12 -> 8L
else -> return null
}
return typeSize * count
}
private fun readUnsignedShort(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Int {
return ByteBuffer.wrap(bytes, offset, 2).order(byteOrder).short.toInt() and 0xFFFF
}
private fun readUnsignedInt(bytes: ByteArray, offset: Int, byteOrder: ByteOrder): Long {
return ByteBuffer.wrap(bytes, offset, 4).order(byteOrder).int.toLong() and 0xFFFFFFFFL
}
private fun shortBytes(value: Int, byteOrder: ByteOrder): ByteArray =
ByteBuffer.allocate(2).order(byteOrder).putShort(value.toShort()).array()
private fun intBytes(value: Int, byteOrder: ByteOrder): ByteArray =
ByteBuffer.allocate(4).order(byteOrder).putInt(value).array()
private fun floatBytes(value: Float, byteOrder: ByteOrder): ByteArray =
ByteBuffer.allocate(4).order(byteOrder).putFloat(value).array()
private fun doubleBytes(value: Double, byteOrder: ByteOrder): ByteArray =
ByteBuffer.allocate(8).order(byteOrder).putDouble(value).array()
}
@@ -246,9 +246,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val rawAutoWhiteBalanceEstimate: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.rawAutoWhiteBalanceEstimate }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
val rawAutoBlackLevelCorrection: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.rawAutoBlackLevelCorrection }
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
val rawBlackLevelMode: StateFlow<String> = combine(
state.map { it.currentCameraId }.distinctUntilChanged(),
userPreferencesRepository.userPreferences
) { cameraId, prefs ->
prefs.rawBlackLevelModes[cameraId] ?: "Default"
}.stateIn(viewModelScope, SharingStarted.Eagerly, "Default")
val rawCustomBlackLevel: StateFlow<Float> = combine(
state.map { it.currentCameraId }.distinctUntilChanged(),
userPreferencesRepository.userPreferences
) { cameraId, prefs ->
prefs.rawCustomBlackLevels[cameraId] ?: 0f
}.stateIn(viewModelScope, SharingStarted.Eagerly, 0f)
val exportDngWithRawExport: StateFlow<Boolean> = userPreferencesRepository.userPreferences
.map { it.exportDngWithRawExport }
.stateIn(viewModelScope, SharingStarted.Eagerly, false)
@@ -718,8 +727,15 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
fun setRawAutoWhiteBalanceEstimate(enabled: Boolean) {
viewModelScope.launch { userPreferencesRepository.saveRawAutoWhiteBalanceEstimate(enabled) }
}
fun setRawAutoBlackLevelCorrection(enabled: Boolean) {
viewModelScope.launch { userPreferencesRepository.saveRawAutoBlackLevelCorrection(enabled) }
fun setRawBlackLevelMode(mode: String) {
viewModelScope.launch {
userPreferencesRepository.saveRawBlackLevelMode(state.value.currentCameraId, mode)
}
}
fun setRawCustomBlackLevel(value: Float) {
viewModelScope.launch {
userPreferencesRepository.saveRawCustomBlackLevel(state.value.currentCameraId, value)
}
}
fun importRawDcp(uri: android.net.Uri, onComplete: (Boolean) -> Unit) {
viewModelScope.launch {
@@ -869,7 +885,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawAutoBlackLevelCorrection = userPrefs?.rawAutoBlackLevelCorrection ?: true,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
cameraId = currentCameraId,
width = width,
height = height,
ratio = aspectRatio,
@@ -2548,7 +2566,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawAutoBlackLevelCorrection = userPrefs?.rawAutoBlackLevelCorrection ?: true,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
cameraId = currentCameraId,
width = image.width,
height = image.height,
ratio = aspectRatio,
@@ -2649,6 +2669,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
val shouldMirror = cameraController.getLensFacing() == CameraCharacteristics.LENS_FACING_FRONT &&
(userPrefs?.mirrorFrontCamera ?: true)
val baselineMetadata = resolveBaselineMetadata(BaselineColorCorrectionTarget.JPG, userPrefs)
val currentCameraId = cameraController.getCurrentCameraId()
val metadata = MediaMetadata(
lutId = currentLutId.value,
@@ -2668,7 +2689,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawAutoBlackLevelCorrection = userPrefs?.rawAutoBlackLevelCorrection ?: true,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
cameraId = currentCameraId,
width = bitmap.width,
height = bitmap.height,
ratio = mapVideoAspectRatioToPhotoAspectRatio(currentState.videoConfig.aspectRatio),
@@ -2809,7 +2832,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawAutoBlackLevelCorrection = userPrefs?.rawAutoBlackLevelCorrection ?: true,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
cameraId = currentCameraId,
width = (images[0].width.toFloat() * superResScale).roundToInt(),
height = (images[0].height.toFloat() * superResScale).roundToInt(),
ratio = aspectRatio,
@@ -2958,7 +2983,9 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
rawBlackPointCorrection = userPrefs?.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = userPrefs?.rawWhitePointCorrection ?: 0f,
rawAutoWhiteBalanceEstimate = userPrefs?.rawAutoWhiteBalanceEstimate ?: false,
rawAutoBlackLevelCorrection = userPrefs?.rawAutoBlackLevelCorrection ?: true,
rawBlackLevelMode = userPrefs?.rawBlackLevelModes?.get(currentCameraId) ?: "Default",
rawCustomBlackLevel = userPrefs?.rawCustomBlackLevels?.get(currentCameraId) ?: 0f,
cameraId = currentCameraId,
width = image.width,
height = image.height,
ratio = aspectRatio,
+5 -2
View File
@@ -664,8 +664,11 @@
<string name="settings_export_dng_with_raw_export_description">导出 RAW 照片时,同时将对应的原始 DNG 文件导出到系统相册。</string>
<string name="settings_raw_auto_white_balance_estimate">RAW 自动白平衡</string>
<string name="settings_raw_auto_white_balance_estimate_description">显影 DNG 时从 RAW 像素估计白平衡,适用于设备白平衡元数据不可靠的情况。</string>
<string name="settings_raw_auto_black_level_correction">RAW 自动黑电平</string>
<string name="settings_raw_auto_black_level_correction_description">显影 DNG 时从 RAW 暗部像素估计黑电平,并在 0、16、64、100 和元数据黑电平中选择最接近的值。</string>
<string name="settings_raw_black_level_correction">黑电平校正</string>
<string name="settings_raw_black_level_correction_with_lens">黑电平校正(镜头 %1$s · %2$dmm)</string>
<string name="settings_raw_black_level_correction_description">手动设置 RAW 显影时的黑电平,用于修复偏色问题。针对镜头单独设置。</string>
<string name="settings_black_level_default">默认</string>
<string name="settings_black_level_custom">自定义</string>
<string name="ghost_mode">幻影模式</string>
<string name="close_ghost_mode">关闭幻影模式</string>
<string name="ghost_mode_dialog_title">开启幻影模式</string>
+5 -2
View File
@@ -648,8 +648,11 @@
<string name="settings_export_dng_with_raw_export_description">When exporting a RAW photo, also export its original DNG file to the system gallery.</string>
<string name="settings_raw_auto_white_balance_estimate">RAW auto white balance</string>
<string name="settings_raw_auto_white_balance_estimate_description">Estimate white balance from RAW pixels when developing DNG files, useful when device metadata is unreliable.</string>
<string name="settings_raw_auto_black_level_correction">RAW auto black level</string>
<string name="settings_raw_auto_black_level_correction_description">Estimate the DNG black level from RAW dark pixels and choose the nearest preset from 0, 16, 64, 100, or the metadata value.</string>
<string name="settings_raw_black_level_correction">Black Level Correction</string>
<string name="settings_raw_black_level_correction_with_lens">Black Level Correction (Lens %1$s · %2$dmm)</string>
<string name="settings_raw_black_level_correction_description">Manually set the black level for RAW development to fix color cast issues. Applied per camera lens.</string>
<string name="settings_black_level_default">Default</string>
<string name="settings_black_level_custom">Custom</string>
<string name="settings_use_p010">P010 (10-bit YUV)</string>
<string name="settings_use_p010_description">Enable 10-bit YUV output for better image data precision. Effective on supported devices when RAW is disabled.</string>
<string name="settings_use_hlg10">HLG10 HDR</string>