Skip to main content

merry_tools/read/
image.rs

1//! Local raster image decoding, validation, SVG safeguards, and automatic
2//! downscaling shared across `read_file` image, PDF, and notebook paths.
3
4use std::{borrow::Cow, fs, io::Cursor, path::Path};
5
6use image::{
7    AnimationDecoder, DynamicImage, GenericImageView, ImageFormat, ImageReader,
8    imageops::FilterType,
9};
10use merry_runtime::{
11    MAX_USER_IMAGE_DIMENSION, MAX_USER_IMAGE_PIXELS, MAX_USER_IMAGE_PNG_BYTES,
12    ToolExecutionOutcome, UserImageInput,
13};
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    READ_FILE_TOOL,
18    errors::{
19        BlockingToolError, DomainError, ERROR_FILE_TOO_LARGE, ERROR_IMAGE_TOO_LARGE,
20        ERROR_INVALID_IMAGE,
21    },
22    file::read_bounded,
23    path::ValidatedToolPath,
24};
25
26const PNG_SIGNATURE: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
27
28/// Maximum encoded source file size accepted for image reads (20 MiB).
29pub(crate) const MAX_IMAGE_SOURCE_BYTES: usize = 20 * 1024 * 1024;
30/// Maximum decoded pixel count accepted before refusing to decode (64 Mpx).
31const MAX_IMAGE_DECODE_PIXELS: u64 = 64_000_000;
32/// Maximum width or height for images embedded by `read_file` after downscaling.
33pub(crate) const MAX_EMBEDDED_IMAGE_DIMENSION: u32 = 2_000;
34/// Maximum total pixel area (1920x1080) for images embedded by `read_file` after downscaling.
35pub(crate) const MAX_EMBEDDED_IMAGE_PIXELS: u64 = 2_073_600;
36/// Maximum raw PNG byte size for images embedded by `read_file` (3 MiB raw ~= 4 MiB base64).
37pub(super) const MAX_EMBEDDED_IMAGE_PNG_BYTES: usize = 3 * 1024 * 1024;
38/// Floor side length when shrinking oversized PNGs to fit the byte budget.
39const MIN_EMBEDDED_IMAGE_DIMENSION: u32 = 128;
40
41/// Raster image formats supported by `read_file`.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(super) enum SupportedRasterFormat {
44    Png,
45    Jpeg,
46    Gif,
47    WebP,
48}
49
50impl SupportedRasterFormat {
51    fn as_str(self) -> &'static str {
52        match self {
53            Self::Png => "png",
54            Self::Jpeg => "jpeg",
55            Self::Gif => "gif",
56            Self::WebP => "webp",
57        }
58    }
59
60    fn image_format(self) -> ImageFormat {
61        match self {
62            Self::Png => ImageFormat::Png,
63            Self::Jpeg => ImageFormat::Jpeg,
64            Self::Gif => ImageFormat::Gif,
65            Self::WebP => ImageFormat::WebP,
66        }
67    }
68}
69
70impl TryFrom<ImageFormat> for SupportedRasterFormat {
71    type Error = ();
72
73    fn try_from(value: ImageFormat) -> Result<Self, Self::Error> {
74        match value {
75            ImageFormat::Png => Ok(Self::Png),
76            ImageFormat::Jpeg => Ok(Self::Jpeg),
77            ImageFormat::Gif => Ok(Self::Gif),
78            ImageFormat::WebP => Ok(Self::WebP),
79            _ => Err(()),
80        }
81    }
82}
83
84/// Structured success envelope produced by `read_file` when reading an image.
85///
86/// The normalized PNG bytes themselves are attached to the tool outcome rather
87/// than embedded in this JSON envelope, keeping stored artifacts compact and
88/// avoiding duplicate base64 payloads.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct WorkspaceReadImageSuccess {
91    /// Always `true` for a successful image read.
92    pub ok: bool,
93    /// Stable tool name (`read_file`).
94    pub tool: String,
95    /// Content kind discriminant (`image`).
96    pub kind: String,
97    /// Normalized display path (workspace-relative when inside the workspace root).
98    pub path: String,
99    /// Detected source format (`png`, `jpeg`, `gif`, or `webp`).
100    pub source_format: String,
101    /// Original decoded image width in pixels.
102    pub source_width: u32,
103    /// Original decoded image height in pixels.
104    pub source_height: u32,
105    /// Attached image width in pixels (equal to `source_width` when not resized).
106    pub width: u32,
107    /// Attached image height in pixels (equal to `source_height` when not resized).
108    pub height: u32,
109    /// Whether the image was downscaled to fit vision dimension or byte budgets.
110    pub resized: bool,
111    /// Byte length of the source file on disk.
112    pub source_bytes: usize,
113    /// Byte length of the normalized PNG attached to the model result.
114    pub png_bytes: usize,
115}
116
117impl WorkspaceReadImageSuccess {
118    fn model_text(&self) -> String {
119        if self.resized {
120            format!(
121                "{}: {} image ({}x{} resized to {}x{}, {} bytes source, {} bytes PNG attached)",
122                self.path,
123                self.source_format,
124                self.source_width,
125                self.source_height,
126                self.width,
127                self.height,
128                self.source_bytes,
129                self.png_bytes
130            )
131        } else {
132            format!(
133                "{}: {} image ({}x{}, {} bytes source, {} bytes PNG attached)",
134                self.path,
135                self.source_format,
136                self.width,
137                self.height,
138                self.source_bytes,
139                self.png_bytes
140            )
141        }
142    }
143}
144
145/// Returns the supported raster image format when `sniff_bytes` should be handled
146/// as a visual image rather than UTF-8 text.
147///
148/// `.svg` files always stay on the text path even if an Adobe Illustrator SVG
149/// begins with a PNG thumbnail prefix.
150pub(super) fn detect_raster_image_format(
151    path: &Path,
152    sniff_bytes: &[u8],
153) -> Option<SupportedRasterFormat> {
154    if super::has_extension(path, "svg") || sniff_bytes.is_empty() {
155        return None;
156    }
157    SupportedRasterFormat::try_from(image::guess_format(sniff_bytes).ok()?).ok()
158}
159
160/// Extracts UTF-8 SVG markup from an `.svg` file that begins with an Adobe
161/// Illustrator PNG thumbnail prefix.
162pub(super) fn extract_svg_after_png_prefix(bytes: &[u8]) -> Option<String> {
163    if !bytes.starts_with(PNG_SIGNATURE) {
164        return None;
165    }
166    let suffix = skip_complete_png_chunks(bytes);
167    if let Some(xml) = find_ascii_case_insensitive(suffix, b"<?xml") {
168        let text = std::str::from_utf8(suffix.get(xml..)?).ok()?;
169        if text.contains("<svg") || text.contains("<SVG") {
170            return Some(text.to_owned());
171        }
172    }
173    let svg = find_ascii_case_insensitive(suffix, b"<svg")?;
174    std::str::from_utf8(suffix.get(svg..)?)
175        .ok()
176        .map(str::to_owned)
177}
178
179fn skip_complete_png_chunks(bytes: &[u8]) -> &[u8] {
180    let mut i = PNG_SIGNATURE.len();
181    while let Some(header) = bytes.get(i..i + 8) {
182        let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
183        let is_iend = header[4..8] == *b"IEND";
184        let Some(chunk_end) = (i + 8).checked_add(len).and_then(|n| n.checked_add(4)) else {
185            break;
186        };
187        if chunk_end > bytes.len() {
188            break;
189        }
190        i = chunk_end;
191        if is_iend {
192            break;
193        }
194    }
195    bytes.get(i..).unwrap_or(&[])
196}
197
198fn find_ascii_case_insensitive(haystack: &[u8], needle: &[u8]) -> Option<usize> {
199    if needle.is_empty() || haystack.len() < needle.len() {
200        return None;
201    }
202    haystack
203        .windows(needle.len())
204        .position(|window| window.eq_ignore_ascii_case(needle))
205}
206
207pub(super) fn read_resolved_image(
208    relative: &ValidatedToolPath,
209    file: &mut fs::File,
210    is_cancelled: &dyn Fn() -> bool,
211) -> Result<ToolExecutionOutcome, BlockingToolError> {
212    if is_cancelled() {
213        return Err(BlockingToolError::Cancelled);
214    }
215
216    let bytes =
217        read_bounded(file, MAX_IMAGE_SOURCE_BYTES, is_cancelled).map_err(|error| match error {
218            BlockingToolError::Domain(domain) if domain.code == ERROR_FILE_TOO_LARGE => {
219                BlockingToolError::Domain(DomainError::new(
220                    ERROR_IMAGE_TOO_LARGE,
221                    "image file exceeds the 20 MiB source limit",
222                ))
223            }
224            other => other,
225        })?;
226    let source_bytes = bytes.len();
227
228    let normalized = normalize_encoded_image(
229        bytes,
230        MAX_EMBEDDED_IMAGE_PNG_BYTES.min(MAX_USER_IMAGE_PNG_BYTES),
231        MAX_EMBEDDED_IMAGE_DIMENSION.min(MAX_USER_IMAGE_DIMENSION),
232        MAX_EMBEDDED_IMAGE_PIXELS.min(MAX_USER_IMAGE_PIXELS),
233        is_cancelled,
234    )?;
235
236    let png_byte_len = normalized.png_bytes.len();
237    let image_input = UserImageInput::png(
238        &relative.display,
239        normalized.png_bytes,
240        normalized.width,
241        normalized.height,
242    )
243    .map_err(|error| DomainError::new(ERROR_INVALID_IMAGE, error.to_string()))?;
244
245    if is_cancelled() {
246        return Err(BlockingToolError::Cancelled);
247    }
248
249    let resized = normalized.width != normalized.source_width
250        || normalized.height != normalized.source_height;
251    let payload = WorkspaceReadImageSuccess {
252        ok: true,
253        tool: READ_FILE_TOOL.to_owned(),
254        kind: "image".to_owned(),
255        path: relative.display.clone(),
256        source_format: normalized.source_format.to_owned(),
257        source_width: normalized.source_width,
258        source_height: normalized.source_height,
259        width: normalized.width,
260        height: normalized.height,
261        resized,
262        source_bytes,
263        png_bytes: png_byte_len,
264    };
265
266    Ok(ToolExecutionOutcome::succeeded_json(
267        serde_json::to_string(&payload).expect("read_file image envelope serializes"),
268    )
269    .with_model_text(payload.model_text())
270    .with_image(image_input))
271}
272
273pub(super) struct NormalizedImage {
274    pub(super) source_format: &'static str,
275    pub(super) source_width: u32,
276    pub(super) source_height: u32,
277    pub(super) width: u32,
278    pub(super) height: u32,
279    pub(super) png_bytes: Vec<u8>,
280}
281
282/// Validates, decodes, and normalizes encoded PNG/JPEG/GIF/WebP bytes into a
283/// structurally complete PNG within the supplied dimension, pixel, and byte budgets.
284pub(super) fn normalize_encoded_image(
285    bytes: Vec<u8>,
286    max_bytes: usize,
287    max_side_px: u32,
288    max_pixels: u64,
289    is_cancelled: &dyn Fn() -> bool,
290) -> Result<NormalizedImage, BlockingToolError> {
291    if is_cancelled() {
292        return Err(BlockingToolError::Cancelled);
293    }
294    if bytes.len() > MAX_IMAGE_SOURCE_BYTES {
295        return Err(DomainError::new(
296            ERROR_IMAGE_TOO_LARGE,
297            "image exceeds the 20 MiB source limit",
298        )
299        .into());
300    }
301
302    let format = image::guess_format(&bytes)
303        .ok()
304        .and_then(|fmt| SupportedRasterFormat::try_from(fmt).ok())
305        .ok_or_else(|| {
306            DomainError::new(
307                ERROR_INVALID_IMAGE,
308                "image header could not be recognized as PNG, JPEG, GIF, or WebP",
309            )
310        })?;
311    let source_format = format.as_str();
312
313    let (header_width, header_height) =
314        ImageReader::with_format(Cursor::new(&bytes), format.image_format())
315            .into_dimensions()
316            .map_err(|error| {
317                DomainError::new(
318                    ERROR_INVALID_IMAGE,
319                    format!("could not read {source_format} image dimensions: {error}"),
320                )
321            })?;
322    validate_decode_dimensions(header_width, header_height)?;
323
324    if is_cancelled() {
325        return Err(BlockingToolError::Cancelled);
326    }
327
328    let decoded = decode_image(&bytes, format)?;
329    let (source_width, source_height) = decoded.dimensions();
330    validate_decode_dimensions(source_width, source_height)?;
331
332    let (png_bytes, width, height) = encode_under_budget(
333        &decoded,
334        Some((bytes, format)),
335        max_bytes,
336        max_side_px,
337        max_pixels,
338        is_cancelled,
339    )?;
340
341    Ok(NormalizedImage {
342        source_format,
343        source_width,
344        source_height,
345        width,
346        height,
347        png_bytes,
348    })
349}
350
351/// Encodes an in-memory `DynamicImage` into a structurally valid PNG within
352/// `max_bytes`, `max_side_px`, and `max_pixels`, downscaling proportionally if needed.
353#[cfg(feature = "pdf")]
354pub(super) fn encode_dynamic_image_under_budget(
355    decoded: &DynamicImage,
356    max_bytes: usize,
357    max_side_px: u32,
358    max_pixels: u64,
359    is_cancelled: &dyn Fn() -> bool,
360) -> Result<(Vec<u8>, u32, u32), BlockingToolError> {
361    encode_under_budget(
362        decoded,
363        None,
364        max_bytes,
365        max_side_px,
366        max_pixels,
367        is_cancelled,
368    )
369}
370
371fn validate_decode_dimensions(width: u32, height: u32) -> Result<(), DomainError> {
372    if width == 0 || height == 0 {
373        return Err(DomainError::new(
374            ERROR_INVALID_IMAGE,
375            "image dimensions must be greater than zero",
376        ));
377    }
378    let pixels = u64::from(width)
379        .checked_mul(u64::from(height))
380        .ok_or_else(|| DomainError::new(ERROR_IMAGE_TOO_LARGE, "image pixel count overflowed"))?;
381    if pixels > MAX_IMAGE_DECODE_PIXELS {
382        return Err(DomainError::new(
383            ERROR_IMAGE_TOO_LARGE,
384            format!(
385                "image pixel count ({width}x{height}) exceeds the {MAX_IMAGE_DECODE_PIXELS} pixel decode limit"
386            ),
387        ));
388    }
389    Ok(())
390}
391
392fn decode_image(bytes: &[u8], format: SupportedRasterFormat) -> Result<DynamicImage, DomainError> {
393    if format == SupportedRasterFormat::Gif {
394        let decoder = image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).map_err(|error| {
395            DomainError::new(
396                ERROR_INVALID_IMAGE,
397                format!("could not decode gif image: {error}"),
398            )
399        })?;
400        let frame = decoder
401            .into_frames()
402            .next()
403            .transpose()
404            .map_err(|error| {
405                DomainError::new(
406                    ERROR_INVALID_IMAGE,
407                    format!("could not decode gif frame: {error}"),
408                )
409            })?
410            .ok_or_else(|| DomainError::new(ERROR_INVALID_IMAGE, "gif image contains no frames"))?;
411        Ok(DynamicImage::ImageRgba8(frame.into_buffer()))
412    } else {
413        let label = format.as_str();
414        image::load_from_memory_with_format(bytes, format.image_format()).map_err(|error| {
415            DomainError::new(
416                ERROR_INVALID_IMAGE,
417                format!("could not decode {label} image: {error}"),
418            )
419        })
420    }
421}
422
423fn encode_under_budget(
424    decoded: &DynamicImage,
425    original: Option<(Vec<u8>, SupportedRasterFormat)>,
426    max_bytes: usize,
427    max_side_px: u32,
428    max_pixels: u64,
429    is_cancelled: &dyn Fn() -> bool,
430) -> Result<(Vec<u8>, u32, u32), BlockingToolError> {
431    let (orig_w, orig_h) = decoded.dimensions();
432    let exceeds_caps = orig_w > max_side_px
433        || orig_h > max_side_px
434        || u64::from(orig_w) * u64::from(orig_h) > max_pixels;
435
436    if let Some((original_bytes, SupportedRasterFormat::Png)) = original
437        && !exceeds_caps
438        && original_bytes.len() <= max_bytes
439        && png_has_complete_chunks(&original_bytes)
440    {
441        return Ok((original_bytes, orig_w, orig_h));
442    }
443
444    let original_max_side = orig_w.max(orig_h);
445    let mut max_side = max_side_px.min(original_max_side);
446    if u64::from(orig_w) * u64::from(orig_h) > max_pixels {
447        max_side = max_side.min(area_capped_side(
448            original_max_side,
449            orig_w.min(orig_h),
450            max_pixels,
451        ));
452    }
453
454    loop {
455        if is_cancelled() {
456            return Err(BlockingToolError::Cancelled);
457        }
458
459        let scaled: Cow<'_, DynamicImage> = if max_side < original_max_side {
460            Cow::Owned(decoded.resize(max_side, max_side, FilterType::Lanczos3))
461        } else {
462            Cow::Borrowed(decoded)
463        };
464        let (w, h) = scaled.dimensions();
465
466        let mut buf = Vec::new();
467        scaled
468            .write_to(&mut Cursor::new(&mut buf), ImageFormat::Png)
469            .map_err(|error| {
470                DomainError::new(
471                    ERROR_INVALID_IMAGE,
472                    format!("could not encode normalized PNG image: {error}"),
473                )
474            })?;
475
476        if buf.len() <= max_bytes {
477            return Ok((buf, w, h));
478        }
479
480        if max_side <= MIN_EMBEDDED_IMAGE_DIMENSION {
481            return Err(DomainError::new(
482                ERROR_IMAGE_TOO_LARGE,
483                format!(
484                    "normalized PNG still exceeds the {max_bytes}-byte limit after downscaling to {w}x{h}"
485                ),
486            )
487            .into());
488        }
489        max_side = (max_side * 3 / 4).max(MIN_EMBEDDED_IMAGE_DIMENSION);
490    }
491}
492
493/// Largest target long side whose aspect-preserving resize area stays within `max_pixels`.
494fn area_capped_side(long: u32, short: u32, max_pixels: u64) -> u32 {
495    let scale = (max_pixels as f64 / (u64::from(long) * u64::from(short)) as f64).sqrt();
496    let mut side = ((f64::from(long) * scale).floor() as u32).clamp(1, long);
497    while side > 1 && predicted_resize_area(long, short, side) > max_pixels {
498        side -= 1;
499    }
500    side
501}
502
503fn predicted_resize_area(long: u32, short: u32, side: u32) -> u64 {
504    let ratio = f64::from(side) / f64::from(long);
505    let scaled_long = (f64::from(long) * ratio).round().max(1.0) as u64;
506    let scaled_short = (f64::from(short) * ratio).round().max(1.0) as u64;
507    scaled_long * scaled_short
508}
509
510/// Walks PNG chunks to verify `IEND` is present and every chunk's bounds and CRC32 are valid.
511fn png_has_complete_chunks(bytes: &[u8]) -> bool {
512    if !bytes.starts_with(PNG_SIGNATURE) {
513        return false;
514    }
515    let mut i = PNG_SIGNATURE.len();
516    while let Some(header) = bytes.get(i..i + 8) {
517        let len = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
518        let is_iend = header[4..8] == *b"IEND";
519        let Some(data_end) = (i + 8).checked_add(len) else {
520            return false;
521        };
522        let Some(chunk_end) = data_end.checked_add(4) else {
523            return false;
524        };
525        let Some(crc_bytes) = bytes.get(data_end..chunk_end) else {
526            return false;
527        };
528        let expected_crc =
529            u32::from_be_bytes([crc_bytes[0], crc_bytes[1], crc_bytes[2], crc_bytes[3]]);
530        let Some(crc_span) = bytes.get(i + 4..data_end) else {
531            return false;
532        };
533        if png_crc32(crc_span) != expected_crc {
534            return false;
535        }
536        if is_iend {
537            return true;
538        }
539        i = chunk_end;
540    }
541    false
542}
543
544pub(crate) fn png_crc32(bytes: &[u8]) -> u32 {
545    let mut crc = 0xffff_ffff_u32;
546    for &byte in bytes {
547        crc ^= u32::from(byte);
548        for _ in 0..8 {
549            crc = if crc & 1 != 0 {
550                (crc >> 1) ^ 0xedb8_8320
551            } else {
552                crc >> 1
553            };
554        }
555    }
556    !crc
557}