fix: phantom raw

This commit is contained in:
zhoubinjia committed 2026-07-10 16:34:32 +08:00
1 parent 8623842830
commit 1c466821c6
5 files changed
+117 -48

No files matched your search

+35 -17
View File
@@ -174,17 +174,44 @@ static jobject decodeJpegPreviewToBitmap(JNIEnv *env, const unsigned char *jpegD
return nullptr;
}
std::vector<unsigned char> rgba(static_cast<size_t>(width) * height * 4);
if (tjDecompress2(handle, mutableJpegData, jpegSize, rgba.data(), width, width * 4,
height, TJPF_RGBA, TJFLAG_FASTUPSAMPLE |
TJFLAG_FASTDCT) != 0) {
constexpr int kPreviewMaxEdge = 512;
int scaledWidth = width;
int scaledHeight = height;
const tjscalingfactor *scalingFactors = nullptr;
int scalingFactorCount = 0;
if (std::max(width, height) > kPreviewMaxEdge) {
scalingFactors = tjGetScalingFactors(&scalingFactorCount);
if (scalingFactors && scalingFactorCount > 0) {
bool foundWithinLimit = false;
for (int i = 0; i < scalingFactorCount; ++i) {
const int candidateWidth = TJSCALED(width, scalingFactors[i]);
const int candidateHeight = TJSCALED(height, scalingFactors[i]);
const bool fitsLimit = std::max(candidateWidth, candidateHeight) <= kPreviewMaxEdge;
if (fitsLimit && (!foundWithinLimit ||
candidateWidth * candidateHeight > scaledWidth * scaledHeight)) {
scaledWidth = candidateWidth;
scaledHeight = candidateHeight;
foundWithinLimit = true;
} else if (!foundWithinLimit &&
candidateWidth * candidateHeight < scaledWidth * scaledHeight) {
scaledWidth = candidateWidth;
scaledHeight = candidateHeight;
}
}
}
}
std::vector<unsigned char> rgba(static_cast<size_t>(scaledWidth) * scaledHeight * 4);
if (tjDecompress2(handle, mutableJpegData, jpegSize, rgba.data(), scaledWidth,
scaledWidth * 4, scaledHeight, TJPF_RGBA,
TJFLAG_FASTUPSAMPLE | TJFLAG_FASTDCT) != 0) {
LOGE("decodeJpegPreviewToBitmap: jpeg decode failed: %s", tjGetErrorStr());
tjDestroy(handle);
return nullptr;
}
tjDestroy(handle);
return createBitmapFromRgba(env, width, height, rgba.data(), width * 4);
return createBitmapFromRgba(env, scaledWidth, scaledHeight, rgba.data(), scaledWidth * 4);
}
static jobject convertBitmapThumbnailToBitmap(JNIEnv *env,
@@ -2958,7 +2985,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
}
jobject embeddedPreviewBitmap = nullptr;
/*ret = RawProcessor.unpack_thumb();
ret = RawProcessor.unpack_thumb();
if (ret == LIBRAW_SUCCESS) {
libraw_processed_image_t *thumb = RawProcessor.dcraw_make_mem_thumb(&ret);
if (thumb && ret == LIBRAW_SUCCESS) {
@@ -2968,17 +2995,8 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
decodeJpegPreviewToBitmap(env, thumb->data, thumb->data_size);
LOGI("processDngNative: extracted embedded JPEG preview (%d bytes)",
(int)thumb->data_size);
} else if (thumb->type == LIBRAW_IMAGE_BITMAP) {
embeddedPreviewBitmap = convertBitmapThumbnailToBitmap(env, thumb);
if (embeddedPreviewBitmap) {
LOGI("processDngNative: converted embedded bitmap preview %dx%d c=%d b=%d",
thumb->width, thumb->height, thumb->colors, thumb->bits);
} else {
LOGI("processDngNative: failed to convert embedded bitmap preview %dx%d c=%d b=%d",
thumb->width, thumb->height, thumb->colors, thumb->bits);
}
} else {
LOGI("processDngNative: embedded preview present but unsupported type=%d",
LOGI("processDngNative: embedded preview ignored because it is not JPEG type=%d",
thumb->type);
}
LibRaw::dcraw_clear_mem(thumb);
@@ -2988,7 +3006,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
} else {
LOGI("processDngNative: unpack_thumb failed ret=%d err=%s", ret,
libraw_strerror(ret));
}*/
}
const bool hasBayerRaw = RawProcessor.imgdata.rawdata.raw_image != nullptr;
const bool hasLinearRawColor3 = RawProcessor.imgdata.rawdata.color3_image != nullptr;
@@ -3186,7 +3186,7 @@ object GalleryManager {
val photoDir = getPhotoDir(context, photoId, true)
val photoFile = File(photoDir, PHOTO_FILE)
val tempFile = File(photoDir, "temp.jpg")
var updatedMetadata: MediaMetadata = metadata.withEmbeddedDngGooglePixelToneMapDefaults(dngFile)
var updatedMetadata: MediaMetadata = metadata.withEmbeddedDngToneMapDefaults(dngFile)
val rawSharpening = updatedMetadata.sharpening ?: RawSharpeningDefaults.forCapture(sharpeningValue)
val rawNoiseReduction = resolveNoiseReduction(updatedMetadata, noiseReductionValue)
val rawChromaNoiseReduction = resolveChromaNoiseReduction(updatedMetadata, chromaNoiseReductionValue)
@@ -4251,9 +4251,25 @@ object GalleryManager {
return hasBitmapGainmap(loadBitmap(context, Uri.fromFile(photoFile), maxEdge = 512, preserveHdr = true))
}
private fun MediaMetadata.withEmbeddedDngGooglePixelToneMapDefaults(
/**
* Applies an embedded DNG profile only when no profile tone map was selected for the photo.
*
* Capture metadata snapshots the global RAW setting. Imported DNGs do the same below before
* reaching this point. An embedded PGTM/ProfileToneCurve is therefore a useful default, not
* an override of the user's selected rendering intent.
*/
private fun MediaMetadata.withEmbeddedDngToneMapDefaults(
dngFile: File
): MediaMetadata {
val selectedProfileToneMapMode = rawToneMappingParameters.normalized().profileToneMapMode
if (selectedProfileToneMapMode != RawProfileToneMapMode.Default) {
PLog.d(
TAG,
"Keeping selected $selectedProfileToneMapMode profile tone map; " +
"embedded DNG PGTM/ProfileToneCurve remains a fallback"
)
return this
}
val hasProfileGainTableMap = DngProfileGainTableMap.readFrom(dngFile)?.isValid == true
if (!hasProfileGainTableMap) return this
val toneMappingParameters = when {
@@ -4279,6 +4295,26 @@ object GalleryManager {
)
}
private suspend fun MediaMetadata.withImportedRawToneMapPreference(
context: Context
): MediaMetadata {
val globalToneMappingParameters = ContentRepository.getInstance(context)
.userPreferencesRepository
.userPreferences
.firstOrNull()
?.rawToneMappingParameters
?.normalized()
?: return this
if (globalToneMappingParameters.profileToneMapMode == RawProfileToneMapMode.Default) {
return this
}
PLog.d(
TAG,
"Applying global ${globalToneMappingParameters.profileToneMapMode} profile tone map to imported RAW"
)
return copy(rawToneMappingParameters = globalToneMappingParameters)
}
/**
* 从 URI 获取文件名
@@ -4385,7 +4421,9 @@ object GalleryManager {
}
}
var updatedMetadata: MediaMetadata = metadata.withEmbeddedDngGooglePixelToneMapDefaults(dngFile)
var updatedMetadata: MediaMetadata = metadata
.withImportedRawToneMapPreference(context)
.withEmbeddedDngToneMapDefaults(dngFile)
if (deferRawPreview) {
val metadataSaved = saveMetadata(context, photoId, updatedMetadata)
if (!metadataSaved) {
@@ -24,6 +24,7 @@ import com.hinnka.mycamera.lut.LutManager
import com.hinnka.mycamera.processor.DepthBokehProcessor
import com.hinnka.mycamera.raw.RawDemosaicProcessor
import com.hinnka.mycamera.raw.RawHdrRenderResult
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.SpectralFilmTuning
import com.hinnka.mycamera.utils.BitmapUtils
import com.hinnka.mycamera.utils.PLog
@@ -424,7 +425,9 @@ class PhotoProcessor(
context: Context, photoId: String, metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
chromaNoiseReduction: Float = 0f,
onRawAutoAdjustments: ((RawDemosaicProcessor.RawAutoAdjustments) -> Unit)? = null,
onRawMetadata: ((RawMetadata) -> Unit)? = null
): Bitmap? {
val dngFile = GalleryManager.getDngFile(context, photoId)
@@ -454,7 +457,9 @@ class PhotoProcessor(
metadata,
sharpening,
noiseReduction,
chromaNoiseReduction
chromaNoiseReduction,
onRawAutoAdjustments,
onRawMetadata
)
} else if (GalleryManager.getOriginalImageFile(context, photoId) != null) {
val bitmap = GalleryManager.loadOriginalBitmap(context, photoId) ?: return null
@@ -546,7 +551,9 @@ class PhotoProcessor(
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f
chromaNoiseReduction: Float = 0f,
onRawAutoAdjustments: ((RawDemosaicProcessor.RawAutoAdjustments) -> Unit)? = null,
onRawMetadata: ((RawMetadata) -> Unit)? = null
): Bitmap? = withContext(Dispatchers.IO) {
var result: Bitmap?
@@ -596,7 +603,9 @@ class PhotoProcessor(
cDensityGain = metadata.spectralFilmCDensityGain,
mDensityGain = metadata.spectralFilmMDensityGain,
yDensityGain = metadata.spectralFilmYDensityGain
)
),
onRawAutoAdjustments = onRawAutoAdjustments,
onMetadata = onRawMetadata
)
result = bitmap?.let {
@@ -214,7 +214,6 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
super.onChange(selfChange, uri)
uri ?: return
if (selfChange) return
val projection = arrayOf(
OpenableColumns.DISPLAY_NAME,
MediaStore.MediaColumns.DATA,
@@ -600,11 +599,10 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
uri,
lutId,
computationalAperture,
existingPhotoId,
deferRawPreview = isRawSource
existingPhotoId
) ?: run {
return@withContext
}
}
val phantomBaselineLutId = preferences?.phantomBaselineLutId
val baselineTarget = if (phantomBaselineLutId != null) BaselineColorCorrectionTarget.PHANTOM else null
val baselineLutId = phantomBaselineLutId
@@ -621,7 +619,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
val metadataCreativeColorRecipeParams = effectiveCreativeColorRecipeParams
.takeUnless { it.isDefault() }
val updatedMetadata = GalleryManager.updateMetadata(context, photoId) { current ->
var updatedMetadata = GalleryManager.updateMetadata(context, photoId) { current ->
if (baselineTarget != null) {
current.copy(
lutId = lutId,
@@ -672,14 +670,23 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
// 读取照片
val processedBitmap = photoProcessor.process(
context, photoId, updatedMetadata,
0f, 0f, 0f
0f, 0f, 0f,
onRawAutoAdjustments = { adjustments ->
updatedMetadata = updatedMetadata.copy(
rawExposureCompensation = adjustments.exposureCompensation,
rawHighlightsAdjustment = adjustments.highlights,
rawShadowsAdjustment = adjustments.shadows
)
},
onRawMetadata = { raw ->
updatedMetadata = updatedMetadata.merge(raw)
}
) ?: return@withContext
if (!isActive) return@withContext
val videoFile = GalleryManager.getVideoFile(context, photoId)
val photoFile = GalleryManager.getPhotoFile(context, photoId)
val saveRawAsNew = shouldSaveRawPhantomExportAsNew(photoId, updatedMetadata.mimeType, name)
val shouldSaveAsNew = saveAsNew || saveRawAsNew
val shouldSaveAsNew = saveAsNew || isRawSource
val exportedWidth = processedBitmap.width
val exportedHeight = processedBitmap.height
@@ -700,7 +707,7 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
var newSize = 0L
var newName = name
val writeUri = if (shouldSaveAsNew) {
if (shouldSaveAsNew) {
val lutName =
updatedMetadata.lutId?.let { ContentRepository.getInstance(context).lutManager.getLutInfo(it)?.getName() }
newName = buildPhantomExportName(name, lutName)
@@ -709,7 +716,9 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
newName = newName,
newSize = newSize
)
}
val writeUri = if (shouldSaveAsNew) {
createPhantomExportUri(uri, relativePath, newName) ?: return@withContext
} else {
uri
@@ -789,7 +798,6 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
}
}
// Save exported URI to metadata
GalleryManager.updateMetadata(context, photoId) { current ->
current.copy(
exportedUris = current.exportedUris + writeUri.toString()
@@ -819,17 +827,6 @@ class PhantomService(val context: Context) : LifecycleOwner, SavedStateRegistryO
delay(200L)
}
private fun shouldSaveRawPhantomExportAsNew(
photoId: String,
mimeType: String?,
sourceName: String
): Boolean {
val dngFile = GalleryManager.getDngFile(context, photoId)
return (dngFile.exists() && dngFile.length() > 0L) ||
isRawMimeType(mimeType) ||
isRawFileName(sourceName)
}
private fun isRawMimeType(mimeType: String?): Boolean {
return mimeType?.contains("raw", ignoreCase = true) == true ||
mimeType?.contains("dng", ignoreCase = true) == true
@@ -1271,6 +1271,7 @@ class RawDemosaicProcessor {
var actualMetadata = metadata
var actualRotation = rotation
var dngRawDataCleanup: DngRawData? = null
var embeddedDngJpegPreview: Bitmap? = null
val requestedColorEngine = rawRenderingEngine
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
val profileWorkingColorSpace = ColorSpace.ProPhoto
@@ -1309,6 +1310,7 @@ class RawDemosaicProcessor {
}
}
dngRawDataCleanup = dngRawData
embeddedDngJpegPreview = dngRawData.embeddedPreview
actualRawData = dngRawData.rawData
actualWidth = dngRawData.width
actualHeight = dngRawData.height
@@ -1414,10 +1416,14 @@ class RawDemosaicProcessor {
metadataDefaultCrop = effectiveDefaultCrop
)
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
val autoExposurePreview = capturePreviewThumbnail ?: embeddedDngJpegPreview
if (capturePreviewThumbnail == null && embeddedDngJpegPreview != null) {
PLog.d(TAG, "Using embedded DNG JPEG preview for RAW auto exposure")
}
val rawAeContentBounds = resolveRawAeContentBounds(
rawSourceBounds = outputSourceBounds,
outputRotation = actualRotation,
thumbnail = capturePreviewThumbnail
thumbnail = autoExposurePreview
)
val embeddedDngProfileName = embeddedDngRenderPlan?.profileName
val embeddedProfileToneCurveLut = embeddedDngRenderPlan?.toneCurveLut
@@ -1656,11 +1662,11 @@ class RawDemosaicProcessor {
!rawAutoExposure -> null
else -> {
analyzeSrgbThumbnailForMetering(
capturePreviewThumbnail,
autoExposurePreview,
rawAeContentBounds?.thumbnailBounds
).also { image ->
if (image == null) {
PLog.d(TAG, "RAW auto exposure disabled: capture preview thumbnail unavailable")
PLog.d(TAG, "RAW auto exposure disabled: no capture or embedded DNG JPEG preview")
}
}
}
@@ -2332,6 +2338,7 @@ class RawDemosaicProcessor {
)
}
} finally {
embeddedDngJpegPreview?.takeIf { !it.isRecycled }?.recycle()
dngRawDataCleanup?.close()
}
}