diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89b5a94..159e02b 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -62,4 +62,31 @@ 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: ${{ 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 + - uses: dtolnay/rust-toolchain@nightly + - uses: taiki-e/install-action@v2 + with: + tool: cargo-fuzz + - name: Build fuzz targets + # 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 + 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/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/fuzz/Cargo.toml b/fuzz/Cargo.toml index d14e304..0bba8b3 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -10,10 +10,11 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" +jpeg-decoder = { version = "0.3", default-features = false } [dependencies.jpeg-encoder] path = ".." -features = ["simd"] +features = ["simd", "benchmark"] # Prevent this from interfering with workspaces [workspace] @@ -60,3 +61,15 @@ 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 + +[[bin]] +name = "encode_roundtrip" +path = "fuzz_targets/encode_roundtrip.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..1c39455 --- /dev/null +++ b/fuzz/fuzz_targets/avx2_matches_scalar.rs @@ -0,0 +1,52 @@ +//! 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 { + 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:?}" + ); +}); + +#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))] +fuzz_target!(|_data: &[u8]| {}); 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(); } 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() + ); +}); diff --git a/src/encoder.rs b/src/encoder.rs index 5f41217..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], } @@ -236,6 +238,7 @@ pub struct Encoder { restart_interval: Option, optimize_huffman_table: bool, + exact_quantization: bool, app_segments: Vec<(u8, Vec)>, } @@ -281,6 +284,7 @@ impl Encoder { progressive_scans: None, restart_interval: None, optimize_huffman_table: false, + exact_quantization: false, app_segments: Vec::new(), } } @@ -394,6 +398,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 +573,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 +824,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 +837,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 +1104,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 +1344,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 +1355,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 +1425,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 +1440,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..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; @@ -308,6 +311,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..eb92961 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) -> (u32, u32, 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, correction, SHIFT) +} + +fn compute_reciprocal_exact(divisor: u32) -> (u32, u32, 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 u32, correction, r) } pub struct QuantizationTable { table: [NonZeroU16; 64], - reciprocals: [i32; 64], - corrections: [i32; 64], + reciprocals: [u32; 64], + corrections: [u32; 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), @@ -230,20 +258,28 @@ 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 { - 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,13 +329,12 @@ impl QuantizationTable { let reciprocal = self.reciprocals[index]; 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; } @@ -313,14 +348,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 +367,71 @@ 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}" + ); + } + } + } + } + } + + /// 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}" + ); + } + } + } }