fix: raw crop, size, exif metadata

This commit is contained in:
zhoubinjia committed 2026-07-13 18:58:33 +08:00
1 parent 5388781c9a
commit 6520bf192e
15 files changed
+611 -118

No files matched your search

+6 -2
View File
@@ -3646,8 +3646,12 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
int defaultCrop[4] = {0, 0, 0, 0};
const bool hasDefaultCrop = computeValidDngDefaultCrop(
dngRawTagInfo, left, top, width, height, defaultCrop);
LOGI("dng default crop tags: origin=%d(%f,%f) size=%d(%f,%f) "
"valid=%d crop=%d,%d,%d,%d buffer=%d,%d,%d,%d",
LOGI("RAW_CROP_TRACE stage=NATIVE_DNG_READ activeTag=%d active=%d,%d,%d,%d "
"originTag=%d origin=%f,%f sizeTag=%d size=%f,%f "
"valid=%d localCrop=%d,%d,%d,%d buffer=%d,%d,%d,%d",
dngRawTagInfo.hasActiveArea ? 1 : 0,
dngRawTagInfo.activeArea[0], dngRawTagInfo.activeArea[1],
dngRawTagInfo.activeArea[2], dngRawTagInfo.activeArea[3],
dngRawTagInfo.hasDefaultCropOrigin ? 1 : 0,
dngRawTagInfo.defaultCropOrigin[0], dngRawTagInfo.defaultCropOrigin[1],
dngRawTagInfo.hasDefaultCropSize ? 1 : 0,
@@ -2310,6 +2310,17 @@ class Camera2Controller(private val context: Context) {
setZslDisabledIfSupported(builder)
}
applyVendorCaptureSettings(builder, isCapture)
if (isCapture) {
PLog.i(
TAG,
"RAW_CROP_TRACE stage=CAMERA2_REQUEST isRaw=$isRawCapture " +
"selectedCamera=${currentState.currentCameraId} openCamera=${getActiveOpenCameraId()} " +
"physicalOutput=$activeOutputPhysicalCameraId stateZoom=${currentState.zoomRatio} " +
"requestZoom=${builder.get(CaptureRequest.CONTROL_ZOOM_RATIO)} " +
"requestScalerCrop=${builder.get(CaptureRequest.SCALER_CROP_REGION)} " +
"requestDistortion=${builder.get(CaptureRequest.DISTORTION_CORRECTION_MODE)}"
)
}
}
private fun forcedVendorSessionParameterValues(state: CameraState): Map<VendorCaptureKey, Int> {
@@ -1536,6 +1536,16 @@ object GalleryManager {
imageWidth = metadata.width,
imageHeight = metadata.height
)
if (includeCropRegionInOutputSize) {
PLog.i(
TAG,
"RAW_CROP_TRACE stage=PREPARE_RESULT image=${metadata.width}x${metadata.height} " +
"scalerCrop=${captureResult?.get(CaptureResult.SCALER_CROP_REGION)} " +
"zoomRatio=${captureResult?.get(CaptureResult.CONTROL_ZOOM_RATIO)} " +
"distortionMode=${captureResult?.get(CaptureResult.DISTORTION_CORRECTION_MODE)} " +
"legacyDerivedCrop=$cropRegion"
)
}
if (superResolutionScale > 1.0f && cropRegion != null) {
cropRegion = Rect(
(cropRegion.left * superResolutionScale).roundToInt(),
@@ -1815,6 +1825,7 @@ object GalleryManager {
}
var dngSaveAttempted = false
val captureInfo = metadata.toCaptureInfo()
FileOutputStream(tempDngFile).use { outputStream ->
image.use {
try {
@@ -1829,7 +1840,9 @@ object GalleryManager {
customBlackLevel = metadata.rawCustomBlackLevel,
whiteLevelMode = metadata.rawWhiteLevelMode,
customWhiteLevel = metadata.rawCustomWhiteLevel,
cfaCorrectionMode = metadata.rawCfaCorrectionMode
cfaCorrectionMode = metadata.rawCfaCorrectionMode,
effectiveFocalLengthMm = captureInfo.focalLength,
effectiveFocalLength35mm = captureInfo.focalLength35mm,
)
} catch (e: Throwable) {
PLog.e(TAG, "DNG save failed", e)
@@ -3368,6 +3381,7 @@ object GalleryManager {
inputColStepSamples: Int? = null,
): Boolean {
val tempDngFile = File(dngFile.parentFile, "temp_stacked.dng")
val captureInfo = metadata.toCaptureInfo()
val dngWritten = try {
FileOutputStream(tempDngFile).use { outputStream ->
RawProcessor.saveRawBufferToDng(
@@ -3377,6 +3391,8 @@ object GalleryManager {
characteristics = characteristics,
captureResult = captureResult,
captureMetadataResult = captureMetadataResult,
effectiveFocalLengthMm = captureInfo.focalLength,
effectiveFocalLength35mm = captureInfo.focalLength35mm,
outputStream = outputStream,
rotation = rotation,
thumbnail = thumbnail,
@@ -3400,10 +3416,14 @@ object GalleryManager {
compression = compression,
inputRowStepSamples = inputRowStepSamples,
inputColStepSamples = inputColStepSamples,
// The fused buffer producer defines its entire returned
// grid as valid. Any future fusion-stage crop must be
// carried here explicitly instead of inferred by the writer.
defaultCrop = Rect(0, 0, width, height),
// 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(
width = width,
height = height,
characteristics = characteristics,
captureResult = captureResult,
),
)
}
} catch (e: Throwable) {
@@ -4527,6 +4547,13 @@ object GalleryManager {
tempImportJpeg(uri, context, metadata, photoFile, thumbnailFile)
}
}
if (!deferRawPreview && photoFile.exists()) {
syncImportedRawMetadataToOriginalJpeg(
context = context,
photoId = photoId,
photoFile = photoFile,
)
}
} else {
// --- 常规 JPEG 处理逻辑 ---
// 传递元数据确保旋转信息被正确处理
@@ -4774,6 +4801,33 @@ object GalleryManager {
generateThumbnail(photoFile, thumbnailFile)
}
private suspend fun syncImportedRawMetadataToOriginalJpeg(
context: Context,
photoId: String,
photoFile: File,
) {
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(photoFile.absolutePath, options)
val outputWidth = options.outWidth
val outputHeight = options.outHeight
if (outputWidth <= 0 || outputHeight <= 0) {
PLog.w(TAG, "Unable to read imported RAW original.jpg dimensions: ${photoFile.absolutePath}")
return
}
updateMetadata(context, photoId) { current ->
current.copy(
width = outputWidth,
height = outputHeight,
rotation = 0,
)
}
PLog.i(
TAG,
"RAW_CROP_TRACE stage=IMPORT_METADATA originalJpeg=${outputWidth}x$outputHeight " +
"photoId=$photoId"
)
}
/**
* 根据 EXIF 方向信息旋转图片
*/
@@ -58,7 +58,13 @@ data class MediaData(
/**
* 分辨率字符串
*/
fun getResolution(): String = "${width}x${height}"
fun getResolution(): String {
val displayedPhoto = relatedPhoto ?: this
val displayedMetadata = displayedPhoto.metadata
val displayedWidth = displayedMetadata?.width?.takeIf { it > 0 } ?: displayedPhoto.width
val displayedHeight = displayedMetadata?.height?.takeIf { it > 0 } ?: displayedPhoto.height
return "${displayedWidth}x${displayedHeight}"
}
fun getFormattedDuration(): String {
val totalSeconds = ((durationMs ?: 0L) / 1000L).coerceAtLeast(0L)
@@ -506,9 +506,9 @@ data class MediaMetadata(
val aperture = exif.getAttributeDouble(ExifInterface.TAG_F_NUMBER, 0.0).takeIf { it > 0 }
?.let { "f/${String.format("%.1f", it)}" }
val focalLength = exif.getAttributeDouble(ExifInterface.TAG_FOCAL_LENGTH, 0.0).let {
"${it.toInt()}mm"
}
val focalLength = exif.getAttributeDouble(ExifInterface.TAG_FOCAL_LENGTH, 0.0)
.takeIf { it > 0.0 }
?.let { "${it.toInt()}mm" }
val focalLength35mm = exif.getAttributeInt(ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM, 0)
.takeIf { it > 0 }?.let { "${it}mm" }
@@ -1307,7 +1307,8 @@ class RawDemosaicProcessor {
return@withContext RawProcessor.processAndToBitmap(
dngFile,
aspectRatio,
cropRegion,
// Platform DNG decoding already consumes DefaultCrop.
null,
rotation
)?.let {
RawHdrRenderResult(
@@ -1317,6 +1318,13 @@ class RawDemosaicProcessor {
}
}
dngRawDataCleanup = dngRawData
PLog.i(
TAG,
"RAW_CROP_TRACE stage=DNG_READ raw=${dngRawData.width}x${dngRawData.height} " +
"activeArray=${dngRawData.activeArray?.contentToString()} " +
"defaultCrop=${dngRawData.defaultCrop?.contentToString()} " +
"warpCount=${dngRawData.warpRectilinear?.size?.div(8) ?: 0}"
)
embeddedDngJpegPreview = dngRawData.embeddedPreview
dngWarpRectilinear = dngRawData.warpRectilinear
actualRawData = dngRawData.rawData
@@ -1416,13 +1424,29 @@ class RawDemosaicProcessor {
metadataDefaultCrop = actualMetadata.defaultCrop
)
val effectiveDefaultCrop = rawBlackBorderDefaultCrop ?: actualMetadata.defaultCrop
val renderCropRegion = if (dngFile != null && effectiveDefaultCrop != null) {
if (cropRegion != null) {
PLog.d(TAG, "DNG DefaultCrop is authoritative; ignoring legacy Camera2 crop=$cropRegion")
}
null
} else {
cropRegion
}
val outputSourceBounds = calculateOutputSourceBounds(
width = actualWidth,
height = actualHeight,
aspectRatio = aspectRatio,
cropRegion = cropRegion,
cropRegion = renderCropRegion,
metadataDefaultCrop = effectiveDefaultCrop
)
PLog.i(
TAG,
"RAW_CROP_TRACE stage=RENDER_BOUNDS raw=${actualWidth}x$actualHeight " +
"metadataDefaultCrop=${actualMetadata.defaultCrop} " +
"blackBorderOverride=$rawBlackBorderDefaultCrop effectiveDefaultCrop=$effectiveDefaultCrop " +
"legacyCrop=$cropRegion appliedLegacyCrop=$renderCropRegion " +
"aspectRatio=$aspectRatio rotation=$actualRotation outputSourceBounds=$outputSourceBounds"
)
val rawOutputBounds = outputSourceBounds.toOutputBounds(actualRotation)
val autoExposurePreview = capturePreviewThumbnail
?: embeddedDngJpegPreview.takeIf { useEmbeddedPreviewForAutoExposure }
@@ -751,17 +751,31 @@ object RcdShaders {
}
}
ivec2 clampCoord(ivec2 coord) {
return clamp(coord, ivec2(0), uImageSize - ivec2(1));
int mirrorIndex(int value, int size) {
if (size <= 1) return 0;
int period = 2 * (size - 1);
int wrapped = value % period;
if (wrapped < 0) wrapped += period;
return (wrapped < size) ? wrapped : period - wrapped;
}
// Mirror at the photosite center instead of clamping to the last sample.
// The reflection preserves x/y parity, so every synthetic neighbour keeps
// the same Bayer color it would have had outside the image.
ivec2 mirrorCoord(ivec2 coord) {
return ivec2(
mirrorIndex(coord.x, uImageSize.x),
mirrorIndex(coord.y, uImageSize.y)
);
}
int indexAt(ivec2 coord) {
ivec2 safe = clampCoord(coord);
ivec2 safe = mirrorCoord(coord);
return safe.y * uImageSize.x + safe.x;
}
int colorAt(ivec2 coord) {
ivec2 safe = clampCoord(coord);
ivec2 safe = mirrorCoord(coord);
return getBayerColor(uCfaPattern, safe.x, safe.y);
}
@@ -769,61 +783,10 @@ object RcdShaders {
return cfa[indexAt(coord)];
}
bool inImage(ivec2 coord) {
return coord.x >= 0 && coord.y >= 0 &&
coord.x < uImageSize.x && coord.y < uImageSize.y;
}
bool inOutermostBorder(ivec2 coord) {
return coord.x < 3 || coord.y < 3 ||
coord.x >= uImageSize.x - 3 || coord.y >= uImageSize.y - 3;
}
vec3 borderInterpolateAt(ivec2 coord) {
ivec2 center = clampCoord(coord);
vec3 sum = vec3(0.0);
vec3 count = vec3(0.0);
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
ivec2 sampleCoord = center + ivec2(dx, dy);
if (!inImage(sampleCoord)) continue;
int sampleColor = colorAt(sampleCoord);
float sampleValue = max(0.0, rawAt(sampleCoord));
if (sampleColor == RED) {
sum.r += sampleValue;
count.r += 1.0;
} else if (sampleColor == GREEN) {
sum.g += sampleValue;
count.g += 1.0;
} else {
sum.b += sampleValue;
count.b += 1.0;
}
}
}
float self = max(0.0, rawAt(center));
vec3 color = vec3(
count.r > 0.0 ? sum.r / count.r : self,
count.g > 0.0 ? sum.g / count.g : self,
count.b > 0.0 ? sum.b / count.b : self
);
int ownColor = colorAt(center);
if (ownColor == RED) {
color.r = self;
} else if (ownColor == GREEN) {
color.g = self;
} else {
color.b = self;
}
return max(color, vec3(0.0));
}
float ppgGreenAt(ivec2 coord) {
ivec2 center = clampCoord(coord);
if (inOutermostBorder(center)) {
return borderInterpolateAt(center).g;
}
// Keep the virtual coordinate so recursive PPG estimates use the neighbourhood
// around that reflected photosite, rather than shifting the kernel into the image.
ivec2 center = coord;
int ownColor = colorAt(center);
float pc = rawAt(center);
@@ -861,10 +824,7 @@ object RcdShaders {
}
vec3 ppgColorAt(ivec2 coord) {
ivec2 center = clampCoord(coord);
if (inOutermostBorder(center)) {
return borderInterpolateAt(center);
}
ivec2 center = coord;
int ownColor = colorAt(center);
float pc = max(0.0, rawAt(center));
@@ -786,6 +786,8 @@ fun GalleryDetailScreen(
// 照片信息对话框
if (showInfoDialog && currentPhoto != null) {
val infoPhoto = currentPhoto.relatedPhoto ?: currentPhoto
val infoMetadata = infoPhoto.metadata ?: currentPhoto.metadata
AlertDialog(
onDismissRequest = { showInfoDialog = false },
title = { Text(stringResource(if (currentPhoto.isVideo) R.string.video_info else R.string.photo_info)) },
@@ -797,7 +799,7 @@ fun GalleryDetailScreen(
InfoRow(stringResource(R.string.photo_info_date), currentPhoto.getFormattedDate())
InfoRow(stringResource(R.string.photo_info_resolution), currentPhoto.getResolution())
InfoRow(stringResource(R.string.photo_info_size), currentPhoto.copy(size = displayPhotoSize).getFormattedSize())
currentPhoto.metadata?.let {
infoMetadata?.let {
if (currentPhoto.isVideo) {
InfoRow(stringResource(R.string.video_info_duration), currentPhoto.getFormattedDuration())
InfoRow(stringResource(R.string.video_info_mime), it.mimeType ?: (currentPhoto.mimeType ?: "N/A"))
@@ -0,0 +1,91 @@
package com.hinnka.mycamera.utils
import kotlin.math.roundToInt
/** Integer rectangle used by the Camera2-to-DNG crop mapping without Android dependencies. */
internal data class RawCropRect(
val left: Int,
val top: Int,
val right: Int,
val bottom: Int,
) {
val width: Int get() = right - left
val height: Int get() = bottom - top
fun isValid(): Boolean = width > 0 && height > 0
}
/**
* Maps the field of view described by Camera2 result metadata to DNG DefaultCrop coordinates.
*
* Camera2 reports SCALER_CROP_REGION in the post-zoom coordinate system. Its coordinate domain
* is the pre-correction active array only when distortion correction is OFF; otherwise it is the
* post-correction active array. DNG DefaultCrop is relative to ActiveArea, which is backed by the
* pre-correction RAW grid. Mapping through normalized coordinates keeps those domains separate.
*/
internal object RawDngCropMapper {
fun mapToDefaultCrop(
preCorrectionActiveArray: RawCropRect,
postCorrectionActiveArray: RawCropRect?,
scalerCropRegion: RawCropRect?,
zoomRatio: Float,
usePreCorrectionCoordinateSystem: Boolean,
targetWidth: Int,
targetHeight: Int,
): RawCropRect {
require(preCorrectionActiveArray.isValid())
require(targetWidth > 0 && targetHeight > 0)
val coordinateDomain = if (usePreCorrectionCoordinateSystem) {
preCorrectionActiveArray
} else {
postCorrectionActiveArray?.takeIf { it.isValid() } ?: preCorrectionActiveArray
}
val localDomain = RawCropRect(0, 0, coordinateDomain.width, coordinateDomain.height)
val localCrop = localizeCrop(scalerCropRegion, coordinateDomain) ?: localDomain
val effectiveZoom = zoomRatio.takeIf { it.isFinite() && it >= 1f }?.toDouble() ?: 1.0
val inverseZoom = 1.0 / effectiveZoom
val zoomOriginX = (1.0 - inverseZoom) * 0.5
val zoomOriginY = (1.0 - inverseZoom) * 0.5
fun mapX(value: Int): Int {
val localNormalized = value.toDouble() / localDomain.width.toDouble()
return ((zoomOriginX + localNormalized * inverseZoom) * targetWidth)
.roundToInt()
.coerceIn(0, targetWidth)
}
fun mapY(value: Int): Int {
val localNormalized = value.toDouble() / localDomain.height.toDouble()
return ((zoomOriginY + localNormalized * inverseZoom) * targetHeight)
.roundToInt()
.coerceIn(0, targetHeight)
}
val left = mapX(localCrop.left)
val top = mapY(localCrop.top)
val right = mapX(localCrop.right).coerceAtLeast(left + 1).coerceAtMost(targetWidth)
val bottom = mapY(localCrop.bottom).coerceAtLeast(top + 1).coerceAtMost(targetHeight)
return RawCropRect(
left = left.coerceAtMost(right - 1),
top = top.coerceAtMost(bottom - 1),
right = right,
bottom = bottom,
)
}
private fun localizeCrop(crop: RawCropRect?, domain: RawCropRect): RawCropRect? {
if (crop == null) return null
require(crop.isValid()) { "SCALER_CROP_REGION must be non-empty: $crop" }
val localBounds = RawCropRect(0, 0, domain.width, domain.height)
require(localBounds.contains(crop)) {
"SCALER_CROP_REGION $crop is outside Camera2 coordinate bounds $localBounds"
}
return crop
}
private fun RawCropRect.contains(other: RawCropRect): Boolean {
return other.left >= left && other.top >= top &&
other.right <= right && other.bottom <= bottom
}
}
@@ -153,6 +153,8 @@ object RawProcessor {
whiteLevelMode: String? = null,
customWhiteLevel: Float? = null,
cfaCorrectionMode: String? = null,
effectiveFocalLengthMm: Float? = null,
effectiveFocalLength35mm: Int? = null,
): Boolean {
if (!isRawImage(image)) {
throw IllegalArgumentException("Image is not RAW format: ${image.format}")
@@ -170,26 +172,63 @@ object RawProcessor {
whiteLevelMode = whiteLevelMode,
customWhiteLevel = customWhiteLevel,
cfaCorrectionMode = cfaCorrectionMode,
defaultCrop = resolveCameraRawDefaultCrop(image.width, image.height, characteristics),
effectiveFocalLengthMm = effectiveFocalLengthMm,
effectiveFocalLength35mm = effectiveFocalLength35mm,
defaultCrop = resolveCameraRawDefaultCrop(
width = image.width,
height = image.height,
characteristics = characteristics,
captureResult = captureResult,
),
)
}
private fun resolveCameraRawDefaultCrop(
internal fun resolveCameraRawDefaultCrop(
width: Int,
height: Int,
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
): Rect {
val pixelArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE)
val preCorrection = characteristics.get(
CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE
) ?: Rect(0, 0, width, height)
val postCorrection = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE)
val bufferIncludesPixelArray = pixelArray?.width == width && pixelArray.height == height
val targetWidth = if (bufferIncludesPixelArray) preCorrection.width() else width
val targetHeight = if (bufferIncludesPixelArray) preCorrection.height() else height
val scalerCropRegion = captureResult.get(CaptureResult.SCALER_CROP_REGION)
val zoomRatio = captureResult.get(CaptureResult.CONTROL_ZOOM_RATIO) ?: 1f
val distortionMode = captureResult.get(CaptureResult.DISTORTION_CORRECTION_MODE)
val hasDistortionCorrectionControl = characteristics.get(
CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES
) != null
val mapped = RawDngCropMapper.mapToDefaultCrop(
preCorrectionActiveArray = preCorrection.toRawCropRect(),
postCorrectionActiveArray = postCorrection?.toRawCropRect(),
scalerCropRegion = scalerCropRegion?.toRawCropRect(),
zoomRatio = zoomRatio,
usePreCorrectionCoordinateSystem = hasDistortionCorrectionControl &&
distortionMode == CaptureResult.DISTORTION_CORRECTION_MODE_OFF,
targetWidth = targetWidth,
targetHeight = targetHeight,
)
return if (pixelArray?.width == width && pixelArray.height == height && preCorrection != null) {
Rect(0, 0, preCorrection.width(), preCorrection.height())
} else {
Rect(0, 0, width, height)
}
val defaultCrop = Rect(mapped.left, mapped.top, mapped.right, mapped.bottom)
PLog.i(
TAG,
"RAW_CROP_TRACE stage=CAMERA2_RESULT buffer=${width}x$height " +
"pixelArray=$pixelArray activePre=$preCorrection activePost=$postCorrection " +
"scalerCrop=$scalerCropRegion scalerReturned=${scalerCropRegion != null} " +
"zoomRatio=$zoomRatio distortionMode=$distortionMode " +
"distortionControl=$hasDistortionCorrectionControl " +
"coordinateSpace=${if (hasDistortionCorrectionControl && distortionMode == CaptureResult.DISTORTION_CORRECTION_MODE_OFF) "PRE_CORRECTION" else "POST_CORRECTION"} " +
"dngTarget=${targetWidth}x$targetHeight mappedDefaultCrop=$defaultCrop"
)
return defaultCrop
}
private fun Rect.toRawCropRect(): RawCropRect = RawCropRect(left, top, right, bottom)
private fun saveRawImageToDngWithCustomWriter(
image: SafeImage,
characteristics: CameraCharacteristics,
@@ -202,6 +241,8 @@ object RawProcessor {
whiteLevelMode: String?,
customWhiteLevel: Float?,
cfaCorrectionMode: String?,
effectiveFocalLengthMm: Float?,
effectiveFocalLength35mm: Int?,
defaultCrop: Rect,
): Boolean {
if (image.format != ImageFormat.RAW_SENSOR) {
@@ -237,6 +278,8 @@ object RawProcessor {
whiteLevelMode = whiteLevelMode,
customWhiteLevel = customWhiteLevel,
cfaCorrectionMode = cfaCorrectionMode,
effectiveFocalLengthMm = effectiveFocalLengthMm,
effectiveFocalLength35mm = effectiveFocalLength35mm,
defaultCrop = defaultCrop,
)
}
@@ -278,6 +321,8 @@ object RawProcessor {
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
captureMetadataResult: CaptureResult? = null,
effectiveFocalLengthMm: Float? = null,
effectiveFocalLength35mm: Int? = null,
outputStream: java.io.OutputStream,
rotation: Int = 0,
thumbnail: Bitmap? = null,
@@ -330,6 +375,8 @@ object RawProcessor {
characteristics = characteristics,
captureResult = captureResult,
captureMetadataResult = captureMetadataResult ?: captureResult,
effectiveFocalLengthMm = effectiveFocalLengthMm,
effectiveFocalLength35mm = effectiveFocalLength35mm,
orientation = orientation,
cfaPattern = resolvedCfaPattern,
blackLevel = blackLevel,
@@ -72,6 +72,7 @@ object SuperResolutionDngWriter {
private const val TAG_PLANAR_CONFIGURATION = 284
private const val TAG_SOFTWARE = 305
private const val TAG_DATETIME = 306
private const val TAG_EXIF_IFD_POINTER = 34665
private const val TAG_EXPOSURE_TIME = 33434
private const val TAG_F_NUMBER = 33437
private const val TAG_ISO_SPEED_RATINGS = 34855
@@ -133,6 +134,8 @@ object SuperResolutionDngWriter {
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
captureMetadataResult: CaptureResult = captureResult,
effectiveFocalLengthMm: Float? = null,
effectiveFocalLength35mm: Int? = null,
orientation: Int,
cfaPattern: Int,
blackLevel: FloatArray,
@@ -229,12 +232,14 @@ object SuperResolutionDngWriter {
}
val imageByteCount = imageBytes?.size?.toLong() ?: uncompressedByteCount
val entries = buildEntries(
val directories = buildEntries(
width = width,
height = height,
characteristics = characteristics,
captureResult = captureResult,
captureMetadataResult = captureMetadataResult,
effectiveFocalLengthMm = effectiveFocalLengthMm,
effectiveFocalLength35mm = effectiveFocalLength35mm,
orientation = orientation,
cfaPattern = cfaPattern,
blackLevel = encodedBlackLevel,
@@ -249,7 +254,10 @@ object SuperResolutionDngWriter {
valueDomain = valueDomain,
defaultCrop = defaultCrop,
)
val header = buildHeader(entries)
val header = buildHeader(
primaryEntries = directories.primaryEntries,
exifEntries = directories.exifEntries,
)
outputStream.write(header)
if (imageBytes != null) {
outputStream.write(imageBytes)
@@ -278,6 +286,8 @@ object SuperResolutionDngWriter {
characteristics: CameraCharacteristics,
captureResult: CaptureResult,
captureMetadataResult: CaptureResult,
effectiveFocalLengthMm: Float?,
effectiveFocalLength35mm: Int?,
orientation: Int,
cfaPattern: Int,
blackLevel: FloatArray,
@@ -291,7 +301,7 @@ object SuperResolutionDngWriter {
compression: Compression,
valueDomain: RawProcessor.RawBufferValueDomain,
defaultCrop: Rect,
): List<TiffEntry> {
): TiffDirectories {
// The custom writer is used when the fused RAW dimensions no longer
// match the camera sensor. The fused buffer already lives in its final
// Bayer pixel grid, so DefaultScale must stay 1:1. Scaling it back to
@@ -301,6 +311,17 @@ object SuperResolutionDngWriter {
val defaultScaleY = 1.0
val cameraModel = buildCameraModel(characteristics)
val geometry = resolveDngGeometry(width, height, characteristics, defaultCrop)
PLog.i(
TAG,
"RAW_CROP_TRACE stage=DNG_WRITE buffer=${width}x$height " +
"activeArea=${geometry.activeArea.contentToString()} " +
"defaultCropOrigin=${geometry.defaultCropLeft},${geometry.defaultCropTop} " +
"defaultCropSize=${geometry.defaultCropWidth}x${geometry.defaultCropHeight} " +
"sourceOrigin=${geometry.sourceOriginX},${geometry.sourceOriginY} " +
"sourceSize=${geometry.sourceWidth}x${geometry.sourceHeight} " +
"includesPixelArray=${geometry.bufferIncludesPixelArray} " +
"scale=${geometry.scaleX},${geometry.scaleY}"
)
val illuminant1 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT1) ?: 21
val illuminant2 = characteristics.get(CameraCharacteristics.SENSOR_REFERENCE_ILLUMINANT2)?.toInt()
val colorMatrix1 = characteristics.get(CameraCharacteristics.SENSOR_COLOR_TRANSFORM1)
@@ -318,8 +339,11 @@ object SuperResolutionDngWriter {
?.let { it.toDouble() / 1_000_000_000.0 }
val iso = captureMetadataResult.get(CaptureResult.SENSOR_SENSITIVITY)?.takeIf { it > 0 }
val aperture = captureMetadataResult.get(CaptureResult.LENS_APERTURE)?.takeIf { it > 0f }
val focalLength = captureMetadataResult.get(CaptureResult.LENS_FOCAL_LENGTH)?.takeIf { it > 0f }
val focalLength35mm = calculate35mmEquivalent(characteristics, focalLength)
val physicalFocalLength = captureMetadataResult.get(CaptureResult.LENS_FOCAL_LENGTH)
?.takeIf { it > 0f }
val focalLength = effectiveFocalLengthMm?.takeIf { it > 0f } ?: physicalFocalLength
val focalLength35mm = effectiveFocalLength35mm?.takeIf { it > 0 }
?: calculate35mmEquivalent(characteristics, physicalFocalLength)
val exifWhiteBalance = captureMetadataResult.get(CaptureResult.CONTROL_AWB_MODE)?.let { awbMode ->
if (awbMode == CameraMetadata.CONTROL_AWB_MODE_AUTO) 0 else 1
}
@@ -349,7 +373,23 @@ object SuperResolutionDngWriter {
}
}
return buildList {
val exifEntries = buildList {
exposureTimeSeconds?.let { add(rationalArray(TAG_EXPOSURE_TIME, listOf(it))) }
aperture?.let {
add(rationalArray(TAG_F_NUMBER, listOf(it.toDouble())))
add(rationalArray(TAG_APERTURE_VALUE, listOf(apexAperture(it).toDouble())))
}
iso?.let { add(short(TAG_ISO_SPEED_RATINGS, it.coerceIn(1, MAX_TIFF_SHORT))) }
add(ascii(TAG_DATETIME_ORIGINAL, dateTime))
add(ascii(TAG_DATETIME_DIGITIZED, dateTime))
focalLength?.let { add(rationalArray(TAG_FOCAL_LENGTH, listOf(it.toDouble()))) }
exifWhiteBalance?.let { add(short(TAG_WHITE_BALANCE, it)) }
focalLength35mm?.let {
add(short(TAG_FOCAL_LENGTH_IN_35MM_FILM, it.coerceIn(1, MAX_TIFF_SHORT)))
}
}.sortedBy { it.tag }
val primaryEntries = buildList {
add(long(TAG_NEW_SUBFILE_TYPE, 0))
add(long(TAG_IMAGE_WIDTH, width.toLong()))
add(long(TAG_IMAGE_LENGTH, height.toLong()))
@@ -366,17 +406,9 @@ object SuperResolutionDngWriter {
add(short(TAG_PLANAR_CONFIGURATION, 1))
add(ascii(TAG_SOFTWARE, "PhotonCamera"))
add(ascii(TAG_DATETIME, dateTime))
exposureTimeSeconds?.let { add(rationalArray(TAG_EXPOSURE_TIME, listOf(it))) }
aperture?.let {
add(rationalArray(TAG_F_NUMBER, listOf(it.toDouble())))
add(sRationalArray(TAG_APERTURE_VALUE, listOf(apexAperture(it).toDouble())))
if (exifEntries.isNotEmpty()) {
add(long(TAG_EXIF_IFD_POINTER, 0))
}
iso?.let { add(short(TAG_ISO_SPEED_RATINGS, it.coerceIn(1, MAX_TIFF_SHORT))) }
add(ascii(TAG_DATETIME_ORIGINAL, dateTime))
add(ascii(TAG_DATETIME_DIGITIZED, dateTime))
focalLength?.let { add(rationalArray(TAG_FOCAL_LENGTH, listOf(it.toDouble()))) }
exifWhiteBalance?.let { add(short(TAG_WHITE_BALANCE, it)) }
focalLength35mm?.let { add(short(TAG_FOCAL_LENGTH_IN_35MM_FILM, it.coerceIn(1, MAX_TIFF_SHORT))) }
if (isCfa) {
add(shortArray(TAG_CFA_REPEAT_PATTERN_DIM, RawCfaCorrection.repeatPatternDim(cfaPattern)))
add(byteArray(TAG_CFA_PATTERN, RawCfaCorrection.cfaPatternBytes(cfaPattern)))
@@ -437,13 +469,26 @@ object SuperResolutionDngWriter {
add(undefined(TAG_PROFILE_GAIN_TABLE_MAP_2, it.encodeProfileGainTableMap2(ByteOrder.LITTLE_ENDIAN)))
}
}.sortedBy { it.tag }
return TiffDirectories(
primaryEntries = primaryEntries,
exifEntries = exifEntries,
).also {
PLog.i(
TAG,
"DNG focal metadata: physical=${physicalFocalLength ?: "none"}mm " +
"recorded=${effectiveFocalLengthMm ?: "none"}mm " +
"encoded=${focalLength ?: "none"}mm " +
"equivalent35mm=${focalLength35mm ?: "none"}mm"
)
}
}
private fun buildHeader(entries: List<TiffEntry>): ByteArray {
private fun encodeDirectoryEntries(
entries: List<TiffEntry>,
dataBaseOffset: Int,
): Pair<List<EncodedEntry>, ByteArray> {
val dataArea = ByteArrayOutputStream()
val entryCount = entries.size
val dataBaseOffset = 8 + 2 + entryCount * 12 + 4
val encodedEntries = entries.map { entry ->
if (entry.value.size <= 4) {
EncodedEntry(entry, inlineValue(entry.value))
@@ -454,27 +499,72 @@ object SuperResolutionDngWriter {
EncodedEntry(entry, uintBytes(offset.toLong()))
}
}
if ((dataArea.size() and 1) != 0) dataArea.write(0)
val rawOffset = dataBaseOffset + dataArea.size()
return encodedEntries to dataArea.toByteArray()
}
private fun buildHeader(
primaryEntries: List<TiffEntry>,
exifEntries: List<TiffEntry>,
): ByteArray {
val primaryEntryCount = primaryEntries.size
val primaryDataBaseOffset = 8 + 2 + primaryEntryCount * 12 + 4
val (encodedPrimaryEntries, primaryData) = encodeDirectoryEntries(
entries = primaryEntries,
dataBaseOffset = primaryDataBaseOffset,
)
val exifIfdOffset = if (exifEntries.isNotEmpty()) {
primaryDataBaseOffset + primaryData.size
} else {
0
}
val exifDataBaseOffset = if (exifEntries.isNotEmpty()) {
exifIfdOffset + 2 + exifEntries.size * 12 + 4
} else {
primaryDataBaseOffset + primaryData.size
}
val (encodedExifEntries, exifData) = encodeDirectoryEntries(
entries = exifEntries,
dataBaseOffset = exifDataBaseOffset,
)
val rawOffset = exifDataBaseOffset + exifData.size
val out = ByteArrayOutputStream(rawOffset)
out.write(byteArrayOf('I'.code.toByte(), 'I'.code.toByte()))
out.write(ushortBytes(42))
out.write(uintBytes(8))
out.write(ushortBytes(entryCount))
for (encoded in encodedEntries) {
out.write(ushortBytes(primaryEntryCount))
for (encoded in encodedPrimaryEntries) {
out.write(ushortBytes(encoded.entry.tag))
out.write(ushortBytes(encoded.entry.type))
out.write(uintBytes(encoded.entry.count))
val value = if (encoded.entry.tag == TAG_STRIP_OFFSETS) {
uintBytes(rawOffset.toLong())
} else {
encoded.valueOrOffset
val value = when (encoded.entry.tag) {
TAG_STRIP_OFFSETS -> uintBytes(rawOffset.toLong())
TAG_EXIF_IFD_POINTER -> uintBytes(exifIfdOffset.toLong())
else -> encoded.valueOrOffset
}
out.write(value)
}
out.write(uintBytes(0))
out.write(dataArea.toByteArray())
out.write(primaryData)
if (exifEntries.isNotEmpty()) {
check(out.size() == exifIfdOffset) {
"ExifIFD offset mismatch: expected=$exifIfdOffset actual=${out.size()}"
}
out.write(ushortBytes(exifEntries.size))
for (encoded in encodedExifEntries) {
out.write(ushortBytes(encoded.entry.tag))
out.write(ushortBytes(encoded.entry.type))
out.write(uintBytes(encoded.entry.count))
out.write(encoded.valueOrOffset)
}
out.write(uintBytes(0))
out.write(exifData)
}
check(out.size() == rawOffset) {
"RAW strip offset mismatch: expected=$rawOffset actual=${out.size()}"
}
return out.toByteArray()
}
@@ -530,9 +620,9 @@ object SuperResolutionDngWriter {
private fun calculate35mmEquivalent(
characteristics: CameraCharacteristics,
focalLength: Float?,
physicalFocalLength: Float?,
): Int? {
val fl = focalLength?.takeIf { it > 0f } ?: return null
val fl = physicalFocalLength?.takeIf { it > 0f } ?: return null
val sensorSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE) ?: return null
val sensorDiagonal = sqrt(
sensorSize.width.toDouble() * sensorSize.width.toDouble() +
@@ -1111,6 +1201,11 @@ object SuperResolutionDngWriter {
val value: ByteArray,
)
private data class TiffDirectories(
val primaryEntries: List<TiffEntry>,
val exifEntries: List<TiffEntry>,
)
private data class EncodedEntry(
val entry: TiffEntry,
val valueOrOffset: ByteArray,
@@ -1171,12 +1171,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
if (selectedTab == GalleryTab.SYSTEM) {
photo.metadata?.let { m ->
photo.relatedPhoto?.metadata?.let { m ->
currentPhotoMetadataId = photo.id
applyMetadataToEditState(m)
return
}
photo.relatedPhoto?.metadata?.let { m ->
photo.metadata?.let { m ->
currentPhotoMetadataId = photo.id
applyMetadataToEditState(m)
return
@@ -2936,10 +2936,18 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
return@launch
}
val targetMetadata = GalleryManager.loadMetadata(context, targetPhotoId)
?: photo.relatedPhoto?.metadata
?: currentMediaMetadata
?: photo.metadata
val rawBaselineLutId = editRawBaselineLutId.value
val rawBaselineRecipeParams = loadRawBaselineRecipeParams(rawBaselineLutId)
val w = photo.metadata?.width ?: photo.width
val h = photo.metadata?.height ?: photo.height
val w = targetMetadata?.width?.takeIf { it > 0 }
?: photo.relatedPhoto?.width?.takeIf { it > 0 }
?: photo.width
val h = targetMetadata?.height?.takeIf { it > 0 }
?: photo.relatedPhoto?.height?.takeIf { it > 0 }
?: photo.height
val finalCropRegion = editCropRect.value?.let { rectF ->
android.graphics.Rect(
(rectF.left * w).roundToInt(),
@@ -2993,6 +3001,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
currentMediaMetadata = success
photo.metadata = success
photo.relatedPhoto?.metadata = success
// 系统相册项保存后保留 SYSTEM tab,通过 relatedPhoto 展示导入副本的编辑结果。
if (wasSystemPhoto) {
@@ -0,0 +1,17 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RcdShadersTest {
@Test
fun ordinaryBayerBorderUsesPpgWithParityPreservingMirroring() {
val shader = RcdShaders.WRITE_OUTPUT
assertTrue(shader.contains("ivec2 mirrorCoord"))
assertTrue(shader.contains("color = ppgColorAt(coord);"))
assertFalse(shader.contains("borderInterpolateAt"))
assertFalse(shader.contains("inOutermostBorder"))
}
}
@@ -0,0 +1,69 @@
package com.hinnka.mycamera.utils
import org.junit.Assert.assertEquals
import org.junit.Test
class RawDngCropMapperTest {
private val pre = RawCropRect(8, 8, 4048, 3048)
private val post = RawCropRect(0, 0, 4000, 3000)
@Test
fun fullFieldMapsToEntireDngActiveArea() {
val crop = map(crop = RawCropRect(0, 0, 4000, 3000))
assertEquals(RawCropRect(0, 0, 4040, 3040), crop)
}
@Test
fun postCorrectionCropMapsByNormalizedFieldOfView() {
val crop = map(crop = RawCropRect(1000, 750, 3000, 2250))
assertEquals(RawCropRect(1010, 760, 3030, 2280), crop)
}
@Test
fun zoomRatioMapsFullPostZoomArrayToCenteredRawFieldOfView() {
val crop = map(
crop = RawCropRect(0, 0, 4000, 3000),
zoomRatio = 2f,
)
assertEquals(RawCropRect(1010, 760, 3030, 2280), crop)
}
@Test
fun scalerCropAndZoomRatioAreComposedInPostZoomCoordinates() {
val crop = map(
crop = RawCropRect(0, 0, 2000, 3000),
zoomRatio = 2f,
)
assertEquals(RawCropRect(1010, 760, 2020, 2280), crop)
}
@Test
fun distortionOffUsesPreCorrectionCoordinateDomain() {
val crop = map(
crop = RawCropRect(1010, 760, 3030, 2280),
distortionOff = true,
)
assertEquals(RawCropRect(1010, 760, 3030, 2280), crop)
}
private fun map(
crop: RawCropRect?,
zoomRatio: Float = 1f,
distortionOff: Boolean = false,
): RawCropRect {
return RawDngCropMapper.mapToDefaultCrop(
preCorrectionActiveArray = pre,
postCorrectionActiveArray = post,
scalerCropRegion = crop,
zoomRatio = zoomRatio,
usePreCorrectionCoordinateSystem = distortionOff,
targetWidth = 4040,
targetHeight = 3040,
)
}
}
@@ -0,0 +1,104 @@
package com.hinnka.mycamera.utils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
class SuperResolutionDngWriterIfdTest {
@Test
fun `header links ExifIFD and keeps focal length out of IFD0`() {
val primaryEntries = listOf(
tiffEntry(TAG_STRIP_OFFSETS, TYPE_LONG, 1, uintBytes(0)),
tiffEntry(TAG_MAKE, TYPE_ASCII, 7, "Photon\u0000".toByteArray(Charsets.US_ASCII)),
tiffEntry(TAG_EXIF_IFD_POINTER, TYPE_LONG, 1, uintBytes(0)),
).sortedBy(::entryTag)
val exifEntries = listOf(
tiffEntry(TAG_DATETIME_ORIGINAL, TYPE_ASCII, 20, "2026:07:13 12:34:56\u0000".toByteArray(Charsets.US_ASCII)),
tiffEntry(TAG_FOCAL_LENGTH, TYPE_RATIONAL, 1, uintBytes(20) + uintBytes(1)),
).sortedBy(::entryTag)
val header = buildHeader(primaryEntries, exifEntries)
val primaryIfd = readIfd(header, 8)
val exifIfdOffset = primaryIfd.getValue(TAG_EXIF_IFD_POINTER).valueOrOffset
val exifIfd = readIfd(header, exifIfdOffset)
assertTrue(primaryIfd.containsKey(TAG_EXIF_IFD_POINTER))
assertFalse(primaryIfd.containsKey(TAG_FOCAL_LENGTH))
assertTrue(exifIfd.containsKey(TAG_FOCAL_LENGTH))
assertTrue(exifIfd.containsKey(TAG_DATETIME_ORIGINAL))
assertEquals(header.size, primaryIfd.getValue(TAG_STRIP_OFFSETS).valueOrOffset)
val focalLength = exifIfd.getValue(TAG_FOCAL_LENGTH)
assertEquals(20, readUInt(header, focalLength.valueOrOffset))
assertEquals(1, readUInt(header, focalLength.valueOrOffset + 4))
assertTrue(exifIfd.getValue(TAG_DATETIME_ORIGINAL).valueOrOffset > exifIfdOffset)
}
private fun buildHeader(primaryEntries: List<Any>, exifEntries: List<Any>): ByteArray {
val method = SuperResolutionDngWriter::class.java.declaredMethods.single {
it.name == "buildHeader" && it.parameterTypes.size == 2
}
method.isAccessible = true
return method.invoke(SuperResolutionDngWriter, primaryEntries, exifEntries) as ByteArray
}
private fun tiffEntry(tag: Int, type: Int, count: Long, value: ByteArray): Any {
val entryClass = Class.forName(
"com.hinnka.mycamera.utils.SuperResolutionDngWriter\$TiffEntry"
)
val constructor = entryClass.declaredConstructors.single()
constructor.isAccessible = true
return constructor.newInstance(tag, type, count, value)
}
private fun entryTag(entry: Any): Int {
val field = entry.javaClass.getDeclaredField("tag")
field.isAccessible = true
return field.getInt(entry)
}
private fun readIfd(bytes: ByteArray, offset: Int): Map<Int, IfdEntry> {
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val count = buffer.getShort(offset).toInt() and 0xFFFF
return buildMap {
repeat(count) { index ->
val entryOffset = offset + 2 + index * 12
val tag = buffer.getShort(entryOffset).toInt() and 0xFFFF
put(
tag,
IfdEntry(
type = buffer.getShort(entryOffset + 2).toInt() and 0xFFFF,
count = buffer.getInt(entryOffset + 4).toLong() and 0xFFFFFFFFL,
valueOrOffset = buffer.getInt(entryOffset + 8),
)
)
}
}
}
private fun readUInt(bytes: ByteArray, offset: Int): Int =
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getInt(offset)
private fun uintBytes(value: Int): ByteArray =
ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(value).array()
private data class IfdEntry(
val type: Int,
val count: Long,
val valueOrOffset: Int,
)
private companion object {
const val TYPE_ASCII = 2
const val TYPE_LONG = 4
const val TYPE_RATIONAL = 5
const val TAG_MAKE = 271
const val TAG_STRIP_OFFSETS = 273
const val TAG_EXIF_IFD_POINTER = 34665
const val TAG_DATETIME_ORIGINAL = 36867
const val TAG_FOCAL_LENGTH = 37386
}
}