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
23 changes: 7 additions & 16 deletions Cargo.lock

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

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,16 @@ png = "0.17"
tempfile = "3"
# Decode the lossless sips intermediate, including tiled 16-bit TIFF.
tiff = { version = "0.11.3", default-features = false }
# Source JPEG decoder. zune-jpeg 0.4 rejects a progressive scan whose length is
# a multiple of the restart interval, which is the shape of this tool's own
# exports (fixed upstream in 0.5.13). Single-threaded: rayon saves a fifth of a
# 24MP decode and costs a dozen crates.
jpeg-decoder = { version = "0.3", default-features = false }
# 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"

[dev-dependencies]
# Independent JPEG fixtures for decoder tests; not a production encoder.
Expand Down
124 changes: 111 additions & 13 deletions src/decode.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
//! Decode at source precision, then colour-manage every format into linear sRGB.
//! HEIF uses macOS sips; JPEG XL uses djxl. Their intermediates retain profiles.
//!
//! JPEG goes through jpeg-decoder rather than zune-jpeg. zune-jpeg 0.4 rejects
//! a progressive scan whose length is a multiple of the restart interval, and
//! ZenJPEG's exports at Instagram sizes are exactly that shape, so the tool
//! could not read its own output. jpeg-decoder matches libjpeg-turbo to within
//! one level on those files. Upstream fixed zune-jpeg in 0.5.13.

use crate::{color, image::Rgb};
use moxcms::ColorProfile;
Expand Down Expand Up @@ -31,22 +37,27 @@ pub fn open(path: &Path) -> Result<Decoded, String> {
}

fn jpeg(bytes: &[u8]) -> Result<Rgb, String> {
use zune_jpeg::zune_core::{colorspace::ColorSpace, options::DecoderOptions};
let mut d = zune_jpeg::JpegDecoder::new(bytes);
d.set_options(DecoderOptions::default().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")?;
// A grayscale JPEG may remain Luma despite requesting RGB.
let channels = match d.get_output_colorspace().ok_or("jpeg: no colourspace")? {
ColorSpace::RGB => 3,
ColorSpace::RGBA => 4,
ColorSpace::Luma => 1,
ColorSpace::LumaA => 2,
other => return Err(format!("jpeg: unsupported colourspace {other:?}")),
use jpeg_decoder::{Decoder, PixelFormat};
let mut d = Decoder::new(bytes);
let px = d.decode().map_err(|e| format!("jpeg: {e}"))?;
let info = d.info().ok_or("jpeg: no image info")?;
// YCbCr and RGB-coded frames both arrive as RGB; only CMYK and 16-bit
// lossless keep their own layout, and neither is a camera format.
let channels = match info.pixel_format {
PixelFormat::RGB24 => 3,
PixelFormat::L8 => 1,
other => return Err(format!("jpeg: unsupported sample format {other:?}")),
};
let icc = d.icc_profile();
let source = color::profile(icc.as_deref())?;
color::convert(w as u32, h as u32, &px, channels, 255.0, &source)
color::convert(
info.width.into(),
info.height.into(),
&px,
channels,
255.0,
&source,
)
}

fn png_profile(info: &png::Info<'_>) -> Result<ColorProfile, String> {
Expand Down Expand Up @@ -283,6 +294,93 @@ mod tests {
}
}

/// A scan whose length is a multiple of the restart interval ends flush
/// with its final interval, and T.81 figure B.2 puts no RST marker after
/// that one. zune-jpeg 0.4 rejected the layout as "Marker SOS found in
/// bitstream", so the two fixtures below are the regression guard.
#[test]
fn progressive_scan_ending_on_a_restart_interval_decodes() {
// 16x8 at 4:4:4 is two data units per scan; an interval of one MCU
// makes every scan end on an interval boundary.
let px: Vec<u8> = (0..16 * 8)
.flat_map(|i| [(i % 16) as u8 * 12 + 30, (i / 16) as u8 * 20 + 40, 160])
.collect();
let mut bytes = Vec::new();
let mut enc = jpeg_encoder::Encoder::new(&mut bytes, 95);
enc.set_progressive(true);
enc.set_restart_interval(1);
enc.set_sampling_factor(jpeg_encoder::SamplingFactor::F_1_1);
enc.encode(&px, 16, 8, jpeg_encoder::ColorType::Rgb)
.unwrap();
assert!(
bytes.windows(2).any(|p| p == [0xff, 0xdd]),
"no DRI segment"
);
assert!(
bytes
.windows(2)
.any(|p| p[0] == 0xff && (0xd0..=0xd7).contains(&p[1])),
"no RST markers"
);
let img = jpeg(&bytes).unwrap();
assert_eq!((img.w, img.h), (16, 8));
for (i, (&linear, &expected)) in img.px.iter().zip(&px).enumerate() {
let got = color::linear_to_srgb(linear) * 255.0;
assert!(
(got - f32::from(expected)).abs() < 8.0,
"sample {i}: decoded {got}, expected {expected}"
);
}
}

#[test]
fn own_export_at_a_realistic_size_reads_back() {
// 1440x960 at 4:4:4 is 180x120 data units. ZenJPEG restarts every four
// rows of them, and 720 divides 21600, which is the shape that failed.
let (w, h) = (1440u32, 960u32);
let mut px = Vec::with_capacity((w * h * 3) as usize);
for y in 0..h {
for x in 0..w {
let mut n = (y * w + x).wrapping_mul(0x9e3779b9);
n ^= n >> 15;
let noise = (n & 0xff) as f32 / 255.0 * 0.01 - 0.005;
px.extend([
0.05 + 0.7 * x as f32 / w as f32 + noise,
0.05 + 0.7 * y as f32 / h as f32 + noise,
0.3 + noise,
]);
}
}
let img = Rgb::new(w, h, px);
let bytes = crate::encode::jpeg(&img, 95, crate::encode::Chroma::Full, false).unwrap();
let dri = bytes
.windows(2)
.position(|p| p == [0xff, 0xdd])
.map(|i| u16::from_be_bytes([bytes[i + 4], bytes[i + 5]]))
.expect("the export defines a restart interval");
assert_eq!(
(w / 8 * (h / 8)) % u32::from(dri),
0,
"the fixture only guards the regression while every scan is a whole number of intervals"
);
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("export.jpg");
std::fs::write(&path, &bytes).unwrap();
let decoded = open(&path).unwrap();
assert!(!decoded.orientation_applied);
assert_eq!((decoded.img.w, decoded.img.h), (w, h));
let (mut worst, mut total) = (0.0f32, 0.0f64);
for (&got, &expected) in decoded.img.px.iter().zip(&img.px) {
let d = (color::linear_to_srgb(got) - color::linear_to_srgb(expected)).abs() * 255.0;
worst = worst.max(d);
total += f64::from(d);
}
let mean = total / img.px.len() as f64;
// Measured 5.8 and 0.76 at the time of writing; a dropped or shifted
// row would push the worst sample past 40.
assert!(worst < 12.0 && mean < 1.5, "worst {worst}, mean {mean}");
}

#[test]
fn png_retains_low_sixteen_bit_values() {
let samples = [32768u16, 32768, 32768, 32769, 32769, 32769];
Expand Down
10 changes: 7 additions & 3 deletions src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ mod tests {
let img = Rgb::new(33, 19, px);
for chroma in [Chroma::Full, Chroma::Halved, Chroma::Quartered] {
let bytes = jpeg(&img, 98, chroma, false).unwrap();
let mut decoder = zune_jpeg::JpegDecoder::new(&bytes);
let mut decoder = jpeg_decoder::Decoder::new(&bytes[..]);
let decoded = decoder.decode().unwrap();
assert_eq!(decoder.dimensions(), Some((33, 19)));
let info = decoder.info().unwrap();
assert_eq!((info.width, info.height), (33, 19));
assert_eq!(decoder.icc_profile().unwrap(), crate::color::SRGB_ICC);
let sof = bytes.windows(2).position(|p| p == [0xff, 0xc2]).unwrap();
assert_eq!(bytes[sof + 4], 8, "standard 8-bit JPEG precision");
Expand Down Expand Up @@ -214,7 +215,10 @@ mod tests {
for q in [1, 100] {
let bytes = jpeg(&img, q, Chroma::Full, false).unwrap();
assert_eq!(
zune_jpeg::JpegDecoder::new(&bytes).decode().unwrap().len(),
jpeg_decoder::Decoder::new(&bytes[..])
.decode()
.unwrap()
.len(),
3
);
}
Expand Down
Loading