feat: raw viewfinder expo match optimize

This commit is contained in:
zhoubinjia committed 2026-07-17 12:43:44 +08:00
1 parent 4c1413847e
commit 4277078087
4 files changed
+486 -162

No files matched your search

@@ -6,8 +6,6 @@ import android.graphics.Rect
import com.hinnka.mycamera.camera.AspectRatio
import com.hinnka.mycamera.camera.RawBlackBorderCrop
import com.hinnka.mycamera.utils.PLog
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.max
internal data class RawExposurePreviewFrame(
@@ -26,10 +24,6 @@ internal data class RawExposurePreviewFrame(
internal object RawViewfinderExposureMatcher {
private const val TAG = "RawViewfinderExposureMatcher"
private const val PREVIEW_LONG_EDGE = 256
private const val LUMA_FLOOR = 0.001f
private const val MAX_SOLVE_STEPS = 3
private const val EV_TOLERANCE = 0.05f
private const val MIN_STEP_EV = 0.025f
suspend fun prepareCaptureProfile(
renderer: RawDemosaicProcessor,
@@ -75,32 +69,20 @@ internal object RawViewfinderExposureMatcher {
)
}
private data class Reference(
val width: Int,
val height: Int,
val bounds: Rect,
val targetDisplayLuma: Float,
)
private data class Sample(
val exposureEv: Float,
val errorEv: Float,
val renderedDisplayLuma: Float,
)
private fun buildReference(bitmap: Bitmap): Reference? {
private fun buildReference(bitmap: Bitmap): RawViewfinderExposureMath.Reference? {
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)
MeteringSystem.analyzeSrgbThumbnail(size.width, size.height, pixels) ?: return null
val bounds = centerTwoThirdsBounds(size.width, size.height) ?: return null
val targetLuma = averageDisplayLuma(pixels, size.width, size.height, bounds) ?: return null
Reference(
RawViewfinderExposureMath.buildReference(
pixels = pixels,
width = size.width,
height = size.height,
bounds = bounds,
targetDisplayLuma = targetLuma,
left = bounds.left,
top = bounds.top,
right = bounds.right,
bottom = bounds.bottom,
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to analyze capture preview", e)
@@ -109,107 +91,37 @@ internal object RawViewfinderExposureMatcher {
}
private fun solve(
reference: Reference,
reference: RawViewfinderExposureMath.Reference,
renderSample: (Float) -> RawExposurePreviewFrame?,
): Float? {
val zero = evaluate(reference, 0f, renderSample(0f)) ?: return null
if (abs(zero.errorEv) <= EV_TOLERANCE) return zero.exposureEv
val samples = mutableListOf(zero)
var best = zero
var nextEv = exposureEvForSample(zero)
repeat(MAX_SOLVE_STEPS) {
val candidateEv = distinctCandidate(nextEv, samples) ?: return best.exposureEv
val sample = evaluate(reference, candidateEv, renderSample(candidateEv))
?: return best.exposureEv
samples += sample
if (abs(sample.errorEv) < abs(best.errorEv)) best = sample
if (abs(sample.errorEv) <= EV_TOLERANCE) return sample.exposureEv
nextEv = nextCandidate(samples, sample)
return RawViewfinderExposureMath.solve { exposureEv ->
evaluate(reference, exposureEv, renderSample(exposureEv))
}
return best.exposureEv
}
private fun evaluate(
reference: Reference,
reference: RawViewfinderExposureMath.Reference,
exposureEv: Float,
frame: RawExposurePreviewFrame?,
): Sample? {
): Float? {
if (frame == null || frame.width != reference.width || frame.height != reference.height) {
return null
}
MeteringSystem.analyzeSrgbThumbnail(frame.width, frame.height, frame.argbPixels) ?: return null
val renderedLuma = averageDisplayLuma(
frame.argbPixels,
frame.width,
frame.height,
reference.bounds,
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = frame.argbPixels,
width = frame.width,
height = frame.height,
) ?: return null
val errorEv = displayLumaErrorEv(renderedLuma, reference.targetDisplayLuma)
PLog.d(
TAG,
"RAW viewfinder sample: exposureEv=$exposureEv errorEv=$errorEv " +
"targetLuma=${reference.targetDisplayLuma} renderedLuma=$renderedLuma"
)
return Sample(
exposureEv = exposureEv,
errorEv = errorEv,
renderedDisplayLuma = renderedLuma,
)
}
private fun nextCandidate(samples: List<Sample>, latest: Sample): Float {
bracketedCandidate(samples)?.let { return it }
val previous = samples.asReversed().firstOrNull {
it !== latest && abs(it.errorEv - latest.errorEv) > 0.0001f
}
return previous?.let { interpolatedExposureEv(it, latest) }
?: exposureEvForSample(latest)
}
private fun bracketedCandidate(samples: List<Sample>): Float? {
val sorted = samples.sortedBy { it.exposureEv }
for (index in 0 until sorted.lastIndex) {
val lower = sorted[index]
val upper = sorted[index + 1]
val crossesTarget =
(lower.errorEv <= 0f && upper.errorEv >= 0f) ||
(lower.errorEv >= 0f && upper.errorEv <= 0f)
if (!crossesTarget) continue
val interpolated = interpolatedExposureEv(lower, upper)
return if (interpolated != null && interpolated in lower.exposureEv..upper.exposureEv) {
interpolated
} else {
sanitizeExposureEv((lower.exposureEv + upper.exposureEv) * 0.5f)
}
}
return null
}
private fun interpolatedExposureEv(a: Sample, b: Sample): Float? {
val errorDelta = b.errorEv - a.errorEv
if (!errorDelta.isFinite() || abs(errorDelta) <= 0.0001f) return null
return sanitizeExposureEv(
a.exposureEv - a.errorEv * (b.exposureEv - a.exposureEv) / errorDelta
)
}
private fun exposureEvForSample(sample: Sample): Float {
return sanitizeExposureEv(sample.exposureEv - sample.errorEv) ?: sample.exposureEv
}
private fun distinctCandidate(candidateEv: Float, samples: List<Sample>): Float? {
val safeEv = sanitizeExposureEv(candidateEv) ?: return null
return safeEv.takeUnless { candidate ->
samples.any { abs(it.exposureEv - candidate) < MIN_STEP_EV }
}
}
private fun sanitizeExposureEv(value: Float): Float? {
return value.takeIf { it.isFinite() }?.coerceIn(
MeteringSystem.RAW_EXPOSURE_MIN_EV,
MeteringSystem.RAW_EXPOSURE_MAX_EV,
"RAW viewfinder sample: exposureEv=$exposureEv " +
"matchLog2Error=${match.matchLog2Error} " +
"medianLog2Error=${match.medianLog2Error} " +
"trimmedMeanLog2Error=${match.trimmedMeanLog2Error} " +
"sampleCount=${match.sampleCount}"
)
return match.matchLog2Error
}
private data class Size(val width: Int, val height: Int)
@@ -256,35 +168,6 @@ internal object RawViewfinderExposureMatcher {
(height * 5 / 6).coerceAtLeast(top + 1),
)
}
private fun averageDisplayLuma(
pixels: IntArray,
width: Int,
height: Int,
bounds: Rect,
): Float? {
if (pixels.size < width * height || bounds.isEmpty) return null
var sum = 0.0
var count = 0
for (y in bounds.top until bounds.bottom) {
for (x in bounds.left until bounds.right) {
val pixel = pixels[y * width + x]
val alpha = ((pixel ushr 24) and 0xff) / 255f
val r = ((pixel ushr 16) and 0xff) / 255f
val g = ((pixel ushr 8) and 0xff) / 255f
val b = (pixel and 0xff) / 255f
sum += ((0.2126f * r + 0.7152f * g + 0.0722f * b) * alpha).toDouble()
count++
}
}
return if (count > 0) (sum / count).toFloat().coerceAtLeast(LUMA_FLOOR) else null
}
private fun displayLumaErrorEv(renderedLuma: Float, targetLuma: Float): Float {
val rendered = renderedLuma.takeIf { it.isFinite() }?.coerceAtLeast(LUMA_FLOOR) ?: LUMA_FLOOR
val target = targetLuma.takeIf { it.isFinite() }?.coerceAtLeast(LUMA_FLOOR) ?: LUMA_FLOOR
return (ln(rendered.toDouble() / target.toDouble()) / ln(2.0)).toFloat()
}
}
internal data class RawExposurePreviewRequest(
@@ -0,0 +1,287 @@
package com.hinnka.mycamera.raw
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.pow
/**
* Display-referred exposure matching math shared by the capture preview matcher and unit tests.
*
* 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. Reference pixels clipped near black or white are
* excluded once and the same fixed sample set is used for every rendered candidate.
*/
internal object RawViewfinderExposureMath {
private const val DISPLAY_LINEAR_LUMA_FLOOR = 0.001f
private const val REFERENCE_CLIP_LOW_LUMA = 0.002f
private const val REFERENCE_CLIP_HIGH_LUMA = 0.995f
private const val MIN_REFERENCE_SAMPLE_COUNT = 32
private const val TRIM_LOW_FRACTION = 0.25f
private const val TRIM_HIGH_FRACTION = 0.75f
private const val MEDIAN_WEIGHT = 0.55f
private const val MAX_SOLVE_STEPS = 4
private const val MATCH_LOG2_TOLERANCE = 0.05f
private const val INITIAL_PROBE_EV = 0.5f
private const val MIN_STEP_EV = 0.025f
private const val MIN_ERROR_DELTA = 0.0001f
private const val SRGB_TRANSFER_THRESHOLD = 0.04045f
private const val SRGB_LINEAR_SCALE = 12.92f
private const val SRGB_TRANSFER_A = 0.055f
private const val SRGB_TRANSFER_GAMMA = 2.4f
data class Reference(
val width: Int,
val height: Int,
val pixelIndices: IntArray,
val targetLog2DisplayLinearLumas: FloatArray,
) {
init {
require(pixelIndices.size == targetLog2DisplayLinearLumas.size)
}
val sampleCount: Int
get() = pixelIndices.size
}
data class MatchResult(
val matchLog2Error: Float,
val medianLog2Error: Float,
val trimmedMeanLog2Error: Float,
val sampleCount: Int,
)
private data class SolverSample(
val exposureEv: Float,
val matchLog2Error: Float,
)
fun buildReference(
pixels: IntArray,
width: Int,
height: Int,
left: Int,
top: Int,
right: Int,
bottom: Int,
): Reference? {
if (width <= 0 || height <= 0 || pixels.size < width * height) return null
val safeLeft = left.coerceIn(0, width)
val safeTop = top.coerceIn(0, height)
val safeRight = right.coerceIn(safeLeft, width)
val safeBottom = bottom.coerceIn(safeTop, height)
if (safeLeft >= safeRight || safeTop >= safeBottom) return null
val capacity = (safeRight - safeLeft) * (safeBottom - safeTop)
val pixelIndices = IntArray(capacity)
val targetLogLumas = FloatArray(capacity)
var sampleCount = 0
for (y in safeTop until safeBottom) {
for (x in safeLeft until safeRight) {
val pixelIndex = y * width + x
val targetLuma = displayLinearLuma(pixels[pixelIndex]) ?: continue
if (targetLuma <= REFERENCE_CLIP_LOW_LUMA ||
targetLuma >= REFERENCE_CLIP_HIGH_LUMA
) {
continue
}
pixelIndices[sampleCount] = pixelIndex
targetLogLumas[sampleCount] = log2(targetLuma)
sampleCount++
}
}
if (sampleCount < MIN_REFERENCE_SAMPLE_COUNT) return null
return Reference(
width = width,
height = height,
pixelIndices = pixelIndices.copyOf(sampleCount),
targetLog2DisplayLinearLumas = targetLogLumas.copyOf(sampleCount),
)
}
fun evaluate(
reference: Reference,
pixels: IntArray,
width: Int,
height: Int,
): MatchResult? {
if (width != reference.width ||
height != reference.height ||
pixels.size < width * height ||
reference.sampleCount < MIN_REFERENCE_SAMPLE_COUNT
) {
return null
}
val log2Errors = FloatArray(reference.sampleCount)
for (sampleIndex in reference.pixelIndices.indices) {
val pixelIndex = reference.pixelIndices[sampleIndex]
val renderedLuma = displayLinearLuma(pixels[pixelIndex])
?.coerceAtLeast(DISPLAY_LINEAR_LUMA_FLOOR)
?: DISPLAY_LINEAR_LUMA_FLOOR
log2Errors[sampleIndex] =
log2(renderedLuma) - reference.targetLog2DisplayLinearLumas[sampleIndex]
}
log2Errors.sort()
val median = median(log2Errors)
val trimmedMean = trimmedMean(
sortedValues = log2Errors,
lowFraction = TRIM_LOW_FRACTION,
highFraction = TRIM_HIGH_FRACTION,
)
val matchError = median * MEDIAN_WEIGHT + trimmedMean * (1f - MEDIAN_WEIGHT)
if (!matchError.isFinite()) return null
return MatchResult(
matchLog2Error = matchError,
medianLog2Error = median,
trimmedMeanLog2Error = trimmedMean,
sampleCount = reference.sampleCount,
)
}
/**
* Solves RAW exposure EV from a monotonic display-light error function.
*
* The error is deliberately not assumed to have a 1:1 slope with RAW EV. A directed probe
* establishes that slope before secant or bracket interpolation is used.
*/
fun solve(evaluateError: (Float) -> Float?): Float? {
val zeroError = evaluateError(0f)?.takeIf { it.isFinite() } ?: return null
val zero = SolverSample(exposureEv = 0f, matchLog2Error = zeroError)
if (abs(zero.matchLog2Error) <= MATCH_LOG2_TOLERANCE) return zero.exposureEv
val samples = mutableListOf(zero)
var best = zero
var nextEv = directionalProbe(zero, samples)
repeat(MAX_SOLVE_STEPS) {
val candidateEv = distinctCandidate(nextEv, samples) ?: return best.exposureEv
val candidateError = evaluateError(candidateEv)?.takeIf { it.isFinite() }
?: return best.exposureEv
val sample = SolverSample(candidateEv, candidateError)
samples += sample
if (abs(sample.matchLog2Error) < abs(best.matchLog2Error)) best = sample
if (abs(sample.matchLog2Error) <= MATCH_LOG2_TOLERANCE) return sample.exposureEv
nextEv = nextCandidate(samples, sample)
}
return best.exposureEv
}
private fun nextCandidate(samples: List<SolverSample>, latest: SolverSample): Float {
bracketedCandidate(samples)?.let { return it }
val previous = samples.asReversed().firstOrNull {
it !== latest && abs(it.matchLog2Error - latest.matchLog2Error) > MIN_ERROR_DELTA
}
return previous?.let { interpolatedExposureEv(it, latest) }
?: directionalProbe(latest, samples)
}
private fun bracketedCandidate(samples: List<SolverSample>): Float? {
val sorted = samples.sortedBy { it.exposureEv }
for (index in 0 until sorted.lastIndex) {
val lower = sorted[index]
val upper = sorted[index + 1]
val crossesTarget =
(lower.matchLog2Error <= 0f && upper.matchLog2Error >= 0f) ||
(lower.matchLog2Error >= 0f && upper.matchLog2Error <= 0f)
if (!crossesTarget) continue
val interpolated = interpolatedExposureEv(lower, upper)
return if (interpolated != null && interpolated in lower.exposureEv..upper.exposureEv) {
interpolated
} else {
sanitizeExposureEv((lower.exposureEv + upper.exposureEv) * 0.5f)
}
}
return null
}
private fun interpolatedExposureEv(a: SolverSample, b: SolverSample): Float? {
val errorDelta = b.matchLog2Error - a.matchLog2Error
if (!errorDelta.isFinite() || abs(errorDelta) <= MIN_ERROR_DELTA) return null
return sanitizeExposureEv(
a.exposureEv -
a.matchLog2Error * (b.exposureEv - a.exposureEv) / errorDelta
)
}
private fun directionalProbe(
sample: SolverSample,
samples: List<SolverSample>,
): Float {
val direction = if (sample.matchLog2Error > 0f) -1f else 1f
val previousInDirection = samples.asReversed().firstOrNull {
it !== sample &&
(sample.exposureEv - it.exposureEv) * direction >= MIN_STEP_EV
}
val stepEv = previousInDirection?.let {
(abs(sample.exposureEv - it.exposureEv) * 2f).coerceAtLeast(INITIAL_PROBE_EV)
} ?: INITIAL_PROBE_EV
return sanitizeExposureEv(sample.exposureEv + direction * stepEv)
?: sample.exposureEv
}
private fun distinctCandidate(candidateEv: Float, samples: List<SolverSample>): Float? {
val safeEv = sanitizeExposureEv(candidateEv) ?: return null
return safeEv.takeUnless { candidate ->
samples.any { abs(it.exposureEv - candidate) < MIN_STEP_EV }
}
}
private fun sanitizeExposureEv(value: Float): Float? {
return value.takeIf { it.isFinite() }?.coerceIn(
MeteringSystem.RAW_EXPOSURE_MIN_EV,
MeteringSystem.RAW_EXPOSURE_MAX_EV,
)
}
private fun displayLinearLuma(argb: Int): Float? {
val alpha = (argb ushr 24) and 0xff
if (alpha == 0) return null
val alphaScale = alpha / 255f
val r = srgbToLinear(((argb ushr 16) and 0xff) / 255f)
val g = srgbToLinear(((argb ushr 8) and 0xff) / 255f)
val b = srgbToLinear((argb and 0xff) / 255f)
return ((0.2126f * r + 0.7152f * g + 0.0722f * b) * alphaScale)
.takeIf { it.isFinite() }
}
private fun srgbToLinear(value: Float): Float {
val clamped = value.coerceIn(0f, 1f)
return if (clamped <= SRGB_TRANSFER_THRESHOLD) {
clamped / SRGB_LINEAR_SCALE
} else {
((clamped + SRGB_TRANSFER_A) / (1f + SRGB_TRANSFER_A))
.pow(SRGB_TRANSFER_GAMMA)
}
}
private fun median(sortedValues: FloatArray): Float {
val middle = sortedValues.size / 2
return if (sortedValues.size % 2 == 0) {
(sortedValues[middle - 1] + sortedValues[middle]) * 0.5f
} else {
sortedValues[middle]
}
}
private fun trimmedMean(
sortedValues: FloatArray,
lowFraction: Float,
highFraction: Float,
): Float {
val start = (sortedValues.size * lowFraction.coerceIn(0f, 1f)).toInt()
val endExclusive = (sortedValues.size * highFraction.coerceIn(0f, 1f)).toInt()
.coerceIn(start + 1, sortedValues.size)
var sum = 0.0
for (index in start until endExclusive) {
sum += sortedValues[index].toDouble()
}
return (sum / (endExclusive - start)).toFloat()
}
private fun log2(value: Float): Float {
return (ln(value.toDouble()) / ln(2.0)).toFloat()
}
}
@@ -1,22 +0,0 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DngProfileToneCurveTest {
@Test
fun photonPgtmCurveUsesReference257PointSerialization() {
val points = DngProfileToneCurve.photonPgtmToneCurvePoints()
assertEquals(514, points.size)
assertTrue(DcpToneCurve(points).isValid)
repeat(257) { pointIndex ->
assertEquals(pointIndex / 256f, points[pointIndex * 2], 0f)
}
assertEquals(0f, points[1], 0f)
assertEquals(0.15f, points[64 * 2 + 1], 1e-6f)
assertEquals(0.8f, points[192 * 2 + 1], 1e-6f)
assertEquals(1f, points.last(), 0f)
}
}
@@ -0,0 +1,176 @@
package com.hinnka.mycamera.raw
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.pow
import kotlin.math.roundToInt
class RawViewfinderExposureMathTest {
@Test
fun displayLinearLogRatioTracksOneStopForUnclippedMidtones() {
val referencePixels = grayscalePixels(8, 8, linearLuma = 0.18f)
val reference = buildReference(referencePixels, 8, 8)
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = grayscalePixels(8, 8, linearLuma = 0.36f),
width = 8,
height = 8,
)
assertNotNull(match)
assertEquals(1f, match!!.matchLog2Error, 0.02f)
}
@Test
fun clippedReferencePixelsNeverEnterCandidateSampleSet() {
val width = 10
val height = 10
val referencePixels = grayscalePixels(width, height, linearLuma = 0.18f)
for (index in 0 until 20) referencePixels[index] = grayscaleArgb(0f)
for (index in 20 until 40) referencePixels[index] = grayscaleArgb(1f)
val reference = buildReference(referencePixels, width, height)
assertEquals(60, reference.sampleCount)
val candidatePixels = grayscalePixels(width, height, linearLuma = 0.36f)
for (index in 0 until 20) candidatePixels[index] = grayscaleArgb(1f)
for (index in 20 until 40) candidatePixels[index] = grayscaleArgb(0f)
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertEquals(60, match!!.sampleCount)
assertEquals(1f, match.matchLog2Error, 0.02f)
}
@Test
fun candidateClippingInsideReferenceSampleSetRemainsAVisibleError() {
val width = 8
val height = 8
val referencePixels = grayscalePixels(width, height, linearLuma = 0.18f)
val reference = buildReference(referencePixels, width, height)
val candidatePixels = grayscalePixels(width, height, linearLuma = 0.36f)
for (index in 0 until candidatePixels.size / 2) {
candidatePixels[index] = grayscaleArgb(0f)
}
val match = RawViewfinderExposureMath.evaluate(
reference = reference,
pixels = candidatePixels,
width = width,
height = height,
)
assertNotNull(match)
assertTrue(match!!.matchLog2Error < -1f)
}
@Test
fun referenceWithOnlyClippedPixelsIsRejected() {
val pixels = IntArray(64) { index ->
if (index % 2 == 0) grayscaleArgb(0f) else grayscaleArgb(1f)
}
val reference = RawViewfinderExposureMath.buildReference(
pixels = pixels,
width = 8,
height = 8,
left = 0,
top = 0,
right = 8,
bottom = 8,
)
assertNull(reference)
}
@Test
fun solverMeasuresUnknownDisplaySlopeBeforeInterpolatingRawEv() {
val calls = mutableListOf<Float>()
val solvedEv = RawViewfinderExposureMath.solve { exposureEv ->
calls += exposureEv
(exposureEv - 1.25f) * 0.4f
}
assertNotNull(solvedEv)
assertEquals(1.25f, solvedEv!!, 0.001f)
assertEquals(0f, calls[0], 0.0001f)
assertEquals(0.5f, calls[1], 0.0001f)
assertTrue(calls.size <= 3)
}
@Test
fun solverProbesInNegativeDirectionWhenCandidateIsTooBright() {
val calls = mutableListOf<Float>()
val solvedEv = RawViewfinderExposureMath.solve { exposureEv ->
calls += exposureEv
(exposureEv + 1.5f) * 0.6f
}
assertNotNull(solvedEv)
assertEquals(-1.5f, solvedEv!!, 0.001f)
assertEquals(-0.5f, calls[1], 0.0001f)
}
@Test
fun solverExpandsProbeAcrossAFlatToneMappedRegion() {
val calls = mutableListOf<Float>()
val solvedEv = RawViewfinderExposureMath.solve { exposureEv ->
calls += exposureEv
if (exposureEv < 1.5f) {
-0.5f
} else {
exposureEv - 2f
}
}
assertNotNull(solvedEv)
assertEquals(2f, solvedEv!!, 0.001f)
assertEquals(listOf(0f, 0.5f, 1.5f, 3.5f, 2f), calls)
}
private fun buildReference(
pixels: IntArray,
width: Int,
height: Int,
): RawViewfinderExposureMath.Reference {
return RawViewfinderExposureMath.buildReference(
pixels = pixels,
width = width,
height = height,
left = 0,
top = 0,
right = width,
bottom = height,
) ?: error("Expected a valid reference")
}
private fun grayscalePixels(width: Int, height: Int, linearLuma: Float): IntArray {
return IntArray(width * height) { grayscaleArgb(linearLuma) }
}
private fun grayscaleArgb(linearLuma: Float): Int {
val byte = linearToSrgbByte(linearLuma)
return (0xff shl 24) or (byte shl 16) or (byte shl 8) or byte
}
private fun linearToSrgbByte(linear: Float): Int {
val clamped = linear.coerceIn(0f, 1f)
val srgb = if (clamped <= 0.0031308f) {
clamped * 12.92f
} else {
1.055f * clamped.pow(1f / 2.4f) - 0.055f
}
return (srgb * 255f).roundToInt().coerceIn(0, 255)
}
}