forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

jpeg.rs1062 lines, 34.8 KiBHistoryRawDownload
1//! JPEG decoding (ITU-T T.81): baseline and extended sequential DCT (SOF0,
2//! SOF1) and progressive DCT (SOF2), Huffman coded, with restart markers.
3//!
4//! Chroma is upsampled with the triangle ("fancy") filter rather than by pixel
5//! replication, because replication puts a visible 2-pixel staircase on every
6//! saturated edge of a 4:2:0 photo — the artefact people notice first.
7//!
8//! What is refused, and why it is refused rather than approximated:
9//!
10//! - Arithmetic-coded and lossless/hierarchical JPEGs (SOF3, SOF5-15): a
11//! different entropy coder and a different process, not a variant of this one.
12//! - CMYK and YCCK (4-component, Adobe APP14): decoding them without the ICC
13//! profile they normally travel with produces colours that look right in a
14//! thumbnail and are wrong in print. Named refusal beats plausible garbage.
15//!
16//! EXIF orientation is parsed into [`Metadata::orientation`] and *not* applied
17//! — matching the incumbent `image` crate, so a caller sees the same pixels
18//! from either.
19
20use crate::upsample::upsample;
21use crate::{Image, ImageFormat, Info, Limits, Metadata, Pixels};
22use ec_core::{Error, Result};
23
24/// Zig-zag order: coefficient `k` of a scan sits at natural index `ZIGZAG[k]`.
25const ZIGZAG: [usize; 64] = [
26 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,
27 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59,
28 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
29];
30
31/// A canonical Huffman table, as DHT specifies it.
32#[derive(Clone, Default)]
33struct HuffTable {
34 /// `(length, value)` for every 8-bit prefix, `length == 0` when the code
35 /// is longer than 8 bits and the slow path is needed.
36 lut: Vec<(u8, u8)>,
37 /// Largest code of each length, or -1 when that length is unused.
38 max_code: [i32; 17],
39 /// Index into `values` of the first code of each length.
40 val_ptr: [usize; 17],
41 /// Smallest code of each length.
42 min_code: [i32; 17],
43 values: Vec<u8>,
44}
45
46impl HuffTable {
47 fn build(counts: &[u8; 16], values: Vec<u8>) -> Result<HuffTable> {
48 let mut table = HuffTable {
49 lut: vec![(0, 0); 256],
50 max_code: [-1; 17],
51 val_ptr: [0; 17],
52 min_code: [0; 17],
53 values,
54 };
55 let mut code = 0i32;
56 let mut k = 0usize;
57 for len in 1..=16usize {
58 table.val_ptr[len] = k;
59 table.min_code[len] = code;
60 for _ in 0..counts[len - 1] {
61 if k >= table.values.len() {
62 return Err(Error::corrupt("JPEG: DHT has fewer values than counts"));
63 }
64 if len <= 8 {
65 // Every 8-bit prefix starting with this code maps to it.
66 let shift = 8 - len;
67 let base = (code as usize) << shift;
68 if base + (1 << shift) > 256 {
69 return Err(Error::corrupt("JPEG: over-long Huffman code"));
70 }
71 for slot in base..base + (1 << shift) {
72 table.lut[slot] = (len as u8, table.values[k]);
73 }
74 }
75 code += 1;
76 k += 1;
77 }
78 table.max_code[len] = code - 1;
79 code <<= 1;
80 }
81 Ok(table)
82 }
83}
84
85/// The entropy-coded segment reader: MSB-first bits, `FF 00` unstuffed.
86struct BitReader<'a> {
87 data: &'a [u8],
88 at: usize,
89 bits: u32,
90 count: u32,
91 /// Set once the reader has had to invent bits: the scan's data ran into a
92 /// marker or ended. The fill runs several bytes ahead of the decoder, so
93 /// this says "the tail is padding", never "stop here" — a scan that stops
94 /// on it loses the last blocks it still had bits for.
95 hit_marker: bool,
96}
97
98impl<'a> BitReader<'a> {
99 fn new(data: &'a [u8], at: usize) -> BitReader<'a> {
100 BitReader {
101 data,
102 at,
103 bits: 0,
104 count: 0,
105 hit_marker: false,
106 }
107 }
108
109 fn fill(&mut self) {
110 while self.count <= 24 {
111 let byte = match self.data.get(self.at) {
112 Some(&0xff) => match self.data.get(self.at + 1) {
113 Some(&0x00) => {
114 self.at += 2;
115 0xff
116 }
117 _ => {
118 self.hit_marker = true;
119 0
120 }
121 },
122 Some(&b) => {
123 self.at += 1;
124 b
125 }
126 None => {
127 self.hit_marker = true;
128 0
129 }
130 };
131 self.bits |= u32::from(byte) << (24 - self.count);
132 self.count += 8;
133 }
134 }
135
136 fn peek8(&mut self) -> u8 {
137 self.fill();
138 (self.bits >> 24) as u8
139 }
140
141 fn consume(&mut self, n: u32) {
142 self.bits <<= n;
143 self.count = self.count.saturating_sub(n);
144 }
145
146 fn bit(&mut self) -> u32 {
147 self.fill();
148 let b = self.bits >> 31;
149 self.consume(1);
150 b
151 }
152
153 fn bits(&mut self, n: u32) -> u32 {
154 if n == 0 {
155 return 0;
156 }
157 self.fill();
158 let v = self.bits >> (32 - n);
159 self.consume(n);
160 v
161 }
162
163 fn decode(&mut self, table: &HuffTable) -> Result<u8> {
164 let prefix = self.peek8();
165 let (len, value) = table.lut[prefix as usize];
166 if len != 0 {
167 self.consume(u32::from(len));
168 return Ok(value);
169 }
170 // Codes longer than the lookahead: walk lengths the canonical way.
171 let mut code = i32::from(prefix);
172 self.consume(8);
173 for len in 9..=16usize {
174 code = (code << 1) | self.bit() as i32;
175 if table.max_code[len] >= code && code >= table.min_code[len] {
176 let index = table.val_ptr[len] + (code - table.min_code[len]) as usize;
177 return table
178 .values
179 .get(index)
180 .copied()
181 .ok_or_else(|| Error::corrupt("JPEG: Huffman code outside its table"));
182 }
183 }
184 Err(Error::corrupt("JPEG: no Huffman code matches the bits"))
185 }
186
187 /// T.81 F.2.2.1 EXTEND: sign-extend an `s`-bit magnitude.
188 fn receive_extend(&mut self, s: u8) -> i32 {
189 if s == 0 {
190 return 0;
191 }
192 let v = self.bits(u32::from(s)) as i32;
193 if v < (1 << (s - 1)) {
194 v - (1 << s) + 1
195 } else {
196 v
197 }
198 }
199
200 /// Restart: byte-align and step over the RSTn marker.
201 fn restart(&mut self) -> bool {
202 self.bits = 0;
203 self.count = 0;
204 // Skip to the marker, which a well-formed stream is already at.
205 while self.at + 1 < self.data.len() {
206 if self.data[self.at] == 0xff && (0xd0..=0xd7).contains(&self.data[self.at + 1]) {
207 self.at += 2;
208 return true;
209 }
210 self.at += 1;
211 }
212 self.hit_marker = true;
213 false
214 }
215}
216
217/// One colour component of the frame.
218#[derive(Clone)]
219struct Component {
220 id: u8,
221 h: usize,
222 v: usize,
223 quant: usize,
224 /// Blocks across and down, padded out to whole MCUs.
225 blocks_w: usize,
226 blocks_h: usize,
227 /// Blocks the picture actually covers (`blocks_w` may be larger).
228 used_w: usize,
229 used_h: usize,
230 coeffs: Vec<i16>,
231 dc_pred: i32,
232}
233
234/// Everything the markers before the first scan established.
235struct Frame {
236 progressive: bool,
237 width: u32,
238 height: u32,
239 hmax: usize,
240 vmax: usize,
241 mcus_w: usize,
242 mcus_h: usize,
243 components: Vec<Component>,
244}
245
246fn be16(data: &[u8], at: usize) -> Result<usize> {
247 data.get(at..at + 2)
248 .map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))
249 .ok_or_else(|| Error::corrupt("JPEG: truncated segment"))
250}
251
252/// Dimensions from the frame header alone.
253pub fn info(data: &[u8]) -> Result<Info> {
254 let mut at = 2;
255 while let Some(marker) = next_marker(data, &mut at) {
256 match marker {
257 0xc0..=0xc2 => {
258 let len = be16(data, at)?;
259 let seg = data
260 .get(at + 2..at + len)
261 .ok_or_else(|| Error::corrupt("JPEG: truncated SOF"))?;
262 if seg.len() < 6 {
263 return Err(Error::corrupt("JPEG: short SOF"));
264 }
265 return Ok(Info {
266 format: ImageFormat::Jpeg,
267 height: u32::from(u16::from_be_bytes([seg[1], seg[2]])),
268 width: u32::from(u16::from_be_bytes([seg[3], seg[4]])),
269 });
270 }
271 0xd8 | 0xd9 => {}
272 0xda => break,
273 _ => {
274 let len = be16(data, at)?;
275 at += len.max(2);
276 }
277 }
278 }
279 Err(Error::corrupt("JPEG: no frame header"))
280}
281
282/// Step to the next marker, returning its byte and leaving `at` on its payload.
283fn next_marker(data: &[u8], at: &mut usize) -> Option<u8> {
284 while *at < data.len() {
285 if data[*at] != 0xff {
286 *at += 1;
287 continue;
288 }
289 let mut scan = *at + 1;
290 while data.get(scan) == Some(&0xff) {
291 scan += 1;
292 }
293 let marker = *data.get(scan)?;
294 *at = scan + 1;
295 if marker != 0x00 {
296 return Some(marker);
297 }
298 }
299 None
300}
301
302/// Decode a JPEG.
303pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
304 let mut quant = [[0u16; 64]; 4];
305 let mut dc_tables: Vec<HuffTable> = vec![HuffTable::default(); 4];
306 let mut ac_tables: Vec<HuffTable> = vec![HuffTable::default(); 4];
307 let mut restart_interval = 0usize;
308 let mut frame: Option<Frame> = None;
309 let mut meta = Metadata::default();
310 let mut adobe_transform: Option<u8> = None;
311
312 let mut at = 2;
313 while let Some(marker) = next_marker(data, &mut at) {
314 match marker {
315 0xd8 => continue,
316 0xd9 => break,
317 0x01 | 0xd0..=0xd7 => continue,
318 _ => {}
319 }
320 let len = be16(data, at)?;
321 if len < 2 {
322 return Err(Error::corrupt("JPEG: segment length below 2"));
323 }
324 let seg = data
325 .get(at + 2..at + len)
326 .ok_or_else(|| Error::corrupt("JPEG: truncated segment"))?;
327 match marker {
328 0xdb => read_dqt(seg, &mut quant)?,
329 0xc4 => read_dht(seg, &mut dc_tables, &mut ac_tables)?,
330 0xdd => {
331 if seg.len() < 2 {
332 return Err(Error::corrupt("JPEG: short DRI"));
333 }
334 restart_interval = usize::from(u16::from_be_bytes([seg[0], seg[1]]));
335 }
336 0xc0..=0xc2 => {
337 frame = Some(read_sof(seg, marker == 0xc2, limits)?);
338 }
339 0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
340 return Err(Error::unsupported(
341 format!("JPEG SOF{}", marker & 0x0f),
342 "arithmetic-coded, lossless and hierarchical JPEG are a different process",
343 ));
344 }
345 0xe1 => {
346 if let Some(o) = exif_orientation(seg) {
347 meta.orientation = Some(o);
348 }
349 }
350 0xee => {
351 if seg.starts_with(b"Adobe") {
352 adobe_transform = seg.last().copied();
353 }
354 }
355 0xda => {
356 let frame = frame
357 .as_mut()
358 .ok_or_else(|| Error::corrupt("JPEG: scan before frame header"))?;
359 at = read_scan(
360 data,
361 at + len,
362 seg,
363 frame,
364 &dc_tables,
365 &ac_tables,
366 restart_interval,
367 )?;
368 continue;
369 }
370 _ => {}
371 }
372 at += len;
373 }
374
375 let frame = frame.ok_or_else(|| Error::corrupt("JPEG: no frame header"))?;
376 let pixels = reconstruct(&frame, &quant, adobe_transform)?;
377 Ok(Image {
378 width: frame.width,
379 height: frame.height,
380 pixels,
381 meta,
382 })
383}
384
385fn read_dqt(mut seg: &[u8], quant: &mut [[u16; 64]; 4]) -> Result<()> {
386 while !seg.is_empty() {
387 let pq = seg[0] >> 4;
388 let tq = usize::from(seg[0] & 0x0f);
389 if tq >= 4 {
390 return Err(Error::corrupt(format!("JPEG: quant table id {tq}")));
391 }
392 let need = if pq == 1 { 128 } else { 64 };
393 let body = seg
394 .get(1..1 + need)
395 .ok_or_else(|| Error::corrupt("JPEG: truncated DQT"))?;
396 for k in 0..64 {
397 quant[tq][ZIGZAG[k]] = if pq == 1 {
398 u16::from_be_bytes([body[k * 2], body[k * 2 + 1]])
399 } else {
400 u16::from(body[k])
401 };
402 }
403 seg = &seg[1 + need..];
404 }
405 Ok(())
406}
407
408fn read_dht(mut seg: &[u8], dc: &mut [HuffTable], ac: &mut [HuffTable]) -> Result<()> {
409 while !seg.is_empty() {
410 let class = seg[0] >> 4;
411 let id = usize::from(seg[0] & 0x0f);
412 if id >= 4 || class > 1 {
413 return Err(Error::corrupt(format!("JPEG: DHT class {class} id {id}")));
414 }
415 let counts: [u8; 16] = seg
416 .get(1..17)
417 .ok_or_else(|| Error::corrupt("JPEG: truncated DHT"))?
418 .try_into()
419 .expect("16 bytes");
420 let total: usize = counts.iter().map(|&c| usize::from(c)).sum();
421 let values = seg
422 .get(17..17 + total)
423 .ok_or_else(|| Error::corrupt("JPEG: truncated DHT values"))?
424 .to_vec();
425 let table = HuffTable::build(&counts, values)?;
426 if class == 0 {
427 dc[id] = table
428 } else {
429 ac[id] = table
430 }
431 seg = &seg[17 + total..];
432 }
433 Ok(())
434}
435
436fn read_sof(seg: &[u8], progressive: bool, limits: Limits) -> Result<Frame> {
437 if seg.len() < 6 {
438 return Err(Error::corrupt("JPEG: short SOF"));
439 }
440 if seg[0] != 8 {
441 return Err(Error::unsupported(
442 format!("{}-bit JPEG", seg[0]),
443 "only 8-bit sample precision is implemented",
444 ));
445 }
446 let height = u32::from(u16::from_be_bytes([seg[1], seg[2]]));
447 let width = u32::from(u16::from_be_bytes([seg[3], seg[4]]));
448 limits.check(width, height)?;
449 let count = usize::from(seg[5]);
450 if count == 0 || count > 4 {
451 return Err(Error::corrupt(format!("JPEG: {count} components")));
452 }
453 if count == 4 {
454 return Err(Error::unsupported(
455 "4-component (CMYK/YCCK) JPEG",
456 "the ink colours need the ICC profile this decoder does not carry",
457 ));
458 }
459 if count == 2 {
460 return Err(Error::unsupported(
461 "2-component JPEG",
462 "no colour interpretation is defined for it",
463 ));
464 }
465 let body = seg
466 .get(6..6 + count * 3)
467 .ok_or_else(|| Error::corrupt("JPEG: truncated SOF components"))?;
468 let mut components = Vec::with_capacity(count);
469 for c in body.chunks_exact(3) {
470 let (h, v) = (usize::from(c[1] >> 4), usize::from(c[1] & 0x0f));
471 if h == 0 || v == 0 || h > 4 || v > 4 {
472 return Err(Error::corrupt(format!("JPEG: sampling factors {h}x{v}")));
473 }
474 components.push(Component {
475 id: c[0],
476 h,
477 v,
478 quant: usize::from(c[2] & 0x03),
479 blocks_w: 0,
480 blocks_h: 0,
481 used_w: 0,
482 used_h: 0,
483 coeffs: Vec::new(),
484 dc_pred: 0,
485 });
486 }
487 let hmax = components.iter().map(|c| c.h).max().unwrap_or(1);
488 let vmax = components.iter().map(|c| c.v).max().unwrap_or(1);
489 let mcus_w = (width as usize).div_ceil(8 * hmax);
490 let mcus_h = (height as usize).div_ceil(8 * vmax);
491 for c in &mut components {
492 c.blocks_w = mcus_w * c.h;
493 c.blocks_h = mcus_h * c.v;
494 c.used_w = ((width as usize) * c.h).div_ceil(8 * hmax);
495 c.used_h = ((height as usize) * c.v).div_ceil(8 * vmax);
496 let cells = c
497 .blocks_w
498 .checked_mul(c.blocks_h)
499 .and_then(|b| b.checked_mul(64))
500 .ok_or_else(|| Error::corrupt("JPEG: component geometry overflows"))?;
501 if cells * 2 > limits.max_alloc {
502 return Err(Error::unsupported(
503 "JPEG",
504 "coefficient storage is past the allocation limit",
505 ));
506 }
507 c.coeffs = vec![0i16; cells];
508 }
509 Ok(Frame {
510 progressive,
511 width,
512 height,
513 hmax,
514 vmax,
515 mcus_w,
516 mcus_h,
517 components,
518 })
519}
520
521/// Decode one scan; returns the offset just past its entropy-coded data.
522fn read_scan(
523 data: &[u8],
524 start: usize,
525 header: &[u8],
526 frame: &mut Frame,
527 dc_tables: &[HuffTable],
528 ac_tables: &[HuffTable],
529 restart_interval: usize,
530) -> Result<usize> {
531 if header.is_empty() {
532 return Err(Error::corrupt("JPEG: empty SOS"));
533 }
534 let ns = usize::from(header[0]);
535 let spec = header
536 .get(1..1 + ns * 2)
537 .ok_or_else(|| Error::corrupt("JPEG: truncated SOS"))?;
538 let tail = header
539 .get(1 + ns * 2..4 + ns * 2)
540 .ok_or_else(|| Error::corrupt("JPEG: truncated SOS tail"))?;
541 let (ss, se) = (usize::from(tail[0]), usize::from(tail[1]));
542 let (ah, al) = (tail[2] >> 4, tail[2] & 0x0f);
543 if se > 63 || ss > se {
544 return Err(Error::corrupt(format!("JPEG: spectral range {ss}..{se}")));
545 }
546
547 // Which frame components this scan carries, and with which tables.
548 let mut in_scan = Vec::with_capacity(ns);
549 for c in spec.chunks_exact(2) {
550 let index = frame
551 .components
552 .iter()
553 .position(|f| f.id == c[0])
554 .ok_or_else(|| Error::corrupt(format!("JPEG: scan names component {}", c[0])))?;
555 in_scan.push((index, usize::from(c[1] >> 4), usize::from(c[1] & 0x0f)));
556 }
557 for c in &mut frame.components {
558 c.dc_pred = 0;
559 }
560
561 let mut bits = BitReader::new(data, start);
562 let mut eob_run = 0u32;
563 let interleaved = ns > 1;
564 let (units_w, units_h) = if interleaved {
565 (frame.mcus_w, frame.mcus_h)
566 } else {
567 let c = &frame.components[in_scan[0].0];
568 (c.used_w, c.used_h)
569 };
570 let mut since_restart = 0usize;
571
572 for unit in 0..units_w * units_h {
573 if restart_interval > 0 && since_restart == restart_interval {
574 since_restart = 0;
575 eob_run = 0;
576 for c in &mut frame.components {
577 c.dc_pred = 0;
578 }
579 if !bits.restart() {
580 break;
581 }
582 }
583 since_restart += 1;
584 let (ux, uy) = (unit % units_w, unit / units_w);
585 for &(index, dc_id, ac_id) in &in_scan {
586 let (h, v) = {
587 let c = &frame.components[index];
588 if interleaved { (c.h, c.v) } else { (1, 1) }
589 };
590 for by in 0..v {
591 for bx in 0..h {
592 let (block_x, block_y) = if interleaved {
593 (ux * h + bx, uy * v + by)
594 } else {
595 (ux, uy)
596 };
597 let component = &mut frame.components[index];
598 if block_x >= component.blocks_w || block_y >= component.blocks_h {
599 continue;
600 }
601 let offset = (block_y * component.blocks_w + block_x) * 64;
602 // A progressive DC scan names an AC table it never uses
603 // (and vice versa), so the table is only required where it
604 // is actually read from.
605 let dc = dc_tables.get(dc_id).filter(|t| !t.values.is_empty());
606 let ac = ac_tables.get(ac_id).filter(|t| !t.values.is_empty());
607 if frame.progressive {
608 decode_progressive_block(
609 &mut bits,
610 component,
611 offset,
612 dc,
613 ac,
614 ss,
615 se,
616 ah,
617 al,
618 &mut eob_run,
619 )?;
620 } else {
621 decode_baseline_block(&mut bits, component, offset, dc, ac)?;
622 }
623 }
624 }
625 }
626 }
627
628 // Walk to the next marker that is not a restart: that is where the next
629 // segment begins.
630 let mut at = bits.at.max(start);
631 while at + 1 < data.len() {
632 if data[at] == 0xff {
633 let m = data[at + 1];
634 if m != 0x00 && !(0xd0..=0xd7).contains(&m) && m != 0xff {
635 return Ok(at);
636 }
637 }
638 at += 1;
639 }
640 Ok(data.len())
641}
642
643/// A scan may name a Huffman table that no DHT ever defined; that is a corrupt
644/// file, not a table to index into.
645fn table_or_corrupt<'a>(table: Option<&'a HuffTable>, which: &str) -> Result<&'a HuffTable> {
646 match table {
647 Some(table) if !table.values.is_empty() => Ok(table),
648 _ => Err(Error::corrupt(format!(
649 "JPEG: scan names a {which} Huffman table the file never sent"
650 ))),
651 }
652}
653
654fn decode_baseline_block(
655 bits: &mut BitReader<'_>,
656 component: &mut Component,
657 offset: usize,
658 dc: Option<&HuffTable>,
659 ac: Option<&HuffTable>,
660) -> Result<()> {
661 let (dc, ac) = (table_or_corrupt(dc, "DC")?, table_or_corrupt(ac, "AC")?);
662 let t = bits.decode(dc)?;
663 if t > 15 {
664 return Err(Error::corrupt(format!("JPEG: DC magnitude {t}")));
665 }
666 let diff = bits.receive_extend(t);
667 component.dc_pred = component.dc_pred.wrapping_add(diff);
668 component.coeffs[offset] = component.dc_pred.clamp(-32768, 32767) as i16;
669
670 let mut k = 1usize;
671 while k < 64 {
672 let rs = bits.decode(ac)?;
673 let (r, s) = ((rs >> 4) as usize, rs & 0x0f);
674 if s == 0 {
675 if r != 15 {
676 break;
677 }
678 k += 16;
679 continue;
680 }
681 k += r;
682 if k > 63 {
683 break;
684 }
685 let value = bits.receive_extend(s);
686 component.coeffs[offset + ZIGZAG[k]] = value.clamp(-32768, 32767) as i16;
687 k += 1;
688 }
689 Ok(())
690}
691
692#[allow(clippy::too_many_arguments)]
693fn decode_progressive_block(
694 bits: &mut BitReader<'_>,
695 component: &mut Component,
696 offset: usize,
697 dc: Option<&HuffTable>,
698 ac: Option<&HuffTable>,
699 ss: usize,
700 se: usize,
701 ah: u8,
702 al: u8,
703 eob_run: &mut u32,
704) -> Result<()> {
705 if ss == 0 {
706 // DC scan: first pass codes the difference, later passes one bit each.
707 if ah == 0 {
708 let t = bits.decode(table_or_corrupt(dc, "DC")?)?;
709 if t > 15 {
710 return Err(Error::corrupt(format!("JPEG: DC magnitude {t}")));
711 }
712 let diff = bits.receive_extend(t);
713 component.dc_pred = component.dc_pred.wrapping_add(diff);
714 component.coeffs[offset] = (component.dc_pred << al).clamp(-32768, 32767) as i16;
715 } else if bits.bit() == 1 {
716 component.coeffs[offset] |= 1 << al;
717 }
718 return Ok(());
719 }
720
721 let ac = table_or_corrupt(ac, "AC")?;
722 if ah == 0 {
723 // AC first pass: values, with runs of end-of-block.
724 if *eob_run > 0 {
725 *eob_run -= 1;
726 return Ok(());
727 }
728 let mut k = ss;
729 while k <= se {
730 let rs = bits.decode(ac)?;
731 let (r, s) = (u32::from(rs >> 4), rs & 0x0f);
732 if s == 0 {
733 if r < 15 {
734 *eob_run = (1 << r) - 1;
735 if r > 0 {
736 *eob_run += bits.bits(r);
737 }
738 break;
739 }
740 k += 16;
741 continue;
742 }
743 k += r as usize;
744 if k > se {
745 break;
746 }
747 let value = bits.receive_extend(s);
748 component.coeffs[offset + ZIGZAG[k]] = ((value) << al).clamp(-32768, 32767) as i16;
749 k += 1;
750 }
751 return Ok(());
752 }
753
754 // AC refinement: correction bits for coefficients already non-zero, plus
755 // newly significant ones placed by the run length.
756 let positive = 1i16 << al;
757 let negative = -1i16 << al;
758 let mut k = ss;
759 if *eob_run > 0 {
760 *eob_run -= 1;
761 refine_nonzero(bits, component, offset, k, se, positive, negative);
762 return Ok(());
763 }
764 while k <= se {
765 let rs = bits.decode(ac)?;
766 let (mut r, s) = (i32::from(rs >> 4), rs & 0x0f);
767 let mut value = 0i16;
768 if s == 0 {
769 if r < 15 {
770 *eob_run = (1 << r) - 1;
771 if r > 0 {
772 *eob_run += bits.bits(r as u32);
773 }
774 refine_nonzero(bits, component, offset, k, se, positive, negative);
775 break;
776 }
777 } else {
778 value = if bits.bit() == 1 { positive } else { negative };
779 }
780 while k <= se {
781 let cell = offset + ZIGZAG[k];
782 if component.coeffs[cell] != 0 {
783 if bits.bit() == 1 && component.coeffs[cell] & positive == 0 {
784 component.coeffs[cell] = if component.coeffs[cell] >= 0 {
785 component.coeffs[cell].saturating_add(positive)
786 } else {
787 component.coeffs[cell].saturating_add(negative)
788 };
789 }
790 } else {
791 if r == 0 {
792 if value != 0 {
793 component.coeffs[cell] = value;
794 }
795 k += 1;
796 break;
797 }
798 r -= 1;
799 }
800 k += 1;
801 }
802 }
803 Ok(())
804}
805
806/// Apply one correction bit to each already-non-zero coefficient in `k..=se`.
807fn refine_nonzero(
808 bits: &mut BitReader<'_>,
809 component: &mut Component,
810 offset: usize,
811 k: usize,
812 se: usize,
813 positive: i16,
814 negative: i16,
815) {
816 for k in k..=se {
817 let cell = offset + ZIGZAG[k];
818 if component.coeffs[cell] != 0 && bits.bit() == 1 && component.coeffs[cell] & positive == 0
819 {
820 component.coeffs[cell] = if component.coeffs[cell] >= 0 {
821 component.coeffs[cell].saturating_add(positive)
822 } else {
823 component.coeffs[cell].saturating_add(negative)
824 };
825 }
826 }
827}
828
829/// Fixed-point 1-D IDCT basis: `round(c_v * cos((2x+1) v pi / 16) * 2^13)`.
830///
831/// Thirteen fractional bits, and eight of them kept between the two passes,
832/// so the separable inversion lands within a count of the exact transform —
833/// the difference against another decoder is then its rounding, not ours.
834const IDCT_BASIS: [[i32; 8]; 8] = build_basis();
835
836const fn build_basis() -> [[i32; 8]; 8] {
837 // Values computed once, off the same formula the tests re-derive in f64.
838 [
839 [2896, 2896, 2896, 2896, 2896, 2896, 2896, 2896],
840 [4017, 3406, 2276, 799, -799, -2276, -3406, -4017],
841 [3784, 1567, -1567, -3784, -3784, -1567, 1567, 3784],
842 [3406, -799, -4017, -2276, 2276, 4017, 799, -3406],
843 [2896, -2896, -2896, 2896, 2896, -2896, -2896, 2896],
844 [2276, -4017, 799, 3406, -3406, -799, 4017, -2276],
845 [1567, -3784, 3784, -1567, -1567, 3784, -3784, 1567],
846 [799, -2276, 3406, -4017, 4017, -3406, 2276, -799],
847 ]
848}
849
850/// Dequantize and invert one 8x8 block into 0..=255 samples.
851fn idct_block(coeffs: &[i16], quant: &[u16; 64], out: &mut [u8; 64]) {
852 let mut tmp = [0i64; 64];
853 for x in 0..8 {
854 // Columns first; the all-zero column shortcut is what makes a flat
855 // photo background cheap.
856 let nonzero = (1..8).any(|v| coeffs[v * 8 + x] != 0);
857 let dc = i64::from(coeffs[x]) * i64::from(quant[x]);
858 if !nonzero {
859 let value = (dc * i64::from(IDCT_BASIS[0][0]) + 16) >> 5;
860 for y in 0..8 {
861 tmp[y * 8 + x] = value;
862 }
863 continue;
864 }
865 for y in 0..8 {
866 let mut sum = 0i64;
867 for v in 0..8 {
868 let c = i64::from(coeffs[v * 8 + x]) * i64::from(quant[v * 8 + x]);
869 sum += c * i64::from(IDCT_BASIS[v][y]);
870 }
871 tmp[y * 8 + x] = (sum + 16) >> 5;
872 }
873 }
874 for y in 0..8 {
875 for x in 0..8 {
876 let mut sum = 0i64;
877 for u in 0..8 {
878 sum += tmp[y * 8 + u] * i64::from(IDCT_BASIS[u][x]);
879 }
880 let value = ((sum + (1 << 20)) >> 21) + 128;
881 out[y * 8 + x] = value.clamp(0, 255) as u8;
882 }
883 }
884}
885
886/// Inverse-transform every block of a component into a plane of samples.
887fn component_plane(component: &Component, quant: &[u16; 64]) -> Vec<u8> {
888 let width = component.blocks_w * 8;
889 let mut plane = vec![0u8; width * component.blocks_h * 8];
890 let mut block = [0u8; 64];
891 for by in 0..component.blocks_h {
892 for bx in 0..component.blocks_w {
893 let offset = (by * component.blocks_w + bx) * 64;
894 idct_block(&component.coeffs[offset..offset + 64], quant, &mut block);
895 for row in 0..8 {
896 let dst = (by * 8 + row) * width + bx * 8;
897 plane[dst..dst + 8].copy_from_slice(&block[row * 8..row * 8 + 8]);
898 }
899 }
900 }
901 plane
902}
903
904/// BT.601 full-range YCbCr to RGB, in libjpeg's 16-bit fixed point.
905fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8) -> [u8; 3] {
906 let y = i32::from(y) << 16;
907 let cb = i32::from(cb) - 128;
908 let cr = i32::from(cr) - 128;
909 let r = y + 91881 * cr;
910 let g = y - 22554 * cb - 46802 * cr;
911 let b = y + 116130 * cb;
912 [
913 ((r + 32768) >> 16).clamp(0, 255) as u8,
914 ((g + 32768) >> 16).clamp(0, 255) as u8,
915 ((b + 32768) >> 16).clamp(0, 255) as u8,
916 ]
917}
918
919fn reconstruct(frame: &Frame, quant: &[[u16; 64]; 4], adobe: Option<u8>) -> Result<Pixels> {
920 let (w, h) = (frame.width as usize, frame.height as usize);
921 let planes: Vec<Vec<u8>> = frame
922 .components
923 .iter()
924 .map(|c| {
925 let plane = component_plane(c, &quant[c.quant]);
926 let pw = c.blocks_w * 8;
927 let ph = c.blocks_h * 8;
928 // Full-resolution extent this component covers before upsampling.
929 let cw = (w * c.h).div_ceil(frame.hmax);
930 let ch = (h * c.v).div_ceil(frame.vmax);
931 let cropped: Vec<u8> = (0..ch.min(ph))
932 .flat_map(|y| plane[y * pw..y * pw + cw.min(pw)].to_vec())
933 .collect();
934 upsample(&cropped, cw.min(pw), ch.min(ph), w, h)
935 })
936 .collect();
937
938 match frame.components.len() {
939 1 => Ok(Pixels::L8(planes.into_iter().next().expect("one plane"))),
940 3 => {
941 // Component ids 'R','G','B' (or an Adobe transform of 0) mean the
942 // samples are already RGB and must not be matrixed again.
943 let ids: Vec<u8> = frame.components.iter().map(|c| c.id).collect();
944 let already_rgb = adobe == Some(0) || ids == *b"RGB";
945 let mut out = Vec::with_capacity(w * h * 3);
946 for i in 0..w * h {
947 if already_rgb {
948 out.extend_from_slice(&[planes[0][i], planes[1][i], planes[2][i]]);
949 } else {
950 out.extend_from_slice(&ycbcr_to_rgb(planes[0][i], planes[1][i], planes[2][i]));
951 }
952 }
953 Ok(Pixels::Rgb8(out))
954 }
955 n => Err(Error::unsupported(
956 format!("{n}-component JPEG"),
957 "no colour interpretation is defined for it",
958 )),
959 }
960}
961
962/// EXIF orientation (IFD0 tag 0x0112) out of an APP1 segment.
963fn exif_orientation(seg: &[u8]) -> Option<u8> {
964 let tiff = seg.strip_prefix(b"Exif\0\0")?;
965 let little = match tiff.get(..2)? {
966 b"II" => true,
967 b"MM" => false,
968 _ => return None,
969 };
970 let u16_at = |at: usize| -> Option<u16> {
971 let b = tiff.get(at..at + 2)?;
972 Some(if little {
973 u16::from_le_bytes([b[0], b[1]])
974 } else {
975 u16::from_be_bytes([b[0], b[1]])
976 })
977 };
978 let u32_at = |at: usize| -> Option<u32> {
979 let b = tiff.get(at..at + 4)?;
980 Some(if little {
981 u32::from_le_bytes([b[0], b[1], b[2], b[3]])
982 } else {
983 u32::from_be_bytes([b[0], b[1], b[2], b[3]])
984 })
985 };
986 if u16_at(2)? != 42 {
987 return None;
988 }
989 let ifd = u32_at(4)? as usize;
990 let count = usize::from(u16_at(ifd)?);
991 for i in 0..count {
992 let entry = ifd + 2 + i * 12;
993 if u16_at(entry)? == 0x0112 {
994 let value = u16_at(entry + 8)?;
995 return (1..=8).contains(&value).then_some(value as u8);
996 }
997 }
998 None
999}
1000
1001#[cfg(test)]
1002mod tests {
1003 use super::*;
1004
1005 #[test]
1006 fn the_idct_basis_matches_the_cosine_it_stands_for() {
1007 for v in 0..8usize {
1008 for x in 0..8usize {
1009 let c = if v == 0 {
1010 1.0 / std::f64::consts::SQRT_2
1011 } else {
1012 1.0
1013 };
1014 let want = 0.5
1015 * c
1016 * ((2 * x + 1) as f64 * v as f64 * std::f64::consts::PI / 16.0).cos()
1017 * 8192.0;
1018 let got = f64::from(IDCT_BASIS[v][x]);
1019 assert!((want - got).abs() <= 0.5, "v{v} x{x}: {want} vs {got}");
1020 }
1021 }
1022 }
1023
1024 #[test]
1025 fn a_flat_block_inverts_to_its_dc_level() {
1026 let mut coeffs = [0i16; 64];
1027 coeffs[0] = 8; // DC of 8 * quant 16 = 128 -> mid grey plus level shift
1028 let quant = [16u16; 64];
1029 let mut out = [0u8; 64];
1030 idct_block(&coeffs, &quant, &mut out);
1031 for &s in &out {
1032 assert_eq!(s, 144, "flat block should be one level everywhere");
1033 }
1034 }
1035
1036 #[test]
1037 fn ycbcr_neutral_chroma_is_grey() {
1038 for y in [0u8, 17, 128, 255] {
1039 assert_eq!(ycbcr_to_rgb(y, 128, 128), [y, y, y]);
1040 }
1041 // Full-range BT.601 red is Y=76 Cb=84 Cr=255 (JFIF has no head/foot
1042 // room), which must come back as saturated red and nothing else.
1043 let rgb = ycbcr_to_rgb(76, 84, 255);
1044 assert!(rgb[0] > 250 && rgb[1] < 6 && rgb[2] < 6, "{rgb:?}");
1045 }
1046
1047 #[test]
1048 fn exif_orientation_is_read_from_either_byte_order() {
1049 // Little-endian TIFF, one IFD entry: tag 0x0112, SHORT, count 1, value 6.
1050 let mut seg = b"Exif\0\0II".to_vec();
1051 seg.extend_from_slice(&42u16.to_le_bytes());
1052 seg.extend_from_slice(&8u32.to_le_bytes());
1053 seg.extend_from_slice(&1u16.to_le_bytes());
1054 seg.extend_from_slice(&0x0112u16.to_le_bytes());
1055 seg.extend_from_slice(&3u16.to_le_bytes());
1056 seg.extend_from_slice(&1u32.to_le_bytes());
1057 seg.extend_from_slice(&6u16.to_le_bytes());
1058 seg.extend_from_slice(&0u16.to_le_bytes());
1059 assert_eq!(exif_orientation(&seg), Some(6));
1060 assert_eq!(exif_orientation(b"Exif\0\0XX"), None);
1061 }
1062}