feat: photon hdr & legacy LL HDR
This commit is contained in:
1 parent
8556733d8e
commit
b6595a06f3
18 files changed
+827
-193
No files matched your search
@@ -165,6 +165,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
jint source_grid_width, jint source_grid_height, jint source_grid_depth,
|
||||
jint coefficient_count, jint output_grid_width, jint output_grid_height,
|
||||
jint point_count, jfloat hdr_ratio, jfloat source_to_short_gain,
|
||||
jfloat renderer_baseline_gain,
|
||||
jfloat render_min_gain, jfloat render_max_gain,
|
||||
jfloat render_max_gain_blend_threshold,
|
||||
jfloat min_table_gain, jfloat max_table_gain,
|
||||
@@ -181,6 +182,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
output_grid_height <= 0 || point_count <= 1 ||
|
||||
!std::isfinite(hdr_ratio) || hdr_ratio < 1.0f ||
|
||||
!std::isfinite(source_to_short_gain) || source_to_short_gain <= 0.0f ||
|
||||
!std::isfinite(renderer_baseline_gain) || renderer_baseline_gain <= 0.0f ||
|
||||
!std::isfinite(render_min_gain) || render_min_gain <= 0.0f ||
|
||||
!std::isfinite(render_max_gain) ||
|
||||
render_max_gain < render_min_gain ||
|
||||
@@ -318,13 +320,13 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
short_intensity * render_gain, 0.0f, 1.0f);
|
||||
const float pre_curve_target = InputForAcrOutput(
|
||||
target_luma, acr_curve.data(), acr_curve_count);
|
||||
// The N axis is final-short intensity = stored source * baselineGain * sourceToShortGain.
|
||||
// BaselineExposure restores the normalized source in both the table coordinate and final
|
||||
// rendering, so the corresponding restored-source denominator is short / shortGain.
|
||||
const float baseline_restored_source_intensity =
|
||||
short_intensity / source_to_short_gain;
|
||||
// The N axis is final-short intensity = stored source * sourceToShortGain. PGTM itself is
|
||||
// applied before the renderer's BaselineExposure, so divide by the source value after that
|
||||
// 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(
|
||||
pre_curve_target / baseline_restored_source_intensity, min_table_gain,
|
||||
pre_curve_target / baseline_applied_source_intensity, min_table_gain,
|
||||
max_table_gain);
|
||||
if (diagnostic_mode >= 0) {
|
||||
const float mask =
|
||||
|
||||
@@ -263,6 +263,16 @@ object ACR3Curve {
|
||||
|
||||
fun samples(): FloatArray = ACR3_DEFAULT_CURVE
|
||||
|
||||
/** Returns the linearly interpolated ACR3 output for a normalized linear input. */
|
||||
internal fun outputForInput(input: Float): Float {
|
||||
val position = input.coerceIn(0f, 1f) * ACR3_DEFAULT_CURVE.lastIndex
|
||||
val lowerIndex = position.toInt().coerceIn(0, ACR3_DEFAULT_CURVE.lastIndex)
|
||||
val upperIndex = (lowerIndex + 1).coerceAtMost(ACR3_DEFAULT_CURVE.lastIndex)
|
||||
val amount = position - lowerIndex
|
||||
return ACR3_DEFAULT_CURVE[lowerIndex] +
|
||||
(ACR3_DEFAULT_CURVE[upperIndex] - ACR3_DEFAULT_CURVE[lowerIndex]) * amount
|
||||
}
|
||||
|
||||
/** Returns the input whose linearly interpolated ACR3 output equals [output]. */
|
||||
internal fun inputForOutput(output: Float): Float {
|
||||
val target = output.coerceIn(ACR3_DEFAULT_CURVE.first(), ACR3_DEFAULT_CURVE.last())
|
||||
|
||||
@@ -17,8 +17,9 @@ object DngBaselineExposure {
|
||||
* Resolves ownership of the BaselineExposure written for a captured RAW.
|
||||
*
|
||||
* [sourceBaselineEv] preserves source-domain normalization such as a multi-frame stack that
|
||||
* was normalized to its ultra-short frame. The classic viewfinder matcher returns an offset
|
||||
* relative to that source baseline. Photon HDR never supplies this offset.
|
||||
* was normalized to its ultra-short frame. The legacy viewfinder matcher returns the display
|
||||
* exposure offset relative to that source baseline for both classic AE and Photon HDR. Photon
|
||||
* HDR then uses the written total as its reproducible global-exposure anchor.
|
||||
*/
|
||||
fun resolveCaptureBaseline(
|
||||
sourceBaselineEv: Float,
|
||||
|
||||
@@ -33,6 +33,7 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
pointCount = plan.pointCount,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
sourceToShortGain = plan.sourceToShortGain,
|
||||
rendererBaselineGain = plan.rendererBaselineGain,
|
||||
renderMinGain = renderMinGain,
|
||||
renderMaxGain = renderMaxGain,
|
||||
renderMaxGainBlendThreshold = renderMaxGainBlendThreshold,
|
||||
@@ -61,6 +62,7 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
pointCount: Int,
|
||||
hdrRatio: Float,
|
||||
sourceToShortGain: Float,
|
||||
rendererBaselineGain: Float,
|
||||
renderMinGain: Float,
|
||||
renderMaxGain: Float,
|
||||
renderMaxGainBlendThreshold: Float,
|
||||
|
||||
@@ -13,6 +13,7 @@ import org.tensorflow.lite.Interpreter
|
||||
import org.tensorflow.lite.support.common.FileUtil
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.floor
|
||||
@@ -950,7 +951,6 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform float uBaselineGain;
|
||||
uniform float uSourceToShortGain;
|
||||
uniform float uHdrRatio;
|
||||
uniform int uWarpCount;
|
||||
@@ -1045,7 +1045,8 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
// The demosaic texture is un-white-balanced camera RGB. The render-stage
|
||||
// camera-to-working matrix includes the selected camera white, matching
|
||||
// MGC's uCcm contract without applying WB a second time.
|
||||
vec3 cameraRgb = storedCameraRgb * uBaselineGain * uSourceToShortGain;
|
||||
// BaselineExposure is the display/middle-gray target, not an HDRNet input.
|
||||
vec3 cameraRgb = storedCameraRgb * uSourceToShortGain;
|
||||
// MGC clamps only positive overrange before box downsampling. Negative
|
||||
// samples remain in the average and are clamped by the final box pass.
|
||||
vec3 profileRgb = min(uColorCorrectionMatrix * cameraRgb, vec3(1.0));
|
||||
@@ -1356,6 +1357,11 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
}
|
||||
|
||||
internal class DngPhotonProfileGainTableAlgorithm {
|
||||
enum class Mode {
|
||||
HDR_NET,
|
||||
LOCAL_LAPLACIAN,
|
||||
}
|
||||
|
||||
fun interface StreamingRawUploader {
|
||||
fun upload(
|
||||
buffer: ByteBuffer,
|
||||
@@ -1366,6 +1372,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
}
|
||||
|
||||
data class Input(
|
||||
val mode: Mode,
|
||||
val context: Context,
|
||||
val linearRgbTextureId: Int,
|
||||
val rawTextureId: Int,
|
||||
@@ -1381,7 +1388,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val samplesPerPixel: Int,
|
||||
val metadata: RawMetadata,
|
||||
val statsBounds: Rect?,
|
||||
/** BaselineExposure that restores the stored multi-frame RAW normalization. */
|
||||
/** DNG BaselineExposure used only by the robust exposure target and final DNG render. */
|
||||
val sourceBaselineExposureEv: Float,
|
||||
/** Total BaselineExposure used by DNG ProfileGainTableMap lookup. */
|
||||
val rendererBaselineExposureEv: Float,
|
||||
@@ -1401,31 +1408,74 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val releaseStreamingRawTexture: () -> Unit = {},
|
||||
)
|
||||
|
||||
data class Output(val map: DngProfileGainTableMap)
|
||||
data class Output(
|
||||
val map: DngProfileGainTableMap,
|
||||
val hdrRatio: Float? = null,
|
||||
val sourceToShortGain: Float? = null,
|
||||
val hdrNetExposureAdjustmentEv: Float,
|
||||
val hdrNetExposureTargetEv: Float? = null,
|
||||
val hdrNetExposureEvaluation: RawHdrNetExposureEvaluation? = null,
|
||||
)
|
||||
|
||||
private data class GpuPhotonGainCurves(
|
||||
val gains: FloatArray,
|
||||
val textureId: Int,
|
||||
)
|
||||
|
||||
private data class HdrNetInferenceCandidate(
|
||||
val plan: HdrNetProfileGainTablePlan,
|
||||
val coefficients: FloatArray,
|
||||
val adjustmentEv: Float,
|
||||
)
|
||||
|
||||
private var cellSamplesProgram = 0
|
||||
private val photonPrograms = IntArray(DngPhotonLocalToneMapGpuShaders.Pass.entries.size)
|
||||
private var hdrNetInputProgram = 0
|
||||
private var hdrNetInterpreter: Interpreter? = null
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (hdrNetInputProgram == 0) {
|
||||
hdrNetInputProgram = RawGlesProgram.compileCompute(
|
||||
DngPhotonProfileGainTableInputShader.HDRNET_INPUT,
|
||||
"DNG_HDRNET_INPUT",
|
||||
)
|
||||
fun initialize(mode: Mode): Boolean {
|
||||
return when (mode) {
|
||||
Mode.HDR_NET -> {
|
||||
if (hdrNetInputProgram == 0) {
|
||||
hdrNetInputProgram = RawGlesProgram.compileCompute(
|
||||
DngPhotonProfileGainTableInputShader.HDRNET_INPUT,
|
||||
"DNG_HDRNET_INPUT",
|
||||
)
|
||||
}
|
||||
hdrNetInputProgram != 0
|
||||
}
|
||||
Mode.LOCAL_LAPLACIAN -> {
|
||||
if (cellSamplesProgram == 0) {
|
||||
cellSamplesProgram = RawGlesProgram.compileCompute(
|
||||
DngPhotonProfileGainTableInputShader.CELL_SAMPLES,
|
||||
"DNG_PGTM_CELL_SAMPLES",
|
||||
)
|
||||
}
|
||||
DngPhotonLocalToneMapGpuShaders.sources.forEachIndexed { index, source ->
|
||||
if (photonPrograms[index] == 0) {
|
||||
val pass = DngPhotonLocalToneMapGpuShaders.Pass.entries[index]
|
||||
photonPrograms[index] = RawGlesProgram.compileCompute(
|
||||
source,
|
||||
"DNG_PHOTON_PGTM_${pass.name}",
|
||||
)
|
||||
}
|
||||
}
|
||||
cellSamplesProgram != 0 && photonPrograms.all { it != 0 }
|
||||
}
|
||||
}
|
||||
return hdrNetInputProgram != 0
|
||||
}
|
||||
|
||||
fun execute(input: Input): Output? {
|
||||
if (!initialize()) return null
|
||||
return generate(input)?.let(::Output)
|
||||
if (!initialize(input.mode)) return null
|
||||
return when (input.mode) {
|
||||
Mode.HDR_NET -> generate(input)
|
||||
Mode.LOCAL_LAPLACIAN -> generateLocalLaplacian(input)?.let { map ->
|
||||
Output(
|
||||
map = map,
|
||||
hdrNetExposureAdjustmentEv = 0f,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
@@ -1441,7 +1491,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
private fun generate(input: Input): DngProfileGainTableMap? {
|
||||
private fun generate(input: Input): Output? {
|
||||
val linearRgbTextureId = input.linearRgbTextureId
|
||||
val width = input.width
|
||||
val height = input.height
|
||||
@@ -1479,7 +1529,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
extentH = stage3Bounds.width().toDouble() / width.toDouble(),
|
||||
extentV = stage3Bounds.height().toDouble() / height.toDouble(),
|
||||
)
|
||||
val plan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
val basePlan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
sourceBaselineExposureEv = input.sourceBaselineExposureEv,
|
||||
@@ -1588,68 +1638,134 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
RawToneMappingGl.transposeMatrix3x3(safeColorCorrectionMatrix),
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uBaselineGain"),
|
||||
plan.sourceBaselineGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"),
|
||||
plan.sourceToShortGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"),
|
||||
plan.hdrRatio,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uWarpCount"),
|
||||
activeWarpParameters.size / 8,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
),
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("prepare HDRNet input")
|
||||
val inputReadyNs = System.nanoTime()
|
||||
val baseShortGain = basePlan.sourceToShortGain
|
||||
val baseLongGain = baseShortGain * basePlan.hdrRatio
|
||||
val exposureTargetEv = input.sourceBaselineExposureEv
|
||||
var totalInputNs = 0L
|
||||
var totalInferenceNs = 0L
|
||||
var baseCandidate: HdrNetInferenceCandidate? = null
|
||||
var exposureSourceLumaByCell: FloatArray? = null
|
||||
|
||||
val inputFloats = readFloatStorageBuffer(
|
||||
bufferId = bufferIds[0],
|
||||
floatCount = inputFloatCount,
|
||||
label = "HDRNet input",
|
||||
) ?: return null
|
||||
if (inputFloats.any { !it.isFinite() }) {
|
||||
PLog.e(TAG, "HDRNet input contains a non-finite value")
|
||||
return null
|
||||
fun runCandidate(adjustmentEv: Float): Pair<HdrNetInferenceCandidate, FloatArray>? {
|
||||
// This solve moves the overall exposure anchor. Dynamic range remains the ML AE
|
||||
// result, so short and long must receive the same gain on every candidate.
|
||||
val adjustmentGain = 2.0f.pow(adjustmentEv)
|
||||
val shortGain = baseShortGain * adjustmentGain
|
||||
val longGain = baseLongGain * adjustmentGain
|
||||
if (!shortGain.isFinite() || shortGain <= 0f ||
|
||||
!longGain.isFinite() || longGain < shortGain
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val candidatePlan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
sourceBaselineExposureEv = input.sourceBaselineExposureEv,
|
||||
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
|
||||
hdrRatio = basePlan.hdrRatio,
|
||||
sourceToShortGain = shortGain,
|
||||
diagnosticBand = DngPgtmDiagnostic.activeBandForSource(
|
||||
"$TAG HDRNet capture",
|
||||
),
|
||||
samplingArea = samplingArea,
|
||||
) ?: 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])
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_RGB_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, linearRgbTextureId)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"),
|
||||
candidatePlan.sourceToShortGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"),
|
||||
candidatePlan.hdrRatio,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
),
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("prepare HDRNet input")
|
||||
val inputFloats = readFloatStorageBuffer(
|
||||
bufferId = bufferIds[0],
|
||||
floatCount = inputFloatCount,
|
||||
label = "HDRNet input",
|
||||
) ?: return null
|
||||
if (inputFloats.any { !it.isFinite() }) {
|
||||
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,
|
||||
)
|
||||
val candidateSourceLumaByCell = exposureSourceLumaByCell
|
||||
?: DngPhotonProfileGainTableGenerator.hdrNetExposureSourceLumaByCell(
|
||||
plan = candidatePlan,
|
||||
modelInput = inputFloats,
|
||||
)?.also { exposureSourceLumaByCell = it }
|
||||
?: return null
|
||||
|
||||
val modelInput = ByteBuffer.allocateDirect(inputFloats.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
modelInput.asFloatBuffer().put(inputFloats)
|
||||
modelInput.rewind()
|
||||
val modelOutput = ByteBuffer.allocateDirect(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT * Float.SIZE_BYTES,
|
||||
).order(ByteOrder.nativeOrder())
|
||||
val inferenceStartNs = System.nanoTime()
|
||||
interpreter.run(modelInput, modelOutput)
|
||||
totalInferenceNs += System.nanoTime() - inferenceStartNs
|
||||
modelOutput.rewind()
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutput.asFloatBuffer().get(coefficients)
|
||||
logHdrNetOutputContract(coefficients, candidatePlan.hdrRatio)
|
||||
val effectiveExposureEvs =
|
||||
DngPhotonProfileGainTableGenerator.hdrNetEffectiveExposureEvs(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
sourceLumaByCell = candidateSourceLumaByCell,
|
||||
) ?: return null
|
||||
return HdrNetInferenceCandidate(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
adjustmentEv = adjustmentEv,
|
||||
).also { candidate ->
|
||||
if (abs(adjustmentEv) < 1e-6f) baseCandidate = candidate
|
||||
} to effectiveExposureEvs
|
||||
}
|
||||
logHdrNetInputContract(
|
||||
input = input,
|
||||
plan = plan,
|
||||
colorCorrectionMatrix = safeColorCorrectionMatrix,
|
||||
values = inputFloats,
|
||||
|
||||
val exposureResult = RawLegacyAutoExposureMatcher.solveHdrNetExposure(
|
||||
targetExposureEv = exposureTargetEv,
|
||||
maxAdjustmentEv = HDRNET_EXPOSURE_MAX_ADJUSTMENT_EV,
|
||||
evaluateCandidate = ::runCandidate,
|
||||
)
|
||||
val modelInput = ByteBuffer.allocateDirect(inputFloats.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
modelInput.asFloatBuffer().put(inputFloats)
|
||||
modelInput.rewind()
|
||||
val modelOutput = ByteBuffer.allocateDirect(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT * Float.SIZE_BYTES,
|
||||
).order(ByteOrder.nativeOrder())
|
||||
val inferenceStartNs = System.nanoTime()
|
||||
interpreter.run(modelInput, modelOutput)
|
||||
val inferenceReadyNs = System.nanoTime()
|
||||
modelOutput.rewind()
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutput.asFloatBuffer().get(coefficients)
|
||||
logHdrNetOutputContract(coefficients, plan.hdrRatio)
|
||||
val selectedCandidate = exposureResult?.payload
|
||||
?: baseCandidate
|
||||
?: runCandidate(0f)?.first
|
||||
?: return null
|
||||
val plan = selectedCandidate.plan
|
||||
val coefficients = selectedCandidate.coefficients
|
||||
val pgtmStartNs = System.nanoTime()
|
||||
val map = DngPhotonProfileGainTableGenerator.mapFromHdrNetCoefficients(
|
||||
plan = plan,
|
||||
@@ -1665,6 +1781,14 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
throw error
|
||||
}
|
||||
val totalReadyNs = System.nanoTime()
|
||||
val retainedSourceLumas = exposureSourceLumaByCell
|
||||
?.filter { it.isFinite() }
|
||||
?.sorted()
|
||||
.orEmpty()
|
||||
val sourceLumaMedian = retainedSourceLumas.takeIf { it.isNotEmpty() }?.let {
|
||||
val upper = it.size / 2
|
||||
if (it.size % 2 == 0) (it[upper - 1] + it[upper]) * 0.5f else it[upper]
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet PGTM ready: input=${DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH}x" +
|
||||
@@ -1674,7 +1798,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"${DngPhotonProfileGainTableGenerator.HDRNET_GRID_DEPTH} " +
|
||||
"pgtmGrid=${plan.grid.mapPointsH}x${plan.grid.mapPointsV} " +
|
||||
"hdrRatio=${plan.hdrRatio} " +
|
||||
"sourceBaselineGain=${plan.sourceBaselineGain} " +
|
||||
"baselineTargetGain=${plan.sourceBaselineGain} " +
|
||||
"rendererBaselineGain=${plan.rendererBaselineGain} " +
|
||||
"sourceToShortGain=${plan.sourceToShortGain} " +
|
||||
"hdrNetTotalInputGain=${plan.hdrNetInputScale} " +
|
||||
@@ -1687,18 +1811,44 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"modelInputHueSat=false " +
|
||||
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
|
||||
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
|
||||
"baselineAppliedToHdrNetInput=true " +
|
||||
"baselineRole=MULTIFRAME_SOURCE_NORMALIZATION_RESTORE " +
|
||||
"mapInputDomain=FINAL_SHORT_RIMM_PXL_INTENSITY_AFTER_SOURCE_RESTORE " +
|
||||
"pgtmGainDenominator=BASELINE_RESTORED_SOURCE_PXL_INTENSITY " +
|
||||
"baselineAppliedToHdrNetInput=false " +
|
||||
"baselineRole=ROBUST_EXPOSURE_TARGET_AND_DNG_RENDER_ONLY " +
|
||||
"mapInputDomain=RAW_X_FINAL_SHORT_GAIN " +
|
||||
"pgtmBaselineCancelledFromInputCoordinate=true " +
|
||||
"exposureSolve=${exposureResult != null} " +
|
||||
"exposureMetric=ROBUST_LOG2_ACR3_INVERSE_H_OVER_ACTUAL_SOURCE_LUMA " +
|
||||
"exposureSourceDomain=MODEL_RGB_16X12_CENTRAL_LUMA_POPULATION " +
|
||||
"exposureSourceSamples=${retainedSourceLumas.size} " +
|
||||
"exposureSourceLumaMin=${retainedSourceLumas.firstOrNull()} " +
|
||||
"exposureSourceLumaMedian=$sourceLumaMedian " +
|
||||
"exposureSourceLumaMax=${retainedSourceLumas.lastOrNull()} " +
|
||||
"exposureTargetEv=$exposureTargetEv " +
|
||||
"exposureTargetGain=${basePlan.sourceBaselineGain} " +
|
||||
"exposureAdjustmentMode=COMMON_SHORT_LONG_GAIN " +
|
||||
"exposureBaseShortGain=$baseShortGain " +
|
||||
"exposureBaseLongGain=$baseLongGain " +
|
||||
"exposureBaseHdrRatio=${basePlan.hdrRatio} " +
|
||||
"exposureAdjustmentEv=${selectedCandidate.adjustmentEv} " +
|
||||
"exposureFinalHdrRatio=${plan.hdrRatio} " +
|
||||
"exposureHdrRatioInvariantError=${plan.hdrRatio - basePlan.hdrRatio} " +
|
||||
"exposureMedianErrorEv=" +
|
||||
"${exposureResult?.evaluation?.medianExposureErrorEv} " +
|
||||
"exposureScore=${exposureResult?.evaluation?.score} " +
|
||||
"stage3Source=${width}x$height linearRgbBounds=$hdrNetSourceBounds " +
|
||||
"processingBounds=$stage3Bounds samplingArea=$samplingArea " +
|
||||
"inputMs=${(inputReadyNs - totalStartNs) / 1_000_000f} " +
|
||||
"inferenceMs=${(inferenceReadyNs - inferenceStartNs) / 1_000_000f} " +
|
||||
"inputMs=${totalInputNs / 1_000_000f} " +
|
||||
"inferenceMs=${totalInferenceNs / 1_000_000f} " +
|
||||
"pgtmMs=${(pgtmReadyNs - pgtmStartNs) / 1_000_000f} " +
|
||||
"totalMs=${(totalReadyNs - totalStartNs) / 1_000_000f}",
|
||||
)
|
||||
return map
|
||||
return Output(
|
||||
map = map,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
sourceToShortGain = plan.sourceToShortGain,
|
||||
hdrNetExposureAdjustmentEv = selectedCandidate.adjustmentEv,
|
||||
hdrNetExposureTargetEv = exposureTargetEv,
|
||||
hdrNetExposureEvaluation = exposureResult?.evaluation,
|
||||
)
|
||||
} catch (error: Throwable) {
|
||||
PLog.e(TAG, "HDRNet ProfileGainTableMap generation failed", error)
|
||||
return null
|
||||
@@ -1715,8 +1865,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
private fun generateLegacy(input: Input): DngProfileGainTableMap? {
|
||||
private fun generateLocalLaplacian(input: Input): DngProfileGainTableMap? {
|
||||
val rawTextureId = input.rawTextureId
|
||||
val streamingRawData = input.streamingRawData
|
||||
val streamingRowStride = input.streamingRowStride
|
||||
@@ -2027,7 +2176,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
2.0f.pow(photonPlan.parameters.preToneMapExposureBoostEv)
|
||||
PLog.d(
|
||||
TAG,
|
||||
"GPU Photon HDR prepared: size=${width}x$height " +
|
||||
"GPU Local Laplacian PGTM prepared: size=${width}x$height " +
|
||||
"source=${rawTextureWidth}x$rawTextureHeight " +
|
||||
"streaming=$streamingInput sampleTiles=${streamingTiles.size} " +
|
||||
"statsBounds=$safeStatsBounds " +
|
||||
@@ -3256,7 +3405,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"whiteBalanceDomain=BAKED_IN_COLOR_CORRECTION_MATRIX " +
|
||||
"modelInputChannels=R_G_B_LONG_LUMA " +
|
||||
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED hueSat=false " +
|
||||
"sourceBaselineGain=${plan.sourceBaselineGain} " +
|
||||
"baselineTargetGain=${plan.sourceBaselineGain} " +
|
||||
"baselineAppliedToModelInput=false " +
|
||||
"rendererBaselineGain=${plan.rendererBaselineGain} " +
|
||||
"sourceToShort=${plan.sourceToShortGain} " +
|
||||
"hdrRatio=${plan.hdrRatio} mapWeights=${plan.mapInputWeights.contentToString()} " +
|
||||
@@ -3362,6 +3512,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
private companion object {
|
||||
const val TAG = "PhotonPGTM"
|
||||
const val HDRNET_MODEL_ASSET = "mgc_hdrnet/hdrnet_coefficients.tflite"
|
||||
const val HDRNET_EXPOSURE_MAX_ADJUSTMENT_EV = 4f
|
||||
const val LINEAR_RGB_TEXTURE_UNIT = 0
|
||||
const val RAW_TEXTURE_UNIT = 0
|
||||
const val LENS_SHADING_TEXTURE_UNIT = 1
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
|
||||
/** Builds a DNG ProfileGainTableMap2 from MGC HDRNet's bilateral affine coefficient grid. */
|
||||
@@ -107,11 +108,11 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
/**
|
||||
* Plans a 64 x 48 PGTM grid resampled from MGC HDRNet's fixed 16 x 12 coefficient grid.
|
||||
*
|
||||
* HDRNet runs in the final-short-exposure linear domain. In this pipeline BaselineExposure
|
||||
* restores a multi-frame source normalized to a shorter exposure; it is not an additional
|
||||
* appearance gain. The desired effective N-axis scale is
|
||||
* `sourceBaselineGain * sourceToShortGain`; the stored weights account for the renderer's
|
||||
* total BaselineExposure so Adobe reconstructs exactly that same final-short domain.
|
||||
* HDRNet runs in the final-short-exposure linear domain: `RAW * sourceToShortGain`.
|
||||
* BaselineExposure supplies only the robust global-exposure target and final DNG exposure; it
|
||||
* is not part of the model tensor. A conforming renderer folds its total BaselineExposure into
|
||||
* the ProfileGainTableMap N coordinate, so the stored weights cancel that renderer gain and
|
||||
* reconstruct the same `RAW * sourceToShortGain` coordinate used to build the table.
|
||||
*/
|
||||
fun hdrNetPlan(
|
||||
sourceWidth: Int,
|
||||
@@ -138,12 +139,10 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
) {
|
||||
return null
|
||||
}
|
||||
// The model sees the fused source after restoring only its physical normalization.
|
||||
// Adobe evaluates MapInputWeights with TotalBaselineExposure, which can additionally
|
||||
// include a profile offset. Remove only that extra renderer factor from the stored
|
||||
// weights so the table N axis and HDRNet input remain in the identical exposure domain.
|
||||
val mapInputScale =
|
||||
sourceToShortGain * sourceBaselineGain / rendererBaselineGain
|
||||
// Adobe evaluates MapInputWeights after applying TotalBaselineExposure (including any
|
||||
// profile offset). Cancel that entire renderer factor: both HDRNet and the PGTM N axis
|
||||
// must operate on RAW * finalShortGain, independently of the display-exposure target.
|
||||
val mapInputScale = sourceToShortGain / rendererBaselineGain
|
||||
if (!mapInputScale.isFinite() || mapInputScale <= 0f) return null
|
||||
val mapInputWeights = FloatArray(PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS.size) { index ->
|
||||
PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS[index] * mapInputScale
|
||||
@@ -232,6 +231,178 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
return guide.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces the actual 256 x 192 HDRNet RGB tensor to one reliable source-luma sample for each
|
||||
* 16 x 12 affine-grid cell. The tensor is already in final-short space, so division by the
|
||||
* candidate short gain restores the common source domain used by BaselineExposure.
|
||||
*
|
||||
* Endpoint and clipped samples do not represent global exposure. After rejecting those
|
||||
* samples, the central source-luma population is retained so large highlight or deep-shadow
|
||||
* regions cannot dominate the exposure anchor merely through their local HDR gain.
|
||||
*/
|
||||
fun hdrNetExposureSourceLumaByCell(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
modelInput: FloatArray,
|
||||
): FloatArray? {
|
||||
val expectedCount = HDRNET_INPUT_WIDTH * HDRNET_INPUT_HEIGHT * 4
|
||||
if (modelInput.size != expectedCount) return null
|
||||
if (HDRNET_INPUT_WIDTH % HDRNET_GRID_WIDTH != 0 ||
|
||||
HDRNET_INPUT_HEIGHT % HDRNET_GRID_HEIGHT != 0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val cellWidth = HDRNET_INPUT_WIDTH / HDRNET_GRID_WIDTH
|
||||
val cellHeight = HDRNET_INPUT_HEIGHT / HDRNET_GRID_HEIGHT
|
||||
val cellPixelCount = cellWidth * cellHeight
|
||||
val minimumValidPixels = (cellPixelCount * HDRNET_EXPOSURE_MIN_VALID_PIXEL_FRACTION)
|
||||
.toInt()
|
||||
.coerceAtLeast(1)
|
||||
val pixelLumas = FloatArray(cellPixelCount)
|
||||
val sourceLumaByCell = FloatArray(HDRNET_GRID_WIDTH * HDRNET_GRID_HEIGHT) { Float.NaN }
|
||||
for (cellY in 0 until HDRNET_GRID_HEIGHT) {
|
||||
for (cellX in 0 until HDRNET_GRID_WIDTH) {
|
||||
var validPixelCount = 0
|
||||
val startX = cellX * cellWidth
|
||||
val startY = cellY * cellHeight
|
||||
for (pixelY in startY until startY + cellHeight) {
|
||||
for (pixelX in startX until startX + cellWidth) {
|
||||
val offset = (pixelY * HDRNET_INPUT_WIDTH + pixelX) * 4
|
||||
val red = modelInput[offset]
|
||||
val green = modelInput[offset + 1]
|
||||
val blue = modelInput[offset + 2]
|
||||
if (!red.isFinite() || !green.isFinite() || !blue.isFinite() ||
|
||||
maxOf(red, green, blue) >= HDRNET_EXPOSURE_INPUT_CLIP
|
||||
) {
|
||||
continue
|
||||
}
|
||||
val shortLuma = red * HDRNET_LUMA_RED +
|
||||
green * HDRNET_LUMA_GREEN + blue * HDRNET_LUMA_BLUE
|
||||
val sourceLuma = shortLuma / plan.hdrNetInputScale
|
||||
if (!sourceLuma.isFinite() || sourceLuma <= HDRNET_EXPOSURE_SOURCE_FLOOR) {
|
||||
continue
|
||||
}
|
||||
pixelLumas[validPixelCount++] = sourceLuma
|
||||
}
|
||||
}
|
||||
if (validPixelCount < minimumValidPixels) continue
|
||||
pixelLumas.sort(0, validPixelCount)
|
||||
sourceLumaByCell[cellY * HDRNET_GRID_WIDTH + cellX] =
|
||||
median(pixelLumas, validPixelCount)
|
||||
}
|
||||
}
|
||||
|
||||
val validCellLumas = sourceLumaByCell.filter { it.isFinite() }.toFloatArray()
|
||||
if (validCellLumas.size < HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT) return null
|
||||
validCellLumas.sort()
|
||||
val lowerLuma = percentile(validCellLumas, HDRNET_EXPOSURE_LOWER_PERCENTILE)
|
||||
val upperLuma = percentile(validCellLumas, HDRNET_EXPOSURE_UPPER_PERCENTILE)
|
||||
var retainedCellCount = 0
|
||||
for (index in sourceLumaByCell.indices) {
|
||||
val sourceLuma = sourceLumaByCell[index]
|
||||
if (!sourceLuma.isFinite() || sourceLuma < lowerLuma || sourceLuma > upperLuma) {
|
||||
sourceLumaByCell[index] = Float.NaN
|
||||
} else {
|
||||
retainedCellCount++
|
||||
}
|
||||
}
|
||||
return sourceLumaByCell.takeIf {
|
||||
retainedCellCount >= HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates HDRNet at the actual source luma of every retained spatial cell and returns its
|
||||
* equivalent pre-tone exposure in stops: `log2(ACR3^-1(H) / sourceLuma)`. This deliberately
|
||||
* measures the robust global exposure produced by HDRNet while leaving its local spatial and
|
||||
* range-dependent shaping intact.
|
||||
*/
|
||||
fun hdrNetEffectiveExposureEvs(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
sourceLumaByCell: FloatArray,
|
||||
): FloatArray? {
|
||||
if (coefficients.size != HDRNET_OUTPUT_FLOAT_COUNT) return null
|
||||
if (sourceLumaByCell.size != HDRNET_GRID_WIDTH * HDRNET_GRID_HEIGHT) return null
|
||||
val output = FloatArray(sourceLumaByCell.count { it.isFinite() })
|
||||
var outputCount = 0
|
||||
fun coefficient(x: Int, y: Int, depth: Int, component: Int): Float {
|
||||
val index = (((y * HDRNET_GRID_WIDTH + x) * HDRNET_GRID_DEPTH + depth) *
|
||||
HDRNET_COEFFICIENT_COUNT) + component
|
||||
return coefficients[index]
|
||||
}
|
||||
for (y in 0 until HDRNET_GRID_HEIGHT) {
|
||||
for (x in 0 until HDRNET_GRID_WIDTH) {
|
||||
val sourceLuma = sourceLumaByCell[y * HDRNET_GRID_WIDTH + x]
|
||||
if (!sourceLuma.isFinite()) continue
|
||||
val shortIntensity = (sourceLuma * plan.hdrNetInputScale).coerceIn(0f, 1f)
|
||||
val guide = hdrNetGuide(shortIntensity)
|
||||
val rangePosition = guide * HDRNET_GRID_DEPTH - 0.5f
|
||||
val rangeFloor = floor(rangePosition).toInt()
|
||||
val lowerRange = rangeFloor.coerceIn(0, HDRNET_GRID_DEPTH - 1)
|
||||
val upperRange = (rangeFloor + 1).coerceIn(0, HDRNET_GRID_DEPTH - 1)
|
||||
val rangeAmount = rangePosition - floor(rangePosition)
|
||||
val rawScale = lerp(
|
||||
coefficient(x, y, lowerRange, component = 0),
|
||||
coefficient(x, y, upperRange, component = 0),
|
||||
rangeAmount,
|
||||
)
|
||||
val bias = lerp(
|
||||
coefficient(x, y, lowerRange, component = 1),
|
||||
coefficient(x, y, upperRange, component = 1),
|
||||
rangeAmount,
|
||||
)
|
||||
val scale = rawScale * (plan.hdrRatio - 1f) + 1f
|
||||
val predictedLuma = scale * shortIntensity + bias
|
||||
if (!predictedLuma.isFinite()) return null
|
||||
val renderGain = (
|
||||
predictedLuma / (shortIntensity + HDRNET_GAIN_EPSILON)
|
||||
).coerceIn(HDRNET_RENDER_MIN_GAIN, HDRNET_RENDER_MAX_GAIN)
|
||||
val hdrNetOutputLuma = (shortIntensity * renderGain).coerceIn(0f, 1f)
|
||||
val preCurveLuma = ACR3Curve.inputForOutput(hdrNetOutputLuma)
|
||||
if (!preCurveLuma.isFinite() || preCurveLuma <= HDRNET_GAIN_EPSILON) continue
|
||||
val exposureEv = (
|
||||
ln((preCurveLuma / sourceLuma).toDouble()) / LN_2
|
||||
).toFloat()
|
||||
if (!exposureEv.isFinite()) return null
|
||||
output[outputCount++] = exposureEv
|
||||
}
|
||||
}
|
||||
return output.copyOf(outputCount).takeIf {
|
||||
outputCount >= HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT
|
||||
}
|
||||
}
|
||||
|
||||
private fun median(sortedValues: FloatArray, count: Int): Float {
|
||||
val upper = count / 2
|
||||
return if (count % 2 == 0) {
|
||||
(sortedValues[upper - 1] + sortedValues[upper]) * 0.5f
|
||||
} else {
|
||||
sortedValues[upper]
|
||||
}
|
||||
}
|
||||
|
||||
private fun percentile(sortedValues: FloatArray, fraction: Float): Float {
|
||||
val position = fraction.coerceIn(0f, 1f) * sortedValues.lastIndex
|
||||
val lower = floor(position).toInt()
|
||||
val upper = (lower + 1).coerceAtMost(sortedValues.lastIndex)
|
||||
return lerp(sortedValues[lower], sortedValues[upper], position - lower)
|
||||
}
|
||||
|
||||
private fun lerp(first: Float, second: Float, amount: Float): Float =
|
||||
first + (second - first) * amount
|
||||
|
||||
private const val HDRNET_GAIN_EPSILON = 1e-6f
|
||||
private const val HDRNET_LUMA_RED = 0.298828125f
|
||||
private const val HDRNET_LUMA_GREEN = 0.5869140625f
|
||||
private const val HDRNET_LUMA_BLUE = 0.1142578125f
|
||||
private const val HDRNET_EXPOSURE_INPUT_CLIP = 0.98f
|
||||
private const val HDRNET_EXPOSURE_SOURCE_FLOOR = 1f / 1024f
|
||||
private const val HDRNET_EXPOSURE_MIN_VALID_PIXEL_FRACTION = 0.5f
|
||||
private const val HDRNET_EXPOSURE_LOWER_PERCENTILE = 0.2f
|
||||
private const val HDRNET_EXPOSURE_UPPER_PERCENTILE = 0.8f
|
||||
private const val HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT = 24
|
||||
private val LN_2 = ln(2.0)
|
||||
|
||||
fun plan(
|
||||
width: Int,
|
||||
height: Int,
|
||||
@@ -426,11 +597,11 @@ internal data class HdrNetProfileGainTablePlan(
|
||||
val pointCount: Int,
|
||||
val mapInputWeights: FloatArray,
|
||||
val gamma: Float,
|
||||
/** Restores the physical multi-frame normalization present in the stored RAW pixels. */
|
||||
/** BaselineExposure gain used only to define the robust global-exposure target. */
|
||||
val sourceBaselineGain: Float,
|
||||
/** Total gain a conforming DNG renderer folds into the MapInputWeights coordinate. */
|
||||
val rendererBaselineGain: Float,
|
||||
/** Gain from the BaselineExposure-restored captured/reference exposure to final short. */
|
||||
/** Gain from source RAW to the candidate final-short exposure used by HDRNet. */
|
||||
val sourceToShortGain: Float,
|
||||
val hdrRatio: Float,
|
||||
val diagnosticBand: DngPhotonProfileGainTableGenerator.DiagnosticBand?,
|
||||
@@ -462,7 +633,7 @@ internal data class HdrNetProfileGainTablePlan(
|
||||
get() = mapInputWeightSum * rendererBaselineGain
|
||||
|
||||
val hdrNetInputScale: Float
|
||||
get() = sourceBaselineGain * sourceToShortGain
|
||||
get() = sourceToShortGain
|
||||
}
|
||||
|
||||
internal data class PhotonPgtmGrid(
|
||||
|
||||
@@ -3,10 +3,11 @@ package com.hinnka.mycamera.raw
|
||||
/**
|
||||
* The mutually exclusive capture/development modes for adaptive RAW exposure handling.
|
||||
*
|
||||
* [OFF] leaves both paths disabled. [PHOTON_HDR] generates an HDRNet ProfileGainTableMap and
|
||||
* preserves the source
|
||||
* BaselineExposure. [LEGACY_AUTO_EXPOSURE] matches the captured viewfinder preview and writes the
|
||||
* solved exposure into BaselineExposure.
|
||||
* [OFF] leaves both paths disabled. [PHOTON_HDR] writes the legacy AE result into
|
||||
* BaselineExposure, then runs ML AE plus HDRNet using that value as its reproducible exposure
|
||||
* anchor. [LEGACY_AUTO_EXPOSURE] writes the same legacy AE result and generates the historical
|
||||
* Local Laplacian profile gain table. Both enabled modes therefore combine automatic metering
|
||||
* with HDR mapping; only the mapping implementation differs.
|
||||
*/
|
||||
enum class RawAdaptiveExposureMode(val persistedValue: String) {
|
||||
OFF("OFF"),
|
||||
|
||||
@@ -7,7 +7,7 @@ import com.hinnka.mycamera.camera.AspectRatio
|
||||
import com.hinnka.mycamera.camera.RawBlackBorderCrop
|
||||
import com.hinnka.mycamera.preview.PortraitMaskSnapshot
|
||||
|
||||
/** Owns the mutually exclusive capture-time Photon HDR and classic auto-exposure paths. */
|
||||
/** Routes capture-time adaptive exposure into one complete, mutually exclusive processing path. */
|
||||
internal object RawCaptureProfileCoordinator {
|
||||
suspend fun prepareCaptureProfile(
|
||||
renderer: RawDemosaicProcessor,
|
||||
@@ -37,7 +37,7 @@ internal object RawCaptureProfileCoordinator {
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val legacyRequest = if (mode.usesLegacyAutoExposure) {
|
||||
val legacyRequest = if (mode.usesLegacyAutoExposure || mode.usesPhotonHdr) {
|
||||
RawLegacyAutoExposureMatcher.createRequest(capturePreviewThumbnail)
|
||||
} else {
|
||||
null
|
||||
@@ -50,7 +50,7 @@ internal object RawCaptureProfileCoordinator {
|
||||
rotation = rotation,
|
||||
sceneExposureRequest = photonRequest,
|
||||
legacyAutoExposureRequest = legacyRequest,
|
||||
generatePhotonPgtm = mode.usesPhotonHdr,
|
||||
generatePhotonPgtm = mode.usesPhotonHdr || mode.usesLegacyAutoExposure,
|
||||
statsBounds = statsBounds,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
|
||||
@@ -2656,8 +2656,11 @@ class RawDemosaicProcessor {
|
||||
val hasActiveWarp = applicableDngWarpRectilinear?.isNotEmpty() == true
|
||||
val captureExposureRequested =
|
||||
sceneExposureRequest != null || legacyAutoExposureRequest != null
|
||||
check(sceneExposureRequest == null || legacyAutoExposureRequest == null) {
|
||||
"Photon HDR and classic auto exposure requests are mutually exclusive"
|
||||
check(
|
||||
sceneExposureRequest == null || legacyAutoExposureRequest == null ||
|
||||
capturePhotonPgtmRequested,
|
||||
) {
|
||||
"Classic auto exposure cannot run alongside scene AE without Photon HDR"
|
||||
}
|
||||
val prepareCaptureProfile = captureProfilePass
|
||||
val useHalfResolutionMeteringDemosaic =
|
||||
@@ -3092,7 +3095,11 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
|
||||
if (prepareCaptureProfile) {
|
||||
val solvedExposureEv = legacyAutoExposureRequest?.let { request ->
|
||||
val captureUsesHdrNet = sceneExposureRequest != null
|
||||
val captureUsesLocalLaplacian =
|
||||
sceneExposureRequest == null && legacyAutoExposureRequest != null
|
||||
val solvedExposureEv = legacyAutoExposureRequest
|
||||
?.let { request ->
|
||||
renderLegacyAutoExposureRequest(
|
||||
request = request,
|
||||
metadata = actualMetadata,
|
||||
@@ -3153,11 +3160,12 @@ class RawDemosaicProcessor {
|
||||
?.takeIf { it.isFinite() && it >= 1f }
|
||||
val captureSourceToShortGain = solvedSceneExposure?.finalShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val captureProfileGainTableMap = if (
|
||||
capturePhotonPgtmRequested && captureHdrRatio != null &&
|
||||
captureSourceToShortGain != null
|
||||
) {
|
||||
generateProfileGainTableMapOnGpu(
|
||||
val captureProfileOutput = when {
|
||||
capturePhotonPgtmRequested && captureUsesHdrNet &&
|
||||
solvedExposureEv != null && captureHdrRatio != null &&
|
||||
captureSourceToShortGain != null -> {
|
||||
generateProfileGainTableMapOnGpu(
|
||||
mode = DngPhotonProfileGainTableAlgorithm.Mode.HDR_NET,
|
||||
context = context.applicationContext,
|
||||
linearRgbTextureId = demosaicTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
@@ -3170,8 +3178,8 @@ class RawDemosaicProcessor {
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = captureProfileStatsBounds,
|
||||
// Photon HDR preserves the source BaselineExposure. Classic auto exposure
|
||||
// is mutually exclusive and is the only path that can contribute an EV.
|
||||
// Legacy AE owns the reproducible display-exposure anchor written into
|
||||
// BaselineExposure. ML AE supplies only HDRNet's short/long relationship.
|
||||
sourceBaselineExposureEv = finalBaselineExposureEv,
|
||||
rendererBaselineExposureEv = finalBaselineExposureEv +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
@@ -3182,20 +3190,94 @@ class RawDemosaicProcessor {
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
// MGC AE is also the owner of HDRNet's ratio, so every Photon HDR capture
|
||||
// profile reaches this point through the metering path. WarpRectilinear
|
||||
// has therefore already been applied to demosaicTextureId.
|
||||
// The continuous linear RGB texture has already received active Stage 3
|
||||
// geometry immediately above. Applying the warp again in HDRNet would
|
||||
// compare a different field of view with the viewfinder thumbnail.
|
||||
warpRectilinear = null,
|
||||
)
|
||||
} else {
|
||||
if (capturePhotonPgtmRequested) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Photon HDR PGTM unavailable: MGC AE HDR ratio or final-short gain " +
|
||||
"is missing",
|
||||
}
|
||||
capturePhotonPgtmRequested && captureUsesLocalLaplacian &&
|
||||
solvedExposureEv != null -> {
|
||||
generateProfileGainTableMapOnGpu(
|
||||
mode = DngPhotonProfileGainTableAlgorithm.Mode.LOCAL_LAPLACIAN,
|
||||
context = context.applicationContext,
|
||||
linearRgbTextureId = demosaicTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
streamingRawData = tiledRawData,
|
||||
streamingRowStride = actualRowStride,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
linearRgbTextureWidth = demosaicWidth,
|
||||
linearRgbTextureHeight = demosaicHeight,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = captureProfileStatsBounds,
|
||||
sourceBaselineExposureEv = finalBaselineExposureEv,
|
||||
rendererBaselineExposureEv = finalBaselineExposureEv +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
hdrRatio = 1f,
|
||||
sourceToShortGain = 1f,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
warpRectilinear = applicableDngWarpRectilinear,
|
||||
)
|
||||
}
|
||||
null
|
||||
else -> {
|
||||
if (capturePhotonPgtmRequested) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
if (captureUsesHdrNet) {
|
||||
"HDRNet PGTM unavailable: legacy BaselineExposure, ML AE " +
|
||||
"HDR ratio, or final-short gain is missing"
|
||||
} else {
|
||||
"Local Laplacian PGTM unavailable: legacy AE result is missing"
|
||||
},
|
||||
)
|
||||
}
|
||||
null
|
||||
}
|
||||
}
|
||||
val captureProfileGainTableMap = captureProfileOutput?.map
|
||||
val selectedCaptureHdrRatio = captureProfileOutput?.hdrRatio ?: captureHdrRatio
|
||||
val selectedCaptureSourceToShortGain =
|
||||
captureProfileOutput?.sourceToShortGain ?: captureSourceToShortGain
|
||||
val captureSummaryText = solvedSceneExposure?.summaryText?.let { summary ->
|
||||
val output = captureProfileOutput ?: return@let summary
|
||||
val outputShortGain = output.sourceToShortGain ?: return@let summary
|
||||
val outputHdrRatio = output.hdrRatio ?: return@let summary
|
||||
buildString {
|
||||
append(summary.trimEnd())
|
||||
appendLine()
|
||||
appendLine("legacyBaselineExposureOffsetEv=$solvedExposureEv")
|
||||
appendLine("hdrNetBaselineExposureEv=$finalBaselineExposureEv")
|
||||
appendLine(
|
||||
"hdrNetBaselineExposureGain=" +
|
||||
DngBaselineExposure.exactGain(finalBaselineExposureEv),
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureAdjustmentEv=${output.hdrNetExposureAdjustmentEv}",
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureTargetEv=" + output.hdrNetExposureTargetEv,
|
||||
)
|
||||
appendLine("hdrNetFinalShortGain=$outputShortGain")
|
||||
appendLine("hdrNetFinalLongGain=${outputShortGain * outputHdrRatio}")
|
||||
appendLine("hdrNetFinalHdrRatio=$outputHdrRatio")
|
||||
output.hdrNetExposureEvaluation?.let { evaluation ->
|
||||
appendLine(
|
||||
"hdrNetExposureMatchedSpatialSamples=" +
|
||||
"${evaluation.matchedSpatialSampleCount}/" +
|
||||
evaluation.spatialSampleCount,
|
||||
)
|
||||
appendLine("hdrNetExposureSpatialMatchRate=${evaluation.matchRate}")
|
||||
appendLine(
|
||||
"hdrNetExposureMedianErrorEv=" +
|
||||
evaluation.medianExposureErrorEv,
|
||||
)
|
||||
appendLine("hdrNetExposureMatchScore=${evaluation.score}")
|
||||
}
|
||||
}.trimEnd()
|
||||
}
|
||||
val captureProfileFailed =
|
||||
capturePhotonPgtmRequested && captureProfileGainTableMap == null
|
||||
@@ -3215,9 +3297,9 @@ class RawDemosaicProcessor {
|
||||
} else {
|
||||
RawDngCaptureProfileResult(
|
||||
exposureOffsetEv = solvedExposureEv,
|
||||
hdrRatio = captureHdrRatio,
|
||||
finalShortGain = captureSourceToShortGain,
|
||||
rawSceneExposureSummaryText = solvedSceneExposure?.summaryText,
|
||||
hdrRatio = selectedCaptureHdrRatio,
|
||||
finalShortGain = selectedCaptureSourceToShortGain,
|
||||
rawSceneExposureSummaryText = captureSummaryText,
|
||||
profileGainTableMap = captureProfileGainTableMap,
|
||||
gpuDemosaicedRawSource = reusableDemosaicSource,
|
||||
)
|
||||
@@ -3230,9 +3312,6 @@ class RawDemosaicProcessor {
|
||||
val persistedHdrRatio = photonHdrRatio?.takeIf { it.isFinite() && it >= 1f }
|
||||
val persistedSourceToShortGain = photonSourceToShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
// Forced regeneration is an explicit request to run the current AE and HDRNet
|
||||
// algorithms against the current RAW payload. Persisted capture coordinates are
|
||||
// only a fallback when the estimator cannot produce a complete ratio/gain pair.
|
||||
val estimatedExposure = renderSceneExposureRequest(
|
||||
request = RawSceneExposureMatcher.createRequest(
|
||||
context = context,
|
||||
@@ -3246,10 +3325,6 @@ class RawDemosaicProcessor {
|
||||
profileToLinearSrgbTransform = profileToLinearSrgbTransform,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
stackCompletionTimeline = borrowedGpuSource?.stackCompletionTimeline,
|
||||
// MGC AE operates in the sensor exposure domain. DNG BaselineExposure is a
|
||||
// rendering coordinate and is supplied separately to PGTM generation below;
|
||||
// applying it to metering pixels without applying it to TET shifts the table's
|
||||
// log-scene-brightness coordinate by ln(baselineGain).
|
||||
restoreSourceBaselineExposure = false,
|
||||
)
|
||||
val estimatedHdrRatio = estimatedExposure?.hdrRatio
|
||||
@@ -3266,8 +3341,8 @@ class RawDemosaicProcessor {
|
||||
if (regenerationHdrRatio == null) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"HDRNet PGTM regeneration could not resolve an MGC AE HDR ratio " +
|
||||
"from persisted metadata or DNG exposure data",
|
||||
"HDRNet PGTM regeneration could not resolve an ML AE " +
|
||||
"HDR ratio",
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
@@ -3277,36 +3352,26 @@ class RawDemosaicProcessor {
|
||||
persistedSourceToShortGain ?: 1f
|
||||
}
|
||||
val regenerationAeSource = when {
|
||||
useEstimatedAe -> "MGC_FAST_MOMENTS_TRUE"
|
||||
useEstimatedAe -> "MGC_ML_AE_REFRESH"
|
||||
persistedHdrRatio != null && persistedSourceToShortGain != null ->
|
||||
"PERSISTED_CAPTURE_AE_FALLBACK"
|
||||
else -> "LEGACY_METADATA_FALLBACK"
|
||||
else -> "LEGACY_RATIO_SHORT_UNITY_FALLBACK"
|
||||
}
|
||||
val regenerationLongGain =
|
||||
regenerationSourceToShortGain * regenerationHdrRatio
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet PGTM regeneration ratio=$regenerationHdrRatio " +
|
||||
"sourceToShortGain=$regenerationSourceToShortGain " +
|
||||
"HDRNet PGTM regeneration " +
|
||||
"hdrRatio=$regenerationHdrRatio " +
|
||||
"finalShortGain=$regenerationSourceToShortGain " +
|
||||
"finalLongGain=$regenerationLongGain " +
|
||||
"aeSource=$regenerationAeSource " +
|
||||
"sourceBaselineEv=${actualMetadata.baselineExposure} " +
|
||||
"sourceBaselineGain=${exactDngBaselineExposureGain(actualMetadata)} " +
|
||||
"persistedRatio=$persistedHdrRatio " +
|
||||
"persistedSourceToShortGain=$persistedSourceToShortGain " +
|
||||
"finalShortTetMs=${estimatedExposure?.finalShortTetMs} " +
|
||||
"finalLongTetMs=${estimatedExposure?.finalLongTetMs} " +
|
||||
"finalShortGain=${estimatedExposure?.finalShortGain} " +
|
||||
"safeUnderexposure=${estimatedExposure?.safeUnderexposure} " +
|
||||
"fractionPixelsClippedAtFinalShortTet=" +
|
||||
"${estimatedExposure?.fractionPixelsClippedAtFinalShortTet}",
|
||||
"statsBounds=$outputSourceBounds",
|
||||
)
|
||||
if (rawRenderTiles.isNotEmpty() || demosaicTextureId == 0) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"HDRNet PGTM regeneration has no continuous linear RGB source: " +
|
||||
"tiles=${rawRenderTiles.size} texture=$demosaicTextureId",
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
val regeneratedPhotonPgtm = generateProfileGainTableMapOnGpu(
|
||||
mode = DngPhotonProfileGainTableAlgorithm.Mode.HDR_NET,
|
||||
context = context.applicationContext,
|
||||
linearRgbTextureId = demosaicTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
@@ -3327,8 +3392,8 @@ class RawDemosaicProcessor {
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
// The ordinary render path has already applied every active DNG warp to the
|
||||
// continuous linear texture immediately above.
|
||||
// The ordinary refresh render has already applied Stage 3 warps to the
|
||||
// continuous linear RGB texture used as HDRNet input.
|
||||
warpRectilinear = null,
|
||||
)
|
||||
if (regeneratedPhotonPgtm == null) {
|
||||
@@ -3336,15 +3401,19 @@ class RawDemosaicProcessor {
|
||||
return@withContext null
|
||||
}
|
||||
actualMetadata = actualMetadata.copy(
|
||||
profileGainTableMap = regeneratedPhotonPgtm,
|
||||
profileGainTableMap = regeneratedPhotonPgtm.map,
|
||||
)
|
||||
hasProfileGainTableMap = true
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet PGTM regenerated for RAW refresh: " +
|
||||
"${regeneratedPhotonPgtm.mapPointsH}x" +
|
||||
"${regeneratedPhotonPgtm.mapPointsV}x" +
|
||||
regeneratedPhotonPgtm.mapPointsN,
|
||||
"${regeneratedPhotonPgtm.map.mapPointsH}x" +
|
||||
"${regeneratedPhotonPgtm.map.mapPointsV}x" +
|
||||
regeneratedPhotonPgtm.map.mapPointsN +
|
||||
" hdrRatio=${regeneratedPhotonPgtm.hdrRatio}" +
|
||||
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}" +
|
||||
" exposureAdjustmentEv=" +
|
||||
regeneratedPhotonPgtm.hdrNetExposureAdjustmentEv,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4399,6 +4468,7 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
|
||||
private fun generateProfileGainTableMapOnGpu(
|
||||
mode: DngPhotonProfileGainTableAlgorithm.Mode,
|
||||
context: Context,
|
||||
linearRgbTextureId: Int,
|
||||
rawTextureId: Int,
|
||||
@@ -4421,7 +4491,7 @@ class RawDemosaicProcessor {
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
hueSatMapSupportsOverrange: Boolean,
|
||||
warpRectilinear: FloatArray? = null,
|
||||
): DngProfileGainTableMap? {
|
||||
): DngPhotonProfileGainTableAlgorithm.Output? {
|
||||
val streamingUploader = streamingRawData?.let {
|
||||
DngPhotonProfileGainTableAlgorithm.StreamingRawUploader {
|
||||
buffer,
|
||||
@@ -4440,6 +4510,7 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
return profileGainTableAlgorithm.execute(
|
||||
DngPhotonProfileGainTableAlgorithm.Input(
|
||||
mode = mode,
|
||||
context = context,
|
||||
linearRgbTextureId = linearRgbTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
@@ -4480,7 +4551,7 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
},
|
||||
),
|
||||
)?.map
|
||||
)
|
||||
}
|
||||
|
||||
private fun calculateOutputSourceBounds(
|
||||
|
||||
@@ -107,7 +107,7 @@ data class GpuDemosaicedRawSource(
|
||||
)
|
||||
|
||||
data class RawDngCaptureProfileResult(
|
||||
/** Classic auto-exposure EV relative to the source baseline; always null for Photon HDR. */
|
||||
/** Legacy auto-exposure EV relative to the source baseline; used by classic AE and Photon HDR. */
|
||||
val exposureOffsetEv: Float?,
|
||||
/** Photon HDR long/short TET ratio; always null for classic auto exposure. */
|
||||
val hdrRatio: Float?,
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.hinnka.mycamera.raw
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
|
||||
internal data class RawLegacyExposurePreviewFrame(
|
||||
@@ -16,6 +17,22 @@ internal data class RawLegacyAutoExposureRequest(
|
||||
val solve: ((Float) -> RawLegacyExposurePreviewFrame?) -> Float?,
|
||||
)
|
||||
|
||||
internal data class RawHdrNetExposureEvaluation(
|
||||
val matchedSpatialSampleCount: Int,
|
||||
val spatialSampleCount: Int,
|
||||
val matchRate: Float,
|
||||
val medianExposureErrorEv: Float,
|
||||
val meanAbsoluteExposureErrorEv: Float,
|
||||
val robustExposureLoss: Float,
|
||||
val score: Float,
|
||||
)
|
||||
|
||||
internal data class RawHdrNetExposureCandidate<T>(
|
||||
val adjustmentEv: Float,
|
||||
val payload: T,
|
||||
val evaluation: RawHdrNetExposureEvaluation,
|
||||
)
|
||||
|
||||
/**
|
||||
* Classic capture-side auto exposure derived from the adaptive spatial grid matcher in
|
||||
* PhotonCamera 1.27.1. The RAW renderer supplies default-curve preview candidates while native
|
||||
@@ -29,8 +46,12 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
val frame: RawLegacyExposurePreviewFrame,
|
||||
)
|
||||
|
||||
fun createRequest(capturePreviewThumbnail: Bitmap?): RawLegacyAutoExposureRequest? {
|
||||
val reference = capturePreviewThumbnail?.let(::buildReference)
|
||||
fun createRequest(
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
): RawLegacyAutoExposureRequest? {
|
||||
val reference = capturePreviewThumbnail?.let {
|
||||
buildReference(it)
|
||||
}
|
||||
if (capturePreviewThumbnail != null && reference == null) {
|
||||
PLog.w(TAG, "Classic auto exposure skipped: capture preview is unavailable")
|
||||
}
|
||||
@@ -61,6 +82,201 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the one-dimensional Photon exposure bracket without rendering a PGTM candidate.
|
||||
* Each EV candidate applies one common gain to short and long, preserving the ML AE HDR ratio.
|
||||
* [evaluateCandidate] returns the spatial effective exposure of the actual image in stops:
|
||||
* `log2(ACR3^-1(H) / sourceLuma)`. Its robust center is matched directly to the legacy
|
||||
* BaselineExposure EV, so local HDR shaping does not turn a synthetic 18% gray into a second
|
||||
* global exposure target.
|
||||
*/
|
||||
fun <T> solveHdrNetExposure(
|
||||
targetExposureEv: Float,
|
||||
maxAdjustmentEv: Float,
|
||||
evaluateCandidate: (Float) -> Pair<T, FloatArray>?,
|
||||
): RawHdrNetExposureCandidate<T>? {
|
||||
if (!targetExposureEv.isFinite()) return null
|
||||
val limit = maxAdjustmentEv.takeIf { it.isFinite() && it > MIN_SEARCH_STEP_EV }
|
||||
?.coerceAtMost(MAX_SEARCH_RANGE_EV)
|
||||
?: 0f
|
||||
val samples = ArrayList<RawHdrNetExposureCandidate<T>>(MAX_HDRNET_SAMPLE_COUNT)
|
||||
var nextEv = 0f
|
||||
var searchMinimumEv = -limit
|
||||
var searchMaximumEv = limit
|
||||
while (samples.size < MAX_HDRNET_SAMPLE_COUNT) {
|
||||
val candidate = evaluateCandidate(nextEv) ?: break
|
||||
val evaluation = evaluateHdrNetExposure(targetExposureEv, candidate.second) ?: break
|
||||
val sample = RawHdrNetExposureCandidate(
|
||||
adjustmentEv = nextEv,
|
||||
payload = candidate.first,
|
||||
evaluation = evaluation,
|
||||
)
|
||||
samples += sample
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet exposure sample: adjustmentEv=$nextEv " +
|
||||
"matchedSpatialSamples=${evaluation.matchedSpatialSampleCount}/" +
|
||||
"${evaluation.spatialSampleCount} " +
|
||||
"targetExposureEv=$targetExposureEv " +
|
||||
"medianExposureErrorEv=${evaluation.medianExposureErrorEv} " +
|
||||
"meanAbsoluteExposureErrorEv=${evaluation.meanAbsoluteExposureErrorEv} " +
|
||||
"robustExposureLoss=${evaluation.robustExposureLoss} " +
|
||||
"matchRate=${evaluation.matchRate} " +
|
||||
"score=${evaluation.score}",
|
||||
)
|
||||
if (limit == 0f ||
|
||||
abs(evaluation.medianExposureErrorEv) <= CONVERGED_RESIDUAL_EV
|
||||
) {
|
||||
break
|
||||
}
|
||||
if (samples.size == 1) {
|
||||
// Lock the search direction from the first response. The controlled variable is
|
||||
// one common exposure EV, so this restriction never changes the short/long ratio.
|
||||
if (evaluation.medianExposureErrorEv > 0f) {
|
||||
searchMaximumEv = 0f
|
||||
} else {
|
||||
searchMinimumEv = 0f
|
||||
}
|
||||
}
|
||||
val proposed = nextHdrNetAdjustment(
|
||||
samples = samples,
|
||||
minimumEv = searchMinimumEv,
|
||||
maximumEv = searchMaximumEv,
|
||||
) ?: break
|
||||
if (samples.any { abs(it.adjustmentEv - proposed) < MIN_SEARCH_STEP_EV }) break
|
||||
nextEv = proposed
|
||||
}
|
||||
val best = samples.minWithOrNull(
|
||||
compareBy<RawHdrNetExposureCandidate<T>> { it.evaluation.robustExposureLoss }
|
||||
.thenBy { it.evaluation.meanAbsoluteExposureErrorEv }
|
||||
.thenByDescending { it.evaluation.matchRate }
|
||||
.thenBy { abs(it.adjustmentEv) },
|
||||
) ?: return null
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet exposure result: adjustmentEv=${best.adjustmentEv} " +
|
||||
"matchedSpatialSamples=${best.evaluation.matchedSpatialSampleCount}/" +
|
||||
"${best.evaluation.spatialSampleCount} " +
|
||||
"targetExposureEv=$targetExposureEv " +
|
||||
"medianExposureErrorEv=${best.evaluation.medianExposureErrorEv} " +
|
||||
"meanAbsoluteExposureErrorEv=${best.evaluation.meanAbsoluteExposureErrorEv} " +
|
||||
"robustExposureLoss=${best.evaluation.robustExposureLoss} " +
|
||||
"matchRate=${best.evaluation.matchRate} " +
|
||||
"score=${best.evaluation.score} sampleCount=${samples.size}",
|
||||
)
|
||||
return best
|
||||
}
|
||||
|
||||
private fun evaluateHdrNetExposure(
|
||||
targetExposureEv: Float,
|
||||
candidateExposureEvs: FloatArray,
|
||||
): RawHdrNetExposureEvaluation? {
|
||||
if (candidateExposureEvs.isEmpty() || candidateExposureEvs.any { !it.isFinite() }) {
|
||||
return null
|
||||
}
|
||||
val residualHistogram = FloatArray(RESIDUAL_HISTOGRAM_BINS)
|
||||
var matchedSpatialSampleCount = 0
|
||||
var absoluteResidualSum = 0.0
|
||||
var robustLossSum = 0.0
|
||||
for (candidateExposureEv in candidateExposureEvs) {
|
||||
val residual = (candidateExposureEv - targetExposureEv)
|
||||
.coerceIn(-MAX_RESIDUAL_EV, MAX_RESIDUAL_EV)
|
||||
val absoluteResidual = abs(residual)
|
||||
val matched = absoluteResidual <= MATCH_RESIDUAL_EV
|
||||
if (matched) matchedSpatialSampleCount++
|
||||
absoluteResidualSum += absoluteResidual
|
||||
robustLossSum += huberLoss(residual)
|
||||
val histogramPosition = ((residual + MAX_RESIDUAL_EV) /
|
||||
(2f * MAX_RESIDUAL_EV) * (RESIDUAL_HISTOGRAM_BINS - 1))
|
||||
.toInt()
|
||||
.coerceIn(0, RESIDUAL_HISTOGRAM_BINS - 1)
|
||||
residualHistogram[histogramPosition] += 1f
|
||||
}
|
||||
val medianTarget = candidateExposureEvs.size * 0.5
|
||||
var cumulative = 0.0
|
||||
var medianBin = 0
|
||||
for (bin in residualHistogram.indices) {
|
||||
cumulative += residualHistogram[bin]
|
||||
if (cumulative >= medianTarget) {
|
||||
medianBin = bin
|
||||
break
|
||||
}
|
||||
}
|
||||
val medianResidual = -MAX_RESIDUAL_EV +
|
||||
(medianBin + 0.5f) * (2f * MAX_RESIDUAL_EV / RESIDUAL_HISTOGRAM_BINS)
|
||||
val meanAbsoluteResidual = (absoluteResidualSum / candidateExposureEvs.size).toFloat()
|
||||
val robustLoss = (robustLossSum / candidateExposureEvs.size).toFloat()
|
||||
val matchRate = matchedSpatialSampleCount.toFloat() / candidateExposureEvs.size
|
||||
return RawHdrNetExposureEvaluation(
|
||||
matchedSpatialSampleCount = matchedSpatialSampleCount,
|
||||
spatialSampleCount = candidateExposureEvs.size,
|
||||
matchRate = matchRate,
|
||||
medianExposureErrorEv = medianResidual,
|
||||
meanAbsoluteExposureErrorEv = meanAbsoluteResidual,
|
||||
robustExposureLoss = robustLoss,
|
||||
score = 1f / (1f + robustLoss),
|
||||
)
|
||||
}
|
||||
|
||||
private fun <T> nextHdrNetAdjustment(
|
||||
samples: List<RawHdrNetExposureCandidate<T>>,
|
||||
minimumEv: Float,
|
||||
maximumEv: Float,
|
||||
): Float? {
|
||||
val sorted = samples.sortedBy { it.adjustmentEv }
|
||||
var narrowestBracket: Pair<RawHdrNetExposureCandidate<T>, RawHdrNetExposureCandidate<T>>? =
|
||||
null
|
||||
for (index in 0 until sorted.lastIndex) {
|
||||
val lower = sorted[index]
|
||||
val upper = sorted[index + 1]
|
||||
if (lower.evaluation.medianExposureErrorEv *
|
||||
upper.evaluation.medianExposureErrorEv > 0f
|
||||
) {
|
||||
continue
|
||||
}
|
||||
val currentWidth = upper.adjustmentEv - lower.adjustmentEv
|
||||
val selectedWidth = narrowestBracket?.let { it.second.adjustmentEv - it.first.adjustmentEv }
|
||||
if (selectedWidth == null || currentWidth < selectedWidth) {
|
||||
narrowestBracket = lower to upper
|
||||
}
|
||||
}
|
||||
narrowestBracket?.let { (lower, upper) ->
|
||||
val lowerResidual = lower.evaluation.medianExposureErrorEv
|
||||
val upperResidual = upper.evaluation.medianExposureErrorEv
|
||||
val width = upper.adjustmentEv - lower.adjustmentEv
|
||||
val denominator = upperResidual - lowerResidual
|
||||
val secant = if (abs(denominator) > 1e-4f) {
|
||||
lower.adjustmentEv - lowerResidual * width / denominator
|
||||
} else {
|
||||
(lower.adjustmentEv + upper.adjustmentEv) * 0.5f
|
||||
}
|
||||
val margin = minOf(width * 0.15f, 0.05f)
|
||||
return secant.coerceIn(
|
||||
lower.adjustmentEv + margin,
|
||||
upper.adjustmentEv - margin,
|
||||
).coerceIn(minimumEv, maximumEv)
|
||||
}
|
||||
val anchor = samples.minWithOrNull(
|
||||
compareBy<RawHdrNetExposureCandidate<T>> {
|
||||
abs(it.evaluation.medianExposureErrorEv)
|
||||
}.thenBy { it.evaluation.robustExposureLoss },
|
||||
) ?: return null
|
||||
val residual = anchor.evaluation.medianExposureErrorEv
|
||||
if (!residual.isFinite() || abs(residual) <= CONVERGED_RESIDUAL_EV) return null
|
||||
val stepMagnitude = abs(residual).coerceIn(MIN_DIRECTIONAL_STEP_EV, MAX_DIRECTIONAL_STEP_EV)
|
||||
return (anchor.adjustmentEv - kotlin.math.sign(residual) * stepMagnitude)
|
||||
.coerceIn(minimumEv, maximumEv)
|
||||
}
|
||||
|
||||
private fun huberLoss(residualEv: Float): Float {
|
||||
val absolute = abs(residualEv)
|
||||
return if (absolute <= HUBER_DELTA_EV) {
|
||||
0.5f * absolute * absolute / HUBER_DELTA_EV
|
||||
} else {
|
||||
absolute - 0.5f * HUBER_DELTA_EV
|
||||
}
|
||||
}
|
||||
|
||||
private fun solve(
|
||||
reference: ViewfinderReference,
|
||||
renderSample: (Float) -> RawLegacyExposurePreviewFrame?,
|
||||
@@ -114,6 +330,17 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
|
||||
private data class Size(val width: Int, val height: Int)
|
||||
|
||||
private const val MATCH_RESIDUAL_EV = 0.13750352f
|
||||
private const val HUBER_DELTA_EV = 0.25f
|
||||
private const val MAX_RESIDUAL_EV = 4f
|
||||
private const val RESIDUAL_HISTOGRAM_BINS = 512
|
||||
private const val CONVERGED_RESIDUAL_EV = 0.03f
|
||||
private const val MIN_SEARCH_STEP_EV = 0.02f
|
||||
private const val MIN_DIRECTIONAL_STEP_EV = 0.125f
|
||||
private const val MAX_DIRECTIONAL_STEP_EV = 1f
|
||||
private const val MAX_SEARCH_RANGE_EV = 4f
|
||||
private const val MAX_HDRNET_SAMPLE_COUNT = 8
|
||||
|
||||
private fun longEdgeSize(sourceWidth: Int, sourceHeight: Int, maxLongEdge: Int): Size {
|
||||
val longEdge = minOf(max(sourceWidth, sourceHeight), maxLongEdge.coerceAtLeast(1))
|
||||
return if (sourceWidth >= sourceHeight) {
|
||||
|
||||
@@ -55,7 +55,6 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import coil.request.ImageRequest
|
||||
import com.hinnka.mycamera.BuildConfig
|
||||
import com.hinnka.mycamera.R
|
||||
import me.saket.telephoto.zoomable.coil.ZoomableAsyncImage
|
||||
import me.saket.telephoto.zoomable.rememberZoomableImageState
|
||||
@@ -282,8 +281,7 @@ fun GalleryEditScreen(
|
||||
val editRawBaselineRecipeParams by viewModel.editRawBaselineRecipeParams.collectAsState()
|
||||
val editRawColorEngine by viewModel.editRawRenderingEngine.collectAsState()
|
||||
val editRawToneMappingParameters by viewModel.editRawToneMappingParameters.collectAsState()
|
||||
val forceRegeneratePhotonPgtmOnRefresh =
|
||||
BuildConfig.DEBUG && editRawToneMappingParameters.usePhotonHdr
|
||||
val forceRegeneratePhotonPgtmOnRefresh = editRawToneMappingParameters.usePhotonHdr
|
||||
val editRawSpectralFilmStock by viewModel.editRawSpectralFilmStock.collectAsState()
|
||||
val editRawSpectralFilmPrint by viewModel.editRawSpectralFilmPrint.collectAsState()
|
||||
val editRawSpectralFilmCDensityGain by viewModel.editRawSpectralFilmCDensityGain.collectAsState()
|
||||
|
||||
@@ -842,7 +842,7 @@ object RawProcessor {
|
||||
"sourceBaselineEv=$sourceBaselineExposureEv " +
|
||||
"sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " +
|
||||
"legacyExposureOffsetEv=$legacyExposureOffsetEv " +
|
||||
"sourceBaselinePreserved=true " +
|
||||
"baselineExposureSource=SOURCE_PLUS_LEGACY_AE " +
|
||||
"finalBaselineEv=${finalProfile.baselineExposureEv} " +
|
||||
"finalBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " +
|
||||
"pgtm=${finalProfile.profileGainTableMap != null} " +
|
||||
|
||||
@@ -861,11 +861,11 @@
|
||||
<string name="settings_raw_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自適應曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇照片的亮度處理方式。關閉時兩種功能都不使用;光子 HDR 能保留更多明暗細節;經典自動曝光會盡量符合拍攝時看到的亮度。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自動曝光與 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典自動曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典 HDR</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -879,11 +879,11 @@
|
||||
<string name="settings_raw_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差较大的场景中保留更多高光和暗部细节,让画面亮度过渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">为当前照片启用光子 HDR。即使拍摄时使用经典自动曝光,也可以重新开启。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自适应曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">选择照片的亮度处理方式。关闭时两种功能都不使用;光子 HDR 能保留更多明暗细节;经典自动曝光会尽量匹配拍摄时看到的亮度。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自动曝光与 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">两种模式都会先自动测光确定曝光基准,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 与 HDRNet,经典 HDR 使用局部拉普拉斯;关闭时不进行自动测光或 HDR 映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">关闭</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">经典自动曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">经典 HDR</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相对曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相对曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -861,11 +861,11 @@
|
||||
<string name="settings_raw_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自適應曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇照片的亮度處理方式。關閉時兩種功能都不使用;光子 HDR 能保留更多明暗細節;經典自動曝光會盡量符合拍攝時看到的亮度。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自動曝光與 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典自動曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典 HDR</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -861,11 +861,11 @@
|
||||
<string name="settings_raw_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片啟用光子 HDR。即使拍攝時使用經典自動曝光,也可以重新開啟。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自適應曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇照片的亮度處理方式。關閉時兩種功能都不使用;光子 HDR 能保留更多明暗細節;經典自動曝光會盡量符合拍攝時看到的亮度。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW 自動曝光與 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">兩種模式都會先自動測光確定曝光基準,再以不同方式完成 HDR 映射:光子 HDR 使用 ML AE 與 HDRNet,經典 HDR 使用局部拉普拉斯;關閉時不進行自動測光或 HDR 映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">光子 HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典自動曝光</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">經典 HDR</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -865,11 +865,11 @@
|
||||
<string name="settings_raw_photon_hdr">Photon HDR</string>
|
||||
<string name="settings_raw_photon_hdr_description">Preserves more highlight and shadow detail in high-contrast scenes for more natural tonal transitions.</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">Enable Photon HDR for this photo. It can also be enabled for photos captured with Classic Auto Exposure.</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">Adaptive RAW Exposure</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">Choose how the photo’s brightness is handled. Off skips both options; Photon HDR preserves more highlight and shadow detail; Classic Auto Exposure aims to match the brightness seen while shooting.</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">RAW Auto Exposure & HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">Both modes meter the scene to establish an exposure baseline, then apply different HDR mapping: Photon HDR uses ML AE with HDRNet, while Classic HDR uses Local Laplacian mapping. Off disables automatic metering and HDR mapping.</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">Off</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">Photon HDR</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">Classic Auto Exposure</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">Classic HDR</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX White Relative Exposure</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX Black Relative Exposure</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX Shoulder</string>
|
||||
|
||||
Reference in new issue
Block a user