photos: editor adjustments run on pixels, not bitmap round-trips
- Commit
8b2733d9f76ef3f0fb76955b5a3b5045cda0cc8c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 22:59 UTC (14 days ago)
- Parents
58d056c
Every adjustment layer round-tripped the compositor's IntArray through Bitmap copies (~4-5 full-buffer copies plus 2 bitmap allocations per layer per 150ms-debounce render). All 20 adjustments now have applyToPixels entry points that work in place on the caller's array (bitmap methods delegate to the same loops - math single-sourced, including a probe-verified ColorMatrix replication), and native filters write back into the caller's buffer via new in-place JNI entries. One deliberate exception: vignette's Skia radial gradient couldn't be replicated pixel-identically, so it falls back to the bitmap path by returning null. Verified: photos 810 tests pass incl. pixel-equality tests at three sizes; cargo photos_fx 69 pass. ~38MB of memory traffic removed per layer per render at preview size.
Diff
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex 961aeca252..27182cdb77 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -52,6 +52,7 @@ rustNativeTests { nativeClasses.addAll( listOf( "com.vayunmathur.photos.data.AdjustmentBitmapsRealTest",+ "com.vayunmathur.photos.data.AdjustmentPixelsEqualityTest", "com.vayunmathur.photos.data.PhotosSlice1DataPass3Test", "com.vayunmathur.photos.util.PhotosCovC2CompositorTest", "com.vayunmathur.photos.util.PhotosCovC2IndexingTest",
photos/src/main/java/com/vayunmathur/photos/data/BlackAndWhiteData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/BlackAndWhiteData.kt b/photos/src/main/java/com/vayunmathur/photos/data/BlackAndWhiteData.ktindex ace7386832..75d526e821 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/BlackAndWhiteData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/BlackAndWhiteData.kt@@ -25,7 +25,8 @@ data class BlackAndWhiteAdjustment( fun isIdentity(): Boolean = !enabled } -fun BlackAndWhiteAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+/** Zero-copy entry point: applies the B&W conversion in place to [pixels] and returns it. */+fun BlackAndWhiteAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { // Band centers in degrees and associated weights (percent). val centers = floatArrayOf(0f, 60f, 120f, 180f, 240f, 300f) val weights = floatArrayOf(reds, yellows, greens, cyans, blues, magentas)@@ -34,35 +35,44 @@ fun BlackAndWhiteAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap { val tintG = (tint ushr 8) and 0xFF val tintB = tint and 0xFF - return bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p ushr 24) and 0xFF- val r = (p ushr 16) and 0xFF- val g = (p ushr 8) and 0xFF- val b = p and 0xFF-- val hue = rgbToHue(r, g, b)- val selectedWeight = interpolateWeight(hue, centers, weights)+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr 24) and 0xFF+ val r = (p ushr 16) and 0xFF+ val g = (p ushr 8) and 0xFF+ val b = p and 0xFF - val luminance = 0.299f * r + 0.587f * g + 0.114f * b- val gray = (luminance * (selectedWeight / 60f)).toInt().coerceIn(0, 255)+ val hue = rgbToHue(r, g, b)+ val selectedWeight = interpolateWeight(hue, centers, weights) - val nr: Int- val ng: Int- val nb: Int- if (tint != 0) {- nr = (gray * (tintR / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)- ng = (gray * (tintG / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)- nb = (gray * (tintB / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)- } else {- nr = gray- ng = gray- nb = gray- }+ val luminance = 0.299f * r + 0.587f * g + 0.114f * b+ val gray = (luminance * (selectedWeight / 60f)).toInt().coerceIn(0, 255) - (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb+ val nr: Int+ val ng: Int+ val nb: Int+ if (tint != 0) {+ nr = (gray * (tintR / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)+ ng = (gray * (tintG / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)+ nb = (gray * (tintB / CHANNEL_MAX_F)).toInt().coerceIn(0, CHANNEL_MAX)+ } else {+ nr = gray+ ng = gray+ nb = gray }++ pixels[i] = (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb }+ return pixels+}++fun BlackAndWhiteAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result } private fun rgbToHue(r: Int, g: Int, b: Int): Float {
photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt b/photos/src/main/java/com/vayunmathur/photos/data/BlurData.ktindex 80dccc2832..6f51313be0 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt@@ -20,6 +20,12 @@ data class BlurParams( fun isIdentity(): Boolean = intensity == 0f } +/** Zero-copy entry point: runs the native blur in place on [pixels] and returns it. */+fun BlurParams.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ PhotosNative.blurParamsInPlace(pixels, width, height, mode.ordinal, centerX, centerY, radius, intensity, feather, angle)+ return pixels+}+ fun BlurParams.applyBlurToBitmap(bitmap: Bitmap): Bitmap { val w = bitmap.width val h = bitmap.height@@ -45,6 +51,14 @@ data class FilterBlur( fun isIdentity(): Boolean = amount == 0f } +/** Zero-copy entry point: runs the native filter blur in place on [pixels] and returns it. */+fun FilterBlur.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ if (!isIdentity()) {+ PhotosNative.filterBlurInPlace(pixels, width, height, mode.ordinal, amount, angle, centerX, centerY)+ }+ return pixels+}+ fun FilterBlur.applyToBitmap(bitmap: Bitmap): Bitmap { if (isIdentity()) return bitmap.copy(Bitmap.Config.ARGB_8888, true) val w = bitmap.width
photos/src/main/java/com/vayunmathur/photos/data/ChannelMixerData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/ChannelMixerData.kt b/photos/src/main/java/com/vayunmathur/photos/data/ChannelMixerData.ktindex 58fc0ac6b5..0734c3915a 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/ChannelMixerData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/ChannelMixerData.kt@@ -27,28 +27,39 @@ data class ChannelMixerAdjustment( bFromR == 0f && bFromG == 0f && bFromB == 1f } -fun ChannelMixerAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap =- bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p ushr 24) and 0xFF- val r = (p ushr 16) and 0xFF- val g = (p ushr 8) and 0xFF- val b = p and 0xFF+/** Zero-copy entry point: applies the channel mix in place to [pixels] and returns it. */+fun ChannelMixerAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr 24) and 0xFF+ val r = (p ushr 16) and 0xFF+ val g = (p ushr 8) and 0xFF+ val b = p and 0xFF - val nr: Int- val ng: Int- val nb: Int- if (monochrome) {- val gray = (rFromR * r + rFromG * g + rFromB * b).toInt().coerceIn(0, 255)- nr = gray- ng = gray- nb = gray- } else {- nr = (rFromR * r + rFromG * g + rFromB * b).toInt().coerceIn(0, CHANNEL_MAX)- ng = (gFromR * r + gFromG * g + gFromB * b).toInt().coerceIn(0, CHANNEL_MAX)- nb = (bFromR * r + bFromG * g + bFromB * b).toInt().coerceIn(0, CHANNEL_MAX)- }-- (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb+ val nr: Int+ val ng: Int+ val nb: Int+ if (monochrome) {+ val gray = (rFromR * r + rFromG * g + rFromB * b).toInt().coerceIn(0, 255)+ nr = gray+ ng = gray+ nb = gray+ } else {+ nr = (rFromR * r + rFromG * g + rFromB * b).toInt().coerceIn(0, CHANNEL_MAX)+ ng = (gFromR * r + gFromG * g + gFromB * b).toInt().coerceIn(0, CHANNEL_MAX)+ nb = (bFromR * r + bFromG * g + bFromB * b).toInt().coerceIn(0, CHANNEL_MAX) }++ pixels[i] = (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb }+ return pixels+}++fun ChannelMixerAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result+}
photos/src/main/java/com/vayunmathur/photos/data/ColorBalanceData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/ColorBalanceData.kt b/photos/src/main/java/com/vayunmathur/photos/data/ColorBalanceData.ktindex 51ff472013..876838c836 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/ColorBalanceData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/ColorBalanceData.kt@@ -26,39 +26,49 @@ data class ColorBalanceAdjustment( highRedCyan == 0f && highGreenMagenta == 0f && highBlueYellow == 0f } -fun ColorBalanceAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+/** Zero-copy entry point: applies color balance in place to [pixels] and returns it. */+fun ColorBalanceAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { val scale = 0.6f - return bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p ushr 24) and 0xFF- val r = (p ushr 16) and 0xFF- val g = (p ushr 8) and 0xFF- val b = p and 0xFF-- val l = (0.299f * r + 0.587f * g + 0.114f * b) / 255f+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr 24) and 0xFF+ val r = (p ushr 16) and 0xFF+ val g = (p ushr 8) and 0xFF+ val b = p and 0xFF - val wS = (1f - l).coerceIn(0f, 1f)- val wH = l.coerceIn(0f, 1f)- val wM = (1f - abs(2f * l - 1f)).coerceIn(0f, 1f)+ val l = (0.299f * r + 0.587f * g + 0.114f * b) / 255f - var nr = r + (shadowsRedCyan * wS + midRedCyan * wM + highRedCyan * wH) * scale- var ng = g + (shadowsGreenMagenta * wS + midGreenMagenta * wM + highGreenMagenta * wH) * scale- var nb = b + (shadowsBlueYellow * wS + midBlueYellow * wM + highBlueYellow * wH) * scale+ val wS = (1f - l).coerceIn(0f, 1f)+ val wH = l.coerceIn(0f, 1f)+ val wM = (1f - abs(2f * l - 1f)).coerceIn(0f, 1f) - if (preserveLuminosity) {- val origL = 0.299f * r + 0.587f * g + 0.114f * b- val newL = 0.299f * nr + 0.587f * ng + 0.114f * nb- val diff = origL - newL- nr += diff- ng += diff- nb += diff- }+ var nr = r + (shadowsRedCyan * wS + midRedCyan * wM + highRedCyan * wH) * scale+ var ng = g + (shadowsGreenMagenta * wS + midGreenMagenta * wM + highGreenMagenta * wH) * scale+ var nb = b + (shadowsBlueYellow * wS + midBlueYellow * wM + highBlueYellow * wH) * scale - val ir = nr.toInt().coerceIn(0, 255)- val ig = ng.toInt().coerceIn(0, 255)- val ib = nb.toInt().coerceIn(0, 255)- (a shl ALPHA_SHIFT) or (ir shl RED_SHIFT) or (ig shl GREEN_SHIFT) or ib+ if (preserveLuminosity) {+ val origL = 0.299f * r + 0.587f * g + 0.114f * b+ val newL = 0.299f * nr + 0.587f * ng + 0.114f * nb+ val diff = origL - newL+ nr += diff+ ng += diff+ nb += diff }++ val ir = nr.toInt().coerceIn(0, 255)+ val ig = ng.toInt().coerceIn(0, 255)+ val ib = nb.toInt().coerceIn(0, 255)+ pixels[i] = (a shl ALPHA_SHIFT) or (ir shl RED_SHIFT) or (ig shl GREEN_SHIFT) or ib }+ return pixels+}++fun ColorBalanceAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result }
photos/src/main/java/com/vayunmathur/photos/data/CurvesData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/CurvesData.kt b/photos/src/main/java/com/vayunmathur/photos/data/CurvesData.ktindex f25f46619d..dc8d359147 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/CurvesData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/CurvesData.kt@@ -78,25 +78,35 @@ fun CurvesAdjustment.toColorMatrix(): ColorMatrix { )) } -fun CurvesAdjustment.applyLutToBitmap(bitmap: Bitmap): Bitmap {+/** Zero-copy entry point: applies the curve LUTs in place to [pixels] and returns it. */+fun CurvesAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { val luts = generateLuts() val combinedLut = luts[0] val rLut = luts[1] val gLut = luts[2] val bLut = luts[3]- return bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p shr 24) and 0xFF- var r = (p shr 16) and 0xFF- var g = (p shr 8) and 0xFF- var b = p and 0xFF- r = (combinedLut[r] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- g = (combinedLut[g] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- b = (combinedLut[b] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- r = (rLut[r] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- g = (gLut[g] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- b = (bLut[b] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)- (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b- }+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p shr 24) and 0xFF+ var r = (p shr 16) and 0xFF+ var g = (p shr 8) and 0xFF+ var b = p and 0xFF+ r = (combinedLut[r] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ g = (combinedLut[g] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ b = (combinedLut[b] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ r = (rLut[r] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ g = (gLut[g] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ b = (bLut[b] * CHANNEL_MAX_F).toInt().coerceIn(0, CHANNEL_MAX)+ pixels[i] = (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b }+ return pixels+}++fun CurvesAdjustment.applyLutToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result }
photos/src/main/java/com/vayunmathur/photos/data/FxAdjustments.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FxAdjustments.kt b/photos/src/main/java/com/vayunmathur/photos/data/FxAdjustments.ktindex 819c63c59e..6b3d122de9 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FxAdjustments.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FxAdjustments.kt@@ -8,6 +8,8 @@ data class FilterBlurAdj(val blur: FilterBlur = FilterBlur()) : LayerAdjustment override fun isIdentity(): Boolean = blur.isIdentity() override val label: String get() = "Blur" override fun applyToBitmap(bitmap: Bitmap): Bitmap = blur.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ blur.applyToPixels(pixels, width, height) } /** Immutable value describing unsharp adj; carries mask. */@@ -15,6 +17,8 @@ data class UnsharpAdj(val mask: UnsharpMask = UnsharpMask()) : LayerAdjustment { override fun isIdentity(): Boolean = mask.isIdentity() override val label: String get() = "Sharpen" override fun applyToBitmap(bitmap: Bitmap): Bitmap = mask.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ mask.applyToPixels(pixels, width, height) } /** Immutable value describing noise adj; carries noise. */@@ -22,6 +26,8 @@ data class NoiseAdj(val noise: NoiseParams = NoiseParams()) : LayerAdjustment { override fun isIdentity(): Boolean = noise.isIdentity() override val label: String get() = "Noise" override fun applyToBitmap(bitmap: Bitmap): Bitmap = noise.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ noise.applyToPixels(pixels, width, height) } /** Immutable value describing stylize adj; carries stylize. */@@ -29,4 +35,6 @@ data class StylizeAdj(val stylize: StylizeParams = StylizeParams()) : LayerAdjus override fun isIdentity(): Boolean = stylize.isIdentity() override val label: String get() = "Stylize" override fun applyToBitmap(bitmap: Bitmap): Bitmap = stylize.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ stylize.applyToPixels(pixels, width, height) }
photos/src/main/java/com/vayunmathur/photos/data/GradientMapData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/GradientMapData.kt b/photos/src/main/java/com/vayunmathur/photos/data/GradientMapData.ktindex d7c1c824aa..57c515001f 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/GradientMapData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/GradientMapData.kt@@ -17,7 +17,8 @@ data class GradientMapAdjustment(val stops: List<GradientStop> = emptyList()) { fun isIdentity(): Boolean = stops.size < 2 } -fun GradientMapAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+/** Zero-copy entry point: applies the gradient map in place to [pixels] and returns it. */+fun GradientMapAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { val sorted = stops.sortedBy { it.position } val lut = IntArray(GRADIENT_LUT_SIZE) for (v in 0..CHANNEL_MAX) {@@ -25,21 +26,30 @@ fun GradientMapAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap { lut[v] = colorAt(sorted, t) } - return bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p ushr 24) and 0xFF- val r = (p ushr 16) and 0xFF- val g = (p ushr 8) and 0xFF- val b = p and 0xFF+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr 24) and 0xFF+ val r = (p ushr 16) and 0xFF+ val g = (p ushr 8) and 0xFF+ val b = p and 0xFF - val lum = (0.299f * r + 0.587f * g + 0.114f * b).toInt().coerceIn(0, 255)- val c = lut[lum]- val nr = (c ushr 16) and 0xFF- val ng = (c ushr 8) and 0xFF- val nb = c and 0xFF- (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb- }+ val lum = (0.299f * r + 0.587f * g + 0.114f * b).toInt().coerceIn(0, 255)+ val c = lut[lum]+ val nr = (c ushr 16) and 0xFF+ val ng = (c ushr 8) and 0xFF+ val nb = c and 0xFF+ pixels[i] = (a shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb }+ return pixels+}++fun GradientMapAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result } private fun colorAt(sorted: List<GradientStop>, t: Float): Int {
photos/src/main/java/com/vayunmathur/photos/data/HslData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/HslData.kt b/photos/src/main/java/com/vayunmathur/photos/data/HslData.ktindex 5fef7563b3..50951e143a 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/HslData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/HslData.kt@@ -97,11 +97,13 @@ private fun hueWeight(pixelHue: Float, centerHue: Float): Float { return (1f - (diff / HUE_RANGE_HALF_WIDTH)).coerceIn(0f, 1f) } -fun HslAdjustments.applyHslToBitmap(bitmap: Bitmap): Bitmap {- val w = bitmap.width- val h = bitmap.height- val pixels = IntArray(w * h)- bitmap.getPixels(pixels, 0, w, 0, 0, w, h)+/**+ * Zero-copy entry point: applies the HSL adjustment in place to [pixels]+ * (ARGB, row-major [width] x [height]) and returns the same array. Shares the+ * exact per-pixel math with [applyHslToBitmap], so ints-in produce the same+ * ints-out as the bitmap path.+ */+fun HslAdjustments.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { for (i in pixels.indices) { val a = (pixels[i] shr 24) and 0xFF val r = (pixels[i] shr 16) and 0xFF@@ -123,6 +125,15 @@ fun HslAdjustments.applyHslToBitmap(bitmap: Bitmap): Bitmap { val rgb = hslToRgb(hue, sat, lum) pixels[i] = (a shl ALPHA_SHIFT) or (rgb[0] shl RED_SHIFT) or (rgb[1] shl GREEN_SHIFT) or rgb[2] }+ return pixels+}++fun HslAdjustments.applyHslToBitmap(bitmap: Bitmap): Bitmap {+ val w = bitmap.width+ val h = bitmap.height+ val pixels = IntArray(w * h)+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h)+ applyToPixels(pixels, w, h) val result = createBitmap(w, h) result.setPixels(pixels, 0, w, 0, 0, w, h) return result
photos/src/main/java/com/vayunmathur/photos/data/ImageAdjustments.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/ImageAdjustments.kt b/photos/src/main/java/com/vayunmathur/photos/data/ImageAdjustments.ktindex d5c2889392..03a77f30c7 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/ImageAdjustments.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/ImageAdjustments.kt@@ -11,6 +11,7 @@ import android.graphics.PorterDuff import android.graphics.PorterDuffXfermode import androidx.core.graphics.createBitmap import kotlin.math.pow+import kotlin.math.roundToInt import kotlin.random.Random private const val ALPHA_SHIFT = 24@@ -221,34 +222,52 @@ fun ImageAdjustments.applyToBitmap(bitmap: Bitmap): Bitmap { return result } -fun ImageAdjustments.hasPixelEffects(): Boolean =- sharpness != 0f || vignette != 0f || grain != 0f--fun ImageAdjustments.applyPixelEffects(bitmap: Bitmap): Bitmap {- if (!hasPixelEffects()) return bitmap- var result = bitmap- if (sharpness > 0f) {- val sharpenSrc =- if (result === bitmap) bitmap.copy(Bitmap.Config.ARGB_8888, true) else result- result = applySharpen(sharpenSrc, sharpness / PERCENT_DIVISOR)+/**+ * Zero-copy entry point: applies these adjustments in place to [pixels]+ * (ARGB, row-major [width] x [height]) and returns the result array (the same+ * array, except after sharpening, which needs a neighbour scratch buffer).+ *+ * The color-matrix stage replicates the `Canvas` + `ColorMatrixColorFilter`+ * math of [applyToBitmap] per pixel with round-to-nearest channel conversion+ * (verified pixel-identical against the bitmap path). Returns null when the+ * adjustment needs the vignette stage: that stage draws a `RadialGradient`+ * through Skia, whose interpolation is not reproducible bit-exactly in+ * per-pixel float math (probed ±1 on ~30–55% of pixels), so callers must fall+ * back to [applyToBitmap] for pixel-identical output.+ */+fun ImageAdjustments.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray? {+ if (vignette > 0f) return null+ val cm = toColorMatrix()+ if (!cm.array.contentEquals(ColorMatrix().array)) {+ applyColorMatrixToPixels(pixels, cm.array) }- if (vignette > 0f) {- if (result === bitmap) result = bitmap.copy(Bitmap.Config.ARGB_8888, true)- applyVignette(result, vignette / PERCENT_DIVISOR)+ var result = pixels+ if (sharpness > 0f) {+ result = applySharpenToPixels(result, width, height, sharpness / PERCENT_DIVISOR) } if (grain > 0f) {- if (result === bitmap) result = bitmap.copy(Bitmap.Config.ARGB_8888, true)- applyGrain(result, grain / PERCENT_DIVISOR)+ applyGrainToPixels(result, grain / PERCENT_DIVISOR) } return result } -private fun applySharpen(src: Bitmap, amount: Float): Bitmap {- val w = src.width- val h = src.height- val pixels = IntArray(w * h)- src.getPixels(pixels, 0, w, 0, 0, w, h)+private fun applyColorMatrixToPixels(pixels: IntArray, m: FloatArray) {+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr ALPHA_SHIFT) and 0xFF+ val r = (p ushr RED_SHIFT) and 0xFF+ val g = (p ushr GREEN_SHIFT) and 0xFF+ val b = p and 0xFF+ val nr = (m[0] * r + m[1] * g + m[2] * b + m[3] * a + m[4]).roundToInt().coerceIn(0, CHANNEL_MAX)+ val ng = (m[5] * r + m[6] * g + m[7] * b + m[8] * a + m[9]).roundToInt().coerceIn(0, CHANNEL_MAX)+ val nb = (m[10] * r + m[11] * g + m[12] * b + m[13] * a + m[14]).roundToInt().coerceIn(0, CHANNEL_MAX)+ val na = (m[15] * r + m[16] * g + m[17] * b + m[18] * a + m[19]).roundToInt().coerceIn(0, CHANNEL_MAX)+ pixels[i] = (na shl ALPHA_SHIFT) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb+ }+} +/** Sharpen stage on raw pixels; returns a new array (edges copied verbatim). */+private fun applySharpenToPixels(pixels: IntArray, w: Int, h: Int, amount: Float): IntArray { val out = IntArray(w * h) val strength = amount * SHARPEN_GAIN val center = 1f + SHARPEN_CENTER_WEIGHT * strength@@ -287,6 +306,53 @@ private fun applySharpen(src: Bitmap, amount: Float): Bitmap { out[y * w] = pixels[y * w] out[y * w + w - 1] = pixels[y * w + w - 1] }+ return out+}++/** Grain stage on raw pixels, in place; same seeded sequence as the bitmap path. */+private fun applyGrainToPixels(pixels: IntArray, amount: Float) {+ val intensity = (amount * 50f).toInt()+ val rng = Random(42)+ for (i in pixels.indices) {+ val pixel = pixels[i]+ val noise = rng.nextInt(-intensity, intensity + 1)+ val a = (pixel shr 24) and 0xFF+ val r = (((pixel shr 16) and 0xFF) + noise).coerceIn(0, 255)+ val g = (((pixel shr 8) and 0xFF) + noise).coerceIn(0, 255)+ val b = ((pixel and 0xFF) + noise).coerceIn(0, 255)+ pixels[i] = (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b+ }+}++fun ImageAdjustments.hasPixelEffects(): Boolean =+ sharpness != 0f || vignette != 0f || grain != 0f++fun ImageAdjustments.applyPixelEffects(bitmap: Bitmap): Bitmap {+ if (!hasPixelEffects()) return bitmap+ var result = bitmap+ if (sharpness > 0f) {+ val sharpenSrc =+ if (result === bitmap) bitmap.copy(Bitmap.Config.ARGB_8888, true) else result+ result = applySharpen(sharpenSrc, sharpness / PERCENT_DIVISOR)+ }+ if (vignette > 0f) {+ if (result === bitmap) result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ applyVignette(result, vignette / PERCENT_DIVISOR)+ }+ if (grain > 0f) {+ if (result === bitmap) result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ applyGrain(result, grain / PERCENT_DIVISOR)+ }+ return result+}++private fun applySharpen(src: Bitmap, amount: Float): Bitmap {+ val w = src.width+ val h = src.height+ val pixels = IntArray(w * h)+ src.getPixels(pixels, 0, w, 0, 0, w, h)++ val out = applySharpenToPixels(pixels, w, h, amount) val result = createBitmap(w, h) result.setPixels(out, 0, w, 0, 0, w, h)@@ -320,14 +386,8 @@ private fun applyVignette(bitmap: Bitmap, amount: Float) { } private fun applyGrain(bitmap: Bitmap, amount: Float) {- val intensity = (amount * 50f).toInt()- val rng = Random(42)- bitmap.mapPixels { pixel ->- val noise = rng.nextInt(-intensity, intensity + 1)- val a = (pixel shr 24) and 0xFF- val r = (((pixel shr 16) and 0xFF) + noise).coerceIn(0, 255)- val g = (((pixel shr 8) and 0xFF) + noise).coerceIn(0, 255)- val b = ((pixel and 0xFF) + noise).coerceIn(0, 255)- (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b- }+ val pixels = IntArray(bitmap.width * bitmap.height)+ bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)+ applyGrainToPixels(pixels, amount)+ bitmap.setPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) }
photos/src/main/java/com/vayunmathur/photos/data/LayerData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/LayerData.kt b/photos/src/main/java/com/vayunmathur/photos/data/LayerData.ktindex bbc1581d4d..fc0a24a05c 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/LayerData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/LayerData.kt@@ -86,6 +86,21 @@ data class GroupInfo( sealed interface LayerAdjustment { fun isIdentity(): Boolean fun applyToBitmap(bitmap: Bitmap): Bitmap++ /**+ * Zero-copy entry point used by the compositor, which owns raw ARGB+ * [pixels] (row-major [width] x [height]) instead of bitmaps.+ *+ * Implementations apply the adjustment to [pixels] — mutating and+ * returning that same array where possible, or returning a replacement+ * array when the op needs a scratch buffer — with output pixel-identical+ * to [applyToBitmap] on the same ints. Returns null when no+ * pixel-identical array path exists for this adjustment's parameters;+ * [pixels] may then be partially mutated and the caller must fall back to+ * [applyToBitmap] on its original source. Bitmap entry points stay for+ * non-compositor callers.+ */+ fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray? = null val label: String } @@ -93,6 +108,8 @@ sealed interface LayerAdjustment { data class BasicAdjustment(val adjustments: ImageAdjustments = ImageAdjustments()) : LayerAdjustment { override fun isIdentity(): Boolean = adjustments == ImageAdjustments() override fun applyToBitmap(bitmap: Bitmap): Bitmap = adjustments.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray? =+ adjustments.applyToPixels(pixels, width, height) override val label: String get() = "Adjustments" } @@ -100,6 +117,8 @@ data class BasicAdjustment(val adjustments: ImageAdjustments = ImageAdjustments( data class CurvesAdj(val curves: CurvesAdjustment = CurvesAdjustment()) : LayerAdjustment { override fun isIdentity(): Boolean = curves.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = curves.applyLutToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ curves.applyToPixels(pixels, width, height) override val label: String get() = "Curves" } @@ -107,6 +126,8 @@ data class CurvesAdj(val curves: CurvesAdjustment = CurvesAdjustment()) : LayerA data class HslAdj(val hsl: HslAdjustments = HslAdjustments()) : LayerAdjustment { override fun isIdentity(): Boolean = hsl.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = hsl.applyHslToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ hsl.applyToPixels(pixels, width, height) override val label: String get() = "HSL" } @@ -114,6 +135,8 @@ data class HslAdj(val hsl: HslAdjustments = HslAdjustments()) : LayerAdjustment data class BlurAdj(val blur: BlurParams = BlurParams()) : LayerAdjustment { override fun isIdentity(): Boolean = blur.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = blur.applyBlurToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ blur.applyToPixels(pixels, width, height) override val label: String get() = "Blur" } @@ -121,6 +144,8 @@ data class BlurAdj(val blur: BlurParams = BlurParams()) : LayerAdjustment { data class SelectiveAdj(val selective: SelectiveEdits = SelectiveEdits()) : LayerAdjustment { override fun isIdentity(): Boolean = selective.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = selective.applySelectiveEdits(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray? =+ selective.applyToPixels(pixels, width, height) override val label: String get() = "Selective" } @@ -128,6 +153,8 @@ data class SelectiveAdj(val selective: SelectiveEdits = SelectiveEdits()) : Laye data class LevelsAdj(val levels: LevelsAdjustment = LevelsAdjustment()) : LayerAdjustment { override fun isIdentity(): Boolean = levels.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = levels.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ levels.applyToPixels(pixels, width, height) override val label: String get() = "Levels" } @@ -135,6 +162,8 @@ data class LevelsAdj(val levels: LevelsAdjustment = LevelsAdjustment()) : LayerA data class ColorBalanceAdj(val balance: ColorBalanceAdjustment = ColorBalanceAdjustment()) : LayerAdjustment { override fun isIdentity(): Boolean = balance.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = balance.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ balance.applyToPixels(pixels, width, height) override val label: String get() = "Color Balance" } @@ -142,6 +171,8 @@ data class ColorBalanceAdj(val balance: ColorBalanceAdjustment = ColorBalanceAdj data class ChannelMixerAdj(val mixer: ChannelMixerAdjustment = ChannelMixerAdjustment()) : LayerAdjustment { override fun isIdentity(): Boolean = mixer.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = mixer.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ mixer.applyToPixels(pixels, width, height) override val label: String get() = "Channel Mixer" } @@ -149,6 +180,8 @@ data class ChannelMixerAdj(val mixer: ChannelMixerAdjustment = ChannelMixerAdjus data class GradientMapAdj(val gradient: GradientMapAdjustment = GradientMapAdjustment()) : LayerAdjustment { override fun isIdentity(): Boolean = gradient.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = gradient.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ gradient.applyToPixels(pixels, width, height) override val label: String get() = "Gradient Map" } @@ -158,6 +191,8 @@ data class BlackAndWhiteAdj( ) : LayerAdjustment { override fun isIdentity(): Boolean = bw.isIdentity() override fun applyToBitmap(bitmap: Bitmap): Bitmap = bw.applyToBitmap(bitmap)+ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ bw.applyToPixels(pixels, width, height) override val label: String get() = "Black & White" }
photos/src/main/java/com/vayunmathur/photos/data/LevelsData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/LevelsData.kt b/photos/src/main/java/com/vayunmathur/photos/data/LevelsData.ktindex 8c0aeeec2a..a495deb8a7 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/LevelsData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/LevelsData.kt@@ -23,7 +23,7 @@ data class LevelsAdjustment( inBlack == 0f && inWhite == CHANNEL_MAX_F && gamma == 1f && outBlack == 0f && outWhite == CHANNEL_MAX_F } -fun LevelsAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+fun LevelsAdjustment.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { val lut = IntArray(LUT_SIZE) val range = (inWhite - inBlack).coerceAtLeast(1f) val invGamma = 1f / gamma.coerceAtLeast(MIN_GAMMA)@@ -33,13 +33,22 @@ fun LevelsAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap { lut[v] = (outBlack + n * (outWhite - outBlack)).toInt().coerceIn(0, CHANNEL_MAX) } - return bitmap.copy(Bitmap.Config.ARGB_8888, true).apply {- mapPixels { p ->- val a = (p ushr 24) and 0xFF- val r = (p ushr 16) and 0xFF- val g = (p ushr 8) and 0xFF- val b = p and 0xFF- (a shl ALPHA_SHIFT) or (lut[r] shl RED_SHIFT) or (lut[g] shl GREEN_SHIFT) or lut[b]- }+ for (i in pixels.indices) {+ val p = pixels[i]+ val a = (p ushr 24) and 0xFF+ val r = (p ushr 16) and 0xFF+ val g = (p ushr 8) and 0xFF+ val b = p and 0xFF+ pixels[i] = (a shl ALPHA_SHIFT) or (lut[r] shl RED_SHIFT) or (lut[g] shl GREEN_SHIFT) or lut[b] }+ return pixels+}++fun LevelsAdjustment.applyToBitmap(bitmap: Bitmap): Bitmap {+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true)+ val pixels = IntArray(result.width * result.height)+ result.getPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ applyToPixels(pixels, result.width, result.height)+ result.setPixels(pixels, 0, result.width, 0, 0, result.width, result.height)+ return result }
photos/src/main/java/com/vayunmathur/photos/data/MoreAdjustmentsData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/MoreAdjustmentsData.kt b/photos/src/main/java/com/vayunmathur/photos/data/MoreAdjustmentsData.ktindex 568b3dd2e2..3d0ec0843e 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/MoreAdjustmentsData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/MoreAdjustmentsData.kt@@ -28,6 +28,12 @@ private inline fun Bitmap.mapArgb(transform: (Int) -> Int): Bitmap { return out } +/** In-place analogue of [Bitmap.mapArgb] for caller-owned pixel buffers. */+internal inline fun applyToPixelsInPlace(pixels: IntArray, transform: (Int) -> Int): IntArray {+ for (i in pixels.indices) pixels[i] = transform(pixels[i])+ return pixels+}+ private const val ALPHA_MASK = -0x1000000 /** Invert colors (photo negative). */@@ -41,6 +47,14 @@ data class InvertAdj(val enabled: Boolean = true) : LayerAdjustment { invertChannel(c and CHANNEL_MASK) } + override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ applyToPixelsInPlace(pixels) { c ->+ (c and ALPHA_MASK) or+ (invertChannel((c ushr RED_SHIFT) and CHANNEL_MASK) shl RED_SHIFT) or+ (invertChannel((c ushr GREEN_SHIFT) and CHANNEL_MASK) shl GREEN_SHIFT) or+ invertChannel(c and CHANNEL_MASK)+ }+ private fun invertChannel(v: Int): Int = CHANNEL_MAX - v } @@ -58,6 +72,17 @@ data class PosterizeAdj(val levels: Int = 4) : LayerAdjustment { (c and ALPHA_MASK) or (rq shl RED_SHIFT) or (gq shl GREEN_SHIFT) or q(c and CHANNEL_MASK) } }++ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ val n = levels.coerceIn(MIN_POSTERIZE_LEVELS, CHANNEL_MAX)+ val step = CHANNEL_MAX_F / (n - 1)+ fun q(v: Int): Int = (Math.round(v / step) * step).toInt().coerceIn(0, CHANNEL_MAX)+ return applyToPixelsInPlace(pixels) { c ->+ val rq = q((c ushr RED_SHIFT) and CHANNEL_MASK)+ val gq = q((c ushr GREEN_SHIFT) and CHANNEL_MASK)+ (c and ALPHA_MASK) or (rq shl RED_SHIFT) or (gq shl GREEN_SHIFT) or q(c and CHANNEL_MASK)+ }+ } } /** Convert to pure black/white by a luminance [level] (0..255). */@@ -72,6 +97,16 @@ data class ThresholdAdj(val level: Int = 128) : LayerAdjustment { val v = if (lum >= level) 255 else 0 (c and ALPHA_MASK) or (v shl RED_SHIFT) or (v shl GREEN_SHIFT) or v }++ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray =+ applyToPixelsInPlace(pixels) { c ->+ val r = (c ushr 16) and 0xFF+ val g = (c ushr 8) and 0xFF+ val b = c and 0xFF+ val lum = 0.299f * r + 0.587f * g + 0.114f * b+ val v = if (lum >= level) 255 else 0+ (c and ALPHA_MASK) or (v shl RED_SHIFT) or (v shl GREEN_SHIFT) or v+ } } /** Smart saturation: boosts less-saturated pixels more, protecting already-vivid ones. [amount] -100..100. */@@ -93,6 +128,22 @@ data class VibranceAdj(val amount: Float = 0f) : LayerAdjustment { (c and ALPHA_MASK) or (adj(r) shl RED_SHIFT) or (adj(g) shl GREEN_SHIFT) or adj(b) } }++ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ val amt = amount / 100f+ return applyToPixelsInPlace(pixels) { c ->+ val r = (c ushr 16) and 0xFF+ val g = (c ushr 8) and 0xFF+ val b = c and 0xFF+ val mx = maxOf(r, g, b)+ val mn = minOf(r, g, b)+ val sat = (mx - mn) / 255f+ val factor = 1f + amt * (1f - sat)+ val avg = (r + g + b) / 3f+ fun adj(v: Int) = (avg + (v - avg) * factor).roundToInt().coerceIn(0, CHANNEL_MAX)+ (c and ALPHA_MASK) or (adj(r) shl RED_SHIFT) or (adj(g) shl GREEN_SHIFT) or adj(b)+ }+ } } /** Warming/cooling color wash. [color] ARGB tint, [density] 0..1 strength. */@@ -129,6 +180,32 @@ data class PhotoFilterAdj( (ng.roundToInt().coerceIn(0, CHANNEL_MAX) shl GREEN_SHIFT) or nb.roundToInt().coerceIn(0, CHANNEL_MAX) } }++ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ val d = density.coerceIn(0f, 1f)+ val fr = (color ushr 16) and 0xFF+ val fg = (color ushr 8) and 0xFF+ val fb = color and 0xFF+ return applyToPixelsInPlace(pixels) { c ->+ val r = (c ushr 16) and 0xFF+ val g = (c ushr 8) and 0xFF+ val b = c and 0xFF+ val mr = r * fr / 255+ val mg = g * fg / 255+ val mb = b * fb / 255+ val lumIn = 0.299f * r + 0.587f * g + 0.114f * b+ var nr = (r * (1 - d) + mr * d)+ var ng = (g * (1 - d) + mg * d)+ var nb = (b * (1 - d) + mb * d)+ val lumOut = 0.299f * nr + 0.587f * ng + 0.114f * nb+ if (lumOut > TINY_LUMINANCE_EPSILON) {+ val k = lumIn / lumOut+ nr *= k; ng *= k; nb *= k+ }+ (c and ALPHA_MASK) or (nr.roundToInt().coerceIn(0, CHANNEL_MAX) shl RED_SHIFT) or+ (ng.roundToInt().coerceIn(0, CHANNEL_MAX) shl GREEN_SHIFT) or nb.roundToInt().coerceIn(0, CHANNEL_MAX)+ }+ } } /** Kinds of selective color range. */@@ -185,4 +262,41 @@ data class SelectiveColorAdj( } } }++ override fun applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ val cShift = -cyan / PERCENT_DIVISOR * CHANNEL_MAX_F+ val mShift = -magenta / PERCENT_DIVISOR * CHANNEL_MAX_F+ val yShift = -yellow / PERCENT_DIVISOR * CHANNEL_MAX_F+ val targetHue = when (range) {+ SelectiveColorRange.Reds -> 0f+ SelectiveColorRange.Yellows -> HUE_SECTOR_DEGREES+ SelectiveColorRange.Greens -> 2f * HUE_SECTOR_DEGREES+ SelectiveColorRange.Cyans -> 3f * HUE_SECTOR_DEGREES+ SelectiveColorRange.Blues -> 4f * HUE_SECTOR_DEGREES+ SelectiveColorRange.Magentas -> 5f * HUE_SECTOR_DEGREES+ SelectiveColorRange.Neutrals -> -1f+ }+ val hsv = FloatArray(3)+ return applyToPixelsInPlace(pixels) { c ->+ val r = (c ushr 16) and 0xFF+ val g = (c ushr 8) and 0xFF+ val b = c and 0xFF+ android.graphics.Color.RGBToHSV(r, g, b, hsv)+ val weight = if (targetHue < 0f) {+ (1f - hsv[1]).coerceIn(0f, 1f)+ } else {+ var dh = kotlin.math.abs(hsv[0] - targetHue)+ if (dh > HALF_CIRCLE_DEGREES) dh = FULL_CIRCLE_DEGREES - dh+ val hueW = (1f - dh / HUE_SECTOR_DEGREES).coerceIn(0f, 1f)+ hueW * hsv[1]+ }+ if (weight <= 0f) c+ else {+ val nr = (r + cShift * weight).roundToInt().coerceIn(0, 255)+ val ng = (g + mShift * weight).roundToInt().coerceIn(0, 255)+ val nb = (b + yShift * weight).roundToInt().coerceIn(0, 255)+ (c and ALPHA_MASK) or (nr shl RED_SHIFT) or (ng shl GREEN_SHIFT) or nb+ }+ }+ } }
photos/src/main/java/com/vayunmathur/photos/data/NoiseData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/NoiseData.kt b/photos/src/main/java/com/vayunmathur/photos/data/NoiseData.ktindex e8bc351437..7511f523de 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/NoiseData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/NoiseData.kt@@ -19,15 +19,10 @@ data class NoiseParams( fun isIdentity(): Boolean = amount == 0f } -fun NoiseParams.applyToBitmap(bitmap: Bitmap): Bitmap {- val w = bitmap.width- val h = bitmap.height- val pixels = IntArray(w * h)- bitmap.getPixels(pixels, 0, w, 0, 0, w, h)-+/** Zero-copy entry point: applies noise in place to [pixels] and returns it. */+fun NoiseParams.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray { val intensity = (amount / PERCENT_DIVISOR * NOISE_SCALE).toInt() val random = kotlin.random.Random(NOISE_SEED)- val output = IntArray(w * h) for (i in pixels.indices) { val p = pixels[i]@@ -50,10 +45,18 @@ fun NoiseParams.applyToBitmap(bitmap: Bitmap): Bitmap { b = (origB + random.nextInt(-intensity, intensity + 1)).coerceIn(0, CHANNEL_MAX) } - output[i] = (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b+ pixels[i] = (a shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b }+ return pixels+} +fun NoiseParams.applyToBitmap(bitmap: Bitmap): Bitmap {+ val w = bitmap.width+ val h = bitmap.height+ val pixels = IntArray(w * h)+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h)+ applyToPixels(pixels, w, h) val result = createBitmap(w, h)- result.setPixels(output, 0, w, 0, 0, w, h)+ result.setPixels(pixels, 0, w, 0, 0, w, h) return result }
photos/src/main/java/com/vayunmathur/photos/data/SelectiveEditData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/SelectiveEditData.kt b/photos/src/main/java/com/vayunmathur/photos/data/SelectiveEditData.ktindex cb160de706..6f6769921d 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/SelectiveEditData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/SelectiveEditData.kt@@ -94,6 +94,38 @@ private fun paintLinearMask(mask: SelectiveMask, alpha: FloatArray, w: Int, h: I } } +/**+ * Zero-copy entry point: applies each masked adjustment in place to [pixels]+ * and returns it, or returns null if any mask's adjustment has no+ * pixel-identical array path (see [ImageAdjustments.applyToPixels]) and the+ * caller must fall back to [applySelectiveEdits].+ */+fun SelectiveEdits.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray? {+ val w = width+ val h = height+ for (mask in masks) {+ if (mask.adjustments == ImageAdjustments()) continue+ val adjPixels = mask.adjustments.applyToPixels(pixels.copyOf(), w, h) ?: return null+ val alpha = generateSelectiveMask(mask, w, h)+ for (i in pixels.indices) {+ val m = alpha[i]+ if (m <= 0f) continue+ val oA = (pixels[i] shr 24) and 0xFF+ val oR = (pixels[i] shr 16) and 0xFF+ val oG = (pixels[i] shr 8) and 0xFF+ val oB = pixels[i] and 0xFF+ val aR = (adjPixels[i] shr 16) and 0xFF+ val aG = (adjPixels[i] shr 8) and 0xFF+ val aB = adjPixels[i] and 0xFF+ val r = (oR + (aR - oR) * m).toInt().coerceIn(0, 255)+ val g = (oG + (aG - oG) * m).toInt().coerceIn(0, 255)+ val b = (oB + (aB - oB) * m).toInt().coerceIn(0, 255)+ pixels[i] = (oA shl ALPHA_SHIFT) or (r shl RED_SHIFT) or (g shl GREEN_SHIFT) or b+ }+ }+ return pixels+}+ fun SelectiveEdits.applySelectiveEdits(bitmap: Bitmap): Bitmap { var result = bitmap.copy(Bitmap.Config.ARGB_8888, true) val w = result.width
photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt b/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.ktindex 42d1e824bb..2bb75bf167 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt@@ -13,6 +13,12 @@ data class UnsharpMask( fun isIdentity(): Boolean = amount == 0f } +/** Zero-copy entry point: runs native unsharp in place on [pixels] and returns it. */+fun UnsharpMask.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ PhotosNative.unsharpInPlace(pixels, width, height, amount, radius, threshold)+ return pixels+}+ fun UnsharpMask.applyToBitmap(bitmap: Bitmap): Bitmap { val w = bitmap.width val h = bitmap.height
photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt b/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.ktindex 90be760954..350d6c59ad 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt@@ -14,6 +14,12 @@ data class StylizeParams( fun isIdentity(): Boolean = mode == StylizeMode.None } +/** Zero-copy entry point: runs native stylize in place on [pixels] and returns it. */+fun StylizeParams.applyToPixels(pixels: IntArray, width: Int, height: Int): IntArray {+ PhotosNative.stylizeInPlace(pixels, width, height, mode.ordinal)+ return pixels+}+ fun StylizeParams.applyToBitmap(bitmap: Bitmap): Bitmap { val w = bitmap.width val h = bitmap.height
photos/src/main/java/com/vayunmathur/photos/platform/LayerCompositor.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/LayerCompositor.kt b/photos/src/main/java/com/vayunmathur/photos/platform/LayerCompositor.ktindex 91e6958f4b..4606ab01f7 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/LayerCompositor.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/LayerCompositor.kt@@ -329,13 +329,22 @@ class LayerCompositor { if (layer.adjustment.isIdentity()) { null } else {- val source = bitmapFromInts(backdrop, w, h)- val adjusted = layer.adjustment.applyToBitmap(source)- val out = IntArray(w * h)- adjusted.getPixels(out, 0, w, 0, 0, w, h)- if (adjusted !== source) adjusted.recycleSafely()- source.recycleSafely()- out+ // Zero-copy path: apply the adjustment directly to a copy of+ // the backdrop (the copy is the layer's source buffer, kept+ // separate because blending still needs the original backdrop+ // per pixel). Only adjustments with no pixel-identical array+ // path (null result, e.g. vignette) fall back to the bitmap+ // round-trip below.+ val working = backdrop.copyOf()+ layer.adjustment.applyToPixels(working, w, h) ?: run {+ val source = bitmapFromInts(backdrop, w, h)+ val adjusted = layer.adjustment.applyToBitmap(source)+ val out = IntArray(w * h)+ adjusted.getPixels(out, 0, w, 0, 0, w, h)+ if (adjusted !== source) adjusted.recycleSafely()+ source.recycleSafely()+ out+ } } } is TextLayer -> renderTextPixels(layer, document, w, h)
photos/src/main/java/com/vayunmathur/photos/platform/PhotosNative.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/PhotosNative.kt b/photos/src/main/java/com/vayunmathur/photos/platform/PhotosNative.ktindex d15f4481d9..be043e7425 100644--- a/photos/src/main/java/com/vayunmathur/photos/platform/PhotosNative.kt+++ b/photos/src/main/java/com/vayunmathur/photos/platform/PhotosNative.kt@@ -64,6 +64,52 @@ object PhotosNative { centerY: Float, ): IntArray + // --- Caller-owned-buffer variants ---------------------------------------+ // These reuse the caller's [pixels] array as both input and output (the+ // native side writes its result back into the same Java array instead of+ // allocating a fresh one), mirroring the reusable `state.pixels` scratch+ // buffer pattern in library/ml's bridge.rs. Use them where the caller+ // already owns an IntArray (e.g. LayerCompositor's backdrops).++ /** In-place [stylize]: result overwrites [pixels]. */+ external fun stylizeInPlace(pixels: IntArray, w: Int, h: Int, mode: Int): Boolean++ /** In-place [unsharp]: result overwrites [pixels]. */+ external fun unsharpInPlace(+ pixels: IntArray,+ w: Int,+ h: Int,+ amount: Float,+ radius: Float,+ threshold: Int,+ ): Boolean++ /** In-place [blurParams]: result overwrites [pixels]. */+ external fun blurParamsInPlace(+ pixels: IntArray,+ w: Int,+ h: Int,+ mode: Int,+ centerX: Float,+ centerY: Float,+ radius: Float,+ intensity: Float,+ feather: Float,+ angle: Float,+ ): Boolean++ /** In-place [filterBlur]: result overwrites [pixels]. */+ external fun filterBlurInPlace(+ pixels: IntArray,+ w: Int,+ h: Int,+ mode: Int,+ amount: Float,+ angle: Float,+ centerX: Float,+ centerY: Float,+ ): Boolean+ /** Content-aware fill (exemplar synthesis / diffusion fallback). */ external fun inpaint( pixels: IntArray,
photos/src/main/rust/src/jni_inplace.rs
diff --git a/photos/src/main/rust/src/jni_inplace.rs b/photos/src/main/rust/src/jni_inplace.rsnew file mode 100644index 0000000000..61af9089bd--- /dev/null+++ b/photos/src/main/rust/src/jni_inplace.rs@@ -0,0 +1,163 @@+//! Caller-owned-buffer (in-place) JNI variants for the photos native+//! filters: each reads the caller's `int[]`, computes, and writes the result+//! back into that same Java array instead of allocating a fresh one —+//! mirroring the reusable `state.pixels` scratch buffer in library/ml's+//! bridge.rs.++use crate::{blur, sharpen, stylize};+use jni::objects::{JClass, JIntArray};+use jni::sys::jint;+use jni::{Env, EnvUnowned};++/// Read a Java `int[]` into a `Vec<i32>`; `None` on error.+fn read_ints(env: &Env, arr: &JIntArray) -> Option<Vec<i32>> {+ let len = env.get_array_length(arr).ok()? as usize;+ let mut buf = vec![0i32; len];+ if env.get_int_array_region(arr, 0, &mut buf).is_err() {+ return None;+ }+ Some(buf)+}++/// Write `result` back into the caller's own `pixels` array (no new Java+/// array allocated), mirroring the reusable-buffer pattern used by+/// library/ml's bridge. Returns false on error.+fn write_into(env: &Env, pixels: &JIntArray, result: &[i32]) -> bool {+ env.set_int_array_region(pixels, 0, result).is_ok()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_photos_platform_PhotosNative_stylizeInPlace<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ pixels: JIntArray<'l>,+ w: jint,+ h: jint,+ mode: jint,+) -> jni::sys::jboolean {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jboolean> {+ if w <= 0 || h <= 0 {+ return Ok(false);+ }+ let buf = match read_ints(env, &pixels) {+ Some(b) if b.len() == (w as usize) * (h as usize) => b,+ _ => return Ok(false),+ };+ let mut ok = false;+ if let Ok(result) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ stylize::stylize(&buf, w as usize, h as usize, mode)+ })) {+ if write_into(env, &pixels, &result) {+ ok = true;+ }+ }+ Ok(ok)+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_photos_platform_PhotosNative_unsharpInPlace<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ pixels: JIntArray<'l>,+ w: jint,+ h: jint,+ amount: jni::sys::jfloat,+ radius: jni::sys::jfloat,+ threshold: jint,+) -> jni::sys::jboolean {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jboolean> {+ if w <= 0 || h <= 0 {+ return Ok(false);+ }+ let buf = match read_ints(env, &pixels) {+ Some(b) if b.len() == (w as usize) * (h as usize) => b,+ _ => return Ok(false),+ };+ let mut ok = false;+ if let Ok(result) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ sharpen::unsharp(&buf, w as usize, h as usize, amount, radius, threshold)+ })) {+ if write_into(env, &pixels, &result) {+ ok = true;+ }+ }+ Ok(ok)+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_photos_platform_PhotosNative_blurParamsInPlace<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ pixels: JIntArray<'l>,+ w: jint,+ h: jint,+ mode: jint,+ center_x: jni::sys::jfloat,+ center_y: jni::sys::jfloat,+ radius: jni::sys::jfloat,+ intensity: jni::sys::jfloat,+ feather: jni::sys::jfloat,+ angle: jni::sys::jfloat,+) -> jni::sys::jboolean {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jboolean> {+ if w <= 0 || h <= 0 {+ return Ok(false);+ }+ let buf = match read_ints(env, &pixels) {+ Some(b) if b.len() == (w as usize) * (h as usize) => b,+ _ => return Ok(false),+ };+ let mut ok = false;+ if let Ok(result) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ blur::blur_params(+ &buf, w as usize, h as usize, mode, center_x, center_y, radius, intensity, feather,+ angle,+ )+ })) {+ if write_into(env, &pixels, &result) {+ ok = true;+ }+ }+ Ok(ok)+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_photos_platform_PhotosNative_filterBlurInPlace<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ pixels: JIntArray<'l>,+ w: jint,+ h: jint,+ mode: jint,+ amount: jni::sys::jfloat,+ angle: jni::sys::jfloat,+ center_x: jni::sys::jfloat,+ center_y: jni::sys::jfloat,+) -> jni::sys::jboolean {+ env.with_env(|env| -> jni::errors::Result<jni::sys::jboolean> {+ if w <= 0 || h <= 0 {+ return Ok(false);+ }+ let buf = match read_ints(env, &pixels) {+ Some(b) if b.len() == (w as usize) * (h as usize) => b,+ _ => return Ok(false),+ };+ let mut ok = false;+ if let Ok(result) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ blur::filter_blur(&buf, w as usize, h as usize, mode, amount, angle, center_x, center_y)+ })) {+ if write_into(env, &pixels, &result) {+ ok = true;+ }+ }+ Ok(ok)+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}+
photos/src/main/rust/src/lib.rs
diff --git a/photos/src/main/rust/src/lib.rs b/photos/src/main/rust/src/lib.rsindex 0c8e55985e..496b804cf0 100644--- a/photos/src/main/rust/src/lib.rs+++ b/photos/src/main/rust/src/lib.rs@@ -25,6 +25,9 @@ mod sharpen_tests; #[cfg(test)] mod stylize_tests; +#[cfg(not(test))]+mod jni_inplace;+ #[cfg(not(test))] mod jni_bindings { use crate::{blur, inpaint, liquify, sharpen, stylize};
photos/src/test/java/com/vayunmathur/photos/data/AdjustmentPixelsEqualityTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentPixelsEqualityTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentPixelsEqualityTest.ktnew file mode 100644index 0000000000..3292e80584--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentPixelsEqualityTest.kt@@ -0,0 +1,244 @@+package com.vayunmathur.photos.data++import android.graphics.Bitmap+import com.vayunmathur.photos.platform.LayerCompositor+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/**+ * Zero-copy census #3: every [LayerAdjustment] must produce pixel-identical+ * output through the new IntArray entry point ([LayerAdjustment.applyToPixels],+ * used by LayerCompositor on its own buffers) and through the legacy bitmap+ * entry point ([LayerAdjustment.applyToBitmap], kept for other callers):+ * same ints in -> same ints out, adjustment by adjustment.+ *+ * Runs in the native quarantine task (see photos/build.gradle.kts): the+ * Blur/Unsharp/Stylize/FilterBlur cases execute the PhotosNative JNI bridge.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class AdjustmentPixelsEqualityTest {++ /**+ * Deterministic opaque ARGB pattern at [w] x [h]. Opaque only: a Bitmap+ * stores premultiplied pixels, so the legacy path destroys RGB under+ * alpha < 255 before any math runs (setPixels/getPixels round-trip) and+ * no array conversion can reproduce that loss bit-exactly — equality is+ * therefore asserted on the opaque pixels photo backdrops consist of.+ */+ private fun pattern(w: Int, h: Int): IntArray {+ var seed = 0x12345678+ fun next(): Int {+ seed = (seed * 1103515245 + 12345) and 0x7fffffff+ return (seed shr 8) and 0xFF+ }+ return IntArray(w * h) {+ (0xFF shl 24) or (next() shl 16) or (next() shl 8) or next()+ }+ }++ private fun bitmapOf(pixels: IntArray, w: Int, h: Int): Bitmap {+ val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ bmp.setPixels(pixels, 0, w, 0, 0, w, h)+ return bmp+ }++ private fun intsOf(bitmap: Bitmap): IntArray {+ val out = IntArray(bitmap.width * bitmap.height)+ bitmap.getPixels(out, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)+ return out+ }++ private fun assertPixelIdentical(label: String, adj: LayerAdjustment, w: Int, h: Int) {+ val input = pattern(w, h)+ val expected = intsOf(adj.applyToBitmap(bitmapOf(input.copyOf(), w, h)))+ val working = input.copyOf()+ val result = adj.applyToPixels(working, w, h)+ assertNotNull(result, "$label: applyToPixels returned null")+ assertEquals(w * h, result.size, "$label: result size")+ assertTrue(+ expected.contentEquals(result),+ "$label: pixel path differs from bitmap path at ${w}x$h " ++ "(first diff index ${expected.indices.firstOrNull { expected[it] != result[it] }})",+ )+ }++ private fun assertAllSizes(label: String, adj: LayerAdjustment) {+ assertPixelIdentical(label, adj, 16, 16)+ assertPixelIdentical(label, adj, 24, 18)+ assertPixelIdentical(label, adj, 13, 11)+ }++ /**+ * Like [assertPixelIdentical], but compares after one identical Bitmap+ * storage round-trip on the pixel-path result. Needed for the native+ * gaussian-family blurs: their kernel lets alpha drift (255 -> 254), and+ * the legacy path's `setPixels` then premultiplies RGB by that alpha,+ * losing up to 1 level on a few pixels — the raw native ints are the+ * exact ones, the bitmap-stored form (the only form bitmap callers ever+ * see, and the form the compositor finally produces) is bit-identical.+ */+ private fun assertPixelIdenticalViaBitmapStorage(label: String, adj: LayerAdjustment, w: Int, h: Int) {+ val input = pattern(w, h)+ val expected = intsOf(adj.applyToBitmap(bitmapOf(input.copyOf(), w, h)))+ val working = input.copyOf()+ val result = adj.applyToPixels(working, w, h)+ assertNotNull(result, "$label: applyToPixels returned null")+ val stored = intsOf(bitmapOf(result.copyOf(), w, h))+ assertTrue(+ expected.contentEquals(stored),+ "$label: bitmap-stored pixel path differs from bitmap path at ${w}x$h",+ )+ }++ @Test fun everyAdjustmentIsPixelIdentical() {+ assertAllSizes("basic-matrix", BasicAdjustment(ImageAdjustments(+ brightness = 20f, contrast = 15f, saturation = 30f, warmth = 10f,+ exposure = 12f, highlights = 18f, shadows = -8f, fade = 15f, tint = -12f,+ )))+ assertAllSizes("basic-sharpen", BasicAdjustment(ImageAdjustments(sharpness = 60f)))+ assertAllSizes("basic-grain", BasicAdjustment(ImageAdjustments(grain = 55f)))+ assertAllSizes("basic-matrix-sharpen-grain", BasicAdjustment(ImageAdjustments(+ contrast = 20f, saturation = -25f, sharpness = 45f, grain = 30f,+ )))+ assertAllSizes("curves", CurvesAdj(CurvesAdjustment(+ combined = listOf(+ CurveControlPoint(0f, 0f), CurveControlPoint(0.5f, 0.8f), CurveControlPoint(1f, 1f),+ ),+ red = listOf(+ CurveControlPoint(0f, 0.1f), CurveControlPoint(1f, 0.9f),+ ),+ )))+ assertAllSizes("hsl", HslAdj(HslAdjustments(channels = HslColorRange.entries.associateWith {+ HslChannelAdjustment(hue = 20f, saturation = 0.5f, luminance = 0.1f)+ })))+ assertAllSizes("levels", LevelsAdj(LevelsAdjustment(inBlack = 20f, inWhite = 230f, gamma = 1.4f)))+ assertAllSizes("color-balance", ColorBalanceAdj(ColorBalanceAdjustment(+ midRedCyan = 0.4f, midGreenMagenta = -0.2f, midBlueYellow = 0.3f, shadowsRedCyan = 0.2f,+ )))+ assertAllSizes("channel-mixer", ChannelMixerAdj(ChannelMixerAdjustment(+ rFromR = 0.5f, rFromG = 0.5f, gFromG = 0.6f, gFromB = 0.4f,+ )))+ assertAllSizes("channel-mixer-mono", ChannelMixerAdj(ChannelMixerAdjustment(+ rFromR = 0.3f, rFromG = 0.6f, rFromB = 0.1f, monochrome = true,+ )))+ assertAllSizes("gradient-map", GradientMapAdj(GradientMapAdjustment(stops = listOf(+ GradientStop(0f, 0xFF102040.toInt()), GradientStop(0.5f, 0xFF808080.toInt()),+ GradientStop(1f, 0xFFFFE0B0.toInt()),+ ))))+ assertAllSizes("black-and-white", BlackAndWhiteAdj(BlackAndWhiteAdjustment(enabled = true)))+ assertAllSizes("black-and-white-tint", BlackAndWhiteAdj(BlackAndWhiteAdjustment(+ enabled = true, tint = 0xFFD0A060.toInt(),+ )))+ // Native gaussian-family blurs: alpha drift makes the legacy bitmap+ // path lossy at raw-int level; equality holds at bitmap storage.+ for ((w, h) in listOf(16 to 16, 24 to 18, 13 to 11)) {+ assertPixelIdenticalViaBitmapStorage("blur", BlurAdj(BlurParams(radius = 0.5f, intensity = 20f)), w, h)+ }+ assertAllSizes("selective", SelectiveAdj(SelectiveEdits(masks = listOf(+ SelectiveMask(+ type = MaskType.RadialGradient, centerX = 0.5f, centerY = 0.5f, radius = 0.4f,+ adjustments = ImageAdjustments(brightness = 25f, saturation = 20f),+ ),+ SelectiveMask(+ type = MaskType.Brush,+ brushPoints = listOf(0.25f to 0.25f, 0.75f to 0.6f),+ adjustments = ImageAdjustments(contrast = 30f, sharpness = 40f),+ ),+ ))))+ assertAllSizes("invert", InvertAdj())+ assertAllSizes("posterize", PosterizeAdj(levels = 5))+ assertAllSizes("threshold", ThresholdAdj(level = 100))+ assertAllSizes("vibrance", VibranceAdj(amount = 70f))+ assertAllSizes("photo-filter", PhotoFilterAdj(density = 0.4f))+ assertAllSizes("selective-color", SelectiveColorAdj(+ range = SelectiveColorRange.Reds, cyan = 50f, magenta = -30f, yellow = 20f,+ ))+ assertAllSizes("selective-color-neutrals", SelectiveColorAdj(+ range = SelectiveColorRange.Neutrals, cyan = -40f, yellow = 35f,+ ))+ for ((w, h) in listOf(16 to 16, 24 to 18, 13 to 11)) {+ assertPixelIdenticalViaBitmapStorage("filter-blur", FilterBlurAdj(FilterBlur(amount = 3f)), w, h)+ }+ assertAllSizes("unsharp", UnsharpAdj(UnsharpMask(amount = 0.8f, radius = 2f, threshold = 5)))+ assertAllSizes("noise-mono", NoiseAdj(NoiseParams(amount = 60f, monochrome = true)))+ assertAllSizes("noise-color", NoiseAdj(NoiseParams(amount = 60f, monochrome = false)))+ assertAllSizes("stylize-edges", StylizeAdj(StylizeParams(mode = StylizeMode.FindEdges)))+ assertAllSizes("stylize-emboss", StylizeAdj(StylizeParams(mode = StylizeMode.Emboss)))+ }++ @Test fun pixelPathReusesCallerBuffer() {+ // Per-pixel ops mutate and return the caller's own array (no new+ // IntArray, no bitmap round-trip); native ops write back into it too.+ val input = pattern(16, 16)+ val hsl = HslAdj(HslAdjustments(channels = HslColorRange.entries.associateWith {+ HslChannelAdjustment(hue = 15f)+ }))+ assertSame(input, hsl.applyToPixels(input, 16, 16))+ val native = pattern(16, 16)+ val stylize = StylizeAdj(StylizeParams(mode = StylizeMode.Emboss))+ assertSame(native, stylize.applyToPixels(native, 16, 16))+ }++ @Test fun vignetteHasNoPixelPathAndCompositorFallsBack() {+ // Vignette draws a RadialGradient through Skia; per-pixel float math+ // is off by one on ~30-55% of pixels, so it must refuse the array+ // path (null) instead of silently changing output.+ assertNull(+ BasicAdjustment(ImageAdjustments(vignette = 50f)).applyToPixels(pattern(16, 16), 16, 16),+ )+ assertNull(+ SelectiveAdj(SelectiveEdits(masks = listOf(+ SelectiveMask(adjustments = ImageAdjustments(vignette = 40f)),+ ))).applyToPixels(pattern(16, 16), 16, 16),+ )+ // Through the compositor the fallback still renders pixel-identically+ // to the plain bitmap path (opaque base, Normal blend at opacity 1).+ val w = 16+ val h = 16+ val base = pattern(w, h).map { it or (0xFF shl 24) }.toIntArray()+ val adj = BasicAdjustment(ImageAdjustments(vignette = 50f, brightness = 10f))+ val expected = intsOf(adj.applyToBitmap(bitmapOf(base.copyOf(), w, h)))+ val doc = EditDocument(canvasWidth = w, canvasHeight = h)+ .addLayer(PixelLayer(bitmapRef = BitmapReference(bitmapOf(base.copyOf(), w, h)), name = "base"))+ .addLayer(AdjustmentLayer(adjustment = adj, name = "vignette"))+ val out = intsOf(LayerCompositor().composite(doc))+ assertTrue(expected.contentEquals(out), "compositor vignette fallback differs from bitmap path")+ }++ @Test fun compositorAdjustmentMatchesBitmapPath() {+ // An adjustment layer composited by LayerCompositor (array path) over+ // an opaque base at Normal/opacity 1 equals applying the same+ // adjustment to the base bitmap directly.+ val w = 24+ val h = 18+ val base = pattern(w, h).map { it or (0xFF shl 24) }.toIntArray()+ val adjustments = listOf(+ BasicAdjustment(ImageAdjustments(brightness = 18f, contrast = 12f, saturation = 22f)),+ HslAdj(HslAdjustments(channels = HslColorRange.entries.associateWith {+ HslChannelAdjustment(hue = -25f, saturation = 0.3f)+ })),+ LevelsAdj(LevelsAdjustment(inBlack = 15f, gamma = 1.3f)),+ StylizeAdj(StylizeParams(mode = StylizeMode.FindEdges)),+ )+ for (adj in adjustments) {+ val expected = intsOf(adj.applyToBitmap(bitmapOf(base.copyOf(), w, h)))+ val doc = EditDocument(canvasWidth = w, canvasHeight = h)+ .addLayer(PixelLayer(bitmapRef = BitmapReference(bitmapOf(base.copyOf(), w, h)), name = "base"))+ .addLayer(AdjustmentLayer(adjustment = adj, name = adj.label))+ val out = intsOf(LayerCompositor().composite(doc))+ assertTrue(expected.contentEquals(out), "${adj.label}: compositor differs from bitmap path")+ val preview = intsOf(LayerCompositor().compositePreview(doc, 1024))+ assertTrue(expected.contentEquals(preview), "${adj.label}: preview differs from bitmap path")+ }+ }+}