Modern Apps git

← Modern-Apps.git

photos: native rust pixel filters (blur/sharpen/liquify/stylize/inpaint)

Commit
4ce4e75f138fb0aa3f7b995da2f97f300a41de67
Author
Vayun Mathur <[email protected]>
When
2026-07-29 03:16 UTC (4 months ago)
Parents
10e0ed7

Diff

photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex def6da6d4b..a5316b8693 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -24,6 +24,17 @@ android {     } } +androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        )+    }+}++// Native pixel filters (Rust). See photos/src/main/rust/.+rustNativeLib("photos_fx", "photos")+ metadataScreenshots {     permissions.addAll(         "android.permission.READ_MEDIA_IMAGES",
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 d2347b5cdf..f6554b6b07 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/BlurData.kt@@ -1,10 +1,7 @@ package com.vayunmathur.photos.data  import android.graphics.Bitmap-import kotlin.math.exp-import kotlin.math.max-import kotlin.math.min-import kotlin.math.sqrt+import com.vayunmathur.photos.util.PhotosNative  enum class BlurMode { Radial, Linear, Lens } @@ -20,142 +17,16 @@ data class BlurParams(     fun isIdentity(): Boolean = intensity == 0f } -private fun generateGaussianKernel(radius: Int): FloatArray {-    val size = radius * 2 + 1-    val kernel = FloatArray(size)-    val sigma = radius / 3f-    var sum = 0f-    for (i in 0 until size) {-        val x = (i - radius).toFloat()-        kernel[i] = exp(-(x * x) / (2f * sigma * sigma))-        sum += kernel[i]-    }-    for (i in 0 until size) kernel[i] /= sum-    return kernel-}--internal fun gaussianBlur(pixels: IntArray, w: Int, h: Int, radius: Int): IntArray {-    if (radius <= 0) return pixels.copyOf()-    val kernel = generateGaussianKernel(radius)-    val temp = IntArray(w * h)-    val output = IntArray(w * h)-    for (y in 0 until h) {-        for (x in 0 until w) {-            var rr = 0f; var gg = 0f; var bb = 0f; var aa = 0f-            for (k in -radius..radius) {-                val sx = (x + k).coerceIn(0, w - 1)-                val px = pixels[y * w + sx]-                val weight = kernel[k + radius]-                aa += ((px shr 24) and 0xFF) * weight-                rr += ((px shr 16) and 0xFF) * weight-                gg += ((px shr 8) and 0xFF) * weight-                bb += (px and 0xFF) * weight-            }-            temp[y * w + x] = (aa.toInt().coerceIn(0, 255) shl 24) or-                    (rr.toInt().coerceIn(0, 255) shl 16) or-                    (gg.toInt().coerceIn(0, 255) shl 8) or-                    bb.toInt().coerceIn(0, 255)-        }-    }-    for (y in 0 until h) {-        for (x in 0 until w) {-            var rr = 0f; var gg = 0f; var bb = 0f; var aa = 0f-            for (k in -radius..radius) {-                val sy = (y + k).coerceIn(0, h - 1)-                val px = temp[sy * w + x]-                val weight = kernel[k + radius]-                aa += ((px shr 24) and 0xFF) * weight-                rr += ((px shr 16) and 0xFF) * weight-                gg += ((px shr 8) and 0xFF) * weight-                bb += (px and 0xFF) * weight-            }-            output[y * w + x] = (aa.toInt().coerceIn(0, 255) shl 24) or-                    (rr.toInt().coerceIn(0, 255) shl 16) or-                    (gg.toInt().coerceIn(0, 255) shl 8) or-                    bb.toInt().coerceIn(0, 255)-        }-    }-    return output-}--private fun generateMask(params: BlurParams, w: Int, h: Int): FloatArray {-    val mask = FloatArray(w * h)-    when (params.mode) {-        BlurMode.Radial -> {-            val cx = params.centerX * w-            val cy = params.centerY * h-            val r = params.radius * max(w, h)-            val featherDist = params.feather * max(w, h)-            for (y in 0 until h) {-                for (x in 0 until w) {-                    val dist = sqrt(((x - cx) * (x - cx) + (y - cy) * (y - cy)).toDouble()).toFloat()-                    mask[y * w + x] = if (dist < r) 0f-                    else ((dist - r) / featherDist.coerceAtLeast(1f)).coerceIn(0f, 1f)-                }-            }-        }-        BlurMode.Linear -> {-            val cx = params.centerX * w-            val cy = params.centerY * h-            val r = params.radius * max(w, h)-            val featherDist = params.feather * max(w, h)-            val rad = Math.toRadians(params.angle.toDouble())-            val nx = -kotlin.math.sin(rad).toFloat()-            val ny = kotlin.math.cos(rad).toFloat()-            for (y in 0 until h) {-                for (x in 0 until w) {-                    val dist = kotlin.math.abs((x - cx) * nx + (y - cy) * ny)-                    mask[y * w + x] = if (dist < r) 0f-                    else ((dist - r) / featherDist.coerceAtLeast(1f)).coerceIn(0f, 1f)-                }-            }-        }-        BlurMode.Lens -> {-            val cx = params.centerX * w-            val cy = params.centerY * h-            val r = params.radius * max(w, h)-            for (y in 0 until h) {-                for (x in 0 until w) {-                    val dist = sqrt(((x - cx) * (x - cx) + (y - cy) * (y - cy)).toDouble()).toFloat()-                    mask[y * w + x] = if (dist > r) 1f else 0f-                }-            }-        }-    }-    return mask-}- fun BlurParams.applyBlurToBitmap(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)-    val blurRadius = (intensity * 0.5f).toInt().coerceIn(1, 25)-    val blurred = gaussianBlur(pixels, w, h, blurRadius)-    val mask = generateMask(this, w, h)-    val output = IntArray(w * h)-    for (i in pixels.indices) {-        val m = mask[i]-        val origA = (pixels[i] shr 24) and 0xFF-        val origR = (pixels[i] shr 16) and 0xFF-        val origG = (pixels[i] shr 8) and 0xFF-        val origB = pixels[i] and 0xFF-        val blurA = (blurred[i] shr 24) and 0xFF-        val blurR = (blurred[i] shr 16) and 0xFF-        val blurG = (blurred[i] shr 8) and 0xFF-        val blurB = blurred[i] and 0xFF-        val a = (origA + (blurA - origA) * m).toInt().coerceIn(0, 255)-        val r = (origR + (blurR - origR) * m).toInt().coerceIn(0, 255)-        val g = (origG + (blurG - origG) * m).toInt().coerceIn(0, 255)-        val b = (origB + (blurB - origB) * m).toInt().coerceIn(0, 255)-        output[i] = (a shl 24) or (r shl 16) or (g shl 8) or b-    }-    val result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)-    result.setPixels(output, 0, w, 0, 0, w, h)-    return result+    val out = PhotosNative.blurParams(pixels, w, h, mode.ordinal, centerX, centerY, radius, intensity, feather, angle)+    return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { setPixels(out, 0, w, 0, 0, w, h) } } -// --- Phase 4: full-image filter blurs -------------------------------------------+// --- Full-image filter blurs ----------------------------------------------------  enum class FilterBlurMode { Gaussian, Motion, Radial, Spin } @@ -176,84 +47,6 @@ fun FilterBlur.applyToBitmap(bitmap: Bitmap): Bitmap {     val h = bitmap.height     val src = IntArray(w * h)     bitmap.getPixels(src, 0, w, 0, 0, w, h)-    val out = when (mode) {-        FilterBlurMode.Gaussian -> gaussianBlur(src, w, h, (amount * 0.5f).toInt().coerceIn(1, 60))-        FilterBlurMode.Motion -> motionBlur(src, w, h, amount.toInt().coerceIn(1, 100), angle)-        FilterBlurMode.Radial -> radialBlur(src, w, h, amount, centerX, centerY, spin = false)-        FilterBlurMode.Spin -> radialBlur(src, w, h, amount, centerX, centerY, spin = true)-    }-    val result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)-    result.setPixels(out, 0, w, 0, 0, w, h)-    return result-}--private fun motionBlur(src: IntArray, w: Int, h: Int, length: Int, angle: Float): IntArray {-    val out = IntArray(w * h)-    val rad = Math.toRadians(angle.toDouble())-    val dx = kotlin.math.cos(rad).toFloat()-    val dy = kotlin.math.sin(rad).toFloat()-    val half = length / 2-    for (y in 0 until h) {-        for (x in 0 until w) {-            var aa = 0f; var rr = 0f; var gg = 0f; var bb = 0f; var n = 0f-            for (k in -half..half) {-                val sx = (x + (dx * k)).toInt().coerceIn(0, w - 1)-                val sy = (y + (dy * k)).toInt().coerceIn(0, h - 1)-                val p = src[sy * w + sx]-                aa += (p ushr 24) and 0xFF-                rr += (p ushr 16) and 0xFF-                gg += (p ushr 8) and 0xFF-                bb += p and 0xFF-                n++-            }-            out[y * w + x] = ((aa / n).toInt() shl 24) or ((rr / n).toInt() shl 16) or-                ((gg / n).toInt() shl 8) or (bb / n).toInt()-        }-    }-    return out-}--private fun radialBlur(-    src: IntArray, w: Int, h: Int, amount: Float,-    centerX: Float, centerY: Float, spin: Boolean,-): IntArray {-    val out = IntArray(w * h)-    val cx = centerX * w-    val cy = centerY * h-    val samples = (amount * 0.2f).toInt().coerceIn(3, 30)-    val strength = amount / 100f-    for (y in 0 until h) {-        for (x in 0 until w) {-            var aa = 0f; var rr = 0f; var gg = 0f; var bb = 0f-            val odx = x - cx-            val ody = y - cy-            for (s in 0 until samples) {-                val t = s.toFloat() / samples-                val sx: Float-                val sy: Float-                if (spin) {-                    val ang = -strength * 0.3f * t-                    val cosA = kotlin.math.cos(ang.toDouble()).toFloat()-                    val sinA = kotlin.math.sin(ang.toDouble()).toFloat()-                    sx = cx + (odx * cosA - ody * sinA)-                    sy = cy + (odx * sinA + ody * cosA)-                } else {-                    val scale = 1f - strength * t-                    sx = cx + odx * scale-                    sy = cy + ody * scale-                }-                val ix = sx.toInt().coerceIn(0, w - 1)-                val iy = sy.toInt().coerceIn(0, h - 1)-                val p = src[iy * w + ix]-                aa += (p ushr 24) and 0xFF-                rr += (p ushr 16) and 0xFF-                gg += (p ushr 8) and 0xFF-                bb += p and 0xFF-            }-            val n = samples.toFloat()-            out[y * w + x] = ((aa / n).toInt() shl 24) or ((rr / n).toInt() shl 16) or-                ((gg / n).toInt() shl 8) or (bb / n).toInt()-        }-    }-    return out+    val out = PhotosNative.filterBlur(src, w, h, mode.ordinal, amount, angle, centerX, centerY)+    return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { setPixels(out, 0, w, 0, 0, w, h) } }
photos/src/main/java/com/vayunmathur/photos/data/ContentAwareData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/ContentAwareData.kt b/photos/src/main/java/com/vayunmathur/photos/data/ContentAwareData.ktindex bad309b2d3..73213f55a4 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/ContentAwareData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/ContentAwareData.kt@@ -1,13 +1,12 @@ package com.vayunmathur.photos.data  import android.graphics.Bitmap+import com.vayunmathur.photos.util.PhotosNative  /**- * Content-aware fill: remove the region marked by [holeMask] (normalized, at- * [maskW] x [maskH]). For small/medium holes it uses exemplar-based synthesis- * (onion-peel: fill boundary pixels by copying the best-matching known patch),- * which reproduces texture far better than diffusion. Very large holes fall back- * to a cheap Jacobi diffusion so the op stays bounded.+ * Content-aware fill: removes the region marked by [holeMask] (normalized, at+ * [maskW] x [maskH]) via native exemplar-based synthesis, falling back internally+ * to Jacobi diffusion for very large holes so the op stays bounded.  */ fun inpaintBitmap(     bitmap: Bitmap,@@ -21,145 +20,7 @@ fun inpaintBitmap(     val out = bitmap.copy(Bitmap.Config.ARGB_8888, true)     val px = IntArray(w * h)     out.getPixels(px, 0, w, 0, 0, w, h)--    val hole = BooleanArray(w * h)-    var holeCount = 0-    var minX = w; var minY = h; var maxX = -1; var maxY = -1-    for (y in 0 until h) {-        val my = (y * maskH / h).coerceIn(0, maskH - 1)-        for (x in 0 until w) {-            val mx = (x * maskW / w).coerceIn(0, maskW - 1)-            if (holeMask[my * maskW + mx] >= 0.5f) {-                hole[y * w + x] = true-                holeCount++-                if (x < minX) minX = x; if (x > maxX) maxX = x-                if (y < minY) minY = y; if (y > maxY) maxY = y-            }-        }-    }-    if (maxX < minX) return out--    if (holeCount > 20000) {-        diffuseFill(px, w, h, hole, minX, minY, maxX, maxY, passes)-    } else {-        exemplarFill(px, w, h, hole, minX, minY, maxX, maxY)-    }-    out.setPixels(px, 0, w, 0, 0, w, h)+    val filled = PhotosNative.inpaint(px, w, h, holeMask, maskW, maskH, passes)+    out.setPixels(filled, 0, w, 0, 0, w, h)     return out }--/** Onion-peel exemplar synthesis over the hole's bounding box. */-private fun exemplarFill(-    px: IntArray, w: Int, h: Int, hole: BooleanArray,-    minX: Int, minY: Int, maxX: Int, maxY: Int,-) {-    val patchR = 1-    val searchR = 12-    fun idx(x: Int, y: Int) = y * w + x-    fun diff(a: Int, b: Int): Int {-        val dr = ((a ushr 16) and 0xFF) - ((b ushr 16) and 0xFF)-        val dg = ((a ushr 8) and 0xFF) - ((b ushr 8) and 0xFF)-        val db = (a and 0xFF) - (b and 0xFF)-        return dr * dr + dg * dg + db * db-    }--    var remaining = true-    var guard = (maxX - minX + 1) * (maxY - minY + 1) + 8-    while (remaining && guard-- > 0) {-        remaining = false-        // Collect current boundary hole pixels (adjacent to a known pixel).-        val boundary = ArrayList<Int>()-        for (y in minY..maxY) {-            for (x in minX..maxX) {-                if (!hole[idx(x, y)]) continue-                val nb = (x > 0 && !hole[idx(x - 1, y)]) || (x < w - 1 && !hole[idx(x + 1, y)]) ||-                    (y > 0 && !hole[idx(x, y - 1)]) || (y < h - 1 && !hole[idx(x, y + 1)])-                if (nb) boundary.add(idx(x, y))-            }-        }-        if (boundary.isEmpty()) break-        remaining = true-        val newColors = IntArray(boundary.size)-        for (bi in boundary.indices) {-            val p = boundary[bi]-            val pxc = p % w; val pyc = p / w-            var bestQ = -1-            var bestScore = Int.MAX_VALUE-            val sx0 = (pxc - searchR).coerceAtLeast(patchR)-            val sx1 = (pxc + searchR).coerceAtMost(w - 1 - patchR)-            val sy0 = (pyc - searchR).coerceAtLeast(patchR)-            val sy1 = (pyc + searchR).coerceAtMost(h - 1 - patchR)-            var qy = sy0-            while (qy <= sy1) {-                var qx = sx0-                while (qx <= sx1) {-                    if (!hole[idx(qx, qy)]) {-                        var score = 0-                        var valid = true-                        var oy = -patchR-                        loop@ while (oy <= patchR) {-                            var ox = -patchR-                            while (ox <= patchR) {-                                val pnx = pxc + ox; val pny = pyc + oy-                                val qnx = qx + ox; val qny = qy + oy-                                if (pnx in 0 until w && pny in 0 until h && !hole[idx(pnx, pny)]) {-                                    if (hole[idx(qnx, qny)]) { valid = false; break@loop }-                                    score += diff(px[idx(pnx, pny)], px[idx(qnx, qny)])-                                }-                                ox++-                            }-                            oy++-                        }-                        if (valid && score < bestScore) { bestScore = score; bestQ = idx(qx, qy) }-                    }-                    qx++-                }-                qy++-            }-            newColors[bi] = if (bestQ >= 0) px[bestQ] else px[p]-        }-        // Commit this peel layer.-        for (bi in boundary.indices) {-            val p = boundary[bi]-            px[p] = newColors[bi]-            hole[p] = false-        }-    }-    // Safety: anything still marked (shouldn't happen) gets a neutral gray.-    for (y in minY..maxY) for (x in minX..maxX) if (hole[idx(x, y)]) px[idx(x, y)] = px[idx(x, y)] and -0x1000000 or 0x808080-}--/** Cheap Jacobi diffusion fallback for very large holes. */-private fun diffuseFill(-    px: IntArray, w: Int, h: Int, hole: BooleanArray,-    minX: Int, minY: Int, maxX: Int, maxY: Int, passes: Int,-) {-    val bw = maxX - minX + 1-    val bh = maxY - minY + 1-    val r = FloatArray(bw * bh); val g = FloatArray(bw * bh); val b = FloatArray(bw * bh)-    val holeBox = BooleanArray(bw * bh)-    for (y in 0 until bh) for (x in 0 until bw) {-        val gi = (minY + y) * w + (minX + x); val c = px[gi]; val bi = y * bw + x-        r[bi] = ((c ushr 16) and 0xFF).toFloat(); g[bi] = ((c ushr 8) and 0xFF).toFloat(); b[bi] = (c and 0xFF).toFloat()-        holeBox[bi] = hole[gi]-    }-    val nr = r.copyOf(); val ng = g.copyOf(); val nb = b.copyOf()-    fun s(a: FloatArray, x: Int, y: Int) = a[y.coerceIn(0, bh - 1) * bw + x.coerceIn(0, bw - 1)]-    repeat(passes) {-        for (y in 0 until bh) for (x in 0 until bw) {-            val bi = y * bw + x-            if (!holeBox[bi]) continue-            nr[bi] = (s(r, x - 1, y) + s(r, x + 1, y) + s(r, x, y - 1) + s(r, x, y + 1)) / 4f-            ng[bi] = (s(g, x - 1, y) + s(g, x + 1, y) + s(g, x, y - 1) + s(g, x, y + 1)) / 4f-            nb[bi] = (s(b, x - 1, y) + s(b, x + 1, y) + s(b, x, y - 1) + s(b, x, y + 1)) / 4f-        }-        System.arraycopy(nr, 0, r, 0, r.size); System.arraycopy(ng, 0, g, 0, g.size); System.arraycopy(nb, 0, b, 0, b.size)-    }-    for (y in 0 until bh) for (x in 0 until bw) {-        val bi = y * bw + x-        if (!holeBox[bi]) continue-        val gi = (minY + y) * w + (minX + x)-        px[gi] = (px[gi] and -0x1000000) or (r[bi].toInt().coerceIn(0, 255) shl 16) or-            (g[bi].toInt().coerceIn(0, 255) shl 8) or b[bi].toInt().coerceIn(0, 255)-    }-}
photos/src/main/java/com/vayunmathur/photos/data/LiquifyData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/LiquifyData.kt b/photos/src/main/java/com/vayunmathur/photos/data/LiquifyData.ktindex 6062958110..d1bbecbf97 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/LiquifyData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/LiquifyData.kt@@ -1,10 +1,7 @@ package com.vayunmathur.photos.data  import android.graphics.Bitmap-import kotlin.math.cos-import kotlin.math.max-import kotlin.math.sin-import kotlin.math.sqrt+import com.vayunmathur.photos.util.PhotosNative  enum class LiquifyTool { Push, Twirl, Pucker, Bloat, Reconstruct } @@ -34,126 +31,18 @@ fun LiquifyParams.applyToBitmap(bitmap: Bitmap): Bitmap {         return output     } -    val dispX = FloatArray(w * h)-    val dispY = FloatArray(w * h)--    val maxDim = max(w, h).toFloat()--    for (op in ops) {-        val cx = op.x * w-        val cy = op.y * h-        val radiusPx = op.radius * maxDim-        if (radiusPx <= 0f) continue--        val angleBase = (op.strength * Math.PI).toFloat()-        val dragX = op.dx * maxDim-        val dragY = op.dy * maxDim--        val minX = max(0, (cx - radiusPx).toInt())-        val maxX = minOf(w - 1, (cx + radiusPx).toInt())-        val minY = max(0, (cy - radiusPx).toInt())-        val maxY = minOf(h - 1, (cy + radiusPx).toInt())--        for (py in minY..maxY) {-            for (px in minX..maxX) {-                val ox = px - cx-                val oy = py - cy-                val dist = sqrt(ox * ox + oy * oy)-                if (dist > radiusPx) continue--                val raw = (1f - dist / radiusPx).coerceIn(0f, 1f)-                val t = raw * raw * (3f - 2f * raw) // smoothstep falloff--                val idx = py * w + px--                when (op.tool) {-                    LiquifyTool.Push -> {-                        dispX[idx] += -dragX * op.strength * t-                        dispY[idx] += -dragY * op.strength * t-                    }-                    LiquifyTool.Twirl -> {-                        val angle = angleBase * t-                        val c = cos(angle)-                        val s = sin(angle)-                        val rotX = ox * c - oy * s-                        val rotY = ox * s + oy * c-                        dispX[idx] += rotX - ox-                        dispY[idx] += rotY - oy-                    }-                    LiquifyTool.Pucker -> {-                        dispX[idx] += (cx - px) * op.strength * t * 0.5f-                        dispY[idx] += (cy - py) * op.strength * t * 0.5f-                    }-                    LiquifyTool.Bloat -> {-                        dispX[idx] += (px - cx) * op.strength * t * 0.5f-                        dispY[idx] += (py - cy) * op.strength * t * 0.5f-                    }-                    LiquifyTool.Reconstruct -> {-                        val factor = (1f - op.strength * t).coerceIn(0f, 1f)-                        dispX[idx] *= factor-                        dispY[idx] *= factor-                    }-                }-            }-        }+    val tools = IntArray(ops.size) { ops[it].tool.ordinal }+    val params = FloatArray(ops.size * 6)+    for (i in ops.indices) {+        val op = ops[i]+        params[i * 6] = op.x+        params[i * 6 + 1] = op.y+        params[i * 6 + 2] = op.dx+        params[i * 6 + 3] = op.dy+        params[i * 6 + 4] = op.radius+        params[i * 6 + 5] = op.strength     }--    val dst = IntArray(w * h)-    for (y in 0 until h) {-        for (x in 0 until w) {-            val idx = y * w + x-            val sx = x + dispX[idx]-            val sy = y + dispY[idx]-            dst[idx] = sampleBilinear(src, w, h, sx, sy)-        }-    }--    output.setPixels(dst, 0, w, 0, 0, w, h)+    val out = PhotosNative.liquify(src, w, h, tools, params)+    output.setPixels(out, 0, w, 0, 0, w, h)     return output }--private fun sampleBilinear(src: IntArray, w: Int, h: Int, fx: Float, fy: Float): Int {-    val cx = fx.coerceIn(0f, (w - 1).toFloat())-    val cy = fy.coerceIn(0f, (h - 1).toFloat())--    val x0 = cx.toInt()-    val y0 = cy.toInt()-    val x1 = minOf(x0 + 1, w - 1)-    val y1 = minOf(y0 + 1, h - 1)--    val tx = cx - x0-    val ty = cy - y0--    val p00 = src[y0 * w + x0]-    val p10 = src[y0 * w + x1]-    val p01 = src[y1 * w + x0]-    val p11 = src[y1 * w + x1]--    val a = lerpChannel(p00, p10, p01, p11, tx, ty, 24)-    val r = lerpChannel(p00, p10, p01, p11, tx, ty, 16)-    val g = lerpChannel(p00, p10, p01, p11, tx, ty, 8)-    val b = lerpChannel(p00, p10, p01, p11, tx, ty, 0)--    return (a shl 24) or (r shl 16) or (g shl 8) or b-}--private fun lerpChannel(-    p00: Int,-    p10: Int,-    p01: Int,-    p11: Int,-    tx: Float,-    ty: Float,-    shift: Int,-): Int {-    val c00 = ((p00 shr shift) and 0xFF).toFloat()-    val c10 = ((p10 shr shift) and 0xFF).toFloat()-    val c01 = ((p01 shr shift) and 0xFF).toFloat()-    val c11 = ((p11 shr shift) and 0xFF).toFloat()--    val top = c00 + (c10 - c00) * tx-    val bottom = c01 + (c11 - c01) * tx-    val value = top + (bottom - top) * ty--    return value.toInt().coerceIn(0, 255)-}
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 c13a95482e..75fa045263 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/SharpenData.kt@@ -1,9 +1,7 @@ package com.vayunmathur.photos.data  import android.graphics.Bitmap-import kotlin.math.abs-import kotlin.math.exp-import kotlin.math.roundToInt+import com.vayunmathur.photos.util.PhotosNative  data class UnsharpMask(     val amount: Float = 0f,@@ -13,103 +11,11 @@ data class UnsharpMask(     fun isIdentity(): Boolean = amount == 0f } -private fun unsharpGaussianKernel(radius: Int): FloatArray {-    val size = radius * 2 + 1-    val kernel = FloatArray(size)-    val sigma = radius / 3f-    var sum = 0f-    for (i in 0 until size) {-        val x = (i - radius).toFloat()-        kernel[i] = exp(-(x * x) / (2f * sigma * sigma))-        sum += kernel[i]-    }-    for (i in 0 until size) kernel[i] /= sum-    return kernel-}--private fun unsharpGaussianBlur(pixels: IntArray, w: Int, h: Int, radius: Int): IntArray {-    if (radius <= 0) return pixels.copyOf()-    val kernel = unsharpGaussianKernel(radius)-    val temp = IntArray(w * h)-    val output = IntArray(w * h)-    for (y in 0 until h) {-        for (x in 0 until w) {-            var rr = 0f; var gg = 0f; var bb = 0f; var aa = 0f-            for (k in -radius..radius) {-                val sx = (x + k).coerceIn(0, w - 1)-                val px = pixels[y * w + sx]-                val weight = kernel[k + radius]-                aa += ((px ushr 24) and 0xFF) * weight-                rr += ((px ushr 16) and 0xFF) * weight-                gg += ((px ushr 8) and 0xFF) * weight-                bb += (px and 0xFF) * weight-            }-            temp[y * w + x] = (aa.toInt().coerceIn(0, 255) shl 24) or-                (rr.toInt().coerceIn(0, 255) shl 16) or-                (gg.toInt().coerceIn(0, 255) shl 8) or-                bb.toInt().coerceIn(0, 255)-        }-    }-    for (y in 0 until h) {-        for (x in 0 until w) {-            var rr = 0f; var gg = 0f; var bb = 0f; var aa = 0f-            for (k in -radius..radius) {-                val sy = (y + k).coerceIn(0, h - 1)-                val px = temp[sy * w + x]-                val weight = kernel[k + radius]-                aa += ((px ushr 24) and 0xFF) * weight-                rr += ((px ushr 16) and 0xFF) * weight-                gg += ((px ushr 8) and 0xFF) * weight-                bb += (px and 0xFF) * weight-            }-            output[y * w + x] = (aa.toInt().coerceIn(0, 255) shl 24) or-                (rr.toInt().coerceIn(0, 255) shl 16) or-                (gg.toInt().coerceIn(0, 255) shl 8) or-                bb.toInt().coerceIn(0, 255)-        }-    }-    return output-}- fun UnsharpMask.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)--    val strength = amount / 100f-    val intRadius = radius.roundToInt().coerceAtLeast(1)-    val blurred = unsharpGaussianBlur(pixels, w, h, intRadius)-    val output = IntArray(w * h)--    for (i in pixels.indices) {-        val p = pixels[i]-        val bp = blurred[i]-        val a = (p ushr 24) and 0xFF-        val origR = (p ushr 16) and 0xFF-        val origG = (p ushr 8) and 0xFF-        val origB = p and 0xFF-        val blurR = (bp ushr 16) and 0xFF-        val blurG = (bp ushr 8) and 0xFF-        val blurB = bp and 0xFF--        val r = sharpenChannel(origR, blurR, strength, threshold)-        val g = sharpenChannel(origG, blurG, strength, threshold)-        val b = sharpenChannel(origB, blurB, strength, threshold)--        output[i] = (a shl 24) or (r shl 16) or (g shl 8) or b-    }--    val result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)-    result.setPixels(output, 0, w, 0, 0, w, h)-    return result-}--private fun sharpenChannel(orig: Int, blurred: Int, strength: Float, threshold: Int): Int {-    val diff = orig - blurred-    return if (abs(diff) > threshold) {-        (orig + strength * diff).toInt().coerceIn(0, 255)-    } else {-        orig-    }+    val out = PhotosNative.unsharp(pixels, w, h, amount, radius, threshold)+    return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { setPixels(out, 0, w, 0, 0, w, h) } }
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 6f9630b99c..8b3602377b 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/StylizeData.kt@@ -1,7 +1,7 @@ package com.vayunmathur.photos.data  import android.graphics.Bitmap-import kotlin.math.sqrt+import com.vayunmathur.photos.util.PhotosNative  enum class StylizeMode { None, FindEdges, Emboss } @@ -11,70 +11,11 @@ data class StylizeParams(     fun isIdentity(): Boolean = mode == StylizeMode.None } -private fun luminanceAt(pixels: IntArray, w: Int, h: Int, x: Int, y: Int): Int {-    val sx = x.coerceIn(0, w - 1)-    val sy = y.coerceIn(0, h - 1)-    val p = pixels[sy * w + sx]-    val r = (p ushr 16) and 0xFF-    val g = (p ushr 8) and 0xFF-    val b = p and 0xFF-    return ((r * 299 + g * 587 + b * 114) / 1000)-}- fun StylizeParams.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)-    val output = IntArray(w * h)--    when (mode) {-        StylizeMode.None -> {-            System.arraycopy(pixels, 0, output, 0, pixels.size)-        }-        StylizeMode.FindEdges -> {-            for (y in 0 until h) {-                for (x in 0 until w) {-                    val tl = luminanceAt(pixels, w, h, x - 1, y - 1)-                    val tc = luminanceAt(pixels, w, h, x, y - 1)-                    val tr = luminanceAt(pixels, w, h, x + 1, y - 1)-                    val ml = luminanceAt(pixels, w, h, x - 1, y)-                    val mr = luminanceAt(pixels, w, h, x + 1, y)-                    val bl = luminanceAt(pixels, w, h, x - 1, y + 1)-                    val bc = luminanceAt(pixels, w, h, x, y + 1)-                    val br = luminanceAt(pixels, w, h, x + 1, y + 1)--                    val gx = (tr + 2 * mr + br) - (tl + 2 * ml + bl)-                    val gy = (bl + 2 * bc + br) - (tl + 2 * tc + tr)-                    val mag = sqrt((gx * gx + gy * gy).toDouble()).toInt().coerceIn(0, 255)-                    val v = 255 - mag--                    val a = (pixels[y * w + x] ushr 24) and 0xFF-                    output[y * w + x] = (a shl 24) or (v shl 16) or (v shl 8) or v-                }-            }-        }-        StylizeMode.Emboss -> {-            val kernel = intArrayOf(-2, -1, 0, -1, 1, 1, 0, 1, 2)-            for (y in 0 until h) {-                for (x in 0 until w) {-                    var sum = 0-                    var ki = 0-                    for (dy in -1..1) {-                        for (dx in -1..1) {-                            sum += luminanceAt(pixels, w, h, x + dx, y + dy) * kernel[ki]-                            ki++-                        }-                    }-                    val v = (sum + 128).coerceIn(0, 255)-                    val a = (pixels[y * w + x] ushr 24) and 0xFF-                    output[y * w + x] = (a shl 24) or (v shl 16) or (v shl 8) or v-                }-            }-        }-    }--    val result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)-    result.setPixels(output, 0, w, 0, 0, w, h)-    return result+    val out = PhotosNative.stylize(pixels, w, h, mode.ordinal)+    return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { setPixels(out, 0, w, 0, 0, w, h) } }
photos/src/main/java/com/vayunmathur/photos/util/PhotosNative.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/PhotosNative.kt b/photos/src/main/java/com/vayunmathur/photos/util/PhotosNative.ktnew file mode 100644index 0000000000..6d9491d4cb--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/util/PhotosNative.kt@@ -0,0 +1,77 @@+package com.vayunmathur.photos.util++/**+ * JNI bridge to the native `photos_fx` Rust library: performance-critical+ * pixel-processing filters (stylize, unsharp mask, liquify, blur, content-aware+ * fill). All pixel arrays are ARGB (0xAARRGGBB), exactly as `Bitmap.getPixels`+ * returns them.+ */+object PhotosNative {+    init {+        System.loadLibrary("photos_fx")+    }++    /** Stylize filter. mode: 0=None, 1=FindEdges (Sobel), 2=Emboss. */+    external fun stylize(pixels: IntArray, w: Int, h: Int, mode: Int): IntArray++    /** Unsharp mask (gaussian blur + per-channel sharpening). */+    external fun unsharp(+        pixels: IntArray,+        w: Int,+        h: Int,+        amount: Float,+        radius: Float,+        threshold: Int,+    ): IntArray++    /**+     * Liquify: displacement field + bilinear resample. Ops are marshalled as+     * [tools] (one LiquifyTool ordinal per op: Push=0, Twirl=1, Pucker=2,+     * Bloat=3, Reconstruct=4) and [params] with 6 floats per op in order+     * [x, y, dx, dy, radius, strength].+     */+    external fun liquify(+        pixels: IntArray,+        w: Int,+        h: Int,+        tools: IntArray,+        params: FloatArray,+    ): IntArray++    /** Masked lens blur. mode: 0=Radial, 1=Linear, 2=Lens. */+    external fun blurParams(+        pixels: IntArray,+        w: Int,+        h: Int,+        mode: Int,+        centerX: Float,+        centerY: Float,+        radius: Float,+        intensity: Float,+        feather: Float,+        angle: Float,+    ): IntArray++    /** Full-image filter blur. mode: 0=Gaussian, 1=Motion, 2=Radial, 3=Spin. */+    external fun filterBlur(+        pixels: IntArray,+        w: Int,+        h: Int,+        mode: Int,+        amount: Float,+        angle: Float,+        centerX: Float,+        centerY: Float,+    ): IntArray++    /** Content-aware fill (exemplar synthesis / diffusion fallback). */+    external fun inpaint(+        pixels: IntArray,+        w: Int,+        h: Int,+        holeMask: FloatArray,+        maskW: Int,+        maskH: Int,+        passes: Int,+    ): IntArray+}
photos/src/main/rust/.gitignore
diff --git a/photos/src/main/rust/.gitignore b/photos/src/main/rust/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/photos/src/main/rust/.gitignore@@ -0,0 +1 @@+/target
photos/src/main/rust/Cargo.lock
diff --git a/photos/src/main/rust/Cargo.lock b/photos/src/main/rust/Cargo.locknew file mode 100644index 0000000000..9f6849eebe--- /dev/null+++ b/photos/src/main/rust/Cargo.lock@@ -0,0 +1,310 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "either"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "photos_fx"+version = "0.1.0"+dependencies = [+ "jni",+ "rayon",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
photos/src/main/rust/Cargo.toml
diff --git a/photos/src/main/rust/Cargo.toml b/photos/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..13da33a013--- /dev/null+++ b/photos/src/main/rust/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "photos_fx"+version = "0.1.0"+edition = "2021"+description = "Native pixel filters (blur/sharpen/liquify/stylize/inpaint) for the photos app, via JNI"+license = "GPL-2.0-only"++[lib]+name = "photos_fx"+crate-type = ["cdylib", "rlib"]++[dependencies]+jni = "0.21"+rayon = "1"++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+strip = true
photos/src/main/rust/rust-toolchain.toml
diff --git a/photos/src/main/rust/rust-toolchain.toml b/photos/src/main/rust/rust-toolchain.tomlnew file mode 100644index 0000000000..fa6ac3abd8--- /dev/null+++ b/photos/src/main/rust/rust-toolchain.toml@@ -0,0 +1,3 @@+[toolchain]+channel = "1.97.0"+targets = ["aarch64-linux-android"]
photos/src/main/rust/src/blur.rs
diff --git a/photos/src/main/rust/src/blur.rs b/photos/src/main/rust/src/blur.rsnew file mode 100644index 0000000000..d006a73d55--- /dev/null+++ b/photos/src/main/rust/src/blur.rs@@ -0,0 +1,295 @@+//! Port of `BlurData.kt`: separable Gaussian blur, motion blur, radial/spin+//! blur, the masked lens-blur composite ([`blur_params`]) and the destructive+//! full-image filter blurs ([`filter_blur`]).++use crate::pixel::*;+use rayon::prelude::*;++/// Matches `generateGaussianKernel` / `unsharpGaussianKernel` (identical math).+pub fn gaussian_kernel(radius: i32) -> Vec<f32> {+    let size = (radius * 2 + 1) as usize;+    let mut kernel = vec![0f32; size];+    let sigma = radius as f32 / 3f32;+    let mut sum = 0f32;+    for i in 0..size {+        let x = (i as i32 - radius) as f32;+        kernel[i] = (-(x * x) / (2f32 * sigma * sigma)).exp();+        sum += kernel[i];+    }+    for i in 0..size {+        kernel[i] /= sum;+    }+    kernel+}++/// Port of `gaussianBlur` (also reused by the unsharp mask, whose blur is+/// byte-identical). Two separable passes (horizontal then vertical).+pub fn gaussian_blur(pixels: &[i32], w: usize, h: usize, radius: i32) -> Vec<i32> {+    if radius <= 0 {+        return pixels.to_vec();+    }+    let kernel = gaussian_kernel(radius);+    let r = radius as isize;+    let mut temp = vec![0i32; w * h];+    // Horizontal pass.+    temp.par_chunks_mut(w).enumerate().for_each(|(y, row)| {+        for x in 0..w {+            let (mut rr, mut gg, mut bb, mut aa) = (0f32, 0f32, 0f32, 0f32);+            for k in -r..=r {+                let sx = clamp_i(x as i32 + k as i32, 0, w as i32 - 1) as usize;+                let px = pixels[y * w + sx];+                let weight = kernel[(k + r) as usize];+                aa += a(px) as f32 * weight;+                rr += r_ch(px) as f32 * weight;+                gg += g(px) as f32 * weight;+                bb += b(px) as f32 * weight;+            }+            row[x] = pack(+                clamp_i(aa as i32, 0, 255),+                clamp_i(rr as i32, 0, 255),+                clamp_i(gg as i32, 0, 255),+                clamp_i(bb as i32, 0, 255),+            );+        }+    });+    let mut output = vec![0i32; w * h];+    // Vertical pass.+    output.par_chunks_mut(w).enumerate().for_each(|(y, row)| {+        for x in 0..w {+            let (mut rr, mut gg, mut bb, mut aa) = (0f32, 0f32, 0f32, 0f32);+            for k in -r..=r {+                let sy = clamp_i(y as i32 + k as i32, 0, h as i32 - 1) as usize;+                let px = temp[sy * w + x];+                let weight = kernel[(k + r) as usize];+                aa += a(px) as f32 * weight;+                rr += r_ch(px) as f32 * weight;+                gg += g(px) as f32 * weight;+                bb += b(px) as f32 * weight;+            }+            row[x] = pack(+                clamp_i(aa as i32, 0, 255),+                clamp_i(rr as i32, 0, 255),+                clamp_i(gg as i32, 0, 255),+                clamp_i(bb as i32, 0, 255),+            );+        }+    });+    output+}++// `r` is taken by the radius param name above; alias the red channel accessor.+#[inline]+fn r_ch(p: i32) -> i32 {+    r(p)+}++/// Port of `motionBlur`.+fn motion_blur(src: &[i32], w: usize, h: usize, length: i32, angle: f32) -> Vec<i32> {+    let mut out = vec![0i32; w * h];+    let rad = (angle as f64).to_radians();+    let dx = rad.cos() as f32;+    let dy = rad.sin() as f32;+    let half = length / 2;+    out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {+        for x in 0..w {+            let (mut aa, mut rr, mut gg, mut bb, mut n) = (0f32, 0f32, 0f32, 0f32, 0f32);+            for k in -half..=half {+                let sx = clamp_i((x as f32 + dx * k as f32) as i32, 0, w as i32 - 1) as usize;+                let sy = clamp_i((y as f32 + dy * k as f32) as i32, 0, h as i32 - 1) as usize;+                let p = src[sy * w + sx];+                aa += a(p) as f32;+                rr += r(p) as f32;+                gg += g(p) as f32;+                bb += b(p) as f32;+                n += 1f32;+            }+            row[x] = pack(+                (aa / n) as i32,+                (rr / n) as i32,+                (gg / n) as i32,+                (bb / n) as i32,+            );+        }+    });+    out+}++/// Port of `radialBlur` (zoom when `spin == false`, rotational when `true`).+fn radial_blur(+    src: &[i32],+    w: usize,+    h: usize,+    amount: f32,+    center_x: f32,+    center_y: f32,+    spin: bool,+) -> Vec<i32> {+    let mut out = vec![0i32; w * h];+    let cx = center_x * w as f32;+    let cy = center_y * h as f32;+    let samples = clamp_i((amount * 0.2f32) as i32, 3, 30);+    let strength = amount / 100f32;+    out.par_chunks_mut(w).enumerate().for_each(|(y, row)| {+        for x in 0..w {+            let (mut aa, mut rr, mut gg, mut bb) = (0f32, 0f32, 0f32, 0f32);+            let odx = x as f32 - cx;+            let ody = y as f32 - cy;+            for s in 0..samples {+                let t = s as f32 / samples as f32;+                let sx: f32;+                let sy: f32;+                if spin {+                    let ang = -strength * 0.3f32 * t;+                    let cos_a = (ang as f64).cos() as f32;+                    let sin_a = (ang as f64).sin() as f32;+                    sx = cx + (odx * cos_a - ody * sin_a);+                    sy = cy + (odx * sin_a + ody * cos_a);+                } else {+                    let scale = 1f32 - strength * t;+                    sx = cx + odx * scale;+                    sy = cy + ody * scale;+                }+                let ix = clamp_i(sx as i32, 0, w as i32 - 1) as usize;+                let iy = clamp_i(sy as i32, 0, h as i32 - 1) as usize;+                let p = src[iy * w + ix];+                aa += a(p) as f32;+                rr += r(p) as f32;+                gg += g(p) as f32;+                bb += b(p) as f32;+            }+            let n = samples as f32;+            row[x] = pack(+                (aa / n) as i32,+                (rr / n) as i32,+                (gg / n) as i32,+                (bb / n) as i32,+            );+        }+    });+    out+}++// BlurMode: 0 = Radial, 1 = Linear, 2 = Lens.+fn generate_mask(+    mode: i32,+    center_x: f32,+    center_y: f32,+    radius: f32,+    feather: f32,+    angle: f32,+    w: usize,+    h: usize,+) -> Vec<f32> {+    let mut mask = vec![0f32; w * h];+    let max_wh = w.max(h) as f32;+    match mode {+        0 => {+            let cx = center_x * w as f32;+            let cy = center_y * h as f32;+            let r = radius * max_wh;+            let feather_dist = feather * max_wh;+            for y in 0..h {+                for x in 0..w {+                    let dx = x as f32 - cx;+                    let dy = y as f32 - cy;+                    let dist = ((dx * dx + dy * dy) as f64).sqrt() as f32;+                    mask[y * w + x] = if dist < r {+                        0f32+                    } else {+                        clamp_f((dist - r) / feather_dist.max(1f32), 0f32, 1f32)+                    };+                }+            }+        }+        1 => {+            let cx = center_x * w as f32;+            let cy = center_y * h as f32;+            let r = radius * max_wh;+            let feather_dist = feather * max_wh;+            let rad = (angle as f64).to_radians();+            let nx = -(rad.sin() as f32);+            let ny = rad.cos() as f32;+            for y in 0..h {+                for x in 0..w {+                    let dist = ((x as f32 - cx) * nx + (y as f32 - cy) * ny).abs();+                    mask[y * w + x] = if dist < r {+                        0f32+                    } else {+                        clamp_f((dist - r) / feather_dist.max(1f32), 0f32, 1f32)+                    };+                }+            }+        }+        _ => {+            // Lens (2)+            let cx = center_x * w as f32;+            let cy = center_y * h as f32;+            let r = radius * max_wh;+            for y in 0..h {+                for x in 0..w {+                    let dx = x as f32 - cx;+                    let dy = y as f32 - cy;+                    let dist = ((dx * dx + dy * dy) as f64).sqrt() as f32;+                    mask[y * w + x] = if dist > r { 1f32 } else { 0f32 };+                }+            }+        }+    }+    mask+}++/// Port of `BlurParams.applyBlurToBitmap` (masked lens/radial/linear blur).+pub fn blur_params(+    pixels: &[i32],+    w: usize,+    h: usize,+    mode: i32,+    center_x: f32,+    center_y: f32,+    radius: f32,+    intensity: f32,+    feather: f32,+    angle: f32,+) -> Vec<i32> {+    let blur_radius = clamp_i((intensity * 0.5f32) as i32, 1, 25);+    let blurred = gaussian_blur(pixels, w, h, blur_radius);+    let mask = generate_mask(mode, center_x, center_y, radius, feather, angle, w, h);+    let mut output = vec![0i32; w * h];+    for i in 0..pixels.len() {+        let m = mask[i];+        let orig_a = a(pixels[i]);+        let orig_r = r(pixels[i]);+        let orig_g = g(pixels[i]);+        let orig_b = b(pixels[i]);+        let blur_a = a(blurred[i]);+        let blur_r = r(blurred[i]);+        let blur_g = g(blurred[i]);+        let blur_b = b(blurred[i]);+        let aa = clamp_i((orig_a as f32 + (blur_a - orig_a) as f32 * m) as i32, 0, 255);+        let rr = clamp_i((orig_r as f32 + (blur_r - orig_r) as f32 * m) as i32, 0, 255);+        let gg = clamp_i((orig_g as f32 + (blur_g - orig_g) as f32 * m) as i32, 0, 255);+        let bb = clamp_i((orig_b as f32 + (blur_b - orig_b) as f32 * m) as i32, 0, 255);+        output[i] = pack(aa, rr, gg, bb);+    }+    output+}++/// Port of `FilterBlur.applyToBitmap`.+/// FilterBlurMode: 0 = Gaussian, 1 = Motion, 2 = Radial, 3 = Spin.+pub fn filter_blur(+    pixels: &[i32],+    w: usize,+    h: usize,+    mode: i32,+    amount: f32,+    angle: f32,+    center_x: f32,+    center_y: f32,+) -> Vec<i32> {+    match mode {+        0 => gaussian_blur(pixels, w, h, clamp_i((amount * 0.5f32) as i32, 1, 60)),+        1 => motion_blur(pixels, w, h, clamp_i(amount as i32, 1, 100), angle),+        2 => radial_blur(pixels, w, h, amount, center_x, center_y, false),+        _ => radial_blur(pixels, w, h, amount, center_x, center_y, true),+    }+}
photos/src/main/rust/src/inpaint.rs
diff --git a/photos/src/main/rust/src/inpaint.rs b/photos/src/main/rust/src/inpaint.rsnew file mode 100644index 0000000000..75598c99e6--- /dev/null+++ b/photos/src/main/rust/src/inpaint.rs@@ -0,0 +1,249 @@+//! Port of `ContentAwareData.kt`: content-aware fill. Small/medium holes use+//! onion-peel exemplar synthesis; very large holes (>20000 px) fall back to+//! Jacobi diffusion.++/// Port of `inpaintBitmap`. `hole_mask` is normalized (>=0.5 => hole) at+/// `mask_w` x `mask_h`; returns the filled ARGB buffer.+pub fn inpaint(+    px_in: &[i32],+    w: usize,+    h: usize,+    hole_mask: &[f32],+    mask_w: usize,+    mask_h: usize,+    passes: i32,+) -> Vec<i32> {+    let mut px = px_in.to_vec();++    let mut hole = vec![false; w * h];+    let mut hole_count: i64 = 0;+    let mut min_x = w as i32;+    let mut min_y = h as i32;+    let mut max_x = -1i32;+    let mut max_y = -1i32;+    for y in 0..h {+        let my = ((y as i64 * mask_h as i64 / h as i64) as i32).clamp(0, mask_h as i32 - 1);+        for x in 0..w {+            let mx = ((x as i64 * mask_w as i64 / w as i64) as i32).clamp(0, mask_w as i32 - 1);+            if hole_mask[(my as usize) * mask_w + mx as usize] >= 0.5f32 {+                hole[y * w + x] = true;+                hole_count += 1;+                if (x as i32) < min_x {+                    min_x = x as i32;+                }+                if (x as i32) > max_x {+                    max_x = x as i32;+                }+                if (y as i32) < min_y {+                    min_y = y as i32;+                }+                if (y as i32) > max_y {+                    max_y = y as i32;+                }+            }+        }+    }+    if max_x < min_x {+        return px;+    }++    if hole_count > 20000 {+        diffuse_fill(&mut px, w, h, &hole, min_x, min_y, max_x, max_y, passes);+    } else {+        exemplar_fill(&mut px, w, h, &mut hole, min_x, min_y, max_x, max_y);+    }+    px+}++#[inline]+fn diff(a: i32, b: i32) -> i32 {+    let dr = (((a as u32) >> 16) & 0xFF) as i32 - (((b as u32) >> 16) & 0xFF) as i32;+    let dg = (((a as u32) >> 8) & 0xFF) as i32 - (((b as u32) >> 8) & 0xFF) as i32;+    let db = ((a as u32) & 0xFF) as i32 - ((b as u32) & 0xFF) as i32;+    dr * dr + dg * dg + db * db+}++/// Onion-peel exemplar synthesis over the hole's bounding box.+#[allow(unused_assignments)] // `remaining` mirrors the Kotlin control flow verbatim.+fn exemplar_fill(+    px: &mut [i32],+    w: usize,+    h: usize,+    hole: &mut [bool],+    min_x: i32,+    min_y: i32,+    max_x: i32,+    max_y: i32,+) {+    let patch_r: i32 = 1;+    let search_r: i32 = 12;+    let idx = |x: i32, y: i32| -> usize { (y * w as i32 + x) as usize };++    let mut remaining = true;+    let mut guard = (max_x - min_x + 1) * (max_y - min_y + 1) + 8;+    while remaining && guard > 0 {+        guard -= 1;+        remaining = false;+        // Collect current boundary hole pixels (adjacent to a known pixel).+        let mut boundary: Vec<i32> = Vec::new();+        for y in min_y..=max_y {+            for x in min_x..=max_x {+                if !hole[idx(x, y)] {+                    continue;+                }+                let nb = (x > 0 && !hole[idx(x - 1, y)])+                    || (x < w as i32 - 1 && !hole[idx(x + 1, y)])+                    || (y > 0 && !hole[idx(x, y - 1)])+                    || (y < h as i32 - 1 && !hole[idx(x, y + 1)]);+                if nb {+                    boundary.push(idx(x, y) as i32);+                }+            }+        }+        if boundary.is_empty() {+            break;+        }+        remaining = true;+        let mut new_colors = vec![0i32; boundary.len()];+        for bi in 0..boundary.len() {+            let p = boundary[bi];+            let pxc = p % w as i32;+            let pyc = p / w as i32;+            let mut best_q: i32 = -1;+            let mut best_score = i32::MAX;+            let sx0 = (pxc - search_r).max(patch_r);+            let sx1 = (pxc + search_r).min(w as i32 - 1 - patch_r);+            let sy0 = (pyc - search_r).max(patch_r);+            let sy1 = (pyc + search_r).min(h as i32 - 1 - patch_r);+            let mut qy = sy0;+            while qy <= sy1 {+                let mut qx = sx0;+                while qx <= sx1 {+                    if !hole[idx(qx, qy)] {+                        let mut score = 0i32;+                        let mut valid = true;+                        let mut oy = -patch_r;+                        'outer: while oy <= patch_r {+                            let mut ox = -patch_r;+                            while ox <= patch_r {+                                let pnx = pxc + ox;+                                let pny = pyc + oy;+                                let qnx = qx + ox;+                                let qny = qy + oy;+                                if pnx >= 0+                                    && pnx < w as i32+                                    && pny >= 0+                                    && pny < h as i32+                                    && !hole[idx(pnx, pny)]+                                {+                                    if hole[idx(qnx, qny)] {+                                        valid = false;+                                        break 'outer;+                                    }+                                    score += diff(px[idx(pnx, pny)], px[idx(qnx, qny)]);+                                }+                                ox += 1;+                            }+                            oy += 1;+                        }+                        if valid && score < best_score {+                            best_score = score;+                            best_q = idx(qx, qy) as i32;+                        }+                    }+                    qx += 1;+                }+                qy += 1;+            }+            new_colors[bi] = if best_q >= 0 {+                px[best_q as usize]+            } else {+                px[p as usize]+            };+        }+        // Commit this peel layer.+        for bi in 0..boundary.len() {+            let p = boundary[bi] as usize;+            px[p] = new_colors[bi];+            hole[p] = false;+        }+    }+    // Safety: anything still marked (shouldn't happen) gets a neutral gray.+    for y in min_y..=max_y {+        for x in min_x..=max_x {+            if hole[idx(x, y)] {+                px[idx(x, y)] = (px[idx(x, y)] & -0x1000000i32) | 0x808080;+            }+        }+    }+}++/// Cheap Jacobi diffusion fallback for very large holes.+fn diffuse_fill(+    px: &mut [i32],+    w: usize,+    _h: usize,+    hole: &[bool],+    min_x: i32,+    min_y: i32,+    max_x: i32,+    max_y: i32,+    passes: i32,+) {+    let bw = (max_x - min_x + 1) as usize;+    let bh = (max_y - min_y + 1) as usize;+    let mut r = vec![0f32; bw * bh];+    let mut g = vec![0f32; bw * bh];+    let mut b = vec![0f32; bw * bh];+    let mut hole_box = vec![false; bw * bh];+    for y in 0..bh {+        for x in 0..bw {+            let gi = (min_y as usize + y) * w + (min_x as usize + x);+            let c = px[gi];+            let bi = y * bw + x;+            r[bi] = (((c as u32) >> 16) & 0xFF) as f32;+            g[bi] = (((c as u32) >> 8) & 0xFF) as f32;+            b[bi] = ((c as u32) & 0xFF) as f32;+            hole_box[bi] = hole[gi];+        }+    }+    let mut nr = r.clone();+    let mut ng = g.clone();+    let mut nb = b.clone();+    let s = |a: &[f32], x: i32, y: i32| -> f32 {+        let cy = y.clamp(0, bh as i32 - 1) as usize;+        let cx = x.clamp(0, bw as i32 - 1) as usize;+        a[cy * bw + cx]+    };+    for _ in 0..passes {+        for y in 0..bh {+            for x in 0..bw {+                let bi = y * bw + x;+                if !hole_box[bi] {+                    continue;+                }+                let xi = x as i32;+                let yi = y as i32;+                nr[bi] = (s(&r, xi - 1, yi) + s(&r, xi + 1, yi) + s(&r, xi, yi - 1) + s(&r, xi, yi + 1)) / 4f32;+                ng[bi] = (s(&g, xi - 1, yi) + s(&g, xi + 1, yi) + s(&g, xi, yi - 1) + s(&g, xi, yi + 1)) / 4f32;+                nb[bi] = (s(&b, xi - 1, yi) + s(&b, xi + 1, yi) + s(&b, xi, yi - 1) + s(&b, xi, yi + 1)) / 4f32;+            }+        }+        r.copy_from_slice(&nr);+        g.copy_from_slice(&ng);+        b.copy_from_slice(&nb);+    }+    for y in 0..bh {+        for x in 0..bw {+            let bi = y * bw + x;+            if !hole_box[bi] {+                continue;+            }+            let gi = (min_y as usize + y) * w + (min_x as usize + x);+            px[gi] = (px[gi] & -0x1000000i32)+                | ((r[bi] as i32).clamp(0, 255) << 16)+                | ((g[bi] as i32).clamp(0, 255) << 8)+                | (b[bi] as i32).clamp(0, 255);+        }+    }+}
photos/src/main/rust/src/lib.rs
diff --git a/photos/src/main/rust/src/lib.rs b/photos/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..900d2efced--- /dev/null+++ b/photos/src/main/rust/src/lib.rs@@ -0,0 +1,459 @@+//! Native pixel filters for the photos app, exposed to Kotlin via JNI.+//!+//! All algorithms are faithful ports of the corresponding Kotlin sources under+//! `photos/src/main/java/com/vayunmathur/photos/data/`. Pure algorithm code+//! lives in normal modules (compiled always, so `cargo test` can exercise it);+//! the JNI shims live in `#[cfg(not(test))] mod jni_bindings`.++pub mod blur;+pub mod inpaint;+pub mod liquify;+pub mod pixel;+pub mod sharpen;+pub mod stylize;++#[cfg(not(test))]+mod jni_bindings {+    use crate::{blur, inpaint, liquify, sharpen, stylize};+    use jni::objects::{JClass, JFloatArray, JIntArray};+    use jni::sys::{jint, jintArray};+    use jni::JNIEnv;++    /// Read a Java `int[]` into a `Vec<i32>`; `None` on error.+    fn read_ints(env: &mut JNIEnv, 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)+    }++    /// Read a Java `float[]` into a `Vec<f32>`; `None` on error.+    fn read_floats(env: &mut JNIEnv, arr: &JFloatArray) -> Option<Vec<f32>> {+        let len = env.get_array_length(arr).ok()? as usize;+        let mut buf = vec![0f32; len];+        if env.get_float_array_region(arr, 0, &mut buf).is_err() {+            return None;+        }+        Some(buf)+    }++    /// Produce a Java `int[]` from `result`, or a null array on error.+    fn write_ints(env: &JNIEnv, result: &[i32]) -> jintArray {+        let out = match env.new_int_array(result.len() as i32) {+            Ok(a) => a,+            Err(_) => return std::ptr::null_mut(),+        };+        if env.set_int_array_region(&out, 0, result).is_err() {+            return std::ptr::null_mut();+        }+        out.into_raw()+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_stylize<'l>(+        mut env: JNIEnv<'l>,+        _class: JClass<'l>,+        pixels: JIntArray<'l>,+        w: jint,+        h: jint,+        mode: jint,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            stylize::stylize(&buf, w as usize, h as usize, mode)+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_unsharp<'l>(+        mut env: JNIEnv<'l>,+        _class: JClass<'l>,+        pixels: JIntArray<'l>,+        w: jint,+        h: jint,+        amount: jni::sys::jfloat,+        radius: jni::sys::jfloat,+        threshold: jint,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            sharpen::unsharp(&buf, w as usize, h as usize, amount, radius, threshold)+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_liquify<'l>(+        mut env: JNIEnv<'l>,+        _class: JClass<'l>,+        pixels: JIntArray<'l>,+        w: jint,+        h: jint,+        tools: JIntArray<'l>,+        params: JFloatArray<'l>,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let tools_v = match read_ints(&mut env, &tools) {+            Some(t) => t,+            None => return null,+        };+        let params_v = match read_floats(&mut env, &params) {+            Some(p) => p,+            None => return null,+        };+        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            liquify::liquify(&buf, w as usize, h as usize, &tools_v, &params_v)+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_blurParams<'l>(+        mut env: JNIEnv<'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,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let result = match 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,+            )+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_filterBlur<'l>(+        mut env: JNIEnv<'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,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            blur::filter_blur(&buf, w as usize, h as usize, mode, amount, angle, center_x, center_y)+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_photos_util_PhotosNative_inpaint<'l>(+        mut env: JNIEnv<'l>,+        _class: JClass<'l>,+        pixels: JIntArray<'l>,+        w: jint,+        h: jint,+        hole_mask: JFloatArray<'l>,+        mask_w: jint,+        mask_h: jint,+        passes: jint,+    ) -> jintArray {+        let null = std::ptr::null_mut();+        if w <= 0 || h <= 0 || mask_w <= 0 || mask_h <= 0 {+            return null;+        }+        let buf = match read_ints(&mut env, &pixels) {+            Some(b) if b.len() == (w as usize) * (h as usize) => b,+            _ => return null,+        };+        let mask = match read_floats(&mut env, &hole_mask) {+            Some(m) if m.len() == (mask_w as usize) * (mask_h as usize) => m,+            _ => return null,+        };+        let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            inpaint::inpaint(+                &buf,+                w as usize,+                h as usize,+                &mask,+                mask_w as usize,+                mask_h as usize,+                passes,+            )+        })) {+            Ok(r) => r,+            Err(_) => return null,+        };+        write_ints(&env, &result)+    }+}++#[cfg(test)]+mod tests {+    use crate::pixel::pack;+    use crate::{blur, inpaint, liquify, sharpen, stylize};++    fn checker(w: usize, h: usize) -> Vec<i32> {+        (0..w * h)+            .map(|i| {+                let x = i % w;+                let y = i / w;+                let v = (((x * 37 + y * 91) % 256) as i32).clamp(0, 255);+                pack(255, v, (255 - v) & 0xFF, (v * 2) & 0xFF)+            })+            .collect()+    }++    #[test]+    fn stylize_none_is_identity() {+        let (w, h) = (16, 12);+        let src = checker(w, h);+        let out = stylize::stylize(&src, w, h, 0);+        assert_eq!(out, src, "mode None must be a bit-exact copy");+    }++    #[test]+    fn stylize_edges_and_emboss_preserve_dims_and_alpha() {+        let (w, h) = (16, 12);+        let src = checker(w, h);+        for mode in [1, 2] {+            let out = stylize::stylize(&src, w, h, mode);+            assert_eq!(out.len(), w * h);+            for i in 0..w * h {+                // Alpha preserved; result is grayscale (R==G==B).+                assert_eq!((out[i] as u32) >> 24, 0xFF, "alpha preserved");+                let r = (out[i] >> 16) & 0xFF;+                let g = (out[i] >> 8) & 0xFF;+                let b = out[i] & 0xFF;+                assert_eq!(r, g);+                assert_eq!(g, b);+            }+        }+    }++    #[test]+    fn stylize_edges_flat_image_is_white() {+        // A flat image has zero gradient => mag 0 => v = 255 (white).+        let (w, h) = (8, 8);+        let src = vec![pack(255, 100, 100, 100); w * h];+        let out = stylize::stylize(&src, w, h, 1);+        for p in out {+            assert_eq!(p, pack(255, 255, 255, 255));+        }+    }++    #[test]+    fn unsharp_amount_zero_is_identity_rgb() {+        let (w, h) = (16, 16);+        let src = checker(w, h);+        // amount 0 => strength 0 => each channel returns orig.+        let out = sharpen::unsharp(&src, w, h, 0.0, 2.0, 0);+        assert_eq!(out, src);+    }++    #[test]+    fn unsharp_preserves_dims_and_alpha() {+        let (w, h) = (20, 14);+        let src = checker(w, h);+        let out = sharpen::unsharp(&src, w, h, 80.0, 3.0, 2);+        assert_eq!(out.len(), w * h);+        for i in 0..w * h {+            assert_eq!((out[i] as u32) >> 24, (src[i] as u32) >> 24, "alpha preserved");+        }+    }++    #[test]+    fn gaussian_blur_uniform_image_near_unchanged() {+        // A flat image blurs back to (nearly) itself. It is not bit-exact+        // because the f32 kernel weights sum to ~1.0 and each channel is+        // truncated via `as i32` โ€” this matches the Kotlin `.toInt()` behaviour+        // exactly, so allow a small (<=2) per-channel truncation drift.+        let (w, h) = (12, 9);+        let src = vec![pack(255, 40, 130, 210); w * h];+        let out = blur::gaussian_blur(&src, w, h, 4);+        for p in out {+            for shift in [24u32, 16, 8, 0] {+                let a = ((p as u32) >> shift) & 0xFF;+                let b = ((src[0] as u32) >> shift) & 0xFF;+                assert!((a as i32 - b as i32).abs() <= 2, "channel drift too large");+            }+        }+    }++    #[test]+    fn gaussian_blur_zero_radius_is_copy() {+        let (w, h) = (10, 10);+        let src = checker(w, h);+        assert_eq!(blur::gaussian_blur(&src, w, h, 0), src);+    }++    #[test]+    fn filter_blur_modes_preserve_dims() {+        let (w, h) = (24, 18);+        let src = checker(w, h);+        for mode in 0..4 {+            let out = blur::filter_blur(&src, w, h, mode, 30.0, 45.0, 0.5, 0.5);+            assert_eq!(out.len(), w * h, "mode {mode} dims");+        }+    }++    #[test]+    fn blur_params_preserves_dims() {+        let (w, h) = (24, 18);+        let src = checker(w, h);+        for mode in 0..3 {+            let out = blur::blur_params(&src, w, h, mode, 0.5, 0.5, 0.3, 10.0, 0.3, 0.0);+            assert_eq!(out.len(), w * h, "mode {mode}");+        }+    }++    #[test]+    fn liquify_empty_ops_is_identity() {+        let (w, h) = (16, 16);+        let src = checker(w, h);+        let out = liquify::liquify(&src, w, h, &[], &[]);+        assert_eq!(out, src);+    }++    #[test]+    fn liquify_push_preserves_dims_and_changes_something() {+        let (w, h) = (32, 32);+        let src = checker(w, h);+        // One Push op (tool 0) at the center with a drag.+        let tools = [0i32];+        let params = [0.5f32, 0.5, 0.1, 0.0, 0.3, 0.8];+        let out = liquify::liquify(&src, w, h, &tools, &params);+        assert_eq!(out.len(), w * h);+        assert_ne!(out, src, "a non-trivial push should displace pixels");+    }++    #[test]+    fn liquify_reconstruct_only_is_identity() {+        // Reconstruct (tool 4) only scales an all-zero displacement field, so+        // the resample samples each pixel at its own location => identity.+        let (w, h) = (24, 24);+        let src = checker(w, h);+        let tools = [4i32];+        let params = [0.5f32, 0.5, 0.0, 0.0, 0.4, 0.7];+        let out = liquify::liquify(&src, w, h, &tools, &params);+        assert_eq!(out, src);+    }++    #[test]+    fn inpaint_no_hole_returns_input() {+        let (w, h) = (16, 16);+        let src = checker(w, h);+        let mask = vec![0f32; w * h];+        let out = inpaint::inpaint(&src, w, h, &mask, w, h, 10);+        assert_eq!(out, src, "empty mask => unchanged");+    }++    #[test]+    fn inpaint_small_hole_exemplar_fills_and_preserves_dims() {+        let (w, h) = (32, 32);+        let mut src = checker(w, h);+        // Mark a small central hole in the source with a sentinel color.+        let sentinel = pack(255, 0, 0, 0);+        let mut mask = vec![0f32; w * h];+        for y in 14..18 {+            for x in 14..18 {+                mask[y * w + x] = 1.0;+                src[y * w + x] = sentinel;+            }+        }+        let out = inpaint::inpaint(&src, w, h, &mask, w, h, 60);+        assert_eq!(out.len(), w * h);+        // Alpha must stay opaque everywhere.+        for p in &out {+            assert_eq!((*p as u32) >> 24, 0xFF);+        }+        // Hole pixels should have been overwritten by exemplar copies.+        let mut changed = 0;+        for y in 14..18 {+            for x in 14..18 {+                if out[y * w + x] != sentinel {+                    changed += 1;+                }+            }+        }+        assert!(changed > 0, "exemplar fill should replace hole pixels");+    }++    #[test]+    fn inpaint_large_hole_uses_diffusion() {+        // >20000 hole pixels forces the diffuse branch; just assert it runs and+        // preserves dims + alpha.+        let (w, h) = (200, 200);+        let src = checker(w, h);+        let mut mask = vec![0f32; w * h];+        for y in 10..190 {+            for x in 10..190 {+                mask[y * w + x] = 1.0;+            }+        }+        let out = inpaint::inpaint(&src, w, h, &mask, w, h, 5);+        assert_eq!(out.len(), w * h);+        for p in &out {+            assert_eq!((*p as u32) >> 24, 0xFF);+        }+    }+}
photos/src/main/rust/src/liquify.rs
diff --git a/photos/src/main/rust/src/liquify.rs b/photos/src/main/rust/src/liquify.rsnew file mode 100644index 0000000000..f6f3184661--- /dev/null+++ b/photos/src/main/rust/src/liquify.rs@@ -0,0 +1,166 @@+//! Port of `LiquifyData.kt`: build a per-pixel displacement field from a list of+//! ops, then bilinear-resample the source through it.+//!+//! Ops are marshalled across JNI as `tools: [i32]` (one LiquifyTool ordinal per+//! op โ€” Push=0, Twirl=1, Pucker=2, Bloat=3, Reconstruct=4) and `params: [f32]`+//! with 6 floats per op: [x, y, dx, dy, radius, strength].++use crate::pixel::*;+use std::f64::consts::PI;++struct Op {+    tool: i32,+    x: f32,+    y: f32,+    dx: f32,+    dy: f32,+    radius: f32,+    strength: f32,+}++/// Port of `lerpChannel`.+#[inline]+fn lerp_channel(p00: i32, p10: i32, p01: i32, p11: i32, tx: f32, ty: f32, shift: u32) -> i32 {+    let c00 = (((p00 as u32) >> shift) & 0xFF) as f32;+    let c10 = (((p10 as u32) >> shift) & 0xFF) as f32;+    let c01 = (((p01 as u32) >> shift) & 0xFF) as f32;+    let c11 = (((p11 as u32) >> shift) & 0xFF) as f32;+    let top = c00 + (c10 - c00) * tx;+    let bottom = c01 + (c11 - c01) * tx;+    let value = top + (bottom - top) * ty;+    clamp_i(value as i32, 0, 255)+}++/// Port of `sampleBilinear`.+#[inline]+fn sample_bilinear(src: &[i32], w: usize, h: usize, fx: f32, fy: f32) -> i32 {+    let cx = clamp_f(fx, 0f32, (w - 1) as f32);+    let cy = clamp_f(fy, 0f32, (h - 1) as f32);+    let x0 = cx as i32;+    let y0 = cy as i32;+    let x1 = (x0 + 1).min(w as i32 - 1);+    let y1 = (y0 + 1).min(h as i32 - 1);+    let tx = cx - x0 as f32;+    let ty = cy - y0 as f32;+    let x0 = x0 as usize;+    let y0 = y0 as usize;+    let x1 = x1 as usize;+    let y1 = y1 as usize;+    let p00 = src[y0 * w + x0];+    let p10 = src[y0 * w + x1];+    let p01 = src[y1 * w + x0];+    let p11 = src[y1 * w + x1];+    let a = lerp_channel(p00, p10, p01, p11, tx, ty, 24);+    let r = lerp_channel(p00, p10, p01, p11, tx, ty, 16);+    let g = lerp_channel(p00, p10, p01, p11, tx, ty, 8);+    let b = lerp_channel(p00, p10, p01, p11, tx, ty, 0);+    pack(a, r, g, b)+}++/// Port of `LiquifyParams.applyToBitmap`.+pub fn liquify(src: &[i32], w: usize, h: usize, tools: &[i32], params: &[f32]) -> Vec<i32> {+    // Reconstruct the ops list (6 floats per op).+    let n = tools.len().min(params.len() / 6);+    let ops: Vec<Op> = (0..n)+        .map(|i| Op {+            tool: tools[i],+            x: params[i * 6],+            y: params[i * 6 + 1],+            dx: params[i * 6 + 2],+            dy: params[i * 6 + 3],+            radius: params[i * 6 + 4],+            strength: params[i * 6 + 5],+        })+        .collect();++    // Identity / degenerate: straight copy (mirrors the Kotlin early return).+    if ops.is_empty() || w == 0 || h == 0 {+        return src.to_vec();+    }++    let mut disp_x = vec![0f32; w * h];+    let mut disp_y = vec![0f32; w * h];+    let max_dim = w.max(h) as f32;++    for op in &ops {+        let cx = op.x * w as f32;+        let cy = op.y * h as f32;+        let radius_px = op.radius * max_dim;+        if radius_px <= 0f32 {+            continue;+        }++        let angle_base = (op.strength as f64 * PI) as f32;+        let drag_x = op.dx * max_dim;+        let drag_y = op.dy * max_dim;++        let min_x = 0.max((cx - radius_px) as i32);+        let max_x = (w as i32 - 1).min((cx + radius_px) as i32);+        let min_y = 0.max((cy - radius_px) as i32);+        let max_y = (h as i32 - 1).min((cy + radius_px) as i32);++        let mut py = min_y;+        while py <= max_y {+            let mut px = min_x;+            while px <= max_x {+                let ox = px as f32 - cx;+                let oy = py as f32 - cy;+                let dist = (ox * ox + oy * oy).sqrt();+                if dist > radius_px {+                    px += 1;+                    continue;+                }+                let raw = clamp_f(1f32 - dist / radius_px, 0f32, 1f32);+                let t = raw * raw * (3f32 - 2f32 * raw); // smoothstep falloff+                let idx = (py * w as i32 + px) as usize;++                match op.tool {+                    0 => {+                        // Push+                        disp_x[idx] += -drag_x * op.strength * t;+                        disp_y[idx] += -drag_y * op.strength * t;+                    }+                    1 => {+                        // Twirl+                        let angle = angle_base * t;+                        let c = angle.cos();+                        let s = angle.sin();+                        let rot_x = ox * c - oy * s;+                        let rot_y = ox * s + oy * c;+                        disp_x[idx] += rot_x - ox;+                        disp_y[idx] += rot_y - oy;+                    }+                    2 => {+                        // Pucker+                        disp_x[idx] += (cx - px as f32) * op.strength * t * 0.5f32;+                        disp_y[idx] += (cy - py as f32) * op.strength * t * 0.5f32;+                    }+                    3 => {+                        // Bloat+                        disp_x[idx] += (px as f32 - cx) * op.strength * t * 0.5f32;+                        disp_y[idx] += (py as f32 - cy) * op.strength * t * 0.5f32;+                    }+                    _ => {+                        // Reconstruct (4)+                        let factor = clamp_f(1f32 - op.strength * t, 0f32, 1f32);+                        disp_x[idx] *= factor;+                        disp_y[idx] *= factor;+                    }+                }+                px += 1;+            }+            py += 1;+        }+    }++    let mut dst = vec![0i32; w * h];+    for y in 0..h {+        for x in 0..w {+            let idx = y * w + x;+            let sx = x as f32 + disp_x[idx];+            let sy = y as f32 + disp_y[idx];+            dst[idx] = sample_bilinear(src, w, h, sx, sy);+        }+    }+    dst+}
photos/src/main/rust/src/pixel.rs
diff --git a/photos/src/main/rust/src/pixel.rs b/photos/src/main/rust/src/pixel.rsnew file mode 100644index 0000000000..848a8950ee--- /dev/null+++ b/photos/src/main/rust/src/pixel.rs@@ -0,0 +1,52 @@+//! ARGB (0xAARRGGBB) pixel helpers. Pixels are stored as `i32` exactly as+//! Android `Bitmap.getPixels` returns them; channel math is done via `u32`+//! casts so shifts never overflow. Extraction masks with `& 0xFF`, which makes+//! Kotlin's `ushr` and `shr` behave identically, so both source conventions map+//! to the same code here.++#[inline]+pub fn a(p: i32) -> i32 {+    (((p as u32) >> 24) & 0xFF) as i32+}+#[inline]+pub fn r(p: i32) -> i32 {+    (((p as u32) >> 16) & 0xFF) as i32+}+#[inline]+pub fn g(p: i32) -> i32 {+    (((p as u32) >> 8) & 0xFF) as i32+}+#[inline]+pub fn b(p: i32) -> i32 {+    ((p as u32) & 0xFF) as i32+}++/// Pack ARGB channels (each already 0..=255) into a single ARGB int.+#[inline]+pub fn pack(a: i32, r: i32, g: i32, b: i32) -> i32 {+    (((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)) as i32+}++/// Kotlin `Int.coerceIn(min, max)`.+#[inline]+pub fn clamp_i(v: i32, lo: i32, hi: i32) -> i32 {+    if v < lo {+        lo+    } else if v > hi {+        hi+    } else {+        v+    }+}++/// Kotlin `Float.coerceIn(min, max)`.+#[inline]+pub fn clamp_f(v: f32, lo: f32, hi: f32) -> f32 {+    if v < lo {+        lo+    } else if v > hi {+        hi+    } else {+        v+    }+}
photos/src/main/rust/src/sharpen.rs
diff --git a/photos/src/main/rust/src/sharpen.rs b/photos/src/main/rust/src/sharpen.rsnew file mode 100644index 0000000000..75d7fd7f36--- /dev/null+++ b/photos/src/main/rust/src/sharpen.rs@@ -0,0 +1,48 @@+//! Port of `SharpenData.kt`: unsharp mask (Gaussian blur + per-channel+//! sharpening). The blur is byte-identical to `BlurData.gaussianBlur`, so it is+//! reused from [`crate::blur::gaussian_blur`].++use crate::blur::gaussian_blur;+use crate::pixel::*;++/// Port of `sharpenChannel`.+#[inline]+fn sharpen_channel(orig: i32, blurred: i32, strength: f32, threshold: i32) -> i32 {+    let diff = orig - blurred;+    if diff.abs() > threshold {+        clamp_i((orig as f32 + strength * diff as f32) as i32, 0, 255)+    } else {+        orig+    }+}++/// Kotlin `Float.roundToInt()` โ€” rounds half toward positive infinity+/// (`floor(x + 0.5)`), unlike Rust's `f32::round` which rounds half away from 0.+#[inline]+fn round_to_int(x: f32) -> i32 {+    (x + 0.5f32).floor() as i32+}++/// Port of `UnsharpMask.applyToBitmap`.+pub fn unsharp(pixels: &[i32], w: usize, h: usize, amount: f32, radius: f32, threshold: i32) -> Vec<i32> {+    let strength = amount / 100f32;+    let int_radius = round_to_int(radius).max(1);+    let blurred = gaussian_blur(pixels, w, h, int_radius);+    let mut output = vec![0i32; w * h];+    for i in 0..pixels.len() {+        let p = pixels[i];+        let bp = blurred[i];+        let av = a(p);+        let orig_r = r(p);+        let orig_g = g(p);+        let orig_b = b(p);+        let blur_r = r(bp);+        let blur_g = g(bp);+        let blur_b = b(bp);+        let rr = sharpen_channel(orig_r, blur_r, strength, threshold);+        let gg = sharpen_channel(orig_g, blur_g, strength, threshold);+        let bb = sharpen_channel(orig_b, blur_b, strength, threshold);+        output[i] = pack(av, rr, gg, bb);+    }+    output+}
photos/src/main/rust/src/stylize.rs
diff --git a/photos/src/main/rust/src/stylize.rs b/photos/src/main/rust/src/stylize.rsnew file mode 100644index 0000000000..c905b528cc--- /dev/null+++ b/photos/src/main/rust/src/stylize.rs@@ -0,0 +1,76 @@+//! Port of `StylizeData.kt`: FindEdges (Sobel on luminance) and Emboss.+//! mode: 0 = None, 1 = FindEdges, 2 = Emboss.++use crate::pixel::*;+use rayon::prelude::*;++/// Port of `luminanceAt` (integer BT.601-ish luma with edge clamping).+#[inline]+fn luminance_at(pixels: &[i32], w: i32, h: i32, x: i32, y: i32) -> i32 {+    let sx = clamp_i(x, 0, w - 1);+    let sy = clamp_i(y, 0, h - 1);+    let p = pixels[(sy * w + sx) as usize];+    let r = r(p);+    let g = g(p);+    let b = b(p);+    (r * 299 + g * 587 + b * 114) / 1000+}++pub fn stylize(pixels: &[i32], w: usize, h: usize, mode: i32) -> Vec<i32> {+    let mut output = vec![0i32; w * h];+    let wi = w as i32;+    let hi = h as i32;+    match mode {+        1 => {+            // FindEdges+            output.par_chunks_mut(w).enumerate().for_each(|(yy, row)| {+                let y = yy as i32;+                for xx in 0..w {+                    let x = xx as i32;+                    let tl = luminance_at(pixels, wi, hi, x - 1, y - 1);+                    let tc = luminance_at(pixels, wi, hi, x, y - 1);+                    let tr = luminance_at(pixels, wi, hi, x + 1, y - 1);+                    let ml = luminance_at(pixels, wi, hi, x - 1, y);+                    let mr = luminance_at(pixels, wi, hi, x + 1, y);+                    let bl = luminance_at(pixels, wi, hi, x - 1, y + 1);+                    let bc = luminance_at(pixels, wi, hi, x, y + 1);+                    let br = luminance_at(pixels, wi, hi, x + 1, y + 1);++                    let gx = (tr + 2 * mr + br) - (tl + 2 * ml + bl);+                    let gy = (bl + 2 * bc + br) - (tl + 2 * tc + tr);+                    let mag = clamp_i(((gx * gx + gy * gy) as f64).sqrt() as i32, 0, 255);+                    let v = 255 - mag;++                    let av = a(pixels[(y * wi + x) as usize]);+                    row[xx] = pack(av, v, v, v);+                }+            });+        }+        2 => {+            // Emboss+            let kernel: [i32; 9] = [-2, -1, 0, -1, 1, 1, 0, 1, 2];+            output.par_chunks_mut(w).enumerate().for_each(|(yy, row)| {+                let y = yy as i32;+                for xx in 0..w {+                    let x = xx as i32;+                    let mut sum = 0i32;+                    let mut ki = 0usize;+                    for dy in -1..=1 {+                        for dx in -1..=1 {+                            sum += luminance_at(pixels, wi, hi, x + dx, y + dy) * kernel[ki];+                            ki += 1;+                        }+                    }+                    let v = clamp_i(sum + 128, 0, 255);+                    let av = a(pixels[(y * wi + x) as usize]);+                    row[xx] = pack(av, v, v, v);+                }+            });+        }+        _ => {+            // None (0) or unknown: identity copy.+            output.copy_from_slice(pixels);+        }+    }+    output+}