feat: ai lut creator

This commit is contained in:
zhoubinjia committed 2026-07-30 13:50:26 +08:00
1 parent 2a1b8b6635
commit 25b7a7715e
7 files changed
+994 -343

No files matched your search

@@ -4,15 +4,27 @@ import android.graphics.Bitmap
import androidx.core.graphics.scale
object AiImagePreprocessor {
private const val MAX_EDGE = 1024
private const val VISION_MAX_EDGE = 1024
private const val IMAGE_EDIT_MAX_EDGE = 1024
fun prepareForVisionAnalysis(bitmap: Bitmap): Bitmap {
if (bitmap.width <= VISION_MAX_EDGE && bitmap.height <= VISION_MAX_EDGE) {
return bitmap
}
val scale = VISION_MAX_EDGE.toFloat() / maxOf(bitmap.width, bitmap.height)
val width = (bitmap.width * scale).toInt().coerceAtLeast(1)
val height = (bitmap.height * scale).toInt().coerceAtLeast(1)
return bitmap.scale(width, height)
}
fun prepareForImageToImage(bitmap: Bitmap): Bitmap {
val squareBitmap = cropBitmapToSquare(bitmap)
if (squareBitmap.width <= MAX_EDGE && squareBitmap.height <= MAX_EDGE) {
if (squareBitmap.width <= IMAGE_EDIT_MAX_EDGE && squareBitmap.height <= IMAGE_EDIT_MAX_EDGE) {
return squareBitmap
}
return squareBitmap.scale(MAX_EDGE, MAX_EDGE)
return squareBitmap.scale(IMAGE_EDIT_MAX_EDGE, IMAGE_EDIT_MAX_EDGE)
}
private fun cropBitmapToSquare(bitmap: Bitmap): Bitmap {
@@ -275,7 +275,7 @@ object LocalImageAnalyzer {
)
} else {
// Fallback: If no neutral pixels found for this luminance, add a slightly stabilized identity point
// with lower weight in logic (or just skip to let RBF decide)
// with lower weight in logic (or just skip to let local interpolation decide)
if (step == 0 || step == toneSteps - 1) {
val fallbackL = targetL
controlPoints.add(
@@ -751,8 +751,8 @@ object LocalImageAnalyzer {
}
private fun mergeNearbyControlPoints(controlPoints: List<ControlPoint>): List<ControlPoint> {
// This is CRITICAL. If two points are very close in Source space but have different Targets,
// the RBF solver will explode (matrix singularity). We merge points within 0.05 distance.
// Nearby source samples with conflicting targets destabilize any local interpolator.
// Merge points within 0.05 distance before LUT generation.
val finalPoints = mutableListOf<ControlPoint>()
for (p in controlPoints) {
var merged = false
@@ -56,7 +56,7 @@ class LutCreatorViewModel(application: Application) : AndroidViewModel(applicati
val context = getApplication<Application>()
val client = OpenAIApiClient()
client.initialize(context)
val preparedBitmap = AiImagePreprocessor.prepareForImageToImage(bitmap)
val preparedBitmap = AiImagePreprocessor.prepareForVisionAnalysis(bitmap)
PLog.d(
"LutCreatorViewModel",
@@ -4,306 +4,562 @@ import kotlin.math.*
/**
* Generator for applying the LutRecipe parameters to a color grid
* and interpolating it into a 33x33x33 3D Matrix (Cube LUT) using RBF
* (Radial Basis Function) interpolation.
* and interpolating it into a 33x33x33 3D Matrix (Cube LUT) using
* confidence-weighted local residual interpolation in Oklab.
*/
object LutGenerator {
private const val INTERPOLATION_NEIGHBORS = 20
private const val INTERPOLATION_POWER = 2.4
private const val SMOOTH_ITERATIONS = 2
private const val SMOOTH_STRENGTH = 0.28f
private const val CLOSEST_PROJECTION_BLEND = 0.14f
private const val MONOTONIC_EPSILON = 1e-5f
private const val RESIDUAL_RANGE_SIGMA = 0.07f
/**
* Given an existing Style Recipe (which maps Source -> Target),
* and a list of specific Local Target points, this function uses Inverse RBF
* to deduce what the original Source colors must have been to yield those targets.
*
* It does this by building an RBF that maps Target -> Source.
*/
fun inverseInterpolate(styleRecipe: LutRecipe, localTargets: List<ControlPoint>): List<ControlPoint> {
val n = styleRecipe.controlPoints.size
if (n == 0) return localTargets
val matrixSize = n + 4
val M = Array(matrixSize) { DoubleArray(matrixSize) }
val B = Array(matrixSize) { DoubleArray(3) }
val pts = styleRecipe.controlPoints
// Build system mapping Target -> Source Residual (Source - Target)
for (i in 0 until n) {
val p1 = pts[i]
// We fit the inverse residual: Source - Target
B[i][0] = (p1.sourceR - p1.targetR).toDouble()
B[i][1] = (p1.sourceG - p1.targetG).toDouble()
B[i][2] = (p1.sourceB - p1.targetB).toDouble()
for (j in 0 until n) {
val p2 = pts[j]
val dr = p1.targetR - p2.targetR
val dg = p1.targetG - p2.targetG
val db = p1.targetB - p2.targetB
val dist = sqrt((dr * dr + dg * dg + db * db).toDouble())
M[i][j] = phi(dist)
}
M[i][i] += 1e-4 // Regularization for Cubic RBF
// Polynomial P block (based on Target as input)
M[i][n] = 1.0
M[i][n + 1] = p1.targetR.toDouble()
M[i][n + 2] = p1.targetG.toDouble()
M[i][n + 3] = p1.targetB.toDouble()
// Polynomial P^T block
M[n][i] = 1.0
M[n + 1][i] = p1.targetR.toDouble()
M[n + 2][i] = p1.targetG.toDouble()
M[n + 3][i] = p1.targetB.toDouble()
}
val W = solveLinearSystem(M, B)
// Evaluate Inverse RBF for each local target
return localTargets.map { local ->
val tInR = local.targetR.toDouble()
val tInG = local.targetG.toDouble()
val tInB = local.targetB.toDouble()
// Base affine output
var sOutR = tInR + W[n][0] + W[n + 1][0] * tInR + W[n + 2][0] * tInG + W[n + 3][0] * tInB
var sOutG = tInG + W[n][1] + W[n + 1][1] * tInR + W[n + 2][1] * tInG + W[n + 3][1] * tInB
var sOutB = tInB + W[n][2] + W[n + 1][2] * tInR + W[n + 2][2] * tInG + W[n + 3][2] * tInB
// RBF kernel contributions
for (i in 0 until n) {
val p = pts[i]
val dr = tInR - p.targetR
val dg = tInG - p.targetG
val db = tInB - p.targetB
val dist = sqrt(dr * dr + dg * dg + db * db)
val rbfVal = phi(dist)
sOutR += W[i][0] * rbfVal
sOutG += W[i][1] * rbfVal
sOutB += W[i][2] * rbfVal
}
ControlPoint(
sourceR = sOutR.toFloat().coerceIn(0f, 1f),
sourceG = sOutG.toFloat().coerceIn(0f, 1f),
sourceB = sOutB.toFloat().coerceIn(0f, 1f),
targetR = local.targetR,
targetG = local.targetG,
targetB = local.targetB
)
}
}
private data class OklabMapping(
val source: FloatArray,
val residual: FloatArray,
val confidence: Float
)
/**
* Generate a 33x33x33 Cube LUT representation from a LutRecipe.
* Returns a float array of size 33 * 33 * 33 * 3
* Returns a float array of size 33 * 33 * 33 * 3
* where each RGB element is stored sequentially.
*/
fun generateLut(recipe: LutRecipe, size: Int = 33): FloatArray {
val lutData = FloatArray(size * size * size * 3)
var index = 0
require(size >= 2) { "LUT size must be at least 2" }
if (recipe.controlPoints.isEmpty()) return createIdentityLut(size)
val n = recipe.controlPoints.size
// If no control points, return Identity LUT
if (n == 0) {
for (bIdx in 0 until size) {
val bIn = bIdx.toFloat() / (size - 1)
for (gIdx in 0 until size) {
val gIn = gIdx.toFloat() / (size - 1)
for (rIdx in 0 until size) {
val rIn = rIdx.toFloat() / (size - 1)
lutData[index++] = rIn
lutData[index++] = gIn
lutData[index++] = bIn
}
}
}
return lutData
}
// --- RBF Solver Setup (Using Affine Linear RBF System) ---
// We solve for weights W that map Source colors to residuals: (Target - Source).
// This ensures the affine polynomial P(x) can default to Identity.
// The size of the system is (N + 4) x (N + 4)
val matrixSize = n + 4
val M = Array(matrixSize) { DoubleArray(matrixSize) }
val B = Array(matrixSize) { DoubleArray(3) }
val pts = recipe.controlPoints
for (i in 0 until n) {
val p1 = pts[i]
// We fit the residual: Target - Source
B[i][0] = (p1.targetR - p1.sourceR).toDouble()
B[i][1] = (p1.targetG - p1.sourceG).toDouble()
B[i][2] = (p1.targetB - p1.sourceB).toDouble()
for (j in 0 until n) {
val p2 = pts[j]
val dr = p1.sourceR - p2.sourceR
val dg = p1.sourceG - p2.sourceG
val db = p1.sourceB - p2.sourceB
val dist = sqrt((dr * dr + dg * dg + db * db).toDouble())
M[i][j] = phi(dist)
}
M[i][i] += 1e-4 // Regularization
// Polynomial P block
M[i][n] = 1.0
M[i][n + 1] = p1.sourceR.toDouble()
M[i][n + 2] = p1.sourceG.toDouble()
M[i][n + 3] = p1.sourceB.toDouble()
// Polynomial P^T block
M[n][i] = 1.0
M[n + 1][i] = p1.sourceR.toDouble()
M[n + 2][i] = p1.sourceG.toDouble()
M[n + 3][i] = p1.sourceB.toDouble()
}
// The remaining bottom-right 4x4 of M is 0.0 (already default)
// The remaining bottom 4 rows of B are 0.0 (already default)
// Solve M * W = B for W
val W = solveLinearSystem(M, B)
// Generate LUT
for (bIdx in 0 until size) {
val bIn = bIdx.toDouble() / (size - 1)
for (gIdx in 0 until size) {
val gIn = gIdx.toDouble() / (size - 1)
for (rIdx in 0 until size) {
val rIn = rIdx.toDouble() / (size - 1)
// Start with affine polynomial part. Note: we are fitting the *residual*,
// so the base output is just the input: (rIn, gIn, bIn)
var rOut = rIn + W[n][0] + W[n + 1][0] * rIn + W[n + 2][0] * gIn + W[n + 3][0] * bIn
var gOut = gIn + W[n][1] + W[n + 1][1] * rIn + W[n + 2][1] * gIn + W[n + 3][1] * bIn
var bOut = bIn + W[n][2] + W[n + 1][2] * rIn + W[n + 2][2] * gIn + W[n + 3][2] * bIn
// Add RBF kernel contributions
for (i in 0 until n) {
val p = pts[i]
val dr = rIn - p.sourceR
val dg = gIn - p.sourceG
val db = bIn - p.sourceB
val dist = sqrt(dr * dr + dg * dg + db * db)
val rbfVal = phi(dist)
rOut += W[i][0] * rbfVal
gOut += W[i][1] * rbfVal
bOut += W[i][2] * rbfVal
}
lutData[index++] = rOut.toFloat().coerceIn(0f, 1f)
lutData[index++] = gOut.toFloat().coerceIn(0f, 1f)
lutData[index++] = bOut.toFloat().coerceIn(0f, 1f)
}
}
}
enforceMonotonicity(lutData, size)
return lutData
validateControlPoints(recipe.controlPoints)
val identity = createIdentityLut(size)
val mappings = recipe.controlPoints.map(::toOklabMapping)
val rawLut = interpolateOklabResiduals(identity, mappings, recipe.isMonochrome)
return constrainSmoothMonotonic(
rawLut = rawLut,
identityLut = identity,
size = size,
isMonochrome = recipe.isMonochrome
)
}
/**
* Ensures that as input RGB increases, output RGB also increases (or stays same).
* Prevents "solarization" and extreme color inversion artifacts.
* Projects the LUT onto a smooth monotonic result while retaining the closest
* style-preserving projection as an attractor.
*/
private fun enforceMonotonicity(lut: FloatArray, size: Int) {
// We iterate through the 3D grid and ensure that each channel
// respects a basic growth trend relative to its own axis.
// 1. Red channel: must be non-decreasing as input Red increases
private fun constrainSmoothMonotonic(
rawLut: FloatArray,
identityLut: FloatArray,
size: Int,
isMonochrome: Boolean
): FloatArray {
val closestMonotonic = if (isMonochrome) {
projectMonochromePava(rawLut, size)
} else {
projectPrimaryChannelsPava(rawLut, size)
}
var current = closestMonotonic
repeat(SMOOTH_ITERATIONS) {
val smoothed = if (isMonochrome) {
smoothMonochromeResidual(current, identityLut, size, SMOOTH_STRENGTH)
} else {
smoothColorResidual(current, identityLut, size, SMOOTH_STRENGTH)
}
val projected = if (isMonochrome) {
projectMonochromePava(smoothed, size)
} else {
projectPrimaryChannelsPava(smoothed, size)
}
current = FloatArray(projected.size) { index ->
projected[index] * (1f - CLOSEST_PROJECTION_BLEND) +
closestMonotonic[index] * CLOSEST_PROJECTION_BLEND
}
}
return FloatArray(current.size) { index ->
val value = current[index]
require(value.isFinite()) { "Generated LUT contains a non-finite value at index $index" }
value.coerceIn(0f, 1f)
}
}
internal fun projectPrimaryChannelsPava(lut: FloatArray, size: Int): FloatArray {
require(lut.size == size * size * size * 3)
val result = lut.copyOf()
val sequence = FloatArray(size)
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) {
sequence[r] = result[gridOffset(b, g, r, size)]
}
val projected = pavaNonDecreasing(sequence)
for (r in 0 until size) {
result[gridOffset(b, g, r, size)] = projected[r]
}
}
}
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 0 until size) {
sequence[g] = result[gridOffset(b, g, r, size) + 1]
}
val projected = pavaNonDecreasing(sequence)
for (g in 0 until size) {
result[gridOffset(b, g, r, size) + 1] = projected[g]
}
}
}
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 0 until size) {
sequence[b] = result[gridOffset(b, g, r, size) + 2]
}
val projected = pavaNonDecreasing(sequence)
for (b in 0 until size) {
result[gridOffset(b, g, r, size) + 2] = projected[b]
}
}
}
return result
}
internal fun pavaNonDecreasing(sequence: FloatArray): FloatArray {
if (sequence.isEmpty()) return sequence.copyOf()
require(sequence.all(Float::isFinite)) { "PAVA input must be finite" }
val levels = FloatArray(sequence.size)
val weights = IntArray(sequence.size)
val starts = IntArray(sequence.size)
val ends = IntArray(sequence.size)
var blockCount = 0
sequence.forEachIndexed { index, value ->
levels[blockCount] = value
weights[blockCount] = 1
starts[blockCount] = index
ends[blockCount] = index
blockCount++
while (blockCount >= 2 && levels[blockCount - 2] > levels[blockCount - 1]) {
val left = blockCount - 2
val right = blockCount - 1
val mergedWeight = weights[left] + weights[right]
levels[left] =
(levels[left] * weights[left] + levels[right] * weights[right]) / mergedWeight
weights[left] = mergedWeight
ends[left] = ends[right]
blockCount--
}
}
return FloatArray(sequence.size).also { result ->
for (block in 0 until blockCount) {
for (index in starts[block]..ends[block]) {
result[index] = levels[block]
}
}
}
}
internal fun maxPrimaryMonotonicViolation(lut: FloatArray, size: Int): Float {
var maxViolation = 0f
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 1 until size) {
val currIdx = (b * size * size + g * size + r) * 3
val prevIdx = (b * size * size + g * size + (r - 1)) * 3
lut[currIdx] = max(lut[currIdx], lut[prevIdx])
val current = lut[gridOffset(b, g, r, size)]
val previous = lut[gridOffset(b, g, r - 1, size)]
maxViolation = max(maxViolation, previous - current)
}
}
}
// 2. Green channel: must be non-decreasing as input Green increases
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 1 until size) {
val currIdx = (b * size * size + g * size + r) * 3 + 1
val prevIdx = (b * size * size + (g - 1) * size + r) * 3 + 1
lut[currIdx] = max(lut[currIdx], lut[prevIdx])
val current = lut[gridOffset(b, g, r, size) + 1]
val previous = lut[gridOffset(b, g - 1, r, size) + 1]
maxViolation = max(maxViolation, previous - current)
}
}
}
// 3. Blue channel: must be non-decreasing as input Blue increases
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 1 until size) {
val currIdx = (b * size * size + g * size + r) * 3 + 2
val prevIdx = ((b - 1) * size * size + g * size + r) * 3 + 2
lut[currIdx] = max(lut[currIdx], lut[prevIdx])
val current = lut[gridOffset(b, g, r, size) + 2]
val previous = lut[gridOffset(b - 1, g, r, size) + 2]
maxViolation = max(maxViolation, previous - current)
}
}
}
return maxViolation
}
private fun projectMonochromePava(lut: FloatArray, size: Int): FloatArray {
val gray = FloatArray(size * size * size) { index ->
val offset = index * 3
rec709Luma(lut[offset], lut[offset + 1], lut[offset + 2])
}
val sequence = FloatArray(size)
repeat(8) {
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) sequence[r] = gray[gridIndex(b, g, r, size)]
val projected = pavaNonDecreasing(sequence)
for (r in 0 until size) gray[gridIndex(b, g, r, size)] = projected[r]
}
}
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 0 until size) sequence[g] = gray[gridIndex(b, g, r, size)]
val projected = pavaNonDecreasing(sequence)
for (g in 0 until size) gray[gridIndex(b, g, r, size)] = projected[g]
}
}
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 0 until size) sequence[b] = gray[gridIndex(b, g, r, size)]
val projected = pavaNonDecreasing(sequence)
for (b in 0 until size) gray[gridIndex(b, g, r, size)] = projected[b]
}
}
if (maxScalarMonotonicViolation(gray, size) <= MONOTONIC_EPSILON) {
return expandGray(gray)
}
}
enforceScalarCumulativeFallback(gray, size)
return expandGray(gray)
}
private fun maxScalarMonotonicViolation(gray: FloatArray, size: Int): Float {
var maxViolation = 0f
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 1 until size) {
maxViolation = max(
maxViolation,
gray[gridIndex(b, g, r - 1, size)] - gray[gridIndex(b, g, r, size)]
)
}
}
}
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 1 until size) {
maxViolation = max(
maxViolation,
gray[gridIndex(b, g - 1, r, size)] - gray[gridIndex(b, g, r, size)]
)
}
}
}
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 1 until size) {
maxViolation = max(
maxViolation,
gray[gridIndex(b - 1, g, r, size)] - gray[gridIndex(b, g, r, size)]
)
}
}
}
return maxViolation
}
private fun enforceScalarCumulativeFallback(gray: FloatArray, size: Int) {
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 1 until size) {
val index = gridIndex(b, g, r, size)
gray[index] = max(gray[index], gray[gridIndex(b, g, r - 1, size)])
}
}
}
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 1 until size) {
val index = gridIndex(b, g, r, size)
gray[index] = max(gray[index], gray[gridIndex(b, g - 1, r, size)])
}
}
}
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 1 until size) {
val index = gridIndex(b, g, r, size)
gray[index] = max(gray[index], gray[gridIndex(b - 1, g, r, size)])
}
}
}
}
private fun phi(r: Double): Double {
// Cubic radial basis phi(r) = r^3 provides C2 continuity and much smoother
// color transitions, effectively suppressing "ringing" and color casts.
return r * r * r
}
private fun interpolateOklabResiduals(
identityLut: FloatArray,
mappings: List<OklabMapping>,
isMonochrome: Boolean
): FloatArray {
val result = FloatArray(identityLut.size)
val nearestCount = min(INTERPOLATION_NEIGHBORS, mappings.size)
val nearestIndices = IntArray(nearestCount)
val nearestDistances = DoubleArray(nearestCount)
/**
* Solves linear system A * X = B using Gaussian elimination with partial pivoting.
* A is N x N, B is N x M. Returns X as N x M.
*/
private fun solveLinearSystem(A: Array<DoubleArray>, B: Array<DoubleArray>): Array<DoubleArray> {
val n = A.size
val m = B[0].size
val M = Array(n) { i -> DoubleArray(n + m) { j -> if (j < n) A[i][j] else B[i][j - n] } }
for (offset in identityLut.indices step 3) {
val input = srgbToOklab(
identityLut[offset],
identityLut[offset + 1],
identityLut[offset + 2]
)
nearestDistances.fill(Double.POSITIVE_INFINITY)
for (i in 0 until n) {
var maxRow = i
for (k in i + 1 until n) {
if (abs(M[k][i]) > abs(M[maxRow][i])) maxRow = k
}
val temp = M[i]
M[i] = M[maxRow]
M[maxRow] = temp
mappings.forEachIndexed { mappingIndex, mapping ->
val dL = (input[0] - mapping.source[0]).toDouble()
val da = (input[1] - mapping.source[1]).toDouble()
val db = (input[2] - mapping.source[2]).toDouble()
val distanceSquared = dL * dL + da * da + db * db
val pivot = M[i][i]
if (abs(pivot) < 1e-12) {
// If the matrix is singular (e.g., highly collinear or identical control points),
// we gracefully continue. The fallback polynomial handles it.
continue
}
for (j in i until n + m) {
M[i][j] /= pivot
}
for (k in 0 until n) {
if (k != i) {
val factor = M[k][i]
for (j in i until n + m) {
M[k][j] -= factor * M[i][j]
var insertionIndex = -1
for (candidate in 0 until nearestCount) {
if (distanceSquared < nearestDistances[candidate]) {
insertionIndex = candidate
break
}
}
if (insertionIndex >= 0) {
for (candidate in nearestCount - 1 downTo insertionIndex + 1) {
nearestDistances[candidate] = nearestDistances[candidate - 1]
nearestIndices[candidate] = nearestIndices[candidate - 1]
}
nearestDistances[insertionIndex] = distanceSquared
nearestIndices[insertionIndex] = mappingIndex
}
}
var weightSum = 0.0
var residualL = 0.0
var residualA = 0.0
var residualB = 0.0
for (neighbor in 0 until nearestCount) {
val mapping = mappings[nearestIndices[neighbor]]
val confidenceWeight = 0.25 + 0.75 * sqrt(mapping.confidence.toDouble())
val distanceWeight =
1.0 / (nearestDistances[neighbor].pow(INTERPOLATION_POWER / 2.0) + 1e-9)
val weight = confidenceWeight * distanceWeight
weightSum += weight
residualL += mapping.residual[0] * weight
residualA += mapping.residual[1] * weight
residualB += mapping.residual[2] * weight
}
val outputL = input[0] + (residualL / weightSum).toFloat()
val outputA = if (isMonochrome) 0f else input[1] + (residualA / weightSum).toFloat()
val outputB = if (isMonochrome) 0f else input[2] + (residualB / weightSum).toFloat()
val output = oklabToSrgb(outputL, outputA, outputB)
result[offset] = output[0]
result[offset + 1] = output[1]
result[offset + 2] = output[2]
}
val X = Array(n) { DoubleArray(m) }
for (i in 0 until n) {
for (j in 0 until m) {
X[i][j] = M[i][n + j]
return result
}
private fun smoothColorResidual(
lut: FloatArray,
identity: FloatArray,
size: Int,
strength: Float
): FloatArray {
val result = FloatArray(lut.size)
val sigmaDenominator = 2f * RESIDUAL_RANGE_SIGMA * RESIDUAL_RANGE_SIGMA * 3f
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) {
val offset = gridOffset(b, g, r, size)
val centerR = lut[offset] - identity[offset]
val centerG = lut[offset + 1] - identity[offset + 1]
val centerB = lut[offset + 2] - identity[offset + 2]
var sumR = 0.0
var sumG = 0.0
var sumB = 0.0
var weightSum = 0.0
for (db in -1..1) {
for (dg in -1..1) {
for (dr in -1..1) {
val neighborOffset = gridOffset(
(b + db).coerceIn(0, size - 1),
(g + dg).coerceIn(0, size - 1),
(r + dr).coerceIn(0, size - 1),
size
)
val neighborR = lut[neighborOffset] - identity[neighborOffset]
val neighborG = lut[neighborOffset + 1] - identity[neighborOffset + 1]
val neighborB = lut[neighborOffset + 2] - identity[neighborOffset + 2]
val deltaR = neighborR - centerR
val deltaG = neighborG - centerG
val deltaB = neighborB - centerB
val rangeDistance =
deltaR * deltaR + deltaG * deltaG + deltaB * deltaB
val spatialDistance = (db * db + dg * dg + dr * dr).toDouble()
val weight =
exp(-spatialDistance / 2.0) *
exp((-rangeDistance / sigmaDenominator).toDouble())
sumR += neighborR * weight
sumG += neighborG * weight
sumB += neighborB * weight
weightSum += weight
}
}
}
result[offset] =
identity[offset] + centerR * (1f - strength) + (sumR / weightSum).toFloat() * strength
result[offset + 1] =
identity[offset + 1] + centerG * (1f - strength) + (sumG / weightSum).toFloat() * strength
result[offset + 2] =
identity[offset + 2] + centerB * (1f - strength) + (sumB / weightSum).toFloat() * strength
}
}
}
return X
return result
}
private fun smoothMonochromeResidual(
lut: FloatArray,
identity: FloatArray,
size: Int,
strength: Float
): FloatArray {
val pointCount = size * size * size
val gray = FloatArray(pointCount)
val identityGray = FloatArray(pointCount)
for (index in 0 until pointCount) {
val offset = index * 3
gray[index] = rec709Luma(lut[offset], lut[offset + 1], lut[offset + 2])
identityGray[index] =
rec709Luma(identity[offset], identity[offset + 1], identity[offset + 2])
}
val smoothed = FloatArray(pointCount)
val sigmaDenominator = 2f * RESIDUAL_RANGE_SIGMA * RESIDUAL_RANGE_SIGMA
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) {
val index = gridIndex(b, g, r, size)
val center = gray[index] - identityGray[index]
var weightedSum = 0.0
var weightSum = 0.0
for (db in -1..1) {
for (dg in -1..1) {
for (dr in -1..1) {
val neighborIndex = gridIndex(
(b + db).coerceIn(0, size - 1),
(g + dg).coerceIn(0, size - 1),
(r + dr).coerceIn(0, size - 1),
size
)
val neighbor = gray[neighborIndex] - identityGray[neighborIndex]
val rangeDistance = (neighbor - center) * (neighbor - center)
val spatialDistance = (db * db + dg * dg + dr * dr).toDouble()
val weight =
exp(-spatialDistance / 2.0) *
exp((-rangeDistance / sigmaDenominator).toDouble())
weightedSum += neighbor * weight
weightSum += weight
}
}
}
smoothed[index] =
identityGray[index] + center * (1f - strength) +
(weightedSum / weightSum).toFloat() * strength
}
}
}
return expandGray(smoothed)
}
private fun validateControlPoints(controlPoints: List<ControlPoint>) {
controlPoints.forEachIndexed { index, point ->
val values = floatArrayOf(
point.sourceR,
point.sourceG,
point.sourceB,
point.targetR,
point.targetG,
point.targetB,
point.matchConfidence
)
require(values.all(Float::isFinite)) {
"LUT control point $index contains a non-finite value"
}
require(values.all { it in 0f..1f }) {
"LUT control point $index contains a value outside [0, 1]"
}
}
}
private fun toOklabMapping(point: ControlPoint): OklabMapping {
val source = srgbToOklab(point.sourceR, point.sourceG, point.sourceB)
val target = srgbToOklab(point.targetR, point.targetG, point.targetB)
return OklabMapping(
source = source,
residual = floatArrayOf(
target[0] - source[0],
target[1] - source[1],
target[2] - source[2]
),
confidence = point.matchConfidence
)
}
private fun srgbToOklab(r: Float, g: Float, b: Float): FloatArray =
OklchConverter.linearSrgbToOklab(
OklchConverter.srgbToLinear(r),
OklchConverter.srgbToLinear(g),
OklchConverter.srgbToLinear(b)
)
private fun oklabToSrgb(l: Float, a: Float, b: Float): FloatArray {
val linear = OklchConverter.oklabToLinearSrgb(l, a, b)
return floatArrayOf(
OklchConverter.linearToSrgb(linear[0]),
OklchConverter.linearToSrgb(linear[1]),
OklchConverter.linearToSrgb(linear[2])
)
}
private fun createIdentityLut(size: Int): FloatArray {
val result = FloatArray(size * size * size * 3)
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) {
val offset = gridOffset(b, g, r, size)
result[offset] = r.toFloat() / (size - 1)
result[offset + 1] = g.toFloat() / (size - 1)
result[offset + 2] = b.toFloat() / (size - 1)
}
}
}
return result
}
private fun expandGray(gray: FloatArray): FloatArray =
FloatArray(gray.size * 3) { index -> gray[index / 3] }
private fun rec709Luma(r: Float, g: Float, b: Float): Float =
r * 0.2126f + g * 0.7152f + b * 0.0722f
private fun gridIndex(b: Int, g: Int, r: Int, size: Int): Int =
b * size * size + g * size + r
private fun gridOffset(b: Int, g: Int, r: Int, size: Int): Int =
gridIndex(b, g, r, size) * 3
/**
* Converts raw 3D FloatArray back to the .cube file format as a String
*/
@@ -3,16 +3,17 @@ package com.hinnka.mycamera.lut.creator
import androidx.annotation.Keep
/**
* LUT recipe representing a color grading style as a set of Control Points for RBF interpolation.
* LUT recipe representing a color grading style as a set of weighted source/target samples.
*/
@Keep
data class LutRecipe(
val controlPoints: List<ControlPoint> = emptyList()
val controlPoints: List<ControlPoint> = emptyList(),
val isMonochrome: Boolean = false
)
/**
* A Control Point maps a source (un-stylized) color to a target (stylized) color.
* Coordinates are in normalized linear RGB or sRGB [0.0, 1.0].
* Coordinates are normalized display-referred sRGB values in [0.0, 1.0].
*/
@Keep
data class ControlPoint(
@@ -3,6 +3,7 @@ package com.hinnka.mycamera.lut.creator
import android.content.Context
import android.graphics.Bitmap
import android.util.Base64
import android.util.Log
import androidx.annotation.Keep
import com.hinnka.mycamera.BuildConfig
import com.hinnka.mycamera.utils.PLog
@@ -29,10 +30,12 @@ class OpenAIApiClient() {
private lateinit var apiBaseUrl: String
private lateinit var apiKey: String
private lateinit var model: String
private var isBuiltInService: Boolean = false
suspend fun initialize(context: Context) {
val userPrefs = ContentRepository.getInstance(context).userPreferencesRepository.userPreferences.firstOrNull()
val isBuiltIn = userPrefs?.openAIApiKey.isNullOrBlank()
isBuiltInService = isBuiltIn
apiKey = if (isBuiltIn) {
BUILT_IN_API_KEY
} else {
@@ -58,12 +61,14 @@ class OpenAIApiClient() {
val BUILT_IN_API_KEY = BuildConfig.BUILT_IN_API_KEY
const val BUILT_IN_IMAGE_MODEL = "gemini-3.5-flash"
const val BUILT_IN_MODEL = "gemini-3.5-flash"
const val CHAT_COMPLETIONS_STREAMING_ENABLED = false
}
private val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(300, TimeUnit.SECONDS)
.writeTimeout(300, TimeUnit.SECONDS)
.build()
suspend fun getAvailableModels(): Result<List<String>> = withContext(Dispatchers.IO) {
@@ -158,48 +163,50 @@ class OpenAIApiClient() {
withContext(Dispatchers.IO) {
try {
val base64Image = bitmapToBase64(bitmap)
val prompt = """
You are a professional color scientist for camera LUT creation.
The user uploads one already-styled target image. The current API cannot edit images, so do not generate or request a restored image.
Instead, infer a practical color grading recipe as text only.
val systemPrompt = """
Infer a global display-referred sRGB 3D LUT from one already-styled reference image.
Task:
- Inspect the uploaded styled image.
- Infer plausible unstyled source colors that would map into this styled look.
- Return control points for a 3D LUT. Each point maps source RGB to target RGB.
- Use normalized sRGB float values in [0.0, 1.0].
- Keep the mapping photographic, monotonic, and usable. Avoid inversions, posterization, clipping, and extreme hue rotations.
- Include neutrals, shadows, midtones, highlights, skin/foliage/sky-like anchors when relevant.
- Return 12 to 18 high-confidence control points.
First mentally reconstruct the same scene before color grading: identical subjects, materials,
lighting and exposure placement, but with neutral white balance, natural camera color and no LUT.
Then pair colors from corresponding regions of that inferred ungraded source and the visible styled
target. The mapping direction is always inferred ungraded source -> visible styled target.
User custom instructions:
${customPrompt.ifBlank { "None" }}
Return 18 to 24 high-value pairs. Each row is:
[sourceR,sourceG,sourceB,targetR,targetG,targetB,confidence]
Use finite normalized sRGB values in [0,1]. Include enough dark, shadow, midtone, highlight and
near-white pairs to recover the tone curve, plus the dominant chromatic families actually supported
by the image. Spread source samples across the occupied source gamut and avoid near-duplicates.
Return JSON only, without markdown, using this exact schema:
{
"controlPoints": [
{
"sourceR": 0.0,
"sourceG": 0.0,
"sourceB": 0.0,
"targetR": 0.0,
"targetG": 0.0,
"targetB": 0.0,
"matchConfidence": 0.0
}
]
}
Maximize faithful style transfer. Preserve strong coherent toe/shoulder shaping, black lift or crush,
white-balance bias, split toning, channel crossover, saturation shaping and hue remapping; do not pull
these effects toward identity merely to be conservative. Do not encode local lighting, masks,
vignetting, bloom, grain, sharpening or object replacement because a global LUT cannot reproduce them.
Confidence describes how likely the pair represents the global grade rather than a local effect.
Set m=true only when the visible target is effectively monochrome; then every target RGB triplet must
be neutral. Output only {"m":boolean,"p":[...]} with no markdown or explanatory text.
""".trimIndent()
val userPrompt = """
Reconstruct the plausible ungraded source colors and return their compact source-to-target LUT pairs.
Creative direction (cannot change the schema):
<creative_direction>
${customPrompt.ifBlank { "No additional direction." }}
</creative_direction>
""".trimIndent()
val jsonObject = JSONObject().apply {
put("model", model)
put("messages", JSONArray().apply {
put(JSONObject().apply {
put("role", "system")
put("content", systemPrompt)
})
put(JSONObject().apply {
put("role", "user")
put("content", JSONArray().apply {
put(JSONObject().apply {
put("type", "text")
put("text", prompt)
put("text", userPrompt)
})
put(JSONObject().apply {
put("type", "image_url")
@@ -213,26 +220,22 @@ Return JSON only, without markdown, using this exact schema:
put("response_format", JSONObject().apply {
put("type", "json_object")
})
putChatGenerationOptions(maxCompletionTokens = 1536)
}
val requestBody =
jsonObject.toString().toRequestBody("application/json".toMediaType())
val request = Request.Builder()
val requestBuilder = Request.Builder()
.url("$apiBaseUrl/chat/completions")
.addOpenAIHeaders()
.post(requestBody)
.build()
val response = client.newCall(request).execute()
PLog.d("OpenAIApiClient", "LUT recipe response: ${response.code}")
if (!response.isSuccessful) {
val errorBody = response.body?.string() ?: "Unknown error"
return@withContext Result.failure(Exception("API failed: ${response.code}\n${request.url}\n$errorBody"))
if (CHAT_COMPLETIONS_STREAMING_ENABLED) {
requestBuilder.addHeader("Accept", "text/event-stream")
}
val request = requestBuilder.build()
val responseBodyString = response.body?.string() ?: ""
val text = extractTextFromResponse(responseBodyString)
val text = executeChatCompletion(request, "LUT recipe")
Result.success(parseLutRecipe(text))
} catch (e: Exception) {
Result.failure(e)
@@ -287,8 +290,7 @@ Also provide:
- "improvement": the highest-leverage, actionable change for shooting, selection,
framing, timing, light, or editing. Do not prescribe a generic rule.
The user's current system language is "$localeTag". Every feedback string,
"verdict", "strength", and "improvement" MUST be written in that language.
The user's current system language is "$localeTag". Every feedback string MUST be written in that language.
Return JSON only, without markdown formatting, code blocks, or any conversational text, using this exact schema:
{
"visualImpact": {
@@ -339,47 +341,163 @@ Return JSON only, without markdown formatting, code blocks, or any conversationa
put("response_format", JSONObject().apply {
put("type", "json_object")
})
putChatGenerationOptions(maxCompletionTokens = 1024)
}
val requestBody =
jsonObject.toString().toRequestBody("application/json".toMediaType())
val request = Request.Builder()
val requestBuilder = Request.Builder()
.url("$apiBaseUrl/chat/completions")
.addOpenAIHeaders()
.post(requestBody)
.build()
val response = client.newCall(request).execute()
PLog.d("OpenAIApiClient", "Evaluate response: ${response.code}")
if (!response.isSuccessful) {
val errorBody = response.body?.string() ?: "Unknown error"
return@withContext Result.failure(Exception("API failed: ${response.code}\n${request.url}\n$errorBody"))
if (CHAT_COMPLETIONS_STREAMING_ENABLED) {
requestBuilder.addHeader("Accept", "text/event-stream")
}
val request = requestBuilder.build()
val responseBodyString = response.body?.string() ?: ""
val text = extractTextFromResponse(responseBodyString)
val text = executeChatCompletion(request, "Evaluate")
Result.success(parseEvaluation(text))
} catch (e: Exception) {
Result.failure(e)
}
}
private fun extractTextFromResponse(responseBodyString: String): String {
val jsonResponse = JSONObject(responseBodyString)
jsonResponse.optJSONArray("choices")?.let { choices ->
if (choices.length() > 0) {
val firstChoice = choices.getJSONObject(0)
val message = firstChoice.optJSONObject("message")
val contentText = message?.extractOpenAIContentText().orEmpty()
if (contentText.isNotBlank()) return contentText
val text = firstChoice.optString("text")
if (text.isNotBlank()) return text
}
private fun executeChatCompletion(request: Request, operation: String): String =
if (CHAT_COMPLETIONS_STREAMING_ENABLED) {
executeStreamingChatCompletion(request, operation)
} else {
executeNonStreamingChatCompletion(request, operation)
}
return responseBodyString
private fun JSONObject.putChatGenerationOptions(maxCompletionTokens: Int) {
put("max_tokens", maxCompletionTokens)
put("stream", CHAT_COMPLETIONS_STREAMING_ENABLED)
}
private fun executeNonStreamingChatCompletion(request: Request, operation: String): String {
return client.newCall(request).execute().use { response ->
PLog.d("OpenAIApiClient", "$operation response: ${response.code}")
if (!response.isSuccessful) {
val errorBody = response.body?.string() ?: "Unknown error"
throw Exception("API failed: ${response.code}\n${request.url}\n$errorBody")
}
val responseBody = response.body?.string()
?: throw Exception("$operation returned an empty response body")
extractTextFromResponse(responseBody).takeIf { it.isNotBlank() }
?: throw Exception("$operation completed without text content")
}
}
private fun executeStreamingChatCompletion(request: Request, operation: String): String {
return client.newCall(request).execute().use { response ->
PLog.d("OpenAIApiClient", "$operation stream response: ${response.code}")
if (!response.isSuccessful) {
val errorBody = response.body?.string() ?: "Unknown error"
throw Exception("API failed: ${response.code}\n${request.url}\n$errorBody")
}
val body = response.body
?: throw Exception("$operation stream returned an empty response body")
val source = body.source()
val output = StringBuilder()
val eventData = StringBuilder()
var streamFinished = false
fun consumeEvent(): Boolean {
if (eventData.isEmpty()) return false
val payload = eventData.toString().trim()
eventData.setLength(0)
if (payload.isEmpty()) return false
if (payload == "[DONE]") return true
val event = try {
JSONObject(payload)
} catch (e: Exception) {
throw IllegalArgumentException(
"$operation stream returned malformed SSE data: ${payload.take(200)}",
e
)
}
event.opt("error")
?.takeUnless { it == JSONObject.NULL }
?.let { error ->
throw Exception("$operation stream failed: $error")
}
output.append(extractStreamingChunkText(event))
return false
}
while (!streamFinished) {
val line = source.readUtf8Line()
if (line == null) {
consumeEvent()
break
}
when {
line.isEmpty() -> streamFinished = consumeEvent()
line.startsWith("data:") -> {
if (eventData.isNotEmpty()) eventData.append('\n')
eventData.append(line.substringAfter("data:").trimStart())
PLog.d("Hinnka", "executeStreamingChatCompletion: $eventData")
}
line.trimStart().startsWith("{") -> {
if (eventData.isNotEmpty()) eventData.append('\n')
eventData.append(line.trim())
PLog.d("Hinnka", "executeStreamingChatCompletion: $eventData")
}
}
}
output.toString().takeIf { it.isNotBlank() }
?: throw Exception("$operation stream completed without text content")
}
}
private fun extractTextFromResponse(responseBody: String): String {
val response = JSONObject(responseBody)
val choices = response.optJSONArray("choices") ?: return responseBody
if (choices.length() == 0) return responseBody
val firstChoice = choices.optJSONObject(0) ?: return responseBody
val messageText = firstChoice.optJSONObject("message")
?.extractOpenAIContentText()
.orEmpty()
if (messageText.isNotBlank()) return messageText
return firstChoice.optString("text")
.takeIf { it.isNotBlank() }
?: responseBody
}
private fun extractStreamingChunkText(event: JSONObject): String {
val choices = event.optJSONArray("choices") ?: return ""
val text = StringBuilder()
for (index in 0 until choices.length()) {
val choice = choices.optJSONObject(index) ?: continue
val deltaText = choice.optJSONObject("delta")
?.extractOpenAIContentText()
.orEmpty()
if (deltaText.isNotEmpty()) {
text.append(deltaText)
continue
}
val messageText = choice.optJSONObject("message")
?.extractOpenAIContentText()
.orEmpty()
if (messageText.isNotEmpty()) {
text.append(messageText)
continue
}
choice.optString("text")
.takeIf { it.isNotEmpty() }
?.let(text::append)
}
return text.toString()
}
private fun parseEvaluation(text: String): AiPhotoEvaluation {
@@ -432,32 +550,115 @@ Return JSON only, without markdown formatting, code blocks, or any conversationa
private fun parseLutRecipe(text: String): LutRecipe {
val json = JSONObject(extractJsonObjectText(text))
if (json.has("p")) {
return parseInferredSourceLutRecipe(json)
}
val isMonochrome = json.optBoolean("isMonochrome", false)
val controlPointsJson = json.optJSONArray("controlPoints")
?: throw IllegalArgumentException("AI response did not include controlPoints")
val controlPoints = buildList {
for (i in 0 until controlPointsJson.length()) {
val item = controlPointsJson.optJSONObject(i) ?: continue
for (index in 0 until controlPointsJson.length()) {
val item = controlPointsJson.optJSONObject(index)
?: throw IllegalArgumentException(
"AI control point at index $index was not an object"
)
add(
ControlPoint(
sourceR = item.optDouble("sourceR").toFloat().coerceIn(0f, 1f),
sourceG = item.optDouble("sourceG").toFloat().coerceIn(0f, 1f),
sourceB = item.optDouble("sourceB").toFloat().coerceIn(0f, 1f),
targetR = item.optDouble("targetR").toFloat().coerceIn(0f, 1f),
targetG = item.optDouble("targetG").toFloat().coerceIn(0f, 1f),
targetB = item.optDouble("targetB").toFloat().coerceIn(0f, 1f),
matchConfidence = item.optDouble("matchConfidence", 0.8).toFloat()
.coerceIn(0f, 1f)
sourceR = item.requireUnitFloat("sourceR", index),
sourceG = item.requireUnitFloat("sourceG", index),
sourceB = item.requireUnitFloat("sourceB", index),
targetR = item.requireUnitFloat("targetR", index),
targetG = item.requireUnitFloat("targetG", index),
targetB = item.requireUnitFloat("targetB", index),
matchConfidence = if (item.has("matchConfidence")) {
item.requireUnitFloat("matchConfidence", index)
} else {
0.8f
}
)
)
}
}
require(controlPoints.size >= 6) {
"AI returned too few inferred source/target pairs: ${controlPoints.size}"
}
validateMonochromeTargets(controlPoints, isMonochrome)
return LutRecipe(
controlPoints = controlPoints,
isMonochrome = isMonochrome
)
}
if (controlPoints.size < 6) {
throw IllegalArgumentException("AI returned too few LUT control points: ${controlPoints.size}")
private fun parseInferredSourceLutRecipe(json: JSONObject): LutRecipe {
require(json.has("m")) { "AI response did not include compact monochrome flag m" }
val isMonochrome = json.getBoolean("m")
val pairs = json.optJSONArray("p")
?: throw IllegalArgumentException("AI response field p was not an array")
require(pairs.length() in 12..32) {
"AI returned ${pairs.length()} inferred source/target pairs; expected 12..32"
}
return LutRecipe(controlPoints)
val controlPoints = buildList {
for (index in 0 until pairs.length()) {
val pair = pairs.optJSONArray(index)
?: throw IllegalArgumentException("AI LUT pair $index was not an array")
require(pair.length() == 7) {
"AI LUT pair $index must contain [sourceR,sourceG,sourceB,targetR,targetG,targetB,confidence]"
}
add(
ControlPoint(
sourceR = pair.requireUnitFloat(0, index),
sourceG = pair.requireUnitFloat(1, index),
sourceB = pair.requireUnitFloat(2, index),
targetR = pair.requireUnitFloat(3, index),
targetG = pair.requireUnitFloat(4, index),
targetB = pair.requireUnitFloat(5, index),
matchConfidence = pair.requireUnitFloat(6, index)
)
)
}
}
validateMonochromeTargets(controlPoints, isMonochrome)
return LutRecipe(
controlPoints = controlPoints,
isMonochrome = isMonochrome
)
}
private fun validateMonochromeTargets(
controlPoints: List<ControlPoint>,
isMonochrome: Boolean
) {
if (!isMonochrome) return
controlPoints.forEachIndexed { index, point ->
require(
kotlin.math.abs(point.targetR - point.targetG) <= 1e-3f &&
kotlin.math.abs(point.targetR - point.targetB) <= 1e-3f
) {
"AI returned a chromatic target for monochrome LUT pair $index"
}
}
}
private fun JSONObject.requireUnitFloat(name: String, pairIndex: Int): Float {
require(has(name)) {
"AI response pair $pairIndex did not include $name"
}
val value = getDouble(name)
require(value.isFinite() && value in 0.0..1.0) {
"AI response pair $pairIndex field $name was outside [0, 1]"
}
return value.toFloat()
}
private fun JSONArray.requireUnitFloat(componentIndex: Int, pairIndex: Int): Float {
val value = getDouble(componentIndex)
require(value.isFinite() && value in 0.0..1.0) {
"AI LUT pair $pairIndex component $componentIndex was outside [0, 1]"
}
return value.toFloat()
}
private fun extractJsonObjectText(text: String): String {
@@ -0,0 +1,181 @@
package com.hinnka.mycamera.lut.creator
import kotlin.math.abs
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
class LutGeneratorTest {
@Test
fun pavaNonDecreasing_returnsClosestL2Projection() {
val actual = LutGenerator.pavaNonDecreasing(floatArrayOf(0.2f, 0.9f, 0.3f))
assertArrayEquals(floatArrayOf(0.2f, 0.6f, 0.6f), actual, 1e-6f)
}
@Test
fun primaryProjection_removesEveryPrimaryAxisViolation() {
val size = 3
val lut = identityLut(size)
lut[offset(size, b = 1, g = 1, r = 1)] = 0.9f
lut[offset(size, b = 1, g = 1, r = 2)] = 0.2f
lut[offset(size, b = 1, g = 1, r = 1) + 1] = 0.9f
lut[offset(size, b = 1, g = 2, r = 1) + 1] = 0.2f
lut[offset(size, b = 1, g = 1, r = 1) + 2] = 0.9f
lut[offset(size, b = 2, g = 1, r = 1) + 2] = 0.2f
val projected = LutGenerator.projectPrimaryChannelsPava(lut, size)
assertEquals(0f, LutGenerator.maxPrimaryMonotonicViolation(projected, size), 1e-6f)
}
@Test
fun identityInferredPairRecipe_staysIdentity() {
val recipe = inferredPairRecipe { source ->
floatArrayOf(source.r, source.g, source.b)
}
val size = 9
val actual = LutGenerator.generateLut(recipe, size)
val expected = identityLut(size)
val maxDifference = actual.indices.maxOf { abs(actual[it] - expected[it]) }
assertTrue("Identity drift was $maxDifference", maxDifference < 2e-4f)
}
@Test
fun strongCoherentStyle_isNotPulledBackTowardIdentity() {
val recipe = inferredPairRecipe { source ->
floatArrayOf(
(0.10f + source.r * 0.90f).coerceIn(0f, 1f),
(source.g * 0.80f).coerceIn(0f, 1f),
(0.05f + source.b * 0.65f).coerceIn(0f, 1f)
)
}
val size = 9
val actual = LutGenerator.generateLut(recipe, size)
val middle = offset(size, b = 4, g = 4, r = 4)
assertTrue(actual[middle] - actual[middle + 1] > 0.10f)
assertTrue(actual[middle] > 0.52f)
assertTrue(actual[middle + 1] < 0.44f)
}
@Test
fun monochromeRecipe_isExactlyNeutralAndMonotonicOnAllAxes() {
val recipe = inferredPairRecipe(
isMonochrome = true
) { source ->
val luma =
source.r * 0.2126f + source.g * 0.7152f + source.b * 0.0722f
val target = (0.08f + luma * 0.82f).coerceIn(0f, 1f)
floatArrayOf(target, target, target)
}
val size = 7
val actual = LutGenerator.generateLut(recipe, size)
for (index in actual.indices step 3) {
assertEquals(actual[index], actual[index + 1], 0f)
assertEquals(actual[index], actual[index + 2], 0f)
}
assertScalarMonotonic(actual, size)
}
@Test
fun nonFiniteControlPoint_isRejected() {
val recipe = LutRecipe(
controlPoints = listOf(
ControlPoint(
sourceR = Float.NaN,
sourceG = 0f,
sourceB = 0f,
targetR = 0f,
targetG = 0f,
targetB = 0f
)
)
)
assertThrows(IllegalArgumentException::class.java) {
LutGenerator.generateLut(recipe, size = 3)
}
}
private data class SourceSample(
val r: Float,
val g: Float,
val b: Float
)
private fun inferredPairRecipe(
isMonochrome: Boolean = false,
target: (SourceSample) -> FloatArray
): LutRecipe = LutRecipe(
controlPoints = sourceSamples().map { source ->
val targetRgb = target(source)
ControlPoint(
sourceR = source.r,
sourceG = source.g,
sourceB = source.b,
targetR = targetRgb[0],
targetG = targetRgb[1],
targetB = targetRgb[2],
matchConfidence = 1f
)
},
isMonochrome = isMonochrome
)
private fun sourceSamples(): List<SourceSample> = buildList {
val levels = floatArrayOf(0f, 0.5f, 1f)
for (b in levels) {
for (g in levels) {
for (r in levels) {
add(SourceSample(r, g, b))
}
}
}
}
private fun identityLut(size: Int): FloatArray {
val result = FloatArray(size * size * size * 3)
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 0 until size) {
val offset = offset(size, b, g, r)
result[offset] = r.toFloat() / (size - 1)
result[offset + 1] = g.toFloat() / (size - 1)
result[offset + 2] = b.toFloat() / (size - 1)
}
}
}
return result
}
private fun assertScalarMonotonic(lut: FloatArray, size: Int) {
fun gray(b: Int, g: Int, r: Int): Float = lut[offset(size, b, g, r)]
for (b in 0 until size) {
for (g in 0 until size) {
for (r in 1 until size) assertTrue(gray(b, g, r) + 1e-6f >= gray(b, g, r - 1))
}
}
for (b in 0 until size) {
for (r in 0 until size) {
for (g in 1 until size) assertTrue(gray(b, g, r) + 1e-6f >= gray(b, g - 1, r))
}
}
for (g in 0 until size) {
for (r in 0 until size) {
for (b in 1 until size) assertTrue(gray(b, g, r) + 1e-6f >= gray(b - 1, g, r))
}
}
}
private fun offset(size: Int, b: Int, g: Int, r: Int): Int =
(b * size * size + g * size + r) * 3
}