From 5229ae5bfd2f0e7ce8be451f3ff52091a481ed74 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Thu, 16 Jul 2026 13:02:59 +0800 Subject: [PATCH] feat: new auto exposure --- .../data/UserPreferencesRepository.kt | 32 +- .../hinnka/mycamera/gallery/GalleryManager.kt | 167 ++- .../hinnka/mycamera/gallery/MediaMetadata.kt | 12 +- .../hinnka/mycamera/gallery/PhotoProcessor.kt | 11 - .../mycamera/gallery/db/GalleryDatabase.kt | 21 +- .../mycamera/gallery/db/GalleryMediaEntity.kt | 1 + .../mycamera/gallery/db/GalleryMediaStore.kt | 6 +- .../hinnka/mycamera/phantom/PhantomService.kt | 7 - .../mycamera/processor/GlesRawStacker.kt | 47 +- .../raw/DngHdrProfileGainTableGenerator.kt | 2 +- .../mycamera/raw/DngPgtmDebugRewriter.kt | 409 ----- .../raw/DngPhotonProfileGainTableGenerator.kt | 81 - .../raw/DngProfileGainTableGeneration.kt | 7 + .../mycamera/raw/DngProfileToneCurve.kt | 27 +- .../raw/GlesRawProfileGainTableMapBuilder.kt | 577 ------- .../com/hinnka/mycamera/raw/MeteringSystem.kt | 24 - .../mycamera/raw/PhotonPgtmBrightnessModel.kt | 183 --- .../mycamera/raw/RawDemosaicProcessor.kt | 1321 ++++------------- .../mycamera/raw/RawDngProfilePreparation.kt | 30 + .../raw/RawProfileGainTableMapBuilder.kt | 98 +- .../hinnka/mycamera/raw/RawRenderingEngine.kt | 16 +- .../raw/RawViewfinderExposureMatcher.kt | 295 ++++ .../mycamera/ui/gallery/GalleryEditScreen.kt | 53 +- .../com/hinnka/mycamera/utils/RawProcessor.kt | 133 +- .../mycamera/viewmodel/GalleryViewModel.kt | 1 - .../mycamera/raw/DngPgtmDebugRewriterTest.kt | 160 -- .../DngPhotonProfileGainTableGeneratorTest.kt | 590 -------- 27 files changed, 1052 insertions(+), 3259 deletions(-) delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriter.kt delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/DngProfileGainTableGeneration.kt delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/PhotonPgtmBrightnessModel.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/RawViewfinderExposureMatcher.kt delete mode 100644 app/src/test/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriterTest.kt delete mode 100644 app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt 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 fd56ada1..0439334f 100644 --- a/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt +++ b/app/src/main/java/com/hinnka/mycamera/data/UserPreferencesRepository.kt @@ -59,6 +59,16 @@ private fun sanitizeTonemapMode(mode: String): String { } } +private fun resolveStoredRawAutoExposure(mode: String?, legacyValue: Boolean?): Boolean { + return when { + mode.equals("OFF", ignoreCase = true) -> false + mode.equals("VIEWFINDER_MATCH", ignoreCase = true) -> true + // Migrate the removed dynamic-scene option to the remaining viewfinder matcher. + mode.equals("DYNAMIC_SCENE_ESTIMATION", ignoreCase = true) -> true + else -> legacyValue ?: true + } +} + enum class VolumeKeyAction { NONE, CAPTURE, @@ -301,6 +311,7 @@ class UserPreferencesRepository(private val context: Context) { private val RAW_NLM_NOISE_FACTOR_KEY = floatPreferencesKey("raw_nlm_noise_factor") private val RAW_EXPOSURE_COMPENSATION_KEY = floatPreferencesKey("raw_exposure_compensation") private val RAW_AUTO_EXPOSURE_KEY = booleanPreferencesKey("raw_auto_exposure") + private val RAW_AUTO_EXPOSURE_MODE_KEY = stringPreferencesKey("raw_auto_exposure_mode") private val RAW_HIGHLIGHTS_ADJUSTMENT_KEY = floatPreferencesKey("raw_highlights_adjustment") private val RAW_SHADOWS_ADJUSTMENT_KEY = floatPreferencesKey("raw_shadows_adjustment") private val RAW_MIN_SHUTTER_SPEED_NS_KEY = longPreferencesKey("raw_min_shutter_speed_ns") @@ -477,7 +488,10 @@ class UserPreferencesRepository(private val context: Context) { ).normalized(), rawNlmNoiseFactor = preferences[RAW_NLM_NOISE_FACTOR_KEY] ?: 0f, rawExposureCompensation = preferences[RAW_EXPOSURE_COMPENSATION_KEY] ?: 0f, - rawAutoExposure = preferences[RAW_AUTO_EXPOSURE_KEY] ?: true, + rawAutoExposure = resolveStoredRawAutoExposure( + mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY], + legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY], + ), rawHighlightsAdjustment = preferences[RAW_HIGHLIGHTS_ADJUSTMENT_KEY] ?: 0f, rawShadowsAdjustment = preferences[RAW_SHADOWS_ADJUSTMENT_KEY] ?: 0f, rawMinShutterSpeedNs = preferences[RAW_MIN_SHUTTER_SPEED_NS_KEY] ?: 0L, @@ -988,6 +1002,11 @@ class UserPreferencesRepository(private val context: Context) { suspend fun saveRawAutoExposure(enabled: Boolean) { context.dataStore.edit { preferences -> preferences[RAW_AUTO_EXPOSURE_KEY] = enabled + preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = if (enabled) { + "VIEWFINDER_MATCH" + } else { + "OFF" + } } } @@ -999,7 +1018,16 @@ class UserPreferencesRepository(private val context: Context) { } preferences[TONEMAP_MODE] = "SYSTEM_DEFAULT" preferences[NATURAL_LIGHT_ENABLED] = false - preferences[RAW_AUTO_EXPOSURE_KEY] = true + val rawAutoExposure = resolveStoredRawAutoExposure( + mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY], + legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY], + ) + preferences[RAW_AUTO_EXPOSURE_KEY] = rawAutoExposure + preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = if (rawAutoExposure) { + "VIEWFINDER_MATCH" + } else { + "OFF" + } preferences[CAMERA_STARTUP_DEFAULTS_RESTORED_V1] = true restored = true } 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 e4762956..b6cac3e8 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -41,10 +41,13 @@ import com.hinnka.mycamera.raw.DngEmbeddedProfile import com.hinnka.mycamera.raw.DngProfileGainTableMap import com.hinnka.mycamera.raw.DngProfileToneCurve import com.hinnka.mycamera.raw.RawDefaultCropOverride +import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions +import com.hinnka.mycamera.raw.RawDngViewfinderExposureMatcher import com.hinnka.mycamera.raw.RawDemosaicProcessor import com.hinnka.mycamera.raw.RawMetadata import com.hinnka.mycamera.raw.RawProfileToneMapMode import com.hinnka.mycamera.raw.RawSharpeningDefaults +import com.hinnka.mycamera.raw.RawViewfinderExposureMatcher import com.hinnka.mycamera.raw.SpectralFilmTuning import com.hinnka.mycamera.utils.BitmapUtils import com.hinnka.mycamera.utils.DngBlackLevelPatcher @@ -194,9 +197,13 @@ object GalleryManager { context: Context, metadata: MediaMetadata? ): Boolean { - return metadata?.rawAutoExposure - ?: (ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull() - ?.rawAutoExposure ?: true) + val fallback = ContentRepository.getInstance(context) + .userPreferencesRepository + .userPreferences + .firstOrNull() + ?.rawAutoExposure + ?: true + return metadata?.rawAutoExposure ?: fallback } private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float { @@ -207,16 +214,6 @@ object GalleryManager { return metadata.chromaNoiseReduction ?: (if (metadata.isImported) 0f else fallback) } - private fun MediaMetadata.withRawAutoAdjustments( - adjustments: RawDemosaicProcessor.RawAutoAdjustments - ): MediaMetadata { - return copy( - rawExposureCompensation = adjustments.exposureCompensation, - rawHighlightsAdjustment = adjustments.highlights, - rawShadowsAdjustment = adjustments.shadows - ) - } - data class PhotoMetadataUpdate( val photoId: String, val metadata: MediaMetadata @@ -1833,6 +1830,12 @@ object GalleryManager { var dngSaveAttempted = false val captureInfo = metadata.toCaptureInfo() + val rawDngDefaultCrop = RawProcessor.resolveCameraRawDefaultCrop( + width = image.width, + height = image.height, + characteristics = characteristics, + captureResult = resolvedCaptureResult, + ) FileOutputStream(tempDngFile).use { outputStream -> image.use { try { @@ -1850,6 +1853,16 @@ object GalleryManager { cfaCorrectionMode = metadata.rawCfaCorrectionMode, effectiveFocalLengthMm = captureInfo.focalLength, effectiveFocalLength35mm = captureInfo.focalLength35mm, + dngProfilePreparationOptions = rawDngProfilePreparationOptions( + context = context, + metadata = metadata, + width = image.width, + height = image.height, + defaultCrop = rawDngDefaultCrop, + aspectRatio = aspectRatio, + rotation = rotation, + capturePreviewThumbnail = thumbnail, + ), ) } catch (e: Throwable) { PLog.e(TAG, "DNG save failed", e) @@ -1885,7 +1898,6 @@ object GalleryManager { rotation = rotation, exposureBias = exposureBias ?: 0f, rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(context, updatedMetadata), rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f, @@ -1903,7 +1915,6 @@ object GalleryManager { rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, - capturePreviewThumbnail = thumbnail, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -1912,9 +1923,6 @@ object GalleryManager { mDensityGain = updatedMetadata.spectralFilmMDensityGain, yDensityGain = updatedMetadata.spectralFilmYDensityGain ), - onRawAutoAdjustments = { adjustments -> - updatedMetadata = updatedMetadata.withRawAutoAdjustments(adjustments) - }, onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) } @@ -2756,6 +2764,8 @@ object GalleryManager { characteristics = characteristics, captureResult = captureResult, rotation = rotation, + aspectRatio = aspectRatio, + capturePreviewThumbnail = capturePreviewThumbnail, thumbnail = null, metadata = stackedMetadata, shouldAutoSave = shouldAutoSave, @@ -2791,7 +2801,6 @@ object GalleryManager { rotation = rotation, exposureBias = exposureBias ?: 0f, rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(context, updatedMetadata), rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f, @@ -2809,7 +2818,6 @@ object GalleryManager { rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, - capturePreviewThumbnail = capturePreviewThumbnail, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -2818,9 +2826,6 @@ object GalleryManager { mDensityGain = updatedMetadata.spectralFilmMDensityGain, yDensityGain = updatedMetadata.spectralFilmYDensityGain ), - onRawAutoAdjustments = { adjustments -> - updatedMetadata = updatedMetadata.withRawAutoAdjustments(adjustments) - }, onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) } @@ -3067,7 +3072,9 @@ object GalleryManager { applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(context, metadata), colorCorrectionMatrix = rawMetadata.colorCorrectionMatrix, pgtmStatsBounds = rawHdrPgtmStatsBounds, - profileToneMapMode = rawHdrPgtmModeForMetadata(metadata), + // The shared DNG writer prepares baseline/PGTM from the fused buffer. Disable + // the stacker's legacy generator so the write path owns the calculation once. + profileToneMapMode = RawProfileToneMapMode.Default, ) closeImagesNow(images) @@ -3076,17 +3083,16 @@ object GalleryManager { return@withContext false } val fusedBayerBuffer = stackResult.fusedBayerBuffer ?: return@withContext false - val rawHdrBaselineExposureEv = calculateRawHdrDngBaselineExposureEv( + val rawHdrSourceBaselineExposureEv = calculateRawHdrDngBaselineExposureEv( referenceProduct = normalReferenceCandidate.exposureProduct, baseProduct = shortCandidate.exposureProduct, ) PLog.d( TAG, - "RAW HDR stack DNG baseline exposure: ${rawHdrBaselineExposureEv}EV, " + + "RAW HDR stack DNG source baseline exposure: ${rawHdrSourceBaselineExposureEv}EV, " + "outputDomain=short, normalReference=${normalReferenceCandidate.exposureProduct}, " + "short=${shortCandidate.exposureProduct}" ) - val rawHdrProfileGainTableMap = stackResult.profileGainTableMap val stackedMetadata = metadata.withNormalizedRawLevelCorrectionsCleared("RAW HDR stack") val stackRawMetadata = rawMetadata.copy( cfaPattern = stackCfaPattern, @@ -3109,13 +3115,15 @@ object GalleryManager { captureResult = shortCandidate.captureResult, captureMetadataResult = normalReferenceCandidate.captureResult, rotation = rotation, + aspectRatio = aspectRatio, + capturePreviewThumbnail = capturePreviewThumbnail, thumbnail = null, metadata = stackedMetadata, shouldAutoSave = shouldAutoSave, exportDngWithRawExport = exportDngWithRawExport, - baselineExposureEv = rawHdrBaselineExposureEv, - profileGainTableMap = rawHdrProfileGainTableMap, - profileToneMapMode = rawHdrPgtmModeForMetadata(stackedMetadata), + baselineExposureEv = rawHdrSourceBaselineExposureEv, + profileGainTableMap = null, + profileToneMapMode = RawProfileToneMapMode.Default, imageLayout = stackResult.bufferLayout.toDngImageLayout(), compression = stackResult.bufferLayout.toDngCompression(), inputRowStepSamples = stackResult.inputRowStepSamples, @@ -3249,7 +3257,6 @@ object GalleryManager { rotation = rotation, exposureBias = exposureBias ?: 0f, rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(context, updatedMetadata), rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f, @@ -3267,7 +3274,6 @@ object GalleryManager { rawRenderingEngine = updatedMetadata.rawRenderingEngine, rawToneMappingParameters = updatedMetadata.rawToneMappingParameters, rawCfaCorrectionMode = updatedMetadata.rawCfaCorrectionMode, - capturePreviewThumbnail = capturePreviewThumbnail, rawBlackBorderCrop = updatedMetadata.rawBlackBorderCrop, spectralFilmStock = updatedMetadata.spectralFilmStock, spectralFilmPrint = updatedMetadata.spectralFilmPrint, @@ -3276,9 +3282,6 @@ object GalleryManager { mDensityGain = updatedMetadata.spectralFilmMDensityGain, yDensityGain = updatedMetadata.spectralFilmYDensityGain ), - onRawAutoAdjustments = { adjustments -> - updatedMetadata = updatedMetadata.withRawAutoAdjustments(adjustments) - }, onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) } @@ -3395,6 +3398,8 @@ object GalleryManager { captureResult: CaptureResult, captureMetadataResult: CaptureResult? = null, rotation: Int, + aspectRatio: AspectRatio?, + capturePreviewThumbnail: Bitmap?, thumbnail: Bitmap?, metadata: MediaMetadata, shouldAutoSave: Boolean, @@ -3409,6 +3414,12 @@ object GalleryManager { ): Boolean { val tempDngFile = File(dngFile.parentFile, "temp_stacked.dng") val captureInfo = metadata.toCaptureInfo() + val rawDngDefaultCrop = RawProcessor.resolveCameraRawDefaultCrop( + width = width, + height = height, + characteristics = characteristics, + captureResult = captureResult, + ) val dngWritten = try { FileOutputStream(tempDngFile).use { outputStream -> RawProcessor.saveRawBufferToDng( @@ -3443,14 +3454,19 @@ object GalleryManager { compression = compression, inputRowStepSamples = inputRowStepSamples, inputColStepSamples = inputColStepSamples, - // Carry the Camera2 field of view into the DNG itself. The renderer consumes - // DefaultCrop after OpcodeList3, matching the DNG SDK processing order. - defaultCrop = RawProcessor.resolveCameraRawDefaultCrop( + dngProfilePreparationOptions = rawDngProfilePreparationOptions( + context = context, + metadata = metadata, width = width, height = height, - characteristics = characteristics, - captureResult = captureResult, + defaultCrop = rawDngDefaultCrop, + aspectRatio = aspectRatio, + rotation = rotation, + capturePreviewThumbnail = capturePreviewThumbnail, ), + // Carry the Camera2 field of view into the DNG itself. The renderer consumes + // DefaultCrop after OpcodeList3, matching the DNG SDK processing order. + defaultCrop = rawDngDefaultCrop, ) } } catch (e: Throwable) { @@ -3603,8 +3619,66 @@ object GalleryManager { } } - private fun rawHdrPgtmModeForMetadata(metadata: MediaMetadata): RawProfileToneMapMode { - return RawProfileToneMapMode.Photon + private fun rawDngPgtmModeForMetadata(metadata: MediaMetadata): RawProfileToneMapMode { + return metadata.rawToneMappingParameters.profileToneMapMode + } + + private suspend fun rawDngProfilePreparationOptions( + context: Context, + metadata: MediaMetadata, + width: Int, + height: Int, + defaultCrop: Rect?, + aspectRatio: AspectRatio?, + rotation: Int, + capturePreviewThumbnail: Bitmap?, + ): RawDngProfilePreparationOptions { + val viewfinderMatchEnabled = capturePreviewThumbnail != null && + resolveRawAutoExposure(context, metadata) && + kotlin.math.abs(metadata.rawExposureCompensation ?: 0f) <= 0.0001f + val viewfinderExposureMatcher = if (viewfinderMatchEnabled) { + val preview = requireNotNull(capturePreviewThumbnail) + RawDngViewfinderExposureMatcher { input -> + RawViewfinderExposureMatcher.match( + renderer = RawDemosaicProcessor.getInstance(), + context = context, + input = input, + aspectRatio = aspectRatio, + cropRegion = metadata.cropRegion, + rotation = rotation, + capturePreviewThumbnail = preview, + rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f, + rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f, + rawAutoWhiteBalanceEstimate = resolveRawAutoWhiteBalanceEstimate( + context, + metadata, + ), + applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled( + context, + metadata, + ), + rawBlackBorderCrop = metadata.rawBlackBorderCrop, + ) + } + } else { + null + } + PLog.i( + TAG, + "RAW_VIEWFINDER_BASELINE stage=DNG_PREPARE enabled=$viewfinderMatchEnabled " + + "curve=DEFAULT pgtmDuringMatch=false sourceAutoExposure=${metadata.rawAutoExposure} " + + "manualExposureEv=${metadata.rawExposureCompensation ?: 0f}" + ) + return RawDngProfilePreparationOptions( + profileToneMapMode = rawDngPgtmModeForMetadata(metadata), + statsBounds = resolveRawStatsBounds( + width = width, + height = height, + defaultCrop = defaultCrop, + cropRegion = metadata.cropRegion, + ), + viewfinderExposureMatcher = viewfinderExposureMatcher, + ) } private fun profileNameForPgtmMode(mode: RawProfileToneMapMode): String { @@ -4513,7 +4587,6 @@ object GalleryManager { context, dngFile.absolutePath, null, null, 0, rawExposureCompensation = updatedMetadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(context, updatedMetadata), rawHighlightsAdjustment = updatedMetadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = updatedMetadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = updatedMetadata.rawBlackPointCorrection ?: 0f, @@ -4541,9 +4614,6 @@ object GalleryManager { ), onMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) - }, - onRawAutoAdjustments = { adjustments -> - updatedMetadata = updatedMetadata.withRawAutoAdjustments(adjustments) } ) @@ -4681,7 +4751,6 @@ object GalleryManager { context, dngFile.absolutePath, metadata?.ratio, metadata?.cropRegion, 0, rawExposureCompensation = updatedMetadata?.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(context, updatedMetadata), rawHighlightsAdjustment = updatedMetadata?.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = updatedMetadata?.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = updatedMetadata?.rawBlackPointCorrection ?: 0f, @@ -4699,7 +4768,6 @@ object GalleryManager { rawRenderingEngine = updatedMetadata?.rawRenderingEngine ?: MediaMetadata().rawRenderingEngine, rawToneMappingParameters = updatedMetadata?.rawToneMappingParameters ?: MediaMetadata().rawToneMappingParameters, rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode, - useEmbeddedPreviewForAutoExposure = false, rawBlackBorderCrop = rawMetadata.rawBlackBorderCrop, spectralFilmStock = updatedMetadata?.spectralFilmStock, spectralFilmPrint = updatedMetadata?.spectralFilmPrint, @@ -4710,9 +4778,6 @@ object GalleryManager { ), onMetadata = { raw -> updatedMetadata = updatedMetadata?.merge(raw) ?: MediaMetadata().merge(raw) - }, - onRawAutoAdjustments = { adjustments -> - updatedMetadata = (updatedMetadata ?: MediaMetadata()).withRawAutoAdjustments(adjustments) } ) 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 cbce7534..86e977e5 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt @@ -23,6 +23,16 @@ import kotlin.math.log2 const val TONEMAP_MODE_NATURAL_LIGHT = "NATURAL_LIGHT" +private fun JSONObject.optCompatibleRawAutoExposure(): Boolean? { + if (!isNull("rawAutoExposureMode")) { + when (optString("rawAutoExposureMode")) { + "OFF" -> return false + "VIEWFINDER_MATCH", "DYNAMIC_SCENE_ESTIMATION" -> return true + } + } + return if (isNull("rawAutoExposure")) null else optBoolean("rawAutoExposure") +} + /** * 照片元数据 * @@ -296,7 +306,7 @@ data class MediaMetadata( captureNoiseReductionLevel = if (obj.isNull("captureNoiseReductionLevel")) null else obj.optInt("captureNoiseReductionLevel"), rawDenoiseValue = if (obj.isNull("denoiseValue")) null else obj.optDouble("denoiseValue").toFloat(), rawExposureCompensation = if (obj.isNull("rawExposureCompensation")) null else obj.optDouble("rawExposureCompensation").toFloat(), - rawAutoExposure = if (obj.isNull("rawAutoExposure")) null else obj.optBoolean("rawAutoExposure"), + rawAutoExposure = obj.optCompatibleRawAutoExposure(), rawHighlightsAdjustment = if (obj.isNull("rawHighlightsAdjustment")) null else obj.optDouble("rawHighlightsAdjustment").toFloat(), rawShadowsAdjustment = if (obj.isNull("rawShadowsAdjustment")) null else obj.optDouble("rawShadowsAdjustment").toFloat(), rawBlackPointCorrection = if (obj.isNull("rawBlackPointCorrection")) null else obj.optDouble("rawBlackPointCorrection").toFloat(), 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 7a5aa856..287db00d 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -84,11 +84,6 @@ class PhotoProcessor( } } - private suspend fun resolveRawAutoExposure(metadata: MediaMetadata): Boolean { - return metadata.rawAutoExposure - ?: (userPreferencesRepository.userPreferences.firstOrNull()?.rawAutoExposure ?: true) - } - private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float { return metadata.noiseReduction ?: (if (metadata.isImported) 0f else fallback) } @@ -432,7 +427,6 @@ class PhotoProcessor( sharpening: Float = 0f, noiseReduction: Float = 0f, chromaNoiseReduction: Float = 0f, - onRawAutoAdjustments: ((RawDemosaicProcessor.RawAutoAdjustments) -> Unit)? = null, onRawMetadata: ((RawMetadata) -> Unit)? = null ): Bitmap? { val dngFile = GalleryManager.getDngFile(context, photoId) @@ -464,7 +458,6 @@ class PhotoProcessor( sharpening, noiseReduction, chromaNoiseReduction, - onRawAutoAdjustments, onRawMetadata ) } else if (GalleryManager.getOriginalImageFile(context, photoId) != null) { @@ -503,7 +496,6 @@ class PhotoProcessor( rotation = metadata.rotation, exposureBias = metadata.exposureBias ?: 0f, rawExposureCompensation = metadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(metadata), rawHighlightsAdjustment = metadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = metadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f, @@ -558,7 +550,6 @@ class PhotoProcessor( sharpening: Float = 0f, noiseReduction: Float = 0f, chromaNoiseReduction: Float = 0f, - onRawAutoAdjustments: ((RawDemosaicProcessor.RawAutoAdjustments) -> Unit)? = null, onRawMetadata: ((RawMetadata) -> Unit)? = null ): Bitmap? = withContext(Dispatchers.IO) { var result: Bitmap? @@ -584,7 +575,6 @@ class PhotoProcessor( metadata.rotation, metadata.exposureBias ?: 0f, rawExposureCompensation = metadata.rawExposureCompensation ?: 0f, - rawAutoExposure = resolveRawAutoExposure(metadata), rawHighlightsAdjustment = metadata.rawHighlightsAdjustment ?: 0f, rawShadowsAdjustment = metadata.rawShadowsAdjustment ?: 0f, rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f, @@ -610,7 +600,6 @@ class PhotoProcessor( mDensityGain = metadata.spectralFilmMDensityGain, yDensityGain = metadata.spectralFilmYDensityGain ), - onRawAutoAdjustments = onRawAutoAdjustments, onMetadata = onRawMetadata ) diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt index fee219ee..06604e59 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryDatabase.kt @@ -8,7 +8,7 @@ import com.hinnka.mycamera.raw.RawToneMappingParameters @Database( entities = [GalleryMediaEntity::class], - version = 23, + version = 24, exportSchema = false ) @androidx.room.TypeConverters(GalleryConverters::class) @@ -184,6 +184,22 @@ abstract class GalleryDatabase : RoomDatabase() { } } + private val MIGRATION_23_24 = object : androidx.room.migration.Migration(23, 24) { + override fun migrate(db: androidx.sqlite.db.SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE gallery_media ADD COLUMN rawAutoExposureMode TEXT") + db.execSQL( + """ + UPDATE gallery_media + SET rawAutoExposureMode = CASE + WHEN rawAutoExposure = 1 THEN 'VIEWFINDER_MATCH' + WHEN rawAutoExposure = 0 THEN 'OFF' + ELSE NULL + END + """.trimIndent() + ) + } + } + private fun rebuildGalleryMediaWithoutLegacyGoogleToneMapFlag( db: androidx.sqlite.db.SupportSQLiteDatabase ) { @@ -538,7 +554,8 @@ abstract class GalleryDatabase : RoomDatabase() { MIGRATION_19_20, MIGRATION_20_21, MIGRATION_21_22, - MIGRATION_22_23 + MIGRATION_22_23, + MIGRATION_23_24 ) .fallbackToDestructiveMigrationOnDowngrade(false) .fallbackToDestructiveMigration(false) diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt index 6ddc2642..3e2320c7 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaEntity.kt @@ -47,6 +47,7 @@ data class GalleryMediaEntity( val rawDenoiseValue: Float?, val rawExposureCompensation: Float?, val rawAutoExposure: Boolean?, + val rawAutoExposureMode: String?, val rawHighlightsAdjustment: Float?, val rawShadowsAdjustment: Float?, val rawBlackPointCorrection: Float?, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt index b77cb226..1b18e9f7 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/db/GalleryMediaStore.kt @@ -221,6 +221,7 @@ object GalleryMediaStore { rawDenoiseValue = metadata.rawDenoiseValue, rawExposureCompensation = metadata.rawExposureCompensation, rawAutoExposure = metadata.rawAutoExposure, + rawAutoExposureMode = null, rawHighlightsAdjustment = metadata.rawHighlightsAdjustment, rawShadowsAdjustment = metadata.rawShadowsAdjustment, rawBlackPointCorrection = metadata.rawBlackPointCorrection, @@ -384,6 +385,9 @@ object GalleryMediaStore { } private fun GalleryMediaEntity.toMetadata(): MediaMetadata { + val resolvedRawAutoExposure = rawAutoExposureMode?.let { mode -> + !mode.equals("OFF", ignoreCase = true) + } ?: rawAutoExposure return MediaMetadata( version = version.takeIf { it > 0 } ?: MediaMetadata().version, mediaType = runCatching { MediaType.valueOf(mediaType) }.getOrDefault(MediaType.IMAGE), @@ -399,7 +403,7 @@ object GalleryMediaStore { captureNoiseReductionLevel = captureNoiseReductionLevel, rawDenoiseValue = rawDenoiseValue, rawExposureCompensation = rawExposureCompensation, - rawAutoExposure = rawAutoExposure, + rawAutoExposure = resolvedRawAutoExposure, rawHighlightsAdjustment = rawHighlightsAdjustment, rawShadowsAdjustment = rawShadowsAdjustment, rawBlackPointCorrection = rawBlackPointCorrection, diff --git a/app/src/main/java/com/hinnka/mycamera/phantom/PhantomService.kt b/app/src/main/java/com/hinnka/mycamera/phantom/PhantomService.kt index 8cf97d84..b6b537bd 100644 --- a/app/src/main/java/com/hinnka/mycamera/phantom/PhantomService.kt +++ b/app/src/main/java/com/hinnka/mycamera/phantom/PhantomService.kt @@ -671,13 +671,6 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO val processedBitmap = photoProcessor.process( context, photoId, updatedMetadata, 0f, 0f, 0f, - onRawAutoAdjustments = { adjustments -> - updatedMetadata = updatedMetadata.copy( - rawExposureCompensation = adjustments.exposureCompensation, - rawHighlightsAdjustment = adjustments.highlights, - rawShadowsAdjustment = adjustments.shadows - ) - }, onRawMetadata = { raw -> updatedMetadata = updatedMetadata.merge(raw) } diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt index 2922cab3..eefb79e1 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesRawStacker.kt @@ -11,7 +11,6 @@ import android.opengl.GLES30 import android.opengl.GLES31 import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.raw.DngHdrProfileGainTableGenerator -import com.hinnka.mycamera.raw.DngPhotonProfileGainTableGenerator import com.hinnka.mycamera.raw.DngPgtmDiagnostic import com.hinnka.mycamera.raw.DngPgtmGlobalStats import com.hinnka.mycamera.raw.RawProfileToneMapMode @@ -614,7 +613,6 @@ class GlesRawStacker( val referenceExposureProduct = validExposureProduct(normalFrames.first().exposureProduct) val referenceOutputScale = hdrExposureScale(shortExposureProduct, referenceExposureProduct) val shortAlignmentScale = hdrExposureScale(referenceExposureProduct, shortExposureProduct) - val rawHdrBaselineExposureEv = hdrBaselineExposureEv(shortExposureProduct, referenceExposureProduct) val alignmentScales = normalFrames.map { hdrExposureScale(referenceExposureProduct, validExposureProduct(it.exposureProduct)) } @@ -683,7 +681,6 @@ class GlesRawStacker( ) val readTiming = readHdrLinearOutput(outputBuffer) outputBuffer.rewind() - val profileGainTableMap = computeHdrProfileGainTableMap(rawHdrBaselineExposureEv) val diagnostics = if (hwmfDebug.collectMetrics) { collectFinalDiagnostics( frameCount = normalFrames.size + 1, @@ -707,12 +704,8 @@ class GlesRawStacker( isNormalizedSensorData = true, blackLevel = normalizedBlackLevel.copyOf(), fusedBayerUsesNativeAllocator = true, - profileGainTableMap = profileGainTableMap, - profileToneMapMode = if (profileGainTableMap != null) { - profileToneMapMode - } else { - RawProfileToneMapMode.Default - }, + profileGainTableMap = null, + profileToneMapMode = RawProfileToneMapMode.Default, diagnostics = diagnostics, bufferLayout = RawStackBufferLayout.LINEAR_RGB, inputRowStepSamples = width * 4, @@ -891,7 +884,6 @@ class GlesRawStacker( rcdStripeStep42Program = linkComputeProgram(RcdShaders.STEP_4_2, "raw_hdr_rcd_step42") rcdStripeStep43Program = linkComputeProgram(RcdShaders.STEP_4_3, "raw_hdr_rcd_step43") } - pgtmStatsProgram = linkComputeProgram(PGTM_STATS_COMPUTE_SHADER, "raw_hdr_pgtm_stats") } private fun validateOutputTextureLimits() { @@ -1250,7 +1242,9 @@ class GlesRawStacker( }.coerceIn(0f, 8f) } - private fun computeHdrProfileGainTableMap(baselineExposureEv: Float): com.hinnka.mycamera.raw.DngProfileGainTableMap? { + private fun computeHdrProfileGainTableMap( + baselineExposureEv: Float, + ): com.hinnka.mycamera.raw.DngProfileGainTableMap? { if (!baselineExposureEv.isFinite() || baselineExposureEv <= 0.05f || pgtmStatsProgram == 0) { return null } @@ -1270,7 +1264,7 @@ class GlesRawStacker( } val cellCount = pgtmGridWidth * pgtmGridHeight - val collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon + val collectGlobalStats = false val cellStatsWordCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE val cellSumsOffset = if (collectGlobalStats) cellStatsWordCount else -1 val globalHistogramOffset = if (collectGlobalStats) { @@ -1402,26 +1396,13 @@ class GlesRawStacker( null } val diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU stacker") - val map = when (profileToneMapMode) { - RawProfileToneMapMode.Photon -> DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = packedCellStats, - globalStats = globalStats - ?: throw IllegalStateException("GPU Photon PGTM global stats are missing"), - diagnosticBand = diagnosticBand, - statsSource = "gpu-log-histogram-$PGTM_GLOBAL_HISTOGRAM_BIN_COUNT" - ) - - else -> DngHdrProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = packedCellStats, - diagnosticBand = diagnosticBand - ) - } + val generation = DngHdrProfileGainTableGenerator.forCellStats( + width = width, + height = height, + baselineExposureEv = baselineExposureEv, + packedCellStats = packedCellStats, + diagnosticBand = diagnosticBand, + ) val completeNs = System.nanoTime() PLog.d( TAG, @@ -1432,7 +1413,7 @@ class GlesRawStacker( "curveMs=${(completeNs - statsReadyNs) / 1_000_000.0} " + "totalMs=${(completeNs - totalStartNs) / 1_000_000.0}" ) - map + generation } catch (e: Exception) { PLog.w(TAG, "Failed to compute GPU HDR PGTM stats", e) null diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt index d18fef70..13c8ea37 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrProfileGainTableGenerator.kt @@ -156,7 +156,7 @@ internal object DngHdrProfileGainTableGenerator { brightnessTarget: HdrExposureFusionBrightnessTarget? = null, resolutionDiagnostics: ((HdrExposureFusionResolutionDiagnostics) -> Unit)? = null, ): DngProfileGainTableMap? { - if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite() || baselineExposureEv < 0f) { + if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) { return null } val grid = chooseLtmGrid(width, height) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriter.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriter.kt deleted file mode 100644 index 5a1deaa0..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriter.kt +++ /dev/null @@ -1,409 +0,0 @@ -package com.hinnka.mycamera.raw - -import com.hinnka.mycamera.BuildConfig -import com.hinnka.mycamera.utils.PLog -import java.io.ByteArrayOutputStream -import java.io.File -import java.io.RandomAccessFile -import java.nio.ByteBuffer -import java.nio.ByteOrder - -internal object DngPgtmDebugRewriter { - private const val TAG = "DngPgtmDebugRewriter" - - private const val REWRITE_GENERATED_PGTM_ON_RAW_REFRESH = false - - private const val TIFF_CLASSIC_MAGIC = 42 - private const val TYPE_BYTE = 1 - private const val TYPE_LONG = 4 - private const val TYPE_FLOAT = 11 - private const val TYPE_UNDEFINED = 7 - - private const val TAG_NEW_SUBFILE_TYPE = 254 - private const val TAG_XMP = DngCameraRawProfileXmp.TAG_XMP - private const val TAG_SUB_IFDS = 330 - private const val TAG_DNG_VERSION = 50706 - private const val TAG_PROFILE_NAME = 50936 - private const val TAG_PROFILE_TONE_CURVE = 50940 - private const val TAG_DEFAULT_BLACK_RENDER = 51110 - private const val TAG_PROFILE_GAIN_TABLE_MAP = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP - private const val TAG_PROFILE_GAIN_TABLE_MAP_2 = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 - - fun rewriteGeneratedPgtmOnRawRefreshIfEnabled( - dngFile: File?, - profileGainTableMap: DngProfileGainTableMap?, - profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon, - ): Boolean { - if (!BuildConfig.DEBUG || !REWRITE_GENERATED_PGTM_ON_RAW_REFRESH) return false - val file = dngFile ?: return false - val map = profileGainTableMap?.takeIf { it.isValid } ?: return false - return rewriteProfileGainTableMap(file, map, profileToneMapMode) - } - - fun rewriteProfileGainTableMap( - dngFile: File, - profileGainTableMap: DngProfileGainTableMap, - profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon, - ): Boolean { - if (!BuildConfig.DEBUG) return false - if (!profileGainTableMap.isValid || !dngFile.exists() || dngFile.length() < 16L) { - return false - } - return runCatching { - RandomAccessFile(dngFile, "rw").use { raf -> - val byteOrder = readTiffByteOrder(raf) ?: return@use false - val magic = raf.readUnsignedShort(byteOrder) - if (magic != TIFF_CLASSIC_MAGIC) { - logWarning("Unsupported TIFF magic=$magic in ${dngFile.name}") - return@use false - } - val ifd0Offset = raf.readUnsignedInt(byteOrder) - val ifd0 = readIfd(raf, ifd0Offset, byteOrder) ?: return@use false - val subIfdOffsets = readLongValues( - raf, - ifd0.entries.firstOrNull { it.tag == TAG_SUB_IFDS }, - byteOrder, - ) ?: return@use false - val rawSubIfdIndex = subIfdOffsets.indices.firstOrNull { index -> - val candidate = readIfd(raf, subIfdOffsets[index], byteOrder) - candidate?.entries?.firstOrNull { it.tag == TAG_NEW_SUBFILE_TYPE } - ?.let { readInlineLong(it, byteOrder) == 0L } == true - } ?: return@use false - val rawIfdOffset = subIfdOffsets[rawSubIfdIndex] - val rawIfd = readIfd(raf, rawIfdOffset, byteOrder) ?: return@use false - val profileLookName = profileLookNameForToneMapMode(profileToneMapMode) - val cameraRawProfileXmp = DngCameraRawProfileXmp.build( - profileLookName = profileLookName, - ) - val toneCurvePoints = profileToneCurveForToneMapMode(profileToneMapMode) - val pgtmPayload = profileGainTableMap.encodeProfileGainTableMap2(byteOrder) - val newRawIfdOffset = appendIfdWithReplacements( - raf = raf, - original = rawIfd, - replacements = emptyList(), - removedTags = setOf( - TAG_PROFILE_GAIN_TABLE_MAP, - TAG_PROFILE_GAIN_TABLE_MAP_2, - ), - byteOrder = byteOrder, - ) ?: return@use false - subIfdOffsets[rawSubIfdIndex] = newRawIfdOffset - val replacements = listOf( - TiffValue( - tag = TAG_XMP, - type = TYPE_BYTE, - count = cameraRawProfileXmp.size.toLong(), - bytes = cameraRawProfileXmp, - ), - TiffValue( - tag = TAG_DNG_VERSION, - type = TYPE_BYTE, - count = 4, - bytes = byteArrayOf(1, 7, 0, 0) - ), - TiffValue( - tag = TAG_PROFILE_TONE_CURVE, - type = TYPE_FLOAT, - count = toneCurvePoints.size.toLong(), - bytes = encodeFloatArray( - values = toneCurvePoints, - byteOrder = byteOrder - ) - ), - TiffValue( - tag = TAG_DEFAULT_BLACK_RENDER, - type = TYPE_LONG, - count = 1, - bytes = uintBytes(1, byteOrder) - ), - TiffValue( - tag = TAG_PROFILE_GAIN_TABLE_MAP_2, - type = TYPE_UNDEFINED, - count = pgtmPayload.size.toLong(), - bytes = pgtmPayload, - ), - TiffValue( - tag = TAG_SUB_IFDS, - type = TYPE_LONG, - count = subIfdOffsets.size.toLong(), - bytes = encodeLongArray(subIfdOffsets, byteOrder), - ) - ) - val newIfdOffset = appendIfdWithReplacements( - raf = raf, - original = ifd0, - replacements = replacements, - removedTags = setOf( - TAG_PROFILE_NAME, - TAG_PROFILE_GAIN_TABLE_MAP, - TAG_PROFILE_GAIN_TABLE_MAP_2, - ), - byteOrder = byteOrder - ) ?: return@use false - raf.seek(4) - raf.writeUInt(newIfdOffset, byteOrder) - logInfo( - "Rewrote debug DNG PGTM: file=${dngFile.name} " + - "profile=anonymous-embedded look=$profileLookName " + - "cameraRawLook=pgtm=100,toneCurve=100 " + - "tag=${DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2} " + - "grid=${profileGainTableMap.mapPointsH}x${profileGainTableMap.mapPointsV}x" + - "${profileGainTableMap.mapPointsN} gamma=${profileGainTableMap.gamma} " + - "rawIfd=$rawIfdOffset->$newRawIfdOffset " + - "ifd0=$ifd0Offset->$newIfdOffset" - ) - true - } - }.onFailure { - logWarning("Failed to rewrite debug DNG PGTM: ${dngFile.absolutePath}", it) - }.getOrDefault(false) - } - - private fun logInfo(message: String) { - runCatching { PLog.i(TAG, message) } - } - - private fun logWarning(message: String, throwable: Throwable? = null) { - runCatching { - if (throwable != null) { - PLog.w(TAG, message, throwable) - } else { - PLog.w(TAG, message) - } - } - } - - private fun profileLookNameForToneMapMode(mode: RawProfileToneMapMode): String { - return when (mode) { - RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME - else -> DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME - } - } - - private fun profileToneCurveForToneMapMode(mode: RawProfileToneMapMode): FloatArray { - return when (mode) { - RawProfileToneMapMode.Photon -> DngProfileToneCurve.photonPgtmToneCurvePoints() - else -> DngProfileToneCurve.googleHdrToneCurvePoints() - } - } - - private fun appendIfdWithReplacements( - raf: RandomAccessFile, - original: TiffIfd, - replacements: List, - removedTags: Set = emptySet(), - byteOrder: ByteOrder, - ): Long? { - if (replacements.isEmpty() && removedTags.isEmpty()) return null - val replacementByTag = replacements.associateBy { it.tag } - val merged = LinkedHashMap() - original.entries.forEach { entry -> - if (entry.tag !in replacementByTag && entry.tag !in removedTags) { - merged[entry.tag] = IfdValue.Existing(entry) - } - } - replacements.forEach { replacement -> - merged[replacement.tag] = IfdValue.Replacement(replacement) - } - val values = merged.values.sortedBy { it.tag } - if (values.size > MAX_IFD_ENTRY_COUNT || values.any { it.count > UINT_MAX }) return null - - val ifdOffset = alignedAppendOffset(raf) - val dataBaseOffset = ifdOffset + 2L + values.size * 12L + 4L - if (dataBaseOffset > UINT_MAX) return null - - val dataArea = ByteArrayOutputStream() - val entryArea = ByteArrayOutputStream() - values.forEach { value -> - entryArea.writeUShort(value.tag, byteOrder) - entryArea.writeUShort(value.type, byteOrder) - entryArea.writeUInt(value.count, byteOrder) - when (value) { - is IfdValue.Existing -> entryArea.write(value.entry.inlineOrOffset) - is IfdValue.Replacement -> { - val replacementBytes = value.value.bytes - if (replacementBytes.size <= 4) { - entryArea.write(inlineValue(replacementBytes)) - } else { - if ((dataArea.size() and 1) != 0) dataArea.write(0) - val valueOffset = dataBaseOffset + dataArea.size().toLong() - if (valueOffset + replacementBytes.size.toLong() > UINT_MAX) return null - entryArea.write(uintBytes(valueOffset, byteOrder)) - dataArea.write(replacementBytes) - } - } - } - } - - raf.seek(ifdOffset) - raf.writeUShort(values.size, byteOrder) - raf.write(entryArea.toByteArray()) - raf.writeUInt(original.nextIfdOffset, byteOrder) - raf.write(dataArea.toByteArray()) - return ifdOffset - } - - private fun alignedAppendOffset(raf: RandomAccessFile): Long { - val offset = raf.length() - raf.seek(offset) - if ((offset and 1L) != 0L) { - raf.write(0) - return offset + 1L - } - return offset - } - - private fun readTiffByteOrder(raf: RandomAccessFile): ByteOrder? { - raf.seek(0) - val marker0 = raf.readUnsignedByte() - val marker1 = raf.readUnsignedByte() - return when { - marker0 == 'I'.code && marker1 == 'I'.code -> ByteOrder.LITTLE_ENDIAN - marker0 == 'M'.code && marker1 == 'M'.code -> ByteOrder.BIG_ENDIAN - else -> null - } - } - - private fun readIfd( - raf: RandomAccessFile, - offset: Long, - byteOrder: ByteOrder, - ): TiffIfd? { - if (offset <= 0L || offset >= raf.length()) return null - raf.seek(offset) - val entryCount = raf.readUnsignedShort(byteOrder) - val entries = ArrayList(entryCount) - repeat(entryCount) { - val tag = raf.readUnsignedShort(byteOrder) - val type = raf.readUnsignedShort(byteOrder) - val count = raf.readUnsignedInt(byteOrder) - val inlineOrOffset = ByteArray(4) - raf.readFully(inlineOrOffset) - entries += TiffEntry( - tag = tag, - type = type, - count = count, - inlineOrOffset = inlineOrOffset - ) - } - return TiffIfd( - entries = entries, - nextIfdOffset = raf.readUnsignedInt(byteOrder) - ) - } - - private fun encodeFloatArray(values: FloatArray, byteOrder: ByteOrder): ByteArray { - val buffer = ByteBuffer - .allocate(values.size * 4) - .order(byteOrder) - values.forEach { value -> buffer.putFloat(value.takeIf { it.isFinite() } ?: 0f) } - return buffer.array() - } - - private fun encodeLongArray(values: LongArray, byteOrder: ByteOrder): ByteArray { - val buffer = ByteBuffer.allocate(values.size * 4).order(byteOrder) - values.forEach { buffer.putInt((it and UINT_MAX).toInt()) } - return buffer.array() - } - - private fun readLongValues( - raf: RandomAccessFile, - entry: TiffEntry?, - byteOrder: ByteOrder, - ): LongArray? { - if (entry == null || entry.type != TYPE_LONG || entry.count <= 0L || - entry.count > MAX_IFD_ENTRY_COUNT.toLong() - ) { - return null - } - if (entry.count == 1L) { - return longArrayOf(readInlineLong(entry, byteOrder)) - } - val offset = readInlineLong(entry, byteOrder) - val byteCount = entry.count * 4L - if (offset <= 0L || offset + byteCount > raf.length()) return null - raf.seek(offset) - return LongArray(entry.count.toInt()) { raf.readUnsignedInt(byteOrder) } - } - - private fun readInlineLong(entry: TiffEntry, byteOrder: ByteOrder): Long = - ByteBuffer.wrap(entry.inlineOrOffset).order(byteOrder).int.toLong() and UINT_MAX - - private fun inlineValue(value: ByteArray): ByteArray = - ByteArray(4).also { value.copyInto(it, endIndex = value.size.coerceAtMost(4)) } - - private fun uintBytes(value: Long, byteOrder: ByteOrder): ByteArray = - ByteBuffer - .allocate(4) - .order(byteOrder) - .putInt((value and UINT_MAX).toInt()) - .array() - - private fun ByteArrayOutputStream.writeUShort(value: Int, byteOrder: ByteOrder) { - write(ByteBuffer.allocate(2).order(byteOrder).putShort((value and 0xFFFF).toShort()).array()) - } - - private fun ByteArrayOutputStream.writeUInt(value: Long, byteOrder: ByteOrder) { - write(uintBytes(value, byteOrder)) - } - - private fun RandomAccessFile.writeUShort(value: Int, byteOrder: ByteOrder) { - write(ByteBuffer.allocate(2).order(byteOrder).putShort((value and 0xFFFF).toShort()).array()) - } - - private fun RandomAccessFile.writeUInt(value: Long, byteOrder: ByteOrder) { - write(uintBytes(value, byteOrder)) - } - - private fun RandomAccessFile.readUnsignedShort(byteOrder: ByteOrder): Int { - val bytes = ByteArray(2) - readFully(bytes) - return ByteBuffer.wrap(bytes).order(byteOrder).short.toInt() and 0xFFFF - } - - private fun RandomAccessFile.readUnsignedInt(byteOrder: ByteOrder): Long { - val bytes = ByteArray(4) - readFully(bytes) - return ByteBuffer.wrap(bytes).order(byteOrder).int.toLong() and UINT_MAX - } - - private sealed class IfdValue { - abstract val tag: Int - abstract val type: Int - abstract val count: Long - - data class Existing(val entry: TiffEntry) : IfdValue() { - override val tag: Int = entry.tag - override val type: Int = entry.type - override val count: Long = entry.count - } - - data class Replacement(val value: TiffValue) : IfdValue() { - override val tag: Int = value.tag - override val type: Int = value.type - override val count: Long = value.count - } - } - - private data class TiffIfd( - val entries: List, - val nextIfdOffset: Long, - ) - - private data class TiffEntry( - val tag: Int, - val type: Int, - val count: Long, - val inlineOrOffset: ByteArray, - ) - - private data class TiffValue( - val tag: Int, - val type: Int, - val count: Long, - val bytes: ByteArray, - ) - - private const val MAX_IFD_ENTRY_COUNT = 65_535 - private const val UINT_MAX = 0xFFFF_FFFFL -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt deleted file mode 100644 index ed1252c6..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.hinnka.mycamera.raw - -import com.hinnka.mycamera.utils.PLog - -/** - * Photon uses Google's current PGTM implementation and translates a fixed-span synthetic - * exposure stack from the historical Photon scene-brightness target. The fusion key remains a - * curve-shape parameter; one exposure stays pinned to inputScale to protect highlight layers. - */ -internal object DngPhotonProfileGainTableGenerator { - private const val TAG = "DngPhotonProfileGainTableGenerator" - private const val DEFAULT_TABLE_POINTS = 257 - - internal val PHOTON_FUSION_PARAMETERS = HdrExposureFusionParameters( - autoExposureTarget = 0.230f, - wellExposedKey = 0.720f, - maxExposureGain = 9.50f, - compactHdrExposureOffsetEv = 0.920f, - highlightFusionStart = 0.200f, - highlightFusionEnd = 0.650f, - ) - - fun forCellStats( - width: Int, - height: Int, - baselineExposureEv: Float, - packedCellStats: FloatArray, - globalStats: DngPgtmGlobalStats, - tablePointCount: Int = DEFAULT_TABLE_POINTS, - diagnosticBand: DngHdrProfileGainTableGenerator.DiagnosticBand? = null, - emitDiagnostics: Boolean = true, - statsSource: String = "global-samples", - ): DngProfileGainTableMap? { - val brightnessTarget = PhotonPgtmBrightnessModel.resolve(globalStats) - var fusionResolution: HdrExposureFusionResolutionDiagnostics? = null - val map = DngHdrProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = packedCellStats, - tablePointCount = tablePointCount, - diagnosticBand = diagnosticBand, - fusionParameters = PHOTON_FUSION_PARAMETERS, - brightnessTarget = brightnessTarget?.fusionTarget, - resolutionDiagnostics = { fusionResolution = it }, - ) ?: return null - - if (emitDiagnostics) { - val inputScale = map.mapInputWeights.sum() - val sceneWhite = 1f / inputScale - val p50Input = globalStats.p50.takeIf { it.isFinite() && it > 0f } ?: 0f - PLog.d( - TAG, - "Built adaptive Photon with Google PGTM: grid=${map.mapPointsH}x${map.mapPointsV}x" + - "${map.mapPointsN} statsSource=$statsSource " + - "globalSampleCount=${globalStats.sampleCount} baselineEv=$baselineExposureEv " + - "autoExposureTarget=${PHOTON_FUSION_PARAMETERS.autoExposureTarget} " + - "wellExposedKey=${PHOTON_FUSION_PARAMETERS.wellExposedKey} " + - "maxExposureGain=${PHOTON_FUSION_PARAMETERS.maxExposureGain} " + - "compactHdrOffsetEv=${PHOTON_FUSION_PARAMETERS.compactHdrExposureOffsetEv} " + - "inputScale=$inputScale sceneWhite=$sceneWhite " + - "p50Input=$p50Input " + - "brightnessAnchor=${brightnessTarget?.sceneAnchor} " + - "anchorSource=${brightnessTarget?.anchorSource} " + - "displayTarget=${brightnessTarget?.displayTarget} " + - "exposureLiftEv=${brightnessTarget?.exposureLiftEv} " + - "tailRangeEv=${brightnessTarget?.tailRangeEv} " + - "exposureRangeEv=${brightnessTarget?.exposureRangeEv} " + - "highlightGapEv=${brightnessTarget?.highlightGapEv} " + - "sparseStrength=${brightnessTarget?.sparseHighlightStrength} " + - "dynamicRangeEv=${brightnessTarget?.dynamicRangeEv} " + - "referenceCenterEv=${fusionResolution?.referenceCenterEv} " + - "resolvedCenterEv=${fusionResolution?.resolvedCenterEv} " + - "centeredSpanEv=${fusionResolution?.centeredExposureSpanEv} " + - "brightnessErrorEv=${fusionResolution?.brightnessErrorEv} " + - "protectedExposureGain=${fusionResolution?.protectedExposureGain}" - ) - } - return map - } -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngProfileGainTableGeneration.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileGainTableGeneration.kt new file mode 100644 index 00000000..9416b10f --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileGainTableGeneration.kt @@ -0,0 +1,7 @@ +package com.hinnka.mycamera.raw + +/** Legacy GPU result kept until the obsolete render-time PGTM shader is removed. */ +internal data class DngProfileGainTableGeneration( + val baselineExposureEv: Float, + val profileGainTableMap: DngProfileGainTableMap, +) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt index 907cdc78..cffe4f87 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngProfileToneCurve.kt @@ -94,25 +94,16 @@ internal object DngProfileToneCurve { 0.02343750f, 0.002622200f, 0.02734375f, 0.004144829f, 0.03125000f, 0.005831674f, - 0.04687500f, 0.011777433f, - 0.06250000f, 0.018572280f, - 0.09375000f, 0.034529686f, - 0.12500000f, 0.053344787f, - 0.17968750f, 0.092067414f, - 0.21875000f, 0.123345188f, - 0.25000000f, 0.150000000f, - 0.28125000f, 0.180555931f, - 0.31250000f, 0.216832463f, - 0.37500000f, 0.301148691f, - 0.43750000f, 0.392151404f, + 0.04687500f, 0.013821328f, + 0.06250000f, 0.023228984f, + 0.09375000f, 0.045079457f, + 0.12500000f, 0.069945026f, + 0.17968750f, 0.118763626f, + 0.25000000f, 0.188884780f, + 0.37500000f, 0.327727005f, 0.50000000f, 0.479043320f, - 0.56250000f, 0.563864078f, - 0.62500000f, 0.650740975f, - 0.68750000f, 0.732008214f, - 0.71875000f, 0.768142651f, - 0.75000000f, 0.800000000f, - 0.78125000f, 0.826992743f, - 0.81250000f, 0.850655138f, + 0.62500000f, 0.636591673f, + 0.75000000f, 0.779041231f, 0.87500000f, 0.896886647f, 1.00000000f, 1.000000000f ) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt b/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt deleted file mode 100644 index 76fd8d4c..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/GlesRawProfileGainTableMapBuilder.kt +++ /dev/null @@ -1,577 +0,0 @@ -package com.hinnka.mycamera.raw - -import android.graphics.Rect -import android.opengl.GLES30 -import android.opengl.GLES31 -import com.hinnka.mycamera.utils.PLog -import java.nio.ByteBuffer -import java.nio.ByteOrder -import kotlin.math.pow - -/** - * Computes dense RAW PGTM statistics on the current GLES context. - * - * One 16x16 workgroup owns one PGTM cell. Samples are converted to profile - * RGB and sorted in shared memory on the GPU. The CPU receives only cell - * percentiles, a compact scene-wide EV histogram, and two sums per cell. - */ -internal class GlesRawProfileGainTableMapBuilder { - private var statsProgram = 0 - - fun initialize(): Boolean { - if (statsProgram != 0) return true - statsProgram = compileComputeProgram(PGTM_STATS_COMPUTE_SHADER) - return statsProgram != 0 - } - - fun release() { - if (statsProgram != 0) { - GLES31.glDeleteProgram(statsProgram) - statsProgram = 0 - } - } - - fun build( - rawTextureId: Int, - width: Int, - height: Int, - metadata: RawMetadata, - samplesPerPixel: Int, - statsBounds: Rect?, - profileToneMapMode: RawProfileToneMapMode, - colorCorrectionMatrix: FloatArray = metadata.colorCorrectionMatrix, - cameraWhite: FloatArray = metadata.cameraWhite, - hueSatMap: DcpHueSatMap? = null, - hueSatTextureId: Int = 0, - ): DngProfileGainTableMap? { - if (statsProgram == 0 || rawTextureId == 0 || width <= 0 || height <= 0) return null - if (profileToneMapMode != RawProfileToneMapMode.Photon && - profileToneMapMode != RawProfileToneMapMode.GooglePixel - ) { - return null - } - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val gridWidth = grid.getOrElse(0) { 0 } - val gridHeight = grid.getOrElse(1) { 0 } - if (gridWidth <= 0 || gridHeight <= 0) return null - - val safeBounds = sanitizeStatsBounds(statsBounds, width, height) ?: return null - val cellCount = gridWidth * gridHeight - val cellStatsWordCount = cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - val cellSumsOffset = cellStatsWordCount - val globalHistogramOffset = cellSumsOffset + cellCount * CELL_SUM_FLOAT_STRIDE - val globalCountersOffset = globalHistogramOffset + GLOBAL_HISTOGRAM_BIN_COUNT - val totalWordCount = globalCountersOffset + GLOBAL_COUNTER_COUNT - val totalBytes = totalWordCount * Int.SIZE_BYTES - val buffers = IntArray(1) - GLES31.glGenBuffers(1, buffers, 0) - val bufferId = buffers[0] - if (bufferId == 0) return null - - val totalStartNs = System.nanoTime() - return try { - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId) - val zeroData = ByteBuffer.allocateDirect(totalBytes).order(ByteOrder.nativeOrder()) - GLES31.glBufferData( - GLES31.GL_SHADER_STORAGE_BUFFER, - totalBytes, - zeroData, - GLES31.GL_DYNAMIC_READ - ) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, BUFFER_BINDING, bufferId) - GLES31.glUseProgram(statsProgram) - GLES31.glActiveTexture(GLES31.GL_TEXTURE0) - GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId) - GLES31.glUniform1i(uniform("uRawTexture"), 0) - GLES31.glUniform2i(uniform("uImageSize"), width, height) - GLES31.glUniform4i( - uniform("uStatsBounds"), - safeBounds.left, - safeBounds.top, - safeBounds.right, - safeBounds.bottom - ) - GLES31.glUniform2i(uniform("uGridSize"), gridWidth, gridHeight) - GLES31.glUniform1i(uniform("uSamplesPerPixel"), samplesPerPixel.coerceAtLeast(1)) - GLES31.glUniform1i(uniform("uCfaPattern"), metadata.cfaPattern) - GLES31.glUniform4fv(uniform("uBlackLevel"), 1, safeBlackLevel(metadata), 0) - GLES31.glUniform1f(uniform("uWhiteLevel"), metadata.whiteLevel.coerceAtLeast(1f)) - GLES31.glUniform1f( - uniform("uBaselineExposureGain"), - 2.0f.pow(DngBaselineExposure.sanitize(metadata.baselineExposure).coerceIn(0f, 8f)) - ) - GLES31.glUniformMatrix3fv( - uniform("uColorCorrectionMatrix"), - 1, - false, - transposeMatrix3x3(colorCorrectionMatrix), - 0 - ) - val safeCameraWhite = safeCameraWhite(cameraWhite) - GLES31.glUniform3f( - uniform("uCameraWhite"), - safeCameraWhite[0], - safeCameraWhite[1], - safeCameraWhite[2], - ) - val activeHueSatMap = hueSatMap?.takeIf { it.isValid && hueSatTextureId != 0 } - GLES31.glUniform1i(uniform("uHueSatMapEnabled"), if (activeHueSatMap != null) 1 else 0) - GLES31.glUniform3i( - uniform("uHueSatMapDivisions"), - activeHueSatMap?.hueDivisions ?: 1, - activeHueSatMap?.satDivisions ?: 1, - activeHueSatMap?.valueDivisions ?: 1, - ) - GLES31.glUniform1i( - uniform("uHueSatMapEncoding"), - activeHueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR, - ) - GLES31.glActiveTexture(GLES31.GL_TEXTURE1) - GLES31.glBindTexture(GLES31.GL_TEXTURE_3D, hueSatTextureId) - GLES31.glUniform1i(uniform("uHueSatMap"), 1) - GLES31.glUniform1i(uniform("uCellSumsOffset"), cellSumsOffset) - GLES31.glUniform1i(uniform("uGlobalHistogramOffset"), globalHistogramOffset) - GLES31.glUniform1i(uniform("uGlobalCountersOffset"), globalCountersOffset) - - val dispatchStartNs = System.nanoTime() - GLES31.glDispatchCompute(gridWidth, gridHeight, 1) - GLES31.glMemoryBarrier( - GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT - ) - checkGlError("dispatch") - - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferId) - val mapped = GLES31.glMapBufferRange( - GLES31.GL_SHADER_STORAGE_BUFFER, - 0, - totalBytes, - GLES31.GL_MAP_READ_BIT - ) as? ByteBuffer ?: error("GPU RAW PGTM stats buffer map failed") - val words = try { - IntArray(totalWordCount).also { values -> - mapped.order(ByteOrder.nativeOrder()).asIntBuffer().get(values) - } - } finally { - GLES31.glUnmapBuffer(GLES31.GL_SHADER_STORAGE_BUFFER) - } - val statsReadyNs = System.nanoTime() - - val packedCellStats = FloatArray(cellStatsWordCount) { index -> - Float.fromBits(words[index]) - } - val sampleCount = words[globalCountersOffset + COUNTER_SAMPLE_COUNT] - .coerceIn(0, cellCount * SAMPLE_COUNT_PER_CELL) - val zeroCount = words[globalCountersOffset + COUNTER_ZERO_COUNT] - .coerceIn(0, sampleCount) - val highlightCount = words[globalCountersOffset + COUNTER_HIGHLIGHT_COUNT] - .coerceIn(0, sampleCount) - val maxInput = Float.fromBits(words[globalCountersOffset + COUNTER_MAX_INPUT_BITS]) - var linearSum = 0.0 - var logSum = 0.0 - for (cellIndex in 0 until cellCount) { - val offset = cellSumsOffset + cellIndex * CELL_SUM_FLOAT_STRIDE - linearSum += Float.fromBits(words[offset]).toDouble() - logSum += Float.fromBits(words[offset + 1]).toDouble() - } - val globalHistogram = IntArray(GLOBAL_HISTOGRAM_BIN_COUNT) { index -> - words[globalHistogramOffset + index].coerceAtLeast(0) - } - val globalStats = DngPgtmGlobalStats.fromLogHistogram( - logHistogram = globalHistogram, - histogramMinEv = GLOBAL_HISTOGRAM_MIN_EV, - histogramMaxEv = GLOBAL_HISTOGRAM_MAX_EV, - sampleCount = sampleCount, - zeroCount = zeroCount, - highlightCount = highlightCount, - maxInput = maxInput, - linearSum = linearSum, - logSum = logSum - ) ?: error("GPU RAW PGTM global stats are empty") - val diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU RAW") - val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure) - val map = when (profileToneMapMode) { - RawProfileToneMapMode.Photon -> DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = packedCellStats, - globalStats = globalStats, - diagnosticBand = diagnosticBand, - statsSource = "gpu-log-histogram-$GLOBAL_HISTOGRAM_BIN_COUNT" - ) - - RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = packedCellStats, - diagnosticBand = diagnosticBand - ) - - RawProfileToneMapMode.Default, - RawProfileToneMapMode.OppoMaster -> null - } - val completeNs = System.nanoTime() - PLog.d( - TAG, - "GPU RAW PGTM built: mode=$profileToneMapMode grid=${gridWidth}x${gridHeight} " + - "samples=$sampleCount readbackBytes=$totalBytes " + - "gpuAndReadbackMs=${(statsReadyNs - dispatchStartNs) / 1_000_000.0} " + - "curveMs=${(completeNs - statsReadyNs) / 1_000_000.0} " + - "totalMs=${(completeNs - totalStartNs) / 1_000_000.0}" - ) - map - } catch (error: Exception) { - PLog.w(TAG, "GPU RAW PGTM generation failed", error) - null - } finally { - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, BUFFER_BINDING, 0) - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) - GLES31.glUseProgram(0) - GLES31.glDeleteBuffers(1, buffers, 0) - } - } - - private fun uniform(name: String): Int = GLES31.glGetUniformLocation(statsProgram, name) - - private fun sanitizeStatsBounds(statsBounds: Rect?, width: Int, height: Int): Rect? { - val imageBounds = Rect(0, 0, width, height) - if (statsBounds == null) return imageBounds - if (statsBounds.isEmpty) return null - return Rect(statsBounds).takeIf { - it.intersect(imageBounds) && it.width() >= 2 && it.height() >= 2 - } - } - - private fun safeBlackLevel(metadata: RawMetadata): FloatArray { - val fallback = metadata.blackLevel.firstOrNull() ?: 0f - return FloatArray(4) { index -> metadata.blackLevel.getOrElse(index) { fallback } } - } - - private fun safeCameraWhite(cameraWhite: FloatArray): FloatArray = FloatArray(3) { index -> - cameraWhite.getOrElse(index) { 1f } - .takeIf { it.isFinite() } - ?.coerceIn(0.001f, 1f) - ?: 1f - } - - private fun transposeMatrix3x3(matrix: FloatArray): FloatArray { - if (matrix.size < 9) { - return floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f) - } - return floatArrayOf( - matrix[0], matrix[3], matrix[6], - matrix[1], matrix[4], matrix[7], - matrix[2], matrix[5], matrix[8] - ) - } - - private fun compileComputeProgram(source: String): Int { - val shader = GLES31.glCreateShader(GLES31.GL_COMPUTE_SHADER) - GLES31.glShaderSource(shader, source) - GLES31.glCompileShader(shader) - val compiled = IntArray(1) - GLES31.glGetShaderiv(shader, GLES31.GL_COMPILE_STATUS, compiled, 0) - if (compiled[0] == 0) { - PLog.e(TAG, "GPU RAW PGTM shader compilation failed: ${GLES31.glGetShaderInfoLog(shader)}") - GLES31.glDeleteShader(shader) - return 0 - } - val program = GLES31.glCreateProgram() - GLES31.glAttachShader(program, shader) - GLES31.glLinkProgram(program) - GLES31.glDeleteShader(shader) - val linked = IntArray(1) - GLES31.glGetProgramiv(program, GLES31.GL_LINK_STATUS, linked, 0) - if (linked[0] == 0) { - PLog.e(TAG, "GPU RAW PGTM program linking failed: ${GLES31.glGetProgramInfoLog(program)}") - GLES31.glDeleteProgram(program) - return 0 - } - return program - } - - private fun checkGlError(stage: String) { - val error = GLES31.glGetError() - if (error != GLES31.GL_NO_ERROR) error("GPU RAW PGTM $stage failed: glError=$error") - } - - private companion object { - private const val TAG = "GlesRawPgtmBuilder" - private const val BUFFER_BINDING = 7 - private const val SAMPLE_GRID = 16 - private const val SAMPLE_COUNT_PER_CELL = SAMPLE_GRID * SAMPLE_GRID - private const val CELL_SUM_FLOAT_STRIDE = 2 - private const val GLOBAL_HISTOGRAM_BIN_COUNT = 2048 - private const val GLOBAL_HISTOGRAM_MIN_EV = -16f - private const val GLOBAL_HISTOGRAM_MAX_EV = 8f - private const val GLOBAL_COUNTER_COUNT = 4 - private const val COUNTER_SAMPLE_COUNT = 0 - private const val COUNTER_ZERO_COUNT = 1 - private const val COUNTER_HIGHLIGHT_COUNT = 2 - private const val COUNTER_MAX_INPUT_BITS = 3 - - private val PGTM_STATS_COMPUTE_SHADER = """ - #version 310 es - precision highp float; - precision highp int; - precision highp usampler2D; - layout(local_size_x = 16, local_size_y = 16) in; - - uniform highp usampler2D uRawTexture; - uniform ivec2 uImageSize; - uniform ivec4 uStatsBounds; - uniform ivec2 uGridSize; - uniform int uSamplesPerPixel; - uniform int uCfaPattern; - uniform vec4 uBlackLevel; - uniform float uWhiteLevel; - uniform float uBaselineExposureGain; - uniform mat3 uColorCorrectionMatrix; - uniform vec3 uCameraWhite; - uniform sampler3D uHueSatMap; - uniform int uHueSatMapEnabled; - uniform ivec3 uHueSatMapDivisions; - uniform int uHueSatMapEncoding; - uniform int uCellSumsOffset; - uniform int uGlobalHistogramOffset; - uniform int uGlobalCountersOffset; - - layout(std430, binding = $BUFFER_BINDING) buffer PgtmData { - uint data[]; - }; - - const int SAMPLE_GRID = 16; - const int SAMPLE_COUNT = 256; - const int STATS_STRIDE = 8; - const int CELL_SUM_STRIDE = 2; - const int GLOBAL_HISTOGRAM_BINS = 2048; - const float GLOBAL_HISTOGRAM_MIN_EV = -16.0; - const float GLOBAL_HISTOGRAM_MAX_EV = 8.0; - const float INV_LOG_2 = 1.4426950408889634; - const int COUNTER_SAMPLE_COUNT = 0; - const int COUNTER_ZERO_COUNT = 1; - const int COUNTER_HIGHLIGHT_COUNT = 2; - const int COUNTER_MAX_INPUT_BITS = 3; - - shared float inputSamples[SAMPLE_COUNT]; - - ${DcpHueSatMapGl.SHADER_FUNCTIONS} - - int baseBayerPattern() { - return uCfaPattern >= 8 ? uCfaPattern - 8 : - (uCfaPattern >= 4 ? uCfaPattern - 4 : uCfaPattern); - } - - int cfaBlockSize() { - return uCfaPattern >= 8 ? 4 : (uCfaPattern >= 4 ? 2 : 1); - } - - int channelIndexAt(ivec2 p) { - int blockSize = cfaBlockSize(); - int xp = (p.x / blockSize) & 1; - int yp = (p.y / blockSize) & 1; - int pattern = baseBayerPattern(); - if (pattern == 1) { - if (yp == 0 && xp == 0) return 1; - if (yp == 0 && xp == 1) return 0; - if (yp == 1 && xp == 0) return 3; - return 2; - } - if (pattern == 2) { - if (yp == 0 && xp == 0) return 2; - if (yp == 0 && xp == 1) return 3; - if (yp == 1 && xp == 0) return 0; - return 1; - } - if (pattern == 3) { - if (yp == 0 && xp == 0) return 3; - if (yp == 0 && xp == 1) return 2; - if (yp == 1 && xp == 0) return 1; - return 0; - } - if (yp == 0 && xp == 0) return 0; - if (yp == 0 && xp == 1) return 1; - if (yp == 1 && xp == 0) return 2; - return 3; - } - - float normalizeRaw(uint raw, int channel) { - float black = uBlackLevel[clamp(channel, 0, 3)]; - return clamp((float(raw) - black) / max(uWhiteLevel - black, 1.0), 0.0, 1.0); - } - - vec3 cameraRgbAt(ivec2 base) { - if (uSamplesPerPixel >= 3) { - ivec2 p = clamp(base, ivec2(0), uImageSize - ivec2(1)); - uvec3 raw = texelFetch(uRawTexture, p, 0).rgb; - return vec3( - normalizeRaw(raw.r, 0), - normalizeRaw(raw.g, 1), - normalizeRaw(raw.b, 2) - ); - } - vec3 sums = vec3(0.0); - vec3 counts = vec3(0.0); - for (int y = 0; y <= 1; ++y) { - for (int x = 0; x <= 1; ++x) { - ivec2 p = clamp(base + ivec2(x, y), ivec2(0), uImageSize - ivec2(1)); - int channel = channelIndexAt(p); - float value = normalizeRaw(texelFetch(uRawTexture, p, 0).r, channel); - if (channel == 0) { - sums.r += value; - counts.r += 1.0; - } else if (channel == 3) { - sums.b += value; - counts.b += 1.0; - } else { - sums.g += value; - counts.g += 1.0; - } - } - } - float fallback = (sums.r + sums.g + sums.b) / - max(counts.r + counts.g + counts.b, 1.0); - return vec3( - counts.r > 0.0 ? sums.r / counts.r : fallback, - counts.g > 0.0 ? sums.g / counts.g : fallback, - counts.b > 0.0 ? sums.b / counts.b : fallback - ); - } - - float pgtmInputAt(ivec2 base) { - vec3 cameraRgb = min(cameraRgbAt(base), max(uCameraWhite, vec3(0.001))); - vec3 profileRgb = clamp(uColorCorrectionMatrix * cameraRgb, vec3(0.0), vec3(1.0)); - if (uHueSatMapEnabled != 0) { - profileRgb = dngApplyHueSatMap( - profileRgb, - uHueSatMap, - uHueSatMapDivisions, - uHueSatMapEncoding - ); - } - profileRgb *= uBaselineExposureGain; - float minChannel = min(profileRgb.r, min(profileRgb.g, profileRgb.b)); - float maxChannel = max(profileRgb.r, max(profileRgb.g, profileRgb.b)); - float value = - 0.1495 * profileRgb.r + - 0.2935 * profileRgb.g + - 0.0570 * profileRgb.b + - 0.1250 * minChannel + - 0.3750 * maxChannel; - return isnan(value) || isinf(value) ? 0.0 : max(value, 0.0); - } - - void main() { - ivec2 cell = ivec2(gl_WorkGroupID.xy); - if (cell.x >= uGridSize.x || cell.y >= uGridSize.y) return; - ivec2 localId = ivec2(gl_LocalInvocationID.xy); - int localIndex = localId.y * SAMPLE_GRID + localId.x; - int cellIndex = cell.y * uGridSize.x + cell.x; - - ivec2 statsMin = clamp(uStatsBounds.xy, ivec2(0), uImageSize - ivec2(1)); - ivec2 statsMax = clamp(uStatsBounds.zw, statsMin + ivec2(1), uImageSize); - ivec2 statsSize = max(statsMax - statsMin, ivec2(2)); - int startX = statsMin.x + (cell.x * statsSize.x) / uGridSize.x; - int endX = statsMin.x + ((cell.x + 1) * statsSize.x + uGridSize.x - 1) / - uGridSize.x; - int startY = statsMin.y + (cell.y * statsSize.y) / uGridSize.y; - int endY = statsMin.y + ((cell.y + 1) * statsSize.y + uGridSize.y - 1) / - uGridSize.y; - startX += startX & 1; - startY += startY & 1; - endX = min(statsMax.x, endX - (endX & 1)); - endY = min(statsMax.y, endY - (endY & 1)); - - if (endX - startX < 2 || endY - startY < 2) { - if (localIndex == 0) { - int offset = cellIndex * STATS_STRIDE; - for (int i = 0; i < STATS_STRIDE; ++i) data[offset + i] = 0u; - int sumOffset = uCellSumsOffset + cellIndex * CELL_SUM_STRIDE; - data[sumOffset] = floatBitsToUint(0.0); - data[sumOffset + 1] = floatBitsToUint(0.0); - } - return; - } - - int cellWidth = max(endX - startX, 2); - int cellHeight = max(endY - startY, 2); - int x = startX + ((localId.x * 2 + 1) * cellWidth) / (SAMPLE_GRID * 2); - int y = startY + ((localId.y * 2 + 1) * cellHeight) / (SAMPLE_GRID * 2); - x = clamp(x - (x & 1), startX, max(startX, endX - 2)); - y = clamp(y - (y & 1), startY, max(startY, endY - 2)); - float inputValue = pgtmInputAt(ivec2(x, y)); - inputSamples[localIndex] = inputValue; - - atomicAdd(data[uGlobalCountersOffset + COUNTER_SAMPLE_COUNT], 1u); - if (inputValue <= 0.0) { - atomicAdd(data[uGlobalCountersOffset + COUNTER_ZERO_COUNT], 1u); - } else { - float ev = clamp( - log(inputValue) * INV_LOG_2, - GLOBAL_HISTOGRAM_MIN_EV, - GLOBAL_HISTOGRAM_MAX_EV - 1e-5 - ); - int bin = clamp( - int(floor( - (ev - GLOBAL_HISTOGRAM_MIN_EV) / - (GLOBAL_HISTOGRAM_MAX_EV - GLOBAL_HISTOGRAM_MIN_EV) * - float(GLOBAL_HISTOGRAM_BINS) - )), - 0, - GLOBAL_HISTOGRAM_BINS - 1 - ); - atomicAdd(data[uGlobalHistogramOffset + bin], 1u); - } - if (inputValue >= 0.92) { - atomicAdd(data[uGlobalCountersOffset + COUNTER_HIGHLIGHT_COUNT], 1u); - } - atomicMax( - data[uGlobalCountersOffset + COUNTER_MAX_INPUT_BITS], - floatBitsToUint(inputValue) - ); - barrier(); - - for (uint sequence = 2u; sequence <= 256u; sequence <<= 1u) { - for (uint distance = sequence >> 1u; distance > 0u; distance >>= 1u) { - uint index = uint(localIndex); - uint peer = index ^ distance; - if (peer > index) { - float own = inputSamples[index]; - float other = inputSamples[peer]; - bool ascending = (index & sequence) == 0u; - if ((ascending && own > other) || (!ascending && own < other)) { - inputSamples[index] = other; - inputSamples[peer] = own; - } - } - barrier(); - } - } - - if (localIndex != 0) return; - float linearSum = 0.0; - float logSum = 0.0; - int highlightCount = 0; - for (int i = 0; i < SAMPLE_COUNT; ++i) { - float value = inputSamples[i]; - linearSum += value; - logSum += log(max(value, 1e-6)); - if (value >= 0.92) highlightCount += 1; - } - int offset = cellIndex * STATS_STRIDE; - data[offset + 0] = floatBitsToUint(inputSamples[25]); - data[offset + 1] = floatBitsToUint(inputSamples[127]); - data[offset + 2] = floatBitsToUint(inputSamples[230]); - data[offset + 3] = floatBitsToUint(inputSamples[250]); - data[offset + 4] = floatBitsToUint(float(highlightCount) / float(SAMPLE_COUNT)); - data[offset + 5] = floatBitsToUint(float(SAMPLE_COUNT)); - data[offset + 6] = floatBitsToUint(inputSamples[254]); - data[offset + 7] = floatBitsToUint(inputSamples[255]); - int sumOffset = uCellSumsOffset + cellIndex * CELL_SUM_STRIDE; - data[sumOffset] = floatBitsToUint(linearSum); - data[sumOffset + 1] = floatBitsToUint(logSum); - } - """.trimIndent() - } -} 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 36352499..ce0b7485 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/MeteringSystem.kt @@ -1,6 +1,5 @@ package com.hinnka.mycamera.raw -import kotlin.math.abs import kotlin.math.exp import kotlin.math.ln import kotlin.math.pow @@ -16,7 +15,6 @@ object MeteringSystem { private const val DISPLAY_TARGET_LUMA = 0.18f private const val LUMA_FLOOR = 0.001f private const val MAX_LINEAR_LUMA = 16.0f - private const val AUTO_DEVELOP_EPSILON = 0.0001f private const val SRGB_TRANSFER_THRESHOLD = 0.04045f private const val SRGB_LINEAR_SCALE = 12.92f private const val SRGB_TRANSFER_A = 0.055f @@ -79,18 +77,6 @@ object MeteringSystem { } } - data class ShadowsHighlightsParams( - val highlights: Float, - val shadows: Float, - ) { - companion object { - val NEUTRAL = ShadowsHighlightsParams( - highlights = 0f, - shadows = 0f, - ) - } - } - data class SrgbThumbnailMeteringStats( val width: Int, val height: Int, @@ -107,16 +93,6 @@ object MeteringSystem { val highlightCompression: HighlightCompressionEstimate ) - fun hasManualRawDevelopAdjustments( - rawExposureCompensation: Float, - rawHighlightsAdjustment: Float, - rawShadowsAdjustment: Float - ): Boolean { - return abs(rawExposureCompensation) > AUTO_DEVELOP_EPSILON || - abs(rawHighlightsAdjustment) > AUTO_DEVELOP_EPSILON || - abs(rawShadowsAdjustment) > AUTO_DEVELOP_EPSILON - } - fun analyzeSrgbThumbnail( width: Int, height: Int, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/PhotonPgtmBrightnessModel.kt b/app/src/main/java/com/hinnka/mycamera/raw/PhotonPgtmBrightnessModel.kt deleted file mode 100644 index 7d3928da..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/PhotonPgtmBrightnessModel.kt +++ /dev/null @@ -1,183 +0,0 @@ -package com.hinnka.mycamera.raw - -import kotlin.math.ln -import kotlin.math.max -import kotlin.math.pow - -/** - * Restores the scene-brightness target used by Photon before 3e320e229 without restoring its - * old gain-curve generator. The returned pre-profile target is consumed by Google's current - * eight-exposure fusion implementation. - */ -internal object PhotonPgtmBrightnessModel { - private const val MIN_SCENE_INPUT = 1e-6f - - private const val STANDARD_DYNAMIC_RANGE_EV = 8f - private const val WIDE_DYNAMIC_RANGE_EV = 8.5f - private const val HDR_DYNAMIC_RANGE_EV = 9f - private const val EXTENDED_HDR_DYNAMIC_RANGE_EV = 9.5f - - private const val WIDE_HIGHLIGHT_RANGE_THRESHOLD_EV = 2.5f - private const val HDR_HIGHLIGHT_RANGE_THRESHOLD_EV = 3.5f - private const val EXTENDED_HDR_HIGHLIGHT_RANGE_THRESHOLD_EV = 4f - - private const val MAX_DISPLAY_MIDDLE_GRAY = 0.26f - - private const val MIN_DISPLAY_EXPOSURE_LIFT_EV = 0.27f - private const val MAX_DISPLAY_EXPOSURE_LIFT_EV = 2.24f - private const val DISPLAY_EXPOSURE_TRANSITION_START_EV = 1.7f - private const val DISPLAY_EXPOSURE_TRANSITION_END_EV = 3.45f - - private const val SPARSE_HIGHLIGHT_GAP_START_EV = 0.45f - private const val SPARSE_HIGHLIGHT_GAP_FULL_EV = 0.90f - fun resolve(globalStats: DngPgtmGlobalStats): PhotonPgtmBrightnessTarget? { - val logAverage = globalStats.logAverage.takeIf { it.isFinite() && it > 0f } - val p50 = globalStats.p50.takeIf { it.isFinite() && it > 0f } - val sceneAnchor = logAverage ?: p50 ?: return null - val anchorSource = if (logAverage != null) { - PhotonPgtmBrightnessAnchorSource.LOG_AVERAGE - } else { - PhotonPgtmBrightnessAnchorSource.P50_FALLBACK - } - val ranges = highlightRanges( - p90 = globalStats.p90, - p98 = globalStats.p98, - p995 = globalStats.p995, - p999 = globalStats.p999, - sceneMiddle = sceneAnchor, - ) - val dynamicRangeEv = dynamicRangeTier(ranges.tailRangeEv) - val displayBlackPoint = 1f / 2.0f.pow(dynamicRangeEv) - val exposureLiftEv = displayExposureLiftEv(ranges.exposureRangeEv) - val displayTarget = (sceneAnchor * 2.0f.pow(exposureLiftEv)).coerceIn( - displayBlackPoint * 4f, - MAX_DISPLAY_MIDDLE_GRAY, - ) - return PhotonPgtmBrightnessTarget( - fusionTarget = HdrExposureFusionBrightnessTarget( - sceneInput = sceneAnchor, - targetOutput = photonProfileInputForDisplay(displayTarget), - ), - anchorSource = anchorSource, - sceneAnchor = sceneAnchor, - displayTarget = displayTarget, - exposureLiftEv = exposureLiftEv, - tailRangeEv = ranges.tailRangeEv, - exposureRangeEv = ranges.exposureRangeEv, - highlightGapEv = ranges.highlightGapEv, - sparseHighlightStrength = ranges.sparseStrength, - dynamicRangeEv = dynamicRangeEv, - ) - } - - internal fun highlightRanges( - p90: Float, - p98: Float, - p995: Float, - p999: Float, - sceneMiddle: Float, - ): PhotonPgtmHighlightRanges { - val safeMiddle = max(sceneMiddle, MIN_SCENE_INPUT) - val safeP90 = max(p90.takeIf { it.isFinite() } ?: safeMiddle, safeMiddle) - val safeP98 = max(p98.takeIf { it.isFinite() } ?: safeP90, safeP90) - val safeP995 = max(p995.takeIf { it.isFinite() } ?: safeP98, safeP98) - val safeP999 = max(p999.takeIf { it.isFinite() } ?: safeP995, safeP995) - val highlightGapEv = log2(safeP98 / safeP90).coerceAtLeast(0f) - val sparseStrength = smoothStep( - SPARSE_HIGHLIGHT_GAP_START_EV, - SPARSE_HIGHLIGHT_GAP_FULL_EV, - highlightGapEv, - ) - val exposureReference = 2.0f.pow( - lerp(log2(safeP999), log2(safeP90), sparseStrength) - ) - return PhotonPgtmHighlightRanges( - tailRangeEv = log2(safeP999 / safeMiddle).coerceAtLeast(0f), - exposureRangeEv = log2(exposureReference / safeMiddle).coerceAtLeast(0f), - exposureReference = exposureReference, - highlightGapEv = highlightGapEv, - sparseStrength = sparseStrength, - ) - } - - internal fun displayExposureLiftEv(highlightRangeEv: Float): Float { - return lerp( - MIN_DISPLAY_EXPOSURE_LIFT_EV, - MAX_DISPLAY_EXPOSURE_LIFT_EV, - smoothStep( - DISPLAY_EXPOSURE_TRANSITION_START_EV, - DISPLAY_EXPOSURE_TRANSITION_END_EV, - highlightRangeEv, - ), - ) - } - - private fun dynamicRangeTier(highlightRangeEv: Float): Float { - return when { - highlightRangeEv >= EXTENDED_HDR_HIGHLIGHT_RANGE_THRESHOLD_EV -> - EXTENDED_HDR_DYNAMIC_RANGE_EV - highlightRangeEv >= HDR_HIGHLIGHT_RANGE_THRESHOLD_EV -> HDR_DYNAMIC_RANGE_EV - highlightRangeEv >= WIDE_HIGHLIGHT_RANGE_THRESHOLD_EV -> WIDE_DYNAMIC_RANGE_EV - else -> STANDARD_DYNAMIC_RANGE_EV - } - } - - private fun photonProfileInputForDisplay(displayValue: Float): Float { - val target = displayValue.coerceIn(0f, 1f) - val points = DngProfileToneCurve.photonPgtmToneCurvePoints() - if (points.size < 4) return target - var index = 0 - while (index + 3 < points.size) { - val x0 = points[index] - val y0 = points[index + 1] - val x1 = points[index + 2] - val y1 = points[index + 3] - if (target <= y1) { - val amount = if (y1 > y0) (target - y0) / (y1 - y0) else 0f - return lerp(x0, x1, amount) - } - index += 2 - } - return points[points.size - 2].coerceIn(0f, 1f) - } - - private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float { - if (edge1 <= edge0) return if (value >= edge1) 1f else 0f - val amount = ((value - edge0) / (edge1 - edge0)).coerceIn(0f, 1f) - return amount * amount * (3f - 2f * amount) - } - - private fun lerp(start: Float, end: Float, amount: Float): Float { - return start + (end - start) * amount - } - - private fun log2(value: Float): Float { - return (ln(max(value, MIN_SCENE_INPUT).toDouble()) / ln(2.0)).toFloat() - } -} - -internal data class PhotonPgtmBrightnessTarget( - val fusionTarget: HdrExposureFusionBrightnessTarget, - val anchorSource: PhotonPgtmBrightnessAnchorSource, - val sceneAnchor: Float, - val displayTarget: Float, - val exposureLiftEv: Float, - val tailRangeEv: Float, - val exposureRangeEv: Float, - val highlightGapEv: Float, - val sparseHighlightStrength: Float, - val dynamicRangeEv: Float, -) - -internal enum class PhotonPgtmBrightnessAnchorSource { - LOG_AVERAGE, - P50_FALLBACK, -} - -internal data class PhotonPgtmHighlightRanges( - val tailRangeEv: Float, - val exposureRangeEv: Float, - val exposureReference: Float, - val highlightGapEv: Float, - val sparseStrength: Float, -) 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 4e1a25ad..56d7f4fb 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -12,7 +12,6 @@ import android.opengl.EGLSurface import android.opengl.GLES30 import android.opengl.GLES31 import androidx.core.graphics.createBitmap -import com.hinnka.mycamera.BuildConfig import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.camera.RawBlackBorderCrop import com.hinnka.mycamera.data.ContentRepository @@ -20,7 +19,6 @@ import com.hinnka.mycamera.lut.ChromaDenoiseDefaults import com.hinnka.mycamera.lut.ChromaDenoiseShaders import com.hinnka.mycamera.lut.ShadowsHighlightsShader import com.hinnka.mycamera.ml.SharedDepthEstimator -import com.hinnka.mycamera.raw.MeteringSystem.ShadowsHighlightsParams import com.hinnka.mycamera.utils.BitmapUtils import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog @@ -45,9 +43,17 @@ import kotlin.math.pow import kotlin.math.sqrt import android.opengl.Matrix as GlMatrix -private typealias ShadowsHighlightsParams = MeteringSystem.ShadowsHighlightsParams private typealias ProfileExposureUniforms = RawProfileExposureGl.Uniforms +private data class ShadowsHighlightsParams( + val highlights: Float, + val shadows: Float, +) { + companion object { + val NEUTRAL = ShadowsHighlightsParams(highlights = 0f, shadows = 0f) + } +} + /** * RAW 图像解马赛克处理器 * @@ -195,11 +201,6 @@ class RawDemosaicProcessor { private const val RCD_HIGHLIGHT_RECONSTRUCTION_CEILING = 8.0f private const val RCD_HIGHLIGHT_RECONSTRUCTION_MIN_WB_GAIN = 1e-3f private const val RCD_HIGHLIGHT_RECONSTRUCTION_MAX_WB_GAIN = 64.0f - private const val RAW_TONE_MAPPED_AE_LUMA_FLOOR = 0.001f - private const val RAW_TONE_MAPPED_AE_LONG_EDGE = 256 - private const val RAW_TONE_MAPPED_AE_MAX_SOLVE_STEPS = 3 - private const val RAW_TONE_MAPPED_AE_EV_TOLERANCE = 0.05f - private const val RAW_TONE_MAPPED_AE_MIN_STEP_EV = 0.025f private const val FILMIC_GREY_SOURCE = 0.1845f private const val FILMIC_OUTPUT_POWER = 3.614815775f private const val FILMIC_DISPLAY_BLACK = 0.0001517634f @@ -279,7 +280,6 @@ class RawDemosaicProcessor { private var rawHdrLinearAccumulateProgram = 0 private var rawHdrLinearNormalizeProgram = 0 private var rawHdrLinearPreviewProgram = 0 - private val rawProfileGainTableGpuBuilder = GlesRawProfileGainTableMapBuilder() private var filmicHrMaskProgram = 0 private var filmicHrInpaintNoiseProgram = 0 private var filmicHrInitReconstructProgram = 0 @@ -314,14 +314,14 @@ class RawDemosaicProcessor { private var adjustmentWidth = 0 private var adjustmentHeight = 0 - private var linearMeteringFramebufferId = 0 - private var linearMeteringTextureId = 0 - private var linearMeteringWidth = 0 - private var linearMeteringHeight = 0 - private var srgbMeteringCropFramebufferId = 0 - private var srgbMeteringCropTextureId = 0 - private var srgbMeteringCropWidth = 0 - private var srgbMeteringCropHeight = 0 + private var linearExposurePreviewFramebufferId = 0 + private var linearExposurePreviewTextureId = 0 + private var linearExposurePreviewWidth = 0 + private var linearExposurePreviewHeight = 0 + private var srgbExposurePreviewFramebufferId = 0 + private var srgbExposurePreviewTextureId = 0 + private var srgbExposurePreviewWidth = 0 + private var srgbExposurePreviewHeight = 0 private var hdrReferenceFramebufferId = 0 private var hdrReferenceTextureId = 0 @@ -406,12 +406,6 @@ class RawDemosaicProcessor { val curveLut: FloatArray? = null ) - data class RawAutoAdjustments( - val exposureCompensation: Float, - val highlights: Float, - val shadows: Float - ) - data class LinearRcdFrame( val pixels: ByteBuffer, val width: Int, @@ -585,305 +579,6 @@ class RawDemosaicProcessor { ) } - private fun analyzeSrgbThumbnailForMetering( - bitmap: Bitmap?, - sourceBounds: Rect? = null - ): RawAeMeteringImage? { - if (bitmap == null || bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) { - return null - } - return try { - val safeSourceBounds = sanitizeBitmapBounds(sourceBounds, bitmap.width, bitmap.height) - ?: Rect(0, 0, bitmap.width, bitmap.height) - val meteringSize = resolveLongEdgeMeteringSize( - sourceWidth = safeSourceBounds.width(), - sourceHeight = safeSourceBounds.height(), - maxLongEdge = RAW_TONE_MAPPED_AE_LONG_EDGE - ) - val width = meteringSize.width - val height = meteringSize.height - val pixels = IntArray(width * height) - val rowPixels = IntArray(bitmap.width) - for (y in 0 until height) { - val sourceY = safeSourceBounds.top + - ((y + 0.5f) * safeSourceBounds.height().toFloat() / height.toFloat()) - .toInt() - .coerceIn(0, bitmap.height - 1) - bitmap.getPixels(rowPixels, 0, bitmap.width, 0, sourceY, bitmap.width, 1) - for (x in 0 until width) { - val sourceX = safeSourceBounds.left + - ((x + 0.5f) * safeSourceBounds.width().toFloat() / width.toFloat()) - .toInt() - .coerceIn(0, bitmap.width - 1) - pixels[y * width + x] = rowPixels[sourceX] - } - } - val stats = MeteringSystem.analyzeSrgbThumbnail(width, height, pixels) - ?: return null - RawAeMeteringImage( - width = width, - height = height, - argbPixels = pixels, - stats = stats - ) - } catch (e: Exception) { - PLog.e(TAG, "Failed to analyze capture preview thumbnail for RAW AE", e) - null - } - } - - private data class RawAeContentBounds( - val rawRenderBounds: Rect, - val thumbnailBounds: Rect - ) - - private data class RawAeMeteringImage( - val width: Int, - val height: Int, - val argbPixels: IntArray, - val stats: MeteringSystem.SrgbThumbnailMeteringStats - ) - - private data class RawAeCenterAverageReference( - val width: Int, - val height: Int, - val bounds: Rect, - val targetDisplayLuma: Float, - val pixelCount: Int - ) - - private data class RawAeCenterAverageMatch( - val errorEv: Float, - val targetDisplayLuma: Float, - val renderedDisplayLuma: Float, - val pixelCount: Int - ) - - private fun buildRawAeCenterAverageReference( - image: RawAeMeteringImage - ): RawAeCenterAverageReference? { - val bounds = rawAeCenterTwoThirdsBounds(image.width, image.height) - ?: return null - val targetDisplayLuma = averageSrgbDisplayLuma(image, bounds) - ?: return null - val reference = RawAeCenterAverageReference( - width = image.width, - height = image.height, - bounds = bounds, - targetDisplayLuma = targetDisplayLuma, - pixelCount = bounds.width() * bounds.height() - ) - return reference - } - - private fun matchRawAeCenterAverage( - reference: RawAeCenterAverageReference, - rendered: RawAeMeteringImage - ): RawAeCenterAverageMatch? { - if (reference.width != rendered.width || reference.height != rendered.height) { - return null - } - val renderedDisplayLuma = averageSrgbDisplayLuma(rendered, reference.bounds) - ?: return null - return RawAeCenterAverageMatch( - errorEv = displayLumaErrorEv( - renderedLuma = renderedDisplayLuma, - targetLuma = reference.targetDisplayLuma - ), - targetDisplayLuma = reference.targetDisplayLuma, - renderedDisplayLuma = renderedDisplayLuma, - pixelCount = reference.pixelCount - ) - } - - private fun rawAeCenterTwoThirdsBounds(width: Int, height: Int): Rect? { - if (width <= 0 || height <= 0) return null - val left = width / 6 - val top = height / 6 - val right = (width * 5 / 6).coerceAtLeast(left + 1) - val bottom = (height * 5 / 6).coerceAtLeast(top + 1) - return Rect( - left.coerceIn(0, width - 1), - top.coerceIn(0, height - 1), - right.coerceIn(left + 1, width), - bottom.coerceIn(top + 1, height) - ) - } - - private fun averageSrgbDisplayLuma(image: RawAeMeteringImage, bounds: Rect): Float? { - if ( - image.width <= 0 || - image.height <= 0 || - image.argbPixels.size < image.width * image.height || - bounds.isEmpty - ) { - return null - } - val safeBounds = Rect(bounds) - if (!safeBounds.intersect(Rect(0, 0, image.width, image.height)) || safeBounds.isEmpty) { - return null - } - var lumaSum = 0.0 - var pixelCount = 0 - for (y in safeBounds.top until safeBounds.bottom) { - val rowOffset = y * image.width - for (x in safeBounds.left until safeBounds.right) { - lumaSum += srgbDisplayLuma(image.argbPixels[rowOffset + x]).toDouble() - pixelCount++ - } - } - if (pixelCount <= 0) return null - return (lumaSum / pixelCount.toDouble()).toFloat() - .coerceAtLeast(RAW_TONE_MAPPED_AE_LUMA_FLOOR) - } - - private fun srgbDisplayLuma(pixel: Int): Float { - val alpha = ((pixel ushr 24) and 0xff) / 255f - if (alpha <= 0f) return 0f - val r = ((pixel ushr 16) and 0xff) / 255f - val g = ((pixel ushr 8) and 0xff) / 255f - val b = (pixel and 0xff) / 255f - val luma = (0.2126f * r + 0.7152f * g + 0.0722f * b) * alpha - return if (luma.isFinite()) luma.coerceIn(0f, 1f) else 0f - } - - private fun resolveRawAeContentBounds( - rawSourceBounds: Rect, - outputRotation: Int, - thumbnail: Bitmap? - ): RawAeContentBounds? { - val rawVisualBounds = sourceBoundsToVisualOutputBounds( - baseSourceBounds = rawSourceBounds, - sourceBounds = rawSourceBounds, - rotation = outputRotation - ) - if ( - rawVisualBounds.isEmpty || - thumbnail == null || - thumbnail.isRecycled || - thumbnail.width <= 0 || - thumbnail.height <= 0 - ) { - return null - } - val thumbnailAspect = thumbnail.width.toFloat() / thumbnail.height.toFloat() - if (!thumbnailAspect.isFinite() || thumbnailAspect <= 0f) return null - val rawDisplayVisualBounds = centerCropToAspect(rawVisualBounds, thumbnailAspect) - val rawDisplaySourceBounds = visualOutputBoundsToSourceBounds( - baseSourceBounds = rawSourceBounds, - visualBounds = rawDisplayVisualBounds, - rotation = outputRotation - ) ?: return null - val rawRenderBounds = rawDisplaySourceBounds.toOutputBounds(outputRotation) - val thumbnailBounds = Rect(0, 0, thumbnail.width, thumbnail.height) - return RawAeContentBounds( - rawRenderBounds = rawRenderBounds, - thumbnailBounds = thumbnailBounds - ) - } - - private fun sourceBoundsToVisualOutputBounds( - baseSourceBounds: Rect, - sourceBounds: Rect, - rotation: Int - ): Rect { - val baseOutputBounds = baseSourceBounds.toOutputBounds(rotation) - val normalizedRotation = ((rotation % 360) + 360) % 360 - return when (normalizedRotation) { - 90 -> Rect( - baseOutputBounds.left + (baseSourceBounds.bottom - sourceBounds.bottom), - baseOutputBounds.top + (sourceBounds.left - baseSourceBounds.left), - baseOutputBounds.left + (baseSourceBounds.bottom - sourceBounds.top), - baseOutputBounds.top + (sourceBounds.right - baseSourceBounds.left) - ) - - 180 -> Rect( - baseOutputBounds.left + (baseSourceBounds.right - sourceBounds.right), - baseOutputBounds.top + (baseSourceBounds.bottom - sourceBounds.bottom), - baseOutputBounds.left + (baseSourceBounds.right - sourceBounds.left), - baseOutputBounds.top + (baseSourceBounds.bottom - sourceBounds.top) - ) - - 270 -> Rect( - baseOutputBounds.left + (sourceBounds.top - baseSourceBounds.top), - baseOutputBounds.top + (baseSourceBounds.right - sourceBounds.right), - baseOutputBounds.left + (sourceBounds.bottom - baseSourceBounds.top), - baseOutputBounds.top + (baseSourceBounds.right - sourceBounds.left) - ) - - else -> Rect( - baseOutputBounds.left + (sourceBounds.left - baseSourceBounds.left), - baseOutputBounds.top + (sourceBounds.top - baseSourceBounds.top), - baseOutputBounds.left + (sourceBounds.right - baseSourceBounds.left), - baseOutputBounds.top + (sourceBounds.bottom - baseSourceBounds.top) - ) - } - } - - private fun visualOutputBoundsToSourceBounds( - baseSourceBounds: Rect, - visualBounds: Rect, - rotation: Int - ): Rect? { - val baseOutputBounds = baseSourceBounds.toOutputBounds(rotation) - val normalizedRotation = ((rotation % 360) + 360) % 360 - val sourceBounds = when (normalizedRotation) { - 90 -> Rect( - baseSourceBounds.left + (visualBounds.top - baseOutputBounds.top), - baseSourceBounds.bottom - (visualBounds.right - baseOutputBounds.left), - baseSourceBounds.left + (visualBounds.bottom - baseOutputBounds.top), - baseSourceBounds.bottom - (visualBounds.left - baseOutputBounds.left) - ) - - 180 -> Rect( - baseSourceBounds.right - (visualBounds.right - baseOutputBounds.left), - baseSourceBounds.bottom - (visualBounds.bottom - baseOutputBounds.top), - baseSourceBounds.right - (visualBounds.left - baseOutputBounds.left), - baseSourceBounds.bottom - (visualBounds.top - baseOutputBounds.top) - ) - - 270 -> Rect( - baseSourceBounds.right - (visualBounds.bottom - baseOutputBounds.top), - baseSourceBounds.top + (visualBounds.left - baseOutputBounds.left), - baseSourceBounds.right - (visualBounds.top - baseOutputBounds.top), - baseSourceBounds.top + (visualBounds.right - baseOutputBounds.left) - ) - - else -> Rect( - baseSourceBounds.left + (visualBounds.left - baseOutputBounds.left), - baseSourceBounds.top + (visualBounds.top - baseOutputBounds.top), - baseSourceBounds.left + (visualBounds.right - baseOutputBounds.left), - baseSourceBounds.top + (visualBounds.bottom - baseOutputBounds.top) - ) - } - return Rect(sourceBounds).takeIf { - it.intersect(baseSourceBounds) && !it.isEmpty - } - } - - private fun centerCropToAspect(bounds: Rect, targetAspect: Float): Rect { - if (bounds.isEmpty || !targetAspect.isFinite() || targetAspect <= 0f) return Rect(bounds) - val sourceAspect = bounds.width().toFloat() / bounds.height().toFloat() - val cropWidth: Int - val cropHeight: Int - if (sourceAspect > targetAspect) { - cropHeight = bounds.height() - cropWidth = (cropHeight * targetAspect).toInt().coerceIn(1, bounds.width()) - } else { - cropWidth = bounds.width() - cropHeight = (cropWidth / targetAspect).toInt().coerceIn(1, bounds.height()) - } - val left = bounds.left + (bounds.width() - cropWidth) / 2 - val top = bounds.top + (bounds.height() - cropHeight) / 2 - return Rect(left, top, left + cropWidth, top + cropHeight) - } - - private fun sanitizeBitmapBounds(bounds: Rect?, width: Int, height: Int): Rect? { - if (bounds == null || bounds.isEmpty || width <= 0 || height <= 0) return null - val imageBounds = Rect(0, 0, width, height) - return Rect(bounds).takeIf { it.intersect(imageBounds) && !it.isEmpty } - } - /** * 处理 DNG 文件 * @@ -901,7 +596,6 @@ class RawDemosaicProcessor { rotation: Int, exposureBias: Float = 0f, rawExposureCompensation: Float = 0f, - rawAutoExposure: Boolean = true, rawHighlightsAdjustment: Float = 0f, rawShadowsAdjustment: Float = 0f, rawBlackPointCorrection: Float = 0f, @@ -923,10 +617,7 @@ class RawDemosaicProcessor { rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawCfaCorrectionMode: String? = null, - capturePreviewThumbnail: Bitmap? = null, - useEmbeddedPreviewForAutoExposure: Boolean = true, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), - onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onMetadata: ((RawMetadata) -> Unit)? = null ): Bitmap? = withContext(glDispatcher) { val dngFile = File(dngFilePath) @@ -943,7 +634,6 @@ class RawDemosaicProcessor { rotation = rotation, exposureBias = exposureBias, rawExposureCompensation = rawExposureCompensation, - rawAutoExposure = rawAutoExposure, rawHighlightsAdjustment = rawHighlightsAdjustment, rawShadowsAdjustment = rawShadowsAdjustment, rawBlackPointCorrection = rawBlackPointCorrection, @@ -965,11 +655,8 @@ class RawDemosaicProcessor { rawRenderingEngine = rawRenderingEngine, rawToneMappingParameters = rawToneMappingParameters, rawCfaCorrectionMode = rawCfaCorrectionMode, - capturePreviewThumbnail = capturePreviewThumbnail, - useEmbeddedPreviewForAutoExposure = useEmbeddedPreviewForAutoExposure, rawBlackBorderCrop = rawBlackBorderCrop, dngFile = dngFile, - onRawAutoAdjustments = onRawAutoAdjustments, onMetadata = onMetadata )?.sdrBitmap } catch (e: Exception) { @@ -992,7 +679,6 @@ class RawDemosaicProcessor { cropRegion: Rect?, rotation: Int, rawExposureCompensation: Float = 0f, - rawAutoExposure: Boolean = true, rawHighlightsAdjustment: Float = 0f, rawShadowsAdjustment: Float = 0f, rawBlackPointCorrection: Float = 0f, @@ -1030,7 +716,6 @@ class RawDemosaicProcessor { cropRegion = cropRegion, rotation = rotation, rawExposureCompensation = rawExposureCompensation, - rawAutoExposure = rawAutoExposure, rawHighlightsAdjustment = rawHighlightsAdjustment, rawShadowsAdjustment = rawShadowsAdjustment, rawBlackPointCorrection = rawBlackPointCorrection, @@ -1055,6 +740,57 @@ class RawDemosaicProcessor { } } + /** Renders default-curve preview samples requested by a capture-side exposure solver. */ + internal suspend fun renderExposurePreviewSamples( + context: Context, + input: RawDngViewfinderMatchInput, + aspectRatio: AspectRatio?, + cropRegion: Rect?, + rotation: Int, + request: RawExposurePreviewRequest, + rawBlackPointCorrection: Float = 0f, + rawWhitePointCorrection: Float = 0f, + rawAutoWhiteBalanceEstimate: Boolean = false, + applyLensShadingCorrection: Boolean = true, + rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), + ): Float? = withContext(glDispatcher) { + var solvedExposureEv: Float? = null + try { + processInternal( + context = context, + rawData = input.rawData, + width = input.width, + height = input.height, + rowStride = input.rowStride, + samplesPerPixel = input.samplesPerPixel, + metadata = input.metadata.copy(profileGainTableMap = null), + aspectRatio = aspectRatio, + cropRegion = cropRegion, + rotation = rotation, + rawExposureCompensation = 0f, + rawHighlightsAdjustment = 0f, + rawShadowsAdjustment = 0f, + rawBlackPointCorrection = rawBlackPointCorrection, + rawWhitePointCorrection = rawWhitePointCorrection, + rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate, + applyLensShadingCorrection = applyLensShadingCorrection, + rawDcpId = null, + spectralFilmStock = null, + spectralFilmPrint = null, + rawRenderingEngine = RawRenderingEngine.AdobeCurve, + rawToneMappingParameters = RawToneMappingParameters.DEFAULT.withProfileToneMapMode( + RawProfileToneMapMode.Default + ), + rawBlackBorderCrop = rawBlackBorderCrop, + exposurePreviewRequest = request, + onExposurePreviewSolved = { solvedExposureEv = it }, + ) + } catch (e: Exception) { + PLog.e(TAG, "Failed to render RAW exposure preview samples", e) + } + solvedExposureEv + } + suspend fun renderLinearRcdFrame( rawData: ByteBuffer, width: Int, @@ -1156,7 +892,6 @@ class RawDemosaicProcessor { rotation: Int, exposureBias: Float = 0f, rawExposureCompensation: Float = 0f, - rawAutoExposure: Boolean = true, rawHighlightsAdjustment: Float = 0f, rawShadowsAdjustment: Float = 0f, rawBlackPointCorrection: Float = 0f, @@ -1178,10 +913,7 @@ class RawDemosaicProcessor { rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawCfaCorrectionMode: String? = null, - capturePreviewThumbnail: Bitmap? = null, - useEmbeddedPreviewForAutoExposure: Boolean = true, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), - onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onMetadata: ((RawMetadata) -> Unit)? = null ): RawHdrRenderResult? = withContext(glDispatcher) { val dngFile = File(dngFilePath) @@ -1198,7 +930,6 @@ class RawDemosaicProcessor { rotation = rotation, exposureBias = exposureBias, rawExposureCompensation = rawExposureCompensation, - rawAutoExposure = rawAutoExposure, rawHighlightsAdjustment = rawHighlightsAdjustment, rawShadowsAdjustment = rawShadowsAdjustment, rawBlackPointCorrection = rawBlackPointCorrection, @@ -1220,11 +951,8 @@ class RawDemosaicProcessor { rawRenderingEngine = rawRenderingEngine, rawToneMappingParameters = rawToneMappingParameters, rawCfaCorrectionMode = rawCfaCorrectionMode, - capturePreviewThumbnail = capturePreviewThumbnail, - useEmbeddedPreviewForAutoExposure = useEmbeddedPreviewForAutoExposure, rawBlackBorderCrop = rawBlackBorderCrop, dngFile = dngFile, - onRawAutoAdjustments = onRawAutoAdjustments, onMetadata = onMetadata, includeHdrReference = true ) @@ -1243,13 +971,13 @@ class RawDemosaicProcessor { width: Int = 0, height: Int = 0, rowStride: Int = 0, + samplesPerPixel: Int = 1, metadata: RawMetadata? = null, aspectRatio: AspectRatio?, cropRegion: Rect?, rotation: Int, exposureBias: Float = 0f, rawExposureCompensation: Float = 0f, - rawAutoExposure: Boolean = true, rawHighlightsAdjustment: Float = 0f, rawShadowsAdjustment: Float = 0f, rawBlackPointCorrection: Float = 0f, @@ -1271,25 +999,23 @@ class RawDemosaicProcessor { rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve, rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT, rawCfaCorrectionMode: String? = null, - capturePreviewThumbnail: Bitmap? = null, - useEmbeddedPreviewForAutoExposure: Boolean = true, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), dngFile: File? = null, - onRawAutoAdjustments: ((RawAutoAdjustments) -> Unit)? = null, onMetadata: ((RawMetadata) -> Unit)? = null, - includeHdrReference: Boolean = false + includeHdrReference: Boolean = false, + exposurePreviewRequest: RawExposurePreviewRequest? = null, + onExposurePreviewSolved: ((Float?) -> Unit)? = null, ): RawHdrRenderResult? = withContext(glDispatcher) { var actualRawData = rawData var actualWidth = width var actualHeight = height var actualRowStride = rowStride - var actualSamplesPerPixel = 1 + var actualSamplesPerPixel = samplesPerPixel.coerceAtLeast(1) var actualMetadata = metadata var actualRotation = rotation var dngRawDataCleanup: DngRawData? = null var embeddedDngJpegPreview: Bitmap? = null var dngWarpRectilinear: FloatArray? = null - var rawTexturePreparedForPgtm = false val requestedColorEngine = rawRenderingEngine val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null val profileWorkingColorSpace = ColorSpace.ProPhoto @@ -1359,7 +1085,7 @@ class RawDemosaicProcessor { ) } actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation - embeddedDngRenderPlan = if (hasClassicTiffHeader && !BuildConfig.DEBUG) { + embeddedDngRenderPlan = if (hasClassicTiffHeader) { DngEmbeddedProfile.resolveRenderPlan( file = dngFile, metadata = actualMetadata, @@ -1459,13 +1185,6 @@ class RawDemosaicProcessor { "aspectRatio=$aspectRatio rotation=$actualRotation outputSourceBounds=$outputSourceBounds" ) val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation) - val autoExposurePreview = capturePreviewThumbnail - ?: embeddedDngJpegPreview.takeIf { useEmbeddedPreviewForAutoExposure } - val rawAeContentBounds = resolveRawAeContentBounds( - rawSourceBounds = outputSourceBounds, - outputRotation = actualRotation, - thumbnail = autoExposurePreview - ) val embeddedDngProfileName = embeddedDngRenderPlan?.profileName val embeddedProfileToneCurveLut = embeddedDngRenderPlan?.toneCurveLut val embeddedProfileToneMapMode = when { @@ -1482,11 +1201,6 @@ class RawDemosaicProcessor { else -> RawProfileToneMapMode.Default } - val embeddedProfileGainTableMap = actualMetadata.profileGainTableMap?.takeIf { it.isValid } - val embeddedDngHdrToneMapAvailable = embeddedProfileToneMapMode != RawProfileToneMapMode.Default && - embeddedProfileGainTableMap != null - val inactiveEmbeddedProfileGainTableMapAvailable = embeddedProfileGainTableMap != null && - !embeddedDngHdrToneMapAvailable val normalizedToneMappingParameters = rawToneMappingParameters.normalized() val googlePixelToneMapRequested = useAdobeProfilePipeline && normalizedToneMappingParameters.useGooglePixelToneMap @@ -1501,162 +1215,72 @@ class RawDemosaicProcessor { } val profileGainToneMapRequested = requestedProfileToneMapMode == RawProfileToneMapMode.GooglePixel || requestedProfileToneMapMode == RawProfileToneMapMode.Photon - val embeddedDngHdrToneMapDisabledByUser = embeddedDngHdrToneMapAvailable && - useAdobeProfilePipeline && - !oppoMasterToneMapRequested && - requestedProfileToneMapMode == RawProfileToneMapMode.Default - val embeddedDngHdrToneMapDisabledByOppo = embeddedDngHdrToneMapAvailable && - oppoMasterToneMapRequested - val embeddedDngHdrToneMapModeMismatch = embeddedDngHdrToneMapAvailable && + val embeddedProfileGainTableMap = actualMetadata.profileGainTableMap?.takeIf { it.isValid } + var profileGainTableMap = embeddedProfileGainTableMap + var profileToneCurveLut = embeddedProfileToneCurveLut + var profileToneMapMode = embeddedProfileToneMapMode + var profileGainTableMapSource = "embedded" + + if (profileGainToneMapRequested && + (profileGainTableMap == null || profileToneMapMode != requestedProfileToneMapMode) + ) { + val generated = RawProfileGainTableMapBuilder.prepareForDngWrite( + rawData = actualRawData, + width = actualWidth, + height = actualHeight, + rowStride = actualRowStride, + samplesPerPixel = actualSamplesPerPixel, + metadata = actualMetadata.copy(profileGainTableMap = null), + options = RawDngProfilePreparationOptions( + profileToneMapMode = requestedProfileToneMapMode, + statsBounds = outputSourceBounds, + ), + colorCorrectionMatrix = resolvedDcpRenderPlan?.colorCorrectionMatrix + ?: actualMetadata.colorCorrectionMatrix, + cameraWhite = resolvedDcpRenderPlan?.cameraWhite ?: actualMetadata.cameraWhite, + hueSatMap = resolvedDcpRenderPlan?.hueSatMap, + )?.profileGainTableMap?.takeIf { it.isValid } + if (generated != null) { + profileGainTableMap = generated + profileGainTableMapSource = "generated" + } else if (profileGainTableMap != null) { + // PGTM maps are curve-independent. A valid embedded map remains usable when the + // user switches between the Photon and Google profile curves. + profileGainTableMapSource = "embedded-reused" + } + if (profileGainTableMap != null) { + profileToneMapMode = requestedProfileToneMapMode + profileToneCurveLut = null + } + } + + val profileGainToneMapActive = useAdobeProfilePipeline && profileGainToneMapRequested && - requestedProfileToneMapMode != embeddedProfileToneMapMode - if (embeddedDngHdrToneMapAvailable) { + !oppoMasterToneMapRequested && + profileGainTableMap != null + actualMetadata = actualMetadata.copy( + profileGainTableMap = profileGainTableMap.takeIf { profileGainToneMapActive } + ) + if (profileGainToneMapActive) { PLog.d( TAG, - "Embedded DNG PGTM/ProfileToneCurve available: " + - "mode=$embeddedProfileToneMapMode " + - "tag=${embeddedProfileGainTableMap.sourceTag} " + - "grid=${embeddedProfileGainTableMap.mapPointsH}x" + - "${embeddedProfileGainTableMap.mapPointsV}x${embeddedProfileGainTableMap.mapPointsN} " + + "RAW PGTM/ProfileToneCurve ready: " + + "mode=$requestedProfileToneMapMode source=$profileGainTableMapSource " + + "tag=${profileGainTableMap.sourceTag} " + + "grid=${profileGainTableMap.mapPointsH}x" + + "${profileGainTableMap.mapPointsV}x${profileGainTableMap.mapPointsN} " + "requested=${normalizedToneMappingParameters.profileToneMapMode}" ) - } - val embeddedDngHdrToneMapOverriddenByDcp = embeddedDngHdrToneMapAvailable && - useAdobeProfilePipeline && - hasDcpSelection && - resolvedDcpRenderPlan?.toneCurveLut != null - val embeddedDngHdrToneMapRenderable = embeddedDngHdrToneMapAvailable && - useAdobeProfilePipeline && - requestedProfileToneMapMode == embeddedProfileToneMapMode && - !embeddedDngHdrToneMapOverriddenByDcp && - !embeddedDngHdrToneMapDisabledByUser && - !embeddedDngHdrToneMapDisabledByOppo - if (embeddedDngHdrToneMapAvailable && !embeddedDngHdrToneMapRenderable) { - val reason = when { - embeddedDngHdrToneMapDisabledByUser -> "profile tone map disabled for this photo" - embeddedDngHdrToneMapDisabledByOppo -> "OPPO master tone map requested" - embeddedDngHdrToneMapModeMismatch -> "requested profile tone map $requestedProfileToneMapMode" - !useAdobeProfilePipeline -> "color engine $colorEngine does not use Adobe/DNG profile tone map" - embeddedDngHdrToneMapOverriddenByDcp -> "selected DCP has tone curve: ${resolvedDcpRenderPlan.profileName}" - else -> "current render pipeline does not use embedded DNG HDR tone map" - } - actualMetadata = actualMetadata.copy(profileGainTableMap = null) - PLog.d( + } else if (profileGainToneMapRequested) { + PLog.e( TAG, - "Embedded DNG PGTM/ProfileToneCurve not rendered: reason=$reason" + "RAW PGTM generation failed: mode=$requestedProfileToneMapMode " + + "size=${actualWidth}x$actualHeight samplesPerPixel=$actualSamplesPerPixel" ) } - if (inactiveEmbeddedProfileGainTableMapAvailable) { - actualMetadata = actualMetadata.copy(profileGainTableMap = null) - PLog.d( - TAG, - "Embedded DNG ProfileGainTableMap ignored: profile=$embeddedDngProfileName" - ) - } - val requestedGeneratedProfileGainToneMap = profileGainToneMapRequested && - (!embeddedDngHdrToneMapAvailable || embeddedProfileToneMapMode != requestedProfileToneMapMode) - val generatedProfileGainToneMapOverriddenByDcp = requestedGeneratedProfileGainToneMap && - hasDcpSelection && - resolvedDcpRenderPlan?.toneCurveLut != null - val generateProfileGainToneMap = requestedGeneratedProfileGainToneMap && - !generatedProfileGainToneMapOverriddenByDcp - if (generatedProfileGainToneMapOverriddenByDcp) { - PLog.d( - TAG, - "Generated $requestedProfileToneMapMode PGTM/ProfileToneCurve not rendered because selected DCP has tone curve: " + - "profile=${resolvedDcpRenderPlan.profileName}" - ) - } - if (embeddedDngHdrToneMapRenderable) { - PLog.d(TAG, "Using embedded $embeddedProfileToneMapMode DNG PGTM/ProfileToneCurve") - } - if (generateProfileGainToneMap) { - val generatedProfileGainTableMap = try { - val initialized = isInitialized || initialize() - if (!initialized) { - null - } else if (actualWidth > maxTextureSize || actualHeight > maxTextureSize) { - PLog.e( - TAG, - "GPU PGTM input ${actualWidth}x$actualHeight exceeds " + - "GL_MAX_TEXTURE_SIZE=$maxTextureSize" - ) - null - } else { - if (actualSamplesPerPixel >= 3) { - uploadLinearRawRgbTextureFromBuffer( - actualRawData, - actualWidth, - actualHeight, - actualRowStride - ) - } else { - uploadRawTextureFromBuffer( - actualRawData, - actualWidth, - actualHeight, - actualRowStride - ) - } - rawTexturePreparedForPgtm = true - val generationColorMatrix = resolvedDcpRenderPlan?.colorCorrectionMatrix - ?: actualMetadata.colorCorrectionMatrix - val generationCameraWhite = resolvedDcpRenderPlan?.cameraWhite - ?: actualMetadata.cameraWhite - val generationHueSatMap = resolvedDcpRenderPlan?.hueSatMap - ?.takeIf { it.isValid } - val generationHueSatTextureId = generationHueSatMap?.let { map -> - uploadDcp3DTexture( - textureIdProvider = { dcpHueSatTextureId }, - assignTextureId = { dcpHueSatTextureId = it }, - table = map, - ) - } ?: ensureDummyDcp3DTexture() - rawProfileGainTableGpuBuilder.build( - rawTextureId = rawTextureId, - width = actualWidth, - height = actualHeight, - metadata = actualMetadata, - samplesPerPixel = actualSamplesPerPixel, - statsBounds = outputSourceBounds, - profileToneMapMode = requestedProfileToneMapMode, - colorCorrectionMatrix = generationColorMatrix, - cameraWhite = generationCameraWhite, - hueSatMap = generationHueSatMap, - hueSatTextureId = generationHueSatTextureId, - ) - } - } catch (error: Exception) { - PLog.w(TAG, "Failed to prepare GPU RAW PGTM generation", error) - null - } - if (generatedProfileGainTableMap?.isValid == true) { - actualMetadata = actualMetadata.copy(profileGainTableMap = generatedProfileGainTableMap) - PLog.d( - TAG, - "Generated $requestedProfileToneMapMode PGTM for RAW: " + - "grid=${generatedProfileGainTableMap.mapPointsH}x" + - "${generatedProfileGainTableMap.mapPointsV}x" + - "${generatedProfileGainTableMap.mapPointsN} " + - "tag=${generatedProfileGainTableMap.sourceTag} " + - "gamma=${generatedProfileGainTableMap.gamma}" - ) - DngPgtmDebugRewriter.rewriteGeneratedPgtmOnRawRefreshIfEnabled( - dngFile = dngFile, - profileGainTableMap = generatedProfileGainTableMap, - profileToneMapMode = requestedProfileToneMapMode - ) - } else { - PLog.w(TAG, "$requestedProfileToneMapMode requested but PGTM stats generation failed") - } - } - val profileGainToneMapActive = (embeddedDngHdrToneMapRenderable || generateProfileGainToneMap) && - actualMetadata.profileGainTableMap?.isValid == true val oppoMasterToneMapActive = oppoMasterToneMapRequested - val embeddedProfileToneCurveDisabled = ( - embeddedDngHdrToneMapDisabledByUser || - embeddedDngHdrToneMapDisabledByOppo - ) + val embeddedProfileToneCurveDisabled = embeddedProfileToneMapMode != RawProfileToneMapMode.Default && + !profileGainToneMapActive val profileBaseDcpRenderPlan = if ( embeddedProfileToneCurveDisabled && !hasDcpSelection && @@ -1665,7 +1289,8 @@ class RawDemosaicProcessor { withoutProfileToneCurve( resolvedDcpRenderPlan, reason = when { - embeddedDngHdrToneMapDisabledByOppo -> "OPPO master tone map requested" + embeddedProfileToneCurveDisabled && oppoMasterToneMapRequested -> + "OPPO master tone map requested" else -> "profile tone map disabled for this photo" } ) @@ -1678,9 +1303,10 @@ class RawDemosaicProcessor { basePlan = profileBaseDcpRenderPlan, metadata = actualMetadata, workingColorSpace = profileWorkingColorSpace, - mode = requestedProfileToneMapMode.takeIf { generateProfileGainToneMap } - ?: embeddedProfileToneMapMode, - preferredToneCurveLut = embeddedProfileToneCurveLut.takeIf { embeddedDngHdrToneMapRenderable } + mode = requestedProfileToneMapMode, + preferredToneCurveLut = profileToneCurveLut.takeIf { + profileToneMapMode == requestedProfileToneMapMode + } ) } oppoMasterToneMapActive -> { @@ -1692,9 +1318,6 @@ class RawDemosaicProcessor { } else -> profileBaseDcpRenderPlan } - val photonToneCurveActive = DngProfileToneCurve.isPhotonPgtmToneCurveLut( - activeDcpRenderPlan?.toneCurveLut - ) val profilePlanSource = when { profileGainToneMapActive -> when { dcpRenderPlan != null -> "provided+${requestedProfileToneMapMode.name.lowercase()}-tone-map" @@ -1752,30 +1375,6 @@ class RawDemosaicProcessor { useProfileExposureRamp = useProfileExposureRamp, applyDcpBaselineExposureOffset = applyDcpBaselineExposureOffset ) - val viewfinderThumbnailMeteringImage = when { - !rawAutoExposure -> null - photonToneCurveActive -> { - PLog.d(TAG, "RAW auto exposure disabled: Photon tone curve is active") - null - } - else -> { - if (capturePreviewThumbnail == null && autoExposurePreview != null) { - PLog.d(TAG, "Using embedded DNG JPEG preview for RAW auto exposure") - } - analyzeSrgbThumbnailForMetering( - autoExposurePreview, - rawAeContentBounds?.thumbnailBounds - ).also { image -> - if (image == null) { - PLog.d(TAG, "RAW auto exposure disabled: no capture or embedded DNG JPEG preview") - } - } - } - } - val viewfinderThumbnailStats = viewfinderThumbnailMeteringImage?.stats - val viewfinderCenterAverageReference = viewfinderThumbnailMeteringImage - ?.let { buildRawAeCenterAverageReference(it) } - PLog.d( TAG, "Processing RAW image: ${actualWidth}x${actualHeight}, " + @@ -1807,14 +1406,12 @@ class RawDemosaicProcessor { // 4. 第一步:全分辨率处理 (Linear CCM / RCD Compute Shader Demosaic) setupFullResFramebuffer(actualWidth, actualHeight) if (actualSamplesPerPixel == 3) { - if (!rawTexturePreparedForPgtm) { - uploadLinearRawRgbTextureFromBuffer( - actualRawData, - actualWidth, - actualHeight, - actualRowStride - ) - } + uploadLinearRawRgbTextureFromBuffer( + actualRawData, + actualWidth, + actualHeight, + actualRowStride + ) actualRawData = null renderLinearRawRgbToFramebuffer( sourceTextureId = rawTextureId, @@ -1828,14 +1425,12 @@ class RawDemosaicProcessor { } PLog.d(TAG, "LinearRaw RGB input prepared on GPU: ${actualWidth}x${actualHeight}") } else { - if (!rawTexturePreparedForPgtm) { - uploadRawTextureFromBuffer( - actualRawData, - actualWidth, - actualHeight, - actualRowStride - ) - } + uploadRawTextureFromBuffer( + actualRawData, + actualWidth, + actualHeight, + actualRowStride + ) // GPU 已消费 rawData,立即释放 CPU 侧引用,帮助 GC 回收(超分时约 288 MB) actualRawData = null @@ -2152,49 +1747,37 @@ class RawDemosaicProcessor { PLog.d(TAG, "Applied $appliedWarpCount/${warps.size / 8} DNG WarpRectilinear opcode(s) before color conversion") } - // RAW AE 使用低分辨率实际渲染结果测光,使高光压缩和最终输出保持一致。 - val meteringResult = resolveRawAutoExposureEv( - metadata = actualMetadata, - sourceTextureId = demosaicTextureId, - rawBlackPointCorrection = rawBlackPointCorrection, - rawWhitePointCorrection = rawWhitePointCorrection, - colorCorrectionMatrix = linearColorCorrectionMatrix, - cameraWhite = linearCameraWhite, - dcpRenderPlan = activeDcpRenderPlan, - applyLinearDngBaselineExposure = applyLinearDngBaselineExposure, - applyProfileGainTableMap = hasProfileGainTableMap, - clampProfileRgb = useAdobeProfilePipeline, - viewfinderThumbnailStats = viewfinderThumbnailStats, - viewfinderCenterAverageReference = viewfinderCenterAverageReference, - outputBounds = rawAeContentBounds?.rawRenderBounds ?: bounds, - outputRotation = actualRotation, - spectralFilmLut = spektrafilmLut, - colorEngine = colorEngine, - outputWorkingColorSpace = engineWorkingColorSpace, - profileToEngineTransform = profileToEngineTransform, - rawToneMappingParameters = rawToneMappingParameters, - useProfileExposureRamp = useProfileExposureRamp, - applyProfileDcpBaselineExposureOffset = applyDcpBaselineExposureOffset - ) + if (exposurePreviewRequest != null) { + val solvedExposureEv = renderExposurePreviewRequest( + request = exposurePreviewRequest, + metadata = actualMetadata, + sourceTextureId = demosaicTextureId, + rawBlackPointCorrection = rawBlackPointCorrection, + rawWhitePointCorrection = rawWhitePointCorrection, + colorCorrectionMatrix = linearColorCorrectionMatrix, + cameraWhite = linearCameraWhite, + dcpRenderPlan = activeDcpRenderPlan, + applyLinearDngBaselineExposure = applyLinearDngBaselineExposure, + applyProfileGainTableMap = false, + clampProfileRgb = useAdobeProfilePipeline, + outputBounds = bounds, + outputRotation = actualRotation, + spectralFilmLut = spektrafilmLut, + colorEngine = colorEngine, + outputWorkingColorSpace = engineWorkingColorSpace, + profileToEngineTransform = profileToEngineTransform, + rawToneMappingParameters = rawToneMappingParameters, + useProfileExposureRamp = useProfileExposureRamp, + applyProfileDcpBaselineExposureOffset = applyDcpBaselineExposureOffset + ) + onExposurePreviewSolved?.invoke(solvedExposureEv) + return@withContext null + } - val autoDevelopAvailable = rawAutoExposure && - viewfinderThumbnailStats != null && - meteringResult != MeteringSystem.MeteringResult.EMPTY - val useAutoExposureAdjustment = autoDevelopAvailable && - abs(rawExposureCompensation) <= 0.0001f - val useAutoHighlightsAdjustment = autoDevelopAvailable && - abs(rawHighlightsAdjustment) <= 0.0001f - val effectiveExposureCompensation = if (useAutoExposureAdjustment) { - meteringResult.meteredEv - } else { - rawExposureCompensation - } - // 自动高光只驱动高光滑块,用于恢复已压缩高光区域的细节、色度和对比度;不参与 EV 求解。 - val effectiveHighlightsAdjustment = if (useAutoHighlightsAdjustment) { - meteringResult.highlightCompression.autoHighlightsAdjustment - } else { - rawHighlightsAdjustment - } + // BaselineExposure already contains the capture-time viewfinder match. Rendering only + // applies explicit edit controls. + val effectiveExposureCompensation = rawExposureCompensation + val effectiveHighlightsAdjustment = rawHighlightsAdjustment val engineDefaultExposureCompensation = colorEngine.defaultExposureCompensationEv val profileExposureCompensation = effectiveExposureCompensation + engineDefaultExposureCompensation @@ -2216,36 +1799,10 @@ class RawDemosaicProcessor { highlights = effectiveHighlightsAdjustment, shadows = rawShadowsAdjustment, ) - RawAutoAdjustments( - exposureCompensation = effectiveExposureCompensation.coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV - ), - highlights = shadowsHighlightsParams.highlights, - shadows = shadowsHighlightsParams.shadows - ).also { adjustments -> - PLog.d( - TAG, - "RAW auto develop sliders: exposure=${adjustments.exposureCompensation} " + - "highlights=${adjustments.highlights} shadows=${adjustments.shadows} " + - "autoExposureApplied=$useAutoExposureAdjustment " + - "autoHighlightsApplied=$useAutoHighlightsAdjustment " + - "engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " + - "engineMeteringEv=${colorEngine.meteringCompensationEv} " + - "engineCompensationDomain=${colorEngine.exposureCompensationDomain} " + - "highlightCompressionAmount=${meteringResult.highlightCompression.amount} " + - "highlightCompressionStrength=${meteringResult.highlightCompression.strength} " + - "highlightReductionThreshold=${meteringResult.highlightCompression.reductionThreshold}" - ) - if (useAutoExposureAdjustment || useAutoHighlightsAdjustment) { - onRawAutoAdjustments?.invoke(adjustments) - } - } PLog.d( TAG, - "RAW render exposure: userOrAutoEv=$effectiveExposureCompensation " + + "RAW render exposure: manualEv=$effectiveExposureCompensation " + "engineDefaultEv=${colorEngine.defaultExposureCompensationEv} " + - "engineMeteringEv=${colorEngine.meteringCompensationEv} " + "engineCompensationDomain=${colorEngine.exposureCompensationDomain} " + "profileExposureEv=${profileExposureUniforms.exposureEv} " + "defaultBlackRender=${if (useProfileExposureRamp) dcpDefaultBlackRenderOrAuto(activeDcpRenderPlan) else DcpDefaultBlackRender.None} " + @@ -3409,7 +2966,6 @@ class RawDemosaicProcessor { quadChromaProgram = compileComputeProgram(QuadBayerShaders.CHROMA, "QUAD_CHROMA") quadRefineProgram = compileComputeProgram(QuadBayerShaders.REFINE, "QUAD_REFINE") quadWriteOutputProgram = compileComputeProgram(QuadBayerShaders.WRITE_OUTPUT, "QUAD_WRITE_OUTPUT") - rawProfileGainTableGpuBuilder.initialize() val fShaderLinearRcd = compileShader( GLES30.GL_FRAGMENT_SHADER, @@ -5683,25 +5239,28 @@ class RawDemosaicProcessor { GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) } - private fun setupLinearMeteringFramebuffer(width: Int, height: Int) { - if (linearMeteringWidth == width && linearMeteringHeight == height && linearMeteringFramebufferId != 0) { + private fun setupLinearExposurePreviewFramebuffer(width: Int, height: Int) { + if (linearExposurePreviewWidth == width && + linearExposurePreviewHeight == height && + linearExposurePreviewFramebufferId != 0 + ) { return } - if (linearMeteringTextureId != 0) { - GLES30.glDeleteTextures(1, intArrayOf(linearMeteringTextureId), 0) + if (linearExposurePreviewTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(linearExposurePreviewTextureId), 0) } - if (linearMeteringFramebufferId != 0) { - GLES30.glDeleteFramebuffers(1, intArrayOf(linearMeteringFramebufferId), 0) + if (linearExposurePreviewFramebufferId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(linearExposurePreviewFramebufferId), 0) } - linearMeteringWidth = width - linearMeteringHeight = height + linearExposurePreviewWidth = width + linearExposurePreviewHeight = height val textures = IntArray(1) GLES30.glGenTextures(1, textures, 0) - linearMeteringTextureId = textures[0] - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, linearMeteringTextureId) + linearExposurePreviewTextureId = textures[0] + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, linearExposurePreviewTextureId) GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR) GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR) @@ -5718,41 +5277,41 @@ class RawDemosaicProcessor { val framebuffers = IntArray(1) GLES30.glGenFramebuffers(1, framebuffers, 0) - linearMeteringFramebufferId = framebuffers[0] - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearMeteringFramebufferId) + linearExposurePreviewFramebufferId = framebuffers[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, linearExposurePreviewFramebufferId) GLES30.glFramebufferTexture2D( GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, - linearMeteringTextureId, + linearExposurePreviewTextureId, 0 ) - checkGlError("setupLinearMeteringFramebuffer") + checkGlError("setupLinearExposurePreviewFramebuffer") } - private fun setupSrgbMeteringCropFramebuffer(width: Int, height: Int) { + private fun setupSrgbExposurePreviewFramebuffer(width: Int, height: Int) { if ( - srgbMeteringCropWidth == width && - srgbMeteringCropHeight == height && - srgbMeteringCropFramebufferId != 0 + srgbExposurePreviewWidth == width && + srgbExposurePreviewHeight == height && + srgbExposurePreviewFramebufferId != 0 ) { return } - if (srgbMeteringCropTextureId != 0) { - GLES30.glDeleteTextures(1, intArrayOf(srgbMeteringCropTextureId), 0) + if (srgbExposurePreviewTextureId != 0) { + GLES30.glDeleteTextures(1, intArrayOf(srgbExposurePreviewTextureId), 0) } - if (srgbMeteringCropFramebufferId != 0) { - GLES30.glDeleteFramebuffers(1, intArrayOf(srgbMeteringCropFramebufferId), 0) + if (srgbExposurePreviewFramebufferId != 0) { + GLES30.glDeleteFramebuffers(1, intArrayOf(srgbExposurePreviewFramebufferId), 0) } - srgbMeteringCropWidth = width - srgbMeteringCropHeight = height + srgbExposurePreviewWidth = width + srgbExposurePreviewHeight = height val textures = IntArray(1) GLES30.glGenTextures(1, textures, 0) - srgbMeteringCropTextureId = textures[0] - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, srgbMeteringCropTextureId) + srgbExposurePreviewTextureId = textures[0] + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, srgbExposurePreviewTextureId) GLES30.glTexImage2D( GLES30.GL_TEXTURE_2D, 0, @@ -5771,16 +5330,16 @@ class RawDemosaicProcessor { val framebuffers = IntArray(1) GLES30.glGenFramebuffers(1, framebuffers, 0) - srgbMeteringCropFramebufferId = framebuffers[0] - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbMeteringCropFramebufferId) + srgbExposurePreviewFramebufferId = framebuffers[0] + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbExposurePreviewFramebufferId) GLES30.glFramebufferTexture2D( GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, - srgbMeteringCropTextureId, + srgbExposurePreviewTextureId, 0 ) - checkGlError("setupSrgbMeteringCropFramebuffer") + checkGlError("setupSrgbExposurePreviewFramebuffer") } private fun setupHdrReferenceFramebuffer(width: Int, height: Int) { @@ -7816,7 +7375,8 @@ class RawDemosaicProcessor { return textureId } - private suspend fun resolveRawAutoExposureEv( + private fun renderExposurePreviewRequest( + request: RawExposurePreviewRequest, metadata: RawMetadata, sourceTextureId: Int, rawBlackPointCorrection: Float, @@ -7827,8 +7387,6 @@ class RawDemosaicProcessor { applyLinearDngBaselineExposure: Boolean, applyProfileGainTableMap: Boolean, clampProfileRgb: Boolean, - viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats?, - viewfinderCenterAverageReference: RawAeCenterAverageReference?, outputBounds: Rect, outputRotation: Int, spectralFilmLut: SpectralFilmLut?, @@ -7838,25 +7396,22 @@ class RawDemosaicProcessor { rawToneMappingParameters: RawToneMappingParameters, useProfileExposureRamp: Boolean, applyProfileDcpBaselineExposureOffset: Boolean - ): MeteringSystem.MeteringResult { - if (viewfinderThumbnailStats == null) { - return MeteringSystem.MeteringResult.EMPTY - } - val meteringSize = resolveLongEdgeMeteringSize( + ): Float? { + val previewSize = resolveLongEdgePreviewSize( sourceWidth = metadata.width, sourceHeight = metadata.height, - maxLongEdge = RAW_TONE_MAPPED_AE_LONG_EDGE + maxLongEdge = 256 ) - val meteringWidth = meteringSize.width - val meteringHeight = meteringSize.height + val previewWidth = previewSize.width + val previewHeight = previewSize.height return try { - setupLinearMeteringFramebuffer(meteringWidth, meteringHeight) + setupLinearExposurePreviewFramebuffer(previewWidth, previewHeight) renderLinearRcdPass( metadata = metadata, sourceTextureId = sourceTextureId, - targetFramebufferId = linearMeteringFramebufferId, - viewportWidth = meteringWidth, - viewportHeight = meteringHeight, + targetFramebufferId = linearExposurePreviewFramebufferId, + viewportWidth = previewWidth, + viewportHeight = previewHeight, rawExposureCompensation = 0f, colorCorrectionMatrix = colorCorrectionMatrix, cameraWhite = cameraWhite, @@ -7864,94 +7419,89 @@ class RawDemosaicProcessor { applyDngBaselineExposure = applyLinearDngBaselineExposure, applyProfileGainTableMap = applyProfileGainTableMap, clampProfileRgb = clampProfileRgb, - label = "LinearMeteringPass" + label = "LinearExposurePreviewPass" ) GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) GLES31.glMemoryBarrier( GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT ) - setupCombinedFramebuffer(meteringWidth, meteringHeight) - val meteringBounds = scaleMeteringBounds( + setupCombinedFramebuffer(previewWidth, previewHeight) + val previewBounds = scaleExposurePreviewBounds( bounds = outputBounds, sourceWidth = metadata.width, sourceHeight = metadata.height, - targetWidth = meteringWidth, - targetHeight = meteringHeight, + targetWidth = previewWidth, + targetHeight = previewHeight, outputRotation = outputRotation ) - setupSrgbMeteringCropFramebuffer( - viewfinderThumbnailStats.width.coerceAtLeast(1), - viewfinderThumbnailStats.height.coerceAtLeast(1) + setupSrgbExposurePreviewFramebuffer( + request.width.coerceAtLeast(1), + request.height.coerceAtLeast(1) ) - resolveToneMappedRawAutoExposureEv( - metadata = metadata, - linearTextureId = linearMeteringTextureId, - width = meteringWidth, - height = meteringHeight, - meteringBounds = meteringBounds, - readbackWidth = viewfinderThumbnailStats.width.coerceAtLeast(1), - readbackHeight = viewfinderThumbnailStats.height.coerceAtLeast(1), - outputRotation = outputRotation, - viewfinderThumbnailStats = viewfinderThumbnailStats, - viewfinderCenterAverageReference = viewfinderCenterAverageReference, - dcpRenderPlan = dcpRenderPlan, - spectralFilmLut = spectralFilmLut, - colorEngine = colorEngine, - outputWorkingColorSpace = outputWorkingColorSpace, - profileToEngineTransform = profileToEngineTransform, - rawToneMappingParameters = rawToneMappingParameters, - rawBlacksAdjustment = rawBlackPointCorrection, - rawWhitesAdjustment = rawWhitePointCorrection, - useProfileExposureRamp = useProfileExposureRamp, - applyProfileDcpBaselineExposureOffset = applyProfileDcpBaselineExposureOffset, - applyProfileDngBaselineExposure = !applyLinearDngBaselineExposure - ) ?: MeteringSystem.MeteringResult.EMPTY + val pixelCount = request.width.coerceAtLeast(1) * request.height.coerceAtLeast(1) + val readbackBuffer = LargeDirectBuffer.allocate( + pixelCount.toLong() * 4L, + "RAW exposure preview readback" + ) ?: return null + try { + request.solve { exposureEv -> + renderToneMappedExposurePreviewFrame( + metadata = metadata, + linearTextureId = linearExposurePreviewTextureId, + width = previewWidth, + height = previewHeight, + exposureEv = exposureEv, + dcpRenderPlan = dcpRenderPlan, + spectralFilmLut = spectralFilmLut, + colorEngine = colorEngine, + outputWorkingColorSpace = outputWorkingColorSpace, + profileToEngineTransform = profileToEngineTransform, + rawToneMappingParameters = rawToneMappingParameters, + rawBlacksAdjustment = rawBlackPointCorrection, + rawWhitesAdjustment = rawWhitePointCorrection, + useProfileExposureRamp = useProfileExposureRamp, + applyProfileDcpBaselineExposureOffset = applyProfileDcpBaselineExposureOffset, + applyProfileDngBaselineExposure = !applyLinearDngBaselineExposure, + readbackBounds = previewBounds, + readbackWidth = request.width.coerceAtLeast(1), + readbackHeight = request.height.coerceAtLeast(1), + outputRotation = outputRotation, + readbackBuffer = readbackBuffer, + ) + } + } finally { + LargeDirectBuffer.free(readbackBuffer) + } } catch (e: Exception) { - PLog.e(TAG, "Failed to resolve RAW auto exposure", e) - MeteringSystem.MeteringResult.EMPTY + PLog.e(TAG, "Failed to render RAW exposure preview", e) + null } } - private data class ToneMappedRawAeSample( - val autoEv: Float, - val profileExposureEv: Float, - val renderedLuma: Float, - val errorEv: Float, - val centerAverageMatch: RawAeCenterAverageMatch, - val stats: MeteringSystem.SrgbThumbnailMeteringStats, - val argbPixels: IntArray - ) - - private data class ToneMappedRawAeSolveResult( - val meteredEv: Float, - val finalSample: ToneMappedRawAeSample, - val renderedStepCount: Int - ) - - private data class RawAeMeteringSize( + private data class ExposurePreviewSize( val width: Int, val height: Int ) - private fun resolveLongEdgeMeteringSize( + private fun resolveLongEdgePreviewSize( sourceWidth: Int, sourceHeight: Int, maxLongEdge: Int - ): RawAeMeteringSize { + ): ExposurePreviewSize { if (sourceWidth <= 0 || sourceHeight <= 0) { - return RawAeMeteringSize(1, 1) + return ExposurePreviewSize(1, 1) } val longEdge = minOf(max(sourceWidth, sourceHeight), maxLongEdge.coerceAtLeast(1)) .coerceAtLeast(1) return if (sourceWidth >= sourceHeight) { - RawAeMeteringSize( + ExposurePreviewSize( width = longEdge, height = ((longEdge.toFloat() * sourceHeight.toFloat() / sourceWidth.toFloat()) + 0.5f) .toInt() .coerceAtLeast(1) ) } else { - RawAeMeteringSize( + ExposurePreviewSize( width = ((longEdge.toFloat() * sourceWidth.toFloat() / sourceHeight.toFloat()) + 0.5f) .toInt() .coerceAtLeast(1), @@ -7960,7 +7510,7 @@ class RawDemosaicProcessor { } } - private fun scaleMeteringBounds( + private fun scaleExposurePreviewBounds( bounds: Rect, sourceWidth: Int, sourceHeight: Int, @@ -7989,246 +7539,12 @@ class RawDemosaicProcessor { return Rect(left, top, right, bottom) } - private fun resolveToneMappedRawAutoExposureEv( + private fun renderToneMappedExposurePreviewFrame( metadata: RawMetadata, linearTextureId: Int, width: Int, height: Int, - meteringBounds: Rect, - readbackWidth: Int, - readbackHeight: Int, - outputRotation: Int, - viewfinderThumbnailStats: MeteringSystem.SrgbThumbnailMeteringStats, - viewfinderCenterAverageReference: RawAeCenterAverageReference?, - dcpRenderPlan: DcpRenderPlan?, - spectralFilmLut: SpectralFilmLut?, - colorEngine: RawRenderingEngine, - outputWorkingColorSpace: ColorSpace, - profileToEngineTransform: FloatArray, - rawToneMappingParameters: RawToneMappingParameters, - rawBlacksAdjustment: Float, - rawWhitesAdjustment: Float, - useProfileExposureRamp: Boolean, - applyProfileDcpBaselineExposureOffset: Boolean, - applyProfileDngBaselineExposure: Boolean - ): MeteringSystem.MeteringResult? { - val centerAverageReference = viewfinderCenterAverageReference ?: run { - PLog.d(TAG, "RAW auto exposure disabled: center average reference unavailable") - return null - } - val pixelCount = readbackWidth * readbackHeight - val readbackBuffer = LargeDirectBuffer.allocate( - pixelCount.toLong() * 4L, - "tone-mapped RAW AE readback" - ) ?: return null - - return try { - val zero = renderToneMappedRawAeSample( - metadata = metadata, - linearTextureId = linearTextureId, - width = width, - height = height, - autoEv = 0f, - centerAverageReference = centerAverageReference, - dcpRenderPlan = dcpRenderPlan, - spectralFilmLut = spectralFilmLut, - colorEngine = colorEngine, - outputWorkingColorSpace = outputWorkingColorSpace, - profileToEngineTransform = profileToEngineTransform, - rawToneMappingParameters = rawToneMappingParameters, - rawBlacksAdjustment = rawBlacksAdjustment, - rawWhitesAdjustment = rawWhitesAdjustment, - useProfileExposureRamp = useProfileExposureRamp, - applyProfileDcpBaselineExposureOffset = applyProfileDcpBaselineExposureOffset, - applyProfileDngBaselineExposure = applyProfileDngBaselineExposure, - readbackBounds = meteringBounds, - readbackWidth = readbackWidth, - readbackHeight = readbackHeight, - outputRotation = outputRotation, - readbackBuffer = readbackBuffer - ) ?: return null - val solved = solveToneMappedRawAutoExposure(zero) { autoEv -> - renderToneMappedRawAeSample( - metadata = metadata, - linearTextureId = linearTextureId, - width = width, - height = height, - autoEv = autoEv, - centerAverageReference = centerAverageReference, - dcpRenderPlan = dcpRenderPlan, - spectralFilmLut = spectralFilmLut, - colorEngine = colorEngine, - outputWorkingColorSpace = outputWorkingColorSpace, - profileToEngineTransform = profileToEngineTransform, - rawToneMappingParameters = rawToneMappingParameters, - rawBlacksAdjustment = rawBlacksAdjustment, - rawWhitesAdjustment = rawWhitesAdjustment, - useProfileExposureRamp = useProfileExposureRamp, - applyProfileDcpBaselineExposureOffset = applyProfileDcpBaselineExposureOffset, - applyProfileDngBaselineExposure = applyProfileDngBaselineExposure, - readbackBounds = meteringBounds, - readbackWidth = readbackWidth, - readbackHeight = readbackHeight, - outputRotation = outputRotation, - readbackBuffer = readbackBuffer - ) - } - val finalSample = solved.finalSample - val meteredEv = solved.meteredEv - val highlightCompression = viewfinderThumbnailStats.highlightCompression - - MeteringSystem.MeteringResult( - meteredEv = meteredEv, - dynamicRangeGap = 0f, - avgLuma = finalSample.renderedLuma, - clipLow = finalSample.stats.clipLow, - clipHigh = finalSample.stats.clipHigh, - curveWhitePoint = 1f, - highlightCompression = highlightCompression - ) - } finally { - LargeDirectBuffer.free(readbackBuffer) - } - } - - private fun solveToneMappedRawAutoExposure( - zero: ToneMappedRawAeSample, - renderSample: (Float) -> ToneMappedRawAeSample? - ): ToneMappedRawAeSolveResult { - if (abs(zero.errorEv) <= RAW_TONE_MAPPED_AE_EV_TOLERANCE) { - return ToneMappedRawAeSolveResult( - meteredEv = zero.autoEv, - finalSample = zero, - renderedStepCount = 0 - ) - } - - val samples = mutableListOf(zero) - var bestSample = zero - var renderedStepCount = 0 - var nextEv = rawAutoExposureEvForSample(zero) - - while (renderedStepCount < RAW_TONE_MAPPED_AE_MAX_SOLVE_STEPS) { - val candidateEv = distinctRawAutoExposureCandidate(nextEv, samples) ?: break - val sample = renderSample(candidateEv) - ?: return ToneMappedRawAeSolveResult( - meteredEv = if (renderedStepCount == 0) candidateEv else bestSample.autoEv, - finalSample = bestSample, - renderedStepCount = renderedStepCount - ) - renderedStepCount++ - samples += sample - - if (abs(sample.errorEv) < abs(bestSample.errorEv)) { - bestSample = sample - } - if (abs(sample.errorEv) <= RAW_TONE_MAPPED_AE_EV_TOLERANCE) { - return ToneMappedRawAeSolveResult( - meteredEv = sample.autoEv, - finalSample = sample, - renderedStepCount = renderedStepCount - ) - } - - nextEv = nextRawAutoExposureCandidate(samples, sample) - } - - return ToneMappedRawAeSolveResult( - meteredEv = bestSample.autoEv, - finalSample = bestSample, - renderedStepCount = renderedStepCount - ) - } - - private fun nextRawAutoExposureCandidate( - samples: List, - latest: ToneMappedRawAeSample - ): Float { - bracketedRawAutoExposureCandidate(samples)?.let { return it } - val previous = samples - .asReversed() - .firstOrNull { - it !== latest && abs(it.errorEv - latest.errorEv) > 0.0001f - } - val secantEv = previous?.let { interpolatedRawAutoExposureEv(it, latest) } - return secantEv ?: rawAutoExposureEvForSample(latest) - } - - private fun bracketedRawAutoExposureCandidate( - samples: List - ): Float? { - val sortedSamples = samples.sortedBy { it.autoEv } - for (index in 0 until sortedSamples.lastIndex) { - val lower = sortedSamples[index] - val upper = sortedSamples[index + 1] - val crossesTarget = - (lower.errorEv <= 0f && upper.errorEv >= 0f) || - (lower.errorEv >= 0f && upper.errorEv <= 0f) - if (!crossesTarget) continue - - val interpolatedEv = interpolatedRawAutoExposureEv(lower, upper) - return if (interpolatedEv != null && - interpolatedEv >= lower.autoEv && - interpolatedEv <= upper.autoEv - ) { - interpolatedEv - } else { - ((lower.autoEv + upper.autoEv) * 0.5f).coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV - ) - } - } - return null - } - - private fun interpolatedRawAutoExposureEv( - a: ToneMappedRawAeSample, - b: ToneMappedRawAeSample - ): Float? { - val errorDelta = b.errorEv - a.errorEv - if (!errorDelta.isFinite() || abs(errorDelta) <= 0.0001f) { - return null - } - return sanitizeRawAutoExposureEv( - a.autoEv - a.errorEv * (b.autoEv - a.autoEv) / errorDelta - ) - } - - private fun rawAutoExposureEvForSample(sample: ToneMappedRawAeSample): Float { - return sanitizeRawAutoExposureEv(sample.autoEv - sample.errorEv) ?: sample.autoEv - } - - private fun distinctRawAutoExposureCandidate( - candidateEv: Float, - samples: List - ): Float? { - val safeEv = sanitizeRawAutoExposureEv(candidateEv) ?: return null - return if (samples.any { abs(it.autoEv - safeEv) < RAW_TONE_MAPPED_AE_MIN_STEP_EV }) { - null - } else { - safeEv - } - } - - private fun sanitizeRawAutoExposureEv(value: Float): Float? { - return if (value.isFinite()) { - value.coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV - ) - } else { - null - } - } - - private fun renderToneMappedRawAeSample( - metadata: RawMetadata, - linearTextureId: Int, - width: Int, - height: Int, - autoEv: Float, - centerAverageReference: RawAeCenterAverageReference, + exposureEv: Float, dcpRenderPlan: DcpRenderPlan?, spectralFilmLut: SpectralFilmLut?, colorEngine: RawRenderingEngine, @@ -8245,14 +7561,11 @@ class RawDemosaicProcessor { readbackHeight: Int, outputRotation: Int, readbackBuffer: ByteBuffer - ): ToneMappedRawAeSample? { - val clampedAutoEv = autoEv.coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV - ) + ): RawExposurePreviewFrame? { + val clampedExposureEv = exposureEv.coerceIn(-4f, 4f) val profileExposureUniforms = computeProfileExposureUniforms( metadata = metadata, - profileExposureCompensation = clampedAutoEv + colorEngine.defaultExposureCompensationEv, + profileExposureCompensation = clampedExposureEv + colorEngine.defaultExposureCompensationEv, dcpRenderPlan = dcpRenderPlan, applyDcpBaselineExposureOffset = applyProfileDcpBaselineExposureOffset, applyDngBaselineExposure = applyProfileDngBaselineExposure, @@ -8276,10 +7589,10 @@ class RawDemosaicProcessor { viewportHeight = height ) if (!rendered) { - PLog.e(TAG, "Tone-mapped RAW AE render failed for ev=$clampedAutoEv") + PLog.e(TAG, "RAW exposure preview render failed for ev=$clampedExposureEv") return null } - if (!renderSrgbMeteringCropPass( + if (!renderSrgbExposurePreviewPass( sourceTextureId = combinedTextureId, sourceWidth = width, sourceHeight = height, @@ -8291,28 +7604,14 @@ class RawDemosaicProcessor { ) { return null } - val image = readSrgbMeteringCropImage( + return readExposurePreviewFrame( width = readbackWidth, height = readbackHeight, pixelBuffer = readbackBuffer - ) ?: return null - val stats = image.stats - val centerAverageMatch = matchRawAeCenterAverage(centerAverageReference, image) - ?: return null - val renderedLuma = centerAverageMatch.renderedDisplayLuma - val errorEv = centerAverageMatch.errorEv - return ToneMappedRawAeSample( - autoEv = clampedAutoEv, - profileExposureEv = profileExposureUniforms.exposureEv, - renderedLuma = renderedLuma, - errorEv = errorEv, - centerAverageMatch = centerAverageMatch, - stats = stats, - argbPixels = image.argbPixels ) } - private fun renderSrgbMeteringCropPass( + private fun renderSrgbExposurePreviewPass( sourceTextureId: Int, sourceWidth: Int, sourceHeight: Int, @@ -8321,15 +7620,15 @@ class RawDemosaicProcessor { targetHeight: Int, rotation: Int ): Boolean { - if (passthroughProgram == 0 || srgbMeteringCropFramebufferId == 0) { + if (passthroughProgram == 0 || srgbExposurePreviewFramebufferId == 0) { PLog.e( TAG, - "Tone-mapped RAW AE crop unavailable: program=$passthroughProgram " + - "fbo=$srgbMeteringCropFramebufferId" + "RAW exposure preview crop unavailable: program=$passthroughProgram " + + "fbo=$srgbExposurePreviewFramebufferId" ) return false } - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbMeteringCropFramebufferId) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbExposurePreviewFramebufferId) GLES30.glViewport(0, 0, targetWidth, targetHeight) GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT) GLES30.glUseProgram(passthroughProgram) @@ -8368,22 +7667,22 @@ class RawDemosaicProcessor { GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) GLES30.glUniform1i(GLES30.glGetUniformLocation(passthroughProgram, "uTexture"), 0) drawQuad(passthroughProgram) - checkGlError("tone-mapped RAW AE crop pass") + checkGlError("RAW exposure preview crop pass") return true } - private fun readSrgbMeteringCropImage( + private fun readExposurePreviewFrame( width: Int, height: Int, pixelBuffer: ByteBuffer - ): RawAeMeteringImage? { + ): RawExposurePreviewFrame? { if (width <= 0 || height <= 0) { return null } val pixelCount = width * height pixelBuffer.clear() pixelBuffer.limit(pixelCount * 4) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbMeteringCropFramebufferId) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, srgbExposurePreviewFramebufferId) GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1) GLES30.glReadPixels( 0, @@ -8394,7 +7693,7 @@ class RawDemosaicProcessor { GLES30.GL_UNSIGNED_BYTE, pixelBuffer ) - checkGlError("tone-mapped RAW AE readback") + checkGlError("RAW exposure preview readback") pixelBuffer.position(0) val argbPixels = IntArray(pixelCount) @@ -8405,28 +7704,13 @@ class RawDemosaicProcessor { val a = pixelBuffer.get().toInt() and 0xff argbPixels[i] = (a shl 24) or (r shl 16) or (g shl 8) or b } - val stats = MeteringSystem.analyzeSrgbThumbnail(width, height, argbPixels) - ?: return null - return RawAeMeteringImage( + return RawExposurePreviewFrame( width = width, height = height, argbPixels = argbPixels, - stats = stats ) } - private fun displayLumaErrorEv(renderedLuma: Float, targetLuma: Float): Float { - val safeRendered = renderedLuma - .takeIf { it.isFinite() } - ?.coerceAtLeast(RAW_TONE_MAPPED_AE_LUMA_FLOOR) - ?: RAW_TONE_MAPPED_AE_LUMA_FLOOR - val safeTarget = targetLuma - .takeIf { it.isFinite() } - ?.coerceAtLeast(RAW_TONE_MAPPED_AE_LUMA_FLOOR) - ?: RAW_TONE_MAPPED_AE_LUMA_FLOOR - return (ln(safeRendered.toDouble() / safeTarget.toDouble()) / ln(2.0)).toFloat() - } - private fun renderOutputPass( rotation: Int, width: Int, @@ -8728,7 +8012,6 @@ class RawDemosaicProcessor { if (rawHdrLinearAccumulateProgram != 0) GLES31.glDeleteProgram(rawHdrLinearAccumulateProgram) if (rawHdrLinearNormalizeProgram != 0) GLES31.glDeleteProgram(rawHdrLinearNormalizeProgram) if (rawHdrLinearPreviewProgram != 0) GLES31.glDeleteProgram(rawHdrLinearPreviewProgram) - rawProfileGainTableGpuBuilder.release() // darktable denoiseprofile compute programs if (denoisePreconditionV2Program != 0) GLES31.glDeleteProgram(denoisePreconditionV2Program) @@ -8787,24 +8070,24 @@ class RawDemosaicProcessor { intArrayOf(adjustmentFramebufferId), 0 ) - if (linearMeteringTextureId != 0) GLES30.glDeleteTextures( + if (linearExposurePreviewTextureId != 0) GLES30.glDeleteTextures( 1, - intArrayOf(linearMeteringTextureId), + intArrayOf(linearExposurePreviewTextureId), 0 ) - if (linearMeteringFramebufferId != 0) GLES30.glDeleteFramebuffers( + if (linearExposurePreviewFramebufferId != 0) GLES30.glDeleteFramebuffers( 1, - intArrayOf(linearMeteringFramebufferId), + intArrayOf(linearExposurePreviewFramebufferId), 0 ) - if (srgbMeteringCropTextureId != 0) GLES30.glDeleteTextures( + if (srgbExposurePreviewTextureId != 0) GLES30.glDeleteTextures( 1, - intArrayOf(srgbMeteringCropTextureId), + intArrayOf(srgbExposurePreviewTextureId), 0 ) - if (srgbMeteringCropFramebufferId != 0) GLES30.glDeleteFramebuffers( + if (srgbExposurePreviewFramebufferId != 0) GLES30.glDeleteFramebuffers( 1, - intArrayOf(srgbMeteringCropFramebufferId), + intArrayOf(srgbExposurePreviewFramebufferId), 0 ) if (hdrReferenceTextureId != 0) GLES30.glDeleteTextures( diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt new file mode 100644 index 00000000..f8ea7dae --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt @@ -0,0 +1,30 @@ +package com.hinnka.mycamera.raw + +import android.graphics.Rect +import java.nio.ByteBuffer + +/** Metadata generated before a RAW buffer is written as DNG. */ +data class RawDngProfilePreparationOptions( + val profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon, + val statsBounds: Rect? = null, + val viewfinderExposureMatcher: RawDngViewfinderExposureMatcher? = null, +) + +fun interface RawDngViewfinderExposureMatcher { + suspend fun match(input: RawDngViewfinderMatchInput): Float? +} + +data class RawDngViewfinderMatchInput( + val rawData: ByteBuffer, + val width: Int, + val height: Int, + val rowStride: Int, + val samplesPerPixel: Int, + val metadata: RawMetadata, +) + +/** BaselineExposure and optional PGTM prepared before the DNG writer starts. */ +internal data class RawDngProfilePreparation( + val baselineExposureEv: Float, + val profileGainTableMap: DngProfileGainTableMap?, +) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt index 5a29f8d0..c9077996 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawProfileGainTableMapBuilder.kt @@ -13,58 +13,84 @@ internal object RawProfileGainTableMapBuilder { private data class BuiltPgtmStats( val packedCellStats: FloatArray, - val globalStats: DngPgtmGlobalStats?, ) - fun build( + fun prepareForDngWrite( rawData: ByteBuffer, width: Int, height: Int, rowStride: Int, metadata: RawMetadata, samplesPerPixel: Int = 1, - statsBounds: Rect? = null, - profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon, + options: RawDngProfilePreparationOptions = RawDngProfilePreparationOptions(), colorCorrectionMatrix: FloatArray = metadata.colorCorrectionMatrix, cameraWhite: FloatArray = metadata.cameraWhite, hueSatMap: DcpHueSatMap? = null, - ): DngProfileGainTableMap? { - val stats = buildPackedCellStats( + ): RawDngProfilePreparation? { + val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure) + val generatePgtm = options.profileToneMapMode == RawProfileToneMapMode.Photon || + options.profileToneMapMode == RawProfileToneMapMode.GooglePixel + if (!generatePgtm) { + return RawDngProfilePreparation( + baselineExposureEv = baselineExposureEv, + profileGainTableMap = null, + ) + } + + val statsMetadata = metadata.copy(baselineExposure = baselineExposureEv) + val initialStats = buildPackedCellStats( rawData = rawData, width = width, height = height, rowStride = rowStride, - metadata = metadata, + metadata = statsMetadata, samplesPerPixel = samplesPerPixel, - statsBounds = statsBounds, + statsBounds = options.statsBounds, colorCorrectionMatrix = colorCorrectionMatrix, cameraWhite = cameraWhite, hueSatMap = hueSatMap, - collectGlobalStats = profileToneMapMode == RawProfileToneMapMode.Photon ) ?: return null + return prepareFromStats( + width = width, + height = height, + baselineExposureEv = baselineExposureEv, + profileToneMapMode = options.profileToneMapMode, + packedCellStats = initialStats.packedCellStats, + ) + } + + internal fun prepareFromStats( + width: Int, + height: Int, + baselineExposureEv: Float, + profileToneMapMode: RawProfileToneMapMode, + packedCellStats: FloatArray, + ): RawDngProfilePreparation? { + val generatePgtm = profileToneMapMode == RawProfileToneMapMode.Photon || + profileToneMapMode == RawProfileToneMapMode.GooglePixel val diagnosticBand = DngPgtmDiagnostic.activeBandForSource(TAG) - val baselineExposureEv = DngBaselineExposure.sanitize(metadata.baselineExposure) - return when (profileToneMapMode) { - RawProfileToneMapMode.GooglePixel -> DngHdrProfileGainTableGenerator.forCellStats( + val profileGainTableMap = if (generatePgtm) { + DngHdrProfileGainTableGenerator.forCellStats( width = width, height = height, baselineExposureEv = baselineExposureEv, - packedCellStats = stats.packedCellStats, - diagnosticBand = diagnosticBand - ) - - RawProfileToneMapMode.Photon -> DngPhotonProfileGainTableGenerator.forCellStats( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedCellStats = stats.packedCellStats, - globalStats = stats.globalStats ?: return null, - diagnosticBand = diagnosticBand - ) - - RawProfileToneMapMode.Default, - RawProfileToneMapMode.OppoMaster -> null + packedCellStats = packedCellStats, + diagnosticBand = diagnosticBand, + ) ?: run { + PLog.w( + TAG, + "PGTM generation failed: mode=$profileToneMapMode " + + "baselineExposureEv=$baselineExposureEv size=${width}x$height" + ) + return null + } + } else { + null } + return RawDngProfilePreparation( + baselineExposureEv = baselineExposureEv, + profileGainTableMap = profileGainTableMap, + ) } private fun buildPackedCellStats( @@ -78,7 +104,6 @@ internal object RawProfileGainTableMapBuilder { colorCorrectionMatrix: FloatArray, cameraWhite: FloatArray, hueSatMap: DcpHueSatMap?, - collectGlobalStats: Boolean, ): BuiltPgtmStats? { if (width <= 0 || height <= 0 || metadata.whiteLevel <= 0f) return null val sampleCountPerPixel = samplesPerPixel.coerceAtLeast(1) @@ -107,12 +132,6 @@ internal object RawProfileGainTableMapBuilder { val baselineGain = DngBaselineExposure.exactGain(metadata.baselineExposure) val stats = FloatArray(gridWidth * gridHeight * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE) val inputSamples = FloatArray(SAMPLE_GRID * SAMPLE_GRID) - val globalSamples = if (collectGlobalStats) { - FloatArray(gridWidth * gridHeight * SAMPLE_GRID * SAMPLE_GRID) - } else { - null - } - var globalSampleCount = 0 val statsWidth = safeStatsBounds.width() val statsHeight = safeStatsBounds.height() for (cellY in 0 until gridHeight) { @@ -158,10 +177,6 @@ internal object RawProfileGainTableMapBuilder { hueSatMap = hueSatMap, ) inputSamples[sampleCount] = inputValue - if (globalSamples != null) { - globalSamples[globalSampleCount] = inputValue - globalSampleCount += 1 - } sampleCount += 1 if (inputValue >= 0.92f) { highlightCount += 1 @@ -184,15 +199,8 @@ internal object RawProfileGainTableMapBuilder { stats[offset + 7] = percentileFromSortedSamples(inputSamples, sampleCount, 0.999f) } } - val globalStats = globalSamples?.let { samples -> - DngPgtmGlobalStats.fromMutableSamples( - samples = samples, - sampleCount = globalSampleCount - ) ?: return null - } return BuiltPgtmStats( packedCellStats = stats, - globalStats = globalStats ) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawRenderingEngine.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawRenderingEngine.kt index 496adc62..463c524a 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawRenderingEngine.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawRenderingEngine.kt @@ -1,6 +1,6 @@ package com.hinnka.mycamera.raw -const val RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV = 0.7f +const val RAW_RENDERING_ENGINE_DEFAULT_EXPOSURE_EV = 0.7f enum class RawExposureCompensationDomain { Curve, @@ -11,42 +11,36 @@ enum class RawRenderingEngine( val shaderId: Int, val workingColorSpace: ColorSpace, val defaultExposureCompensationEv: Float, - val meteringCompensationEv: Float, val exposureCompensationDomain: RawExposureCompensationDomain ) { AdobeCurve( shaderId = 0, workingColorSpace = ColorSpace.ProPhoto, defaultExposureCompensationEv = 0f, - meteringCompensationEv = 1f, exposureCompensationDomain = RawExposureCompensationDomain.Curve ), DarktableFilmic( shaderId = 4, workingColorSpace = ColorSpace.BT2020, - defaultExposureCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, - meteringCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, + defaultExposureCompensationEv = RAW_RENDERING_ENGINE_DEFAULT_EXPOSURE_EV, exposureCompensationDomain = RawExposureCompensationDomain.Linear ), AgX( shaderId = 1, workingColorSpace = ColorSpace.BT2020, - defaultExposureCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, - meteringCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, + defaultExposureCompensationEv = RAW_RENDERING_ENGINE_DEFAULT_EXPOSURE_EV, exposureCompensationDomain = RawExposureCompensationDomain.Linear ), DarktableSigmoid( shaderId = 3, workingColorSpace = ColorSpace.BT2020, - defaultExposureCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, - meteringCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, + defaultExposureCompensationEv = RAW_RENDERING_ENGINE_DEFAULT_EXPOSURE_EV, exposureCompensationDomain = RawExposureCompensationDomain.Linear ), Spektrafilm( shaderId = 2, workingColorSpace = ColorSpace.ProPhoto, - defaultExposureCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, - meteringCompensationEv = RAW_RENDERING_ENGINE_METERING_COMPENSATION_EV, + defaultExposureCompensationEv = RAW_RENDERING_ENGINE_DEFAULT_EXPOSURE_EV, exposureCompensationDomain = RawExposureCompensationDomain.Linear ), ; diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawViewfinderExposureMatcher.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawViewfinderExposureMatcher.kt new file mode 100644 index 00000000..3ae3dfbf --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawViewfinderExposureMatcher.kt @@ -0,0 +1,295 @@ +package com.hinnka.mycamera.raw + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Rect +import com.hinnka.mycamera.camera.AspectRatio +import com.hinnka.mycamera.camera.RawBlackBorderCrop +import com.hinnka.mycamera.utils.PLog +import kotlin.math.abs +import kotlin.math.ln +import kotlin.math.max + +internal data class RawExposurePreviewFrame( + val width: Int, + val height: Int, + val argbPixels: IntArray, +) + +/** + * Capture-side viewfinder matcher. + * + * The RAW renderer only supplies default-curve preview samples for requested EV values. All + * thumbnail analysis, error calculation and iterative exposure solving live here, outside the + * normal RAW rendering path. + */ +internal object RawViewfinderExposureMatcher { + private const val TAG = "RawViewfinderExposureMatcher" + private const val PREVIEW_LONG_EDGE = 256 + private const val LUMA_FLOOR = 0.001f + private const val MAX_SOLVE_STEPS = 3 + private const val EV_TOLERANCE = 0.05f + private const val MIN_STEP_EV = 0.025f + + suspend fun match( + renderer: RawDemosaicProcessor, + context: Context, + input: RawDngViewfinderMatchInput, + aspectRatio: AspectRatio?, + cropRegion: Rect?, + rotation: Int, + capturePreviewThumbnail: Bitmap, + rawBlackPointCorrection: Float = 0f, + rawWhitePointCorrection: Float = 0f, + rawAutoWhiteBalanceEstimate: Boolean = false, + applyLensShadingCorrection: Boolean = true, + rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), + ): Float? { + val reference = buildReference(capturePreviewThumbnail) ?: run { + PLog.w(TAG, "Viewfinder match skipped: capture preview is unavailable") + return null + } + val request = RawExposurePreviewRequest( + width = reference.width, + height = reference.height, + solve = { renderSample -> solve(reference, renderSample) }, + ) + return renderer.renderExposurePreviewSamples( + context = context, + input = input, + aspectRatio = aspectRatio, + cropRegion = cropRegion, + rotation = rotation, + request = request, + rawBlackPointCorrection = rawBlackPointCorrection, + rawWhitePointCorrection = rawWhitePointCorrection, + rawAutoWhiteBalanceEstimate = rawAutoWhiteBalanceEstimate, + applyLensShadingCorrection = applyLensShadingCorrection, + rawBlackBorderCrop = rawBlackBorderCrop, + ).also { exposureEv -> + PLog.i( + TAG, + "RAW_VIEWFINDER_BASELINE stage=METERING_COMPLETE curve=DEFAULT " + + "pgtm=false sourceBaselineEv=${input.metadata.baselineExposure} " + + "meteredExposureOffsetEv=$exposureEv" + ) + } + } + + private data class Reference( + val width: Int, + val height: Int, + val bounds: Rect, + val targetDisplayLuma: Float, + ) + + private data class Sample( + val exposureEv: Float, + val errorEv: Float, + val renderedDisplayLuma: Float, + ) + + private fun buildReference(bitmap: Bitmap): Reference? { + if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return null + return try { + val size = longEdgeSize(bitmap.width, bitmap.height, PREVIEW_LONG_EDGE) + val pixels = sampleBitmap(bitmap, size.width, size.height) + MeteringSystem.analyzeSrgbThumbnail(size.width, size.height, pixels) ?: return null + val bounds = centerTwoThirdsBounds(size.width, size.height) ?: return null + val targetLuma = averageDisplayLuma(pixels, size.width, size.height, bounds) ?: return null + Reference( + width = size.width, + height = size.height, + bounds = bounds, + targetDisplayLuma = targetLuma, + ) + } catch (e: Exception) { + PLog.e(TAG, "Failed to analyze capture preview", e) + null + } + } + + private fun solve( + reference: Reference, + renderSample: (Float) -> RawExposurePreviewFrame?, + ): Float? { + val zero = evaluate(reference, 0f, renderSample(0f)) ?: return null + if (abs(zero.errorEv) <= EV_TOLERANCE) return zero.exposureEv + + val samples = mutableListOf(zero) + var best = zero + var nextEv = exposureEvForSample(zero) + repeat(MAX_SOLVE_STEPS) { + val candidateEv = distinctCandidate(nextEv, samples) ?: return best.exposureEv + val sample = evaluate(reference, candidateEv, renderSample(candidateEv)) + ?: return best.exposureEv + samples += sample + if (abs(sample.errorEv) < abs(best.errorEv)) best = sample + if (abs(sample.errorEv) <= EV_TOLERANCE) return sample.exposureEv + nextEv = nextCandidate(samples, sample) + } + return best.exposureEv + } + + private fun evaluate( + reference: Reference, + exposureEv: Float, + frame: RawExposurePreviewFrame?, + ): Sample? { + if (frame == null || frame.width != reference.width || frame.height != reference.height) { + return null + } + MeteringSystem.analyzeSrgbThumbnail(frame.width, frame.height, frame.argbPixels) ?: return null + val renderedLuma = averageDisplayLuma( + frame.argbPixels, + frame.width, + frame.height, + reference.bounds, + ) ?: return null + val errorEv = displayLumaErrorEv(renderedLuma, reference.targetDisplayLuma) + PLog.d( + TAG, + "RAW viewfinder sample: exposureEv=$exposureEv errorEv=$errorEv " + + "targetLuma=${reference.targetDisplayLuma} renderedLuma=$renderedLuma" + ) + return Sample( + exposureEv = exposureEv, + errorEv = errorEv, + renderedDisplayLuma = renderedLuma, + ) + } + + private fun nextCandidate(samples: List, latest: Sample): Float { + bracketedCandidate(samples)?.let { return it } + val previous = samples.asReversed().firstOrNull { + it !== latest && abs(it.errorEv - latest.errorEv) > 0.0001f + } + return previous?.let { interpolatedExposureEv(it, latest) } + ?: exposureEvForSample(latest) + } + + private fun bracketedCandidate(samples: List): Float? { + val sorted = samples.sortedBy { it.exposureEv } + for (index in 0 until sorted.lastIndex) { + val lower = sorted[index] + val upper = sorted[index + 1] + val crossesTarget = + (lower.errorEv <= 0f && upper.errorEv >= 0f) || + (lower.errorEv >= 0f && upper.errorEv <= 0f) + if (!crossesTarget) continue + val interpolated = interpolatedExposureEv(lower, upper) + return if (interpolated != null && interpolated in lower.exposureEv..upper.exposureEv) { + interpolated + } else { + sanitizeExposureEv((lower.exposureEv + upper.exposureEv) * 0.5f) + } + } + return null + } + + private fun interpolatedExposureEv(a: Sample, b: Sample): Float? { + val errorDelta = b.errorEv - a.errorEv + if (!errorDelta.isFinite() || abs(errorDelta) <= 0.0001f) return null + return sanitizeExposureEv( + a.exposureEv - a.errorEv * (b.exposureEv - a.exposureEv) / errorDelta + ) + } + + private fun exposureEvForSample(sample: Sample): Float { + return sanitizeExposureEv(sample.exposureEv - sample.errorEv) ?: sample.exposureEv + } + + private fun distinctCandidate(candidateEv: Float, samples: List): Float? { + val safeEv = sanitizeExposureEv(candidateEv) ?: return null + return safeEv.takeUnless { candidate -> + samples.any { abs(it.exposureEv - candidate) < MIN_STEP_EV } + } + } + + private fun sanitizeExposureEv(value: Float): Float? { + return value.takeIf { it.isFinite() }?.coerceIn( + MeteringSystem.RAW_EXPOSURE_MIN_EV, + MeteringSystem.RAW_EXPOSURE_MAX_EV, + ) + } + + private data class Size(val width: Int, val height: Int) + + private fun longEdgeSize(sourceWidth: Int, sourceHeight: Int, maxLongEdge: Int): Size { + val longEdge = minOf(max(sourceWidth, sourceHeight), maxLongEdge.coerceAtLeast(1)) + return if (sourceWidth >= sourceHeight) { + Size( + width = longEdge, + height = (longEdge.toFloat() * sourceHeight / sourceWidth).toInt().coerceAtLeast(1), + ) + } else { + Size( + width = (longEdge.toFloat() * sourceWidth / sourceHeight).toInt().coerceAtLeast(1), + height = longEdge, + ) + } + } + + private fun sampleBitmap(bitmap: Bitmap, width: Int, height: Int): IntArray { + val pixels = IntArray(width * height) + val row = IntArray(bitmap.width) + for (y in 0 until height) { + val sourceY = ((y + 0.5f) * bitmap.height / height).toInt() + .coerceIn(0, bitmap.height - 1) + bitmap.getPixels(row, 0, bitmap.width, 0, sourceY, bitmap.width, 1) + for (x in 0 until width) { + val sourceX = ((x + 0.5f) * bitmap.width / width).toInt() + .coerceIn(0, bitmap.width - 1) + pixels[y * width + x] = row[sourceX] + } + } + return pixels + } + + private fun centerTwoThirdsBounds(width: Int, height: Int): Rect? { + if (width <= 0 || height <= 0) return null + val left = width / 6 + val top = height / 6 + return Rect( + left, + top, + (width * 5 / 6).coerceAtLeast(left + 1), + (height * 5 / 6).coerceAtLeast(top + 1), + ) + } + + private fun averageDisplayLuma( + pixels: IntArray, + width: Int, + height: Int, + bounds: Rect, + ): Float? { + if (pixels.size < width * height || bounds.isEmpty) return null + var sum = 0.0 + var count = 0 + for (y in bounds.top until bounds.bottom) { + for (x in bounds.left until bounds.right) { + val pixel = pixels[y * width + x] + val alpha = ((pixel ushr 24) and 0xff) / 255f + val r = ((pixel ushr 16) and 0xff) / 255f + val g = ((pixel ushr 8) and 0xff) / 255f + val b = (pixel and 0xff) / 255f + sum += ((0.2126f * r + 0.7152f * g + 0.0722f * b) * alpha).toDouble() + count++ + } + } + return if (count > 0) (sum / count).toFloat().coerceAtLeast(LUMA_FLOOR) else null + } + + private fun displayLumaErrorEv(renderedLuma: Float, targetLuma: Float): Float { + val rendered = renderedLuma.takeIf { it.isFinite() }?.coerceAtLeast(LUMA_FLOOR) ?: LUMA_FLOOR + val target = targetLuma.takeIf { it.isFinite() }?.coerceAtLeast(LUMA_FLOOR) ?: LUMA_FLOOR + return (ln(rendered.toDouble() / target.toDouble()) / ln(2.0)).toFloat() + } +} + +internal data class RawExposurePreviewRequest( + val width: Int, + val height: Int, + val solve: ((Float) -> RawExposurePreviewFrame?) -> Float?, +) diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt index 05e43c2b..6b6865f9 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt @@ -248,6 +248,7 @@ fun GalleryEditScreen( fun currentPreviewSignature(fast: Boolean = false): PreviewRenderSignature? { val photo = editSourcePhoto ?: return null + val rawDevelopIsBaked = isRaw return PreviewRenderSignature( photoId = photo.id, refreshKey = refreshKey, @@ -258,26 +259,26 @@ fun GalleryEditScreen( editLutConfig = editLutConfig, editFrameId = editFrameId, editFrameCustomProperties = editFrameCustomProperties.toMap(), - editSharpening = editSharpening, - editNoiseReduction = if (fast) 0f else editNoiseReduction, - editChromaNoiseReduction = if (fast) 0f else editChromaNoiseReduction, - editRawExposureCompensation = if (fast) 0f else editRawExposureCompensation, - editRawAutoExposure = if (fast) false else editRawAutoExposure, - editRawHighlightsAdjustment = if (fast) 0f else editRawHighlightsAdjustment, - editRawShadowsAdjustment = if (fast) 0f else editRawShadowsAdjustment, - editRawBlackPointCorrection = if (fast) 0f else editRawBlackPointCorrection, - editRawWhitePointCorrection = if (fast) 0f else editRawWhitePointCorrection, - editRawLensShadingCorrectionEnabled = if (fast) false else editRawLensShadingCorrectionEnabled, - editRawDROMode = if (fast) "" else editRawDROMode, - editRawBlackLevelMode = if (fast) "" else editRawBlackLevelMode, - editRawCustomBlackLevel = if (fast) 0f else editRawCustomBlackLevel, - editRawWhiteLevelMode = if (fast) "" else editRawWhiteLevelMode, - editRawCustomWhiteLevel = if (fast) 0f else editRawCustomWhiteLevel, - editRawCfaCorrectionMode = if (fast) "" else editRawCfaCorrectionMode, - editRawDcpId = if (fast) null else editRawDcpId, - editRawRenderingEngine = if (fast) "" else editRawColorEngine.name, - editRawBaselineLutId = editRawBaselineLutId, - editRawBaselineRecipeParams = editRawBaselineRecipeParams, + editSharpening = if (rawDevelopIsBaked) 0f else editSharpening, + editNoiseReduction = if (fast || rawDevelopIsBaked) 0f else editNoiseReduction, + editChromaNoiseReduction = if (fast || rawDevelopIsBaked) 0f else editChromaNoiseReduction, + editRawExposureCompensation = if (fast || rawDevelopIsBaked) 0f else editRawExposureCompensation, + editRawAutoExposure = if (fast || rawDevelopIsBaked) false else editRawAutoExposure, + editRawHighlightsAdjustment = if (fast || rawDevelopIsBaked) 0f else editRawHighlightsAdjustment, + editRawShadowsAdjustment = if (fast || rawDevelopIsBaked) 0f else editRawShadowsAdjustment, + editRawBlackPointCorrection = if (fast || rawDevelopIsBaked) 0f else editRawBlackPointCorrection, + editRawWhitePointCorrection = if (fast || rawDevelopIsBaked) 0f else editRawWhitePointCorrection, + editRawLensShadingCorrectionEnabled = if (fast || rawDevelopIsBaked) false else editRawLensShadingCorrectionEnabled, + editRawDROMode = if (fast || rawDevelopIsBaked) "" else editRawDROMode, + editRawBlackLevelMode = if (fast || rawDevelopIsBaked) "" else editRawBlackLevelMode, + editRawCustomBlackLevel = if (fast || rawDevelopIsBaked) 0f else editRawCustomBlackLevel, + editRawWhiteLevelMode = if (fast || rawDevelopIsBaked) "" else editRawWhiteLevelMode, + editRawCustomWhiteLevel = if (fast || rawDevelopIsBaked) 0f else editRawCustomWhiteLevel, + editRawCfaCorrectionMode = if (fast || rawDevelopIsBaked) "" else editRawCfaCorrectionMode, + editRawDcpId = if (fast || rawDevelopIsBaked) null else editRawDcpId, + editRawRenderingEngine = if (fast || rawDevelopIsBaked) "" else editRawColorEngine.name, + editRawBaselineLutId = editRawBaselineLutId.takeUnless { rawDevelopIsBaked }, + editRawBaselineRecipeParams = editRawBaselineRecipeParams.takeUnless { rawDevelopIsBaked }, editComputationalAperture = if (fast) 0f else editComputationalAperture, editFocusX = editFocusX, editFocusY = editFocusY, @@ -346,9 +347,11 @@ fun GalleryEditScreen( } } - LaunchedEffect(editSourcePhoto, refreshKey) { + LaunchedEffect(editSourcePhoto?.id, refreshKey, isRaw) { val photo = editSourcePhoto ?: return@LaunchedEffect - if (photo.isVideo) return@LaunchedEffect + // RAW decoding is already the expensive source load. Running the fast JPEG-style pass + // before the full pass decodes the same DNG twice for every refresh. + if (photo.isVideo || isRaw) return@LaunchedEffect snapshotFlow { currentPreviewSignature(true) } @@ -359,7 +362,7 @@ fun GalleryEditScreen( } } - LaunchedEffect(editSourcePhoto, refreshKey) { + LaunchedEffect(editSourcePhoto?.id, refreshKey) { val photo = editSourcePhoto ?: return@LaunchedEffect if (photo.isVideo) return@LaunchedEffect snapshotFlow { @@ -1112,7 +1115,9 @@ fun GalleryEditScreen( availableDcps = availableDcps, selectedBaselineLutId = editRawBaselineLutId, onSelectBaselineLut = { lutId -> - viewModel.saveRawBaselineLutSelection(currentEditSourcePhoto, lutId) + viewModel.saveRawBaselineLutSelection(currentEditSourcePhoto, lutId) { + requestRawPreviewRefresh() + } }, onEditBaselineRecipe = { lutId -> baselineLutEditId = lutId diff --git a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt index eeb58bc8..c356fb11 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -11,9 +11,14 @@ import android.util.Size import com.hinnka.mycamera.camera.AspectRatio import com.hinnka.mycamera.model.SafeImage import com.hinnka.mycamera.raw.DngProfileGainTableMap +import com.hinnka.mycamera.raw.DngBaselineExposure +import com.hinnka.mycamera.raw.DngProfileToneCurve import com.hinnka.mycamera.raw.RawCfaCorrection +import com.hinnka.mycamera.raw.RawDngProfilePreparationOptions import com.hinnka.mycamera.raw.RawMetadata import com.hinnka.mycamera.raw.RawDemosaicProcessor +import com.hinnka.mycamera.raw.RawProfileGainTableMapBuilder +import com.hinnka.mycamera.raw.RawProfileToneMapMode import com.hinnka.mycamera.raw.RawWhiteLevelCorrection import java.io.File import java.io.FileInputStream @@ -141,7 +146,7 @@ object RawProcessor { * @param outputStream 输出流 * @param rotation 旋转角度 (0, 90, 180, 270) */ - fun saveToDng( + suspend fun saveToDng( image: SafeImage, characteristics: CameraCharacteristics, captureResult: CaptureResult, @@ -155,6 +160,7 @@ object RawProcessor { cfaCorrectionMode: String? = null, effectiveFocalLengthMm: Float? = null, effectiveFocalLength35mm: Int? = null, + dngProfilePreparationOptions: RawDngProfilePreparationOptions? = null, ): Boolean { if (!isRawImage(image)) { throw IllegalArgumentException("Image is not RAW format: ${image.format}") @@ -174,6 +180,7 @@ object RawProcessor { cfaCorrectionMode = cfaCorrectionMode, effectiveFocalLengthMm = effectiveFocalLengthMm, effectiveFocalLength35mm = effectiveFocalLength35mm, + dngProfilePreparationOptions = dngProfilePreparationOptions, defaultCrop = resolveCameraRawDefaultCrop( width = image.width, height = image.height, @@ -229,7 +236,7 @@ object RawProcessor { private fun Rect.toRawCropRect(): RawCropRect = RawCropRect(left, top, right, bottom) - private fun saveRawImageToDngWithCustomWriter( + private suspend fun saveRawImageToDngWithCustomWriter( image: SafeImage, characteristics: CameraCharacteristics, captureResult: CaptureResult, @@ -243,6 +250,7 @@ object RawProcessor { cfaCorrectionMode: String?, effectiveFocalLengthMm: Float?, effectiveFocalLength35mm: Int?, + dngProfilePreparationOptions: RawDngProfilePreparationOptions?, defaultCrop: Rect, ): Boolean { if (image.format != ImageFormat.RAW_SENSOR) { @@ -280,6 +288,7 @@ object RawProcessor { cfaCorrectionMode = cfaCorrectionMode, effectiveFocalLengthMm = effectiveFocalLengthMm, effectiveFocalLength35mm = effectiveFocalLength35mm, + dngProfilePreparationOptions = dngProfilePreparationOptions, defaultCrop = defaultCrop, ) } @@ -314,7 +323,7 @@ object RawProcessor { return output } - fun saveRawBufferToDng( + suspend fun saveRawBufferToDng( rawBuffer: ByteBuffer, width: Int, height: Int, @@ -344,14 +353,17 @@ object RawProcessor { compression: SuperResolutionDngWriter.Compression = SuperResolutionDngWriter.Compression.UNCOMPRESSED, inputRowStepSamples: Int? = null, inputColStepSamples: Int? = null, + dngProfilePreparationOptions: RawDngProfilePreparationOptions? = null, defaultCrop: Rect, ): Boolean { val resolvedCfaPattern = resolveCfaPatternForMode(cfaPattern, cfaCorrectionMode) + val resolvedBlackLevel = resolveBlackLevelForMode(blackLevel, blackLevelMode, customBlackLevel) val resolvedWhiteLevel = resolveWhiteLevelForMode(whiteLevel.toFloat(), whiteLevelMode, customWhiteLevel).toInt() val hasCfaOverride = RawCfaCorrection.isOverrideMode(cfaCorrectionMode) val hasWhiteLevelOverride = RawWhiteLevelCorrection.isOverrideMode(whiteLevelMode) val requiresCustomWriter = imageLayout != SuperResolutionDngWriter.ImageLayout.CFA || - compression != SuperResolutionDngWriter.Compression.UNCOMPRESSED + compression != SuperResolutionDngWriter.Compression.UNCOMPRESSED || + dngProfilePreparationOptions != null if (hasCfaOverride && resolvedCfaPattern != cfaPattern) { PLog.d(TAG, "RAW DNG CFA override mode=$cfaCorrectionMode cfa=$cfaPattern->$resolvedCfaPattern") } @@ -359,6 +371,101 @@ object RawProcessor { PLog.d(TAG, "RAW DNG white level override mode=$whiteLevelMode white=$whiteLevel->$resolvedWhiteLevel") } + val sourceBaselineExposureEv = DngBaselineExposure.sanitize( + baselineExposureEv ?: captureResult + .get(CaptureResult.CONTROL_POST_RAW_SENSITIVITY_BOOST) + ?.takeIf { it > 0 } + ?.let { kotlin.math.log2(it / 100.0).toFloat() } + ?: 0f + ) + val preparedProfile = dngProfilePreparationOptions?.let { options -> + val inputSamplesPerPixel = inputColStepSamples ?: imageLayout.samplesPerPixel + val inputRowStrideBytes = (inputRowStepSamples + ?: width * inputSamplesPerPixel) * Short.SIZE_BYTES + val statsBlackLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) { + FloatArray(if (inputSamplesPerPixel >= 3) 3 else 4) + } else { + resolvedBlackLevel + } + val statsWhiteLevel = if (valueDomain == RawBufferValueDomain.NORMALIZED_SENSOR_RANGE) { + 65535f + } else { + resolvedWhiteLevel.toFloat() + } + val statsMetadata = RawMetadata.create( + width = width, + height = height, + characteristics = characteristics, + captureResult = captureMetadataResult ?: captureResult, + ).copy( + width = width, + height = height, + cfaPattern = resolvedCfaPattern, + blackLevel = statsBlackLevel, + whiteLevel = statsWhiteLevel, + baselineExposure = sourceBaselineExposureEv, + defaultCrop = defaultCrop, + ) + val exposureOffsetEv = options.viewfinderExposureMatcher?.match( + com.hinnka.mycamera.raw.RawDngViewfinderMatchInput( + rawData = rawBuffer.duplicate().order(ByteOrder.nativeOrder()), + width = width, + height = height, + rowStride = inputRowStrideBytes, + samplesPerPixel = inputSamplesPerPixel, + metadata = statsMetadata.copy(profileGainTableMap = null), + ) + )?.takeIf { it.isFinite() } + ?.coerceIn( + com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MIN_EV, + com.hinnka.mycamera.raw.MeteringSystem.RAW_EXPOSURE_MAX_EV, + ) + val finalBaselineExposureEv = DngBaselineExposure.sanitize( + sourceBaselineExposureEv + (exposureOffsetEv ?: 0f) + ) + val finalProfile = RawProfileGainTableMapBuilder.prepareForDngWrite( + rawData = rawBuffer, + width = width, + height = height, + rowStride = inputRowStrideBytes, + metadata = statsMetadata.copy(baselineExposure = finalBaselineExposureEv), + samplesPerPixel = inputSamplesPerPixel, + options = options, + ) ?: return false + PLog.i( + TAG, + "RAW_VIEWFINDER_BASELINE stage=DNG_WRITE_READY " + + "enabled=${options.viewfinderExposureMatcher != null} " + + "matched=${exposureOffsetEv != null} " + + "sourceBaselineEv=$sourceBaselineExposureEv " + + "sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " + + "meteredExposureOffsetEv=${exposureOffsetEv ?: 0f} " + + "meteredExposureGain=${DngBaselineExposure.exactGain(exposureOffsetEv ?: 0f)} " + + "writtenBaselineEv=${finalProfile.baselineExposureEv} " + + "writtenBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " + + "pgtm=${finalProfile.profileGainTableMap != null} " + + "mode=${options.profileToneMapMode} statsBounds=${options.statsBounds}" + ) + finalProfile + } + val writtenBaselineExposureEv = preparedProfile?.baselineExposureEv ?: baselineExposureEv + val writtenProfileGainTableMap = if (dngProfilePreparationOptions != null) { + preparedProfile?.profileGainTableMap + } else { + profileGainTableMap + } + val preparedToneMapMode = dngProfilePreparationOptions?.profileToneMapMode + ?.takeIf { writtenProfileGainTableMap != null } + val writtenProfileName = if (dngProfilePreparationOptions != null) { + preparedToneMapMode?.let(::profileNameForToneMapMode) + } else { + profileName + } + val writtenProfileToneCurve = if (dngProfilePreparationOptions != null) { + preparedToneMapMode?.let(::profileToneCurveForToneMapMode) + } else { + profileToneCurve + } val orientation = when (rotation) { 90 -> ExifInterface.ORIENTATION_ROTATE_90 180 -> ExifInterface.ORIENTATION_ROTATE_180 @@ -386,10 +493,10 @@ object RawProcessor { customBlackLevel = customBlackLevel, whiteLevelMode = whiteLevelMode, customWhiteLevel = customWhiteLevel, - baselineExposureEv = baselineExposureEv, - profileGainTableMap = profileGainTableMap, - profileName = profileName, - profileToneCurve = profileToneCurve, + baselineExposureEv = writtenBaselineExposureEv, + profileGainTableMap = writtenProfileGainTableMap, + profileName = writtenProfileName, + profileToneCurve = writtenProfileToneCurve, imageLayout = imageLayout, compression = compression, inputRowStepSamples = inputRowStepSamples, @@ -428,6 +535,16 @@ object RawProcessor { } } + private fun profileNameForToneMapMode(mode: RawProfileToneMapMode): String = when (mode) { + RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME + else -> DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME + } + + private fun profileToneCurveForToneMapMode(mode: RawProfileToneMapMode): FloatArray = when (mode) { + RawProfileToneMapMode.Photon -> DngProfileToneCurve.photonPgtmToneCurvePoints() + else -> DngProfileToneCurve.googleHdrToneCurvePoints() + } + internal fun denormalizeNormalizedRawBufferInPlace( rawBuffer: ByteBuffer, width: Int, diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index df12f9c7..a3881241 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -2271,7 +2271,6 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) if (_latestPhoto.value?.id == mediaData.id) { _latestPhoto.value = _latestPhoto.value?.copy(metadata = updated) } - photoRefreshKeys[mediaData.id] = System.currentTimeMillis() } onComplete?.invoke(updated != null) } diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriterTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriterTest.kt deleted file mode 100644 index 2a98e210..00000000 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngPgtmDebugRewriterTest.kt +++ /dev/null @@ -1,160 +0,0 @@ -package com.hinnka.mycamera.raw - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test -import java.io.ByteArrayOutputStream -import java.io.File -import java.nio.ByteBuffer -import java.nio.ByteOrder - -class DngPgtmDebugRewriterTest { - @Test - fun rewriteProfileGainTableMapAddsAnonymousLookAndVersion2Map() { - val file = File.createTempFile("pgtm-debug-rewrite", ".dng") - try { - file.writeBytes(minimalClassicDng()) - assertTrue(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 in readRawIfd(file)) - val map = DngProfileGainTableMap( - mapPointsV = 1, - mapPointsH = 1, - mapSpacingV = 1.0, - mapSpacingH = 1.0, - mapOriginV = 0.0, - mapOriginH = 0.0, - mapPointsN = 257, - mapInputWeights = floatArrayOf(0.10f, 0.20f, 0.05f, 0.15f, 0.50f), - gamma = 0.5f, - gains = FloatArray(257) { index -> - 1.75f + (0.72f - 1.75f) * index.toFloat() / 256f - } - ) - - assertTrue(DngPgtmDebugRewriter.rewriteProfileGainTableMap(file, map)) - - val decoded = DngProfileGainTableMap.readFrom(file) - assertTrue(decoded?.isValid == true) - assertEquals(map.mapPointsH, decoded?.mapPointsH) - assertEquals(map.mapPointsV, decoded?.mapPointsV) - assertEquals(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2, decoded?.sourceTag) - assertEquals(map.gamma, decoded?.gamma ?: 0f, 0f) - assertEquals(257, decoded?.mapPointsN) - assertEquals(map.gains[0], decoded?.gains?.get(0) ?: 0f, 0f) - val ifd0 = readIfd0(file) - val rawIfd = readRawIfd(file) - assertFalse(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP in ifd0) - assertTrue(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 in ifd0) - assertFalse(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP in rawIfd) - assertFalse(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2 in rawIfd) - assertTrue(ifd0[50706]?.inlineOrOffset?.contentEquals(byteArrayOf(1, 7, 0, 0)) == true) - val cameraRawXmp = readEntryBytes(file, ifd0.getValue(700)).toString(Charsets.UTF_8) - assertTrue(cameraRawXmp.contains("")) - assertTrue(cameraRawXmp.contains("crs:ProfileGainTableMap=\"100\"")) - assertTrue(cameraRawXmp.contains("crs:ProfileToneCurve=\"100\"")) - assertTrue(cameraRawXmp.contains("crs:Name=\"Photon HDR\"")) - assertFalse(cameraRawXmp.contains("crs:CameraProfile=")) - assertFalse(ifd0.containsKey(50936)) - assertEquals(514, ifd0.getValue(50940).count) - assertEquals( - 1, - ifd0.getValue(51110).inlineOrOffset - .let { ByteBuffer.wrap(it).order(ByteOrder.LITTLE_ENDIAN).int }, - ) - assertTrue(DngEmbeddedProfile.hasPhotonPgtmProfile(file)) - } finally { - file.delete() - } - } - - private fun readIfd0(file: File): Map { - val bytes = file.readBytes() - val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) - val ifdOffset = buffer.getInt(4) - return readIfd(buffer, ifdOffset) - } - - private fun readRawIfd(file: File): Map { - val bytes = file.readBytes() - val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN) - val ifd0 = readIfd(buffer, buffer.getInt(4)) - val rawIfdOffset = ifd0.getValue(330).inlineOrOffset - .let { ByteBuffer.wrap(it).order(ByteOrder.LITTLE_ENDIAN).int } - return readIfd(buffer, rawIfdOffset) - } - - private fun readIfd(buffer: ByteBuffer, ifdOffset: Int): Map { - buffer.position(ifdOffset) - val count = buffer.short.toInt() and 0xFFFF - return buildMap(count) { - repeat(count) { - val tag = buffer.short.toInt() and 0xFFFF - val type = buffer.short.toInt() and 0xFFFF - val valueCount = buffer.int.toLong() and 0xFFFF_FFFFL - val inlineOrOffset = ByteArray(4).also(buffer::get) - put(tag, TestEntry(type, valueCount, inlineOrOffset)) - } - } - } - - private fun readEntryBytes(file: File, entry: TestEntry): ByteArray { - val bytes = file.readBytes() - val byteCount = entry.count.toInt() - if (byteCount <= 4) return entry.inlineOrOffset.copyOf(byteCount) - val offset = ByteBuffer.wrap(entry.inlineOrOffset) - .order(ByteOrder.LITTLE_ENDIAN) - .int - return bytes.copyOfRange(offset, offset + byteCount) - } - - private fun minimalClassicDng(): ByteArray { - val byteOrder = ByteOrder.LITTLE_ENDIAN - val rawIfdOffset = 8 + 2 + 2 * 12 + 4 - return ByteArrayOutputStream().apply { - write(byteArrayOf('I'.code.toByte(), 'I'.code.toByte())) - writeUShort(42, byteOrder) - writeUInt(8, byteOrder) - writeUShort(2, byteOrder) - writeUShort(50706, byteOrder) - writeUShort(1, byteOrder) - writeUInt(4, byteOrder) - write(byteArrayOf(1, 4, 0, 0)) - writeUShort(330, byteOrder) - writeUShort(4, byteOrder) - writeUInt(1, byteOrder) - writeUInt(rawIfdOffset.toLong(), byteOrder) - writeUInt(0, byteOrder) - - writeUShort(2, byteOrder) - writeUShort(254, byteOrder) - writeUShort(4, byteOrder) - writeUInt(1, byteOrder) - writeUInt(0, byteOrder) - writeUShort(DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2, byteOrder) - writeUShort(7, byteOrder) - writeUInt(1, byteOrder) - write(byteArrayOf(0, 0, 0, 0)) - writeUInt(0, byteOrder) - }.toByteArray() - } - - private fun ByteArrayOutputStream.writeUShort(value: Int, byteOrder: ByteOrder) { - write(ByteBuffer.allocate(2).order(byteOrder).putShort((value and 0xFFFF).toShort()).array()) - } - - private fun ByteArrayOutputStream.writeUInt(value: Long, byteOrder: ByteOrder) { - write( - ByteBuffer - .allocate(4) - .order(byteOrder) - .putInt((value and 0xFFFF_FFFFL).toInt()) - .array() - ) - } - - private data class TestEntry( - val type: Int, - val count: Long, - val inlineOrOffset: ByteArray, - ) -} diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt deleted file mode 100644 index 4944ed6b..00000000 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGeneratorTest.kt +++ /dev/null @@ -1,590 +0,0 @@ -package com.hinnka.mycamera.raw - -import org.junit.Assert.assertArrayEquals -import org.junit.Assert.assertEquals -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test -import kotlin.math.abs -import kotlin.math.floor -import kotlin.math.ln -import kotlin.math.max -import kotlin.math.pow - -class DngPhotonProfileGainTableGeneratorTest { - @Test - fun photonKeepsGoogleDomainWhileAdaptingItsSceneBrightness() { - val fixture = uniformFixture( - p10 = 0.015f, - p50 = 0.08f, - p90 = 0.55f, - p98 = 0.80f, - p995 = 1.058f, - p999 = 1.15f, - ) - val photon = generatePhotonMap(fixture) - val directGoogle = DngHdrProfileGainTableGenerator.forCellStats( - width = fixture.width, - height = fixture.height, - baselineExposureEv = fixture.baselineExposureEv, - packedCellStats = fixture.packedStats, - fusionParameters = DngPhotonProfileGainTableGenerator.PHOTON_FUSION_PARAMETERS, - ) ?: error("Expected direct Google PGTM") - - assertEquals(directGoogle.gamma, photon.gamma, 0f) - assertArrayEquals(directGoogle.mapInputWeights, photon.mapInputWeights, 0f) - assertTrue( - "Brightness target must change the fusion curve", - !directGoogle.gains.contentEquals(photon.gains), - ) - val target = PhotonPgtmBrightnessModel.resolve(fixture.globalStats) - ?: error("Expected Photon brightness target") - val actual = finalPhotonOutputForScene(photon, target.sceneAnchor) - assertEquals(target.displayTarget, actual, 0.004f) - } - - @Test - fun photonKeepsGoogleDomainAndWhiteEndpoint() { - val fixture = uniformFixture( - baselineExposureEv = 3.000001f, - p10 = 0.008017952f, - p50 = 0.06326936f, - p90 = 1f, - p98 = 1f, - p995 = 12.278543f, - p999 = 14.262961f, - highlightFraction = 0.13241959f, - ) - val photon = generatePhotonMap(fixture) - val google = DngHdrProfileGainTableGenerator.forCellStats( - width = fixture.width, - height = fixture.height, - baselineExposureEv = fixture.baselineExposureEv, - packedCellStats = fixture.packedStats, - ) ?: error("Expected Google PGTM") - - assertEquals(google.gamma, photon.gamma, 0f) - assertArrayEquals(google.mapInputWeights, photon.mapInputWeights, 0f) - val inputScale = photon.mapInputWeights.sum() - val sceneWhite = 1f / inputScale - repeat(photon.mapPointsH * photon.mapPointsV) { cell -> - val photonTerminalGain = photon.gains[(cell + 1) * photon.mapPointsN - 1] - val googleTerminalGain = google.gains[(cell + 1) * google.mapPointsN - 1] - assertEquals(googleTerminalGain, photonTerminalGain, 1e-6f) - assertEquals(1f, sceneWhite * photonTerminalGain, 2e-4f) - } - assertCurvesAreFiniteAndMonotonic(photon, sceneWhite) - } - - @Test - fun centeredFusionHitsPre3e320SceneBrightnessTargets() { - val cases = historicalBrightnessCases() - val results = cases.map { case -> - val fixture = uniformFixture( - baselineExposureEv = case.baselineExposureEv, - p10 = case.p10, - p50 = case.p50, - p90 = case.p90, - p98 = case.p98, - p995 = case.p995, - p999 = case.p999, - highlightFraction = case.highlightFraction, - maxInput = case.maxInput, - linearMean = case.linearMean, - logAverage = case.logAverage, - ) - val map = generatePhotonMap(fixture) - val target = PhotonPgtmBrightnessModel.resolve(fixture.globalStats) - ?: error("Expected target for ${case.name}") - val actual = finalPhotonOutputForScene(map, target.sceneAnchor) - val errorEv = abs(log2(actual / target.displayTarget)) - HistoricalBrightnessResult( - case = case, - targetDisplayAnchor = target.displayTarget, - actualDisplayAnchor = actual, - errorEv = errorEv, - ) - } - assertTrue( - results.joinToString(separator = "\n") { result -> - "${result.case.name}: expected=${result.targetDisplayAnchor} " + - "actual=${result.actualDisplayAnchor} errorEv=${result.errorEv}" - }, - results.all { it.errorEv <= 0.04f }, - ) - } - - @Test - fun pre3e320WideFieldUsesHistoricalLogAverageLift() { - val stats = testGlobalStats( - p10 = 0.0046890248f, - p50 = 0.035560552f, - p90 = 0.35547075f, - p98 = 0.4203099f, - p995 = 0.44679728f, - p999 = 0.46304873f, - maxInput = 0.5280757f, - linearMean = 0.114991106f, - logAverage = 0.039605092f, - highlightFraction = 0f, - ) - val target = PhotonPgtmBrightnessModel.resolve(stats) ?: error("Expected target") - - assertEquals( - PhotonPgtmBrightnessAnchorSource.LOG_AVERAGE, - target.anchorSource, - ) - assertEquals(2.24f, target.exposureLiftEv, 1e-5f) - assertEquals(0.039605092f * 2.0f.pow(2.24f), target.displayTarget, 1e-5f) - assertEquals(9f, target.dynamicRangeEv, 0f) - } - - @Test - fun sparseHighlightsUseTheMainHighlightPopulationForExposure() { - val ranges = PhotonPgtmBrightnessModel.highlightRanges( - p90 = 0.20524885f, - p98 = 0.45892385f, - p995 = 0.5724387f, - p999 = 0.6364626f, - sceneMiddle = 0.09018845f, - ) - val tailLift = PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.tailRangeEv) - val exposureLift = PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.exposureRangeEv) - - assertTrue(ranges.tailRangeEv in 2.81f..2.83f) - assertTrue(ranges.exposureRangeEv in 1.18f..1.20f) - assertEquals(0.20524885f, ranges.exposureReference, 1e-6f) - assertEquals(1f, ranges.sparseStrength, 0f) - assertTrue(exposureLift - tailLift in -1.39f..-1.37f) - } - - @Test - fun separatedHighlightScenesDoNotRaiseTheWholeFrameExposure() { - val saturatedTarget = PhotonPgtmBrightnessModel.resolve( - testGlobalStats( - p10 = 0.01f, - p50 = 0.064226665f, - p90 = 2.1271088f, - p98 = 3.989237f, - p995 = 5f, - p999 = 6.0202312f, - logAverage = 0.07215811f, - ) - ) ?: error("Expected saturated sparse-highlight target") - val separatedTarget = PhotonPgtmBrightnessModel.resolve( - testGlobalStats( - p10 = 0.01f, - p50 = 0.0600047f, - p90 = 0.21020813f, - p98 = 0.88294554f, - p995 = 0.94f, - p999 = 0.9819474f, - logAverage = 0.06115667f, - ) - ) ?: error("Expected separated sparse-highlight target") - - assertEquals(0.26f, saturatedTarget.displayTarget, 0f) - assertTrue(separatedTarget.exposureRangeEv in 1.77f..1.79f) - assertTrue(separatedTarget.displayTarget < 0.08f) - } - - @Test - fun pre3e320DngPairRetainsItsMeasuredBrightnessRelationship() { - fun displayEv( - logAverage: Float, - p90: Float, - p98: Float, - p995: Float, - p999: Float, - ): Float { - val ranges = PhotonPgtmBrightnessModel.highlightRanges( - p90 = p90, - p98 = p98, - p995 = p995, - p999 = p999, - sceneMiddle = logAverage, - ) - return log2(logAverage) + - PhotonPgtmBrightnessModel.displayExposureLiftEv(ranges.exposureRangeEv) - } - - val dng2840DisplayEv = displayEv( - logAverage = 0.0932018935f, - p90 = 0.263932749f, - p98 = 0.3304134763f, - p995 = 0.3685588609f, - p999 = 0.3981607637f, - ) - val dng2842DisplayEv = displayEv( - logAverage = 0.07615876645f, - p90 = 0.2486532208f, - p98 = 0.2975876967f, - p995 = 0.3287509693f, - p999 = 0.3566421426f, - ) - - assertTrue(abs(dng2842DisplayEv - dng2840DisplayEv) <= 0.12f) - } - - @Test - fun missingLogAverageFallsBackToP50WithoutChangingTheModel() { - val target = PhotonPgtmBrightnessModel.resolve( - testGlobalStats( - p10 = 0.035187688f, - p50 = 0.08524494f, - p90 = 0.14404307f, - p98 = 0.16417652f, - p995 = 0.17360601f, - p999 = 0.18164334f, - maxInput = 0.20776238f, - logAverage = Float.NaN, - ) - ) ?: error("Expected P50 fallback") - - assertEquals(PhotonPgtmBrightnessAnchorSource.P50_FALLBACK, target.anchorSource) - assertEquals(0.08524494f, target.sceneAnchor, 0f) - } - - @Test - fun pre3e320ExtendedHdrShoulderKeepsSeparationNearWhite() { - val map = generatePhotonMap(fixtureFor(dynamicRangeTiers().last())) - val sceneWhite = 1f / map.mapInputWeights.sum() - val output85 = finalPhotonOutputForScene(map, sceneWhite * 0.85f) - val output95 = finalPhotonOutputForScene(map, sceneWhite * 0.95f) - val output100 = finalPhotonOutputForScene(map, sceneWhite) - val lowerHighlightSpan = output95 - output85 - val endpointSpan = output100 - output95 - - assertTrue( - "output85=$output85 output95=$output95 output100=$output100", - endpointSpan > 0.008f, - ) - assertTrue( - "lowerHighlightSpan=$lowerHighlightSpan endpointSpan=$endpointSpan", - endpointSpan > lowerHighlightSpan * 0.30f, - ) - } - - @Test - fun adaptiveBrightnessKeepsAnIntrinsicToeAndShoulder() { - historicalBrightnessCases().forEach { case -> - val fixture = uniformFixture( - baselineExposureEv = case.baselineExposureEv, - p10 = case.p10, - p50 = case.p50, - p90 = case.p90, - p98 = case.p98, - p995 = case.p995, - p999 = case.p999, - highlightFraction = case.highlightFraction, - maxInput = case.maxInput, - linearMean = case.linearMean, - logAverage = case.logAverage, - ) - val map = generatePhotonMap(fixture) - val sceneWhite = 1f / map.mapInputWeights.sum() - val shadowSpanEv = log2( - finalPhotonOutputForScene(map, sceneWhite / 16f) / - finalPhotonOutputForScene(map, sceneWhite / 64f) - ) - val output85 = finalPhotonOutputForScene(map, sceneWhite * 0.85f) - val output95 = finalPhotonOutputForScene(map, sceneWhite * 0.95f) - val output100 = finalPhotonOutputForScene(map, sceneWhite) - assertTrue( - "${case.name}: shadowSpanEv=$shadowSpanEv", - shadowSpanEv >= 0.8f, - ) - assertTrue( - "${case.name}: output85=$output85 output95=$output95 output100=$output100", - output85 < output95 && output95 < output100, - ) - assertCurvesAreFiniteAndMonotonic(map, sceneWhite) - } - } - - @Test - fun invalidInputStillUsesGoogleValidation() { - assertNull( - DngPhotonProfileGainTableGenerator.forCellStats( - width = 0, - height = 480, - baselineExposureEv = 0f, - packedCellStats = FloatArray(0), - globalStats = testGlobalStats(0.1f), - emitDiagnostics = false, - ) - ) - } - - private fun generatePhotonMap(fixture: UniformFixture): DngProfileGainTableMap { - return DngPhotonProfileGainTableGenerator.forCellStats( - width = fixture.width, - height = fixture.height, - baselineExposureEv = fixture.baselineExposureEv, - packedCellStats = fixture.packedStats, - globalStats = fixture.globalStats, - emitDiagnostics = false, - ) ?: error("Expected Photon PGTM") - } - - // Fixtures recovered from 3e320e229^, before Photon was replaced by fixed fusion parameters. - private fun historicalBrightnessCases(): List = listOf( - HistoricalBrightnessCase( - "14:22 baseline-0 wide", - 0f, - 0.0046890248f, - 0.035560552f, - 0.35547075f, - 0.4203099f, - 0.44679728f, - 0.46304873f, - 0.5280757f, - 0.114991106f, - 0.039605092f, - 0f, - ), - HistoricalBrightnessCase( - "18:53 baseline-3 sparse-tail", - 3f, - 0.022204947f, - 0.13993193f, - 0.21021318f, - 0.24911182f, - 0.27169982f, - 0.5752382f, - 1.249979f, - 0.1295324f, - 0.09985464f, - 6.739298E-5f, - ), - HistoricalBrightnessCase( - "18:54 baseline-3 low-range", - 3f, - 0.045957692f, - 0.08537395f, - 0.13890508f, - 0.18092623f, - 0.2126976f, - 0.2313348f, - 0.27256522f, - 0.08850919f, - 0.07818398f, - 0f, - ), - ) - - private fun dynamicRangeTiers(): List = listOf( - DynamicRangeTier(0.10f, 0.15f, 0.40f, 0.60f, 0.75f, 8f), - DynamicRangeTier(0.020f, 0.10f, 0.50f, 0.75f, 1.05f, 8.5f), - DynamicRangeTier(0.015f, 0.08f, 0.55f, 0.80f, 1.15f, 9f), - DynamicRangeTier(0.012f, 0.07f, 0.55f, 0.85f, 1.20f, 9.5f), - ) - - private fun fixtureFor(tier: DynamicRangeTier): UniformFixture { - return uniformFixture( - p10 = tier.p10, - p50 = tier.p50, - p90 = tier.p90, - p98 = tier.p98, - p995 = tier.p999 * 0.92f, - p999 = tier.p999, - highlightFraction = 0f, - maxInput = tier.p999, - logAverage = tier.p50, - ) - } - - private fun uniformFixture( - baselineExposureEv: Float = 0f, - p10: Float, - p50: Float, - p90: Float, - p98: Float, - p995: Float, - p999: Float, - highlightFraction: Float = 0.02f, - maxInput: Float = p999, - linearMean: Float = p50, - logAverage: Float = p50, - ): UniformFixture { - val width = 640 - val height = 480 - val grid = DngHdrProfileGainTableGenerator.gridSizeFor(width, height) - val cellCount = grid[0] * grid[1] - val packedStats = FloatArray( - cellCount * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - ) - repeat(cellCount) { cell -> - val offset = cell * DngHdrProfileGainTableGenerator.CELL_STATS_FLOAT_STRIDE - packedStats[offset] = p10 - packedStats[offset + 1] = p50 - packedStats[offset + 2] = p90 - packedStats[offset + 3] = p98 - packedStats[offset + 4] = highlightFraction - packedStats[offset + 5] = 64f - packedStats[offset + 6] = p995 - packedStats[offset + 7] = p999 - } - return UniformFixture( - width = width, - height = height, - baselineExposureEv = baselineExposureEv, - packedStats = packedStats, - globalStats = testGlobalStats( - p50 = p50, - p10 = p10, - p90 = p90, - p98 = p98, - p995 = p995, - p999 = p999, - maxInput = maxInput, - highlightFraction = highlightFraction, - linearMean = linearMean, - logAverage = logAverage, - ), - ) - } - - private fun testGlobalStats( - p50: Float, - p10: Float = p50, - p90: Float = p50, - p98: Float = p90, - p995: Float = p98, - p999: Float = p995, - maxInput: Float = p999, - highlightFraction: Float = 0f, - linearMean: Float = p50, - logAverage: Float = p50, - ): DngPgtmGlobalStats { - return DngPgtmGlobalStats( - p10 = p10, - p50 = p50, - p90 = p90, - p98 = p98, - p995 = p995, - p999 = p999, - maxInput = maxInput, - highlightFraction = highlightFraction, - linearMean = linearMean, - logAverage = logAverage, - shadowEdge = p10, - shadowFoot = p10, - sampleCount = 256, - ) - } - - private fun finalPhotonOutputForScene( - map: DngProfileGainTableMap, - sceneLinear: Float, - ): Float { - val inputScale = map.mapInputWeights.sum() - val tableInput = (sceneLinear * inputScale).coerceIn(0f, 1f).pow(map.gamma) - val pgtmOutput = sceneLinear * medianGain(map, tableInput) - return samplePhotonProfileCurve(pgtmOutput) - } - - private fun samplePhotonProfileCurve(input: Float): Float { - val points = DngProfileToneCurve.photonPgtmToneCurvePoints() - var index = 0 - while (index + 3 < points.size) { - val x0 = points[index] - val y0 = points[index + 1] - val x1 = points[index + 2] - val y1 = points[index + 3] - if (input <= x1) { - val amount = ((input - x0) / (x1 - x0)).coerceIn(0f, 1f) - return y0 + (y1 - y0) * amount - } - index += 2 - } - return points.last() - } - - private fun medianGain(map: DngProfileGainTableMap, tableInput: Float): Float { - val values = FloatArray(map.mapPointsH * map.mapPointsV) { cell -> - gainForCell(map, cell, tableInput) - } - values.sort() - return values[values.size / 2] - } - - private fun gainForCell(map: DngProfileGainTableMap, cell: Int, tableInput: Float): Float { - val position = tableInput.coerceIn(0f, 1f) * map.mapPointsN - val lower = floor(position).toInt().coerceIn(0, map.mapPointsN - 1) - val upper = (lower + 1).coerceAtMost(map.mapPointsN - 1) - val fraction = position - lower - val offset = cell * map.mapPointsN - return map.gains[offset + lower] * (1f - fraction) + - map.gains[offset + upper] * fraction - } - - private fun assertCurvesAreFiniteAndMonotonic( - map: DngProfileGainTableMap, - sceneWhite: Float, - ) { - repeat(map.mapPointsH * map.mapPointsV) { cell -> - var previousOutput = 0f - repeat(map.mapPointsN) { index -> - val tableInput = if (index == map.mapPointsN - 1) { - 1f - } else { - index.toFloat() / map.mapPointsN.toFloat() - } - val sceneLinear = sceneWhite * tableInput.pow(1f / map.gamma) - val gain = map.gains[cell * map.mapPointsN + index] - val output = sceneLinear * gain - assertTrue("cell=$cell index=$index gain=$gain", gain.isFinite() && gain >= 0.05f) - assertTrue( - "cell=$cell index=$index previous=$previousOutput output=$output", - output + 1e-5f >= previousOutput, - ) - previousOutput = max(previousOutput, output) - } - } - } - - private fun log2(value: Float): Float { - return (ln(value.toDouble()) / ln(2.0)).toFloat() - } - - private data class UniformFixture( - val width: Int, - val height: Int, - val baselineExposureEv: Float, - val packedStats: FloatArray, - val globalStats: DngPgtmGlobalStats, - ) - - private data class HistoricalBrightnessCase( - val name: String, - val baselineExposureEv: Float, - val p10: Float, - val p50: Float, - val p90: Float, - val p98: Float, - val p995: Float, - val p999: Float, - val maxInput: Float, - val linearMean: Float, - val logAverage: Float, - val highlightFraction: Float, - ) - - private data class HistoricalBrightnessResult( - val case: HistoricalBrightnessCase, - val targetDisplayAnchor: Float, - val actualDisplayAnchor: Float, - val errorEv: Float, - ) - - private data class DynamicRangeTier( - val p10: Float, - val p50: Float, - val p90: Float, - val p98: Float, - val p999: Float, - val dynamicRangeEv: Float, - ) - -}