Skip to main content

lib_jsl_file_io/
jpeg.rs

1//! A simple baseline JPEG codec.
2//!
3//! This is a small, readable implementation intended as a worked example rather than a
4//! production codec. It supports:
5//!
6//! - **Encoding** 8-bit grayscale or RGB images as baseline sequential JPEG (JFIF), using the
7//!   standard Annex K quantization and Huffman tables, a quality factor in `1..=100`, and
8//!   4:4:4 chroma (no subsampling).
9//! - **Decoding** baseline sequential (SOF0) JPEG files with one or three components, 8-bit
10//!   precision, any chroma subsampling (upsampled by linear interpolation, like libjpeg's
11//!   "fancy" upsampling), custom Huffman and
12//!   quantization tables, and restart intervals.
13//!
14//! Progressive, arithmetic-coded, 12-bit, CMYK and multi-scan files are rejected with an error.
15//!
16//! The pipeline is the classic one: colour conversion, 8x8 forward DCT, quantization, zig-zag
17//! ordering, differential DC coding and run-length AC coding, then Huffman coding; the decoder
18//! runs it in reverse.
19//!
20//! See the book entry [Image files](https://jwkunz.github.io/lib_jsl/book/foundations/images.html#baseline-jpeg).
21
22use lib_jsl_core::ErrorsJSL;
23use std::f64::consts::PI;
24
25/// A decoded raster image with interleaved 8-bit samples (`channels` is 1 for grayscale or 3 for
26/// RGB, row-major, `width * height * channels` bytes).
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct JpegImage {
29    pub width: usize,
30    pub height: usize,
31    pub channels: usize,
32    pub pixels: Vec<u8>,
33}
34
35// ---------------------------------------------------------------- tables
36
37const ZIGZAG: [usize; 64] = [
38    0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21,
39    28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61,
40    54, 47, 55, 62, 63,
41];
42
43const LUMA_QUANT: [u8; 64] = [
44    16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51,
45    87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101,
46    72, 92, 95, 98, 112, 100, 103, 99,
47];
48
49const CHROMA_QUANT: [u8; 64] = [
50    17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99,
51    99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
52    99, 99, 99, 99, 99, 99,
53];
54
55/// A Huffman table in JPEG form: counts of codes per length (1..=16) and the symbols in order.
56struct HuffSpec {
57    counts: [u8; 16],
58    symbols: &'static [u8],
59}
60
61const DC_LUMA: HuffSpec = HuffSpec {
62    counts: [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
63    symbols: &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
64};
65const DC_CHROMA: HuffSpec = HuffSpec {
66    counts: [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
67    symbols: &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
68};
69const AC_LUMA: HuffSpec = HuffSpec {
70    counts: [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d],
71    symbols: &[
72        0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71,
73        0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72,
74        0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37,
75        0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
76        0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83,
77        0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3,
78        0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
79        0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
80        0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa,
81    ],
82};
83const AC_CHROMA: HuffSpec = HuffSpec {
84    counts: [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77],
85    symbols: &[
86        0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22,
87        0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
88        0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36,
89        0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
90        0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
91        0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a,
92        0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba,
93        0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
94        0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa,
95    ],
96};
97
98// ------------------------------------------------------------------- DCT
99
100/// `COS[x][u] = c(u)/2 * cos((2x+1) u π / 16)`, so that the 2-D DCT is `C^T · block · C`.
101fn dct_basis() -> [[f64; 8]; 8] {
102    let mut c = [[0.0; 8]; 8];
103    for (x, row) in c.iter_mut().enumerate() {
104        for (u, v) in row.iter_mut().enumerate() {
105            let scale = if u == 0 { (1.0f64 / 8.0).sqrt() } else { 0.5 };
106            *v = scale * ((2 * x + 1) as f64 * u as f64 * PI / 16.0).cos();
107        }
108    }
109    c
110}
111
112/// Forward 8x8 DCT-II (orthonormal).
113// ANCHOR: dct
114fn fdct(block: &[f64; 64]) -> [f64; 64] {
115    let c = dct_basis();
116    let mut tmp = [0.0; 64];
117    for y in 0..8 {
118        for u in 0..8 {
119            tmp[y * 8 + u] = (0..8).map(|x| block[y * 8 + x] * c[x][u]).sum();
120        }
121    }
122    let mut out = [0.0; 64];
123    for u in 0..8 {
124        for v in 0..8 {
125            out[v * 8 + u] = (0..8).map(|y| tmp[y * 8 + u] * c[y][v]).sum();
126        }
127    }
128    out
129}
130// ANCHOR_END: dct
131
132/// Inverse 8x8 DCT.
133fn idct(coef: &[f64; 64]) -> [f64; 64] {
134    let c = dct_basis();
135    let mut tmp = [0.0; 64];
136    for v in 0..8 {
137        for x in 0..8 {
138            tmp[v * 8 + x] = (0..8).map(|u| coef[v * 8 + u] * c[x][u]).sum();
139        }
140    }
141    let mut out = [0.0; 64];
142    for x in 0..8 {
143        for y in 0..8 {
144            out[y * 8 + x] = (0..8).map(|v| tmp[v * 8 + x] * c[y][v]).sum();
145        }
146    }
147    out
148}
149
150// --------------------------------------------------------------- encoder
151
152fn scaled_quant(base: &[u8; 64], quality: u8) -> [u8; 64] {
153    let q = quality.clamp(1, 100) as i32;
154    let scale = if q < 50 { 5000 / q } else { 200 - 2 * q };
155    let mut out = [0u8; 64];
156    for (o, &b) in out.iter_mut().zip(base) {
157        *o = ((b as i32 * scale + 50) / 100).clamp(1, 255) as u8;
158    }
159    out
160}
161
162/// Canonical Huffman code assignment: `codes[symbol] = (code, length)`.
163fn encoder_codes(spec: &HuffSpec) -> Vec<Option<(u16, u8)>> {
164    let mut table = vec![None; 256];
165    let mut code = 0u16;
166    let mut k = 0;
167    for len in 1..=16u8 {
168        for _ in 0..spec.counts[len as usize - 1] {
169            table[spec.symbols[k] as usize] = Some((code, len));
170            code += 1;
171            k += 1;
172        }
173        code <<= 1;
174    }
175    table
176}
177
178struct BitWriter {
179    out: Vec<u8>,
180    acc: u32,
181    nbits: u32,
182}
183
184impl BitWriter {
185    fn new() -> Self {
186        BitWriter { out: Vec::new(), acc: 0, nbits: 0 }
187    }
188
189    fn put(&mut self, value: u32, len: u32) {
190        if len == 0 {
191            return;
192        }
193        self.acc = (self.acc << len) | (value & ((1u32 << len) - 1));
194        self.nbits += len;
195        while self.nbits >= 8 {
196            let byte = (self.acc >> (self.nbits - 8)) as u8;
197            self.out.push(byte);
198            if byte == 0xFF {
199                self.out.push(0x00); // byte stuffing
200            }
201            self.nbits -= 8;
202        }
203        self.acc &= (1u32 << self.nbits) - 1;
204    }
205
206    fn finish(mut self) -> Vec<u8> {
207        if self.nbits > 0 {
208            let pad = 8 - self.nbits;
209            self.put((1u32 << pad) - 1, pad); // pad with 1 bits
210        }
211        self.out
212    }
213}
214
215/// Size category (number of bits) of a coefficient magnitude.
216fn category(v: i32) -> u32 {
217    32 - v.unsigned_abs().leading_zeros()
218}
219
220/// The `category` low bits that follow a Huffman symbol for value `v`.
221fn magnitude_bits(v: i32, cat: u32) -> u32 {
222    if v >= 0 { v as u32 } else { (v + (1 << cat) - 1) as u32 }
223}
224
225struct ComponentEncoder<'a> {
226    quant: &'a [u8; 64],
227    dc: &'a [Option<(u16, u8)>],
228    ac: &'a [Option<(u16, u8)>],
229    prev_dc: i32,
230}
231
232impl ComponentEncoder<'_> {
233    fn encode_block(&mut self, samples: &[f64; 64], w: &mut BitWriter) {
234        let mut shifted = [0.0; 64];
235        for (s, &v) in shifted.iter_mut().zip(samples) {
236            *s = v - 128.0;
237        }
238        let coef = fdct(&shifted);
239        let mut q = [0i32; 64];
240        for (i, &z) in ZIGZAG.iter().enumerate() {
241            q[i] = (coef[z] / self.quant[z] as f64).round() as i32;
242        }
243        // DC difference.
244        let diff = q[0] - self.prev_dc;
245        self.prev_dc = q[0];
246        let cat = category(diff);
247        let (code, len) = self.dc[cat as usize].expect("DC symbol present in table");
248        w.put(code as u32, len as u32);
249        w.put(magnitude_bits(diff, cat), cat);
250        // AC coefficients: (run, size) symbols.
251        let mut run = 0;
252        for &v in &q[1..] {
253            if v == 0 {
254                run += 1;
255                continue;
256            }
257            while run >= 16 {
258                let (code, len) = self.ac[0xF0].unwrap();
259                w.put(code as u32, len as u32);
260                run -= 16;
261            }
262            let cat = category(v);
263            let (code, len) = self.ac[(run << 4) | cat as usize].expect("AC symbol present in table");
264            w.put(code as u32, len as u32);
265            w.put(magnitude_bits(v, cat), cat);
266            run = 0;
267        }
268        if run > 0 {
269            let (code, len) = self.ac[0x00].unwrap();
270            w.put(code as u32, len as u32);
271        }
272    }
273}
274
275fn put_marker(out: &mut Vec<u8>, marker: u8, payload: &[u8]) {
276    out.extend_from_slice(&[0xFF, marker]);
277    out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
278    out.extend_from_slice(payload);
279}
280
281fn put_dht(out: &mut Vec<u8>, class_and_id: u8, spec: &HuffSpec) {
282    let mut payload = vec![class_and_id];
283    payload.extend_from_slice(&spec.counts);
284    payload.extend_from_slice(spec.symbols);
285    put_marker(out, 0xC4, &payload);
286}
287
288fn put_dqt(out: &mut Vec<u8>, id: u8, table: &[u8; 64]) {
289    let mut payload = vec![id];
290    payload.extend(ZIGZAG.iter().map(|&z| table[z]));
291    put_marker(out, 0xDB, &payload);
292}
293
294/// Encodes an 8-bit image as a baseline JPEG (JFIF) byte stream.
295///
296/// `pixels` holds `width * height * channels` interleaved samples, row-major, with `channels`
297/// equal to 1 (grayscale) or 3 (RGB). `quality` runs from 1 (smallest file) to 100 (best fidelity).
298/// Dimensions must be between 1 and 65535.
299pub fn jpeg_encode(pixels: &[u8], width: usize, height: usize, channels: usize, quality: u8) -> Result<Vec<u8>, ErrorsJSL> {
300    if channels != 1 && channels != 3 {
301        return Err(ErrorsJSL::InvalidInputRange("JPEG encoding supports 1 (gray) or 3 (RGB) channels."));
302    }
303    if width == 0 || height == 0 || width > 65535 || height > 65535 {
304        return Err(ErrorsJSL::InvalidInputRange("JPEG dimensions must be between 1 and 65535."));
305    }
306    if pixels.len() != width * height * channels {
307        return Err(ErrorsJSL::IncompatibleArraySizes((pixels.len(), width * height * channels)));
308    }
309    let luma_q = scaled_quant(&LUMA_QUANT, quality);
310    let chroma_q = scaled_quant(&CHROMA_QUANT, quality);
311
312    // Split into planes of f64 samples (Y, Cb, Cr with the JFIF full-range conversion).
313    let n = width * height;
314    let mut planes: Vec<Vec<f64>> = vec![Vec::with_capacity(n); channels];
315    for px in pixels.chunks_exact(channels) {
316        if channels == 1 {
317            planes[0].push(px[0] as f64);
318        } else {
319            let (r, g, b) = (px[0] as f64, px[1] as f64, px[2] as f64);
320            planes[0].push(0.299 * r + 0.587 * g + 0.114 * b);
321            planes[1].push(-0.168_736 * r - 0.331_264 * g + 0.5 * b + 128.0);
322            planes[2].push(0.5 * r - 0.418_688 * g - 0.081_312 * b + 128.0);
323        }
324    }
325
326    let dc_luma = encoder_codes(&DC_LUMA);
327    let ac_luma = encoder_codes(&AC_LUMA);
328    let dc_chroma = encoder_codes(&DC_CHROMA);
329    let ac_chroma = encoder_codes(&AC_CHROMA);
330
331    let mut out = vec![0xFF, 0xD8]; // SOI
332    // JFIF APP0: version 1.01, no density units, 1:1 aspect, no thumbnail.
333    put_marker(&mut out, 0xE0, &[b'J', b'F', b'I', b'F', 0, 1, 1, 0, 0, 1, 0, 1, 0, 0]);
334    put_dqt(&mut out, 0, &luma_q);
335    if channels == 3 {
336        put_dqt(&mut out, 1, &chroma_q);
337    }
338    // SOF0: precision 8, height, width, components (id, sampling 1x1, quant table).
339    let mut sof = vec![8];
340    sof.extend_from_slice(&(height as u16).to_be_bytes());
341    sof.extend_from_slice(&(width as u16).to_be_bytes());
342    sof.push(channels as u8);
343    for c in 0..channels {
344        sof.extend_from_slice(&[c as u8 + 1, 0x11, if c == 0 { 0 } else { 1 }]);
345    }
346    put_marker(&mut out, 0xC0, &sof);
347    put_dht(&mut out, 0x00, &DC_LUMA);
348    put_dht(&mut out, 0x10, &AC_LUMA);
349    if channels == 3 {
350        put_dht(&mut out, 0x01, &DC_CHROMA);
351        put_dht(&mut out, 0x11, &AC_CHROMA);
352    }
353    // SOS: all components, DC/AC table selectors, spectral range 0..63, no approximation.
354    let mut sos = vec![channels as u8];
355    for c in 0..channels {
356        sos.extend_from_slice(&[c as u8 + 1, if c == 0 { 0x00 } else { 0x11 }]);
357    }
358    sos.extend_from_slice(&[0, 63, 0]);
359    put_marker(&mut out, 0xDA, &sos);
360
361    let mut encoders: Vec<ComponentEncoder> = (0..channels)
362        .map(|c| ComponentEncoder {
363            quant: if c == 0 { &luma_q } else { &chroma_q },
364            dc: if c == 0 { &dc_luma } else { &dc_chroma },
365            ac: if c == 0 { &ac_luma } else { &ac_chroma },
366            prev_dc: 0,
367        })
368        .collect();
369    let mut writer = BitWriter::new();
370    for by in 0..height.div_ceil(8) {
371        for bx in 0..width.div_ceil(8) {
372            for (c, enc) in encoders.iter_mut().enumerate() {
373                let mut block = [0.0; 64];
374                for y in 0..8 {
375                    for x in 0..8 {
376                        // Replicate edge pixels into the padding.
377                        let sx = (bx * 8 + x).min(width - 1);
378                        let sy = (by * 8 + y).min(height - 1);
379                        block[y * 8 + x] = planes[c][sy * width + sx];
380                    }
381                }
382                enc.encode_block(&block, &mut writer);
383            }
384        }
385    }
386    out.extend(writer.finish());
387    out.extend_from_slice(&[0xFF, 0xD9]); // EOI
388    Ok(out)
389}
390
391// --------------------------------------------------------------- decoder
392
393struct HuffDecoder {
394    /// For each code length 1..=16: smallest code, largest code (or -1), index of first symbol.
395    min_code: [i32; 17],
396    max_code: [i32; 18],
397    val_ptr: [i32; 17],
398    symbols: Vec<u8>,
399}
400
401impl HuffDecoder {
402    fn new(counts: &[u8; 16], symbols: &[u8]) -> Result<Self, ErrorsJSL> {
403        let total: usize = counts.iter().map(|&c| c as usize).sum();
404        if total != symbols.len() || total > 256 {
405            return Err(ErrorsJSL::InvalidInputRange("Malformed JPEG Huffman table."));
406        }
407        let mut min_code = [0i32; 17];
408        let mut max_code = [-1i32; 18];
409        let mut val_ptr = [0i32; 17];
410        let mut code = 0i32;
411        let mut k = 0i32;
412        for len in 1..=16usize {
413            val_ptr[len] = k;
414            min_code[len] = code;
415            code += counts[len - 1] as i32;
416            k += counts[len - 1] as i32;
417            max_code[len] = if counts[len - 1] > 0 { code - 1 } else { -1 };
418            if code > (1 << len) {
419                return Err(ErrorsJSL::InvalidInputRange("Over-subscribed JPEG Huffman table."));
420            }
421            code <<= 1;
422        }
423        Ok(HuffDecoder { min_code, max_code, val_ptr, symbols: symbols.to_vec() })
424    }
425}
426
427struct BitReader<'a> {
428    data: &'a [u8],
429    pos: usize,
430    acc: u32,
431    nbits: u32,
432}
433
434impl<'a> BitReader<'a> {
435    fn new(data: &'a [u8], pos: usize) -> Self {
436        BitReader { data, pos, acc: 0, nbits: 0 }
437    }
438
439    fn bit(&mut self) -> Result<u32, ErrorsJSL> {
440        if self.nbits == 0 {
441            let b = *self.data.get(self.pos).ok_or(ErrorsJSL::InvalidInputRange("JPEG scan data ended unexpectedly."))?;
442            if b == 0xFF {
443                match self.data.get(self.pos + 1) {
444                    Some(0x00) => self.pos += 2,
445                    _ => return Err(ErrorsJSL::InvalidInputRange("Unexpected marker inside JPEG scan data.")),
446                }
447            } else {
448                self.pos += 1;
449            }
450            self.acc = b as u32;
451            self.nbits = 8;
452        }
453        self.nbits -= 1;
454        Ok((self.acc >> self.nbits) & 1)
455    }
456
457    fn bits(&mut self, n: u32) -> Result<u32, ErrorsJSL> {
458        let mut v = 0;
459        for _ in 0..n {
460            v = (v << 1) | self.bit()?;
461        }
462        Ok(v)
463    }
464
465    fn decode(&mut self, h: &HuffDecoder) -> Result<u8, ErrorsJSL> {
466        let mut code = 0i32;
467        for len in 1..=16usize {
468            code = (code << 1) | self.bit()? as i32;
469            if h.max_code[len] >= 0 && code <= h.max_code[len] && code >= h.min_code[len] {
470                let idx = (h.val_ptr[len] + code - h.min_code[len]) as usize;
471                return Ok(h.symbols[idx]);
472            }
473        }
474        Err(ErrorsJSL::InvalidInputRange("Invalid JPEG Huffman code."))
475    }
476
477    /// Discards any partial byte and consumes an `RSTn` marker.
478    fn restart(&mut self) -> Result<(), ErrorsJSL> {
479        self.nbits = 0;
480        if self.data.get(self.pos) == Some(&0xFF) && matches!(self.data.get(self.pos + 1), Some(0xD0..=0xD7)) {
481            self.pos += 2;
482            Ok(())
483        } else {
484            Err(ErrorsJSL::InvalidInputRange("Missing JPEG restart marker."))
485        }
486    }
487}
488
489/// Sign-extends an `n`-bit magnitude as in JPEG (the inverse of [`magnitude_bits`]).
490fn extend(v: u32, n: u32) -> i32 {
491    if n == 0 {
492        0
493    } else if v < (1 << (n - 1)) {
494        v as i32 - (1 << n) + 1
495    } else {
496        v as i32
497    }
498}
499
500struct Component {
501    id: u8,
502    h: usize,
503    v: usize,
504    quant_id: usize,
505    dc_id: usize,
506    ac_id: usize,
507    plane: Vec<f64>,
508    plane_w: usize,
509}
510
511fn read_u16(data: &[u8], pos: usize) -> Result<usize, ErrorsJSL> {
512    match data.get(pos..pos + 2) {
513        Some(b) => Ok(u16::from_be_bytes([b[0], b[1]]) as usize),
514        None => Err(ErrorsJSL::InvalidInputRange("Truncated JPEG header.")),
515    }
516}
517
518/// Decodes a baseline JPEG byte stream into an interleaved 8-bit image (grayscale stays 1
519/// channel; three-component YCbCr files become RGB).
520pub fn jpeg_decode(data: &[u8]) -> Result<JpegImage, ErrorsJSL> {
521    if data.get(0..2) != Some(&[0xFF, 0xD8]) {
522        return Err(ErrorsJSL::InvalidInputRange("Not a JPEG file (missing SOI)."));
523    }
524    let mut pos = 2;
525    let mut quant: [Option<[u16; 64]>; 4] = [None; 4];
526    let mut dc_tables: [Option<HuffDecoder>; 4] = [None, None, None, None];
527    let mut ac_tables: [Option<HuffDecoder>; 4] = [None, None, None, None];
528    let mut comps: Vec<Component> = Vec::new();
529    let (mut width, mut height) = (0usize, 0usize);
530    let mut restart_interval = 0usize;
531    let mut scan_start = None;
532
533    while scan_start.is_none() {
534        if data.get(pos) != Some(&0xFF) {
535            return Err(ErrorsJSL::InvalidInputRange("Expected a JPEG marker."));
536        }
537        while data.get(pos) == Some(&0xFF) {
538            pos += 1; // skip fill bytes
539        }
540        let marker = *data.get(pos).ok_or(ErrorsJSL::InvalidInputRange("Truncated JPEG."))?;
541        pos += 1;
542        if marker == 0xD9 {
543            return Err(ErrorsJSL::InvalidInputRange("JPEG ended before any image data."));
544        }
545        if marker == 0x01 || (0xD0..=0xD7).contains(&marker) {
546            continue; // standalone markers
547        }
548        let len = read_u16(data, pos)?;
549        let seg = data.get(pos + 2..pos + len).ok_or(ErrorsJSL::InvalidInputRange("Truncated JPEG segment."))?;
550        match marker {
551            0xDB => {
552                let mut i = 0;
553                while i < seg.len() {
554                    let (prec, id) = (seg[i] >> 4, (seg[i] & 15) as usize);
555                    i += 1;
556                    if id > 3 || prec > 1 {
557                        return Err(ErrorsJSL::InvalidInputRange("Unsupported JPEG quantization table."));
558                    }
559                    let mut t = [0u16; 64];
560                    for k in 0..64 {
561                        let v = if prec == 0 {
562                            *seg.get(i).ok_or(ErrorsJSL::InvalidInputRange("Truncated DQT."))? as u16
563                        } else {
564                            read_u16(seg, i)? as u16
565                        };
566                        i += if prec == 0 { 1 } else { 2 };
567                        t[ZIGZAG[k]] = v;
568                    }
569                    quant[id] = Some(t);
570                }
571            }
572            0xC4 => {
573                let mut i = 0;
574                while i + 17 <= seg.len() {
575                    let (class, id) = (seg[i] >> 4, (seg[i] & 15) as usize);
576                    let mut counts = [0u8; 16];
577                    counts.copy_from_slice(&seg[i + 1..i + 17]);
578                    let total: usize = counts.iter().map(|&c| c as usize).sum();
579                    let symbols = seg.get(i + 17..i + 17 + total).ok_or(ErrorsJSL::InvalidInputRange("Truncated DHT."))?;
580                    if id > 3 || class > 1 {
581                        return Err(ErrorsJSL::InvalidInputRange("Unsupported JPEG Huffman table id."));
582                    }
583                    let table = HuffDecoder::new(&counts, symbols)?;
584                    if class == 0 { dc_tables[id] = Some(table) } else { ac_tables[id] = Some(table) }
585                    i += 17 + total;
586                }
587            }
588            0xC0 | 0xC1 => {
589                if seg.len() < 6 || seg[0] != 8 {
590                    return Err(ErrorsJSL::InvalidInputRange("Only 8-bit baseline JPEG is supported."));
591                }
592                height = read_u16(seg, 1)?;
593                width = read_u16(seg, 3)?;
594                let n = seg[5] as usize;
595                if (n != 1 && n != 3) || seg.len() < 6 + 3 * n || width == 0 || height == 0 {
596                    return Err(ErrorsJSL::InvalidInputRange("Unsupported JPEG component layout."));
597                }
598                comps = (0..n)
599                    .map(|i| {
600                        let s = &seg[6 + 3 * i..9 + 3 * i];
601                        Component {
602                            id: s[0],
603                            h: (s[1] >> 4) as usize,
604                            v: (s[1] & 15) as usize,
605                            quant_id: (s[2] & 3) as usize,
606                            dc_id: 0,
607                            ac_id: 0,
608                            plane: Vec::new(),
609                            plane_w: 0,
610                        }
611                    })
612                    .collect();
613                if comps.iter().any(|c| c.h == 0 || c.v == 0 || c.h > 4 || c.v > 4) {
614                    return Err(ErrorsJSL::InvalidInputRange("Invalid JPEG sampling factors."));
615                }
616            }
617            0xC2 | 0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => {
618                return Err(ErrorsJSL::InvalidInputRange("Only baseline sequential Huffman JPEG is supported."));
619            }
620            0xDD => restart_interval = read_u16(seg, 0)?,
621            0xDA => {
622                if comps.is_empty() {
623                    return Err(ErrorsJSL::InvalidInputRange("JPEG scan before frame header."));
624                }
625                let ns = *seg.first().ok_or(ErrorsJSL::InvalidInputRange("Truncated SOS."))? as usize;
626                if ns != comps.len() || seg.len() < 1 + 2 * ns + 3 {
627                    return Err(ErrorsJSL::InvalidInputRange("Only single-scan JPEG files are supported."));
628                }
629                for i in 0..ns {
630                    let (cid, tabs) = (seg[1 + 2 * i], seg[2 + 2 * i]);
631                    let comp = comps.iter_mut().find(|c| c.id == cid).ok_or(ErrorsJSL::InvalidInputRange("Unknown component in SOS."))?;
632                    comp.dc_id = (tabs >> 4) as usize & 3;
633                    comp.ac_id = (tabs & 15) as usize & 3;
634                }
635                scan_start = Some(pos + len);
636            }
637            _ => {}
638        }
639        pos += len;
640    }
641
642    let hmax = comps.iter().map(|c| c.h).max().unwrap();
643    let vmax = comps.iter().map(|c| c.v).max().unwrap();
644    let mcu_w = 8 * hmax;
645    let mcu_h = 8 * vmax;
646    let mcus_x = width.div_ceil(mcu_w);
647    let mcus_y = height.div_ceil(mcu_h);
648    // Every 8x8 block costs at least two bits of scan data (a DC code and an end-of-block code),
649    // so a frame header claiming more blocks than the data could hold is rejected before the
650    // planes are allocated.
651    let scan = scan_start.ok_or(ErrorsJSL::InvalidInputRange("JPEG file has no scan."))?;
652    let blocks = mcus_x * mcus_y * comps.iter().map(|c| c.h * c.v).sum::<usize>();
653    if blocks / 4 > data.len().saturating_sub(scan) {
654        return Err(ErrorsJSL::InvalidInputRange("JPEG scan data are shorter than the frame needs."));
655    }
656    for c in comps.iter_mut() {
657        c.plane_w = mcus_x * c.h * 8;
658        c.plane = vec![0.0; c.plane_w * mcus_y * c.v * 8];
659    }
660
661    let mut reader = BitReader::new(data, scan);
662    let mut prev_dc = vec![0i32; comps.len()];
663    let mut mcu_count = 0usize;
664    for my in 0..mcus_y {
665        for mx in 0..mcus_x {
666            if restart_interval > 0 && mcu_count > 0 && mcu_count.is_multiple_of(restart_interval) {
667                reader.restart()?;
668                prev_dc.iter_mut().for_each(|p| *p = 0);
669            }
670            mcu_count += 1;
671            for (ci, comp) in comps.iter_mut().enumerate() {
672                let q = quant[comp.quant_id].ok_or(ErrorsJSL::InvalidInputRange("Missing JPEG quantization table."))?;
673                let dc = dc_tables[comp.dc_id].as_ref().ok_or(ErrorsJSL::InvalidInputRange("Missing JPEG DC table."))?;
674                let ac = ac_tables[comp.ac_id].as_ref().ok_or(ErrorsJSL::InvalidInputRange("Missing JPEG AC table."))?;
675                for bv in 0..comp.v {
676                    for bh in 0..comp.h {
677                        let mut coef = [0.0; 64];
678                        let cat = reader.decode(dc)? as u32;
679                        if cat > 11 {
680                            return Err(ErrorsJSL::InvalidInputRange("Invalid JPEG DC category."));
681                        }
682                        prev_dc[ci] += extend(reader.bits(cat)?, cat);
683                        coef[0] = (prev_dc[ci] * q[0] as i32) as f64;
684                        let mut k = 1;
685                        while k < 64 {
686                            let sym = reader.decode(ac)?;
687                            let (run, size) = ((sym >> 4) as usize, (sym & 15) as u32);
688                            if size == 0 {
689                                if run == 15 {
690                                    k += 16;
691                                    continue;
692                                }
693                                break; // end of block
694                            }
695                            k += run;
696                            if k > 63 {
697                                return Err(ErrorsJSL::InvalidInputRange("JPEG AC run exceeds the block."));
698                            }
699                            let z = ZIGZAG[k];
700                            coef[z] = (extend(reader.bits(size)?, size) * q[z] as i32) as f64;
701                            k += 1;
702                        }
703                        let samples = idct(&coef);
704                        let x0 = (mx * comp.h + bh) * 8;
705                        let y0 = (my * comp.v + bv) * 8;
706                        for y in 0..8 {
707                            for x in 0..8 {
708                                comp.plane[(y0 + y) * comp.plane_w + x0 + x] = samples[y * 8 + x] + 128.0;
709                            }
710                        }
711                    }
712                }
713            }
714        }
715    }
716
717    // Upsample and colour-convert.
718    let channels = comps.len();
719    let mut pixels = vec![0u8; width * height * channels];
720    let clamp = |v: f64| v.round().clamp(0.0, 255.0) as u8;
721    // ANCHOR: upsample
722    // A subsampled component is interpolated linearly between its sample centres, as libjpeg's
723    // "fancy" upsampling does: for 2:1 that weights the nearer sample 3/4 and the farther 1/4 in
724    // each direction (9/3/3/1 sixteenths for 2:1 both ways). Samples beyond the component's
725    // edge repeat the last one.
726    let sample = |c: &Component, x: usize, y: usize| -> f64 {
727        let (rh, rv) = (hmax / c.h, vmax / c.v);
728        if rh == 1 && rv == 1 {
729            return c.plane[y * c.plane_w + x];
730        }
731        let (cw, ch) = ((width * c.h).div_ceil(hmax), (height * c.v).div_ceil(vmax));
732        let at = |i: isize, j: isize| c.plane[(j.clamp(0, ch as isize - 1) as usize) * c.plane_w + i.clamp(0, cw as isize - 1) as usize].clamp(0.0, 255.0);
733        let u = (x as f64 + 0.5) / rh as f64 - 0.5;
734        let v = (y as f64 + 0.5) / rv as f64 - 0.5;
735        let (i, j) = (u.floor(), v.floor());
736        let (fu, fv) = (u - i, v - j);
737        let (i, j) = (i as isize, j as isize);
738        (1.0 - fv) * ((1.0 - fu) * at(i, j) + fu * at(i + 1, j)) + fv * ((1.0 - fu) * at(i, j + 1) + fu * at(i + 1, j + 1))
739    };
740    // ANCHOR_END: upsample
741    for y in 0..height {
742        for x in 0..width {
743            let sample = |c: &Component| sample(c, x, y);
744            let o = (y * width + x) * channels;
745            if channels == 1 {
746                pixels[o] = clamp(sample(&comps[0]));
747            } else {
748                let (yy, cb, cr) = (sample(&comps[0]), sample(&comps[1]) - 128.0, sample(&comps[2]) - 128.0);
749                pixels[o] = clamp(yy + 1.402 * cr);
750                pixels[o + 1] = clamp(yy - 0.344_136 * cb - 0.714_136 * cr);
751                pixels[o + 2] = clamp(yy + 1.772 * cb);
752            }
753        }
754    }
755    Ok(JpegImage { width, height, channels, pixels })
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761
762    #[test]
763    fn a_frame_larger_than_its_scan_data_is_an_error() {
764        // A 65535 x 65535 frame header on a tiny file used to allocate 100 GB of planes.
765        let mut bytes = jpeg_encode(&[128u8; 64], 8, 8, 1, 90).unwrap();
766        let sof = bytes.windows(2).position(|w| w == [0xFF, 0xC0]).unwrap();
767        bytes[sof + 5..sof + 9].copy_from_slice(&[0xFF; 4]);
768        assert!(jpeg_decode(&bytes).is_err());
769    }
770
771    fn psnr(a: &[u8], b: &[u8]) -> f64 {
772        let mse: f64 = a.iter().zip(b).map(|(&x, &y)| (x as f64 - y as f64).powi(2)).sum::<f64>() / a.len() as f64;
773        if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64 * 255.0 / mse).log10() }
774    }
775
776    /// A smooth synthetic test image with gradients and a few edges.
777    fn test_image(w: usize, h: usize, channels: usize) -> Vec<u8> {
778        let mut p = Vec::with_capacity(w * h * channels);
779        for y in 0..h {
780            for x in 0..w {
781                let base = (x * 255 / w.max(1)) as f64 * 0.6 + (y * 255 / h.max(1)) as f64 * 0.4;
782                let edge = if (x / 8 + y / 8) % 4 == 0 { 40.0 } else { 0.0 };
783                let v = (base + edge).min(255.0);
784                if channels == 1 {
785                    p.push(v as u8);
786                } else {
787                    p.push(v as u8);
788                    p.push((255.0 - v) as u8);
789                    p.push(((x * 7 + y * 3) % 256) as u8);
790                }
791            }
792        }
793        p
794    }
795
796    #[test]
797    fn standard_huffman_tables_are_complete() {
798        // AC tables must cover (run 0..=15, size 1..=10) plus EOB (0x00) and ZRL (0xF0).
799        let mut expected: Vec<u8> = vec![0x00, 0xF0];
800        for run in 0..16u8 {
801            for size in 1..=10u8 {
802                expected.push(run << 4 | size);
803            }
804        }
805        expected.sort_unstable();
806        for spec in [&AC_LUMA, &AC_CHROMA] {
807            assert_eq!(spec.counts.iter().map(|&c| c as usize).sum::<usize>(), spec.symbols.len());
808            let mut got = spec.symbols.to_vec();
809            got.sort_unstable();
810            assert_eq!(got, expected);
811        }
812        for spec in [&DC_LUMA, &DC_CHROMA] {
813            assert_eq!(spec.counts.iter().map(|&c| c as usize).sum::<usize>(), 12);
814        }
815        // All tables must be valid prefix codes.
816        for spec in [&DC_LUMA, &DC_CHROMA, &AC_LUMA, &AC_CHROMA] {
817            assert!(HuffDecoder::new(&spec.counts, spec.symbols).is_ok());
818        }
819    }
820
821    #[test]
822    fn dct_round_trip_and_dc_gain() {
823        let mut block = [0.0; 64];
824        for (i, v) in block.iter_mut().enumerate() {
825            *v = ((i * 37) % 101) as f64 - 50.0;
826        }
827        let back = idct(&fdct(&block));
828        assert!(block.iter().zip(&back).all(|(a, b)| (a - b).abs() < 1e-9));
829        // A constant block has only a DC term equal to 8 * value.
830        let flat = fdct(&[10.0; 64]);
831        assert!((flat[0] - 80.0).abs() < 1e-9 && flat[1..].iter().all(|c| c.abs() < 1e-9));
832    }
833
834    #[test]
835    fn magnitude_coding_round_trips() {
836        for v in -2047..=2047 {
837            let cat = category(v);
838            assert_eq!(extend(magnitude_bits(v, cat), cat), v);
839        }
840        assert_eq!(category(0), 0);
841        assert_eq!(category(-1), 1);
842        assert_eq!(category(255), 8);
843    }
844
845    #[test]
846    fn gray_round_trip_quality() {
847        let img = test_image(37, 29, 1); // not a multiple of 8
848        let jpg = jpeg_encode(&img, 37, 29, 1, 90).unwrap();
849        assert_eq!(&jpg[..2], &[0xFF, 0xD8]);
850        assert_eq!(&jpg[jpg.len() - 2..], &[0xFF, 0xD9]);
851        let dec = jpeg_decode(&jpg).unwrap();
852        assert_eq!((dec.width, dec.height, dec.channels), (37, 29, 1));
853        assert!(psnr(&img, &dec.pixels) > 35.0, "psnr {}", psnr(&img, &dec.pixels));
854    }
855
856    #[test]
857    fn rgb_round_trip_quality_and_size_tradeoff() {
858        let img = test_image(48, 40, 3);
859        let high = jpeg_encode(&img, 48, 40, 3, 95).unwrap();
860        let low = jpeg_encode(&img, 48, 40, 3, 20).unwrap();
861        assert!(low.len() < high.len());
862        let dh = jpeg_decode(&high).unwrap();
863        let dl = jpeg_decode(&low).unwrap();
864        assert_eq!(dh.channels, 3);
865        assert!(psnr(&img, &dh.pixels) > psnr(&img, &dl.pixels));
866        assert!(psnr(&img, &dh.pixels) > 28.0, "psnr {}", psnr(&img, &dh.pixels));
867        assert!(img.len() > high.len(), "should compress a smooth image");
868    }
869
870    #[test]
871    fn flat_image_is_exact_and_tiny() {
872        let img = vec![200u8; 16 * 16];
873        let jpg = jpeg_encode(&img, 16, 16, 1, 75).unwrap();
874        assert!(jpg.len() < 700);
875        let dec = jpeg_decode(&jpg).unwrap();
876        assert!(dec.pixels.iter().all(|&p| (p as i32 - 200).abs() <= 1));
877    }
878
879    #[test]
880    fn noisy_image_exercises_long_codes_and_byte_stuffing() {
881        let mut state = 12345u64;
882        let img: Vec<u8> = (0..64 * 64)
883            .map(|_| {
884                state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
885                (state >> 56) as u8
886            })
887            .collect();
888        let jpg = jpeg_encode(&img, 64, 64, 1, 100).unwrap();
889        let dec = jpeg_decode(&jpg).unwrap();
890        assert!(psnr(&img, &dec.pixels) > 38.0, "psnr {}", psnr(&img, &dec.pixels));
891    }
892
893    /// Smooth test pattern used to produce the libjpeg fixtures below:
894    /// R rises left to right, G rises top to bottom, B is constant.
895    fn gradient(w: usize, h: usize) -> Vec<u8> {
896        let mut p = Vec::with_capacity(w * h * 3);
897        for y in 0..h {
898            for x in 0..w {
899                p.extend_from_slice(&[(x * 255 / (w - 1)) as u8, (y * 255 / (h - 1)) as u8, 128]);
900            }
901        }
902        p
903    }
904
905    // Both files were written by libjpeg (Pillow / ImageMagick) from `gradient`, quality 90.
906    //  - LIBJPEG_420_16X16: 4:2:0 chroma subsampling.
907    //  - LIBJPEG_RESTART_24X16: 4:4:4 with a restart interval of 2 MCUs.
908    const LIBJPEG_420_16X16: &[u8] = &[
909    0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01,
910    0x00, 0x01, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03,
911    0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0a, 0x07,
912    0x07, 0x06, 0x08, 0x0c, 0x0a, 0x0c, 0x0c, 0x0b, 0x0a, 0x0b, 0x0b, 0x0d, 0x0e, 0x12, 0x10, 0x0d,
913    0x0e, 0x11, 0x0e, 0x0b, 0x0b, 0x10, 0x16, 0x10, 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0c, 0x0f,
914    0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, 0x14, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x03, 0x04,
915    0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, 0x14, 0x0d, 0x0b, 0x0d, 0x14, 0x14, 0x14, 0x14,
916    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
917    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
918    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xff, 0xc0,
919    0x00, 0x11, 0x08, 0x00, 0x10, 0x00, 0x10, 0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11,
920    0x01, 0xff, 0xc4, 0x00, 0x1f, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00,
921    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
922    0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05,
923    0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21,
924    0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23,
925    0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17,
926    0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a,
927    0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
928    0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,
929    0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
930    0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
931    0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5,
932    0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1,
933    0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xff, 0xc4, 0x00, 0x1f, 0x01, 0x00, 0x03,
934    0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
935    0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 0xc4, 0x00, 0xb5, 0x11, 0x00,
936    0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00,
937    0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13,
938    0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15,
939    0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27,
940    0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
941    0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
942    0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88,
943    0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6,
944    0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4,
945    0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2,
946    0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9,
947    0xfa, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00, 0x3f, 0x00, 0xf9,
948    0x7b, 0xc2, 0x3f, 0x09, 0x3e, 0xe7, 0xee, 0x7f, 0x4a, 0xf6, 0xcf, 0x08, 0x7c, 0x24, 0xfb, 0x9f,
949    0xb9, 0xfd, 0x2b, 0xda, 0x3c, 0x21, 0xf0, 0x93, 0x84, 0xfd, 0xcf, 0xe9, 0x5e, 0xd9, 0xe1, 0x0f,
950    0x84, 0x9c, 0xa7, 0xee, 0x7f, 0x4a, 0x79, 0xd7, 0x19, 0xef, 0xef, 0x07, 0x86, 0x3e, 0x20, 0xff,
951    0x00, 0x0f, 0xdf, 0xec, 0x7f, 0xff, 0xd9,
952    ];
953
954    const LIBJPEG_RESTART_24X16: &[u8] = &[
955    0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01,
956    0x00, 0x01, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x43, 0x00, 0x03, 0x02, 0x02, 0x03, 0x02, 0x02, 0x03,
957    0x03, 0x03, 0x03, 0x04, 0x03, 0x03, 0x04, 0x05, 0x08, 0x05, 0x05, 0x04, 0x04, 0x05, 0x0a, 0x07,
958    0x07, 0x06, 0x08, 0x0c, 0x0a, 0x0c, 0x0c, 0x0b, 0x0a, 0x0b, 0x0b, 0x0d, 0x0e, 0x12, 0x10, 0x0d,
959    0x0e, 0x11, 0x0e, 0x0b, 0x0b, 0x10, 0x16, 0x10, 0x11, 0x13, 0x14, 0x15, 0x15, 0x15, 0x0c, 0x0f,
960    0x17, 0x18, 0x16, 0x14, 0x18, 0x12, 0x14, 0x15, 0x14, 0xff, 0xdb, 0x00, 0x43, 0x01, 0x03, 0x04,
961    0x04, 0x05, 0x04, 0x05, 0x09, 0x05, 0x05, 0x09, 0x14, 0x0d, 0x0b, 0x0d, 0x14, 0x14, 0x14, 0x14,
962    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
963    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14,
964    0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0x14, 0xff, 0xc0,
965    0x00, 0x11, 0x08, 0x00, 0x10, 0x00, 0x18, 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11,
966    0x01, 0xff, 0xc4, 0x00, 0x16, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
967    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x06, 0x08, 0xff, 0xc4, 0x00, 0x1d, 0x10, 0x00, 0x00,
968    0x06, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05,
969    0x07, 0x23, 0x31, 0xa1, 0x06, 0x32, 0x41, 0x51, 0xff, 0xc4, 0x00, 0x18, 0x01, 0x01, 0x01, 0x00,
970    0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x07, 0x05,
971    0x08, 0x09, 0xff, 0xc4, 0x00, 0x1a, 0x11, 0x00, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
972    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x04, 0x31, 0x06, 0x21, 0x22, 0xff, 0xdd,
973    0x00, 0x04, 0x00, 0x02, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03, 0x11, 0x00,
974    0x3f, 0x00, 0xc9, 0x84, 0x09, 0x1c, 0x33, 0xe7, 0x05, 0x96, 0x43, 0xab, 0xd8, 0x51, 0x2e, 0x43,
975    0x5d, 0x08, 0xf8, 0xfa, 0x47, 0x0c, 0xd0, 0x2f, 0x21, 0xd5, 0xec, 0xbb, 0x25, 0xc8, 0x6b, 0xa3,
976    0xff, 0xd0, 0x9a, 0xc7, 0xd2, 0x3d, 0x59, 0xf3, 0x83, 0x2b, 0x21, 0xd5, 0xec, 0xdc, 0x14, 0xb9,
977    0x0d, 0x74, 0x23, 0x90, 0x24, 0x70, 0xcd, 0x02, 0xf2, 0x1d, 0x5e, 0xce, 0x3d, 0xa5, 0xc8, 0x6b,
978    0xa3, 0xff, 0xd1, 0x69, 0x20, 0x48, 0xe1, 0x9a, 0x01, 0x24, 0x3a, 0xbd, 0x93, 0x24, 0xb9, 0x0d,
979    0x74, 0x23, 0x90, 0x24, 0x7a, 0xb3, 0x40, 0xbc, 0x87, 0x57, 0xb2, 0xee, 0x97, 0x21, 0xae, 0x8f,
980    0xff, 0xd9,
981    ];
982
983    /// Pillow's (libjpeg's) decoding of LIBJPEG_420_16X16, with its interpolated chroma.
984    const PILLOW_420_16X16: [u8; 768] = [
985        0, 5, 119, 10, 5, 121, 29, 4, 121, 48, 5, 121, 63, 4, 122, 79, 5, 120, 95, 6, 122, 112, 5, 121,
986        132, 5, 122, 148, 3, 120, 164, 5, 123, 180, 6, 121, 197, 6, 120, 214, 6, 120, 234, 5, 122, 245, 6, 125,
987        4, 16, 124, 15, 17, 126, 35, 17, 127, 53, 17, 127, 69, 17, 127, 85, 17, 126, 101, 19, 127, 117, 18, 126,
988        137, 17, 127, 153, 15, 126, 169, 17, 126, 186, 18, 127, 201, 18, 126, 220, 18, 126, 239, 17, 128, 250, 18, 130,
989        6, 32, 125, 17, 33, 128, 37, 33, 130, 54, 32, 130, 70, 33, 129, 87, 33, 129, 102, 35, 130, 119, 34, 128,
990        139, 33, 131, 156, 32, 130, 172, 34, 130, 188, 34, 130, 204, 34, 130, 222, 34, 129, 243, 33, 130, 254, 34, 132,
991        6, 49, 127, 17, 50, 129, 37, 49, 131, 54, 49, 131, 71, 49, 131, 87, 50, 128, 103, 52, 131, 119, 50, 130,
992        138, 49, 129, 155, 48, 128, 171, 50, 130, 188, 51, 129, 203, 51, 128, 222, 51, 130, 242, 49, 130, 253, 50, 132,
993        4, 69, 127, 15, 69, 129, 36, 68, 129, 54, 68, 131, 69, 67, 130, 86, 68, 128, 101, 70, 130, 118, 68, 129,
994        138, 68, 130, 155, 67, 128, 170, 68, 131, 187, 69, 129, 203, 69, 128, 221, 69, 128, 241, 68, 131, 252, 69, 133,
995        3, 85, 125, 14, 85, 127, 34, 85, 128, 52, 85, 130, 68, 85, 129, 84, 86, 127, 102, 87, 130, 117, 86, 128,
996        136, 85, 128, 153, 84, 128, 170, 84, 129, 185, 87, 128, 201, 86, 127, 219, 87, 127, 239, 86, 130, 250, 87, 132,
997        4, 103, 126, 16, 104, 128, 35, 102, 129, 53, 103, 130, 68, 102, 129, 83, 103, 127, 100, 104, 129, 117, 103, 128,
998        137, 103, 128, 152, 102, 127, 169, 103, 130, 186, 104, 127, 202, 104, 127, 220, 103, 129, 240, 103, 129, 251, 104, 132,
999        4, 119, 124, 15, 120, 126, 35, 119, 129, 52, 118, 130, 69, 119, 128, 85, 119, 128, 101, 121, 128, 117, 120, 127,
1000        136, 119, 129, 153, 117, 127, 169, 119, 128, 185, 120, 128, 201, 120, 127, 219, 119, 127, 240, 118, 129, 251, 119, 130,
1001        3, 135, 124, 15, 136, 127, 36, 135, 130, 54, 135, 129, 70, 135, 129, 86, 135, 129, 102, 137, 130, 119, 136, 128,
1002        139, 136, 129, 155, 135, 128, 170, 136, 127, 186, 136, 127, 203, 136, 127, 220, 135, 128, 241, 136, 132, 252, 137, 132,
1003        4, 151, 123, 15, 152, 126, 35, 151, 128, 54, 152, 129, 70, 152, 130, 87, 152, 128, 103, 152, 130, 118, 152, 128,
1004        138, 152, 129, 155, 150, 128, 172, 152, 128, 187, 153, 128, 202, 152, 127, 220, 153, 127, 240, 152, 130, 252, 153, 132,
1005        5, 168, 125, 17, 169, 128, 37, 169, 129, 54, 169, 128, 71, 169, 130, 85, 170, 128, 103, 171, 130, 118, 169, 128,
1006        138, 169, 128, 153, 168, 127, 171, 169, 128, 187, 170, 127, 203, 170, 127, 221, 170, 127, 241, 169, 129, 253, 171, 133,
1007        3, 185, 124, 14, 186, 126, 34, 186, 127, 53, 187, 128, 69, 187, 129, 86, 187, 127, 100, 188, 128, 117, 187, 127,
1008        137, 187, 128, 154, 185, 126, 169, 187, 127, 186, 187, 127, 201, 187, 126, 219, 187, 126, 241, 186, 129, 252, 187, 131,
1009        1, 204, 122, 13, 206, 125, 34, 205, 127, 52, 204, 127, 68, 204, 128, 84, 205, 126, 100, 207, 129, 117, 205, 127,
1010        137, 205, 128, 153, 204, 127, 168, 205, 127, 184, 205, 126, 201, 206, 126, 218, 205, 126, 239, 206, 129, 250, 206, 131,
1011        1, 221, 123, 12, 222, 125, 34, 222, 128, 52, 221, 128, 68, 222, 128, 84, 222, 127, 99, 223, 127, 116, 221, 126,
1012        136, 221, 127, 153, 220, 125, 168, 222, 128, 185, 222, 126, 201, 223, 125, 218, 222, 127, 238, 221, 129, 250, 223, 132,
1013        4, 236, 126, 16, 238, 129, 36, 238, 130, 54, 237, 131, 70, 237, 131, 86, 237, 130, 102, 240, 131, 118, 238, 130,
1014        139, 238, 130, 155, 237, 129, 170, 237, 131, 186, 238, 128, 202, 238, 128, 220, 238, 128, 241, 238, 131, 252, 239, 134,
1015        10, 249, 132, 21, 250, 134, 41, 249, 135, 59, 250, 136, 75, 249, 136, 92, 251, 135, 107, 251, 137, 123, 250, 135,
1016        143, 250, 136, 160, 248, 135, 176, 250, 137, 192, 251, 135, 207, 250, 134, 226, 251, 134, 246, 250, 137, 255, 251, 139,
1017    ];
1018
1019    #[test]
1020    fn decodes_libjpeg_subsampled_file() {
1021        let img = jpeg_decode(LIBJPEG_420_16X16).unwrap();
1022        assert_eq!((img.width, img.height, img.channels), (16, 16, 3));
1023        let want = gradient(16, 16);
1024        assert!(psnr(&img.pixels, &want) > 30.0, "psnr {}", psnr(&img.pixels, &want));
1025        // Interpolating the chroma as libjpeg does reproduces its output to rounding; replicating
1026        // it differed by up to 14 levels here.
1027        let worst = img.pixels.iter().zip(PILLOW_420_16X16).map(|(&a, b)| a.abs_diff(b)).max().unwrap();
1028        assert!(worst <= 2, "largest difference from libjpeg {worst}");
1029    }
1030
1031    #[test]
1032    fn decodes_libjpeg_restart_intervals() {
1033        assert!(LIBJPEG_RESTART_24X16.windows(2).any(|w| w == [0xFF, 0xDD]), "fixture has a DRI segment");
1034        let img = jpeg_decode(LIBJPEG_RESTART_24X16).unwrap();
1035        assert_eq!((img.width, img.height, img.channels), (24, 16, 3));
1036        let want = gradient(24, 16);
1037        assert!(psnr(&img.pixels, &want) > 35.0, "psnr {}", psnr(&img.pixels, &want));
1038    }
1039
1040    #[test]
1041    fn rejects_malformed_input() {
1042        assert!(jpeg_decode(&[]).is_err());
1043        assert!(jpeg_decode(b"not a jpeg").is_err());
1044        assert!(jpeg_decode(&LIBJPEG_420_16X16[..60]).is_err()); // truncated in the headers
1045        let mut corrupt = LIBJPEG_RESTART_24X16.to_vec();
1046        let sos = corrupt.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap();
1047        corrupt.truncate(sos + 20);
1048        assert!(jpeg_decode(&corrupt).is_err()); // scan data ends early
1049        let good = jpeg_encode(&test_image(16, 16, 1), 16, 16, 1, 80).unwrap();
1050        assert!(jpeg_decode(&good[..good.len() / 2]).is_err());
1051        assert!(jpeg_encode(&[0; 10], 4, 4, 1, 50).is_err());
1052        assert!(jpeg_encode(&[0; 16], 4, 4, 2, 50).is_err());
1053        assert!(jpeg_encode(&[], 0, 4, 1, 50).is_err());
1054    }
1055}