fix: remove dehaze

This commit is contained in:
zhoubinjia committed 2026-09-02 22:49:54 +08:00
1 parent 81c4a4fc2a
commit f476c23af0
23 files changed
+1472 -1936

No files matched your search

+2 -40
View File
@@ -192,23 +192,6 @@ float InputForAcrOutput(float output, const float* curve, int curve_count) {
return (lower_index + amount) / static_cast<float>(curve_count - 1);
}
float SmoothStep(float edge_0, float edge_1, float value) {
const float amount = std::clamp(
(value - edge_0) / std::max(edge_1 - edge_0, 1.0e-6f), 0.0f, 1.0f);
return amount * amount * (3.0f - 2.0f * amount);
}
float DiagnosticMask(float input, float start, float end, float feather) {
const float enter = start <= 0.0f || feather <= 0.0f
? (input >= start ? 1.0f : 0.0f)
: SmoothStep(start - feather, start + feather, input);
const float exit = end >= 1.0f || feather <= 0.0f
? (input <= end ? 1.0f : 0.0f)
: 1.0f -
SmoothStep(end - feather, end + feather, input);
return std::clamp(std::min(enter, exit), 0.0f, 1.0f);
}
bool IsFiniteArray(const float* values, int count) {
for (int index = 0; index < count; ++index) {
if (!std::isfinite(values[index])) return false;
@@ -389,8 +372,6 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
jfloat min_table_gain, jfloat max_table_gain,
jfloatArray guide_shifts_array,
jfloatArray guide_slopes_array, jfloatArray acr_curve_array,
jfloat diagnostic_start, jfloat diagnostic_end,
jfloat diagnostic_feather, jint diagnostic_mode,
jfloatArray output_gains_array) {
if (coefficients_array == nullptr || guide_shifts_array == nullptr ||
guide_slopes_array == nullptr || acr_curve_array == nullptr ||
@@ -407,8 +388,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
!std::isfinite(render_max_gain_blend_threshold) ||
render_max_gain_blend_threshold < 0.0f ||
!std::isfinite(min_table_gain) || min_table_gain <= 0.0f ||
!std::isfinite(max_table_gain) || max_table_gain < min_table_gain ||
diagnostic_mode < -1 || diagnostic_mode > 1) {
!std::isfinite(max_table_gain) || max_table_gain < min_table_gain) {
LogError("Rejected invalid HDRNet PGTM parameters");
return JNI_FALSE;
}
@@ -431,16 +411,6 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
LogError("Rejected mismatched HDRNet PGTM array geometry");
return JNI_FALSE;
}
if (diagnostic_mode >= 0 &&
(!std::isfinite(diagnostic_start) ||
!std::isfinite(diagnostic_end) ||
!std::isfinite(diagnostic_feather) ||
diagnostic_start < 0.0f || diagnostic_end > 1.0f ||
diagnostic_end <= diagnostic_start || diagnostic_feather < 0.0f)) {
LogError("Rejected invalid HDRNet diagnostic band");
return JNI_FALSE;
}
ScopedFloatArray coefficients(env, coefficients_array);
ScopedFloatArray guide_shifts(env, guide_shifts_array);
ScopedFloatArray guide_slopes(env, guide_slopes_array);
@@ -543,17 +513,9 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
// pending exposure. The subsequent exposure ramp then restores pre_curve_target exactly.
const float baseline_applied_source_intensity =
short_intensity * renderer_baseline_gain / source_to_short_gain;
float gain = std::clamp(
const float gain = std::clamp(
pre_curve_target / baseline_applied_source_intensity, min_table_gain,
max_table_gain);
if (diagnostic_mode >= 0) {
const float mask =
DiagnosticMask(short_intensity, diagnostic_start,
diagnostic_end, diagnostic_feather);
gain = diagnostic_mode == 0 ? Lerp(1.0f, gain, mask)
: Lerp(gain, 1.0f, mask);
gain = std::clamp(gain, min_table_gain, max_table_gain);
}
gain_curve[point] = gain;
}
}
File diff suppressed because it is too large. Load diff
@@ -369,10 +369,19 @@ data class PhotonDehazeTuning(
val isActive: Boolean
get() = normalized().let {
it.enabled && (it.strength > 0f || it.dynamicHighlightStrength > 0f)
PROCESSING_ENABLED &&
it.enabled && (it.strength > 0f || it.dynamicHighlightStrength > 0f)
}
companion object {
/**
* Temporary master gate for the standalone Dehaze stage.
*
* Keep persisted tuning intact so captures and presets remain forward-compatible, while
* every render/metering path observes the same disabled state until the stage is restored.
*/
const val PROCESSING_ENABLED = false
val DEFAULT = PhotonDehazeTuning()
val DISABLED = PhotonDehazeTuning(enabled = false)
}
@@ -21,7 +21,6 @@ internal object DngHdrNetProfileGainTableNative {
val outputCount = plan.cellCount.toLong() * plan.pointCount
if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null
val output = FloatArray(outputCount.toInt())
val diagnosticBand = plan.diagnosticBand
val completed = nativeGenerateGains(
coefficients = coefficients,
sourceGridWidth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_WIDTH,
@@ -42,10 +41,6 @@ internal object DngHdrNetProfileGainTableNative {
guideShifts = guideShifts,
guideSlopes = guideSlopes,
acr3Curve = acr3Curve,
diagnosticStart = diagnosticBand?.start ?: 0f,
diagnosticEnd = diagnosticBand?.end ?: 1f,
diagnosticFeather = diagnosticBand?.feather ?: 0f,
diagnosticMode = diagnosticBand?.mode?.ordinal ?: -1,
outputGains = output,
)
return output.takeIf { completed }
@@ -133,10 +128,6 @@ internal object DngHdrNetProfileGainTableNative {
guideShifts: FloatArray,
guideSlopes: FloatArray,
acr3Curve: FloatArray,
diagnosticStart: Float,
diagnosticEnd: Float,
diagnosticFeather: Float,
diagnosticMode: Int,
outputGains: FloatArray,
): Boolean
@@ -1,81 +0,0 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.utils.PLog
internal object DngPgtmDiagnostic {
private const val TAG = "DngPgtmDiagnostic"
// 0 disables gain mutation. For halo isolation, use BLOCK_ONLY and sweep 7..18.
private const val PGTM_DIAGNOSTIC_BAND_INDEX = 0
private val PGTM_DIAGNOSTIC_MODE =
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY
// Draws tableInput 0.080..0.140 as 0.005-wide false-color bands in RAW preview.
private const val PGTM_VISUAL_OVERLAY_MODE = 0
private var visualOverlayLogged = false
fun activeBandForSource(source: String): DngPhotonProfileGainTableGenerator.DiagnosticBand? {
val band = activeBand() ?: return null
PLog.w(
TAG,
"PGTM diagnostic band active for $source: mode=${band.mode} " +
"tableInput=${band.start}..${band.end} feather=${band.feather}"
)
return band
}
fun visualOverlayModeForSource(source: String): Int {
if (PGTM_VISUAL_OVERLAY_MODE == 0) return 0
if (!visualOverlayLogged) {
visualOverlayLogged = true
PLog.w(
TAG,
"PGTM visual overlay active for $source: tableInput 0.080..0.140 " +
"split by 0.005; outside range is dim grayscale"
)
}
return PGTM_VISUAL_OVERLAY_MODE
}
private fun activeBand(): DngPhotonProfileGainTableGenerator.DiagnosticBand? {
return when (PGTM_DIAGNOSTIC_BAND_INDEX) {
1 -> band(0.000f, 0.005f, feather = 0.0010f)
2 -> band(0.005f, 0.010f, feather = 0.0010f)
3 -> band(0.010f, 0.020f, feather = 0.0020f)
4 -> band(0.020f, 0.040f, feather = 0.0030f)
5 -> band(0.040f, 0.060f, feather = 0.0030f)
6 -> band(0.060f, 0.080f, feather = 0.0030f)
7 -> band(0.080f, 0.085f)
8 -> band(0.085f, 0.090f)
9 -> band(0.090f, 0.095f)
10 -> band(0.095f, 0.100f)
11 -> band(0.100f, 0.105f)
12 -> band(0.105f, 0.110f)
13 -> band(0.110f, 0.115f)
14 -> band(0.115f, 0.120f)
15 -> band(0.120f, 0.125f)
16 -> band(0.125f, 0.130f)
17 -> band(0.130f, 0.135f)
18 -> band(0.135f, 0.140f)
19 -> band(0.140f, 0.160f, feather = 0.0040f)
20 -> band(0.160f, 0.180f, feather = 0.0040f)
21 -> band(0.180f, 0.250f, feather = 0.0080f)
22 -> band(0.250f, 0.400f, feather = 0.0120f)
else -> null
}
}
private fun band(
start: Float,
end: Float,
feather: Float = 0.0010f,
): DngPhotonProfileGainTableGenerator.DiagnosticBand {
return DngPhotonProfileGainTableGenerator.DiagnosticBand(
start = start,
end = end,
feather = feather,
mode = PGTM_DIAGNOSTIC_MODE
)
}
}
@@ -522,57 +522,12 @@ internal object DngPhotonLocalToneMapper {
photonPlan.minTableGain,
photonPlan.maxTableGain,
)
val diagnosticGain = applyDiagnostic(
trueGain = fittedGain,
tableInput = sourceInput,
plan = plan,
)
result[outputOffset + point] = diagnosticGain.coerceIn(
photonPlan.minTableGain,
photonPlan.maxTableGain,
)
result[outputOffset + point] = fittedGain
}
}
return result
}
private fun applyDiagnostic(
trueGain: Float,
tableInput: Float,
plan: PhotonProfileGainTablePlan,
): Float {
val band = plan.diagnosticBand ?: return trueGain
val mask = diagnosticMask(tableInput, band)
return when (band.mode) {
DngPhotonProfileGainTableGenerator.DiagnosticMode.PASS_ONLY ->
lerp(1f, trueGain, mask)
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY ->
lerp(trueGain, 1f, mask)
}
}
private fun diagnosticMask(
input: Float,
band: DngPhotonProfileGainTableGenerator.DiagnosticBand,
): Float {
val enter = if (band.start <= 0f || band.feather <= 0f) {
if (input >= band.start) 1f else 0f
} else {
smoothStep(band.start - band.feather, band.start + band.feather, input)
}
val exit = if (band.end >= 1f || band.feather <= 0f) {
if (input <= band.end) 1f else 0f
} else {
1f - smoothStep(band.end - band.feather, band.end + band.feather, input)
}
return min(enter, exit).coerceIn(0f, 1f)
}
private fun smoothStep(edge0: Float, edge1: Float, value: Float): Float {
val amount = ((value - edge0) / max(edge1 - edge0, CURVE_EPS)).coerceIn(0f, 1f)
return amount * amount * (3f - 2f * amount)
}
private fun curvedBilateralGuide(value: Float, alpha: Float): Float {
val clamped = value.coerceIn(0f, 1f)
return (
@@ -807,39 +807,8 @@ internal object DngPhotonLocalToneMapGpuShaders {
uniform float uGuideAlpha;
uniform float uMinTableGain;
uniform float uMaxTableGain;
uniform int uDiagnosticMode;
uniform float uDiagnosticStart;
uniform float uDiagnosticEnd;
uniform float uDiagnosticFeather;
const float CURVE_EPS = 1e-6;
float smoothUnit(float edge0, float edge1, float value) {
float amount = clamp(
(value - edge0) / max(edge1 - edge0, CURVE_EPS),
0.0,
1.0
);
return amount * amount * (3.0 - 2.0 * amount);
}
float diagnosticMask(float inputValue) {
float enter = uDiagnosticStart <= 0.0 || uDiagnosticFeather <= 0.0
? (inputValue >= uDiagnosticStart ? 1.0 : 0.0)
: smoothUnit(
uDiagnosticStart - uDiagnosticFeather,
uDiagnosticStart + uDiagnosticFeather,
inputValue
);
float exit = uDiagnosticEnd >= 1.0 || uDiagnosticFeather <= 0.0
? (inputValue <= uDiagnosticEnd ? 1.0 : 0.0)
: 1.0 - smoothUnit(
uDiagnosticEnd - uDiagnosticFeather,
uDiagnosticEnd + uDiagnosticFeather,
inputValue
);
return clamp(min(enter, exit), 0.0, 1.0);
}
void main() {
int outputIndex = int(gl_GlobalInvocationID.x);
int outputCount = uCellCount * uPointCount;
@@ -873,20 +842,8 @@ internal object DngPhotonLocalToneMapGpuShaders {
uMinTableGain,
uMaxTableGain
);
float finalGain = trueGain;
if (uDiagnosticMode >= 0) {
float mask = diagnosticMask(sourceInput);
finalGain = uDiagnosticMode == 0
? mix(1.0, trueGain, mask)
: mix(trueGain, 1.0, mask);
}
float outputGain = clamp(
finalGain,
uMinTableGain,
uMaxTableGain
);
gainCurves[outputIndex] = outputGain;
imageStore(uGainTexture, ivec2(point, cell), vec4(outputGain, 0.0, 0.0, 1.0));
gainCurves[outputIndex] = trueGain;
imageStore(uGainTexture, ivec2(point, cell), vec4(trueGain, 0.0, 0.0, 1.0));
}
""".trimIndent()
@@ -1415,9 +1372,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
val map: DngProfileGainTableMap,
val hdrRatio: Float? = null,
val sourceToShortGain: Float? = null,
val hdrNetShortExposureAdjustmentEv: Float,
val hdrNetLongExposureAdjustmentEv: Float,
val hdrNetExposureEvaluation: RawHdrNetExposureEvaluation? = null,
)
private data class GpuPhotonGainCurves(
@@ -1428,8 +1382,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
private data class HdrNetInferenceCandidate(
val plan: HdrNetProfileGainTablePlan,
val coefficients: FloatArray,
val shortAdjustmentEv: Float,
val longAdjustmentEv: Float,
)
private var cellSamplesProgram = 0
@@ -1474,11 +1426,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
return when (input.mode) {
Mode.HDR_NET -> generate(input)
Mode.LOCAL_LAPLACIAN -> generateLocalLaplacian(input)?.let { map ->
Output(
map = map,
hdrNetShortExposureAdjustmentEv = 0f,
hdrNetLongExposureAdjustmentEv = 0f,
)
Output(map = map)
}
}
}
@@ -1535,12 +1483,9 @@ internal class DngPhotonProfileGainTableAlgorithm {
extentV = stage3Bounds.height().toDouble() / height.toDouble(),
)
val basePlan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
sourceWidth = width,
sourceHeight = height,
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
hdrRatio = input.hdrRatio,
sourceToShortGain = input.sourceToShortGain,
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG HDRNet capture"),
samplingArea = samplingArea,
) ?: return null
val interpreter = ensureHdrNetInterpreter(input.context) ?: return null
@@ -1580,7 +1525,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
return null
}
val bufferIds = IntArray(2)
val totalStartNs = System.nanoTime()
GLES31.glGenBuffers(bufferIds.size, bufferIds, 0)
try {
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bufferIds[0])
@@ -1648,9 +1592,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
)
val baseShortGain = basePlan.sourceToShortGain
val baseLongGain = baseShortGain * basePlan.hdrRatio
var totalInputNs = 0L
var totalInferenceNs = 0L
var totalMatchGridNs = 0L
val modelInputBuffer = ByteBuffer.allocateDirect(inputFloatCount * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
val modelOutputBuffer = ByteBuffer.allocateDirect(
@@ -1664,28 +1605,19 @@ internal class DngPhotonProfileGainTableAlgorithm {
val candidateHdrRatio = longGain / shortGain
if (!candidateHdrRatio.isFinite() || candidateHdrRatio < 1f) return null
return DngPhotonProfileGainTableGenerator.hdrNetPlan(
sourceWidth = width,
sourceHeight = height,
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
hdrRatio = candidateHdrRatio,
sourceToShortGain = shortGain,
diagnosticBand = DngPgtmDiagnostic.activeBandForSource(
"$TAG HDRNet capture",
),
samplingArea = samplingArea,
)
}
fun exposureAdjustmentEv(gain: Float, baseGain: Float): Float =
(ln((gain / baseGain).toDouble()) / ln(2.0)).toFloat()
fun runCandidate(
shortGain: Float,
longGain: Float,
): Pair<HdrNetInferenceCandidate, FloatArray>? {
val candidatePlan = planCandidate(shortGain, longGain) ?: return null
val inputStartNs = System.nanoTime()
GLES31.glUseProgram(hdrNetInputProgram)
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bufferIds[0])
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bufferIds[1])
@@ -1721,28 +1653,16 @@ internal class DngPhotonProfileGainTableAlgorithm {
PLog.e(TAG, "HDRNet input contains a non-finite value")
return null
}
totalInputNs += System.nanoTime() - inputStartNs
logHdrNetInputContract(
input = input,
plan = candidatePlan,
colorCorrectionMatrix = safeColorCorrectionMatrix,
values = inputFloats,
)
modelInputBuffer.clear()
modelInputBuffer.asFloatBuffer().put(inputFloats)
modelInputBuffer.rewind()
modelOutputBuffer.clear()
val inferenceStartNs = System.nanoTime()
interpreter.run(modelInputBuffer, modelOutputBuffer)
totalInferenceNs += System.nanoTime() - inferenceStartNs
modelOutputBuffer.rewind()
val coefficients = FloatArray(
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
)
modelOutputBuffer.asFloatBuffer().get(coefficients)
logHdrNetOutputContract(coefficients, candidatePlan.hdrRatio)
val matchGridStartNs = System.nanoTime()
val displayLinearLumaGrid =
DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
plan = candidatePlan,
@@ -1750,20 +1670,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
modelInput = inputFloats,
outputRotation = input.outputRotation,
)
val matchGridNs = System.nanoTime() - matchGridStartNs
totalMatchGridNs += matchGridNs
PLog.d(
TAG,
"HDRNet viewfinder grid: shortGain=$shortGain longGain=$longGain " +
"hdrRatio=${candidatePlan.hdrRatio} " +
"gridMs=${matchGridNs / 1_000_000f}",
)
if (displayLinearLumaGrid == null) return null
return HdrNetInferenceCandidate(
plan = candidatePlan,
coefficients = coefficients,
shortAdjustmentEv = exposureAdjustmentEv(shortGain, baseShortGain),
longAdjustmentEv = exposureAdjustmentEv(longGain, baseLongGain),
) to displayLinearLumaGrid
}
@@ -1775,18 +1685,15 @@ internal class DngPhotonProfileGainTableAlgorithm {
evaluateCandidate = ::runCandidate,
)
}
val selectedCandidate = exposureResult?.payload
val selectedCandidate = exposureResult
?: runCandidate(baseShortGain, baseLongGain)?.first
?: return null
val plan = selectedCandidate.plan
val coefficients = selectedCandidate.coefficients
val pgtmStartNs = System.nanoTime()
val map = DngPhotonProfileGainTableGenerator.mapFromHdrNetCoefficients(
plan = plan,
coefficients = coefficients,
) ?: return null
// logHdrNetGainTableContract(map)
val pgtmReadyNs = System.nanoTime()
val textureId = uploadProfileGainTableTexture(map) ?: return null
try {
input.installProfileGainTableTexture(map, textureId)
@@ -1794,106 +1701,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
GLES30.glDeleteTextures(1, intArrayOf(textureId), 0)
throw error
}
val totalReadyNs = System.nanoTime()
PLog.d(
TAG,
"HDRNet PGTM ready: input=${DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH}x" +
"${DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT}x4 " +
"modelGrid=${DngPhotonProfileGainTableGenerator.HDRNET_GRID_WIDTH}x" +
"${DngPhotonProfileGainTableGenerator.HDRNET_GRID_HEIGHT}x" +
"${DngPhotonProfileGainTableGenerator.HDRNET_GRID_DEPTH} " +
"pgtmGrid=${plan.grid.mapPointsH}x${plan.grid.mapPointsV} " +
"hdrRatio=${plan.hdrRatio} " +
"rendererBaselineGain=${plan.rendererBaselineGain} " +
"sourceToShortGain=${plan.sourceToShortGain} " +
"hdrNetTotalInputGain=${plan.hdrNetInputScale} " +
"mapInputWeightSum=${plan.mapInputWeightSum} " +
"mapInputEffectiveScale=${plan.rendererMapInputEffectiveScale} " +
"mapInputInvariantError=" +
"${plan.rendererMapInputEffectiveScale - plan.hdrNetInputScale} " +
"modelInputChannels=R_G_B_LONG_LUMA " +
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED " +
"modelInputHueSat=false " +
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
"baselineAppliedToHdrNetInput=false " +
"baselineAppliedToViewfinderMatch=false " +
"baselineRole=DNG_RENDER_COORDINATE_ONLY " +
"mapInputDomain=RAW_X_FINAL_SHORT_GAIN " +
"pgtmBaselineCancelledFromInputCoordinate=true " +
"exposureSolve=${exposureResult != null} " +
"exposureMetric=PERCEPTUAL_LSTAR_GRID_MATCH_RATE " +
"exposureCandidateDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
"exposureReferenceDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
"exposureSpatialWeight=CLASSIC_REFERENCE_ENDPOINT_RELIABILITY " +
"exposureTarget=FULL_CAPTURE_VIEWFINDER_THUMBNAIL " +
"exposureReferenceAvailable=${input.viewfinderReference != null} " +
"exposureOutputRotation=${input.outputRotation} " +
"exposureAdjustmentMode=HIGHLIGHT_SHORT_SHADOW_LONG_GRID_GUIDED " +
"exposureConvergenceCondition=GRID_MATCH_RATE_ONLY " +
"exposureBaseShortGain=$baseShortGain " +
"exposureBaseLongGain=$baseLongGain " +
"exposureBaseHdrRatio=${basePlan.hdrRatio} " +
"exposureShortAdjustmentEv=${selectedCandidate.shortAdjustmentEv} " +
"exposureLongAdjustmentEv=${selectedCandidate.longAdjustmentEv} " +
"exposureFinalShortGain=${plan.sourceToShortGain} " +
"exposureFinalLongGain=${plan.sourceToShortGain * plan.hdrRatio} " +
"exposureFinalHdrRatio=${plan.hdrRatio} " +
"exposureMedianLog2Ratio=" +
"${exposureResult?.evaluation?.medianLog2Ratio} " +
"exposureCenterErrorEv=" +
"${exposureResult?.evaluation?.centerErrorEv} " +
"exposureSpanErrorEv=" +
"${exposureResult?.evaluation?.spanErrorEv} " +
"exposureCurveSlopeError=" +
"${exposureResult?.evaluation?.curveSlopeError} " +
"exposureReferenceSpanEv=" +
"${exposureResult?.evaluation?.referenceSpanEv} " +
"exposureHighlightTargetErrorEv=" +
"${exposureResult?.evaluation?.highlightTargetErrorEv} " +
"exposureShadowTargetErrorEv=" +
"${exposureResult?.evaluation?.shadowTargetErrorEv} " +
"exposureShortTargetCorrectionEv=" +
"${exposureResult?.evaluation?.shortTargetCorrectionEv} " +
"exposureLongTargetCorrectionEv=" +
"${exposureResult?.evaluation?.longTargetCorrectionEv} " +
"exposureRobustLog2Loss=" +
"${exposureResult?.evaluation?.robustLog2Loss} " +
"exposureMeanAbsoluteLog2Ratio=" +
"${exposureResult?.evaluation?.meanAbsoluteLog2Ratio} " +
"exposureMeanPerceptualLightnessError=" +
"${exposureResult?.evaluation?.meanAbsolutePerceptualLightnessError} " +
"exposureMatchRate=${exposureResult?.evaluation?.matchRate} " +
"exposureCoordinateEdges=" +
"${exposureResult?.evaluation?.coordinateComparedEdgeCount} " +
"exposureCoordinateMatchRate=" +
"${exposureResult?.evaluation?.coordinateMatchRate} " +
"exposureCoordinatesMatched=" +
"${exposureResult?.evaluation?.coordinatesMatched} " +
"exposureRecommendedCorrectionEv=" +
"${exposureResult?.evaluation?.recommendedExposureCorrectionEv} " +
"exposureConverged=${exposureResult?.evaluation?.converged} " +
"exposureFallback1d=" +
"${exposureResult?.evaluation?.usedOneDimensionalFallback} " +
"exposureJacobianNormalizedDeterminant=" +
"${exposureResult?.evaluation?.jacobianNormalizedDeterminant} " +
"exposureCandidateCount=" +
"${exposureResult?.evaluation?.evaluatedCandidateCount} " +
"stage3Source=${width}x$height linearRgbBounds=$hdrNetSourceBounds " +
"processingBounds=$stage3Bounds samplingArea=$samplingArea " +
"inputMs=${totalInputNs / 1_000_000f} " +
"inferenceMs=${totalInferenceNs / 1_000_000f} " +
"matchGridMs=${totalMatchGridNs / 1_000_000f} " +
"pgtmMs=${(pgtmReadyNs - pgtmStartNs) / 1_000_000f} " +
"totalMs=${(totalReadyNs - totalStartNs) / 1_000_000f}",
)
return Output(
map = map,
hdrRatio = plan.hdrRatio,
sourceToShortGain = plan.sourceToShortGain,
hdrNetShortExposureAdjustmentEv = selectedCandidate.shortAdjustmentEv,
hdrNetLongExposureAdjustmentEv = selectedCandidate.longAdjustmentEv,
hdrNetExposureEvaluation = exposureResult?.evaluation,
)
} catch (error: Throwable) {
PLog.e(TAG, "HDRNet ProfileGainTableMap generation failed", error)
@@ -1993,7 +1804,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
emptyList()
}
val bufferIds = IntArray(2)
val totalStartNs = System.nanoTime()
GLES31.glGenBuffers(bufferIds.size, bufferIds, 0)
try {
val sampleBufferId = bufferIds[0]
@@ -2122,7 +1932,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
RawToneMappingGl.transposeMatrix3x3(safeColorCorrectionMatrix),
0,
)
val samplesGpuStartNs = System.nanoTime()
if (streamingInput) {
val source = requireNotNull(streamingRawData)
streamingTiles.forEachIndexed { tileIndex, tile ->
@@ -2181,13 +1990,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
)
RawGlesProgram.logErrors("generateProfileGainTableMapOnGpu sample dispatch")
val samplesGpuReadyNs = System.nanoTime()
val plan = DngPhotonProfileGainTableGenerator.plan(
width = width,
height = height,
baselineExposureEv = baselineExposureEv,
diagnosticBand = DngPgtmDiagnostic.activeBandForSource("$TAG GPU capture"),
samplingArea = PhotonPgtmSamplingArea(
originH = safeStatsBounds.left.toDouble() / rawTextureWidth,
originV = safeStatsBounds.top.toDouble() / rawTextureHeight,
@@ -2195,7 +2001,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
extentV = safeStatsBounds.height().toDouble() / rawTextureHeight,
),
) ?: return null
val planReadyNs = System.nanoTime()
if (plan.cellCount != cellCount) {
PLog.e(
TAG,
@@ -2204,12 +2009,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
return null
}
val localToneMapGpuStartNs = System.nanoTime()
val generated = generatePhotonProfileGainCurvesOnGpu(
plan = plan,
sampleBufferId = sampleBufferId,
) ?: return null
val localToneMapGpuReadyNs = System.nanoTime()
val map =
DngPhotonProfileGainTableGenerator.mapFromGpuGains(plan, generated.gains)
?: run {
@@ -2217,31 +2020,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
return null
}
input.installProfileGainTableTexture(map, generated.textureId)
val photonPlan = plan.photonPlan
val photonPreToneMapGain = photonPlan.exposureGain *
2.0f.pow(photonPlan.parameters.preToneMapExposureBoostEv)
PLog.d(
TAG,
"GPU Local Laplacian PGTM prepared: size=${width}x$height " +
"source=${rawTextureWidth}x$rawTextureHeight " +
"streaming=$streamingInput sampleTiles=${streamingTiles.size} " +
"statsBounds=$safeStatsBounds " +
"grid=${gridWidth}x$gridHeight samplesPerPixel=$samplesPerPixel " +
"lsc=${input.lensShadingDescription} " +
"warpCount=${activeWarpParameters.size / 8} " +
"photonGuide=paperIntensity " +
"hueSatOverrange=$hueSatMapSupportsOverrange " +
"photonBaselineGain=${photonPlan.exposureGain} " +
"photonPreToneMapGain=$photonPreToneMapGain " +
"photonLlfLevels=${photonPlan.parameters.localLaplacianIntensityLevels} " +
"photonRangeSigma=${photonPlan.parameters.localLaplacianRangeSigma} " +
"photonBguRangeSigma=${photonPlan.parameters.bilateralRangeSigma} " +
"samplesGpuMs=${(samplesGpuReadyNs - samplesGpuStartNs) / 1_000_000.0} " +
"planCpuMs=${(planReadyNs - samplesGpuReadyNs) / 1_000_000.0} " +
"localToneMapGpuMs=" +
"${(localToneMapGpuReadyNs - localToneMapGpuStartNs) / 1_000_000.0} " +
"totalMs=${(localToneMapGpuReadyNs - totalStartNs) / 1_000_000.0}",
)
return map
} catch (error: Exception) {
PLog.e(TAG, "GPU RAW PGTM preparation failed", error)
@@ -2956,27 +2734,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
)
uniform1f(activeProgram, "uMinTableGain", photonPlan.minTableGain)
uniform1f(activeProgram, "uMaxTableGain", photonPlan.maxTableGain)
val diagnosticMode = when (plan.diagnosticBand?.mode) {
DngPhotonProfileGainTableGenerator.DiagnosticMode.PASS_ONLY -> 0
DngPhotonProfileGainTableGenerator.DiagnosticMode.BLOCK_ONLY -> 1
null -> -1
}
uniform1i(activeProgram, "uDiagnosticMode", diagnosticMode)
uniform1f(
activeProgram,
"uDiagnosticStart",
plan.diagnosticBand?.start ?: 0f,
)
uniform1f(
activeProgram,
"uDiagnosticEnd",
plan.diagnosticBand?.end ?: 1f,
)
uniform1f(
activeProgram,
"uDiagnosticFeather",
plan.diagnosticBand?.feather ?: 0f,
)
dispatch1d(gainFloatCount, GlesComputeWorkGroup.LINEAR_SIZE)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or
@@ -2991,9 +2748,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
floatCount = gainFloatCount,
label = "Photon PGTM gain curves",
) ?: return null
if (plan.diagnosticBand != null) {
PLog.d(TAG, summarizePhotonGainCurves(plan, gains))
}
val result = GpuPhotonGainCurves(
gains = gains,
textureId = generatedTextureId,
@@ -3015,111 +2769,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
}
}
private fun summarizePhotonGainCurves(
plan: PhotonProfileGainTablePlan,
gains: FloatArray,
): String {
val photonPlan = plan.photonPlan
val pointCount = plan.pointCount
val gridWidth = plan.grid.mapPointsH
val gridHeight = plan.grid.mapPointsV
val firstVisiblePoint = max(1, ceil(0.02f * pointCount).toInt())
var gainMinimum = Float.POSITIVE_INFINITY
var gainMaximum = Float.NEGATIVE_INFINITY
var reversalCount = 0
var worstOutputDrop = 0f
var worstOutputDropCell = -1
var worstOutputDropPoint = -1
var maximumRangeGainRatio = 1f
var maximumRangeGainCell = -1
var maximumRangeGainPoint = -1
var maximumSpatialGainRatio = 1f
var maximumSpatialGainCell = -1
var maximumSpatialGainPoint = -1
fun gainRatio(first: Float, second: Float): Float {
val low = min(first, second).coerceAtLeast(1e-12f)
return max(first, second) / low
}
repeat(plan.cellCount) { cell ->
val curveOffset = cell * pointCount
var previousOutput = 0f
for (point in 0 until pointCount) {
val gain = gains[curveOffset + point]
gainMinimum = min(gainMinimum, gain)
gainMaximum = max(gainMaximum, gain)
val sourceInput = when (point) {
0 -> 0f
pointCount - 1 -> 1f
else -> point.toFloat() / pointCount
}
val output = photonPlan.exposureGain * sourceInput * gain
if (point > 0 && output < previousOutput) {
reversalCount++
val drop = previousOutput - output
if (drop > worstOutputDrop) {
worstOutputDrop = drop
worstOutputDropCell = cell
worstOutputDropPoint = point
}
}
if (point >= firstVisiblePoint) {
val previousGain = gains[curveOffset + point - 1]
val ratio = gainRatio(previousGain, gain)
if (ratio > maximumRangeGainRatio) {
maximumRangeGainRatio = ratio
maximumRangeGainCell = cell
maximumRangeGainPoint = point
}
}
previousOutput = output
}
}
repeat(gridHeight) { y ->
repeat(gridWidth) { x ->
val cell = y * gridWidth + x
for (point in firstVisiblePoint until pointCount) {
val gain = gains[cell * pointCount + point]
if (x > 0) {
val ratio = gainRatio(
gain,
gains[(cell - 1) * pointCount + point],
)
if (ratio > maximumSpatialGainRatio) {
maximumSpatialGainRatio = ratio
maximumSpatialGainCell = cell
maximumSpatialGainPoint = point
}
}
if (y > 0) {
val ratio = gainRatio(
gain,
gains[(cell - gridWidth) * pointCount + point],
)
if (ratio > maximumSpatialGainRatio) {
maximumSpatialGainRatio = ratio
maximumSpatialGainCell = cell
maximumSpatialGainPoint = point
}
}
}
}
}
fun ratioToEv(ratio: Float): Float =
(ln(ratio.coerceAtLeast(1f).toDouble()) / ln(2.0)).toFloat()
return "Photon PGTM curve diagnostics: gain=$gainMinimum..$gainMaximum " +
"outputReversals=$reversalCount worstOutputDrop=$worstOutputDrop " +
"atCell=$worstOutputDropCell point=$worstOutputDropPoint " +
"maxRangeGainStep=${ratioToEv(maximumRangeGainRatio)}EV " +
"atCell=$maximumRangeGainCell point=$maximumRangeGainPoint " +
"maxSpatialNeighborStep=${ratioToEv(maximumSpatialGainRatio)}EV " +
"atCell=$maximumSpatialGainCell point=$maximumSpatialGainPoint"
}
private fun ensureHdrNetInterpreter(context: Context): Interpreter? {
hdrNetInterpreter?.let { return it }
return runCatching {
@@ -3403,158 +3052,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
}
}
private fun logHdrNetInputContract(
input: Input,
plan: HdrNetProfileGainTablePlan,
colorCorrectionMatrix: FloatArray,
values: FloatArray,
) {
val whiteBalance = input.metadata.whiteBalanceGains
val redGain = whiteBalance.getOrElse(0) { 1f }.coerceAtLeast(1e-6f)
val greenEven = whiteBalance.getOrElse(1) { 1f }.coerceAtLeast(1e-6f)
val greenOdd = whiteBalance.getOrElse(2) { greenEven }.coerceAtLeast(1e-6f)
val blueGain = whiteBalance.getOrElse(3) {
whiteBalance.getOrElse(2) { 1f }
}.coerceAtLeast(1e-6f)
val greenGain = (greenEven + greenOdd) * 0.5f
val cameraNeutral = floatArrayOf(greenGain / redGain, 1f, greenGain / blueGain)
val mappedNeutral = FloatArray(3) { row ->
colorCorrectionMatrix[row * 3] * cameraNeutral[0] +
colorCorrectionMatrix[row * 3 + 1] * cameraNeutral[1] +
colorCorrectionMatrix[row * 3 + 2] * cameraNeutral[2]
}
val minimums = FloatArray(4) { Float.POSITIVE_INFINITY }
val maximums = FloatArray(4) { Float.NEGATIVE_INFINITY }
val sums = DoubleArray(4)
val rgbClipped = LongArray(3)
for (index in values.indices) {
val channel = index and 3
val value = values[index]
minimums[channel] = minOf(minimums[channel], value)
maximums[channel] = maxOf(maximums[channel], value)
sums[channel] += value.toDouble()
if (channel < 3 && value >= 0.999999f) rgbClipped[channel]++
}
val pixelCount = (values.size / 4).coerceAtLeast(1)
val means = FloatArray(4) { channel ->
(sums[channel] / pixelCount).toFloat()
}
val clippedFractions = FloatArray(3) { channel ->
rgbClipped[channel].toFloat() / pixelCount
}
PLog.d(
TAG,
"HDRNet input contract: wb=${whiteBalance.contentToString()} " +
"cameraNeutral=${cameraNeutral.contentToString()} " +
"mappedNeutral=${mappedNeutral.contentToString()} " +
"matrix=${colorCorrectionMatrix.take(9)} " +
"whiteBalanceDomain=BAKED_IN_COLOR_CORRECTION_MATRIX " +
"modelInputChannels=R_G_B_LONG_LUMA " +
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED hueSat=false " +
"baselineAppliedToModelInput=false " +
"baselineAppliedToViewfinderMatch=false " +
"rendererBaselineGain=${plan.rendererBaselineGain} " +
"sourceToShort=${plan.sourceToShortGain} " +
"hdrRatio=${plan.hdrRatio} mapWeights=${plan.mapInputWeights.contentToString()} " +
"mapWeightSum=${plan.mapInputWeightSum} " +
"mapInputEffectiveScale=${plan.rendererMapInputEffectiveScale} " +
"mapInputInvariantError=" +
"${plan.rendererMapInputEffectiveScale - plan.hdrNetInputScale} " +
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
"channelMin=${minimums.contentToString()} " +
"channelMean=${means.contentToString()} " +
"channelMax=${maximums.contentToString()} " +
"rgbClipped=${clippedFractions.contentToString()}",
)
}
private fun logHdrNetOutputContract(coefficients: FloatArray, hdrRatio: Float) {
if (coefficients.size % DngPhotonProfileGainTableGenerator.HDRNET_COEFFICIENT_COUNT != 0) {
return
}
val minimums = floatArrayOf(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
val maximums = floatArrayOf(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)
val sums = DoubleArray(2)
var pairCount = 0
for (offset in coefficients.indices step 2) {
for (component in 0..1) {
val value = coefficients[offset + component]
minimums[component] = minOf(minimums[component], value)
maximums[component] = maxOf(maximums[component], value)
sums[component] += value.toDouble()
}
++pairCount
}
val means = FloatArray(2) { component ->
(sums[component] / pairCount.coerceAtLeast(1)).toFloat()
}
val affineScaleMinimum = minimums[0] * (hdrRatio - 1f) + 1f
val affineScaleMean = means[0] * (hdrRatio - 1f) + 1f
val affineScaleMaximum = maximums[0] * (hdrRatio - 1f) + 1f
PLog.d(
TAG,
"HDRNet model output contract: layout=Y_X_Z_ONE_SCALE_RESIDUAL_BIAS " +
"coefficientMin=${minimums.contentToString()} " +
"coefficientMean=${means.contentToString()} " +
"coefficientMax=${maximums.contentToString()} " +
"affineScaleAfterRatio=[$affineScaleMinimum,$affineScaleMean,$affineScaleMaximum] " +
"hdrRatio=$hdrRatio",
)
}
private fun logHdrNetGainTableContract(map: DngProfileGainTableMap) {
val pointCount = map.mapPointsN
if (pointCount <= 0 || map.gains.isEmpty()) return
val requestedPoints = intArrayOf(0, 1, 4, 16, 64, 128, pointCount - 1)
val points = requestedPoints.distinct().filter { it in 0 until pointCount }
val pointMin = FloatArray(points.size) { Float.POSITIVE_INFINITY }
val pointMax = FloatArray(points.size) { Float.NEGATIVE_INFINITY }
val pointSum = DoubleArray(points.size)
var gainMin = Float.POSITIVE_INFINITY
var gainMax = Float.NEGATIVE_INFINITY
var gainSum = 0.0
var finiteCount = 0
var nonFiniteCount = 0
var renderFloorCount = 0
var belowPointOneCount = 0
map.gains.forEachIndexed { index, gain ->
if (!gain.isFinite()) {
nonFiniteCount++
return@forEachIndexed
}
gainMin = min(gainMin, gain)
gainMax = max(gainMax, gain)
gainSum += gain
finiteCount++
if (gain <= 0.031f) renderFloorCount++
if (gain <= 0.1f) belowPointOneCount++
val point = index % pointCount
val selected = points.indexOf(point)
if (selected >= 0) {
pointMin[selected] = min(pointMin[selected], gain)
pointMax[selected] = max(pointMax[selected], gain)
pointSum[selected] += gain
}
}
val cellCount = map.gains.size / pointCount
val pointSummary = points.indices.joinToString(prefix = "[", postfix = "]") { index ->
val mean = if (cellCount > 0) pointSum[index] / cellCount else Double.NaN
"${points[index]}:${pointMin[index]}/$mean/${pointMax[index]}"
}
PLog.i(
TAG,
"HDRNet PGTM gain contract: gainMin=$gainMin " +
"gainMean=${if (finiteCount > 0) gainSum / finiteCount else Double.NaN} " +
"gainMax=$gainMax finiteCount=$finiteCount nonFiniteCount=$nonFiniteCount " +
"atOrBelowRenderFloorFraction=" +
"${renderFloorCount.toDouble() / map.gains.size.coerceAtLeast(1)} " +
"atOrBelowPointOneFraction=" +
"${belowPointOneCount.toDouble() / map.gains.size.coerceAtLeast(1)} " +
"pointGainMinMeanMax=$pointSummary",
)
}
private companion object {
const val TAG = "PhotonPGTM"
const val HDRNET_MODEL_ASSET = "mgc_hdrnet/hdrnet_coefficients.tflite"
@@ -30,6 +30,8 @@ internal object DngPhotonProfileGainTableGenerator {
const val HDRNET_GRID_DEPTH = 8
const val HDRNET_PGTM_GRID_WIDTH = 64
const val HDRNET_PGTM_GRID_HEIGHT = 48
const val HDRNET_MATCH_GRID_WIDTH = 8
const val HDRNET_MATCH_GRID_HEIGHT = 6
const val HDRNET_COEFFICIENT_COUNT = 2
const val HDRNET_OUTPUT_FLOAT_COUNT =
HDRNET_GRID_WIDTH * HDRNET_GRID_HEIGHT * HDRNET_GRID_DEPTH * HDRNET_COEFFICIENT_COUNT
@@ -77,7 +79,8 @@ internal object DngPhotonProfileGainTableGenerator {
/**
* Normalized ProfileGainTableMap intensity direction written by Pixel's MGC pipeline.
*
* This is deliberately distinct from the HDRNet tensor, whose channels are Y, U, V, 1.
* This is deliberately distinct from the HDRNet tensor, whose channels are final-short
* R, G, B and reconstructed final-long Rec.601 luma.
* The DNG table N axis combines half of standard RGB luma with one eighth of min-RGB and
* three eighths of max-RGB. Pixel DNGs scale all five values together for final-short space;
* [hdrNetPlan] performs the same scale after accounting for renderer BaselineExposure.
@@ -114,16 +117,12 @@ internal object DngPhotonProfileGainTableGenerator {
* in HDRNet inference or viewfinder matching.
*/
fun hdrNetPlan(
sourceWidth: Int,
sourceHeight: Int,
rendererBaselineExposureEv: Float,
hdrRatio: Float,
sourceToShortGain: Float,
diagnosticBand: DiagnosticBand? = null,
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
): HdrNetProfileGainTablePlan? {
if (sourceWidth <= 0 || sourceHeight <= 0 ||
!rendererBaselineExposureEv.isFinite() ||
if (!rendererBaselineExposureEv.isFinite() ||
!hdrRatio.isFinite() || hdrRatio <= 0f ||
!sourceToShortGain.isFinite() || sourceToShortGain <= 0f
) {
@@ -159,7 +158,6 @@ internal object DngPhotonProfileGainTableGenerator {
sourceToShortGain = sourceToShortGain,
// The native MGC path builds the long-exposure guide from a ratio of at least one.
hdrRatio = hdrRatio.coerceAtLeast(1f),
diagnosticBand = diagnosticBand?.sanitized(),
)
}
@@ -225,7 +223,7 @@ internal object DngPhotonProfileGainTableGenerator {
}
/**
* Evaluates HDRNet on the complete 64 x 48 PGTM spatial grid and returns clipped
* Evaluates HDRNet across the complete image on the 8 x 6 matching grid and returns clipped
* display-linear Rec.709 luma. This is the same post-EOTF domain built from the classic
* matcher's ARGB_8888 candidate and reference images.
*/
@@ -249,8 +247,8 @@ internal object DngPhotonProfileGainTableGenerator {
guideSlopes = HDRNET_GUIDE_SLOPES,
renderMinGain = HDRNET_RENDER_MIN_GAIN,
renderMaxGain = HDRNET_RENDER_MAX_GAIN,
outputGridWidth = HDRNET_PGTM_GRID_WIDTH,
outputGridHeight = HDRNET_PGTM_GRID_HEIGHT,
outputGridWidth = HDRNET_MATCH_GRID_WIDTH,
outputGridHeight = HDRNET_MATCH_GRID_HEIGHT,
footprintSamplesPerAxis = HDRNET_MATCH_FOOTPRINT_SAMPLES_PER_AXIS,
)
}
@@ -262,7 +260,6 @@ internal object DngPhotonProfileGainTableGenerator {
height: Int,
baselineExposureEv: Float,
tablePointCount: Int = TABLE_POINTS,
diagnosticBand: DiagnosticBand? = null,
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
): PhotonProfileGainTablePlan? {
if (width <= 0 || height <= 0 || !baselineExposureEv.isFinite()) return null
@@ -271,7 +268,6 @@ internal object DngPhotonProfileGainTableGenerator {
pointCount = tablePointCount.coerceIn(TABLE_POINTS, TABLE_POINTS),
baselineExposureEv = baselineExposureEv,
samplingArea = samplingArea,
diagnosticBand = diagnosticBand?.sanitized(),
)
}
@@ -280,7 +276,6 @@ internal object DngPhotonProfileGainTableGenerator {
pointCount: Int,
baselineExposureEv: Float,
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
diagnosticBand: DiagnosticBand?,
): PhotonProfileGainTablePlan {
val exposureGain = DngBaselineExposure.exactGain(baselineExposureEv)
// The input shader samples one non-overlapping 16x16 block per spatial table entry.
@@ -311,7 +306,6 @@ internal object DngPhotonProfileGainTableGenerator {
maxTableGain = MAX_TABLE_GAIN,
parameters = PhotonLocalToneMappingParameters(),
),
diagnosticBand = diagnosticBand,
)
}
@@ -344,28 +338,6 @@ internal object DngPhotonProfileGainTableGenerator {
return map
}
data class DiagnosticBand(
val start: Float,
val end: Float,
val feather: Float = 0.02f,
val mode: DiagnosticMode = DiagnosticMode.PASS_ONLY,
) {
internal fun sanitized(): DiagnosticBand? {
if (!start.isFinite() || !end.isFinite() || !feather.isFinite()) return null
val safeStart = start.coerceIn(0f, 1f)
val safeEnd = end.coerceIn(0f, 1f)
if (safeEnd <= safeStart) return null
return DiagnosticBand(
start = safeStart,
end = safeEnd,
feather = feather.coerceIn(0f, 0.12f),
mode = mode,
)
}
}
enum class DiagnosticMode { PASS_ONLY, BLOCK_ONLY }
private fun chooseGrid(width: Int, height: Int): PhotonPgtmGrid {
val mapPointsH = ((width + TARGET_TILE_PX - 1) / TARGET_TILE_PX)
.coerceIn(GRID_MIN_H, GRID_MAX_H)
@@ -435,7 +407,6 @@ internal data class PhotonProfileGainTablePlan(
val mapInputWeights: FloatArray,
val gamma: Float,
val photonPlan: PhotonPgtmPlan,
val diagnosticBand: DngPhotonProfileGainTableGenerator.DiagnosticBand?,
) {
init {
require(mapInputWeights.size == 5 && mapInputWeights.all { it.isFinite() })
@@ -456,7 +427,6 @@ internal data class HdrNetProfileGainTablePlan(
/** Gain from source RAW to the candidate final-short exposure used by HDRNet. */
val sourceToShortGain: Float,
val hdrRatio: Float,
val diagnosticBand: DngPhotonProfileGainTableGenerator.DiagnosticBand?,
) {
init {
require(grid.mapPointsH == DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH)
@@ -467,24 +437,16 @@ internal data class HdrNetProfileGainTablePlan(
require(rendererBaselineGain.isFinite() && rendererBaselineGain > 0f)
require(sourceToShortGain.isFinite() && sourceToShortGain > 0f)
require(hdrRatio.isFinite() && hdrRatio >= 1f)
val rendererMapInputEffectiveScale = mapInputWeights.sum() * rendererBaselineGain
require(
kotlin.math.abs(rendererMapInputEffectiveScale - hdrNetInputScale) <=
maxOf(1e-6f, hdrNetInputScale * 1e-5f)
kotlin.math.abs(rendererMapInputEffectiveScale - sourceToShortGain) <=
maxOf(1e-6f, sourceToShortGain * 1e-5f)
)
}
val cellCount: Int
get() = grid.mapPointsH * grid.mapPointsV
val mapInputWeightSum: Float
get() = mapInputWeights.sum()
/** Effective neutral-axis scale after a conforming renderer restores BaselineExposure. */
val rendererMapInputEffectiveScale: Float
get() = mapInputWeightSum * rendererBaselineGain
val hdrNetInputScale: Float
get() = sourceToShortGain
}
internal data class PhotonPgtmGrid(
@@ -47,6 +47,33 @@ data class DngProfileGainTableMap(
)
}
/**
* Preserves the map's source-linear lookup coordinate when TotalBaselineExposure changes.
*
* DNG renderers multiply [mapInputWeights] by TotalBaselineExposure before indexing the
* table. The generated gain curves remain unchanged; only the weights need the inverse gain
* ratio. Both EV values must therefore include the selected profile's BaselineExposureOffset.
*/
fun rebasedForRendererBaseline(
fromTotalBaselineExposureEv: Float,
toTotalBaselineExposureEv: Float,
): DngProfileGainTableMap? {
if (!fromTotalBaselineExposureEv.isFinite() ||
!toTotalBaselineExposureEv.isFinite()
) {
return null
}
val fromGain = DngBaselineExposure.exactGain(fromTotalBaselineExposureEv)
val toGain = DngBaselineExposure.exactGain(toTotalBaselineExposureEv)
val weightScale = fromGain / toGain
if (!weightScale.isFinite() || weightScale <= 0f) return null
val rebasedWeights = FloatArray(mapInputWeights.size) { index ->
mapInputWeights[index] * weightScale
}
if (rebasedWeights.any { !it.isFinite() }) return null
return copy(mapInputWeights = rebasedWeights)
}
fun encodeProfileGainTableMap2(byteOrder: ByteOrder): ByteArray {
require(isValid) { "Invalid ProfileGainTableMap2" }
val gainMin = gains.minOrNull()
@@ -99,24 +99,53 @@ internal class PhotonDehazePipeline {
width: Int,
height: Int,
tuning: PhotonDehazeTuning,
): Output? = renderWithHistogramSource(
histogramSourceTextureId = sourceTextureId,
histogramWidth = width,
histogramHeight = height,
sourceTextureId = sourceTextureId,
targetTextureId = targetTextureId,
width = width,
height = height,
tuning = tuning,
)
/**
* Builds the adaptive curve from the full-resolution source while applying it to another
* texture in the same linear RGB domain. Capture metering uses this to preserve the exact
* final-render histogram while evaluating only its small viewfinder-sized image.
*/
fun renderWithHistogramSource(
histogramSourceTextureId: Int,
histogramWidth: Int,
histogramHeight: Int,
sourceTextureId: Int,
targetTextureId: Int,
width: Int,
height: Int,
tuning: PhotonDehazeTuning,
): Output? {
val startedAtNs = System.nanoTime()
val normalizedTuning = tuning.normalized()
require(normalizedTuning.isActive) { "Photon dehaze render requested while disabled" }
require(sourceTextureId != 0 && targetTextureId != 0) {
require(
histogramSourceTextureId != 0 && sourceTextureId != 0 && targetTextureId != 0
) {
"Photon dehaze requires valid source and destination textures"
}
require(sourceTextureId != targetTextureId) {
"Photon dehaze requires a linear RGB ping-pong destination"
}
require(width > 0 && height > 0) { "Invalid Photon dehaze dimensions" }
require(
histogramWidth > 0 && histogramHeight > 0 && width > 0 && height > 0
) { "Invalid Photon dehaze dimensions" }
if (!initialize()) return null
val lowWidth = (width + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
val lowHeight = (height + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
val lowWidth = (histogramWidth + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
val lowHeight = (histogramHeight + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
resetHistogram()
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, sourceTextureId)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, histogramSourceTextureId)
// LinearRcd writes through a framebuffer; histogram consumes that texture by sampler.
GLES31.glMemoryBarrier(
@@ -124,7 +153,11 @@ internal class PhotonDehazePipeline {
)
GLES31.glUseProgram(histogramProgram)
GLES31.glUniform1i(histogramSourceLocation, 0)
GLES31.glUniform2i(histogramSourceSizeLocation, width, height)
GLES31.glUniform2i(
histogramSourceSizeLocation,
histogramWidth,
histogramHeight,
)
GLES31.glUniform2i(histogramLowSizeLocation, lowWidth, lowHeight)
GLES31.glBindBufferBase(
GLES31.GL_SHADER_STORAGE_BUFFER,
@@ -158,6 +191,8 @@ internal class PhotonDehazePipeline {
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
GLES31.glUseProgram(applyProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, sourceTextureId)
GLES31.glUniform1i(applySourceLocation, 0)
GLES31.glUniform2i(applySourceSizeLocation, width, height)
GLES31.glBindBufferBase(
@@ -189,7 +224,9 @@ internal class PhotonDehazePipeline {
requireNoGlError("GPU-resident histogram/curve/apply")
PLog.i(
TAG,
"Photon dehaze submitted size=${width}x$height low=${lowWidth}x$lowHeight " +
"Photon dehaze submitted size=${width}x$height " +
"histogram=${histogramWidth}x$histogramHeight " +
"low=${lowWidth}x$lowHeight " +
"maxSamples=${lowWidth * lowHeight} path=GPU_COMPUTE_BATCHED_HISTOGRAM " +
"curveScanBins=${HAZE_HISTOGRAM_SIZE + HIGHLIGHT_HISTOGRAM_SIZE} " +
"cpuReadback=false strength=${normalizedTuning.strength} " +
@@ -45,11 +45,6 @@ internal object RawCaptureProfileCoordinator {
viewfinderMirroredHorizontally = viewfinderMirroredHorizontally,
viewfinderPreviewToCaptureRotationDegrees =
viewfinderPreviewToCaptureRotationDegrees,
scalarMatchingCenterFractionPerAxis = if (mode.usesPhotonHdr) {
1f
} else {
RawLegacyAutoExposureMatcher.SCALAR_MATCH_CENTER_FRACTION_PER_AXIS
},
highlightClippingConstraint = if (mode == RawAdaptiveExposureMode.OFF) {
RawLegacyHighlightClippingConstraint.HDR_PLUS_DISABLED
} else {
@@ -2398,18 +2398,7 @@ class RawDemosaicProcessor {
var embeddedDngRenderPlan: DcpRenderPlan? = sourceDngRenderPlan
var embeddedDngProfiles: List<DngEmbeddedProfileEntry> = emptyList()
var selectedEmbeddedDngProfile: DngEmbeddedProfileEntry? = null
val sourceProfileGainTableMapCandidate = metadata?.profileGainTableMap
val sourcePgtmValidationStartNs = System.nanoTime()
val sourceProfileGainTableMap =
sourceProfileGainTableMapCandidate?.takeIf { it.isValid }
sourceProfileGainTableMapCandidate?.let { candidate ->
PLog.i(
TAG,
"PGTM validation stage=RENDER_SOURCE " +
"points=${candidate.gains.size} valid=${sourceProfileGainTableMap != null} " +
"tookUs=${(System.nanoTime() - sourcePgtmValidationStartNs) / 1_000L}",
)
}
val sourceProfileGainTableMap = metadata?.profileGainTableMap?.takeIf { it.isValid }
if (dngFile != null) {
val hasClassicTiffHeader = DngProfileGainTableMap.hasClassicTiffHeader(dngFile)
@@ -3101,7 +3090,7 @@ class RawDemosaicProcessor {
sceneExposureRequest == null && legacyAutoExposureRequest != null
val captureUsesLocalLaplacian =
captureUsesViewfinderBrightnessMatch && capturePhotonPgtmRequested
val solvedExposureEv = legacyAutoExposureRequest
val initialSolvedExposureEv = legacyAutoExposureRequest
?.takeIf { captureUsesViewfinderBrightnessMatch }
?.let { request ->
renderLegacyAutoExposureRequest(
@@ -3148,23 +3137,30 @@ class RawDemosaicProcessor {
"${solution.fractionPixelsClippedAtFinalShortTet}",
)
}
solvedExposureEv?.let { exposureEv ->
initialSolvedExposureEv?.let { exposureEv ->
PLog.i(
TAG,
"RAW_VIEWFINDER_BRIGHTNESS_MATCH stage=METERING_COMPLETE " +
"RAW_VIEWFINDER_BRIGHTNESS_MATCH stage=" +
"${if (captureUsesLocalLaplacian) {
"PRE_PGTM_METERING_COMPLETE"
} else {
"METERING_COMPLETE"
}} " +
"sourceBaselineEv=${actualMetadata.baselineExposure} " +
"exposureOffsetEv=$exposureEv",
)
}
val finalBaselineExposureEv = DngBaselineExposure.resolveCaptureBaseline(
val initialBaselineExposureEv = DngBaselineExposure.resolveCaptureBaseline(
sourceBaselineEv = actualMetadata.baselineExposure,
legacyExposureOffsetEv = solvedExposureEv,
legacyExposureOffsetEv = initialSolvedExposureEv,
)
val dcpBaselineExposureOffsetEv =
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan)
val captureHdrRatio = solvedSceneExposure?.hdrRatio
?.takeIf { it.isFinite() && it >= 1f }
val captureSourceToShortGain = solvedSceneExposure?.finalShortGain
?.takeIf { it.isFinite() && it > 0f }
val captureProfileOutput = when {
val initialCaptureProfileOutput = when {
capturePhotonPgtmRequested && captureUsesHdrNet &&
legacyAutoExposureRequest != null && captureHdrRatio != null &&
captureSourceToShortGain != null -> {
@@ -3182,8 +3178,8 @@ class RawDemosaicProcessor {
samplesPerPixel = actualSamplesPerPixel,
metadata = actualMetadata.copy(profileGainTableMap = null),
statsBounds = processingBounds,
rendererBaselineExposureEv = finalBaselineExposureEv +
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
rendererBaselineExposureEv = initialBaselineExposureEv +
dcpBaselineExposureOffsetEv,
viewfinderReference = legacyAutoExposureRequest.referenceFrame,
outputRotation = actualRotation,
// HDRNet's ratio describes capture exposure, not the DCP profile's
@@ -3200,7 +3196,7 @@ class RawDemosaicProcessor {
)
}
capturePhotonPgtmRequested && captureUsesLocalLaplacian &&
solvedExposureEv != null -> {
initialSolvedExposureEv != null -> {
generateProfileGainTableMapOnGpu(
mode = DngPhotonProfileGainTableAlgorithm.Mode.LOCAL_LAPLACIAN,
context = context.applicationContext,
@@ -3215,8 +3211,8 @@ class RawDemosaicProcessor {
samplesPerPixel = actualSamplesPerPixel,
metadata = actualMetadata.copy(profileGainTableMap = null),
statsBounds = processingBounds,
rendererBaselineExposureEv = finalBaselineExposureEv +
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
rendererBaselineExposureEv = initialBaselineExposureEv +
dcpBaselineExposureOffsetEv,
viewfinderReference = null,
outputRotation = actualRotation,
hdrRatio = 1f,
@@ -3243,6 +3239,72 @@ class RawDemosaicProcessor {
null
}
}
var solvedExposureEv = initialSolvedExposureEv
var captureProfileOutput = initialCaptureProfileOutput
if (captureUsesLocalLaplacian && initialSolvedExposureEv != null &&
initialCaptureProfileOutput != null
) {
val viewfinderMatchRequest = checkNotNull(legacyAutoExposureRequest)
val generatedTotalBaselineExposureEv = initialBaselineExposureEv +
dcpBaselineExposureOffsetEv
// Candidate EV remains relative to the source BaselineExposure. Rebase only
// the lookup weights used by this preview so the generated LL curve keeps the
// same sensor-linear N coordinate while the solver varies the post-PGTM ramp.
val previewTotalBaselineExposureEv =
DngBaselineExposure.sanitize(actualMetadata.baselineExposure) +
dcpBaselineExposureOffsetEv
val previewMap = initialCaptureProfileOutput.map
.rebasedForRendererBaseline(
fromTotalBaselineExposureEv = generatedTotalBaselineExposureEv,
toTotalBaselineExposureEv = previewTotalBaselineExposureEv,
)
val finalMatchedExposureEv = previewMap?.let { map ->
renderLegacyAutoExposureRequest(
request = viewfinderMatchRequest,
metadata = actualMetadata.copy(profileGainTableMap = map),
sourceTextureId = demosaicTextureId,
colorCorrectionMatrix = linearColorCorrectionMatrix,
cameraWhite = linearCameraWhite,
dcpRenderPlan = activeDcpRenderPlan,
rawBlackPointCorrection = rawBlackPointCorrection,
rawWhitePointCorrection = rawWhitePointCorrection,
outputSourceBounds = outputSourceBounds,
outputRotation = actualRotation,
applyProfileGainTableMap = true,
)
}
val finalMap = finalMatchedExposureEv?.let { exposureEv ->
val finalBaselineExposureEv = DngBaselineExposure.resolveCaptureBaseline(
sourceBaselineEv = actualMetadata.baselineExposure,
legacyExposureOffsetEv = exposureEv,
)
initialCaptureProfileOutput.map.rebasedForRendererBaseline(
fromTotalBaselineExposureEv = generatedTotalBaselineExposureEv,
toTotalBaselineExposureEv = finalBaselineExposureEv +
dcpBaselineExposureOffsetEv,
)
}
if (finalMatchedExposureEv == null || finalMap == null) {
PLog.e(
TAG,
"Local Laplacian final-domain viewfinder matching failed",
)
solvedExposureEv = null
captureProfileOutput = null
} else {
solvedExposureEv = finalMatchedExposureEv
captureProfileOutput = initialCaptureProfileOutput.copy(map = finalMap)
PLog.i(
TAG,
"RAW_VIEWFINDER_BRIGHTNESS_MATCH " +
"stage=POST_LOCAL_LAPLACIAN_METERING_COMPLETE " +
"sourceBaselineEv=${actualMetadata.baselineExposure} " +
"prePgtmExposureOffsetEv=$initialSolvedExposureEv " +
"finalExposureOffsetEv=$finalMatchedExposureEv " +
"pgtmWeightRebase=true",
)
}
}
val captureProfileGainTableMap = captureProfileOutput?.map
val selectedCaptureHdrRatio = captureProfileOutput?.hdrRatio ?: captureHdrRatio
val selectedCaptureSourceToShortGain =
@@ -3255,94 +3317,10 @@ class RawDemosaicProcessor {
append(summary.trimEnd())
appendLine()
appendLine("hdrNetExposureTarget=FULL_CAPTURE_VIEWFINDER_THUMBNAIL")
appendLine("hdrNetExposureGrid=64x48_PAIRED_LOG2_REC709")
appendLine(
"hdrNetShortExposureAdjustmentEv=" +
output.hdrNetShortExposureAdjustmentEv,
)
appendLine(
"hdrNetLongExposureAdjustmentEv=" +
output.hdrNetLongExposureAdjustmentEv,
)
appendLine("hdrNetExposureGrid=8x6_WEIGHTED_DIRECT_LOG2_EV")
appendLine("hdrNetFinalShortGain=$outputShortGain")
appendLine("hdrNetFinalLongGain=${outputShortGain * outputHdrRatio}")
appendLine("hdrNetFinalHdrRatio=$outputHdrRatio")
output.hdrNetExposureEvaluation?.let { evaluation ->
appendLine(
"hdrNetExposureCenterErrorEv=${evaluation.centerErrorEv}",
)
appendLine(
"hdrNetExposureSpanErrorEv=${evaluation.spanErrorEv}",
)
appendLine(
"hdrNetExposureCurveSlopeError=" +
evaluation.curveSlopeError,
)
appendLine(
"hdrNetExposureReferenceSpanEv=" +
evaluation.referenceSpanEv,
)
appendLine(
"hdrNetExposureMedianLog2Ratio=${evaluation.medianLog2Ratio}",
)
appendLine(
"hdrNetExposureRobustLog2Loss=${evaluation.robustLog2Loss}",
)
appendLine(
"hdrNetExposureMeanAbsoluteLog2Ratio=" +
evaluation.meanAbsoluteLog2Ratio,
)
appendLine(
"hdrNetExposureMeanPerceptualLightnessError=" +
evaluation.meanAbsolutePerceptualLightnessError,
)
appendLine("hdrNetExposureMatchRate=${evaluation.matchRate}")
appendLine(
"hdrNetExposureCoordinateEdges=" +
evaluation.coordinateComparedEdgeCount,
)
appendLine(
"hdrNetExposureCoordinateMatchRate=" +
evaluation.coordinateMatchRate,
)
appendLine(
"hdrNetExposureCoordinatesMatched=" +
evaluation.coordinatesMatched,
)
appendLine(
"hdrNetExposureRecommendedCorrectionEv=" +
evaluation.recommendedExposureCorrectionEv,
)
appendLine(
"hdrNetExposureHighlightTargetErrorEv=" +
evaluation.highlightTargetErrorEv,
)
appendLine(
"hdrNetExposureShadowTargetErrorEv=" +
evaluation.shadowTargetErrorEv,
)
appendLine(
"hdrNetExposureShortTargetCorrectionEv=" +
evaluation.shortTargetCorrectionEv,
)
appendLine(
"hdrNetExposureLongTargetCorrectionEv=" +
evaluation.longTargetCorrectionEv,
)
appendLine("hdrNetExposureConverged=${evaluation.converged}")
appendLine(
"hdrNetExposureFallback1d=" +
evaluation.usedOneDimensionalFallback,
)
appendLine(
"hdrNetExposureJacobianNormalizedDeterminant=" +
evaluation.jacobianNormalizedDeterminant,
)
appendLine(
"hdrNetExposureCandidateCount=" +
evaluation.evaluatedCandidateCount,
)
}
}.trimEnd()
}
val captureProfileFailed =
@@ -3487,11 +3465,7 @@ class RawDemosaicProcessor {
"${regeneratedPhotonPgtm.map.mapPointsV}x" +
regeneratedPhotonPgtm.map.mapPointsN +
" hdrRatio=${regeneratedPhotonPgtm.hdrRatio}" +
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}" +
" shortExposureAdjustmentEv=" +
regeneratedPhotonPgtm.hdrNetShortExposureAdjustmentEv +
" longExposureAdjustmentEv=" +
regeneratedPhotonPgtm.hdrNetLongExposureAdjustmentEv,
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}",
)
}
@@ -6709,7 +6683,9 @@ class RawDemosaicProcessor {
fullImageWidth: Int = metadata.width,
fullImageHeight: Int = metadata.height,
viewportWidth: Int = metadata.width,
viewportHeight: Int = metadata.height
viewportHeight: Int = metadata.height,
globalWidth: Int = viewportWidth,
globalHeight: Int = viewportHeight,
): RawCombinedRenderOutput? {
val outputTransform = computeWorkingToOutputTransform(outputWorkingColorSpace, ColorSpace.SRGB)
setupEngineToneFramebuffer(viewportWidth, viewportHeight)
@@ -6729,6 +6705,8 @@ class RawDemosaicProcessor {
globalOriginY = globalOriginY,
fullImageWidth = fullImageWidth,
fullImageHeight = fullImageHeight,
globalWidth = globalWidth,
globalHeight = globalHeight,
rawToneMappingParameters = rawToneMappingParameters,
outputTransform = outputTransform,
viewportWidth = viewportWidth,
@@ -6847,7 +6825,9 @@ class RawDemosaicProcessor {
rawToneMappingParameters: RawToneMappingParameters,
outputTransform: FloatArray,
viewportWidth: Int,
viewportHeight: Int
viewportHeight: Int,
globalWidth: Int = viewportWidth,
globalHeight: Int = viewportHeight,
): Boolean {
return engineTonePass.render(
RawEngineTonePass.Input(
@@ -6863,6 +6843,8 @@ class RawDemosaicProcessor {
fullImageHeight = fullImageHeight,
width = viewportWidth,
height = viewportHeight,
globalWidth = globalWidth,
globalHeight = globalHeight,
toneMappingParameters = rawToneMappingParameters,
profileExposure = profileExposureUniforms,
dcpRenderPlan = dcpRenderPlan,
@@ -8019,7 +8001,6 @@ class RawDemosaicProcessor {
stackCompletionTimeline: GpuStackCompletionTimeline? = null,
restoreSourceBaselineExposure: Boolean = false,
): RawSceneExposureResult? {
val inputPreparationStartedNs = System.nanoTime()
return try {
val width = RawSceneExposureMath.INPUT_WIDTH
val height = RawSceneExposureMath.INPUT_HEIGHT
@@ -8098,18 +8079,15 @@ class RawDemosaicProcessor {
} else {
1f
}
val meteringInputSource: String
val cameraRgb: FloatArray
val lensShadingStats: RawSceneAERawStats?
if (baseFrameMetering != null) {
meteringInputSource = "BASE_RAW_SENSOR"
cameraRgb = baseFrameMetering.sensorRgb
lensShadingStats = suppliedFastMomentsRawStats
} else {
// Regenerated/standalone DNGs cannot recover the selected burst base frame. The
// demosaic output is camera RGB with LSC already applied, so only use it as an
// explicit fallback and keep all remaining MGC color operations on the CPU.
meteringInputSource = "RENDERED_CAMERA_RGB_FALLBACK"
lensShadingStats = null
val areaSampleFootprint = floatArrayOf(
(normalizedBounds[2] - normalizedBounds[0]) / width.toFloat(),
@@ -8155,7 +8133,6 @@ class RawDemosaicProcessor {
} else {
metadata
}
val meteringStartedNs = System.nanoTime()
val meteringRgb = RawSceneExposureMath.prepareFastMomentsMeteringRgb(
cameraRgb = cameraRgb,
width = width,
@@ -8165,60 +8142,6 @@ class RawDemosaicProcessor {
rgbTransform = meteringRgbTransform,
lensShadingStats = lensShadingStats,
) ?: return null
val meteringCompletedNs = System.nanoTime()
val meteringRgbMean = FloatArray(3)
val meteringRgbMax = FloatArray(3)
for (pixel in 0 until width * height) {
for (channel in 0..2) {
val value = meteringRgb[pixel * 3 + channel]
meteringRgbMean[channel] += value
if (value > meteringRgbMax[channel]) meteringRgbMax[channel] = value
}
}
for (channel in 0..2) meteringRgbMean[channel] /= (width * height).toFloat()
val baseFrameHasLensShading = baseFrameMetering?.let { metering ->
metering.lensShadingMap != null &&
metering.lensShadingMapWidth > 0 && metering.lensShadingMapHeight > 0 &&
metering.lensShadingMap.size >=
metering.lensShadingMapWidth * metering.lensShadingMapHeight * 4
} == true
val diagnosticsCompletedNs = System.nanoTime()
fun elapsedMs(startedNs: Long, completedNs: Long): Float =
(completedNs - startedNs).toFloat() / 1_000_000f
PLog.i(
TAG,
"RAW_SCENE_EXPOSURE stage=INPUT_PREP_TIMING " +
"setupMs=${elapsedMs(inputPreparationStartedNs, meteringStartedNs)} " +
"fastMeteringMs=${elapsedMs(meteringStartedNs, meteringCompletedNs)} " +
"diagnosticsMs=${elapsedMs(meteringCompletedNs, diagnosticsCompletedNs)} " +
"totalMs=${elapsedMs(inputPreparationStartedNs, diagnosticsCompletedNs)}",
)
PLog.i(
TAG,
"RAW_SCENE_EXPOSURE stage=INPUT_COLOR_CONTRACT " +
"meteringSource=$meteringInputSource " +
"meteringGeometry=${if (baseFrameMetering != null) {
"MGC_RAW_ROWS_X1_OR_X4_GROUPS_DIRECT_64X64"
} else {
"RENDERED_CAMERA_RGB_AREA_64X64_FALLBACK"
}} " +
"sourceBaselineRestored=$restoreFallbackBaselineExposure " +
"sourceBaselineGain=$sourceBaselineGain " +
"lscSource=${when {
baseFrameHasLensShading -> "BASE_RAW_CAPTURE_MAP"
baseFrameMetering != null -> "UNITY"
else -> "RENDERED_CAMERA_RGB"
}} " +
"gainsSource=${if (camera2Gains != null) "CAMERA2_CAPTURE_RESULT" else "DNG_WHITE_BALANCE_FALLBACK"} " +
"matrixSource=${if (camera2Transform != null) "CAMERA2_CAPTURE_RESULT" else "DNG_COLOR_SPEC_FALLBACK"} " +
"camera2ColorCorrectionMode=${metadata.camera2ColorCorrectionMode} " +
"rggbGains=${gains.contentToString()} " +
"rgbGains=${rgbGains.contentToString()} " +
"rgb2rgb=${meteringRgbTransform.contentToString()} " +
"rawAeBounds=$rawAeBounds " +
"meteringRgbMean=${meteringRgbMean.contentToString()} " +
"meteringRgbMax=${meteringRgbMax.contentToString()}",
)
val fastMomentsStats = suppliedFastMomentsRawStats ?: if (
rawSamplesPerPixel == 1 && rawTextureIdForStats != 0
@@ -8372,15 +8295,23 @@ class RawDemosaicProcessor {
rawWhitePointCorrection: Float,
outputSourceBounds: Rect,
outputRotation: Int,
applyProfileGainTableMap: Boolean = false,
): Float? {
val width = request.width.coerceAtLeast(1)
val height = request.height.coerceAtLeast(1)
val normalizedRotation = Math.floorMod(outputRotation, 360)
if (normalizedRotation != 0 && normalizedRotation != 90 &&
normalizedRotation != 180 && normalizedRotation != 270
) {
return null
}
val swapsAxes = normalizedRotation == 90 || normalizedRotation == 270
val renderWidth = if (swapsAxes) height else width
val renderHeight = if (swapsAxes) width else height
return try {
setupLinearExposurePreviewFramebuffer(width, height)
val matchingSourceBounds = RawLegacyAutoExposureMatcher.centeredBounds(
outputBounds = outputSourceBounds,
centerFractionPerAxis = request.scalarMatchingCenterFractionPerAxis,
) ?: return null
setupLinearExposurePreviewFramebuffer(renderWidth, renderHeight)
setupSharpenFramebuffer(width, height)
val matchingSourceBounds = outputSourceBounds
val normalizedBounds = floatArrayOf(
matchingSourceBounds.left.toFloat() / metadata.width.toFloat(),
matchingSourceBounds.top.toFloat() / metadata.height.toFloat(),
@@ -8388,27 +8319,29 @@ class RawDemosaicProcessor {
matchingSourceBounds.bottom.toFloat() / metadata.height.toFloat(),
)
val areaSampleFootprint = floatArrayOf(
(normalizedBounds[2] - normalizedBounds[0]) / width.toFloat(),
(normalizedBounds[3] - normalizedBounds[1]) / height.toFloat(),
(normalizedBounds[2] - normalizedBounds[0]) / renderWidth.toFloat(),
(normalizedBounds[3] - normalizedBounds[1]) / renderHeight.toFloat(),
)
// Candidate exposure is applied through the same Adobe/DNG exposure ramp used by the
// final render. The camera-to-profile conversion itself remains exposure-neutral.
// Dehaze is globally bypassed. Match the remaining final Adobe path exactly: apply
// the selected HueSatMap in profile-linear space, then PGTM (when requested), the DNG
// exposure ramp, black/white adjustment, sRGB encoding, and final output rotation.
// Keeping PGTM before rotation also preserves the map's sensor-space coordinates.
renderLinearRcdPass(
metadata = metadata,
sourceTextureId = sourceTextureId,
targetFramebufferId = linearExposurePreviewFramebufferId,
viewportWidth = width,
viewportHeight = height,
viewportWidth = renderWidth,
viewportHeight = renderHeight,
rawExposureCompensation = 0f,
colorCorrectionMatrix = colorCorrectionMatrix,
cameraWhite = cameraWhite,
hueSatMap = null,
hueSatMap = dcpRenderPlan?.hueSatMap,
applyDngBaselineExposure = false,
clampProfileRgb = true,
hueSatMapSupportsOverrange = dcpRenderPlan?.supportsOverrange == true,
textureBounds = normalizedBounds,
areaSampleFootprint = areaSampleFootprint,
textureRotation = outputRotation,
textureRotation = 0,
label = "RawViewfinderBrightnessMatchLinearPass",
)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
@@ -8476,14 +8409,48 @@ class RawDemosaicProcessor {
rawWhitesAdjustment = rawWhitePointCorrection,
rawToneMappingParameters = RawToneMappingParameters.DEFAULT
.withPhotonHdr(false),
applyProfileGainTableMap = false,
viewportWidth = width,
viewportHeight = height,
applyProfileGainTableMap = applyProfileGainTableMap,
globalOriginX = matchingSourceBounds.left,
globalOriginY = matchingSourceBounds.top,
fullImageWidth = metadata.width,
fullImageHeight = metadata.height,
viewportWidth = renderWidth,
viewportHeight = renderHeight,
globalWidth = matchingSourceBounds.width(),
globalHeight = matchingSourceBounds.height(),
)
if (rendered == null) {
null
} else {
readLegacyExposurePreviewFrame(width, height, readback)
val orientedBounds = Rect(
0,
0,
renderWidth,
renderHeight,
).toOutputBounds(normalizedRotation)
val oriented = outputPass.render(
RawOutputPass.Input(
textureId = rendered.encodedTextureId,
sourceWidth = renderWidth,
sourceHeight = renderHeight,
rotation = normalizedRotation,
bounds = orientedBounds,
targetFramebufferId = sharpenFramebufferId,
targetTextureId = sharpenTextureId,
targetWidth = width,
targetHeight = height,
),
)
if (oriented == null) {
null
} else {
readLegacyExposurePreviewFrame(
width = width,
height = height,
readback = readback,
framebufferId = sharpenFramebufferId,
)
}
}
},
maximumExposureEv,
@@ -8501,11 +8468,12 @@ class RawDemosaicProcessor {
width: Int,
height: Int,
readback: ByteBuffer,
framebufferId: Int,
): RawLegacyExposurePreviewFrame? {
val pixelCount = width * height
readback.clear()
readback.limit(pixelCount * 4)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, combinedFramebufferId)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
GLES30.glReadPixels(
@@ -21,6 +21,9 @@ internal class RawEngineTonePass(
val fullImageHeight: Int,
val width: Int,
val height: Int,
/** Full-image pixel span represented by this possibly downsampled input texture. */
val globalWidth: Int = width,
val globalHeight: Int = height,
val toneMappingParameters: RawToneMappingParameters,
val profileExposure: RawProfileExposureGl.Uniforms,
val dcpRenderPlan: DcpRenderPlan?,
@@ -20,10 +20,8 @@ internal data class RawLegacyExposurePreviewFrame(
internal data class RawLegacyAutoExposureRequest(
val width: Int,
val height: Int,
/** Complete capture-time viewfinder image retained for Photon HDR spatial matching. */
/** Complete capture-time viewfinder image used by both exposure matching paths. */
val referenceFrame: RawLegacyExposurePreviewFrame,
/** Center fraction used by the scalar viewfinder matcher on both axes. */
val scalarMatchingCenterFractionPerAxis: Float,
val highlightClippingConstraint: RawLegacyHighlightClippingConstraint?,
val solve: (
renderSample: (Float) -> RawLegacyExposurePreviewFrame?,
@@ -76,37 +74,6 @@ internal data class RawLegacyHighlightExposureLimit(
val pixelCount: Long,
)
internal data class RawHdrNetExposureEvaluation(
val centerErrorEv: Float,
val spanErrorEv: Float,
val curveSlopeError: Float,
val referenceSpanEv: Float,
val highlightTargetErrorEv: Float,
val shadowTargetErrorEv: Float,
val shortTargetCorrectionEv: Float,
val longTargetCorrectionEv: Float,
val medianLog2Ratio: Float,
val robustLog2Loss: Float,
val meanAbsoluteLog2Ratio: Float,
val meanAbsolutePerceptualLightnessError: Float,
val matchRate: Float,
val coordinateComparedEdgeCount: Int,
val coordinateMatchRate: Float,
val coordinatesMatched: Boolean?,
val recommendedExposureCorrectionEv: Float,
val evaluatedCandidateCount: Int,
val converged: Boolean,
val usedOneDimensionalFallback: Boolean,
val jacobianNormalizedDeterminant: Float,
)
internal data class RawHdrNetExposureCandidate<T>(
val shortGain: Float,
val longGain: Float,
val payload: T,
val evaluation: RawHdrNetExposureEvaluation,
)
/**
* Capture-side viewfinder matching derived from PhotonCamera 1.27.1's spatial solver. Native code
* owns reference linearization, robust grid statistics and both exposure solvers. Kotlin only
@@ -116,8 +83,6 @@ internal object RawLegacyAutoExposureMatcher {
private const val TAG = "RawLegacyAutoExposureMatcher"
private const val PREVIEW_LONG_EDGE = 256
private const val PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION = 0.045f
const val SCALAR_MATCH_CENTER_FRACTION_PER_AXIS = 2f / 3f
private data class ViewfinderReference(
val frame: RawLegacyExposurePreviewFrame,
)
@@ -130,8 +95,6 @@ internal object RawLegacyAutoExposureMatcher {
private data class HdrNetInference<T>(
val shortEv: Float,
val hdrRatioEv: Float,
val shortGain: Float,
val longGain: Float,
val payload: T,
)
@@ -140,15 +103,8 @@ internal object RawLegacyAutoExposureMatcher {
capturePortraitMask: PortraitMaskSnapshot? = null,
viewfinderMirroredHorizontally: Boolean = false,
viewfinderPreviewToCaptureRotationDegrees: Int = 0,
scalarMatchingCenterFractionPerAxis: Float = 1f,
highlightClippingConstraint: RawLegacyHighlightClippingConstraint? = null,
): RawLegacyAutoExposureRequest? {
if (!scalarMatchingCenterFractionPerAxis.isFinite() ||
scalarMatchingCenterFractionPerAxis <= 0f ||
scalarMatchingCenterFractionPerAxis > 1f
) {
return null
}
val normalizedViewfinderRotation = Math.floorMod(
viewfinderPreviewToCaptureRotationDegrees,
360,
@@ -169,58 +125,25 @@ internal object RawLegacyAutoExposureMatcher {
snapshot = capturePortraitMask,
expectedRotationDegrees = normalizedViewfinderRotation,
)
val detectedPortraitAreaFraction = portraitPriority?.areaFraction
?: capturePortraitMask?.let(::portraitAreaFraction)
// A portrait outside the historical center crop still has to be observable by the scalar
// solver. The RAW highlight guard remains independently constrained to its center region.
val effectiveScalarCenterFraction = if (portraitPriority != null) {
1f
} else {
scalarMatchingCenterFractionPerAxis
}
PLog.i(
TAG,
"Viewfinder portrait target: available=${capturePortraitMask != null} " +
"areaFraction=$detectedPortraitAreaFraction " +
"minimumAreaFraction=$PORTRAIT_PRIORITY_MINIMUM_AREA_FRACTION " +
"active=${portraitPriority != null} " +
"previewToCaptureRotation=" +
"$normalizedViewfinderRotation " +
"portraitMaskRotation=${capturePortraitMask?.previewToCaptureRotationDegrees} " +
"viewfinderMirroredHorizontally=$viewfinderMirroredHorizontally " +
"scalarCenterFraction=$effectiveScalarCenterFraction",
)
// Matching always uses the complete viewfinder. The RAW highlight guard remains
// independently constrained to its configured center region.
val completeReference = buildReference(
bitmap = bitmap,
portraitPriority = portraitPriority,
mirrorHorizontally = viewfinderMirroredHorizontally,
previewToCaptureRotationDegrees = normalizedViewfinderRotation,
)
val scalarReference = when {
completeReference == null -> null
effectiveScalarCenterFraction >= 1f -> completeReference
else -> buildReference(
bitmap = bitmap,
centerFractionPerAxis = effectiveScalarCenterFraction,
portraitPriority = portraitPriority,
mirrorHorizontally = viewfinderMirroredHorizontally,
previewToCaptureRotationDegrees = normalizedViewfinderRotation,
)
}
if (completeReference == null || scalarReference == null) {
if (completeReference == null) {
PLog.w(TAG, "Viewfinder matching skipped: capture preview is unavailable")
}
return completeReference?.let { complete ->
val scalar = scalarReference ?: return@let null
RawLegacyAutoExposureRequest(
width = scalar.frame.width,
height = scalar.frame.height,
width = complete.frame.width,
height = complete.frame.height,
referenceFrame = complete.frame,
scalarMatchingCenterFractionPerAxis =
effectiveScalarCenterFraction,
highlightClippingConstraint = highlightClippingConstraint,
solve = { renderSample, maximumExposureEv ->
solve(scalar, renderSample, maximumExposureEv)
solve(complete, renderSample, maximumExposureEv)
},
)
}
@@ -290,17 +213,13 @@ internal object RawLegacyAutoExposureMatcher {
private fun buildReference(
bitmap: Bitmap,
centerFractionPerAxis: Float = 1f,
portraitPriority: PortraitPrioritySource? = null,
mirrorHorizontally: Boolean = false,
previewToCaptureRotationDegrees: Int = 0,
): ViewfinderReference? {
if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return null
return try {
val sourceBounds = centeredBounds(
outputBounds = Rect(0, 0, bitmap.width, bitmap.height),
centerFractionPerAxis = centerFractionPerAxis,
) ?: return null
val sourceBounds = Rect(0, 0, bitmap.width, bitmap.height)
val size = longEdgeSize(
sourceBounds.width(),
sourceBounds.height(),
@@ -341,17 +260,17 @@ internal object RawLegacyAutoExposureMatcher {
/**
* Drives the native two-dimensional HDRNet matcher.
*
* Native code jointly searches independent short and long EV coordinates. Highlight-grid
* error drives short, shadow-grid error drives long, and the measured cross-response is kept
* in the Jacobian. Selection and convergence use the full-grid match rate. This maps native
* requests back to short EV and HDR-ratio EV and runs the model callback.
* Native code jointly searches the model's short-EV and HDR-ratio-EV coordinates. Robust
* highlight error anchors short exposure, paired p20..p80 dynamic-range error drives HDR
* ratio, and their measured cross-response is retained in the damped Jacobian. Selection and
* convergence still use the weighted full-grid direct-EV match rate.
*/
fun <T> solveHdrNetExposure(
referenceFrame: RawLegacyExposurePreviewFrame,
initialShortGain: Float,
initialLongGain: Float,
evaluateCandidate: (shortGain: Float, longGain: Float) -> Pair<T, FloatArray>?,
): RawHdrNetExposureCandidate<T>? {
): T? {
if (!initialShortGain.isFinite() || !initialLongGain.isFinite() ||
initialShortGain <= 0f || initialLongGain < initialShortGain
) {
@@ -384,83 +303,20 @@ internal object RawLegacyAutoExposureMatcher {
) {
return@use null
}
val probeStartNs = System.nanoTime()
val candidate = evaluateCandidate(shortGain, longGain) ?: return@use null
val candidateReadyNs = System.nanoTime()
val sample = solver.submitHdrNetCandidate(
if (!solver.submitHdrNetCandidate(
parameters = parameters,
displayLinearLumas = candidate.second,
columns = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH,
rows = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_HEIGHT,
) ?: return@use null
val coordinatesMatched = solver.lastCandidateCoordinatesMatch()
columns = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH,
rows = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT,
)) return@use null
inferences += HdrNetInference(
shortEv = parameters.shortEv,
hdrRatioEv = parameters.hdrRatioEv,
shortGain = shortGain,
longGain = longGain,
payload = candidate.first,
)
val probeReadyNs = System.nanoTime()
PLog.d(
TAG,
"HDRNet viewfinder probe: index=${inferences.size} " +
"adjustmentAxis=${parameters.axis} " +
"shortEv=${parameters.shortEv} ratioEv=${parameters.hdrRatioEv} " +
"longEv=${parameters.shortEv + parameters.hdrRatioEv} " +
"shortGain=$shortGain longGain=$longGain hdrRatio=$hdrRatio " +
"matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " +
"curveFitCells=${sample.curveFitCellCount} " +
"centerErrorEv=${sample.centerErrorEv} " +
"spanErrorEv=${sample.spanErrorEv} " +
"curveSlopeError=${sample.curveSlopeError} " +
"highlightTargetErrorEv=${sample.highlightTargetErrorEv} " +
"shadowTargetErrorEv=${sample.shadowTargetErrorEv} " +
"shortTargetCorrectionEv=${sample.shortTargetCorrectionEv} " +
"longTargetCorrectionEv=${sample.longTargetCorrectionEv} " +
"referenceP20Ev=${sample.referenceP20Ev} " +
"referenceP50Ev=${sample.referenceP50Ev} " +
"referenceP80Ev=${sample.referenceP80Ev} " +
"robustLog2Loss=${sample.robustLog2Loss} " +
"matchRate=${sample.matchRate} " +
"meanPerceptualLightnessError=" +
"${sample.meanAbsolutePerceptualLightnessError} " +
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${sample.coordinateMatchRate} " +
"coordinatesMatched=$coordinatesMatched " +
"recommendedExposureCorrectionEv=" +
"${sample.recommendedExposureCorrectionEv} " +
"candidateMs=${(candidateReadyNs - probeStartNs) / 1_000_000f} " +
"matchStatsMs=${(probeReadyNs - candidateReadyNs) / 1_000_000f} " +
"totalMs=${(probeReadyNs - probeStartNs) / 1_000_000f}",
)
}
val result = solver.hdrNetResult() ?: return@use null
if (result.sample.coordinatesMatched == false) {
PLog.w(
TAG,
"HDRNet viewfinder matching rejected: " +
"reason=COORDINATE_MISMATCH " +
"matchRate=${result.sample.matchRate} " +
"coordinateEdges=${result.sample.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${result.sample.coordinateMatchRate} " +
"coordinatesMatched=${result.sample.coordinatesMatched} " +
"candidateCount=${result.evaluatedCandidateCount}",
)
return@use null
}
if (!result.converged) {
PLog.w(
TAG,
"HDRNet viewfinder matching did not reach the early-convergence target; " +
"using the highest-match-rate candidate: " +
"matchRate=${result.sample.matchRate} " +
"coordinateEdges=${result.sample.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${result.sample.coordinateMatchRate} " +
"coordinatesMatched=${result.sample.coordinatesMatched} " +
"candidateCount=${result.evaluatedCandidateCount}",
)
}
val selectedInference = inferences.minByOrNull {
abs(it.shortEv - result.shortEv) +
abs(it.hdrRatioEv - result.hdrRatioEv)
@@ -469,67 +325,7 @@ internal object RawLegacyAutoExposureMatcher {
abs(it.hdrRatioEv - result.hdrRatioEv) <
HDRNET_PAYLOAD_LOOKUP_TOLERANCE_EV
} ?: return@use null
val sample = result.sample
val selected = RawHdrNetExposureCandidate(
shortGain = selectedInference.shortGain,
longGain = selectedInference.longGain,
payload = selectedInference.payload,
evaluation = RawHdrNetExposureEvaluation(
centerErrorEv = sample.centerErrorEv,
spanErrorEv = sample.spanErrorEv,
curveSlopeError = sample.curveSlopeError,
referenceSpanEv = sample.referenceSpanEv,
highlightTargetErrorEv = sample.highlightTargetErrorEv,
shadowTargetErrorEv = sample.shadowTargetErrorEv,
shortTargetCorrectionEv = sample.shortTargetCorrectionEv,
longTargetCorrectionEv = sample.longTargetCorrectionEv,
medianLog2Ratio = sample.medianLog2Ratio,
robustLog2Loss = sample.robustLog2Loss,
meanAbsoluteLog2Ratio = sample.meanAbsoluteLog2Ratio,
meanAbsolutePerceptualLightnessError =
sample.meanAbsolutePerceptualLightnessError,
matchRate = sample.matchRate,
coordinateComparedEdgeCount = sample.coordinateComparedEdgeCount,
coordinateMatchRate = sample.coordinateMatchRate,
coordinatesMatched = sample.coordinatesMatched,
recommendedExposureCorrectionEv =
sample.recommendedExposureCorrectionEv,
evaluatedCandidateCount = result.evaluatedCandidateCount,
converged = result.converged,
usedOneDimensionalFallback = result.usedOneDimensionalFallback,
jacobianNormalizedDeterminant =
result.jacobianNormalizedDeterminant,
),
)
PLog.i(
TAG,
"HDRNet viewfinder result: shortGain=${selected.shortGain} " +
"longGain=${selected.longGain} " +
"hdrRatio=${selected.longGain / selected.shortGain} " +
"shortEv=${result.shortEv} ratioEv=${result.hdrRatioEv} " +
"longEv=${result.shortEv + result.hdrRatioEv} " +
"centerErrorEv=${sample.centerErrorEv} " +
"spanErrorEv=${sample.spanErrorEv} " +
"curveSlopeError=${sample.curveSlopeError} " +
"highlightTargetErrorEv=${sample.highlightTargetErrorEv} " +
"shadowTargetErrorEv=${sample.shadowTargetErrorEv} " +
"shortTargetCorrectionEv=${sample.shortTargetCorrectionEv} " +
"longTargetCorrectionEv=${sample.longTargetCorrectionEv} " +
"referenceSpanEv=${sample.referenceSpanEv} " +
"robustLog2Loss=${sample.robustLog2Loss} " +
"matchRate=${sample.matchRate} " +
"meanPerceptualLightnessError=" +
"${sample.meanAbsolutePerceptualLightnessError} " +
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${sample.coordinateMatchRate} " +
"coordinatesMatched=${sample.coordinatesMatched} " +
"jacobianNormalizedDeterminant=" +
"${result.jacobianNormalizedDeterminant} " +
"fallback1d=${result.usedOneDimensionalFallback} " +
"converged=${result.converged} " +
"candidateCount=${result.evaluatedCandidateCount}",
)
selected
selectedInference.payload
}
}
@@ -569,82 +365,14 @@ internal object RawLegacyAutoExposureMatcher {
val exposureEv = solver.nextExposureEv() ?: break
val frame = renderSample(exposureEv) ?: return@use null
if (!solver.submitCandidate(exposureEv, frame)) return@use null
val coordinatesMatched = solver.lastCandidateCoordinatesMatch()
solver.lastSample()?.let { sample ->
PLog.d(
TAG,
"Viewfinder brightness matching sample: " +
"exposureEv=${sample.exposureEv} " +
"matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " +
"matchRate=${sample.matchRate} " +
"meanPerceptualLightnessError=" +
"${sample.meanAbsolutePerceptualLightnessError} " +
"meanAbsoluteLog2Ratio=${sample.meanAbsoluteLog2Ratio} " +
"medianLog2Ratio=${sample.medianLog2Ratio} " +
"robustLog2Loss=${sample.robustLog2Loss} " +
"recommendedExposureCorrectionEv=" +
"${sample.recommendedExposureCorrectionEv} " +
"referenceWeightSum=${sample.referenceWeightSum} " +
"coordinateEdges=${sample.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${sample.coordinateMatchRate} " +
"coordinatesMatched=$coordinatesMatched",
)
}
}
val result = solver.result() ?: return@use null
if (result.best.coordinatesMatched == false) {
PLog.w(
TAG,
"Viewfinder brightness matching rejected: " +
"reason=COORDINATE_MISMATCH " +
"matchRate=${result.best.matchRate} " +
"requiredMatchRate=${result.requiredGridMatchRate} " +
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
"coordinatesMatched=${result.best.coordinatesMatched}",
)
return@use null
}
if (!solver.hasConverged()) {
PLog.w(
TAG,
"Viewfinder brightness matching did not reach the early-convergence " +
"target; using the highest-match-rate candidate: " +
"matchRate=${result.best.matchRate} " +
"requiredMatchRate=${result.requiredGridMatchRate} " +
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
"coordinatesMatched=${result.best.coordinatesMatched}",
)
}
val resultExposureEv = solver.resultExposureEv() ?: return@use null
PLog.i(
TAG,
"Viewfinder brightness matching result: " +
"exposureEv=${result.best.exposureEv} " +
"matchedCells=${result.best.matchedCellCount}/${result.best.validCellCount} " +
"matchRate=${result.best.matchRate} " +
"meanPerceptualLightnessError=" +
"${result.best.meanAbsolutePerceptualLightnessError} " +
"meanAbsoluteLog2Ratio=${result.best.meanAbsoluteLog2Ratio} " +
"medianLog2Ratio=${result.best.medianLog2Ratio} " +
"robustLog2Loss=${result.best.robustLog2Loss} " +
"recommendedExposureCorrectionEv=" +
"${result.best.recommendedExposureCorrectionEv} " +
"referenceWeightSum=${result.best.referenceWeightSum} " +
"coordinateEdges=${result.best.coordinateComparedEdgeCount} " +
"coordinateMatchRate=${result.best.coordinateMatchRate} " +
"coordinatesMatched=${result.best.coordinatesMatched} " +
"sampleCount=${result.evaluatedSampleCount} " +
"excludedShadowCells=${result.excludedShadowCellCount} " +
"excludedHighlightCells=${result.excludedHighlightCellCount} " +
"shadowWeightZeroLinear=${result.shadowWeightZeroLinear} " +
"highlightWeightZeroLinear=${result.highlightWeightZeroLinear} " +
"huberDeltaEv=${result.huberDeltaEv} " +
"perceptualLightnessTolerance=" +
"${result.perceptualLightnessTolerance} " +
"requiredGridMatchRate=${result.requiredGridMatchRate}",
"exposureEv=$resultExposureEv",
)
result.best.exposureEv
resultExposureEv
}
}
@@ -1,105 +1,24 @@
package com.hinnka.mycamera.raw
import kotlin.math.roundToInt
/** Lifecycle wrapper for the robust native solver derived from PhotonCamera 1.27.1. */
internal object RawLegacyAutoExposureNativeBridge {
init {
System.loadLibrary("my-native-lib")
}
data class Sample(
val exposureEv: Float,
val matchedCellCount: Int,
val validCellCount: Int,
val comparedCellCount: Int,
val matchRate: Float,
val meanAbsoluteLog2Ratio: Float,
val medianLog2Ratio: Float,
val robustLog2Loss: Float,
val referenceWeightSum: Float,
val recommendedExposureCorrectionEv: Float,
val meanAbsolutePerceptualLightnessError: Float,
val coordinateComparedEdgeCount: Int,
val coordinateMatchRate: Float,
val coordinatesMatched: Boolean?,
)
data class Result(
val best: Sample,
val evaluatedSampleCount: Int,
val excludedShadowCellCount: Int,
val excludedHighlightCellCount: Int,
val shadowWeightZeroLinear: Float,
val highlightWeightZeroLinear: Float,
val huberDeltaEv: Float,
val perceptualLightnessTolerance: Float,
val requiredGridMatchRate: Float,
)
data class HdrNetCurveSample(
val matchedCellCount: Int,
val validCellCount: Int,
val comparedCellCount: Int,
val matchRate: Float,
val meanAbsoluteLog2Ratio: Float,
val medianLog2Ratio: Float,
val robustLog2Loss: Float,
val referenceWeightSum: Float,
val recommendedExposureCorrectionEv: Float,
val centerErrorEv: Float,
val spanErrorEv: Float,
val curveSlopeError: Float,
val referenceP20Ev: Float,
val referenceP50Ev: Float,
val referenceP80Ev: Float,
val curveFitCellCount: Int,
val shortTargetCorrectionEv: Float,
val longTargetCorrectionEv: Float,
val meanAbsolutePerceptualLightnessError: Float,
val coordinateComparedEdgeCount: Int,
val coordinateMatchRate: Float,
val coordinatesMatched: Boolean?,
) {
val referenceSpanEv: Float
get() = referenceP80Ev - referenceP20Ev
val highlightTargetErrorEv: Float
get() = -shortTargetCorrectionEv
val shadowTargetErrorEv: Float
get() = -longTargetCorrectionEv
}
enum class HdrNetProbeAxis {
BASE,
SHORT_JACOBIAN,
LONG_JACOBIAN,
JOINT_NEWTON,
FALLBACK_SHORT,
}
data class HdrNetParameters(
val shortEv: Float,
val hdrRatioEv: Float,
val axis: HdrNetProbeAxis,
)
data class HdrNetResult(
val shortEv: Float,
val hdrRatioEv: Float,
val sample: HdrNetCurveSample,
val evaluatedCandidateCount: Int,
val converged: Boolean,
val usedOneDimensionalFallback: Boolean,
val jacobianNormalizedDeterminant: Float,
)
class Solver private constructor(
private var handle: Long,
) : AutoCloseable {
private var latestCoordinatesMatched: Boolean? = null
fun nextExposureEv(): Float? {
check(handle != 0L) { "Native exposure solver is closed" }
return nativeNextExposureEv(handle).takeIf { it.isFinite() }
@@ -107,18 +26,13 @@ internal object RawLegacyAutoExposureNativeBridge {
fun submitCandidate(exposureEv: Float, frame: RawLegacyExposurePreviewFrame): Boolean {
check(handle != 0L) { "Native exposure solver is closed" }
val submitted = nativeSubmitCandidate(
return nativeSubmitCandidate(
handle = handle,
exposureEv = exposureEv,
candidatePixels = frame.argbPixels,
width = frame.width,
height = frame.height,
)
if (submitted) {
latestCoordinatesMatched =
nativeGetLastSample(handle)?.toSample()?.coordinatesMatched
}
return submitted
}
fun submitCandidate(
@@ -131,18 +45,13 @@ internal object RawLegacyAutoExposureNativeBridge {
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows) {
return false
}
val submitted = nativeSubmitGridCandidate(
return nativeSubmitGridCandidate(
handle = handle,
exposureEv = exposureEv,
candidateDisplayLinearLumas = displayLinearLumas,
columns = columns,
rows = rows,
)
if (submitted) {
latestCoordinatesMatched =
nativeGetLastSample(handle)?.toSample()?.coordinatesMatched
}
return submitted
}
fun startHdrNetSolve(
@@ -157,12 +66,9 @@ internal object RawLegacyAutoExposureNativeBridge {
check(handle != 0L) { "Native exposure solver is closed" }
val values = nativeNextHdrNetParameters(handle) ?: return null
if (values.size != HDRNET_PARAMETER_VALUE_COUNT) return null
val axis = HdrNetProbeAxis.entries.getOrNull(values[2].roundToInt())
?: return null
return HdrNetParameters(
shortEv = values[0],
hdrRatioEv = values[1],
axis = axis,
).takeIf { it.shortEv.isFinite() && it.hdrRatioEv.isFinite() }
}
@@ -171,22 +77,19 @@ internal object RawLegacyAutoExposureNativeBridge {
displayLinearLumas: FloatArray,
columns: Int,
rows: Int,
): HdrNetCurveSample? {
): Boolean {
check(handle != 0L) { "Native exposure solver is closed" }
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows) {
return null
return false
}
val values = nativeSubmitHdrNetGridCandidate(
return nativeSubmitHdrNetGridCandidate(
handle = handle,
shortEv = parameters.shortEv,
hdrRatioEv = parameters.hdrRatioEv,
candidateDisplayLinearLumas = displayLinearLumas,
columns = columns,
rows = rows,
) ?: return null
return values.toHdrNetCurveSample()?.also {
latestCoordinatesMatched = it.coordinatesMatched
}
)
}
fun hdrNetResult(): HdrNetResult? {
@@ -196,12 +99,7 @@ internal object RawLegacyAutoExposureNativeBridge {
return HdrNetResult(
shortEv = values[0],
hdrRatioEv = values[1],
sample = values.toHdrNetCurveSample(offset = 2) ?: return null,
evaluatedCandidateCount = values[24].roundToInt(),
converged = values[25] != 0f,
usedOneDimensionalFallback = values[26] != 0f,
jacobianNormalizedDeterminant = values[27],
)
).takeIf { it.shortEv.isFinite() && it.hdrRatioEv.isFinite() }
}
fun configureExposureBounds(minimumEv: Float, maximumEv: Float): Boolean {
@@ -209,46 +107,15 @@ internal object RawLegacyAutoExposureNativeBridge {
return nativeConfigureExposureBounds(handle, minimumEv, maximumEv)
}
fun hasConverged(): Boolean {
fun resultExposureEv(): Float? {
check(handle != 0L) { "Native exposure solver is closed" }
return nativeHasConverged(handle)
}
/**
* Returns whether the latest candidate uses the same spatial coordinates as the
* viewfinder reference, or null when the scene has too little local contrast to decide.
*/
fun lastCandidateCoordinatesMatch(): Boolean? = latestCoordinatesMatched
fun lastSample(): Sample? {
check(handle != 0L) { "Native exposure solver is closed" }
return nativeGetLastSample(handle)?.toSample()?.also {
latestCoordinatesMatched = it.coordinatesMatched
}
}
fun result(): Result? {
check(handle != 0L) { "Native exposure solver is closed" }
val values = nativeGetResult(handle) ?: return null
if (values.size != RESULT_VALUE_COUNT) return null
return Result(
best = values.toSample() ?: return null,
evaluatedSampleCount = values[14].roundToInt(),
excludedShadowCellCount = values[15].roundToInt(),
excludedHighlightCellCount = values[16].roundToInt(),
shadowWeightZeroLinear = values[17],
highlightWeightZeroLinear = values[18],
huberDeltaEv = values[19],
perceptualLightnessTolerance = values[20],
requiredGridMatchRate = values[21],
)
return nativeGetResultExposureEv(handle).takeIf { it.isFinite() }
}
override fun close() {
val nativeHandle = handle
if (nativeHandle == 0L) return
handle = 0L
latestCoordinatesMatched = null
nativeDestroy(nativeHandle)
}
@@ -265,70 +132,6 @@ internal object RawLegacyAutoExposureNativeBridge {
}
}
private fun FloatArray.toSample(): Sample? {
if (size < SAMPLE_VALUE_COUNT) return null
return Sample(
exposureEv = this[0],
matchedCellCount = this[1].roundToInt(),
validCellCount = this[2].roundToInt(),
comparedCellCount = this[3].roundToInt(),
matchRate = this[4],
meanAbsoluteLog2Ratio = this[5],
medianLog2Ratio = this[6],
robustLog2Loss = this[7],
referenceWeightSum = this[8],
recommendedExposureCorrectionEv = this[9],
meanAbsolutePerceptualLightnessError = this[10],
coordinateComparedEdgeCount = this[11].roundToInt(),
coordinateMatchRate = this[12],
coordinatesMatched = this[13].toCoordinateMatch(),
)
}
private fun FloatArray.toHdrNetCurveSample(offset: Int = 0): HdrNetCurveSample? {
if (size < offset + HDRNET_CURVE_SAMPLE_VALUE_COUNT) return null
return HdrNetCurveSample(
matchedCellCount = this[offset].roundToInt(),
validCellCount = this[offset + 1].roundToInt(),
comparedCellCount = this[offset + 2].roundToInt(),
matchRate = this[offset + 3],
meanAbsoluteLog2Ratio = this[offset + 4],
medianLog2Ratio = this[offset + 5],
robustLog2Loss = this[offset + 6],
referenceWeightSum = this[offset + 7],
recommendedExposureCorrectionEv = this[offset + 8],
centerErrorEv = this[offset + 9],
spanErrorEv = this[offset + 10],
curveSlopeError = this[offset + 11],
referenceP20Ev = this[offset + 12],
referenceP50Ev = this[offset + 13],
referenceP80Ev = this[offset + 14],
curveFitCellCount = this[offset + 15].roundToInt(),
shortTargetCorrectionEv = this[offset + 16],
longTargetCorrectionEv = this[offset + 17],
meanAbsolutePerceptualLightnessError = this[offset + 18],
coordinateComparedEdgeCount = this[offset + 19].roundToInt(),
coordinateMatchRate = this[offset + 20],
coordinatesMatched = this[offset + 21].toCoordinateMatch(),
).takeIf {
it.matchRate.isFinite() &&
it.meanAbsolutePerceptualLightnessError.isFinite() &&
it.coordinateMatchRate.isFinite() &&
it.meanAbsoluteLog2Ratio.isFinite() &&
it.medianLog2Ratio.isFinite() &&
it.robustLog2Loss.isFinite() &&
it.referenceWeightSum.isFinite() &&
it.recommendedExposureCorrectionEv.isFinite()
}
}
private fun Float.toCoordinateMatch(): Boolean? = when (roundToInt()) {
-1 -> null
0 -> false
1 -> true
else -> null
}
private external fun nativeCreate(
referencePixels: IntArray,
portraitPriorityWeights: FloatArray?,
@@ -369,7 +172,7 @@ internal object RawLegacyAutoExposureNativeBridge {
candidateDisplayLinearLumas: FloatArray,
columns: Int,
rows: Int,
): FloatArray?
): Boolean
private external fun nativeGetHdrNetResult(handle: Long): FloatArray?
@@ -379,15 +182,9 @@ internal object RawLegacyAutoExposureNativeBridge {
maximumEv: Float,
): Boolean
private external fun nativeHasConverged(handle: Long): Boolean
private external fun nativeGetLastSample(handle: Long): FloatArray?
private external fun nativeGetResult(handle: Long): FloatArray?
private external fun nativeGetResultExposureEv(handle: Long): Float
private external fun nativeDestroy(handle: Long)
private const val SAMPLE_VALUE_COUNT = 14
private const val RESULT_VALUE_COUNT = 22
private const val HDRNET_CURVE_SAMPLE_VALUE_COUNT = 22
private const val HDRNET_PARAMETER_VALUE_COUNT = 3
private const val HDRNET_RESULT_VALUE_COUNT = 28
private const val HDRNET_PARAMETER_VALUE_COUNT = 2
private const val HDRNET_RESULT_VALUE_COUNT = 2
}
@@ -392,8 +392,8 @@ internal abstract class RawRenderingEngineToneAlgorithm(
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(program, "uGlobalUvScale"),
input.width.toFloat() / input.fullImageWidth.coerceAtLeast(1),
input.height.toFloat() / input.fullImageHeight.coerceAtLeast(1),
input.globalWidth.toFloat() / input.fullImageWidth.coerceAtLeast(1),
input.globalHeight.toFloat() / input.fullImageHeight.coerceAtLeast(1),
)
if (!input.colorEngine.isHncs) {
GLES30.glUniformMatrix3fv(
@@ -99,7 +99,7 @@ class PhotonCoreImagingTuningTest {
assertEquals(4f, normalized.strength, 0f)
assertEquals(0f, normalized.dynamicHighlightStrength, 0f)
assertEquals(true, normalized.isActive)
assertEquals(false, normalized.isActive)
}
@Test
@@ -115,7 +115,7 @@ class PhotonCoreImagingTuningTest {
assertEquals(true, tuning.dehaze.enabled)
assertEquals(1f, tuning.dehaze.strength, 0f)
assertEquals(1f, tuning.dehaze.dynamicHighlightStrength, 0f)
assertEquals(true, tuning.dehaze.isActive)
assertEquals(false, tuning.dehaze.isActive)
}
@Test
@@ -23,8 +23,6 @@ class DngHdrNetViewfinderGridTest {
)
val neutralBaselinePlan = checkNotNull(
DngPhotonProfileGainTableGenerator.hdrNetPlan(
sourceWidth = 4_032,
sourceHeight = 3_024,
rendererBaselineExposureEv = 0f,
hdrRatio = 2f,
sourceToShortGain = 1f,
@@ -32,8 +30,6 @@ class DngHdrNetViewfinderGridTest {
)
val brightBaselinePlan = checkNotNull(
DngPhotonProfileGainTableGenerator.hdrNetPlan(
sourceWidth = 4_032,
sourceHeight = 3_024,
rendererBaselineExposureEv = 3f,
hdrRatio = 2f,
sourceToShortGain = 1f,
@@ -60,8 +56,8 @@ class DngHdrNetViewfinderGridTest {
val brightBaselineGrid = checkNotNull(grids.second)
assertEquals(
DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH *
DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_HEIGHT,
DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH *
DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT,
neutralGrid.size,
)
neutralGrid.forEach { assertEquals(0.249999f, it, 2e-6f) }
@@ -57,6 +57,31 @@ class DngProfileGainTableMapTest {
assertEquals(3_158_096, payload.size)
}
@Test
fun rebasingRendererBaselinePreservesEffectiveInputWeights() {
val map = testMap(
mapPointsN = 2,
gamma = 1f,
gains = floatArrayOf(1f, 1f),
)
val rebased = requireNotNull(
map.rebasedForRendererBaseline(
fromTotalBaselineExposureEv = 1f,
toTotalBaselineExposureEv = 3f,
),
)
map.mapInputWeights.indices.forEach { index ->
val originalEffectiveWeight = map.mapInputWeights[index] *
DngBaselineExposure.exactGain(1f)
val rebasedEffectiveWeight = rebased.mapInputWeights[index] *
DngBaselineExposure.exactGain(3f)
assertEquals(originalEffectiveWeight, rebasedEffectiveWeight, 1e-6f)
}
assertEquals(map.gains, rebased.gains)
}
private fun testMap(
mapPointsN: Int,
gamma: Float,