Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,9 @@ exif-sooc = { git = "https://github.com/oddharsh/exif-sooc" }
fast_image_resize = "6"
jpeg-encoder = "0.6"
png = "0.17"
# JSON-RPC needs a real JSON reader. Hand-rolling one to save a dependency
# means hand-rolling string escapes and unicode, which is exactly where a
# hand-rolled parser goes quietly wrong on a path containing a quote. Derive
# is deliberately off: the server works in `Value` and pulls no proc-macro.
serde_json = "1"
zune-jpeg = "0.4"
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,51 @@ grid, save what Instagram serves back, and score each against its source. That
harness is the obvious next piece and the upload is the one step a program
cannot do for you.

## Point a model at it

`ig-prep mcp` speaks [MCP](https://modelcontextprotocol.io) on stdin and stdout,
so an assistant with file access can convert photographs where they already sit.

```jsonc
// claude_desktop_config.json, or any MCP client's server list
{
"mcpServers": {
"ig-prep": {
"command": "ig-prep",
"args": ["mcp", "--root", "/Users/you/Pictures"]
}
}
}
```

Then: *"convert everything in ~/Pictures/selects for Instagram."*

Three tools. `ig_plan` reports what a conversion would do and writes nothing,
`ig_convert` does it, and `ig_check_rotation` is `--check`. They take the same
arguments the flags take and share the same defaults, because both surfaces call
the same function — a tool server that reimplements its own CLI grows a second
set of defaults and then disagrees with its own documentation.

**Photographs never move and never enter the conversation.** The files are
already on the machine the server runs on, so a result carries paths, sizes and
dimensions rather than image data. That is a deliberate limit and not a missing
feature: a converted frame is a few hundred kilobytes, which is roughly a
megabyte of base64, and forty of them would be forty megabytes of a model's
context spent on pixels it cannot look at anyway.

**`--root` is the boundary.** Every path argument, inputs and output directory
alike, is resolved through its symlinks and refused if it lands outside. Without
it the server will convert anything it can read, which is fine for a tool you
drive yourself and is worth thinking about before handing it to an agent.

One call converts at most 200 files, and says how many it left, because a result
listing 200 conversions of a 900-file directory otherwise reads as a complete
run.

The server answers the 2026-07-28 revision and the three before it. Both eras
stay because a legacy client has no fall-forward mechanism: pointed at a
modern-only server it does not negotiate down, it fails.

## --check

A HEIF can state its rotation twice: as a container transform (`irot`, `imir`)
Expand Down
110 changes: 107 additions & 3 deletions src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,58 @@ fn read_head(path: &Path) -> Result<Vec<u8>, String> {
Ok(b)
}

/// Decode a JPEG to three channels.
///
/// `jpeg_set_out_colorspace` is a REQUEST rather than an instruction, and for a
/// single-channel source zune-jpeg declines it and returns Luma anyway. That
/// declining is silent, which is what makes it worth a comment: the buffer
/// comes back at one byte per pixel, `Rgb::new` labels it as three, and the
/// mismatch surfaces two layers later inside the resizer as "Size of buffer is
/// smaller than required" — an error that names neither the file nor its
/// colour. Every black-and-white JPEG failed that way.
///
/// So the colourspace the decoder actually USED is what gets expanded here,
/// never the one it was asked for. The length check below is the backstop for
/// the next colourspace this misses: a decoder disagreeing with its own
/// dimensions should be caught at the decode boundary, where the file name is
/// still in hand.
fn jpeg(bytes: &[u8]) -> Result<Rgb, String> {
use zune_jpeg::zune_core::colorspace::ColorSpace;

let mut d = zune_jpeg::JpegDecoder::new(bytes);
d.set_options(
zune_jpeg::zune_core::options::DecoderOptions::default()
.jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::RGB),
.jpeg_set_out_colorspace(ColorSpace::RGB),
);
let px = d.decode().map_err(|e| format!("jpeg: {e:?}"))?;
let (w, h) = d.dimensions().ok_or("jpeg: no dimensions")?;
let space = d.get_output_colorspace().ok_or("jpeg: no colourspace")?;

let px = match space {
ColorSpace::RGB => px,
ColorSpace::Luma => px.iter().flat_map(|&v| [v, v, v]).collect(),
ColorSpace::LumaA => px
.as_chunks::<2>()
.0
.iter()
.flat_map(|c| [c[0], c[0], c[0]])
.collect(),
ColorSpace::RGBA => px
.as_chunks::<4>()
.0
.iter()
.flat_map(|c| [c[0], c[1], c[2]])
.collect(),
other => return Err(format!("jpeg: unsupported colourspace {other:?}")),
};

let want = w * h * 3;
if px.len() != want {
return Err(format!(
"jpeg: decoded {} bytes for a {w}x{h} {space:?} image, expected {want}",
px.len()
));
}
Ok(Rgb::new(w as u32, h as u32, px))
}

Expand All @@ -89,7 +133,9 @@ fn png(bytes: &[u8]) -> Result<Rgb, String> {
let px = match info.color_type {
png::ColorType::Rgb => buf[..info.buffer_size()].to_vec(),
png::ColorType::Rgba => buf[..info.buffer_size()]
.chunks_exact(4)
.as_chunks::<4>()
.0
.iter()
.flat_map(|c| [c[0], c[1], c[2]])
.collect(),
png::ColorType::Grayscale => buf[..info.buffer_size()]
Expand Down Expand Up @@ -284,7 +330,9 @@ fn tiff(d: &[u8]) -> Result<Rgb, String> {
if samples == 3 {
raw
} else {
raw.chunks_exact(4)
raw.as_chunks::<4>()
.0
.iter()
.flat_map(|c| [c[0], c[1], c[2]])
.collect()
}
Expand All @@ -308,3 +356,59 @@ fn tiff(d: &[u8]) -> Result<Rgb, String> {
};
Ok(Rgb::new(w, h, px))
}

#[cfg(test)]
mod tests {
use super::*;

/// A grayscale JPEG must come back as three channels.
///
/// This is a regression rather than a nicety: `jpeg_set_out_colorspace` is
/// a request the decoder declines for a single-channel source, so every
/// black-and-white JPEG used to reach the resizer at a third of the length
/// its dimensions claimed and die there with an error naming neither.
/// Built here rather than committed as a fixture so the test carries its
/// own input.
#[test]
fn grayscale_jpeg_expands_to_rgb() {
let (w, h) = (32usize, 24usize);
let luma: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
let mut encoded = Vec::new();
jpeg_encoder::Encoder::new(&mut encoded, 90)
.encode(&luma, w as u16, h as u16, jpeg_encoder::ColorType::Luma)
.expect("encode a luma jpeg");

let img = jpeg(&encoded).expect("decode the luma jpeg");
assert_eq!((img.w, img.h), (w as u32, h as u32));
assert_eq!(img.px.len(), w * h * 3, "must be three channels");
// Expanded rather than merely padded: a pixel is grey, so its three
// channels agree.
for px in img.px.as_chunks::<3>().0.iter() {
assert_eq!(px[0], px[1]);
assert_eq!(px[1], px[2]);
}
}

/// The colour path is untouched by that expansion.
#[test]
fn colour_jpeg_still_decodes_to_rgb() {
let (w, h) = (32usize, 24usize);
let rgb: Vec<u8> = (0..w * h)
.flat_map(|i| {
[
(i % 256) as u8,
((i * 3) % 256) as u8,
((i * 7) % 256) as u8,
]
})
.collect();
let mut encoded = Vec::new();
jpeg_encoder::Encoder::new(&mut encoded, 90)
.encode(&rgb, w as u16, h as u16, jpeg_encoder::ColorType::Rgb)
.expect("encode an rgb jpeg");

let img = jpeg(&encoded).expect("decode the rgb jpeg");
assert_eq!((img.w, img.h), (w as u32, h as u32));
assert_eq!(img.px.len(), w * h * 3);
}
}
56 changes: 48 additions & 8 deletions src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,60 @@
//! successive halvings visibly smear saturated edges. The cost is bytes on an
//! upload, which nobody sees.
//!
//! UNVERIFIED, like the rest of the Instagram-facing assumptions here: worth a
//! round trip before anyone treats it as fact.
//! 4:2:2 is the middle, and it is the honest one for a camera that shoots
//! 4:2:2. It is worth being precise about why the source ratio does NOT settle
//! the question on its own. A Fujifilm HIF halves chroma horizontally in its
//! own landscape orientation, so a 7728x5152 frame carries a 3864x5152 chroma
//! plane; held vertically that becomes 5152x3864, and the halved axis lands on
//! the LONG edge of the portrait. Against a 1440x2160 output that is still
//! 3.58x horizontally and 1.79x vertically of real chroma to average down.
//! Full-resolution output chroma is therefore measured rather than invented,
//! and 4:2:0 here would discard detail the source genuinely resolves.
//!
//! That reasoning holds only while the downscale stays large. Somebody
//! delivering at or near native size has a 4:2:2 source that cannot fill a
//! 4:4:4 output, and should say `--422` and mean it.
//!
//! UNVERIFIED, like the rest of the Instagram-facing assumptions here: which of
//! the three survives a round trip best is exactly what the upload harness is
//! supposed to settle.

use crate::image::Rgb;
use jpeg_encoder::{ColorType, Encoder, SamplingFactor};

pub fn jpeg(img: &Rgb, quality: u8, subsample: bool) -> Result<Vec<u8>, String> {
/// What the chroma plane is worth on the way out, named for the JPEG ratio.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Chroma {
/// 4:4:4, chroma at luma resolution.
Full,
/// 4:2:2, chroma halved horizontally. What the camera shot.
Halved,
/// 4:2:0, chroma halved on both axes. What Instagram will store anyway.
Quartered,
}

impl Chroma {
fn sampling(self) -> SamplingFactor {
match self {
Chroma::Full => SamplingFactor::R_4_4_4,
Chroma::Halved => SamplingFactor::R_4_2_2,
Chroma::Quartered => SamplingFactor::R_4_2_0,
}
}

pub fn label(self) -> &'static str {
match self {
Chroma::Full => "4:4:4",
Chroma::Halved => "4:2:2",
Chroma::Quartered => "4:2:0",
}
}
}

pub fn jpeg(img: &Rgb, quality: u8, chroma: Chroma) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
let mut enc = Encoder::new(&mut out, quality);
enc.set_sampling_factor(if subsample {
SamplingFactor::F_2_2
} else {
SamplingFactor::F_1_1
});
enc.set_sampling_factor(chroma.sampling());
enc.set_progressive(false);
enc.encode(&img.px, img.w as u16, img.h as u16, ColorType::Rgb)
.map_err(|e| format!("encode: {e}"))?;
Expand Down
6 changes: 4 additions & 2 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ pub fn resize(src: &Rgb, w: u32, h: u32) -> Result<Rgb, String> {
// took a file from 2.4s to under a second.
let table = srgb_to_linear_table();
let mut bytes = vec![0u8; src.px.len() * 4];
for (chunk, &i) in bytes.chunks_exact_mut(4).zip(src.px.iter()) {
for (chunk, &i) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(src.px.iter()) {
chunk.copy_from_slice(&table[i as usize].to_ne_bytes());
}
let src_img = Image::from_vec_u8(src.w, src.h, bytes, PixelType::F32x3)
Expand All @@ -140,7 +140,9 @@ pub fn resize(src: &Rgb, w: u32, h: u32) -> Result<Rgb, String> {

let out: Vec<u8> = dst_img
.buffer()
.chunks_exact(4)
.as_chunks::<4>()
.0
.iter()
.map(|c| linear_to_srgb(f32::from_ne_bytes([c[0], c[1], c[2], c[3]])))
.collect();
Ok(Rgb::new(w, h, out))
Expand Down
Loading
Loading