forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

jpeg.rs1477 lines, 51.6 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::{AllocBudget, 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 /// Padding bytes (zeros invented past the data or a marker) loaded since the last restart.
97 padding: u32,
98}
99
100/// Padding bytes loaded into one restart interval before the scan counts as out of data. A
101/// well-formed interval loads at most four (the fill runs up to four bytes ahead), so eight
102/// is never reached by a valid file.
103const EXHAUSTED_PADDING: u32 = 8;
104
105impl<'a> BitReader<'a> {
106 fn new(data: &'a [u8], at: usize) -> BitReader<'a> {
107 BitReader {
108 data,
109 at,
110 bits: 0,
111 count: 0,
112 hit_marker: false,
113 padding: 0,
114 }
115 }
116
117 /// Whether the scan has run out of data: it has consumed far enough into the invented bits
118 /// that the rest of the picture cannot be real. The decoder then stops, as libjpeg does, and
119 /// the blocks it did not reach keep their zero coefficients.
120 fn exhausted(&self) -> bool {
121 self.padding >= EXHAUSTED_PADDING
122 }
123
124 fn fill(&mut self) {
125 while self.count <= 24 {
126 let byte = match self.data.get(self.at) {
127 Some(&0xff) => match self.data.get(self.at + 1) {
128 Some(&0x00) => {
129 self.at += 2;
130 0xff
131 }
132 _ => {
133 self.hit_marker = true;
134 self.padding += 1;
135 0
136 }
137 },
138 Some(&b) => {
139 self.at += 1;
140 b
141 }
142 None => {
143 self.hit_marker = true;
144 self.padding += 1;
145 0
146 }
147 };
148 self.bits |= u32::from(byte) << (24 - self.count);
149 self.count += 8;
150 }
151 }
152
153 fn peek8(&mut self) -> u8 {
154 self.fill();
155 (self.bits >> 24) as u8
156 }
157
158 fn consume(&mut self, n: u32) {
159 self.bits <<= n;
160 self.count = self.count.saturating_sub(n);
161 }
162
163 fn bit(&mut self) -> u32 {
164 self.fill();
165 let b = self.bits >> 31;
166 self.consume(1);
167 b
168 }
169
170 fn bits(&mut self, n: u32) -> u32 {
171 if n == 0 {
172 return 0;
173 }
174 self.fill();
175 let v = self.bits >> (32 - n);
176 self.consume(n);
177 v
178 }
179
180 fn decode(&mut self, table: &HuffTable) -> Result<u8> {
181 let prefix = self.peek8();
182 let (len, value) = table.lut[prefix as usize];
183 if len != 0 {
184 self.consume(u32::from(len));
185 return Ok(value);
186 }
187 // Codes longer than the lookahead: walk lengths the canonical way.
188 let mut code = i32::from(prefix);
189 self.consume(8);
190 for len in 9..=16usize {
191 code = (code << 1) | self.bit() as i32;
192 if table.max_code[len] >= code && code >= table.min_code[len] {
193 let index = table.val_ptr[len] + (code - table.min_code[len]) as usize;
194 return table
195 .values
196 .get(index)
197 .copied()
198 .ok_or_else(|| Error::corrupt("JPEG: Huffman code outside its table"));
199 }
200 }
201 Err(Error::corrupt("JPEG: no Huffman code matches the bits"))
202 }
203
204 /// T.81 F.2.2.1 EXTEND: sign-extend an `s`-bit magnitude.
205 fn receive_extend(&mut self, s: u8) -> i32 {
206 if s == 0 {
207 return 0;
208 }
209 let v = self.bits(u32::from(s)) as i32;
210 if v < (1 << (s - 1)) {
211 v - (1 << s) + 1
212 } else {
213 v
214 }
215 }
216
217 /// Restart: byte-align and step over the RSTn marker.
218 fn restart(&mut self) -> bool {
219 self.bits = 0;
220 self.count = 0;
221 self.padding = 0;
222 // Skip to the marker, which a well-formed stream is already at.
223 while self.at + 1 < self.data.len() {
224 if self.data[self.at] == 0xff && (0xd0..=0xd7).contains(&self.data[self.at + 1]) {
225 self.at += 2;
226 return true;
227 }
228 self.at += 1;
229 }
230 self.hit_marker = true;
231 false
232 }
233}
234
235/// One colour component of the frame.
236#[derive(Clone)]
237struct Component {
238 id: u8,
239 h: usize,
240 v: usize,
241 quant: usize,
242 /// Blocks across and down, padded out to whole MCUs.
243 blocks_w: usize,
244 blocks_h: usize,
245 /// Blocks the picture actually covers (`blocks_w` may be larger).
246 used_w: usize,
247 used_h: usize,
248 coeffs: Vec<i16>,
249 dc_pred: i32,
250}
251
252/// Everything the markers before the first scan established.
253struct Frame {
254 progressive: bool,
255 width: u32,
256 height: u32,
257 hmax: usize,
258 vmax: usize,
259 mcus_w: usize,
260 mcus_h: usize,
261 components: Vec<Component>,
262}
263
264fn be16(data: &[u8], at: usize) -> Result<usize> {
265 data.get(at..at + 2)
266 .map(|b| usize::from(u16::from_be_bytes([b[0], b[1]])))
267 .ok_or_else(|| Error::corrupt("JPEG: truncated segment"))
268}
269
270/// Dimensions and EXIF orientation from the headers alone.
271///
272/// Walks the marker segments up to the start of scan, so it reads no entropy-coded
273/// data. The frame header gives the size; the first APP1 `Exif` segment gives the
274/// orientation (1 when there is none).
275pub fn info(data: &[u8]) -> Result<Info> {
276 let mut at = 2;
277 let mut frame = None;
278 let mut orientation = 1;
279 while let Some(marker) = next_marker(data, &mut at) {
280 match marker {
281 0xc0..=0xc2 => {
282 let len = be16(data, at)?;
283 let seg = data
284 .get(at + 2..at + len)
285 .ok_or_else(|| Error::corrupt("JPEG: truncated SOF"))?;
286 if seg.len() < 6 {
287 return Err(Error::corrupt("JPEG: short SOF"));
288 }
289 frame.get_or_insert((
290 u32::from(u16::from_be_bytes([seg[3], seg[4]])),
291 u32::from(u16::from_be_bytes([seg[1], seg[2]])),
292 ));
293 }
294 0xd8 | 0xd9 => {}
295 0xda => break,
296 _ => {
297 let len = be16(data, at)?;
298 if marker == 0xe1 && orientation == 1 {
299 orientation = data
300 .get(at + 2..at + len)
301 .and_then(exif_orientation)
302 .unwrap_or(1);
303 }
304 at += len.max(2);
305 }
306 }
307 if frame.is_some() && orientation != 1 {
308 break;
309 }
310 }
311 let (width, height) = frame.ok_or_else(|| Error::corrupt("JPEG: no frame header"))?;
312 Ok(Info {
313 format: ImageFormat::Jpeg,
314 width,
315 height,
316 orientation,
317 })
318}
319
320/// Step to the next marker, returning its byte and leaving `at` on its payload.
321fn next_marker(data: &[u8], at: &mut usize) -> Option<u8> {
322 while *at < data.len() {
323 if data[*at] != 0xff {
324 *at += 1;
325 continue;
326 }
327 let mut scan = *at + 1;
328 while data.get(scan) == Some(&0xff) {
329 scan += 1;
330 }
331 let marker = *data.get(scan)?;
332 *at = scan + 1;
333 if marker != 0x00 {
334 return Some(marker);
335 }
336 }
337 None
338}
339
340/// Everything the marker segments of one JPEG established, with every scan decoded into
341/// coefficients but nothing inverse-transformed yet.
342struct Parsed {
343 frame: Frame,
344 quant: [[u16; 64]; 4],
345 meta: Metadata,
346 adobe: Option<u8>,
347 /// Offset just past the EOI marker (or the end of the data when there was none).
348 end: usize,
349}
350
351/// Decode a JPEG.
352pub fn decode(data: &[u8], limits: Limits) -> Result<Image> {
353 let parsed = parse(data, limits, false)?;
354 let pixels = reconstruct(&parsed.frame, &parsed.quant, parsed.adobe, limits)?;
355 Ok(Image {
356 width: parsed.frame.width,
357 height: parsed.frame.height,
358 pixels,
359 meta: parsed.meta,
360 })
361}
362
363/// Walk the marker segments and entropy-decode every scan. `mjpeg` preloads the Annex K
364/// default Huffman tables as tables 0 and 1, for the AVI1/MJPG packets that carry no DHT.
365fn parse(data: &[u8], limits: Limits, mjpeg: bool) -> Result<Parsed> {
366 let mut quant = [[0u16; 64]; 4];
367 let mut dc_tables: Vec<HuffTable> = vec![HuffTable::default(); 4];
368 let mut ac_tables: Vec<HuffTable> = vec![HuffTable::default(); 4];
369 if mjpeg {
370 install_default_tables(&mut dc_tables, &mut ac_tables)?;
371 }
372 let mut restart_interval = 0usize;
373 let mut frame: Option<Frame> = None;
374 let mut scanned = false;
375 let mut meta = Metadata::default();
376 let mut adobe_transform: Option<u8> = None;
377 let mut end = data.len();
378
379 let mut at = 2;
380 while let Some(marker) = next_marker(data, &mut at) {
381 match marker {
382 0xd8 => continue,
383 0xd9 => {
384 end = at;
385 break;
386 }
387 0x01 | 0xd0..=0xd7 => continue,
388 _ => {}
389 }
390 let len = be16(data, at)?;
391 if len < 2 {
392 return Err(Error::corrupt("JPEG: segment length below 2"));
393 }
394 let seg = data
395 .get(at + 2..at + len)
396 .ok_or_else(|| Error::corrupt("JPEG: truncated segment"))?;
397 match marker {
398 0xdb => read_dqt(seg, &mut quant)?,
399 0xc4 => read_dht(seg, &mut dc_tables, &mut ac_tables)?,
400 0xdd => {
401 if seg.len() < 2 {
402 return Err(Error::corrupt("JPEG: short DRI"));
403 }
404 restart_interval = usize::from(u16::from_be_bytes([seg[0], seg[1]]));
405 }
406 0xc0..=0xc2 => {
407 let f = read_sof(seg, marker == 0xc2, limits)?;
408 if mjpeg {
409 // Refuse an unmappable layout before any scan is decoded.
410 subsampling_of(&f)?;
411 }
412 frame = Some(f);
413 }
414 0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf => {
415 return Err(Error::unsupported(
416 format!("JPEG SOF{}", marker & 0x0f),
417 "arithmetic-coded, lossless and hierarchical JPEG are a different process",
418 ));
419 }
420 0xe1 => {
421 // The first EXIF segment is the one that counts.
422 if meta.orientation.is_none() {
423 meta.orientation = exif_orientation(seg);
424 }
425 }
426 0xee => {
427 if seg.starts_with(b"Adobe") {
428 adobe_transform = seg.last().copied();
429 }
430 }
431 0xda => {
432 let frame = frame
433 .as_mut()
434 .ok_or_else(|| Error::corrupt("JPEG: scan before frame header"))?;
435 scanned = true;
436 at = read_scan(
437 data,
438 at + len,
439 seg,
440 frame,
441 &dc_tables,
442 &ac_tables,
443 restart_interval,
444 )?;
445 continue;
446 }
447 _ => {}
448 }
449 at += len;
450 }
451
452 let frame = frame.ok_or_else(|| Error::corrupt("JPEG: no frame header"))?;
453 // A frame with no scan carries no picture data. Refused rather than returned as a grey
454 // canvas, so a header that declares a large picture costs nothing to refuse.
455 if !scanned {
456 return Err(Error::corrupt("JPEG: a frame header with no scan"));
457 }
458 Ok(Parsed {
459 frame,
460 quant,
461 meta,
462 adobe: adobe_transform,
463 end,
464 })
465}
466
467fn read_dqt(mut seg: &[u8], quant: &mut [[u16; 64]; 4]) -> Result<()> {
468 while !seg.is_empty() {
469 let pq = seg[0] >> 4;
470 let tq = usize::from(seg[0] & 0x0f);
471 if tq >= 4 {
472 return Err(Error::corrupt(format!("JPEG: quant table id {tq}")));
473 }
474 let need = if pq == 1 { 128 } else { 64 };
475 let body = seg
476 .get(1..1 + need)
477 .ok_or_else(|| Error::corrupt("JPEG: truncated DQT"))?;
478 for k in 0..64 {
479 quant[tq][ZIGZAG[k]] = if pq == 1 {
480 u16::from_be_bytes([body[k * 2], body[k * 2 + 1]])
481 } else {
482 u16::from(body[k])
483 };
484 }
485 seg = &seg[1 + need..];
486 }
487 Ok(())
488}
489
490fn read_dht(mut seg: &[u8], dc: &mut [HuffTable], ac: &mut [HuffTable]) -> Result<()> {
491 while !seg.is_empty() {
492 let class = seg[0] >> 4;
493 let id = usize::from(seg[0] & 0x0f);
494 if id >= 4 || class > 1 {
495 return Err(Error::corrupt(format!("JPEG: DHT class {class} id {id}")));
496 }
497 let counts: [u8; 16] = seg
498 .get(1..17)
499 .ok_or_else(|| Error::corrupt("JPEG: truncated DHT"))?
500 .try_into()
501 .expect("16 bytes");
502 let total: usize = counts.iter().map(|&c| usize::from(c)).sum();
503 let values = seg
504 .get(17..17 + total)
505 .ok_or_else(|| Error::corrupt("JPEG: truncated DHT values"))?
506 .to_vec();
507 let table = HuffTable::build(&counts, values)?;
508 if class == 0 {
509 dc[id] = table
510 } else {
511 ac[id] = table
512 }
513 seg = &seg[17 + total..];
514 }
515 Ok(())
516}
517
518fn read_sof(seg: &[u8], progressive: bool, limits: Limits) -> Result<Frame> {
519 if seg.len() < 6 {
520 return Err(Error::corrupt("JPEG: short SOF"));
521 }
522 if seg[0] != 8 {
523 return Err(Error::unsupported(
524 format!("{}-bit JPEG", seg[0]),
525 "only 8-bit sample precision is implemented",
526 ));
527 }
528 let height = u32::from(u16::from_be_bytes([seg[1], seg[2]]));
529 let width = u32::from(u16::from_be_bytes([seg[3], seg[4]]));
530 limits.check(width, height)?;
531 let count = usize::from(seg[5]);
532 if count == 0 || count > 4 {
533 return Err(Error::corrupt(format!("JPEG: {count} components")));
534 }
535 if count == 4 {
536 return Err(Error::unsupported(
537 "4-component (CMYK/YCCK) JPEG",
538 "the ink colours need the ICC profile this decoder does not carry",
539 ));
540 }
541 if count == 2 {
542 return Err(Error::unsupported(
543 "2-component JPEG",
544 "no colour interpretation is defined for it",
545 ));
546 }
547 let body = seg
548 .get(6..6 + count * 3)
549 .ok_or_else(|| Error::corrupt("JPEG: truncated SOF components"))?;
550 let mut components = Vec::with_capacity(count);
551 for c in body.as_chunks::<3>().0.iter() {
552 let (h, v) = (usize::from(c[1] >> 4), usize::from(c[1] & 0x0f));
553 if h == 0 || v == 0 || h > 4 || v > 4 {
554 return Err(Error::corrupt(format!("JPEG: sampling factors {h}x{v}")));
555 }
556 components.push(Component {
557 id: c[0],
558 h,
559 v,
560 quant: usize::from(c[2] & 0x03),
561 blocks_w: 0,
562 blocks_h: 0,
563 used_w: 0,
564 used_h: 0,
565 coeffs: Vec::new(),
566 dc_pred: 0,
567 });
568 }
569 let hmax = components.iter().map(|c| c.h).max().unwrap_or(1);
570 let vmax = components.iter().map(|c| c.v).max().unwrap_or(1);
571 let mcus_w = (width as usize).div_ceil(8 * hmax);
572 let mcus_h = (height as usize).div_ceil(8 * vmax);
573 // Coefficient storage is budgeted across every component, not one at a time: three
574 // full-size planes each under the per-buffer cap can still add up to far past it.
575 let mut budget = AllocBudget::default();
576 for c in &mut components {
577 c.blocks_w = mcus_w * c.h;
578 c.blocks_h = mcus_h * c.v;
579 c.used_w = ((width as usize) * c.h).div_ceil(8 * hmax);
580 c.used_h = ((height as usize) * c.v).div_ceil(8 * vmax);
581 let cells = c
582 .blocks_w
583 .checked_mul(c.blocks_h)
584 .and_then(|b| b.checked_mul(64))
585 .ok_or_else(|| Error::corrupt("JPEG: component geometry overflows"))?;
586 limits.check_bytes("JPEG coefficients", cells.checked_mul(2))?;
587 budget.spend(&limits, "JPEG coefficients", cells * 2)?;
588 c.coeffs = vec![0i16; cells];
589 }
590 Ok(Frame {
591 progressive,
592 width,
593 height,
594 hmax,
595 vmax,
596 mcus_w,
597 mcus_h,
598 components,
599 })
600}
601
602/// Decode one scan; returns the offset just past its entropy-coded data.
603fn read_scan(
604 data: &[u8],
605 start: usize,
606 header: &[u8],
607 frame: &mut Frame,
608 dc_tables: &[HuffTable],
609 ac_tables: &[HuffTable],
610 restart_interval: usize,
611) -> Result<usize> {
612 if header.is_empty() {
613 return Err(Error::corrupt("JPEG: empty SOS"));
614 }
615 let ns = usize::from(header[0]);
616 let spec = header
617 .get(1..1 + ns * 2)
618 .ok_or_else(|| Error::corrupt("JPEG: truncated SOS"))?;
619 let tail = header
620 .get(1 + ns * 2..4 + ns * 2)
621 .ok_or_else(|| Error::corrupt("JPEG: truncated SOS tail"))?;
622 let (ss, se) = (usize::from(tail[0]), usize::from(tail[1]));
623 let (ah, al) = (tail[2] >> 4, tail[2] & 0x0f);
624 if se > 63 || ss > se {
625 return Err(Error::corrupt(format!("JPEG: spectral range {ss}..{se}")));
626 }
627
628 // Which frame components this scan carries, and with which tables.
629 let mut in_scan = Vec::with_capacity(ns);
630 for c in spec.as_chunks::<2>().0.iter() {
631 let index = frame
632 .components
633 .iter()
634 .position(|f| f.id == c[0])
635 .ok_or_else(|| Error::corrupt(format!("JPEG: scan names component {}", c[0])))?;
636 in_scan.push((index, usize::from(c[1] >> 4), usize::from(c[1] & 0x0f)));
637 }
638 // A scan naming no components has nothing to decode and no geometry to walk.
639 if in_scan.is_empty() {
640 return Err(Error::corrupt("JPEG: a scan with no components"));
641 }
642 for c in &mut frame.components {
643 c.dc_pred = 0;
644 }
645
646 let mut bits = BitReader::new(data, start);
647 let mut eob_run = 0u32;
648 let interleaved = ns > 1;
649 let (units_w, units_h) = if interleaved {
650 (frame.mcus_w, frame.mcus_h)
651 } else {
652 let c = &frame.components[in_scan[0].0];
653 (c.used_w, c.used_h)
654 };
655 let mut since_restart = 0usize;
656
657 for unit in 0..units_w * units_h {
658 if restart_interval > 0 && since_restart == restart_interval {
659 since_restart = 0;
660 eob_run = 0;
661 for c in &mut frame.components {
662 c.dc_pred = 0;
663 }
664 if !bits.restart() {
665 break;
666 }
667 }
668 if bits.exhausted() {
669 break;
670 }
671 since_restart += 1;
672 let (ux, uy) = (unit % units_w, unit / units_w);
673 for &(index, dc_id, ac_id) in &in_scan {
674 let (h, v) = {
675 let c = &frame.components[index];
676 if interleaved { (c.h, c.v) } else { (1, 1) }
677 };
678 for by in 0..v {
679 for bx in 0..h {
680 let (block_x, block_y) = if interleaved {
681 (ux * h + bx, uy * v + by)
682 } else {
683 (ux, uy)
684 };
685 let component = &mut frame.components[index];
686 if block_x >= component.blocks_w || block_y >= component.blocks_h {
687 continue;
688 }
689 let offset = (block_y * component.blocks_w + block_x) * 64;
690 // A progressive DC scan names an AC table it never uses
691 // (and vice versa), so the table is only required where it
692 // is actually read from.
693 let dc = dc_tables.get(dc_id).filter(|t| !t.values.is_empty());
694 let ac = ac_tables.get(ac_id).filter(|t| !t.values.is_empty());
695 if frame.progressive {
696 decode_progressive_block(
697 &mut bits,
698 component,
699 offset,
700 dc,
701 ac,
702 ss,
703 se,
704 ah,
705 al,
706 &mut eob_run,
707 )?;
708 } else {
709 decode_baseline_block(&mut bits, component, offset, dc, ac)?;
710 }
711 }
712 }
713 }
714 }
715
716 // Walk to the next marker that is not a restart: that is where the next
717 // segment begins.
718 let mut at = bits.at.max(start);
719 while at + 1 < data.len() {
720 if data[at] == 0xff {
721 let m = data[at + 1];
722 if m != 0x00 && !(0xd0..=0xd7).contains(&m) && m != 0xff {
723 return Ok(at);
724 }
725 }
726 at += 1;
727 }
728 Ok(data.len())
729}
730
731/// A scan may name a Huffman table that no DHT ever defined; that is a corrupt
732/// file, not a table to index into.
733fn table_or_corrupt<'a>(table: Option<&'a HuffTable>, which: &str) -> Result<&'a HuffTable> {
734 match table {
735 Some(table) if !table.values.is_empty() => Ok(table),
736 _ => Err(Error::corrupt(format!(
737 "JPEG: scan names a {which} Huffman table the file never sent"
738 ))),
739 }
740}
741
742fn decode_baseline_block(
743 bits: &mut BitReader<'_>,
744 component: &mut Component,
745 offset: usize,
746 dc: Option<&HuffTable>,
747 ac: Option<&HuffTable>,
748) -> Result<()> {
749 let (dc, ac) = (table_or_corrupt(dc, "DC")?, table_or_corrupt(ac, "AC")?);
750 let t = bits.decode(dc)?;
751 if t > 15 {
752 return Err(Error::corrupt(format!("JPEG: DC magnitude {t}")));
753 }
754 let diff = bits.receive_extend(t);
755 component.dc_pred = component.dc_pred.wrapping_add(diff);
756 component.coeffs[offset] = component.dc_pred.clamp(-32768, 32767) as i16;
757
758 let mut k = 1usize;
759 while k < 64 {
760 let rs = bits.decode(ac)?;
761 let (r, s) = ((rs >> 4) as usize, rs & 0x0f);
762 if s == 0 {
763 if r != 15 {
764 break;
765 }
766 k += 16;
767 continue;
768 }
769 k += r;
770 if k > 63 {
771 break;
772 }
773 let value = bits.receive_extend(s);
774 component.coeffs[offset + ZIGZAG[k]] = value.clamp(-32768, 32767) as i16;
775 k += 1;
776 }
777 Ok(())
778}
779
780#[allow(clippy::too_many_arguments)]
781fn decode_progressive_block(
782 bits: &mut BitReader<'_>,
783 component: &mut Component,
784 offset: usize,
785 dc: Option<&HuffTable>,
786 ac: Option<&HuffTable>,
787 ss: usize,
788 se: usize,
789 ah: u8,
790 al: u8,
791 eob_run: &mut u32,
792) -> Result<()> {
793 if ss == 0 {
794 // DC scan: first pass codes the difference, later passes one bit each.
795 if ah == 0 {
796 let t = bits.decode(table_or_corrupt(dc, "DC")?)?;
797 if t > 15 {
798 return Err(Error::corrupt(format!("JPEG: DC magnitude {t}")));
799 }
800 let diff = bits.receive_extend(t);
801 component.dc_pred = component.dc_pred.wrapping_add(diff);
802 component.coeffs[offset] = (component.dc_pred << al).clamp(-32768, 32767) as i16;
803 } else if bits.bit() == 1 {
804 component.coeffs[offset] |= 1 << al;
805 }
806 return Ok(());
807 }
808
809 let ac = table_or_corrupt(ac, "AC")?;
810 if ah == 0 {
811 // AC first pass: values, with runs of end-of-block.
812 if *eob_run > 0 {
813 *eob_run -= 1;
814 return Ok(());
815 }
816 let mut k = ss;
817 while k <= se {
818 let rs = bits.decode(ac)?;
819 let (r, s) = (u32::from(rs >> 4), rs & 0x0f);
820 if s == 0 {
821 if r < 15 {
822 *eob_run = (1 << r) - 1;
823 if r > 0 {
824 *eob_run += bits.bits(r);
825 }
826 break;
827 }
828 k += 16;
829 continue;
830 }
831 k += r as usize;
832 if k > se {
833 break;
834 }
835 let value = bits.receive_extend(s);
836 component.coeffs[offset + ZIGZAG[k]] = ((value) << al).clamp(-32768, 32767) as i16;
837 k += 1;
838 }
839 return Ok(());
840 }
841
842 // AC refinement: correction bits for coefficients already non-zero, plus
843 // newly significant ones placed by the run length.
844 let positive = 1i16 << al;
845 let negative = -1i16 << al;
846 let mut k = ss;
847 if *eob_run > 0 {
848 *eob_run -= 1;
849 refine_nonzero(bits, component, offset, k, se, positive, negative);
850 return Ok(());
851 }
852 while k <= se {
853 let rs = bits.decode(ac)?;
854 let (mut r, s) = (i32::from(rs >> 4), rs & 0x0f);
855 let mut value = 0i16;
856 if s == 0 {
857 if r < 15 {
858 *eob_run = (1 << r) - 1;
859 if r > 0 {
860 *eob_run += bits.bits(r as u32);
861 }
862 refine_nonzero(bits, component, offset, k, se, positive, negative);
863 break;
864 }
865 } else {
866 value = if bits.bit() == 1 { positive } else { negative };
867 }
868 while k <= se {
869 let cell = offset + ZIGZAG[k];
870 if component.coeffs[cell] != 0 {
871 if bits.bit() == 1 && component.coeffs[cell] & positive == 0 {
872 component.coeffs[cell] = if component.coeffs[cell] >= 0 {
873 component.coeffs[cell].saturating_add(positive)
874 } else {
875 component.coeffs[cell].saturating_add(negative)
876 };
877 }
878 } else {
879 if r == 0 {
880 if value != 0 {
881 component.coeffs[cell] = value;
882 }
883 k += 1;
884 break;
885 }
886 r -= 1;
887 }
888 k += 1;
889 }
890 }
891 Ok(())
892}
893
894/// Apply one correction bit to each already-non-zero coefficient in `k..=se`.
895fn refine_nonzero(
896 bits: &mut BitReader<'_>,
897 component: &mut Component,
898 offset: usize,
899 k: usize,
900 se: usize,
901 positive: i16,
902 negative: i16,
903) {
904 for k in k..=se {
905 let cell = offset + ZIGZAG[k];
906 if component.coeffs[cell] != 0 && bits.bit() == 1 && component.coeffs[cell] & positive == 0
907 {
908 component.coeffs[cell] = if component.coeffs[cell] >= 0 {
909 component.coeffs[cell].saturating_add(positive)
910 } else {
911 component.coeffs[cell].saturating_add(negative)
912 };
913 }
914 }
915}
916
917/// Fixed-point 1-D IDCT basis: `round(c_v * cos((2x+1) v pi / 16) * 2^13)`.
918///
919/// Thirteen fractional bits, and eight of them kept between the two passes,
920/// so the separable inversion lands within a count of the exact transform —
921/// the difference against another decoder is then its rounding, not ours.
922const IDCT_BASIS: [[i32; 8]; 8] = build_basis();
923
924const fn build_basis() -> [[i32; 8]; 8] {
925 // Values computed once, off the same formula the tests re-derive in f64.
926 [
927 [2896, 2896, 2896, 2896, 2896, 2896, 2896, 2896],
928 [4017, 3406, 2276, 799, -799, -2276, -3406, -4017],
929 [3784, 1567, -1567, -3784, -3784, -1567, 1567, 3784],
930 [3406, -799, -4017, -2276, 2276, 4017, 799, -3406],
931 [2896, -2896, -2896, 2896, 2896, -2896, -2896, 2896],
932 [2276, -4017, 799, 3406, -3406, -799, 4017, -2276],
933 [1567, -3784, 3784, -1567, -1567, 3784, -3784, 1567],
934 [799, -2276, 3406, -4017, 4017, -3406, 2276, -799],
935 ]
936}
937
938/// Dequantize and invert one 8x8 block into 0..=255 samples.
939fn idct_block(coeffs: &[i16], quant: &[u16; 64], out: &mut [u8; 64]) {
940 // A block whose only coefficient is the DC term (the common case, and every block of a
941 // scan that runs out of data) has one non-zero column of the first pass, so the second pass
942 // gives each output column one value. This is the general transform below, computed once
943 // per column rather than 512 times.
944 if coeffs[1..].iter().all(|&c| c == 0) {
945 let dc = i64::from(coeffs[0]) * i64::from(quant[0]);
946 let value = (dc * i64::from(IDCT_BASIS[0][0]) + 16) >> 5;
947 for x in 0..8 {
948 let column = ((value * i64::from(IDCT_BASIS[0][x]) + (1 << 20)) >> 21) + 128;
949 let column = column.clamp(0, 255) as u8;
950 for y in 0..8 {
951 out[y * 8 + x] = column;
952 }
953 }
954 return;
955 }
956 let mut tmp = [0i64; 64];
957 for x in 0..8 {
958 // Columns first; the all-zero column shortcut is what makes a flat
959 // photo background cheap.
960 let nonzero = (1..8).any(|v| coeffs[v * 8 + x] != 0);
961 let dc = i64::from(coeffs[x]) * i64::from(quant[x]);
962 if !nonzero {
963 let value = (dc * i64::from(IDCT_BASIS[0][0]) + 16) >> 5;
964 for y in 0..8 {
965 tmp[y * 8 + x] = value;
966 }
967 continue;
968 }
969 for y in 0..8 {
970 let mut sum = 0i64;
971 for v in 0..8 {
972 let c = i64::from(coeffs[v * 8 + x]) * i64::from(quant[v * 8 + x]);
973 sum += c * i64::from(IDCT_BASIS[v][y]);
974 }
975 tmp[y * 8 + x] = (sum + 16) >> 5;
976 }
977 }
978 for y in 0..8 {
979 for x in 0..8 {
980 let mut sum = 0i64;
981 for u in 0..8 {
982 sum += tmp[y * 8 + u] * i64::from(IDCT_BASIS[u][x]);
983 }
984 let value = ((sum + (1 << 20)) >> 21) + 128;
985 out[y * 8 + x] = value.clamp(0, 255) as u8;
986 }
987 }
988}
989
990/// Inverse-transform every block of a component into a plane of samples.
991fn component_plane(component: &Component, quant: &[u16; 64]) -> Vec<u8> {
992 let width = component.blocks_w * 8;
993 let mut plane = vec![0u8; width * component.blocks_h * 8];
994 let mut block = [0u8; 64];
995 for by in 0..component.blocks_h {
996 for bx in 0..component.blocks_w {
997 let offset = (by * component.blocks_w + bx) * 64;
998 idct_block(&component.coeffs[offset..offset + 64], quant, &mut block);
999 for row in 0..8 {
1000 let dst = (by * 8 + row) * width + bx * 8;
1001 plane[dst..dst + 8].copy_from_slice(&block[row * 8..row * 8 + 8]);
1002 }
1003 }
1004 }
1005 plane
1006}
1007
1008/// BT.601 full-range YCbCr to RGB, in libjpeg's 16-bit fixed point.
1009fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8) -> [u8; 3] {
1010 let y = i32::from(y) << 16;
1011 let cb = i32::from(cb) - 128;
1012 let cr = i32::from(cr) - 128;
1013 let r = y + 91881 * cr;
1014 let g = y - 22554 * cb - 46802 * cr;
1015 let b = y + 116130 * cb;
1016 [
1017 ((r + 32768) >> 16).clamp(0, 255) as u8,
1018 ((g + 32768) >> 16).clamp(0, 255) as u8,
1019 ((b + 32768) >> 16).clamp(0, 255) as u8,
1020 ]
1021}
1022
1023fn reconstruct(
1024 frame: &Frame,
1025 quant: &[[u16; 64]; 4],
1026 adobe: Option<u8>,
1027 limits: Limits,
1028) -> Result<Pixels> {
1029 let (w, h) = (frame.width as usize, frame.height as usize);
1030 let out_per_pixel = if frame.components.len() == 1 { 1 } else { 3 };
1031 limits.check_output(frame.width, frame.height, out_per_pixel)?;
1032 let planes: Vec<Vec<u8>> = frame
1033 .components
1034 .iter()
1035 .map(|c| {
1036 let plane = component_plane(c, &quant[c.quant]);
1037 let pw = c.blocks_w * 8;
1038 let ph = c.blocks_h * 8;
1039 // Full-resolution extent this component covers before upsampling.
1040 let cw = (w * c.h).div_ceil(frame.hmax);
1041 let ch = (h * c.v).div_ceil(frame.vmax);
1042 let mut cropped: Vec<u8> = Vec::with_capacity(cw.min(pw) * ch.min(ph));
1043 for y in 0..ch.min(ph) {
1044 cropped.extend_from_slice(&plane[y * pw..y * pw + cw.min(pw)]);
1045 }
1046 upsample(&cropped, cw.min(pw), ch.min(ph), w, h)
1047 })
1048 .collect();
1049
1050 match frame.components.len() {
1051 1 => Ok(Pixels::L8(planes.into_iter().next().ok_or_else(|| {
1052 Error::corrupt("JPEG: a single-component frame with no plane")
1053 })?)),
1054 3 => {
1055 // Component ids 'R','G','B' (or an Adobe transform of 0) mean the
1056 // samples are already RGB and must not be matrixed again.
1057 let ids: Vec<u8> = frame.components.iter().map(|c| c.id).collect();
1058 let already_rgb = adobe == Some(0) || ids == *b"RGB";
1059 // Every plane is out_w * out_h, so the three zip to the picture with no bounds checks.
1060 let mut out = vec![0u8; w * h * 3];
1061 for (px, ((&a, &b), &c)) in out
1062 .as_chunks_mut::<3>()
1063 .0
1064 .iter_mut()
1065 .zip(planes[0].iter().zip(&planes[1]).zip(&planes[2]))
1066 {
1067 *px = if already_rgb { [a, b, c] } else { ycbcr_to_rgb(a, b, c) };
1068 }
1069 Ok(Pixels::Rgb8(out))
1070 }
1071 n => Err(Error::unsupported(
1072 format!("{n}-component JPEG"),
1073 "no colour interpretation is defined for it",
1074 )),
1075 }
1076}
1077
1078// ---------------------------------------------------------------------------------------------
1079// Video path: Motion JPEG frames straight to planar YUV.
1080// ---------------------------------------------------------------------------------------------
1081
1082const DC_LUM_COUNTS: [u8; 16] = [0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
1083const DC_CHR_COUNTS: [u8; 16] = [0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
1084const AC_LUM_COUNTS: [u8; 16] = [0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
1085const AC_CHR_COUNTS: [u8; 16] = [0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
1086const AC_LUM_VALUES: [u8; 162] = [
1087 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
1088 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
1089 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
1090 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
1091 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
1092 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
1093 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
1094 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
1095 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
1096 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
1097 0xf9, 0xfa,
1098];
1099const AC_CHR_VALUES: [u8; 162] = [
1100 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
1101 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
1102 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
1103 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
1104 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
1105 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
1106 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
1107 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
1108 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
1109 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
1110 0xf9, 0xfa,
1111];
1112
1113/// T.81 Annex K.3 tables as table 0 (luminance) and table 1 (chrominance), which is what an
1114/// AVI1/MJPG packet without a DHT segment relies on.
1115fn install_default_tables(dc: &mut [HuffTable], ac: &mut [HuffTable]) -> Result<()> {
1116 dc[0] = HuffTable::build(&DC_LUM_COUNTS, (0..12).collect())?;
1117 dc[1] = HuffTable::build(&DC_CHR_COUNTS, (0..12).collect())?;
1118 ac[0] = HuffTable::build(&AC_LUM_COUNTS, AC_LUM_VALUES.to_vec())?;
1119 ac[1] = HuffTable::build(&AC_CHR_COUNTS, AC_CHR_VALUES.to_vec())?;
1120 Ok(())
1121}
1122
1123/// Chroma layout of a decoded video frame.
1124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1125pub enum Subsampling {
1126 /// One component.
1127 Gray,
1128 /// Chroma halved both ways.
1129 Yuv420,
1130 /// Chroma halved across.
1131 Yuv422,
1132 /// Chroma at full size.
1133 Yuv444,
1134}
1135
1136/// One 8-bit plane, tightly packed (`stride == width`) and cropped to the picture.
1137#[derive(Debug, Clone, PartialEq, Eq)]
1138pub struct YuvPlane {
1139 /// Samples per row.
1140 pub width: usize,
1141 /// Rows.
1142 pub height: usize,
1143 /// `width * height` samples.
1144 pub data: Vec<u8>,
1145}
1146
1147/// A JPEG decoded to its native planes: no chroma upsampling, no colour conversion.
1148#[derive(Debug, Clone, PartialEq, Eq)]
1149pub struct YuvImage {
1150 /// Luma width.
1151 pub width: u32,
1152 /// Luma height.
1153 pub height: u32,
1154 /// Chroma layout.
1155 pub subsampling: Subsampling,
1156 /// Y (then Cb, Cr unless [`Subsampling::Gray`]).
1157 pub planes: Vec<YuvPlane>,
1158 /// Whether the file was progressive (SOF2).
1159 pub progressive: bool,
1160 /// Offset in the input just past this image's EOI marker (the end of the input when the
1161 /// image has none): where a second field of a two-field packet would start.
1162 pub end: usize,
1163}
1164
1165/// FFmpeg's `simple_idct` constants (cos(i*pi/16) * sqrt(2) * 2^14, rounded).
1166const W1: i64 = 22725;
1167const W2: i64 = 21407;
1168const W3: i64 = 19266;
1169const W4: i64 = 16383;
1170const W5: i64 = 12873;
1171const W6: i64 = 8867;
1172const W7: i64 = 4520;
1173const ROW_SHIFT: u32 = 11;
1174const COL_SHIFT: u32 = 20;
1175
1176/// One row pass of the integer IDCT the JPEG-world decoders (libavcodec's mjpeg, in
1177/// particular) use. Sums are formed in 64 bits and truncated to 32 where C's `int` would wrap.
1178fn simple_idct_row(row: &mut [i16; 8]) {
1179 if row[1..].iter().all(|&c| c == 0) {
1180 let v = ((i32::from(row[0]) << 3) & 0xffff) as u16 as i16;
1181 *row = [v; 8];
1182 return;
1183 }
1184 let r: [i64; 8] = std::array::from_fn(|i| i64::from(row[i]));
1185 let a0 = W4 * r[0] + (1 << (ROW_SHIFT - 1));
1186 let (mut a0, mut a1, mut a2, mut a3) = (a0, a0, a0, a0);
1187 a0 += W2 * r[2];
1188 a1 += W6 * r[2];
1189 a2 -= W6 * r[2];
1190 a3 -= W2 * r[2];
1191 let mut b0 = W1 * r[1] + W3 * r[3];
1192 let mut b1 = W3 * r[1] - W7 * r[3];
1193 let mut b2 = W5 * r[1] - W1 * r[3];
1194 let mut b3 = W7 * r[1] - W5 * r[3];
1195 a0 += W4 * r[4] + W6 * r[6];
1196 a1 += -W4 * r[4] - W2 * r[6];
1197 a2 += -W4 * r[4] + W2 * r[6];
1198 a3 += W4 * r[4] - W6 * r[6];
1199 b0 += W5 * r[5] + W7 * r[7];
1200 b1 += -W1 * r[5] - W5 * r[7];
1201 b2 += W7 * r[5] + W3 * r[7];
1202 b3 += W3 * r[5] - W1 * r[7];
1203 let t = |v: i64| ((v as i32) >> ROW_SHIFT) as i16;
1204 row[0] = t(a0 + b0);
1205 row[7] = t(a0 - b0);
1206 row[1] = t(a1 + b1);
1207 row[6] = t(a1 - b1);
1208 row[2] = t(a2 + b2);
1209 row[5] = t(a2 - b2);
1210 row[3] = t(a3 + b3);
1211 row[4] = t(a3 - b3);
1212}
1213
1214/// One column pass, clamped straight to samples.
1215fn simple_idct_col(block: &[i16; 64], x: usize, out: &mut [u8; 64]) {
1216 let c: [i64; 8] = std::array::from_fn(|i| i64::from(block[i * 8 + x]));
1217 let a0 = W4 * (c[0] + ((1 << (COL_SHIFT - 1)) / W4));
1218 let (mut a0, mut a1, mut a2, mut a3) = (a0, a0, a0, a0);
1219 a0 += W2 * c[2];
1220 a1 += W6 * c[2];
1221 a2 -= W6 * c[2];
1222 a3 -= W2 * c[2];
1223 let mut b0 = W1 * c[1] + W3 * c[3];
1224 let mut b1 = W3 * c[1] - W7 * c[3];
1225 let mut b2 = W5 * c[1] - W1 * c[3];
1226 let mut b3 = W7 * c[1] - W5 * c[3];
1227 a0 += W4 * c[4];
1228 a1 -= W4 * c[4];
1229 a2 -= W4 * c[4];
1230 a3 += W4 * c[4];
1231 b0 += W5 * c[5];
1232 b1 -= W1 * c[5];
1233 b2 += W7 * c[5];
1234 b3 += W3 * c[5];
1235 a0 += W6 * c[6];
1236 a1 -= W2 * c[6];
1237 a2 += W2 * c[6];
1238 a3 -= W6 * c[6];
1239 b0 += W7 * c[7];
1240 b1 -= W5 * c[7];
1241 b2 += W3 * c[7];
1242 b3 -= W1 * c[7];
1243 let q = |v: i64| (((v as i32) >> COL_SHIFT).clamp(0, 255)) as u8;
1244 out[x] = q(a0 + b0);
1245 out[8 + x] = q(a1 + b1);
1246 out[16 + x] = q(a2 + b2);
1247 out[24 + x] = q(a3 + b3);
1248 out[32 + x] = q(a3 - b3);
1249 out[40 + x] = q(a2 - b2);
1250 out[48 + x] = q(a1 - b1);
1251 out[56 + x] = q(a0 - b0);
1252}
1253
1254/// Dequantize and invert one block the way libavcodec's mjpeg decoder does: the level shift
1255/// is 1024 added to the dequantized DC term, products wrap to 16 bits, and the transform is
1256/// `simple_idct`.
1257fn idct_block_video(coeffs: &[i16], quant: &[u16; 64], out: &mut [u8; 64]) {
1258 let mut block = [0i16; 64];
1259 for i in 0..64 {
1260 block[i] = (i32::from(coeffs[i]) * i32::from(quant[i])) as i16;
1261 }
1262 block[0] = (i32::from(coeffs[0]) * i32::from(quant[0]) + 1024) as i16;
1263 for r in 0..8 {
1264 let row: &mut [i16; 8] = (&mut block[r * 8..r * 8 + 8]).try_into().expect("8");
1265 simple_idct_row(row);
1266 }
1267 for x in 0..8 {
1268 simple_idct_col(&block, x, out);
1269 }
1270}
1271
1272fn subsampling_of(frame: &Frame) -> Result<Subsampling> {
1273 match frame.components.len() {
1274 1 => Ok(Subsampling::Gray),
1275 3 => {
1276 let c = &frame.components;
1277 let (y, cb, cr) = (&c[0], &c[1], &c[2]);
1278 if (cb.h, cb.v) != (cr.h, cr.v) || (y.h, y.v) != (frame.hmax, frame.vmax) {
1279 return Err(Error::unsupported(
1280 format!(
1281 "JPEG sampling {}x{} {}x{} {}x{}",
1282 y.h, y.v, cb.h, cb.v, cr.h, cr.v
1283 ),
1284 "only gray, 4:2:0, 4:2:2 and 4:4:4 map to a pixel format",
1285 ));
1286 }
1287 match (y.h / cb.h.max(1), y.v / cb.v.max(1), y.h % cb.h, y.v % cb.v) {
1288 (1, 1, 0, 0) => Ok(Subsampling::Yuv444),
1289 (2, 1, 0, 0) => Ok(Subsampling::Yuv422),
1290 (2, 2, 0, 0) => Ok(Subsampling::Yuv420),
1291 _ => Err(Error::unsupported(
1292 format!(
1293 "JPEG sampling {}x{} {}x{} {}x{}",
1294 y.h, y.v, cb.h, cb.v, cr.h, cr.v
1295 ),
1296 "only gray, 4:2:0, 4:2:2 and 4:4:4 map to a pixel format",
1297 )),
1298 }
1299 }
1300 n => Err(Error::unsupported(
1301 format!("{n}-component JPEG"),
1302 "no colour interpretation is defined for it",
1303 )),
1304 }
1305}
1306
1307/// Decode a Motion JPEG frame to its native planes.
1308///
1309/// Chroma stays at the file's own subsampling and is not converted: the planes are what
1310/// libavcodec's `mjpeg` decoder returns (`yuvj420p`, `yuvj422p`, `yuvj444p`, `gray`),
1311/// sample for sample. The default Huffman tables (T.81 Annex K) stand in for a missing DHT,
1312/// as AVI1/MJPG packets need. Progressive (SOF2) frames decode; 12-bit precision, arithmetic
1313/// coding, CMYK, RGB-coded and non-4:2:0/4:2:2/4:4:4 layouts are refused by name.
1314pub fn decode_yuv(data: &[u8], limits: Limits) -> Result<YuvImage> {
1315 if data.len() < 4 || data[0] != 0xff || data[1] != 0xd8 {
1316 return Err(Error::corrupt("JPEG: no SOI marker"));
1317 }
1318 let parsed = parse(data, limits, true)?;
1319 let frame = &parsed.frame;
1320 let subsampling = subsampling_of(frame)?;
1321 if subsampling != Subsampling::Gray {
1322 let ids: Vec<u8> = frame.components.iter().map(|c| c.id).collect();
1323 if parsed.adobe == Some(0) || ids == *b"RGB" {
1324 return Err(Error::unsupported(
1325 "RGB-coded Motion JPEG",
1326 "the samples are not YCbCr and no planar RGB format is wired",
1327 ));
1328 }
1329 }
1330 let (w, h) = (frame.width as usize, frame.height as usize);
1331 let mut planes = Vec::with_capacity(frame.components.len());
1332 for c in &frame.components {
1333 let q = &parsed.quant[c.quant];
1334 let pw = c.blocks_w * 8;
1335 let cw = (w * c.h).div_ceil(frame.hmax);
1336 let ch = (h * c.v).div_ceil(frame.vmax);
1337 let mut data = vec![0u8; cw * ch];
1338 let mut block = [0u8; 64];
1339 for by in 0..c.blocks_h {
1340 if by * 8 >= ch {
1341 break;
1342 }
1343 for bx in 0..c.blocks_w {
1344 if bx * 8 >= cw {
1345 break;
1346 }
1347 let off = (by * c.blocks_w + bx) * 64;
1348 idct_block_video(&c.coeffs[off..off + 64], q, &mut block);
1349 let n = (cw - bx * 8).min(8);
1350 for row in 0..8.min(ch - by * 8) {
1351 let dst = (by * 8 + row) * cw + bx * 8;
1352 data[dst..dst + n].copy_from_slice(&block[row * 8..row * 8 + n]);
1353 }
1354 }
1355 }
1356 let _ = pw;
1357 planes.push(YuvPlane {
1358 width: cw,
1359 height: ch,
1360 data,
1361 });
1362 }
1363 Ok(YuvImage {
1364 width: frame.width,
1365 height: frame.height,
1366 subsampling,
1367 planes,
1368 progressive: frame.progressive,
1369 end: parsed.end,
1370 })
1371}
1372
1373/// EXIF orientation out of an APP1 segment (the `Exif\0\0` header, then TIFF).
1374fn exif_orientation(seg: &[u8]) -> Option<u8> {
1375 crate::exif::tiff_orientation(seg.strip_prefix(b"Exif\0\0")?)
1376}
1377
1378#[cfg(test)]
1379mod tests {
1380 use super::*;
1381
1382 #[test]
1383 fn the_idct_basis_matches_the_cosine_it_stands_for() {
1384 for v in 0..8usize {
1385 for x in 0..8usize {
1386 let c = if v == 0 {
1387 1.0 / std::f64::consts::SQRT_2
1388 } else {
1389 1.0
1390 };
1391 let want = 0.5
1392 * c
1393 * ((2 * x + 1) as f64 * v as f64 * std::f64::consts::PI / 16.0).cos()
1394 * 8192.0;
1395 let got = f64::from(IDCT_BASIS[v][x]);
1396 assert!((want - got).abs() <= 0.5, "v{v} x{x}: {want} vs {got}");
1397 }
1398 }
1399 }
1400
1401 #[test]
1402 fn the_dc_only_shortcut_matches_the_full_transform() {
1403 // The full transform, as idct_block computes it with no shortcut.
1404 fn full(coeffs: &[i16], quant: &[u16; 64]) -> [u8; 64] {
1405 let mut tmp = [0i64; 64];
1406 for x in 0..8 {
1407 for y in 0..8 {
1408 let mut sum = 0i64;
1409 for v in 0..8 {
1410 let c = i64::from(coeffs[v * 8 + x]) * i64::from(quant[v * 8 + x]);
1411 sum += c * i64::from(IDCT_BASIS[v][y]);
1412 }
1413 tmp[y * 8 + x] = (sum + 16) >> 5;
1414 }
1415 }
1416 let mut out = [0u8; 64];
1417 for y in 0..8 {
1418 for x in 0..8 {
1419 let mut sum = 0i64;
1420 for u in 0..8 {
1421 sum += tmp[y * 8 + u] * i64::from(IDCT_BASIS[u][x]);
1422 }
1423 let value = ((sum + (1 << 20)) >> 21) + 128;
1424 out[y * 8 + x] = value.clamp(0, 255) as u8;
1425 }
1426 }
1427 out
1428 }
1429 let quant = [3u16; 64];
1430 for dc in [-32768i32, -2048, -7, -1, 0, 1, 5, 64, 1000, 32767] {
1431 let mut coeffs = [0i16; 64];
1432 coeffs[0] = dc as i16;
1433 let mut fast = [0u8; 64];
1434 idct_block(&coeffs, &quant, &mut fast);
1435 assert_eq!(fast, full(&coeffs, &quant), "DC {dc}");
1436 }
1437 }
1438
1439 #[test]
1440 fn a_flat_block_inverts_to_its_dc_level() {
1441 let mut coeffs = [0i16; 64];
1442 coeffs[0] = 8; // DC of 8 * quant 16 = 128 -> mid grey plus level shift
1443 let quant = [16u16; 64];
1444 let mut out = [0u8; 64];
1445 idct_block(&coeffs, &quant, &mut out);
1446 for &s in &out {
1447 assert_eq!(s, 144, "flat block should be one level everywhere");
1448 }
1449 }
1450
1451 #[test]
1452 fn ycbcr_neutral_chroma_is_grey() {
1453 for y in [0u8, 17, 128, 255] {
1454 assert_eq!(ycbcr_to_rgb(y, 128, 128), [y, y, y]);
1455 }
1456 // Full-range BT.601 red is Y=76 Cb=84 Cr=255 (JFIF has no head/foot
1457 // room), which must come back as saturated red and nothing else.
1458 let rgb = ycbcr_to_rgb(76, 84, 255);
1459 assert!(rgb[0] > 250 && rgb[1] < 6 && rgb[2] < 6, "{rgb:?}");
1460 }
1461
1462 #[test]
1463 fn exif_orientation_is_read_from_either_byte_order() {
1464 // Little-endian TIFF, one IFD entry: tag 0x0112, SHORT, count 1, value 6.
1465 let mut seg = b"Exif\0\0II".to_vec();
1466 seg.extend_from_slice(&42u16.to_le_bytes());
1467 seg.extend_from_slice(&8u32.to_le_bytes());
1468 seg.extend_from_slice(&1u16.to_le_bytes());
1469 seg.extend_from_slice(&0x0112u16.to_le_bytes());
1470 seg.extend_from_slice(&3u16.to_le_bytes());
1471 seg.extend_from_slice(&1u32.to_le_bytes());
1472 seg.extend_from_slice(&6u16.to_le_bytes());
1473 seg.extend_from_slice(&0u16.to_le_bytes());
1474 assert_eq!(exif_orientation(&seg), Some(6));
1475 assert_eq!(exif_orientation(b"Exif\0\0XX"), None);
1476 }
1477}