π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Properly handle exif orientation even for heic using libheic-rs
laurenspriemf4c8a1052224
diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lockindex a5cddeb8ad..922425f324 100644--- a/mobile/apps/photos/rust/Cargo.lock+++ b/mobile/apps/photos/rust/Cargo.lock@@ -988,7 +988,7 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"[[package]]name = "heic-decoder"version = "0.1.0"-source = "git+https://github.com/laurens-pilot/libheic-rs.git?tag=v0.1.1#9aa274d93a5a7c84eb32ae5022afddd57dda3801"+source = "git+https://github.com/laurens-pilot/libheic-rs.git?tag=v0.1.3#ad5f147bf1e7d66906ef1e30ae5ef9691a6caadb"dependencies = ["archmage","enough",@@ -1164,8 +1164,8 @@ dependencies = [[[package]]name = "libheic-rs"-version = "0.1.1"-source = "git+https://github.com/laurens-pilot/libheic-rs.git?tag=v0.1.1#9aa274d93a5a7c84eb32ae5022afddd57dda3801"+version = "0.1.3"+source = "git+https://github.com/laurens-pilot/libheic-rs.git?tag=v0.1.3#ad5f147bf1e7d66906ef1e30ae5ef9691a6caadb"dependencies = ["brotli","flate2",diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.tomlindex de6426b8fb..ce69b7162a 100644--- a/mobile/apps/photos/rust/Cargo.toml+++ b/mobile/apps/photos/rust/Cargo.toml@@ -14,7 +14,7 @@ fast_image_resize = { version = "5.5.0", features = ["image", "rayon"] }image = { version = "0.25.5", default-features = true }imageproc = "0.25.0"kamadak-exif = "0.6.1"-libheic-rs = { git = "https://github.com/laurens-pilot/libheic-rs.git", tag = "v0.1.1", features = ["image-integration"] }+libheic-rs = { git = "https://github.com/laurens-pilot/libheic-rs.git", tag = "v0.1.3", features = ["image-integration"] }nalgebra = "0.33.2"ndarray = "0.16.1"once_cell = "1.20.2"diff --git a/mobile/apps/photos/rust/src/ml/decode.rs b/mobile/apps/photos/rust/src/ml/decode.rsindex 50c99839b7..35883991f9 100644--- a/mobile/apps/photos/rust/src/ml/decode.rs+++ b/mobile/apps/photos/rust/src/ml/decode.rs@@ -1,11 +1,13 @@-use std::{ffi::OsStr, io::Cursor, sync::Once};+use std::{ffi::OsStr, fs::File, io::BufReader, path::Path, sync::Once};use exif::{In, Reader as ExifReader, Tag};-use image::{DynamicImage, ImageReader, RgbImage, hooks::decoding_hook_registered};+use image::{DynamicImage, ImageReader, hooks::decoding_hook_registered};use libheic_rs::{- DecodeGuardrails,- image_integration::register_image_decoder_hooks_with_guardrails,- isobmff::{PrimaryItemTransformProperty, parse_primary_item_transform_properties},+ DecodeGuardrails, exif_orientation_hint_from_path,+ image_integration::{+ apply_exif_orientation_dynamic, register_image_decoder_hooks_with_guardrails,+ },+ path_extension_is_heif,};use crate::ml::{@@ -16,20 +18,8 @@ use crate::ml::{static IMAGE_DECODER_HOOKS_INIT: Once = Once::new();pub fn decode_image_from_path(image_path: &str) -> MlResult<DecodedImage> {- let file_bytes = std::fs::read(image_path)- .map_err(|e| MlError::Decode(format!("failed to read image file '{image_path}': {e}")))?;- let exif_orientation = read_exif_orientation(&file_bytes);- let should_apply_exif_orientation =- should_apply_exif_orientation(&file_bytes, exif_orientation);-- let decoded_rgb = decode_with_image_crate(&file_bytes)?;- let decoded_dynamic = DynamicImage::ImageRgb8(decoded_rgb);- let oriented = if should_apply_exif_orientation {- apply_exif_orientation(decoded_dynamic, exif_orientation)- } else {- decoded_dynamic- }- .to_rgb8();+ let decoded_dynamic = decode_with_image_crate(image_path)?;+ let oriented = orient_decoded_image(decoded_dynamic, image_path).to_rgb8();Ok(DecodedImage {dimensions: Dimensions {@@ -40,14 +30,14 @@ pub fn decode_image_from_path(image_path: &str) -> MlResult<DecodedImage> {})}-fn decode_with_image_crate(file_bytes: &[u8]) -> MlResult<RgbImage> {+fn decode_with_image_crate(image_path: &str) -> MlResult<DynamicImage> {init_image_decoders();- let reader = ImageReader::new(Cursor::new(file_bytes))+ let reader = ImageReader::open(image_path)+ .map_err(|e| MlError::Decode(format!("failed to open image file '{image_path}': {e}")))?.with_guessed_format().map_err(|e| MlError::Decode(format!("failed to guess image format: {e}")))?;- let dynamic = reader.decode()?;- Ok(dynamic.to_rgb8())+ Ok(reader.decode()?)}fn init_image_decoders() {@@ -93,51 +83,49 @@ fn init_image_decoders() {});}-fn read_exif_orientation(image_data: &[u8]) -> u32 {- let mut reader = Cursor::new(image_data);- let exif_reader = ExifReader::new();- let exif = exif_reader.read_from_container(&mut reader);- exif.ok()- .and_then(|data| {- data.get_field(Tag::Orientation, In::PRIMARY)- .and_then(|field| field.value.get_uint(0))- })- .unwrap_or(1)-}--fn should_apply_exif_orientation(image_data: &[u8], exif_orientation: u32) -> bool {- if exif_orientation == 1 {- return false;+fn orient_decoded_image(image: DynamicImage, image_path: &str) -> DynamicImage {+ let path = Path::new(image_path);+ if path_extension_is_heif(path) {+ return apply_heif_exif_orientation_hint(image, path);}- // HEIF decode already applies primary transforms (irot/imir). Applying Exif orientation again- // can double-rotate mirrored/rotated files.- !heif_primary_transforms_include_orientation(image_data)+ apply_standard_exif_orientation(image, image_path)}-fn heif_primary_transforms_include_orientation(image_data: &[u8]) -> bool {- let Ok(primary_transforms) = parse_primary_item_transform_properties(image_data) else {- return false;+fn apply_heif_exif_orientation_hint(image: DynamicImage, image_path: &Path) -> DynamicImage {+ let hint = match exif_orientation_hint_from_path(image_path) {+ Ok(hint) => hint,+ Err(err) => {+ eprintln!(+ "[ml][decode] failed to inspect HEIF EXIF orientation for '{}': {}",+ image_path.display(),+ err+ );+ return image;+ }};- primary_transforms.transforms.iter().any(|transform| {- matches!(- transform,- PrimaryItemTransformProperty::Rotation(rotation)- if rotation.rotation_ccw_degrees % 360 != 0- ) || matches!(transform, PrimaryItemTransformProperty::Mirror(_))- })+ if let Some(orientation) = hint.orientation_to_apply() {+ return apply_exif_orientation_dynamic(image, orientation);+ }++ image}-fn apply_exif_orientation(image: DynamicImage, orientation: u32) -> DynamicImage {- match orientation {- 2 => image.fliph(),- 3 => image.rotate180(),- 4 => image.flipv(),- 5 => image.fliph().rotate270(),- 6 => image.rotate90(),- 7 => image.fliph().rotate90(),- 8 => image.rotate270(),- _ => image,+fn apply_standard_exif_orientation(image: DynamicImage, image_path: &str) -> DynamicImage {+ match read_exif_orientation_from_path(image_path) {+ Some(orientation) => apply_exif_orientation_dynamic(image, orientation),+ None => image,}}++fn read_exif_orientation_from_path(image_path: &str) -> Option<u8> {+ let file = File::open(image_path).ok()?;+ let mut reader = BufReader::new(file);+ let exif = ExifReader::new().read_from_container(&mut reader).ok()?;++ exif.get_field(Tag::Orientation, In::PRIMARY)+ .and_then(|field| field.value.get_uint(0))+ .and_then(|value| u8::try_from(value).ok())+ .filter(|value| (1..=8).contains(value))+}