From a9ad83f68bf1c0ee61d4493ac7aa394f5839fa5f Mon Sep 17 00:00:00 2001 From: Sergio Gonzalez Martin Date: Tue, 10 Nov 2026 12:05:46 +0000 Subject: [PATCH 1/8] Add opt-in exact reciprocal quantization and fix average-subsampling bottom padding Add Encoder::set_exact_quantization to opt into 16-bit variable-shift reciprocal quantization matching libjpeg-turbo's compute_reciprocal, while keeping the existing 15-bit fixed shift as the default. When ChromaSubsamplingMethod::Average is used on images whose height is not a multiple of the vertical MCU size, clamp the vertical row index in get_block_averaged so bottom padding repeats the last downsampled row (matching libjpeg's expand_bottom_edge) instead of averaging the repeated bottom input row. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/encoder.rs | 73 ++++++++++++++++++++++++++++++++++---- src/lib.rs | 25 +++++++++++++ src/quantization.rs | 85 ++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 169 insertions(+), 14 deletions(-) diff --git a/src/encoder.rs b/src/encoder.rs index 5f41217..60db579 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -236,6 +236,7 @@ pub struct Encoder { restart_interval: Option, optimize_huffman_table: bool, + exact_quantization: bool, app_segments: Vec<(u8, Vec)>, } @@ -281,6 +282,7 @@ impl Encoder { progressive_scans: None, restart_interval: None, optimize_huffman_table: false, + exact_quantization: false, app_segments: Vec::new(), } } @@ -394,6 +396,18 @@ impl Encoder { self.optimize_huffman_table } + /// Set if exact 16-bit reciprocal quantization matching libjpeg should be used. + /// + /// By default, a fixed 15-bit reciprocal shift is used. + pub fn set_exact_quantization(&mut self, exact_quantization: bool) { + self.exact_quantization = exact_quantization; + } + + /// Returns if exact 16-bit reciprocal quantization is enabled. + pub fn exact_quantization(&self) -> bool { + self.exact_quantization + } + /// Appends a custom app segment to the JFIF file /// /// Segment numbers need to be in the range between 1 and 15
@@ -557,8 +571,18 @@ impl Encoder { } let q_tables = [ - QuantizationTable::new_with_quality(&self.quantization_tables[0], self.quality, true), - QuantizationTable::new_with_quality(&self.quantization_tables[1], self.quality, false), + QuantizationTable::new_with_quality( + &self.quantization_tables[0], + self.quality, + true, + self.exact_quantization, + ), + QuantizationTable::new_with_quality( + &self.quantization_tables[1], + self.quality, + false, + self.exact_quantization, + ), ]; let jpeg_color_type = image.get_jpeg_color_type(); @@ -798,6 +822,11 @@ impl Encoder { for h_offset in 0..component.horizontal_sampling_factor as usize { let bx = block_x * 8 * max_h_sampling + (h_offset * 8); let by = v_offset * 8; + let imcu_rows = (usize::from(height) + .saturating_sub(block_y * 8 * max_v_sampling)) + .min(8 * max_v_sampling); + let max_start_y = + imcu_rows.div_ceil(v_stride).saturating_sub(1) * v_stride; let mut block = if average { get_block_averaged( &row[i], @@ -806,6 +835,7 @@ impl Encoder { h_stride, v_stride, buffer_width, + max_start_y, ) } else { get_block(&row[i], bx, by, h_stride, v_stride, buffer_width) @@ -1072,13 +1102,22 @@ impl Encoder { let average = self.chroma_subsampling_method == ChromaSubsamplingMethod::Average && (h_scale > 1 || v_scale > 1); + let max_start_y = usize::from(height).div_ceil(v_scale).saturating_sub(1) * v_scale; for block_y in 0..rows { for block_x in 0..cols { let bx = block_x * 8 * h_scale; let by = block_y * 8 * v_scale; let mut block = if average { - get_block_averaged(&row[i], bx, by, h_scale, v_scale, buffer_width) + get_block_averaged( + &row[i], + bx, + by, + h_scale, + v_scale, + buffer_width, + max_start_y, + ) } else { get_block(&row[i], bx, by, h_scale, v_scale, buffer_width) }; @@ -1303,6 +1342,7 @@ fn get_block_averaged( col_stride: usize, row_stride: usize, width: usize, + max_start_y: usize, ) -> AlignedBlock { let mut block = [0i16; 64]; let n = col_stride * row_stride; @@ -1313,7 +1353,8 @@ fn get_block_averaged( for y in 0..8 { for x in 0..8 { let ix = start_x + (x * col_stride); - let iy = start_y + (y * row_stride); + // Repeat the last downsampled row at the bottom edge (matching libjpeg jcprepct.c). + let iy = (start_y + (y * row_stride)).min(max_start_y); let mut sum = 0usize; for dy in 0..row_stride { @@ -1382,7 +1423,7 @@ mod tests { } let nearest = get_block(&data, 0, 0, 2, 2, width); - let averaged = get_block_averaged(&data, 0, 0, 2, 2, width); + let averaged = get_block_averaged(&data, 0, 0, 2, 2, width, 14); assert!(nearest.data.iter().all(|&v| v == -128)); assert!(averaged.data.iter().all(|&v| v == 126 - 128)); @@ -1397,12 +1438,32 @@ mod tests { *v = if (i % width) % 2 == 0 { 1 } else { 2 }; } - let averaged = get_block_averaged(&data, 0, 0, 2, 2, width); + let averaged = get_block_averaged(&data, 0, 0, 2, 2, width, 14); assert_eq!(averaged.data[0], 1 - 128); assert_eq!(averaged.data[1], 2 - 128); assert_eq!(averaged.data[8], 1 - 128); } + #[test] + fn test_get_block_averaged_partial_imcu_bottom_edge() { + // Simulate a 16-row buffer where only the first 4 rows (2 downsampled 2x2 rows) + // are inside the image height: row 0 = 10, row 1 = 30, row 2 = 50, row 3..15 = 90. + // The last valid downsampled row (rows 2..3) averages (50 + 90) / 2 = 70, and + // bottom-edge padding should repeat that downsampled row rather than averaging (90, 90). + let width = 16; + let mut data = vec![90u8; width * 16]; + data[0..width].fill(10); + data[width..width * 2].fill(30); + data[width * 2..width * 3].fill(50); + + let averaged = get_block_averaged(&data, 0, 0, 2, 2, width, 2); + assert_eq!(averaged.data[0], 20 - 128); + assert_eq!(averaged.data[8], 70 - 128); + for row in 2..8 { + assert_eq!(averaged.data[row * 8], 70 - 128); + } + } + #[test] fn test_get_num_bits() { let min_max = 2i16.pow(13); diff --git a/src/lib.rs b/src/lib.rs index 88503e3..04cacea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -308,6 +308,31 @@ mod tests { check_result(data, width, height, &mut result, PixelFormat::RGB24); } + #[test] + fn test_exact_quantization() { + let row = [0u8, 0, 0, 246, 255, 255, 255, 255]; + let mut data = Vec::with_capacity(64); + for _ in 0..8 { + data.extend_from_slice(&row); + } + + let mut default_result = Vec::new(); + let encoder = Encoder::new(&mut default_result, 85); + assert!(!encoder.exact_quantization()); + encoder.encode(&data, 8, 8, ColorType::Luma).unwrap(); + + let mut exact_result = Vec::new(); + let mut encoder = Encoder::new(&mut exact_result, 85); + encoder.set_exact_quantization(true); + assert!(encoder.exact_quantization()); + encoder.encode(&data, 8, 8, ColorType::Luma).unwrap(); + + let (default_img, _) = decode(&default_result); + let (exact_img, _) = decode(&exact_result); + assert_eq!(&default_img[..8], &[0, 1, 0, 247, 254, 255, 254, 255]); + assert_eq!(&exact_img[..8], &[0, 1, 0, 246, 254, 255, 255, 255]); + } + #[test] fn test_rgb_2_1() { let (data, width, height) = create_test_img_rgb(); diff --git a/src/quantization.rs b/src/quantization.rs index 93055e6..1b8a7a2 100644 --- a/src/quantization.rs +++ b/src/quantization.rs @@ -184,9 +184,9 @@ static DEFAULT_CHROMA_TABLES: [[u16; 64]; 9] = [ const SHIFT: u32 = 2 * 8 - 1; -fn compute_reciprocal(divisor: u32) -> (i32, i32) { +fn compute_reciprocal(divisor: u32) -> (i32, i32, u32) { if divisor <= 1 { - return (1, 0); + return (1, 0, 0); } let mut reciprocals = (1 << SHIFT) / divisor; @@ -203,13 +203,40 @@ fn compute_reciprocal(divisor: u32) -> (i32, i32) { } } - (reciprocals as i32, correction as i32) + (reciprocals as i32, correction as i32, SHIFT) +} + +fn compute_reciprocal_exact(divisor: u32) -> (i32, i32, u32) { + if divisor <= 1 { + return (1, 0, 0); + } + + let b = divisor.ilog2(); + let mut r = 16 + b; + + let mut reciprocals = (1u64 << r) / divisor as u64; + let fractional = (1u64 << r) % divisor as u64; + + // Correction for rounding errors in division (matching libjpeg-turbo jcdctmgr.c). + let mut correction = divisor / 2; + + if fractional == 0 { + reciprocals >>= 1; + r -= 1; + } else if fractional <= correction as u64 { + correction += 1; + } else { + reciprocals += 1; + } + + (reciprocals as i32, correction as i32, r) } pub struct QuantizationTable { table: [NonZeroU16; 64], reciprocals: [i32; 64], corrections: [i32; 64], + shifts: [u32; 64], } impl QuantizationTable { @@ -217,6 +244,7 @@ impl QuantizationTable { table: &QuantizationTableType, quality: u8, luma: bool, + exact: bool, ) -> QuantizationTable { let table = match table { QuantizationTableType::Custom(table) => Self::get_user_table(table), @@ -232,18 +260,26 @@ impl QuantizationTable { let mut reciprocals = [0i32; 64]; let mut corrections = [0i32; 64]; + let mut shifts = [0u32; 64]; for i in 0..64 { - let (reciprocal, correction) = compute_reciprocal(table[i].get() as u32); + let divisor = table[i].get() as u32; + let (reciprocal, correction, shift) = if exact { + compute_reciprocal_exact(divisor) + } else { + compute_reciprocal(divisor) + }; reciprocals[i] = reciprocal; corrections[i] = correction; + shifts[i] = shift; } QuantizationTable { table, reciprocals, corrections, + shifts, } } @@ -293,11 +329,12 @@ impl QuantizationTable { let reciprocal = self.reciprocals[index]; let corrections = self.corrections[index]; + let shift = self.shifts[index]; let abs_value = value.abs(); let mut product = (abs_value + corrections) * reciprocal; - product >>= SHIFT; + product >>= shift; if value != abs_value { product *= -1; @@ -313,14 +350,16 @@ mod tests { #[test] fn test_new_100() { - let q = QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, true); + let q = + QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, true, false); for &v in &q.table { let v = v.get(); assert_eq!(v, 1 << 3); } - let q = QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, false); + let q = + QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, false, false); for &v in &q.table { let v = v.get(); @@ -330,10 +369,40 @@ mod tests { #[test] fn test_new_100_quantize() { - let q = QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, true); + let q = + QuantizationTable::new_with_quality(&QuantizationTableType::Default, 100, true, false); for i in -255..255 { assert_eq!(i, q.quantize(i << 3, 0)); } } + + #[test] + fn test_quantize_exact_matches_rounded_division() { + for quality in [1, 50, 75, 85, 95, 100] { + for luma in [true, false] { + let q = QuantizationTable::new_with_quality( + &QuantizationTableType::Default, + quality, + luma, + true, + ); + for index in 0..64 { + let divisor = q.table[index].get() as i32; + for val in -8192i16..=8192 { + let abs_val = (val as i32).abs(); + let mut expected = ((abs_val + divisor / 2) / divisor) as i16; + if val < 0 { + expected = -expected; + } + assert_eq!( + q.quantize(val, index), + expected, + "mismatch at quality={quality}, luma={luma}, index={index}, divisor={divisor}, val={val}" + ); + } + } + } + } + } } From 706622c91510e47c5427dd7e0b8b920356d34626 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:27:54 +0100 Subject: [PATCH 2/8] Quantize in u32 so exact reciprocals cannot overflow With the variable shift from `compute_reciprocal_exact`, the reciprocal keeps 16 significant bits, so `(|v| + correction) * reciprocal` can exceed i32::MAX: for divisor 1032 and |v| = 32768 it is ~2.16e9. In i32 that panics in debug builds and wraps in release, where -32768 / 1032 quantized to +32 instead of -32. Store reciprocals and corrections as u32 and do the multiply and shift in u32; the product stays below ~2^31.3 for every divisor `Custom` can produce. The 15-bit default path gives the same results as before. Adds an exhaustive test: for every `Custom` divisor (t << 3, t in 1..=2048) and every i16, exact quantization equals round-half-up division with the sign restored. --- src/quantization.rs | 55 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 13 deletions(-) diff --git a/src/quantization.rs b/src/quantization.rs index 1b8a7a2..eb92961 100644 --- a/src/quantization.rs +++ b/src/quantization.rs @@ -184,7 +184,7 @@ static DEFAULT_CHROMA_TABLES: [[u16; 64]; 9] = [ const SHIFT: u32 = 2 * 8 - 1; -fn compute_reciprocal(divisor: u32) -> (i32, i32, u32) { +fn compute_reciprocal(divisor: u32) -> (u32, u32, u32) { if divisor <= 1 { return (1, 0, 0); } @@ -203,10 +203,10 @@ fn compute_reciprocal(divisor: u32) -> (i32, i32, u32) { } } - (reciprocals as i32, correction as i32, SHIFT) + (reciprocals, correction, SHIFT) } -fn compute_reciprocal_exact(divisor: u32) -> (i32, i32, u32) { +fn compute_reciprocal_exact(divisor: u32) -> (u32, u32, u32) { if divisor <= 1 { return (1, 0, 0); } @@ -229,13 +229,13 @@ fn compute_reciprocal_exact(divisor: u32) -> (i32, i32, u32) { reciprocals += 1; } - (reciprocals as i32, correction as i32, r) + (reciprocals as u32, correction, r) } pub struct QuantizationTable { table: [NonZeroU16; 64], - reciprocals: [i32; 64], - corrections: [i32; 64], + reciprocals: [u32; 64], + corrections: [u32; 64], shifts: [u32; 64], } @@ -258,8 +258,8 @@ impl QuantizationTable { } }; - let mut reciprocals = [0i32; 64]; - let mut corrections = [0i32; 64]; + let mut reciprocals = [0u32; 64]; + let mut corrections = [0u32; 64]; let mut shifts = [0u32; 64]; for i in 0..64 { @@ -331,12 +331,10 @@ impl QuantizationTable { let corrections = self.corrections[index]; let shift = self.shifts[index]; - let abs_value = value.abs(); + // u32: with exact shifts the product can exceed i32::MAX (up to ~2^31.3). + let mut product = (((value.unsigned_abs() + corrections) * reciprocal) >> shift) as i32; - let mut product = (abs_value + corrections) * reciprocal; - product >>= shift; - - if value != abs_value { + if value < 0 { product *= -1; } @@ -405,4 +403,35 @@ mod tests { } } } + + /// Every divisor a `Custom` table can produce (`t << 3`, t in 1..=2048) + /// against every `i16`: exact quantization must equal round-half-up + /// division, including where `(|v| + correction) * reciprocal` exceeds + /// `i32::MAX` (e.g. divisor 1032, |v| = 32768). + #[test] + fn test_quantize_exact_all_divisors_all_values() { + use alloc::boxed::Box; + + for t in 1u16..=2048 { + let q = QuantizationTable::new_with_quality( + &QuantizationTableType::Custom(Box::new([t; 64])), + 100, + true, + true, + ); + let divisor = q.table[0].get() as i32; + for val in i16::MIN..=i16::MAX { + let abs_val = (val as i32).abs(); + let mut expected = (abs_val + divisor / 2) / divisor; + if val < 0 { + expected = -expected; + } + assert_eq!( + q.quantize(val, 0) as i32, + expected, + "mismatch at divisor={divisor}, val={val}" + ); + } + } + } } From 01002a29a209403dbb38c5c0a4be46126001bf55 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:51:33 +0100 Subject: [PATCH 3/8] Export AlignedBlock under the benchmark feature The benchmark feature re-exports fdct and fdct_avx2, but both take &mut AlignedBlock, which was pub(crate). Nothing outside the crate could call them, and criterion/benches/fdct.rs did not compile because it passed a plain [i16; 64]. Make AlignedBlock pub and re-export it only with `benchmark`; the encoder module stays private, so the normal public API is unchanged. The fdct bench now wraps its input in AlignedBlock::new. --- criterion/benches/fdct.rs | 6 +++--- src/encoder.rs | 4 +++- src/lib.rs | 3 +++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/criterion/benches/fdct.rs b/criterion/benches/fdct.rs index bf77599..84f40d2 100644 --- a/criterion/benches/fdct.rs +++ b/criterion/benches/fdct.rs @@ -1,6 +1,6 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use jpeg_encoder::fdct; +use jpeg_encoder::{fdct, AlignedBlock}; use std::time::Duration; const INPUT1: [i16; 64] = [ @@ -18,7 +18,7 @@ fn criterion_benchmark(c: &mut Criterion) { group.bench_function("default fdct", |b| { b.iter(|| { - let mut input = INPUT1.clone(); + let mut input = AlignedBlock::new(INPUT1); fdct( black_box(&mut input), ); @@ -31,7 +31,7 @@ fn criterion_benchmark(c: &mut Criterion) { b.iter(|| { use jpeg_encoder::fdct_avx2; - let mut input = INPUT1.clone(); + let mut input = AlignedBlock::new(INPUT1); fdct_avx2( black_box(&mut input), ); diff --git a/src/encoder.rs b/src/encoder.rs index 60db579..e063e67 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -36,7 +36,9 @@ pub enum JpegColorType { #[derive(Copy, Clone)] #[repr(C, align(32))] -pub(crate) struct AlignedBlock { +/// An 8x8 block of level-shifted samples, aligned for AVX2 loads and stores. +pub struct AlignedBlock { + /// The 64 coefficients in row-major order. pub data: [i16; 64], } diff --git a/src/lib.rs b/src/lib.rs index 04cacea..7dcee2c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,6 +48,9 @@ pub use image_buffer::{ImageBuffer, cmyk_to_ycck, rgb_to_ycbcr}; pub use quantization::QuantizationTableType; pub use writer::{JfifWrite, PixelDensity, PixelDensityUnit}; +#[cfg(feature = "benchmark")] +pub use encoder::AlignedBlock; + #[cfg(feature = "benchmark")] pub use fdct::fdct; From 60dadb0c9b1f50b5f6fd1e59fe6fcceac85e18a7 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:51:33 +0100 Subject: [PATCH 4/8] Add a differential fuzz target for AVX2 vs scalar paths avx2_matches_scalar asserts that fdct_avx2 and RgbImageAVX2 produce exactly the same output as fdct and RgbImage. FDCT input is level-shifted bytes (-128..=127), the range the encoder feeds it; the RGB part is a single row of arbitrary width so both the vector body and the remainder are hit. The target returns early without AVX2, since the AVX2 entry points do not check for it themselves. With the AVX2 FDCT from before ffbfcdb restored, the target reports an fdct mismatch within 60 seconds. The fuzz crate now enables the benchmark feature to reach these internals. --- fuzz/Cargo.toml | 8 ++++- fuzz/fuzz_targets/avx2_matches_scalar.rs | 40 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 fuzz/fuzz_targets/avx2_matches_scalar.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index d14e304..fdde2bb 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -13,7 +13,7 @@ libfuzzer-sys = "0.4" [dependencies.jpeg-encoder] path = ".." -features = ["simd"] +features = ["simd", "benchmark"] # Prevent this from interfering with workspaces [workspace] @@ -60,3 +60,9 @@ name = "encode_rgb_progressive" path = "fuzz_targets/encode_rgb_progressive.rs" test = false doc = false + +[[bin]] +name = "avx2_matches_scalar" +path = "fuzz_targets/avx2_matches_scalar.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/avx2_matches_scalar.rs b/fuzz/fuzz_targets/avx2_matches_scalar.rs new file mode 100644 index 0000000..406f49a --- /dev/null +++ b/fuzz/fuzz_targets/avx2_matches_scalar.rs @@ -0,0 +1,40 @@ +//! Differential target: the AVX2 FDCT and RGB to YCbCr conversion must produce +//! exactly the same output as their scalar counterparts. + +#![no_main] + +use jpeg_encoder::{fdct, fdct_avx2, AlignedBlock, ImageBuffer, RgbImage, RgbImageAVX2}; +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| { + // The AVX2 entry points do not check for AVX2 themselves. + if !std::is_x86_feature_detected!("avx2") || data.len() < 64 { + return; + } + let (block, pixels) = data.split_at(64); + + // Samples are level-shifted bytes, the same range the encoder feeds the FDCT. + let mut samples = [0i16; 64]; + for (s, &b) in samples.iter_mut().zip(block) { + *s = i16::from(b) - 128; + } + let mut scalar = AlignedBlock::new(samples); + let mut avx2 = AlignedBlock::new(samples); + fdct(&mut scalar); + fdct_avx2(&mut avx2); + assert_eq!(scalar.data, avx2.data, "fdct mismatch for input {samples:?}"); + + // A single row of arbitrary width exercises both the vector body and the remainder. + let Ok(width) = u16::try_from(pixels.len() / 3) else { + return; + }; + if width == 0 { + return; + } + let rgb = &pixels[..usize::from(width) * 3]; + let mut scalar_buffers: [Vec; 4] = Default::default(); + let mut avx2_buffers: [Vec; 4] = Default::default(); + RgbImage(rgb, width, 1).fill_buffers(0, &mut scalar_buffers); + RgbImageAVX2(rgb, width, 1).fill_buffers(0, &mut avx2_buffers); + assert_eq!(scalar_buffers, avx2_buffers, "ycbcr mismatch for input {rgb:?}"); +}); From 20f83a075964593edbaa2c52949688742ae0e10d Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:51:33 +0100 Subject: [PATCH 5/8] Fix q-table fuzz decoding and cover exact quantization `a as u16 + (b as u16) << 8` parses as `(a + b) << 8`, so every fuzzed table entry was a multiple of 256 and small divisors were never tried. Decode entries with u16::from_le_bytes instead. Byte 128 of the input now toggles set_exact_quantization, so the u32 exact-reciprocal path gets fuzzed with arbitrary Custom tables. Pixels start at byte 129; existing corpora are still valid input, just reinterpreted. --- fuzz/fuzz_targets/encode_rgb_custom_q_table.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/fuzz/fuzz_targets/encode_rgb_custom_q_table.rs b/fuzz/fuzz_targets/encode_rgb_custom_q_table.rs index 02ce621..a83937a 100644 --- a/fuzz/fuzz_targets/encode_rgb_custom_q_table.rs +++ b/fuzz/fuzz_targets/encode_rgb_custom_q_table.rs @@ -4,10 +4,12 @@ use libfuzzer_sys::fuzz_target; use jpeg_encoder::*; fuzz_target!(|data: &[u8]| { - if data.len() >= 128 + 3 { + // 128 bytes of table, 1 flag byte, then RGB pixels. + if data.len() >= 128 + 1 + 3 { let q_table = &data[0..128]; - let data = &data[128..]; + let exact_quantization = data[128] & 1 == 1; + let data = &data[129..]; let pixels = data.len() / 3; @@ -17,7 +19,7 @@ fuzz_target!(|data: &[u8]| { if width >0 && width < u16::MAX && height >0 && height < u16::MAX { let mut table = [0;64]; for i in 0..64 { - let v = q_table[i*2] as u16 + (q_table[i*2+1] as u16) << 8; + let v = u16::from_le_bytes([q_table[i * 2], q_table[i * 2 + 1]]); table[i] = v.max(1); } @@ -27,6 +29,7 @@ fuzz_target!(|data: &[u8]| { let mut encoder = Encoder::new(&mut out, 100); encoder.set_quantization_tables(table.clone(), table); + encoder.set_exact_quantization(exact_quantization); encoder.encode(data, width as u16, height as u16, ColorType::Rgb).unwrap(); } From 820fc47f4851e8bf95c343c930fa8b213d57d408 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:51:33 +0100 Subject: [PATCH 6/8] Build and run fuzz targets in CI The fuzz targets were never built in CI, so they could rot unnoticed. A new fuzz job installs nightly and cargo-fuzz, builds every target, and runs avx2_matches_scalar for 60 seconds to catch AVX2/scalar mismatches on GitHub's AVX2-capable runners. --- .github/workflows/rust.yml | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89b5a94..3b6ab78 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -62,4 +62,21 @@ jobs: with: components: rustfmt - name: Run rustfmt check - run: cargo fmt -- --check \ No newline at end of file + run: cargo fmt -- --check + + fuzz: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@nightly + - uses: taiki-e/install-action@v2 + with: + tool: cargo-fuzz + - name: Build fuzz targets + run: cargo fuzz build -O + working-directory: fuzz + - name: Run AVX2 vs scalar differential fuzzing + run: cargo fuzz run -O avx2_matches_scalar -- -max_total_time=60 + working-directory: fuzz From a19a7baf3d8ccb10a95d9b689890ef6763e921fe Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 23:04:39 +0100 Subject: [PATCH 7/8] Add a round-trip fuzz target that decodes the encoder output encode_roundtrip lets the fuzzer pick every encoder setting from an 8-byte header: color type, quality, sampling factor, optimized Huffman tables, exact quantization, average subsampling, progressive mode with 2..=64 scans, restart interval and width. When encoding succeeds, the output must decode with jpeg-decoder to the same dimensions, pixel format and buffer length. Pixel values are not compared, since arbitrary input has no meaningful error bound. On main it currently finds two known bugs within minutes: progressive scan counts of 34..=64 write an empty AC range (fixed by #47), and optimized Huffman tables with a restart interval miss the DC prediction reset (fixed by #42). With both applied, 589k runs pass. CI builds the target but does not run it until those land. --- fuzz/Cargo.toml | 7 ++ fuzz/fuzz_targets/encode_roundtrip.rs | 92 +++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 fuzz/fuzz_targets/encode_roundtrip.rs diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index fdde2bb..0bba8b3 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -10,6 +10,7 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" +jpeg-decoder = { version = "0.3", default-features = false } [dependencies.jpeg-encoder] path = ".." @@ -66,3 +67,9 @@ name = "avx2_matches_scalar" path = "fuzz_targets/avx2_matches_scalar.rs" test = false doc = false + +[[bin]] +name = "encode_roundtrip" +path = "fuzz_targets/encode_roundtrip.rs" +test = false +doc = false diff --git a/fuzz/fuzz_targets/encode_roundtrip.rs b/fuzz/fuzz_targets/encode_roundtrip.rs new file mode 100644 index 0000000..7cb050f --- /dev/null +++ b/fuzz/fuzz_targets/encode_roundtrip.rs @@ -0,0 +1,92 @@ +//! Round-trip target: whatever settings the fuzzer picks, the encoder must +//! either reject the input with an error or produce a JPEG that jpeg-decoder +//! decodes to the same dimensions and pixel format. + +#![no_main] + +use jpeg_decoder::{Decoder, PixelFormat}; +use jpeg_encoder::*; +use libfuzzer_sys::fuzz_target; + +const COLOR_TYPES: [ColorType; 9] = [ + ColorType::Luma, + ColorType::Rgb, + ColorType::Rgba, + ColorType::Bgr, + ColorType::Bgra, + ColorType::Ycbcr, + ColorType::Cmyk, + ColorType::CmykAsYcck, + ColorType::Ycck, +]; + +const SAMPLING_FACTORS: [(u8, u8); 8] = [ + (1, 1), + (1, 2), + (1, 4), + (2, 1), + (2, 2), + (2, 4), + (4, 1), + (4, 2), +]; + +fuzz_target!(|data: &[u8]| { + // Header: color type, quality, flags, sampling factor, progressive scans, + // restart interval (2 bytes), width - 1. Pixels follow. + let Some((header, pixels)) = data.split_first_chunk::<8>() else { + return; + }; + let [color, quality, flags, sampling, scans, restart_lo, restart_hi, width] = *header; + + let color_type = COLOR_TYPES[usize::from(color) % COLOR_TYPES.len()]; + let (h, v) = SAMPLING_FACTORS[usize::from(sampling) % SAMPLING_FACTORS.len()]; + let bytes_per_pixel = match color_type { + ColorType::Luma => 1, + ColorType::Rgb | ColorType::Bgr | ColorType::Ycbcr => 3, + _ => 4, + }; + + let width = u16::from(width) + 1; + let Ok(height) = u16::try_from(pixels.len() / bytes_per_pixel / usize::from(width)) else { + return; + }; + if height == 0 { + return; + } + + let mut out = Vec::new(); + let mut encoder = Encoder::new(&mut out, quality); + encoder.set_sampling_factor(SamplingFactor::from_factors(h, v).unwrap()); + encoder.set_optimized_huffman_tables(flags & 1 != 0); + encoder.set_exact_quantization(flags & 2 != 0); + if flags & 4 != 0 { + encoder.set_chroma_subsampling_method(ChromaSubsamplingMethod::Average); + } + if flags & 8 != 0 { + encoder.set_progressive(true); + // Valid range is 2..=64. + encoder.set_progressive_scans(2 + scans % 63); + } + encoder.set_restart_interval(u16::from_le_bytes([restart_lo, restart_hi])); + + if encoder.encode(pixels, width, height, color_type).is_err() { + return; + } + + let mut decoder = Decoder::new(out.as_slice()); + let decoded = decoder.decode().expect("encoder produced an undecodable JPEG"); + let info = decoder.info().unwrap(); + + let expected_format = match color_type { + ColorType::Luma => PixelFormat::L8, + ColorType::Cmyk | ColorType::CmykAsYcck | ColorType::Ycck => PixelFormat::CMYK32, + _ => PixelFormat::RGB24, + }; + assert_eq!((info.width, info.height), (width, height)); + assert_eq!(info.pixel_format, expected_format); + assert_eq!( + decoded.len(), + usize::from(width) * usize::from(height) * expected_format.pixel_bytes() + ); +}); From 6a455aad81a8fb892b7ba901a9e26eed0323dfe8 Mon Sep 17 00:00:00 2001 From: Sergio Gonzalez Martin Date: Mon, 23 Nov 2026 23:27:39 +0000 Subject: [PATCH 8/8] Fix fuzz target portability and CI target selection Guard AVX2-only fuzz code at compile time and build fuzz targets on ARM64 in CI. Select each runner's GNU target explicitly so musl-built cargo-fuzz binaries do not select an incompatible sanitizer target. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/rust.yml | 16 +++++++++++++--- fuzz/fuzz_targets/avx2_matches_scalar.rs | 16 ++++++++++++++-- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 3b6ab78..159e02b 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -66,7 +66,15 @@ jobs: fuzz: - runs-on: ubuntu-latest + runs-on: ${{ matrix.os }} + + strategy: + matrix: + include: + - os: ubuntu-latest + target: x86_64-unknown-linux-gnu + - os: ubuntu-24.04-arm + target: aarch64-unknown-linux-gnu steps: - uses: actions/checkout@v4 @@ -75,8 +83,10 @@ jobs: with: tool: cargo-fuzz - name: Build fuzz targets - run: cargo fuzz build -O + # cargo-fuzz binaries built for musl otherwise default to a musl target. + run: cargo fuzz build -O --target ${{ matrix.target }} working-directory: fuzz - name: Run AVX2 vs scalar differential fuzzing - run: cargo fuzz run -O avx2_matches_scalar -- -max_total_time=60 + if: matrix.target == 'x86_64-unknown-linux-gnu' + run: cargo fuzz run -O --target ${{ matrix.target }} avx2_matches_scalar -- -max_total_time=60 working-directory: fuzz diff --git a/fuzz/fuzz_targets/avx2_matches_scalar.rs b/fuzz/fuzz_targets/avx2_matches_scalar.rs index 406f49a..1c39455 100644 --- a/fuzz/fuzz_targets/avx2_matches_scalar.rs +++ b/fuzz/fuzz_targets/avx2_matches_scalar.rs @@ -1,11 +1,14 @@ //! Differential target: the AVX2 FDCT and RGB to YCbCr conversion must produce //! exactly the same output as their scalar counterparts. +//! Inactive on non-x86 architectures and CPUs without AVX2 support. #![no_main] +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] use jpeg_encoder::{fdct, fdct_avx2, AlignedBlock, ImageBuffer, RgbImage, RgbImageAVX2}; use libfuzzer_sys::fuzz_target; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fuzz_target!(|data: &[u8]| { // The AVX2 entry points do not check for AVX2 themselves. if !std::is_x86_feature_detected!("avx2") || data.len() < 64 { @@ -22,7 +25,10 @@ fuzz_target!(|data: &[u8]| { let mut avx2 = AlignedBlock::new(samples); fdct(&mut scalar); fdct_avx2(&mut avx2); - assert_eq!(scalar.data, avx2.data, "fdct mismatch for input {samples:?}"); + assert_eq!( + scalar.data, avx2.data, + "fdct mismatch for input {samples:?}" + ); // A single row of arbitrary width exercises both the vector body and the remainder. let Ok(width) = u16::try_from(pixels.len() / 3) else { @@ -36,5 +42,11 @@ fuzz_target!(|data: &[u8]| { let mut avx2_buffers: [Vec; 4] = Default::default(); RgbImage(rgb, width, 1).fill_buffers(0, &mut scalar_buffers); RgbImageAVX2(rgb, width, 1).fill_buffers(0, &mut avx2_buffers); - assert_eq!(scalar_buffers, avx2_buffers, "ycbcr mismatch for input {rgb:?}"); + assert_eq!( + scalar_buffers, avx2_buffers, + "ycbcr mismatch for input {rgb:?}" + ); }); + +#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] +fuzz_target!(|_data: &[u8]| {});