feat: new RawViewfinderExposureMatcher

This commit is contained in:
Hinnka committed 2026-08-02 21:01:01 +08:00
1 parent 6b886cc67a
commit 89d8a9ba95
3 files changed
+321 -35

No files matched your search

@@ -3,9 +3,11 @@ 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 kotlin.math.max
internal data class RawExposurePreviewFrame(
@@ -27,7 +29,6 @@ internal object RawViewfinderExposureMatcher {
private data class ViewfinderReference(
val analysis: RawViewfinderExposureMath.Reference,
val frame: RawExposurePreviewFrame,
)
suspend fun prepareCaptureProfile(
@@ -46,7 +47,13 @@ internal object RawViewfinderExposureMatcher {
applyLensShadingCorrection: Boolean = true,
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
): RawDngCaptureProfileResult? {
val reference = capturePreviewThumbnail?.let(::buildReference)
val testImageCache = ExposureMatchTestImageCache.create(context)
val reference = capturePreviewThumbnail?.let { bitmap ->
buildReference(
bitmap = bitmap,
testImageCache = testImageCache,
)
}
if (capturePreviewThumbnail != null && reference == null) {
PLog.w(TAG, "Viewfinder match skipped: capture preview is unavailable")
}
@@ -58,6 +65,7 @@ internal object RawViewfinderExposureMatcher {
solve(
reference = it,
renderSample = renderSample,
testImageCache = testImageCache,
)
},
)
@@ -79,28 +87,31 @@ internal object RawViewfinderExposureMatcher {
)
}
private fun buildReference(bitmap: Bitmap): ViewfinderReference? {
private fun buildReference(
bitmap: Bitmap,
testImageCache: ExposureMatchTestImageCache?,
): 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
val frame = RawExposurePreviewFrame(
width = size.width,
height = size.height,
argbPixels = pixels,
)
testImageCache?.writeViewfinder(frame)
val analysis = RawViewfinderExposureMath.buildReference(
pixels = pixels,
width = size.width,
height = size.height,
left = bounds.left,
top = bounds.top,
right = bounds.right,
bottom = bounds.bottom,
left = 0,
top = 0,
right = size.width,
bottom = size.height,
) ?: 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)
@@ -111,9 +122,20 @@ internal object RawViewfinderExposureMatcher {
private fun solve(
reference: ViewfinderReference,
renderSample: (Float) -> RawExposurePreviewFrame?,
testImageCache: ExposureMatchTestImageCache?,
): Float? {
var candidateIndex = 0
return RawViewfinderExposureMath.solve { exposureEv ->
evaluate(reference.analysis, exposureEv, renderSample(exposureEv))
val frame = renderSample(exposureEv)
if (frame != null) {
testImageCache?.writeCandidate(
index = candidateIndex,
exposureEv = exposureEv,
frame = frame,
)
}
candidateIndex++
evaluate(reference.analysis, exposureEv, frame)
}
}
@@ -131,7 +153,7 @@ internal object RawViewfinderExposureMatcher {
width = frame.width,
height = frame.height,
) ?: return null
val meteringLog2Error = match.meanBrightnessLog2Error
val meteringLog2Error = match.meteringLog2Error
PLog.d(
TAG,
"RAW viewfinder sample: exposureEv=$exposureEv " +
@@ -154,7 +176,12 @@ internal object RawViewfinderExposureMatcher {
"referencePerceptualBrightnessMean=" +
"${match.referencePerceptualBrightnessMean} " +
"candidatePerceptualBrightnessMean=" +
"${match.candidatePerceptualBrightnessMean}"
"${match.candidatePerceptualBrightnessMean} " +
"meteringSampleCount=${match.meteringSampleCount} " +
"referenceMeteringDisplayLinearLumaMean=" +
"${match.referenceMeteringDisplayLinearLumaMean} " +
"candidateMeteringDisplayLinearLumaMean=" +
"${match.candidateMeteringDisplayLinearLumaMean}"
)
return meteringLog2Error
}
@@ -192,16 +219,113 @@ internal object RawViewfinderExposureMatcher {
return pixels
}
private fun centerTwoThirdsBounds(width: Int, height: Int): Rect? {
if (width <= 0 || height <= 0) return null
val left = width / 6
val top = height / 6
return Rect(
left,
top,
(width * 5 / 6).coerceAtLeast(left + 1),
(height * 5 / 6).coerceAtLeast(top + 1),
)
private class ExposureMatchTestImageCache private constructor(
private val directory: File,
) {
fun writeViewfinder(frame: RawExposurePreviewFrame) {
writeFrame(
frame = frame,
target = File(directory, VIEWFINDER_FILE_NAME),
description = "viewfinder",
)
}
fun writeCandidate(
index: Int,
exposureEv: Float,
frame: RawExposurePreviewFrame,
) {
val target = File(
directory,
"$CANDIDATE_FILE_PREFIX${index.toString().padStart(2, '0')}.png",
)
writeFrame(
frame = frame,
target = target,
description = "candidate index=$index exposureEv=$exposureEv",
)
}
private fun writeFrame(
frame: RawExposurePreviewFrame,
target: File,
description: String,
) {
if (frame.width <= 0 ||
frame.height <= 0 ||
frame.argbPixels.size < frame.width * frame.height
) {
PLog.w(TAG, "Skipped invalid RAW exposure match test image: $description")
return
}
try {
val bitmap = Bitmap.createBitmap(
frame.argbPixels,
frame.width,
frame.height,
Bitmap.Config.ARGB_8888,
)
try {
target.outputStream().buffered().use { output ->
check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) {
"Bitmap PNG compression returned false"
}
}
} finally {
bitmap.recycle()
}
PLog.d(
TAG,
"Cached RAW exposure match test image: $description path=${target.absolutePath}",
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to cache RAW exposure match test image: $description", e)
}
}
companion object {
private const val CACHE_DIRECTORY_NAME = "raw_viewfinder_exposure_match"
private const val VIEWFINDER_FILE_NAME = "viewfinder.png"
private const val CANDIDATE_FILE_PREFIX = "candidate_"
fun create(context: Context): ExposureMatchTestImageCache? {
if (!BuildConfig.DEBUG) return null
val directory = File(context.cacheDir, CACHE_DIRECTORY_NAME)
if (!directory.exists() && !directory.mkdirs()) {
PLog.w(
TAG,
"Failed to create RAW exposure match test cache: " +
directory.absolutePath,
)
return null
}
if (!directory.isDirectory) {
PLog.w(
TAG,
"RAW exposure match test cache path is not a directory: " +
directory.absolutePath,
)
return null
}
directory.listFiles()
?.filter { file ->
file.isFile &&
(file.name == VIEWFINDER_FILE_NAME ||
file.name.startsWith(CANDIDATE_FILE_PREFIX) &&
file.extension == "png")
}
?.forEach { staleFile ->
if (!staleFile.delete()) {
PLog.w(
TAG,
"Failed to remove stale RAW exposure match test image: " +
staleFile.absolutePath,
)
}
}
return ExposureMatchTestImageCache(directory)
}
}
}
}
@@ -9,17 +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. 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.
* 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.
*/
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 QUANTILE_TRIM_LOW_FRACTION = 0.15f
private const val QUANTILE_TRIM_HIGH_FRACTION = 0.85f
private const val QUANTILE_SPREAD_LOW_FRACTION = 0.15f
@@ -44,7 +45,7 @@ internal object RawViewfinderExposureMath {
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
private const val MATCH_LOG2_TOLERANCE = 0.01f
private const val INITIAL_PROBE_EV = 0.5f
private const val MIN_STEP_EV = 0.025f
private const val MIN_ERROR_DELTA = 0.0001f
@@ -66,6 +67,7 @@ internal object RawViewfinderExposureMath {
val targetMeanLog2DisplayLinearLuma: Float,
val targetMeanLog2PerceptualBrightness: Float,
val targetQuantileLog2Lumas: FloatArray,
val meteringReferenceDisplayLinearLumas: FloatArray,
val sampleCount: Int,
val displayLinearLumaMean: Float,
val perceptualBrightnessMean: Float,
@@ -77,6 +79,15 @@ internal object RawViewfinderExposureMath {
require(targetMeanLog2PerceptualBrightness.isFinite())
require(targetQuantileLog2Lumas.size == MATCH_QUANTILES.size)
require(targetQuantileLog2Lumas.all { it.isFinite() })
require(
meteringReferenceDisplayLinearLumas.size ==
(right - left) * (bottom - top)
)
require(
meteringReferenceDisplayLinearLumas.all {
it.isNaN() || (it.isFinite() && it in 0f..1f)
}
)
require(sampleCount >= MIN_SAMPLE_COUNT)
require(displayLinearLumaMean.isFinite() && displayLinearLumaMean >= 0f)
require(perceptualBrightnessMean.isFinite() && perceptualBrightnessMean >= 0f)
@@ -84,6 +95,10 @@ internal object RawViewfinderExposureMath {
}
data class MatchResult(
val meteringLog2Error: Float?,
val meteringSampleCount: Int,
val referenceMeteringDisplayLinearLumaMean: Float?,
val candidateMeteringDisplayLinearLumaMean: Float?,
val matchLog2Error: Float,
val toneWeightedLog2Error: Float,
val meanBrightnessLog2Error: Float,
@@ -112,6 +127,13 @@ internal object RawViewfinderExposureMath {
val sampleCount: Int,
)
private data class MeteringEvaluation(
val log2Error: Float,
val sampleCount: Int,
val referenceDisplayLinearLumaMean: Float,
val candidateDisplayLinearLumaMean: Float,
)
private data class SolverSample(
val exposureEv: Float,
val matchLog2Error: Float,
@@ -142,6 +164,14 @@ internal object RawViewfinderExposureMath {
bottom = safeBottom,
) ?: return null
if (distribution.sampleCount < MIN_SAMPLE_COUNT) return null
val referenceDisplayLinearLumas = buildReferenceDisplayLinearLumas(
pixels = pixels,
width = width,
left = safeLeft,
top = safeTop,
right = safeRight,
bottom = safeBottom,
)
return Reference(
width = width,
height = height,
@@ -160,6 +190,7 @@ internal object RawViewfinderExposureMath {
targetMeanLog2DisplayLinearLuma = distribution.meanLog2DisplayLinearLuma,
targetMeanLog2PerceptualBrightness = distribution.meanLog2PerceptualBrightness,
targetQuantileLog2Lumas = distribution.quantiles(),
meteringReferenceDisplayLinearLumas = referenceDisplayLinearLumas,
sampleCount = distribution.sampleCount,
displayLinearLumaMean = distribution.displayLinearLumaMean,
perceptualBrightnessMean = distribution.perceptualBrightnessMean,
@@ -188,6 +219,12 @@ internal object RawViewfinderExposureMath {
right = reference.right,
bottom = reference.bottom,
) ?: return null
val metering = evaluateMetering(
reference = reference,
pixels = pixels,
width = width,
)
val meteringError = metering?.log2Error
val candidateQuantiles = distribution.quantiles()
val meanBrightnessError = log2(
distribution.perceptualBrightnessMean.coerceAtLeast(PERCEPTUAL_BRIGHTNESS_FLOOR)
@@ -247,7 +284,8 @@ internal object RawViewfinderExposureMath {
val matchError =
TRIMMED_QUANTILE_ERROR_WEIGHT * trimmedMean +
MEAN_BRIGHTNESS_ERROR_WEIGHT * meanBrightnessError
if (!meanBrightnessError.isFinite() ||
if (meteringError?.isFinite() == false ||
!meanBrightnessError.isFinite() ||
!linearArithmeticMeanError.isFinite() ||
!linearLogAverageError.isFinite() ||
!perceptualLogAverageError.isFinite() ||
@@ -261,6 +299,12 @@ internal object RawViewfinderExposureMath {
return null
}
return MatchResult(
meteringLog2Error = meteringError,
meteringSampleCount = metering?.sampleCount ?: 0,
referenceMeteringDisplayLinearLumaMean =
metering?.referenceDisplayLinearLumaMean,
candidateMeteringDisplayLinearLumaMean =
metering?.candidateDisplayLinearLumaMean,
matchLog2Error = matchError,
toneWeightedLog2Error = toneWeightedError,
meanBrightnessLog2Error = meanBrightnessError,
@@ -281,6 +325,71 @@ internal object RawViewfinderExposureMath {
)
}
private fun buildReferenceDisplayLinearLumas(
pixels: IntArray,
width: Int,
left: Int,
top: Int,
right: Int,
bottom: Int,
): FloatArray {
val lumas = FloatArray((right - left) * (bottom - top))
var lumaIndex = 0
for (y in top until bottom) {
for (x in left until right) {
lumas[lumaIndex++] =
displayLinearLuma(pixels[y * width + x]) ?: Float.NaN
}
}
return lumas
}
private fun evaluateMetering(
reference: Reference,
pixels: IntArray,
width: Int,
): MeteringEvaluation? {
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++
}
}
if (sampleCount < MIN_SAMPLE_COUNT) return null
val referenceMean = (referenceLumaSum / sampleCount).toFloat()
val candidateMean = (candidateLumaSum / sampleCount).toFloat()
val log2Error =
log2(candidateMean.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR)) -
log2(referenceMean.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR))
if (!log2Error.isFinite() ||
!referenceMean.isFinite() ||
!candidateMean.isFinite()
) {
return null
}
return MeteringEvaluation(
log2Error = log2Error,
sampleCount = sampleCount,
referenceDisplayLinearLumaMean = referenceMean,
candidateDisplayLinearLumaMean = candidateMean,
)
}
private fun buildDistribution(
pixels: IntArray,
width: Int,
@@ -10,6 +10,57 @@ import kotlin.math.pow
import kotlin.math.roundToInt
class RawViewfinderExposureMathTest {
@Test
fun meteringUsesCandidateLinearRangeAndCorrespondingReferenceCoordinates() {
val width = 10
val height = 10
val referencePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index < 64) 0.20f else 0.01f)
}
val candidatePixels = IntArray(width * height) { index ->
grayscaleArgb(if (index < 64) 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(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertEquals(0, match!!.meteringSampleCount)
assertNull(match.meteringLog2Error)
assertNull(match.referenceMeteringDisplayLinearLumaMean)
assertNull(match.candidateMeteringDisplayLinearLumaMean)
}
@Test
fun meanPerceptualBrightnessTracksDisplayedMidtoneDifference() {
val referencePixels = grayscalePixels(8, 8, linearLuma = 0.18f)
@@ -278,7 +329,7 @@ class RawViewfinderExposureMathTest {
}
@Test
fun referenceWithBlackAndWhiteEndpointsHasDefinedBrightness() {
fun referenceWithOnlyBlackAndWhiteEndpointsHasDefinedDiagnostics() {
val pixels = IntArray(64) { index ->
if (index % 2 == 0) grayscaleArgb(0f) else grayscaleArgb(1f)
}
@@ -319,6 +370,8 @@ class RawViewfinderExposureMathTest {
assertNotNull(match)
assertEquals(0.5f, match!!.candidatePerceptualBrightnessMean, 0.001f)
assertEquals(0, match.meteringSampleCount)
assertNull(match.meteringLog2Error)
}
@Test