Fix RAW viewfinder exposure matching

This commit is contained in:
zhoubinjia committed 2026-07-22 20:25:54 +08:00
1 parent 1ede1d361f
commit 05891a043e
4 files changed
+402 -45

No files matched your search

@@ -1524,12 +1524,18 @@ class LutRenderer : GLSurfaceView.Renderer {
}
}
if (meteringEnabled && activeVideoRecorder == null) {
runMeteringInternal(
sourceTextureId = finalDisplayTextureId,
sourceWidth = finalDisplayWidth,
sourceHeight = finalDisplayHeight,
compositeWithHdf = needsHdfCompositeForSampling
)
// Metering must observe the same LUT-free source used by Original preview
// capture. Feeding finalDisplayTextureId here makes the current user-selected
// 3D LUT part of the exposure loop and therefore biases the captured RAW.
if (rawPreviewSource != null) {
runMeteringInternal(
sourceTextureId = rawPreviewSource.textureId,
sourceWidth = viewportWidth,
sourceHeight = viewportHeight,
)
} else {
runMeteringInternal()
}
}
} else {
// 直接渲染到屏幕
@@ -3022,7 +3028,9 @@ class LutRenderer : GLSurfaceView.Renderer {
fboId = meteringFboId,
width = METERING_SIZE,
height = METERING_SIZE,
targetMvpMatrix = buildMvpMatrix(METERING_SIZE, METERING_SIZE)
targetMvpMatrix = buildMvpMatrix(METERING_SIZE, METERING_SIZE),
suppressBaselineLayer = true,
suppressCreativeLayer = true,
)
}
@@ -3,9 +3,12 @@ package com.hinnka.mycamera.raw
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Rect
import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.RawBlackBorderCrop
import com.hinnka.mycamera.utils.PLog
import java.io.File
import java.io.FileOutputStream
import kotlin.math.max
internal data class RawExposurePreviewFrame(
@@ -24,6 +27,12 @@ internal data class RawExposurePreviewFrame(
internal object RawViewfinderExposureMatcher {
private const val TAG = "RawViewfinderExposureMatcher"
private const val PREVIEW_LONG_EDGE = 256
private const val DIAGNOSTIC_DIRECTORY = "raw_viewfinder_exposure_match"
private data class ViewfinderReference(
val analysis: RawViewfinderExposureMath.Reference,
val frame: RawExposurePreviewFrame,
)
suspend fun prepareCaptureProfile(
renderer: RawDemosaicProcessor,
@@ -47,9 +56,15 @@ internal object RawViewfinderExposureMatcher {
}
val request = reference?.let {
RawExposurePreviewRequest(
width = it.width,
height = it.height,
solve = { renderSample -> solve(it, renderSample) },
width = it.analysis.width,
height = it.analysis.height,
solve = { renderSample ->
solve(
context = context,
reference = it,
renderSample = renderSample,
)
},
)
}
return renderer.prepareCaptureProfile(
@@ -69,13 +84,13 @@ internal object RawViewfinderExposureMatcher {
)
}
private fun buildReference(bitmap: Bitmap): RawViewfinderExposureMath.Reference? {
private fun buildReference(bitmap: Bitmap): ViewfinderReference? {
if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return null
return try {
val size = longEdgeSize(bitmap.width, bitmap.height, PREVIEW_LONG_EDGE)
val pixels = sampleBitmap(bitmap, size.width, size.height)
val bounds = centerTwoThirdsBounds(size.width, size.height) ?: return null
RawViewfinderExposureMath.buildReference(
val analysis = RawViewfinderExposureMath.buildReference(
pixels = pixels,
width = size.width,
height = size.height,
@@ -83,6 +98,14 @@ internal object RawViewfinderExposureMatcher {
top = bounds.top,
right = bounds.right,
bottom = bounds.bottom,
) ?: return null
ViewfinderReference(
analysis = analysis,
frame = RawExposurePreviewFrame(
width = size.width,
height = size.height,
argbPixels = pixels,
),
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to analyze capture preview", e)
@@ -91,11 +114,130 @@ internal object RawViewfinderExposureMatcher {
}
private fun solve(
reference: RawViewfinderExposureMath.Reference,
context: Context,
reference: ViewfinderReference,
renderSample: (Float) -> RawExposurePreviewFrame?,
): Float? {
return RawViewfinderExposureMath.solve { exposureEv ->
evaluate(reference, exposureEv, renderSample(exposureEv))
val solvedExposureEv = RawViewfinderExposureMath.solve { exposureEv ->
evaluate(reference.analysis, exposureEv, renderSample(exposureEv))
}
if (BuildConfig.DEBUG && solvedExposureEv != null) {
val solvedFrame = renderSample(solvedExposureEv)
if (solvedFrame != null &&
solvedFrame.width == reference.frame.width &&
solvedFrame.height == reference.frame.height
) {
saveDiagnosticFrames(
context = context,
reference = reference,
candidate = solvedFrame,
solvedExposureEv = solvedExposureEv,
)
} else {
PLog.w(
TAG,
"RAW viewfinder diagnostic skipped: solved candidate frame is unavailable " +
"exposureEv=$solvedExposureEv " +
"reference=${reference.frame.width}x${reference.frame.height} " +
"candidate=${solvedFrame?.let { "${it.width}x${it.height}" } ?: "null"}",
)
}
}
return solvedExposureEv
}
private fun saveDiagnosticFrames(
context: Context,
reference: ViewfinderReference,
candidate: RawExposurePreviewFrame,
solvedExposureEv: Float,
) {
val rootDirectory = File(context.cacheDir, DIAGNOSTIC_DIRECTORY)
if (!rootDirectory.exists() && !rootDirectory.mkdirs()) {
PLog.w(TAG, "Unable to create RAW viewfinder diagnostic directory: $rootDirectory")
return
}
val directory = File(rootDirectory, System.currentTimeMillis().toString())
if (!directory.mkdirs()) {
PLog.w(TAG, "Unable to create RAW viewfinder capture directory: $directory")
return
}
val referenceFile = File(directory, "reference.png")
val candidateFile = File(directory, "candidate.png")
val referenceRoiFile = File(directory, "reference_roi.png")
val candidateRoiFile = File(directory, "candidate_roi.png")
val bounds = Rect(
reference.analysis.left,
reference.analysis.top,
reference.analysis.right,
reference.analysis.bottom,
)
val referenceBitmap = Bitmap.createBitmap(
reference.frame.argbPixels,
reference.frame.width,
reference.frame.height,
Bitmap.Config.ARGB_8888,
)
val candidateBitmap = Bitmap.createBitmap(
candidate.argbPixels,
candidate.width,
candidate.height,
Bitmap.Config.ARGB_8888,
)
var referenceRoiBitmap: Bitmap? = null
var candidateRoiBitmap: Bitmap? = null
try {
val referenceRoi = Bitmap.createBitmap(
referenceBitmap,
bounds.left,
bounds.top,
bounds.width(),
bounds.height(),
)
val candidateRoi = Bitmap.createBitmap(
candidateBitmap,
bounds.left,
bounds.top,
bounds.width(),
bounds.height(),
)
referenceRoiBitmap = referenceRoi
candidateRoiBitmap = candidateRoi
val saved = listOf(
writePng(referenceBitmap, referenceFile),
writePng(candidateBitmap, candidateFile),
writePng(referenceRoi, referenceRoiFile),
writePng(candidateRoi, candidateRoiFile),
).all { it }
if (saved) {
PLog.i(
TAG,
"RAW viewfinder diagnostic saved: exposureEv=$solvedExposureEv " +
"size=${candidate.width}x${candidate.height} roi=$bounds " +
"reference=${referenceFile.absolutePath} " +
"candidate=${candidateFile.absolutePath} " +
"referenceRoi=${referenceRoiFile.absolutePath} " +
"candidateRoi=${candidateRoiFile.absolutePath}",
)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to save RAW viewfinder diagnostic frames", e)
} finally {
referenceRoiBitmap?.recycle()
candidateRoiBitmap?.recycle()
referenceBitmap.recycle()
candidateBitmap.recycle()
}
}
private fun writePng(bitmap: Bitmap, file: File): Boolean {
return try {
FileOutputStream(file, false).use { output ->
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to write RAW viewfinder diagnostic PNG: $file", e)
false
}
}
@@ -115,13 +257,22 @@ internal object RawViewfinderExposureMatcher {
) ?: return null
PLog.d(
TAG,
"RAW viewfinder sample: exposureEv=$exposureEv " +
"RAW viewfinder sample: exposureEv=$exposureEv " +
"matchLog2Error=${match.matchLog2Error} " +
"shadowPriorityTrimmedLog2Error=${match.toneWeightedLog2Error} " +
"linearArithmeticMeanLog2Error=${match.linearArithmeticMeanLog2Error} " +
"linearLogAverageLog2Error=${match.linearLogAverageLog2Error} " +
"perceptualArithmeticMeanLog2Error=${match.meanBrightnessLog2Error} " +
"perceptualLogAverageLog2Error=${match.perceptualLogAverageLog2Error} " +
"p50PerceptualLog2Error=${match.p50Log2Error} " +
"quantileLog2Errors=${match.quantileLog2Errors.contentToString()} " +
"quantileMedianLog2Error=${match.quantileMedianLog2Error} " +
"quantileTrimmedMeanLog2Error=${match.quantileTrimmedMeanLog2Error} " +
"solverQuantileTrimmedLog2Error=${match.quantileTrimmedMeanLog2Error} " +
"quantileSpreadLog2=${match.quantileSpreadLog2} " +
"referenceSampleCount=${match.referenceSampleCount} " +
"candidateSampleCount=${match.candidateSampleCount} " +
"referenceDisplayLinearLumaMean=${match.referenceDisplayLinearLumaMean} " +
"candidateDisplayLinearLumaMean=${match.candidateDisplayLinearLumaMean} " +
"referencePerceptualBrightnessMean=" +
"${match.referencePerceptualBrightnessMean} " +
"candidatePerceptualBrightnessMean=" +
@@ -9,13 +9,16 @@ import kotlin.math.pow
*
* Both inputs are tone-mapped 8-bit sRGB previews. Converting their surviving code values back
* to display-linear light does not recover scene-linear RAW data; it only makes the logarithmic
* ratio describe a ratio of displayed light. Overall exposure is matched from the mean perceived
* brightness of the same fixed image area, including displayed black and white endpoints. This
* remains defined when local tone mapping changes the shape of the tonal distribution and does not
* require pixel correspondence. Quantile shifts are retained only as diagnostics for that shape.
* ratio describe a ratio of displayed light. Overall exposure is matched primarily from a robust,
* center-weighted estimate of fixed tonal-distribution quantiles. Trimming the conflicting error
* tails prevents one crushed shadow or clipped highlight band from controlling the result. The
* perceptual arithmetic mean keeps the complete fixed image area, including displayed black and
* white endpoints, as a global guardrail. This remains defined when local tone mapping changes the
* shape of the tonal distribution and does not require pixel correspondence.
*/
internal object RawViewfinderExposureMath {
private const val PERCEPTUAL_BRIGHTNESS_FLOOR = 1f / 255f
private const val DISPLAY_LINEAR_LUMA_FLOOR = 1f / (255f * 12.92f)
private const val MIN_SAMPLE_COUNT = 32
private const val QUANTILE_TRIM_LOW_FRACTION = 0.15f
private const val QUANTILE_TRIM_HIGH_FRACTION = 0.85f
@@ -31,7 +34,14 @@ internal object RawViewfinderExposureMath {
0.70f,
0.80f,
)
private val MATCH_QUANTILE_WEIGHTS = floatArrayOf(1f, 2f, 3f, 4f, 3f, 2f, 1f)
private const val P50_QUANTILE_INDEX = 3
// Retained as a diagnostic for comparing the former shadow-priority target in real scenes.
private val SHADOW_PRIORITY_QUANTILE_WEIGHTS =
floatArrayOf(3f, 4f, 5f, 5f, 4f, 2f, 1f)
// The solver excludes the deepest and brightest 20%, then favors the stable distribution center.
private val SOLVER_QUANTILE_WEIGHTS = floatArrayOf(1f, 2f, 3f, 4f, 3f, 2f, 1f)
private const val TRIMMED_QUANTILE_ERROR_WEIGHT = 0.70f
private const val MEAN_BRIGHTNESS_ERROR_WEIGHT = 1f - TRIMMED_QUANTILE_ERROR_WEIGHT
private const val MAX_SOLVE_STEPS = 4
private const val MATCH_LOG2_TOLERANCE = 0.05f
@@ -52,33 +62,53 @@ internal object RawViewfinderExposureMath {
val right: Int,
val bottom: Int,
val targetLog2PerceptualBrightness: Float,
val targetLog2DisplayLinearLumaMean: Float,
val targetMeanLog2DisplayLinearLuma: Float,
val targetMeanLog2PerceptualBrightness: Float,
val targetQuantileLog2Lumas: FloatArray,
val sampleCount: Int,
val displayLinearLumaMean: Float,
val perceptualBrightnessMean: Float,
) {
init {
require(targetLog2PerceptualBrightness.isFinite())
require(targetLog2DisplayLinearLumaMean.isFinite())
require(targetMeanLog2DisplayLinearLuma.isFinite())
require(targetMeanLog2PerceptualBrightness.isFinite())
require(targetQuantileLog2Lumas.size == MATCH_QUANTILES.size)
require(targetQuantileLog2Lumas.all { it.isFinite() })
require(sampleCount >= MIN_SAMPLE_COUNT)
require(displayLinearLumaMean.isFinite() && displayLinearLumaMean >= 0f)
require(perceptualBrightnessMean.isFinite() && perceptualBrightnessMean >= 0f)
}
}
data class MatchResult(
val matchLog2Error: Float,
val toneWeightedLog2Error: Float,
val meanBrightnessLog2Error: Float,
val linearArithmeticMeanLog2Error: Float,
val linearLogAverageLog2Error: Float,
val perceptualLogAverageLog2Error: Float,
val p50Log2Error: Float,
val quantileLog2Errors: FloatArray,
val quantileMedianLog2Error: Float,
val quantileTrimmedMeanLog2Error: Float,
val quantileSpreadLog2: Float,
val referenceSampleCount: Int,
val candidateSampleCount: Int,
val referenceDisplayLinearLumaMean: Float,
val candidateDisplayLinearLumaMean: Float,
val referencePerceptualBrightnessMean: Float,
val candidatePerceptualBrightnessMean: Float,
)
private data class LumaDistribution(
val sortedLog2PerceptualBrightness: FloatArray,
val displayLinearLumaMean: Float,
val meanLog2DisplayLinearLuma: Float,
val perceptualBrightnessMean: Float,
val meanLog2PerceptualBrightness: Float,
val sampleCount: Int,
)
@@ -124,8 +154,14 @@ internal object RawViewfinderExposureMath {
PERCEPTUAL_BRIGHTNESS_FLOOR
)
),
targetLog2DisplayLinearLumaMean = log2(
distribution.displayLinearLumaMean.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR)
),
targetMeanLog2DisplayLinearLuma = distribution.meanLog2DisplayLinearLuma,
targetMeanLog2PerceptualBrightness = distribution.meanLog2PerceptualBrightness,
targetQuantileLog2Lumas = distribution.quantiles(),
sampleCount = distribution.sampleCount,
displayLinearLumaMean = distribution.displayLinearLumaMean,
perceptualBrightnessMean = distribution.perceptualBrightnessMean,
)
}
@@ -156,34 +192,68 @@ internal object RawViewfinderExposureMath {
val meanBrightnessError = log2(
distribution.perceptualBrightnessMean.coerceAtLeast(PERCEPTUAL_BRIGHTNESS_FLOOR)
) - reference.targetLog2PerceptualBrightness
val linearArithmeticMeanError = log2(
distribution.displayLinearLumaMean.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR)
) - reference.targetLog2DisplayLinearLumaMean
val linearLogAverageError =
distribution.meanLog2DisplayLinearLuma - reference.targetMeanLog2DisplayLinearLuma
val perceptualLogAverageError =
distribution.meanLog2PerceptualBrightness -
reference.targetMeanLog2PerceptualBrightness
val quantileErrors = FloatArray(MATCH_QUANTILES.size) { index ->
candidateQuantiles[index] - reference.targetQuantileLog2Lumas[index]
}
val quantileWeights = MATCH_QUANTILE_WEIGHTS.copyOf()
sortPairsByFirst(quantileErrors, quantileWeights)
val quantileWeightSum = quantileWeights.sumOf { it.toDouble() }
val median = weightedMedian(quantileErrors, quantileWeights, quantileWeightSum)
val p50Error = quantileErrors[P50_QUANTILE_INDEX]
val sortedToneErrors = quantileErrors.copyOf()
val toneWeights = SHADOW_PRIORITY_QUANTILE_WEIGHTS.copyOf()
sortPairsByFirst(sortedToneErrors, toneWeights)
val toneWeightSum = toneWeights.sumOf { it.toDouble() }
val toneWeightedError = weightedTrimmedMean(
sortedValues = sortedToneErrors,
sortedWeights = toneWeights,
weightSum = toneWeightSum,
lowFraction = QUANTILE_TRIM_LOW_FRACTION,
highFraction = QUANTILE_TRIM_HIGH_FRACTION,
)
val sortedQuantileErrors = quantileErrors.copyOf()
val solverWeights = SOLVER_QUANTILE_WEIGHTS.copyOf()
sortPairsByFirst(sortedQuantileErrors, solverWeights)
val solverWeightSum = solverWeights.sumOf { it.toDouble() }
val median = weightedMedian(
sortedQuantileErrors,
solverWeights,
solverWeightSum,
)
val trimmedMean = weightedTrimmedMean(
sortedValues = quantileErrors,
sortedWeights = quantileWeights,
weightSum = quantileWeightSum,
sortedValues = sortedQuantileErrors,
sortedWeights = solverWeights,
weightSum = solverWeightSum,
lowFraction = QUANTILE_TRIM_LOW_FRACTION,
highFraction = QUANTILE_TRIM_HIGH_FRACTION,
)
val spreadLow = weightedQuantile(
quantileErrors,
quantileWeights,
quantileWeightSum,
sortedQuantileErrors,
solverWeights,
solverWeightSum,
QUANTILE_SPREAD_LOW_FRACTION,
)
val spreadHigh = weightedQuantile(
quantileErrors,
quantileWeights,
quantileWeightSum,
sortedQuantileErrors,
solverWeights,
solverWeightSum,
QUANTILE_SPREAD_HIGH_FRACTION,
)
val quantileSpread = (spreadHigh - spreadLow).coerceAtLeast(0f)
val matchError =
TRIMMED_QUANTILE_ERROR_WEIGHT * trimmedMean +
MEAN_BRIGHTNESS_ERROR_WEIGHT * meanBrightnessError
if (!meanBrightnessError.isFinite() ||
!linearArithmeticMeanError.isFinite() ||
!linearLogAverageError.isFinite() ||
!perceptualLogAverageError.isFinite() ||
!p50Error.isFinite() ||
!toneWeightedError.isFinite() ||
!matchError.isFinite() ||
!median.isFinite() ||
!trimmedMean.isFinite() ||
!quantileSpread.isFinite()
@@ -191,12 +261,21 @@ internal object RawViewfinderExposureMath {
return null
}
return MatchResult(
matchLog2Error = meanBrightnessError,
matchLog2Error = matchError,
toneWeightedLog2Error = toneWeightedError,
meanBrightnessLog2Error = meanBrightnessError,
linearArithmeticMeanLog2Error = linearArithmeticMeanError,
linearLogAverageLog2Error = linearLogAverageError,
perceptualLogAverageLog2Error = perceptualLogAverageError,
p50Log2Error = p50Error,
quantileLog2Errors = quantileErrors,
quantileMedianLog2Error = median,
quantileTrimmedMeanLog2Error = trimmedMean,
quantileSpreadLog2 = quantileSpread,
referenceSampleCount = reference.sampleCount,
candidateSampleCount = distribution.sampleCount,
referenceDisplayLinearLumaMean = reference.displayLinearLumaMean,
candidateDisplayLinearLumaMean = distribution.displayLinearLumaMean,
referencePerceptualBrightnessMean = reference.perceptualBrightnessMean,
candidatePerceptualBrightnessMean = distribution.perceptualBrightnessMean,
)
@@ -214,26 +293,49 @@ internal object RawViewfinderExposureMath {
if (capacity <= 0) return null
val log2PerceptualBrightness = FloatArray(capacity)
var sampleCount = 0
var displayLinearLumaSum = 0.0
var log2DisplayLinearLumaSum = 0.0
var perceptualBrightnessSum = 0.0
var log2PerceptualBrightnessSum = 0.0
for (y in top until bottom) {
for (x in left until right) {
val luma = displayLinearLuma(pixels[y * width + x]) ?: continue
val perceptualBrightness = linearToSrgb(luma)
perceptualBrightnessSum += perceptualBrightness.toDouble()
log2PerceptualBrightness[sampleCount] = log2(
val log2DisplayLinearLuma = log2(
luma.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR)
)
val log2Perceptual = log2(
perceptualBrightness.coerceAtLeast(PERCEPTUAL_BRIGHTNESS_FLOOR)
)
displayLinearLumaSum += luma.toDouble()
log2DisplayLinearLumaSum += log2DisplayLinearLuma.toDouble()
perceptualBrightnessSum += perceptualBrightness.toDouble()
log2PerceptualBrightnessSum += log2Perceptual.toDouble()
log2PerceptualBrightness[sampleCount] = log2Perceptual
sampleCount++
}
}
if (sampleCount < MIN_SAMPLE_COUNT) return null
val sortedBrightness = log2PerceptualBrightness.copyOf(sampleCount)
sortedBrightness.sort()
val displayLinearLumaMean = (displayLinearLumaSum / sampleCount).toFloat()
val meanLog2DisplayLinearLuma = (log2DisplayLinearLumaSum / sampleCount).toFloat()
val perceptualBrightnessMean = (perceptualBrightnessSum / sampleCount).toFloat()
if (!perceptualBrightnessMean.isFinite()) return null
val meanLog2PerceptualBrightness =
(log2PerceptualBrightnessSum / sampleCount).toFloat()
if (!displayLinearLumaMean.isFinite() ||
!meanLog2DisplayLinearLuma.isFinite() ||
!perceptualBrightnessMean.isFinite() ||
!meanLog2PerceptualBrightness.isFinite()
) {
return null
}
return LumaDistribution(
sortedLog2PerceptualBrightness = sortedBrightness,
displayLinearLumaMean = displayLinearLumaMean,
meanLog2DisplayLinearLuma = meanLog2DisplayLinearLuma,
perceptualBrightnessMean = perceptualBrightnessMean,
meanLog2PerceptualBrightness = meanLog2PerceptualBrightness,
sampleCount = sampleCount,
)
}
@@ -25,6 +25,15 @@ class RawViewfinderExposureMathTest {
assertNotNull(match)
val expected = log2(srgbCode(0.36f) / srgbCode(0.18f))
assertEquals(expected, match!!.matchLog2Error, 0.001f)
assertEquals(
match.linearArithmeticMeanLog2Error,
match.linearLogAverageLog2Error,
0.001f,
)
assertEquals(expected, match.meanBrightnessLog2Error, 0.001f)
assertEquals(expected, match.perceptualLogAverageLog2Error, 0.001f)
assertEquals(expected, match.p50Log2Error, 0.001f)
assertTrue(match.linearArithmeticMeanLog2Error > match.meanBrightnessLog2Error)
assertTrue(match.matchLog2Error > 0f)
}
@@ -107,7 +116,7 @@ class RawViewfinderExposureMathTest {
}
@Test
fun opposingTonalShiftsStillProduceOverallBrightnessError() {
fun opposingTonalShiftsPreferDarkAndMidtoneAppearance() {
val width = 10
val height = 10
val referencePixels = IntArray(width * height) { index ->
@@ -127,12 +136,96 @@ class RawViewfinderExposureMathTest {
assertNotNull(match)
assertTrue(match!!.quantileSpreadLog2 > 0.75f)
assertTrue(match.matchLog2Error.isFinite())
val expected = log2(
val expectedMeanError = log2(
match.candidatePerceptualBrightnessMean /
match.referencePerceptualBrightnessMean
)
assertEquals(expected, match.matchLog2Error, 0.001f)
assertEquals(expectedMeanError, match.meanBrightnessLog2Error, 0.001f)
assertTrue("Brighter highlights should raise the global mean", expectedMeanError > 0f)
assertEquals(
0.70f * match.quantileTrimmedMeanLog2Error +
0.30f * match.meanBrightnessLog2Error,
match.matchLog2Error,
0.0001f,
)
assertTrue(
"Dark and midtone deficits should control the exposure target",
match.matchLog2Error < 0f,
)
assertTrue(match.toneWeightedLog2Error < match.matchLog2Error)
}
@Test
fun isolatedDeepShadowMismatchCannotControlOverallExposure() {
val width = 16
val height = 10
val darkEnd = width * height / 4
val highlightStart = width * height * 3 / 4
val referencePixels = IntArray(width * height) { index ->
grayscaleArgb(
when {
index < darkEnd -> 0.04f
index < highlightStart -> 0.18f
else -> 0.64f
}
)
}
val candidatePixels = IntArray(width * height) { index ->
grayscaleArgb(
when {
index < darkEnd -> 0.001f
index < highlightStart -> 0.18f
else -> 0.64f
}
)
}
val match = RawViewfinderExposureMath.evaluate(
reference = buildReference(referencePixels, width, height),
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertTrue(match!!.quantileLog2Errors.first() < -3f)
assertEquals(0f, match.toneWeightedLog2Error, 0.001f)
assertTrue(match.meanBrightnessLog2Error < 0f)
assertTrue(
"The full-image guardrail may react, but the crushed tail must not dominate",
match.matchLog2Error > -0.05f,
)
}
@Test
fun solverLiftsDarkAndMidtonesWhenHighlightsConflict() {
val width = 16
val height = 16
val highlightStart = width * height * 3 / 4
val referencePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index < highlightStart) 0.08f else 0.64f)
}
val reference = buildReference(referencePixels, width, height)
val solvedEv = RawViewfinderExposureMath.solve { exposureEv ->
val exposureGain = 2f.pow(exposureEv)
val candidatePixels = IntArray(width * height) { index ->
val baseLuma = if (index < highlightStart) 0.04f else 0.64f
grayscaleArgb(baseLuma * exposureGain)
}
RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)?.matchLog2Error
}
assertNotNull(solvedEv)
assertTrue(
"The solver should accept brighter highlights to restore the darker majority",
solvedEv!! > 0.8f,
)
assertTrue(solvedEv < 1.2f)
}
@Test
@@ -177,8 +270,11 @@ class RawViewfinderExposureMathTest {
}
assertNotNull(solvedEv)
assertTrue(solvedEv!! > 1f)
assertTrue(solvedEv < 2f)
assertTrue(
"The darker majority should remain the exposure target after highlights clip",
solvedEv!! > 2f,
)
assertTrue(solvedEv <= MeteringSystem.RAW_EXPOSURE_MAX_EV)
}
@Test