From 02a7542c7ed6b7243d014ff586d40afa8bfe5410 Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Tue, 15 Sep 2026 23:09:10 +0800 Subject: [PATCH] fix: highlight error when negative expo for hdrnet --- app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp | 2 +- .../cpp/raw_legacy_auto_exposure_solver.cpp | 76 ++++- .../hinnka/mycamera/gallery/GalleryManager.kt | 57 +++- .../hinnka/mycamera/gallery/PhotoProcessor.kt | 1 + .../mycamera/raw/DngCameraRawProfileXmp.kt | 22 ++ .../raw/DngPhotonProfileGainTableAlgorithm.kt | 287 +++++++++++------- .../raw/DngPhotonProfileGainTableGenerator.kt | 48 ++- .../mycamera/raw/RawDemosaicProcessor.kt | 50 ++- .../mycamera/raw/RawDngProfilePreparation.kt | 82 +---- .../mycamera/raw/RawHdrReferenceMath.kt | 9 +- .../raw/RawLegacyAutoExposureMatcher.kt | 96 +++++- .../raw/RawLegacyAutoExposureNativeBridge.kt | 12 + .../mycamera/raw/RawPhotonHdrMetadata.kt | 139 +++++++++ .../mycamera/ui/gallery/GalleryEditScreen.kt | 31 +- .../com/hinnka/mycamera/utils/RawProcessor.kt | 1 + .../raw/DngHdrNetViewfinderGridTest.kt | 42 +++ .../mycamera/raw/RawHdrReferenceMathTest.kt | 10 + .../mycamera/raw/RawPhotonHdrMetadataTest.kt | 84 +++++ docs/photon-dehaze-pipeline.md | 164 +++++----- docs/research/lumix-rendering-engine.md | 6 +- tools/dng_hdrnet_dehaze_test.cpp | 88 ++++++ .../raw_hdrnet_post_exposure_solver_test.cpp | 64 ++++ 22 files changed, 1051 insertions(+), 320 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadata.kt create mode 100644 app/src/test/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadataTest.kt diff --git a/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp b/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp index 2df9e093..4ddced4f 100644 --- a/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp +++ b/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp @@ -466,7 +466,7 @@ RgbSample RgbForTableCoordinate(float coordinate, const RgbSample& cell_rgb, float cell_coordinate, float weight_sum) { // A positive scalar table cannot reproduce a positive target from non-positive // source luma. Define black/signed-noise cells on the neutral axis instead. - if (cell_coordinate <= kHdrNetGainEpsilon || HdrNetLuma(cell_rgb) <= kHdrNetGainEpsilon) { + if (cell_coordinate <= kHdrNetGainEpsilon * weight_sum || HdrNetLuma(cell_rgb) <= kHdrNetGainEpsilon) { const float gray = coordinate / weight_sum; return {gray, gray, gray}; } diff --git a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp index 9f511a85..aec71579 100644 --- a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp +++ b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp @@ -93,6 +93,37 @@ float HdrNetShadowPriority(float reference_luma) { return 1.0f + 0.25f * (1.0f - SmoothStep(0.02f, 0.25f, reference_luma)); } +bool BuildLegacyHdrNetReference( + const float* rgb, + int pixel_count, + float post_exposure_ev, + std::vector* pixels) { + if (rgb == nullptr || pixels == nullptr || pixel_count <= 0 || + !std::isfinite(post_exposure_ev)) return false; + const float gain = std::exp2(post_exposure_ev); + if (!std::isfinite(gain) || gain <= 0.0f) return false; + namespace post = photon::hdrnet_post_exposure; + const auto gains = post::SplitGain(gain); + const auto encode = [](float linear) -> uint32_t { + const float srgb = linear <= 0.0031308f ? 12.92f * linear + : 1.055f * std::pow(linear, 1.0f / 2.4f) - 0.055f; + return static_cast(std::lround(std::clamp(srgb, 0.0f, 1.0f) * 255.0f)); + }; + pixels->resize(pixel_count); + for (int index = 0; index < pixel_count; ++index) { + const int offset = index * 3; + const post::Rgb source{rgb[offset], rgb[offset + 1], rgb[offset + 2]}; + if (!std::isfinite(source.red) || !std::isfinite(source.green) || + !std::isfinite(source.blue) || + std::min({source.red, source.green, source.blue}) < 0.0f || + std::max({source.red, source.green, source.blue}) > 1.0f) return false; + const auto display = post::Apply(source, gains); + (*pixels)[index] = static_cast(0xff000000U | + (encode(display.red) << 16U) | (encode(display.green) << 8U) | encode(display.blue)); + } + return true; +} + float SpatialGridWeight(int cell) { const int grid_x = cell % kGridColumns; const int grid_y = cell / kGridColumns; @@ -413,6 +444,19 @@ public: return IssueCandidate(*next); } + bool ConfigureHdrNetPriority() { + if (!samples_.empty() || pending_exposure_ev_.has_value()) return false; + if (hdrnet_priority_configured_) return true; + reference_weight_sum_ = 0.0f; + for (size_t index = 0; index < eligible_cell_indices_.size(); ++index) { + reference_cell_weights_[index] *= + HdrNetShadowPriority(reference_grid_lumas_[eligible_cell_indices_[index]]); + reference_weight_sum_ += reference_cell_weights_[index]; + } + hdrnet_priority_configured_ = true; + return true; + } + bool SubmitCandidate( float exposure_ev, const jint* pixels, @@ -505,7 +549,7 @@ public: for (size_t index = 0; index < eligible_cell_indices_.size(); ++index) { const int cell = eligible_cell_indices_[index]; const float reference_luma = reference_grid_lumas_[cell]; - weights[index] *= HdrNetShadowPriority(reference_luma); + if (!hdrnet_priority_configured_) weights[index] *= HdrNetShadowPriority(reference_luma); boundaries.push_back(exposure_for_luma(cell, reference_luma * std::exp2(-kMatchResidualToleranceEv))); boundaries.push_back(exposure_for_luma(cell, @@ -914,6 +958,7 @@ private: float minimum_exposure_ev_ = kMinExposureEv; float maximum_exposure_ev_ = kMaxExposureEv; bool finished_ = false; + bool hdrnet_priority_configured_ = false; std::optional pending_exposure_ev_; std::vector reference_grid_lumas_; std::vector eligible_cell_indices_; @@ -1088,6 +1133,35 @@ Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeSolveSingle return output; } +extern "C" JNIEXPORT jboolean JNICALL +Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeConfigureHdrNetPriority( + JNIEnv*, jobject, jlong handle) { + ExposureSolver* solver = FromHandle(handle); + return solver != nullptr && solver->ConfigureHdrNetPriority() ? JNI_TRUE : JNI_FALSE; +} + +extern "C" JNIEXPORT jintArray JNICALL +Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_legacyHdrNetReferencePixels( + JNIEnv* env, jobject, jfloatArray display_linear_rgb, jfloat post_exposure_ev) { + if (display_linear_rgb == nullptr) return nullptr; + const jsize value_count = env->GetArrayLength(display_linear_rgb); + if (value_count <= 0 || value_count % 3 != 0) return nullptr; + jfloat* rgb = env->GetFloatArrayElements(display_linear_rgb, nullptr); + if (rgb == nullptr) return nullptr; + std::vector pixels; + bool completed = false; + try { + completed = BuildLegacyHdrNetReference(rgb, value_count / 3, post_exposure_ev, &pixels); + } catch (const std::bad_alloc&) { + completed = false; + } + env->ReleaseFloatArrayElements(display_linear_rgb, rgb, JNI_ABORT); + if (!completed) return nullptr; + jintArray output = env->NewIntArray(value_count / 3); + if (output != nullptr) env->SetIntArrayRegion(output, 0, value_count / 3, pixels.data()); + return output; +} + extern "C" JNIEXPORT jboolean JNICALL Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeConfigureExposureBounds( JNIEnv*, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt index 34824534..af901924 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/GalleryManager.kt @@ -49,6 +49,7 @@ import com.hinnka.mycamera.processor.RawStackFrame import com.hinnka.mycamera.processor.YuvHdrStackFrame import com.hinnka.mycamera.processor.YuvHdrStackFrameRole import com.hinnka.mycamera.raw.DngEmbeddedProfile +import com.hinnka.mycamera.raw.DngCameraRawProfileXmp import com.hinnka.mycamera.raw.DngProfileGainTableMap import com.hinnka.mycamera.raw.GpuDemosaicedRawSource import com.hinnka.mycamera.raw.MgcSpatialGpuDenoiseMode @@ -2298,6 +2299,7 @@ object GalleryManager { preparedProfile.hdrRatio, preparedProfile.finalShortGain, preparedProfile.hdrNetPostExposureEv, + preparedProfile.hdrNetInputExposureEv, ), ) @@ -2441,6 +2443,7 @@ object GalleryManager { photonHdrRatio = preparedProfile.hdrRatio, photonSourceToShortGain = preparedProfile.finalShortGain, photonHdrNetPostExposureEv = preparedProfile.hdrNetPostExposureEv, + photonHdrNetInputExposureEv = preparedProfile.hdrNetInputExposureEv, rawData = rawBuffer.duplicate(), width = rawWidth, height = rawHeight, @@ -3643,6 +3646,7 @@ object GalleryManager { dngProfilePreparation.hdrRatio, dngProfilePreparation.finalShortGain, dngProfilePreparation.hdrNetPostExposureEv, + dngProfilePreparation.hdrNetInputExposureEv, ), ) val profileElapsedMs = System.currentTimeMillis() - profileStartMs @@ -3776,6 +3780,7 @@ object GalleryManager { photonHdrRatio = dngProfilePreparation.hdrRatio, photonSourceToShortGain = dngProfilePreparation.finalShortGain, photonHdrNetPostExposureEv = dngProfilePreparation.hdrNetPostExposureEv, + photonHdrNetInputExposureEv = dngProfilePreparation.hdrNetInputExposureEv, rawData = null, width = finalStackResult.width, height = finalStackResult.height, @@ -5333,32 +5338,48 @@ object GalleryManager { ?.rawToneMappingParameters ?.normalized() ?: rawToneMappingParameters.normalized() - val embeddedProfile = if (isDng) { + val embeddedProfiles = if (isDng) { DngEmbeddedProfile.readAllFrom(dngFile) - .asSequence() - .filterNot { it.isPhotonHdr } - .filter { it.profile?.toneCurve?.isValid == true } - .sortedBy { it.id != DngEmbeddedProfile.PRIMARY_PROFILE_ID } - .firstOrNull() } else { - null + emptyList() } - // Capture defaults must not opt imported sensor data into HDRNet. The per-photo editor - // is the only place that enables it, regardless of the source RAW container format. - val importedToneMappingParameters = globalToneMappingParameters.withPhotonHdr(false).let { - if (embeddedProfile != null) { - it.withProfileToneMapMode(RawProfileToneMapMode.Profile) - } else { - it + val embeddedPhotonProfile = embeddedProfiles + .firstOrNull { it.isPhotonHdr && it.hasProfileGainTableMap } + val importedHdrProperties = if (embeddedPhotonProfile != null) { + val summary = runCatching { + DngCameraRawProfileXmp.readSceneExposureSummary( + ExifInterface(dngFile).getAttribute(ExifInterface.TAG_XMP), + ) + }.getOrNull() + RawPhotonHdrMetadata.restoreFromSummary(customProperties, summary) + } else { + customProperties + } + val embeddedProfile = embeddedProfiles.asSequence() + .filterNot { it.isPhotonHdr } + .filter { it.profile?.toneCurve?.isValid == true } + .sortedBy { it.id != DngEmbeddedProfile.PRIMARY_PROFILE_ID } + .firstOrNull() + // A valid embedded Photon map carries the capture's rendering intent. Restore it on + // import, but do not opt other RAWs into HDRNet based on the global capture defaults. + val importedToneMappingParameters = globalToneMappingParameters + .withPhotonHdr(embeddedPhotonProfile != null) + .let { + if (embeddedProfile != null) { + it.withProfileToneMapMode(RawProfileToneMapMode.Profile) + } else { + it + } } - } PLog.d( TAG, "Applying RAW tone defaults to imported RAW: " + "profile=${importedToneMappingParameters.profileToneMapMode} " + "embeddedProfile=${embeddedProfile?.profileName ?: "none"} " + + "embeddedPhotonPgtm=${embeddedPhotonProfile?.id ?: "none"} " + "photonHdr=${importedToneMappingParameters.usePhotonHdr} " + "dng=$isDng activation=${when { + embeddedPhotonProfile != null -> "embedded-photon-pgtm" embeddedProfile != null -> "embedded-profile" else -> "manual-only" }}" @@ -5367,6 +5388,7 @@ object GalleryManager { rawEmbeddedDngProfileId = embeddedProfile?.id, rawAutoExposure = false, rawToneMappingParameters = importedToneMappingParameters, + customProperties = importedHdrProperties, ) } @@ -5562,7 +5584,7 @@ object GalleryManager { } else { // 降级:如果 RAW 处理失败,尝试直接解码(某些 DNG 包含内置预览图) // 传递元数据确保旋转信息被正确处理 - tempImportJpeg(uri, context, metadata, photoFile, thumbnailFile) + tempImportJpeg(uri, context, updatedMetadata, photoFile, thumbnailFile) } } if (!deferRawPreview && photoFile.exists()) { @@ -5709,6 +5731,9 @@ object GalleryManager { photonHdrNetPostExposureEv = RawPhotonHdrMetadata.readPostExposureEv( rawMetadata.customProperties, ), + photonHdrNetInputExposureEv = RawPhotonHdrMetadata.readInputExposureEv( + rawMetadata.customProperties, + ), rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode, rawBlackBorderCrop = rawMetadata.rawBlackBorderCrop, spectralFilmStock = updatedMetadata?.spectralFilmStock, diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index d94b7bea..72d6bece 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -572,6 +572,7 @@ class PhotoProcessor( photonHdrRatio = RawPhotonHdrMetadata.read(metadata.customProperties), photonSourceToShortGain = RawPhotonHdrMetadata.readFinalShortGain(metadata.customProperties), photonHdrNetPostExposureEv = RawPhotonHdrMetadata.readPostExposureEv(metadata.customProperties), + photonHdrNetInputExposureEv = RawPhotonHdrMetadata.readInputExposureEv(metadata.customProperties), aspectRatio = resolveRawAspectRatio(metadata), cropRegion = metadata.cropRegion, rotation = metadata.rotation, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngCameraRawProfileXmp.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngCameraRawProfileXmp.kt index 06bd184f..f7709e62 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngCameraRawProfileXmp.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngCameraRawProfileXmp.kt @@ -1,6 +1,9 @@ package com.hinnka.mycamera.raw import java.security.MessageDigest +import java.io.StringReader +import javax.xml.parsers.DocumentBuilderFactory +import org.xml.sax.InputSource /** * Camera Raw treats ProfileGainTableMap and ProfileToneCurve as weighted profile operations. @@ -11,6 +14,25 @@ internal object DngCameraRawProfileXmp { private const val CAMERA_RAW_VERSION = "16.0" private const val PROCESS_VERSION = "15.4" + private const val PHOTON_NAMESPACE = "https://hinnka.github.io/PhotonCamera/xmp/1.0/" + + /** Reads the single Photon recipe summary from embedded DNG XMP. */ + fun readSceneExposureSummary(xmp: String?): String? { + if (xmp == null || xmp.length > 1024 * 1024 || + xmp.contains(" InputSource(StringReader("")) } + val document = builder.parse(InputSource(StringReader(xmp))) + val summaries = document.getElementsByTagNameNS(PHOTON_NAMESPACE, "SummaryText") + if (summaries.length != 1) return@runCatching null + summaries.item(0).textContent?.takeIf { it.isNotBlank() && it.length <= 256 * 1024 } + }.getOrNull() + } fun build( profileLookName: String, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt index 77f3fe0b..fecf77e3 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt @@ -989,6 +989,8 @@ internal object DngPhotonProfileGainTableInputShader { sourceEnd = clamp(sourceEnd, sourceStart + ivec2(1), uImageSize); vec3 profileRgbSum = vec3(0.0); + float maximumShortIntensity = 0.0; + bool validIntensity = true; int sampleCount = 0; for (int y = sourceStart.y; y < sourceEnd.y; ++y) { for (int x = sourceStart.x; x < sourceEnd.x; ++x) { @@ -1008,18 +1010,34 @@ internal object DngPhotonProfileGainTableInputShader { vec3 cameraRgb = storedCameraRgb * uSourceToShortGain; // MGC clamps only positive overrange before box downsampling. Negative // samples remain in the average and are clamped by the final box pass. - vec3 profileRgb = min(uColorCorrectionMatrix * cameraRgb, vec3(1.0)); + vec3 unclippedProfileRgb = uColorCorrectionMatrix * cameraRgb; + // Measure before HDRNet's model-input clamp and box average. + // Small high-energy details can disappear in the model thumbnail + // but still need valid PGTM knots in the full-resolution render. + // Non-negative DNG input weights are componentwise monotone: + // this also bounds engines that clear negative RGB before lookup. + vec3 rangeRgb = max(unclippedProfileRgb, vec3(0.0)); + float tableIntensity = dot(rangeRgb, vec3( + ${DngPhotonProfileGainTableGenerator.PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[0]}, + ${DngPhotonProfileGainTableGenerator.PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[1]}, + ${DngPhotonProfileGainTableGenerator.PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[2]} + )) + min(rangeRgb.r, min(rangeRgb.g, rangeRgb.b)) * + ${DngPhotonProfileGainTableGenerator.PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[3]} + + max(rangeRgb.r, max(rangeRgb.g, rangeRgb.b)) * + ${DngPhotonProfileGainTableGenerator.PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[4]}; + validIntensity = validIntensity && !any(isnan(unclippedProfileRgb)) && + !any(isinf(unclippedProfileRgb)) && !isnan(tableIntensity) && !isinf(tableIntensity); + maximumShortIntensity = max(maximumShortIntensity, tableIntensity); + vec3 profileRgb = min(unclippedProfileRgb, vec3(1.0)); profileRgbSum += profileRgb; ++sampleCount; } } - // MGC deliberately preserves negative black-referenced samples through the box - // downsample and into HDRNet. Only positive overrange is clipped. Clearing the - // negative tail here changes the first convolution's dark-region response and can - // drive the recovered affine grid to its 0.03 minimum-gain floor. - vec3 modelRgb = min( + // MGC's first CCM pass retains signed noise while limiting positive + // overrange; the final box pass clamps the completed mean to [0, 1]. + vec3 modelRgb = clamp( profileRgbSum / float(max(sampleCount, 1)), - vec3(1.0) + vec3(0.0), vec3(1.0) ); // This TFLite is the 1x2 normal HDRNet model recovered from MGC's TensorFlow // graph. Its original fused first-convolution shader constructs channel four from @@ -1037,6 +1055,9 @@ internal object DngPhotonProfileGainTableInputShader { hdrNetInput[outputIndex + 1] = modelRgb.g; hdrNetInput[outputIndex + 2] = modelRgb.b; hdrNetInput[outputIndex + 3] = longLuma; + int rangeIndex = OUTPUT_SIZE.x * OUTPUT_SIZE.y * 4 + + outputPosition.y * OUTPUT_SIZE.x + outputPosition.x; + hdrNetInput[rangeIndex] = validIntensity ? maximumShortIntensity : -1.0; } """.trimIndent() @@ -1355,7 +1376,9 @@ internal class DngPhotonProfileGainTableAlgorithm { val outputRotation: Int, val hdrRatio: Float, val sourceToShortGain: Float, - /** Persisted downstream HDRNet exposure used when regenerating without a viewfinder. */ + /** Exposure applied before model preparation, restored with its own recipe contract. */ + val hdrNetInputExposureEv: Float? = null, + /** Legacy downstream exposure, used only to reconstruct a migration brightness target. */ val hdrNetPostExposureEv: Float? = null, val colorCorrectionMatrix: FloatArray, val hueSatMap: DcpHueSatMap?, @@ -1375,9 +1398,18 @@ internal class DngPhotonProfileGainTableAlgorithm { val map: DngProfileGainTableMap, val hdrRatio: Float? = null, val sourceToShortGain: Float? = null, + val hdrNetInputExposureEv: Float? = null, val hdrNetPostExposureEv: Float? = null, ) + private data class HdrNetExposureCandidate( + val inputExposureEv: Float, + val plan: HdrNetProfileGainTablePlan, + val modelInput: FloatArray, + val coefficients: FloatArray, + val evaluation: DngHdrNetProfileGainTableNative.Evaluation, + ) + private data class GpuPhotonGainCurves( val gains: FloatArray, val textureId: Int, @@ -1501,6 +1533,8 @@ internal class DngPhotonProfileGainTableAlgorithm { val inputFloatCount = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH * DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT * 4 val inputByteCount = inputFloatCount * Float.SIZE_BYTES + val storageFloatCount = inputFloatCount + inputFloatCount / 4 + val storageByteCount = storageFloatCount * Float.SIZE_BYTES RawGlesProgram.logErrors("before HDRNet SSBO capability query") val maxSsboBytes = LongArray(1) GLES30.glGetInteger64v(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE, maxSsboBytes, 0) @@ -1515,10 +1549,10 @@ internal class DngPhotonProfileGainTableAlgorithm { } val maxSsboBindings = IntArray(1) GLES30.glGetIntegerv(GLES31.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS, maxSsboBindings, 0) - if (inputByteCount > usableMaxSsboBytes || maxSsboBindings[0] < 2) { + if (storageByteCount > usableMaxSsboBytes || maxSsboBindings[0] < 2) { PLog.e( TAG, - "HDRNet SSBO requirements unavailable: inputBytes=$inputByteCount " + + "HDRNet SSBO requirements unavailable: inputBytes=$storageByteCount " + "maxBlockBytes=$usableMaxSsboBytes bindings=${maxSsboBindings[0]}", ) return null @@ -1529,7 +1563,7 @@ internal class DngPhotonProfileGainTableAlgorithm { GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferIds[0]) GLES31.glBufferData( GLES31.GL_SHADER_STORAGE_BUFFER, - inputByteCount, + storageByteCount, null, GLES31.GL_DYNAMIC_READ, ) @@ -1590,111 +1624,154 @@ internal class DngPhotonProfileGainTableAlgorithm { activeWarpParameters.size / 8, ) val dehazeTuning = PhotonCoreImagingTuning.dehaze.normalized() - val modelInputBuffer = ByteBuffer.allocateDirect(inputFloatCount * Float.SIZE_BYTES) + val modelInputBuffer = ByteBuffer.allocateDirect(inputByteCount) .order(ByteOrder.nativeOrder()) val modelOutputBuffer = ByteBuffer.allocateDirect( DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT * Float.SIZE_BYTES, ).order(ByteOrder.nativeOrder()) - val plan = basePlan - GLES31.glUseProgram(hdrNetInputProgram) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bufferIds[0]) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bufferIds[1]) - GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_RGB_TEXTURE_UNIT) - GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, linearRgbTextureId) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"), - plan.sourceToShortGain, - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"), - plan.hdrRatio, - ) - GLES31.glDispatchCompute( - GlesComputeWorkGroup.imageGroupCount( - DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH, - ), - GlesComputeWorkGroup.imageGroupCount( - DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT, - ), - 1, - ) - GLES31.glMemoryBarrier( - GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT, - ) - RawGlesProgram.logErrors("prepare HDRNet input") - val modelInput = readFloatStorageBuffer( - bufferId = bufferIds[0], - floatCount = inputFloatCount, - label = "HDRNet input", - ) ?: return null - if (modelInput.any { !it.isFinite() }) { - PLog.e(TAG, "HDRNet input contains a non-finite value") - return null - } - modelInputBuffer.clear() - modelInputBuffer.asFloatBuffer().put(modelInput) - modelInputBuffer.rewind() - modelOutputBuffer.clear() - interpreter.run(modelInputBuffer, modelOutputBuffer) - modelOutputBuffer.rewind() - val coefficients = FloatArray( - DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT, - ) - modelOutputBuffer.asFloatBuffer().get(coefficients) - val evaluation = DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze( - plan = plan, - coefficients = coefficients, - modelInput = modelInput, - outputRotation = input.outputRotation, - dehazeTuning = dehazeTuning, - ) ?: return null - val match = input.viewfinderReference - ?.takeIf { HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED } - ?.let { reference -> - RawLegacyAutoExposureMatcher.solveHdrNetPostExposure( - referenceFrame = reference, - displayLinearRgb = evaluation.displayLinearRgb, - sampleWidth = evaluation.sampleWidth, - sampleHeight = evaluation.sampleHeight, - ) - } - val restoredPostExposureEv = input.hdrNetPostExposureEv - ?.takeIf { HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED } - ?.takeIf(Float::isFinite) - ?.coerceIn( - MeteringSystem.RAW_EXPOSURE_MIN_EV, - MeteringSystem.RAW_EXPOSURE_MAX_EV, + // A candidate owns all data derived from its input exposure. In particular, + // scaling an already-clipped tensor or reusing the previous inference/Dehaze + // would evaluate a different response from the one baked into the selected PGTM. + var cachedCandidate: HdrNetExposureCandidate? = null + fun candidate(inputExposureEv: Float): HdrNetExposureCandidate? { + cachedCandidate?.takeIf { it.inputExposureEv == inputExposureEv }?.let { return it } + if (!inputExposureEv.isFinite() || inputExposureEv !in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV + ) return null + val effectiveShortGain = input.sourceToShortGain * 2f.pow(inputExposureEv) + GLES31.glUseProgram(hdrNetInputProgram) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bufferIds[0]) + GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bufferIds[1]) + GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_RGB_TEXTURE_UNIT) + GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, linearRgbTextureId) + GLES31.glUniform1f( + GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"), + effectiveShortGain, ) - val postExposureEv = match?.exposureEv ?: restoredPostExposureEv ?: 0f - val postExposureSource = when { - !HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED -> "DISABLED" - match != null -> "VIEWFINDER_MATCH" - restoredPostExposureEv != null -> "PERSISTED_CAPTURE_MATCH" + GLES31.glUniform1f( + GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"), + basePlan.hdrRatio, + ) + GLES31.glDispatchCompute( + GlesComputeWorkGroup.imageGroupCount( + DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH, + ), + GlesComputeWorkGroup.imageGroupCount( + DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT, + ), + 1, + ) + GLES31.glMemoryBarrier( + GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT, + ) + RawGlesProgram.logErrors("prepare HDRNet input") + val preparedInput = readFloatStorageBuffer( + bufferId = bufferIds[0], + floatCount = storageFloatCount, + label = "HDRNet input", + ) ?: return null + if (preparedInput.any { !it.isFinite() }) { + PLog.e(TAG, "HDRNet input contains a non-finite value") + return null + } + var maximumShortIntensity = 0f + for (index in inputFloatCount until storageFloatCount) { + val intensity = preparedInput[index] + if (intensity < 0f) { + PLog.e(TAG, "HDRNet PGTM range contains an invalid source intensity") + return null + } + maximumShortIntensity = max(maximumShortIntensity, intensity) + } + val maxTextureSize = IntArray(1) + GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0) + val tableTextureHeight = basePlan.grid.mapPointsH * basePlan.grid.mapPointsV + if (maxTextureSize[0] < tableTextureHeight) { + PLog.e(TAG, "HDRNet PGTM texture height $tableTextureHeight exceeds ${maxTextureSize[0]}") + return null + } + val plan = DngPhotonProfileGainTableGenerator.hdrNetPlan( + rendererBaselineExposureEv = input.rendererBaselineExposureEv, + hdrRatio = input.hdrRatio, + sourceToShortGain = effectiveShortGain, + samplingArea = samplingArea, + maximumShortIntensity = maximumShortIntensity, + maximumTablePoints = maxTextureSize[0], + ) ?: return null + PLog.d(TAG, "HDRNET_PGTM_RANGE maxShortIntensity=$maximumShortIntensity " + + "pointsN=${plan.pointCount} inputRangeScale=${plan.mapInputRangeScale} " + + "lastShortIntensity=${(plan.pointCount - 1f) / (plan.pointCount * plan.mapInputRangeScale)} " + + "source=${linearRgbTextureWidth}x$linearRgbTextureHeight") + val modelInput = preparedInput.copyOf(inputFloatCount) + modelInputBuffer.clear() + modelInputBuffer.asFloatBuffer().put(modelInput) + modelInputBuffer.rewind() + modelOutputBuffer.clear() + interpreter.run(modelInputBuffer, modelOutputBuffer) + modelOutputBuffer.rewind() + val coefficients = FloatArray( + DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT, + ) + modelOutputBuffer.asFloatBuffer().get(coefficients) + val evaluation = DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze( + plan = plan, + coefficients = coefficients, + modelInput = modelInput, + outputRotation = input.outputRotation, + dehazeTuning = dehazeTuning, + ) ?: return null + return HdrNetExposureCandidate( + inputExposureEv, plan, modelInput, coefficients, evaluation, + ).also { cachedCandidate = it } + } + val restoredInputExposureEv = input.hdrNetInputExposureEv + ?.takeIf { it.isFinite() && it in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV } + // A legacy post-EV is not numerically equivalent to an input EV. Reconstruct + // its old displayed brightness, then solve the new complete processing chain. + val legacyPostExposureEv = input.hdrNetPostExposureEv + ?.takeIf { it.isFinite() && it in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV } + val reference = if (restoredInputExposureEv != null) null else { + input.viewfinderReference ?: legacyPostExposureEv?.let { legacyEv -> + val original = candidate(0f) ?: return null + RawLegacyAutoExposureMatcher.legacyHdrNetReference(original.evaluation, legacyEv) + ?: return null + } + } + val exposureMatch = if (restoredInputExposureEv == null && + HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED && reference != null) { + RawLegacyAutoExposureMatcher.solveHdrNetInputExposure(reference) { ev -> + candidate(ev)?.evaluation + } ?: return null + } else null + val inputExposureEv = restoredInputExposureEv ?: exposureMatch?.exposureEv ?: 0f + val selected = candidate(inputExposureEv) ?: return null + val plan = selected.plan + val modelInput = selected.modelInput + val coefficients = selected.coefficients + val evaluation = selected.evaluation + val exposureSource = when { + restoredInputExposureEv != null -> "PERSISTED_INPUT_EXPOSURE" + exposureMatch?.matchedReference == false -> "UNUSABLE_REFERENCE" + input.viewfinderReference != null -> "VIEWFINDER_MATCH" + legacyPostExposureEv != null -> "LEGACY_BRIGHTNESS_TARGET" else -> "NONE" } - PLog.i( - TAG, - "HDRNET_MATCH stage=SELECTED shortGain=${plan.sourceToShortGain} " + - "hdrRatio=${plan.hdrRatio} " + - "postExposureEv=$postExposureEv " + - "postExposureSource=$postExposureSource " + - "matchRate=${match?.matchRate} " + - "meanAbsoluteErrorEv=${match?.meanAbsoluteErrorEv} " + - "postDehazeP99Peak=${evaluation.postDehazeP99Peak} " + - "dehazeActive=${dehazeTuning.isActive} " + - "dehazeLow=${evaluation.dehazeCurve.hazePointLow} " + - "dehazeHigh=${evaluation.dehazeCurve.hazePointHigh} " + - "dhaScale=${evaluation.dehazeCurve.highlightScale} " + - "dhaDetected=${evaluation.dehazeCurve.detectedHighlightScale} " + - "dehazeSamples=${evaluation.dehazeCurve.sampledPixelCount}", - ) + PLog.i(TAG, "HDRNET_MATCH stage=SELECTED " + + "physicalShortGain=${input.sourceToShortGain} effectiveShortGain=${plan.sourceToShortGain} " + + "hdrRatio=${plan.hdrRatio} inputExposureEv=$inputExposureEv source=$exposureSource " + + "postDehazeP99Peak=${evaluation.postDehazeP99Peak} " + + "dehazeLow=${evaluation.dehazeCurve.hazePointLow} " + + "dehazeHigh=${evaluation.dehazeCurve.hazePointHigh} " + + "dhaScale=${evaluation.dehazeCurve.highlightScale} pointsN=${plan.pointCount}") val map = DngPhotonProfileGainTableGenerator.mapFromHdrNetCoefficients( plan = plan, coefficients = coefficients, modelInput = modelInput, dehazeCurve = evaluation.dehazeCurve, - postExposureEv = postExposureEv, + postExposureEv = 0f, ) ?: return null val textureId = uploadProfileGainTableTexture(map) ?: return null try { @@ -1706,8 +1783,8 @@ internal class DngPhotonProfileGainTableAlgorithm { return Output( map = map, hdrRatio = plan.hdrRatio, - sourceToShortGain = plan.sourceToShortGain, - hdrNetPostExposureEv = postExposureEv, + sourceToShortGain = input.sourceToShortGain, + hdrNetInputExposureEv = inputExposureEv, ) } catch (error: Throwable) { PLog.e(TAG, "HDRNet ProfileGainTableMap generation failed", error) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt index afe5d605..54b41475 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt @@ -3,12 +3,14 @@ package com.hinnka.mycamera.raw import com.hinnka.mycamera.processor.PhotonDehazeTuning import com.hinnka.mycamera.utils.PLog import kotlin.math.ln +import kotlin.math.ceil /** Builds a DNG ProfileGainTableMap2 from MGC HDRNet's bilateral affine coefficient grid. */ internal object DngPhotonProfileGainTableGenerator { private const val TAG = "DngPhotonProfileGainTableGenerator" private const val TABLE_POINTS = 257 + private const val HDRNET_MAX_TABLE_POINTS = 4096 private const val TARGET_TILE_PX = 64 private const val GRID_MIN_H = 8 private const val GRID_MIN_V = 6 @@ -114,7 +116,8 @@ internal object DngPhotonProfileGainTableGenerator { * HDRNet runs in the final-short-exposure linear domain: `RAW * sourceToShortGain`. * A conforming renderer folds its total BaselineExposure into the ProfileGainTableMap N * coordinate, so the stored weights cancel that renderer gain and reconstruct the same - * `RAW * sourceToShortGain` coordinate used to build the table. BaselineExposure has no role + * `RAW * sourceToShortGain` domain used to build the table. The N axis is additionally scaled + * to cover the measured source intensity range. BaselineExposure has no role * in HDRNet inference or viewfinder matching. */ fun hdrNetPlan( @@ -122,10 +125,14 @@ internal object DngPhotonProfileGainTableGenerator { hdrRatio: Float, sourceToShortGain: Float, samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL, + maximumShortIntensity: Float = 0f, + maximumTablePoints: Int = HDRNET_MAX_TABLE_POINTS, ): HdrNetProfileGainTablePlan? { if (!rendererBaselineExposureEv.isFinite() || !hdrRatio.isFinite() || hdrRatio <= 0f || - !sourceToShortGain.isFinite() || sourceToShortGain <= 0f + !sourceToShortGain.isFinite() || sourceToShortGain <= 0f || + !maximumShortIntensity.isFinite() || maximumShortIntensity < 0f || + maximumTablePoints < TABLE_POINTS ) { return null } @@ -135,8 +142,27 @@ internal object DngPhotonProfileGainTableGenerator { } // Adobe evaluates MapInputWeights after applying TotalBaselineExposure (including any // profile offset). Cancel that entire renderer factor: both HDRNet and the PGTM N axis - // must operate on RAW * finalShortGain, independently of the display-exposure target. - val mapInputScale = sourceToShortGain / rendererBaselineGain + // must operate on RAW * finalShortGain (with the table range scale below), independently + // of the display-exposure target. + // DNG clamps the table index at N-1, then multiplies the original RGB by + // that last gain. If captured highlights exceed the table domain, their + // compressed response suddenly becomes linear again (bright islands). + // Add knots at the original 1/257 spacing and scale the stored weights + // inversely: pointCount * rangeScale stays 257, preserving existing knots. + val pointLimit = minOf(maximumTablePoints, HDRNET_MAX_TABLE_POINTS) + val requiredPoints = maxOf( + TABLE_POINTS.toDouble(), + ceil(maximumShortIntensity.toDouble() * TABLE_POINTS) + 1.0, + ) + val pointCount = minOf(requiredPoints, pointLimit.toDouble()).toInt() + val rangeScale = if (requiredPoints <= pointLimit) { + TABLE_POINTS.toFloat() / pointCount + } else { + // Respect the renderer's texture/memory budget while still covering + // the complete source range; only the knot density is reduced. + ((pointCount - 1).toDouble() / pointCount / maximumShortIntensity).toFloat() + } + val mapInputScale = sourceToShortGain / rendererBaselineGain * rangeScale if (!mapInputScale.isFinite() || mapInputScale <= 0f) return null val mapInputWeights = FloatArray(PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS.size) { index -> PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[index] * mapInputScale @@ -152,13 +178,14 @@ internal object DngPhotonProfileGainTableGenerator { mapOriginH = samplingArea.originH + 0.5 * spacingH, mapOriginV = samplingArea.originV + 0.5 * spacingV, ), - pointCount = TABLE_POINTS, + pointCount = pointCount, mapInputWeights = mapInputWeights, gamma = 1f, rendererBaselineGain = rendererBaselineGain, sourceToShortGain = sourceToShortGain, // The native MGC path builds the long-exposure guide from a ratio of at least one. hdrRatio = hdrRatio.coerceAtLeast(1f), + mapInputRangeScale = rangeScale, ) } @@ -167,7 +194,8 @@ internal object DngPhotonProfileGainTableGenerator { * * The extracted network returns one scale and one bias for every 16 x 12 x 8 grid entry. * DNG can only apply a scalar multiplicative gain, so each spatial cell's affine response is - * resampled to 64 x 48 and converted into a 257-point gain curve per cell. The range + * resampled to 64 x 48 and converted into a gain curve per cell, extending the original + * 257-knot domain to cover captured highlights. The range * coordinate uses MGC's learned 16-segment luma guide from guide_coeffs.pb before trilinear * sampling of the bilateral grid. The selected model input supplies each cell's local * chromaticity so the downstream arithmetic-RGB Dehaze curve is represented by the scalar @@ -438,6 +466,8 @@ internal data class HdrNetProfileGainTablePlan( /** Gain from source RAW to the candidate final-short exposure used by HDRNet. */ val sourceToShortGain: Float, val hdrRatio: Float, + /** Maps the captured final-short intensity range into the DNG table's unit N axis. */ + val mapInputRangeScale: Float = 1f, ) { init { require(grid.mapPointsH == DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH) @@ -448,10 +478,12 @@ internal data class HdrNetProfileGainTablePlan( require(rendererBaselineGain.isFinite() && rendererBaselineGain > 0f) require(sourceToShortGain.isFinite() && sourceToShortGain > 0f) require(hdrRatio.isFinite() && hdrRatio >= 1f) + require(mapInputRangeScale.isFinite() && mapInputRangeScale > 0f && mapInputRangeScale <= 1f) val rendererMapInputEffectiveScale = mapInputWeights.sum() * rendererBaselineGain + val expectedScale = sourceToShortGain * mapInputRangeScale require( - kotlin.math.abs(rendererMapInputEffectiveScale - sourceToShortGain) <= - maxOf(1e-6f, sourceToShortGain * 1e-5f) + kotlin.math.abs(rendererMapInputEffectiveScale - expectedScale) <= + maxOf(1e-6f, expectedScale * 1e-5f) ) } 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 c9c8a9c3..c3ee98f5 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDemosaicProcessor.kt @@ -1835,6 +1835,7 @@ class RawDemosaicProcessor { photonHdrRatio: Float? = null, photonSourceToShortGain: Float? = null, photonHdrNetPostExposureEv: Float? = null, + photonHdrNetInputExposureEv: Float? = null, rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), onMetadata: ((RawMetadata) -> Unit)? = null @@ -1882,6 +1883,7 @@ class RawDemosaicProcessor { photonHdrRatio = photonHdrRatio, photonSourceToShortGain = photonSourceToShortGain, photonHdrNetPostExposureEv = photonHdrNetPostExposureEv, + photonHdrNetInputExposureEv = photonHdrNetInputExposureEv, rawCfaCorrectionMode = rawCfaCorrectionMode, rawBlackBorderCrop = rawBlackBorderCrop, dngFile = dngFile, @@ -2080,6 +2082,7 @@ class RawDemosaicProcessor { photonHdrRatio: Float? = null, photonSourceToShortGain: Float? = null, photonHdrNetPostExposureEv: Float? = null, + photonHdrNetInputExposureEv: Float? = null, onMetadata: ((RawMetadata) -> Unit)? = null ): RawHdrRenderResult? = withContext(glDispatcher) { val dngFile = File(dngFilePath) @@ -2131,6 +2134,7 @@ class RawDemosaicProcessor { photonHdrRatio = photonHdrRatio, photonSourceToShortGain = photonSourceToShortGain, photonHdrNetPostExposureEv = photonHdrNetPostExposureEv, + photonHdrNetInputExposureEv = photonHdrNetInputExposureEv, ) } catch (e: Exception) { PLog.e(TAG, "Failed to process RAW HDR sources: $dngFilePath", e) @@ -2190,6 +2194,7 @@ class RawDemosaicProcessor { photonHdrRatio: Float? = null, photonSourceToShortGain: Float? = null, photonHdrNetPostExposureEv: Float? = null, + photonHdrNetInputExposureEv: Float? = null, onMetadata: ((RawMetadata) -> Unit)? = null, ): RawHdrRenderResult? = withContext(glDispatcher) { if ((rawData == null && gpuLinearRgbSource == null) || @@ -2286,6 +2291,7 @@ class RawDemosaicProcessor { photonHdrRatio = photonHdrRatio, photonSourceToShortGain = photonSourceToShortGain, photonHdrNetPostExposureEv = photonHdrNetPostExposureEv, + photonHdrNetInputExposureEv = photonHdrNetInputExposureEv, defaultCropIsAuthoritative = true, ) } catch (e: Exception) { @@ -2344,6 +2350,7 @@ class RawDemosaicProcessor { photonHdrRatio: Float? = null, photonSourceToShortGain: Float? = null, photonHdrNetPostExposureEv: Float? = null, + photonHdrNetInputExposureEv: Float? = null, rawCfaCorrectionMode: String? = null, rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(), dngFile: File? = null, @@ -3467,7 +3474,10 @@ class RawDemosaicProcessor { val selectedCaptureHdrRatio = captureProfileOutput?.hdrRatio ?: captureHdrRatio val selectedCaptureSourceToShortGain = captureProfileOutput?.sourceToShortGain ?: captureSourceToShortGain - val captureSummaryText = solvedSceneExposure?.summaryText?.let { summary -> + val captureSummaryText = (solvedSceneExposure?.summaryText + ?: captureProfileOutput?.hdrNetInputExposureEv?.let { + "PhotonCamera RAW AE SummaryText v1" + })?.let { summary -> val output = captureProfileOutput ?: return@let summary val outputShortGain = output.sourceToShortGain ?: return@let summary val outputHdrRatio = output.hdrRatio ?: return@let summary @@ -3479,9 +3489,12 @@ class RawDemosaicProcessor { appendLine("hdrNetFinalShortGain=$outputShortGain") appendLine("hdrNetFinalLongGain=${outputShortGain * outputHdrRatio}") appendLine("hdrNetFinalHdrRatio=$outputHdrRatio") - appendLine( - "hdrNetPostExposureEv=${output.hdrNetPostExposureEv ?: 0f}", - ) + RawPhotonHdrMetadata.appendInputExposureSummary(this, output.hdrNetInputExposureEv) + if (output.hdrNetInputExposureEv == null) { + output.hdrNetPostExposureEv?.let { + appendLine("hdrNetPostExposureEv=$it") + } + } }.trimEnd() } val captureProfileFailed = @@ -3505,6 +3518,7 @@ class RawDemosaicProcessor { hdrRatio = selectedCaptureHdrRatio, finalShortGain = selectedCaptureSourceToShortGain, hdrNetPostExposureEv = captureProfileOutput?.hdrNetPostExposureEv, + hdrNetInputExposureEv = captureProfileOutput?.hdrNetInputExposureEv, rawSceneExposureSummaryText = captureSummaryText, profileGainTableMap = captureProfileGainTableMap, gpuDemosaicedRawSource = reusableDemosaicSource, @@ -3516,6 +3530,7 @@ class RawDemosaicProcessor { var hdrNetSceneExposureGain = RawHdrReferenceMath.hdrNetSceneExposureGain( photonHdrRatio, photonSourceToShortGain, photonHdrNetPostExposureEv, + photonHdrNetInputExposureEv, ) if (regeneratePhotonPgtm) { val persistedHdrRatio = photonHdrRatio?.takeIf { it.isFinite() && it >= 1f } @@ -3526,6 +3541,11 @@ class RawDemosaicProcessor { it.isFinite() && it in MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV } + val persistedInputExposureEv = photonHdrNetInputExposureEv + ?.takeIf { + it.isFinite() && it in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV + } val usePersistedCaptureAe = persistedHdrRatio != null && persistedSourceToShortGain != null val estimatedExposure = if (usePersistedCaptureAe) { @@ -3551,10 +3571,10 @@ class RawDemosaicProcessor { ?.takeIf { it.isFinite() && it >= 1f } val estimatedSourceToShortGain = estimatedExposure?.finalShortGain ?.takeIf { it.isFinite() && it > 0f } - // Capture-time short gain and HDR ratio describe the fixed HDRNet inference. - // The downstream viewfinder-match exposure is persisted independently so PGTM - // refresh can reproduce the composed result without changing model inputs. - // ML AE remains a fallback for older metadata contracts. + // Physical short gain and ratio remain separate from the versioned HDRNet + // input exposure. Legacy post EV is only a target-reconstruction hint; the + // generator must not reinterpret it as an input EV. ML AE is the fallback + // when an imported RAW has no complete capture recipe. val useEstimatedAe = !usePersistedCaptureAe && estimatedHdrRatio != null && estimatedSourceToShortGain != null val regenerationHdrRatio = when { @@ -3591,6 +3611,7 @@ class RawDemosaicProcessor { "finalShortGain=$regenerationSourceToShortGain " + "finalLongGain=$regenerationLongGain " + "postExposureEv=${persistedPostExposureEv ?: 0f} " + + "inputExposureEv=$persistedInputExposureEv " + "aeSource=$regenerationAeSource " + "sourceBaselineEv=${actualMetadata.baselineExposure} " + "sourceBaselineGain=${exactDngBaselineExposureGain(actualMetadata)} " + @@ -3617,6 +3638,7 @@ class RawDemosaicProcessor { hdrRatio = regenerationHdrRatio, sourceToShortGain = regenerationSourceToShortGain, hdrNetPostExposureEv = persistedPostExposureEv, + hdrNetInputExposureEv = persistedInputExposureEv, colorCorrectionMatrix = linearColorCorrectionMatrix, hueSatMap = activeDcpRenderPlan?.hueSatMap, hueSatMapSupportsOverrange = hueSatMapSupportsOverrange, @@ -3636,6 +3658,7 @@ class RawDemosaicProcessor { regeneratedPhotonPgtm.hdrRatio, regeneratedPhotonPgtm.sourceToShortGain, regeneratedPhotonPgtm.hdrNetPostExposureEv, + regeneratedPhotonPgtm.hdrNetInputExposureEv, ) PLog.i( TAG, @@ -3645,7 +3668,8 @@ class RawDemosaicProcessor { regeneratedPhotonPgtm.map.mapPointsN + " hdrRatio=${regeneratedPhotonPgtm.hdrRatio}" + " finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}" + - " postExposureEv=${regeneratedPhotonPgtm.hdrNetPostExposureEv}", + " postExposureEv=${regeneratedPhotonPgtm.hdrNetPostExposureEv}" + + " inputExposureEv=${regeneratedPhotonPgtm.hdrNetInputExposureEv}", ) } @@ -3672,9 +3696,9 @@ class RawDemosaicProcessor { applyDngBaselineExposure = applyProfileDngBaselineExposure, useRamp = useProfileExposureRamp ) - // HDRNet's PGTM includes short -> long fusion and post exposure, while its lookup - // weights encode only the short coordinate. BaselineExposure cannot recover that - // scene reference. Carry the captured long gain separately and apply edit EV once. + // HDRNet's PGTM includes its input exposure and short -> long response. Keep the + // physical long gain and recipe EV explicit for the HDR scene reference rather + // than inferring either from PGTM weights; apply the user's edit EV once. val hdrReferenceSceneExposureGain = hdrNetSceneExposureGain ?.takeIf { photonHdrRequested && hasProfileGainTableMap } ?.let { it * 2f.pow(profileExposureCompensation) } @@ -4710,6 +4734,7 @@ class RawDemosaicProcessor { hdrRatio: Float, sourceToShortGain: Float, hdrNetPostExposureEv: Float? = null, + hdrNetInputExposureEv: Float? = null, colorCorrectionMatrix: FloatArray, hueSatMap: DcpHueSatMap?, hueSatMapSupportsOverrange: Boolean, @@ -4754,6 +4779,7 @@ class RawDemosaicProcessor { hdrRatio = hdrRatio, sourceToShortGain = sourceToShortGain, hdrNetPostExposureEv = hdrNetPostExposureEv, + hdrNetInputExposureEv = hdrNetInputExposureEv, colorCorrectionMatrix = colorCorrectionMatrix, hueSatMap = hueSatMap, hueSatMapSupportsOverrange = hueSatMapSupportsOverrange, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt index 193a0f54..5782f13c 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt @@ -112,10 +112,12 @@ data class RawDngCaptureProfileResult( val exposureOffsetEv: Float?, /** Photon HDR long/short TET ratio; always null for classic auto exposure. */ val hdrRatio: Float?, - /** Fixed source/short gain used by Photon HDR inference. */ + /** Physical source/short gain before the independent HDRNet input exposure. */ val finalShortGain: Float?, - /** Viewfinder-match exposure applied after HDRNet + Dehaze/DHA; null for non-HDRNet paths. */ + /** Legacy downstream exposure, retained only to reconstruct older rendering targets. */ val hdrNetPostExposureEv: Float? = null, + /** Exposure applied before HDRNet inference, independently of the physical short gain. */ + val hdrNetInputExposureEv: Float? = null, /** Capture-time MGC AE inputs and results serialized as photon:SummaryText in the DNG XMP. */ val rawSceneExposureSummaryText: String? = null, val profileGainTableMap: DngProfileGainTableMap?, @@ -138,85 +140,13 @@ data class RawDngProfilePreparation( val hdrRatio: Float?, val finalShortGain: Float?, val hdrNetPostExposureEv: Float? = null, + /** Exposure applied before HDRNet inference, independently of the physical short gain. */ + val hdrNetInputExposureEv: Float? = null, val rawSceneExposureSummaryText: String? = null, val profileGainTableMap: DngProfileGainTableMap?, val gpuDemosaicedRawSource: GpuDemosaicedRawSource? = null, ) -/** Process-local capture result persisted with Photon gallery metadata for PGTM regeneration. */ -internal object RawPhotonHdrMetadata { - private const val PROPERTY = "photonHdrNetRatio" - private const val CONTRACT_PROPERTY = "photonHdrNetRatioContract" - private const val CURRENT_CONTRACT = "mgc_fast_moments_v25_portrait_mask_v1" - private const val SHORT_GAIN_PROPERTY = "photonHdrNetSourceToShortGain" - private const val SHORT_GAIN_CONTRACT_PROPERTY = "photonHdrNetSourceToShortGainContract" - private const val CURRENT_SHORT_GAIN_CONTRACT = "mgc_fast_moments_v25_final_short_v1" - private const val POST_EXPOSURE_PROPERTY = "photonHdrNetPostExposureEv" - private const val POST_EXPOSURE_CONTRACT_PROPERTY = - "photonHdrNetPostExposureEvContract" - private const val CURRENT_POST_EXPOSURE_CONTRACT = - "hdrnet_post_dehaze_viewfinder_rolloff_v2" - - fun read(properties: Map): Float? = properties[PROPERTY] - ?.toFloatOrNull() - ?.takeIf { it.isFinite() && it >= 1f } - - fun readFinalShortGain(properties: Map): Float? { - if (properties[SHORT_GAIN_CONTRACT_PROPERTY] != CURRENT_SHORT_GAIN_CONTRACT) return null - return properties[SHORT_GAIN_PROPERTY] - ?.toFloatOrNull() - ?.takeIf { it.isFinite() && it > 0f } - } - - fun readPostExposureEv(properties: Map): Float? { - if (properties[POST_EXPOSURE_CONTRACT_PROPERTY] != - CURRENT_POST_EXPOSURE_CONTRACT - ) return null - return properties[POST_EXPOSURE_PROPERTY] - ?.toFloatOrNull() - ?.takeIf { - it.isFinite() && it in - MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV - } - } - - fun write( - properties: Map, - hdrRatio: Float?, - finalShortGain: Float? = null, - postExposureEv: Float? = null, - ): Map { - val validRatio = hdrRatio?.takeIf { it.isFinite() && it >= 1f } ?: return properties - var result = properties + mapOf( - PROPERTY to validRatio.toString(), - CONTRACT_PROPERTY to CURRENT_CONTRACT, - ) - val validShortGain = finalShortGain?.takeIf { it.isFinite() && it > 0f } - if (validShortGain != null) { - result += mapOf( - SHORT_GAIN_PROPERTY to validShortGain.toString(), - SHORT_GAIN_CONTRACT_PROPERTY to CURRENT_SHORT_GAIN_CONTRACT, - ) - } - val validPostExposureEv = postExposureEv?.takeIf { - it.isFinite() && it in - MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV - } - if (validPostExposureEv != null) { - result += mapOf( - POST_EXPOSURE_PROPERTY to validPostExposureEv.toString(), - POST_EXPOSURE_CONTRACT_PROPERTY to CURRENT_POST_EXPOSURE_CONTRACT, - ) - } - return result - } - - fun isCurrentCaptureContract(properties: Map): Boolean { - return properties[CONTRACT_PROPERTY] == CURRENT_CONTRACT - } -} - - /** Capture-request AE compensation persisted independently from presentation ExposureBias. */ internal object RawCaptureExposureCompensationMetadata { private const val PROPERTY = "captureAeExposureCompensationEv" diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawHdrReferenceMath.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawHdrReferenceMath.kt index be9c8755..6187a2f1 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawHdrReferenceMath.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawHdrReferenceMath.kt @@ -32,18 +32,19 @@ object RawHdrReferenceMath { private const val MIN_INTERVAL = 1e-4f private const val MIN_WHITE = 1e-4f - /** RAW -> HDRNet long exposure, including its persisted post-Dehaze exposure edit. */ + /** RAW -> HDRNet long reference; new input exposure takes precedence over legacy post EV. */ internal fun hdrNetSceneExposureGain( hdrRatio: Float?, sourceToShortGain: Float?, postExposureEv: Float?, + inputExposureEv: Float? = null, ): Float? { if (hdrRatio == null || !hdrRatio.isFinite() || hdrRatio < 1f || sourceToShortGain == null || !sourceToShortGain.isFinite() || sourceToShortGain <= 0f ) return null - val postEv = postExposureEv ?: 0f - if (!postEv.isFinite()) return null - return (sourceToShortGain * hdrRatio * 2f.pow(postEv)) + val exposureEv = inputExposureEv ?: postExposureEv ?: 0f + if (!exposureEv.isFinite()) return null + return (sourceToShortGain * hdrRatio * 2f.pow(exposureEv)) .takeIf { it.isFinite() && it > 0f } } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt index c073f15c..31d853b3 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt @@ -75,11 +75,13 @@ internal data class RawLegacyHighlightExposureLimit( /** * Capture-side viewfinder matching derived from PhotonCamera 1.27.1's spatial solver. Native code * owns reference linearization, robust grid statistics and exposure selection. HDRNet matching - * evaluates its completed processing chain once and solves only a downstream scalar exposure. + * rerenders the complete HDRNet and Dehaze chain at each proposed input exposure. */ internal object RawLegacyAutoExposureMatcher { private const val TAG = "RawLegacyAutoExposureMatcher" private const val PREVIEW_LONG_EDGE = 256 + private const val HDRNET_GRID_COLUMNS = 8 + private const val HDRNET_GRID_ROWS = 6 private const val PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION = 0.045f private data class ViewfinderReference( val frame: RawLegacyExposurePreviewFrame, @@ -96,6 +98,11 @@ internal object RawLegacyAutoExposureMatcher { val meanAbsoluteErrorEv: Float, ) + data class HdrNetInputExposureMatch( + val exposureEv: Float, + val matchedReference: Boolean, + ) + fun createRequest( capturePreviewThumbnail: Bitmap?, capturePortraitMask: PortraitMaskSnapshot? = null, @@ -255,6 +262,91 @@ internal object RawLegacyAutoExposureMatcher { } } + /** Scores completed HDRNet candidates; no exposure is applied after their tone response. */ + fun solveHdrNetInputExposure( + referenceFrame: RawLegacyExposurePreviewFrame, + renderSample: (Float) -> DngHdrNetProfileGainTableNative.Evaluation?, + ): HdrNetInputExposureMatch? { + val solver = RawLegacyAutoExposureNativeBridge.Solver.create(referenceFrame) + ?: run { + PLog.i(TAG, "HDRNet input-exposure matching skipped: " + + "no reliable reference cells; retaining input exposureEv=0") + return HdrNetInputExposureMatch(0f, false) + } + return solver.use { + if (!solver.configureHdrNetPriority()) return@use null + var candidateCount = 0 + while (true) { + val exposureEv = solver.nextExposureEv() ?: break + val evaluation = renderSample(exposureEv) ?: return@use null + val grid = completedHdrNetLumaGrid(evaluation) ?: return@use null + if (!solver.submitCandidate( + exposureEv, + grid, + HDRNET_GRID_COLUMNS, + HDRNET_GRID_ROWS, + ) + ) return@use null + candidateCount++ + } + solver.resultExposureEv()?.let { result -> + PLog.i(TAG, "HDRNet input-exposure matching result: " + + "exposureEv=$result candidates=$candidateCount") + HdrNetInputExposureMatch(result, true) + } + } + } + + private fun completedHdrNetLumaGrid( + evaluation: DngHdrNetProfileGainTableNative.Evaluation, + ): FloatArray? { + val width = evaluation.sampleWidth + val height = evaluation.sampleHeight + val rgb = evaluation.displayLinearRgb + if (width < HDRNET_GRID_COLUMNS || height < HDRNET_GRID_ROWS || + rgb.size.toLong() != width.toLong() * height * 3 + ) return null + val sums = DoubleArray(HDRNET_GRID_COLUMNS * HDRNET_GRID_ROWS) + val counts = IntArray(sums.size) + for (y in 0 until height) { + for (x in 0 until width) { + val offset = (y * width + x) * 3 + val red = rgb[offset] + val green = rgb[offset + 1] + val blue = rgb[offset + 2] + if (!red.isFinite() || !green.isFinite() || !blue.isFinite()) return null + val cell = (y * HDRNET_GRID_ROWS / height) * HDRNET_GRID_COLUMNS + + x * HDRNET_GRID_COLUMNS / width + // Match the displayed image: clip individual channels before the cell mean. + sums[cell] += red.coerceIn(0f, 1f) * 0.2126 + + green.coerceIn(0f, 1f) * 0.7152 + blue.coerceIn(0f, 1f) * 0.0722 + counts[cell]++ + } + } + return FloatArray(sums.size) { (sums[it] / counts[it]).toFloat() } + } + + /** Reconstructs the old displayed target for a DNG without its capture viewfinder. */ + fun legacyHdrNetReference( + evaluation: DngHdrNetProfileGainTableNative.Evaluation, + postExposureEv: Float, + ): RawLegacyExposurePreviewFrame? { + if (evaluation.sampleWidth <= 0 || evaluation.sampleHeight <= 0 || + evaluation.displayLinearRgb.size.toLong() != + evaluation.sampleWidth.toLong() * evaluation.sampleHeight * 3 || + !postExposureEv.isFinite() + ) return null + val pixels = RawLegacyAutoExposureNativeBridge.legacyHdrNetReferencePixels( + evaluation.displayLinearRgb, + postExposureEv, + ) ?: return null + return RawLegacyExposurePreviewFrame( + evaluation.sampleWidth, + evaluation.sampleHeight, + pixels, + ) + } + /** * Matches the composed HDRNet -> Dehaze/DHA RGB through the downstream SLM gain response. * HDRNet input exposure and HDR ratio remain fixed. Native selection maximizes the weighted @@ -269,7 +361,7 @@ internal object RawLegacyAutoExposureMatcher { ): HdrNetPostExposureMatch? { if (sampleWidth <= 0 || sampleHeight <= 0 || displayLinearRgb.size.toLong() != sampleWidth.toLong() * sampleHeight * 3 || - displayLinearRgb.any { !it.isFinite() || it < 0f } + displayLinearRgb.any { !it.isFinite() || it !in 0f..1f } ) return null val solver = RawLegacyAutoExposureNativeBridge.Solver.create(referenceFrame) ?: run { diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt index d064569a..828603d8 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt @@ -90,6 +90,11 @@ internal object RawLegacyAutoExposureNativeBridge { return nativeConfigureExposureBounds(handle, minimumEv, maximumEv) } + fun configureHdrNetPriority(): Boolean { + check(handle != 0L) { "Native exposure solver is closed" } + return nativeConfigureHdrNetPriority(handle) + } + fun resultExposureEv(): Float? { check(handle != 0L) { "Native exposure solver is closed" } return nativeGetResultExposureEv(handle).takeIf { it.isFinite() } @@ -155,6 +160,13 @@ internal object RawLegacyAutoExposureNativeBridge { maximumEv: Float, ): Boolean + private external fun nativeConfigureHdrNetPriority(handle: Long): Boolean + + external fun legacyHdrNetReferencePixels( + displayLinearRgb: FloatArray, + postExposureEv: Float, + ): IntArray? + private external fun nativeGetResultExposureEv(handle: Long): Float private external fun nativeDestroy(handle: Long) diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadata.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadata.kt new file mode 100644 index 00000000..97c3fb46 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadata.kt @@ -0,0 +1,139 @@ +package com.hinnka.mycamera.raw + +/** Versioned HDRNet recipe shared by gallery metadata and the embedded Photon XMP summary. */ +internal object RawPhotonHdrMetadata { + private const val PROPERTY = "photonHdrNetRatio" + private const val CONTRACT_PROPERTY = "photonHdrNetRatioContract" + private const val CURRENT_CONTRACT = "mgc_fast_moments_v25_portrait_mask_v1" + private const val SHORT_GAIN_PROPERTY = "photonHdrNetSourceToShortGain" + private const val SHORT_GAIN_CONTRACT_PROPERTY = "photonHdrNetSourceToShortGainContract" + private const val CURRENT_SHORT_GAIN_CONTRACT = "mgc_fast_moments_v25_final_short_v1" + private const val POST_EXPOSURE_PROPERTY = "photonHdrNetPostExposureEv" + private const val POST_EXPOSURE_CONTRACT_PROPERTY = + "photonHdrNetPostExposureEvContract" + private const val CURRENT_POST_EXPOSURE_CONTRACT = + "hdrnet_post_dehaze_viewfinder_rolloff_v2" + private const val INPUT_EXPOSURE_PROPERTY = "photonHdrNetInputExposureEv" + private const val INPUT_EXPOSURE_CONTRACT_PROPERTY = "photonHdrNetInputExposureEvContract" + const val INPUT_EXPOSURE_CONTRACT = "hdrnet_input_viewfinder_v1" + private const val SUMMARY_INPUT_EXPOSURE = "hdrNetInputExposureEv" + private const val SUMMARY_INPUT_EXPOSURE_CONTRACT = "hdrNetInputExposureEvContract" + + fun read(properties: Map): Float? = properties[PROPERTY] + ?.toFloatOrNull() + ?.takeIf { it.isFinite() && it >= 1f } + + fun readFinalShortGain(properties: Map): Float? { + if (properties[SHORT_GAIN_CONTRACT_PROPERTY] != CURRENT_SHORT_GAIN_CONTRACT) return null + return properties[SHORT_GAIN_PROPERTY] + ?.toFloatOrNull() + ?.takeIf { it.isFinite() && it > 0f } + } + + fun readPostExposureEv(properties: Map): Float? { + // An input-exposure recipe must never resurrect a stale post-exposure value. + if (INPUT_EXPOSURE_CONTRACT_PROPERTY in properties) return null + if (properties[POST_EXPOSURE_CONTRACT_PROPERTY] != + CURRENT_POST_EXPOSURE_CONTRACT + ) return null + return properties[POST_EXPOSURE_PROPERTY] + ?.toFloatOrNull() + ?.takeIf { + it.isFinite() && it in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV + } + } + + fun readInputExposureEv(properties: Map): Float? { + if (properties[INPUT_EXPOSURE_CONTRACT_PROPERTY] != INPUT_EXPOSURE_CONTRACT || + !isCurrentCaptureContract(properties) || + read(properties) == null || readFinalShortGain(properties) == null + ) return null + return properties[INPUT_EXPOSURE_PROPERTY]?.toFloatOrNull()?.takeIf(::isValidExposureEv) + } + + fun write( + properties: Map, + hdrRatio: Float?, + finalShortGain: Float? = null, + postExposureEv: Float? = null, + inputExposureEv: Float? = null, + ): Map { + val validRatio = hdrRatio?.takeIf { it.isFinite() && it >= 1f } ?: return properties + val validShortGain = finalShortGain?.takeIf { it.isFinite() && it > 0f } + val validInputExposureEv = inputExposureEv?.takeIf(::isValidExposureEv) + if (inputExposureEv != null && + (validInputExposureEv == null || validShortGain == null) + ) return properties + var result = properties + mapOf( + PROPERTY to validRatio.toString(), + CONTRACT_PROPERTY to CURRENT_CONTRACT, + ) + if (validShortGain != null) { + result += mapOf( + SHORT_GAIN_PROPERTY to validShortGain.toString(), + SHORT_GAIN_CONTRACT_PROPERTY to CURRENT_SHORT_GAIN_CONTRACT, + ) + } + val validPostExposureEv = postExposureEv?.takeIf(::isValidExposureEv) + if (validInputExposureEv != null) { + result = result - POST_EXPOSURE_PROPERTY - POST_EXPOSURE_CONTRACT_PROPERTY + result += mapOf( + INPUT_EXPOSURE_PROPERTY to validInputExposureEv.toString(), + INPUT_EXPOSURE_CONTRACT_PROPERTY to INPUT_EXPOSURE_CONTRACT, + ) + } else if (validPostExposureEv != null) { + result = result - INPUT_EXPOSURE_PROPERTY - INPUT_EXPOSURE_CONTRACT_PROPERTY + result += mapOf( + POST_EXPOSURE_PROPERTY to validPostExposureEv.toString(), + POST_EXPOSURE_CONTRACT_PROPERTY to CURRENT_POST_EXPOSURE_CONTRACT, + ) + } + return result + } + + /** Only called for an imported DNG containing a valid embedded Photon PGTM. */ + fun restoreFromSummary( + properties: Map, + summary: String?, + ): Map { + if (summary == null || summary.length > 256 * 1024 || + summary.lineSequence().firstOrNull()?.trim() != "PhotonCamera RAW AE SummaryText v1" + ) return properties + val fields = mutableMapOf() + for (line in summary.lineSequence()) { + val separator = line.indexOf('=') + if (separator <= 0) continue + val key = line.substring(0, separator).trim() + if (fields.put(key, line.substring(separator + 1).trim()) != null) return properties + } + val shortGain = (fields["hdrNetFinalShortGain"] ?: fields["finalShortGain"]) + ?.toFloatOrNull()?.takeIf { it.isFinite() && it > 0f } ?: return properties + val ratio = (fields["hdrNetFinalHdrRatio"] ?: fields["finalHdrRatio"]) + ?.toFloatOrNull()?.takeIf { it.isFinite() && it >= 1f } ?: return properties + if (SUMMARY_INPUT_EXPOSURE in fields || SUMMARY_INPUT_EXPOSURE_CONTRACT in fields) { + if (fields[SUMMARY_INPUT_EXPOSURE_CONTRACT] != INPUT_EXPOSURE_CONTRACT) return properties + val inputEv = fields[SUMMARY_INPUT_EXPOSURE]?.toFloatOrNull() + ?.takeIf(::isValidExposureEv) ?: return properties + return write(properties, ratio, shortGain, inputExposureEv = inputEv) + } + // Earlier Photon summaries used this name exclusively for downstream exposure. + // Keep it in the legacy field so regeneration can rebuild the old brightness target. + val legacyPostEv = fields["hdrNetPostExposureEv"]?.toFloatOrNull() + ?.takeIf(::isValidExposureEv) + return write(properties, ratio, shortGain, postExposureEv = legacyPostEv) + } + + fun appendInputExposureSummary(summary: StringBuilder, inputExposureEv: Float?) { + val exposureEv = inputExposureEv?.takeIf(::isValidExposureEv) ?: return + summary.appendLine("$SUMMARY_INPUT_EXPOSURE=$exposureEv") + summary.appendLine("$SUMMARY_INPUT_EXPOSURE_CONTRACT=$INPUT_EXPOSURE_CONTRACT") + } + + private fun isValidExposureEv(value: Float): Boolean = value.isFinite() && value in + MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV + + fun isCurrentCaptureContract(properties: Map): Boolean { + return properties[CONTRACT_PROPERTY] == CURRENT_CONTRACT + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt index 5a647cb6..d497cb3b 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/GalleryEditScreen.kt @@ -281,7 +281,6 @@ fun GalleryEditScreen( val editRawBaselineRecipeParams by viewModel.editRawBaselineRecipeParams.collectAsState() val editRawColorEngine by viewModel.editRawRenderingEngine.collectAsState() val editRawToneMappingParameters by viewModel.editRawToneMappingParameters.collectAsState() - val forceRegeneratePhotonPgtmOnRefresh = editRawToneMappingParameters.usePhotonHdr val editRawSpectralFilmStock by viewModel.editRawSpectralFilmStock.collectAsState() val editRawSpectralFilmPrint by viewModel.editRawSpectralFilmPrint.collectAsState() val editRawSpectralFilmCDensityGain by viewModel.editRawSpectralFilmCDensityGain.collectAsState() @@ -497,7 +496,6 @@ fun GalleryEditScreen( viewModel.saveRawDcpSelection(photo, it.id) { viewModel.refreshRawPreview( photo = photo, - forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtmOnRefresh, ) } } @@ -645,11 +643,13 @@ fun GalleryEditScreen( ) var pendingRawPreviewRefresh by remember(currentEditSourcePhoto.id) { mutableStateOf(false) } + var pendingPhotonPgtmRegeneration by remember(currentEditSourcePhoto.id) { mutableStateOf(false) } + var pendingRawRefreshToast by remember(currentEditSourcePhoto.id) { mutableStateOf(false) } val isRefreshingRawPreview = viewModel.refreshingPhotos.contains(currentEditSourcePhoto.id) fun refreshRawPreview( showResultToast: Boolean = false, - forceRegeneratePhotonPgtm: Boolean = forceRegeneratePhotonPgtmOnRefresh, + forceRegeneratePhotonPgtm: Boolean = false, ) { viewModel.refreshRawPreview( photo = currentEditSourcePhoto, @@ -667,10 +667,12 @@ fun GalleryEditScreen( fun requestRawPreviewRefresh( showResultToast: Boolean = false, - forceRegeneratePhotonPgtm: Boolean = forceRegeneratePhotonPgtmOnRefresh, + forceRegeneratePhotonPgtm: Boolean = false, ) { if (!isRaw) return if (viewModel.refreshingPhotos.contains(currentEditSourcePhoto.id)) { + pendingPhotonPgtmRegeneration = pendingPhotonPgtmRegeneration || forceRegeneratePhotonPgtm + pendingRawRefreshToast = pendingRawRefreshToast || showResultToast pendingRawPreviewRefresh = true return } @@ -682,8 +684,15 @@ fun GalleryEditScreen( LaunchedEffect(isRefreshingRawPreview, pendingRawPreviewRefresh, currentEditSourcePhoto.id) { if (!isRefreshingRawPreview && pendingRawPreviewRefresh) { + val forceRegeneratePhotonPgtm = pendingPhotonPgtmRegeneration + val showResultToast = pendingRawRefreshToast pendingRawPreviewRefresh = false - refreshRawPreview() + pendingPhotonPgtmRegeneration = false + pendingRawRefreshToast = false + refreshRawPreview( + showResultToast = showResultToast, + forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm, + ) } } @@ -1133,7 +1142,12 @@ fun GalleryEditScreen( IconButton( onClick = { - requestRawPreviewRefresh(showResultToast = true) + // Explicit refresh recomputes Photon PGTM; changing an + // edit setting or enabling HDR reuses the embedded map. + requestRawPreviewRefresh( + showResultToast = true, + forceRegeneratePhotonPgtm = editRawToneMappingParameters.usePhotonHdr, + ) }, enabled = !isRefreshingRawPreview ) { @@ -1793,10 +1807,7 @@ fun GalleryEditScreen( currentEditSourcePhoto ) { success -> if (success) { - requestRawPreviewRefresh( - forceRegeneratePhotonPgtm = - mode.usesPhotonHdr, - ) + requestRawPreviewRefresh() } } }, diff --git a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt index f88b7a55..64f4541d 100644 --- a/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/utils/RawProcessor.kt @@ -829,6 +829,7 @@ object RawProcessor { hdrRatio = captureProfile?.hdrRatio, finalShortGain = captureProfile?.finalShortGain, hdrNetPostExposureEv = captureProfile?.hdrNetPostExposureEv, + hdrNetInputExposureEv = captureProfile?.hdrNetInputExposureEv, rawSceneExposureSummaryText = captureProfile?.rawSceneExposureSummaryText, profileGainTableMap = preparedProfileGainTableMap, gpuDemosaicedRawSource = captureProfile?.gpuDemosaicedRawSource, diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt index 03fb14eb..9cf2347a 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt @@ -4,10 +4,52 @@ import com.hinnka.mycamera.processor.PhotonDehazeTuning import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Assume.assumeNoException import org.junit.Test class DngHdrNetViewfinderGridTest { + @Test + fun pgtmRangeCoversHighlightsWithoutMovingExistingKnots() { + val base = checkNotNull(DngPhotonProfileGainTableGenerator.hdrNetPlan(0f, 2f, 1f)) + val expanded = checkNotNull(DngPhotonProfileGainTableGenerator.hdrNetPlan( + rendererBaselineExposureEv = 0f, + hdrRatio = 2f, + sourceToShortGain = 1f, + maximumShortIntensity = 1.6f, + )) + assertEquals(257, base.pointCount) + assertEquals(413, expanded.pointCount) + for (point in 1 until base.pointCount) { + val originalCoordinate = point.toFloat() / base.pointCount + val expandedCoordinate = point.toFloat() / expanded.pointCount / expanded.mapInputRangeScale + assertEquals(originalCoordinate, expandedCoordinate, 2e-7f) + } + val lastKnot = (expanded.pointCount - 1f) / expanded.pointCount + assertTrue(1.6f * expanded.mapInputRangeScale <= lastKnot) + assertEquals(1f, expanded.mapInputWeights.sum() / expanded.mapInputRangeScale, 1e-6f) + } + + @Test + fun pgtmTextureLimitStillCoversTheCompleteIntensityRange() { + val plan = checkNotNull(DngPhotonProfileGainTableGenerator.hdrNetPlan( + rendererBaselineExposureEv = 3f, + hdrRatio = 2f, + sourceToShortGain = 1.7f, + maximumShortIntensity = 32f, + maximumTablePoints = 1024, + )) + assertEquals(1024, plan.pointCount) + val sourceCoordinate = 32f / plan.sourceToShortGain + val tableIndex = sourceCoordinate * plan.mapInputWeights.sum() * + plan.rendererBaselineGain * plan.pointCount + assertEquals(1023f, tableIndex, 0.001f) + assertNull(DngPhotonProfileGainTableGenerator.hdrNetPlan(0f, 2f, 1f, + maximumShortIntensity = Float.NaN)) + assertNull(DngPhotonProfileGainTableGenerator.hdrNetPlan(0f, 2f, 1f, + maximumTablePoints = 128)) + } + @Test fun displayLinearGridMatchesClassicDomainAndIgnoresRendererBaseline() { val modelInput = FloatArray( diff --git a/app/src/test/java/com/hinnka/mycamera/raw/RawHdrReferenceMathTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/RawHdrReferenceMathTest.kt index eed0d2d3..39505ec1 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/RawHdrReferenceMathTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/RawHdrReferenceMathTest.kt @@ -7,6 +7,16 @@ import kotlin.math.exp import kotlin.math.pow class RawHdrReferenceMathTest { + @Test + fun inputExposureReferenceTakesPrecedenceWithoutMultiplyingLegacyPostEv() { + assertEquals( + 0.25f, + RawHdrReferenceMath.hdrNetSceneExposureGain(4f, 0.5f, -2f, -3f)!!, + 0f, + ) + assertEquals(0.5f, RawHdrReferenceMath.hdrNetSceneExposureGain(4f, 0.5f, -2f)!!, 0f) + } + @Test fun followsSelectedBaseCurveThroughTheJoin() { val base = sampledCurve { x -> x * x * (3f - 2f * x) } diff --git a/app/src/test/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadataTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadataTest.kt new file mode 100644 index 00000000..434deb79 --- /dev/null +++ b/app/src/test/java/com/hinnka/mycamera/raw/RawPhotonHdrMetadataTest.kt @@ -0,0 +1,84 @@ +package com.hinnka.mycamera.raw + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Test + +class RawPhotonHdrMetadataTest { + @Test + fun `new input recipe keeps physical AE and removes legacy post exposure`() { + val legacy = RawPhotonHdrMetadata.write(emptyMap(), 4f, 0.5f, postExposureEv = -2f) + val updated = RawPhotonHdrMetadata.write( + legacy, 4f, 0.5f, postExposureEv = -2f, inputExposureEv = -3f, + ) + + assertEquals(4f, RawPhotonHdrMetadata.read(updated)!!, 0f) + assertEquals(0.5f, RawPhotonHdrMetadata.readFinalShortGain(updated)!!, 0f) + assertEquals(-3f, RawPhotonHdrMetadata.readInputExposureEv(updated)!!, 0f) + assertNull(RawPhotonHdrMetadata.readPostExposureEv(updated)) + assertFalse(updated.keys.any { it.contains("PostExposure") }) + } + + @Test + fun `standalone DNG summary restores the same complete input recipe`() { + val summary = buildString { + appendLine("PhotonCamera RAW AE SummaryText v1") + appendLine("finalShortGain=9.0") + appendLine("finalHdrRatio=2.0") + appendLine("hdrNetFinalShortGain=0.5") + appendLine("hdrNetFinalHdrRatio=4.0") + RawPhotonHdrMetadata.appendInputExposureSummary(this, -2.5f) + } + val xmp = DngCameraRawProfileXmp.build("Photon HDR", true, false, summary) + .toString(Charsets.UTF_8) + val restored = RawPhotonHdrMetadata.restoreFromSummary( + emptyMap(), DngCameraRawProfileXmp.readSceneExposureSummary(xmp), + ) + + assertEquals(0.5f, RawPhotonHdrMetadata.readFinalShortGain(restored)!!, 0f) + assertEquals(4f, RawPhotonHdrMetadata.read(restored)!!, 0f) + assertEquals(-2.5f, RawPhotonHdrMetadata.readInputExposureEv(restored)!!, 0f) + assertNull(RawPhotonHdrMetadata.readPostExposureEv(restored)) + } + + @Test + fun `legacy summary keeps post exposure separate and never relabels it`() { + val restored = RawPhotonHdrMetadata.restoreFromSummary( + emptyMap(), + """ + PhotonCamera RAW AE SummaryText v1 + hdrNetFinalShortGain=0.5 + hdrNetFinalHdrRatio=4.0 + hdrNetPostExposureEv=-1.88388 + """.trimIndent(), + ) + + assertEquals(-1.88388f, RawPhotonHdrMetadata.readPostExposureEv(restored)!!, 0f) + assertNull(RawPhotonHdrMetadata.readInputExposureEv(restored)) + } + + @Test + fun `unknown input contract never falls back to a legacy post value`() { + val legacy = RawPhotonHdrMetadata.write(emptyMap(), 4f, 0.5f, postExposureEv = -2f) + val unknown = legacy + mapOf( + "photonHdrNetInputExposureEv" to "-3.0", + "photonHdrNetInputExposureEvContract" to "unknown", + ) + assertNull(RawPhotonHdrMetadata.readInputExposureEv(unknown)) + assertNull(RawPhotonHdrMetadata.readPostExposureEv(unknown)) + } + + @Test + fun `ambiguous or incomplete embedded recipe cannot replace gallery state`() { + val existing = mapOf("unrelated" to "preserved") + val prefix = "PhotonCamera RAW AE SummaryText v1\nfinalShortGain=0.5\nfinalHdrRatio=4.0\n" + for (suffix in listOf( + "hdrNetInputExposureEv=-2.5", + "hdrNetInputExposureEv=NaN\nhdrNetInputExposureEvContract=${RawPhotonHdrMetadata.INPUT_EXPOSURE_CONTRACT}", + "finalShortGain=0.75", + )) { + assertEquals(existing, RawPhotonHdrMetadata.restoreFromSummary(existing, prefix + suffix)) + } + } +} diff --git a/docs/photon-dehaze-pipeline.md b/docs/photon-dehaze-pipeline.md index ccd1f52c..f94e521c 100644 --- a/docs/photon-dehaze-pipeline.md +++ b/docs/photon-dehaze-pipeline.md @@ -1,103 +1,101 @@ -# Photon HDRNet Dehaze + DHA 链路 +# Photon HDRNet、Dehaze 与曝光匹配 -Photon 不再运行独立的全分辨率 Dehaze pass。Dehaze 与 DHA 只属于 HDRNet 路径,并和 -HDRNet 的 bilateral-grid 输出一起烘焙到 DNG `ProfileGainTableMap2`。 +HDRNet 和 Dehaze/DHA 的结果共同烘焙到 DNG `ProfileGainTableMap2`。运行期只查一次 +PGTM,不另加全分辨率 Dehaze,也不在生成后追加曝光匹配增益。 -## 顺序 +## 曝光与处理顺序 -MGC v25 的低频处理顺序是 LTM → `DehazeAndDha` → `ShadowLevelMatching` → -`ApplyColorMap`。Photon 用 HDRNet/PGTM 代替 LTM,因此对应顺序为: +物理 AE 的 `sourceToShortGain=s0`、`hdrRatio=r` 与渲染输入曝光 `e` 分开保存。 +`e` 调整短、长曝光的共同输入尺度,不改变物理 TET 和长短曝光比例: ```text -final-short linear working RGB - -> one HDRNet model input / bilateral-grid inference with fixed short gain and HDR ratio - -> HDRNet output (256 x 192) - -> whole-image Dehaze + DHA histogram and curve - -> composed HDRNet + Dehaze/DHA output - -> full-coverage 8 x 6 viewfinder matching with modest shadow preference - -> downstream SLM rolloff / digital gain - -> bake the fixed HDRNet grid, Dehaze/DHA curve and gain response into PGTM - -> DCP HueSatMap / profile exposure / LookTable / tone / output +RAW camera RGB + -> s0 * 2^e -> working-space CCM + -> per-pixel min(RGB, 1) -> box average -> clamp(mean, 0, 1) + -> HDRNet tensor [short R, G, B, min(short BT601 luma * r, 12)] + -> inference -> HDRNet RGB -> Dehaze/DHA + -> viewfinder brightness score + -> bake this same candidate into PGTM -> profile / film rendering ``` -Dehaze 不进入 HDRNet 模型输入。HDR ratio 与 short gain 由拍摄阶段确定,取景器匹配不得修改 -这两个量,否则会把 HDRNet 与 Dehaze/DHA 形成的动态范围和反差当作曝光误差抵消。Dehaze 的 -统计源是唯一一次推理后的完整 256×192 HDRNet 输出;8×6 网格的每格覆盖对应区域的全部像素, -只用于求一个 HDRNet 下游增益参数,不用于估算 Dehaze 曲线。后处理结果的全图 P99 最大通道 -只用于诊断,不再限制正向匹配或重生成时恢复的参数。通用匹配范围仍为 `-4..4 EV`。 +曝光必须参与非线性响应的求解。旧链在固定 HDRNet/Dehaze 输出后再乘匹配增益;当匹配为 +负 EV 时,已经被压缩或裁剪的白色高光会变成灰色平台,原有差异无法通过后乘增益恢复。 +仅延后 RGB 裁剪或扩大 PGTM 范围不足以修复这类分块。现在每个候选都从未裁剪源纹理 +重新准备模型输入、推理并重算 Dehaze,最终表使用选中候选的全部数据。不能缩放旧 tensor、 +复用上一候选的系数或去雾曲线。 -## 取景器权重与 rolloff +模型准备的裁剪顺序对应原 MGC `apply_lsc_and_ccm.frag` 和最终 box pass:逐像素保留负值、 +仅限制正上界,完成平均后再限制到 `[0,1]`。HDRNet guide 是原 protobuf 的 16 项 hinge 和, +两侧仿射均为 `[1,0]`。原 renderer 的输入也经过 CCM 上裁剪;不能把原 apply shader 没有 +显式 luma clamp 理解为模型支持任意未归一化高光外推。 -目标仍是拍摄时对齐后的取景器图。保留现有参考可靠性、8×6 空间权重、人像优先和 ±0.1 EV -匹配评分;HDRNet 路径只在原权重上叠加 `1 + 0.25*(1-smoothstep(0.02, 0.25, referenceLuma))`。 -亮度为取景器 sRGB 解码后的线性 Rec.709 luma,可靠暗部最多增加 25% 权重;原有近黑和 -饱和参考排除规则继续生效。Classic/Local Laplacian 的权重不变。 +## 匹配 -匹配输出 `g=2^postExposureEv`,按照 MGC V25 SLM 的 further-gain split 处理: +沿用原 8×6 全图参考、空间权重、可靠暗/亮端排除与人像优先。HDRNet 单独启用 +`1 + 0.25*(1-smoothstep(0.02,0.25,referenceLuma))` 阴影权重,Classic 不变。 +每个候选按 RGB 逐像素完成最终通道裁剪、计算线性 Rec.709 亮度,再取每格均值。 +不能先平均 RGB 再裁剪,也不能给候选结果追加 EV。 + +使用既有原生候选搜索和评分:优先最大化 ±0.1 EV 内的加权匹配率,其次比较平均 EV 误差 +和 robust loss。候选范围为用户支持的 `-4..4 EV`,搜索次数有界。GPU 输入缓冲和推理器 +复用,内存只保留最近一个完整候选;如果最终选择了较早候选,就重新计算它再烘焙。 + +## Dehaze 契约 + +Dehaze 不进入模型 tensor。统计来自当前候选唯一一次 HDRNet 推理后的完整 256×192 图像: + +- 877-bin haze histogram; +- 5251-bin highlight histogram; +- 20 个低百分位样本决定 atmospheric haze point; +- 5 个高百分位样本决定 DHA highlight scale,限制到 `0.78..1.7`; +- 低端二次段和高端线性段保持数值及斜率连续。 + +保留原有有界 HDRNet/Dehaze 响应。新链不再用负的匹配增益压暗已经裁剪的结果。 +Dehaze 的本地开关与强度仍来自 `PhotonCoreImagingTuning.dehaze`;每个曝光候选重新计算曲线, +P99 只用于诊断,不限制曝光结果。 + +## PGTM 范围与曝光计数 + +内部 plan 使用有效 short gain `s=s0*2^e`。N 权重同时消除渲染 BaselineExposure 并带入 +这个有效增益;native 烘焙分母仍还原为实际 `RAW*BaselineGain`,因此输入曝光仅烘焙一次。 +不修改物理 `sourceToShortGain` 的持久化值,不将用户编辑 EV 混入输入配方。 + +全分辨率 RGB 可能超过模型输入的上界。DNG 按 `tableIndex=N*pointCount` 查表,越过末端 +后只返回最后 gain;原 RGB 继续增大会导致高光重新线性变亮。GPU 在逐像素裁剪和 box +平均之前,用 PXL 五权重计算最大短曝光强度 `M`。范围统计单独将负 RGB 归零,以同时覆盖 +保留或清除负值的渲染器,不改变模型 tensor。 ```text -g <= 1: rolloff = 1, digital = g -1 < g < 1.25: rolloff = g, digital = 1 -g >= 1.25: - t = clamp(2*(g-1.25), 0, 1) - rolloff = 1.25 + 0.5*(t-0.5*t*t) - digital = g / rolloff +pointCount = max(257, ceil(M*257)+1) +rangeScale = 257/pointCount +storedWeights = PXLWeights * s / BaselineGain * rangeScale ``` -逐像素取 Dehaze/DHA 后的 `m=max(RGB)`,使用共享增益: +原有强度节点间距保持为 `1/257`。节点上限为 `min(4096,GL_MAX_TEXTURE_SIZE)`,达到上限 +时使用 `rangeScale=(pointCount-1)/(pointCount*M)` 保证完整覆盖。上传纹理高度固定为 +`64*48`,生成前检查设备能力。极暗 cell 的中性轴判定使用按权重和归一的阈值,不随范围 +缩放改变。DNG 读取端无需 Photon 特殊查表规则。 -```text -G = 1 + (rolloff-1)*(1-m)^2 -gain = digital // rolloff*digital < 1 -gain = (1e-7 + m*digital*G) / (m+1e-7) // 其余情况 -outputRGB = clamp(RGB * gain, 0, 1) -``` +## 持久化与旧文件 -亮部的 rolloff 增益自然减弱,rolloff 最大为 1.5,剩余增益由 digital 承担;不再用 P99 -硬裁剪匹配 EV。这里只使用 SLM 的增益拆分和 rolloff,保留单路 HDRNet 图像与取景器目标。 +新配方保存物理 `s0/r`、`hdrNetInputExposureEv` 和合约 `hdrnet_input_viewfinder_v1`。 +新写入清除旧 post EV 字段;完整配方也进入 DNG XMP SummaryText,独立导入有效 Photon +PGTM 时恢复,不能仅依赖相册 metadata.json。HDR 场景参考采用 `s0*2^e*r`,后续用户编辑 +EV 仍单独应用一次。 -求解器接收完整的旋转对齐 RGB,每个候选先逐像素执行上述响应及通道截断,再计算每格平均 -Rec.709 亮度。不能先平均亮度再做 rolloff:同格内亮暗/彩色混合的结果会不同。求解器反解 -各格 ±0.1 EV 匹配区间边界,沿用加权匹配率、平均 EV 误差及 robust loss 的选择顺序。 -HDRNet 和 Dehaze 只计算一次。 +- 普通打开、开关动态范围优化:复用有效内嵌 Photon PGTM。 +- 新配方显式重生成:恢复 `s0/r/e`,只计算这一候选,不重新匹配。 +- 旧配方显式重生成:用旧 HDRNet/Dehaze 和旧 SLM 响应重建亮度参考,再求解新的输入 EV。 + 旧 post EV 不能直接解释为 input EV;目标迁移只约束亮度,不要求继续保留旧高光压缩失真。 +- 没有参考和有效配方的 RAW:采用 `e=0`。 +- 参考没有可靠计量区域(如全黑或全白):记录 `UNUSABLE_REFERENCE`,采用同样的 `e=0` + 策略;候选准备、推理或原生提交失败仍终止生成,不静默降级。 -## 曲线契约 +显式刷新延续当前处理结果重生成的既有语义,不覆写原始 DNG。原内嵌表与原配方仍是旧文件 +再次显式重生成的参考。新拍摄 DNG 保存的则是选中候选的完整表与新配方。 -HDRNet 输出先转换到原版 12-bit 统计域: +## 日志 -- 877-bin haze histogram:`clamp(R+G+B, 0, 876)`; -- 5251-bin highlight histogram:`max(RGB) + (max-min)/8`; -- 20 个低百分位样本决定两组 atmospheric haze point; -- 5 个高百分位样本决定 DHA highlight scale,并限制到 `0.78..1.7`; -- 最终曲线由低端二次段和高端线性段组成,数值和斜率连续。 - -合成时,曲线按 `(R+G+B)/3` 求共享 gain 并同时乘到三个通道。PGTM 是标量表,生成时使用 -固定的模型输入,从每个 64×48 空间 cell 保留局部色度与 PXL N 强度的比例,在 257 点强度轴 -上重建 RGB,再单独计算 Rec.601 HDRNet guide。PXL N 包含 min/max 通道权重,不能直接当作 -HDRNet luma,否则彩色区域的 rolloff 强度会偏移。随后执行相同的 Dehaze/DHA 和 RGB rolloff, -取结果亮度并反解 ACR3 输入。黑色或负噪声使源 luma 不可由正标量增益表达时,该 cell 的表 -曲线定义在中性灰轴上。PGTM 的空间/强度采样与标量格式仍有限制。运行期只查一次 -PGTM,不会再次执行 HDRNet、Dehaze 或 DHA。 - -## 本地控制与曝光匹配持久化 - -去雾直接使用 `PhotonCoreImagingTuning.dehaze` 的本地默认值: - -- `enabled` -- `strength`(`0..4`) -- `dynamicHighlightStrength`(`0..1`) - -默认启用,强度均为 `1`,不做持久化读写。参数只在 HDRNet PGTM 生成或重新生成时消费;Classic 与 Local -Laplacian 路径不执行 Dehaze/DHA。拍摄时得到的 HDRNet 下游匹配曝光独立保存,重新生成 PGTM -时恢复并使用相同 rolloff,仅按通用 EV 范围约束;不会折回 short gain、HDR ratio 或 -BaselineExposure。持久化契约为 `hdrnet_post_dehaze_viewfinder_rolloff_v2`;旧的线性增益 -`hdrnet_post_dehaze_viewfinder_v1` 参数不作为新响应的匹配结果恢复。没有兼容匹配值且没有 -取景器时使用 0 EV。 -已有 DNG 的 PGTM 不在最终渲染时叠加独立去雾。 - -## 匹配日志 - -`PLog_RawExposureMatch` 输出 Classic/Local Laplacian 的候选结果,以及 HDRNet 单曝光最终匹配率、 -平均 EV 误差和校正量。`DngPhotonProfileGainTableAlgorithm` 另外输出固定的 short/ratio、匹配 -参数、诊断用 P99 peak、haze point、DHA scale 与全图统计样本数。native PGTM 的 -`POST_EXPOSURE` 日志同时记录总 gain、rolloffGain 与 digitalGain。 +`HDRNET_PGTM_RANGE` 记录每次准备的最大强度、节点数和范围比例。 +`HDRNET_MATCH stage=SELECTED` 记录物理与有效 short gain、ratio、input EV、来源、Dehaze +参数和节点数。原生 matcher 记录候选评分,用于区分匹配变化、配方恢复和模型输入变化。 diff --git a/docs/research/lumix-rendering-engine.md b/docs/research/lumix-rendering-engine.md index 44782a55..55409a37 100644 --- a/docs/research/lumix-rendering-engine.md +++ b/docs/research/lumix-rendering-engine.md @@ -62,8 +62,10 @@ V-Log 选择保留平坦的代码值显示;这里的 sRGB 解码/编码是宿 ## 导入 RAW 的 HDRNet 与日志 -所有新导入 RAW(包括 RW2、DNG 及其他 LibRaw 格式)的 HDRNet PGTM 默认关闭,不继承拍摄全局的开启状态。 -RAW 编辑面板的“动态范围优化”开关显式开启后才生成或复用 Photon PGTM,关闭后不再使用它;开关按照片持久化。 +导入 DNG 含名为 `Photon HDR` 且有效的 PGTM 时,自动开启“动态范围优化”并复用拍摄时的映射。 +其他新导入 RAW(包括 RW2、DNG 及其他 LibRaw 格式)的 HDRNet PGTM 默认关闭,不继承拍摄全局的开启状态。 +RAW 编辑面板的“动态范围优化”开关按照片持久化:开启时优先复用有效的 Photon PGTM,缺失时生成,关闭后不再使用它。 +普通编辑引起的预览刷新遵守相同复用策略;用户点击工具栏刷新按钮时,若动态范围优化开启,则显式重新生成 PGTM。 用户选择的非 Photon 原生 DNG profile 所含 PGTM 仍遵守其 profile 选择策略,不冒充 HDRNet。 - `RAW_CAMERA_WORKING_SPACE`:打印共享空间、实际前置矩阵和返回 Camera RGB 的矩阵,以及旁路状态。 diff --git a/tools/dng_hdrnet_dehaze_test.cpp b/tools/dng_hdrnet_dehaze_test.cpp index 63f3b8ab..6cd320a9 100644 --- a/tools/dng_hdrnet_dehaze_test.cpp +++ b/tools/dng_hdrnet_dehaze_test.cpp @@ -8,6 +8,77 @@ namespace { +// Minimal host JNI array access so this regression exercises the production +// gain-table generator, including its point count and stored-weight contract. +struct TestFloatArray : _jfloatArray { + std::vector values; + explicit TestFloatArray(std::vector data) : values(std::move(data)) {} +}; + +std::vector GenerateHighlightTable(int points, float range_scale, + float input_gain = 1.0f, float post_gain = 1.0f) { + JNINativeInterface_ functions{}; + functions.GetArrayLength = [](JNIEnv*, jarray array) -> jsize { + return static_cast(static_cast(array)->values.size()); + }; + functions.GetFloatArrayElements = [](JNIEnv*, jfloatArray array, jboolean*) -> jfloat* { + return static_cast(array)->values.data(); + }; + functions.ReleaseFloatArrayElements = [](JNIEnv*, jfloatArray, jfloat*, jint) {}; + functions.ExceptionCheck = [](JNIEnv*) -> jboolean { return JNI_FALSE; }; + JNIEnv env{&functions}; + TestFloatArray coefficients({1.0f, 0.0f}); + TestFloatArray model({0.5f * input_gain, 0.5f * input_gain, + 0.5f * input_gain, 2.0f * input_gain}); + TestFloatArray shifts({0.0f}), slopes({1.0f}), curve({0.0f, 1.0f}); + TestFloatArray dehaze({0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f}); + const float weight_scale = range_scale * input_gain; + TestFloatArray weights({0.1495f * weight_scale, 0.2935f * weight_scale, + 0.057f * weight_scale, 0.125f * weight_scale, 0.375f * weight_scale}); + TestFloatArray output(std::vector(points, 0.0f)); + assert(Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains( + &env, nullptr, &coefficients, &model, 1, 1, 4, 1, 1, 1, 2, 1, 1, points, + 4.0f, input_gain, 1.0f, 0.03f, 30.0f, 0.0f, 1.0f / 4096.0f, 4096.0f, + &shifts, &slopes, &curve, &dehaze, post_gain, &weights, &output)); + return output.values; +} + +float RenderNeutralThroughTable(float source, float range_scale, const std::vector& table) { + const float index = std::clamp(source * range_scale * table.size(), 0.0f, + static_cast(table.size() - 1)); + const int lower = static_cast(std::floor(index)); + const int upper = std::min(lower + 1, static_cast(table.size() - 1)); + return source * Lerp(table[lower], table[upper], index - lower); +} + +void TestRangeExtensionDoesNotRebrightenCompressedHighlights() { + const auto old_table = GenerateHighlightTable(257, 1.0f); + const float scale = 257.0f / 413.0f; + const auto expanded = GenerateHighlightTable(413, scale); + for (int point = 0; point < 257; ++point) { + assert(std::abs(old_table[point] - expanded[point]) < 2.0e-5f); + } + // The old table hits its terminal gain: a source of 1.6 becomes a bright + // island, despite the final post-exposure target remaining at white. + assert(RenderNeutralThroughTable(1.6f, 1.0f, old_table) > 1.6f); + for (float value : {0.5f, 0.8f, 1.0f, 1.2f, 1.6f}) { + // Linear interpolation of reciprocal gains has at most ~1.6e-5 error here. + assert(std::abs(RenderNeutralThroughTable(value, scale, expanded) - 1.0f) < 2.0e-5f); + } +} + +void TestInputExposureIsBakedOnceBeforeHighlightCompression() { + const auto legacy = GenerateHighlightTable(257, 1.0f, 1.0f, 0.25f); + const auto input_exposed = GenerateHighlightTable(257, 1.0f, 0.25f, 1.0f); + // The old post-EV turns both clipped highlights into the same gray plateau. + for (float source : {0.5f, 0.8f}) { + assert(std::abs(RenderNeutralThroughTable(source, 1.0f, legacy) - 0.25f) < 1.0e-5f); + // New exposure participates in the nonlinear response. The stored N weights + // and denominator encode it once, while the renderer still receives original RAW. + assert(std::abs(RenderNeutralThroughTable(source, 0.25f, input_exposed) - source) < 1.0e-5f); + } +} + void TestDisabledCurveIsIdentity() { std::vector haze(kDehazeHistogramSize, 0); std::vector highlight(kHighlightHistogramSize, 0); @@ -115,9 +186,26 @@ void TestColoredPgtmCoordinateAndRolloffAgreeWithEvaluation() { assert(neutral.red == 0.2f && neutral.green == 0.2f && neutral.blue == 0.2f); } +void TestRangeScalingPreservesDarkCellChromaticity() { + const float weights[] = {0.1495f, 0.2935f, 0.057f, 0.125f, 0.375f}; + const RgbSample cell{3.0e-6f, 1.0e-6f, 0.5e-6f}; + const float coordinate = TableIntensity(cell, weights); + const auto original = RgbForTableCoordinate(0.4f, cell, coordinate, 1.0f); + for (float scale : {0.63f, 0.1f}) { + const auto expanded = RgbForTableCoordinate(0.4f * scale, cell, coordinate * scale, scale); + assert(std::abs(expanded.red - original.red) < 1.0e-6f); + assert(std::abs(expanded.green - original.green) < 1.0e-6f); + assert(std::abs(expanded.blue - original.blue) < 1.0e-6f); + assert(expanded.red > expanded.green * 2.9f); + } +} + } // namespace int main() { + TestInputExposureIsBakedOnceBeforeHighlightCompression(); + TestRangeExtensionDoesNotRebrightenCompressedHighlights(); + TestRangeScalingPreservesDarkCellChromaticity(); TestDisabledCurveIsIdentity(); TestHdrNetOutputFeedsWholeImageDehaze(); TestColoredPgtmCoordinateAndRolloffAgreeWithEvaluation(); diff --git a/tools/raw_hdrnet_post_exposure_solver_test.cpp b/tools/raw_hdrnet_post_exposure_solver_test.cpp index c6d84ac0..63afe674 100644 --- a/tools/raw_hdrnet_post_exposure_solver_test.cpp +++ b/tools/raw_hdrnet_post_exposure_solver_test.cpp @@ -207,6 +207,67 @@ void TestMgcRolloffOracles() { check({1, 4, 16}, {1.5f, 1.0f}, {1, 6, 24}); } +void TestInputExposureRerendersNonlinearCandidates() { + auto solver = CreateSolver(); + assert(solver && solver->ConfigureHdrNetPriority()); + constexpr float expected_ev = -1.7f; + const float reference = ReferenceLuma(); + const float source = reference / (1.0f - reference) / std::exp2(expected_ev); + int candidate_count = 0; + while (const auto ev = solver->NextExposureEv()) { + // Stand-in for a complete nonlinear HDRNet candidate. Scaling an already + // rendered pixel would solve a different exposure and is intentionally excluded. + const float exposed = source * std::exp2(*ev); + const float rendered = exposed / (1.0f + exposed); + const std::vector grid(kGridCellCount, rendered); + assert(solver->SubmitCandidate(*ev, grid.data(), kGridColumns, kGridRows)); + candidate_count++; + } + assert(candidate_count > 1 && candidate_count <= kMaximumSampleCount); + assert(solver->HasResult()); + const float selected_source = source * std::exp2(solver->BestSample().exposure_ev); + assert(ErrorEv(selected_source / (1.0f + selected_source), reference) <= + kMatchResidualToleranceEv); + assert(solver->BestSample().match.match_rate == 1.0f); + assert(!solver->ConfigureHdrNetPriority()); +} + +void TestHdrNetPriorityDoesNotChangeClassicScoring() { + std::vector reference(kGridCellCount); + std::vector grid(kGridCellCount); + for (int cell = 0; cell < kGridCellCount; ++cell) { + const bool shadow = cell % kGridColumns < kGridColumns / 2; + reference[cell] = GrayPixel(shadow ? 64 : 180); + grid[cell] = *DisplayLinearLuma(reference[cell]) * (shadow ? 1.0f : 0.5f); + } + auto classic = ExposureSolver::Create(reference.data(), nullptr, kGridColumns, kGridRows); + auto hdrnet = ExposureSolver::Create(reference.data(), nullptr, kGridColumns, kGridRows); + assert(classic && hdrnet); + assert(hdrnet->ConfigureHdrNetPriority()); + assert(hdrnet->ConfigureHdrNetPriority()); // configuration is idempotent + assert(classic->NextExposureEv() == 0.0f && hdrnet->NextExposureEv() == 0.0f); + assert(classic->SubmitCandidate(0.0f, grid.data(), kGridColumns, kGridRows)); + assert(hdrnet->SubmitCandidate(0.0f, grid.data(), kGridColumns, kGridRows)); + assert(std::abs(classic->BestSample().match.match_rate - 0.5f) < 1.0e-6f); + assert(hdrnet->BestSample().match.match_rate > 0.5f); + assert(hdrnet->BestSample().match.match_rate <= 1.25f / 2.25f + 1.0e-6f); +} + +void TestLegacyReferenceUsesSharedSlmResponse() { + const std::vector rgb{0.02f, 0.12f, 0.8f, 1.0f, 0.5f, 0.25f}; + for (float ev : {-1.5f, 0.0f, 1.5f}) { + std::vector pixels; + assert(BuildLegacyHdrNetReference(rgb.data(), 2, ev, &pixels)); + for (int index = 0; index < 2; ++index) { + assert(pixels[index] == EncodeDisplayRgb( + post::Apply(RgbAt(rgb, index), post::SplitGain(std::exp2(ev))))); + } + } + std::vector pixels; + assert(!BuildLegacyHdrNetReference(rgb.data(), 2, + std::numeric_limits::quiet_NaN(), &pixels)); +} + } // namespace int main() { @@ -220,6 +281,9 @@ int main() { TestPerPixelResponseBeforeCellMean({post::Rgb{0.04f, 0.02f, 0.01f}, {0.9f, 0.08f, 0.015f}, {0.1f, 0.7f, 0.2f}, {0.01f, 0.03f, 0.95f}}, 3.0f); TestMgcRolloffOracles(); + TestInputExposureRerendersNonlinearCandidates(); + TestHdrNetPriorityDoesNotChangeClassicScoring(); + TestLegacyReferenceUsesSharedSlmResponse(); std::cout << "raw HDRNet post-exposure solver tests passed\n"; return 0; }