feat: new RawViewfinderExposureMatcher

This commit is contained in:
Hinnka committed 2026-08-02 22:39:03 +08:00
1 parent ce0c4e1129
commit 72cc577813
4 files changed
+295 -66

No files matched your search

+2 -2
View File
@@ -26,8 +26,8 @@ android {
applicationId = "com.hinnka.mycamera"
minSdk = 30
targetSdk = 36
versionCode = 140
versionName = "1.26.0.1"
versionCode = 141
versionName = "1.26.0.2test"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -125,6 +125,7 @@ internal object RawViewfinderExposureMatcher {
testImageCache: ExposureMatchTestImageCache?,
): Float? {
var candidateIndex = 0
var meteringSelection: RawViewfinderExposureMath.MeteringSelection? = null
return RawViewfinderExposureMath.solve { exposureEv ->
val frame = renderSample(exposureEv)
if (frame != null) {
@@ -134,17 +135,51 @@ internal object RawViewfinderExposureMatcher {
frame = frame,
)
}
if (candidateIndex == 0 &&
frame != null &&
frame.width == reference.analysis.width &&
frame.height == reference.analysis.height
) {
meteringSelection = RawViewfinderExposureMath.buildMeteringSelection(
reference = reference.analysis,
pixels = frame.argbPixels,
width = frame.width,
height = frame.height,
)
meteringSelection?.let { selection ->
PLog.d(
TAG,
"RAW metering selection: seedExposureEv=$exposureEv " +
"candidateDisplayLinearLumaP50=" +
"${selection.seedCandidateDisplayLinearLumaP50} " +
"candidateDisplayLinearLumaRange=" +
"[${selection.seedCandidateDisplayLinearLumaRangeMin}, " +
"${selection.seedCandidateDisplayLinearLumaRangeMax}] " +
"sampleCount=${selection.sampleCount}"
)
}
}
candidateIndex++
evaluate(reference.analysis, exposureEv, frame)
evaluate(
reference = reference.analysis,
meteringSelection = meteringSelection,
exposureEv = exposureEv,
frame = frame,
)
}
}
private fun evaluate(
reference: RawViewfinderExposureMath.Reference,
meteringSelection: RawViewfinderExposureMath.MeteringSelection?,
exposureEv: Float,
frame: RawExposurePreviewFrame?,
): Float? {
if (frame == null || frame.width != reference.width || frame.height != reference.height) {
if (meteringSelection == null ||
frame == null ||
frame.width != reference.width ||
frame.height != reference.height
) {
return null
}
val match = RawViewfinderExposureMath.evaluate(
@@ -152,6 +187,7 @@ internal object RawViewfinderExposureMatcher {
pixels = frame.argbPixels,
width = frame.width,
height = frame.height,
meteringSelection = meteringSelection,
) ?: return null
val meteringLog2Error = match.meteringLog2Error
PLog.d(
@@ -9,18 +9,18 @@ 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. Capture metering selects coordinates where the
* rendered RAW candidate has display-linear luma in [0.05, 0.32], then compares the candidate and
* viewfinder arithmetic means over exactly those coordinates. The selection is recomputed for every
* exposure candidate. Distribution quantiles and full-area means remain available as diagnostics
* for local tone-map differences.
* ratio describe a ratio of displayed light. Capture metering builds one fixed coordinate set from
* the first rendered RAW candidate: it starts around that candidate's display-linear P50 and expands
* symmetrically only when the band contains too few valid corresponding pixels. Every exposure
* candidate is then compared with the viewfinder over that same coordinate set. Distribution
* quantiles and full-area means remain available as diagnostics for local tone-map differences.
*/
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 CANDIDATE_METERING_LUMA_MIN = 0.05f
private const val CANDIDATE_METERING_LUMA_MAX = 0.32f
private const val INITIAL_P50_METERING_HALF_RANGE = 0.01f
private const val METERING_RANGE_EPSILON = 1e-6f
private const val QUANTILE_TRIM_LOW_FRACTION = 0.15f
private const val QUANTILE_TRIM_HIGH_FRACTION = 0.85f
private const val QUANTILE_SPREAD_LOW_FRACTION = 0.15f
@@ -118,6 +118,31 @@ internal object RawViewfinderExposureMath {
val candidatePerceptualBrightnessMean: Float,
)
class MeteringSelection internal constructor(
internal val pixelIndices: IntArray,
internal val referenceDisplayLinearLumas: FloatArray,
val seedCandidateDisplayLinearLumaP50: Float,
val seedCandidateDisplayLinearLumaRangeMin: Float,
val seedCandidateDisplayLinearLumaRangeMax: Float,
) {
val sampleCount: Int
get() = pixelIndices.size
init {
require(pixelIndices.size >= MIN_SAMPLE_COUNT)
require(referenceDisplayLinearLumas.size == pixelIndices.size)
require(referenceDisplayLinearLumas.all { it.isFinite() && it in 0f..1f })
require(seedCandidateDisplayLinearLumaP50.isFinite())
require(seedCandidateDisplayLinearLumaRangeMin.isFinite())
require(seedCandidateDisplayLinearLumaRangeMax.isFinite())
require(
seedCandidateDisplayLinearLumaP50 in
seedCandidateDisplayLinearLumaRangeMin..
seedCandidateDisplayLinearLumaRangeMax
)
}
}
private data class LumaDistribution(
val sortedLog2PerceptualBrightness: FloatArray,
val displayLinearLumaMean: Float,
@@ -202,6 +227,28 @@ internal object RawViewfinderExposureMath {
pixels: IntArray,
width: Int,
height: Int,
): MatchResult? {
val meteringSelection = buildMeteringSelection(
reference = reference,
pixels = pixels,
width = width,
height = height,
) ?: return null
return evaluate(
reference = reference,
pixels = pixels,
width = width,
height = height,
meteringSelection = meteringSelection,
)
}
fun evaluate(
reference: Reference,
pixels: IntArray,
width: Int,
height: Int,
meteringSelection: MeteringSelection,
): MatchResult? {
if (width != reference.width ||
height != reference.height ||
@@ -220,9 +267,8 @@ internal object RawViewfinderExposureMath {
bottom = reference.bottom,
) ?: return null
val metering = evaluateMetering(
reference = reference,
pixels = pixels,
width = width,
selection = meteringSelection,
)
val meteringError = metering?.log2Error
val candidateQuantiles = distribution.quantiles()
@@ -344,32 +390,90 @@ internal object RawViewfinderExposureMath {
return lumas
}
private fun evaluateMetering(
fun buildMeteringSelection(
reference: Reference,
pixels: IntArray,
width: Int,
): MeteringEvaluation? {
height: Int,
): MeteringSelection? {
if (width != reference.width ||
height != reference.height ||
pixels.size < width * height
) {
return null
}
val capacity = (reference.right - reference.left) *
(reference.bottom - reference.top)
val candidateLumas = FloatArray(capacity)
val pixelIndices = IntArray(capacity)
val referenceLumas = FloatArray(capacity)
var validPairCount = 0
var referenceLumaIndex = 0
var sampleCount = 0
var referenceLumaSum = 0.0
var candidateLumaSum = 0.0
for (y in reference.top until reference.bottom) {
for (x in reference.left until reference.right) {
val referenceLuma =
reference.meteringReferenceDisplayLinearLumas[referenceLumaIndex++]
val candidateLuma =
displayLinearLuma(pixels[y * width + x]) ?: continue
if (candidateLuma !in
CANDIDATE_METERING_LUMA_MIN..CANDIDATE_METERING_LUMA_MAX ||
!referenceLuma.isFinite()
) {
continue
}
referenceLumaSum += referenceLuma
candidateLumaSum += candidateLuma
sampleCount++
val pixelIndex = y * width + x
val candidateLuma = displayLinearLuma(pixels[pixelIndex]) ?: continue
if (!referenceLuma.isFinite()) continue
candidateLumas[validPairCount] = candidateLuma
pixelIndices[validPairCount] = pixelIndex
referenceLumas[validPairCount] = referenceLuma
validPairCount++
}
}
if (validPairCount < MIN_SAMPLE_COUNT) return null
val sortedCandidateLumas = candidateLumas.copyOf(validPairCount)
sortedCandidateLumas.sort()
val candidateP50 = unweightedQuantile(sortedCandidateLumas, 0.5f)
val distancesFromP50 = FloatArray(validPairCount) { index ->
abs(candidateLumas[index] - candidateP50)
}
distancesFromP50.sort()
val minimumHalfRange = distancesFromP50[MIN_SAMPLE_COUNT - 1]
val halfRange = if (minimumHalfRange > INITIAL_P50_METERING_HALF_RANGE) {
minimumHalfRange + METERING_RANGE_EPSILON
} else {
INITIAL_P50_METERING_HALF_RANGE
}
val rangeMin = (candidateP50 - halfRange).coerceAtLeast(0f)
val rangeMax = (candidateP50 + halfRange).coerceAtMost(1f)
val selectedPixelIndices = IntArray(validPairCount)
val selectedReferenceLumas = FloatArray(validPairCount)
var selectedCount = 0
for (index in 0 until validPairCount) {
if (candidateLumas[index] !in rangeMin..rangeMax) continue
selectedPixelIndices[selectedCount] = pixelIndices[index]
selectedReferenceLumas[selectedCount] = referenceLumas[index]
selectedCount++
}
if (selectedCount < MIN_SAMPLE_COUNT) return null
return MeteringSelection(
pixelIndices = selectedPixelIndices.copyOf(selectedCount),
referenceDisplayLinearLumas = selectedReferenceLumas.copyOf(selectedCount),
seedCandidateDisplayLinearLumaP50 = candidateP50,
seedCandidateDisplayLinearLumaRangeMin = rangeMin,
seedCandidateDisplayLinearLumaRangeMax = rangeMax,
)
}
private fun evaluateMetering(
pixels: IntArray,
selection: MeteringSelection,
): MeteringEvaluation? {
var sampleCount = 0
var referenceLumaSum = 0.0
var candidateLumaSum = 0.0
for (index in selection.pixelIndices.indices) {
val candidateLuma =
displayLinearLuma(pixels[selection.pixelIndices[index]]) ?: continue
referenceLumaSum += selection.referenceDisplayLinearLumas[index]
candidateLumaSum += candidateLuma
sampleCount++
}
if (sampleCount < MIN_SAMPLE_COUNT) return null
val referenceMean = (referenceLumaSum / sampleCount).toFloat()
val candidateMean = (candidateLumaSum / sampleCount).toFloat()
@@ -11,54 +11,143 @@ import kotlin.math.roundToInt
class RawViewfinderExposureMathTest {
@Test
fun meteringUsesCandidateLinearRangeAndCorrespondingReferenceCoordinates() {
fun meteringUsesCandidateP50BandAndCorrespondingReferenceCoordinates() {
val width = 10
val height = 10
val referencePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index < 64) 0.20f else 0.01f)
grayscaleArgb(if (index in 20 until 80) 0.20f else 0.01f)
}
val candidatePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index < 64) 0.10f else 0.50f)
grayscaleArgb(
when {
index < 20 -> 0.02f
index < 80 -> 0.10f
else -> 0.50f
}
)
}
val match = RawViewfinderExposureMath.evaluate(
reference = buildReference(referencePixels, width, height),
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertEquals(64, match!!.meteringSampleCount)
assertEquals(-1f, match.meteringLog2Error!!, 0.04f)
assertEquals(0.20f, match.referenceMeteringDisplayLinearLumaMean!!, 0.005f)
assertEquals(0.10f, match.candidateMeteringDisplayLinearLumaMean!!, 0.005f)
}
@Test
fun meteringIsUnavailableWhenCandidateHasNoPixelsInLinearRange() {
val width = 8
val height = 8
val reference = buildReference(
grayscalePixels(width, height, linearLuma = 0.10f),
width,
height,
)
val candidatePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index % 2 == 0) 0.03f else 0.50f)
}
val match = RawViewfinderExposureMath.evaluate(
val reference = buildReference(referencePixels, width, height)
val selection = RawViewfinderExposureMath.buildMeteringSelection(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(selection)
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
meteringSelection = selection!!,
)
assertNotNull(match)
assertEquals(0, match!!.meteringSampleCount)
assertNull(match.meteringLog2Error)
assertNull(match.referenceMeteringDisplayLinearLumaMean)
assertNull(match.candidateMeteringDisplayLinearLumaMean)
assertEquals(60, match!!.meteringSampleCount)
assertEquals(-1f, match.meteringLog2Error!!, 0.04f)
assertEquals(0.20f, match.referenceMeteringDisplayLinearLumaMean!!, 0.005f)
assertEquals(0.10f, match.candidateMeteringDisplayLinearLumaMean!!, 0.005f)
assertEquals(0.10f, selection.seedCandidateDisplayLinearLumaP50, 0.005f)
assertEquals(
0.01f,
selection.seedCandidateDisplayLinearLumaP50 -
selection.seedCandidateDisplayLinearLumaRangeMin,
0.0001f,
)
assertEquals(
0.01f,
selection.seedCandidateDisplayLinearLumaRangeMax -
selection.seedCandidateDisplayLinearLumaP50,
0.0001f,
)
}
@Test
fun meteringExpandsSymmetricallyAroundP50WhenInitialBandIsSparse() {
val width = 10
val height = 10
val candidatePixels = IntArray(width * height) { index ->
grayscaleArgb(
when {
index < 49 -> 0.02f
index < 51 -> 0.10f
else -> 0.18f
}
)
}
val reference = buildReference(candidatePixels, width, height)
val selection = RawViewfinderExposureMath.buildMeteringSelection(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(selection)
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
meteringSelection = selection!!,
)
assertNotNull(match)
assertTrue(match!!.meteringSampleCount >= 32)
assertEquals(0f, match.meteringLog2Error!!, 0.001f)
assertEquals(0.10f, selection.seedCandidateDisplayLinearLumaP50, 0.005f)
val lowerHalfRange =
selection.seedCandidateDisplayLinearLumaP50 -
selection.seedCandidateDisplayLinearLumaRangeMin
val upperHalfRange =
selection.seedCandidateDisplayLinearLumaRangeMax -
selection.seedCandidateDisplayLinearLumaP50
assertTrue(lowerHalfRange > 0.01f)
assertEquals(lowerHalfRange, upperHalfRange, 0.0001f)
}
@Test
fun meteringSelectionIsReusedAcrossExposureCandidates() {
val width = 10
val height = 10
val reference = buildReference(
grayscalePixels(width, height, linearLuma = 0.40f),
width,
height,
)
val seedCandidatePixels = IntArray(width * height) { index ->
grayscaleArgb(0.02f + 0.48f * index / (width * height - 1))
}
val selection = RawViewfinderExposureMath.buildMeteringSelection(
reference = reference,
pixels = seedCandidatePixels,
width = width,
height = height,
)
assertNotNull(selection)
val nextCandidatePixels = grayscalePixels(width, height, linearLuma = 0.10f)
selection!!.pixelIndices.forEach { pixelIndex ->
nextCandidatePixels[pixelIndex] = grayscaleArgb(0.40f)
}
val fixedSelectionMatch = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = nextCandidatePixels,
width = width,
height = height,
meteringSelection = selection,
)
val reselectedMatch = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = nextCandidatePixels,
width = width,
height = height,
)
assertNotNull(fixedSelectionMatch)
assertEquals(selection.sampleCount, fixedSelectionMatch!!.meteringSampleCount)
assertEquals(0f, fixedSelectionMatch.meteringLog2Error!!, 0.001f)
assertNotNull(reselectedMatch)
assertTrue(reselectedMatch!!.meteringLog2Error!! < -1f)
}
@Test
@@ -370,8 +459,8 @@ class RawViewfinderExposureMathTest {
assertNotNull(match)
assertEquals(0.5f, match!!.candidatePerceptualBrightnessMean, 0.001f)
assertEquals(0, match.meteringSampleCount)
assertNull(match.meteringLog2Error)
assertEquals(64, match.meteringSampleCount)
assertNotNull(match.meteringLog2Error)
}
@Test