feat: camera raw support for photon tone curve

This commit is contained in:
zhoubinjia committed 2026-07-15 16:23:58 +08:00
1 parent 5b0e43ff6c
commit aff23d7b02
12 files changed
+735 -70

No files matched your search

@@ -0,0 +1,81 @@
package com.hinnka.mycamera.raw
import java.security.MessageDigest
/**
* Camera Raw treats ProfileGainTableMap and ProfileToneCurve as weighted
* profile operations. The DNG tags provide the data, while this embedded Look
* opts the selected camera profile into both operations at full strength.
*/
internal object DngCameraRawProfileXmp {
const val TAG_XMP = 700
private const val CAMERA_RAW_VERSION = "16.0"
private const val PROCESS_VERSION = "15.4"
fun build(
profileLookName: String,
): ByteArray {
require(profileLookName.isNotBlank()) { "Camera Raw Look name must not be blank" }
val escapedProfileLookName = escapeXmlAttribute(profileLookName)
val lookUuid = stableLookUuid(profileLookName)
return """
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="PhotonCamera">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
crs:Version="$CAMERA_RAW_VERSION"
crs:ProcessVersion="$PROCESS_VERSION"
crs:HasSettings="True"
crs:AlreadyApplied="False">
<crs:Look>
<rdf:Description
crs:Name="$escapedProfileLookName"
crs:Amount="1"
crs:UUID="$lookUuid"
crs:SupportsMonochrome="false"
crs:SupportsOutputReferred="false">
<crs:Group>
<rdf:Alt>
<rdf:li xml:lang="x-default">Profiles</rdf:li>
</rdf:Alt>
</crs:Group>
<crs:Parameters
crs:Version="$CAMERA_RAW_VERSION"
crs:ProcessVersion="$PROCESS_VERSION"
crs:ProfileGainTableMap="100"
crs:ProfileToneCurve="100"
crs:ConvertToGrayscale="False"/>
</rdf:Description>
</crs:Look>
</rdf:Description>
</rdf:RDF>
</x:xmpmeta>
""".trimIndent().toByteArray(Charsets.UTF_8)
}
private fun stableLookUuid(profileLookName: String): String {
// The Look identity must not change when its bound base profile is renamed;
// otherwise Camera Raw keeps both identities in its profile cache.
val digest = MessageDigest.getInstance("SHA-256")
.digest("PhotonCamera Camera Raw Look:$profileLookName".toByteArray(Charsets.UTF_8))
return digest.take(16).joinToString(separator = "") { byte ->
"%02X".format(byte.toInt() and 0xFF)
}
}
private fun escapeXmlAttribute(value: String): String = buildString(value.length) {
value.forEach { character ->
append(
when (character) {
'&' -> "&amp;"
'<' -> "&lt;"
'>' -> "&gt;"
'"' -> "&quot;"
'\'' -> "&apos;"
else -> character
}
)
}
}
}
@@ -97,8 +97,7 @@ internal object DngEmbeddedProfile {
fun hasPhotonPgtmProfile(file: File): Boolean {
val profile = readFrom(file) ?: return false
return isPhotonPgtmProfileName(profile.profileName) &&
DngProfileToneCurve.isPhotonPgtmToneCurve(profile.toneCurve)
return DngProfileToneCurve.isPhotonPgtmToneCurve(profile.toneCurve)
}
fun hasGoogleHdrToneCurve(file: File): Boolean {
@@ -15,15 +15,18 @@ internal object DngPgtmDebugRewriter {
private const val TIFF_CLASSIC_MAGIC = 42
private const val TYPE_BYTE = 1
private const val TYPE_ASCII = 2
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(
@@ -34,10 +37,10 @@ internal object DngPgtmDebugRewriter {
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 rewriteProfileGainTableMap2(file, map, profileToneMapMode)
return rewriteProfileGainTableMap(file, map, profileToneMapMode)
}
fun rewriteProfileGainTableMap2(
fun rewriteProfileGainTableMap(
dngFile: File,
profileGainTableMap: DngProfileGainTableMap,
profileToneMapMode: RawProfileToneMapMode = RawProfileToneMapMode.Photon,
@@ -56,23 +59,48 @@ internal object DngPgtmDebugRewriter {
}
val ifd0Offset = raf.readUnsignedInt(byteOrder)
val ifd0 = readIfd(raf, ifd0Offset, byteOrder) ?: return@use false
val profileName = profileNameForToneMapMode(profileToneMapMode)
val profileNameBytes = asciiBytes(profileName)
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_NAME,
type = TYPE_ASCII,
count = profileNameBytes.size.toLong(),
bytes = profileNameBytes
),
TiffValue(
tag = TAG_PROFILE_TONE_CURVE,
type = TYPE_FLOAT,
@@ -86,28 +114,43 @@ internal object DngPgtmDebugRewriter {
tag = TAG_DEFAULT_BLACK_RENDER,
type = TYPE_LONG,
count = 1,
bytes = uintBytes(0, byteOrder)
bytes = uintBytes(1, byteOrder)
),
TiffValue(
tag = TAG_PROFILE_GAIN_TABLE_MAP_2,
type = TYPE_UNDEFINED,
count = pgtmPayload.size.toLong(),
bytes = pgtmPayload
bytes = pgtmPayload,
),
TiffValue(
tag = TAG_SUB_IFDS,
type = TYPE_LONG,
count = subIfdOffsets.size.toLong(),
bytes = encodeLongArray(subIfdOffsets, byteOrder),
)
)
val newIfdOffset = appendIfd0WithReplacements(
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=$profileName " +
"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} ifd0=$ifd0Offset->$newIfdOffset"
"${profileGainTableMap.mapPointsN} gamma=${profileGainTableMap.gamma} " +
"rawIfd=$rawIfdOffset->$newRawIfdOffset " +
"ifd0=$ifd0Offset->$newIfdOffset"
)
true
}
@@ -130,7 +173,7 @@ internal object DngPgtmDebugRewriter {
}
}
private fun profileNameForToneMapMode(mode: RawProfileToneMapMode): String {
private fun profileLookNameForToneMapMode(mode: RawProfileToneMapMode): String {
return when (mode) {
RawProfileToneMapMode.Photon -> DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME
else -> DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME
@@ -144,21 +187,18 @@ internal object DngPgtmDebugRewriter {
}
}
private fun asciiBytes(value: String): ByteArray {
return (value + "\u0000").toByteArray(Charsets.US_ASCII)
}
private fun appendIfd0WithReplacements(
private fun appendIfdWithReplacements(
raf: RandomAccessFile,
original: TiffIfd,
replacements: List<TiffValue>,
removedTags: Set<Int> = emptySet(),
byteOrder: ByteOrder,
): Long? {
if (replacements.isEmpty()) return null
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) {
if (entry.tag !in replacementByTag && entry.tag !in removedTags) {
merged[entry.tag] = IfdValue.Existing(entry)
}
}
@@ -260,6 +300,35 @@ internal object DngPgtmDebugRewriter {
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)) }
@@ -21,16 +21,22 @@ data class DngProfileGainTableMap(
val sourceTag: Int = TAG_PROFILE_GAIN_TABLE_MAP2,
) {
val isValid: Boolean
get() = mapPointsV > 0 &&
mapPointsH > 0 &&
mapPointsN > 0 &&
mapSpacingV > 0.0 &&
mapSpacingH > 0.0 &&
mapInputWeights.size == MAP_INPUT_WEIGHT_COUNT &&
mapInputWeights.all { it.isFinite() } &&
gamma in MIN_GAMMA..MAX_GAMMA &&
gains.size == mapPointsV * mapPointsH * mapPointsN &&
gains.all { it.isFinite() && it in MIN_GAIN_VALUE..MAX_GAIN_VALUE }
get() {
val gainCount = mapPointsV.toLong() * mapPointsH.toLong() * mapPointsN.toLong()
return mapPointsV > 0 &&
mapPointsH > 0 &&
mapPointsN > 0 &&
mapSpacingV.isFinite() && mapSpacingV > 0.0 &&
mapSpacingH.isFinite() && mapSpacingH > 0.0 &&
mapOriginV.isFinite() &&
mapOriginH.isFinite() &&
mapInputWeights.size == MAP_INPUT_WEIGHT_COUNT &&
mapInputWeights.all { it.isFinite() } &&
gamma in MIN_GAMMA..MAX_GAMMA &&
gainCount in 1 until MAX_PROFILE_GAIN_TABLE_MAP_POINTS &&
gains.size.toLong() == gainCount &&
gains.all { it.isFinite() && it in MIN_GAIN_VALUE..MAX_GAIN_VALUE }
}
fun encodeProfileGainTableMap2(byteOrder: ByteOrder): ByteArray {
require(isValid) { "Invalid ProfileGainTableMap2" }
@@ -43,6 +49,16 @@ data class DngProfileGainTableMap(
val buffer = ByteBuffer
.allocate(PROFILE_GAIN_TABLE_MAP2_HEADER_BYTES + gains.size * FLOAT_BYTES)
.order(byteOrder)
putCommonHeader(buffer)
buffer.putInt(DATA_TYPE_FLOAT32)
buffer.putFloat(gamma)
buffer.putFloat(gainMin)
buffer.putFloat(gainMax)
gains.forEach { buffer.putFloat(it) }
return buffer.array()
}
private fun putCommonHeader(buffer: ByteBuffer) {
buffer.putInt(mapPointsV)
buffer.putInt(mapPointsH)
buffer.putDouble(mapSpacingV)
@@ -53,12 +69,6 @@ data class DngProfileGainTableMap(
repeat(MAP_INPUT_WEIGHT_COUNT) { index ->
buffer.putFloat(mapInputWeights[index])
}
buffer.putInt(DATA_TYPE_FLOAT32)
buffer.putFloat(gamma)
buffer.putFloat(gainMin)
buffer.putFloat(gainMax)
gains.forEach { buffer.putFloat(it) }
return buffer.array()
}
override fun equals(other: Any?): Boolean {
@@ -106,6 +116,7 @@ data class DngProfileGainTableMap(
private const val MAP_INPUT_WEIGHT_COUNT = 5
private const val PROFILE_GAIN_TABLE_MAP_HEADER_BYTES = 64
private const val PROFILE_GAIN_TABLE_MAP2_HEADER_BYTES = 80
private const val MAX_PROFILE_GAIN_TABLE_MAP_POINTS = 16_777_216L
private const val FLOAT_BYTES = 4
private const val DATA_TYPE_UINT8 = 0
@@ -6,6 +6,7 @@ internal object DngProfileToneCurve {
private const val POINT_TOLERANCE = 2e-4f
private const val LUT_TOLERANCE = 2e-3f
private const val DNG_PROFILE_TONE_CURVE_POINT_COUNT = 257
private val LINEAR_TONE_CURVE_POINTS = floatArrayOf(0f, 0f, 1f, 1f)
@@ -140,7 +141,16 @@ internal object DngProfileToneCurve {
}
fun photonPgtmToneCurvePoints(): FloatArray {
return PHOTON_PGTM_TONE_CURVE_POINTS.copyOf()
val values = DcpToneCurve(PHOTON_PGTM_TONE_CURVE_POINTS)
.toLut(DNG_PROFILE_TONE_CURVE_POINT_COUNT)
return FloatArray(DNG_PROFILE_TONE_CURVE_POINT_COUNT * 2) { index ->
val pointIndex = index / 2
if ((index and 1) == 0) {
pointIndex.toFloat() / (DNG_PROFILE_TONE_CURVE_POINT_COUNT - 1).toFloat()
} else {
values[pointIndex]
}
}
}
fun photonPgtmToneCurveLut(sampleCount: Int = 256): FloatArray {
@@ -1467,8 +1467,7 @@ class RawDemosaicProcessor {
}
embeddedProfileToneCurveLut != null &&
DngProfileToneCurve.isPhotonPgtmToneCurveLut(embeddedProfileToneCurveLut) &&
DngEmbeddedProfile.isPhotonPgtmProfileName(embeddedDngProfileName) -> {
DngProfileToneCurve.isPhotonPgtmToneCurveLut(embeddedProfileToneCurveLut) -> {
RawProfileToneMapMode.Photon
}
@@ -1612,7 +1611,9 @@ class RawDemosaicProcessor {
"Generated $requestedProfileToneMapMode PGTM for RAW: " +
"grid=${generatedProfileGainTableMap.mapPointsH}x" +
"${generatedProfileGainTableMap.mapPointsV}x" +
"${generatedProfileGainTableMap.mapPointsN}"
"${generatedProfileGainTableMap.mapPointsN} " +
"tag=${generatedProfileGainTableMap.sourceTag} " +
"gamma=${generatedProfileGainTableMap.gamma}"
)
DngPgtmDebugRewriter.rewriteGeneratedPgtmOnRawRefreshIfEnabled(
dngFile = dngFile,
@@ -1,5 +1,6 @@
package com.hinnka.mycamera.utils
import android.graphics.Bitmap
import android.graphics.Rect
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraMetadata
@@ -10,6 +11,7 @@ import android.os.Build
import android.os.SystemClock
import com.hinnka.mycamera.raw.DngProfileGainTableMap
import com.hinnka.mycamera.raw.DngProfileToneCurve
import com.hinnka.mycamera.raw.DngCameraRawProfileXmp
import com.hinnka.mycamera.raw.RawCfaCorrection
import com.hinnka.mycamera.raw.RawMetadata
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
@@ -23,6 +25,7 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.ln
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.roundToLong
import kotlin.math.sqrt
@@ -72,6 +75,8 @@ 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_SUB_IFDS = 330
private const val TAG_XMP = DngCameraRawProfileXmp.TAG_XMP
private const val TAG_EXIF_IFD_POINTER = 34665
private const val TAG_EXPOSURE_TIME = 33434
private const val TAG_F_NUMBER = 33437
@@ -99,7 +104,6 @@ object SuperResolutionDngWriter {
private const val TAG_COLOR_MATRIX_2 = 50722
private const val TAG_CAMERA_CALIBRATION_1 = 50723
private const val TAG_CAMERA_CALIBRATION_2 = 50724
private const val TAG_PROFILE_NAME = 50936
private const val TAG_PROFILE_TONE_CURVE = 50940
private const val TAG_AS_SHOT_NEUTRAL = 50728
private const val TAG_BASELINE_EXPOSURE = 50730
@@ -111,7 +115,7 @@ object SuperResolutionDngWriter {
private const val TAG_NOISE_PROFILE = 51041
private const val TAG_DEFAULT_BLACK_RENDER = 51110
private const val TAG_PROFILE_GAIN_TABLE_MAP_2 = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
private const val PREVIEW_MAX_EDGE = 512
init {
runCatching { System.loadLibrary("my-native-lib") }
}
@@ -232,6 +236,15 @@ object SuperResolutionDngWriter {
}
val imageByteCount = imageBytes?.size?.toLong() ?: uncompressedByteCount
val writtenProfileGainTableMap = profileGainTableMap
?.takeIf { it.isValid }
?.let { map ->
if (map.sourceTag == DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2) {
map
} else {
map.copy(sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2)
}
}
val directories = buildEntries(
width = width,
height = height,
@@ -246,7 +259,7 @@ object SuperResolutionDngWriter {
whiteLevel = encodedWhiteLevel,
imageByteCount = imageByteCount,
baselineExposureEv = baselineExposureEv,
profileGainTableMap = profileGainTableMap?.takeIf { it.isValid },
profileGainTableMap = writtenProfileGainTableMap,
profileName = profileName,
profileToneCurve = profileToneCurve,
imageLayout = imageLayout,
@@ -272,7 +285,13 @@ object SuperResolutionDngWriter {
"rowStepSamples=$rowStepSamples colStepSamples=$colStepSamples " +
"blackLevel=${encodedBlackLevel.joinToString()} whiteLevel=$encodedWhiteLevel " +
"baselineExposureEv=$baselineExposureEv " +
"profileGainTable=${profileGainTableMap?.takeIf { it.isValid }?.let { "${it.mapPointsH}x${it.mapPointsV}x${it.mapPointsN}" } ?: "none"}"
"ifdLayout=raw-ifd0 preview=none " +
"defaultBlackRender=${if (writtenProfileGainTableMap != null) "none" else "default"} " +
"profileToneCurvePoints=${profileToneCurve?.size?.div(2) ?: 0} " +
"cameraRawLook=${if (writtenProfileGainTableMap != null) "pgtm=100,toneCurve=100" else "none"} " +
"profileGainTable=${writtenProfileGainTableMap?.let {
"tag=${it.sourceTag} ${it.mapPointsH}x${it.mapPointsV}x${it.mapPointsN} gamma=${it.gamma}"
} ?: "none"}"
)
true
}.onFailure {
@@ -379,6 +398,13 @@ object SuperResolutionDngWriter {
}
listOf(red, green, blue)
}
val profileLookName = profileName?.takeIf { it.isNotBlank() }
?: DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME
val cameraRawProfileXmp = profileGainTableMap?.let {
DngCameraRawProfileXmp.build(
profileLookName = profileLookName,
)
}
val exifEntries = buildList {
exposureTimeSeconds?.let { add(rationalArray(TAG_EXPOSURE_TIME, listOf(it))) }
@@ -411,6 +437,7 @@ object SuperResolutionDngWriter {
add(long(TAG_ROWS_PER_STRIP, height.toLong()))
add(long(TAG_STRIP_BYTE_COUNTS, imageByteCount))
add(short(TAG_PLANAR_CONFIGURATION, 1))
cameraRawProfileXmp?.let { add(byteArray(TAG_XMP, it)) }
add(ascii(TAG_SOFTWARE, "PhotonCamera"))
add(ascii(TAG_DATETIME, dateTime))
if (exifEntries.isNotEmpty()) {
@@ -425,10 +452,10 @@ object SuperResolutionDngWriter {
!isCfa -> byteArrayOf(1, 6, 0, 0)
else -> byteArrayOf(1, 4, 0, 0)
}))
add(byteArray(TAG_DNG_BACKWARD_VERSION, if (isCfa) {
byteArrayOf(1, 1, 0, 0)
} else {
byteArrayOf(1, 3, 0, 0)
add(byteArray(TAG_DNG_BACKWARD_VERSION, when {
profileGainTableMap != null -> byteArrayOf(1, 3, 0, 0)
isCfa -> byteArrayOf(1, 1, 0, 0)
else -> byteArrayOf(1, 3, 0, 0)
}))
add(ascii(TAG_UNIQUE_CAMERA_MODEL, cameraModel))
if (isCfa) {
@@ -453,14 +480,12 @@ object SuperResolutionDngWriter {
}
add(rationalArray(TAG_AS_SHOT_NEUTRAL, asShotNeutral(captureResult)))
if (profileGainTableMap != null) {
add(long(TAG_DEFAULT_BLACK_RENDER, 0))
add(long(TAG_DEFAULT_BLACK_RENDER, 1))
} else if (!isCfa) {
add(long(TAG_DEFAULT_BLACK_RENDER, 1))
}
add(sRationalArray(TAG_BASELINE_EXPOSURE, listOf(resolvedBaselineExposureEv.toDouble())))
if (profileGainTableMap != null) {
add(ascii(TAG_PROFILE_NAME, profileName?.takeIf { it.isNotBlank() }
?: DngProfileToneCurve.GOOGLE_HDR_PROFILE_NAME))
add(floatArray(TAG_PROFILE_TONE_CURVE, profileToneCurve?.takeIf { it.size >= 4 }
?: DngProfileToneCurve.googleHdrToneCurvePoints()))
}
@@ -513,7 +538,23 @@ object SuperResolutionDngWriter {
private fun buildHeader(
primaryEntries: List<TiffEntry>,
exifEntries: List<TiffEntry>,
): ByteArray = buildHeader(
primaryEntries = primaryEntries,
exifEntries = exifEntries,
rawEntries = emptyList(),
previewByteCount = 0,
)
private fun buildHeader(
primaryEntries: List<TiffEntry>,
exifEntries: List<TiffEntry>,
rawEntries: List<TiffEntry>,
previewByteCount: Int,
): ByteArray {
require(previewByteCount >= 0)
require(rawEntries.isNotEmpty() || previewByteCount == 0) {
"Preview image requires a RAW SubIFD"
}
val primaryEntryCount = primaryEntries.size
val primaryDataBaseOffset = 8 + 2 + primaryEntryCount * 12 + 4
val (encodedPrimaryEntries, primaryData) = encodeDirectoryEntries(
@@ -535,8 +576,25 @@ object SuperResolutionDngWriter {
entries = exifEntries,
dataBaseOffset = exifDataBaseOffset,
)
val rawOffset = exifDataBaseOffset + exifData.size
val out = ByteArrayOutputStream(rawOffset)
val rawIfdOffset = if (rawEntries.isNotEmpty()) {
exifDataBaseOffset + exifData.size
} else {
0
}
val rawDataBaseOffset = if (rawEntries.isNotEmpty()) {
rawIfdOffset + 2 + rawEntries.size * 12 + 4
} else {
exifDataBaseOffset + exifData.size
}
val (encodedRawEntries, rawIfdData) = encodeDirectoryEntries(
entries = rawEntries,
dataBaseOffset = rawDataBaseOffset,
)
val previewOffset = rawDataBaseOffset + rawIfdData.size
val previewPadding = if ((previewByteCount and 1) != 0) 1 else 0
val rawOffset = previewOffset + previewByteCount + previewPadding
val headerEndOffset = if (rawEntries.isNotEmpty()) previewOffset else rawOffset
val out = ByteArrayOutputStream(headerEndOffset)
out.write(byteArrayOf('I'.code.toByte(), 'I'.code.toByte()))
out.write(ushortBytes(42))
out.write(uintBytes(8))
@@ -546,8 +604,11 @@ object SuperResolutionDngWriter {
out.write(ushortBytes(encoded.entry.type))
out.write(uintBytes(encoded.entry.count))
val value = when (encoded.entry.tag) {
TAG_STRIP_OFFSETS -> uintBytes(rawOffset.toLong())
TAG_STRIP_OFFSETS -> uintBytes(
if (rawEntries.isNotEmpty()) previewOffset.toLong() else rawOffset.toLong()
)
TAG_EXIF_IFD_POINTER -> uintBytes(exifIfdOffset.toLong())
TAG_SUB_IFDS -> uintBytes(rawIfdOffset.toLong())
else -> encoded.valueOrOffset
}
out.write(value)
@@ -569,12 +630,170 @@ object SuperResolutionDngWriter {
out.write(uintBytes(0))
out.write(exifData)
}
check(out.size() == rawOffset) {
"RAW strip offset mismatch: expected=$rawOffset actual=${out.size()}"
if (rawEntries.isNotEmpty()) {
check(out.size() == rawIfdOffset) {
"RAW SubIFD offset mismatch: expected=$rawIfdOffset actual=${out.size()}"
}
out.write(ushortBytes(rawEntries.size))
for (encoded in encodedRawEntries) {
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
}
out.write(value)
}
out.write(uintBytes(0))
out.write(rawIfdData)
}
check(out.size() == headerEndOffset) {
"DNG header offset mismatch: expected=$headerEndOffset actual=${out.size()}"
}
return out.toByteArray()
}
private fun buildPreview(
source: Bitmap?,
rawBuffer: ByteBuffer,
rawWidth: Int,
rawHeight: Int,
imageLayout: ImageLayout,
rowStepSamples: Int,
colStepSamples: Int,
blackLevel: FloatArray,
whiteLevel: Int,
): DngPreview {
if (source == null || source.isRecycled || source.width <= 0 || source.height <= 0) {
return buildRawPreview(
rawBuffer = rawBuffer,
rawWidth = rawWidth,
rawHeight = rawHeight,
imageLayout = imageLayout,
rowStepSamples = rowStepSamples,
colStepSamples = colStepSamples,
blackLevel = blackLevel,
whiteLevel = whiteLevel,
)
}
val scale = minOf(
PREVIEW_MAX_EDGE.toFloat() / source.width.toFloat(),
PREVIEW_MAX_EDGE.toFloat() / source.height.toFloat(),
1f,
)
val width = (source.width * scale).roundToInt().coerceAtLeast(1)
val height = (source.height * scale).roundToInt().coerceAtLeast(1)
val sizedBitmap = if (width == source.width && height == source.height) {
source
} else {
Bitmap.createScaledBitmap(source, width, height, true)
}
val readableBitmap = if (sizedBitmap.config == Bitmap.Config.HARDWARE) {
requireNotNull(sizedBitmap.copy(Bitmap.Config.ARGB_8888, false)) {
"Unable to copy hardware DNG preview bitmap"
}
} else {
sizedBitmap
}
return try {
val pixels = IntArray(width * height)
readableBitmap.getPixels(pixels, 0, width, 0, 0, width, height)
val rgb = ByteArray(pixels.size * 3)
var outputIndex = 0
for (pixel in pixels) {
rgb[outputIndex++] = ((pixel ushr 16) and 0xFF).toByte()
rgb[outputIndex++] = ((pixel ushr 8) and 0xFF).toByte()
rgb[outputIndex++] = (pixel and 0xFF).toByte()
}
DngPreview(width = width, height = height, bytes = rgb, source = "bitmap")
} finally {
if (readableBitmap !== sizedBitmap) readableBitmap.recycle()
if (sizedBitmap !== source) sizedBitmap.recycle()
}
}
private fun buildRawPreview(
rawBuffer: ByteBuffer,
rawWidth: Int,
rawHeight: Int,
imageLayout: ImageLayout,
rowStepSamples: Int,
colStepSamples: Int,
blackLevel: FloatArray,
whiteLevel: Int,
): DngPreview {
require(rawWidth > 0 && rawHeight > 0)
val samplesPerPixel = imageLayout.samplesPerPixel
val lastSampleIndex = (rawHeight - 1).toLong() * rowStepSamples.toLong() +
(rawWidth - 1).toLong() * colStepSamples.toLong() +
(samplesPerPixel - 1).toLong()
require(lastSampleIndex >= 0L && (lastSampleIndex + 1L) * 2L <= rawBuffer.capacity().toLong()) {
"RAW preview source exceeds input buffer"
}
val scale = minOf(
PREVIEW_MAX_EDGE.toFloat() / rawWidth.toFloat(),
PREVIEW_MAX_EDGE.toFloat() / rawHeight.toFloat(),
1f,
)
val width = (rawWidth * scale).roundToInt().coerceAtLeast(1)
val height = (rawHeight * scale).roundToInt().coerceAtLeast(1)
val input = rawBuffer.duplicate().order(ByteOrder.nativeOrder())
val rgb = ByteArray(width * height * 3)
var outputIndex = 0
for (previewY in 0 until height) {
val sourceY = (((previewY + 0.5f) * rawHeight) / height)
.toInt()
.coerceIn(0, rawHeight - 1)
for (previewX in 0 until width) {
val sourceX = (((previewX + 0.5f) * rawWidth) / width)
.toInt()
.coerceIn(0, rawWidth - 1)
val sampleOffset = sourceY * rowStepSamples + sourceX * colStepSamples
if (samplesPerPixel == 1) {
val gray = previewSample(
input = input,
sampleIndex = sampleOffset,
blackLevel = blackLevel.firstOrNull() ?: 0f,
whiteLevel = whiteLevel,
)
rgb[outputIndex++] = gray
rgb[outputIndex++] = gray
rgb[outputIndex++] = gray
} else {
repeat(3) { channel ->
rgb[outputIndex++] = previewSample(
input = input,
sampleIndex = sampleOffset + channel,
blackLevel = blackLevel.getOrElse(channel) { blackLevel.firstOrNull() ?: 0f },
whiteLevel = whiteLevel,
)
}
}
}
}
return DngPreview(width = width, height = height, bytes = rgb, source = "raw")
}
private fun previewSample(
input: ByteBuffer,
sampleIndex: Int,
blackLevel: Float,
whiteLevel: Int,
): Byte {
val raw = input.getShort(sampleIndex * 2).toInt() and 0xFFFF
val range = (whiteLevel.toFloat() - blackLevel).coerceAtLeast(1f)
val linear = ((raw.toFloat() - blackLevel) / range).coerceIn(0f, 1f)
val encoded = if (linear <= 0.0031308f) {
linear * 12.92f
} else {
1.055f * linear.toDouble().pow(1.0 / 2.4).toFloat() - 0.055f
}
return (encoded.coerceIn(0f, 1f) * 255f).roundToInt().toByte()
}
private fun writeRawImage(outputStream: OutputStream, rawBuffer: ByteBuffer, byteCount: Int) {
val imageBytes = rawBuffer.duplicate()
imageBytes.position(0)
@@ -1213,6 +1432,13 @@ object SuperResolutionDngWriter {
val exifEntries: List<TiffEntry>,
)
private data class DngPreview(
val width: Int,
val height: Int,
val bytes: ByteArray,
val source: String,
)
private data class EncodedEntry(
val entry: TiffEntry,
val valueOrOffset: ByteArray,
@@ -0,0 +1,56 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
import javax.xml.parsers.DocumentBuilderFactory
class DngCameraRawProfileXmpTest {
@Test
fun `embedded Camera Raw Look enables PGTM and tone curve`() {
val profileLookName = "Photon \"HDR\" & Look"
val document = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
}.newDocumentBuilder().parse(
ByteArrayInputStream(
DngCameraRawProfileXmp.build(
profileLookName = profileLookName,
)
)
)
val cameraRawNamespace = "http://ns.adobe.com/camera-raw-settings/1.0/"
val descriptions = document.getElementsByTagNameNS(
"http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"Description",
)
val rootDescription = descriptions.item(0)
val lookDescription = descriptions.item(1)
val parameters = document.getElementsByTagNameNS(cameraRawNamespace, "Parameters").item(0)
assertNull(rootDescription.attributes
.getNamedItemNS(cameraRawNamespace, "CameraProfile"))
assertEquals(profileLookName, lookDescription.attributes
.getNamedItemNS(cameraRawNamespace, "Name").nodeValue)
assertEquals("1", lookDescription.attributes
.getNamedItemNS(cameraRawNamespace, "Amount").nodeValue)
assertEquals("100", parameters.attributes
.getNamedItemNS(cameraRawNamespace, "ProfileGainTableMap").nodeValue)
assertEquals("100", parameters.attributes
.getNamedItemNS(cameraRawNamespace, "ProfileToneCurve").nodeValue)
assertNull(parameters.attributes
.getNamedItemNS(cameraRawNamespace, "CameraProfile"))
assertTrue(lookDescription.attributes
.getNamedItemNS(cameraRawNamespace, "UUID").nodeValue.matches(Regex("[0-9A-F]{32}")))
}
@Test
fun `Photon HDR Look keeps its existing Camera Raw identity`() {
val xmp = DngCameraRawProfileXmp.build(
profileLookName = DngProfileToneCurve.PHOTON_PGTM_PROFILE_NAME,
).toString(Charsets.UTF_8)
assertTrue(xmp.contains("crs:UUID=\"F73E46FD59ECF8FE66D156114E53ED6F\""))
}
}
@@ -1,6 +1,7 @@
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
@@ -10,10 +11,11 @@ import java.nio.ByteOrder
class DngPgtmDebugRewriterTest {
@Test
fun rewriteProfileGainTableMap2AddsReadableDebugTags() {
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,
@@ -21,38 +23,117 @@ class DngPgtmDebugRewriterTest {
mapSpacingH = 1.0,
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = 2,
mapPointsN = 257,
mapInputWeights = floatArrayOf(0.10f, 0.20f, 0.05f, 0.15f, 0.50f),
gamma = 1f,
gains = floatArrayOf(1.75f, 0.72f)
gamma = 0.5f,
gains = FloatArray(257) { index ->
1.75f + (0.72f - 1.75f) * index.toFloat() / 256f
}
)
assertTrue(DngPgtmDebugRewriter.rewriteProfileGainTableMap2(file, map))
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(map.mapPointsN, decoded?.mapPointsN)
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)
assertEquals(map.gains[1], decoded?.gains?.get(1) ?: 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(1, 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()
}
@@ -70,4 +151,10 @@ class DngPgtmDebugRewriterTest {
.array()
)
}
private data class TestEntry(
val type: Int,
val count: Long,
val inlineOrOffset: ByteArray,
)
}
@@ -0,0 +1,78 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Test
import java.nio.ByteBuffer
import java.nio.ByteOrder
class DngProfileGainTableMapTest {
@Test
fun version2EncoderPreservesGammaAndWritesThe80ByteHeader() {
val map = testMap(
mapPointsN = 2,
gamma = 0.5f,
gains = floatArrayOf(1.75f, 0.72f),
)
val payload = map.encodeProfileGainTableMap2(ByteOrder.LITTLE_ENDIAN)
val buffer = ByteBuffer.wrap(payload).order(ByteOrder.LITTLE_ENDIAN)
assertEquals(80 + map.gains.size * Float.SIZE_BYTES, payload.size)
assertEquals(map.mapPointsV, buffer.int)
assertEquals(map.mapPointsH, buffer.int)
assertEquals(map.mapSpacingV, buffer.double, 0.0)
assertEquals(map.mapSpacingH, buffer.double, 0.0)
assertEquals(map.mapOriginV, buffer.double, 0.0)
assertEquals(map.mapOriginH, buffer.double, 0.0)
assertEquals(map.mapPointsN, buffer.int)
map.mapInputWeights.forEach { assertEquals(it, buffer.float, 0f) }
assertEquals(3, buffer.int)
assertEquals(map.gamma, buffer.float, 0f)
assertEquals(map.gains.min(), buffer.float, 0f)
assertEquals(map.gains.max(), buffer.float, 0f)
map.gains.forEach { assertEquals(it, buffer.float, 0f) }
assertEquals(payload.size, buffer.position())
}
@Test
fun version2EncoderWritesReference64By48By257PayloadSize() {
val mapPointsV = 48
val mapPointsH = 64
val mapPointsN = 257
val map = DngProfileGainTableMap(
mapPointsV = mapPointsV,
mapPointsH = mapPointsH,
mapSpacingV = 1.0 / (mapPointsV - 1),
mapSpacingH = 1.0 / (mapPointsH - 1),
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = mapPointsN,
mapInputWeights = floatArrayOf(0.10f, 0.20f, 0.05f, 0.15f, 0.50f),
gamma = 0.5f,
gains = FloatArray(mapPointsV * mapPointsH * mapPointsN) { 1f },
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2,
)
val payload = map.encodeProfileGainTableMap2(ByteOrder.LITTLE_ENDIAN)
assertEquals(3_158_096, payload.size)
}
private fun testMap(
mapPointsN: Int,
gamma: Float,
gains: FloatArray,
) = DngProfileGainTableMap(
mapPointsV = 1,
mapPointsH = 1,
mapSpacingV = 1.0,
mapSpacingH = 1.0,
mapOriginV = 0.0,
mapOriginH = 0.0,
mapPointsN = mapPointsN,
mapInputWeights = floatArrayOf(0.10f, 0.20f, 0.05f, 0.15f, 0.50f),
gamma = gamma,
gains = gains,
sourceTag = DngProfileGainTableMap.TAG_PROFILE_GAIN_TABLE_MAP2
)
}
@@ -0,0 +1,22 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DngProfileToneCurveTest {
@Test
fun photonPgtmCurveUsesReference257PointSerialization() {
val points = DngProfileToneCurve.photonPgtmToneCurvePoints()
assertEquals(514, points.size)
assertTrue(DcpToneCurve(points).isValid)
repeat(257) { pointIndex ->
assertEquals(pointIndex / 256f, points[pointIndex * 2], 0f)
}
assertEquals(0f, points[1], 0f)
assertEquals(0.15f, points[64 * 2 + 1], 1e-6f)
assertEquals(0.8f, points[192 * 2 + 1], 1e-6f)
assertEquals(1f, points.last(), 0f)
}
}
@@ -37,6 +37,25 @@ class SuperResolutionDngWriterIfdTest {
assertTrue(exifIfd.getValue(TAG_DATETIME_ORIGINAL).valueOrOffset > exifIfdOffset)
}
@Test
fun `profile DNG keeps Camera Raw Look and PGTM2 in raw IFD0 without preview`() {
val primaryEntries = listOf(
tiffEntry(TAG_XMP, TYPE_BYTE, 8, "PGTM-XMP".toByteArray(Charsets.US_ASCII)),
tiffEntry(TAG_STRIP_OFFSETS, TYPE_LONG, 1, uintBytes(0)),
tiffEntry(TAG_STRIP_BYTE_COUNTS, TYPE_LONG, 1, uintBytes(32)),
tiffEntry(TAG_PROFILE_GAIN_TABLE_MAP_2, TYPE_UNDEFINED, 8, ByteArray(8) { it.toByte() }),
).sortedBy(::entryTag)
val header = buildHeader(primaryEntries, emptyList())
val ifd0 = readIfd(header, 8)
assertEquals(header.size, ifd0.getValue(TAG_STRIP_OFFSETS).valueOrOffset)
assertTrue(ifd0.containsKey(TAG_PROFILE_GAIN_TABLE_MAP_2))
assertTrue(ifd0.containsKey(TAG_XMP))
assertFalse(ifd0.containsKey(TAG_SUB_IFDS))
assertTrue(ifd0.getValue(TAG_PROFILE_GAIN_TABLE_MAP_2).valueOrOffset > 8)
}
private fun buildHeader(primaryEntries: List<Any>, exifEntries: List<Any>): ByteArray {
val method = SuperResolutionDngWriter::class.java.declaredMethods.single {
it.name == "buildHeader" && it.parameterTypes.size == 2
@@ -93,12 +112,18 @@ class SuperResolutionDngWriterIfdTest {
private companion object {
const val TYPE_ASCII = 2
const val TYPE_BYTE = 1
const val TYPE_LONG = 4
const val TYPE_RATIONAL = 5
const val TYPE_UNDEFINED = 7
const val TAG_MAKE = 271
const val TAG_STRIP_OFFSETS = 273
const val TAG_STRIP_BYTE_COUNTS = 279
const val TAG_SUB_IFDS = 330
const val TAG_XMP = 700
const val TAG_EXIF_IFD_POINTER = 34665
const val TAG_DATETIME_ORIGINAL = 36867
const val TAG_FOCAL_LENGTH = 37386
const val TAG_PROFILE_GAIN_TABLE_MAP_2 = 52544
}
}