aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "image",
crate_name = "akode_utils_image",
)

View File

@@ -0,0 +1,33 @@
[package]
name = "akode-utils-image"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[package.metadata.cargo-shear]
# "image" does not forward png's zlib-rs feature. This direct dependency keeps
# encoded PNG bytes stable when WebSocket dependencies are absent from a build.
ignored = ["png"]
[dependencies]
base64 = { workspace = true }
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
png = { version = "0.18.0", features = ["zlib-rs"] }
akode-utils-cache = { workspace = true }
mime_guess = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs", "rt", "rt-multi-thread", "macros"] }
[dev-dependencies]
divan = { workspace = true }
image = { workspace = true, features = ["jpeg", "png", "gif", "webp"] }
[lib]
doctest = false
[[bench]]
name = "prompt_images"
harness = false

View File

@@ -0,0 +1,178 @@
use std::io::Cursor;
use std::path::Path;
use akode_utils_image::PromptImageMode;
use akode_utils_image::load_for_prompt_bytes;
use divan::Bencher;
use image::DynamicImage;
use image::ImageFormat;
use image::Rgb;
use image::RgbImage;
use image::Rgba;
use image::RgbaImage;
const CACHE_MISS_VARIANT_COUNT: usize = 48;
const SMALL_SCREENSHOT: ImageSize = ImageSize {
width: 1_536,
height: 864,
};
const LARGE_SCREENSHOT: ImageSize = ImageSize {
width: 2_560,
height: 1_440,
};
const LARGE_PHOTO: ImageSize = ImageSize {
width: 3_264,
height: 2_448,
};
#[derive(Clone, Copy)]
struct ImageSize {
width: u32,
height: u32,
}
fn main() {
divan::main();
}
#[divan::bench]
fn small_png_screenshot_fresh_attachment(bencher: Bencher) {
bench_fresh_attachment(
bencher,
"small-screenshot.png",
cache_miss_variants(screenshot_png(SMALL_SCREENSHOT)),
);
}
#[divan::bench]
fn large_png_screenshot_fresh_attachment(bencher: Bencher) {
bench_fresh_attachment(
bencher,
"large-screenshot.png",
cache_miss_variants(screenshot_png(LARGE_SCREENSHOT)),
);
}
#[divan::bench]
fn large_jpeg_photo_fresh_attachment(bencher: Bencher) {
bench_fresh_attachment(
bencher,
"large-photo.jpg",
cache_miss_variants(photo_jpeg(LARGE_PHOTO)),
);
}
#[divan::bench]
fn small_png_screenshot_repeated_attachment(bencher: Bencher) {
bench_repeated_attachment(
bencher,
"small-screenshot.png",
screenshot_png(SMALL_SCREENSHOT),
);
}
fn bench_fresh_attachment(bencher: Bencher, path: &'static str, images: Vec<Vec<u8>>) {
let mut image_index = 0;
bencher
// Divan excludes `with_inputs` from the measured benchmark timing.
.with_inputs(move || {
let image = images[image_index].clone();
image_index = (image_index + 1) % images.len();
image
})
.bench_local_values(move |image| prepare_prompt_data_url(path, image));
}
fn bench_repeated_attachment(bencher: Bencher, path: &'static str, image: Vec<u8>) {
let _ = prepare_prompt_data_url(path, image.clone());
bencher
// Divan excludes the per-iteration input clone from measured timing.
.with_inputs(move || image.clone())
.bench_local_values(move |image| prepare_prompt_data_url(path, image));
}
fn prepare_prompt_data_url(path: &str, image: Vec<u8>) -> String {
#[allow(clippy::expect_used)]
load_for_prompt_bytes(Path::new(path), image, PromptImageMode::ResizeToFit)
.expect("benchmark fixture should load")
.into_data_url()
}
fn cache_miss_variants(image: Vec<u8>) -> Vec<Vec<u8>> {
// The loader caches by content digest. Suffixes keep this workload on the miss path.
(0..CACHE_MISS_VARIANT_COUNT)
.map(|variant| {
let mut image = image.clone();
image.extend_from_slice(&variant.to_le_bytes());
image
})
.collect()
}
/// Encodes a synthetic UI screenshot fixture for prompt image benchmarks.
fn screenshot_png(size: ImageSize) -> Vec<u8> {
let image = RgbaImage::from_fn(size.width, size.height, |x, y| {
let toolbar = y < 52;
let sidebar = x < 240;
let panel_border = x % 320 < 2 || y % 216 < 2;
let text_row = x > 270 && y > 88 && x % 19 < 13 && y % 31 < 3;
if toolbar {
Rgba([33, 40, 52, 255])
} else if sidebar {
let selection = y / 68 % 5 == 2;
if selection {
Rgba([65, 106, 171, 255])
} else {
Rgba([44, 54, 67, 255])
}
} else if panel_border {
Rgba([198, 205, 216, 255])
} else if text_row {
Rgba([72, 82, 96, 255])
} else {
let panel = ((x / 320) + (y / 216) * 3) % 4;
match panel {
0 => Rgba([246, 248, 252, 255]),
1 => Rgba([234, 241, 250, 255]),
2 => Rgba([240, 247, 236, 255]),
_ => Rgba([250, 240, 235, 255]),
}
}
});
encode_fixture(DynamicImage::ImageRgba8(image), ImageFormat::Png)
}
/// Encodes a synthetic textured photo fixture for prompt image benchmarks.
fn photo_jpeg(size: ImageSize) -> Vec<u8> {
let image = RgbImage::from_fn(size.width, size.height, |x, y| {
let x_gradient = x * 255 / size.width;
let y_gradient = y * 255 / size.height;
let texture = ((x.wrapping_mul(17) ^ y.wrapping_mul(31) ^ (x / 7) ^ (y / 11)) & 0xff) as u8;
Rgb([
blend_channel(x_gradient, texture, 3),
blend_channel((x_gradient + y_gradient) / 2, texture, 5),
blend_channel(255 - y_gradient, texture, 4),
])
});
encode_fixture(DynamicImage::ImageRgb8(image), ImageFormat::Jpeg)
}
fn blend_channel(gradient: u32, texture: u8, divisor: u32) -> u8 {
((gradient + u32::from(texture) / divisor) % 256) as u8
}
fn encode_fixture(image: DynamicImage, format: ImageFormat) -> Vec<u8> {
let mut encoded = Cursor::new(Vec::new());
#[allow(clippy::expect_used)]
image
.write_to(&mut encoded, format)
.expect("benchmark fixture should encode");
encoded.into_inner()
}

View File

@@ -0,0 +1,63 @@
use image::ImageError;
use image::ImageFormat;
use std::path::PathBuf;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ImageProcessingError {
#[error("failed to read image at {path}: {source}")]
Read {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("failed to decode image at {path}: {source}")]
Decode {
path: PathBuf,
#[source]
source: image::ImageError,
},
#[error("failed to encode image as {format:?}: {source}")]
Encode {
format: ImageFormat,
#[source]
source: image::ImageError,
},
#[error("unsupported image `{mime}`")]
UnsupportedImageFormat { mime: String },
#[error("invalid image data URL: {reason}")]
InvalidDataUrl { reason: String },
#[error("image {representation} is too large ({size} bytes; max {max} bytes)")]
ImageTooLarge {
representation: &'static str,
size: usize,
max: usize,
},
}
impl ImageProcessingError {
pub fn decode_error(path: &std::path::Path, source: image::ImageError) -> Self {
if matches!(source, ImageError::Decoding(_)) {
return ImageProcessingError::Decode {
path: path.to_path_buf(),
source,
};
}
let mime = mime_guess::from_path(path)
.first()
.map(|mime_guess| mime_guess.essence_str().to_owned())
.unwrap_or_else(|| "unknown".to_string());
ImageProcessingError::UnsupportedImageFormat { mime }
}
pub fn is_invalid_image(&self) -> bool {
matches!(
self,
ImageProcessingError::Decode {
source: ImageError::Decoding(_),
..
}
)
}
}

View File

@@ -0,0 +1,408 @@
use std::io::Cursor;
use super::*;
use image::GenericImageView;
use image::ImageBuffer;
use image::ImageDecoder;
use image::Rgba;
use image::metadata::Orientation;
const TEST_RGB_ICC_PROFILE: &[u8] = b"0123456789abcdefRGB ";
const TEST_CMYK_ICC_PROFILE: &[u8] = b"0123456789abcdefCMYK";
const ROTATE_90_EXIF: &[u8] = &[
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x01, 0x03, 0x00, 0x01, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
fn image_bytes(image: &ImageBuffer<Rgba<u8>, Vec<u8>>, format: ImageFormat) -> Vec<u8> {
let mut encoded = Cursor::new(Vec::new());
DynamicImage::ImageRgba8(image.clone())
.write_to(&mut encoded, format)
.expect("encode image to bytes");
encoded.into_inner()
}
fn image_bytes_with_metadata(
image: &ImageBuffer<Rgba<u8>, Vec<u8>>,
format: ImageFormat,
icc_profile: &[u8],
) -> Vec<u8> {
let mut encoded = Vec::new();
match format {
ImageFormat::Png => {
let mut encoder = PngEncoder::new(&mut encoded);
encoder
.set_icc_profile(icc_profile.to_vec())
.expect("set PNG ICC profile");
encoder
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
.expect("set PNG EXIF metadata");
encoder
.write_image(
image.as_raw(),
image.width(),
image.height(),
ColorType::Rgba8.into(),
)
.expect("encode PNG with metadata");
}
ImageFormat::Jpeg => {
let mut encoder = JpegEncoder::new_with_quality(&mut encoded, 90);
encoder
.set_icc_profile(icc_profile.to_vec())
.expect("set JPEG ICC profile");
encoder
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
.expect("set JPEG EXIF metadata");
encoder
.encode_image(&DynamicImage::ImageRgba8(image.clone()))
.expect("encode JPEG with metadata");
}
ImageFormat::WebP => {
let mut encoder = WebPEncoder::new_lossless(&mut encoded);
encoder
.set_icc_profile(icc_profile.to_vec())
.expect("set WebP ICC profile");
encoder
.set_exif_metadata(ROTATE_90_EXIF.to_vec())
.expect("set WebP EXIF metadata");
encoder
.write_image(
image.as_raw(),
image.width(),
image.height(),
ColorType::Rgba8.into(),
)
.expect("encode WebP with metadata");
}
_ => panic!("unsupported test format"),
}
encoded
}
#[tokio::test(flavor = "multi_thread")]
async fn returns_original_image_when_within_bounds() {
for (format, mime) in [
(ImageFormat::Png, "image/png"),
(ImageFormat::WebP, "image/webp"),
] {
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
let original_bytes = image_bytes(&image, format);
let encoded = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes.clone(),
PromptImageMode::ResizeToFit,
)
.expect("process image");
assert_eq!(encoded.width, 64);
assert_eq!(encoded.height, 32);
assert_eq!(encoded.mime, mime);
assert_eq!(encoded.bytes.as_ref(), original_bytes);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn downscales_large_image() {
for (format, mime) in [
(ImageFormat::Png, "image/png"),
(ImageFormat::WebP, "image/webp"),
] {
let image = ImageBuffer::from_pixel(4096, 2048, Rgba([200u8, 10, 10, 255]));
let original_bytes = image_bytes(&image, format);
let processed = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process image");
assert!(processed.width <= MAX_DIMENSION);
assert!(processed.height <= MAX_DIMENSION);
assert_eq!(processed.mime, mime);
let detected_format =
image::guess_format(&processed.bytes).expect("detect resized output format");
assert_eq!(detected_format, format);
let loaded =
image::load_from_memory(&processed.bytes).expect("read resized bytes back into image");
assert_eq!(loaded.dimensions(), (processed.width, processed.height));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn downscales_tall_image_to_fit_square_bounds() {
let image = ImageBuffer::from_pixel(1024, 4096, Rgba([200u8, 10, 10, 255]));
let original_bytes = image_bytes(&image, ImageFormat::Png);
let processed = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process image");
assert_eq!(processed.width, 512);
assert_eq!(processed.height, MAX_DIMENSION);
assert_eq!(processed.mime, "image/png");
}
#[tokio::test(flavor = "multi_thread")]
async fn resizing_preserves_supported_metadata() {
for format in [ImageFormat::Png, ImageFormat::Jpeg, ImageFormat::WebP] {
let image = ImageBuffer::from_pixel(2050, 2, Rgba([200u8, 10, 10, 255]));
let original_bytes = image_bytes_with_metadata(&image, format, TEST_RGB_ICC_PROFILE);
let processed = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process image");
assert_eq!((processed.width, processed.height), (2048, 2));
let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), format)
.into_decoder()
.expect("create decoder");
assert_eq!(
(
decoder.dimensions(),
decoder.orientation().expect("read orientation"),
decoder.icc_profile().expect("read ICC profile"),
decoder.exif_metadata().expect("read EXIF metadata"),
),
(
(2048, 2),
Orientation::Rotate90,
Some(TEST_RGB_ICC_PROFILE.to_vec()),
Some(ROTATE_90_EXIF.to_vec()),
)
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn resizing_drops_non_rgb_icc_profile() {
let image = ImageBuffer::from_pixel(2050, 2, Rgba([200u8, 10, 10, 255]));
let original_bytes =
image_bytes_with_metadata(&image, ImageFormat::Jpeg, TEST_CMYK_ICC_PROFILE);
let processed = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process image");
let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), ImageFormat::Jpeg)
.into_decoder()
.expect("create decoder");
assert_eq!(
(
decoder.icc_profile().expect("read ICC profile"),
decoder.exif_metadata().expect("read EXIF metadata"),
),
(None, Some(ROTATE_90_EXIF.to_vec()))
);
}
#[tokio::test(flavor = "multi_thread")]
async fn preserves_large_image_in_original_mode() {
let image = ImageBuffer::from_pixel(4096, 2048, Rgba([180u8, 30, 30, 255]));
let original_bytes = image_bytes(&image, ImageFormat::Png);
let processed = load_for_prompt_bytes(
Path::new("in-memory-image"),
original_bytes.clone(),
PromptImageMode::Original,
)
.expect("process image");
assert_eq!(processed.width, 4096);
assert_eq!(processed.height, 2048);
assert_eq!(processed.mime, "image/png");
assert_eq!(processed.bytes.as_ref(), original_bytes);
}
#[tokio::test(flavor = "current_thread")]
async fn data_url_processing_preserves_supported_source_bytes() {
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
let original_bytes = image_bytes(&image, ImageFormat::Png);
let image_url = data_url_from_bytes("image/png", &original_bytes)
.replacen("data:", "DATA:", 1)
.replacen(";base64,", ";BASE64,", 1);
let processed = load_data_url_for_prompt_uncached(&image_url, PromptImageMode::ResizeToFit)
.expect("process data URL image");
assert_eq!(processed.width, 64);
assert_eq!(processed.height, 32);
assert_eq!(processed.mime, "image/png");
assert_eq!(processed.bytes.as_ref(), original_bytes);
}
#[tokio::test(flavor = "multi_thread")]
async fn data_url_processing_converts_gif_to_png() {
let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255]));
let gif_bytes = image_bytes(&image, ImageFormat::Gif);
let image_url = data_url_from_bytes("image/gif", &gif_bytes);
let processed = load_data_url_for_prompt(&image_url, PromptImageMode::ResizeToFit)
.expect("process GIF data URL");
assert_eq!(processed.mime, "image/png");
assert_eq!(
image::guess_format(&processed.bytes).expect("detect processed format"),
ImageFormat::Png
);
}
#[test]
fn data_url_processing_rejects_malformed_input() {
for image_url in [
"image/png;base64,AAAA",
"data:image/png;base64",
"data:image/png,AAAA",
"data:image/png;base64,not base64",
] {
assert!(matches!(
load_data_url_for_prompt(image_url, PromptImageMode::ResizeToFit),
Err(ImageProcessingError::InvalidDataUrl { .. })
));
}
}
/// The shared detail modes apply the policies used by external byte-oriented callers.
#[tokio::test(flavor = "multi_thread")]
async fn detail_modes_apply_expected_budgets() {
for (mode, input_dimensions, expected_dimensions) in [
(PromptImageMode::HIGH_DETAIL, (2048, 2048), (1600, 1600)),
(PromptImageMode::ORIGINAL_DETAIL, (6401, 100), (6000, 94)),
] {
let image = ImageBuffer::from_pixel(
input_dimensions.0,
input_dimensions.1,
Rgba([200u8, 10, 10, 255]),
);
let original_bytes = image_bytes(&image, ImageFormat::Png);
let processed = load_for_prompt_bytes(Path::new("in-memory-image"), original_bytes, mode)
.expect("process image with detail mode");
assert_eq!(
(
processed.source_width,
processed.source_height,
processed.width,
processed.height,
),
(
input_dimensions.0,
input_dimensions.1,
expected_dimensions.0,
expected_dimensions.1,
)
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn fails_cleanly_for_invalid_images() {
let err = load_for_prompt_bytes(
Path::new("in-memory-image"),
b"not an image".to_vec(),
PromptImageMode::ResizeToFit,
)
.expect_err("invalid image should fail");
assert!(matches!(
err,
ImageProcessingError::Decode { .. } | ImageProcessingError::UnsupportedImageFormat { .. }
));
}
#[test]
fn rejects_png_with_readable_dimensions_and_corrupt_pixels() {
let image = ImageBuffer::from_pixel(100, 100, Rgba([10u8, 20, 30, 255]));
let mut bytes = image_bytes(&image, ImageFormat::Png);
let idat = bytes
.windows(4)
.position(|chunk_type| chunk_type == b"IDAT")
.expect("PNG has an IDAT chunk");
// Damage the compressed pixel data while keeping the PNG header intact.
bytes[idat + 4] ^= 0xff;
let dimensions = ImageReader::with_format(Cursor::new(&bytes), ImageFormat::Png)
.into_dimensions()
.expect("dimensions should still be readable");
assert_eq!(dimensions, (100, 100));
let error = load_for_prompt_bytes(
Path::new("corrupt.png"),
bytes,
PromptImageMode::ORIGINAL_DETAIL,
)
.expect_err("even a PNG small enough to pass through must have decodable pixels");
assert!(
matches!(error, ImageProcessingError::Decode { .. }),
"{error}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn reprocesses_updated_file_contents() {
IMAGE_CACHE.clear();
let first_image = ImageBuffer::from_pixel(32, 16, Rgba([20u8, 120, 220, 255]));
let first_bytes = image_bytes(&first_image, ImageFormat::Png);
let first = load_for_prompt_bytes(
Path::new("in-memory-image"),
first_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process first image");
let second_image = ImageBuffer::from_pixel(96, 48, Rgba([50u8, 60, 70, 255]));
let second_bytes = image_bytes(&second_image, ImageFormat::Png);
let second = load_for_prompt_bytes(
Path::new("in-memory-image"),
second_bytes,
PromptImageMode::ResizeToFit,
)
.expect("process updated image");
assert_eq!(first.width, 32);
assert_eq!(first.height, 16);
assert_eq!(second.width, 96);
assert_eq!(second.height, 48);
assert_ne!(second.bytes, first.bytes);
}
#[tokio::test(flavor = "multi_thread")]
async fn bounds_cache_by_encoded_byte_size() {
let cache = ImageCache::new(NonZeroUsize::new(4).expect("non-zero cache capacity"));
let key = |digest_byte| ImageCacheKey {
digest: [digest_byte; 20],
mode: PromptImageMode::Original,
};
let image = |size| EncodedImage {
bytes: vec![0; size].into(),
mime: "image/png".to_string(),
source_width: 1,
source_height: 1,
width: 1,
height: 1,
};
cache_image(&cache, key(1), image(3), /*byte_capacity*/ 5);
cache_image(&cache, key(2), image(3), /*byte_capacity*/ 5);
cache_image(&cache, key(3), image(6), /*byte_capacity*/ 5);
assert!(cache.get(&key(1)).is_none());
assert!(cache.get(&key(2)).is_some());
assert!(cache.get(&key(3)).is_none());
}

View File

@@ -0,0 +1,462 @@
use std::io::Cursor;
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::Arc;
use std::sync::LazyLock;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use akode_utils_cache::BlockingLruCache;
use akode_utils_cache::sha1_digest;
use image::ColorType;
use image::DynamicImage;
use image::GenericImageView;
use image::ImageDecoder;
use image::ImageEncoder;
use image::ImageFormat;
use image::ImageReader;
use image::codecs::jpeg::JpegEncoder;
use image::codecs::png::PngEncoder;
use image::codecs::webp::WebPEncoder;
use image::imageops::FilterType;
const DATA_URL_PREFIX: &str = "data:";
pub const PROMPT_IMAGE_PATCH_SIZE: u32 = 32;
/// Maximum width or height used when resizing images before uploading.
pub const MAX_DIMENSION: u32 = 2048;
/// Maximum accepted byte length for prompt image input representations.
///
/// This is a high sanity guard against pathological inputs, not a protocol
/// requirement or target upload size.
pub const MAX_PROMPT_IMAGE_INPUT_BYTES: usize = 1024 * 1024 * 1024;
const MAX_IMAGE_CACHE_BYTES: usize = 64 * 1024 * 1024;
pub mod error;
pub use crate::error::ImageProcessingError;
#[derive(Debug, Clone)]
pub struct EncodedImage {
pub bytes: Arc<[u8]>,
pub mime: String,
pub source_width: u32,
pub source_height: u32,
pub width: u32,
pub height: u32,
}
impl EncodedImage {
pub fn into_data_url(self) -> String {
data_url_from_bytes(&self.mime, &self.bytes)
}
}
/// Wraps image bytes in a data URL without decoding or validating them.
pub fn data_url_from_bytes(mime: &str, bytes: &[u8]) -> String {
let encoded = BASE64_STANDARD.encode(bytes);
format!("data:{mime};base64,{encoded}")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PromptImageMode {
ResizeToFit,
Original,
ResizeWithLimits(PromptImageResizeLimits),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PromptImageResizeLimits {
pub max_dimension: u32,
pub max_patches: usize,
}
impl PromptImageMode {
/// Resize policy for high-detail prompt images.
pub const HIGH_DETAIL: Self = Self::ResizeWithLimits(PromptImageResizeLimits {
max_dimension: 2048,
max_patches: 2_500,
});
/// Resize policy for original-detail prompt images.
pub const ORIGINAL_DETAIL: Self = Self::ResizeWithLimits(PromptImageResizeLimits {
max_dimension: 6000,
max_patches: 10_000,
});
}
struct ImageMetadata {
icc_profile: Option<Vec<u8>>,
exif: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ImageCacheKey {
digest: [u8; 20],
mode: PromptImageMode,
}
type ImageCache = BlockingLruCache<ImageCacheKey, EncodedImage>;
static IMAGE_CACHE: LazyLock<ImageCache> =
LazyLock::new(|| BlockingLruCache::new(NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN)));
pub fn load_for_prompt_bytes(
path: &Path,
file_bytes: Vec<u8>,
mode: PromptImageMode,
) -> Result<EncodedImage, ImageProcessingError> {
let path_buf = path.to_path_buf();
let key = ImageCacheKey {
digest: sha1_digest(&file_bytes),
mode,
};
if let Some(image) = IMAGE_CACHE.get(&key) {
return Ok(image);
}
let image = load_for_prompt_bytes_uncached(&path_buf, file_bytes, mode)?;
cache_image(&IMAGE_CACHE, key, image.clone(), MAX_IMAGE_CACHE_BYTES);
Ok(image)
}
fn load_for_prompt_bytes_uncached(
path: &Path,
file_bytes: Vec<u8>,
mode: PromptImageMode,
) -> Result<EncodedImage, ImageProcessingError> {
let path_buf = path.to_path_buf();
(move || {
let guessed_format = image::guess_format(&file_bytes)
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
let format = match guessed_format {
ImageFormat::Png => Some(ImageFormat::Png),
ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
ImageFormat::Gif => Some(ImageFormat::Gif),
ImageFormat::WebP => Some(ImageFormat::WebP),
_ => None,
};
let mut decoder = ImageReader::with_format(Cursor::new(&file_bytes), guessed_format)
.into_decoder()
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
// Preserve the metadata most important for rendering prompt images faithfully: the color
// profile and EXIF data, including orientation. Other format-specific metadata is
// intentionally not copied.
let metadata = ImageMetadata {
// Only RGB profiles are safe across every re-encoding path. For example, JPEG decoding
// can convert CMYK/YCCK pixels to RGB while retaining the source profile; copying it
// would mislabel the output. Bytes 16..20 are the ICC data color space signature.
icc_profile: decoder
.icc_profile()
.ok()
.flatten()
.filter(|profile| profile.get(16..20) == Some(b"RGB ")),
exif: decoder.exif_metadata().ok().flatten(),
};
let dynamic = DynamicImage::from_decoder(decoder)
.map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?;
let (width, height) = dynamic.dimensions();
let target_dimensions = match mode {
PromptImageMode::ResizeToFit if width > MAX_DIMENSION || height > MAX_DIMENSION => {
let resized = dynamic.resize(MAX_DIMENSION, MAX_DIMENSION, FilterType::Triangle);
Some((resized.width(), resized.height(), resized))
}
PromptImageMode::ResizeWithLimits(limits) => {
let (target_width, target_height) =
prompt_image_output_dimensions_for_limits(width, height, limits);
if (target_width, target_height) == (width, height) {
None
} else {
let resized =
dynamic.resize_exact(target_width, target_height, FilterType::Triangle);
Some((target_width, target_height, resized))
}
}
PromptImageMode::ResizeToFit | PromptImageMode::Original => None,
};
let encoded = if let Some((prepared_width, prepared_height, resized)) = target_dimensions {
let target_format = format
.filter(|format| can_preserve_source_bytes(*format))
.unwrap_or(ImageFormat::Png);
let (bytes, output_format) = encode_image(&resized, target_format, metadata)?;
let mime = format_to_mime(output_format);
EncodedImage {
bytes: bytes.into(),
mime,
source_width: width,
source_height: height,
width: prepared_width,
height: prepared_height,
}
} else {
if let Some(format) = format.filter(|format| can_preserve_source_bytes(*format)) {
let mime = format_to_mime(format);
EncodedImage {
bytes: file_bytes.into(),
mime,
source_width: width,
source_height: height,
width,
height,
}
} else {
let (bytes, output_format) = encode_image(&dynamic, ImageFormat::Png, metadata)?;
let mime = format_to_mime(output_format);
EncodedImage {
bytes: bytes.into(),
mime,
source_width: width,
source_height: height,
width,
height,
}
}
};
Ok(encoded)
})()
}
fn cache_image(cache: &ImageCache, key: ImageCacheKey, image: EncodedImage, byte_capacity: usize) {
if image.bytes.len() > byte_capacity {
return;
}
cache.with_mut(|cache| {
cache.put(key, image);
let mut cached_bytes = cache
.iter()
.map(|(_, image)| image.bytes.len())
.sum::<usize>();
while cached_bytes > byte_capacity {
let Some((_, evicted)) = cache.pop_lru() else {
break;
};
cached_bytes -= evicted.bytes.len();
}
});
}
pub fn load_data_url_for_prompt(
image_url: &str,
mode: PromptImageMode,
) -> Result<EncodedImage, ImageProcessingError> {
load_data_url_for_prompt_with(image_url, mode, load_for_prompt_bytes)
}
pub fn load_data_url_for_prompt_uncached(
image_url: &str,
mode: PromptImageMode,
) -> Result<EncodedImage, ImageProcessingError> {
load_data_url_for_prompt_with(image_url, mode, load_for_prompt_bytes_uncached)
}
fn load_data_url_for_prompt_with(
image_url: &str,
mode: PromptImageMode,
load: impl FnOnce(&Path, Vec<u8>, PromptImageMode) -> Result<EncodedImage, ImageProcessingError>,
) -> Result<EncodedImage, ImageProcessingError> {
let rest = image_url
.get(..DATA_URL_PREFIX.len())
.filter(|prefix| prefix.eq_ignore_ascii_case(DATA_URL_PREFIX))
.and_then(|_| image_url.get(DATA_URL_PREFIX.len()..))
.ok_or_else(|| ImageProcessingError::InvalidDataUrl {
reason: "missing data: prefix".to_string(),
})?;
let (metadata, encoded) =
rest.split_once(',')
.ok_or_else(|| ImageProcessingError::InvalidDataUrl {
reason: "missing comma separator".to_string(),
})?;
if !metadata
.split(';')
.any(|part| part.eq_ignore_ascii_case("base64"))
{
return Err(ImageProcessingError::InvalidDataUrl {
reason: "only base64 data URLs are supported".to_string(),
});
}
if encoded.len() > MAX_PROMPT_IMAGE_INPUT_BYTES {
return Err(ImageProcessingError::ImageTooLarge {
representation: "base64 payload",
size: encoded.len(),
max: MAX_PROMPT_IMAGE_INPUT_BYTES,
});
}
let file_bytes =
BASE64_STANDARD
.decode(encoded)
.map_err(|source| ImageProcessingError::InvalidDataUrl {
reason: format!("invalid base64 payload: {source}"),
})?;
if file_bytes.len() > MAX_PROMPT_IMAGE_INPUT_BYTES {
return Err(ImageProcessingError::ImageTooLarge {
representation: "decoded input",
size: file_bytes.len(),
max: MAX_PROMPT_IMAGE_INPUT_BYTES,
});
}
load(Path::new("<data-url-image>"), file_bytes, mode)
}
fn prompt_image_output_dimensions_for_limits(
width: u32,
height: u32,
limits: PromptImageResizeLimits,
) -> (u32, u32) {
let width = width.max(1);
let height = height.max(1);
if prompt_image_dimensions_fit(width, height, limits) {
return (width, height);
}
let max_dimension_scale =
(f64::from(limits.max_dimension) / f64::from(width.max(height))).min(1.0);
let width = ((f64::from(width) * max_dimension_scale).round() as u32).max(1);
let height = ((f64::from(height) * max_dimension_scale).round() as u32).max(1);
if prompt_image_dimensions_fit(width, height, limits) {
return (width, height);
}
let width_f64 = f64::from(width);
let height_f64 = f64::from(height);
let patch_size = f64::from(PROMPT_IMAGE_PATCH_SIZE);
let mut scale =
(patch_size * patch_size * limits.max_patches as f64 / width_f64 / height_f64).sqrt();
// Match Responses patch-budget math: shrink by area, then round the scaled
// patch grid down so integer output dimensions remain within the budget.
let scaled_patches_wide = width_f64 * scale / patch_size;
let scaled_patches_high = height_f64 * scale / patch_size;
scale *= (scaled_patches_wide.floor() / scaled_patches_wide)
.min(scaled_patches_high.floor() / scaled_patches_high);
(
((width_f64 * scale).floor() as u32).max(1),
((height_f64 * scale).floor() as u32).max(1),
)
}
fn prompt_image_dimensions_fit(width: u32, height: u32, limits: PromptImageResizeLimits) -> bool {
let patches_wide = width.div_ceil(PROMPT_IMAGE_PATCH_SIZE);
let patches_high = height.div_ceil(PROMPT_IMAGE_PATCH_SIZE);
let patch_count = u64::from(patches_wide) * u64::from(patches_high);
width <= limits.max_dimension
&& height <= limits.max_dimension
&& patch_count <= limits.max_patches as u64
}
fn can_preserve_source_bytes(format: ImageFormat) -> bool {
// Public API docs explicitly call out non-animated GIF support only.
// Preserve byte-for-byte only for formats we can safely pass through.
matches!(
format,
ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP
)
}
fn encode_image(
image: &DynamicImage,
preferred_format: ImageFormat,
metadata: ImageMetadata,
) -> Result<(Vec<u8>, ImageFormat), ImageProcessingError> {
let target_format = match preferred_format {
ImageFormat::Jpeg => ImageFormat::Jpeg,
ImageFormat::WebP => ImageFormat::WebP,
_ => ImageFormat::Png,
};
let mut buffer = Vec::new();
let ImageMetadata { icc_profile, exif } = metadata;
match target_format {
ImageFormat::Png => {
let rgba = image.to_rgba8();
let mut encoder = PngEncoder::new(&mut buffer);
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
encoder
.write_image(
rgba.as_raw(),
image.width(),
image.height(),
ColorType::Rgba8.into(),
)
.map_err(|source| ImageProcessingError::Encode {
format: target_format,
source,
})?;
}
ImageFormat::Jpeg => {
let mut encoder = JpegEncoder::new_with_quality(&mut buffer, 85);
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
encoder
.encode_image(image)
.map_err(|source| ImageProcessingError::Encode {
format: target_format,
source,
})?;
}
ImageFormat::WebP => {
let rgba = image.to_rgba8();
let mut encoder = WebPEncoder::new_lossless(&mut buffer);
apply_image_metadata(&mut encoder, icc_profile, exif, target_format)?;
encoder
.write_image(
rgba.as_raw(),
image.width(),
image.height(),
ColorType::Rgba8.into(),
)
.map_err(|source| ImageProcessingError::Encode {
format: target_format,
source,
})?;
}
_ => unreachable!("unsupported target_format should have been handled earlier"),
}
Ok((buffer, target_format))
}
fn apply_image_metadata(
encoder: &mut impl ImageEncoder,
icc_profile: Option<Vec<u8>>,
exif: Option<Vec<u8>>,
format: ImageFormat,
) -> Result<(), ImageProcessingError> {
if let Some(icc_profile) = icc_profile {
encoder
.set_icc_profile(icc_profile)
.map_err(|source| ImageProcessingError::Encode {
format,
source: image::ImageError::Unsupported(source),
})?;
}
if let Some(exif) = exif {
encoder
.set_exif_metadata(exif)
.map_err(|source| ImageProcessingError::Encode {
format,
source: image::ImageError::Unsupported(source),
})?;
}
Ok(())
}
fn format_to_mime(format: ImageFormat) -> String {
match format {
ImageFormat::Jpeg => "image/jpeg".to_string(),
ImageFormat::Gif => "image/gif".to_string(),
ImageFormat::WebP => "image/webp".to_string(),
_ => "image/png".to_string(),
}
}
#[cfg(test)]
#[path = "image_tests.rs"]
mod tests;