fix: highlight error when negative expo for hdrnet

This commit is contained in:
zhoubinjia committed 2026-09-15 23:09:10 +08:00
1 parent a6b60ca836
commit 02a7542c7e
22 files changed
+1051 -320

No files matched your search

+1 -1
View File
@@ -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};
}
@@ -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<jint>* 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<uint32_t>(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<jint>(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<float> pending_exposure_ev_;
std::vector<float> reference_grid_lumas_;
std::vector<int> 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<jint> 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*,
@@ -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,
@@ -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,
@@ -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("<!DOCTYPE", ignoreCase = true)
) return null
return runCatching {
val builder = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
isExpandEntityReferences = false
}.newDocumentBuilder()
builder.setEntityResolver { _, _ -> 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,
@@ -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)
@@ -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)
)
}
@@ -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,
@@ -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<String, String>): Float? = properties[PROPERTY]
?.toFloatOrNull()
?.takeIf { it.isFinite() && it >= 1f }
fun readFinalShortGain(properties: Map<String, String>): 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<String, String>): 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<String, String>,
hdrRatio: Float?,
finalShortGain: Float? = null,
postExposureEv: Float? = null,
): Map<String, String> {
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<String, String>): Boolean {
return properties[CONTRACT_PROPERTY] == CURRENT_CONTRACT
}
}
/** Capture-request AE compensation persisted independently from presentation ExposureBias. */
internal object RawCaptureExposureCompensationMetadata {
private const val PROPERTY = "captureAeExposureCompensationEv"
@@ -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 }
}
@@ -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 {
@@ -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)
@@ -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<String, String>): Float? = properties[PROPERTY]
?.toFloatOrNull()
?.takeIf { it.isFinite() && it >= 1f }
fun readFinalShortGain(properties: Map<String, String>): 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<String, String>): 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<String, String>): 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<String, String>,
hdrRatio: Float?,
finalShortGain: Float? = null,
postExposureEv: Float? = null,
inputExposureEv: Float? = null,
): Map<String, String> {
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<String, String>,
summary: String?,
): Map<String, String> {
if (summary == null || summary.length > 256 * 1024 ||
summary.lineSequence().firstOrNull()?.trim() != "PhotonCamera RAW AE SummaryText v1"
) return properties
val fields = mutableMapOf<String, String>()
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<String, String>): Boolean {
return properties[CONTRACT_PROPERTY] == CURRENT_CONTRACT
}
}
@@ -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()
}
}
},
@@ -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,
@@ -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(
@@ -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) }
@@ -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))
}
}
}