feat: ForwardMatrix support and Lumix RW2 calibration refinement

This commit is contained in:
zhoubinjia committed 2026-09-10 16:33:48 +08:00
1 parent 8dd17a7b37
commit 62d0d25020
16 files changed
+483 -102

No files matched your search

+42 -26
View File
@@ -1053,8 +1053,10 @@ static jobject createRawCameraCalibration(
int illuminant2, bool hasAnalogBalance,
const std::array<float, 3> &analogBalance, bool hasCalibration1,
const Matrix3x3 &cameraCalibration1, bool hasCalibration2,
const Matrix3x3 &cameraCalibration2) {
if (!hasColor1 && !hasColor2) {
const Matrix3x3 &cameraCalibration2, bool hasForward1,
const Matrix3x3 &forwardMatrix1, bool hasForward2,
const Matrix3x3 &forwardMatrix2) {
if (!hasColor1 && !hasColor2 && !hasForward1 && !hasForward2) {
return nullptr;
}
@@ -1064,7 +1066,7 @@ static jobject createRawCameraCalibration(
return nullptr;
}
jmethodID constructor = env->GetMethodID(
calibrationClass, "<init>", "([F[FII[F[F[F)V");
calibrationClass, "<init>", "([F[FII[F[F[F[F[F)V");
if (!constructor) {
env->DeleteLocalRef(calibrationClass);
return nullptr;
@@ -1072,6 +1074,8 @@ static jobject createRawCameraCalibration(
jfloatArray color1 = hasColor1 ? matrixToJava(env, colorMatrix1) : nullptr;
jfloatArray color2 = hasColor2 ? matrixToJava(env, colorMatrix2) : nullptr;
jfloatArray forward1 = hasForward1 ? matrixToJava(env, forwardMatrix1) : nullptr;
jfloatArray forward2 = hasForward2 ? matrixToJava(env, forwardMatrix2) : nullptr;
jfloatArray analog = nullptr;
if (hasAnalogBalance) {
analog = env->NewFloatArray(3);
@@ -1085,9 +1089,11 @@ static jobject createRawCameraCalibration(
hasCalibration2 ? matrixToJava(env, cameraCalibration2) : nullptr;
jobject result = env->NewObject(calibrationClass, constructor, color1, color2,
illuminant1, illuminant2, analog,
calibration1, calibration2);
calibration1, calibration2, forward1, forward2);
if (color1) env->DeleteLocalRef(color1);
if (color2) env->DeleteLocalRef(color2);
if (forward1) env->DeleteLocalRef(forward1);
if (forward2) env->DeleteLocalRef(forward2);
if (analog) env->DeleteLocalRef(analog);
if (calibration1) env->DeleteLocalRef(calibration1);
if (calibration2) env->DeleteLocalRef(calibration2);
@@ -1482,6 +1488,7 @@ static bool prepareDngSdkColor(const Matrix3x3 &colorMatrix1, bool hasColor1,
int ill2 = illuminant2;
bool validColor1 = hasColor1;
bool validColor2 = hasColor2;
const bool promoteSecond = !validColor1 && validColor2;
Matrix3x3 calibration1 = cameraCalibration1;
Matrix3x3 calibration2 = cameraCalibration2;
@@ -1504,8 +1511,8 @@ static bool prepareDngSdkColor(const Matrix3x3 &colorMatrix1, bool hasColor1,
applyDngCameraCalibration(normalizeDngColorMatrix(matrix1), calibration1,
analogMatrix);
prepared.cameraCalibration1 = calibration1;
prepared.forwardMatrix1 = normalizeDngForwardMatrix(forwardMatrix1);
prepared.hasForward1 = hasForward1;
prepared.forwardMatrix1 = normalizeDngForwardMatrix(promoteSecond ? forwardMatrix2 : forwardMatrix1);
prepared.hasForward1 = promoteSecond ? hasForward2 : hasForward1;
if (!validColor2 || prepared.temperature1 <= 0.0f ||
prepared.temperature2 <= 0.0f ||
@@ -2930,7 +2937,8 @@ static void exif_callback(void *datap, int tag, int type, int len,
JNIEXPORT jobject JNICALL
Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
JNIEnv *env, jobject /* this */, jstring filePath, jfloat xr, jfloat yr,
jfloat xg, jfloat yg, jfloat xb, jfloat yb, jfloat xw, jfloat yw) {
jfloat xg, jfloat yg, jfloat xb, jfloat yb, jfloat xw, jfloat yw,
jboolean embeddedCalibrationOnly) {
const char *path = env->GetStringUTFChars(filePath, nullptr);
if (path == nullptr) {
@@ -3315,7 +3323,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
jclass dngDataClass = env->FindClass("com/hinnka/mycamera/raw/DngRawData");
jmethodID constructor =
env->GetMethodID(dngDataClass, "<init>",
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[F[F[FLjava/lang/String;Ljava/lang/String;IIFF[FII[FFIJF[I[I[F[F[ILandroid/graphics/Bitmap;Lcom/hinnka/mycamera/raw/RawCameraCalibration;)V");
"(Ljava/nio/ByteBuffer;IIIIF[F[F[F[F[F[FLjava/lang/String;Ljava/lang/String;IIFF[FII[FFIJF[I[I[F[F[ILandroid/graphics/Bitmap;Lcom/hinnka/mycamera/raw/RawCameraCalibration;Z)V");
jfloatArray blackLevelArray = env->NewFloatArray(4);
for (int i = 0; i < 4; i++) {
@@ -3363,10 +3371,9 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
Matrix3x3 cameraCalibration2 = Matrix3x3::identity();
// Keep the fixed source calibration separate from finalCCM, which is the
// current frame's WB/working-space transform. DNG uses its native
// XYZ->camera ColorMatrix fields; proprietary RAW uses LibRaw's cam_xyz
// table, which the cam_xyz_coeff source path shows is already XYZ->camera
// in this matrix convention.
// current frame's WB/working-space transform. Only embedded DNG calibration
// fields qualify, irrespective of the file extension. LibRaw's cam_xyz is
// populated from its model table and must never become source calibration.
Matrix3x3 fixedColorMatrix1 = Matrix3x3::identity();
Matrix3x3 fixedColorMatrix2 = Matrix3x3::identity();
Matrix3x3 fixedCameraCalibration1 = Matrix3x3::identity();
@@ -3431,7 +3438,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
}
}
if (isDngInput) {
if (hasColor1 || hasColor2 || hasForward1 || hasForward2) {
hasFixedColor1 = hasColor1;
hasFixedColor2 = hasColor2;
fixedColorMatrix1 = colorMatrix1;
@@ -3447,17 +3454,6 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
hasFixedAnalogBalance = true;
fixedAnalogBalance = analogBalance;
}
} else {
// Extraction is independent of the per-photo rendering branch. LibRaw's
// fixed cam_xyz is XYZ -> camera, as used by cam_xyz_coeff; ccm/rgb_cam
// are not substituted for it when this calibration is unavailable.
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
fixedColorMatrix1.m[row * 3 + col] =
RawProcessor.imgdata.color.cam_xyz[row][col];
}
}
hasFixedColor1 = hasMatrixSignal(fixedColorMatrix1);
}
LOGI("dng color metadata: color1=%d color2=%d forward1=%d forward2=%d "
@@ -3499,6 +3495,13 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
LOGI("Using DNG color spec path: whiteXY=%f,%f cameraWhite=%f,%f,%f",
sdkWhiteXy[0], sdkWhiteXy[1], sdkCameraWhite[0],
sdkCameraWhite[1], sdkCameraWhite[2]);
} else if (embeddedCalibrationOnly ||
((hasForward1 || hasForward2) && dngRawTagInfo.hasAsShotWhiteXY)) {
// The engine consumes sensor RGB directly when embedded calibration is
// absent. Do not introduce rgb_cam/cam_xyz and later try to undo them.
LOGI("RAW_CAMERA_CALIBRATION source=%s prepass=wb-camera-rgb "
"librawMatrixFallback=disabled",
hasForward1 || hasForward2 ? "forward-only" : "none");
} else if (!isDngInput &&
computeLibRawCameraToXyzD50(RawProcessor, wb, camToXYZ,
&sdkWhiteXy)) {
@@ -3584,6 +3587,17 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
}
Matrix3x3 finalCCM = targetTransform.multiply(camToXYZ);
if ((embeddedCalibrationOnly ||
((hasForward1 || hasForward2) && dngRawTagInfo.hasAsShotWhiteXY)) && !hasSdkMatrix) {
// The shared linear prepass carries WB camera RGB in this branch; there
// is no XYZ/ProPhoto conversion. Preserve its usual neutral normalization.
finalCCM = Matrix3x3::identity();
for (int i = 0; i < 3; ++i)
finalCCM.m[i * 3 + i] = 1.0f / sdkCameraWhite[i];
if (dngRawTagInfo.hasAsShotWhiteXY) {
sdkWhiteXy = {dngRawTagInfo.asShotWhiteXY[0], dngRawTagInfo.asShotWhiteXY[1]};
}
}
jfloatArray colorMatrixArray = env->NewFloatArray(9);
env->SetFloatArrayRegion(colorMatrixArray, 0, 9, finalCCM.m);
jfloatArray cameraWhiteArray = env->NewFloatArray(3);
@@ -3596,7 +3610,8 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
env, hasFixedColor1, fixedColorMatrix1, hasFixedColor2,
fixedColorMatrix2, fixedIlluminant1, fixedIlluminant2,
hasFixedAnalogBalance, fixedAnalogBalance, hasFixedCalibration1,
fixedCameraCalibration1, hasFixedCalibration2, fixedCameraCalibration2);
fixedCameraCalibration1, hasFixedCalibration2, fixedCameraCalibration2,
hasForward1, forwardMatrix1, hasForward2, forwardMatrix2);
LOGI("finalCCM: %f, %f, %f, %f, %f, %f, %f, %f, %f", finalCCM.m[0],
finalCCM.m[1], finalCCM.m[2], finalCCM.m[3], finalCCM.m[4],
@@ -3699,7 +3714,8 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
exportedLscGridArray, exposureBias, iso,
shutterSpeedLong, aperture, activeArray, defaultCropArray, noiseProfileArray,
warpRectilinearArray, warpRectilinearFlagsArray,
embeddedPreviewBitmap, rawCameraCalibration);
embeddedPreviewBitmap, rawCameraCalibration,
static_cast<jboolean>(dngRawTagInfo.hasAsShotWhiteXY));
// 释放资源
env->ReleaseStringUTFChars(filePath, path);
@@ -212,11 +212,8 @@ internal object DngEmbeddedProfile {
var colorMatrix1 = readMatrix(raf, ifd[TAG_COLOR_MATRIX1], byteOrder)
val colorMatrix2 = readMatrix(raf, ifd[TAG_COLOR_MATRIX2], byteOrder)
if (colorMatrix1 == null && colorMatrix2 != null) {
colorMatrix1 = colorMatrix2
illuminant1 = illuminant2
cameraCalibration1 = cameraCalibration2
}
// Preserve illuminant slots. DngSdkColorSpec promotes a lone second slot
// together with its ForwardMatrix and CameraCalibration when needed.
val forwardMatrix1 = readMatrix(raf, ifd[TAG_FORWARD_MATRIX1], byteOrder)
val forwardMatrix2 = readMatrix(raf, ifd[TAG_FORWARD_MATRIX2], byteOrder)
@@ -64,8 +64,10 @@ data class DngRawData @Keep constructor(
val warpRectilinear: FloatArray?, // repeated [k0, k1, k2, k3, t0, t1, centerH, centerV]
val warpRectilinearFlags: IntArray?, // one DNG opcode flags value per warp
val embeddedPreview: Bitmap? = null,
/** Fixed camera calibration from DNG metadata or LibRaw's camera color table. */
/** Embedded source calibration only; null when neither ColorMatrix nor ForwardMatrix is present. */
val cameraCalibration: RawCameraCalibration? = null,
/** Provenance for FM-only interpolation: never infer this from LibRaw's matrix-derived xy. */
val hasAsShotWhiteXy: Boolean = false,
) : AutoCloseable {
@Volatile
@@ -144,6 +146,7 @@ data class DngRawData @Keep constructor(
if (!embeddedPreview.sameAs(other.embeddedPreview)) return false
} else if (other.embeddedPreview != null) return false
if (cameraCalibration != other.cameraCalibration) return false
if (hasAsShotWhiteXy != other.hasAsShotWhiteXy) return false
return true
}
@@ -176,6 +179,7 @@ data class DngRawData @Keep constructor(
result = 31 * result + (warpRectilinearFlags?.contentHashCode() ?: 0)
result = 31 * result + (embeddedPreview?.hashCode() ?: 0)
result = 31 * result + (cameraCalibration?.hashCode() ?: 0)
result = 31 * result + hasAsShotWhiteXy.hashCode()
return result
}
@@ -46,8 +46,9 @@ internal object DngSdkColorSpec {
metadata: RawMetadata,
workingColorSpace: ColorSpace,
): RawMetadata? {
val whiteXy = whiteXyForProfile(profile, metadata) ?: return null
val temperature = colorTemperatureForXy(whiteXy) ?: return null
val whiteXy = whiteXyForProfile(profile, metadata)
if (!profile.isForwardOnly() && whiteXy == null) return null
val temperature = whiteXy?.let(::colorTemperatureForXy)
val matrix = computeCameraToWorkingMatrix(profile, metadata, workingColorSpace) ?: return null
val white = computeCameraWhite(profile, metadata) ?: return null
return metadata.copy(
@@ -64,6 +65,21 @@ internal object DngSdkColorSpec {
metadata: RawMetadata,
workingColorSpace: ColorSpace
): FloatArray? {
if (profile.isForwardOnly()) {
val matrices = forwardOnlyMatrices(profile, whiteXyForProfile(profile, metadata)) ?: return null
val cameraWhite = computeCameraWhite(profile, metadata) ?: return null
val individualToReference = invertMatrix3x3(multiplyMatrix3x3(
diagonalMatrix(profile.analogBalance.validVectorOrDefault()), matrices.second,
)) ?: return null
val referenceWhite = multiplyMatrixVector(individualToReference, cameraWhite)
if (referenceWhite.any { !it.isFinite() || it <= EPSILON }) return null
// dng_color_spec::SetWhiteXY, with AsShotNeutral supplying camera white
// directly when CM is absent. FM is never treated as XYZ-to-camera.
val cameraToPcs = multiplyMatrix3x3(multiplyMatrix3x3(
matrices.first, diagonalMatrix(referenceWhite.map { 1f / it }.toFloatArray()),
), individualToReference)
return multiplyMatrix3x3(computeXyzD50ToGamut(workingColorSpace) ?: return null, cameraToPcs)
}
return computeCameraToWorkingMatrix(
colorMatrix1 = profile.colorMatrix1,
colorMatrix2 = profile.colorMatrix2,
@@ -83,6 +99,11 @@ internal object DngSdkColorSpec {
profile: DcpProfile,
metadata: RawMetadata
): FloatArray? {
if (profile.isForwardOnly()) {
val neutral = cameraNeutralFromWb(metadata.whiteBalanceGains)
val scale = neutral.maxOrNullValue()
return neutral.map { (it / scale).coerceIn(0.001f, 1f) }.toFloatArray()
}
return computeCameraWhite(
colorMatrix1 = profile.colorMatrix1,
colorMatrix2 = profile.colorMatrix2,
@@ -110,6 +131,9 @@ internal object DngSdkColorSpec {
): FloatArray? {
if (whiteXy.size != 2 || whiteXy.any { !it.isFinite() || it <= 0f } ||
whiteXy.sum() >= 1f) return null
if (profile.isForwardOnly()) {
return computeReferenceCameraToWorkingMatrix(profile, whiteXy, workingColorSpace)
}
val prepared = prepareProfile(
profile.colorMatrix1, profile.colorMatrix2,
profile.forwardMatrix1, profile.forwardMatrix2,
@@ -250,6 +274,12 @@ internal object DngSdkColorSpec {
}
fun whiteXyForProfile(profile: DcpProfile, metadata: RawMetadata): FloatArray? {
if (profile.isForwardOnly()) {
// FM maps neutral to D50 after WB: it cannot recover the scene illuminant.
return metadata.whitePointXy?.takeIf {
it.size == 2 && it.all { value -> value.isFinite() && value > 0f } && it.sum() < 1f
}?.copyOf()
}
val prepared = prepareProfile(
colorMatrix1 = profile.colorMatrix1,
colorMatrix2 = profile.colorMatrix2,
@@ -264,6 +294,42 @@ internal object DngSdkColorSpec {
return neutralToXy(prepared, cameraNeutralFromWb(metadata.whiteBalanceGains))
}
private fun DcpProfile.isForwardOnly(): Boolean =
colorMatrix1 == null && colorMatrix2 == null &&
(forwardMatrix1 != null || forwardMatrix2 != null)
/** Matrix for WB reference-camera RGB, the domain baked for ForwardMatrix-only sources. */
fun computeReferenceCameraToWorkingMatrix(
profile: DcpProfile, whiteXy: FloatArray?, workingColorSpace: ColorSpace,
): FloatArray? {
val forward = forwardOnlyMatrices(profile, whiteXy)?.first ?: return null
return multiplyMatrix3x3(computeXyzD50ToGamut(workingColorSpace) ?: return null, forward)
}
/**
* The FM/CameraCalibration part of dng_color_spec::FindXYZtoCamera_SingleOrDual.
* Adobe's full profile validator requires CM; this extension accepts FM-only data
* with an independently supplied scene white, without inventing a ColorMatrix.
*/
private fun forwardOnlyMatrices(profile: DcpProfile, whiteXy: FloatArray?): Pair<FloatArray, FloatArray>? {
val first = profile.forwardMatrix1.validMatrixOrNull()?.let(::normalizeForwardMatrix)
val second = profile.forwardMatrix2.validMatrixOrNull()?.let(::normalizeForwardMatrix)
if (first == null && second == null) return null
val temp1 = illuminantToTemperature(profile.calibrationIlluminant1)
val temp2 = illuminantToTemperature(profile.calibrationIlluminant2)
val dual = temp1 > 0f && temp2 > 0f && abs(temp1 - temp2) >= EPSILON &&
((first != null && second != null) ||
(profile.cameraCalibration1 != null && profile.cameraCalibration2 != null))
val weight = if (dual) {
hueSatWeightForWhite(profile.calibrationIlluminant1, profile.calibrationIlluminant2,
whiteXy ?: return null)
} else if (first == null) 0f else 1f
val forward = interpolateOptionalMatrix(first, second, weight) ?: return null
val calibration = interpolateMatrix(profile.cameraCalibration1.validMatrixOrIdentity(),
profile.cameraCalibration2.validMatrixOrIdentity(), weight)
return forward to calibration
}
fun hueSatWeightForWhite(illuminant1: Int, illuminant2: Int, whiteXy: FloatArray): Float {
var temperature1 = illuminantToTemperature(illuminant1)
var temperature2 = illuminantToTemperature(illuminant2)
@@ -377,6 +443,7 @@ internal object DngSdkColorSpec {
): PreparedProfile? {
var matrix1 = colorMatrix1.validMatrixOrNull()
var matrix2 = colorMatrix2.validMatrixOrNull()
val promoteSecond = matrix1 == null && matrix2 != null
var illuminant1 = calibrationIlluminant1
var illuminant2 = calibrationIlluminant2
if (matrix1 == null && matrix2 != null) {
@@ -387,14 +454,15 @@ internal object DngSdkColorSpec {
matrix1 ?: return null
val analog = analogBalance.validVectorOrDefault()
val calibration1 = cameraCalibration1.validMatrixOrIdentity()
val calibration1 = (if (promoteSecond) cameraCalibration2 else cameraCalibration1).validMatrixOrIdentity()
val calibration2 = cameraCalibration2.validMatrixOrIdentity()
val analogMatrix = diagonalMatrix(analog)
var temperature1 = illuminantToTemperature(illuminant1)
var temperature2 = illuminantToTemperature(illuminant2)
var preparedColor1 = applyCameraCalibration(normalizeColorMatrix(matrix1), calibration1, analogMatrix)
var preparedForward1 = forwardMatrix1.validMatrixOrNull()?.let(::normalizeForwardMatrix)
var preparedForward1 = (if (promoteSecond) forwardMatrix2 else forwardMatrix1)
.validMatrixOrNull()?.let(::normalizeForwardMatrix)
var preparedCalibration1 = calibration1
var preparedColor2 = matrix2?.let {
@@ -3,6 +3,17 @@ package com.hinnka.mycamera.raw
/** Recovers source white-balanced sensor RGB from the shared linear profile prepass. */
internal object EquivalentCameraCalibration {
fun profileToCameraTransform(metadata: RawMetadata, sourceCameraToProfile: FloatArray): FloatArray {
val calibration = metadata.cameraCalibration
if (calibration?.isForwardOnly == true) {
// FM-only LUTs are baked in WB reference-camera RGB. The shared prepass
// already applied AnalogBalance/CameraCalibration and reference white.
val referenceToProfile = requireNotNull(DngSdkColorSpec.computeReferenceCameraToWorkingMatrix(
calibration.toDcpProfile(), metadata.whitePointXy, ColorSpace.ProPhoto,
)) { "ForwardMatrix interpolation requires the scene white" }
return requireNotNull(DngSdkColorSpec.invertMatrix3x3(referenceToProfile)) {
"ForwardMatrix must be invertible for equivalent-camera rendering"
}
}
val inverse = requireNotNull(DngSdkColorSpec.invertMatrix3x3(sourceCameraToProfile)) {
"Equivalent camera rendering requires an invertible source camera matrix"
}
@@ -44,7 +44,7 @@ internal class EquivalentCameraLutCache(private val target: EquivalentCameraTarg
private val DCP_ASSET_PATH = target.assetPath
private val CACHE_DIRECTORY = "equivalent_camera_calibration_luts"
private val CACHE_EXTENSION = ".bin"
private val SCHEMA_VERSION = 1
private val SCHEMA_VERSION = 2
private val MAGIC = 0x4c434c54 // LCLT
private val SHA256_BYTES = 32
private val HEADER_BYTES = 6 * Int.SIZE_BYTES + SHA256_BYTES
@@ -66,6 +66,25 @@ internal class EquivalentCameraLutCache(private val target: EquivalentCameraTarg
private val lock = Any()
@Volatile private var bundledProfileSha: String? = null
@Volatile private var bundledProfile: DcpProfile? = null
private fun targetProfile(context: Context): DcpProfile = bundledProfile ?: synchronized(lock) {
bundledProfile ?: run {
val info = requireNotNull(DcpManager(context).getAvailableDcps().firstOrNull {
it.isBuiltIn && it.filePath == DCP_ASSET_PATH
}) { "Bundled target DCP ${target.assetPath} is unavailable" }
requireNotNull(DcpProfileParser.resolveProfile(context, info)) {
"Unable to parse target DCP ${target.assetPath}"
}.also { bundledProfile = it }
}
}
/** Direct sensor input is interpreted in the target camera domain, including its WB/CCT. */
fun directCameraWhiteXy(context: Context, metadata: RawMetadata): FloatArray =
requireNotNull(DngSdkColorSpec.whiteXyForProfile(targetProfile(context), metadata)) {
"Unable to resolve target camera white from RAW white balance"
}
private val memory = object : LinkedHashMap<String, EquivalentCameraLuts>(
MAX_MEMORY_ENTRIES, 0.75f, true
) {
@@ -120,12 +139,7 @@ internal class EquivalentCameraLutCache(private val target: EquivalentCameraTarg
size: Int,
): EquivalentCameraLuts {
val sourceProfile = source.toDcpProfile()
val targetInfo = requireNotNull(DcpManager(context).getAvailableDcps().firstOrNull {
it.isBuiltIn && it.filePath == DCP_ASSET_PATH
}) { "Bundled target DCP ${target.assetPath} is unavailable" }
val targetProfile = requireNotNull(
DcpProfileParser.resolveProfile(context, targetInfo)
) { "Unable to parse target DCP ${target.assetPath}" }
val targetProfile = targetProfile(context)
require(targetProfile.hueSatDeltas1?.isValid == true &&
targetProfile.hueSatDeltas2?.isValid == true && targetProfile.lookTable?.isValid == true) {
"Bundled target camera DCP requires both HueSatMaps and its LookTable"
@@ -213,6 +227,8 @@ internal class EquivalentCameraLutCache(private val target: EquivalentCameraTarg
digest.putInt(source.calibrationIlluminant2)
digest.putFloatArray(source.colorMatrix1)
digest.putFloatArray(source.colorMatrix2)
digest.putFloatArray(source.forwardMatrix1)
digest.putFloatArray(source.forwardMatrix2)
digest.putFloatArray(source.analogBalance)
digest.putFloatArray(source.cameraCalibration1)
digest.putFloatArray(source.cameraCalibration2)
@@ -7,6 +7,7 @@ import java.nio.ByteOrder
/** Shared tetrahedral lookup for inverse-DCP camera calibration, in linear WB sensor RGB. */
internal object EquivalentCameraLutShader {
val UNIFORMS = """
uniform bool uEquivalentCameraEnabled;
uniform highp sampler3D uEquivalentCameraLow;
uniform highp sampler3D uEquivalentCameraHigh;
uniform float uEquivalentCameraFirstWeight;
@@ -36,6 +37,7 @@ internal object EquivalentCameraLutShader {
}
vec3 equivalentCameraRgb(vec3 camera) {
if (!uEquivalentCameraEnabled) return camera;
camera = max(camera, vec3(0.0));
// A linear [0,1] section followed by HDR logarithmic nodes. This is a
// lookup coordinate, not sRGB encoding. Extend homogeneously above 16.
@@ -56,8 +58,13 @@ internal class EquivalentCameraLutGl {
private val calibrationTextures = IntArray(2)
private var uploadedCalibrationKey: String? = null
fun bind(program: Int, luts: EquivalentCameraLuts, firstWeight: Float) {
fun bind(program: Int, luts: EquivalentCameraLuts?, firstWeight: Float) {
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uEquivalentCameraEnabled"), if (luts != null) 1 else 0)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uEquivalentCameraFirstWeight"), firstWeight)
// Even a disabled sampler needs a complete texture on a distinct unit.
// These 1x1 placeholders are never sampled; bypass does no LUT baking or disk I/O.
val key = luts?.key ?: "direct-camera-rgb"
val size = luts?.size ?: 1
val units = intArrayOf(1, 5)
val names = arrayOf("uEquivalentCameraLow", "uEquivalentCameraHigh")
if (calibrationTextures.any { it == 0 }) {
@@ -76,8 +83,9 @@ internal class EquivalentCameraLutGl {
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, names[index]), units[index])
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + units[index])
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, calibrationTextures[index])
if (uploadedCalibrationKey == luts.key) continue
val values = if (index == 0) luts.low else luts.high
if (uploadedCalibrationKey == key) continue
val values = if (luts == null) floatArrayOf(0f, 0f, 0f)
else if (index == 0) luts.low else luts.high
val data = ByteBuffer.allocateDirect(values.size * 4).order(ByteOrder.nativeOrder()).asFloatBuffer()
data.put(values).position(0)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST)
@@ -85,11 +93,11 @@ internal class EquivalentCameraLutGl {
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_R, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexImage3D(GLES30.GL_TEXTURE_3D, 0, GLES30.GL_RGB32F, luts.size, luts.size, luts.size,
GLES30.glTexImage3D(GLES30.GL_TEXTURE_3D, 0, GLES30.GL_RGB32F, size, size, size,
0, GLES30.GL_RGB, GLES30.GL_FLOAT, data)
check(GLES30.glGetError() == GLES30.GL_NO_ERROR) { "Equivalent camera calibration LUT upload failed" }
}
uploadedCalibrationKey = luts.key
uploadedCalibrationKey = key
} catch (error: Throwable) {
// A partial upload must never be reused as the previous lens's pair.
GLES30.glDeleteTextures(calibrationTextures.size, calibrationTextures, 0)
@@ -129,7 +129,8 @@ internal data class HncsRenderPlan(
val sourceKey: String,
val colorTemperature: Float?,
val cameraToHncsMatrix: FloatArray,
val calibrationLuts: EquivalentCameraLuts,
/** Null means direct WB Camera RGB, without equivalent-camera conversion. */
val calibrationLuts: EquivalentCameraLuts?,
val calibrationFirstWeight: Float,
/**
* CXMLLut v* calibration values after its value * 0.5 + 1.0 decryption.
@@ -208,7 +209,7 @@ class HncsProfileManager(private val context: Context) {
internal fun resolveLutRenderPlan(
colorTemperature: Float?,
calibrationLuts: EquivalentCameraLuts,
calibrationLuts: EquivalentCameraLuts?,
calibrationFirstWeight: Float,
filmCurveMode: HncsFilmCurveMode = HncsFilmCurveMode.Standard
): HncsRenderPlan? {
@@ -231,7 +232,7 @@ class HncsProfileManager(private val context: Context) {
val profile = parseProfile(info) ?: return null
val cacheKey =
"$profileId|${temperature.toInt()}|${filmCurveMode.persistedValue}|" +
"${calibrationLuts.key}|${calibrationFirstWeight.toBits()}"
"${calibrationLuts?.key ?: "direct-camera-rgb"}|${calibrationFirstWeight.toBits()}"
synchronized(renderPlanCache) {
renderPlanCache[cacheKey]?.let { return it }
}
@@ -313,7 +314,7 @@ class HncsProfileManager(private val context: Context) {
profile: ParsedHncsProfile,
colorTemperature: Float?,
cameraMatrix: FloatArray,
calibrationLuts: EquivalentCameraLuts,
calibrationLuts: EquivalentCameraLuts?,
calibrationFirstWeight: Float,
profileNeutralGains: FloatArray?,
colorMap: HncsColorMap,
@@ -0,0 +1,65 @@
package com.hinnka.mycamera.raw
import java.io.File
import java.io.RandomAccessFile
/** LumixLab libtechorfilter.so: GetCTempInfoForColorCorrection / GetPhotStyleCorrectLUT. */
internal object LumixColorTemperature {
private val kelvinPoints = doubleArrayOf(3000.0, 5000.0, 6500.0, 7500.0)
private val coordinatePoints = doubleArrayOf(256.0, 512.0, 618.0, 725.0)
fun coordinateForKelvin(kelvin: Float?): Int {
val temperature = kelvin?.takeIf { it.isFinite() && it > 0f }?.toDouble() ?: 5000.0
val segment = when {
temperature < kelvinPoints[1] -> 0
temperature < kelvinPoints[2] -> 1
else -> 2
}
val coordinate = coordinatePoints[segment] +
(temperature - kelvinPoints[segment]) *
(coordinatePoints[segment + 1] - coordinatePoints[segment]) /
(kelvinPoints[segment + 1] - kelvinPoints[segment])
// Original ConvertInternal uses double, clamps to uint16, then truncates.
return coordinate.coerceIn(0.0, 65535.0).toInt()
}
fun highWeight(kelvin: Float?, asShotCoordinate: Int? = null): Float {
val coordinate = asShotCoordinate ?: coordinateForKelvin(kelvin)
return ((coordinate - 256) / 256f).coerceIn(0f, 1f)
}
/** Panasonic RW2 IFD0 tag 0x011c is a correction coordinate, not Kelvin. */
fun readAsShotCoordinate(file: File): Int? = runCatching {
RandomAccessFile(file, "r").use { input ->
if (input.length() < 8) return@use null
val order = input.readUnsignedShort()
if (order != 0x4949 && order != 0x4d4d) return@use null
val littleEndian = order == 0x4949
fun ushort(): Int {
val value = input.readUnsignedShort()
return if (littleEndian) ((value and 255) shl 8) or (value ushr 8) else value
}
fun uint(): Long {
val value = input.readInt()
return (if (littleEndian) Integer.reverseBytes(value) else value).toLong() and 0xffffffffL
}
// Ordinary TIFF uses this numeric tag for PlanarConfiguration. Only RW2
// magic 85 qualifies; never read it as a Panasonic coordinate in a DNG.
if (ushort() != 85) return@use null
val offset = uint()
if (offset < 8 || offset > input.length() - 2) return@use null
input.seek(offset)
val count = ushort()
if (count > 4096 || offset + 2L + count * 12L > input.length()) return@use null
repeat(count) {
val entry = input.filePointer
val tag = ushort()
val type = ushort()
val length = uint()
if (tag == 0x011c && type == 3 && length == 1L) return@use ushort()
input.seek(entry + 12)
}
null
}
}.getOrNull()
}
@@ -17,7 +17,8 @@ internal data class LumixRenderPlan(
val tables: LumixPhotoStyleTables,
val highWeight: Float,
val outputClip: Float,
val calibrationLuts: EquivalentCameraLuts,
/** Null means direct WB Camera RGB, without equivalent-camera conversion. */
val calibrationLuts: EquivalentCameraLuts?,
val calibrationFirstWeight: Float = 1f,
)
@@ -30,9 +31,10 @@ internal object LumixProfile {
context: Context,
style: LumixPhotoStyle,
colorTemperature: Float?,
calibrationLuts: EquivalentCameraLuts,
calibrationLuts: EquivalentCameraLuts?,
calibrationFirstWeight: Float,
iso: Int = 100,
colorCorrectionCoordinate: Int? = null,
): LumixRenderPlan {
val tables = cache.getOrPut(style) {
val prefix = "lumix/s9/lut_${style.assetName}"
@@ -43,15 +45,11 @@ internal object LumixProfile {
readTable(context, "${prefix}_high.bin", 1, 33),
)
}
// LumixLab's default CCT coordinate is 256 at 3000 K and 512 at 5000 K.
// The cube interpolation clamps to those coordinates, not to 6500 K.
val temperature = colorTemperature?.takeIf { it.isFinite() && it > 0f } ?: 5000f
// Native stores the CCT coordinate as an integer before interpolating the tables.
val coordinate = (256f + (temperature.coerceIn(3000f, 5000f) - 3000f) * 256f / 2000f).toInt()
val highWeight = LumixColorTemperature.highWeight(colorTemperature, colorCorrectionCoordinate)
val clip = if (style == LumixPhotoStyle.VLog) {
when (iso) { 320 -> 3300; 400 -> 3400; 500 -> 3496; else -> 3596 }
} else 4095
return LumixRenderPlan(tables, (coordinate - 256) / 256f, clip / 4095f, calibrationLuts, calibrationFirstWeight)
return LumixRenderPlan(tables, highWeight, clip / 4095f, calibrationLuts, calibrationFirstWeight)
}
private fun readTable(context: Context, path: String, kind: Int, dimension: Int): FloatArray {
@@ -23,6 +23,8 @@ class RawCameraCalibration(
analogBalance: FloatArray? = null,
cameraCalibration1: FloatArray? = null,
cameraCalibration2: FloatArray? = null,
forwardMatrix1: FloatArray? = null,
forwardMatrix2: FloatArray? = null,
) {
/** DNG ColorMatrix1, with XYZ as input and camera RGB as output. */
val colorMatrix1: FloatArray? = colorMatrix1?.copyAndValidate("colorMatrix1")
@@ -30,6 +32,10 @@ class RawCameraCalibration(
/** DNG ColorMatrix2, with XYZ as input and camera RGB as output. */
val colorMatrix2: FloatArray? = colorMatrix2?.copyAndValidate("colorMatrix2")
val forwardMatrix1: FloatArray? = forwardMatrix1?.copyAndValidate("forwardMatrix1")
val forwardMatrix2: FloatArray? = forwardMatrix2?.copyAndValidate("forwardMatrix2")
val isForwardOnly: Boolean get() = colorMatrix1 == null && colorMatrix2 == null
/** DNG AnalogBalance, if the source profile supplied it. */
val analogBalance: FloatArray? = analogBalance?.copyAndValidate("analogBalance", 3)
@@ -42,18 +48,18 @@ class RawCameraCalibration(
cameraCalibration2?.copyAndValidate("cameraCalibration2")
init {
require(colorMatrix1 != null || colorMatrix2 != null) {
"Raw camera calibration requires at least one ColorMatrix"
require(colorMatrix1 != null || colorMatrix2 != null ||
forwardMatrix1 != null || forwardMatrix2 != null) {
"Raw camera calibration requires a ColorMatrix or ForwardMatrix"
}
}
/**
* Converts this fixed calibration to a matrix-only DCP profile.
*
* ForwardMatrix, HueSatMap, LookTable, and ToneCurve are intentionally
* absent. In particular, a ForwardMatrix is never substituted for a
* ColorMatrix because this object is the fixed XYZ-to-camera source used
* to bake the lens LUTs.
* Retains both matrix directions. A ForwardMatrix is never inverted and
* relabeled ColorMatrix. Forward-only sources use reference WB camera RGB.
* HueSatMap, LookTable and ToneCurve are not part of this fixed calibration.
*/
fun toDcpProfile(profileName: String = "Raw camera calibration"): DcpProfile {
return DcpProfile(
@@ -65,8 +71,8 @@ class RawCameraCalibration(
supportsOverrange = false,
colorMatrix1 = colorMatrix1?.copyOf(),
colorMatrix2 = colorMatrix2?.copyOf(),
forwardMatrix1 = null,
forwardMatrix2 = null,
forwardMatrix1 = forwardMatrix1?.copyOf(),
forwardMatrix2 = forwardMatrix2?.copyOf(),
hueSatDeltas1 = null,
hueSatDeltas2 = null,
lookTable = null,
@@ -84,6 +90,8 @@ class RawCameraCalibration(
calibrationIlluminant2 == other.calibrationIlluminant2 &&
colorMatrix1.contentEqualsNullable(other.colorMatrix1) &&
colorMatrix2.contentEqualsNullable(other.colorMatrix2) &&
forwardMatrix1.contentEqualsNullable(other.forwardMatrix1) &&
forwardMatrix2.contentEqualsNullable(other.forwardMatrix2) &&
analogBalance.contentEqualsNullable(other.analogBalance) &&
cameraCalibration1.contentEqualsNullable(other.cameraCalibration1) &&
cameraCalibration2.contentEqualsNullable(other.cameraCalibration2)
@@ -94,6 +102,8 @@ class RawCameraCalibration(
result = 31 * result + calibrationIlluminant2
result = 31 * result + (colorMatrix1?.contentHashCode() ?: 0)
result = 31 * result + (colorMatrix2?.contentHashCode() ?: 0)
result = 31 * result + (forwardMatrix1?.contentHashCode() ?: 0)
result = 31 * result + (forwardMatrix2?.contentHashCode() ?: 0)
result = 31 * result + (analogBalance?.contentHashCode() ?: 0)
result = 31 * result + (cameraCalibration1?.contentHashCode() ?: 0)
result = 31 * result + (cameraCalibration2?.contentHashCode() ?: 0)
@@ -105,17 +115,19 @@ class RawCameraCalibration(
"illuminant1=$calibrationIlluminant1, " +
"illuminant2=$calibrationIlluminant2, " +
"colorMatrix1=${colorMatrix1?.contentToString()}, " +
"colorMatrix2=${colorMatrix2?.contentToString()})"
"colorMatrix2=${colorMatrix2?.contentToString()}, " +
"forwardMatrix1=${forwardMatrix1?.contentToString()}, " +
"forwardMatrix2=${forwardMatrix2?.contentToString()})"
}
companion object {
/**
* Imports only the fixed DNG calibration fields from [profile].
* Profiles containing only ForwardMatrix data are intentionally
* rejected because ForwardMatrix has the opposite direction.
* ForwardMatrix-only profiles retain their own direction and input domain.
*/
fun fromProfile(profile: DcpProfile): RawCameraCalibration? {
if (profile.colorMatrix1 == null && profile.colorMatrix2 == null) return null
if (profile.colorMatrix1 == null && profile.colorMatrix2 == null &&
profile.forwardMatrix1 == null && profile.forwardMatrix2 == null) return null
return RawCameraCalibration(
colorMatrix1 = profile.colorMatrix1,
colorMatrix2 = profile.colorMatrix2,
@@ -124,6 +136,8 @@ class RawCameraCalibration(
analogBalance = profile.analogBalance,
cameraCalibration1 = profile.cameraCalibration1,
cameraCalibration2 = profile.cameraCalibration2,
forwardMatrix1 = profile.forwardMatrix1,
forwardMatrix2 = profile.forwardMatrix2,
)
}
@@ -244,6 +244,7 @@ class RawDemosaicProcessor {
xg: Float, yg: Float,
xb: Float, yb: Float,
xw: Float, yw: Float,
embeddedCalibrationOnly: Boolean,
): DngRawData?
private external fun estimateMgcReferenceSignalNative(
@@ -2395,6 +2396,7 @@ class RawDemosaicProcessor {
var embeddedDngJpegPreview: Bitmap? = null
var dngWarpRectilinear: FloatArray? = null
var dngWarpRectilinearFlags: IntArray? = null
var lumixColorCorrectionCoordinate: Int? = null
val requestedColorEngine = rawRenderingEngine
val hasDcpSelection = dcpRenderPlan != null || rawDcpId != null
val profileWorkingColorSpace = ColorSpace.ProPhoto
@@ -2404,6 +2406,9 @@ class RawDemosaicProcessor {
val sourceProfileGainTableMap = metadata?.profileGainTableMap?.takeIf { it.isValid }
if (dngFile != null) {
if (requestedColorEngine.isLumix) {
lumixColorCorrectionCoordinate = LumixColorTemperature.readAsShotCoordinate(dngFile)
}
val hasClassicTiffHeader = DngProfileGainTableMap.hasClassicTiffHeader(dngFile)
embeddedDngProfiles = if (hasClassicTiffHeader) {
DngEmbeddedProfile.readAllFrom(dngFile)
@@ -2421,8 +2426,13 @@ class RawDemosaicProcessor {
profileWorkingColorSpace.xg, profileWorkingColorSpace.yg,
profileWorkingColorSpace.xb, profileWorkingColorSpace.yb,
profileWorkingColorSpace.xw, profileWorkingColorSpace.yw,
embeddedCalibrationOnly = requestedColorEngine.isLumix || requestedColorEngine.isHncs,
)
if (dngRawData == null) {
if (requestedColorEngine.isLumix || requestedColorEngine.isHncs) {
PLog.e(TAG, "Camera RGB engine RAW decode failed; color-converted fallback is disabled")
return@withContext null
}
return@withContext RawProcessor.processAndToBitmap(
dngFile,
aspectRatio,
@@ -2453,12 +2463,41 @@ class RawDemosaicProcessor {
actualHeight = dngRawData.height
actualRowStride = dngRawData.rowStride
actualSamplesPerPixel = dngRawData.samplesPerPixel.coerceAtLeast(1)
val primarySourceProfile = embeddedDngProfiles
.firstOrNull { it.id == DngEmbeddedProfile.PRIMARY_PROFILE_ID }?.profile
val embeddedCalibration = primarySourceProfile?.let(RawCameraCalibration::fromProfile)
?: dngRawData.cameraCalibration
// Keep the existing handling for FM-only files without an independent scene
// white. In camera-domain engines that means bypass, not guessed interpolation.
val sourceCalibration = embeddedCalibration?.takeUnless {
it.isForwardOnly && !dngRawData.hasAsShotWhiteXy
}
val importedMetadata = convertDngRawDataToMetadata(dngRawData, exposureBias, actualMetadata)
// The TIFF reader can expose embedded standard calibration even when LibRaw
// does not promote that IFD for a proprietary RAW. Keep the prepass and the
// equivalent LUT on the same embedded source, never a LibRaw table matrix.
val calibratedMetadata = if (sourceCalibration?.isForwardOnly == true) {
// Do not inherit a previous camera/file's white point. FM cannot recover it
// from AsShotNeutral; native exports AsShotWhiteXY when it is present.
val whiteXy = dngRawData.whitePointXy.takeIf {
it.size == 2 && it.all { value -> value.isFinite() && value > 0f } && it.sum() < 1f
}
val source = primarySourceProfile ?: sourceCalibration.toDcpProfile()
requireNotNull(DngSdkColorSpec.resolveSourceMetadata(source,
importedMetadata.copy(whitePointXy = whiteXy, colorTemperature = whiteXy?.let(DngSdkColorSpec::colorTemperatureForXy)),
profileWorkingColorSpace)) {
"ForwardMatrix calibration requires an independent scene white for dual-illuminant interpolation"
}
} else if ((requestedColorEngine.isLumix || requestedColorEngine.isHncs) &&
dngRawData.cameraCalibration == null
) {
primarySourceProfile?.let {
DngSdkColorSpec.resolveSourceMetadata(it, importedMetadata, profileWorkingColorSpace)
} ?: importedMetadata
} else importedMetadata
actualMetadata = applyDngMetadataOverrides(
metadata = convertDngRawDataToMetadata(dngRawData, exposureBias, actualMetadata).copy(
cameraCalibration = embeddedDngProfiles
.firstOrNull { it.id == DngEmbeddedProfile.PRIMARY_PROFILE_ID }
?.profile?.let(RawCameraCalibration::fromProfile)
?: dngRawData.cameraCalibration,
metadata = calibratedMetadata.copy(
cameraCalibration = sourceCalibration,
),
rawBlackLevelMode = rawBlackLevelMode,
rawCustomBlackLevel = rawCustomBlackLevel,
@@ -2481,9 +2520,37 @@ class RawDemosaicProcessor {
coreImagingTuning = processLocalCoreImagingTuning.normalized(),
)
actualRotation = if (dngRawData.rotation != 0) dngRawData.rotation else rotation
if ((requestedColorEngine.isLumix || requestedColorEngine.isHncs) &&
actualMetadata.cameraCalibration == null
) {
val target = if (requestedColorEngine.isLumix) {
EquivalentCameraTarget.LumixS9
} else {
EquivalentCameraTarget.HasselbladX1D50
}
// Without source calibration, interpret sensor RGB directly as the target
// camera's RGB. Its DCP is used only to infer the style's CCT from as-shot WB;
// no source matrix or inverse-DCP LUT is applied to the pixels.
val whiteXy = target.calibrationCache.directCameraWhiteXy(context, actualMetadata)
actualMetadata = actualMetadata.copy(
whitePointXy = whiteXy,
colorTemperature = DngSdkColorSpec.colorTemperatureForXy(whiteXy),
)
PLog.i(TAG, "RAW_CAMERA_CALIBRATION source=none engine=$requestedColorEngine " +
"equivalent=disabled input=wb-camera-rgb cctSource=target-profile " +
"librawMatrixFallback=disabled")
}
embeddedDngRenderPlan = selectedEmbeddedDngProfile?.let { selectedProfile ->
// Keep the pre-existing matrix fallback for an unresolved FM-only source.
// In particular, a derived/fallback CCT must not silently activate its FM.
val renderProfile = if (embeddedCalibration?.isForwardOnly == true &&
sourceCalibration == null && selectedProfile.profile?.colorMatrix1 == null &&
selectedProfile.profile?.colorMatrix2 == null
) selectedProfile.copy(profile = selectedProfile.profile?.copy(
forwardMatrix1 = null, forwardMatrix2 = null,
)) else selectedProfile
DngEmbeddedProfile.resolveRenderPlan(
entry = selectedProfile,
entry = renderProfile,
metadata = actualMetadata,
workingColorSpace = profileWorkingColorSpace
)
@@ -2550,16 +2617,16 @@ class RawDemosaicProcessor {
}
val hncsRenderPlan = if (requestedColorEngine.isHncs) {
val calibration = EquivalentCameraTarget.HasselbladX1D50.calibrationCache
val sourceCalibration = actualMetadata.cameraCalibration
check(dngFile != null || sourceCalibration != null) {
"HNCS requires fixed source ColorMatrix calibration for camera capture"
}
HncsProfileManager(context.applicationContext).resolveLutRenderPlan(
colorTemperature = actualMetadata.colorTemperature,
calibrationLuts = calibration.resolve(
context, requireNotNull(actualMetadata.cameraCalibration) {
"HNCS requires fixed source ColorMatrix calibration"
},
),
calibrationFirstWeight = calibration.firstWeight(
calibrationLuts = sourceCalibration?.let { calibration.resolve(context, it) },
calibrationFirstWeight = if (sourceCalibration != null) calibration.firstWeight(
requireNotNull(actualMetadata.whitePointXy) { "HNCS requires the source white point" },
),
) else 1f,
filmCurveMode = rawHncsFilmCurveMode,
)
} else null
@@ -2917,7 +2984,12 @@ class RawDemosaicProcessor {
metadata = actualMetadata,
dcpRenderPlan = activeDcpRenderPlan,
)
val cameraInputTransform = if (colorEngine.isLumix || colorEngine.isHncs) {
val directCameraInput = dngFile != null && actualMetadata.cameraCalibration == null &&
(colorEngine.isLumix || colorEngine.isHncs)
val cameraInputTransform = if (directCameraInput) {
// Native exported a WB-only prepass matrix; these values are already camera RGB.
floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f)
} else if (colorEngine.isLumix || colorEngine.isHncs) {
EquivalentCameraCalibration.profileToCameraTransform(
actualMetadata, linearColorCorrectionMatrix,
)
@@ -2927,17 +2999,20 @@ class RawDemosaicProcessor {
val profileToEngineTransform = cameraInputTransform
val lumixRenderPlan = if (colorEngine.isLumix) {
check(profileWorkingColorSpace == ColorSpace.ProPhoto)
val sourceCalibration = actualMetadata.cameraCalibration
check(dngFile != null || sourceCalibration != null) {
"Lumix requires fixed source ColorMatrix calibration for camera capture"
}
LumixProfile.createRenderPlan(
context, normalizedToneMappingParameters.lumixPhotoStyle, actualMetadata.colorTemperature,
calibrationLuts = EquivalentCameraTarget.LumixS9.calibrationCache.resolve(
context, requireNotNull(actualMetadata.cameraCalibration) {
"Lumix rendering requires fixed source ColorMatrix calibration"
},
),
calibrationFirstWeight = EquivalentCameraTarget.LumixS9.calibrationCache.firstWeight(
calibrationLuts = sourceCalibration?.let {
EquivalentCameraTarget.LumixS9.calibrationCache.resolve(context, it)
},
calibrationFirstWeight = if (sourceCalibration != null) EquivalentCameraTarget.LumixS9.calibrationCache.firstWeight(
requireNotNull(actualMetadata.whitePointXy),
),
) else 1f,
iso = actualMetadata.iso,
colorCorrectionCoordinate = lumixColorCorrectionCoordinate,
)
} else null
if (colorEngine.isLumix) {
@@ -94,9 +94,10 @@ data class RawMetadata(
val colorCorrectionMatrix: FloatArray,
/**
* Camera2 static lens calibration. This is kept separate from
* Camera2 static lens calibration or calibration embedded in an imported RAW.
* LibRaw's built-in camera matrices are never used for this field. Kept separate from
* [colorCorrectionMatrix], which is resolved for the current frame/WB.
* The matrices retain DNG ColorMatrix direction: XYZ -> camera RGB.
* CM retains XYZ -> camera direction; FM retains WB reference camera -> XYZ D50.
*/
val cameraCalibration: RawCameraCalibration? = null,
@@ -3,9 +3,74 @@ package com.hinnka.mycamera.raw
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.assertNull
import org.junit.Test
class DngSourceColorMetadataTest {
private val fm1 = floatArrayOf(0.4409f, 0.4176f, 0.1058f, 0.2049f, 0.7639f, 0.0311f, 0.0759f, 0.0003f, 0.7489f)
private val fm2 = floatArrayOf(0.4594f, 0.3471f, 0.1578f, 0.2504f, 0.7023f, 0.0473f, 0.1023f, 0.0032f, 0.7195f)
@Test
fun forwardOnlyUsesSdkReciprocalTemperatureAndPreservesSlots() {
val source = RawCameraCalibration(null, null, 17, 21, forwardMatrix1 = fm1, forwardMatrix2 = fm2)
assertTrue(source.isForwardOnly)
assertEquals(source, RawCameraCalibration.fromProfile(source.toDcpProfile()))
val white = floatArrayOf(0.3457f, 0.3585f)
val temperature = DngSdkColorSpec.colorTemperatureForXy(white)!!.toDouble()
// dng_camera_profile::IlluminantToTemperature: A=2850, D65=6500.
val firstWeight = ((1.0 / temperature - 1.0 / 6500.0) /
(1.0 / 2850.0 - 1.0 / 6500.0)).coerceIn(0.0, 1.0)
val normalized1 = sdkNormalizeForward(fm1)
val normalized2 = sdkNormalizeForward(fm2)
val expected = FloatArray(9) { (normalized1[it] * firstWeight + normalized2[it] * (1.0 - firstWeight)).toFloat() }
val workingFromPcs = DngSdkColorSpec.computeXyzD50ToGamut(ColorSpace.ProPhoto)!!
val result = DngSdkColorSpec.computeReferenceCameraToWorkingMatrix(source.toDcpProfile(), white, ColorSpace.ProPhoto)!!
val actual = DngSdkColorSpec.multiplyMatrix3x3(DngSdkColorSpec.invertMatrix3x3(workingFromPcs)!!, result)
assertArrayEquals(expected, actual, 0.000002f)
val reversed = RawCameraCalibration(null, null, 21, 17, forwardMatrix1 = fm2, forwardMatrix2 = fm1)
assertArrayEquals(result, DngSdkColorSpec.computeReferenceCameraToWorkingMatrix(reversed.toDcpProfile(), white, ColorSpace.ProPhoto)!!, 0.000002f)
assertNull(DngSdkColorSpec.computeReferenceCameraToWorkingMatrix(source.toDcpProfile(), null, ColorSpace.ProPhoto))
}
@Test
fun forwardOnlyFactorsIndividualCalibrationAndWhiteExactlyOnce() {
val source = RawCameraCalibration(null, null, 17, 21,
analogBalance = floatArrayOf(1.1f, 1f, 0.9f),
cameraCalibration1 = floatArrayOf(1f, 0.02f, 0f, 0f, 1f, 0f, 0f, 0.01f, 1f),
cameraCalibration2 = floatArrayOf(1f, 0.04f, 0f, 0f, 1f, 0f, 0f, 0.02f, 1f),
forwardMatrix1 = fm1, forwardMatrix2 = fm2)
val resolved = DngSdkColorSpec.resolveSourceMetadata(source.toDcpProfile(),
metadata().copy(whitePointXy = floatArrayOf(0.3457f, 0.3585f)), ColorSpace.ProPhoto)!!
val neutralOutput = multiply(resolved.colorCorrectionMatrix, resolved.cameraWhite)
assertArrayEquals(floatArrayOf(1f, 1f, 1f), neutralOutput, 0.002f)
val recovery = EquivalentCameraCalibration.profileToCameraTransform(resolved, resolved.colorCorrectionMatrix)
val referenceNeutral = multiply(recovery, neutralOutput)
assertArrayEquals(floatArrayOf(1f, 1f, 1f), referenceNeutral, 0.000002f)
}
@Test
fun aLoneSecondSlotKeepsItsForwardAndCalibration() {
val cm = floatArrayOf(0.8f, 0.1f, 0.05f, 0.1f, 0.9f, 0.05f, 0.02f, 0.1f, 0.7f)
val calibration = floatArrayOf(1.1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0.9f)
val first = RawCameraCalibration(cm, null, 21, 0, cameraCalibration1 = calibration, forwardMatrix1 = fm2)
val second = RawCameraCalibration(null, cm, 0, 21, cameraCalibration2 = calibration, forwardMatrix2 = fm2)
assertArrayEquals(DngSdkColorSpec.computeCameraToWorkingMatrix(first.toDcpProfile(), metadata(), ColorSpace.ProPhoto)!!,
DngSdkColorSpec.computeCameraToWorkingMatrix(second.toDcpProfile(), metadata(), ColorSpace.ProPhoto)!!, 0f)
}
private fun sdkNormalizeForward(matrix: FloatArray): FloatArray {
val white = doubleArrayOf(0.9642957, 1.0, 0.8251046)
return FloatArray(9) { index ->
val row = index / 3
(matrix[index].toDouble() * white[row] /
(matrix[row * 3].toDouble() + matrix[row * 3 + 1] + matrix[row * 3 + 2])).toFloat()
}
}
private fun multiply(matrix: FloatArray, vector: FloatArray) = FloatArray(3) { row ->
(0..2).sumOf { column -> (matrix[row * 3 + column] * vector[column]).toDouble() }.toFloat()
}
@Test
fun asShotNeutralReplacesStaleCaptureWhiteAndCalibrationTogether() {
val source = RawCameraCalibration(
@@ -0,0 +1,42 @@
package com.hinnka.mycamera.raw
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class LumixColorTemperatureTest {
@Test
fun originalCoordinatesTruncateBeforeMixingAndClampAtEndpoints() {
assertEquals(256, LumixColorTemperature.coordinateForKelvin(3000f))
assertEquals(512, LumixColorTemperature.coordinateForKelvin(5000f))
assertEquals(618, LumixColorTemperature.coordinateForKelvin(6500f))
assertEquals(725, LumixColorTemperature.coordinateForKelvin(7500f))
assertEquals(0f, LumixColorTemperature.highWeight(2000f), 0f)
assertEquals(0.5f, LumixColorTemperature.highWeight(4000f), 0f)
assertEquals(128f / 256f, LumixColorTemperature.highWeight(4007f), 0f)
assertEquals(1f, LumixColorTemperature.highWeight(9000f), 0f)
assertEquals(1f, LumixColorTemperature.highWeight(null), 0f)
}
@Test
fun rw2CorrectionCoordinateOverridesKelvinButOrdinaryTiffTagDoesNot() {
for (order in listOf(ByteOrder.LITTLE_ENDIAN, ByteOrder.BIG_ENDIAN)) {
val file = File.createTempFile("lumix-temperature", ".rw2")
try {
val bytes = ByteBuffer.allocate(26).order(order)
bytes.putShort(if (order == ByteOrder.LITTLE_ENDIAN) 0x4949 else 0x4d4d)
bytes.putShort(85).putInt(8).putShort(1)
bytes.putShort(0x011c).putShort(3).putInt(1).putShort(320).putShort(0).putInt(0)
file.writeBytes(bytes.array())
assertEquals(320, LumixColorTemperature.readAsShotCoordinate(file))
assertEquals(0.25f, LumixColorTemperature.highWeight(6500f, LumixColorTemperature.readAsShotCoordinate(file)), 0f)
bytes.putShort(2, 42)
file.writeBytes(bytes.array())
assertNull(LumixColorTemperature.readAsShotCoordinate(file))
} finally { file.delete() }
}
}
}