From 9e2a3d9bb5dfdce2d5806c2ff492d16714af1e62 Mon Sep 17 00:00:00 2001 From: Hinnka Date: Sat, 2 May 2026 13:15:41 +0800 Subject: [PATCH] feat: implement per-camera black level correction and DNG metadata patching --- app/src/main/cpp/native-lib.cpp | 232 +++--------------- .../mycamera/camera/Camera2Controller.kt | 109 +++++++- .../data/UserPreferencesRepository.kt | 60 ++++- .../hinnka/mycamera/gallery/GalleryManager.kt | 27 +- .../hinnka/mycamera/gallery/MediaMetadata.kt | 16 +- .../hinnka/mycamera/gallery/PhotoProcessor.kt | 7 - .../com/hinnka/mycamera/raw/MeteringSystem.kt | 59 +++-- .../mycamera/raw/RawDemosaicProcessor.kt | 13 +- .../mycamera/ui/settings/SettingsScreen.kt | 46 +++- .../mycamera/utils/DngBlackLevelPatcher.kt | 157 ++++++++++++ .../mycamera/viewmodel/CameraViewModel.kt | 47 +++- app/src/main/res/values-zh-rCN/strings.xml | 7 +- app/src/main/res/values/strings.xml | 7 +- 13 files changed, 494 insertions(+), 293 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/utils/DngBlackLevelPatcher.kt diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index fb1ecb77..607bf399 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -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 &histogram, int count, - float percentile) { - if (count <= 0) { - return 0; - } - const int target = static_cast((count - 1) * percentile); - int cumulative = 0; - for (int value = 0; value < static_cast(histogram.size()); ++value) { - cumulative += histogram[value]; - if (cumulative > target) { - return value; +static void computeEffectiveBlackLevels(LibRaw &rawProcessor, float out[4]) { + const float base = static_cast(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(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( + rawProcessor.imgdata.color.cblack[6 + r * cols + c]); + ++count; + } + } + } + if (count > 0) { + total += sum / static_cast(count); + } } + out[ch] = total; } - return static_cast(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(sizeof(ushort)) - : rawWidth; - const int left = - std::max(0, static_cast(rawProcessor.imgdata.sizes.left_margin)); - const int top = - std::max(0, static_cast(rawProcessor.imgdata.sizes.top_margin)); - const int activeWidth = static_cast(rawProcessor.imgdata.sizes.width); - const int activeHeight = static_cast(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 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(rawProcessor.imgdata.sizes.left_margin); - int top_margin = static_cast(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( - 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(std::max(0.0f, blackLevels[i]) + 0.5f); - rawProcessor.imgdata.params.user_cblack[i] = static_cast(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(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(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); diff --git a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt index d34a407f..ccac3cfa 100644 --- a/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt +++ b/app/src/main/java/com/hinnka/mycamera/camera/Camera2Controller.kt @@ -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) diff --git a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt index 965db8c7..348d0c53 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -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 = emptyMap(), + val rawCustomBlackLevels: Map = 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 { + 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 { + return map.entries.joinToString(",") { "${it.key}:${it.value}" } + } + + private fun parseMapFloat(value: String?): Map { + 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 { + return map.entries.joinToString(",") { "${it.key}:${it.value}" } + } + private fun parseCustomLensIds(value: String?): List { 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) } } diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index 15f5f2eb..502d94f4 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -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(extraBufferCapacity = 16) val detailHdrReadyEvents: SharedFlow = _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, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt index 0705e1e5..29a98c56 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt @@ -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), diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index 5fc6890c..ccc4a3ea 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -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 ) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt index bc6ec427..0e213860 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt @@ -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 + } + } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index 2fd094f4..143bcaef 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -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 { diff --git a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt index f595dde2..cebe2ade 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/settings/SettingsScreen.kt @@ -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( diff --git a/app/src/main/java/com/hinnka/mycamera/utils/DngBlackLevelPatcher.kt b/app/src/main/java/com/hinnka/mycamera/utils/DngBlackLevelPatcher.kt new file mode 100644 index 00000000..8366cea3 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/utils/DngBlackLevelPatcher.kt @@ -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() +} diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt index 1a765484..db73fb31 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/CameraViewModel.kt @@ -246,9 +246,18 @@ class CameraViewModel(application: Application) : AndroidViewModel(application) val rawAutoWhiteBalanceEstimate: StateFlow = userPreferencesRepository.userPreferences .map { it.rawAutoWhiteBalanceEstimate } .stateIn(viewModelScope, SharingStarted.Eagerly, false) - val rawAutoBlackLevelCorrection: StateFlow = userPreferencesRepository.userPreferences - .map { it.rawAutoBlackLevelCorrection } - .stateIn(viewModelScope, SharingStarted.Eagerly, true) + val rawBlackLevelMode: StateFlow = combine( + state.map { it.currentCameraId }.distinctUntilChanged(), + userPreferencesRepository.userPreferences + ) { cameraId, prefs -> + prefs.rawBlackLevelModes[cameraId] ?: "Default" + }.stateIn(viewModelScope, SharingStarted.Eagerly, "Default") + val rawCustomBlackLevel: StateFlow = combine( + state.map { it.currentCameraId }.distinctUntilChanged(), + userPreferencesRepository.userPreferences + ) { cameraId, prefs -> + prefs.rawCustomBlackLevels[cameraId] ?: 0f + }.stateIn(viewModelScope, SharingStarted.Eagerly, 0f) val exportDngWithRawExport: StateFlow = 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, diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index e9675fe4..a5c8bb47 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -664,8 +664,11 @@ 导出 RAW 照片时,同时将对应的原始 DNG 文件导出到系统相册。 RAW 自动白平衡 显影 DNG 时从 RAW 像素估计白平衡,适用于设备白平衡元数据不可靠的情况。 - RAW 自动黑电平 - 显影 DNG 时从 RAW 暗部像素估计黑电平,并在 0、16、64、100 和元数据黑电平中选择最接近的值。 + 黑电平校正 + 黑电平校正(镜头 %1$s · %2$dmm) + 手动设置 RAW 显影时的黑电平,用于修复偏色问题。针对镜头单独设置。 + 默认 + 自定义 幻影模式 关闭幻影模式 开启幻影模式 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e594a3d..8991c96c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -648,8 +648,11 @@ When exporting a RAW photo, also export its original DNG file to the system gallery. RAW auto white balance Estimate white balance from RAW pixels when developing DNG files, useful when device metadata is unreliable. - RAW auto black level - Estimate the DNG black level from RAW dark pixels and choose the nearest preset from 0, 16, 64, 100, or the metadata value. + Black Level Correction + Black Level Correction (Lens %1$s · %2$dmm) + Manually set the black level for RAW development to fix color cast issues. Applied per camera lens. + Default + Custom P010 (10-bit YUV) Enable 10-bit YUV output for better image data precision. Effective on supported devices when RAW is disabled. HLG10 HDR