Skip to main content

pltrs_codec/jpeg/encode/
mod.rs

1//! Baseline JPEG encoding of RGB images with libjpeg-turbo's defaults —
2//! the settings Pillow saves with: JFIF, YCbCr with 4:2:0 chroma
3//! subsampling, the accurate integer DCT, Annex K quantization tables
4//! scaled by quality and the standard Huffman tables. Encoding mirrors
5//! libjpeg's arithmetic, so files match Pillow's byte for byte.
6
7mod fdct;
8mod huffman;
9mod planes;
10
11use std::fmt;
12
13use self::fdct::{Quantizer, forward_dct};
14use self::huffman::{BitWriter, BlockCoder, CodeTable};
15use self::planes::{Plane, planes};
16use super::marker::{APP0, DHT, DQT, EOI, SOF0, SOI, SOS};
17use super::tables::{
18    AC_CHROMINANCE, AC_LUMINANCE, DC_CHROMINANCE, DC_LUMINANCE, HuffmanSpec, TableSet, ZIGZAG,
19    quant_table,
20};
21
22/// Settings of an encoding.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub struct JpegOptions {
25    /// Quality from 1 (smallest) to 100 (best); 75 by default, as in
26    /// Pillow.
27    pub quality: u8,
28    /// The resolution recorded in the JFIF header, in dots per inch.
29    pub dpi: u16,
30}
31
32impl Default for JpegOptions {
33    fn default() -> Self {
34        Self {
35            quality: 75,
36            dpi: 72,
37        }
38    }
39}
40
41/// Why an image could not be encoded.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum JpegError {
44    /// A side is zero or larger than JPEG's 65 535 pixels.
45    InvalidDimensions {
46        /// The requested width.
47        width: u32,
48        /// The requested height.
49        height: u32,
50    },
51    /// The pixel data does not have `width × height × 3` bytes.
52    DataLengthMismatch {
53        /// The bytes needed.
54        expected: usize,
55        /// The bytes given.
56        actual: usize,
57    },
58}
59
60impl fmt::Display for JpegError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::InvalidDimensions { width, height } => write!(
64                f,
65                "a JPEG image cannot be {width} × {height} pixels (each side must be 1 to 65535)"
66            ),
67            Self::DataLengthMismatch { expected, actual } => write!(
68                f,
69                "the image has {actual} bytes of pixel data, expected {expected}"
70            ),
71        }
72    }
73}
74
75impl std::error::Error for JpegError {}
76
77/// Encodes `width × height` RGB pixels, row by row, as a baseline JPEG
78/// file.
79///
80/// ```
81/// use pltrs_codec::jpeg::{JpegOptions, encode_rgb8};
82/// let jpeg = encode_rgb8(2, 2, &[200; 12], &JpegOptions::default())?;
83/// assert!(jpeg.starts_with(&[0xFF, 0xD8]) && jpeg.ends_with(&[0xFF, 0xD9]));
84/// # Ok::<(), pltrs_codec::jpeg::JpegError>(())
85/// ```
86///
87/// # Errors
88///
89/// When a side is out of range or the data has the wrong length.
90pub fn encode_rgb8(
91    width: u32,
92    height: u32,
93    rgb: &[u8],
94    options: &JpegOptions,
95) -> Result<Vec<u8>, JpegError> {
96    let side = |n: u32| u16::try_from(n).ok().filter(|&n| n > 0);
97    let (Some(columns), Some(rows)) = (side(width), side(height)) else {
98        return Err(JpegError::InvalidDimensions { width, height });
99    };
100    let expected = usize::from(columns) * usize::from(rows) * 3;
101    if rgb.len() != expected {
102        return Err(JpegError::DataLengthMismatch {
103            expected,
104            actual: rgb.len(),
105        });
106    }
107    let luma_table = quant_table(TableSet::Luminance, options.quality);
108    let chroma_table = quant_table(TableSet::Chrominance, options.quality);
109    let mut jpeg = Vec::new();
110    jpeg.extend_from_slice(&[0xFF, SOI]);
111    write_jfif(&mut jpeg, options.dpi);
112    write_quant_table(&mut jpeg, TableSet::Luminance, &luma_table);
113    write_quant_table(&mut jpeg, TableSet::Chrominance, &chroma_table);
114    write_frame(&mut jpeg, columns, rows);
115    for (class, set, spec) in [
116        (0, TableSet::Luminance, &DC_LUMINANCE),
117        (1, TableSet::Luminance, &AC_LUMINANCE),
118        (0, TableSet::Chrominance, &DC_CHROMINANCE),
119        (1, TableSet::Chrominance, &AC_CHROMINANCE),
120    ] {
121        write_huffman_table(&mut jpeg, class, set, spec);
122    }
123    write_scan_header(&mut jpeg);
124    let planes = planes(usize::from(columns), usize::from(rows), rgb);
125    jpeg.extend(scan_data(
126        &planes,
127        usize::from(columns),
128        usize::from(rows),
129        [Quantizer::new(&luma_table), Quantizer::new(&chroma_table)],
130    ));
131    jpeg.extend_from_slice(&[0xFF, EOI]);
132    Ok(jpeg)
133}
134
135/// The entropy-coded MCUs of an image: per 16×16 pixels, four Y blocks,
136/// one Cb and one Cr. Luminance blocks past the image's last block column
137/// or row are "dummy" blocks holding only the DC term of the block before,
138/// as libjpeg's `compress_data` makes them.
139fn scan_data(
140    planes: &[Plane; 3],
141    width: usize,
142    height: usize,
143    [luma, chroma]: [Quantizer; 2],
144) -> Vec<u8> {
145    let tables = [
146        CodeTable::new(&DC_LUMINANCE),
147        CodeTable::new(&AC_LUMINANCE),
148        CodeTable::new(&DC_CHROMINANCE),
149        CodeTable::new(&AC_CHROMINANCE),
150    ];
151    let mut coders = [
152        BlockCoder::new(&tables[0], &tables[1]),
153        BlockCoder::new(&tables[2], &tables[3]),
154        BlockCoder::new(&tables[2], &tables[3]),
155    ];
156    let (luma_columns, luma_rows) = (width.div_ceil(8), height.div_ceil(8));
157    let mut out = BitWriter::default();
158    for mcu_row in 0..height.div_ceil(16) {
159        for mcu_column in 0..width.div_ceil(16) {
160            let mut previous = [0; 64];
161            for y in 0..2 {
162                for x in 0..2 {
163                    let (column, row) = (mcu_column * 2 + x, mcu_row * 2 + y);
164                    let block = if column < luma_columns && row < luma_rows {
165                        luma.quantize(&forward_dct(&planes[0].block(column, row)))
166                    } else {
167                        dummy(previous[0])
168                    };
169                    coders[0].encode(&mut out, &block);
170                    previous = block;
171                }
172            }
173            for (coder, plane) in coders[1..].iter_mut().zip(&planes[1..]) {
174                let block = chroma.quantize(&forward_dct(&plane.block(mcu_column, mcu_row)));
175                coder.encode(&mut out, &block);
176            }
177        }
178    }
179    out.finish()
180}
181
182/// A block with only a DC term.
183fn dummy(dc: i32) -> [i32; 64] {
184    let mut block = [0; 64];
185    block[0] = dc;
186    block
187}
188
189/// Writes a marker segment: the marker and its length-prefixed payload.
190fn write_segment(jpeg: &mut Vec<u8>, marker: u8, payload: &[u8]) {
191    let length = u16::try_from(payload.len() + 2).expect("segments are short");
192    jpeg.extend_from_slice(&[0xFF, marker]);
193    jpeg.extend_from_slice(&length.to_be_bytes());
194    jpeg.extend_from_slice(payload);
195}
196
197/// The JFIF 1.01 header with the resolution in dots per inch.
198fn write_jfif(jpeg: &mut Vec<u8>, dpi: u16) {
199    let mut payload = b"JFIF\0\x01\x01\x01".to_vec();
200    payload.extend_from_slice(&dpi.to_be_bytes());
201    payload.extend_from_slice(&dpi.to_be_bytes());
202    payload.extend_from_slice(&[0, 0]);
203    write_segment(jpeg, APP0, &payload);
204}
205
206/// A quantization table of 8-bit steps, in zigzag order.
207fn write_quant_table(jpeg: &mut Vec<u8>, set: TableSet, table: &[u16; 64]) {
208    let mut payload = vec![set.index()];
209    payload.extend(
210        ZIGZAG
211            .iter()
212            .map(|&i| u8::try_from(table[i]).expect("baseline steps are bytes")),
213    );
214    write_segment(jpeg, DQT, &payload);
215}
216
217/// The baseline frame header: 8-bit samples, Y sampled 2×2, Cb and Cr
218/// 1×1.
219fn write_frame(jpeg: &mut Vec<u8>, width: u16, height: u16) {
220    let mut payload = vec![8];
221    payload.extend_from_slice(&height.to_be_bytes());
222    payload.extend_from_slice(&width.to_be_bytes());
223    payload.extend_from_slice(&[3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1]);
224    write_segment(jpeg, SOF0, &payload);
225}
226
227/// A Huffman table of `class` 0 (DC) or 1 (AC).
228fn write_huffman_table(jpeg: &mut Vec<u8>, class: u8, set: TableSet, spec: &HuffmanSpec) {
229    let mut payload = vec![class << 4 | set.index()];
230    payload.extend_from_slice(&spec.counts);
231    payload.extend_from_slice(spec.symbols);
232    write_segment(jpeg, DHT, &payload);
233}
234
235/// The header of the single interleaved scan.
236fn write_scan_header(jpeg: &mut Vec<u8>) {
237    write_segment(jpeg, SOS, &[3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 63, 0]);
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    /// The marker segments of a file, up to the scan data.
245    fn markers(jpeg: &[u8]) -> Vec<u8> {
246        let mut found = Vec::new();
247        let mut at = 2;
248        loop {
249            let marker = jpeg[at + 1];
250            found.push(marker);
251            if marker == SOS {
252                return found;
253            }
254            at += 2 + usize::from(u16::from_be_bytes([jpeg[at + 2], jpeg[at + 3]]));
255        }
256    }
257
258    #[test]
259    fn segments_come_in_libjpeg_order() {
260        let jpeg = encode_rgb8(17, 9, &[90; 17 * 9 * 3], &JpegOptions::default()).unwrap();
261        assert_eq!(
262            markers(&jpeg),
263            [APP0, DQT, DQT, SOF0, DHT, DHT, DHT, DHT, SOS]
264        );
265        assert_eq!(&jpeg[6..11], b"JFIF\0");
266        assert_eq!(&jpeg[jpeg.len() - 2..], [0xFF, EOI]);
267    }
268
269    #[test]
270    fn edge_sizes_encode() {
271        for (width, height) in [(1, 1), (8, 8), (15, 17), (16, 16), (33, 2)] {
272            let rgb: Vec<u8> = (0..width * height * 3)
273                .map(|i| u8::try_from(i * 7 % 256).unwrap())
274                .collect();
275            let jpeg = encode_rgb8(width, height, &rgb, &JpegOptions::default()).unwrap();
276            assert!(jpeg.len() > 300, "{width} × {height}");
277        }
278    }
279
280    #[test]
281    fn bad_input_is_rejected() {
282        let options = JpegOptions::default();
283        assert_eq!(
284            encode_rgb8(0, 4, &[], &options),
285            Err(JpegError::InvalidDimensions {
286                width: 0,
287                height: 4
288            })
289        );
290        assert_eq!(
291            encode_rgb8(1, 1, &[0; 4], &options),
292            Err(JpegError::DataLengthMismatch {
293                expected: 3,
294                actual: 4
295            })
296        );
297    }
298}