From 62d0d250206e8b09b812a8fc63154ef50e300e48 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Thu, 10 Sep 2026 16:33:48 +0800 Subject: [PATCH] feat: ForwardMatrix support and Lumix RW2 calibration refinement --- app/src/main/cpp/native-lib.cpp | 68 ++++++---- .../hinnka/mycamera/raw/DngEmbeddedProfile.kt | 7 +- .../com/hinnka/mycamera/raw/DngRawData.kt | 6 +- .../hinnka/mycamera/raw/DngSdkColorSpec.kt | 76 +++++++++++- .../raw/EquivalentCameraCalibration.kt | 11 ++ .../mycamera/raw/EquivalentCameraLutCache.kt | 30 +++-- .../mycamera/raw/EquivalentCameraLutGl.kt | 18 ++- .../com/hinnka/mycamera/raw/HncsProfile.kt | 9 +- .../mycamera/raw/LumixColorTemperature.kt | 65 ++++++++++ .../com/hinnka/mycamera/raw/LumixProfile.kt | 14 +-- .../mycamera/raw/RawCameraCalibration.kt | 38 ++++-- .../mycamera/raw/RawDemosaicProcessor.kt | 117 ++++++++++++++---- .../com/hinnka/mycamera/raw/RawMetadata.kt | 5 +- .../raw/DngSourceColorMetadataTest.kt | 65 ++++++++++ .../mycamera/raw/LumixColorTemperatureTest.kt | 42 +++++++ docs/research/lumix-rendering-engine.md | 14 +-- 16 files changed, 483 insertions(+), 102 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/LumixColorTemperature.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/raw/LumixColorTemperatureTest.kt diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index a5afa359..6204e4b3 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -1053,8 +1053,10 @@ static jobject createRawCameraCalibration( int illuminant2, bool hasAnalogBalance, const std::array &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, "", "([F[FII[F[F[F)V"); + calibrationClass, "", "([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, "", - "(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(dngRawTagInfo.hasAsShotWhiteXY)); // 释放资源 env->ReleaseStringUTFChars(filePath, path); diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngEmbeddedProfile.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngEmbeddedProfile.kt index 6af35834..a7754b66 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngEmbeddedProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngEmbeddedProfile.kt @@ -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) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt index 7b8cb099..3c3b1045 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngRawData.kt @@ -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 } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngSdkColorSpec.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngSdkColorSpec.kt index 172e0c09..a953c238 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngSdkColorSpec.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngSdkColorSpec.kt @@ -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? { + 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 { diff --git a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraCalibration.kt b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraCalibration.kt index f1b1ac74..e9c4fb4a 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraCalibration.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraCalibration.kt @@ -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" } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutCache.kt b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutCache.kt index 8b759690..9e9d6d24 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutCache.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutCache.kt @@ -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( 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) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutGl.kt b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutGl.kt index 2b4f7aae..a3e37044 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutGl.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/EquivalentCameraLutGl.kt @@ -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) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/HncsProfile.kt b/app/src/main/java/com/hinnka/mycamera/raw/HncsProfile.kt index dcadb751..fa0379de 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/HncsProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/HncsProfile.kt @@ -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, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/LumixColorTemperature.kt b/app/src/main/java/com/hinnka/mycamera/raw/LumixColorTemperature.kt new file mode 100644 index 00000000..e65626de --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/LumixColorTemperature.kt @@ -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() +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/LumixProfile.kt b/app/src/main/java/com/hinnka/mycamera/raw/LumixProfile.kt index ff94f543..5432144e 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/LumixProfile.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/LumixProfile.kt @@ -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 { diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawCameraCalibration.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawCameraCalibration.kt index fb2b50ac..a201f502 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawCameraCalibration.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawCameraCalibration.kt @@ -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, ) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt index fad9e72d..70d096c2 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -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) { diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt index 8cf39b3d..2ce9697f 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawMetadata.kt @@ -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, diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngSourceColorMetadataTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngSourceColorMetadataTest.kt index 81e687a7..1faf0575 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngSourceColorMetadataTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngSourceColorMetadataTest.kt @@ -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( diff --git a/app/src/test/java/com/hinnka/mycamera/raw/LumixColorTemperatureTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/LumixColorTemperatureTest.kt new file mode 100644 index 00000000..48e25f4c --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/raw/LumixColorTemperatureTest.kt @@ -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() } + } + } +} diff --git a/docs/research/lumix-rendering-engine.md b/docs/research/lumix-rendering-engine.md index ae738f44..c0f2a912 100644 --- a/docs/research/lumix-rendering-engine.md +++ b/docs/research/lumix-rendering-engine.md @@ -4,7 +4,7 @@ 固定读取 LumixLab 的 S9 PSL1 资产,支持 16 种 PhotoStyle,默认 Standard。 这是接入 PhotonCamera RAW 前端的颜色引擎:继续使用现有黑白电平归一、去马赛克、降噪、PGTM、编辑和导出。 -Lumix 只提供等效 Camera RGB 渲染,界面保留 S9 PhotoStyle 选择。内部设置值统一为 `Lumix`,不保留此前两种模式的名称兼容。 +Lumix 按源内嵌标定自动决定是否执行等效 Camera RGB 转换;没有可用源标定时,白平衡后的相机 RGB 直接进入 PhotoStyle。界面保留 S9 PhotoStyle 选择。内部设置值统一为 `Lumix`,不保留此前两种模式的名称兼容。 S9 标定直接读取项目已有的 `app/src/main/assets/dcp/Panasonic DC-S9 Adobe Standard.dcp`,不是松下原厂 CCM。 使用 ColorMatrix1/2、ForwardMatrix1/2、A/D65 光源、两组 90×30×1 HueSatMap,以及 36×8×16 LookTable。两种表的编码均为 linear;LookTable 的 ValueScale 全为 1,但色相和饱和度修正不可省略。不引入 Adobe ToneCurve;成像曲线来自 Lumix PhotoStyle。 @@ -18,9 +18,9 @@ Lumix 通过 `diag(1 / sourceCameraWhite) × inverse(M_source_photo) × p` 恢 对每个镜头的固定标定预生成两个端点转换,分别以 A、D65 为参考白点: -`源 WB Camera RGB → 源固定 ColorMatrix 构建的 Camera-to-ProPhoto → 逆 S9 LookTable → 逆 S9 HueSatMap → 逆 S9 WB Camera-to-ProPhoto → S9 WB Camera RGB`。 +`源 WB Camera RGB → 源 CM/FM 构建的 Camera-to-ProPhoto → 逆 S9 LookTable → 逆 S9 HueSatMap → 逆 S9 WB Camera-to-ProPhoto → S9 WB Camera RGB`。 -源矩阵取 Camera2 静态 ColorMatrix1/2 和参考光源,或 DNG 原始 ColorMatrix/CameraCalibration/AnalogBalance。RW2 等原生 RAW 使用 LibRaw 固定 cam_xyz(XYZ→camera);其方向依据 cam_xyz_coeff 的实际矩阵运算核实,不使用每张照片变化的合成 CCM 或 rgb_cam 生成缓存。 +源矩阵取 Camera2 静态 ColorMatrix1/2 和参考光源,或 RAW 内嵌的 ColorMatrix/ForwardMatrix/CameraCalibration/AnalogBalance。不再用 LibRaw 的 cam_xyz/rgb_cam 作为源标定或这条路径的前置颜色变换。仅 FM 且有独立 AsShotWhiteXY 时,在 WB 参考相机 RGB 域烘焙;仅 FM 但缺少独立白点时按用户要求保留旁路。详见 [双光源插值](raw-dual-illuminant-interpolation.md)。 S9 Camera-to-ProPhoto 使用既有 DNG 颜色模型,结合 ColorMatrix、ForwardMatrix、CameraWhite 和 D50 PCS 白适应。所有矩阵输入输出均是线性值;HueSatMap 与 LookTable 在 ProPhoto HSV 中求逆,必须在逆 S9 矩阵之前、按正向相反的顺序执行。 ## 预生成与持久化 @@ -29,7 +29,7 @@ S9 Camera-to-ProPhoto 使用既有 DNG 颜色模型,结合 ColorMatrix、Forwa - 线性相机输入域为 [0,16];[0,1] 占前 48 个区间,按 `u = 0.75x` 线性分布;[1,16] 占后 16 个区间,按 `u = 0.75 + 0.25 log(x)/log(16)` 分布。这个 shaper 仅分配 LUT 采样精度,不是图像 sRGB 编码。 - GPU 对两表分别做四面体插值,每张表读取四个顶点,再按照片白点的倒数色温权重混合。权重由烘焙端点的精确 xy 对应色温定义,端点会准确选中自身;与 PhotoStyle 原版 3000–5000 K 的低/高温权重独立。 - 两端点逆变换的插值是此处采用的渲染模型,与“先插值正向 DCP 再求逆”不严格相等。运行时不再逐照片反解 DCP。 -- 缓存路径为应用 filesDir/lumix_calibration_luts。键包含源固定矩阵/参考光源/校准参数、S9 DCP 全内容 SHA、算法版本和采样域。修改曝光或白平衡不会生成新缓存;标定或算法变化才会生成。 +- 缓存路径为应用 filesDir/equivalent_camera_calibration_luts。键包含源 CM/FM/参考光源/校准参数、S9 DCP 全内容 SHA、算法版本和采样域。修改曝光或白平衡不会生成新缓存;标定或算法变化才会生成。 - 磁盘格式校验版本、尺寸、精确长度和 payload SHA,原子写入;损坏会记录日志并重建。内存保留最近四组,GPU 纹理按键复用,切换风格不重新上传标定表。 逆映射求解不包含 DCP 的破坏性输出裁剪,不能恢复已经剪掉的信息。表坐标在定义域边界取值,修正因子允许向高动态范围和超色域延伸;超出 Camera RGB=16 的部分使用齐次延伸。局部多解区域选择一个通过正向残差检查的输入,不宣称唯一反演。 @@ -38,11 +38,11 @@ Lumix 枚举的 `workingColorSpace=SRGB` 描述输出调整接口;**不描述 ## PhotoStyle 和输出 -1. shader 接收白平衡后的线性源相机 RGB,必须先采样上述两张标定 LUT,随后沿用宿主的标准曝光尺度。渲染计划要求有效标定;启动预热只编译 Lumix shader,不执行无标定显影。 +1. shader 接收白平衡后的线性源相机 RGB,有可用源标定时采样上述两张标定 LUT;无标定时直接跳过查表,随后沿用宿主的标准曝光尺度。启动预热只编译 Lumix shader。 2. CineLike D2/V2 使用 S9 Standard→Cine 的 `−7/6 EV`,V-Log 使用 `−8/3 EV`,其他风格为零。 3. 每通道查询原始 2048 点一维曲线,线性插值。 4. 曲线输出作为非线性查表坐标;对 33³ RGB 表做八角点三线性插值,红色坐标变化最快。不能把这一层坐标称为统一的 sRGB 编码。 -5. 低/高色温表使用原版默认坐标:3000 K→256,5000 K→512,坐标先截为整数,再将高温权重限制到 `[0,1]`。原版其余两个温度折点已超出表间混合区间,不影响这个默认权重。 +5. 低/高色温表优先使用原始 RW2 的 0x011c 校正坐标,缺失时使用原版默认折线:3000 K→256,5000 K→512,6500 K→618,7500 K→725。double 坐标先夹到 uint16 范围并截为整数,再将高温权重 `(q-256)/256` 限制到 `[0,1]`。普通 TIFF/DNG 的同号 PlanarConfiguration 标签不参与此逻辑。 6. 普通风格限制为 `[0,1]`;V-Log 依 ISO 使用原版 3300/3400/3496/3596 的 12-bit 上限;输出按 4095 量化。 7. **不在 PhotoStyle 后直接再做 sRGB OETF**。先解码这些输出代码值,交给现有线性调整接口,最后由 RawSrgbPass 编码一次。中性设置下解码/编码抵消,保留 PhotoStyle 的输出代码值。 @@ -50,7 +50,7 @@ V-Log 选择保留平坦的代码值显示;这里的 sRGB 解码/编码是宿 ## 与原生 RAW 的边界 -当前从宿主的归一化、标准曝光相机 RGB 接入。LumixLab 的 packed RAW `pixelMaxVal/defaultGain`、原始拍摄 PhotoStyle 家族、绝对白平衡尺度、EXIF 专用色温校正坐标及 ISO tone correction 没有伪装成已移植参数。其 `colorspace==2` 的分段 RGB 差分校正也没有启用;该分支并不是一个标准的 AdobeRGB↔sRGB 矩阵。 +当前从宿主的归一化、标准曝光相机 RGB 接入。LumixLab 的 packed RAW `pixelMaxVal/defaultGain`、原始拍摄 PhotoStyle 家族、绝对白平衡尺度、IslZWBCalc 的完整 WB2Kelvin 模型及 ISO tone correction 没有伪装成已移植参数。其 `colorspace==2` 的分段 RGB 差分校正也没有启用;该分支并不是一个标准的 AdobeRGB↔sRGB 矩阵。 需要进行原厂像素对照时,必须先固定这些前端条件以及 PGTM/降噪/锐化,不能用额外的亮度或颜色补偿掩盖差异。 ## 验证