From b2fbdf2499acf0094138718428d8e7b48ca6b62e Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 14:27:24 +0000 Subject: [PATCH 01/21] Add jpeg-encoder as a conditional dependency --- Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 020b2c9f6e..7f522ea05b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,6 +55,7 @@ rgb = { version = "0.8.48", default-features = false, optional = true } tiff = { version = "0.10.3", optional = true } zune-core = { version = "0.5.0", default-features = false, optional = true } zune-jpeg = { version = "0.5.5", optional = true } +jpeg-encoder = { version = "0.6.1", optional = true, features = ["simd"] } serde = { version = "1.0.214", optional = true, features = ["derive"] } [dev-dependencies] @@ -77,7 +78,7 @@ ff = [] # Farbfeld image format gif = ["dep:gif", "dep:color_quant"] hdr = [] ico = ["bmp", "png"] -jpeg = ["dep:zune-core", "dep:zune-jpeg"] +jpeg = ["dep:zune-core", "dep:zune-jpeg", "dep:jpeg-encoder"] png = ["dep:png"] pnm = [] qoi = ["dep:qoi"] From c8984578a5349208ed72462efeea2c153ab98b31 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:08:21 +0000 Subject: [PATCH 02/21] Initial conversion pass from built-in JPEG encoder to jpeg-encoder crate --- src/codecs/jpeg/encoder.rs | 367 ++++--------------------------------- 1 file changed, 37 insertions(+), 330 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 245defd045..b2b8e2353b 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -18,6 +18,8 @@ use num_traits::ToPrimitive; use super::entropy::build_huff_lut_const; use super::transform; +use jpeg_encoder::Encoder; + // Markers // Baseline DCT static SOF0: u8 = 0xC0; @@ -330,6 +332,15 @@ impl PixelDensity { unit: PixelDensityUnit::Inches, } } + + /// Converts pixel density to the representation used by jpeg-encoder crate + fn to_encoder_repr(&self) -> jpeg_encoder::Density { + match self.unit { + PixelDensityUnit::PixelAspectRatio => todo!(), // Not supported in jpeg-encoder? + PixelDensityUnit::Inches => jpeg_encoder::Density::Inch {x: self.density.0, y: self.density.1}, + PixelDensityUnit::Centimeters => jpeg_encoder::Density::Centimeter {x: self.density.0, y: self.density.1}, + } + } } impl Default for PixelDensity { @@ -343,21 +354,8 @@ impl Default for PixelDensity { } /// The representation of a JPEG encoder -pub struct JpegEncoder { - writer: BitWriter, - - components: Vec, - tables: Vec<[u8; 64]>, - - luma_dctable: Cow<'static, [(u8, u16); 256]>, - luma_actable: Cow<'static, [(u8, u16); 256]>, - chroma_dctable: Cow<'static, [(u8, u16); 256]>, - chroma_actable: Cow<'static, [(u8, u16); 256]>, - - pixel_density: PixelDensity, - - icc_profile: Vec, - exif: Vec, +pub struct JpegEncoder { + encoder: Encoder, } impl JpegEncoder { @@ -370,66 +368,8 @@ impl JpegEncoder { /// the quality parameter ```quality``` with a value in the range 1-100 /// where 1 is the worst and 100 is the best. pub fn new_with_quality(w: W, quality: u8) -> JpegEncoder { - let components = vec![ - Component { - id: LUMAID, - h: 1, - v: 1, - tq: LUMADESTINATION, - dc_table: LUMADESTINATION, - ac_table: LUMADESTINATION, - _dc_pred: 0, - }, - Component { - id: CHROMABLUEID, - h: 1, - v: 1, - tq: CHROMADESTINATION, - dc_table: CHROMADESTINATION, - ac_table: CHROMADESTINATION, - _dc_pred: 0, - }, - Component { - id: CHROMAREDID, - h: 1, - v: 1, - tq: CHROMADESTINATION, - dc_table: CHROMADESTINATION, - ac_table: CHROMADESTINATION, - _dc_pred: 0, - }, - ]; - - // Derive our quantization table scaling value using the libjpeg algorithm - let scale = u32::from(clamp(quality, 1, 100)); - let scale = if scale < 50 { - 5000 / scale - } else { - 200 - scale * 2 - }; - - let mut tables = vec![STD_LUMA_QTABLE, STD_CHROMA_QTABLE]; - for t in tables.iter_mut() { - for v in t.iter_mut() { - *v = clamp((u32::from(*v) * scale + 50) / 100, 1, u32::from(u8::MAX)) as u8; - } - } - JpegEncoder { - writer: BitWriter::new(w), - - components, - tables, - - luma_dctable: Cow::Borrowed(&STD_LUMA_DC_HUFF_LUT), - luma_actable: Cow::Borrowed(&STD_LUMA_AC_HUFF_LUT), - chroma_dctable: Cow::Borrowed(&STD_CHROMA_DC_HUFF_LUT), - chroma_actable: Cow::Borrowed(&STD_CHROMA_AC_HUFF_LUT), - - pixel_density: PixelDensity::default(), - - icc_profile: Vec::new(), - exif: Vec::new(), + encoder: Encoder::new(w, quality), } } @@ -437,21 +377,19 @@ impl JpegEncoder { /// If this method is not called, then a default pixel aspect ratio of 1x1 will be applied, /// and no DPI information will be stored in the image. pub fn set_pixel_density(&mut self, pixel_density: PixelDensity) { - self.pixel_density = pixel_density; + self.encoder.set_density(pixel_density.to_encoder_repr()); } /// Encodes the image stored in the raw byte buffer ```image``` /// that has dimensions ```width``` and ```height``` /// and ```ColorType``` ```c``` /// - /// The Image in encoded with subsampling ratio 4:2:2 - /// /// # Panics /// /// Panics if `width * height * color_type.bytes_per_pixel() != image.len()`. #[track_caller] - pub fn encode( - &mut self, + fn encode( + self, image: &[u8], width: u32, height: u32, @@ -465,16 +403,18 @@ impl JpegEncoder { image.len(), ); + // TODO: error out instead of panicking + let width: u16 = width.try_into().expect("width too large to encode in JPEG"); + let height: u16 = height.try_into().expect("height too large to encode in JPEG"); + match color_type { ExtendedColorType::L8 => { - let image: ImageBuffer, _> = - ImageBuffer::from_raw(width, height, image).unwrap(); - self.encode_image(&image) + let color = jpeg_encoder::ColorType::Luma; + Ok(self.encoder.encode(image, width, height, color).unwrap()) // TODO: error handling } ExtendedColorType::Rgb8 => { - let image: ImageBuffer, _> = - ImageBuffer::from_raw(width, height, image).unwrap(); - self.encode_image(&image) + let color = jpeg_encoder::ColorType::Rgb; + Ok(self.encoder.encode(image, width, height, color).unwrap()) // TODO: error handling } _ => Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( @@ -486,240 +426,21 @@ impl JpegEncoder { } fn write_exif(&mut self) -> ImageResult<()> { - if !self.exif.is_empty() { - let mut formatted = EXIF_HEADER.to_vec(); - formatted.extend_from_slice(&self.exif); - self.writer.write_segment(APP1, &formatted)?; - } - - Ok(()) - } - - /// Encodes the given image. - /// - /// As a special feature this does not require the whole image to be present in memory at the - /// same time such that it may be computed on the fly, which is why this method exists on this - /// encoder but not on others. Instead the encoder will iterate over 8-by-8 blocks of pixels at - /// a time, inspecting each pixel exactly once. You can rely on this behaviour when calling - /// this method. - /// - /// The Image in encoded with subsampling ratio 4:2:2 - pub fn encode_image(&mut self, image: &I) -> ImageResult<()> - where - I::Pixel: PixelWithColorType, - { - let n = I::Pixel::CHANNEL_COUNT; - let color_type = I::Pixel::COLOR_TYPE; - let num_components = if n == 1 || n == 2 { 1 } else { 3 }; - - self.writer.write_marker(SOI)?; - - let mut buf = Vec::new(); - - build_jfif_header(&mut buf, self.pixel_density); - self.writer.write_segment(APP0, &buf)?; - self.write_exif()?; - - // Write ICC profile chunks if present - self.write_icc_profile_chunks()?; - - build_frame_header( - &mut buf, - 8, - // TODO: not idiomatic yet. Should be an EncodingError and mention jpg. Further it - // should check dimensions prior to writing. - u16::try_from(image.width()).map_err(|_| { - ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - )) - })?, - u16::try_from(image.height()).map_err(|_| { - ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - )) - })?, - &self.components[..num_components], - ); - self.writer.write_segment(SOF0, &buf)?; - - assert_eq!(self.tables.len(), 2); - let numtables = if num_components == 1 { 1 } else { 2 }; - - for (i, table) in self.tables[..numtables].iter().enumerate() { - build_quantization_segment(&mut buf, 8, i as u8, table); - self.writer.write_segment(DQT, &buf)?; - } - - build_huffman_segment( - &mut buf, - DCCLASS, - LUMADESTINATION, - &STD_LUMA_DC_CODE_LENGTHS, - &STD_LUMA_DC_VALUES, - ); - self.writer.write_segment(DHT, &buf)?; - - build_huffman_segment( - &mut buf, - ACCLASS, - LUMADESTINATION, - &STD_LUMA_AC_CODE_LENGTHS, - &STD_LUMA_AC_VALUES, - ); - self.writer.write_segment(DHT, &buf)?; - - if num_components == 3 { - build_huffman_segment( - &mut buf, - DCCLASS, - CHROMADESTINATION, - &STD_CHROMA_DC_CODE_LENGTHS, - &STD_CHROMA_DC_VALUES, - ); - self.writer.write_segment(DHT, &buf)?; - - build_huffman_segment( - &mut buf, - ACCLASS, - CHROMADESTINATION, - &STD_CHROMA_AC_CODE_LENGTHS, - &STD_CHROMA_AC_VALUES, - ); - self.writer.write_segment(DHT, &buf)?; - } - - build_scan_header(&mut buf, &self.components[..num_components]); - self.writer.write_segment(SOS, &buf)?; - - if ExtendedColorType::Rgb8 == color_type || ExtendedColorType::Rgba8 == color_type { - self.encode_rgb(image) - } else { - self.encode_gray(image) - }?; - - self.writer.pad_byte()?; - self.writer.write_marker(EOI)?; - Ok(()) - } - - fn encode_gray(&mut self, image: &I) -> io::Result<()> { - let mut yblock = [0u8; 64]; - let mut y_dcprev = 0; - let mut dct_yblock = [0i32; 64]; - - for y in (0..image.height()).step_by(8) { - for x in (0..image.width()).step_by(8) { - copy_blocks_gray(image, x, y, &mut yblock); - - // Level shift and fdct - // Coeffs are scaled by 8 - transform::fdct(&yblock, &mut dct_yblock); - - // Quantization - for (i, dct) in dct_yblock.iter_mut().enumerate() { - *dct = ((*dct / 8) as f32 / f32::from(self.tables[0][i])).round() as i32; - } - - let la = &*self.luma_actable; - let ld = &*self.luma_dctable; - - y_dcprev = self.writer.write_block(&dct_yblock, y_dcprev, ld, la)?; - } - } - - Ok(()) - } - - fn encode_rgb(&mut self, image: &I) -> io::Result<()> { - let mut y_dcprev = 0; - let mut cb_dcprev = 0; - let mut cr_dcprev = 0; - - let mut dct_yblock = [0i32; 64]; - let mut dct_cb_block = [0i32; 64]; - let mut dct_cr_block = [0i32; 64]; - - let mut yblock = [0u8; 64]; - let mut cb_block = [0u8; 64]; - let mut cr_block = [0u8; 64]; - - for y in (0..image.height()).step_by(8) { - for x in (0..image.width()).step_by(8) { - // RGB -> YCbCr - copy_blocks_ycbcr(image, x, y, &mut yblock, &mut cb_block, &mut cr_block); - - // Level shift and fdct - // Coeffs are scaled by 8 - transform::fdct(&yblock, &mut dct_yblock); - transform::fdct(&cb_block, &mut dct_cb_block); - transform::fdct(&cr_block, &mut dct_cr_block); - - // Quantization - for i in 0usize..64 { - dct_yblock[i] = - ((dct_yblock[i] / 8) as f32 / f32::from(self.tables[0][i])).round() as i32; - dct_cb_block[i] = ((dct_cb_block[i] / 8) as f32 / f32::from(self.tables[1][i])) - .round() as i32; - dct_cr_block[i] = ((dct_cr_block[i] / 8) as f32 / f32::from(self.tables[1][i])) - .round() as i32; - } - - let la = &*self.luma_actable; - let ld = &*self.luma_dctable; - let cd = &*self.chroma_dctable; - let ca = &*self.chroma_actable; - - y_dcprev = self.writer.write_block(&dct_yblock, y_dcprev, ld, la)?; - cb_dcprev = self.writer.write_block(&dct_cb_block, cb_dcprev, cd, ca)?; - cr_dcprev = self.writer.write_block(&dct_cr_block, cr_dcprev, cd, ca)?; - } - } - - Ok(()) - } - - fn write_icc_profile_chunks(&mut self) -> io::Result<()> { - if self.icc_profile.is_empty() { - return Ok(()); - } - - const MAX_CHUNK_SIZE: usize = 65533 - 14; - const MAX_CHUNK_COUNT: usize = 255; - const MAX_ICC_PROFILE_SIZE: usize = MAX_CHUNK_SIZE * MAX_CHUNK_COUNT; - - if self.icc_profile.len() > MAX_ICC_PROFILE_SIZE { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "ICC profile too large", - )); - } - - let chunk_iter = self.icc_profile.chunks(MAX_CHUNK_SIZE); - let num_chunks = chunk_iter.len() as u8; - let mut segment = Vec::new(); - - for (i, chunk) in chunk_iter.enumerate() { - let chunk_number = (i + 1) as u8; - let length = 14 + chunk.len(); - - segment.clear(); - segment.reserve(length); - segment.extend_from_slice(b"ICC_PROFILE\0"); - segment.push(chunk_number); - segment.push(num_chunks); - segment.extend_from_slice(chunk); - - self.writer.write_segment(APP2, &segment)?; - } - - Ok(()) + todo!(); // no convenience method in jpeg-encoder + // if !self.exif.is_empty() { + // let mut formatted = EXIF_HEADER.to_vec(); + // formatted.extend_from_slice(&self.exif); + // self.writer.write_segment(APP1, &formatted)?; + // } + // + // Ok(()) } } impl ImageEncoder for JpegEncoder { #[track_caller] fn write_image( - mut self, + self, buf: &[u8], width: u32, height: u32, @@ -729,12 +450,12 @@ impl ImageEncoder for JpegEncoder { } fn set_icc_profile(&mut self, icc_profile: Vec) -> Result<(), UnsupportedError> { - self.icc_profile = icc_profile; + self.encoder.add_icc_profile(&icc_profile); Ok(()) } fn set_exif_metadata(&mut self, exif: Vec) -> Result<(), UnsupportedError> { - self.exif = exif; + todo!(); // no convenience method in jpeg-encoder yet Ok(()) } @@ -1196,18 +917,4 @@ mod tests { let _x = JpegEncoder::new(&mut y); }); } -} - -// Tests regressions of `encode_image` against #1412, confusion about the subimage's position vs. -// dimensions. (We no longer have a position, four `u32` returns was confusing). -#[test] -fn sub_image_encoder_regression_1412() { - let image = DynamicImage::new_rgb8(1280, 720); - let subimg = crate::imageops::crop_imm(&image, 0, 358, 425, 361); - - let mut encoded_crop = vec![]; - let mut encoder = JpegEncoder::new(&mut encoded_crop); - - let result = encoder.encode_image(&*subimg); - assert!(result.is_ok(), "Failed to encode subimage: {result:?}"); -} +} \ No newline at end of file From 41d9abad24eea566e49103ef4bde02f6999aafa5 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:12:23 +0000 Subject: [PATCH 03/21] Remove a great deal of now-unused code --- src/codecs/jpeg/encoder.rs | 600 +------------------------------------ 1 file changed, 5 insertions(+), 595 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index b2b8e2353b..accb9e62a6 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -1,295 +1,17 @@ #![allow(clippy::too_many_arguments)] -use std::borrow::Cow; -use std::io::{self, Write}; +use std::io::Write; use crate::error::{ - ImageError, ImageResult, ParameterError, ParameterErrorKind, UnsupportedError, + ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind, }; -use crate::traits::PixelWithColorType; -use crate::utils::clamp; use crate::{ - ColorType, DynamicImage, ExtendedColorType, GenericImageView, ImageBuffer, ImageEncoder, - ImageFormat, Luma, Pixel, Rgb, + ColorType, DynamicImage, ExtendedColorType, ImageEncoder, + ImageFormat, }; -use num_traits::ToPrimitive; - -use super::entropy::build_huff_lut_const; -use super::transform; - use jpeg_encoder::Encoder; -// Markers -// Baseline DCT -static SOF0: u8 = 0xC0; -// Huffman Tables -static DHT: u8 = 0xC4; -// Start of Image (standalone) -static SOI: u8 = 0xD8; -// End of image (standalone) -static EOI: u8 = 0xD9; -// Start of Scan -static SOS: u8 = 0xDA; -// Quantization Tables -static DQT: u8 = 0xDB; -// Application segments start and end -static APP0: u8 = 0xE0; -static APP1: u8 = 0xE1; -static APP2: u8 = 0xE2; - -// section K.1 -// table K.1 -#[rustfmt::skip] -static STD_LUMA_QTABLE: [u8; 64] = [ - 16, 11, 10, 16, 24, 40, 51, 61, - 12, 12, 14, 19, 26, 58, 60, 55, - 14, 13, 16, 24, 40, 57, 69, 56, - 14, 17, 22, 29, 51, 87, 80, 62, - 18, 22, 37, 56, 68, 109, 103, 77, - 24, 35, 55, 64, 81, 104, 113, 92, - 49, 64, 78, 87, 103, 121, 120, 101, - 72, 92, 95, 98, 112, 100, 103, 99, -]; - -// table K.2 -#[rustfmt::skip] -static STD_CHROMA_QTABLE: [u8; 64] = [ - 17, 18, 24, 47, 99, 99, 99, 99, - 18, 21, 26, 66, 99, 99, 99, 99, - 24, 26, 56, 99, 99, 99, 99, 99, - 47, 66, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, -]; - -// section K.3 -// Code lengths and values for table K.3 -static STD_LUMA_DC_CODE_LENGTHS: [u8; 16] = [ - 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -]; - -static STD_LUMA_DC_VALUES: [u8; 12] = [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, -]; - -static STD_LUMA_DC_HUFF_LUT: [(u8, u16); 256] = - build_huff_lut_const(&STD_LUMA_DC_CODE_LENGTHS, &STD_LUMA_DC_VALUES); - -// Code lengths and values for table K.4 -static STD_CHROMA_DC_CODE_LENGTHS: [u8; 16] = [ - 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, -]; - -static STD_CHROMA_DC_VALUES: [u8; 12] = [ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, -]; - -static STD_CHROMA_DC_HUFF_LUT: [(u8, u16); 256] = - build_huff_lut_const(&STD_CHROMA_DC_CODE_LENGTHS, &STD_CHROMA_DC_VALUES); - -// Code lengths and values for table k.5 -static STD_LUMA_AC_CODE_LENGTHS: [u8; 16] = [ - 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7D, -]; - -static STD_LUMA_AC_VALUES: [u8; 162] = [ - 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, - 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1, 0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1, 0xF0, - 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, - 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, - 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, - 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, - 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, - 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xE1, 0xE2, - 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, - 0xF9, 0xFA, -]; - -static STD_LUMA_AC_HUFF_LUT: [(u8, u16); 256] = - build_huff_lut_const(&STD_LUMA_AC_CODE_LENGTHS, &STD_LUMA_AC_VALUES); - -// Code lengths and values for table k.6 -static STD_CHROMA_AC_CODE_LENGTHS: [u8; 16] = [ - 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, -]; -static STD_CHROMA_AC_VALUES: [u8; 162] = [ - 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, - 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23, 0x33, 0x52, 0xF0, - 0x15, 0x62, 0x72, 0xD1, 0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17, 0x18, 0x19, 0x1A, 0x26, - 0x27, 0x28, 0x29, 0x2A, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, - 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5, - 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3, - 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, - 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, - 0xF9, 0xFA, -]; - -static STD_CHROMA_AC_HUFF_LUT: [(u8, u16); 256] = - build_huff_lut_const(&STD_CHROMA_AC_CODE_LENGTHS, &STD_CHROMA_AC_VALUES); - -static DCCLASS: u8 = 0; -static ACCLASS: u8 = 1; - -static LUMADESTINATION: u8 = 0; -static CHROMADESTINATION: u8 = 1; - -static LUMAID: u8 = 1; -static CHROMABLUEID: u8 = 2; -static CHROMAREDID: u8 = 3; - -/// The permutation of dct coefficients. -#[rustfmt::skip] -static UNZIGZAG: [u8; 64] = [ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63, -]; - -// E x i f \0 \0 -/// The header for an EXIF APP1 segment -static EXIF_HEADER: [u8; 6] = [0x45, 0x78, 0x69, 0x66, 0x00, 0x00]; - -/// A representation of a JPEG component -#[derive(Copy, Clone)] -struct Component { - /// The Component's identifier - id: u8, - - /// Horizontal sampling factor - h: u8, - - /// Vertical sampling factor - v: u8, - - /// The quantization table selector - tq: u8, - - /// Index to the Huffman DC Table - dc_table: u8, - - /// Index to the AC Huffman Table - ac_table: u8, - - /// The dc prediction of the component - _dc_pred: i32, -} - -pub(crate) struct BitWriter { - w: W, - accumulator: u32, - nbits: u8, -} - -impl BitWriter { - fn new(w: W) -> Self { - BitWriter { - w, - accumulator: 0, - nbits: 0, - } - } - - fn write_bits(&mut self, bits: u16, size: u8) -> io::Result<()> { - if size == 0 { - return Ok(()); - } - - self.nbits += size; - self.accumulator |= u32::from(bits) << (32 - self.nbits) as usize; - - while self.nbits >= 8 { - let byte = self.accumulator >> 24; - self.w.write_all(&[byte as u8])?; - - if byte == 0xFF { - self.w.write_all(&[0x00])?; - } - - self.nbits -= 8; - self.accumulator <<= 8; - } - - Ok(()) - } - - fn pad_byte(&mut self) -> io::Result<()> { - self.write_bits(0x7F, 7) - } - - fn huffman_encode(&mut self, val: u8, table: &[(u8, u16); 256]) -> io::Result<()> { - let (size, code) = table[val as usize]; - - assert!(size <= 16, "bad huffman value"); - - self.write_bits(code, size) - } - - fn write_block( - &mut self, - block: &[i32; 64], - prevdc: i32, - dctable: &[(u8, u16); 256], - actable: &[(u8, u16); 256], - ) -> io::Result { - // Differential DC encoding - let dcval = block[0]; - let diff = dcval - prevdc; - let (size, value) = encode_coefficient(diff); - - self.huffman_encode(size, dctable)?; - self.write_bits(value, size)?; - - // Figure F.2 - let mut zero_run = 0; - - for &k in &UNZIGZAG[1..] { - if block[k as usize] == 0 { - zero_run += 1; - } else { - while zero_run > 15 { - self.huffman_encode(0xF0, actable)?; - zero_run -= 16; - } - - let (size, value) = encode_coefficient(block[k as usize]); - let symbol = (zero_run << 4) | size; - - self.huffman_encode(symbol, actable)?; - self.write_bits(value, size)?; - - zero_run = 0; - } - } - - if block[UNZIGZAG[63] as usize] == 0 { - self.huffman_encode(0x00, actable)?; - } - - Ok(dcval) - } - - fn write_marker(&mut self, marker: u8) -> io::Result<()> { - self.w.write_all(&[0xFF, marker]) - } - - fn write_segment(&mut self, marker: u8, data: &[u8]) -> io::Result<()> { - self.w.write_all(&[0xFF, marker])?; - self.w.write_all(&(data.len() as u16 + 2).to_be_bytes())?; - self.w.write_all(data) - } -} - /// Represents a unit in which the density of an image is measured #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PixelDensityUnit { @@ -473,190 +195,6 @@ impl ImageEncoder for JpegEncoder { } } -fn build_jfif_header(m: &mut Vec, density: PixelDensity) { - m.clear(); - m.extend_from_slice(b"JFIF"); - m.extend_from_slice(&[ - 0, - 0x01, - 0x02, - match density.unit { - PixelDensityUnit::PixelAspectRatio => 0x00, - PixelDensityUnit::Inches => 0x01, - PixelDensityUnit::Centimeters => 0x02, - }, - ]); - m.extend_from_slice(&density.density.0.to_be_bytes()); - m.extend_from_slice(&density.density.1.to_be_bytes()); - m.extend_from_slice(&[0, 0]); -} - -fn build_frame_header( - m: &mut Vec, - precision: u8, - width: u16, - height: u16, - components: &[Component], -) { - m.clear(); - - m.push(precision); - m.extend_from_slice(&height.to_be_bytes()); - m.extend_from_slice(&width.to_be_bytes()); - m.push(components.len() as u8); - - for &comp in components { - let hv = (comp.h << 4) | comp.v; - m.extend_from_slice(&[comp.id, hv, comp.tq]); - } -} - -fn build_scan_header(m: &mut Vec, components: &[Component]) { - m.clear(); - - m.push(components.len() as u8); - - for &comp in components { - let tables = (comp.dc_table << 4) | comp.ac_table; - m.extend_from_slice(&[comp.id, tables]); - } - - // spectral start and end, approx. high and low - m.extend_from_slice(&[0, 63, 0]); -} - -fn build_huffman_segment( - m: &mut Vec, - class: u8, - destination: u8, - numcodes: &[u8; 16], - values: &[u8], -) { - m.clear(); - - let tcth = (class << 4) | destination; - m.push(tcth); - - m.extend_from_slice(numcodes); - - let sum: usize = numcodes.iter().map(|&x| x as usize).sum(); - - assert_eq!(sum, values.len()); - - m.extend_from_slice(values); -} - -fn build_quantization_segment(m: &mut Vec, precision: u8, identifier: u8, qtable: &[u8; 64]) { - m.clear(); - - let p = if precision == 8 { 0 } else { 1 }; - - let pqtq = (p << 4) | identifier; - m.push(pqtq); - - for &i in &UNZIGZAG[..] { - m.push(qtable[i as usize]); - } -} - -fn encode_coefficient(coefficient: i32) -> (u8, u16) { - let mut magnitude = coefficient.unsigned_abs() as u16; - let mut num_bits = 0u8; - - while magnitude > 0 { - magnitude >>= 1; - num_bits += 1; - } - - let mask = (1 << num_bits as usize) - 1; - - let val = if coefficient < 0 { - (coefficient - 1) as u16 & mask - } else { - coefficient as u16 & mask - }; - - (num_bits, val) -} - -#[inline] -fn rgb_to_ycbcr(pixel: P) -> (u8, u8, u8) { - let [r, g, b] = pixel.to_rgb().0; - let r: i32 = i32::from(r.to_u8().unwrap()); - let g: i32 = i32::from(g.to_u8().unwrap()); - let b: i32 = i32::from(b.to_u8().unwrap()); - - /* - JPEG RGB -> YCbCr is defined as following equations using Bt.601 Full Range matrix: - Y = 0.29900 * R + 0.58700 * G + 0.11400 * B - Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + 128 - Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + 128 - - To avoid using slow floating point conversion is done in fixed point, - using following coefficients with rounding to nearest integer mode: - */ - - const C_YR: i32 = 19595; // 0.29900 = 19595 * 2^-16 - const C_YG: i32 = 38469; // 0.58700 = 38469 * 2^-16 - const C_YB: i32 = 7471; // 0.11400 = 7471 * 2^-16 - const Y_ROUNDING: i32 = (1 << 15) - 1; // + 0.5 to perform rounding shift right in-place - const C_UR: i32 = 11059; // 0.16874 = 11059 * 2^-16 - const C_UG: i32 = 21709; // 0.33126 = 21709 * 2^-16 - const C_UB: i32 = 32768; // 0.5 = 32768 * 2^-16 - const UV_BIAS_ROUNDING: i32 = (128 * (1 << 16)) + ((1 << 15) - 1); // 128 + 0.5 = ((128 * (1 << 16)) + ((1 << 15) - 1)) * 2^-16 ; + 0.5 to perform rounding shift right in-place - const C_VR: i32 = C_UB; // 0.5 = 32768 * 2^-16 - const C_VG: i32 = 27439; // 0.41869 = 27439 * 2^-16 - const C_VB: i32 = 5329; // 0.08131409 = 5329 * 2^-16 - - let y = (C_YR * r + C_YG * g + C_YB * b + Y_ROUNDING) >> 16; - let cb = (-C_UR * r - C_UG * g + C_UB * b + UV_BIAS_ROUNDING) >> 16; - let cr = (C_VR * r - C_VG * g - C_VB * b + UV_BIAS_ROUNDING) >> 16; - - (y as u8, cb as u8, cr as u8) -} - -/// Returns the pixel at (x,y) if (x,y) is in the image, -/// otherwise the closest pixel in the image -#[inline] -fn pixel_at_or_near(source: &I, x: u32, y: u32) -> I::Pixel { - if source.in_bounds(x, y) { - source.get_pixel(x, y) - } else { - source.get_pixel(x.min(source.width() - 1), y.min(source.height() - 1)) - } -} - -fn copy_blocks_ycbcr( - source: &I, - x0: u32, - y0: u32, - yb: &mut [u8; 64], - cbb: &mut [u8; 64], - crb: &mut [u8; 64], -) { - for y in 0..8 { - for x in 0..8 { - let pixel = pixel_at_or_near(source, x + x0, y + y0); - let (yc, cb, cr) = rgb_to_ycbcr(pixel); - - yb[(y * 8 + x) as usize] = yc; - cbb[(y * 8 + x) as usize] = cb; - crb[(y * 8 + x) as usize] = cr; - } - } -} - -fn copy_blocks_gray(source: &I, x0: u32, y0: u32, gb: &mut [u8; 64]) { - use num_traits::cast::ToPrimitive; - for y in 0..8 { - for x in 0..8 { - let pixel = pixel_at_or_near(source, x0 + x, y0 + y); - let [luma] = pixel.to_luma().0; - gb[(y * 8 + x) as usize] = luma.to_u8().unwrap(); - } - } -} - #[cfg(test)] mod tests { use std::io::Cursor; @@ -670,12 +208,7 @@ mod tests { use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageError}; use crate::{ImageDecoder as _, ImageFormat}; - use super::super::JpegDecoder; - use super::{ - build_frame_header, build_huffman_segment, build_jfif_header, build_quantization_segment, - build_scan_header, Component, JpegEncoder, PixelDensity, DCCLASS, LUMADESTINATION, - STD_LUMA_DC_CODE_LENGTHS, STD_LUMA_DC_VALUES, - }; + use super::super::{JpegDecoder, JpegEncoder}; fn decode(encoded: &[u8]) -> Vec { let decoder = JpegDecoder::new(Cursor::new(encoded)).expect("Could not decode image"); @@ -740,31 +273,6 @@ mod tests { } } - #[test] - fn jfif_header_density_check() { - let mut buffer = Vec::new(); - build_jfif_header(&mut buffer, PixelDensity::dpi(300)); - assert_eq!( - buffer, - vec![ - b'J', - b'F', - b'I', - b'F', - 0, - 1, - 2, // JFIF version 1.2 - 1, // density is in dpi - 300u16.to_be_bytes()[0], - 300u16.to_be_bytes()[1], - 300u16.to_be_bytes()[0], - 300u16.to_be_bytes()[1], - 0, - 0, // No thumbnail - ] - ); - } - #[test] fn test_image_too_large() { // JPEG cannot encode images larger than 65,535×65,535 @@ -787,104 +295,6 @@ mod tests { } } - #[test] - fn test_build_jfif_header() { - let mut buf = vec![]; - let density = PixelDensity::dpi(100); - build_jfif_header(&mut buf, density); - assert_eq!( - buf, - [0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x02, 0x01, 0, 100, 0, 100, 0, 0] - ); - } - - #[test] - fn test_build_frame_header() { - let mut buf = vec![]; - let components = vec![ - Component { - id: 1, - h: 1, - v: 1, - tq: 5, - dc_table: 5, - ac_table: 5, - _dc_pred: 0, - }, - Component { - id: 2, - h: 1, - v: 1, - tq: 4, - dc_table: 4, - ac_table: 4, - _dc_pred: 0, - }, - ]; - build_frame_header(&mut buf, 5, 100, 150, &components); - assert_eq!( - buf, - [5, 0, 150, 0, 100, 2, 1, (1 << 4) | 1, 5, 2, (1 << 4) | 1, 4] - ); - } - - #[test] - fn test_build_scan_header() { - let mut buf = vec![]; - let components = vec![ - Component { - id: 1, - h: 1, - v: 1, - tq: 5, - dc_table: 5, - ac_table: 5, - _dc_pred: 0, - }, - Component { - id: 2, - h: 1, - v: 1, - tq: 4, - dc_table: 4, - ac_table: 4, - _dc_pred: 0, - }, - ]; - build_scan_header(&mut buf, &components); - assert_eq!(buf, [2, 1, (5 << 4) | 5, 2, (4 << 4) | 4, 0, 63, 0]); - } - - #[test] - fn test_build_huffman_segment() { - let mut buf = vec![]; - build_huffman_segment( - &mut buf, - DCCLASS, - LUMADESTINATION, - &STD_LUMA_DC_CODE_LENGTHS, - &STD_LUMA_DC_VALUES, - ); - assert_eq!( - buf, - vec![ - 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11 - ] - ); - } - - #[test] - fn test_build_quantization_segment() { - let mut buf = vec![]; - let qtable = [0u8; 64]; - build_quantization_segment(&mut buf, 8, 1, &qtable); - let mut expected = vec![]; - expected.push(1); - expected.extend_from_slice(&[0; 64]); - assert_eq!(buf, expected); - } - #[test] fn check_color_types() { const ALL: &[ColorType] = &[ From 0a845dd25653114ea7feb778ad120e9de8a64900 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:13:07 +0000 Subject: [PATCH 04/21] cargo fmt --- src/codecs/jpeg/encoder.rs | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index accb9e62a6..d74489c8ae 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -1,14 +1,8 @@ #![allow(clippy::too_many_arguments)] use std::io::Write; -use crate::error::{ - ImageError, ImageResult, UnsupportedError, - UnsupportedErrorKind, -}; -use crate::{ - ColorType, DynamicImage, ExtendedColorType, ImageEncoder, - ImageFormat, -}; +use crate::error::{ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind}; +use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat}; use jpeg_encoder::Encoder; @@ -59,8 +53,14 @@ impl PixelDensity { fn to_encoder_repr(&self) -> jpeg_encoder::Density { match self.unit { PixelDensityUnit::PixelAspectRatio => todo!(), // Not supported in jpeg-encoder? - PixelDensityUnit::Inches => jpeg_encoder::Density::Inch {x: self.density.0, y: self.density.1}, - PixelDensityUnit::Centimeters => jpeg_encoder::Density::Centimeter {x: self.density.0, y: self.density.1}, + PixelDensityUnit::Inches => jpeg_encoder::Density::Inch { + x: self.density.0, + y: self.density.1, + }, + PixelDensityUnit::Centimeters => jpeg_encoder::Density::Centimeter { + x: self.density.0, + y: self.density.1, + }, } } } @@ -127,7 +127,9 @@ impl JpegEncoder { // TODO: error out instead of panicking let width: u16 = width.try_into().expect("width too large to encode in JPEG"); - let height: u16 = height.try_into().expect("height too large to encode in JPEG"); + let height: u16 = height + .try_into() + .expect("height too large to encode in JPEG"); match color_type { ExtendedColorType::L8 => { @@ -149,6 +151,7 @@ impl JpegEncoder { fn write_exif(&mut self) -> ImageResult<()> { todo!(); // no convenience method in jpeg-encoder + // if !self.exif.is_empty() { // let mut formatted = EXIF_HEADER.to_vec(); // formatted.extend_from_slice(&self.exif); @@ -327,4 +330,4 @@ mod tests { let _x = JpegEncoder::new(&mut y); }); } -} \ No newline at end of file +} From 1e50e532e6960bf467af14e91e32f7d9302af0d1 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:16:38 +0000 Subject: [PATCH 05/21] Error handling in setting ICC profile --- src/codecs/jpeg/encoder.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index d74489c8ae..bc52387c6d 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -175,8 +175,12 @@ impl ImageEncoder for JpegEncoder { } fn set_icc_profile(&mut self, icc_profile: Vec) -> Result<(), UnsupportedError> { - self.encoder.add_icc_profile(&icc_profile); - Ok(()) + self.encoder.add_icc_profile(&icc_profile).map_err(|e| { + UnsupportedError::from_format_and_kind( + ImageFormat::Jpeg.into(), + UnsupportedErrorKind::GenericFeature("ICC chunk too large".to_string()), + ) + }) } fn set_exif_metadata(&mut self, exif: Vec) -> Result<(), UnsupportedError> { From 0823351df5747383b8d43edd18bd0fb56b0b4cc8 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:21:02 +0000 Subject: [PATCH 06/21] Reinstate the DimensionMismatch errors when passing images that are too large --- src/codecs/jpeg/encoder.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index bc52387c6d..bec25bfaaa 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -1,7 +1,7 @@ #![allow(clippy::too_many_arguments)] use std::io::Write; -use crate::error::{ImageError, ImageResult, UnsupportedError, UnsupportedErrorKind}; +use crate::error::{ImageError, ImageResult, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind}; use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat}; use jpeg_encoder::Encoder; @@ -125,11 +125,8 @@ impl JpegEncoder { image.len(), ); - // TODO: error out instead of panicking - let width: u16 = width.try_into().expect("width too large to encode in JPEG"); - let height: u16 = height - .try_into() - .expect("height too large to encode in JPEG"); + let width: u16 = width.try_into().map_err(|_| ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::DimensionMismatch)))?; + let height: u16 = height.try_into().map_err(|_| ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::DimensionMismatch)))?; match color_type { ExtendedColorType::L8 => { From b25355f975abd4203a74783e2e1bf54c938ee097 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:34:13 +0000 Subject: [PATCH 07/21] Fulfill an old TODO to return an EncodingError instead of a DimensionError --- src/codecs/jpeg/encoder.rs | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index bec25bfaaa..8e859643fe 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -1,7 +1,10 @@ #![allow(clippy::too_many_arguments)] use std::io::Write; -use crate::error::{ImageError, ImageResult, ParameterError, ParameterErrorKind, UnsupportedError, UnsupportedErrorKind}; +use crate::error::{ + EncodingError, ImageError, ImageFormatHint, ImageResult, ParameterError, ParameterErrorKind, + UnsupportedError, UnsupportedErrorKind, +}; use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat}; use jpeg_encoder::Encoder; @@ -125,8 +128,17 @@ impl JpegEncoder { image.len(), ); - let width: u16 = width.try_into().map_err(|_| ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::DimensionMismatch)))?; - let height: u16 = height.try_into().map_err(|_| ImageError::Parameter(ParameterError::from_kind(ParameterErrorKind::DimensionMismatch)))?; + let dimension_err = || { + ImageError::Encoding(EncodingError::new( + ImageFormatHint::Exact(ImageFormat::Jpeg), + ImageError::Parameter(ParameterError::from_kind( + ParameterErrorKind::DimensionMismatch, + )), + )) + }; + + let width: u16 = width.try_into().map_err(|_| dimension_err())?; + let height: u16 = height.try_into().map_err(|_| dimension_err())?; match color_type { ExtendedColorType::L8 => { @@ -208,7 +220,6 @@ mod tests { #[cfg(feature = "benchmarks")] use test::Bencher; - use crate::error::ParameterErrorKind::DimensionMismatch; use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageError}; use crate::{ImageDecoder as _, ImageFormat}; @@ -287,12 +298,10 @@ mod tests { let encoder = JpegEncoder::new_with_quality(&mut encoded, 100); let result = encoder.write_image(&img, 65_536, 1, ExtendedColorType::L8); match result { - Err(ImageError::Parameter(err)) => { - assert_eq!(err.kind(), DimensionMismatch); - } + Err(ImageError::Encoding(_)) => (), other => { panic!( - "Encoding an image that is too large should return a DimensionError \ + "Encoding an image that is too large should return an EncodingError \ it returned {other:?} instead" ) } From 78c14058fc7f0e6d1ca4583184999e6172f41289 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:49:31 +0000 Subject: [PATCH 08/21] Wire up writing Exif --- src/codecs/jpeg/encoder.rs | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 8e859643fe..1163abe9f2 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -81,6 +81,7 @@ impl Default for PixelDensity { /// The representation of a JPEG encoder pub struct JpegEncoder { encoder: Encoder, + exif: Vec, } impl JpegEncoder { @@ -95,6 +96,7 @@ impl JpegEncoder { pub fn new_with_quality(w: W, quality: u8) -> JpegEncoder { JpegEncoder { encoder: Encoder::new(w, quality), + exif: Vec::new(), } } @@ -114,7 +116,7 @@ impl JpegEncoder { /// Panics if `width * height * color_type.bytes_per_pixel() != image.len()`. #[track_caller] fn encode( - self, + mut self, image: &[u8], width: u32, height: u32, @@ -140,6 +142,8 @@ impl JpegEncoder { let width: u16 = width.try_into().map_err(|_| dimension_err())?; let height: u16 = height.try_into().map_err(|_| dimension_err())?; + self.write_exif()?; + match color_type { ExtendedColorType::L8 => { let color = jpeg_encoder::ColorType::Luma; @@ -159,18 +163,28 @@ impl JpegEncoder { } fn write_exif(&mut self) -> ImageResult<()> { - todo!(); // no convenience method in jpeg-encoder - - // if !self.exif.is_empty() { - // let mut formatted = EXIF_HEADER.to_vec(); - // formatted.extend_from_slice(&self.exif); - // self.writer.write_segment(APP1, &formatted)?; - // } - // - // Ok(()) + if !self.exif.is_empty() { + let mut formatted = EXIF_HEADER.to_vec(); + formatted.extend_from_slice(&self.exif); + self.encoder + .add_app_segment(APP1, &formatted) + .map_err(|_| { + ImageError::Unsupported(UnsupportedError::from_format_and_kind( + ImageFormat::Jpeg.into(), + UnsupportedErrorKind::GenericFeature("Exif chunk too large".to_string()), + )) + })?; + } + + Ok(()) } } +// E x i f \0 \0 +/// The header for an EXIF APP1 segment +const EXIF_HEADER: [u8; 6] = [0x45, 0x78, 0x69, 0x66, 0x00, 0x00]; +const APP1: u8 = 0xE1; + impl ImageEncoder for JpegEncoder { #[track_caller] fn write_image( @@ -184,7 +198,7 @@ impl ImageEncoder for JpegEncoder { } fn set_icc_profile(&mut self, icc_profile: Vec) -> Result<(), UnsupportedError> { - self.encoder.add_icc_profile(&icc_profile).map_err(|e| { + self.encoder.add_icc_profile(&icc_profile).map_err(|_| { UnsupportedError::from_format_and_kind( ImageFormat::Jpeg.into(), UnsupportedErrorKind::GenericFeature("ICC chunk too large".to_string()), @@ -193,7 +207,7 @@ impl ImageEncoder for JpegEncoder { } fn set_exif_metadata(&mut self, exif: Vec) -> Result<(), UnsupportedError> { - todo!(); // no convenience method in jpeg-encoder yet + self.exif = exif; Ok(()) } From 4f530ef975767bdb6ff0fc4d1202c6450f4bb4fd Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 15:55:50 +0000 Subject: [PATCH 09/21] add a test for roundtripping Exif and ICC --- src/codecs/jpeg/encoder.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 1163abe9f2..c6028a98a9 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -302,6 +302,41 @@ mod tests { } } + #[test] + fn roundtrip_exif_icc() { + // create a 2x2 8-bit image buffer containing a white diagonal + let img = [255u8, 0, 0, 255]; + + let exif = vec![1, 2, 3]; + let icc = vec![4, 5, 6]; + + // encode it into a memory buffer + let mut encoded_img = Vec::new(); + { + let mut encoder = JpegEncoder::new_with_quality(&mut encoded_img, 100); + + encoder.set_exif_metadata(exif.clone()).unwrap(); + encoder.set_icc_profile(icc.clone()).unwrap(); + + encoder + .write_image(&img[..], 2, 2, ExtendedColorType::L8) + .expect("Could not encode image"); + } + + let mut decoder = + JpegDecoder::new(Cursor::new(encoded_img)).expect("Could not decode image"); + let decoded_exif = decoder + .exif_metadata() + .expect("Error decoding Exif") + .expect("Exif is empty"); + assert_eq!(exif, decoded_exif); + let decoded_icc = decoder + .icc_profile() + .expect("Error decoding ICC") + .expect("ICC is empty"); + assert_eq!(icc, decoded_icc); + } + #[test] fn test_image_too_large() { // JPEG cannot encode images larger than 65,535×65,535 From db9ae3fe458d551b3dc64ba72301edf601ebf631 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 16:02:01 +0000 Subject: [PATCH 10/21] Fix Exif roundtrip --- src/codecs/jpeg/encoder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index c6028a98a9..b00fb9e6c5 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -183,7 +183,7 @@ impl JpegEncoder { // E x i f \0 \0 /// The header for an EXIF APP1 segment const EXIF_HEADER: [u8; 6] = [0x45, 0x78, 0x69, 0x66, 0x00, 0x00]; -const APP1: u8 = 0xE1; +const APP1: u8 = 1; impl ImageEncoder for JpegEncoder { #[track_caller] From a4315047cbb3a29450a362eb65dd71ef96e58e47 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 16:07:19 +0000 Subject: [PATCH 11/21] Error handling in encoding --- src/codecs/jpeg/encoder.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index b00fb9e6c5..98bf157f51 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -144,14 +144,25 @@ impl JpegEncoder { self.write_exif()?; + let encode_jpeg = |color: jpeg_encoder::ColorType| { + self.encoder + .encode(image, width, height, color) + .map_err(|err| { + ImageError::Encoding(EncodingError::new( + ImageFormatHint::Exact(ImageFormat::Jpeg), + err, + )) + }) + }; + match color_type { ExtendedColorType::L8 => { let color = jpeg_encoder::ColorType::Luma; - Ok(self.encoder.encode(image, width, height, color).unwrap()) // TODO: error handling + encode_jpeg(color) } ExtendedColorType::Rgb8 => { let color = jpeg_encoder::ColorType::Rgb; - Ok(self.encoder.encode(image, width, height, color).unwrap()) // TODO: error handling + encode_jpeg(color) } _ => Err(ImageError::Unsupported( UnsupportedError::from_format_and_kind( From 819b0590a21a4791290508ebd5a37c69193d4118 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 16:31:45 +0000 Subject: [PATCH 12/21] Remove last vestiges of in-tree JPEG encoder --- src/codecs/jpeg/entropy.rs | 63 ----------- src/codecs/jpeg/mod.rs | 2 - src/codecs/jpeg/transform.rs | 196 ----------------------------------- 3 files changed, 261 deletions(-) delete mode 100644 src/codecs/jpeg/entropy.rs delete mode 100644 src/codecs/jpeg/transform.rs diff --git a/src/codecs/jpeg/entropy.rs b/src/codecs/jpeg/entropy.rs deleted file mode 100644 index 5bdcef6a37..0000000000 --- a/src/codecs/jpeg/entropy.rs +++ /dev/null @@ -1,63 +0,0 @@ -/// Given an array containing the number of codes of each code length, -/// this function generates the huffman codes lengths and their respective -/// code lengths as specified by the JPEG spec. -const fn derive_codes_and_sizes(bits: &[u8; 16]) -> ([u8; 256], [u16; 256]) { - let mut huffsize = [0u8; 256]; - let mut huffcode = [0u16; 256]; - - let mut k = 0; - - // Annex C.2 - // Figure C.1 - // Generate table of individual code lengths - let mut i = 0; - while i < 16 { - let mut j = 0; - while j < bits[i as usize] { - huffsize[k] = i + 1; - k += 1; - j += 1; - } - i += 1; - } - - huffsize[k] = 0; - - // Annex C.2 - // Figure C.2 - // Generate table of huffman codes - k = 0; - let mut code = 0u16; - let mut size = huffsize[0]; - - while huffsize[k] != 0 { - huffcode[k] = code; - code += 1; - k += 1; - - if huffsize[k] == size { - continue; - } - - // FIXME there is something wrong with this code - let diff = huffsize[k].wrapping_sub(size); - code = if diff < 16 { code << diff as usize } else { 0 }; - - size = size.wrapping_add(diff); - } - - (huffsize, huffcode) -} - -pub(crate) const fn build_huff_lut_const(bits: &[u8; 16], huffval: &[u8]) -> [(u8, u16); 256] { - let mut lut = [(17u8, 0u16); 256]; - let (huffsize, huffcode) = derive_codes_and_sizes(bits); - - let mut i = 0; - while i < huffval.len() { - lut[huffval[i] as usize] = (huffsize[i], huffcode[i]); - i += 1; - } - - lut -} diff --git a/src/codecs/jpeg/mod.rs b/src/codecs/jpeg/mod.rs index 65ebecddbc..666feb8f27 100644 --- a/src/codecs/jpeg/mod.rs +++ b/src/codecs/jpeg/mod.rs @@ -11,5 +11,3 @@ pub use self::encoder::{JpegEncoder, PixelDensity, PixelDensityUnit}; mod decoder; mod encoder; -mod entropy; -mod transform; diff --git a/src/codecs/jpeg/transform.rs b/src/codecs/jpeg/transform.rs deleted file mode 100644 index 1ca01a9b52..0000000000 --- a/src/codecs/jpeg/transform.rs +++ /dev/null @@ -1,196 +0,0 @@ -/* -fdct is a Rust translation of jfdctint.c from the -Independent JPEG Group's libjpeg version 9a -obtained from http://www.ijg.org/files/jpegsr9a.zip -It comes with the following conditions of distribution and use: - - In plain English: - - 1. We don't promise that this software works. (But if you find any bugs, - please let us know!) - 2. You can use this software for whatever you want. You don't have to pay us. - 3. You may not pretend that you wrote this software. If you use it in a - program, you must acknowledge somewhere in your documentation that - you've used the IJG code. - - In legalese: - - The authors make NO WARRANTY or representation, either express or implied, - with respect to this software, its quality, accuracy, merchantability, or - fitness for a particular purpose. This software is provided "AS IS", and you, - its user, assume the entire risk as to its quality and accuracy. - - This software is copyright (C) 1991-2014, Thomas G. Lane, Guido Vollbeding. - All Rights Reserved except as specified below. - - Permission is hereby granted to use, copy, modify, and distribute this - software (or portions thereof) for any purpose, without fee, subject to these - conditions: - (1) If any part of the source code for this software is distributed, then this - README file must be included, with this copyright and no-warranty notice - unaltered; and any additions, deletions, or changes to the original files - must be clearly indicated in accompanying documentation. - (2) If only executable code is distributed, then the accompanying - documentation must state that "this software is based in part on the work of - the Independent JPEG Group". - (3) Permission for use of this software is granted only if the user accepts - full responsibility for any undesirable consequences; the authors accept - NO LIABILITY for damages of any kind. - - These conditions apply to any software derived from or based on the IJG code, - not just to the unmodified library. If you use our work, you ought to - acknowledge us. - - Permission is NOT granted for the use of any IJG author's name or company name - in advertising or publicity relating to this software or products derived from - it. This software may be referred to only as "the Independent JPEG Group's - software". - - We specifically permit and encourage the use of this software as the basis of - commercial products, provided that all warranty or liability claims are - assumed by the product vendor. -*/ - -static CONST_BITS: i32 = 13; -static PASS1_BITS: i32 = 2; - -static FIX_0_298631336: i32 = 2446; -static FIX_0_390180644: i32 = 3196; -static FIX_0_541196100: i32 = 4433; -static FIX_0_765366865: i32 = 6270; -static FIX_0_899976223: i32 = 7373; -static FIX_1_175875602: i32 = 9633; -static FIX_1_501321110: i32 = 12_299; -static FIX_1_847759065: i32 = 15_137; -static FIX_1_961570560: i32 = 16_069; -static FIX_2_053119869: i32 = 16_819; -static FIX_2_562915447: i32 = 20_995; -static FIX_3_072711026: i32 = 25_172; - -pub(crate) fn fdct(samples: &[u8; 64], coeffs: &mut [i32; 64]) { - // Pass 1: process rows. - // Results are scaled by sqrt(8) compared to a true DCT - // furthermore we scale the results by 2**PASS1_BITS - for y in 0usize..8 { - let y0 = y * 8; - - // Even part - let t0 = i32::from(samples[y0]) + i32::from(samples[y0 + 7]); - let t1 = i32::from(samples[y0 + 1]) + i32::from(samples[y0 + 6]); - let t2 = i32::from(samples[y0 + 2]) + i32::from(samples[y0 + 5]); - let t3 = i32::from(samples[y0 + 3]) + i32::from(samples[y0 + 4]); - - let t10 = t0 + t3; - let t12 = t0 - t3; - let t11 = t1 + t2; - let t13 = t1 - t2; - - let t0 = i32::from(samples[y0]) - i32::from(samples[y0 + 7]); - let t1 = i32::from(samples[y0 + 1]) - i32::from(samples[y0 + 6]); - let t2 = i32::from(samples[y0 + 2]) - i32::from(samples[y0 + 5]); - let t3 = i32::from(samples[y0 + 3]) - i32::from(samples[y0 + 4]); - - // Apply unsigned -> signed conversion - coeffs[y0] = (t10 + t11 - 8 * 128) << PASS1_BITS as usize; - coeffs[y0 + 4] = (t10 - t11) << PASS1_BITS as usize; - - let mut z1 = (t12 + t13) * FIX_0_541196100; - // Add fudge factor here for final descale - z1 += 1 << (CONST_BITS - PASS1_BITS - 1) as usize; - - coeffs[y0 + 2] = (z1 + t12 * FIX_0_765366865) >> (CONST_BITS - PASS1_BITS) as usize; - coeffs[y0 + 6] = (z1 - t13 * FIX_1_847759065) >> (CONST_BITS - PASS1_BITS) as usize; - - // Odd part - let t12 = t0 + t2; - let t13 = t1 + t3; - - let mut z1 = (t12 + t13) * FIX_1_175875602; - // Add fudge factor here for final descale - z1 += 1 << (CONST_BITS - PASS1_BITS - 1) as usize; - - let mut t12 = t12 * (-FIX_0_390180644); - let mut t13 = t13 * (-FIX_1_961570560); - t12 += z1; - t13 += z1; - - let z1 = (t0 + t3) * (-FIX_0_899976223); - let mut t0 = t0 * FIX_1_501321110; - let mut t3 = t3 * FIX_0_298631336; - t0 += z1 + t12; - t3 += z1 + t13; - - let z1 = (t1 + t2) * (-FIX_2_562915447); - let mut t1 = t1 * FIX_3_072711026; - let mut t2 = t2 * FIX_2_053119869; - t1 += z1 + t13; - t2 += z1 + t12; - - coeffs[y0 + 1] = t0 >> (CONST_BITS - PASS1_BITS) as usize; - coeffs[y0 + 3] = t1 >> (CONST_BITS - PASS1_BITS) as usize; - coeffs[y0 + 5] = t2 >> (CONST_BITS - PASS1_BITS) as usize; - coeffs[y0 + 7] = t3 >> (CONST_BITS - PASS1_BITS) as usize; - } - - // Pass 2: process columns - // We remove the PASS1_BITS scaling but leave the results scaled up an - // overall factor of 8 - for x in (0usize..8).rev() { - // Even part - let t0 = coeffs[x] + coeffs[x + 8 * 7]; - let t1 = coeffs[x + 8] + coeffs[x + 8 * 6]; - let t2 = coeffs[x + 8 * 2] + coeffs[x + 8 * 5]; - let t3 = coeffs[x + 8 * 3] + coeffs[x + 8 * 4]; - - // Add fudge factor here for final descale - let t10 = t0 + t3 + (1 << (PASS1_BITS - 1) as usize); - let t12 = t0 - t3; - let t11 = t1 + t2; - let t13 = t1 - t2; - - let t0 = coeffs[x] - coeffs[x + 8 * 7]; - let t1 = coeffs[x + 8] - coeffs[x + 8 * 6]; - let t2 = coeffs[x + 8 * 2] - coeffs[x + 8 * 5]; - let t3 = coeffs[x + 8 * 3] - coeffs[x + 8 * 4]; - - coeffs[x] = (t10 + t11) >> PASS1_BITS as usize; - coeffs[x + 8 * 4] = (t10 - t11) >> PASS1_BITS as usize; - - let mut z1 = (t12 + t13) * FIX_0_541196100; - // Add fudge factor here for final descale - z1 += 1 << (CONST_BITS + PASS1_BITS - 1) as usize; - - coeffs[x + 8 * 2] = (z1 + t12 * FIX_0_765366865) >> (CONST_BITS + PASS1_BITS) as usize; - coeffs[x + 8 * 6] = (z1 - t13 * FIX_1_847759065) >> (CONST_BITS + PASS1_BITS) as usize; - - // Odd part - let t12 = t0 + t2; - let t13 = t1 + t3; - - let mut z1 = (t12 + t13) * FIX_1_175875602; - // Add fudge factor here for final descale - z1 += 1 << (CONST_BITS - PASS1_BITS - 1) as usize; - - let mut t12 = t12 * (-FIX_0_390180644); - let mut t13 = t13 * (-FIX_1_961570560); - t12 += z1; - t13 += z1; - - let z1 = (t0 + t3) * (-FIX_0_899976223); - let mut t0 = t0 * FIX_1_501321110; - let mut t3 = t3 * FIX_0_298631336; - t0 += z1 + t12; - t3 += z1 + t13; - - let z1 = (t1 + t2) * (-FIX_2_562915447); - let mut t1 = t1 * FIX_3_072711026; - let mut t2 = t2 * FIX_2_053119869; - t1 += z1 + t13; - t2 += z1 + t12; - - coeffs[x + 8] = t0 >> (CONST_BITS + PASS1_BITS) as usize; - coeffs[x + 8 * 3] = t1 >> (CONST_BITS + PASS1_BITS) as usize; - coeffs[x + 8 * 5] = t2 >> (CONST_BITS + PASS1_BITS) as usize; - coeffs[x + 8 * 7] = t3 >> (CONST_BITS + PASS1_BITS) as usize; - } -} From bf2b2d05272c4fcb59d829f5e3793f25184a428c Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Thu, 30 Oct 2025 17:52:22 +0000 Subject: [PATCH 13/21] Replace todo!() with an interim solution that doesn't panic --- src/codecs/jpeg/encoder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 98bf157f51..53e0b028a7 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -55,7 +55,7 @@ impl PixelDensity { /// Converts pixel density to the representation used by jpeg-encoder crate fn to_encoder_repr(&self) -> jpeg_encoder::Density { match self.unit { - PixelDensityUnit::PixelAspectRatio => todo!(), // Not supported in jpeg-encoder? + PixelDensityUnit::PixelAspectRatio => jpeg_encoder::Density::None, // TODO: https://github.com/vstroebel/jpeg-encoder/issues/21 PixelDensityUnit::Inches => jpeg_encoder::Density::Inch { x: self.density.0, y: self.density.1, From a22a2f7cb9928cb12e0760e3a49009f231aa0673 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 20:52:05 +0000 Subject: [PATCH 14/21] Replace previous ad-hoc error with usage of the custom EncoderError type --- src/codecs/jpeg/encoder.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 8449d31468..7873b1afd7 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -157,18 +157,11 @@ impl JpegEncoder { image.len(), ); - let dimension_err = || { - ImageError::Encoding(EncodingError::new( - ImageFormatHint::Exact(ImageFormat::Jpeg), - ImageError::Parameter(ParameterError::from_kind( - ParameterErrorKind::DimensionMismatch, - )), - )) + let (width, height) = match (u16::try_from(width), u16::try_from(height)) { + (Ok(w @ 1..), Ok(h @ 1..)) => (w, h), + _ => return Err(EncoderError::InvalidSize(width, height).into()), }; - let width: u16 = width.try_into().map_err(|_| dimension_err())?; - let height: u16 = height.try_into().map_err(|_| dimension_err())?; - self.write_exif()?; let encode_jpeg = |color: jpeg_encoder::ColorType| { From 8e7df44ae1e3a14ee7663c50a6d4ffac928d9a23 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 21:03:19 +0000 Subject: [PATCH 15/21] Drop unused imports --- src/codecs/jpeg/encoder.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 7873b1afd7..5872b94a71 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -3,8 +3,7 @@ use std::io::Write; use std::{error, fmt}; use crate::error::{ - EncodingError, ImageError, ImageFormatHint, ImageResult, ParameterError, ParameterErrorKind, - UnsupportedError, UnsupportedErrorKind, + EncodingError, ImageError, ImageFormatHint, ImageResult, UnsupportedError, UnsupportedErrorKind, }; use crate::{ColorType, DynamicImage, ExtendedColorType, ImageEncoder, ImageFormat}; From a7fef3c7f41326fa463195e9df1f871137e1a4f1 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 21:03:45 +0000 Subject: [PATCH 16/21] Satisfy clippy --- src/codecs/jpeg/encoder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 5872b94a71..a62b2d33c5 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -53,7 +53,7 @@ impl PixelDensity { } /// Converts pixel density to the representation used by jpeg-encoder crate - fn to_encoder_repr(&self) -> jpeg_encoder::Density { + fn to_encoder_repr(self) -> jpeg_encoder::Density { match self.unit { PixelDensityUnit::PixelAspectRatio => jpeg_encoder::Density::None, // TODO: https://github.com/vstroebel/jpeg-encoder/issues/21 PixelDensityUnit::Inches => jpeg_encoder::Density::Inch { From 0dcffea1fe80b0c208655f85624a116f83b6b1b9 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 21:08:36 +0000 Subject: [PATCH 17/21] Fix encoding benchmark --- benches/encode.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/benches/encode.rs b/benches/encode.rs index 5f74cc9bc5..6a81829ef9 100644 --- a/benches/encode.rs +++ b/benches/encode.rs @@ -1,8 +1,8 @@ extern crate criterion; use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; -use image::ExtendedColorType; use image::{codecs::bmp::BmpEncoder, codecs::jpeg::JpegEncoder, ColorType}; +use image::{ExtendedColorType, ImageEncoder}; use std::fs::File; use std::io::{BufWriter, Seek, SeekFrom, Write}; @@ -128,7 +128,7 @@ impl EncoderBase for Bmp { impl EncoderBase for Jpeg { fn encode(&self, mut into: impl Write, im: &[u8], size: u32, color: ExtendedColorType) { - let mut x = JpegEncoder::new(&mut into); - x.encode(im, size, size, color).unwrap(); + let x = JpegEncoder::new(&mut into); + x.write_image(im, size, size, color).unwrap(); } } From e7a31cc182fd435e438a74cb8489bbfb1ebe5380 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 22:07:25 +0000 Subject: [PATCH 18/21] Do not defer writing Exif metadata to the encoder --- src/codecs/jpeg/encoder.rs | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index a62b2d33c5..31c37ba7be 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -107,7 +107,6 @@ impl error::Error for EncoderError {} /// The representation of a JPEG encoder pub struct JpegEncoder { encoder: Encoder, - exif: Vec, } impl JpegEncoder { @@ -122,7 +121,6 @@ impl JpegEncoder { pub fn new_with_quality(w: W, quality: u8) -> JpegEncoder { JpegEncoder { encoder: Encoder::new(w, quality), - exif: Vec::new(), } } @@ -142,7 +140,7 @@ impl JpegEncoder { /// Panics if `width * height * color_type.bytes_per_pixel() != image.len()`. #[track_caller] fn encode( - mut self, + self, image: &[u8], width: u32, height: u32, @@ -161,8 +159,6 @@ impl JpegEncoder { _ => return Err(EncoderError::InvalidSize(width, height).into()), }; - self.write_exif()?; - let encode_jpeg = |color: jpeg_encoder::ColorType| { self.encoder .encode(image, width, height, color) @@ -191,23 +187,6 @@ impl JpegEncoder { )), } } - - fn write_exif(&mut self) -> ImageResult<()> { - if !self.exif.is_empty() { - let mut formatted = EXIF_HEADER.to_vec(); - formatted.extend_from_slice(&self.exif); - self.encoder - .add_app_segment(APP1, &formatted) - .map_err(|_| { - ImageError::Unsupported(UnsupportedError::from_format_and_kind( - ImageFormat::Jpeg.into(), - UnsupportedErrorKind::GenericFeature("Exif chunk too large".to_string()), - )) - })?; - } - - Ok(()) - } } // E x i f \0 \0 @@ -237,7 +216,16 @@ impl ImageEncoder for JpegEncoder { } fn set_exif_metadata(&mut self, exif: Vec) -> Result<(), UnsupportedError> { - self.exif = exif; + let mut formatted = EXIF_HEADER.to_vec(); + formatted.extend_from_slice(&exif); + self.encoder + .add_app_segment(APP1, &formatted) + .map_err(|_| { + UnsupportedError::from_format_and_kind( + ImageFormat::Jpeg.into(), + UnsupportedErrorKind::GenericFeature("Exif chunk too large".to_string()), + ) + })?; Ok(()) } From 274bc19dd19e9b03d824083f116ae408d1aca3f2 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Sun, 2 Nov 2025 22:11:18 +0000 Subject: [PATCH 19/21] Explicitly allow IJG in deny.toml to admit jpeg-encoder as a dependency. It is a highly permissive license comparable to MIT. --- deny.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/deny.toml b/deny.toml index 154ed08bed..d066fa25a2 100644 --- a/deny.toml +++ b/deny.toml @@ -20,6 +20,7 @@ allow = [ "BSD-3-Clause", "MIT", "Unicode-3.0", + "IJG", # for parts of jpeg-encoder ported from IJG libjpeg; highly permissive ] [[licenses.exceptions]] From 1f2b19c8e8e1f03e2c337aecf5ad5f999aa5e227 Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Mon, 3 Nov 2025 00:10:16 +0000 Subject: [PATCH 20/21] Add a method for controlling subsampling mode --- src/codecs/jpeg/encoder.rs | 42 ++++++++++++++++++++++++++++++++++++++ src/codecs/jpeg/mod.rs | 2 +- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index 31c37ba7be..e34c977864 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -23,6 +23,38 @@ pub enum PixelDensityUnit { Centimeters, } +/// Controls the resolution of the color information. +/// +/// Human eye is much less sensitive to the detail of color than brightness. +/// JPEG can exploit this to significantly reduce the file size by storing color information +/// (Cb and Cr channels) in a lower resolution than brightness (Y channel) without visual quality loss. +/// +/// See the documentation on each variant for details. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum ChromaSubsampling { + /// **4:4:4** Color information is encoded in full resolution. Results in larger file size. + /// + /// Recommended when the image has small brightly colored elements, e.g. artwork or screenshots. + S444, + /// **4:2:2** The resolution of color information is reduced by a factor of 2 in the horizontal direction. + S422, + /// **4:2:0** The resolution of color information is reduced by a factor of 2 both horizontally and vertically. + /// + /// Results in a smaller file size. Well suited for photographs where it incurs no visial quality loss. + S420, +} + +impl ChromaSubsampling { + fn to_encoder_repr(self) -> jpeg_encoder::SamplingFactor { + match self { + ChromaSubsampling::S444 => jpeg_encoder::SamplingFactor::R_4_4_4, + ChromaSubsampling::S422 => jpeg_encoder::SamplingFactor::R_4_2_2, + ChromaSubsampling::S420 => jpeg_encoder::SamplingFactor::R_4_2_0, + } + } +} + /// Represents the pixel density of an image /// /// For example, a 300 DPI image is represented by: @@ -118,12 +150,22 @@ impl JpegEncoder { /// Create a new encoder that writes its output to ```w```, and has /// the quality parameter ```quality``` with a value in the range 1-100 /// where 1 is the worst and 100 is the best. + /// + /// By default quality settings 90 or above use [chroma subsampling](ChromaSubsampling) + /// mode [4:4:4](ChromaSubsampling::S444), while quality below 90 subsampling mode + /// [4:2:0](ChromaSubsampling::S420). + /// This can be overridden using [Self::set_chroma_subsampling]. pub fn new_with_quality(w: W, quality: u8) -> JpegEncoder { JpegEncoder { encoder: Encoder::new(w, quality), } } + /// Sets the chroma subsampling mode. See [ChromaSubsampling] for details. + pub fn set_chroma_subsampling(&mut self, sampling: ChromaSubsampling) { + self.encoder.set_sampling_factor(sampling.to_encoder_repr()); + } + /// Set the pixel density of the images the encoder will encode. /// If this method is not called, then a default pixel aspect ratio of 1x1 will be applied, /// and no DPI information will be stored in the image. diff --git a/src/codecs/jpeg/mod.rs b/src/codecs/jpeg/mod.rs index 666feb8f27..74625bcf9e 100644 --- a/src/codecs/jpeg/mod.rs +++ b/src/codecs/jpeg/mod.rs @@ -7,7 +7,7 @@ //! * - The JPEG specification pub use self::decoder::JpegDecoder; -pub use self::encoder::{JpegEncoder, PixelDensity, PixelDensityUnit}; +pub use self::encoder::{ChromaSubsampling, JpegEncoder, PixelDensity, PixelDensityUnit}; mod decoder; mod encoder; From 31eef2cb2d6490ebe0b71cf8c6411abd229ab04e Mon Sep 17 00:00:00 2001 From: "Sergey \"Shnatsel\" Davidoff" Date: Mon, 3 Nov 2025 00:15:14 +0000 Subject: [PATCH 21/21] Expose a function to control optimizing Huffman tables --- src/codecs/jpeg/encoder.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/codecs/jpeg/encoder.rs b/src/codecs/jpeg/encoder.rs index e34c977864..45cb99af5e 100644 --- a/src/codecs/jpeg/encoder.rs +++ b/src/codecs/jpeg/encoder.rs @@ -166,6 +166,13 @@ impl JpegEncoder { self.encoder.set_sampling_factor(sampling.to_encoder_repr()); } + /// Spend extra time optimizing Huffman tables. Slightly reduces file size at the cost of encoding speed. + /// + /// Defaults to **false**. + pub fn set_optimize_huffman_tables(&mut self, optimize: bool) { + self.encoder.set_optimized_huffman_tables(optimize); + } + /// Set the pixel density of the images the encoder will encode. /// If this method is not called, then a default pixel aspect ratio of 1x1 will be applied, /// and no DPI information will be stored in the image.