feat: new auto exposure
This commit is contained in:
1 parent
01f4d8f353
commit
5229ae5bfd
27 files changed
+1052
-3259
No files matched your search
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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?,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<TiffValue>,
|
||||
removedTags: Set<Int> = emptySet(),
|
||||
byteOrder: ByteOrder,
|
||||
): Long? {
|
||||
if (replacements.isEmpty() && removedTags.isEmpty()) return null
|
||||
val replacementByTag = replacements.associateBy { it.tag }
|
||||
val merged = LinkedHashMap<Int, IfdValue>()
|
||||
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<TiffEntry>(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<TiffEntry>,
|
||||
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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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?,
|
||||
)
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
),
|
||||
;
|
||||
|
||||
@@ -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<Sample>, 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<Sample>): 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<Sample>): 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?,
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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("<crs:Look>"))
|
||||
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<Int, TestEntry> {
|
||||
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<Int, TestEntry> {
|
||||
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<Int, TestEntry> {
|
||||
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,
|
||||
)
|
||||
}
|
||||
@@ -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<HistoricalBrightnessCase> = 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<DynamicRangeTier> = 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,
|
||||
)
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user