From d4da9df05aea9a5476f314101f437973dca997d2 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Wed, 4 Nov 2026 12:53:22 +0800 Subject: [PATCH] fix: raw color calibration d65 srgb fallback --- app/src/main/cpp/fixed_raw_calibration.h | 28 --- app/src/main/cpp/native-lib.cpp | 63 ++----- .../mycamera/raw/FixedRawCalibration.kt | 29 --- .../mycamera/raw/RawColorCalibrationPolicy.kt | 91 ++++++---- .../processor/GlesMgcRawSpatialShadersTest.kt | 170 ------------------ .../raw/RawColorCalibrationPolicyTest.kt | 120 +++++++++++++ 6 files changed, 197 insertions(+), 304 deletions(-) delete mode 100644 app/src/main/cpp/fixed_raw_calibration.h delete mode 100644 app/src/main/java/com/hinnka/mycamera/raw/FixedRawCalibration.kt delete mode 100644 app/src/test/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShadersTest.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicyTest.kt diff --git a/app/src/main/cpp/fixed_raw_calibration.h b/app/src/main/cpp/fixed_raw_calibration.h deleted file mode 100644 index e3258feb..00000000 --- a/app/src/main/cpp/fixed_raw_calibration.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -// Extracted without fitting from PhotonCamera_20261006_185625.dng. -// Source SHA-256: b679ed4227ec627f0b9f05b5db36864b62fca0b019971bf059eeeec0267d0b04 -// Generated by tools/extract_fallback_calibration.py. -namespace fixed_raw_calibration { -inline constexpr int illuminant1 = 21; -inline constexpr float colorMatrix1[9] = { - 0.82950000f, -0.30550000f, -0.06240000f, - -0.42770000f, 1.28200000f, 0.15810000f, - -0.16980000f, 0.32650000f, 0.51680000f, -}; -inline constexpr float cameraCalibration1[9] = { - 0.99218800f, 0.00000000f, 0.00000000f, - 0.00000000f, 1.00000000f, 0.00000000f, - 0.00000000f, 0.00000000f, 1.01562500f, -}; -inline constexpr int illuminant2 = 17; -inline constexpr float colorMatrix2[9] = { - 0.90540000f, -0.41370000f, 0.03050000f, - -0.35840000f, 1.17330000f, 0.20870000f, - -0.08470000f, 0.22130000f, 0.58070000f, -}; -inline constexpr float cameraCalibration2[9] = { - 0.99218800f, 0.00000000f, 0.00000000f, - 0.00000000f, 1.00000000f, 0.00000000f, - 0.00000000f, 0.00000000f, 1.00781300f, -}; -} diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index 3b3093b3..12bf8a13 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -29,7 +29,6 @@ #include "dng_memory_stream.h" #include "libraw/libraw.h" #include "math_utils.h" -#include "fixed_raw_calibration.h" #include "srgb_color_matrix_policy.h" #ifndef LOG_TAG @@ -1066,15 +1065,6 @@ static bool isUsableSourceMatrix(const Matrix3x3 &matrix, bool forward = false) return true; } -static bool isUsableSourceColorMatrix(const Matrix3x3 &matrix, int illuminant) { - if (!isUsableSourceMatrix(matrix)) return false; - if (srgb_color_matrix_policy::isPlaceholder(matrix.m, illuminant)) { - LOGI("Ignoring sRGB placeholder ColorMatrix, illuminant=%d", illuminant); - return false; - } - return true; -} - static jfloatArray matrixToJava(JNIEnv *env, const Matrix3x3 &matrix) { jfloatArray result = env->NewFloatArray(9); if (result) { @@ -1164,15 +1154,17 @@ static bool isSrgbPlaceholderForwardMatrixPair(const libraw_dng_color_t &first, } struct SourceCalibrationSelection { - bool useSource = false; // false: replace with fixed_raw_calibration + bool useSource = false; // false: no usable ColorMatrix1, use the legacy chain bool useForward = false; bool keepSlot2 = false; }; // Same order as RawColorCalibrationPolicy.kt. A usable ForwardMatrix set keeps the // source calibration as is: ColorMatrix then only locates the scene white, so an -// sRGB placeholder ColorMatrix is kept. Otherwise ForwardMatrix is dropped and a -// usable ColorMatrix is used alone; otherwise the fixed DNG calibration applies. +// sRGB placeholder ColorMatrix is kept. Otherwise ForwardMatrix is dropped and the +// ColorMatrix is used alone, sRGB placeholder included; a placeholder second slot +// is dropped only next to a real first slot. Without a structurally usable +// ColorMatrix1 (including non-DNG RAW) the LibRaw fallback chain applies. static SourceCalibrationSelection selectSourceCalibration( const libraw_dng_color_t *dngColor, const Matrix3x3 &colorMatrix1, const Matrix3x3 &colorMatrix2, int illuminant1, int illuminant2, @@ -1191,8 +1183,14 @@ static SourceCalibrationSelection selectSourceCalibration( if (hasForward1 || hasForward2) { LOGI("Ignoring unusable ForwardMatrix set; using ColorMatrix only"); } - if (!isUsableSourceColorMatrix(colorMatrix1, illuminant1)) return {}; - return {true, false, isUsableSourceColorMatrix(colorMatrix2, illuminant2)}; + if (!isUsableSourceMatrix(colorMatrix1)) return {}; + const bool placeholder1 = srgb_color_matrix_policy::isPlaceholder(colorMatrix1.m, illuminant1); + if (placeholder1) { + LOGI("Keeping sRGB placeholder ColorMatrix, illuminant=%d", illuminant1); + } + const bool keepSlot2 = isUsableSourceMatrix(colorMatrix2) && + (placeholder1 || !srgb_color_matrix_policy::isPlaceholder(colorMatrix2.m, illuminant2)); + return {true, false, keepSlot2}; } static std::array multiplyMatrixVector(const Matrix3x3 &matrix, @@ -1852,22 +1850,12 @@ static bool computeWbFromDngAsShotWhiteXY(const LibRaw &rawProcessor, const SourceCalibrationSelection selection = selectSourceCalibration( rawProcessor.imgdata.color.dng_color, colorMatrix1, colorMatrix2, illuminant1, illuminant2, forwardMatrix1, forwardMatrix2); - bool hasColor1 = selection.useSource; - bool hasColor2 = selection.useSource && selection.keepSlot2; + // Without a usable ColorMatrix1 the render path has no DNG calibration either. if (!selection.useSource) { - // AsShotWhiteXY-derived WB must use the same replacement as the render CCM. - memcpy(colorMatrix1.m, fixed_raw_calibration::colorMatrix1, sizeof(colorMatrix1.m)); - memcpy(colorMatrix2.m, fixed_raw_calibration::colorMatrix2, sizeof(colorMatrix2.m)); - illuminant1 = fixed_raw_calibration::illuminant1; - illuminant2 = fixed_raw_calibration::illuminant2; - Matrix3x3 calibration1, calibration2; - memcpy(calibration1.m, fixed_raw_calibration::cameraCalibration1, sizeof(calibration1.m)); - memcpy(calibration2.m, fixed_raw_calibration::cameraCalibration2, sizeof(calibration2.m)); - // Apply individual-camera calibration after CM normalization, as in the render path. - colorMatrix1 = calibration1.multiply(normalizeDngColorMatrix(colorMatrix1)); - colorMatrix2 = calibration2.multiply(normalizeDngColorMatrix(colorMatrix2)); - hasColor1 = hasColor2 = true; + return false; } + const bool hasColor1 = true; + const bool hasColor2 = selection.keepSlot2; if (!findXyzToCamera( whiteXy, colorMatrix1, hasColor1, colorMatrix2, hasColor2, illuminant1, illuminant2, xyzToCamera)) { @@ -3543,21 +3531,6 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( } } - const bool useFallbackCalibration = !selection.useSource; - if (useFallbackCalibration) { - memcpy(colorMatrix1.m, fixed_raw_calibration::colorMatrix1, sizeof(colorMatrix1.m)); - memcpy(colorMatrix2.m, fixed_raw_calibration::colorMatrix2, sizeof(colorMatrix2.m)); - hasColor1 = hasColor2 = true; - hasForward1 = hasForward2 = false; - illuminant1 = fixed_raw_calibration::illuminant1; - illuminant2 = fixed_raw_calibration::illuminant2; - memcpy(cameraCalibration1.m, fixed_raw_calibration::cameraCalibration1, sizeof(cameraCalibration1.m)); - memcpy(cameraCalibration2.m, fixed_raw_calibration::cameraCalibration2, sizeof(cameraCalibration2.m)); - hasCameraCalibration1 = hasCameraCalibration2 = true; - analogBalance = {1.0f, 1.0f, 1.0f}; - LOGI("No usable source matrices; using fixed DNG calibration (ColorMatrix only)"); - } - if (hasColor1 || hasColor2 || hasForward1 || hasForward2) { hasFixedColor1 = hasColor1; hasFixedColor2 = hasColor2; @@ -3569,7 +3542,7 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative( fixedCameraCalibration2 = cameraCalibration2; fixedIlluminant1 = illuminant1; fixedIlluminant2 = illuminant2; - if (!useFallbackCalibration && (RawProcessor.imgdata.color.dng_levels.parsedfields & + if ((RawProcessor.imgdata.color.dng_levels.parsedfields & LIBRAW_DNGFM_ANALOGBALANCE) != 0) { hasFixedAnalogBalance = true; fixedAnalogBalance = analogBalance; diff --git a/app/src/main/java/com/hinnka/mycamera/raw/FixedRawCalibration.kt b/app/src/main/java/com/hinnka/mycamera/raw/FixedRawCalibration.kt deleted file mode 100644 index a9ae1f3f..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/FixedRawCalibration.kt +++ /dev/null @@ -1,29 +0,0 @@ -package com.hinnka.mycamera.raw - -// Extracted without fitting from PhotonCamera_20261006_185625.dng. -// Source SHA-256: b679ed4227ec627f0b9f05b5db36864b62fca0b019971bf059eeeec0267d0b04 -// Generated by tools/extract_fallback_calibration.py. -internal object FixedRawCalibration { - const val ILLUMINANT1 = 21 - fun colorMatrix1(): FloatArray = floatArrayOf( - 0.82950000f, -0.30550000f, -0.06240000f, - -0.42770000f, 1.28200000f, 0.15810000f, - -0.16980000f, 0.32650000f, 0.51680000f, - ) - fun cameraCalibration1(): FloatArray = floatArrayOf( - 0.99218800f, 0.00000000f, 0.00000000f, - 0.00000000f, 1.00000000f, 0.00000000f, - 0.00000000f, 0.00000000f, 1.01562500f, - ) - const val ILLUMINANT2 = 17 - fun colorMatrix2(): FloatArray = floatArrayOf( - 0.90540000f, -0.41370000f, 0.03050000f, - -0.35840000f, 1.17330000f, 0.20870000f, - -0.08470000f, 0.22130000f, 0.58070000f, - ) - fun cameraCalibration2(): FloatArray = floatArrayOf( - 0.99218800f, 0.00000000f, 0.00000000f, - 0.00000000f, 1.00000000f, 0.00000000f, - 0.00000000f, 0.00000000f, 1.00781300f, - ) -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicy.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicy.kt index 4c5e9337..73ed7787 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicy.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicy.kt @@ -14,8 +14,12 @@ import kotlin.math.roundToInt * present), so in-app rendering and third-party readers see the same matrices: * 1. Usable ForwardMatrix set → source calibration as is. ColorMatrix then only * locates the scene white, so an sRGB placeholder ColorMatrix is kept. - * 2. Otherwise ForwardMatrix is dropped; usable ColorMatrix → ColorMatrix only. - * 3. Otherwise the fixed DNG calibration replaces the source. + * 2. Otherwise ForwardMatrix is dropped and the source ColorMatrix is used alone. + * An sRGB placeholder is kept as well: another sensor's calibration is not a + * better guess, and its larger gains turn the CFA mismatch into hue shifts. + * A placeholder second slot is dropped only when the first slot is a real one. + * 3. Otherwise (no structurally usable ColorMatrix1) a D65 sRGB ColorMatrix, i.e. + * white-balanced camera RGB rendered as linear sRGB. */ internal object RawColorCalibrationPolicy { data class CameraCalibration( @@ -36,10 +40,26 @@ internal object RawColorCalibrationPolicy { ) } - private data class Selection(val useForward: Boolean, val keepSlot2: Boolean) + internal data class Selection( + val useForward: Boolean, + val keepSlot2: Boolean, + val droppedForward: Boolean = false, + val placeholderColor: Boolean = false, + ) - /** ForwardMatrices must already have passed original-payload placeholder rejection. */ - private fun select( + /** XYZ(D65) -> linear sRGB, so a D65 white maps to camera (1, 1, 1). */ + internal val SRGB_D65_COLOR_MATRIX = floatArrayOf( + 3.2404542f, -1.5371385f, -0.4985314f, + -0.9692660f, 1.8760108f, 0.0415560f, + 0.0556434f, -0.2040259f, 1.0572252f, + ) + private const val ILLUMINANT_D65 = 21 + + /** + * ForwardMatrices must already have passed original-payload placeholder rejection. + * Pure, so callers log; null means no structurally usable ColorMatrix1. + */ + internal fun select( colorMatrix1: FloatArray?, colorMatrix2: FloatArray?, illuminant1: Int, illuminant2: Int, forwardMatrix1: FloatArray?, forwardMatrix2: FloatArray?, @@ -49,11 +69,29 @@ internal object RawColorCalibrationPolicy { if (forwardUsable && isUsableMatrix(colorMatrix1)) { return Selection(useForward = true, keepSlot2 = isUsableMatrix(colorMatrix2)) } - if (forwardMatrix1 != null || forwardMatrix2 != null) { - PLog.w(TAG, "Ignoring unusable ForwardMatrix set; using ColorMatrix only") + if (!isUsableMatrix(colorMatrix1)) return null + val placeholder1 = SrgbColorMatrixPolicy.isPlaceholder(requireNotNull(colorMatrix1), illuminant1) + val keepSlot2 = isUsableMatrix(colorMatrix2) && + (placeholder1 || !SrgbColorMatrixPolicy.isPlaceholder(requireNotNull(colorMatrix2), illuminant2)) + return Selection( + useForward = false, + keepSlot2 = keepSlot2, + droppedForward = forwardMatrix1 != null || forwardMatrix2 != null, + placeholderColor = placeholder1, + ) + } + + private fun log(selection: Selection?, source: String) { + if (selection == null) { + PLog.w(TAG, "No usable $source ColorMatrix1; using D65 sRGB ColorMatrix") + return + } + if (selection.droppedForward) { + PLog.w(TAG, "Ignoring unusable $source ForwardMatrix set; using ColorMatrix only") + } + if (selection.placeholderColor) { + PLog.w(TAG, "Keeping $source sRGB placeholder ColorMatrix") } - if (!isUsableColorMatrix(colorMatrix1, illuminant1)) return null - return Selection(useForward = false, keepSlot2 = isUsableColorMatrix(colorMatrix2, illuminant2)) } // CameraCharacteristics is immutable; one capture resolves the same instance many times. @@ -72,13 +110,11 @@ internal object RawColorCalibrationPolicy { val selection = select( cm1?.toMatrix(), cm2?.toMatrix(), illuminant1, illuminant2, fm1?.toMatrix(), fm2?.toMatrix(), ) + log(selection, "source") if (selection == null) { - PLog.w(TAG, "No usable source matrices; using fixed DNG calibration") return CameraCalibration( - FixedRawCalibration.colorMatrix1().toTransform(), FixedRawCalibration.colorMatrix2().toTransform(), - null, null, - FixedRawCalibration.ILLUMINANT1, FixedRawCalibration.ILLUMINANT2, - FixedRawCalibration.cameraCalibration1().toTransform(), FixedRawCalibration.cameraCalibration2().toTransform(), + SRGB_D65_COLOR_MATRIX.toTransform(), null, null, null, + ILLUMINANT_D65, 0, null, null, ) } val keep2 = selection.keepSlot2 @@ -102,6 +138,7 @@ internal object RawColorCalibrationPolicy { profile.calibrationIlluminant1, profile.calibrationIlluminant2, profile.forwardMatrix1, profile.forwardMatrix2, ) + log(selection, "embedded") if (selection != null) { val keep2 = selection.keepSlot2 return profile.copy( @@ -113,31 +150,21 @@ internal object RawColorCalibrationPolicy { hueSatDeltas2 = profile.hueSatDeltas2.takeIf { keep2 }, ) } - PLog.w(TAG, "No usable embedded matrices; using fixed DNG calibration") return profile.copy( - colorMatrix1 = FixedRawCalibration.colorMatrix1(), colorMatrix2 = FixedRawCalibration.colorMatrix2(), + colorMatrix1 = SRGB_D65_COLOR_MATRIX.copyOf(), colorMatrix2 = null, forwardMatrix1 = null, forwardMatrix2 = null, - calibrationIlluminant1 = FixedRawCalibration.ILLUMINANT1, - calibrationIlluminant2 = FixedRawCalibration.ILLUMINANT2, + calibrationIlluminant1 = ILLUMINANT_D65, + calibrationIlluminant2 = 0, analogBalance = null, - cameraCalibration1 = FixedRawCalibration.cameraCalibration1(), - cameraCalibration2 = FixedRawCalibration.cameraCalibration2(), - // Tables tied to the rejected source calibration do not belong to this - // replacement, which uses only the selected DNG's fixed calibration. + cameraCalibration1 = null, + cameraCalibration2 = null, + // Tables tied to the missing source calibration do not belong to this + // replacement, which renders white-balanced camera RGB as sRGB. hueSatDeltas1 = null, hueSatDeltas2 = null, lookTable = null, ) } - fun isUsableColorMatrix(matrix: FloatArray?, illuminant: Int): Boolean { - if (!isUsableMatrix(matrix)) return false - if (SrgbColorMatrixPolicy.isPlaceholder(requireNotNull(matrix), illuminant)) { - PLog.w(TAG, "Ignoring sRGB placeholder ColorMatrix, illuminant=$illuminant") - return false - } - return true - } - - // Structural check only; ColorMatrix-only selection also rejects placeholders. + // Structural check only; sRGB placeholders are handled by the selection order. fun isUsableMatrix(matrix: FloatArray?): Boolean { if (matrix == null || matrix.size != 9 || matrix.any { !it.isFinite() }) return false if (matrix.sumOf { abs(it).toDouble() } <= 0.01) return false diff --git a/app/src/test/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShadersTest.kt deleted file mode 100644 index 0df10e74..00000000 --- a/app/src/test/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShadersTest.kt +++ /dev/null @@ -1,170 +0,0 @@ -package com.hinnka.mycamera.processor - -import com.hinnka.mycamera.raw.RawOutputPass -import java.io.File -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Assume.assumeTrue -import org.junit.Test - -class GlesMgcRawSpatialShadersTest { - @Test - fun sabreBayerMergePreservesMgcRbfAndCfaContract() { - val shader = GlesMgcRawSpatialShaders.sabreMergeBayer - - assertTrue(shader.contains("exp2(-0.5 * kernelDistance) + 0.00005")) - assertTrue(shader.contains("pixelOffset.x * pixelOffset.y * covariance.z * 2.0")) - assertTrue(shader.contains("uniform sampler2D uCovariance")) - assertTrue(shader.contains("uniform sampler2D uFrameWeight")) - assertTrue(shader.contains("targetIsGreen")) - assertTrue(shader.contains("uBlackLevelsTimesGains[channel]")) - assertFalse(shader.contains("uLinearKernelMask")) - } - - @Test - fun bentoHighlightCountUsesBaselineCompatibleGroupedReduction() { - val shader = GlesMgcRawSpatialShaders.bentoCountHighlightMask - - assertEquals( - GlesComputeWorkGroup.Size(x = 8, y = 8, z = 1), - GlesComputeWorkGroup.declaredSize(shader), - ) - GlesComputeWorkGroup.requireBaselineCompatible(shader, "MGC_BENTO_HIGHLIGHT_COUNT") - assertTrue(shader.contains("shared uint localCounts[64]")) - assertTrue(shader.contains("atomicAdd(activeCount, localCounts[0])")) - } - - @Test - fun rgbMergeUsesJointGreenOpponentReconstruction() { - val guide = GlesMgcRawSpatialShaders.rgbChromaGuide - val merge = GlesMgcRawSpatialShaders.mergeRgb - val normalize = GlesMgcRawSpatialShaders.normalizeRgb16 - - assertTrue(guide.contains("float greenAtNonGreen")) - assertTrue(merge.contains("float chromaGuideAt")) - assertFalse(merge.contains("float greenAtNonGreen")) - assertTrue(merge.contains("nativeValue - localGreen")) - assertTrue(merge.contains("greenSum += gainedRaw(p)")) - assertTrue(normalize.contains("semantic.r + semantic.g")) - assertTrue(normalize.contains("semantic.r + semantic.b")) - assertFalse(merge.contains("intensities[rgbChannel]")) - } - - @Test - fun filteredRgb16UsesComputeForTheFirstFloatConversion() { - val shader = GlesMgcRawSpatialShaders.copyRgb16ToFloat - - assertEquals( - GlesComputeWorkGroup.Size(x = 8, y = 8, z = 1), - GlesComputeWorkGroup.declaredSize(shader), - ) - GlesComputeWorkGroup.requireBaselineCompatible(shader, "MGC_RGB_CHROMA_TO_FLOAT") - assertTrue(shader.contains("readonly uniform highp uimage2D uRgb16")) - assertTrue(shader.contains("writeonly uniform highp image2D uRgb16f")) - assertTrue(shader.contains("uvec3 encoded = imageLoad(uRgb16, p).rgb")) - assertFalse(shader.contains("usampler2D")) - assertFalse(shader.contains("texelFetch")) - } - - - @Test - fun rgbOpponentInterpolationIsGuidedByTheSameGreenReconstruction() { - val merge = GlesMgcRawSpatialShaders.mergeRgb - - assertTrue(merge.contains("float targetGreen = greenSum")) - assertTrue(merge.contains("chromaGuideWeight(localGreen, targetGreen)")) - assertTrue(merge.contains("uGreenNoise.x * signal + uGreenNoise.y")) - assertTrue(merge.contains("jointWeight")) - } - - @Test - fun rgbMergeCarriesFusedRawGreenDirectionWithoutAnotherSurface() { - val merge = GlesMgcRawSpatialShaders.mergeRgb - val normalize = GlesMgcRawSpatialShaders.normalizeRgb16 - - assertTrue(merge.contains("vec2 greenDirectionMoment")) - assertTrue(merge.contains("directionMoment * weights.r * frameWeight")) - assertTrue(normalize.contains("gbWeightsAndDirection.ba / max(colorAndR.a")) - assertTrue(normalize.contains("packDirectionMoment(directionMoment)")) - } - - @Test - fun changedRgbFragmentShadersPassAvailableNdkValidator() { - val sdkRoot = System.getenv("ANDROID_SDK_ROOT") ?: System.getenv("ANDROID_HOME") - val validator = sdkRoot?.let(::File) - ?.resolve("ndk") - ?.listFiles() - ?.sortedByDescending { it.name } - ?.asSequence() - ?.mapNotNull { ndk -> - ndk.resolve("shader-tools") - .walkTopDown() - .firstOrNull { it.name == "glslc" && it.canExecute() } - } - ?.firstOrNull() - assumeTrue("Android NDK glslc is unavailable", validator != null) - - listOf( - GlesMgcRawSpatialShaders.mergeRgb, - GlesMgcRawSpatialShaders.normalizeRgb16, - GlesMgcRawSpatialShaders.normalizeAotRgb16, - RawOutputPass.FRAGMENT_SHADER, - GlesYuvSpatialShaders.lanczosOutput, - GlesYuvSpatialShaders.lanczosFrameOutput, - ).forEachIndexed { index, shader -> - val sourceFile = File.createTempFile("mgc-spatial-rgb-$index-", ".frag") - val outputFile = File.createTempFile("mgc-spatial-rgb-$index-", ".spv") - try { - sourceFile.writeText(shader.replaceFirst("#version 300 es", "#version 310 es")) - val process = ProcessBuilder( - checkNotNull(validator).absolutePath, - "--target-env=opengl", - "-fauto-map-locations", - "-fauto-bind-uniforms", - "-fshader-stage=frag", - sourceFile.absolutePath, - "-o", - outputFile.absolutePath, - ).redirectErrorStream(true).start() - val output = process.inputStream.bufferedReader().use { it.readText() } - - assertEquals("shader $index: $output", 0, process.waitFor()) - } finally { - sourceFile.delete() - outputFile.delete() - } - } - } - - @Test - fun rgbRawBoundaryFetchPreservesCfaPhase() { - val guide = GlesMgcRawSpatialShaders.rgbChromaGuide - val merge = GlesMgcRawSpatialShaders.mergeRgb - - assertTrue(guide.contains("clampRawCoordinateToPhase")) - assertTrue(guide.contains("int channel = canonicalChannel(globalPixel)")) - assertTrue(guide.contains("globalPixel = clampRawPixelToPhase(globalPixel)")) - assertTrue(merge.contains("uniform highp usampler2D uRaw;")) - assertFalse(merge.contains("usampler2D uRawRegion")) - assertFalse(merge.contains("canonicalChannel(mirrorRawPixel")) - } - - @Test - fun originalAotOutputUsesPlanarQ14CameraRgbWithoutWbUndo() { - val shader = GlesMgcRawSpatialShaders.normalizeAotRgb16 - - assertTrue(shader.contains("#version 300 es")) - assertTrue(shader.contains("* (1.0 / 16384.0)")) - assertTrue(shader.contains("float channelShading")) - assertTrue(shader.contains("out highp uvec4 oRgb16")) - assertTrue(shader.contains("oRgb16 = uvec4(uvec3(encodedValue), 0u)")) - assertFalse(shader.contains("oRgb16[uChannel]")) - assertFalse(shader.contains("uimage2D")) - assertFalse(shader.contains("imageLoad")) - assertFalse(shader.contains("imageStore")) - assertFalse(shader.contains("uCalculationGains")) - assertFalse(shader.contains("uCameraDomainScale")) - } - -} diff --git a/app/src/test/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicyTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicyTest.kt new file mode 100644 index 00000000..bb0298f1 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/raw/RawColorCalibrationPolicyTest.kt @@ -0,0 +1,120 @@ +package com.hinnka.mycamera.raw + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class RawColorCalibrationPolicyTest { + // Row directions of the generated sRGB placeholders, with per-row gains as a HAL + // or DNG writer would apply them. + private val placeholderCm1 = scaleRows( + floatArrayOf( + 0.894898f, -0.424503f, -0.137677f, + -0.458929f, 0.888255f, 0.019676f, + 0.051609f, -0.189234f, 0.980575f, + ), + 1.21f, 0.93f, 1.07f, + ) + private val placeholderCm2 = scaleRows( + floatArrayOf( + 0.813831f, -0.563242f, -0.142960f, + -0.441178f, 0.897414f, -0.003170f, + 0.046917f, -0.110280f, 0.992793f, + ), + 1.1f, 0.97f, 1.02f, + ) + private val sensorCm1 = floatArrayOf( + 0.8295f, -0.3055f, -0.0624f, + -0.4277f, 1.2820f, 0.1581f, + -0.1698f, 0.3265f, 0.5168f, + ) + private val sensorCm2 = floatArrayOf( + 0.9054f, -0.4137f, 0.0305f, + -0.3584f, 1.1733f, 0.2087f, + -0.0847f, 0.2213f, 0.5807f, + ) + private val sensorFm1 = floatArrayOf( + 0.6484f, 0.2266f, 0.0898f, + 0.2578f, 0.7969f, -0.0547f, + 0.0234f, -0.1563f, 0.9570f, + ) + private val sensorFm2 = floatArrayOf( + 0.6016f, 0.2813f, 0.0820f, + 0.2109f, 0.8828f, -0.0938f, + 0.0156f, -0.2422f, 1.0508f, + ) + + @Test + fun placeholderMatricesAreRecognized() { + assertTrue(SrgbColorMatrixPolicy.isPlaceholder(placeholderCm1, 21)) + assertTrue(SrgbColorMatrixPolicy.isPlaceholder(placeholderCm2, 17)) + assertFalse(SrgbColorMatrixPolicy.isPlaceholder(sensorCm1, 21)) + assertFalse(SrgbColorMatrixPolicy.isPlaceholder(sensorCm2, 17)) + } + + // GitHub issue #85: 1.28.5 dropped placeholder ColorMatrices but kept the + // ForwardMatrices, so the exported DNG had ForwardMatrix without ColorMatrix1. + @Test + fun usableForwardMatrixKeepsPlaceholderColorMatrices() { + val selection = select(placeholderCm1, placeholderCm2, sensorFm1, sensorFm2) + + assertTrue(selection!!.useForward) + assertTrue(selection.keepSlot2) + assertFalse(selection.placeholderColor) + } + + // A placeholder must not be replaced by another sensor's calibration. + @Test + fun placeholderColorMatricesAreKeptWithoutForwardMatrix() { + val selection = select(placeholderCm1, placeholderCm2, null, null) + + assertFalse(selection!!.useForward) + assertTrue(selection.keepSlot2) + assertTrue(selection.placeholderColor) + } + + @Test + fun placeholderSecondSlotIsDroppedNextToRealFirstSlot() { + val selection = select(sensorCm1, placeholderCm2, null, null) + + assertFalse(selection!!.useForward) + assertFalse(selection.keepSlot2) + assertFalse(selection.placeholderColor) + } + + @Test + fun unusableForwardMatrixFallsBackToColorMatrix() { + val negativeRow = sensorFm1.copyOf().also { it[6] = -1f; it[7] = -0.5f; it[8] = 0.2f } + val selection = select(sensorCm1, sensorCm2, negativeRow, sensorFm2) + + assertFalse(selection!!.useForward) + assertTrue(selection.keepSlot2) + assertTrue(selection.droppedForward) + } + + @Test + fun missingColorMatrix1HasNoSourceSelection() { + assertNull(select(null, sensorCm2, sensorFm1, sensorFm2)) + assertNull(select(FloatArray(9), sensorCm2, null, null)) + } + + @Test + fun srgbFallbackMapsD65WhiteToUnitCameraWhite() { + val d65 = floatArrayOf(0.3127f / 0.3290f, 1f, (1f - 0.3127f - 0.3290f) / 0.3290f) + val m = RawColorCalibrationPolicy.SRGB_D65_COLOR_MATRIX + for (row in 0..2) { + val value = (0..2).sumOf { m[row * 3 + it].toDouble() * d65[it] } + assertEquals(1.0, value, 2e-3) + } + assertTrue(SrgbColorMatrixPolicy.isPlaceholder(m, 21)) + } + + private fun select( + cm1: FloatArray?, cm2: FloatArray?, fm1: FloatArray?, fm2: FloatArray?, + ) = RawColorCalibrationPolicy.select(cm1, cm2, 21, 17, fm1, fm2) + + private fun scaleRows(matrix: FloatArray, vararg gains: Float) = + FloatArray(9) { matrix[it] * gains[it / 3] } +}