From a0a7659d7ea8e27fc772dfe229a17bd61aa1b025 Mon Sep 17 00:00:00 2001 From: Markus Mayer Date: Mon, 23 Nov 2026 22:25:01 +0100 Subject: [PATCH] Clamp custom quantization table values to 255 `QuantizationTableType::Custom` clamped values to 1..=2048, but the DQT segment is written with 8-bit precision, so `QuantizationTable::get` truncated larger values: 256 was written as 0 (an invalid table entry) and 300 as 44, while the encoder quantized with the real value. Decoders then dequantized with a different table than the one used to encode. Clamp to 1..=255, the range baseline JPEG allows for 8-bit samples, and document it on the variant. --- src/lib.rs | 21 +++++++++++++++++++++ src/quantization.rs | 8 ++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 88503e3..c2a53ab 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -263,6 +263,27 @@ mod tests { check_result(data, width, height, &mut result, PixelFormat::RGB24); } + #[test] + fn test_custom_q_table_above_255() { + let (data, width, height) = create_test_img_rgb(); + + for v in [256u16, 300, 2048] { + let mut result = Vec::new(); + let mut encoder = Encoder::new(&mut result, 100); + + let table = QuantizationTableType::Custom(Box::new([v; 64])); + encoder.set_quantization_tables(table.clone(), table); + + encoder + .encode(&data, width, height, ColorType::Rgb) + .unwrap(); + + // DQT is 8-bit: the value must be clamped to 255, not truncated. + let dqt = result.windows(2).position(|w| w == [0xFF, 0xDB]).unwrap(); + assert_eq!(result[dqt + 5], 255, "custom value {v}"); + } + } + #[test] fn test_rgb_2_2() { let (data, width, height) = create_test_img_rgb(); diff --git a/src/quantization.rs b/src/quantization.rs index 93055e6..b6391da 100644 --- a/src/quantization.rs +++ b/src/quantization.rs @@ -35,7 +35,10 @@ pub enum QuantizationTableType { /// An improved detection model for DCT coefficient quantization (1993) Peterson, Ahumada and Watson ImprovedDetectionModel, - /// A user supplied quantization table + /// A user supplied quantization table, in natural (row-major) order. + /// + /// Values are clamped to `1..=255`: the DQT segment is written with 8-bit + /// precision, which baseline JPEG requires for 8-bit samples. Custom(Box<[u16; 64]>), } @@ -250,7 +253,8 @@ impl QuantizationTable { fn get_user_table(table: &[u16; 64]) -> [NonZeroU16; 64] { let mut q_table = [NonZeroU16::new(1).unwrap(); 64]; for (i, &v) in table.iter().enumerate() { - q_table[i] = match NonZeroU16::new(v.clamp(1, 2 << 10) << 3) { + // 8-bit DQT: a larger value would be written truncated. + q_table[i] = match NonZeroU16::new(v.clamp(1, 255) << 3) { Some(v) => v, None => panic!("Invalid quantization table value: {}", v), };