Skip to content

High performance self-hosted photo and video management solution.

chore(mobile): move the raw photo rotation into the native core (#31362)

Santo Shakil003670d013b7
diff --git a/mobile/android/app/src/main/cpp/native_image.c b/mobile/android/app/src/main/cpp/native_image.c
index 3a4f2f11a4..ce188e06a3 100644
--- a/mobile/android/app/src/main/cpp/native_image.c
+++ b/mobile/android/app/src/main/cpp/native_image.c
@@ -3,111 +3,6 @@
#include <stdint.h>
#include <android/bitmap.h>
-// Cache-friendly block size for the tiled rotation (in pixels). 32x32 uint32 = 4KB, fits L1.
-#define TILE 32
-
-// EXIF orientation values (androidx.exifinterface.media.ExifInterface.ORIENTATION_*).
-enum {
- ORIENTATION_FLIP_HORIZONTAL = 2,
- ORIENTATION_ROTATE_180 = 3,
- ORIENTATION_FLIP_VERTICAL = 4,
- ORIENTATION_TRANSPOSE = 5,
- ORIENTATION_ROTATE_90 = 6,
- ORIENTATION_TRANSVERSE = 7,
- ORIENTATION_ROTATE_270 = 8,
-};
-
-// The orientations that swap width and height. Must stay in sync with affine_for's dim usage.
-static int swaps_dims(int o) {
- return o == ORIENTATION_ROTATE_90 || o == ORIENTATION_ROTATE_270 ||
- o == ORIENTATION_TRANSPOSE || o == ORIENTATION_TRANSVERSE;
-}
-
-// A source pixel (sx, sy) maps to destination index base + sx*stepX + sy*stepY, where dw is the
-// destination width. This affine form covers all 8 EXIF orientations and matches the pixel layout
-// of Bitmap.createBitmap(src, matrixForExifOrientation(o)). int64_t so it stays correct on
-// armeabi-v7a (32-bit long) regardless of how large MAX_RAW_DECODE_PIXELS grows.
-static void affine_for(int o, int sw, int sh, int dw, int64_t *base, int64_t *stepX, int64_t *stepY) {
- switch (o) {
- case ORIENTATION_ROTATE_90: *base = sh - 1; *stepX = dw; *stepY = -1; break;
- case ORIENTATION_ROTATE_270: *base = (int64_t) (sw - 1) * dw; *stepX = -dw; *stepY = 1; break;
- case ORIENTATION_ROTATE_180: *base = (int64_t) (sh - 1) * dw + (sw - 1); *stepX = -1; *stepY = -dw; break;
- case ORIENTATION_FLIP_HORIZONTAL: *base = sw - 1; *stepX = -1; *stepY = dw; break;
- case ORIENTATION_FLIP_VERTICAL: *base = (int64_t) (sh - 1) * dw; *stepX = 1; *stepY = -dw; break;
- case ORIENTATION_TRANSPOSE: *base = 0; *stepX = dw; *stepY = 1; break;
- case ORIENTATION_TRANSVERSE: *base = (int64_t) (sw - 1) * dw + (sh - 1); *stepX = -dw; *stepY = -1; break;
- default: *base = 0; *stepX = 1; *stepY = dw; break;
- }
-}
-
-// Copy each source pixel (whole uint32, so channel order/premult is irrelevant) to its rotated
-// destination, walking TILE x TILE blocks so the scattered writes of a 90/270 transpose stay
-// cache-resident. dst is densely packed (rowBytes == dw*4, no padding), which the affine math relies on.
-static void rotate_tiled(const uint8_t *src, int srcStride, uint32_t *dst,
- int sw, int sh, int64_t base, int64_t stepX, int64_t stepY) {
- for (int ty = 0; ty < sh; ty += TILE) {
- int yEnd = ty + TILE < sh ? ty + TILE : sh;
- for (int tx = 0; tx < sw; tx += TILE) {
- int xEnd = tx + TILE < sw ? tx + TILE : sw;
- for (int sy = ty; sy < yEnd; sy++) {
- const uint32_t *srcRow = (const uint32_t *) (src + (size_t) sy * srcStride);
- int64_t idx = base + (int64_t) sy * stepY + (int64_t) tx * stepX;
- for (int sx = tx; sx < xEnd; sx++) {
- dst[idx] = srcRow[sx];
- idx += stepX;
- }
- }
- }
- }
-}
-
-// Rotates an RGBA_8888 bitmap to the given EXIF orientation into a freshly malloc'd buffer (free it
-// via NativeBuffer.free). Fills outInfo with {width, height, rowBytes} and returns the buffer
-// address, or 0 if the bitmap can't be handled (e.g. a non-8888 format) so the caller can fall back.
-JNIEXPORT jlong JNICALL
-Java_app_alextran_immich_NativeImage_rotate(
- JNIEnv *env, jclass clazz, jobject bitmap, jint orientation, jintArray outInfo) {
- AndroidBitmapInfo info;
- if (AndroidBitmap_getInfo(env, bitmap, &info) != ANDROID_BITMAP_RESULT_SUCCESS) {
- return 0;
- }
- if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
- return 0;
- }
-
- int sw = (int) info.width;
- int sh = (int) info.height;
- int dw = swaps_dims(orientation) ? sh : sw;
- int dh = swaps_dims(orientation) ? sw : sh;
-
- uint32_t *dst = (uint32_t *) malloc((size_t) dw * dh * 4);
- if (dst == NULL) {
- return 0;
- }
-
- void *srcPixels = NULL;
- if (AndroidBitmap_lockPixels(env, bitmap, &srcPixels) != ANDROID_BITMAP_RESULT_SUCCESS) {
- free(dst);
- return 0;
- }
-
- int64_t base, stepX, stepY;
- affine_for(orientation, sw, sh, dw, &base, &stepX, &stepY);
- rotate_tiled((const uint8_t *) srcPixels, (int) info.stride, dst, sw, sh, base, stepX, stepY);
-
- AndroidBitmap_unlockPixels(env, bitmap);
-
- jint dims[3] = {dw, dh, dw * 4};
- (*env)->SetIntArrayRegion(env, outInfo, 0, 3, dims);
- // Keep ownership in C until the buffer is safely handed back: if outInfo was somehow too small,
- // SetIntArrayRegion left a pending exception and Kotlin will never receive (or free) dst.
- if ((*env)->ExceptionCheck(env)) {
- free(dst);
- return 0;
- }
- return (jlong) dst;
-}
-
// Convert an RGBA_1010102 buffer to densely-packed RGBA_8888, matching Skia's
// Bitmap.copy(ARGB_8888) byte-for-byte so it's a drop-in for the intermediate 8888 bitmap.
// Each source pixel is a native (little-endian on every Android ABI) u32 with R in bits 0-9,
diff --git a/mobile/android/app/src/main/kotlin/app/alextran/immich/NativeImage.kt b/mobile/android/app/src/main/kotlin/app/alextran/immich/NativeImage.kt
index 68feaa2d14..73645f1e3d 100644
--- a/mobile/android/app/src/main/kotlin/app/alextran/immich/NativeImage.kt
+++ b/mobile/android/app/src/main/kotlin/app/alextran/immich/NativeImage.kt
@@ -4,8 +4,8 @@ import android.graphics.Bitmap
object NativeImage {
init {
- // rotate() is compiled into the native_buffer shared lib (which already links jnigraphics).
System.loadLibrary("native_buffer")
+ System.loadLibrary("immich_core_ffi")
}
/**
diff --git a/native/crates/immich_core/src/lib.rs b/native/crates/immich_core/src/lib.rs
index 03c55c24e8..e642f99406 100644
--- a/native/crates/immich_core/src/lib.rs
+++ b/native/crates/immich_core/src/lib.rs
@@ -1,3 +1,5 @@
+pub mod rotate;
+
pub fn core_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
diff --git a/native/crates/immich_core/src/rotate.rs b/native/crates/immich_core/src/rotate.rs
new file mode 100644
index 0000000000..4c0d68911f
--- /dev/null
+++ b/native/crates/immich_core/src/rotate.rs
@@ -0,0 +1,78 @@
+#[derive(Clone, Copy)]
+pub enum Orientation {
+ Normal,
+ FlipHorizontal,
+ Rotate180,
+ FlipVertical,
+ Transpose,
+ Rotate90,
+ Transverse,
+ Rotate270,
+}
+
+impl From<i32> for Orientation {
+ fn from(value: i32) -> Self {
+ match value {
+ 2 => Self::FlipHorizontal,
+ 3 => Self::Rotate180,
+ 4 => Self::FlipVertical,
+ 5 => Self::Transpose,
+ 6 => Self::Rotate90,
+ 7 => Self::Transverse,
+ 8 => Self::Rotate270,
+ _ => Self::Normal,
+ }
+ }
+}
+
+impl Orientation {
+ pub fn dimensions(self, w: usize, h: usize) -> (usize, usize) {
+ match self {
+ Self::Transpose | Self::Rotate90 | Self::Transverse | Self::Rotate270 => (h, w),
+ _ => (w, h),
+ }
+ }
+}
+
+/// Copies `h` rows of `w` pixels, `stride` pixels apart in `src`, into `dst` with `orientation`
+/// applied. `dst` is dense: `orientation.dimensions(w, h)` pixels.
+pub fn rotate(
+ src: &[u32],
+ stride: usize,
+ w: usize,
+ h: usize,
+ orientation: Orientation,
+ dst: &mut [u32],
+) {
+ assert!(w <= stride && h.saturating_mul(stride) <= src.len() && w * h <= dst.len());
+ let (dw, _) = orientation.dimensions(w, h);
+ let (w, h, dw) = (w as isize, h as isize, dw as isize);
+ // A source pixel (x, y) lands at base + x * step_x + y * step_y in the dense dw-wide output,
+ // the same layout as Bitmap.createBitmap(src, matrixForExifOrientation(orientation)).
+ let (base, step_x, step_y) = match orientation {
+ Orientation::FlipHorizontal => (w - 1, -1, dw),
+ Orientation::Rotate180 => ((h - 1) * dw + w - 1, -1, -dw),
+ Orientation::FlipVertical => ((h - 1) * dw, 1, -dw),
+ Orientation::Transpose => (0, dw, 1),
+ Orientation::Rotate90 => (h - 1, dw, -1),
+ Orientation::Transverse => ((w - 1) * dw + h - 1, -dw, -1),
+ Orientation::Rotate270 => ((w - 1) * dw, -dw, 1),
+ Orientation::Normal => (0, 1, dw),
+ };
+ let (src, dst) = (src.as_ptr(), dst.as_mut_ptr());
+ // 32x32 u32 tiles are 4KB, so the scattered writes of a 90/270 transpose stay in L1.
+ for ty in (0..h).step_by(32) {
+ for tx in (0..w).step_by(32) {
+ for y in ty..(ty + 32).min(h) {
+ // SAFETY: src holds h rows of stride pixels (asserted above).
+ let row = unsafe { src.add(y as usize * stride) };
+ let mut idx = base + y * step_y + tx * step_x;
+ for x in tx..(tx + 32).min(w) {
+ // SAFETY: the affine mapping stays within the w*h output and x stays within its row.
+ unsafe { dst.add(idx as usize).write(row.add(x as usize).read()) };
+ idx += step_x;
+ }
+ }
+ }
+ }
+}
diff --git a/native/crates/immich_core/tests/rotate.rs b/native/crates/immich_core/tests/rotate.rs
new file mode 100644
index 0000000000..1bcb765ce1
--- /dev/null
+++ b/native/crates/immich_core/tests/rotate.rs
@@ -0,0 +1,32 @@
+use immich_core::rotate::{Orientation, rotate};
+
+#[test]
+fn exif_orientations() {
+ let src = [1u32, 2, 3, 4, 5, 6];
+ let cases = [
+ (1, (3, 2), [1, 2, 3, 4, 5, 6]),
+ (2, (3, 2), [3, 2, 1, 6, 5, 4]),
+ (3, (3, 2), [6, 5, 4, 3, 2, 1]),
+ (4, (3, 2), [4, 5, 6, 1, 2, 3]),
+ (5, (2, 3), [1, 4, 2, 5, 3, 6]),
+ (6, (2, 3), [4, 1, 5, 2, 6, 3]),
+ (7, (2, 3), [6, 3, 5, 2, 4, 1]),
+ (8, (2, 3), [3, 6, 2, 5, 1, 4]),
+ (9, (3, 2), [1, 2, 3, 4, 5, 6]),
+ ];
+ for (exif, size, expected) in cases {
+ let orientation = Orientation::from(exif);
+ let mut dst = [0; 6];
+ rotate(&src, 3, 3, 2, orientation, &mut dst);
+ assert_eq!(orientation.dimensions(3, 2), size);
+ assert_eq!(dst, expected, "orientation {exif}");
+ }
+}
+
+#[test]
+fn padded_rows() {
+ let src = [1u32, 2, 3, 99, 4, 5, 6, 99];
+ let mut dst = [0; 6];
+ rotate(&src, 4, 3, 2, Orientation::Rotate90, &mut dst);
+ assert_eq!(dst, [4, 1, 5, 2, 6, 3]);
+}
diff --git a/native/crates/immich_core_ffi/src/bitmap.rs b/native/crates/immich_core_ffi/src/bitmap.rs
new file mode 100644
index 0000000000..d4f96b3a87
--- /dev/null
+++ b/native/crates/immich_core_ffi/src/bitmap.rs
@@ -0,0 +1,90 @@
+use std::ffi::c_void;
+use std::mem::MaybeUninit;
+use std::{ptr, slice};
+
+use jni::EnvUnowned;
+use jni::errors::ThrowRuntimeExAndDefault;
+use jni::objects::{JIntArray, JObject};
+use jni::sys::{JNIEnv, jlong, jobject};
+
+pub const FORMAT_RGBA_8888: i32 = 1;
+
+pub const RESULT_SUCCESS: i32 = 0;
+
+#[repr(C)]
+pub struct Info {
+ pub width: u32,
+ pub height: u32,
+ pub stride: u32,
+ pub format: i32,
+ pub flags: u32,
+}
+
+#[link(name = "jnigraphics")]
+unsafe extern "C" {
+ #[link_name = "AndroidBitmap_getInfo"]
+ pub fn get_info(env: *mut JNIEnv, bitmap: jobject, info: *mut Info) -> i32;
+ #[link_name = "AndroidBitmap_lockPixels"]
+ pub fn lock_pixels(env: *mut JNIEnv, bitmap: jobject, pixels: *mut *mut c_void) -> i32;
+ #[link_name = "AndroidBitmap_unlockPixels"]
+ pub fn unlock_pixels(env: *mut JNIEnv, bitmap: jobject) -> i32;
+}
+
+/// Runs `f(src, stride, width, height, dst)` over the pixels of a `format` bitmap, writing into a
+/// malloc'd dense buffer of `size(width, height)` pixels that Kotlin frees. Fills `out_info` with
+/// {width, height, rowBytes} of that buffer. Returns 0 when the bitmap can't be handled.
+pub fn transform<'caller>(
+ mut env: EnvUnowned<'caller>,
+ bitmap: JObject<'caller>,
+ out_info: JIntArray<'caller>,
+ format: i32,
+ size: impl Fn(usize, usize) -> (usize, usize),
+ f: impl FnOnce(&[u32], usize, usize, usize, &mut [u32]),
+) -> jlong {
+ let mut dst = ptr::null_mut();
+ let outcome = env.with_env(|env| -> jni::errors::Result<_> {
+ let raw_env = env.get_raw();
+ let mut info = MaybeUninit::uninit();
+ // SAFETY: JNI owns the bitmap reference and info is writable.
+ if unsafe { get_info(raw_env, bitmap.as_raw(), info.as_mut_ptr()) } != RESULT_SUCCESS {
+ return Ok(0);
+ }
+ // SAFETY: get_info initialized info on success.
+ let info = unsafe { info.assume_init() };
+ if info.format != format {
+ return Ok(0);
+ }
+ let (w, h) = (info.width as usize, info.height as usize);
+ let stride = info.stride as usize / 4;
+ let (dw, dh) = size(w, h);
+ // SAFETY: malloc accepts the byte size of this valid Android bitmap.
+ dst = unsafe { libc::malloc(dw * dh * 4) };
+ if dst.is_null() {
+ return Ok(0);
+ }
+ let mut pixels = ptr::null_mut();
+ // SAFETY: the bitmap reference is valid and pixels is writable.
+ if unsafe { lock_pixels(raw_env, bitmap.as_raw(), &mut pixels) } != RESULT_SUCCESS {
+ return Ok(0);
+ }
+ // SAFETY: a locked 4 byte format bitmap holds h aligned rows of stride pixels, and the
+ // malloc above holds dw * dh pixels.
+ let (src, out) = unsafe {
+ (
+ slice::from_raw_parts(pixels.cast::<u32>(), h * stride),
+ slice::from_raw_parts_mut(dst.cast::<u32>(), dw * dh),
+ )
+ };
+ f(src, stride, w, h, out);
+ // SAFETY: balances the successful lock above.
+ unsafe { unlock_pixels(raw_env, bitmap.as_raw()) };
+ out_info.set_region(env, 0, &[dw as i32, dh as i32, (dw * 4) as i32])?;
+ Ok(dst as jlong)
+ });
+ let result = outcome.resolve::<ThrowRuntimeExAndDefault>();
+ if result == 0 {
+ // SAFETY: dst is null or the malloc allocation that has not been returned to Kotlin.
+ unsafe { libc::free(dst) };
+ }
+ result
+}
diff --git a/native/crates/immich_core_ffi/src/lib.rs b/native/crates/immich_core_ffi/src/lib.rs
index 3680db52af..c0e4cd70ff 100644
--- a/native/crates/immich_core_ffi/src/lib.rs
+++ b/native/crates/immich_core_ffi/src/lib.rs
@@ -4,6 +4,11 @@ use std::ptr;
#[cfg(target_os = "android")]
mod android;
+/// cbindgen:ignore
+#[cfg(target_os = "android")]
+mod bitmap;
+#[cfg(target_os = "android")]
+mod rotate;
/// Returns the core version as a C string. Free it with `immich_core_free_string`.
#[unsafe(no_mangle)]
diff --git a/native/crates/immich_core_ffi/src/rotate.rs b/native/crates/immich_core_ffi/src/rotate.rs
new file mode 100644
index 0000000000..9627668622
--- /dev/null
+++ b/native/crates/immich_core_ffi/src/rotate.rs
@@ -0,0 +1,25 @@
+use immich_core::rotate::{Orientation, rotate};
+use jni::EnvUnowned;
+use jni::objects::{JClass, JIntArray, JObject};
+use jni::sys::{jint, jlong};
+
+use super::bitmap::{self, FORMAT_RGBA_8888};
+
+#[unsafe(no_mangle)]
+pub extern "system" fn Java_app_alextran_immich_NativeImage_rotate<'caller>(
+ env: EnvUnowned<'caller>,
+ _class: JClass<'caller>,
+ bitmap: JObject<'caller>,
+ orientation: jint,
+ out_info: JIntArray<'caller>,
+) -> jlong {
+ let orientation: Orientation = orientation.into();
+ bitmap::transform(
+ env,
+ bitmap,
+ out_info,
+ FORMAT_RGBA_8888,
+ |w, h| orientation.dimensions(w, h),
+ |src, stride, w, h, dst| rotate(src, stride, w, h, orientation, dst),
+ )
+}