Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
8 changes: 6 additions & 2 deletions src/quantization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]>),
}

Expand Down Expand Up @@ -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),
};
Expand Down