Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

do image compression on rust side

laurenspriem01dfaac7e5fd
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart b/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
index e195c148a4..c7de0fab49 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
@@ -37,6 +37,7 @@ class FaceThumbnailGenerator extends SuperIsolate {
List<FaceBox> faceBoxes,
) async {
try {
+ final useRustForFaceThumbnails = flagService.useRustForFaceThumbnails;
_logger.info(
"Generating face thumbnails for ${faceBoxes.length} face boxes in $imagePath",
);
@@ -47,10 +48,14 @@ class FaceThumbnailGenerator extends SuperIsolate {
{
'imagePath': imagePath,
'faceBoxesList': faceBoxesJson,
- 'useRustForFaceThumbnails': flagService.useRustForFaceThumbnails,
+ 'useRustForFaceThumbnails': useRustForFaceThumbnails,
},
).then((value) => value.cast<Uint8List>());
_logger.info("Generated face thumbnails");
+ if (useRustForFaceThumbnails) {
+ // Rust path already emits compressed JPEG bytes.
+ return faces;
+ }
final compressedFaces =
await compressFaceThumbnails({'listPngBytes': faces});
_logger.fine(
diff --git a/mobile/apps/photos/rust/src/image_processing/image_compression.rs b/mobile/apps/photos/rust/src/image_processing/image_compression.rs
new file mode 100644
index 0000000000..d4eea24613
--- /dev/null
+++ b/mobile/apps/photos/rust/src/image_processing/image_compression.rs
@@ -0,0 +1,93 @@
+use image::{
+ ColorType, ImageEncoder,
+ codecs::{jpeg::JpegEncoder, png::PngEncoder},
+};
+
+use crate::ml::error::{MlError, MlResult};
+
+pub const FACE_THUMBNAIL_JPEG_QUALITY: u8 = 90;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EncodedImageFormat {
+ Jpeg { quality: u8 },
+ Png,
+}
+
+pub fn encode_rgb(
+ rgb_bytes: &[u8],
+ width: u32,
+ height: u32,
+ format: EncodedImageFormat,
+) -> MlResult<Vec<u8>> {
+ if width == 0 || height == 0 {
+ return Err(MlError::Postprocess(
+ "cannot encode image with zero width or height".to_string(),
+ ));
+ }
+
+ let expected_len = width as usize * height as usize * 3;
+ if rgb_bytes.len() != expected_len {
+ return Err(MlError::Postprocess(format!(
+ "invalid RGB buffer length {}, expected {} for {}x{}",
+ rgb_bytes.len(),
+ expected_len,
+ width,
+ height
+ )));
+ }
+
+ let mut encoded = Vec::new();
+ match format {
+ EncodedImageFormat::Jpeg { quality } => {
+ JpegEncoder::new_with_quality(&mut encoded, quality)
+ .write_image(rgb_bytes, width, height, ColorType::Rgb8.into())
+ .map_err(|e| MlError::Postprocess(format!("failed to encode JPEG: {e}")))?;
+ }
+ EncodedImageFormat::Png => {
+ PngEncoder::new(&mut encoded)
+ .write_image(rgb_bytes, width, height, ColorType::Rgb8.into())
+ .map_err(|e| MlError::Postprocess(format!("failed to encode PNG: {e}")))?;
+ }
+ }
+ Ok(encoded)
+}
+
+#[cfg(test)]
+mod tests {
+ use image::ImageFormat;
+
+ use super::{EncodedImageFormat, FACE_THUMBNAIL_JPEG_QUALITY, encode_rgb};
+
+ #[test]
+ fn encode_rgb_jpeg_produces_valid_jpeg() {
+ let rgb = vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255];
+ let encoded = encode_rgb(
+ &rgb,
+ 2,
+ 2,
+ EncodedImageFormat::Jpeg {
+ quality: FACE_THUMBNAIL_JPEG_QUALITY,
+ },
+ )
+ .expect("jpeg encoding should succeed");
+
+ assert!(!encoded.is_empty());
+ image::load_from_memory_with_format(&encoded, ImageFormat::Jpeg)
+ .expect("encoded bytes should be valid JPEG");
+ }
+
+ #[test]
+ fn encode_rgb_rejects_invalid_buffer_size() {
+ let invalid_rgb = vec![0, 1, 2];
+ let result = encode_rgb(
+ &invalid_rgb,
+ 2,
+ 2,
+ EncodedImageFormat::Jpeg {
+ quality: FACE_THUMBNAIL_JPEG_QUALITY,
+ },
+ );
+
+ assert!(result.is_err());
+ }
+}
diff --git a/mobile/apps/photos/rust/src/image_processing/mod.rs b/mobile/apps/photos/rust/src/image_processing/mod.rs
new file mode 100644
index 0000000000..a3f47c6ca9
--- /dev/null
+++ b/mobile/apps/photos/rust/src/image_processing/mod.rs
@@ -0,0 +1 @@
+pub mod image_compression;
diff --git a/mobile/apps/photos/rust/src/lib.rs b/mobile/apps/photos/rust/src/lib.rs
index 997cce5c00..548ebcc676 100644
--- a/mobile/apps/photos/rust/src/lib.rs
+++ b/mobile/apps/photos/rust/src/lib.rs
@@ -1,3 +1,4 @@
pub mod api;
mod frb_generated;
+pub mod image_processing;
pub mod ml;
diff --git a/mobile/apps/photos/rust/src/ml/face/thumbnail.rs b/mobile/apps/photos/rust/src/ml/face/thumbnail.rs
index 00cc9039e2..8db738c64d 100644
--- a/mobile/apps/photos/rust/src/ml/face/thumbnail.rs
+++ b/mobile/apps/photos/rust/src/ml/face/thumbnail.rs
@@ -2,8 +2,10 @@ use fast_image_resize::{
FilterType, IntoImageView, PixelType, ResizeAlg, ResizeOptions, Resizer,
images::{Image as FirImage, ImageRef as FirImageRef},
};
-use image::{ColorType, ImageEncoder, codecs::png::PngEncoder};
+use crate::image_processing::image_compression::{
+ EncodedImageFormat, FACE_THUMBNAIL_JPEG_QUALITY, encode_rgb,
+};
use crate::ml::{
error::{MlError, MlResult},
types::DecodedImage,
@@ -54,8 +56,15 @@ pub fn generate_face_thumbnails(
MlError::InvalidRequest(format!("invalid face box at index {index}: {e}",))
})?;
let resized = resize_crop_with_fir(&source, &crop, &mut resizer)?;
- let png_bytes = encode_png(resized.buffer(), crop.output_width, crop.output_height)?;
- results.push(png_bytes);
+ let compressed = encode_rgb(
+ resized.buffer(),
+ crop.output_width,
+ crop.output_height,
+ EncodedImageFormat::Jpeg {
+ quality: FACE_THUMBNAIL_JPEG_QUALITY,
+ },
+ )?;
+ results.push(compressed);
}
Ok(results)
@@ -169,14 +178,6 @@ fn select_resize_filter(crop: &CropRect) -> FilterType {
}
}
-fn encode_png(rgb_bytes: &[u8], width: u32, height: u32) -> MlResult<Vec<u8>> {
- let mut png_bytes = Vec::new();
- PngEncoder::new(&mut png_bytes)
- .write_image(rgb_bytes, width, height, ColorType::Rgb8.into())
- .map_err(|e| MlError::Postprocess(format!("failed to encode PNG thumbnail: {e}")))?;
- Ok(png_bytes)
-}
-
#[cfg(test)]
mod tests {
use fast_image_resize::FilterType;
@@ -221,7 +222,7 @@ mod tests {
}
#[test]
- fn generate_face_thumbnails_returns_png_per_input_face() {
+ fn generate_face_thumbnails_returns_jpeg_per_input_face() {
let decoded = synthetic_decoded_image(16, 16);
let face_boxes = vec![
FaceBox {
@@ -244,10 +245,10 @@ mod tests {
assert_eq!(thumbnails.len(), 2);
for bytes in thumbnails {
assert!(!bytes.is_empty());
- let decoded_png = image::load_from_memory_with_format(&bytes, ImageFormat::Png)
- .expect("thumbnail bytes should decode as PNG");
- assert!(decoded_png.width() > 0);
- assert!(decoded_png.height() > 0);
+ let decoded_jpeg = image::load_from_memory_with_format(&bytes, ImageFormat::Jpeg)
+ .expect("thumbnail bytes should decode as JPEG");
+ assert!(decoded_jpeg.width() > 0);
+ assert!(decoded_jpeg.height() > 0);
}
}