Skip to content

Clamp custom quantization table values to 255 - #45

Open
sunsided wants to merge 1 commit into
vstroebel:mainfrom
sunsided:feature/custom-quant-table-clamp
Open

sunsided wants to merge 1 commit into
vstroebel:mainfrom
sunsided:feature/custom-quant-table-clamp

Conversation

@sunsided

Copy link
Copy Markdown

QuantizationTableType::Custom clamps values to 1..=2048, but the DQT segment is written with 8-bit precision (QuantizationTable::get returns (x >> 3) as u8). Values above 255 are therefore truncated in the file while the encoder quantizes with the real value:

Custom value Written to DQT Used for quantization
256 0 (invalid) 256
300 44 300
2048 0 (invalid) 2048

Decoders then dequantize with a different table than the one the encoder used.

Change

  • Clamp Custom values to 1..=255, the range baseline JPEG allows for 8-bit samples.
  • Document the clamp (and the natural-order layout the DQT writer assumes) on QuantizationTableType::Custom.

A 16-bit DQT (Pq = 1) would preserve larger values, but it is not valid in a baseline frame, so clamping looked like the right fix here.

Tests

test_custom_q_table_above_255 encodes with Custom([v; 64]) for v = 256, 300 and 2048, finds the DQT marker and checks that the first table value is 255. It fails on main (256 is written as 0).

cargo fmt --check and cargo test pass with --features simd, with --features use_wide, and with --no-default-features --tests, also on 1.89.

`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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant