Skip to content
Open
29 changes: 28 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,31 @@ jobs:
with:
components: rustfmt
- name: Run rustfmt check
run: cargo fmt -- --check
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
6 changes: 3 additions & 3 deletions criterion/benches/fdct.rs
Original file line number Diff line number Diff line change
@@ -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] = [
Expand All @@ -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),
);
Expand All @@ -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),
);
Expand Down
15 changes: 14 additions & 1 deletion fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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
52 changes: 52 additions & 0 deletions fuzz/fuzz_targets/avx2_matches_scalar.rs
Original file line number Diff line number Diff line change
@@ -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<u8>; 4] = Default::default();
let mut avx2_buffers: [Vec<u8>; 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]| {});
9 changes: 6 additions & 3 deletions fuzz/fuzz_targets/encode_rgb_custom_q_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
}

Expand All @@ -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();
}
Expand Down
92 changes: 92 additions & 0 deletions fuzz/fuzz_targets/encode_roundtrip.rs
Original file line number Diff line number Diff line change
@@ -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()
);
});
Loading
Loading